All user data for FoundryVTT. Includes worlds, systems, modules, and any asset in the "foundryuserdata" directory. Does NOT include the FoundryVTT installation itself.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

54 lines
907 KiB

var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __defProp2=Object.defineProperty,__name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:!0}),"__name"),_a,_b,_c,__spreadArray$1=globalThis&&globalThis.__spreadArray||function(to,from,pack){if(pack||arguments.length===2)for(var i=0,l2=from.length,ar;i<l2;i++)(ar||!(i in from))&&(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))};function purry(fn,args,lazy){var diff2=fn.length-args.length,arrayArgs=Array.from(args);if(diff2===0)return fn.apply(void 0,arrayArgs);if(diff2===1){var ret=__name2(function(data){return fn.apply(void 0,__spreadArray$1([data],arrayArgs,!1))},"ret");return(lazy||fn.lazy)&&(ret.lazy=lazy||fn.lazy,ret.lazyArgs=args),ret}throw new Error("Wrong number of arguments")}__name(purry,"purry"),__name2(purry,"purry");function isTruthy(data){return!!data}__name(isTruthy,"isTruthy"),__name2(isTruthy,"isTruthy");function compact(items){return items.filter(isTruthy)}__name(compact,"compact"),__name2(compact,"compact");function pipe(value){for(var operations=[],_i=1;_i<arguments.length;_i++)operations[_i-1]=arguments[_i];for(var ret=value,lazyOps=operations.map(function(op2){var _a4=op2,lazy=_a4.lazy,lazyArgs=_a4.lazyArgs;if(lazy){var fn=lazy.apply(void 0,lazyArgs||[]);return fn.indexed=lazy.indexed,fn.single=lazy.single,fn.index=0,fn.items=[],fn}return null}),opIdx=0;opIdx<operations.length;){var op=operations[opIdx],lazyOp=lazyOps[opIdx];if(!lazyOp){ret=op(ret),opIdx++;continue}for(var lazySeq=[],j=opIdx;j<operations.length&&lazyOps[j];j++)if(lazySeq.push(lazyOps[j]),lazyOps[j].single)break;for(var acc=[],_a3=0,ret_1=ret;_a3<ret_1.length;_a3++){var item=ret_1[_a3];if(_processItem({item,acc,lazySeq}))break}var lastLazySeq=lazySeq[lazySeq.length-1];lastLazySeq.single?ret=acc[0]:ret=acc,opIdx+=lazySeq.length}return ret}__name(pipe,"pipe"),__name2(pipe,"pipe");function _processItem(_a3){var item=_a3.item,lazySeq=_a3.lazySeq,acc=_a3.acc;if(lazySeq.length===0)return acc.push(item),!1;for(var lazyResult={done:!1,hasNext:!1},isDone=!1,i=0;i<lazySeq.length;i++){var lazyFn=lazySeq[i],indexed=lazyFn.indexed,index2=lazyFn.index,items=lazyFn.items;if(items.push(item),lazyResult=indexed?lazyFn(item,index2,items):lazyFn(item),lazyFn.index++,lazyResult.hasNext)if(lazyResult.hasMany){for(var nextValues=lazyResult.next,_i=0,nextValues_1=nextValues;_i<nextValues_1.length;_i++){var subItem=nextValues_1[_i],subResult=_processItem({item:subItem,acc,lazySeq:lazySeq.slice(i+1)});if(subResult)return!0}return!1}else item=lazyResult.next;if(!lazyResult.hasNext)break;lazyResult.done&&(isDone=!0)}return lazyResult.hasNext&&acc.push(item),!!isDone}__name(_processItem,"_processItem"),__name2(_processItem,"_processItem");function _reduceLazy(array,lazy,indexed){for(var newArray=[],index2=0;index2<array.length;index2++){var item=array[index2],result=indexed?lazy(item,index2,array):lazy(item);result.hasMany===!0?newArray.push.apply(newArray,result.next):result.hasNext&&newArray.push(result.next)}return newArray}__name(_reduceLazy,"_reduceLazy"),__name2(_reduceLazy,"_reduceLazy");function difference(){return purry(_difference,arguments,difference.lazy)}__name(difference,"difference"),__name2(difference,"difference");function _difference(array,other){var lazy=difference.lazy(other);return _reduceLazy(array,lazy)}__name(_difference,"_difference"),__name2(_difference,"_difference"),function(difference2){function lazy(other){var set=new Set(other);return function(value){return set.has(value)?{done:!1,hasNext:!1}:{done:!1,hasNext:!0,next:value}}}__name(lazy,"lazy"),__name2(lazy,"lazy"),difference2.lazy=lazy}(difference||(difference={}));var isArray$1=Array.isArray,keyList=Object.keys;function equals(){return purry(_equals,arguments)}__name(equals,"equals"),__name2(equals,"equals");function _equals(a,b){if(a===b)return!0;if(a&&b&&typeof a=="object"&&typeof b=="object"){var arrA=isArray$1(a),arrB=isArray$1(b),i=void 0,length=void 0,key=void 0;if(arrA&&arrB){if(length=a.length,length!==b.length)return!1;for(i=length;i--!==0;)if(!equals(a[i],b[i]))return!1;return!0}if(arrA!==arrB)return!1;var dateA=a instanceof Date,dateB=b instanceof Date;if(dateA!==dateB)return!1;if(dateA&&dateB)return a.getTime()===b.getTime();var regexpA=a instanceof RegExp,regexpB=b instanceof RegExp;if(regexpA!==regexpB)return!1;if(regexpA&&regexpB)return a.toString()===b.toString();var keys2=keyList(a);if(length=keys2.length,length!==keyList(b).length)return!1;for(i=length;i--!==0;)if(!Object.prototype.hasOwnProperty.call(b,keys2[i]))return!1;for(i=length;i--!==0;)if(key=keys2[i],!equals(a[key],b[key]))return!1;return!0}return a!==a&&b!==b}__name(_equals,"_equals"),__name2(_equals,"_equals");var _toLazyIndexed=__name2(function(fn){return fn.indexed=!0,fn},"_toLazyIndexed");function filter(){return purry(_filter(!1),arguments,filter.lazy)}__name(filter,"filter"),__name2(filter,"filter");var _filter=__name2(function(indexed){return function(array,fn){return _reduceLazy(array,indexed?filter.lazyIndexed(fn):filter.lazy(fn),indexed)}},"_filter"),_lazy$1=__name2(function(indexed){return function(fn){return function(value,index2,array){var valid=indexed?fn(value,index2,array):fn(value);return valid?{done:!1,hasNext:!0,next:value}:{done:!1,hasNext:!1}}}},"_lazy$1");(function(filter2){function indexed(){return purry(_filter(!0),arguments,filter2.lazyIndexed)}__name(indexed,"indexed"),__name2(indexed,"indexed"),filter2.indexed=indexed,filter2.lazy=_lazy$1(!1),filter2.lazyIndexed=_toLazyIndexed(_lazy$1(!0))})(filter||(filter={}));function findLast(){return purry(_findLast(!1),arguments)}__name(findLast,"findLast"),__name2(findLast,"findLast");var _findLast=__name2(function(indexed){return function(array,fn){for(var i=array.length-1;i>=0;i--)if(indexed?fn(array[i],i,array):fn(array[i]))return array[i]}},"_findLast");(function(findLast2){function indexed(){return purry(_findLast(!0),arguments)}__name(indexed,"indexed"),__name2(indexed,"indexed"),findLast2.indexed=indexed})(findLast||(findLast={}));function fromPairs(entries){for(var out={},_i=0,entries_1=entries;_i<entries_1.length;_i++){var _a3=entries_1[_i],key=_a3[0],value=_a3[1];out[key]=value}return out}__name(fromPairs,"fromPairs"),__name2(fromPairs,"fromPairs"),function(fromPairs2){fromPairs2.strict=fromPairs2}(fromPairs||(fromPairs={}));function groupBy(){return purry(_groupBy(!1),arguments)}__name(groupBy,"groupBy"),__name2(groupBy,"groupBy");var _groupBy=__name2(function(indexed){return function(array,fn){var ret={};return array.forEach(function(item,index2){var key=indexed?fn(item,index2,array):fn(item);if(key!==void 0){var actualKey=String(key);ret[actualKey]||(ret[actualKey]=[]),ret[actualKey].push(item)}}),ret}},"_groupBy");(function(groupBy2){function indexed(){return purry(_groupBy(!0),arguments)}__name(indexed,"indexed"),__name2(indexed,"indexed"),groupBy2.indexed=indexed,groupBy2.strict=groupBy2})(groupBy||(groupBy={}));function isArray(data){return Array.isArray(data)}__name(isArray,"isArray"),__name2(isArray,"isArray");function isObject(data){return!!data&&!Array.isArray(data)&&typeof data=="object"}__name(isObject,"isObject"),__name2(isObject,"isObject");function isString$1(data){return typeof data=="string"}__name(isString$1,"isString$1"),__name2(isString$1,"isString$1");function isEmpty(data){return data===void 0?!0:isArray(data)||isString$1(data)?data.length===0:isObject(data)?Object.keys(data).length===0:!1}__name(isEmpty,"isEmpty"),__name2(isEmpty,"isEmpty");function isNil(data){return data==null}__name(isNil,"isNil"),__name2(isNil,"isNil");function keys$1(source){return Object.keys(source)}__name(keys$1,"keys$1"),__name2(keys$1,"keys$1"),function(keys2){keys2.strict=keys2}(keys$1||(keys$1={}));function map(){return purry(_map(!1),arguments,map.lazy)}__name(map,"map"),__name2(map,"map");var _map=__name2(function(indexed){return function(array,fn){return _reduceLazy(array,indexed?map.lazyIndexed(fn):map.lazy(fn),indexed)}},"_map"),_lazy=__name2(function(indexed){return function(fn){return function(value,index2,array){return{done:!1,hasNext:!0,next:indexed?fn(value,index2,array):fn(value)}}}},"_lazy");(function(map2){function indexed(){return purry(_map(!0),arguments,map2.lazyIndexed)}__name(indexed,"indexed"),__name2(indexed,"indexed"),map2.indexed=indexed,map2.lazy=_lazy(!1),map2.lazyIndexed=_toLazyIndexed(_lazy(!0)),map2.strict=map2})(map||(map={}));function mapToObj(){return purry(_mapToObj(!1),arguments)}__name(mapToObj,"mapToObj"),__name2(mapToObj,"mapToObj");var _mapToObj=__name2(function(indexed){return function(array,fn){return array.reduce(function(result,element,index2){var _a3=indexed?fn(element,index2,array):fn(element),key=_a3[0],value=_a3[1];return result[key]=value,result},{})}},"_mapToObj");(function(mapToObj2){function indexed(){return purry(_mapToObj(!0),arguments)}__name(indexed,"indexed"),__name2(indexed,"indexed"),mapToObj2.indexed=indexed})(mapToObj||(mapToObj={}));function mapValues(arg1,arg2){return arguments.length===1?function(data){return _mapValues(data,arg1)}:_mapValues(arg1,arg2)}__name(mapValues,"mapValues"),__name2(mapValues,"mapValues");function _mapValues(obj,fn){return Object.keys(obj).reduce(function(acc,key){return acc[key]=fn(obj[key],key),acc},{})}__name(_mapValues,"_mapValues"),__name2(_mapValues,"_mapValues");var _maxBy=__name2(function(indexed){return function(array,fn){var ret=void 0,retMax=void 0;return array.forEach(function(item,i){var max=indexed?fn(item,i,array):fn(item);(retMax===void 0||max>retMax)&&(ret=item,retMax=max)}),ret}},"_maxBy");function maxBy(){return purry(_maxBy(!1),arguments)}__name(maxBy,"maxBy"),__name2(maxBy,"maxBy"),function(maxBy2){function indexed(){return purry(_maxBy(!0),arguments)}__name(indexed,"indexed"),__name2(indexed,"indexed"),maxBy2.indexed=indexed}(maxBy||(maxBy={}));var _meanBy=__name2(function(indexed){return function(array,fn){if(array.length===0)return NaN;var sum=0;return array.forEach(function(item,i){sum+=indexed?fn(item,i,array):fn(item)}),sum/array.length}},"_meanBy");function meanBy(){return purry(_meanBy(!1),arguments)}__name(meanBy,"meanBy"),__name2(meanBy,"meanBy"),function(meanBy2){function indexed(){return purry(_meanBy(!0),arguments)}__name(indexed,"indexed"),__name2(indexed,"indexed"),meanBy2.indexed=indexed}(meanBy||(meanBy={}));var __assign$1=globalThis&&globalThis.__assign||function(){return __assign$1=Object.assign||function(t2){for(var s2,i=1,n2=arguments.length;i<n2;i++){s2=arguments[i];for(var p in s2)Object.prototype.hasOwnProperty.call(s2,p)&&(t2[p]=s2[p])}return t2},__assign$1.apply(this,arguments)},__rest=globalThis&&globalThis.__rest||function(s2,e){var t2={};for(var p in s2)Object.prototype.hasOwnProperty.call(s2,p)&&e.indexOf(p)<0&&(t2[p]=s2[p]);if(s2!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,p=Object.getOwnPropertySymbols(s2);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s2,p[i])&&(t2[p[i]]=s2[p[i]]);return t2};function omit(){return purry(_omit,arguments)}__name(omit,"omit"),__name2(omit,"omit");function _omit(data,propNames){if(propNames.length===0)return __assign$1({},data);if(propNames.length===1){var propName=propNames[0],_a3=data,_b2=propName;_a3[_b2];var remaining=__rest(_a3,[typeof _b2=="symbol"?_b2:_b2+""]);return remaining}if(!propNames.some(function(propName2){return propName2 in data}))return __assign$1({},data);var asSet=new Set(propNames);return fromPairs(Object.entries(data).filter(function(_a4){var key=_a4[0];return!asSet.has(key)}))}__name(_omit,"_omit"),__name2(_omit,"_omit");function omitBy(){return purry(_omitBy,arguments)}__name(omitBy,"omitBy"),__name2(omitBy,"omitBy");function _omitBy(object,fn){return Object.keys(object).reduce(function(acc,key){return fn(object[key],key)||(acc[key]=object[key]),acc},{})}__name(_omitBy,"_omitBy"),__name2(_omitBy,"_omitBy");function pick$1(){return purry(_pick,arguments)}__name(pick$1,"pick$1"),__name2(pick$1,"pick$1");function _pick(object,names){return object==null?{}:names.reduce(function(acc,name2){return name2 in object&&(acc[name2]=object[name2]),acc},{})}__name(_pick,"_pick"),__name2(_pick,"_pick");var __spreadArray=globalThis&&globalThis.__spreadArray||function(to,from,pack){if(pack||arguments.length===2)for(var i=0,l2=from.length,ar;i<l2;i++)(ar||!(i in from))&&(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))},ALL_DIRECTIONS=["asc","desc"],COMPARATOR={asc:function(x,y){return x>y},desc:function(x,y){return x<y}};function sortBy(arrayOrSortRule){for(var sortRules=[],_i=1;_i<arguments.length;_i++)sortRules[_i-1]=arguments[_i];var args=isSortRule(arrayOrSortRule)?[__spreadArray([arrayOrSortRule],sortRules,!0)]:[arrayOrSortRule,sortRules];return purry(_sortBy,args)}__name(sortBy,"sortBy"),__name2(sortBy,"sortBy");function isSortRule(x){if(typeof x=="function")return!0;var maybeProjection=x[0],maybeDirection=x[1],rest=x.slice(2);return rest.length>0?!1:typeof maybeProjection=="function"&&ALL_DIRECTIONS.indexOf(maybeDirection)!==-1}__name(isSortRule,"isSortRule"),__name2(isSortRule,"isSortRule");var _sortBy=__name2(function(array,sorts){return __spreadArray([],array,!0).sort(comparer.apply(void 0,sorts))},"_sortBy");function comparer(primaryRule,secondaryRule){for(var otherRules=[],_i=2;_i<arguments.length;_i++)otherRules[_i-2]=arguments[_i];var projector=typeof primaryRule=="function"?primaryRule:primaryRule[0],direction=typeof primaryRule=="function"?"asc":primaryRule[1],comparator=COMPARATOR[direction],nextComparer=secondaryRule===void 0?void 0:comparer.apply(void 0,__spreadArray([secondaryRule],otherRules,!1));return function(a,b){var _a3,projectedA=projector(a),projectedB=projector(b);return comparator(projectedA,projectedB)?1:comparator(projectedB,projectedA)?-1:(_a3=nextComparer?.(a,b))!==null&&_a3!==void 0?_a3:0}}__name(comparer,"comparer"),__name2(comparer,"comparer"),function(sortBy2){sortBy2.strict=sortBy2}(sortBy||(sortBy={}));var _sumBy=__name2(function(indexed){return function(array,fn){var sum=0;return array.forEach(function(item,i){var summand=indexed?fn(item,i,array):fn(item);sum+=summand}),sum}},"_sumBy");function sumBy(){return purry(_sumBy(!1),arguments)}__name(sumBy,"sumBy"),__name2(sumBy,"sumBy"),function(sumBy2){function indexed(){return purry(_sumBy(!0),arguments)}__name(indexed,"indexed"),__name2(indexed,"indexed"),sumBy2.indexed=indexed}(sumBy||(sumBy={}));function uniq(){return purry(_uniq,arguments,uniq.lazy)}__name(uniq,"uniq"),__name2(uniq,"uniq");function _uniq(array){return _reduceLazy(array,uniq.lazy())}__name(_uniq,"_uniq"),__name2(_uniq,"_uniq"),function(uniq2){function lazy(){var set=new Set;return function(value){return set.has(value)?{done:!1,hasNext:!1}:(set.add(value),{done:!1,hasNext:!0,next:value})}}__name(lazy,"lazy"),__name2(lazy,"lazy"),uniq2.lazy=lazy}(uniq||(uniq={}));function uniqBy(){return purry(_uniqBy,arguments,lazyUniqBy)}__name(uniqBy,"uniqBy"),__name2(uniqBy,"uniqBy");function _uniqBy(array,transformer){return _reduceLazy(array,lazyUniqBy(transformer))}__name(_uniqBy,"_uniqBy"),__name2(_uniqBy,"_uniqBy");function lazyUniqBy(transformer){var set=new Set;return function(value){var appliedItem=transformer(value);return set.has(appliedItem)?{done:!1,hasNext:!1}:(set.add(appliedItem),{done:!1,hasNext:!0,next:value})}}__name(lazyUniqBy,"lazyUniqBy"),__name2(lazyUniqBy,"lazyUniqBy");var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}__name(getDefaultExportFromCjs,"getDefaultExportFromCjs"),__name2(getDefaultExportFromCjs,"getDefaultExportFromCjs");var tagify_min={exports:{}};(function(module,exports){(function(t2,e){module.exports=e()})(commonjsGlobal,function(){function t2(t3,e2){var i2=Object.keys(t3);if(Object.getOwnPropertySymbols){var s3=Object.getOwnPropertySymbols(t3);e2&&(s3=s3.filter(function(e3){return Object.getOwnPropertyDescriptor(t3,e3).enumerable})),i2.push.apply(i2,s3)}return i2}__name(t2,"t2"),__name2(t2,"t");function e(e2){for(var s3=1;s3<arguments.length;s3++){var a2=arguments[s3]!=null?arguments[s3]:{};s3%2?t2(Object(a2),!0).forEach(function(t3){i(e2,t3,a2[t3])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e2,Object.getOwnPropertyDescriptors(a2)):t2(Object(a2)).forEach(function(t3){Object.defineProperty(e2,t3,Object.getOwnPropertyDescriptor(a2,t3))})}return e2}__name(e,"e"),__name2(e,"e");function i(t3,e2,i2){return e2 in t3?Object.defineProperty(t3,e2,{value:i2,enumerable:!0,configurable:!0,writable:!0}):t3[e2]=i2,t3}__name(i,"i"),__name2(i,"i");const s2=__name2((t3,e2,i2,s3)=>(t3=""+t3,e2=""+e2,s3&&(t3=t3.trim(),e2=e2.trim()),i2?t3==e2:t3.toLowerCase()==e2.toLowerCase()),"s"),a=__name2((t3,e2)=>t3&&Array.isArray(t3)&&t3.map(t4=>n2(t4,e2)),"a");function n2(t3,e2){var i2,s3={};for(i2 in t3)e2.indexOf(i2)<0&&(s3[i2]=t3[i2]);return s3}__name(n2,"n2"),__name2(n2,"n");function o(t3){var e2=document.createElement("div");return t3.replace(/\&#?[0-9a-z]+;/gi,function(t4){return e2.innerHTML=t4,e2.innerText})}__name(o,"o"),__name2(o,"o");function r(t3){return new DOMParser().parseFromString(t3.trim(),"text/html").body.firstElementChild}__name(r,"r"),__name2(r,"r");function l2(t3,e2){for(e2=e2||"previous";t3=t3[e2+"Sibling"];)if(t3.nodeType==3)return t3}__name(l2,"l2"),__name2(l2,"l");function d(t3){return typeof t3=="string"?t3.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/`|'/g,"&#039;"):t3}__name(d,"d"),__name2(d,"d");function h(t3){var e2=Object.prototype.toString.call(t3).split(" ")[1].slice(0,-1);return t3===Object(t3)&&e2!="Array"&&e2!="Function"&&e2!="RegExp"&&e2!="HTMLUnknownElement"}__name(h,"h"),__name2(h,"h");function g(t3,e2,i2){function s3(t4,e3){for(var i3 in e3)if(e3.hasOwnProperty(i3)){if(h(e3[i3])){h(t4[i3])?s3(t4[i3],e3[i3]):t4[i3]=Object.assign({},e3[i3]);continue}if(Array.isArray(e3[i3])){t4[i3]=Object.assign([],e3[i3]);continue}t4[i3]=e3[i3]}}return __name(s3,"s3"),__name2(s3,"s"),t3 instanceof Object||(t3={}),s3(t3,e2),i2&&s3(t3,i2),t3}__name(g,"g"),__name2(g,"g");function p(){const t3=[],e2={};for(let i2 of arguments)for(let s3 of i2)h(s3)?e2[s3.value]||(t3.push(s3),e2[s3.value]=1):t3.includes(s3)||t3.push(s3);return t3}__name(p,"p"),__name2(p,"p");function c(t3){return String.prototype.normalize?typeof t3=="string"?t3.normalize("NFD").replace(/[\u0300-\u036f]/g,""):void 0:t3}__name(c,"c"),__name2(c,"c");var u=__name2(()=>/(?=.*chrome)(?=.*android)/i.test(navigator.userAgent),"u");function m(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,t3=>(t3^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t3/4).toString(16))}__name(m,"m"),__name2(m,"m");function v(t3){return t3&&t3.classList&&t3.classList.contains(this.settings.classNames.tag)}__name(v,"v"),__name2(v,"v");var f2={delimiters:",",pattern:null,tagTextProp:"value",maxTags:1/0,callbacks:{},addTagOnBlur:!0,onChangeAfterBlur:!0,duplicates:!1,whitelist:[],blacklist:[],enforceWhitelist:!1,userInput:!0,keepInvalidTags:!1,createInvalidTags:!0,mixTagsAllowedAfter:/,|\.|\:|\s/,mixTagsInterpolator:["[[","]]"],backspace:!0,skipInvalid:!1,pasteAsTags:!0,editTags:{clicks:2,keepInvalid:!0},transformTag:()=>{},trim:!0,a11y:{focusableTags:!1},mixMode:{insertAfterTag:"\xA0"},autoComplete:{enabled:!0,rightKey:!1},classNames:{namespace:"tagify",mixMode:"tagify--mix",selectMode:"tagify--select",input:"tagify__input",focus:"tagify--focus",tagNoAnimation:"tagify--noAnim",tagInvalid:"tagify--invalid",tagNotAllowed:"tagify--notAllowed",scopeLoading:"tagify--loading",hasMaxTags:"tagify--hasMaxTags",hasNoTags:"tagify--noTags",empty:"tagify--empty",inputInvalid:"tagify__input--invalid",dropdown:"tagify__dropdown",dropdownWrapper:"tagify__dropdown__wrapper",dropdownHeader:"tagify__dropdown__header",dropdownFooter:"tagify__dropdown__footer",dropdownItem:"tagify__dropdown__item",dropdownItemActive:"tagify__dropdown__item--active",dropdownItemHidden:"tagify__dropdown__item--hidden",dropdownInital:"tagify__dropdown--initial",tag:"tagify__tag",tagText:"tagify__tag-text",tagX:"tagify__tag__removeBtn",tagLoading:"tagify__tag--loading",tagEditing:"tagify__tag--editable",tagFlash:"tagify__tag--flash",tagHide:"tagify__tag--hide"},dropdown:{classname:"",enabled:2,maxItems:10,searchKeys:["value","searchBy"],fuzzySearch:!0,caseSensitive:!1,accentedSearch:!0,includeSelectedTags:!1,highlightFirst:!1,closeOnSelect:!0,clearOnSelect:!0,position:"all",appendTarget:null},hooks:{beforeRemoveTag:()=>Promise.resolve(),beforePaste:()=>Promise.resolve(),suggestionClick:()=>Promise.resolve()}};function T(){this.dropdown={};for(let t3 in this._dropdown)this.dropdown[t3]=typeof this._dropdown[t3]=="function"?this._dropdown[t3].bind(this):this._dropdown[t3];this.dropdown.refs()}__name(T,"T"),__name2(T,"T");var w={refs(){this.DOM.dropdown=this.parseTemplate("dropdown",[this.settings]),this.DOM.dropdown.content=this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-wrapper']")},getHeaderRef(){return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-header']")},getFooterRef(){return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-footer']")},getAllSuggestionsRefs(){return[...this.DOM.dropdown.content.querySelectorAll(this.settings.classNames.dropdownItemSelector)]},show(t3){var e2,i2,a2,n3=this.settings,o2=n3.mode=="mix"&&!n3.enforceWhitelist,r2=!n3.whitelist||!n3.whitelist.length,l3=n3.dropdown.position=="manual";if(t3=t3===void 0?this.state.inputText:t3,!(r2&&!o2&&!n3.templates.dropdownItemNoMatch||n3.dropdown.enable===!1||this.state.isLoading||this.settings.readonly)){if(clearTimeout(this.dropdownHide__bindEventsTimeout),this.suggestedListItems=this.dropdown.filterListItems(t3),t3&&!this.suggestedListItems.length&&(this.trigger("dropdown:noMatch",t3),n3.templates.dropdownItemNoMatch&&(a2=n3.templates.dropdownItemNoMatch.call(this,{value:t3}))),!a2){if(this.suggestedListItems.length)t3&&o2&&!this.state.editing.scope&&!s2(this.suggestedListItems[0].value,t3)&&this.suggestedListItems.unshift({value:t3});else{if(!t3||!o2||this.state.editing.scope)return this.input.autocomplete.suggest.call(this),void this.dropdown.hide();this.suggestedListItems=[{value:t3}]}i2=""+(h(e2=this.suggestedListItems[0])?e2.value:e2),n3.autoComplete&&i2&&i2.indexOf(t3)==0&&this.input.autocomplete.suggest.call(this,e2)}this.dropdown.fill(a2),n3.dropdown.highlightFirst&&this.dropdown.highlightOption(this.DOM.dropdown.content.querySelector(n3.classNames.dropdownItemSelector)),this.state.dropdown.visible||setTimeout(this.dropdown.events.binding.bind(this)),this.state.dropdown.visible=t3||!0,this.state.dropdown.query=t3,this.setStateSelection(),l3||setTimeout(()=>{this.dropdown.position(),this.dropdown.render()}),setTimeout(()=>{this.trigger("dropdown:show",this.DOM.dropdown)})}},hide(t3){var e2=this.DOM,i2=e2.scope,s3=e2.dropdown,a2=this.settings.dropdown.position=="manual"&&!t3;if(s3&&document.body.contains(s3)&&!a2)return window.removeEventListener("resize",this.dropdown.position),this.dropdown.events.binding.call(this,!1),i2.setAttribute("aria-expanded",!1),s3.parentNode.removeChild(s3),setTimeout(()=>{this.state.dropdown.visible=!1},100),this.state.dropdown.query=this.state.ddItemData=this.state.ddItemElm=this.state.selection=null,this.state.tag&&this.state.tag.value.length&&(this.state.flaggedTags[this.state.tag.baseOffset]=this.state.tag),this.trigger("dropdown:hide",s3),this},toggle(t3){this.dropdown[this.state.dropdown.visible&&!t3?"hide":"show"]()},render(){var t3,e2,i2,s3=(t3=this.DOM.dropdown,(i2=t3.cloneNode(!0)).style.cssText="position:fixed; top:-9999px; opacity:0",document.body.appendChild(i2),e2=i2.clientHeight,i2.parentNode.removeChild(i2),e2),a2=this.settings;return typeof a2.dropdown.enabled=="number"&&a2.dropdown.enabled>=0?(this.DOM.scope.setAttribute("aria-expanded",!0),document.body.contains(this.DOM.dropdown)||(this.DOM.dropdown.classList.add(a2.classNames.dropdownInital),this.dropdown.position(s3),a2.dropdown.appendTarget.appendChild(this.DOM.dropdown),setTimeout(()=>this.DOM.dropdown.classList.remove(a2.classNames.dropdownInital))),this):this},fill(t3){t3=typeof t3=="string"?t3:this.dropdown.createListHTML(t3||this.suggestedListItems);var e2,i2=this.settings.templates.dropdownContent.call(this,t3);this.DOM.dropdown.content.innerHTML=(e2=i2)?e2.replace(/\>[\r\n ]+\</g,"><").replace(/(<.*?>)|\s+/g,(t4,e3)=>e3||" "):""},fillHeaderFooter(){this.settings.templates;var t3=this.dropdown.filterListItems(this.state.dropdown.query),e2=this.parseTemplate("dropdownHeader",[t3]),i2=this.parseTemplate("dropdownFooter",[t3]),s3=this.dropdown.getHeaderRef(),a2=this.dropdown.getFooterRef();e2&&s3?.parentNode.replaceChild(e2,s3),i2&&a2?.parentNode.replaceChild(i2,a2)},refilter(t3){t3=t3||this.state.dropdown.query||"",this.suggestedListItems=this.dropdown.filterListItems(t3),this.dropdown.fill(),this.suggestedListItems.length||this.dropdown.hide(),this.trigger("dropdown:updated",this.DOM.dropdown)},position(t3){var e2=this.settings.dropdown;if(e2.position!="manual"){var i2,s3,a2,n3,o2,r2,l3=this.DOM.dropdown,d2=e2.placeAbove,h2=e2.appendTarget===document.body,g2=h2?window.pageYOffset:e2.appendTarget.scrollTop,p2=document.fullscreenElement||document.webkitFullscreenElement||document.documentElement,c2=p2.clientHeight,u2=Math.max(p2.clientWidth||0,window.innerWidth||0)>480?e2.position:"all",m2=this.DOM[u2=="input"?"input":"scope"];if(t3=t3||l3.clientHeight,this.state.dropdown.visible){if(u2=="text"?(a2=(i2=this.getCaretGlobalPosition()).bottom,s3=i2.top,n3=i2.left,o2="auto"):(r2=function(t4){for(var e3=0,i3=0;t4&&t4!=p2;)e3+=t4.offsetLeft||0,i3+=t4.offsetTop||0,t4=t4.parentNode;return{left:e3,top:i3}}(e2.appendTarget),s3=(i2=m2.getBoundingClientRect()).top-r2.top,a2=i2.bottom-1-r2.top,n3=i2.left-r2.left,o2=i2.width+"px"),!h2){let t4=function(){for(var t5=0,i3=e2.appendTarget.parentNode;i3;)t5+=i3.scrollTop||0,i3=i3.parentNode;return t5}();s3+=t4,a2+=t4}s3=Math.floor(s3),a2=Math.ceil(a2),d2=d2===void 0?c2-i2.bottom<t3:d2,l3.style.cssText="left:"+(n3+window.pageXOffset)+"px; width:"+o2+";"+(d2?"top: "+(s3+g2)+"px":"top: "+(a2+g2)+"px"),l3.setAttribute("placement",d2?"top":"bottom"),l3.setAttribute("position",u2)}}},events:{binding(){let t3=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];var e2=this.dropdown.events.callbacks,i2=this.listeners.dropdown=this.listeners.dropdown||{position:this.dropdown.position.bind(this,null),onKeyDown:e2.onKeyDown.bind(this),onMouseOver:e2.onMouseOver.bind(this),onMouseLeave:e2.onMouseLeave.bind(this),onClick:e2.onClick.bind(this),onScroll:e2.onScroll.bind(this)},s3=t3?"addEventListener":"removeEventListener";this.settings.dropdown.position!="manual"&&(document[s3]("scroll",i2.position,!0),window[s3]("resize",i2.position),window[s3]("keydown",i2.onKeyDown)),this.DOM.dropdown[s3]("mouseover",i2.onMouseOver),this.DOM.dropdown[s3]("mouseleave",i2.onMouseLeave),this.DOM.dropdown[s3]("mousedown",i2.onClick),this.DOM.dropdown.content[s3]("scroll",i2.onScroll)},callbacks:{onKeyDown(t3){if(this.state.hasFocus&&!this.state.composing){var e2=this.DOM.dropdown.querySelector(this.settings.classNames.dropdownItemActiveSelector),i2=this.dropdown.getSuggestionDataByNode(e2);switch(t3.key){case"ArrowDown":case"ArrowUp":case"Down":case"Up":t3.preventDefault();var s3=this.dropdown.getAllSuggestionsRefs(),a2=t3.key=="ArrowUp"||t3.key=="Up";e2&&(e2=this.dropdown.getNextOrPrevOption(e2,!a2)),e2&&e2.matches(this.settings.classNames.dropdownItemSelector)||(e2=s3[a2?s3.length-1:0]),i2=this.dropdown.getSuggestionDataByNode(e2),this.dropdown.highlightOption(e2,!0);break;case"Escape":case"Esc":this.dropdown.hide();break;case"ArrowRight":if(this.state.actions.ArrowLeft)return;case"Tab":if(this.settings.mode!="mix"&&e2&&!this.settings.autoComplete.rightKey&&!this.state.editing){t3.preventDefault();var n3=this.dropdown.getMappedValue(i2);return this.input.autocomplete.set.call(this,n3),!1}return!0;case"Enter":t3.preventDefault(),this.settings.hooks.suggestionClick(t3,{tagify:this,tagData:i2,suggestionElm:e2}).then(()=>{if(e2)return this.dropdown.selectOption(e2),e2=this.dropdown.getNextOrPrevOption(e2,!a2),void this.dropdown.highlightOption(e2);this.dropdown.hide(),this.settings.mode!="mix"&&this.addTags(this.state.inputText.trim(),!0)}).catch(t4=>t4);break;case"Backspace":{if(this.settings.mode=="mix"||this.state.editing.scope)return;const t4=this.input.raw.call(this);t4!=""&&t4.charCodeAt(0)!=8203||(this.settings.backspace===!0?this.removeTags():this.settings.backspace=="edit"&&setTimeout(this.editTag.bind(this),0))}}}},onMouseOver(t3){var e2=t3.target.closest(this.settings.classNames.dropdownItemSelector);e2&&this.dropdown.highlightOption(e2)},onMouseLeave(t3){this.dropdown.highlightOption()},onClick(t3){if(t3.button==0&&t3.target!=this.DOM.dropdown&&t3.target!=this.DOM.dropdown.content){var e2=t3.target.closest(this.settings.classNames.dropdownItemSelector),i2=this.dropdown.getSuggestionDataByNode(e2);this.state.actions.selectOption=!0,setTimeout(()=>this.state.actions.selectOption=!1,50),this.settings.hooks.suggestionClick(t3,{tagify:this,tagData:i2,suggestionElm:e2}).then(()=>{e2?this.dropdown.selectOption(e2,t3):this.dropdown.hide()}).catch(t4=>console.warn(t4))}},onScroll(t3){var e2=t3.target,i2=e2.scrollTop/(e2.scrollHeight-e2.parentNode.clientHeight)*100;this.trigger("dropdown:scroll",{percentage:Math.round(i2)})}}},getSuggestionDataByNode(t3){var e2=t3&&t3.getAttribute("value");return this.suggestedListItems.find(t4=>t4.value==e2)||null},getNextOrPrevOption(t3){let e2=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];var i2=this.dropdown.getAllSuggestionsRefs(),s3=i2.findIndex(e3=>e3===t3);return e2?i2[s3+1]:i2[s3-1]},highlightOption(t3,e2){var i2,s3=this.settings.classNames.dropdownItemActive;if(this.state.ddItemElm&&(this.state.ddItemElm.classList.remove(s3),this.state.ddItemElm.removeAttribute("aria-selected")),!t3)return this.state.ddItemData=null,this.state.ddItemElm=null,void this.input.autocomplete.suggest.call(this);i2=this.dropdown.getSuggestionDataByNode(t3),this.state.ddItemData=i2,this.state.ddItemElm=t3,t3.classList.add(s3),t3.setAttribute("aria-selected",!0),e2&&(t3.parentNode.scrollTop=t3.clientHeight+t3.offsetTop-t3.parentNode.clientHeight),this.settings.autoComplete&&(this.input.autocomplete.suggest.call(this,i2),this.dropdown.position())},selectOption(t3,e2){var i2=this.settings.dropdown,s3=i2.clearOnSelect,a2=i2.closeOnSelect;if(!t3)return this.addTags(this.state.inputText,!0),void(a2&&this.dropdown.hide());e2=e2||{};var n3=t3.getAttribute("value"),o2=n3=="noMatch",r2=this.suggestedListItems.find(t4=>(t4.value||t4)==n3);this.trigger("dropdown:select",{data:r2,elm:t3,event:e2}),n3&&(r2||o2)?(this.state.editing?this.onEditTagDone(null,g({__isValid:!0},this.normalizeTags([r2])[0])):this[this.settings.mode=="mix"?"addMixTags":"addTags"]([r2||this.input.raw.call(this)],s3),this.DOM.input.parentNode&&(setTimeout(()=>{this.DOM.input.focus(),this.toggleFocusClass(!0),this.setRangeAtStartEnd(!1)}),a2&&setTimeout(this.dropdown.hide.bind(this)),t3.addEventListener("transitionend",()=>{this.dropdown.fillHeaderFooter(),setTimeout(()=>t3.remove(),100)},{once:!0}),t3.classList.add(this.settings.classNames.dropdownItemHidden))):a2&&setTimeout(this.dropdown.hide.bind(this))},selectAll(t3){this.suggestedListItems.length=0,this.dropdown.hide(),this.dropdown.filterListItems("");var e2=this.dropdown.filterListItems("");return t3||(e2=this.state.dropdown.suggestions),this.addTags(e2,!0),this},filterListItems(t3,e2){var i2,s3,a2,n3,o2,r2=this.settings,l3=r2.dropdown,d2=(e2=e2||{},[]),g2=[],p2=r2.whitelist,u2=l3.maxItems>=0?l3.maxItems:1/0,m2=l3.searchKeys,v2=0;if(!(t3=r2.mode=="select"&&this.value.length&&this.value[0][r2.tagTextProp]==t3?"":t3)||!m2.length)return d2=l3.includeSelectedTags?p2:p2.filter(t4=>!this.isTagDuplicate(h(t4)?t4.value:t4)),this.state.dropdown.suggestions=d2,d2.slice(0,u2);function f3(t4,e3){return e3.toLowerCase().split(" ").every(e4=>t4.includes(e4.toLowerCase()))}for(__name(f3,"f3"),__name2(f3,"f"),o2=l3.caseSensitive?""+t3:(""+t3).toLowerCase();v2<p2.length;v2++){let t4,r3;i2=p2[v2]instanceof Object?p2[v2]:{value:p2[v2]};let u3=Object.keys(i2).some(t5=>m2.includes(t5))?m2:["value"];l3.fuzzySearch&&!e2.exact?(a2=u3.reduce((t5,e3)=>t5+" "+(i2[e3]||""),"").toLowerCase().trim(),l3.accentedSearch&&(a2=c(a2),o2=c(o2)),t4=a2.indexOf(o2)==0,r3=a2===o2,s3=f3(a2,o2)):(t4=!0,s3=u3.some(t5=>{var s4=""+(i2[t5]||"");return l3.accentedSearch&&(s4=c(s4),o2=c(o2)),l3.caseSensitive||(s4=s4.toLowerCase()),r3=s4===o2,e2.exact?s4===o2:s4.indexOf(o2)==0})),n3=!l3.includeSelectedTags&&this.isTagDuplicate(h(i2)?i2.value:i2),s3&&!n3&&(r3&&t4?g2.push(i2):l3.sortby=="startsWith"&&t4?d2.unshift(i2):d2.push(i2))}return this.state.dropdown.suggestions=g2.concat(d2),typeof l3.sortby=="function"?l3.sortby(g2.concat(d2),o2):g2.concat(d2).slice(0,u2)},getMappedValue(t3){var e2=this.settings.dropdown.mapValueTo;return e2?typeof e2=="function"?e2(t3):t3[e2]||t3.value:t3.value},createListHTML(t3){return g([],t3).map((t4,i2)=>{typeof t4!="string"&&typeof t4!="number"||(t4={value:t4});var s3=this.dropdown.getMappedValue(t4);return s3=typeof s3=="string"?d(s3):s3,this.settings.templates.dropdownItem.apply(this,[e(e({},t4),{},{mappedValue:s3}),this])}).join("")}};const b="@yaireo/tagify/";var y,x={empty:"empty",exceed:"number of tags exceeded",pattern:"pattern mismatch",duplicate:"already exists",notAllowed:"not allowed"},D={wrapper:(t3,e2)=>`<tags class="${e2.classNames.namespace} ${e2.mode?`${e2.classNames[e2.mode+"Mode"]}`:""} ${t3.className}"
${e2.readonly?"readonly":""}
${e2.disabled?"disabled":""}
${e2.required?"required":""}
${e2.mode==="select"?"spellcheck='false'":""}
tabIndex="-1">
<span ${!e2.readonly&&e2.userInput?"contenteditable":""} tabIndex="0" data-placeholder="${e2.placeholder||"&#8203;"}" aria-placeholder="${e2.placeholder||""}"
class="${e2.classNames.input}"
role="textbox"
aria-autocomplete="both"
aria-multiline="${e2.mode=="mix"}"></span>
&#8203;
</tags>`,tag(t3,e2){let i2=e2.settings;return`<tag title="${t3.title||t3.value}"
contenteditable='false'
spellcheck='false'
tabIndex="${i2.a11y.focusableTags?0:-1}"
class="${i2.classNames.tag} ${t3.class||""}"
${this.getAttributes(t3)}>
<x title='' class="${i2.classNames.tagX}" role='button' aria-label='remove tag'></x>
<div>
<span class="${i2.classNames.tagText}">${t3[i2.tagTextProp]||t3.value}</span>
</div>
</tag>`},dropdown(t3){var e2=t3.dropdown,i2=e2.position=="manual",s3=`${t3.classNames.dropdown}`;return`<div class="${i2?"":s3} ${e2.classname}" role="listbox" aria-labelledby="dropdown">
<div data-selector='tagify-suggestions-wrapper' class="${t3.classNames.dropdownWrapper}"></div>
</div>`},dropdownContent(t3){var e2=this.settings,i2=this.state.dropdown.suggestions;return`
${e2.templates.dropdownHeader.call(this,i2)}
${t3}
${e2.templates.dropdownFooter.call(this,i2)}
`},dropdownItem(t3){return`<div ${this.getAttributes(t3)}
class='${this.settings.classNames.dropdownItem} ${t3.class?t3.class:""}'
tabindex="0"
role="option">${t3.mappedValue||t3.value}</div>`},dropdownHeader(t3){return`<header data-selector='tagify-suggestions-header' class="${this.settings.classNames.dropdownHeader}"></header>`},dropdownFooter(t3){var e2=t3.length-this.settings.dropdown.maxItems;return e2>0?`<footer data-selector='tagify-suggestions-footer' class="${this.settings.classNames.dropdownFooter}">
${e2} more items. Refine your search.
</footer>`:""},dropdownItemNoMatch:null},O={customBinding(){this.customEventsList.forEach(t3=>{this.on(t3,this.settings.callbacks[t3])})},binding(){let t3=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];var e2,i2=this.events.callbacks,s3=t3?"addEventListener":"removeEventListener";if(!this.state.mainEvents||!t3){for(var a2 in this.state.mainEvents=t3,t3&&!this.listeners.main&&(this.events.bindGlobal.call(this),this.settings.isJQueryPlugin&&jQuery(this.DOM.originalInput).on("tagify.removeAllTags",this.removeAllTags.bind(this))),e2=this.listeners.main=this.listeners.main||{focus:["input",i2.onFocusBlur.bind(this)],keydown:["input",i2.onKeydown.bind(this)],click:["scope",i2.onClickScope.bind(this)],dblclick:["scope",i2.onDoubleClickScope.bind(this)],paste:["input",i2.onPaste.bind(this)],drop:["input",i2.onDrop.bind(this)],compositionstart:["input",i2.onCompositionStart.bind(this)],compositionend:["input",i2.onCompositionEnd.bind(this)]})this.DOM[e2[a2][0]][s3](a2,e2[a2][1]);clearInterval(this.listeners.main.originalInputValueObserverInterval),this.listeners.main.originalInputValueObserverInterval=setInterval(i2.observeOriginalInputValue.bind(this),500);var n3=this.listeners.main.inputMutationObserver||new MutationObserver(i2.onInputDOMChange.bind(this));n3&&n3.disconnect(),this.settings.mode=="mix"&&n3.observe(this.DOM.input,{childList:!0})}},bindGlobal(t3){var e2,i2=this.events.callbacks,s3=t3?"removeEventListener":"addEventListener";if(t3||!this.listeners.global)for(e2 of(this.listeners.global=this.listeners&&this.listeners.global||[{type:this.isIE?"keydown":"input",target:this.DOM.input,cb:i2[this.isIE?"onInputIE":"onInput"].bind(this)},{type:"keydown",target:window,cb:i2.onWindowKeyDown.bind(this)},{type:"blur",target:this.DOM.input,cb:i2.onFocusBlur.bind(this)}],this.listeners.global))e2.target[s3](e2.type,e2.cb)},unbindGlobal(){this.events.bindGlobal.call(this,!0)},callbacks:{onFocusBlur(t3){var e2=this.settings,i2=t3.target?this.trim(t3.target.textContent):"",s3=this.value?.[0]?.[e2.tagTextProp],a2=t3.type,n3=e2.dropdown.enabled>=0,o2={relatedTarget:t3.relatedTarget},r2=this.state.actions.selectOption&&(n3||!e2.dropdown.closeOnSelect),l3=this.state.actions.addNew&&n3,d2=t3.relatedTarget&&v.call(this,t3.relatedTarget)&&this.DOM.scope.contains(t3.relatedTarget);if(a2=="blur"){if(t3.relatedTarget===this.DOM.scope)return this.dropdown.hide(),void this.DOM.input.focus();this.postUpdate(),e2.onChangeAfterBlur&&this.triggerChangeEvent()}if(!r2&&!l3)if(this.state.hasFocus=a2=="focus"&&+new Date,this.toggleFocusClass(this.state.hasFocus),e2.mode!="mix"){if(a2=="focus")return this.trigger("focus",o2),void(e2.dropdown.enabled!==0&&e2.userInput||this.dropdown.show(this.value.length?"":void 0));a2=="blur"&&(this.trigger("blur",o2),this.loading(!1),e2.mode=="select"&&(d2&&(this.removeTags(),i2=""),s3===i2&&(i2="")),i2&&!this.state.actions.selectOption&&e2.addTagOnBlur&&this.addTags(i2,!0)),this.DOM.input.removeAttribute("style"),this.dropdown.hide()}else a2=="focus"?this.trigger("focus",o2):t3.type=="blur"&&(this.trigger("blur",o2),this.loading(!1),this.dropdown.hide(),this.state.dropdown.visible=void 0,this.setStateSelection())},onCompositionStart(t3){this.state.composing=!0},onCompositionEnd(t3){this.state.composing=!1},onWindowKeyDown(t3){var e2,i2=document.activeElement;if(v.call(this,i2)&&this.DOM.scope.contains(document.activeElement))switch(e2=i2.nextElementSibling,t3.key){case"Backspace":this.settings.readonly||(this.removeTags(i2),(e2||this.DOM.input).focus());break;case"Enter":setTimeout(this.editTag.bind(this),0,i2)}},onKeydown(t3){var e2=this.settings;if(!this.state.composing&&e2.userInput){e2.mode=="select"&&e2.enforceWhitelist&&this.value.length&&t3.key!="Tab"&&t3.preventDefault();var i2=this.trim(t3.target.textContent);if(this.trigger("keydown",{event:t3}),e2.mode=="mix"){switch(t3.key){case"Left":case"ArrowLeft":this.state.actions.ArrowLeft=!0;break;case"Delete":case"Backspace":if(this.state.editing)return;var s3,a2,n3,r2=document.getSelection(),d2=t3.key=="Delete"&&r2.anchorOffset==(r2.anchorNode.length||0),h2=r2.anchorNode.previousSibling,g2=r2.anchorNode.nodeType==1||!r2.anchorOffset&&h2&&h2.nodeType==1&&r2.anchorNode.previousSibling,p2=o(this.DOM.input.innerHTML),c2=this.getTagElms();if(e2.backspace=="edit"&&g2)return s3=r2.anchorNode.nodeType==1?null:r2.anchorNode.previousElementSibling,setTimeout(this.editTag.bind(this),0,s3),void t3.preventDefault();if(u()&&g2)return n3=l2(g2),g2.hasAttribute("readonly")||g2.remove(),this.DOM.input.focus(),void setTimeout(()=>{this.placeCaretAfterNode(n3),this.DOM.input.click()});if(r2.anchorNode.nodeName=="BR")return;if((d2||g2)&&r2.anchorNode.nodeType==1?a2=r2.anchorOffset==0?d2?c2[0]:null:c2[Math.min(c2.length,r2.anchorOffset)-1]:d2?a2=r2.anchorNode.nextElementSibling:g2&&(a2=g2),r2.anchorNode.nodeType==3&&!r2.anchorNode.nodeValue&&r2.anchorNode.previousElementSibling&&t3.preventDefault(),(g2||d2)&&!e2.backspace||r2.type!="Range"&&!r2.anchorOffset&&r2.anchorNode==this.DOM.input&&t3.key!="Delete")return void t3.preventDefault();if(r2.type!="Range"&&a2&&a2.hasAttribute("readonly"))return void this.placeCaretAfterNode(l2(a2));clearTimeout(y),y=setTimeout(()=>{var t4=document.getSelection(),e3=o(this.DOM.input.innerHTML),i3=!d2&&t4.anchorNode.previousSibling;if(e3.length>=p2.length&&i3)if(v.call(this,i3)&&!i3.hasAttribute("readonly")){if(this.removeTags(i3),this.fixFirefoxLastTagNoCaret(),this.DOM.input.children.length==2&&this.DOM.input.children[1].tagName=="BR")return this.DOM.input.innerHTML="",this.value.length=0,!0}else i3.remove();this.value=[].map.call(c2,(t5,e4)=>{var i4=this.tagData(t5);if(t5.parentNode||i4.readonly)return i4;this.trigger("remove",{tag:t5,index:e4,data:i4})}).filter(t5=>t5)},20)}return!0}switch(t3.key){case"Backspace":e2.mode=="select"&&e2.enforceWhitelist&&this.value.length?this.removeTags():this.state.dropdown.visible&&e2.dropdown.position!="manual"||t3.target.textContent!=""&&i2.charCodeAt(0)!=8203||(e2.backspace===!0?this.removeTags():e2.backspace=="edit"&&setTimeout(this.editTag.bind(this),0));break;case"Esc":case"Escape":if(this.state.dropdown.visible)return;t3.target.blur();break;case"Down":case"ArrowDown":this.state.dropdown.visible||this.dropdown.show();break;case"ArrowRight":{let t4=this.state.inputSuggestion||this.state.ddItemData;if(t4&&e2.autoComplete.rightKey)return void this.addTags([t4],!0);break}case"Tab":{let s4=e2.mode=="select";if(!i2||s4)return!0;t3.preventDefault()}case"Enter":if(this.state.dropdown.visible&&e2.dropdown.position!="manual")return;t3.preventDefault(),setTimeout(()=>{this.state.actions.selectOption||this.addTags(i2,!0)})}}},onInput(t3){this.postUpdate();var e2=this.settings;if(e2.mode=="mix")return this.events.callbacks.onMixTagsInput.call(this,t3);var i2=this.input.normalize.call(this),s3=i2.length>=e2.dropdown.enabled,a2={value:i2,inputElm:this.DOM.input},n3=this.validateTag({value:i2});e2.mode=="select"&&this.toggleScopeValidation(n3),a2.isValid=n3,this.state.inputText!=i2&&(this.input.set.call(this,i2,!1),i2.search(e2.delimiters)!=-1?this.addTags(i2)&&this.input.set.call(this):e2.dropdown.enabled>=0&&this.dropdown[s3?"show":"hide"](i2),this.trigger("input",a2))},onMixTagsInput(t3){var e2,i2,s3,a2,n3,o2,r2,l3,d2=this.settings,h2=this.value.length,p2=this.getTagElms(),c2=document.createDocumentFragment(),m2=window.getSelection().getRangeAt(0),v2=[].map.call(p2,t4=>this.tagData(t4).value);if(t3.inputType=="deleteContentBackward"&&u()&&this.events.callbacks.onKeydown.call(this,{target:t3.target,key:"Backspace"}),this.value.slice().forEach(t4=>{t4.readonly&&!v2.includes(t4.value)&&c2.appendChild(this.createTagElem(t4))}),c2.childNodes.length&&(m2.insertNode(c2),this.setRangeAtStartEnd(!1,c2.lastChild)),p2.length!=h2)return this.value=[].map.call(this.getTagElms(),t4=>this.tagData(t4)),void this.update({withoutChangeEvent:!0});if(this.hasMaxTags())return!0;if(window.getSelection&&(o2=window.getSelection()).rangeCount>0&&o2.anchorNode.nodeType==3){if((m2=o2.getRangeAt(0).cloneRange()).collapse(!0),m2.setStart(o2.focusNode,0),s3=(e2=m2.toString().slice(0,m2.endOffset)).split(d2.pattern).length-1,(i2=e2.match(d2.pattern))&&(a2=e2.slice(e2.lastIndexOf(i2[i2.length-1]))),a2){if(this.state.actions.ArrowLeft=!1,this.state.tag={prefix:a2.match(d2.pattern)[0],value:a2.replace(d2.pattern,"")},this.state.tag.baseOffset=o2.baseOffset-this.state.tag.value.length,l3=this.state.tag.value.match(d2.delimiters))return this.state.tag.value=this.state.tag.value.replace(d2.delimiters,""),this.state.tag.delimiters=l3[0],this.addTags(this.state.tag.value,d2.dropdown.clearOnSelect),void this.dropdown.hide();n3=this.state.tag.value.length>=d2.dropdown.enabled;try{r2=(r2=this.state.flaggedTags[this.state.tag.baseOffset]).prefix==this.state.tag.prefix&&r2.value[0]==this.state.tag.value[0],this.state.flaggedTags[this.state.tag.baseOffset]&&!this.state.tag.value&&delete this.state.flaggedTags[this.state.tag.baseOffset]}catch{}(r2||s3<this.state.mixMode.matchedPatternCount)&&(n3=!1)}else this.state.flaggedTags={};this.state.mixMode.matchedPatternCount=s3}setTimeout(()=>{this.update({withoutChangeEvent:!0}),this.trigger("input",g({},this.state.tag,{textContent:this.DOM.input.textContent})),this.state.tag&&this.dropdown[n3?"show":"hide"](this.state.tag.value)},10)},onInputIE(t3){var e2=this;setTimeout(function(){e2.events.callbacks.onInput.call(e2,t3)})},observeOriginalInputValue(){this.DOM.originalInput.parentNode||this.destroy(),this.DOM.originalInput.value!=this.DOM.originalInput.tagifyValue&&this.loadOriginalValues()},onClickScope(t3){var e2=this.settings,i2=t3.target.closest("."+e2.classNames.tag),s3=+new Date-this.state.hasFocus;if(t3.target!=this.DOM.scope){if(!t3.target.classList.contains(e2.classNames.tagX))return i2?(this.trigger("click",{tag:i2,index:this.getNodeIndex(i2),data:this.tagData(i2),event:t3}),void(e2.editTags!==1&&e2.editTags.clicks!==1||this.events.callbacks.onDoubleClickScope.call(this,t3))):void(t3.target==this.DOM.input&&(e2.mode=="mix"&&this.fixFirefoxLastTagNoCaret(),s3>500)?this.state.dropdown.visible?this.dropdown.hide():e2.dropdown.enabled===0&&e2.mode!="mix"&&this.dropdown.show(this.value.length?"":void 0):e2.mode=="select"&&!this.state.dropdown.visible&&this.dropdown.show());this.removeTags(t3.target.parentNode)}else this.state.hasFocus||this.DOM.input.focus()},onPaste(t3){t3.preventDefault();var e2,i2,s3=this.settings;if(s3.mode=="select"&&s3.enforceWhitelist||!s3.userInput)return!1;s3.readonly||(e2=t3.clipboardData||window.clipboardData,i2=e2.getData("Text"),s3.hooks.beforePaste(t3,{tagify:this,pastedText:i2,clipboardData:e2}).then(e3=>{e3===void 0&&(e3=i2),e3&&(this.injectAtCaret(e3,window.getSelection().getRangeAt(0)),this.settings.mode=="mix"?this.events.callbacks.onMixTagsInput.call(this,t3):this.settings.pasteAsTags?this.addTags(this.state.inputText+e3,!0):this.state.inputText=e3)}).catch(t4=>t4))},onDrop(t3){t3.preventDefault()},onEditTagInput(t3,e2){var i2=t3.closest("."+this.settings.classNames.tag),s3=this.getNodeIndex(i2),a2=this.tagData(i2),n3=this.input.normalize.call(this,t3),o2={[this.settings.tagTextProp]:n3,__tagId:a2.__tagId},r2=this.validateTag(o2);this.editTagChangeDetected(g(a2,o2))||t3.originalIsValid!==!0||(r2=!0),i2.classList.toggle(this.settings.classNames.tagInvalid,r2!==!0),a2.__isValid=r2,i2.title=r2===!0?a2.title||a2.value:r2,n3.length>=this.settings.dropdown.enabled&&(this.state.editing&&(this.state.editing.value=n3),this.dropdown.show(n3)),this.trigger("edit:input",{tag:i2,index:s3,data:g({},this.value[s3],{newValue:n3}),event:e2})},onEditTagFocus(t3){this.state.editing={scope:t3,input:t3.querySelector("[contenteditable]")}},onEditTagBlur(t3){if(this.state.hasFocus||this.toggleFocusClass(),this.DOM.scope.contains(t3)){var e2,i2,s3=this.settings,a2=t3.closest("."+s3.classNames.tag),n3=this.input.normalize.call(this,t3),o2=this.tagData(a2),r2=o2.__originalData,l3=this.editTagChangeDetected(o2),d2=this.validateTag({[s3.tagTextProp]:n3,__tagId:o2.__tagId});if(n3)if(l3){if(e2=this.hasMaxTags(),i2=g({},r2,{[s3.tagTextProp]:this.trim(n3),__isValid:d2}),s3.transformTag.call(this,i2,r2),(d2=(!e2||r2.__isValid===!0)&&this.validateTag(i2))!==!0){if(this.trigger("invalid",{data:i2,tag:a2,message:d2}),s3.editTags.keepInvalid)return;s3.keepInvalidTags?i2.__isValid=d2:i2=r2}else s3.keepInvalidTags&&(delete i2.title,delete i2["aria-invalid"],delete i2.class);this.onEditTagDone(a2,i2)}else this.onEditTagDone(a2,r2);else this.onEditTagDone(a2)}},onEditTagkeydown(t3,e2){if(!this.state.composing)switch(this.trigger("edit:keydown",{event:t3}),t3.key){case"Esc":case"Escape":e2.parentNode.replaceChild(e2.__tagifyTagData.__originalHTML,e2),this.state.editing=!1;case"Enter":case"Tab":t3.preventDefault(),t3.target.blur()}},onDoubleClickScope(t3){var e2,i2,s3=t3.target.closest("."+this.settings.classNames.tag),a2=this.tagData(s3),n3=this.settings;s3&&n3.userInput&&a2.editable!==!1&&(e2=s3.classList.contains(this.settings.classNames.tagEditing),i2=s3.hasAttribute("readonly"),n3.mode=="select"||n3.readonly||e2||i2||!this.settings.editTags||this.editTag(s3),this.toggleFocusClass(!0),this.trigger("dblclick",{tag:s3,index:this.getNodeIndex(s3),data:this.tagData(s3)}))},onInputDOMChange(t3){t3.forEach(t4=>{t4.addedNodes.forEach(t5=>{if(t5.outerHTML=="<div><br></div>")t5.replaceWith(document.createElement("br"));else if(t5.nodeType==1&&t5.querySelector(this.settings.classNames.tagSelector)){let e3=document.createTextNode("");t5.childNodes[0].nodeType==3&&t5.previousSibling.nodeName!="BR"&&(e3=document.createTextNode(`
`)),t5.replaceWith(e3,...[...t5.childNodes].slice(0,-1)),this.placeCaretAfterNode(e3)}else if(v.call(this,t5)&&(t5.previousSibling?.nodeType!=3||t5.previousSibling.textContent||t5.previousSibling.remove(),t5.previousSibling&&t5.previousSibling.nodeName=="BR")){t5.previousSibling.replaceWith(`
\u200B`);let e3=t5.nextSibling,i2="";for(;e3;)i2+=e3.textContent,e3=e3.nextSibling;i2.trim()&&this.placeCaretAfterNode(t5.previousSibling)}}),t4.removedNodes.forEach(t5=>{t5&&t5.nodeName=="BR"&&v.call(this,e2)&&(this.removeTags(e2),this.fixFirefoxLastTagNoCaret())})});var e2=this.DOM.input.lastChild;e2&&e2.nodeValue==""&&e2.remove(),e2&&e2.nodeName=="BR"||this.DOM.input.appendChild(document.createElement("br"))}}};function M(t3,e2){if(!t3){console.warn("Tagify:","input element not found",t3);const e3=new Proxy(this,{get:()=>()=>e3});return e3}if(t3.__tagify)return console.warn("Tagify: ","input element is already Tagified - Same instance is returned.",t3),t3.__tagify;var i2;g(this,function(t4){var e3=document.createTextNode("");function i3(t5,i4,s3){s3&&i4.split(/\s+/g).forEach(i5=>e3[t5+"EventListener"].call(e3,i5,s3))}return __name(i3,"i3"),__name2(i3,"i"),{off(t5,e4){return i3("remove",t5,e4),this},on(t5,e4){return e4&&typeof e4=="function"&&i3("add",t5,e4),this},trigger(i4,s3,a2){var n3;if(a2=a2||{cloneData:!0},i4)if(t4.settings.isJQueryPlugin)i4=="remove"&&(i4="removeTag"),jQuery(t4.DOM.originalInput).triggerHandler(i4,[s3]);else{try{var o2=typeof s3=="object"?s3:{value:s3};if((o2=a2.cloneData?g({},o2):o2).tagify=this,s3.event&&(o2.event=this.cloneEvent(s3.event)),s3 instanceof Object)for(var r2 in s3)s3[r2]instanceof HTMLElement&&(o2[r2]=s3[r2]);n3=new CustomEvent(i4,{detail:o2})}catch(t5){console.warn(t5)}e3.dispatchEvent(n3)}}}}(this)),this.isFirefox=typeof InstallTrigger<"u",this.isIE=window.document.documentMode,e2=e2||{},this.getPersistedData=(i2=e2.id,t4=>{let e3,s3="/"+t4;if(localStorage.getItem(b+i2+"/v",1)==1)try{e3=JSON.parse(localStorage[b+i2+s3])}catch{}return e3}),this.setPersistedData=(t4=>t4?(localStorage.setItem(b+t4+"/v",1),(e3,i3)=>{let s3="/"+i3,a2=JSON.stringify(e3);e3&&i3&&(localStorage.setItem(b+t4+s3,a2),dispatchEvent(new Event("storage")))}):()=>{})(e2.id),this.clearPersistedData=(t4=>e3=>{const i3=b+"/"+t4+"/";if(e3)localStorage.removeItem(i3+e3);else for(let t5 in localStorage)t5.includes(i3)&&localStorage.removeItem(t5)})(e2.id),this.applySettings(t3,e2),this.state={inputText:"",editing:!1,composing:!1,actions:{},mixMode:{},dropdown:{},flaggedTags:{}},this.value=[],this.listeners={},this.DOM={},this.build(t3),T.call(this),this.getCSSVars(),this.loadOriginalValues(),this.events.customBinding.call(this),this.events.binding.call(this),t3.autofocus&&this.DOM.input.focus(),t3.__tagify=this}return __name(M,"M"),__name2(M,"M"),M.prototype={_dropdown:w,helpers:{sameStr:s2,removeCollectionProp:a,omit:n2,isObject:h,parseHTML:r,escapeHTML:d,extend:g,concatWithoutDups:p,getUID:m,isNodeTag:v},customEventsList:["change","add","remove","invalid","input","click","keydown","focus","blur","edit:input","edit:beforeUpdate","edit:updated","edit:start","edit:keydown","dropdown:show","dropdown:hide","dropdown:select","dropdown:updated","dropdown:noMatch","dropdown:scroll"],dataProps:["__isValid","__removed","__originalData","__originalHTML","__tagId"],trim(t3){return this.settings.trim&&t3&&typeof t3=="string"?t3.trim():t3},parseHTML:r,templates:D,parseTemplate(t3,e2){return t3=this.settings.templates[t3]||t3,this.parseHTML(t3.apply(this,e2))},set whitelist(t3){const e2=t3&&Array.isArray(t3);this.settings.whitelist=e2?t3:[],this.setPersistedData(e2?t3:[],"whitelist")},get whitelist(){return this.settings.whitelist},generateClassSelectors(t3){for(let e2 in t3){let i2=e2;Object.defineProperty(t3,i2+"Selector",{get(){return"."+this[i2].split(" ")[0]}})}},applySettings(t3,i2){f2.templates=this.templates;var s3=this.settings=g({},f2,i2);if(s3.disabled=t3.hasAttribute("disabled"),s3.readonly=s3.readonly||t3.hasAttribute("readonly"),s3.placeholder=d(t3.getAttribute("placeholder")||s3.placeholder||""),s3.required=t3.hasAttribute("required"),this.generateClassSelectors(s3.classNames),s3.dropdown.includeSelectedTags===void 0&&(s3.dropdown.includeSelectedTags=s3.duplicates),this.isIE&&(s3.autoComplete=!1),["whitelist","blacklist"].forEach(e2=>{var i3=t3.getAttribute("data-"+e2);i3&&(i3=i3.split(s3.delimiters))instanceof Array&&(s3[e2]=i3)}),"autoComplete"in i2&&!h(i2.autoComplete)&&(s3.autoComplete=f2.autoComplete,s3.autoComplete.enabled=i2.autoComplete),s3.mode=="mix"&&(s3.autoComplete.rightKey=!0,s3.delimiters=i2.delimiters||null,s3.tagTextProp&&!s3.dropdown.searchKeys.includes(s3.tagTextProp)&&s3.dropdown.searchKeys.push(s3.tagTextProp)),t3.pattern)try{s3.pattern=new RegExp(t3.pattern)}catch{}if(s3.delimiters){s3._delimiters=s3.delimiters;try{s3.delimiters=new RegExp(this.settings.delimiters,"g")}catch{}}s3.disabled&&(s3.userInput=!1),this.TEXTS=e(e({},x),s3.texts||{}),s3.mode!="select"&&s3.userInput||(s3.dropdown.enabled=0),s3.dropdown.appendTarget=i2.dropdown&&i2.dropdown.appendTarget?i2.dropdown.appendTarget:document.body;let a2=this.getPersistedData("whitelist");Array.isArray(a2)&&(this.whitelist=Array.isArray(s3.whitelist)?p(s3.whitelist,a2):a2)},getAttributes(t3){var e2,i2=this.getCustomAttributes(t3),s3="";for(e2 in i2)s3+=" "+e2+(t3[e2]!==void 0?`="${i2[e2]}"`:"");return s3},getCustomAttributes(t3){if(!h(t3))return"";var e2,i2={};for(e2 in t3)e2.slice(0,2)!="__"&&e2!="class"&&t3.hasOwnProperty(e2)&&t3[e2]!==void 0&&(i2[e2]=d(t3[e2]));return i2},setStateSelection(){var t3=window.getSelection(),e2={anchorOffset:t3.anchorOffset,anchorNode:t3.anchorNode,range:t3.getRangeAt&&t3.rangeCount&&t3.getRangeAt(0)};return this.state.selection=e2,e2},getCaretGlobalPosition(){const t3=document.getSelection();if(t3.rangeCount){const e2=t3.getRangeAt(0),i2=e2.startContainer,s3=e2.startOffset;let a2,n3;if(s3>0)return n3=document.createRange(),n3.setStart(i2,s3-1),n3.setEnd(i2,s3),a2=n3.getBoundingClientRect(),{left:a2.right,top:a2.top,bottom:a2.bottom};if(i2.getBoundingClientRect)return i2.getBoundingClientRect()}return{left:-9999,top:-9999}},getCSSVars(){var t3=getComputedStyle(this.DOM.scope,null),e2;this.CSSVars={tagHideTransition:(t4=>{let e3=t4.value;return t4.unit=="s"?1e3*e3:e3})(function(t4){if(!t4)return{};var e3=(t4=t4.trim().split(" ")[0]).split(/\d+/g).filter(t5=>t5).pop().trim();return{value:+t4.split(e3).filter(t5=>t5)[0].trim(),unit:e3}}((e2="tag-hide-transition",t3.getPropertyValue("--"+e2))))}},build(t3){var e2=this.DOM;this.settings.mixMode.integrated?(e2.originalInput=null,e2.scope=t3,e2.input=t3):(e2.originalInput=t3,e2.originalInput_tabIndex=t3.tabIndex,e2.scope=this.parseTemplate("wrapper",[t3,this.settings]),e2.input=e2.scope.querySelector(this.settings.classNames.inputSelector),t3.parentNode.insertBefore(e2.scope,t3),t3.tabIndex=-1)},destroy(){this.events.unbindGlobal.call(this),this.DOM.scope.parentNode.removeChild(this.DOM.scope),this.DOM.originalInput.tabIndex=this.DOM.originalInput_tabIndex,delete this.DOM.originalInput.__tagify,this.dropdown.hide(!0),clearTimeout(this.dropdownHide__bindEventsTimeout),clearInterval(this.listeners.main.originalInputValueObserverInterval)},loadOriginalValues(t3){var e2,i2=this.settings;if(this.state.blockChangeEvent=!0,t3===void 0){const e3=this.getPersistedData("value");t3=e3&&!this.DOM.originalInput.value?e3:i2.mixMode.integrated?this.DOM.input.textContent:this.DOM.originalInput.value}if(this.removeAllTags(),t3)if(i2.mode=="mix")this.parseMixTags(this.trim(t3)),(e2=this.DOM.input.lastChild)&&e2.tagName=="BR"||this.DOM.input.insertAdjacentHTML("beforeend","<br>");else{try{JSON.parse(t3)instanceof Array&&(t3=JSON.parse(t3))}catch{}this.addTags(t3,!0).forEach(t4=>t4&&t4.classList.add(i2.classNames.tagNoAnimation))}else this.postUpdate();this.state.lastOriginalValueReported=i2.mixMode.integrated?"":this.DOM.originalInput.value,this.state.blockChangeEvent=!1},cloneEvent(t3){var e2={};for(var i2 in t3)i2!="path"&&(e2[i2]=t3[i2]);return e2},loading(t3){return this.state.isLoading=t3,this.DOM.scope.classList[t3?"add":"remove"](this.settings.classNames.scopeLoading),this},tagLoading(t3,e2){return t3&&t3.classList[e2?"add":"remove"](this.settings.classNames.tagLoading),this},toggleClass(t3,e2){typeof t3=="string"&&this.DOM.scope.classList.toggle(t3,e2)},toggleScopeValidation(t3){var e2=t3===!0||t3===void 0;!this.settings.required&&t3&&t3===this.TEXTS.empty&&(e2=!0),this.toggleClass(this.settings.classNames.tagInvalid,!e2),this.DOM.scope.title=e2?"":t3},toggleFocusClass(t3){this.toggleClass(this.settings.classNames.focus,!!t3)},triggerChangeEvent:function(){if(!this.settings.mixMode.integrated){var t3=this.DOM.originalInput,e2=this.state.lastOriginalValueReported!==t3.value,i2=new CustomEvent("change",{bubbles:!0});e2&&(this.state.lastOriginalValueReported=t3.value,i2.simulated=!0,t3._valueTracker&&t3._valueTracker.setValue(Math.random()),t3.dispatchEvent(i2),this.trigger("change",this.state.lastOriginalValueReported),t3.value=this.state.lastOriginalValueReported)}},events:O,fixFirefoxLastTagNoCaret(){},placeCaretAfterNode(t3){if(t3&&t3.parentNode){var e2=t3,i2=window.getSelection(),s3=i2.getRangeAt(0);i2.rangeCount&&(s3.setStartAfter(e2||t3),s3.collapse(!0),i2.removeAllRanges(),i2.addRange(s3))}},insertAfterTag(t3,e2){if(e2=e2||this.settings.mixMode.insertAfterTag,t3&&t3.parentNode&&e2)return e2=typeof e2=="string"?document.createTextNode(e2):e2,t3.parentNode.insertBefore(e2,t3.nextSibling),e2},editTagChangeDetected(t3){var e2=t3.__originalData;for(var i2 in e2)if(!this.dataProps.includes(i2)&&t3[i2]!=e2[i2])return!0;return!1},getTagTextNode(t3){return t3.querySelector(this.settings.classNames.tagTextSelector)},setTagTextNode(t3,e2){this.getTagTextNode(t3).innerHTML=d(e2)},editTag(t3,e2){t3=t3||this.getLastTag(),e2=e2||{},this.dropdown.hide();var i2=this.settings,s3=this.getTagTextNode(t3),a2=this.getNodeIndex(t3),n3=this.tagData(t3),o2=this.events.callbacks,r2=this,l3=!0;if(s3){if(!(n3 instanceof Object&&"editable"in n3)||n3.editable)return n3=this.tagData(t3,{__originalData:g({},n3),__originalHTML:t3.cloneNode(!0)}),this.tagData(n3.__originalHTML,n3.__originalData),s3.setAttribute("contenteditable",!0),t3.classList.add(i2.classNames.tagEditing),s3.addEventListener("focus",o2.onEditTagFocus.bind(this,t3)),s3.addEventListener("blur",function(){setTimeout(()=>o2.onEditTagBlur.call(r2,r2.getTagTextNode(t3)))}),s3.addEventListener("input",o2.onEditTagInput.bind(this,s3)),s3.addEventListener("keydown",e3=>o2.onEditTagkeydown.call(this,e3,t3)),s3.addEventListener("compositionstart",o2.onCompositionStart.bind(this)),s3.addEventListener("compositionend",o2.onCompositionEnd.bind(this)),e2.skipValidation||(l3=this.editTagToggleValidity(t3)),s3.originalIsValid=l3,this.trigger("edit:start",{tag:t3,index:a2,data:n3,isValid:l3}),s3.focus(),this.setRangeAtStartEnd(!1,s3),this}else console.warn("Cannot find element in Tag template: .",i2.classNames.tagTextSelector)},editTagToggleValidity(t3,e2){var i2;if(e2=e2||this.tagData(t3))return(i2=!("__isValid"in e2)||e2.__isValid===!0)||this.removeTagsFromValue(t3),this.update(),t3.classList.toggle(this.settings.classNames.tagNotAllowed,!i2),e2.__isValid;console.warn("tag has no data: ",t3,e2)},onEditTagDone(t3,e2){e2=e2||{};var i2={tag:t3=t3||this.state.editing.scope,index:this.getNodeIndex(t3),previousData:this.tagData(t3),data:e2};this.trigger("edit:beforeUpdate",i2,{cloneData:!1}),this.state.editing=!1,delete e2.__originalData,delete e2.__originalHTML,t3&&e2[this.settings.tagTextProp]?(t3=this.replaceTag(t3,e2),this.editTagToggleValidity(t3,e2),this.settings.a11y.focusableTags?t3.focus():this.placeCaretAfterNode(t3)):t3&&this.removeTags(t3),this.trigger("edit:updated",i2),this.dropdown.hide(),this.settings.keepInvalidTags&&this.reCheckInvalidTags()},replaceTag(t3,e2){e2&&e2.value||(e2=t3.__tagifyTagData),e2.__isValid&&e2.__isValid!=1&&g(e2,this.getInvalidTagAttrs(e2,e2.__isValid));var i2=this.createTagElem(e2);return t3.parentNode.replaceChild(i2,t3),this.updateValueByDOMTags(),i2},updateValueByDOMTags(){this.value.length=0,[].forEach.call(this.getTagElms(),t3=>{t3.classList.contains(this.settings.classNames.tagNotAllowed.split(" ")[0])||this.value.push(this.tagData(t3))}),this.update()},setRangeAtStartEnd(t3,e2){t3=typeof t3=="number"?t3:!!t3,e2=(e2=e2||this.DOM.input).lastChild||e2;var i2=document.getSelection();try{i2.rangeCount>=1&&["Start","End"].forEach(s3=>i2.getRangeAt(0)["set"+s3](e2,t3||e2.length))}catch{}},injectAtCaret(t3,e2){return!(e2=e2||this.state.selection?.range)&&t3?(this.appendMixTags(t3),this):(typeof t3=="string"&&(t3=document.createTextNode(t3)),e2.deleteContents(),e2.insertNode(t3),this.setRangeAtStartEnd(!1,t3),this.updateValueByDOMTags(),this.update(),this)},input:{set(){let t3=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",e2=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];var i2=this.settings.dropdown.closeOnSelect;this.state.inputText=t3,e2&&(this.DOM.input.innerHTML=d(""+t3)),!t3&&i2&&this.dropdown.hide.bind(this),this.input.autocomplete.suggest.call(this),this.input.validate.call(this)},raw(){return this.DOM.input.textContent},validate(){var t3=!this.state.inputText||this.validateTag({value:this.state.inputText})===!0;return this.DOM.input.classList.toggle(this.settings.classNames.inputInvalid,!t3),t3},normalize(t3){var e2=t3||this.DOM.input,i2=[];e2.childNodes.forEach(t4=>t4.nodeType==3&&i2.push(t4.nodeValue)),i2=i2.join(`
`);try{i2=i2.replace(/(?:\r\n|\r|\n)/g,this.settings.delimiters.source.charAt(0))}catch{}return i2=i2.replace(/\s/g," "),this.trim(i2)},autocomplete:{suggest(t3){if(this.settings.autoComplete.enabled){typeof(t3=t3||{})=="string"&&(t3={value:t3});var e2=t3.value?""+t3.value:"",i2=e2.substr(0,this.state.inputText.length).toLowerCase(),s3=e2.substring(this.state.inputText.length);e2&&this.state.inputText&&i2==this.state.inputText.toLowerCase()?(this.DOM.input.setAttribute("data-suggest",s3),this.state.inputSuggestion=t3):(this.DOM.input.removeAttribute("data-suggest"),delete this.state.inputSuggestion)}},set(t3){var e2=this.DOM.input.getAttribute("data-suggest"),i2=t3||(e2?this.state.inputText+e2:null);return!!i2&&(this.settings.mode=="mix"?this.replaceTextWithNode(document.createTextNode(this.state.tag.prefix+i2)):(this.input.set.call(this,i2),this.setRangeAtStartEnd()),this.input.autocomplete.suggest.call(this),this.dropdown.hide(),!0)}}},getTagIdx(t3){return this.value.findIndex(e2=>e2.__tagId==(t3||{}).__tagId)},getNodeIndex(t3){var e2=0;if(t3)for(;t3=t3.previousElementSibling;)e2++;return e2},getTagElms(){for(var t3=arguments.length,e2=new Array(t3),i2=0;i2<t3;i2++)e2[i2]=arguments[i2];var s3="."+[...this.settings.classNames.tag.split(" "),...e2].join(".");return[].slice.call(this.DOM.scope.querySelectorAll(s3))},getLastTag(){var t3=this.DOM.scope.querySelectorAll(`${this.settings.classNames.tagSelector}:not(.${this.settings.classNames.tagHide}):not([readonly])`);return t3[t3.length-1]},tagData:(t3,e2,i2)=>t3?(e2&&(t3.__tagifyTagData=i2?e2:g({},t3.__tagifyTagData||{},e2)),t3.__tagifyTagData):(console.warn("tag element doesn't exist",t3,e2),e2),isTagDuplicate(t3,e2,i2){var a2=0;if(this.settings.mode=="select")return!1;for(let n3 of this.value)s2(this.trim(""+t3),n3.value,e2)&&i2!=n3.__tagId&&a2++;return a2},getTagIndexByValue(t3){var e2=[];return this.getTagElms().forEach((i2,a2)=>{s2(this.trim(i2.textContent),t3,this.settings.dropdown.caseSensitive)&&e2.push(a2)}),e2},getTagElmByValue(t3){var e2=this.getTagIndexByValue(t3)[0];return this.getTagElms()[e2]},flashTag(t3){t3&&(t3.classList.add(this.settings.classNames.tagFlash),setTimeout(()=>{t3.classList.remove(this.settings.classNames.tagFlash)},100))},isTagBlacklisted(t3){return t3=this.trim(t3.toLowerCase()),this.settings.blacklist.filter(e2=>(""+e2).toLowerCase()==t3).length},isTagWhitelisted(t3){return!!this.getWhitelistItem(t3)},getWhitelistItem(t3,e2,i2){e2=e2||"value";var a2,n3=this.settings;return(i2=i2||n3.whitelist).some(i3=>{var o2=typeof i3=="string"?i3:i3[e2]||i3.value;if(s2(o2,t3,n3.dropdown.caseSensitive,n3.trim))return a2=typeof i3=="string"?{value:i3}:i3,!0}),a2||e2!="value"||n3.tagTextProp=="value"||(a2=this.getWhitelistItem(t3,n3.tagTextProp,i2)),a2},validateTag(t3){var e2=this.settings,i2="value"in t3?"value":e2.tagTextProp,s3=this.trim(t3[i2]+"");return(t3[i2]+"").trim()?e2.pattern&&e2.pattern instanceof RegExp&&!e2.pattern.test(s3)?this.TEXTS.pattern:!e2.duplicates&&this.isTagDuplicate(s3,e2.dropdown.caseSensitive,t3.__tagId)?this.TEXTS.duplicate:this.isTagBlacklisted(s3)||e2.enforceWhitelist&&!this.isTagWhitelisted(s3)?this.TEXTS.notAllowed:!e2.validate||e2.validate(t3):this.TEXTS.empty},getInvalidTagAttrs(t3,e2){return{"aria-invalid":!0,class:`${t3.class||""} ${this.settings.classNames.tagNotAllowed}`.trim(),title:e2}},hasMaxTags(){return this.value.length>=this.settings.maxTags&&this.TEXTS.exceed},setReadonly(t3,e2){var i2=this.settings;document.activeElement.blur(),i2[e2||"readonly"]=t3,this.DOM.scope[(t3?"set":"remove")+"Attribute"](e2||"readonly",!0),this.setContentEditable(!t3)},setContentEditable(t3){this.settings.userInput&&(this.DOM.input.contentEditable=t3,this.DOM.input.tabIndex=t3?0:-1)},setDisabled(t3){this.setReadonly(t3,"disabled")},normalizeTags(t3){var e2=this.settings,i2=e2.whitelist,s3=e2.delimiters,a2=e2.mode,n3=e2.tagTextProp;e2.enforceWhitelist;var o2=[],r2=!!i2&&i2[0]instanceof Object,l3=Array.isArray(t3),d2=l3&&t3[0].value,h2=__name2(t4=>(t4+"").split(s3).filter(t5=>t5).map(t5=>({[n3]:this.trim(t5),value:this.trim(t5)})),"h");if(typeof t3=="number"&&(t3=t3.toString()),typeof t3=="string"){if(!t3.trim())return[];t3=h2(t3)}else l3&&(t3=[].concat(...t3.map(t4=>t4.value?t4:h2(t4))));return r2&&!d2&&(t3.forEach(t4=>{var e3=o2.map(t5=>t5.value),i3=this.dropdown.filterListItems.call(this,t4[n3],{exact:!0});this.settings.duplicates||(i3=i3.filter(t5=>!e3.includes(t5.value)));var s4=i3.length>1?this.getWhitelistItem(t4[n3],n3,i3):i3[0];s4&&s4 instanceof Object?o2.push(s4):a2!="mix"&&(t4.value==null&&(t4.value=t4[n3]),o2.push(t4))}),o2.length&&(t3=o2)),t3},parseMixTags(t3){var e2=this.settings,i2=e2.mixTagsInterpolator,s3=e2.duplicates,a2=e2.transformTag,n3=e2.enforceWhitelist,o2=e2.maxTags,r2=e2.tagTextProp,l3=[];return t3=t3.split(i2[0]).map((t4,e3)=>{var d2,h2,g2,p2=t4.split(i2[1]),c2=p2[0],u2=l3.length==o2;try{if(c2==+c2)throw Error;h2=JSON.parse(c2)}catch{h2=this.normalizeTags(c2)[0]||{value:c2}}if(a2.call(this,h2),u2||!(p2.length>1)||n3&&!this.isTagWhitelisted(h2.value)||!s3&&this.isTagDuplicate(h2.value)){if(t4)return e3?i2[0]+t4:t4}else h2[d2=h2[r2]?r2:"value"]=this.trim(h2[d2]),g2=this.createTagElem(h2),l3.push(h2),g2.classList.add(this.settings.classNames.tagNoAnimation),p2[0]=g2.outerHTML,this.value.push(h2);return p2.join("")}).join(""),this.DOM.input.innerHTML=t3,this.DOM.input.appendChild(document.createTextNode("")),this.DOM.input.normalize(),this.getTagElms().forEach((t4,e3)=>this.tagData(t4,l3[e3])),this.update({withoutChangeEvent:!0}),t3},replaceTextWithNode(t3,e2){if(this.state.tag||e2){e2=e2||this.state.tag.prefix+this.state.tag.value;var i2,s3,a2=this.state.selection||window.getSelection(),n3=a2.anchorNode,o2=this.state.tag.delimiters?this.state.tag.delimiters.length:0;return n3.splitText(a2.anchorOffset-o2),(i2=n3.nodeValue.lastIndexOf(e2))==-1||(s3=n3.splitText(i2),t3&&n3.parentNode.replaceChild(t3,s3)),!0}},selectTag(t3,e2){var i2=this.settings;if(!i2.enforceWhitelist||this.isTagWhitelisted(e2.value)){this.input.set.call(this,e2[i2.tagTextProp]||e2.value,!0),this.state.actions.selectOption&&setTimeout(this.setRangeAtStartEnd.bind(this));var s3=this.getLastTag();return s3?this.replaceTag(s3,e2):this.appendTag(t3),this.value[0]=e2,this.update(),this.trigger("add",{tag:t3,data:e2}),[t3]}},addEmptyTag(t3){var e2=g({value:""},t3||{}),i2=this.createTagElem(e2);this.tagData(i2,e2),this.appendTag(i2),this.editTag(i2,{skipValidation:!0})},addTags(t3,e2,i2){var s3=[],a2=this.settings,n3=[],o2=document.createDocumentFragment();if(i2=i2||a2.skipInvalid,!t3||t3.length==0)return s3;switch(t3=this.normalizeTags(t3),a2.mode){case"mix":return this.addMixTags(t3);case"select":e2=!1,this.removeAllTags()}return this.DOM.input.removeAttribute("style"),t3.forEach(t4=>{var e3,r2={},l3=Object.assign({},t4,{value:t4.value+""});if(t4=Object.assign({},l3),a2.transformTag.call(this,t4),t4.__isValid=this.hasMaxTags()||this.validateTag(t4),t4.__isValid!==!0){if(i2)return;if(g(r2,this.getInvalidTagAttrs(t4,t4.__isValid),{__preInvalidData:l3}),t4.__isValid==this.TEXTS.duplicate&&this.flashTag(this.getTagElmByValue(t4.value)),!a2.createInvalidTags)return void n3.push(t4.value)}if("readonly"in t4&&(t4.readonly?r2["aria-readonly"]=!0:delete t4.readonly),e3=this.createTagElem(t4,r2),s3.push(e3),a2.mode=="select")return this.selectTag(e3,t4);o2.appendChild(e3),t4.__isValid&&t4.__isValid===!0?(this.value.push(t4),this.trigger("add",{tag:e3,index:this.value.length-1,data:t4})):(this.trigger("invalid",{data:t4,index:this.value.length,tag:e3,message:t4.__isValid}),a2.keepInvalidTags||setTimeout(()=>this.removeTags(e3,!0),1e3)),this.dropdown.position()}),this.appendTag(o2),this.update(),t3.length&&e2&&(this.input.set.call(this,a2.createInvalidTags?"":n3.join(a2._delimiters)),this.setRangeAtStartEnd()),a2.dropdown.enabled&&this.dropdown.refilter(),s3},addMixTags(t3){if((t3=this.normalizeTags(t3))[0].prefix||this.state.tag)return this.prefixedTextToTag(t3[0]);typeof t3=="string"&&(t3=[{value:t3}]),this.state.selection;var e2=document.createDocumentFragment();return t3.forEach(t4=>{var i2=this.createTagElem(t4);e2.appendChild(i2),this.insertAfterTag(i2)}),this.appendMixTags(e2),e2},appendMixTags(t3){var e2=!!this.state.selection;e2?this.injectAtCaret(t3):(this.DOM.input.focus(),(e2=this.setStateSelection()).range.setStart(this.DOM.input,e2.range.endOffset),e2.range.setEnd(this.DOM.input,e2.range.endOffset),this.DOM.input.appendChild(t3),this.updateValueByDOMTags(),this.update())},prefixedTextToTag(t3){var e2,i2=this.settings,s3=this.state.tag.delimiters;if(i2.transformTag.call(this,t3),t3.prefix=t3.prefix||this.state.tag?this.state.tag.prefix:(i2.pattern.source||i2.pattern)[0],e2=this.createTagElem(t3),this.replaceTextWithNode(e2)||this.DOM.input.appendChild(e2),setTimeout(()=>e2.classList.add(this.settings.classNames.tagNoAnimation),300),this.value.push(t3),this.update(),!s3){var a2=this.insertAfterTag(e2)||e2;this.placeCaretAfterNode(a2)}return this.state.tag=null,this.trigger("add",g({},{tag:e2},{data:t3})),e2},appendTag(t3){var e2=this.DOM,i2=e2.input;i2===e2.input?e2.scope.insertBefore(t3,i2):e2.scope.appendChild(t3)},createTagElem(t3,i2){t3.__tagId=m();var s3,a2=g({},t3,e({value:d(t3.value+"")},i2));return function(t4){for(var e2,i3=document.createNodeIterator(t4,NodeFilter.SHOW_TEXT,null,!1);e2=i3.nextNode();)e2.textContent.trim()||e2.parentNode.removeChild(e2)}(s3=this.parseTemplate("tag",[a2,this])),this.tagData(s3,t3),s3},reCheckInvalidTags(){var t3=this.settings;this.getTagElms(t3.classNames.tagNotAllowed).forEach((e2,i2)=>{var s3=this.tagData(e2),a2=this.hasMaxTags(),n3=this.validateTag(s3),o2=n3===!0&&!a2;if(t3.mode=="select"&&this.toggleScopeValidation(n3),o2)return s3=s3.__preInvalidData?s3.__preInvalidData:{value:s3.value},this.replaceTag(e2,s3);e2.title=a2||n3})},removeTags(t3,e2,i2){var s3,a2=this.settings;if(t3=t3&&t3 instanceof HTMLElement?[t3]:t3 instanceof Array?t3:t3?[t3]:[this.getLastTag()],s3=t3.reduce((t4,e3)=>{e3&&typeof e3=="string"&&(e3=this.getTagElmByValue(e3));var i3=this.tagData(e3);return e3&&i3&&!i3.readonly&&t4.push({node:e3,idx:this.getTagIdx(i3),data:this.tagData(e3,{__removed:!0})}),t4},[]),i2=typeof i2=="number"?i2:this.CSSVars.tagHideTransition,a2.mode=="select"&&(i2=0,this.input.set.call(this)),s3.length==1&&a2.mode!="select"&&s3[0].node.classList.contains(a2.classNames.tagNotAllowed)&&(e2=!0),s3.length)return a2.hooks.beforeRemoveTag(s3,{tagify:this}).then(()=>{function t4(t5){t5.node.parentNode&&(t5.node.parentNode.removeChild(t5.node),e2?a2.keepInvalidTags&&this.trigger("remove",{tag:t5.node,index:t5.idx}):(this.trigger("remove",{tag:t5.node,index:t5.idx,data:t5.data}),this.dropdown.refilter(),this.dropdown.position(),this.DOM.input.normalize(),a2.keepInvalidTags&&this.reCheckInvalidTags()))}__name(t4,"t4"),__name2(t4,"t"),i2&&i2>10&&s3.length==1?function(e3){e3.node.style.width=parseFloat(window.getComputedStyle(e3.node).width)+"px",document.body.clientTop,e3.node.classList.add(a2.classNames.tagHide),setTimeout(t4.bind(this),i2,e3)}.call(this,s3[0]):s3.forEach(t4.bind(this)),e2||(this.removeTagsFromValue(s3.map(t5=>t5.node)),this.update(),a2.mode=="select"&&this.setContentEditable(!0))}).catch(t4=>{})},removeTagsFromDOM(){[].slice.call(this.getTagElms()).forEach(t3=>t3.parentNode.removeChild(t3))},removeTagsFromValue(t3){(t3=Array.isArray(t3)?t3:[t3]).forEach(t4=>{var e2=this.tagData(t4),i2=this.getTagIdx(e2);i2>-1&&this.value.splice(i2,1)})},removeAllTags(t3){t3=t3||{},this.value=[],this.settings.mode=="mix"?this.DOM.input.innerHTML="":this.removeTagsFromDOM(),this.dropdown.refilter(),this.dropdown.position(),this.state.dropdown.visible&&setTimeout(()=>{this.DOM.input.focus()}),this.settings.mode=="select"&&(this.input.set.call(this),this.setContentEditable(!0)),this.update(t3)},postUpdate(){var t3=this.settings,e2=t3.classNames,i2=t3.mode=="mix"?t3.mixMode.integrated?this.DOM.input.textContent:this.DOM.originalInput.value.trim():this.value.length+this.input.raw.call(this).length;this.toggleClass(e2.hasMaxTags,this.value.length>=t3.maxTags),this.toggleClass(e2.hasNoTags,!this.value.length),this.toggleClass(e2.empty,!i2),t3.mode=="select"&&this.toggleScopeValidation(this.value?.[0]?.__isValid)},setOriginalInputValue(t3){var e2=this.DOM.originalInput;this.settings.mixMode.integrated||(e2.value=t3,e2.tagifyValue=e2.value,this.setPersistedData(t3,"value"))},update(t3){var e2=this.getInputValue();this.setOriginalInputValue(e2),this.postUpdate(),this.settings.onChangeAfterBlur&&(t3||{}).withoutChangeEvent||this.state.blockChangeEvent||this.triggerChangeEvent()},getInputValue(){var t3=this.getCleanValue();return this.settings.mode=="mix"?this.getMixedTagsAsString(t3):t3.length?this.settings.originalInputValueFormat?this.settings.originalInputValueFormat(t3):JSON.stringify(t3):""},getCleanValue(t3){return a(t3||this.value,this.dataProps)},getMixedTagsAsString(){var t3="",e2=this,i2=this.settings,s3=i2.originalInputValueFormat||JSON.stringify,a2=i2.mixTagsInterpolator;return __name2(__name(function i3(o2){o2.childNodes.forEach(o3=>{if(o3.nodeType==1){const r2=e2.tagData(o3);if(o3.tagName=="BR"&&(t3+=`\r
`),r2&&v.call(e2,o3)){if(r2.__removed)return;t3+=a2[0]+s3(n2(r2,e2.dataProps))+a2[1]}else o3.getAttribute("style")||["B","I","U"].includes(o3.tagName)?t3+=o3.textContent:o3.tagName!="DIV"&&o3.tagName!="P"||(t3+=`\r
`,i3(o3))}else t3+=o3.textContent})},"i3"),"i")(this.DOM.input),t3}},M.prototype.removeTag=M.prototype.removeTags,M})})(tagify_min);var tagify_minExports=tagify_min.exports;const Tagify=getDefaultExportFromCjs(tagify_minExports),_LuxonError=class extends Error{static{__name(this,"_LuxonError")}};__name2(_LuxonError,"LuxonError");let LuxonError=_LuxonError;const _InvalidDateTimeError=class extends LuxonError{static{__name(this,"_InvalidDateTimeError")}constructor(reason){super(`Invalid DateTime: ${reason.toMessage()}`)}};__name2(_InvalidDateTimeError,"InvalidDateTimeError");let InvalidDateTimeError=_InvalidDateTimeError;const _InvalidIntervalError=class extends LuxonError{static{__name(this,"_InvalidIntervalError")}constructor(reason){super(`Invalid Interval: ${reason.toMessage()}`)}};__name2(_InvalidIntervalError,"InvalidIntervalError");let InvalidIntervalError=_InvalidIntervalError;const _InvalidDurationError=class extends LuxonError{static{__name(this,"_InvalidDurationError")}constructor(reason){super(`Invalid Duration: ${reason.toMessage()}`)}};__name2(_InvalidDurationError,"InvalidDurationError");let InvalidDurationError=_InvalidDurationError;const _ConflictingSpecificationError=class extends LuxonError{static{__name(this,"_ConflictingSpecificationError")}};__name2(_ConflictingSpecificationError,"ConflictingSpecificationError");let ConflictingSpecificationError=_ConflictingSpecificationError;const _InvalidUnitError=class extends LuxonError{static{__name(this,"_InvalidUnitError")}constructor(unit){super(`Invalid unit ${unit}`)}};__name2(_InvalidUnitError,"InvalidUnitError");let InvalidUnitError=_InvalidUnitError;const _InvalidArgumentError=class extends LuxonError{static{__name(this,"_InvalidArgumentError")}};__name2(_InvalidArgumentError,"InvalidArgumentError");let InvalidArgumentError=_InvalidArgumentError;const _ZoneIsAbstractError=class extends LuxonError{static{__name(this,"_ZoneIsAbstractError")}constructor(){super("Zone is an abstract class")}};__name2(_ZoneIsAbstractError,"ZoneIsAbstractError");let ZoneIsAbstractError=_ZoneIsAbstractError;const n="numeric",s="short",l="long",DATE_SHORT={year:n,month:n,day:n},DATE_MED={year:n,month:s,day:n},DATE_MED_WITH_WEEKDAY={year:n,month:s,day:n,weekday:s},DATE_FULL={year:n,month:l,day:n},DATE_HUGE={year:n,month:l,day:n,weekday:l},TIME_SIMPLE={hour:n,minute:n},TIME_WITH_SECONDS={hour:n,minute:n,second:n},TIME_WITH_SHORT_OFFSET={hour:n,minute:n,second:n,timeZoneName:s},TIME_WITH_LONG_OFFSET={hour:n,minute:n,second:n,timeZoneName:l},TIME_24_SIMPLE={hour:n,minute:n,hourCycle:"h23"},TIME_24_WITH_SECONDS={hour:n,minute:n,second:n,hourCycle:"h23"},TIME_24_WITH_SHORT_OFFSET={hour:n,minute:n,second:n,hourCycle:"h23",timeZoneName:s},TIME_24_WITH_LONG_OFFSET={hour:n,minute:n,second:n,hourCycle:"h23",timeZoneName:l},DATETIME_SHORT={year:n,month:n,day:n,hour:n,minute:n},DATETIME_SHORT_WITH_SECONDS={year:n,month:n,day:n,hour:n,minute:n,second:n},DATETIME_MED={year:n,month:s,day:n,hour:n,minute:n},DATETIME_MED_WITH_SECONDS={year:n,month:s,day:n,hour:n,minute:n,second:n},DATETIME_MED_WITH_WEEKDAY={year:n,month:s,day:n,weekday:s,hour:n,minute:n},DATETIME_FULL={year:n,month:l,day:n,hour:n,minute:n,timeZoneName:s},DATETIME_FULL_WITH_SECONDS={year:n,month:l,day:n,hour:n,minute:n,second:n,timeZoneName:s},DATETIME_HUGE={year:n,month:l,day:n,weekday:l,hour:n,minute:n,timeZoneName:l},DATETIME_HUGE_WITH_SECONDS={year:n,month:l,day:n,weekday:l,hour:n,minute:n,second:n,timeZoneName:l},_Zone=class{static{__name(this,"_Zone")}get type(){throw new ZoneIsAbstractError}get name(){throw new ZoneIsAbstractError}get ianaName(){return this.name}get isUniversal(){throw new ZoneIsAbstractError}offsetName(ts,opts){throw new ZoneIsAbstractError}formatOffset(ts,format){throw new ZoneIsAbstractError}offset(ts){throw new ZoneIsAbstractError}equals(otherZone){throw new ZoneIsAbstractError}get isValid(){throw new ZoneIsAbstractError}};__name2(_Zone,"Zone");let Zone=_Zone,singleton$1=null;const _SystemZone=class _SystemZone2 extends Zone{static{__name(this,"_SystemZone")}static get instance(){return singleton$1===null&&(singleton$1=new _SystemZone2),singleton$1}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(ts,{format,locale}){return parseZoneInfo(ts,format,locale)}formatOffset(ts,format){return formatOffset(this.offset(ts),format)}offset(ts){return-new Date(ts).getTimezoneOffset()}equals(otherZone){return otherZone.type==="system"}get isValid(){return!0}};__name2(_SystemZone,"SystemZone");let SystemZone=_SystemZone,dtfCache={};function makeDTF(zone){return dtfCache[zone]||(dtfCache[zone]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:zone,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),dtfCache[zone]}__name(makeDTF,"makeDTF"),__name2(makeDTF,"makeDTF");const typeToPos={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function hackyOffset(dtf,date){const formatted=dtf.format(date).replace(/\u200E/g,""),parsed=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted),[,fMonth,fDay,fYear,fadOrBc,fHour,fMinute,fSecond]=parsed;return[fYear,fMonth,fDay,fadOrBc,fHour,fMinute,fSecond]}__name(hackyOffset,"hackyOffset"),__name2(hackyOffset,"hackyOffset");function partsOffset(dtf,date){const formatted=dtf.formatToParts(date),filled=[];for(let i=0;i<formatted.length;i++){const{type,value}=formatted[i],pos=typeToPos[type];type==="era"?filled[pos]=value:isUndefined(pos)||(filled[pos]=parseInt(value,10))}return filled}__name(partsOffset,"partsOffset"),__name2(partsOffset,"partsOffset");let ianaZoneCache={};const _IANAZone=class _IANAZone2 extends Zone{static{__name(this,"_IANAZone")}static create(name2){return ianaZoneCache[name2]||(ianaZoneCache[name2]=new _IANAZone2(name2)),ianaZoneCache[name2]}static resetCache(){ianaZoneCache={},dtfCache={}}static isValidSpecifier(s2){return this.isValidZone(s2)}static isValidZone(zone){if(!zone)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:zone}).format(),!0}catch{return!1}}constructor(name2){super(),this.zoneName=name2,this.valid=_IANAZone2.isValidZone(name2)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(ts,{format,locale}){return parseZoneInfo(ts,format,locale,this.name)}formatOffset(ts,format){return formatOffset(this.offset(ts),format)}offset(ts){const date=new Date(ts);if(isNaN(date))return NaN;const dtf=makeDTF(this.name);let[year,month,day,adOrBc,hour,minute,second]=dtf.formatToParts?partsOffset(dtf,date):hackyOffset(dtf,date);adOrBc==="BC"&&(year=-Math.abs(year)+1);const asUTC=objToLocalTS({year,month,day,hour:hour===24?0:hour,minute,second,millisecond:0});let asTS=+date;const over=asTS%1e3;return asTS-=over>=0?over:1e3+over,(asUTC-asTS)/(60*1e3)}equals(otherZone){return otherZone.type==="iana"&&otherZone.name===this.name}get isValid(){return this.valid}};__name2(_IANAZone,"IANAZone");let IANAZone=_IANAZone,intlLFCache={};function getCachedLF(locString,opts={}){const key=JSON.stringify([locString,opts]);let dtf=intlLFCache[key];return dtf||(dtf=new Intl.ListFormat(locString,opts),intlLFCache[key]=dtf),dtf}__name(getCachedLF,"getCachedLF"),__name2(getCachedLF,"getCachedLF");let intlDTCache={};function getCachedDTF(locString,opts={}){const key=JSON.stringify([locString,opts]);let dtf=intlDTCache[key];return dtf||(dtf=new Intl.DateTimeFormat(locString,opts),intlDTCache[key]=dtf),dtf}__name(getCachedDTF,"getCachedDTF"),__name2(getCachedDTF,"getCachedDTF");let intlNumCache={};function getCachedINF(locString,opts={}){const key=JSON.stringify([locString,opts]);let inf=intlNumCache[key];return inf||(inf=new Intl.NumberFormat(locString,opts),intlNumCache[key]=inf),inf}__name(getCachedINF,"getCachedINF"),__name2(getCachedINF,"getCachedINF");let intlRelCache={};function getCachedRTF(locString,opts={}){const{base:base2,...cacheKeyOpts}=opts,key=JSON.stringify([locString,cacheKeyOpts]);let inf=intlRelCache[key];return inf||(inf=new Intl.RelativeTimeFormat(locString,opts),intlRelCache[key]=inf),inf}__name(getCachedRTF,"getCachedRTF"),__name2(getCachedRTF,"getCachedRTF");let sysLocaleCache=null;function systemLocale(){return sysLocaleCache||(sysLocaleCache=new Intl.DateTimeFormat().resolvedOptions().locale,sysLocaleCache)}__name(systemLocale,"systemLocale"),__name2(systemLocale,"systemLocale");function parseLocaleString(localeStr){const xIndex=localeStr.indexOf("-x-");xIndex!==-1&&(localeStr=localeStr.substring(0,xIndex));const uIndex=localeStr.indexOf("-u-");if(uIndex===-1)return[localeStr];{let options,selectedStr;try{options=getCachedDTF(localeStr).resolvedOptions(),selectedStr=localeStr}catch{const smaller=localeStr.substring(0,uIndex);options=getCachedDTF(smaller).resolvedOptions(),selectedStr=smaller}const{numberingSystem,calendar}=options;return[selectedStr,numberingSystem,calendar]}}__name(parseLocaleString,"parseLocaleString"),__name2(parseLocaleString,"parseLocaleString");function intlConfigString(localeStr,numberingSystem,outputCalendar){return(outputCalendar||numberingSystem)&&(localeStr.includes("-u-")||(localeStr+="-u"),outputCalendar&&(localeStr+=`-ca-${outputCalendar}`),numberingSystem&&(localeStr+=`-nu-${numberingSystem}`)),localeStr}__name(intlConfigString,"intlConfigString"),__name2(intlConfigString,"intlConfigString");function mapMonths(f2){const ms=[];for(let i=1;i<=12;i++){const dt=DateTime.utc(2009,i,1);ms.push(f2(dt))}return ms}__name(mapMonths,"mapMonths"),__name2(mapMonths,"mapMonths");function mapWeekdays(f2){const ms=[];for(let i=1;i<=7;i++){const dt=DateTime.utc(2016,11,13+i);ms.push(f2(dt))}return ms}__name(mapWeekdays,"mapWeekdays"),__name2(mapWeekdays,"mapWeekdays");function listStuff(loc,length,englishFn,intlFn){const mode=loc.listingMode();return mode==="error"?null:mode==="en"?englishFn(length):intlFn(length)}__name(listStuff,"listStuff"),__name2(listStuff,"listStuff");function supportsFastNumbers(loc){return loc.numberingSystem&&loc.numberingSystem!=="latn"?!1:loc.numberingSystem==="latn"||!loc.locale||loc.locale.startsWith("en")||new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem==="latn"}__name(supportsFastNumbers,"supportsFastNumbers"),__name2(supportsFastNumbers,"supportsFastNumbers");const _PolyNumberFormatter=class{static{__name(this,"_PolyNumberFormatter")}constructor(intl,forceSimple,opts){this.padTo=opts.padTo||0,this.floor=opts.floor||!1;const{padTo,floor,...otherOpts}=opts;if(!forceSimple||Object.keys(otherOpts).length>0){const intlOpts={useGrouping:!1,...opts};opts.padTo>0&&(intlOpts.minimumIntegerDigits=opts.padTo),this.inf=getCachedINF(intl,intlOpts)}}format(i){if(this.inf){const fixed=this.floor?Math.floor(i):i;return this.inf.format(fixed)}else{const fixed=this.floor?Math.floor(i):roundTo(i,3);return padStart(fixed,this.padTo)}}};__name2(_PolyNumberFormatter,"PolyNumberFormatter");let PolyNumberFormatter=_PolyNumberFormatter;const _PolyDateFormatter=class{static{__name(this,"_PolyDateFormatter")}constructor(dt,intl,opts){this.opts=opts,this.originalZone=void 0;let z;if(this.opts.timeZone)this.dt=dt;else if(dt.zone.type==="fixed"){const gmtOffset=-1*(dt.offset/60),offsetZ=gmtOffset>=0?`Etc/GMT+${gmtOffset}`:`Etc/GMT${gmtOffset}`;dt.offset!==0&&IANAZone.create(offsetZ).valid?(z=offsetZ,this.dt=dt):(z="UTC",this.dt=dt.offset===0?dt:dt.setZone("UTC").plus({minutes:dt.offset}),this.originalZone=dt.zone)}else dt.zone.type==="system"?this.dt=dt:dt.zone.type==="iana"?(this.dt=dt,z=dt.zone.name):(z="UTC",this.dt=dt.setZone("UTC").plus({minutes:dt.offset}),this.originalZone=dt.zone);const intlOpts={...this.opts};intlOpts.timeZone=intlOpts.timeZone||z,this.dtf=getCachedDTF(intl,intlOpts)}format(){return this.originalZone?this.formatToParts().map(({value})=>value).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const parts=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?parts.map(part=>{if(part.type==="timeZoneName"){const offsetName=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...part,value:offsetName}}else return part}):parts}resolvedOptions(){return this.dtf.resolvedOptions()}};__name2(_PolyDateFormatter,"PolyDateFormatter");let PolyDateFormatter=_PolyDateFormatter;const _PolyRelFormatter=class{static{__name(this,"_PolyRelFormatter")}constructor(intl,isEnglish,opts){this.opts={style:"long",...opts},!isEnglish&&hasRelative()&&(this.rtf=getCachedRTF(intl,opts))}format(count,unit){return this.rtf?this.rtf.format(count,unit):formatRelativeTime(unit,count,this.opts.numeric,this.opts.style!=="long")}formatToParts(count,unit){return this.rtf?this.rtf.formatToParts(count,unit):[]}};__name2(_PolyRelFormatter,"PolyRelFormatter");let PolyRelFormatter=_PolyRelFormatter;const _Locale=class _Locale2{static{__name(this,"_Locale")}static fromOpts(opts){return _Locale2.create(opts.locale,opts.numberingSystem,opts.outputCalendar,opts.defaultToEN)}static create(locale,numberingSystem,outputCalendar,defaultToEN=!1){const specifiedLocale=locale||Settings.defaultLocale,localeR=specifiedLocale||(defaultToEN?"en-US":systemLocale()),numberingSystemR=numberingSystem||Settings.defaultNumberingSystem,outputCalendarR=outputCalendar||Settings.defaultOutputCalendar;return new _Locale2(localeR,numberingSystemR,outputCalendarR,specifiedLocale)}static resetCache(){sysLocaleCache=null,intlDTCache={},intlNumCache={},intlRelCache={}}static fromObject({locale,numberingSystem,outputCalendar}={}){return _Locale2.create(locale,numberingSystem,outputCalendar)}constructor(locale,numbering,outputCalendar,specifiedLocale){const[parsedLocale,parsedNumberingSystem,parsedOutputCalendar]=parseLocaleString(locale);this.locale=parsedLocale,this.numberingSystem=numbering||parsedNumberingSystem||null,this.outputCalendar=outputCalendar||parsedOutputCalendar||null,this.intl=intlConfigString(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=specifiedLocale,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=supportsFastNumbers(this)),this.fastNumbersCached}listingMode(){const isActuallyEn=this.isEnglish(),hasNoWeirdness=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return isActuallyEn&&hasNoWeirdness?"en":"intl"}clone(alts){return!alts||Object.getOwnPropertyNames(alts).length===0?this:_Locale2.create(alts.locale||this.specifiedLocale,alts.numberingSystem||this.numberingSystem,alts.outputCalendar||this.outputCalendar,alts.defaultToEN||!1)}redefaultToEN(alts={}){return this.clone({...alts,defaultToEN:!0})}redefaultToSystem(alts={}){return this.clone({...alts,defaultToEN:!1})}months(length,format=!1){return listStuff(this,length,months,()=>{const intl=format?{month:length,day:"numeric"}:{month:length},formatStr=format?"format":"standalone";return this.monthsCache[formatStr][length]||(this.monthsCache[formatStr][length]=mapMonths(dt=>this.extract(dt,intl,"month"))),this.monthsCache[formatStr][length]})}weekdays(length,format=!1){return listStuff(this,length,weekdays,()=>{const intl=format?{weekday:length,year:"numeric",month:"long",day:"numeric"}:{weekday:length},formatStr=format?"format":"standalone";return this.weekdaysCache[formatStr][length]||(this.weekdaysCache[formatStr][length]=mapWeekdays(dt=>this.extract(dt,intl,"weekday"))),this.weekdaysCache[formatStr][length]})}meridiems(){return listStuff(this,void 0,()=>meridiems,()=>{if(!this.meridiemCache){const intl={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[DateTime.utc(2016,11,13,9),DateTime.utc(2016,11,13,19)].map(dt=>this.extract(dt,intl,"dayperiod"))}return this.meridiemCache})}eras(length){return listStuff(this,length,eras,()=>{const intl={era:length};return this.eraCache[length]||(this.eraCache[length]=[DateTime.utc(-40,1,1),DateTime.utc(2017,1,1)].map(dt=>this.extract(dt,intl,"era"))),this.eraCache[length]})}extract(dt,intlOpts,field){const df=this.dtFormatter(dt,intlOpts),results=df.formatToParts(),matching=results.find(m=>m.type.toLowerCase()===field);return matching?matching.value:null}numberFormatter(opts={}){return new PolyNumberFormatter(this.intl,opts.forceSimple||this.fastNumbers,opts)}dtFormatter(dt,intlOpts={}){return new PolyDateFormatter(dt,this.intl,intlOpts)}relFormatter(opts={}){return new PolyRelFormatter(this.intl,this.isEnglish(),opts)}listFormatter(opts={}){return getCachedLF(this.intl,opts)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(other){return this.locale===other.locale&&this.numberingSystem===other.numberingSystem&&this.outputCalendar===other.outputCalendar}};__name2(_Locale,"Locale");let Locale=_Locale,singleton=null;const _FixedOffsetZone=class _FixedOffsetZone2 extends Zone{static{__name(this,"_FixedOffsetZone")}static get utcInstance(){return singleton===null&&(singleton=new _FixedOffsetZone2(0)),singleton}static instance(offset2){return offset2===0?_FixedOffsetZone2.utcInstance:new _FixedOffsetZone2(offset2)}static parseSpecifier(s2){if(s2){const r=s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new _FixedOffsetZone2(signedOffset(r[1],r[2]))}return null}constructor(offset2){super(),this.fixed=offset2}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${formatOffset(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${formatOffset(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(ts,format){return formatOffset(this.fixed,format)}get isUniversal(){return!0}offset(){return this.fixed}equals(otherZone){return otherZone.type==="fixed"&&otherZone.fixed===this.fixed}get isValid(){return!0}};__name2(_FixedOffsetZone,"FixedOffsetZone");let FixedOffsetZone=_FixedOffsetZone;const _InvalidZone=class extends Zone{static{__name(this,"_InvalidZone")}constructor(zoneName){super(),this.zoneName=zoneName}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};__name2(_InvalidZone,"InvalidZone");let InvalidZone=_InvalidZone;function normalizeZone(input,defaultZone2){if(isUndefined(input)||input===null)return defaultZone2;if(input instanceof Zone)return input;if(isString(input)){const lowered=input.toLowerCase();return lowered==="default"?defaultZone2:lowered==="local"||lowered==="system"?SystemZone.instance:lowered==="utc"||lowered==="gmt"?FixedOffsetZone.utcInstance:FixedOffsetZone.parseSpecifier(lowered)||IANAZone.create(input)}else return isNumber(input)?FixedOffsetZone.instance(input):typeof input=="object"&&"offset"in input&&typeof input.offset=="function"?input:new InvalidZone(input)}__name(normalizeZone,"normalizeZone"),__name2(normalizeZone,"normalizeZone");let now=__name2(()=>Date.now(),"now"),defaultZone="system",defaultLocale=null,defaultNumberingSystem=null,defaultOutputCalendar=null,twoDigitCutoffYear=60,throwOnInvalid;const _Settings=class{static{__name(this,"_Settings")}static get now(){return now}static set now(n2){now=n2}static set defaultZone(zone){defaultZone=zone}static get defaultZone(){return normalizeZone(defaultZone,SystemZone.instance)}static get defaultLocale(){return defaultLocale}static set defaultLocale(locale){defaultLocale=locale}static get defaultNumberingSystem(){return defaultNumberingSystem}static set defaultNumberingSystem(numberingSystem){defaultNumberingSystem=numberingSystem}static get defaultOutputCalendar(){return defaultOutputCalendar}static set defaultOutputCalendar(outputCalendar){defaultOutputCalendar=outputCalendar}static get twoDigitCutoffYear(){return twoDigitCutoffYear}static set twoDigitCutoffYear(cutoffYear){twoDigitCutoffYear=cutoffYear%100}static get throwOnInvalid(){return throwOnInvalid}static set throwOnInvalid(t2){throwOnInvalid=t2}static resetCaches(){Locale.resetCache(),IANAZone.resetCache()}};__name2(_Settings,"Settings");let Settings=_Settings;function isUndefined(o){return typeof o>"u"}__name(isUndefined,"isUndefined"),__name2(isUndefined,"isUndefined");function isNumber(o){return typeof o=="number"}__name(isNumber,"isNumber"),__name2(isNumber,"isNumber");function isInteger(o){return typeof o=="number"&&o%1===0}__name(isInteger,"isInteger"),__name2(isInteger,"isInteger");function isString(o){return typeof o=="string"}__name(isString,"isString"),__name2(isString,"isString");function isDate(o){return Object.prototype.toString.call(o)==="[object Date]"}__name(isDate,"isDate"),__name2(isDate,"isDate");function hasRelative(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}__name(hasRelative,"hasRelative"),__name2(hasRelative,"hasRelative");function maybeArray(thing){return Array.isArray(thing)?thing:[thing]}__name(maybeArray,"maybeArray"),__name2(maybeArray,"maybeArray");function bestBy(arr,by,compare2){if(arr.length!==0)return arr.reduce((best,next)=>{const pair2=[by(next),next];return best&&compare2(best[0],pair2[0])===best[0]?best:pair2},null)[1]}__name(bestBy,"bestBy"),__name2(bestBy,"bestBy");function pick(obj,keys2){return keys2.reduce((a,k)=>(a[k]=obj[k],a),{})}__name(pick,"pick"),__name2(pick,"pick");function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}__name(hasOwnProperty,"hasOwnProperty"),__name2(hasOwnProperty,"hasOwnProperty");function integerBetween(thing,bottom,top2){return isInteger(thing)&&thing>=bottom&&thing<=top2}__name(integerBetween,"integerBetween"),__name2(integerBetween,"integerBetween");function floorMod(x,n2){return x-n2*Math.floor(x/n2)}__name(floorMod,"floorMod"),__name2(floorMod,"floorMod");function padStart(input,n2=2){const isNeg=input<0;let padded;return isNeg?padded="-"+(""+-input).padStart(n2,"0"):padded=(""+input).padStart(n2,"0"),padded}__name(padStart,"padStart"),__name2(padStart,"padStart");function parseInteger(string2){if(!(isUndefined(string2)||string2===null||string2===""))return parseInt(string2,10)}__name(parseInteger,"parseInteger"),__name2(parseInteger,"parseInteger");function parseFloating(string2){if(!(isUndefined(string2)||string2===null||string2===""))return parseFloat(string2)}__name(parseFloating,"parseFloating"),__name2(parseFloating,"parseFloating");function parseMillis(fraction){if(!(isUndefined(fraction)||fraction===null||fraction==="")){const f2=parseFloat("0."+fraction)*1e3;return Math.floor(f2)}}__name(parseMillis,"parseMillis"),__name2(parseMillis,"parseMillis");function roundTo(number2,digits,towardZero=!1){const factor=10**digits;return(towardZero?Math.trunc:Math.round)(number2*factor)/factor}__name(roundTo,"roundTo"),__name2(roundTo,"roundTo");function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}__name(isLeapYear,"isLeapYear"),__name2(isLeapYear,"isLeapYear");function daysInYear(year){return isLeapYear(year)?366:365}__name(daysInYear,"daysInYear"),__name2(daysInYear,"daysInYear");function daysInMonth(year,month){const modMonth=floorMod(month-1,12)+1,modYear=year+(month-modMonth)/12;return modMonth===2?isLeapYear(modYear)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][modMonth-1]}__name(daysInMonth,"daysInMonth"),__name2(daysInMonth,"daysInMonth");function objToLocalTS(obj){let d=Date.UTC(obj.year,obj.month-1,obj.day,obj.hour,obj.minute,obj.second,obj.millisecond);return obj.year<100&&obj.year>=0&&(d=new Date(d),d.setUTCFullYear(obj.year,obj.month-1,obj.day)),+d}__name(objToLocalTS,"objToLocalTS"),__name2(objToLocalTS,"objToLocalTS");function weeksInWeekYear(weekYear){const p1=(weekYear+Math.floor(weekYear/4)-Math.floor(weekYear/100)+Math.floor(weekYear/400))%7,last2=weekYear-1,p2=(last2+Math.floor(last2/4)-Math.floor(last2/100)+Math.floor(last2/400))%7;return p1===4||p2===3?53:52}__name(weeksInWeekYear,"weeksInWeekYear"),__name2(weeksInWeekYear,"weeksInWeekYear");function untruncateYear(year){return year>99?year:year>Settings.twoDigitCutoffYear?1900+year:2e3+year}__name(untruncateYear,"untruncateYear"),__name2(untruncateYear,"untruncateYear");function parseZoneInfo(ts,offsetFormat,locale,timeZone=null){const date=new Date(ts),intlOpts={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};timeZone&&(intlOpts.timeZone=timeZone);const modified={timeZoneName:offsetFormat,...intlOpts},parsed=new Intl.DateTimeFormat(locale,modified).formatToParts(date).find(m=>m.type.toLowerCase()==="timezonename");return parsed?parsed.value:null}__name(parseZoneInfo,"parseZoneInfo"),__name2(parseZoneInfo,"parseZoneInfo");function signedOffset(offHourStr,offMinuteStr){let offHour=parseInt(offHourStr,10);Number.isNaN(offHour)&&(offHour=0);const offMin=parseInt(offMinuteStr,10)||0,offMinSigned=offHour<0||Object.is(offHour,-0)?-offMin:offMin;return offHour*60+offMinSigned}__name(signedOffset,"signedOffset"),__name2(signedOffset,"signedOffset");function asNumber(value){const numericValue=Number(value);if(typeof value=="boolean"||value===""||Number.isNaN(numericValue))throw new InvalidArgumentError(`Invalid unit value ${value}`);return numericValue}__name(asNumber,"asNumber"),__name2(asNumber,"asNumber");function normalizeObject(obj,normalizer){const normalized={};for(const u in obj)if(hasOwnProperty(obj,u)){const v=obj[u];if(v==null)continue;normalized[normalizer(u)]=asNumber(v)}return normalized}__name(normalizeObject,"normalizeObject"),__name2(normalizeObject,"normalizeObject");function formatOffset(offset2,format){const hours=Math.trunc(Math.abs(offset2/60)),minutes=Math.trunc(Math.abs(offset2%60)),sign=offset2>=0?"+":"-";switch(format){case"short":return`${sign}${padStart(hours,2)}:${padStart(minutes,2)}`;case"narrow":return`${sign}${hours}${minutes>0?`:${minutes}`:""}`;case"techie":return`${sign}${padStart(hours,2)}${padStart(minutes,2)}`;default:throw new RangeError(`Value format ${format} is out of range for property format`)}}__name(formatOffset,"formatOffset"),__name2(formatOffset,"formatOffset");function timeObject(obj){return pick(obj,["hour","minute","second","millisecond"])}__name(timeObject,"timeObject"),__name2(timeObject,"timeObject");const monthsLong=["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],monthsNarrow=["J","F","M","A","M","J","J","A","S","O","N","D"];function months(length){switch(length){case"narrow":return[...monthsNarrow];case"short":return[...monthsShort];case"long":return[...monthsLong];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}__name(months,"months"),__name2(months,"months");const weekdaysLong=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],weekdaysShort=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],weekdaysNarrow=["M","T","W","T","F","S","S"];function weekdays(length){switch(length){case"narrow":return[...weekdaysNarrow];case"short":return[...weekdaysShort];case"long":return[...weekdaysLong];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}__name(weekdays,"weekdays"),__name2(weekdays,"weekdays");const meridiems=["AM","PM"],erasLong=["Before Christ","Anno Domini"],erasShort=["BC","AD"],erasNarrow=["B","A"];function eras(length){switch(length){case"narrow":return[...erasNarrow];case"short":return[...erasShort];case"long":return[...erasLong];default:return null}}__name(eras,"eras"),__name2(eras,"eras");function meridiemForDateTime(dt){return meridiems[dt.hour<12?0:1]}__name(meridiemForDateTime,"meridiemForDateTime"),__name2(meridiemForDateTime,"meridiemForDateTime");function weekdayForDateTime(dt,length){return weekdays(length)[dt.weekday-1]}__name(weekdayForDateTime,"weekdayForDateTime"),__name2(weekdayForDateTime,"weekdayForDateTime");function monthForDateTime(dt,length){return months(length)[dt.month-1]}__name(monthForDateTime,"monthForDateTime"),__name2(monthForDateTime,"monthForDateTime");function eraForDateTime(dt,length){return eras(length)[dt.year<0?0:1]}__name(eraForDateTime,"eraForDateTime"),__name2(eraForDateTime,"eraForDateTime");function formatRelativeTime(unit,count,numeric="always",narrow=!1){const units={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},lastable=["hours","minutes","seconds"].indexOf(unit)===-1;if(numeric==="auto"&&lastable){const isDay=unit==="days";switch(count){case 1:return isDay?"tomorrow":`next ${units[unit][0]}`;case-1:return isDay?"yesterday":`last ${units[unit][0]}`;case 0:return isDay?"today":`this ${units[unit][0]}`}}const isInPast=Object.is(count,-0)||count<0,fmtValue=Math.abs(count),singular=fmtValue===1,lilUnits=units[unit],fmtUnit=narrow?singular?lilUnits[1]:lilUnits[2]||lilUnits[1]:singular?units[unit][0]:unit;return isInPast?`${fmtValue} ${fmtUnit} ago`:`in ${fmtValue} ${fmtUnit}`}__name(formatRelativeTime,"formatRelativeTime"),__name2(formatRelativeTime,"formatRelativeTime");function stringifyTokens(splits,tokenToString){let s2="";for(const token of splits)token.literal?s2+=token.val:s2+=tokenToString(token.val);return s2}__name(stringifyTokens,"stringifyTokens"),__name2(stringifyTokens,"stringifyTokens");const macroTokenToFormatOpts={D:DATE_SHORT,DD:DATE_MED,DDD:DATE_FULL,DDDD:DATE_HUGE,t:TIME_SIMPLE,tt:TIME_WITH_SECONDS,ttt:TIME_WITH_SHORT_OFFSET,tttt:TIME_WITH_LONG_OFFSET,T:TIME_24_SIMPLE,TT:TIME_24_WITH_SECONDS,TTT:TIME_24_WITH_SHORT_OFFSET,TTTT:TIME_24_WITH_LONG_OFFSET,f:DATETIME_SHORT,ff:DATETIME_MED,fff:DATETIME_FULL,ffff:DATETIME_HUGE,F:DATETIME_SHORT_WITH_SECONDS,FF:DATETIME_MED_WITH_SECONDS,FFF:DATETIME_FULL_WITH_SECONDS,FFFF:DATETIME_HUGE_WITH_SECONDS},_Formatter=class _Formatter2{static{__name(this,"_Formatter")}static create(locale,opts={}){return new _Formatter2(locale,opts)}static parseFormat(fmt){let current=null,currentFull="",bracketed=!1;const splits=[];for(let i=0;i<fmt.length;i++){const c=fmt.charAt(i);c==="'"?(currentFull.length>0&&splits.push({literal:bracketed||/^\s+$/.test(currentFull),val:currentFull}),current=null,currentFull="",bracketed=!bracketed):bracketed||c===current?currentFull+=c:(currentFull.length>0&&splits.push({literal:/^\s+$/.test(currentFull),val:currentFull}),currentFull=c,current=c)}return currentFull.length>0&&splits.push({literal:bracketed||/^\s+$/.test(currentFull),val:currentFull}),splits}static macroTokenToFormatOpts(token){return macroTokenToFormatOpts[token]}constructor(locale,formatOpts){this.opts=formatOpts,this.loc=locale,this.systemLoc=null}formatWithSystemDefault(dt,opts){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(dt,{...this.opts,...opts}).format()}dtFormatter(dt,opts={}){return this.loc.dtFormatter(dt,{...this.opts,...opts})}formatDateTime(dt,opts){return this.dtFormatter(dt,opts).format()}formatDateTimeParts(dt,opts){return this.dtFormatter(dt,opts).formatToParts()}formatInterval(interval,opts){return this.dtFormatter(interval.start,opts).dtf.formatRange(interval.start.toJSDate(),interval.end.toJSDate())}resolvedOptions(dt,opts){return this.dtFormatter(dt,opts).resolvedOptions()}num(n2,p=0){if(this.opts.forceSimple)return padStart(n2,p);const opts={...this.opts};return p>0&&(opts.padTo=p),this.loc.numberFormatter(opts).format(n2)}formatDateTimeFromString(dt,fmt){const knownEnglish=this.loc.listingMode()==="en",useDateTimeFormatter=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",string2=__name2((opts,extract)=>this.loc.extract(dt,opts,extract),"string"),formatOffset2=__name2(opts=>dt.isOffsetFixed&&dt.offset===0&&opts.allowZ?"Z":dt.isValid?dt.zone.formatOffset(dt.ts,opts.format):"","formatOffset"),meridiem=__name2(()=>knownEnglish?meridiemForDateTime(dt):string2({hour:"numeric",hourCycle:"h12"},"dayperiod"),"meridiem"),month=__name2((length,standalone)=>knownEnglish?monthForDateTime(dt,length):string2(standalone?{month:length}:{month:length,day:"numeric"},"month"),"month"),weekday=__name2((length,standalone)=>knownEnglish?weekdayForDateTime(dt,length):string2(standalone?{weekday:length}:{weekday:length,month:"long",day:"numeric"},"weekday"),"weekday"),maybeMacro=__name2(token=>{const formatOpts=_Formatter2.macroTokenToFormatOpts(token);return formatOpts?this.formatWithSystemDefault(dt,formatOpts):token},"maybeMacro"),era=__name2(length=>knownEnglish?eraForDateTime(dt,length):string2({era:length},"era"),"era"),tokenToString=__name2(token=>{switch(token){case"S":return this.num(dt.millisecond);case"u":case"SSS":return this.num(dt.millisecond,3);case"s":return this.num(dt.second);case"ss":return this.num(dt.second,2);case"uu":return this.num(Math.floor(dt.millisecond/10),2);case"uuu":return this.num(Math.floor(dt.millisecond/100));case"m":return this.num(dt.minute);case"mm":return this.num(dt.minute,2);case"h":return this.num(dt.hour%12===0?12:dt.hour%12);case"hh":return this.num(dt.hour%12===0?12:dt.hour%12,2);case"H":return this.num(dt.hour);case"HH":return this.num(dt.hour,2);case"Z":return formatOffset2({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return formatOffset2({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return formatOffset2({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return dt.zone.offsetName(dt.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return dt.zone.offsetName(dt.ts,{format:"long",locale:this.loc.locale});case"z":return dt.zoneName;case"a":return meridiem();case"d":return useDateTimeFormatter?string2({day:"numeric"},"day"):this.num(dt.day);case"dd":return useDateTimeFormatter?string2({day:"2-digit"},"day"):this.num(dt.day,2);case"c":return this.num(dt.weekday);case"ccc":return weekday("short",!0);case"cccc":return weekday("long",!0);case"ccccc":return weekday("narrow",!0);case"E":return this.num(dt.weekday);case"EEE":return weekday("short",!1);case"EEEE":return weekday("long",!1);case"EEEEE":return weekday("narrow",!1);case"L":return useDateTimeFormatter?string2({month:"numeric",day:"numeric"},"month"):this.num(dt.month);case"LL":return useDateTimeFormatter?string2({month:"2-digit",day:"numeric"},"month"):this.num(dt.month,2);case"LLL":return month("short",!0);case"LLLL":return month("long",!0);case"LLLLL":return month("narrow",!0);case"M":return useDateTimeFormatter?string2({month:"numeric"},"month"):this.num(dt.month);case"MM":return useDateTimeFormatter?string2({month:"2-digit"},"month"):this.num(dt.month,2);case"MMM":return month("short",!1);case"MMMM":return month("long",!1);case"MMMMM":return month("narrow",!1);case"y":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year);case"yy":return useDateTimeFormatter?string2({year:"2-digit"},"year"):this.num(dt.year.toString().slice(-2),2);case"yyyy":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year,4);case"yyyyyy":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year,6);case"G":return era("short");case"GG":return era("long");case"GGGGG":return era("narrow");case"kk":return this.num(dt.weekYear.toString().slice(-2),2);case"kkkk":return this.num(dt.weekYear,4);case"W":return this.num(dt.weekNumber);case"WW":return this.num(dt.weekNumber,2);case"o":return this.num(dt.ordinal);case"ooo":return this.num(dt.ordinal,3);case"q":return this.num(dt.quarter);case"qq":return this.num(dt.quarter,2);case"X":return this.num(Math.floor(dt.ts/1e3));case"x":return this.num(dt.ts);default:return maybeMacro(token)}},"tokenToString");return stringifyTokens(_Formatter2.parseFormat(fmt),tokenToString)}formatDurationFromString(dur,fmt){const tokenToField=__name2(token=>{switch(token[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},"tokenToField"),tokenToString=__name2(lildur=>token=>{const mapped=tokenToField(token);return mapped?this.num(lildur.get(mapped),token.length):token},"tokenToString"),tokens=_Formatter2.parseFormat(fmt),realTokens=tokens.reduce((found,{literal:literal2,val})=>literal2?found:found.concat(val),[]),collapsed=dur.shiftTo(...realTokens.map(tokenToField).filter(t2=>t2));return stringifyTokens(tokens,tokenToString(collapsed))}};__name2(_Formatter,"Formatter");let Formatter=_Formatter;const _Invalid=class{static{__name(this,"_Invalid")}constructor(reason,explanation){this.reason=reason,this.explanation=explanation}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};__name2(_Invalid,"Invalid");let Invalid=_Invalid;const ianaRegex=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function combineRegexes(...regexes){const full=regexes.reduce((f2,r)=>f2+r.source,"");return RegExp(`^${full}$`)}__name(combineRegexes,"combineRegexes"),__name2(combineRegexes,"combineRegexes");function combineExtractors(...extractors){return m=>extractors.reduce(([mergedVals,mergedZone,cursor],ex)=>{const[val,zone,next]=ex(m,cursor);return[{...mergedVals,...val},zone||mergedZone,next]},[{},null,1]).slice(0,2)}__name(combineExtractors,"combineExtractors"),__name2(combineExtractors,"combineExtractors");function parse$1(s2,...patterns){if(s2==null)return[null,null];for(const[regex,extractor]of patterns){const m=regex.exec(s2);if(m)return extractor(m)}return[null,null]}__name(parse$1,"parse$1"),__name2(parse$1,"parse$1");function simpleParse(...keys2){return(match2,cursor)=>{const ret={};let i;for(i=0;i<keys2.length;i++)ret[keys2[i]]=parseInteger(match2[cursor+i]);return[ret,null,cursor+i]}}__name(simpleParse,"simpleParse"),__name2(simpleParse,"simpleParse");const offsetRegex=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,isoExtendedZone=`(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`,isoTimeBaseRegex=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,isoTimeRegex=RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`),isoTimeExtensionRegex=RegExp(`(?:T${isoTimeRegex.source})?`),isoYmdRegex=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,isoWeekRegex=/(\d{4})-?W(\d\d)(?:-?(\d))?/,isoOrdinalRegex=/(\d{4})-?(\d{3})/,extractISOWeekData=simpleParse("weekYear","weekNumber","weekDay"),extractISOOrdinalData=simpleParse("year","ordinal"),sqlYmdRegex=/(\d{4})-(\d\d)-(\d\d)/,sqlTimeRegex=RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`),sqlTimeExtensionRegex=RegExp(`(?: ${sqlTimeRegex.source})?`);function int(match2,pos,fallback){const m=match2[pos];return isUndefined(m)?fallback:parseInteger(m)}__name(int,"int"),__name2(int,"int");function extractISOYmd(match2,cursor){return[{year:int(match2,cursor),month:int(match2,cursor+1,1),day:int(match2,cursor+2,1)},null,cursor+3]}__name(extractISOYmd,"extractISOYmd"),__name2(extractISOYmd,"extractISOYmd");function extractISOTime(match2,cursor){return[{hours:int(match2,cursor,0),minutes:int(match2,cursor+1,0),seconds:int(match2,cursor+2,0),milliseconds:parseMillis(match2[cursor+3])},null,cursor+4]}__name(extractISOTime,"extractISOTime"),__name2(extractISOTime,"extractISOTime");function extractISOOffset(match2,cursor){const local=!match2[cursor]&&!match2[cursor+1],fullOffset=signedOffset(match2[cursor+1],match2[cursor+2]),zone=local?null:FixedOffsetZone.instance(fullOffset);return[{},zone,cursor+3]}__name(extractISOOffset,"extractISOOffset"),__name2(extractISOOffset,"extractISOOffset");function extractIANAZone(match2,cursor){const zone=match2[cursor]?IANAZone.create(match2[cursor]):null;return[{},zone,cursor+1]}__name(extractIANAZone,"extractIANAZone"),__name2(extractIANAZone,"extractIANAZone");const isoTimeOnly=RegExp(`^T?${isoTimeBaseRegex.source}$`),isoDuration=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function extractISODuration(match2){const[s2,yearStr,monthStr,weekStr,dayStr,hourStr,minuteStr,secondStr,millisecondsStr]=match2,hasNegativePrefix=s2[0]==="-",negativeSeconds=secondStr&&secondStr[0]==="-",maybeNegate=__name2((num,force=!1)=>num!==void 0&&(force||num&&hasNegativePrefix)?-num:num,"maybeNegate");return[{years:maybeNegate(parseFloating(yearStr)),months:maybeNegate(parseFloating(monthStr)),weeks:maybeNegate(parseFloating(weekStr)),days:maybeNegate(parseFloating(dayStr)),hours:maybeNegate(parseFloating(hourStr)),minutes:maybeNegate(parseFloating(minuteStr)),seconds:maybeNegate(parseFloating(secondStr),secondStr==="-0"),milliseconds:maybeNegate(parseMillis(millisecondsStr),negativeSeconds)}]}__name(extractISODuration,"extractISODuration"),__name2(extractISODuration,"extractISODuration");const obsOffsets={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr){const result={year:yearStr.length===2?untruncateYear(parseInteger(yearStr)):parseInteger(yearStr),month:monthsShort.indexOf(monthStr)+1,day:parseInteger(dayStr),hour:parseInteger(hourStr),minute:parseInteger(minuteStr)};return secondStr&&(result.second=parseInteger(secondStr)),weekdayStr&&(result.weekday=weekdayStr.length>3?weekdaysLong.indexOf(weekdayStr)+1:weekdaysShort.indexOf(weekdayStr)+1),result}__name(fromStrings,"fromStrings"),__name2(fromStrings,"fromStrings");const rfc2822=/^(?:(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\d)(\d\d)))$/;function extractRFC2822(match2){const[,weekdayStr,dayStr,monthStr,yearStr,hourStr,minuteStr,secondStr,obsOffset,milOffset,offHourStr,offMinuteStr]=match2,result=fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr);let offset2;return obsOffset?offset2=obsOffsets[obsOffset]:milOffset?offset2=0:offset2=signedOffset(offHourStr,offMinuteStr),[result,new FixedOffsetZone(offset2)]}__name(extractRFC2822,"extractRFC2822"),__name2(extractRFC2822,"extractRFC2822");function preprocessRFC2822(s2){return s2.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}__name(preprocessRFC2822,"preprocessRFC2822"),__name2(preprocessRFC2822,"preprocessRFC2822");const rfc1123=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,rfc850=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,ascii=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function extractRFC1123Or850(match2){const[,weekdayStr,dayStr,monthStr,yearStr,hourStr,minuteStr,secondStr]=match2;return[fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr),FixedOffsetZone.utcInstance]}__name(extractRFC1123Or850,"extractRFC1123Or850"),__name2(extractRFC1123Or850,"extractRFC1123Or850");function extractASCII(match2){const[,weekdayStr,monthStr,dayStr,hourStr,minuteStr,secondStr,yearStr]=match2;return[fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr),FixedOffsetZone.utcInstance]}__name(extractASCII,"extractASCII"),__name2(extractASCII,"extractASCII");const isoYmdWithTimeExtensionRegex=combineRegexes(isoYmdRegex,isoTimeExtensionRegex),isoWeekWithTimeExtensionRegex=combineRegexes(isoWeekRegex,isoTimeExtensionRegex),isoOrdinalWithTimeExtensionRegex=combineRegexes(isoOrdinalRegex,isoTimeExtensionRegex),isoTimeCombinedRegex=combineRegexes(isoTimeRegex),extractISOYmdTimeAndOffset=combineExtractors(extractISOYmd,extractISOTime,extractISOOffset,extractIANAZone),extractISOWeekTimeAndOffset=combineExtractors(extractISOWeekData,extractISOTime,extractISOOffset,extractIANAZone),extractISOOrdinalDateAndTime=combineExtractors(extractISOOrdinalData,extractISOTime,extractISOOffset,extractIANAZone),extractISOTimeAndOffset=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseISODate(s2){return parse$1(s2,[isoYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[isoWeekWithTimeExtensionRegex,extractISOWeekTimeAndOffset],[isoOrdinalWithTimeExtensionRegex,extractISOOrdinalDateAndTime],[isoTimeCombinedRegex,extractISOTimeAndOffset])}__name(parseISODate,"parseISODate"),__name2(parseISODate,"parseISODate");function parseRFC2822Date(s2){return parse$1(preprocessRFC2822(s2),[rfc2822,extractRFC2822])}__name(parseRFC2822Date,"parseRFC2822Date"),__name2(parseRFC2822Date,"parseRFC2822Date");function parseHTTPDate(s2){return parse$1(s2,[rfc1123,extractRFC1123Or850],[rfc850,extractRFC1123Or850],[ascii,extractASCII])}__name(parseHTTPDate,"parseHTTPDate"),__name2(parseHTTPDate,"parseHTTPDate");function parseISODuration(s2){return parse$1(s2,[isoDuration,extractISODuration])}__name(parseISODuration,"parseISODuration"),__name2(parseISODuration,"parseISODuration");const extractISOTimeOnly=combineExtractors(extractISOTime);function parseISOTimeOnly(s2){return parse$1(s2,[isoTimeOnly,extractISOTimeOnly])}__name(parseISOTimeOnly,"parseISOTimeOnly"),__name2(parseISOTimeOnly,"parseISOTimeOnly");const sqlYmdWithTimeExtensionRegex=combineRegexes(sqlYmdRegex,sqlTimeExtensionRegex),sqlTimeCombinedRegex=combineRegexes(sqlTimeRegex),extractISOTimeOffsetAndIANAZone=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseSQL(s2){return parse$1(s2,[sqlYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[sqlTimeCombinedRegex,extractISOTimeOffsetAndIANAZone])}__name(parseSQL,"parseSQL"),__name2(parseSQL,"parseSQL");const INVALID$2="Invalid Duration",lowOrderMatrix={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},casualMatrix={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...lowOrderMatrix},daysInYearAccurate=146097/400,daysInMonthAccurate=146097/4800,accurateMatrix={years:{quarters:4,months:12,weeks:daysInYearAccurate/7,days:daysInYearAccurate,hours:daysInYearAccurate*24,minutes:daysInYearAccurate*24*60,seconds:daysInYearAccurate*24*60*60,milliseconds:daysInYearAccurate*24*60*60*1e3},quarters:{months:3,weeks:daysInYearAccurate/28,days:daysInYearAccurate/4,hours:daysInYearAccurate*24/4,minutes:daysInYearAccurate*24*60/4,seconds:daysInYearAccurate*24*60*60/4,milliseconds:daysInYearAccurate*24*60*60*1e3/4},months:{weeks:daysInMonthAccurate/7,days:daysInMonthAccurate,hours:daysInMonthAccurate*24,minutes:daysInMonthAccurate*24*60,seconds:daysInMonthAccurate*24*60*60,milliseconds:daysInMonthAccurate*24*60*60*1e3},...lowOrderMatrix},orderedUnits$1=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],reverseUnits=orderedUnits$1.slice(0).reverse();function clone$2(dur,alts,clear=!1){const conf={values:clear?alts.values:{...dur.values,...alts.values||{}},loc:dur.loc.clone(alts.loc),conversionAccuracy:alts.conversionAccuracy||dur.conversionAccuracy,matrix:alts.matrix||dur.matrix};return new Duration(conf)}__name(clone$2,"clone$2"),__name2(clone$2,"clone$2");function durationToMillis(matrix2,vals){let sum=vals.milliseconds??0;for(const unit of reverseUnits.slice(1))vals[unit]&&(sum+=vals[unit]*matrix2[unit].milliseconds);return sum}__name(durationToMillis,"durationToMillis"),__name2(durationToMillis,"durationToMillis");function normalizeValues(matrix2,vals){const factor=durationToMillis(matrix2,vals)<0?-1:1;orderedUnits$1.reduceRight((previous,current)=>{if(isUndefined(vals[current]))return previous;if(previous){const previousVal=vals[previous]*factor,conv=matrix2[current][previous],rollUp=Math.floor(previousVal/conv);vals[current]+=rollUp*factor,vals[previous]-=rollUp*conv*factor}return current},null),orderedUnits$1.reduce((previous,current)=>{if(isUndefined(vals[current]))return previous;if(previous){const fraction=vals[previous]%1;vals[previous]-=fraction,vals[current]+=fraction*matrix2[previous][current]}return current},null)}__name(normalizeValues,"normalizeValues"),__name2(normalizeValues,"normalizeValues");function removeZeroes(vals){const newVals={};for(const[key,value]of Object.entries(vals))value!==0&&(newVals[key]=value);return newVals}__name(removeZeroes,"removeZeroes"),__name2(removeZeroes,"removeZeroes");const _Duration=class _Duration2{static{__name(this,"_Duration")}constructor(config2){const accurate=config2.conversionAccuracy==="longterm"||!1;let matrix2=accurate?accurateMatrix:casualMatrix;config2.matrix&&(matrix2=config2.matrix),this.values=config2.values,this.loc=config2.loc||Locale.create(),this.conversionAccuracy=accurate?"longterm":"casual",this.invalid=config2.invalid||null,this.matrix=matrix2,this.isLuxonDuration=!0}static fromMillis(count,opts){return _Duration2.fromObject({milliseconds:count},opts)}static fromObject(obj,opts={}){if(obj==null||typeof obj!="object")throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj===null?"null":typeof obj}`);return new _Duration2({values:normalizeObject(obj,_Duration2.normalizeUnit),loc:Locale.fromObject(opts),conversionAccuracy:opts.conversionAccuracy,matrix:opts.matrix})}static fromDurationLike(durationLike){if(isNumber(durationLike))return _Duration2.fromMillis(durationLike);if(_Duration2.isDuration(durationLike))return durationLike;if(typeof durationLike=="object")return _Duration2.fromObject(durationLike);throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`)}static fromISO(text,opts){const[parsed]=parseISODuration(text);return parsed?_Duration2.fromObject(parsed,opts):_Duration2.invalid("unparsable",`the input "${text}" can't be parsed as ISO 8601`)}static fromISOTime(text,opts){const[parsed]=parseISOTimeOnly(text);return parsed?_Duration2.fromObject(parsed,opts):_Duration2.invalid("unparsable",`the input "${text}" can't be parsed as ISO 8601`)}static invalid(reason,explanation=null){if(!reason)throw new InvalidArgumentError("need to specify a reason the Duration is invalid");const invalid=reason instanceof Invalid?reason:new Invalid(reason,explanation);if(Settings.throwOnInvalid)throw new InvalidDurationError(invalid);return new _Duration2({invalid})}static normalizeUnit(unit){const normalized={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[unit&&unit.toLowerCase()];if(!normalized)throw new InvalidUnitError(unit);return normalized}static isDuration(o){return o&&o.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(fmt,opts={}){const fmtOpts={...opts,floor:opts.round!==!1&&opts.floor!==!1};return this.isValid?Formatter.create(this.loc,fmtOpts).formatDurationFromString(this,fmt):INVALID$2}toHuman(opts={}){if(!this.isValid)return INVALID$2;const l2=orderedUnits$1.map(unit=>{const val=this.values[unit];return isUndefined(val)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...opts,unit:unit.slice(0,-1)}).format(val)}).filter(n2=>n2);return this.loc.listFormatter({type:"conjunction",style:opts.listStyle||"narrow",...opts}).format(l2)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let s2="P";return this.years!==0&&(s2+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(s2+=this.months+this.quarters*3+"M"),this.weeks!==0&&(s2+=this.weeks+"W"),this.days!==0&&(s2+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(s2+="T"),this.hours!==0&&(s2+=this.hours+"H"),this.minutes!==0&&(s2+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(s2+=roundTo(this.seconds+this.milliseconds/1e3,3)+"S"),s2==="P"&&(s2+="T0S"),s2}toISOTime(opts={}){if(!this.isValid)return null;const millis=this.toMillis();return millis<0||millis>=864e5?null:(opts={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...opts,includeOffset:!1},DateTime.fromMillis(millis,{zone:"UTC"}).toISOTime(opts))}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.isValid?durationToMillis(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(duration){if(!this.isValid)return this;const dur=_Duration2.fromDurationLike(duration),result={};for(const k of orderedUnits$1)(hasOwnProperty(dur.values,k)||hasOwnProperty(this.values,k))&&(result[k]=dur.get(k)+this.get(k));return clone$2(this,{values:result},!0)}minus(duration){if(!this.isValid)return this;const dur=_Duration2.fromDurationLike(duration);return this.plus(dur.negate())}mapUnits(fn){if(!this.isValid)return this;const result={};for(const k of Object.keys(this.values))result[k]=asNumber(fn(this.values[k],k));return clone$2(this,{values:result},!0)}get(unit){return this[_Duration2.normalizeUnit(unit)]}set(values){if(!this.isValid)return this;const mixed={...this.values,...normalizeObject(values,_Duration2.normalizeUnit)};return clone$2(this,{values:mixed})}reconfigure({locale,numberingSystem,conversionAccuracy,matrix:matrix2}={}){const opts={loc:this.loc.clone({locale,numberingSystem}),matrix:matrix2,conversionAccuracy};return clone$2(this,opts)}as(unit){return this.isValid?this.shiftTo(unit).get(unit):NaN}normalize(){if(!this.isValid)return this;const vals=this.toObject();return normalizeValues(this.matrix,vals),clone$2(this,{values:vals},!0)}rescale(){if(!this.isValid)return this;const vals=removeZeroes(this.normalize().shiftToAll().toObject());return clone$2(this,{values:vals},!0)}shiftTo(...units){if(!this.isValid)return this;if(units.length===0)return this;units=units.map(u=>_Duration2.normalizeUnit(u));const built={},accumulated={},vals=this.toObject();let lastUnit;for(const k of orderedUnits$1)if(units.indexOf(k)>=0){lastUnit=k;let own=0;for(const ak in accumulated)own+=this.matrix[ak][k]*accumulated[ak],accumulated[ak]=0;isNumber(vals[k])&&(own+=vals[k]);const i=Math.trunc(own);built[k]=i,accumulated[k]=(own*1e3-i*1e3)/1e3}else isNumber(vals[k])&&(accumulated[k]=vals[k]);for(const key in accumulated)accumulated[key]!==0&&(built[lastUnit]+=key===lastUnit?accumulated[key]:accumulated[key]/this.matrix[lastUnit][key]);return normalizeValues(this.matrix,built),clone$2(this,{values:built},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const negated={};for(const k of Object.keys(this.values))negated[k]=this.values[k]===0?0:-this.values[k];return clone$2(this,{values:negated},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(other){if(!this.isValid||!other.isValid||!this.loc.equals(other.loc))return!1;function eq(v1,v2){return v1===void 0||v1===0?v2===void 0||v2===0:v1===v2}__name(eq,"eq"),__name2(eq,"eq");for(const u of orderedUnits$1)if(!eq(this.values[u],other.values[u]))return!1;return!0}};__name2(_Duration,"Duration");let Duration=_Duration;const INVALID$1="Invalid Interval";function validateStartEnd(start,end){return!start||!start.isValid?Interval.invalid("missing or invalid start"):!end||!end.isValid?Interval.invalid("missing or invalid end"):end<start?Interval.invalid("end before start",`The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`):null}__name(validateStartEnd,"validateStartEnd"),__name2(validateStartEnd,"validateStartEnd");const _Interval=class _Interval2{static{__name(this,"_Interval")}constructor(config2){this.s=config2.start,this.e=config2.end,this.invalid=config2.invalid||null,this.isLuxonInterval=!0}static invalid(reason,explanation=null){if(!reason)throw new InvalidArgumentError("need to specify a reason the Interval is invalid");const invalid=reason instanceof Invalid?reason:new Invalid(reason,explanation);if(Settings.throwOnInvalid)throw new InvalidIntervalError(invalid);return new _Interval2({invalid})}static fromDateTimes(start,end){const builtStart=friendlyDateTime(start),builtEnd=friendlyDateTime(end),validateError=validateStartEnd(builtStart,builtEnd);return validateError??new _Interval2({start:builtStart,end:builtEnd})}static after(start,duration){const dur=Duration.fromDurationLike(duration),dt=friendlyDateTime(start);return _Interval2.fromDateTimes(dt,dt.plus(dur))}static before(end,duration){const dur=Duration.fromDurationLike(duration),dt=friendlyDateTime(end);return _Interval2.fromDateTimes(dt.minus(dur),dt)}static fromISO(text,opts){const[s2,e]=(text||"").split("/",2);if(s2&&e){let start,startIsValid;try{start=DateTime.fromISO(s2,opts),startIsValid=start.isValid}catch{startIsValid=!1}let end,endIsValid;try{end=DateTime.fromISO(e,opts),endIsValid=end.isValid}catch{endIsValid=!1}if(startIsValid&&endIsValid)return _Interval2.fromDateTimes(start,end);if(startIsValid){const dur=Duration.fromISO(e,opts);if(dur.isValid)return _Interval2.after(start,dur)}else if(endIsValid){const dur=Duration.fromISO(s2,opts);if(dur.isValid)return _Interval2.before(end,dur)}}return _Interval2.invalid("unparsable",`the input "${text}" can't be parsed as ISO 8601`)}static isInterval(o){return o&&o.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(unit="milliseconds"){return this.isValid?this.toDuration(unit).get(unit):NaN}count(unit="milliseconds"){if(!this.isValid)return NaN;const start=this.start.startOf(unit),end=this.end.startOf(unit);return Math.floor(end.diff(start,unit).get(unit))+(end.valueOf()!==this.end.valueOf())}hasSame(unit){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,unit):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(dateTime){return this.isValid?this.s>dateTime:!1}isBefore(dateTime){return this.isValid?this.e<=dateTime:!1}contains(dateTime){return this.isValid?this.s<=dateTime&&this.e>dateTime:!1}set({start,end}={}){return this.isValid?_Interval2.fromDateTimes(start||this.s,end||this.e):this}splitAt(...dateTimes){if(!this.isValid)return[];const sorted=dateTimes.map(friendlyDateTime).filter(d=>this.contains(d)).sort(),results=[];let{s:s2}=this,i=0;for(;s2<this.e;){const added=sorted[i]||this.e,next=+added>+this.e?this.e:added;results.push(_Interval2.fromDateTimes(s2,next)),s2=next,i+=1}return results}splitBy(duration){const dur=Duration.fromDurationLike(duration);if(!this.isValid||!dur.isValid||dur.as("milliseconds")===0)return[];let{s:s2}=this,idx=1,next;const results=[];for(;s2<this.e;){const added=this.start.plus(dur.mapUnits(x=>x*idx));next=+added>+this.e?this.e:added,results.push(_Interval2.fromDateTimes(s2,next)),s2=next,idx+=1}return results}divideEqually(numberOfParts){return this.isValid?this.splitBy(this.length()/numberOfParts).slice(0,numberOfParts):[]}overlaps(other){return this.e>other.s&&this.s<other.e}abutsStart(other){return this.isValid?+this.e==+other.s:!1}abutsEnd(other){return this.isValid?+other.e==+this.s:!1}engulfs(other){return this.isValid?this.s<=other.s&&this.e>=other.e:!1}equals(other){return!this.isValid||!other.isValid?!1:this.s.equals(other.s)&&this.e.equals(other.e)}intersection(other){if(!this.isValid)return this;const s2=this.s>other.s?this.s:other.s,e=this.e<other.e?this.e:other.e;return s2>=e?null:_Interval2.fromDateTimes(s2,e)}union(other){if(!this.isValid)return this;const s2=this.s<other.s?this.s:other.s,e=this.e>other.e?this.e:other.e;return _Interval2.fromDateTimes(s2,e)}static merge(intervals){const[found,final]=intervals.sort((a,b)=>a.s-b.s).reduce(([sofar,current],item)=>current?current.overlaps(item)||current.abutsStart(item)?[sofar,current.union(item)]:[sofar.concat([current]),item]:[sofar,item],[[],null]);return final&&found.push(final),found}static xor(intervals){let start=null,currentCount=0;const results=[],ends=intervals.map(i=>[{time:i.s,type:"s"},{time:i.e,type:"e"}]),flattened2=Array.prototype.concat(...ends),arr=flattened2.sort((a,b)=>a.time-b.time);for(const i of arr)currentCount+=i.type==="s"?1:-1,currentCount===1?start=i.time:(start&&+start!=+i.time&&results.push(_Interval2.fromDateTimes(start,i.time)),start=null);return _Interval2.merge(results)}difference(...intervals){return _Interval2.xor([this].concat(intervals)).map(i=>this.intersection(i)).filter(i=>i&&!i.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:INVALID$1}toLocaleString(formatOpts=DATE_SHORT,opts={}){return this.isValid?Formatter.create(this.s.loc.clone(opts),formatOpts).formatInterval(this):INVALID$1}toISO(opts){return this.isValid?`${this.s.toISO(opts)}/${this.e.toISO(opts)}`:INVALID$1}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:INVALID$1}toISOTime(opts){return this.isValid?`${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`:INVALID$1}toFormat(dateFormat,{separator=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`:INVALID$1}toDuration(unit,opts){return this.isValid?this.e.diff(this.s,unit,opts):Duration.invalid(this.invalidReason)}mapEndpoints(mapFn){return _Interval2.fromDateTimes(mapFn(this.s),mapFn(this.e))}};__name2(_Interval,"Interval");let Interval=_Interval;const _Info=class{static{__name(this,"_Info")}static hasDST(zone=Settings.defaultZone){const proto=DateTime.now().setZone(zone).set({month:12});return!zone.isUniversal&&proto.offset!==proto.set({month:6}).offset}static isValidIANAZone(zone){return IANAZone.isValidZone(zone)}static normalizeZone(input){return normalizeZone(input,Settings.defaultZone)}static months(length="long",{locale=null,numberingSystem=null,locObj=null,outputCalendar="gregory"}={}){return(locObj||Locale.create(locale,numberingSystem,outputCalendar)).months(length)}static monthsFormat(length="long",{locale=null,numberingSystem=null,locObj=null,outputCalendar="gregory"}={}){return(locObj||Locale.create(locale,numberingSystem,outputCalendar)).months(length,!0)}static weekdays(length="long",{locale=null,numberingSystem=null,locObj=null}={}){return(locObj||Locale.create(locale,numberingSystem,null)).weekdays(length)}static weekdaysFormat(length="long",{locale=null,numberingSystem=null,locObj=null}={}){return(locObj||Locale.create(locale,numberingSystem,null)).weekdays(length,!0)}static meridiems({locale=null}={}){return Locale.create(locale).meridiems()}static eras(length="short",{locale=null}={}){return Locale.create(locale,null,"gregory").eras(length)}static features(){return{relative:hasRelative()}}};__name2(_Info,"Info");let Info=_Info;function dayDiff(earlier,later){const utcDayStart=__name2(dt=>dt.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),"utcDayStart"),ms=utcDayStart(later)-utcDayStart(earlier);return Math.floor(Duration.fromMillis(ms).as("days"))}__name(dayDiff,"dayDiff"),__name2(dayDiff,"dayDiff");function highOrderDiffs(cursor,later,units){const differs=[["years",(a,b)=>b.year-a.year],["quarters",(a,b)=>b.quarter-a.quarter+(b.year-a.year)*4],["months",(a,b)=>b.month-a.month+(b.year-a.year)*12],["weeks",(a,b)=>{const days=dayDiff(a,b);return(days-days%7)/7}],["days",dayDiff]],results={},earlier=cursor;let lowestOrder,highWater;for(const[unit,differ]of differs)units.indexOf(unit)>=0&&(lowestOrder=unit,results[unit]=differ(cursor,later),highWater=earlier.plus(results),highWater>later?(results[unit]--,cursor=earlier.plus(results),cursor>later&&(highWater=cursor,results[unit]--,cursor=earlier.plus(results))):cursor=highWater);return[cursor,results,highWater,lowestOrder]}__name(highOrderDiffs,"highOrderDiffs"),__name2(highOrderDiffs,"highOrderDiffs");function diff(earlier,later,units,opts){let[cursor,results,highWater,lowestOrder]=highOrderDiffs(earlier,later,units);const remainingMillis=later-cursor,lowerOrderUnits=units.filter(u=>["hours","minutes","seconds","milliseconds"].indexOf(u)>=0);lowerOrderUnits.length===0&&(highWater<later&&(highWater=cursor.plus({[lowestOrder]:1})),highWater!==cursor&&(results[lowestOrder]=(results[lowestOrder]||0)+remainingMillis/(highWater-cursor)));const duration=Duration.fromObject(results,opts);return lowerOrderUnits.length>0?Duration.fromMillis(remainingMillis,opts).shiftTo(...lowerOrderUnits).plus(duration):duration}__name(diff,"diff"),__name2(diff,"diff");const numberingSystems={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},numberingSystemsUTF16={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},hanidecChars=numberingSystems.hanidec.replace(/[\[|\]]/g,"").split("");function parseDigits(str){let value=parseInt(str,10);if(isNaN(value)){value="";for(let i=0;i<str.length;i++){const code=str.charCodeAt(i);if(str[i].search(numberingSystems.hanidec)!==-1)value+=hanidecChars.indexOf(str[i]);else for(const key in numberingSystemsUTF16){const[min,max]=numberingSystemsUTF16[key];code>=min&&code<=max&&(value+=code-min)}}return parseInt(value,10)}else return value}__name(parseDigits,"parseDigits"),__name2(parseDigits,"parseDigits");function digitRegex({numberingSystem},append=""){return new RegExp(`${numberingSystems[numberingSystem||"latn"]}${append}`)}__name(digitRegex,"digitRegex"),__name2(digitRegex,"digitRegex");const MISSING_FTP="missing Intl.DateTimeFormat.formatToParts support";function intUnit(regex,post=i=>i){return{regex,deser:([s2])=>post(parseDigits(s2))}}__name(intUnit,"intUnit"),__name2(intUnit,"intUnit");const NBSP=String.fromCharCode(160),spaceOrNBSP=`[ ${NBSP}]`,spaceOrNBSPRegExp=new RegExp(spaceOrNBSP,"g");function fixListRegex(s2){return s2.replace(/\./g,"\\.?").replace(spaceOrNBSPRegExp,spaceOrNBSP)}__name(fixListRegex,"fixListRegex"),__name2(fixListRegex,"fixListRegex");function stripInsensitivities(s2){return s2.replace(/\./g,"").replace(spaceOrNBSPRegExp," ").toLowerCase()}__name(stripInsensitivities,"stripInsensitivities"),__name2(stripInsensitivities,"stripInsensitivities");function oneOf(strings,startIndex){return strings===null?null:{regex:RegExp(strings.map(fixListRegex).join("|")),deser:([s2])=>strings.findIndex(i=>stripInsensitivities(s2)===stripInsensitivities(i))+startIndex}}__name(oneOf,"oneOf"),__name2(oneOf,"oneOf");function offset$1(regex,groups){return{regex,deser:([,h,m])=>signedOffset(h,m),groups}}__name(offset$1,"offset$1"),__name2(offset$1,"offset$1");function simple(regex){return{regex,deser:([s2])=>s2}}__name(simple,"simple"),__name2(simple,"simple");function escapeToken(value){return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}__name(escapeToken,"escapeToken"),__name2(escapeToken,"escapeToken");function unitForToken(token,loc){const one=digitRegex(loc),two=digitRegex(loc,"{2}"),three=digitRegex(loc,"{3}"),four=digitRegex(loc,"{4}"),six=digitRegex(loc,"{6}"),oneOrTwo=digitRegex(loc,"{1,2}"),oneToThree=digitRegex(loc,"{1,3}"),oneToSix=digitRegex(loc,"{1,6}"),oneToNine=digitRegex(loc,"{1,9}"),twoToFour=digitRegex(loc,"{2,4}"),fourToSix=digitRegex(loc,"{4,6}"),literal2=__name2(t2=>({regex:RegExp(escapeToken(t2.val)),deser:([s2])=>s2,literal:!0}),"literal"),unit=__name2(t2=>{if(token.literal)return literal2(t2);switch(t2.val){case"G":return oneOf(loc.eras("short"),0);case"GG":return oneOf(loc.eras("long"),0);case"y":return intUnit(oneToSix);case"yy":return intUnit(twoToFour,untruncateYear);case"yyyy":return intUnit(four);case"yyyyy":return intUnit(fourToSix);case"yyyyyy":return intUnit(six);case"M":return intUnit(oneOrTwo);case"MM":return intUnit(two);case"MMM":return oneOf(loc.months("short",!0),1);case"MMMM":return oneOf(loc.months("long",!0),1);case"L":return intUnit(oneOrTwo);case"LL":return intUnit(two);case"LLL":return oneOf(loc.months("short",!1),1);case"LLLL":return oneOf(loc.months("long",!1),1);case"d":return intUnit(oneOrTwo);case"dd":return intUnit(two);case"o":return intUnit(oneToThree);case"ooo":return intUnit(three);case"HH":return intUnit(two);case"H":return intUnit(oneOrTwo);case"hh":return intUnit(two);case"h":return intUnit(oneOrTwo);case"mm":return intUnit(two);case"m":return intUnit(oneOrTwo);case"q":return intUnit(oneOrTwo);case"qq":return intUnit(two);case"s":return intUnit(oneOrTwo);case"ss":return intUnit(two);case"S":return intUnit(oneToThree);case"SSS":return intUnit(three);case"u":return simple(oneToNine);case"uu":return simple(oneOrTwo);case"uuu":return intUnit(one);case"a":return oneOf(loc.meridiems(),0);case"kkkk":return intUnit(four);case"kk":return intUnit(twoToFour,untruncateYear);case"W":return intUnit(oneOrTwo);case"WW":return intUnit(two);case"E":case"c":return intUnit(one);case"EEE":return oneOf(loc.weekdays("short",!1),1);case"EEEE":return oneOf(loc.weekdays("long",!1),1);case"ccc":return oneOf(loc.weekdays("short",!0),1);case"cccc":return oneOf(loc.weekdays("long",!0),1);case"Z":case"ZZ":return offset$1(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`),2);case"ZZZ":return offset$1(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`),2);case"z":return simple(/[a-z_+-/]{1,256}?/i);case" ":return simple(/[^\S\n\r]/);default:return literal2(t2)}},"unitate")(token)||{invalidReason:MISSING_FTP};return unit.token=token,unit}__name(unitForToken,"unitForToken"),__name2(unitForToken,"unitForToken");const partTypeStyleToTokenVal={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function tokenForPart(part,formatOpts,resolvedOpts){const{type,value}=part;if(type==="literal"){const isSpace=/^\s+$/.test(value);return{literal:!isSpace,val:isSpace?" ":value}}const style=formatOpts[type];let actualType=type;type==="hour"&&(formatOpts.hour12!=null?actualType=formatOpts.hour12?"hour12":"hour24":formatOpts.hourCycle!=null?formatOpts.hourCycle==="h11"||formatOpts.hourCycle==="h12"?actualType="hour12":actualType="hour24":actualType=resolvedOpts.hour12?"hour12":"hour24");let val=partTypeStyleToTokenVal[actualType];if(typeof val=="object"&&(val=val[style]),val)return{literal:!1,val}}__name(tokenForPart,"tokenForPart"),__name2(tokenForPart,"tokenForPart");function buildRegex(units){return[`^${units.map(u=>u.regex).reduce((f2,r)=>`${f2}(${r.source})`,"")}$`,units]}__name(buildRegex,"buildRegex"),__name2(buildRegex,"buildRegex");function match(input,regex,handlers2){const matches2=input.match(regex);if(matches2){const all={};let matchIndex=1;for(const i in handlers2)if(hasOwnProperty(handlers2,i)){const h=handlers2[i],groups=h.groups?h.groups+1:1;!h.literal&&h.token&&(all[h.token.val[0]]=h.deser(matches2.slice(matchIndex,matchIndex+groups))),matchIndex+=groups}return[matches2,all]}else return[matches2,{}]}__name(match,"match"),__name2(match,"match");function dateTimeFromMatches(matches2){const toField=__name2(token=>{switch(token){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},"toField");let zone=null,specificOffset;return isUndefined(matches2.z)||(zone=IANAZone.create(matches2.z)),isUndefined(matches2.Z)||(zone||(zone=new FixedOffsetZone(matches2.Z)),specificOffset=matches2.Z),isUndefined(matches2.q)||(matches2.M=(matches2.q-1)*3+1),isUndefined(matches2.h)||(matches2.h<12&&matches2.a===1?matches2.h+=12:matches2.h===12&&matches2.a===0&&(matches2.h=0)),matches2.G===0&&matches2.y&&(matches2.y=-matches2.y),isUndefined(matches2.u)||(matches2.S=parseMillis(matches2.u)),[Object.keys(matches2).reduce((r,k)=>{const f2=toField(k);return f2&&(r[f2]=matches2[k]),r},{}),zone,specificOffset]}__name(dateTimeFromMatches,"dateTimeFromMatches"),__name2(dateTimeFromMatches,"dateTimeFromMatches");let dummyDateTimeCache=null;function getDummyDateTime(){return dummyDateTimeCache||(dummyDateTimeCache=DateTime.fromMillis(1555555555555)),dummyDateTimeCache}__name(getDummyDateTime,"getDummyDateTime"),__name2(getDummyDateTime,"getDummyDateTime");function maybeExpandMacroToken(token,locale){if(token.literal)return token;const formatOpts=Formatter.macroTokenToFormatOpts(token.val),tokens=formatOptsToTokens(formatOpts,locale);return tokens==null||tokens.includes(void 0)?token:tokens}__name(maybeExpandMacroToken,"maybeExpandMacroToken"),__name2(maybeExpandMacroToken,"maybeExpandMacroToken");function expandMacroTokens(tokens,locale){return Array.prototype.concat(...tokens.map(t2=>maybeExpandMacroToken(t2,locale)))}__name(expandMacroTokens,"expandMacroTokens"),__name2(expandMacroTokens,"expandMacroTokens");function explainFromTokens(locale,input,format){const tokens=expandMacroTokens(Formatter.parseFormat(format),locale),units=tokens.map(t2=>unitForToken(t2,locale)),disqualifyingUnit=units.find(t2=>t2.invalidReason);if(disqualifyingUnit)return{input,tokens,invalidReason:disqualifyingUnit.invalidReason};{const[regexString,handlers2]=buildRegex(units),regex=RegExp(regexString,"i"),[rawMatches,matches2]=match(input,regex,handlers2),[result,zone,specificOffset]=matches2?dateTimeFromMatches(matches2):[null,null,void 0];if(hasOwnProperty(matches2,"a")&&hasOwnProperty(matches2,"H"))throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");return{input,tokens,regex,rawMatches,matches:matches2,result,zone,specificOffset}}}__name(explainFromTokens,"explainFromTokens"),__name2(explainFromTokens,"explainFromTokens");function parseFromTokens(locale,input,format){const{result,zone,specificOffset,invalidReason}=explainFromTokens(locale,input,format);return[result,zone,specificOffset,invalidReason]}__name(parseFromTokens,"parseFromTokens"),__name2(parseFromTokens,"parseFromTokens");function formatOptsToTokens(formatOpts,locale){if(!formatOpts)return null;const df=Formatter.create(locale,formatOpts).dtFormatter(getDummyDateTime()),parts=df.formatToParts(),resolvedOpts=df.resolvedOptions();return parts.map(p=>tokenForPart(p,formatOpts,resolvedOpts))}__name(formatOptsToTokens,"formatOptsToTokens"),__name2(formatOptsToTokens,"formatOptsToTokens");const nonLeapLadder=[0,31,59,90,120,151,181,212,243,273,304,334],leapLadder=[0,31,60,91,121,152,182,213,244,274,305,335];function unitOutOfRange(unit,value){return new Invalid("unit out of range",`you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`)}__name(unitOutOfRange,"unitOutOfRange"),__name2(unitOutOfRange,"unitOutOfRange");function dayOfWeek(year,month,day){const d=new Date(Date.UTC(year,month-1,day));year<100&&year>=0&&d.setUTCFullYear(d.getUTCFullYear()-1900);const js=d.getUTCDay();return js===0?7:js}__name(dayOfWeek,"dayOfWeek"),__name2(dayOfWeek,"dayOfWeek");function computeOrdinal(year,month,day){return day+(isLeapYear(year)?leapLadder:nonLeapLadder)[month-1]}__name(computeOrdinal,"computeOrdinal"),__name2(computeOrdinal,"computeOrdinal");function uncomputeOrdinal(year,ordinal){const table=isLeapYear(year)?leapLadder:nonLeapLadder,month0=table.findIndex(i=>i<ordinal),day=ordinal-table[month0];return{month:month0+1,day}}__name(uncomputeOrdinal,"uncomputeOrdinal"),__name2(uncomputeOrdinal,"uncomputeOrdinal");function gregorianToWeek(gregObj){const{year,month,day}=gregObj,ordinal=computeOrdinal(year,month,day),weekday=dayOfWeek(year,month,day);let weekNumber=Math.floor((ordinal-weekday+10)/7),weekYear;return weekNumber<1?(weekYear=year-1,weekNumber=weeksInWeekYear(weekYear)):weekNumber>weeksInWeekYear(year)?(weekYear=year+1,weekNumber=1):weekYear=year,{weekYear,weekNumber,weekday,...timeObject(gregObj)}}__name(gregorianToWeek,"gregorianToWeek"),__name2(gregorianToWeek,"gregorianToWeek");function weekToGregorian(weekData){const{weekYear,weekNumber,weekday}=weekData,weekdayOfJan4=dayOfWeek(weekYear,1,4),yearInDays=daysInYear(weekYear);let ordinal=weekNumber*7+weekday-weekdayOfJan4-3,year;ordinal<1?(year=weekYear-1,ordinal+=daysInYear(year)):ordinal>yearInDays?(year=weekYear+1,ordinal-=daysInYear(weekYear)):year=weekYear;const{month,day}=uncomputeOrdinal(year,ordinal);return{year,month,day,...timeObject(weekData)}}__name(weekToGregorian,"weekToGregorian"),__name2(weekToGregorian,"weekToGregorian");function gregorianToOrdinal(gregData){const{year,month,day}=gregData,ordinal=computeOrdinal(year,month,day);return{year,ordinal,...timeObject(gregData)}}__name(gregorianToOrdinal,"gregorianToOrdinal"),__name2(gregorianToOrdinal,"gregorianToOrdinal");function ordinalToGregorian(ordinalData){const{year,ordinal}=ordinalData,{month,day}=uncomputeOrdinal(year,ordinal);return{year,month,day,...timeObject(ordinalData)}}__name(ordinalToGregorian,"ordinalToGregorian"),__name2(ordinalToGregorian,"ordinalToGregorian");function hasInvalidWeekData(obj){const validYear=isInteger(obj.weekYear),validWeek=integerBetween(obj.weekNumber,1,weeksInWeekYear(obj.weekYear)),validWeekday=integerBetween(obj.weekday,1,7);return validYear?validWeek?validWeekday?!1:unitOutOfRange("weekday",obj.weekday):unitOutOfRange("week",obj.week):unitOutOfRange("weekYear",obj.weekYear)}__name(hasInvalidWeekData,"hasInvalidWeekData"),__name2(hasInvalidWeekData,"hasInvalidWeekData");function hasInvalidOrdinalData(obj){const validYear=isInteger(obj.year),validOrdinal=integerBetween(obj.ordinal,1,daysInYear(obj.year));return validYear?validOrdinal?!1:unitOutOfRange("ordinal",obj.ordinal):unitOutOfRange("year",obj.year)}__name(hasInvalidOrdinalData,"hasInvalidOrdinalData"),__name2(hasInvalidOrdinalData,"hasInvalidOrdinalData");function hasInvalidGregorianData(obj){const validYear=isInteger(obj.year),validMonth=integerBetween(obj.month,1,12),validDay=integerBetween(obj.day,1,daysInMonth(obj.year,obj.month));return validYear?validMonth?validDay?!1:unitOutOfRange("day",obj.day):unitOutOfRange("month",obj.month):unitOutOfRange("year",obj.year)}__name(hasInvalidGregorianData,"hasInvalidGregorianData"),__name2(hasInvalidGregorianData,"hasInvalidGregorianData");function hasInvalidTimeData(obj){const{hour,minute,second,millisecond}=obj,validHour=integerBetween(hour,0,23)||hour===24&&minute===0&&second===0&&millisecond===0,validMinute=integerBetween(minute,0,59),validSecond=integerBetween(second,0,59),validMillisecond=integerBetween(millisecond,0,999);return validHour?validMinute?validSecond?validMillisecond?!1:unitOutOfRange("millisecond",millisecond):unitOutOfRange("second",second):unitOutOfRange("minute",minute):unitOutOfRange("hour",hour)}__name(hasInvalidTimeData,"hasInvalidTimeData"),__name2(hasInvalidTimeData,"hasInvalidTimeData");const INVALID="Invalid DateTime",MAX_DATE=864e13;function unsupportedZone(zone){return new Invalid("unsupported zone",`the zone "${zone.name}" is not supported`)}__name(unsupportedZone,"unsupportedZone"),__name2(unsupportedZone,"unsupportedZone");function possiblyCachedWeekData(dt){return dt.weekData===null&&(dt.weekData=gregorianToWeek(dt.c)),dt.weekData}__name(possiblyCachedWeekData,"possiblyCachedWeekData"),__name2(possiblyCachedWeekData,"possiblyCachedWeekData");function clone$1(inst,alts){const current={ts:inst.ts,zone:inst.zone,c:inst.c,o:inst.o,loc:inst.loc,invalid:inst.invalid};return new DateTime({...current,...alts,old:current})}__name(clone$1,"clone$1"),__name2(clone$1,"clone$1");function fixOffset(localTS,o,tz){let utcGuess=localTS-o*60*1e3;const o2=tz.offset(utcGuess);if(o===o2)return[utcGuess,o];utcGuess-=(o2-o)*60*1e3;const o3=tz.offset(utcGuess);return o2===o3?[utcGuess,o2]:[localTS-Math.min(o2,o3)*60*1e3,Math.max(o2,o3)]}__name(fixOffset,"fixOffset"),__name2(fixOffset,"fixOffset");function tsToObj(ts,offset2){ts+=offset2*60*1e3;const d=new Date(ts);return{year:d.getUTCFullYear(),month:d.getUTCMonth()+1,day:d.getUTCDate(),hour:d.getUTCHours(),minute:d.getUTCMinutes(),second:d.getUTCSeconds(),millisecond:d.getUTCMilliseconds()}}__name(tsToObj,"tsToObj"),__name2(tsToObj,"tsToObj");function objToTS(obj,offset2,zone){return fixOffset(objToLocalTS(obj),offset2,zone)}__name(objToTS,"objToTS"),__name2(objToTS,"objToTS");function adjustTime(inst,dur){const oPre=inst.o,year=inst.c.year+Math.trunc(dur.years),month=inst.c.month+Math.trunc(dur.months)+Math.trunc(dur.quarters)*3,c={...inst.c,year,month,day:Math.min(inst.c.day,daysInMonth(year,month))+Math.trunc(dur.days)+Math.trunc(dur.weeks)*7},millisToAdd=Duration.fromObject({years:dur.years-Math.trunc(dur.years),quarters:dur.quarters-Math.trunc(dur.quarters),months:dur.months-Math.trunc(dur.months),weeks:dur.weeks-Math.trunc(dur.weeks),days:dur.days-Math.trunc(dur.days),hours:dur.hours,minutes:dur.minutes,seconds:dur.seconds,milliseconds:dur.milliseconds}).as("milliseconds"),localTS=objToLocalTS(c);let[ts,o]=fixOffset(localTS,oPre,inst.zone);return millisToAdd!==0&&(ts+=millisToAdd,o=inst.zone.offset(ts)),{ts,o}}__name(adjustTime,"adjustTime"),__name2(adjustTime,"adjustTime");function parseDataToDateTime(parsed,parsedZone,opts,format,text,specificOffset){const{setZone,zone}=opts;if(parsed&&Object.keys(parsed).length!==0||parsedZone){const interpretationZone=parsedZone||zone,inst=DateTime.fromObject(parsed,{...opts,zone:interpretationZone,specificOffset});return setZone?inst:inst.setZone(zone)}else return DateTime.invalid(new Invalid("unparsable",`the input "${text}" can't be parsed as ${format}`))}__name(parseDataToDateTime,"parseDataToDateTime"),__name2(parseDataToDateTime,"parseDataToDateTime");function toTechFormat(dt,format,allowZ=!0){return dt.isValid?Formatter.create(Locale.create("en-US"),{allowZ,forceSimple:!0}).formatDateTimeFromString(dt,format):null}__name(toTechFormat,"toTechFormat"),__name2(toTechFormat,"toTechFormat");function toISODate(o,extended){const longFormat=o.c.year>9999||o.c.year<0;let c="";return longFormat&&o.c.year>=0&&(c+="+"),c+=padStart(o.c.year,longFormat?6:4),extended?(c+="-",c+=padStart(o.c.month),c+="-",c+=padStart(o.c.day)):(c+=padStart(o.c.month),c+=padStart(o.c.day)),c}__name(toISODate,"toISODate"),__name2(toISODate,"toISODate");function toISOTime(o,extended,suppressSeconds,suppressMilliseconds,includeOffset,extendedZone){let c=padStart(o.c.hour);return extended?(c+=":",c+=padStart(o.c.minute),(o.c.millisecond!==0||o.c.second!==0||!suppressSeconds)&&(c+=":")):c+=padStart(o.c.minute),(o.c.millisecond!==0||o.c.second!==0||!suppressSeconds)&&(c+=padStart(o.c.second),(o.c.millisecond!==0||!suppressMilliseconds)&&(c+=".",c+=padStart(o.c.millisecond,3))),includeOffset&&(o.isOffsetFixed&&o.offset===0&&!extendedZone?c+="Z":o.o<0?(c+="-",c+=padStart(Math.trunc(-o.o/60)),c+=":",c+=padStart(Math.trunc(-o.o%60))):(c+="+",c+=padStart(Math.trunc(o.o/60)),c+=":",c+=padStart(Math.trunc(o.o%60)))),extendedZone&&(c+="["+o.zone.ianaName+"]"),c}__name(toISOTime,"toISOTime"),__name2(toISOTime,"toISOTime");const defaultUnitValues={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},defaultWeekUnitValues={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},defaultOrdinalUnitValues={ordinal:1,hour:0,minute:0,second:0,millisecond:0},orderedUnits=["year","month","day","hour","minute","second","millisecond"],orderedWeekUnits=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],orderedOrdinalUnits=["year","ordinal","hour","minute","second","millisecond"];function normalizeUnit(unit){const normalized={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[unit.toLowerCase()];if(!normalized)throw new InvalidUnitError(unit);return normalized}__name(normalizeUnit,"normalizeUnit"),__name2(normalizeUnit,"normalizeUnit");function quickDT(obj,opts){const zone=normalizeZone(opts.zone,Settings.defaultZone),loc=Locale.fromObject(opts),tsNow=Settings.now();let ts,o;if(isUndefined(obj.year))ts=tsNow;else{for(const u of orderedUnits)isUndefined(obj[u])&&(obj[u]=defaultUnitValues[u]);const invalid=hasInvalidGregorianData(obj)||hasInvalidTimeData(obj);if(invalid)return DateTime.invalid(invalid);const offsetProvis=zone.offset(tsNow);[ts,o]=objToTS(obj,offsetProvis,zone)}return new DateTime({ts,zone,loc,o})}__name(quickDT,"quickDT"),__name2(quickDT,"quickDT");function diffRelative(start,end,opts){const round=isUndefined(opts.round)?!0:opts.round,format=__name2((c,unit)=>(c=roundTo(c,round||opts.calendary?0:2,!0),end.loc.clone(opts).relFormatter(opts).format(c,unit)),"format"),differ=__name2(unit=>opts.calendary?end.hasSame(start,unit)?0:end.startOf(unit).diff(start.startOf(unit),unit).get(unit):end.diff(start,unit).get(unit),"differ");if(opts.unit)return format(differ(opts.unit),opts.unit);for(const unit of opts.units){const count=differ(unit);if(Math.abs(count)>=1)return format(count,unit)}return format(start>end?-0:0,opts.units[opts.units.length-1])}__name(diffRelative,"diffRelative"),__name2(diffRelative,"diffRelative");function lastOpts(argList){let opts={},args;return argList.length>0&&typeof argList[argList.length-1]=="object"?(opts=argList[argList.length-1],args=Array.from(argList).slice(0,argList.length-1)):args=Array.from(argList),[opts,args]}__name(lastOpts,"lastOpts"),__name2(lastOpts,"lastOpts");const _DateTime=class _DateTime2{static{__name(this,"_DateTime")}constructor(config2){const zone=config2.zone||Settings.defaultZone;let invalid=config2.invalid||(Number.isNaN(config2.ts)?new Invalid("invalid input"):null)||(zone.isValid?null:unsupportedZone(zone));this.ts=isUndefined(config2.ts)?Settings.now():config2.ts;let c=null,o=null;if(!invalid)if(config2.old&&config2.old.ts===this.ts&&config2.old.zone.equals(zone))[c,o]=[config2.old.c,config2.old.o];else{const ot=zone.offset(this.ts);c=tsToObj(this.ts,ot),invalid=Number.isNaN(c.year)?new Invalid("invalid input"):null,c=invalid?null:c,o=invalid?null:ot}this._zone=zone,this.loc=config2.loc||Locale.create(),this.invalid=invalid,this.weekData=null,this.c=c,this.o=o,this.isLuxonDateTime=!0}static now(){return new _DateTime2({})}static local(){const[opts,args]=lastOpts(arguments),[year,month,day,hour,minute,second,millisecond]=args;return quickDT({year,month,day,hour,minute,second,millisecond},opts)}static utc(){const[opts,args]=lastOpts(arguments),[year,month,day,hour,minute,second,millisecond]=args;return opts.zone=FixedOffsetZone.utcInstance,quickDT({year,month,day,hour,minute,second,millisecond},opts)}static fromJSDate(date,options={}){const ts=isDate(date)?date.valueOf():NaN;if(Number.isNaN(ts))return _DateTime2.invalid("invalid input");const zoneToUse=normalizeZone(options.zone,Settings.defaultZone);return zoneToUse.isValid?new _DateTime2({ts,zone:zoneToUse,loc:Locale.fromObject(options)}):_DateTime2.invalid(unsupportedZone(zoneToUse))}static fromMillis(milliseconds,options={}){if(isNumber(milliseconds))return milliseconds<-MAX_DATE||milliseconds>MAX_DATE?_DateTime2.invalid("Timestamp out of range"):new _DateTime2({ts:milliseconds,zone:normalizeZone(options.zone,Settings.defaultZone),loc:Locale.fromObject(options)});throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`)}static fromSeconds(seconds,options={}){if(isNumber(seconds))return new _DateTime2({ts:seconds*1e3,zone:normalizeZone(options.zone,Settings.defaultZone),loc:Locale.fromObject(options)});throw new InvalidArgumentError("fromSeconds requires a numerical input")}static fromObject(obj,opts={}){obj=obj||{};const zoneToUse=normalizeZone(opts.zone,Settings.defaultZone);if(!zoneToUse.isValid)return _DateTime2.invalid(unsupportedZone(zoneToUse));const tsNow=Settings.now(),offsetProvis=isUndefined(opts.specificOffset)?zoneToUse.offset(tsNow):opts.specificOffset,normalized=normalizeObject(obj,normalizeUnit),containsOrdinal=!isUndefined(normalized.ordinal),containsGregorYear=!isUndefined(normalized.year),containsGregorMD=!isUndefined(normalized.month)||!isUndefined(normalized.day),containsGregor=containsGregorYear||containsGregorMD,definiteWeekDef=normalized.weekYear||normalized.weekNumber,loc=Locale.fromObject(opts);if((containsGregor||containsOrdinal)&&definiteWeekDef)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(containsGregorMD&&containsOrdinal)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");const useWeekData=definiteWeekDef||normalized.weekday&&!containsGregor;let units,defaultValues,objNow=tsToObj(tsNow,offsetProvis);useWeekData?(units=orderedWeekUnits,defaultValues=defaultWeekUnitValues,objNow=gregorianToWeek(objNow)):containsOrdinal?(units=orderedOrdinalUnits,defaultValues=defaultOrdinalUnitValues,objNow=gregorianToOrdinal(objNow)):(units=orderedUnits,defaultValues=defaultUnitValues);let foundFirst=!1;for(const u of units){const v=normalized[u];isUndefined(v)?foundFirst?normalized[u]=defaultValues[u]:normalized[u]=objNow[u]:foundFirst=!0}const higherOrderInvalid=useWeekData?hasInvalidWeekData(normalized):containsOrdinal?hasInvalidOrdinalData(normalized):hasInvalidGregorianData(normalized),invalid=higherOrderInvalid||hasInvalidTimeData(normalized);if(invalid)return _DateTime2.invalid(invalid);const gregorian=useWeekData?weekToGregorian(normalized):containsOrdinal?ordinalToGregorian(normalized):normalized,[tsFinal,offsetFinal]=objToTS(gregorian,offsetProvis,zoneToUse),inst=new _DateTime2({ts:tsFinal,zone:zoneToUse,o:offsetFinal,loc});return normalized.weekday&&containsGregor&&obj.weekday!==inst.weekday?_DateTime2.invalid("mismatched weekday",`you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`):inst}static fromISO(text,opts={}){const[vals,parsedZone]=parseISODate(text);return parseDataToDateTime(vals,parsedZone,opts,"ISO 8601",text)}static fromRFC2822(text,opts={}){const[vals,parsedZone]=parseRFC2822Date(text);return parseDataToDateTime(vals,parsedZone,opts,"RFC 2822",text)}static fromHTTP(text,opts={}){const[vals,parsedZone]=parseHTTPDate(text);return parseDataToDateTime(vals,parsedZone,opts,"HTTP",opts)}static fromFormat(text,fmt,opts={}){if(isUndefined(text)||isUndefined(fmt))throw new InvalidArgumentError("fromFormat requires an input string and a format");const{locale=null,numberingSystem=null}=opts,localeToUse=Locale.fromOpts({locale,numberingSystem,defaultToEN:!0}),[vals,parsedZone,specificOffset,invalid]=parseFromTokens(localeToUse,text,fmt);return invalid?_DateTime2.invalid(invalid):parseDataToDateTime(vals,parsedZone,opts,`format ${fmt}`,text,specificOffset)}static fromString(text,fmt,opts={}){return _DateTime2.fromFormat(text,fmt,opts)}static fromSQL(text,opts={}){const[vals,parsedZone]=parseSQL(text);return parseDataToDateTime(vals,parsedZone,opts,"SQL",text)}static invalid(reason,explanation=null){if(!reason)throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");const invalid=reason instanceof Invalid?reason:new Invalid(reason,explanation);if(Settings.throwOnInvalid)throw new InvalidDateTimeError(invalid);return new _DateTime2({invalid})}static isDateTime(o){return o&&o.isLuxonDateTime||!1}static parseFormatForOpts(formatOpts,localeOpts={}){const tokenList=formatOptsToTokens(formatOpts,Locale.fromObject(localeOpts));return tokenList?tokenList.map(t2=>t2?t2.val:null).join(""):null}static expandFormat(fmt,localeOpts={}){return expandMacroTokens(Formatter.parseFormat(fmt),Locale.fromObject(localeOpts)).map(t2=>t2.val).join("")}get(unit){return this[unit]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?possiblyCachedWeekData(this).weekYear:NaN}get weekNumber(){return this.isValid?possiblyCachedWeekData(this).weekNumber:NaN}get weekday(){return this.isValid?possiblyCachedWeekData(this).weekday:NaN}get ordinal(){return this.isValid?gregorianToOrdinal(this.c).ordinal:NaN}get monthShort(){return this.isValid?Info.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Info.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Info.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Info.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const dayMs=864e5,minuteMs=6e4,localTS=objToLocalTS(this.c),oEarlier=this.zone.offset(localTS-dayMs),oLater=this.zone.offset(localTS+dayMs),o1=this.zone.offset(localTS-oEarlier*minuteMs),o2=this.zone.offset(localTS-oLater*minuteMs);if(o1===o2)return[this];const ts1=localTS-o1*minuteMs,ts2=localTS-o2*minuteMs,c1=tsToObj(ts1,o1),c2=tsToObj(ts2,o2);return c1.hour===c2.hour&&c1.minute===c2.minute&&c1.second===c2.second&&c1.millisecond===c2.millisecond?[clone$1(this,{ts:ts1}),clone$1(this,{ts:ts2})]:[this]}get isInLeapYear(){return isLeapYear(this.year)}get daysInMonth(){return daysInMonth(this.year,this.month)}get daysInYear(){return this.isValid?daysInYear(this.year):NaN}get weeksInWeekYear(){return this.isValid?weeksInWeekYear(this.weekYear):NaN}resolvedLocaleOptions(opts={}){const{locale,numberingSystem,calendar}=Formatter.create(this.loc.clone(opts),opts).resolvedOptions(this);return{locale,numberingSystem,outputCalendar:calendar}}toUTC(offset2=0,opts={}){return this.setZone(FixedOffsetZone.instance(offset2),opts)}toLocal(){return this.setZone(Settings.defaultZone)}setZone(zone,{keepLocalTime=!1,keepCalendarTime=!1}={}){if(zone=normalizeZone(zone,Settings.defaultZone),zone.equals(this.zone))return this;if(zone.isValid){let newTS=this.ts;if(keepLocalTime||keepCalendarTime){const offsetGuess=zone.offset(this.ts),asObj=this.toObject();[newTS]=objToTS(asObj,offsetGuess,zone)}return clone$1(this,{ts:newTS,zone})}else return _DateTime2.invalid(unsupportedZone(zone))}reconfigure({locale,numberingSystem,outputCalendar}={}){const loc=this.loc.clone({locale,numberingSystem,outputCalendar});return clone$1(this,{loc})}setLocale(locale){return this.reconfigure({locale})}set(values){if(!this.isValid)return this;const normalized=normalizeObject(values,normalizeUnit),settingWeekStuff=!isUndefined(normalized.weekYear)||!isUndefined(normalized.weekNumber)||!isUndefined(normalized.weekday),containsOrdinal=!isUndefined(normalized.ordinal),containsGregorYear=!isUndefined(normalized.year),containsGregorMD=!isUndefined(normalized.month)||!isUndefined(normalized.day),containsGregor=containsGregorYear||containsGregorMD,definiteWeekDef=normalized.weekYear||normalized.weekNumber;if((containsGregor||containsOrdinal)&&definiteWeekDef)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(containsGregorMD&&containsOrdinal)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");let mixed;settingWeekStuff?mixed=weekToGregorian({...gregorianToWeek(this.c),...normalized}):isUndefined(normalized.ordinal)?(mixed={...this.toObject(),...normalized},isUndefined(normalized.day)&&(mixed.day=Math.min(daysInMonth(mixed.year,mixed.month),mixed.day))):mixed=ordinalToGregorian({...gregorianToOrdinal(this.c),...normalized});const[ts,o]=objToTS(mixed,this.o,this.zone);return clone$1(this,{ts,o})}plus(duration){if(!this.isValid)return this;const dur=Duration.fromDurationLike(duration);return clone$1(this,adjustTime(this,dur))}minus(duration){if(!this.isValid)return this;const dur=Duration.fromDurationLike(duration).negate();return clone$1(this,adjustTime(this,dur))}startOf(unit){if(!this.isValid)return this;const o={},normalizedUnit=Duration.normalizeUnit(unit);switch(normalizedUnit){case"years":o.month=1;case"quarters":case"months":o.day=1;case"weeks":case"days":o.hour=0;case"hours":o.minute=0;case"minutes":o.second=0;case"seconds":o.millisecond=0;break}if(normalizedUnit==="weeks"&&(o.weekday=1),normalizedUnit==="quarters"){const q=Math.ceil(this.month/3);o.month=(q-1)*3+1}return this.set(o)}endOf(unit){return this.isValid?this.plus({[unit]:1}).startOf(unit).minus(1):this}toFormat(fmt,opts={}){return this.isValid?Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this,fmt):INVALID}toLocaleString(formatOpts=DATE_SHORT,opts={}){return this.isValid?Formatter.create(this.loc.clone(opts),formatOpts).formatDateTime(this):INVALID}toLocaleParts(opts={}){return this.isValid?Formatter.create(this.loc.clone(opts),opts).formatDateTimeParts(this):[]}toISO({format="extended",suppressSeconds=!1,suppressMilliseconds=!1,includeOffset=!0,extendedZone=!1}={}){if(!this.isValid)return null;const ext=format==="extended";let c=toISODate(this,ext);return c+="T",c+=toISOTime(this,ext,suppressSeconds,suppressMilliseconds,includeOffset,extendedZone),c}toISODate({format="extended"}={}){return this.isValid?toISODate(this,format==="extended"):null}toISOWeekDate(){return toTechFormat(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds=!1,suppressSeconds=!1,includeOffset=!0,includePrefix=!1,extendedZone=!1,format="extended"}={}){return this.isValid?(includePrefix?"T":"")+toISOTime(this,format==="extended",suppressSeconds,suppressMilliseconds,includeOffset,extendedZone):null}toRFC2822(){return toTechFormat(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return toTechFormat(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?toISODate(this,!0):null}toSQLTime({includeOffset=!0,includeZone=!1,includeOffsetSpace=!0}={}){let fmt="HH:mm:ss.SSS";return(includeZone||includeOffset)&&(includeOffsetSpace&&(fmt+=" "),includeZone?fmt+="z":includeOffset&&(fmt+="ZZ")),toTechFormat(this,fmt,!0)}toSQL(opts={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(opts)}`:null}toString(){return this.isValid?this.toISO():INVALID}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(opts={}){if(!this.isValid)return{};const base2={...this.c};return opts.includeConfig&&(base2.outputCalendar=this.outputCalendar,base2.numberingSystem=this.loc.numberingSystem,base2.locale=this.loc.locale),base2}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(otherDateTime,unit="milliseconds",opts={}){if(!this.isValid||!otherDateTime.isValid)return Duration.invalid("created by diffing an invalid DateTime");const durOpts={locale:this.locale,numberingSystem:this.numberingSystem,...opts},units=maybeArray(unit).map(Duration.normalizeUnit),otherIsLater=otherDateTime.valueOf()>this.valueOf(),earlier=otherIsLater?this:otherDateTime,later=otherIsLater?otherDateTime:this,diffed=diff(earlier,later,units,durOpts);return otherIsLater?diffed.negate():diffed}diffNow(unit="milliseconds",opts={}){return this.diff(_DateTime2.now(),unit,opts)}until(otherDateTime){return this.isValid?Interval.fromDateTimes(this,otherDateTime):this}hasSame(otherDateTime,unit){if(!this.isValid)return!1;const inputMs=otherDateTime.valueOf(),adjustedToZone=this.setZone(otherDateTime.zone,{keepLocalTime:!0});return adjustedToZone.startOf(unit)<=inputMs&&inputMs<=adjustedToZone.endOf(unit)}equals(other){return this.isValid&&other.isValid&&this.valueOf()===other.valueOf()&&this.zone.equals(other.zone)&&this.loc.equals(other.loc)}toRelative(options={}){if(!this.isValid)return null;const base2=options.base||_DateTime2.fromObject({},{zone:this.zone}),padding=options.padding?this<base2?-options.padding:options.padding:0;let units=["years","months","days","hours","minutes","seconds"],unit=options.unit;return Array.isArray(options.unit)&&(units=options.unit,unit=void 0),diffRelative(base2,this.plus(padding),{...options,numeric:"always",units,unit})}toRelativeCalendar(options={}){return this.isValid?diffRelative(options.base||_DateTime2.fromObject({},{zone:this.zone}),this,{...options,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...dateTimes){if(!dateTimes.every(_DateTime2.isDateTime))throw new InvalidArgumentError("min requires all arguments be DateTimes");return bestBy(dateTimes,i=>i.valueOf(),Math.min)}static max(...dateTimes){if(!dateTimes.every(_DateTime2.isDateTime))throw new InvalidArgumentError("max requires all arguments be DateTimes");return bestBy(dateTimes,i=>i.valueOf(),Math.max)}static fromFormatExplain(text,fmt,options={}){const{locale=null,numberingSystem=null}=options,localeToUse=Locale.fromOpts({locale,numberingSystem,defaultToEN:!0});return explainFromTokens(localeToUse,text,fmt)}static fromStringExplain(text,fmt,options={}){return _DateTime2.fromFormatExplain(text,fmt,options)}static get DATE_SHORT(){return DATE_SHORT}static get DATE_MED(){return DATE_MED}static get DATE_MED_WITH_WEEKDAY(){return DATE_MED_WITH_WEEKDAY}static get DATE_FULL(){return DATE_FULL}static get DATE_HUGE(){return DATE_HUGE}static get TIME_SIMPLE(){return TIME_SIMPLE}static get TIME_WITH_SECONDS(){return TIME_WITH_SECONDS}static get TIME_WITH_SHORT_OFFSET(){return TIME_WITH_SHORT_OFFSET}static get TIME_WITH_LONG_OFFSET(){return TIME_WITH_LONG_OFFSET}static get TIME_24_SIMPLE(){return TIME_24_SIMPLE}static get TIME_24_WITH_SECONDS(){return TIME_24_WITH_SECONDS}static get TIME_24_WITH_SHORT_OFFSET(){return TIME_24_WITH_SHORT_OFFSET}static get TIME_24_WITH_LONG_OFFSET(){return TIME_24_WITH_LONG_OFFSET}static get DATETIME_SHORT(){return DATETIME_SHORT}static get DATETIME_SHORT_WITH_SECONDS(){return DATETIME_SHORT_WITH_SECONDS}static get DATETIME_MED(){return DATETIME_MED}static get DATETIME_MED_WITH_SECONDS(){return DATETIME_MED_WITH_SECONDS}static get DATETIME_MED_WITH_WEEKDAY(){return DATETIME_MED_WITH_WEEKDAY}static get DATETIME_FULL(){return DATETIME_FULL}static get DATETIME_FULL_WITH_SECONDS(){return DATETIME_FULL_WITH_SECONDS}static get DATETIME_HUGE(){return DATETIME_HUGE}static get DATETIME_HUGE_WITH_SECONDS(){return DATETIME_HUGE_WITH_SECONDS}};__name2(_DateTime,"DateTime");let DateTime=_DateTime;function friendlyDateTime(dateTimeish){if(DateTime.isDateTime(dateTimeish))return dateTimeish;if(dateTimeish&&dateTimeish.valueOf&&isNumber(dateTimeish.valueOf()))return DateTime.fromJSDate(dateTimeish);if(dateTimeish&&typeof dateTimeish=="object")return DateTime.fromObject(dateTimeish);throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`)}__name(friendlyDateTime,"friendlyDateTime"),__name2(friendlyDateTime,"friendlyDateTime");/**!
* Sortable 1.15.0
* @author RubaXa <trash@rubaxa.org>
* @author owenm <owen23355@gmail.com>
* @license MIT
*/function ownKeys(object,enumerableOnly){var keys2=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys2.push.apply(keys2,symbols)}return keys2}__name(ownKeys,"ownKeys"),__name2(ownKeys,"ownKeys");function _objectSpread2(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};i%2?ownKeys(Object(source),!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}return target}__name(_objectSpread2,"_objectSpread2"),__name2(_objectSpread2,"_objectSpread2");function _typeof(obj){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?_typeof=__name2(function(obj2){return typeof obj2},"_typeof"):_typeof=__name2(function(obj2){return obj2&&typeof Symbol=="function"&&obj2.constructor===Symbol&&obj2!==Symbol.prototype?"symbol":typeof obj2},"_typeof"),_typeof(obj)}__name(_typeof,"_typeof"),__name2(_typeof,"_typeof");function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_defineProperty,"_defineProperty"),__name2(_defineProperty,"_defineProperty");function _extends(){return _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends.apply(this,arguments)}__name(_extends,"_extends"),__name2(_extends,"_extends");function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={},sourceKeys=Object.keys(source),key,i;for(i=0;i<sourceKeys.length;i++)key=sourceKeys[i],!(excluded.indexOf(key)>=0)&&(target[key]=source[key]);return target}__name(_objectWithoutPropertiesLoose,"_objectWithoutPropertiesLoose"),__name2(_objectWithoutPropertiesLoose,"_objectWithoutPropertiesLoose");function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded),key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++)key=sourceSymbolKeys[i],!(excluded.indexOf(key)>=0)&&Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}__name(_objectWithoutProperties,"_objectWithoutProperties"),__name2(_objectWithoutProperties,"_objectWithoutProperties");var version="1.15.0";function userAgent(pattern){if(typeof window<"u"&&window.navigator)return!!navigator.userAgent.match(pattern)}__name(userAgent,"userAgent"),__name2(userAgent,"userAgent");var IE11OrLess=userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),Edge=userAgent(/Edge/i),FireFox=userAgent(/firefox/i),Safari=userAgent(/safari/i)&&!userAgent(/chrome/i)&&!userAgent(/android/i),IOS=userAgent(/iP(ad|od|hone)/i),ChromeForAndroid=userAgent(/chrome/i)&&userAgent(/android/i),captureMode={capture:!1,passive:!1};function on(el,event,fn){el.addEventListener(event,fn,!IE11OrLess&&captureMode)}__name(on,"on"),__name2(on,"on");function off(el,event,fn){el.removeEventListener(event,fn,!IE11OrLess&&captureMode)}__name(off,"off"),__name2(off,"off");function matches(el,selector){if(selector){if(selector[0]===">"&&(selector=selector.substring(1)),el)try{if(el.matches)return el.matches(selector);if(el.msMatchesSelector)return el.msMatchesSelector(selector);if(el.webkitMatchesSelector)return el.webkitMatchesSelector(selector)}catch{return!1}return!1}}__name(matches,"matches"),__name2(matches,"matches");function getParentOrHost(el){return el.host&&el!==document&&el.host.nodeType?el.host:el.parentNode}__name(getParentOrHost,"getParentOrHost"),__name2(getParentOrHost,"getParentOrHost");function closest$1(el,selector,ctx,includeCTX){if(el){ctx=ctx||document;do{if(selector!=null&&(selector[0]===">"?el.parentNode===ctx&&matches(el,selector):matches(el,selector))||includeCTX&&el===ctx)return el;if(el===ctx)break}while(el=getParentOrHost(el))}return null}__name(closest$1,"closest$1"),__name2(closest$1,"closest$1");var R_SPACE=/\s+/g;function toggleClass(el,name2,state){if(el&&name2)if(el.classList)el.classList[state?"add":"remove"](name2);else{var className=(" "+el.className+" ").replace(R_SPACE," ").replace(" "+name2+" "," ");el.className=(className+(state?" "+name2:"")).replace(R_SPACE," ")}}__name(toggleClass,"toggleClass"),__name2(toggleClass,"toggleClass");function css(el,prop,val){var style=el&&el.style;if(style){if(val===void 0)return document.defaultView&&document.defaultView.getComputedStyle?val=document.defaultView.getComputedStyle(el,""):el.currentStyle&&(val=el.currentStyle),prop===void 0?val:val[prop];!(prop in style)&&prop.indexOf("webkit")===-1&&(prop="-webkit-"+prop),style[prop]=val+(typeof val=="string"?"":"px")}}__name(css,"css"),__name2(css,"css");function matrix(el,selfOnly){var appliedTransforms="";if(typeof el=="string")appliedTransforms=el;else do{var transform=css(el,"transform");transform&&transform!=="none"&&(appliedTransforms=transform+" "+appliedTransforms)}while(!selfOnly&&(el=el.parentNode));var matrixFn=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return matrixFn&&new matrixFn(appliedTransforms)}__name(matrix,"matrix"),__name2(matrix,"matrix");function find$1(ctx,tagName,iterator){if(ctx){var list=ctx.getElementsByTagName(tagName),i=0,n2=list.length;if(iterator)for(;i<n2;i++)iterator(list[i],i);return list}return[]}__name(find$1,"find$1"),__name2(find$1,"find$1");function getWindowScrollingElement(){var scrollingElement=document.scrollingElement;return scrollingElement||document.documentElement}__name(getWindowScrollingElement,"getWindowScrollingElement"),__name2(getWindowScrollingElement,"getWindowScrollingElement");function getRect(el,relativeToContainingBlock,relativeToNonStaticParent,undoScale,container){if(!(!el.getBoundingClientRect&&el!==window)){var elRect,top2,left,bottom,right,height,width;if(el!==window&&el.parentNode&&el!==getWindowScrollingElement()?(elRect=el.getBoundingClientRect(),top2=elRect.top,left=elRect.left,bottom=elRect.bottom,right=elRect.right,height=elRect.height,width=elRect.width):(top2=0,left=0,bottom=window.innerHeight,right=window.innerWidth,height=window.innerHeight,width=window.innerWidth),(relativeToContainingBlock||relativeToNonStaticParent)&&el!==window&&(container=container||el.parentNode,!IE11OrLess))do if(container&&container.getBoundingClientRect&&(css(container,"transform")!=="none"||relativeToNonStaticParent&&css(container,"position")!=="static")){var containerRect=container.getBoundingClientRect();top2-=containerRect.top+parseInt(css(container,"border-top-width")),left-=containerRect.left+parseInt(css(container,"border-left-width")),bottom=top2+elRect.height,right=left+elRect.width;break}while(container=container.parentNode);if(undoScale&&el!==window){var elMatrix=matrix(container||el),scaleX=elMatrix&&elMatrix.a,scaleY=elMatrix&&elMatrix.d;elMatrix&&(top2/=scaleY,left/=scaleX,width/=scaleX,height/=scaleY,bottom=top2+height,right=left+width)}return{top:top2,left,bottom,right,width,height}}}__name(getRect,"getRect"),__name2(getRect,"getRect");function isScrolledPast(el,elSide,parentSide){for(var parent=getParentAutoScrollElement(el,!0),elSideVal=getRect(el)[elSide];parent;){var parentSideVal=getRect(parent)[parentSide],visible=void 0;if(parentSide==="top"||parentSide==="left"?visible=elSideVal>=parentSideVal:visible=elSideVal<=parentSideVal,!visible)return parent;if(parent===getWindowScrollingElement())break;parent=getParentAutoScrollElement(parent,!1)}return!1}__name(isScrolledPast,"isScrolledPast"),__name2(isScrolledPast,"isScrolledPast");function getChild(el,childNum,options,includeDragEl){for(var currentChild=0,i=0,children=el.children;i<children.length;){if(children[i].style.display!=="none"&&children[i]!==Sortable.ghost&&(includeDragEl||children[i]!==Sortable.dragged)&&closest$1(children[i],options.draggable,el,!1)){if(currentChild===childNum)return children[i];currentChild++}i++}return null}__name(getChild,"getChild"),__name2(getChild,"getChild");function lastChild(el,selector){for(var last2=el.lastElementChild;last2&&(last2===Sortable.ghost||css(last2,"display")==="none"||selector&&!matches(last2,selector));)last2=last2.previousElementSibling;return last2||null}__name(lastChild,"lastChild"),__name2(lastChild,"lastChild");function index(el,selector){var index2=0;if(!el||!el.parentNode)return-1;for(;el=el.previousElementSibling;)el.nodeName.toUpperCase()!=="TEMPLATE"&&el!==Sortable.clone&&(!selector||matches(el,selector))&&index2++;return index2}__name(index,"index"),__name2(index,"index");function getRelativeScrollOffset(el){var offsetLeft=0,offsetTop=0,winScroller=getWindowScrollingElement();if(el)do{var elMatrix=matrix(el),scaleX=elMatrix.a,scaleY=elMatrix.d;offsetLeft+=el.scrollLeft*scaleX,offsetTop+=el.scrollTop*scaleY}while(el!==winScroller&&(el=el.parentNode));return[offsetLeft,offsetTop]}__name(getRelativeScrollOffset,"getRelativeScrollOffset"),__name2(getRelativeScrollOffset,"getRelativeScrollOffset");function indexOfObject(arr,obj){for(var i in arr)if(arr.hasOwnProperty(i)){for(var key in obj)if(obj.hasOwnProperty(key)&&obj[key]===arr[i][key])return Number(i)}return-1}__name(indexOfObject,"indexOfObject"),__name2(indexOfObject,"indexOfObject");function getParentAutoScrollElement(el,includeSelf){if(!el||!el.getBoundingClientRect)return getWindowScrollingElement();var elem=el,gotSelf=!1;do if(elem.clientWidth<elem.scrollWidth||elem.clientHeight<elem.scrollHeight){var elemCSS=css(elem);if(elem.clientWidth<elem.scrollWidth&&(elemCSS.overflowX=="auto"||elemCSS.overflowX=="scroll")||elem.clientHeight<elem.scrollHeight&&(elemCSS.overflowY=="auto"||elemCSS.overflowY=="scroll")){if(!elem.getBoundingClientRect||elem===document.body)return getWindowScrollingElement();if(gotSelf||includeSelf)return elem;gotSelf=!0}}while(elem=elem.parentNode);return getWindowScrollingElement()}__name(getParentAutoScrollElement,"getParentAutoScrollElement"),__name2(getParentAutoScrollElement,"getParentAutoScrollElement");function extend$1(dst,src){if(dst&&src)for(var key in src)src.hasOwnProperty(key)&&(dst[key]=src[key]);return dst}__name(extend$1,"extend$1"),__name2(extend$1,"extend$1");function isRectEqual(rect1,rect2){return Math.round(rect1.top)===Math.round(rect2.top)&&Math.round(rect1.left)===Math.round(rect2.left)&&Math.round(rect1.height)===Math.round(rect2.height)&&Math.round(rect1.width)===Math.round(rect2.width)}__name(isRectEqual,"isRectEqual"),__name2(isRectEqual,"isRectEqual");var _throttleTimeout;function throttle(callback,ms){return function(){if(!_throttleTimeout){var args=arguments,_this=this;args.length===1?callback.call(_this,args[0]):callback.apply(_this,args),_throttleTimeout=setTimeout(function(){_throttleTimeout=void 0},ms)}}}__name(throttle,"throttle"),__name2(throttle,"throttle");function cancelThrottle(){clearTimeout(_throttleTimeout),_throttleTimeout=void 0}__name(cancelThrottle,"cancelThrottle"),__name2(cancelThrottle,"cancelThrottle");function scrollBy(el,x,y){el.scrollLeft+=x,el.scrollTop+=y}__name(scrollBy,"scrollBy"),__name2(scrollBy,"scrollBy");function clone(el){var Polymer=window.Polymer,$=window.jQuery||window.Zepto;return Polymer&&Polymer.dom?Polymer.dom(el).cloneNode(!0):$?$(el).clone(!0)[0]:el.cloneNode(!0)}__name(clone,"clone"),__name2(clone,"clone");var expando="Sortable"+new Date().getTime();function AnimationStateManager(){var animationStates=[],animationCallbackId;return{captureAnimationState:__name2(__name(function(){if(animationStates=[],!!this.options.animation){var children=[].slice.call(this.el.children);children.forEach(function(child){if(!(css(child,"display")==="none"||child===Sortable.ghost)){animationStates.push({target:child,rect:getRect(child)});var fromRect=_objectSpread2({},animationStates[animationStates.length-1].rect);if(child.thisAnimationDuration){var childMatrix=matrix(child,!0);childMatrix&&(fromRect.top-=childMatrix.f,fromRect.left-=childMatrix.e)}child.fromRect=fromRect}})}},"captureAnimationState"),"captureAnimationState"),addAnimationState:__name2(__name(function(state){animationStates.push(state)},"addAnimationState"),"addAnimationState"),removeAnimationState:__name2(__name(function(target){animationStates.splice(indexOfObject(animationStates,{target}),1)},"removeAnimationState"),"removeAnimationState"),animateAll:__name2(__name(function(callback){var _this=this;if(!this.options.animation){clearTimeout(animationCallbackId),typeof callback=="function"&&callback();return}var animating=!1,animationTime=0;animationStates.forEach(function(state){var time=0,target=state.target,fromRect=target.fromRect,toRect=getRect(target),prevFromRect=target.prevFromRect,prevToRect=target.prevToRect,animatingRect=state.rect,targetMatrix=matrix(target,!0);targetMatrix&&(toRect.top-=targetMatrix.f,toRect.left-=targetMatrix.e),target.toRect=toRect,target.thisAnimationDuration&&isRectEqual(prevFromRect,toRect)&&!isRectEqual(fromRect,toRect)&&(animatingRect.top-toRect.top)/(animatingRect.left-toRect.left)===(fromRect.top-toRect.top)/(fromRect.left-toRect.left)&&(time=calculateRealTime(animatingRect,prevFromRect,prevToRect,_this.options)),isRectEqual(toRect,fromRect)||(target.prevFromRect=fromRect,target.prevToRect=toRect,time||(time=_this.options.animation),_this.animate(target,animatingRect,toRect,time)),time&&(animating=!0,animationTime=Math.max(animationTime,time),clearTimeout(target.animationResetTimer),target.animationResetTimer=setTimeout(function(){target.animationTime=0,target.prevFromRect=null,target.fromRect=null,target.prevToRect=null,target.thisAnimationDuration=null},time),target.thisAnimationDuration=time)}),clearTimeout(animationCallbackId),animating?animationCallbackId=setTimeout(function(){typeof callback=="function"&&callback()},animationTime):typeof callback=="function"&&callback(),animationStates=[]},"animateAll"),"animateAll"),animate:__name2(__name(function(target,currentRect,toRect,duration){if(duration){css(target,"transition",""),css(target,"transform","");var elMatrix=matrix(this.el),scaleX=elMatrix&&elMatrix.a,scaleY=elMatrix&&elMatrix.d,translateX=(currentRect.left-toRect.left)/(scaleX||1),translateY=(currentRect.top-toRect.top)/(scaleY||1);target.animatingX=!!translateX,target.animatingY=!!translateY,css(target,"transform","translate3d("+translateX+"px,"+translateY+"px,0)"),this.forRepaintDummy=repaint(target),css(target,"transition","transform "+duration+"ms"+(this.options.easing?" "+this.options.easing:"")),css(target,"transform","translate3d(0,0,0)"),typeof target.animated=="number"&&clearTimeout(target.animated),target.animated=setTimeout(function(){css(target,"transition",""),css(target,"transform",""),target.animated=!1,target.animatingX=!1,target.animatingY=!1},duration)}},"animate"),"animate")}}__name(AnimationStateManager,"AnimationStateManager"),__name2(AnimationStateManager,"AnimationStateManager");function repaint(target){return target.offsetWidth}__name(repaint,"repaint"),__name2(repaint,"repaint");function calculateRealTime(animatingRect,fromRect,toRect,options){return Math.sqrt(Math.pow(fromRect.top-animatingRect.top,2)+Math.pow(fromRect.left-animatingRect.left,2))/Math.sqrt(Math.pow(fromRect.top-toRect.top,2)+Math.pow(fromRect.left-toRect.left,2))*options.animation}__name(calculateRealTime,"calculateRealTime"),__name2(calculateRealTime,"calculateRealTime");var plugins=[],defaults$2={initializeByDefault:!0},PluginManager={mount:__name2(__name(function(plugin){for(var option2 in defaults$2)defaults$2.hasOwnProperty(option2)&&!(option2 in plugin)&&(plugin[option2]=defaults$2[option2]);plugins.forEach(function(p){if(p.pluginName===plugin.pluginName)throw"Sortable: Cannot mount plugin ".concat(plugin.pluginName," more than once")}),plugins.push(plugin)},"mount"),"mount"),pluginEvent:__name2(__name(function(eventName,sortable,evt){var _this=this;this.eventCanceled=!1,evt.cancel=function(){_this.eventCanceled=!0};var eventNameGlobal=eventName+"Global";plugins.forEach(function(plugin){sortable[plugin.pluginName]&&(sortable[plugin.pluginName][eventNameGlobal]&&sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({sortable},evt)),sortable.options[plugin.pluginName]&&sortable[plugin.pluginName][eventName]&&sortable[plugin.pluginName][eventName](_objectSpread2({sortable},evt)))})},"pluginEvent"),"pluginEvent"),initializePlugins:__name2(__name(function(sortable,el,defaults2,options){plugins.forEach(function(plugin){var pluginName=plugin.pluginName;if(!(!sortable.options[pluginName]&&!plugin.initializeByDefault)){var initialized=new plugin(sortable,el,sortable.options);initialized.sortable=sortable,initialized.options=sortable.options,sortable[pluginName]=initialized,_extends(defaults2,initialized.defaults)}});for(var option2 in sortable.options)if(sortable.options.hasOwnProperty(option2)){var modified=this.modifyOption(sortable,option2,sortable.options[option2]);typeof modified<"u"&&(sortable.options[option2]=modified)}},"initializePlugins"),"initializePlugins"),getEventProperties:__name2(__name(function(name2,sortable){var eventProperties={};return plugins.forEach(function(plugin){typeof plugin.eventProperties=="function"&&_extends(eventProperties,plugin.eventProperties.call(sortable[plugin.pluginName],name2))}),eventProperties},"getEventProperties"),"getEventProperties"),modifyOption:__name2(__name(function(sortable,name2,value){var modifiedValue;return plugins.forEach(function(plugin){sortable[plugin.pluginName]&&plugin.optionListeners&&typeof plugin.optionListeners[name2]=="function"&&(modifiedValue=plugin.optionListeners[name2].call(sortable[plugin.pluginName],value))}),modifiedValue},"modifyOption"),"modifyOption")};function dispatchEvent$1(_ref){var sortable=_ref.sortable,rootEl2=_ref.rootEl,name2=_ref.name,targetEl=_ref.targetEl,cloneEl2=_ref.cloneEl,toEl=_ref.toEl,fromEl=_ref.fromEl,oldIndex2=_ref.oldIndex,newIndex2=_ref.newIndex,oldDraggableIndex2=_ref.oldDraggableIndex,newDraggableIndex2=_ref.newDraggableIndex,originalEvent=_ref.originalEvent,putSortable2=_ref.putSortable,extraEventProperties=_ref.extraEventProperties;if(sortable=sortable||rootEl2&&rootEl2[expando],!!sortable){var evt,options=sortable.options,onName="on"+name2.charAt(0).toUpperCase()+name2.substr(1);window.CustomEvent&&!IE11OrLess&&!Edge?evt=new CustomEvent(name2,{bubbles:!0,cancelable:!0}):(evt=document.createEvent("Event"),evt.initEvent(name2,!0,!0)),evt.to=toEl||rootEl2,evt.from=fromEl||rootEl2,evt.item=targetEl||rootEl2,evt.clone=cloneEl2,evt.oldIndex=oldIndex2,evt.newIndex=newIndex2,evt.oldDraggableIndex=oldDraggableIndex2,evt.newDraggableIndex=newDraggableIndex2,evt.originalEvent=originalEvent,evt.pullMode=putSortable2?putSortable2.lastPutMode:void 0;var allEventProperties=_objectSpread2(_objectSpread2({},extraEventProperties),PluginManager.getEventProperties(name2,sortable));for(var option2 in allEventProperties)evt[option2]=allEventProperties[option2];rootEl2&&rootEl2.dispatchEvent(evt),options[onName]&&options[onName].call(sortable,evt)}}__name(dispatchEvent$1,"dispatchEvent$1"),__name2(dispatchEvent$1,"dispatchEvent$1");var _excluded=["evt"],pluginEvent2=__name2(__name(function(eventName,sortable){var _ref=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},originalEvent=_ref.evt,data=_objectWithoutProperties(_ref,_excluded);PluginManager.pluginEvent.bind(Sortable)(eventName,sortable,_objectSpread2({dragEl,parentEl,ghostEl,rootEl,nextEl,lastDownEl,cloneEl,cloneHidden,dragStarted:moved,putSortable,activeSortable:Sortable.active,originalEvent,oldIndex,oldDraggableIndex,newIndex,newDraggableIndex,hideGhostForTarget:_hideGhostForTarget,unhideGhostForTarget:_unhideGhostForTarget,cloneNowHidden:__name2(__name(function(){cloneHidden=!0},"cloneNowHidden"),"cloneNowHidden"),cloneNowShown:__name2(__name(function(){cloneHidden=!1},"cloneNowShown"),"cloneNowShown"),dispatchSortableEvent:__name2(__name(function(name2){_dispatchEvent({sortable,name:name2,originalEvent})},"dispatchSortableEvent"),"dispatchSortableEvent")},data))},"pluginEvent3"),"pluginEvent");function _dispatchEvent(info){dispatchEvent$1(_objectSpread2({putSortable,cloneEl,targetEl:dragEl,rootEl,oldIndex,oldDraggableIndex,newIndex,newDraggableIndex},info))}__name(_dispatchEvent,"_dispatchEvent"),__name2(_dispatchEvent,"_dispatchEvent");var dragEl,parentEl,ghostEl,rootEl,nextEl,lastDownEl,cloneEl,cloneHidden,oldIndex,newIndex,oldDraggableIndex,newDraggableIndex,activeGroup,putSortable,awaitingDragStarted=!1,ignoreNextClick=!1,sortables=[],tapEvt,touchEvt,lastDx,lastDy,tapDistanceLeft,tapDistanceTop,moved,lastTarget,lastDirection,pastFirstInvertThresh=!1,isCircumstantialInvert=!1,targetMoveDistance,ghostRelativeParent,ghostRelativeParentInitialScroll=[],_silent=!1,savedInputChecked=[],documentExists=typeof document<"u",PositionGhostAbsolutely=IOS,CSSFloatProperty=Edge||IE11OrLess?"cssFloat":"float",supportDraggable=documentExists&&!ChromeForAndroid&&!IOS&&"draggable"in document.createElement("div"),supportCssPointerEvents=function(){if(documentExists){if(IE11OrLess)return!1;var el=document.createElement("x");return el.style.cssText="pointer-events:auto",el.style.pointerEvents==="auto"}}(),_detectDirection=__name2(__name(function(el,options){var elCSS=css(el),elWidth=parseInt(elCSS.width)-parseInt(elCSS.paddingLeft)-parseInt(elCSS.paddingRight)-parseInt(elCSS.borderLeftWidth)-parseInt(elCSS.borderRightWidth),child1=getChild(el,0,options),child2=getChild(el,1,options),firstChildCSS=child1&&css(child1),secondChildCSS=child2&&css(child2),firstChildWidth=firstChildCSS&&parseInt(firstChildCSS.marginLeft)+parseInt(firstChildCSS.marginRight)+getRect(child1).width,secondChildWidth=secondChildCSS&&parseInt(secondChildCSS.marginLeft)+parseInt(secondChildCSS.marginRight)+getRect(child2).width;if(elCSS.display==="flex")return elCSS.flexDirection==="column"||elCSS.flexDirection==="column-reverse"?"vertical":"horizontal";if(elCSS.display==="grid")return elCSS.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(child1&&firstChildCSS.float&&firstChildCSS.float!=="none"){var touchingSideChild2=firstChildCSS.float==="left"?"left":"right";return child2&&(secondChildCSS.clear==="both"||secondChildCSS.clear===touchingSideChild2)?"vertical":"horizontal"}return child1&&(firstChildCSS.display==="block"||firstChildCSS.display==="flex"||firstChildCSS.display==="table"||firstChildCSS.display==="grid"||firstChildWidth>=elWidth&&elCSS[CSSFloatProperty]==="none"||child2&&elCSS[CSSFloatProperty]==="none"&&firstChildWidth+secondChildWidth>elWidth)?"vertical":"horizontal"},"_detectDirection2"),"_detectDirection"),_dragElInRowColumn=__name2(__name(function(dragRect,targetRect,vertical){var dragElS1Opp=vertical?dragRect.left:dragRect.top,dragElS2Opp=vertical?dragRect.right:dragRect.bottom,dragElOppLength=vertical?dragRect.width:dragRect.height,targetS1Opp=vertical?targetRect.left:targetRect.top,targetS2Opp=vertical?targetRect.right:targetRect.bottom,targetOppLength=vertical?targetRect.width:targetRect.height;return dragElS1Opp===targetS1Opp||dragElS2Opp===targetS2Opp||dragElS1Opp+dragElOppLength/2===targetS1Opp+targetOppLength/2},"_dragElInRowColumn2"),"_dragElInRowColumn"),_detectNearestEmptySortable=__name2(__name(function(x,y){var ret;return sortables.some(function(sortable){var threshold=sortable[expando].options.emptyInsertThreshold;if(!(!threshold||lastChild(sortable))){var rect=getRect(sortable),insideHorizontally=x>=rect.left-threshold&&x<=rect.right+threshold,insideVertically=y>=rect.top-threshold&&y<=rect.bottom+threshold;if(insideHorizontally&&insideVertically)return ret=sortable}}),ret},"_detectNearestEmptySortable2"),"_detectNearestEmptySortable"),_prepareGroup=__name2(__name(function(options){function toFn(value,pull){return function(to,from,dragEl2,evt){var sameGroup=to.options.group.name&&from.options.group.name&&to.options.group.name===from.options.group.name;if(value==null&&(pull||sameGroup))return!0;if(value==null||value===!1)return!1;if(pull&&value==="clone")return value;if(typeof value=="function")return toFn(value(to,from,dragEl2,evt),pull)(to,from,dragEl2,evt);var otherGroup=(pull?to:from).options.group.name;return value===!0||typeof value=="string"&&value===otherGroup||value.join&&value.indexOf(otherGroup)>-1}}__name(toFn,"toFn"),__name2(toFn,"toFn");var group={},originalGroup=options.group;(!originalGroup||_typeof(originalGroup)!="object")&&(originalGroup={name:originalGroup}),group.name=originalGroup.name,group.checkPull=toFn(originalGroup.pull,!0),group.checkPut=toFn(originalGroup.put),group.revertClone=originalGroup.revertClone,options.group=group},"_prepareGroup2"),"_prepareGroup"),_hideGhostForTarget=__name2(__name(function(){!supportCssPointerEvents&&ghostEl&&css(ghostEl,"display","none")},"_hideGhostForTarget2"),"_hideGhostForTarget"),_unhideGhostForTarget=__name2(__name(function(){!supportCssPointerEvents&&ghostEl&&css(ghostEl,"display","")},"_unhideGhostForTarget2"),"_unhideGhostForTarget");documentExists&&!ChromeForAndroid&&document.addEventListener("click",function(evt){if(ignoreNextClick)return evt.preventDefault(),evt.stopPropagation&&evt.stopPropagation(),evt.stopImmediatePropagation&&evt.stopImmediatePropagation(),ignoreNextClick=!1,!1},!0);var nearestEmptyInsertDetectEvent=__name2(__name(function(evt){if(dragEl){evt=evt.touches?evt.touches[0]:evt;var nearest=_detectNearestEmptySortable(evt.clientX,evt.clientY);if(nearest){var event={};for(var i in evt)evt.hasOwnProperty(i)&&(event[i]=evt[i]);event.target=event.rootEl=nearest,event.preventDefault=void 0,event.stopPropagation=void 0,nearest[expando]._onDragOver(event)}}},"nearestEmptyInsertDetectEvent2"),"nearestEmptyInsertDetectEvent"),_checkOutsideTargetEl=__name2(__name(function(evt){dragEl&&dragEl.parentNode[expando]._isOutsideThisEl(evt.target)},"_checkOutsideTargetEl2"),"_checkOutsideTargetEl");function Sortable(el,options){if(!(el&&el.nodeType&&el.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el));this.el=el,this.options=options=_extends({},options),el[expando]=this;var defaults2={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(el.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:__name2(__name(function(){return _detectDirection(el,this.options)},"direction"),"direction"),ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:__name2(__name(function(dataTransfer,dragEl2){dataTransfer.setData("Text",dragEl2.textContent)},"setData"),"setData"),dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:Sortable.supportPointer!==!1&&"PointerEvent"in window&&!Safari,emptyInsertThreshold:5};PluginManager.initializePlugins(this,el,defaults2);for(var name2 in defaults2)!(name2 in options)&&(options[name2]=defaults2[name2]);_prepareGroup(options);for(var fn in this)fn.charAt(0)==="_"&&typeof this[fn]=="function"&&(this[fn]=this[fn].bind(this));this.nativeDraggable=options.forceFallback?!1:supportDraggable,this.nativeDraggable&&(this.options.touchStartThreshold=1),options.supportPointer?on(el,"pointerdown",this._onTapStart):(on(el,"mousedown",this._onTapStart),on(el,"touchstart",this._onTapStart)),this.nativeDraggable&&(on(el,"dragover",this),on(el,"dragenter",this)),sortables.push(this.el),options.store&&options.store.get&&this.sort(options.store.get(this)||[]),_extends(this,AnimationStateManager())}__name(Sortable,"Sortable"),__name2(Sortable,"Sortable"),Sortable.prototype={constructor:Sortable,_isOutsideThisEl:__name2(__name(function(target){!this.el.contains(target)&&target!==this.el&&(lastTarget=null)},"_isOutsideThisEl"),"_isOutsideThisEl"),_getDirection:__name2(__name(function(evt,target){return typeof this.options.direction=="function"?this.options.direction.call(this,evt,target,dragEl):this.options.direction},"_getDirection"),"_getDirection"),_onTapStart:__name2(__name(function(evt){if(evt.cancelable){var _this=this,el=this.el,options=this.options,preventOnFilter=options.preventOnFilter,type=evt.type,touch=evt.touches&&evt.touches[0]||evt.pointerType&&evt.pointerType==="touch"&&evt,target=(touch||evt).target,originalTarget=evt.target.shadowRoot&&(evt.path&&evt.path[0]||evt.composedPath&&evt.composedPath()[0])||target,filter2=options.filter;if(_saveInputCheckedState(el),!dragEl&&!(/mousedown|pointerdown/.test(type)&&evt.button!==0||options.disabled)&&!originalTarget.isContentEditable&&!(!this.nativeDraggable&&Safari&&target&&target.tagName.toUpperCase()==="SELECT")&&(target=closest$1(target,options.draggable,el,!1),!(target&&target.animated)&&lastDownEl!==target)){if(oldIndex=index(target),oldDraggableIndex=index(target,options.draggable),typeof filter2=="function"){if(filter2.call(this,evt,target,this)){_dispatchEvent({sortable:_this,rootEl:originalTarget,name:"filter",targetEl:target,toEl:el,fromEl:el}),pluginEvent2("filter",_this,{evt}),preventOnFilter&&evt.cancelable&&evt.preventDefault();return}}else if(filter2&&(filter2=filter2.split(",").some(function(criteria){if(criteria=closest$1(originalTarget,criteria.trim(),el,!1),criteria)return _dispatchEvent({sortable:_this,rootEl:criteria,name:"filter",targetEl:target,fromEl:el,toEl:el}),pluginEvent2("filter",_this,{evt}),!0}),filter2)){preventOnFilter&&evt.cancelable&&evt.preventDefault();return}options.handle&&!closest$1(originalTarget,options.handle,el,!1)||this._prepareDragStart(evt,touch,target)}}},"_onTapStart"),"_onTapStart"),_prepareDragStart:__name2(__name(function(evt,touch,target){var _this=this,el=_this.el,options=_this.options,ownerDocument=el.ownerDocument,dragStartFn;if(target&&!dragEl&&target.parentNode===el){var dragRect=getRect(target);if(rootEl=el,dragEl=target,parentEl=dragEl.parentNode,nextEl=dragEl.nextSibling,lastDownEl=target,activeGroup=options.group,Sortable.dragged=dragEl,tapEvt={target:dragEl,clientX:(touch||evt).clientX,clientY:(touch||evt).clientY},tapDistanceLeft=tapEvt.clientX-dragRect.left,tapDistanceTop=tapEvt.clientY-dragRect.top,this._lastX=(touch||evt).clientX,this._lastY=(touch||evt).clientY,dragEl.style["will-change"]="all",dragStartFn=__name2(__name(function(){if(pluginEvent2("delayEnded",_this,{evt}),Sortable.eventCanceled){_this._onDrop();return}_this._disableDelayedDragEvents(),!FireFox&&_this.nativeDraggable&&(dragEl.draggable=!0),_this._triggerDragStart(evt,touch),_dispatchEvent({sortable:_this,name:"choose",originalEvent:evt}),toggleClass(dragEl,options.chosenClass,!0)},"dragStartFn2"),"dragStartFn"),options.ignore.split(",").forEach(function(criteria){find$1(dragEl,criteria.trim(),_disableDraggable)}),on(ownerDocument,"dragover",nearestEmptyInsertDetectEvent),on(ownerDocument,"mousemove",nearestEmptyInsertDetectEvent),on(ownerDocument,"touchmove",nearestEmptyInsertDetectEvent),on(ownerDocument,"mouseup",_this._onDrop),on(ownerDocument,"touchend",_this._onDrop),on(ownerDocument,"touchcancel",_this._onDrop),FireFox&&this.nativeDraggable&&(this.options.touchStartThreshold=4,dragEl.draggable=!0),pluginEvent2("delayStart",this,{evt}),options.delay&&(!options.delayOnTouchOnly||touch)&&(!this.nativeDraggable||!(Edge||IE11OrLess))){if(Sortable.eventCanceled){this._onDrop();return}on(ownerDocument,"mouseup",_this._disableDelayedDrag),on(ownerDocument,"touchend",_this._disableDelayedDrag),on(ownerDocument,"touchcancel",_this._disableDelayedDrag),on(ownerDocument,"mousemove",_this._delayedDragTouchMoveHandler),on(ownerDocument,"touchmove",_this._delayedDragTouchMoveHandler),options.supportPointer&&on(ownerDocument,"pointermove",_this._delayedDragTouchMoveHandler),_this._dragStartTimer=setTimeout(dragStartFn,options.delay)}else dragStartFn()}},"_prepareDragStart"),"_prepareDragStart"),_delayedDragTouchMoveHandler:__name2(__name(function(e){var touch=e.touches?e.touches[0]:e;Math.max(Math.abs(touch.clientX-this._lastX),Math.abs(touch.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},"_delayedDragTouchMoveHandler"),"_delayedDragTouchMoveHandler"),_disableDelayedDrag:__name2(__name(function(){dragEl&&_disableDraggable(dragEl),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},"_disableDelayedDrag"),"_disableDelayedDrag"),_disableDelayedDragEvents:__name2(__name(function(){var ownerDocument=this.el.ownerDocument;off(ownerDocument,"mouseup",this._disableDelayedDrag),off(ownerDocument,"touchend",this._disableDelayedDrag),off(ownerDocument,"touchcancel",this._disableDelayedDrag),off(ownerDocument,"mousemove",this._delayedDragTouchMoveHandler),off(ownerDocument,"touchmove",this._delayedDragTouchMoveHandler),off(ownerDocument,"pointermove",this._delayedDragTouchMoveHandler)},"_disableDelayedDragEvents"),"_disableDelayedDragEvents"),_triggerDragStart:__name2(__name(function(evt,touch){touch=touch||evt.pointerType=="touch"&&evt,!this.nativeDraggable||touch?this.options.supportPointer?on(document,"pointermove",this._onTouchMove):touch?on(document,"touchmove",this._onTouchMove):on(document,"mousemove",this._onTouchMove):(on(dragEl,"dragend",this),on(rootEl,"dragstart",this._onDragStart));try{document.selection?_nextTick(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},"_triggerDragStart"),"_triggerDragStart"),_dragStarted:__name2(__name(function(fallback,evt){if(awaitingDragStarted=!1,rootEl&&dragEl){pluginEvent2("dragStarted",this,{evt}),this.nativeDraggable&&on(document,"dragover",_checkOutsideTargetEl);var options=this.options;!fallback&&toggleClass(dragEl,options.dragClass,!1),toggleClass(dragEl,options.ghostClass,!0),Sortable.active=this,fallback&&this._appendGhost(),_dispatchEvent({sortable:this,name:"start",originalEvent:evt})}else this._nulling()},"_dragStarted"),"_dragStarted"),_emulateDragOver:__name2(__name(function(){if(touchEvt){this._lastX=touchEvt.clientX,this._lastY=touchEvt.clientY,_hideGhostForTarget();for(var target=document.elementFromPoint(touchEvt.clientX,touchEvt.clientY),parent=target;target&&target.shadowRoot&&(target=target.shadowRoot.elementFromPoint(touchEvt.clientX,touchEvt.clientY),target!==parent);)parent=target;if(dragEl.parentNode[expando]._isOutsideThisEl(target),parent)do{if(parent[expando]){var inserted=void 0;if(inserted=parent[expando]._onDragOver({clientX:touchEvt.clientX,clientY:touchEvt.clientY,target,rootEl:parent}),inserted&&!this.options.dragoverBubble)break}target=parent}while(parent=parent.parentNode);_unhideGhostForTarget()}},"_emulateDragOver"),"_emulateDragOver"),_onTouchMove:__name2(__name(function(evt){if(tapEvt){var options=this.options,fallbackTolerance=options.fallbackTolerance,fallbackOffset=options.fallbackOffset,touch=evt.touches?evt.touches[0]:evt,ghostMatrix=ghostEl&&matrix(ghostEl,!0),scaleX=ghostEl&&ghostMatrix&&ghostMatrix.a,scaleY=ghostEl&&ghostMatrix&&ghostMatrix.d,relativeScrollOffset=PositionGhostAbsolutely&&ghostRelativeParent&&getRelativeScrollOffset(ghostRelativeParent),dx=(touch.clientX-tapEvt.clientX+fallbackOffset.x)/(scaleX||1)+(relativeScrollOffset?relativeScrollOffset[0]-ghostRelativeParentInitialScroll[0]:0)/(scaleX||1),dy=(touch.clientY-tapEvt.clientY+fallbackOffset.y)/(scaleY||1)+(relativeScrollOffset?relativeScrollOffset[1]-ghostRelativeParentInitialScroll[1]:0)/(scaleY||1);if(!Sortable.active&&!awaitingDragStarted){if(fallbackTolerance&&Math.max(Math.abs(touch.clientX-this._lastX),Math.abs(touch.clientY-this._lastY))<fallbackTolerance)return;this._onDragStart(evt,!0)}if(ghostEl){ghostMatrix?(ghostMatrix.e+=dx-(lastDx||0),ghostMatrix.f+=dy-(lastDy||0)):ghostMatrix={a:1,b:0,c:0,d:1,e:dx,f:dy};var cssMatrix="matrix(".concat(ghostMatrix.a,",").concat(ghostMatrix.b,",").concat(ghostMatrix.c,",").concat(ghostMatrix.d,",").concat(ghostMatrix.e,",").concat(ghostMatrix.f,")");css(ghostEl,"webkitTransform",cssMatrix),css(ghostEl,"mozTransform",cssMatrix),css(ghostEl,"msTransform",cssMatrix),css(ghostEl,"transform",cssMatrix),lastDx=dx,lastDy=dy,touchEvt=touch}evt.cancelable&&evt.preventDefault()}},"_onTouchMove"),"_onTouchMove"),_appendGhost:__name2(__name(function(){if(!ghostEl){var container=this.options.fallbackOnBody?document.body:rootEl,rect=getRect(dragEl,!0,PositionGhostAbsolutely,!0,container),options=this.options;if(PositionGhostAbsolutely){for(ghostRelativeParent=container;css(ghostRelativeParent,"position")==="static"&&css(ghostRelativeParent,"transform")==="none"&&ghostRelativeParent!==document;)ghostRelativeParent=ghostRelativeParent.parentNode;ghostRelativeParent!==document.body&&ghostRelativeParent!==document.documentElement?(ghostRelativeParent===document&&(ghostRelativeParent=getWindowScrollingElement()),rect.top+=ghostRelativeParent.scrollTop,rect.left+=ghostRelativeParent.scrollLeft):ghostRelativeParent=getWindowScrollingElement(),ghostRelativeParentInitialScroll=getRelativeScrollOffset(ghostRelativeParent)}ghostEl=dragEl.cloneNode(!0),toggleClass(ghostEl,options.ghostClass,!1),toggleClass(ghostEl,options.fallbackClass,!0),toggleClass(ghostEl,options.dragClass,!0),css(ghostEl,"transition",""),css(ghostEl,"transform",""),css(ghostEl,"box-sizing","border-box"),css(ghostEl,"margin",0),css(ghostEl,"top",rect.top),css(ghostEl,"left",rect.left),css(ghostEl,"width",rect.width),css(ghostEl,"height",rect.height),css(ghostEl,"opacity","0.8"),css(ghostEl,"position",PositionGhostAbsolutely?"absolute":"fixed"),css(ghostEl,"zIndex","100000"),css(ghostEl,"pointerEvents","none"),Sortable.ghost=ghostEl,container.appendChild(ghostEl),css(ghostEl,"transform-origin",tapDistanceLeft/parseInt(ghostEl.style.width)*100+"% "+tapDistanceTop/parseInt(ghostEl.style.height)*100+"%")}},"_appendGhost"),"_appendGhost"),_onDragStart:__name2(__name(function(evt,fallback){var _this=this,dataTransfer=evt.dataTransfer,options=_this.options;if(pluginEvent2("dragStart",this,{evt}),Sortable.eventCanceled){this._onDrop();return}pluginEvent2("setupClone",this),Sortable.eventCanceled||(cloneEl=clone(dragEl),cloneEl.removeAttribute("id"),cloneEl.draggable=!1,cloneEl.style["will-change"]="",this._hideClone(),toggleClass(cloneEl,this.options.chosenClass,!1),Sortable.clone=cloneEl),_this.cloneId=_nextTick(function(){pluginEvent2("clone",_this),!Sortable.eventCanceled&&(_this.options.removeCloneOnHide||rootEl.insertBefore(cloneEl,dragEl),_this._hideClone(),_dispatchEvent({sortable:_this,name:"clone"}))}),!fallback&&toggleClass(dragEl,options.dragClass,!0),fallback?(ignoreNextClick=!0,_this._loopId=setInterval(_this._emulateDragOver,50)):(off(document,"mouseup",_this._onDrop),off(document,"touchend",_this._onDrop),off(document,"touchcancel",_this._onDrop),dataTransfer&&(dataTransfer.effectAllowed="move",options.setData&&options.setData.call(_this,dataTransfer,dragEl)),on(document,"drop",_this),css(dragEl,"transform","translateZ(0)")),awaitingDragStarted=!0,_this._dragStartId=_nextTick(_this._dragStarted.bind(_this,fallback,evt)),on(document,"selectstart",_this),moved=!0,Safari&&css(document.body,"user-select","none")},"_onDragStart"),"_onDragStart"),_onDragOver:__name2(__name(function(evt){var el=this.el,target=evt.target,dragRect,targetRect,revert,options=this.options,group=options.group,activeSortable=Sortable.active,isOwner=activeGroup===group,canSort=options.sort,fromSortable=putSortable||activeSortable,vertical,_this=this,completedFired=!1;if(_silent)return;function dragOverEvent(name2,extra){pluginEvent2(name2,_this,_objectSpread2({evt,isOwner,axis:vertical?"vertical":"horizontal",revert,dragRect,targetRect,canSort,fromSortable,target,completed,onMove:__name2(__name(function(target2,after2){return _onMove(rootEl,el,dragEl,dragRect,target2,getRect(target2),evt,after2)},"onMove"),"onMove"),changed},extra))}__name(dragOverEvent,"dragOverEvent"),__name2(dragOverEvent,"dragOverEvent");function capture(){dragOverEvent("dragOverAnimationCapture"),_this.captureAnimationState(),_this!==fromSortable&&fromSortable.captureAnimationState()}__name(capture,"capture"),__name2(capture,"capture");function completed(insertion){return dragOverEvent("dragOverCompleted",{insertion}),insertion&&(isOwner?activeSortable._hideClone():activeSortable._showClone(_this),_this!==fromSortable&&(toggleClass(dragEl,putSortable?putSortable.options.ghostClass:activeSortable.options.ghostClass,!1),toggleClass(dragEl,options.ghostClass,!0)),putSortable!==_this&&_this!==Sortable.active?putSortable=_this:_this===Sortable.active&&putSortable&&(putSortable=null),fromSortable===_this&&(_this._ignoreWhileAnimating=target),_this.animateAll(function(){dragOverEvent("dragOverAnimationComplete"),_this._ignoreWhileAnimating=null}),_this!==fromSortable&&(fromSortable.animateAll(),fromSortable._ignoreWhileAnimating=null)),(target===dragEl&&!dragEl.animated||target===el&&!target.animated)&&(lastTarget=null),!options.dragoverBubble&&!evt.rootEl&&target!==document&&(dragEl.parentNode[expando]._isOutsideThisEl(evt.target),!insertion&&nearestEmptyInsertDetectEvent(evt)),!options.dragoverBubble&&evt.stopPropagation&&evt.stopPropagation(),completedFired=!0}__name(completed,"completed"),__name2(completed,"completed");function changed(){newIndex=index(dragEl),newDraggableIndex=index(dragEl,options.draggable),_dispatchEvent({sortable:_this,name:"change",toEl:el,newIndex,newDraggableIndex,originalEvent:evt})}if(__name(changed,"changed"),__name2(changed,"changed"),evt.preventDefault!==void 0&&evt.cancelable&&evt.preventDefault(),target=closest$1(target,options.draggable,el,!0),dragOverEvent("dragOver"),Sortable.eventCanceled)return completedFired;if(dragEl.contains(evt.target)||target.animated&&target.animatingX&&target.animatingY||_this._ignoreWhileAnimating===target)return completed(!1);if(ignoreNextClick=!1,activeSortable&&!options.disabled&&(isOwner?canSort||(revert=parentEl!==rootEl):putSortable===this||(this.lastPutMode=activeGroup.checkPull(this,activeSortable,dragEl,evt))&&group.checkPut(this,activeSortable,dragEl,evt))){if(vertical=this._getDirection(evt,target)==="vertical",dragRect=getRect(dragEl),dragOverEvent("dragOverValid"),Sortable.eventCanceled)return completedFired;if(revert)return parentEl=rootEl,capture(),this._hideClone(),dragOverEvent("revert"),Sortable.eventCanceled||(nextEl?rootEl.insertBefore(dragEl,nextEl):rootEl.appendChild(dragEl)),completed(!0);var elLastChild=lastChild(el,options.draggable);if(!elLastChild||_ghostIsLast(evt,vertical,this)&&!elLastChild.animated){if(elLastChild===dragEl)return completed(!1);if(elLastChild&&el===evt.target&&(target=elLastChild),target&&(targetRect=getRect(target)),_onMove(rootEl,el,dragEl,dragRect,target,targetRect,evt,!!target)!==!1)return capture(),elLastChild&&elLastChild.nextSibling?el.insertBefore(dragEl,elLastChild.nextSibling):el.appendChild(dragEl),parentEl=el,changed(),completed(!0)}else if(elLastChild&&_ghostIsFirst(evt,vertical,this)){var firstChild=getChild(el,0,options,!0);if(firstChild===dragEl)return completed(!1);if(target=firstChild,targetRect=getRect(target),_onMove(rootEl,el,dragEl,dragRect,target,targetRect,evt,!1)!==!1)return capture(),el.insertBefore(dragEl,firstChild),parentEl=el,changed(),completed(!0)}else if(target.parentNode===el){targetRect=getRect(target);var direction=0,targetBeforeFirstSwap,differentLevel=dragEl.parentNode!==el,differentRowCol=!_dragElInRowColumn(dragEl.animated&&dragEl.toRect||dragRect,target.animated&&target.toRect||targetRect,vertical),side1=vertical?"top":"left",scrolledPastTop=isScrolledPast(target,"top","top")||isScrolledPast(dragEl,"top","top"),scrollBefore=scrolledPastTop?scrolledPastTop.scrollTop:void 0;lastTarget!==target&&(targetBeforeFirstSwap=targetRect[side1],pastFirstInvertThresh=!1,isCircumstantialInvert=!differentRowCol&&options.invertSwap||differentLevel),direction=_getSwapDirection(evt,target,targetRect,vertical,differentRowCol?1:options.swapThreshold,options.invertedSwapThreshold==null?options.swapThreshold:options.invertedSwapThreshold,isCircumstantialInvert,lastTarget===target);var sibling;if(direction!==0){var dragIndex=index(dragEl);do dragIndex-=direction,sibling=parentEl.children[dragIndex];while(sibling&&(css(sibling,"display")==="none"||sibling===ghostEl))}if(direction===0||sibling===target)return completed(!1);lastTarget=target,lastDirection=direction;var nextSibling=target.nextElementSibling,after=!1;after=direction===1;var moveVector=_onMove(rootEl,el,dragEl,dragRect,target,targetRect,evt,after);if(moveVector!==!1)return(moveVector===1||moveVector===-1)&&(after=moveVector===1),_silent=!0,setTimeout(_unsilent,30),capture(),after&&!nextSibling?el.appendChild(dragEl):target.parentNode.insertBefore(dragEl,after?nextSibling:target),scrolledPastTop&&scrollBy(scrolledPastTop,0,scrollBefore-scrolledPastTop.scrollTop),parentEl=dragEl.parentNode,targetBeforeFirstSwap!==void 0&&!isCircumstantialInvert&&(targetMoveDistance=Math.abs(targetBeforeFirstSwap-getRect(target)[side1])),changed(),completed(!0)}if(el.contains(dragEl))return completed(!1)}return!1},"_onDragOver"),"_onDragOver"),_ignoreWhileAnimating:null,_offMoveEvents:__name2(__name(function(){off(document,"mousemove",this._onTouchMove),off(document,"touchmove",this._onTouchMove),off(document,"pointermove",this._onTouchMove),off(document,"dragover",nearestEmptyInsertDetectEvent),off(document,"mousemove",nearestEmptyInsertDetectEvent),off(document,"touchmove",nearestEmptyInsertDetectEvent)},"_offMoveEvents"),"_offMoveEvents"),_offUpEvents:__name2(__name(function(){var ownerDocument=this.el.ownerDocument;off(ownerDocument,"mouseup",this._onDrop),off(ownerDocument,"touchend",this._onDrop),off(ownerDocument,"pointerup",this._onDrop),off(ownerDocument,"touchcancel",this._onDrop),off(document,"selectstart",this)},"_offUpEvents"),"_offUpEvents"),_onDrop:__name2(__name(function(evt){var el=this.el,options=this.options;if(newIndex=index(dragEl),newDraggableIndex=index(dragEl,options.draggable),pluginEvent2("drop",this,{evt}),parentEl=dragEl&&dragEl.parentNode,newIndex=index(dragEl),newDraggableIndex=index(dragEl,options.draggable),Sortable.eventCanceled){this._nulling();return}awaitingDragStarted=!1,isCircumstantialInvert=!1,pastFirstInvertThresh=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),_cancelNextTick(this.cloneId),_cancelNextTick(this._dragStartId),this.nativeDraggable&&(off(document,"drop",this),off(el,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),Safari&&css(document.body,"user-select",""),css(dragEl,"transform",""),evt&&(moved&&(evt.cancelable&&evt.preventDefault(),!options.dropBubble&&evt.stopPropagation()),ghostEl&&ghostEl.parentNode&&ghostEl.parentNode.removeChild(ghostEl),(rootEl===parentEl||putSortable&&putSortable.lastPutMode!=="clone")&&cloneEl&&cloneEl.parentNode&&cloneEl.parentNode.removeChild(cloneEl),dragEl&&(this.nativeDraggable&&off(dragEl,"dragend",this),_disableDraggable(dragEl),dragEl.style["will-change"]="",moved&&!awaitingDragStarted&&toggleClass(dragEl,putSortable?putSortable.options.ghostClass:this.options.ghostClass,!1),toggleClass(dragEl,this.options.chosenClass,!1),_dispatchEvent({sortable:this,name:"unchoose",toEl:parentEl,newIndex:null,newDraggableIndex:null,originalEvent:evt}),rootEl!==parentEl?(newIndex>=0&&(_dispatchEvent({rootEl:parentEl,name:"add",toEl:parentEl,fromEl:rootEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"remove",toEl:parentEl,originalEvent:evt}),_dispatchEvent({rootEl:parentEl,name:"sort",toEl:parentEl,fromEl:rootEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"sort",toEl:parentEl,originalEvent:evt})),putSortable&&putSortable.save()):newIndex!==oldIndex&&newIndex>=0&&(_dispatchEvent({sortable:this,name:"update",toEl:parentEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"sort",toEl:parentEl,originalEvent:evt})),Sortable.active&&((newIndex==null||newIndex===-1)&&(newIndex=oldIndex,newDraggableIndex=oldDraggableIndex),_dispatchEvent({sortable:this,name:"end",toEl:parentEl,originalEvent:evt}),this.save()))),this._nulling()},"_onDrop"),"_onDrop"),_nulling:__name2(__name(function(){pluginEvent2("nulling",this),rootEl=dragEl=parentEl=ghostEl=nextEl=cloneEl=lastDownEl=cloneHidden=tapEvt=touchEvt=moved=newIndex=newDraggableIndex=oldIndex=oldDraggableIndex=lastTarget=lastDirection=putSortable=activeGroup=Sortable.dragged=Sortable.ghost=Sortable.clone=Sortable.active=null,savedInputChecked.forEach(function(el){el.checked=!0}),savedInputChecked.length=lastDx=lastDy=0},"_nulling"),"_nulling"),handleEvent:__name2(__name(function(evt){switch(evt.type){case"drop":case"dragend":this._onDrop(evt);break;case"dragenter":case"dragover":dragEl&&(this._onDragOver(evt),_globalDragOver(evt));break;case"selectstart":evt.preventDefault();break}},"handleEvent"),"handleEvent"),toArray:__name2(__name(function(){for(var order=[],el,children=this.el.children,i=0,n2=children.length,options=this.options;i<n2;i++)el=children[i],closest$1(el,options.draggable,this.el,!1)&&order.push(el.getAttribute(options.dataIdAttr)||_generateId(el));return order},"toArray"),"toArray"),sort:__name2(__name(function(order,useAnimation){var items={},rootEl2=this.el;this.toArray().forEach(function(id,i){var el=rootEl2.children[i];closest$1(el,this.options.draggable,rootEl2,!1)&&(items[id]=el)},this),useAnimation&&this.captureAnimationState(),order.forEach(function(id){items[id]&&(rootEl2.removeChild(items[id]),rootEl2.appendChild(items[id]))}),useAnimation&&this.animateAll()},"sort"),"sort"),save:__name2(__name(function(){var store=this.options.store;store&&store.set&&store.set(this)},"save"),"save"),closest:__name2(__name(function(el,selector){return closest$1(el,selector||this.options.draggable,this.el,!1)},"closest$1$1"),"closest$1$1"),option:__name2(__name(function(name2,value){var options=this.options;if(value===void 0)return options[name2];var modifiedValue=PluginManager.modifyOption(this,name2,value);typeof modifiedValue<"u"?options[name2]=modifiedValue:options[name2]=value,name2==="group"&&_prepareGroup(options)},"option"),"option"),destroy:__name2(__name(function(){pluginEvent2("destroy",this);var el=this.el;el[expando]=null,off(el,"mousedown",this._onTapStart),off(el,"touchstart",this._onTapStart),off(el,"pointerdown",this._onTapStart),this.nativeDraggable&&(off(el,"dragover",this),off(el,"dragenter",this)),Array.prototype.forEach.call(el.querySelectorAll("[draggable]"),function(el2){el2.removeAttribute("draggable")}),this._onDrop(),this._disableDelayedDragEvents(),sortables.splice(sortables.indexOf(this.el),1),this.el=el=null},"destroy"),"destroy"),_hideClone:__name2(__name(function(){if(!cloneHidden){if(pluginEvent2("hideClone",this),Sortable.eventCanceled)return;css(cloneEl,"display","none"),this.options.removeCloneOnHide&&cloneEl.parentNode&&cloneEl.parentNode.removeChild(cloneEl),cloneHidden=!0}},"_hideClone"),"_hideClone"),_showClone:__name2(__name(function(putSortable2){if(putSortable2.lastPutMode!=="clone"){this._hideClone();return}if(cloneHidden){if(pluginEvent2("showClone",this),Sortable.eventCanceled)return;dragEl.parentNode==rootEl&&!this.options.group.revertClone?rootEl.insertBefore(cloneEl,dragEl):nextEl?rootEl.insertBefore(cloneEl,nextEl):rootEl.appendChild(cloneEl),this.options.group.revertClone&&this.animate(dragEl,cloneEl),css(cloneEl,"display",""),cloneHidden=!1}},"_showClone"),"_showClone")};function _globalDragOver(evt){evt.dataTransfer&&(evt.dataTransfer.dropEffect="move"),evt.cancelable&&evt.preventDefault()}__name(_globalDragOver,"_globalDragOver"),__name2(_globalDragOver,"_globalDragOver");function _onMove(fromEl,toEl,dragEl2,dragRect,targetEl,targetRect,originalEvent,willInsertAfter){var evt,sortable=fromEl[expando],onMoveFn=sortable.options.onMove,retVal;return window.CustomEvent&&!IE11OrLess&&!Edge?evt=new CustomEvent("move",{bubbles:!0,cancelable:!0}):(evt=document.createEvent("Event"),evt.initEvent("move",!0,!0)),evt.to=toEl,evt.from=fromEl,evt.dragged=dragEl2,evt.draggedRect=dragRect,evt.related=targetEl||toEl,evt.relatedRect=targetRect||getRect(toEl),evt.willInsertAfter=willInsertAfter,evt.originalEvent=originalEvent,fromEl.dispatchEvent(evt),onMoveFn&&(retVal=onMoveFn.call(sortable,evt,originalEvent)),retVal}__name(_onMove,"_onMove"),__name2(_onMove,"_onMove");function _disableDraggable(el){el.draggable=!1}__name(_disableDraggable,"_disableDraggable"),__name2(_disableDraggable,"_disableDraggable");function _unsilent(){_silent=!1}__name(_unsilent,"_unsilent"),__name2(_unsilent,"_unsilent");function _ghostIsFirst(evt,vertical,sortable){var rect=getRect(getChild(sortable.el,0,sortable.options,!0)),spacer=10;return vertical?evt.clientX<rect.left-spacer||evt.clientY<rect.top&&evt.clientX<rect.right:evt.clientY<rect.top-spacer||evt.clientY<rect.bottom&&evt.clientX<rect.left}__name(_ghostIsFirst,"_ghostIsFirst"),__name2(_ghostIsFirst,"_ghostIsFirst");function _ghostIsLast(evt,vertical,sortable){var rect=getRect(lastChild(sortable.el,sortable.options.draggable)),spacer=10;return vertical?evt.clientX>rect.right+spacer||evt.clientX<=rect.right&&evt.clientY>rect.bottom&&evt.clientX>=rect.left:evt.clientX>rect.right&&evt.clientY>rect.top||evt.clientX<=rect.right&&evt.clientY>rect.bottom+spacer}__name(_ghostIsLast,"_ghostIsLast"),__name2(_ghostIsLast,"_ghostIsLast");function _getSwapDirection(evt,target,targetRect,vertical,swapThreshold,invertedSwapThreshold,invertSwap,isLastTarget){var mouseOnAxis=vertical?evt.clientY:evt.clientX,targetLength=vertical?targetRect.height:targetRect.width,targetS1=vertical?targetRect.top:targetRect.left,targetS2=vertical?targetRect.bottom:targetRect.right,invert=!1;if(!invertSwap){if(isLastTarget&&targetMoveDistance<targetLength*swapThreshold){if(!pastFirstInvertThresh&&(lastDirection===1?mouseOnAxis>targetS1+targetLength*invertedSwapThreshold/2:mouseOnAxis<targetS2-targetLength*invertedSwapThreshold/2)&&(pastFirstInvertThresh=!0),pastFirstInvertThresh)invert=!0;else if(lastDirection===1?mouseOnAxis<targetS1+targetMoveDistance:mouseOnAxis>targetS2-targetMoveDistance)return-lastDirection}else if(mouseOnAxis>targetS1+targetLength*(1-swapThreshold)/2&&mouseOnAxis<targetS2-targetLength*(1-swapThreshold)/2)return _getInsertDirection(target)}return invert=invert||invertSwap,invert&&(mouseOnAxis<targetS1+targetLength*invertedSwapThreshold/2||mouseOnAxis>targetS2-targetLength*invertedSwapThreshold/2)?mouseOnAxis>targetS1+targetLength/2?1:-1:0}__name(_getSwapDirection,"_getSwapDirection"),__name2(_getSwapDirection,"_getSwapDirection");function _getInsertDirection(target){return index(dragEl)<index(target)?1:-1}__name(_getInsertDirection,"_getInsertDirection"),__name2(_getInsertDirection,"_getInsertDirection");function _generateId(el){for(var str=el.tagName+el.className+el.src+el.href+el.textContent,i=str.length,sum=0;i--;)sum+=str.charCodeAt(i);return sum.toString(36)}__name(_generateId,"_generateId"),__name2(_generateId,"_generateId");function _saveInputCheckedState(root){savedInputChecked.length=0;for(var inputs=root.getElementsByTagName("input"),idx=inputs.length;idx--;){var el=inputs[idx];el.checked&&savedInputChecked.push(el)}}__name(_saveInputCheckedState,"_saveInputCheckedState"),__name2(_saveInputCheckedState,"_saveInputCheckedState");function _nextTick(fn){return setTimeout(fn,0)}__name(_nextTick,"_nextTick"),__name2(_nextTick,"_nextTick");function _cancelNextTick(id){return clearTimeout(id)}__name(_cancelNextTick,"_cancelNextTick"),__name2(_cancelNextTick,"_cancelNextTick"),documentExists&&on(document,"touchmove",function(evt){(Sortable.active||awaitingDragStarted)&&evt.cancelable&&evt.preventDefault()}),Sortable.utils={on,off,css,find:find$1,is:__name2(__name(function(el,selector){return!!closest$1(el,selector,el,!1)},"is"),"is"),extend:extend$1,throttle,closest:closest$1,toggleClass,clone,index,nextTick:_nextTick,cancelNextTick:_cancelNextTick,detectDirection:_detectDirection,getChild},Sortable.get=function(element){return element[expando]},Sortable.mount=function(){for(var _len=arguments.length,plugins2=new Array(_len),_key=0;_key<_len;_key++)plugins2[_key]=arguments[_key];plugins2[0].constructor===Array&&(plugins2=plugins2[0]),plugins2.forEach(function(plugin){if(!plugin.prototype||!plugin.prototype.constructor)throw"Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(plugin));plugin.utils&&(Sortable.utils=_objectSpread2(_objectSpread2({},Sortable.utils),plugin.utils)),PluginManager.mount(plugin)})},Sortable.create=function(el,options){return new Sortable(el,options)},Sortable.version=version;var autoScrolls=[],scrollEl,scrollRootEl,scrolling=!1,lastAutoScrollX,lastAutoScrollY,touchEvt$1,pointerElemChangedInterval;function AutoScrollPlugin(){function AutoScroll(){this.defaults={scroll:!0,forceAutoScrollFallback:!1,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0};for(var fn in this)fn.charAt(0)==="_"&&typeof this[fn]=="function"&&(this[fn]=this[fn].bind(this))}return __name(AutoScroll,"AutoScroll"),__name2(AutoScroll,"AutoScroll"),AutoScroll.prototype={dragStarted:__name2(__name(function(_ref){var originalEvent=_ref.originalEvent;this.sortable.nativeDraggable?on(document,"dragover",this._handleAutoScroll):this.options.supportPointer?on(document,"pointermove",this._handleFallbackAutoScroll):originalEvent.touches?on(document,"touchmove",this._handleFallbackAutoScroll):on(document,"mousemove",this._handleFallbackAutoScroll)},"dragStarted"),"dragStarted"),dragOverCompleted:__name2(__name(function(_ref2){var originalEvent=_ref2.originalEvent;!this.options.dragOverBubble&&!originalEvent.rootEl&&this._handleAutoScroll(originalEvent)},"dragOverCompleted"),"dragOverCompleted"),drop:__name2(__name(function(){this.sortable.nativeDraggable?off(document,"dragover",this._handleAutoScroll):(off(document,"pointermove",this._handleFallbackAutoScroll),off(document,"touchmove",this._handleFallbackAutoScroll),off(document,"mousemove",this._handleFallbackAutoScroll)),clearPointerElemChangedInterval(),clearAutoScrolls(),cancelThrottle()},"drop3"),"drop"),nulling:__name2(__name(function(){touchEvt$1=scrollRootEl=scrollEl=scrolling=pointerElemChangedInterval=lastAutoScrollX=lastAutoScrollY=null,autoScrolls.length=0},"nulling"),"nulling"),_handleFallbackAutoScroll:__name2(__name(function(evt){this._handleAutoScroll(evt,!0)},"_handleFallbackAutoScroll"),"_handleFallbackAutoScroll"),_handleAutoScroll:__name2(__name(function(evt,fallback){var _this=this,x=(evt.touches?evt.touches[0]:evt).clientX,y=(evt.touches?evt.touches[0]:evt).clientY,elem=document.elementFromPoint(x,y);if(touchEvt$1=evt,fallback||this.options.forceAutoScrollFallback||Edge||IE11OrLess||Safari){autoScroll(evt,this.options,elem,fallback);var ogElemScroller=getParentAutoScrollElement(elem,!0);scrolling&&(!pointerElemChangedInterval||x!==lastAutoScrollX||y!==lastAutoScrollY)&&(pointerElemChangedInterval&&clearPointerElemChangedInterval(),pointerElemChangedInterval=setInterval(function(){var newElem=getParentAutoScrollElement(document.elementFromPoint(x,y),!0);newElem!==ogElemScroller&&(ogElemScroller=newElem,clearAutoScrolls()),autoScroll(evt,_this.options,newElem,fallback)},10),lastAutoScrollX=x,lastAutoScrollY=y)}else{if(!this.options.bubbleScroll||getParentAutoScrollElement(elem,!0)===getWindowScrollingElement()){clearAutoScrolls();return}autoScroll(evt,this.options,getParentAutoScrollElement(elem,!1),!1)}},"_handleAutoScroll"),"_handleAutoScroll")},_extends(AutoScroll,{pluginName:"scroll",initializeByDefault:!0})}__name(AutoScrollPlugin,"AutoScrollPlugin"),__name2(AutoScrollPlugin,"AutoScrollPlugin");function clearAutoScrolls(){autoScrolls.forEach(function(autoScroll2){clearInterval(autoScroll2.pid)}),autoScrolls=[]}__name(clearAutoScrolls,"clearAutoScrolls"),__name2(clearAutoScrolls,"clearAutoScrolls");function clearPointerElemChangedInterval(){clearInterval(pointerElemChangedInterval)}__name(clearPointerElemChangedInterval,"clearPointerElemChangedInterval"),__name2(clearPointerElemChangedInterval,"clearPointerElemChangedInterval");var autoScroll=throttle(function(evt,options,rootEl2,isFallback){if(options.scroll){var x=(evt.touches?evt.touches[0]:evt).clientX,y=(evt.touches?evt.touches[0]:evt).clientY,sens=options.scrollSensitivity,speed=options.scrollSpeed,winScroller=getWindowScrollingElement(),scrollThisInstance=!1,scrollCustomFn;scrollRootEl!==rootEl2&&(scrollRootEl=rootEl2,clearAutoScrolls(),scrollEl=options.scroll,scrollCustomFn=options.scrollFn,scrollEl===!0&&(scrollEl=getParentAutoScrollElement(rootEl2,!0)));var layersOut=0,currentParent=scrollEl;do{var el=currentParent,rect=getRect(el),top2=rect.top,bottom=rect.bottom,left=rect.left,right=rect.right,width=rect.width,height=rect.height,canScrollX=void 0,canScrollY=void 0,scrollWidth=el.scrollWidth,scrollHeight=el.scrollHeight,elCSS=css(el),scrollPosX=el.scrollLeft,scrollPosY=el.scrollTop;el===winScroller?(canScrollX=width<scrollWidth&&(elCSS.overflowX==="auto"||elCSS.overflowX==="scroll"||elCSS.overflowX==="visible"),canScrollY=height<scrollHeight&&(elCSS.overflowY==="auto"||elCSS.overflowY==="scroll"||elCSS.overflowY==="visible")):(canScrollX=width<scrollWidth&&(elCSS.overflowX==="auto"||elCSS.overflowX==="scroll"),canScrollY=height<scrollHeight&&(elCSS.overflowY==="auto"||elCSS.overflowY==="scroll"));var vx=canScrollX&&(Math.abs(right-x)<=sens&&scrollPosX+width<scrollWidth)-(Math.abs(left-x)<=sens&&!!scrollPosX),vy=canScrollY&&(Math.abs(bottom-y)<=sens&&scrollPosY+height<scrollHeight)-(Math.abs(top2-y)<=sens&&!!scrollPosY);if(!autoScrolls[layersOut])for(var i=0;i<=layersOut;i++)autoScrolls[i]||(autoScrolls[i]={});(autoScrolls[layersOut].vx!=vx||autoScrolls[layersOut].vy!=vy||autoScrolls[layersOut].el!==el)&&(autoScrolls[layersOut].el=el,autoScrolls[layersOut].vx=vx,autoScrolls[layersOut].vy=vy,clearInterval(autoScrolls[layersOut].pid),(vx!=0||vy!=0)&&(scrollThisInstance=!0,autoScrolls[layersOut].pid=setInterval(function(){isFallback&&this.layer===0&&Sortable.active._onTouchMove(touchEvt$1);var scrollOffsetY=autoScrolls[this.layer].vy?autoScrolls[this.layer].vy*speed:0,scrollOffsetX=autoScrolls[this.layer].vx?autoScrolls[this.layer].vx*speed:0;typeof scrollCustomFn=="function"&&scrollCustomFn.call(Sortable.dragged.parentNode[expando],scrollOffsetX,scrollOffsetY,evt,touchEvt$1,autoScrolls[this.layer].el)!=="continue"||scrollBy(autoScrolls[this.layer].el,scrollOffsetX,scrollOffsetY)}.bind({layer:layersOut}),24))),layersOut++}while(options.bubbleScroll&&currentParent!==winScroller&&(currentParent=getParentAutoScrollElement(currentParent,!1)));scrolling=scrollThisInstance}},30),drop=__name2(__name(function(_ref){var originalEvent=_ref.originalEvent,putSortable2=_ref.putSortable,dragEl2=_ref.dragEl,activeSortable=_ref.activeSortable,dispatchSortableEvent=_ref.dispatchSortableEvent,hideGhostForTarget=_ref.hideGhostForTarget,unhideGhostForTarget=_ref.unhideGhostForTarget;if(originalEvent){var toSortable=putSortable2||activeSortable;hideGhostForTarget();var touch=originalEvent.changedTouches&&originalEvent.changedTouches.length?originalEvent.changedTouches[0]:originalEvent,target=document.elementFromPoint(touch.clientX,touch.clientY);unhideGhostForTarget(),toSortable&&!toSortable.el.contains(target)&&(dispatchSortableEvent("spill"),this.onSpill({dragEl:dragEl2,putSortable:putSortable2}))}},"drop2"),"drop");function Revert(){}__name(Revert,"Revert"),__name2(Revert,"Revert"),Revert.prototype={startIndex:null,dragStart:__name2(__name(function(_ref2){var oldDraggableIndex2=_ref2.oldDraggableIndex;this.startIndex=oldDraggableIndex2},"dragStart"),"dragStart"),onSpill:__name2(__name(function(_ref3){var dragEl2=_ref3.dragEl,putSortable2=_ref3.putSortable;this.sortable.captureAnimationState(),putSortable2&&putSortable2.captureAnimationState();var nextSibling=getChild(this.sortable.el,this.startIndex,this.options);nextSibling?this.sortable.el.insertBefore(dragEl2,nextSibling):this.sortable.el.appendChild(dragEl2),this.sortable.animateAll(),putSortable2&&putSortable2.animateAll()},"onSpill"),"onSpill"),drop},_extends(Revert,{pluginName:"revertOnSpill"});function Remove(){}__name(Remove,"Remove"),__name2(Remove,"Remove"),Remove.prototype={onSpill:__name2(__name(function(_ref4){var dragEl2=_ref4.dragEl,putSortable2=_ref4.putSortable,parentSortable=putSortable2||this.sortable;parentSortable.captureAnimationState(),dragEl2.parentNode&&dragEl2.parentNode.removeChild(dragEl2),parentSortable.animateAll()},"onSpill2"),"onSpill"),drop},_extends(Remove,{pluginName:"removeOnSpill"}),Sortable.mount(new AutoScrollPlugin),Sortable.mount(Remove,Revert);var __assign=__name2(function(){return __assign=Object.assign||__name2(__name(function(t2){for(var s2,i=1,n2=arguments.length;i<n2;i++){s2=arguments[i];for(var p in s2)Object.prototype.hasOwnProperty.call(s2,p)&&(t2[p]=s2[p])}return t2},"__assign2"),"__assign"),__assign.apply(this,arguments)},"__assign");function __awaiter(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return __name(adopt,"adopt"),__name2(adopt,"adopt"),new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}__name(fulfilled,"fulfilled"),__name2(fulfilled,"fulfilled");function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}__name(rejected,"rejected"),__name2(rejected,"rejected");function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}__name(step,"step"),__name2(step,"step"),step((generator=generator.apply(thisArg,_arguments||[])).next())})}__name(__awaiter,"__awaiter"),__name2(__awaiter,"__awaiter");function __generator(thisArg,body){var _={label:0,sent:function(){if(t2[0]&1)throw t2[1];return t2[1]},trys:[],ops:[]},f2,y,t2,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n2){return function(v){return step([n2,v])}}function step(op){if(f2)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f2=1,y&&(t2=op[0]&2?y.return:op[0]?y.throw||((t2=y.return)&&t2.call(y),0):y.next)&&!(t2=t2.call(y,op[1])).done)return t2;switch(y=0,t2&&(op=[op[0]&2,t2.value]),op[0]){case 0:case 1:t2=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(t2=_.trys,!(t2=t2.length>0&&t2[t2.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t2||op[1]>t2[0]&&op[1]<t2[3])){_.label=op[1];break}if(op[0]===6&&_.label<t2[1]){_.label=t2[1],t2=op;break}if(t2&&_.label<t2[2]){_.label=t2[2],_.ops.push(op);break}t2[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f2=t2=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}}__name(__generator,"__generator"),__name2(__generator,"__generator");function __values(o){var s2=typeof Symbol=="function"&&Symbol.iterator,m=s2&&o[s2],i=0;if(m)return m.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s2?"Object is not iterable.":"Symbol.iterator is not defined.")}__name(__values,"__values"),__name2(__values,"__values");function __read(o,n2){var m=typeof Symbol=="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{for(;(n2===void 0||n2-- >0)&&!(r=i.next()).done;)ar.push(r.value)}catch(error){e={error}}finally{try{r&&!r.done&&(m=i.return)&&m.call(i)}finally{if(e)throw e.error}}return ar}__name(__read,"__read"),__name2(__read,"__read"),typeof SuppressedError=="function"&&SuppressedError;var ENTRIES="ENTRIES",KEYS="KEYS",VALUES="VALUES",LEAF="",TreeIterator=function(){function TreeIterator2(set,type){var node=set._tree,keys2=Array.from(node.keys());this.set=set,this._type=type,this._path=keys2.length>0?[{node,keys:keys2}]:[]}return __name(TreeIterator2,"TreeIterator2"),__name2(TreeIterator2,"TreeIterator"),TreeIterator2.prototype.next=function(){var value=this.dive();return this.backtrack(),value},TreeIterator2.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var _a3=last$1(this._path),node=_a3.node,keys2=_a3.keys;if(last$1(keys2)===LEAF)return{done:!1,value:this.result()};var child=node.get(last$1(keys2));return this._path.push({node:child,keys:Array.from(child.keys())}),this.dive()},TreeIterator2.prototype.backtrack=function(){if(this._path.length!==0){var keys2=last$1(this._path).keys;keys2.pop(),!(keys2.length>0)&&(this._path.pop(),this.backtrack())}},TreeIterator2.prototype.key=function(){return this.set._prefix+this._path.map(function(_a3){var keys2=_a3.keys;return last$1(keys2)}).filter(function(key){return key!==LEAF}).join("")},TreeIterator2.prototype.value=function(){return last$1(this._path).node.get(LEAF)},TreeIterator2.prototype.result=function(){switch(this._type){case VALUES:return this.value();case KEYS:return this.key();default:return[this.key(),this.value()]}},TreeIterator2.prototype[Symbol.iterator]=function(){return this},TreeIterator2}(),last$1=__name2(function(array){return array[array.length-1]},"last$1"),fuzzySearch=__name2(function(node,query,maxDistance){var results=new Map;if(query===void 0)return results;for(var n2=query.length+1,m=n2+maxDistance,matrix2=new Uint8Array(m*n2).fill(maxDistance+1),j=0;j<n2;++j)matrix2[j]=j;for(var i=1;i<m;++i)matrix2[i*n2]=i;return recurse(node,query,maxDistance,results,matrix2,1,n2,""),results},"fuzzySearch"),recurse=__name2(function(node,query,maxDistance,results,matrix2,m,n2,prefix){var e_1,_a3,offset2=m*n2;try{key:for(var _b2=__values(node.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var key=_c2.value;if(key===LEAF){var distance=matrix2[offset2-1];distance<=maxDistance&&results.set(prefix,[node.get(key),distance])}else{for(var i=m,pos=0;pos<key.length;++pos,++i){for(var char=key[pos],thisRowOffset=n2*i,prevRowOffset=thisRowOffset-n2,minDistance=matrix2[thisRowOffset],jmin=Math.max(0,i-maxDistance-1),jmax=Math.min(n2-1,i+maxDistance),j=jmin;j<jmax;++j){var different=char!==query[j],rpl=matrix2[prevRowOffset+j]+ +different,del=matrix2[prevRowOffset+j+1]+1,ins=matrix2[thisRowOffset+j]+1,dist2=matrix2[thisRowOffset+j+1]=Math.min(rpl,del,ins);dist2<minDistance&&(minDistance=dist2)}if(minDistance>maxDistance)continue key}recurse(node.get(key),query,maxDistance,results,matrix2,i,n2,prefix+key)}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_1)throw e_1.error}}},"recurse"),SearchableMap=function(){function SearchableMap2(tree,prefix){tree===void 0&&(tree=new Map),prefix===void 0&&(prefix=""),this._size=void 0,this._tree=tree,this._prefix=prefix}return __name(SearchableMap2,"SearchableMap2"),__name2(SearchableMap2,"SearchableMap"),SearchableMap2.prototype.atPrefix=function(prefix){var e_1,_a3;if(!prefix.startsWith(this._prefix))throw new Error("Mismatched prefix");var _b2=__read(trackDown(this._tree,prefix.slice(this._prefix.length)),2),node=_b2[0],path=_b2[1];if(node===void 0){var _c2=__read(last(path),2),parentNode=_c2[0],key=_c2[1];try{for(var _d=__values(parentNode.keys()),_e=_d.next();!_e.done;_e=_d.next()){var k=_e.value;if(k!==LEAF&&k.startsWith(key)){var node_1=new Map;return node_1.set(k.slice(key.length),parentNode.get(k)),new SearchableMap2(node_1,prefix)}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_1)throw e_1.error}}}return new SearchableMap2(node,prefix)},SearchableMap2.prototype.clear=function(){this._size=void 0,this._tree.clear()},SearchableMap2.prototype.delete=function(key){return this._size=void 0,remove$1(this._tree,key)},SearchableMap2.prototype.entries=function(){return new TreeIterator(this,ENTRIES)},SearchableMap2.prototype.forEach=function(fn){var e_2,_a3;try{for(var _b2=__values(this),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var _d=__read(_c2.value,2),key=_d[0],value=_d[1];fn(key,value,this)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_2)throw e_2.error}}},SearchableMap2.prototype.fuzzyGet=function(key,maxEditDistance){return fuzzySearch(this._tree,key,maxEditDistance)},SearchableMap2.prototype.get=function(key){var node=lookup(this._tree,key);return node!==void 0?node.get(LEAF):void 0},SearchableMap2.prototype.has=function(key){var node=lookup(this._tree,key);return node!==void 0&&node.has(LEAF)},SearchableMap2.prototype.keys=function(){return new TreeIterator(this,KEYS)},SearchableMap2.prototype.set=function(key,value){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key);return node.set(LEAF,value),this},Object.defineProperty(SearchableMap2.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var iter=this.entries();!iter.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),SearchableMap2.prototype.update=function(key,fn){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key);return node.set(LEAF,fn(node.get(LEAF))),this},SearchableMap2.prototype.fetch=function(key,initial){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key),value=node.get(LEAF);return value===void 0&&node.set(LEAF,value=initial()),value},SearchableMap2.prototype.values=function(){return new TreeIterator(this,VALUES)},SearchableMap2.prototype[Symbol.iterator]=function(){return this.entries()},SearchableMap2.from=function(entries){var e_3,_a3,tree=new SearchableMap2;try{for(var entries_1=__values(entries),entries_1_1=entries_1.next();!entries_1_1.done;entries_1_1=entries_1.next()){var _b2=__read(entries_1_1.value,2),key=_b2[0],value=_b2[1];tree.set(key,value)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{entries_1_1&&!entries_1_1.done&&(_a3=entries_1.return)&&_a3.call(entries_1)}finally{if(e_3)throw e_3.error}}return tree},SearchableMap2.fromObject=function(object){return SearchableMap2.from(Object.entries(object))},SearchableMap2}(),trackDown=__name2(function(tree,key,path){var e_4,_a3;if(path===void 0&&(path=[]),key.length===0||tree==null)return[tree,path];try{for(var _b2=__values(tree.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var k=_c2.value;if(k!==LEAF&&key.startsWith(k))return path.push([tree,k]),trackDown(tree.get(k),key.slice(k.length),path)}}catch(e_4_1){e_4={error:e_4_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_4)throw e_4.error}}return path.push([tree,key]),trackDown(void 0,"",path)},"trackDown"),lookup=__name2(function(tree,key){var e_5,_a3;if(key.length===0||tree==null)return tree;try{for(var _b2=__values(tree.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var k=_c2.value;if(k!==LEAF&&key.startsWith(k))return lookup(tree.get(k),key.slice(k.length))}}catch(e_5_1){e_5={error:e_5_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_5)throw e_5.error}}},"lookup"),createPath=__name2(function(node,key){var e_6,_a3,keyLength=key.length;outer:for(var pos=0;node&&pos<keyLength;){try{for(var _b2=(e_6=void 0,__values(node.keys())),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var k=_c2.value;if(k!==LEAF&&key[pos]===k[0]){for(var len=Math.min(keyLength-pos,k.length),offset2=1;offset2<len&&key[pos+offset2]===k[offset2];)++offset2;var child_1=node.get(k);if(offset2===k.length)node=child_1;else{var intermediate=new Map;intermediate.set(k.slice(offset2),child_1),node.set(key.slice(pos,pos+offset2),intermediate),node.delete(k),node=intermediate}pos+=offset2;continue outer}}}catch(e_6_1){e_6={error:e_6_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_6)throw e_6.error}}var child=new Map;return node.set(key.slice(pos),child),child}return node},"createPath"),remove$1=__name2(function(tree,key){var _a3=__read(trackDown(tree,key),2),node=_a3[0],path=_a3[1];if(node!==void 0){if(node.delete(LEAF),node.size===0)cleanup(path);else if(node.size===1){var _b2=__read(node.entries().next().value,2),key_1=_b2[0],value=_b2[1];merge(path,key_1,value)}}},"remove$1"),cleanup=__name2(function(path){if(path.length!==0){var _a3=__read(last(path),2),node=_a3[0],key=_a3[1];if(node.delete(key),node.size===0)cleanup(path.slice(0,-1));else if(node.size===1){var _b2=__read(node.entries().next().value,2),key_2=_b2[0],value=_b2[1];key_2!==LEAF&&merge(path.slice(0,-1),key_2,value)}}},"cleanup"),merge=__name2(function(path,key,value){if(path.length!==0){var _a3=__read(last(path),2),node=_a3[0],nodeKey=_a3[1];node.set(nodeKey+key,value),node.delete(nodeKey)}},"merge"),last=__name2(function(array){return array[array.length-1]},"last"),_a$1,OR="or",AND="and",AND_NOT="and_not",MiniSearch=function(){function MiniSearch2(options){if(options?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var autoVacuum=options.autoVacuum==null||options.autoVacuum===!0?defaultAutoVacuumOptions:options.autoVacuum;this._options=__assign(__assign(__assign({},defaultOptions),options),{autoVacuum,searchOptions:__assign(__assign({},defaultSearchOptions),options.searchOptions||{}),autoSuggestOptions:__assign(__assign({},defaultAutoSuggestOptions),options.autoSuggestOptions||{})}),this._index=new SearchableMap,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=defaultVacuumConditions,this.addFields(this._options.fields)}return __name(MiniSearch2,"MiniSearch2"),__name2(MiniSearch2,"MiniSearch"),MiniSearch2.prototype.add=function(document2){var e_1,_a3,e_2,_b2,e_3,_c2,_d=this._options,extractField=_d.extractField,tokenize=_d.tokenize,processTerm=_d.processTerm,fields=_d.fields,idField=_d.idField,id=extractField(document2,idField);if(id==null)throw new Error('MiniSearch: document does not have ID field "'.concat(idField,'"'));if(this._idToShortId.has(id))throw new Error("MiniSearch: duplicate ID ".concat(id));var shortDocumentId=this.addDocumentId(id);this.saveStoredFields(shortDocumentId,document2);try{for(var fields_1=__values(fields),fields_1_1=fields_1.next();!fields_1_1.done;fields_1_1=fields_1.next()){var field=fields_1_1.value,fieldValue=extractField(document2,field);if(fieldValue!=null){var tokens=tokenize(fieldValue.toString(),field),fieldId=this._fieldIds[field],uniqueTerms=new Set(tokens).size;this.addFieldLength(shortDocumentId,fieldId,this._documentCount-1,uniqueTerms);try{for(var tokens_1=(e_2=void 0,__values(tokens)),tokens_1_1=tokens_1.next();!tokens_1_1.done;tokens_1_1=tokens_1.next()){var term=tokens_1_1.value,processedTerm=processTerm(term,field);if(Array.isArray(processedTerm))try{for(var processedTerm_1=(e_3=void 0,__values(processedTerm)),processedTerm_1_1=processedTerm_1.next();!processedTerm_1_1.done;processedTerm_1_1=processedTerm_1.next()){var t2=processedTerm_1_1.value;this.addTerm(fieldId,shortDocumentId,t2)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{processedTerm_1_1&&!processedTerm_1_1.done&&(_c2=processedTerm_1.return)&&_c2.call(processedTerm_1)}finally{if(e_3)throw e_3.error}}else processedTerm&&this.addTerm(fieldId,shortDocumentId,processedTerm)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{tokens_1_1&&!tokens_1_1.done&&(_b2=tokens_1.return)&&_b2.call(tokens_1)}finally{if(e_2)throw e_2.error}}}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{fields_1_1&&!fields_1_1.done&&(_a3=fields_1.return)&&_a3.call(fields_1)}finally{if(e_1)throw e_1.error}}},MiniSearch2.prototype.addAll=function(documents){var e_4,_a3;try{for(var documents_1=__values(documents),documents_1_1=documents_1.next();!documents_1_1.done;documents_1_1=documents_1.next()){var document_1=documents_1_1.value;this.add(document_1)}}catch(e_4_1){e_4={error:e_4_1}}finally{try{documents_1_1&&!documents_1_1.done&&(_a3=documents_1.return)&&_a3.call(documents_1)}finally{if(e_4)throw e_4.error}}},MiniSearch2.prototype.addAllAsync=function(documents,options){var _this=this;options===void 0&&(options={});var _a3=options.chunkSize,chunkSize=_a3===void 0?10:_a3,acc={chunk:[],promise:Promise.resolve()},_b2=documents.reduce(function(_a4,document2,i){var chunk2=_a4.chunk,promise2=_a4.promise;return chunk2.push(document2),(i+1)%chunkSize===0?{chunk:[],promise:promise2.then(function(){return new Promise(function(resolve){return setTimeout(resolve,0)})}).then(function(){return _this.addAll(chunk2)})}:{chunk:chunk2,promise:promise2}},acc),chunk=_b2.chunk,promise=_b2.promise;return promise.then(function(){return _this.addAll(chunk)})},MiniSearch2.prototype.remove=function(document2){var e_5,_a3,e_6,_b2,e_7,_c2,_d=this._options,tokenize=_d.tokenize,processTerm=_d.processTerm,extractField=_d.extractField,fields=_d.fields,idField=_d.idField,id=extractField(document2,idField);if(id==null)throw new Error('MiniSearch: document does not have ID field "'.concat(idField,'"'));var shortId=this._idToShortId.get(id);if(shortId==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(id,": it is not in the index"));try{for(var fields_2=__values(fields),fields_2_1=fields_2.next();!fields_2_1.done;fields_2_1=fields_2.next()){var field=fields_2_1.value,fieldValue=extractField(document2,field);if(fieldValue!=null){var tokens=tokenize(fieldValue.toString(),field),fieldId=this._fieldIds[field],uniqueTerms=new Set(tokens).size;this.removeFieldLength(shortId,fieldId,this._documentCount,uniqueTerms);try{for(var tokens_2=(e_6=void 0,__values(tokens)),tokens_2_1=tokens_2.next();!tokens_2_1.done;tokens_2_1=tokens_2.next()){var term=tokens_2_1.value,processedTerm=processTerm(term,field);if(Array.isArray(processedTerm))try{for(var processedTerm_2=(e_7=void 0,__values(processedTerm)),processedTerm_2_1=processedTerm_2.next();!processedTerm_2_1.done;processedTerm_2_1=processedTerm_2.next()){var t2=processedTerm_2_1.value;this.removeTerm(fieldId,shortId,t2)}}catch(e_7_1){e_7={error:e_7_1}}finally{try{processedTerm_2_1&&!processedTerm_2_1.done&&(_c2=processedTerm_2.return)&&_c2.call(processedTerm_2)}finally{if(e_7)throw e_7.error}}else processedTerm&&this.removeTerm(fieldId,shortId,processedTerm)}}catch(e_6_1){e_6={error:e_6_1}}finally{try{tokens_2_1&&!tokens_2_1.done&&(_b2=tokens_2.return)&&_b2.call(tokens_2)}finally{if(e_6)throw e_6.error}}}}}catch(e_5_1){e_5={error:e_5_1}}finally{try{fields_2_1&&!fields_2_1.done&&(_a3=fields_2.return)&&_a3.call(fields_2)}finally{if(e_5)throw e_5.error}}this._storedFields.delete(shortId),this._documentIds.delete(shortId),this._idToShortId.delete(id),this._fieldLength.delete(shortId),this._documentCount-=1},MiniSearch2.prototype.removeAll=function(documents){var e_8,_a3;if(documents)try{for(var documents_2=__values(documents),documents_2_1=documents_2.next();!documents_2_1.done;documents_2_1=documents_2.next()){var document_2=documents_2_1.value;this.remove(document_2)}}catch(e_8_1){e_8={error:e_8_1}}finally{try{documents_2_1&&!documents_2_1.done&&(_a3=documents_2.return)&&_a3.call(documents_2)}finally{if(e_8)throw e_8.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new SearchableMap,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},MiniSearch2.prototype.discard=function(id){var _this=this,shortId=this._idToShortId.get(id);if(shortId==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(id,": it is not in the index"));this._idToShortId.delete(id),this._documentIds.delete(shortId),this._storedFields.delete(shortId),(this._fieldLength.get(shortId)||[]).forEach(function(fieldLength,fieldId){_this.removeFieldLength(shortId,fieldId,_this._documentCount,fieldLength)}),this._fieldLength.delete(shortId),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},MiniSearch2.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var _a3=this._options.autoVacuum,minDirtFactor=_a3.minDirtFactor,minDirtCount=_a3.minDirtCount,batchSize=_a3.batchSize,batchWait=_a3.batchWait;this.conditionalVacuum({batchSize,batchWait},{minDirtCount,minDirtFactor})}},MiniSearch2.prototype.discardAll=function(ids){var e_9,_a3,autoVacuum=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var ids_1=__values(ids),ids_1_1=ids_1.next();!ids_1_1.done;ids_1_1=ids_1.next()){var id=ids_1_1.value;this.discard(id)}}catch(e_9_1){e_9={error:e_9_1}}finally{try{ids_1_1&&!ids_1_1.done&&(_a3=ids_1.return)&&_a3.call(ids_1)}finally{if(e_9)throw e_9.error}}}finally{this._options.autoVacuum=autoVacuum}this.maybeAutoVacuum()},MiniSearch2.prototype.replace=function(updatedDocument){var _a3=this._options,idField=_a3.idField,extractField=_a3.extractField,id=extractField(updatedDocument,idField);this.discard(id),this.add(updatedDocument)},MiniSearch2.prototype.vacuum=function(options){return options===void 0&&(options={}),this.conditionalVacuum(options)},MiniSearch2.prototype.conditionalVacuum=function(options,conditions){var _this=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&conditions,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var conditions2=_this._enqueuedVacuumConditions;return _this._enqueuedVacuumConditions=defaultVacuumConditions,_this.performVacuuming(options,conditions2)}),this._enqueuedVacuum)):this.vacuumConditionsMet(conditions)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(options),this._currentVacuum)},MiniSearch2.prototype.performVacuuming=function(options,conditions){return __awaiter(this,void 0,void 0,function(){var initialDirtCount,batchSize,batchWait_1,i,_a3,_b2,_c2,term,fieldsData,fieldsData_1,fieldsData_1_1,_d,fieldId,fieldIndex,fieldIndex_1,fieldIndex_1_1,_e,shortId,e_10_1,e_10,_f,e_11,_g,e_12,_h;return __generator(this,function(_j){switch(_j.label){case 0:if(initialDirtCount=this._dirtCount,!this.vacuumConditionsMet(conditions))return[3,10];batchSize=options.batchSize||defaultVacuumOptions.batchSize,batchWait_1=options.batchWait||defaultVacuumOptions.batchWait,i=1,_j.label=1;case 1:_j.trys.push([1,7,8,9]),_a3=__values(this._index),_b2=_a3.next(),_j.label=2;case 2:if(_b2.done)return[3,6];_c2=__read(_b2.value,2),term=_c2[0],fieldsData=_c2[1];try{for(fieldsData_1=(e_11=void 0,__values(fieldsData)),fieldsData_1_1=fieldsData_1.next();!fieldsData_1_1.done;fieldsData_1_1=fieldsData_1.next()){_d=__read(fieldsData_1_1.value,2),fieldId=_d[0],fieldIndex=_d[1];try{for(fieldIndex_1=(e_12=void 0,__values(fieldIndex)),fieldIndex_1_1=fieldIndex_1.next();!fieldIndex_1_1.done;fieldIndex_1_1=fieldIndex_1.next())_e=__read(fieldIndex_1_1.value,1),shortId=_e[0],!this._documentIds.has(shortId)&&(fieldIndex.size<=1?fieldsData.delete(fieldId):fieldIndex.delete(shortId))}catch(e_12_1){e_12={error:e_12_1}}finally{try{fieldIndex_1_1&&!fieldIndex_1_1.done&&(_h=fieldIndex_1.return)&&_h.call(fieldIndex_1)}finally{if(e_12)throw e_12.error}}}}catch(e_11_1){e_11={error:e_11_1}}finally{try{fieldsData_1_1&&!fieldsData_1_1.done&&(_g=fieldsData_1.return)&&_g.call(fieldsData_1)}finally{if(e_11)throw e_11.error}}return this._index.get(term).size===0&&this._index.delete(term),i%batchSize!==0?[3,4]:[4,new Promise(function(resolve){return setTimeout(resolve,batchWait_1)})];case 3:_j.sent(),_j.label=4;case 4:i+=1,_j.label=5;case 5:return _b2=_a3.next(),[3,2];case 6:return[3,9];case 7:return e_10_1=_j.sent(),e_10={error:e_10_1},[3,9];case 8:try{_b2&&!_b2.done&&(_f=_a3.return)&&_f.call(_a3)}finally{if(e_10)throw e_10.error}return[7];case 9:this._dirtCount-=initialDirtCount,_j.label=10;case 10:return[4,null];case 11:return _j.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},MiniSearch2.prototype.vacuumConditionsMet=function(conditions){if(conditions==null)return!0;var minDirtCount=conditions.minDirtCount,minDirtFactor=conditions.minDirtFactor;return minDirtCount=minDirtCount||defaultAutoVacuumOptions.minDirtCount,minDirtFactor=minDirtFactor||defaultAutoVacuumOptions.minDirtFactor,this.dirtCount>=minDirtCount&&this.dirtFactor>=minDirtFactor},Object.defineProperty(MiniSearch2.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),MiniSearch2.prototype.has=function(id){return this._idToShortId.has(id)},MiniSearch2.prototype.getStoredFields=function(id){var shortId=this._idToShortId.get(id);if(shortId!=null)return this._storedFields.get(shortId)},MiniSearch2.prototype.search=function(query,searchOptions){var e_13,_a3;searchOptions===void 0&&(searchOptions={});var rawResults=this.executeQuery(query,searchOptions),results=[];try{for(var rawResults_1=__values(rawResults),rawResults_1_1=rawResults_1.next();!rawResults_1_1.done;rawResults_1_1=rawResults_1.next()){var _b2=__read(rawResults_1_1.value,2),docId=_b2[0],_c2=_b2[1],score2=_c2.score,terms=_c2.terms,match2=_c2.match,quality=terms.length||1,result={id:this._documentIds.get(docId),score:score2*quality,terms:Object.keys(match2),match:match2};Object.assign(result,this._storedFields.get(docId)),(searchOptions.filter==null||searchOptions.filter(result))&&results.push(result)}}catch(e_13_1){e_13={error:e_13_1}}finally{try{rawResults_1_1&&!rawResults_1_1.done&&(_a3=rawResults_1.return)&&_a3.call(rawResults_1)}finally{if(e_13)throw e_13.error}}return query===MiniSearch2.wildcard&&searchOptions.boostDocument==null&&this._options.searchOptions.boostDocument==null||results.sort(byScore),results},MiniSearch2.prototype.autoSuggest=function(queryString,options){var e_14,_a3,e_15,_b2;options===void 0&&(options={}),options=__assign(__assign({},this._options.autoSuggestOptions),options);var suggestions=new Map;try{for(var _c2=__values(this.search(queryString,options)),_d=_c2.next();!_d.done;_d=_c2.next()){var _e=_d.value,score2=_e.score,terms=_e.terms,phrase2=terms.join(" "),suggestion=suggestions.get(phrase2);suggestion!=null?(suggestion.score+=score2,suggestion.count+=1):suggestions.set(phrase2,{score:score2,terms,count:1})}}catch(e_14_1){e_14={error:e_14_1}}finally{try{_d&&!_d.done&&(_a3=_c2.return)&&_a3.call(_c2)}finally{if(e_14)throw e_14.error}}var results=[];try{for(var suggestions_1=__values(suggestions),suggestions_1_1=suggestions_1.next();!suggestions_1_1.done;suggestions_1_1=suggestions_1.next()){var _f=__read(suggestions_1_1.value,2),suggestion=_f[0],_g=_f[1],score2=_g.score,terms=_g.terms,count=_g.count;results.push({suggestion,terms,score:score2/count})}}catch(e_15_1){e_15={error:e_15_1}}finally{try{suggestions_1_1&&!suggestions_1_1.done&&(_b2=suggestions_1.return)&&_b2.call(suggestions_1)}finally{if(e_15)throw e_15.error}}return results.sort(byScore),results},Object.defineProperty(MiniSearch2.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),MiniSearch2.loadJSON=function(json2,options){if(options==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(json2),options)},MiniSearch2.getDefault=function(optionName){if(defaultOptions.hasOwnProperty(optionName))return getOwnProperty(defaultOptions,optionName);throw new Error('MiniSearch: unknown option "'.concat(optionName,'"'))},MiniSearch2.loadJS=function(js,options){var e_16,_a3,e_17,_b2,e_18,_c2,index2=js.index,documentCount=js.documentCount,nextId=js.nextId,documentIds=js.documentIds,fieldIds=js.fieldIds,fieldLength=js.fieldLength,averageFieldLength=js.averageFieldLength,storedFields=js.storedFields,dirtCount=js.dirtCount,serializationVersion=js.serializationVersion;if(serializationVersion!==1&&serializationVersion!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var miniSearch=new MiniSearch2(options);miniSearch._documentCount=documentCount,miniSearch._nextId=nextId,miniSearch._documentIds=objectToNumericMap(documentIds),miniSearch._idToShortId=new Map,miniSearch._fieldIds=fieldIds,miniSearch._fieldLength=objectToNumericMap(fieldLength),miniSearch._avgFieldLength=averageFieldLength,miniSearch._storedFields=objectToNumericMap(storedFields),miniSearch._dirtCount=dirtCount||0,miniSearch._index=new SearchableMap;try{for(var _d=__values(miniSearch._documentIds),_e=_d.next();!_e.done;_e=_d.next()){var _f=__read(_e.value,2),shortId=_f[0],id=_f[1];miniSearch._idToShortId.set(id,shortId)}}catch(e_16_1){e_16={error:e_16_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_16)throw e_16.error}}try{for(var index_1=__values(index2),index_1_1=index_1.next();!index_1_1.done;index_1_1=index_1.next()){var _g=__read(index_1_1.value,2),term=_g[0],data=_g[1],dataMap=new Map;try{for(var _h=(e_18=void 0,__values(Object.keys(data))),_j=_h.next();!_j.done;_j=_h.next()){var fieldId=_j.value,indexEntry=data[fieldId];serializationVersion===1&&(indexEntry=indexEntry.ds),dataMap.set(parseInt(fieldId,10),objectToNumericMap(indexEntry))}}catch(e_18_1){e_18={error:e_18_1}}finally{try{_j&&!_j.done&&(_c2=_h.return)&&_c2.call(_h)}finally{if(e_18)throw e_18.error}}miniSearch._index.set(term,dataMap)}}catch(e_17_1){e_17={error:e_17_1}}finally{try{index_1_1&&!index_1_1.done&&(_b2=index_1.return)&&_b2.call(index_1)}finally{if(e_17)throw e_17.error}}return miniSearch},MiniSearch2.prototype.executeQuery=function(query,searchOptions){var _this=this;if(searchOptions===void 0&&(searchOptions={}),query===MiniSearch2.wildcard)return this.executeWildcardQuery(searchOptions);if(typeof query!="string"){var options_1=__assign(__assign(__assign({},searchOptions),query),{queries:void 0}),results_1=query.queries.map(function(subquery){return _this.executeQuery(subquery,options_1)});return this.combineResults(results_1,options_1.combineWith)}var _a3=this._options,tokenize=_a3.tokenize,processTerm=_a3.processTerm,globalSearchOptions=_a3.searchOptions,options=__assign(__assign({tokenize,processTerm},globalSearchOptions),searchOptions),searchTokenize=options.tokenize,searchProcessTerm=options.processTerm,terms=searchTokenize(query).flatMap(function(term){return searchProcessTerm(term)}).filter(function(term){return!!term}),queries=terms.map(termToQuerySpec(options)),results=queries.map(function(query2){return _this.executeQuerySpec(query2,options)});return this.combineResults(results,options.combineWith)},MiniSearch2.prototype.executeQuerySpec=function(query,searchOptions){var e_19,_a3,e_20,_b2,options=__assign(__assign({},this._options.searchOptions),searchOptions),boosts=(options.fields||this._options.fields).reduce(function(boosts2,field){var _a4;return __assign(__assign({},boosts2),(_a4={},_a4[field]=getOwnProperty(options.boost,field)||1,_a4))},{}),boostDocument=options.boostDocument,weights=options.weights,maxFuzzy=options.maxFuzzy,bm25params=options.bm25,_c2=__assign(__assign({},defaultSearchOptions.weights),weights),fuzzyWeight=_c2.fuzzy,prefixWeight=_c2.prefix,data=this._index.get(query.term),results=this.termResults(query.term,query.term,1,data,boosts,boostDocument,bm25params),prefixMatches,fuzzyMatches;if(query.prefix&&(prefixMatches=this._index.atPrefix(query.term)),query.fuzzy){var fuzzy=query.fuzzy===!0?.2:query.fuzzy,maxDistance=fuzzy<1?Math.min(maxFuzzy,Math.round(query.term.length*fuzzy)):fuzzy;maxDistance&&(fuzzyMatches=this._index.fuzzyGet(query.term,maxDistance))}if(prefixMatches)try{for(var prefixMatches_1=__values(prefixMatches),prefixMatches_1_1=prefixMatches_1.next();!prefixMatches_1_1.done;prefixMatches_1_1=prefixMatches_1.next()){var _d=__read(prefixMatches_1_1.value,2),term=_d[0],data_1=_d[1],distance=term.length-query.term.length;if(distance){fuzzyMatches?.delete(term);var weight=prefixWeight*term.length/(term.length+.3*distance);this.termResults(query.term,term,weight,data_1,boosts,boostDocument,bm25params,results)}}}catch(e_19_1){e_19={error:e_19_1}}finally{try{prefixMatches_1_1&&!prefixMatches_1_1.done&&(_a3=prefixMatches_1.return)&&_a3.call(prefixMatches_1)}finally{if(e_19)throw e_19.error}}if(fuzzyMatches)try{for(var _e=__values(fuzzyMatches.keys()),_f=_e.next();!_f.done;_f=_e.next()){var term=_f.value,_g=__read(fuzzyMatches.get(term),2),data_2=_g[0],distance=_g[1];if(distance){var weight=fuzzyWeight*term.length/(term.length+distance);this.termResults(query.term,term,weight,data_2,boosts,boostDocument,bm25params,results)}}}catch(e_20_1){e_20={error:e_20_1}}finally{try{_f&&!_f.done&&(_b2=_e.return)&&_b2.call(_e)}finally{if(e_20)throw e_20.error}}return results},MiniSearch2.prototype.executeWildcardQuery=function(searchOptions){var e_21,_a3,results=new Map,options=__assign(__assign({},this._options.searchOptions),searchOptions);try{for(var _b2=__values(this._documentIds),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var _d=__read(_c2.value,2),shortId=_d[0],id=_d[1],score2=options.boostDocument?options.boostDocument(id,"",this._storedFields.get(shortId)):1;results.set(shortId,{score:score2,terms:[],match:{}})}}catch(e_21_1){e_21={error:e_21_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_21)throw e_21.error}}return results},MiniSearch2.prototype.combineResults=function(results,combineWith){if(combineWith===void 0&&(combineWith=OR),results.length===0)return new Map;var operator2=combineWith.toLowerCase();return results.reduce(combinators[operator2])||new Map},MiniSearch2.prototype.toJSON=function(){var e_22,_a3,e_23,_b2,index2=[];try{for(var _c2=__values(this._index),_d=_c2.next();!_d.done;_d=_c2.next()){var _e=__read(_d.value,2),term=_e[0],fieldIndex=_e[1],data={};try{for(var fieldIndex_2=(e_23=void 0,__values(fieldIndex)),fieldIndex_2_1=fieldIndex_2.next();!fieldIndex_2_1.done;fieldIndex_2_1=fieldIndex_2.next()){var _f=__read(fieldIndex_2_1.value,2),fieldId=_f[0],freqs=_f[1];data[fieldId]=Object.fromEntries(freqs)}}catch(e_23_1){e_23={error:e_23_1}}finally{try{fieldIndex_2_1&&!fieldIndex_2_1.done&&(_b2=fieldIndex_2.return)&&_b2.call(fieldIndex_2)}finally{if(e_23)throw e_23.error}}index2.push([term,data])}}catch(e_22_1){e_22={error:e_22_1}}finally{try{_d&&!_d.done&&(_a3=_c2.return)&&_a3.call(_c2)}finally{if(e_22)throw e_22.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:index2,serializationVersion:2}},MiniSearch2.prototype.termResults=function(sourceTerm,derivedTerm,termWeight,fieldTermData,fieldBoosts,boostDocumentFn,bm25params,results){var e_24,_a3,e_25,_b2,_c2;if(results===void 0&&(results=new Map),fieldTermData==null)return results;try{for(var _d=__values(Object.keys(fieldBoosts)),_e=_d.next();!_e.done;_e=_d.next()){var field=_e.value,fieldBoost=fieldBoosts[field],fieldId=this._fieldIds[field],fieldTermFreqs=fieldTermData.get(fieldId);if(fieldTermFreqs!=null){var matchingFields=fieldTermFreqs.size,avgFieldLength=this._avgFieldLength[fieldId];try{for(var _f=(e_25=void 0,__values(fieldTermFreqs.keys())),_g=_f.next();!_g.done;_g=_f.next()){var docId=_g.value;if(!this._documentIds.has(docId)){this.removeTerm(fieldId,docId,derivedTerm),matchingFields-=1;continue}var docBoost=boostDocumentFn?boostDocumentFn(this._documentIds.get(docId),derivedTerm,this._storedFields.get(docId)):1;if(docBoost){var termFreq=fieldTermFreqs.get(docId),fieldLength=this._fieldLength.get(docId)[fieldId],rawScore=calcBM25Score(termFreq,matchingFields,this._documentCount,fieldLength,avgFieldLength,bm25params),weightedScore=termWeight*fieldBoost*docBoost*rawScore,result=results.get(docId);if(result){result.score+=weightedScore,assignUniqueTerm(result.terms,sourceTerm);var match2=getOwnProperty(result.match,derivedTerm);match2?match2.push(field):result.match[derivedTerm]=[field]}else results.set(docId,{score:weightedScore,terms:[sourceTerm],match:(_c2={},_c2[derivedTerm]=[field],_c2)})}}}catch(e_25_1){e_25={error:e_25_1}}finally{try{_g&&!_g.done&&(_b2=_f.return)&&_b2.call(_f)}finally{if(e_25)throw e_25.error}}}}}catch(e_24_1){e_24={error:e_24_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_24)throw e_24.error}}return results},MiniSearch2.prototype.addTerm=function(fieldId,documentId,term){var indexData=this._index.fetch(term,createMap),fieldIndex=indexData.get(fieldId);if(fieldIndex==null)fieldIndex=new Map,fieldIndex.set(documentId,1),indexData.set(fieldId,fieldIndex);else{var docs=fieldIndex.get(documentId);fieldIndex.set(documentId,(docs||0)+1)}},MiniSearch2.prototype.removeTerm=function(fieldId,documentId,term){if(!this._index.has(term)){this.warnDocumentChanged(documentId,fieldId,term);return}var indexData=this._index.fetch(term,createMap),fieldIndex=indexData.get(fieldId);fieldIndex==null||fieldIndex.get(documentId)==null?this.warnDocumentChanged(documentId,fieldId,term):fieldIndex.get(documentId)<=1?fieldIndex.size<=1?indexData.delete(fieldId):fieldIndex.delete(documentId):fieldIndex.set(documentId,fieldIndex.get(documentId)-1),this._index.get(term).size===0&&this._index.delete(term)},MiniSearch2.prototype.warnDocumentChanged=function(shortDocumentId,fieldId,term){var e_26,_a3;try{for(var _b2=__values(Object.keys(this._fieldIds)),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var fieldName=_c2.value;if(this._fieldIds[fieldName]===fieldId){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(shortDocumentId),' has changed before removal: term "').concat(term,'" was not present in field "').concat(fieldName,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(e_26_1){e_26={error:e_26_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_26)throw e_26.error}}},MiniSearch2.prototype.addDocumentId=function(documentId){var shortDocumentId=this._nextId;return this._idToShortId.set(documentId,shortDocumentId),this._documentIds.set(shortDocumentId,documentId),this._documentCount+=1,this._nextId+=1,shortDocumentId},MiniSearch2.prototype.addFields=function(fields){for(var i=0;i<fields.length;i++)this._fieldIds[fields[i]]=i},MiniSearch2.prototype.addFieldLength=function(documentId,fieldId,count,length){var fieldLengths=this._fieldLength.get(documentId);fieldLengths==null&&this._fieldLength.set(documentId,fieldLengths=[]),fieldLengths[fieldId]=length;var averageFieldLength=this._avgFieldLength[fieldId]||0,totalFieldLength=averageFieldLength*count+length;this._avgFieldLength[fieldId]=totalFieldLength/(count+1)},MiniSearch2.prototype.removeFieldLength=function(documentId,fieldId,count,length){if(count===1){this._avgFieldLength[fieldId]=0;return}var totalFieldLength=this._avgFieldLength[fieldId]*count-length;this._avgFieldLength[fieldId]=totalFieldLength/(count-1)},MiniSearch2.prototype.saveStoredFields=function(documentId,doc2){var e_27,_a3,_b2=this._options,storeFields=_b2.storeFields,extractField=_b2.extractField;if(!(storeFields==null||storeFields.length===0)){var documentFields=this._storedFields.get(documentId);documentFields==null&&this._storedFields.set(documentId,documentFields={});try{for(var storeFields_1=__values(storeFields),storeFields_1_1=storeFields_1.next();!storeFields_1_1.done;storeFields_1_1=storeFields_1.next()){var fieldName=storeFields_1_1.value,fieldValue=extractField(doc2,fieldName);fieldValue!==void 0&&(documentFields[fieldName]=fieldValue)}}catch(e_27_1){e_27={error:e_27_1}}finally{try{storeFields_1_1&&!storeFields_1_1.done&&(_a3=storeFields_1.return)&&_a3.call(storeFields_1)}finally{if(e_27)throw e_27.error}}}},MiniSearch2.wildcard=Symbol("*"),MiniSearch2}(),getOwnProperty=__name2(function(object,property){return Object.prototype.hasOwnProperty.call(object,property)?object[property]:void 0},"getOwnProperty"),combinators=(_a$1={},_a$1[OR]=function(a,b){var e_28,_a3;try{for(var _b2=__values(b.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var docId=_c2.value,existing=a.get(docId);if(existing==null)a.set(docId,b.get(docId));else{var _d=b.get(docId),score2=_d.score,terms=_d.terms,match2=_d.match;existing.score=existing.score+score2,existing.match=Object.assign(existing.match,match2),assignUniqueTerms(existing.terms,terms)}}}catch(e_28_1){e_28={error:e_28_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_28)throw e_28.error}}return a},_a$1[AND]=function(a,b){var e_29,_a3,combined=new Map;try{for(var _b2=__values(b.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var docId=_c2.value,existing=a.get(docId);if(existing!=null){var _d=b.get(docId),score2=_d.score,terms=_d.terms,match2=_d.match;assignUniqueTerms(existing.terms,terms),combined.set(docId,{score:existing.score+score2,terms:existing.terms,match:Object.assign(existing.match,match2)})}}}catch(e_29_1){e_29={error:e_29_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_29)throw e_29.error}}return combined},_a$1[AND_NOT]=function(a,b){var e_30,_a3;try{for(var _b2=__values(b.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var docId=_c2.value;a.delete(docId)}}catch(e_30_1){e_30={error:e_30_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_30)throw e_30.error}}return a},_a$1),defaultBM25params={k:1.2,b:.7,d:.5},calcBM25Score=__name2(function(termFreq,matchingCount,totalCount,fieldLength,avgFieldLength,bm25params){var k=bm25params.k,b=bm25params.b,d=bm25params.d,invDocFreq=Math.log(1+(totalCount-matchingCount+.5)/(matchingCount+.5));return invDocFreq*(d+termFreq*(k+1)/(termFreq+k*(1-b+b*fieldLength/avgFieldLength)))},"calcBM25Score"),termToQuerySpec=__name2(function(options){return function(term,i,terms){var fuzzy=typeof options.fuzzy=="function"?options.fuzzy(term,i,terms):options.fuzzy||!1,prefix=typeof options.prefix=="function"?options.prefix(term,i,terms):options.prefix===!0;return{term,fuzzy,prefix}}},"termToQuerySpec"),defaultOptions={idField:"id",extractField:function(document2,fieldName){return document2[fieldName]},tokenize:function(text){return text.split(SPACE_OR_PUNCTUATION)},processTerm:function(term){return term.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(level,message){typeof console?.[level]=="function"&&console[level](message)},autoVacuum:!0},defaultSearchOptions={combineWith:OR,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:defaultBM25params},defaultAutoSuggestOptions={combineWith:AND,prefix:function(term,i,terms){return i===terms.length-1}},defaultVacuumOptions={batchSize:1e3,batchWait:10},defaultVacuumConditions={minDirtFactor:.1,minDirtCount:20},defaultAutoVacuumOptions=__assign(__assign({},defaultVacuumOptions),defaultVacuumConditions),assignUniqueTerm=__name2(function(target,term){target.includes(term)||target.push(term)},"assignUniqueTerm"),assignUniqueTerms=__name2(function(target,source){var e_31,_a3;try{for(var source_1=__values(source),source_1_1=source_1.next();!source_1_1.done;source_1_1=source_1.next()){var term=source_1_1.value;target.includes(term)||target.push(term)}}catch(e_31_1){e_31={error:e_31_1}}finally{try{source_1_1&&!source_1_1.done&&(_a3=source_1.return)&&_a3.call(source_1)}finally{if(e_31)throw e_31.error}}},"assignUniqueTerms"),byScore=__name2(function(_a3,_b2){var a=_a3.score,b=_b2.score;return b-a},"byScore"),createMap=__name2(function(){return new Map},"createMap"),objectToNumericMap=__name2(function(object){var e_32,_a3,map2=new Map;try{for(var _b2=__values(Object.keys(object)),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var key=_c2.value;map2.set(parseInt(key,10),object[key])}}catch(e_32_1){e_32={error:e_32_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_32)throw e_32.error}}return map2},"objectToNumericMap"),SPACE_OR_PUNCTUATION=/[\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\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\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\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\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\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-\u2E4F\u3000-\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]+/u;const _Text=class _Text2{static{__name(this,"_Text")}lineAt(pos){if(pos<0||pos>this.length)throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);return this.lineInner(pos,!1,1,0)}line(n2){if(n2<1||n2>this.lines)throw new RangeError(`Invalid line number ${n2} in ${this.lines}-line document`);return this.lineInner(n2,!0,1,0)}replace(from,to,text){let parts=[];return this.decompose(0,from,parts,2),text.length&&text.decompose(0,text.length,parts,3),this.decompose(to,this.length,parts,1),TextNode.from(parts,this.length-(to-from)+text.length)}append(other){return this.replace(this.length,this.length,other)}slice(from,to=this.length){let parts=[];return this.decompose(from,to,parts,0),TextNode.from(parts,to-from)}eq(other){if(other==this)return!0;if(other.length!=this.length||other.lines!=this.lines)return!1;let start=this.scanIdentical(other,1),end=this.length-this.scanIdentical(other,-1),a=new RawTextCursor(this),b=new RawTextCursor(other);for(let skip=start,pos=start;;){if(a.next(skip),b.next(skip),skip=0,a.lineBreak!=b.lineBreak||a.done!=b.done||a.value!=b.value)return!1;if(pos+=a.value.length,a.done||pos>=end)return!0}}iter(dir=1){return new RawTextCursor(this,dir)}iterRange(from,to=this.length){return new PartialTextCursor(this,from,to)}iterLines(from,to){let inner;if(from==null)inner=this.iter();else{to==null&&(to=this.lines+1);let start=this.line(from).from;inner=this.iterRange(start,Math.max(start,to==this.lines+1?this.length:to<=1?0:this.line(to-1).to))}return new LineCursor(inner)}toString(){return this.sliceString(0)}toJSON(){let lines=[];return this.flatten(lines),lines}constructor(){}static of(text){if(text.length==0)throw new RangeError("A document must have at least one line");return text.length==1&&!text[0]?_Text2.empty:text.length<=32?new TextLeaf(text):TextNode.from(TextLeaf.split(text,[]))}};__name2(_Text,"Text");let Text=_Text;const _TextLeaf=class _TextLeaf2 extends Text{static{__name(this,"_TextLeaf")}constructor(text,length=textLength(text)){super(),this.text=text,this.length=length}get lines(){return this.text.length}get children(){return null}lineInner(target,isLine,line,offset2){for(let i=0;;i++){let string2=this.text[i],end=offset2+string2.length;if((isLine?line:end)>=target)return new Line(offset2,end,line,string2);offset2=end+1,line++}}decompose(from,to,target,open){let text=from<=0&&to>=this.length?this:new _TextLeaf2(sliceText(this.text,from,to),Math.min(to,this.length)-Math.max(0,from));if(open&1){let prev=target.pop(),joined=appendText(text.text,prev.text.slice(),0,text.length);if(joined.length<=32)target.push(new _TextLeaf2(joined,prev.length+text.length));else{let mid=joined.length>>1;target.push(new _TextLeaf2(joined.slice(0,mid)),new _TextLeaf2(joined.slice(mid)))}}else target.push(text)}replace(from,to,text){if(!(text instanceof _TextLeaf2))return super.replace(from,to,text);let lines=appendText(this.text,appendText(text.text,sliceText(this.text,0,from)),to),newLen=this.length+text.length-(to-from);return lines.length<=32?new _TextLeaf2(lines,newLen):TextNode.from(_TextLeaf2.split(lines,[]),newLen)}sliceString(from,to=this.length,lineSep=`
`){let result="";for(let pos=0,i=0;pos<=to&&i<this.text.length;i++){let line=this.text[i],end=pos+line.length;pos>from&&i&&(result+=lineSep),from<end&&to>pos&&(result+=line.slice(Math.max(0,from-pos),to-pos)),pos=end+1}return result}flatten(target){for(let line of this.text)target.push(line)}scanIdentical(){return 0}static split(text,target){let part=[],len=-1;for(let line of text)part.push(line),len+=line.length+1,part.length==32&&(target.push(new _TextLeaf2(part,len)),part=[],len=-1);return len>-1&&target.push(new _TextLeaf2(part,len)),target}};__name2(_TextLeaf,"TextLeaf");let TextLeaf=_TextLeaf;const _TextNode=class _TextNode2 extends Text{static{__name(this,"_TextNode")}constructor(children,length){super(),this.children=children,this.length=length,this.lines=0;for(let child of children)this.lines+=child.lines}lineInner(target,isLine,line,offset2){for(let i=0;;i++){let child=this.children[i],end=offset2+child.length,endLine=line+child.lines-1;if((isLine?endLine:end)>=target)return child.lineInner(target,isLine,line,offset2);offset2=end+1,line=endLine+1}}decompose(from,to,target,open){for(let i=0,pos=0;pos<=to&&i<this.children.length;i++){let child=this.children[i],end=pos+child.length;if(from<=end&&to>=pos){let childOpen=open&((pos<=from?1:0)|(end>=to?2:0));pos>=from&&end<=to&&!childOpen?target.push(child):child.decompose(from-pos,to-pos,target,childOpen)}pos=end+1}}replace(from,to,text){if(text.lines<this.lines)for(let i=0,pos=0;i<this.children.length;i++){let child=this.children[i],end=pos+child.length;if(from>=pos&&to<=end){let updated=child.replace(from-pos,to-pos,text),totalLines=this.lines-child.lines+updated.lines;if(updated.lines<totalLines>>5-1&&updated.lines>totalLines>>5+1){let copy=this.children.slice();return copy[i]=updated,new _TextNode2(copy,this.length-(to-from)+text.length)}return super.replace(pos,end,updated)}pos=end+1}return super.replace(from,to,text)}sliceString(from,to=this.length,lineSep=`
`){let result="";for(let i=0,pos=0;i<this.children.length&&pos<=to;i++){let child=this.children[i],end=pos+child.length;pos>from&&i&&(result+=lineSep),from<end&&to>pos&&(result+=child.sliceString(from-pos,to-pos,lineSep)),pos=end+1}return result}flatten(target){for(let child of this.children)child.flatten(target)}scanIdentical(other,dir){if(!(other instanceof _TextNode2))return 0;let length=0,[iA,iB,eA,eB]=dir>0?[0,0,this.children.length,other.children.length]:[this.children.length-1,other.children.length-1,-1,-1];for(;;iA+=dir,iB+=dir){if(iA==eA||iB==eB)return length;let chA=this.children[iA],chB=other.children[iB];if(chA!=chB)return length+chA.scanIdentical(chB,dir);length+=chA.length+1}}static from(children,length=children.reduce((l2,ch)=>l2+ch.length+1,-1)){let lines=0;for(let ch of children)lines+=ch.lines;if(lines<32){let flat=[];for(let ch of children)ch.flatten(flat);return new TextLeaf(flat,length)}let chunk=Math.max(32,lines>>5),maxChunk=chunk<<1,minChunk=chunk>>1,chunked=[],currentLines=0,currentLen=-1,currentChunk=[];function add2(child){let last2;if(child.lines>maxChunk&&child instanceof _TextNode2)for(let node of child.children)add2(node);else child.lines>minChunk&&(currentLines>minChunk||!currentLines)?(flush(),chunked.push(child)):child instanceof TextLeaf&&currentLines&&(last2=currentChunk[currentChunk.length-1])instanceof TextLeaf&&child.lines+last2.lines<=32?(currentLines+=child.lines,currentLen+=child.length+1,currentChunk[currentChunk.length-1]=new TextLeaf(last2.text.concat(child.text),last2.length+1+child.length)):(currentLines+child.lines>chunk&&flush(),currentLines+=child.lines,currentLen+=child.length+1,currentChunk.push(child))}__name(add2,"add2"),__name2(add2,"add");function flush(){currentLines!=0&&(chunked.push(currentChunk.length==1?currentChunk[0]:_TextNode2.from(currentChunk,currentLen)),currentLen=-1,currentLines=currentChunk.length=0)}__name(flush,"flush"),__name2(flush,"flush");for(let child of children)add2(child);return flush(),chunked.length==1?chunked[0]:new _TextNode2(chunked,length)}};__name2(_TextNode,"TextNode");let TextNode=_TextNode;Text.empty=new TextLeaf([""],0);function textLength(text){let length=-1;for(let line of text)length+=line.length+1;return length}__name(textLength,"textLength"),__name2(textLength,"textLength");function appendText(text,target,from=0,to=1e9){for(let pos=0,i=0,first=!0;i<text.length&&pos<=to;i++){let line=text[i],end=pos+line.length;end>=from&&(end>to&&(line=line.slice(0,to-pos)),pos<from&&(line=line.slice(from-pos)),first?(target[target.length-1]+=line,first=!1):target.push(line)),pos=end+1}return target}__name(appendText,"appendText"),__name2(appendText,"appendText");function sliceText(text,from,to){return appendText(text,[""],from,to)}__name(sliceText,"sliceText"),__name2(sliceText,"sliceText");const _RawTextCursor=class{static{__name(this,"_RawTextCursor")}constructor(text,dir=1){this.dir=dir,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[text],this.offsets=[dir>0?1:(text instanceof TextLeaf?text.text.length:text.children.length)<<1]}nextInner(skip,dir){for(this.done=this.lineBreak=!1;;){let last2=this.nodes.length-1,top2=this.nodes[last2],offsetValue=this.offsets[last2],offset2=offsetValue>>1,size=top2 instanceof TextLeaf?top2.text.length:top2.children.length;if(offset2==(dir>0?size:0)){if(last2==0)return this.done=!0,this.value="",this;dir>0&&this.offsets[last2-1]++,this.nodes.pop(),this.offsets.pop()}else if((offsetValue&1)==(dir>0?0:1)){if(this.offsets[last2]+=dir,skip==0)return this.lineBreak=!0,this.value=`
`,this;skip--}else if(top2 instanceof TextLeaf){let next=top2.text[offset2+(dir<0?-1:0)];if(this.offsets[last2]+=dir,next.length>Math.max(0,skip))return this.value=skip==0?next:dir>0?next.slice(skip):next.slice(0,next.length-skip),this;skip-=next.length}else{let next=top2.children[offset2+(dir<0?-1:0)];skip>next.length?(skip-=next.length,this.offsets[last2]+=dir):(dir<0&&this.offsets[last2]--,this.nodes.push(next),this.offsets.push(dir>0?1:(next instanceof TextLeaf?next.text.length:next.children.length)<<1))}}}next(skip=0){return skip<0&&(this.nextInner(-skip,-this.dir),skip=this.value.length),this.nextInner(skip,this.dir)}};__name2(_RawTextCursor,"RawTextCursor");let RawTextCursor=_RawTextCursor;const _PartialTextCursor=class{static{__name(this,"_PartialTextCursor")}constructor(text,start,end){this.value="",this.done=!1,this.cursor=new RawTextCursor(text,start>end?-1:1),this.pos=start>end?text.length:0,this.from=Math.min(start,end),this.to=Math.max(start,end)}nextInner(skip,dir){if(dir<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;skip+=Math.max(0,dir<0?this.pos-this.to:this.from-this.pos);let limit2=dir<0?this.pos-this.from:this.to-this.pos;skip>limit2&&(skip=limit2),limit2-=skip;let{value}=this.cursor.next(skip);return this.pos+=(value.length+skip)*dir,this.value=value.length<=limit2?value:dir<0?value.slice(value.length-limit2):value.slice(0,limit2),this.done=!this.value,this}next(skip=0){return skip<0?skip=Math.max(skip,this.from-this.pos):skip>0&&(skip=Math.min(skip,this.to-this.pos)),this.nextInner(skip,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}};__name2(_PartialTextCursor,"PartialTextCursor");let PartialTextCursor=_PartialTextCursor;const _LineCursor=class{static{__name(this,"_LineCursor")}constructor(inner){this.inner=inner,this.afterBreak=!0,this.value="",this.done=!1}next(skip=0){let{done,lineBreak,value}=this.inner.next(skip);return done?(this.done=!0,this.value=""):lineBreak?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=value,this.afterBreak=!1),this}get lineBreak(){return!1}};__name2(_LineCursor,"LineCursor");let LineCursor=_LineCursor;typeof Symbol<"u"&&(Text.prototype[Symbol.iterator]=function(){return this.iter()},RawTextCursor.prototype[Symbol.iterator]=PartialTextCursor.prototype[Symbol.iterator]=LineCursor.prototype[Symbol.iterator]=function(){return this});const _Line=class{static{__name(this,"_Line")}constructor(from,to,number2,text){this.from=from,this.to=to,this.number=number2,this.text=text}get length(){return this.to-this.from}};__name2(_Line,"Line");let Line=_Line,extend="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s2=>s2?parseInt(s2,36):1);for(let i=1;i<extend.length;i++)extend[i]+=extend[i-1];function isExtendingChar(code){for(let i=1;i<extend.length;i+=2)if(extend[i]>code)return extend[i-1]<=code;return!1}__name(isExtendingChar,"isExtendingChar"),__name2(isExtendingChar,"isExtendingChar");function isRegionalIndicator(code){return code>=127462&&code<=127487}__name(isRegionalIndicator,"isRegionalIndicator"),__name2(isRegionalIndicator,"isRegionalIndicator");const ZWJ=8205;function findClusterBreak(str,pos,forward=!0,includeExtending=!0){return(forward?nextClusterBreak:prevClusterBreak)(str,pos,includeExtending)}__name(findClusterBreak,"findClusterBreak"),__name2(findClusterBreak,"findClusterBreak");function nextClusterBreak(str,pos,includeExtending){if(pos==str.length)return pos;pos&&surrogateLow(str.charCodeAt(pos))&&surrogateHigh(str.charCodeAt(pos-1))&&pos--;let prev=codePointAt(str,pos);for(pos+=codePointSize(prev);pos<str.length;){let next=codePointAt(str,pos);if(prev==ZWJ||next==ZWJ||includeExtending&&isExtendingChar(next))pos+=codePointSize(next),prev=next;else if(isRegionalIndicator(next)){let countBefore=0,i=pos-2;for(;i>=0&&isRegionalIndicator(codePointAt(str,i));)countBefore++,i-=2;if(countBefore%2==0)break;pos+=2}else break}return pos}__name(nextClusterBreak,"nextClusterBreak"),__name2(nextClusterBreak,"nextClusterBreak");function prevClusterBreak(str,pos,includeExtending){for(;pos>0;){let found=nextClusterBreak(str,pos-2,includeExtending);if(found<pos)return found;pos--}return 0}__name(prevClusterBreak,"prevClusterBreak"),__name2(prevClusterBreak,"prevClusterBreak");function surrogateLow(ch){return ch>=56320&&ch<57344}__name(surrogateLow,"surrogateLow"),__name2(surrogateLow,"surrogateLow");function surrogateHigh(ch){return ch>=55296&&ch<56320}__name(surrogateHigh,"surrogateHigh"),__name2(surrogateHigh,"surrogateHigh");function codePointAt(str,pos){let code0=str.charCodeAt(pos);if(!surrogateHigh(code0)||pos+1==str.length)return code0;let code1=str.charCodeAt(pos+1);return surrogateLow(code1)?(code0-55296<<10)+(code1-56320)+65536:code0}__name(codePointAt,"codePointAt"),__name2(codePointAt,"codePointAt");function fromCodePoint(code){return code<=65535?String.fromCharCode(code):(code-=65536,String.fromCharCode((code>>10)+55296,(code&1023)+56320))}__name(fromCodePoint,"fromCodePoint"),__name2(fromCodePoint,"fromCodePoint");function codePointSize(code){return code<65536?1:2}__name(codePointSize,"codePointSize"),__name2(codePointSize,"codePointSize");const DefaultSplit=/\r\n?|\n/;var MapMode=function(MapMode2){return MapMode2[MapMode2.Simple=0]="Simple",MapMode2[MapMode2.TrackDel=1]="TrackDel",MapMode2[MapMode2.TrackBefore=2]="TrackBefore",MapMode2[MapMode2.TrackAfter=3]="TrackAfter",MapMode2}(MapMode||(MapMode={}));const _ChangeDesc=class _ChangeDesc2{static{__name(this,"_ChangeDesc")}constructor(sections){this.sections=sections}get length(){let result=0;for(let i=0;i<this.sections.length;i+=2)result+=this.sections[i];return result}get newLength(){let result=0;for(let i=0;i<this.sections.length;i+=2){let ins=this.sections[i+1];result+=ins<0?this.sections[i]:ins}return result}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(f2){for(let i=0,posA=0,posB=0;i<this.sections.length;){let len=this.sections[i++],ins=this.sections[i++];ins<0?(f2(posA,posB,len),posB+=len):posB+=ins,posA+=len}}iterChangedRanges(f2,individual=!1){iterChanges(this,f2,individual)}get invertedDesc(){let sections=[];for(let i=0;i<this.sections.length;){let len=this.sections[i++],ins=this.sections[i++];ins<0?sections.push(len,ins):sections.push(ins,len)}return new _ChangeDesc2(sections)}composeDesc(other){return this.empty?other:other.empty?this:composeSets(this,other)}mapDesc(other,before=!1){return other.empty?this:mapSet(this,other,before)}mapPos(pos,assoc=-1,mode=MapMode.Simple){let posA=0,posB=0;for(let i=0;i<this.sections.length;){let len=this.sections[i++],ins=this.sections[i++],endA=posA+len;if(ins<0){if(endA>pos)return posB+(pos-posA);posB+=len}else{if(mode!=MapMode.Simple&&endA>=pos&&(mode==MapMode.TrackDel&&posA<pos&&endA>pos||mode==MapMode.TrackBefore&&posA<pos||mode==MapMode.TrackAfter&&endA>pos))return null;if(endA>pos||endA==pos&&assoc<0&&!len)return pos==posA||assoc<0?posB:posB+ins;posB+=ins}posA=endA}if(pos>posA)throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);return posB}touchesRange(from,to=from){for(let i=0,pos=0;i<this.sections.length&&pos<=to;){let len=this.sections[i++],ins=this.sections[i++],end=pos+len;if(ins>=0&&pos<=to&&end>=from)return pos<from&&end>to?"cover":!0;pos=end}return!1}toString(){let result="";for(let i=0;i<this.sections.length;){let len=this.sections[i++],ins=this.sections[i++];result+=(result?" ":"")+len+(ins>=0?":"+ins:"")}return result}toJSON(){return this.sections}static fromJSON(json2){if(!Array.isArray(json2)||json2.length%2||json2.some(a=>typeof a!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new _ChangeDesc2(json2)}static create(sections){return new _ChangeDesc2(sections)}};__name2(_ChangeDesc,"ChangeDesc");let ChangeDesc=_ChangeDesc;const _ChangeSet=class _ChangeSet2 extends ChangeDesc{static{__name(this,"_ChangeSet")}constructor(sections,inserted){super(sections),this.inserted=inserted}apply(doc2){if(this.length!=doc2.length)throw new RangeError("Applying change set to a document with the wrong length");return iterChanges(this,(fromA,toA,fromB,_toB,text)=>doc2=doc2.replace(fromB,fromB+(toA-fromA),text),!1),doc2}mapDesc(other,before=!1){return mapSet(this,other,before,!0)}invert(doc2){let sections=this.sections.slice(),inserted=[];for(let i=0,pos=0;i<sections.length;i+=2){let len=sections[i],ins=sections[i+1];if(ins>=0){sections[i]=ins,sections[i+1]=len;let index2=i>>1;for(;inserted.length<index2;)inserted.push(Text.empty);inserted.push(len?doc2.slice(pos,pos+len):Text.empty)}pos+=len}return new _ChangeSet2(sections,inserted)}compose(other){return this.empty?other:other.empty?this:composeSets(this,other,!0)}map(other,before=!1){return other.empty?this:mapSet(this,other,before,!0)}iterChanges(f2,individual=!1){iterChanges(this,f2,individual)}get desc(){return ChangeDesc.create(this.sections)}filter(ranges){let resultSections=[],resultInserted=[],filteredSections=[],iter=new SectionIter(this);done:for(let i=0,pos=0;;){let next=i==ranges.length?1e9:ranges[i++];for(;pos<next||pos==next&&iter.len==0;){if(iter.done)break done;let len=Math.min(iter.len,next-pos);addSection(filteredSections,len,-1);let ins=iter.ins==-1?-1:iter.off==0?iter.ins:0;addSection(resultSections,len,ins),ins>0&&addInsert(resultInserted,resultSections,iter.text),iter.forward(len),pos+=len}let end=ranges[i++];for(;pos<end;){if(iter.done)break done;let len=Math.min(iter.len,end-pos);addSection(resultSections,len,-1),addSection(filteredSections,len,iter.ins==-1?-1:iter.off==0?iter.ins:0),iter.forward(len),pos+=len}}return{changes:new _ChangeSet2(resultSections,resultInserted),filtered:ChangeDesc.create(filteredSections)}}toJSON(){let parts=[];for(let i=0;i<this.sections.length;i+=2){let len=this.sections[i],ins=this.sections[i+1];ins<0?parts.push(len):ins==0?parts.push([len]):parts.push([len].concat(this.inserted[i>>1].toJSON()))}return parts}static of(changes,length,lineSep){let sections=[],inserted=[],pos=0,total=null;function flush(force=!1){if(!force&&!sections.length)return;pos<length&&addSection(sections,length-pos,-1);let set=new _ChangeSet2(sections,inserted);total=total?total.compose(set.map(total)):set,sections=[],inserted=[],pos=0}__name(flush,"flush"),__name2(flush,"flush");function process2(spec){if(Array.isArray(spec))for(let sub of spec)process2(sub);else if(spec instanceof _ChangeSet2){if(spec.length!=length)throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);flush(),total=total?total.compose(spec.map(total)):spec}else{let{from,to=from,insert:insert2}=spec;if(from>to||from<0||to>length)throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);let insText=insert2?typeof insert2=="string"?Text.of(insert2.split(lineSep||DefaultSplit)):insert2:Text.empty,insLen=insText.length;if(from==to&&insLen==0)return;from<pos&&flush(),from>pos&&addSection(sections,from-pos,-1),addSection(sections,to-from,insLen),addInsert(inserted,sections,insText),pos=to}}return __name(process2,"process2"),__name2(process2,"process"),process2(changes),flush(!total),total}static empty(length){return new _ChangeSet2(length?[length,-1]:[],[])}static fromJSON(json2){if(!Array.isArray(json2))throw new RangeError("Invalid JSON representation of ChangeSet");let sections=[],inserted=[];for(let i=0;i<json2.length;i++){let part=json2[i];if(typeof part=="number")sections.push(part,-1);else{if(!Array.isArray(part)||typeof part[0]!="number"||part.some((e,i2)=>i2&&typeof e!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(part.length==1)sections.push(part[0],0);else{for(;inserted.length<i;)inserted.push(Text.empty);inserted[i]=Text.of(part.slice(1)),sections.push(part[0],inserted[i].length)}}}return new _ChangeSet2(sections,inserted)}static createSet(sections,inserted){return new _ChangeSet2(sections,inserted)}};__name2(_ChangeSet,"ChangeSet");let ChangeSet=_ChangeSet;function addSection(sections,len,ins,forceJoin=!1){if(len==0&&ins<=0)return;let last2=sections.length-2;last2>=0&&ins<=0&&ins==sections[last2+1]?sections[last2]+=len:len==0&&sections[last2]==0?sections[last2+1]+=ins:forceJoin?(sections[last2]+=len,sections[last2+1]+=ins):sections.push(len,ins)}__name(addSection,"addSection"),__name2(addSection,"addSection");function addInsert(values,sections,value){if(value.length==0)return;let index2=sections.length-2>>1;if(index2<values.length)values[values.length-1]=values[values.length-1].append(value);else{for(;values.length<index2;)values.push(Text.empty);values.push(value)}}__name(addInsert,"addInsert"),__name2(addInsert,"addInsert");function iterChanges(desc,f2,individual){let inserted=desc.inserted;for(let posA=0,posB=0,i=0;i<desc.sections.length;){let len=desc.sections[i++],ins=desc.sections[i++];if(ins<0)posA+=len,posB+=len;else{let endA=posA,endB=posB,text=Text.empty;for(;endA+=len,endB+=ins,ins&&inserted&&(text=text.append(inserted[i-2>>1])),!(individual||i==desc.sections.length||desc.sections[i+1]<0);)len=desc.sections[i++],ins=desc.sections[i++];f2(posA,endA,posB,endB,text),posA=endA,posB=endB}}}__name(iterChanges,"iterChanges"),__name2(iterChanges,"iterChanges");function mapSet(setA,setB,before,mkSet=!1){let sections=[],insert2=mkSet?[]:null,a=new SectionIter(setA),b=new SectionIter(setB);for(let inserted=-1;;)if(a.ins==-1&&b.ins==-1){let len=Math.min(a.len,b.len);addSection(sections,len,-1),a.forward(len),b.forward(len)}else if(b.ins>=0&&(a.ins<0||inserted==a.i||a.off==0&&(b.len<a.len||b.len==a.len&&!before))){let len=b.len;for(addSection(sections,b.ins,-1);len;){let piece=Math.min(a.len,len);a.ins>=0&&inserted<a.i&&a.len<=piece&&(addSection(sections,0,a.ins),insert2&&addInsert(insert2,sections,a.text),inserted=a.i),a.forward(piece),len-=piece}b.next()}else if(a.ins>=0){let len=0,left=a.len;for(;left;)if(b.ins==-1){let piece=Math.min(left,b.len);len+=piece,left-=piece,b.forward(piece)}else if(b.ins==0&&b.len<left)left-=b.len,b.next();else break;addSection(sections,len,inserted<a.i?a.ins:0),insert2&&inserted<a.i&&addInsert(insert2,sections,a.text),inserted=a.i,a.forward(a.len-left)}else{if(a.done&&b.done)return insert2?ChangeSet.createSet(sections,insert2):ChangeDesc.create(sections);throw new Error("Mismatched change set lengths")}}__name(mapSet,"mapSet"),__name2(mapSet,"mapSet");function composeSets(setA,setB,mkSet=!1){let sections=[],insert2=mkSet?[]:null,a=new SectionIter(setA),b=new SectionIter(setB);for(let open=!1;;){if(a.done&&b.done)return insert2?ChangeSet.createSet(sections,insert2):ChangeDesc.create(sections);if(a.ins==0)addSection(sections,a.len,0,open),a.next();else if(b.len==0&&!b.done)addSection(sections,0,b.ins,open),insert2&&addInsert(insert2,sections,b.text),b.next();else{if(a.done||b.done)throw new Error("Mismatched change set lengths");{let len=Math.min(a.len2,b.len),sectionLen=sections.length;if(a.ins==-1){let insB=b.ins==-1?-1:b.off?0:b.ins;addSection(sections,len,insB,open),insert2&&insB&&addInsert(insert2,sections,b.text)}else b.ins==-1?(addSection(sections,a.off?0:a.len,len,open),insert2&&addInsert(insert2,sections,a.textBit(len))):(addSection(sections,a.off?0:a.len,b.off?0:b.ins,open),insert2&&!b.off&&addInsert(insert2,sections,b.text));open=(a.ins>len||b.ins>=0&&b.len>len)&&(open||sections.length>sectionLen),a.forward2(len),b.forward(len)}}}}__name(composeSets,"composeSets"),__name2(composeSets,"composeSets");const _SectionIter=class{static{__name(this,"_SectionIter")}constructor(set){this.set=set,this.i=0,this.next()}next(){let{sections}=this.set;this.i<sections.length?(this.len=sections[this.i++],this.ins=sections[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted}=this.set,index2=this.i-2>>1;return index2>=inserted.length?Text.empty:inserted[index2]}textBit(len){let{inserted}=this.set,index2=this.i-2>>1;return index2>=inserted.length&&!len?Text.empty:inserted[index2].slice(this.off,len==null?void 0:this.off+len)}forward(len){len==this.len?this.next():(this.len-=len,this.off+=len)}forward2(len){this.ins==-1?this.forward(len):len==this.ins?this.next():(this.ins-=len,this.off+=len)}};__name2(_SectionIter,"SectionIter");let SectionIter=_SectionIter;const _SelectionRange=class _SelectionRange2{static{__name(this,"_SelectionRange")}constructor(from,to,flags){this.from=from,this.to=to,this.flags=flags}get anchor(){return this.flags&16?this.to:this.from}get head(){return this.flags&16?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&4?-1:this.flags&8?1:0}get bidiLevel(){let level=this.flags&3;return level==3?null:level}get goalColumn(){let value=this.flags>>5;return value==33554431?void 0:value}map(change,assoc=-1){let from,to;return this.empty?from=to=change.mapPos(this.from,assoc):(from=change.mapPos(this.from,1),to=change.mapPos(this.to,-1)),from==this.from&&to==this.to?this:new _SelectionRange2(from,to,this.flags)}extend(from,to=from){if(from<=this.anchor&&to>=this.anchor)return EditorSelection.range(from,to);let head=Math.abs(from-this.anchor)>Math.abs(to-this.anchor)?from:to;return EditorSelection.range(this.anchor,head)}eq(other){return this.anchor==other.anchor&&this.head==other.head}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(json2){if(!json2||typeof json2.anchor!="number"||typeof json2.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return EditorSelection.range(json2.anchor,json2.head)}static create(from,to,flags){return new _SelectionRange2(from,to,flags)}};__name2(_SelectionRange,"SelectionRange");let SelectionRange=_SelectionRange;const _EditorSelection=class _EditorSelection2{static{__name(this,"_EditorSelection")}constructor(ranges,mainIndex){this.ranges=ranges,this.mainIndex=mainIndex}map(change,assoc=-1){return change.empty?this:_EditorSelection2.create(this.ranges.map(r=>r.map(change,assoc)),this.mainIndex)}eq(other){if(this.ranges.length!=other.ranges.length||this.mainIndex!=other.mainIndex)return!1;for(let i=0;i<this.ranges.length;i++)if(!this.ranges[i].eq(other.ranges[i]))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new _EditorSelection2([this.main],0)}addRange(range,main=!0){return _EditorSelection2.create([range].concat(this.ranges),main?0:this.mainIndex+1)}replaceRange(range,which=this.mainIndex){let ranges=this.ranges.slice();return ranges[which]=range,_EditorSelection2.create(ranges,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(r=>r.toJSON()),main:this.mainIndex}}static fromJSON(json2){if(!json2||!Array.isArray(json2.ranges)||typeof json2.main!="number"||json2.main>=json2.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new _EditorSelection2(json2.ranges.map(r=>SelectionRange.fromJSON(r)),json2.main)}static single(anchor,head=anchor){return new _EditorSelection2([_EditorSelection2.range(anchor,head)],0)}static create(ranges,mainIndex=0){if(ranges.length==0)throw new RangeError("A selection needs at least one range");for(let pos=0,i=0;i<ranges.length;i++){let range=ranges[i];if(range.empty?range.from<=pos:range.from<pos)return _EditorSelection2.normalized(ranges.slice(),mainIndex);pos=range.to}return new _EditorSelection2(ranges,mainIndex)}static cursor(pos,assoc=0,bidiLevel,goalColumn){return SelectionRange.create(pos,pos,(assoc==0?0:assoc<0?4:8)|(bidiLevel==null?3:Math.min(2,bidiLevel))|(goalColumn??33554431)<<5)}static range(anchor,head,goalColumn,bidiLevel){let flags=(goalColumn??33554431)<<5|(bidiLevel==null?3:Math.min(2,bidiLevel));return head<anchor?SelectionRange.create(head,anchor,24|flags):SelectionRange.create(anchor,head,(head>anchor?4:0)|flags)}static normalized(ranges,mainIndex=0){let main=ranges[mainIndex];ranges.sort((a,b)=>a.from-b.from),mainIndex=ranges.indexOf(main);for(let i=1;i<ranges.length;i++){let range=ranges[i],prev=ranges[i-1];if(range.empty?range.from<=prev.to:range.from<prev.to){let from=prev.from,to=Math.max(range.to,prev.to);i<=mainIndex&&mainIndex--,ranges.splice(--i,2,range.anchor>range.head?_EditorSelection2.range(to,from):_EditorSelection2.range(from,to))}}return new _EditorSelection2(ranges,mainIndex)}};__name2(_EditorSelection,"EditorSelection");let EditorSelection=_EditorSelection;function checkSelection(selection,docLength){for(let range of selection.ranges)if(range.to>docLength)throw new RangeError("Selection points outside of document")}__name(checkSelection,"checkSelection"),__name2(checkSelection,"checkSelection");let nextID=0;const _Facet=class _Facet2{static{__name(this,"_Facet")}constructor(combine,compareInput,compare2,isStatic,enables){this.combine=combine,this.compareInput=compareInput,this.compare=compare2,this.isStatic=isStatic,this.id=nextID++,this.default=combine([]),this.extensions=typeof enables=="function"?enables(this):enables}static define(config2={}){return new _Facet2(config2.combine||(a=>a),config2.compareInput||((a,b)=>a===b),config2.compare||(config2.combine?(a,b)=>a===b:sameArray$1),!!config2.static,config2.enables)}of(value){return new FacetProvider([],this,0,value)}compute(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,1,get)}computeN(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,2,get)}from(field,get){return get||(get=__name2(x=>x,"get")),this.compute([field],state=>get(state.field(field)))}};__name2(_Facet,"Facet");let Facet=_Facet;function sameArray$1(a,b){return a==b||a.length==b.length&&a.every((e,i)=>e===b[i])}__name(sameArray$1,"sameArray$1"),__name2(sameArray$1,"sameArray$1");const _FacetProvider=class{static{__name(this,"_FacetProvider")}constructor(dependencies,facet,type,value){this.dependencies=dependencies,this.facet=facet,this.type=type,this.value=value,this.id=nextID++}dynamicSlot(addresses){var _a3;let getter=this.value,compare2=this.facet.compareInput,id=this.id,idx=addresses[id]>>1,multi=this.type==2,depDoc=!1,depSel=!1,depAddrs=[];for(let dep of this.dependencies)dep=="doc"?depDoc=!0:dep=="selection"?depSel=!0:((_a3=addresses[dep.id])!==null&&_a3!==void 0?_a3:1)&1||depAddrs.push(addresses[dep.id]);return{create(state){return state.values[idx]=getter(state),1},update(state,tr){if(depDoc&&tr.docChanged||depSel&&(tr.docChanged||tr.selection)||ensureAll(state,depAddrs)){let newVal=getter(state);if(multi?!compareArray(newVal,state.values[idx],compare2):!compare2(newVal,state.values[idx]))return state.values[idx]=newVal,1}return 0},reconfigure:(state,oldState)=>{let newVal,oldAddr=oldState.config.address[id];if(oldAddr!=null){let oldVal=getAddr(oldState,oldAddr);if(this.dependencies.every(dep=>dep instanceof Facet?oldState.facet(dep)===state.facet(dep):dep instanceof StateField?oldState.field(dep,!1)==state.field(dep,!1):!0)||(multi?compareArray(newVal=getter(state),oldVal,compare2):compare2(newVal=getter(state),oldVal)))return state.values[idx]=oldVal,0}else newVal=getter(state);return state.values[idx]=newVal,1}}}};__name2(_FacetProvider,"FacetProvider");let FacetProvider=_FacetProvider;function compareArray(a,b,compare2){if(a.length!=b.length)return!1;for(let i=0;i<a.length;i++)if(!compare2(a[i],b[i]))return!1;return!0}__name(compareArray,"compareArray"),__name2(compareArray,"compareArray");function ensureAll(state,addrs){let changed=!1;for(let addr of addrs)ensureAddr(state,addr)&1&&(changed=!0);return changed}__name(ensureAll,"ensureAll"),__name2(ensureAll,"ensureAll");function dynamicFacetSlot(addresses,facet,providers){let providerAddrs=providers.map(p=>addresses[p.id]),providerTypes=providers.map(p=>p.type),dynamic=providerAddrs.filter(p=>!(p&1)),idx=addresses[facet.id]>>1;function get(state){let values=[];for(let i=0;i<providerAddrs.length;i++){let value=getAddr(state,providerAddrs[i]);if(providerTypes[i]==2)for(let val of value)values.push(val);else values.push(value)}return facet.combine(values)}return __name(get,"get"),__name2(get,"get"),{create(state){for(let addr of providerAddrs)ensureAddr(state,addr);return state.values[idx]=get(state),1},update(state,tr){if(!ensureAll(state,dynamic))return 0;let value=get(state);return facet.compare(value,state.values[idx])?0:(state.values[idx]=value,1)},reconfigure(state,oldState){let depChanged=ensureAll(state,providerAddrs),oldProviders=oldState.config.facets[facet.id],oldValue=oldState.facet(facet);if(oldProviders&&!depChanged&&sameArray$1(providers,oldProviders))return state.values[idx]=oldValue,0;let value=get(state);return facet.compare(value,oldValue)?(state.values[idx]=oldValue,0):(state.values[idx]=value,1)}}}__name(dynamicFacetSlot,"dynamicFacetSlot"),__name2(dynamicFacetSlot,"dynamicFacetSlot");const initField=Facet.define({static:!0}),_StateField=class _StateField2{static{__name(this,"_StateField")}constructor(id,createF,updateF,compareF,spec){this.id=id,this.createF=createF,this.updateF=updateF,this.compareF=compareF,this.spec=spec,this.provides=void 0}static define(config2){let field=new _StateField2(nextID++,config2.create,config2.update,config2.compare||((a,b)=>a===b),config2);return config2.provide&&(field.provides=config2.provide(field)),field}create(state){let init=state.facet(initField).find(i=>i.field==this);return(init?.create||this.createF)(state)}slot(addresses){let idx=addresses[this.id]>>1;return{create:state=>(state.values[idx]=this.create(state),1),update:(state,tr)=>{let oldVal=state.values[idx],value=this.updateF(oldVal,tr);return this.compareF(oldVal,value)?0:(state.values[idx]=value,1)},reconfigure:(state,oldState)=>oldState.config.address[this.id]!=null?(state.values[idx]=oldState.field(this),0):(state.values[idx]=this.create(state),1)}}init(create){return[this,initField.of({field:this,create})]}get extension(){return this}};__name2(_StateField,"StateField");let StateField=_StateField;const Prec_={lowest:4,low:3,default:2,high:1,highest:0};function prec(value){return ext=>new PrecExtension(ext,value)}__name(prec,"prec"),__name2(prec,"prec");const Prec={highest:prec(Prec_.highest),high:prec(Prec_.high),default:prec(Prec_.default),low:prec(Prec_.low),lowest:prec(Prec_.lowest)},_PrecExtension=class{static{__name(this,"_PrecExtension")}constructor(inner,prec2){this.inner=inner,this.prec=prec2}};__name2(_PrecExtension,"PrecExtension");let PrecExtension=_PrecExtension;const _Compartment=class _Compartment2{static{__name(this,"_Compartment")}of(ext){return new CompartmentInstance(this,ext)}reconfigure(content2){return _Compartment2.reconfigure.of({compartment:this,extension:content2})}get(state){return state.config.compartments.get(this)}};__name2(_Compartment,"Compartment");let Compartment=_Compartment;const _CompartmentInstance=class{static{__name(this,"_CompartmentInstance")}constructor(compartment,inner){this.compartment=compartment,this.inner=inner}};__name2(_CompartmentInstance,"CompartmentInstance");let CompartmentInstance=_CompartmentInstance;const _Configuration=class _Configuration2{static{__name(this,"_Configuration")}constructor(base2,compartments,dynamicSlots,address,staticValues,facets){for(this.base=base2,this.compartments=compartments,this.dynamicSlots=dynamicSlots,this.address=address,this.staticValues=staticValues,this.facets=facets,this.statusTemplate=[];this.statusTemplate.length<dynamicSlots.length;)this.statusTemplate.push(0)}staticFacet(facet){let addr=this.address[facet.id];return addr==null?facet.default:this.staticValues[addr>>1]}static resolve(base2,compartments,oldState){let fields=[],facets=Object.create(null),newCompartments=new Map;for(let ext of flatten(base2,compartments,newCompartments))ext instanceof StateField?fields.push(ext):(facets[ext.facet.id]||(facets[ext.facet.id]=[])).push(ext);let address=Object.create(null),staticValues=[],dynamicSlots=[];for(let field of fields)address[field.id]=dynamicSlots.length<<1,dynamicSlots.push(a=>field.slot(a));let oldFacets=oldState?.config.facets;for(let id in facets){let providers=facets[id],facet=providers[0].facet,oldProviders=oldFacets&&oldFacets[id]||[];if(providers.every(p=>p.type==0))if(address[facet.id]=staticValues.length<<1|1,sameArray$1(oldProviders,providers))staticValues.push(oldState.facet(facet));else{let value=facet.combine(providers.map(p=>p.value));staticValues.push(oldState&&facet.compare(value,oldState.facet(facet))?oldState.facet(facet):value)}else{for(let p of providers)p.type==0?(address[p.id]=staticValues.length<<1|1,staticValues.push(p.value)):(address[p.id]=dynamicSlots.length<<1,dynamicSlots.push(a=>p.dynamicSlot(a)));address[facet.id]=dynamicSlots.length<<1,dynamicSlots.push(a=>dynamicFacetSlot(a,facet,providers))}}let dynamic=dynamicSlots.map(f2=>f2(address));return new _Configuration2(base2,newCompartments,dynamic,address,staticValues,facets)}};__name2(_Configuration,"Configuration");let Configuration=_Configuration;function flatten(extension,compartments,newCompartments){let result=[[],[],[],[],[]],seen=new Map;function inner(ext,prec2){let known=seen.get(ext);if(known!=null){if(known<=prec2)return;let found=result[known].indexOf(ext);found>-1&&result[known].splice(found,1),ext instanceof CompartmentInstance&&newCompartments.delete(ext.compartment)}if(seen.set(ext,prec2),Array.isArray(ext))for(let e of ext)inner(e,prec2);else if(ext instanceof CompartmentInstance){if(newCompartments.has(ext.compartment))throw new RangeError("Duplicate use of compartment in extensions");let content2=compartments.get(ext.compartment)||ext.inner;newCompartments.set(ext.compartment,content2),inner(content2,prec2)}else if(ext instanceof PrecExtension)inner(ext.inner,ext.prec);else if(ext instanceof StateField)result[prec2].push(ext),ext.provides&&inner(ext.provides,prec2);else if(ext instanceof FacetProvider)result[prec2].push(ext),ext.facet.extensions&&inner(ext.facet.extensions,Prec_.default);else{let content2=ext.extension;if(!content2)throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);inner(content2,prec2)}}return __name(inner,"inner"),__name2(inner,"inner"),inner(extension,Prec_.default),result.reduce((a,b)=>a.concat(b))}__name(flatten,"flatten"),__name2(flatten,"flatten");function ensureAddr(state,addr){if(addr&1)return 2;let idx=addr>>1,status=state.status[idx];if(status==4)throw new Error("Cyclic dependency between fields and/or facets");if(status&2)return status;state.status[idx]=4;let changed=state.computeSlot(state,state.config.dynamicSlots[idx]);return state.status[idx]=2|changed}__name(ensureAddr,"ensureAddr"),__name2(ensureAddr,"ensureAddr");function getAddr(state,addr){return addr&1?state.config.staticValues[addr>>1]:state.values[addr>>1]}__name(getAddr,"getAddr"),__name2(getAddr,"getAddr");const languageData=Facet.define(),allowMultipleSelections=Facet.define({combine:values=>values.some(v=>v),static:!0}),lineSeparator=Facet.define({combine:values=>values.length?values[0]:void 0,static:!0}),changeFilter=Facet.define(),transactionFilter=Facet.define(),transactionExtender=Facet.define(),readOnly=Facet.define({combine:values=>values.length?values[0]:!1}),_Annotation=class{static{__name(this,"_Annotation")}constructor(type,value){this.type=type,this.value=value}static define(){return new AnnotationType}};__name2(_Annotation,"Annotation");let Annotation=_Annotation;const _AnnotationType=class{static{__name(this,"_AnnotationType")}of(value){return new Annotation(this,value)}};__name2(_AnnotationType,"AnnotationType");let AnnotationType=_AnnotationType;const _StateEffectType=class{static{__name(this,"_StateEffectType")}constructor(map2){this.map=map2}of(value){return new StateEffect(this,value)}};__name2(_StateEffectType,"StateEffectType");let StateEffectType=_StateEffectType;const _StateEffect=class _StateEffect2{static{__name(this,"_StateEffect")}constructor(type,value){this.type=type,this.value=value}map(mapping){let mapped=this.type.map(this.value,mapping);return mapped===void 0?void 0:mapped==this.value?this:new _StateEffect2(this.type,mapped)}is(type){return this.type==type}static define(spec={}){return new StateEffectType(spec.map||(v=>v))}static mapEffects(effects,mapping){if(!effects.length)return effects;let result=[];for(let effect of effects){let mapped=effect.map(mapping);mapped&&result.push(mapped)}return result}};__name2(_StateEffect,"StateEffect");let StateEffect=_StateEffect;StateEffect.reconfigure=StateEffect.define(),StateEffect.appendConfig=StateEffect.define();const _Transaction=class _Transaction2{static{__name(this,"_Transaction")}constructor(startState,changes,selection,effects,annotations,scrollIntoView2){this.startState=startState,this.changes=changes,this.selection=selection,this.effects=effects,this.annotations=annotations,this.scrollIntoView=scrollIntoView2,this._doc=null,this._state=null,selection&&checkSelection(selection,changes.newLength),annotations.some(a=>a.type==_Transaction2.time)||(this.annotations=annotations.concat(_Transaction2.time.of(Date.now())))}static create(startState,changes,selection,effects,annotations,scrollIntoView2){return new _Transaction2(startState,changes,selection,effects,annotations,scrollIntoView2)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(type){for(let ann of this.annotations)if(ann.type==type)return ann.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(event){let e=this.annotation(_Transaction2.userEvent);return!!(e&&(e==event||e.length>event.length&&e.slice(0,event.length)==event&&e[event.length]=="."))}};__name2(_Transaction,"Transaction");let Transaction=_Transaction;Transaction.time=Annotation.define(),Transaction.userEvent=Annotation.define(),Transaction.addToHistory=Annotation.define(),Transaction.remote=Annotation.define();function joinRanges(a,b){let result=[];for(let iA=0,iB=0;;){let from,to;if(iA<a.length&&(iB==b.length||b[iB]>=a[iA]))from=a[iA++],to=a[iA++];else if(iB<b.length)from=b[iB++],to=b[iB++];else return result;!result.length||result[result.length-1]<from?result.push(from,to):result[result.length-1]<to&&(result[result.length-1]=to)}}__name(joinRanges,"joinRanges"),__name2(joinRanges,"joinRanges");function mergeTransaction(a,b,sequential){var _a3;let mapForA,mapForB,changes;return sequential?(mapForA=b.changes,mapForB=ChangeSet.empty(b.changes.length),changes=a.changes.compose(b.changes)):(mapForA=b.changes.map(a.changes),mapForB=a.changes.mapDesc(b.changes,!0),changes=a.changes.compose(mapForA)),{changes,selection:b.selection?b.selection.map(mapForB):(_a3=a.selection)===null||_a3===void 0?void 0:_a3.map(mapForA),effects:StateEffect.mapEffects(a.effects,mapForA).concat(StateEffect.mapEffects(b.effects,mapForB)),annotations:a.annotations.length?a.annotations.concat(b.annotations):b.annotations,scrollIntoView:a.scrollIntoView||b.scrollIntoView}}__name(mergeTransaction,"mergeTransaction"),__name2(mergeTransaction,"mergeTransaction");function resolveTransactionInner(state,spec,docSize){let sel=spec.selection,annotations=asArray$2(spec.annotations);return spec.userEvent&&(annotations=annotations.concat(Transaction.userEvent.of(spec.userEvent))),{changes:spec.changes instanceof ChangeSet?spec.changes:ChangeSet.of(spec.changes||[],docSize,state.facet(lineSeparator)),selection:sel&&(sel instanceof EditorSelection?sel:EditorSelection.single(sel.anchor,sel.head)),effects:asArray$2(spec.effects),annotations,scrollIntoView:!!spec.scrollIntoView}}__name(resolveTransactionInner,"resolveTransactionInner"),__name2(resolveTransactionInner,"resolveTransactionInner");function resolveTransaction(state,specs,filter2){let s2=resolveTransactionInner(state,specs.length?specs[0]:{},state.doc.length);specs.length&&specs[0].filter===!1&&(filter2=!1);for(let i=1;i<specs.length;i++){specs[i].filter===!1&&(filter2=!1);let seq=!!specs[i].sequential;s2=mergeTransaction(s2,resolveTransactionInner(state,specs[i],seq?s2.changes.newLength:state.doc.length),seq)}let tr=Transaction.create(state,s2.changes,s2.selection,s2.effects,s2.annotations,s2.scrollIntoView);return extendTransaction(filter2?filterTransaction(tr):tr)}__name(resolveTransaction,"resolveTransaction"),__name2(resolveTransaction,"resolveTransaction");function filterTransaction(tr){let state=tr.startState,result=!0;for(let filter2 of state.facet(changeFilter)){let value=filter2(tr);if(value===!1){result=!1;break}Array.isArray(value)&&(result=result===!0?value:joinRanges(result,value))}if(result!==!0){let changes,back;if(result===!1)back=tr.changes.invertedDesc,changes=ChangeSet.empty(state.doc.length);else{let filtered=tr.changes.filter(result);changes=filtered.changes,back=filtered.filtered.mapDesc(filtered.changes).invertedDesc}tr=Transaction.create(state,changes,tr.selection&&tr.selection.map(back),StateEffect.mapEffects(tr.effects,back),tr.annotations,tr.scrollIntoView)}let filters=state.facet(transactionFilter);for(let i=filters.length-1;i>=0;i--){let filtered=filters[i](tr);filtered instanceof Transaction?tr=filtered:Array.isArray(filtered)&&filtered.length==1&&filtered[0]instanceof Transaction?tr=filtered[0]:tr=resolveTransaction(state,asArray$2(filtered),!1)}return tr}__name(filterTransaction,"filterTransaction"),__name2(filterTransaction,"filterTransaction");function extendTransaction(tr){let state=tr.startState,extenders=state.facet(transactionExtender),spec=tr;for(let i=extenders.length-1;i>=0;i--){let extension=extenders[i](tr);extension&&Object.keys(extension).length&&(spec=mergeTransaction(spec,resolveTransactionInner(state,extension,tr.changes.newLength),!0))}return spec==tr?tr:Transaction.create(state,tr.changes,tr.selection,spec.effects,spec.annotations,spec.scrollIntoView)}__name(extendTransaction,"extendTransaction"),__name2(extendTransaction,"extendTransaction");const none$2=[];function asArray$2(value){return value==null?none$2:Array.isArray(value)?value:[value]}__name(asArray$2,"asArray$2"),__name2(asArray$2,"asArray$2");var CharCategory=function(CharCategory2){return CharCategory2[CharCategory2.Word=0]="Word",CharCategory2[CharCategory2.Space=1]="Space",CharCategory2[CharCategory2.Other=2]="Other",CharCategory2}(CharCategory||(CharCategory={}));const nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let wordChar;try{wordChar=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function hasWordChar(str){if(wordChar)return wordChar.test(str);for(let i=0;i<str.length;i++){let ch=str[i];if(/\w/.test(ch)||ch>"\x80"&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch)))return!0}return!1}__name(hasWordChar,"hasWordChar"),__name2(hasWordChar,"hasWordChar");function makeCategorizer(wordChars){return char=>{if(!/\S/.test(char))return CharCategory.Space;if(hasWordChar(char))return CharCategory.Word;for(let i=0;i<wordChars.length;i++)if(char.indexOf(wordChars[i])>-1)return CharCategory.Word;return CharCategory.Other}}__name(makeCategorizer,"makeCategorizer"),__name2(makeCategorizer,"makeCategorizer");const _EditorState=class _EditorState2{static{__name(this,"_EditorState")}constructor(config2,doc2,selection,values,computeSlot,tr){this.config=config2,this.doc=doc2,this.selection=selection,this.values=values,this.status=config2.statusTemplate.slice(),this.computeSlot=computeSlot,tr&&(tr._state=this);for(let i=0;i<this.config.dynamicSlots.length;i++)ensureAddr(this,i<<1);this.computeSlot=null}field(field,require2=!0){let addr=this.config.address[field.id];if(addr==null){if(require2)throw new RangeError("Field is not present in this state");return}return ensureAddr(this,addr),getAddr(this,addr)}update(...specs){return resolveTransaction(this,specs,!0)}applyTransaction(tr){let conf=this.config,{base:base2,compartments}=conf;for(let effect of tr.effects)effect.is(Compartment.reconfigure)?(conf&&(compartments=new Map,conf.compartments.forEach((val,key)=>compartments.set(key,val)),conf=null),compartments.set(effect.value.compartment,effect.value.extension)):effect.is(StateEffect.reconfigure)?(conf=null,base2=effect.value):effect.is(StateEffect.appendConfig)&&(conf=null,base2=asArray$2(base2).concat(effect.value));let startValues;conf?startValues=tr.startState.values.slice():(conf=Configuration.resolve(base2,compartments,this),startValues=new _EditorState2(conf,this.doc,this.selection,conf.dynamicSlots.map(()=>null),(state,slot)=>slot.reconfigure(state,this),null).values),new _EditorState2(conf,tr.newDoc,tr.newSelection,startValues,(state,slot)=>slot.update(state,tr),tr)}replaceSelection(text){return typeof text=="string"&&(text=this.toText(text)),this.changeByRange(range=>({changes:{from:range.from,to:range.to,insert:text},range:EditorSelection.cursor(range.from+text.length)}))}changeByRange(f2){let sel=this.selection,result1=f2(sel.ranges[0]),changes=this.changes(result1.changes),ranges=[result1.range],effects=asArray$2(result1.effects);for(let i=1;i<sel.ranges.length;i++){let result=f2(sel.ranges[i]),newChanges=this.changes(result.changes),newMapped=newChanges.map(changes);for(let j=0;j<i;j++)ranges[j]=ranges[j].map(newMapped);let mapBy=changes.mapDesc(newChanges,!0);ranges.push(result.range.map(mapBy)),changes=changes.compose(newMapped),effects=StateEffect.mapEffects(effects,newMapped).concat(StateEffect.mapEffects(asArray$2(result.effects),mapBy))}return{changes,selection:EditorSelection.create(ranges,sel.mainIndex),effects}}changes(spec=[]){return spec instanceof ChangeSet?spec:ChangeSet.of(spec,this.doc.length,this.facet(_EditorState2.lineSeparator))}toText(string2){return Text.of(string2.split(this.facet(_EditorState2.lineSeparator)||DefaultSplit))}sliceDoc(from=0,to=this.doc.length){return this.doc.sliceString(from,to,this.lineBreak)}facet(facet){let addr=this.config.address[facet.id];return addr==null?facet.default:(ensureAddr(this,addr),getAddr(this,addr))}toJSON(fields){let result={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(fields)for(let prop in fields){let value=fields[prop];value instanceof StateField&&this.config.address[value.id]!=null&&(result[prop]=value.spec.toJSON(this.field(fields[prop]),this))}return result}static fromJSON(json2,config2={},fields){if(!json2||typeof json2.doc!="string")throw new RangeError("Invalid JSON representation for EditorState");let fieldInit=[];if(fields){for(let prop in fields)if(Object.prototype.hasOwnProperty.call(json2,prop)){let field=fields[prop],value=json2[prop];fieldInit.push(field.init(state=>field.spec.fromJSON(value,state)))}}return _EditorState2.create({doc:json2.doc,selection:EditorSelection.fromJSON(json2.selection),extensions:config2.extensions?fieldInit.concat([config2.extensions]):fieldInit})}static create(config2={}){let configuration=Configuration.resolve(config2.extensions||[],new Map),doc2=config2.doc instanceof Text?config2.doc:Text.of((config2.doc||"").split(configuration.staticFacet(_EditorState2.lineSeparator)||DefaultSplit)),selection=config2.selection?config2.selection instanceof EditorSelection?config2.selection:EditorSelection.single(config2.selection.anchor,config2.selection.head):EditorSelection.single(0);return checkSelection(selection,doc2.length),configuration.staticFacet(allowMultipleSelections)||(selection=selection.asSingle()),new _EditorState2(configuration,doc2,selection,configuration.dynamicSlots.map(()=>null),(state,slot)=>slot.create(state),null)}get tabSize(){return this.facet(_EditorState2.tabSize)}get lineBreak(){return this.facet(_EditorState2.lineSeparator)||`
`}get readOnly(){return this.facet(readOnly)}phrase(phrase2,...insert2){for(let map2 of this.facet(_EditorState2.phrases))if(Object.prototype.hasOwnProperty.call(map2,phrase2)){phrase2=map2[phrase2];break}return insert2.length&&(phrase2=phrase2.replace(/\$(\$|\d*)/g,(m,i)=>{if(i=="$")return"$";let n2=+(i||1);return!n2||n2>insert2.length?m:insert2[n2-1]})),phrase2}languageDataAt(name2,pos,side=-1){let values=[];for(let provider of this.facet(languageData))for(let result of provider(this,pos,side))Object.prototype.hasOwnProperty.call(result,name2)&&values.push(result[name2]);return values}charCategorizer(at){return makeCategorizer(this.languageDataAt("wordChars",at).join(""))}wordAt(pos){let{text,from,length}=this.doc.lineAt(pos),cat=this.charCategorizer(pos),start=pos-from,end=pos-from;for(;start>0;){let prev=findClusterBreak(text,start,!1);if(cat(text.slice(prev,start))!=CharCategory.Word)break;start=prev}for(;end<length;){let next=findClusterBreak(text,end);if(cat(text.slice(end,next))!=CharCategory.Word)break;end=next}return start==end?null:EditorSelection.range(start+from,end+from)}};__name2(_EditorState,"EditorState");let EditorState=_EditorState;EditorState.allowMultipleSelections=allowMultipleSelections,EditorState.tabSize=Facet.define({combine:values=>values.length?values[0]:4}),EditorState.lineSeparator=lineSeparator,EditorState.readOnly=readOnly,EditorState.phrases=Facet.define({compare(a,b){let kA=Object.keys(a),kB=Object.keys(b);return kA.length==kB.length&&kA.every(k=>a[k]==b[k])}}),EditorState.languageData=languageData,EditorState.changeFilter=changeFilter,EditorState.transactionFilter=transactionFilter,EditorState.transactionExtender=transactionExtender,Compartment.reconfigure=StateEffect.define();function combineConfig(configs,defaults2,combine={}){let result={};for(let config2 of configs)for(let key of Object.keys(config2)){let value=config2[key],current=result[key];if(current===void 0)result[key]=value;else if(!(current===value||value===void 0))if(Object.hasOwnProperty.call(combine,key))result[key]=combine[key](current,value);else throw new Error("Config merge conflict for field "+key)}for(let key in defaults2)result[key]===void 0&&(result[key]=defaults2[key]);return result}__name(combineConfig,"combineConfig"),__name2(combineConfig,"combineConfig");const _RangeValue=class{static{__name(this,"_RangeValue")}eq(other){return this==other}range(from,to=from){return Range$1.create(from,to,this)}};__name2(_RangeValue,"RangeValue");let RangeValue=_RangeValue;RangeValue.prototype.startSide=RangeValue.prototype.endSide=0,RangeValue.prototype.point=!1,RangeValue.prototype.mapMode=MapMode.TrackDel;let Range$1=(_a=class{static{__name(this,"_a")}constructor(from,to,value){this.from=from,this.to=to,this.value=value}static create(from,to,value){return new _a(from,to,value)}},__name2(_a,"Range"),_a);function cmpRange(a,b){return a.from-b.from||a.value.startSide-b.value.startSide}__name(cmpRange,"cmpRange"),__name2(cmpRange,"cmpRange");const _Chunk=class _Chunk2{static{__name(this,"_Chunk")}constructor(from,to,value,maxPoint){this.from=from,this.to=to,this.value=value,this.maxPoint=maxPoint}get length(){return this.to[this.to.length-1]}findIndex(pos,side,end,startAt=0){let arr=end?this.to:this.from;for(let lo=startAt,hi=arr.length;;){if(lo==hi)return lo;let mid=lo+hi>>1,diff2=arr[mid]-pos||(end?this.value[mid].endSide:this.value[mid].startSide)-side;if(mid==lo)return diff2>=0?lo:hi;diff2>=0?hi=mid:lo=mid+1}}between(offset2,from,to,f2){for(let i=this.findIndex(from,-1e9,!0),e=this.findIndex(to,1e9,!1,i);i<e;i++)if(f2(this.from[i]+offset2,this.to[i]+offset2,this.value[i])===!1)return!1}map(offset2,changes){let value=[],from=[],to=[],newPos=-1,maxPoint=-1;for(let i=0;i<this.value.length;i++){let val=this.value[i],curFrom=this.from[i]+offset2,curTo=this.to[i]+offset2,newFrom,newTo;if(curFrom==curTo){let mapped=changes.mapPos(curFrom,val.startSide,val.mapMode);if(mapped==null||(newFrom=newTo=mapped,val.startSide!=val.endSide&&(newTo=changes.mapPos(curFrom,val.endSide),newTo<newFrom)))continue}else if(newFrom=changes.mapPos(curFrom,val.startSide),newTo=changes.mapPos(curTo,val.endSide),newFrom>newTo||newFrom==newTo&&val.startSide>0&&val.endSide<=0)continue;(newTo-newFrom||val.endSide-val.startSide)<0||(newPos<0&&(newPos=newFrom),val.point&&(maxPoint=Math.max(maxPoint,newTo-newFrom)),value.push(val),from.push(newFrom-newPos),to.push(newTo-newPos))}return{mapped:value.length?new _Chunk2(from,to,value,maxPoint):null,pos:newPos}}};__name2(_Chunk,"Chunk");let Chunk=_Chunk;const _RangeSet=class _RangeSet2{static{__name(this,"_RangeSet")}constructor(chunkPos,chunk,nextLayer,maxPoint){this.chunkPos=chunkPos,this.chunk=chunk,this.nextLayer=nextLayer,this.maxPoint=maxPoint}static create(chunkPos,chunk,nextLayer,maxPoint){return new _RangeSet2(chunkPos,chunk,nextLayer,maxPoint)}get length(){let last2=this.chunk.length-1;return last2<0?0:Math.max(this.chunkEnd(last2),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let size=this.nextLayer.size;for(let chunk of this.chunk)size+=chunk.value.length;return size}chunkEnd(index2){return this.chunkPos[index2]+this.chunk[index2].length}update(updateSpec){let{add:add2=[],sort:sort2=!1,filterFrom=0,filterTo=this.length}=updateSpec,filter2=updateSpec.filter;if(add2.length==0&&!filter2)return this;if(sort2&&(add2=add2.slice().sort(cmpRange)),this.isEmpty)return add2.length?_RangeSet2.of(add2):this;let cur2=new LayerCursor(this,null,-1).goto(0),i=0,spill=[],builder=new RangeSetBuilder;for(;cur2.value||i<add2.length;)if(i<add2.length&&(cur2.from-add2[i].from||cur2.startSide-add2[i].value.startSide)>=0){let range=add2[i++];builder.addInner(range.from,range.to,range.value)||spill.push(range)}else cur2.rangeIndex==1&&cur2.chunkIndex<this.chunk.length&&(i==add2.length||this.chunkEnd(cur2.chunkIndex)<add2[i].from)&&(!filter2||filterFrom>this.chunkEnd(cur2.chunkIndex)||filterTo<this.chunkPos[cur2.chunkIndex])&&builder.addChunk(this.chunkPos[cur2.chunkIndex],this.chunk[cur2.chunkIndex])?cur2.nextChunk():((!filter2||filterFrom>cur2.to||filterTo<cur2.from||filter2(cur2.from,cur2.to,cur2.value))&&(builder.addInner(cur2.from,cur2.to,cur2.value)||spill.push(Range$1.create(cur2.from,cur2.to,cur2.value))),cur2.next());return builder.finishInner(this.nextLayer.isEmpty&&!spill.length?_RangeSet2.empty:this.nextLayer.update({add:spill,filter:filter2,filterFrom,filterTo}))}map(changes){if(changes.empty||this.isEmpty)return this;let chunks=[],chunkPos=[],maxPoint=-1;for(let i=0;i<this.chunk.length;i++){let start=this.chunkPos[i],chunk=this.chunk[i],touch=changes.touchesRange(start,start+chunk.length);if(touch===!1)maxPoint=Math.max(maxPoint,chunk.maxPoint),chunks.push(chunk),chunkPos.push(changes.mapPos(start));else if(touch===!0){let{mapped,pos}=chunk.map(start,changes);mapped&&(maxPoint=Math.max(maxPoint,mapped.maxPoint),chunks.push(mapped),chunkPos.push(pos))}}let next=this.nextLayer.map(changes);return chunks.length==0?next:new _RangeSet2(chunkPos,chunks,next||_RangeSet2.empty,maxPoint)}between(from,to,f2){if(!this.isEmpty){for(let i=0;i<this.chunk.length;i++){let start=this.chunkPos[i],chunk=this.chunk[i];if(to>=start&&from<=start+chunk.length&&chunk.between(start,from-start,to-start,f2)===!1)return}this.nextLayer.between(from,to,f2)}}iter(from=0){return HeapCursor.from([this]).goto(from)}get isEmpty(){return this.nextLayer==this}static iter(sets,from=0){return HeapCursor.from(sets).goto(from)}static compare(oldSets,newSets,textDiff,comparator,minPointSize=-1){let a=oldSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize),b=newSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize),sharedChunks=findSharedChunks(a,b,textDiff),sideA=new SpanCursor(a,sharedChunks,minPointSize),sideB=new SpanCursor(b,sharedChunks,minPointSize);textDiff.iterGaps((fromA,fromB,length)=>compare(sideA,fromA,sideB,fromB,length,comparator)),textDiff.empty&&textDiff.length==0&&compare(sideA,0,sideB,0,0,comparator)}static eq(oldSets,newSets,from=0,to){to==null&&(to=1e9-1);let a=oldSets.filter(set=>!set.isEmpty&&newSets.indexOf(set)<0),b=newSets.filter(set=>!set.isEmpty&&oldSets.indexOf(set)<0);if(a.length!=b.length)return!1;if(!a.length)return!0;let sharedChunks=findSharedChunks(a,b),sideA=new SpanCursor(a,sharedChunks,0).goto(from),sideB=new SpanCursor(b,sharedChunks,0).goto(from);for(;;){if(sideA.to!=sideB.to||!sameValues(sideA.active,sideB.active)||sideA.point&&(!sideB.point||!sideA.point.eq(sideB.point)))return!1;if(sideA.to>to)return!0;sideA.next(),sideB.next()}}static spans(sets,from,to,iterator,minPointSize=-1){let cursor=new SpanCursor(sets,null,minPointSize).goto(from),pos=from,openRanges=cursor.openStart;for(;;){let curTo=Math.min(cursor.to,to);if(cursor.point){let active=cursor.activeForPoint(cursor.to),openCount=cursor.pointFrom<from?active.length+1:Math.min(active.length,openRanges);iterator.point(pos,curTo,cursor.point,active,openCount,cursor.pointRank),openRanges=Math.min(cursor.openEnd(curTo),active.length)}else curTo>pos&&(iterator.span(pos,curTo,cursor.active,openRanges),openRanges=cursor.openEnd(curTo));if(cursor.to>to)return openRanges+(cursor.point&&cursor.to>to?1:0);pos=cursor.to,cursor.next()}}static of(ranges,sort2=!1){let build=new RangeSetBuilder;for(let range of ranges instanceof Range$1?[ranges]:sort2?lazySort(ranges):ranges)build.add(range.from,range.to,range.value);return build.finish()}};__name2(_RangeSet,"RangeSet");let RangeSet=_RangeSet;RangeSet.empty=new RangeSet([],[],null,-1);function lazySort(ranges){if(ranges.length>1)for(let prev=ranges[0],i=1;i<ranges.length;i++){let cur2=ranges[i];if(cmpRange(prev,cur2)>0)return ranges.slice().sort(cmpRange);prev=cur2}return ranges}__name(lazySort,"lazySort"),__name2(lazySort,"lazySort"),RangeSet.empty.nextLayer=RangeSet.empty;const _RangeSetBuilder=class _RangeSetBuilder2{static{__name(this,"_RangeSetBuilder")}finishChunk(newArrays){this.chunks.push(new Chunk(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,newArrays&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(from,to,value){this.addInner(from,to,value)||(this.nextLayer||(this.nextLayer=new _RangeSetBuilder2)).add(from,to,value)}addInner(from,to,value){let diff2=from-this.lastTo||value.startSide-this.last.endSide;if(diff2<=0&&(from-this.lastFrom||value.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return diff2<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=from),this.from.push(from-this.chunkStart),this.to.push(to-this.chunkStart),this.last=value,this.lastFrom=from,this.lastTo=to,this.value.push(value),value.point&&(this.maxPoint=Math.max(this.maxPoint,to-from)),!0)}addChunk(from,chunk){if((from-this.lastTo||chunk.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,chunk.maxPoint),this.chunks.push(chunk),this.chunkPos.push(from);let last2=chunk.value.length-1;return this.last=chunk.value[last2],this.lastFrom=chunk.from[last2]+from,this.lastTo=chunk.to[last2]+from,!0}finish(){return this.finishInner(RangeSet.empty)}finishInner(next){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return next;let result=RangeSet.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(next):next,this.setMaxPoint);return this.from=null,result}};__name2(_RangeSetBuilder,"RangeSetBuilder");let RangeSetBuilder=_RangeSetBuilder;function findSharedChunks(a,b,textDiff){let inA=new Map;for(let set of a)for(let i=0;i<set.chunk.length;i++)set.chunk[i].maxPoint<=0&&inA.set(set.chunk[i],set.chunkPos[i]);let shared=new Set;for(let set of b)for(let i=0;i<set.chunk.length;i++){let known=inA.get(set.chunk[i]);known!=null&&(textDiff?textDiff.mapPos(known):known)==set.chunkPos[i]&&!textDiff?.touchesRange(known,known+set.chunk[i].length)&&shared.add(set.chunk[i])}return shared}__name(findSharedChunks,"findSharedChunks"),__name2(findSharedChunks,"findSharedChunks");const _LayerCursor=class{static{__name(this,"_LayerCursor")}constructor(layer2,skip,minPoint,rank=0){this.layer=layer2,this.skip=skip,this.minPoint=minPoint,this.rank=rank}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(pos,side=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(pos,side,!1),this}gotoInner(pos,side,forward){for(;this.chunkIndex<this.layer.chunk.length;){let next=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(next)||this.layer.chunkEnd(this.chunkIndex)<pos||next.maxPoint<this.minPoint))break;this.chunkIndex++,forward=!1}if(this.chunkIndex<this.layer.chunk.length){let rangeIndex=this.layer.chunk[this.chunkIndex].findIndex(pos-this.layer.chunkPos[this.chunkIndex],side,!0);(!forward||this.rangeIndex<rangeIndex)&&this.setRangeIndex(rangeIndex)}this.next()}forward(pos,side){(this.to-pos||this.endSide-side)<0&&this.gotoInner(pos,side,!0)}next(){for(;;)if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}else{let chunkPos=this.layer.chunkPos[this.chunkIndex],chunk=this.layer.chunk[this.chunkIndex],from=chunkPos+chunk.from[this.rangeIndex];if(this.from=from,this.to=chunkPos+chunk.to[this.rangeIndex],this.value=chunk.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}setRangeIndex(index2){if(index2==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=index2}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(other){return this.from-other.from||this.startSide-other.startSide||this.rank-other.rank||this.to-other.to||this.endSide-other.endSide}};__name2(_LayerCursor,"LayerCursor");let LayerCursor=_LayerCursor;const _HeapCursor=class _HeapCursor2{static{__name(this,"_HeapCursor")}constructor(heap){this.heap=heap}static from(sets,skip=null,minPoint=-1){let heap=[];for(let i=0;i<sets.length;i++)for(let cur2=sets[i];!cur2.isEmpty;cur2=cur2.nextLayer)cur2.maxPoint>=minPoint&&heap.push(new LayerCursor(cur2,skip,minPoint,i));return heap.length==1?heap[0]:new _HeapCursor2(heap)}get startSide(){return this.value?this.value.startSide:0}goto(pos,side=-1e9){for(let cur2 of this.heap)cur2.goto(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);return this.next(),this}forward(pos,side){for(let cur2 of this.heap)cur2.forward(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);(this.to-pos||this.value.endSide-side)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let top2=this.heap[0];this.from=top2.from,this.to=top2.to,this.value=top2.value,this.rank=top2.rank,top2.value&&top2.next(),heapBubble(this.heap,0)}}};__name2(_HeapCursor,"HeapCursor");let HeapCursor=_HeapCursor;function heapBubble(heap,index2){for(let cur2=heap[index2];;){let childIndex=(index2<<1)+1;if(childIndex>=heap.length)break;let child=heap[childIndex];if(childIndex+1<heap.length&&child.compare(heap[childIndex+1])>=0&&(child=heap[childIndex+1],childIndex++),cur2.compare(child)<0)break;heap[childIndex]=cur2,heap[index2]=child,index2=childIndex}}__name(heapBubble,"heapBubble"),__name2(heapBubble,"heapBubble");const _SpanCursor=class{static{__name(this,"_SpanCursor")}constructor(sets,skip,minPoint){this.minPoint=minPoint,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=HeapCursor.from(sets,skip,minPoint)}goto(pos,side=-1e9){return this.cursor.goto(pos,side),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=pos,this.endSide=side,this.openStart=-1,this.next(),this}forward(pos,side){for(;this.minActive>-1&&(this.activeTo[this.minActive]-pos||this.active[this.minActive].endSide-side)<0;)this.removeActive(this.minActive);this.cursor.forward(pos,side)}removeActive(index2){remove(this.active,index2),remove(this.activeTo,index2),remove(this.activeRank,index2),this.minActive=findMinIndex(this.active,this.activeTo)}addActive(trackOpen){let i=0,{value,to,rank}=this.cursor;for(;i<this.activeRank.length&&this.activeRank[i]<=rank;)i++;insert(this.active,i,value),insert(this.activeTo,i,to),insert(this.activeRank,i,rank),trackOpen&&insert(trackOpen,i,this.cursor.from),this.minActive=findMinIndex(this.active,this.activeTo)}next(){let from=this.to,wasPoint=this.point;this.point=null;let trackOpen=this.openStart<0?[]:null;for(;;){let a=this.minActive;if(a>-1&&(this.activeTo[a]-this.cursor.from||this.active[a].endSide-this.cursor.startSide)<0){if(this.activeTo[a]>from){this.to=this.activeTo[a],this.endSide=this.active[a].endSide;break}this.removeActive(a),trackOpen&&remove(trackOpen,a)}else if(this.cursor.value)if(this.cursor.from>from){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let nextVal=this.cursor.value;if(!nextVal.point)this.addActive(trackOpen),this.cursor.next();else if(wasPoint&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)this.cursor.next();else{this.point=nextVal,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=nextVal.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}}else{this.to=this.endSide=1e9;break}}if(trackOpen){this.openStart=0;for(let i=trackOpen.length-1;i>=0&&trackOpen[i]<from;i--)this.openStart++}}activeForPoint(to){if(!this.active.length)return this.active;let active=[];for(let i=this.active.length-1;i>=0&&!(this.activeRank[i]<this.pointRank);i--)(this.activeTo[i]>to||this.activeTo[i]==to&&this.active[i].endSide>=this.point.endSide)&&active.push(this.active[i]);return active.reverse()}openEnd(to){let open=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>to;i--)open++;return open}};__name2(_SpanCursor,"SpanCursor");let SpanCursor=_SpanCursor;function compare(a,startA,b,startB,length,comparator){a.goto(startA),b.goto(startB);let endB=startB+length,pos=startB,dPos=startB-startA;for(;;){let diff2=a.to+dPos-b.to||a.endSide-b.endSide,end=diff2<0?a.to+dPos:b.to,clipEnd=Math.min(end,endB);if(a.point||b.point?a.point&&b.point&&(a.point==b.point||a.point.eq(b.point))&&sameValues(a.activeForPoint(a.to),b.activeForPoint(b.to))||comparator.comparePoint(pos,clipEnd,a.point,b.point):clipEnd>pos&&!sameValues(a.active,b.active)&&comparator.compareRange(pos,clipEnd,a.active,b.active),end>endB)break;pos=end,diff2<=0&&a.next(),diff2>=0&&b.next()}}__name(compare,"compare"),__name2(compare,"compare");function sameValues(a,b){if(a.length!=b.length)return!1;for(let i=0;i<a.length;i++)if(a[i]!=b[i]&&!a[i].eq(b[i]))return!1;return!0}__name(sameValues,"sameValues"),__name2(sameValues,"sameValues");function remove(array,index2){for(let i=index2,e=array.length-1;i<e;i++)array[i]=array[i+1];array.pop()}__name(remove,"remove"),__name2(remove,"remove");function insert(array,index2,value){for(let i=array.length-1;i>=index2;i--)array[i+1]=array[i];array[index2]=value}__name(insert,"insert"),__name2(insert,"insert");function findMinIndex(value,array){let found=-1,foundPos=1e9;for(let i=0;i<array.length;i++)(array[i]-foundPos||value[i].endSide-value[found].endSide)<0&&(found=i,foundPos=array[i]);return found}__name(findMinIndex,"findMinIndex"),__name2(findMinIndex,"findMinIndex");function countColumn(string2,tabSize,to=string2.length){let n2=0;for(let i=0;i<to;)string2.charCodeAt(i)==9?(n2+=tabSize-n2%tabSize,i++):(n2++,i=findClusterBreak(string2,i));return n2}__name(countColumn,"countColumn"),__name2(countColumn,"countColumn");function findColumn(string2,col,tabSize,strict){for(let i=0,n2=0;;){if(n2>=col)return i;if(i==string2.length)break;n2+=string2.charCodeAt(i)==9?tabSize-n2%tabSize:1,i=findClusterBreak(string2,i)}return strict===!0?-1:string2.length}__name(findColumn,"findColumn"),__name2(findColumn,"findColumn");const C="\u037C",COUNT=typeof Symbol>"u"?"__"+C:Symbol.for(C),SET=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),top=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},_StyleModule=class{static{__name(this,"_StyleModule")}constructor(spec,options){this.rules=[];let{finish}=options||{};function splitSelector(selector){return/^@/.test(selector)?[selector]:selector.split(/,\s*/)}__name(splitSelector,"splitSelector"),__name2(splitSelector,"splitSelector");function render(selectors,spec2,target,isKeyframes){let local=[],isAt=/^@(\w+)\b/.exec(selectors[0]),keyframes=isAt&&isAt[1]=="keyframes";if(isAt&&spec2==null)return target.push(selectors[0]+";");for(let prop in spec2){let value=spec2[prop];if(/&/.test(prop))render(prop.split(/,\s*/).map(part=>selectors.map(sel=>part.replace(/&/,sel))).reduce((a,b)=>a.concat(b)),value,target);else if(value&&typeof value=="object"){if(!isAt)throw new RangeError("The value of a property ("+prop+") should be a primitive value.");render(splitSelector(prop),value,local,keyframes)}else value!=null&&local.push(prop.replace(/_.*/,"").replace(/[A-Z]/g,l2=>"-"+l2.toLowerCase())+": "+value+";")}(local.length||keyframes)&&target.push((finish&&!isAt&&!isKeyframes?selectors.map(finish):selectors).join(", ")+" {"+local.join(" ")+"}")}__name(render,"render"),__name2(render,"render");for(let prop in spec)render(splitSelector(prop),spec[prop],this.rules)}getRules(){return this.rules.join(`
`)}static newName(){let id=top[COUNT]||1;return top[COUNT]=id+1,C+id.toString(36)}static mount(root,modules,options){let set=root[SET],nonce=options&&options.nonce;set?nonce&&set.setNonce(nonce):set=new StyleSet(root,nonce),set.mount(Array.isArray(modules)?modules:[modules])}};__name2(_StyleModule,"StyleModule");let StyleModule=_StyleModule,adoptedSet=new Map;const _StyleSet=class{static{__name(this,"_StyleSet")}constructor(root,nonce){let doc2=root.ownerDocument||root,win=doc2.defaultView;if(!root.head&&root.adoptedStyleSheets&&win.CSSStyleSheet){let adopted=adoptedSet.get(doc2);if(adopted)return root.adoptedStyleSheets=[adopted.sheet,...root.adoptedStyleSheets],root[SET]=adopted;this.sheet=new win.CSSStyleSheet,root.adoptedStyleSheets=[this.sheet,...root.adoptedStyleSheets],adoptedSet.set(doc2,this)}else{this.styleTag=doc2.createElement("style"),nonce&&this.styleTag.setAttribute("nonce",nonce);let target=root.head||root;target.insertBefore(this.styleTag,target.firstChild)}this.modules=[],root[SET]=this}mount(modules){let sheet=this.sheet,pos=0,j=0;for(let i=0;i<modules.length;i++){let mod=modules[i],index2=this.modules.indexOf(mod);if(index2<j&&index2>-1&&(this.modules.splice(index2,1),j--,index2=-1),index2==-1){if(this.modules.splice(j++,0,mod),sheet)for(let k=0;k<mod.rules.length;k++)sheet.insertRule(mod.rules[k],pos++)}else{for(;j<index2;)pos+=this.modules[j++].rules.length;pos+=mod.rules.length,j++}}if(!sheet){let text="";for(let i=0;i<this.modules.length;i++)text+=this.modules[i].getRules()+`
`;this.styleTag.textContent=text}}setNonce(nonce){this.styleTag&&this.styleTag.getAttribute("nonce")!=nonce&&this.styleTag.setAttribute("nonce",nonce)}};__name2(_StyleSet,"StyleSet");let StyleSet=_StyleSet;for(var base={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},shift={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},mac=typeof navigator<"u"&&/Mac/.test(navigator.platform),ie$1=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),i=0;i<10;i++)base[48+i]=base[96+i]=String(i);for(var i=1;i<=24;i++)base[i+111]="F"+i;for(var i=65;i<=90;i++)base[i]=String.fromCharCode(i+32),shift[i]=String.fromCharCode(i);for(var code in base)shift.hasOwnProperty(code)||(shift[code]=base[code]);function keyName(event){var ignoreKey=mac&&event.metaKey&&event.shiftKey&&!event.ctrlKey&&!event.altKey||ie$1&&event.shiftKey&&event.key&&event.key.length==1||event.key=="Unidentified",name2=!ignoreKey&&event.key||(event.shiftKey?shift:base)[event.keyCode]||event.key||"Unidentified";return name2=="Esc"&&(name2="Escape"),name2=="Del"&&(name2="Delete"),name2=="Left"&&(name2="ArrowLeft"),name2=="Up"&&(name2="ArrowUp"),name2=="Right"&&(name2="ArrowRight"),name2=="Down"&&(name2="ArrowDown"),name2}__name(keyName,"keyName"),__name2(keyName,"keyName");function getSelection(root){let target;return root.nodeType==11?target=root.getSelection?root:root.ownerDocument:target=root,target.getSelection()}__name(getSelection,"getSelection"),__name2(getSelection,"getSelection");function contains(dom,node){return node?dom==node||dom.contains(node.nodeType!=1?node.parentNode:node):!1}__name(contains,"contains"),__name2(contains,"contains");function deepActiveElement(doc2){let elt=doc2.activeElement;for(;elt&&elt.shadowRoot;)elt=elt.shadowRoot.activeElement;return elt}__name(deepActiveElement,"deepActiveElement"),__name2(deepActiveElement,"deepActiveElement");function hasSelection(dom,selection){if(!selection.anchorNode)return!1;try{return contains(dom,selection.anchorNode)}catch{return!1}}__name(hasSelection,"hasSelection"),__name2(hasSelection,"hasSelection");function clientRectsFor(dom){return dom.nodeType==3?textRange(dom,0,dom.nodeValue.length).getClientRects():dom.nodeType==1?dom.getClientRects():[]}__name(clientRectsFor,"clientRectsFor"),__name2(clientRectsFor,"clientRectsFor");function isEquivalentPosition(node,off2,targetNode,targetOff){return targetNode?scanFor(node,off2,targetNode,targetOff,-1)||scanFor(node,off2,targetNode,targetOff,1):!1}__name(isEquivalentPosition,"isEquivalentPosition"),__name2(isEquivalentPosition,"isEquivalentPosition");function domIndex(node){for(var index2=0;;index2++)if(node=node.previousSibling,!node)return index2}__name(domIndex,"domIndex"),__name2(domIndex,"domIndex");function scanFor(node,off2,targetNode,targetOff,dir){for(;;){if(node==targetNode&&off2==targetOff)return!0;if(off2==(dir<0?0:maxOffset(node))){if(node.nodeName=="DIV")return!1;let parent=node.parentNode;if(!parent||parent.nodeType!=1)return!1;off2=domIndex(node)+(dir<0?0:1),node=parent}else if(node.nodeType==1){if(node=node.childNodes[off2+(dir<0?-1:0)],node.nodeType==1&&node.contentEditable=="false")return!1;off2=dir<0?maxOffset(node):0}else return!1}}__name(scanFor,"scanFor"),__name2(scanFor,"scanFor");function maxOffset(node){return node.nodeType==3?node.nodeValue.length:node.childNodes.length}__name(maxOffset,"maxOffset"),__name2(maxOffset,"maxOffset");function flattenRect(rect,left){let x=left?rect.left:rect.right;return{left:x,right:x,top:rect.top,bottom:rect.bottom}}__name(flattenRect,"flattenRect"),__name2(flattenRect,"flattenRect");function windowRect(win){return{left:0,right:win.innerWidth,top:0,bottom:win.innerHeight}}__name(windowRect,"windowRect"),__name2(windowRect,"windowRect");function scrollRectIntoView(dom,rect,side,x,y,xMargin,yMargin,ltr){let doc2=dom.ownerDocument,win=doc2.defaultView||window;for(let cur2=dom,stop=!1;cur2&&!stop;)if(cur2.nodeType==1){let bounding,top2=cur2==doc2.body,scaleX=1,scaleY=1;if(top2)bounding=windowRect(win);else{if(/^(fixed|sticky)$/.test(getComputedStyle(cur2).position)&&(stop=!0),cur2.scrollHeight<=cur2.clientHeight&&cur2.scrollWidth<=cur2.clientWidth){cur2=cur2.assignedSlot||cur2.parentNode;continue}let rect2=cur2.getBoundingClientRect();scaleX=rect2.width/cur2.offsetWidth,scaleY=rect2.height/cur2.offsetHeight,bounding={left:rect2.left,right:rect2.left+cur2.clientWidth*scaleX,top:rect2.top,bottom:rect2.top+cur2.clientHeight*scaleY}}let moveX=0,moveY=0;if(y=="nearest")rect.top<bounding.top?(moveY=-(bounding.top-rect.top+yMargin),side>0&&rect.bottom>bounding.bottom+moveY&&(moveY=rect.bottom-bounding.bottom+moveY+yMargin)):rect.bottom>bounding.bottom&&(moveY=rect.bottom-bounding.bottom+yMargin,side<0&&rect.top-moveY<bounding.top&&(moveY=-(bounding.top+moveY-rect.top+yMargin)));else{let rectHeight=rect.bottom-rect.top,boundingHeight=bounding.bottom-bounding.top;moveY=(y=="center"&&rectHeight<=boundingHeight?rect.top+rectHeight/2-boundingHeight/2:y=="start"||y=="center"&&side<0?rect.top-yMargin:rect.bottom-boundingHeight+yMargin)-bounding.top}if(x=="nearest"?rect.left<bounding.left?(moveX=-(bounding.left-rect.left+xMargin),side>0&&rect.right>bounding.right+moveX&&(moveX=rect.right-bounding.right+moveX+xMargin)):rect.right>bounding.right&&(moveX=rect.right-bounding.right+xMargin,side<0&&rect.left<bounding.left+moveX&&(moveX=-(bounding.left+moveX-rect.left+xMargin))):moveX=(x=="center"?rect.left+(rect.right-rect.left)/2-(bounding.right-bounding.left)/2:x=="start"==ltr?rect.left-xMargin:rect.right-(bounding.right-bounding.left)+xMargin)-bounding.left,moveX||moveY)if(top2)win.scrollBy(moveX,moveY);else{let movedX=0,movedY=0;if(moveY){let start=cur2.scrollTop;cur2.scrollTop+=moveY/scaleY,movedY=(cur2.scrollTop-start)*scaleY}if(moveX){let start=cur2.scrollLeft;cur2.scrollLeft+=moveX/scaleX,movedX=(cur2.scrollLeft-start)*scaleX}rect={left:rect.left-movedX,top:rect.top-movedY,right:rect.right-movedX,bottom:rect.bottom-movedY},movedX&&Math.abs(movedX-moveX)<1&&(x="nearest"),movedY&&Math.abs(movedY-moveY)<1&&(y="nearest")}if(top2)break;cur2=cur2.assignedSlot||cur2.parentNode}else if(cur2.nodeType==11)cur2=cur2.host;else break}__name(scrollRectIntoView,"scrollRectIntoView"),__name2(scrollRectIntoView,"scrollRectIntoView");function scrollableParent(dom){let doc2=dom.ownerDocument;for(let cur2=dom.parentNode;cur2&&cur2!=doc2.body;)if(cur2.nodeType==1){if(cur2.scrollHeight>cur2.clientHeight||cur2.scrollWidth>cur2.clientWidth)return cur2;cur2=cur2.assignedSlot||cur2.parentNode}else if(cur2.nodeType==11)cur2=cur2.host;else break;return null}__name(scrollableParent,"scrollableParent"),__name2(scrollableParent,"scrollableParent");const _DOMSelectionState=class{static{__name(this,"_DOMSelectionState")}constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(domSel){return this.anchorNode==domSel.anchorNode&&this.anchorOffset==domSel.anchorOffset&&this.focusNode==domSel.focusNode&&this.focusOffset==domSel.focusOffset}setRange(range){let{anchorNode,focusNode}=range;this.set(anchorNode,Math.min(range.anchorOffset,anchorNode?maxOffset(anchorNode):0),focusNode,Math.min(range.focusOffset,focusNode?maxOffset(focusNode):0))}set(anchorNode,anchorOffset,focusNode,focusOffset){this.anchorNode=anchorNode,this.anchorOffset=anchorOffset,this.focusNode=focusNode,this.focusOffset=focusOffset}};__name2(_DOMSelectionState,"DOMSelectionState");let DOMSelectionState=_DOMSelectionState,preventScrollSupported=null;function focusPreventScroll(dom){if(dom.setActive)return dom.setActive();if(preventScrollSupported)return dom.focus(preventScrollSupported);let stack=[];for(let cur2=dom;cur2&&(stack.push(cur2,cur2.scrollTop,cur2.scrollLeft),cur2!=cur2.ownerDocument);cur2=cur2.parentNode);if(dom.focus(preventScrollSupported==null?{get preventScroll(){return preventScrollSupported={preventScroll:!0},!0}}:void 0),!preventScrollSupported){preventScrollSupported=!1;for(let i=0;i<stack.length;){let elt=stack[i++],top2=stack[i++],left=stack[i++];elt.scrollTop!=top2&&(elt.scrollTop=top2),elt.scrollLeft!=left&&(elt.scrollLeft=left)}}}__name(focusPreventScroll,"focusPreventScroll"),__name2(focusPreventScroll,"focusPreventScroll");let scratchRange;function textRange(node,from,to=from){let range=scratchRange||(scratchRange=document.createRange());return range.setEnd(node,to),range.setStart(node,from),range}__name(textRange,"textRange"),__name2(textRange,"textRange");function dispatchKey(elt,name2,code){let options={key:name2,code:name2,keyCode:code,which:code,cancelable:!0},down=new KeyboardEvent("keydown",options);down.synthetic=!0,elt.dispatchEvent(down);let up=new KeyboardEvent("keyup",options);return up.synthetic=!0,elt.dispatchEvent(up),down.defaultPrevented||up.defaultPrevented}__name(dispatchKey,"dispatchKey"),__name2(dispatchKey,"dispatchKey");function getRoot(node){for(;node;){if(node&&(node.nodeType==9||node.nodeType==11&&node.host))return node;node=node.assignedSlot||node.parentNode}return null}__name(getRoot,"getRoot"),__name2(getRoot,"getRoot");function clearAttributes(node){for(;node.attributes.length;)node.removeAttributeNode(node.attributes[0])}__name(clearAttributes,"clearAttributes"),__name2(clearAttributes,"clearAttributes");function atElementStart(doc2,selection){let node=selection.focusNode,offset2=selection.focusOffset;if(!node||selection.anchorNode!=node||selection.anchorOffset!=offset2)return!1;for(offset2=Math.min(offset2,maxOffset(node));;)if(offset2){if(node.nodeType!=1)return!1;let prev=node.childNodes[offset2-1];prev.contentEditable=="false"?offset2--:(node=prev,offset2=maxOffset(node))}else{if(node==doc2)return!0;offset2=domIndex(node),node=node.parentNode}}__name(atElementStart,"atElementStart"),__name2(atElementStart,"atElementStart");function isScrolledToBottom(elt){return elt.scrollTop>Math.max(1,elt.scrollHeight-elt.clientHeight-4)}__name(isScrolledToBottom,"isScrolledToBottom"),__name2(isScrolledToBottom,"isScrolledToBottom");const _DOMPos=class _DOMPos2{static{__name(this,"_DOMPos")}constructor(node,offset2,precise=!0){this.node=node,this.offset=offset2,this.precise=precise}static before(dom,precise){return new _DOMPos2(dom.parentNode,domIndex(dom),precise)}static after(dom,precise){return new _DOMPos2(dom.parentNode,domIndex(dom)+1,precise)}};__name2(_DOMPos,"DOMPos");let DOMPos=_DOMPos;const noChildren=[],_ContentView=class _ContentView2{static{__name(this,"_ContentView")}constructor(){this.parent=null,this.dom=null,this.flags=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(view){let pos=this.posAtStart;for(let child of this.children){if(child==view)return pos;pos+=child.length+child.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(view){return this.posBefore(view)+view.length}sync(view,track){if(this.flags&2){let parent=this.dom,prev=null,next;for(let child of this.children){if(child.flags&7){if(!child.dom&&(next=prev?prev.nextSibling:parent.firstChild)){let contentView=_ContentView2.get(next);(!contentView||!contentView.parent&&contentView.canReuseDOM(child))&&child.reuseDOM(next)}child.sync(view,track),child.flags&=-8}if(next=prev?prev.nextSibling:parent.firstChild,track&&!track.written&&track.node==parent&&next!=child.dom&&(track.written=!0),child.dom.parentNode==parent)for(;next&&next!=child.dom;)next=rm$1(next);else parent.insertBefore(child.dom,next);prev=child.dom}for(next=prev?prev.nextSibling:parent.firstChild,next&&track&&track.node==parent&&(track.written=!0);next;)next=rm$1(next)}else if(this.flags&1)for(let child of this.children)child.flags&7&&(child.sync(view,track),child.flags&=-8)}reuseDOM(_dom){}localPosFromDOM(node,offset2){let after;if(node==this.dom)after=this.dom.childNodes[offset2];else{let bias=maxOffset(node)==0?0:offset2==0?-1:1;for(;;){let parent=node.parentNode;if(parent==this.dom)break;bias==0&&parent.firstChild!=parent.lastChild&&(node==parent.firstChild?bias=-1:bias=1),node=parent}bias<0?after=node:after=node.nextSibling}if(after==this.dom.firstChild)return 0;for(;after&&!_ContentView2.get(after);)after=after.nextSibling;if(!after)return this.length;for(let i=0,pos=0;;i++){let child=this.children[i];if(child.dom==after)return pos;pos+=child.length+child.breakAfter}}domBoundsAround(from,to,offset2=0){let fromI=-1,fromStart=-1,toI=-1,toEnd=-1;for(let i=0,pos=offset2,prevEnd=offset2;i<this.children.length;i++){let child=this.children[i],end=pos+child.length;if(pos<from&&end>to)return child.domBoundsAround(from,to,pos);if(end>=from&&fromI==-1&&(fromI=i,fromStart=pos),pos>to&&child.dom.parentNode==this.dom){toI=i,toEnd=prevEnd;break}prevEnd=end,pos=end+child.breakAfter}return{from:fromStart,to:toEnd<0?offset2+this.length:toEnd,startDOM:(fromI?this.children[fromI-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:toI<this.children.length&&toI>=0?this.children[toI].dom:null}}markDirty(andParent=!1){this.flags|=2,this.markParentsDirty(andParent)}markParentsDirty(childList){for(let parent=this.parent;parent;parent=parent.parent){if(childList&&(parent.flags|=2),parent.flags&1)return;parent.flags|=1,childList=!1}}setParent(parent){this.parent!=parent&&(this.parent=parent,this.flags&7&&this.markParentsDirty(!0))}setDOM(dom){this.dom!=dom&&(this.dom&&(this.dom.cmView=null),this.dom=dom,dom.cmView=this)}get rootView(){for(let v=this;;){let parent=v.parent;if(!parent)return v;v=parent}}replaceChildren(from,to,children=noChildren){this.markDirty();for(let i=from;i<to;i++){let child=this.children[i];child.parent==this&&child.destroy()}this.children.splice(from,to-from,...children);for(let i=0;i<children.length;i++)children[i].setParent(this)}ignoreMutation(_rec){return!1}ignoreEvent(_event){return!1}childCursor(pos=this.length){return new ChildCursor(this.children,pos,this.children.length)}childPos(pos,bias=1){return this.childCursor().findPos(pos,bias)}toString(){let name2=this.constructor.name.replace("View","");return name2+(this.children.length?"("+this.children.join()+")":this.length?"["+(name2=="Text"?this.text:this.length)+"]":"")+(this.breakAfter?"#":"")}static get(node){return node.cmView}get isEditable(){return!0}get isWidget(){return!1}get isHidden(){return!1}merge(from,to,source,hasStart,openStart,openEnd){return!1}become(other){return!1}canReuseDOM(other){return other.constructor==this.constructor&&!((this.flags|other.flags)&8)}getSide(){return 0}destroy(){this.parent=null}};__name2(_ContentView,"ContentView");let ContentView=_ContentView;ContentView.prototype.breakAfter=0;function rm$1(dom){let next=dom.nextSibling;return dom.parentNode.removeChild(dom),next}__name(rm$1,"rm$1"),__name2(rm$1,"rm$1");const _ChildCursor=class{static{__name(this,"_ChildCursor")}constructor(children,pos,i){this.children=children,this.pos=pos,this.i=i,this.off=0}findPos(pos,bias=1){for(;;){if(pos>this.pos||pos==this.pos&&(bias>0||this.i==0||this.children[this.i-1].breakAfter))return this.off=pos-this.pos,this;let next=this.children[--this.i];this.pos-=next.length+next.breakAfter}}};__name2(_ChildCursor,"ChildCursor");let ChildCursor=_ChildCursor;function replaceRange(parent,fromI,fromOff,toI,toOff,insert2,breakAtStart,openStart,openEnd){let{children}=parent,before=children.length?children[fromI]:null,last2=insert2.length?insert2[insert2.length-1]:null,breakAtEnd=last2?last2.breakAfter:breakAtStart;if(!(fromI==toI&&before&&!breakAtStart&&!breakAtEnd&&insert2.length<2&&before.merge(fromOff,toOff,insert2.length?last2:null,fromOff==0,openStart,openEnd))){if(toI<children.length){let after=children[toI];after&&(toOff<after.length||after.breakAfter&&last2?.breakAfter)?(fromI==toI&&(after=after.split(toOff),toOff=0),!breakAtEnd&&last2&&after.merge(0,toOff,last2,!0,0,openEnd)?insert2[insert2.length-1]=after:((toOff||after.children.length&&!after.children[0].length)&&after.merge(0,toOff,null,!1,0,openEnd),insert2.push(after))):after?.breakAfter&&(last2?last2.breakAfter=1:breakAtStart=1),toI++}for(before&&(before.breakAfter=breakAtStart,fromOff>0&&(!breakAtStart&&insert2.length&&before.merge(fromOff,before.length,insert2[0],!1,openStart,0)?before.breakAfter=insert2.shift().breakAfter:(fromOff<before.length||before.children.length&&before.children[before.children.length-1].length==0)&&before.merge(fromOff,before.length,null,!1,openStart,0),fromI++));fromI<toI&&insert2.length;)if(children[toI-1].become(insert2[insert2.length-1]))toI--,insert2.pop(),openEnd=insert2.length?0:openStart;else if(children[fromI].become(insert2[0]))fromI++,insert2.shift(),openStart=insert2.length?0:openEnd;else break;!insert2.length&&fromI&&toI<children.length&&!children[fromI-1].breakAfter&&children[toI].merge(0,0,children[fromI-1],!1,openStart,openEnd)&&fromI--,(fromI<toI||insert2.length)&&parent.replaceChildren(fromI,toI,insert2)}}__name(replaceRange,"replaceRange"),__name2(replaceRange,"replaceRange");function mergeChildrenInto(parent,from,to,insert2,openStart,openEnd){let cur2=parent.childCursor(),{i:toI,off:toOff}=cur2.findPos(to,1),{i:fromI,off:fromOff}=cur2.findPos(from,-1),dLen=from-to;for(let view of insert2)dLen+=view.length;parent.length+=dLen,replaceRange(parent,fromI,fromOff,toI,toOff,insert2,0,openStart,openEnd)}__name(mergeChildrenInto,"mergeChildrenInto"),__name2(mergeChildrenInto,"mergeChildrenInto");let nav=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},doc=typeof document<"u"?document:{documentElement:{style:{}}};const ie_edge=/Edge\/(\d+)/.exec(nav.userAgent),ie_upto10=/MSIE \d/.test(nav.userAgent),ie_11up=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent),ie=!!(ie_upto10||ie_11up||ie_edge),gecko=!ie&&/gecko\/(\d+)/i.test(nav.userAgent),chrome=!ie&&/Chrome\/(\d+)/.exec(nav.userAgent),webkit="webkitFontSmoothing"in doc.documentElement.style,safari=!ie&&/Apple Computer/.test(nav.vendor),ios=safari&&(/Mobile\/\w+/.test(nav.userAgent)||nav.maxTouchPoints>2);var browser={mac:ios||/Mac/.test(nav.platform),windows:/Win/.test(nav.platform),linux:/Linux|X11/.test(nav.platform),ie,ie_version:ie_upto10?doc.documentMode||6:ie_11up?+ie_11up[1]:ie_edge?+ie_edge[1]:0,gecko,gecko_version:gecko?+(/Firefox\/(\d+)/.exec(nav.userAgent)||[0,0])[1]:0,chrome:!!chrome,chrome_version:chrome?+chrome[1]:0,ios,android:/Android\b/.test(nav.userAgent),webkit,safari,webkit_version:webkit?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:doc.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};const MaxJoinLen=256,_TextView=class _TextView2 extends ContentView{static{__name(this,"_TextView")}constructor(text){super(),this.text=text}get length(){return this.text.length}createDOM(textDOM){this.setDOM(textDOM||document.createTextNode(this.text))}sync(view,track){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(track&&track.node==this.dom&&(track.written=!0),this.dom.nodeValue=this.text)}reuseDOM(dom){dom.nodeType==3&&this.createDOM(dom)}merge(from,to,source){return this.flags&8||source&&(!(source instanceof _TextView2)||this.length-(to-from)+source.length>MaxJoinLen||source.flags&8)?!1:(this.text=this.text.slice(0,from)+(source?source.text:"")+this.text.slice(to),this.markDirty(),!0)}split(from){let result=new _TextView2(this.text.slice(from));return this.text=this.text.slice(0,from),this.markDirty(),result.flags|=this.flags&8,result}localPosFromDOM(node,offset2){return node==this.dom?offset2:offset2?this.text.length:0}domAtPos(pos){return new DOMPos(this.dom,pos)}domBoundsAround(_from,_to,offset2){return{from:offset2,to:offset2+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(pos,side){return textCoords(this.dom,pos,side)}};__name2(_TextView,"TextView");let TextView=_TextView;const _MarkView=class _MarkView2 extends ContentView{static{__name(this,"_MarkView")}constructor(mark,children=[],length=0){super(),this.mark=mark,this.children=children,this.length=length;for(let ch of children)ch.setParent(this)}setAttrs(dom){if(clearAttributes(dom),this.mark.class&&(dom.className=this.mark.class),this.mark.attrs)for(let name2 in this.mark.attrs)dom.setAttribute(name2,this.mark.attrs[name2]);return dom}canReuseDOM(other){return super.canReuseDOM(other)&&!((this.flags|other.flags)&8)}reuseDOM(node){node.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(node),this.flags|=6)}sync(view,track){this.dom?this.flags&4&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(view,track)}merge(from,to,source,_hasStart,openStart,openEnd){return source&&(!(source instanceof _MarkView2&&source.mark.eq(this.mark))||from&&openStart<=0||to<this.length&&openEnd<=0)?!1:(mergeChildrenInto(this,from,to,source?source.children:[],openStart-1,openEnd-1),this.markDirty(),!0)}split(from){let result=[],off2=0,detachFrom=-1,i=0;for(let elt of this.children){let end=off2+elt.length;end>from&&result.push(off2<from?elt.split(from-off2):elt),detachFrom<0&&off2>=from&&(detachFrom=i),off2=end,i++}let length=this.length-from;return this.length=from,detachFrom>-1&&(this.children.length=detachFrom,this.markDirty()),new _MarkView2(this.mark,result,length)}domAtPos(pos){return inlineDOMAtPos(this,pos)}coordsAt(pos,side){return coordsInChildren(this,pos,side)}};__name2(_MarkView,"MarkView");let MarkView=_MarkView;function textCoords(text,pos,side){let length=text.nodeValue.length;pos>length&&(pos=length);let from=pos,to=pos,flatten2=0;pos==0&&side<0||pos==length&&side>=0?browser.chrome||browser.gecko||(pos?(from--,flatten2=1):to<length&&(to++,flatten2=-1)):side<0?from--:to<length&&to++;let rects=textRange(text,from,to).getClientRects();if(!rects.length)return null;let rect=rects[(flatten2?flatten2<0:side>=0)?0:rects.length-1];return browser.safari&&!flatten2&&rect.width==0&&(rect=Array.prototype.find.call(rects,r=>r.width)||rect),flatten2?flattenRect(rect,flatten2<0):rect||null}__name(textCoords,"textCoords"),__name2(textCoords,"textCoords");const _WidgetView=class _WidgetView2 extends ContentView{static{__name(this,"_WidgetView")}static create(widget,length,side){return new _WidgetView2(widget,length,side)}constructor(widget,length,side){super(),this.widget=widget,this.length=length,this.side=side,this.prevWidget=null}split(from){let result=_WidgetView2.create(this.widget,this.length-from,this.side);return this.length-=from,result}sync(view){(!this.dom||!this.widget.updateDOM(this.dom,view))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(view)),this.dom.contentEditable="false")}getSide(){return this.side}merge(from,to,source,hasStart,openStart,openEnd){return source&&(!(source instanceof _WidgetView2)||!this.widget.compare(source.widget)||from>0&&openStart<=0||to<this.length&&openEnd<=0)?!1:(this.length=from+(source?source.length:0)+(this.length-to),!0)}become(other){return other instanceof _WidgetView2&&other.side==this.side&&this.widget.constructor==other.widget.constructor?(this.widget.compare(other.widget)||this.markDirty(!0),this.dom&&!this.prevWidget&&(this.prevWidget=this.widget),this.widget=other.widget,this.length=other.length,!0):!1}ignoreMutation(){return!0}ignoreEvent(event){return this.widget.ignoreEvent(event)}get overrideDOMText(){if(this.length==0)return Text.empty;let top2=this;for(;top2.parent;)top2=top2.parent;let{view}=top2,text=view&&view.state.doc,start=this.posAtStart;return text?text.slice(start,start+this.length):Text.empty}domAtPos(pos){return(this.length?pos==0:this.side>0)?DOMPos.before(this.dom):DOMPos.after(this.dom,pos==this.length)}domBoundsAround(){return null}coordsAt(pos,side){let custom=this.widget.coordsAt(this.dom,pos,side);if(custom)return custom;let rects=this.dom.getClientRects(),rect=null;if(!rects.length)return null;let fromBack=this.side?this.side<0:pos>0;for(let i=fromBack?rects.length-1:0;rect=rects[i],!(pos>0?i==0:i==rects.length-1||rect.top<rect.bottom);i+=fromBack?-1:1);return flattenRect(rect,!fromBack)}get isEditable(){return!1}get isWidget(){return!0}get isHidden(){return this.widget.isHidden}destroy(){super.destroy(),this.dom&&this.widget.destroy(this.dom)}};__name2(_WidgetView,"WidgetView");let WidgetView=_WidgetView;const _WidgetBufferView=class _WidgetBufferView2 extends ContentView{static{__name(this,"_WidgetBufferView")}constructor(side){super(),this.side=side}get length(){return 0}merge(){return!1}become(other){return other instanceof _WidgetBufferView2&&other.side==this.side}split(){return new _WidgetBufferView2(this.side)}sync(){if(!this.dom){let dom=document.createElement("img");dom.className="cm-widgetBuffer",dom.setAttribute("aria-hidden","true"),this.setDOM(dom)}}getSide(){return this.side}domAtPos(pos){return this.side>0?DOMPos.before(this.dom):DOMPos.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(pos){return this.dom.getBoundingClientRect()}get overrideDOMText(){return Text.empty}get isHidden(){return!0}};__name2(_WidgetBufferView,"WidgetBufferView");let WidgetBufferView=_WidgetBufferView;TextView.prototype.children=WidgetView.prototype.children=WidgetBufferView.prototype.children=noChildren;function inlineDOMAtPos(parent,pos){let dom=parent.dom,{children}=parent,i=0;for(let off2=0;i<children.length;i++){let child=children[i],end=off2+child.length;if(!(end==off2&&child.getSide()<=0)){if(pos>off2&&pos<end&&child.dom.parentNode==dom)return child.domAtPos(pos-off2);if(pos<=off2)break;off2=end}}for(let j=i;j>0;j--){let prev=children[j-1];if(prev.dom.parentNode==dom)return prev.domAtPos(prev.length)}for(let j=i;j<children.length;j++){let next=children[j];if(next.dom.parentNode==dom)return next.domAtPos(0)}return new DOMPos(dom,0)}__name(inlineDOMAtPos,"inlineDOMAtPos"),__name2(inlineDOMAtPos,"inlineDOMAtPos");function joinInlineInto(parent,view,open){let last2,{children}=parent;open>0&&view instanceof MarkView&&children.length&&(last2=children[children.length-1])instanceof MarkView&&last2.mark.eq(view.mark)?joinInlineInto(last2,view.children[0],open-1):(children.push(view),view.setParent(parent)),parent.length+=view.length}__name(joinInlineInto,"joinInlineInto"),__name2(joinInlineInto,"joinInlineInto");function coordsInChildren(view,pos,side){let before=null,beforePos=-1,after=null,afterPos=-1;function scan(view2,pos2){for(let i=0,off2=0;i<view2.children.length&&off2<=pos2;i++){let child=view2.children[i],end=off2+child.length;end>=pos2&&(child.children.length?scan(child,pos2-off2):(!after||after.isHidden&&side>0)&&(end>pos2||off2==end&&child.getSide()>0)?(after=child,afterPos=pos2-off2):(off2<pos2||off2==end&&child.getSide()<0&&!child.isHidden)&&(before=child,beforePos=pos2-off2)),off2=end}}__name(scan,"scan"),__name2(scan,"scan"),scan(view,pos);let target=(side<0?before:after)||before||after;return target?target.coordsAt(Math.max(0,target==before?beforePos:afterPos),side):fallbackRect(view)}__name(coordsInChildren,"coordsInChildren"),__name2(coordsInChildren,"coordsInChildren");function fallbackRect(view){let last2=view.dom.lastChild;if(!last2)return view.dom.getBoundingClientRect();let rects=clientRectsFor(last2);return rects[rects.length-1]||null}__name(fallbackRect,"fallbackRect"),__name2(fallbackRect,"fallbackRect");function combineAttrs(source,target){for(let name2 in source)name2=="class"&&target.class?target.class+=" "+source.class:name2=="style"&&target.style?target.style+=";"+source.style:target[name2]=source[name2];return target}__name(combineAttrs,"combineAttrs"),__name2(combineAttrs,"combineAttrs");const noAttrs=Object.create(null);function attrsEq(a,b,ignore){if(a==b)return!0;a||(a=noAttrs),b||(b=noAttrs);let keysA=Object.keys(a),keysB=Object.keys(b);if(keysA.length-(ignore&&keysA.indexOf(ignore)>-1?1:0)!=keysB.length-(ignore&&keysB.indexOf(ignore)>-1?1:0))return!1;for(let key of keysA)if(key!=ignore&&(keysB.indexOf(key)==-1||a[key]!==b[key]))return!1;return!0}__name(attrsEq,"attrsEq"),__name2(attrsEq,"attrsEq");function updateAttrs(dom,prev,attrs){let changed=!1;if(prev)for(let name2 in prev)attrs&&name2 in attrs||(changed=!0,name2=="style"?dom.style.cssText="":dom.removeAttribute(name2));if(attrs)for(let name2 in attrs)prev&&prev[name2]==attrs[name2]||(changed=!0,name2=="style"?dom.style.cssText=attrs[name2]:dom.setAttribute(name2,attrs[name2]));return changed}__name(updateAttrs,"updateAttrs"),__name2(updateAttrs,"updateAttrs");function getAttrs(dom){let attrs=Object.create(null);for(let i=0;i<dom.attributes.length;i++){let attr=dom.attributes[i];attrs[attr.name]=attr.value}return attrs}__name(getAttrs,"getAttrs"),__name2(getAttrs,"getAttrs");const _LineView=class _LineView2 extends ContentView{static{__name(this,"_LineView")}constructor(){super(...arguments),this.children=[],this.length=0,this.prevAttrs=void 0,this.attrs=null,this.breakAfter=0}merge(from,to,source,hasStart,openStart,openEnd){if(source){if(!(source instanceof _LineView2))return!1;this.dom||source.transferDOM(this)}return hasStart&&this.setDeco(source?source.attrs:null),mergeChildrenInto(this,from,to,source?source.children:[],openStart,openEnd),!0}split(at){let end=new _LineView2;if(end.breakAfter=this.breakAfter,this.length==0)return end;let{i,off:off2}=this.childPos(at);off2&&(end.append(this.children[i].split(off2),0),this.children[i].merge(off2,this.children[i].length,null,!1,0,0),i++);for(let j=i;j<this.children.length;j++)end.append(this.children[j],0);for(;i>0&&this.children[i-1].length==0;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=at,end}transferDOM(other){this.dom&&(this.markDirty(),other.setDOM(this.dom),other.prevAttrs=this.prevAttrs===void 0?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(attrs){attrsEq(this.attrs,attrs)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=attrs)}append(child,openStart){joinInlineInto(this,child,openStart)}addLineDeco(deco){let attrs=deco.spec.attributes,cls=deco.spec.class;attrs&&(this.attrs=combineAttrs(attrs,this.attrs||{})),cls&&(this.attrs=combineAttrs({class:cls},this.attrs||{}))}domAtPos(pos){return inlineDOMAtPos(this,pos)}reuseDOM(node){node.nodeName=="DIV"&&(this.setDOM(node),this.flags|=6)}sync(view,track){var _a3;this.dom?this.flags&4&&(clearAttributes(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),this.prevAttrs!==void 0&&(updateAttrs(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(view,track);let last2=this.dom.lastChild;for(;last2&&ContentView.get(last2)instanceof MarkView;)last2=last2.lastChild;if(!last2||!this.length||last2.nodeName!="BR"&&((_a3=ContentView.get(last2))===null||_a3===void 0?void 0:_a3.isEditable)==!1&&(!browser.ios||!this.children.some(ch=>ch instanceof TextView))){let hack=document.createElement("BR");hack.cmIgnore=!0,this.dom.appendChild(hack)}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let totalWidth=0,textHeight;for(let child of this.children){if(!(child instanceof TextView)||/[^ -~]/.test(child.text))return null;let rects=clientRectsFor(child.dom);if(rects.length!=1)return null;totalWidth+=rects[0].width,textHeight=rects[0].height}return totalWidth?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:totalWidth/this.length,textHeight}:null}coordsAt(pos,side){let rect=coordsInChildren(this,pos,side);if(!this.children.length&&rect&&this.parent){let{heightOracle}=this.parent.view.viewState,height=rect.bottom-rect.top;if(Math.abs(height-heightOracle.lineHeight)<2&&heightOracle.textHeight<height){let dist2=(height-heightOracle.textHeight)/2;return{top:rect.top+dist2,bottom:rect.bottom-dist2,left:rect.left,right:rect.left}}}return rect}become(_other){return!1}covers(){return!0}static find(docView,pos){for(let i=0,off2=0;i<docView.children.length;i++){let block=docView.children[i],end=off2+block.length;if(end>=pos){if(block instanceof _LineView2)return block;if(end>pos)break}off2=end+block.breakAfter}return null}};__name2(_LineView,"LineView");let LineView=_LineView;const _BlockWidgetView=class _BlockWidgetView2 extends ContentView{static{__name(this,"_BlockWidgetView")}constructor(widget,length,deco){super(),this.widget=widget,this.length=length,this.deco=deco,this.breakAfter=0,this.prevWidget=null}merge(from,to,source,_takeDeco,openStart,openEnd){return source&&(!(source instanceof _BlockWidgetView2)||!this.widget.compare(source.widget)||from>0&&openStart<=0||to<this.length&&openEnd<=0)?!1:(this.length=from+(source?source.length:0)+(this.length-to),!0)}domAtPos(pos){return pos==0?DOMPos.before(this.dom):DOMPos.after(this.dom,pos==this.length)}split(at){let len=this.length-at;this.length=at;let end=new _BlockWidgetView2(this.widget,len,this.deco);return end.breakAfter=this.breakAfter,end}get children(){return noChildren}sync(view){(!this.dom||!this.widget.updateDOM(this.dom,view))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(view)),this.dom.contentEditable="false")}get overrideDOMText(){return this.parent?this.parent.view.state.doc.slice(this.posAtStart,this.posAtEnd):Text.empty}domBoundsAround(){return null}become(other){return other instanceof _BlockWidgetView2&&other.widget.constructor==this.widget.constructor?(other.widget.compare(this.widget)||this.markDirty(!0),this.dom&&!this.prevWidget&&(this.prevWidget=this.widget),this.widget=other.widget,this.length=other.length,this.deco=other.deco,this.breakAfter=other.breakAfter,!0):!1}ignoreMutation(){return!0}ignoreEvent(event){return this.widget.ignoreEvent(event)}get isEditable(){return!1}get isWidget(){return!0}coordsAt(pos,side){return this.widget.coordsAt(this.dom,pos,side)}destroy(){super.destroy(),this.dom&&this.widget.destroy(this.dom)}covers(side){let{startSide,endSide}=this.deco;return startSide==endSide?!1:side<0?startSide<0:endSide>0}};__name2(_BlockWidgetView,"BlockWidgetView");let BlockWidgetView=_BlockWidgetView;const _WidgetType=class{static{__name(this,"_WidgetType")}eq(widget){return!1}updateDOM(dom,view){return!1}compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(event){return!0}coordsAt(dom,pos,side){return null}get isHidden(){return!1}destroy(dom){}};__name2(_WidgetType,"WidgetType");let WidgetType=_WidgetType;var BlockType=function(BlockType2){return BlockType2[BlockType2.Text=0]="Text",BlockType2[BlockType2.WidgetBefore=1]="WidgetBefore",BlockType2[BlockType2.WidgetAfter=2]="WidgetAfter",BlockType2[BlockType2.WidgetRange=3]="WidgetRange",BlockType2}(BlockType||(BlockType={}));const _Decoration=class extends RangeValue{static{__name(this,"_Decoration")}constructor(startSide,endSide,widget,spec){super(),this.startSide=startSide,this.endSide=endSide,this.widget=widget,this.spec=spec}get heightRelevant(){return!1}static mark(spec){return new MarkDecoration(spec)}static widget(spec){let side=Math.max(-1e4,Math.min(1e4,spec.side||0)),block=!!spec.block;return side+=block&&!spec.inlineOrder?side>0?3e8:-4e8:side>0?1e8:-1e8,new PointDecoration(spec,side,side,block,spec.widget||null,!1)}static replace(spec){let block=!!spec.block,startSide,endSide;if(spec.isBlockGap)startSide=-5e8,endSide=4e8;else{let{start,end}=getInclusive(spec,block);startSide=(start?block?-3e8:-1:5e8)-1,endSide=(end?block?2e8:1:-6e8)+1}return new PointDecoration(spec,startSide,endSide,block,spec.widget||null,!0)}static line(spec){return new LineDecoration(spec)}static set(of,sort2=!1){return RangeSet.of(of,sort2)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};__name2(_Decoration,"Decoration");let Decoration=_Decoration;Decoration.none=RangeSet.empty;const _MarkDecoration=class _MarkDecoration2 extends Decoration{static{__name(this,"_MarkDecoration")}constructor(spec){let{start,end}=getInclusive(spec);super(start?-1:5e8,end?1:-6e8,null,spec),this.tagName=spec.tagName||"span",this.class=spec.class||"",this.attrs=spec.attributes||null}eq(other){var _a3,_b2;return this==other||other instanceof _MarkDecoration2&&this.tagName==other.tagName&&(this.class||((_a3=this.attrs)===null||_a3===void 0?void 0:_a3.class))==(other.class||((_b2=other.attrs)===null||_b2===void 0?void 0:_b2.class))&&attrsEq(this.attrs,other.attrs,"class")}range(from,to=from){if(from>=to)throw new RangeError("Mark decorations may not be empty");return super.range(from,to)}};__name2(_MarkDecoration,"MarkDecoration");let MarkDecoration=_MarkDecoration;MarkDecoration.prototype.point=!1;const _LineDecoration=class _LineDecoration2 extends Decoration{static{__name(this,"_LineDecoration")}constructor(spec){super(-2e8,-2e8,null,spec)}eq(other){return other instanceof _LineDecoration2&&this.spec.class==other.spec.class&&attrsEq(this.spec.attributes,other.spec.attributes)}range(from,to=from){if(to!=from)throw new RangeError("Line decoration ranges must be zero-length");return super.range(from,to)}};__name2(_LineDecoration,"LineDecoration");let LineDecoration=_LineDecoration;LineDecoration.prototype.mapMode=MapMode.TrackBefore,LineDecoration.prototype.point=!0;const _PointDecoration=class _PointDecoration2 extends Decoration{static{__name(this,"_PointDecoration")}constructor(spec,startSide,endSide,block,widget,isReplace){super(startSide,endSide,widget,spec),this.block=block,this.isReplace=isReplace,this.mapMode=block?startSide<=0?MapMode.TrackBefore:MapMode.TrackAfter:MapMode.TrackDel}get type(){return this.startSide!=this.endSide?BlockType.WidgetRange:this.startSide<=0?BlockType.WidgetBefore:BlockType.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(other){return other instanceof _PointDecoration2&&widgetsEq(this.widget,other.widget)&&this.block==other.block&&this.startSide==other.startSide&&this.endSide==other.endSide}range(from,to=from){if(this.isReplace&&(from>to||from==to&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&to!=from)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(from,to)}};__name2(_PointDecoration,"PointDecoration");let PointDecoration=_PointDecoration;PointDecoration.prototype.point=!0;function getInclusive(spec,block=!1){let{inclusiveStart:start,inclusiveEnd:end}=spec;return start==null&&(start=spec.inclusive),end==null&&(end=spec.inclusive),{start:start??block,end:end??block}}__name(getInclusive,"getInclusive"),__name2(getInclusive,"getInclusive");function widgetsEq(a,b){return a==b||!!(a&&b&&a.compare(b))}__name(widgetsEq,"widgetsEq"),__name2(widgetsEq,"widgetsEq");function addRange(from,to,ranges,margin=0){let last2=ranges.length-1;last2>=0&&ranges[last2]+margin>=from?ranges[last2]=Math.max(ranges[last2],to):ranges.push(from,to)}__name(addRange,"addRange"),__name2(addRange,"addRange");const _ContentBuilder=class _ContentBuilder2{static{__name(this,"_ContentBuilder")}constructor(doc2,pos,end,disallowBlockEffectsFor){this.doc=doc2,this.pos=pos,this.end=end,this.disallowBlockEffectsFor=disallowBlockEffectsFor,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=doc2.iter(),this.skip=pos}posCovered(){if(this.content.length==0)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let last2=this.content[this.content.length-1];return!(last2.breakAfter||last2 instanceof BlockWidgetView&&last2.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new LineView),this.atCursorPos=!0),this.curLine}flushBuffer(active=this.bufferMarks){this.pendingBuffer&&(this.curLine.append(wrapMarks(new WidgetBufferView(-1),active),active.length),this.pendingBuffer=0)}addBlockWidget(view){this.flushBuffer(),this.curLine=null,this.content.push(view)}finish(openEnd){this.pendingBuffer&&openEnd<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,!this.posCovered()&&!(openEnd&&this.content.length&&this.content[this.content.length-1]instanceof BlockWidgetView)&&this.getLine()}buildText(length,active,openStart){for(;length>0;){if(this.textOff==this.text.length){let{value,lineBreak,done}=this.cursor.next(this.skip);if(this.skip=0,done)throw new Error("Ran out of text content when drawing inline views");if(lineBreak){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,length--;continue}else this.text=value,this.textOff=0}let take=Math.min(this.text.length-this.textOff,length,512);this.flushBuffer(active.slice(active.length-openStart)),this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff,this.textOff+take)),active),openStart),this.atCursorPos=!0,this.textOff+=take,length-=take,openStart=0}}span(from,to,active,openStart){this.buildText(to-from,active,openStart),this.pos=to,this.openStart<0&&(this.openStart=openStart)}point(from,to,deco,active,openStart,index2){if(this.disallowBlockEffectsFor[index2]&&deco instanceof PointDecoration){if(deco.block)throw new RangeError("Block decorations may not be specified via plugins");if(to>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let len=to-from;if(deco instanceof PointDecoration)if(deco.block)deco.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new BlockWidgetView(deco.widget||new NullWidget("div"),len,deco));else{let view=WidgetView.create(deco.widget||new NullWidget("span"),len,len?0:deco.startSide),cursorBefore=this.atCursorPos&&!view.isEditable&&openStart<=active.length&&(from<to||deco.startSide>0),cursorAfter=!view.isEditable&&(from<to||openStart>active.length||deco.startSide<=0),line=this.getLine();this.pendingBuffer==2&&!cursorBefore&&!view.isEditable&&(this.pendingBuffer=0),this.flushBuffer(active),cursorBefore&&(line.append(wrapMarks(new WidgetBufferView(1),active),openStart),openStart=active.length+Math.max(0,openStart-active.length)),line.append(wrapMarks(view,active),openStart),this.atCursorPos=cursorAfter,this.pendingBuffer=cursorAfter?from<to||openStart>active.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=active.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(deco);len&&(this.textOff+len<=this.text.length?this.textOff+=len:(this.skip+=len-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=to),this.openStart<0&&(this.openStart=openStart)}static build(text,from,to,decorations2,dynamicDecorationMap){let builder=new _ContentBuilder2(text,from,to,dynamicDecorationMap);return builder.openEnd=RangeSet.spans(decorations2,from,to,builder),builder.openStart<0&&(builder.openStart=builder.openEnd),builder.finish(builder.openEnd),builder}};__name2(_ContentBuilder,"ContentBuilder");let ContentBuilder=_ContentBuilder;function wrapMarks(view,active){for(let mark of active)view=new MarkView(mark,[view],view.length);return view}__name(wrapMarks,"wrapMarks"),__name2(wrapMarks,"wrapMarks");const _NullWidget=class extends WidgetType{static{__name(this,"_NullWidget")}constructor(tag){super(),this.tag=tag}eq(other){return other.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(elt){return elt.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}};__name2(_NullWidget,"NullWidget");let NullWidget=_NullWidget;const clickAddsSelectionRange=Facet.define(),dragMovesSelection$1=Facet.define(),mouseSelectionStyle=Facet.define(),exceptionSink=Facet.define(),updateListener=Facet.define(),inputHandler$1=Facet.define(),focusChangeEffect=Facet.define(),perLineTextDirection=Facet.define({combine:values=>values.some(x=>x)}),nativeSelectionHidden=Facet.define({combine:values=>values.some(x=>x)}),_ScrollTarget=class _ScrollTarget2{static{__name(this,"_ScrollTarget")}constructor(range,y="nearest",x="nearest",yMargin=5,xMargin=5){this.range=range,this.y=y,this.x=x,this.yMargin=yMargin,this.xMargin=xMargin}map(changes){return changes.empty?this:new _ScrollTarget2(this.range.map(changes),this.y,this.x,this.yMargin,this.xMargin)}};__name2(_ScrollTarget,"ScrollTarget");let ScrollTarget=_ScrollTarget;const scrollIntoView$1=StateEffect.define({map:(t2,ch)=>t2.map(ch)});function logException(state,exception,context){let handler=state.facet(exceptionSink);handler.length?handler[0](exception):window.onerror?window.onerror(String(exception),context,void 0,void 0,exception):context?console.error(context+":",exception):console.error(exception)}__name(logException,"logException"),__name2(logException,"logException");const editable=Facet.define({combine:values=>values.length?values[0]:!0});let nextPluginID=0;const viewPlugin=Facet.define(),_ViewPlugin=class _ViewPlugin2{static{__name(this,"_ViewPlugin")}constructor(id,create,domEventHandlers,domEventObservers,buildExtensions){this.id=id,this.create=create,this.domEventHandlers=domEventHandlers,this.domEventObservers=domEventObservers,this.extension=buildExtensions(this)}static define(create,spec){const{eventHandlers,eventObservers,provide,decorations:deco}=spec||{};return new _ViewPlugin2(nextPluginID++,create,eventHandlers,eventObservers,plugin=>{let ext=[viewPlugin.of(plugin)];return deco&&ext.push(decorations.of(view=>{let pluginInst=view.plugin(plugin);return pluginInst?deco(pluginInst):Decoration.none})),provide&&ext.push(provide(plugin)),ext})}static fromClass(cls,spec){return _ViewPlugin2.define(view=>new cls(view),spec)}};__name2(_ViewPlugin,"ViewPlugin");let ViewPlugin=_ViewPlugin;const _PluginInstance=class{static{__name(this,"_PluginInstance")}constructor(spec){this.spec=spec,this.mustUpdate=null,this.value=null}update(view){if(this.value){if(this.mustUpdate){let update=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(update)}catch(e){if(logException(update.state,e,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(view)}catch(e){logException(view.state,e,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(view){var _a3;if(!((_a3=this.value)===null||_a3===void 0)&&_a3.destroy)try{this.value.destroy()}catch(e){logException(view.state,e,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}};__name2(_PluginInstance,"PluginInstance");let PluginInstance=_PluginInstance;const editorAttributes=Facet.define(),contentAttributes=Facet.define(),decorations=Facet.define(),atomicRanges=Facet.define(),bidiIsolatedRanges=Facet.define();function getIsolatedRanges(view,from,to){let isolates=view.state.facet(bidiIsolatedRanges);if(!isolates.length)return isolates;let sets=isolates.map(i=>i instanceof Function?i(view):i),result=[];return RangeSet.spans(sets,from,to,{point(){},span(from2,to2,active,open){let level=result;for(let i=active.length-1;i>=0;i--,open--){let iso=active[i].spec.bidiIsolate,update;if(iso!=null)if(open>0&&level.length&&(update=level[level.length-1]).to==from2&&update.direction==iso)update.to=to2,level=update.inner;else{let add2={from:from2,to:to2,direction:iso,inner:[]};level.push(add2),level=add2.inner}}}}),result}__name(getIsolatedRanges,"getIsolatedRanges"),__name2(getIsolatedRanges,"getIsolatedRanges");const scrollMargins=Facet.define();function getScrollMargins(view){let left=0,right=0,top2=0,bottom=0;for(let source of view.state.facet(scrollMargins)){let m=source(view);m&&(m.left!=null&&(left=Math.max(left,m.left)),m.right!=null&&(right=Math.max(right,m.right)),m.top!=null&&(top2=Math.max(top2,m.top)),m.bottom!=null&&(bottom=Math.max(bottom,m.bottom)))}return{left,right,top:top2,bottom}}__name(getScrollMargins,"getScrollMargins"),__name2(getScrollMargins,"getScrollMargins");const styleModule=Facet.define(),_ChangedRange=class _ChangedRange2{static{__name(this,"_ChangedRange")}constructor(fromA,toA,fromB,toB){this.fromA=fromA,this.toA=toA,this.fromB=fromB,this.toB=toB}join(other){return new _ChangedRange2(Math.min(this.fromA,other.fromA),Math.max(this.toA,other.toA),Math.min(this.fromB,other.fromB),Math.max(this.toB,other.toB))}addToSet(set){let i=set.length,me=this;for(;i>0;i--){let range=set[i-1];if(!(range.fromA>me.toA)){if(range.toA<me.fromA)break;me=me.join(range),set.splice(i-1,1)}}return set.splice(i,0,me),set}static extendWithRanges(diff2,ranges){if(ranges.length==0)return diff2;let result=[];for(let dI=0,rI=0,posA=0,posB=0;;dI++){let next=dI==diff2.length?null:diff2[dI],off2=posA-posB,end=next?next.fromB:1e9;for(;rI<ranges.length&&ranges[rI]<end;){let from=ranges[rI],to=ranges[rI+1],fromB=Math.max(posB,from),toB=Math.min(end,to);if(fromB<=toB&&new _ChangedRange2(fromB+off2,toB+off2,fromB,toB).addToSet(result),to>end)break;rI+=2}if(!next)return result;new _ChangedRange2(next.fromA,next.toA,next.fromB,next.toB).addToSet(result),posA=next.toA,posB=next.toB}}};__name2(_ChangedRange,"ChangedRange");let ChangedRange=_ChangedRange;const _ViewUpdate=class _ViewUpdate2{static{__name(this,"_ViewUpdate")}constructor(view,state,transactions){this.view=view,this.state=state,this.transactions=transactions,this.flags=0,this.startState=view.state,this.changes=ChangeSet.empty(this.startState.doc.length);for(let tr of transactions)this.changes=this.changes.compose(tr.changes);let changedRanges=[];this.changes.iterChangedRanges((fromA,toA,fromB,toB)=>changedRanges.push(new ChangedRange(fromA,toA,fromB,toB))),this.changedRanges=changedRanges}static create(view,state,transactions){return new _ViewUpdate2(view,state,transactions)}get viewportChanged(){return(this.flags&4)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&10)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(tr=>tr.selection)}get empty(){return this.flags==0&&this.transactions.length==0}};__name2(_ViewUpdate,"ViewUpdate");let ViewUpdate=_ViewUpdate;var Direction=function(Direction2){return Direction2[Direction2.LTR=0]="LTR",Direction2[Direction2.RTL=1]="RTL",Direction2}(Direction||(Direction={}));const LTR=Direction.LTR,RTL=Direction.RTL;function dec(str){let result=[];for(let i=0;i<str.length;i++)result.push(1<<+str[i]);return result}__name(dec,"dec"),__name2(dec,"dec");const LowTypes=dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"),ArabicTypes=dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"),Brackets=Object.create(null),BracketStack=[];for(let p of["()","[]","{}"]){let l2=p.charCodeAt(0),r=p.charCodeAt(1);Brackets[l2]=r,Brackets[r]=-l2}function charType(ch){return ch<=247?LowTypes[ch]:1424<=ch&&ch<=1524?2:1536<=ch&&ch<=1785?ArabicTypes[ch-1536]:1774<=ch&&ch<=2220?4:8192<=ch&&ch<=8203?256:64336<=ch&&ch<=65023?4:ch==8204?256:1}__name(charType,"charType"),__name2(charType,"charType");const BidiRE=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/,_BidiSpan=class{static{__name(this,"_BidiSpan")}get dir(){return this.level%2?RTL:LTR}constructor(from,to,level){this.from=from,this.to=to,this.level=level}side(end,dir){return this.dir==dir==end?this.to:this.from}static find(order,index2,level,assoc){let maybe=-1;for(let i=0;i<order.length;i++){let span=order[i];if(span.from<=index2&&span.to>=index2){if(span.level==level)return i;(maybe<0||(assoc!=0?assoc<0?span.from<index2:span.to>index2:order[maybe].level>span.level))&&(maybe=i)}}if(maybe<0)throw new RangeError("Index out of range");return maybe}};__name2(_BidiSpan,"BidiSpan");let BidiSpan=_BidiSpan;function isolatesEq(a,b){if(a.length!=b.length)return!1;for(let i=0;i<a.length;i++){let iA=a[i],iB=b[i];if(iA.from!=iB.from||iA.to!=iB.to||iA.direction!=iB.direction||!isolatesEq(iA.inner,iB.inner))return!1}return!0}__name(isolatesEq,"isolatesEq"),__name2(isolatesEq,"isolatesEq");const types=[];function computeCharTypes(line,rFrom,rTo,isolates,outerType){for(let iI=0;iI<=isolates.length;iI++){let from=iI?isolates[iI-1].to:rFrom,to=iI<isolates.length?isolates[iI].from:rTo,prevType=iI?256:outerType;for(let i=from,prev=prevType,prevStrong=prevType;i<to;i++){let type=charType(line.charCodeAt(i));type==512?type=prev:type==8&&prevStrong==4&&(type=16),types[i]=type==4?2:type,type&7&&(prevStrong=type),prev=type}for(let i=from,prev=prevType,prevStrong=prevType;i<to;i++){let type=types[i];if(type==128)i<to-1&&prev==types[i+1]&&prev&24?type=types[i]=prev:types[i]=256;else if(type==64){let end=i+1;for(;end<to&&types[end]==64;)end++;let replace=i&&prev==8||end<rTo&&types[end]==8?prevStrong==1?1:8:256;for(let j=i;j<end;j++)types[j]=replace;i=end-1}else type==8&&prevStrong==1&&(types[i]=1);prev=type,type&7&&(prevStrong=type)}}}__name(computeCharTypes,"computeCharTypes"),__name2(computeCharTypes,"computeCharTypes");function processBracketPairs(line,rFrom,rTo,isolates,outerType){let oppositeType=outerType==1?2:1;for(let iI=0,sI=0,context=0;iI<=isolates.length;iI++){let from=iI?isolates[iI-1].to:rFrom,to=iI<isolates.length?isolates[iI].from:rTo;for(let i=from,ch,br,type;i<to;i++)if(br=Brackets[ch=line.charCodeAt(i)])if(br<0){for(let sJ=sI-3;sJ>=0;sJ-=3)if(BracketStack[sJ+1]==-br){let flags=BracketStack[sJ+2],type2=flags&2?outerType:flags&4?flags&1?oppositeType:outerType:0;type2&&(types[i]=types[BracketStack[sJ]]=type2),sI=sJ;break}}else{if(BracketStack.length==189)break;BracketStack[sI++]=i,BracketStack[sI++]=ch,BracketStack[sI++]=context}else if((type=types[i])==2||type==1){let embed=type==outerType;context=embed?0:1;for(let sJ=sI-3;sJ>=0;sJ-=3){let cur2=BracketStack[sJ+2];if(cur2&2)break;if(embed)BracketStack[sJ+2]|=2;else{if(cur2&4)break;BracketStack[sJ+2]|=4}}}}}__name(processBracketPairs,"processBracketPairs"),__name2(processBracketPairs,"processBracketPairs");function processNeutrals(rFrom,rTo,isolates,outerType){for(let iI=0,prev=outerType;iI<=isolates.length;iI++){let from=iI?isolates[iI-1].to:rFrom,to=iI<isolates.length?isolates[iI].from:rTo;for(let i=from;i<to;){let type=types[i];if(type==256){let end=i+1;for(;;)if(end==to){if(iI==isolates.length)break;end=isolates[iI++].to,to=iI<isolates.length?isolates[iI].from:rTo}else if(types[end]==256)end++;else break;let beforeL=prev==1,afterL=(end<rTo?types[end]:outerType)==1,replace=beforeL==afterL?beforeL?1:2:outerType;for(let j=end,jI=iI,fromJ=jI?isolates[jI-1].to:rFrom;j>i;)j==fromJ&&(j=isolates[--jI].from,fromJ=jI?isolates[jI-1].to:rFrom),types[--j]=replace;i=end}else prev=type,i++}}}__name(processNeutrals,"processNeutrals"),__name2(processNeutrals,"processNeutrals");function emitSpans(line,from,to,level,baseLevel,isolates,order){let ourType=level%2?2:1;if(level%2==baseLevel%2)for(let iCh=from,iI=0;iCh<to;){let sameDir=!0,isNum=!1;if(iI==isolates.length||iCh<isolates[iI].from){let next=types[iCh];next!=ourType&&(sameDir=!1,isNum=next==16)}let recurse2=!sameDir&&ourType==1?[]:null,localLevel=sameDir?level:level+1,iScan=iCh;run:for(;;)if(iI<isolates.length&&iScan==isolates[iI].from){if(isNum)break run;let iso=isolates[iI];if(!sameDir)for(let upto=iso.to,jI=iI+1;;){if(upto==to)break run;if(jI<isolates.length&&isolates[jI].from==upto)upto=isolates[jI++].to;else{if(types[upto]==ourType)break run;break}}if(iI++,recurse2)recurse2.push(iso);else{iso.from>iCh&&order.push(new BidiSpan(iCh,iso.from,localLevel));let dirSwap=iso.direction==LTR!=!(localLevel%2);computeSectionOrder(line,dirSwap?level+1:level,baseLevel,iso.inner,iso.from,iso.to,order),iCh=iso.to}iScan=iso.to}else{if(iScan==to||(sameDir?types[iScan]!=ourType:types[iScan]==ourType))break;iScan++}recurse2?emitSpans(line,iCh,iScan,level+1,baseLevel,recurse2,order):iCh<iScan&&order.push(new BidiSpan(iCh,iScan,localLevel)),iCh=iScan}else for(let iCh=to,iI=isolates.length;iCh>from;){let sameDir=!0,isNum=!1;if(!iI||iCh>isolates[iI-1].to){let next=types[iCh-1];next!=ourType&&(sameDir=!1,isNum=next==16)}let recurse2=!sameDir&&ourType==1?[]:null,localLevel=sameDir?level:level+1,iScan=iCh;run:for(;;)if(iI&&iScan==isolates[iI-1].to){if(isNum)break run;let iso=isolates[--iI];if(!sameDir)for(let upto=iso.from,jI=iI;;){if(upto==from)break run;if(jI&&isolates[jI-1].to==upto)upto=isolates[--jI].from;else{if(types[upto-1]==ourType)break run;break}}if(recurse2)recurse2.push(iso);else{iso.to<iCh&&order.push(new BidiSpan(iso.to,iCh,localLevel));let dirSwap=iso.direction==LTR!=!(localLevel%2);computeSectionOrder(line,dirSwap?level+1:level,baseLevel,iso.inner,iso.from,iso.to,order),iCh=iso.from}iScan=iso.from}else{if(iScan==from||(sameDir?types[iScan-1]!=ourType:types[iScan-1]==ourType))break;iScan--}recurse2?emitSpans(line,iScan,iCh,level+1,baseLevel,recurse2,order):iScan<iCh&&order.push(new BidiSpan(iScan,iCh,localLevel)),iCh=iScan}}__name(emitSpans,"emitSpans"),__name2(emitSpans,"emitSpans");function computeSectionOrder(line,level,baseLevel,isolates,from,to,order){let outerType=level%2?2:1;computeCharTypes(line,from,to,isolates,outerType),processBracketPairs(line,from,to,isolates,outerType),processNeutrals(from,to,isolates,outerType),emitSpans(line,from,to,level,baseLevel,isolates,order)}__name(computeSectionOrder,"computeSectionOrder"),__name2(computeSectionOrder,"computeSectionOrder");function computeOrder(line,direction,isolates){if(!line)return[new BidiSpan(0,0,direction==RTL?1:0)];if(direction==LTR&&!isolates.length&&!BidiRE.test(line))return trivialOrder(line.length);if(isolates.length)for(;line.length>types.length;)types[types.length]=256;let order=[],level=direction==LTR?0:1;return computeSectionOrder(line,level,level,isolates,0,line.length,order),order}__name(computeOrder,"computeOrder"),__name2(computeOrder,"computeOrder");function trivialOrder(length){return[new BidiSpan(0,length,0)]}__name(trivialOrder,"trivialOrder"),__name2(trivialOrder,"trivialOrder");let movedOver="";function moveVisually(line,order,dir,start,forward){var _a3;let startIndex=start.head-line.from,spanI=-1;if(startIndex==0){if(!forward||!line.length)return null;order[0].level!=dir&&(startIndex=order[0].side(!1,dir),spanI=0)}else if(startIndex==line.length){if(forward)return null;let last2=order[order.length-1];last2.level!=dir&&(startIndex=last2.side(!0,dir),spanI=order.length-1)}spanI<0&&(spanI=BidiSpan.find(order,startIndex,(_a3=start.bidiLevel)!==null&&_a3!==void 0?_a3:-1,start.assoc));let span=order[spanI];startIndex==span.side(forward,dir)&&(span=order[spanI+=forward?1:-1],startIndex=span.side(!forward,dir));let indexForward=forward==(span.dir==dir),nextIndex=findClusterBreak(line.text,startIndex,indexForward);if(movedOver=line.text.slice(Math.min(startIndex,nextIndex),Math.max(startIndex,nextIndex)),nextIndex!=span.side(forward,dir))return EditorSelection.cursor(nextIndex+line.from,indexForward?-1:1,span.level);let nextSpan=spanI==(forward?order.length-1:0)?null:order[spanI+(forward?1:-1)];return!nextSpan&&span.level!=dir?EditorSelection.cursor(forward?line.to:line.from,forward?-1:1,dir):nextSpan&&nextSpan.level<span.level?EditorSelection.cursor(nextSpan.side(!forward,dir)+line.from,forward?1:-1,nextSpan.level):EditorSelection.cursor(nextIndex+line.from,forward?-1:1,span.level)}__name(moveVisually,"moveVisually"),__name2(moveVisually,"moveVisually");const _DocView=class extends ContentView{static{__name(this,"_DocView")}get length(){return this.view.state.doc.length}constructor(view){super(),this.view=view,this.decorations=[],this.dynamicDecorationMap=[],this.domChanged=null,this.hasComposition=null,this.markedForComposition=new Set,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.setDOM(view.contentDOM),this.children=[new LineView],this.children[0].setParent(this),this.updateDeco(),this.updateInner([new ChangedRange(0,0,0,view.state.doc.length)],0,null)}update(update){var _a3;let changedRanges=update.changedRanges;this.minWidth>0&&changedRanges.length&&(changedRanges.every(({fromA,toA})=>toA<this.minWidthFrom||fromA>this.minWidthTo)?(this.minWidthFrom=update.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=update.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0);let readCompositionAt=-1;this.view.inputState.composing>=0&&(!((_a3=this.domChanged)===null||_a3===void 0)&&_a3.newSel?readCompositionAt=this.domChanged.newSel.head:!touchesComposition(update.changes,this.hasComposition)&&!update.selectionSet&&(readCompositionAt=update.state.selection.main.head));let composition=readCompositionAt>-1?findCompositionRange(this.view,update.changes,readCompositionAt):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();let{from,to}=this.hasComposition;changedRanges=new ChangedRange(from,to,update.changes.mapPos(from,-1),update.changes.mapPos(to,1)).addToSet(changedRanges.slice())}this.hasComposition=composition?{from:composition.range.fromB,to:composition.range.toB}:null,(browser.ie||browser.chrome)&&!composition&&update&&update.state.doc.lines!=update.startState.doc.lines&&(this.forceSelection=!0);let prevDeco=this.decorations,deco=this.updateDeco(),decoDiff=findChangedDeco(prevDeco,deco,update.changes);return changedRanges=ChangedRange.extendWithRanges(changedRanges,decoDiff),!(this.flags&7)&&changedRanges.length==0?!1:(this.updateInner(changedRanges,update.startState.doc.length,composition),update.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(changes,oldLength,composition){this.view.viewState.mustMeasureContent=!0,this.updateChildren(changes,oldLength,composition);let{observer}=this.view;observer.ignore(()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let track=browser.chrome||browser.ios?{node:observer.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,track),this.flags&=-8,track&&(track.written||observer.selectionRange.focusNode!=track.node)&&(this.forceSelection=!0),this.dom.style.height=""}),this.markedForComposition.forEach(cView=>cView.flags&=-9);let gaps=[];if(this.view.viewport.from||this.view.viewport.to<this.view.state.doc.length)for(let child of this.children)child instanceof BlockWidgetView&&child.widget instanceof BlockGapWidget&&gaps.push(child.dom);observer.updateGaps(gaps)}updateChildren(changes,oldLength,composition){let ranges=composition?composition.range.addToSet(changes.slice()):changes,cursor=this.childCursor(oldLength);for(let i=ranges.length-1;;i--){let next=i>=0?ranges[i]:null;if(!next)break;let{fromA,toA,fromB,toB}=next,content2,breakAtStart,openStart,openEnd;if(composition&&composition.range.fromB<toB&&composition.range.toB>fromB){let before=ContentBuilder.build(this.view.state.doc,fromB,composition.range.fromB,this.decorations,this.dynamicDecorationMap),after=ContentBuilder.build(this.view.state.doc,composition.range.toB,toB,this.decorations,this.dynamicDecorationMap);breakAtStart=before.breakAtStart,openStart=before.openStart,openEnd=after.openEnd;let compLine=this.compositionView(composition);after.breakAtStart?compLine.breakAfter=1:after.content.length&&compLine.merge(compLine.length,compLine.length,after.content[0],!1,after.openStart,0)&&(compLine.breakAfter=after.content[0].breakAfter,after.content.shift()),before.content.length&&compLine.merge(0,0,before.content[before.content.length-1],!0,0,before.openEnd)&&before.content.pop(),content2=before.content.concat(compLine).concat(after.content)}else({content:content2,breakAtStart,openStart,openEnd}=ContentBuilder.build(this.view.state.doc,fromB,toB,this.decorations,this.dynamicDecorationMap));let{i:toI,off:toOff}=cursor.findPos(toA,1),{i:fromI,off:fromOff}=cursor.findPos(fromA,-1);replaceRange(this,fromI,fromOff,toI,toOff,content2,breakAtStart,openStart,openEnd)}composition&&this.fixCompositionDOM(composition)}compositionView(composition){let cur2=new TextView(composition.text.nodeValue);cur2.flags|=8;for(let{deco}of composition.marks)cur2=new MarkView(deco,[cur2],cur2.length);let line=new LineView;return line.append(cur2,0),line}fixCompositionDOM(composition){let fix=__name2((dom,cView2)=>{cView2.flags|=8|(cView2.children.some(c=>c.flags&7)?1:0),this.markedForComposition.add(cView2);let prev=ContentView.get(dom);prev&&prev!=cView2&&(prev.dom=null),cView2.setDOM(dom)},"fix"),pos=this.childPos(composition.range.fromB,1),cView=this.children[pos.i];fix(composition.line,cView);for(let i=composition.marks.length-1;i>=-1;i--)pos=cView.childPos(pos.off,1),cView=cView.children[pos.i],fix(i>=0?composition.marks[i].node:composition.text,cView)}updateSelection(mustRead=!1,fromPointer=!1){(mustRead||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let activeElt=this.view.root.activeElement,focused=activeElt==this.dom,selectionNotFocus=!focused&&hasSelection(this.dom,this.view.observer.selectionRange)&&!(activeElt&&this.dom.contains(activeElt));if(!(focused||fromPointer||selectionNotFocus))return;let force=this.forceSelection;this.forceSelection=!1;let main=this.view.state.selection.main,anchor=this.moveToLine(this.domAtPos(main.anchor)),head=main.empty?anchor:this.moveToLine(this.domAtPos(main.head));if(browser.gecko&&main.empty&&!this.hasComposition&&betweenUneditable(anchor)){let dummy=document.createTextNode("");this.view.observer.ignore(()=>anchor.node.insertBefore(dummy,anchor.node.childNodes[anchor.offset]||null)),anchor=head=new DOMPos(dummy,0),force=!0}let domSel=this.view.observer.selectionRange;(force||!domSel.focusNode||!isEquivalentPosition(anchor.node,anchor.offset,domSel.anchorNode,domSel.anchorOffset)||!isEquivalentPosition(head.node,head.offset,domSel.focusNode,domSel.focusOffset))&&(this.view.observer.ignore(()=>{browser.android&&browser.chrome&&this.dom.contains(domSel.focusNode)&&inUneditable(domSel.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let rawSel=getSelection(this.view.root);if(rawSel)if(main.empty){if(browser.gecko){let nextTo=nextToUneditable(anchor.node,anchor.offset);if(nextTo&&nextTo!=3){let text=nearbyTextNode(anchor.node,anchor.offset,nextTo==1?1:-1);text&&(anchor=new DOMPos(text.node,text.offset))}}rawSel.collapse(anchor.node,anchor.offset),main.bidiLevel!=null&&rawSel.caretBidiLevel!==void 0&&(rawSel.caretBidiLevel=main.bidiLevel)}else if(rawSel.extend){rawSel.collapse(anchor.node,anchor.offset);try{rawSel.extend(head.node,head.offset)}catch{}}else{let range=document.createRange();main.anchor>main.head&&([anchor,head]=[head,anchor]),range.setEnd(head.node,head.offset),range.setStart(anchor.node,anchor.offset),rawSel.removeAllRanges(),rawSel.addRange(range)}selectionNotFocus&&this.view.root.activeElement==this.dom&&(this.dom.blur(),activeElt&&activeElt.focus())}),this.view.observer.setSelectionRange(anchor,head)),this.impreciseAnchor=anchor.precise?null:new DOMPos(domSel.anchorNode,domSel.anchorOffset),this.impreciseHead=head.precise?null:new DOMPos(domSel.focusNode,domSel.focusOffset)}enforceCursorAssoc(){if(this.hasComposition)return;let{view}=this,cursor=view.state.selection.main,sel=getSelection(view.root),{anchorNode,anchorOffset}=view.observer.selectionRange;if(!sel||!cursor.empty||!cursor.assoc||!sel.modify)return;let line=LineView.find(this,cursor.head);if(!line)return;let lineStart=line.posAtStart;if(cursor.head==lineStart||cursor.head==lineStart+line.length)return;let before=this.coordsAt(cursor.head,-1),after=this.coordsAt(cursor.head,1);if(!before||!after||before.bottom>after.top)return;let dom=this.domAtPos(cursor.head+cursor.assoc);sel.collapse(dom.node,dom.offset),sel.modify("move",cursor.assoc<0?"forward":"backward","lineboundary"),view.observer.readSelectionRange();let newRange=view.observer.selectionRange;view.docView.posFromDOM(newRange.anchorNode,newRange.anchorOffset)!=cursor.from&&sel.collapse(anchorNode,anchorOffset)}moveToLine(pos){let dom=this.dom,newPos;if(pos.node!=dom)return pos;for(let i=pos.offset;!newPos&&i<dom.childNodes.length;i++){let view=ContentView.get(dom.childNodes[i]);view instanceof LineView&&(newPos=view.domAtPos(0))}for(let i=pos.offset-1;!newPos&&i>=0;i--){let view=ContentView.get(dom.childNodes[i]);view instanceof LineView&&(newPos=view.domAtPos(view.length))}return newPos?new DOMPos(newPos.node,newPos.offset,!0):pos}nearest(dom){for(let cur2=dom;cur2;){let domView=ContentView.get(cur2);if(domView&&domView.rootView==this)return domView;cur2=cur2.parentNode}return null}posFromDOM(node,offset2){let view=this.nearest(node);if(!view)throw new RangeError("Trying to find position for a DOM position outside of the document");return view.localPosFromDOM(node,offset2)+view.posAtStart}domAtPos(pos){let{i,off:off2}=this.childCursor().findPos(pos,-1);for(;i<this.children.length-1;){let child=this.children[i];if(off2<child.length||child instanceof LineView)break;i++,off2=0}return this.children[i].domAtPos(off2)}coordsAt(pos,side){let best=null,bestPos=0;for(let off2=this.length,i=this.children.length-1;i>=0;i--){let child=this.children[i],end=off2-child.breakAfter,start=end-child.length;if(end<pos)break;start<=pos&&(start<pos||child.covers(-1))&&(end>pos||child.covers(1))&&(!best||child instanceof LineView&&!(best instanceof LineView&&side>=0))&&(best=child,bestPos=start),off2=start}return best?best.coordsAt(pos-bestPos,side):null}coordsForChar(pos){let{i,off:off2}=this.childPos(pos,1),child=this.children[i];if(!(child instanceof LineView))return null;for(;child.children.length;){let{i:i2,off:childOff}=child.childPos(off2,1);for(;;i2++){if(i2==child.children.length)return null;if((child=child.children[i2]).length)break}off2=childOff}if(!(child instanceof TextView))return null;let end=findClusterBreak(child.text,off2);if(end==off2)return null;let rects=textRange(child.dom,off2,end).getClientRects();return!rects.length||rects[0].top>=rects[0].bottom?null:rects[0]}measureVisibleLineHeights(viewport){let result=[],{from,to}=viewport,contentWidth=this.view.contentDOM.clientWidth,isWider=contentWidth>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,widest=-1,ltr=this.view.textDirection==Direction.LTR;for(let pos=0,i=0;i<this.children.length;i++){let child=this.children[i],end=pos+child.length;if(end>to)break;if(pos>=from){let childRect=child.dom.getBoundingClientRect();if(result.push(childRect.height),isWider){let last2=child.dom.lastChild,rects=last2?clientRectsFor(last2):[];if(rects.length){let rect=rects[rects.length-1],width=ltr?rect.right-childRect.left:childRect.right-rect.left;width>widest&&(widest=width,this.minWidth=contentWidth,this.minWidthFrom=pos,this.minWidthTo=end)}}}pos=end+child.breakAfter}return result}textDirectionAt(pos){let{i}=this.childPos(pos,1);return getComputedStyle(this.children[i].dom).direction=="rtl"?Direction.RTL:Direction.LTR}measureTextSize(){for(let child of this.children)if(child instanceof LineView){let measure=child.measureTextSize();if(measure)return measure}let dummy=document.createElement("div"),lineHeight,charWidth,textHeight;return dummy.className="cm-line",dummy.style.width="99999px",dummy.style.position="absolute",dummy.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.dom.appendChild(dummy);let rect=clientRectsFor(dummy.firstChild)[0];lineHeight=dummy.getBoundingClientRect().height,charWidth=rect?rect.width/27:7,textHeight=rect?rect.height:lineHeight,dummy.remove()}),{lineHeight,charWidth,textHeight}}childCursor(pos=this.length){let i=this.children.length;return i&&(pos-=this.children[--i].length),new ChildCursor(this.children,pos,i)}computeBlockGapDeco(){let deco=[],vs=this.view.viewState;for(let pos=0,i=0;;i++){let next=i==vs.viewports.length?null:vs.viewports[i],end=next?next.from-1:this.length;if(end>pos){let height=(vs.lineBlockAt(end).bottom-vs.lineBlockAt(pos).top)/this.view.scaleY;deco.push(Decoration.replace({widget:new BlockGapWidget(height),block:!0,inclusive:!0,isBlockGap:!0}).range(pos,end))}if(!next)break;pos=next.to+1}return Decoration.set(deco)}updateDeco(){let allDeco=this.view.state.facet(decorations).map((d,i)=>(this.dynamicDecorationMap[i]=typeof d=="function")?d(this.view):d);for(let i=allDeco.length;i<allDeco.length+3;i++)this.dynamicDecorationMap[i]=!1;return this.decorations=[...allDeco,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco]}scrollIntoView(target){let{range}=target,rect=this.coordsAt(range.head,range.empty?range.assoc:range.head>range.anchor?-1:1),other;if(!rect)return;!range.empty&&(other=this.coordsAt(range.anchor,range.anchor>range.head?-1:1))&&(rect={left:Math.min(rect.left,other.left),top:Math.min(rect.top,other.top),right:Math.max(rect.right,other.right),bottom:Math.max(rect.bottom,other.bottom)});let margins=getScrollMargins(this.view),targetRect={left:rect.left-margins.left,top:rect.top-margins.top,right:rect.right+margins.right,bottom:rect.bottom+margins.bottom};scrollRectIntoView(this.view.scrollDOM,targetRect,range.head<range.anchor?-1:1,target.x,target.y,target.xMargin,target.yMargin,this.view.textDirection==Direction.LTR)}};__name2(_DocView,"DocView");let DocView=_DocView;function betweenUneditable(pos){return pos.node.nodeType==1&&pos.node.firstChild&&(pos.offset==0||pos.node.childNodes[pos.offset-1].contentEditable=="false")&&(pos.offset==pos.node.childNodes.length||pos.node.childNodes[pos.offset].contentEditable=="false")}__name(betweenUneditable,"betweenUneditable"),__name2(betweenUneditable,"betweenUneditable");const _BlockGapWidget=class extends WidgetType{static{__name(this,"_BlockGapWidget")}constructor(height){super(),this.height=height}toDOM(){let elt=document.createElement("div");return this.updateDOM(elt),elt}eq(other){return other.height==this.height}updateDOM(elt){return elt.style.height=this.height+"px",!0}get estimatedHeight(){return this.height}};__name2(_BlockGapWidget,"BlockGapWidget");let BlockGapWidget=_BlockGapWidget;function findCompositionNode(view,headPos){let sel=view.observer.selectionRange,textNode=sel.focusNode&&nearbyTextNode(sel.focusNode,sel.focusOffset,0);if(!textNode)return null;let from=headPos-textNode.offset;return{from,to:from+textNode.node.nodeValue.length,node:textNode.node}}__name(findCompositionNode,"findCompositionNode"),__name2(findCompositionNode,"findCompositionNode");function findCompositionRange(view,changes,headPos){let found=findCompositionNode(view,headPos);if(!found)return null;let{node:textNode,from,to}=found,text=textNode.nodeValue;if(/[\n\r]/.test(text)||view.state.doc.sliceString(found.from,found.to)!=text)return null;let inv=changes.invertedDesc,range=new ChangedRange(inv.mapPos(from),inv.mapPos(to),from,to),marks=[];for(let parent=textNode.parentNode;;parent=parent.parentNode){let parentView=ContentView.get(parent);if(parentView instanceof MarkView)marks.push({node:parent,deco:parentView.mark});else{if(parentView instanceof LineView||parent.nodeName=="DIV"&&parent.parentNode==view.contentDOM)return{range,text:textNode,marks,line:parent};if(parent!=view.contentDOM)marks.push({node:parent,deco:new MarkDecoration({inclusive:!0,attributes:getAttrs(parent),tagName:parent.tagName.toLowerCase()})});else return null}}}__name(findCompositionRange,"findCompositionRange"),__name2(findCompositionRange,"findCompositionRange");function nearbyTextNode(startNode,startOffset,side){if(side<=0)for(let node=startNode,offset2=startOffset;;){if(node.nodeType==3)return{node,offset:offset2};if(node.nodeType==1&&offset2>0)node=node.childNodes[offset2-1],offset2=maxOffset(node);else break}if(side>=0)for(let node=startNode,offset2=startOffset;;){if(node.nodeType==3)return{node,offset:offset2};if(node.nodeType==1&&offset2<node.childNodes.length&&side>=0)node=node.childNodes[offset2],offset2=0;else break}return null}__name(nearbyTextNode,"nearbyTextNode"),__name2(nearbyTextNode,"nearbyTextNode");function nextToUneditable(node,offset2){return node.nodeType!=1?0:(offset2&&node.childNodes[offset2-1].contentEditable=="false"?1:0)|(offset2<node.childNodes.length&&node.childNodes[offset2].contentEditable=="false"?2:0)}__name(nextToUneditable,"nextToUneditable"),__name2(nextToUneditable,"nextToUneditable");let DecorationComparator$1=(_b=class{static{__name(this,"_b")}constructor(){this.changes=[]}compareRange(from,to){addRange(from,to,this.changes)}comparePoint(from,to){addRange(from,to,this.changes)}},__name2(_b,"DecorationComparator"),_b);function findChangedDeco(a,b,diff2){let comp=new DecorationComparator$1;return RangeSet.compare(a,b,diff2,comp),comp.changes}__name(findChangedDeco,"findChangedDeco"),__name2(findChangedDeco,"findChangedDeco");function inUneditable(node,inside2){for(let cur2=node;cur2&&cur2!=inside2;cur2=cur2.assignedSlot||cur2.parentNode)if(cur2.nodeType==1&&cur2.contentEditable=="false")return!0;return!1}__name(inUneditable,"inUneditable"),__name2(inUneditable,"inUneditable");function touchesComposition(changes,composition){let touched=!1;return composition&&changes.iterChangedRanges((from,to)=>{from<composition.to&&to>composition.from&&(touched=!0)}),touched}__name(touchesComposition,"touchesComposition"),__name2(touchesComposition,"touchesComposition");function groupAt(state,pos,bias=1){let categorize=state.charCategorizer(pos),line=state.doc.lineAt(pos),linePos=pos-line.from;if(line.length==0)return EditorSelection.cursor(pos);linePos==0?bias=1:linePos==line.length&&(bias=-1);let from=linePos,to=linePos;bias<0?from=findClusterBreak(line.text,linePos,!1):to=findClusterBreak(line.text,linePos);let cat=categorize(line.text.slice(from,to));for(;from>0;){let prev=findClusterBreak(line.text,from,!1);if(categorize(line.text.slice(prev,from))!=cat)break;from=prev}for(;to<line.length;){let next=findClusterBreak(line.text,to);if(categorize(line.text.slice(to,next))!=cat)break;to=next}return EditorSelection.range(from+line.from,to+line.from)}__name(groupAt,"groupAt"),__name2(groupAt,"groupAt");function getdx(x,rect){return rect.left>x?rect.left-x:Math.max(0,x-rect.right)}__name(getdx,"getdx"),__name2(getdx,"getdx");function getdy(y,rect){return rect.top>y?rect.top-y:Math.max(0,y-rect.bottom)}__name(getdy,"getdy"),__name2(getdy,"getdy");function yOverlap(a,b){return a.top<b.bottom-1&&a.bottom>b.top+1}__name(yOverlap,"yOverlap"),__name2(yOverlap,"yOverlap");function upTop(rect,top2){return top2<rect.top?{top:top2,left:rect.left,right:rect.right,bottom:rect.bottom}:rect}__name(upTop,"upTop"),__name2(upTop,"upTop");function upBot(rect,bottom){return bottom>rect.bottom?{top:rect.top,left:rect.left,right:rect.right,bottom}:rect}__name(upBot,"upBot"),__name2(upBot,"upBot");function domPosAtCoords(parent,x,y){let closest2,closestRect,closestX,closestY,closestOverlap=!1,above,below,aboveRect,belowRect;for(let child=parent.firstChild;child;child=child.nextSibling){let rects=clientRectsFor(child);for(let i=0;i<rects.length;i++){let rect=rects[i];closestRect&&yOverlap(closestRect,rect)&&(rect=upTop(upBot(rect,closestRect.bottom),closestRect.top));let dx=getdx(x,rect),dy=getdy(y,rect);if(dx==0&&dy==0)return child.nodeType==3?domPosInText(child,x,y):domPosAtCoords(child,x,y);if(!closest2||closestY>dy||closestY==dy&&closestX>dx){closest2=child,closestRect=rect,closestX=dx,closestY=dy;let side=dy?y<rect.top?-1:1:dx?x<rect.left?-1:1:0;closestOverlap=!side||(side>0?i<rects.length-1:i>0)}dx==0?y>rect.bottom&&(!aboveRect||aboveRect.bottom<rect.bottom)?(above=child,aboveRect=rect):y<rect.top&&(!belowRect||belowRect.top>rect.top)&&(below=child,belowRect=rect):aboveRect&&yOverlap(aboveRect,rect)?aboveRect=upBot(aboveRect,rect.bottom):belowRect&&yOverlap(belowRect,rect)&&(belowRect=upTop(belowRect,rect.top))}}if(aboveRect&&aboveRect.bottom>=y?(closest2=above,closestRect=aboveRect):belowRect&&belowRect.top<=y&&(closest2=below,closestRect=belowRect),!closest2)return{node:parent,offset:0};let clipX=Math.max(closestRect.left,Math.min(closestRect.right,x));if(closest2.nodeType==3)return domPosInText(closest2,clipX,y);if(closestOverlap&&closest2.contentEditable!="false")return domPosAtCoords(closest2,clipX,y);let offset2=Array.prototype.indexOf.call(parent.childNodes,closest2)+(x>=(closestRect.left+closestRect.right)/2?1:0);return{node:parent,offset:offset2}}__name(domPosAtCoords,"domPosAtCoords"),__name2(domPosAtCoords,"domPosAtCoords");function domPosInText(node,x,y){let len=node.nodeValue.length,closestOffset=-1,closestDY=1e9,generalSide=0;for(let i=0;i<len;i++){let rects=textRange(node,i,i+1).getClientRects();for(let j=0;j<rects.length;j++){let rect=rects[j];if(rect.top==rect.bottom)continue;generalSide||(generalSide=x-rect.left);let dy=(rect.top>y?rect.top-y:y-rect.bottom)-1;if(rect.left-1<=x&&rect.right+1>=x&&dy<closestDY){let right=x>=(rect.left+rect.right)/2,after=right;if((browser.chrome||browser.gecko)&&textRange(node,i).getBoundingClientRect().left==rect.right&&(after=!right),dy<=0)return{node,offset:i+(after?1:0)};closestOffset=i+(after?1:0),closestDY=dy}}}return{node,offset:closestOffset>-1?closestOffset:generalSide>0?node.nodeValue.length:0}}__name(domPosInText,"domPosInText"),__name2(domPosInText,"domPosInText");function posAtCoords(view,coords,precise,bias=-1){var _a3,_b2;let content2=view.contentDOM.getBoundingClientRect(),docTop=content2.top+view.viewState.paddingTop,block,{docHeight}=view.viewState,{x,y}=coords,yOffset=y-docTop;if(yOffset<0)return 0;if(yOffset>docHeight)return view.state.doc.length;for(let halfLine=view.viewState.heightOracle.textHeight/2,bounced=!1;block=view.elementAtHeight(yOffset),block.type!=BlockType.Text;)for(;yOffset=bias>0?block.bottom+halfLine:block.top-halfLine,!(yOffset>=0&&yOffset<=docHeight);){if(bounced)return precise?null:0;bounced=!0,bias=-bias}y=docTop+yOffset;let lineStart=block.from;if(lineStart<view.viewport.from)return view.viewport.from==0?0:precise?null:posAtCoordsImprecise(view,content2,block,x,y);if(lineStart>view.viewport.to)return view.viewport.to==view.state.doc.length?view.state.doc.length:precise?null:posAtCoordsImprecise(view,content2,block,x,y);let doc2=view.dom.ownerDocument,root=view.root.elementFromPoint?view.root:doc2,element=root.elementFromPoint(x,y);element&&!view.contentDOM.contains(element)&&(element=null),element||(x=Math.max(content2.left+1,Math.min(content2.right-1,x)),element=root.elementFromPoint(x,y),element&&!view.contentDOM.contains(element)&&(element=null));let node,offset2=-1;if(element&&((_a3=view.docView.nearest(element))===null||_a3===void 0?void 0:_a3.isEditable)!=!1){if(doc2.caretPositionFromPoint){let pos=doc2.caretPositionFromPoint(x,y);pos&&({offsetNode:node,offset:offset2}=pos)}else if(doc2.caretRangeFromPoint){let range=doc2.caretRangeFromPoint(x,y);range&&({startContainer:node,startOffset:offset2}=range,(!view.contentDOM.contains(node)||browser.safari&&isSuspiciousSafariCaretResult(node,offset2,x)||browser.chrome&&isSuspiciousChromeCaretResult(node,offset2,x))&&(node=void 0))}}if(!node||!view.docView.dom.contains(node)){let line=LineView.find(view.docView,lineStart);if(!line)return yOffset>block.top+block.height/2?block.to:block.from;({node,offset:offset2}=domPosAtCoords(line.dom,x,y))}let nearest=view.docView.nearest(node);if(!nearest)return null;if(nearest.isWidget&&((_b2=nearest.dom)===null||_b2===void 0?void 0:_b2.nodeType)==1){let rect=nearest.dom.getBoundingClientRect();return coords.y<rect.top||coords.y<=rect.bottom&&coords.x<=(rect.left+rect.right)/2?nearest.posAtStart:nearest.posAtEnd}else return nearest.localPosFromDOM(node,offset2)+nearest.posAtStart}__name(posAtCoords,"posAtCoords"),__name2(posAtCoords,"posAtCoords");function posAtCoordsImprecise(view,contentRect,block,x,y){let into=Math.round((x-contentRect.left)*view.defaultCharacterWidth);if(view.lineWrapping&&block.height>view.defaultLineHeight*1.5){let textHeight=view.viewState.heightOracle.textHeight,line=Math.floor((y-block.top-(view.defaultLineHeight-textHeight)*.5)/textHeight);into+=line*view.viewState.heightOracle.lineLength}let content2=view.state.sliceDoc(block.from,block.to);return block.from+findColumn(content2,into,view.state.tabSize)}__name(posAtCoordsImprecise,"posAtCoordsImprecise"),__name2(posAtCoordsImprecise,"posAtCoordsImprecise");function isSuspiciousSafariCaretResult(node,offset2,x){let len;if(node.nodeType!=3||offset2!=(len=node.nodeValue.length))return!1;for(let next=node.nextSibling;next;next=next.nextSibling)if(next.nodeType!=1||next.nodeName!="BR")return!1;return textRange(node,len-1,len).getBoundingClientRect().left>x}__name(isSuspiciousSafariCaretResult,"isSuspiciousSafariCaretResult"),__name2(isSuspiciousSafariCaretResult,"isSuspiciousSafariCaretResult");function isSuspiciousChromeCaretResult(node,offset2,x){if(offset2!=0)return!1;for(let cur2=node;;){let parent=cur2.parentNode;if(!parent||parent.nodeType!=1||parent.firstChild!=cur2)return!1;if(parent.classList.contains("cm-line"))break;cur2=parent}let rect=node.nodeType==1?node.getBoundingClientRect():textRange(node,0,Math.max(node.nodeValue.length,1)).getBoundingClientRect();return x-rect.left>5}__name(isSuspiciousChromeCaretResult,"isSuspiciousChromeCaretResult"),__name2(isSuspiciousChromeCaretResult,"isSuspiciousChromeCaretResult");function blockAt(view,pos){let line=view.lineBlockAt(pos);if(Array.isArray(line.type)){for(let l2 of line.type)if(l2.to>pos||l2.to==pos&&(l2.to==line.to||l2.type==BlockType.Text))return l2}return line}__name(blockAt,"blockAt"),__name2(blockAt,"blockAt");function moveToLineBoundary(view,start,forward,includeWrap){let line=blockAt(view,start.head),coords=!includeWrap||line.type!=BlockType.Text||!(view.lineWrapping||line.widgetLineBreaks)?null:view.coordsAtPos(start.assoc<0&&start.head>line.from?start.head-1:start.head);if(coords){let editorRect=view.dom.getBoundingClientRect(),direction=view.textDirectionAt(line.from),pos=view.posAtCoords({x:forward==(direction==Direction.LTR)?editorRect.right-1:editorRect.left+1,y:(coords.top+coords.bottom)/2});if(pos!=null)return EditorSelection.cursor(pos,forward?-1:1)}return EditorSelection.cursor(forward?line.to:line.from,forward?-1:1)}__name(moveToLineBoundary,"moveToLineBoundary"),__name2(moveToLineBoundary,"moveToLineBoundary");function moveByChar(view,start,forward,by){let line=view.state.doc.lineAt(start.head),spans=view.bidiSpans(line),direction=view.textDirectionAt(line.from);for(let cur2=start,check=null;;){let next=moveVisually(line,spans,direction,cur2,forward),char=movedOver;if(!next){if(line.number==(forward?view.state.doc.lines:1))return cur2;char=`
`,line=view.state.doc.line(line.number+(forward?1:-1)),spans=view.bidiSpans(line),next=EditorSelection.cursor(forward?line.from:line.to)}if(check){if(!check(char))return cur2}else{if(!by)return next;check=by(char)}cur2=next}}__name(moveByChar,"moveByChar"),__name2(moveByChar,"moveByChar");function byGroup(view,pos,start){let categorize=view.state.charCategorizer(pos),cat=categorize(start);return next=>{let nextCat=categorize(next);return cat==CharCategory.Space&&(cat=nextCat),cat==nextCat}}__name(byGroup,"byGroup"),__name2(byGroup,"byGroup");function moveVertically(view,start,forward,distance){let startPos=start.head,dir=forward?1:-1;if(startPos==(forward?view.state.doc.length:0))return EditorSelection.cursor(startPos,start.assoc);let goal=start.goalColumn,startY,rect=view.contentDOM.getBoundingClientRect(),startCoords=view.coordsAtPos(startPos,start.assoc||-1),docTop=view.documentTop;if(startCoords)goal==null&&(goal=startCoords.left-rect.left),startY=dir<0?startCoords.top:startCoords.bottom;else{let line=view.viewState.lineBlockAt(startPos);goal==null&&(goal=Math.min(rect.right-rect.left,view.defaultCharacterWidth*(startPos-line.from))),startY=(dir<0?line.top:line.bottom)+docTop}let resolvedGoal=rect.left+goal,dist2=distance??view.viewState.heightOracle.textHeight>>1;for(let extra=0;;extra+=10){let curY=startY+(dist2+extra)*dir,pos=posAtCoords(view,{x:resolvedGoal,y:curY},!1,dir);if(curY<rect.top||curY>rect.bottom||(dir<0?pos<startPos:pos>startPos)){let charRect=view.docView.coordsForChar(pos),assoc=!charRect||curY<charRect.top?-1:1;return EditorSelection.cursor(pos,assoc,void 0,goal)}}}__name(moveVertically,"moveVertically"),__name2(moveVertically,"moveVertically");function skipAtomicRanges(atoms,pos,bias){for(;;){let moved2=0;for(let set of atoms)set.between(pos-1,pos+1,(from,to,value)=>{if(pos>from&&pos<to){let side=moved2||bias||(pos-from<to-pos?-1:1);pos=side<0?from:to,moved2=side}});if(!moved2)return pos}}__name(skipAtomicRanges,"skipAtomicRanges"),__name2(skipAtomicRanges,"skipAtomicRanges");function skipAtoms(view,oldPos,pos){let newPos=skipAtomicRanges(view.state.facet(atomicRanges).map(f2=>f2(view)),pos.from,oldPos.head>pos.from?-1:1);return newPos==pos.from?pos:EditorSelection.cursor(newPos,newPos<pos.from?1:-1)}__name(skipAtoms,"skipAtoms"),__name2(skipAtoms,"skipAtoms");const _InputState=class{static{__name(this,"_InputState")}setSelectionOrigin(origin){this.lastSelectionOrigin=origin,this.lastSelectionTime=Date.now()}constructor(view){this.view=view,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.pendingIOSKey=void 0,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastEscPress=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.mouseSelection=null,this.handleEvent=this.handleEvent.bind(this),view.scrollDOM.addEventListener("mousedown",event=>{if(event.target==view.scrollDOM&&event.clientY>view.contentDOM.getBoundingClientRect().bottom&&(this.runHandlers("mousedown",event),!event.defaultPrevented&&event.button==2)){let start=view.contentDOM.style.minHeight;view.contentDOM.style.minHeight="100%",setTimeout(()=>view.contentDOM.style.minHeight=start,200)}}),view.scrollDOM.addEventListener("drop",event=>{event.target==view.scrollDOM&&event.clientY>view.contentDOM.getBoundingClientRect().bottom&&this.runHandlers("drop",event)}),this.notifiedFocused=view.hasFocus,browser.safari&&view.contentDOM.addEventListener("input",()=>null),browser.gecko&&firefoxCopyCutHack(view.contentDOM.ownerDocument)}handleEvent(event){!eventBelongsToEditor(this.view,event)||this.ignoreDuringComposition(event)||event.type=="keydown"&&this.keydown(event)||this.runHandlers(event.type,event)}runHandlers(type,event){let handlers2=this.handlers[type];if(handlers2){for(let observer of handlers2.observers)observer(this.view,event);for(let handler of handlers2.handlers){if(event.defaultPrevented)break;if(handler(this.view,event)){event.preventDefault();break}}}}ensureHandlers(plugins2){let handlers2=computeHandlers(plugins2),prev=this.handlers,dom=this.view.contentDOM;for(let type in handlers2)if(type!="scroll"){let passive=!handlers2[type].handlers.length,exists=prev[type];exists&&passive!=!exists.handlers.length&&(dom.removeEventListener(type,this.handleEvent),exists=null),exists||dom.addEventListener(type,this.handleEvent,{passive})}for(let type in prev)type!="scroll"&&!handlers2[type]&&dom.removeEventListener(type,this.handleEvent);this.handlers=handlers2}keydown(event){if(this.lastKeyCode=event.keyCode,this.lastKeyTime=Date.now(),event.keyCode==9&&Date.now()<this.lastEscPress+2e3)return!0;if(event.keyCode!=27&&modifierCodes.indexOf(event.keyCode)<0&&(this.view.inputState.lastEscPress=0),browser.android&&browser.chrome&&!event.synthetic&&(event.keyCode==13||event.keyCode==8))return this.view.observer.delayAndroidKey(event.key,event.keyCode),!0;let pending;return browser.ios&&!event.synthetic&&!event.altKey&&!event.metaKey&&((pending=PendingKeys.find(key=>key.keyCode==event.keyCode))&&!event.ctrlKey||EmacsyPendingKeys.indexOf(event.key)>-1&&event.ctrlKey&&!event.shiftKey)?(this.pendingIOSKey=pending||event,setTimeout(()=>this.flushIOSKey(),250),!0):(event.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(){let key=this.pendingIOSKey;return key?(this.pendingIOSKey=void 0,dispatchKey(this.view.contentDOM,key.key,key.keyCode)):!1}ignoreDuringComposition(event){return/^key/.test(event.type)?this.composing>0?!0:browser.safari&&!browser.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1:!1}startMouseSelection(mouseSelection){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=mouseSelection}update(update){this.mouseSelection&&this.mouseSelection.update(update),update.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};__name2(_InputState,"InputState");let InputState=_InputState;function bindHandler(plugin,handler){return(view,event)=>{try{return handler.call(plugin,event,view)}catch(e){logException(view.state,e)}}}__name(bindHandler,"bindHandler"),__name2(bindHandler,"bindHandler");function computeHandlers(plugins2){let result=Object.create(null);function record(type){return result[type]||(result[type]={observers:[],handlers:[]})}__name(record,"record"),__name2(record,"record");for(let plugin of plugins2){let spec=plugin.spec;if(spec&&spec.domEventHandlers)for(let type in spec.domEventHandlers){let f2=spec.domEventHandlers[type];f2&&record(type).handlers.push(bindHandler(plugin.value,f2))}if(spec&&spec.domEventObservers)for(let type in spec.domEventObservers){let f2=spec.domEventObservers[type];f2&&record(type).observers.push(bindHandler(plugin.value,f2))}}for(let type in handlers)record(type).handlers.push(handlers[type]);for(let type in observers)record(type).observers.push(observers[type]);return result}__name(computeHandlers,"computeHandlers"),__name2(computeHandlers,"computeHandlers");const PendingKeys=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],EmacsyPendingKeys="dthko",modifierCodes=[16,17,18,20,91,92,224,225],dragScrollMargin=6;function dragScrollSpeed(dist2){return Math.max(0,dist2)*.7+8}__name(dragScrollSpeed,"dragScrollSpeed"),__name2(dragScrollSpeed,"dragScrollSpeed");function dist(a,b){return Math.max(Math.abs(a.clientX-b.clientX),Math.abs(a.clientY-b.clientY))}__name(dist,"dist"),__name2(dist,"dist");const _MouseSelection=class{static{__name(this,"_MouseSelection")}constructor(view,startEvent,style,mustSelect){this.view=view,this.startEvent=startEvent,this.style=style,this.mustSelect=mustSelect,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=startEvent,this.scrollParent=scrollableParent(view.contentDOM),this.atoms=view.state.facet(atomicRanges).map(f2=>f2(view));let doc2=view.contentDOM.ownerDocument;doc2.addEventListener("mousemove",this.move=this.move.bind(this)),doc2.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=startEvent.shiftKey,this.multiple=view.state.facet(EditorState.allowMultipleSelections)&&addsSelectionRange(view,startEvent),this.dragging=isInPrimarySelection(view,startEvent)&&getClickType(startEvent)==1?null:!1}start(event){this.dragging===!1&&this.select(event)}move(event){var _a3;if(event.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&dist(this.startEvent,event)<10)return;this.select(this.lastEvent=event);let sx=0,sy=0,rect=((_a3=this.scrollParent)===null||_a3===void 0?void 0:_a3.getBoundingClientRect())||{left:0,top:0,right:this.view.win.innerWidth,bottom:this.view.win.innerHeight},margins=getScrollMargins(this.view);event.clientX-margins.left<=rect.left+dragScrollMargin?sx=-dragScrollSpeed(rect.left-event.clientX):event.clientX+margins.right>=rect.right-dragScrollMargin&&(sx=dragScrollSpeed(event.clientX-rect.right)),event.clientY-margins.top<=rect.top+dragScrollMargin?sy=-dragScrollSpeed(rect.top-event.clientY):event.clientY+margins.bottom>=rect.bottom-dragScrollMargin&&(sy=dragScrollSpeed(event.clientY-rect.bottom)),this.setScrollSpeed(sx,sy)}up(event){this.dragging==null&&this.select(this.lastEvent),this.dragging||event.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let doc2=this.view.contentDOM.ownerDocument;doc2.removeEventListener("mousemove",this.move),doc2.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=null}setScrollSpeed(sx,sy){this.scrollSpeed={x:sx,y:sy},sx||sy?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){this.scrollParent?(this.scrollParent.scrollLeft+=this.scrollSpeed.x,this.scrollParent.scrollTop+=this.scrollSpeed.y):this.view.win.scrollBy(this.scrollSpeed.x,this.scrollSpeed.y),this.dragging===!1&&this.select(this.lastEvent)}skipAtoms(sel){let ranges=null;for(let i=0;i<sel.ranges.length;i++){let range=sel.ranges[i],updated=null;if(range.empty){let pos=skipAtomicRanges(this.atoms,range.from,0);pos!=range.from&&(updated=EditorSelection.cursor(pos,-1))}else{let from=skipAtomicRanges(this.atoms,range.from,-1),to=skipAtomicRanges(this.atoms,range.to,1);(from!=range.from||to!=range.to)&&(updated=EditorSelection.range(range.from==range.anchor?from:to,range.from==range.head?from:to))}updated&&(ranges||(ranges=sel.ranges.slice()),ranges[i]=updated)}return ranges?EditorSelection.create(ranges,sel.mainIndex):sel}select(event){let{view}=this,selection=this.skipAtoms(this.style.get(event,this.extend,this.multiple));(this.mustSelect||!selection.eq(view.state.selection)||selection.main.assoc!=view.state.selection.main.assoc&&this.dragging===!1)&&this.view.dispatch({selection,userEvent:"select.pointer"}),this.mustSelect=!1}update(update){update.docChanged&&this.dragging&&(this.dragging=this.dragging.map(update.changes)),this.style.update(update)&&setTimeout(()=>this.select(this.lastEvent),20)}};__name2(_MouseSelection,"MouseSelection");let MouseSelection=_MouseSelection;function addsSelectionRange(view,event){let facet=view.state.facet(clickAddsSelectionRange);return facet.length?facet[0](event):browser.mac?event.metaKey:event.ctrlKey}__name(addsSelectionRange,"addsSelectionRange"),__name2(addsSelectionRange,"addsSelectionRange");function dragMovesSelection(view,event){let facet=view.state.facet(dragMovesSelection$1);return facet.length?facet[0](event):browser.mac?!event.altKey:!event.ctrlKey}__name(dragMovesSelection,"dragMovesSelection"),__name2(dragMovesSelection,"dragMovesSelection");function isInPrimarySelection(view,event){let{main}=view.state.selection;if(main.empty)return!1;let sel=getSelection(view.root);if(!sel||sel.rangeCount==0)return!0;let rects=sel.getRangeAt(0).getClientRects();for(let i=0;i<rects.length;i++){let rect=rects[i];if(rect.left<=event.clientX&&rect.right>=event.clientX&&rect.top<=event.clientY&&rect.bottom>=event.clientY)return!0}return!1}__name(isInPrimarySelection,"isInPrimarySelection"),__name2(isInPrimarySelection,"isInPrimarySelection");function eventBelongsToEditor(view,event){if(!event.bubbles)return!0;if(event.defaultPrevented)return!1;for(let node=event.target,cView;node!=view.contentDOM;node=node.parentNode)if(!node||node.nodeType==11||(cView=ContentView.get(node))&&cView.ignoreEvent(event))return!1;return!0}__name(eventBelongsToEditor,"eventBelongsToEditor"),__name2(eventBelongsToEditor,"eventBelongsToEditor");const handlers=Object.create(null),observers=Object.create(null),brokenClipboardAPI=browser.ie&&browser.ie_version<15||browser.ios&&browser.webkit_version<604;function capturePaste(view){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px",target.focus(),setTimeout(()=>{view.focus(),target.remove(),doPaste(view,target.value)},50)}__name(capturePaste,"capturePaste"),__name2(capturePaste,"capturePaste");function doPaste(view,input){let{state}=view,changes,i=1,text=state.toText(input),byLine=text.lines==state.selection.ranges.length;if(lastLinewiseCopy!=null&&state.selection.ranges.every(r=>r.empty)&&lastLinewiseCopy==text.toString()){let lastLine=-1;changes=state.changeByRange(range=>{let line=state.doc.lineAt(range.from);if(line.from==lastLine)return{range};lastLine=line.from;let insert2=state.toText((byLine?text.line(i++).text:input)+state.lineBreak);return{changes:{from:line.from,insert:insert2},range:EditorSelection.cursor(range.from+insert2.length)}})}else byLine?changes=state.changeByRange(range=>{let line=text.line(i++);return{changes:{from:range.from,to:range.to,insert:line.text},range:EditorSelection.cursor(range.from+line.length)}}):changes=state.replaceSelection(text);view.dispatch(changes,{userEvent:"input.paste",scrollIntoView:!0})}__name(doPaste,"doPaste"),__name2(doPaste,"doPaste"),observers.scroll=view=>{view.inputState.lastScrollTop=view.scrollDOM.scrollTop,view.inputState.lastScrollLeft=view.scrollDOM.scrollLeft},handlers.keydown=(view,event)=>(view.inputState.setSelectionOrigin("select"),event.keyCode==27&&(view.inputState.lastEscPress=Date.now()),!1),observers.touchstart=(view,e)=>{view.inputState.lastTouchTime=Date.now(),view.inputState.setSelectionOrigin("select.pointer")},observers.touchmove=view=>{view.inputState.setSelectionOrigin("select.pointer")},handlers.mousedown=(view,event)=>{if(view.observer.flush(),view.inputState.lastTouchTime>Date.now()-2e3)return!1;let style=null;for(let makeStyle of view.state.facet(mouseSelectionStyle))if(style=makeStyle(view,event),style)break;if(!style&&event.button==0&&(style=basicMouseSelection(view,event)),style){let mustFocus=!view.hasFocus;view.inputState.startMouseSelection(new MouseSelection(view,event,style,mustFocus)),mustFocus&&view.observer.ignore(()=>focusPreventScroll(view.contentDOM));let mouseSel=view.inputState.mouseSelection;if(mouseSel)return mouseSel.start(event),!mouseSel.dragging}return!1};function rangeForClick(view,pos,bias,type){if(type==1)return EditorSelection.cursor(pos,bias);if(type==2)return groupAt(view.state,pos,bias);{let visual=LineView.find(view.docView,pos),line=view.state.doc.lineAt(visual?visual.posAtEnd:pos),from=visual?visual.posAtStart:line.from,to=visual?visual.posAtEnd:line.to;return to<view.state.doc.length&&to==line.to&&to++,EditorSelection.range(from,to)}}__name(rangeForClick,"rangeForClick"),__name2(rangeForClick,"rangeForClick");let insideY=__name2((y,rect)=>y>=rect.top&&y<=rect.bottom,"insideY"),inside=__name2((x,y,rect)=>insideY(y,rect)&&x>=rect.left&&x<=rect.right,"inside");function findPositionSide(view,pos,x,y){let line=LineView.find(view.docView,pos);if(!line)return 1;let off2=pos-line.posAtStart;if(off2==0)return 1;if(off2==line.length)return-1;let before=line.coordsAt(off2,-1);if(before&&inside(x,y,before))return-1;let after=line.coordsAt(off2,1);return after&&inside(x,y,after)?1:before&&insideY(y,before)?-1:1}__name(findPositionSide,"findPositionSide"),__name2(findPositionSide,"findPositionSide");function queryPos(view,event){let pos=view.posAtCoords({x:event.clientX,y:event.clientY},!1);return{pos,bias:findPositionSide(view,pos,event.clientX,event.clientY)}}__name(queryPos,"queryPos"),__name2(queryPos,"queryPos");const BadMouseDetail=browser.ie&&browser.ie_version<=11;let lastMouseDown=null,lastMouseDownCount=0,lastMouseDownTime=0;function getClickType(event){if(!BadMouseDetail)return event.detail;let last2=lastMouseDown,lastTime=lastMouseDownTime;return lastMouseDown=event,lastMouseDownTime=Date.now(),lastMouseDownCount=!last2||lastTime>Date.now()-400&&Math.abs(last2.clientX-event.clientX)<2&&Math.abs(last2.clientY-event.clientY)<2?(lastMouseDownCount+1)%3:1}__name(getClickType,"getClickType"),__name2(getClickType,"getClickType");function basicMouseSelection(view,event){let start=queryPos(view,event),type=getClickType(event),startSel=view.state.selection;return{update(update){update.docChanged&&(start.pos=update.changes.mapPos(start.pos),startSel=startSel.map(update.changes))},get(event2,extend2,multiple){let cur2=queryPos(view,event2),removed,range=rangeForClick(view,cur2.pos,cur2.bias,type);if(start.pos!=cur2.pos&&!extend2){let startRange=rangeForClick(view,start.pos,start.bias,type),from=Math.min(startRange.from,range.from),to=Math.max(startRange.to,range.to);range=from<range.from?EditorSelection.range(from,to):EditorSelection.range(to,from)}return extend2?startSel.replaceRange(startSel.main.extend(range.from,range.to)):multiple&&type==1&&startSel.ranges.length>1&&(removed=removeRangeAround(startSel,cur2.pos))?removed:multiple?startSel.addRange(range):EditorSelection.create([range])}}}__name(basicMouseSelection,"basicMouseSelection"),__name2(basicMouseSelection,"basicMouseSelection");function removeRangeAround(sel,pos){for(let i=0;i<sel.ranges.length;i++){let{from,to}=sel.ranges[i];if(from<=pos&&to>=pos)return EditorSelection.create(sel.ranges.slice(0,i).concat(sel.ranges.slice(i+1)),sel.mainIndex==i?0:sel.mainIndex-(sel.mainIndex>i?1:0))}return null}__name(removeRangeAround,"removeRangeAround"),__name2(removeRangeAround,"removeRangeAround"),handlers.dragstart=(view,event)=>{let{selection:{main}}=view.state,{mouseSelection}=view.inputState;return mouseSelection&&(mouseSelection.dragging=main),event.dataTransfer&&(event.dataTransfer.setData("Text",view.state.sliceDoc(main.from,main.to)),event.dataTransfer.effectAllowed="copyMove"),!1};function dropText(view,event,text,direct){if(!text)return;let dropPos=view.posAtCoords({x:event.clientX,y:event.clientY},!1),{mouseSelection}=view.inputState,del=direct&&mouseSelection&&mouseSelection.dragging&&dragMovesSelection(view,event)?{from:mouseSelection.dragging.from,to:mouseSelection.dragging.to}:null,ins={from:dropPos,insert:text},changes=view.state.changes(del?[del,ins]:ins);view.focus(),view.dispatch({changes,selection:{anchor:changes.mapPos(dropPos,-1),head:changes.mapPos(dropPos,1)},userEvent:del?"move.drop":"input.drop"})}__name(dropText,"dropText"),__name2(dropText,"dropText"),handlers.drop=(view,event)=>{if(!event.dataTransfer)return!1;if(view.state.readOnly)return!0;let files=event.dataTransfer.files;if(files&&files.length){let text=Array(files.length),read=0,finishFile=__name2(()=>{++read==files.length&&dropText(view,event,text.filter(s2=>s2!=null).join(view.state.lineBreak),!1)},"finishFile");for(let i=0;i<files.length;i++){let reader=new FileReader;reader.onerror=finishFile,reader.onload=()=>{/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)||(text[i]=reader.result),finishFile()},reader.readAsText(files[i])}return!0}else{let text=event.dataTransfer.getData("Text");if(text)return dropText(view,event,text,!0),!0}return!1},handlers.paste=(view,event)=>{if(view.state.readOnly)return!0;view.observer.flush();let data=brokenClipboardAPI?null:event.clipboardData;return data?(doPaste(view,data.getData("text/plain")||data.getData("text/uri-text")),!0):(capturePaste(view),!1)};function captureCopy(view,text){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px",target.value=text,target.focus(),target.selectionEnd=text.length,target.selectionStart=0,setTimeout(()=>{target.remove(),view.focus()},50)}__name(captureCopy,"captureCopy"),__name2(captureCopy,"captureCopy");function copiedRange(state){let content2=[],ranges=[],linewise=!1;for(let range of state.selection.ranges)range.empty||(content2.push(state.sliceDoc(range.from,range.to)),ranges.push(range));if(!content2.length){let upto=-1;for(let{from}of state.selection.ranges){let line=state.doc.lineAt(from);line.number>upto&&(content2.push(line.text),ranges.push({from:line.from,to:Math.min(state.doc.length,line.to+1)})),upto=line.number}linewise=!0}return{text:content2.join(state.lineBreak),ranges,linewise}}__name(copiedRange,"copiedRange"),__name2(copiedRange,"copiedRange");let lastLinewiseCopy=null;handlers.copy=handlers.cut=(view,event)=>{let{text,ranges,linewise}=copiedRange(view.state);if(!text&&!linewise)return!1;lastLinewiseCopy=linewise?text:null,event.type=="cut"&&!view.state.readOnly&&view.dispatch({changes:ranges,scrollIntoView:!0,userEvent:"delete.cut"});let data=brokenClipboardAPI?null:event.clipboardData;return data?(data.clearData(),data.setData("text/plain",text),!0):(captureCopy(view,text),!1)};const isFocusChange=Annotation.define();function focusChangeTransaction(state,focus){let effects=[];for(let getEffect of state.facet(focusChangeEffect)){let effect=getEffect(state,focus);effect&&effects.push(effect)}return effects?state.update({effects,annotations:isFocusChange.of(!0)}):null}__name(focusChangeTransaction,"focusChangeTransaction"),__name2(focusChangeTransaction,"focusChangeTransaction");function updateForFocusChange(view){setTimeout(()=>{let focus=view.hasFocus;if(focus!=view.inputState.notifiedFocused){let tr=focusChangeTransaction(view.state,focus);tr?view.dispatch(tr):view.update([])}},10)}__name(updateForFocusChange,"updateForFocusChange"),__name2(updateForFocusChange,"updateForFocusChange"),observers.focus=view=>{view.inputState.lastFocusTime=Date.now(),!view.scrollDOM.scrollTop&&(view.inputState.lastScrollTop||view.inputState.lastScrollLeft)&&(view.scrollDOM.scrollTop=view.inputState.lastScrollTop,view.scrollDOM.scrollLeft=view.inputState.lastScrollLeft),updateForFocusChange(view)},observers.blur=view=>{view.observer.clearSelectionRange(),updateForFocusChange(view)},observers.compositionstart=observers.compositionupdate=view=>{view.inputState.compositionFirstChange==null&&(view.inputState.compositionFirstChange=!0),view.inputState.composing<0&&(view.inputState.composing=0)},observers.compositionend=view=>{view.inputState.composing=-1,view.inputState.compositionEndedAt=Date.now(),view.inputState.compositionPendingKey=!0,view.inputState.compositionPendingChange=view.observer.pendingRecords().length>0,view.inputState.compositionFirstChange=null,browser.chrome&&browser.android?view.observer.flushSoon():view.inputState.compositionPendingChange?Promise.resolve().then(()=>view.observer.flush()):setTimeout(()=>{view.inputState.composing<0&&view.docView.hasComposition&&view.update([])},50)},observers.contextmenu=view=>{view.inputState.lastContextMenu=Date.now()},handlers.beforeinput=(view,event)=>{var _a3;let pending;if(browser.chrome&&browser.android&&(pending=PendingKeys.find(key=>key.inputType==event.inputType))&&(view.observer.delayAndroidKey(pending.key,pending.keyCode),pending.key=="Backspace"||pending.key=="Delete")){let startViewHeight=((_a3=window.visualViewport)===null||_a3===void 0?void 0:_a3.height)||0;setTimeout(()=>{var _a4;(((_a4=window.visualViewport)===null||_a4===void 0?void 0:_a4.height)||0)>startViewHeight+10&&view.hasFocus&&(view.contentDOM.blur(),view.focus())},100)}return!1};const appliedFirefoxHack=new Set;function firefoxCopyCutHack(doc2){appliedFirefoxHack.has(doc2)||(appliedFirefoxHack.add(doc2),doc2.addEventListener("copy",()=>{}),doc2.addEventListener("cut",()=>{}))}__name(firefoxCopyCutHack,"firefoxCopyCutHack"),__name2(firefoxCopyCutHack,"firefoxCopyCutHack");const wrappingWhiteSpace=["pre-wrap","normal","pre-line","break-spaces"],_HeightOracle=class{static{__name(this,"_HeightOracle")}constructor(lineWrapping){this.lineWrapping=lineWrapping,this.doc=Text.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(from,to){let lines=this.doc.lineAt(to).number-this.doc.lineAt(from).number+1;return this.lineWrapping&&(lines+=Math.max(0,Math.ceil((to-from-lines*this.lineLength*.5)/this.lineLength))),this.lineHeight*lines}heightForLine(length){return this.lineWrapping?(1+Math.max(0,Math.ceil((length-this.lineLength)/(this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(doc2){return this.doc=doc2,this}mustRefreshForWrapping(whiteSpace){return wrappingWhiteSpace.indexOf(whiteSpace)>-1!=this.lineWrapping}mustRefreshForHeights(lineHeights){let newHeight=!1;for(let i=0;i<lineHeights.length;i++){let h=lineHeights[i];h<0?i++:this.heightSamples[Math.floor(h*10)]||(newHeight=!0,this.heightSamples[Math.floor(h*10)]=!0)}return newHeight}refresh(whiteSpace,lineHeight,charWidth,textHeight,lineLength,knownHeights){let lineWrapping=wrappingWhiteSpace.indexOf(whiteSpace)>-1,changed=Math.round(lineHeight)!=Math.round(this.lineHeight)||this.lineWrapping!=lineWrapping;if(this.lineWrapping=lineWrapping,this.lineHeight=lineHeight,this.charWidth=charWidth,this.textHeight=textHeight,this.lineLength=lineLength,changed){this.heightSamples={};for(let i=0;i<knownHeights.length;i++){let h=knownHeights[i];h<0?i++:this.heightSamples[Math.floor(h*10)]=!0}}return changed}};__name2(_HeightOracle,"HeightOracle");let HeightOracle=_HeightOracle;const _MeasuredHeights=class{static{__name(this,"_MeasuredHeights")}constructor(from,heights){this.from=from,this.heights=heights,this.index=0}get more(){return this.index<this.heights.length}};__name2(_MeasuredHeights,"MeasuredHeights");let MeasuredHeights=_MeasuredHeights;const _BlockInfo=class _BlockInfo2{static{__name(this,"_BlockInfo")}constructor(from,length,top2,height,_content){this.from=from,this.length=length,this.top=top2,this.height=height,this._content=_content}get type(){return typeof this._content=="number"?BlockType.Text:Array.isArray(this._content)?this._content:this._content.type}get to(){return this.from+this.length}get bottom(){return this.top+this.height}get widget(){return this._content instanceof PointDecoration?this._content.widget:null}get widgetLineBreaks(){return typeof this._content=="number"?this._content:0}join(other){let content2=(Array.isArray(this._content)?this._content:[this]).concat(Array.isArray(other._content)?other._content:[other]);return new _BlockInfo2(this.from,this.length+other.length,this.top,this.height+other.height,content2)}};__name2(_BlockInfo,"BlockInfo");let BlockInfo=_BlockInfo;var QueryType$1=function(QueryType2){return QueryType2[QueryType2.ByPos=0]="ByPos",QueryType2[QueryType2.ByHeight=1]="ByHeight",QueryType2[QueryType2.ByPosNoHeight=2]="ByPosNoHeight",QueryType2}(QueryType$1||(QueryType$1={}));const Epsilon=.001,_HeightMap=class _HeightMap2{static{__name(this,"_HeightMap")}constructor(length,height,flags=2){this.length=length,this.height=height,this.flags=flags}get outdated(){return(this.flags&2)>0}set outdated(value){this.flags=(value?2:0)|this.flags&-3}setHeight(oracle,height){this.height!=height&&(Math.abs(this.height-height)>Epsilon&&(oracle.heightChanged=!0),this.height=height)}replace(_from,_to,nodes){return _HeightMap2.of(nodes)}decomposeLeft(_to,result){result.push(this)}decomposeRight(_from,result){result.push(this)}applyChanges(decorations2,oldDoc,oracle,changes){let me=this,doc2=oracle.doc;for(let i=changes.length-1;i>=0;i--){let{fromA,toA,fromB,toB}=changes[i],start=me.lineAt(fromA,QueryType$1.ByPosNoHeight,oracle.setDoc(oldDoc),0,0),end=start.to>=toA?start:me.lineAt(toA,QueryType$1.ByPosNoHeight,oracle,0,0);for(toB+=end.to-toA,toA=end.to;i>0&&start.from<=changes[i-1].toA;)fromA=changes[i-1].fromA,fromB=changes[i-1].fromB,i--,fromA<start.from&&(start=me.lineAt(fromA,QueryType$1.ByPosNoHeight,oracle,0,0));fromB+=start.from-fromA,fromA=start.from;let nodes=NodeBuilder.build(oracle.setDoc(doc2),decorations2,fromB,toB);me=me.replace(fromA,toA,nodes)}return me.updateHeight(oracle,0)}static empty(){return new HeightMapText(0,0)}static of(nodes){if(nodes.length==1)return nodes[0];let i=0,j=nodes.length,before=0,after=0;for(;;)if(i==j)if(before>after*2){let split=nodes[i-1];split.break?nodes.splice(--i,1,split.left,null,split.right):nodes.splice(--i,1,split.left,split.right),j+=1+split.break,before-=split.size}else if(after>before*2){let split=nodes[j];split.break?nodes.splice(j,1,split.left,null,split.right):nodes.splice(j,1,split.left,split.right),j+=2+split.break,after-=split.size}else break;else if(before<after){let next=nodes[i++];next&&(before+=next.size)}else{let next=nodes[--j];next&&(after+=next.size)}let brk=0;return nodes[i-1]==null?(brk=1,i--):nodes[i]==null&&(brk=1,j++),new HeightMapBranch(_HeightMap2.of(nodes.slice(0,i)),brk,_HeightMap2.of(nodes.slice(j)))}};__name2(_HeightMap,"HeightMap");let HeightMap=_HeightMap;HeightMap.prototype.size=1;const _HeightMapBlock=class extends HeightMap{static{__name(this,"_HeightMapBlock")}constructor(length,height,deco){super(length,height),this.deco=deco}blockAt(_height,_oracle,top2,offset2){return new BlockInfo(offset2,this.length,top2,this.height,this.deco||0)}lineAt(_value,_type,oracle,top2,offset2){return this.blockAt(0,oracle,top2,offset2)}forEachLine(from,to,oracle,top2,offset2,f2){from<=offset2+this.length&&to>=offset2&&f2(this.blockAt(0,oracle,top2,offset2))}updateHeight(oracle,offset2=0,_force=!1,measured){return measured&&measured.from<=offset2&&measured.more&&this.setHeight(oracle,measured.heights[measured.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}};__name2(_HeightMapBlock,"HeightMapBlock");let HeightMapBlock=_HeightMapBlock;const _HeightMapText=class _HeightMapText2 extends HeightMapBlock{static{__name(this,"_HeightMapText")}constructor(length,height){super(length,height,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(_height,_oracle,top2,offset2){return new BlockInfo(offset2,this.length,top2,this.height,this.breaks)}replace(_from,_to,nodes){let node=nodes[0];return nodes.length==1&&(node instanceof _HeightMapText2||node instanceof HeightMapGap&&node.flags&4)&&Math.abs(this.length-node.length)<10?(node instanceof HeightMapGap?node=new _HeightMapText2(node.length,this.height):node.height=this.height,this.outdated||(node.outdated=!1),node):HeightMap.of(nodes)}updateHeight(oracle,offset2=0,force=!1,measured){return measured&&measured.from<=offset2&&measured.more?this.setHeight(oracle,measured.heights[measured.index++]):(force||this.outdated)&&this.setHeight(oracle,Math.max(this.widgetHeight,oracle.heightForLine(this.length-this.collapsed))+this.breaks*oracle.lineHeight),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}};__name2(_HeightMapText,"HeightMapText");let HeightMapText=_HeightMapText;const _HeightMapGap=class _HeightMapGap2 extends HeightMap{static{__name(this,"_HeightMapGap")}constructor(length){super(length,0)}heightMetrics(oracle,offset2){let firstLine=oracle.doc.lineAt(offset2).number,lastLine=oracle.doc.lineAt(offset2+this.length).number,lines=lastLine-firstLine+1,perLine,perChar=0;if(oracle.lineWrapping){let totalPerLine=Math.min(this.height,oracle.lineHeight*lines);perLine=totalPerLine/lines,this.length>lines+1&&(perChar=(this.height-totalPerLine)/(this.length-lines-1))}else perLine=this.height/lines;return{firstLine,lastLine,perLine,perChar}}blockAt(height,oracle,top2,offset2){let{firstLine,lastLine,perLine,perChar}=this.heightMetrics(oracle,offset2);if(oracle.lineWrapping){let guess=offset2+Math.round(Math.max(0,Math.min(1,(height-top2)/this.height))*this.length),line=oracle.doc.lineAt(guess),lineHeight=perLine+line.length*perChar,lineTop=Math.max(top2,height-lineHeight/2);return new BlockInfo(line.from,line.length,lineTop,lineHeight,0)}else{let line=Math.max(0,Math.min(lastLine-firstLine,Math.floor((height-top2)/perLine))),{from,length}=oracle.doc.line(firstLine+line);return new BlockInfo(from,length,top2+perLine*line,perLine,0)}}lineAt(value,type,oracle,top2,offset2){if(type==QueryType$1.ByHeight)return this.blockAt(value,oracle,top2,offset2);if(type==QueryType$1.ByPosNoHeight){let{from,to}=oracle.doc.lineAt(value);return new BlockInfo(from,to-from,0,0,0)}let{firstLine,perLine,perChar}=this.heightMetrics(oracle,offset2),line=oracle.doc.lineAt(value),lineHeight=perLine+line.length*perChar,linesAbove=line.number-firstLine,lineTop=top2+perLine*linesAbove+perChar*(line.from-offset2-linesAbove);return new BlockInfo(line.from,line.length,Math.max(top2,Math.min(lineTop,top2+this.height-lineHeight)),lineHeight,0)}forEachLine(from,to,oracle,top2,offset2,f2){from=Math.max(from,offset2),to=Math.min(to,offset2+this.length);let{firstLine,perLine,perChar}=this.heightMetrics(oracle,offset2);for(let pos=from,lineTop=top2;pos<=to;){let line=oracle.doc.lineAt(pos);if(pos==from){let linesAbove=line.number-firstLine;lineTop+=perLine*linesAbove+perChar*(from-offset2-linesAbove)}let lineHeight=perLine+perChar*line.length;f2(new BlockInfo(line.from,line.length,lineTop,lineHeight,0)),lineTop+=lineHeight,pos=line.to+1}}replace(from,to,nodes){let after=this.length-to;if(after>0){let last2=nodes[nodes.length-1];last2 instanceof _HeightMapGap2?nodes[nodes.length-1]=new _HeightMapGap2(last2.length+after):nodes.push(null,new _HeightMapGap2(after-1))}if(from>0){let first=nodes[0];first instanceof _HeightMapGap2?nodes[0]=new _HeightMapGap2(from+first.length):nodes.unshift(new _HeightMapGap2(from-1),null)}return HeightMap.of(nodes)}decomposeLeft(to,result){result.push(new _HeightMapGap2(to-1),null)}decomposeRight(from,result){result.push(null,new _HeightMapGap2(this.length-from-1))}updateHeight(oracle,offset2=0,force=!1,measured){let end=offset2+this.length;if(measured&&measured.from<=offset2+this.length&&measured.more){let nodes=[],pos=Math.max(offset2,measured.from),singleHeight=-1;for(measured.from>offset2&&nodes.push(new _HeightMapGap2(measured.from-offset2-1).updateHeight(oracle,offset2));pos<=end&&measured.more;){let len=oracle.doc.lineAt(pos).length;nodes.length&&nodes.push(null);let height=measured.heights[measured.index++];singleHeight==-1?singleHeight=height:Math.abs(height-singleHeight)>=Epsilon&&(singleHeight=-2);let line=new HeightMapText(len,height);line.outdated=!1,nodes.push(line),pos+=len+1}pos<=end&&nodes.push(null,new _HeightMapGap2(end-pos).updateHeight(oracle,pos));let result=HeightMap.of(nodes);return(singleHeight<0||Math.abs(result.height-this.height)>=Epsilon||Math.abs(singleHeight-this.heightMetrics(oracle,offset2).perLine)>=Epsilon)&&(oracle.heightChanged=!0),result}else(force||this.outdated)&&(this.setHeight(oracle,oracle.heightForGap(offset2,offset2+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}};__name2(_HeightMapGap,"HeightMapGap");let HeightMapGap=_HeightMapGap;const _HeightMapBranch=class extends HeightMap{static{__name(this,"_HeightMapBranch")}constructor(left,brk,right){super(left.length+brk+right.length,left.height+right.height,brk|(left.outdated||right.outdated?2:0)),this.left=left,this.right=right,this.size=left.size+right.size}get break(){return this.flags&1}blockAt(height,oracle,top2,offset2){let mid=top2+this.left.height;return height<mid?this.left.blockAt(height,oracle,top2,offset2):this.right.blockAt(height,oracle,mid,offset2+this.left.length+this.break)}lineAt(value,type,oracle,top2,offset2){let rightTop=top2+this.left.height,rightOffset=offset2+this.left.length+this.break,left=type==QueryType$1.ByHeight?value<rightTop:value<rightOffset,base2=left?this.left.lineAt(value,type,oracle,top2,offset2):this.right.lineAt(value,type,oracle,rightTop,rightOffset);if(this.break||(left?base2.to<rightOffset:base2.from>rightOffset))return base2;let subQuery=type==QueryType$1.ByPosNoHeight?QueryType$1.ByPosNoHeight:QueryType$1.ByPos;return left?base2.join(this.right.lineAt(rightOffset,subQuery,oracle,rightTop,rightOffset)):this.left.lineAt(rightOffset,subQuery,oracle,top2,offset2).join(base2)}forEachLine(from,to,oracle,top2,offset2,f2){let rightTop=top2+this.left.height,rightOffset=offset2+this.left.length+this.break;if(this.break)from<rightOffset&&this.left.forEachLine(from,to,oracle,top2,offset2,f2),to>=rightOffset&&this.right.forEachLine(from,to,oracle,rightTop,rightOffset,f2);else{let mid=this.lineAt(rightOffset,QueryType$1.ByPos,oracle,top2,offset2);from<mid.from&&this.left.forEachLine(from,mid.from-1,oracle,top2,offset2,f2),mid.to>=from&&mid.from<=to&&f2(mid),to>mid.to&&this.right.forEachLine(mid.to+1,to,oracle,rightTop,rightOffset,f2)}}replace(from,to,nodes){let rightStart=this.left.length+this.break;if(to<rightStart)return this.balanced(this.left.replace(from,to,nodes),this.right);if(from>this.left.length)return this.balanced(this.left,this.right.replace(from-rightStart,to-rightStart,nodes));let result=[];from>0&&this.decomposeLeft(from,result);let left=result.length;for(let node of nodes)result.push(node);if(from>0&&mergeGaps(result,left-1),to<this.length){let right=result.length;this.decomposeRight(to,result),mergeGaps(result,right)}return HeightMap.of(result)}decomposeLeft(to,result){let left=this.left.length;if(to<=left)return this.left.decomposeLeft(to,result);result.push(this.left),this.break&&(left++,to>=left&&result.push(null)),to>left&&this.right.decomposeLeft(to-left,result)}decomposeRight(from,result){let left=this.left.length,right=left+this.break;if(from>=right)return this.right.decomposeRight(from-right,result);from<left&&this.left.decomposeRight(from,result),this.break&&from<right&&result.push(null),result.push(this.right)}balanced(left,right){return left.size>2*right.size||right.size>2*left.size?HeightMap.of(this.break?[left,null,right]:[left,right]):(this.left=left,this.right=right,this.height=left.height+right.height,this.outdated=left.outdated||right.outdated,this.size=left.size+right.size,this.length=left.length+this.break+right.length,this)}updateHeight(oracle,offset2=0,force=!1,measured){let{left,right}=this,rightStart=offset2+left.length+this.break,rebalance=null;return measured&&measured.from<=offset2+left.length&&measured.more?rebalance=left=left.updateHeight(oracle,offset2,force,measured):left.updateHeight(oracle,offset2,force),measured&&measured.from<=rightStart+right.length&&measured.more?rebalance=right=right.updateHeight(oracle,rightStart,force,measured):right.updateHeight(oracle,rightStart,force),rebalance?this.balanced(left,right):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};__name2(_HeightMapBranch,"HeightMapBranch");let HeightMapBranch=_HeightMapBranch;function mergeGaps(nodes,around){let before,after;nodes[around]==null&&(before=nodes[around-1])instanceof HeightMapGap&&(after=nodes[around+1])instanceof HeightMapGap&&nodes.splice(around-1,3,new HeightMapGap(before.length+1+after.length))}__name(mergeGaps,"mergeGaps"),__name2(mergeGaps,"mergeGaps");const relevantWidgetHeight=5,_NodeBuilder=class _NodeBuilder2{static{__name(this,"_NodeBuilder")}constructor(pos,oracle){this.pos=pos,this.oracle=oracle,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=pos}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(_from,to){if(this.lineStart>-1){let end=Math.min(to,this.lineEnd),last2=this.nodes[this.nodes.length-1];last2 instanceof HeightMapText?last2.length+=end-this.pos:(end>this.pos||!this.isCovered)&&this.nodes.push(new HeightMapText(end-this.pos,-1)),this.writtenTo=end,to>end&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=to}point(from,to,deco){if(from<to||deco.heightRelevant){let height=deco.widget?deco.widget.estimatedHeight:0,breaks=deco.widget?deco.widget.lineBreaks:0;height<0&&(height=this.oracle.lineHeight);let len=to-from;deco.block?this.addBlock(new HeightMapBlock(len,height,deco)):(len||breaks||height>=relevantWidgetHeight)&&this.addLineDeco(height,breaks,len)}else to>from&&this.span(from,to);this.lineEnd>-1&&this.lineEnd<this.pos&&(this.lineEnd=this.oracle.doc.lineAt(this.pos).to)}enterLine(){if(this.lineStart>-1)return;let{from,to}=this.oracle.doc.lineAt(this.pos);this.lineStart=from,this.lineEnd=to,this.writtenTo<from&&((this.writtenTo<from-1||this.nodes[this.nodes.length-1]==null)&&this.nodes.push(this.blankContent(this.writtenTo,from-1)),this.nodes.push(null)),this.pos>from&&this.nodes.push(new HeightMapText(this.pos-from,-1)),this.writtenTo=this.pos}blankContent(from,to){let gap=new HeightMapGap(to-from);return this.oracle.doc.lineAt(from).to==to&&(gap.flags|=4),gap}ensureLine(){this.enterLine();let last2=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(last2 instanceof HeightMapText)return last2;let line=new HeightMapText(0,-1);return this.nodes.push(line),line}addBlock(block){this.enterLine();let deco=block.deco;deco&&deco.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(block),this.writtenTo=this.pos=this.pos+block.length,deco&&deco.endSide>0&&(this.covering=block)}addLineDeco(height,breaks,length){let line=this.ensureLine();line.length+=length,line.collapsed+=length,line.widgetHeight=Math.max(line.widgetHeight,height),line.breaks+=breaks,this.writtenTo=this.pos=this.pos+length}finish(from){let last2=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(last2 instanceof HeightMapText)&&!this.isCovered?this.nodes.push(new HeightMapText(0,-1)):(this.writtenTo<this.pos||last2==null)&&this.nodes.push(this.blankContent(this.writtenTo,this.pos));let pos=from;for(let node of this.nodes)node instanceof HeightMapText&&node.updateHeight(this.oracle,pos),pos+=node?node.length:1;return this.nodes}static build(oracle,decorations2,from,to){let builder=new _NodeBuilder2(from,oracle);return RangeSet.spans(decorations2,from,to,builder,0),builder.finish(from)}};__name2(_NodeBuilder,"NodeBuilder");let NodeBuilder=_NodeBuilder;function heightRelevantDecoChanges(a,b,diff2){let comp=new DecorationComparator;return RangeSet.compare(a,b,diff2,comp,0),comp.changes}__name(heightRelevantDecoChanges,"heightRelevantDecoChanges"),__name2(heightRelevantDecoChanges,"heightRelevantDecoChanges");const _DecorationComparator=class{static{__name(this,"_DecorationComparator")}constructor(){this.changes=[]}compareRange(){}comparePoint(from,to,a,b){(from<to||a&&a.heightRelevant||b&&b.heightRelevant)&&addRange(from,to,this.changes,5)}};__name2(_DecorationComparator,"DecorationComparator");let DecorationComparator=_DecorationComparator;function visiblePixelRange(dom,paddingTop){let rect=dom.getBoundingClientRect(),doc2=dom.ownerDocument,win=doc2.defaultView||window,left=Math.max(0,rect.left),right=Math.min(win.innerWidth,rect.right),top2=Math.max(0,rect.top),bottom=Math.min(win.innerHeight,rect.bottom);for(let parent=dom.parentNode;parent&&parent!=doc2.body;)if(parent.nodeType==1){let elt=parent,style=window.getComputedStyle(elt);if((elt.scrollHeight>elt.clientHeight||elt.scrollWidth>elt.clientWidth)&&style.overflow!="visible"){let parentRect=elt.getBoundingClientRect();left=Math.max(left,parentRect.left),right=Math.min(right,parentRect.right),top2=Math.max(top2,parentRect.top),bottom=parent==dom.parentNode?parentRect.bottom:Math.min(bottom,parentRect.bottom)}parent=style.position=="absolute"||style.position=="fixed"?elt.offsetParent:elt.parentNode}else if(parent.nodeType==11)parent=parent.host;else break;return{left:left-rect.left,right:Math.max(left,right)-rect.left,top:top2-(rect.top+paddingTop),bottom:Math.max(top2,bottom)-(rect.top+paddingTop)}}__name(visiblePixelRange,"visiblePixelRange"),__name2(visiblePixelRange,"visiblePixelRange");function fullPixelRange(dom,paddingTop){let rect=dom.getBoundingClientRect();return{left:0,right:rect.right-rect.left,top:paddingTop,bottom:rect.bottom-(rect.top+paddingTop)}}__name(fullPixelRange,"fullPixelRange"),__name2(fullPixelRange,"fullPixelRange");const _LineGap=class{static{__name(this,"_LineGap")}constructor(from,to,size){this.from=from,this.to=to,this.size=size}static same(a,b){if(a.length!=b.length)return!1;for(let i=0;i<a.length;i++){let gA=a[i],gB=b[i];if(gA.from!=gB.from||gA.to!=gB.to||gA.size!=gB.size)return!1}return!0}draw(viewState,wrapping){return Decoration.replace({widget:new LineGapWidget(this.size*(wrapping?viewState.scaleY:viewState.scaleX),wrapping)}).range(this.from,this.to)}};__name2(_LineGap,"LineGap");let LineGap=_LineGap;const _LineGapWidget=class extends WidgetType{static{__name(this,"_LineGapWidget")}constructor(size,vertical){super(),this.size=size,this.vertical=vertical}eq(other){return other.size==this.size&&other.vertical==this.vertical}toDOM(){let elt=document.createElement("div");return this.vertical?elt.style.height=this.size+"px":(elt.style.width=this.size+"px",elt.style.height="2px",elt.style.display="inline-block"),elt}get estimatedHeight(){return this.vertical?this.size:-1}};__name2(_LineGapWidget,"LineGapWidget");let LineGapWidget=_LineGapWidget;const _ViewState=class{static{__name(this,"_ViewState")}constructor(state){this.state=state,this.pixelViewport={left:0,right:window.innerWidth,top:0,bottom:0},this.inView=!0,this.paddingTop=0,this.paddingBottom=0,this.contentDOMWidth=0,this.contentDOMHeight=0,this.editorHeight=0,this.editorWidth=0,this.scrollTop=0,this.scrolledToBottom=!0,this.scaleX=1,this.scaleY=1,this.scrollAnchorPos=0,this.scrollAnchorHeight=-1,this.scaler=IdScaler,this.scrollTarget=null,this.printing=!1,this.mustMeasureContent=!0,this.defaultTextDirection=Direction.LTR,this.visibleRanges=[],this.mustEnforceCursorAssoc=!1;let guessWrapping=state.facet(contentAttributes).some(v=>typeof v!="function"&&v.class=="cm-lineWrapping");this.heightOracle=new HeightOracle(guessWrapping),this.stateDeco=state.facet(decorations).filter(d=>typeof d!="function"),this.heightMap=HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle.setDoc(state.doc),[new ChangedRange(0,0,0,state.doc.length)]),this.viewport=this.getViewport(0,null),this.updateViewportLines(),this.updateForViewport(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Decoration.set(this.lineGaps.map(gap=>gap.draw(this,!1))),this.computeVisibleRanges()}updateForViewport(){let viewports=[this.viewport],{main}=this.state.selection;for(let i=0;i<=1;i++){let pos=i?main.head:main.anchor;if(!viewports.some(({from,to})=>pos>=from&&pos<=to)){let{from,to}=this.lineBlockAt(pos);viewports.push(new Viewport(from,to))}}this.viewports=viewports.sort((a,b)=>a.from-b.from),this.scaler=this.heightMap.height<=7e6?IdScaler:new BigScaler(this.heightOracle,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,block=>{this.viewportLines.push(this.scaler.scale==1?block:scaleBlock(block,this.scaler))})}update(update,scrollTarget=null){this.state=update.state;let prevDeco=this.stateDeco;this.stateDeco=this.state.facet(decorations).filter(d=>typeof d!="function");let contentChanges=update.changedRanges,heightChanges=ChangedRange.extendWithRanges(contentChanges,heightRelevantDecoChanges(prevDeco,this.stateDeco,update?update.changes:ChangeSet.empty(this.state.doc.length))),prevHeight=this.heightMap.height,scrollAnchor=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,update.startState.doc,this.heightOracle.setDoc(this.state.doc),heightChanges),this.heightMap.height!=prevHeight&&(update.flags|=2),scrollAnchor?(this.scrollAnchorPos=update.changes.mapPos(scrollAnchor.from,-1),this.scrollAnchorHeight=scrollAnchor.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let viewport=heightChanges.length?this.mapViewport(this.viewport,update.changes):this.viewport;(scrollTarget&&(scrollTarget.range.head<viewport.from||scrollTarget.range.head>viewport.to)||!this.viewportIsAppropriate(viewport))&&(viewport=this.getViewport(0,scrollTarget));let updateLines=!update.changes.empty||update.flags&2||viewport.from!=this.viewport.from||viewport.to!=this.viewport.to;this.viewport=viewport,this.updateForViewport(),updateLines&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,update.changes))),update.flags|=this.computeVisibleRanges(),scrollTarget&&(this.scrollTarget=scrollTarget),!this.mustEnforceCursorAssoc&&update.selectionSet&&update.view.lineWrapping&&update.state.selection.main.empty&&update.state.selection.main.assoc&&!update.state.facet(nativeSelectionHidden)&&(this.mustEnforceCursorAssoc=!0)}measure(view){let dom=view.contentDOM,style=window.getComputedStyle(dom),oracle=this.heightOracle,whiteSpace=style.whiteSpace;this.defaultTextDirection=style.direction=="rtl"?Direction.RTL:Direction.LTR;let refresh=this.heightOracle.mustRefreshForWrapping(whiteSpace),domRect=dom.getBoundingClientRect(),measureContent=refresh||this.mustMeasureContent||this.contentDOMHeight!=domRect.height;this.contentDOMHeight=domRect.height,this.mustMeasureContent=!1;let result=0,bias=0;if(domRect.width&&domRect.height){let scaleX=domRect.width/dom.offsetWidth,scaleY=domRect.height/dom.offsetHeight;(scaleX>.995&&scaleX<1.005||!isFinite(scaleX)||Math.abs(domRect.width-dom.offsetWidth)<1)&&(scaleX=1),(scaleY>.995&&scaleY<1.005||!isFinite(scaleY)||Math.abs(domRect.height-dom.offsetHeight)<1)&&(scaleY=1),(this.scaleX!=scaleX||this.scaleY!=scaleY)&&(this.scaleX=scaleX,this.scaleY=scaleY,result|=8,refresh=measureContent=!0)}let paddingTop=(parseInt(style.paddingTop)||0)*this.scaleY,paddingBottom=(parseInt(style.paddingBottom)||0)*this.scaleY;(this.paddingTop!=paddingTop||this.paddingBottom!=paddingBottom)&&(this.paddingTop=paddingTop,this.paddingBottom=paddingBottom,result|=10),this.editorWidth!=view.scrollDOM.clientWidth&&(oracle.lineWrapping&&(measureContent=!0),this.editorWidth=view.scrollDOM.clientWidth,result|=8);let scrollTop=view.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=scrollTop&&(this.scrollAnchorHeight=-1,this.scrollTop=scrollTop),this.scrolledToBottom=isScrolledToBottom(view.scrollDOM);let pixelViewport=(this.printing?fullPixelRange:visiblePixelRange)(dom,this.paddingTop),dTop=pixelViewport.top-this.pixelViewport.top,dBottom=pixelViewport.bottom-this.pixelViewport.bottom;this.pixelViewport=pixelViewport;let inView=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(inView!=this.inView&&(this.inView=inView,inView&&(measureContent=!0)),!this.inView&&!this.scrollTarget)return 0;let contentWidth=domRect.width;if((this.contentDOMWidth!=contentWidth||this.editorHeight!=view.scrollDOM.clientHeight)&&(this.contentDOMWidth=domRect.width,this.editorHeight=view.scrollDOM.clientHeight,result|=8),measureContent){let lineHeights=view.docView.measureVisibleLineHeights(this.viewport);if(oracle.mustRefreshForHeights(lineHeights)&&(refresh=!0),refresh||oracle.lineWrapping&&Math.abs(contentWidth-this.contentDOMWidth)>oracle.charWidth){let{lineHeight,charWidth,textHeight}=view.docView.measureTextSize();refresh=lineHeight>0&&oracle.refresh(whiteSpace,lineHeight,charWidth,textHeight,contentWidth/charWidth,lineHeights),refresh&&(view.docView.minWidth=0,result|=8)}dTop>0&&dBottom>0?bias=Math.max(dTop,dBottom):dTop<0&&dBottom<0&&(bias=Math.min(dTop,dBottom)),oracle.heightChanged=!1;for(let vp of this.viewports){let heights=vp.from==this.viewport.from?lineHeights:view.docView.measureVisibleLineHeights(vp);this.heightMap=(refresh?HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle,[new ChangedRange(0,0,0,view.state.doc.length)]):this.heightMap).updateHeight(oracle,0,refresh,new MeasuredHeights(vp.from,heights))}oracle.heightChanged&&(result|=2)}let viewportChange=!this.viewportIsAppropriate(this.viewport,bias)||this.scrollTarget&&(this.scrollTarget.range.head<this.viewport.from||this.scrollTarget.range.head>this.viewport.to);return viewportChange&&(this.viewport=this.getViewport(bias,this.scrollTarget)),this.updateForViewport(),(result&2||viewportChange)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(refresh?[]:this.lineGaps,view)),result|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,view.docView.enforceCursorAssoc()),result}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(bias,scrollTarget){let marginTop=.5-Math.max(-.5,Math.min(.5,bias/1e3/2)),map2=this.heightMap,oracle=this.heightOracle,{visibleTop,visibleBottom}=this,viewport=new Viewport(map2.lineAt(visibleTop-marginTop*1e3,QueryType$1.ByHeight,oracle,0,0).from,map2.lineAt(visibleBottom+(1-marginTop)*1e3,QueryType$1.ByHeight,oracle,0,0).to);if(scrollTarget){let{head}=scrollTarget.range;if(head<viewport.from||head>viewport.to){let viewHeight=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),block=map2.lineAt(head,QueryType$1.ByPos,oracle,0,0),topPos;scrollTarget.y=="center"?topPos=(block.top+block.bottom)/2-viewHeight/2:scrollTarget.y=="start"||scrollTarget.y=="nearest"&&head<viewport.from?topPos=block.top:topPos=block.bottom-viewHeight,viewport=new Viewport(map2.lineAt(topPos-1e3/2,QueryType$1.ByHeight,oracle,0,0).from,map2.lineAt(topPos+viewHeight+1e3/2,QueryType$1.ByHeight,oracle,0,0).to)}}return viewport}mapViewport(viewport,changes){let from=changes.mapPos(viewport.from,-1),to=changes.mapPos(viewport.to,1);return new Viewport(this.heightMap.lineAt(from,QueryType$1.ByPos,this.heightOracle,0,0).from,this.heightMap.lineAt(to,QueryType$1.ByPos,this.heightOracle,0,0).to)}viewportIsAppropriate({from,to},bias=0){if(!this.inView)return!0;let{top:top2}=this.heightMap.lineAt(from,QueryType$1.ByPos,this.heightOracle,0,0),{bottom}=this.heightMap.lineAt(to,QueryType$1.ByPos,this.heightOracle,0,0),{visibleTop,visibleBottom}=this;return(from==0||top2<=visibleTop-Math.max(10,Math.min(-bias,250)))&&(to==this.state.doc.length||bottom>=visibleBottom+Math.max(10,Math.min(bias,250)))&&top2>visibleTop-2*1e3&&bottom<visibleBottom+2*1e3}mapLineGaps(gaps,changes){if(!gaps.length||changes.empty)return gaps;let mapped=[];for(let gap of gaps)changes.touchesRange(gap.from,gap.to)||mapped.push(new LineGap(changes.mapPos(gap.from),changes.mapPos(gap.to),gap.size));return mapped}ensureLineGaps(current,mayMeasure){let wrapping=this.heightOracle.lineWrapping,margin=wrapping?1e4:2e3,halfMargin=margin>>1,doubleMargin=margin<<1;if(this.defaultTextDirection!=Direction.LTR&&!wrapping)return[];let gaps=[],addGap=__name2((from,to,line,structure)=>{if(to-from<halfMargin)return;let sel=this.state.selection.main,avoid=[sel.from];sel.empty||avoid.push(sel.to);for(let pos of avoid)if(pos>from&&pos<to){addGap(from,pos-10,line,structure),addGap(pos+10,to,line,structure);return}let gap=find(current,gap2=>gap2.from>=line.from&&gap2.to<=line.to&&Math.abs(gap2.from-from)<halfMargin&&Math.abs(gap2.to-to)<halfMargin&&!avoid.some(pos=>gap2.from<pos&&gap2.to>pos));if(!gap){if(to<line.to&&mayMeasure&&wrapping&&mayMeasure.visibleRanges.some(r=>r.from<=to&&r.to>=to)){let lineStart=mayMeasure.moveToLineBoundary(EditorSelection.cursor(to),!1,!0).head;lineStart>from&&(to=lineStart)}gap=new LineGap(from,to,this.gapSize(line,from,to,structure))}gaps.push(gap)},"addGap");for(let line of this.viewportLines){if(line.length<doubleMargin)continue;let structure=lineStructure(line.from,line.to,this.stateDeco);if(structure.total<doubleMargin)continue;let target=this.scrollTarget?this.scrollTarget.range.head:null,viewFrom,viewTo;if(wrapping){let marginHeight=margin/this.heightOracle.lineLength*this.heightOracle.lineHeight,top2,bot;if(target!=null){let targetFrac=findFraction(structure,target),spaceFrac=((this.visibleBottom-this.visibleTop)/2+marginHeight)/line.height;top2=targetFrac-spaceFrac,bot=targetFrac+spaceFrac}else top2=(this.visibleTop-line.top-marginHeight)/line.height,bot=(this.visibleBottom-line.top+marginHeight)/line.height;viewFrom=findPosition(structure,top2),viewTo=findPosition(structure,bot)}else{let totalWidth=structure.total*this.heightOracle.charWidth,marginWidth=margin*this.heightOracle.charWidth,left,right;if(target!=null){let targetFrac=findFraction(structure,target),spaceFrac=((this.pixelViewport.right-this.pixelViewport.left)/2+marginWidth)/totalWidth;left=targetFrac-spaceFrac,right=targetFrac+spaceFrac}else left=(this.pixelViewport.left-marginWidth)/totalWidth,right=(this.pixelViewport.right+marginWidth)/totalWidth;viewFrom=findPosition(structure,left),viewTo=findPosition(structure,right)}viewFrom>line.from&&addGap(line.from,viewFrom,line,structure),viewTo<line.to&&addGap(viewTo,line.to,line,structure)}return gaps}gapSize(line,from,to,structure){let fraction=findFraction(structure,to)-findFraction(structure,from);return this.heightOracle.lineWrapping?line.height*fraction:structure.total*this.heightOracle.charWidth*fraction}updateLineGaps(gaps){LineGap.same(gaps,this.lineGaps)||(this.lineGaps=gaps,this.lineGapDeco=Decoration.set(gaps.map(gap=>gap.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(){let deco=this.stateDeco;this.lineGaps.length&&(deco=deco.concat(this.lineGapDeco));let ranges=[];RangeSet.spans(deco,this.viewport.from,this.viewport.to,{span(from,to){ranges.push({from,to})},point(){}},20);let changed=ranges.length!=this.visibleRanges.length||this.visibleRanges.some((r,i)=>r.from!=ranges[i].from||r.to!=ranges[i].to);return this.visibleRanges=ranges,changed?4:0}lineBlockAt(pos){return pos>=this.viewport.from&&pos<=this.viewport.to&&this.viewportLines.find(b=>b.from<=pos&&b.to>=pos)||scaleBlock(this.heightMap.lineAt(pos,QueryType$1.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(height){return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height),QueryType$1.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(scrollTop){let block=this.lineBlockAtHeight(scrollTop+8);return block.from>=this.viewport.from||this.viewportLines[0].top-scrollTop>200?block:this.viewportLines[0]}elementAtHeight(height){return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}};__name2(_ViewState,"ViewState");let ViewState=_ViewState;const _Viewport=class{static{__name(this,"_Viewport")}constructor(from,to){this.from=from,this.to=to}};__name2(_Viewport,"Viewport");let Viewport=_Viewport;function lineStructure(from,to,stateDeco){let ranges=[],pos=from,total=0;return RangeSet.spans(stateDeco,from,to,{span(){},point(from2,to2){from2>pos&&(ranges.push({from:pos,to:from2}),total+=from2-pos),pos=to2}},20),pos<to&&(ranges.push({from:pos,to}),total+=to-pos),{total,ranges}}__name(lineStructure,"lineStructure"),__name2(lineStructure,"lineStructure");function findPosition({total,ranges},ratio){if(ratio<=0)return ranges[0].from;if(ratio>=1)return ranges[ranges.length-1].to;let dist2=Math.floor(total*ratio);for(let i=0;;i++){let{from,to}=ranges[i],size=to-from;if(dist2<=size)return from+dist2;dist2-=size}}__name(findPosition,"findPosition"),__name2(findPosition,"findPosition");function findFraction(structure,pos){let counted=0;for(let{from,to}of structure.ranges){if(pos<=to){counted+=pos-from;break}counted+=to-from}return counted/structure.total}__name(findFraction,"findFraction"),__name2(findFraction,"findFraction");function find(array,f2){for(let val of array)if(f2(val))return val}__name(find,"find"),__name2(find,"find");const IdScaler={toDOM(n2){return n2},fromDOM(n2){return n2},scale:1},_BigScaler=class{static{__name(this,"_BigScaler")}constructor(oracle,heightMap,viewports){let vpHeight=0,base2=0,domBase=0;this.viewports=viewports.map(({from,to})=>{let top2=heightMap.lineAt(from,QueryType$1.ByPos,oracle,0,0).top,bottom=heightMap.lineAt(to,QueryType$1.ByPos,oracle,0,0).bottom;return vpHeight+=bottom-top2,{from,to,top:top2,bottom,domTop:0,domBottom:0}}),this.scale=(7e6-vpHeight)/(heightMap.height-vpHeight);for(let obj of this.viewports)obj.domTop=domBase+(obj.top-base2)*this.scale,domBase=obj.domBottom=obj.domTop+(obj.bottom-obj.top),base2=obj.bottom}toDOM(n2){for(let i=0,base2=0,domBase=0;;i++){let vp=i<this.viewports.length?this.viewports[i]:null;if(!vp||n2<vp.top)return domBase+(n2-base2)*this.scale;if(n2<=vp.bottom)return vp.domTop+(n2-vp.top);base2=vp.bottom,domBase=vp.domBottom}}fromDOM(n2){for(let i=0,base2=0,domBase=0;;i++){let vp=i<this.viewports.length?this.viewports[i]:null;if(!vp||n2<vp.domTop)return base2+(n2-domBase)/this.scale;if(n2<=vp.domBottom)return vp.top+(n2-vp.domTop);base2=vp.bottom,domBase=vp.domBottom}}};__name2(_BigScaler,"BigScaler");let BigScaler=_BigScaler;function scaleBlock(block,scaler){if(scaler.scale==1)return block;let bTop=scaler.toDOM(block.top),bBottom=scaler.toDOM(block.bottom);return new BlockInfo(block.from,block.length,bTop,bBottom-bTop,Array.isArray(block._content)?block._content.map(b=>scaleBlock(b,scaler)):block._content)}__name(scaleBlock,"scaleBlock"),__name2(scaleBlock,"scaleBlock");const theme=Facet.define({combine:strs=>strs.join(" ")}),darkTheme=Facet.define({combine:values=>values.indexOf(!0)>-1}),baseThemeID=StyleModule.newName(),baseLightID=StyleModule.newName(),baseDarkID=StyleModule.newName(),lightDarkIDs={"&light":"."+baseLightID,"&dark":"."+baseDarkID};function buildTheme(main,spec,scopes){return new StyleModule(spec,{finish(sel){return/&/.test(sel)?sel.replace(/&\w*/,m=>{if(m=="&")return main;if(!scopes||!scopes[m])throw new RangeError(`Unsupported selector: ${m}`);return scopes[m]}):main+" "+sel}})}__name(buildTheme,"buildTheme"),__name2(buildTheme,"buildTheme");const baseTheme$1$2=buildTheme("."+baseThemeID,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},lightDarkIDs),LineBreakPlaceholder="\uFFFF",_DOMReader=class{static{__name(this,"_DOMReader")}constructor(points,state){this.points=points,this.text="",this.lineSeparator=state.facet(EditorState.lineSeparator)}append(text){this.text+=text}lineBreak(){this.text+=LineBreakPlaceholder}readRange(start,end){if(!start)return this;let parent=start.parentNode;for(let cur2=start;;){this.findPointBefore(parent,cur2);let oldLen=this.text.length;this.readNode(cur2);let next=cur2.nextSibling;if(next==end)break;let view=ContentView.get(cur2),nextView=ContentView.get(next);(view&&nextView?view.breakAfter:(view?view.breakAfter:isBlockElement(cur2))||isBlockElement(next)&&(cur2.nodeName!="BR"||cur2.cmIgnore)&&this.text.length>oldLen)&&this.lineBreak(),cur2=next}return this.findPointBefore(parent,end),this}readTextNode(node){let text=node.nodeValue;for(let point of this.points)point.node==node&&(point.pos=this.text.length+Math.min(point.offset,text.length));for(let off2=0,re=this.lineSeparator?null:/\r\n?|\n/g;;){let nextBreak=-1,breakSize=1,m;if(this.lineSeparator?(nextBreak=text.indexOf(this.lineSeparator,off2),breakSize=this.lineSeparator.length):(m=re.exec(text))&&(nextBreak=m.index,breakSize=m[0].length),this.append(text.slice(off2,nextBreak<0?text.length:nextBreak)),nextBreak<0)break;if(this.lineBreak(),breakSize>1)for(let point of this.points)point.node==node&&point.pos>this.text.length&&(point.pos-=breakSize-1);off2=nextBreak+breakSize}}readNode(node){if(node.cmIgnore)return;let view=ContentView.get(node),fromView=view&&view.overrideDOMText;if(fromView!=null){this.findPointInside(node,fromView.length);for(let i=fromView.iter();!i.next().done;)i.lineBreak?this.lineBreak():this.append(i.value)}else node.nodeType==3?this.readTextNode(node):node.nodeName=="BR"?node.nextSibling&&this.lineBreak():node.nodeType==1&&this.readRange(node.firstChild,null)}findPointBefore(node,next){for(let point of this.points)point.node==node&&node.childNodes[point.offset]==next&&(point.pos=this.text.length)}findPointInside(node,length){for(let point of this.points)(node.nodeType==3?point.node==node:node.contains(point.node))&&(point.pos=this.text.length+(isAtEnd(node,point.node,point.offset)?length:0))}};__name2(_DOMReader,"DOMReader");let DOMReader=_DOMReader;function isAtEnd(parent,node,offset2){for(;;){if(!node||offset2<maxOffset(node))return!1;if(node==parent)return!0;offset2=domIndex(node)+1,node=node.parentNode}}__name(isAtEnd,"isAtEnd"),__name2(isAtEnd,"isAtEnd");function isBlockElement(node){return node.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName)}__name(isBlockElement,"isBlockElement"),__name2(isBlockElement,"isBlockElement");const _DOMPoint=class{static{__name(this,"_DOMPoint")}constructor(node,offset2){this.node=node,this.offset=offset2,this.pos=-1}};__name2(_DOMPoint,"DOMPoint");let DOMPoint=_DOMPoint;const _DOMChange=class{static{__name(this,"_DOMChange")}constructor(view,start,end,typeOver){this.typeOver=typeOver,this.bounds=null,this.text="";let{impreciseHead:iHead,impreciseAnchor:iAnchor}=view.docView;if(view.state.readOnly&&start>-1)this.newSel=null;else if(start>-1&&(this.bounds=view.docView.domBoundsAround(start,end,0))){let selPoints=iHead||iAnchor?[]:selectionPoints(view),reader=new DOMReader(selPoints,view.state);reader.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=reader.text,this.newSel=selectionFromPoints(selPoints,this.bounds.from)}else{let domSel=view.observer.selectionRange,head=iHead&&iHead.node==domSel.focusNode&&iHead.offset==domSel.focusOffset||!contains(view.contentDOM,domSel.focusNode)?view.state.selection.main.head:view.docView.posFromDOM(domSel.focusNode,domSel.focusOffset),anchor=iAnchor&&iAnchor.node==domSel.anchorNode&&iAnchor.offset==domSel.anchorOffset||!contains(view.contentDOM,domSel.anchorNode)?view.state.selection.main.anchor:view.docView.posFromDOM(domSel.anchorNode,domSel.anchorOffset);this.newSel=EditorSelection.single(anchor,head)}}};__name2(_DOMChange,"DOMChange");let DOMChange=_DOMChange;function applyDOMChange(view,domChange){let change,{newSel}=domChange,sel=view.state.selection.main,lastKey=view.inputState.lastKeyTime>Date.now()-100?view.inputState.lastKeyCode:-1;if(domChange.bounds){let{from,to}=domChange.bounds,preferredPos=sel.from,preferredSide=null;(lastKey===8||browser.android&&domChange.text.length<to-from)&&(preferredPos=sel.to,preferredSide="end");let diff2=findDiff(view.state.doc.sliceString(from,to,LineBreakPlaceholder),domChange.text,preferredPos-from,preferredSide);diff2&&(browser.chrome&&lastKey==13&&diff2.toB==diff2.from+2&&domChange.text.slice(diff2.from,diff2.toB)==LineBreakPlaceholder+LineBreakPlaceholder&&diff2.toB--,change={from:from+diff2.from,to:from+diff2.toA,insert:Text.of(domChange.text.slice(diff2.from,diff2.toB).split(LineBreakPlaceholder))})}else newSel&&(!view.hasFocus&&view.state.facet(editable)||newSel.main.eq(sel))&&(newSel=null);if(!change&&!newSel)return!1;if(!change&&domChange.typeOver&&!sel.empty&&newSel&&newSel.main.empty?change={from:sel.from,to:sel.to,insert:view.state.doc.slice(sel.from,sel.to)}:change&&change.from>=sel.from&&change.to<=sel.to&&(change.from!=sel.from||change.to!=sel.to)&&sel.to-sel.from-(change.to-change.from)<=4?change={from:sel.from,to:sel.to,insert:view.state.doc.slice(sel.from,change.from).append(change.insert).append(view.state.doc.slice(change.to,sel.to))}:(browser.mac||browser.android)&&change&&change.from==change.to&&change.from==sel.head-1&&/^\. ?$/.test(change.insert.toString())&&view.contentDOM.getAttribute("autocorrect")=="off"?(newSel&&change.insert.length==2&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}):browser.chrome&&change&&change.from==change.to&&change.from==sel.head&&change.insert.toString()==`
`&&view.lineWrapping&&(newSel&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}),change){if(browser.ios&&view.inputState.flushIOSKey()||browser.android&&(change.from==sel.from&&change.to==sel.to&&change.insert.length==1&&change.insert.lines==2&&dispatchKey(view.contentDOM,"Enter",13)||(change.from==sel.from-1&&change.to==sel.to&&change.insert.length==0||lastKey==8&&change.insert.length<change.to-change.from&&change.to>sel.head)&&dispatchKey(view.contentDOM,"Backspace",8)||change.from==sel.from&&change.to==sel.to+1&&change.insert.length==0&&dispatchKey(view.contentDOM,"Delete",46)))return!0;let text=change.insert.toString();view.inputState.composing>=0&&view.inputState.composing++;let defaultTr,defaultInsert=__name2(()=>defaultTr||(defaultTr=applyDefaultInsert(view,change,newSel)),"defaultInsert");return view.state.facet(inputHandler$1).some(h=>h(view,change.from,change.to,text,defaultInsert))||view.dispatch(defaultInsert()),!0}else if(newSel&&!newSel.main.eq(sel)){let scrollIntoView2=!1,userEvent="select";return view.inputState.lastSelectionTime>Date.now()-50&&(view.inputState.lastSelectionOrigin=="select"&&(scrollIntoView2=!0),userEvent=view.inputState.lastSelectionOrigin),view.dispatch({selection:newSel,scrollIntoView:scrollIntoView2,userEvent}),!0}else return!1}__name(applyDOMChange,"applyDOMChange"),__name2(applyDOMChange,"applyDOMChange");function applyDefaultInsert(view,change,newSel){let tr,startState=view.state,sel=startState.selection.main;if(change.from>=sel.from&&change.to<=sel.to&&change.to-change.from>=(sel.to-sel.from)/3&&(!newSel||newSel.main.empty&&newSel.main.from==change.from+change.insert.length)&&view.inputState.composing<0){let before=sel.from<change.from?startState.sliceDoc(sel.from,change.from):"",after=sel.to>change.to?startState.sliceDoc(change.to,sel.to):"";tr=startState.replaceSelection(view.state.toText(before+change.insert.sliceString(0,void 0,view.state.lineBreak)+after))}else{let changes=startState.changes(change),mainSel=newSel&&newSel.main.to<=changes.newLength?newSel.main:void 0;if(startState.selection.ranges.length>1&&view.inputState.composing>=0&&change.to<=sel.to&&change.to>=sel.to-10){let replaced=view.state.sliceDoc(change.from,change.to),compositionRange,composition=newSel&&findCompositionNode(view,newSel.main.head);if(composition){let dLen=change.insert.length-(change.to-change.from);compositionRange={from:composition.from,to:composition.to-dLen}}else compositionRange=view.state.doc.lineAt(sel.head);let offset2=sel.to-change.to,size=sel.to-sel.from;tr=startState.changeByRange(range=>{if(range.from==sel.from&&range.to==sel.to)return{changes,range:mainSel||range.map(changes)};let to=range.to-offset2,from=to-replaced.length;if(range.to-range.from!=size||view.state.sliceDoc(from,to)!=replaced||range.to>=compositionRange.from&&range.from<=compositionRange.to)return{range};let rangeChanges=startState.changes({from,to,insert:change.insert}),selOff=range.to-sel.to;return{changes:rangeChanges,range:mainSel?EditorSelection.range(Math.max(0,mainSel.anchor+selOff),Math.max(0,mainSel.head+selOff)):range.map(rangeChanges)}})}else tr={changes,selection:mainSel&&startState.selection.replaceRange(mainSel)}}let userEvent="input.type";return(view.composing||view.inputState.compositionPendingChange&&view.inputState.compositionEndedAt>Date.now()-50)&&(view.inputState.compositionPendingChange=!1,userEvent+=".compose",view.inputState.compositionFirstChange&&(userEvent+=".start",view.inputState.compositionFirstChange=!1)),startState.update(tr,{userEvent,scrollIntoView:!0})}__name(applyDefaultInsert,"applyDefaultInsert"),__name2(applyDefaultInsert,"applyDefaultInsert");function findDiff(a,b,preferredPos,preferredSide){let minLen=Math.min(a.length,b.length),from=0;for(;from<minLen&&a.charCodeAt(from)==b.charCodeAt(from);)from++;if(from==minLen&&a.length==b.length)return null;let toA=a.length,toB=b.length;for(;toA>0&&toB>0&&a.charCodeAt(toA-1)==b.charCodeAt(toB-1);)toA--,toB--;if(preferredSide=="end"){let adjust=Math.max(0,from-Math.min(toA,toB));preferredPos-=toA+adjust-from}if(toA<from&&a.length<b.length){let move=preferredPos<=from&&preferredPos>=toA?from-preferredPos:0;from-=move,toB=from+(toB-toA),toA=from}else if(toB<from){let move=preferredPos<=from&&preferredPos>=toB?from-preferredPos:0;from-=move,toA=from+(toA-toB),toB=from}return{from,toA,toB}}__name(findDiff,"findDiff"),__name2(findDiff,"findDiff");function selectionPoints(view){let result=[];if(view.root.activeElement!=view.contentDOM)return result;let{anchorNode,anchorOffset,focusNode,focusOffset}=view.observer.selectionRange;return anchorNode&&(result.push(new DOMPoint(anchorNode,anchorOffset)),(focusNode!=anchorNode||focusOffset!=anchorOffset)&&result.push(new DOMPoint(focusNode,focusOffset))),result}__name(selectionPoints,"selectionPoints"),__name2(selectionPoints,"selectionPoints");function selectionFromPoints(points,base2){if(points.length==0)return null;let anchor=points[0].pos,head=points.length==2?points[1].pos:anchor;return anchor>-1&&head>-1?EditorSelection.single(anchor+base2,head+base2):null}__name(selectionFromPoints,"selectionFromPoints"),__name2(selectionFromPoints,"selectionFromPoints");const observeOptions={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},useCharData=browser.ie&&browser.ie_version<=11,_DOMObserver=class{static{__name(this,"_DOMObserver")}constructor(view){this.view=view,this.active=!1,this.selectionRange=new DOMSelectionState,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.resizeContent=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.parentCheck=-1,this.dom=view.contentDOM,this.observer=new MutationObserver(mutations=>{for(let mut of mutations)this.queue.push(mut);(browser.ie&&browser.ie_version<=11||browser.ios&&view.composing)&&mutations.some(m=>m.type=="childList"&&m.removedNodes.length||m.type=="characterData"&&m.oldValue.length>m.target.nodeValue.length)?this.flushSoon():this.flush()}),useCharData&&(this.onCharData=event=>{this.queue.push({target:event.target,type:"characterData",oldValue:event.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var _a3;((_a3=this.view.docView)===null||_a3===void 0?void 0:_a3.lastUpdate)<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(view.scrollDOM),this.resizeContent=new ResizeObserver(()=>this.view.requestMeasure()),this.resizeContent.observe(view.contentDOM)),this.addWindowListeners(this.win=view.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(entries=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),entries.length>0&&entries[entries.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(entries=>{entries.length>0&&entries[entries.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(){this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500)}updateGaps(gaps){if(this.gapIntersection&&(gaps.length!=this.gaps.length||this.gaps.some((g,i)=>g!=gaps[i]))){this.gapIntersection.disconnect();for(let gap of gaps)this.gapIntersection.observe(gap);this.gaps=gaps}}onSelectionChange(event){let wasChanged=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view}=this,sel=this.selectionRange;if(view.state.facet(editable)?view.root.activeElement!=this.dom:!hasSelection(view.dom,sel))return;let context=sel.anchorNode&&view.docView.nearest(sel.anchorNode);if(context&&context.ignoreEvent(event)){wasChanged||(this.selectionChanged=!1);return}(browser.ie&&browser.ie_version<=11||browser.android&&browser.chrome)&&!view.state.selection.main.empty&&sel.focusNode&&isEquivalentPosition(sel.focusNode,sel.focusOffset,sel.anchorNode,sel.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view}=this,range=browser.safari&&view.root.nodeType==11&&deepActiveElement(this.dom.ownerDocument)==this.dom&&safariSelectionRangeHack(this.view)||getSelection(view.root);if(!range||this.selectionRange.eq(range))return!1;let local=hasSelection(this.dom,range);return local&&!this.selectionChanged&&view.inputState.lastFocusTime>Date.now()-200&&view.inputState.lastTouchTime<Date.now()-300&&atElementStart(this.dom,range)?(this.view.inputState.lastFocusTime=0,view.docView.updateSelection(),!1):(this.selectionRange.setRange(range),local&&(this.selectionChanged=!0),!0)}setSelectionRange(anchor,head){this.selectionRange.set(anchor.node,anchor.offset,head.node,head.offset),this.selectionChanged=!1}clearSelectionRange(){this.selectionRange.set(null,0,null,0)}listenForScroll(){this.parentCheck=-1;let i=0,changed=null;for(let dom=this.dom;dom;)if(dom.nodeType==1)!changed&&i<this.scrollTargets.length&&this.scrollTargets[i]==dom?i++:changed||(changed=this.scrollTargets.slice(0,i)),changed&&changed.push(dom),dom=dom.assignedSlot||dom.parentNode;else if(dom.nodeType==11)dom=dom.host;else break;if(i<this.scrollTargets.length&&!changed&&(changed=this.scrollTargets.slice(0,i)),changed){for(let dom of this.scrollTargets)dom.removeEventListener("scroll",this.onScroll);for(let dom of this.scrollTargets=changed)dom.addEventListener("scroll",this.onScroll)}}ignore(f2){if(!this.active)return f2();try{return this.stop(),f2()}finally{this.start(),this.clear()}}start(){this.active||(this.observer.observe(this.dom,observeOptions),useCharData&&this.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.active=!0)}stop(){this.active&&(this.active=!1,this.observer.disconnect(),useCharData&&this.dom.removeEventListener("DOMCharacterDataModified",this.onCharData))}clear(){this.processRecords(),this.queue.length=0,this.selectionChanged=!1}delayAndroidKey(key,keyCode){var _a3;if(!this.delayedAndroidKey){let flush=__name2(()=>{let key2=this.delayedAndroidKey;key2&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=key2.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&key2.force&&dispatchKey(this.dom,key2.key,key2.keyCode))},"flush");this.flushingAndroidKey=this.view.win.requestAnimationFrame(flush)}(!this.delayedAndroidKey||key=="Enter")&&(this.delayedAndroidKey={key,keyCode,force:this.lastChange<Date.now()-50||!!(!((_a3=this.delayedAndroidKey)===null||_a3===void 0)&&_a3.force)})}clearDelayedAndroidKey(){this.win.cancelAnimationFrame(this.flushingAndroidKey),this.delayedAndroidKey=null,this.flushingAndroidKey=-1}flushSoon(){this.delayedFlush<0&&(this.delayedFlush=this.view.win.requestAnimationFrame(()=>{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let mut of this.observer.takeRecords())this.queue.push(mut);return this.queue}processRecords(){let records=this.pendingRecords();records.length&&(this.queue=[]);let from=-1,to=-1,typeOver=!1;for(let record of records){let range=this.readMutation(record);range&&(range.typeOver&&(typeOver=!0),from==-1?{from,to}=range:(from=Math.min(range.from,from),to=Math.max(range.to,to)))}return{from,to,typeOver}}readChange(){let{from,to,typeOver}=this.processRecords(),newSel=this.selectionChanged&&hasSelection(this.dom,this.selectionRange);if(from<0&&!newSel)return null;from>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let change=new DOMChange(this.view,from,to,typeOver);return this.view.docView.domChanged={newSel:change.newSel?change.newSel.main:null},change}flush(readSelection=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;readSelection&&this.readSelectionRange();let domChange=this.readChange();if(!domChange)return!1;let startState=this.view.state,handled=applyDOMChange(this.view,domChange);return this.view.state==startState&&this.view.update([]),handled}readMutation(rec){let cView=this.view.docView.nearest(rec.target);if(!cView||cView.ignoreMutation(rec))return null;if(cView.markDirty(rec.type=="attributes"),rec.type=="attributes"&&(cView.flags|=4),rec.type=="childList"){let childBefore=findChild(cView,rec.previousSibling||rec.target.previousSibling,-1),childAfter=findChild(cView,rec.nextSibling||rec.target.nextSibling,1);return{from:childBefore?cView.posAfter(childBefore):cView.posAtStart,to:childAfter?cView.posBefore(childAfter):cView.posAtEnd,typeOver:!1}}else return rec.type=="characterData"?{from:cView.posAtStart,to:cView.posAtEnd,typeOver:rec.target.nodeValue==rec.oldValue}:null}setWindow(win){win!=this.win&&(this.removeWindowListeners(this.win),this.win=win,this.addWindowListeners(this.win))}addWindowListeners(win){win.addEventListener("resize",this.onResize),win.addEventListener("beforeprint",this.onPrint),win.addEventListener("scroll",this.onScroll),win.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(win){win.removeEventListener("scroll",this.onScroll),win.removeEventListener("resize",this.onResize),win.removeEventListener("beforeprint",this.onPrint),win.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var _a3,_b2,_c2,_d;this.stop(),(_a3=this.intersection)===null||_a3===void 0||_a3.disconnect(),(_b2=this.gapIntersection)===null||_b2===void 0||_b2.disconnect(),(_c2=this.resizeScroll)===null||_c2===void 0||_c2.disconnect(),(_d=this.resizeContent)===null||_d===void 0||_d.disconnect();for(let dom of this.scrollTargets)dom.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey)}};__name2(_DOMObserver,"DOMObserver");let DOMObserver=_DOMObserver;function findChild(cView,dom,dir){for(;dom;){let curView=ContentView.get(dom);if(curView&&curView.parent==cView)return curView;let parent=dom.parentNode;dom=parent!=cView.dom?parent:dir>0?dom.nextSibling:dom.previousSibling}return null}__name(findChild,"findChild"),__name2(findChild,"findChild");function safariSelectionRangeHack(view){let found=null;function read(event){event.preventDefault(),event.stopImmediatePropagation(),found=event.getTargetRanges()[0]}if(__name(read,"read"),__name2(read,"read"),view.contentDOM.addEventListener("beforeinput",read,!0),view.dom.ownerDocument.execCommand("indent"),view.contentDOM.removeEventListener("beforeinput",read,!0),!found)return null;let anchorNode=found.startContainer,anchorOffset=found.startOffset,focusNode=found.endContainer,focusOffset=found.endOffset,curAnchor=view.docView.domAtPos(view.state.selection.main.anchor);return isEquivalentPosition(curAnchor.node,curAnchor.offset,focusNode,focusOffset)&&([anchorNode,anchorOffset,focusNode,focusOffset]=[focusNode,focusOffset,anchorNode,anchorOffset]),{anchorNode,anchorOffset,focusNode,focusOffset}}__name(safariSelectionRangeHack,"safariSelectionRangeHack"),__name2(safariSelectionRangeHack,"safariSelectionRangeHack");const _EditorView=class _EditorView2{static{__name(this,"_EditorView")}get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(config2={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.style.cssText="position: fixed; top: -10000px",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM);let{dispatch}=config2;this.dispatchTransactions=config2.dispatchTransactions||dispatch&&(trs=>trs.forEach(tr=>dispatch(tr,this)))||(trs=>this.update(trs)),this.dispatch=this.dispatch.bind(this),this._root=config2.root||getRoot(config2.parent)||document,this.viewState=new ViewState(config2.state||EditorState.create(config2)),this.plugins=this.state.facet(viewPlugin).map(spec=>new PluginInstance(spec));for(let plugin of this.plugins)plugin.update(this);this.observer=new DOMObserver(this),this.inputState=new InputState(this),this.inputState.ensureHandlers(this.plugins),this.docView=new DocView(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),config2.parent&&config2.parent.appendChild(this.dom)}dispatch(...input){let trs=input.length==1&&input[0]instanceof Transaction?input:input.length==1&&Array.isArray(input[0])?input[0]:[this.state.update(...input)];this.dispatchTransactions(trs,this)}update(transactions){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let redrawn=!1,attrsChanged=!1,update,state=this.state;for(let tr of transactions){if(tr.startState!=state)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");state=tr.state}if(this.destroyed){this.viewState.state=state;return}let focus=this.hasFocus,focusFlag=0,dispatchFocus=null;transactions.some(tr=>tr.annotation(isFocusChange))?(this.inputState.notifiedFocused=focus,focusFlag=1):focus!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=focus,dispatchFocus=focusChangeTransaction(state,focus),dispatchFocus||(focusFlag=1));let pendingKey=this.observer.delayedAndroidKey,domChange=null;if(pendingKey?(this.observer.clearDelayedAndroidKey(),domChange=this.observer.readChange(),(domChange&&!this.state.doc.eq(state.doc)||!this.state.selection.eq(state.selection))&&(domChange=null)):this.observer.clear(),state.facet(EditorState.phrases)!=this.state.facet(EditorState.phrases))return this.setState(state);update=ViewUpdate.create(this,state,transactions),update.flags|=focusFlag;let scrollTarget=this.viewState.scrollTarget;try{this.updateState=2;for(let tr of transactions){if(scrollTarget&&(scrollTarget=scrollTarget.map(tr.changes)),tr.scrollIntoView){let{main}=tr.state.selection;scrollTarget=new ScrollTarget(main.empty?main:EditorSelection.cursor(main.head,main.head>main.anchor?-1:1))}for(let e of tr.effects)e.is(scrollIntoView$1)&&(scrollTarget=e.value)}this.viewState.update(update,scrollTarget),this.bidiCache=CachedOrder.update(this.bidiCache,update.changes),update.empty||(this.updatePlugins(update),this.inputState.update(update)),redrawn=this.docView.update(update),this.state.facet(styleModule)!=this.styleModules&&this.mountStyles(),attrsChanged=this.updateAttrs(),this.showAnnouncements(transactions),this.docView.updateSelection(redrawn,transactions.some(tr=>tr.isUserEvent("select.pointer")))}finally{this.updateState=0}if(update.startState.facet(theme)!=update.state.facet(theme)&&(this.viewState.mustMeasureContent=!0),(redrawn||attrsChanged||scrollTarget||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),!update.empty)for(let listener of this.state.facet(updateListener))listener(update);(dispatchFocus||domChange)&&Promise.resolve().then(()=>{dispatchFocus&&this.state==dispatchFocus.startState&&this.dispatch(dispatchFocus),domChange&&!applyDOMChange(this,domChange)&&pendingKey.force&&dispatchKey(this.contentDOM,pendingKey.key,pendingKey.keyCode)})}setState(newState){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=newState;return}this.updateState=2;let hadFocus=this.hasFocus;try{for(let plugin of this.plugins)plugin.destroy(this);this.viewState=new ViewState(newState),this.plugins=newState.facet(viewPlugin).map(spec=>new PluginInstance(spec)),this.pluginMap.clear();for(let plugin of this.plugins)plugin.update(this);this.docView=new DocView(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}hadFocus&&this.focus(),this.requestMeasure()}updatePlugins(update){let prevSpecs=update.startState.facet(viewPlugin),specs=update.state.facet(viewPlugin);if(prevSpecs!=specs){let newPlugins=[];for(let spec of specs){let found=prevSpecs.indexOf(spec);if(found<0)newPlugins.push(new PluginInstance(spec));else{let plugin=this.plugins[found];plugin.mustUpdate=update,newPlugins.push(plugin)}}for(let plugin of this.plugins)plugin.mustUpdate!=update&&plugin.destroy(this);this.plugins=newPlugins,this.pluginMap.clear()}else for(let p of this.plugins)p.mustUpdate=update;for(let i=0;i<this.plugins.length;i++)this.plugins[i].update(this);prevSpecs!=specs&&this.inputState.ensureHandlers(this.plugins)}measure(flush=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,flush&&this.observer.forceFlush();let updated=null,sDOM=this.scrollDOM,scrollTop=sDOM.scrollTop*this.scaleY,{scrollAnchorPos,scrollAnchorHeight}=this.viewState;Math.abs(scrollTop-this.viewState.scrollTop)>1&&(scrollAnchorHeight=-1),this.viewState.scrollAnchorHeight=-1;try{for(let i=0;;i++){if(scrollAnchorHeight<0)if(isScrolledToBottom(sDOM))scrollAnchorPos=-1,scrollAnchorHeight=this.viewState.heightMap.height;else{let block=this.viewState.scrollAnchorAt(scrollTop);scrollAnchorPos=block.from,scrollAnchorHeight=block.top}this.updateState=1;let changed=this.viewState.measure(this);if(!changed&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(i>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let measuring=[];changed&4||([this.measureRequests,measuring]=[measuring,this.measureRequests]);let measured=measuring.map(m=>{try{return m.read(this)}catch(e){return logException(this.state,e),BadMeasure}}),update=ViewUpdate.create(this,this.state,[]),redrawn=!1;update.flags|=changed,updated?updated.flags|=changed:updated=update,this.updateState=2,update.empty||(this.updatePlugins(update),this.inputState.update(update),this.updateAttrs(),redrawn=this.docView.update(update));for(let i2=0;i2<measuring.length;i2++)if(measured[i2]!=BadMeasure)try{let m=measuring[i2];m.write&&m.write(measured[i2],this)}catch(e){logException(this.state,e)}if(redrawn&&this.docView.updateSelection(!0),!update.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight)if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null;continue}else{let diff2=(scrollAnchorPos<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(scrollAnchorPos).top)-scrollAnchorHeight;if(diff2>1||diff2<-1){scrollTop=scrollTop+diff2,sDOM.scrollTop=scrollTop/this.scaleY,scrollAnchorHeight=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(updated&&!updated.empty)for(let listener of this.state.facet(updateListener))listener(updated)}get themeClasses(){return baseThemeID+" "+(this.state.facet(darkTheme)?baseDarkID:baseLightID)+" "+this.state.facet(theme)}updateAttrs(){let editorAttrs=attrsFromFacet(this,editorAttributes,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),contentAttrs={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(editable)?"true":"false",class:"cm-content",style:`${browser.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(contentAttrs["aria-readonly"]="true"),attrsFromFacet(this,contentAttributes,contentAttrs);let changed=this.observer.ignore(()=>{let changedContent=updateAttrs(this.contentDOM,this.contentAttrs,contentAttrs),changedEditor=updateAttrs(this.dom,this.editorAttrs,editorAttrs);return changedContent||changedEditor});return this.editorAttrs=editorAttrs,this.contentAttrs=contentAttrs,changed}showAnnouncements(trs){let first=!0;for(let tr of trs)for(let effect of tr.effects)if(effect.is(_EditorView2.announce)){first&&(this.announceDOM.textContent=""),first=!1;let div=this.announceDOM.appendChild(document.createElement("div"));div.textContent=effect.value}}mountStyles(){this.styleModules=this.state.facet(styleModule);let nonce=this.state.facet(_EditorView2.cspNonce);StyleModule.mount(this.root,this.styleModules.concat(baseTheme$1$2).reverse(),nonce?{nonce}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(request){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),request){if(this.measureRequests.indexOf(request)>-1)return;if(request.key!=null){for(let i=0;i<this.measureRequests.length;i++)if(this.measureRequests[i].key===request.key){this.measureRequests[i]=request;return}}this.measureRequests.push(request)}}plugin(plugin){let known=this.pluginMap.get(plugin);return(known===void 0||known&&known.spec!=plugin)&&this.pluginMap.set(plugin,known=this.plugins.find(p=>p.spec==plugin)||null),known&&known.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(height){return this.readMeasured(),this.viewState.elementAtHeight(height)}lineBlockAtHeight(height){return this.readMeasured(),this.viewState.lineBlockAtHeight(height)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(pos){return this.viewState.lineBlockAt(pos)}get contentHeight(){return this.viewState.contentHeight}moveByChar(start,forward,by){return skipAtoms(this,start,moveByChar(this,start,forward,by))}moveByGroup(start,forward){return skipAtoms(this,start,moveByChar(this,start,forward,initial=>byGroup(this,start.head,initial)))}moveToLineBoundary(start,forward,includeWrap=!0){return moveToLineBoundary(this,start,forward,includeWrap)}moveVertically(start,forward,distance){return skipAtoms(this,start,moveVertically(this,start,forward,distance))}domAtPos(pos){return this.docView.domAtPos(pos)}posAtDOM(node,offset2=0){return this.docView.posFromDOM(node,offset2)}posAtCoords(coords,precise=!0){return this.readMeasured(),posAtCoords(this,coords,precise)}coordsAtPos(pos,side=1){this.readMeasured();let rect=this.docView.coordsAt(pos,side);if(!rect||rect.left==rect.right)return rect;let line=this.state.doc.lineAt(pos),order=this.bidiSpans(line),span=order[BidiSpan.find(order,pos-line.from,-1,side)];return flattenRect(rect,span.dir==Direction.LTR==side>0)}coordsForChar(pos){return this.readMeasured(),this.docView.coordsForChar(pos)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(pos){return!this.state.facet(perLineTextDirection)||pos<this.viewport.from||pos>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(pos))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(line){if(line.length>MaxBidiLine)return trivialOrder(line.length);let dir=this.textDirectionAt(line.from),isolates;for(let entry of this.bidiCache)if(entry.from==line.from&&entry.dir==dir&&(entry.fresh||isolatesEq(entry.isolates,isolates=getIsolatedRanges(this,line.from,line.to))))return entry.order;isolates||(isolates=getIsolatedRanges(this,line.from,line.to));let order=computeOrder(line.text,dir,isolates);return this.bidiCache.push(new CachedOrder(line.from,line.to,dir,isolates,!0,order)),order}get hasFocus(){var _a3;return(this.dom.ownerDocument.hasFocus()||browser.safari&&((_a3=this.inputState)===null||_a3===void 0?void 0:_a3.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{focusPreventScroll(this.contentDOM),this.docView.updateSelection()})}setRoot(root){this._root!=root&&(this._root=root,this.observer.setWindow((root.nodeType==9?root:root.ownerDocument).defaultView||window),this.mountStyles())}destroy(){for(let plugin of this.plugins)plugin.destroy(this);this.plugins=[],this.inputState.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(pos,options={}){return scrollIntoView$1.of(new ScrollTarget(typeof pos=="number"?EditorSelection.cursor(pos):pos,options.y,options.x,options.yMargin,options.xMargin))}static domEventHandlers(handlers2){return ViewPlugin.define(()=>({}),{eventHandlers:handlers2})}static domEventObservers(observers2){return ViewPlugin.define(()=>({}),{eventObservers:observers2})}static theme(spec,options){let prefix=StyleModule.newName(),result=[theme.of(prefix),styleModule.of(buildTheme(`.${prefix}`,spec))];return options&&options.dark&&result.push(darkTheme.of(!0)),result}static baseTheme(spec){return Prec.lowest(styleModule.of(buildTheme("."+baseThemeID,spec,lightDarkIDs)))}static findFromDOM(dom){var _a3;let content2=dom.querySelector(".cm-content"),cView=content2&&ContentView.get(content2)||ContentView.get(dom);return((_a3=cView?.rootView)===null||_a3===void 0?void 0:_a3.view)||null}};__name2(_EditorView,"EditorView");let EditorView=_EditorView;EditorView.styleModule=styleModule,EditorView.inputHandler=inputHandler$1,EditorView.focusChangeEffect=focusChangeEffect,EditorView.perLineTextDirection=perLineTextDirection,EditorView.exceptionSink=exceptionSink,EditorView.updateListener=updateListener,EditorView.editable=editable,EditorView.mouseSelectionStyle=mouseSelectionStyle,EditorView.dragMovesSelection=dragMovesSelection$1,EditorView.clickAddsSelectionRange=clickAddsSelectionRange,EditorView.decorations=decorations,EditorView.atomicRanges=atomicRanges,EditorView.bidiIsolatedRanges=bidiIsolatedRanges,EditorView.scrollMargins=scrollMargins,EditorView.darkTheme=darkTheme,EditorView.cspNonce=Facet.define({combine:values=>values.length?values[0]:""}),EditorView.contentAttributes=contentAttributes,EditorView.editorAttributes=editorAttributes,EditorView.lineWrapping=EditorView.contentAttributes.of({class:"cm-lineWrapping"}),EditorView.announce=StateEffect.define();const MaxBidiLine=4096,BadMeasure={},_CachedOrder=class _CachedOrder2{static{__name(this,"_CachedOrder")}constructor(from,to,dir,isolates,fresh,order){this.from=from,this.to=to,this.dir=dir,this.isolates=isolates,this.fresh=fresh,this.order=order}static update(cache,changes){if(changes.empty&&!cache.some(c=>c.fresh))return cache;let result=[],lastDir=cache.length?cache[cache.length-1].dir:Direction.LTR;for(let i=Math.max(0,cache.length-10);i<cache.length;i++){let entry=cache[i];entry.dir==lastDir&&!changes.touchesRange(entry.from,entry.to)&&result.push(new _CachedOrder2(changes.mapPos(entry.from,1),changes.mapPos(entry.to,-1),entry.dir,entry.isolates,!1,entry.order))}return result}};__name2(_CachedOrder,"CachedOrder");let CachedOrder=_CachedOrder;function attrsFromFacet(view,facet,base2){for(let sources=view.state.facet(facet),i=sources.length-1;i>=0;i--){let source=sources[i],value=typeof source=="function"?source(view):source;value&&combineAttrs(value,base2)}return base2}__name(attrsFromFacet,"attrsFromFacet"),__name2(attrsFromFacet,"attrsFromFacet");const currentPlatform=browser.mac?"mac":browser.windows?"win":browser.linux?"linux":"key";function normalizeKeyName(name2,platform){const parts=name2.split(/-(?!$)/);let result=parts[parts.length-1];result=="Space"&&(result=" ");let alt,ctrl,shift2,meta2;for(let i=0;i<parts.length-1;++i){const mod=parts[i];if(/^(cmd|meta|m)$/i.test(mod))meta2=!0;else if(/^a(lt)?$/i.test(mod))alt=!0;else if(/^(c|ctrl|control)$/i.test(mod))ctrl=!0;else if(/^s(hift)?$/i.test(mod))shift2=!0;else if(/^mod$/i.test(mod))platform=="mac"?meta2=!0:ctrl=!0;else throw new Error("Unrecognized modifier name: "+mod)}return alt&&(result="Alt-"+result),ctrl&&(result="Ctrl-"+result),meta2&&(result="Meta-"+result),shift2&&(result="Shift-"+result),result}__name(normalizeKeyName,"normalizeKeyName"),__name2(normalizeKeyName,"normalizeKeyName");function modifiers(name2,event,shift2){return event.altKey&&(name2="Alt-"+name2),event.ctrlKey&&(name2="Ctrl-"+name2),event.metaKey&&(name2="Meta-"+name2),shift2!==!1&&event.shiftKey&&(name2="Shift-"+name2),name2}__name(modifiers,"modifiers"),__name2(modifiers,"modifiers");const handleKeyEvents=Prec.default(EditorView.domEventHandlers({keydown(event,view){return runHandlers(getKeymap(view.state),event,view,"editor")}})),keymap=Facet.define({enables:handleKeyEvents}),Keymaps=new WeakMap;function getKeymap(state){let bindings=state.facet(keymap),map2=Keymaps.get(bindings);return map2||Keymaps.set(bindings,map2=buildKeymap(bindings.reduce((a,b)=>a.concat(b),[]))),map2}__name(getKeymap,"getKeymap"),__name2(getKeymap,"getKeymap");function runScopeHandlers(view,event,scope2){return runHandlers(getKeymap(view.state),event,view,scope2)}__name(runScopeHandlers,"runScopeHandlers"),__name2(runScopeHandlers,"runScopeHandlers");let storedPrefix=null;const PrefixTimeout=4e3;function buildKeymap(bindings,platform=currentPlatform){let bound=Object.create(null),isPrefix=Object.create(null),checkPrefix=__name2((name2,is2)=>{let current=isPrefix[name2];if(current==null)isPrefix[name2]=is2;else if(current!=is2)throw new Error("Key binding "+name2+" is used both as a regular binding and as a multi-stroke prefix")},"checkPrefix"),add2=__name2((scope2,key,command2,preventDefault2,stopPropagation)=>{var _a3,_b2;let scopeObj=bound[scope2]||(bound[scope2]=Object.create(null)),parts=key.split(/ (?!$)/).map(k=>normalizeKeyName(k,platform));for(let i=1;i<parts.length;i++){let prefix=parts.slice(0,i).join(" ");checkPrefix(prefix,!0),scopeObj[prefix]||(scopeObj[prefix]={preventDefault:!0,stopPropagation:!1,run:[view=>{let ourObj=storedPrefix={view,prefix,scope:scope2};return setTimeout(()=>{storedPrefix==ourObj&&(storedPrefix=null)},PrefixTimeout),!0}]})}let full=parts.join(" ");checkPrefix(full,!1);let binding=scopeObj[full]||(scopeObj[full]={preventDefault:!1,stopPropagation:!1,run:((_b2=(_a3=scopeObj._any)===null||_a3===void 0?void 0:_a3.run)===null||_b2===void 0?void 0:_b2.slice())||[]});command2&&binding.run.push(command2),preventDefault2&&(binding.preventDefault=!0),stopPropagation&&(binding.stopPropagation=!0)},"add");for(let b of bindings){let scopes=b.scope?b.scope.split(" "):["editor"];if(b.any)for(let scope2 of scopes){let scopeObj=bound[scope2]||(bound[scope2]=Object.create(null));scopeObj._any||(scopeObj._any={preventDefault:!1,stopPropagation:!1,run:[]});for(let key in scopeObj)scopeObj[key].run.push(b.any)}let name2=b[platform]||b.key;if(name2)for(let scope2 of scopes)add2(scope2,name2,b.run,b.preventDefault,b.stopPropagation),b.shift&&add2(scope2,"Shift-"+name2,b.shift,b.preventDefault,b.stopPropagation)}return bound}__name(buildKeymap,"buildKeymap"),__name2(buildKeymap,"buildKeymap");function runHandlers(map2,event,view,scope2){let name2=keyName(event),charCode=codePointAt(name2,0),isChar=codePointSize(charCode)==name2.length&&name2!=" ",prefix="",handled=!1,prevented=!1,stopPropagation=!1;storedPrefix&&storedPrefix.view==view&&storedPrefix.scope==scope2&&(prefix=storedPrefix.prefix+" ",modifierCodes.indexOf(event.keyCode)<0&&(prevented=!0,storedPrefix=null));let ran=new Set,runFor=__name2(binding=>{if(binding){for(let cmd2 of binding.run)if(!ran.has(cmd2)&&(ran.add(cmd2),cmd2(view,event)))return binding.stopPropagation&&(stopPropagation=!0),!0;binding.preventDefault&&(binding.stopPropagation&&(stopPropagation=!0),prevented=!0)}return!1},"runFor"),scopeObj=map2[scope2],baseName,shiftName;return scopeObj&&(runFor(scopeObj[prefix+modifiers(name2,event,!isChar)])?handled=!0:isChar&&(event.altKey||event.metaKey||event.ctrlKey)&&!(browser.windows&&event.ctrlKey&&event.altKey)&&(baseName=base[event.keyCode])&&baseName!=name2?(runFor(scopeObj[prefix+modifiers(baseName,event,!0)])||event.shiftKey&&(shiftName=shift[event.keyCode])!=name2&&shiftName!=baseName&&runFor(scopeObj[prefix+modifiers(shiftName,event,!1)]))&&(handled=!0):isChar&&event.shiftKey&&runFor(scopeObj[prefix+modifiers(name2,event,!0)])&&(handled=!0),!handled&&runFor(scopeObj._any)&&(handled=!0)),prevented&&(handled=!0),handled&&stopPropagation&&event.stopPropagation(),handled}__name(runHandlers,"runHandlers"),__name2(runHandlers,"runHandlers");const _RectangleMarker=class _RectangleMarker2{static{__name(this,"_RectangleMarker")}constructor(className,left,top2,width,height){this.className=className,this.left=left,this.top=top2,this.width=width,this.height=height}draw(){let elt=document.createElement("div");return elt.className=this.className,this.adjust(elt),elt}update(elt,prev){return prev.className!=this.className?!1:(this.adjust(elt),!0)}adjust(elt){elt.style.left=this.left+"px",elt.style.top=this.top+"px",this.width!=null&&(elt.style.width=this.width+"px"),elt.style.height=this.height+"px"}eq(p){return this.left==p.left&&this.top==p.top&&this.width==p.width&&this.height==p.height&&this.className==p.className}static forRange(view,className,range){if(range.empty){let pos=view.coordsAtPos(range.head,range.assoc||1);if(!pos)return[];let base2=getBase(view);return[new _RectangleMarker2(className,pos.left-base2.left,pos.top-base2.top,null,pos.bottom-pos.top)]}else return rectanglesForRange(view,className,range)}};__name2(_RectangleMarker,"RectangleMarker");let RectangleMarker=_RectangleMarker;function getBase(view){let rect=view.scrollDOM.getBoundingClientRect();return{left:(view.textDirection==Direction.LTR?rect.left:rect.right-view.scrollDOM.clientWidth*view.scaleX)-view.scrollDOM.scrollLeft*view.scaleX,top:rect.top-view.scrollDOM.scrollTop*view.scaleY}}__name(getBase,"getBase"),__name2(getBase,"getBase");function wrappedLine(view,pos,inside2){let range=EditorSelection.cursor(pos);return{from:Math.max(inside2.from,view.moveToLineBoundary(range,!1,!0).from),to:Math.min(inside2.to,view.moveToLineBoundary(range,!0,!0).from),type:BlockType.Text}}__name(wrappedLine,"wrappedLine"),__name2(wrappedLine,"wrappedLine");function rectanglesForRange(view,className,range){if(range.to<=view.viewport.from||range.from>=view.viewport.to)return[];let from=Math.max(range.from,view.viewport.from),to=Math.min(range.to,view.viewport.to),ltr=view.textDirection==Direction.LTR,content2=view.contentDOM,contentRect=content2.getBoundingClientRect(),base2=getBase(view),lineElt=content2.querySelector(".cm-line"),lineStyle=lineElt&&window.getComputedStyle(lineElt),leftSide=contentRect.left+(lineStyle?parseInt(lineStyle.paddingLeft)+Math.min(0,parseInt(lineStyle.textIndent)):0),rightSide=contentRect.right-(lineStyle?parseInt(lineStyle.paddingRight):0),startBlock=blockAt(view,from),endBlock=blockAt(view,to),visualStart=startBlock.type==BlockType.Text?startBlock:null,visualEnd=endBlock.type==BlockType.Text?endBlock:null;if(visualStart&&(view.lineWrapping||startBlock.widgetLineBreaks)&&(visualStart=wrappedLine(view,from,visualStart)),visualEnd&&(view.lineWrapping||endBlock.widgetLineBreaks)&&(visualEnd=wrappedLine(view,to,visualEnd)),visualStart&&visualEnd&&visualStart.from==visualEnd.from)return pieces(drawForLine(range.from,range.to,visualStart));{let top2=visualStart?drawForLine(range.from,null,visualStart):drawForWidget(startBlock,!1),bottom=visualEnd?drawForLine(null,range.to,visualEnd):drawForWidget(endBlock,!0),between=[];return(visualStart||startBlock).to<(visualEnd||endBlock).from-(visualStart&&visualEnd?1:0)||startBlock.widgetLineBreaks>1&&top2.bottom+view.defaultLineHeight/2<bottom.top?between.push(piece(leftSide,top2.bottom,rightSide,bottom.top)):top2.bottom<bottom.top&&view.elementAtHeight((top2.bottom+bottom.top)/2).type==BlockType.Text&&(top2.bottom=bottom.top=(top2.bottom+bottom.top)/2),pieces(top2).concat(between).concat(pieces(bottom))}function piece(left,top2,right,bottom){return new RectangleMarker(className,left-base2.left,top2-base2.top-.01,right-left,bottom-top2+.01)}__name(piece,"piece"),__name2(piece,"piece");function pieces({top:top2,bottom,horizontal}){let pieces2=[];for(let i=0;i<horizontal.length;i+=2)pieces2.push(piece(horizontal[i],top2,horizontal[i+1],bottom));return pieces2}__name(pieces,"pieces"),__name2(pieces,"pieces");function drawForLine(from2,to2,line){let top2=1e9,bottom=-1e9,horizontal=[];function addSpan(from3,fromOpen,to3,toOpen,dir){let fromCoords=view.coordsAtPos(from3,from3==line.to?-2:2),toCoords=view.coordsAtPos(to3,to3==line.from?2:-2);!fromCoords||!toCoords||(top2=Math.min(fromCoords.top,toCoords.top,top2),bottom=Math.max(fromCoords.bottom,toCoords.bottom,bottom),dir==Direction.LTR?horizontal.push(ltr&&fromOpen?leftSide:fromCoords.left,ltr&&toOpen?rightSide:toCoords.right):horizontal.push(!ltr&&toOpen?leftSide:toCoords.left,!ltr&&fromOpen?rightSide:fromCoords.right))}__name(addSpan,"addSpan"),__name2(addSpan,"addSpan");let start=from2??line.from,end=to2??line.to;for(let r of view.visibleRanges)if(r.to>start&&r.from<end)for(let pos=Math.max(r.from,start),endPos=Math.min(r.to,end);;){let docLine=view.state.doc.lineAt(pos);for(let span of view.bidiSpans(docLine)){let spanFrom=span.from+docLine.from,spanTo=span.to+docLine.from;if(spanFrom>=endPos)break;spanTo>pos&&addSpan(Math.max(spanFrom,pos),from2==null&&spanFrom<=start,Math.min(spanTo,endPos),to2==null&&spanTo>=end,span.dir)}if(pos=docLine.to+1,pos>=endPos)break}return horizontal.length==0&&addSpan(start,from2==null,end,to2==null,view.textDirection),{top:top2,bottom,horizontal}}__name(drawForLine,"drawForLine"),__name2(drawForLine,"drawForLine");function drawForWidget(block,top2){let y=contentRect.top+(top2?block.top:block.bottom);return{top:y,bottom:y,horizontal:[]}}__name(drawForWidget,"drawForWidget"),__name2(drawForWidget,"drawForWidget")}__name(rectanglesForRange,"rectanglesForRange"),__name2(rectanglesForRange,"rectanglesForRange");function sameMarker(a,b){return a.constructor==b.constructor&&a.eq(b)}__name(sameMarker,"sameMarker"),__name2(sameMarker,"sameMarker");const _LayerView=class{static{__name(this,"_LayerView")}constructor(view,layer2){this.view=view,this.layer=layer2,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=view.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),layer2.above&&this.dom.classList.add("cm-layer-above"),layer2.class&&this.dom.classList.add(layer2.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(view.state),view.requestMeasure(this.measureReq),layer2.mount&&layer2.mount(this.dom,view)}update(update){update.startState.facet(layerOrder)!=update.state.facet(layerOrder)&&this.setOrder(update.state),(this.layer.update(update,this.dom)||update.geometryChanged)&&(this.scale(),update.view.requestMeasure(this.measureReq))}setOrder(state){let pos=0,order=state.facet(layerOrder);for(;pos<order.length&&order[pos]!=this.layer;)pos++;this.dom.style.zIndex=String((this.layer.above?150:-1)-pos)}measure(){return this.layer.markers(this.view)}scale(){let{scaleX,scaleY}=this.view;(scaleX!=this.scaleX||scaleY!=this.scaleY)&&(this.scaleX=scaleX,this.scaleY=scaleY,this.dom.style.transform=`scale(${1/scaleX}, ${1/scaleY})`)}draw(markers){if(markers.length!=this.drawn.length||markers.some((p,i)=>!sameMarker(p,this.drawn[i]))){let old=this.dom.firstChild,oldI=0;for(let marker of markers)marker.update&&old&&marker.constructor&&this.drawn[oldI].constructor&&marker.update(old,this.drawn[oldI])?(old=old.nextSibling,oldI++):this.dom.insertBefore(marker.draw(),old);for(;old;){let next=old.nextSibling;old.remove(),old=next}this.drawn=markers}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}};__name2(_LayerView,"LayerView");let LayerView=_LayerView;const layerOrder=Facet.define();function layer(config2){return[ViewPlugin.define(v=>new LayerView(v,config2)),layerOrder.of(config2)]}__name(layer,"layer"),__name2(layer,"layer");const CanHidePrimary=!browser.ios,selectionConfig=Facet.define({combine(configs){return combineConfig(configs,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(a,b)=>Math.min(a,b),drawRangeCursor:(a,b)=>a||b})}});function drawSelection(config2={}){return[selectionConfig.of(config2),cursorLayer,selectionLayer,hideNativeSelection,nativeSelectionHidden.of(!0)]}__name(drawSelection,"drawSelection"),__name2(drawSelection,"drawSelection");function configChanged(update){return update.startState.facet(selectionConfig)!=update.state.facet(selectionConfig)}__name(configChanged,"configChanged"),__name2(configChanged,"configChanged");const cursorLayer=layer({above:!0,markers(view){let{state}=view,conf=state.facet(selectionConfig),cursors=[];for(let r of state.selection.ranges){let prim=r==state.selection.main;if(r.empty?!prim||CanHidePrimary:conf.drawRangeCursor){let className=prim?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",cursor=r.empty?r:EditorSelection.cursor(r.head,r.head>r.anchor?-1:1);for(let piece of RectangleMarker.forRange(view,className,cursor))cursors.push(piece)}}return cursors},update(update,dom){update.transactions.some(tr=>tr.selection)&&(dom.style.animationName=dom.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let confChange=configChanged(update);return confChange&&setBlinkRate(update.state,dom),update.docChanged||update.selectionSet||confChange},mount(dom,view){setBlinkRate(view.state,dom)},class:"cm-cursorLayer"});function setBlinkRate(state,dom){dom.style.animationDuration=state.facet(selectionConfig).cursorBlinkRate+"ms"}__name(setBlinkRate,"setBlinkRate"),__name2(setBlinkRate,"setBlinkRate");const selectionLayer=layer({above:!1,markers(view){return view.state.selection.ranges.map(r=>r.empty?[]:RectangleMarker.forRange(view,"cm-selectionBackground",r)).reduce((a,b)=>a.concat(b))},update(update,dom){return update.docChanged||update.selectionSet||update.viewportChanged||configChanged(update)},class:"cm-selectionLayer"}),themeSpec={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};CanHidePrimary&&(themeSpec[".cm-line"].caretColor="transparent !important");const hideNativeSelection=Prec.highest(EditorView.theme(themeSpec)),setDropCursorPos=StateEffect.define({map(pos,mapping){return pos==null?null:mapping.mapPos(pos)}}),dropCursorPos=StateField.define({create(){return null},update(pos,tr){return pos!=null&&(pos=tr.changes.mapPos(pos)),tr.effects.reduce((pos2,e)=>e.is(setDropCursorPos)?e.value:pos2,pos)}}),drawDropCursor=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(update){var _a3;let cursorPos=update.state.field(dropCursorPos);cursorPos==null?this.cursor!=null&&((_a3=this.cursor)===null||_a3===void 0||_a3.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(update.startState.field(dropCursorPos)!=cursorPos||update.docChanged||update.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view}=this,pos=view.state.field(dropCursorPos),rect=pos!=null&&view.coordsAtPos(pos);if(!rect)return null;let outer=view.scrollDOM.getBoundingClientRect();return{left:rect.left-outer.left+view.scrollDOM.scrollLeft*view.scaleX,top:rect.top-outer.top+view.scrollDOM.scrollTop*view.scaleY,height:rect.bottom-rect.top}}drawCursor(pos){if(this.cursor){let{scaleX,scaleY}=this.view;pos?(this.cursor.style.left=pos.left/scaleX+"px",this.cursor.style.top=pos.top/scaleY+"px",this.cursor.style.height=pos.height/scaleY+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(pos){this.view.state.field(dropCursorPos)!=pos&&this.view.dispatch({effects:setDropCursorPos.of(pos)})}},{eventObservers:{dragover(event){this.setDropPos(this.view.posAtCoords({x:event.clientX,y:event.clientY}))},dragleave(event){(event.target==this.view.contentDOM||!this.view.contentDOM.contains(event.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function dropCursor(){return[dropCursorPos,drawDropCursor]}__name(dropCursor,"dropCursor"),__name2(dropCursor,"dropCursor");function iterMatches(doc2,re,from,to,f2){re.lastIndex=0;for(let cursor=doc2.iterRange(from,to),pos=from,m;!cursor.next().done;pos+=cursor.value.length)if(!cursor.lineBreak)for(;m=re.exec(cursor.value);)f2(pos+m.index,m)}__name(iterMatches,"iterMatches"),__name2(iterMatches,"iterMatches");function matchRanges(view,maxLength){let visible=view.visibleRanges;if(visible.length==1&&visible[0].from==view.viewport.from&&visible[0].to==view.viewport.to)return visible;let result=[];for(let{from,to}of visible)from=Math.max(view.state.doc.lineAt(from).from,from-maxLength),to=Math.min(view.state.doc.lineAt(to).to,to+maxLength),result.length&&result[result.length-1].to>=from?result[result.length-1].to=to:result.push({from,to});return result}__name(matchRanges,"matchRanges"),__name2(matchRanges,"matchRanges");const _MatchDecorator=class{static{__name(this,"_MatchDecorator")}constructor(config2){const{regexp,decoration,decorate,boundary,maxLength=1e3}=config2;if(!regexp.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=regexp,decorate)this.addMatch=(match2,view,from,add2)=>decorate(add2,from,from+match2[0].length,match2,view);else if(typeof decoration=="function")this.addMatch=(match2,view,from,add2)=>{let deco=decoration(match2,view,from);deco&&add2(from,from+match2[0].length,deco)};else if(decoration)this.addMatch=(match2,_view,from,add2)=>add2(from,from+match2[0].length,decoration);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=boundary,this.maxLength=maxLength}createDeco(view){let build=new RangeSetBuilder,add2=build.add.bind(build);for(let{from,to}of matchRanges(view,this.maxLength))iterMatches(view.state.doc,this.regexp,from,to,(from2,m)=>this.addMatch(m,view,from2,add2));return build.finish()}updateDeco(update,deco){let changeFrom=1e9,changeTo=-1;return update.docChanged&&update.changes.iterChanges((_f,_t,from,to)=>{to>update.view.viewport.from&&from<update.view.viewport.to&&(changeFrom=Math.min(from,changeFrom),changeTo=Math.max(to,changeTo))}),update.viewportChanged||changeTo-changeFrom>1e3?this.createDeco(update.view):changeTo>-1?this.updateRange(update.view,deco.map(update.changes),changeFrom,changeTo):deco}updateRange(view,deco,updateFrom,updateTo){for(let r of view.visibleRanges){let from=Math.max(r.from,updateFrom),to=Math.min(r.to,updateTo);if(to>from){let fromLine=view.state.doc.lineAt(from),toLine=fromLine.to<to?view.state.doc.lineAt(to):fromLine,start=Math.max(r.from,fromLine.from),end=Math.min(r.to,toLine.to);if(this.boundary){for(;from>fromLine.from;from--)if(this.boundary.test(fromLine.text[from-1-fromLine.from])){start=from;break}for(;to<toLine.to;to++)if(this.boundary.test(toLine.text[to-toLine.from])){end=to;break}}let ranges=[],m,add2=__name2((from2,to2,deco2)=>ranges.push(deco2.range(from2,to2)),"add");if(fromLine==toLine)for(this.regexp.lastIndex=start-fromLine.from;(m=this.regexp.exec(fromLine.text))&&m.index<end-fromLine.from;)this.addMatch(m,view,m.index+fromLine.from,add2);else iterMatches(view.state.doc,this.regexp,start,end,(from2,m2)=>this.addMatch(m2,view,from2,add2));deco=deco.update({filterFrom:start,filterTo:end,filter:(from2,to2)=>from2<start||to2>end,add:ranges})}}return deco}};__name2(_MatchDecorator,"MatchDecorator");let MatchDecorator=_MatchDecorator;const UnicodeRegexpSupport=/x/.unicode!=null?"gu":"g",Specials=new RegExp(`[\0-\b
-\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,UnicodeRegexpSupport),Names={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let _supportsTabSize=null;function supportsTabSize(){var _a3;if(_supportsTabSize==null&&typeof document<"u"&&document.body){let styles=document.body.style;_supportsTabSize=((_a3=styles.tabSize)!==null&&_a3!==void 0?_a3:styles.MozTabSize)!=null}return _supportsTabSize||!1}__name(supportsTabSize,"supportsTabSize"),__name2(supportsTabSize,"supportsTabSize");const specialCharConfig=Facet.define({combine(configs){let config2=combineConfig(configs,{render:null,specialChars:Specials,addSpecialChars:null});return(config2.replaceTabs=!supportsTabSize())&&(config2.specialChars=new RegExp(" |"+config2.specialChars.source,UnicodeRegexpSupport)),config2.addSpecialChars&&(config2.specialChars=new RegExp(config2.specialChars.source+"|"+config2.addSpecialChars.source,UnicodeRegexpSupport)),config2}});function highlightSpecialChars(config2={}){return[specialCharConfig.of(config2),specialCharPlugin()]}__name(highlightSpecialChars,"highlightSpecialChars"),__name2(highlightSpecialChars,"highlightSpecialChars");let _plugin=null;function specialCharPlugin(){return _plugin||(_plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=Decoration.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(view.state.facet(specialCharConfig)),this.decorations=this.decorator.createDeco(view)}makeDecorator(conf){return new MatchDecorator({regexp:conf.specialChars,decoration:(m,view,pos)=>{let{doc:doc2}=view.state,code=codePointAt(m[0],0);if(code==9){let line=doc2.lineAt(pos),size=view.state.tabSize,col=countColumn(line.text,size,pos-line.from);return Decoration.replace({widget:new TabWidget((size-col%size)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[code]||(this.decorationCache[code]=Decoration.replace({widget:new SpecialCharWidget(conf,code)}))},boundary:conf.replaceTabs?void 0:/[^]/})}update(update){let conf=update.state.facet(specialCharConfig);update.startState.facet(specialCharConfig)!=conf?(this.decorator=this.makeDecorator(conf),this.decorations=this.decorator.createDeco(update.view)):this.decorations=this.decorator.updateDeco(update,this.decorations)}},{decorations:v=>v.decorations}))}__name(specialCharPlugin,"specialCharPlugin"),__name2(specialCharPlugin,"specialCharPlugin");const DefaultPlaceholder="\u2022";function placeholder$1(code){return code>=32?DefaultPlaceholder:code==10?"\u2424":String.fromCharCode(9216+code)}__name(placeholder$1,"placeholder$1"),__name2(placeholder$1,"placeholder$1");const _SpecialCharWidget=class extends WidgetType{static{__name(this,"_SpecialCharWidget")}constructor(options,code){super(),this.options=options,this.code=code}eq(other){return other.code==this.code}toDOM(view){let ph=placeholder$1(this.code),desc=view.state.phrase("Control character")+" "+(Names[this.code]||"0x"+this.code.toString(16)),custom=this.options.render&&this.options.render(this.code,desc,ph);if(custom)return custom;let span=document.createElement("span");return span.textContent=ph,span.title=desc,span.setAttribute("aria-label",desc),span.className="cm-specialChar",span}ignoreEvent(){return!1}};__name2(_SpecialCharWidget,"SpecialCharWidget");let SpecialCharWidget=_SpecialCharWidget;const _TabWidget=class extends WidgetType{static{__name(this,"_TabWidget")}constructor(width){super(),this.width=width}eq(other){return other.width==this.width}toDOM(){let span=document.createElement("span");return span.textContent=" ",span.className="cm-tab",span.style.width=this.width+"px",span}ignoreEvent(){return!1}};__name2(_TabWidget,"TabWidget");let TabWidget=_TabWidget;function highlightActiveLine(){return activeLineHighlighter}__name(highlightActiveLine,"highlightActiveLine"),__name2(highlightActiveLine,"highlightActiveLine");const lineDeco=Decoration.line({class:"cm-activeLine"}),activeLineHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.docChanged||update.selectionSet)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let lastLineStart=-1,deco=[];for(let r of view.state.selection.ranges){let line=view.lineBlockAt(r.head);line.from>lastLineStart&&(deco.push(lineDeco.range(line.from)),lastLineStart=line.from)}return Decoration.set(deco)}},{decorations:v=>v.decorations}),MaxOff=2e3;function rectangleFor(state,a,b){let startLine=Math.min(a.line,b.line),endLine=Math.max(a.line,b.line),ranges=[];if(a.off>MaxOff||b.off>MaxOff||a.col<0||b.col<0){let startOff=Math.min(a.off,b.off),endOff=Math.max(a.off,b.off);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i);line.length<=endOff&&ranges.push(EditorSelection.range(line.from+startOff,line.to+endOff))}}else{let startCol=Math.min(a.col,b.col),endCol=Math.max(a.col,b.col);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i),start=findColumn(line.text,startCol,state.tabSize,!0);if(start<0)ranges.push(EditorSelection.cursor(line.to));else{let end=findColumn(line.text,endCol,state.tabSize);ranges.push(EditorSelection.range(line.from+start,line.from+end))}}}return ranges}__name(rectangleFor,"rectangleFor"),__name2(rectangleFor,"rectangleFor");function absoluteColumn(view,x){let ref=view.coordsAtPos(view.viewport.from);return ref?Math.round(Math.abs((ref.left-x)/view.defaultCharacterWidth)):-1}__name(absoluteColumn,"absoluteColumn"),__name2(absoluteColumn,"absoluteColumn");function getPos(view,event){let offset2=view.posAtCoords({x:event.clientX,y:event.clientY},!1),line=view.state.doc.lineAt(offset2),off2=offset2-line.from,col=off2>MaxOff?-1:off2==line.length?absoluteColumn(view,event.clientX):countColumn(line.text,view.state.tabSize,offset2-line.from);return{line:line.number,col,off:off2}}__name(getPos,"getPos"),__name2(getPos,"getPos");function rectangleSelectionStyle(view,event){let start=getPos(view,event),startSel=view.state.selection;return start?{update(update){if(update.docChanged){let newStart=update.changes.mapPos(update.startState.doc.line(start.line).from),newLine=update.state.doc.lineAt(newStart);start={line:newLine.number,col:start.col,off:Math.min(start.off,newLine.length)},startSel=startSel.map(update.changes)}},get(event2,_extend,multiple){let cur2=getPos(view,event2);if(!cur2)return startSel;let ranges=rectangleFor(view.state,start,cur2);return ranges.length?multiple?EditorSelection.create(ranges.concat(startSel.ranges)):EditorSelection.create(ranges):startSel}}:null}__name(rectangleSelectionStyle,"rectangleSelectionStyle"),__name2(rectangleSelectionStyle,"rectangleSelectionStyle");function rectangularSelection(options){let filter2=options?.eventFilter||(e=>e.altKey&&e.button==0);return EditorView.mouseSelectionStyle.of((view,event)=>filter2(event)?rectangleSelectionStyle(view,event):null)}__name(rectangularSelection,"rectangularSelection"),__name2(rectangularSelection,"rectangularSelection");const keys={Alt:[18,e=>!!e.altKey],Control:[17,e=>!!e.ctrlKey],Shift:[16,e=>!!e.shiftKey],Meta:[91,e=>!!e.metaKey]},showCrosshair={style:"cursor: crosshair"};function crosshairCursor(options={}){let[code,getter]=keys[options.key||"Alt"],plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.isDown=!1}set(isDown){this.isDown!=isDown&&(this.isDown=isDown,this.view.update([]))}},{eventObservers:{keydown(e){this.set(e.keyCode==code||getter(e))},keyup(e){(e.keyCode==code||!getter(e))&&this.set(!1)},mousemove(e){this.set(getter(e))}}});return[plugin,EditorView.contentAttributes.of(view=>{var _a3;return!((_a3=view.plugin(plugin))===null||_a3===void 0)&&_a3.isDown?showCrosshair:null})]}__name(crosshairCursor,"crosshairCursor"),__name2(crosshairCursor,"crosshairCursor");const Outside="-10000px",_TooltipViewManager=class{static{__name(this,"_TooltipViewManager")}constructor(view,facet,createTooltipView){this.facet=facet,this.createTooltipView=createTooltipView,this.input=view.state.facet(facet),this.tooltips=this.input.filter(t2=>t2),this.tooltipViews=this.tooltips.map(createTooltipView)}update(update){var _a3;let input=update.state.facet(this.facet),tooltips=input.filter(x=>x);if(input===this.input){for(let t2 of this.tooltipViews)t2.update&&t2.update(update);return!1}let tooltipViews=[];for(let i=0;i<tooltips.length;i++){let tip=tooltips[i],known=-1;if(tip){for(let i2=0;i2<this.tooltips.length;i2++){let other=this.tooltips[i2];other&&other.create==tip.create&&(known=i2)}if(known<0)tooltipViews[i]=this.createTooltipView(tip);else{let tooltipView=tooltipViews[i]=this.tooltipViews[known];tooltipView.update&&tooltipView.update(update)}}}for(let t2 of this.tooltipViews)tooltipViews.indexOf(t2)<0&&(t2.dom.remove(),(_a3=t2.destroy)===null||_a3===void 0||_a3.call(t2));return this.input=input,this.tooltips=tooltips,this.tooltipViews=tooltipViews,!0}};__name2(_TooltipViewManager,"TooltipViewManager");let TooltipViewManager=_TooltipViewManager;function windowSpace(view){let{win}=view;return{top:0,left:0,bottom:win.innerHeight,right:win.innerWidth}}__name(windowSpace,"windowSpace"),__name2(windowSpace,"windowSpace");const tooltipConfig=Facet.define({combine:values=>{var _a3,_b2,_c2;return{position:browser.ios?"absolute":((_a3=values.find(conf=>conf.position))===null||_a3===void 0?void 0:_a3.position)||"fixed",parent:((_b2=values.find(conf=>conf.parent))===null||_b2===void 0?void 0:_b2.parent)||null,tooltipSpace:((_c2=values.find(conf=>conf.tooltipSpace))===null||_c2===void 0?void 0:_c2.tooltipSpace)||windowSpace}}}),knownHeight=new WeakMap,tooltipPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let config2=view.state.facet(tooltipConfig);this.position=config2.position,this.parent=config2.parent,this.classes=view.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.manager=new TooltipViewManager(view,showTooltip,t2=>this.createTooltip(t2)),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(entries=>{Date.now()>this.lastTransaction-50&&entries.length>0&&entries[entries.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),view.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let tooltip of this.manager.tooltipViews)this.intersectionObserver.observe(tooltip.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(update){update.transactions.length&&(this.lastTransaction=Date.now());let updated=this.manager.update(update);updated&&this.observeIntersection();let shouldMeasure=updated||update.geometryChanged,newConfig=update.state.facet(tooltipConfig);if(newConfig.position!=this.position&&!this.madeAbsolute){this.position=newConfig.position;for(let t2 of this.manager.tooltipViews)t2.dom.style.position=this.position;shouldMeasure=!0}if(newConfig.parent!=this.parent){this.parent&&this.container.remove(),this.parent=newConfig.parent,this.createContainer();for(let t2 of this.manager.tooltipViews)this.container.appendChild(t2.dom);shouldMeasure=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);shouldMeasure&&this.maybeMeasure()}createTooltip(tooltip){let tooltipView=tooltip.create(this.view);if(tooltipView.dom.classList.add("cm-tooltip"),tooltip.arrow&&!tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let arrow=document.createElement("div");arrow.className="cm-tooltip-arrow",tooltipView.dom.appendChild(arrow)}return tooltipView.dom.style.position=this.position,tooltipView.dom.style.top=Outside,this.container.appendChild(tooltipView.dom),tooltipView.mount&&tooltipView.mount(this.view),tooltipView}destroy(){var _a3,_b2;this.view.win.removeEventListener("resize",this.measureSoon);for(let tooltipView of this.manager.tooltipViews)tooltipView.dom.remove(),(_a3=tooltipView.destroy)===null||_a3===void 0||_a3.call(tooltipView);this.parent&&this.container.remove(),(_b2=this.intersectionObserver)===null||_b2===void 0||_b2.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let editor=this.view.dom.getBoundingClientRect(),scaleX=1,scaleY=1,makeAbsolute=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{offsetParent}=this.manager.tooltipViews[0].dom;makeAbsolute=!!(offsetParent&&offsetParent!=this.container.ownerDocument.body)}if(makeAbsolute||this.position=="absolute")if(this.parent){let rect=this.parent.getBoundingClientRect();rect.width&&rect.height&&(scaleX=rect.width/this.parent.offsetWidth,scaleY=rect.height/this.parent.offsetHeight)}else({scaleX,scaleY}=this.view.viewState);return{editor,parent:this.parent?this.container.getBoundingClientRect():editor,pos:this.manager.tooltips.map((t2,i)=>{let tv=this.manager.tooltipViews[i];return tv.getCoords?tv.getCoords(t2.pos):this.view.coordsAtPos(t2.pos)}),size:this.manager.tooltipViews.map(({dom})=>dom.getBoundingClientRect()),space:this.view.state.facet(tooltipConfig).tooltipSpace(this.view),scaleX,scaleY,makeAbsolute}}writeMeasure(measured){var _a3;if(measured.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let t2 of this.manager.tooltipViews)t2.dom.style.position="absolute"}let{editor,space,scaleX,scaleY}=measured,others=[];for(let i=0;i<this.manager.tooltips.length;i++){let tooltip=this.manager.tooltips[i],tView=this.manager.tooltipViews[i],{dom}=tView,pos=measured.pos[i],size=measured.size[i];if(!pos||pos.bottom<=Math.max(editor.top,space.top)||pos.top>=Math.min(editor.bottom,space.bottom)||pos.right<Math.max(editor.left,space.left)-.1||pos.left>Math.min(editor.right,space.right)+.1){dom.style.top=Outside;continue}let arrow=tooltip.arrow?tView.dom.querySelector(".cm-tooltip-arrow"):null,arrowHeight=arrow?7:0,width=size.right-size.left,height=(_a3=knownHeight.get(tView))!==null&&_a3!==void 0?_a3:size.bottom-size.top,offset2=tView.offset||noOffset,ltr=this.view.textDirection==Direction.LTR,left=size.width>space.right-space.left?ltr?space.left:space.right-size.width:ltr?Math.min(pos.left-(arrow?14:0)+offset2.x,space.right-width):Math.max(space.left,pos.left-width+(arrow?14:0)-offset2.x),above=!!tooltip.above;!tooltip.strictSide&&(above?pos.top-(size.bottom-size.top)-offset2.y<space.top:pos.bottom+(size.bottom-size.top)+offset2.y>space.bottom)&&above==space.bottom-pos.bottom>pos.top-space.top&&(above=!above);let spaceVert=(above?pos.top-space.top:space.bottom-pos.bottom)-arrowHeight;if(spaceVert<height&&tView.resize!==!1){if(spaceVert<this.view.defaultLineHeight){dom.style.top=Outside;continue}knownHeight.set(tView,height),dom.style.height=(height=spaceVert)/scaleY+"px"}else dom.style.height&&(dom.style.height="");let top2=above?pos.top-height-arrowHeight-offset2.y:pos.bottom+arrowHeight+offset2.y,right=left+width;if(tView.overlap!==!0)for(let r of others)r.left<right&&r.right>left&&r.top<top2+height&&r.bottom>top2&&(top2=above?r.top-height-2-arrowHeight:r.bottom+arrowHeight+2);if(this.position=="absolute"?(dom.style.top=(top2-measured.parent.top)/scaleY+"px",dom.style.left=(left-measured.parent.left)/scaleX+"px"):(dom.style.top=top2/scaleY+"px",dom.style.left=left/scaleX+"px"),arrow){let arrowLeft=pos.left+(ltr?offset2.x:-offset2.x)-(left+14-7);arrow.style.left=arrowLeft/scaleX+"px"}tView.overlap!==!0&&others.push({left,top:top2,right,bottom:top2+height}),dom.classList.toggle("cm-tooltip-above",above),dom.classList.toggle("cm-tooltip-below",!above),tView.positioned&&tView.positioned(measured.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let tv of this.manager.tooltipViews)tv.dom.style.top=Outside}},{eventObservers:{scroll(){this.maybeMeasure()}}}),baseTheme$5=EditorView.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),noOffset={x:0,y:0},showTooltip=Facet.define({enables:[tooltipPlugin,baseTheme$5]}),showHoverTooltip=Facet.define(),_HoverTooltipHost=class _HoverTooltipHost2{static{__name(this,"_HoverTooltipHost")}static create(view){return new _HoverTooltipHost2(view)}constructor(view){this.view=view,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new TooltipViewManager(view,showHoverTooltip,t2=>this.createHostedView(t2))}createHostedView(tooltip){let hostedView=tooltip.create(this.view);return hostedView.dom.classList.add("cm-tooltip-section"),this.dom.appendChild(hostedView.dom),this.mounted&&hostedView.mount&&hostedView.mount(this.view),hostedView}mount(view){for(let hostedView of this.manager.tooltipViews)hostedView.mount&&hostedView.mount(view);this.mounted=!0}positioned(space){for(let hostedView of this.manager.tooltipViews)hostedView.positioned&&hostedView.positioned(space)}update(update){this.manager.update(update)}destroy(){var _a3;for(let t2 of this.manager.tooltipViews)(_a3=t2.destroy)===null||_a3===void 0||_a3.call(t2)}};__name2(_HoverTooltipHost,"HoverTooltipHost");let HoverTooltipHost=_HoverTooltipHost;const showHoverTooltipHost=showTooltip.compute([showHoverTooltip],state=>{let tooltips=state.facet(showHoverTooltip).filter(t2=>t2);return tooltips.length===0?null:{pos:Math.min(...tooltips.map(t2=>t2.pos)),end:Math.max(...tooltips.filter(t2=>t2.end!=null).map(t2=>t2.end)),create:HoverTooltipHost.create,above:tooltips[0].above,arrow:tooltips.some(t2=>t2.arrow)}}),_HoverPlugin=class{static{__name(this,"_HoverPlugin")}constructor(view,source,field,setHover,hoverTime){this.view=view,this.source=source,this.field=field,this.setHover=setHover,this.hoverTime=hoverTime,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:view.dom,time:0},this.checkHover=this.checkHover.bind(this),view.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),view.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active)return;let hovered=Date.now()-this.lastMove.time;hovered<this.hoverTime?this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime-hovered):this.startHover()}startHover(){clearTimeout(this.restartTimeout);let{view,lastMove}=this,desc=view.docView.nearest(lastMove.target);if(!desc)return;let pos,side=1;if(desc instanceof WidgetView)pos=desc.posAtStart;else{if(pos=view.posAtCoords(lastMove),pos==null)return;let posCoords=view.coordsAtPos(pos);if(!posCoords||lastMove.y<posCoords.top||lastMove.y>posCoords.bottom||lastMove.x<posCoords.left-view.defaultCharacterWidth||lastMove.x>posCoords.right+view.defaultCharacterWidth)return;let bidi=view.bidiSpans(view.state.doc.lineAt(pos)).find(s2=>s2.from<=pos&&s2.to>=pos),rtl=bidi&&bidi.dir==Direction.RTL?-1:1;side=lastMove.x<posCoords.left?-rtl:rtl}let open=this.source(view,pos,side);if(open?.then){let pending=this.pending={pos};open.then(result=>{this.pending==pending&&(this.pending=null,result&&view.dispatch({effects:this.setHover.of(result)}))},e=>logException(view.state,e,"hover tooltip"))}else open&&view.dispatch({effects:this.setHover.of(open)})}mousemove(event){var _a3;this.lastMove={x:event.clientX,y:event.clientY,target:event.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let tooltip=this.active;if(tooltip&&!isInTooltip(this.lastMove.target)||this.pending){let{pos}=tooltip||this.pending,end=(_a3=tooltip?.end)!==null&&_a3!==void 0?_a3:pos;(pos==end?this.view.posAtCoords(this.lastMove)!=pos:!isOverRange(this.view,pos,end,event.clientX,event.clientY))&&(this.view.dispatch({effects:this.setHover.of(null)}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1,this.active&&!isInTooltip(e.relatedTarget)&&this.view.dispatch({effects:this.setHover.of(null)})}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}};__name2(_HoverPlugin,"HoverPlugin");let HoverPlugin=_HoverPlugin;function isInTooltip(elt){for(let cur2=elt;cur2;cur2=cur2.parentNode)if(cur2.nodeType==1&&cur2.classList.contains("cm-tooltip"))return!0;return!1}__name(isInTooltip,"isInTooltip"),__name2(isInTooltip,"isInTooltip");function isOverRange(view,from,to,x,y,margin){let rect=view.scrollDOM.getBoundingClientRect(),docBottom=view.documentTop+view.documentPadding.top+view.contentHeight;if(rect.left>x||rect.right<x||rect.top>y||Math.min(rect.bottom,docBottom)<y)return!1;let pos=view.posAtCoords({x,y},!1);return pos>=from&&pos<=to}__name(isOverRange,"isOverRange"),__name2(isOverRange,"isOverRange");function hoverTooltip(source,options={}){let setHover=StateEffect.define(),hoverState=StateField.define({create(){return null},update(value,tr){if(value&&(options.hideOnChange&&(tr.docChanged||tr.selection)||options.hideOn&&options.hideOn(tr,value)))return null;if(value&&tr.docChanged){let newPos=tr.changes.mapPos(value.pos,-1,MapMode.TrackDel);if(newPos==null)return null;let copy=Object.assign(Object.create(null),value);copy.pos=newPos,value.end!=null&&(copy.end=tr.changes.mapPos(value.end)),value=copy}for(let effect of tr.effects)effect.is(setHover)&&(value=effect.value),effect.is(closeHoverTooltipEffect)&&(value=null);return value},provide:f2=>showHoverTooltip.from(f2)});return[hoverState,ViewPlugin.define(view=>new HoverPlugin(view,source,hoverState,setHover,options.hoverTime||300)),showHoverTooltipHost]}__name(hoverTooltip,"hoverTooltip"),__name2(hoverTooltip,"hoverTooltip");function getTooltip(view,tooltip){let plugin=view.plugin(tooltipPlugin);if(!plugin)return null;let found=plugin.manager.tooltips.indexOf(tooltip);return found<0?null:plugin.manager.tooltipViews[found]}__name(getTooltip,"getTooltip"),__name2(getTooltip,"getTooltip");const closeHoverTooltipEffect=StateEffect.define(),panelConfig=Facet.define({combine(configs){let topContainer,bottomContainer;for(let c of configs)topContainer=topContainer||c.topContainer,bottomContainer=bottomContainer||c.bottomContainer;return{topContainer,bottomContainer}}});function getPanel(view,panel){let plugin=view.plugin(panelPlugin),index2=plugin?plugin.specs.indexOf(panel):-1;return index2>-1?plugin.panels[index2]:null}__name(getPanel,"getPanel"),__name2(getPanel,"getPanel");const panelPlugin=ViewPlugin.fromClass(class{constructor(view){this.input=view.state.facet(showPanel),this.specs=this.input.filter(s2=>s2),this.panels=this.specs.map(spec=>spec(view));let conf=view.state.facet(panelConfig);this.top=new PanelGroup(view,!0,conf.topContainer),this.bottom=new PanelGroup(view,!1,conf.bottomContainer),this.top.sync(this.panels.filter(p=>p.top)),this.bottom.sync(this.panels.filter(p=>!p.top));for(let p of this.panels)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}update(update){let conf=update.state.facet(panelConfig);this.top.container!=conf.topContainer&&(this.top.sync([]),this.top=new PanelGroup(update.view,!0,conf.topContainer)),this.bottom.container!=conf.bottomContainer&&(this.bottom.sync([]),this.bottom=new PanelGroup(update.view,!1,conf.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let input=update.state.facet(showPanel);if(input!=this.input){let specs=input.filter(x=>x),panels=[],top2=[],bottom=[],mount2=[];for(let spec of specs){let known=this.specs.indexOf(spec),panel;known<0?(panel=spec(update.view),mount2.push(panel)):(panel=this.panels[known],panel.update&&panel.update(update)),panels.push(panel),(panel.top?top2:bottom).push(panel)}this.specs=specs,this.panels=panels,this.top.sync(top2),this.bottom.sync(bottom);for(let p of mount2)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}else for(let p of this.panels)p.update&&p.update(update)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return value&&{top:value.top.scrollMargin(),bottom:value.bottom.scrollMargin()}})}),_PanelGroup=class{static{__name(this,"_PanelGroup")}constructor(view,top2,container){this.view=view,this.top=top2,this.container=container,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(panels){for(let p of this.panels)p.destroy&&panels.indexOf(p)<0&&p.destroy();this.panels=panels,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let parent=this.container||this.view.dom;parent.insertBefore(this.dom,this.top?parent.firstChild:null)}let curDOM=this.dom.firstChild;for(let panel of this.panels)if(panel.dom.parentNode==this.dom){for(;curDOM!=panel.dom;)curDOM=rm(curDOM);curDOM=curDOM.nextSibling}else this.dom.insertBefore(panel.dom,curDOM);for(;curDOM;)curDOM=rm(curDOM)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let cls of this.classes.split(" "))cls&&this.container.classList.remove(cls);for(let cls of(this.classes=this.view.themeClasses).split(" "))cls&&this.container.classList.add(cls)}}};__name2(_PanelGroup,"PanelGroup");let PanelGroup=_PanelGroup;function rm(node){let next=node.nextSibling;return node.remove(),next}__name(rm,"rm"),__name2(rm,"rm");const showPanel=Facet.define({enables:panelPlugin}),_GutterMarker=class extends RangeValue{static{__name(this,"_GutterMarker")}compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}eq(other){return!1}destroy(dom){}};__name2(_GutterMarker,"GutterMarker");let GutterMarker=_GutterMarker;GutterMarker.prototype.elementClass="",GutterMarker.prototype.toDOM=void 0,GutterMarker.prototype.mapMode=MapMode.TrackBefore,GutterMarker.prototype.startSide=GutterMarker.prototype.endSide=-1,GutterMarker.prototype.point=!0;const gutterLineClass=Facet.define(),defaults$1={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>RangeSet.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},activeGutters=Facet.define();function gutter(config2){return[gutters(),activeGutters.of(Object.assign(Object.assign({},defaults$1),config2))]}__name(gutter,"gutter"),__name2(gutter,"gutter");const unfixGutters=Facet.define({combine:values=>values.some(x=>x)});function gutters(config2){let result=[gutterView];return config2&&config2.fixed===!1&&result.push(unfixGutters.of(!0)),result}__name(gutters,"gutters"),__name2(gutters,"gutters");const gutterView=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.prevViewport=view.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=view.state.facet(activeGutters).map(conf=>new SingleGutterView(view,conf));for(let gutter2 of this.gutters)this.dom.appendChild(gutter2.dom);this.fixed=!view.state.facet(unfixGutters),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),view.scrollDOM.insertBefore(this.dom,view.contentDOM)}update(update){if(this.updateGutters(update)){let vpA=this.prevViewport,vpB=update.view.viewport,vpOverlap=Math.min(vpA.to,vpB.to)-Math.max(vpA.from,vpB.from);this.syncGutters(vpOverlap<(vpB.to-vpB.from)*.8)}update.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight+"px"),this.view.state.facet(unfixGutters)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=update.view.viewport}syncGutters(detach){let after=this.dom.nextSibling;detach&&this.dom.remove();let lineClasses=RangeSet.iter(this.view.state.facet(gutterLineClass),this.view.viewport.from),classSet=[],contexts=this.gutters.map(gutter2=>new UpdateContext(gutter2,this.view.viewport,-this.view.documentPadding.top));for(let line of this.view.viewportLineBlocks)if(classSet.length&&(classSet=[]),Array.isArray(line.type)){let first=!0;for(let b of line.type)if(b.type==BlockType.Text&&first){advanceCursor(lineClasses,classSet,b.from);for(let cx of contexts)cx.line(this.view,b,classSet);first=!1}else if(b.widget)for(let cx of contexts)cx.widget(this.view,b)}else if(line.type==BlockType.Text){advanceCursor(lineClasses,classSet,line.from);for(let cx of contexts)cx.line(this.view,line,classSet)}else if(line.widget)for(let cx of contexts)cx.widget(this.view,line);for(let cx of contexts)cx.finish();detach&&this.view.scrollDOM.insertBefore(this.dom,after)}updateGutters(update){let prev=update.startState.facet(activeGutters),cur2=update.state.facet(activeGutters),change=update.docChanged||update.heightChanged||update.viewportChanged||!RangeSet.eq(update.startState.facet(gutterLineClass),update.state.facet(gutterLineClass),update.view.viewport.from,update.view.viewport.to);if(prev==cur2)for(let gutter2 of this.gutters)gutter2.update(update)&&(change=!0);else{change=!0;let gutters2=[];for(let conf of cur2){let known=prev.indexOf(conf);known<0?gutters2.push(new SingleGutterView(this.view,conf)):(this.gutters[known].update(update),gutters2.push(this.gutters[known]))}for(let g of this.gutters)g.dom.remove(),gutters2.indexOf(g)<0&&g.destroy();for(let g of gutters2)this.dom.appendChild(g.dom);this.gutters=gutters2}return change}destroy(){for(let view of this.gutters)view.destroy();this.dom.remove()}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return!value||value.gutters.length==0||!value.fixed?null:view.textDirection==Direction.LTR?{left:value.dom.offsetWidth*view.scaleX}:{right:value.dom.offsetWidth*view.scaleX}})});function asArray$1(val){return Array.isArray(val)?val:[val]}__name(asArray$1,"asArray$1"),__name2(asArray$1,"asArray$1");function advanceCursor(cursor,collect,pos){for(;cursor.value&&cursor.from<=pos;)cursor.from==pos&&collect.push(cursor.value),cursor.next()}__name(advanceCursor,"advanceCursor"),__name2(advanceCursor,"advanceCursor");const _UpdateContext=class{static{__name(this,"_UpdateContext")}constructor(gutter2,viewport,height){this.gutter=gutter2,this.height=height,this.i=0,this.cursor=RangeSet.iter(gutter2.markers,viewport.from)}addElement(view,block,markers){let{gutter:gutter2}=this,above=(block.top-this.height)/view.scaleY,height=block.height/view.scaleY;if(this.i==gutter2.elements.length){let newElt=new GutterElement(view,height,above,markers);gutter2.elements.push(newElt),gutter2.dom.appendChild(newElt.dom)}else gutter2.elements[this.i].update(view,height,above,markers);this.height=block.bottom,this.i++}line(view,line,extraMarkers){let localMarkers=[];advanceCursor(this.cursor,localMarkers,line.from),extraMarkers.length&&(localMarkers=localMarkers.concat(extraMarkers));let forLine=this.gutter.config.lineMarker(view,line,localMarkers);forLine&&localMarkers.unshift(forLine);let gutter2=this.gutter;localMarkers.length==0&&!gutter2.config.renderEmptyElements||this.addElement(view,line,localMarkers)}widget(view,block){let marker=this.gutter.config.widgetMarker(view,block.widget,block);marker&&this.addElement(view,block,[marker])}finish(){let gutter2=this.gutter;for(;gutter2.elements.length>this.i;){let last2=gutter2.elements.pop();gutter2.dom.removeChild(last2.dom),last2.destroy()}}};__name2(_UpdateContext,"UpdateContext");let UpdateContext=_UpdateContext;const _SingleGutterView=class{static{__name(this,"_SingleGutterView")}constructor(view,config2){this.view=view,this.config=config2,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let prop in config2.domEventHandlers)this.dom.addEventListener(prop,event=>{let target=event.target,y;if(target!=this.dom&&this.dom.contains(target)){for(;target.parentNode!=this.dom;)target=target.parentNode;let rect=target.getBoundingClientRect();y=(rect.top+rect.bottom)/2}else y=event.clientY;let line=view.lineBlockAtHeight(y-view.documentTop);config2.domEventHandlers[prop](view,line,event)&&event.preventDefault()});this.markers=asArray$1(config2.markers(view)),config2.initialSpacer&&(this.spacer=new GutterElement(view,0,0,[config2.initialSpacer(view)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(update){let prevMarkers=this.markers;if(this.markers=asArray$1(this.config.markers(update.view)),this.spacer&&this.config.updateSpacer){let updated=this.config.updateSpacer(this.spacer.markers[0],update);updated!=this.spacer.markers[0]&&this.spacer.update(update.view,0,0,[updated])}let vp=update.view.viewport;return!RangeSet.eq(this.markers,prevMarkers,vp.from,vp.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(update):!1)}destroy(){for(let elt of this.elements)elt.destroy()}};__name2(_SingleGutterView,"SingleGutterView");let SingleGutterView=_SingleGutterView;const _GutterElement=class{static{__name(this,"_GutterElement")}constructor(view,height,above,markers){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(view,height,above,markers)}update(view,height,above,markers){this.height!=height&&(this.height=height,this.dom.style.height=height+"px"),this.above!=above&&(this.dom.style.marginTop=(this.above=above)?above+"px":""),sameMarkers(this.markers,markers)||this.setMarkers(view,markers)}setMarkers(view,markers){let cls="cm-gutterElement",domPos=this.dom.firstChild;for(let iNew=0,iOld=0;;){let skipTo=iOld,marker=iNew<markers.length?markers[iNew++]:null,matched=!1;if(marker){let c=marker.elementClass;c&&(cls+=" "+c);for(let i=iOld;i<this.markers.length;i++)if(this.markers[i].compare(marker)){skipTo=i,matched=!0;break}}else skipTo=this.markers.length;for(;iOld<skipTo;){let next=this.markers[iOld++];if(next.toDOM){next.destroy(domPos);let after=domPos.nextSibling;domPos.remove(),domPos=after}}if(!marker)break;marker.toDOM&&(matched?domPos=domPos.nextSibling:this.dom.insertBefore(marker.toDOM(view),domPos)),matched&&iOld++}this.dom.className=cls,this.markers=markers}destroy(){this.setMarkers(null,[])}};__name2(_GutterElement,"GutterElement");let GutterElement=_GutterElement;function sameMarkers(a,b){if(a.length!=b.length)return!1;for(let i=0;i<a.length;i++)if(!a[i].compare(b[i]))return!1;return!0}__name(sameMarkers,"sameMarkers"),__name2(sameMarkers,"sameMarkers");const lineNumberMarkers=Facet.define(),lineNumberConfig=Facet.define({combine(values){return combineConfig(values,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(a,b){let result=Object.assign({},a);for(let event in b){let exists=result[event],add2=b[event];result[event]=exists?(view,line,event2)=>exists(view,line,event2)||add2(view,line,event2):add2}return result}})}}),_NumberMarker=class extends GutterMarker{static{__name(this,"_NumberMarker")}constructor(number2){super(),this.number=number2}eq(other){return this.number==other.number}toDOM(){return document.createTextNode(this.number)}};__name2(_NumberMarker,"NumberMarker");let NumberMarker=_NumberMarker;function formatNumber(view,number2){return view.state.facet(lineNumberConfig).formatNumber(number2,view.state)}__name(formatNumber,"formatNumber"),__name2(formatNumber,"formatNumber");const lineNumberGutter=activeGutters.compute([lineNumberConfig],state=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(view){return view.state.facet(lineNumberMarkers)},lineMarker(view,line,others){return others.some(m=>m.toDOM)?null:new NumberMarker(formatNumber(view,view.state.doc.lineAt(line.from).number))},widgetMarker:()=>null,lineMarkerChange:update=>update.startState.facet(lineNumberConfig)!=update.state.facet(lineNumberConfig),initialSpacer(view){return new NumberMarker(formatNumber(view,maxLineNumber(view.state.doc.lines)))},updateSpacer(spacer,update){let max=formatNumber(update.view,maxLineNumber(update.view.state.doc.lines));return max==spacer.number?spacer:new NumberMarker(max)},domEventHandlers:state.facet(lineNumberConfig).domEventHandlers}));function lineNumbers(config2={}){return[lineNumberConfig.of(config2),gutters(),lineNumberGutter]}__name(lineNumbers,"lineNumbers"),__name2(lineNumbers,"lineNumbers");function maxLineNumber(lines){let last2=9;for(;last2<lines;)last2=last2*10+9;return last2}__name(maxLineNumber,"maxLineNumber"),__name2(maxLineNumber,"maxLineNumber");const activeLineGutterMarker=new class extends GutterMarker{constructor(){super(...arguments),this.elementClass="cm-activeLineGutter"}},activeLineGutterHighlighter=gutterLineClass.compute(["selection"],state=>{let marks=[],last2=-1;for(let range of state.selection.ranges){let linePos=state.doc.lineAt(range.head).from;linePos>last2&&(last2=linePos,marks.push(activeLineGutterMarker.range(linePos)))}return RangeSet.of(marks)});function highlightActiveLineGutter(){return activeLineGutterHighlighter}__name(highlightActiveLineGutter,"highlightActiveLineGutter"),__name2(highlightActiveLineGutter,"highlightActiveLineGutter");const DefaultBufferLength=1024;let nextPropID=0;const _Range=class{static{__name(this,"_Range")}constructor(from,to){this.from=from,this.to=to}};__name2(_Range,"Range");let Range=_Range;const _NodeProp=class{static{__name(this,"_NodeProp")}constructor(config2={}){this.id=nextPropID++,this.perNode=!!config2.perNode,this.deserialize=config2.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(match2){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof match2!="function"&&(match2=NodeType.match(match2)),type=>{let result=match2(type);return result===void 0?null:[this,result]}}};__name2(_NodeProp,"NodeProp");let NodeProp=_NodeProp;NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null),_NodeType=class _NodeType2{static{__name(this,"_NodeType")}constructor(name2,props,id,flags=0){this.name=name2,this.props=props,this.id=id,this.flags=flags}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps,flags=(spec.top?1:0)|(spec.skipped?2:0)|(spec.error?4:0)|(spec.name==null?8:0),type=new _NodeType2(spec.name||"",props,spec.id,flags);if(spec.props){for(let src of spec.props)if(Array.isArray(src)||(src=src(type)),src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1]}}return type}prop(prop){return this.props[prop.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(name2){if(typeof name2=="string"){if(this.name==name2)return!0;let group=this.prop(NodeProp.group);return group?group.indexOf(name2)>-1:!1}return this.id==name2}static match(map2){let direct=Object.create(null);for(let prop in map2)for(let name2 of prop.split(" "))direct[name2]=map2[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found}}}};__name2(_NodeType,"NodeType");let NodeType=_NodeType;NodeType.none=new NodeType("",Object.create(null),0,8);const _NodeSet=class _NodeSet2{static{__name(this,"_NodeSet")}constructor(types2){this.types=types2;for(let i=0;i<types2.length;i++)if(types2[i].id!=i)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...props){let newTypes=[];for(let type of this.types){let newProps=null;for(let source of props){let add2=source(type);add2&&(newProps||(newProps=Object.assign({},type.props)),newProps[add2[0].id]=add2[1])}newTypes.push(newProps?new NodeType(type.name,newProps,type.id,type.flags):type)}return new _NodeSet2(newTypes)}};__name2(_NodeSet,"NodeSet");let NodeSet=_NodeSet;const CachedNode=new WeakMap,CachedInnerNode=new WeakMap;var IterMode;(function(IterMode2){IterMode2[IterMode2.ExcludeBuffers=1]="ExcludeBuffers",IterMode2[IterMode2.IncludeAnonymous=2]="IncludeAnonymous",IterMode2[IterMode2.IgnoreMounts=4]="IgnoreMounts",IterMode2[IterMode2.IgnoreOverlays=8]="IgnoreOverlays"})(IterMode||(IterMode={}));const _Tree=class _Tree2{static{__name(this,"_Tree")}constructor(type,children,positions,length,props){if(this.type=type,this.children=children,this.positions=positions,this.length=length,this.props=null,props&&props.length){this.props=Object.create(null);for(let[prop,value]of props)this.props[typeof prop=="number"?prop:prop.id]=value}}toString(){let mounted=this.prop(NodeProp.mounted);if(mounted&&!mounted.overlay)return mounted.tree.toString();let children="";for(let ch of this.children){let str=ch.toString();str&&(children&&(children+=","),children+=str)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(children.length?"("+children+")":""):children}cursor(mode=0){return new TreeCursor(this.topNode,mode)}cursorAt(pos,side=0,mode=0){let scope2=CachedNode.get(this)||this.topNode,cursor=new TreeCursor(scope2);return cursor.moveTo(pos,side),CachedNode.set(this,cursor._tree),cursor}get topNode(){return new TreeNode(this,0,0,null)}resolve(pos,side=0){let node=resolveNode(CachedNode.get(this)||this.topNode,pos,side,!1);return CachedNode.set(this,node),node}resolveInner(pos,side=0){let node=resolveNode(CachedInnerNode.get(this)||this.topNode,pos,side,!0);return CachedInnerNode.set(this,node),node}iterate(spec){let{enter,leave,from=0,to=this.length}=spec,mode=spec.mode||0,anon=(mode&IterMode.IncludeAnonymous)>0;for(let c=this.cursor(mode|IterMode.IncludeAnonymous);;){let entered=!1;if(c.from<=to&&c.to>=from&&(!anon&&c.type.isAnonymous||enter(c)!==!1)){if(c.firstChild())continue;entered=!0}for(;entered&&leave&&(anon||!c.type.isAnonymous)&&leave(c),!c.nextSibling();){if(!c.parent())return;entered=!0}}}prop(prop){return prop.perNode?this.props?this.props[prop.id]:void 0:this.type.prop(prop)}get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result}balance(config2={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,(children,positions,length)=>new _Tree2(this.type,children,positions,length,this.propValues),config2.makeTree||((children,positions,length)=>new _Tree2(NodeType.none,children,positions,length)))}static build(data){return buildTree(data)}};__name2(_Tree,"Tree");let Tree=_Tree;Tree.empty=new Tree(NodeType.none,[],[],0);const _FlatBufferCursor=class _FlatBufferCursor2{static{__name(this,"_FlatBufferCursor")}constructor(buffer,index2){this.buffer=buffer,this.index=index2}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new _FlatBufferCursor2(this.buffer,this.index)}};__name2(_FlatBufferCursor,"FlatBufferCursor");let FlatBufferCursor=_FlatBufferCursor;const _TreeBuffer=class _TreeBuffer2{static{__name(this,"_TreeBuffer")}constructor(buffer,length,set){this.buffer=buffer,this.length=length,this.set=set}get type(){return NodeType.none}toString(){let result=[];for(let index2=0;index2<this.buffer.length;)result.push(this.childString(index2)),index2=this.buffer[index2+3];return result.join(",")}childString(index2){let id=this.buffer[index2],endIndex=this.buffer[index2+3],type=this.set.types[id],result=type.name;if(/\W/.test(result)&&!type.isError&&(result=JSON.stringify(result)),index2+=4,endIndex==index2)return result;let children=[];for(;index2<endIndex;)children.push(this.childString(index2)),index2=this.buffer[index2+3];return result+"("+children.join(",")+")"}findChild(startIndex,endIndex,dir,pos,side){let{buffer}=this,pick2=-1;for(let i=startIndex;i!=endIndex&&!(checkSide(side,pos,buffer[i+1],buffer[i+2])&&(pick2=i,dir>0));i=buffer[i+3]);return pick2}slice(startI,endI,from){let b=this.buffer,copy=new Uint16Array(endI-startI),len=0;for(let i=startI,j=0;i<endI;){copy[j++]=b[i++],copy[j++]=b[i++]-from;let to=copy[j++]=b[i++]-from;copy[j++]=b[i++]-startI,len=Math.max(len,to)}return new _TreeBuffer2(copy,len,this.set)}};__name2(_TreeBuffer,"TreeBuffer");let TreeBuffer=_TreeBuffer;function checkSide(side,pos,from,to){switch(side){case-2:return from<pos;case-1:return to>=pos&&from<pos;case 0:return from<pos&&to>pos;case 1:return from<=pos&&to>pos;case 2:return to>pos;case 4:return!0}}__name(checkSide,"checkSide"),__name2(checkSide,"checkSide");function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);for(;scan;){let last2=scan.lastChild;if(!last2||last2.to!=scan.to)break;last2.type.isError&&last2.from==last2.to?(node=scan,scan=last2.prevSibling):scan=last2}return node}__name(enterUnfinishedNodesBefore,"enterUnfinishedNodesBefore"),__name2(enterUnfinishedNodesBefore,"enterUnfinishedNodesBefore");function resolveNode(node,pos,side,overlays){for(var _a3;node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to<pos);){let parent=!overlays&&node instanceof TreeNode&&node.index<0?null:node.parent;if(!parent)return node;node=parent}let mode=overlays?0:IterMode.IgnoreOverlays;if(overlays)for(let scan=node,parent=scan.parent;parent;scan=parent,parent=scan.parent)scan instanceof TreeNode&&scan.index<0&&((_a3=parent.enter(pos,side,mode))===null||_a3===void 0?void 0:_a3.from)!=scan.from&&(node=parent);for(;;){let inner=node.enter(pos,side,mode);if(!inner)return node;node=inner}}__name(resolveNode,"resolveNode"),__name2(resolveNode,"resolveNode");const _TreeNode=class _TreeNode2{static{__name(this,"_TreeNode")}constructor(_tree,from,index2,_parent){this._tree=_tree,this.from=from,this.index=index2,this._parent=_parent}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(i,dir,pos,side,mode=0){for(let parent=this;;){for(let{children,positions}=parent._tree,e=dir>0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(checkSide(side,pos,start,start+next.length)){if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index2=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index2>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index2)}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new _TreeNode2(mounted.tree,start,i,parent);let inner=new _TreeNode2(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side)}}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous||(parent.index>=0?i=parent.index+dir:i=dir<0?-1:parent._parent._tree.children.length,parent=parent._parent,!parent))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(pos){return this.nextChild(0,1,pos,2)}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2)}enter(pos,side,mode=0){let mounted;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from,to}of mounted.overlay)if((side>0?from<=rPos:from<rPos)&&(side<0?to>=rPos:to>rPos))return new _TreeNode2(mounted.tree,mounted.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,pos,side,mode)}nextSignificantParent(){let val=this;for(;val.type.isAnonymous&&val._parent;)val=val._parent;return val}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(mode=0){return new TreeCursor(this,mode)}get tree(){return this._tree}toTree(){return this._tree}resolve(pos,side=0){return resolveNode(this,pos,side,!1)}resolveInner(pos,side=0){return resolveNode(this,pos,side,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null}getChildren(type,before=null,after=null){return getChildren(this,type,before,after)}toString(){return this._tree.toString()}get node(){return this}matchContext(context){return matchNodeContext(this,context)}};__name2(_TreeNode,"TreeNode");let TreeNode=_TreeNode;function getChildren(node,type,before,after){let cur2=node.cursor(),result=[];if(!cur2.firstChild())return result;if(before!=null){for(;!cur2.type.is(before);)if(!cur2.nextSibling())return result}for(;;){if(after!=null&&cur2.type.is(after))return result;if(cur2.type.is(type)&&result.push(cur2.node),!cur2.nextSibling())return after==null?result:[]}}__name(getChildren,"getChildren"),__name2(getChildren,"getChildren");function matchNodeContext(node,context,i=context.length-1){for(let p=node.parent;i>=0;p=p.parent){if(!p)return!1;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return!1;i--}}return!0}__name(matchNodeContext,"matchNodeContext"),__name2(matchNodeContext,"matchNodeContext");const _BufferContext=class{static{__name(this,"_BufferContext")}constructor(parent,buffer,index2,start){this.parent=parent,this.buffer=buffer,this.index=index2,this.start=start}};__name2(_BufferContext,"BufferContext");let BufferContext=_BufferContext;const _BufferNode=class _BufferNode2{static{__name(this,"_BufferNode")}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(context,_parent,index2){this.context=context,this._parent=_parent,this.index=index2,this.type=context.buffer.set.types[context.buffer.buffer[index2]]}child(dir,pos,side){let{buffer}=this.context,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index2<0?null:new _BufferNode2(this.context,this,index2)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(pos){return this.child(1,pos,2)}childBefore(pos){return this.child(-1,pos,-2)}enter(pos,side,mode=0){if(mode&IterMode.ExcludeBuffers)return null;let{buffer}=this.context,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index2<0?null:new _BufferNode2(this.context,this,index2)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(dir){return this._parent?null:this.context.parent.nextChild(this.context.index+dir,dir,0,4)}get nextSibling(){let{buffer}=this.context,after=buffer.buffer[this.index+3];return after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length)?new _BufferNode2(this.context,this._parent,after):this.externalSibling(1)}get prevSibling(){let{buffer}=this.context,parentStart=this._parent?this._parent.index+4:0;return this.index==parentStart?this.externalSibling(-1):new _BufferNode2(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4))}cursor(mode=0){return new TreeCursor(this,mode)}get tree(){return null}toTree(){let children=[],positions=[],{buffer}=this.context,startI=this.index+4,endI=buffer.buffer[this.index+3];if(endI>startI){let from=buffer.buffer[this.index+1];children.push(buffer.slice(startI,endI,from)),positions.push(0)}return new Tree(this.type,children,positions,this.to-this.from)}resolve(pos,side=0){return resolveNode(this,pos,side,!1)}resolveInner(pos,side=0){return resolveNode(this,pos,side,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}toString(){return this.context.buffer.childString(this.index)}getChild(type,before=null,after=null){let r=getChildren(this,type,before,after);return r.length?r[0]:null}getChildren(type,before=null,after=null){return getChildren(this,type,before,after)}get node(){return this}matchContext(context){return matchNodeContext(this,context)}};__name2(_BufferNode,"BufferNode");let BufferNode=_BufferNode;const _TreeCursor=class{static{__name(this,"_TreeCursor")}get name(){return this.type.name}constructor(node,mode=0){if(this.mode=mode,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,node instanceof TreeNode)this.yieldNode(node);else{this._tree=node.context.parent,this.buffer=node.context;for(let n2=node._parent;n2;n2=n2._parent)this.stack.unshift(n2.index);this.bufferNode=node,this.yieldBuf(node.index)}}yieldNode(node){return node?(this._tree=node,this.type=node.type,this.from=node.from,this.to=node.to,!0):!1}yieldBuf(index2,type){this.index=index2;let{start,buffer}=this.buffer;return this.type=type||buffer.set.types[buffer.buffer[index2]],this.from=start+buffer.buffer[index2+1],this.to=start+buffer.buffer[index2+2],!0}yield(node){return node?node instanceof TreeNode?(this.buffer=null,this.yieldNode(node)):(this.buffer=node.context,this.yieldBuf(node.index,node.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(dir,pos,side){if(!this.buffer)return this.yield(this._tree.nextChild(dir<0?this._tree._tree.children.length-1:0,dir,pos,side,this.mode));let{buffer}=this.buffer,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);return index2<0?!1:(this.stack.push(this.index),this.yieldBuf(index2))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(pos){return this.enterChild(1,pos,2)}childBefore(pos){return this.enterChild(-1,pos,-2)}enter(pos,side,mode=this.mode){return this.buffer?mode&IterMode.ExcludeBuffers?!1:this.enterChild(1,pos,side):this.yield(this._tree.enter(pos,side,mode))}parent(){if(!this.buffer)return this.yieldNode(this.mode&IterMode.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let parent=this.mode&IterMode.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(parent)}sibling(dir){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4,this.mode)):!1;let{buffer}=this.buffer,d=this.stack.length-1;if(dir<0){let parentStart=d<0?0:this.stack[d]+4;if(this.index!=parentStart)return this.yieldBuf(buffer.findChild(parentStart,this.index,-1,0,4))}else{let after=buffer.buffer[this.index+3];if(after<(d<0?buffer.buffer.length:buffer.buffer[this.stack[d]+3]))return this.yieldBuf(after)}return d<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+dir,dir,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(dir){let index2,parent,{buffer}=this;if(buffer){if(dir>0){if(this.index<buffer.buffer.buffer.length)return!1}else for(let i=0;i<this.index;i++)if(buffer.buffer.buffer[i+3]<this.index)return!1;({index:index2,parent}=buffer)}else({index:index2,_parent:parent}=this._tree);for(;parent;{index:index2,_parent:parent}=parent)if(index2>-1)for(let i=index2+dir,e=dir<0?-1:parent._tree.children.length;i!=e;i+=dir){let child=parent._tree.children[i];if(this.mode&IterMode.IncludeAnonymous||child instanceof TreeBuffer||!child.type.isAnonymous||hasChild(child))return!1}return!0}move(dir,enter){if(enter&&this.enterChild(dir,0,4))return!0;for(;;){if(this.sibling(dir))return!0;if(this.atLastNode(dir)||!this.parent())return!1}}next(enter=!0){return this.move(1,enter)}prev(enter=!0){return this.move(-1,enter)}moveTo(pos,side=0){for(;(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to<pos))&&this.parent(););for(;this.enterChild(1,pos,side););return this}get node(){if(!this.buffer)return this._tree;let cache=this.bufferNode,result=null,depth=0;if(cache&&cache.context==this.buffer)scan:for(let index2=this.index,d=this.stack.length;d>=0;){for(let c=cache;c;c=c._parent)if(c.index==index2){if(index2==this.index)return c;result=c,depth=d+1;break scan}index2=this.stack[--d]}for(let i=depth;i<this.stack.length;i++)result=new BufferNode(this.buffer,result,this.stack[i]);return this.bufferNode=new BufferNode(this.buffer,result,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(enter,leave){for(let depth=0;;){let mustLeave=!1;if(this.type.isAnonymous||enter(this)!==!1){if(this.firstChild()){depth++;continue}this.type.isAnonymous||(mustLeave=!0)}for(;mustLeave&&leave&&leave(this),mustLeave=this.type.isAnonymous,!this.nextSibling();){if(!depth)return;this.parent(),depth--,mustLeave=!0}}}matchContext(context){if(!this.buffer)return matchNodeContext(this.node,context);let{buffer}=this.buffer,{types:types2}=buffer.set;for(let i=context.length-1,d=this.stack.length-1;i>=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types2[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return!1;i--}}return!0}};__name2(_TreeCursor,"TreeCursor");let TreeCursor=_TreeCursor;function hasChild(tree){return tree.children.some(ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch))}__name(hasChild,"hasChild"),__name2(hasChild,"hasChild");function buildTree(data){var _a3;let{buffer,nodeSet,maxBufferLength=DefaultBufferLength,reused=[],minRepeatType=nodeSet.types.length}=data,cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer,types2=nodeSet.types,contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children2,positions2,inRepeat){let{id,start,end,size}=cursor,lookAheadAtStart=lookAhead;for(;size<0;)if(cursor.next(),size==-1){let node2=reused[id];children2.push(node2),positions2.push(start-parentStart);return}else if(size==-3){contextHash=id;return}else if(size==-4){lookAhead=id;return}else throw new RangeError(`Unrecognized record size: ${size}`);let type=types2[id],node,buffer2,startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer2=findBufferSize(cursor.pos-minPos,inRepeat))){let data2=new Uint16Array(buffer2.size-buffer2.skip),endPos=cursor.pos-buffer2.size,index2=data2.length;for(;cursor.pos>endPos;)index2=copyToBuffer(buffer2.start,data2,index2);node=new TreeBuffer(data2,end-buffer2.start,nodeSet),startPos=buffer2.start-parentStart}else{let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[],localInRepeat=id>=minRepeatType?id:-1,lastGroup=0,lastEnd=end;for(;cursor.pos>endPos;)localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0?(cursor.end<=lastEnd-maxBufferLength&&(makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart),lastGroup=localChildren.length,lastEnd=cursor.end),cursor.next()):takeNode(start,endPos,localChildren,localPositions,localInRepeat);if(localInRepeat>=0&&lastGroup>0&&lastGroup<localChildren.length&&makeRepeatLeaf(localChildren,localPositions,start,lastGroup,start,lastEnd,localInRepeat,lookAheadAtStart),localChildren.reverse(),localPositions.reverse(),localInRepeat>-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make)}else node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end)}children2.push(node),positions2.push(startPos)}__name(takeNode,"takeNode"),__name2(takeNode,"takeNode");function makeBalanced(type){return(children2,positions2,length2)=>{let lookAhead2=0,lastI=children2.length-1,last2,lookAheadProp;if(lastI>=0&&(last2=children2[lastI])instanceof Tree){if(!lastI&&last2.type==type&&last2.length==length2)return last2;(lookAheadProp=last2.prop(NodeProp.lookAhead))&&(lookAhead2=positions2[lastI]+last2.length+lookAheadProp)}return makeTree(type,children2,positions2,length2,lookAhead2)}}__name(makeBalanced,"makeBalanced"),__name2(makeBalanced,"makeBalanced");function makeRepeatLeaf(children2,positions2,base2,i,from,to,type,lookAhead2){let localChildren=[],localPositions=[];for(;children2.length>i;)localChildren.push(children2.pop()),localPositions.push(positions2.pop()+base2-from);children2.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead2-to)),positions2.push(from-base2)}__name(makeRepeatLeaf,"makeRepeatLeaf"),__name2(makeRepeatLeaf,"makeRepeatLeaf");function makeTree(type,children2,positions2,length2,lookAhead2=0,props){if(contextHash){let pair2=[NodeProp.contextHash,contextHash];props=props?[pair2].concat(props):[pair2]}if(lookAhead2>25){let pair2=[NodeProp.lookAhead,lookAhead2];props=props?[pair2].concat(props):[pair2]}return new Tree(type,children2,positions2,length2,props)}__name(makeTree,"makeTree"),__name2(makeTree,"makeTree");function findBufferSize(maxSize,inRepeat){let fork=cursor.fork(),size=0,start=0,skip=0,minStart=fork.end-maxBufferLength,result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize2=fork.size;if(fork.id==inRepeat&&nodeSize2>=0){result.size=size,result.start=start,result.skip=skip,skip+=4,size+=4,fork.next();continue}let startPos=fork.pos-nodeSize2;if(nodeSize2<0||startPos<minPos||fork.start<minStart)break;let localSkipped=fork.id>=minRepeatType?4:0,nodeStart2=fork.start;for(fork.next();fork.pos>startPos;){if(fork.size<0)if(fork.size==-3)localSkipped+=4;else break scan;else fork.id>=minRepeatType&&(localSkipped+=4);fork.next()}start=nodeStart2,size+=nodeSize2,skip+=localSkipped}return(inRepeat<0||size==maxSize)&&(result.size=size,result.start=start,result.skip=skip),result.size>4?result:void 0}__name(findBufferSize,"findBufferSize"),__name2(findBufferSize,"findBufferSize");function copyToBuffer(bufferStart,buffer2,index2){let{id,start,end,size}=cursor;if(cursor.next(),size>=0&&id<minRepeatType){let startIndex=index2;if(size>4){let endPos=cursor.pos-(size-4);for(;cursor.pos>endPos;)index2=copyToBuffer(bufferStart,buffer2,index2)}buffer2[--index2]=startIndex,buffer2[--index2]=end-bufferStart,buffer2[--index2]=start-bufferStart,buffer2[--index2]=id}else size==-3?contextHash=id:size==-4&&(lookAhead=id);return index2}__name(copyToBuffer,"copyToBuffer"),__name2(copyToBuffer,"copyToBuffer");let children=[],positions=[];for(;cursor.pos>0;)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=(_a3=data.length)!==null&&_a3!==void 0?_a3:children.length?positions[0]+children[0].length:0;return new Tree(types2[data.topID],children.reverse(),positions.reverse(),length)}__name(buildTree,"buildTree"),__name2(buildTree,"buildTree");const nodeSizeCache=new WeakMap;function nodeSize(balanceType,node){if(!balanceType.isAnonymous||node instanceof TreeBuffer||node.type!=balanceType)return 1;let size=nodeSizeCache.get(node);if(size==null){size=1;for(let child of node.children){if(child.type!=balanceType||!(child instanceof Tree)){size=1;break}size+=nodeSize(balanceType,child)}nodeSizeCache.set(node,size)}return size}__name(nodeSize,"nodeSize"),__name2(nodeSize,"nodeSize");function balanceRange(balanceType,children,positions,from,to,start,length,mkTop,mkTree){let total=0;for(let i=from;i<to;i++)total+=nodeSize(balanceType,children[i]);let maxChild=Math.ceil(total*1.5/8),localChildren=[],localPositions=[];function divide(children2,positions2,from2,to2,offset2){for(let i=from2;i<to2;){let groupFrom=i,groupStart=positions2[i],groupSize=nodeSize(balanceType,children2[i]);for(i++;i<to2;i++){let nextSize=nodeSize(balanceType,children2[i]);if(groupSize+nextSize>=maxChild)break;groupSize+=nextSize}if(i==groupFrom+1){if(groupSize>maxChild){let only=children2[groupFrom];divide(only.children,only.positions,0,only.children.length,positions2[groupFrom]+offset2);continue}localChildren.push(children2[groupFrom])}else{let length2=positions2[i-1]+children2[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children2,positions2,groupFrom,i,groupStart,length2,null,mkTree))}localPositions.push(groupStart+offset2-start)}}return __name(divide,"divide"),__name2(divide,"divide"),divide(children,positions,from,to,0),(mkTop||mkTree)(localChildren,localPositions,length)}__name(balanceRange,"balanceRange"),__name2(balanceRange,"balanceRange");const _TreeFragment=class _TreeFragment2{static{__name(this,"_TreeFragment")}constructor(from,to,tree,offset2,openStart=!1,openEnd=!1){this.from=from,this.to=to,this.tree=tree,this.offset=offset2,this.open=(openStart?1:0)|(openEnd?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(tree,fragments=[],partial=!1){let result=[new _TreeFragment2(0,tree.length,tree,0,!1,partial)];for(let f2 of fragments)f2.to>tree.length&&result.push(f2);return result}static applyChanges(fragments,changes,minGap=128){if(!changes.length)return fragments;let result=[],fI=1,nextF=fragments.length?fragments[0]:null;for(let cI=0,pos=0,off2=0;;cI++){let nextC=cI<changes.length?changes[cI]:null,nextPos=nextC?nextC.fromA:1e9;if(nextPos-pos>=minGap)for(;nextF&&nextF.from<nextPos;){let cut=nextF;if(pos>=cut.from||nextPos<=cut.to||off2){let fFrom=Math.max(cut.from,pos)-off2,fTo=Math.min(cut.to,nextPos)-off2;cut=fFrom>=fTo?null:new _TreeFragment2(fFrom,fTo,cut.tree,cut.offset+off2,cI>0,!!nextC)}if(cut&&result.push(cut),nextF.to>nextPos)break;nextF=fI<fragments.length?fragments[fI++]:null}if(!nextC)break;pos=nextC.toA,off2=nextC.toA-nextC.toB}return result}};__name2(_TreeFragment,"TreeFragment");let TreeFragment=_TreeFragment;const _Parser=class{static{__name(this,"_Parser")}startParse(input,fragments,ranges){return typeof input=="string"&&(input=new StringInput(input)),ranges=ranges?ranges.length?ranges.map(r=>new Range(r.from,r.to)):[new Range(0,0)]:[new Range(0,input.length)],this.createParse(input,fragments||[],ranges)}parse(input,fragments,ranges){let parse2=this.startParse(input,fragments,ranges);for(;;){let done=parse2.advance();if(done)return done}}};__name2(_Parser,"Parser");let Parser=_Parser;const _StringInput=class{static{__name(this,"_StringInput")}constructor(string2){this.string=string2}get length(){return this.string.length}chunk(from){return this.string.slice(from)}get lineChunks(){return!1}read(from,to){return this.string.slice(from,to)}};__name2(_StringInput,"StringInput");let StringInput=_StringInput;new NodeProp({perNode:!0});let nextTagID=0;const _Tag=class _Tag2{static{__name(this,"_Tag")}constructor(set,base2,modified){this.set=set,this.base=base2,this.modified=modified,this.id=nextTagID++}static define(parent){if(parent?.base)throw new Error("Can not derive from a modified tag");let tag=new _Tag2([],null,[]);if(tag.set.push(tag),parent)for(let t2 of parent.set)tag.set.push(t2);return tag}static defineModifier(){let mod=new Modifier;return tag=>tag.modified.indexOf(mod)>-1?tag:Modifier.get(tag.base||tag,tag.modified.concat(mod).sort((a,b)=>a.id-b.id))}};__name2(_Tag,"Tag");let Tag=_Tag,nextModifierID=0;const _Modifier=class _Modifier2{static{__name(this,"_Modifier")}constructor(){this.instances=[],this.id=nextModifierID++}static get(base2,mods){if(!mods.length)return base2;let exists=mods[0].instances.find(t2=>t2.base==base2&&sameArray(mods,t2.modified));if(exists)return exists;let set=[],tag=new Tag(set,base2,mods);for(let m of mods)m.instances.push(tag);let configs=powerSet(mods);for(let parent of base2.set)if(!parent.modified.length)for(let config2 of configs)set.push(_Modifier2.get(parent,config2));return tag}};__name2(_Modifier,"Modifier");let Modifier=_Modifier;function sameArray(a,b){return a.length==b.length&&a.every((x,i)=>x==b[i])}__name(sameArray,"sameArray"),__name2(sameArray,"sameArray");function powerSet(array){let sets=[[]];for(let i=0;i<array.length;i++)for(let j=0,e=sets.length;j<e;j++)sets.push(sets[j].concat(array[i]));return sets.sort((a,b)=>b.length-a.length)}__name(powerSet,"powerSet"),__name2(powerSet,"powerSet");function styleTags(spec){let byName=Object.create(null);for(let prop in spec){let tags2=spec[prop];Array.isArray(tags2)||(tags2=[tags2]);for(let part of prop.split(" "))if(part){let pieces=[],mode=2,rest=part;for(let pos=0;;){if(rest=="..."&&pos>0&&pos+3==part.length){mode=1;break}let m=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);if(!m)throw new RangeError("Invalid path: "+part);if(pieces.push(m[0]=="*"?"":m[0][0]=='"'?JSON.parse(m[0]):m[0]),pos+=m[0].length,pos==part.length)break;let next=part[pos++];if(pos==part.length&&next=="!"){mode=0;break}if(next!="/")throw new RangeError("Invalid path: "+part);rest=part.slice(pos)}let last2=pieces.length-1,inner=pieces[last2];if(!inner)throw new RangeError("Invalid path: "+part);let rule=new Rule(tags2,mode,last2>0?pieces.slice(0,last2):null);byName[inner]=rule.sort(byName[inner])}}return ruleNodeProp.add(byName)}__name(styleTags,"styleTags"),__name2(styleTags,"styleTags");const ruleNodeProp=new NodeProp,_Rule=class{static{__name(this,"_Rule")}constructor(tags2,mode,context,next){this.tags=tags2,this.mode=mode,this.context=context,this.next=next}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(other){return!other||other.depth<this.depth?(this.next=other,this):(other.next=this.sort(other.next),other)}get depth(){return this.context?this.context.length:0}};__name2(_Rule,"Rule");let Rule=_Rule;Rule.empty=new Rule([],2,null);function tagHighlighter(tags2,options){let map2=Object.create(null);for(let style of tags2)if(!Array.isArray(style.tag))map2[style.tag.id]=style.class;else for(let tag of style.tag)map2[tag.id]=style.class;let{scope:scope2,all=null}=options||{};return{style:tags3=>{let cls=all;for(let tag of tags3)for(let sub of tag.set){let tagClass=map2[sub.id];if(tagClass){cls=cls?cls+" "+tagClass:tagClass;break}}return cls},scope:scope2}}__name(tagHighlighter,"tagHighlighter"),__name2(tagHighlighter,"tagHighlighter");function highlightTags(highlighters,tags2){let result=null;for(let highlighter of highlighters){let value=highlighter.style(tags2);value&&(result=result?result+" "+value:value)}return result}__name(highlightTags,"highlightTags"),__name2(highlightTags,"highlightTags");function highlightTree(tree,highlighter,putStyle,from=0,to=tree.length){let builder=new HighlightBuilder(from,Array.isArray(highlighter)?highlighter:[highlighter],putStyle);builder.highlightRange(tree.cursor(),from,to,"",builder.highlighters),builder.flush(to)}__name(highlightTree,"highlightTree"),__name2(highlightTree,"highlightTree");const _HighlightBuilder=class{static{__name(this,"_HighlightBuilder")}constructor(at,highlighters,span){this.at=at,this.highlighters=highlighters,this.span=span,this.class=""}startSpan(at,cls){cls!=this.class&&(this.flush(at),at>this.at&&(this.at=at),this.class=cls)}flush(to){to>this.at&&this.class&&this.span(this.at,to,this.class)}highlightRange(cursor,from,to,inheritedClass,highlighters){let{type,from:start,to:end}=cursor;if(start>=to||end<=from)return;type.isTop&&(highlighters=this.highlighters.filter(h=>!h.scope||h.scope(type)));let cls=inheritedClass,rule=getStyleTags(cursor)||Rule.empty,tagCls=highlightTags(highlighters,rule.tags);if(tagCls&&(cls&&(cls+=" "),cls+=tagCls,rule.mode==1&&(inheritedClass+=(inheritedClass?" ":"")+tagCls)),this.startSpan(Math.max(from,start),cls),rule.opaque)return;let mounted=cursor.tree&&cursor.tree.prop(NodeProp.mounted);if(mounted&&mounted.overlay){let inner=cursor.node.enter(mounted.overlay[0].from+start,1),innerHighlighters=this.highlighters.filter(h=>!h.scope||h.scope(mounted.tree.type)),hasChild2=cursor.firstChild();for(let i=0,pos=start;;i++){let next=i<mounted.overlay.length?mounted.overlay[i]:null,nextPos=next?next.from+start:end,rangeFrom=Math.max(from,pos),rangeTo=Math.min(to,nextPos);if(rangeFrom<rangeTo&&hasChild2)for(;cursor.from<rangeTo&&(this.highlightRange(cursor,rangeFrom,rangeTo,inheritedClass,highlighters),this.startSpan(Math.min(rangeTo,cursor.to),cls),!(cursor.to>=nextPos||!cursor.nextSibling())););if(!next||nextPos>to)break;pos=next.to+start,pos>from&&(this.highlightRange(inner.cursor(),Math.max(from,next.from+start),Math.min(to,pos),"",innerHighlighters),this.startSpan(Math.min(to,pos),cls))}hasChild2&&cursor.parent()}else if(cursor.firstChild()){mounted&&(inheritedClass="");do if(!(cursor.to<=from)){if(cursor.from>=to)break;this.highlightRange(cursor,from,to,inheritedClass,highlighters),this.startSpan(Math.min(to,cursor.to),cls)}while(cursor.nextSibling());cursor.parent()}}};__name2(_HighlightBuilder,"HighlightBuilder");let HighlightBuilder=_HighlightBuilder;function getStyleTags(node){let rule=node.type.prop(ruleNodeProp);for(;rule&&rule.context&&!node.matchContext(rule.context);)rule=rule.next;return rule||null}__name(getStyleTags,"getStyleTags"),__name2(getStyleTags,"getStyleTags");const t=Tag.define,comment=t(),name=t(),typeName=t(name),propertyName=t(name),literal=t(),string=t(literal),number=t(literal),content=t(),heading=t(content),keyword=t(),operator=t(),punctuation=t(),bracket=t(punctuation),meta=t(),tags={comment,lineComment:t(comment),blockComment:t(comment),docComment:t(comment),name,variableName:t(name),typeName,tagName:t(typeName),propertyName,attributeName:t(propertyName),className:t(name),labelName:t(name),namespace:t(name),macroName:t(name),literal,string,docString:t(string),character:t(string),attributeValue:t(string),number,integer:t(number),float:t(number),bool:t(literal),regexp:t(literal),escape:t(literal),color:t(literal),url:t(literal),keyword,self:t(keyword),null:t(keyword),atom:t(keyword),unit:t(keyword),modifier:t(keyword),operatorKeyword:t(keyword),controlKeyword:t(keyword),definitionKeyword:t(keyword),moduleKeyword:t(keyword),operator,derefOperator:t(operator),arithmeticOperator:t(operator),logicOperator:t(operator),bitwiseOperator:t(operator),compareOperator:t(operator),updateOperator:t(operator),definitionOperator:t(operator),typeOperator:t(operator),controlOperator:t(operator),punctuation,separator:t(punctuation),bracket,angleBracket:t(bracket),squareBracket:t(bracket),paren:t(bracket),brace:t(bracket),content,heading,heading1:t(heading),heading2:t(heading),heading3:t(heading),heading4:t(heading),heading5:t(heading),heading6:t(heading),contentSeparator:t(content),list:t(content),quote:t(content),emphasis:t(content),strong:t(content),link:t(content),monospace:t(content),strikethrough:t(content),inserted:t(),deleted:t(),changed:t(),invalid:t(),meta,documentMeta:t(meta),annotation:t(meta),processingInstruction:t(meta),definition:Tag.defineModifier(),constant:Tag.defineModifier(),function:Tag.defineModifier(),standard:Tag.defineModifier(),local:Tag.defineModifier(),special:Tag.defineModifier()};tagHighlighter([{tag:tags.link,class:"tok-link"},{tag:tags.heading,class:"tok-heading"},{tag:tags.emphasis,class:"tok-emphasis"},{tag:tags.strong,class:"tok-strong"},{tag:tags.keyword,class:"tok-keyword"},{tag:tags.atom,class:"tok-atom"},{tag:tags.bool,class:"tok-bool"},{tag:tags.url,class:"tok-url"},{tag:tags.labelName,class:"tok-labelName"},{tag:tags.inserted,class:"tok-inserted"},{tag:tags.deleted,class:"tok-deleted"},{tag:tags.literal,class:"tok-literal"},{tag:tags.string,class:"tok-string"},{tag:tags.number,class:"tok-number"},{tag:[tags.regexp,tags.escape,tags.special(tags.string)],class:"tok-string2"},{tag:tags.variableName,class:"tok-variableName"},{tag:tags.local(tags.variableName),class:"tok-variableName tok-local"},{tag:tags.definition(tags.variableName),class:"tok-variableName tok-definition"},{tag:tags.special(tags.variableName),class:"tok-variableName2"},{tag:tags.definition(tags.propertyName),class:"tok-propertyName tok-definition"},{tag:tags.typeName,class:"tok-typeName"},{tag:tags.namespace,class:"tok-namespace"},{tag:tags.className,class:"tok-className"},{tag:tags.macroName,class:"tok-macroName"},{tag:tags.propertyName,class:"tok-propertyName"},{tag:tags.operator,class:"tok-operator"},{tag:tags.comment,class:"tok-comment"},{tag:tags.meta,class:"tok-meta"},{tag:tags.invalid,class:"tok-invalid"},{tag:tags.punctuation,class:"tok-punctuation"}]);var _a2;const languageDataProp=new NodeProp;function defineLanguageFacet(baseData){return Facet.define({combine:baseData?values=>values.concat(baseData):void 0})}__name(defineLanguageFacet,"defineLanguageFacet"),__name2(defineLanguageFacet,"defineLanguageFacet");const sublanguageProp=new NodeProp,_Language=class{static{__name(this,"_Language")}constructor(data,parser2,extraExtensions=[],name2=""){this.data=data,this.name=name2,EditorState.prototype.hasOwnProperty("tree")||Object.defineProperty(EditorState.prototype,"tree",{get(){return syntaxTree(this)}}),this.parser=parser2,this.extension=[language.of(this),EditorState.languageData.of((state,pos,side)=>{let top2=topNodeAt(state,pos,side),data2=top2.type.prop(languageDataProp);if(!data2)return[];let base2=state.facet(data2),sub=top2.type.prop(sublanguageProp);if(sub){let innerNode=top2.resolve(pos-top2.from,side);for(let sublang of sub)if(sublang.test(innerNode,state)){let data3=state.facet(sublang.facet);return sublang.type=="replace"?data3:data3.concat(base2)}}return base2})].concat(extraExtensions)}isActiveAt(state,pos,side=-1){return topNodeAt(state,pos,side).type.prop(languageDataProp)==this.data}findRegions(state){let lang=state.facet(language);if(lang?.data==this.data)return[{from:0,to:state.doc.length}];if(!lang||!lang.allowsNesting)return[];let result=[],explore=__name2((tree,from)=>{if(tree.prop(languageDataProp)==this.data){result.push({from,to:from+tree.length});return}let mount2=tree.prop(NodeProp.mounted);if(mount2){if(mount2.tree.prop(languageDataProp)==this.data){if(mount2.overlay)for(let r of mount2.overlay)result.push({from:r.from+from,to:r.to+from});else result.push({from,to:from+tree.length});return}else if(mount2.overlay){let size=result.length;if(explore(mount2.tree,mount2.overlay[0].from+from),result.length>size)return}}for(let i=0;i<tree.children.length;i++){let ch=tree.children[i];ch instanceof Tree&&explore(ch,tree.positions[i]+from)}},"explore");return explore(syntaxTree(state),0),result}get allowsNesting(){return!0}};__name2(_Language,"Language");let Language=_Language;Language.setState=StateEffect.define();function topNodeAt(state,pos,side){let topLang=state.facet(language),tree=syntaxTree(state).topNode;if(!topLang||topLang.allowsNesting)for(let node=tree;node;node=node.enter(pos,side,IterMode.ExcludeBuffers))node.type.isTop&&(tree=node);return tree}__name(topNodeAt,"topNodeAt"),__name2(topNodeAt,"topNodeAt");const _LRLanguage=class _LRLanguage2 extends Language{static{__name(this,"_LRLanguage")}constructor(data,parser2,name2){super(data,parser2,[],name2),this.parser=parser2}static define(spec){let data=defineLanguageFacet(spec.languageData);return new _LRLanguage2(data,spec.parser.configure({props:[languageDataProp.add(type=>type.isTop?data:void 0)]}),spec.name)}configure(options,name2){return new _LRLanguage2(this.data,this.parser.configure(options),name2||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};__name2(_LRLanguage,"LRLanguage");let LRLanguage=_LRLanguage;function syntaxTree(state){let field=state.field(Language.state,!1);return field?field.tree:Tree.empty}__name(syntaxTree,"syntaxTree"),__name2(syntaxTree,"syntaxTree");const _DocInput=class{static{__name(this,"_DocInput")}constructor(doc2){this.doc=doc2,this.cursorPos=0,this.string="",this.cursor=doc2.iter()}get length(){return this.doc.length}syncTo(pos){return this.string=this.cursor.next(pos-this.cursorPos).value,this.cursorPos=pos+this.string.length,this.cursorPos-this.string.length}chunk(pos){return this.syncTo(pos),this.string}get lineChunks(){return!0}read(from,to){let stringStart=this.cursorPos-this.string.length;return from<stringStart||to>=this.cursorPos?this.doc.sliceString(from,to):this.string.slice(from-stringStart,to-stringStart)}};__name2(_DocInput,"DocInput");let DocInput=_DocInput,currentContext=null;const _ParseContext=class _ParseContext2{static{__name(this,"_ParseContext")}constructor(parser2,state,fragments=[],tree,treeLen,viewport,skipped,scheduleOn){this.parser=parser2,this.state=state,this.fragments=fragments,this.tree=tree,this.treeLen=treeLen,this.viewport=viewport,this.skipped=skipped,this.scheduleOn=scheduleOn,this.parse=null,this.tempSkipped=[]}static create(parser2,state,viewport){return new _ParseContext2(parser2,state,[],Tree.empty,0,viewport,[],null)}startParse(){return this.parser.startParse(new DocInput(this.state.doc),this.fragments)}work(until,upto){return upto!=null&&upto>=this.state.doc.length&&(upto=void 0),this.tree!=Tree.empty&&this.isDone(upto??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var _a3;if(typeof until=="number"){let endTime=Date.now()+until;until=__name2(()=>Date.now()>endTime,"until")}for(this.parse||(this.parse=this.startParse()),upto!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>upto)&&upto<this.state.doc.length&&this.parse.stopAt(upto);;){let done=this.parse.advance();if(done)if(this.fragments=this.withoutTempSkipped(TreeFragment.addTree(done,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=(_a3=this.parse.stoppedAt)!==null&&_a3!==void 0?_a3:this.state.doc.length,this.tree=done,this.parse=null,this.treeLen<(upto??this.state.doc.length))this.parse=this.startParse();else return!0;if(until())return!1}})}takeTree(){let pos,tree;this.parse&&(pos=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>pos)&&this.parse.stopAt(pos),this.withContext(()=>{for(;!(tree=this.parse.advance()););}),this.treeLen=pos,this.tree=tree,this.fragments=this.withoutTempSkipped(TreeFragment.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(f2){let prev=currentContext;currentContext=this;try{return f2()}finally{currentContext=prev}}withoutTempSkipped(fragments){for(let r;r=this.tempSkipped.pop();)fragments=cutFragments(fragments,r.from,r.to);return fragments}changes(changes,newState){let{fragments,tree,treeLen,viewport,skipped}=this;if(this.takeTree(),!changes.empty){let ranges=[];if(changes.iterChangedRanges((fromA,toA,fromB,toB)=>ranges.push({fromA,toA,fromB,toB})),fragments=TreeFragment.applyChanges(fragments,ranges),tree=Tree.empty,treeLen=0,viewport={from:changes.mapPos(viewport.from,-1),to:changes.mapPos(viewport.to,1)},this.skipped.length){skipped=[];for(let r of this.skipped){let from=changes.mapPos(r.from,1),to=changes.mapPos(r.to,-1);from<to&&skipped.push({from,to})}}}return new _ParseContext2(this.parser,newState,fragments,tree,treeLen,viewport,skipped,this.scheduleOn)}updateViewport(viewport){if(this.viewport.from==viewport.from&&this.viewport.to==viewport.to)return!1;this.viewport=viewport;let startLen=this.skipped.length;for(let i=0;i<this.skipped.length;i++){let{from,to}=this.skipped[i];from<viewport.to&&to>viewport.from&&(this.fragments=cutFragments(this.fragments,from,to),this.skipped.splice(i--,1))}return this.skipped.length>=startLen?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(from,to){this.skipped.push({from,to})}static getSkippingParser(until){return new class extends Parser{createParse(input,fragments,ranges){let from=ranges[0].from,to=ranges[ranges.length-1].to;return{parsedPos:from,advance(){let cx=currentContext;if(cx){for(let r of ranges)cx.tempSkipped.push(r);until&&(cx.scheduleOn=cx.scheduleOn?Promise.all([cx.scheduleOn,until]):until)}return this.parsedPos=to,new Tree(NodeType.none,[],[],to-from)},stoppedAt:null,stopAt(){}}}}}isDone(upto){upto=Math.min(upto,this.state.doc.length);let frags=this.fragments;return this.treeLen>=upto&&frags.length&&frags[0].from==0&&frags[0].to>=upto}static get(){return currentContext}};__name2(_ParseContext,"ParseContext");let ParseContext=_ParseContext;function cutFragments(fragments,from,to){return TreeFragment.applyChanges(fragments,[{fromA:from,toA:to,fromB:from,toB:to}])}__name(cutFragments,"cutFragments"),__name2(cutFragments,"cutFragments");const _LanguageState=class _LanguageState2{static{__name(this,"_LanguageState")}constructor(context){this.context=context,this.tree=context.tree}apply(tr){if(!tr.docChanged&&this.tree==this.context.tree)return this;let newCx=this.context.changes(tr.changes,tr.state),upto=this.context.treeLen==tr.startState.doc.length?void 0:Math.max(tr.changes.mapPos(this.context.treeLen),newCx.viewport.to);return newCx.work(20,upto)||newCx.takeTree(),new _LanguageState2(newCx)}static init(state){let vpTo=Math.min(3e3,state.doc.length),parseState=ParseContext.create(state.facet(language).parser,state,{from:0,to:vpTo});return parseState.work(20,vpTo)||parseState.takeTree(),new _LanguageState2(parseState)}};__name2(_LanguageState,"LanguageState");let LanguageState=_LanguageState;Language.state=StateField.define({create:LanguageState.init,update(value,tr){for(let e of tr.effects)if(e.is(Language.setState))return e.value;return tr.startState.facet(language)!=tr.state.facet(language)?LanguageState.init(tr.state):value.apply(tr)}});let requestIdle=__name2(callback=>{let timeout=setTimeout(()=>callback(),500);return()=>clearTimeout(timeout)},"requestIdle");typeof requestIdleCallback<"u"&&(requestIdle=__name2(callback=>{let idle=-1,timeout=setTimeout(()=>{idle=requestIdleCallback(callback,{timeout:500-100})},100);return()=>idle<0?clearTimeout(timeout):cancelIdleCallback(idle)},"requestIdle"));const isInputPending=typeof navigator<"u"&&(!((_a2=navigator.scheduling)===null||_a2===void 0)&&_a2.isInputPending)?()=>navigator.scheduling.isInputPending():null,parseWorker=ViewPlugin.fromClass((_c=class{static{__name(this,"_c")}constructor(view){this.view=view,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(update){let cx=this.view.state.field(Language.state).context;(cx.updateViewport(update.view.viewport)||this.view.viewport.to>cx.treeLen)&&this.scheduleWork(),update.docChanged&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(cx)}scheduleWork(){if(this.working)return;let{state}=this.view,field=state.field(Language.state);(field.tree!=field.context.tree||!field.context.isDone(state.doc.length))&&(this.working=requestIdle(this.work))}work(deadline){this.working=null;let now2=Date.now();if(this.chunkEnd<now2&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=now2+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state,viewport:{to:vpTo}}=this.view,field=state.field(Language.state);if(field.tree==field.context.tree&&field.context.isDone(vpTo+1e5))return;let endTime=Date.now()+Math.min(this.chunkBudget,100,deadline&&!isInputPending?Math.max(25,deadline.timeRemaining()-5):1e9),viewportFirst=field.context.treeLen<vpTo&&state.doc.length>vpTo+1e3,done=field.context.work(()=>isInputPending&&isInputPending()||Date.now()>endTime,vpTo+(viewportFirst?0:1e5));this.chunkBudget-=Date.now()-now2,(done||this.chunkBudget<=0)&&(field.context.takeTree(),this.view.dispatch({effects:Language.setState.of(new LanguageState(field.context))})),this.chunkBudget>0&&!(done&&!viewportFirst)&&this.scheduleWork(),this.checkAsyncSchedule(field.context)}checkAsyncSchedule(cx){cx.scheduleOn&&(this.workScheduled++,cx.scheduleOn.then(()=>this.scheduleWork()).catch(err=>logException(this.view.state,err)).then(()=>this.workScheduled--),cx.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},__name2(_c,"ParseWorker"),_c),{eventHandlers:{focus(){this.scheduleWork()}}}),language=Facet.define({combine(languages){return languages.length?languages[0]:null},enables:language2=>[Language.state,parseWorker,EditorView.contentAttributes.compute([language2],state=>{let lang=state.facet(language2);return lang&&lang.name?{"data-language":lang.name}:{}})]}),_LanguageSupport=class{static{__name(this,"_LanguageSupport")}constructor(language2,support=[]){this.language=language2,this.support=support,this.extension=[language2,support]}};__name2(_LanguageSupport,"LanguageSupport");let LanguageSupport=_LanguageSupport;const indentService=Facet.define(),indentUnit=Facet.define({combine:values=>{if(!values.length)return" ";let unit=values[0];if(!unit||/\S/.test(unit)||Array.from(unit).some(e=>e!=unit[0]))throw new Error("Invalid indent unit: "+JSON.stringify(values[0]));return unit}});function getIndentUnit(state){let unit=state.facet(indentUnit);return unit.charCodeAt(0)==9?state.tabSize*unit.length:unit.length}__name(getIndentUnit,"getIndentUnit"),__name2(getIndentUnit,"getIndentUnit");function indentString(state,cols){let result="",ts=state.tabSize,ch=state.facet(indentUnit)[0];if(ch==" "){for(;cols>=ts;)result+=" ",cols-=ts;ch=" "}for(let i=0;i<cols;i++)result+=ch;return result}__name(indentString,"indentString"),__name2(indentString,"indentString");function getIndentation(context,pos){context instanceof EditorState&&(context=new IndentContext(context));for(let service of context.state.facet(indentService)){let result=service(context,pos);if(result!==void 0)return result}let tree=syntaxTree(context.state);return tree?syntaxIndentation(context,tree,pos):null}__name(getIndentation,"getIndentation"),__name2(getIndentation,"getIndentation");const _IndentContext=class{static{__name(this,"_IndentContext")}constructor(state,options={}){this.state=state,this.options=options,this.unit=getIndentUnit(state)}lineAt(pos,bias=1){let line=this.state.doc.lineAt(pos),{simulateBreak,simulateDoubleBreak}=this.options;return simulateBreak!=null&&simulateBreak>=line.from&&simulateBreak<=line.to?simulateDoubleBreak&&simulateBreak==pos?{text:"",from:pos}:(bias<0?simulateBreak<pos:simulateBreak<=pos)?{text:line.text.slice(simulateBreak-line.from),from:simulateBreak}:{text:line.text.slice(0,simulateBreak-line.from),from:line.from}:line}textAfterPos(pos,bias=1){if(this.options.simulateDoubleBreak&&pos==this.options.simulateBreak)return"";let{text,from}=this.lineAt(pos,bias);return text.slice(pos-from,Math.min(text.length,pos+100-from))}column(pos,bias=1){let{text,from}=this.lineAt(pos,bias),result=this.countColumn(text,pos-from),override=this.options.overrideIndentation?this.options.overrideIndentation(from):-1;return override>-1&&(result+=override-this.countColumn(text,text.search(/\S|$/))),result}countColumn(line,pos=line.length){return countColumn(line,this.state.tabSize,pos)}lineIndent(pos,bias=1){let{text,from}=this.lineAt(pos,bias),override=this.options.overrideIndentation;if(override){let overriden=override(from);if(overriden>-1)return overriden}return this.countColumn(text,text.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}};__name2(_IndentContext,"IndentContext");let IndentContext=_IndentContext;const indentNodeProp=new NodeProp;function syntaxIndentation(cx,ast,pos){return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos),pos,cx)}__name(syntaxIndentation,"syntaxIndentation"),__name2(syntaxIndentation,"syntaxIndentation");function ignoreClosed(cx){return cx.pos==cx.options.simulateBreak&&cx.options.simulateDoubleBreak}__name(ignoreClosed,"ignoreClosed"),__name2(ignoreClosed,"ignoreClosed");function indentStrategy(tree){let strategy=tree.type.prop(indentNodeProp);if(strategy)return strategy;let first=tree.firstChild,close;if(first&&(close=first.type.prop(NodeProp.closedBy))){let last2=tree.lastChild,closed=last2&&close.indexOf(last2.name)>-1;return cx=>delimitedStrategy(cx,!0,1,void 0,closed&&!ignoreClosed(cx)?last2.from:void 0)}return tree.parent==null?topIndent:null}__name(indentStrategy,"indentStrategy"),__name2(indentStrategy,"indentStrategy");function indentFrom(node,pos,base2){for(;node;node=node.parent){let strategy=indentStrategy(node);if(strategy)return strategy(TreeIndentContext.create(base2,pos,node))}return null}__name(indentFrom,"indentFrom"),__name2(indentFrom,"indentFrom");function topIndent(){return 0}__name(topIndent,"topIndent"),__name2(topIndent,"topIndent");const _TreeIndentContext=class _TreeIndentContext2 extends IndentContext{static{__name(this,"_TreeIndentContext")}constructor(base2,pos,node){super(base2.state,base2.options),this.base=base2,this.pos=pos,this.node=node}static create(base2,pos,node){return new _TreeIndentContext2(base2,pos,node)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(node){let line=this.state.doc.lineAt(node.from);for(;;){let atBreak=node.resolve(line.from);for(;atBreak.parent&&atBreak.parent.from==atBreak.from;)atBreak=atBreak.parent;if(isParent(atBreak,node))break;line=this.state.doc.lineAt(atBreak.from)}return this.lineIndent(line.from)}continue(){let parent=this.node.parent;return parent?indentFrom(parent,this.pos,this.base):0}};__name2(_TreeIndentContext,"TreeIndentContext");let TreeIndentContext=_TreeIndentContext;function isParent(parent,of){for(let cur2=of;cur2;cur2=cur2.parent)if(parent==cur2)return!0;return!1}__name(isParent,"isParent"),__name2(isParent,"isParent");function bracketedAligned(context){let tree=context.node,openToken=tree.childAfter(tree.from),last2=tree.lastChild;if(!openToken)return null;let sim=context.options.simulateBreak,openLine=context.state.doc.lineAt(openToken.from),lineEnd=sim==null||sim<=openLine.from?openLine.to:Math.min(openLine.to,sim);for(let pos=openToken.to;;){let next=tree.childAfter(pos);if(!next||next==last2)return null;if(!next.type.isSkipped)return next.from<lineEnd?openToken:null;pos=next.to}}__name(bracketedAligned,"bracketedAligned"),__name2(bracketedAligned,"bracketedAligned");function delimitedStrategy(context,align,units,closing2,closedAt){let after=context.textAfter,space=after.match(/^\s*/)[0].length,closed=closing2&&after.slice(space,space+closing2.length)==closing2||closedAt==context.pos+space,aligned=align?bracketedAligned(context):null;return aligned?closed?context.column(aligned.from):context.column(aligned.to):context.baseIndent+(closed?0:context.unit*units)}__name(delimitedStrategy,"delimitedStrategy"),__name2(delimitedStrategy,"delimitedStrategy");function continuedIndent({except,units=1}={}){return context=>{let matchExcept=except&&except.test(context.textAfter);return context.baseIndent+(matchExcept?0:units*context.unit)}}__name(continuedIndent,"continuedIndent"),__name2(continuedIndent,"continuedIndent");const DontIndentBeyond=200;function indentOnInput(){return EditorState.transactionFilter.of(tr=>{if(!tr.docChanged||!tr.isUserEvent("input.type")&&!tr.isUserEvent("input.complete"))return tr;let rules=tr.startState.languageDataAt("indentOnInput",tr.startState.selection.main.head);if(!rules.length)return tr;let doc2=tr.newDoc,{head}=tr.newSelection.main,line=doc2.lineAt(head);if(head>line.from+DontIndentBeyond)return tr;let lineStart=doc2.sliceString(line.from,head);if(!rules.some(r=>r.test(lineStart)))return tr;let{state}=tr,last2=-1,changes=[];for(let{head:head2}of state.selection.ranges){let line2=state.doc.lineAt(head2);if(line2.from==last2)continue;last2=line2.from;let indent=getIndentation(state,line2.from);if(indent==null)continue;let cur2=/^\s*/.exec(line2.text)[0],norm=indentString(state,indent);cur2!=norm&&changes.push({from:line2.from,to:line2.from+cur2.length,insert:norm})}return changes.length?[tr,{changes,sequential:!0}]:tr})}__name(indentOnInput,"indentOnInput"),__name2(indentOnInput,"indentOnInput");const foldService=Facet.define(),foldNodeProp=new NodeProp;function foldInside(node){let first=node.firstChild,last2=node.lastChild;return first&&first.to<last2.from?{from:first.to,to:last2.type.isError?node.to:last2.from}:null}__name(foldInside,"foldInside"),__name2(foldInside,"foldInside");function syntaxFolding(state,start,end){let tree=syntaxTree(state);if(tree.length<end)return null;let inner=tree.resolveInner(end,1),found=null;for(let cur2=inner;cur2;cur2=cur2.parent){if(cur2.to<=end||cur2.from>end)continue;if(found&&cur2.from<start)break;let prop=cur2.type.prop(foldNodeProp);if(prop&&(cur2.to<tree.length-50||tree.length==state.doc.length||!isUnfinished(cur2))){let value=prop(cur2,state);value&&value.from<=end&&value.from>=start&&value.to>end&&(found=value)}}return found}__name(syntaxFolding,"syntaxFolding"),__name2(syntaxFolding,"syntaxFolding");function isUnfinished(node){let ch=node.lastChild;return ch&&ch.to==node.to&&ch.type.isError}__name(isUnfinished,"isUnfinished"),__name2(isUnfinished,"isUnfinished");function foldable(state,lineStart,lineEnd){for(let service of state.facet(foldService)){let result=service(state,lineStart,lineEnd);if(result)return result}return syntaxFolding(state,lineStart,lineEnd)}__name(foldable,"foldable"),__name2(foldable,"foldable");function mapRange(range,mapping){let from=mapping.mapPos(range.from,1),to=mapping.mapPos(range.to,-1);return from>=to?void 0:{from,to}}__name(mapRange,"mapRange"),__name2(mapRange,"mapRange");const foldEffect=StateEffect.define({map:mapRange}),unfoldEffect=StateEffect.define({map:mapRange});function selectedLines(view){let lines=[];for(let{head}of view.state.selection.ranges)lines.some(l2=>l2.from<=head&&l2.to>=head)||lines.push(view.lineBlockAt(head));return lines}__name(selectedLines,"selectedLines"),__name2(selectedLines,"selectedLines");const foldState=StateField.define({create(){return Decoration.none},update(folded,tr){folded=folded.map(tr.changes);for(let e of tr.effects)e.is(foldEffect)&&!foldExists(folded,e.value.from,e.value.to)?folded=folded.update({add:[foldWidget.range(e.value.from,e.value.to)]}):e.is(unfoldEffect)&&(folded=folded.update({filter:(from,to)=>e.value.from!=from||e.value.to!=to,filterFrom:e.value.from,filterTo:e.value.to}));if(tr.selection){let onSelection=!1,{head}=tr.selection.main;folded.between(head,head,(a,b)=>{a<head&&b>head&&(onSelection=!0)}),onSelection&&(folded=folded.update({filterFrom:head,filterTo:head,filter:(a,b)=>b<=head||a>=head}))}return folded},provide:f2=>EditorView.decorations.from(f2),toJSON(folded,state){let ranges=[];return folded.between(0,state.doc.length,(from,to)=>{ranges.push(from,to)}),ranges},fromJSON(value){if(!Array.isArray(value)||value.length%2)throw new RangeError("Invalid JSON for fold state");let ranges=[];for(let i=0;i<value.length;){let from=value[i++],to=value[i++];if(typeof from!="number"||typeof to!="number")throw new RangeError("Invalid JSON for fold state");ranges.push(foldWidget.range(from,to))}return Decoration.set(ranges,!0)}});function findFold(state,from,to){var _a3;let found=null;return(_a3=state.field(foldState,!1))===null||_a3===void 0||_a3.between(from,to,(from2,to2)=>{(!found||found.from>from2)&&(found={from:from2,to:to2})}),found}__name(findFold,"findFold"),__name2(findFold,"findFold");function foldExists(folded,from,to){let found=!1;return folded.between(from,from,(a,b)=>{a==from&&b==to&&(found=!0)}),found}__name(foldExists,"foldExists"),__name2(foldExists,"foldExists");function maybeEnable(state,other){return state.field(foldState,!1)?other:other.concat(StateEffect.appendConfig.of(codeFolding()))}__name(maybeEnable,"maybeEnable"),__name2(maybeEnable,"maybeEnable");const foldCode=__name2(view=>{for(let line of selectedLines(view)){let range=foldable(view.state,line.from,line.to);if(range)return view.dispatch({effects:maybeEnable(view.state,[foldEffect.of(range),announceFold(view,range)])}),!0}return!1},"foldCode"),unfoldCode=__name2(view=>{if(!view.state.field(foldState,!1))return!1;let effects=[];for(let line of selectedLines(view)){let folded=findFold(view.state,line.from,line.to);folded&&effects.push(unfoldEffect.of(folded),announceFold(view,folded,!1))}return effects.length&&view.dispatch({effects}),effects.length>0},"unfoldCode");function announceFold(view,range,fold=!0){let lineFrom=view.state.doc.lineAt(range.from).number,lineTo=view.state.doc.lineAt(range.to).number;return EditorView.announce.of(`${view.state.phrase(fold?"Folded lines":"Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`)}__name(announceFold,"announceFold"),__name2(announceFold,"announceFold");const foldAll=__name2(view=>{let{state}=view,effects=[];for(let pos=0;pos<state.doc.length;){let line=view.lineBlockAt(pos),range=foldable(state,line.from,line.to);range&&effects.push(foldEffect.of(range)),pos=(range?view.lineBlockAt(range.to):line).to+1}return effects.length&&view.dispatch({effects:maybeEnable(view.state,effects)}),!!effects.length},"foldAll"),unfoldAll=__name2(view=>{let field=view.state.field(foldState,!1);if(!field||!field.size)return!1;let effects=[];return field.between(0,view.state.doc.length,(from,to)=>{effects.push(unfoldEffect.of({from,to}))}),view.dispatch({effects}),!0},"unfoldAll"),foldKeymap=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:foldCode},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:unfoldCode},{key:"Ctrl-Alt-[",run:foldAll},{key:"Ctrl-Alt-]",run:unfoldAll}],defaultConfig={placeholderDOM:null,placeholderText:"\u2026"},foldConfig=Facet.define({combine(values){return combineConfig(values,defaultConfig)}});function codeFolding(config2){let result=[foldState,baseTheme$1$1];return config2&&result.push(foldConfig.of(config2)),result}__name(codeFolding,"codeFolding"),__name2(codeFolding,"codeFolding");const foldWidget=Decoration.replace({widget:new class extends WidgetType{toDOM(view){let{state}=view,conf=state.facet(foldConfig),onclick=__name2(event=>{let line=view.lineBlockAt(view.posAtDOM(event.target)),folded=findFold(view.state,line.from,line.to);folded&&view.dispatch({effects:unfoldEffect.of(folded)}),event.preventDefault()},"onclick");if(conf.placeholderDOM)return conf.placeholderDOM(view,onclick);let element=document.createElement("span");return element.textContent=conf.placeholderText,element.setAttribute("aria-label",state.phrase("folded code")),element.title=state.phrase("unfold"),element.className="cm-foldPlaceholder",element.onclick=onclick,element}}}),foldGutterDefaults={openText:"\u2304",closedText:"\u203A",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},_FoldMarker=class extends GutterMarker{static{__name(this,"_FoldMarker")}constructor(config2,open){super(),this.config=config2,this.open=open}eq(other){return this.config==other.config&&this.open==other.open}toDOM(view){if(this.config.markerDOM)return this.config.markerDOM(this.open);let span=document.createElement("span");return span.textContent=this.open?this.config.openText:this.config.closedText,span.title=view.state.phrase(this.open?"Fold line":"Unfold line"),span}};__name2(_FoldMarker,"FoldMarker");let FoldMarker=_FoldMarker;function foldGutter(config2={}){let fullConfig=Object.assign(Object.assign({},foldGutterDefaults),config2),canFold=new FoldMarker(fullConfig,!0),canUnfold=new FoldMarker(fullConfig,!1),markers=ViewPlugin.fromClass(class{constructor(view){this.from=view.viewport.from,this.markers=this.buildMarkers(view)}update(update){(update.docChanged||update.viewportChanged||update.startState.facet(language)!=update.state.facet(language)||update.startState.field(foldState,!1)!=update.state.field(foldState,!1)||syntaxTree(update.startState)!=syntaxTree(update.state)||fullConfig.foldingChanged(update))&&(this.markers=this.buildMarkers(update.view))}buildMarkers(view){let builder=new RangeSetBuilder;for(let line of view.viewportLineBlocks){let mark=findFold(view.state,line.from,line.to)?canUnfold:foldable(view.state,line.from,line.to)?canFold:null;mark&&builder.add(line.from,line.from,mark)}return builder.finish()}}),{domEventHandlers}=fullConfig;return[markers,gutter({class:"cm-foldGutter",markers(view){var _a3;return((_a3=view.plugin(markers))===null||_a3===void 0?void 0:_a3.markers)||RangeSet.empty},initialSpacer(){return new FoldMarker(fullConfig,!1)},domEventHandlers:Object.assign(Object.assign({},domEventHandlers),{click:(view,line,event)=>{if(domEventHandlers.click&&domEventHandlers.click(view,line,event))return!0;let folded=findFold(view.state,line.from,line.to);if(folded)return view.dispatch({effects:unfoldEffect.of(folded)}),!0;let range=foldable(view.state,line.from,line.to);return range?(view.dispatch({effects:foldEffect.of(range)}),!0):!1}})}),codeFolding()]}__name(foldGutter,"foldGutter"),__name2(foldGutter,"foldGutter");const baseTheme$1$1=EditorView.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}}),_HighlightStyle=class _HighlightStyle2{static{__name(this,"_HighlightStyle")}constructor(specs,options){this.specs=specs;let modSpec;function def(spec){let cls=StyleModule.newName();return(modSpec||(modSpec=Object.create(null)))["."+cls]=spec,cls}__name(def,"def"),__name2(def,"def");const all=typeof options.all=="string"?options.all:options.all?def(options.all):void 0,scopeOpt=options.scope;this.scope=scopeOpt instanceof Language?type=>type.prop(languageDataProp)==scopeOpt.data:scopeOpt?type=>type==scopeOpt:void 0,this.style=tagHighlighter(specs.map(style=>({tag:style.tag,class:style.class||def(Object.assign({},style,{tag:null}))})),{all}).style,this.module=modSpec?new StyleModule(modSpec):null,this.themeType=options.themeType}static define(specs,options){return new _HighlightStyle2(specs,options||{})}};__name2(_HighlightStyle,"HighlightStyle");let HighlightStyle=_HighlightStyle;const highlighterFacet=Facet.define(),fallbackHighlighter=Facet.define({combine(values){return values.length?[values[0]]:null}});function getHighlighters(state){let main=state.facet(highlighterFacet);return main.length?main:state.facet(fallbackHighlighter)}__name(getHighlighters,"getHighlighters"),__name2(getHighlighters,"getHighlighters");function syntaxHighlighting(highlighter,options){let ext=[treeHighlighter],themeType;return highlighter instanceof HighlightStyle&&(highlighter.module&&ext.push(EditorView.styleModule.of(highlighter.module)),themeType=highlighter.themeType),options?.fallback?ext.push(fallbackHighlighter.of(highlighter)):themeType?ext.push(highlighterFacet.computeN([EditorView.darkTheme],state=>state.facet(EditorView.darkTheme)==(themeType=="dark")?[highlighter]:[])):ext.push(highlighterFacet.of(highlighter)),ext}__name(syntaxHighlighting,"syntaxHighlighting"),__name2(syntaxHighlighting,"syntaxHighlighting");const _TreeHighlighter=class{static{__name(this,"_TreeHighlighter")}constructor(view){this.markCache=Object.create(null),this.tree=syntaxTree(view.state),this.decorations=this.buildDeco(view,getHighlighters(view.state))}update(update){let tree=syntaxTree(update.state),highlighters=getHighlighters(update.state),styleChange=highlighters!=getHighlighters(update.startState);tree.length<update.view.viewport.to&&!styleChange&&tree.type==this.tree.type?this.decorations=this.decorations.map(update.changes):(tree!=this.tree||update.viewportChanged||styleChange)&&(this.tree=tree,this.decorations=this.buildDeco(update.view,highlighters))}buildDeco(view,highlighters){if(!highlighters||!this.tree.length)return Decoration.none;let builder=new RangeSetBuilder;for(let{from,to}of view.visibleRanges)highlightTree(this.tree,highlighters,(from2,to2,style)=>{builder.add(from2,to2,this.markCache[style]||(this.markCache[style]=Decoration.mark({class:style})))},from,to);return builder.finish()}};__name2(_TreeHighlighter,"TreeHighlighter");let TreeHighlighter=_TreeHighlighter;const treeHighlighter=Prec.high(ViewPlugin.fromClass(TreeHighlighter,{decorations:v=>v.decorations})),defaultHighlightStyle=HighlightStyle.define([{tag:tags.meta,color:"#404740"},{tag:tags.link,textDecoration:"underline"},{tag:tags.heading,textDecoration:"underline",fontWeight:"bold"},{tag:tags.emphasis,fontStyle:"italic"},{tag:tags.strong,fontWeight:"bold"},{tag:tags.strikethrough,textDecoration:"line-through"},{tag:tags.keyword,color:"#708"},{tag:[tags.atom,tags.bool,tags.url,tags.contentSeparator,tags.labelName],color:"#219"},{tag:[tags.literal,tags.inserted],color:"#164"},{tag:[tags.string,tags.deleted],color:"#a11"},{tag:[tags.regexp,tags.escape,tags.special(tags.string)],color:"#e40"},{tag:tags.definition(tags.variableName),color:"#00f"},{tag:tags.local(tags.variableName),color:"#30a"},{tag:[tags.typeName,tags.namespace],color:"#085"},{tag:tags.className,color:"#167"},{tag:[tags.special(tags.variableName),tags.macroName],color:"#256"},{tag:tags.definition(tags.propertyName),color:"#00c"},{tag:tags.comment,color:"#940"},{tag:tags.invalid,color:"#f00"}]),baseTheme$4=EditorView.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),DefaultScanDist=1e4,DefaultBrackets="()[]{}",bracketMatchingConfig=Facet.define({combine(configs){return combineConfig(configs,{afterCursor:!0,brackets:DefaultBrackets,maxScanDistance:DefaultScanDist,renderMatch:defaultRenderMatch})}}),matchingMark=Decoration.mark({class:"cm-matchingBracket"}),nonmatchingMark=Decoration.mark({class:"cm-nonmatchingBracket"});function defaultRenderMatch(match2){let decorations2=[],mark=match2.matched?matchingMark:nonmatchingMark;return decorations2.push(mark.range(match2.start.from,match2.start.to)),match2.end&&decorations2.push(mark.range(match2.end.from,match2.end.to)),decorations2}__name(defaultRenderMatch,"defaultRenderMatch"),__name2(defaultRenderMatch,"defaultRenderMatch");const bracketMatchingState=StateField.define({create(){return Decoration.none},update(deco,tr){if(!tr.docChanged&&!tr.selection)return deco;let decorations2=[],config2=tr.state.facet(bracketMatchingConfig);for(let range of tr.state.selection.ranges){if(!range.empty)continue;let match2=matchBrackets(tr.state,range.head,-1,config2)||range.head>0&&matchBrackets(tr.state,range.head-1,1,config2)||config2.afterCursor&&(matchBrackets(tr.state,range.head,1,config2)||range.head<tr.state.doc.length&&matchBrackets(tr.state,range.head+1,-1,config2));match2&&(decorations2=decorations2.concat(config2.renderMatch(match2,tr.state)))}return Decoration.set(decorations2,!0)},provide:f2=>EditorView.decorations.from(f2)}),bracketMatchingUnique=[bracketMatchingState,baseTheme$4];function bracketMatching(config2={}){return[bracketMatchingConfig.of(config2),bracketMatchingUnique]}__name(bracketMatching,"bracketMatching"),__name2(bracketMatching,"bracketMatching");const bracketMatchingHandle=new NodeProp;function matchingNodes(node,dir,brackets){let byProp=node.prop(dir<0?NodeProp.openedBy:NodeProp.closedBy);if(byProp)return byProp;if(node.name.length==1){let index2=brackets.indexOf(node.name);if(index2>-1&&index2%2==(dir<0?1:0))return[brackets[index2+dir]]}return null}__name(matchingNodes,"matchingNodes"),__name2(matchingNodes,"matchingNodes");function findHandle(node){let hasHandle=node.type.prop(bracketMatchingHandle);return hasHandle?hasHandle(node.node):node}__name(findHandle,"findHandle"),__name2(findHandle,"findHandle");function matchBrackets(state,pos,dir,config2={}){let maxScanDistance=config2.maxScanDistance||DefaultScanDist,brackets=config2.brackets||DefaultBrackets,tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur2=node;cur2;cur2=cur2.parent){let matches2=matchingNodes(cur2.type,dir,brackets);if(matches2&&cur2.from<cur2.to){let handle=findHandle(cur2);if(handle&&(dir>0?pos>=handle.from&&pos<handle.to:pos>handle.from&&pos<=handle.to))return matchMarkedBrackets(state,pos,dir,cur2,handle,matches2,brackets)}}return matchPlainBrackets(state,pos,dir,tree,node.type,maxScanDistance,brackets)}__name(matchBrackets,"matchBrackets"),__name2(matchBrackets,"matchBrackets");function matchMarkedBrackets(_state,_pos,dir,token,handle,matching,brackets){let parent=token.parent,firstToken={from:handle.from,to:handle.to},depth=0,cursor=parent?.cursor();if(cursor&&(dir<0?cursor.childBefore(token.from):cursor.childAfter(token.to)))do if(dir<0?cursor.to<=token.from:cursor.from>=token.to){if(depth==0&&matching.indexOf(cursor.type.name)>-1&&cursor.from<cursor.to){let endHandle=findHandle(cursor);return{start:firstToken,end:endHandle?{from:endHandle.from,to:endHandle.to}:void 0,matched:!0}}else if(matchingNodes(cursor.type,dir,brackets))depth++;else if(matchingNodes(cursor.type,-dir,brackets)){if(depth==0){let endHandle=findHandle(cursor);return{start:firstToken,end:endHandle&&endHandle.from<endHandle.to?{from:endHandle.from,to:endHandle.to}:void 0,matched:!1}}depth--}}while(dir<0?cursor.prevSibling():cursor.nextSibling());return{start:firstToken,matched:!1}}__name(matchMarkedBrackets,"matchMarkedBrackets"),__name2(matchMarkedBrackets,"matchMarkedBrackets");function matchPlainBrackets(state,pos,dir,tree,tokenType,maxScanDistance,brackets){let startCh=dir<0?state.sliceDoc(pos-1,pos):state.sliceDoc(pos,pos+1),bracket2=brackets.indexOf(startCh);if(bracket2<0||bracket2%2==0!=dir>0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos},iter=state.doc.iterRange(pos,dir>0?state.doc.length:0),depth=0;for(let distance=0;!iter.next().done&&distance<=maxScanDistance;){let text=iter.value;dir<0&&(distance+=text.length);let basePos=pos+distance*dir;for(let pos2=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos2!=end;pos2+=dir){let found=brackets.indexOf(text[pos2]);if(!(found<0||tree.resolveInner(basePos+pos2,1).type!=tokenType))if(found%2==0==dir>0)depth++;else{if(depth==1)return{start:startToken,end:{from:basePos+pos2,to:basePos+pos2+1},matched:found>>1==bracket2>>1};depth--}}dir>0&&(distance+=text.length)}return iter.done?{start:startToken,matched:!1}:null}__name(matchPlainBrackets,"matchPlainBrackets"),__name2(matchPlainBrackets,"matchPlainBrackets");const noTokens=Object.create(null),typeArray=[NodeType.none],warned=[],defaultTable=Object.create(null);for(let[legacyName,name2]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=createTokenType(noTokens,name2);function warnForPart(part,msg){warned.indexOf(part)>-1||(warned.push(part),console.warn(msg))}__name(warnForPart,"warnForPart"),__name2(warnForPart,"warnForPart");function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags[part];value?typeof value=="function"?tag?tag=value(tag):warnForPart(part,`Modifier ${part} used at start of tag`):tag?warnForPart(part,`Tag ${part} used as modifier`):tag=value:warnForPart(part,`Unknown highlighting tag ${part}`)}if(!tag)return 0;let name2=tagStr.replace(/ /g,"_"),type=NodeType.define({id:typeArray.length,name:name2,props:[styleTags({[name2]:tag})]});return typeArray.push(type),type.id}__name(createTokenType,"createTokenType"),__name2(createTokenType,"createTokenType");const _CompletionContext=class{static{__name(this,"_CompletionContext")}constructor(state,pos,explicit){this.state=state,this.pos=pos,this.explicit=explicit,this.abortListeners=[]}tokenBefore(types2){let token=syntaxTree(this.state).resolveInner(this.pos,-1);for(;token&&types2.indexOf(token.name)<0;)token=token.parent;return token?{from:token.from,to:this.pos,text:this.state.sliceDoc(token.from,this.pos),type:token.type}:null}matchBefore(expr){let line=this.state.doc.lineAt(this.pos),start=Math.max(line.from,this.pos-250),str=line.text.slice(start-line.from,this.pos-line.from),found=str.search(ensureAnchor(expr,!1));return found<0?null:{from:start+found,to:this.pos,text:str.slice(found)}}get aborted(){return this.abortListeners==null}addEventListener(type,listener){type=="abort"&&this.abortListeners&&this.abortListeners.push(listener)}};__name2(_CompletionContext,"CompletionContext");let CompletionContext=_CompletionContext;function toSet(chars){let flat=Object.keys(chars).join(""),words=/\w/.test(flat);return words&&(flat=flat.replace(/\w/g,"")),`[${words?"\\w":""}${flat.replace(/[^\w\s]/g,"\\$&")}]`}__name(toSet,"toSet"),__name2(toSet,"toSet");function prefixMatch(options){let first=Object.create(null),rest=Object.create(null);for(let{label}of options){first[label[0]]=!0;for(let i=1;i<label.length;i++)rest[label[i]]=!0}let source=toSet(first)+toSet(rest)+"*$";return[new RegExp("^"+source),new RegExp(source)]}__name(prefixMatch,"prefixMatch"),__name2(prefixMatch,"prefixMatch");function completeFromList(list){let options=list.map(o=>typeof o=="string"?{label:o}:o),[validFor,match2]=options.every(o=>/^\w+$/.test(o.label))?[/\w*$/,/\w+$/]:prefixMatch(options);return context=>{let token=context.matchBefore(match2);return token||context.explicit?{from:token?token.from:context.pos,options,validFor}:null}}__name(completeFromList,"completeFromList"),__name2(completeFromList,"completeFromList");const _Option=class{static{__name(this,"_Option")}constructor(completion,source,match2,score2){this.completion=completion,this.source=source,this.match=match2,this.score=score2}};__name2(_Option,"Option");let Option=_Option;function cur(state){return state.selection.main.from}__name(cur,"cur"),__name2(cur,"cur");function ensureAnchor(expr,start){var _a3;let{source}=expr,addStart=start&&source[0]!="^",addEnd=source[source.length-1]!="$";return!addStart&&!addEnd?expr:new RegExp(`${addStart?"^":""}(?:${source})${addEnd?"$":""}`,(_a3=expr.flags)!==null&&_a3!==void 0?_a3:expr.ignoreCase?"i":"")}__name(ensureAnchor,"ensureAnchor"),__name2(ensureAnchor,"ensureAnchor");const pickedCompletion=Annotation.define();function insertCompletionText(state,text,from,to){let{main}=state.selection,fromOff=from-main.from,toOff=to-main.from;return Object.assign(Object.assign({},state.changeByRange(range=>range!=main&&from!=to&&state.sliceDoc(range.from+fromOff,range.from+toOff)!=state.sliceDoc(from,to)?{range}:{changes:{from:range.from+fromOff,to:to==main.from?range.to:range.from+toOff,insert:text},range:EditorSelection.cursor(range.from+fromOff+text.length)})),{scrollIntoView:!0,userEvent:"input.complete"})}__name(insertCompletionText,"insertCompletionText"),__name2(insertCompletionText,"insertCompletionText");const SourceCache=new WeakMap;function asSource(source){if(!Array.isArray(source))return source;let known=SourceCache.get(source);return known||SourceCache.set(source,known=completeFromList(source)),known}__name(asSource,"asSource"),__name2(asSource,"asSource");const startCompletionEffect=StateEffect.define(),closeCompletionEffect=StateEffect.define(),_FuzzyMatcher=class{static{__name(this,"_FuzzyMatcher")}constructor(pattern){this.pattern=pattern,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let p=0;p<pattern.length;){let char=codePointAt(pattern,p),size=codePointSize(char);this.chars.push(char);let part=pattern.slice(p,p+size),upper=part.toUpperCase();this.folded.push(codePointAt(upper==part?part.toLowerCase():upper,0)),p+=size}this.astral=pattern.length!=this.chars.length}ret(score2,matched){return this.score=score2,this.matched=matched,!0}match(word){if(this.pattern.length==0)return this.ret(-100,[]);if(word.length<this.pattern.length)return!1;let{chars,folded,any,precise,byWord}=this;if(chars.length==1){let first=codePointAt(word,0),firstSize=codePointSize(first),score2=firstSize==word.length?0:-100;if(first!=chars[0])if(first==folded[0])score2+=-200;else return!1;return this.ret(score2,[0,firstSize])}let direct=word.indexOf(this.pattern);if(direct==0)return this.ret(word.length==this.pattern.length?0:-100,[0,this.pattern.length]);let len=chars.length,anyTo=0;if(direct<0){for(let i=0,e=Math.min(word.length,200);i<e&&anyTo<len;){let next=codePointAt(word,i);(next==chars[anyTo]||next==folded[anyTo])&&(any[anyTo++]=i),i+=codePointSize(next)}if(anyTo<len)return!1}let preciseTo=0,byWordTo=0,byWordFolded=!1,adjacentTo=0,adjacentStart=-1,adjacentEnd=-1,hasLower=/[a-z]/.test(word),wordAdjacent=!0;for(let i=0,e=Math.min(word.length,200),prevType=0;i<e&&byWordTo<len;){let next=codePointAt(word,i);direct<0&&(preciseTo<len&&next==chars[preciseTo]&&(precise[preciseTo++]=i),adjacentTo<len&&(next==chars[adjacentTo]||next==folded[adjacentTo]?(adjacentTo==0&&(adjacentStart=i),adjacentEnd=i+1,adjacentTo++):adjacentTo=0));let ch,type=next<255?next>=48&&next<=57||next>=97&&next<=122?2:next>=65&&next<=90?1:0:(ch=fromCodePoint(next))!=ch.toLowerCase()?1:ch!=ch.toUpperCase()?2:0;(!i||type==1&&hasLower||prevType==0&&type!=0)&&(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=!0)?byWord[byWordTo++]=i:byWord.length&&(wordAdjacent=!1)),prevType=type,i+=codePointSize(next)}return byWordTo==len&&byWord[0]==0&&wordAdjacent?this.result(-100+(byWordFolded?-200:0),byWord,word):adjacentTo==len&&adjacentStart==0?this.ret(-200-word.length+(adjacentEnd==word.length?0:-100),[0,adjacentEnd]):direct>-1?this.ret(-700-word.length,[direct,direct+this.pattern.length]):adjacentTo==len?this.ret(-200+-700-word.length,[adjacentStart,adjacentEnd]):byWordTo==len?this.result(-100+(byWordFolded?-200:0)+-700+(wordAdjacent?0:-1100),byWord,word):chars.length==2?!1:this.result((any[0]?-700:0)+-200+-1100,any,word)}result(score2,positions,word){let result=[],i=0;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);i&&result[i-1]==pos?result[i-1]=to:(result[i++]=pos,result[i++]=to)}return this.ret(score2-word.length,result)}};__name2(_FuzzyMatcher,"FuzzyMatcher");let FuzzyMatcher=_FuzzyMatcher;const completionConfig=Facet.define({combine(configs){return combineConfig(configs,{activateOnTyping:!0,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:defaultPositionInfo,compareCompletions:(a,b)=>a.label.localeCompare(b.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,tooltipClass:(a,b)=>c=>joinClass(a(c),b(c)),optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)})}});function joinClass(a,b){return a?b?a+" "+b:a:b}__name(joinClass,"joinClass"),__name2(joinClass,"joinClass");function defaultPositionInfo(view,list,option2,info,space,tooltip){let rtl=view.textDirection==Direction.RTL,left=rtl,narrow=!1,side="top",offset2,maxWidth,spaceLeft=list.left-space.left,spaceRight=space.right-list.right,infoWidth=info.right-info.left,infoHeight=info.bottom-info.top;if(left&&spaceLeft<Math.min(infoWidth,spaceRight)?left=!1:!left&&spaceRight<Math.min(infoWidth,spaceLeft)&&(left=!0),infoWidth<=(left?spaceLeft:spaceRight))offset2=Math.max(space.top,Math.min(option2.top,space.bottom-infoHeight))-list.top,maxWidth=Math.min(400,left?spaceLeft:spaceRight);else{narrow=!0,maxWidth=Math.min(400,(rtl?list.right:space.right-list.left)-30);let spaceBelow=space.bottom-list.bottom;spaceBelow>=infoHeight||spaceBelow>list.top?offset2=option2.bottom-list.top:(side="bottom",offset2=list.bottom-option2.top)}let scaleY=(list.bottom-list.top)/tooltip.offsetHeight,scaleX=(list.right-list.left)/tooltip.offsetWidth;return{style:`${side}: ${offset2/scaleY}px; max-width: ${maxWidth/scaleX}px`,class:"cm-completionInfo-"+(narrow?rtl?"left-narrow":"right-narrow":left?"left":"right")}}__name(defaultPositionInfo,"defaultPositionInfo"),__name2(defaultPositionInfo,"defaultPositionInfo");function optionContent(config2){let content2=config2.addToOptions.slice();return config2.icons&&content2.push({render(completion){let icon=document.createElement("div");return icon.classList.add("cm-completionIcon"),completion.type&&icon.classList.add(...completion.type.split(/\s+/g).map(cls=>"cm-completionIcon-"+cls)),icon.setAttribute("aria-hidden","true"),icon},position:20}),content2.push({render(completion,_s,match2){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let label=completion.displayLabel||completion.label,off2=0;for(let j=0;j<match2.length;){let from=match2[j++],to=match2[j++];from>off2&&labelElt.appendChild(document.createTextNode(label.slice(off2,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to))),span.className="cm-completionMatchedText",off2=to}return off2<label.length&&labelElt.appendChild(document.createTextNode(label.slice(off2))),labelElt},position:50},{render(completion){if(!completion.detail)return null;let detailElt=document.createElement("span");return detailElt.className="cm-completionDetail",detailElt.textContent=completion.detail,detailElt},position:80}),content2.sort((a,b)=>a.position-b.position).map(a=>a.render)}__name(optionContent,"optionContent"),__name2(optionContent,"optionContent");function rangeAroundSelected(total,selected,max){if(total<=max)return{from:0,to:total};if(selected<0&&(selected=0),selected<=total>>1){let off3=Math.floor(selected/max);return{from:off3*max,to:(off3+1)*max}}let off2=Math.floor((total-selected)/max);return{from:total-(off2+1)*max,to:total-off2*max}}__name(rangeAroundSelected,"rangeAroundSelected"),__name2(rangeAroundSelected,"rangeAroundSelected");const _CompletionTooltip=class{static{__name(this,"_CompletionTooltip")}constructor(view,stateField,applyCompletion2){this.view=view,this.stateField=stateField,this.applyCompletion=applyCompletion2,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:pos=>this.placeInfo(pos),key:this},this.space=null,this.currentClass="";let cState=view.state.field(stateField),{options,selected}=cState.open,config2=view.state.facet(completionConfig);this.optionContent=optionContent(config2),this.optionClass=config2.optionClass,this.tooltipClass=config2.tooltipClass,this.range=rangeAroundSelected(options.length,selected,config2.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(view.state),this.dom.addEventListener("mousedown",e=>{let{options:options2}=view.state.field(stateField).open;for(let dom=e.target,match2;dom&&dom!=this.dom;dom=dom.parentNode)if(dom.nodeName=="LI"&&(match2=/-(\d+)$/.exec(dom.id))&&+match2[1]<options2.length){this.applyCompletion(view,options2[+match2[1]]),e.preventDefault();return}}),this.dom.addEventListener("focusout",e=>{let state=view.state.field(this.stateField,!1);state&&state.tooltip&&view.state.facet(completionConfig).closeOnBlur&&e.relatedTarget!=view.contentDOM&&view.dispatch({effects:closeCompletionEffect.of(null)})}),this.showOptions(options,cState.id)}mount(){this.updateSel()}showOptions(options,id){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(options,id,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(update){var _a3;let cState=update.state.field(this.stateField),prevState=update.startState.field(this.stateField);if(this.updateTooltipClass(update.state),cState!=prevState){let{options,selected,disabled}=cState.open;(!prevState.open||prevState.open.options!=options)&&(this.range=rangeAroundSelected(options.length,selected,update.state.facet(completionConfig).maxRenderedOptions),this.showOptions(options,cState.id)),this.updateSel(),disabled!=((_a3=prevState.open)===null||_a3===void 0?void 0:_a3.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!disabled)}}updateTooltipClass(state){let cls=this.tooltipClass(state);if(cls!=this.currentClass){for(let c of this.currentClass.split(" "))c&&this.dom.classList.remove(c);for(let c of cls.split(" "))c&&this.dom.classList.add(c);this.currentClass=cls}}positioned(space){this.space=space,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if((open.selected>-1&&open.selected<this.range.from||open.selected>=this.range.to)&&(this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions),this.showOptions(open.options,cState.id)),this.updateSelectedOption(open.selected)){this.destroyInfo();let{completion}=open.options[open.selected],{info}=completion;if(!info)return;let infoResult=typeof info=="string"?document.createTextNode(info):info(completion);if(!infoResult)return;"then"in infoResult?infoResult.then(obj=>{obj&&this.view.state.field(this.stateField,!1)==cState&&this.addInfoPane(obj,completion)}).catch(e=>logException(this.view.state,e,"completion info")):this.addInfoPane(infoResult,completion)}}addInfoPane(content2,completion){this.destroyInfo();let wrap=this.info=document.createElement("div");if(wrap.className="cm-tooltip cm-completionInfo",content2.nodeType!=null)wrap.appendChild(content2),this.infoDestroy=null;else{let{dom,destroy:destroy2}=content2;wrap.appendChild(dom),this.infoDestroy=destroy2||null}this.dom.appendChild(wrap),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++)opt.nodeName!="LI"||!opt.id?i--:i==selected?opt.hasAttribute("aria-selected")||(opt.setAttribute("aria-selected","true"),set=opt):opt.hasAttribute("aria-selected")&&opt.removeAttribute("aria-selected");return set&&scrollIntoView(this.list,set),set}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect(),infoRect=this.info.getBoundingClientRect(),selRect=sel.getBoundingClientRect(),space=this.space;if(!space){let win=this.dom.ownerDocument.defaultView||window;space={left:0,top:0,right:win.innerWidth,bottom:win.innerHeight}}return selRect.top>Math.min(space.bottom,listRect.bottom)-10||selRect.bottom<Math.max(space.top,listRect.top)+10?null:this.view.state.facet(completionConfig).positionInfo(this.view,listRect,selRect,infoRect,space,this.dom)}placeInfo(pos){this.info&&(pos?(pos.style&&(this.info.style.cssText=pos.style),this.info.className="cm-tooltip cm-completionInfo "+(pos.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(options,id,range){const ul=document.createElement("ul");ul.id=id,ul.setAttribute("role","listbox"),ul.setAttribute("aria-expanded","true"),ul.setAttribute("aria-label",this.view.state.phrase("Completions"));let curSection=null;for(let i=range.from;i<range.to;i++){let{completion,match:match2}=options[i],{section}=completion;if(section){let name2=typeof section=="string"?section:section.name;if(name2!=curSection&&(i>range.from||range.from==0))if(curSection=name2,typeof section!="string"&&section.header)ul.appendChild(section.header(section));else{let header=ul.appendChild(document.createElement("completion-section"));header.textContent=name2}}const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i,li.setAttribute("role","option");let cls=this.optionClass(completion);cls&&(li.className=cls);for(let source of this.optionContent){let node=source(completion,this.view.state,match2);node&&li.appendChild(node)}}return range.from&&ul.classList.add("cm-completionListIncompleteTop"),range.to<options.length&&ul.classList.add("cm-completionListIncompleteBottom"),ul}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}};__name2(_CompletionTooltip,"CompletionTooltip");let CompletionTooltip=_CompletionTooltip;function completionTooltip(stateField,applyCompletion2){return view=>new CompletionTooltip(view,stateField,applyCompletion2)}__name(completionTooltip,"completionTooltip"),__name2(completionTooltip,"completionTooltip");function scrollIntoView(container,element){let parent=container.getBoundingClientRect(),self2=element.getBoundingClientRect(),scaleY=parent.height/container.offsetHeight;self2.top<parent.top?container.scrollTop-=(parent.top-self2.top)/scaleY:self2.bottom>parent.bottom&&(container.scrollTop+=(self2.bottom-parent.bottom)/scaleY)}__name(scrollIntoView,"scrollIntoView"),__name2(scrollIntoView,"scrollIntoView");function score(option2){return(option2.boost||0)*100+(option2.apply?10:0)+(option2.info?5:0)+(option2.type?1:0)}__name(score,"score"),__name2(score,"score");function sortOptions(active,state){let options=[],sections=null,addOption=__name2(option2=>{options.push(option2);let{section}=option2.completion;if(section){sections||(sections=[]);let name2=typeof section=="string"?section:section.name;sections.some(s2=>s2.name==name2)||sections.push(typeof section=="string"?{name:name2}:section)}},"addOption");for(let a of active)if(a.hasResult()){let getMatch=a.result.getMatch;if(a.result.filter===!1)for(let option2 of a.result.options)addOption(new Option(option2,a.source,getMatch?getMatch(option2):[],1e9-options.length));else{let matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to));for(let option2 of a.result.options)if(matcher.match(option2.label)){let matched=option2.displayLabel?getMatch?getMatch(option2,matcher.matched):[]:matcher.matched;addOption(new Option(option2,a.source,matched,matcher.score+(option2.boost||0)))}}}if(sections){let sectionOrder=Object.create(null),pos=0,cmp=__name2((a,b)=>{var _a3,_b2;return((_a3=a.rank)!==null&&_a3!==void 0?_a3:1e9)-((_b2=b.rank)!==null&&_b2!==void 0?_b2:1e9)||(a.name<b.name?-1:1)},"cmp");for(let s2 of sections.sort(cmp))pos-=1e5,sectionOrder[s2.name]=pos;for(let option2 of options){let{section}=option2.completion;section&&(option2.score+=sectionOrder[typeof section=="string"?section:section.name])}}let result=[],prev=null,compare2=state.facet(completionConfig).compareCompletions;for(let opt of options.sort((a,b)=>b.score-a.score||compare2(a.completion,b.completion))){let cur2=opt.completion;!prev||prev.label!=cur2.label||prev.detail!=cur2.detail||prev.type!=null&&cur2.type!=null&&prev.type!=cur2.type||prev.apply!=cur2.apply||prev.boost!=cur2.boost?result.push(opt):score(opt.completion)>score(prev)&&(result[result.length-1]=opt),prev=opt.completion}return result}__name(sortOptions,"sortOptions"),__name2(sortOptions,"sortOptions");const _CompletionDialog=class _CompletionDialog2{static{__name(this,"_CompletionDialog")}constructor(options,attrs,tooltip,timestamp,selected,disabled){this.options=options,this.attrs=attrs,this.tooltip=tooltip,this.timestamp=timestamp,this.selected=selected,this.disabled=disabled}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new _CompletionDialog2(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected,this.disabled)}static build(active,state,id,prev,conf){let options=sortOptions(active,state);if(!options.length)return prev&&active.some(a=>a.state==1)?new _CompletionDialog2(prev.options,prev.attrs,prev.tooltip,prev.timestamp,prev.selected,!0):null;let selected=state.facet(completionConfig).selectOnOpen?0:-1;if(prev&&prev.selected!=selected&&prev.selected!=-1){let selectedValue=prev.options[prev.selected].completion;for(let i=0;i<options.length;i++)if(options[i].completion==selectedValue){selected=i;break}}return new _CompletionDialog2(options,makeAttrs(id,selected),{pos:active.reduce((a,b)=>b.hasResult()?Math.min(a,b.from):a,1e8),create:createTooltip,above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected,!1)}map(changes){return new _CompletionDialog2(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}};__name2(_CompletionDialog,"CompletionDialog");let CompletionDialog=_CompletionDialog;const _CompletionState=class _CompletionState2{static{__name(this,"_CompletionState")}constructor(active,id,open){this.active=active,this.id=id,this.open=open}static start(){return new _CompletionState2(none$1,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(tr){let{state}=tr,conf=state.facet(completionConfig),active=(conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource)).map(source=>(this.active.find(s2=>s2.source==source)||new ActiveSource(source,this.active.some(a=>a.state!=0)?1:0)).update(tr,conf));active.length==this.active.length&&active.every((a,i)=>a==this.active[i])&&(active=this.active);let open=this.open;open&&tr.docChanged&&(open=open.map(tr.changes)),tr.selection||active.some(a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to))||!sameResults(active,this.active)?open=CompletionDialog.build(active,state,this.id,open,conf):open&&open.disabled&&!active.some(a=>a.state==1)&&(open=null),!open&&active.every(a=>a.state!=1)&&active.some(a=>a.hasResult())&&(active=active.map(a=>a.hasResult()?new ActiveSource(a.source,0):a));for(let effect of tr.effects)effect.is(setSelectedEffect)&&(open=open&&open.setSelected(effect.value,this.id));return active==this.active&&open==this.open?this:new _CompletionState2(active,this.id,open)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:baseAttrs}};__name2(_CompletionState,"CompletionState");let CompletionState=_CompletionState;function sameResults(a,b){if(a==b)return!0;for(let iA=0,iB=0;;){for(;iA<a.length&&!a[iA].hasResult;)iA++;for(;iB<b.length&&!b[iB].hasResult;)iB++;let endA=iA==a.length,endB=iB==b.length;if(endA||endB)return endA==endB;if(a[iA++].result!=b[iB++].result)return!1}}__name(sameResults,"sameResults"),__name2(sameResults,"sameResults");const baseAttrs={"aria-autocomplete":"list"};function makeAttrs(id,selected){let result={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":id};return selected>-1&&(result["aria-activedescendant"]=id+"-"+selected),result}__name(makeAttrs,"makeAttrs"),__name2(makeAttrs,"makeAttrs");const none$1=[];function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null}__name(getUserEvent,"getUserEvent"),__name2(getUserEvent,"getUserEvent");const _ActiveSource=class _ActiveSource2{static{__name(this,"_ActiveSource")}constructor(source,state,explicitPos=-1){this.source=source,this.state=state,this.explicitPos=explicitPos}hasResult(){return!1}update(tr,conf){let event=getUserEvent(tr),value=this;event?value=value.handleUserEvent(tr,event,conf):tr.docChanged?value=value.handleChange(tr):tr.selection&&value.state!=0&&(value=new _ActiveSource2(value.source,0));for(let effect of tr.effects)if(effect.is(startCompletionEffect))value=new _ActiveSource2(value.source,1,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new _ActiveSource2(value.source,0);else if(effect.is(setActiveEffect))for(let active of effect.value)active.source==value.source&&(value=active);return value}handleUserEvent(tr,type,conf){return type=="delete"||!conf.activateOnTyping?this.map(tr.changes):new _ActiveSource2(this.source,1)}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new _ActiveSource2(this.source,0):this.map(tr.changes)}map(changes){return changes.empty||this.explicitPos<0?this:new _ActiveSource2(this.source,this.state,changes.mapPos(this.explicitPos))}};__name2(_ActiveSource,"ActiveSource");let ActiveSource=_ActiveSource;const _ActiveResult=class _ActiveResult2 extends ActiveSource{static{__name(this,"_ActiveResult")}constructor(source,explicitPos,result,from,to){super(source,2,explicitPos),this.result=result,this.from=from,this.to=to}hasResult(){return!0}handleUserEvent(tr,type,conf){var _a3;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1),pos=cur(tr.state);if((this.explicitPos<0?pos<=from:pos<this.from)||pos>to||type=="delete"&&cur(tr.startState)==this.from)return new ActiveSource(this.source,type=="input"&&conf.activateOnTyping?1:0);let explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos),updated;return checkValid(this.result.validFor,tr.state,from,to)?new _ActiveResult2(this.source,explicitPos,this.result,from,to):this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0)))?new _ActiveResult2(this.source,explicitPos,updated,updated.from,(_a3=updated.to)!==null&&_a3!==void 0?_a3:cur(tr.state)):new ActiveSource(this.source,1,explicitPos)}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0):this.map(tr.changes)}map(mapping){return mapping.empty?this:new _ActiveResult2(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1))}};__name2(_ActiveResult,"ActiveResult");let ActiveResult=_ActiveResult;function checkValid(validFor,state,from,to){if(!validFor)return!1;let text=state.sliceDoc(from,to);return typeof validFor=="function"?validFor(text,from,to,state):ensureAnchor(validFor,!0).test(text)}__name(checkValid,"checkValid"),__name2(checkValid,"checkValid");const setActiveEffect=StateEffect.define({map(sources,mapping){return sources.map(s2=>s2.map(mapping))}}),setSelectedEffect=StateEffect.define(),completionState=StateField.define({create(){return CompletionState.start()},update(value,tr){return value.update(tr)},provide:f2=>[showTooltip.from(f2,val=>val.tooltip),EditorView.contentAttributes.from(f2,state=>state.attrs)]});function applyCompletion(view,option2){const apply=option2.completion.apply||option2.completion.label;let result=view.state.field(completionState).active.find(a=>a.source==option2.source);return result instanceof ActiveResult?(typeof apply=="string"?view.dispatch(Object.assign(Object.assign({},insertCompletionText(view.state,apply,result.from,result.to)),{annotations:pickedCompletion.of(option2.completion)})):apply(view,option2.completion,result.from,result.to),!0):!1}__name(applyCompletion,"applyCompletion"),__name2(applyCompletion,"applyCompletion");const createTooltip=completionTooltip(completionState,applyCompletion);function moveCompletionSelection(forward,by="option"){return view=>{let cState=view.state.field(completionState,!1);if(!cState||!cState.open||cState.open.disabled||Date.now()-cState.open.timestamp<view.state.facet(completionConfig).interactionDelay)return!1;let step=1,tooltip;by=="page"&&(tooltip=getTooltip(view,cState.open.tooltip))&&(step=Math.max(2,Math.floor(tooltip.dom.offsetHeight/tooltip.dom.querySelector("li").offsetHeight)-1));let{length}=cState.open.options,selected=cState.open.selected>-1?cState.open.selected+step*(forward?1:-1):forward?0:length-1;return selected<0?selected=by=="page"?0:length-1:selected>=length&&(selected=by=="page"?length-1:0),view.dispatch({effects:setSelectedEffect.of(selected)}),!0}}__name(moveCompletionSelection,"moveCompletionSelection"),__name2(moveCompletionSelection,"moveCompletionSelection");const acceptCompletion=__name2(view=>{let cState=view.state.field(completionState,!1);return view.state.readOnly||!cState||!cState.open||cState.open.selected<0||cState.open.disabled||Date.now()-cState.open.timestamp<view.state.facet(completionConfig).interactionDelay?!1:applyCompletion(view,cState.open.options[cState.open.selected])},"acceptCompletion"),startCompletion=__name2(view=>view.state.field(completionState,!1)?(view.dispatch({effects:startCompletionEffect.of(!0)}),!0):!1,"startCompletion"),closeCompletion=__name2(view=>{let cState=view.state.field(completionState,!1);return!cState||!cState.active.some(a=>a.state!=0)?!1:(view.dispatch({effects:closeCompletionEffect.of(null)}),!0)},"closeCompletion"),_RunningQuery=class{static{__name(this,"_RunningQuery")}constructor(active,context){this.active=active,this.context=context,this.time=Date.now(),this.updates=[],this.done=void 0}};__name2(_RunningQuery,"RunningQuery");let RunningQuery=_RunningQuery;const MaxUpdateCount=50,MinAbortTime=1e3,completionPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.composing=0;for(let active of view.state.field(completionState).active)active.state==1&&this.startQuery(active)}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some(tr=>(tr.selection||tr.docChanged)&&!getUserEvent(tr));for(let i=0;i<this.running.length;i++){let query=this.running[i];if(doesReset||query.updates.length+update.transactions.length>MaxUpdateCount&&Date.now()-query.time>MinAbortTime){for(let handler of query.context.abortListeners)try{handler()}catch(e){logException(this.view.state,e)}query.context.abortListeners=null,this.running.splice(i--,1)}else query.updates.push(...update.transactions)}if(this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),this.debounceUpdate=cState.active.some(a=>a.state==1&&!this.running.some(q=>q.active.source==a.source))?setTimeout(()=>this.startUpdate(),50):-1,this.composing!=0)for(let tr of update.transactions)getUserEvent(tr)=="input"?this.composing=2:this.composing==2&&tr.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1;let{state}=this.view,cState=state.field(completionState);for(let active of cState.active)active.state==1&&!this.running.some(r=>r.active.source==active.source)&&this.startQuery(active)}startQuery(active){let{state}=this.view,pos=cur(state),context=new CompletionContext(state,pos,active.explicitPos==pos),pending=new RunningQuery(active,context);this.running.push(pending),Promise.resolve(active.source(context)).then(result=>{pending.context.aborted||(pending.done=result||null,this.scheduleAccept())},err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)}),logException(this.view.state,err)})}scheduleAccept(){this.running.every(q=>q.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(completionConfig).updateSyncTime))}accept(){var _a3;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let updated=[],conf=this.view.state.facet(completionConfig);for(let i=0;i<this.running.length;i++){let query=this.running[i];if(query.done===void 0)continue;if(this.running.splice(i--,1),query.done){let active=new ActiveResult(query.active.source,query.active.explicitPos,query.done,query.done.from,(_a3=query.done.to)!==null&&_a3!==void 0?_a3:cur(query.updates.length?query.updates[0].startState:this.view.state));for(let tr of query.updates)active=active.update(tr,conf);if(active.hasResult()){updated.push(active);continue}}let current=this.view.state.field(completionState).active.find(a=>a.source==query.active.source);if(current&&current.state==1)if(query.done==null){let active=new ActiveSource(query.active.source,0);for(let tr of query.updates)active=active.update(tr,conf);active.state!=1&&updated.push(active)}else this.startQuery(current)}updated.length&&this.view.dispatch({effects:setActiveEffect.of(updated)})}},{eventHandlers:{blur(event){let state=this.view.state.field(completionState,!1);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur){let dialog=state.open&&getTooltip(this.view,state.open.tooltip);(!dialog||!dialog.dom.contains(event.relatedTarget))&&this.view.dispatch({effects:closeCompletionEffect.of(null)})}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:startCompletionEffect.of(!1)}),20),this.composing=0}}}),baseTheme$3=EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"\xB7\xB7\xB7"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'\u0192'"}},".cm-completionIcon-class":{"&:after":{content:"'\u25CB'"}},".cm-completionIcon-interface":{"&:after":{content:"'\u25CC'"}},".cm-completionIcon-variable":{"&:after":{content:"'\u{1D465}'"}},".cm-completionIcon-constant":{"&:after":{content:"'\u{1D436}'"}},".cm-completionIcon-type":{"&:after":{content:"'\u{1D461}'"}},".cm-completionIcon-enum":{"&:after":{content:"'\u222A'"}},".cm-completionIcon-property":{"&:after":{content:"'\u25A1'"}},".cm-completionIcon-keyword":{"&:after":{content:"'\u{1F511}\uFE0E'"}},".cm-completionIcon-namespace":{"&:after":{content:"'\u25A2'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}}),defaults={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},closeBracketEffect=StateEffect.define({map(value,mapping){let mapped=mapping.mapPos(value,-1,MapMode.TrackAfter);return mapped??void 0}}),closedBracket=new class extends RangeValue{};closedBracket.startSide=1,closedBracket.endSide=-1;const bracketState=StateField.define({create(){return RangeSet.empty},update(value,tr){if(tr.selection){let lineStart=tr.state.doc.lineAt(tr.selection.main.head).from,prevLineStart=tr.startState.doc.lineAt(tr.startState.selection.main.head).from;lineStart!=tr.changes.mapPos(prevLineStart,-1)&&(value=RangeSet.empty)}value=value.map(tr.changes);for(let effect of tr.effects)effect.is(closeBracketEffect)&&(value=value.update({add:[closedBracket.range(effect.value,effect.value+1)]}));return value}});function closeBrackets(){return[inputHandler,bracketState]}__name(closeBrackets,"closeBrackets"),__name2(closeBrackets,"closeBrackets");const definedClosing="()[]{}<>";function closing(ch){for(let i=0;i<definedClosing.length;i+=2)if(definedClosing.charCodeAt(i)==ch)return definedClosing.charAt(i+1);return fromCodePoint(ch<128?ch:ch+1)}__name(closing,"closing"),__name2(closing,"closing");function config(state,pos){return state.languageDataAt("closeBrackets",pos)[0]||defaults}__name(config,"config"),__name2(config,"config");const android=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),inputHandler=EditorView.inputHandler.of((view,from,to,insert2)=>{if((android?view.composing:view.compositionStarted)||view.state.readOnly)return!1;let sel=view.state.selection.main;if(insert2.length>2||insert2.length==2&&codePointSize(codePointAt(insert2,0))==1||from!=sel.from||to!=sel.to)return!1;let tr=insertBracket(view.state,insert2);return tr?(view.dispatch(tr),!0):!1}),deleteBracketPair=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let tokens=config(state,state.selection.main.head).brackets||defaults.brackets,dont=null,changes=state.changeByRange(range=>{if(range.empty){let before=prevChar(state.doc,range.head);for(let token of tokens)if(token==before&&nextChar(state.doc,range.head)==closing(codePointAt(token,0)))return{changes:{from:range.head-token.length,to:range.head+token.length},range:EditorSelection.cursor(range.head-token.length)}}return{range:dont=range}});return dont||dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"delete.backward"})),!dont},"deleteBracketPair"),closeBracketsKeymap=[{key:"Backspace",run:deleteBracketPair}];function insertBracket(state,bracket2){let conf=config(state,state.selection.main.head),tokens=conf.brackets||defaults.brackets;for(let tok of tokens){let closed=closing(codePointAt(tok,0));if(bracket2==tok)return closed==tok?handleSame(state,tok,tokens.indexOf(tok+tok+tok)>-1,conf):handleOpen(state,tok,closed,conf.before||defaults.before);if(bracket2==closed&&closedBracketAt(state,state.selection.main.from))return handleClose(state,tok,closed)}return null}__name(insertBracket,"insertBracket"),__name2(insertBracket,"insertBracket");function closedBracketAt(state,pos){let found=!1;return state.field(bracketState).between(0,state.doc.length,from=>{from==pos&&(found=!0)}),found}__name(closedBracketAt,"closedBracketAt"),__name2(closedBracketAt,"closedBracketAt");function nextChar(doc2,pos){let next=doc2.sliceString(pos,pos+2);return next.slice(0,codePointSize(codePointAt(next,0)))}__name(nextChar,"nextChar"),__name2(nextChar,"nextChar");function prevChar(doc2,pos){let prev=doc2.sliceString(pos-2,pos);return codePointSize(codePointAt(prev,0))==prev.length?prev:prev.slice(1)}__name(prevChar,"prevChar"),__name2(prevChar,"prevChar");function handleOpen(state,open,close,closeBefore){let dont=null,changes=state.changeByRange(range=>{if(!range.empty)return{changes:[{insert:open,from:range.from},{insert:close,from:range.to}],effects:closeBracketEffect.of(range.to+open.length),range:EditorSelection.range(range.anchor+open.length,range.head+open.length)};let next=nextChar(state.doc,range.head);return!next||/\s/.test(next)||closeBefore.indexOf(next)>-1?{changes:{insert:open+close,from:range.head},effects:closeBracketEffect.of(range.head+open.length),range:EditorSelection.cursor(range.head+open.length)}:{range:dont=range}});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleOpen,"handleOpen"),__name2(handleOpen,"handleOpen");function handleClose(state,_open,close){let dont=null,changes=state.changeByRange(range=>range.empty&&nextChar(state.doc,range.head)==close?{changes:{from:range.head,to:range.head+close.length,insert:close},range:EditorSelection.cursor(range.head+close.length)}:dont={range});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleClose,"handleClose"),__name2(handleClose,"handleClose");function handleSame(state,token,allowTriple,config2){let stringPrefixes=config2.stringPrefixes||defaults.stringPrefixes,dont=null,changes=state.changeByRange(range=>{if(!range.empty)return{changes:[{insert:token,from:range.from},{insert:token,from:range.to}],effects:closeBracketEffect.of(range.to+token.length),range:EditorSelection.range(range.anchor+token.length,range.head+token.length)};let pos=range.head,next=nextChar(state.doc,pos),start;if(next==token){if(nodeStart(state,pos))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(closedBracketAt(state,pos)){let content2=allowTriple&&state.sliceDoc(pos,pos+token.length*3)==token+token+token?token+token+token:token;return{changes:{from:pos,to:pos+content2.length,insert:content2},range:EditorSelection.cursor(pos+content2.length)}}}else{if(allowTriple&&state.sliceDoc(pos-2*token.length,pos)==token+token&&(start=canStartStringAt(state,pos-2*token.length,stringPrefixes))>-1&&nodeStart(state,start))return{changes:{insert:token+token+token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(state.charCategorizer(pos)(next)!=CharCategory.Word&&canStartStringAt(state,pos,stringPrefixes)>-1&&!probablyInString(state,pos,token,stringPrefixes))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)}}return{range:dont=range}});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleSame,"handleSame"),__name2(handleSame,"handleSame");function nodeStart(state,pos){let tree=syntaxTree(state).resolveInner(pos+1);return tree.parent&&tree.from==pos}__name(nodeStart,"nodeStart"),__name2(nodeStart,"nodeStart");function probablyInString(state,pos,quoteToken,prefixes){let node=syntaxTree(state).resolveInner(pos,-1),maxPrefix=prefixes.reduce((m,p)=>Math.max(m,p.length),0);for(let i=0;i<5;i++){let start=state.sliceDoc(node.from,Math.min(node.to,node.from+quoteToken.length+maxPrefix)),quotePos=start.indexOf(quoteToken);if(!quotePos||quotePos>-1&&prefixes.indexOf(start.slice(0,quotePos))>-1){let first=node.firstChild;for(;first&&first.from==node.from&&first.to-first.from>quoteToken.length+quotePos;){if(state.sliceDoc(first.to-quoteToken.length,first.to)==quoteToken)return!1;first=first.firstChild}return!0}let parent=node.to==pos&&node.parent;if(!parent)break;node=parent}return!1}__name(probablyInString,"probablyInString"),__name2(probablyInString,"probablyInString");function canStartStringAt(state,pos,prefixes){let charCat=state.charCategorizer(pos);if(charCat(state.sliceDoc(pos-1,pos))!=CharCategory.Word)return pos;for(let prefix of prefixes){let start=pos-prefix.length;if(state.sliceDoc(start,pos)==prefix&&charCat(state.sliceDoc(start-1,start))!=CharCategory.Word)return start}return-1}__name(canStartStringAt,"canStartStringAt"),__name2(canStartStringAt,"canStartStringAt");function autocompletion(config2={}){return[completionState,completionConfig.of(config2),completionPlugin,completionKeymapExt,baseTheme$3]}__name(autocompletion,"autocompletion"),__name2(autocompletion,"autocompletion");const completionKeymap=[{key:"Ctrl-Space",run:startCompletion},{key:"Escape",run:closeCompletion},{key:"ArrowDown",run:moveCompletionSelection(!0)},{key:"ArrowUp",run:moveCompletionSelection(!1)},{key:"PageDown",run:moveCompletionSelection(!0,"page")},{key:"PageUp",run:moveCompletionSelection(!1,"page")},{key:"Enter",run:acceptCompletion}],completionKeymapExt=Prec.highest(keymap.computeN([completionConfig],state=>state.facet(completionConfig).defaultKeymap?[completionKeymap]:[])),toggleComment=__name2(target=>{let{state}=target,line=state.doc.lineAt(state.selection.main.from),config2=getConfig(target.state,line.from);return config2.line?toggleLineComment(target):config2.block?toggleBlockCommentByLine(target):!1},"toggleComment");function command(f2,option2){return({state,dispatch})=>{if(state.readOnly)return!1;let tr=f2(option2,state);return tr?(dispatch(state.update(tr)),!0):!1}}__name(command,"command"),__name2(command,"command");const toggleLineComment=command(changeLineComment,0),toggleBlockComment=command(changeBlockComment,0),toggleBlockCommentByLine=command((o,s2)=>changeBlockComment(o,s2,selectedLineRanges(s2)),0);function getConfig(state,pos){let data=state.languageDataAt("commentTokens",pos);return data.length?data[0]:{}}__name(getConfig,"getConfig"),__name2(getConfig,"getConfig");const SearchMargin=50;function findBlockComment(state,{open,close},from,to){let textBefore=state.sliceDoc(from-SearchMargin,from),textAfter=state.sliceDoc(to,to+SearchMargin),spaceBefore=/\s*$/.exec(textBefore)[0].length,spaceAfter=/^\s*/.exec(textAfter)[0].length,beforeOff=textBefore.length-spaceBefore;if(textBefore.slice(beforeOff-open.length,beforeOff)==open&&textAfter.slice(spaceAfter,spaceAfter+close.length)==close)return{open:{pos:from-spaceBefore,margin:spaceBefore&&1},close:{pos:to+spaceAfter,margin:spaceAfter&&1}};let startText,endText;to-from<=2*SearchMargin?startText=endText=state.sliceDoc(from,to):(startText=state.sliceDoc(from,from+SearchMargin),endText=state.sliceDoc(to-SearchMargin,to));let startSpace=/^\s*/.exec(startText)[0].length,endSpace=/\s*$/.exec(endText)[0].length,endOff=endText.length-endSpace-close.length;return startText.slice(startSpace,startSpace+open.length)==open&&endText.slice(endOff,endOff+close.length)==close?{open:{pos:from+startSpace+open.length,margin:/\s/.test(startText.charAt(startSpace+open.length))?1:0},close:{pos:to-endSpace-close.length,margin:/\s/.test(endText.charAt(endOff-1))?1:0}}:null}__name(findBlockComment,"findBlockComment"),__name2(findBlockComment,"findBlockComment");function selectedLineRanges(state){let ranges=[];for(let r of state.selection.ranges){let fromLine=state.doc.lineAt(r.from),toLine=r.to<=fromLine.to?fromLine:state.doc.lineAt(r.to),last2=ranges.length-1;last2>=0&&ranges[last2].to>fromLine.from?ranges[last2].to=toLine.to:ranges.push({from:fromLine.from+/^\s*/.exec(fromLine.text)[0].length,to:toLine.to})}return ranges}__name(selectedLineRanges,"selectedLineRanges"),__name2(selectedLineRanges,"selectedLineRanges");function changeBlockComment(option2,state,ranges=state.selection.ranges){let tokens=ranges.map(r=>getConfig(state,r.from).block);if(!tokens.every(c=>c))return null;let comments=ranges.map((r,i)=>findBlockComment(state,tokens[i],r.from,r.to));if(option2!=2&&!comments.every(c=>c))return{changes:state.changes(ranges.map((range,i)=>comments[i]?[]:[{from:range.from,insert:tokens[i].open+" "},{from:range.to,insert:" "+tokens[i].close}]))};if(option2!=1&&comments.some(c=>c)){let changes=[];for(let i=0,comment2;i<comments.length;i++)if(comment2=comments[i]){let token=tokens[i],{open,close}=comment2;changes.push({from:open.pos-token.open.length,to:open.pos+open.margin},{from:close.pos-close.margin,to:close.pos+token.close.length})}return{changes}}return null}__name(changeBlockComment,"changeBlockComment"),__name2(changeBlockComment,"changeBlockComment");function changeLineComment(option2,state,ranges=state.selection.ranges){let lines=[],prevLine=-1;for(let{from,to}of ranges){let startI=lines.length,minIndent=1e9,token=getConfig(state,from).line;if(token){for(let pos=from;pos<=to;){let line=state.doc.lineAt(pos);if(line.from>prevLine&&(from==to||to>line.from)){prevLine=line.from;let indent=/^\s*/.exec(line.text)[0].length,empty2=indent==line.length,comment2=line.text.slice(indent,indent+token.length)==token?indent:-1;indent<line.text.length&&indent<minIndent&&(minIndent=indent),lines.push({line,comment:comment2,token,indent,empty:empty2,single:!1})}pos=line.to+1}if(minIndent<1e9)for(let i=startI;i<lines.length;i++)lines[i].indent<lines[i].line.text.length&&(lines[i].indent=minIndent);lines.length==startI+1&&(lines[startI].single=!0)}}if(option2!=2&&lines.some(l2=>l2.comment<0&&(!l2.empty||l2.single))){let changes=[];for(let{line,token,indent,empty:empty2,single}of lines)(single||!empty2)&&changes.push({from:line.from+indent,insert:token+" "});let changeSet=state.changes(changes);return{changes:changeSet,selection:state.selection.map(changeSet,1)}}else if(option2!=1&&lines.some(l2=>l2.comment>=0)){let changes=[];for(let{line,comment:comment2,token}of lines)if(comment2>=0){let from=line.from+comment2,to=from+token.length;line.text[to-line.from]==" "&&to++,changes.push({from,to})}return{changes}}return null}__name(changeLineComment,"changeLineComment"),__name2(changeLineComment,"changeLineComment");const fromHistory=Annotation.define(),isolateHistory=Annotation.define(),invertedEffects=Facet.define(),historyConfig=Facet.define({combine(configs){return combineConfig(configs,{minDepth:100,newGroupDelay:500,joinToEvent:(_t,isAdjacent2)=>isAdjacent2},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(a,b)=>(tr,adj)=>a(tr,adj)||b(tr,adj)})}});function changeEnd(changes){let end=0;return changes.iterChangedRanges((_,to)=>end=to),end}__name(changeEnd,"changeEnd"),__name2(changeEnd,"changeEnd");const historyField_=StateField.define({create(){return HistoryState.empty},update(state,tr){let config2=tr.state.facet(historyConfig),fromHist=tr.annotation(fromHistory);if(fromHist){let selection=tr.docChanged?EditorSelection.single(changeEnd(tr.changes)):void 0,item=HistEvent.fromTransaction(tr,selection),from=fromHist.side,other=from==0?state.undone:state.done;return item?other=updateBranch(other,other.length,config2.minDepth,item):other=addSelection(other,tr.startState.selection),new HistoryState(from==0?fromHist.rest:other,from==0?other:fromHist.rest)}let isolate=tr.annotation(isolateHistory);if((isolate=="full"||isolate=="before")&&(state=state.isolate()),tr.annotation(Transaction.addToHistory)===!1)return tr.changes.empty?state:state.addMapping(tr.changes.desc);let event=HistEvent.fromTransaction(tr),time=tr.annotation(Transaction.time),userEvent=tr.annotation(Transaction.userEvent);return event?state=state.addChanges(event,time,userEvent,config2,tr):tr.selection&&(state=state.addSelection(tr.startState.selection,time,userEvent,config2.newGroupDelay)),(isolate=="full"||isolate=="after")&&(state=state.isolate()),state},toJSON(value){return{done:value.done.map(e=>e.toJSON()),undone:value.undone.map(e=>e.toJSON())}},fromJSON(json2){return new HistoryState(json2.done.map(HistEvent.fromJSON),json2.undone.map(HistEvent.fromJSON))}});function history(config2={}){return[historyField_,historyConfig.of(config2),EditorView.domEventHandlers({beforeinput(e,view){let command2=e.inputType=="historyUndo"?undo:e.inputType=="historyRedo"?redo:null;return command2?(e.preventDefault(),command2(view)):!1}})]}__name(history,"history"),__name2(history,"history");function cmd(side,selection){return function({state,dispatch}){if(!selection&&state.readOnly)return!1;let historyState=state.field(historyField_,!1);if(!historyState)return!1;let tr=historyState.pop(side,state,selection);return tr?(dispatch(tr),!0):!1}}__name(cmd,"cmd"),__name2(cmd,"cmd");const undo=cmd(0,!1),redo=cmd(1,!1),undoSelection=cmd(0,!0),redoSelection=cmd(1,!0),_HistEvent=class _HistEvent2{static{__name(this,"_HistEvent")}constructor(changes,effects,mapped,startSelection,selectionsAfter){this.changes=changes,this.effects=effects,this.mapped=mapped,this.startSelection=startSelection,this.selectionsAfter=selectionsAfter}setSelAfter(after){return new _HistEvent2(this.changes,this.effects,this.mapped,this.startSelection,after)}toJSON(){var _a3,_b2,_c2;return{changes:(_a3=this.changes)===null||_a3===void 0?void 0:_a3.toJSON(),mapped:(_b2=this.mapped)===null||_b2===void 0?void 0:_b2.toJSON(),startSelection:(_c2=this.startSelection)===null||_c2===void 0?void 0:_c2.toJSON(),selectionsAfter:this.selectionsAfter.map(s2=>s2.toJSON())}}static fromJSON(json2){return new _HistEvent2(json2.changes&&ChangeSet.fromJSON(json2.changes),[],json2.mapped&&ChangeDesc.fromJSON(json2.mapped),json2.startSelection&&EditorSelection.fromJSON(json2.startSelection),json2.selectionsAfter.map(EditorSelection.fromJSON))}static fromTransaction(tr,selection){let effects=none;for(let invert of tr.startState.facet(invertedEffects)){let result=invert(tr);result.length&&(effects=effects.concat(result))}return!effects.length&&tr.changes.empty?null:new _HistEvent2(tr.changes.invert(tr.startState.doc),effects,void 0,selection||tr.startState.selection,none)}static selection(selections){return new _HistEvent2(void 0,none,void 0,void 0,selections)}};__name2(_HistEvent,"HistEvent");let HistEvent=_HistEvent;function updateBranch(branch,to,maxLen,newEvent){let start=to+1>maxLen+20?to-maxLen-1:0,newBranch=branch.slice(start,to);return newBranch.push(newEvent),newBranch}__name(updateBranch,"updateBranch"),__name2(updateBranch,"updateBranch");function isAdjacent(a,b){let ranges=[],isAdjacent2=!1;return a.iterChangedRanges((f2,t2)=>ranges.push(f2,t2)),b.iterChangedRanges((_f,_t,f2,t2)=>{for(let i=0;i<ranges.length;){let from=ranges[i++],to=ranges[i++];t2>=from&&f2<=to&&(isAdjacent2=!0)}}),isAdjacent2}__name(isAdjacent,"isAdjacent"),__name2(isAdjacent,"isAdjacent");function eqSelectionShape(a,b){return a.ranges.length==b.ranges.length&&a.ranges.filter((r,i)=>r.empty!=b.ranges[i].empty).length===0}__name(eqSelectionShape,"eqSelectionShape"),__name2(eqSelectionShape,"eqSelectionShape");function conc(a,b){return a.length?b.length?a.concat(b):a:b}__name(conc,"conc"),__name2(conc,"conc");const none=[],MaxSelectionsPerEvent=200;function addSelection(branch,selection){if(branch.length){let lastEvent=branch[branch.length-1],sels=lastEvent.selectionsAfter.slice(Math.max(0,lastEvent.selectionsAfter.length-MaxSelectionsPerEvent));return sels.length&&sels[sels.length-1].eq(selection)?branch:(sels.push(selection),updateBranch(branch,branch.length-1,1e9,lastEvent.setSelAfter(sels)))}else return[HistEvent.selection([selection])]}__name(addSelection,"addSelection"),__name2(addSelection,"addSelection");function popSelection(branch){let last2=branch[branch.length-1],newBranch=branch.slice();return newBranch[branch.length-1]=last2.setSelAfter(last2.selectionsAfter.slice(0,last2.selectionsAfter.length-1)),newBranch}__name(popSelection,"popSelection"),__name2(popSelection,"popSelection");function addMappingToBranch(branch,mapping){if(!branch.length)return branch;let length=branch.length,selections=none;for(;length;){let event=mapEvent(branch[length-1],mapping,selections);if(event.changes&&!event.changes.empty||event.effects.length){let result=branch.slice(0,length);return result[length-1]=event,result}else mapping=event.mapped,length--,selections=event.selectionsAfter}return selections.length?[HistEvent.selection(selections)]:none}__name(addMappingToBranch,"addMappingToBranch"),__name2(addMappingToBranch,"addMappingToBranch");function mapEvent(event,mapping,extraSelections){let selections=conc(event.selectionsAfter.length?event.selectionsAfter.map(s2=>s2.map(mapping)):none,extraSelections);if(!event.changes)return HistEvent.selection(selections);let mappedChanges=event.changes.map(mapping),before=mapping.mapDesc(event.changes,!0),fullMapping=event.mapped?event.mapped.composeDesc(before):before;return new HistEvent(mappedChanges,StateEffect.mapEffects(event.effects,mapping),fullMapping,event.startSelection.map(before),selections)}__name(mapEvent,"mapEvent"),__name2(mapEvent,"mapEvent");const joinableUserEvent=/^(input\.type|delete)($|\.)/,_HistoryState=class _HistoryState2{static{__name(this,"_HistoryState")}constructor(done,undone,prevTime=0,prevUserEvent=void 0){this.done=done,this.undone=undone,this.prevTime=prevTime,this.prevUserEvent=prevUserEvent}isolate(){return this.prevTime?new _HistoryState2(this.done,this.undone):this}addChanges(event,time,userEvent,config2,tr){let done=this.done,lastEvent=done[done.length-1];return lastEvent&&lastEvent.changes&&!lastEvent.changes.empty&&event.changes&&(!userEvent||joinableUserEvent.test(userEvent))&&(!lastEvent.selectionsAfter.length&&time-this.prevTime<config2.newGroupDelay&&config2.joinToEvent(tr,isAdjacent(lastEvent.changes,event.changes))||userEvent=="input.type.compose")?done=updateBranch(done,done.length-1,config2.minDepth,new HistEvent(event.changes.compose(lastEvent.changes),conc(event.effects,lastEvent.effects),lastEvent.mapped,lastEvent.startSelection,none)):done=updateBranch(done,done.length,config2.minDepth,event),new _HistoryState2(done,none,time,userEvent)}addSelection(selection,time,userEvent,newGroupDelay){let last2=this.done.length?this.done[this.done.length-1].selectionsAfter:none;return last2.length>0&&time-this.prevTime<newGroupDelay&&userEvent==this.prevUserEvent&&userEvent&&/^select($|\.)/.test(userEvent)&&eqSelectionShape(last2[last2.length-1],selection)?this:new _HistoryState2(addSelection(this.done,selection),this.undone,time,userEvent)}addMapping(mapping){return new _HistoryState2(addMappingToBranch(this.done,mapping),addMappingToBranch(this.undone,mapping),this.prevTime,this.prevUserEvent)}pop(side,state,selection){let branch=side==0?this.done:this.undone;if(branch.length==0)return null;let event=branch[branch.length-1];if(selection&&event.selectionsAfter.length)return state.update({selection:event.selectionsAfter[event.selectionsAfter.length-1],annotations:fromHistory.of({side,rest:popSelection(branch)}),userEvent:side==0?"select.undo":"select.redo",scrollIntoView:!0});if(event.changes){let rest=branch.length==1?none:branch.slice(0,branch.length-1);return event.mapped&&(rest=addMappingToBranch(rest,event.mapped)),state.update({changes:event.changes,selection:event.startSelection,effects:event.effects,annotations:fromHistory.of({side,rest}),filter:!1,userEvent:side==0?"undo":"redo",scrollIntoView:!0})}else return null}};__name2(_HistoryState,"HistoryState");let HistoryState=_HistoryState;HistoryState.empty=new HistoryState(none,none);const historyKeymap=[{key:"Mod-z",run:undo,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:redo,preventDefault:!0},{linux:"Ctrl-Shift-z",run:redo,preventDefault:!0},{key:"Mod-u",run:undoSelection,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:redoSelection,preventDefault:!0}];function updateSel(sel,by){return EditorSelection.create(sel.ranges.map(by),sel.mainIndex)}__name(updateSel,"updateSel"),__name2(updateSel,"updateSel");function setSel(state,selection){return state.update({selection,scrollIntoView:!0,userEvent:"select"})}__name(setSel,"setSel"),__name2(setSel,"setSel");function moveSel({state,dispatch},how){let selection=updateSel(state.selection,how);return selection.eq(state.selection)?!1:(dispatch(setSel(state,selection)),!0)}__name(moveSel,"moveSel"),__name2(moveSel,"moveSel");function rangeEnd(range,forward){return EditorSelection.cursor(forward?range.to:range.from)}__name(rangeEnd,"rangeEnd"),__name2(rangeEnd,"rangeEnd");function cursorByChar(view,forward){return moveSel(view,range=>range.empty?view.moveByChar(range,forward):rangeEnd(range,forward))}__name(cursorByChar,"cursorByChar"),__name2(cursorByChar,"cursorByChar");function ltrAtCursor(view){return view.textDirectionAt(view.state.selection.main.head)==Direction.LTR}__name(ltrAtCursor,"ltrAtCursor"),__name2(ltrAtCursor,"ltrAtCursor");const cursorCharLeft=__name2(view=>cursorByChar(view,!ltrAtCursor(view)),"cursorCharLeft"),cursorCharRight=__name2(view=>cursorByChar(view,ltrAtCursor(view)),"cursorCharRight");function cursorByGroup(view,forward){return moveSel(view,range=>range.empty?view.moveByGroup(range,forward):rangeEnd(range,forward))}__name(cursorByGroup,"cursorByGroup"),__name2(cursorByGroup,"cursorByGroup");const cursorGroupLeft=__name2(view=>cursorByGroup(view,!ltrAtCursor(view)),"cursorGroupLeft"),cursorGroupRight=__name2(view=>cursorByGroup(view,ltrAtCursor(view)),"cursorGroupRight");function interestingNode(state,node,bracketProp){if(node.type.prop(bracketProp))return!0;let len=node.to-node.from;return len&&(len>2||/[^\s,.;:]/.test(state.sliceDoc(node.from,node.to)))||node.firstChild}__name(interestingNode,"interestingNode"),__name2(interestingNode,"interestingNode");function moveBySyntax(state,start,forward){let pos=syntaxTree(state).resolveInner(start.head),bracketProp=forward?NodeProp.closedBy:NodeProp.openedBy;for(let at=start.head;;){let next=forward?pos.childAfter(at):pos.childBefore(at);if(!next)break;interestingNode(state,next,bracketProp)?pos=next:at=forward?next.to:next.from}let bracket2=pos.type.prop(bracketProp),match2,newPos;return bracket2&&(match2=forward?matchBrackets(state,pos.from,1):matchBrackets(state,pos.to,-1))&&match2.matched?newPos=forward?match2.end.to:match2.end.from:newPos=forward?pos.to:pos.from,EditorSelection.cursor(newPos,forward?-1:1)}__name(moveBySyntax,"moveBySyntax"),__name2(moveBySyntax,"moveBySyntax");const cursorSyntaxLeft=__name2(view=>moveSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view))),"cursorSyntaxLeft"),cursorSyntaxRight=__name2(view=>moveSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view))),"cursorSyntaxRight");function cursorByLine(view,forward){return moveSel(view,range=>{if(!range.empty)return rangeEnd(range,forward);let moved2=view.moveVertically(range,forward);return moved2.head!=range.head?moved2:view.moveToLineBoundary(range,forward)})}__name(cursorByLine,"cursorByLine"),__name2(cursorByLine,"cursorByLine");const cursorLineUp=__name2(view=>cursorByLine(view,!1),"cursorLineUp"),cursorLineDown=__name2(view=>cursorByLine(view,!0),"cursorLineDown");function pageInfo(view){let selfScroll=view.scrollDOM.clientHeight<view.scrollDOM.scrollHeight-2,marginTop=0,marginBottom=0,height;if(selfScroll){for(let source of view.state.facet(EditorView.scrollMargins)){let margins=source(view);margins?.top&&(marginTop=Math.max(margins?.top,marginTop)),margins?.bottom&&(marginBottom=Math.max(margins?.bottom,marginBottom))}height=view.scrollDOM.clientHeight-marginTop-marginBottom}else height=(view.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop,marginBottom,selfScroll,height:Math.max(view.defaultLineHeight,height-5)}}__name(pageInfo,"pageInfo"),__name2(pageInfo,"pageInfo");function cursorByPage(view,forward){let page=pageInfo(view),{state}=view,selection=updateSel(state.selection,range=>range.empty?view.moveVertically(range,forward,page.height):rangeEnd(range,forward));if(selection.eq(state.selection))return!1;let effect;if(page.selfScroll){let startPos=view.coordsAtPos(state.selection.main.head),scrollRect=view.scrollDOM.getBoundingClientRect(),scrollTop=scrollRect.top+page.marginTop,scrollBottom=scrollRect.bottom-page.marginBottom;startPos&&startPos.top>scrollTop&&startPos.bottom<scrollBottom&&(effect=EditorView.scrollIntoView(selection.main.head,{y:"start",yMargin:startPos.top-scrollTop}))}return view.dispatch(setSel(state,selection),{effects:effect}),!0}__name(cursorByPage,"cursorByPage"),__name2(cursorByPage,"cursorByPage");const cursorPageUp=__name2(view=>cursorByPage(view,!1),"cursorPageUp"),cursorPageDown=__name2(view=>cursorByPage(view,!0),"cursorPageDown");function moveByLineBoundary(view,start,forward){let line=view.lineBlockAt(start.head),moved2=view.moveToLineBoundary(start,forward);if(moved2.head==start.head&&moved2.head!=(forward?line.to:line.from)&&(moved2=view.moveToLineBoundary(start,forward,!1)),!forward&&moved2.head==line.from&&line.length){let space=/^\s*/.exec(view.state.sliceDoc(line.from,Math.min(line.from+100,line.to)))[0].length;space&&start.head!=line.from+space&&(moved2=EditorSelection.cursor(line.from+space))}return moved2}__name(moveByLineBoundary,"moveByLineBoundary"),__name2(moveByLineBoundary,"moveByLineBoundary");const cursorLineBoundaryForward=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!0)),"cursorLineBoundaryForward"),cursorLineBoundaryBackward=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!1)),"cursorLineBoundaryBackward"),cursorLineBoundaryLeft=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view))),"cursorLineBoundaryLeft"),cursorLineBoundaryRight=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view))),"cursorLineBoundaryRight"),cursorLineStart=__name2(view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from,1)),"cursorLineStart"),cursorLineEnd=__name2(view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to,-1)),"cursorLineEnd");function toMatchingBracket(state,dispatch,extend2){let found=!1,selection=updateSel(state.selection,range=>{let matching=matchBrackets(state,range.head,-1)||matchBrackets(state,range.head,1)||range.head>0&&matchBrackets(state,range.head-1,1)||range.head<state.doc.length&&matchBrackets(state,range.head+1,-1);if(!matching||!matching.end)return range;found=!0;let head=matching.start.from==range.head?matching.end.to:matching.end.from;return extend2?EditorSelection.range(range.anchor,head):EditorSelection.cursor(head)});return found?(dispatch(setSel(state,selection)),!0):!1}__name(toMatchingBracket,"toMatchingBracket"),__name2(toMatchingBracket,"toMatchingBracket");const cursorMatchingBracket=__name2(({state,dispatch})=>toMatchingBracket(state,dispatch,!1),"cursorMatchingBracket");function extendSel(view,how){let selection=updateSel(view.state.selection,range=>{let head=how(range);return EditorSelection.range(range.anchor,head.head,head.goalColumn,head.bidiLevel||void 0)});return selection.eq(view.state.selection)?!1:(view.dispatch(setSel(view.state,selection)),!0)}__name(extendSel,"extendSel"),__name2(extendSel,"extendSel");function selectByChar(view,forward){return extendSel(view,range=>view.moveByChar(range,forward))}__name(selectByChar,"selectByChar"),__name2(selectByChar,"selectByChar");const selectCharLeft=__name2(view=>selectByChar(view,!ltrAtCursor(view)),"selectCharLeft"),selectCharRight=__name2(view=>selectByChar(view,ltrAtCursor(view)),"selectCharRight");function selectByGroup(view,forward){return extendSel(view,range=>view.moveByGroup(range,forward))}__name(selectByGroup,"selectByGroup"),__name2(selectByGroup,"selectByGroup");const selectGroupLeft=__name2(view=>selectByGroup(view,!ltrAtCursor(view)),"selectGroupLeft"),selectGroupRight=__name2(view=>selectByGroup(view,ltrAtCursor(view)),"selectGroupRight"),selectSyntaxLeft=__name2(view=>extendSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view))),"selectSyntaxLeft"),selectSyntaxRight=__name2(view=>extendSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view))),"selectSyntaxRight");function selectByLine(view,forward){return extendSel(view,range=>view.moveVertically(range,forward))}__name(selectByLine,"selectByLine"),__name2(selectByLine,"selectByLine");const selectLineUp=__name2(view=>selectByLine(view,!1),"selectLineUp"),selectLineDown=__name2(view=>selectByLine(view,!0),"selectLineDown");function selectByPage(view,forward){return extendSel(view,range=>view.moveVertically(range,forward,pageInfo(view).height))}__name(selectByPage,"selectByPage"),__name2(selectByPage,"selectByPage");const selectPageUp=__name2(view=>selectByPage(view,!1),"selectPageUp"),selectPageDown=__name2(view=>selectByPage(view,!0),"selectPageDown"),selectLineBoundaryForward=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!0)),"selectLineBoundaryForward"),selectLineBoundaryBackward=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!1)),"selectLineBoundaryBackward"),selectLineBoundaryLeft=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view))),"selectLineBoundaryLeft"),selectLineBoundaryRight=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view))),"selectLineBoundaryRight"),selectLineStart=__name2(view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from)),"selectLineStart"),selectLineEnd=__name2(view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to)),"selectLineEnd"),cursorDocStart=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:0})),!0),"cursorDocStart"),cursorDocEnd=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.doc.length})),!0),"cursorDocEnd"),selectDocStart=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.selection.main.anchor,head:0})),!0),"selectDocStart"),selectDocEnd=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.selection.main.anchor,head:state.doc.length})),!0),"selectDocEnd"),selectAll=__name2(({state,dispatch})=>(dispatch(state.update({selection:{anchor:0,head:state.doc.length},userEvent:"select"})),!0),"selectAll"),selectLine=__name2(({state,dispatch})=>{let ranges=selectedLineBlocks(state).map(({from,to})=>EditorSelection.range(from,Math.min(to+1,state.doc.length)));return dispatch(state.update({selection:EditorSelection.create(ranges),userEvent:"select"})),!0},"selectLine"),selectParentSyntax=__name2(({state,dispatch})=>{let selection=updateSel(state.selection,range=>{var _a3;let context=syntaxTree(state).resolveInner(range.head,1);for(;!(context.from<range.from&&context.to>=range.to||context.to>range.to&&context.from<=range.from||!(!((_a3=context.parent)===null||_a3===void 0)&&_a3.parent));)context=context.parent;return EditorSelection.range(context.to,context.from)});return dispatch(setSel(state,selection)),!0},"selectParentSyntax"),simplifySelection=__name2(({state,dispatch})=>{let cur2=state.selection,selection=null;return cur2.ranges.length>1?selection=EditorSelection.create([cur2.main]):cur2.main.empty||(selection=EditorSelection.create([EditorSelection.cursor(cur2.main.head)])),selection?(dispatch(setSel(state,selection)),!0):!1},"simplifySelection");function deleteBy(target,by){if(target.state.readOnly)return!1;let event="delete.selection",{state}=target,changes=state.changeByRange(range=>{let{from,to}=range;if(from==to){let towards=by(from);towards<from?(event="delete.backward",towards=skipAtomic(target,towards,!1)):towards>from&&(event="delete.forward",towards=skipAtomic(target,towards,!0)),from=Math.min(from,towards),to=Math.max(to,towards)}else from=skipAtomic(target,from,!1),to=skipAtomic(target,to,!0);return from==to?{range}:{changes:{from,to},range:EditorSelection.cursor(from)}});return changes.changes.empty?!1:(target.dispatch(state.update(changes,{scrollIntoView:!0,userEvent:event,effects:event=="delete.selection"?EditorView.announce.of(state.phrase("Selection deleted")):void 0})),!0)}__name(deleteBy,"deleteBy"),__name2(deleteBy,"deleteBy");function skipAtomic(target,pos,forward){if(target instanceof EditorView)for(let ranges of target.state.facet(EditorView.atomicRanges).map(f2=>f2(target)))ranges.between(pos,pos,(from,to)=>{from<pos&&to>pos&&(pos=forward?to:from)});return pos}__name(skipAtomic,"skipAtomic"),__name2(skipAtomic,"skipAtomic");const deleteByChar=__name2((target,forward)=>deleteBy(target,pos=>{let{state}=target,line=state.doc.lineAt(pos),before,targetPos;if(!forward&&pos>line.from&&pos<line.from+200&&!/[^ \t]/.test(before=line.text.slice(0,pos-line.from))){if(before[before.length-1]==" ")return pos-1;let col=countColumn(before,state.tabSize),drop3=col%getIndentUnit(state)||getIndentUnit(state);for(let i=0;i<drop3&&before[before.length-1-i]==" ";i++)pos--;targetPos=pos}else targetPos=findClusterBreak(line.text,pos-line.from,forward,forward)+line.from,targetPos==pos&&line.number!=(forward?state.doc.lines:1)&&(targetPos+=forward?1:-1);return targetPos}),"deleteByChar"),deleteCharBackward=__name2(view=>deleteByChar(view,!1),"deleteCharBackward"),deleteCharForward=__name2(view=>deleteByChar(view,!0),"deleteCharForward"),deleteByGroup=__name2((target,forward)=>deleteBy(target,start=>{let pos=start,{state}=target,line=state.doc.lineAt(pos),categorize=state.charCategorizer(pos);for(let cat=null;;){if(pos==(forward?line.to:line.from)){pos==start&&line.number!=(forward?state.doc.lines:1)&&(pos+=forward?1:-1);break}let next=findClusterBreak(line.text,pos-line.from,forward)+line.from,nextChar2=line.text.slice(Math.min(pos,next)-line.from,Math.max(pos,next)-line.from),nextCat=categorize(nextChar2);if(cat!=null&&nextCat!=cat)break;(nextChar2!=" "||pos!=start)&&(cat=nextCat),pos=next}return pos}),"deleteByGroup"),deleteGroupBackward=__name2(target=>deleteByGroup(target,!1),"deleteGroupBackward"),deleteGroupForward=__name2(target=>deleteByGroup(target,!0),"deleteGroupForward"),deleteToLineEnd=__name2(view=>deleteBy(view,pos=>{let lineEnd=view.lineBlockAt(pos).to;return pos<lineEnd?lineEnd:Math.min(view.state.doc.length,pos+1)}),"deleteToLineEnd"),deleteToLineStart=__name2(view=>deleteBy(view,pos=>{let lineStart=view.lineBlockAt(pos).from;return pos>lineStart?lineStart:Math.max(0,pos-1)}),"deleteToLineStart"),splitLine=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>({changes:{from:range.from,to:range.to,insert:Text.of(["",""])},range:EditorSelection.cursor(range.from)}));return dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"input"})),!0},"splitLine"),transposeChars=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>{if(!range.empty||range.from==0||range.from==state.doc.length)return{range};let pos=range.from,line=state.doc.lineAt(pos),from=pos==line.from?pos-1:findClusterBreak(line.text,pos-line.from,!1)+line.from,to=pos==line.to?pos+1:findClusterBreak(line.text,pos-line.from,!0)+line.from;return{changes:{from,to,insert:state.doc.slice(pos,to).append(state.doc.slice(from,pos))},range:EditorSelection.cursor(to)}});return changes.changes.empty?!1:(dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"move.character"})),!0)},"transposeChars");function selectedLineBlocks(state){let blocks=[],upto=-1;for(let range of state.selection.ranges){let startLine=state.doc.lineAt(range.from),endLine=state.doc.lineAt(range.to);if(!range.empty&&range.to==endLine.from&&(endLine=state.doc.lineAt(range.to-1)),upto>=startLine.number){let prev=blocks[blocks.length-1];prev.to=endLine.to,prev.ranges.push(range)}else blocks.push({from:startLine.from,to:endLine.to,ranges:[range]});upto=endLine.number+1}return blocks}__name(selectedLineBlocks,"selectedLineBlocks"),__name2(selectedLineBlocks,"selectedLineBlocks");function moveLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[],ranges=[];for(let block of selectedLineBlocks(state)){if(forward?block.to==state.doc.length:block.from==0)continue;let nextLine=state.doc.lineAt(forward?block.to+1:block.from-1),size=nextLine.length+1;if(forward){changes.push({from:block.to,to:nextLine.to},{from:block.from,insert:nextLine.text+state.lineBreak});for(let r of block.ranges)ranges.push(EditorSelection.range(Math.min(state.doc.length,r.anchor+size),Math.min(state.doc.length,r.head+size)))}else{changes.push({from:nextLine.from,to:block.from},{from:block.to,insert:state.lineBreak+nextLine.text});for(let r of block.ranges)ranges.push(EditorSelection.range(r.anchor-size,r.head-size))}}return changes.length?(dispatch(state.update({changes,scrollIntoView:!0,selection:EditorSelection.create(ranges,state.selection.mainIndex),userEvent:"move.line"})),!0):!1}__name(moveLine,"moveLine"),__name2(moveLine,"moveLine");const moveLineUp=__name2(({state,dispatch})=>moveLine(state,dispatch,!1),"moveLineUp"),moveLineDown=__name2(({state,dispatch})=>moveLine(state,dispatch,!0),"moveLineDown");function copyLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[];for(let block of selectedLineBlocks(state))forward?changes.push({from:block.from,insert:state.doc.slice(block.from,block.to)+state.lineBreak}):changes.push({from:block.to,insert:state.lineBreak+state.doc.slice(block.from,block.to)});return dispatch(state.update({changes,scrollIntoView:!0,userEvent:"input.copyline"})),!0}__name(copyLine,"copyLine"),__name2(copyLine,"copyLine");const copyLineUp=__name2(({state,dispatch})=>copyLine(state,dispatch,!1),"copyLineUp"),copyLineDown=__name2(({state,dispatch})=>copyLine(state,dispatch,!0),"copyLineDown"),deleteLine=__name2(view=>{if(view.state.readOnly)return!1;let{state}=view,changes=state.changes(selectedLineBlocks(state).map(({from,to})=>(from>0?from--:to<state.doc.length&&to++,{from,to}))),selection=updateSel(state.selection,range=>view.moveVertically(range,!0)).map(changes);return view.dispatch({changes,selection,scrollIntoView:!0,userEvent:"delete.line"}),!0},"deleteLine");function isBetweenBrackets(state,pos){if(/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos-1,pos+1)))return{from:pos,to:pos};let context=syntaxTree(state).resolveInner(pos),before=context.childBefore(pos),after=context.childAfter(pos),closedBy;return before&&after&&before.to<=pos&&after.from>=pos&&(closedBy=before.type.prop(NodeProp.closedBy))&&closedBy.indexOf(after.name)>-1&&state.doc.lineAt(before.to).from==state.doc.lineAt(after.from).from?{from:before.to,to:after.from}:null}__name(isBetweenBrackets,"isBetweenBrackets"),__name2(isBetweenBrackets,"isBetweenBrackets");const insertNewlineAndIndent=newlineAndIndent(!1),insertBlankLine=newlineAndIndent(!0);function newlineAndIndent(atEof){return({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>{let{from,to}=range,line=state.doc.lineAt(from),explode=!atEof&&from==to&&isBetweenBrackets(state,from);atEof&&(from=to=(to<=line.to?line:state.doc.lineAt(to)).to);let cx=new IndentContext(state,{simulateBreak:from,simulateDoubleBreak:!!explode}),indent=getIndentation(cx,from);for(indent==null&&(indent=/^\s*/.exec(state.doc.lineAt(from).text)[0].length);to<line.to&&/\s/.test(line.text[to-line.from]);)to++;explode?{from,to}=explode:from>line.from&&from<line.from+100&&!/\S/.test(line.text.slice(0,from))&&(from=line.from);let insert2=["",indentString(state,indent)];return explode&&insert2.push(indentString(state,cx.lineIndent(line.from,-1))),{changes:{from,to,insert:Text.of(insert2)},range:EditorSelection.cursor(from+1+insert2[1].length)}});return dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"input"})),!0}}__name(newlineAndIndent,"newlineAndIndent"),__name2(newlineAndIndent,"newlineAndIndent");function changeBySelectedLine(state,f2){let atLine=-1;return state.changeByRange(range=>{let changes=[];for(let pos=range.from;pos<=range.to;){let line=state.doc.lineAt(pos);line.number>atLine&&(range.empty||range.to>line.from)&&(f2(line,changes,range),atLine=line.number),pos=line.to+1}let changeSet=state.changes(changes);return{changes,range:EditorSelection.range(changeSet.mapPos(range.anchor,1),changeSet.mapPos(range.head,1))}})}__name(changeBySelectedLine,"changeBySelectedLine"),__name2(changeBySelectedLine,"changeBySelectedLine");const indentSelection=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let updated=Object.create(null),context=new IndentContext(state,{overrideIndentation:start=>{let found=updated[start];return found??-1}}),changes=changeBySelectedLine(state,(line,changes2,range)=>{let indent=getIndentation(context,line.from);if(indent==null)return;/\S/.test(line.text)||(indent=0);let cur2=/^\s*/.exec(line.text)[0],norm=indentString(state,indent);(cur2!=norm||range.from<line.from+cur2.length)&&(updated[line.from]=indent,changes2.push({from:line.from,to:line.from+cur2.length,insert:norm}))});return changes.changes.empty||dispatch(state.update(changes,{userEvent:"indent"})),!0},"indentSelection"),indentMore=__name2(({state,dispatch})=>state.readOnly?!1:(dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{changes.push({from:line.from,insert:state.facet(indentUnit)})}),{userEvent:"input.indent"})),!0),"indentMore"),indentLess=__name2(({state,dispatch})=>state.readOnly?!1:(dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{let space=/^\s*/.exec(line.text)[0];if(!space)return;let col=countColumn(space,state.tabSize),keep=0,insert2=indentString(state,Math.max(0,col-getIndentUnit(state)));for(;keep<space.length&&keep<insert2.length&&space.charCodeAt(keep)==insert2.charCodeAt(keep);)keep++;changes.push({from:line.from+keep,to:line.from+space.length,insert:insert2.slice(keep)})}),{userEvent:"delete.dedent"})),!0),"indentLess"),emacsStyleKeymap=[{key:"Ctrl-b",run:cursorCharLeft,shift:selectCharLeft,preventDefault:!0},{key:"Ctrl-f",run:cursorCharRight,shift:selectCharRight},{key:"Ctrl-p",run:cursorLineUp,shift:selectLineUp},{key:"Ctrl-n",run:cursorLineDown,shift:selectLineDown},{key:"Ctrl-a",run:cursorLineStart,shift:selectLineStart},{key:"Ctrl-e",run:cursorLineEnd,shift:selectLineEnd},{key:"Ctrl-d",run:deleteCharForward},{key:"Ctrl-h",run:deleteCharBackward},{key:"Ctrl-k",run:deleteToLineEnd},{key:"Ctrl-Alt-h",run:deleteGroupBackward},{key:"Ctrl-o",run:splitLine},{key:"Ctrl-t",run:transposeChars},{key:"Ctrl-v",run:cursorPageDown}],standardKeymap=[{key:"ArrowLeft",run:cursorCharLeft,shift:selectCharLeft,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:cursorGroupLeft,shift:selectGroupLeft,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:cursorLineBoundaryLeft,shift:selectLineBoundaryLeft,preventDefault:!0},{key:"ArrowRight",run:cursorCharRight,shift:selectCharRight,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:cursorGroupRight,shift:selectGroupRight,preventDefault:!0},{mac:"Cmd-ArrowRight",run:cursorLineBoundaryRight,shift:selectLineBoundaryRight,preventDefault:!0},{key:"ArrowUp",run:cursorLineUp,shift:selectLineUp,preventDefault:!0},{mac:"Cmd-ArrowUp",run:cursorDocStart,shift:selectDocStart},{mac:"Ctrl-ArrowUp",run:cursorPageUp,shift:selectPageUp},{key:"ArrowDown",run:cursorLineDown,shift:selectLineDown,preventDefault:!0},{mac:"Cmd-ArrowDown",run:cursorDocEnd,shift:selectDocEnd},{mac:"Ctrl-ArrowDown",run:cursorPageDown,shift:selectPageDown},{key:"PageUp",run:cursorPageUp,shift:selectPageUp},{key:"PageDown",run:cursorPageDown,shift:selectPageDown},{key:"Home",run:cursorLineBoundaryBackward,shift:selectLineBoundaryBackward,preventDefault:!0},{key:"Mod-Home",run:cursorDocStart,shift:selectDocStart},{key:"End",run:cursorLineBoundaryForward,shift:selectLineBoundaryForward,preventDefault:!0},{key:"Mod-End",run:cursorDocEnd,shift:selectDocEnd},{key:"Enter",run:insertNewlineAndIndent},{key:"Mod-a",run:selectAll},{key:"Backspace",run:deleteCharBackward,shift:deleteCharBackward},{key:"Delete",run:deleteCharForward},{key:"Mod-Backspace",mac:"Alt-Backspace",run:deleteGroupBackward},{key:"Mod-Delete",mac:"Alt-Delete",run:deleteGroupForward},{mac:"Mod-Backspace",run:deleteToLineStart},{mac:"Mod-Delete",run:deleteToLineEnd}].concat(emacsStyleKeymap.map(b=>({mac:b.key,run:b.run,shift:b.shift}))),defaultKeymap=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:cursorSyntaxLeft,shift:selectSyntaxLeft},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:cursorSyntaxRight,shift:selectSyntaxRight},{key:"Alt-ArrowUp",run:moveLineUp},{key:"Shift-Alt-ArrowUp",run:copyLineUp},{key:"Alt-ArrowDown",run:moveLineDown},{key:"Shift-Alt-ArrowDown",run:copyLineDown},{key:"Escape",run:simplifySelection},{key:"Mod-Enter",run:insertBlankLine},{key:"Alt-l",mac:"Ctrl-l",run:selectLine},{key:"Mod-i",run:selectParentSyntax,preventDefault:!0},{key:"Mod-[",run:indentLess},{key:"Mod-]",run:indentMore},{key:"Mod-Alt-\\",run:indentSelection},{key:"Shift-Mod-k",run:deleteLine},{key:"Shift-Mod-\\",run:cursorMatchingBracket},{key:"Mod-/",run:toggleComment},{key:"Alt-A",run:toggleBlockComment}].concat(standardKeymap),indentWithTab={key:"Tab",run:indentMore,shift:indentLess},_Stack=class _Stack2{static{__name(this,"_Stack")}constructor(p,stack,state,reducePos,pos,score2,buffer,bufferBase,curContext,lookAhead=0,parent){this.p=p,this.stack=stack,this.state=state,this.reducePos=reducePos,this.pos=pos,this.score=score2,this.buffer=buffer,this.bufferBase=bufferBase,this.curContext=curContext,this.lookAhead=lookAhead,this.parent=parent}toString(){return`[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(p,state,pos=0){let cx=p.parser.context;return new _Stack2(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length),this.state=state}reduce(action){var _a3;let depth=action>>19,type=action&65535,{parser:parser2}=this.p,dPrec=parser2.dynamicPrecedence(type);if(dPrec&&(this.score+=dPrec),depth==0){this.pushState(parser2.getGoto(this.state,type,!0),this.reducePos),type<parser2.minRepeatTerm&&this.storeNode(type,this.reducePos,this.reducePos,4,!0),this.reduceContext(type,this.reducePos);return}let base2=this.stack.length-(depth-1)*3-(action&262144?6:0),start=base2?this.stack[base2-2]:this.p.ranges[0].from,size=this.reducePos-start;size>=2e3&&!(!((_a3=this.p.parser.nodeSet.types[type])===null||_a3===void 0)&&_a3.isAnonymous)&&(start==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=size):this.p.lastBigReductionSize<size&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=start,this.p.lastBigReductionSize=size));let bufferBase=base2?this.stack[base2-1]:0,count=this.bufferBase+this.buffer.length-bufferBase;if(type<parser2.minRepeatTerm||action&131072){let pos=parser2.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(type,start,pos,count+4,!0)}if(action&262144)this.state=this.stack[base2];else{let baseStateID=this.stack[base2-3];this.state=parser2.getGoto(baseStateID,type,!0)}for(;this.stack.length>base2;)this.stack.pop();this.reduceContext(type,start)}storeNode(term,start,end,size=4,isReduce=!1){if(term==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let cur2=this,top2=this.buffer.length;if(top2==0&&cur2.parent&&(top2=cur2.bufferBase-cur2.parent.bufferBase,cur2=cur2.parent),top2>0&&cur2.buffer[top2-4]==0&&cur2.buffer[top2-1]>-1){if(start==end)return;if(cur2.buffer[top2-2]>=start){cur2.buffer[top2-2]=end;return}}}if(!isReduce||this.pos==end)this.buffer.push(term,start,end,size);else{let index2=this.buffer.length;if(index2>0&&this.buffer[index2-4]!=0)for(;index2>0&&this.buffer[index2-2]>end;)this.buffer[index2]=this.buffer[index2-4],this.buffer[index2+1]=this.buffer[index2-3],this.buffer[index2+2]=this.buffer[index2-2],this.buffer[index2+3]=this.buffer[index2-1],index2-=4,size>4&&(size-=4);this.buffer[index2]=term,this.buffer[index2+1]=start,this.buffer[index2+2]=end,this.buffer[index2+3]=size}}shift(action,next,nextEnd){let start=this.pos;if(action&131072)this.pushState(action&65535,this.pos);else if(action&262144)this.pos=nextEnd,this.shiftContext(next,start),next<=this.p.parser.maxNode&&this.buffer.push(next,start,nextEnd,4);else{let nextState=action,{parser:parser2}=this.p;(nextEnd>this.pos||next<=parser2.maxNode)&&(this.pos=nextEnd,parser2.stateFlag(nextState,1)||(this.reducePos=nextEnd)),this.pushState(nextState,start),this.shiftContext(next,start),next<=parser2.maxNode&&this.buffer.push(next,start,nextEnd,4)}}apply(action,next,nextEnd){action&65536?this.reduce(action):this.shift(action,next,nextEnd)}useNode(value,next){let index2=this.p.reused.length-1;(index2<0||this.p.reused[index2]!=value)&&(this.p.reused.push(value),index2++);let start=this.pos;this.reducePos=this.pos=start+value.length,this.pushState(next,start),this.buffer.push(index2,start,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)))}split(){let parent=this,off2=parent.buffer.length;for(;off2>0&&parent.buffer[off2-2]>parent.reducePos;)off2-=4;let buffer=parent.buffer.slice(off2),base2=parent.bufferBase+off2;for(;parent&&base2==parent.bufferBase;)parent=parent.parent;return new _Stack2(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base2,this.curContext,this.lookAhead,parent)}recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;isNode&&this.storeNode(next,this.pos,nextEnd,4),this.storeNode(0,this.pos,nextEnd,isNode?8:4),this.pos=this.reducePos=nextEnd,this.score-=190}canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4)||this.p.parser.hasAction(sim.state,term);if(action==0)return!1;if(!(action&65536))return!0;sim.reduce(action)}}recoverByInsert(next){if(this.stack.length>=300)return[];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>8||this.stack.length>=120){let best=[];for(let i=0,s2;i<nextStates.length;i+=2)(s2=nextStates[i+1])!=this.state&&this.p.parser.hasAction(s2,next)&&best.push(nextStates[i],s2);if(this.stack.length<120)for(let i=0;best.length<8&&i<nextStates.length;i+=2){let s2=nextStates[i+1];best.some((v,i2)=>i2&1&&v==s2)||best.push(nextStates[i],s2)}nextStates=best}let result=[];for(let i=0;i<nextStates.length&&result.length<4;i+=2){let s2=nextStates[i+1];if(s2==this.state)continue;let stack=this.split();stack.pushState(s2,this.pos),stack.storeNode(0,stack.pos,stack.pos,4,!0),stack.shiftContext(nextStates[i],this.pos),stack.score-=200,result.push(stack)}return result}forceReduce(){let{parser:parser2}=this.p,reduce=parser2.stateSlot(this.state,5);if(!(reduce&65536))return!1;if(!parser2.validAction(this.state,reduce)){let depth=reduce>>19,term=reduce&65535,target=this.stack.length-depth*3;if(target<0||parser2.getGoto(this.stack[target],term,!1)<0){let backup=this.findForcedReduction();if(backup==null)return!1;reduce=backup}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(reduce),!0}findForcedReduction(){let{parser:parser2}=this.p,seen=[],explore=__name2((state,depth)=>{if(!seen.includes(state))return seen.push(state),parser2.allActions(state,action=>{if(!(action&393216))if(action&65536){let rDepth=(action>>19)-depth;if(rDepth>1){let term=action&65535,target=this.stack.length-rDepth*3;if(target>=0&&parser2.getGoto(this.stack[target],term,!1)>=0)return rDepth<<19|65536|term}}else{let found=explore(action,depth+1);if(found!=null)return found}})},"explore");return explore(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:parser2}=this.p;return parser2.data[parser2.stateSlot(this.state,1)]==65535&&!parser2.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return!1;for(let i=0;i<this.stack.length;i+=3)if(this.stack[i]!=other.stack[i])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(dialectID){return this.p.parser.dialect.flags[dialectID]}shiftContext(term,start){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,term,this,this.p.stream.reset(start)))}reduceContext(term,start){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,term,this,this.p.stream.reset(start)))}emitContext(){let last2=this.buffer.length-1;(last2<0||this.buffer[last2]!=-3)&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let last2=this.buffer.length-1;(last2<0||this.buffer[last2]!=-4)&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(context){if(context!=this.curContext.context){let newCx=new StackContext(this.curContext.tracker,context);newCx.hash!=this.curContext.hash&&this.emitContext(),this.curContext=newCx}}setLookAhead(lookAhead){lookAhead>this.lookAhead&&(this.emitLookAhead(),this.lookAhead=lookAhead)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}};__name2(_Stack,"Stack");let Stack=_Stack;const _StackContext=class{static{__name(this,"_StackContext")}constructor(tracker,context){this.tracker=tracker,this.context=context,this.hash=tracker.strict?tracker.hash(context):0}};__name2(_StackContext,"StackContext");let StackContext=_StackContext;var Recover;(function(Recover2){Recover2[Recover2.Insert=200]="Insert",Recover2[Recover2.Delete=190]="Delete",Recover2[Recover2.Reduce=100]="Reduce",Recover2[Recover2.MaxNext=4]="MaxNext",Recover2[Recover2.MaxInsertStackDepth=300]="MaxInsertStackDepth",Recover2[Recover2.DampenInsertStackDepth=120]="DampenInsertStackDepth",Recover2[Recover2.MinBigReduction=2e3]="MinBigReduction"})(Recover||(Recover={}));const _SimulatedStack=class{static{__name(this,"_SimulatedStack")}constructor(start){this.start=start,this.state=start.state,this.stack=start.stack,this.base=this.stack.length}reduce(action){let term=action&65535,depth=action>>19;depth==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(depth-1)*3;let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,!0);this.state=goto}};__name2(_SimulatedStack,"SimulatedStack");let SimulatedStack=_SimulatedStack;const _StackBufferCursor=class _StackBufferCursor2{static{__name(this,"_StackBufferCursor")}constructor(stack,pos,index2){this.stack=stack,this.pos=pos,this.index=index2,this.buffer=stack.buffer,this.index==0&&this.maybeNext()}static create(stack,pos=stack.bufferBase+stack.buffer.length){return new _StackBufferCursor2(stack,pos,pos-stack.bufferBase)}maybeNext(){let next=this.stack.parent;next!=null&&(this.index=this.stack.bufferBase-next.bufferBase,this.stack=next,this.buffer=next.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new _StackBufferCursor2(this.stack,this.pos,this.index)}};__name2(_StackBufferCursor,"StackBufferCursor");let StackBufferCursor=_StackBufferCursor;function decodeArray(input,Type=Uint16Array){if(typeof input!="string")return input;let array=null;for(let pos=0,out=0;pos<input.length;){let value=0;for(;;){let next=input.charCodeAt(pos++),stop=!1;if(next==126){value=65535;break}next>=92&&next--,next>=34&&next--;let digit=next-32;if(digit>=46&&(digit-=46,stop=!0),value+=digit,stop)break;value*=46}array?array[out++]=value:array=new Type(value)}return array}__name(decodeArray,"decodeArray"),__name2(decodeArray,"decodeArray");const _CachedToken=class{static{__name(this,"_CachedToken")}constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}};__name2(_CachedToken,"CachedToken");let CachedToken=_CachedToken;const nullToken=new CachedToken,_InputStream=class{static{__name(this,"_InputStream")}constructor(input,ranges){this.input=input,this.ranges=ranges,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=ranges[0].from,this.range=ranges[0],this.end=ranges[ranges.length-1].to,this.readNext()}resolveOffset(offset2,assoc){let range=this.range,index2=this.rangeIndex,pos=this.pos+offset2;for(;pos<range.from;){if(!index2)return null;let next=this.ranges[--index2];pos-=range.from-next.to,range=next}for(;assoc<0?pos>range.to:pos>=range.to;){if(index2==this.ranges.length-1)return null;let next=this.ranges[++index2];pos+=next.from-range.to,range=next}return pos}clipPos(pos){if(pos>=this.range.from&&pos<this.range.to)return pos;for(let range of this.ranges)if(range.to>pos)return Math.max(pos,range.from);return this.end}peek(offset2){let idx=this.chunkOff+offset2,pos,result;if(idx>=0&&idx<this.chunk.length)pos=this.pos+offset2,result=this.chunk.charCodeAt(idx);else{let resolved=this.resolveOffset(offset2,1);if(resolved==null)return-1;if(pos=resolved,pos>=this.chunk2Pos&&pos<this.chunk2Pos+this.chunk2.length)result=this.chunk2.charCodeAt(pos-this.chunk2Pos);else{let i=this.rangeIndex,range=this.range;for(;range.to<=pos;)range=this.ranges[++i];this.chunk2=this.input.chunk(this.chunk2Pos=pos),pos+this.chunk2.length>range.to&&(this.chunk2=this.chunk2.slice(0,range.to-pos)),result=this.chunk2.charCodeAt(0)}}return pos>=this.token.lookAhead&&(this.token.lookAhead=pos+1),result}acceptToken(token,endOffset=0){let end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(end==null||end<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=token,this.token.end=end}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk,chunkPos}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=chunk,this.chunk2Pos=chunkPos,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let nextChunk=this.input.chunk(this.pos),end=this.pos+nextChunk.length;this.chunk=end>this.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(n2=1){for(this.chunkOff+=n2;this.pos+n2>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n2-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=n2,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(pos,token){if(token?(this.token=token,token.start=pos,token.lookAhead=pos+1,token.value=token.extended=-1):this.token=nullToken,this.pos!=pos){if(this.pos=pos,pos==this.end)return this.setDone(),this;for(;pos<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;pos>=this.range.to;)this.range=this.ranges[++this.rangeIndex];pos>=this.chunkPos&&pos<this.chunkPos+this.chunk.length?this.chunkOff=pos-this.chunkPos:(this.chunk="",this.chunkOff=0),this.readNext()}return this}read(from,to){if(from>=this.chunkPos&&to<=this.chunkPos+this.chunk.length)return this.chunk.slice(from-this.chunkPos,to-this.chunkPos);if(from>=this.chunk2Pos&&to<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(from-this.chunk2Pos,to-this.chunk2Pos);if(from>=this.range.from&&to<=this.range.to)return this.input.read(from,to);let result="";for(let r of this.ranges){if(r.from>=to)break;r.to>from&&(result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to)))}return result}};__name2(_InputStream,"InputStream");let InputStream=_InputStream;const _TokenGroup=class{static{__name(this,"_TokenGroup")}constructor(data,id){this.data=data,this.id=id}token(input,stack){let{parser:parser2}=stack.p;readToken(this.data,input,stack,this.id,parser2.data,parser2.tokenPrecTable)}};__name2(_TokenGroup,"TokenGroup");let TokenGroup=_TokenGroup;TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1,TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;function readToken(data,input,stack,group,precTable,precOffset){let state=0,groupMask=1<<group,{dialect}=stack.p.parser;scan:for(;groupMask&data[state];){let accEnd=data[state+1];for(let i=state+3;i<accEnd;i+=2)if((data[i+1]&groupMask)>0){let term=data[i];if(dialect.allows(term)&&(input.token.value==-1||input.token.value==term||overrides(term,input.token.value,precTable,precOffset))){input.acceptToken(term);break}}let next=input.next,low=0,high=data[state+2];if(input.next<0&&high>low&&data[accEnd+high*3-3]==65535&&data[accEnd+high*3-3]==65535){state=data[accEnd+high*3-1];continue scan}for(;low<high;){let mid=low+high>>1,index2=accEnd+mid+(mid<<1),from=data[index2],to=data[index2+1]||65536;if(next<from)high=mid;else if(next>=to)low=mid+1;else{state=data[index2+2],input.advance();continue scan}}break}}__name(readToken,"readToken"),__name2(readToken,"readToken");function findOffset(data,start,term){for(let i=start,next;(next=data[i])!=65535;i++)if(next==term)return i-start;return-1}__name(findOffset,"findOffset"),__name2(findOffset,"findOffset");function overrides(token,prev,tableData,tableOffset){let iPrev=findOffset(tableData,tableOffset,prev);return iPrev<0||findOffset(tableData,tableOffset,token)<iPrev}__name(overrides,"overrides"),__name2(overrides,"overrides");const verbose=typeof process<"u"&&process.env&&/\bparse\b/.test(process.env.LOG);let stackIDs=null;var Safety;(function(Safety2){Safety2[Safety2.Margin=25]="Margin"})(Safety||(Safety={}));function cutAt(tree,pos,side){let cursor=tree.cursor(IterMode.IncludeAnonymous);for(cursor.moveTo(pos);;)if(!(side<0?cursor.childBefore(pos):cursor.childAfter(pos)))for(;;){if((side<0?cursor.to<pos:cursor.from>pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25)):Math.min(tree.length,Math.max(cursor.from+1,pos+25));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length}}__name(cutAt,"cutAt"),__name2(cutAt,"cutAt");const _FragmentCursor=class{static{__name(this,"_FragmentCursor")}constructor(fragments,nodeSet){this.fragments=fragments,this.nodeSet=nodeSet,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let fr=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(fr){for(this.safeFrom=fr.openStart?cutAt(fr.tree,fr.from+fr.offset,1)-fr.offset:fr.from,this.safeTo=fr.openEnd?cutAt(fr.tree,fr.to+fr.offset,-1)-fr.offset:fr.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(fr.tree),this.start.push(-fr.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(pos){if(pos<this.nextStart)return null;for(;this.fragment&&this.safeTo<=pos;)this.nextFragment();if(!this.fragment)return null;for(;;){let last2=this.trees.length-1;if(last2<0)return this.nextFragment(),null;let top2=this.trees[last2],index2=this.index[last2];if(index2==top2.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let next=top2.children[index2],start=this.start[last2]+top2.positions[index2];if(start>pos)return this.nextStart=start,null;if(next instanceof Tree){if(start==pos){if(start<this.safeFrom)return null;let end=start+next.length;if(end<=this.safeTo){let lookAhead=next.prop(NodeProp.lookAhead);if(!lookAhead||end+lookAhead<this.fragment.to)return next}}this.index[last2]++,start+next.length>=Math.max(this.safeFrom,pos)&&(this.trees.push(next),this.start.push(start),this.index.push(0))}else this.index[last2]++,this.nextStart=start+next.length}}};__name2(_FragmentCursor,"FragmentCursor");let FragmentCursor=_FragmentCursor;const _TokenCache=class{static{__name(this,"_TokenCache")}constructor(parser2,stream){this.stream=stream,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=parser2.tokenizers.map(_=>new CachedToken)}getActions(stack){let actionIndex=0,main=null,{parser:parser2}=stack.p,{tokenizers}=parser2,mask=parser2.stateSlot(stack.state,3),context=stack.curContext?stack.curContext.hash:0,lookAhead=0;for(let i=0;i<tokenizers.length;i++){if(!(1<<i&mask))continue;let tokenizer=tokenizers[i],token=this.tokens[i];if(!(main&&!tokenizer.fallback)&&((tokenizer.contextual||token.start!=stack.pos||token.mask!=mask||token.context!=context)&&(this.updateCachedToken(token,tokenizer,stack),token.mask=mask,token.context=context),token.lookAhead>token.end+25&&(lookAhead=Math.max(token.lookAhead,lookAhead)),token.value!=0)){let startIndex=actionIndex;if(token.extended>-1&&(actionIndex=this.addActions(stack,token.extended,token.end,actionIndex)),actionIndex=this.addActions(stack,token.value,token.end,actionIndex),!tokenizer.extend&&(main=token,actionIndex>startIndex))break}}for(;this.actions.length>actionIndex;)this.actions.pop();return lookAhead&&stack.setLookAhead(lookAhead),!main&&stack.pos==this.stream.end&&(main=new CachedToken,main.value=stack.p.parser.eofTerm,main.start=main.end=stack.pos,actionIndex=this.addActions(stack,main.value,main.end,actionIndex)),this.mainToken=main,this.actions}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken,{pos,p}=stack;return main.start=pos,main.end=Math.min(pos+1,p.stream.end),main.value=pos==p.stream.end?p.parser.eofTerm:0,main}updateCachedToken(token,tokenizer,stack){let start=this.stream.clipPos(stack.pos);if(tokenizer.token(this.stream.reset(start,token),stack),token.value>-1){let{parser:parser2}=stack.p;for(let i=0;i<parser2.specialized.length;i++)if(parser2.specialized[i]==token.value){let result=parser2.specializers[i](this.stream.read(token.start,token.end),stack);if(result>=0&&stack.p.parser.dialect.allows(result>>1)){result&1?token.extended=result>>1:token.value=result>>1;break}}}else token.value=0,token.end=this.stream.clipPos(start+1)}putAction(action,token,end,index2){for(let i=0;i<index2;i+=3)if(this.actions[i]==action)return index2;return this.actions[index2++]=action,this.actions[index2++]=token,this.actions[index2++]=end,index2}addActions(stack,token,end,index2){let{state}=stack,{parser:parser2}=stack.p,{data}=parser2;for(let set=0;set<2;set++)for(let i=parser2.stateSlot(state,set?2:1);;i+=3){if(data[i]==65535)if(data[i+1]==1)i=pair(data,i+2);else{index2==0&&data[i+1]==2&&(index2=this.putAction(pair(data,i+2),token,end,index2));break}data[i]==token&&(index2=this.putAction(pair(data,i+1),token,end,index2))}return index2}};__name2(_TokenCache,"TokenCache");let TokenCache=_TokenCache;var Rec;(function(Rec2){Rec2[Rec2.Distance=5]="Distance",Rec2[Rec2.MaxRemainingPerStep=3]="MaxRemainingPerStep",Rec2[Rec2.MinBufferLengthPrune=500]="MinBufferLengthPrune",Rec2[Rec2.ForceReduceLimit=10]="ForceReduceLimit",Rec2[Rec2.CutDepth=15e3]="CutDepth",Rec2[Rec2.CutTo=9e3]="CutTo",Rec2[Rec2.MaxLeftAssociativeReductionCount=300]="MaxLeftAssociativeReductionCount",Rec2[Rec2.MaxStackCount=12]="MaxStackCount"})(Rec||(Rec={}));const _Parse=class{static{__name(this,"_Parse")}constructor(parser2,input,fragments,ranges){this.parser=parser2,this.input=input,this.ranges=ranges,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new InputStream(input,ranges),this.tokens=new TokenCache(parser2,this.stream),this.topTerm=parser2.top[1];let{from}=ranges[0];this.stacks=[Stack.start(this,parser2.top[0],from)],this.fragments=fragments.length&&this.stream.end-from>parser2.bufferLength*4?new FragmentCursor(fragments,parser2.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let stacks=this.stacks,pos=this.minStackPos,newStacks=this.stacks=[],stopped,stoppedTokens;if(this.bigReductionCount>300&&stacks.length==1){let[s2]=stacks;for(;s2.forceReduce()&&s2.stack.length&&s2.stack[s2.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let i=0;i<stacks.length;i++){let stack=stacks[i];for(;;){if(this.tokens.mainToken=null,stack.pos>pos)newStacks.push(stack);else{if(this.advanceStack(stack,newStacks,stacks))continue;{stopped||(stopped=[],stoppedTokens=[]),stopped.push(stack);let tok=this.tokens.getMainToken(stack);stoppedTokens.push(tok.value,tok.end)}}break}}if(!newStacks.length){let finished=stopped&&findFinished(stopped);if(finished)return this.stackToTree(finished);if(this.parser.strict)throw verbose&&stopped&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+pos);this.recovering||(this.recovering=5)}if(this.recovering&&stopped){let finished=this.stoppedAt!=null&&stopped[0].pos>this.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll())}if(this.recovering){let maxRemaining=this.recovering==1?1:this.recovering*3;if(newStacks.length>maxRemaining)for(newStacks.sort((a,b)=>b.score-a.score);newStacks.length>maxRemaining;)newStacks.pop();newStacks.some(s2=>s2.reducePos>pos)&&this.recovering--}else if(newStacks.length>1){outer:for(let i=0;i<newStacks.length-1;i++){let stack=newStacks[i];for(let j=i+1;j<newStacks.length;j++){let other=newStacks[j];if(stack.sameState(other)||stack.buffer.length>500&&other.buffer.length>500)if((stack.score-other.score||stack.buffer.length-other.buffer.length)>0)newStacks.splice(j--,1);else{newStacks.splice(i--,1);continue outer}}}newStacks.length>12&&newStacks.splice(12,newStacks.length-12)}this.minStackPos=newStacks[0].pos;for(let i=1;i<newStacks.length;i++)newStacks[i].pos<this.minStackPos&&(this.minStackPos=newStacks[i].pos);return null}stopAt(pos){if(this.stoppedAt!=null&&this.stoppedAt<pos)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=pos}advanceStack(stack,stacks,split){let start=stack.pos,{parser:parser2}=this,base2=verbose?this.stackID(stack)+" -> ":"";if(this.stoppedAt!=null&&start>this.stoppedAt)return stack.forceReduce()?stack:null;if(this.fragments){let strictCx=stack.curContext&&stack.curContext.tracker.strict,cxHash=strictCx?stack.curContext.hash:0;for(let cached=this.fragments.nodeAt(start);cached;){let match2=this.parser.nodeSet.types[cached.type.id]==cached.type?parser2.getGoto(stack.state,cached.type.id):-1;if(match2>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash))return stack.useNode(cached,match2),verbose&&console.log(base2+this.stackID(stack)+` (via reuse of ${parser2.getName(cached.type.id)})`),!0;if(!(cached instanceof Tree)||cached.children.length==0||cached.positions[0]>0)break;let inner=cached.children[0];if(inner instanceof Tree&&cached.positions[0]==0)cached=inner;else break}}let defaultReduce=parser2.stateSlot(stack.state,4);if(defaultReduce>0)return stack.reduce(defaultReduce),verbose&&console.log(base2+this.stackID(stack)+` (via always-reduce ${parser2.getName(defaultReduce&65535)})`),!0;if(stack.stack.length>=15e3)for(;stack.stack.length>9e3&&stack.forceReduce(););let actions=this.tokens.getActions(stack);for(let i=0;i<actions.length;){let action=actions[i++],term=actions[i++],end=actions[i++],last2=i==actions.length||!split,localStack=last2?stack:stack.split();if(localStack.apply(action,term,end),verbose&&console.log(base2+this.stackID(localStack)+` (via ${action&65536?`reduce of ${parser2.getName(action&65535)}`:"shift"} for ${parser2.getName(term)} @ ${start}${localStack==stack?"":", split"})`),last2)return!0;localStack.pos>start?stacks.push(localStack):split.push(localStack)}return!1}advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return!1;if(stack.pos>pos)return pushStackDedup(stack,newStacks),!0}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=!1;for(let i=0;i<stacks.length;i++){let stack=stacks[i],token=tokens[i<<1],tokenEnd=tokens[(i<<1)+1],base2=verbose?this.stackID(stack)+" -> ":"";if(stack.deadEnd&&(restarted||(restarted=!0,stack.restart(),verbose&&console.log(base2+this.stackID(stack)+" (restarted)"),this.advanceFully(stack,newStacks))))continue;let force=stack.split(),forceBase=base2;for(let j=0;force.forceReduce()&&j<10&&(verbose&&console.log(forceBase+this.stackID(force)+" (via force-reduce)"),!this.advanceFully(force,newStacks));j++)verbose&&(forceBase=this.stackID(force)+" -> ");for(let insert2 of stack.recoverByInsert(token))verbose&&console.log(base2+this.stackID(insert2)+" (via recover-insert)"),this.advanceFully(insert2,newStacks);this.stream.end>stack.pos?(tokenEnd==stack.pos&&(tokenEnd++,token=0),stack.recoverByDelete(token,tokenEnd),verbose&&console.log(base2+this.stackID(stack)+` (via recover-delete ${this.parser.getName(token)})`),pushStackDedup(stack,newStacks)):(!finished||finished.score<stack.score)&&(finished=stack)}return finished}stackToTree(stack){return stack.close(),Tree.build({buffer:StackBufferCursor.create(stack),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:stack.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(stack){let id=(stackIDs||(stackIDs=new WeakMap)).get(stack);return id||stackIDs.set(stack,id=String.fromCodePoint(this.nextStackID++)),id+stack}};__name2(_Parse,"Parse");let Parse=_Parse;function pushStackDedup(stack,newStacks){for(let i=0;i<newStacks.length;i++){let other=newStacks[i];if(other.pos==stack.pos&&other.sameState(stack)){newStacks[i].score<stack.score&&(newStacks[i]=stack);return}}newStacks.push(stack)}__name(pushStackDedup,"pushStackDedup"),__name2(pushStackDedup,"pushStackDedup");const _Dialect=class{static{__name(this,"_Dialect")}constructor(source,flags,disabled){this.source=source,this.flags=flags,this.disabled=disabled}allows(term){return!this.disabled||this.disabled[term]==0}};__name2(_Dialect,"Dialect");let Dialect=_Dialect;const _LRParser=class _LRParser2 extends Parser{static{__name(this,"_LRParser")}constructor(spec){if(super(),this.wrappers=[],spec.version!=14)throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (14)`);let nodeNames=spec.nodeNames.split(" ");this.minRepeatTerm=nodeNames.length;for(let i=0;i<spec.repeatNodeCount;i++)nodeNames.push("");let topTerms=Object.keys(spec.topRules).map(r=>spec.topRules[r][1]),nodeProps=[];for(let i=0;i<nodeNames.length;i++)nodeProps.push([]);function setProp(nodeID,prop,value){nodeProps[nodeID].push([prop,prop.deserialize(String(value))])}if(__name(setProp,"setProp"),__name2(setProp,"setProp"),spec.nodeProps)for(let propSpec of spec.nodeProps){let prop=propSpec[0];typeof prop=="string"&&(prop=NodeProp[prop]);for(let i=1;i<propSpec.length;){let next=propSpec[i++];if(next>=0)setProp(next,prop,propSpec[i++]);else{let value=propSpec[i+-next];for(let j=-next;j>0;j--)setProp(propSpec[i++],prop,value);i++}}}this.nodeSet=new NodeSet(nodeNames.map((name2,i)=>NodeType.define({name:i>=this.minRepeatTerm?void 0:name2,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:i==0,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1}))),spec.propSources&&(this.nodeSet=this.nodeSet.extend(...spec.propSources)),this.strict=!1,this.bufferLength=DefaultBufferLength;let tokenArray=decodeArray(spec.tokenData);this.context=spec.context,this.specializerSpecs=spec.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let i=0;i<this.specializerSpecs.length;i++)this.specialized[i]=this.specializerSpecs[i].term;this.specializers=this.specializerSpecs.map(getSpecializer),this.states=decodeArray(spec.states,Uint32Array),this.data=decodeArray(spec.stateData),this.goto=decodeArray(spec.goto),this.maxTerm=spec.maxTerm,this.tokenizers=spec.tokenizers.map(value=>typeof value=="number"?new TokenGroup(tokenArray,value):value),this.topRules=spec.topRules,this.dialects=spec.dialects||{},this.dynamicPrecedences=spec.dynamicPrecedences||null,this.tokenPrecTable=spec.tokenPrec,this.termNames=spec.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(input,fragments,ranges){let parse2=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse2=w(parse2,input,fragments,ranges);return parse2}getGoto(state,term,loose=!1){let table=this.goto;if(term>=table[0])return-1;for(let pos=table[term+1];;){let groupTag=table[pos++],last2=groupTag&1,target=table[pos++];if(last2&&loose)return target;for(let end=pos+(groupTag>>1);pos<end;pos++)if(table[pos]==state)return target;if(last2)return-1}}hasAction(state,terminal){let data=this.data;for(let set=0;set<2;set++)for(let i=this.stateSlot(state,set?2:1),next;;i+=3){if((next=data[i])==65535)if(data[i+1]==1)next=data[i=pair(data,i+2)];else{if(data[i+1]==2)return pair(data,i+2);break}if(next==terminal||next==0)return pair(data,i+1)}return 0}stateSlot(state,slot){return this.states[state*6+slot]}stateFlag(state,flag){return(this.stateSlot(state,0)&flag)>0}validAction(state,action){return!!this.allActions(state,a=>a==action?!0:null)}allActions(state,action){let deflt=this.stateSlot(state,4),result=deflt?action(deflt):void 0;for(let i=this.stateSlot(state,1);result==null;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=pair(this.data,i+2);else break;result=action(pair(this.data,i+1))}return result}nextStates(state){let result=[];for(let i=this.stateSlot(state,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=pair(this.data,i+2);else break;if(!(this.data[i+2]&1)){let value=this.data[i+1];result.some((v,i2)=>i2&1&&v==value)||result.push(this.data[i],value)}}return result}configure(config2){let copy=Object.assign(Object.create(_LRParser2.prototype),this);if(config2.props&&(copy.nodeSet=this.nodeSet.extend(...config2.props)),config2.top){let info=this.topRules[config2.top];if(!info)throw new RangeError(`Invalid top rule name ${config2.top}`);copy.top=info}return config2.tokenizers&&(copy.tokenizers=this.tokenizers.map(t2=>{let found=config2.tokenizers.find(r=>r.from==t2);return found?found.to:t2})),config2.specializers&&(copy.specializers=this.specializers.slice(),copy.specializerSpecs=this.specializerSpecs.map((s2,i)=>{let found=config2.specializers.find(r=>r.from==s2.external);if(!found)return s2;let spec=Object.assign(Object.assign({},s2),{external:found.to});return copy.specializers[i]=getSpecializer(spec),spec})),config2.contextTracker&&(copy.context=config2.contextTracker),config2.dialect&&(copy.dialect=this.parseDialect(config2.dialect)),config2.strict!=null&&(copy.strict=config2.strict),config2.wrap&&(copy.wrappers=copy.wrappers.concat(config2.wrap)),config2.bufferLength!=null&&(copy.bufferLength=config2.bufferLength),copy}hasWrappers(){return this.wrappers.length>0}getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(term){let prec2=this.dynamicPrecedences;return prec2==null?0:prec2[term]||0}parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map(()=>!1);if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);id>=0&&(flags[id]=!0)}let disabled=null;for(let i=0;i<values.length;i++)if(!flags[i])for(let j=this.dialects[values[i]],id;(id=this.data[j++])!=65535;)(disabled||(disabled=new Uint8Array(this.maxTerm+1)))[id]=1;return new Dialect(dialect,flags,disabled)}static deserialize(spec){return new _LRParser2(spec)}};__name2(_LRParser,"LRParser");let LRParser=_LRParser;function pair(data,off2){return data[off2]|data[off2+1]<<16}__name(pair,"pair"),__name2(pair,"pair");function findFinished(stacks){let best=null;for(let stack of stacks){let stopped=stack.p.stoppedAt;(stack.pos==stack.p.stream.end||stopped!=null&&stack.pos>stopped)&&stack.p.parser.stateFlag(stack.state,2)&&(!best||best.score<stack.score)&&(best=stack)}return best}__name(findFinished,"findFinished"),__name2(findFinished,"findFinished");function getSpecializer(spec){if(spec.external){let mask=spec.extend?1:0;return(value,stack)=>spec.external(value,stack)<<1|mask}return spec.get}__name(getSpecializer,"getSpecializer"),__name2(getSpecializer,"getSpecializer");const jsonHighlighting=styleTags({String:tags.string,Number:tags.number,"True False":tags.bool,PropertyName:tags.propertyName,Null:tags.null,",":tags.separator,"[ ]":tags.squareBracket,"{ }":tags.brace}),parser=LRParser.deserialize({version:14,states:"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#CjOOQO'#Cp'#CpQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CrOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59U,59UO!iQPO,59UOVQPO,59QOqQPO'#CkO!nQPO,59^OOQO1G.k1G.kOVQPO'#ClO!vQPO,59aOOQO1G.p1G.pOOQO1G.l1G.lOOQO,59V,59VOOQO-E6i-E6iOOQO,59W,59WOOQO-E6j-E6j",stateData:"#O~OcOS~OQSORSOSSOTSOWQO]ROePO~OVXOeUO~O[[O~PVOg^O~Oh_OVfX~OVaO~OhbO[iX~O[dO~Oh_OVfa~OhbO[ia~O",goto:"!kjPPPPPPkPPkqwPPk{!RPPP!XP!ePP!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",nodeNames:"\u26A0 JsonText True False Null Number String } { Object Property PropertyName ] [ Array",maxTerm:25,nodeProps:[["openedBy",7,"{",12,"["],["closedBy",8,"}",13,"]"]],propSources:[jsonHighlighting],skippedNodes:[0],repeatNodeCount:2,tokenData:"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oc~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Oe~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zOh~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yOg~~'OO]~~'TO[~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",tokenizers:[0],topRules:{JsonText:[0,1]},tokenPrec:0}),jsonParseLinter=__name2(()=>view=>{try{JSON.parse(view.state.doc.toString())}catch(e){if(!(e instanceof SyntaxError))throw e;const pos=getErrorPosition(e,view.state.doc);return[{from:pos,message:e.message,severity:"error",to:pos}]}return[]},"jsonParseLinter");function getErrorPosition(error,doc2){let m;return(m=error.message.match(/at position (\d+)/))?Math.min(+m[1],doc2.length):(m=error.message.match(/at line (\d+) column (\d+)/))?Math.min(doc2.line(+m[1]).from+ +m[2]-1,doc2.length):0}__name(getErrorPosition,"getErrorPosition"),__name2(getErrorPosition,"getErrorPosition");const jsonLanguage=LRLanguage.define({name:"json",parser:parser.configure({props:[indentNodeProp.add({Object:continuedIndent({except:/^\s*\}/}),Array:continuedIndent({except:/^\s*\]/})}),foldNodeProp.add({"Object Array":foldInside})]}),languageData:{closeBrackets:{brackets:["[","{",'"']},indentOnInput:/^\s*[\}\]]$/}});function json(){return new LanguageSupport(jsonLanguage)}__name(json,"json"),__name2(json,"json");function crelt(){var elt=arguments[0];typeof elt=="string"&&(elt=document.createElement(elt));var i=1,next=arguments[1];if(next&&typeof next=="object"&&next.nodeType==null&&!Array.isArray(next)){for(var name2 in next)if(Object.prototype.hasOwnProperty.call(next,name2)){var value=next[name2];typeof value=="string"?elt.setAttribute(name2,value):value!=null&&(elt[name2]=value)}i++}for(;i<arguments.length;i++)add(elt,arguments[i]);return elt}__name(crelt,"crelt"),__name2(crelt,"crelt");function add(elt,child){if(typeof child=="string")elt.appendChild(document.createTextNode(child));else if(child!=null)if(child.nodeType!=null)elt.appendChild(child);else if(Array.isArray(child))for(var i=0;i<child.length;i++)add(elt,child[i]);else throw new RangeError("Unsupported child node: "+child)}__name(add,"add"),__name2(add,"add");const _SelectedDiagnostic=class{static{__name(this,"_SelectedDiagnostic")}constructor(from,to,diagnostic){this.from=from,this.to=to,this.diagnostic=diagnostic}};__name2(_SelectedDiagnostic,"SelectedDiagnostic");let SelectedDiagnostic=_SelectedDiagnostic;const _LintState=class _LintState2{static{__name(this,"_LintState")}constructor(diagnostics,panel,selected){this.diagnostics=diagnostics,this.panel=panel,this.selected=selected}static init(diagnostics,panel,state){let markedDiagnostics=diagnostics,diagnosticFilter=state.facet(lintConfig).markerFilter;diagnosticFilter&&(markedDiagnostics=diagnosticFilter(markedDiagnostics));let ranges=Decoration.set(markedDiagnostics.map(d=>d.from==d.to||d.from==d.to-1&&state.doc.lineAt(d.from).to==d.from?Decoration.widget({widget:new DiagnosticWidget(d),diagnostic:d}).range(d.from):Decoration.mark({attributes:{class:"cm-lintRange cm-lintRange-"+d.severity+(d.markClass?" "+d.markClass:"")},diagnostic:d}).range(d.from,d.to)),!0);return new _LintState2(ranges,panel,findDiagnostic(ranges))}};__name2(_LintState,"LintState");let LintState=_LintState;function findDiagnostic(diagnostics,diagnostic=null,after=0){let found=null;return diagnostics.between(after,1e9,(from,to,{spec})=>{if(!(diagnostic&&spec.diagnostic!=diagnostic))return found=new SelectedDiagnostic(from,to,spec.diagnostic),!1}),found}__name(findDiagnostic,"findDiagnostic"),__name2(findDiagnostic,"findDiagnostic");function hideTooltip(tr,tooltip){let line=tr.startState.doc.lineAt(tooltip.pos);return!!(tr.effects.some(e=>e.is(setDiagnosticsEffect))||tr.changes.touchesRange(line.from,line.to))}__name(hideTooltip,"hideTooltip"),__name2(hideTooltip,"hideTooltip");function maybeEnableLint(state,effects){return state.field(lintState,!1)?effects:effects.concat(StateEffect.appendConfig.of(lintExtensions))}__name(maybeEnableLint,"maybeEnableLint"),__name2(maybeEnableLint,"maybeEnableLint");function setDiagnostics(state,diagnostics){return{effects:maybeEnableLint(state,[setDiagnosticsEffect.of(diagnostics)])}}__name(setDiagnostics,"setDiagnostics"),__name2(setDiagnostics,"setDiagnostics");const setDiagnosticsEffect=StateEffect.define(),togglePanel$1=StateEffect.define(),movePanelSelection=StateEffect.define(),lintState=StateField.define({create(){return new LintState(Decoration.none,null,null)},update(value,tr){if(tr.docChanged){let mapped=value.diagnostics.map(tr.changes),selected=null;if(value.selected){let selPos=tr.changes.mapPos(value.selected.from,1);selected=findDiagnostic(mapped,value.selected.diagnostic,selPos)||findDiagnostic(mapped,null,selPos)}value=new LintState(mapped,value.panel,selected)}for(let effect of tr.effects)effect.is(setDiagnosticsEffect)?value=LintState.init(effect.value,value.panel,tr.state):effect.is(togglePanel$1)?value=new LintState(value.diagnostics,effect.value?LintPanel.open:null,value.selected):effect.is(movePanelSelection)&&(value=new LintState(value.diagnostics,value.panel,effect.value));return value},provide:f2=>[showPanel.from(f2,val=>val.panel),EditorView.decorations.from(f2,s2=>s2.diagnostics)]}),activeMark=Decoration.mark({class:"cm-lintRange cm-lintRange-active"});function lintTooltip(view,pos,side){let{diagnostics}=view.state.field(lintState),found=[],stackStart=2e8,stackEnd=0;diagnostics.between(pos-(side<0?1:0),pos+(side>0?1:0),(from,to,{spec})=>{pos>=from&&pos<=to&&(from==to||(pos>from||side>0)&&(pos<to||side<0))&&(found.push(spec.diagnostic),stackStart=Math.min(from,stackStart),stackEnd=Math.max(to,stackEnd))});let diagnosticFilter=view.state.facet(lintConfig).tooltipFilter;return diagnosticFilter&&(found=diagnosticFilter(found)),found.length?{pos:stackStart,end:stackEnd,above:view.state.doc.lineAt(stackStart).to<stackEnd,create(){return{dom:diagnosticsTooltip(view,found)}}}:null}__name(lintTooltip,"lintTooltip"),__name2(lintTooltip,"lintTooltip");function diagnosticsTooltip(view,diagnostics){return crelt("ul",{class:"cm-tooltip-lint"},diagnostics.map(d=>renderDiagnostic(view,d,!1)))}__name(diagnosticsTooltip,"diagnosticsTooltip"),__name2(diagnosticsTooltip,"diagnosticsTooltip");const openLintPanel=__name2(view=>{let field=view.state.field(lintState,!1);(!field||!field.panel)&&view.dispatch({effects:maybeEnableLint(view.state,[togglePanel$1.of(!0)])});let panel=getPanel(view,LintPanel.open);return panel&&panel.dom.querySelector(".cm-panel-lint ul").focus(),!0},"openLintPanel"),closeLintPanel=__name2(view=>{let field=view.state.field(lintState,!1);return!field||!field.panel?!1:(view.dispatch({effects:togglePanel$1.of(!1)}),!0)},"closeLintPanel"),nextDiagnostic=__name2(view=>{let field=view.state.field(lintState,!1);if(!field)return!1;let sel=view.state.selection.main,next=field.diagnostics.iter(sel.to+1);return!next.value&&(next=field.diagnostics.iter(0),!next.value||next.from==sel.from&&next.to==sel.to)?!1:(view.dispatch({selection:{anchor:next.from,head:next.to},scrollIntoView:!0}),!0)},"nextDiagnostic"),lintKeymap=[{key:"Mod-Shift-m",run:openLintPanel,preventDefault:!0},{key:"F8",run:nextDiagnostic}],lintPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.timeout=-1,this.set=!0;let{delay}=view.state.facet(lintConfig);this.lintTime=Date.now()+delay,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,delay)}run(){let now2=Date.now();if(now2<this.lintTime-10)setTimeout(this.run,this.lintTime-now2);else{this.set=!1;let{state}=this.view,{sources}=state.facet(lintConfig);Promise.all(sources.map(source=>Promise.resolve(source(this.view)))).then(annotations=>{let all=annotations.reduce((a,b)=>a.concat(b));this.view.state.doc==state.doc&&this.view.dispatch(setDiagnostics(this.view.state,all))},error=>{logException(this.view.state,error)})}}update(update){let config2=update.state.facet(lintConfig);(update.docChanged||config2!=update.startState.facet(lintConfig)||config2.needsRefresh&&config2.needsRefresh(update))&&(this.lintTime=Date.now()+config2.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,config2.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}}),lintConfig=Facet.define({combine(input){return Object.assign({sources:input.map(i=>i.source)},combineConfig(input.map(i=>i.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null},{needsRefresh:(a,b)=>a?b?u=>a(u)||b(u):a:b}))}});function linter(source,config2={}){return[lintConfig.of({source,config:config2}),lintPlugin,lintExtensions]}__name(linter,"linter"),__name2(linter,"linter");function assignKeys(actions){let assigned=[];if(actions)actions:for(let{name:name2}of actions){for(let i=0;i<name2.length;i++){let ch=name2[i];if(/[a-zA-Z]/.test(ch)&&!assigned.some(c=>c.toLowerCase()==ch.toLowerCase())){assigned.push(ch);continue actions}}assigned.push("")}return assigned}__name(assignKeys,"assignKeys"),__name2(assignKeys,"assignKeys");function renderDiagnostic(view,diagnostic,inPanel){var _a3;let keys2=inPanel?assignKeys(diagnostic.actions):[];return crelt("li",{class:"cm-diagnostic cm-diagnostic-"+diagnostic.severity},crelt("span",{class:"cm-diagnosticText"},diagnostic.renderMessage?diagnostic.renderMessage():diagnostic.message),(_a3=diagnostic.actions)===null||_a3===void 0?void 0:_a3.map((action,i)=>{let fired=!1,click=__name2(e=>{if(e.preventDefault(),fired)return;fired=!0;let found=findDiagnostic(view.state.field(lintState).diagnostics,diagnostic);found&&action.apply(view,found.from,found.to)},"click"),{name:name2}=action,keyIndex=keys2[i]?name2.indexOf(keys2[i]):-1,nameElt=keyIndex<0?name2:[name2.slice(0,keyIndex),crelt("u",name2.slice(keyIndex,keyIndex+1)),name2.slice(keyIndex+1)];return crelt("button",{type:"button",class:"cm-diagnosticAction",onclick:click,onmousedown:click,"aria-label":` Action: ${name2}${keyIndex<0?"":` (access key "${keys2[i]})"`}.`},nameElt)}),diagnostic.source&&crelt("div",{class:"cm-diagnosticSource"},diagnostic.source))}__name(renderDiagnostic,"renderDiagnostic"),__name2(renderDiagnostic,"renderDiagnostic");const _DiagnosticWidget=class extends WidgetType{static{__name(this,"_DiagnosticWidget")}constructor(diagnostic){super(),this.diagnostic=diagnostic}eq(other){return other.diagnostic==this.diagnostic}toDOM(){return crelt("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}};__name2(_DiagnosticWidget,"DiagnosticWidget");let DiagnosticWidget=_DiagnosticWidget;const _PanelItem=class{static{__name(this,"_PanelItem")}constructor(view,diagnostic){this.diagnostic=diagnostic,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=renderDiagnostic(view,diagnostic,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}};__name2(_PanelItem,"PanelItem");let PanelItem=_PanelItem;const _LintPanel=class _LintPanel2{static{__name(this,"_LintPanel")}constructor(view){this.view=view,this.items=[];let onkeydown=__name2(event=>{if(event.keyCode==27)closeLintPanel(this.view),this.view.focus();else if(event.keyCode==38||event.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(event.keyCode==40||event.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(event.keyCode==36)this.moveSelection(0);else if(event.keyCode==35)this.moveSelection(this.items.length-1);else if(event.keyCode==13)this.view.focus();else if(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0){let{diagnostic}=this.items[this.selectedIndex],keys2=assignKeys(diagnostic.actions);for(let i=0;i<keys2.length;i++)if(keys2[i].toUpperCase().charCodeAt(0)==event.keyCode){let found=findDiagnostic(this.view.state.field(lintState).diagnostics,diagnostic);found&&diagnostic.actions[i].apply(view,found.from,found.to)}}else return;event.preventDefault()},"onkeydown"),onclick=__name2(event=>{for(let i=0;i<this.items.length;i++)this.items[i].dom.contains(event.target)&&this.moveSelection(i)},"onclick");this.list=crelt("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown,onclick}),this.dom=crelt("div",{class:"cm-panel-lint"},this.list,crelt("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>closeLintPanel(this.view)},"\xD7")),this.update()}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return-1;for(let i=0;i<this.items.length;i++)if(this.items[i].diagnostic==selected.diagnostic)return i;return-1}update(){let{diagnostics,selected}=this.view.state.field(lintState),i=0,needsSync=!1,newSelectedItem=null;for(diagnostics.between(0,this.view.state.doc.length,(_start,_end,{spec})=>{let found=-1,item;for(let j=i;j<this.items.length;j++)if(this.items[j].diagnostic==spec.diagnostic){found=j;break}found<0?(item=new PanelItem(this.view,spec.diagnostic),this.items.splice(i,0,item),needsSync=!0):(item=this.items[found],found>i&&(this.items.splice(i,found-i),needsSync=!0)),selected&&item.diagnostic==selected.diagnostic?item.dom.hasAttribute("aria-selected")||(item.dom.setAttribute("aria-selected","true"),newSelectedItem=item):item.dom.hasAttribute("aria-selected")&&item.dom.removeAttribute("aria-selected"),i++});i<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)needsSync=!0,this.items.pop();this.items.length==0&&(this.items.push(new PanelItem(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),needsSync=!0),newSelectedItem?(this.list.setAttribute("aria-activedescendant",newSelectedItem.id),this.view.requestMeasure({key:this,read:()=>({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel,panel})=>{sel.top<panel.top?this.list.scrollTop-=panel.top-sel.top:sel.bottom>panel.bottom&&(this.list.scrollTop+=sel.bottom-panel.bottom)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),needsSync&&this.sync()}sync(){let domPos=this.list.firstChild;function rm2(){let prev=domPos;domPos=prev.nextSibling,prev.remove()}__name(rm2,"rm2"),__name2(rm2,"rm");for(let item of this.items)if(item.dom.parentNode==this.list){for(;domPos!=item.dom;)rm2();domPos=item.dom.nextSibling}else this.list.insertBefore(item.dom,domPos);for(;domPos;)rm2()}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let field=this.view.state.field(lintState),selection=findDiagnostic(field.diagnostics,this.items[selectedIndex].diagnostic);selection&&this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:!0,effects:movePanelSelection.of(selection)})}static open(view){return new _LintPanel2(view)}};__name2(_LintPanel,"LintPanel");let LintPanel=_LintPanel;function svg(content2,attrs='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content2)}</svg>')`}__name(svg,"svg"),__name2(svg,"svg");function underline(color){return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}__name(underline,"underline"),__name2(underline,"underline");const baseTheme$2=EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:underline("#d11")},".cm-lintRange-warning":{backgroundImage:underline("orange")},".cm-lintRange-info":{backgroundImage:underline("#999")},".cm-lintRange-hint":{backgroundImage:underline("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),lintExtensions=[lintState,EditorView.decorations.compute([lintState],state=>{let{selected,panel}=state.field(lintState);return!selected||!panel||selected.from==selected.to?Decoration.none:Decoration.set([activeMark.range(selected.from,selected.to)])}),hoverTooltip(lintTooltip,{hideOn:hideTooltip}),baseTheme$2],basicNormalize=typeof String.prototype.normalize=="function"?x=>x.normalize("NFKD"):x=>x,_SearchCursor=class{static{__name(this,"_SearchCursor")}constructor(text,query,from=0,to=text.length,normalize,test){this.test=test,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=text.iterRange(from,to),this.bufferStart=from,this.normalize=normalize?x=>normalize(basicNormalize(x)):basicNormalize,this.query=this.normalize(query)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return codePointAt(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let next=this.peek();if(next<0)return this.done=!0,this;let str=fromCodePoint(next),start=this.bufferStart+this.bufferPos;this.bufferPos+=codePointSize(next);let norm=this.normalize(str);for(let i=0,pos=start;;i++){let code=norm.charCodeAt(i),match2=this.match(code,pos);if(i==norm.length-1){if(match2)return this.value=match2,this;break}pos==start&&i<str.length&&str.charCodeAt(i)==code&&pos++}}}match(code,pos){let match2=null;for(let i=0;i<this.matches.length;i+=2){let index2=this.matches[i],keep=!1;this.query.charCodeAt(index2)==code&&(index2==this.query.length-1?match2={from:this.matches[i+1],to:pos+1}:(this.matches[i]++,keep=!0)),keep||(this.matches.splice(i,2),i-=2)}return this.query.charCodeAt(0)==code&&(this.query.length==1?match2={from:pos,to:pos+1}:this.matches.push(1,pos)),match2&&this.test&&!this.test(match2.from,match2.to,this.buffer,this.bufferPos)&&(match2=null),match2}};__name2(_SearchCursor,"SearchCursor");let SearchCursor=_SearchCursor;typeof Symbol<"u"&&(SearchCursor.prototype[Symbol.iterator]=function(){return this});const empty={from:-1,to:-1,match:/.*/.exec("")},baseFlags="gm"+(/x/.unicode==null?"":"u"),_RegExpCursor=class{static{__name(this,"_RegExpCursor")}constructor(text,query,options,from=0,to=text.length){if(this.text=text,this.to=to,this.curLine="",this.done=!1,this.value=empty,/\\[sWDnr]|\n|\r|\[\^/.test(query))return new MultilineRegExpCursor(text,query,options,from,to);this.re=new RegExp(query,baseFlags+(options?.ignoreCase?"i":"")),this.test=options?.test,this.iter=text.iter();let startLine=text.lineAt(from);this.curLineStart=startLine.from,this.matchPos=toCharEnd(text,from),this.getLine(this.curLineStart)}getLine(skip){this.iter.next(skip),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let off2=this.matchPos-this.curLineStart;;){this.re.lastIndex=off2;let match2=this.matchPos<=this.to&&this.re.exec(this.curLine);if(match2){let from=this.curLineStart+match2.index,to=from+match2[0].length;if(this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),from==this.curLineStart+this.curLine.length&&this.nextLine(),(from<to||from>this.value.to)&&(!this.test||this.test(from,to,match2)))return this.value={from,to,match:match2},this;off2=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),off2=0;else return this.done=!0,this}}};__name2(_RegExpCursor,"RegExpCursor");let RegExpCursor=_RegExpCursor;const flattened=new WeakMap,_FlattenedDoc=class _FlattenedDoc2{static{__name(this,"_FlattenedDoc")}constructor(from,text){this.from=from,this.text=text}get to(){return this.from+this.text.length}static get(doc2,from,to){let cached=flattened.get(doc2);if(!cached||cached.from>=to||cached.to<=from){let flat=new _FlattenedDoc2(from,doc2.sliceString(from,to));return flattened.set(doc2,flat),flat}if(cached.from==from&&cached.to==to)return cached;let{text,from:cachedFrom}=cached;return cachedFrom>from&&(text=doc2.sliceString(from,cachedFrom)+text,cachedFrom=from),cached.to<to&&(text+=doc2.sliceString(cached.to,to)),flattened.set(doc2,new _FlattenedDoc2(cachedFrom,text)),new _FlattenedDoc2(from,text.slice(from-cachedFrom,to-cachedFrom))}};__name2(_FlattenedDoc,"FlattenedDoc");let FlattenedDoc=_FlattenedDoc;const _MultilineRegExpCursor=class{static{__name(this,"_MultilineRegExpCursor")}constructor(text,query,options,from,to){this.text=text,this.to=to,this.done=!1,this.value=empty,this.matchPos=toCharEnd(text,from),this.re=new RegExp(query,baseFlags+(options?.ignoreCase?"i":"")),this.test=options?.test,this.flat=FlattenedDoc.get(text,from,this.chunkEnd(from+5e3))}chunkEnd(pos){return pos>=this.to?this.to:this.text.lineAt(pos).to}next(){for(;;){let off2=this.re.lastIndex=this.matchPos-this.flat.from,match2=this.re.exec(this.flat.text);if(match2&&!match2[0]&&match2.index==off2&&(this.re.lastIndex=off2+1,match2=this.re.exec(this.flat.text)),match2){let from=this.flat.from+match2.index,to=from+match2[0].length;if((this.flat.to>=this.to||match2.index+match2[0].length<=this.flat.text.length-10)&&(!this.test||this.test(from,to,match2)))return this.value={from,to,match:match2},this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=FlattenedDoc.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};__name2(_MultilineRegExpCursor,"MultilineRegExpCursor");let MultilineRegExpCursor=_MultilineRegExpCursor;typeof Symbol<"u"&&(RegExpCursor.prototype[Symbol.iterator]=MultilineRegExpCursor.prototype[Symbol.iterator]=function(){return this});function validRegExp(source){try{return new RegExp(source,baseFlags),!0}catch{return!1}}__name(validRegExp,"validRegExp"),__name2(validRegExp,"validRegExp");function toCharEnd(text,pos){if(pos>=text.length)return pos;let line=text.lineAt(pos),next;for(;pos<line.to&&(next=line.text.charCodeAt(pos-line.from))>=56320&&next<57344;)pos++;return pos}__name(toCharEnd,"toCharEnd"),__name2(toCharEnd,"toCharEnd");function createLineDialog(view){let input=crelt("input",{class:"cm-textfield",name:"line"}),dom=crelt("form",{class:"cm-gotoLine",onkeydown:event=>{event.keyCode==27?(event.preventDefault(),view.dispatch({effects:dialogEffect.of(!1)}),view.focus()):event.keyCode==13&&(event.preventDefault(),go())},onsubmit:event=>{event.preventDefault(),go()}},crelt("label",view.state.phrase("Go to line"),": ",input)," ",crelt("button",{class:"cm-button",type:"submit"},view.state.phrase("go")));function go(){let match2=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);if(!match2)return;let{state}=view,startLine=state.doc.lineAt(state.selection.main.head),[,sign,ln,cl,percent]=match2,col=cl?+cl.slice(1):0,line=ln?+ln:startLine.number;if(ln&&percent){let pc=line/100;sign&&(pc=pc*(sign=="-"?-1:1)+startLine.number/state.doc.lines),line=Math.round(state.doc.lines*pc)}else ln&&sign&&(line=line*(sign=="-"?-1:1)+startLine.number);let docLine=state.doc.line(Math.max(1,Math.min(state.doc.lines,line))),selection=EditorSelection.cursor(docLine.from+Math.max(0,Math.min(col,docLine.length)));view.dispatch({effects:[dialogEffect.of(!1),EditorView.scrollIntoView(selection.from,{y:"center"})],selection}),view.focus()}return __name(go,"go"),__name2(go,"go"),{dom}}__name(createLineDialog,"createLineDialog"),__name2(createLineDialog,"createLineDialog");const dialogEffect=StateEffect.define(),dialogField=StateField.define({create(){return!0},update(value,tr){for(let e of tr.effects)e.is(dialogEffect)&&(value=e.value);return value},provide:f2=>showPanel.from(f2,val=>val?createLineDialog:null)}),gotoLine=__name2(view=>{let panel=getPanel(view,createLineDialog);if(!panel){let effects=[dialogEffect.of(!0)];view.state.field(dialogField,!1)==null&&effects.push(StateEffect.appendConfig.of([dialogField,baseTheme$1])),view.dispatch({effects}),panel=getPanel(view,createLineDialog)}return panel&&panel.dom.querySelector("input").focus(),!0},"gotoLine"),baseTheme$1=EditorView.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),defaultHighlightOptions={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},highlightConfig=Facet.define({combine(options){return combineConfig(options,defaultHighlightOptions,{highlightWordAroundCursor:(a,b)=>a||b,minSelectionLength:Math.min,maxMatches:Math.min})}});function highlightSelectionMatches(options){let ext=[defaultTheme,matchHighlighter];return options&&ext.push(highlightConfig.of(options)),ext}__name(highlightSelectionMatches,"highlightSelectionMatches"),__name2(highlightSelectionMatches,"highlightSelectionMatches");const matchDeco=Decoration.mark({class:"cm-selectionMatch"}),mainMatchDeco=Decoration.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function insideWordBoundaries(check,state,from,to){return(from==0||check(state.sliceDoc(from-1,from))!=CharCategory.Word)&&(to==state.doc.length||check(state.sliceDoc(to,to+1))!=CharCategory.Word)}__name(insideWordBoundaries,"insideWordBoundaries"),__name2(insideWordBoundaries,"insideWordBoundaries");function insideWord(check,state,from,to){return check(state.sliceDoc(from,from+1))==CharCategory.Word&&check(state.sliceDoc(to-1,to))==CharCategory.Word}__name(insideWord,"insideWord"),__name2(insideWord,"insideWord");const matchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.selectionSet||update.docChanged||update.viewportChanged)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let conf=view.state.facet(highlightConfig),{state}=view,sel=state.selection;if(sel.ranges.length>1)return Decoration.none;let range=sel.main,query,check=null;if(range.empty){if(!conf.highlightWordAroundCursor)return Decoration.none;let word=state.wordAt(range.head);if(!word)return Decoration.none;check=state.charCategorizer(range.head),query=state.sliceDoc(word.from,word.to)}else{let len=range.to-range.from;if(len<conf.minSelectionLength||len>200)return Decoration.none;if(conf.wholeWords){if(query=state.sliceDoc(range.from,range.to),check=state.charCategorizer(range.head),!(insideWordBoundaries(check,state,range.from,range.to)&&insideWord(check,state,range.from,range.to)))return Decoration.none}else if(query=state.sliceDoc(range.from,range.to).trim(),!query)return Decoration.none}let deco=[];for(let part of view.visibleRanges){let cursor=new SearchCursor(state.doc,query,part.from,part.to);for(;!cursor.next().done;){let{from,to}=cursor.value;if((!check||insideWordBoundaries(check,state,from,to))&&(range.empty&&from<=range.from&&to>=range.to?deco.push(mainMatchDeco.range(from,to)):(from>=range.to||to<=range.from)&&deco.push(matchDeco.range(from,to)),deco.length>conf.maxMatches))return Decoration.none}}return Decoration.set(deco)}},{decorations:v=>v.decorations}),defaultTheme=EditorView.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),selectWord=__name2(({state,dispatch})=>{let{selection}=state,newSel=EditorSelection.create(selection.ranges.map(range=>state.wordAt(range.head)||EditorSelection.cursor(range.head)),selection.mainIndex);return newSel.eq(selection)?!1:(dispatch(state.update({selection:newSel})),!0)},"selectWord");function findNextOccurrence(state,query){let{main,ranges}=state.selection,word=state.wordAt(main.head),fullWord=word&&word.from==main.from&&word.to==main.to;for(let cycled=!1,cursor=new SearchCursor(state.doc,query,ranges[ranges.length-1].to);;)if(cursor.next(),cursor.done){if(cycled)return null;cursor=new SearchCursor(state.doc,query,0,Math.max(0,ranges[ranges.length-1].from-1)),cycled=!0}else{if(cycled&&ranges.some(r=>r.from==cursor.value.from))continue;if(fullWord){let word2=state.wordAt(cursor.value.from);if(!word2||word2.from!=cursor.value.from||word2.to!=cursor.value.to)continue}return cursor.value}}__name(findNextOccurrence,"findNextOccurrence"),__name2(findNextOccurrence,"findNextOccurrence");const selectNextOccurrence=__name2(({state,dispatch})=>{let{ranges}=state.selection;if(ranges.some(sel=>sel.from===sel.to))return selectWord({state,dispatch});let searchedText=state.sliceDoc(ranges[0].from,ranges[0].to);if(state.selection.ranges.some(r=>state.sliceDoc(r.from,r.to)!=searchedText))return!1;let range=findNextOccurrence(state,searchedText);return range?(dispatch(state.update({selection:state.selection.addRange(EditorSelection.range(range.from,range.to),!1),effects:EditorView.scrollIntoView(range.to)})),!0):!1},"selectNextOccurrence"),searchConfigFacet=Facet.define({combine(configs){return combineConfig(configs,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:view=>new SearchPanel(view),scrollToMatch:range=>EditorView.scrollIntoView(range)})}}),_SearchQuery=class{static{__name(this,"_SearchQuery")}constructor(config2){this.search=config2.search,this.caseSensitive=!!config2.caseSensitive,this.literal=!!config2.literal,this.regexp=!!config2.regexp,this.replace=config2.replace||"",this.valid=!!this.search&&(!this.regexp||validRegExp(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!config2.wholeWord}unquote(text){return this.literal?text:text.replace(/\\([nrt\\])/g,(_,ch)=>ch=="n"?`
`:ch=="r"?"\r":ch=="t"?" ":"\\")}eq(other){return this.search==other.search&&this.replace==other.replace&&this.caseSensitive==other.caseSensitive&&this.regexp==other.regexp&&this.wholeWord==other.wholeWord}create(){return this.regexp?new RegExpQuery(this):new StringQuery(this)}getCursor(state,from=0,to){let st=state.doc?state:EditorState.create({doc:state});return to==null&&(to=st.doc.length),this.regexp?regexpCursor(this,st,from,to):stringCursor(this,st,from,to)}};__name2(_SearchQuery,"SearchQuery");let SearchQuery=_SearchQuery;const _QueryType=class{static{__name(this,"_QueryType")}constructor(spec){this.spec=spec}};__name2(_QueryType,"QueryType");let QueryType=_QueryType;function stringCursor(spec,state,from,to){return new SearchCursor(state.doc,spec.unquoted,from,to,spec.caseSensitive?void 0:x=>x.toLowerCase(),spec.wholeWord?stringWordTest(state.doc,state.charCategorizer(state.selection.main.head)):void 0)}__name(stringCursor,"stringCursor"),__name2(stringCursor,"stringCursor");function stringWordTest(doc2,categorizer){return(from,to,buf,bufPos)=>((bufPos>from||bufPos+buf.length<to)&&(bufPos=Math.max(0,from-2),buf=doc2.sliceString(bufPos,Math.min(doc2.length,to+2))),(categorizer(charBefore(buf,from-bufPos))!=CharCategory.Word||categorizer(charAfter(buf,from-bufPos))!=CharCategory.Word)&&(categorizer(charAfter(buf,to-bufPos))!=CharCategory.Word||categorizer(charBefore(buf,to-bufPos))!=CharCategory.Word))}__name(stringWordTest,"stringWordTest"),__name2(stringWordTest,"stringWordTest");const _StringQuery=class extends QueryType{static{__name(this,"_StringQuery")}constructor(spec){super(spec)}nextMatch(state,curFrom,curTo){let cursor=stringCursor(this.spec,state,curTo,state.doc.length).nextOverlapping();return cursor.done&&(cursor=stringCursor(this.spec,state,0,curFrom).nextOverlapping()),cursor.done?null:cursor.value}prevMatchInRange(state,from,to){for(let pos=to;;){let start=Math.max(from,pos-1e4-this.spec.unquoted.length),cursor=stringCursor(this.spec,state,start,pos),range=null;for(;!cursor.nextOverlapping().done;)range=cursor.value;if(range)return range;if(start==from)return null;pos-=1e4}}prevMatch(state,curFrom,curTo){return this.prevMatchInRange(state,0,curFrom)||this.prevMatchInRange(state,curTo,state.doc.length)}getReplacement(_result){return this.spec.unquote(this.spec.replace)}matchAll(state,limit2){let cursor=stringCursor(this.spec,state,0,state.doc.length),ranges=[];for(;!cursor.next().done;){if(ranges.length>=limit2)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add2){let cursor=stringCursor(this.spec,state,Math.max(0,from-this.spec.unquoted.length),Math.min(to+this.spec.unquoted.length,state.doc.length));for(;!cursor.next().done;)add2(cursor.value.from,cursor.value.to)}};__name2(_StringQuery,"StringQuery");let StringQuery=_StringQuery;function regexpCursor(spec,state,from,to){return new RegExpCursor(state.doc,spec.search,{ignoreCase:!spec.caseSensitive,test:spec.wholeWord?regexpWordTest(state.charCategorizer(state.selection.main.head)):void 0},from,to)}__name(regexpCursor,"regexpCursor"),__name2(regexpCursor,"regexpCursor");function charBefore(str,index2){return str.slice(findClusterBreak(str,index2,!1),index2)}__name(charBefore,"charBefore"),__name2(charBefore,"charBefore");function charAfter(str,index2){return str.slice(index2,findClusterBreak(str,index2))}__name(charAfter,"charAfter"),__name2(charAfter,"charAfter");function regexpWordTest(categorizer){return(_from,_to,match2)=>!match2[0].length||(categorizer(charBefore(match2.input,match2.index))!=CharCategory.Word||categorizer(charAfter(match2.input,match2.index))!=CharCategory.Word)&&(categorizer(charAfter(match2.input,match2.index+match2[0].length))!=CharCategory.Word||categorizer(charBefore(match2.input,match2.index+match2[0].length))!=CharCategory.Word)}__name(regexpWordTest,"regexpWordTest"),__name2(regexpWordTest,"regexpWordTest");const _RegExpQuery=class extends QueryType{static{__name(this,"_RegExpQuery")}nextMatch(state,curFrom,curTo){let cursor=regexpCursor(this.spec,state,curTo,state.doc.length).next();return cursor.done&&(cursor=regexpCursor(this.spec,state,0,curFrom).next()),cursor.done?null:cursor.value}prevMatchInRange(state,from,to){for(let size=1;;size++){let start=Math.max(from,to-size*1e4),cursor=regexpCursor(this.spec,state,start,to),range=null;for(;!cursor.next().done;)range=cursor.value;if(range&&(start==from||range.from>start+10))return range;if(start==from)return null}}prevMatch(state,curFrom,curTo){return this.prevMatchInRange(state,0,curFrom)||this.prevMatchInRange(state,curTo,state.doc.length)}getReplacement(result){return this.spec.unquote(this.spec.replace.replace(/\$([$&\d+])/g,(m,i)=>i=="$"?"$":i=="&"?result.match[0]:i!="0"&&+i<result.match.length?result.match[i]:m))}matchAll(state,limit2){let cursor=regexpCursor(this.spec,state,0,state.doc.length),ranges=[];for(;!cursor.next().done;){if(ranges.length>=limit2)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add2){let cursor=regexpCursor(this.spec,state,Math.max(0,from-250),Math.min(to+250,state.doc.length));for(;!cursor.next().done;)add2(cursor.value.from,cursor.value.to)}};__name2(_RegExpQuery,"RegExpQuery");let RegExpQuery=_RegExpQuery;const setSearchQuery=StateEffect.define(),togglePanel=StateEffect.define(),searchState=StateField.define({create(state){return new SearchState(defaultQuery(state).create(),null)},update(value,tr){for(let effect of tr.effects)effect.is(setSearchQuery)?value=new SearchState(effect.value.create(),value.panel):effect.is(togglePanel)&&(value=new SearchState(value.query,effect.value?createSearchPanel:null));return value},provide:f2=>showPanel.from(f2,val=>val.panel)}),_SearchState=class{static{__name(this,"_SearchState")}constructor(query,panel){this.query=query,this.panel=panel}};__name2(_SearchState,"SearchState");let SearchState=_SearchState;const matchMark=Decoration.mark({class:"cm-searchMatch"}),selectedMatchMark=Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"}),searchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=this.highlight(view.state.field(searchState))}update(update){let state=update.state.field(searchState);(state!=update.startState.field(searchState)||update.docChanged||update.selectionSet||update.viewportChanged)&&(this.decorations=this.highlight(state))}highlight({query,panel}){if(!panel||!query.spec.valid)return Decoration.none;let{view}=this,builder=new RangeSetBuilder;for(let i=0,ranges=view.visibleRanges,l2=ranges.length;i<l2;i++){let{from,to}=ranges[i];for(;i<l2-1&&to>ranges[i+1].from-2*250;)to=ranges[++i].to;query.highlight(view.state,from,to,(from2,to2)=>{let selected=view.state.selection.ranges.some(r=>r.from==from2&&r.to==to2);builder.add(from2,to2,selected?selectedMatchMark:matchMark)})}return builder.finish()}},{decorations:v=>v.decorations});function searchCommand(f2){return view=>{let state=view.state.field(searchState,!1);return state&&state.query.spec.valid?f2(view,state):openSearchPanel(view)}}__name(searchCommand,"searchCommand"),__name2(searchCommand,"searchCommand");const findNext=searchCommand((view,{query})=>{let{to}=view.state.selection.main,next=query.nextMatch(view.state,to,to);if(!next)return!1;let selection=EditorSelection.single(next.from,next.to),config2=view.state.facet(searchConfigFacet);return view.dispatch({selection,effects:[announceMatch(view,next),config2.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0}),findPrevious=searchCommand((view,{query})=>{let{state}=view,{from}=state.selection.main,prev=query.prevMatch(state,from,from);if(!prev)return!1;let selection=EditorSelection.single(prev.from,prev.to),config2=view.state.facet(searchConfigFacet);return view.dispatch({selection,effects:[announceMatch(view,prev),config2.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0}),selectMatches=searchCommand((view,{query})=>{let ranges=query.matchAll(view.state,1e3);return!ranges||!ranges.length?!1:(view.dispatch({selection:EditorSelection.create(ranges.map(r=>EditorSelection.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),selectSelectionMatches=__name2(({state,dispatch})=>{let sel=state.selection;if(sel.ranges.length>1||sel.main.empty)return!1;let{from,to}=sel.main,ranges=[],main=0;for(let cur2=new SearchCursor(state.doc,state.sliceDoc(from,to));!cur2.next().done;){if(ranges.length>1e3)return!1;cur2.value.from==from&&(main=ranges.length),ranges.push(EditorSelection.range(cur2.value.from,cur2.value.to))}return dispatch(state.update({selection:EditorSelection.create(ranges,main),userEvent:"select.search.matches"})),!0},"selectSelectionMatches"),replaceNext=searchCommand((view,{query})=>{let{state}=view,{from,to}=state.selection.main;if(state.readOnly)return!1;let next=query.nextMatch(state,from,from);if(!next)return!1;let changes=[],selection,replacement,effects=[];if(next.from==from&&next.to==to&&(replacement=state.toText(query.getReplacement(next)),changes.push({from:next.from,to:next.to,insert:replacement}),next=query.nextMatch(state,next.from,next.to),effects.push(EditorView.announce.of(state.phrase("replaced match on line $",state.doc.lineAt(from).number)+"."))),next){let off2=changes.length==0||changes[0].from>=next.to?0:next.to-next.from-replacement.length;selection=EditorSelection.single(next.from-off2,next.to-off2),effects.push(announceMatch(view,next)),effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main,view))}return view.dispatch({changes,selection,effects,userEvent:"input.replace"}),!0}),replaceAll=searchCommand((view,{query})=>{if(view.state.readOnly)return!1;let changes=query.matchAll(view.state,1e9).map(match2=>{let{from,to}=match2;return{from,to,insert:query.getReplacement(match2)}});if(!changes.length)return!1;let announceText=view.state.phrase("replaced $ matches",changes.length)+".";return view.dispatch({changes,effects:EditorView.announce.of(announceText),userEvent:"input.replace.all"}),!0});function createSearchPanel(view){return view.state.facet(searchConfigFacet).createPanel(view)}__name(createSearchPanel,"createSearchPanel"),__name2(createSearchPanel,"createSearchPanel");function defaultQuery(state,fallback){var _a3,_b2,_c2,_d,_e;let sel=state.selection.main,selText=sel.empty||sel.to>sel.from+100?"":state.sliceDoc(sel.from,sel.to);if(fallback&&!selText)return fallback;let config2=state.facet(searchConfigFacet);return new SearchQuery({search:((_a3=fallback?.literal)!==null&&_a3!==void 0?_a3:config2.literal)?selText:selText.replace(/\n/g,"\\n"),caseSensitive:(_b2=fallback?.caseSensitive)!==null&&_b2!==void 0?_b2:config2.caseSensitive,literal:(_c2=fallback?.literal)!==null&&_c2!==void 0?_c2:config2.literal,regexp:(_d=fallback?.regexp)!==null&&_d!==void 0?_d:config2.regexp,wholeWord:(_e=fallback?.wholeWord)!==null&&_e!==void 0?_e:config2.wholeWord})}__name(defaultQuery,"defaultQuery"),__name2(defaultQuery,"defaultQuery");function getSearchInput(view){let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.querySelector("[main-field]")}__name(getSearchInput,"getSearchInput"),__name2(getSearchInput,"getSearchInput");function selectSearchInput(view){let input=getSearchInput(view);input&&input==view.root.activeElement&&input.select()}__name(selectSearchInput,"selectSearchInput"),__name2(selectSearchInput,"selectSearchInput");const openSearchPanel=__name2(view=>{let state=view.state.field(searchState,!1);if(state&&state.panel){let searchInput=getSearchInput(view);if(searchInput&&searchInput!=view.root.activeElement){let query=defaultQuery(view.state,state.query.spec);query.valid&&view.dispatch({effects:setSearchQuery.of(query)}),searchInput.focus(),searchInput.select()}}else view.dispatch({effects:[togglePanel.of(!0),state?setSearchQuery.of(defaultQuery(view.state,state.query.spec)):StateEffect.appendConfig.of(searchExtensions)]});return!0},"openSearchPanel"),closeSearchPanel=__name2(view=>{let state=view.state.field(searchState,!1);if(!state||!state.panel)return!1;let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.contains(view.root.activeElement)&&view.focus(),view.dispatch({effects:togglePanel.of(!1)}),!0},"closeSearchPanel"),searchKeymap=[{key:"Mod-f",run:openSearchPanel,scope:"editor search-panel"},{key:"F3",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:closeSearchPanel,scope:"editor search-panel"},{key:"Mod-Shift-l",run:selectSelectionMatches},{key:"Alt-g",run:gotoLine},{key:"Mod-d",run:selectNextOccurrence,preventDefault:!0}],_SearchPanel=class{static{__name(this,"_SearchPanel")}constructor(view){this.view=view;let query=this.query=view.state.field(searchState).query.spec;this.commit=this.commit.bind(this),this.searchField=crelt("input",{value:query.search,placeholder:phrase(view,"Find"),"aria-label":phrase(view,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=crelt("input",{value:query.replace,placeholder:phrase(view,"Replace"),"aria-label":phrase(view,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=crelt("input",{type:"checkbox",name:"case",form:"",checked:query.caseSensitive,onchange:this.commit}),this.reField=crelt("input",{type:"checkbox",name:"re",form:"",checked:query.regexp,onchange:this.commit}),this.wordField=crelt("input",{type:"checkbox",name:"word",form:"",checked:query.wholeWord,onchange:this.commit});function button(name2,onclick,content2){return crelt("button",{class:"cm-button",name:name2,onclick,type:"button"},content2)}__name(button,"button"),__name2(button,"button"),this.dom=crelt("div",{onkeydown:e=>this.keydown(e),class:"cm-search"},[this.searchField,button("next",()=>findNext(view),[phrase(view,"next")]),button("prev",()=>findPrevious(view),[phrase(view,"previous")]),button("select",()=>selectMatches(view),[phrase(view,"all")]),crelt("label",null,[this.caseField,phrase(view,"match case")]),crelt("label",null,[this.reField,phrase(view,"regexp")]),crelt("label",null,[this.wordField,phrase(view,"by word")]),...view.state.readOnly?[]:[crelt("br"),this.replaceField,button("replace",()=>replaceNext(view),[phrase(view,"replace")]),button("replaceAll",()=>replaceAll(view),[phrase(view,"replace all")])],crelt("button",{name:"close",onclick:()=>closeSearchPanel(view),"aria-label":phrase(view,"close"),type:"button"},["\xD7"])])}commit(){let query=new SearchQuery({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});query.eq(this.query)||(this.query=query,this.view.dispatch({effects:setSearchQuery.of(query)}))}keydown(e){runScopeHandlers(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?findPrevious:findNext)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),replaceNext(this.view))}update(update){for(let tr of update.transactions)for(let effect of tr.effects)effect.is(setSearchQuery)&&!effect.value.eq(this.query)&&this.setQuery(effect.value)}setQuery(query){this.query=query,this.searchField.value=query.search,this.replaceField.value=query.replace,this.caseField.checked=query.caseSensitive,this.reField.checked=query.regexp,this.wordField.checked=query.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(searchConfigFacet).top}};__name2(_SearchPanel,"SearchPanel");let SearchPanel=_SearchPanel;function phrase(view,phrase2){return view.state.phrase(phrase2)}__name(phrase,"phrase"),__name2(phrase,"phrase");const AnnounceMargin=30,Break=/[\s\.,:;?!]/;function announceMatch(view,{from,to}){let line=view.state.doc.lineAt(from),lineEnd=view.state.doc.lineAt(to).to,start=Math.max(line.from,from-AnnounceMargin),end=Math.min(lineEnd,to+AnnounceMargin),text=view.state.sliceDoc(start,end);if(start!=line.from){for(let i=0;i<AnnounceMargin;i++)if(!Break.test(text[i+1])&&Break.test(text[i])){text=text.slice(i);break}}if(end!=lineEnd){for(let i=text.length-1;i>text.length-AnnounceMargin;i--)if(!Break.test(text[i-1])&&Break.test(text[i])){text=text.slice(0,i);break}}return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`)}__name(announceMatch,"announceMatch"),__name2(announceMatch,"announceMatch");const baseTheme=EditorView.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),searchExtensions=[searchState,Prec.lowest(searchHighlighter),baseTheme],basicSetup=(()=>[lineNumbers(),highlightActiveLineGutter(),highlightSpecialChars(),history(),foldGutter(),drawSelection(),dropCursor(),EditorState.allowMultipleSelections.of(!0),indentOnInput(),syntaxHighlighting(defaultHighlightStyle,{fallback:!0}),bracketMatching(),closeBrackets(),autocompletion(),rectangularSelection(),crosshairCursor(),highlightActiveLine(),highlightSelectionMatches(),keymap.of([...closeBracketsKeymap,...defaultKeymap,...searchKeymap,...historyKeymap,...foldKeymap,...completionKeymap,...lintKeymap])])(),REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function validate(uuid){return typeof uuid=="string"&&REGEX.test(uuid)}__name(validate,"validate"),__name2(validate,"validate");const byteToHex=[];for(let i=0;i<256;++i)byteToHex.push((i+256).toString(16).slice(1));function unsafeStringify(arr,offset2=0){return byteToHex[arr[offset2+0]]+byteToHex[arr[offset2+1]]+byteToHex[arr[offset2+2]]+byteToHex[arr[offset2+3]]+"-"+byteToHex[arr[offset2+4]]+byteToHex[arr[offset2+5]]+"-"+byteToHex[arr[offset2+6]]+byteToHex[arr[offset2+7]]+"-"+byteToHex[arr[offset2+8]]+byteToHex[arr[offset2+9]]+"-"+byteToHex[arr[offset2+10]]+byteToHex[arr[offset2+11]]+byteToHex[arr[offset2+12]]+byteToHex[arr[offset2+13]]+byteToHex[arr[offset2+14]]+byteToHex[arr[offset2+15]]}__name(unsafeStringify,"unsafeStringify"),__name2(unsafeStringify,"unsafeStringify");function parse(uuid){if(!validate(uuid))throw TypeError("Invalid UUID");let v;const arr=new Uint8Array(16);return arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24,arr[1]=v>>>16&255,arr[2]=v>>>8&255,arr[3]=v&255,arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8,arr[5]=v&255,arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8,arr[7]=v&255,arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8,arr[9]=v&255,arr[10]=(v=parseInt(uuid.slice(24,36),16))/1099511627776&255,arr[11]=v/4294967296&255,arr[12]=v>>>24&255,arr[13]=v>>>16&255,arr[14]=v>>>8&255,arr[15]=v&255,arr}__name(parse,"parse"),__name2(parse,"parse");function stringToBytes(str){str=unescape(encodeURIComponent(str));const bytes=[];for(let i=0;i<str.length;++i)bytes.push(str.charCodeAt(i));return bytes}__name(stringToBytes,"stringToBytes"),__name2(stringToBytes,"stringToBytes");const DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function v35(name2,version2,hashfunc){function generateUUID(value,namespace,buf,offset2){var _namespace;if(typeof value=="string"&&(value=stringToBytes(value)),typeof namespace=="string"&&(namespace=parse(namespace)),((_namespace=namespace)===null||_namespace===void 0?void 0:_namespace.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let bytes=new Uint8Array(16+value.length);if(bytes.set(namespace),bytes.set(value,namespace.length),bytes=hashfunc(bytes),bytes[6]=bytes[6]&15|version2,bytes[8]=bytes[8]&63|128,buf){offset2=offset2||0;for(let i=0;i<16;++i)buf[offset2+i]=bytes[i];return buf}return unsafeStringify(bytes)}__name(generateUUID,"generateUUID"),__name2(generateUUID,"generateUUID");try{generateUUID.name=name2}catch{}return generateUUID.DNS=DNS,generateUUID.URL=URL,generateUUID}__name(v35,"v35"),__name2(v35,"v35");function f(s2,x,y,z){switch(s2){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z}}__name(f,"f"),__name2(f,"f");function ROTL(x,n2){return x<<n2|x>>>32-n2}__name(ROTL,"ROTL"),__name2(ROTL,"ROTL");function sha1(bytes){const K=[1518500249,1859775393,2400959708,3395469782],H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof bytes=="string"){const msg=unescape(encodeURIComponent(bytes));bytes=[];for(let i=0;i<msg.length;++i)bytes.push(msg.charCodeAt(i))}else Array.isArray(bytes)||(bytes=Array.prototype.slice.call(bytes));bytes.push(128);const l2=bytes.length/4+2,N=Math.ceil(l2/16),M=new Array(N);for(let i=0;i<N;++i){const arr=new Uint32Array(16);for(let j=0;j<16;++j)arr[j]=bytes[i*64+j*4]<<24|bytes[i*64+j*4+1]<<16|bytes[i*64+j*4+2]<<8|bytes[i*64+j*4+3];M[i]=arr}M[N-1][14]=(bytes.length-1)*8/Math.pow(2,32),M[N-1][14]=Math.floor(M[N-1][14]),M[N-1][15]=(bytes.length-1)*8&4294967295;for(let i=0;i<N;++i){const W=new Uint32Array(80);for(let t2=0;t2<16;++t2)W[t2]=M[i][t2];for(let t2=16;t2<80;++t2)W[t2]=ROTL(W[t2-3]^W[t2-8]^W[t2-14]^W[t2-16],1);let a=H[0],b=H[1],c=H[2],d=H[3],e=H[4];for(let t2=0;t2<80;++t2){const s2=Math.floor(t2/20),T=ROTL(a,5)+f(s2,b,c,d)+e+K[s2]+W[t2]>>>0;e=d,d=c,c=ROTL(b,30)>>>0,b=a,a=T}H[0]=H[0]+a>>>0,H[1]=H[1]+b>>>0,H[2]=H[2]+c>>>0,H[3]=H[3]+d>>>0,H[4]=H[4]+e>>>0}return[H[0]>>24&255,H[0]>>16&255,H[0]>>8&255,H[0]&255,H[1]>>24&255,H[1]>>16&255,H[1]>>8&255,H[1]&255,H[2]>>24&255,H[2]>>16&255,H[2]>>8&255,H[2]&255,H[3]>>24&255,H[3]>>16&255,H[3]>>8&255,H[3]&255,H[4]>>24&255,H[4]>>16&255,H[4]>>8&255,H[4]&255]}__name(sha1,"sha1"),__name2(sha1,"sha1");const v5=v35("v5",80,sha1),UUIDv5=v5;var PipsMode;(function(PipsMode2){PipsMode2.Range="range",PipsMode2.Steps="steps",PipsMode2.Positions="positions",PipsMode2.Count="count",PipsMode2.Values="values"})(PipsMode||(PipsMode={}));var PipsType;(function(PipsType2){PipsType2[PipsType2.None=-1]="None",PipsType2[PipsType2.NoValue=0]="NoValue",PipsType2[PipsType2.LargeValue=1]="LargeValue",PipsType2[PipsType2.SmallValue=2]="SmallValue"})(PipsType||(PipsType={}));function isValidFormatter(entry){return isValidPartialFormatter(entry)&&typeof entry.from=="function"}__name(isValidFormatter,"isValidFormatter"),__name2(isValidFormatter,"isValidFormatter");function isValidPartialFormatter(entry){return typeof entry=="object"&&typeof entry.to=="function"}__name(isValidPartialFormatter,"isValidPartialFormatter"),__name2(isValidPartialFormatter,"isValidPartialFormatter");function removeElement(el){el.parentElement.removeChild(el)}__name(removeElement,"removeElement"),__name2(removeElement,"removeElement");function isSet(value){return value!=null}__name(isSet,"isSet"),__name2(isSet,"isSet");function preventDefault(e){e.preventDefault()}__name(preventDefault,"preventDefault"),__name2(preventDefault,"preventDefault");function unique(array){return array.filter(function(a){return this[a]?!1:this[a]=!0},{})}__name(unique,"unique"),__name2(unique,"unique");function closest(value,to){return Math.round(value/to)*to}__name(closest,"closest"),__name2(closest,"closest");function offset(elem,orientation){var rect=elem.getBoundingClientRect(),doc2=elem.ownerDocument,docElem=doc2.documentElement,pageOffset=getPageOffset(doc2);return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(pageOffset.x=0),orientation?rect.top+pageOffset.y-docElem.clientTop:rect.left+pageOffset.x-docElem.clientLeft}__name(offset,"offset"),__name2(offset,"offset");function isNumeric(a){return typeof a=="number"&&!isNaN(a)&&isFinite(a)}__name(isNumeric,"isNumeric"),__name2(isNumeric,"isNumeric");function addClassFor(element,className,duration){duration>0&&(addClass(element,className),setTimeout(function(){removeClass(element,className)},duration))}__name(addClassFor,"addClassFor"),__name2(addClassFor,"addClassFor");function limit(a){return Math.max(Math.min(a,100),0)}__name(limit,"limit"),__name2(limit,"limit");function asArray(a){return Array.isArray(a)?a:[a]}__name(asArray,"asArray"),__name2(asArray,"asArray");function countDecimals(numStr){numStr=String(numStr);var pieces=numStr.split(".");return pieces.length>1?pieces[1].length:0}__name(countDecimals,"countDecimals"),__name2(countDecimals,"countDecimals");function addClass(el,className){el.classList&&!/\s/.test(className)?el.classList.add(className):el.className+=" "+className}__name(addClass,"addClass"),__name2(addClass,"addClass");function removeClass(el,className){el.classList&&!/\s/.test(className)?el.classList.remove(className):el.className=el.className.replace(new RegExp("(^|\\b)"+className.split(" ").join("|")+"(\\b|$)","gi")," ")}__name(removeClass,"removeClass"),__name2(removeClass,"removeClass");function hasClass(el,className){return el.classList?el.classList.contains(className):new RegExp("\\b"+className+"\\b").test(el.className)}__name(hasClass,"hasClass"),__name2(hasClass,"hasClass");function getPageOffset(doc2){var supportPageOffset=window.pageXOffset!==void 0,isCSS1Compat=(doc2.compatMode||"")==="CSS1Compat",x=supportPageOffset?window.pageXOffset:isCSS1Compat?doc2.documentElement.scrollLeft:doc2.body.scrollLeft,y=supportPageOffset?window.pageYOffset:isCSS1Compat?doc2.documentElement.scrollTop:doc2.body.scrollTop;return{x,y}}__name(getPageOffset,"getPageOffset"),__name2(getPageOffset,"getPageOffset");function getActions(){return window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"}}__name(getActions,"getActions"),__name2(getActions,"getActions");function getSupportsPassive(){var supportsPassive=!1;try{var opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=!0}});window.addEventListener("test",null,opts)}catch{}return supportsPassive}__name(getSupportsPassive,"getSupportsPassive"),__name2(getSupportsPassive,"getSupportsPassive");function getSupportsTouchActionNone(){return window.CSS&&CSS.supports&&CSS.supports("touch-action","none")}__name(getSupportsTouchActionNone,"getSupportsTouchActionNone"),__name2(getSupportsTouchActionNone,"getSupportsTouchActionNone");function subRangeRatio(pa,pb){return 100/(pb-pa)}__name(subRangeRatio,"subRangeRatio"),__name2(subRangeRatio,"subRangeRatio");function fromPercentage(range,value,startRange){return value*100/(range[startRange+1]-range[startRange])}__name(fromPercentage,"fromPercentage"),__name2(fromPercentage,"fromPercentage");function toPercentage(range,value){return fromPercentage(range,range[0]<0?value+Math.abs(range[0]):value-range[0],0)}__name(toPercentage,"toPercentage"),__name2(toPercentage,"toPercentage");function isPercentage(range,value){return value*(range[1]-range[0])/100+range[0]}__name(isPercentage,"isPercentage"),__name2(isPercentage,"isPercentage");function getJ(value,arr){for(var j=1;value>=arr[j];)j+=1;return j}__name(getJ,"getJ"),__name2(getJ,"getJ");function toStepping(xVal,xPct,value){if(value>=xVal.slice(-1)[0])return 100;var j=getJ(value,xVal),va=xVal[j-1],vb=xVal[j],pa=xPct[j-1],pb=xPct[j];return pa+toPercentage([va,vb],value)/subRangeRatio(pa,pb)}__name(toStepping,"toStepping"),__name2(toStepping,"toStepping");function fromStepping(xVal,xPct,value){if(value>=100)return xVal.slice(-1)[0];var j=getJ(value,xPct),va=xVal[j-1],vb=xVal[j],pa=xPct[j-1],pb=xPct[j];return isPercentage([va,vb],(value-pa)*subRangeRatio(pa,pb))}__name(fromStepping,"fromStepping"),__name2(fromStepping,"fromStepping");function getStep(xPct,xSteps,snap,value){if(value===100)return value;var j=getJ(value,xPct),a=xPct[j-1],b=xPct[j];return snap?value-a>(b-a)/2?b:a:xSteps[j-1]?xPct[j-1]+closest(value-xPct[j-1],xSteps[j-1]):value}__name(getStep,"getStep"),__name2(getStep,"getStep");var Spectrum=function(){function Spectrum2(entry,snap,singleStep){this.xPct=[],this.xVal=[],this.xSteps=[],this.xNumSteps=[],this.xHighestCompleteStep=[],this.xSteps=[singleStep||!1],this.xNumSteps=[!1],this.snap=snap;var index2,ordered=[];for(Object.keys(entry).forEach(function(index3){ordered.push([asArray(entry[index3]),index3])}),ordered.sort(function(a,b){return a[0][0]-b[0][0]}),index2=0;index2<ordered.length;index2++)this.handleEntryPoint(ordered[index2][1],ordered[index2][0]);for(this.xNumSteps=this.xSteps.slice(0),index2=0;index2<this.xNumSteps.length;index2++)this.handleStepPoint(index2,this.xNumSteps[index2])}return __name(Spectrum2,"Spectrum2"),__name2(Spectrum2,"Spectrum"),Spectrum2.prototype.getDistance=function(value){for(var distances=[],index2=0;index2<this.xNumSteps.length-1;index2++)distances[index2]=fromPercentage(this.xVal,value,index2);return distances},Spectrum2.prototype.getAbsoluteDistance=function(value,distances,direction){var xPct_index=0;if(value<this.xPct[this.xPct.length-1])for(;value>this.xPct[xPct_index+1];)xPct_index++;else value===this.xPct[this.xPct.length-1]&&(xPct_index=this.xPct.length-2);!direction&&value===this.xPct[xPct_index+1]&&xPct_index++,distances===null&&(distances=[]);var start_factor,rest_factor=1,rest_rel_distance=distances[xPct_index],range_pct=0,rel_range_distance=0,abs_distance_counter=0,range_counter=0;for(direction?start_factor=(value-this.xPct[xPct_index])/(this.xPct[xPct_index+1]-this.xPct[xPct_index]):start_factor=(this.xPct[xPct_index+1]-value)/(this.xPct[xPct_index+1]-this.xPct[xPct_index]);rest_rel_distance>0;)range_pct=this.xPct[xPct_index+1+range_counter]-this.xPct[xPct_index+range_counter],distances[xPct_index+range_counter]*rest_factor+100-start_factor*100>100?(rel_range_distance=range_pct*start_factor,rest_factor=(rest_rel_distance-100*start_factor)/distances[xPct_index+range_counter],start_factor=1):(rel_range_distance=distances[xPct_index+range_counter]*range_pct/100*rest_factor,rest_factor=0),direction?(abs_distance_counter=abs_distance_counter-rel_range_distance,this.xPct.length+range_counter>=1&&range_counter--):(abs_distance_counter=abs_distance_counter+rel_range_distance,this.xPct.length-range_counter>=1&&range_counter++),rest_rel_distance=distances[xPct_index+range_counter]*rest_factor;return value+abs_distance_counter},Spectrum2.prototype.toStepping=function(value){return value=toStepping(this.xVal,this.xPct,value),value},Spectrum2.prototype.fromStepping=function(value){return fromStepping(this.xVal,this.xPct,value)},Spectrum2.prototype.getStep=function(value){return value=getStep(this.xPct,this.xSteps,this.snap,value),value},Spectrum2.prototype.getDefaultStep=function(value,isDown,size){var j=getJ(value,this.xPct);return(value===100||isDown&&value===this.xPct[j-1])&&(j=Math.max(j-1,1)),(this.xVal[j]-this.xVal[j-1])/size},Spectrum2.prototype.getNearbySteps=function(value){var j=getJ(value,this.xPct);return{stepBefore:{startValue:this.xVal[j-2],step:this.xNumSteps[j-2],highestStep:this.xHighestCompleteStep[j-2]},thisStep:{startValue:this.xVal[j-1],step:this.xNumSteps[j-1],highestStep:this.xHighestCompleteStep[j-1]},stepAfter:{startValue:this.xVal[j],step:this.xNumSteps[j],highestStep:this.xHighestCompleteStep[j]}}},Spectrum2.prototype.countStepDecimals=function(){var stepDecimals=this.xNumSteps.map(countDecimals);return Math.max.apply(null,stepDecimals)},Spectrum2.prototype.hasNoSize=function(){return this.xVal[0]===this.xVal[this.xVal.length-1]},Spectrum2.prototype.convert=function(value){return this.getStep(this.toStepping(value))},Spectrum2.prototype.handleEntryPoint=function(index2,value){var percentage;if(index2==="min"?percentage=0:index2==="max"?percentage=100:percentage=parseFloat(index2),!isNumeric(percentage)||!isNumeric(value[0]))throw new Error("noUiSlider: 'range' value isn't numeric.");this.xPct.push(percentage),this.xVal.push(value[0]);var value1=Number(value[1]);percentage?this.xSteps.push(isNaN(value1)?!1:value1):isNaN(value1)||(this.xSteps[0]=value1),this.xHighestCompleteStep.push(0)},Spectrum2.prototype.handleStepPoint=function(i,n2){if(n2){if(this.xVal[i]===this.xVal[i+1]){this.xSteps[i]=this.xHighestCompleteStep[i]=this.xVal[i];return}this.xSteps[i]=fromPercentage([this.xVal[i],this.xVal[i+1]],n2,0)/subRangeRatio(this.xPct[i],this.xPct[i+1]);var totalSteps=(this.xVal[i+1]-this.xVal[i])/this.xNumSteps[i],highestStep=Math.ceil(Number(totalSteps.toFixed(3))-1),step=this.xVal[i]+this.xNumSteps[i]*highestStep;this.xHighestCompleteStep[i]=step}},Spectrum2}(),defaultFormatter={to:function(value){return value===void 0?"":value.toFixed(2)},from:Number},cssClasses={target:"target",base:"base",origin:"origin",handle:"handle",handleLower:"handle-lower",handleUpper:"handle-upper",touchArea:"touch-area",horizontal:"horizontal",vertical:"vertical",background:"background",connect:"connect",connects:"connects",ltr:"ltr",rtl:"rtl",textDirectionLtr:"txt-dir-ltr",textDirectionRtl:"txt-dir-rtl",draggable:"draggable",drag:"state-drag",tap:"state-tap",active:"active",tooltip:"tooltip",pips:"pips",pipsHorizontal:"pips-horizontal",pipsVertical:"pips-vertical",marker:"marker",markerHorizontal:"marker-horizontal",markerVertical:"marker-vertical",markerNormal:"marker-normal",markerLarge:"marker-large",markerSub:"marker-sub",value:"value",valueHorizontal:"value-horizontal",valueVertical:"value-vertical",valueNormal:"value-normal",valueLarge:"value-large",valueSub:"value-sub"},INTERNAL_EVENT_NS={tooltips:".__tooltips",aria:".__aria"};function testStep(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'step' is not numeric.");parsed.singleStep=entry}__name(testStep,"testStep"),__name2(testStep,"testStep");function testKeyboardPageMultiplier(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardPageMultiplier' is not numeric.");parsed.keyboardPageMultiplier=entry}__name(testKeyboardPageMultiplier,"testKeyboardPageMultiplier"),__name2(testKeyboardPageMultiplier,"testKeyboardPageMultiplier");function testKeyboardMultiplier(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardMultiplier' is not numeric.");parsed.keyboardMultiplier=entry}__name(testKeyboardMultiplier,"testKeyboardMultiplier"),__name2(testKeyboardMultiplier,"testKeyboardMultiplier");function testKeyboardDefaultStep(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardDefaultStep' is not numeric.");parsed.keyboardDefaultStep=entry}__name(testKeyboardDefaultStep,"testKeyboardDefaultStep"),__name2(testKeyboardDefaultStep,"testKeyboardDefaultStep");function testRange(parsed,entry){if(typeof entry!="object"||Array.isArray(entry))throw new Error("noUiSlider: 'range' is not an object.");if(entry.min===void 0||entry.max===void 0)throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");parsed.spectrum=new Spectrum(entry,parsed.snap||!1,parsed.singleStep)}__name(testRange,"testRange"),__name2(testRange,"testRange");function testStart(parsed,entry){if(entry=asArray(entry),!Array.isArray(entry)||!entry.length)throw new Error("noUiSlider: 'start' option is incorrect.");parsed.handles=entry.length,parsed.start=entry}__name(testStart,"testStart"),__name2(testStart,"testStart");function testSnap(parsed,entry){if(typeof entry!="boolean")throw new Error("noUiSlider: 'snap' option must be a boolean.");parsed.snap=entry}__name(testSnap,"testSnap"),__name2(testSnap,"testSnap");function testAnimate(parsed,entry){if(typeof entry!="boolean")throw new Error("noUiSlider: 'animate' option must be a boolean.");parsed.animate=entry}__name(testAnimate,"testAnimate"),__name2(testAnimate,"testAnimate");function testAnimationDuration(parsed,entry){if(typeof entry!="number")throw new Error("noUiSlider: 'animationDuration' option must be a number.");parsed.animationDuration=entry}__name(testAnimationDuration,"testAnimationDuration"),__name2(testAnimationDuration,"testAnimationDuration");function testConnect(parsed,entry){var connect=[!1],i;if(entry==="lower"?entry=[!0,!1]:entry==="upper"&&(entry=[!1,!0]),entry===!0||entry===!1){for(i=1;i<parsed.handles;i++)connect.push(entry);connect.push(!1)}else{if(!Array.isArray(entry)||!entry.length||entry.length!==parsed.handles+1)throw new Error("noUiSlider: 'connect' option doesn't match handle count.");connect=entry}parsed.connect=connect}__name(testConnect,"testConnect"),__name2(testConnect,"testConnect");function testOrientation(parsed,entry){switch(entry){case"horizontal":parsed.ort=0;break;case"vertical":parsed.ort=1;break;default:throw new Error("noUiSlider: 'orientation' option is invalid.")}}__name(testOrientation,"testOrientation"),__name2(testOrientation,"testOrientation");function testMargin(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'margin' option must be numeric.");entry!==0&&(parsed.margin=parsed.spectrum.getDistance(entry))}__name(testMargin,"testMargin"),__name2(testMargin,"testMargin");function testLimit(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'limit' option must be numeric.");if(parsed.limit=parsed.spectrum.getDistance(entry),!parsed.limit||parsed.handles<2)throw new Error("noUiSlider: 'limit' option is only supported on linear sliders with 2 or more handles.")}__name(testLimit,"testLimit"),__name2(testLimit,"testLimit");function testPadding(parsed,entry){var index2;if(!isNumeric(entry)&&!Array.isArray(entry))throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.");if(Array.isArray(entry)&&!(entry.length===2||isNumeric(entry[0])||isNumeric(entry[1])))throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.");if(entry!==0){for(Array.isArray(entry)||(entry=[entry,entry]),parsed.padding=[parsed.spectrum.getDistance(entry[0]),parsed.spectrum.getDistance(entry[1])],index2=0;index2<parsed.spectrum.xNumSteps.length-1;index2++)if(parsed.padding[0][index2]<0||parsed.padding[1][index2]<0)throw new Error("noUiSlider: 'padding' option must be a positive number(s).");var totalPadding=entry[0]+entry[1],firstValue=parsed.spectrum.xVal[0],lastValue=parsed.spectrum.xVal[parsed.spectrum.xVal.length-1];if(totalPadding/(lastValue-firstValue)>1)throw new Error("noUiSlider: 'padding' option must not exceed 100% of the range.")}}__name(testPadding,"testPadding"),__name2(testPadding,"testPadding");function testDirection(parsed,entry){switch(entry){case"ltr":parsed.dir=0;break;case"rtl":parsed.dir=1;break;default:throw new Error("noUiSlider: 'direction' option was not recognized.")}}__name(testDirection,"testDirection"),__name2(testDirection,"testDirection");function testBehaviour(parsed,entry){if(typeof entry!="string")throw new Error("noUiSlider: 'behaviour' must be a string containing options.");var tap=entry.indexOf("tap")>=0,drag=entry.indexOf("drag")>=0,fixed=entry.indexOf("fixed")>=0,snap=entry.indexOf("snap")>=0,hover=entry.indexOf("hover")>=0,unconstrained=entry.indexOf("unconstrained")>=0,dragAll=entry.indexOf("drag-all")>=0,smoothSteps=entry.indexOf("smooth-steps")>=0;if(fixed){if(parsed.handles!==2)throw new Error("noUiSlider: 'fixed' behaviour must be used with 2 handles");testMargin(parsed,parsed.start[1]-parsed.start[0])}if(unconstrained&&(parsed.margin||parsed.limit))throw new Error("noUiSlider: 'unconstrained' behaviour cannot be used with margin or limit");parsed.events={tap:tap||snap,drag,dragAll,smoothSteps,fixed,snap,hover,unconstrained}}__name(testBehaviour,"testBehaviour"),__name2(testBehaviour,"testBehaviour");function testTooltips(parsed,entry){if(entry!==!1)if(entry===!0||isValidPartialFormatter(entry)){parsed.tooltips=[];for(var i=0;i<parsed.handles;i++)parsed.tooltips.push(entry)}else{if(entry=asArray(entry),entry.length!==parsed.handles)throw new Error("noUiSlider: must pass a formatter for all handles.");entry.forEach(function(formatter){if(typeof formatter!="boolean"&&!isValidPartialFormatter(formatter))throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'.")}),parsed.tooltips=entry}}__name(testTooltips,"testTooltips"),__name2(testTooltips,"testTooltips");function testHandleAttributes(parsed,entry){if(entry.length!==parsed.handles)throw new Error("noUiSlider: must pass a attributes for all handles.");parsed.handleAttributes=entry}__name(testHandleAttributes,"testHandleAttributes"),__name2(testHandleAttributes,"testHandleAttributes");function testAriaFormat(parsed,entry){if(!isValidPartialFormatter(entry))throw new Error("noUiSlider: 'ariaFormat' requires 'to' method.");parsed.ariaFormat=entry}__name(testAriaFormat,"testAriaFormat"),__name2(testAriaFormat,"testAriaFormat");function testFormat(parsed,entry){if(!isValidFormatter(entry))throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.");parsed.format=entry}__name(testFormat,"testFormat"),__name2(testFormat,"testFormat");function testKeyboardSupport(parsed,entry){if(typeof entry!="boolean")throw new Error("noUiSlider: 'keyboardSupport' option must be a boolean.");parsed.keyboardSupport=entry}__name(testKeyboardSupport,"testKeyboardSupport"),__name2(testKeyboardSupport,"testKeyboardSupport");function testDocumentElement(parsed,entry){parsed.documentElement=entry}__name(testDocumentElement,"testDocumentElement"),__name2(testDocumentElement,"testDocumentElement");function testCssPrefix(parsed,entry){if(typeof entry!="string"&&entry!==!1)throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`.");parsed.cssPrefix=entry}__name(testCssPrefix,"testCssPrefix"),__name2(testCssPrefix,"testCssPrefix");function testCssClasses(parsed,entry){if(typeof entry!="object")throw new Error("noUiSlider: 'cssClasses' must be an object.");typeof parsed.cssPrefix=="string"?(parsed.cssClasses={},Object.keys(entry).forEach(function(key){parsed.cssClasses[key]=parsed.cssPrefix+entry[key]})):parsed.cssClasses=entry}__name(testCssClasses,"testCssClasses"),__name2(testCssClasses,"testCssClasses");function testOptions(options){var parsed={margin:null,limit:null,padding:null,animate:!0,animationDuration:300,ariaFormat:defaultFormatter,format:defaultFormatter},tests={step:{r:!1,t:testStep},keyboardPageMultiplier:{r:!1,t:testKeyboardPageMultiplier},keyboardMultiplier:{r:!1,t:testKeyboardMultiplier},keyboardDefaultStep:{r:!1,t:testKeyboardDefaultStep},start:{r:!0,t:testStart},connect:{r:!0,t:testConnect},direction:{r:!0,t:testDirection},snap:{r:!1,t:testSnap},animate:{r:!1,t:testAnimate},animationDuration:{r:!1,t:testAnimationDuration},range:{r:!0,t:testRange},orientation:{r:!1,t:testOrientation},margin:{r:!1,t:testMargin},limit:{r:!1,t:testLimit},padding:{r:!1,t:testPadding},behaviour:{r:!0,t:testBehaviour},ariaFormat:{r:!1,t:testAriaFormat},format:{r:!1,t:testFormat},tooltips:{r:!1,t:testTooltips},keyboardSupport:{r:!0,t:testKeyboardSupport},documentElement:{r:!1,t:testDocumentElement},cssPrefix:{r:!0,t:testCssPrefix},cssClasses:{r:!0,t:testCssClasses},handleAttributes:{r:!1,t:testHandleAttributes}},defaults2={connect:!1,direction:"ltr",behaviour:"tap",orientation:"horizontal",keyboardSupport:!0,cssPrefix:"noUi-",cssClasses,keyboardPageMultiplier:5,keyboardMultiplier:1,keyboardDefaultStep:10};options.format&&!options.ariaFormat&&(options.ariaFormat=options.format),Object.keys(tests).forEach(function(name2){if(!isSet(options[name2])&&defaults2[name2]===void 0){if(tests[name2].r)throw new Error("noUiSlider: '"+name2+"' is required.");return}tests[name2].t(parsed,isSet(options[name2])?options[name2]:defaults2[name2])}),parsed.pips=options.pips;var d=document.createElement("div"),msPrefix=d.style.msTransform!==void 0,noPrefix=d.style.transform!==void 0;parsed.transformRule=noPrefix?"transform":msPrefix?"msTransform":"webkitTransform";var styles=[["left","top"],["right","bottom"]];return parsed.style=styles[parsed.dir][parsed.ort],parsed}__name(testOptions,"testOptions"),__name2(testOptions,"testOptions");function scope(target,options,originalOptions){var actions=getActions(),supportsTouchActionNone=getSupportsTouchActionNone(),supportsPassive=supportsTouchActionNone&&getSupportsPassive(),scope_Target=target,scope_Base,scope_Handles,scope_Connects,scope_Pips,scope_Tooltips,scope_Spectrum=options.spectrum,scope_Values=[],scope_Locations=[],scope_HandleNumbers=[],scope_ActiveHandlesCount=0,scope_Events={},scope_Document=target.ownerDocument,scope_DocumentElement=options.documentElement||scope_Document.documentElement,scope_Body=scope_Document.body,scope_DirOffset=scope_Document.dir==="rtl"||options.ort===1?0:100;function addNodeTo(addTarget,className){var div=scope_Document.createElement("div");return className&&addClass(div,className),addTarget.appendChild(div),div}__name(addNodeTo,"addNodeTo"),__name2(addNodeTo,"addNodeTo");function addOrigin(base2,handleNumber){var origin=addNodeTo(base2,options.cssClasses.origin),handle=addNodeTo(origin,options.cssClasses.handle);if(addNodeTo(handle,options.cssClasses.touchArea),handle.setAttribute("data-handle",String(handleNumber)),options.keyboardSupport&&(handle.setAttribute("tabindex","0"),handle.addEventListener("keydown",function(event){return eventKeydown(event,handleNumber)})),options.handleAttributes!==void 0){var attributes_1=options.handleAttributes[handleNumber];Object.keys(attributes_1).forEach(function(attribute){handle.setAttribute(attribute,attributes_1[attribute])})}return handle.setAttribute("role","slider"),handle.setAttribute("aria-orientation",options.ort?"vertical":"horizontal"),handleNumber===0?addClass(handle,options.cssClasses.handleLower):handleNumber===options.handles-1&&addClass(handle,options.cssClasses.handleUpper),origin.handle=handle,origin}__name(addOrigin,"addOrigin"),__name2(addOrigin,"addOrigin");function addConnect(base2,add2){return add2?addNodeTo(base2,options.cssClasses.connect):!1}__name(addConnect,"addConnect"),__name2(addConnect,"addConnect");function addElements(connectOptions,base2){var connectBase=addNodeTo(base2,options.cssClasses.connects);scope_Handles=[],scope_Connects=[],scope_Connects.push(addConnect(connectBase,connectOptions[0]));for(var i=0;i<options.handles;i++)scope_Handles.push(addOrigin(base2,i)),scope_HandleNumbers[i]=i,scope_Connects.push(addConnect(connectBase,connectOptions[i+1]))}__name(addElements,"addElements"),__name2(addElements,"addElements");function addSlider(addTarget){addClass(addTarget,options.cssClasses.target),options.dir===0?addClass(addTarget,options.cssClasses.ltr):addClass(addTarget,options.cssClasses.rtl),options.ort===0?addClass(addTarget,options.cssClasses.horizontal):addClass(addTarget,options.cssClasses.vertical);var textDirection=getComputedStyle(addTarget).direction;return textDirection==="rtl"?addClass(addTarget,options.cssClasses.textDirectionRtl):addClass(addTarget,options.cssClasses.textDirectionLtr),addNodeTo(addTarget,options.cssClasses.base)}__name(addSlider,"addSlider"),__name2(addSlider,"addSlider");function addTooltip(handle,handleNumber){return!options.tooltips||!options.tooltips[handleNumber]?!1:addNodeTo(handle.firstChild,options.cssClasses.tooltip)}__name(addTooltip,"addTooltip"),__name2(addTooltip,"addTooltip");function isSliderDisabled(){return scope_Target.hasAttribute("disabled")}__name(isSliderDisabled,"isSliderDisabled"),__name2(isSliderDisabled,"isSliderDisabled");function isHandleDisabled(handleNumber){var handleOrigin=scope_Handles[handleNumber];return handleOrigin.hasAttribute("disabled")}__name(isHandleDisabled,"isHandleDisabled"),__name2(isHandleDisabled,"isHandleDisabled");function disable(handleNumber){handleNumber!=null?(scope_Handles[handleNumber].setAttribute("disabled",""),scope_Handles[handleNumber].handle.removeAttribute("tabindex")):(scope_Target.setAttribute("disabled",""),scope_Handles.forEach(function(handle){handle.handle.removeAttribute("tabindex")}))}__name(disable,"disable"),__name2(disable,"disable");function enable(handleNumber){handleNumber!=null?(scope_Handles[handleNumber].removeAttribute("disabled"),scope_Handles[handleNumber].handle.setAttribute("tabindex","0")):(scope_Target.removeAttribute("disabled"),scope_Handles.forEach(function(handle){handle.removeAttribute("disabled"),handle.handle.setAttribute("tabindex","0")}))}__name(enable,"enable"),__name2(enable,"enable");function removeTooltips(){scope_Tooltips&&(removeEvent("update"+INTERNAL_EVENT_NS.tooltips),scope_Tooltips.forEach(function(tooltip){tooltip&&removeElement(tooltip)}),scope_Tooltips=null)}__name(removeTooltips,"removeTooltips"),__name2(removeTooltips,"removeTooltips");function tooltips(){removeTooltips(),scope_Tooltips=scope_Handles.map(addTooltip),bindEvent("update"+INTERNAL_EVENT_NS.tooltips,function(values,handleNumber,unencoded){if(!(!scope_Tooltips||!options.tooltips)&&scope_Tooltips[handleNumber]!==!1){var formattedValue=values[handleNumber];options.tooltips[handleNumber]!==!0&&(formattedValue=options.tooltips[handleNumber].to(unencoded[handleNumber])),scope_Tooltips[handleNumber].innerHTML=formattedValue}})}__name(tooltips,"tooltips"),__name2(tooltips,"tooltips");function aria(){removeEvent("update"+INTERNAL_EVENT_NS.aria),bindEvent("update"+INTERNAL_EVENT_NS.aria,function(values,handleNumber,unencoded,tap,positions){scope_HandleNumbers.forEach(function(index2){var handle=scope_Handles[index2],min=checkHandlePosition(scope_Locations,index2,0,!0,!0,!0),max=checkHandlePosition(scope_Locations,index2,100,!0,!0,!0),now2=positions[index2],text=String(options.ariaFormat.to(unencoded[index2]));min=scope_Spectrum.fromStepping(min).toFixed(1),max=scope_Spectrum.fromStepping(max).toFixed(1),now2=scope_Spectrum.fromStepping(now2).toFixed(1),handle.children[0].setAttribute("aria-valuemin",min),handle.children[0].setAttribute("aria-valuemax",max),handle.children[0].setAttribute("aria-valuenow",now2),handle.children[0].setAttribute("aria-valuetext",text)})})}__name(aria,"aria"),__name2(aria,"aria");function getGroup(pips2){if(pips2.mode===PipsMode.Range||pips2.mode===PipsMode.Steps)return scope_Spectrum.xVal;if(pips2.mode===PipsMode.Count){if(pips2.values<2)throw new Error("noUiSlider: 'values' (>= 2) required for mode 'count'.");for(var interval=pips2.values-1,spread=100/interval,values=[];interval--;)values[interval]=interval*spread;return values.push(100),mapToRange(values,pips2.stepped)}return pips2.mode===PipsMode.Positions?mapToRange(pips2.values,pips2.stepped):pips2.mode===PipsMode.Values?pips2.stepped?pips2.values.map(function(value){return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)))}):pips2.values:[]}__name(getGroup,"getGroup"),__name2(getGroup,"getGroup");function mapToRange(values,stepped){return values.map(function(value){return scope_Spectrum.fromStepping(stepped?scope_Spectrum.getStep(value):value)})}__name(mapToRange,"mapToRange"),__name2(mapToRange,"mapToRange");function generateSpread(pips2){function safeIncrement(value,increment){return Number((value+increment).toFixed(7))}__name(safeIncrement,"safeIncrement"),__name2(safeIncrement,"safeIncrement");var group=getGroup(pips2),indexes={},firstInRange=scope_Spectrum.xVal[0],lastInRange=scope_Spectrum.xVal[scope_Spectrum.xVal.length-1],ignoreFirst=!1,ignoreLast=!1,prevPct=0;return group=unique(group.slice().sort(function(a,b){return a-b})),group[0]!==firstInRange&&(group.unshift(firstInRange),ignoreFirst=!0),group[group.length-1]!==lastInRange&&(group.push(lastInRange),ignoreLast=!0),group.forEach(function(current,index2){var step,i,q,low=current,high=group[index2+1],newPct,pctDifference,pctPos,type,steps,realSteps,stepSize,isSteps=pips2.mode===PipsMode.Steps;for(isSteps&&(step=scope_Spectrum.xNumSteps[index2]),step||(step=high-low),high===void 0&&(high=low),step=Math.max(step,1e-7),i=low;i<=high;i=safeIncrement(i,step)){for(newPct=scope_Spectrum.toStepping(i),pctDifference=newPct-prevPct,steps=pctDifference/(pips2.density||1),realSteps=Math.round(steps),stepSize=pctDifference/realSteps,q=1;q<=realSteps;q+=1)pctPos=prevPct+q*stepSize,indexes[pctPos.toFixed(5)]=[scope_Spectrum.fromStepping(pctPos),0];type=group.indexOf(i)>-1?PipsType.LargeValue:isSteps?PipsType.SmallValue:PipsType.NoValue,!index2&&ignoreFirst&&i!==high&&(type=0),i===high&&ignoreLast||(indexes[newPct.toFixed(5)]=[i,type]),prevPct=newPct}}),indexes}__name(generateSpread,"generateSpread"),__name2(generateSpread,"generateSpread");function addMarking(spread,filterFunc,formatter){var _a3,_b2,element=scope_Document.createElement("div"),valueSizeClasses=(_a3={},_a3[PipsType.None]="",_a3[PipsType.NoValue]=options.cssClasses.valueNormal,_a3[PipsType.LargeValue]=options.cssClasses.valueLarge,_a3[PipsType.SmallValue]=options.cssClasses.valueSub,_a3),markerSizeClasses=(_b2={},_b2[PipsType.None]="",_b2[PipsType.NoValue]=options.cssClasses.markerNormal,_b2[PipsType.LargeValue]=options.cssClasses.markerLarge,_b2[PipsType.SmallValue]=options.cssClasses.markerSub,_b2),valueOrientationClasses=[options.cssClasses.valueHorizontal,options.cssClasses.valueVertical],markerOrientationClasses=[options.cssClasses.markerHorizontal,options.cssClasses.markerVertical];addClass(element,options.cssClasses.pips),addClass(element,options.ort===0?options.cssClasses.pipsHorizontal:options.cssClasses.pipsVertical);function getClasses(type,source){var a=source===options.cssClasses.value,orientationClasses=a?valueOrientationClasses:markerOrientationClasses,sizeClasses=a?valueSizeClasses:markerSizeClasses;return source+" "+orientationClasses[options.ort]+" "+sizeClasses[type]}__name(getClasses,"getClasses"),__name2(getClasses,"getClasses");function addSpread(offset2,value,type){if(type=filterFunc?filterFunc(value,type):type,type!==PipsType.None){var node=addNodeTo(element,!1);node.className=getClasses(type,options.cssClasses.marker),node.style[options.style]=offset2+"%",type>PipsType.NoValue&&(node=addNodeTo(element,!1),node.className=getClasses(type,options.cssClasses.value),node.setAttribute("data-value",String(value)),node.style[options.style]=offset2+"%",node.innerHTML=String(formatter.to(value)))}}return __name(addSpread,"addSpread"),__name2(addSpread,"addSpread"),Object.keys(spread).forEach(function(offset2){addSpread(offset2,spread[offset2][0],spread[offset2][1])}),element}__name(addMarking,"addMarking"),__name2(addMarking,"addMarking");function removePips(){scope_Pips&&(removeElement(scope_Pips),scope_Pips=null)}__name(removePips,"removePips"),__name2(removePips,"removePips");function pips(pips2){removePips();var spread=generateSpread(pips2),filter2=pips2.filter,format=pips2.format||{to:function(value){return String(Math.round(value))}};return scope_Pips=scope_Target.appendChild(addMarking(spread,filter2,format)),scope_Pips}__name(pips,"pips"),__name2(pips,"pips");function baseSize(){var rect=scope_Base.getBoundingClientRect(),alt="offset"+["Width","Height"][options.ort];return options.ort===0?rect.width||scope_Base[alt]:rect.height||scope_Base[alt]}__name(baseSize,"baseSize"),__name2(baseSize,"baseSize");function attachEvent(events,element,callback,data){var method=__name2(function(event){var e=fixEvent(event,data.pageOffset,data.target||element);if(!e||isSliderDisabled()&&!data.doNotReject||hasClass(scope_Target,options.cssClasses.tap)&&!data.doNotReject||events===actions.start&&e.buttons!==void 0&&e.buttons>1||data.hover&&e.buttons)return!1;supportsPassive||e.preventDefault(),e.calcPoint=e.points[options.ort],callback(e,data)},"method"),methods=[];return events.split(" ").forEach(function(eventName){element.addEventListener(eventName,method,supportsPassive?{passive:!0}:!1),methods.push([eventName,method])}),methods}__name(attachEvent,"attachEvent"),__name2(attachEvent,"attachEvent");function fixEvent(e,pageOffset,eventTarget){var touch=e.type.indexOf("touch")===0,mouse=e.type.indexOf("mouse")===0,pointer=e.type.indexOf("pointer")===0,x=0,y=0;if(e.type.indexOf("MSPointer")===0&&(pointer=!0),e.type==="mousedown"&&!e.buttons&&!e.touches)return!1;if(touch){var isTouchOnTarget=__name2(function(checkTouch){var target2=checkTouch.target;return target2===eventTarget||eventTarget.contains(target2)||e.composed&&e.composedPath().shift()===eventTarget},"isTouchOnTarget");if(e.type==="touchstart"){var targetTouches=Array.prototype.filter.call(e.touches,isTouchOnTarget);if(targetTouches.length>1)return!1;x=targetTouches[0].pageX,y=targetTouches[0].pageY}else{var targetTouch=Array.prototype.find.call(e.changedTouches,isTouchOnTarget);if(!targetTouch)return!1;x=targetTouch.pageX,y=targetTouch.pageY}}return pageOffset=pageOffset||getPageOffset(scope_Document),(mouse||pointer)&&(x=e.clientX+pageOffset.x,y=e.clientY+pageOffset.y),e.pageOffset=pageOffset,e.points=[x,y],e.cursor=mouse||pointer,e}__name(fixEvent,"fixEvent"),__name2(fixEvent,"fixEvent");function calcPointToPercentage(calcPoint){var location=calcPoint-offset(scope_Base,options.ort),proposal=location*100/baseSize();return proposal=limit(proposal),options.dir?100-proposal:proposal}__name(calcPointToPercentage,"calcPointToPercentage"),__name2(calcPointToPercentage,"calcPointToPercentage");function getClosestHandle(clickedPosition){var smallestDifference=100,handleNumber=!1;return scope_Handles.forEach(function(handle,index2){if(!isHandleDisabled(index2)){var handlePosition=scope_Locations[index2],differenceWithThisHandle=Math.abs(handlePosition-clickedPosition),clickAtEdge=differenceWithThisHandle===100&&smallestDifference===100,isCloser=differenceWithThisHandle<smallestDifference,isCloserAfter=differenceWithThisHandle<=smallestDifference&&clickedPosition>handlePosition;(isCloser||isCloserAfter||clickAtEdge)&&(handleNumber=index2,smallestDifference=differenceWithThisHandle)}}),handleNumber}__name(getClosestHandle,"getClosestHandle"),__name2(getClosestHandle,"getClosestHandle");function documentLeave(event,data){event.type==="mouseout"&&event.target.nodeName==="HTML"&&event.relatedTarget===null&&eventEnd(event,data)}__name(documentLeave,"documentLeave"),__name2(documentLeave,"documentLeave");function eventMove(event,data){if(navigator.appVersion.indexOf("MSIE 9")===-1&&event.buttons===0&&data.buttonsProperty!==0)return eventEnd(event,data);var movement=(options.dir?-1:1)*(event.calcPoint-data.startCalcPoint),proposal=movement*100/data.baseSize;moveHandles(movement>0,proposal,data.locations,data.handleNumbers,data.connect)}__name(eventMove,"eventMove"),__name2(eventMove,"eventMove");function eventEnd(event,data){data.handle&&(removeClass(data.handle,options.cssClasses.active),scope_ActiveHandlesCount-=1),data.listeners.forEach(function(c){scope_DocumentElement.removeEventListener(c[0],c[1])}),scope_ActiveHandlesCount===0&&(removeClass(scope_Target,options.cssClasses.drag),setZindex(),event.cursor&&(scope_Body.style.cursor="",scope_Body.removeEventListener("selectstart",preventDefault))),options.events.smoothSteps&&(data.handleNumbers.forEach(function(handleNumber){setHandle(handleNumber,scope_Locations[handleNumber],!0,!0,!1,!1)}),data.handleNumbers.forEach(function(handleNumber){fireEvent("update",handleNumber)})),data.handleNumbers.forEach(function(handleNumber){fireEvent("change",handleNumber),fireEvent("set",handleNumber),fireEvent("end",handleNumber)})}__name(eventEnd,"eventEnd"),__name2(eventEnd,"eventEnd");function eventStart(event,data){if(!data.handleNumbers.some(isHandleDisabled)){var handle;if(data.handleNumbers.length===1){var handleOrigin=scope_Handles[data.handleNumbers[0]];handle=handleOrigin.children[0],scope_ActiveHandlesCount+=1,addClass(handle,options.cssClasses.active)}event.stopPropagation();var listeners=[],moveEvent=attachEvent(actions.move,scope_DocumentElement,eventMove,{target:event.target,handle,connect:data.connect,listeners,startCalcPoint:event.calcPoint,baseSize:baseSize(),pageOffset:event.pageOffset,handleNumbers:data.handleNumbers,buttonsProperty:event.buttons,locations:scope_Locations.slice()}),endEvent=attachEvent(actions.end,scope_DocumentElement,eventEnd,{target:event.target,handle,listeners,doNotReject:!0,handleNumbers:data.handleNumbers}),outEvent=attachEvent("mouseout",scope_DocumentElement,documentLeave,{target:event.target,handle,listeners,doNotReject:!0,handleNumbers:data.handleNumbers});listeners.push.apply(listeners,moveEvent.concat(endEvent,outEvent)),event.cursor&&(scope_Body.style.cursor=getComputedStyle(event.target).cursor,scope_Handles.length>1&&addClass(scope_Target,options.cssClasses.drag),scope_Body.addEventListener("selectstart",preventDefault,!1)),data.handleNumbers.forEach(function(handleNumber){fireEvent("start",handleNumber)})}}__name(eventStart,"eventStart"),__name2(eventStart,"eventStart");function eventTap(event){event.stopPropagation();var proposal=calcPointToPercentage(event.calcPoint),handleNumber=getClosestHandle(proposal);handleNumber!==!1&&(options.events.snap||addClassFor(scope_Target,options.cssClasses.tap,options.animationDuration),setHandle(handleNumber,proposal,!0,!0),setZindex(),fireEvent("slide",handleNumber,!0),fireEvent("update",handleNumber,!0),options.events.snap?eventStart(event,{handleNumbers:[handleNumber]}):(fireEvent("change",handleNumber,!0),fireEvent("set",handleNumber,!0)))}__name(eventTap,"eventTap"),__name2(eventTap,"eventTap");function eventHover(event){var proposal=calcPointToPercentage(event.calcPoint),to=scope_Spectrum.getStep(proposal),value=scope_Spectrum.fromStepping(to);Object.keys(scope_Events).forEach(function(targetEvent){targetEvent.split(".")[0]==="hover"&&scope_Events[targetEvent].forEach(function(callback){callback.call(scope_Self,value)})})}__name(eventHover,"eventHover"),__name2(eventHover,"eventHover");function eventKeydown(event,handleNumber){if(isSliderDisabled()||isHandleDisabled(handleNumber))return!1;var horizontalKeys=["Left","Right"],verticalKeys=["Down","Up"],largeStepKeys=["PageDown","PageUp"],edgeKeys=["Home","End"];options.dir&&!options.ort?horizontalKeys.reverse():options.ort&&!options.dir&&(verticalKeys.reverse(),largeStepKeys.reverse());var key=event.key.replace("Arrow",""),isLargeDown=key===largeStepKeys[0],isLargeUp=key===largeStepKeys[1],isDown=key===verticalKeys[0]||key===horizontalKeys[0]||isLargeDown,isUp=key===verticalKeys[1]||key===horizontalKeys[1]||isLargeUp,isMin=key===edgeKeys[0],isMax=key===edgeKeys[1];if(!isDown&&!isUp&&!isMin&&!isMax)return!0;event.preventDefault();var to;if(isUp||isDown){var direction=isDown?0:1,steps=getNextStepsForHandle(handleNumber),step=steps[direction];if(step===null)return!1;step===!1&&(step=scope_Spectrum.getDefaultStep(scope_Locations[handleNumber],isDown,options.keyboardDefaultStep)),isLargeUp||isLargeDown?step*=options.keyboardPageMultiplier:step*=options.keyboardMultiplier,step=Math.max(step,1e-7),step=(isDown?-1:1)*step,to=scope_Values[handleNumber]+step}else isMax?to=options.spectrum.xVal[options.spectrum.xVal.length-1]:to=options.spectrum.xVal[0];return setHandle(handleNumber,scope_Spectrum.toStepping(to),!0,!0),fireEvent("slide",handleNumber),fireEvent("update",handleNumber),fireEvent("change",handleNumber),fireEvent("set",handleNumber),!1}__name(eventKeydown,"eventKeydown"),__name2(eventKeydown,"eventKeydown");function bindSliderEvents(behaviour){behaviour.fixed||scope_Handles.forEach(function(handle,index2){attachEvent(actions.start,handle.children[0],eventStart,{handleNumbers:[index2]})}),behaviour.tap&&attachEvent(actions.start,scope_Base,eventTap,{}),behaviour.hover&&attachEvent(actions.move,scope_Base,eventHover,{hover:!0}),behaviour.drag&&scope_Connects.forEach(function(connect,index2){if(!(connect===!1||index2===0||index2===scope_Connects.length-1)){var handleBefore=scope_Handles[index2-1],handleAfter=scope_Handles[index2],eventHolders=[connect],handlesToDrag=[handleBefore,handleAfter],handleNumbersToDrag=[index2-1,index2];addClass(connect,options.cssClasses.draggable),behaviour.fixed&&(eventHolders.push(handleBefore.children[0]),eventHolders.push(handleAfter.children[0])),behaviour.dragAll&&(handlesToDrag=scope_Handles,handleNumbersToDrag=scope_HandleNumbers),eventHolders.forEach(function(eventHolder){attachEvent(actions.start,eventHolder,eventStart,{handles:handlesToDrag,handleNumbers:handleNumbersToDrag,connect})})}})}__name(bindSliderEvents,"bindSliderEvents"),__name2(bindSliderEvents,"bindSliderEvents");function bindEvent(namespacedEvent,callback){scope_Events[namespacedEvent]=scope_Events[namespacedEvent]||[],scope_Events[namespacedEvent].push(callback),namespacedEvent.split(".")[0]==="update"&&scope_Handles.forEach(function(a,index2){fireEvent("update",index2)})}__name(bindEvent,"bindEvent"),__name2(bindEvent,"bindEvent");function isInternalNamespace(namespace){return namespace===INTERNAL_EVENT_NS.aria||namespace===INTERNAL_EVENT_NS.tooltips}__name(isInternalNamespace,"isInternalNamespace"),__name2(isInternalNamespace,"isInternalNamespace");function removeEvent(namespacedEvent){var event=namespacedEvent&&namespacedEvent.split(".")[0],namespace=event?namespacedEvent.substring(event.length):namespacedEvent;Object.keys(scope_Events).forEach(function(bind){var tEvent=bind.split(".")[0],tNamespace=bind.substring(tEvent.length);(!event||event===tEvent)&&(!namespace||namespace===tNamespace)&&(!isInternalNamespace(tNamespace)||namespace===tNamespace)&&delete scope_Events[bind]})}__name(removeEvent,"removeEvent"),__name2(removeEvent,"removeEvent");function fireEvent(eventName,handleNumber,tap){Object.keys(scope_Events).forEach(function(targetEvent){var eventType=targetEvent.split(".")[0];eventName===eventType&&scope_Events[targetEvent].forEach(function(callback){callback.call(scope_Self,scope_Values.map(options.format.to),handleNumber,scope_Values.slice(),tap||!1,scope_Locations.slice(),scope_Self)})})}__name(fireEvent,"fireEvent"),__name2(fireEvent,"fireEvent");function checkHandlePosition(reference,handleNumber,to,lookBackward,lookForward,getValue,smoothSteps){var distance;return scope_Handles.length>1&&!options.events.unconstrained&&(lookBackward&&handleNumber>0&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber-1],options.margin,!1),to=Math.max(to,distance)),lookForward&&handleNumber<scope_Handles.length-1&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber+1],options.margin,!0),to=Math.min(to,distance))),scope_Handles.length>1&&options.limit&&(lookBackward&&handleNumber>0&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber-1],options.limit,!1),to=Math.min(to,distance)),lookForward&&handleNumber<scope_Handles.length-1&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber+1],options.limit,!0),to=Math.max(to,distance))),options.padding&&(handleNumber===0&&(distance=scope_Spectrum.getAbsoluteDistance(0,options.padding[0],!1),to=Math.max(to,distance)),handleNumber===scope_Handles.length-1&&(distance=scope_Spectrum.getAbsoluteDistance(100,options.padding[1],!0),to=Math.min(to,distance))),smoothSteps||(to=scope_Spectrum.getStep(to)),to=limit(to),to===reference[handleNumber]&&!getValue?!1:to}__name(checkHandlePosition,"checkHandlePosition"),__name2(checkHandlePosition,"checkHandlePosition");function inRuleOrder(v,a){var o=options.ort;return(o?a:v)+", "+(o?v:a)}__name(inRuleOrder,"inRuleOrder"),__name2(inRuleOrder,"inRuleOrder");function moveHandles(upward,proposal,locations,handleNumbers,connect){var proposals=locations.slice(),firstHandle=handleNumbers[0],smoothSteps=options.events.smoothSteps,b=[!upward,upward],f2=[upward,!upward];handleNumbers=handleNumbers.slice(),upward&&handleNumbers.reverse(),handleNumbers.length>1?handleNumbers.forEach(function(handleNumber,o){var to=checkHandlePosition(proposals,handleNumber,proposals[handleNumber]+proposal,b[o],f2[o],!1,smoothSteps);to===!1?proposal=0:(proposal=to-proposals[handleNumber],proposals[handleNumber]=to)}):b=f2=[!0];var state=!1;handleNumbers.forEach(function(handleNumber,o){state=setHandle(handleNumber,locations[handleNumber]+proposal,b[o],f2[o],!1,smoothSteps)||state}),state&&(handleNumbers.forEach(function(handleNumber){fireEvent("update",handleNumber),fireEvent("slide",handleNumber)}),connect!=null&&fireEvent("drag",firstHandle))}__name(moveHandles,"moveHandles"),__name2(moveHandles,"moveHandles");function transformDirection(a,b){return options.dir?100-a-b:a}__name(transformDirection,"transformDirection"),__name2(transformDirection,"transformDirection");function updateHandlePosition(handleNumber,to){scope_Locations[handleNumber]=to,scope_Values[handleNumber]=scope_Spectrum.fromStepping(to);var translation=transformDirection(to,0)-scope_DirOffset,translateRule="translate("+inRuleOrder(translation+"%","0")+")";scope_Handles[handleNumber].style[options.transformRule]=translateRule,updateConnect(handleNumber),updateConnect(handleNumber+1)}__name(updateHandlePosition,"updateHandlePosition"),__name2(updateHandlePosition,"updateHandlePosition");function setZindex(){scope_HandleNumbers.forEach(function(handleNumber){var dir=scope_Locations[handleNumber]>50?-1:1,zIndex=3+(scope_Handles.length+dir*handleNumber);scope_Handles[handleNumber].style.zIndex=String(zIndex)})}__name(setZindex,"setZindex"),__name2(setZindex,"setZindex");function setHandle(handleNumber,to,lookBackward,lookForward,exactInput,smoothSteps){return exactInput||(to=checkHandlePosition(scope_Locations,handleNumber,to,lookBackward,lookForward,!1,smoothSteps)),to===!1?!1:(updateHandlePosition(handleNumber,to),!0)}__name(setHandle,"setHandle"),__name2(setHandle,"setHandle");function updateConnect(index2){if(scope_Connects[index2]){var l2=0,h=100;index2!==0&&(l2=scope_Locations[index2-1]),index2!==scope_Connects.length-1&&(h=scope_Locations[index2]);var connectWidth=h-l2,translateRule="translate("+inRuleOrder(transformDirection(l2,connectWidth)+"%","0")+")",scaleRule="scale("+inRuleOrder(connectWidth/100,"1")+")";scope_Connects[index2].style[options.transformRule]=translateRule+" "+scaleRule}}__name(updateConnect,"updateConnect"),__name2(updateConnect,"updateConnect");function resolveToValue(to,handleNumber){return to===null||to===!1||to===void 0||(typeof to=="number"&&(to=String(to)),to=options.format.from(to),to!==!1&&(to=scope_Spectrum.toStepping(to)),to===!1||isNaN(to))?scope_Locations[handleNumber]:to}__name(resolveToValue,"resolveToValue"),__name2(resolveToValue,"resolveToValue");function valueSet(input,fireSetEvent,exactInput){var values=asArray(input),isInit=scope_Locations[0]===void 0;fireSetEvent=fireSetEvent===void 0?!0:fireSetEvent,options.animate&&!isInit&&addClassFor(scope_Target,options.cssClasses.tap,options.animationDuration),scope_HandleNumbers.forEach(function(handleNumber){setHandle(handleNumber,resolveToValue(values[handleNumber],handleNumber),!0,!1,exactInput)});var i=scope_HandleNumbers.length===1?0:1;if(isInit&&scope_Spectrum.hasNoSize()&&(exactInput=!0,scope_Locations[0]=0,scope_HandleNumbers.length>1)){var space_1=100/(scope_HandleNumbers.length-1);scope_HandleNumbers.forEach(function(handleNumber){scope_Locations[handleNumber]=handleNumber*space_1})}for(;i<scope_HandleNumbers.length;++i)scope_HandleNumbers.forEach(function(handleNumber){setHandle(handleNumber,scope_Locations[handleNumber],!0,!0,exactInput)});setZindex(),scope_HandleNumbers.forEach(function(handleNumber){fireEvent("update",handleNumber),values[handleNumber]!==null&&fireSetEvent&&fireEvent("set",handleNumber)})}__name(valueSet,"valueSet"),__name2(valueSet,"valueSet");function valueReset(fireSetEvent){valueSet(options.start,fireSetEvent)}__name(valueReset,"valueReset"),__name2(valueReset,"valueReset");function valueSetHandle(handleNumber,value,fireSetEvent,exactInput){if(handleNumber=Number(handleNumber),!(handleNumber>=0&&handleNumber<scope_HandleNumbers.length))throw new Error("noUiSlider: invalid handle number, got: "+handleNumber);setHandle(handleNumber,resolveToValue(value,handleNumber),!0,!0,exactInput),fireEvent("update",handleNumber),fireSetEvent&&fireEvent("set",handleNumber)}__name(valueSetHandle,"valueSetHandle"),__name2(valueSetHandle,"valueSetHandle");function valueGet(unencoded){if(unencoded===void 0&&(unencoded=!1),unencoded)return scope_Values.length===1?scope_Values[0]:scope_Values.slice(0);var values=scope_Values.map(options.format.to);return values.length===1?values[0]:values}__name(valueGet,"valueGet"),__name2(valueGet,"valueGet");function destroy2(){for(removeEvent(INTERNAL_EVENT_NS.aria),removeEvent(INTERNAL_EVENT_NS.tooltips),Object.keys(options.cssClasses).forEach(function(key){removeClass(scope_Target,options.cssClasses[key])});scope_Target.firstChild;)scope_Target.removeChild(scope_Target.firstChild);delete scope_Target.noUiSlider}__name(destroy2,"destroy2"),__name2(destroy2,"destroy");function getNextStepsForHandle(handleNumber){var location=scope_Locations[handleNumber],nearbySteps=scope_Spectrum.getNearbySteps(location),value=scope_Values[handleNumber],increment=nearbySteps.thisStep.step,decrement=null;if(options.snap)return[value-nearbySteps.stepBefore.startValue||null,nearbySteps.stepAfter.startValue-value||null];increment!==!1&&value+increment>nearbySteps.stepAfter.startValue&&(increment=nearbySteps.stepAfter.startValue-value),value>nearbySteps.thisStep.startValue?decrement=nearbySteps.thisStep.step:nearbySteps.stepBefore.step===!1?decrement=!1:decrement=value-nearbySteps.stepBefore.highestStep,location===100?increment=null:location===0&&(decrement=null);var stepDecimals=scope_Spectrum.countStepDecimals();return increment!==null&&increment!==!1&&(increment=Number(increment.toFixed(stepDecimals))),decrement!==null&&decrement!==!1&&(decrement=Number(decrement.toFixed(stepDecimals))),[decrement,increment]}__name(getNextStepsForHandle,"getNextStepsForHandle"),__name2(getNextStepsForHandle,"getNextStepsForHandle");function getNextSteps(){return scope_HandleNumbers.map(getNextStepsForHandle)}__name(getNextSteps,"getNextSteps"),__name2(getNextSteps,"getNextSteps");function updateOptions(optionsToUpdate,fireSetEvent){var v=valueGet(),updateAble=["margin","limit","padding","range","animate","snap","step","format","pips","tooltips"];updateAble.forEach(function(name2){optionsToUpdate[name2]!==void 0&&(originalOptions[name2]=optionsToUpdate[name2])});var newOptions=testOptions(originalOptions);updateAble.forEach(function(name2){optionsToUpdate[name2]!==void 0&&(options[name2]=newOptions[name2])}),scope_Spectrum=newOptions.spectrum,options.margin=newOptions.margin,options.limit=newOptions.limit,options.padding=newOptions.padding,options.pips?pips(options.pips):removePips(),options.tooltips?tooltips():removeTooltips(),scope_Locations=[],valueSet(isSet(optionsToUpdate.start)?optionsToUpdate.start:v,fireSetEvent)}__name(updateOptions,"updateOptions"),__name2(updateOptions,"updateOptions");function setupSlider(){scope_Base=addSlider(scope_Target),addElements(options.connect,scope_Base),bindSliderEvents(options.events),valueSet(options.start),options.pips&&pips(options.pips),options.tooltips&&tooltips(),aria()}__name(setupSlider,"setupSlider"),__name2(setupSlider,"setupSlider"),setupSlider();var scope_Self={destroy:destroy2,steps:getNextSteps,on:bindEvent,off:removeEvent,get:valueGet,set:valueSet,setHandle:valueSetHandle,reset:valueReset,disable,enable,__moveHandles:function(upward,proposal,handleNumbers){moveHandles(upward,proposal,scope_Locations,handleNumbers)},options:originalOptions,updateOptions,target:scope_Target,removePips,removeTooltips,getPositions:function(){return scope_Locations.slice()},getTooltips:function(){return scope_Tooltips},getOrigins:function(){return scope_Handles},pips};return scope_Self}__name(scope,"scope"),__name2(scope,"scope");function initialize(target,originalOptions){if(!target||!target.nodeName)throw new Error("noUiSlider: create requires a single element, got: "+target);if(target.noUiSlider)throw new Error("noUiSlider: Slider was already initialized.");var options=testOptions(originalOptions),api=scope(target,options,originalOptions);return target.noUiSlider=api,api}__name(initialize,"initialize"),__name2(initialize,"initialize");const noUiSlider={__spectrum:Spectrum,cssClasses,create:initialize};export{jsonParseLinter as A,fromPairs as B,maxBy as C,Duration as D,EditorView as E,sumBy as F,DateTime as G,noUiSlider as H,Interval as I,findLast as J,omitBy as K,MiniSearch as M,PipsMode as P,Sortable as S,Tagify as T,UUIDv5 as U,mapValues as a,isObject as b,compact as c,isEmpty as d,equals as e,pipe as f,groupBy as g,map as h,isNil as i,filter as j,keys$1 as k,uniqBy as l,mapToObj as m,difference as n,omit as o,pick$1 as p,meanBy as q,basicSetup as r,sortBy as s,json as t,uniq as u,linter as v,keymap as w,indentWithTab as x,autocompletion as y,syntaxTree as z};