tutuca 0.9.64 → 0.9.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/tutuca-cli.js +27 -11
- package/dist/tutuca-dev.js +46 -20
- package/dist/tutuca-dev.min.js +2 -2
- package/dist/tutuca-extra.js +30 -12
- package/dist/tutuca-extra.min.js +2 -2
- package/dist/tutuca.js +30 -12
- package/dist/tutuca.min.js +2 -2
- package/package.json +1 -1
- package/skill/tutuca/core.md +28 -5
- package/skill/tutuca/testing.md +6 -3
package/dist/tutuca-dev.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
var __defProp=Object.defineProperty,__defNormalProp=(obj,key,value)=>(key in obj)?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__name=(target,value)=>__defProp(target,"name",{value,configurable:!0}),__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value),utils_exports={};__export(utils_exports,{addChainableMethod:()=>addChainableMethod,addLengthGuard:()=>addLengthGuard,addMethod:()=>addMethod,addProperty:()=>addProperty,checkError:()=>check_error_exports,compareByInspect:()=>compareByInspect,eql:()=>deep_eql_default,events:()=>events,expectTypes:()=>expectTypes,flag:()=>flag,getActual:()=>getActual,getMessage:()=>getMessage2,getName:()=>getName,getOperator:()=>getOperator,getOwnEnumerableProperties:()=>getOwnEnumerableProperties,getOwnEnumerablePropertySymbols:()=>getOwnEnumerablePropertySymbols,getPathInfo:()=>getPathInfo,hasProperty:()=>hasProperty,inspect:()=>inspect2,isNaN:()=>isNaN2,isNumeric:()=>isNumeric,isProxyEnabled:()=>isProxyEnabled,isRegExp:()=>isRegExp2,objDisplay:()=>objDisplay,overwriteChainableMethod:()=>overwriteChainableMethod,overwriteMethod:()=>overwriteMethod,overwriteProperty:()=>overwriteProperty,proxify:()=>proxify,test:()=>test,transferFlags:()=>transferFlags,type:()=>type});var check_error_exports={};__export(check_error_exports,{compatibleConstructor:()=>compatibleConstructor,compatibleInstance:()=>compatibleInstance,compatibleMessage:()=>compatibleMessage,getConstructorName:()=>getConstructorName,getMessage:()=>getMessage});function isErrorInstance(obj){return obj instanceof Error||Object.prototype.toString.call(obj)==="[object Error]"}__name(isErrorInstance,"isErrorInstance");function isRegExp(obj){return Object.prototype.toString.call(obj)==="[object RegExp]"}__name(isRegExp,"isRegExp");function compatibleInstance(thrown,errorLike){return isErrorInstance(errorLike)&&thrown===errorLike}__name(compatibleInstance,"compatibleInstance");function compatibleConstructor(thrown,errorLike){if(isErrorInstance(errorLike))return thrown.constructor===errorLike.constructor||thrown instanceof errorLike.constructor;else if((typeof errorLike==="object"||typeof errorLike==="function")&&errorLike.prototype)return thrown.constructor===errorLike||thrown instanceof errorLike;return!1}__name(compatibleConstructor,"compatibleConstructor");function compatibleMessage(thrown,errMatcher){let comparisonString=typeof thrown==="string"?thrown:thrown.message;if(isRegExp(errMatcher))return errMatcher.test(comparisonString);else if(typeof errMatcher==="string")return comparisonString.indexOf(errMatcher)!==-1;return!1}__name(compatibleMessage,"compatibleMessage");function getConstructorName(errorLike){let constructorName=errorLike;if(isErrorInstance(errorLike))constructorName=errorLike.constructor.name;else if(typeof errorLike==="function"){if(constructorName=errorLike.name,constructorName==="")constructorName=new errorLike().name||constructorName}return constructorName}__name(getConstructorName,"getConstructorName");function getMessage(errorLike){let msg="";if(errorLike&&errorLike.message)msg=errorLike.message;else if(typeof errorLike==="string")msg=errorLike;return msg}__name(getMessage,"getMessage");function flag(obj,key,value){let flags=obj.__flags||(obj.__flags=Object.create(null));if(arguments.length===3)flags[key]=value;else return flags[key]}__name(flag,"flag");function test(obj,args){let negate=flag(obj,"negate"),expr=args[0];return negate?!expr:expr}__name(test,"test");function type(obj){if(typeof obj>"u")return"undefined";if(obj===null)return"null";let stringTag=obj[Symbol.toStringTag];if(typeof stringTag==="string")return stringTag;return Object.prototype.toString.call(obj).slice(8,-1)}__name(type,"type");var canElideFrames="captureStackTrace"in Error,_AssertionError=class _AssertionError2 extends Error{constructor(message="Unspecified AssertionError",props,ssf){super(message);if(__publicField(this,"message"),this.message=message,canElideFrames)Error.captureStackTrace(this,ssf||_AssertionError2);for(let key in props)if(!(key in this))this[key]=props[key]}get name(){return"AssertionError"}get ok(){return!1}toJSON(stack){return{...this,name:this.name,message:this.message,ok:!1,stack:stack!==!1?this.stack:void 0}}};__name(_AssertionError,"AssertionError");var AssertionError=_AssertionError;function expectTypes(obj,types){let flagMsg=flag(obj,"message"),ssfi=flag(obj,"ssfi");flagMsg=flagMsg?flagMsg+": ":"",obj=flag(obj,"object"),types=types.map(function(t){return t.toLowerCase()}),types.sort();let str=types.map(function(t,index){let art=~["a","e","i","o","u"].indexOf(t.charAt(0))?"an":"a";return(types.length>1&&index===types.length-1?"or ":"")+art+" "+t}).join(", "),objType=type(obj).toLowerCase();if(!types.some(function(expected){return objType===expected}))throw new AssertionError(flagMsg+"object tested must be "+str+", but "+objType+" given",void 0,ssfi)}__name(expectTypes,"expectTypes");function getActual(obj,args){return args.length>4?args[4]:obj._obj}__name(getActual,"getActual");var ansiColors={bold:["1","22"],dim:["2","22"],italic:["3","23"],underline:["4","24"],inverse:["7","27"],hidden:["8","28"],strike:["9","29"],black:["30","39"],red:["31","39"],green:["32","39"],yellow:["33","39"],blue:["34","39"],magenta:["35","39"],cyan:["36","39"],white:["37","39"],brightblack:["30;1","39"],brightred:["31;1","39"],brightgreen:["32;1","39"],brightyellow:["33;1","39"],brightblue:["34;1","39"],brightmagenta:["35;1","39"],brightcyan:["36;1","39"],brightwhite:["37;1","39"],grey:["90","39"]},styles={special:"cyan",number:"yellow",bigint:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",symbol:"green",date:"magenta",regexp:"red"},truncator="…";function colorise(value,styleType){let color=ansiColors[styles[styleType]]||ansiColors[styleType]||"";if(!color)return String(value);return`\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m`}__name(colorise,"colorise");function normaliseOptions({showHidden=!1,depth=2,colors=!1,customInspect=!0,showProxy=!1,maxArrayLength=1/0,breakLength=1/0,seen=[],truncate:truncate2=1/0,stylize=String}={},inspect3){let options={showHidden:Boolean(showHidden),depth:Number(depth),colors:Boolean(colors),customInspect:Boolean(customInspect),showProxy:Boolean(showProxy),maxArrayLength:Number(maxArrayLength),breakLength:Number(breakLength),truncate:Number(truncate2),seen,inspect:inspect3,stylize};if(options.colors)options.stylize=colorise;return options}__name(normaliseOptions,"normaliseOptions");function isHighSurrogate(char){return char>="\uD800"&&char<="\uDBFF"}__name(isHighSurrogate,"isHighSurrogate");function truncate(string,length,tail=truncator){string=String(string);let tailLength=tail.length,stringLength=string.length;if(tailLength>length&&stringLength>tailLength)return tail;if(stringLength>length&&stringLength>tailLength){let end=length-tailLength;if(end>0&&isHighSurrogate(string[end-1]))end=end-1;return`${string.slice(0,end)}${tail}`}return string}__name(truncate,"truncate");function inspectList(list,options,inspectItem,separator=", "){inspectItem=inspectItem||options.inspect;let size=list.length;if(size===0)return"";let originalLength=options.truncate,output="",peek="",truncated="";for(let i=0;i<size;i+=1){let last=i+1===list.length,secondToLast=i+2===list.length;truncated=`${truncator}(${list.length-i})`;let value=list[i];options.truncate=originalLength-output.length-(last?0:separator.length);let string=peek||inspectItem(value,options)+(last?"":separator),nextLength=output.length+string.length,truncatedLength=nextLength+truncated.length;if(last&&nextLength>originalLength&&output.length+truncated.length<=originalLength)break;if(!last&&!secondToLast&&truncatedLength>originalLength)break;if(peek=last?"":inspectItem(list[i+1],options)+(secondToLast?"":separator),!last&&secondToLast&&truncatedLength>originalLength&&nextLength+peek.length>originalLength)break;if(output+=string,!last&&!secondToLast&&nextLength+peek.length>=originalLength){truncated=`${truncator}(${list.length-i-1})`;break}truncated=""}return`${output}${truncated}`}__name(inspectList,"inspectList");function quoteComplexKey(key){if(key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/))return key;return JSON.stringify(key).replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'")}__name(quoteComplexKey,"quoteComplexKey");function inspectProperty([key,value],options){if(options.truncate-=2,typeof key==="string")key=quoteComplexKey(key);else if(typeof key!=="number")key=`[${options.inspect(key,options)}]`;return options.truncate-=key.length,value=options.inspect(value,options),`${key}: ${value}`}__name(inspectProperty,"inspectProperty");function inspectArray(array,options){let nonIndexProperties=Object.keys(array).slice(array.length);if(!array.length&&!nonIndexProperties.length)return"[]";options.truncate-=4;let listContents=inspectList(array,options);options.truncate-=listContents.length;let propertyContents="";if(nonIndexProperties.length)propertyContents=inspectList(nonIndexProperties.map((key)=>[key,array[key]]),options,inspectProperty);return`[ ${listContents}${propertyContents?`, ${propertyContents}`:""} ]`}__name(inspectArray,"inspectArray");var getArrayName=__name((array)=>{if(typeof Buffer==="function"&&array instanceof Buffer)return"Buffer";if(array[Symbol.toStringTag])return array[Symbol.toStringTag];return array.constructor.name},"getArrayName");function inspectTypedArray(array,options){let name=getArrayName(array);options.truncate-=name.length+4;let nonIndexProperties=Object.keys(array).slice(array.length);if(!array.length&&!nonIndexProperties.length)return`${name}[]`;let output="";for(let i=0;i<array.length;i++){let string=`${options.stylize(truncate(array[i],options.truncate),"number")}${i===array.length-1?"":", "}`;if(options.truncate-=string.length,array[i]!==array.length&&options.truncate<=3){output+=`${truncator}(${array.length-array[i]+1})`;break}output+=string}let propertyContents="";if(nonIndexProperties.length)propertyContents=inspectList(nonIndexProperties.map((key)=>[key,array[key]]),options,inspectProperty);return`${name}[ ${output}${propertyContents?`, ${propertyContents}`:""} ]`}__name(inspectTypedArray,"inspectTypedArray");function inspectDate(dateObject,options){let stringRepresentation=dateObject.toJSON();if(stringRepresentation===null)return"Invalid Date";let split=stringRepresentation.split("T"),date=split[0];return options.stylize(`${date}T${truncate(split[1],options.truncate-date.length-1)}`,"date")}__name(inspectDate,"inspectDate");function inspectFunction(func,options){let functionType=func[Symbol.toStringTag]||"Function",name=func.name;if(!name)return options.stylize(`[${functionType}]`,"special");return options.stylize(`[${functionType} ${truncate(name,options.truncate-11)}]`,"special")}__name(inspectFunction,"inspectFunction");function inspectMapEntry([key,value],options){return options.truncate-=4,key=options.inspect(key,options),options.truncate-=key.length,value=options.inspect(value,options),`${key} => ${value}`}__name(inspectMapEntry,"inspectMapEntry");function mapToEntries(map){let entries=[];return map.forEach((value,key)=>{entries.push([key,value])}),entries}__name(mapToEntries,"mapToEntries");function inspectMap(map,options){if(map.size===0)return"Map{}";return options.truncate-=7,`Map{ ${inspectList(mapToEntries(map),options,inspectMapEntry)} }`}__name(inspectMap,"inspectMap");var isNaN=Number.isNaN||((i)=>i!==i);function inspectNumber(number,options){if(isNaN(number))return options.stylize("NaN","number");if(number===1/0)return options.stylize("Infinity","number");if(number===-1/0)return options.stylize("-Infinity","number");if(number===0)return options.stylize(1/number===1/0?"+0":"-0","number");return options.stylize(truncate(String(number),options.truncate),"number")}__name(inspectNumber,"inspectNumber");function inspectBigInt(number,options){let nums=truncate(number.toString(),options.truncate-1);if(nums!==truncator)nums+="n";return options.stylize(nums,"bigint")}__name(inspectBigInt,"inspectBigInt");function inspectRegExp(value,options){let flags=value.toString().split("/")[2],sourceLength=options.truncate-(2+flags.length),source=value.source;return options.stylize(`/${truncate(source,sourceLength)}/${flags}`,"regexp")}__name(inspectRegExp,"inspectRegExp");function arrayFromSet(set2){let values=[];return set2.forEach((value)=>{values.push(value)}),values}__name(arrayFromSet,"arrayFromSet");function inspectSet(set2,options){if(set2.size===0)return"Set{}";return options.truncate-=7,`Set{ ${inspectList(arrayFromSet(set2),options)} }`}__name(inspectSet,"inspectSet");var stringEscapeChars=new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]","g"),escapeCharacters={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r","'":"\\'","\\":"\\\\"},hex=16,unicodeLength=4;function escape(char){return escapeCharacters[char]||`\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-unicodeLength)}`}__name(escape,"escape");function inspectString(string,options){if(stringEscapeChars.test(string))string=string.replace(stringEscapeChars,escape);return options.stylize(`'${truncate(string,options.truncate-2)}'`,"string")}__name(inspectString,"inspectString");function inspectSymbol(value){if("description"in Symbol.prototype)return value.description?`Symbol(${value.description})`:"Symbol()";return value.toString()}__name(inspectSymbol,"inspectSymbol");var getPromiseValue=__name(()=>"Promise{…}","getPromiseValue"),promise_default=getPromiseValue;function inspectObject(object,options){let properties=Object.getOwnPropertyNames(object),symbols=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(object):[];if(properties.length===0&&symbols.length===0)return"{}";if(options.truncate-=4,options.seen=options.seen||[],options.seen.includes(object))return"[Circular]";options.seen.push(object);let propertyContents=inspectList(properties.map((key)=>[key,object[key]]),options,inspectProperty),symbolContents=inspectList(symbols.map((key)=>[key,object[key]]),options,inspectProperty);options.seen.pop();let sep="";if(propertyContents&&symbolContents)sep=", ";return`{ ${propertyContents}${sep}${symbolContents} }`}__name(inspectObject,"inspectObject");var toStringTag=typeof Symbol<"u"&&Symbol.toStringTag?Symbol.toStringTag:!1;function inspectClass(value,options){let name="";if(toStringTag&&toStringTag in value)name=value[toStringTag];if(name=name||value.constructor.name,!name||name==="_class")name="<Anonymous Class>";return options.truncate-=name.length,`${name}${inspectObject(value,options)}`}__name(inspectClass,"inspectClass");function inspectArguments(args,options){if(args.length===0)return"Arguments[]";return options.truncate-=13,`Arguments[ ${inspectList(args,options)} ]`}__name(inspectArguments,"inspectArguments");var errorKeys=["stack","line","column","name","message","fileName","lineNumber","columnNumber","number","description","cause"];function inspectObject2(error,options){let properties=Object.getOwnPropertyNames(error).filter((key)=>errorKeys.indexOf(key)===-1),name=error.name;options.truncate-=name.length;let message="";if(typeof error.message==="string")message=truncate(error.message,options.truncate);else properties.unshift("message");if(message=message?`: ${message}`:"",options.truncate-=message.length+5,options.seen=options.seen||[],options.seen.includes(error))return"[Circular]";options.seen.push(error);let propertyContents=inspectList(properties.map((key)=>[key,error[key]]),options,inspectProperty);return`${name}${message}${propertyContents?` { ${propertyContents} }`:""}`}__name(inspectObject2,"inspectObject");function inspectAttribute([key,value],options){if(options.truncate-=3,!value)return`${options.stylize(String(key),"yellow")}`;return`${options.stylize(String(key),"yellow")}=${options.stylize(`"${value}"`,"string")}`}__name(inspectAttribute,"inspectAttribute");function inspectNodeCollection(collection,options){return inspectList(collection,options,inspectNode,`
|
|
2
|
-
`)}__name(inspectNodeCollection,"inspectNodeCollection");function inspectNode(node,options){switch(node.nodeType){case 1:return inspectHTML(node,options);case 3:return options.inspect(node.data,options);default:return options.inspect(node,options)}}__name(inspectNode,"inspectNode");function inspectHTML(element,options){let properties=element.getAttributeNames(),name=element.tagName.toLowerCase(),head=options.stylize(`<${name}`,"special"),headClose=options.stylize(">","special"),tail=options.stylize(`</${name}>`,"special");options.truncate-=name.length*2+5;let propertyContents="";if(properties.length>0)propertyContents+=" ",propertyContents+=inspectList(properties.map((key)=>[key,element.getAttribute(key)]),options,inspectAttribute," ");options.truncate-=propertyContents.length;let truncate2=options.truncate,children=inspectNodeCollection(element.children,options);if(children&&children.length>truncate2)children=`${truncator}(${element.children.length})`;return`${head}${propertyContents}${headClose}${children}${tail}`}__name(inspectHTML,"inspectHTML");var symbolsSupported=typeof Symbol==="function"&&typeof Symbol.for==="function",chaiInspect=symbolsSupported?Symbol.for("chai/inspect"):"@@chai/inspect",nodeInspect=Symbol.for("nodejs.util.inspect.custom"),constructorMap=new WeakMap,stringTagMap={},baseTypesMap={undefined:__name((value,options)=>options.stylize("undefined","undefined"),"undefined"),null:__name((value,options)=>options.stylize("null","null"),"null"),boolean:__name((value,options)=>options.stylize(String(value),"boolean"),"boolean"),Boolean:__name((value,options)=>options.stylize(String(value),"boolean"),"Boolean"),number:inspectNumber,Number:inspectNumber,bigint:inspectBigInt,BigInt:inspectBigInt,string:inspectString,String:inspectString,function:inspectFunction,Function:inspectFunction,symbol:inspectSymbol,Symbol:inspectSymbol,Array:inspectArray,Date:inspectDate,Map:inspectMap,Set:inspectSet,RegExp:inspectRegExp,Promise:promise_default,WeakSet:__name((value,options)=>options.stylize("WeakSet{…}","special"),"WeakSet"),WeakMap:__name((value,options)=>options.stylize("WeakMap{…}","special"),"WeakMap"),Arguments:inspectArguments,Int8Array:inspectTypedArray,Uint8Array:inspectTypedArray,Uint8ClampedArray:inspectTypedArray,Int16Array:inspectTypedArray,Uint16Array:inspectTypedArray,Int32Array:inspectTypedArray,Uint32Array:inspectTypedArray,Float32Array:inspectTypedArray,Float64Array:inspectTypedArray,Generator:__name(()=>"","Generator"),DataView:__name(()=>"","DataView"),ArrayBuffer:__name(()=>"","ArrayBuffer"),Error:inspectObject2,HTMLCollection:inspectNodeCollection,NodeList:inspectNodeCollection},inspectCustom=__name((value,options,type3,inspectFn)=>{if(chaiInspect in value&&typeof value[chaiInspect]==="function")return value[chaiInspect](options);if(nodeInspect in value&&typeof value[nodeInspect]==="function")return value[nodeInspect](options.depth,options,inspectFn);if("inspect"in value&&typeof value.inspect==="function")return value.inspect(options.depth,options);if("constructor"in value&&constructorMap.has(value.constructor))return constructorMap.get(value.constructor)(value,options);if(stringTagMap[type3])return stringTagMap[type3](value,options);return""},"inspectCustom"),toString=Object.prototype.toString;function inspect(value,opts={}){let options=normaliseOptions(opts,inspect),{customInspect}=options,type3=value===null?"null":typeof value;if(type3==="object")type3=toString.call(value).slice(8,-1);if(type3 in baseTypesMap)return baseTypesMap[type3](value,options);if(customInspect&&value){let output=inspectCustom(value,options,type3,inspect);if(output){if(typeof output==="string")return output;return inspect(output,options)}}let proto=value?Object.getPrototypeOf(value):!1;if(proto===Object.prototype||proto===null)return inspectObject(value,options);if(value&&typeof HTMLElement==="function"&&value instanceof HTMLElement)return inspectHTML(value,options);if("constructor"in value){if(value.constructor!==Object)return inspectClass(value,options);return inspectObject(value,options)}if(value===Object(value))return inspectObject(value,options);return options.stylize(String(value),type3)}__name(inspect,"inspect");var config={includeStack:!1,showDiff:!0,truncateThreshold:40,useProxy:!0,proxyExcludedKeys:["then","catch","inspect","toJSON"],deepEqual:null};function inspect2(obj,showHidden,depth,colors){let options={colors,depth:typeof depth>"u"?2:depth,showHidden,truncate:config.truncateThreshold?config.truncateThreshold:1/0};return inspect(obj,options)}__name(inspect2,"inspect");function objDisplay(obj){let str=inspect2(obj),type3=Object.prototype.toString.call(obj);if(config.truncateThreshold&&str.length>=config.truncateThreshold)if(type3==="[object Function]")return!obj.name||obj.name===""?"[Function]":"[Function: "+obj.name+"]";else if(type3==="[object Array]")return"[ Array("+obj.length+") ]";else if(type3==="[object Object]"){let keys=Object.keys(obj);return"{ Object ("+(keys.length>2?keys.splice(0,2).join(", ")+", ...":keys.join(", "))+") }"}else return str;else return str}__name(objDisplay,"objDisplay");function getMessage2(obj,args){let negate=flag(obj,"negate"),val=flag(obj,"object"),expected=args[3],actual=getActual(obj,args),msg=negate?args[2]:args[1],flagMsg=flag(obj,"message");if(typeof msg==="function")msg=msg();return msg=msg||"",msg=msg.replace(/#\{this\}/g,function(){return objDisplay(val)}).replace(/#\{act\}/g,function(){return objDisplay(actual)}).replace(/#\{exp\}/g,function(){return objDisplay(expected)}),flagMsg?flagMsg+": "+msg:msg}__name(getMessage2,"getMessage");function transferFlags(assertion,object,includeAll){let flags=assertion.__flags||(assertion.__flags=Object.create(null));if(!object.__flags)object.__flags=Object.create(null);includeAll=arguments.length===3?includeAll:!0;for(let flag3 in flags)if(includeAll||flag3!=="object"&&flag3!=="ssfi"&&flag3!=="lockSsfi"&&flag3!="message")object.__flags[flag3]=flags[flag3]}__name(transferFlags,"transferFlags");function type2(obj){if(typeof obj>"u")return"undefined";if(obj===null)return"null";let stringTag=obj[Symbol.toStringTag];if(typeof stringTag==="string")return stringTag;let sliceStart=8,sliceEnd=-1;return Object.prototype.toString.call(obj).slice(sliceStart,sliceEnd)}__name(type2,"type");function FakeMap(){this._key="chai/deep-eql__"+Math.random()+Date.now()}__name(FakeMap,"FakeMap");FakeMap.prototype={get:__name(function(key){return key[this._key]},"get"),set:__name(function(key,value){if(Object.isExtensible(key))Object.defineProperty(key,this._key,{value,configurable:!0})},"set")};var MemoizeMap=typeof WeakMap==="function"?WeakMap:FakeMap;function memoizeCompare(leftHandOperand,rightHandOperand,memoizeMap){if(!memoizeMap||isPrimitive(leftHandOperand)||isPrimitive(rightHandOperand))return null;var leftHandMap=memoizeMap.get(leftHandOperand);if(leftHandMap){var result=leftHandMap.get(rightHandOperand);if(typeof result==="boolean")return result}return null}__name(memoizeCompare,"memoizeCompare");function memoizeSet(leftHandOperand,rightHandOperand,memoizeMap,result){if(!memoizeMap||isPrimitive(leftHandOperand)||isPrimitive(rightHandOperand))return;var leftHandMap=memoizeMap.get(leftHandOperand);if(leftHandMap)leftHandMap.set(rightHandOperand,result);else leftHandMap=new MemoizeMap,leftHandMap.set(rightHandOperand,result),memoizeMap.set(leftHandOperand,leftHandMap)}__name(memoizeSet,"memoizeSet");var deep_eql_default=deepEqual;function deepEqual(leftHandOperand,rightHandOperand,options){if(options&&options.comparator)return extensiveDeepEqual(leftHandOperand,rightHandOperand,options);var simpleResult=simpleEqual(leftHandOperand,rightHandOperand);if(simpleResult!==null)return simpleResult;return extensiveDeepEqual(leftHandOperand,rightHandOperand,options)}__name(deepEqual,"deepEqual");function simpleEqual(leftHandOperand,rightHandOperand){if(leftHandOperand===rightHandOperand)return leftHandOperand!==0||1/leftHandOperand===1/rightHandOperand;if(leftHandOperand!==leftHandOperand&&rightHandOperand!==rightHandOperand)return!0;if(isPrimitive(leftHandOperand)||isPrimitive(rightHandOperand))return!1;return null}__name(simpleEqual,"simpleEqual");function extensiveDeepEqual(leftHandOperand,rightHandOperand,options){options=options||{},options.memoize=options.memoize===!1?!1:options.memoize||new MemoizeMap;var comparator=options&&options.comparator,memoizeResultLeft=memoizeCompare(leftHandOperand,rightHandOperand,options.memoize);if(memoizeResultLeft!==null)return memoizeResultLeft;var memoizeResultRight=memoizeCompare(rightHandOperand,leftHandOperand,options.memoize);if(memoizeResultRight!==null)return memoizeResultRight;if(comparator){var comparatorResult=comparator(leftHandOperand,rightHandOperand);if(comparatorResult===!1||comparatorResult===!0)return memoizeSet(leftHandOperand,rightHandOperand,options.memoize,comparatorResult),comparatorResult;var simpleResult=simpleEqual(leftHandOperand,rightHandOperand);if(simpleResult!==null)return simpleResult}var leftHandType=type2(leftHandOperand);if(leftHandType!==type2(rightHandOperand))return memoizeSet(leftHandOperand,rightHandOperand,options.memoize,!1),!1;memoizeSet(leftHandOperand,rightHandOperand,options.memoize,!0);var result=extensiveDeepEqualByType(leftHandOperand,rightHandOperand,leftHandType,options);return memoizeSet(leftHandOperand,rightHandOperand,options.memoize,result),result}__name(extensiveDeepEqual,"extensiveDeepEqual");function extensiveDeepEqualByType(leftHandOperand,rightHandOperand,leftHandType,options){switch(leftHandType){case"String":case"Number":case"Boolean":case"Date":return deepEqual(leftHandOperand.valueOf(),rightHandOperand.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return leftHandOperand===rightHandOperand;case"Error":return keysEqual(leftHandOperand,rightHandOperand,["name","message","code"],options);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return iterableEqual(leftHandOperand,rightHandOperand,options);case"RegExp":return regexpEqual(leftHandOperand,rightHandOperand);case"Generator":return generatorEqual(leftHandOperand,rightHandOperand,options);case"DataView":return iterableEqual(new Uint8Array(leftHandOperand.buffer),new Uint8Array(rightHandOperand.buffer),options);case"ArrayBuffer":return iterableEqual(new Uint8Array(leftHandOperand),new Uint8Array(rightHandOperand),options);case"Set":return entriesEqual(leftHandOperand,rightHandOperand,options);case"Map":return entriesEqual(leftHandOperand,rightHandOperand,options);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return leftHandOperand.equals(rightHandOperand);case"Temporal.Duration":return leftHandOperand.total("nanoseconds")===rightHandOperand.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return leftHandOperand.toString()===rightHandOperand.toString();default:return objectEqual(leftHandOperand,rightHandOperand,options)}}__name(extensiveDeepEqualByType,"extensiveDeepEqualByType");function regexpEqual(leftHandOperand,rightHandOperand){return leftHandOperand.toString()===rightHandOperand.toString()}__name(regexpEqual,"regexpEqual");function entriesEqual(leftHandOperand,rightHandOperand,options){try{if(leftHandOperand.size!==rightHandOperand.size)return!1;if(leftHandOperand.size===0)return!0}catch(sizeError){return!1}var leftHandItems=[],rightHandItems=[];return leftHandOperand.forEach(__name(function(key,value){leftHandItems.push([key,value])},"gatherEntries")),rightHandOperand.forEach(__name(function(key,value){rightHandItems.push([key,value])},"gatherEntries")),iterableEqual(leftHandItems.sort(),rightHandItems.sort(),options)}__name(entriesEqual,"entriesEqual");function iterableEqual(leftHandOperand,rightHandOperand,options){var length=leftHandOperand.length;if(length!==rightHandOperand.length)return!1;if(length===0)return!0;var index=-1;while(++index<length)if(deepEqual(leftHandOperand[index],rightHandOperand[index],options)===!1)return!1;return!0}__name(iterableEqual,"iterableEqual");function generatorEqual(leftHandOperand,rightHandOperand,options){return iterableEqual(getGeneratorEntries(leftHandOperand),getGeneratorEntries(rightHandOperand),options)}__name(generatorEqual,"generatorEqual");function hasIteratorFunction(target){return typeof Symbol<"u"&&typeof target==="object"&&typeof Symbol.iterator<"u"&&typeof target[Symbol.iterator]==="function"}__name(hasIteratorFunction,"hasIteratorFunction");function getIteratorEntries(target){if(hasIteratorFunction(target))try{return getGeneratorEntries(target[Symbol.iterator]())}catch(iteratorError){return[]}return[]}__name(getIteratorEntries,"getIteratorEntries");function getGeneratorEntries(generator){var generatorResult=generator.next(),accumulator=[generatorResult.value];while(generatorResult.done===!1)generatorResult=generator.next(),accumulator.push(generatorResult.value);return accumulator}__name(getGeneratorEntries,"getGeneratorEntries");function getEnumerableKeys(target){var keys=[];for(var key in target)keys.push(key);return keys}__name(getEnumerableKeys,"getEnumerableKeys");function getEnumerableSymbols(target){var keys=[],allKeys=Object.getOwnPropertySymbols(target);for(var i=0;i<allKeys.length;i+=1){var key=allKeys[i];if(Object.getOwnPropertyDescriptor(target,key).enumerable)keys.push(key)}return keys}__name(getEnumerableSymbols,"getEnumerableSymbols");function keysEqual(leftHandOperand,rightHandOperand,keys,options){var length=keys.length;if(length===0)return!0;for(var i=0;i<length;i+=1)if(deepEqual(leftHandOperand[keys[i]],rightHandOperand[keys[i]],options)===!1)return!1;return!0}__name(keysEqual,"keysEqual");function objectEqual(leftHandOperand,rightHandOperand,options){var leftHandKeys=getEnumerableKeys(leftHandOperand),rightHandKeys=getEnumerableKeys(rightHandOperand),leftHandSymbols=getEnumerableSymbols(leftHandOperand),rightHandSymbols=getEnumerableSymbols(rightHandOperand);if(leftHandKeys=leftHandKeys.concat(leftHandSymbols),rightHandKeys=rightHandKeys.concat(rightHandSymbols),leftHandKeys.length&&leftHandKeys.length===rightHandKeys.length){if(iterableEqual(mapSymbols(leftHandKeys).sort(),mapSymbols(rightHandKeys).sort())===!1)return!1;return keysEqual(leftHandOperand,rightHandOperand,leftHandKeys,options)}var leftHandEntries=getIteratorEntries(leftHandOperand),rightHandEntries=getIteratorEntries(rightHandOperand);if(leftHandEntries.length&&leftHandEntries.length===rightHandEntries.length)return leftHandEntries.sort(),rightHandEntries.sort(),iterableEqual(leftHandEntries,rightHandEntries,options);if(leftHandKeys.length===0&&leftHandEntries.length===0&&rightHandKeys.length===0&&rightHandEntries.length===0)return!0;return!1}__name(objectEqual,"objectEqual");function isPrimitive(value){return value===null||typeof value!=="object"}__name(isPrimitive,"isPrimitive");function mapSymbols(arr){return arr.map(__name(function(entry){if(typeof entry==="symbol")return entry.toString();return entry},"mapSymbol"))}__name(mapSymbols,"mapSymbols");function hasProperty(obj,name){if(typeof obj>"u"||obj===null)return!1;return name in Object(obj)}__name(hasProperty,"hasProperty");function parsePath(path){return path.replace(/([^\\])\[/g,"$1.[").match(/(\\\.|[^.]+?)+/g).map((value)=>{if(value==="constructor"||value==="__proto__"||value==="prototype")return{};let mArr=/^\[(\d+)\]$/.exec(value),parsed=null;if(mArr)parsed={i:parseFloat(mArr[1])};else parsed={p:value.replace(/\\([.[\]])/g,"$1")};return parsed})}__name(parsePath,"parsePath");function internalGetPathValue(obj,parsed,pathDepth){let temporaryValue=obj,res=null;pathDepth=typeof pathDepth>"u"?parsed.length:pathDepth;for(let i=0;i<pathDepth;i++){let part=parsed[i];if(temporaryValue){if(typeof part.p>"u")temporaryValue=temporaryValue[part.i];else temporaryValue=temporaryValue[part.p];if(i===pathDepth-1)res=temporaryValue}}return res}__name(internalGetPathValue,"internalGetPathValue");function getPathInfo(obj,path){let parsed=parsePath(path),last=parsed[parsed.length-1],info={parent:parsed.length>1?internalGetPathValue(obj,parsed,parsed.length-1):obj,name:last.p||last.i,value:internalGetPathValue(obj,parsed)};return info.exists=hasProperty(info.parent,info.name),info}__name(getPathInfo,"getPathInfo");var _Assertion=class _Assertion2{constructor(obj,msg,ssfi,lockSsfi){return __publicField(this,"__flags",{}),flag(this,"ssfi",ssfi||_Assertion2),flag(this,"lockSsfi",lockSsfi),flag(this,"object",obj),flag(this,"message",msg),flag(this,"eql",config.deepEqual||deep_eql_default),proxify(this)}static get includeStack(){return console.warn("Assertion.includeStack is deprecated, use chai.config.includeStack instead."),config.includeStack}static set includeStack(value){console.warn("Assertion.includeStack is deprecated, use chai.config.includeStack instead."),config.includeStack=value}static get showDiff(){return console.warn("Assertion.showDiff is deprecated, use chai.config.showDiff instead."),config.showDiff}static set showDiff(value){console.warn("Assertion.showDiff is deprecated, use chai.config.showDiff instead."),config.showDiff=value}static addProperty(name,fn){addProperty(this.prototype,name,fn)}static addMethod(name,fn){addMethod(this.prototype,name,fn)}static addChainableMethod(name,fn,chainingBehavior){addChainableMethod(this.prototype,name,fn,chainingBehavior)}static overwriteProperty(name,fn){overwriteProperty(this.prototype,name,fn)}static overwriteMethod(name,fn){overwriteMethod(this.prototype,name,fn)}static overwriteChainableMethod(name,fn,chainingBehavior){overwriteChainableMethod(this.prototype,name,fn,chainingBehavior)}assert(_expr,msg,_negateMsg,expected,_actual,showDiff){let ok=test(this,arguments);if(showDiff!==!1)showDiff=!0;if(expected===void 0&&_actual===void 0)showDiff=!1;if(config.showDiff!==!0)showDiff=!1;if(!ok){msg=getMessage2(this,arguments);let assertionErrorObjectProperties={actual:getActual(this,arguments),expected,showDiff},operator=getOperator(this,arguments);if(operator)assertionErrorObjectProperties.operator=operator;throw new AssertionError(msg,assertionErrorObjectProperties,config.includeStack?this.assert:flag(this,"ssfi"))}}get _obj(){return flag(this,"object")}set _obj(val){flag(this,"object",val)}};__name(_Assertion,"Assertion");var Assertion=_Assertion,events=new EventTarget,_PluginEvent=class extends Event{constructor(type3,name,fn){super(type3);this.name=String(name),this.fn=fn}};__name(_PluginEvent,"PluginEvent");var PluginEvent=_PluginEvent;function isProxyEnabled(){return config.useProxy&&typeof Proxy<"u"&&typeof Reflect<"u"}__name(isProxyEnabled,"isProxyEnabled");function addProperty(ctx,name,getter){getter=getter===void 0?function(){}:getter,Object.defineProperty(ctx,name,{get:__name(function propertyGetter(){if(!isProxyEnabled()&&!flag(this,"lockSsfi"))flag(this,"ssfi",propertyGetter);let result=getter.call(this);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"propertyGetter"),configurable:!0}),events.dispatchEvent(new PluginEvent("addProperty",name,getter))}__name(addProperty,"addProperty");var fnLengthDesc=Object.getOwnPropertyDescriptor(function(){},"length");function addLengthGuard(fn,assertionName,isChainable){if(!fnLengthDesc.configurable)return fn;return Object.defineProperty(fn,"length",{get:__name(function(){if(isChainable)throw Error("Invalid Chai property: "+assertionName+'.length. Due to a compatibility issue, "length" cannot directly follow "'+assertionName+'". Use "'+assertionName+'.lengthOf" instead.');throw Error("Invalid Chai property: "+assertionName+'.length. See docs for proper usage of "'+assertionName+'".')},"get")}),fn}__name(addLengthGuard,"addLengthGuard");function getProperties(object){let result=Object.getOwnPropertyNames(object);function addProperty2(property){if(result.indexOf(property)===-1)result.push(property)}__name(addProperty2,"addProperty");let proto=Object.getPrototypeOf(object);while(proto!==null)Object.getOwnPropertyNames(proto).forEach(addProperty2),proto=Object.getPrototypeOf(proto);return result}__name(getProperties,"getProperties");var builtins=["__flags","__methods","_obj","assert"];function proxify(obj,nonChainableMethodName){if(!isProxyEnabled())return obj;return new Proxy(obj,{get:__name(function proxyGetter(target,property){if(typeof property==="string"&&config.proxyExcludedKeys.indexOf(property)===-1&&!Reflect.has(target,property)){if(nonChainableMethodName)throw Error("Invalid Chai property: "+nonChainableMethodName+"."+property+'. See docs for proper usage of "'+nonChainableMethodName+'".');let suggestion=null,suggestionDistance=4;if(getProperties(target).forEach(function(prop){if(!Object.prototype.hasOwnProperty(prop)&&builtins.indexOf(prop)===-1){let dist=stringDistanceCapped(property,prop,suggestionDistance);if(dist<suggestionDistance)suggestion=prop,suggestionDistance=dist}}),suggestion!==null)throw Error("Invalid Chai property: "+property+'. Did you mean "'+suggestion+'"?');else throw Error("Invalid Chai property: "+property)}if(builtins.indexOf(property)===-1&&!flag(target,"lockSsfi"))flag(target,"ssfi",proxyGetter);return Reflect.get(target,property)},"proxyGetter")})}__name(proxify,"proxify");function stringDistanceCapped(strA,strB,cap){if(Math.abs(strA.length-strB.length)>=cap)return cap;let memo=[];for(let i=0;i<=strA.length;i++)memo[i]=Array(strB.length+1).fill(0),memo[i][0]=i;for(let j=0;j<strB.length;j++)memo[0][j]=j;for(let i=1;i<=strA.length;i++){let ch=strA.charCodeAt(i-1);for(let j=1;j<=strB.length;j++){if(Math.abs(i-j)>=cap){memo[i][j]=cap;continue}memo[i][j]=Math.min(memo[i-1][j]+1,memo[i][j-1]+1,memo[i-1][j-1]+(ch===strB.charCodeAt(j-1)?0:1))}}return memo[strA.length][strB.length]}__name(stringDistanceCapped,"stringDistanceCapped");function addMethod(ctx,name,method){let methodWrapper=__name(function(){if(!flag(this,"lockSsfi"))flag(this,"ssfi",methodWrapper);let result=method.apply(this,arguments);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"methodWrapper");addLengthGuard(methodWrapper,name,!1),ctx[name]=proxify(methodWrapper,name),events.dispatchEvent(new PluginEvent("addMethod",name,method))}__name(addMethod,"addMethod");function overwriteProperty(ctx,name,getter){let _get=Object.getOwnPropertyDescriptor(ctx,name),_super=__name(function(){},"_super");if(_get&&typeof _get.get==="function")_super=_get.get;Object.defineProperty(ctx,name,{get:__name(function overwritingPropertyGetter(){if(!isProxyEnabled()&&!flag(this,"lockSsfi"))flag(this,"ssfi",overwritingPropertyGetter);let origLockSsfi=flag(this,"lockSsfi");flag(this,"lockSsfi",!0);let result=getter(_super).call(this);if(flag(this,"lockSsfi",origLockSsfi),result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"overwritingPropertyGetter"),configurable:!0})}__name(overwriteProperty,"overwriteProperty");function overwriteMethod(ctx,name,method){let _method=ctx[name],_super=__name(function(){throw Error(name+" is not a function")},"_super");if(_method&&typeof _method==="function")_super=_method;let overwritingMethodWrapper=__name(function(){if(!flag(this,"lockSsfi"))flag(this,"ssfi",overwritingMethodWrapper);let origLockSsfi=flag(this,"lockSsfi");flag(this,"lockSsfi",!0);let result=method(_super).apply(this,arguments);if(flag(this,"lockSsfi",origLockSsfi),result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"overwritingMethodWrapper");addLengthGuard(overwritingMethodWrapper,name,!1),ctx[name]=proxify(overwritingMethodWrapper,name)}__name(overwriteMethod,"overwriteMethod");var canSetPrototype=typeof Object.setPrototypeOf==="function",testFn=__name(function(){},"testFn"),excludeNames=Object.getOwnPropertyNames(testFn).filter(function(name){let propDesc=Object.getOwnPropertyDescriptor(testFn,name);if(typeof propDesc!=="object")return!0;return!propDesc.configurable}),call=Function.prototype.call,apply=Function.prototype.apply,_PluginAddChainableMethodEvent=class extends PluginEvent{constructor(type3,name,fn,chainingBehavior){super(type3,name,fn);this.chainingBehavior=chainingBehavior}};__name(_PluginAddChainableMethodEvent,"PluginAddChainableMethodEvent");var PluginAddChainableMethodEvent=_PluginAddChainableMethodEvent;function addChainableMethod(ctx,name,method,chainingBehavior){if(typeof chainingBehavior!=="function")chainingBehavior=__name(function(){},"chainingBehavior");let chainableBehavior={method,chainingBehavior};if(!ctx.__methods)ctx.__methods={};ctx.__methods[name]=chainableBehavior,Object.defineProperty(ctx,name,{get:__name(function(){chainableBehavior.chainingBehavior.call(this);let chainableMethodWrapper=__name(function(){if(!flag(this,"lockSsfi"))flag(this,"ssfi",chainableMethodWrapper);let result=chainableBehavior.method.apply(this,arguments);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"chainableMethodWrapper");if(addLengthGuard(chainableMethodWrapper,name,!0),canSetPrototype){let prototype=Object.create(this);prototype.call=call,prototype.apply=apply,Object.setPrototypeOf(chainableMethodWrapper,prototype)}else Object.getOwnPropertyNames(ctx).forEach(function(asserterName){if(excludeNames.indexOf(asserterName)!==-1)return;let pd=Object.getOwnPropertyDescriptor(ctx,asserterName);Object.defineProperty(chainableMethodWrapper,asserterName,pd)});return transferFlags(this,chainableMethodWrapper),proxify(chainableMethodWrapper)},"chainableMethodGetter"),configurable:!0}),events.dispatchEvent(new PluginAddChainableMethodEvent("addChainableMethod",name,method,chainingBehavior))}__name(addChainableMethod,"addChainableMethod");function overwriteChainableMethod(ctx,name,method,chainingBehavior){let chainableBehavior=ctx.__methods[name],_chainingBehavior=chainableBehavior.chainingBehavior;chainableBehavior.chainingBehavior=__name(function(){let result=chainingBehavior(_chainingBehavior).call(this);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"overwritingChainableMethodGetter");let _method=chainableBehavior.method;chainableBehavior.method=__name(function(){let result=method(_method).apply(this,arguments);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"overwritingChainableMethodWrapper")}__name(overwriteChainableMethod,"overwriteChainableMethod");function compareByInspect(a,b){return inspect2(a)<inspect2(b)?-1:1}__name(compareByInspect,"compareByInspect");function getOwnEnumerablePropertySymbols(obj){if(typeof Object.getOwnPropertySymbols!=="function")return[];return Object.getOwnPropertySymbols(obj).filter(function(sym){return Object.getOwnPropertyDescriptor(obj,sym).enumerable})}__name(getOwnEnumerablePropertySymbols,"getOwnEnumerablePropertySymbols");function getOwnEnumerableProperties(obj){return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj))}__name(getOwnEnumerableProperties,"getOwnEnumerableProperties");var isNaN2=Number.isNaN;function isObjectType(obj){let objectType=type(obj);return["Array","Object","Function"].indexOf(objectType)!==-1}__name(isObjectType,"isObjectType");function getOperator(obj,args){let operator=flag(obj,"operator"),negate=flag(obj,"negate"),expected=args[3],msg=negate?args[2]:args[1];if(operator)return operator;if(typeof msg==="function")msg=msg();if(msg=msg||"",!msg)return;if(/\shave\s/.test(msg))return;let isObject=isObjectType(expected);if(/\snot\s/.test(msg))return isObject?"notDeepStrictEqual":"notStrictEqual";return isObject?"deepStrictEqual":"strictEqual"}__name(getOperator,"getOperator");function getName(fn){return fn.name}__name(getName,"getName");function isRegExp2(obj){return Object.prototype.toString.call(obj)==="[object RegExp]"}__name(isRegExp2,"isRegExp");function isNumeric(obj){return["Number","BigInt"].includes(type(obj))}__name(isNumeric,"isNumeric");var{flag:flag2}=utils_exports;["to","be","been","is","and","has","have","with","that","which","at","of","same","but","does","still","also"].forEach(function(chain){Assertion.addProperty(chain)});Assertion.addProperty("not",function(){flag2(this,"negate",!0)});Assertion.addProperty("deep",function(){flag2(this,"deep",!0)});Assertion.addProperty("nested",function(){flag2(this,"nested",!0)});Assertion.addProperty("own",function(){flag2(this,"own",!0)});Assertion.addProperty("ordered",function(){flag2(this,"ordered",!0)});Assertion.addProperty("any",function(){flag2(this,"any",!0),flag2(this,"all",!1)});Assertion.addProperty("all",function(){flag2(this,"all",!0),flag2(this,"any",!1)});var functionTypes={function:["function","asyncfunction","generatorfunction","asyncgeneratorfunction"],asyncfunction:["asyncfunction","asyncgeneratorfunction"],generatorfunction:["generatorfunction","asyncgeneratorfunction"],asyncgeneratorfunction:["asyncgeneratorfunction"]};function an(type3,msg){if(msg)flag2(this,"message",msg);type3=type3.toLowerCase();let obj=flag2(this,"object"),article=~["a","e","i","o","u"].indexOf(type3.charAt(0))?"an ":"a ",detectedType=type(obj).toLowerCase();if(functionTypes.function.includes(type3))this.assert(functionTypes[type3].includes(detectedType),"expected #{this} to be "+article+type3,"expected #{this} not to be "+article+type3);else this.assert(type3===detectedType,"expected #{this} to be "+article+type3,"expected #{this} not to be "+article+type3)}__name(an,"an");Assertion.addChainableMethod("an",an);Assertion.addChainableMethod("a",an);function SameValueZero(a,b){return isNaN2(a)&&isNaN2(b)||a===b}__name(SameValueZero,"SameValueZero");function includeChainingBehavior(){flag2(this,"contains",!0)}__name(includeChainingBehavior,"includeChainingBehavior");function include(val,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),objType=type(obj).toLowerCase(),flagMsg=flag2(this,"message"),negate=flag2(this,"negate"),ssfi=flag2(this,"ssfi"),isDeep=flag2(this,"deep"),descriptor=isDeep?"deep ":"",isEql=isDeep?flag2(this,"eql"):SameValueZero;flagMsg=flagMsg?flagMsg+": ":"";let included=!1;switch(objType){case"string":included=obj.indexOf(val)!==-1;break;case"weakset":if(isDeep)throw new AssertionError(flagMsg+"unable to use .deep.include with WeakSet",void 0,ssfi);included=obj.has(val);break;case"map":obj.forEach(function(item){included=included||isEql(item,val)});break;case"set":if(isDeep)obj.forEach(function(item){included=included||isEql(item,val)});else included=obj.has(val);break;case"array":if(isDeep)included=obj.some(function(item){return isEql(item,val)});else included=obj.indexOf(val)!==-1;break;default:{if(val!==Object(val))throw new AssertionError(flagMsg+"the given combination of arguments ("+objType+" and "+type(val).toLowerCase()+") is invalid for this assertion. You can use an array, a map, an object, a set, a string, or a weakset instead of a "+type(val).toLowerCase(),void 0,ssfi);let props=Object.keys(val),firstErr=null,numErrs=0;if(props.forEach(function(prop){let propAssertion=new Assertion(obj);if(transferFlags(this,propAssertion,!0),flag2(propAssertion,"lockSsfi",!0),!negate||props.length===1){propAssertion.property(prop,val[prop]);return}try{propAssertion.property(prop,val[prop])}catch(err){if(!check_error_exports.compatibleConstructor(err,AssertionError))throw err;if(firstErr===null)firstErr=err;numErrs++}},this),negate&&props.length>1&&numErrs===props.length)throw firstErr;return}}this.assert(included,"expected #{this} to "+descriptor+"include "+inspect2(val),"expected #{this} to not "+descriptor+"include "+inspect2(val))}__name(include,"include");Assertion.addChainableMethod("include",include,includeChainingBehavior);Assertion.addChainableMethod("contain",include,includeChainingBehavior);Assertion.addChainableMethod("contains",include,includeChainingBehavior);Assertion.addChainableMethod("includes",include,includeChainingBehavior);Assertion.addProperty("ok",function(){this.assert(flag2(this,"object"),"expected #{this} to be truthy","expected #{this} to be falsy")});Assertion.addProperty("true",function(){this.assert(flag2(this,"object")===!0,"expected #{this} to be true","expected #{this} to be false",flag2(this,"negate")?!1:!0)});Assertion.addProperty("numeric",function(){let object=flag2(this,"object");this.assert(["Number","BigInt"].includes(type(object)),"expected #{this} to be numeric","expected #{this} to not be numeric",flag2(this,"negate")?!1:!0)});Assertion.addProperty("callable",function(){let val=flag2(this,"object"),ssfi=flag2(this,"ssfi"),message=flag2(this,"message"),msg=message?`${message}: `:"",negate=flag2(this,"negate"),assertionMessage=negate?`${msg}expected ${inspect2(val)} not to be a callable function`:`${msg}expected ${inspect2(val)} to be a callable function`,isCallable=["Function","AsyncFunction","GeneratorFunction","AsyncGeneratorFunction"].includes(type(val));if(isCallable&&negate||!isCallable&&!negate)throw new AssertionError(assertionMessage,void 0,ssfi)});Assertion.addProperty("false",function(){this.assert(flag2(this,"object")===!1,"expected #{this} to be false","expected #{this} to be true",flag2(this,"negate")?!0:!1)});Assertion.addProperty("null",function(){this.assert(flag2(this,"object")===null,"expected #{this} to be null","expected #{this} not to be null")});Assertion.addProperty("undefined",function(){this.assert(flag2(this,"object")===void 0,"expected #{this} to be undefined","expected #{this} not to be undefined")});Assertion.addProperty("NaN",function(){this.assert(isNaN2(flag2(this,"object")),"expected #{this} to be NaN","expected #{this} not to be NaN")});function assertExist(){let val=flag2(this,"object");this.assert(val!==null&&val!==void 0,"expected #{this} to exist","expected #{this} to not exist")}__name(assertExist,"assertExist");Assertion.addProperty("exist",assertExist);Assertion.addProperty("exists",assertExist);Assertion.addProperty("empty",function(){let val=flag2(this,"object"),ssfi=flag2(this,"ssfi"),flagMsg=flag2(this,"message"),itemsCount;switch(flagMsg=flagMsg?flagMsg+": ":"",type(val).toLowerCase()){case"array":case"string":itemsCount=val.length;break;case"map":case"set":itemsCount=val.size;break;case"weakmap":case"weakset":throw new AssertionError(flagMsg+".empty was passed a weak collection",void 0,ssfi);case"function":{let msg=flagMsg+".empty was passed a function "+getName(val);throw new AssertionError(msg.trim(),void 0,ssfi)}default:if(val!==Object(val))throw new AssertionError(flagMsg+".empty was passed non-string primitive "+inspect2(val),void 0,ssfi);itemsCount=Object.keys(val).length}this.assert(itemsCount===0,"expected #{this} to be empty","expected #{this} not to be empty")});function checkArguments(){let obj=flag2(this,"object"),type3=type(obj);this.assert(type3==="Arguments","expected #{this} to be arguments but got "+type3,"expected #{this} to not be arguments")}__name(checkArguments,"checkArguments");Assertion.addProperty("arguments",checkArguments);Assertion.addProperty("Arguments",checkArguments);function assertEqual(val,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object");if(flag2(this,"deep")){let prevLockSsfi=flag2(this,"lockSsfi");flag2(this,"lockSsfi",!0),this.eql(val),flag2(this,"lockSsfi",prevLockSsfi)}else this.assert(val===obj,"expected #{this} to equal #{exp}","expected #{this} to not equal #{exp}",val,this._obj,!0)}__name(assertEqual,"assertEqual");Assertion.addMethod("equal",assertEqual);Assertion.addMethod("equals",assertEqual);Assertion.addMethod("eq",assertEqual);function assertEql(obj,msg){if(msg)flag2(this,"message",msg);let eql=flag2(this,"eql");this.assert(eql(obj,flag2(this,"object")),"expected #{this} to deeply equal #{exp}","expected #{this} to not deeply equal #{exp}",obj,this._obj,!0)}__name(assertEql,"assertEql");Assertion.addMethod("eql",assertEql);Assertion.addMethod("eqls",assertEql);function assertAbove(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),nType=type(n).toLowerCase();if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&nType!=="date")throw new AssertionError(msgPrefix+"the argument to above must be a date",void 0,ssfi);else if(!isNumeric(n)&&(doLength||isNumeric(obj)))throw new AssertionError(msgPrefix+"the argument to above must be a number",void 0,ssfi);else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;throw new AssertionError(msgPrefix+"expected "+printObj+" to be a number or a date",void 0,ssfi)}if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount>n,"expected #{this} to have a "+descriptor+" above #{exp} but got #{act}","expected #{this} to not have a "+descriptor+" above #{exp}",n,itemsCount)}else this.assert(obj>n,"expected #{this} to be above #{exp}","expected #{this} to be at most #{exp}",n)}__name(assertAbove,"assertAbove");Assertion.addMethod("above",assertAbove);Assertion.addMethod("gt",assertAbove);Assertion.addMethod("greaterThan",assertAbove);function assertLeast(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),nType=type(n).toLowerCase(),errorMessage,shouldThrow=!0;if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&nType!=="date")errorMessage=msgPrefix+"the argument to least must be a date";else if(!isNumeric(n)&&(doLength||isNumeric(obj)))errorMessage=msgPrefix+"the argument to least must be a number";else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;errorMessage=msgPrefix+"expected "+printObj+" to be a number or a date"}else shouldThrow=!1;if(shouldThrow)throw new AssertionError(errorMessage,void 0,ssfi);if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount>=n,"expected #{this} to have a "+descriptor+" at least #{exp} but got #{act}","expected #{this} to have a "+descriptor+" below #{exp}",n,itemsCount)}else this.assert(obj>=n,"expected #{this} to be at least #{exp}","expected #{this} to be below #{exp}",n)}__name(assertLeast,"assertLeast");Assertion.addMethod("least",assertLeast);Assertion.addMethod("gte",assertLeast);Assertion.addMethod("greaterThanOrEqual",assertLeast);function assertBelow(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),nType=type(n).toLowerCase(),errorMessage,shouldThrow=!0;if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&nType!=="date")errorMessage=msgPrefix+"the argument to below must be a date";else if(!isNumeric(n)&&(doLength||isNumeric(obj)))errorMessage=msgPrefix+"the argument to below must be a number";else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;errorMessage=msgPrefix+"expected "+printObj+" to be a number or a date"}else shouldThrow=!1;if(shouldThrow)throw new AssertionError(errorMessage,void 0,ssfi);if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount<n,"expected #{this} to have a "+descriptor+" below #{exp} but got #{act}","expected #{this} to not have a "+descriptor+" below #{exp}",n,itemsCount)}else this.assert(obj<n,"expected #{this} to be below #{exp}","expected #{this} to be at least #{exp}",n)}__name(assertBelow,"assertBelow");Assertion.addMethod("below",assertBelow);Assertion.addMethod("lt",assertBelow);Assertion.addMethod("lessThan",assertBelow);function assertMost(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),nType=type(n).toLowerCase(),errorMessage,shouldThrow=!0;if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&nType!=="date")errorMessage=msgPrefix+"the argument to most must be a date";else if(!isNumeric(n)&&(doLength||isNumeric(obj)))errorMessage=msgPrefix+"the argument to most must be a number";else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;errorMessage=msgPrefix+"expected "+printObj+" to be a number or a date"}else shouldThrow=!1;if(shouldThrow)throw new AssertionError(errorMessage,void 0,ssfi);if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount<=n,"expected #{this} to have a "+descriptor+" at most #{exp} but got #{act}","expected #{this} to have a "+descriptor+" above #{exp}",n,itemsCount)}else this.assert(obj<=n,"expected #{this} to be at most #{exp}","expected #{this} to be above #{exp}",n)}__name(assertMost,"assertMost");Assertion.addMethod("most",assertMost);Assertion.addMethod("lte",assertMost);Assertion.addMethod("lessThanOrEqual",assertMost);Assertion.addMethod("within",function(start,finish,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),startType=type(start).toLowerCase(),finishType=type(finish).toLowerCase(),errorMessage,shouldThrow=!0,range=startType==="date"&&finishType==="date"?start.toISOString()+".."+finish.toISOString():start+".."+finish;if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&(startType!=="date"||finishType!=="date"))errorMessage=msgPrefix+"the arguments to within must be dates";else if((!isNumeric(start)||!isNumeric(finish))&&(doLength||isNumeric(obj)))errorMessage=msgPrefix+"the arguments to within must be numbers";else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;errorMessage=msgPrefix+"expected "+printObj+" to be a number or a date"}else shouldThrow=!1;if(shouldThrow)throw new AssertionError(errorMessage,void 0,ssfi);if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount>=start&&itemsCount<=finish,"expected #{this} to have a "+descriptor+" within "+range,"expected #{this} to not have a "+descriptor+" within "+range)}else this.assert(obj>=start&&obj<=finish,"expected #{this} to be within "+range,"expected #{this} to not be within "+range)});function assertInstanceOf(constructor,msg){if(msg)flag2(this,"message",msg);let target=flag2(this,"object"),ssfi=flag2(this,"ssfi"),flagMsg=flag2(this,"message"),isInstanceOf;try{isInstanceOf=target instanceof constructor}catch(err){if(err instanceof TypeError)throw flagMsg=flagMsg?flagMsg+": ":"",new AssertionError(flagMsg+"The instanceof assertion needs a constructor but "+type(constructor)+" was given.",void 0,ssfi);throw err}let name=getName(constructor);if(name==null)name="an unnamed constructor";this.assert(isInstanceOf,"expected #{this} to be an instance of "+name,"expected #{this} to not be an instance of "+name)}__name(assertInstanceOf,"assertInstanceOf");Assertion.addMethod("instanceof",assertInstanceOf);Assertion.addMethod("instanceOf",assertInstanceOf);function assertProperty(name,val,msg){if(msg)flag2(this,"message",msg);let isNested=flag2(this,"nested"),isOwn=flag2(this,"own"),flagMsg=flag2(this,"message"),obj=flag2(this,"object"),ssfi=flag2(this,"ssfi"),nameType=typeof name;if(flagMsg=flagMsg?flagMsg+": ":"",isNested){if(nameType!=="string")throw new AssertionError(flagMsg+"the argument to property must be a string when using nested syntax",void 0,ssfi)}else if(nameType!=="string"&&nameType!=="number"&&nameType!=="symbol")throw new AssertionError(flagMsg+"the argument to property must be a string, number, or symbol",void 0,ssfi);if(isNested&&isOwn)throw new AssertionError(flagMsg+'The "nested" and "own" flags cannot be combined.',void 0,ssfi);if(obj===null||obj===void 0)throw new AssertionError(flagMsg+"Target cannot be null or undefined.",void 0,ssfi);let isDeep=flag2(this,"deep"),negate=flag2(this,"negate"),pathInfo=isNested?getPathInfo(obj,name):null,value=isNested?pathInfo.value:obj[name],isEql=isDeep?flag2(this,"eql"):(val1,val2)=>val1===val2,descriptor="";if(isDeep)descriptor+="deep ";if(isOwn)descriptor+="own ";if(isNested)descriptor+="nested ";descriptor+="property ";let hasProperty2;if(isOwn)hasProperty2=Object.prototype.hasOwnProperty.call(obj,name);else if(isNested)hasProperty2=pathInfo.exists;else hasProperty2=hasProperty(obj,name);if(!negate||arguments.length===1)this.assert(hasProperty2,"expected #{this} to have "+descriptor+inspect2(name),"expected #{this} to not have "+descriptor+inspect2(name));if(arguments.length>1)this.assert(hasProperty2&&isEql(val,value),"expected #{this} to have "+descriptor+inspect2(name)+" of #{exp}, but got #{act}","expected #{this} to not have "+descriptor+inspect2(name)+" of #{act}",val,value);flag2(this,"object",value)}__name(assertProperty,"assertProperty");Assertion.addMethod("property",assertProperty);function assertOwnProperty(_name,_value,_msg){flag2(this,"own",!0),assertProperty.apply(this,arguments)}__name(assertOwnProperty,"assertOwnProperty");Assertion.addMethod("ownProperty",assertOwnProperty);Assertion.addMethod("haveOwnProperty",assertOwnProperty);function assertOwnPropertyDescriptor(name,descriptor,msg){if(typeof descriptor==="string")msg=descriptor,descriptor=null;if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),actualDescriptor=Object.getOwnPropertyDescriptor(Object(obj),name),eql=flag2(this,"eql");if(actualDescriptor&&descriptor)this.assert(eql(descriptor,actualDescriptor),"expected the own property descriptor for "+inspect2(name)+" on #{this} to match "+inspect2(descriptor)+", got "+inspect2(actualDescriptor),"expected the own property descriptor for "+inspect2(name)+" on #{this} to not match "+inspect2(descriptor),descriptor,actualDescriptor,!0);else this.assert(actualDescriptor,"expected #{this} to have an own property descriptor for "+inspect2(name),"expected #{this} to not have an own property descriptor for "+inspect2(name));flag2(this,"object",actualDescriptor)}__name(assertOwnPropertyDescriptor,"assertOwnPropertyDescriptor");Assertion.addMethod("ownPropertyDescriptor",assertOwnPropertyDescriptor);Assertion.addMethod("haveOwnPropertyDescriptor",assertOwnPropertyDescriptor);function assertLengthChain(){flag2(this,"doLength",!0)}__name(assertLengthChain,"assertLengthChain");function assertLength(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),objType=type(obj).toLowerCase(),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi"),descriptor="length",itemsCount;switch(objType){case"map":case"set":descriptor="size",itemsCount=obj.size;break;default:new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length"),itemsCount=obj.length}this.assert(itemsCount==n,"expected #{this} to have a "+descriptor+" of #{exp} but got #{act}","expected #{this} to not have a "+descriptor+" of #{act}",n,itemsCount)}__name(assertLength,"assertLength");Assertion.addChainableMethod("length",assertLength,assertLengthChain);Assertion.addChainableMethod("lengthOf",assertLength,assertLengthChain);function assertMatch(re,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object");this.assert(re.exec(obj),"expected #{this} to match "+re,"expected #{this} not to match "+re)}__name(assertMatch,"assertMatch");Assertion.addMethod("match",assertMatch);Assertion.addMethod("matches",assertMatch);Assertion.addMethod("string",function(str,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(obj,flagMsg,ssfi,!0).is.a("string"),this.assert(~obj.indexOf(str),"expected #{this} to contain "+inspect2(str),"expected #{this} to not contain "+inspect2(str))});function assertKeys(keys){let obj=flag2(this,"object"),objType=type(obj),keysType=type(keys),ssfi=flag2(this,"ssfi"),isDeep=flag2(this,"deep"),str,deepStr="",actual,ok=!0,flagMsg=flag2(this,"message");flagMsg=flagMsg?flagMsg+": ":"";let mixedArgsMsg=flagMsg+"when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments";if(objType==="Map"||objType==="Set"){if(deepStr=isDeep?"deeply ":"",actual=[],obj.forEach(function(val,key){actual.push(key)}),keysType!=="Array")keys=Array.prototype.slice.call(arguments)}else{switch(actual=getOwnEnumerableProperties(obj),keysType){case"Array":if(arguments.length>1)throw new AssertionError(mixedArgsMsg,void 0,ssfi);break;case"Object":if(arguments.length>1)throw new AssertionError(mixedArgsMsg,void 0,ssfi);keys=Object.keys(keys);break;default:keys=Array.prototype.slice.call(arguments)}keys=keys.map(function(val){return typeof val==="symbol"?val:String(val)})}if(!keys.length)throw new AssertionError(flagMsg+"keys required",void 0,ssfi);let len=keys.length,any=flag2(this,"any"),all=flag2(this,"all"),expected=keys,isEql=isDeep?flag2(this,"eql"):(val1,val2)=>val1===val2;if(!any&&!all)all=!0;if(any)ok=expected.some(function(expectedKey){return actual.some(function(actualKey){return isEql(expectedKey,actualKey)})});if(all){if(ok=expected.every(function(expectedKey){return actual.some(function(actualKey){return isEql(expectedKey,actualKey)})}),!flag2(this,"contains"))ok=ok&&keys.length==actual.length}if(len>1){keys=keys.map(function(key){return inspect2(key)});let last=keys.pop();if(all)str=keys.join(", ")+", and "+last;if(any)str=keys.join(", ")+", or "+last}else str=inspect2(keys[0]);str=(len>1?"keys ":"key ")+str,str=(flag2(this,"contains")?"contain ":"have ")+str,this.assert(ok,"expected #{this} to "+deepStr+str,"expected #{this} to not "+deepStr+str,expected.slice(0).sort(compareByInspect),actual.sort(compareByInspect),!0)}__name(assertKeys,"assertKeys");Assertion.addMethod("keys",assertKeys);Assertion.addMethod("key",assertKeys);function assertThrows(errorLike,errMsgMatcher,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),ssfi=flag2(this,"ssfi"),flagMsg=flag2(this,"message"),negate=flag2(this,"negate")||!1;if(new Assertion(obj,flagMsg,ssfi,!0).is.a("function"),isRegExp2(errorLike)||typeof errorLike==="string")errMsgMatcher=errorLike,errorLike=null;let caughtErr,errorWasThrown=!1;try{obj()}catch(err){errorWasThrown=!0,caughtErr=err}let everyArgIsUndefined=errorLike===void 0&&errMsgMatcher===void 0,everyArgIsDefined=Boolean(errorLike&&errMsgMatcher),errorLikeFail=!1,errMsgMatcherFail=!1;if(everyArgIsUndefined||!everyArgIsUndefined&&!negate){let errorLikeString="an error";if(errorLike instanceof Error)errorLikeString="#{exp}";else if(errorLike)errorLikeString=check_error_exports.getConstructorName(errorLike);let actual=caughtErr;if(caughtErr instanceof Error)actual=caughtErr.toString();else if(typeof caughtErr==="string")actual=caughtErr;else if(caughtErr&&(typeof caughtErr==="object"||typeof caughtErr==="function"))try{actual=check_error_exports.getConstructorName(caughtErr)}catch(_err){}this.assert(errorWasThrown,"expected #{this} to throw "+errorLikeString,"expected #{this} to not throw an error but #{act} was thrown",errorLike&&errorLike.toString(),actual)}if(errorLike&&caughtErr){if(errorLike instanceof Error){if(check_error_exports.compatibleInstance(caughtErr,errorLike)===negate)if(everyArgIsDefined&&negate)errorLikeFail=!0;else this.assert(negate,"expected #{this} to throw #{exp} but #{act} was thrown","expected #{this} to not throw #{exp}"+(caughtErr&&!negate?" but #{act} was thrown":""),errorLike.toString(),caughtErr.toString())}if(check_error_exports.compatibleConstructor(caughtErr,errorLike)===negate)if(everyArgIsDefined&&negate)errorLikeFail=!0;else this.assert(negate,"expected #{this} to throw #{exp} but #{act} was thrown","expected #{this} to not throw #{exp}"+(caughtErr?" but #{act} was thrown":""),errorLike instanceof Error?errorLike.toString():errorLike&&check_error_exports.getConstructorName(errorLike),caughtErr instanceof Error?caughtErr.toString():caughtErr&&check_error_exports.getConstructorName(caughtErr))}if(caughtErr&&errMsgMatcher!==void 0&&errMsgMatcher!==null){let placeholder="including";if(isRegExp2(errMsgMatcher))placeholder="matching";if(check_error_exports.compatibleMessage(caughtErr,errMsgMatcher)===negate)if(everyArgIsDefined&&negate)errMsgMatcherFail=!0;else this.assert(negate,"expected #{this} to throw error "+placeholder+" #{exp} but got #{act}","expected #{this} to throw error not "+placeholder+" #{exp}",errMsgMatcher,check_error_exports.getMessage(caughtErr))}if(errorLikeFail&&errMsgMatcherFail)this.assert(negate,"expected #{this} to throw #{exp} but #{act} was thrown","expected #{this} to not throw #{exp}"+(caughtErr?" but #{act} was thrown":""),errorLike instanceof Error?errorLike.toString():errorLike&&check_error_exports.getConstructorName(errorLike),caughtErr instanceof Error?caughtErr.toString():caughtErr&&check_error_exports.getConstructorName(caughtErr));flag2(this,"object",caughtErr)}__name(assertThrows,"assertThrows");Assertion.addMethod("throw",assertThrows);Assertion.addMethod("throws",assertThrows);Assertion.addMethod("Throw",assertThrows);function respondTo(method,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),itself=flag2(this,"itself"),context=typeof obj==="function"&&!itself?obj.prototype[method]:obj[method];this.assert(typeof context==="function","expected #{this} to respond to "+inspect2(method),"expected #{this} to not respond to "+inspect2(method))}__name(respondTo,"respondTo");Assertion.addMethod("respondTo",respondTo);Assertion.addMethod("respondsTo",respondTo);Assertion.addProperty("itself",function(){flag2(this,"itself",!0)});function satisfy(matcher,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),result=matcher(obj);this.assert(result,"expected #{this} to satisfy "+objDisplay(matcher),"expected #{this} to not satisfy"+objDisplay(matcher),flag2(this,"negate")?!1:!0,result)}__name(satisfy,"satisfy");Assertion.addMethod("satisfy",satisfy);Assertion.addMethod("satisfies",satisfy);function closeTo(expected,delta,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(obj,flagMsg,ssfi,!0).is.numeric;let message="A `delta` value is required for `closeTo`";if(delta==null)throw new AssertionError(flagMsg?`${flagMsg}: ${message}`:message,void 0,ssfi);if(new Assertion(delta,flagMsg,ssfi,!0).is.numeric,message="A `expected` value is required for `closeTo`",expected==null)throw new AssertionError(flagMsg?`${flagMsg}: ${message}`:message,void 0,ssfi);new Assertion(expected,flagMsg,ssfi,!0).is.numeric;let abs=__name((x)=>x<0?-x:x,"abs"),strip=__name((number)=>parseFloat(parseFloat(number).toPrecision(12)),"strip");this.assert(strip(abs(obj-expected))<=delta,"expected #{this} to be close to "+expected+" +/- "+delta,"expected #{this} not to be close to "+expected+" +/- "+delta)}__name(closeTo,"closeTo");Assertion.addMethod("closeTo",closeTo);Assertion.addMethod("approximately",closeTo);function isSubsetOf(_subset,_superset,cmp,contains,ordered){let superset=Array.from(_superset),subset=Array.from(_subset);if(!contains){if(subset.length!==superset.length)return!1;superset=superset.slice()}return subset.every(function(elem,idx){if(ordered)return cmp?cmp(elem,superset[idx]):elem===superset[idx];if(!cmp){let matchIdx=superset.indexOf(elem);if(matchIdx===-1)return!1;if(!contains)superset.splice(matchIdx,1);return!0}return superset.some(function(elem2,matchIdx){if(!cmp(elem,elem2))return!1;if(!contains)superset.splice(matchIdx,1);return!0})})}__name(isSubsetOf,"isSubsetOf");Assertion.addMethod("members",function(subset,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(obj,flagMsg,ssfi,!0).to.be.iterable,new Assertion(subset,flagMsg,ssfi,!0).to.be.iterable;let contains=flag2(this,"contains"),ordered=flag2(this,"ordered"),subject,failMsg,failNegateMsg;if(contains)subject=ordered?"an ordered superset":"a superset",failMsg="expected #{this} to be "+subject+" of #{exp}",failNegateMsg="expected #{this} to not be "+subject+" of #{exp}";else subject=ordered?"ordered members":"members",failMsg="expected #{this} to have the same "+subject+" as #{exp}",failNegateMsg="expected #{this} to not have the same "+subject+" as #{exp}";let cmp=flag2(this,"deep")?flag2(this,"eql"):void 0;this.assert(isSubsetOf(subset,obj,cmp,contains,ordered),failMsg,failNegateMsg,subset,obj,!0)});Assertion.addProperty("iterable",function(msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object");this.assert(obj!=null&&obj[Symbol.iterator],"expected #{this} to be an iterable","expected #{this} to not be an iterable",obj)});function oneOf(list,msg){if(msg)flag2(this,"message",msg);let expected=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi"),contains=flag2(this,"contains"),isDeep=flag2(this,"deep"),eql=flag2(this,"eql");if(new Assertion(list,flagMsg,ssfi,!0).to.be.an("array"),contains)this.assert(list.some(function(possibility){return expected.indexOf(possibility)>-1}),"expected #{this} to contain one of #{exp}","expected #{this} to not contain one of #{exp}",list,expected);else if(isDeep)this.assert(list.some(function(possibility){return eql(expected,possibility)}),"expected #{this} to deeply equal one of #{exp}","expected #{this} to deeply equal one of #{exp}",list,expected);else this.assert(list.indexOf(expected)>-1,"expected #{this} to be one of #{exp}","expected #{this} to not be one of #{exp}",list,expected)}__name(oneOf,"oneOf");Assertion.addMethod("oneOf",oneOf);function assertChanges(subject,prop,msg){if(msg)flag2(this,"message",msg);let fn=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(fn,flagMsg,ssfi,!0).is.a("function");let initial;if(!prop)new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject();else new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop];fn();let final=prop===void 0||prop===null?subject():subject[prop],msgObj=prop===void 0||prop===null?initial:"."+prop;flag2(this,"deltaMsgObj",msgObj),flag2(this,"initialDeltaValue",initial),flag2(this,"finalDeltaValue",final),flag2(this,"deltaBehavior","change"),flag2(this,"realDelta",final!==initial),this.assert(initial!==final,"expected "+msgObj+" to change","expected "+msgObj+" to not change")}__name(assertChanges,"assertChanges");Assertion.addMethod("change",assertChanges);Assertion.addMethod("changes",assertChanges);function assertIncreases(subject,prop,msg){if(msg)flag2(this,"message",msg);let fn=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(fn,flagMsg,ssfi,!0).is.a("function");let initial;if(!prop)new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject();else new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop];new Assertion(initial,flagMsg,ssfi,!0).is.a("number"),fn();let final=prop===void 0||prop===null?subject():subject[prop],msgObj=prop===void 0||prop===null?initial:"."+prop;flag2(this,"deltaMsgObj",msgObj),flag2(this,"initialDeltaValue",initial),flag2(this,"finalDeltaValue",final),flag2(this,"deltaBehavior","increase"),flag2(this,"realDelta",final-initial),this.assert(final-initial>0,"expected "+msgObj+" to increase","expected "+msgObj+" to not increase")}__name(assertIncreases,"assertIncreases");Assertion.addMethod("increase",assertIncreases);Assertion.addMethod("increases",assertIncreases);function assertDecreases(subject,prop,msg){if(msg)flag2(this,"message",msg);let fn=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(fn,flagMsg,ssfi,!0).is.a("function");let initial;if(!prop)new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject();else new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop];new Assertion(initial,flagMsg,ssfi,!0).is.a("number"),fn();let final=prop===void 0||prop===null?subject():subject[prop],msgObj=prop===void 0||prop===null?initial:"."+prop;flag2(this,"deltaMsgObj",msgObj),flag2(this,"initialDeltaValue",initial),flag2(this,"finalDeltaValue",final),flag2(this,"deltaBehavior","decrease"),flag2(this,"realDelta",initial-final),this.assert(final-initial<0,"expected "+msgObj+" to decrease","expected "+msgObj+" to not decrease")}__name(assertDecreases,"assertDecreases");Assertion.addMethod("decrease",assertDecreases);Assertion.addMethod("decreases",assertDecreases);function assertDelta(delta,msg){if(msg)flag2(this,"message",msg);let msgObj=flag2(this,"deltaMsgObj"),initial=flag2(this,"initialDeltaValue"),final=flag2(this,"finalDeltaValue"),behavior=flag2(this,"deltaBehavior"),realDelta=flag2(this,"realDelta"),expression;if(behavior==="change")expression=Math.abs(final-initial)===Math.abs(delta);else expression=realDelta===Math.abs(delta);this.assert(expression,"expected "+msgObj+" to "+behavior+" by "+delta,"expected "+msgObj+" to not "+behavior+" by "+delta)}__name(assertDelta,"assertDelta");Assertion.addMethod("by",assertDelta);Assertion.addProperty("extensible",function(){let obj=flag2(this,"object"),isExtensible=obj===Object(obj)&&Object.isExtensible(obj);this.assert(isExtensible,"expected #{this} to be extensible","expected #{this} to not be extensible")});Assertion.addProperty("sealed",function(){let obj=flag2(this,"object"),isSealed=obj===Object(obj)?Object.isSealed(obj):!0;this.assert(isSealed,"expected #{this} to be sealed","expected #{this} to not be sealed")});Assertion.addProperty("frozen",function(){let obj=flag2(this,"object"),isFrozen=obj===Object(obj)?Object.isFrozen(obj):!0;this.assert(isFrozen,"expected #{this} to be frozen","expected #{this} to not be frozen")});Assertion.addProperty("finite",function(_msg){let obj=flag2(this,"object");this.assert(typeof obj==="number"&&isFinite(obj),"expected #{this} to be a finite number","expected #{this} to not be a finite number")});function compareSubset(expected,actual){if(expected===actual)return!0;if(typeof actual!==typeof expected)return!1;if(typeof expected!=="object"||expected===null)return expected===actual;if(!actual)return!1;if(Array.isArray(expected)){if(!Array.isArray(actual))return!1;return expected.every(function(exp){return actual.some(function(act){return compareSubset(exp,act)})})}if(expected instanceof Date)if(actual instanceof Date)return expected.getTime()===actual.getTime();else return!1;return Object.keys(expected).every(function(key){let expectedValue=expected[key],actualValue=actual[key];if(typeof expectedValue==="object"&&expectedValue!==null&&actualValue!==null)return compareSubset(expectedValue,actualValue);if(typeof expectedValue==="function")return expectedValue(actualValue);return actualValue===expectedValue})}__name(compareSubset,"compareSubset");Assertion.addMethod("containSubset",function(expected){let actual=flag(this,"object"),showDiff=config.showDiff;this.assert(compareSubset(expected,actual),"expected #{act} to contain subset #{exp}","expected #{act} to not contain subset #{exp}",expected,actual,showDiff)});function expect(val,message){return new Assertion(val,message)}__name(expect,"expect");expect.fail=function(actual,expected,message,operator){if(arguments.length<2)message=actual,actual=void 0;throw message=message||"expect.fail()",new AssertionError(message,{actual,expected,operator},expect.fail)};var should_exports={};__export(should_exports,{Should:()=>Should,should:()=>should});function loadShould(){function shouldGetter(){if(this instanceof String||this instanceof Number||this instanceof Boolean||typeof Symbol==="function"&&this instanceof Symbol||typeof BigInt==="function"&&this instanceof BigInt)return new Assertion(this.valueOf(),null,shouldGetter);return new Assertion(this,null,shouldGetter)}__name(shouldGetter,"shouldGetter");function shouldSetter(value){Object.defineProperty(this,"should",{value,enumerable:!0,configurable:!0,writable:!0})}__name(shouldSetter,"shouldSetter"),Object.defineProperty(Object.prototype,"should",{set:shouldSetter,get:shouldGetter,configurable:!0});let should2={};return should2.fail=function(actual,expected,message,operator){if(arguments.length<2)message=actual,actual=void 0;throw message=message||"should.fail()",new AssertionError(message,{actual,expected,operator},should2.fail)},should2.equal=function(actual,expected,message){new Assertion(actual,message).to.equal(expected)},should2.Throw=function(fn,errt,errs,msg){new Assertion(fn,msg).to.Throw(errt,errs)},should2.exist=function(val,msg){new Assertion(val,msg).to.exist},should2.not={},should2.not.equal=function(actual,expected,msg){new Assertion(actual,msg).to.not.equal(expected)},should2.not.Throw=function(fn,errt,errs,msg){new Assertion(fn,msg).to.not.Throw(errt,errs)},should2.not.exist=function(val,msg){new Assertion(val,msg).to.not.exist},should2.throw=should2.Throw,should2.not.throw=should2.not.Throw,should2}__name(loadShould,"loadShould");var should=loadShould,Should=loadShould;function assert(express,errmsg){new Assertion(null,null,assert,!0).assert(express,errmsg,"[ negation message unavailable ]")}__name(assert,"assert");assert.fail=function(actual,expected,message,operator){if(arguments.length<2)message=actual,actual=void 0;throw message=message||"assert.fail()",new AssertionError(message,{actual,expected,operator},assert.fail)};assert.isOk=function(val,msg){new Assertion(val,msg,assert.isOk,!0).is.ok};assert.isNotOk=function(val,msg){new Assertion(val,msg,assert.isNotOk,!0).is.not.ok};assert.equal=function(act,exp,msg){let test2=new Assertion(act,msg,assert.equal,!0);test2.assert(exp==flag(test2,"object"),"expected #{this} to equal #{exp}","expected #{this} to not equal #{act}",exp,act,!0)};assert.notEqual=function(act,exp,msg){let test2=new Assertion(act,msg,assert.notEqual,!0);test2.assert(exp!=flag(test2,"object"),"expected #{this} to not equal #{exp}","expected #{this} to equal #{act}",exp,act,!0)};assert.strictEqual=function(act,exp,msg){new Assertion(act,msg,assert.strictEqual,!0).to.equal(exp)};assert.notStrictEqual=function(act,exp,msg){new Assertion(act,msg,assert.notStrictEqual,!0).to.not.equal(exp)};assert.deepEqual=assert.deepStrictEqual=function(act,exp,msg){new Assertion(act,msg,assert.deepEqual,!0).to.eql(exp)};assert.notDeepEqual=function(act,exp,msg){new Assertion(act,msg,assert.notDeepEqual,!0).to.not.eql(exp)};assert.isAbove=function(val,abv,msg){new Assertion(val,msg,assert.isAbove,!0).to.be.above(abv)};assert.isAtLeast=function(val,atlst,msg){new Assertion(val,msg,assert.isAtLeast,!0).to.be.least(atlst)};assert.isBelow=function(val,blw,msg){new Assertion(val,msg,assert.isBelow,!0).to.be.below(blw)};assert.isAtMost=function(val,atmst,msg){new Assertion(val,msg,assert.isAtMost,!0).to.be.most(atmst)};assert.isTrue=function(val,msg){new Assertion(val,msg,assert.isTrue,!0).is.true};assert.isNotTrue=function(val,msg){new Assertion(val,msg,assert.isNotTrue,!0).to.not.equal(!0)};assert.isFalse=function(val,msg){new Assertion(val,msg,assert.isFalse,!0).is.false};assert.isNotFalse=function(val,msg){new Assertion(val,msg,assert.isNotFalse,!0).to.not.equal(!1)};assert.isNull=function(val,msg){new Assertion(val,msg,assert.isNull,!0).to.equal(null)};assert.isNotNull=function(val,msg){new Assertion(val,msg,assert.isNotNull,!0).to.not.equal(null)};assert.isNaN=function(val,msg){new Assertion(val,msg,assert.isNaN,!0).to.be.NaN};assert.isNotNaN=function(value,message){new Assertion(value,message,assert.isNotNaN,!0).not.to.be.NaN};assert.exists=function(val,msg){new Assertion(val,msg,assert.exists,!0).to.exist};assert.notExists=function(val,msg){new Assertion(val,msg,assert.notExists,!0).to.not.exist};assert.isUndefined=function(val,msg){new Assertion(val,msg,assert.isUndefined,!0).to.equal(void 0)};assert.isDefined=function(val,msg){new Assertion(val,msg,assert.isDefined,!0).to.not.equal(void 0)};assert.isCallable=function(value,message){new Assertion(value,message,assert.isCallable,!0).is.callable};assert.isNotCallable=function(value,message){new Assertion(value,message,assert.isNotCallable,!0).is.not.callable};assert.isObject=function(val,msg){new Assertion(val,msg,assert.isObject,!0).to.be.a("object")};assert.isNotObject=function(val,msg){new Assertion(val,msg,assert.isNotObject,!0).to.not.be.a("object")};assert.isArray=function(val,msg){new Assertion(val,msg,assert.isArray,!0).to.be.an("array")};assert.isNotArray=function(val,msg){new Assertion(val,msg,assert.isNotArray,!0).to.not.be.an("array")};assert.isString=function(val,msg){new Assertion(val,msg,assert.isString,!0).to.be.a("string")};assert.isNotString=function(val,msg){new Assertion(val,msg,assert.isNotString,!0).to.not.be.a("string")};assert.isNumber=function(val,msg){new Assertion(val,msg,assert.isNumber,!0).to.be.a("number")};assert.isNotNumber=function(val,msg){new Assertion(val,msg,assert.isNotNumber,!0).to.not.be.a("number")};assert.isNumeric=function(val,msg){new Assertion(val,msg,assert.isNumeric,!0).is.numeric};assert.isNotNumeric=function(val,msg){new Assertion(val,msg,assert.isNotNumeric,!0).is.not.numeric};assert.isFinite=function(val,msg){new Assertion(val,msg,assert.isFinite,!0).to.be.finite};assert.isBoolean=function(val,msg){new Assertion(val,msg,assert.isBoolean,!0).to.be.a("boolean")};assert.isNotBoolean=function(val,msg){new Assertion(val,msg,assert.isNotBoolean,!0).to.not.be.a("boolean")};assert.typeOf=function(val,type3,msg){new Assertion(val,msg,assert.typeOf,!0).to.be.a(type3)};assert.notTypeOf=function(value,type3,message){new Assertion(value,message,assert.notTypeOf,!0).to.not.be.a(type3)};assert.instanceOf=function(val,type3,msg){new Assertion(val,msg,assert.instanceOf,!0).to.be.instanceOf(type3)};assert.notInstanceOf=function(val,type3,msg){new Assertion(val,msg,assert.notInstanceOf,!0).to.not.be.instanceOf(type3)};assert.include=function(exp,inc,msg){new Assertion(exp,msg,assert.include,!0).include(inc)};assert.notInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notInclude,!0).not.include(inc)};assert.deepInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.deepInclude,!0).deep.include(inc)};assert.notDeepInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notDeepInclude,!0).not.deep.include(inc)};assert.nestedInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.nestedInclude,!0).nested.include(inc)};assert.notNestedInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notNestedInclude,!0).not.nested.include(inc)};assert.deepNestedInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.deepNestedInclude,!0).deep.nested.include(inc)};assert.notDeepNestedInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notDeepNestedInclude,!0).not.deep.nested.include(inc)};assert.ownInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.ownInclude,!0).own.include(inc)};assert.notOwnInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notOwnInclude,!0).not.own.include(inc)};assert.deepOwnInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.deepOwnInclude,!0).deep.own.include(inc)};assert.notDeepOwnInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notDeepOwnInclude,!0).not.deep.own.include(inc)};assert.match=function(exp,re,msg){new Assertion(exp,msg,assert.match,!0).to.match(re)};assert.notMatch=function(exp,re,msg){new Assertion(exp,msg,assert.notMatch,!0).to.not.match(re)};assert.property=function(obj,prop,msg){new Assertion(obj,msg,assert.property,!0).to.have.property(prop)};assert.notProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.notProperty,!0).to.not.have.property(prop)};assert.propertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.propertyVal,!0).to.have.property(prop,val)};assert.notPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.notPropertyVal,!0).to.not.have.property(prop,val)};assert.deepPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.deepPropertyVal,!0).to.have.deep.property(prop,val)};assert.notDeepPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.notDeepPropertyVal,!0).to.not.have.deep.property(prop,val)};assert.ownProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.ownProperty,!0).to.have.own.property(prop)};assert.notOwnProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.notOwnProperty,!0).to.not.have.own.property(prop)};assert.ownPropertyVal=function(obj,prop,value,msg){new Assertion(obj,msg,assert.ownPropertyVal,!0).to.have.own.property(prop,value)};assert.notOwnPropertyVal=function(obj,prop,value,msg){new Assertion(obj,msg,assert.notOwnPropertyVal,!0).to.not.have.own.property(prop,value)};assert.deepOwnPropertyVal=function(obj,prop,value,msg){new Assertion(obj,msg,assert.deepOwnPropertyVal,!0).to.have.deep.own.property(prop,value)};assert.notDeepOwnPropertyVal=function(obj,prop,value,msg){new Assertion(obj,msg,assert.notDeepOwnPropertyVal,!0).to.not.have.deep.own.property(prop,value)};assert.nestedProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.nestedProperty,!0).to.have.nested.property(prop)};assert.notNestedProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.notNestedProperty,!0).to.not.have.nested.property(prop)};assert.nestedPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.nestedPropertyVal,!0).to.have.nested.property(prop,val)};assert.notNestedPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.notNestedPropertyVal,!0).to.not.have.nested.property(prop,val)};assert.deepNestedPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.deepNestedPropertyVal,!0).to.have.deep.nested.property(prop,val)};assert.notDeepNestedPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.notDeepNestedPropertyVal,!0).to.not.have.deep.nested.property(prop,val)};assert.lengthOf=function(exp,len,msg){new Assertion(exp,msg,assert.lengthOf,!0).to.have.lengthOf(len)};assert.hasAnyKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.hasAnyKeys,!0).to.have.any.keys(keys)};assert.hasAllKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.hasAllKeys,!0).to.have.all.keys(keys)};assert.containsAllKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.containsAllKeys,!0).to.contain.all.keys(keys)};assert.doesNotHaveAnyKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.doesNotHaveAnyKeys,!0).to.not.have.any.keys(keys)};assert.doesNotHaveAllKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.doesNotHaveAllKeys,!0).to.not.have.all.keys(keys)};assert.hasAnyDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.hasAnyDeepKeys,!0).to.have.any.deep.keys(keys)};assert.hasAllDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.hasAllDeepKeys,!0).to.have.all.deep.keys(keys)};assert.containsAllDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.containsAllDeepKeys,!0).to.contain.all.deep.keys(keys)};assert.doesNotHaveAnyDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.doesNotHaveAnyDeepKeys,!0).to.not.have.any.deep.keys(keys)};assert.doesNotHaveAllDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.doesNotHaveAllDeepKeys,!0).to.not.have.all.deep.keys(keys)};assert.throws=function(fn,errorLike,errMsgMatcher,msg){if(typeof errorLike==="string"||errorLike instanceof RegExp)errMsgMatcher=errorLike,errorLike=null;let assertErr=new Assertion(fn,msg,assert.throws,!0).to.throw(errorLike,errMsgMatcher);return flag(assertErr,"object")};assert.doesNotThrow=function(fn,errorLike,errMsgMatcher,message){if(typeof errorLike==="string"||errorLike instanceof RegExp)errMsgMatcher=errorLike,errorLike=null;new Assertion(fn,message,assert.doesNotThrow,!0).to.not.throw(errorLike,errMsgMatcher)};assert.operator=function(val,operator,val2,msg){let ok;switch(operator){case"==":ok=val==val2;break;case"===":ok=val===val2;break;case">":ok=val>val2;break;case">=":ok=val>=val2;break;case"<":ok=val<val2;break;case"<=":ok=val<=val2;break;case"!=":ok=val!=val2;break;case"!==":ok=val!==val2;break;default:throw msg=msg?msg+": ":msg,new AssertionError(msg+'Invalid operator "'+operator+'"',void 0,assert.operator)}let test2=new Assertion(ok,msg,assert.operator,!0);test2.assert(flag(test2,"object")===!0,"expected "+inspect2(val)+" to be "+operator+" "+inspect2(val2),"expected "+inspect2(val)+" to not be "+operator+" "+inspect2(val2))};assert.closeTo=function(act,exp,delta,msg){new Assertion(act,msg,assert.closeTo,!0).to.be.closeTo(exp,delta)};assert.approximately=function(act,exp,delta,msg){new Assertion(act,msg,assert.approximately,!0).to.be.approximately(exp,delta)};assert.sameMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.sameMembers,!0).to.have.same.members(set2)};assert.notSameMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.notSameMembers,!0).to.not.have.same.members(set2)};assert.sameDeepMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.sameDeepMembers,!0).to.have.same.deep.members(set2)};assert.notSameDeepMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.notSameDeepMembers,!0).to.not.have.same.deep.members(set2)};assert.sameOrderedMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.sameOrderedMembers,!0).to.have.same.ordered.members(set2)};assert.notSameOrderedMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.notSameOrderedMembers,!0).to.not.have.same.ordered.members(set2)};assert.sameDeepOrderedMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.sameDeepOrderedMembers,!0).to.have.same.deep.ordered.members(set2)};assert.notSameDeepOrderedMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.notSameDeepOrderedMembers,!0).to.not.have.same.deep.ordered.members(set2)};assert.includeMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.includeMembers,!0).to.include.members(subset)};assert.notIncludeMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.notIncludeMembers,!0).to.not.include.members(subset)};assert.includeDeepMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.includeDeepMembers,!0).to.include.deep.members(subset)};assert.notIncludeDeepMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.notIncludeDeepMembers,!0).to.not.include.deep.members(subset)};assert.includeOrderedMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.includeOrderedMembers,!0).to.include.ordered.members(subset)};assert.notIncludeOrderedMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.notIncludeOrderedMembers,!0).to.not.include.ordered.members(subset)};assert.includeDeepOrderedMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.includeDeepOrderedMembers,!0).to.include.deep.ordered.members(subset)};assert.notIncludeDeepOrderedMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.notIncludeDeepOrderedMembers,!0).to.not.include.deep.ordered.members(subset)};assert.oneOf=function(inList,list,msg){new Assertion(inList,msg,assert.oneOf,!0).to.be.oneOf(list)};assert.isIterable=function(obj,msg){if(obj==null||!obj[Symbol.iterator])throw msg=msg?`${msg} expected ${inspect2(obj)} to be an iterable`:`expected ${inspect2(obj)} to be an iterable`,new AssertionError(msg,void 0,assert.isIterable)};assert.changes=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;new Assertion(fn,msg,assert.changes,!0).to.change(obj,prop)};assert.changesBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.changesBy,!0).to.change(obj,prop).by(delta)};assert.doesNotChange=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.doesNotChange,!0).to.not.change(obj,prop)};assert.changesButNotBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.changesButNotBy,!0).to.change(obj,prop).but.not.by(delta)};assert.increases=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.increases,!0).to.increase(obj,prop)};assert.increasesBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.increasesBy,!0).to.increase(obj,prop).by(delta)};assert.doesNotIncrease=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.doesNotIncrease,!0).to.not.increase(obj,prop)};assert.increasesButNotBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.increasesButNotBy,!0).to.increase(obj,prop).but.not.by(delta)};assert.decreases=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.decreases,!0).to.decrease(obj,prop)};assert.decreasesBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.decreasesBy,!0).to.decrease(obj,prop).by(delta)};assert.doesNotDecrease=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.doesNotDecrease,!0).to.not.decrease(obj,prop)};assert.doesNotDecreaseBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;return new Assertion(fn,msg,assert.doesNotDecreaseBy,!0).to.not.decrease(obj,prop).by(delta)};assert.decreasesButNotBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.decreasesButNotBy,!0).to.decrease(obj,prop).but.not.by(delta)};assert.ifError=function(val){if(val)throw val};assert.isExtensible=function(obj,msg){new Assertion(obj,msg,assert.isExtensible,!0).to.be.extensible};assert.isNotExtensible=function(obj,msg){new Assertion(obj,msg,assert.isNotExtensible,!0).to.not.be.extensible};assert.isSealed=function(obj,msg){new Assertion(obj,msg,assert.isSealed,!0).to.be.sealed};assert.isNotSealed=function(obj,msg){new Assertion(obj,msg,assert.isNotSealed,!0).to.not.be.sealed};assert.isFrozen=function(obj,msg){new Assertion(obj,msg,assert.isFrozen,!0).to.be.frozen};assert.isNotFrozen=function(obj,msg){new Assertion(obj,msg,assert.isNotFrozen,!0).to.not.be.frozen};assert.isEmpty=function(val,msg){new Assertion(val,msg,assert.isEmpty,!0).to.be.empty};assert.isNotEmpty=function(val,msg){new Assertion(val,msg,assert.isNotEmpty,!0).to.not.be.empty};assert.containsSubset=function(val,exp,msg){new Assertion(val,msg).to.containSubset(exp)};assert.doesNotContainSubset=function(val,exp,msg){new Assertion(val,msg).to.not.containSubset(exp)};var aliases=[["isOk","ok"],["isNotOk","notOk"],["throws","throw"],["throws","Throw"],["isExtensible","extensible"],["isNotExtensible","notExtensible"],["isSealed","sealed"],["isNotSealed","notSealed"],["isFrozen","frozen"],["isNotFrozen","notFrozen"],["isEmpty","empty"],["isNotEmpty","notEmpty"],["isCallable","isFunction"],["isNotCallable","isNotFunction"],["containsSubset","containSubset"]];for(let[name,as]of aliases)assert[as]=assert[name];var used=[];function use(fn){let exports={use,AssertionError,util:utils_exports,config,expect,assert,Assertion,...should_exports};if(!~used.indexOf(fn))fn(exports,utils_exports),used.push(fn);return exports}__name(use,"use");function invariant(condition,error){if(!condition)throw Error(error)}function assertNotInfinite(size){invariant(size!==1/0,"Cannot perform this action with an infinite size.")}function reduce(collection,reducer,reduction,context,useFirst,reverse){return assertNotInfinite(collection.size),collection.__iterate((v,k,c)=>{if(useFirst)useFirst=!1,reduction=v;else reduction=reducer.call(context,reduction,v,k,c)},reverse),reduction}var keyMapper=(v,k)=>k,entryMapper=(v,k)=>[k,v],not=(predicate)=>function(...args){return!predicate.apply(this,args)},neg=(predicate)=>function(...args){return-predicate.apply(this,args)};function defaultComparator(a,b){if(a===void 0&&b===void 0)return 0;if(a===void 0)return 1;if(b===void 0)return-1;return a>b?1:a<b?-1:0}var defaultNegComparator=(a,b)=>a<b?1:a>b?-1:0,DONE={done:!0,value:void 0};class Iter{constructor(next){this.next=next}[Symbol.iterator](){return this}}function makeIterator(next){return new Iter(next)}function makeEntryIterator(next){let entry=[void 0,void 0],result={done:!1,value:void 0};return makeIterator(()=>{if(next(entry))return result.value=[entry[0],entry[1]],result;return DONE})}var EMPTY_ITERATOR=makeIterator(()=>DONE),emptyIterator=()=>EMPTY_ITERATOR;function makeIndexKeys(size){let i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return result.value=i++,result})}function mapEntries(source,transform){return makeEntryIterator((entry)=>{let step=source.next();if(step.done)return!1;return transform(step.value[0],step.value[1],entry),!0})}function hasIterator(maybeIterable){if(Array.isArray(maybeIterable))return!0;return!!getIteratorFn(maybeIterable)}var isIterator=(maybeIterator)=>typeof maybeIterator?.next==="function";function getIterator(iterable){return getIteratorFn(iterable)?.call(iterable)}function getIteratorFn(iterable){let iteratorFn=iterable?.[Symbol.iterator];if(typeof iteratorFn==="function")return iteratorFn}function isEntriesIterable(maybeIterable){let iteratorFn=getIteratorFn(maybeIterable);return iteratorFn&&iteratorFn===maybeIterable.entries}function isKeysIterable(maybeIterable){let iteratorFn=getIteratorFn(maybeIterable);return iteratorFn&&iteratorFn===maybeIterable.keys}var DELETE="delete",SHIFT=5,SIZE=1<<SHIFT,MASK=SIZE-1,NOT_SET={},MakeRef=()=>({value:!1});function SetRef(ref){if(ref)ref.value=!0}class OwnerID{}function ensureSize(iter){if(iter.size===void 0)iter.size=iter.__iterate(returnTrue);return iter.size}function wrapIndex(iter,index){if(typeof index!=="number"){let uint32Index=index>>>0;if(String(uint32Index)!==index||uint32Index===4294967295)return NaN;index=uint32Index}return index<0?ensureSize(iter)+index:index}var returnTrue=()=>!0,isNeg=(value)=>value<0||Object.is(value,-0),wholeSlice=(begin,end,size)=>(begin===0&&!isNeg(begin)||size!==void 0&&(begin??0)<=-size)&&(end===void 0||size!==void 0&&end>=size),resolveIndex=(index,size,defaultIndex)=>index===void 0?defaultIndex:isNeg(index)?size===1/0?size:Math.max(0,size+index)|0:size===void 0||size===index?index:Math.min(size,index)|0,resolveBegin=(begin,size)=>resolveIndex(begin,size,0),resolveEnd=(end,size)=>resolveIndex(end,size,size),IS_COLLECTION_SYMBOL="@@__IMMUTABLE_ITERABLE__@@",IS_KEYED_SYMBOL="@@__IMMUTABLE_KEYED__@@",IS_INDEXED_SYMBOL="@@__IMMUTABLE_INDEXED__@@",IS_ORDERED_SYMBOL="@@__IMMUTABLE_ORDERED__@@",IS_SEQ_SYMBOL="@@__IMMUTABLE_SEQ__@@",IS_LIST_SYMBOL="@@__IMMUTABLE_LIST__@@",IS_MAP_SYMBOL="@@__IMMUTABLE_MAP__@@",IS_SET_SYMBOL="@@__IMMUTABLE_SET__@@",IS_STACK_SYMBOL="@@__IMMUTABLE_STACK__@@",IS_RECORD_SYMBOL="@@__IMMUTABLE_RECORD__@@";function hasSymbol(v,symbol){return typeof v==="object"&&v!==null&&symbol in v}var isCollection=(v)=>hasSymbol(v,IS_COLLECTION_SYMBOL),isKeyed=(v)=>hasSymbol(v,IS_KEYED_SYMBOL),isIndexed=(v)=>hasSymbol(v,IS_INDEXED_SYMBOL),isAssociative=(v)=>isKeyed(v)||isIndexed(v),isOrdered=(v)=>hasSymbol(v,IS_ORDERED_SYMBOL),isSeq=(v)=>hasSymbol(v,IS_SEQ_SYMBOL),isList=(v)=>hasSymbol(v,IS_LIST_SYMBOL),isMap=(v)=>hasSymbol(v,IS_MAP_SYMBOL),isSet=(v)=>hasSymbol(v,IS_SET_SYMBOL),isStack=(v)=>hasSymbol(v,IS_STACK_SYMBOL),isRecord=(v)=>hasSymbol(v,IS_RECORD_SYMBOL),isImmutable=(v)=>isCollection(v)||isRecord(v),isOrderedMap=(v)=>isMap(v)&&isOrdered(v),isOrderedSet=(v)=>isSet(v)&&isOrdered(v),isValueObject=(v)=>typeof v==="object"&&v!==null&&typeof v.equals==="function"&&typeof v.hashCode==="function";function flipFactory(collection){let flipSequence=makeSequence(collection);return flipSequence._iter=collection,flipSequence.size=collection.size,flipSequence.flip=()=>collection,flipSequence.reverse=function(){let reversedSequence=collection.reverse.call(this);return reversedSequence.flip=()=>collection.reverse(),reversedSequence},flipSequence.has=(key)=>collection.includes(key),flipSequence.includes=(key)=>collection.has(key),flipSequence.cacheResult=cacheResultThrough,flipSequence.__iterate=function(fn,reverse){return collection.__iterate((v,k)=>fn(k,v,this),reverse)},flipSequence.__iteratorUncached=(reverse)=>mapEntries(collection.__iterator(reverse),(k,v,entry)=>{entry[0]=v,entry[1]=k}),flipSequence}function mapFactory(collection,mapper,context){let mappedSequence=makeSequence(collection);return mappedSequence.size=collection.size,mappedSequence.has=(key)=>collection.has(key),mappedSequence.get=(key,notSetValue)=>{let v=collection.get(key,NOT_SET);return v===NOT_SET?notSetValue:mapper.call(context,v,key,collection)},mappedSequence.__iterate=function(fn,reverse){return collection.__iterate((v,k)=>fn(mapper.call(context,v,k,collection),k,this),reverse)},mappedSequence.__iteratorUncached=(reverse)=>mapEntries(collection.__iterator(reverse),(k,v,entry)=>{entry[0]=k,entry[1]=mapper.call(context,v,k,collection)}),mappedSequence}function reverseFactory(collection,useKeys){let reversedSequence=makeSequence(collection);if(reversedSequence._iter=collection,reversedSequence.size=collection.size,reversedSequence.reverse=()=>collection,collection.flip)reversedSequence.flip=function(){let flipSequence=flipFactory(collection);return flipSequence.reverse=()=>collection.flip(),flipSequence};return reversedSequence.get=(key,notSetValue)=>collection.get(useKeys?key:-1-key,notSetValue),reversedSequence.has=(key)=>collection.has(useKeys?key:-1-key),reversedSequence.includes=(value)=>collection.includes(value),reversedSequence.cacheResult=cacheResultThrough,reversedSequence.__iterate=function(fn,reverse){let i=0;if(reverse)ensureSize(collection);return collection.__iterate((v,k)=>fn(v,useKeys?k:reverse?this.size-++i:i++,this),!reverse)},reversedSequence.__iteratorUncached=function(reverse){let i=0;if(reverse)ensureSize(collection);let size=this.size;return mapEntries(collection.__iterator(!reverse),(k,v,entry)=>{entry[0]=useKeys?k:reverse?size-++i:i++,entry[1]=v})},reversedSequence}function sliceFactory(collection,begin,end,useKeys){let originalSize=collection.size;if(wholeSlice(begin,end,originalSize))return collection;if(originalSize===void 0&&(begin<0||end<0))return sliceFactory(collection.toSeq().cacheResult(),begin,end,useKeys);let resolvedBegin=resolveBegin(begin,originalSize),resolvedSize=resolveEnd(end,originalSize)-resolvedBegin,sliceSize;if(!Number.isNaN(resolvedSize))sliceSize=Math.max(0,resolvedSize);let sliceSeq=makeSequence(collection);if(sliceSeq.size=sliceSize===0?sliceSize:collection.size&&sliceSize||void 0,!useKeys&&isSeq(collection)&&sliceSize>=0)sliceSeq.get=function(index,notSetValue){return index=wrapIndex(this,index),index>=0&&index<sliceSize?collection.get(index+resolvedBegin,notSetValue):notSetValue};return sliceSeq.__iterateUncached=function(fn,reverse){if(sliceSize!==0&&reverse)return this.cacheResult().__iterate(fn,reverse);if(sliceSize===0)return 0;let skipped=0,iterations=0;return collection.__iterate((v,k)=>{if(skipped<resolvedBegin){skipped++;return}if(sliceSize!==void 0&&iterations>=sliceSize)return!1;if(iterations++,fn(v,useKeys?k:iterations-1,this)===!1)return!1},reverse),iterations},sliceSeq.__iteratorUncached=function(reverse){if(sliceSize!==0&&reverse)return this.cacheResult().__iterator(reverse);if(sliceSize===0)return emptyIterator();let iterator=collection.__iterator(reverse),skipped=0,iterations=0;if(useKeys)return makeIterator(()=>{while(skipped<resolvedBegin)skipped++,iterator.next();if(sliceSize!==void 0&&iterations>=sliceSize)return DONE;let step=iterator.next();if(step.done)return step;return iterations++,step});return makeEntryIterator((entry)=>{while(skipped<resolvedBegin)skipped++,iterator.next();if(sliceSize!==void 0&&iterations>=sliceSize)return!1;let step=iterator.next();if(step.done)return!1;return iterations++,entry[0]=iterations-1,entry[1]=step.value[1],!0})},sliceSeq}function sortFactory(collection,comparator,mapper){if(!comparator)comparator=defaultComparator;let isKeyedCollection=isKeyed(collection),index=0,entries=collection.toSeq().map((v,k)=>[k,v,index++,mapper?mapper(v,k,collection):v]).valueSeq().toArray();return entries.sort((a,b)=>comparator(a[3],b[3])||a[2]-b[2]).forEach(isKeyedCollection?(v,i)=>{entries[i].length=2}:(v,i)=>{entries[i]=v[1]}),isKeyedCollection?KeyedSeq(entries):isIndexed(collection)?IndexedSeq(entries):SetSeq(entries)}function maxFactory(collection,comparator,mapper){if(!comparator)comparator=defaultComparator;if(mapper)return collection.toSeq().map((v,k)=>[v,mapper(v,k,collection)]).reduce((a,b)=>maxCompare(comparator,a[1],b[1])?b:a)?.[0];return collection.reduce((a,b)=>maxCompare(comparator,a,b)?b:a)}function maxCompare(comparator,a,b){let comp=comparator(b,a);return comp===0&&b!==a&&(b===void 0||b===null||Number.isNaN(b))||comp>0}function zipWithFactory(keyIter,zipper,iters,zipAll){let zipSequence=makeSequence(keyIter),sizes=new ArraySeq(iters).map((i)=>i.size);return zipSequence.size=zipAll?sizes.max():sizes.min(),zipSequence.__iterate=function(fn,reverse){let iterator=this.__iterator(reverse),iterations=0,step;while(!(step=iterator.next()).done)if(fn(step.value[1],iterations++,this)===!1)break;return iterations},zipSequence.__iteratorUncached=function(reverse){let iterators=iters.map((i)=>{let col=Collection(i);return getIterator(reverse?col.reverse():col)}),iterations=0,steps=Array(iterators.length),values=Array(iterators.length);return makeEntryIterator((entry)=>{let done=zipAll;for(let i=0;i<iterators.length;i++)steps[i]=iterators[i].next(),done=zipAll?done&&steps[i].done:done||steps[i].done;if(done)return!1;for(let i=0;i<steps.length;i++)values[i]=steps[i].value;return entry[0]=iterations++,entry[1]=zipper(...values),!0})},zipSequence}function isArrayLike(value){if(Array.isArray(value)||typeof value==="string")return!0;return value&&typeof value==="object"&&Number.isInteger(value.length)&&value.length>=0&&(value.length===0?Object.keys(value).length===1:Object.hasOwn(value,value.length-1))}function isPlainObject(value){if(!value||typeof value!=="object"||Object.prototype.toString.call(value)!=="[object Object]")return!1;let proto=Object.getPrototypeOf(value);if(proto===null)return!0;let parentProto=proto,nextProto=Object.getPrototypeOf(proto);while(nextProto!==null)parentProto=nextProto,nextProto=Object.getPrototypeOf(parentProto);return parentProto===proto}var isDataStructure=(value)=>typeof value==="object"&&(isImmutable(value)||Array.isArray(value)||isPlainObject(value));function coerceKeyPath(keyPath){if(isArrayLike(keyPath)&&typeof keyPath!=="string")return keyPath;if(isOrdered(keyPath))return keyPath.toArray();throw TypeError(`Invalid keyPath: expected Ordered Collection or Array: ${keyPath}`)}var has=(collection,key)=>isImmutable(collection)?collection.has(key):isDataStructure(collection)&&Object.hasOwn(collection,key);function get2(collection,key,notSetValue){return isImmutable(collection)?collection.get(key,notSetValue):!has(collection,key)?notSetValue:typeof collection.get==="function"?collection.get(key):collection[key]}function getIn$1(collection,searchKeyPath,notSetValue){let keyPath=coerceKeyPath(searchKeyPath),i=0;while(i!==keyPath.length)if(collection=get2(collection,keyPath[i++],NOT_SET),collection===NOT_SET)return notSetValue;return collection}var hasIn$1=(collection,keyPath)=>getIn$1(collection,keyPath,NOT_SET)!==NOT_SET;function is(valueA,valueB){if(valueA===valueB||Number.isNaN(valueA)&&Number.isNaN(valueB))return!0;if(!valueA||!valueB)return!1;if(typeof valueA.valueOf==="function"&&typeof valueB.valueOf==="function"){if(valueA=valueA.valueOf(),valueB=valueB.valueOf(),valueA===valueB||Number.isNaN(valueA)&&Number.isNaN(valueB))return!0;if(!valueA||!valueB)return!1}return!!(isValueObject(valueA)&&isValueObject(valueB)&&valueA.equals(valueB))}function toJS(value){if(!value||typeof value!=="object")return value;if(!isCollection(value)){if(!isDataStructure(value))return value;value=Seq(value)}if(isKeyed(value)){let result2={};return value.__iterate((v,k)=>{result2[String(k)]=toJS(v)}),result2}let result=[];return value.__iterate((v)=>{result.push(toJS(v))}),result}function deepEqual2(a,b){if(a===b)return!0;if(!isCollection(b)||a.size!==void 0&&b.size!==void 0&&a.size!==b.size||a.__hash!==void 0&&b.__hash!==void 0&&a.__hash!==b.__hash||isKeyed(a)!==isKeyed(b)||isIndexed(a)!==isIndexed(b)||isOrdered(a)!==isOrdered(b))return!1;if(a.size===0&&b.size===0)return!0;let notAssociative=!isAssociative(a);if(isOrdered(a)){let entries=a.entries();return!!(b.every((v,k)=>{let entry=entries.next().value;return entry&&is(entry[1],v)&&(notAssociative||is(entry[0],k))})&&entries.next().done)}let flipped=!1;if(a.size===void 0)if(b.size===void 0){if(typeof a.cacheResult==="function")a.cacheResult()}else{flipped=!0;let _=a;a=b,b=_}let allEqual=!0,bSize=b.__iterate((v,k)=>{if(notAssociative?!a.has(v):flipped?!is(v,a.get(k,NOT_SET)):!is(a.get(k,NOT_SET),v))return allEqual=!1,!1;return!0});return allEqual&&a.size===bSize}var smi=(i32)=>i32>>>1&1073741824|i32&3221225471;function hash(o){if(o===null||o===void 0)return hashNullish(o);if(typeof o.hashCode==="function")return smi(o.hashCode(o));let v=valueOf(o);if(v===null||v===void 0)return hashNullish(v);switch(typeof v){case"boolean":return v?1108378657:1108378656;case"number":return hashNumber(v);case"string":return v.length>STRING_HASH_CACHE_MIN_STRLEN?cachedHashString(v):hashString(v);case"object":case"function":return hashJSObj(v);case"symbol":return hashSymbol(v);default:if(typeof v.toString==="function")return hashString(v.toString());throw Error(`Value type ${typeof v} cannot be hashed.`)}}var hashNullish=(nullish)=>nullish===null?1108378658:1108378659;function hashNumber(n){if(Number.isNaN(n)||n===1/0)return 0;let hash2=n|0;if(hash2!==n)hash2^=n*4294967295;while(n>4294967295)n/=4294967295,hash2^=n;return smi(hash2)}function cachedHashString(string){let hashed=stringHashCache[string];if(hashed===void 0){if(hashed=hashString(string),STRING_HASH_CACHE_SIZE===STRING_HASH_CACHE_MAX_SIZE)STRING_HASH_CACHE_SIZE=0,stringHashCache={};STRING_HASH_CACHE_SIZE++,stringHashCache[string]=hashed}return hashed}function hashString(string){let hashed=0;for(let ii=0;ii<string.length;ii++)hashed=31*hashed+string.charCodeAt(ii)|0;return smi(hashed)}function hashSymbol(sym){let hashed=symbolMap[sym];if(hashed!==void 0)return hashed;return hashed=nextHash(),symbolMap[sym]=hashed,hashed}function hashJSObj(obj){let hashed=weakMap.get(obj);if(hashed!==void 0)return hashed;return hashed=nextHash(),weakMap.set(obj,hashed),hashed}var valueOf=(obj)=>obj.valueOf!==Object.prototype.valueOf?obj.valueOf():obj;function nextHash(){let nextHash2=++_objHashUID;if(_objHashUID&1073741824)_objHashUID=0;return nextHash2}var weakMap=new WeakMap,symbolMap=Object.create(null),_objHashUID=0,STRING_HASH_CACHE_MIN_STRLEN=16,STRING_HASH_CACHE_MAX_SIZE=255,STRING_HASH_CACHE_SIZE=0,stringHashCache={};function hashCollection(collection){if(collection.size===1/0)return 0;let ordered=isOrdered(collection),keyed=isKeyed(collection),h=ordered?1:0;return collection.__iterate(keyed?ordered?(v,k)=>{h=31*h+hashMerge(hash(v),hash(k))|0}:(v,k)=>{h=h+hashMerge(hash(v),hash(k))|0}:ordered?(v)=>{h=31*h+hash(v)|0}:(v)=>{h=h+hash(v)|0}),murmurHashOfSize(collection.size,h)}var hashMerge=(a,b)=>a^b+2654435769+(a<<6)+(a>>2)|0;function murmurHashOfSize(size,h){return h=Math.imul(h,3432918353),h=Math.imul(h<<15|h>>>-15,461845907),h=Math.imul(h<<13|h>>>-13,5),h=(h+3864292196|0)^size,h=Math.imul(h^h>>>16,2246822507),h=Math.imul(h^h>>>13,3266489909),h=smi(h^h>>>16),h}function quoteString(value){try{return typeof value==="string"?JSON.stringify(value):String(value)}catch{return JSON.stringify(value)}}var reify=(iter,seq)=>iter===seq?iter:isSeq(iter)?seq:iter.create?iter.create(seq):iter.constructor(seq),reifyValues=(collection,arr)=>reify(collection,(isKeyed(collection)?KeyedCollection:isIndexed(collection)?IndexedCollection:SetCollection)(arr)),defaultZipper=(...values)=>values,Collection=(value)=>isCollection(value)?value:Seq(value);class CollectionImpl{size=0;static{this.prototype[IS_COLLECTION_SYMBOL]=!0,this.prototype.__toStringMapper=quoteString,this.prototype[Symbol.iterator]=this.prototype.values,this.prototype.toJSON=this.prototype.toArray,this.prototype.contains=this.prototype.includes}equals(other){return deepEqual2(this,other)}hashCode(){return this.__hash??(this.__hash=hashCollection(this))}toArray(){assertNotInfinite(this.size);let array=Array(this.size||0),useTuples=isKeyed(this),i=0;return this.__iterate((v,k)=>{array[i++]=useTuples?[k,v]:v}),array}toIndexedSeq(){return new ToIndexedSequence(this)}toJS(){return toJS(this)}toKeyedSeq(){return new ToKeyedSequence(this,!0)}toMap(){throw Error("toMap: not patched — import CollectionConversions")}toObject(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}toOrderedMap(){throw Error("toOrderedMap: not patched — import CollectionConversions")}toOrderedSet(){throw Error("toOrderedSet: not patched — import CollectionConversions")}toSet(){throw Error("toSet: not patched — import CollectionConversions")}toSetSeq(){return new ToSetSequence(this)}toSeq(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()}toStack(){throw Error("toStack: not patched — import CollectionConversions")}toList(){throw Error("toList: not patched — import CollectionConversions")}toString(){return"[Collection]"}__toString(head,tail){if(this.size===0)return`${head}${tail}`;return`${head} ${this.toSeq().map(this.__toStringMapper).join(", ")} ${tail}`}concat(...values){let isKeyedCollection=isKeyed(this),iters=[this,...values].map((v)=>{if(!isCollection(v))v=isKeyedCollection?keyedSeqFromValue(v):indexedSeqFromValue(Array.isArray(v)?v:[v]);else if(isKeyedCollection)v=KeyedCollection(v);return v}).filter((v)=>v.size!==0);if(iters.length===0)return this;if(iters.length===1){let singleton=iters[0];if(singleton===this||isKeyedCollection&&isKeyed(singleton)||isIndexed(this)&&isIndexed(singleton))return singleton}return reify(this,new ConcatSeq(iters))}includes(searchValue){return this.some((value)=>is(value,searchValue))}every(predicate,context){assertNotInfinite(this.size);let returnValue=!0;return this.__iterate((v,k,c)=>{if(!predicate.call(context,v,k,c))return returnValue=!1,!1}),returnValue}entries(){return this.__iterator()}filter(predicate,context){let collection=this,useKeys=isKeyed(this),filterSequence=makeSequence(collection);if(useKeys)filterSequence.has=(key)=>{let v=collection.get(key,NOT_SET);return v!==NOT_SET&&!!predicate.call(context,v,key,collection)},filterSequence.get=(key,notSetValue)=>{let v=collection.get(key,NOT_SET);return v!==NOT_SET&&predicate.call(context,v,key,collection)?v:notSetValue};return filterSequence.__iterateUncached=function(fn,reverse){let iterations=0;return collection.__iterate((v,k)=>{if(predicate.call(context,v,k,collection))return iterations++,fn(v,useKeys?k:iterations-1,this)},reverse),iterations},filterSequence.__iteratorUncached=function(reverse){let iterator=collection.__iterator(reverse),iterations=0;return makeEntryIterator((entry)=>{while(!0){let step=iterator.next();if(step.done)return!1;let k=step.value[0],v=step.value[1];if(predicate.call(context,v,k,collection))return entry[0]=useKeys?k:iterations++,entry[1]=v,!0}})},reify(this,filterSequence)}partition(predicate,context){let isKeyedIter=isKeyed(this),groups=[[],[]];return this.__iterate((v,k)=>{groups[predicate.call(context,v,k,this)?1:0].push(isKeyedIter?[k,v]:v)}),groups.map((arr)=>reifyValues(this,arr))}find(predicate,context,notSetValue){let entry=this.findEntry(predicate,context);return entry?entry[1]:notSetValue}forEach(sideEffect,context){return assertNotInfinite(this.size),this.__iterate(context?sideEffect.bind(context):sideEffect)}join(separator){assertNotInfinite(this.size),separator=separator!==void 0?String(separator):",";let joined="",isFirst=!0;return this.__iterate((v)=>{if(isFirst)isFirst=!1;else joined+=separator;joined+=v!==null&&v!==void 0?String(v):""}),joined}keys(){let iterator=this.__iterator(),result={done:!1,value:void 0};return makeIterator(()=>{let step=iterator.next();if(step.done)return DONE;return result.value=step.value[0],result})}map(mapper,context){return reify(this,mapFactory(this,mapper,context))}reduce(reducer,initialReduction=NOT_SET,context){return reduce(this,reducer,initialReduction,context,initialReduction===NOT_SET,!1)}reduceRight(reducer,initialReduction=NOT_SET,context){return reduce(this,reducer,initialReduction,context,initialReduction===NOT_SET,!0)}reverse(){return reify(this,reverseFactory(this,isKeyed(this)))}slice(begin,end){return reify(this,sliceFactory(this,begin,end,isKeyed(this)))}some(predicate,context){assertNotInfinite(this.size);let returnValue=!1;return this.__iterate((v,k,c)=>{if(predicate.call(context,v,k,c))return returnValue=!0,!1}),returnValue}sort(comparator){return reify(this,sortFactory(this,comparator))}values(){let iterator=this.__iterator(),result={done:!1,value:void 0};return makeIterator(()=>{let step=iterator.next();if(step.done)return DONE;return result.value=step.value[1],result})}butLast(){return this.slice(0,-1)}isEmpty(){return this.size!==void 0?this.size===0:!this.some(()=>!0)}count(predicate,context){return ensureSize(predicate?this.toSeq().filter(predicate,context):this)}countBy(_grouper,_context){throw Error("countBy: not patched — import CollectionConversions")}entrySeq(){let collection=this;if(collection._cache)return new ArraySeq(collection._cache);let entriesSequence=collection.toSeq().map(entryMapper).toIndexedSeq();return entriesSequence.fromEntrySeq=()=>collection.toSeq(),entriesSequence}filterNot(predicate,context){return this.filter(not(predicate),context)}findEntry(predicate,context,notSetValue){let found=notSetValue;return this.__iterate((v,k,c)=>{if(predicate.call(context,v,k,c))return found=[k,v],!1}),found}findKey(predicate,context){return this.findEntry(predicate,context)?.[0]}findLast(predicate,context,notSetValue){return this.toKeyedSeq().reverse().find(predicate,context,notSetValue)}findLastEntry(predicate,context,notSetValue){return this.toKeyedSeq().reverse().findEntry(predicate,context,notSetValue)}findLastKey(predicate,context){return this.toKeyedSeq().reverse().findKey(predicate,context)}first(notSetValue){return this.find(returnTrue,null,notSetValue)}flatMap(mapper,context){return reify(this,this.toSeq().map((v,k)=>(isKeyed(this)?KeyedCollection:isIndexed(this)?IndexedCollection:SetCollection)(mapper.call(context,v,k,this))).flatten(!0))}flatten(depth){let collection=this,useKeys=isKeyed(this),flatSequence=makeSequence(collection);return flatSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0,stopped=!1;function flatDeep(iter,currentDepth){iter.__iterate((v,k)=>{if((!depth||currentDepth<depth)&&isCollection(v))flatDeep(v,currentDepth+1);else if(iterations++,fn(v,useKeys?k:iterations-1,flatSequence)===!1)stopped=!0;if(stopped)return!1},reverse)}return flatDeep(collection,0),iterations},flatSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterations=0,stack=[{iterator:collection.__iterator(reverse),depth:0}];return makeEntryIterator((entry)=>{while(stack.length>0){let frame=stack[stack.length-1],step=frame.iterator.next();if(step.done){stack.pop();continue}let v=step.value[1];if((!depth||frame.depth<depth)&&isCollection(v)){stack.push({iterator:v.__iterator(reverse),depth:frame.depth+1});continue}return entry[0]=useKeys?step.value[0]:iterations++,entry[1]=v,!0}return!1})},reify(this,flatSequence)}fromEntrySeq(){return new FromEntriesSequence(this)}get(searchKey,notSetValue){return this.find((_,key)=>is(key,searchKey),void 0,notSetValue)}getIn(searchKeyPath,notSetValue){return getIn$1(this,searchKeyPath,notSetValue)}groupBy(_grouper,_context){throw Error("groupBy: not patched — import CollectionConversions")}has(searchKey){return this.get(searchKey,NOT_SET)!==NOT_SET}hasIn(searchKeyPath){return hasIn$1(this,searchKeyPath)}isSubset(iter){let other=typeof iter.includes==="function"?iter:Collection(iter);return this.every((value)=>other.includes(value))}isSuperset(iter){return(typeof iter.isSubset==="function"?iter:Collection(iter)).isSubset(this)}keyOf(searchValue){return this.findKey((value)=>is(value,searchValue))}keySeq(){return this.toSeq().map(keyMapper).toIndexedSeq()}last(notSetValue){return this.toSeq().reverse().first(notSetValue)}lastKeyOf(searchValue){return this.toKeyedSeq().reverse().keyOf(searchValue)}max(comparator){return maxFactory(this,comparator)}maxBy(mapper,comparator){return maxFactory(this,comparator,mapper)}min(comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator)}minBy(mapper,comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator,mapper)}rest(){return this.slice(1)}skip(amount){return amount===0?this:this.slice(Math.max(0,amount))}skipLast(amount){return amount===0?this:this.slice(0,-Math.max(0,amount))}skipWhile(predicate,context){let collection=this,useKeys=isKeyed(this),skipSequence=makeSequence(collection);return skipSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let skipping=!0,iterations=0;return collection.__iterate((v,k)=>{if(skipping&&predicate.call(context,v,k,this))return;return skipping=!1,iterations++,fn(v,useKeys?k:iterations-1,this)},reverse),iterations},skipSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterator=collection.__iterator(reverse),iterations=0,seq=this,skipping=!0;return makeEntryIterator((entry)=>{while(!0){let step=iterator.next();if(step.done)return!1;let k=step.value[0],v=step.value[1];if(skipping&&predicate.call(context,v,k,seq))continue;return skipping=!1,entry[0]=useKeys?k:iterations++,entry[1]=v,!0}})},reify(this,skipSequence)}skipUntil(predicate,context){return this.skipWhile(not(predicate),context)}sortBy(mapper,comparator){return reify(this,sortFactory(this,comparator,mapper))}take(amount){return this.slice(0,Math.max(0,amount))}takeLast(amount){return this.slice(-Math.max(0,amount))}takeWhile(predicate,context){let collection=this,takeSequence=makeSequence(collection);return takeSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0;return collection.__iterate((v,k)=>{if(!predicate.call(context,v,k,this))return!1;return iterations++,fn(v,k,this)},reverse),iterations},takeSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterator=collection.__iterator(reverse),seq=this,finished=!1;return makeIterator(()=>{if(finished)return DONE;let step=iterator.next();if(step.done)return step;if(!predicate.call(context,step.value[1],step.value[0],seq))return finished=!0,DONE;return step})},reify(this,takeSequence)}takeUntil(predicate,context){return this.takeWhile(not(predicate),context)}update(fn){return fn(this)}valueSeq(){return this.toIndexedSeq()}__iterate(fn,reverse=!1){let iterator=this.__iterator(reverse),iterations=0,step;while(!(step=iterator.next()).done)if(iterations++,fn(step.value[1],step.value[0],this)===!1)break;return iterations}__iterator(_reverse=!1){throw Error("CollectionImpl does not implement __iterator. Use a subclass instead.")}}var KeyedCollection=(value)=>isKeyed(value)?value:KeyedSeq(value);class KeyedCollectionImpl extends CollectionImpl{static{this.prototype[IS_KEYED_SYMBOL]=!0,this.prototype.__toStringMapper=(v,k)=>`${quoteString(k)}: ${quoteString(v)}`,this.prototype[Symbol.iterator]=CollectionImpl.prototype.entries,this.prototype.toJSON=function(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}}flip(){return reify(this,flipFactory(this))}mapEntries(mapper,context){let iterations=0;return reify(this,this.toSeq().map((v,k)=>mapper.call(context,[k,v],iterations++,this)).fromEntrySeq())}mapKeys(mapper,context){return reify(this,this.toSeq().flip().map((k,v)=>mapper.call(context,k,v,this)).flip())}}var IndexedCollection=(value)=>isIndexed(value)?value:IndexedSeq(value);class IndexedCollectionImpl extends CollectionImpl{static{this.prototype[IS_INDEXED_SYMBOL]=!0,this.prototype[IS_ORDERED_SYMBOL]=!0}toKeyedSeq(){return new ToKeyedSequence(this,!1)}findIndex(predicate,context){let entry=this.findEntry(predicate,context);return entry?entry[0]:-1}indexOf(searchValue){let key=this.keyOf(searchValue);return key===void 0?-1:key}lastIndexOf(searchValue){let key=this.lastKeyOf(searchValue);return key===void 0?-1:key}splice(index,removeNum=NOT_SET,...values){if(index===void 0)return this;let hasRemoveNum=removeNum!==NOT_SET;if(removeNum=hasRemoveNum?Math.max(removeNum||0,0):0,hasRemoveNum&&!removeNum&&values.length===0)return this;index=resolveBegin(index,index<0?this.count():this.size);let spliced=this.slice(0,index);return reify(this,!hasRemoveNum?spliced:spliced.concat(values,this.slice(index+removeNum)))}findLastIndex(predicate,context){let entry=this.findLastEntry(predicate,context);return entry?entry[0]:-1}first(notSetValue){return this.get(0,notSetValue)}get(index,notSetValue){return index=wrapIndex(this,index),index<0||this.size===1/0||this.size!==void 0&&index>this.size?notSetValue:this.find((_,key)=>key===index,void 0,notSetValue)}has(index){return index=wrapIndex(this,index),index>=0&&(this.size!==void 0?this.size===1/0||index<this.size:this.indexOf(index)!==-1)}interpose(separator){let collection=this,interposedSequence=makeSequence(collection);return interposedSequence.size=collection.size&&collection.size*2-1,interposedSequence.__iterateUncached=function(fn,reverse){let iterations=0,isFirst=!0;return collection.__iterate((v)=>{if(!isFirst){if(fn(separator,iterations++,this)===!1)return!1}return isFirst=!1,fn(v,iterations++,this)},reverse),iterations},interposedSequence.__iteratorUncached=function(reverse){let iterator=collection.__iterator(reverse),iterations=0,isFirst=!0,pendingValue,hasPending=!1;return makeEntryIterator((entry)=>{if(hasPending)return hasPending=!1,entry[0]=iterations++,entry[1]=pendingValue,!0;let step=iterator.next();if(step.done)return!1;let value=step.value[1];if(!isFirst)return pendingValue=value,hasPending=!0,entry[0]=iterations++,entry[1]=separator,!0;return isFirst=!1,entry[0]=iterations++,entry[1]=value,!0})},reify(this,interposedSequence)}interleave(...collections){let thisAndCollections=[this,...collections],zipped=zipWithFactory(this.toSeq(),IndexedSeq.of,thisAndCollections),interleaved=zipped.flatten(!0);if(zipped.size)interleaved.size=zipped.size*thisAndCollections.length;return reify(this,interleaved)}keySeq(){throw Error("keySeq: not patched — import CollectionConversions")}last(notSetValue){return this.get(-1,notSetValue)}zip(...collections){return this.zipWith(defaultZipper,...collections)}zipAll(...collections){let thisAndCollections=[this,...collections];return reify(this,zipWithFactory(this,defaultZipper,thisAndCollections,!0))}zipWith(zipper,...collections){let thisAndCollections=[this,...collections];return reify(this,zipWithFactory(this,zipper,thisAndCollections))}}var SetCollection=(value)=>isCollection(value)&&!isAssociative(value)?value:SetSeq(value);class SetCollectionImpl extends CollectionImpl{static{this.prototype.has=CollectionImpl.prototype.includes,this.prototype.contains=CollectionImpl.prototype.includes,this.prototype.keys=SetCollectionImpl.prototype.values}get(value,notSetValue){return this.has(value)?value:notSetValue}includes(value){return this.has(value)}keySeq(){return this.valueSeq()}}Collection.Keyed=KeyedCollection;Collection.Indexed=IndexedCollection;Collection.Set=SetCollection;var IndexedCollectionPrototype=IndexedCollectionImpl.prototype,Seq=(value)=>value===void 0||value===null?emptySequence():isImmutable(value)?value.toSeq():seqFromValue(value),makeSequence=(collection)=>Object.create((isKeyed(collection)?KeyedSeqImpl:isIndexed(collection)?IndexedSeqImpl:SetSeqImpl).prototype);class SeqImpl extends CollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0}toSeq(){return this}toString(){return this.__toString("Seq {","}")}cacheResult(){if(!this._cache&&this.__iterateUncached)this._cache=this.entrySeq().toArray(),this.size=this._cache.length;return this}__iterateUncached(fn,reverse){let iterator=this.__iteratorUncached(reverse),iterations=0,step;while(!(step=iterator.next()).done)if(iterations++,fn(step.value[1],step.value[0],this)===!1)break;return iterations}__iterate(fn,reverse){let cache=this._cache;if(cache){let size=cache.length,i=0;while(i!==size){let entry=cache[reverse?size-++i:i++];if(fn(entry[1],entry[0],this)===!1)break}return i}return this.__iterateUncached(fn,reverse)}__iterator(reverse){let cache=this._cache;if(cache){let size=cache.length,i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return result.value=cache[reverse?size-++i:i++],result})}return this.__iteratorUncached(reverse)}}var seqMixin={cacheResult:SeqImpl.prototype.cacheResult,__iterateUncached:SeqImpl.prototype.__iterateUncached,__iterate:SeqImpl.prototype.__iterate,__iterator:SeqImpl.prototype.__iterator},KeyedSeq=(value)=>value===void 0||value===null?emptySequence().toKeyedSeq():isCollection(value)?isKeyed(value)?value.toSeq():value.fromEntrySeq():isRecord(value)?value.toSeq():keyedSeqFromValue(value);class KeyedSeqImpl extends KeyedCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toKeyedSeq(){return this}}var IndexedSeq=(value)=>value===void 0||value===null?emptySequence():isCollection(value)?isKeyed(value)?value.entrySeq():value.toIndexedSeq():isRecord(value)?value.toSeq().entrySeq():indexedSeqFromValue(value);IndexedSeq.of=(...values)=>IndexedSeq(values);class IndexedSeqImpl extends IndexedCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toIndexedSeq(){return this}toString(){return this.__toString("Seq [","]")}}var SetSeq=(value)=>(isCollection(value)&&!isAssociative(value)?value:IndexedSeq(value)).toSetSeq();SetSeq.of=(...values)=>SetSeq(values);class SetSeqImpl extends SetCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toSetSeq(){return this}}Seq.isSeq=isSeq;Seq.Keyed=KeyedSeq;Seq.Set=SetSeq;Seq.Indexed=IndexedSeq;class ArraySeq extends IndexedSeqImpl{constructor(array){super();this._array=array,this.size=array.length}get(index,notSetValue){return this.has(index)?this._array[wrapIndex(this,index)]:notSetValue}__iterateUncached(fn,reverse){let array=this._array,size=array.length,i=0;while(i!==size){let ii=reverse?size-++i:i++;if(fn(array[ii],ii,this)===!1)break}return i}__iteratorUncached(reverse){let array=this._array,size=array.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let ii=reverse?size-++i:i++;return entry[0]=ii,entry[1]=array[ii],!0})}}class ObjectSeq extends KeyedSeqImpl{static{this.prototype[IS_ORDERED_SYMBOL]=!0}constructor(object){super();let keys=[...Object.keys(object),...Object.getOwnPropertySymbols(object)];this._object=object,this._keys=keys,this.size=keys.length}get(key,notSetValue){if(notSetValue!==void 0&&!this.has(key))return notSetValue;return this._object[key]}has(key){return Object.hasOwn(this._object,key)}__iterateUncached(fn,reverse){let object=this._object,keys=this._keys,size=keys.length,i=0;while(i!==size){let key=keys[reverse?size-++i:i++];if(fn(object[key],key,this)===!1)break}return i}__iteratorUncached(reverse){let object=this._object,keys=this._keys,size=keys.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let key=keys[reverse?size-++i:i++];return entry[0]=key,entry[1]=object[key],!0})}}class CollectionSeq extends IndexedSeqImpl{constructor(collection){super();this._collection=collection,this.size=collection.length||collection.size}__iterateUncached(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0;for(let value of this._collection){if(fn(value,iterations,this)===!1)break;iterations++}return iterations}__iteratorUncached(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let collection=this._collection,iterator=getIterator(collection);if(!isIterator(iterator))return emptyIterator();let iterations=0;return makeEntryIterator((entry)=>{let step=iterator.next();if(step.done)return!1;return entry[0]=iterations++,entry[1]=step.value,!0})}}var emptySequence=()=>new ArraySeq([]),maybeIndexedSeqFromValue=(value)=>isArrayLike(value)?new ArraySeq(value):hasIterator(value)?new CollectionSeq(value):void 0;function keyedSeqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return seq.fromEntrySeq();if(typeof value==="object")return new ObjectSeq(value);throw TypeError(`Expected Array or collection object of [k, v] entries, or keyed object: ${value}`)}function indexedSeqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return seq;throw TypeError(`Expected Array or collection object of values: ${value}`)}function seqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return isEntriesIterable(value)?seq.fromEntrySeq():isKeysIterable(value)?seq.toSetSeq():seq;if(typeof value==="object")return new ObjectSeq(value);throw TypeError(`Expected Array or collection object of values, or keyed object: ${value}`)}class ConcatSeq extends SeqImpl{constructor(iterables){super();let wrappedIterables=[],size=0,sizeKnown=!0;for(let iterable of iterables)if(iterable._wrappedIterables){for(let wrapped of iterable._wrappedIterables)if(wrappedIterables.push(wrapped),sizeKnown){let s=wrapped.size;if(s!==void 0)size+=s;else sizeKnown=!1}}else if(wrappedIterables.push(iterable),sizeKnown){let s=iterable.size;if(s!==void 0)size+=s;else sizeKnown=!1}this._wrappedIterables=wrappedIterables,this.size=sizeKnown?size:void 0;let first=this._wrappedIterables[0];if(first[IS_KEYED_SYMBOL])this[IS_KEYED_SYMBOL]=!0;if(first[IS_INDEXED_SYMBOL])this[IS_INDEXED_SYMBOL]=!0;if(first[IS_ORDERED_SYMBOL])this[IS_ORDERED_SYMBOL]=!0}__iterateUncached(fn,reverse){if(this._wrappedIterables.length===0)return 0;if(reverse)return this.cacheResult().__iterate(fn,reverse);let wrappedIterables=this._wrappedIterables,reIndex=!isKeyed(this),index=0,stopped=!1;for(let iterable of wrappedIterables)if(iterable.__iterate((v,k)=>{if(fn(v,reIndex?index++:k,this)===!1)return stopped=!0,!1},reverse),stopped)break;return index}__iteratorUncached(reverse){if(this._wrappedIterables.length===0)return emptyIterator();if(reverse)return this.cacheResult().__iterator(reverse);let wrappedIterables=this._wrappedIterables,reIndex=!isKeyed(this),iterableIdx=0,currentIterator=wrappedIterables[0].__iterator(reverse);function nextStep(){while(iterableIdx<wrappedIterables.length){let step=currentIterator.next();if(!step.done)return step;if(iterableIdx++,iterableIdx<wrappedIterables.length)currentIterator=wrappedIterables[iterableIdx].__iterator(reverse)}return}if(reIndex){let index=0;return makeEntryIterator((entry)=>{let step=nextStep();if(!step)return!1;return entry[0]=index++,entry[1]=step.value[1],!0})}return makeIterator(()=>nextStep()||DONE)}}class ToKeyedSequence extends KeyedSeqImpl{static{this.prototype[IS_ORDERED_SYMBOL]=!0}constructor(indexed,useKeys){super();this._iter=indexed,this._useKeys=useKeys,this.size=indexed.size}cacheResult(){return cacheResultThrough.call(this)}get(key,notSetValue){return this._iter.get(key,notSetValue)}has(key){return this._iter.has(key)}valueSeq(){return this._iter.valueSeq()}reverse(){let reversedSequence=reverseFactory(this,!0);if(!this._useKeys)reversedSequence.valueSeq=()=>this._iter.toSeq().reverse();return reversedSequence}map(mapper,context){let mappedSequence=mapFactory(this,mapper,context);if(!this._useKeys)mappedSequence.valueSeq=()=>this._iter.toSeq().map(mapper,context);return mappedSequence}__iterateUncached(fn,reverse){return this._iter.__iterate(fn,reverse)}__iteratorUncached(reverse){return this._iter.__iterator(reverse)}}class ToIndexedSequence extends IndexedSeqImpl{constructor(iter){super();this._iter=iter,this.size=iter.size}cacheResult(){return cacheResultThrough.call(this)}includes(value){return this._iter.includes(value)}__iterateUncached(fn,reverse){let i=0;if(reverse)ensureSize(this);let size=this.size;return this._iter.__iterate((v)=>{let ii=reverse?size-++i:i++;return fn(v,ii,this)},reverse),i}__iteratorUncached(reverse){let i=0;if(reverse)ensureSize(this);let size=this.size;return mapEntries(this._iter.__iterator(reverse),(k,v,entry)=>{entry[0]=reverse?size-++i:i++,entry[1]=v})}}class ToSetSequence extends SetSeqImpl{constructor(iter){super();this._iter=iter,this.size=iter.size}cacheResult(){return cacheResultThrough.call(this)}has(key){return this._iter.includes(key)}__iterateUncached(fn,reverse){return this._iter.__iterate((v)=>fn(v,v,this),reverse)}__iteratorUncached(reverse){return mapEntries(this._iter.__iterator(reverse),(k,v,entry)=>{entry[0]=v,entry[1]=v})}}class FromEntriesSequence extends KeyedSeqImpl{constructor(entries){super();this._iter=entries,this.size=entries.size}cacheResult(){return cacheResultThrough.call(this)}entrySeq(){return this._iter.toSeq()}__iterateUncached(fn,reverse){let iterations=0;return this._iter.__iterate((entry)=>{if(entry){validateEntry(entry),iterations++;let indexedCollection=isCollection(entry);return fn(indexedCollection?entry.get(1):entry[1],indexedCollection?entry.get(0):entry[0],this)}},reverse),iterations}__iteratorUncached(reverse){let iterator=this._iter.__iterator(reverse);return makeEntryIterator((out)=>{while(!0){let step=iterator.next();if(step.done)return!1;let entry=step.value[1];if(entry){validateEntry(entry);let indexedCollection=isCollection(entry);return out[0]=indexedCollection?entry.get(0):entry[0],out[1]=indexedCollection?entry.get(1):entry[1],!0}}})}}function cacheResultThrough(){if(this._iter.cacheResult)return this._iter.cacheResult(),this.size=this._iter.size,this;return SeqImpl.prototype.cacheResult.call(this)}function validateEntry(entry){if(entry!==Object(entry))throw TypeError(`Expected [K, V] tuple: ${entry}`)}var Map2=(value)=>value===void 0||value===null?emptyMap():isMap(value)&&!isOrdered(value)?value:emptyMap().withMutations((map)=>{let iter=KeyedCollection(value);assertNotInfinite(iter.size),iter.forEach((v,k)=>map.set(k,v))});class MapImpl extends KeyedCollectionImpl{static{mixin(this,{asImmutable,asMutable,deleteIn,merge,mergeWith,mergeDeep,mergeDeepWith,mergeDeepIn,mergeIn,setIn,update,updateIn,wasAltered,withMutations,removeIn:deleteIn,concat:merge,[IS_MAP_SYMBOL]:!0,[DELETE]:this.prototype.remove,removeAll:this.prototype.deleteAll,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.Map"})}constructor(size,root,ownerID,hash2){super();this.size=size,this._root=root,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return Map2(value)}toString(){return this.__toString("Map {","}")}get(k,notSetValue){return this._root?this._root.get(0,hash(k),k,notSetValue):notSetValue}set(k,v){return updateMap(this,k,v)}remove(k){return updateMap(this,k,NOT_SET)}deleteAll(keys){let collection=Collection(keys);if(collection.size===0)return this;return this.withMutations((map)=>{collection.forEach((key)=>map.remove(key))})}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this;return emptyMap()}map(mapper,context){return this.withMutations((map)=>{map.forEach((value,key)=>{map.set(key,mapper.call(context,value,key,this))})})}keys(){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,!1,0)}values(){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,!1,1)}entries(){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,!1)}__iterator(reverse){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,reverse)}__iterate(fn,reverse){let iterations=0;if(this._root)this._root.iterate(([key,value])=>{return iterations++,fn(value,key,this)},reverse);return iterations}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;if(!ownerID){if(this.size===0)return emptyMap();return this.__ownerID=ownerID,this.__altered=!1,this}return makeMap(this.size,this._root,ownerID,this.__hash)}}Map2.isMap=isMap;class ArrayMapNode{constructor(ownerID,entries){this.ownerID=ownerID,this.entries=entries}get(shift,keyHash,key,notSetValue){return linearGet(this.entries,key,notSetValue)}iterate(fn,reverse){return iterateLinearEntries(this.entries,fn,reverse)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let removed=value===NOT_SET,entries=this.entries,idx=0,len=entries.length;for(;idx<len;idx++)if(is(key,entries[idx][0]))break;let exists=idx<len;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),removed||!exists)SetRef(didChangeSize);if(removed&&len===1)return;if(!exists&&!removed&&len>=MAX_ARRAY_MAP_SIZE)return createNodes(ownerID,entries,key,value);let isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:entries.slice();if(exists)if(removed)if(idx===len-1)newEntries.pop();else newEntries[idx]=newEntries.pop();else newEntries[idx]=[key,value];else newEntries.push([key,value]);if(isEditable)return this.entries=newEntries,this;return new ArrayMapNode(ownerID,newEntries)}}class BitmapIndexedNode{constructor(ownerID,bitmap,nodes){this.ownerID=ownerID,this.bitmap=bitmap,this.nodes=nodes}iterate(fn,reverse){return iterateNodeArray(this.nodes,fn,reverse)}get(shift,keyHash,key,notSetValue){let bit=1<<((shift===0?keyHash:keyHash>>>shift)&MASK),bitmap=this.bitmap;return(bitmap&bit)===0?notSetValue:this.nodes[popCount(bitmap&bit-1)].get(shift+SHIFT,keyHash,key,notSetValue)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let keyHashFrag=(shift===0?keyHash:keyHash>>>shift)&MASK,bit=1<<keyHashFrag,bitmap=this.bitmap,exists=(bitmap&bit)!==0;if(!exists&&value===NOT_SET)return this;let idx=popCount(bitmap&bit-1),nodes=this.nodes,node=exists?nodes[idx]:void 0,newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node)return this;if(!exists&&newNode&&nodes.length>=MAX_BITMAP_INDEXED_SIZE)return expandNodes(ownerID,nodes,bitmap,keyHashFrag,newNode);if(exists&&!newNode&&nodes.length===2&&isLeafNode(nodes[idx^1]))return nodes[idx^1];if(exists&&newNode&&nodes.length===1&&isLeafNode(newNode))return newNode;let isEditable=ownerID&&ownerID===this.ownerID,newBitmap=exists?newNode?bitmap:bitmap^bit:bitmap|bit,newNodes=exists?newNode?setAt(nodes,idx,newNode,isEditable):spliceOut(nodes,idx,isEditable):spliceIn(nodes,idx,newNode,isEditable);if(isEditable)return this.bitmap=newBitmap,this.nodes=newNodes,this;return new BitmapIndexedNode(ownerID,newBitmap,newNodes)}}class HashArrayMapNode{constructor(ownerID,count,nodes){this.ownerID=ownerID,this.count=count,this.nodes=nodes}iterate(fn,reverse){return iterateNodeArray(this.nodes,fn,reverse)}get(shift,keyHash,key,notSetValue){let idx=(shift===0?keyHash:keyHash>>>shift)&MASK,node=this.nodes[idx];return node?node.get(shift+SHIFT,keyHash,key,notSetValue):notSetValue}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let idx=(shift===0?keyHash:keyHash>>>shift)&MASK,removed=value===NOT_SET,nodes=this.nodes,node=nodes[idx];if(removed&&!node)return this;let newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node)return this;let newCount=this.count;if(!node)newCount++;else if(!newNode){if(newCount--,newCount<MIN_HASH_ARRAY_MAP_SIZE)return packNodes(ownerID,nodes,newCount,idx)}let isEditable=ownerID&&ownerID===this.ownerID,newNodes=setAt(nodes,idx,newNode,isEditable);if(isEditable)return this.count=newCount,this.nodes=newNodes,this;return new HashArrayMapNode(ownerID,newCount,newNodes)}}class HashCollisionNode{constructor(ownerID,keyHash,entries){this.ownerID=ownerID,this.keyHash=keyHash,this.entries=entries}get(shift,keyHash,key,notSetValue){return linearGet(this.entries,key,notSetValue)}iterate(fn,reverse){return iterateLinearEntries(this.entries,fn,reverse)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(keyHash!==this.keyHash){if(value===NOT_SET)return this;return SetRef(didAlter),SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,keyHash,[key,value])}let removed=value===NOT_SET,entries=this.entries,idx=0,len=entries.length;for(;idx<len;idx++)if(is(key,entries[idx][0]))break;let exists=idx<len;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),removed||!exists)SetRef(didChangeSize);if(removed&&len===2)return new ValueNode(ownerID,this.keyHash,entries[idx^1]);let isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:entries.slice();if(exists)if(removed)if(idx===len-1)newEntries.pop();else newEntries[idx]=newEntries.pop();else newEntries[idx]=[key,value];else newEntries.push([key,value]);if(isEditable)return this.entries=newEntries,this;return new HashCollisionNode(ownerID,this.keyHash,newEntries)}}class ValueNode{constructor(ownerID,keyHash,entry){this.ownerID=ownerID,this.keyHash=keyHash,this.entry=entry}iterate(fn,_reverse){return fn(this.entry)}get(shift,keyHash,key,notSetValue){return is(key,this.entry[0])?this.entry[1]:notSetValue}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let removed=value===NOT_SET,keyMatch=is(key,this.entry[0]);if(keyMatch?value===this.entry[1]:removed)return this;if(SetRef(didAlter),removed){SetRef(didChangeSize);return}if(keyMatch){if(ownerID&&ownerID===this.ownerID)return this.entry[1]=value,this;return new ValueNode(ownerID,this.keyHash,[key,value])}return SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,hash(key),[key,value])}}function linearGet(entries,key,notSetValue){for(let ii=0,len=entries.length;ii<len;ii++)if(is(key,entries[ii][0]))return entries[ii][1];return notSetValue}function iterateLinearEntries(entries,fn,reverse){for(let ii=0,maxIndex=entries.length-1;ii<=maxIndex;ii++)if(fn(entries[reverse?maxIndex-ii:ii])===!1)return!1}function iterateNodeArray(nodes,fn,reverse){for(let ii=0,maxIndex=nodes.length-1;ii<=maxIndex;ii++)if(nodes[reverse?maxIndex-ii:ii]?.iterate(fn,reverse)===!1)return!1}function mapIteratorGenerator(node,reverse,entryIndex){let stack={node,index:0,__prev:null},extractValue=entryIndex!==void 0?(entry)=>entry[entryIndex]:(entry)=>entry,result={done:!1,value:void 0};return makeIterator(()=>{while(stack){let node2=stack.node,index=stack.index++,maxIndex;if(node2.entry){if(index===0)return result.value=extractValue(node2.entry),result}else if(node2.entries){if(maxIndex=node2.entries.length-1,index<=maxIndex)return result.value=extractValue(node2.entries[reverse?maxIndex-index:index]),result}else if(maxIndex=node2.nodes.length-1,index<=maxIndex){let subNode=node2.nodes[reverse?maxIndex-index:index];if(subNode){if(subNode.entry)return result.value=extractValue(subNode.entry),result;stack={node:subNode,index:0,__prev:stack}}continue}stack=stack.__prev}return DONE})}var makeMap=(size,root,ownerID,hash2)=>new MapImpl(size,root,ownerID,hash2),EMPTY_MAP,emptyMap=()=>EMPTY_MAP||(EMPTY_MAP=makeMap(0));function updateMap(map,k,v){let newRoot,newSize;if(!map._root){if(v===NOT_SET)return map;newSize=1,newRoot=new ArrayMapNode(map.__ownerID,[[k,v]])}else{let didChangeSize=MakeRef(),didAlter=MakeRef();if(newRoot=updateNode(map._root,map.__ownerID,0,hash(k),k,v,didChangeSize,didAlter),!didAlter.value)return map;newSize=map.size+(didChangeSize.value?v===NOT_SET?-1:1:0)}if(map.__ownerID)return map.size=newSize,map._root=newRoot,map.__hash=void 0,map.__altered=!0,map;return newRoot?makeMap(newSize,newRoot):emptyMap()}function updateNode(node,ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(!node){if(value===NOT_SET)return node;return SetRef(didAlter),SetRef(didChangeSize),new ValueNode(ownerID,keyHash,[key,value])}return node.update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter)}var isLeafNode=(node)=>node.constructor===ValueNode||node.constructor===HashCollisionNode;function mergeIntoNode(node,ownerID,shift,keyHash,entry){if(node.keyHash===keyHash)return new HashCollisionNode(ownerID,keyHash,[node.entry,entry]);let idx1=(shift===0?node.keyHash:node.keyHash>>>shift)&MASK,idx2=(shift===0?keyHash:keyHash>>>shift)&MASK,newNode=new ValueNode(ownerID,keyHash,entry),nodes=idx1===idx2?[mergeIntoNode(node,ownerID,shift+SHIFT,keyHash,entry)]:idx1<idx2?[node,newNode]:[newNode,node];return new BitmapIndexedNode(ownerID,1<<idx1|1<<idx2,nodes)}function createNodes(ownerID,entries,key,value){if(!ownerID)ownerID=new OwnerID;let node=new ValueNode(ownerID,hash(key),[key,value]);for(let[k,v]of entries)node=node.update(ownerID,0,hash(k),k,v);return node}function packNodes(ownerID,nodes,count,excluding){let bitmap=0,packedII=0,packedNodes=Array(count);for(let ii=0,bit=1,len=nodes.length;ii<len;ii++,bit<<=1){let node=nodes[ii];if(node!==void 0&&ii!==excluding)bitmap|=bit,packedNodes[packedII++]=node}return new BitmapIndexedNode(ownerID,bitmap,packedNodes)}function expandNodes(ownerID,nodes,bitmap,including,node){let count=0,expandedNodes=Array(SIZE);for(let ii=0;bitmap!==0;ii++,bitmap>>>=1)expandedNodes[ii]=bitmap&1?nodes[count++]:void 0;return expandedNodes[including]=node,new HashArrayMapNode(ownerID,count+1,expandedNodes)}function popCount(x){return x-=x>>1&1431655765,x=(x&858993459)+(x>>2&858993459),x=x+(x>>4)&252645135,x+=x>>8,x+=x>>16,x&127}function setAt(array,idx,val,canEdit){let newArray=canEdit?array:array.slice();return newArray[idx]=val,newArray}function spliceIn(array,idx,val,canEdit){let newLen=array.length+1;if(canEdit&&idx+1===newLen)return array[idx]=val,array;let newArray=Array(newLen),after=0;for(let ii=0;ii<newLen;ii++)if(ii===idx)newArray[ii]=val,after=-1;else newArray[ii]=array[ii+after];return newArray}function spliceOut(array,idx,canEdit){let newLen=array.length-1;if(canEdit&&idx===newLen)return array.pop(),array;let newArray=Array(newLen),after=0;for(let ii=0;ii<newLen;ii++){if(ii===idx)after=1;newArray[ii]=array[ii+after]}return newArray}var MAX_ARRAY_MAP_SIZE=SIZE/4,MAX_BITMAP_INDEXED_SIZE=SIZE/2,MIN_HASH_ARRAY_MAP_SIZE=SIZE/4;function shallowCopy(from){if(Array.isArray(from))return from.slice();return{...from}}var merge$1=(collection,...sources)=>mergeWithSources(collection,sources),mergeWith$1=(merger,collection,...sources)=>mergeWithSources(collection,sources,merger),mergeDeepWithSources=(collection,sources,merger)=>mergeWithSources(collection,sources,deepMergerWith(merger)),mergeDeep$1=(collection,...sources)=>mergeDeepWithSources(collection,sources),mergeDeepWith$1=(merger,collection,...sources)=>mergeDeepWithSources(collection,sources,merger);function mergeWithSources(collection,sources,merger){if(!isDataStructure(collection))throw TypeError(`Cannot merge into non-data-structure value: ${collection}`);if(isImmutable(collection))return typeof merger==="function"&&collection.mergeWith?collection.mergeWith(merger,...sources):collection.merge?collection.merge(...sources):collection.concat(...sources);let isArray=Array.isArray(collection),merged=collection,Collection2=isArray?IndexedCollection:KeyedCollection,mergeItem=isArray?(value)=>{if(merged===collection)merged=shallowCopy(merged);merged.push(value)}:(value,key)=>{let hasVal=Object.hasOwn(merged,key),nextVal=hasVal&&merger?merger(merged[key],value,key):value;if(!hasVal||nextVal!==merged[key]){if(merged===collection)merged=shallowCopy(merged);merged[key]=nextVal}};for(let source of sources)Collection2(source).forEach(mergeItem);return merged}function deepMergerWith(merger){function deepMerger(oldValue,newValue,key){return isDataStructure(oldValue)&&isDataStructure(newValue)&&areMergeable(oldValue,newValue)?mergeWithSources(oldValue,[newValue],deepMerger):merger?merger(oldValue,newValue,key):newValue}return deepMerger}function areMergeable(oldDataStructure,newDataStructure){let oldSeq=Seq(oldDataStructure),newSeq=Seq(newDataStructure);return isIndexed(oldSeq)===isIndexed(newSeq)&&isKeyed(oldSeq)===isKeyed(newSeq)}function remove(collection,key){if(!isDataStructure(collection))throw TypeError(`Cannot update non-data-structure value: ${collection}`);if(isImmutable(collection)){if(!collection.remove)throw TypeError(`Cannot update immutable value without .remove() method: ${collection}`);return collection.remove(key)}if(!Object.hasOwn(collection,key))return collection;let collectionCopy=shallowCopy(collection);if(Array.isArray(collectionCopy))collectionCopy.splice(key,1);else delete collectionCopy[key];return collectionCopy}function set2(collection,key,value){if(!isDataStructure(collection))throw TypeError(`Cannot update non-data-structure value: ${collection}`);if(isImmutable(collection)){if(!collection.set)throw TypeError(`Cannot update immutable value without .set() method: ${collection}`);return collection.set(key,value)}if(Object.hasOwn(collection,key)&&value===collection[key])return collection;let collectionCopy=shallowCopy(collection);return collectionCopy[key]=value,collectionCopy}function updateIn$1(collection,keyPath,notSetValue,updater){if(!updater)updater=notSetValue,notSetValue=void 0;let updatedValue=updateInDeeply(isImmutable(collection),collection,coerceKeyPath(keyPath),0,notSetValue,updater);return updatedValue===NOT_SET?notSetValue:updatedValue}function updateInDeeply(inImmutable,existing,keyPath,i,notSetValue,updater){let wasNotSet=existing===NOT_SET;if(i===keyPath.length){let existingValue=wasNotSet?notSetValue:existing,newValue=updater(existingValue);return newValue===existingValue?existing:newValue}if(!wasNotSet&&!isDataStructure(existing))throw TypeError(`Cannot update within non-data-structure value in path [${Array.from(keyPath).slice(0,i).map(quoteString)}]: ${existing}`);let key=keyPath[i],nextExisting=wasNotSet?NOT_SET:get2(existing,key,NOT_SET),nextUpdated=updateInDeeply(nextExisting===NOT_SET?inImmutable:isImmutable(nextExisting),nextExisting,keyPath,i+1,notSetValue,updater);if(nextUpdated===nextExisting)return existing;if(nextUpdated===NOT_SET)return remove(existing,key);let collection=wasNotSet?inImmutable?emptyMap():{}:existing;return set2(collection,key,nextUpdated)}var removeIn=(collection,keyPath)=>updateIn$1(collection,keyPath,()=>NOT_SET),setIn$1=(collection,keyPath,value)=>updateIn$1(collection,keyPath,NOT_SET,()=>value);function update$1(collection,key,notSetValue,updater){return updateIn$1(collection,[key],notSetValue,updater)}function asImmutable(){return this.__ensureOwner()}function asMutable(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)}function wasAltered(){return this.__altered}function withMutations(fn){let mutable=this.asMutable();return fn(mutable),mutable.wasAltered()?mutable.__ensureOwner(this.__ownerID):this}function getIn(searchKeyPath,notSetValue){return getIn$1(this,searchKeyPath,notSetValue)}function hasIn(searchKeyPath){return hasIn$1(this,searchKeyPath)}function deleteIn(keyPath){return removeIn(this,keyPath)}function setIn(keyPath,v){return setIn$1(this,keyPath,v)}function update(key,notSetValue,updater){return typeof key==="function"?key(this):update$1(this,key,notSetValue,updater)}function updateIn(keyPath,notSetValue,updater){return updateIn$1(this,keyPath,notSetValue,updater)}function toObject(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}function merge(...iters){return mergeIntoKeyedWith(this,iters)}function mergeWith(merger,...iters){if(typeof merger!=="function")throw TypeError(`Invalid merger function: ${merger}`);return mergeIntoKeyedWith(this,iters,merger)}function mergeIntoKeyedWith(collection,collections,merger){let iters=[];for(let item of collections){let collection2=KeyedCollection(item);if(collection2.size!==0)iters.push(collection2)}if(iters.length===0)return collection;if(collection.toSeq().size===0&&!collection.__ownerID&&iters.length===1)return isRecord(collection)?collection:collection.create(iters[0]);return collection.withMutations((collection2)=>{let mergeIntoCollection=merger?(value,key)=>{update$1(collection2,key,NOT_SET,(oldVal)=>oldVal===NOT_SET?value:merger(oldVal,value,key))}:(value,key)=>{collection2.set(key,value)};for(let iter of iters)iter.forEach(mergeIntoCollection)})}function mergeDeep(...iters){return mergeDeepWithSources(this,iters)}function mergeDeepWith(merger,...iters){return mergeDeepWithSources(this,iters,merger)}function mergeIn(keyPath,...iters){return updateIn$1(this,keyPath,emptyMap(),(m)=>mergeWithSources(m,iters))}function mergeDeepIn(keyPath,...iters){return updateIn$1(this,keyPath,emptyMap(),(m)=>mergeDeepWithSources(m,iters))}function mixin(Class,methods){Object.assign(Class.prototype,methods)}var List=(value)=>{let empty=emptyList();if(value===void 0||value===null)return empty;if(isList(value))return value;let iter=IndexedCollection(value),size=iter.size;if(size===0)return empty;if(assertNotInfinite(size),size>0&&size<SIZE)return makeList(0,size,SHIFT,null,new VNode(iter.toArray()));return empty.withMutations((list)=>{list.setSize(size),iter.forEach((v,i)=>list.set(i,v))})};List.of=(...values)=>List(values);class ListImpl extends IndexedCollectionImpl{static{mixin(this,{asImmutable,asMutable,deleteIn,mergeDeepIn,mergeIn,setIn,update,updateIn,wasAltered,withMutations,removeIn:deleteIn,[IS_LIST_SYMBOL]:!0,[DELETE]:this.prototype.remove,merge:this.prototype.concat,[Symbol.toStringTag]:"Immutable.List",[Symbol.iterator]:this.prototype.values})}constructor(origin,capacity,level,root,tail,ownerID,hash2){super();this.size=capacity-origin,this._origin=origin,this._capacity=capacity,this._level=level,this._root=root,this._tail=tail,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return List(value)}toString(){return this.__toString("List [","]")}get(index,notSetValue){if(index=wrapIndex(this,index),index>=0&&index<this.size)return index+=this._origin,listNodeFor(this,index)?.array[index&MASK];return notSetValue}set(index,value){return updateList(this,index,value)}remove(index){return!this.has(index)?this:index===0?this.shift():index===this.size-1?this.pop():this.splice(index,1)}insert(index,value){return this.splice(index,0,value)}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=this._origin=this._capacity=0,this._level=SHIFT,this._root=this._tail=this.__hash=void 0,this.__altered=!0,this;return emptyList()}push(...values){let oldSize=this.size;return this.withMutations((list)=>{setListBounds(list,0,oldSize+values.length);for(let ii=0;ii<values.length;ii++)list.set(oldSize+ii,values[ii])})}pop(){return setListBounds(this,0,-1)}unshift(...values){return this.withMutations((list)=>{setListBounds(list,-values.length);for(let ii=0;ii<values.length;ii++)list.set(ii,values[ii])})}shift(){return setListBounds(this,1)}shuffle(random=Math.random){return this.withMutations((mutable)=>{let current=mutable.size,destination,tmp;while(current)destination=Math.floor(random()*current--),tmp=mutable.get(destination),mutable.set(destination,mutable.get(current)),mutable.set(current,tmp)})}concat(...collections){let seqs=[];for(let collection of collections){let seq=IndexedCollection(typeof collection!=="string"&&hasIterator(collection)?collection:[collection]);if(seq.size!==0)seqs.push(seq)}if(seqs.length===0)return this;if(this.size===0&&!this.__ownerID&&seqs.length===1)return List(seqs[0]);return this.withMutations((list)=>{seqs.forEach((seq)=>seq.forEach((value)=>list.push(value)))})}setSize(size){return setListBounds(this,0,size)}map(mapper,context){return this.withMutations((list)=>{for(let i=0;i<this.size;i++)list.set(i,mapper.call(context,list.get(i),i,this))})}slice(begin,end){let size=this.size;if(wholeSlice(begin,end,size))return this;return setListBounds(this,resolveBegin(begin,size),resolveEnd(end,size))}__iterate(fn,reverse){let index=reverse?this.size:0;return iterateListCallback(this,(value)=>fn(value,reverse?--index:index++,this),reverse),reverse?this.size-index:index}__iterator(reverse){let index=reverse?this.size:0,iter=iterateList(this,reverse);return makeEntryIterator((entry)=>{let step=iter.next();if(step.done)return!1;return entry[0]=reverse?--index:index++,entry[1]=step.value,!0})}values(){return iterateList(this,!1)}keys(){return makeIndexKeys(this.size)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;if(!ownerID){if(this.size===0)return emptyList();return this.__ownerID=ownerID,this.__altered=!1,this}return makeList(this._origin,this._capacity,this._level,this._root,this._tail,ownerID,this.__hash)}}List.isList=isList;class VNode{constructor(array,ownerID){this.array=array,this.ownerID=ownerID}removeBefore(ownerID,level,index){if((index&(1<<level+SHIFT)-1)===0||this.array.length===0)return this;let originIndex=index>>>level&MASK;if(originIndex>=this.array.length)return new VNode([],ownerID);let removingFirst=originIndex===0,newChild;if(level>0){let oldChild=this.array[originIndex];if(newChild=oldChild?.removeBefore(ownerID,level-SHIFT,index),newChild===oldChild&&removingFirst)return this}if(removingFirst&&!newChild)return this;let editable=editableVNode(this,ownerID);if(!removingFirst)for(let ii=0;ii<originIndex;ii++)editable.array[ii]=void 0;if(newChild)editable.array[originIndex]=newChild;return editable}removeAfter(ownerID,level,index){if(index===(level?1<<level+SHIFT:SIZE)||this.array.length===0)return this;let sizeIndex=index-1>>>level&MASK;if(sizeIndex>=this.array.length)return this;let newChild;if(level>0){let oldChild=this.array[sizeIndex];if(newChild=oldChild?.removeAfter(ownerID,level-SHIFT,index),newChild===oldChild&&sizeIndex===this.array.length-1)return this}let editable=editableVNode(this,ownerID);if(editable.array.splice(sizeIndex+1),newChild)editable.array[sizeIndex]=newChild;return editable}}function iterateList(list,reverse){let{_origin:left,_capacity:right}=list,tailPos=getTailOffset(right),tail=list._tail,stack=[];pushFrame(list._root,list._level,0);let result={done:!1,value:void 0};return makeIterator(()=>{while(stack.length>0){let frame=stack[stack.length-1];if(frame.from===frame.to){stack.pop();continue}let idx=reverse?--frame.to:frame.from++;if(frame.isLeaf)return result.value=frame.array?.[idx],result;let childNode=frame.array?.[idx],childLevel=frame.level-SHIFT,childOffset=frame.offset+(idx<<frame.level);pushFrame(childNode,childLevel,childOffset)}return DONE});function pushFrame(node,level,offset){if(level===0){let array=offset===tailPos?tail?.array:node?.array,from=offset>left?0:left-offset,to=right-offset;if(to>SIZE)to=SIZE;if(from!==to)stack.push({array,from,to,isLeaf:!0})}else{let array=node?.array,from=offset>left?0:left-offset>>level,to=(right-offset>>level)+1;if(to>SIZE)to=SIZE;if(from!==to)stack.push({array,from,to,level,offset,isLeaf:!1})}}}function iterateListCallback(list,fn,reverse){let{_origin:left,_capacity:right}=list,tailPos=getTailOffset(right),tail=list._tail,level=list._level,root=list._root;return level===0?iterateLeaf(root,0,left,right,tailPos,tail,fn,reverse):iterateNode(root,level,0,left,right,tailPos,tail,fn,reverse)}function iterateLeaf(node,offset,left,right,tailPos,tail,fn,reverse){let array=offset===tailPos?tail?.array:node?.array,from=offset>left?0:left-offset,to=right-offset;if(to>SIZE)to=SIZE;while(from!==to){let idx=reverse?--to:from++;if(fn(array?.[idx])===!1)return!1}}function iterateNode(node,level,offset,left,right,tailPos,tail,fn,reverse){let array=node?.array,from=offset>left?0:left-offset>>level,to=(right-offset>>level)+1;if(to>SIZE)to=SIZE;let nextLevel=level-SHIFT;while(from!==to){let idx=reverse?--to:from++,nextOffset=offset+(idx<<level);if((nextLevel===0?iterateLeaf(array?.[idx],nextOffset,left,right,tailPos,tail,fn,reverse):iterateNode(array?.[idx],nextLevel,nextOffset,left,right,tailPos,tail,fn,reverse))===!1)return!1}}var makeList=(origin,capacity,level,root,tail,ownerID,hash2)=>new ListImpl(origin,capacity,level,root,tail,ownerID,hash2),emptyList=()=>makeList(0,0,SHIFT);function updateList(list,index,value){if(index=wrapIndex(list,index),Number.isNaN(index))return list;if(index>=list.size||index<0)return list.withMutations((list2)=>{if(index<0)setListBounds(list2,index).set(0,value);else setListBounds(list2,0,index+1).set(index,value)});index+=list._origin;let{_tail:newTail,_root:newRoot}=list,didAlter=MakeRef();if(index>=getTailOffset(list._capacity))newTail=updateVNode(newTail,list.__ownerID,0,index,value,didAlter);else newRoot=updateVNode(newRoot,list.__ownerID,list._level,index,value,didAlter);if(!didAlter.value)return list;if(list.__ownerID)return list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list;return makeList(list._origin,list._capacity,list._level,newRoot,newTail)}function updateVNode(node,ownerID,level,index,value,didAlter){let idx=index>>>level&MASK,nodeHas=node&&idx<node.array.length;if(!nodeHas&&value===void 0)return node;let newNode;if(level>0){let lowerNode=node?.array[idx],newLowerNode=updateVNode(lowerNode,ownerID,level-SHIFT,index,value,didAlter);if(newLowerNode===lowerNode)return node;return newNode=editableVNode(node,ownerID),newNode.array[idx]=newLowerNode,newNode}if(nodeHas&&node.array[idx]===value)return node;if(didAlter)SetRef(didAlter);if(newNode=editableVNode(node,ownerID),value===void 0&&idx===newNode.array.length-1)newNode.array.pop();else newNode.array[idx]=value;return newNode}function editableVNode(node,ownerID){if(ownerID&&ownerID===node?.ownerID)return node;return new VNode(node?.array.slice()??[],ownerID)}function listNodeFor(list,rawIndex){if(rawIndex>=getTailOffset(list._capacity))return list._tail;if(rawIndex<1<<list._level+SHIFT){let{_root:node,_level:level}=list;while(node&&level>0)node=node.array[rawIndex>>>level&MASK],level-=SHIFT;return node}}function setListBounds(list,begin,end){if(begin!==void 0)begin|=0;if(end!==void 0)end|=0;let owner=list.__ownerID||new OwnerID,oldOrigin=list._origin,oldCapacity=list._capacity,newOrigin=oldOrigin+begin,newCapacity=end===void 0?oldCapacity:end<0?oldCapacity+end:oldOrigin+end;if(newOrigin===oldOrigin&&newCapacity===oldCapacity)return list;if(newOrigin>=newCapacity)return list.clear();let{_level:newLevel,_root:newRoot}=list,offsetShift=0;while(newOrigin+offsetShift<0)newRoot=new VNode(newRoot?.array.length?[void 0,newRoot]:[],owner),newLevel+=SHIFT,offsetShift+=1<<newLevel;if(offsetShift)newOrigin+=offsetShift,oldOrigin+=offsetShift,newCapacity+=offsetShift,oldCapacity+=offsetShift;let oldTailOffset=getTailOffset(oldCapacity),newTailOffset=getTailOffset(newCapacity);while(newTailOffset>=1<<newLevel+SHIFT)newRoot=new VNode(newRoot?.array.length?[newRoot]:[],owner),newLevel+=SHIFT;let oldTail=list._tail,newTail=newTailOffset<oldTailOffset?listNodeFor(list,newCapacity-1):newTailOffset>oldTailOffset?new VNode([],owner):oldTail;if(oldTail&&newTailOffset>oldTailOffset&&newOrigin<oldCapacity&&oldTail.array.length){newRoot=editableVNode(newRoot,owner);let node=newRoot;for(let level=newLevel;level>SHIFT;level-=SHIFT){let idx=oldTailOffset>>>level&MASK;node=node.array[idx]=editableVNode(node.array[idx],owner)}node.array[oldTailOffset>>>SHIFT&MASK]=oldTail}if(newCapacity<oldCapacity)newTail=newTail?.removeAfter(owner,0,newCapacity);if(newOrigin>=newTailOffset)newOrigin-=newTailOffset,newCapacity-=newTailOffset,newLevel=SHIFT,newRoot=null,newTail=newTail?.removeBefore(owner,0,newOrigin);else if(newOrigin>oldOrigin||newTailOffset<oldTailOffset){offsetShift=0;while(newRoot){let beginIndex=newOrigin>>>newLevel&MASK;if(beginIndex!==newTailOffset>>>newLevel&MASK)break;if(beginIndex)offsetShift+=(1<<newLevel)*beginIndex;newLevel-=SHIFT,newRoot=newRoot.array[beginIndex]}if(newRoot&&newOrigin>oldOrigin)newRoot=newRoot.removeBefore(owner,newLevel,newOrigin-offsetShift);if(newRoot&&newTailOffset<oldTailOffset)newRoot=newRoot.removeAfter(owner,newLevel,newTailOffset-offsetShift);if(offsetShift)newOrigin-=offsetShift,newCapacity-=offsetShift}if(list.__ownerID)return list.size=newCapacity-newOrigin,list._origin=newOrigin,list._capacity=newCapacity,list._level=newLevel,list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list;return makeList(newOrigin,newCapacity,newLevel,newRoot,newTail)}var getTailOffset=(size)=>size<SIZE?0:size-1>>>SHIFT<<SHIFT,OrderedMap=(value)=>value===void 0||value===null?emptyOrderedMap():isOrderedMap(value)?value:emptyOrderedMap().withMutations((map)=>{let iter=KeyedCollection(value);assertNotInfinite(iter.size),iter.forEach((v,k)=>map.set(k,v))});OrderedMap.of=(...values)=>OrderedMap(values);class OrderedMapImpl extends MapImpl{static{mixin(this,{[IS_ORDERED_SYMBOL]:!0,[DELETE]:this.prototype.remove,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.OrderedMap",keys:CollectionImpl.prototype.keys,values:CollectionImpl.prototype.values,__iterate:CollectionImpl.prototype.__iterate})}constructor(map,list,ownerID,hash2){super(map?map.size:0,void 0,ownerID,hash2);this._map=map,this._list=list}create(value){return OrderedMap(value)}toString(){return this.__toString("OrderedMap {","}")}get(k,notSetValue){let index=this._map.get(k);return index!==void 0?this._list.get(index)[1]:notSetValue}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=0,this._map.clear(),this._list.clear(),this.__altered=!0,this;return emptyOrderedMap()}set(k,v){return updateOrderedMap(this,k,v)}remove(k){return updateOrderedMap(this,k,NOT_SET)}entries(){return this.__iterator(!1)}__iterator(reverse){let listIter=this._list.__iterator(reverse);return makeEntryIterator((entry)=>{while(!0){let step=listIter.next();if(step.done)return!1;let e=step.value[1];if(e)return entry[0]=e[0],entry[1]=e[1],!0}})}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newMap=this._map.__ensureOwner(ownerID),newList=this._list.__ensureOwner(ownerID);if(!ownerID){if(this.size===0)return emptyOrderedMap();return this.__ownerID=ownerID,this.__altered=!1,this._map=newMap,this._list=newList,this}return makeOrderedMap(newMap,newList,ownerID,this.__hash)}}OrderedMap.isOrderedMap=isOrderedMap;var makeOrderedMap=(map,list,ownerID,hash2)=>new OrderedMapImpl(map,list,ownerID,hash2),emptyOrderedMap=()=>makeOrderedMap(emptyMap(),emptyList());function updateOrderedMap(omap,k,v){let{_map:map,_list:list}=omap,i=map.get(k),has2=i!==void 0,newMap,newList;if(v===NOT_SET){if(!has2)return omap;if(list.size>=SIZE&&list.size>=map.size*2){let entries=[];if(list.forEach((entry,idx)=>{if(entry!==void 0&&i!==idx)entries.push(entry)}),newList=emptyList().withMutations((l)=>{for(let j=0;j<entries.length;j++)l.set(j,entries[j])}),newMap=emptyMap().withMutations((m)=>{for(let j=0;j<entries.length;j++)m.set(entries[j][0],j)}),omap.__ownerID)newMap.__ownerID=newList.__ownerID=omap.__ownerID}else newMap=map.remove(k),newList=i===list.size-1?list.pop():list.set(i,void 0)}else if(has2){if(v===list.get(i)[1])return omap;newMap=map,newList=list.set(i,[k,v])}else{let newIdx=list.size;newMap=map.set(k,newIdx),newList=list.set(newIdx,[k,v])}if(omap.__ownerID)return omap.size=newMap.size,omap._map=newMap,omap._list=newList,omap.__hash=void 0,omap.__altered=!0,omap;return makeOrderedMap(newMap,newList)}var Stack=(value)=>value===void 0||value===null?emptyStack():isStack(value)?value:emptyStack().pushAll(value);Stack.of=(...values)=>Stack(values);class StackImpl extends IndexedCollectionImpl{static{mixin(this,{asImmutable,asMutable,wasAltered,withMutations,[IS_STACK_SYMBOL]:!0,shift:this.prototype.pop,unshift:this.prototype.push,unshiftAll:this.prototype.pushAll,[Symbol.toStringTag]:"Immutable.Stack",[Symbol.iterator]:this.prototype.values})}constructor(size,head,ownerID,hash2){super();this.size=size,this._head=head,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return Stack(value)}toString(){return this.__toString("Stack [","]")}get(index,notSetValue){let head=this._head;index=wrapIndex(this,index);while(head&&index--)head=head.next;return head?head.value:notSetValue}peek(){return this._head?.value}push(...values){if(values.length===0)return this;let newSize=this.size+values.length,head=this._head;for(let ii=values.length-1;ii>=0;ii--)head={value:values[ii],next:head};return returnStack(this,newSize,head)}pushAll(iter){if(iter=IndexedCollection(iter),iter.size===0)return this;if(this.size===0&&isStack(iter))return iter;assertNotInfinite(iter.size);let newSize=this.size,head=this._head;return iter.__iterate((value)=>{newSize++,head={value,next:head}},!0),returnStack(this,newSize,head)}pop(){return this.slice(1)}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this;return emptyStack()}slice(begin,end){if(wholeSlice(begin,end,this.size))return this;let resolvedBegin=resolveBegin(begin,this.size);if(resolveEnd(end,this.size)!==this.size)return IndexedCollectionImpl.prototype.slice.call(this,begin,end);let newSize=this.size-resolvedBegin,head=this._head;while(resolvedBegin--)head=head.next;return returnStack(this,newSize,head)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;if(!ownerID){if(this.size===0)return emptyStack();return this.__ownerID=ownerID,this.__altered=!1,this}return makeStack(this.size,this._head,ownerID,this.__hash)}__iterate(fn,reverse){if(reverse){let arr=this.toArray(),size=arr.length,i=0;while(i!==size)if(fn(arr[size-++i],size-i,this)===!1)break;return i}let iterations=0,node=this._head;while(node){if(fn(node.value,iterations++,this)===!1)break;node=node.next}return iterations}__iterator(reverse){if(reverse){let arr=this.toArray(),size=arr.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let ii=size-++i;return entry[0]=ii,entry[1]=arr[ii],!0})}let iterations=0,node=this._head;return makeEntryIterator((entry)=>{if(!node)return!1;return entry[0]=iterations++,entry[1]=node.value,node=node.next,!0})}values(){let node=this._head,result={done:!1,value:void 0};return makeIterator(()=>{if(!node)return DONE;return result.value=node.value,node=node.next,result})}keys(){return makeIndexKeys(this.size)}}Stack.isStack=isStack;function returnStack(stack,newSize,head){if(stack.__ownerID)return stack.size=newSize,stack._head=head,stack.__hash=void 0,stack.__altered=!0,stack;return makeStack(newSize,head)}var makeStack=(size,head,ownerID,hash2)=>new StackImpl(size,head,ownerID,hash2),EMPTY_STACK,emptyStack=()=>EMPTY_STACK||(EMPTY_STACK=makeStack(0)),Set2=(value)=>value===void 0||value===null?emptySet():isSet(value)&&!isOrdered(value)?value:emptySet().withMutations((set3)=>{let iter=SetCollection(value);assertNotInfinite(iter.size),iter.forEach((v)=>set3.add(v))});Set2.of=(...values)=>Set2(values);Set2.fromKeys=(value)=>Set2(KeyedCollection(value).keySeq());Set2.intersect=(sets)=>{return sets=Collection(sets).toArray(),sets.length?Set2(sets.pop()).intersect(...sets):emptySet()};Set2.union=(sets)=>{let setArray=Collection(sets).toArray();return setArray.length?Set2(setArray.pop()).union(...setArray):emptySet()};class SetImpl extends SetCollectionImpl{static{mixin(this,{withMutations,asImmutable,asMutable,[IS_SET_SYMBOL]:!0,[DELETE]:this.prototype.remove,merge:this.prototype.union,concat:this.prototype.union,[Symbol.toStringTag]:"Immutable.Set"})}constructor(map,ownerID){super();this.size=map?map.size:0,this._map=map,this.__ownerID=ownerID}create(value){return Set2(value)}toString(){return this.__toString("Set {","}")}has(value){return this._map.has(value)}add(value){return updateSet(this,this._map.set(value,value))}remove(value){return updateSet(this,this._map.remove(value))}clear(){return updateSet(this,this._map.clear())}map(mapper,context){let didChanges=!1,newMap=updateSet(this,this._map.mapEntries(([,v])=>{let mapped=mapper.call(context,v,v,this);if(mapped!==v)didChanges=!0;return[mapped,mapped]},context));return didChanges?newMap:this}union(...iters){if(iters=iters.filter((x)=>x.size!==0),iters.length===0)return this;if(this.size===0&&!this.__ownerID&&iters.length===1)return Set2(iters[0]);return this.withMutations((set3)=>{for(let iter of iters)if(typeof iter==="string")set3.add(iter);else SetCollection(iter).forEach((value)=>set3.add(value))})}intersect(...iters){return filterByIters(this,iters,(value,sets)=>!sets.every((iter)=>iter.includes(value)))}subtract(...iters){return filterByIters(this,iters,(value,sets)=>sets.some((iter)=>iter.includes(value)))}wasAltered(){return this._map.wasAltered()}__iterator(reverse){return this._map.__iterator(reverse)}__empty(){return emptySet()}__make(map,ownerID){return makeSet(map,ownerID)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newMap=this._map.__ensureOwner(ownerID);if(!ownerID){if(this.size===0)return this.__empty();return this.__ownerID=ownerID,this._map=newMap,this}return this.__make(newMap,ownerID)}}Set2.isSet=isSet;var makeSet=(map,ownerID)=>new SetImpl(map,ownerID),EMPTY_SET,emptySet=()=>EMPTY_SET||(EMPTY_SET=makeSet(emptyMap()));function filterByIters(set3,iters,shouldRemove){if(iters.length===0)return set3;return iters=iters.map((iter)=>SetCollection(iter)),set3.withMutations((s)=>{set3.forEach((value)=>{if(shouldRemove(value,iters))s.remove(value)})})}function updateSet(set3,newMap){if(set3.__ownerID)return set3.size=newMap.size,set3._map=newMap,set3;return newMap===set3._map?set3:newMap.size===0?set3.__empty():set3.__make(newMap)}var OrderedSet=(value)=>value===void 0||value===null?emptyOrderedSet():isOrderedSet(value)?value:emptyOrderedSet().withMutations((set3)=>{let iter=SetCollection(value);assertNotInfinite(iter.size),iter.forEach((v)=>set3.add(v))});OrderedSet.of=(...values)=>OrderedSet(values);OrderedSet.fromKeys=(value)=>OrderedSet(KeyedCollection(value).keySeq());class OrderedSetImpl extends SetImpl{static{mixin(this,{[IS_ORDERED_SYMBOL]:!0,[Symbol.toStringTag]:"Immutable.OrderedSet",zip:IndexedCollectionPrototype.zip,zipWith:IndexedCollectionPrototype.zipWith,zipAll:IndexedCollectionPrototype.zipAll})}create(value){return OrderedSet(value)}toString(){return this.__toString("OrderedSet {","}")}__empty(){return emptyOrderedSet()}__make(map,ownerID){return makeOrderedSet(map,ownerID)}}OrderedSet.isOrderedSet=isOrderedSet;var makeOrderedSet=(map,ownerID)=>new OrderedSetImpl(map,ownerID),emptyOrderedSet=()=>makeOrderedSet(emptyOrderedMap()),PairSorting={LeftThenRight:-1,RightThenLeft:1};function throwOnInvalidDefaultValues(defaultValues){if(isRecord(defaultValues))throw Error("Can not call `Record` with an immutable Record as default values. Use a plain javascript object instead.");if(isImmutable(defaultValues))throw Error("Can not call `Record` with an immutable Collection as default values. Use a plain javascript object instead.");if(defaultValues===null||typeof defaultValues!=="object")throw Error("Can not call `Record` with a non-object as default values. Use a plain javascript object instead.")}var Record=(defaultValues,name)=>{let hasInitialized;throwOnInvalidDefaultValues(defaultValues);let RecordType=function(values){if(values instanceof RecordType)return values;if(!(this instanceof RecordType))return new RecordType(values);if(!hasInitialized){hasInitialized=!0;let keys=Object.keys(defaultValues),indices=RecordTypePrototype._indices={};RecordTypePrototype._name=name,RecordTypePrototype._keys=keys,RecordTypePrototype._defaultValues=defaultValues;for(let i=0;i<keys.length;i++){let propName=keys[i];if(indices[propName]=i,RecordTypePrototype[propName])console.warn(`Cannot define ${recordName(this)} with property "${propName}" since that property name is part of the Record API.`);else setProp(RecordTypePrototype,propName)}}return this.__ownerID=void 0,this._values=List().withMutations((l)=>{l.setSize(this._keys.length),KeyedCollection(values).forEach((v,k)=>{l.set(this._indices[k],v===this._defaultValues[k]?void 0:v)})}),this},RecordTypePrototype=RecordType.prototype=Object.create(RecordPrototype);if(RecordTypePrototype.constructor=RecordType,RecordTypePrototype.create=RecordType,name)RecordType.displayName=name;return RecordType};class RecordImpl{static{mixin(this,{asImmutable,asMutable,deleteIn,getIn,hasIn,merge,mergeWith,mergeDeep,mergeDeepWith,mergeDeepIn,mergeIn,setIn,toObject,update,updateIn,withMutations,removeIn:deleteIn,toJSON:toObject,[IS_RECORD_SYMBOL]:!0,[DELETE]:this.prototype.remove,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.Record"})}toString(){let body=this._keys.map((k)=>`${k}: ${quoteString(this.get(k))}`).join(", ");return`${recordName(this)} { ${body} }`}equals(other){return this===other||isRecord(other)&&recordSeq(this).equals(recordSeq(other))}hashCode(){return recordSeq(this).hashCode()}has(k){return Object.hasOwn(this._indices,k)}get(k,notSetValue){if(!this.has(k))return notSetValue;let index=this._indices[k],value=this._values.get(index);return value===void 0?this._defaultValues[k]:value}set(k,v){if(this.has(k)){let newValues=this._values.set(this._indices[k],v===this._defaultValues[k]?void 0:v);if(newValues!==this._values&&!this.__ownerID)return makeRecord(this,newValues)}return this}remove(k){return this.set(k)}clear(){let newValues=this._values.clear().setSize(this._keys.length);return this.__ownerID?this:makeRecord(this,newValues)}wasAltered(){return this._values.wasAltered()}toSeq(){return recordSeq(this)}toJS(){return toJS(this)}entries(){return this.__iterator()}__iterate(fn,reverse){return recordSeq(this).__iterate(fn,reverse)}__iterator(reverse){return recordSeq(this).__iterator(reverse)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newValues=this._values.__ensureOwner(ownerID);if(!ownerID)return this.__ownerID=ownerID,this._values=newValues,this;return makeRecord(this,newValues,ownerID)}}Record.isRecord=isRecord;var recordName=(record)=>record.constructor.displayName||record.constructor.name||"Record";class RecordSeq extends KeyedSeqImpl{constructor(record){super();this._record=record,this.size=record._keys.length}get(key,notSetValue){return this._record.get(key,notSetValue)}has(key){return this._record.has(key)}__iterateUncached(fn,reverse){let record=this._record,keys=record._keys,size=keys.length,i=0;while(i!==size){let ii=reverse?size-++i:i++,k=keys[ii];if(fn(record.get(k),k,this)===!1)break}return i}__iteratorUncached(reverse){let record=this._record,keys=record._keys,size=keys.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let ii=reverse?size-++i:i++,k=keys[ii];return entry[0]=k,entry[1]=record.get(k),!0})}}var recordSeq=(record)=>new RecordSeq(record);Record.getDescriptiveName=recordName;var RecordPrototype=RecordImpl.prototype;function makeRecord(likeRecord,values,ownerID){let record=Object.create(Object.getPrototypeOf(likeRecord));return record._values=values,record.__ownerID=ownerID,record}function setProp(prototype,name){Object.defineProperty(prototype,name,{get(){return this.get(name)},set(value){invariant(this.__ownerID,"Cannot set on an immutable record."),this.set(name,value)}})}var Range=(start,end,step=1)=>{if(invariant(step!==0,"Cannot step a Range by 0"),invariant(start!==void 0,"You must define a start value when using Range"),invariant(end!==void 0,"You must define an end value when using Range"),step=Math.abs(step),end<start)step=-step;let size=Math.max(0,Math.ceil((end-start)/step-1)+1);return new RangeImpl(start,end,step,size)};class RangeImpl extends IndexedSeqImpl{_start;_end;_step;constructor(start,end,step,size){super();this._start=start,this._end=end,this._step=step,this.size=size}toString(){return this.size===0?"Range []":`Range [ ${this._start}...${this._end}${this._step!==1?` by ${this._step}`:""} ]`}get(index,notSetValue){return this.has(index)?this._start+wrapIndex(this,index)*this._step:notSetValue}includes(searchValue){let possibleIndex=(searchValue-this._start)/this._step;return possibleIndex>=0&&possibleIndex<this.size&&possibleIndex===Math.floor(possibleIndex)}slice(begin,end){if(wholeSlice(begin,end,this.size))return this;if(begin=resolveBegin(begin,this.size),end=resolveEnd(end,this.size),end<=begin)return Range(0,0);return Range(this.get(begin,this._end),this.get(end,this._end),this._step)}indexOf(searchValue){let offsetValue=searchValue-this._start;if(offsetValue%this._step===0){let index=offsetValue/this._step;if(index>=0&&index<this.size)return index}return-1}lastIndexOf(searchValue){return this.indexOf(searchValue)}__iterateUncached(fn,reverse=!1){let size=this.size,step=this._step,value=reverse?this._start+(size-1)*step:this._start,i=0;while(i!==size){let v=value;value+=reverse?-step:step;let ii=reverse?size-++i:i++;if(fn(v,ii,this)===!1)break}return i}__iteratorUncached(reverse=!1){let size=this.size,step=this._step,value=reverse?this._start+(size-1)*step:this._start,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let v=value;return value+=reverse?-step:step,entry[0]=reverse?size-++i:i++,entry[1]=v,!0})}values(){let size=this.size,step=this._step,value=this._start,i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return result.value=value,value+=step,i++,result})}keys(){return makeIndexKeys(this.size)}equals(other){return other instanceof RangeImpl?this._start===other._start&&this._end===other._end&&this._step===other._step:deepEqual2(this,other)}static{this.prototype[Symbol.iterator]=this.prototype.values}}var Repeat=(value,times)=>{let size=times===void 0?1/0:Math.max(0,times);return new RepeatImpl(value,size)};class RepeatImpl extends IndexedSeqImpl{constructor(value,size){super();this._value=value,this.size=size}toString(){if(this.size===0)return"Repeat []";return`Repeat [ ${this._value} ${this.size} times ]`}get(index,notSetValue){return this.has(index)?this._value:notSetValue}includes(searchValue){return is(this._value,searchValue)}slice(begin,end){let size=this.size;return wholeSlice(begin,end,size)?this:new RepeatImpl(this._value,resolveEnd(end,size)-resolveBegin(begin,size))}reverse(){return this}indexOf(searchValue){if(is(this._value,searchValue))return 0;return-1}lastIndexOf(searchValue){if(is(this._value,searchValue))return this.size;return-1}__iterateUncached(fn,reverse){let size=this.size,i=0;while(i!==size)if(fn(this._value,reverse?size-++i:i++,this)===!1)break;return i}__iteratorUncached(reverse){let size=this.size,val=this._value,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;return entry[0]=reverse?size-++i:i++,entry[1]=val,!0})}values(){let size=this.size,val=this._value,i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return i++,result.value=val,result})}keys(){return makeIndexKeys(this.size)}equals(other){return other instanceof RepeatImpl?this.size===other.size&&is(this._value,other._value):deepEqual2(this,other)}static{this.prototype[Symbol.iterator]=this.prototype.values}}var fromJS=(value,converter)=>fromJSWith([],converter??defaultConverter,value,"",converter?.length>2?[]:void 0,{"":value});function fromJSWith(stack,converter,value,key,keyPath,parentValue){if(typeof value!=="string"&&!isImmutable(value)&&(isArrayLike(value)||hasIterator(value)||isPlainObject(value))){if(stack.includes(value))throw TypeError("Cannot convert circular structure to Immutable");if(stack.push(value),keyPath&&key!=="")keyPath.push(key);let converted=converter.call(parentValue,key,Seq(value).map((v,k)=>fromJSWith(stack,converter,v,k,keyPath,value)),keyPath?.slice());if(stack.pop(),keyPath)keyPath.pop();return converted}return value}var defaultConverter=(k,v)=>isIndexed(v)?v.toList():isKeyed(v)?v.toMap():v.toSet(),asValues=(collection)=>isKeyed(collection)?collection.valueSeq():collection;function initCollectionConversions(){CollectionImpl.prototype.toMap=function(){return Map2(this.toKeyedSeq())},CollectionImpl.prototype.toOrderedMap=function(){return OrderedMap(this.toKeyedSeq())},CollectionImpl.prototype.toOrderedSet=function(){return OrderedSet(asValues(this))},CollectionImpl.prototype.toSet=function(){return Set2(asValues(this))},CollectionImpl.prototype.toStack=function(){return Stack(asValues(this))},CollectionImpl.prototype.toList=function(){return List(asValues(this))},CollectionImpl.prototype.countBy=function(grouper,context){let groups=Map2().asMutable();return this.__iterate((v,k)=>{groups.update(grouper.call(context,v,k,this),0,(a)=>a+1)}),groups.asImmutable()},CollectionImpl.prototype.groupBy=function(grouper,context){let isKeyedIter=isKeyed(this),groups=(isOrdered(this)?OrderedMap():Map2()).asMutable();return this.__iterate((v,k)=>{groups.update(grouper.call(context,v,k,this),(a)=>{return a??=[],a.push(isKeyedIter?[k,v]:v),a})}),groups.map((arr)=>reifyValues(this,arr)).asImmutable()},IndexedCollectionImpl.prototype.keySeq=function(){return Range(0,this.size)},MapImpl.prototype.sort=function(comparator){return OrderedMap(sortFactory(this,comparator))},MapImpl.prototype.sortBy=function(mapper,comparator){return OrderedMap(sortFactory(this,comparator,mapper))},SetImpl.prototype.sort=function(comparator){return OrderedSet(sortFactory(this,comparator))},SetImpl.prototype.sortBy=function(mapper,comparator){return OrderedSet(sortFactory(this,comparator,mapper))}}var version$1="7.0.0",pkg={version:version$1};initCollectionConversions();var{version}=pkg;var NONE=Symbol("NONE");class Step{lookup(_v,dval=null){return dval}setValue(root,_v){return root}enterFrame(stack,_prev,next){return stack.enter(next,{},!0)}toAbstractPathStep(){return this}}class BindStep extends Step{constructor(binds){super();this.binds=binds}lookup(v,_dval){return v}setValue(_root,v){return v}enterFrame(stack,_prev,next){return stack.enter(next,{...this.binds},!1)}withIndex(i){return new BindStep({...this.binds,key:i})}withKey(key){return new BindStep({...this.binds,key})}toAbstractPathStep(){return null}}class FieldStep extends Step{constructor(field){super();this.field=field}lookup(v,dval=null){return v?.get?v.get(this.field,dval):dval}setValue(root,v){return root.set(this.field,v)}withIndex(i){return new SeqStep(this.field,i)}withKey(k){return new SeqStep(this.field,k)}}class SeqStep extends Step{constructor(field,key){super();this.field=field,this.key=key}lookup(v,dval=null){let o=v?.get(this.field,null);return o?.get?o.get(this.key,dval):dval}setValue(root,v){let seq=root?.get(this.field,null);return seq?root.set(this.field,seq.set(this.key,v)):root}enterFrame(stack,_prev,next){return stack.enter(next,{key:this.key},!0)}}class SeqAccessStep extends Step{constructor(seqField,keyField){super();this.seqField=seqField,this.keyField=keyField}lookup(v,dval=null){let seq=v?.get(this.seqField,NONE),key=v?.get(this.keyField,NONE);return key!==NONE&&seq?.get?seq.get(key,dval):dval}setValue(root,v){let seq=root?.get(this.seqField,NONE),key=root?.get(this.keyField,NONE);return seq===NONE||key===NONE?root:root.set(this.seqField,seq.set(key,v))}}class EachBindStep extends Step{constructor(seqVal,key){super();this.seqVal=seqVal,this.key=key}lookup(v,_dval){return v}setValue(_root,v){return v}enterFrame(stack,_prev,next){let item=this.seqVal.eval(stack)?.get(this.key,null);return stack.enter(next,{key:this.key,value:item},!1)}toAbstractPathStep(){return null}}class EachRenderItStep extends SeqStep{enterFrame(stack,_prev,next){return stack.enter(next,{key:this.key,value:next},!1).enter(next,{},!0)}toAbstractPathStep(){return new SeqStep(this.field,this.key)}}function warnRawDynStep(op,step){console.warn(`Path.${op} reached a DynStep: call toTransactionPath() first`,step)}class DynStep extends Step{constructor(producerCompId,producerSteps){super();this.producerCompId=producerCompId,this.producerSteps=producerSteps,this.interiorCids=new Set}teleportSteps(){return this.producerSteps}lookup(_v,dval=null){return warnRawDynStep("lookup",this),dval}setValue(root,_v){return warnRawDynStep("setValue",this),root}enterFrame(stack,_prev,_next){return warnRawDynStep("enterFrame",this),stack}}class DynEachStep extends DynStep{constructor(producerCompId,producerSteps,key){super(producerCompId,producerSteps);this.key=key}teleportSteps(){let{producerSteps,key}=this;if(producerSteps.length===0)return producerSteps;let last=producerSteps[producerSteps.length-1];if(!(last instanceof FieldStep))return console.warn("DynEachStep: seq-access dynamic cannot be iterated",this),producerSteps;return producerSteps.slice(0,-1).concat(new SeqStep(last.field,key))}}class Path{constructor(steps=[]){this.steps=steps}concat(steps){return new Path(this.steps.concat(steps))}popStep(){return new Path(this.steps.slice(0,-1))}compact(){let out=[];for(let step of this.steps){let s=step.toAbstractPathStep();if(s!==null){if(s!==step)s._originCid=step._originCid;out.push(s)}}return new Path(out)}toTransactionPath(){let hasDyn=!1;for(let step of this.steps)if(step instanceof DynStep){hasDyn=!0;break}if(!hasDyn)return this;let out=[];for(let step of this.steps)if(step instanceof DynStep){while(out.length>0&&step.interiorCids.has(out[out.length-1]._originCid))out.pop();for(let ts of step.teleportSteps())ts._originCid=step.producerCompId,out.push(ts)}else out.push(step);return new Path(out)}lookup(v,dval=null){let curVal=v;for(let step of this.steps)if(curVal=step.lookup(curVal,NONE),curVal===NONE)return dval;return curVal}setValue(root,v){let intermediates=Array(this.steps.length),curVal=root;for(let i=0;i<this.steps.length;i++)if(intermediates[i]=curVal,curVal=this.steps[i].lookup(curVal,NONE),curVal===NONE)return root;let newVal=v;for(let i=this.steps.length-1;i>=0;i--)newVal=this.steps[i].setValue(intermediates[i],newVal),intermediates[i]=newVal;return newVal}buildStack(stack){let prev=stack.it;for(let step of this.steps){let next=step.lookup(prev,NONE);if(next===NONE)return console.warn("bad PathItem",{root:stack.it,step,path:this}),null;stack=step.enterFrame(stack,prev,next),prev=next}return stack}static fromNodeAndEventName(node,eventName,rootNode,maxDepth,comps,stopOnNoEvent=!0){let pathSteps=[],pendingDyns=[],bubbles=BUBBLING_EVENTS.has(eventName),depth=0,eventIds=[],handlers=null,nodeIds=[],isLeafComponent=!0;while(node&&node!==rootNode&&depth<maxDepth){if(node?.dataset){let{nid,si,sk}=parseMetaComment(node.previousSibling),{eid,cid,vid}=node.dataset;if(eid!==void 0)eventIds.push(eid);if(cid!==void 0){let cidNum=+cid,comp=comps.getComponentForId(cidNum),pushStep=!0;if(handlers===null&&(isLeafComponent||bubbles)){if(handlers=findHandlers(comp,eventIds,vid,eventName),handlers===null){if(isLeafComponent&&stopOnNoEvent&&!bubbles)return NO_EVENT_INFO}else if(!isLeafComponent)pathSteps.length=0,pendingDyns.length=0,pushStep=!1}isLeafComponent=!1;for(let dyn of pendingDyns)dyn.interiorCids.add(cidNum);if(pushStep){let step=resolvePathStep(comp,nodeIds,vid);if(step){if(step._originCid=cidNum,pathSteps.push(step),step instanceof DynStep)step.interiorCids.add(cidNum),pendingDyns.push(step)}}for(let i=pendingDyns.length-1;i>=0;i--)if(pendingDyns[i].producerCompId===cidNum)pendingDyns.splice(i,1);eventIds=[],nodeIds=[]}if(nid!==void 0)nodeIds.push({nid,si,sk})}depth+=1,node=node.parentNode}if(pendingDyns.length>0)console.warn("event reconstruction: dynamic-var producer not found",pendingDyns);return[new Path(pathSteps.reverse()),handlers]}static fromEvent(e,rNode,maxDepth,comps,stopOnNoEvent=!0){let{type:type3,target}=e;return Path.fromNodeAndEventName(target,type3,rNode,maxDepth,comps,stopOnNoEvent)}}var EMPTY_META={};function parseMetaComment(n){if(n?.nodeType===8&&n.textContent[0]==="§"){let m=parseMetaComment(n.previousSibling);if(m!==EMPTY_META)return m;try{return JSON.parse(n.textContent.slice(1,-1))}catch(err){console.warn(err,n)}}return EMPTY_META}function findHandlers(comp,eventIds,vid,eventName){for(let eid of eventIds){let handlers=comp.getEventForId(+eid,vid).getHandlersFor(eventName);if(handlers!==null)return handlers}return null}class StepCtx{constructor(comp,nodeIds,idx,vid){this.comp=comp,this.nodeIds=nodeIds,this.idx=idx,this.vid=vid}get meta(){return this.nodeIds[this.idx]}get key(){let m=this.meta;return m.si!==void 0?+m.si:m.sk}get hasKey(){let m=this.meta;return m.si!==void 0||m.sk!==void 0}next(){let{idx,nodeIds}=this;return idx+1<nodeIds.length?new StepCtx(this.comp,nodeIds,idx+1,this.vid):null}resolveNode(){return this.comp.getNodeForId(+this.meta.nid,this.vid)}applyKey(pi){if(pi===null)return null;let m=this.meta;if(m.si!==void 0)return pi.withIndex(+m.si);if(m.sk!==void 0)return pi.withKey(m.sk);return pi}}function resolvePathStep(comp,nodeIds,vid){for(let i=0;i<nodeIds.length;i++){let ctx=new StepCtx(comp,nodeIds,i,vid),step=ctx.resolveNode().toPathStep(ctx);if(step!==null)return step}return null}var NO_EVENT_INFO=[null,null],BUBBLING_EVENTS=new Set(["drop"]);class PathBuilder{constructor(){this.pathChanges=[]}add(pathChange){return this.pathChanges.push(pathChange),this}field(name){return this.add(new FieldStep(name))}index(name,index){return this.add(new SeqStep(name,index))}key(name,key){return this.add(new SeqStep(name,key))}}var VALID_VAL_ID_RE=/^[a-zA-Z][a-zA-Z0-9_]*\??$/,isValidValId=(name)=>VALID_VAL_ID_RE.test(name),VALID_FLOAT_RE=/^-?[0-9]+(\.[0-9]+)?$/,STR_TPL_SPLIT_RE=/(\{[^}]+\})/g,mkVal=(name,Cls)=>isValidValId(name)?new Cls(name):null,VAL_TOKEN_RE=/\$'(?:[^'\\]|\\.)*'|'(?:[^'\\]|\\.)*'|\S+/g,tokenizeValue=(s)=>s.match(VAL_TOKEN_RE)??[],unescapeStr=(s)=>s.replace(/\\(['\\])/g,"$1"),K_CONST=1,K_STRTPL=2,K_FIELD=4,K_BIND=8,K_DYN=16,K_NAME=32,K_TYPE=64,K_REQUEST=128,K_SEQ=256,K_STR=512,K_METHOD=1024,G_BOOL=K_FIELD|K_METHOD|K_BIND|K_DYN|K_CONST,G_TEXT=G_BOOL|K_STRTPL,G_COMPONENT=K_FIELD|K_SEQ|K_DYN,G_SEQUENCE=K_FIELD|K_DYN,G_FIELD=K_FIELD|K_METHOD|K_CONST|K_STR|K_SEQ,G_VALUE=K_FIELD|K_METHOD|K_BIND|K_DYN|K_NAME|K_TYPE|K_REQUEST|K_CONST,G_PRED_ARG=G_BOOL|K_STR,G_HANDLER_ARG=G_VALUE|K_STR,G_ALL=G_VALUE|K_STRTPL|K_SEQ;function sizeOf(v){if(v==null)return null;let s=v.size;if(typeof s==="number")return s;let l=v.length;return typeof l==="number"?l:null}var predTruthy=(v)=>{let n=sizeOf(v);return n===null?!!v:n>0},PREDICATES={"empty?":{name:"empty?",arity:1,fn:(v)=>v==null||sizeOf(v)===0},"truthy?":{name:"truthy?",arity:1,fn:predTruthy},"falsy?":{name:"falsy?",arity:1,fn:(v)=>!predTruthy(v)},"null?":{name:"null?",arity:1,fn:(v)=>v==null},"equals?":{name:"equals?",arity:2,fn:(a,b)=>is(a,b)}};class ValParser{constructor(){this.bindValIt=new BindVal("it"),this.nullConstVal=new ConstVal(null)}const(v){return new ConstVal(v)}parseToken(s,px){let c0=s.charCodeAt(0);if(c0===39)return s.length>=2&&s.charCodeAt(s.length-1)===39?new ConstVal(unescapeStr(s.slice(1,-1)),K_STR|K_STRTPL):null;if(c0===36&&s.charCodeAt(1)===39)return s.length>=3&&s.charCodeAt(s.length-1)===39?StrTplVal.parse(s.slice(2,-1),px):null;if(s.indexOf("[")!==-1||s.indexOf("]")!==-1)return this._parseSeqAccess(s,px);if(s.indexOf("{")!==-1||s.indexOf("}")!==-1)return null;switch(c0){case 94:{let name=s.slice(1),newS=px.frame.macroVars?.[name];if(newS!==void 0){let tokens=tokenizeValue(newS.trim());if(tokens.length!==1)return null;let val=this.parseToken(tokens[0],px);if(val instanceof ConstVal)val.fromMacroVar=!0;return val}return px.onParseIssue("bad-value",{role:"macro-var",name,value:s}),null}case 36:return mkVal(s.slice(1),MethodVal);case 64:return mkVal(s.slice(1),BindVal);case 42:return mkVal(s.slice(1),DynVal);case 46:return mkVal(s.slice(1),FieldVal);case 33:return mkVal(s.slice(1),RequestVal)}let num=VALID_FLOAT_RE.test(s)?parseFloat(s):null;if(Number.isFinite(num))return new ConstVal(num);if(s==="true"||s==="false")return new ConstVal(s==="true");if(c0>=97&&c0<=122)return mkVal(s,NameVal);if(c0>=65&&c0<=90)return mkVal(s,TypeVal);return null}_parseSeqAccess(s,px){let open=s.indexOf("["),close=s.indexOf("]");if(open<1||close!==s.length-1||close<open||s.indexOf("[",open+1)!==-1)return null;let left=this.parseToken(s.slice(0,open),px),right=this.parseToken(s.slice(open+1,close),px);return left instanceof FieldVal&&right instanceof FieldVal?new SeqAccessVal(left,right):null}_parseSingle(s,px,group){let tokens=tokenizeValue(s.trim());if(tokens.length!==1)return null;let val=this.parseToken(tokens[0],px);return val!==null&&kindOf(val)&group?val:null}parseBool(s,px){let t=s.trim(),tokens=tokenizeValue(t);if(tokens.length!==1)return tokens.length===0?null:this._parsePredicate(t,tokens,px);let val=this.parseToken(tokens[0],px);return val!==null&&kindOf(val)&G_BOOL?val:null}parseText(s,px){return this._parseSingle(s,px,G_TEXT)}parseComponent(s,px){return this._parseSingle(s,px,G_COMPONENT)}parseSequence(s,px){return this._parseSingle(s,px,G_SEQUENCE)}parseField(s,px){return this._parseSingle(s,px,G_FIELD)}parseHandlerArg(s,px){return this._parseSingle(s,px,G_HANDLER_ARG)}parseMacroAttr(s,px){return this._parseSingle(s,px,G_ALL)}parseInputHandler(s,px){return this._parseHandler(s,px,"input",!0,!0)}parseAlterHandler(s,px){let r=this._parseHandler(s,px,"alter",!1,!1);return r===null?null:r.handlerVal}_parseHandler(s,px,namespace,allowArgs,report){let tokens=tokenizeValue(s.trim()),headTok=tokens[0]??"",head=headTok===""?null:this.parseToken(headTok,px),hk=kindOf(head),handlerVal;if(hk&K_METHOD)handlerVal=head;else if(hk&K_NAME)handlerVal=new HandlerNameVal(head.name,namespace);else{if(report)px.onParseIssue("bad-value",{role:"handler-name",value:headTok});return null}if(!allowArgs)return tokens.length===1?{handlerVal,args:[]}:null;let args=Array(tokens.length-1);for(let i=1;i<tokens.length;i++){let val=this.parseToken(tokens[i],px);if(val!==null&&kindOf(val)&G_HANDLER_ARG)args[i-1]=val;else{if(report)px.onParseIssue("bad-value",{role:"handler-arg",value:tokens[i]});args[i-1]=this.nullConstVal}}return{handlerVal,args}}_parsePredicate(s,tokens,px){let predName=tokens[0],pred=PREDICATES[predName];if(pred===void 0)return px.onParseIssue("bad-value",{role:"predicate",value:predName}),null;let arity=tokens.length-1;if(arity!==pred.arity)return px.onParseIssue("bad-value",{role:"predicate-arity",value:s,predicate:predName}),null;let args=Array(arity);for(let i=0;i<arity;i++){let tok=tokens[i+1],val=this.parseToken(tok,px);if(val===null||!(kindOf(val)&G_PRED_ARG))return px.onParseIssue("bad-value",{role:"predicate-arg",value:tok}),null;args[i]=val}return new PredicateVal(pred,args)}}function kindOf(val){if(val===null)return 0;if(val instanceof ConstVal)return val.kind;if(val instanceof StrTplVal)return K_STRTPL;if(val instanceof SeqAccessVal)return K_SEQ;if(val instanceof FieldVal)return K_FIELD;if(val instanceof MethodVal)return K_METHOD;if(val instanceof BindVal)return K_BIND;if(val instanceof DynVal)return K_DYN;if(val instanceof RequestVal)return K_REQUEST;if(val instanceof TypeVal)return K_TYPE;if(val instanceof NameVal)return K_NAME;return 0}class BaseVal{render(_stack,_rx){}eval(_stack){}toPathItem(){return null}evalAsHandler(stack){return this.eval(stack)}}class ConstVal extends BaseVal{constructor(val,kind=K_CONST){super();this.val=val,this.kind=kind}render(_stack,_rx){return this.val}eval(_stack){return this.val}toString(){let v=this.val;return typeof v==="string"?`'${v.replace(/(['\\])/g,"\\$1")}'`:`${v}`}}class PredicateVal extends BaseVal{constructor(pred,args){super();this.pred=pred,this.args=args}eval(stack){let n=this.args.length,vals=Array(n);for(let i=0;i<n;i++)vals[i]=this.args[i].eval(stack);return this.pred.fn(...vals)}toString(){return`${this.pred.name} ${this.args.map(String).join(" ")}`}}class VarVal extends BaseVal{}class StrTplVal extends VarVal{constructor(vals){super();this.vals=vals}render(stack,_rx){return this.eval(stack)}eval(stack){let strs=Array(this.vals.length);for(let i=0;i<this.vals.length;i++)strs[i]=this.vals[i]?.eval(stack,"");return strs.join("")}toLiteralSource(){let out="";for(let v of this.vals){if(!(v instanceof ConstVal)||v.fromMacroVar)return null;out+=v.val}return new ConstVal(out).toString()}static parse(s,px){let parts=unescapeStr(s).split(STR_TPL_SPLIT_RE),vals=Array(parts.length);for(let i=0;i<parts.length;i++){let part=parts[i],isExpr=part[0]==="{"&&part.at(-1)==="}";vals[i]=isExpr?vp.parseText(part.slice(1,-1),px):new ConstVal(part)}let lo=0,hi=vals.length,isTrimmable=(v)=>v instanceof ConstVal&&v.val===""&&!v.fromMacroVar;while(lo<hi&&isTrimmable(vals[lo]))lo++;while(hi>lo&&isTrimmable(vals[hi-1]))hi--;return new StrTplVal(lo===0&&hi===vals.length?vals:vals.slice(lo,hi))}}class NameVal extends VarVal{constructor(name){super();this.name=name}eval(stack){return stack.lookupName(this.name)}toString(){return this.name}}class HandlerNameVal extends NameVal{constructor(name,namespace){super(name);this.namespace=namespace}eval(stack){return stack.getHandlerFor(this.name,this.namespace)??mk404Handler(this.namespace,this.name)}}var mk404Handler=(type3,name)=>function(...args){return console.warn("handler not found",{type:type3,name,args},this),this};class TypeVal extends NameVal{eval(stack){return stack.lookupType(this.name)}}class RequestVal extends NameVal{eval(stack){return stack.lookupRequest(this.name)}toString(){return`!${this.name}`}}class RenderVal extends BaseVal{render(stack,_rx){return this.eval(stack)}}class RenderNameVal extends RenderVal{constructor(name){super();this.name=name}}class BindVal extends RenderNameVal{eval(stack){return stack.lookupBind(this.name)}toString(){return`@${this.name}`}}class DynVal extends RenderNameVal{eval(stack){return stack.lookupDynamic(this.name)}toPathItem(){return null}toString(){return`*${this.name}`}}class FieldVal extends RenderNameVal{eval(stack){return stack.lookupFieldRaw(this.name)}toPathItem(){return new FieldStep(this.name)}toString(){return`.${this.name}`}}class MethodVal extends RenderNameVal{eval(stack){return stack.lookupMethod(this.name)}evalAsHandler(stack){return stack.lookupFieldRaw(this.name)}toString(){return`$${this.name}`}}class SeqAccessVal extends RenderVal{constructor(seqVal,keyVal){super();this.seqVal=seqVal,this.keyVal=keyVal}toPathItem(){return new SeqAccessStep(this.seqVal.name,this.keyVal.name)}eval(stack){let key=this.keyVal.eval(stack);return this.seqVal.eval(stack)?.get(key,null)}toString(){return`${this.seqVal}[${this.keyVal}]`}}var vp=new ValParser;class Attributes{constructor(items){this.items=items}eval(_stack){return{}}static parse(attributes,px,parseAll=!1){return getAttrParser(px).parse(attributes,parseAll)}isConstant(){return!1}}var booleanAttrsRaw="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected",booleanAttrs=new Set(booleanAttrsRaw.split(","));class AttrParser{constructor(px){this.clear(px)}clear(px){this.px=px,this.attrs=null,this.hasDynamic=!1,this.wrapperAttrs=null,this.textChild=null,this.eachAttr=null,this.ifAttr=null,this.events=null}parseAttr(name,value,parseAll=!1){let val=parseAll?vp.parseMacroAttr(value,this.px):vp.parseText(value,this.px);if(val!==null)this.attrs??=[],this.attrs.push(new Attr(name,val)),this.hasDynamic||=!(val instanceof ConstVal);else this.px.onParseIssue("bad-value",{role:"attr",attr:name,value})}pushWrapper(name,raw,val){let node={name,val,raw};return this.wrapperAttrs??=[],this.wrapperAttrs.push(node),node}parseIf(directiveName,value){let dynVal=vp.parseBool(value,this.px);if(dynVal)this.ifAttr=new IfAttr(directiveName.slice(3),dynVal),this.attrs??=[],this.attrs.push(this.ifAttr),this.hasDynamic=!0;else{let info={role:"if",attr:directiveName.slice(3),value};this.px.onParseIssue("bad-value",info)}}parseThen(s){if(this.ifAttr)this.ifAttr.thenVal=vp.parseText(s,this.px)??NOT_SET_VAL}parseElse(value){if(this.ifAttr)this.ifAttr.elseVal=vp.parseText(value,this.px)??NOT_SET_VAL}parseEvent(directiveName,value){let[eventName,...modifiers]=directiveName.slice(3).split("+"),handler=EventHandler.parse(value,this.px);if(handler){if(this.events===null)this.events=this.px.registerEvents(),this.attrs??=[],this.attrs.push(new ConstAttr("data-eid",vp.const(this.events.id)));this.events.add(eventName,handler,modifiers)}}_parseDirectiveValue(directiveName,s,parserFn){let val=parserFn.call(vp,s,this.px);if(val===null){let info={role:"directive",directive:directiveName,value:s};this.px.onParseIssue("bad-value",info)}return val}parseDirective(s,directiveName){switch(directiveName){case"dangerouslysetinnerhtml":this.attrs??=[],this.attrs.push(new RawHtmlAttr(this._parseDirectiveValue(directiveName,s,vp.parseText))),this.hasDynamic=!0;return;case"slot":this.pushWrapper("slot",s,vp.const(s));return;case"push-view":this.pushWrapper("push-view",s,this._parseDirectiveValue(directiveName,s,vp.parseText));return;case"text":this.textChild=this._parseDirectiveValue(directiveName,s,vp.parseText);return;case"show":this.pushWrapper("show",s,this._parseDirectiveValue(directiveName,s,vp.parseBool));return;case"hide":this.pushWrapper("hide",s,this._parseDirectiveValue(directiveName,s,vp.parseBool));return;case"each":{let val=this._parseDirectiveValue(directiveName,s,vp.parseSequence);this.eachAttr=this.pushWrapper("each",s,val);return}case"enrich-with":if(this.eachAttr!==null)this.eachAttr.enrichWithVal=this._parseDirectiveValue(directiveName,s,vp.parseAlterHandler);else this.pushWrapper("scope",s,this._parseDirectiveValue(directiveName,s,vp.parseAlterHandler));return;case"when":this._parseWhen(s);return;case"loop-with":this._parseLoopWith(s);return;case"then":this.parseThen(s);return;case"else":this.parseElse(s);return}if(directiveName.startsWith("on."))this.parseEvent(directiveName,s);else if(directiveName.startsWith("if."))this.parseIf(directiveName,s);else if(directiveName.startsWith("then."))this.parseThen(s);else if(directiveName.startsWith("else."))this.parseElse(s);else{let info={name:directiveName,value:s};this.px.onParseIssue("unknown-directive",info)}}_parseWhen(s){if(this.eachAttr!==null)this.eachAttr.whenVal=this._parseDirectiveValue("when",s,vp.parseAlterHandler)}_parseLoopWith(s){if(this.eachAttr!==null)this.eachAttr.loopWithVal=this._parseDirectiveValue("loop-with",s,vp.parseAlterHandler)}parse(attributes,parseAll=!1){for(let{name,value}of attributes){let charCode=name.charCodeAt(0);if(charCode===58)this.parseAttr(name===":viewbox"?"viewBox":name.slice(1),value,parseAll);else if(charCode===64)this.parseDirective(value,name.slice(1));else{this.attrs??=[];let constVal=value===""&&booleanAttrs.has(name)?!0:value;this.attrs.push(new ConstAttr(name,vp.const(constVal)))}}let{attrs,hasDynamic}=this;return[hasDynamic?new DynAttrs(attrs):ConstAttrs.fromAttrs(attrs??[]),this.wrapperAttrs,this.textChild]}}class ConstAttrs extends Attributes{eval(_stack){return this.items}static fromAttrs(attrs){let attrsObj={};for(let attr of attrs)attrsObj[attr.name]=attr.val.eval(null);return new ConstAttrs(attrsObj)}setDataAttr(key,val){this.items[key]=val}toMacroVars(){let r={};for(let name in this.items)r[name]=`'${this.items[name]}'`;return r}isConstant(){return!0}}class DynAttrs extends Attributes{eval(stack){let attrs={};for(let i=0;i<this.items.length;i++){let attr=this.items[i];attrs[attr.name]=attr.eval(stack)}return attrs}setDataAttr(key,val){this.items.push(new ConstAttr(key,new ConstVal(val)))}toMacroVars(){let r={};for(let attr of this.items)r[attr.name]=attr.val.toString();return r}}class BaseAttr{constructor(name){this.name=name}}class Attr extends BaseAttr{constructor(name,val){super(name);this.val=val}eval(stack){return this.val.eval(stack)}}class ConstAttr extends Attr{}class RawHtmlAttr extends Attr{constructor(val){super("dangerouslySetInnerHTML",val??vp.nullConstVal)}eval(stack){return{__html:`${this.val.eval(stack)}`}}}var NOT_SET_VAL=vp.nullConstVal;class IfAttr extends BaseAttr{constructor(name,condVal){super(name);this.condVal=condVal,this.thenVal=this.elseVal=NOT_SET_VAL}get anyBranchIsSet(){return this.thenVal!==NOT_SET_VAL||this.elseVal!==NOT_SET_VAL}eval(stack){return this.condVal.eval(stack)?this.thenVal.eval(stack):this.elseVal.eval(stack)}}var _attrParser=null;function getAttrParser(px){return _attrParser??=new AttrParser(px),_attrParser.clear(px),_attrParser}class EventHandler{constructor(handlerVal,args=[]){this.handlerVal=handlerVal,this.args=args}getHandlerAndArgs(stack,_event){let argValues=Array(this.args.length);for(let i=0;i<argValues.length;i++)argValues[i]=this.args[i].eval(stack);return[this.handlerVal.evalAsHandler(stack),argValues]}static parse(s,px){let r=vp.parseInputHandler(s,px);return r===null?null:new EventHandler(r.handlerVal,r.args)}}class RequestHandler{constructor(name,fn){this.name=name,this.fn=fn}toHandlerArg(disp){let f=(...args)=>disp.request(this.name,args);return f.withOpts=(...args)=>disp.request(this.name,args.slice(0,-1),args.at(-1)),f}}var isHtmlAttribute=(propName)=>propName[4]==="-"&&(propName[0]==="d"||propName[0]==="a"),HTML_NS="http://www.w3.org/1999/xhtml",isNamespaced=(node)=>{let ns=node.namespaceURI;return ns!==null&&ns!=="http://www.w3.org/1999/xhtml"};function applyProperties(node,props,previous){let namespaced=isNamespaced(node);for(let propName in props){let propValue=props[propName];if(propValue===void 0)removeProperty(node,propName,previous);else if(propName==="dangerouslySetInnerHTML")node.innerHTML=propValue.__html??"";else if(propName==="className")node.setAttribute("class",propValue);else if(namespaced||isHtmlAttribute(propName))node.setAttribute(propName,propValue);else node[propName]=propValue}}function removeProperty(node,propName,previous){let previousValue=previous[propName];if(propName==="dangerouslySetInnerHTML")node.replaceChildren();else if(propName==="className")node.removeAttribute("class");else if(propName==="htmlFor")node.removeAttribute("for");else if(isNamespaced(node)||typeof previousValue==="string"||isHtmlAttribute(propName))node.removeAttribute(propName);else node[propName]=null}class VBase{}var getKey=(child)=>child instanceof VNode2?child.key:void 0,isIterable=(obj)=>obj!=null&&typeof obj!=="string"&&typeof obj[Symbol.iterator]==="function";function childsEqual(a,b){if(a===b)return!0;for(let i=0;i<a.length;i++)if(!a[i].isEqualTo(b[i]))return!1;return!0}function appendChildNodes(parent,childs,opts){for(let child of childs)parent.appendChild(child.toDom(opts))}function addChild(normalizedChildren,child){if(child==null)return;if(isIterable(child))for(let c of child)addChild(normalizedChildren,c);else if(child instanceof VBase)if(child instanceof VFragment)normalizedChildren.push(...child.childs);else normalizedChildren.push(child);else normalizedChildren.push(new VText(child))}class VText extends VBase{constructor(text){super();this.text=String(text)}get nodeType(){return 3}isEqualTo(other){return other instanceof VText&&this.text===other.text}toDom(opts){return opts.document.createTextNode(this.text)}}class VComment extends VBase{constructor(text){super();this.text=text}get nodeType(){return 8}isEqualTo(other){return other instanceof VComment&&this.text===other.text}toDom(opts){return opts.document.createComment(this.text)}}class VFragment extends VBase{constructor(childs){super();this.childs=[],addChild(this.childs,childs)}get nodeType(){return 11}isEqualTo(other){if(!(other instanceof VFragment)||this.childs.length!==other.childs.length)return!1;return childsEqual(this.childs,other.childs)}toDom(opts){let fragment=opts.document.createDocumentFragment();return appendChildNodes(fragment,this.childs,opts),fragment}}class VNode2 extends VBase{constructor(tag,attrs,childs,key,namespace){super();this.tag=tag,this.attrs=attrs??{},this.childs=childs??[],this.key=key!=null?String(key):void 0,this.namespace=typeof namespace==="string"?namespace:null}get nodeType(){return 1}isSameKind(other){return this.tag===other.tag&&this.namespace===other.namespace&&this.key===other.key}isEqualTo(other){if(this===other)return!0;if(!(other instanceof VNode2)||!this.isSameKind(other)||this.childs.length!==other.childs.length)return!1;if(this.attrs!==other.attrs){for(let key in this.attrs)if(this.attrs[key]!==other.attrs[key])return!1;for(let key in other.attrs)if(!Object.hasOwn(this.attrs,key))return!1}return childsEqual(this.childs,other.childs)}toDom(opts){let doc=opts.document,node=this.namespace===null?doc.createElement(this.tag):doc.createElementNS(this.namespace,this.tag);if(this.tag==="SELECT"&&"value"in this.attrs){let{value,...rest}=this.attrs;applyProperties(node,rest,{}),appendChildNodes(node,this.childs,opts),applyProperties(node,{value},{})}else applyProperties(node,this.attrs,{}),appendChildNodes(node,this.childs,opts);return node}}function diffProps(a,b){if(a===b)return null;let diff=null;for(let aKey in a)if(!Object.hasOwn(b,aKey))diff??={},diff[aKey]=void 0;else if(a[aKey]!==b[aKey])diff??={},diff[aKey]=b[aKey];for(let bKey in b)if(!Object.hasOwn(a,bKey))diff??={},diff[bKey]=b[bKey];return diff}function morphNode(domNode,source,target,opts){if(source===target||source.isEqualTo(target))return domNode;let type3=source.nodeType;if(type3===target.nodeType){if(type3===3||type3===8)return domNode.data=target.text,domNode;if(type3===1&&source.isSameKind(target)){let propsDiff=diffProps(source.attrs,target.attrs),isSelect=source.tag==="SELECT";if(propsDiff)if(isSelect&&"value"in propsDiff){let{value:_v,...rest}=propsDiff;applyProperties(domNode,rest,source.attrs)}else applyProperties(domNode,propsDiff,source.attrs);if(!target.attrs.dangerouslySetInnerHTML)morphChildren(domNode,source.childs,target.childs,opts);if(isSelect&&target.attrs.value!==void 0)applyProperties(domNode,{value:target.attrs.value},source.attrs);return domNode}if(type3===11)return morphChildren(domNode,source.childs,target.childs,opts),domNode}let newNode=target.toDom(opts);return domNode.parentNode?.replaceChild(newNode,domNode),newNode}function morphChildren(parentDom,oldChilds,newChilds,opts){if(oldChilds.length===0){appendChildNodes(parentDom,newChilds,opts);return}if(newChilds.length===0){parentDom.replaceChildren();return}if(oldChilds.length===newChilds.length){let hasKey=!1;for(let i=0;i<oldChilds.length;i++)if(getKey(oldChilds[i])!=null||getKey(newChilds[i])!=null){hasKey=!0;break}if(!hasKey){let dom=parentDom.firstChild;for(let i=0;i<oldChilds.length;i++){let next=dom.nextSibling;morphNode(dom,oldChilds[i],newChilds[i],opts),dom=next}return}}let domNodes=Array.from(parentDom.childNodes),oldKeyMap=Object.create(null);for(let i=0;i<oldChilds.length;i++){let key=getKey(oldChilds[i]);if(key!=null)oldKeyMap[key]=i}let used2=new Uint8Array(oldChilds.length),unkeyedCursor=0;for(let j=0;j<newChilds.length;j++){let newChild=newChilds[j],newKey=getKey(newChild),oldIdx=-1;if(newKey!=null){if(newKey in oldKeyMap&&!used2[oldKeyMap[newKey]])oldIdx=oldKeyMap[newKey]}else while(unkeyedCursor<oldChilds.length){if(!used2[unkeyedCursor]&&getKey(oldChilds[unkeyedCursor])==null){oldIdx=unkeyedCursor++;break}unkeyedCursor++}if(oldIdx>=0){used2[oldIdx]=1;let newDom=morphNode(domNodes[oldIdx],oldChilds[oldIdx],newChild,opts),ref=parentDom.childNodes[j]??null;if(newDom!==ref)parentDom.insertBefore(newDom,ref)}else{let ref=parentDom.childNodes[j]??null;parentDom.insertBefore(newChild.toDom(opts),ref)}}for(let i=oldChilds.length-1;i>=0;i--)if(!used2[i]&&domNodes[i].parentNode===parentDom)parentDom.removeChild(domNodes[i])}function render(vnode,container,options,prev){let isFragment=vnode instanceof VFragment;if(prev&&prev.vnode instanceof VFragment===isFragment){let oldDom=isFragment?container:prev.dom,newDom=morphNode(oldDom,prev.vnode,vnode,options);return{vnode,dom:isFragment?container:newDom}}let domNode=vnode.toDom(options);return container.replaceChildren(domNode),{vnode,dom:isFragment?container:domNode}}function h(tagName,properties,children,namespace){let props={},key;if(properties)for(let propName in properties){let propVal=properties[propName];switch(propName){case"key":key=propVal;break;case"namespace":namespace=namespace??propVal;break;case"class":props.className=propVal;break;case"for":props.htmlFor=propVal;break;default:props[propName]=isHtmlAttribute(propName)?String(propVal):propVal}}let c=tagName.charCodeAt(0),tag=namespace==null&&c>=97&&c<=122?tagName.toUpperCase():tagName,normalizedChildren=[];return addChild(normalizedChildren,children),new VNode2(tag,props,normalizedChildren,key,namespace)}function resolveDynProducer(comp,dynName){let dyn=comp?.dynamic?.[dynName];if(dyn==null)return null;let producerComp,producerDyn;if(dyn.compName!=null)producerComp=comp.scope?.lookupComponent(dyn.compName),producerDyn=producerComp?.dynamic?.[dyn.dynName];else producerComp=comp,producerDyn=dyn;if(producerComp==null||producerDyn==null)return null;let pi=producerDyn.val?.toPathItem?.()??null;return{producerCompId:producerComp.id,producerSteps:pi?[pi]:[]}}class BaseNode{render(_stack,_rx){return null}setDataAttr(key,val){console.warn("setDataAttr not implemented for",this,{key,val})}isConstant(){return!1}optimize(){}}class TextNode extends BaseNode{constructor(val){super();this.val=val}render(_stack,_rx){return this.val}isWhiteSpace(){for(let i=0;i<this.val.length;i++){let c=this.val.charCodeAt(i);if(!(c===32||c===10||c===9||c===13))return!1}return!0}hasNewLine(){for(let i=0;i<this.val.length;i++){let c=this.val.charCodeAt(i);if(c===10||c===13)return!0}return!1}condenseWhiteSpace(replacement=""){this.val=replacement}isConstant(){return!0}setDataAttr(_key,_val){}}class CommentNode extends TextNode{render(_stack,rx){return rx.renderComment(this.val)}}function optimizeChilds(childs){for(let i=0;i<childs.length;i++){let child=childs[i];if(child.isConstant())childs[i]=new RenderOnceNode(child);else child.optimize()}}function optimizeNode(node){if(node.isConstant())return new RenderOnceNode(node);return node.optimize(),node}class ChildsNode extends BaseNode{constructor(childs){super();this.childs=childs}isConstant(){return this.childs.every((v)=>v.isConstant())}optimize(){optimizeChilds(this.childs)}}class DomNode extends ChildsNode{constructor(tagName,attrs,childs,namespace=null){super(childs);this.tagName=tagName,this.attrs=attrs,this.namespace=namespace}render(stack,rx){let childNodes=Array(this.childs.length);for(let i=0;i<childNodes.length;i++)childNodes[i]=this.childs[i]?.render?.(stack,rx)??null;return rx.renderTag(this.tagName,this.attrs.eval(stack),childNodes,this.namespace)}setDataAttr(key,val){this.attrs.setDataAttr(key,val)}isConstant(){return this.attrs.isConstant()&&super.isConstant()}}class FragmentNode extends ChildsNode{render(stack,rx){return rx.renderFragment(this.childs.map((c)=>c?.render(stack,rx)))}setDataAttr(key,val){for(let child of this.childs)child.setDataAttr(key,val)}}var maybeFragment=(xs)=>xs.length===1?xs[0]:new FragmentNode(xs),VALID_NODE_RE=/^[a-zA-Z][a-zA-Z0-9-]*$/;class ANode extends BaseNode{constructor(nodeId,val){super();this.nodeId=nodeId,this.val=val}toPathStep(ctx){return ctx.applyKey(this.val?.toPathItem?.()??null)}static parse(html,px){let nodes=px.parseHTML(html);if(nodes.length===0)return new CommentNode("Empty View in ANode.parse");if(nodes.length===1)return ANode.fromDOM(nodes[0],px);let childs=[];for(let i=0;i<nodes.length;i++){let child=ANode.fromDOM(nodes[i],px);if(child!==null)childs.push(child)}let trimmed=condenseChildsWhites(childs);if(trimmed.length===0)return new CommentNode("Empty View in ANode.parse");return maybeFragment(trimmed)}static fromDOM(node,px){if(node instanceof px.Text)return new TextNode(node.textContent);else if(node instanceof px.Comment)return new CommentNode(node.textContent);let{childNodes,attributes:attrs,tagName:tag}=node,childs=[];for(let i=0;i<childNodes.length;i++){let child=ANode.fromDOM(childNodes[i],px);if(child!==null)childs.push(child)}let prevTag=px.currentTag;px.currentTag=tag;try{let isPseudoX=attrs[0]?.name==="@x";if(tag==="X"||isPseudoX)return parseXOp(attrs,childs,isPseudoX?1:0,px);else if(tag.charCodeAt(1)===58&&tag.charCodeAt(0)===88){let macroName=tag.slice(2).toLowerCase();if(macroName==="slot"){let slotName=attrs.getNamedItem("name")?.value??"_";return px.frame.macroSlots[slotName]??maybeFragment(childs)}let[nAttrs,wrappers]=Attributes.parse(attrs,px,!0);return px.onAttributes(nAttrs,wrappers,null,!0,tag),wrap(px.newMacroNode(macroName,nAttrs.toMacroVars(),childs),px,wrappers)}else if(VALID_NODE_RE.test(tag)){let[nAttrs,wrappers,textChild]=Attributes.parse(attrs,px);if(px.onAttributes(nAttrs,wrappers,textChild,!1,tag),textChild)childs.unshift(new RenderTextNode(null,textChild));let domChilds=tag!=="PRE"?condenseChildsWhites(childs):childs,ns=node.namespaceURI;return wrap(new DomNode(tag,nAttrs,domChilds,ns&&ns!==HTML_NS?ns:null),px,wrappers)}return new CommentNode(`Error: InvalidTagName ${tag}`)}finally{px.currentTag=prevTag}}}function parseXOp(attrs,childs,opIdx,px){if(attrs.length===0)return maybeFragment(childs);let{name,value}=attrs[opIdx],as=attrs.getNamedItem("as")?.value??null,node;switch(name){case"slot":node=new SlotNode(null,vp.const(value),maybeFragment(childs));break;case"text":node=px.addNodeIf(RenderTextNode,parseXOpVal(name,value,px,vp.parseText));break;case"render":node=px.addNodeIf(RenderNode,parseXOpVal(name,value,px,vp.parseComponent),as);break;case"render-it":node=px.addNodeIf(RenderItNode,vp.bindValIt,as);break;case"render-each":node=RenderEachNode.parse(px,vp,value,as,attrs);break;case"show":{let val=parseXOpVal(name,value,px,vp.parseBool);node=px.addNodeIf(ShowNode,val,maybeFragment(childs));break}case"hide":{let val=parseXOpVal(name,value,px,vp.parseBool);node=px.addNodeIf(HideNode,val,maybeFragment(childs));break}default:return px.onParseIssue("unknown-x-op",{name,value}),new CommentNode(`Error: InvalidSpecialTagOp ${name}=${value}`)}return processXExtras(node,attrs,name,opIdx+1,px)}function parseXOpVal(opName,value,px,parserFn){let val=parserFn.call(vp,value,px);if(val===null)px.onParseIssue("bad-value",{role:"x-op",op:opName,value});return val}function processXExtras(node,attrs,opName,startIdx,px){let consumed=X_OP_CONSUMED[opName],wrappable=X_OP_WRAPPABLE.has(opName),wrappers=[];for(let i=startIdx;i<attrs.length;i++){let a=attrs[i],aName=a.name;if(consumed.has(aName))continue;if(wrappable&&X_ATTR_WRAPPERS[aName]){wrappers.push([X_ATTR_WRAPPERS[aName],vp.parseBool(a.value,px)]);continue}let issueInfo={op:opName,name:aName,value:a.value};px.onParseIssue("unknown-x-attr",issueInfo)}for(let i=wrappers.length-1;i>=0;i--){let[Cls,val]=wrappers[i],wrapper=px.addNodeIf(Cls,val,node);if(wrapper!==null)node=wrapper}return node}function wrap(node,px,wrappers){if(wrappers)for(let i=wrappers.length-1;i>=0;i--){let wrapperNode=makeWrapperNode(wrappers[i],px);if(wrapperNode)wrapperNode.wrapNode(node),node=wrapperNode}return node}function makeWrapperNode(data,px){let Cls=WRAPPER_NODES[data.name],node=Cls.register?px.addNodeIf(Cls,data.val):data.val&&new Cls(null,data.val);if(node!==null&&data.name==="each")node.iterInfo.enrichWithVal=data.enrichWithVal??null,node.iterInfo.whenVal=data.whenVal??null,node.iterInfo.loopWithVal=data.loopWithVal??null;return node}class MacroNode extends BaseNode{constructor(name,attrs,slots,px){super();this.name=name,this.attrs=attrs,this.slots=slots,this.px=px,this.node=null,this.dataAttrs={}}compile(scope){let{name,attrs,slots}=this;if(this.px.isInsideMacro(name))throw Error(`Recursive macro expansion: ${name}`);let macro=scope.lookupMacro(name);if(macro===null)this.node=new CommentNode(`bad macro: ${name}`);else{let vars={...macro.defaults,...attrs};this.node=macro.expand(this.px.enterMacro(name,vars,slots));for(let key in this.dataAttrs)this.node.setDataAttr(key,this.dataAttrs[key])}}render(stack,rx){return this.node.render(stack,rx)}setDataAttr(key,val){this.dataAttrs[key]=val}isConstant(){return this.node.isConstant()}optimize(){this.node=optimizeNode(this.node)}}class Macro{constructor(defaults,rawView){this.defaults=defaults,this.rawView=rawView}expand(px){return ANode.parse(this.rawView,px)}}class RenderViewId extends ANode{constructor(nodeId,val,viewId){super(nodeId,val);this.viewId=viewId}}class RenderNode extends RenderViewId{render(stack,rx){let newStack=stack.enter(this.val.eval(stack),{},!0);return rx.renderIt(newStack,this,"",this.viewId)}toPathStep(ctx){if(this.val instanceof DynVal){let p=resolveDynProducer(ctx.comp,this.val.name);return p?new DynStep(p.producerCompId,p.producerSteps):null}return super.toPathStep(ctx)}}class RenderItNode extends RenderViewId{render(stack,rx){let newStack=stack.enter(stack.it,{},!0);return rx.renderIt(newStack,this,"",this.viewId)}toPathStep(ctx){let next=ctx.next();if(next===null)return null;let nextNode=next.resolveNode();if(nextNode instanceof EachNode&&next.hasKey){if(nextNode.val instanceof DynVal){let p=resolveDynProducer(ctx.comp,nextNode.val.name);return p?new DynEachStep(p.producerCompId,p.producerSteps,next.key):null}return new EachRenderItStep(nextNode.val.name,next.key)}return null}}class RenderEachNode extends RenderViewId{constructor(nodeId,val,viewId){super(nodeId,val,viewId);this.iterInfo=new IterInfo(val,null,null,null)}render(stack,rx){return rx.renderEach(stack,this.iterInfo,this,this.viewId)}toPathStep(ctx){if(this.val instanceof DynVal){if(!ctx.hasKey)return null;let p=resolveDynProducer(ctx.comp,this.val.name);return p?new DynEachStep(p.producerCompId,p.producerSteps,ctx.key):null}return super.toPathStep(ctx)}static parse(px,vp2,s,as,attrs){let node=px.addNodeIf(RenderEachNode,parseXOpVal("render-each",s,px,vp2.parseSequence),as);if(node!==null){let attrParser=getAttrParser(px);attrParser.eachAttr=attrParser.pushWrapper("each",s,node.val);let when=attrs.getNamedItem("when");if(when)attrParser._parseWhen(when.value);let lWith=attrs.getNamedItem("loop-with");if(lWith)attrParser._parseLoopWith(lWith.value);node.iterInfo.whenVal=attrParser.eachAttr.whenVal??null,node.iterInfo.loopWithVal=attrParser.eachAttr.loopWithVal??null}return node}}class RenderTextNode extends ANode{render(stack,_rx){return this.val.eval(stack)}}class RenderOnceNode extends BaseNode{constructor(node){super();this.node=node,this._render=(stack,rx)=>{let dom=node.render(stack,rx);return this._render=(_stack,_rx)=>dom,dom}}render(stack,rx){return this._render(stack,rx)}}class WrapperNode extends ANode{constructor(nodeId,val,node=null){super(nodeId,val);this.node=node}wrapNode(node){this.node=node}setDataAttr(key,val){this.node.setDataAttr(key,val)}optimize(){this.node=optimizeNode(this.node)}static register=!1}class ShowNode extends WrapperNode{render(stack,rx){return this.val.eval(stack)?this.node.render(stack,rx):null}}class HideNode extends WrapperNode{render(stack,rx){return this.val.eval(stack)?null:this.node.render(stack,rx)}}class PushViewNameNode extends WrapperNode{render(stack,rx){return this.node.render(stack.pushViewName(this.val.eval(stack)),rx)}}class SlotNode extends WrapperNode{optimize(){this.node.optimize()}}class ScopeNode extends WrapperNode{render(stack,rx){let binds=this.val.evalAsHandler(stack)?.call(stack.it)??{};return this.node.render(stack.enter(stack.it,binds,!1),rx)}toPathStep(_ctx){return new BindStep({})}wrapNode(node){this.node=node,this.node.setDataAttr("data-nid",this.nodeId)}static register=!0}class EachNode extends WrapperNode{constructor(nodeId,val){super(nodeId,val);this.iterInfo=new IterInfo(val,null,null,null)}render(stack,rx){return rx.renderEachWhen(stack,this.iterInfo,this.node,this.nodeId)}toPathStep(ctx){return ctx.hasKey?new EachBindStep(this.val,ctx.key):null}static register=!0}class IterInfo{constructor(val,whenVal,loopWithVal,enrichWithVal){this.val=val,this.whenVal=whenVal,this.loopWithVal=loopWithVal,this.enrichWithVal=enrichWithVal}eval(stack){let seq=this.val.eval(stack)??[],filter=this.whenVal?.evalAsHandler(stack)??filterAlwaysTrue,loopWith=this.loopWithVal?.evalAsHandler(stack)??nullLoopWith,enricher=this.enrichWithVal?.evalAsHandler(stack)??null;return{seq,filter,loopWith,enricher}}}var filterAlwaysTrue=(_v,_k,_seq)=>!0,nullLoopWith=(seq)=>({seq}),X_OP_CONSUMED={slot:new Set,text:new Set,render:new Set(["as"]),"render-it":new Set(["as"]),"render-each":new Set(["as","when","loop-with"]),show:new Set,hide:new Set},X_OP_WRAPPABLE=new Set(["text","render","render-it","render-each"]),X_ATTR_WRAPPERS={show:ShowNode,hide:HideNode},WRAPPER_NODES={slot:SlotNode,show:ShowNode,hide:HideNode,each:EachNode,scope:ScopeNode,"push-view":PushViewNameNode};class ParseContext{constructor(document2,Text,Comment,nodes,events2,macroNodes,frame,parent){this.nodes=nodes??[],this.events=events2??[],this.macroNodes=macroNodes??[],this.parent=parent??null,this.frame=frame??{},this.document=document2??globalThis.document,this.Text=Text??globalThis.Text,this.Comment=Comment??globalThis.Comment,this.cacheConstNodes=!0,this.currentTag=null}isInsideMacro(name){return this.frame.macroName===name||this.parent?.isInsideMacro(name)}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events:events2,macroNodes}=this;return new ParseContext(document2,Text,Comment,nodes,events2,macroNodes,{macroName,macroVars,macroSlots},this)}parseHTML(html){let t=this.document.createElement("template");return t.innerHTML=html,t.content.childNodes}addNodeIf(Class,val,extra){if(val!==null){let nodeId=this.nodes.length,node=new Class(nodeId,val,extra);return this.nodes.push(node),node}return null}registerEvents(){let id=this.events.length,events2=new NodeEvents(id);return this.events.push(events2),events2}newMacroNode(macroName,mAttrs,childs){let anySlot=[],slots={_:new FragmentNode(anySlot)};for(let child of childs)if(child instanceof SlotNode)slots[child.val.val]=child.node;else if(!(child instanceof TextNode)||!child.isWhiteSpace())anySlot.push(child);let node=new MacroNode(macroName,mAttrs,slots,this);return this.macroNodes.push(node),node}compile(scope){for(let i=0;i<this.macroNodes.length;i++)this.macroNodes[i].compile(scope)}*genEventNames(){for(let event of this.events)yield*event.genEventNames()}getEventForId(id){return this.events[id]??null}getNodeForId(id){return this.nodes[id]??null}onAttributes(_attrs,_wrapperAttrs,_textChild,_isMacroCall,_tag){}onParseIssue(kind,info){console.warn(`tutuca parse issue [${kind}]`,info)}}var _htmlBlockTags="ADDRESS,ARTICLE,ASIDE,BLOCKQUOTE,CAPTION,COL,COLGROUP,DETAILS,DIALOG,DIV,DD,DL,DT,FIELDSET,FIGCAPTION,FIGURE,FOOTER,FORM,H1,H2,H3,H4,H5,H6,HEADER,HGROUP,HR,LEGEND,LI,MAIN,MENU,NAV,OL,P,PRE,SECTION,SUMMARY,TABLE,TBODY,TD,TFOOT,TH,THEAD,TR,UL",HTML_BLOCK_TAGS=new Set(_htmlBlockTags.split(",")),isBlockDomNode=(n)=>{let node=n instanceof FragmentNode?n.childs[0]:n;return node instanceof DomNode&&HTML_BLOCK_TAGS.has(node.tagName)};function condenseChildsWhites(childs){if(childs.length===0)return childs;let changed=!1;if(childs[0].isWhiteSpace?.())childs[0].condenseWhiteSpace(),changed=!0;let last=childs.length-1;if(last>0&&childs[last].isWhiteSpace?.())childs[last].condenseWhiteSpace(),changed=!0;for(let i=1;i<last;i++){let cur=childs[i];if(cur.isWhiteSpace?.()&&cur.hasNewLine()){let bothBlock=isBlockDomNode(childs[i-1])&&isBlockDomNode(childs[i+1]);if(cur.condenseWhiteSpace(bothBlock?"":" "),bothBlock)changed=!0}}return changed?childs.filter((c)=>!(c instanceof TextNode&&c.val==="")):childs}class View{constructor(name,rawView="No View Defined",style="",anode=null,ctx=null){this.name=name,this.anode=anode,this.style=style,this.ctx=ctx,this.rawView=rawView}compile(ctx,scope,cid){if(this.ctx=ctx,this.anode=ANode.parse(this.rawView,ctx),this.anode.setDataAttr("data-cid",cid),this.anode.setDataAttr("data-vid",this.name),this.ctx.compile(scope),ctx.cacheConstNodes)this.anode=optimizeNode(this.anode)}render(stack,rx){return this.anode.render(stack,rx)}}class NodeEvents{constructor(id){this.id=id,this.handlers=[]}add(name,handlerCall,modifiers){this.handlers.push(new NodeEvent(name,handlerCall,modifiers))}*genEventNames(){for(let handler of this.handlers)yield handler.name}getHandlersFor(eventName){let r=null;for(let handler of this.handlers)if(handler.handlesEventName(eventName))r??=[],r.push(handler);return r}}class NodeEvent{constructor(name,handlerCall,modifiers){this.name=name,this.handlerCall=handlerCall,this.modifierWrapper=compileModifiers(name,modifiers),this.modifiers=modifiers}handlesEventName(name){return this.name===name}getHandlerAndArgs(stack,event){let r=this.handlerCall.getHandlerAndArgs(stack,event);return r[0]=this.modifierWrapper(r[0],event),r}}var isMac=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac"),fwdIfCtxPred=(pred)=>(w)=>(that,f,args,ctx)=>pred(ctx)?w(that,f,args,ctx):that,fwdIfKey=(keyName)=>fwdIfCtxPred((ctx)=>ctx.e.key===keyName),fwdCtrl=fwdIfCtxPred(({e})=>isMac&&e.metaKey||e.ctrlKey),fwdMeta=fwdIfCtxPred(({e})=>e.metaKey),fwdAlt=fwdIfCtxPred(({e})=>e.altKey),metaWraps={ctrl:fwdCtrl,cmd:fwdCtrl,meta:fwdMeta,alt:fwdAlt},MOD_WRAPPERS_BY_EVENT={keydown:{send:fwdIfKey("Enter"),cancel:fwdIfKey("Escape"),...metaWraps},click:{...metaWraps}},identityModifierWrapper=(f,_ctx)=>f;function compileModifiers(eventName,names){if(names.length===0)return identityModifierWrapper;let wrappers=MOD_WRAPPERS_BY_EVENT[eventName]??{},w=(that,f,args,_ctx)=>f.apply(that,args);for(let name of names){let wrapper=wrappers[name];if(wrapper!==void 0)w=wrapper(w)}return(f,ctx)=>function(...args){return w(this,f,args,ctx)}}class ParseCtxClassSetCollector extends ParseContext{constructor(...args){super(...args);this.classes=new Set}_addClasses(s){for(let v of s.split(/\s+/))this.classes.add(v)}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events:events2,macroNodes}=this,v=new ParseCtxClassSetCollector(document2,Text,Comment,nodes,events2,macroNodes,{macroName,macroVars,macroSlots},this);return v.classes=this.classes,v}onAttributes(attrs,_wrapperAttrs,_textChild,_isMacroCall,_tag){if(Array.isArray(attrs.items))for(let attr of attrs.items){if(attr.name!=="class")continue;let{val,thenVal,elseVal}=attr;if(thenVal!==void 0)this._maybeAddVal(thenVal),this._maybeAddVal(elseVal);else this._maybeAddVal(val)}else{let attr=attrs.items.class;if(attr)this._addClasses(attr)}}_maybeAddVal(value){if(!this._maybeAddStrTpl(value)&&typeof value?.val==="string")this._addClasses(value.val)}_maybeAddStrTpl(value){if(value?.vals!==void 0){for(let val of value.vals)if(val instanceof ConstVal&&val.val!=="")this._addClasses(val.val);return!0}return!1}}var CharCodes={Tab:9,NewLine:10,FormFeed:12,CarriageReturn:13,Space:32,ExclamationMark:33,Number:35,SingleQuote:39,DoubleQuote:34,Dash:45,Slash:47,Zero:48,Nine:57,Semi:59,Lt:60,Eq:61,Gt:62,Questionmark:63,UpperA:65,LowerA:97,UpperF:70,LowerF:102,UpperZ:90,LowerZ:122,LowerX:120,OpeningSquareBracket:91},State={Text:1,BeforeTagName:2,InTagName:3,InSelfClosingTag:4,BeforeClosingTagName:5,InClosingTagName:6,AfterClosingTagName:7,BeforeAttributeName:8,InAttributeName:9,AfterAttributeName:10,BeforeAttributeValue:11,InAttributeValueDq:12,InAttributeValueSq:13,InAttributeValueNq:14,BeforeDeclaration:15,InDeclaration:16,InProcessingInstruction:17,BeforeComment:18,CDATASequence:19,DeclarationSequence:20,InSpecialComment:21,InCommentLike:22,SpecialStartSequence:23,InSpecialTag:24,InPlainText:25};function isWhitespace(c){return c===CharCodes.Space||c===CharCodes.NewLine||c===CharCodes.Tab||c===CharCodes.FormFeed||c===CharCodes.CarriageReturn}function isEndOfTagSection(c){return c===CharCodes.Slash||c===CharCodes.Gt||isWhitespace(c)}function isASCIIAlpha(c){return c>=CharCodes.LowerA&&c<=CharCodes.LowerZ||c>=CharCodes.UpperA&&c<=CharCodes.UpperZ}var QuoteType={NoValue:0,Unquoted:1,Single:2,Double:3},Sequences={Empty:new Uint8Array(0),Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,33,62]),Doctype:new Uint8Array([100,111,99,116,121,112,101]),IframeEnd:new Uint8Array([60,47,105,102,114,97,109,101]),NoembedEnd:new Uint8Array([60,47,110,111,101,109,98,101,100]),NoframesEnd:new Uint8Array([60,47,110,111,102,114,97,109,101,115]),Plaintext:new Uint8Array([60,47,112,108,97,105,110,116,101,120,116]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])},specialStartSequences=new Map([[Sequences.IframeEnd[2],Sequences.IframeEnd],[Sequences.NoembedEnd[2],Sequences.NoembedEnd],[Sequences.Plaintext[2],Sequences.Plaintext],[Sequences.ScriptEnd[2],Sequences.ScriptEnd],[Sequences.TitleEnd[2],Sequences.TitleEnd],[Sequences.XmpEnd[2],Sequences.XmpEnd]]);class HtmlTokenizer{constructor({xmlMode=!1,recognizeSelfClosing=xmlMode}={},cbs){this.cbs=cbs,this.xmlMode=xmlMode,this.recognizeSelfClosing=recognizeSelfClosing,this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.isSpecial=!1,this.running=!0,this.offset=0,this.currentSequence=Sequences.Empty,this.sequenceIndex=0}reset(){this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.isSpecial=!1,this.currentSequence=Sequences.Empty,this.sequenceIndex=0,this.running=!0,this.offset=0}write(chunk){this.offset+=this.buffer.length,this.buffer=chunk,this.parse()}end(){if(this.running)this.finish()}pause(){this.running=!1}resume(){if(this.running=!0,this.index<this.buffer.length+this.offset)this.parse()}stateText(c){if(c===CharCodes.Lt||this.fastForwardTo(CharCodes.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=State.BeforeTagName,this.sectionStart=this.index}}enterTagBody(){if(this.currentSequence===Sequences.Plaintext)this.currentSequence=Sequences.Empty,this.state=State.InPlainText;else if(this.isSpecial)this.state=State.InSpecialTag,this.sequenceIndex=0;else this.state=State.Text}stateSpecialStartSequence(c){let lower=c|32;if(this.sequenceIndex<this.currentSequence.length){if(lower===this.currentSequence[this.sequenceIndex]){this.sequenceIndex++;return}if(this.sequenceIndex===3){if(this.currentSequence===Sequences.ScriptEnd&&lower===Sequences.StyleEnd[3]){this.currentSequence=Sequences.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===Sequences.TitleEnd&&lower===Sequences.TextareaEnd[3]){this.currentSequence=Sequences.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===Sequences.NoembedEnd&&lower===Sequences.NoframesEnd[4]){this.currentSequence=Sequences.NoframesEnd,this.sequenceIndex=5;return}}else if(isEndOfTagSection(c)){this.sequenceIndex=0,this.state=State.InTagName,this.stateInTagName(c);return}this.isSpecial=!1,this.currentSequence=Sequences.Empty,this.sequenceIndex=0,this.state=State.InTagName,this.stateInTagName(c)}stateCDATASequence(c){if(c===Sequences.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===Sequences.Cdata.length)this.state=State.InCommentLike,this.currentSequence=Sequences.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=State.InDeclaration,this.stateInDeclaration(c);else this.state=State.InSpecialComment,this.stateInSpecialComment(c)}fastForwardTo(c){while(++this.index<this.buffer.length+this.offset)if(this.buffer.charCodeAt(this.index-this.offset)===c)return!0;return this.index=this.buffer.length+this.offset-1,!1}emitComment(offset){this.cbs.oncomment(this.sectionStart,this.index,offset),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=State.Text}stateInCommentLike(c){if(!this.xmlMode&&this.currentSequence===Sequences.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&c===CharCodes.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===Sequences.CommentEnd&&this.sequenceIndex===2&&c===CharCodes.Gt)this.emitComment(2);else if(this.currentSequence===Sequences.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&c!==CharCodes.Gt)this.sequenceIndex=Number(c===CharCodes.Dash);else if(c===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===Sequences.CdataEnd)this.cbs.oncdata(this.sectionStart,this.index,2);else this.cbs.oncomment(this.sectionStart,this.index,3);this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=State.Text}}else if(this.sequenceIndex===0){if(this.fastForwardTo(this.currentSequence[0]))this.sequenceIndex=1}else if(c!==this.currentSequence[this.sequenceIndex-1])this.sequenceIndex=0}isTagStartChar(c){return this.xmlMode?!isEndOfTagSection(c):isASCIIAlpha(c)}stateInSpecialTag(c){if(this.sequenceIndex===this.currentSequence.length){if(isEndOfTagSection(c)){let endOfText=this.index-this.currentSequence.length;if(this.sectionStart<endOfText){let actualIndex=this.index;this.index=endOfText,this.cbs.ontext(this.sectionStart,endOfText),this.index=actualIndex}this.isSpecial=!1,this.sectionStart=endOfText+2,this.stateInClosingTagName(c);return}this.sequenceIndex=0}if((c|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.fastForwardTo(CharCodes.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(c===CharCodes.Lt)}stateBeforeTagName(c){if(c===CharCodes.ExclamationMark)this.state=State.BeforeDeclaration,this.sectionStart=this.index+1;else if(c===CharCodes.Questionmark)if(this.xmlMode)this.state=State.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=State.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(c)){this.sectionStart=this.index;let special=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:specialStartSequences.get(c|32);if(special===void 0)this.state=State.InTagName;else this.isSpecial=!0,this.currentSequence=special,this.sequenceIndex=3,this.state=State.SpecialStartSequence}else if(c===CharCodes.Slash)this.state=State.BeforeClosingTagName;else this.state=State.Text,this.stateText(c)}stateInTagName(c){if(isEndOfTagSection(c))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c)}stateBeforeClosingTagName(c){if(isWhitespace(c)){if(!this.xmlMode)this.state=State.InSpecialComment,this.sectionStart=this.index}else if(c===CharCodes.Gt){if(this.state=State.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(c)?State.InClosingTagName:State.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(c){if(isEndOfTagSection(c))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.AfterClosingTagName,this.stateAfterClosingTagName(c)}stateAfterClosingTagName(c){if(c===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))this.state=State.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(c){if(c===CharCodes.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(c===CharCodes.Slash)this.state=State.InSelfClosingTag;else if(!isWhitespace(c))this.state=State.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(c){if(c===CharCodes.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=State.Text,this.isSpecial=!1,this.currentSequence=Sequences.Empty}else if(!isWhitespace(c))this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c)}stateInAttributeName(c){if(c===CharCodes.Eq||isEndOfTagSection(c))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=State.AfterAttributeName,this.stateAfterAttributeName(c)}stateAfterAttributeName(c){if(c===CharCodes.Eq)this.state=State.BeforeAttributeValue;else if(c===CharCodes.Slash||c===CharCodes.Gt)this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c);else if(!isWhitespace(c))this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.state=State.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(c){if(c===CharCodes.DoubleQuote)this.state=State.InAttributeValueDq,this.sectionStart=this.index+1;else if(c===CharCodes.SingleQuote)this.state=State.InAttributeValueSq,this.sectionStart=this.index+1;else if(!isWhitespace(c))this.sectionStart=this.index,this.state=State.InAttributeValueNq,this.stateInAttributeValueNoQuotes(c)}handleInAttributeValue(c,quote){if(c===quote||this.fastForwardTo(quote))this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(quote===CharCodes.DoubleQuote?QuoteType.Double:QuoteType.Single,this.index+1),this.state=State.BeforeAttributeName}stateInAttributeValueDoubleQuotes(c){this.handleInAttributeValue(c,CharCodes.DoubleQuote)}stateInAttributeValueSingleQuotes(c){this.handleInAttributeValue(c,CharCodes.SingleQuote)}stateInAttributeValueNoQuotes(c){if(isWhitespace(c)||c===CharCodes.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(QuoteType.Unquoted,this.index),this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c)}stateBeforeDeclaration(c){if(c===CharCodes.OpeningSquareBracket)this.state=State.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=c===CharCodes.Dash?State.BeforeComment:State.InDeclaration;else if((c|32)===Sequences.Doctype[0])this.state=State.DeclarationSequence,this.currentSequence=Sequences.Doctype,this.sequenceIndex=1;else if(c===CharCodes.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1;else if(c===CharCodes.Dash)this.state=State.BeforeComment;else this.state=State.InSpecialComment}stateDeclarationSequence(c){if(this.sequenceIndex===this.currentSequence.length)this.state=State.InDeclaration,this.stateInDeclaration(c);else if((c|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(c===CharCodes.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1;else this.state=State.InSpecialComment}stateInDeclaration(c){if(c===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=State.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(c){if(c===CharCodes.Questionmark)this.sequenceIndex=1;else if(c===CharCodes.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=State.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(CharCodes.Questionmark))}stateBeforeComment(c){if(c===CharCodes.Dash)this.state=State.InCommentLike,this.currentSequence=Sequences.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=State.InDeclaration;else if(c===CharCodes.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1;else this.state=State.InSpecialComment}stateInSpecialComment(c){if(c===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1}cleanup(){if(this.running&&this.sectionStart!==this.index){if(this.state===State.Text||this.state===State.InPlainText||this.state===State.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===State.InAttributeValueDq||this.state===State.InAttributeValueSq||this.state===State.InAttributeValueNq)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index}}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){while(this.shouldContinue()){let c=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case State.Text:this.stateText(c);break;case State.InPlainText:this.index=this.buffer.length+this.offset-1;break;case State.SpecialStartSequence:this.stateSpecialStartSequence(c);break;case State.InSpecialTag:this.stateInSpecialTag(c);break;case State.CDATASequence:this.stateCDATASequence(c);break;case State.DeclarationSequence:this.stateDeclarationSequence(c);break;case State.InAttributeValueDq:this.stateInAttributeValueDoubleQuotes(c);break;case State.InAttributeName:this.stateInAttributeName(c);break;case State.InCommentLike:this.stateInCommentLike(c);break;case State.InSpecialComment:this.stateInSpecialComment(c);break;case State.BeforeAttributeName:this.stateBeforeAttributeName(c);break;case State.InTagName:this.stateInTagName(c);break;case State.InClosingTagName:this.stateInClosingTagName(c);break;case State.BeforeTagName:this.stateBeforeTagName(c);break;case State.AfterAttributeName:this.stateAfterAttributeName(c);break;case State.InAttributeValueSq:this.stateInAttributeValueSingleQuotes(c);break;case State.BeforeAttributeValue:this.stateBeforeAttributeValue(c);break;case State.BeforeClosingTagName:this.stateBeforeClosingTagName(c);break;case State.AfterClosingTagName:this.stateAfterClosingTagName(c);break;case State.InAttributeValueNq:this.stateInAttributeValueNoQuotes(c);break;case State.InSelfClosingTag:this.stateInSelfClosingTag(c);break;case State.InDeclaration:this.stateInDeclaration(c);break;case State.BeforeDeclaration:this.stateBeforeDeclaration(c);break;case State.BeforeComment:this.stateBeforeComment(c);break;case State.InProcessingInstruction:this.stateInProcessingInstruction(c);break}this.index++}this.cleanup()}finish(){this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(endIndex){if(this.state!==State.InCommentLike)return!1;if(this.currentSequence===Sequences.CdataEnd)if(this.xmlMode){if(this.sectionStart<endIndex)this.cbs.oncdata(this.sectionStart,endIndex,0)}else{let cdataStart=this.sectionStart-Sequences.Cdata.length-1;this.cbs.oncomment(cdataStart,endIndex,0)}else{let offset=this.xmlMode?0:Math.min(this.sequenceIndex,Sequences.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,endIndex,offset)}return!0}handleTrailingMarkupDeclaration(endIndex){if(this.xmlMode)switch(this.state){case State.InSpecialComment:case State.BeforeComment:case State.CDATASequence:case State.DeclarationSequence:case State.InDeclaration:return this.cbs.ontext(this.sectionStart,endIndex),!0;default:return!1}switch(this.state){case State.BeforeDeclaration:case State.InSpecialComment:case State.BeforeComment:case State.CDATASequence:return this.cbs.oncomment(this.sectionStart,endIndex,0),!0;case State.DeclarationSequence:if(this.sequenceIndex!==Sequences.Doctype.length)this.cbs.oncomment(this.sectionStart,endIndex,0);return!0;case State.InDeclaration:return!0;default:return!1}}handleTrailingData(){let endIndex=this.buffer.length+this.offset;if(this.handleTrailingCommentLikeData(endIndex)||this.handleTrailingMarkupDeclaration(endIndex))return;if(this.sectionStart>=endIndex)return;switch(this.state){case State.InTagName:case State.BeforeAttributeName:case State.BeforeAttributeValue:case State.AfterAttributeName:case State.InAttributeName:case State.InAttributeValueSq:case State.InAttributeValueDq:case State.InAttributeValueNq:case State.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,endIndex)}}}var VOID_ELEMENTS=new Set(["area","base","br","col","embed","hr","img","input","link","meta","source","track","wbr"]),RAW_TEXT_ELEMENTS=new Set(["script","style","iframe","noembed","noframes","noscript","xmp","plaintext"]);var SPECIAL_ELEMENTS=new Set(["address","applet","area","article","aside","base","basefont","bgsound","blockquote","br","button","caption","center","col","colgroup","dd","details","dir","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","iframe","img","input","keygen","li","link","listing","main","marquee","menu","meta","nav","noembed","noframes","noscript","object","ol","p","param","plaintext","pre","script","search","section","select","source","style","summary","table","tbody","td","template","textarea","tfoot","th","thead","title","tr","track","ul","wbr","xmp"]),FORMATTING_ELEMENTS=new Set(["a","b","big","code","em","font","i","nobr","s","small","strike","strong","tt","u"]),DEFAULT_SCOPE_BOUNDARIES=new Set(["applet","caption","html","table","td","th","marquee","object","select","template"]),MATHML_TEXT_INTEGRATION_POINT_NAMES=new Set(["mi","mo","mn","ms","mtext"]),SVG_HTML_INTEGRATION_POINT_NAMES=new Set(["foreignobject","desc","title"]),SCOPE_LIST_ITEM=new Set([...DEFAULT_SCOPE_BOUNDARIES,"ol","ul"]),SCOPE_BUTTON=new Set([...DEFAULT_SCOPE_BOUNDARIES,"button"]),SCOPE_DEFAULT=DEFAULT_SCOPE_BOUNDARIES,SCOPE_TABLE=new Set(["html","table","template"]);var STANDARD_SVG_CAMEL_ELEMENTS=new Set(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"]),STANDARD_SVG_CAMEL_ATTRS=new Set(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","xChannelSelector","yChannelSelector","zoomAndPan"]),MATHML_CAMEL_ATTRS=new Set(["definitionURL"]),SVG_ATTR_LOWERCASE_TO_CAMEL=new Map;for(let camel of STANDARD_SVG_CAMEL_ATTRS)SVG_ATTR_LOWERCASE_TO_CAMEL.set(camel.toLowerCase(),camel);var MATHML_ATTR_LOWERCASE_TO_CAMEL=new Map;for(let camel of MATHML_CAMEL_ATTRS)MATHML_ATTR_LOWERCASE_TO_CAMEL.set(camel.toLowerCase(),camel);var FOREIGN_BREAKOUT_TAGS=new Set(["b","big","blockquote","body","br","center","code","dd","div","dl","dt","em","embed","h1","h2","h3","h4","h5","h6","head","hr","i","img","li","listing","menu","meta","nobr","ol","p","pre","ruby","s","small","span","strong","strike","sub","sup","table","tt","u","ul","var"]);var SELECT_BREAKOUT_TAGS=new Set(["input","keygen","textarea","select"]),MODES=Object.freeze({inBody:"inBody",inTable:"inTable",inCaption:"inCaption",inColumnGroup:"inColumnGroup",inTableBody:"inTableBody",inRow:"inRow",inCell:"inCell",inSelect:"inSelect",inSelectInTable:"inSelectInTable",inTemplate:"inTemplate"}),NS=Object.freeze({html:"html",svg:"svg",math:"math"}),FRAGMENT_CONTEXT_MODES=Object.freeze({template:{mode:MODES.inTemplate,ns:NS.html},body:{mode:MODES.inBody,ns:NS.html},div:{mode:MODES.inBody,ns:NS.html},table:{mode:MODES.inTable,ns:NS.html},tbody:{mode:MODES.inTableBody,ns:NS.html},thead:{mode:MODES.inTableBody,ns:NS.html},tfoot:{mode:MODES.inTableBody,ns:NS.html},caption:{mode:MODES.inCaption,ns:NS.html},colgroup:{mode:MODES.inColumnGroup,ns:NS.html},tr:{mode:MODES.inRow,ns:NS.html},td:{mode:MODES.inCell,ns:NS.html},th:{mode:MODES.inCell,ns:NS.html},select:{mode:MODES.inSelect,ns:NS.html},svg:{mode:MODES.inBody,ns:NS.svg},math:{mode:MODES.inBody,ns:NS.math}});var HTML_TAG_NAME_HAS_UPPERCASE="HTML_TAG_NAME_HAS_UPPERCASE",HTML_SVG_TAG_WILL_LOWERCASE="HTML_SVG_TAG_WILL_LOWERCASE",HTML_SVG_ATTR_WILL_LOWERCASE="HTML_SVG_ATTR_WILL_LOWERCASE",HTML_MATHML_ATTR_WILL_LOWERCASE="HTML_MATHML_ATTR_WILL_LOWERCASE",HTML_TAG_NOT_ALLOWED_IN_PARENT="HTML_TAG_NOT_ALLOWED_IN_PARENT",HTML_TEXT_NOT_ALLOWED_IN_PARENT="HTML_TEXT_NOT_ALLOWED_IN_PARENT",HTML_VOID_ELEMENT_HAS_CLOSE_TAG="HTML_VOID_ELEMENT_HAS_CLOSE_TAG",HTML_DUPLICATE_FORM="HTML_DUPLICATE_FORM",HTML_NESTED_INTERACTIVE="HTML_NESTED_INTERACTIVE",HTML_MISNESTED_FORMATTING="HTML_MISNESTED_FORMATTING",HTML_UNEXPECTED_END_TAG="HTML_UNEXPECTED_END_TAG",HTML_DUPLICATE_ATTRIBUTE="HTML_DUPLICATE_ATTRIBUTE",HTML_ATTRIBUTES_ON_END_TAG="HTML_ATTRIBUTES_ON_END_TAG",HTML_SELF_CLOSING_END_TAG="HTML_SELF_CLOSING_END_TAG",HTML_MISSING_ATTRIBUTE_VALUE="HTML_MISSING_ATTRIBUTE_VALUE",HTML_CDATA_IN_HTML_NAMESPACE="HTML_CDATA_IN_HTML_NAMESPACE",HTML_BOGUS_COMMENT="HTML_BOGUS_COMMENT",HTML_UNCLOSED_BEFORE_END="HTML_UNCLOSED_BEFORE_END",LEVEL_ERROR="error",LEVEL_WARN="warn",TABLE_SCOPE_TAGS=new Set(["caption","colgroup","thead","tbody","tfoot","tr","td","th","table"]),TABLE_BODY_CELL_TAGS=new Set(["td","th"]),IMPLIED_END_TAGS=new Set(["dd","dt","li","optgroup","option","p","rb","rp","rt","rtc"]);function lintHtml(html,onFinding,opts={}){let TokenizerClass=opts.TokenizerClass??HtmlTokenizer,ctx=new LinterCtx(html,onFinding,opts),tokenizer=new TokenizerClass({xmlMode:!1,decodeEntities:!1,recognizeSelfClosing:!0},ctx);return ctx.tokenizer=tokenizer,tokenizer.write(html),tokenizer.end(),ctx.findingCount}class LinterCtx{constructor(html,onFinding,opts){this.html=html,this.onFinding=onFinding,this.findingCount=0,this.lineStarts=computeLineStarts(html);let ctxName=opts.fragmentContext??"template",ctxInfo=FRAGMENT_CONTEXT_MODES[ctxName]??FRAGMENT_CONTEXT_MODES.template;if(this.openElements=[],ctxName==="tr")this.openElements.push({name:"table",ns:NS.html,start:-1}),this.openElements.push({name:"tbody",ns:NS.html,start:-1});else if(ctxName==="tbody"||ctxName==="thead"||ctxName==="tfoot")this.openElements.push({name:"table",ns:NS.html,start:-1});else if(ctxName==="td"||ctxName==="th")this.openElements.push({name:"table",ns:NS.html,start:-1}),this.openElements.push({name:"tbody",ns:NS.html,start:-1}),this.openElements.push({name:"tr",ns:NS.html,start:-1});else if(ctxName==="caption")this.openElements.push({name:"table",ns:NS.html,start:-1});else if(ctxName==="colgroup")this.openElements.push({name:"table",ns:NS.html,start:-1});else if(ctxName==="svg")this.openElements.push({name:"svg",ns:NS.svg,start:-1});else if(ctxName==="math")this.openElements.push({name:"math",ns:NS.math,start:-1});else if(ctxName==="select")this.openElements.push({name:"select",ns:NS.html,start:-1});this.insertionMode=ctxInfo.mode,this.templateInsertionModes=ctxName==="template"?[MODES.inTemplate]:[],this.activeFormatting=[],this.framesetOk=!0,this.svgCamelElements=opts.svgCamelElements??STANDARD_SVG_CAMEL_ELEMENTS,this.transparentTagPrefixes=(opts.transparentTagPrefixes??[]).map((p)=>p.toLowerCase()),this.currentTagName="",this.currentTagRawName="",this.currentTagStart=0,this.currentAttrs=[],this.currentAttr=null,this.tokenizer=null}onopentagname(start,end){let raw=this.html.slice(start,end);this.currentTagRawName=raw,this.currentTagName=raw.toLowerCase(),this.currentTagStart=start,this.currentAttrs=[],this.currentAttr=null}onattribname(start,end){let rawName=this.html.slice(start,end);this.currentAttr={name:rawName.toLowerCase(),rawName,nameStart:start,value:null,valueStart:-1,valueEnd:-1,quote:QuoteType.NoValue}}onattribdata(start,end){if(!this.currentAttr)return;this.currentAttr.valueStart=start,this.currentAttr.valueEnd=end,this.currentAttr.value=this.html.slice(start,end)}onattribend(quote,_end){let a=this.currentAttr;if(!a)return;a.quote=quote;let dup=this.currentAttrs.find((x)=>x.name===a.name);if(dup)this.report(HTML_DUPLICATE_ATTRIBUTE,LEVEL_WARN,a.nameStart,{name:a.name,firstAt:dup.nameStart},{kind:"remove",what:`the duplicate '${a.name}' attribute`});else this.currentAttrs.push(a);if(a.quote===QuoteType.Unquoted&&a.value==="")this.report(HTML_MISSING_ATTRIBUTE_VALUE,LEVEL_WARN,a.nameStart,{name:a.name});this.currentAttr=null}onattribentity(_cp){}ontextentity(_cp,_end){}getAttr(name){let a=this.currentAttrs.find((x)=>x.name===name);return a?a.value:null}hasAttr(name){return this.currentAttrs.some((x)=>x.name===name)}onopentagend(endIndex){this.handleStartTag(!1,endIndex)}onselfclosingtag(endIndex){this.handleStartTag(!0,endIndex)}onclosetag(start,end){let name=this.html.slice(start,end).toLowerCase(),i=end,lastNonWs=-1;while(i<this.html.length){let c=this.html.charCodeAt(i);if(c===62)break;if(c!==32&&c!==9&&c!==10&&c!==13&&c!==12)lastNonWs=i;i++}if(lastNonWs>=0)if(this.html.charCodeAt(lastNonWs)===47&&lastNonWs===i-1){let firstNonWs=-1;for(let j=end;j<lastNonWs;j++){let c2=this.html.charCodeAt(j);if(c2!==32&&c2!==9&&c2!==10&&c2!==13&&c2!==12){firstNonWs=j;break}}if(firstNonWs<0)this.report(HTML_SELF_CLOSING_END_TAG,LEVEL_WARN,start,{tag:name},{kind:"rewrite",from:`</${name}/>`,to:`</${name}>`});else this.report(HTML_ATTRIBUTES_ON_END_TAG,LEVEL_WARN,start,{tag:name},{kind:"remove",what:`attributes from </${name}>`})}else this.report(HTML_ATTRIBUTES_ON_END_TAG,LEVEL_WARN,start,{tag:name},{kind:"remove",what:`attributes from </${name}>`});this.handleEndTag(name,start)}ontext(start,end){if(start>=end)return;let top=this.currentNode();if(top&&top.ns!==NS.html&&!this.isIntegrationPoint(top))return;this.handleText(start,end)}oncomment(start,_end,endOffset){if(endOffset===0)this.report(HTML_BOGUS_COMMENT,LEVEL_WARN,start,{mode:this.insertionMode})}oncdata(start,_end,_endOffset){if(this.currentNamespace()===NS.html)this.report(HTML_CDATA_IN_HTML_NAMESPACE,LEVEL_WARN,start,{mode:this.insertionMode})}ondeclaration(_start,_end){}onprocessinginstruction(_start,_end){}isInForeignContext(){return this.currentNamespace()!==NS.html}onend(){}report(id,level,offset,info,suggestion=null){this.findingCount++;let{line,column}=offsetToLineCol(this.lineStarts,offset);this.onFinding({id,level,info,location:{start:offset,end:offset+(info.tag?.length??0),line,column},suggestion})}currentNode(){return this.openElements[this.openElements.length-1]??null}currentNamespace(){let top=this.currentNode();return top?top.ns:NS.html}push(name,ns,start){this.openElements.push({name,ns,start})}pop(){return this.openElements.pop()}hasInScope(target,scopeSet){for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.name===target&&f.ns===NS.html)return!0;if(f.ns===NS.html){if(scopeSet.has(f.name))return!1}else if(this.isScopeBoundary(f))return!1}return!1}isScopeBoundary(frame){if(frame.ns===NS.math)return MATHML_TEXT_INTEGRATION_POINT_NAMES.has(frame.name)||frame.name==="annotation-xml";if(frame.ns===NS.svg)return SVG_HTML_INTEGRATION_POINT_NAMES.has(frame.name);return!1}isIntegrationPoint(frame){if(frame.ns===NS.math){if(MATHML_TEXT_INTEGRATION_POINT_NAMES.has(frame.name))return!0;if(frame.name==="annotation-xml"&&frame.htmlIntegration)return!0;return!1}if(frame.ns===NS.svg)return SVG_HTML_INTEGRATION_POINT_NAMES.has(frame.name);return!1}hasInDefaultScope(target){return this.hasInScope(target,SCOPE_DEFAULT)}hasInButtonScope(target){return this.hasInScope(target,SCOPE_BUTTON)}hasInListItemScope(target){return this.hasInScope(target,SCOPE_LIST_ITEM)}hasInTableScope(target){return this.hasInScope(target,SCOPE_TABLE)}hasInSelectScope(target){for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns!==NS.html)return!1;if(f.name===target)return!0;if(f.name!=="optgroup"&&f.name!=="option")return!1}return!1}popUntilName(name){while(this.openElements.length){let f=this.openElements.pop();if(f.name===name)return f}return null}generateImpliedEndTags(except=null){let implied=new Set(["dd","dt","li","optgroup","option","p","rb","rp","rt","rtc"]);while(this.openElements.length){let top=this.currentNode();if(top.ns!==NS.html)break;if(!implied.has(top.name)||top.name===except)break;this.openElements.pop()}}isTransparentTag(name){for(let prefix of this.transparentTagPrefixes)if(name===prefix||name.startsWith(`${prefix}:`))return!0;return!1}handleStartTag(selfClosing,endIndex){let name=this.currentTagName,raw=this.currentTagRawName,start=this.currentTagStart,ns=this.currentNamespace();if(ns===NS.html){if(raw!==name)this.report(HTML_TAG_NAME_HAS_UPPERCASE,LEVEL_ERROR,start,{raw,lowercased:name},{kind:"rewrite",from:`<${raw}>`,to:`<${name}>`})}else if(ns===NS.svg){if(raw!==raw.toLowerCase()&&!this.svgCamelElements.has(raw))this.report(HTML_SVG_TAG_WILL_LOWERCASE,LEVEL_ERROR,start,{raw,lowercased:name},{kind:"rewrite",from:`<${raw}>`,to:`<${name}>`})}let targetNs=ns!==NS.html?ns:name==="svg"?NS.svg:name==="math"?NS.math:NS.html;if(targetNs===NS.svg)for(let a of this.currentAttrs){let canonical=SVG_ATTR_LOWERCASE_TO_CAMEL.get(a.name);if(canonical&&a.rawName!==canonical)this.report(HTML_SVG_ATTR_WILL_LOWERCASE,LEVEL_ERROR,a.nameStart,{raw:a.rawName,canonical},{kind:"rewrite",from:a.rawName,to:canonical})}else if(targetNs===NS.math)for(let a of this.currentAttrs){let canonical=MATHML_ATTR_LOWERCASE_TO_CAMEL.get(a.name);if(canonical&&a.rawName!==canonical)this.report(HTML_MATHML_ATTR_WILL_LOWERCASE,LEVEL_ERROR,a.nameStart,{raw:a.rawName,canonical},{kind:"rewrite",from:a.rawName,to:canonical})}if(this.isTransparentTag(name))return;let top=this.currentNode(),inForeign=ns!==NS.html&&!(top&&this.isIntegrationPoint(top));if(inForeign&&!this.shouldBreakoutFromForeign(name)){this.startTagInForeign(name,raw,selfClosing,start);return}if(inForeign&&this.shouldBreakoutFromForeign(name)){this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_WARN,start,{tag:raw,parent:this.currentNode()?.name??"(root)",mode:this.insertionMode,action:"foreign-breakout"});while(this.openElements.length&&this.currentNode()?.ns!==NS.html)this.openElements.pop()}this.dispatchStartTag(name,raw,selfClosing,start,endIndex)}shouldBreakoutFromForeign(name){if(FOREIGN_BREAKOUT_TAGS.has(name))return!0;if(name==="font")return this.hasAttr("color")||this.hasAttr("face")||this.hasAttr("size");return!1}startTagInForeign(name,raw,selfClosing,start){let ns=name==="svg"?NS.svg:name==="math"?NS.math:this.currentNamespace(),top=this.currentNode();if(top&&this.isIntegrationPoint(top)&&name!=="mglyph"&&name!=="malignmark"){this.dispatchStartTag(name,raw,selfClosing,start,start+raw.length);return}if(selfClosing)return;let frame={name,ns,start};if(ns===NS.math&&name==="annotation-xml"){let enc=(this.getAttr("encoding")??"").toLowerCase();if(enc==="text/html"||enc==="application/xhtml+xml")frame.htmlIntegration=!0}this.openElements.push(frame)}dispatchStartTag(name,raw,selfClosing,start,endIndex){switch(this.insertionMode){case MODES.inTemplate:return this.startInTemplate(name,raw,selfClosing,start,endIndex);case MODES.inBody:return this.startInBody(name,raw,selfClosing,start,endIndex);case MODES.inTable:return this.startInTable(name,raw,selfClosing,start,endIndex);case MODES.inCaption:return this.startInCaption(name,raw,selfClosing,start,endIndex);case MODES.inColumnGroup:return this.startInColumnGroup(name,raw,selfClosing,start,endIndex);case MODES.inTableBody:return this.startInTableBody(name,raw,selfClosing,start,endIndex);case MODES.inRow:return this.startInRow(name,raw,selfClosing,start,endIndex);case MODES.inCell:return this.startInCell(name,raw,selfClosing,start,endIndex);case MODES.inSelect:return this.startInSelect(name,raw,selfClosing,start,endIndex);case MODES.inSelectInTable:return this.startInSelectInTable(name,raw,selfClosing,start,endIndex)}}startInBody(name,raw,selfClosing,start,_endIndex){if(name==="html"||name==="head"||name==="body"||name==="frame"||name==="frameset"){this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_WARN,start,{tag:raw,mode:this.insertionMode,action:"ignored"});return}if(name==="address"||name==="article"||name==="aside"||name==="blockquote"||name==="center"||name==="details"||name==="dialog"||name==="dir"||name==="div"||name==="dl"||name==="fieldset"||name==="figcaption"||name==="figure"||name==="footer"||name==="header"||name==="hgroup"||name==="main"||name==="menu"||name==="nav"||name==="ol"||name==="p"||name==="search"||name==="section"||name==="summary"||name==="ul"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="h1"||name==="h2"||name==="h3"||name==="h4"||name==="h5"||name==="h6"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);let top=this.currentNode();if(top&&/^h[1-6]$/.test(top.name))this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:top.name,mode:this.insertionMode,action:"auto-close-implicit"}),this.openElements.pop();this.push(raw,NS.html,start);return}if(name==="pre"||name==="listing"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start),this.framesetOk=!1;return}if(name==="form"){if(this.openElementsHas("form")&&!this.openElementsHas("template")){this.report(HTML_DUPLICATE_FORM,LEVEL_ERROR,start,{tag:raw,mode:this.insertionMode},{kind:"remove",what:"the inner <form>"});return}if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="li"){this.framesetOk=!1;for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns!==NS.html)break;if(f.name==="li"){this.generateImpliedEndTags("li");while(this.openElements.length)if(this.openElements.pop().name==="li")break;break}if(SPECIAL_ELEMENTS.has(f.name)&&f.name!=="address"&&f.name!=="div"&&f.name!=="p")break}if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="dd"||name==="dt"){this.framesetOk=!1;for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns!==NS.html)break;if(f.name==="dd"||f.name==="dt"){this.generateImpliedEndTags(f.name);while(this.openElements.length)if(this.openElements.pop().name===f.name)break;break}if(SPECIAL_ELEMENTS.has(f.name)&&f.name!=="address"&&f.name!=="div"&&f.name!=="p")break}if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="plaintext"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="button"){if(this.hasInDefaultScope("button"))this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"button",mode:this.insertionMode,action:"auto-close-implicit"}),this.generateImpliedEndTags(),this.popUntilName("button");this.push(raw,NS.html,start),this.framesetOk=!1;return}if(name==="a"){if(this.activeFormattingHas("a"))this.report(HTML_NESTED_INTERACTIVE,LEVEL_WARN,start,{tag:raw,mode:this.insertionMode}),this.runAdoptionAgency("a");this.push(raw,NS.html,start),this.activeFormatting.push(this.currentNode());return}if(FORMATTING_ELEMENTS.has(name)){this.push(raw,NS.html,start),this.activeFormatting.push(this.currentNode());return}if(name==="nobr"){if(this.activeFormattingHas("nobr"))this.report(HTML_NESTED_INTERACTIVE,LEVEL_WARN,start,{tag:raw,mode:this.insertionMode}),this.runAdoptionAgency("nobr");this.push(raw,NS.html,start),this.activeFormatting.push(this.currentNode());return}if(name==="table"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start),this.framesetOk=!1,this.insertionMode=MODES.inTable;return}if(name==="area"||name==="br"||name==="embed"||name==="img"||name==="keygen"||name==="wbr"||name==="input"||name==="param"||name==="source"||name==="track"||name==="hr"||name==="meta"||name==="link"||name==="col"||name==="base"){this.framesetOk=!1;return}if(name==="select"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start),this.framesetOk=!1,this.insertionMode=MODES.inSelect;return}if(name==="option"||name==="optgroup"){if(this.currentNode()?.name==="option")this.openElements.pop();this.push(raw,NS.html,start);return}if(name==="textarea"||name==="title"||RAW_TEXT_ELEMENTS.has(name)){this.push(raw,NS.html,start);return}if(name==="math"||name==="svg"){this.push(raw,name==="svg"?NS.svg:NS.math,start),this.framesetOk=!1;return}if(name==="caption"||name==="col"||name==="colgroup"||name==="frame"||name==="tbody"||name==="td"||name==="tfoot"||name==="th"||name==="thead"||name==="tr"){this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:this.currentNode()?.name??"(root)",mode:this.insertionMode,action:"ignored"});return}if(selfClosing)return;this.push(raw,NS.html,start)}openElementsHas(name){for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns===NS.html&&f.name===name)return!0}return!1}activeFormattingHas(name){for(let i=this.activeFormatting.length-1;i>=0;i--){let e=this.activeFormatting[i];if(e===null)return!1;if(e.name===name)return!0}return!1}runAdoptionAgency(name){for(let i=this.activeFormatting.length-1;i>=0;i--){let e=this.activeFormatting[i];if(e===null)break;if(e.name===name){let idx=this.openElements.indexOf(e);if(idx>=0)this.openElements.splice(idx,1);return}}}implicitlyClose(name,_start,_newTagRaw){while(this.openElements.length)if(this.openElements.pop().name===name)break}startInTemplate(name,raw,selfClosing,start,endIndex){let next;if(name==="caption"||name==="colgroup"||name==="tbody"||name==="tfoot"||name==="thead")next=MODES.inTable;else if(name==="col")next=MODES.inColumnGroup;else if(name==="tr")next=MODES.inTableBody;else if(name==="td"||name==="th")next=MODES.inRow;else return this.popTemplateMode(),this.pushTemplateMode(MODES.inBody),this.insertionMode=MODES.inBody,this.startInBody(name,raw,selfClosing,start,endIndex);return this.popTemplateMode(),this.pushTemplateMode(next),this.insertionMode=next,this.dispatchStartTag(name,raw,selfClosing,start,endIndex)}popTemplateMode(){if(this.templateInsertionModes.length)this.templateInsertionModes.pop()}pushTemplateMode(mode){this.templateInsertionModes.push(mode)}startInTable(name,raw,selfClosing,start,endIndex){if(name==="caption"){this.clearStackBackToTable(),this.activeFormatting.push(null),this.push(raw,NS.html,start),this.insertionMode=MODES.inCaption;return}if(name==="colgroup"){this.clearStackBackToTable(),this.push(raw,NS.html,start),this.insertionMode=MODES.inColumnGroup;return}if(name==="col")return this.clearStackBackToTable(),this.push("colgroup",NS.html,start),this.insertionMode=MODES.inColumnGroup,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);if(name==="tbody"||name==="thead"||name==="tfoot"){this.clearStackBackToTable(),this.push(raw,NS.html,start),this.insertionMode=MODES.inTableBody;return}if(name==="td"||name==="th"||name==="tr")return this.clearStackBackToTable(),this.push("tbody",NS.html,start),this.insertionMode=MODES.inTableBody,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);if(name==="table"){if(this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"table",mode:this.insertionMode,action:"auto-close-implicit"}),this.hasInTableScope("table"))return this.popUntilName("table"),this.resetInsertionModeAppropriately(),this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}if(name==="style"||name==="script"||name==="template")return this.startInBody(name,raw,selfClosing,start,endIndex);if(name==="input"){if((this.getAttr("type")??"").toLowerCase()==="hidden")return;this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_WARN,start,{tag:raw,parent:"table",mode:this.insertionMode,action:"foster-parent"});return}if(name==="form"){this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"table",mode:this.insertionMode,action:"ignored"});return}return this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:this.currentNode()?.name??"table",mode:this.insertionMode,action:"foster-parent"}),this.startInBody(name,raw,selfClosing,start,endIndex)}clearStackBackToTable(){while(this.openElements.length){let top=this.currentNode();if(!top)break;if(top.name==="table"||top.name==="template")break;this.openElements.pop()}}startInCaption(name,raw,selfClosing,start,endIndex){if(name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="td"||name==="tfoot"||name==="th"||name==="thead"||name==="tr"){if(this.hasInTableScope("caption"))return this.generateImpliedEndTags(),this.popUntilName("caption"),this.clearActiveFormattingToMarker(),this.insertionMode=MODES.inTable,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}return this.startInBody(name,raw,selfClosing,start,endIndex)}clearActiveFormattingToMarker(){while(this.activeFormatting.length)if(this.activeFormatting.pop()===null)return}startInColumnGroup(name,raw,selfClosing,start,endIndex){if(name==="col")return;if(name==="template")return this.startInBody(name,raw,selfClosing,start,endIndex);if(this.currentNode()?.name==="colgroup")return this.openElements.pop(),this.insertionMode=MODES.inTable,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"colgroup",mode:this.insertionMode,action:"ignored"})}startInTableBody(name,raw,selfClosing,start,endIndex){if(name==="tr"){this.clearStackBackToTableBody(),this.push(raw,NS.html,start),this.insertionMode=MODES.inRow;return}if(TABLE_BODY_CELL_TAGS.has(name))return this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_WARN,start,{tag:raw,parent:this.currentNode()?.name??"tbody",mode:this.insertionMode,action:"auto-close-implicit"}),this.clearStackBackToTableBody(),this.push("tr",NS.html,start),this.insertionMode=MODES.inRow,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);if(name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="tfoot"||name==="thead"){if(this.hasInTableScope("tbody")||this.hasInTableScope("thead")||this.hasInTableScope("tfoot"))return this.clearStackBackToTableBody(),this.openElements.pop(),this.insertionMode=MODES.inTable,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}return this.startInTable(name,raw,selfClosing,start,endIndex)}clearStackBackToTableBody(){while(this.openElements.length){let top=this.currentNode();if(!top)break;if(top.name==="tbody"||top.name==="thead"||top.name==="tfoot"||top.name==="template"||top.name==="table")break;this.openElements.pop()}}startInRow(name,raw,selfClosing,start,endIndex){if(TABLE_BODY_CELL_TAGS.has(name)){this.clearStackBackToTableRow(),this.push(raw,NS.html,start),this.insertionMode=MODES.inCell,this.activeFormatting.push(null);return}if(name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="tfoot"||name==="thead"||name==="tr"){if(this.hasInTableScope("tr"))return this.clearStackBackToTableRow(),this.openElements.pop(),this.insertionMode=MODES.inTableBody,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}return this.startInTable(name,raw,selfClosing,start,endIndex)}clearStackBackToTableRow(){while(this.openElements.length){let top=this.currentNode();if(!top)break;if(top.name==="tr"||top.name==="template"||top.name==="table")break;this.openElements.pop()}}startInCell(name,raw,selfClosing,start,endIndex){if(name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="td"||name==="tfoot"||name==="th"||name==="thead"||name==="tr"){if(this.hasInTableScope("td")||this.hasInTableScope("th"))return this.closeCell(),this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}return this.startInBody(name,raw,selfClosing,start,endIndex)}closeCell(){this.generateImpliedEndTags();while(this.openElements.length){let popped=this.openElements.pop();if(popped.name==="td"||popped.name==="th")break}this.clearActiveFormattingToMarker(),this.insertionMode=MODES.inRow}startInSelect(name,raw,_selfClosing,start,_endIndex){if(name==="option"){if(this.currentNode()?.name==="option")this.openElements.pop();this.push(raw,NS.html,start);return}if(name==="optgroup"){if(this.currentNode()?.name==="option")this.openElements.pop();if(this.currentNode()?.name==="optgroup")this.openElements.pop();this.push(raw,NS.html,start);return}if(name==="hr")return;if(SELECT_BREAKOUT_TAGS.has(name)){if(this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"select",mode:this.insertionMode,action:"auto-close-implicit"}),this.hasInSelectScope("select"))this.popUntilName("select"),this.resetInsertionModeAppropriately();if(name==="select")return;return this.dispatchStartTag(name,raw,!1,start,_endIndex)}if(name==="script"||name==="template")return this.startInBody(name,raw,!1,start,_endIndex);this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"select",mode:this.insertionMode,action:"ignored"})}startInSelectInTable(name,raw,selfClosing,start,endIndex){if(name==="caption"||name==="table"||name==="tbody"||name==="tfoot"||name==="thead"||name==="tr"||name==="td"||name==="th")return this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"select",mode:this.insertionMode,action:"auto-close-implicit"}),this.popUntilName("select"),this.resetInsertionModeAppropriately(),this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return this.startInSelect(name,raw,selfClosing,start,endIndex)}resetInsertionModeAppropriately(){for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns!==NS.html)continue;let last=i===0;switch(f.name){case"select":this.insertionMode=MODES.inSelect;return;case"td":case"th":if(!last){this.insertionMode=MODES.inCell;return}break;case"tr":this.insertionMode=MODES.inRow;return;case"tbody":case"thead":case"tfoot":this.insertionMode=MODES.inTableBody;return;case"caption":this.insertionMode=MODES.inCaption;return;case"colgroup":this.insertionMode=MODES.inColumnGroup;return;case"table":this.insertionMode=MODES.inTable;return;case"template":this.insertionMode=this.templateInsertionModes[this.templateInsertionModes.length-1]??MODES.inBody;return;default:break}}this.insertionMode=MODES.inBody}handleEndTag(name,start){if(this.isTransparentTag(name))return;if(this.currentNamespace()!==NS.html){let stackIdx=this.openElements.length-1,first=!0;while(stackIdx>0){let f=this.openElements[stackIdx];if(!first&&f.ns===NS.html)break;if(f.ns!==NS.html&&f.name.toLowerCase()===name){this.openElements.length=stackIdx;return}if(first)this.report(HTML_UNEXPECTED_END_TAG,LEVEL_WARN,start,{tag:name,mode:this.insertionMode}),first=!1;stackIdx--}}if(VOID_ELEMENTS.has(name)){this.report(HTML_VOID_ELEMENT_HAS_CLOSE_TAG,LEVEL_WARN,start,{tag:name,mode:this.insertionMode},{kind:"remove",what:`the </${name}>`});return}if(FORMATTING_ELEMENTS.has(name)){let top=this.currentNode();if(top&&top.ns===NS.html&&top.name===name){this.openElements.pop(),this.removeFromActiveFormattingByRef(top);return}if(this.activeFormattingHas(name)||this.openElementsHas(name)){this.report(HTML_MISNESTED_FORMATTING,LEVEL_WARN,start,{tag:name,mode:this.insertionMode}),this.runAdoptionAgency(name);return}this.report(HTML_UNEXPECTED_END_TAG,LEVEL_WARN,start,{tag:name,mode:this.insertionMode});return}let endIsTableStructural=TABLE_SCOPE_TAGS.has(name);for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns===NS.html&&f.name===name){for(let j=this.openElements.length-1;j>i;j--){let popped=this.openElements[j];if(popped.ns===NS.html&&popped.name!==name&&!IMPLIED_END_TAGS.has(popped.name)&&!(endIsTableStructural&&TABLE_SCOPE_TAGS.has(popped.name))){this.report(HTML_UNCLOSED_BEFORE_END,LEVEL_WARN,start,{tag:name,unclosed:popped.name,mode:this.insertionMode});break}}if(this.openElements.length=i,TABLE_SCOPE_TAGS.has(name)||name==="select"||name==="template")this.resetInsertionModeAppropriately();return}if(f.ns===NS.html&&SPECIAL_ELEMENTS.has(f.name)&&!IMPLIED_END_TAGS.has(f.name)&&!(endIsTableStructural&&TABLE_SCOPE_TAGS.has(f.name))){this.report(HTML_UNEXPECTED_END_TAG,LEVEL_WARN,start,{tag:name,mode:this.insertionMode});return}}}removeFromActiveFormattingByRef(ref){let idx=this.activeFormatting.indexOf(ref);if(idx>=0)this.activeFormatting.splice(idx,1)}handleText(start,end){if(this.insertionMode===MODES.inTable||this.insertionMode===MODES.inTableBody||this.insertionMode===MODES.inRow){let slice=this.html.slice(start,end);if(/\S/.test(slice))this.report(HTML_TEXT_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{mode:this.insertionMode,snippet:slice.length>40?`${slice.slice(0,40)}…`:slice});return}if(this.insertionMode===MODES.inColumnGroup){let slice=this.html.slice(start,end);if(/\S/.test(slice)){if(this.currentNode()?.name==="colgroup")return this.openElements.pop(),this.insertionMode=MODES.inTable,this.handleText(start,end)}return}if(this.insertionMode===MODES.inSelect||this.insertionMode===MODES.inSelectInTable)return}}function computeLineStarts(html){let arr=[0];for(let i=0;i<html.length;i++)if(html.charCodeAt(i)===10)arr.push(i+1);return arr}function offsetToLineCol(lineStarts,offset){let lo=0,hi=lineStarts.length-1;while(lo<hi){let mid=lo+hi+1>>>1;if(lineStarts[mid]<=offset)lo=mid;else hi=mid-1}return{line:lo+1,column:offset-lineStarts[lo]+1}}function editDistance(a,b){if(a===b)return 0;let la=a.length,lb=b.length;if(la===0)return lb;if(lb===0)return la;let prev2=Array(lb+1),prev1=Array(lb+1),curr=Array(lb+1);for(let j=0;j<=lb;j++)prev1[j]=j;for(let i=1;i<=la;i++){curr[0]=i;let ca=a.charCodeAt(i-1);for(let j=1;j<=lb;j++){let cb=b.charCodeAt(j-1),cost=ca===cb?0:1,v=Math.min(curr[j-1]+1,prev1[j]+1,prev1[j-1]+cost);if(i>1&&j>1&&ca===b.charCodeAt(j-2)&&a.charCodeAt(i-2)===cb)v=Math.min(v,prev2[j-2]+1);curr[j]=v}for(let j=0;j<=lb;j++)prev2[j]=prev1[j],prev1[j]=curr[j]}return prev1[lb]}function closestName(name,candidates,maxDistance=2){if(!name)return null;let lower=name.toLowerCase(),best=null,bestDist=maxDistance+1;for(let cand of candidates){if(cand===name)return null;if(cand.toLowerCase()===lower)return cand;let d=editDistance(name,cand);if(d<bestDist)best=cand,bestDist=d}return bestDist<=maxDistance?best:null}var KNOWN_COMPONENT_SPEC_KEYS=new Set("name view style commonStyle globalStyle input receive bubble response alter on views dynamic fields methods statics".split(" ")),EMPTY_SET2=new Set,KNOWN_DIRECTIVE_NAMES=new Set(["dangerouslysetinnerhtml","slot","push-view","text","show","hide","each","enrich-with","when","loop-with","then","else"]),ALT_HANDLER_NOT_DEFINED="ALT_HANDLER_NOT_DEFINED",ALT_HANDLER_NOT_REFERENCED="ALT_HANDLER_NOT_REFERENCED",DYN_VAL_NOT_DEFINED="DYN_VAL_NOT_DEFINED",DYN_ALIAS_NOT_REFERENCED="DYN_ALIAS_NOT_REFERENCED",RENDER_IT_OUTSIDE_OF_LOOP="RENDER_IT_OUTSIDE_OF_LOOP",UNKNOWN_EVENT_MODIFIER="UNKNOWN_EVENT_MODIFIER",UNKNOWN_HANDLER_ARG_NAME="UNKNOWN_HANDLER_ARG_NAME",INPUT_HANDLER_NOT_IMPLEMENTED="INPUT_HANDLER_NOT_IMPLEMENTED",INPUT_HANDLER_NOT_REFERENCED="INPUT_HANDLER_NOT_REFERENCED",INPUT_HANDLER_METHOD_NOT_IMPLEMENTED="INPUT_HANDLER_METHOD_NOT_IMPLEMENTED",INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD="INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD",INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER="INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER",FIELD_VAL_NOT_DEFINED="FIELD_VAL_NOT_DEFINED",FIELD_VAL_IS_METHOD="FIELD_VAL_IS_METHOD",METHOD_VAL_NOT_DEFINED="METHOD_VAL_NOT_DEFINED",METHOD_VAL_IS_FIELD="METHOD_VAL_IS_FIELD",DUPLICATE_ATTR_DEFINITION="DUPLICATE_ATTR_DEFINITION",IF_NO_BRANCH_SET="IF_NO_BRANCH_SET",UNKNOWN_REQUEST_NAME="UNKNOWN_REQUEST_NAME",UNKNOWN_COMPONENT_NAME="UNKNOWN_COMPONENT_NAME",UNKNOWN_MACRO_ARG="UNKNOWN_MACRO_ARG",UNKNOWN_DIRECTIVE="UNKNOWN_DIRECTIVE",UNKNOWN_X_OP="UNKNOWN_X_OP",UNKNOWN_X_ATTR="UNKNOWN_X_ATTR",MAYBE_DROP_AT_PREFIX="MAYBE_DROP_AT_PREFIX",BAD_VALUE="BAD_VALUE",UNSUPPORTED_EXPR_SYNTAX="UNSUPPORTED_EXPR_SYNTAX",REDUNDANT_TEMPLATE_STRING="REDUNDANT_TEMPLATE_STRING",PLACEHOLDERLESS_TEMPLATE_STRING="PLACEHOLDERLESS_TEMPLATE_STRING",UNKNOWN_COMPONENT_SPEC_KEY="UNKNOWN_COMPONENT_SPEC_KEY",PARSE_ISSUE_KIND_TO_LINT_ID={"unknown-directive":UNKNOWN_DIRECTIVE,"unknown-x-op":UNKNOWN_X_OP,"unknown-x-attr":UNKNOWN_X_ATTR,"bad-value":BAD_VALUE},X_KNOWN_OP_NAMES=new Set(["slot","text","render","render-it","render-each","show","hide"]),X_KNOWN_ATTR_NAMES=new Set(["as","when","loop-with","show","hide"]),AT_PREFIX_HINT_KNOWN_BY_KIND={"unknown-x-op":X_KNOWN_OP_NAMES,"unknown-x-attr":X_KNOWN_ATTR_NAMES},LEVEL_WARN2="warn",LEVEL_ERROR2="error",LEVEL_HINT="hint",PARSE_ISSUE_KIND_TO_KNOWN_NAMES={"unknown-directive":KNOWN_DIRECTIVE_NAMES,"unknown-x-op":X_KNOWN_OP_NAMES,"unknown-x-attr":X_KNOWN_ATTR_NAMES};function collectProtoMethodNames(proto){let out=[],cursor=proto;while(cursor&&cursor!==Object.prototype){for(let key of Object.getOwnPropertyNames(cursor)){if(key==="constructor")continue;out.push(key)}cursor=Object.getPrototypeOf(cursor)}return out}function scopeKeysAlong(scope,mapKey){let out=[];for(let cursor=scope;cursor;cursor=cursor.parent){let map=cursor[mapKey];if(!map)continue;for(let key of Object.keys(map))out.push(key)}return out}function replaceNameSuggestion(name,candidates){let close=closestName(name,candidates);return close?{kind:"replace-name",from:name,to:close}:null}function classifyBadValue(value){if(typeof value!=="string")return null;let s=value.trim();if(s==="")return null;if(/\{[^}]*\}/.test(s)&&!s.startsWith("$'"))return"legacy-template";if(/\s\?\s.+\s:\s/.test(s))return"ternary";if(/===|!==|==|!=|<=|>=|\s<\s|\s>\s/.test(s))return"comparison";if(/&&|\|\|/.test(s))return"logical";if(/^[.$][A-Za-z_]\w*\s+\S/.test(s))return"call-with-args";return null}var UNSUPPORTED_EXPR_GUIDANCE={"legacy-template":"Unquoted {...} string templates are no longer supported. Wrap the value in $'...', e.g. $'flex {.color}'.",ternary:"Ternary expressions aren't supported in dynamic attributes. Define a method or computed field on the component that returns the value, then reference it as '$methodName'.",comparison:"Comparisons aren't supported in dynamic attributes. Define a method like 'isFooSelected' that returns the boolean, then reference it as '$isFooSelected'.",logical:"Logical operators aren't supported in dynamic attributes. Combine the conditions in a method on the component and reference it as '$methodName'.","call-with-args":"Method calls with arguments aren't supported here. Reference a no-arg method ('$methodName') and read what you need from component state, or split into per-case methods."};function checkComponent(Comp,lx=new LintContext,{wellKnownExtras=EMPTY_SET2}={}){return lx.push({componentName:Comp.name},()=>{checkUnknownSpecKeys(lx,Comp,wellKnownExtras);let referencedAlters=new Set,referencedInputs=new Set,referencedDynamics=new Set;checkEventHandlersHaveImpls(lx,Comp,referencedInputs),checkConsistentAttrs(lx,Comp,referencedAlters,referencedDynamics);for(let name in Comp.views)lx.push({viewName:name},()=>checkView(lx,Comp.views[name],Comp,referencedAlters,referencedDynamics));return checkUnreferencedAlterHandlers(lx,Comp,referencedAlters),checkUnreferencedInputHandlers(lx,Comp,referencedInputs),checkUnreferencedDynamics(lx,Comp,referencedDynamics),lx})}function checkView(lx,view,Comp,referencedAlters,referencedDynamics){checkParseIssues(lx,view),checkRenderItInLoop(lx,view),checkEventModifiers(lx,view),checkKnownHandlerNames(lx,view,Comp,referencedAlters,referencedDynamics),checkMacroCallArgs(lx,view,Comp),checkHtmlStructure(lx,view)}var HTML_LINT_OPTS={fragmentContext:"template",transparentTagPrefixes:["x"]};function checkHtmlStructure(lx,view){if(typeof view.rawView!=="string"||!view.rawView)return;lintHtml(view.rawView,(f)=>lx.report(f.id,{...f.info,location:f.location},f.level,f.suggestion??null),HTML_LINT_OPTS)}function checkParseIssues(lx,view){let issues=view.ctx.parseIssues;if(!issues)return;for(let{kind,info}of issues){let id=PARSE_ISSUE_KIND_TO_LINT_ID[kind];if(!id)continue;if(kind==="bad-value"){let detected=classifyBadValue(info.value);if(detected){lx.error(UNSUPPORTED_EXPR_SYNTAX,{...info,detected},{kind:"rephrase",from:info.value,text:UNSUPPORTED_EXPR_GUIDANCE[detected]});continue}}let atPrefixKnown=AT_PREFIX_HINT_KNOWN_BY_KIND[kind],isAtPrefixedTypo=atPrefixKnown&&info.name?.startsWith("@")&&atPrefixKnown.has(info.name.slice(1)),suggestion=null;if(isAtPrefixedTypo)suggestion={kind:"drop-prefix",from:info.name,to:info.name.slice(1)};else{let candidates=PARSE_ISSUE_KIND_TO_KNOWN_NAMES[kind];if(candidates)suggestion=replaceNameSuggestion(info.name,candidates)}if(lx.error(id,info,suggestion),isAtPrefixedTypo)lx.hint(MAYBE_DROP_AT_PREFIX,{...info,suggestion:info.name.slice(1)},{kind:"drop-prefix",from:info.name,to:info.name.slice(1)})}}function checkMacroCallArgs(lx,view,Comp){let{scope}=Comp;for(let macroNode of view.ctx.macroNodes){let macro=scope.lookupMacro(macroNode.name);if(macro===null)continue;let{defaults}=macro;for(let argName in macroNode.attrs)if(!(argName in defaults))lx.error(UNKNOWN_MACRO_ARG,{name:argName,macroName:macroNode.name,tag:`x:${macroNode.name}`},replaceNameSuggestion(argName,Object.keys(defaults)))}}function checkRenderItInLoop(lx,view){let hasRenderIt=!1;for(let node of view.ctx.nodes)if(node.constructor.name==="RenderItNode"){hasRenderIt=!0;break}if(!hasRenderIt)return;walkForRenderIt(lx,view.anode,0)}function walkForRenderIt(lx,node,loopDepth){if(node===null||node===void 0)return;switch(node.constructor.name){case"RenderItNode":if(loopDepth===0)lx.error(RENDER_IT_OUTSIDE_OF_LOOP,{node},{kind:"wrap",from:"<x render-it>",to:"<x render-each>"});return;case"EachNode":walkForRenderIt(lx,node.node,loopDepth+1);return;case"ShowNode":case"HideNode":case"ScopeNode":case"SlotNode":case"PushViewNameNode":case"MacroNode":case"RenderOnceNode":walkForRenderIt(lx,node.node,loopDepth);return;case"DomNode":case"FragmentNode":for(let child of node.childs)walkForRenderIt(lx,child,loopDepth);return;default:return}}var NO_WRAPPERS={};function checkEventModifiers(lx,view){for(let event of view.ctx.events)for(let handler of event.handlers){let{name,modifiers}=handler,modWrappers=MOD_WRAPPERS_BY_EVENT[name]??NO_WRAPPERS;for(let modifier of modifiers)if(modWrappers[modifier]===void 0){let close=closestName(modifier,Object.keys(modWrappers));lx.error(UNKNOWN_EVENT_MODIFIER,{name,modifier,handler,event,originAttr:`@on.${name}+${modifiers.join("+")}`},close?{kind:"replace-name",from:`+${modifier}`,to:`+${close}`}:null)}}}var KNOWN_HANDLER_NAMES=new Set(["value","valueAsInt","valueAsFloat","target","event","isAlt","isShift","isCtrl","isCmd","key","keyCode","isUpKey","isDownKey","isSend","isCancel","isTabKey","ctx","dragInfo"]);function isKnownHandlerName(name){return KNOWN_HANDLER_NAMES.has(name)}function checkKnownHandlerNames(lx,view,Comp,referencedAlters,referencedDynamics){let env=mkAttrValEnv(Comp,referencedAlters,referencedDynamics);for(let event of view.ctx.events)for(let handler of event.handlers){let{args,handlerVal}=handler.handlerCall,handlerName=handlerVal?.name,eventName=handler.name,errCtx={eventName,handlerName,originAttr:`@on.${eventName}`};for(let i=0;i<args.length;i++)checkConsistentAttrVal(lx,args[i],env,!1,{...errCtx,argIndex:i})}}function mkAttrValEnv(Comp,referencedAlters,referencedDynamics){let{scope,alter,dynamic,Class}=Comp,{prototype:proto}=Class,{fields}=Class.getMetaClass();return{fields,proto,scope,alter,referencedAlters,dynamicMap:dynamic,referencedDynamics}}function checkEventHandlersHaveImpls(lx,Comp,referencedInputs){let{input,views,Class}=Comp,{prototype:proto}=Class;for(let viewName in views)lx.push({viewName},()=>{let view=views[viewName];for(let event of view.ctx.events)for(let handler of event.handlers){let{handlerVal}=handler.handlerCall,hvName=handlerVal?.constructor.name,eventName=handler.name,originAttr=`@on.${eventName}`;if(hvName==="HandlerNameVal"){referencedInputs?.add(handlerVal.name);let{name}=handlerVal;if(input[name]===void 0){let isMethodFix=proto[name]!==void 0;if(lx.error(INPUT_HANDLER_NOT_IMPLEMENTED,{name,handler,event,eventName,originAttr},isMethodFix?{kind:"add-prefix",from:name,to:`$${name}`}:replaceNameSuggestion(name,Object.keys(input))),isMethodFix)lx.hint(INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER,{name,handler,event,eventName,originAttr},{kind:"add-prefix",from:name,to:`$${name}`})}}else if(hvName==="MethodVal"){referencedInputs?.add(handlerVal.name);let{name}=handlerVal;if(proto[name]===void 0){let isInputFix=input[name]!==void 0;if(lx.error(INPUT_HANDLER_METHOD_NOT_IMPLEMENTED,{name,handler,event,eventName,originAttr},isInputFix?{kind:"drop-prefix",from:`$${name}`,to:name}:replaceNameSuggestion(name,collectProtoMethodNames(proto))),isInputFix)lx.hint(INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD,{name,handler,event,eventName,originAttr},{kind:"drop-prefix",from:`$${name}`,to:name})}}}})}function checkConsistentAttrVal(lx,val,env,skipNameVal=!1,errCtx=null){let{fields,proto,scope,alter}=env,valName=val?.constructor.name;if(valName==="FieldVal"){let{name}=val;if(fields[name]===void 0)if(proto[name]!==void 0)lx.error(FIELD_VAL_IS_METHOD,{...errCtx,val,name},{kind:"rewrite",from:`.${name}`,to:`$${name}`});else lx.error(FIELD_VAL_NOT_DEFINED,{...errCtx,val,name},replaceNameSuggestion(name,Object.keys(fields)))}else if(valName==="MethodVal"){let{name}=val;if(proto[name]===void 0)if(fields[name]!==void 0)lx.error(METHOD_VAL_IS_FIELD,{...errCtx,val,name},{kind:"rewrite",from:`$${name}`,to:`.${name}`});else lx.error(METHOD_VAL_NOT_DEFINED,{...errCtx,val,name},replaceNameSuggestion(name,collectProtoMethodNames(proto)))}else if(valName==="SeqAccessVal")checkConsistentAttrVal(lx,val.seqVal,env,skipNameVal,errCtx),checkConsistentAttrVal(lx,val.keyVal,env,skipNameVal,errCtx);else if(valName==="RequestVal"){if(scope.lookupRequest(val.name)===null)lx.error(UNKNOWN_REQUEST_NAME,{...errCtx,name:val.name},replaceNameSuggestion(val.name,scopeKeysAlong(scope,"reqsByName")))}else if(valName==="TypeVal"){if(scope.lookupComponent(val.name)===null)lx.error(UNKNOWN_COMPONENT_NAME,{...errCtx,name:val.name},replaceNameSuggestion(val.name,scopeKeysAlong(scope,"byName")))}else if(valName==="NameVal"){if(!skipNameVal&&!isKnownHandlerName(val.name))lx.error(UNKNOWN_HANDLER_ARG_NAME,{...errCtx,name:val.name},replaceNameSuggestion(val.name,KNOWN_HANDLER_NAMES))}else if(valName==="StrTplVal"){let vs=val.vals,literal=val.toLiteralSource();if(literal!==null)lx.hint(PLACEHOLDERLESS_TEMPLATE_STRING,{...errCtx,literal},{kind:"rewrite",from:`$${literal}`,to:literal});else if(vs.length===1){let simpler=String(vs[0]);lx.warn(REDUNDANT_TEMPLATE_STRING,{...errCtx,simpler},{kind:"rewrite",from:`$'{${simpler}}'`,to:simpler})}for(let subVal of vs)checkConsistentAttrVal(lx,subVal,env,skipNameVal,errCtx)}else if(valName==="HandlerNameVal"){if(env.referencedAlters?.add(val.name),alter[val.name]===void 0)lx.error(ALT_HANDLER_NOT_DEFINED,{...errCtx,name:val.name},replaceNameSuggestion(val.name,Object.keys(alter)))}else if(valName==="PredicateVal")for(let arg of val.args)checkConsistentAttrVal(lx,arg,env,skipNameVal,errCtx);else if(valName==="DynVal"){if(env.referencedDynamics?.add(val.name),env.dynamicMap[val.name]===void 0)lx.error(DYN_VAL_NOT_DEFINED,{...errCtx,name:val.name},replaceNameSuggestion(val.name,Object.keys(env.dynamicMap)))}else if(valName!=="ConstVal"&&valName!=="BindVal")console.log(val)}var NODE_KIND_TO_CTX={RenderTextNode:{originAttr:"<x text>"},RenderNode:{originAttr:"<x render>"},RenderItNode:{originAttr:"<x render-it>"},RenderEachNode:{originAttr:"<x render-each>"},ShowNode:{originAttr:"<x show>"},HideNode:{originAttr:"<x hide>"},PushViewNameNode:{originAttr:"<x push-view>"}};function nodeCtxForNode(nodeKind){return NODE_KIND_TO_CTX[nodeKind]??null}function attrSourceLabel(attr){let cn=attr.constructor.name;if(cn==="ConstAttr")return"literal";if(cn==="IfAttr")return`@if.${attr.name}`;if(cn==="RawHtmlAttr")return"@dangerouslysetinnerhtml";return`:${attr.name}`}function attrOriginAttr(attr){let cn=attr.constructor.name;if(cn==="IfAttr")return`@if.${attr.name}`;if(cn==="RawHtmlAttr")return"@dangerouslysetinnerhtml";return`:${attr.name}`}function checkConsistentAttrs(lx,Comp,referencedAlters,referencedDynamics){let{views}=Comp,env=mkAttrValEnv(Comp,referencedAlters,referencedDynamics);for(let viewName in views)lx.push({viewName},()=>{let view=views[viewName];for(let entry of view.ctx.attrs){let{attrs,wrapperAttrs,textChild,isMacroCall,tag}=entry;if(attrs?.constructor.name==="DynAttrs"){let sourcesByName=new Map;for(let attr of attrs.items){let name=attr?.name;if(name!==void 0&&name!=="data-eid"){let sources=sourcesByName.get(name),label=attrSourceLabel(attr);if(sources)sources.push(label);else sourcesByName.set(name,[label])}if(attr?.constructor.name==="IfAttr"){if(!attr.anyBranchIsSet)lx.error(IF_NO_BRANCH_SET,{attr:attr.name,tag});let branches=[["@if",attr.condVal],["@then",attr.thenVal],["@else",attr.elseVal]];for(let[branch,subVal]of branches)checkConsistentAttrVal(lx,subVal,env,isMacroCall,{tag,originAttr:`@if.${attr.name}`,branch})}else if(attr?.val!==void 0)checkConsistentAttrVal(lx,attr.val,env,isMacroCall,{tag,originAttr:attrOriginAttr(attr)})}for(let[name,sources]of sourcesByName)if(sources.length>1)lx.error(DUPLICATE_ATTR_DEFINITION,{name,sources,tag})}if(wrapperAttrs!==null)for(let w of wrapperAttrs)if(w.name==="each"){if(w.whenVal)checkConsistentAttrVal(lx,w.whenVal,env,!1,{tag,originAttr:"@when"});if(w.enrichWithVal)checkConsistentAttrVal(lx,w.enrichWithVal,env,!1,{tag,originAttr:"@enrich-with"});if(w.loopWithVal)checkConsistentAttrVal(lx,w.loopWithVal,env,!1,{tag,originAttr:"@loop-with"})}else{let originAttr=w.name==="scope"?"@enrich-with":`@${w.name}`;checkConsistentAttrVal(lx,w.val,env,!1,{tag,originAttr})}if(textChild)checkConsistentAttrVal(lx,textChild,env,!1,{tag,originAttr:"@text"})}for(let node of view.ctx.nodes){let nodeKind=node.constructor.name;if(nodeKind==="ScopeNode")continue;let baseCtx=nodeCtxForNode(nodeKind);if(node.val)checkConsistentAttrVal(lx,node.val,env,!1,baseCtx);if(nodeKind==="RenderEachNode"){let iter=node.iterInfo;if(iter.whenVal)checkConsistentAttrVal(lx,iter.whenVal,env,!1,{originAttr:"<x render-each when>"});if(iter.loopWithVal)checkConsistentAttrVal(lx,iter.loopWithVal,env,!1,{originAttr:"<x render-each loop-with>"})}}})}function checkUnknownSpecKeys(lx,Comp,wellKnownExtras){let extra=Comp.extra;if(!extra)return;let candidates=null;for(let key of Object.keys(extra)){if(wellKnownExtras.has(key))continue;candidates??=[...KNOWN_COMPONENT_SPEC_KEYS,...wellKnownExtras],lx.warn(UNKNOWN_COMPONENT_SPEC_KEY,{key},replaceNameSuggestion(key,candidates))}}function checkUnreferencedAlterHandlers(lx,Comp,referencedAlters){for(let name in Comp.alter)if(!referencedAlters.has(name))lx.hint(ALT_HANDLER_NOT_REFERENCED,{name})}function checkUnreferencedInputHandlers(lx,Comp,referencedInputs){for(let name in Comp.input)if(!referencedInputs.has(name))lx.hint(INPUT_HANDLER_NOT_REFERENCED,{name})}function checkUnreferencedDynamics(lx,Comp,referencedDynamics){for(let name in Comp.dynamic)if(Comp.dynamic[name].constructor.name==="DynamicAlias"&&!referencedDynamics.has(name))lx.hint(DYN_ALIAS_NOT_REFERENCED,{name})}class LintContext{constructor(){this.reports=[],this.frame={}}push(patch,fn){let prev=this.frame;this.frame={...prev,...patch};try{return fn()}finally{this.frame=prev}}error(id,info,suggestion=null){this.report(id,info,LEVEL_ERROR2,suggestion)}warn(id,info,suggestion=null){this.report(id,info,LEVEL_WARN2,suggestion)}hint(id,info,suggestion=null){this.report(id,info,LEVEL_HINT,suggestion)}report(id,info={},level=LEVEL_ERROR2,suggestion=null){this.reports.push({id,info,level,context:{...this.frame},suggestion})}}class LintParseContext extends ParseContext{constructor(document2,Text,Comment){super(document2,Text,Comment);this.attrs=[],this.parseIssues=[]}onAttributes(attrs,wrapperAttrs,textChild,isMacroCall=!1,tag=null){this.attrs.push({attrs,wrapperAttrs,textChild,isMacroCall,tag})}onParseIssue(kind,info){let tag=this.currentTag;this.parseIssues.push({kind,info:tag&&info.tag===void 0?{...info,tag}:info})}}class ModuleInfo{constructor({path=null,present=new Set,counts={},warnings=[]}){this.path=path,this.present=present,this.counts=counts,this.warnings=warnings}}class ComponentSummary{constructor({name,views,fields}){this.name=name,this.views=views,this.fields=fields}}class ComponentList{constructor({items,total=null,truncated=!1}){this.items=items,this.total=total??items.length,this.truncated=truncated}}class ExampleIndex{constructor({sections,total=null,truncated=!1}){this.sections=sections,this.total=total??sections.reduce((n,s)=>n+(s.items?.length??0),0),this.truncated=truncated}}class ComponentDocs{constructor({items}){this.items=items}}class LintFinding{constructor({id,level,info,context={},suggestion=null}){this.id=id,this.level=level,this.info=info,this.context=context,this.suggestion=suggestion}}class LintComponentResult{constructor({componentName,findings}){this.componentName=componentName,this.findings=findings}get errorCount(){return this.findings.filter((f)=>f.level==="error").length}get warnCount(){return this.findings.filter((f)=>f.level==="warn").length}}class LintReport{constructor({components}){this.components=components}get hasErrors(){return this.components.some((c)=>c.errorCount>0)}get totalErrors(){return this.components.reduce((n,c)=>n+c.errorCount,0)}get totalWarnings(){return this.components.reduce((n,c)=>n+c.warnCount,0)}}class RenderedExample{constructor({title,description=null,componentName,view,html,error=null}){this.title=title,this.description=description,this.componentName=componentName,this.view=view,this.html=html,this.error=error}}class RenderedSection{constructor({title,description=null,items}){this.title=title,this.description=description,this.items=items}}class RenderBatch{constructor({sections}){this.sections=sections}get hasErrors(){return this.sections.some((s)=>s.items.some((i)=>i.error!==null))}}class TestResult{constructor({title,fullPath,componentName=null,status,durationMs=0,error=null}){this.title=title,this.fullPath=fullPath,this.componentName=componentName,this.status=status,this.durationMs=durationMs,this.error=error}}class DescribeResult{constructor({title,componentName=null,children=[]}){this.title=title,this.componentName=componentName,this.children=children}}class ModuleTestReport{constructor({path=null,suites=[],counts={pass:0,fail:0,skip:0,total:0}}){this.path=path,this.suites=suites,this.counts=counts}}class TestReport{constructor({modules=[]}){this.modules=modules}get totals(){return this.modules.reduce((acc,m)=>({pass:acc.pass+m.counts.pass,fail:acc.fail+m.counts.fail,skip:acc.skip+m.counts.skip,total:acc.total+m.counts.total}),{pass:0,fail:0,skip:0,total:0})}get hasFailures(){return this.modules.some((m)=>m.counts.fail>0)}}class Describe{constructor({title,componentName=null,parent=null}){this.title=title,this.componentName=componentName,this.parent=parent,this.children=[]}}class Test{constructor({title,fn,componentName=null,parent=null}){this.title=title,this.fn=fn,this.componentName=componentName,this.parent=parent}}class ModuleTests{constructor({path=null,suites=[]}={}){this.path=path,this.suites=suites}}class TestIndex{constructor({modules=[]}={}){this.modules=modules}}function isComponentObject(x){return x!==null&&typeof x==="object"&&typeof x.name==="string"&&typeof x.Class==="function"}function resolveComponentName(arg,components){if(isComponentObject(arg))return arg.name;if(typeof arg==="function"){for(let c of components)if(c.Class===arg)return c.name}return null}function titleFromArg(arg){if(typeof arg==="string")return arg;if(isComponentObject(arg))return arg.name;if(typeof arg==="function")return arg.name||"(anonymous)";return String(arg)}function makeCollector({path=null,components=[]}={}){let moduleTests=new ModuleTests({path,suites:[]}),stack=[];function describe(...args){let head,options=null,fn;if(args.length===2)[head,fn]=args;else if(args.length===3)[head,options,fn]=args;else throw Error(`describe() expects 2 or 3 arguments, got ${args.length}`);if(typeof fn!=="function")throw Error(`describe(${JSON.stringify(titleFromArg(head))}): final argument must be a function`);let componentName=null;if(typeof head!=="string")componentName=resolveComponentName(head,components);if(componentName===null&&options&&options.component!=null)componentName=resolveComponentName(options.component,components);if(componentName===null){let parent2=stack.length?stack[stack.length-1]:null;if(parent2)componentName=parent2.componentName}let parent=stack.length?stack[stack.length-1]:null,node=new Describe({title:titleFromArg(head),componentName,parent});if(parent)parent.children.push(node);else moduleTests.suites.push(node);stack.push(node);try{fn()}finally{stack.pop()}}function test2(title,fn){if(typeof title!=="string")throw Error("test(title, fn): title must be a string");if(typeof fn!=="function")throw Error(`test(${JSON.stringify(title)}): fn must be a function`);let parent=stack.length?stack[stack.length-1]:null;if(!parent)throw Error(`test(${JSON.stringify(title)}) must be called inside a describe()`);parent.children.push(new Test({title,fn,componentName:parent.componentName,parent}))}return{describe,test:test2,moduleTests}}function buildPath(node){let parts=[],cur=node;while(cur)parts.unshift(cur.title),cur=cur.parent;return parts.join(" > ")}function captureError(e){let out={message:e.message,stack:e.stack};if("expected"in e)out.expected=e.expected;if("actual"in e)out.actual=e.actual;return out}async function runTests({getTests,components=[],path=null,expect:expect2,name=null,grep=null,bail=!1}={}){let counts={pass:0,fail:0,skip:0,total:0};if(typeof getTests!=="function")return new TestReport({modules:[new ModuleTestReport({path,suites:[],counts})]});if(typeof expect2!=="function")throw Error("runTests: expect must be provided (e.g. chai's expect)");let{describe,test:test2,moduleTests}=makeCollector({path,components});await getTests({describe,test:test2,expect:expect2});let bailed=!1;async function visit(node){if(node instanceof Test){if(name!==null&&node.componentName!==name)return null;let fullPath=buildPath(node);if(grep!==null&&!fullPath.includes(grep))return null;if(counts.total++,bailed)return counts.skip++,new TestResult({title:node.title,fullPath,componentName:node.componentName,status:"skip"});let start=performance.now();try{return await node.fn(),counts.pass++,new TestResult({title:node.title,fullPath,componentName:node.componentName,status:"pass",durationMs:performance.now()-start})}catch(e){if(counts.fail++,bail)bailed=!0;return new TestResult({title:node.title,fullPath,componentName:node.componentName,status:"fail",durationMs:performance.now()-start,error:captureError(e)})}}let childResults=[];for(let child of node.children){let r=await visit(child);if(r!==null)childResults.push(r)}if(childResults.length===0)return null;return new DescribeResult({title:node.title,componentName:node.componentName,children:childResults})}let suiteResults=[];for(let suite of moduleTests.suites){let r=await visit(suite);if(r!==null)suiteResults.push(r)}return new TestReport({modules:[new ModuleTestReport({path,suites:suiteResults,counts})]})}function reportTestNode(node){if(node.children){let label=node.componentName?`${node.title} [${node.componentName}]`:node.title;console.group(label);for(let child of node.children)reportTestNode(child);console.groupEnd();return}let dur=node.status==="skip"?"":` (${Math.round(node.durationMs)}ms)`;if(node.status==="pass")console.log(`%c✓%c ${node.title}%c${dur}`,"color: #0a0; font-weight: bold","color: inherit; font-weight: normal","color: #888");else if(node.status==="skip")console.log(`%c○ ${node.title}%c (skipped)`,"color: #888","color: inherit; font-weight: normal");else{if(console.group(`%c✗%c ${node.title}%c${dur}`,"color: #c00; font-weight: bold","color: inherit; font-weight: normal","color: #888"),console.error(node.error?.message??"(no error message)"),node.error&&(("expected"in node.error)||("actual"in node.error)))console.log("expected:",node.error.expected),console.log("actual: ",node.error.actual);if(node.error?.stack)console.log(node.error.stack);console.groupEnd()}}function reportTestReportToConsole(report){for(let m of report.modules){let label=`tutuca tests${m.path?` — ${m.path}`:""}`;if(console.group(label),m.suites.length===0)console.log("(no tests)");else for(let s of m.suites)reportTestNode(s);let c=m.counts,summary=`${c.pass} passed, ${c.fail} failed, ${c.skip} skipped (${c.total} total)`;if(c.fail>0)console.error(`%c${summary}`,"color: #c00; font-weight: bold");else if(c.total===0)console.log(`%c${summary}`,"color: #888");else console.log(`%c${summary}`,"color: #0a0; font-weight: bold");console.groupEnd()}return report}var UNSUPPORTED_EXPR_LABEL={"legacy-template":"string template",ternary:"ternary expression",comparison:"comparison",logical:"logical expression","call-with-args":"method call with arguments"};function unsupportedExprMessage(info){let v=JSON.stringify(info.value),label=UNSUPPORTED_EXPR_LABEL[info.detected]??"expression";switch(info.role){case"attr":return`Unsupported ${label} ${v} in dynamic attribute ':${info.attr}'`;case"directive":return`Unsupported ${label} ${v} in directive '@${info.directive}'`;case"if":return`Unsupported ${label} ${v} in '@if.${info.attr}' condition`;case"x-op":return`Unsupported ${label} ${v} in <x ${info.op}>`;default:return`Unsupported ${label} ${v}`}}function badValueMessage(info){let v=JSON.stringify(info.value);switch(info.role){case"attr":return`Cannot parse value ${v} for attribute ':${info.attr}'`;case"directive":return`Cannot parse value ${v} for directive '@${info.directive}'`;case"if":return`Cannot parse condition ${v} for '@if.${info.attr}'`;case"x-op":return`Cannot parse value ${v} for <x ${info.op}>`;case"handler-name":return`Cannot parse handler name ${v}`;case"handler-arg":return`Cannot parse handler argument ${v}`;case"macro-var":return`Macro variable '^${info.name}' is not defined`;default:return`Cannot parse value ${v}`}}function tagDisplay(tag){return tag?String(tag).toLowerCase():null}function fmtTagSuffix(info){let t=tagDisplay(info?.tag);return t&&t!=="x"?` on <${t}>`:""}function fmtOriginSuffix(info){if(!info)return"";let parts=[];if(info.originAttr){let branch=info.branch?`[${info.branch}]`:"";parts.push(`in ${info.originAttr}${branch}`)}if(info.handlerName)parts.push(`handler '${info.handlerName}'${info.argIndex!==void 0?` arg ${info.argIndex}`:""}`);let t=tagDisplay(info.tag);if(t&&t!=="x")parts.push(`on <${t}>`);return parts.length?` (${parts.join(", ")})`:""}function fmtEventSuffix(info){if(info?.originAttr)return` in ${info.originAttr}`;if(info?.eventName)return` in @on.${info.eventName}`;return""}function lintIdToMessage(id,info){switch(id){case"RENDER_IT_OUTSIDE_OF_LOOP":return"<x render-it> used outside of a loop";case"UNKNOWN_EVENT_MODIFIER":{let mods=info.handler?.modifiers??[info.modifier],written=`@on.${info.name}+${mods.join("+")}`;return`Unknown modifier '+${info.modifier}' in '${written}'`}case"UNKNOWN_HANDLER_ARG_NAME":return`Unknown handler argument '${info.name}'${fmtOriginSuffix(info)}`;case"INPUT_HANDLER_NOT_IMPLEMENTED":return`Input handler '${info.name}' is not implemented${fmtEventSuffix(info)}`;case"INPUT_HANDLER_NOT_REFERENCED":return`Input handler '${info.name}' is defined but never used — remove it or wire it to an @on.* event`;case"INPUT_HANDLER_METHOD_NOT_IMPLEMENTED":return`Method '$${info.name}' is not implemented${fmtEventSuffix(info)}`;case"INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD":return`'$${info.name}' is a method reference, but '${info.name}' is defined as an input handler${fmtEventSuffix(info)}`;case"INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER":return`'${info.name}' is an input handler reference, but '${info.name}' is defined as a method${fmtEventSuffix(info)}`;case"FIELD_VAL_NOT_DEFINED":return`Field '.${info.name}' is not defined${fmtOriginSuffix(info)}`;case"FIELD_VAL_IS_METHOD":return`'.${info.name}' reads a field, but '${info.name}' is defined as a method — use '$${info.name}'${fmtOriginSuffix(info)}`;case"METHOD_VAL_NOT_DEFINED":return`Method '$${info.name}' is not defined${fmtOriginSuffix(info)}`;case"METHOD_VAL_IS_FIELD":return`'$${info.name}' calls a method, but '${info.name}' is defined as a field — use '.${info.name}'${fmtOriginSuffix(info)}`;case"DUPLICATE_ATTR_DEFINITION":{let sources=info.sources?.length?` (${info.sources.join(", ")})`:"",tag=info.tag?` on <${String(info.tag).toLowerCase()}>`:"";return`Attribute '${info.name}' is set ${info.sources?.length??"multiple"} times${sources}${tag}`}case"IF_NO_BRANCH_SET":return`'@if.${info.attr}' has no '@then' or '@else' branch — add '@then="…"' or '@else="…"' (or both)${fmtTagSuffix(info)}`;case"UNKNOWN_REQUEST_NAME":return`Unknown request '!${info.name}'${fmtOriginSuffix(info)}`;case"UNKNOWN_COMPONENT_NAME":return`Unknown component '${info.name}'${fmtOriginSuffix(info)}`;case"ALT_HANDLER_NOT_DEFINED":return`Alter handler '${info.name}' is not defined${fmtOriginSuffix(info)}`;case"ALT_HANDLER_NOT_REFERENCED":return`Alter handler '${info.name}' is defined but never used — remove it or reference it from @when, @enrich-with, or @loop-with`;case"DYN_VAL_NOT_DEFINED":return`Dynamic variable '*${info.name}' is not defined${fmtOriginSuffix(info)}`;case"DYN_ALIAS_NOT_REFERENCED":return`Dynamic '${info.name}' is defined but never used — remove it or reference it as '*${info.name}' in a view`;case"UNKNOWN_MACRO_ARG":return`Argument '${info.name}' is not declared in macro '${info.macroName}'`;case"UNKNOWN_DIRECTIVE":return`Unknown directive '@${info.name}=${JSON.stringify(info.value)}'${fmtTagSuffix(info)}`;case"UNKNOWN_X_OP":return`Unknown <x> op '${info.name}=${JSON.stringify(info.value)}'${fmtTagSuffix(info)}`;case"UNKNOWN_X_ATTR":return`Unknown attribute '${info.name}=${JSON.stringify(info.value)}' on <x ${info.op}>${fmtTagSuffix(info)}`;case"MAYBE_DROP_AT_PREFIX":return`'${info.value!==void 0?`${info.name}=${JSON.stringify(info.value)}`:info.name}' on <x> looks like a directive but is actually an x op/attr written with a leading '@'`;case"BAD_VALUE":return`${badValueMessage(info)}${fmtTagSuffix(info)}`;case"UNSUPPORTED_EXPR_SYNTAX":return`${unsupportedExprMessage(info)}${fmtTagSuffix(info)}`;case"REDUNDANT_TEMPLATE_STRING":return`Redundant template string — '{${info.simpler}}' should be just '${info.simpler}'${fmtOriginSuffix(info)}`;case"PLACEHOLDERLESS_TEMPLATE_STRING":return`Template string has no dynamic parts — use the string literal ${info.literal} instead${fmtOriginSuffix(info)}`;case"UNKNOWN_COMPONENT_SPEC_KEY":return`Unknown component spec key '${info.key}' — value will be ignored at runtime`;case"HTML_TAG_NAME_HAS_UPPERCASE":return`Tag <${info.raw}> will be lowercased to <${info.lowercased}>${fmtLocationSuffix(info)}`;case"HTML_SVG_TAG_WILL_LOWERCASE":return`SVG tag <${info.raw}> is not in the WHATWG case-correction list — will be lowercased to <${info.lowercased}>${fmtLocationSuffix(info)}`;case"HTML_TAG_NOT_ALLOWED_IN_PARENT":return`<${info.tag}> not allowed under <${info.parent??"?"}> in ${info.mode} — ${htmlActionPhrase(info.action,info.tag,info.parent)}${fmtLocationSuffix(info)}`;case"HTML_TEXT_NOT_ALLOWED_IN_PARENT":return`Non-whitespace text not allowed in ${info.mode}: ${JSON.stringify(info.snippet)}${fmtLocationSuffix(info)}`;case"HTML_VOID_ELEMENT_HAS_CLOSE_TAG":return`Void element <${info.tag}> has an explicit close tag${fmtLocationSuffix(info)}`;case"HTML_DUPLICATE_FORM":return`Nested <form> — the inner form will be dropped by the parser${fmtLocationSuffix(info)}`;case"HTML_NESTED_INTERACTIVE":return`<${info.tag}> nested inside another <${info.tag}> — adoption agency will reorder${fmtLocationSuffix(info)}`;case"HTML_MISNESTED_FORMATTING":return`Misnested formatting tag </${info.tag}> — adoption agency will reorder nodes${fmtLocationSuffix(info)}`;case"HTML_UNEXPECTED_END_TAG":return`Unexpected end tag </${info.tag}>${fmtLocationSuffix(info)}`;case"HTML_UNCLOSED_BEFORE_END":return`<${info.unclosed}> still open when </${info.tag}> was seen — implicitly closed${fmtLocationSuffix(info)}`;case"HTML_DUPLICATE_ATTRIBUTE":return`Duplicate attribute '${info.name}' — second occurrence dropped${fmtLocationSuffix(info)}`;case"HTML_ATTRIBUTES_ON_END_TAG":return`Attributes on end tag </${info.tag}> — dropped by the parser${fmtLocationSuffix(info)}`;case"HTML_SELF_CLOSING_END_TAG":return`Self-closing end tag </${info.tag}/> — trailing '/' is meaningless${fmtLocationSuffix(info)}`;case"HTML_MISSING_ATTRIBUTE_VALUE":return`Attribute '${info.name}' is missing a value${fmtLocationSuffix(info)}`;case"HTML_CDATA_IN_HTML_NAMESPACE":return`CDATA section in HTML namespace — reinterpreted as a bogus comment${fmtLocationSuffix(info)}`;case"HTML_BOGUS_COMMENT":return`Bogus comment — content dropped by the parser${fmtLocationSuffix(info)}`;case"HTML_SVG_ATTR_WILL_LOWERCASE":return`SVG attribute '${info.raw}' will be rewritten to '${info.canonical}'${fmtLocationSuffix(info)}`;case"HTML_MATHML_ATTR_WILL_LOWERCASE":return`MathML attribute '${info.raw}' will be rewritten to '${info.canonical}'${fmtLocationSuffix(info)}`;case"LINT_ERROR":return info.message;default:return id}}function suggestionToMessage(suggestion){if(!suggestion)return null;switch(suggestion.kind){case"replace-name":return`did you mean '${suggestion.to}'?`;case"drop-prefix":return`did you mean '${suggestion.to}'? (drop the leading '${suggestion.from.slice(0,suggestion.from.length-suggestion.to.length)}')`;case"add-prefix":return`did you mean '${suggestion.to}'? (add the leading '${suggestion.to.slice(0,suggestion.to.length-suggestion.from.length)}')`;case"remove":return`remove ${suggestion.what}`;case"rewrite":return`use '${suggestion.to}' instead of '${suggestion.from}'`;case"wrap":return`wrap it in ${suggestion.to}`;case"rephrase":return suggestion.text??null;default:return null}}function fmtLocationSuffix(info){let loc=info?.location;if(!loc)return"";return` at line ${loc.line}, col ${loc.column}`}function htmlActionPhrase(action,tag,parent){switch(action){case"ignored":return`the parser will drop this <${tag}>`;case"drop":return`the parser will drop this <${tag}>`;case"auto-close-implicit":return`the parser will close <${parent??"?"}> first, then place <${tag}> as a sibling`;case"foster-parent":return`the parser will move <${tag}> outside <${parent??"?"}> (foster-parenting)`;case"foreign-breakout":return`the parser will exit foreign content and re-process <${tag}> in HTML mode`;default:return`parser action: ${action}`}}class Components{constructor(){this.getComponentSymbol=Symbol("getComponent"),this.byId=new Map}registerComponent(comp){comp.Class.prototype[this.getComponentSymbol]=()=>comp,this.byId.set(comp.id,comp)}getComponentForId(id){return this.byId.get(id)??null}getCompFor(v){return v?.[this.getComponentSymbol]?.()??null}getOnEnterFor(v){return this.getCompFor(v)?.on.stackEnter??defaultOnStackEnter}getHandlerFor(v,name,key){return this.getCompFor(v)?.[key][name]??null}getRequestFor(v,name){return this.getCompFor(v)?.scope.lookupRequest(name)??null}compileStyles(){let styles2=[];for(let comp of this.byId.values())styles2.push(comp.compileStyle());return styles2.join(`
|
|
2
|
+
`)}__name(inspectNodeCollection,"inspectNodeCollection");function inspectNode(node,options){switch(node.nodeType){case 1:return inspectHTML(node,options);case 3:return options.inspect(node.data,options);default:return options.inspect(node,options)}}__name(inspectNode,"inspectNode");function inspectHTML(element,options){let properties=element.getAttributeNames(),name=element.tagName.toLowerCase(),head=options.stylize(`<${name}`,"special"),headClose=options.stylize(">","special"),tail=options.stylize(`</${name}>`,"special");options.truncate-=name.length*2+5;let propertyContents="";if(properties.length>0)propertyContents+=" ",propertyContents+=inspectList(properties.map((key)=>[key,element.getAttribute(key)]),options,inspectAttribute," ");options.truncate-=propertyContents.length;let truncate2=options.truncate,children=inspectNodeCollection(element.children,options);if(children&&children.length>truncate2)children=`${truncator}(${element.children.length})`;return`${head}${propertyContents}${headClose}${children}${tail}`}__name(inspectHTML,"inspectHTML");var symbolsSupported=typeof Symbol==="function"&&typeof Symbol.for==="function",chaiInspect=symbolsSupported?Symbol.for("chai/inspect"):"@@chai/inspect",nodeInspect=Symbol.for("nodejs.util.inspect.custom"),constructorMap=new WeakMap,stringTagMap={},baseTypesMap={undefined:__name((value,options)=>options.stylize("undefined","undefined"),"undefined"),null:__name((value,options)=>options.stylize("null","null"),"null"),boolean:__name((value,options)=>options.stylize(String(value),"boolean"),"boolean"),Boolean:__name((value,options)=>options.stylize(String(value),"boolean"),"Boolean"),number:inspectNumber,Number:inspectNumber,bigint:inspectBigInt,BigInt:inspectBigInt,string:inspectString,String:inspectString,function:inspectFunction,Function:inspectFunction,symbol:inspectSymbol,Symbol:inspectSymbol,Array:inspectArray,Date:inspectDate,Map:inspectMap,Set:inspectSet,RegExp:inspectRegExp,Promise:promise_default,WeakSet:__name((value,options)=>options.stylize("WeakSet{…}","special"),"WeakSet"),WeakMap:__name((value,options)=>options.stylize("WeakMap{…}","special"),"WeakMap"),Arguments:inspectArguments,Int8Array:inspectTypedArray,Uint8Array:inspectTypedArray,Uint8ClampedArray:inspectTypedArray,Int16Array:inspectTypedArray,Uint16Array:inspectTypedArray,Int32Array:inspectTypedArray,Uint32Array:inspectTypedArray,Float32Array:inspectTypedArray,Float64Array:inspectTypedArray,Generator:__name(()=>"","Generator"),DataView:__name(()=>"","DataView"),ArrayBuffer:__name(()=>"","ArrayBuffer"),Error:inspectObject2,HTMLCollection:inspectNodeCollection,NodeList:inspectNodeCollection},inspectCustom=__name((value,options,type3,inspectFn)=>{if(chaiInspect in value&&typeof value[chaiInspect]==="function")return value[chaiInspect](options);if(nodeInspect in value&&typeof value[nodeInspect]==="function")return value[nodeInspect](options.depth,options,inspectFn);if("inspect"in value&&typeof value.inspect==="function")return value.inspect(options.depth,options);if("constructor"in value&&constructorMap.has(value.constructor))return constructorMap.get(value.constructor)(value,options);if(stringTagMap[type3])return stringTagMap[type3](value,options);return""},"inspectCustom"),toString=Object.prototype.toString;function inspect(value,opts={}){let options=normaliseOptions(opts,inspect),{customInspect}=options,type3=value===null?"null":typeof value;if(type3==="object")type3=toString.call(value).slice(8,-1);if(type3 in baseTypesMap)return baseTypesMap[type3](value,options);if(customInspect&&value){let output=inspectCustom(value,options,type3,inspect);if(output){if(typeof output==="string")return output;return inspect(output,options)}}let proto=value?Object.getPrototypeOf(value):!1;if(proto===Object.prototype||proto===null)return inspectObject(value,options);if(value&&typeof HTMLElement==="function"&&value instanceof HTMLElement)return inspectHTML(value,options);if("constructor"in value){if(value.constructor!==Object)return inspectClass(value,options);return inspectObject(value,options)}if(value===Object(value))return inspectObject(value,options);return options.stylize(String(value),type3)}__name(inspect,"inspect");var config={includeStack:!1,showDiff:!0,truncateThreshold:40,useProxy:!0,proxyExcludedKeys:["then","catch","inspect","toJSON"],deepEqual:null};function inspect2(obj,showHidden,depth,colors){let options={colors,depth:typeof depth>"u"?2:depth,showHidden,truncate:config.truncateThreshold?config.truncateThreshold:1/0};return inspect(obj,options)}__name(inspect2,"inspect");function objDisplay(obj){let str=inspect2(obj),type3=Object.prototype.toString.call(obj);if(config.truncateThreshold&&str.length>=config.truncateThreshold)if(type3==="[object Function]")return!obj.name||obj.name===""?"[Function]":"[Function: "+obj.name+"]";else if(type3==="[object Array]")return"[ Array("+obj.length+") ]";else if(type3==="[object Object]"){let keys=Object.keys(obj);return"{ Object ("+(keys.length>2?keys.splice(0,2).join(", ")+", ...":keys.join(", "))+") }"}else return str;else return str}__name(objDisplay,"objDisplay");function getMessage2(obj,args){let negate=flag(obj,"negate"),val=flag(obj,"object"),expected=args[3],actual=getActual(obj,args),msg=negate?args[2]:args[1],flagMsg=flag(obj,"message");if(typeof msg==="function")msg=msg();return msg=msg||"",msg=msg.replace(/#\{this\}/g,function(){return objDisplay(val)}).replace(/#\{act\}/g,function(){return objDisplay(actual)}).replace(/#\{exp\}/g,function(){return objDisplay(expected)}),flagMsg?flagMsg+": "+msg:msg}__name(getMessage2,"getMessage");function transferFlags(assertion,object,includeAll){let flags=assertion.__flags||(assertion.__flags=Object.create(null));if(!object.__flags)object.__flags=Object.create(null);includeAll=arguments.length===3?includeAll:!0;for(let flag3 in flags)if(includeAll||flag3!=="object"&&flag3!=="ssfi"&&flag3!=="lockSsfi"&&flag3!="message")object.__flags[flag3]=flags[flag3]}__name(transferFlags,"transferFlags");function type2(obj){if(typeof obj>"u")return"undefined";if(obj===null)return"null";let stringTag=obj[Symbol.toStringTag];if(typeof stringTag==="string")return stringTag;let sliceStart=8,sliceEnd=-1;return Object.prototype.toString.call(obj).slice(sliceStart,sliceEnd)}__name(type2,"type");function FakeMap(){this._key="chai/deep-eql__"+Math.random()+Date.now()}__name(FakeMap,"FakeMap");FakeMap.prototype={get:__name(function(key){return key[this._key]},"get"),set:__name(function(key,value){if(Object.isExtensible(key))Object.defineProperty(key,this._key,{value,configurable:!0})},"set")};var MemoizeMap=typeof WeakMap==="function"?WeakMap:FakeMap;function memoizeCompare(leftHandOperand,rightHandOperand,memoizeMap){if(!memoizeMap||isPrimitive(leftHandOperand)||isPrimitive(rightHandOperand))return null;var leftHandMap=memoizeMap.get(leftHandOperand);if(leftHandMap){var result=leftHandMap.get(rightHandOperand);if(typeof result==="boolean")return result}return null}__name(memoizeCompare,"memoizeCompare");function memoizeSet(leftHandOperand,rightHandOperand,memoizeMap,result){if(!memoizeMap||isPrimitive(leftHandOperand)||isPrimitive(rightHandOperand))return;var leftHandMap=memoizeMap.get(leftHandOperand);if(leftHandMap)leftHandMap.set(rightHandOperand,result);else leftHandMap=new MemoizeMap,leftHandMap.set(rightHandOperand,result),memoizeMap.set(leftHandOperand,leftHandMap)}__name(memoizeSet,"memoizeSet");var deep_eql_default=deepEqual;function deepEqual(leftHandOperand,rightHandOperand,options){if(options&&options.comparator)return extensiveDeepEqual(leftHandOperand,rightHandOperand,options);var simpleResult=simpleEqual(leftHandOperand,rightHandOperand);if(simpleResult!==null)return simpleResult;return extensiveDeepEqual(leftHandOperand,rightHandOperand,options)}__name(deepEqual,"deepEqual");function simpleEqual(leftHandOperand,rightHandOperand){if(leftHandOperand===rightHandOperand)return leftHandOperand!==0||1/leftHandOperand===1/rightHandOperand;if(leftHandOperand!==leftHandOperand&&rightHandOperand!==rightHandOperand)return!0;if(isPrimitive(leftHandOperand)||isPrimitive(rightHandOperand))return!1;return null}__name(simpleEqual,"simpleEqual");function extensiveDeepEqual(leftHandOperand,rightHandOperand,options){options=options||{},options.memoize=options.memoize===!1?!1:options.memoize||new MemoizeMap;var comparator=options&&options.comparator,memoizeResultLeft=memoizeCompare(leftHandOperand,rightHandOperand,options.memoize);if(memoizeResultLeft!==null)return memoizeResultLeft;var memoizeResultRight=memoizeCompare(rightHandOperand,leftHandOperand,options.memoize);if(memoizeResultRight!==null)return memoizeResultRight;if(comparator){var comparatorResult=comparator(leftHandOperand,rightHandOperand);if(comparatorResult===!1||comparatorResult===!0)return memoizeSet(leftHandOperand,rightHandOperand,options.memoize,comparatorResult),comparatorResult;var simpleResult=simpleEqual(leftHandOperand,rightHandOperand);if(simpleResult!==null)return simpleResult}var leftHandType=type2(leftHandOperand);if(leftHandType!==type2(rightHandOperand))return memoizeSet(leftHandOperand,rightHandOperand,options.memoize,!1),!1;memoizeSet(leftHandOperand,rightHandOperand,options.memoize,!0);var result=extensiveDeepEqualByType(leftHandOperand,rightHandOperand,leftHandType,options);return memoizeSet(leftHandOperand,rightHandOperand,options.memoize,result),result}__name(extensiveDeepEqual,"extensiveDeepEqual");function extensiveDeepEqualByType(leftHandOperand,rightHandOperand,leftHandType,options){switch(leftHandType){case"String":case"Number":case"Boolean":case"Date":return deepEqual(leftHandOperand.valueOf(),rightHandOperand.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return leftHandOperand===rightHandOperand;case"Error":return keysEqual(leftHandOperand,rightHandOperand,["name","message","code"],options);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return iterableEqual(leftHandOperand,rightHandOperand,options);case"RegExp":return regexpEqual(leftHandOperand,rightHandOperand);case"Generator":return generatorEqual(leftHandOperand,rightHandOperand,options);case"DataView":return iterableEqual(new Uint8Array(leftHandOperand.buffer),new Uint8Array(rightHandOperand.buffer),options);case"ArrayBuffer":return iterableEqual(new Uint8Array(leftHandOperand),new Uint8Array(rightHandOperand),options);case"Set":return entriesEqual(leftHandOperand,rightHandOperand,options);case"Map":return entriesEqual(leftHandOperand,rightHandOperand,options);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return leftHandOperand.equals(rightHandOperand);case"Temporal.Duration":return leftHandOperand.total("nanoseconds")===rightHandOperand.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return leftHandOperand.toString()===rightHandOperand.toString();default:return objectEqual(leftHandOperand,rightHandOperand,options)}}__name(extensiveDeepEqualByType,"extensiveDeepEqualByType");function regexpEqual(leftHandOperand,rightHandOperand){return leftHandOperand.toString()===rightHandOperand.toString()}__name(regexpEqual,"regexpEqual");function entriesEqual(leftHandOperand,rightHandOperand,options){try{if(leftHandOperand.size!==rightHandOperand.size)return!1;if(leftHandOperand.size===0)return!0}catch(sizeError){return!1}var leftHandItems=[],rightHandItems=[];return leftHandOperand.forEach(__name(function(key,value){leftHandItems.push([key,value])},"gatherEntries")),rightHandOperand.forEach(__name(function(key,value){rightHandItems.push([key,value])},"gatherEntries")),iterableEqual(leftHandItems.sort(),rightHandItems.sort(),options)}__name(entriesEqual,"entriesEqual");function iterableEqual(leftHandOperand,rightHandOperand,options){var length=leftHandOperand.length;if(length!==rightHandOperand.length)return!1;if(length===0)return!0;var index=-1;while(++index<length)if(deepEqual(leftHandOperand[index],rightHandOperand[index],options)===!1)return!1;return!0}__name(iterableEqual,"iterableEqual");function generatorEqual(leftHandOperand,rightHandOperand,options){return iterableEqual(getGeneratorEntries(leftHandOperand),getGeneratorEntries(rightHandOperand),options)}__name(generatorEqual,"generatorEqual");function hasIteratorFunction(target){return typeof Symbol<"u"&&typeof target==="object"&&typeof Symbol.iterator<"u"&&typeof target[Symbol.iterator]==="function"}__name(hasIteratorFunction,"hasIteratorFunction");function getIteratorEntries(target){if(hasIteratorFunction(target))try{return getGeneratorEntries(target[Symbol.iterator]())}catch(iteratorError){return[]}return[]}__name(getIteratorEntries,"getIteratorEntries");function getGeneratorEntries(generator){var generatorResult=generator.next(),accumulator=[generatorResult.value];while(generatorResult.done===!1)generatorResult=generator.next(),accumulator.push(generatorResult.value);return accumulator}__name(getGeneratorEntries,"getGeneratorEntries");function getEnumerableKeys(target){var keys=[];for(var key in target)keys.push(key);return keys}__name(getEnumerableKeys,"getEnumerableKeys");function getEnumerableSymbols(target){var keys=[],allKeys=Object.getOwnPropertySymbols(target);for(var i=0;i<allKeys.length;i+=1){var key=allKeys[i];if(Object.getOwnPropertyDescriptor(target,key).enumerable)keys.push(key)}return keys}__name(getEnumerableSymbols,"getEnumerableSymbols");function keysEqual(leftHandOperand,rightHandOperand,keys,options){var length=keys.length;if(length===0)return!0;for(var i=0;i<length;i+=1)if(deepEqual(leftHandOperand[keys[i]],rightHandOperand[keys[i]],options)===!1)return!1;return!0}__name(keysEqual,"keysEqual");function objectEqual(leftHandOperand,rightHandOperand,options){var leftHandKeys=getEnumerableKeys(leftHandOperand),rightHandKeys=getEnumerableKeys(rightHandOperand),leftHandSymbols=getEnumerableSymbols(leftHandOperand),rightHandSymbols=getEnumerableSymbols(rightHandOperand);if(leftHandKeys=leftHandKeys.concat(leftHandSymbols),rightHandKeys=rightHandKeys.concat(rightHandSymbols),leftHandKeys.length&&leftHandKeys.length===rightHandKeys.length){if(iterableEqual(mapSymbols(leftHandKeys).sort(),mapSymbols(rightHandKeys).sort())===!1)return!1;return keysEqual(leftHandOperand,rightHandOperand,leftHandKeys,options)}var leftHandEntries=getIteratorEntries(leftHandOperand),rightHandEntries=getIteratorEntries(rightHandOperand);if(leftHandEntries.length&&leftHandEntries.length===rightHandEntries.length)return leftHandEntries.sort(),rightHandEntries.sort(),iterableEqual(leftHandEntries,rightHandEntries,options);if(leftHandKeys.length===0&&leftHandEntries.length===0&&rightHandKeys.length===0&&rightHandEntries.length===0)return!0;return!1}__name(objectEqual,"objectEqual");function isPrimitive(value){return value===null||typeof value!=="object"}__name(isPrimitive,"isPrimitive");function mapSymbols(arr){return arr.map(__name(function(entry){if(typeof entry==="symbol")return entry.toString();return entry},"mapSymbol"))}__name(mapSymbols,"mapSymbols");function hasProperty(obj,name){if(typeof obj>"u"||obj===null)return!1;return name in Object(obj)}__name(hasProperty,"hasProperty");function parsePath(path){return path.replace(/([^\\])\[/g,"$1.[").match(/(\\\.|[^.]+?)+/g).map((value)=>{if(value==="constructor"||value==="__proto__"||value==="prototype")return{};let mArr=/^\[(\d+)\]$/.exec(value),parsed=null;if(mArr)parsed={i:parseFloat(mArr[1])};else parsed={p:value.replace(/\\([.[\]])/g,"$1")};return parsed})}__name(parsePath,"parsePath");function internalGetPathValue(obj,parsed,pathDepth){let temporaryValue=obj,res=null;pathDepth=typeof pathDepth>"u"?parsed.length:pathDepth;for(let i=0;i<pathDepth;i++){let part=parsed[i];if(temporaryValue){if(typeof part.p>"u")temporaryValue=temporaryValue[part.i];else temporaryValue=temporaryValue[part.p];if(i===pathDepth-1)res=temporaryValue}}return res}__name(internalGetPathValue,"internalGetPathValue");function getPathInfo(obj,path){let parsed=parsePath(path),last=parsed[parsed.length-1],info={parent:parsed.length>1?internalGetPathValue(obj,parsed,parsed.length-1):obj,name:last.p||last.i,value:internalGetPathValue(obj,parsed)};return info.exists=hasProperty(info.parent,info.name),info}__name(getPathInfo,"getPathInfo");var _Assertion=class _Assertion2{constructor(obj,msg,ssfi,lockSsfi){return __publicField(this,"__flags",{}),flag(this,"ssfi",ssfi||_Assertion2),flag(this,"lockSsfi",lockSsfi),flag(this,"object",obj),flag(this,"message",msg),flag(this,"eql",config.deepEqual||deep_eql_default),proxify(this)}static get includeStack(){return console.warn("Assertion.includeStack is deprecated, use chai.config.includeStack instead."),config.includeStack}static set includeStack(value){console.warn("Assertion.includeStack is deprecated, use chai.config.includeStack instead."),config.includeStack=value}static get showDiff(){return console.warn("Assertion.showDiff is deprecated, use chai.config.showDiff instead."),config.showDiff}static set showDiff(value){console.warn("Assertion.showDiff is deprecated, use chai.config.showDiff instead."),config.showDiff=value}static addProperty(name,fn){addProperty(this.prototype,name,fn)}static addMethod(name,fn){addMethod(this.prototype,name,fn)}static addChainableMethod(name,fn,chainingBehavior){addChainableMethod(this.prototype,name,fn,chainingBehavior)}static overwriteProperty(name,fn){overwriteProperty(this.prototype,name,fn)}static overwriteMethod(name,fn){overwriteMethod(this.prototype,name,fn)}static overwriteChainableMethod(name,fn,chainingBehavior){overwriteChainableMethod(this.prototype,name,fn,chainingBehavior)}assert(_expr,msg,_negateMsg,expected,_actual,showDiff){let ok=test(this,arguments);if(showDiff!==!1)showDiff=!0;if(expected===void 0&&_actual===void 0)showDiff=!1;if(config.showDiff!==!0)showDiff=!1;if(!ok){msg=getMessage2(this,arguments);let assertionErrorObjectProperties={actual:getActual(this,arguments),expected,showDiff},operator=getOperator(this,arguments);if(operator)assertionErrorObjectProperties.operator=operator;throw new AssertionError(msg,assertionErrorObjectProperties,config.includeStack?this.assert:flag(this,"ssfi"))}}get _obj(){return flag(this,"object")}set _obj(val){flag(this,"object",val)}};__name(_Assertion,"Assertion");var Assertion=_Assertion,events=new EventTarget,_PluginEvent=class extends Event{constructor(type3,name,fn){super(type3);this.name=String(name),this.fn=fn}};__name(_PluginEvent,"PluginEvent");var PluginEvent=_PluginEvent;function isProxyEnabled(){return config.useProxy&&typeof Proxy<"u"&&typeof Reflect<"u"}__name(isProxyEnabled,"isProxyEnabled");function addProperty(ctx,name,getter){getter=getter===void 0?function(){}:getter,Object.defineProperty(ctx,name,{get:__name(function propertyGetter(){if(!isProxyEnabled()&&!flag(this,"lockSsfi"))flag(this,"ssfi",propertyGetter);let result=getter.call(this);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"propertyGetter"),configurable:!0}),events.dispatchEvent(new PluginEvent("addProperty",name,getter))}__name(addProperty,"addProperty");var fnLengthDesc=Object.getOwnPropertyDescriptor(function(){},"length");function addLengthGuard(fn,assertionName,isChainable){if(!fnLengthDesc.configurable)return fn;return Object.defineProperty(fn,"length",{get:__name(function(){if(isChainable)throw Error("Invalid Chai property: "+assertionName+'.length. Due to a compatibility issue, "length" cannot directly follow "'+assertionName+'". Use "'+assertionName+'.lengthOf" instead.');throw Error("Invalid Chai property: "+assertionName+'.length. See docs for proper usage of "'+assertionName+'".')},"get")}),fn}__name(addLengthGuard,"addLengthGuard");function getProperties(object){let result=Object.getOwnPropertyNames(object);function addProperty2(property){if(result.indexOf(property)===-1)result.push(property)}__name(addProperty2,"addProperty");let proto=Object.getPrototypeOf(object);while(proto!==null)Object.getOwnPropertyNames(proto).forEach(addProperty2),proto=Object.getPrototypeOf(proto);return result}__name(getProperties,"getProperties");var builtins=["__flags","__methods","_obj","assert"];function proxify(obj,nonChainableMethodName){if(!isProxyEnabled())return obj;return new Proxy(obj,{get:__name(function proxyGetter(target,property){if(typeof property==="string"&&config.proxyExcludedKeys.indexOf(property)===-1&&!Reflect.has(target,property)){if(nonChainableMethodName)throw Error("Invalid Chai property: "+nonChainableMethodName+"."+property+'. See docs for proper usage of "'+nonChainableMethodName+'".');let suggestion=null,suggestionDistance=4;if(getProperties(target).forEach(function(prop){if(!Object.prototype.hasOwnProperty(prop)&&builtins.indexOf(prop)===-1){let dist=stringDistanceCapped(property,prop,suggestionDistance);if(dist<suggestionDistance)suggestion=prop,suggestionDistance=dist}}),suggestion!==null)throw Error("Invalid Chai property: "+property+'. Did you mean "'+suggestion+'"?');else throw Error("Invalid Chai property: "+property)}if(builtins.indexOf(property)===-1&&!flag(target,"lockSsfi"))flag(target,"ssfi",proxyGetter);return Reflect.get(target,property)},"proxyGetter")})}__name(proxify,"proxify");function stringDistanceCapped(strA,strB,cap){if(Math.abs(strA.length-strB.length)>=cap)return cap;let memo=[];for(let i=0;i<=strA.length;i++)memo[i]=Array(strB.length+1).fill(0),memo[i][0]=i;for(let j=0;j<strB.length;j++)memo[0][j]=j;for(let i=1;i<=strA.length;i++){let ch=strA.charCodeAt(i-1);for(let j=1;j<=strB.length;j++){if(Math.abs(i-j)>=cap){memo[i][j]=cap;continue}memo[i][j]=Math.min(memo[i-1][j]+1,memo[i][j-1]+1,memo[i-1][j-1]+(ch===strB.charCodeAt(j-1)?0:1))}}return memo[strA.length][strB.length]}__name(stringDistanceCapped,"stringDistanceCapped");function addMethod(ctx,name,method){let methodWrapper=__name(function(){if(!flag(this,"lockSsfi"))flag(this,"ssfi",methodWrapper);let result=method.apply(this,arguments);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"methodWrapper");addLengthGuard(methodWrapper,name,!1),ctx[name]=proxify(methodWrapper,name),events.dispatchEvent(new PluginEvent("addMethod",name,method))}__name(addMethod,"addMethod");function overwriteProperty(ctx,name,getter){let _get=Object.getOwnPropertyDescriptor(ctx,name),_super=__name(function(){},"_super");if(_get&&typeof _get.get==="function")_super=_get.get;Object.defineProperty(ctx,name,{get:__name(function overwritingPropertyGetter(){if(!isProxyEnabled()&&!flag(this,"lockSsfi"))flag(this,"ssfi",overwritingPropertyGetter);let origLockSsfi=flag(this,"lockSsfi");flag(this,"lockSsfi",!0);let result=getter(_super).call(this);if(flag(this,"lockSsfi",origLockSsfi),result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"overwritingPropertyGetter"),configurable:!0})}__name(overwriteProperty,"overwriteProperty");function overwriteMethod(ctx,name,method){let _method=ctx[name],_super=__name(function(){throw Error(name+" is not a function")},"_super");if(_method&&typeof _method==="function")_super=_method;let overwritingMethodWrapper=__name(function(){if(!flag(this,"lockSsfi"))flag(this,"ssfi",overwritingMethodWrapper);let origLockSsfi=flag(this,"lockSsfi");flag(this,"lockSsfi",!0);let result=method(_super).apply(this,arguments);if(flag(this,"lockSsfi",origLockSsfi),result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"overwritingMethodWrapper");addLengthGuard(overwritingMethodWrapper,name,!1),ctx[name]=proxify(overwritingMethodWrapper,name)}__name(overwriteMethod,"overwriteMethod");var canSetPrototype=typeof Object.setPrototypeOf==="function",testFn=__name(function(){},"testFn"),excludeNames=Object.getOwnPropertyNames(testFn).filter(function(name){let propDesc=Object.getOwnPropertyDescriptor(testFn,name);if(typeof propDesc!=="object")return!0;return!propDesc.configurable}),call=Function.prototype.call,apply=Function.prototype.apply,_PluginAddChainableMethodEvent=class extends PluginEvent{constructor(type3,name,fn,chainingBehavior){super(type3,name,fn);this.chainingBehavior=chainingBehavior}};__name(_PluginAddChainableMethodEvent,"PluginAddChainableMethodEvent");var PluginAddChainableMethodEvent=_PluginAddChainableMethodEvent;function addChainableMethod(ctx,name,method,chainingBehavior){if(typeof chainingBehavior!=="function")chainingBehavior=__name(function(){},"chainingBehavior");let chainableBehavior={method,chainingBehavior};if(!ctx.__methods)ctx.__methods={};ctx.__methods[name]=chainableBehavior,Object.defineProperty(ctx,name,{get:__name(function(){chainableBehavior.chainingBehavior.call(this);let chainableMethodWrapper=__name(function(){if(!flag(this,"lockSsfi"))flag(this,"ssfi",chainableMethodWrapper);let result=chainableBehavior.method.apply(this,arguments);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"chainableMethodWrapper");if(addLengthGuard(chainableMethodWrapper,name,!0),canSetPrototype){let prototype=Object.create(this);prototype.call=call,prototype.apply=apply,Object.setPrototypeOf(chainableMethodWrapper,prototype)}else Object.getOwnPropertyNames(ctx).forEach(function(asserterName){if(excludeNames.indexOf(asserterName)!==-1)return;let pd=Object.getOwnPropertyDescriptor(ctx,asserterName);Object.defineProperty(chainableMethodWrapper,asserterName,pd)});return transferFlags(this,chainableMethodWrapper),proxify(chainableMethodWrapper)},"chainableMethodGetter"),configurable:!0}),events.dispatchEvent(new PluginAddChainableMethodEvent("addChainableMethod",name,method,chainingBehavior))}__name(addChainableMethod,"addChainableMethod");function overwriteChainableMethod(ctx,name,method,chainingBehavior){let chainableBehavior=ctx.__methods[name],_chainingBehavior=chainableBehavior.chainingBehavior;chainableBehavior.chainingBehavior=__name(function(){let result=chainingBehavior(_chainingBehavior).call(this);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"overwritingChainableMethodGetter");let _method=chainableBehavior.method;chainableBehavior.method=__name(function(){let result=method(_method).apply(this,arguments);if(result!==void 0)return result;let newAssertion=new Assertion;return transferFlags(this,newAssertion),newAssertion},"overwritingChainableMethodWrapper")}__name(overwriteChainableMethod,"overwriteChainableMethod");function compareByInspect(a,b){return inspect2(a)<inspect2(b)?-1:1}__name(compareByInspect,"compareByInspect");function getOwnEnumerablePropertySymbols(obj){if(typeof Object.getOwnPropertySymbols!=="function")return[];return Object.getOwnPropertySymbols(obj).filter(function(sym){return Object.getOwnPropertyDescriptor(obj,sym).enumerable})}__name(getOwnEnumerablePropertySymbols,"getOwnEnumerablePropertySymbols");function getOwnEnumerableProperties(obj){return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj))}__name(getOwnEnumerableProperties,"getOwnEnumerableProperties");var isNaN2=Number.isNaN;function isObjectType(obj){let objectType=type(obj);return["Array","Object","Function"].indexOf(objectType)!==-1}__name(isObjectType,"isObjectType");function getOperator(obj,args){let operator=flag(obj,"operator"),negate=flag(obj,"negate"),expected=args[3],msg=negate?args[2]:args[1];if(operator)return operator;if(typeof msg==="function")msg=msg();if(msg=msg||"",!msg)return;if(/\shave\s/.test(msg))return;let isObject=isObjectType(expected);if(/\snot\s/.test(msg))return isObject?"notDeepStrictEqual":"notStrictEqual";return isObject?"deepStrictEqual":"strictEqual"}__name(getOperator,"getOperator");function getName(fn){return fn.name}__name(getName,"getName");function isRegExp2(obj){return Object.prototype.toString.call(obj)==="[object RegExp]"}__name(isRegExp2,"isRegExp");function isNumeric(obj){return["Number","BigInt"].includes(type(obj))}__name(isNumeric,"isNumeric");var{flag:flag2}=utils_exports;["to","be","been","is","and","has","have","with","that","which","at","of","same","but","does","still","also"].forEach(function(chain){Assertion.addProperty(chain)});Assertion.addProperty("not",function(){flag2(this,"negate",!0)});Assertion.addProperty("deep",function(){flag2(this,"deep",!0)});Assertion.addProperty("nested",function(){flag2(this,"nested",!0)});Assertion.addProperty("own",function(){flag2(this,"own",!0)});Assertion.addProperty("ordered",function(){flag2(this,"ordered",!0)});Assertion.addProperty("any",function(){flag2(this,"any",!0),flag2(this,"all",!1)});Assertion.addProperty("all",function(){flag2(this,"all",!0),flag2(this,"any",!1)});var functionTypes={function:["function","asyncfunction","generatorfunction","asyncgeneratorfunction"],asyncfunction:["asyncfunction","asyncgeneratorfunction"],generatorfunction:["generatorfunction","asyncgeneratorfunction"],asyncgeneratorfunction:["asyncgeneratorfunction"]};function an(type3,msg){if(msg)flag2(this,"message",msg);type3=type3.toLowerCase();let obj=flag2(this,"object"),article=~["a","e","i","o","u"].indexOf(type3.charAt(0))?"an ":"a ",detectedType=type(obj).toLowerCase();if(functionTypes.function.includes(type3))this.assert(functionTypes[type3].includes(detectedType),"expected #{this} to be "+article+type3,"expected #{this} not to be "+article+type3);else this.assert(type3===detectedType,"expected #{this} to be "+article+type3,"expected #{this} not to be "+article+type3)}__name(an,"an");Assertion.addChainableMethod("an",an);Assertion.addChainableMethod("a",an);function SameValueZero(a,b){return isNaN2(a)&&isNaN2(b)||a===b}__name(SameValueZero,"SameValueZero");function includeChainingBehavior(){flag2(this,"contains",!0)}__name(includeChainingBehavior,"includeChainingBehavior");function include(val,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),objType=type(obj).toLowerCase(),flagMsg=flag2(this,"message"),negate=flag2(this,"negate"),ssfi=flag2(this,"ssfi"),isDeep=flag2(this,"deep"),descriptor=isDeep?"deep ":"",isEql=isDeep?flag2(this,"eql"):SameValueZero;flagMsg=flagMsg?flagMsg+": ":"";let included=!1;switch(objType){case"string":included=obj.indexOf(val)!==-1;break;case"weakset":if(isDeep)throw new AssertionError(flagMsg+"unable to use .deep.include with WeakSet",void 0,ssfi);included=obj.has(val);break;case"map":obj.forEach(function(item){included=included||isEql(item,val)});break;case"set":if(isDeep)obj.forEach(function(item){included=included||isEql(item,val)});else included=obj.has(val);break;case"array":if(isDeep)included=obj.some(function(item){return isEql(item,val)});else included=obj.indexOf(val)!==-1;break;default:{if(val!==Object(val))throw new AssertionError(flagMsg+"the given combination of arguments ("+objType+" and "+type(val).toLowerCase()+") is invalid for this assertion. You can use an array, a map, an object, a set, a string, or a weakset instead of a "+type(val).toLowerCase(),void 0,ssfi);let props=Object.keys(val),firstErr=null,numErrs=0;if(props.forEach(function(prop){let propAssertion=new Assertion(obj);if(transferFlags(this,propAssertion,!0),flag2(propAssertion,"lockSsfi",!0),!negate||props.length===1){propAssertion.property(prop,val[prop]);return}try{propAssertion.property(prop,val[prop])}catch(err){if(!check_error_exports.compatibleConstructor(err,AssertionError))throw err;if(firstErr===null)firstErr=err;numErrs++}},this),negate&&props.length>1&&numErrs===props.length)throw firstErr;return}}this.assert(included,"expected #{this} to "+descriptor+"include "+inspect2(val),"expected #{this} to not "+descriptor+"include "+inspect2(val))}__name(include,"include");Assertion.addChainableMethod("include",include,includeChainingBehavior);Assertion.addChainableMethod("contain",include,includeChainingBehavior);Assertion.addChainableMethod("contains",include,includeChainingBehavior);Assertion.addChainableMethod("includes",include,includeChainingBehavior);Assertion.addProperty("ok",function(){this.assert(flag2(this,"object"),"expected #{this} to be truthy","expected #{this} to be falsy")});Assertion.addProperty("true",function(){this.assert(flag2(this,"object")===!0,"expected #{this} to be true","expected #{this} to be false",flag2(this,"negate")?!1:!0)});Assertion.addProperty("numeric",function(){let object=flag2(this,"object");this.assert(["Number","BigInt"].includes(type(object)),"expected #{this} to be numeric","expected #{this} to not be numeric",flag2(this,"negate")?!1:!0)});Assertion.addProperty("callable",function(){let val=flag2(this,"object"),ssfi=flag2(this,"ssfi"),message=flag2(this,"message"),msg=message?`${message}: `:"",negate=flag2(this,"negate"),assertionMessage=negate?`${msg}expected ${inspect2(val)} not to be a callable function`:`${msg}expected ${inspect2(val)} to be a callable function`,isCallable=["Function","AsyncFunction","GeneratorFunction","AsyncGeneratorFunction"].includes(type(val));if(isCallable&&negate||!isCallable&&!negate)throw new AssertionError(assertionMessage,void 0,ssfi)});Assertion.addProperty("false",function(){this.assert(flag2(this,"object")===!1,"expected #{this} to be false","expected #{this} to be true",flag2(this,"negate")?!0:!1)});Assertion.addProperty("null",function(){this.assert(flag2(this,"object")===null,"expected #{this} to be null","expected #{this} not to be null")});Assertion.addProperty("undefined",function(){this.assert(flag2(this,"object")===void 0,"expected #{this} to be undefined","expected #{this} not to be undefined")});Assertion.addProperty("NaN",function(){this.assert(isNaN2(flag2(this,"object")),"expected #{this} to be NaN","expected #{this} not to be NaN")});function assertExist(){let val=flag2(this,"object");this.assert(val!==null&&val!==void 0,"expected #{this} to exist","expected #{this} to not exist")}__name(assertExist,"assertExist");Assertion.addProperty("exist",assertExist);Assertion.addProperty("exists",assertExist);Assertion.addProperty("empty",function(){let val=flag2(this,"object"),ssfi=flag2(this,"ssfi"),flagMsg=flag2(this,"message"),itemsCount;switch(flagMsg=flagMsg?flagMsg+": ":"",type(val).toLowerCase()){case"array":case"string":itemsCount=val.length;break;case"map":case"set":itemsCount=val.size;break;case"weakmap":case"weakset":throw new AssertionError(flagMsg+".empty was passed a weak collection",void 0,ssfi);case"function":{let msg=flagMsg+".empty was passed a function "+getName(val);throw new AssertionError(msg.trim(),void 0,ssfi)}default:if(val!==Object(val))throw new AssertionError(flagMsg+".empty was passed non-string primitive "+inspect2(val),void 0,ssfi);itemsCount=Object.keys(val).length}this.assert(itemsCount===0,"expected #{this} to be empty","expected #{this} not to be empty")});function checkArguments(){let obj=flag2(this,"object"),type3=type(obj);this.assert(type3==="Arguments","expected #{this} to be arguments but got "+type3,"expected #{this} to not be arguments")}__name(checkArguments,"checkArguments");Assertion.addProperty("arguments",checkArguments);Assertion.addProperty("Arguments",checkArguments);function assertEqual(val,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object");if(flag2(this,"deep")){let prevLockSsfi=flag2(this,"lockSsfi");flag2(this,"lockSsfi",!0),this.eql(val),flag2(this,"lockSsfi",prevLockSsfi)}else this.assert(val===obj,"expected #{this} to equal #{exp}","expected #{this} to not equal #{exp}",val,this._obj,!0)}__name(assertEqual,"assertEqual");Assertion.addMethod("equal",assertEqual);Assertion.addMethod("equals",assertEqual);Assertion.addMethod("eq",assertEqual);function assertEql(obj,msg){if(msg)flag2(this,"message",msg);let eql=flag2(this,"eql");this.assert(eql(obj,flag2(this,"object")),"expected #{this} to deeply equal #{exp}","expected #{this} to not deeply equal #{exp}",obj,this._obj,!0)}__name(assertEql,"assertEql");Assertion.addMethod("eql",assertEql);Assertion.addMethod("eqls",assertEql);function assertAbove(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),nType=type(n).toLowerCase();if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&nType!=="date")throw new AssertionError(msgPrefix+"the argument to above must be a date",void 0,ssfi);else if(!isNumeric(n)&&(doLength||isNumeric(obj)))throw new AssertionError(msgPrefix+"the argument to above must be a number",void 0,ssfi);else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;throw new AssertionError(msgPrefix+"expected "+printObj+" to be a number or a date",void 0,ssfi)}if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount>n,"expected #{this} to have a "+descriptor+" above #{exp} but got #{act}","expected #{this} to not have a "+descriptor+" above #{exp}",n,itemsCount)}else this.assert(obj>n,"expected #{this} to be above #{exp}","expected #{this} to be at most #{exp}",n)}__name(assertAbove,"assertAbove");Assertion.addMethod("above",assertAbove);Assertion.addMethod("gt",assertAbove);Assertion.addMethod("greaterThan",assertAbove);function assertLeast(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),nType=type(n).toLowerCase(),errorMessage,shouldThrow=!0;if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&nType!=="date")errorMessage=msgPrefix+"the argument to least must be a date";else if(!isNumeric(n)&&(doLength||isNumeric(obj)))errorMessage=msgPrefix+"the argument to least must be a number";else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;errorMessage=msgPrefix+"expected "+printObj+" to be a number or a date"}else shouldThrow=!1;if(shouldThrow)throw new AssertionError(errorMessage,void 0,ssfi);if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount>=n,"expected #{this} to have a "+descriptor+" at least #{exp} but got #{act}","expected #{this} to have a "+descriptor+" below #{exp}",n,itemsCount)}else this.assert(obj>=n,"expected #{this} to be at least #{exp}","expected #{this} to be below #{exp}",n)}__name(assertLeast,"assertLeast");Assertion.addMethod("least",assertLeast);Assertion.addMethod("gte",assertLeast);Assertion.addMethod("greaterThanOrEqual",assertLeast);function assertBelow(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),nType=type(n).toLowerCase(),errorMessage,shouldThrow=!0;if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&nType!=="date")errorMessage=msgPrefix+"the argument to below must be a date";else if(!isNumeric(n)&&(doLength||isNumeric(obj)))errorMessage=msgPrefix+"the argument to below must be a number";else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;errorMessage=msgPrefix+"expected "+printObj+" to be a number or a date"}else shouldThrow=!1;if(shouldThrow)throw new AssertionError(errorMessage,void 0,ssfi);if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount<n,"expected #{this} to have a "+descriptor+" below #{exp} but got #{act}","expected #{this} to not have a "+descriptor+" below #{exp}",n,itemsCount)}else this.assert(obj<n,"expected #{this} to be below #{exp}","expected #{this} to be at least #{exp}",n)}__name(assertBelow,"assertBelow");Assertion.addMethod("below",assertBelow);Assertion.addMethod("lt",assertBelow);Assertion.addMethod("lessThan",assertBelow);function assertMost(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),nType=type(n).toLowerCase(),errorMessage,shouldThrow=!0;if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&nType!=="date")errorMessage=msgPrefix+"the argument to most must be a date";else if(!isNumeric(n)&&(doLength||isNumeric(obj)))errorMessage=msgPrefix+"the argument to most must be a number";else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;errorMessage=msgPrefix+"expected "+printObj+" to be a number or a date"}else shouldThrow=!1;if(shouldThrow)throw new AssertionError(errorMessage,void 0,ssfi);if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount<=n,"expected #{this} to have a "+descriptor+" at most #{exp} but got #{act}","expected #{this} to have a "+descriptor+" above #{exp}",n,itemsCount)}else this.assert(obj<=n,"expected #{this} to be at most #{exp}","expected #{this} to be above #{exp}",n)}__name(assertMost,"assertMost");Assertion.addMethod("most",assertMost);Assertion.addMethod("lte",assertMost);Assertion.addMethod("lessThanOrEqual",assertMost);Assertion.addMethod("within",function(start,finish,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),doLength=flag2(this,"doLength"),flagMsg=flag2(this,"message"),msgPrefix=flagMsg?flagMsg+": ":"",ssfi=flag2(this,"ssfi"),objType=type(obj).toLowerCase(),startType=type(start).toLowerCase(),finishType=type(finish).toLowerCase(),errorMessage,shouldThrow=!0,range=startType==="date"&&finishType==="date"?start.toISOString()+".."+finish.toISOString():start+".."+finish;if(doLength&&objType!=="map"&&objType!=="set")new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length");if(!doLength&&objType==="date"&&(startType!=="date"||finishType!=="date"))errorMessage=msgPrefix+"the arguments to within must be dates";else if((!isNumeric(start)||!isNumeric(finish))&&(doLength||isNumeric(obj)))errorMessage=msgPrefix+"the arguments to within must be numbers";else if(!doLength&&objType!=="date"&&!isNumeric(obj)){let printObj=objType==="string"?"'"+obj+"'":obj;errorMessage=msgPrefix+"expected "+printObj+" to be a number or a date"}else shouldThrow=!1;if(shouldThrow)throw new AssertionError(errorMessage,void 0,ssfi);if(doLength){let descriptor="length",itemsCount;if(objType==="map"||objType==="set")descriptor="size",itemsCount=obj.size;else itemsCount=obj.length;this.assert(itemsCount>=start&&itemsCount<=finish,"expected #{this} to have a "+descriptor+" within "+range,"expected #{this} to not have a "+descriptor+" within "+range)}else this.assert(obj>=start&&obj<=finish,"expected #{this} to be within "+range,"expected #{this} to not be within "+range)});function assertInstanceOf(constructor,msg){if(msg)flag2(this,"message",msg);let target=flag2(this,"object"),ssfi=flag2(this,"ssfi"),flagMsg=flag2(this,"message"),isInstanceOf;try{isInstanceOf=target instanceof constructor}catch(err){if(err instanceof TypeError)throw flagMsg=flagMsg?flagMsg+": ":"",new AssertionError(flagMsg+"The instanceof assertion needs a constructor but "+type(constructor)+" was given.",void 0,ssfi);throw err}let name=getName(constructor);if(name==null)name="an unnamed constructor";this.assert(isInstanceOf,"expected #{this} to be an instance of "+name,"expected #{this} to not be an instance of "+name)}__name(assertInstanceOf,"assertInstanceOf");Assertion.addMethod("instanceof",assertInstanceOf);Assertion.addMethod("instanceOf",assertInstanceOf);function assertProperty(name,val,msg){if(msg)flag2(this,"message",msg);let isNested=flag2(this,"nested"),isOwn=flag2(this,"own"),flagMsg=flag2(this,"message"),obj=flag2(this,"object"),ssfi=flag2(this,"ssfi"),nameType=typeof name;if(flagMsg=flagMsg?flagMsg+": ":"",isNested){if(nameType!=="string")throw new AssertionError(flagMsg+"the argument to property must be a string when using nested syntax",void 0,ssfi)}else if(nameType!=="string"&&nameType!=="number"&&nameType!=="symbol")throw new AssertionError(flagMsg+"the argument to property must be a string, number, or symbol",void 0,ssfi);if(isNested&&isOwn)throw new AssertionError(flagMsg+'The "nested" and "own" flags cannot be combined.',void 0,ssfi);if(obj===null||obj===void 0)throw new AssertionError(flagMsg+"Target cannot be null or undefined.",void 0,ssfi);let isDeep=flag2(this,"deep"),negate=flag2(this,"negate"),pathInfo=isNested?getPathInfo(obj,name):null,value=isNested?pathInfo.value:obj[name],isEql=isDeep?flag2(this,"eql"):(val1,val2)=>val1===val2,descriptor="";if(isDeep)descriptor+="deep ";if(isOwn)descriptor+="own ";if(isNested)descriptor+="nested ";descriptor+="property ";let hasProperty2;if(isOwn)hasProperty2=Object.prototype.hasOwnProperty.call(obj,name);else if(isNested)hasProperty2=pathInfo.exists;else hasProperty2=hasProperty(obj,name);if(!negate||arguments.length===1)this.assert(hasProperty2,"expected #{this} to have "+descriptor+inspect2(name),"expected #{this} to not have "+descriptor+inspect2(name));if(arguments.length>1)this.assert(hasProperty2&&isEql(val,value),"expected #{this} to have "+descriptor+inspect2(name)+" of #{exp}, but got #{act}","expected #{this} to not have "+descriptor+inspect2(name)+" of #{act}",val,value);flag2(this,"object",value)}__name(assertProperty,"assertProperty");Assertion.addMethod("property",assertProperty);function assertOwnProperty(_name,_value,_msg){flag2(this,"own",!0),assertProperty.apply(this,arguments)}__name(assertOwnProperty,"assertOwnProperty");Assertion.addMethod("ownProperty",assertOwnProperty);Assertion.addMethod("haveOwnProperty",assertOwnProperty);function assertOwnPropertyDescriptor(name,descriptor,msg){if(typeof descriptor==="string")msg=descriptor,descriptor=null;if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),actualDescriptor=Object.getOwnPropertyDescriptor(Object(obj),name),eql=flag2(this,"eql");if(actualDescriptor&&descriptor)this.assert(eql(descriptor,actualDescriptor),"expected the own property descriptor for "+inspect2(name)+" on #{this} to match "+inspect2(descriptor)+", got "+inspect2(actualDescriptor),"expected the own property descriptor for "+inspect2(name)+" on #{this} to not match "+inspect2(descriptor),descriptor,actualDescriptor,!0);else this.assert(actualDescriptor,"expected #{this} to have an own property descriptor for "+inspect2(name),"expected #{this} to not have an own property descriptor for "+inspect2(name));flag2(this,"object",actualDescriptor)}__name(assertOwnPropertyDescriptor,"assertOwnPropertyDescriptor");Assertion.addMethod("ownPropertyDescriptor",assertOwnPropertyDescriptor);Assertion.addMethod("haveOwnPropertyDescriptor",assertOwnPropertyDescriptor);function assertLengthChain(){flag2(this,"doLength",!0)}__name(assertLengthChain,"assertLengthChain");function assertLength(n,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),objType=type(obj).toLowerCase(),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi"),descriptor="length",itemsCount;switch(objType){case"map":case"set":descriptor="size",itemsCount=obj.size;break;default:new Assertion(obj,flagMsg,ssfi,!0).to.have.property("length"),itemsCount=obj.length}this.assert(itemsCount==n,"expected #{this} to have a "+descriptor+" of #{exp} but got #{act}","expected #{this} to not have a "+descriptor+" of #{act}",n,itemsCount)}__name(assertLength,"assertLength");Assertion.addChainableMethod("length",assertLength,assertLengthChain);Assertion.addChainableMethod("lengthOf",assertLength,assertLengthChain);function assertMatch(re,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object");this.assert(re.exec(obj),"expected #{this} to match "+re,"expected #{this} not to match "+re)}__name(assertMatch,"assertMatch");Assertion.addMethod("match",assertMatch);Assertion.addMethod("matches",assertMatch);Assertion.addMethod("string",function(str,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(obj,flagMsg,ssfi,!0).is.a("string"),this.assert(~obj.indexOf(str),"expected #{this} to contain "+inspect2(str),"expected #{this} to not contain "+inspect2(str))});function assertKeys(keys){let obj=flag2(this,"object"),objType=type(obj),keysType=type(keys),ssfi=flag2(this,"ssfi"),isDeep=flag2(this,"deep"),str,deepStr="",actual,ok=!0,flagMsg=flag2(this,"message");flagMsg=flagMsg?flagMsg+": ":"";let mixedArgsMsg=flagMsg+"when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments";if(objType==="Map"||objType==="Set"){if(deepStr=isDeep?"deeply ":"",actual=[],obj.forEach(function(val,key){actual.push(key)}),keysType!=="Array")keys=Array.prototype.slice.call(arguments)}else{switch(actual=getOwnEnumerableProperties(obj),keysType){case"Array":if(arguments.length>1)throw new AssertionError(mixedArgsMsg,void 0,ssfi);break;case"Object":if(arguments.length>1)throw new AssertionError(mixedArgsMsg,void 0,ssfi);keys=Object.keys(keys);break;default:keys=Array.prototype.slice.call(arguments)}keys=keys.map(function(val){return typeof val==="symbol"?val:String(val)})}if(!keys.length)throw new AssertionError(flagMsg+"keys required",void 0,ssfi);let len=keys.length,any=flag2(this,"any"),all=flag2(this,"all"),expected=keys,isEql=isDeep?flag2(this,"eql"):(val1,val2)=>val1===val2;if(!any&&!all)all=!0;if(any)ok=expected.some(function(expectedKey){return actual.some(function(actualKey){return isEql(expectedKey,actualKey)})});if(all){if(ok=expected.every(function(expectedKey){return actual.some(function(actualKey){return isEql(expectedKey,actualKey)})}),!flag2(this,"contains"))ok=ok&&keys.length==actual.length}if(len>1){keys=keys.map(function(key){return inspect2(key)});let last=keys.pop();if(all)str=keys.join(", ")+", and "+last;if(any)str=keys.join(", ")+", or "+last}else str=inspect2(keys[0]);str=(len>1?"keys ":"key ")+str,str=(flag2(this,"contains")?"contain ":"have ")+str,this.assert(ok,"expected #{this} to "+deepStr+str,"expected #{this} to not "+deepStr+str,expected.slice(0).sort(compareByInspect),actual.sort(compareByInspect),!0)}__name(assertKeys,"assertKeys");Assertion.addMethod("keys",assertKeys);Assertion.addMethod("key",assertKeys);function assertThrows(errorLike,errMsgMatcher,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),ssfi=flag2(this,"ssfi"),flagMsg=flag2(this,"message"),negate=flag2(this,"negate")||!1;if(new Assertion(obj,flagMsg,ssfi,!0).is.a("function"),isRegExp2(errorLike)||typeof errorLike==="string")errMsgMatcher=errorLike,errorLike=null;let caughtErr,errorWasThrown=!1;try{obj()}catch(err){errorWasThrown=!0,caughtErr=err}let everyArgIsUndefined=errorLike===void 0&&errMsgMatcher===void 0,everyArgIsDefined=Boolean(errorLike&&errMsgMatcher),errorLikeFail=!1,errMsgMatcherFail=!1;if(everyArgIsUndefined||!everyArgIsUndefined&&!negate){let errorLikeString="an error";if(errorLike instanceof Error)errorLikeString="#{exp}";else if(errorLike)errorLikeString=check_error_exports.getConstructorName(errorLike);let actual=caughtErr;if(caughtErr instanceof Error)actual=caughtErr.toString();else if(typeof caughtErr==="string")actual=caughtErr;else if(caughtErr&&(typeof caughtErr==="object"||typeof caughtErr==="function"))try{actual=check_error_exports.getConstructorName(caughtErr)}catch(_err){}this.assert(errorWasThrown,"expected #{this} to throw "+errorLikeString,"expected #{this} to not throw an error but #{act} was thrown",errorLike&&errorLike.toString(),actual)}if(errorLike&&caughtErr){if(errorLike instanceof Error){if(check_error_exports.compatibleInstance(caughtErr,errorLike)===negate)if(everyArgIsDefined&&negate)errorLikeFail=!0;else this.assert(negate,"expected #{this} to throw #{exp} but #{act} was thrown","expected #{this} to not throw #{exp}"+(caughtErr&&!negate?" but #{act} was thrown":""),errorLike.toString(),caughtErr.toString())}if(check_error_exports.compatibleConstructor(caughtErr,errorLike)===negate)if(everyArgIsDefined&&negate)errorLikeFail=!0;else this.assert(negate,"expected #{this} to throw #{exp} but #{act} was thrown","expected #{this} to not throw #{exp}"+(caughtErr?" but #{act} was thrown":""),errorLike instanceof Error?errorLike.toString():errorLike&&check_error_exports.getConstructorName(errorLike),caughtErr instanceof Error?caughtErr.toString():caughtErr&&check_error_exports.getConstructorName(caughtErr))}if(caughtErr&&errMsgMatcher!==void 0&&errMsgMatcher!==null){let placeholder="including";if(isRegExp2(errMsgMatcher))placeholder="matching";if(check_error_exports.compatibleMessage(caughtErr,errMsgMatcher)===negate)if(everyArgIsDefined&&negate)errMsgMatcherFail=!0;else this.assert(negate,"expected #{this} to throw error "+placeholder+" #{exp} but got #{act}","expected #{this} to throw error not "+placeholder+" #{exp}",errMsgMatcher,check_error_exports.getMessage(caughtErr))}if(errorLikeFail&&errMsgMatcherFail)this.assert(negate,"expected #{this} to throw #{exp} but #{act} was thrown","expected #{this} to not throw #{exp}"+(caughtErr?" but #{act} was thrown":""),errorLike instanceof Error?errorLike.toString():errorLike&&check_error_exports.getConstructorName(errorLike),caughtErr instanceof Error?caughtErr.toString():caughtErr&&check_error_exports.getConstructorName(caughtErr));flag2(this,"object",caughtErr)}__name(assertThrows,"assertThrows");Assertion.addMethod("throw",assertThrows);Assertion.addMethod("throws",assertThrows);Assertion.addMethod("Throw",assertThrows);function respondTo(method,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),itself=flag2(this,"itself"),context=typeof obj==="function"&&!itself?obj.prototype[method]:obj[method];this.assert(typeof context==="function","expected #{this} to respond to "+inspect2(method),"expected #{this} to not respond to "+inspect2(method))}__name(respondTo,"respondTo");Assertion.addMethod("respondTo",respondTo);Assertion.addMethod("respondsTo",respondTo);Assertion.addProperty("itself",function(){flag2(this,"itself",!0)});function satisfy(matcher,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),result=matcher(obj);this.assert(result,"expected #{this} to satisfy "+objDisplay(matcher),"expected #{this} to not satisfy"+objDisplay(matcher),flag2(this,"negate")?!1:!0,result)}__name(satisfy,"satisfy");Assertion.addMethod("satisfy",satisfy);Assertion.addMethod("satisfies",satisfy);function closeTo(expected,delta,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(obj,flagMsg,ssfi,!0).is.numeric;let message="A `delta` value is required for `closeTo`";if(delta==null)throw new AssertionError(flagMsg?`${flagMsg}: ${message}`:message,void 0,ssfi);if(new Assertion(delta,flagMsg,ssfi,!0).is.numeric,message="A `expected` value is required for `closeTo`",expected==null)throw new AssertionError(flagMsg?`${flagMsg}: ${message}`:message,void 0,ssfi);new Assertion(expected,flagMsg,ssfi,!0).is.numeric;let abs=__name((x)=>x<0?-x:x,"abs"),strip=__name((number)=>parseFloat(parseFloat(number).toPrecision(12)),"strip");this.assert(strip(abs(obj-expected))<=delta,"expected #{this} to be close to "+expected+" +/- "+delta,"expected #{this} not to be close to "+expected+" +/- "+delta)}__name(closeTo,"closeTo");Assertion.addMethod("closeTo",closeTo);Assertion.addMethod("approximately",closeTo);function isSubsetOf(_subset,_superset,cmp,contains,ordered){let superset=Array.from(_superset),subset=Array.from(_subset);if(!contains){if(subset.length!==superset.length)return!1;superset=superset.slice()}return subset.every(function(elem,idx){if(ordered)return cmp?cmp(elem,superset[idx]):elem===superset[idx];if(!cmp){let matchIdx=superset.indexOf(elem);if(matchIdx===-1)return!1;if(!contains)superset.splice(matchIdx,1);return!0}return superset.some(function(elem2,matchIdx){if(!cmp(elem,elem2))return!1;if(!contains)superset.splice(matchIdx,1);return!0})})}__name(isSubsetOf,"isSubsetOf");Assertion.addMethod("members",function(subset,msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(obj,flagMsg,ssfi,!0).to.be.iterable,new Assertion(subset,flagMsg,ssfi,!0).to.be.iterable;let contains=flag2(this,"contains"),ordered=flag2(this,"ordered"),subject,failMsg,failNegateMsg;if(contains)subject=ordered?"an ordered superset":"a superset",failMsg="expected #{this} to be "+subject+" of #{exp}",failNegateMsg="expected #{this} to not be "+subject+" of #{exp}";else subject=ordered?"ordered members":"members",failMsg="expected #{this} to have the same "+subject+" as #{exp}",failNegateMsg="expected #{this} to not have the same "+subject+" as #{exp}";let cmp=flag2(this,"deep")?flag2(this,"eql"):void 0;this.assert(isSubsetOf(subset,obj,cmp,contains,ordered),failMsg,failNegateMsg,subset,obj,!0)});Assertion.addProperty("iterable",function(msg){if(msg)flag2(this,"message",msg);let obj=flag2(this,"object");this.assert(obj!=null&&obj[Symbol.iterator],"expected #{this} to be an iterable","expected #{this} to not be an iterable",obj)});function oneOf(list,msg){if(msg)flag2(this,"message",msg);let expected=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi"),contains=flag2(this,"contains"),isDeep=flag2(this,"deep"),eql=flag2(this,"eql");if(new Assertion(list,flagMsg,ssfi,!0).to.be.an("array"),contains)this.assert(list.some(function(possibility){return expected.indexOf(possibility)>-1}),"expected #{this} to contain one of #{exp}","expected #{this} to not contain one of #{exp}",list,expected);else if(isDeep)this.assert(list.some(function(possibility){return eql(expected,possibility)}),"expected #{this} to deeply equal one of #{exp}","expected #{this} to deeply equal one of #{exp}",list,expected);else this.assert(list.indexOf(expected)>-1,"expected #{this} to be one of #{exp}","expected #{this} to not be one of #{exp}",list,expected)}__name(oneOf,"oneOf");Assertion.addMethod("oneOf",oneOf);function assertChanges(subject,prop,msg){if(msg)flag2(this,"message",msg);let fn=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(fn,flagMsg,ssfi,!0).is.a("function");let initial;if(!prop)new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject();else new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop];fn();let final=prop===void 0||prop===null?subject():subject[prop],msgObj=prop===void 0||prop===null?initial:"."+prop;flag2(this,"deltaMsgObj",msgObj),flag2(this,"initialDeltaValue",initial),flag2(this,"finalDeltaValue",final),flag2(this,"deltaBehavior","change"),flag2(this,"realDelta",final!==initial),this.assert(initial!==final,"expected "+msgObj+" to change","expected "+msgObj+" to not change")}__name(assertChanges,"assertChanges");Assertion.addMethod("change",assertChanges);Assertion.addMethod("changes",assertChanges);function assertIncreases(subject,prop,msg){if(msg)flag2(this,"message",msg);let fn=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(fn,flagMsg,ssfi,!0).is.a("function");let initial;if(!prop)new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject();else new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop];new Assertion(initial,flagMsg,ssfi,!0).is.a("number"),fn();let final=prop===void 0||prop===null?subject():subject[prop],msgObj=prop===void 0||prop===null?initial:"."+prop;flag2(this,"deltaMsgObj",msgObj),flag2(this,"initialDeltaValue",initial),flag2(this,"finalDeltaValue",final),flag2(this,"deltaBehavior","increase"),flag2(this,"realDelta",final-initial),this.assert(final-initial>0,"expected "+msgObj+" to increase","expected "+msgObj+" to not increase")}__name(assertIncreases,"assertIncreases");Assertion.addMethod("increase",assertIncreases);Assertion.addMethod("increases",assertIncreases);function assertDecreases(subject,prop,msg){if(msg)flag2(this,"message",msg);let fn=flag2(this,"object"),flagMsg=flag2(this,"message"),ssfi=flag2(this,"ssfi");new Assertion(fn,flagMsg,ssfi,!0).is.a("function");let initial;if(!prop)new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject();else new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop];new Assertion(initial,flagMsg,ssfi,!0).is.a("number"),fn();let final=prop===void 0||prop===null?subject():subject[prop],msgObj=prop===void 0||prop===null?initial:"."+prop;flag2(this,"deltaMsgObj",msgObj),flag2(this,"initialDeltaValue",initial),flag2(this,"finalDeltaValue",final),flag2(this,"deltaBehavior","decrease"),flag2(this,"realDelta",initial-final),this.assert(final-initial<0,"expected "+msgObj+" to decrease","expected "+msgObj+" to not decrease")}__name(assertDecreases,"assertDecreases");Assertion.addMethod("decrease",assertDecreases);Assertion.addMethod("decreases",assertDecreases);function assertDelta(delta,msg){if(msg)flag2(this,"message",msg);let msgObj=flag2(this,"deltaMsgObj"),initial=flag2(this,"initialDeltaValue"),final=flag2(this,"finalDeltaValue"),behavior=flag2(this,"deltaBehavior"),realDelta=flag2(this,"realDelta"),expression;if(behavior==="change")expression=Math.abs(final-initial)===Math.abs(delta);else expression=realDelta===Math.abs(delta);this.assert(expression,"expected "+msgObj+" to "+behavior+" by "+delta,"expected "+msgObj+" to not "+behavior+" by "+delta)}__name(assertDelta,"assertDelta");Assertion.addMethod("by",assertDelta);Assertion.addProperty("extensible",function(){let obj=flag2(this,"object"),isExtensible=obj===Object(obj)&&Object.isExtensible(obj);this.assert(isExtensible,"expected #{this} to be extensible","expected #{this} to not be extensible")});Assertion.addProperty("sealed",function(){let obj=flag2(this,"object"),isSealed=obj===Object(obj)?Object.isSealed(obj):!0;this.assert(isSealed,"expected #{this} to be sealed","expected #{this} to not be sealed")});Assertion.addProperty("frozen",function(){let obj=flag2(this,"object"),isFrozen=obj===Object(obj)?Object.isFrozen(obj):!0;this.assert(isFrozen,"expected #{this} to be frozen","expected #{this} to not be frozen")});Assertion.addProperty("finite",function(_msg){let obj=flag2(this,"object");this.assert(typeof obj==="number"&&isFinite(obj),"expected #{this} to be a finite number","expected #{this} to not be a finite number")});function compareSubset(expected,actual){if(expected===actual)return!0;if(typeof actual!==typeof expected)return!1;if(typeof expected!=="object"||expected===null)return expected===actual;if(!actual)return!1;if(Array.isArray(expected)){if(!Array.isArray(actual))return!1;return expected.every(function(exp){return actual.some(function(act){return compareSubset(exp,act)})})}if(expected instanceof Date)if(actual instanceof Date)return expected.getTime()===actual.getTime();else return!1;return Object.keys(expected).every(function(key){let expectedValue=expected[key],actualValue=actual[key];if(typeof expectedValue==="object"&&expectedValue!==null&&actualValue!==null)return compareSubset(expectedValue,actualValue);if(typeof expectedValue==="function")return expectedValue(actualValue);return actualValue===expectedValue})}__name(compareSubset,"compareSubset");Assertion.addMethod("containSubset",function(expected){let actual=flag(this,"object"),showDiff=config.showDiff;this.assert(compareSubset(expected,actual),"expected #{act} to contain subset #{exp}","expected #{act} to not contain subset #{exp}",expected,actual,showDiff)});function expect(val,message){return new Assertion(val,message)}__name(expect,"expect");expect.fail=function(actual,expected,message,operator){if(arguments.length<2)message=actual,actual=void 0;throw message=message||"expect.fail()",new AssertionError(message,{actual,expected,operator},expect.fail)};var should_exports={};__export(should_exports,{Should:()=>Should,should:()=>should});function loadShould(){function shouldGetter(){if(this instanceof String||this instanceof Number||this instanceof Boolean||typeof Symbol==="function"&&this instanceof Symbol||typeof BigInt==="function"&&this instanceof BigInt)return new Assertion(this.valueOf(),null,shouldGetter);return new Assertion(this,null,shouldGetter)}__name(shouldGetter,"shouldGetter");function shouldSetter(value){Object.defineProperty(this,"should",{value,enumerable:!0,configurable:!0,writable:!0})}__name(shouldSetter,"shouldSetter"),Object.defineProperty(Object.prototype,"should",{set:shouldSetter,get:shouldGetter,configurable:!0});let should2={};return should2.fail=function(actual,expected,message,operator){if(arguments.length<2)message=actual,actual=void 0;throw message=message||"should.fail()",new AssertionError(message,{actual,expected,operator},should2.fail)},should2.equal=function(actual,expected,message){new Assertion(actual,message).to.equal(expected)},should2.Throw=function(fn,errt,errs,msg){new Assertion(fn,msg).to.Throw(errt,errs)},should2.exist=function(val,msg){new Assertion(val,msg).to.exist},should2.not={},should2.not.equal=function(actual,expected,msg){new Assertion(actual,msg).to.not.equal(expected)},should2.not.Throw=function(fn,errt,errs,msg){new Assertion(fn,msg).to.not.Throw(errt,errs)},should2.not.exist=function(val,msg){new Assertion(val,msg).to.not.exist},should2.throw=should2.Throw,should2.not.throw=should2.not.Throw,should2}__name(loadShould,"loadShould");var should=loadShould,Should=loadShould;function assert(express,errmsg){new Assertion(null,null,assert,!0).assert(express,errmsg,"[ negation message unavailable ]")}__name(assert,"assert");assert.fail=function(actual,expected,message,operator){if(arguments.length<2)message=actual,actual=void 0;throw message=message||"assert.fail()",new AssertionError(message,{actual,expected,operator},assert.fail)};assert.isOk=function(val,msg){new Assertion(val,msg,assert.isOk,!0).is.ok};assert.isNotOk=function(val,msg){new Assertion(val,msg,assert.isNotOk,!0).is.not.ok};assert.equal=function(act,exp,msg){let test2=new Assertion(act,msg,assert.equal,!0);test2.assert(exp==flag(test2,"object"),"expected #{this} to equal #{exp}","expected #{this} to not equal #{act}",exp,act,!0)};assert.notEqual=function(act,exp,msg){let test2=new Assertion(act,msg,assert.notEqual,!0);test2.assert(exp!=flag(test2,"object"),"expected #{this} to not equal #{exp}","expected #{this} to equal #{act}",exp,act,!0)};assert.strictEqual=function(act,exp,msg){new Assertion(act,msg,assert.strictEqual,!0).to.equal(exp)};assert.notStrictEqual=function(act,exp,msg){new Assertion(act,msg,assert.notStrictEqual,!0).to.not.equal(exp)};assert.deepEqual=assert.deepStrictEqual=function(act,exp,msg){new Assertion(act,msg,assert.deepEqual,!0).to.eql(exp)};assert.notDeepEqual=function(act,exp,msg){new Assertion(act,msg,assert.notDeepEqual,!0).to.not.eql(exp)};assert.isAbove=function(val,abv,msg){new Assertion(val,msg,assert.isAbove,!0).to.be.above(abv)};assert.isAtLeast=function(val,atlst,msg){new Assertion(val,msg,assert.isAtLeast,!0).to.be.least(atlst)};assert.isBelow=function(val,blw,msg){new Assertion(val,msg,assert.isBelow,!0).to.be.below(blw)};assert.isAtMost=function(val,atmst,msg){new Assertion(val,msg,assert.isAtMost,!0).to.be.most(atmst)};assert.isTrue=function(val,msg){new Assertion(val,msg,assert.isTrue,!0).is.true};assert.isNotTrue=function(val,msg){new Assertion(val,msg,assert.isNotTrue,!0).to.not.equal(!0)};assert.isFalse=function(val,msg){new Assertion(val,msg,assert.isFalse,!0).is.false};assert.isNotFalse=function(val,msg){new Assertion(val,msg,assert.isNotFalse,!0).to.not.equal(!1)};assert.isNull=function(val,msg){new Assertion(val,msg,assert.isNull,!0).to.equal(null)};assert.isNotNull=function(val,msg){new Assertion(val,msg,assert.isNotNull,!0).to.not.equal(null)};assert.isNaN=function(val,msg){new Assertion(val,msg,assert.isNaN,!0).to.be.NaN};assert.isNotNaN=function(value,message){new Assertion(value,message,assert.isNotNaN,!0).not.to.be.NaN};assert.exists=function(val,msg){new Assertion(val,msg,assert.exists,!0).to.exist};assert.notExists=function(val,msg){new Assertion(val,msg,assert.notExists,!0).to.not.exist};assert.isUndefined=function(val,msg){new Assertion(val,msg,assert.isUndefined,!0).to.equal(void 0)};assert.isDefined=function(val,msg){new Assertion(val,msg,assert.isDefined,!0).to.not.equal(void 0)};assert.isCallable=function(value,message){new Assertion(value,message,assert.isCallable,!0).is.callable};assert.isNotCallable=function(value,message){new Assertion(value,message,assert.isNotCallable,!0).is.not.callable};assert.isObject=function(val,msg){new Assertion(val,msg,assert.isObject,!0).to.be.a("object")};assert.isNotObject=function(val,msg){new Assertion(val,msg,assert.isNotObject,!0).to.not.be.a("object")};assert.isArray=function(val,msg){new Assertion(val,msg,assert.isArray,!0).to.be.an("array")};assert.isNotArray=function(val,msg){new Assertion(val,msg,assert.isNotArray,!0).to.not.be.an("array")};assert.isString=function(val,msg){new Assertion(val,msg,assert.isString,!0).to.be.a("string")};assert.isNotString=function(val,msg){new Assertion(val,msg,assert.isNotString,!0).to.not.be.a("string")};assert.isNumber=function(val,msg){new Assertion(val,msg,assert.isNumber,!0).to.be.a("number")};assert.isNotNumber=function(val,msg){new Assertion(val,msg,assert.isNotNumber,!0).to.not.be.a("number")};assert.isNumeric=function(val,msg){new Assertion(val,msg,assert.isNumeric,!0).is.numeric};assert.isNotNumeric=function(val,msg){new Assertion(val,msg,assert.isNotNumeric,!0).is.not.numeric};assert.isFinite=function(val,msg){new Assertion(val,msg,assert.isFinite,!0).to.be.finite};assert.isBoolean=function(val,msg){new Assertion(val,msg,assert.isBoolean,!0).to.be.a("boolean")};assert.isNotBoolean=function(val,msg){new Assertion(val,msg,assert.isNotBoolean,!0).to.not.be.a("boolean")};assert.typeOf=function(val,type3,msg){new Assertion(val,msg,assert.typeOf,!0).to.be.a(type3)};assert.notTypeOf=function(value,type3,message){new Assertion(value,message,assert.notTypeOf,!0).to.not.be.a(type3)};assert.instanceOf=function(val,type3,msg){new Assertion(val,msg,assert.instanceOf,!0).to.be.instanceOf(type3)};assert.notInstanceOf=function(val,type3,msg){new Assertion(val,msg,assert.notInstanceOf,!0).to.not.be.instanceOf(type3)};assert.include=function(exp,inc,msg){new Assertion(exp,msg,assert.include,!0).include(inc)};assert.notInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notInclude,!0).not.include(inc)};assert.deepInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.deepInclude,!0).deep.include(inc)};assert.notDeepInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notDeepInclude,!0).not.deep.include(inc)};assert.nestedInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.nestedInclude,!0).nested.include(inc)};assert.notNestedInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notNestedInclude,!0).not.nested.include(inc)};assert.deepNestedInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.deepNestedInclude,!0).deep.nested.include(inc)};assert.notDeepNestedInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notDeepNestedInclude,!0).not.deep.nested.include(inc)};assert.ownInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.ownInclude,!0).own.include(inc)};assert.notOwnInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notOwnInclude,!0).not.own.include(inc)};assert.deepOwnInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.deepOwnInclude,!0).deep.own.include(inc)};assert.notDeepOwnInclude=function(exp,inc,msg){new Assertion(exp,msg,assert.notDeepOwnInclude,!0).not.deep.own.include(inc)};assert.match=function(exp,re,msg){new Assertion(exp,msg,assert.match,!0).to.match(re)};assert.notMatch=function(exp,re,msg){new Assertion(exp,msg,assert.notMatch,!0).to.not.match(re)};assert.property=function(obj,prop,msg){new Assertion(obj,msg,assert.property,!0).to.have.property(prop)};assert.notProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.notProperty,!0).to.not.have.property(prop)};assert.propertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.propertyVal,!0).to.have.property(prop,val)};assert.notPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.notPropertyVal,!0).to.not.have.property(prop,val)};assert.deepPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.deepPropertyVal,!0).to.have.deep.property(prop,val)};assert.notDeepPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.notDeepPropertyVal,!0).to.not.have.deep.property(prop,val)};assert.ownProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.ownProperty,!0).to.have.own.property(prop)};assert.notOwnProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.notOwnProperty,!0).to.not.have.own.property(prop)};assert.ownPropertyVal=function(obj,prop,value,msg){new Assertion(obj,msg,assert.ownPropertyVal,!0).to.have.own.property(prop,value)};assert.notOwnPropertyVal=function(obj,prop,value,msg){new Assertion(obj,msg,assert.notOwnPropertyVal,!0).to.not.have.own.property(prop,value)};assert.deepOwnPropertyVal=function(obj,prop,value,msg){new Assertion(obj,msg,assert.deepOwnPropertyVal,!0).to.have.deep.own.property(prop,value)};assert.notDeepOwnPropertyVal=function(obj,prop,value,msg){new Assertion(obj,msg,assert.notDeepOwnPropertyVal,!0).to.not.have.deep.own.property(prop,value)};assert.nestedProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.nestedProperty,!0).to.have.nested.property(prop)};assert.notNestedProperty=function(obj,prop,msg){new Assertion(obj,msg,assert.notNestedProperty,!0).to.not.have.nested.property(prop)};assert.nestedPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.nestedPropertyVal,!0).to.have.nested.property(prop,val)};assert.notNestedPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.notNestedPropertyVal,!0).to.not.have.nested.property(prop,val)};assert.deepNestedPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.deepNestedPropertyVal,!0).to.have.deep.nested.property(prop,val)};assert.notDeepNestedPropertyVal=function(obj,prop,val,msg){new Assertion(obj,msg,assert.notDeepNestedPropertyVal,!0).to.not.have.deep.nested.property(prop,val)};assert.lengthOf=function(exp,len,msg){new Assertion(exp,msg,assert.lengthOf,!0).to.have.lengthOf(len)};assert.hasAnyKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.hasAnyKeys,!0).to.have.any.keys(keys)};assert.hasAllKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.hasAllKeys,!0).to.have.all.keys(keys)};assert.containsAllKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.containsAllKeys,!0).to.contain.all.keys(keys)};assert.doesNotHaveAnyKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.doesNotHaveAnyKeys,!0).to.not.have.any.keys(keys)};assert.doesNotHaveAllKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.doesNotHaveAllKeys,!0).to.not.have.all.keys(keys)};assert.hasAnyDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.hasAnyDeepKeys,!0).to.have.any.deep.keys(keys)};assert.hasAllDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.hasAllDeepKeys,!0).to.have.all.deep.keys(keys)};assert.containsAllDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.containsAllDeepKeys,!0).to.contain.all.deep.keys(keys)};assert.doesNotHaveAnyDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.doesNotHaveAnyDeepKeys,!0).to.not.have.any.deep.keys(keys)};assert.doesNotHaveAllDeepKeys=function(obj,keys,msg){new Assertion(obj,msg,assert.doesNotHaveAllDeepKeys,!0).to.not.have.all.deep.keys(keys)};assert.throws=function(fn,errorLike,errMsgMatcher,msg){if(typeof errorLike==="string"||errorLike instanceof RegExp)errMsgMatcher=errorLike,errorLike=null;let assertErr=new Assertion(fn,msg,assert.throws,!0).to.throw(errorLike,errMsgMatcher);return flag(assertErr,"object")};assert.doesNotThrow=function(fn,errorLike,errMsgMatcher,message){if(typeof errorLike==="string"||errorLike instanceof RegExp)errMsgMatcher=errorLike,errorLike=null;new Assertion(fn,message,assert.doesNotThrow,!0).to.not.throw(errorLike,errMsgMatcher)};assert.operator=function(val,operator,val2,msg){let ok;switch(operator){case"==":ok=val==val2;break;case"===":ok=val===val2;break;case">":ok=val>val2;break;case">=":ok=val>=val2;break;case"<":ok=val<val2;break;case"<=":ok=val<=val2;break;case"!=":ok=val!=val2;break;case"!==":ok=val!==val2;break;default:throw msg=msg?msg+": ":msg,new AssertionError(msg+'Invalid operator "'+operator+'"',void 0,assert.operator)}let test2=new Assertion(ok,msg,assert.operator,!0);test2.assert(flag(test2,"object")===!0,"expected "+inspect2(val)+" to be "+operator+" "+inspect2(val2),"expected "+inspect2(val)+" to not be "+operator+" "+inspect2(val2))};assert.closeTo=function(act,exp,delta,msg){new Assertion(act,msg,assert.closeTo,!0).to.be.closeTo(exp,delta)};assert.approximately=function(act,exp,delta,msg){new Assertion(act,msg,assert.approximately,!0).to.be.approximately(exp,delta)};assert.sameMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.sameMembers,!0).to.have.same.members(set2)};assert.notSameMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.notSameMembers,!0).to.not.have.same.members(set2)};assert.sameDeepMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.sameDeepMembers,!0).to.have.same.deep.members(set2)};assert.notSameDeepMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.notSameDeepMembers,!0).to.not.have.same.deep.members(set2)};assert.sameOrderedMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.sameOrderedMembers,!0).to.have.same.ordered.members(set2)};assert.notSameOrderedMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.notSameOrderedMembers,!0).to.not.have.same.ordered.members(set2)};assert.sameDeepOrderedMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.sameDeepOrderedMembers,!0).to.have.same.deep.ordered.members(set2)};assert.notSameDeepOrderedMembers=function(set1,set2,msg){new Assertion(set1,msg,assert.notSameDeepOrderedMembers,!0).to.not.have.same.deep.ordered.members(set2)};assert.includeMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.includeMembers,!0).to.include.members(subset)};assert.notIncludeMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.notIncludeMembers,!0).to.not.include.members(subset)};assert.includeDeepMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.includeDeepMembers,!0).to.include.deep.members(subset)};assert.notIncludeDeepMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.notIncludeDeepMembers,!0).to.not.include.deep.members(subset)};assert.includeOrderedMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.includeOrderedMembers,!0).to.include.ordered.members(subset)};assert.notIncludeOrderedMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.notIncludeOrderedMembers,!0).to.not.include.ordered.members(subset)};assert.includeDeepOrderedMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.includeDeepOrderedMembers,!0).to.include.deep.ordered.members(subset)};assert.notIncludeDeepOrderedMembers=function(superset,subset,msg){new Assertion(superset,msg,assert.notIncludeDeepOrderedMembers,!0).to.not.include.deep.ordered.members(subset)};assert.oneOf=function(inList,list,msg){new Assertion(inList,msg,assert.oneOf,!0).to.be.oneOf(list)};assert.isIterable=function(obj,msg){if(obj==null||!obj[Symbol.iterator])throw msg=msg?`${msg} expected ${inspect2(obj)} to be an iterable`:`expected ${inspect2(obj)} to be an iterable`,new AssertionError(msg,void 0,assert.isIterable)};assert.changes=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;new Assertion(fn,msg,assert.changes,!0).to.change(obj,prop)};assert.changesBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.changesBy,!0).to.change(obj,prop).by(delta)};assert.doesNotChange=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.doesNotChange,!0).to.not.change(obj,prop)};assert.changesButNotBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.changesButNotBy,!0).to.change(obj,prop).but.not.by(delta)};assert.increases=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.increases,!0).to.increase(obj,prop)};assert.increasesBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.increasesBy,!0).to.increase(obj,prop).by(delta)};assert.doesNotIncrease=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.doesNotIncrease,!0).to.not.increase(obj,prop)};assert.increasesButNotBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.increasesButNotBy,!0).to.increase(obj,prop).but.not.by(delta)};assert.decreases=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.decreases,!0).to.decrease(obj,prop)};assert.decreasesBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.decreasesBy,!0).to.decrease(obj,prop).by(delta)};assert.doesNotDecrease=function(fn,obj,prop,msg){if(arguments.length===3&&typeof obj==="function")msg=prop,prop=null;return new Assertion(fn,msg,assert.doesNotDecrease,!0).to.not.decrease(obj,prop)};assert.doesNotDecreaseBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;return new Assertion(fn,msg,assert.doesNotDecreaseBy,!0).to.not.decrease(obj,prop).by(delta)};assert.decreasesButNotBy=function(fn,obj,prop,delta,msg){if(arguments.length===4&&typeof obj==="function"){let tmpMsg=delta;delta=prop,msg=tmpMsg}else if(arguments.length===3)delta=prop,prop=null;new Assertion(fn,msg,assert.decreasesButNotBy,!0).to.decrease(obj,prop).but.not.by(delta)};assert.ifError=function(val){if(val)throw val};assert.isExtensible=function(obj,msg){new Assertion(obj,msg,assert.isExtensible,!0).to.be.extensible};assert.isNotExtensible=function(obj,msg){new Assertion(obj,msg,assert.isNotExtensible,!0).to.not.be.extensible};assert.isSealed=function(obj,msg){new Assertion(obj,msg,assert.isSealed,!0).to.be.sealed};assert.isNotSealed=function(obj,msg){new Assertion(obj,msg,assert.isNotSealed,!0).to.not.be.sealed};assert.isFrozen=function(obj,msg){new Assertion(obj,msg,assert.isFrozen,!0).to.be.frozen};assert.isNotFrozen=function(obj,msg){new Assertion(obj,msg,assert.isNotFrozen,!0).to.not.be.frozen};assert.isEmpty=function(val,msg){new Assertion(val,msg,assert.isEmpty,!0).to.be.empty};assert.isNotEmpty=function(val,msg){new Assertion(val,msg,assert.isNotEmpty,!0).to.not.be.empty};assert.containsSubset=function(val,exp,msg){new Assertion(val,msg).to.containSubset(exp)};assert.doesNotContainSubset=function(val,exp,msg){new Assertion(val,msg).to.not.containSubset(exp)};var aliases=[["isOk","ok"],["isNotOk","notOk"],["throws","throw"],["throws","Throw"],["isExtensible","extensible"],["isNotExtensible","notExtensible"],["isSealed","sealed"],["isNotSealed","notSealed"],["isFrozen","frozen"],["isNotFrozen","notFrozen"],["isEmpty","empty"],["isNotEmpty","notEmpty"],["isCallable","isFunction"],["isNotCallable","isNotFunction"],["containsSubset","containSubset"]];for(let[name,as]of aliases)assert[as]=assert[name];var used=[];function use(fn){let exports={use,AssertionError,util:utils_exports,config,expect,assert,Assertion,...should_exports};if(!~used.indexOf(fn))fn(exports,utils_exports),used.push(fn);return exports}__name(use,"use");function invariant(condition,error){if(!condition)throw Error(error)}function assertNotInfinite(size){invariant(size!==1/0,"Cannot perform this action with an infinite size.")}function reduce(collection,reducer,reduction,context,useFirst,reverse){return assertNotInfinite(collection.size),collection.__iterate((v,k,c)=>{if(useFirst)useFirst=!1,reduction=v;else reduction=reducer.call(context,reduction,v,k,c)},reverse),reduction}var keyMapper=(v,k)=>k,entryMapper=(v,k)=>[k,v],not=(predicate)=>function(...args){return!predicate.apply(this,args)},neg=(predicate)=>function(...args){return-predicate.apply(this,args)};function defaultComparator(a,b){if(a===void 0&&b===void 0)return 0;if(a===void 0)return 1;if(b===void 0)return-1;return a>b?1:a<b?-1:0}var defaultNegComparator=(a,b)=>a<b?1:a>b?-1:0,DONE={done:!0,value:void 0};class Iter{constructor(next){this.next=next}[Symbol.iterator](){return this}}function makeIterator(next){return new Iter(next)}function makeEntryIterator(next){let entry=[void 0,void 0],result={done:!1,value:void 0};return makeIterator(()=>{if(next(entry))return result.value=[entry[0],entry[1]],result;return DONE})}var EMPTY_ITERATOR=makeIterator(()=>DONE),emptyIterator=()=>EMPTY_ITERATOR;function makeIndexKeys(size){let i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return result.value=i++,result})}function mapEntries(source,transform){return makeEntryIterator((entry)=>{let step=source.next();if(step.done)return!1;return transform(step.value[0],step.value[1],entry),!0})}function hasIterator(maybeIterable){if(Array.isArray(maybeIterable))return!0;return!!getIteratorFn(maybeIterable)}var isIterator=(maybeIterator)=>typeof maybeIterator?.next==="function";function getIterator(iterable){return getIteratorFn(iterable)?.call(iterable)}function getIteratorFn(iterable){let iteratorFn=iterable?.[Symbol.iterator];if(typeof iteratorFn==="function")return iteratorFn}function isEntriesIterable(maybeIterable){let iteratorFn=getIteratorFn(maybeIterable);return iteratorFn&&iteratorFn===maybeIterable.entries}function isKeysIterable(maybeIterable){let iteratorFn=getIteratorFn(maybeIterable);return iteratorFn&&iteratorFn===maybeIterable.keys}var DELETE="delete",SHIFT=5,SIZE=1<<SHIFT,MASK=SIZE-1,NOT_SET={},MakeRef=()=>({value:!1});function SetRef(ref){if(ref)ref.value=!0}class OwnerID{}function ensureSize(iter){if(iter.size===void 0)iter.size=iter.__iterate(returnTrue);return iter.size}function wrapIndex(iter,index){if(typeof index!=="number"){let uint32Index=index>>>0;if(String(uint32Index)!==index||uint32Index===4294967295)return NaN;index=uint32Index}return index<0?ensureSize(iter)+index:index}var returnTrue=()=>!0,isNeg=(value)=>value<0||Object.is(value,-0),wholeSlice=(begin,end,size)=>(begin===0&&!isNeg(begin)||size!==void 0&&(begin??0)<=-size)&&(end===void 0||size!==void 0&&end>=size),resolveIndex=(index,size,defaultIndex)=>index===void 0?defaultIndex:isNeg(index)?size===1/0?size:Math.max(0,size+index)|0:size===void 0||size===index?index:Math.min(size,index)|0,resolveBegin=(begin,size)=>resolveIndex(begin,size,0),resolveEnd=(end,size)=>resolveIndex(end,size,size),IS_COLLECTION_SYMBOL="@@__IMMUTABLE_ITERABLE__@@",IS_KEYED_SYMBOL="@@__IMMUTABLE_KEYED__@@",IS_INDEXED_SYMBOL="@@__IMMUTABLE_INDEXED__@@",IS_ORDERED_SYMBOL="@@__IMMUTABLE_ORDERED__@@",IS_SEQ_SYMBOL="@@__IMMUTABLE_SEQ__@@",IS_LIST_SYMBOL="@@__IMMUTABLE_LIST__@@",IS_MAP_SYMBOL="@@__IMMUTABLE_MAP__@@",IS_SET_SYMBOL="@@__IMMUTABLE_SET__@@",IS_STACK_SYMBOL="@@__IMMUTABLE_STACK__@@",IS_RECORD_SYMBOL="@@__IMMUTABLE_RECORD__@@";function hasSymbol(v,symbol){return typeof v==="object"&&v!==null&&symbol in v}var isCollection=(v)=>hasSymbol(v,IS_COLLECTION_SYMBOL),isKeyed=(v)=>hasSymbol(v,IS_KEYED_SYMBOL),isIndexed=(v)=>hasSymbol(v,IS_INDEXED_SYMBOL),isAssociative=(v)=>isKeyed(v)||isIndexed(v),isOrdered=(v)=>hasSymbol(v,IS_ORDERED_SYMBOL),isSeq=(v)=>hasSymbol(v,IS_SEQ_SYMBOL),isList=(v)=>hasSymbol(v,IS_LIST_SYMBOL),isMap=(v)=>hasSymbol(v,IS_MAP_SYMBOL),isSet=(v)=>hasSymbol(v,IS_SET_SYMBOL),isStack=(v)=>hasSymbol(v,IS_STACK_SYMBOL),isRecord=(v)=>hasSymbol(v,IS_RECORD_SYMBOL),isImmutable=(v)=>isCollection(v)||isRecord(v),isOrderedMap=(v)=>isMap(v)&&isOrdered(v),isOrderedSet=(v)=>isSet(v)&&isOrdered(v),isValueObject=(v)=>typeof v==="object"&&v!==null&&typeof v.equals==="function"&&typeof v.hashCode==="function";function flipFactory(collection){let flipSequence=makeSequence(collection);return flipSequence._iter=collection,flipSequence.size=collection.size,flipSequence.flip=()=>collection,flipSequence.reverse=function(){let reversedSequence=collection.reverse.call(this);return reversedSequence.flip=()=>collection.reverse(),reversedSequence},flipSequence.has=(key)=>collection.includes(key),flipSequence.includes=(key)=>collection.has(key),flipSequence.cacheResult=cacheResultThrough,flipSequence.__iterate=function(fn,reverse){return collection.__iterate((v,k)=>fn(k,v,this),reverse)},flipSequence.__iteratorUncached=(reverse)=>mapEntries(collection.__iterator(reverse),(k,v,entry)=>{entry[0]=v,entry[1]=k}),flipSequence}function mapFactory(collection,mapper,context){let mappedSequence=makeSequence(collection);return mappedSequence.size=collection.size,mappedSequence.has=(key)=>collection.has(key),mappedSequence.get=(key,notSetValue)=>{let v=collection.get(key,NOT_SET);return v===NOT_SET?notSetValue:mapper.call(context,v,key,collection)},mappedSequence.__iterate=function(fn,reverse){return collection.__iterate((v,k)=>fn(mapper.call(context,v,k,collection),k,this),reverse)},mappedSequence.__iteratorUncached=(reverse)=>mapEntries(collection.__iterator(reverse),(k,v,entry)=>{entry[0]=k,entry[1]=mapper.call(context,v,k,collection)}),mappedSequence}function reverseFactory(collection,useKeys){let reversedSequence=makeSequence(collection);if(reversedSequence._iter=collection,reversedSequence.size=collection.size,reversedSequence.reverse=()=>collection,collection.flip)reversedSequence.flip=function(){let flipSequence=flipFactory(collection);return flipSequence.reverse=()=>collection.flip(),flipSequence};return reversedSequence.get=(key,notSetValue)=>collection.get(useKeys?key:-1-key,notSetValue),reversedSequence.has=(key)=>collection.has(useKeys?key:-1-key),reversedSequence.includes=(value)=>collection.includes(value),reversedSequence.cacheResult=cacheResultThrough,reversedSequence.__iterate=function(fn,reverse){let i=0;if(reverse)ensureSize(collection);return collection.__iterate((v,k)=>fn(v,useKeys?k:reverse?this.size-++i:i++,this),!reverse)},reversedSequence.__iteratorUncached=function(reverse){let i=0;if(reverse)ensureSize(collection);let size=this.size;return mapEntries(collection.__iterator(!reverse),(k,v,entry)=>{entry[0]=useKeys?k:reverse?size-++i:i++,entry[1]=v})},reversedSequence}function sliceFactory(collection,begin,end,useKeys){let originalSize=collection.size;if(wholeSlice(begin,end,originalSize))return collection;if(originalSize===void 0&&(begin<0||end<0))return sliceFactory(collection.toSeq().cacheResult(),begin,end,useKeys);let resolvedBegin=resolveBegin(begin,originalSize),resolvedSize=resolveEnd(end,originalSize)-resolvedBegin,sliceSize;if(!Number.isNaN(resolvedSize))sliceSize=Math.max(0,resolvedSize);let sliceSeq=makeSequence(collection);if(sliceSeq.size=sliceSize===0?sliceSize:collection.size&&sliceSize||void 0,!useKeys&&isSeq(collection)&&sliceSize>=0)sliceSeq.get=function(index,notSetValue){return index=wrapIndex(this,index),index>=0&&index<sliceSize?collection.get(index+resolvedBegin,notSetValue):notSetValue};return sliceSeq.__iterateUncached=function(fn,reverse){if(sliceSize!==0&&reverse)return this.cacheResult().__iterate(fn,reverse);if(sliceSize===0)return 0;let skipped=0,iterations=0;return collection.__iterate((v,k)=>{if(skipped<resolvedBegin){skipped++;return}if(sliceSize!==void 0&&iterations>=sliceSize)return!1;if(iterations++,fn(v,useKeys?k:iterations-1,this)===!1)return!1},reverse),iterations},sliceSeq.__iteratorUncached=function(reverse){if(sliceSize!==0&&reverse)return this.cacheResult().__iterator(reverse);if(sliceSize===0)return emptyIterator();let iterator=collection.__iterator(reverse),skipped=0,iterations=0;if(useKeys)return makeIterator(()=>{while(skipped<resolvedBegin)skipped++,iterator.next();if(sliceSize!==void 0&&iterations>=sliceSize)return DONE;let step=iterator.next();if(step.done)return step;return iterations++,step});return makeEntryIterator((entry)=>{while(skipped<resolvedBegin)skipped++,iterator.next();if(sliceSize!==void 0&&iterations>=sliceSize)return!1;let step=iterator.next();if(step.done)return!1;return iterations++,entry[0]=iterations-1,entry[1]=step.value[1],!0})},sliceSeq}function sortFactory(collection,comparator,mapper){if(!comparator)comparator=defaultComparator;let isKeyedCollection=isKeyed(collection),index=0,entries=collection.toSeq().map((v,k)=>[k,v,index++,mapper?mapper(v,k,collection):v]).valueSeq().toArray();return entries.sort((a,b)=>comparator(a[3],b[3])||a[2]-b[2]).forEach(isKeyedCollection?(v,i)=>{entries[i].length=2}:(v,i)=>{entries[i]=v[1]}),isKeyedCollection?KeyedSeq(entries):isIndexed(collection)?IndexedSeq(entries):SetSeq(entries)}function maxFactory(collection,comparator,mapper){if(!comparator)comparator=defaultComparator;if(mapper)return collection.toSeq().map((v,k)=>[v,mapper(v,k,collection)]).reduce((a,b)=>maxCompare(comparator,a[1],b[1])?b:a)?.[0];return collection.reduce((a,b)=>maxCompare(comparator,a,b)?b:a)}function maxCompare(comparator,a,b){let comp=comparator(b,a);return comp===0&&b!==a&&(b===void 0||b===null||Number.isNaN(b))||comp>0}function zipWithFactory(keyIter,zipper,iters,zipAll){let zipSequence=makeSequence(keyIter),sizes=new ArraySeq(iters).map((i)=>i.size);return zipSequence.size=zipAll?sizes.max():sizes.min(),zipSequence.__iterate=function(fn,reverse){let iterator=this.__iterator(reverse),iterations=0,step;while(!(step=iterator.next()).done)if(fn(step.value[1],iterations++,this)===!1)break;return iterations},zipSequence.__iteratorUncached=function(reverse){let iterators=iters.map((i)=>{let col=Collection(i);return getIterator(reverse?col.reverse():col)}),iterations=0,steps=Array(iterators.length),values=Array(iterators.length);return makeEntryIterator((entry)=>{let done=zipAll;for(let i=0;i<iterators.length;i++)steps[i]=iterators[i].next(),done=zipAll?done&&steps[i].done:done||steps[i].done;if(done)return!1;for(let i=0;i<steps.length;i++)values[i]=steps[i].value;return entry[0]=iterations++,entry[1]=zipper(...values),!0})},zipSequence}function isArrayLike(value){if(Array.isArray(value)||typeof value==="string")return!0;return value&&typeof value==="object"&&Number.isInteger(value.length)&&value.length>=0&&(value.length===0?Object.keys(value).length===1:Object.hasOwn(value,value.length-1))}function isPlainObject(value){if(!value||typeof value!=="object"||Object.prototype.toString.call(value)!=="[object Object]")return!1;let proto=Object.getPrototypeOf(value);if(proto===null)return!0;let parentProto=proto,nextProto=Object.getPrototypeOf(proto);while(nextProto!==null)parentProto=nextProto,nextProto=Object.getPrototypeOf(parentProto);return parentProto===proto}var isDataStructure=(value)=>typeof value==="object"&&(isImmutable(value)||Array.isArray(value)||isPlainObject(value));function coerceKeyPath(keyPath){if(isArrayLike(keyPath)&&typeof keyPath!=="string")return keyPath;if(isOrdered(keyPath))return keyPath.toArray();throw TypeError(`Invalid keyPath: expected Ordered Collection or Array: ${keyPath}`)}var has=(collection,key)=>isImmutable(collection)?collection.has(key):isDataStructure(collection)&&Object.hasOwn(collection,key);function get2(collection,key,notSetValue){return isImmutable(collection)?collection.get(key,notSetValue):!has(collection,key)?notSetValue:typeof collection.get==="function"?collection.get(key):collection[key]}function getIn$1(collection,searchKeyPath,notSetValue){let keyPath=coerceKeyPath(searchKeyPath),i=0;while(i!==keyPath.length)if(collection=get2(collection,keyPath[i++],NOT_SET),collection===NOT_SET)return notSetValue;return collection}var hasIn$1=(collection,keyPath)=>getIn$1(collection,keyPath,NOT_SET)!==NOT_SET;function is(valueA,valueB){if(valueA===valueB||Number.isNaN(valueA)&&Number.isNaN(valueB))return!0;if(!valueA||!valueB)return!1;if(typeof valueA.valueOf==="function"&&typeof valueB.valueOf==="function"){if(valueA=valueA.valueOf(),valueB=valueB.valueOf(),valueA===valueB||Number.isNaN(valueA)&&Number.isNaN(valueB))return!0;if(!valueA||!valueB)return!1}return!!(isValueObject(valueA)&&isValueObject(valueB)&&valueA.equals(valueB))}function toJS(value){if(!value||typeof value!=="object")return value;if(!isCollection(value)){if(!isDataStructure(value))return value;value=Seq(value)}if(isKeyed(value)){let result2={};return value.__iterate((v,k)=>{result2[String(k)]=toJS(v)}),result2}let result=[];return value.__iterate((v)=>{result.push(toJS(v))}),result}function deepEqual2(a,b){if(a===b)return!0;if(!isCollection(b)||a.size!==void 0&&b.size!==void 0&&a.size!==b.size||a.__hash!==void 0&&b.__hash!==void 0&&a.__hash!==b.__hash||isKeyed(a)!==isKeyed(b)||isIndexed(a)!==isIndexed(b)||isOrdered(a)!==isOrdered(b))return!1;if(a.size===0&&b.size===0)return!0;let notAssociative=!isAssociative(a);if(isOrdered(a)){let entries=a.entries();return!!(b.every((v,k)=>{let entry=entries.next().value;return entry&&is(entry[1],v)&&(notAssociative||is(entry[0],k))})&&entries.next().done)}let flipped=!1;if(a.size===void 0)if(b.size===void 0){if(typeof a.cacheResult==="function")a.cacheResult()}else{flipped=!0;let _=a;a=b,b=_}let allEqual=!0,bSize=b.__iterate((v,k)=>{if(notAssociative?!a.has(v):flipped?!is(v,a.get(k,NOT_SET)):!is(a.get(k,NOT_SET),v))return allEqual=!1,!1;return!0});return allEqual&&a.size===bSize}var smi=(i32)=>i32>>>1&1073741824|i32&3221225471;function hash(o){if(o===null||o===void 0)return hashNullish(o);if(typeof o.hashCode==="function")return smi(o.hashCode(o));let v=valueOf(o);if(v===null||v===void 0)return hashNullish(v);switch(typeof v){case"boolean":return v?1108378657:1108378656;case"number":return hashNumber(v);case"string":return v.length>STRING_HASH_CACHE_MIN_STRLEN?cachedHashString(v):hashString(v);case"object":case"function":return hashJSObj(v);case"symbol":return hashSymbol(v);default:if(typeof v.toString==="function")return hashString(v.toString());throw Error(`Value type ${typeof v} cannot be hashed.`)}}var hashNullish=(nullish)=>nullish===null?1108378658:1108378659;function hashNumber(n){if(Number.isNaN(n)||n===1/0)return 0;let hash2=n|0;if(hash2!==n)hash2^=n*4294967295;while(n>4294967295)n/=4294967295,hash2^=n;return smi(hash2)}function cachedHashString(string){let hashed=stringHashCache[string];if(hashed===void 0){if(hashed=hashString(string),STRING_HASH_CACHE_SIZE===STRING_HASH_CACHE_MAX_SIZE)STRING_HASH_CACHE_SIZE=0,stringHashCache={};STRING_HASH_CACHE_SIZE++,stringHashCache[string]=hashed}return hashed}function hashString(string){let hashed=0;for(let ii=0;ii<string.length;ii++)hashed=31*hashed+string.charCodeAt(ii)|0;return smi(hashed)}function hashSymbol(sym){let hashed=symbolMap[sym];if(hashed!==void 0)return hashed;return hashed=nextHash(),symbolMap[sym]=hashed,hashed}function hashJSObj(obj){let hashed=weakMap.get(obj);if(hashed!==void 0)return hashed;return hashed=nextHash(),weakMap.set(obj,hashed),hashed}var valueOf=(obj)=>obj.valueOf!==Object.prototype.valueOf?obj.valueOf():obj;function nextHash(){let nextHash2=++_objHashUID;if(_objHashUID&1073741824)_objHashUID=0;return nextHash2}var weakMap=new WeakMap,symbolMap=Object.create(null),_objHashUID=0,STRING_HASH_CACHE_MIN_STRLEN=16,STRING_HASH_CACHE_MAX_SIZE=255,STRING_HASH_CACHE_SIZE=0,stringHashCache={};function hashCollection(collection){if(collection.size===1/0)return 0;let ordered=isOrdered(collection),keyed=isKeyed(collection),h=ordered?1:0;return collection.__iterate(keyed?ordered?(v,k)=>{h=31*h+hashMerge(hash(v),hash(k))|0}:(v,k)=>{h=h+hashMerge(hash(v),hash(k))|0}:ordered?(v)=>{h=31*h+hash(v)|0}:(v)=>{h=h+hash(v)|0}),murmurHashOfSize(collection.size,h)}var hashMerge=(a,b)=>a^b+2654435769+(a<<6)+(a>>2)|0;function murmurHashOfSize(size,h){return h=Math.imul(h,3432918353),h=Math.imul(h<<15|h>>>-15,461845907),h=Math.imul(h<<13|h>>>-13,5),h=(h+3864292196|0)^size,h=Math.imul(h^h>>>16,2246822507),h=Math.imul(h^h>>>13,3266489909),h=smi(h^h>>>16),h}function quoteString(value){try{return typeof value==="string"?JSON.stringify(value):String(value)}catch{return JSON.stringify(value)}}var reify=(iter,seq)=>iter===seq?iter:isSeq(iter)?seq:iter.create?iter.create(seq):iter.constructor(seq),reifyValues=(collection,arr)=>reify(collection,(isKeyed(collection)?KeyedCollection:isIndexed(collection)?IndexedCollection:SetCollection)(arr)),defaultZipper=(...values)=>values,Collection=(value)=>isCollection(value)?value:Seq(value);class CollectionImpl{size=0;static{this.prototype[IS_COLLECTION_SYMBOL]=!0,this.prototype.__toStringMapper=quoteString,this.prototype[Symbol.iterator]=this.prototype.values,this.prototype.toJSON=this.prototype.toArray,this.prototype.contains=this.prototype.includes}equals(other){return deepEqual2(this,other)}hashCode(){return this.__hash??(this.__hash=hashCollection(this))}toArray(){assertNotInfinite(this.size);let array=Array(this.size||0),useTuples=isKeyed(this),i=0;return this.__iterate((v,k)=>{array[i++]=useTuples?[k,v]:v}),array}toIndexedSeq(){return new ToIndexedSequence(this)}toJS(){return toJS(this)}toKeyedSeq(){return new ToKeyedSequence(this,!0)}toMap(){throw Error("toMap: not patched — import CollectionConversions")}toObject(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}toOrderedMap(){throw Error("toOrderedMap: not patched — import CollectionConversions")}toOrderedSet(){throw Error("toOrderedSet: not patched — import CollectionConversions")}toSet(){throw Error("toSet: not patched — import CollectionConversions")}toSetSeq(){return new ToSetSequence(this)}toSeq(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()}toStack(){throw Error("toStack: not patched — import CollectionConversions")}toList(){throw Error("toList: not patched — import CollectionConversions")}toString(){return"[Collection]"}__toString(head,tail){if(this.size===0)return`${head}${tail}`;return`${head} ${this.toSeq().map(this.__toStringMapper).join(", ")} ${tail}`}concat(...values){let isKeyedCollection=isKeyed(this),iters=[this,...values].map((v)=>{if(!isCollection(v))v=isKeyedCollection?keyedSeqFromValue(v):indexedSeqFromValue(Array.isArray(v)?v:[v]);else if(isKeyedCollection)v=KeyedCollection(v);return v}).filter((v)=>v.size!==0);if(iters.length===0)return this;if(iters.length===1){let singleton=iters[0];if(singleton===this||isKeyedCollection&&isKeyed(singleton)||isIndexed(this)&&isIndexed(singleton))return singleton}return reify(this,new ConcatSeq(iters))}includes(searchValue){return this.some((value)=>is(value,searchValue))}every(predicate,context){assertNotInfinite(this.size);let returnValue=!0;return this.__iterate((v,k,c)=>{if(!predicate.call(context,v,k,c))return returnValue=!1,!1}),returnValue}entries(){return this.__iterator()}filter(predicate,context){let collection=this,useKeys=isKeyed(this),filterSequence=makeSequence(collection);if(useKeys)filterSequence.has=(key)=>{let v=collection.get(key,NOT_SET);return v!==NOT_SET&&!!predicate.call(context,v,key,collection)},filterSequence.get=(key,notSetValue)=>{let v=collection.get(key,NOT_SET);return v!==NOT_SET&&predicate.call(context,v,key,collection)?v:notSetValue};return filterSequence.__iterateUncached=function(fn,reverse){let iterations=0;return collection.__iterate((v,k)=>{if(predicate.call(context,v,k,collection))return iterations++,fn(v,useKeys?k:iterations-1,this)},reverse),iterations},filterSequence.__iteratorUncached=function(reverse){let iterator=collection.__iterator(reverse),iterations=0;return makeEntryIterator((entry)=>{while(!0){let step=iterator.next();if(step.done)return!1;let k=step.value[0],v=step.value[1];if(predicate.call(context,v,k,collection))return entry[0]=useKeys?k:iterations++,entry[1]=v,!0}})},reify(this,filterSequence)}partition(predicate,context){let isKeyedIter=isKeyed(this),groups=[[],[]];return this.__iterate((v,k)=>{groups[predicate.call(context,v,k,this)?1:0].push(isKeyedIter?[k,v]:v)}),groups.map((arr)=>reifyValues(this,arr))}find(predicate,context,notSetValue){let entry=this.findEntry(predicate,context);return entry?entry[1]:notSetValue}forEach(sideEffect,context){return assertNotInfinite(this.size),this.__iterate(context?sideEffect.bind(context):sideEffect)}join(separator){assertNotInfinite(this.size),separator=separator!==void 0?String(separator):",";let joined="",isFirst=!0;return this.__iterate((v)=>{if(isFirst)isFirst=!1;else joined+=separator;joined+=v!==null&&v!==void 0?String(v):""}),joined}keys(){let iterator=this.__iterator(),result={done:!1,value:void 0};return makeIterator(()=>{let step=iterator.next();if(step.done)return DONE;return result.value=step.value[0],result})}map(mapper,context){return reify(this,mapFactory(this,mapper,context))}reduce(reducer,initialReduction=NOT_SET,context){return reduce(this,reducer,initialReduction,context,initialReduction===NOT_SET,!1)}reduceRight(reducer,initialReduction=NOT_SET,context){return reduce(this,reducer,initialReduction,context,initialReduction===NOT_SET,!0)}reverse(){return reify(this,reverseFactory(this,isKeyed(this)))}slice(begin,end){return reify(this,sliceFactory(this,begin,end,isKeyed(this)))}some(predicate,context){assertNotInfinite(this.size);let returnValue=!1;return this.__iterate((v,k,c)=>{if(predicate.call(context,v,k,c))return returnValue=!0,!1}),returnValue}sort(comparator){return reify(this,sortFactory(this,comparator))}values(){let iterator=this.__iterator(),result={done:!1,value:void 0};return makeIterator(()=>{let step=iterator.next();if(step.done)return DONE;return result.value=step.value[1],result})}butLast(){return this.slice(0,-1)}isEmpty(){return this.size!==void 0?this.size===0:!this.some(()=>!0)}count(predicate,context){return ensureSize(predicate?this.toSeq().filter(predicate,context):this)}countBy(_grouper,_context){throw Error("countBy: not patched — import CollectionConversions")}entrySeq(){let collection=this;if(collection._cache)return new ArraySeq(collection._cache);let entriesSequence=collection.toSeq().map(entryMapper).toIndexedSeq();return entriesSequence.fromEntrySeq=()=>collection.toSeq(),entriesSequence}filterNot(predicate,context){return this.filter(not(predicate),context)}findEntry(predicate,context,notSetValue){let found=notSetValue;return this.__iterate((v,k,c)=>{if(predicate.call(context,v,k,c))return found=[k,v],!1}),found}findKey(predicate,context){return this.findEntry(predicate,context)?.[0]}findLast(predicate,context,notSetValue){return this.toKeyedSeq().reverse().find(predicate,context,notSetValue)}findLastEntry(predicate,context,notSetValue){return this.toKeyedSeq().reverse().findEntry(predicate,context,notSetValue)}findLastKey(predicate,context){return this.toKeyedSeq().reverse().findKey(predicate,context)}first(notSetValue){return this.find(returnTrue,null,notSetValue)}flatMap(mapper,context){return reify(this,this.toSeq().map((v,k)=>(isKeyed(this)?KeyedCollection:isIndexed(this)?IndexedCollection:SetCollection)(mapper.call(context,v,k,this))).flatten(!0))}flatten(depth){let collection=this,useKeys=isKeyed(this),flatSequence=makeSequence(collection);return flatSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0,stopped=!1;function flatDeep(iter,currentDepth){iter.__iterate((v,k)=>{if((!depth||currentDepth<depth)&&isCollection(v))flatDeep(v,currentDepth+1);else if(iterations++,fn(v,useKeys?k:iterations-1,flatSequence)===!1)stopped=!0;if(stopped)return!1},reverse)}return flatDeep(collection,0),iterations},flatSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterations=0,stack=[{iterator:collection.__iterator(reverse),depth:0}];return makeEntryIterator((entry)=>{while(stack.length>0){let frame=stack[stack.length-1],step=frame.iterator.next();if(step.done){stack.pop();continue}let v=step.value[1];if((!depth||frame.depth<depth)&&isCollection(v)){stack.push({iterator:v.__iterator(reverse),depth:frame.depth+1});continue}return entry[0]=useKeys?step.value[0]:iterations++,entry[1]=v,!0}return!1})},reify(this,flatSequence)}fromEntrySeq(){return new FromEntriesSequence(this)}get(searchKey,notSetValue){return this.find((_,key)=>is(key,searchKey),void 0,notSetValue)}getIn(searchKeyPath,notSetValue){return getIn$1(this,searchKeyPath,notSetValue)}groupBy(_grouper,_context){throw Error("groupBy: not patched — import CollectionConversions")}has(searchKey){return this.get(searchKey,NOT_SET)!==NOT_SET}hasIn(searchKeyPath){return hasIn$1(this,searchKeyPath)}isSubset(iter){let other=typeof iter.includes==="function"?iter:Collection(iter);return this.every((value)=>other.includes(value))}isSuperset(iter){return(typeof iter.isSubset==="function"?iter:Collection(iter)).isSubset(this)}keyOf(searchValue){return this.findKey((value)=>is(value,searchValue))}keySeq(){return this.toSeq().map(keyMapper).toIndexedSeq()}last(notSetValue){return this.toSeq().reverse().first(notSetValue)}lastKeyOf(searchValue){return this.toKeyedSeq().reverse().keyOf(searchValue)}max(comparator){return maxFactory(this,comparator)}maxBy(mapper,comparator){return maxFactory(this,comparator,mapper)}min(comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator)}minBy(mapper,comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator,mapper)}rest(){return this.slice(1)}skip(amount){return amount===0?this:this.slice(Math.max(0,amount))}skipLast(amount){return amount===0?this:this.slice(0,-Math.max(0,amount))}skipWhile(predicate,context){let collection=this,useKeys=isKeyed(this),skipSequence=makeSequence(collection);return skipSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let skipping=!0,iterations=0;return collection.__iterate((v,k)=>{if(skipping&&predicate.call(context,v,k,this))return;return skipping=!1,iterations++,fn(v,useKeys?k:iterations-1,this)},reverse),iterations},skipSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterator=collection.__iterator(reverse),iterations=0,seq=this,skipping=!0;return makeEntryIterator((entry)=>{while(!0){let step=iterator.next();if(step.done)return!1;let k=step.value[0],v=step.value[1];if(skipping&&predicate.call(context,v,k,seq))continue;return skipping=!1,entry[0]=useKeys?k:iterations++,entry[1]=v,!0}})},reify(this,skipSequence)}skipUntil(predicate,context){return this.skipWhile(not(predicate),context)}sortBy(mapper,comparator){return reify(this,sortFactory(this,comparator,mapper))}take(amount){return this.slice(0,Math.max(0,amount))}takeLast(amount){return this.slice(-Math.max(0,amount))}takeWhile(predicate,context){let collection=this,takeSequence=makeSequence(collection);return takeSequence.__iterateUncached=function(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0;return collection.__iterate((v,k)=>{if(!predicate.call(context,v,k,this))return!1;return iterations++,fn(v,k,this)},reverse),iterations},takeSequence.__iteratorUncached=function(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let iterator=collection.__iterator(reverse),seq=this,finished=!1;return makeIterator(()=>{if(finished)return DONE;let step=iterator.next();if(step.done)return step;if(!predicate.call(context,step.value[1],step.value[0],seq))return finished=!0,DONE;return step})},reify(this,takeSequence)}takeUntil(predicate,context){return this.takeWhile(not(predicate),context)}update(fn){return fn(this)}valueSeq(){return this.toIndexedSeq()}__iterate(fn,reverse=!1){let iterator=this.__iterator(reverse),iterations=0,step;while(!(step=iterator.next()).done)if(iterations++,fn(step.value[1],step.value[0],this)===!1)break;return iterations}__iterator(_reverse=!1){throw Error("CollectionImpl does not implement __iterator. Use a subclass instead.")}}var KeyedCollection=(value)=>isKeyed(value)?value:KeyedSeq(value);class KeyedCollectionImpl extends CollectionImpl{static{this.prototype[IS_KEYED_SYMBOL]=!0,this.prototype.__toStringMapper=(v,k)=>`${quoteString(k)}: ${quoteString(v)}`,this.prototype[Symbol.iterator]=CollectionImpl.prototype.entries,this.prototype.toJSON=function(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}}flip(){return reify(this,flipFactory(this))}mapEntries(mapper,context){let iterations=0;return reify(this,this.toSeq().map((v,k)=>mapper.call(context,[k,v],iterations++,this)).fromEntrySeq())}mapKeys(mapper,context){return reify(this,this.toSeq().flip().map((k,v)=>mapper.call(context,k,v,this)).flip())}}var IndexedCollection=(value)=>isIndexed(value)?value:IndexedSeq(value);class IndexedCollectionImpl extends CollectionImpl{static{this.prototype[IS_INDEXED_SYMBOL]=!0,this.prototype[IS_ORDERED_SYMBOL]=!0}toKeyedSeq(){return new ToKeyedSequence(this,!1)}findIndex(predicate,context){let entry=this.findEntry(predicate,context);return entry?entry[0]:-1}indexOf(searchValue){let key=this.keyOf(searchValue);return key===void 0?-1:key}lastIndexOf(searchValue){let key=this.lastKeyOf(searchValue);return key===void 0?-1:key}splice(index,removeNum=NOT_SET,...values){if(index===void 0)return this;let hasRemoveNum=removeNum!==NOT_SET;if(removeNum=hasRemoveNum?Math.max(removeNum||0,0):0,hasRemoveNum&&!removeNum&&values.length===0)return this;index=resolveBegin(index,index<0?this.count():this.size);let spliced=this.slice(0,index);return reify(this,!hasRemoveNum?spliced:spliced.concat(values,this.slice(index+removeNum)))}findLastIndex(predicate,context){let entry=this.findLastEntry(predicate,context);return entry?entry[0]:-1}first(notSetValue){return this.get(0,notSetValue)}get(index,notSetValue){return index=wrapIndex(this,index),index<0||this.size===1/0||this.size!==void 0&&index>this.size?notSetValue:this.find((_,key)=>key===index,void 0,notSetValue)}has(index){return index=wrapIndex(this,index),index>=0&&(this.size!==void 0?this.size===1/0||index<this.size:this.indexOf(index)!==-1)}interpose(separator){let collection=this,interposedSequence=makeSequence(collection);return interposedSequence.size=collection.size&&collection.size*2-1,interposedSequence.__iterateUncached=function(fn,reverse){let iterations=0,isFirst=!0;return collection.__iterate((v)=>{if(!isFirst){if(fn(separator,iterations++,this)===!1)return!1}return isFirst=!1,fn(v,iterations++,this)},reverse),iterations},interposedSequence.__iteratorUncached=function(reverse){let iterator=collection.__iterator(reverse),iterations=0,isFirst=!0,pendingValue,hasPending=!1;return makeEntryIterator((entry)=>{if(hasPending)return hasPending=!1,entry[0]=iterations++,entry[1]=pendingValue,!0;let step=iterator.next();if(step.done)return!1;let value=step.value[1];if(!isFirst)return pendingValue=value,hasPending=!0,entry[0]=iterations++,entry[1]=separator,!0;return isFirst=!1,entry[0]=iterations++,entry[1]=value,!0})},reify(this,interposedSequence)}interleave(...collections){let thisAndCollections=[this,...collections],zipped=zipWithFactory(this.toSeq(),IndexedSeq.of,thisAndCollections),interleaved=zipped.flatten(!0);if(zipped.size)interleaved.size=zipped.size*thisAndCollections.length;return reify(this,interleaved)}keySeq(){throw Error("keySeq: not patched — import CollectionConversions")}last(notSetValue){return this.get(-1,notSetValue)}zip(...collections){return this.zipWith(defaultZipper,...collections)}zipAll(...collections){let thisAndCollections=[this,...collections];return reify(this,zipWithFactory(this,defaultZipper,thisAndCollections,!0))}zipWith(zipper,...collections){let thisAndCollections=[this,...collections];return reify(this,zipWithFactory(this,zipper,thisAndCollections))}}var SetCollection=(value)=>isCollection(value)&&!isAssociative(value)?value:SetSeq(value);class SetCollectionImpl extends CollectionImpl{static{this.prototype.has=CollectionImpl.prototype.includes,this.prototype.contains=CollectionImpl.prototype.includes,this.prototype.keys=SetCollectionImpl.prototype.values}get(value,notSetValue){return this.has(value)?value:notSetValue}includes(value){return this.has(value)}keySeq(){return this.valueSeq()}}Collection.Keyed=KeyedCollection;Collection.Indexed=IndexedCollection;Collection.Set=SetCollection;var IndexedCollectionPrototype=IndexedCollectionImpl.prototype,Seq=(value)=>value===void 0||value===null?emptySequence():isImmutable(value)?value.toSeq():seqFromValue(value),makeSequence=(collection)=>Object.create((isKeyed(collection)?KeyedSeqImpl:isIndexed(collection)?IndexedSeqImpl:SetSeqImpl).prototype);class SeqImpl extends CollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0}toSeq(){return this}toString(){return this.__toString("Seq {","}")}cacheResult(){if(!this._cache&&this.__iterateUncached)this._cache=this.entrySeq().toArray(),this.size=this._cache.length;return this}__iterateUncached(fn,reverse){let iterator=this.__iteratorUncached(reverse),iterations=0,step;while(!(step=iterator.next()).done)if(iterations++,fn(step.value[1],step.value[0],this)===!1)break;return iterations}__iterate(fn,reverse){let cache=this._cache;if(cache){let size=cache.length,i=0;while(i!==size){let entry=cache[reverse?size-++i:i++];if(fn(entry[1],entry[0],this)===!1)break}return i}return this.__iterateUncached(fn,reverse)}__iterator(reverse){let cache=this._cache;if(cache){let size=cache.length,i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return result.value=cache[reverse?size-++i:i++],result})}return this.__iteratorUncached(reverse)}}var seqMixin={cacheResult:SeqImpl.prototype.cacheResult,__iterateUncached:SeqImpl.prototype.__iterateUncached,__iterate:SeqImpl.prototype.__iterate,__iterator:SeqImpl.prototype.__iterator},KeyedSeq=(value)=>value===void 0||value===null?emptySequence().toKeyedSeq():isCollection(value)?isKeyed(value)?value.toSeq():value.fromEntrySeq():isRecord(value)?value.toSeq():keyedSeqFromValue(value);class KeyedSeqImpl extends KeyedCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toKeyedSeq(){return this}}var IndexedSeq=(value)=>value===void 0||value===null?emptySequence():isCollection(value)?isKeyed(value)?value.entrySeq():value.toIndexedSeq():isRecord(value)?value.toSeq().entrySeq():indexedSeqFromValue(value);IndexedSeq.of=(...values)=>IndexedSeq(values);class IndexedSeqImpl extends IndexedCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toIndexedSeq(){return this}toString(){return this.__toString("Seq [","]")}}var SetSeq=(value)=>(isCollection(value)&&!isAssociative(value)?value:IndexedSeq(value)).toSetSeq();SetSeq.of=(...values)=>SetSeq(values);class SetSeqImpl extends SetCollectionImpl{static{this.prototype[IS_SEQ_SYMBOL]=!0,Object.assign(this.prototype,seqMixin)}toSeq(){return this}toSetSeq(){return this}}Seq.isSeq=isSeq;Seq.Keyed=KeyedSeq;Seq.Set=SetSeq;Seq.Indexed=IndexedSeq;class ArraySeq extends IndexedSeqImpl{constructor(array){super();this._array=array,this.size=array.length}get(index,notSetValue){return this.has(index)?this._array[wrapIndex(this,index)]:notSetValue}__iterateUncached(fn,reverse){let array=this._array,size=array.length,i=0;while(i!==size){let ii=reverse?size-++i:i++;if(fn(array[ii],ii,this)===!1)break}return i}__iteratorUncached(reverse){let array=this._array,size=array.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let ii=reverse?size-++i:i++;return entry[0]=ii,entry[1]=array[ii],!0})}}class ObjectSeq extends KeyedSeqImpl{static{this.prototype[IS_ORDERED_SYMBOL]=!0}constructor(object){super();let keys=[...Object.keys(object),...Object.getOwnPropertySymbols(object)];this._object=object,this._keys=keys,this.size=keys.length}get(key,notSetValue){if(notSetValue!==void 0&&!this.has(key))return notSetValue;return this._object[key]}has(key){return Object.hasOwn(this._object,key)}__iterateUncached(fn,reverse){let object=this._object,keys=this._keys,size=keys.length,i=0;while(i!==size){let key=keys[reverse?size-++i:i++];if(fn(object[key],key,this)===!1)break}return i}__iteratorUncached(reverse){let object=this._object,keys=this._keys,size=keys.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let key=keys[reverse?size-++i:i++];return entry[0]=key,entry[1]=object[key],!0})}}class CollectionSeq extends IndexedSeqImpl{constructor(collection){super();this._collection=collection,this.size=collection.length||collection.size}__iterateUncached(fn,reverse){if(reverse)return this.cacheResult().__iterate(fn,reverse);let iterations=0;for(let value of this._collection){if(fn(value,iterations,this)===!1)break;iterations++}return iterations}__iteratorUncached(reverse){if(reverse)return this.cacheResult().__iterator(reverse);let collection=this._collection,iterator=getIterator(collection);if(!isIterator(iterator))return emptyIterator();let iterations=0;return makeEntryIterator((entry)=>{let step=iterator.next();if(step.done)return!1;return entry[0]=iterations++,entry[1]=step.value,!0})}}var emptySequence=()=>new ArraySeq([]),maybeIndexedSeqFromValue=(value)=>isArrayLike(value)?new ArraySeq(value):hasIterator(value)?new CollectionSeq(value):void 0;function keyedSeqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return seq.fromEntrySeq();if(typeof value==="object")return new ObjectSeq(value);throw TypeError(`Expected Array or collection object of [k, v] entries, or keyed object: ${value}`)}function indexedSeqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return seq;throw TypeError(`Expected Array or collection object of values: ${value}`)}function seqFromValue(value){let seq=maybeIndexedSeqFromValue(value);if(seq)return isEntriesIterable(value)?seq.fromEntrySeq():isKeysIterable(value)?seq.toSetSeq():seq;if(typeof value==="object")return new ObjectSeq(value);throw TypeError(`Expected Array or collection object of values, or keyed object: ${value}`)}class ConcatSeq extends SeqImpl{constructor(iterables){super();let wrappedIterables=[],size=0,sizeKnown=!0;for(let iterable of iterables)if(iterable._wrappedIterables){for(let wrapped of iterable._wrappedIterables)if(wrappedIterables.push(wrapped),sizeKnown){let s=wrapped.size;if(s!==void 0)size+=s;else sizeKnown=!1}}else if(wrappedIterables.push(iterable),sizeKnown){let s=iterable.size;if(s!==void 0)size+=s;else sizeKnown=!1}this._wrappedIterables=wrappedIterables,this.size=sizeKnown?size:void 0;let first=this._wrappedIterables[0];if(first[IS_KEYED_SYMBOL])this[IS_KEYED_SYMBOL]=!0;if(first[IS_INDEXED_SYMBOL])this[IS_INDEXED_SYMBOL]=!0;if(first[IS_ORDERED_SYMBOL])this[IS_ORDERED_SYMBOL]=!0}__iterateUncached(fn,reverse){if(this._wrappedIterables.length===0)return 0;if(reverse)return this.cacheResult().__iterate(fn,reverse);let wrappedIterables=this._wrappedIterables,reIndex=!isKeyed(this),index=0,stopped=!1;for(let iterable of wrappedIterables)if(iterable.__iterate((v,k)=>{if(fn(v,reIndex?index++:k,this)===!1)return stopped=!0,!1},reverse),stopped)break;return index}__iteratorUncached(reverse){if(this._wrappedIterables.length===0)return emptyIterator();if(reverse)return this.cacheResult().__iterator(reverse);let wrappedIterables=this._wrappedIterables,reIndex=!isKeyed(this),iterableIdx=0,currentIterator=wrappedIterables[0].__iterator(reverse);function nextStep(){while(iterableIdx<wrappedIterables.length){let step=currentIterator.next();if(!step.done)return step;if(iterableIdx++,iterableIdx<wrappedIterables.length)currentIterator=wrappedIterables[iterableIdx].__iterator(reverse)}return}if(reIndex){let index=0;return makeEntryIterator((entry)=>{let step=nextStep();if(!step)return!1;return entry[0]=index++,entry[1]=step.value[1],!0})}return makeIterator(()=>nextStep()||DONE)}}class ToKeyedSequence extends KeyedSeqImpl{static{this.prototype[IS_ORDERED_SYMBOL]=!0}constructor(indexed,useKeys){super();this._iter=indexed,this._useKeys=useKeys,this.size=indexed.size}cacheResult(){return cacheResultThrough.call(this)}get(key,notSetValue){return this._iter.get(key,notSetValue)}has(key){return this._iter.has(key)}valueSeq(){return this._iter.valueSeq()}reverse(){let reversedSequence=reverseFactory(this,!0);if(!this._useKeys)reversedSequence.valueSeq=()=>this._iter.toSeq().reverse();return reversedSequence}map(mapper,context){let mappedSequence=mapFactory(this,mapper,context);if(!this._useKeys)mappedSequence.valueSeq=()=>this._iter.toSeq().map(mapper,context);return mappedSequence}__iterateUncached(fn,reverse){return this._iter.__iterate(fn,reverse)}__iteratorUncached(reverse){return this._iter.__iterator(reverse)}}class ToIndexedSequence extends IndexedSeqImpl{constructor(iter){super();this._iter=iter,this.size=iter.size}cacheResult(){return cacheResultThrough.call(this)}includes(value){return this._iter.includes(value)}__iterateUncached(fn,reverse){let i=0;if(reverse)ensureSize(this);let size=this.size;return this._iter.__iterate((v)=>{let ii=reverse?size-++i:i++;return fn(v,ii,this)},reverse),i}__iteratorUncached(reverse){let i=0;if(reverse)ensureSize(this);let size=this.size;return mapEntries(this._iter.__iterator(reverse),(k,v,entry)=>{entry[0]=reverse?size-++i:i++,entry[1]=v})}}class ToSetSequence extends SetSeqImpl{constructor(iter){super();this._iter=iter,this.size=iter.size}cacheResult(){return cacheResultThrough.call(this)}has(key){return this._iter.includes(key)}__iterateUncached(fn,reverse){return this._iter.__iterate((v)=>fn(v,v,this),reverse)}__iteratorUncached(reverse){return mapEntries(this._iter.__iterator(reverse),(k,v,entry)=>{entry[0]=v,entry[1]=v})}}class FromEntriesSequence extends KeyedSeqImpl{constructor(entries){super();this._iter=entries,this.size=entries.size}cacheResult(){return cacheResultThrough.call(this)}entrySeq(){return this._iter.toSeq()}__iterateUncached(fn,reverse){let iterations=0;return this._iter.__iterate((entry)=>{if(entry){validateEntry(entry),iterations++;let indexedCollection=isCollection(entry);return fn(indexedCollection?entry.get(1):entry[1],indexedCollection?entry.get(0):entry[0],this)}},reverse),iterations}__iteratorUncached(reverse){let iterator=this._iter.__iterator(reverse);return makeEntryIterator((out)=>{while(!0){let step=iterator.next();if(step.done)return!1;let entry=step.value[1];if(entry){validateEntry(entry);let indexedCollection=isCollection(entry);return out[0]=indexedCollection?entry.get(0):entry[0],out[1]=indexedCollection?entry.get(1):entry[1],!0}}})}}function cacheResultThrough(){if(this._iter.cacheResult)return this._iter.cacheResult(),this.size=this._iter.size,this;return SeqImpl.prototype.cacheResult.call(this)}function validateEntry(entry){if(entry!==Object(entry))throw TypeError(`Expected [K, V] tuple: ${entry}`)}var Map2=(value)=>value===void 0||value===null?emptyMap():isMap(value)&&!isOrdered(value)?value:emptyMap().withMutations((map)=>{let iter=KeyedCollection(value);assertNotInfinite(iter.size),iter.forEach((v,k)=>map.set(k,v))});class MapImpl extends KeyedCollectionImpl{static{mixin(this,{asImmutable,asMutable,deleteIn,merge,mergeWith,mergeDeep,mergeDeepWith,mergeDeepIn,mergeIn,setIn,update,updateIn,wasAltered,withMutations,removeIn:deleteIn,concat:merge,[IS_MAP_SYMBOL]:!0,[DELETE]:this.prototype.remove,removeAll:this.prototype.deleteAll,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.Map"})}constructor(size,root,ownerID,hash2){super();this.size=size,this._root=root,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return Map2(value)}toString(){return this.__toString("Map {","}")}get(k,notSetValue){return this._root?this._root.get(0,hash(k),k,notSetValue):notSetValue}set(k,v){return updateMap(this,k,v)}remove(k){return updateMap(this,k,NOT_SET)}deleteAll(keys){let collection=Collection(keys);if(collection.size===0)return this;return this.withMutations((map)=>{collection.forEach((key)=>map.remove(key))})}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this;return emptyMap()}map(mapper,context){return this.withMutations((map)=>{map.forEach((value,key)=>{map.set(key,mapper.call(context,value,key,this))})})}keys(){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,!1,0)}values(){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,!1,1)}entries(){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,!1)}__iterator(reverse){if(!this._root)return emptyIterator();return mapIteratorGenerator(this._root,reverse)}__iterate(fn,reverse){let iterations=0;if(this._root)this._root.iterate(([key,value])=>{return iterations++,fn(value,key,this)},reverse);return iterations}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;if(!ownerID){if(this.size===0)return emptyMap();return this.__ownerID=ownerID,this.__altered=!1,this}return makeMap(this.size,this._root,ownerID,this.__hash)}}Map2.isMap=isMap;class ArrayMapNode{constructor(ownerID,entries){this.ownerID=ownerID,this.entries=entries}get(shift,keyHash,key,notSetValue){return linearGet(this.entries,key,notSetValue)}iterate(fn,reverse){return iterateLinearEntries(this.entries,fn,reverse)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let removed=value===NOT_SET,entries=this.entries,idx=0,len=entries.length;for(;idx<len;idx++)if(is(key,entries[idx][0]))break;let exists=idx<len;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),removed||!exists)SetRef(didChangeSize);if(removed&&len===1)return;if(!exists&&!removed&&len>=MAX_ARRAY_MAP_SIZE)return createNodes(ownerID,entries,key,value);let isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:entries.slice();if(exists)if(removed)if(idx===len-1)newEntries.pop();else newEntries[idx]=newEntries.pop();else newEntries[idx]=[key,value];else newEntries.push([key,value]);if(isEditable)return this.entries=newEntries,this;return new ArrayMapNode(ownerID,newEntries)}}class BitmapIndexedNode{constructor(ownerID,bitmap,nodes){this.ownerID=ownerID,this.bitmap=bitmap,this.nodes=nodes}iterate(fn,reverse){return iterateNodeArray(this.nodes,fn,reverse)}get(shift,keyHash,key,notSetValue){let bit=1<<((shift===0?keyHash:keyHash>>>shift)&MASK),bitmap=this.bitmap;return(bitmap&bit)===0?notSetValue:this.nodes[popCount(bitmap&bit-1)].get(shift+SHIFT,keyHash,key,notSetValue)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let keyHashFrag=(shift===0?keyHash:keyHash>>>shift)&MASK,bit=1<<keyHashFrag,bitmap=this.bitmap,exists=(bitmap&bit)!==0;if(!exists&&value===NOT_SET)return this;let idx=popCount(bitmap&bit-1),nodes=this.nodes,node=exists?nodes[idx]:void 0,newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node)return this;if(!exists&&newNode&&nodes.length>=MAX_BITMAP_INDEXED_SIZE)return expandNodes(ownerID,nodes,bitmap,keyHashFrag,newNode);if(exists&&!newNode&&nodes.length===2&&isLeafNode(nodes[idx^1]))return nodes[idx^1];if(exists&&newNode&&nodes.length===1&&isLeafNode(newNode))return newNode;let isEditable=ownerID&&ownerID===this.ownerID,newBitmap=exists?newNode?bitmap:bitmap^bit:bitmap|bit,newNodes=exists?newNode?setAt(nodes,idx,newNode,isEditable):spliceOut(nodes,idx,isEditable):spliceIn(nodes,idx,newNode,isEditable);if(isEditable)return this.bitmap=newBitmap,this.nodes=newNodes,this;return new BitmapIndexedNode(ownerID,newBitmap,newNodes)}}class HashArrayMapNode{constructor(ownerID,count,nodes){this.ownerID=ownerID,this.count=count,this.nodes=nodes}iterate(fn,reverse){return iterateNodeArray(this.nodes,fn,reverse)}get(shift,keyHash,key,notSetValue){let idx=(shift===0?keyHash:keyHash>>>shift)&MASK,node=this.nodes[idx];return node?node.get(shift+SHIFT,keyHash,key,notSetValue):notSetValue}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let idx=(shift===0?keyHash:keyHash>>>shift)&MASK,removed=value===NOT_SET,nodes=this.nodes,node=nodes[idx];if(removed&&!node)return this;let newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node)return this;let newCount=this.count;if(!node)newCount++;else if(!newNode){if(newCount--,newCount<MIN_HASH_ARRAY_MAP_SIZE)return packNodes(ownerID,nodes,newCount,idx)}let isEditable=ownerID&&ownerID===this.ownerID,newNodes=setAt(nodes,idx,newNode,isEditable);if(isEditable)return this.count=newCount,this.nodes=newNodes,this;return new HashArrayMapNode(ownerID,newCount,newNodes)}}class HashCollisionNode{constructor(ownerID,keyHash,entries){this.ownerID=ownerID,this.keyHash=keyHash,this.entries=entries}get(shift,keyHash,key,notSetValue){return linearGet(this.entries,key,notSetValue)}iterate(fn,reverse){return iterateLinearEntries(this.entries,fn,reverse)}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(keyHash!==this.keyHash){if(value===NOT_SET)return this;return SetRef(didAlter),SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,keyHash,[key,value])}let removed=value===NOT_SET,entries=this.entries,idx=0,len=entries.length;for(;idx<len;idx++)if(is(key,entries[idx][0]))break;let exists=idx<len;if(exists?entries[idx][1]===value:removed)return this;if(SetRef(didAlter),removed||!exists)SetRef(didChangeSize);if(removed&&len===2)return new ValueNode(ownerID,this.keyHash,entries[idx^1]);let isEditable=ownerID&&ownerID===this.ownerID,newEntries=isEditable?entries:entries.slice();if(exists)if(removed)if(idx===len-1)newEntries.pop();else newEntries[idx]=newEntries.pop();else newEntries[idx]=[key,value];else newEntries.push([key,value]);if(isEditable)return this.entries=newEntries,this;return new HashCollisionNode(ownerID,this.keyHash,newEntries)}}class ValueNode{constructor(ownerID,keyHash,entry){this.ownerID=ownerID,this.keyHash=keyHash,this.entry=entry}iterate(fn,_reverse){return fn(this.entry)}get(shift,keyHash,key,notSetValue){return is(key,this.entry[0])?this.entry[1]:notSetValue}update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){let removed=value===NOT_SET,keyMatch=is(key,this.entry[0]);if(keyMatch?value===this.entry[1]:removed)return this;if(SetRef(didAlter),removed){SetRef(didChangeSize);return}if(keyMatch){if(ownerID&&ownerID===this.ownerID)return this.entry[1]=value,this;return new ValueNode(ownerID,this.keyHash,[key,value])}return SetRef(didChangeSize),mergeIntoNode(this,ownerID,shift,hash(key),[key,value])}}function linearGet(entries,key,notSetValue){for(let ii=0,len=entries.length;ii<len;ii++)if(is(key,entries[ii][0]))return entries[ii][1];return notSetValue}function iterateLinearEntries(entries,fn,reverse){for(let ii=0,maxIndex=entries.length-1;ii<=maxIndex;ii++)if(fn(entries[reverse?maxIndex-ii:ii])===!1)return!1}function iterateNodeArray(nodes,fn,reverse){for(let ii=0,maxIndex=nodes.length-1;ii<=maxIndex;ii++)if(nodes[reverse?maxIndex-ii:ii]?.iterate(fn,reverse)===!1)return!1}function mapIteratorGenerator(node,reverse,entryIndex){let stack={node,index:0,__prev:null},extractValue=entryIndex!==void 0?(entry)=>entry[entryIndex]:(entry)=>entry,result={done:!1,value:void 0};return makeIterator(()=>{while(stack){let node2=stack.node,index=stack.index++,maxIndex;if(node2.entry){if(index===0)return result.value=extractValue(node2.entry),result}else if(node2.entries){if(maxIndex=node2.entries.length-1,index<=maxIndex)return result.value=extractValue(node2.entries[reverse?maxIndex-index:index]),result}else if(maxIndex=node2.nodes.length-1,index<=maxIndex){let subNode=node2.nodes[reverse?maxIndex-index:index];if(subNode){if(subNode.entry)return result.value=extractValue(subNode.entry),result;stack={node:subNode,index:0,__prev:stack}}continue}stack=stack.__prev}return DONE})}var makeMap=(size,root,ownerID,hash2)=>new MapImpl(size,root,ownerID,hash2),EMPTY_MAP,emptyMap=()=>EMPTY_MAP||(EMPTY_MAP=makeMap(0));function updateMap(map,k,v){let newRoot,newSize;if(!map._root){if(v===NOT_SET)return map;newSize=1,newRoot=new ArrayMapNode(map.__ownerID,[[k,v]])}else{let didChangeSize=MakeRef(),didAlter=MakeRef();if(newRoot=updateNode(map._root,map.__ownerID,0,hash(k),k,v,didChangeSize,didAlter),!didAlter.value)return map;newSize=map.size+(didChangeSize.value?v===NOT_SET?-1:1:0)}if(map.__ownerID)return map.size=newSize,map._root=newRoot,map.__hash=void 0,map.__altered=!0,map;return newRoot?makeMap(newSize,newRoot):emptyMap()}function updateNode(node,ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(!node){if(value===NOT_SET)return node;return SetRef(didAlter),SetRef(didChangeSize),new ValueNode(ownerID,keyHash,[key,value])}return node.update(ownerID,shift,keyHash,key,value,didChangeSize,didAlter)}var isLeafNode=(node)=>node.constructor===ValueNode||node.constructor===HashCollisionNode;function mergeIntoNode(node,ownerID,shift,keyHash,entry){if(node.keyHash===keyHash)return new HashCollisionNode(ownerID,keyHash,[node.entry,entry]);let idx1=(shift===0?node.keyHash:node.keyHash>>>shift)&MASK,idx2=(shift===0?keyHash:keyHash>>>shift)&MASK,newNode=new ValueNode(ownerID,keyHash,entry),nodes=idx1===idx2?[mergeIntoNode(node,ownerID,shift+SHIFT,keyHash,entry)]:idx1<idx2?[node,newNode]:[newNode,node];return new BitmapIndexedNode(ownerID,1<<idx1|1<<idx2,nodes)}function createNodes(ownerID,entries,key,value){if(!ownerID)ownerID=new OwnerID;let node=new ValueNode(ownerID,hash(key),[key,value]);for(let[k,v]of entries)node=node.update(ownerID,0,hash(k),k,v);return node}function packNodes(ownerID,nodes,count,excluding){let bitmap=0,packedII=0,packedNodes=Array(count);for(let ii=0,bit=1,len=nodes.length;ii<len;ii++,bit<<=1){let node=nodes[ii];if(node!==void 0&&ii!==excluding)bitmap|=bit,packedNodes[packedII++]=node}return new BitmapIndexedNode(ownerID,bitmap,packedNodes)}function expandNodes(ownerID,nodes,bitmap,including,node){let count=0,expandedNodes=Array(SIZE);for(let ii=0;bitmap!==0;ii++,bitmap>>>=1)expandedNodes[ii]=bitmap&1?nodes[count++]:void 0;return expandedNodes[including]=node,new HashArrayMapNode(ownerID,count+1,expandedNodes)}function popCount(x){return x-=x>>1&1431655765,x=(x&858993459)+(x>>2&858993459),x=x+(x>>4)&252645135,x+=x>>8,x+=x>>16,x&127}function setAt(array,idx,val,canEdit){let newArray=canEdit?array:array.slice();return newArray[idx]=val,newArray}function spliceIn(array,idx,val,canEdit){let newLen=array.length+1;if(canEdit&&idx+1===newLen)return array[idx]=val,array;let newArray=Array(newLen),after=0;for(let ii=0;ii<newLen;ii++)if(ii===idx)newArray[ii]=val,after=-1;else newArray[ii]=array[ii+after];return newArray}function spliceOut(array,idx,canEdit){let newLen=array.length-1;if(canEdit&&idx===newLen)return array.pop(),array;let newArray=Array(newLen),after=0;for(let ii=0;ii<newLen;ii++){if(ii===idx)after=1;newArray[ii]=array[ii+after]}return newArray}var MAX_ARRAY_MAP_SIZE=SIZE/4,MAX_BITMAP_INDEXED_SIZE=SIZE/2,MIN_HASH_ARRAY_MAP_SIZE=SIZE/4;function shallowCopy(from){if(Array.isArray(from))return from.slice();return{...from}}var merge$1=(collection,...sources)=>mergeWithSources(collection,sources),mergeWith$1=(merger,collection,...sources)=>mergeWithSources(collection,sources,merger),mergeDeepWithSources=(collection,sources,merger)=>mergeWithSources(collection,sources,deepMergerWith(merger)),mergeDeep$1=(collection,...sources)=>mergeDeepWithSources(collection,sources),mergeDeepWith$1=(merger,collection,...sources)=>mergeDeepWithSources(collection,sources,merger);function mergeWithSources(collection,sources,merger){if(!isDataStructure(collection))throw TypeError(`Cannot merge into non-data-structure value: ${collection}`);if(isImmutable(collection))return typeof merger==="function"&&collection.mergeWith?collection.mergeWith(merger,...sources):collection.merge?collection.merge(...sources):collection.concat(...sources);let isArray=Array.isArray(collection),merged=collection,Collection2=isArray?IndexedCollection:KeyedCollection,mergeItem=isArray?(value)=>{if(merged===collection)merged=shallowCopy(merged);merged.push(value)}:(value,key)=>{let hasVal=Object.hasOwn(merged,key),nextVal=hasVal&&merger?merger(merged[key],value,key):value;if(!hasVal||nextVal!==merged[key]){if(merged===collection)merged=shallowCopy(merged);merged[key]=nextVal}};for(let source of sources)Collection2(source).forEach(mergeItem);return merged}function deepMergerWith(merger){function deepMerger(oldValue,newValue,key){return isDataStructure(oldValue)&&isDataStructure(newValue)&&areMergeable(oldValue,newValue)?mergeWithSources(oldValue,[newValue],deepMerger):merger?merger(oldValue,newValue,key):newValue}return deepMerger}function areMergeable(oldDataStructure,newDataStructure){let oldSeq=Seq(oldDataStructure),newSeq=Seq(newDataStructure);return isIndexed(oldSeq)===isIndexed(newSeq)&&isKeyed(oldSeq)===isKeyed(newSeq)}function remove(collection,key){if(!isDataStructure(collection))throw TypeError(`Cannot update non-data-structure value: ${collection}`);if(isImmutable(collection)){if(!collection.remove)throw TypeError(`Cannot update immutable value without .remove() method: ${collection}`);return collection.remove(key)}if(!Object.hasOwn(collection,key))return collection;let collectionCopy=shallowCopy(collection);if(Array.isArray(collectionCopy))collectionCopy.splice(key,1);else delete collectionCopy[key];return collectionCopy}function set2(collection,key,value){if(!isDataStructure(collection))throw TypeError(`Cannot update non-data-structure value: ${collection}`);if(isImmutable(collection)){if(!collection.set)throw TypeError(`Cannot update immutable value without .set() method: ${collection}`);return collection.set(key,value)}if(Object.hasOwn(collection,key)&&value===collection[key])return collection;let collectionCopy=shallowCopy(collection);return collectionCopy[key]=value,collectionCopy}function updateIn$1(collection,keyPath,notSetValue,updater){if(!updater)updater=notSetValue,notSetValue=void 0;let updatedValue=updateInDeeply(isImmutable(collection),collection,coerceKeyPath(keyPath),0,notSetValue,updater);return updatedValue===NOT_SET?notSetValue:updatedValue}function updateInDeeply(inImmutable,existing,keyPath,i,notSetValue,updater){let wasNotSet=existing===NOT_SET;if(i===keyPath.length){let existingValue=wasNotSet?notSetValue:existing,newValue=updater(existingValue);return newValue===existingValue?existing:newValue}if(!wasNotSet&&!isDataStructure(existing))throw TypeError(`Cannot update within non-data-structure value in path [${Array.from(keyPath).slice(0,i).map(quoteString)}]: ${existing}`);let key=keyPath[i],nextExisting=wasNotSet?NOT_SET:get2(existing,key,NOT_SET),nextUpdated=updateInDeeply(nextExisting===NOT_SET?inImmutable:isImmutable(nextExisting),nextExisting,keyPath,i+1,notSetValue,updater);if(nextUpdated===nextExisting)return existing;if(nextUpdated===NOT_SET)return remove(existing,key);let collection=wasNotSet?inImmutable?emptyMap():{}:existing;return set2(collection,key,nextUpdated)}var removeIn=(collection,keyPath)=>updateIn$1(collection,keyPath,()=>NOT_SET),setIn$1=(collection,keyPath,value)=>updateIn$1(collection,keyPath,NOT_SET,()=>value);function update$1(collection,key,notSetValue,updater){return updateIn$1(collection,[key],notSetValue,updater)}function asImmutable(){return this.__ensureOwner()}function asMutable(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)}function wasAltered(){return this.__altered}function withMutations(fn){let mutable=this.asMutable();return fn(mutable),mutable.wasAltered()?mutable.__ensureOwner(this.__ownerID):this}function getIn(searchKeyPath,notSetValue){return getIn$1(this,searchKeyPath,notSetValue)}function hasIn(searchKeyPath){return hasIn$1(this,searchKeyPath)}function deleteIn(keyPath){return removeIn(this,keyPath)}function setIn(keyPath,v){return setIn$1(this,keyPath,v)}function update(key,notSetValue,updater){return typeof key==="function"?key(this):update$1(this,key,notSetValue,updater)}function updateIn(keyPath,notSetValue,updater){return updateIn$1(this,keyPath,notSetValue,updater)}function toObject(){assertNotInfinite(this.size);let object={};return this.__iterate((v,k)=>{object[k]=v}),object}function merge(...iters){return mergeIntoKeyedWith(this,iters)}function mergeWith(merger,...iters){if(typeof merger!=="function")throw TypeError(`Invalid merger function: ${merger}`);return mergeIntoKeyedWith(this,iters,merger)}function mergeIntoKeyedWith(collection,collections,merger){let iters=[];for(let item of collections){let collection2=KeyedCollection(item);if(collection2.size!==0)iters.push(collection2)}if(iters.length===0)return collection;if(collection.toSeq().size===0&&!collection.__ownerID&&iters.length===1)return isRecord(collection)?collection:collection.create(iters[0]);return collection.withMutations((collection2)=>{let mergeIntoCollection=merger?(value,key)=>{update$1(collection2,key,NOT_SET,(oldVal)=>oldVal===NOT_SET?value:merger(oldVal,value,key))}:(value,key)=>{collection2.set(key,value)};for(let iter of iters)iter.forEach(mergeIntoCollection)})}function mergeDeep(...iters){return mergeDeepWithSources(this,iters)}function mergeDeepWith(merger,...iters){return mergeDeepWithSources(this,iters,merger)}function mergeIn(keyPath,...iters){return updateIn$1(this,keyPath,emptyMap(),(m)=>mergeWithSources(m,iters))}function mergeDeepIn(keyPath,...iters){return updateIn$1(this,keyPath,emptyMap(),(m)=>mergeDeepWithSources(m,iters))}function mixin(Class,methods){Object.assign(Class.prototype,methods)}var List=(value)=>{let empty=emptyList();if(value===void 0||value===null)return empty;if(isList(value))return value;let iter=IndexedCollection(value),size=iter.size;if(size===0)return empty;if(assertNotInfinite(size),size>0&&size<SIZE)return makeList(0,size,SHIFT,null,new VNode(iter.toArray()));return empty.withMutations((list)=>{list.setSize(size),iter.forEach((v,i)=>list.set(i,v))})};List.of=(...values)=>List(values);class ListImpl extends IndexedCollectionImpl{static{mixin(this,{asImmutable,asMutable,deleteIn,mergeDeepIn,mergeIn,setIn,update,updateIn,wasAltered,withMutations,removeIn:deleteIn,[IS_LIST_SYMBOL]:!0,[DELETE]:this.prototype.remove,merge:this.prototype.concat,[Symbol.toStringTag]:"Immutable.List",[Symbol.iterator]:this.prototype.values})}constructor(origin,capacity,level,root,tail,ownerID,hash2){super();this.size=capacity-origin,this._origin=origin,this._capacity=capacity,this._level=level,this._root=root,this._tail=tail,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return List(value)}toString(){return this.__toString("List [","]")}get(index,notSetValue){if(index=wrapIndex(this,index),index>=0&&index<this.size)return index+=this._origin,listNodeFor(this,index)?.array[index&MASK];return notSetValue}set(index,value){return updateList(this,index,value)}remove(index){return!this.has(index)?this:index===0?this.shift():index===this.size-1?this.pop():this.splice(index,1)}insert(index,value){return this.splice(index,0,value)}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=this._origin=this._capacity=0,this._level=SHIFT,this._root=this._tail=this.__hash=void 0,this.__altered=!0,this;return emptyList()}push(...values){let oldSize=this.size;return this.withMutations((list)=>{setListBounds(list,0,oldSize+values.length);for(let ii=0;ii<values.length;ii++)list.set(oldSize+ii,values[ii])})}pop(){return setListBounds(this,0,-1)}unshift(...values){return this.withMutations((list)=>{setListBounds(list,-values.length);for(let ii=0;ii<values.length;ii++)list.set(ii,values[ii])})}shift(){return setListBounds(this,1)}shuffle(random=Math.random){return this.withMutations((mutable)=>{let current=mutable.size,destination,tmp;while(current)destination=Math.floor(random()*current--),tmp=mutable.get(destination),mutable.set(destination,mutable.get(current)),mutable.set(current,tmp)})}concat(...collections){let seqs=[];for(let collection of collections){let seq=IndexedCollection(typeof collection!=="string"&&hasIterator(collection)?collection:[collection]);if(seq.size!==0)seqs.push(seq)}if(seqs.length===0)return this;if(this.size===0&&!this.__ownerID&&seqs.length===1)return List(seqs[0]);return this.withMutations((list)=>{seqs.forEach((seq)=>seq.forEach((value)=>list.push(value)))})}setSize(size){return setListBounds(this,0,size)}map(mapper,context){return this.withMutations((list)=>{for(let i=0;i<this.size;i++)list.set(i,mapper.call(context,list.get(i),i,this))})}slice(begin,end){let size=this.size;if(wholeSlice(begin,end,size))return this;return setListBounds(this,resolveBegin(begin,size),resolveEnd(end,size))}__iterate(fn,reverse){let index=reverse?this.size:0;return iterateListCallback(this,(value)=>fn(value,reverse?--index:index++,this),reverse),reverse?this.size-index:index}__iterator(reverse){let index=reverse?this.size:0,iter=iterateList(this,reverse);return makeEntryIterator((entry)=>{let step=iter.next();if(step.done)return!1;return entry[0]=reverse?--index:index++,entry[1]=step.value,!0})}values(){return iterateList(this,!1)}keys(){return makeIndexKeys(this.size)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;if(!ownerID){if(this.size===0)return emptyList();return this.__ownerID=ownerID,this.__altered=!1,this}return makeList(this._origin,this._capacity,this._level,this._root,this._tail,ownerID,this.__hash)}}List.isList=isList;class VNode{constructor(array,ownerID){this.array=array,this.ownerID=ownerID}removeBefore(ownerID,level,index){if((index&(1<<level+SHIFT)-1)===0||this.array.length===0)return this;let originIndex=index>>>level&MASK;if(originIndex>=this.array.length)return new VNode([],ownerID);let removingFirst=originIndex===0,newChild;if(level>0){let oldChild=this.array[originIndex];if(newChild=oldChild?.removeBefore(ownerID,level-SHIFT,index),newChild===oldChild&&removingFirst)return this}if(removingFirst&&!newChild)return this;let editable=editableVNode(this,ownerID);if(!removingFirst)for(let ii=0;ii<originIndex;ii++)editable.array[ii]=void 0;if(newChild)editable.array[originIndex]=newChild;return editable}removeAfter(ownerID,level,index){if(index===(level?1<<level+SHIFT:SIZE)||this.array.length===0)return this;let sizeIndex=index-1>>>level&MASK;if(sizeIndex>=this.array.length)return this;let newChild;if(level>0){let oldChild=this.array[sizeIndex];if(newChild=oldChild?.removeAfter(ownerID,level-SHIFT,index),newChild===oldChild&&sizeIndex===this.array.length-1)return this}let editable=editableVNode(this,ownerID);if(editable.array.splice(sizeIndex+1),newChild)editable.array[sizeIndex]=newChild;return editable}}function iterateList(list,reverse){let{_origin:left,_capacity:right}=list,tailPos=getTailOffset(right),tail=list._tail,stack=[];pushFrame(list._root,list._level,0);let result={done:!1,value:void 0};return makeIterator(()=>{while(stack.length>0){let frame=stack[stack.length-1];if(frame.from===frame.to){stack.pop();continue}let idx=reverse?--frame.to:frame.from++;if(frame.isLeaf)return result.value=frame.array?.[idx],result;let childNode=frame.array?.[idx],childLevel=frame.level-SHIFT,childOffset=frame.offset+(idx<<frame.level);pushFrame(childNode,childLevel,childOffset)}return DONE});function pushFrame(node,level,offset){if(level===0){let array=offset===tailPos?tail?.array:node?.array,from=offset>left?0:left-offset,to=right-offset;if(to>SIZE)to=SIZE;if(from!==to)stack.push({array,from,to,isLeaf:!0})}else{let array=node?.array,from=offset>left?0:left-offset>>level,to=(right-offset>>level)+1;if(to>SIZE)to=SIZE;if(from!==to)stack.push({array,from,to,level,offset,isLeaf:!1})}}}function iterateListCallback(list,fn,reverse){let{_origin:left,_capacity:right}=list,tailPos=getTailOffset(right),tail=list._tail,level=list._level,root=list._root;return level===0?iterateLeaf(root,0,left,right,tailPos,tail,fn,reverse):iterateNode(root,level,0,left,right,tailPos,tail,fn,reverse)}function iterateLeaf(node,offset,left,right,tailPos,tail,fn,reverse){let array=offset===tailPos?tail?.array:node?.array,from=offset>left?0:left-offset,to=right-offset;if(to>SIZE)to=SIZE;while(from!==to){let idx=reverse?--to:from++;if(fn(array?.[idx])===!1)return!1}}function iterateNode(node,level,offset,left,right,tailPos,tail,fn,reverse){let array=node?.array,from=offset>left?0:left-offset>>level,to=(right-offset>>level)+1;if(to>SIZE)to=SIZE;let nextLevel=level-SHIFT;while(from!==to){let idx=reverse?--to:from++,nextOffset=offset+(idx<<level);if((nextLevel===0?iterateLeaf(array?.[idx],nextOffset,left,right,tailPos,tail,fn,reverse):iterateNode(array?.[idx],nextLevel,nextOffset,left,right,tailPos,tail,fn,reverse))===!1)return!1}}var makeList=(origin,capacity,level,root,tail,ownerID,hash2)=>new ListImpl(origin,capacity,level,root,tail,ownerID,hash2),emptyList=()=>makeList(0,0,SHIFT);function updateList(list,index,value){if(index=wrapIndex(list,index),Number.isNaN(index))return list;if(index>=list.size||index<0)return list.withMutations((list2)=>{if(index<0)setListBounds(list2,index).set(0,value);else setListBounds(list2,0,index+1).set(index,value)});index+=list._origin;let{_tail:newTail,_root:newRoot}=list,didAlter=MakeRef();if(index>=getTailOffset(list._capacity))newTail=updateVNode(newTail,list.__ownerID,0,index,value,didAlter);else newRoot=updateVNode(newRoot,list.__ownerID,list._level,index,value,didAlter);if(!didAlter.value)return list;if(list.__ownerID)return list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list;return makeList(list._origin,list._capacity,list._level,newRoot,newTail)}function updateVNode(node,ownerID,level,index,value,didAlter){let idx=index>>>level&MASK,nodeHas=node&&idx<node.array.length;if(!nodeHas&&value===void 0)return node;let newNode;if(level>0){let lowerNode=node?.array[idx],newLowerNode=updateVNode(lowerNode,ownerID,level-SHIFT,index,value,didAlter);if(newLowerNode===lowerNode)return node;return newNode=editableVNode(node,ownerID),newNode.array[idx]=newLowerNode,newNode}if(nodeHas&&node.array[idx]===value)return node;if(didAlter)SetRef(didAlter);if(newNode=editableVNode(node,ownerID),value===void 0&&idx===newNode.array.length-1)newNode.array.pop();else newNode.array[idx]=value;return newNode}function editableVNode(node,ownerID){if(ownerID&&ownerID===node?.ownerID)return node;return new VNode(node?.array.slice()??[],ownerID)}function listNodeFor(list,rawIndex){if(rawIndex>=getTailOffset(list._capacity))return list._tail;if(rawIndex<1<<list._level+SHIFT){let{_root:node,_level:level}=list;while(node&&level>0)node=node.array[rawIndex>>>level&MASK],level-=SHIFT;return node}}function setListBounds(list,begin,end){if(begin!==void 0)begin|=0;if(end!==void 0)end|=0;let owner=list.__ownerID||new OwnerID,oldOrigin=list._origin,oldCapacity=list._capacity,newOrigin=oldOrigin+begin,newCapacity=end===void 0?oldCapacity:end<0?oldCapacity+end:oldOrigin+end;if(newOrigin===oldOrigin&&newCapacity===oldCapacity)return list;if(newOrigin>=newCapacity)return list.clear();let{_level:newLevel,_root:newRoot}=list,offsetShift=0;while(newOrigin+offsetShift<0)newRoot=new VNode(newRoot?.array.length?[void 0,newRoot]:[],owner),newLevel+=SHIFT,offsetShift+=1<<newLevel;if(offsetShift)newOrigin+=offsetShift,oldOrigin+=offsetShift,newCapacity+=offsetShift,oldCapacity+=offsetShift;let oldTailOffset=getTailOffset(oldCapacity),newTailOffset=getTailOffset(newCapacity);while(newTailOffset>=1<<newLevel+SHIFT)newRoot=new VNode(newRoot?.array.length?[newRoot]:[],owner),newLevel+=SHIFT;let oldTail=list._tail,newTail=newTailOffset<oldTailOffset?listNodeFor(list,newCapacity-1):newTailOffset>oldTailOffset?new VNode([],owner):oldTail;if(oldTail&&newTailOffset>oldTailOffset&&newOrigin<oldCapacity&&oldTail.array.length){newRoot=editableVNode(newRoot,owner);let node=newRoot;for(let level=newLevel;level>SHIFT;level-=SHIFT){let idx=oldTailOffset>>>level&MASK;node=node.array[idx]=editableVNode(node.array[idx],owner)}node.array[oldTailOffset>>>SHIFT&MASK]=oldTail}if(newCapacity<oldCapacity)newTail=newTail?.removeAfter(owner,0,newCapacity);if(newOrigin>=newTailOffset)newOrigin-=newTailOffset,newCapacity-=newTailOffset,newLevel=SHIFT,newRoot=null,newTail=newTail?.removeBefore(owner,0,newOrigin);else if(newOrigin>oldOrigin||newTailOffset<oldTailOffset){offsetShift=0;while(newRoot){let beginIndex=newOrigin>>>newLevel&MASK;if(beginIndex!==newTailOffset>>>newLevel&MASK)break;if(beginIndex)offsetShift+=(1<<newLevel)*beginIndex;newLevel-=SHIFT,newRoot=newRoot.array[beginIndex]}if(newRoot&&newOrigin>oldOrigin)newRoot=newRoot.removeBefore(owner,newLevel,newOrigin-offsetShift);if(newRoot&&newTailOffset<oldTailOffset)newRoot=newRoot.removeAfter(owner,newLevel,newTailOffset-offsetShift);if(offsetShift)newOrigin-=offsetShift,newCapacity-=offsetShift}if(list.__ownerID)return list.size=newCapacity-newOrigin,list._origin=newOrigin,list._capacity=newCapacity,list._level=newLevel,list._root=newRoot,list._tail=newTail,list.__hash=void 0,list.__altered=!0,list;return makeList(newOrigin,newCapacity,newLevel,newRoot,newTail)}var getTailOffset=(size)=>size<SIZE?0:size-1>>>SHIFT<<SHIFT,OrderedMap=(value)=>value===void 0||value===null?emptyOrderedMap():isOrderedMap(value)?value:emptyOrderedMap().withMutations((map)=>{let iter=KeyedCollection(value);assertNotInfinite(iter.size),iter.forEach((v,k)=>map.set(k,v))});OrderedMap.of=(...values)=>OrderedMap(values);class OrderedMapImpl extends MapImpl{static{mixin(this,{[IS_ORDERED_SYMBOL]:!0,[DELETE]:this.prototype.remove,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.OrderedMap",keys:CollectionImpl.prototype.keys,values:CollectionImpl.prototype.values,__iterate:CollectionImpl.prototype.__iterate})}constructor(map,list,ownerID,hash2){super(map?map.size:0,void 0,ownerID,hash2);this._map=map,this._list=list}create(value){return OrderedMap(value)}toString(){return this.__toString("OrderedMap {","}")}get(k,notSetValue){let index=this._map.get(k);return index!==void 0?this._list.get(index)[1]:notSetValue}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=0,this._map.clear(),this._list.clear(),this.__altered=!0,this;return emptyOrderedMap()}set(k,v){return updateOrderedMap(this,k,v)}remove(k){return updateOrderedMap(this,k,NOT_SET)}entries(){return this.__iterator(!1)}__iterator(reverse){let listIter=this._list.__iterator(reverse);return makeEntryIterator((entry)=>{while(!0){let step=listIter.next();if(step.done)return!1;let e=step.value[1];if(e)return entry[0]=e[0],entry[1]=e[1],!0}})}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newMap=this._map.__ensureOwner(ownerID),newList=this._list.__ensureOwner(ownerID);if(!ownerID){if(this.size===0)return emptyOrderedMap();return this.__ownerID=ownerID,this.__altered=!1,this._map=newMap,this._list=newList,this}return makeOrderedMap(newMap,newList,ownerID,this.__hash)}}OrderedMap.isOrderedMap=isOrderedMap;var makeOrderedMap=(map,list,ownerID,hash2)=>new OrderedMapImpl(map,list,ownerID,hash2),emptyOrderedMap=()=>makeOrderedMap(emptyMap(),emptyList());function updateOrderedMap(omap,k,v){let{_map:map,_list:list}=omap,i=map.get(k),has2=i!==void 0,newMap,newList;if(v===NOT_SET){if(!has2)return omap;if(list.size>=SIZE&&list.size>=map.size*2){let entries=[];if(list.forEach((entry,idx)=>{if(entry!==void 0&&i!==idx)entries.push(entry)}),newList=emptyList().withMutations((l)=>{for(let j=0;j<entries.length;j++)l.set(j,entries[j])}),newMap=emptyMap().withMutations((m)=>{for(let j=0;j<entries.length;j++)m.set(entries[j][0],j)}),omap.__ownerID)newMap.__ownerID=newList.__ownerID=omap.__ownerID}else newMap=map.remove(k),newList=i===list.size-1?list.pop():list.set(i,void 0)}else if(has2){if(v===list.get(i)[1])return omap;newMap=map,newList=list.set(i,[k,v])}else{let newIdx=list.size;newMap=map.set(k,newIdx),newList=list.set(newIdx,[k,v])}if(omap.__ownerID)return omap.size=newMap.size,omap._map=newMap,omap._list=newList,omap.__hash=void 0,omap.__altered=!0,omap;return makeOrderedMap(newMap,newList)}var Stack=(value)=>value===void 0||value===null?emptyStack():isStack(value)?value:emptyStack().pushAll(value);Stack.of=(...values)=>Stack(values);class StackImpl extends IndexedCollectionImpl{static{mixin(this,{asImmutable,asMutable,wasAltered,withMutations,[IS_STACK_SYMBOL]:!0,shift:this.prototype.pop,unshift:this.prototype.push,unshiftAll:this.prototype.pushAll,[Symbol.toStringTag]:"Immutable.Stack",[Symbol.iterator]:this.prototype.values})}constructor(size,head,ownerID,hash2){super();this.size=size,this._head=head,this.__ownerID=ownerID,this.__hash=hash2,this.__altered=!1}create(value){return Stack(value)}toString(){return this.__toString("Stack [","]")}get(index,notSetValue){let head=this._head;index=wrapIndex(this,index);while(head&&index--)head=head.next;return head?head.value:notSetValue}peek(){return this._head?.value}push(...values){if(values.length===0)return this;let newSize=this.size+values.length,head=this._head;for(let ii=values.length-1;ii>=0;ii--)head={value:values[ii],next:head};return returnStack(this,newSize,head)}pushAll(iter){if(iter=IndexedCollection(iter),iter.size===0)return this;if(this.size===0&&isStack(iter))return iter;assertNotInfinite(iter.size);let newSize=this.size,head=this._head;return iter.__iterate((value)=>{newSize++,head={value,next:head}},!0),returnStack(this,newSize,head)}pop(){return this.slice(1)}clear(){if(this.size===0)return this;if(this.__ownerID)return this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this;return emptyStack()}slice(begin,end){if(wholeSlice(begin,end,this.size))return this;let resolvedBegin=resolveBegin(begin,this.size);if(resolveEnd(end,this.size)!==this.size)return IndexedCollectionImpl.prototype.slice.call(this,begin,end);let newSize=this.size-resolvedBegin,head=this._head;while(resolvedBegin--)head=head.next;return returnStack(this,newSize,head)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;if(!ownerID){if(this.size===0)return emptyStack();return this.__ownerID=ownerID,this.__altered=!1,this}return makeStack(this.size,this._head,ownerID,this.__hash)}__iterate(fn,reverse){if(reverse){let arr=this.toArray(),size=arr.length,i=0;while(i!==size)if(fn(arr[size-++i],size-i,this)===!1)break;return i}let iterations=0,node=this._head;while(node){if(fn(node.value,iterations++,this)===!1)break;node=node.next}return iterations}__iterator(reverse){if(reverse){let arr=this.toArray(),size=arr.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let ii=size-++i;return entry[0]=ii,entry[1]=arr[ii],!0})}let iterations=0,node=this._head;return makeEntryIterator((entry)=>{if(!node)return!1;return entry[0]=iterations++,entry[1]=node.value,node=node.next,!0})}values(){let node=this._head,result={done:!1,value:void 0};return makeIterator(()=>{if(!node)return DONE;return result.value=node.value,node=node.next,result})}keys(){return makeIndexKeys(this.size)}}Stack.isStack=isStack;function returnStack(stack,newSize,head){if(stack.__ownerID)return stack.size=newSize,stack._head=head,stack.__hash=void 0,stack.__altered=!0,stack;return makeStack(newSize,head)}var makeStack=(size,head,ownerID,hash2)=>new StackImpl(size,head,ownerID,hash2),EMPTY_STACK,emptyStack=()=>EMPTY_STACK||(EMPTY_STACK=makeStack(0)),Set2=(value)=>value===void 0||value===null?emptySet():isSet(value)&&!isOrdered(value)?value:emptySet().withMutations((set3)=>{let iter=SetCollection(value);assertNotInfinite(iter.size),iter.forEach((v)=>set3.add(v))});Set2.of=(...values)=>Set2(values);Set2.fromKeys=(value)=>Set2(KeyedCollection(value).keySeq());Set2.intersect=(sets)=>{return sets=Collection(sets).toArray(),sets.length?Set2(sets.pop()).intersect(...sets):emptySet()};Set2.union=(sets)=>{let setArray=Collection(sets).toArray();return setArray.length?Set2(setArray.pop()).union(...setArray):emptySet()};class SetImpl extends SetCollectionImpl{static{mixin(this,{withMutations,asImmutable,asMutable,[IS_SET_SYMBOL]:!0,[DELETE]:this.prototype.remove,merge:this.prototype.union,concat:this.prototype.union,[Symbol.toStringTag]:"Immutable.Set"})}constructor(map,ownerID){super();this.size=map?map.size:0,this._map=map,this.__ownerID=ownerID}create(value){return Set2(value)}toString(){return this.__toString("Set {","}")}has(value){return this._map.has(value)}add(value){return updateSet(this,this._map.set(value,value))}remove(value){return updateSet(this,this._map.remove(value))}clear(){return updateSet(this,this._map.clear())}map(mapper,context){let didChanges=!1,newMap=updateSet(this,this._map.mapEntries(([,v])=>{let mapped=mapper.call(context,v,v,this);if(mapped!==v)didChanges=!0;return[mapped,mapped]},context));return didChanges?newMap:this}union(...iters){if(iters=iters.filter((x)=>x.size!==0),iters.length===0)return this;if(this.size===0&&!this.__ownerID&&iters.length===1)return Set2(iters[0]);return this.withMutations((set3)=>{for(let iter of iters)if(typeof iter==="string")set3.add(iter);else SetCollection(iter).forEach((value)=>set3.add(value))})}intersect(...iters){return filterByIters(this,iters,(value,sets)=>!sets.every((iter)=>iter.includes(value)))}subtract(...iters){return filterByIters(this,iters,(value,sets)=>sets.some((iter)=>iter.includes(value)))}wasAltered(){return this._map.wasAltered()}__iterator(reverse){return this._map.__iterator(reverse)}__empty(){return emptySet()}__make(map,ownerID){return makeSet(map,ownerID)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newMap=this._map.__ensureOwner(ownerID);if(!ownerID){if(this.size===0)return this.__empty();return this.__ownerID=ownerID,this._map=newMap,this}return this.__make(newMap,ownerID)}}Set2.isSet=isSet;var makeSet=(map,ownerID)=>new SetImpl(map,ownerID),EMPTY_SET,emptySet=()=>EMPTY_SET||(EMPTY_SET=makeSet(emptyMap()));function filterByIters(set3,iters,shouldRemove){if(iters.length===0)return set3;return iters=iters.map((iter)=>SetCollection(iter)),set3.withMutations((s)=>{set3.forEach((value)=>{if(shouldRemove(value,iters))s.remove(value)})})}function updateSet(set3,newMap){if(set3.__ownerID)return set3.size=newMap.size,set3._map=newMap,set3;return newMap===set3._map?set3:newMap.size===0?set3.__empty():set3.__make(newMap)}var OrderedSet=(value)=>value===void 0||value===null?emptyOrderedSet():isOrderedSet(value)?value:emptyOrderedSet().withMutations((set3)=>{let iter=SetCollection(value);assertNotInfinite(iter.size),iter.forEach((v)=>set3.add(v))});OrderedSet.of=(...values)=>OrderedSet(values);OrderedSet.fromKeys=(value)=>OrderedSet(KeyedCollection(value).keySeq());class OrderedSetImpl extends SetImpl{static{mixin(this,{[IS_ORDERED_SYMBOL]:!0,[Symbol.toStringTag]:"Immutable.OrderedSet",zip:IndexedCollectionPrototype.zip,zipWith:IndexedCollectionPrototype.zipWith,zipAll:IndexedCollectionPrototype.zipAll})}create(value){return OrderedSet(value)}toString(){return this.__toString("OrderedSet {","}")}__empty(){return emptyOrderedSet()}__make(map,ownerID){return makeOrderedSet(map,ownerID)}}OrderedSet.isOrderedSet=isOrderedSet;var makeOrderedSet=(map,ownerID)=>new OrderedSetImpl(map,ownerID),emptyOrderedSet=()=>makeOrderedSet(emptyOrderedMap()),PairSorting={LeftThenRight:-1,RightThenLeft:1};function throwOnInvalidDefaultValues(defaultValues){if(isRecord(defaultValues))throw Error("Can not call `Record` with an immutable Record as default values. Use a plain javascript object instead.");if(isImmutable(defaultValues))throw Error("Can not call `Record` with an immutable Collection as default values. Use a plain javascript object instead.");if(defaultValues===null||typeof defaultValues!=="object")throw Error("Can not call `Record` with a non-object as default values. Use a plain javascript object instead.")}var Record=(defaultValues,name)=>{let hasInitialized;throwOnInvalidDefaultValues(defaultValues);let RecordType=function(values){if(values instanceof RecordType)return values;if(!(this instanceof RecordType))return new RecordType(values);if(!hasInitialized){hasInitialized=!0;let keys=Object.keys(defaultValues),indices=RecordTypePrototype._indices={};RecordTypePrototype._name=name,RecordTypePrototype._keys=keys,RecordTypePrototype._defaultValues=defaultValues;for(let i=0;i<keys.length;i++){let propName=keys[i];if(indices[propName]=i,RecordTypePrototype[propName])console.warn(`Cannot define ${recordName(this)} with property "${propName}" since that property name is part of the Record API.`);else setProp(RecordTypePrototype,propName)}}return this.__ownerID=void 0,this._values=List().withMutations((l)=>{l.setSize(this._keys.length),KeyedCollection(values).forEach((v,k)=>{l.set(this._indices[k],v===this._defaultValues[k]?void 0:v)})}),this},RecordTypePrototype=RecordType.prototype=Object.create(RecordPrototype);if(RecordTypePrototype.constructor=RecordType,RecordTypePrototype.create=RecordType,name)RecordType.displayName=name;return RecordType};class RecordImpl{static{mixin(this,{asImmutable,asMutable,deleteIn,getIn,hasIn,merge,mergeWith,mergeDeep,mergeDeepWith,mergeDeepIn,mergeIn,setIn,toObject,update,updateIn,withMutations,removeIn:deleteIn,toJSON:toObject,[IS_RECORD_SYMBOL]:!0,[DELETE]:this.prototype.remove,[Symbol.iterator]:this.prototype.entries,[Symbol.toStringTag]:"Immutable.Record"})}toString(){let body=this._keys.map((k)=>`${k}: ${quoteString(this.get(k))}`).join(", ");return`${recordName(this)} { ${body} }`}equals(other){return this===other||isRecord(other)&&recordSeq(this).equals(recordSeq(other))}hashCode(){return recordSeq(this).hashCode()}has(k){return Object.hasOwn(this._indices,k)}get(k,notSetValue){if(!this.has(k))return notSetValue;let index=this._indices[k],value=this._values.get(index);return value===void 0?this._defaultValues[k]:value}set(k,v){if(this.has(k)){let newValues=this._values.set(this._indices[k],v===this._defaultValues[k]?void 0:v);if(newValues!==this._values&&!this.__ownerID)return makeRecord(this,newValues)}return this}remove(k){return this.set(k)}clear(){let newValues=this._values.clear().setSize(this._keys.length);return this.__ownerID?this:makeRecord(this,newValues)}wasAltered(){return this._values.wasAltered()}toSeq(){return recordSeq(this)}toJS(){return toJS(this)}entries(){return this.__iterator()}__iterate(fn,reverse){return recordSeq(this).__iterate(fn,reverse)}__iterator(reverse){return recordSeq(this).__iterator(reverse)}__ensureOwner(ownerID){if(ownerID===this.__ownerID)return this;let newValues=this._values.__ensureOwner(ownerID);if(!ownerID)return this.__ownerID=ownerID,this._values=newValues,this;return makeRecord(this,newValues,ownerID)}}Record.isRecord=isRecord;var recordName=(record)=>record.constructor.displayName||record.constructor.name||"Record";class RecordSeq extends KeyedSeqImpl{constructor(record){super();this._record=record,this.size=record._keys.length}get(key,notSetValue){return this._record.get(key,notSetValue)}has(key){return this._record.has(key)}__iterateUncached(fn,reverse){let record=this._record,keys=record._keys,size=keys.length,i=0;while(i!==size){let ii=reverse?size-++i:i++,k=keys[ii];if(fn(record.get(k),k,this)===!1)break}return i}__iteratorUncached(reverse){let record=this._record,keys=record._keys,size=keys.length,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let ii=reverse?size-++i:i++,k=keys[ii];return entry[0]=k,entry[1]=record.get(k),!0})}}var recordSeq=(record)=>new RecordSeq(record);Record.getDescriptiveName=recordName;var RecordPrototype=RecordImpl.prototype;function makeRecord(likeRecord,values,ownerID){let record=Object.create(Object.getPrototypeOf(likeRecord));return record._values=values,record.__ownerID=ownerID,record}function setProp(prototype,name){Object.defineProperty(prototype,name,{get(){return this.get(name)},set(value){invariant(this.__ownerID,"Cannot set on an immutable record."),this.set(name,value)}})}var Range=(start,end,step=1)=>{if(invariant(step!==0,"Cannot step a Range by 0"),invariant(start!==void 0,"You must define a start value when using Range"),invariant(end!==void 0,"You must define an end value when using Range"),step=Math.abs(step),end<start)step=-step;let size=Math.max(0,Math.ceil((end-start)/step-1)+1);return new RangeImpl(start,end,step,size)};class RangeImpl extends IndexedSeqImpl{_start;_end;_step;constructor(start,end,step,size){super();this._start=start,this._end=end,this._step=step,this.size=size}toString(){return this.size===0?"Range []":`Range [ ${this._start}...${this._end}${this._step!==1?` by ${this._step}`:""} ]`}get(index,notSetValue){return this.has(index)?this._start+wrapIndex(this,index)*this._step:notSetValue}includes(searchValue){let possibleIndex=(searchValue-this._start)/this._step;return possibleIndex>=0&&possibleIndex<this.size&&possibleIndex===Math.floor(possibleIndex)}slice(begin,end){if(wholeSlice(begin,end,this.size))return this;if(begin=resolveBegin(begin,this.size),end=resolveEnd(end,this.size),end<=begin)return Range(0,0);return Range(this.get(begin,this._end),this.get(end,this._end),this._step)}indexOf(searchValue){let offsetValue=searchValue-this._start;if(offsetValue%this._step===0){let index=offsetValue/this._step;if(index>=0&&index<this.size)return index}return-1}lastIndexOf(searchValue){return this.indexOf(searchValue)}__iterateUncached(fn,reverse=!1){let size=this.size,step=this._step,value=reverse?this._start+(size-1)*step:this._start,i=0;while(i!==size){let v=value;value+=reverse?-step:step;let ii=reverse?size-++i:i++;if(fn(v,ii,this)===!1)break}return i}__iteratorUncached(reverse=!1){let size=this.size,step=this._step,value=reverse?this._start+(size-1)*step:this._start,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;let v=value;return value+=reverse?-step:step,entry[0]=reverse?size-++i:i++,entry[1]=v,!0})}values(){let size=this.size,step=this._step,value=this._start,i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return result.value=value,value+=step,i++,result})}keys(){return makeIndexKeys(this.size)}equals(other){return other instanceof RangeImpl?this._start===other._start&&this._end===other._end&&this._step===other._step:deepEqual2(this,other)}static{this.prototype[Symbol.iterator]=this.prototype.values}}var Repeat=(value,times)=>{let size=times===void 0?1/0:Math.max(0,times);return new RepeatImpl(value,size)};class RepeatImpl extends IndexedSeqImpl{constructor(value,size){super();this._value=value,this.size=size}toString(){if(this.size===0)return"Repeat []";return`Repeat [ ${this._value} ${this.size} times ]`}get(index,notSetValue){return this.has(index)?this._value:notSetValue}includes(searchValue){return is(this._value,searchValue)}slice(begin,end){let size=this.size;return wholeSlice(begin,end,size)?this:new RepeatImpl(this._value,resolveEnd(end,size)-resolveBegin(begin,size))}reverse(){return this}indexOf(searchValue){if(is(this._value,searchValue))return 0;return-1}lastIndexOf(searchValue){if(is(this._value,searchValue))return this.size;return-1}__iterateUncached(fn,reverse){let size=this.size,i=0;while(i!==size)if(fn(this._value,reverse?size-++i:i++,this)===!1)break;return i}__iteratorUncached(reverse){let size=this.size,val=this._value,i=0;return makeEntryIterator((entry)=>{if(i===size)return!1;return entry[0]=reverse?size-++i:i++,entry[1]=val,!0})}values(){let size=this.size,val=this._value,i=0,result={done:!1,value:void 0};return makeIterator(()=>{if(i===size)return DONE;return i++,result.value=val,result})}keys(){return makeIndexKeys(this.size)}equals(other){return other instanceof RepeatImpl?this.size===other.size&&is(this._value,other._value):deepEqual2(this,other)}static{this.prototype[Symbol.iterator]=this.prototype.values}}var fromJS=(value,converter)=>fromJSWith([],converter??defaultConverter,value,"",converter?.length>2?[]:void 0,{"":value});function fromJSWith(stack,converter,value,key,keyPath,parentValue){if(typeof value!=="string"&&!isImmutable(value)&&(isArrayLike(value)||hasIterator(value)||isPlainObject(value))){if(stack.includes(value))throw TypeError("Cannot convert circular structure to Immutable");if(stack.push(value),keyPath&&key!=="")keyPath.push(key);let converted=converter.call(parentValue,key,Seq(value).map((v,k)=>fromJSWith(stack,converter,v,k,keyPath,value)),keyPath?.slice());if(stack.pop(),keyPath)keyPath.pop();return converted}return value}var defaultConverter=(k,v)=>isIndexed(v)?v.toList():isKeyed(v)?v.toMap():v.toSet(),asValues=(collection)=>isKeyed(collection)?collection.valueSeq():collection;function initCollectionConversions(){CollectionImpl.prototype.toMap=function(){return Map2(this.toKeyedSeq())},CollectionImpl.prototype.toOrderedMap=function(){return OrderedMap(this.toKeyedSeq())},CollectionImpl.prototype.toOrderedSet=function(){return OrderedSet(asValues(this))},CollectionImpl.prototype.toSet=function(){return Set2(asValues(this))},CollectionImpl.prototype.toStack=function(){return Stack(asValues(this))},CollectionImpl.prototype.toList=function(){return List(asValues(this))},CollectionImpl.prototype.countBy=function(grouper,context){let groups=Map2().asMutable();return this.__iterate((v,k)=>{groups.update(grouper.call(context,v,k,this),0,(a)=>a+1)}),groups.asImmutable()},CollectionImpl.prototype.groupBy=function(grouper,context){let isKeyedIter=isKeyed(this),groups=(isOrdered(this)?OrderedMap():Map2()).asMutable();return this.__iterate((v,k)=>{groups.update(grouper.call(context,v,k,this),(a)=>{return a??=[],a.push(isKeyedIter?[k,v]:v),a})}),groups.map((arr)=>reifyValues(this,arr)).asImmutable()},IndexedCollectionImpl.prototype.keySeq=function(){return Range(0,this.size)},MapImpl.prototype.sort=function(comparator){return OrderedMap(sortFactory(this,comparator))},MapImpl.prototype.sortBy=function(mapper,comparator){return OrderedMap(sortFactory(this,comparator,mapper))},SetImpl.prototype.sort=function(comparator){return OrderedSet(sortFactory(this,comparator))},SetImpl.prototype.sortBy=function(mapper,comparator){return OrderedSet(sortFactory(this,comparator,mapper))}}var version$1="7.0.0",pkg={version:version$1};initCollectionConversions();var{version}=pkg;var NONE=Symbol("NONE");class Step{lookup(_v,dval=null){return dval}setValue(root,_v){return root}enterFrame(stack,_prev,next){return stack.enter(next,{},!0)}toAbstractPathStep(){return this}}class BindStep extends Step{constructor(binds){super();this.binds=binds}lookup(v,_dval){return v}setValue(_root,v){return v}enterFrame(stack,_prev,next){return stack.enter(next,{...this.binds},!1)}withIndex(i){return new BindStep({...this.binds,key:i})}withKey(key){return new BindStep({...this.binds,key})}toAbstractPathStep(){return null}}class FieldStep extends Step{constructor(field){super();this.field=field}lookup(v,dval=null){return v?.get?v.get(this.field,dval):dval}setValue(root,v){return root.set(this.field,v)}withIndex(i){return new SeqStep(this.field,i)}withKey(k){return new SeqStep(this.field,k)}}class SeqStep extends Step{constructor(field,key){super();this.field=field,this.key=key}lookup(v,dval=null){let o=v?.get(this.field,null);return o?.get?o.get(this.key,dval):dval}setValue(root,v){let seq=root?.get(this.field,null);return seq?root.set(this.field,seq.set(this.key,v)):root}enterFrame(stack,_prev,next){return stack.enter(next,{key:this.key},!0)}}class SeqAccessStep extends Step{constructor(seqField,keyField){super();this.seqField=seqField,this.keyField=keyField}lookup(v,dval=null){let seq=v?.get(this.seqField,NONE),key=v?.get(this.keyField,NONE);return key!==NONE&&seq?.get?seq.get(key,dval):dval}setValue(root,v){let seq=root?.get(this.seqField,NONE),key=root?.get(this.keyField,NONE);return seq===NONE||key===NONE?root:root.set(this.seqField,seq.set(key,v))}}class EachBindStep extends Step{constructor(seqVal,key){super();this.seqVal=seqVal,this.key=key}lookup(v,_dval){return v}setValue(_root,v){return v}enterFrame(stack,_prev,next){let item=this.seqVal.eval(stack)?.get(this.key,null);return stack.enter(next,{key:this.key,value:item},!1)}toAbstractPathStep(){return null}}class EachRenderItStep extends SeqStep{enterFrame(stack,_prev,next){return stack.enter(next,{key:this.key,value:next},!1).enter(next,{},!0)}toAbstractPathStep(){return new SeqStep(this.field,this.key)}}function warnRawDynStep(op,step){console.warn(`Path.${op} reached a DynStep: call toTransactionPath() first`,step)}class DynStep extends Step{constructor(producerCompId,producerSteps){super();this.producerCompId=producerCompId,this.producerSteps=producerSteps,this.interiorCids=new Set}teleportSteps(){return this.producerSteps}lookup(_v,dval=null){return warnRawDynStep("lookup",this),dval}setValue(root,_v){return warnRawDynStep("setValue",this),root}enterFrame(stack,_prev,_next){return warnRawDynStep("enterFrame",this),stack}}class DynEachStep extends DynStep{constructor(producerCompId,producerSteps,key){super(producerCompId,producerSteps);this.key=key}teleportSteps(){let{producerSteps,key}=this;if(producerSteps.length===0)return producerSteps;let last=producerSteps[producerSteps.length-1];if(!(last instanceof FieldStep))return console.warn("DynEachStep: seq-access dynamic cannot be iterated",this),producerSteps;return producerSteps.slice(0,-1).concat(new SeqStep(last.field,key))}}class Path{constructor(steps=[]){this.steps=steps}concat(steps){return new Path(this.steps.concat(steps))}popStep(){return new Path(this.steps.slice(0,-1))}compact(){let out=[];for(let step of this.steps){let s=step.toAbstractPathStep();if(s!==null){if(s!==step)s._originCid=step._originCid;out.push(s)}}return new Path(out)}toTransactionPath(){let hasDyn=!1;for(let step of this.steps)if(step instanceof DynStep){hasDyn=!0;break}if(!hasDyn)return this;let out=[];for(let step of this.steps)if(step instanceof DynStep){while(out.length>0&&step.interiorCids.has(out[out.length-1]._originCid))out.pop();for(let ts of step.teleportSteps())ts._originCid=step.producerCompId,out.push(ts)}else out.push(step);return new Path(out)}lookup(v,dval=null){let curVal=v;for(let step of this.steps)if(curVal=step.lookup(curVal,NONE),curVal===NONE)return dval;return curVal}setValue(root,v){let intermediates=Array(this.steps.length),curVal=root;for(let i=0;i<this.steps.length;i++)if(intermediates[i]=curVal,curVal=this.steps[i].lookup(curVal,NONE),curVal===NONE)return root;let newVal=v;for(let i=this.steps.length-1;i>=0;i--)newVal=this.steps[i].setValue(intermediates[i],newVal),intermediates[i]=newVal;return newVal}buildStack(stack){let prev=stack.it;for(let step of this.steps){let next=step.lookup(prev,NONE);if(next===NONE)return console.warn("bad PathItem",{root:stack.it,step,path:this}),null;stack=step.enterFrame(stack,prev,next),prev=next}return stack}static fromNodeAndEventName(node,eventName,rootNode,maxDepth,comps,stopOnNoEvent=!0){let pathSteps=[],pendingDyns=[],bubbles=BUBBLING_EVENTS.has(eventName),depth=0,eventIds=[],handlers=null,nodeIds=[],isLeafComponent=!0;while(node&&node!==rootNode&&depth<maxDepth){if(node?.dataset){let{nid,si,sk}=parseMetaComment(node.previousSibling),{eid,cid,vid}=node.dataset;if(eid!==void 0)eventIds.push(eid);if(cid!==void 0){let cidNum=+cid,comp=comps.getComponentForId(cidNum),pushStep=!0;if(handlers===null&&(isLeafComponent||bubbles)){if(handlers=findHandlers(comp,eventIds,vid,eventName),handlers===null){if(isLeafComponent&&stopOnNoEvent&&!bubbles)return NO_EVENT_INFO}else if(!isLeafComponent)pathSteps.length=0,pendingDyns.length=0,pushStep=!1}isLeafComponent=!1;for(let dyn of pendingDyns)dyn.interiorCids.add(cidNum);if(pushStep){let step=resolvePathStep(comp,nodeIds,vid);if(step){if(step._originCid=cidNum,pathSteps.push(step),step instanceof DynStep)step.interiorCids.add(cidNum),pendingDyns.push(step)}}for(let i=pendingDyns.length-1;i>=0;i--)if(pendingDyns[i].producerCompId===cidNum)pendingDyns.splice(i,1);eventIds=[],nodeIds=[]}if(nid!==void 0)nodeIds.push({nid,si,sk})}depth+=1,node=node.parentNode}if(pendingDyns.length>0)console.warn("event reconstruction: dynamic-var producer not found",pendingDyns);return[new Path(pathSteps.reverse()),handlers]}static fromEvent(e,rNode,maxDepth,comps,stopOnNoEvent=!0){let{type:type3,target}=e;return Path.fromNodeAndEventName(target,type3,rNode,maxDepth,comps,stopOnNoEvent)}}var EMPTY_META={};function parseMetaComment(n){if(n?.nodeType===8&&n.textContent[0]==="§"){let m=parseMetaComment(n.previousSibling);if(m!==EMPTY_META)return m;try{return JSON.parse(n.textContent.slice(1,-1))}catch(err){console.warn(err,n)}}return EMPTY_META}function findHandlers(comp,eventIds,vid,eventName){for(let eid of eventIds){let handlers=comp.getEventForId(+eid,vid).getHandlersFor(eventName);if(handlers!==null)return handlers}return null}class StepCtx{constructor(comp,nodeIds,idx,vid){this.comp=comp,this.nodeIds=nodeIds,this.idx=idx,this.vid=vid}get meta(){return this.nodeIds[this.idx]}get key(){let m=this.meta;return m.si!==void 0?+m.si:m.sk}get hasKey(){let m=this.meta;return m.si!==void 0||m.sk!==void 0}next(){let{idx,nodeIds}=this;return idx+1<nodeIds.length?new StepCtx(this.comp,nodeIds,idx+1,this.vid):null}resolveNode(){return this.comp.getNodeForId(+this.meta.nid,this.vid)}applyKey(pi){if(pi===null)return null;let m=this.meta;if(m.si!==void 0)return pi.withIndex(+m.si);if(m.sk!==void 0)return pi.withKey(m.sk);return pi}}function resolvePathStep(comp,nodeIds,vid){for(let i=0;i<nodeIds.length;i++){let ctx=new StepCtx(comp,nodeIds,i,vid),step=ctx.resolveNode().toPathStep(ctx);if(step!==null)return step}return null}var NO_EVENT_INFO=[null,null],BUBBLING_EVENTS=new Set(["drop"]);class PathBuilder{constructor(){this.pathChanges=[]}add(pathChange){return this.pathChanges.push(pathChange),this}field(name){return this.add(new FieldStep(name))}index(name,index){return this.add(new SeqStep(name,index))}key(name,key){return this.add(new SeqStep(name,key))}}var VALID_VAL_ID_RE=/^[a-zA-Z][a-zA-Z0-9_]*\??$/,isValidValId=(name)=>VALID_VAL_ID_RE.test(name),VALID_FLOAT_RE=/^-?[0-9]+(\.[0-9]+)?$/,STR_TPL_SPLIT_RE=/(\{[^}]+\})/g,mkVal=(name,Cls)=>isValidValId(name)?new Cls(name):null,VAL_TOKEN_RE=/\$'(?:[^'\\]|\\.)*'|'(?:[^'\\]|\\.)*'|\S+/g,tokenizeValue=(s)=>s.match(VAL_TOKEN_RE)??[],unescapeStr=(s)=>s.replace(/\\(['\\])/g,"$1"),K_CONST=1,K_STRTPL=2,K_FIELD=4,K_BIND=8,K_DYN=16,K_NAME=32,K_TYPE=64,K_REQUEST=128,K_SEQ=256,K_STR=512,K_METHOD=1024,G_BOOL=K_FIELD|K_METHOD|K_BIND|K_DYN|K_CONST,G_TEXT=G_BOOL|K_STRTPL,G_COMPONENT=K_FIELD|K_SEQ|K_DYN,G_SEQUENCE=K_FIELD|K_DYN,G_FIELD=K_FIELD|K_METHOD|K_CONST|K_STR|K_SEQ,G_VALUE=K_FIELD|K_METHOD|K_BIND|K_DYN|K_NAME|K_TYPE|K_REQUEST|K_CONST,G_PRED_ARG=G_BOOL|K_STR,G_HANDLER_ARG=G_VALUE|K_STR,G_ALL=G_VALUE|K_STRTPL|K_SEQ;function sizeOf(v){if(v==null)return null;let s=v.size;if(typeof s==="number")return s;let l=v.length;return typeof l==="number"?l:null}var predTruthy=(v)=>{let n=sizeOf(v);return n===null?!!v:n>0},PREDICATES={"empty?":{name:"empty?",arity:1,fn:(v)=>v==null||sizeOf(v)===0},"truthy?":{name:"truthy?",arity:1,fn:predTruthy},"falsy?":{name:"falsy?",arity:1,fn:(v)=>!predTruthy(v)},"null?":{name:"null?",arity:1,fn:(v)=>v==null},"equals?":{name:"equals?",arity:2,fn:(a,b)=>is(a,b)}};class ValParser{constructor(){this.bindValIt=new BindVal("it"),this.nullConstVal=new ConstVal(null)}const(v){return new ConstVal(v)}parseToken(s,px){let c0=s.charCodeAt(0);if(c0===39)return s.length>=2&&s.charCodeAt(s.length-1)===39?new ConstVal(unescapeStr(s.slice(1,-1)),K_STR|K_STRTPL):null;if(c0===36&&s.charCodeAt(1)===39)return s.length>=3&&s.charCodeAt(s.length-1)===39?StrTplVal.parse(s.slice(2,-1),px):null;if(s.indexOf("[")!==-1||s.indexOf("]")!==-1)return this._parseSeqAccess(s,px);if(s.indexOf("{")!==-1||s.indexOf("}")!==-1)return null;switch(c0){case 94:{let name=s.slice(1),newS=px.frame.macroVars?.[name];if(newS!==void 0){let tokens=tokenizeValue(newS.trim());if(tokens.length!==1)return null;let val=this.parseToken(tokens[0],px);if(val instanceof ConstVal)val.fromMacroVar=!0;return val}return px.onParseIssue("bad-value",{role:"macro-var",name,value:s}),null}case 36:return mkVal(s.slice(1),MethodVal);case 64:return mkVal(s.slice(1),BindVal);case 42:return mkVal(s.slice(1),DynVal);case 46:return mkVal(s.slice(1),FieldVal);case 33:return mkVal(s.slice(1),RequestVal)}let num=VALID_FLOAT_RE.test(s)?parseFloat(s):null;if(Number.isFinite(num))return new ConstVal(num);if(s==="true"||s==="false")return new ConstVal(s==="true");if(c0>=97&&c0<=122)return mkVal(s,NameVal);if(c0>=65&&c0<=90)return mkVal(s,TypeVal);return null}_parseSeqAccess(s,px){let open=s.indexOf("["),close=s.indexOf("]");if(open<1||close!==s.length-1||close<open||s.indexOf("[",open+1)!==-1)return null;let left=this.parseToken(s.slice(0,open),px),right=this.parseToken(s.slice(open+1,close),px);return left instanceof FieldVal&&right instanceof FieldVal?new SeqAccessVal(left,right):null}_parseSingle(s,px,group){let tokens=tokenizeValue(s.trim());if(tokens.length!==1)return null;let val=this.parseToken(tokens[0],px);return val!==null&&kindOf(val)&group?val:null}parseBool(s,px){let t=s.trim(),tokens=tokenizeValue(t);if(tokens.length!==1)return tokens.length===0?null:this._parsePredicate(t,tokens,px);let val=this.parseToken(tokens[0],px);return val!==null&&kindOf(val)&G_BOOL?val:null}parseText(s,px){return this._parseSingle(s,px,G_TEXT)}parseComponent(s,px){return this._parseSingle(s,px,G_COMPONENT)}parseSequence(s,px){return this._parseSingle(s,px,G_SEQUENCE)}parseField(s,px){return this._parseSingle(s,px,G_FIELD)}parseHandlerArg(s,px){return this._parseSingle(s,px,G_HANDLER_ARG)}parseMacroAttr(s,px){return this._parseSingle(s,px,G_ALL)}parseInputHandler(s,px){return this._parseHandler(s,px,"input",!0,!0)}parseAlterHandler(s,px){let r=this._parseHandler(s,px,"alter",!1,!1);return r===null?null:r.handlerVal}_parseHandler(s,px,namespace,allowArgs,report){let tokens=tokenizeValue(s.trim()),headTok=tokens[0]??"",head=headTok===""?null:this.parseToken(headTok,px),hk=kindOf(head),handlerVal;if(hk&K_METHOD)handlerVal=head;else if(hk&K_NAME)handlerVal=new HandlerNameVal(head.name,namespace);else{if(report)px.onParseIssue("bad-value",{role:"handler-name",value:headTok});return null}if(!allowArgs)return tokens.length===1?{handlerVal,args:[]}:null;let args=Array(tokens.length-1);for(let i=1;i<tokens.length;i++){let val=this.parseToken(tokens[i],px);if(val!==null&&kindOf(val)&G_HANDLER_ARG)args[i-1]=val;else{if(report)px.onParseIssue("bad-value",{role:"handler-arg",value:tokens[i]});args[i-1]=this.nullConstVal}}return{handlerVal,args}}_parsePredicate(s,tokens,px){let predName=tokens[0],pred=PREDICATES[predName];if(pred===void 0)return px.onParseIssue("bad-value",{role:"predicate",value:predName}),null;let arity=tokens.length-1;if(arity!==pred.arity)return px.onParseIssue("bad-value",{role:"predicate-arity",value:s,predicate:predName}),null;let args=Array(arity);for(let i=0;i<arity;i++){let tok=tokens[i+1],val=this.parseToken(tok,px);if(val===null||!(kindOf(val)&G_PRED_ARG))return px.onParseIssue("bad-value",{role:"predicate-arg",value:tok}),null;args[i]=val}return new PredicateVal(pred,args)}}function kindOf(val){if(val===null)return 0;if(val instanceof ConstVal)return val.kind;if(val instanceof StrTplVal)return K_STRTPL;if(val instanceof SeqAccessVal)return K_SEQ;if(val instanceof FieldVal)return K_FIELD;if(val instanceof MethodVal)return K_METHOD;if(val instanceof BindVal)return K_BIND;if(val instanceof DynVal)return K_DYN;if(val instanceof RequestVal)return K_REQUEST;if(val instanceof TypeVal)return K_TYPE;if(val instanceof NameVal)return K_NAME;return 0}class BaseVal{render(_stack,_rx){}eval(_stack){}toPathItem(){return null}evalAsHandler(stack){return this.eval(stack)}}class ConstVal extends BaseVal{constructor(val,kind=K_CONST){super();this.val=val,this.kind=kind}render(_stack,_rx){return this.val}eval(_stack){return this.val}toString(){let v=this.val;return typeof v==="string"?`'${v.replace(/(['\\])/g,"\\$1")}'`:`${v}`}}class PredicateVal extends BaseVal{constructor(pred,args){super();this.pred=pred,this.args=args}eval(stack){let n=this.args.length,vals=Array(n);for(let i=0;i<n;i++)vals[i]=this.args[i].eval(stack);return this.pred.fn(...vals)}toString(){return`${this.pred.name} ${this.args.map(String).join(" ")}`}}class VarVal extends BaseVal{}class StrTplVal extends VarVal{constructor(vals){super();this.vals=vals}render(stack,_rx){return this.eval(stack)}eval(stack){let strs=Array(this.vals.length);for(let i=0;i<this.vals.length;i++)strs[i]=this.vals[i]?.eval(stack,"");return strs.join("")}toLiteralSource(){let out="";for(let v of this.vals){if(!(v instanceof ConstVal)||v.fromMacroVar)return null;out+=v.val}return new ConstVal(out).toString()}static parse(s,px){let parts=unescapeStr(s).split(STR_TPL_SPLIT_RE),vals=Array(parts.length);for(let i=0;i<parts.length;i++){let part=parts[i],isExpr=part[0]==="{"&&part.at(-1)==="}";vals[i]=isExpr?vp.parseText(part.slice(1,-1),px):new ConstVal(part)}let lo=0,hi=vals.length,isTrimmable=(v)=>v instanceof ConstVal&&v.val===""&&!v.fromMacroVar;while(lo<hi&&isTrimmable(vals[lo]))lo++;while(hi>lo&&isTrimmable(vals[hi-1]))hi--;return new StrTplVal(lo===0&&hi===vals.length?vals:vals.slice(lo,hi))}}class NameVal extends VarVal{constructor(name){super();this.name=name}eval(stack){return stack.lookupName(this.name)}toString(){return this.name}}class HandlerNameVal extends NameVal{constructor(name,namespace){super(name);this.namespace=namespace}eval(stack){return stack.getHandlerFor(this.name,this.namespace)??mk404Handler(this.namespace,this.name)}}var mk404Handler=(type3,name)=>function(...args){return console.warn("handler not found",{type:type3,name,args},this),this};class TypeVal extends NameVal{eval(stack){return stack.lookupType(this.name)}}class RequestVal extends NameVal{eval(stack){return stack.lookupRequest(this.name)}toString(){return`!${this.name}`}}class RenderVal extends BaseVal{render(stack,_rx){return this.eval(stack)}}class RenderNameVal extends RenderVal{constructor(name){super();this.name=name}}class BindVal extends RenderNameVal{eval(stack){return stack.lookupBind(this.name)}toString(){return`@${this.name}`}}class DynVal extends RenderNameVal{eval(stack){return stack.lookupDynamic(this.name)}toPathItem(){return null}toString(){return`*${this.name}`}}class FieldVal extends RenderNameVal{eval(stack){return stack.lookupFieldRaw(this.name)}toPathItem(){return new FieldStep(this.name)}toString(){return`.${this.name}`}}class MethodVal extends RenderNameVal{eval(stack){return stack.lookupMethod(this.name)}evalAsHandler(stack){return stack.lookupFieldRaw(this.name)}toString(){return`$${this.name}`}}class SeqAccessVal extends RenderVal{constructor(seqVal,keyVal){super();this.seqVal=seqVal,this.keyVal=keyVal}toPathItem(){return new SeqAccessStep(this.seqVal.name,this.keyVal.name)}eval(stack){let key=this.keyVal.eval(stack);return this.seqVal.eval(stack)?.get(key,null)}toString(){return`${this.seqVal}[${this.keyVal}]`}}var vp=new ValParser;class Attributes{constructor(items){this.items=items}eval(_stack){return{}}static parse(attributes,px,parseAll=!1){return getAttrParser(px).parse(attributes,parseAll)}isConstant(){return!1}}var booleanAttrsRaw="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected",booleanAttrs=new Set(booleanAttrsRaw.split(","));class AttrParser{constructor(px){this.clear(px)}clear(px){this.px=px,this.attrs=null,this.hasDynamic=!1,this.wrapperAttrs=null,this.textChild=null,this.eachAttr=null,this.ifAttr=null,this.events=null}parseAttr(name,value,parseAll=!1){let val=parseAll?vp.parseMacroAttr(value,this.px):vp.parseText(value,this.px);if(val!==null)this.attrs??=[],this.attrs.push(new Attr(name,val)),this.hasDynamic||=!(val instanceof ConstVal);else this.px.onParseIssue("bad-value",{role:"attr",attr:name,value})}pushWrapper(name,raw,val){let node={name,val,raw};return this.wrapperAttrs??=[],this.wrapperAttrs.push(node),node}parseIf(directiveName,value){let dynVal=vp.parseBool(value,this.px);if(dynVal)this.ifAttr=new IfAttr(directiveName.slice(3),dynVal),this.attrs??=[],this.attrs.push(this.ifAttr),this.hasDynamic=!0;else{let info={role:"if",attr:directiveName.slice(3),value};this.px.onParseIssue("bad-value",info)}}parseThen(s){if(this.ifAttr)this.ifAttr.thenVal=vp.parseText(s,this.px)??NOT_SET_VAL}parseElse(value){if(this.ifAttr)this.ifAttr.elseVal=vp.parseText(value,this.px)??NOT_SET_VAL}parseEvent(directiveName,value){let[eventName,...modifiers]=directiveName.slice(3).split("+"),handler=EventHandler.parse(value,this.px);if(handler){if(this.events===null)this.events=this.px.registerEvents(),this.attrs??=[],this.attrs.push(new ConstAttr("data-eid",vp.const(this.events.id)));this.events.add(eventName,handler,modifiers)}}_parseDirectiveValue(directiveName,s,parserFn){let val=parserFn.call(vp,s,this.px);if(val===null){let info={role:"directive",directive:directiveName,value:s};this.px.onParseIssue("bad-value",info)}return val}parseDirective(s,directiveName){switch(directiveName){case"dangerouslysetinnerhtml":this.attrs??=[],this.attrs.push(new RawHtmlAttr(this._parseDirectiveValue(directiveName,s,vp.parseText))),this.hasDynamic=!0;return;case"slot":this.pushWrapper("slot",s,vp.const(s));return;case"push-view":this.pushWrapper("push-view",s,this._parseDirectiveValue(directiveName,s,vp.parseText));return;case"text":this.textChild=this._parseDirectiveValue(directiveName,s,vp.parseText);return;case"show":this.pushWrapper("show",s,this._parseDirectiveValue(directiveName,s,vp.parseBool));return;case"hide":this.pushWrapper("hide",s,this._parseDirectiveValue(directiveName,s,vp.parseBool));return;case"each":{let val=this._parseDirectiveValue(directiveName,s,vp.parseSequence);this.eachAttr=this.pushWrapper("each",s,val);return}case"enrich-with":if(this.eachAttr!==null)this.eachAttr.enrichWithVal=this._parseDirectiveValue(directiveName,s,vp.parseAlterHandler);else this.pushWrapper("scope",s,this._parseDirectiveValue(directiveName,s,vp.parseAlterHandler));return;case"when":this._parseWhen(s);return;case"loop-with":this._parseLoopWith(s);return;case"then":this.parseThen(s);return;case"else":this.parseElse(s);return}if(directiveName.startsWith("on."))this.parseEvent(directiveName,s);else if(directiveName.startsWith("if."))this.parseIf(directiveName,s);else if(directiveName.startsWith("then."))this.parseThen(s);else if(directiveName.startsWith("else."))this.parseElse(s);else{let info={name:directiveName,value:s};this.px.onParseIssue("unknown-directive",info)}}_parseWhen(s){if(this.eachAttr!==null)this.eachAttr.whenVal=this._parseDirectiveValue("when",s,vp.parseAlterHandler)}_parseLoopWith(s){if(this.eachAttr!==null)this.eachAttr.loopWithVal=this._parseDirectiveValue("loop-with",s,vp.parseAlterHandler)}parse(attributes,parseAll=!1){for(let{name,value}of attributes){let charCode=name.charCodeAt(0);if(charCode===58)this.parseAttr(name===":viewbox"?"viewBox":name.slice(1),value,parseAll);else if(charCode===64)this.parseDirective(value,name.slice(1));else{this.attrs??=[];let constVal=value===""&&booleanAttrs.has(name)?!0:value;this.attrs.push(new ConstAttr(name,vp.const(constVal)))}}let{attrs,hasDynamic}=this;return[hasDynamic?new DynAttrs(attrs):ConstAttrs.fromAttrs(attrs??[]),this.wrapperAttrs,this.textChild]}}class ConstAttrs extends Attributes{eval(_stack){return this.items}static fromAttrs(attrs){let attrsObj={};for(let attr of attrs)attrsObj[attr.name]=attr.val.eval(null);return new ConstAttrs(attrsObj)}setDataAttr(key,val){this.items[key]=val}toMacroVars(){let r={};for(let name in this.items)r[name]=`'${this.items[name]}'`;return r}isConstant(){return!0}}class DynAttrs extends Attributes{eval(stack){let attrs={};for(let i=0;i<this.items.length;i++){let attr=this.items[i];attrs[attr.name]=attr.eval(stack)}return attrs}setDataAttr(key,val){this.items.push(new ConstAttr(key,new ConstVal(val)))}toMacroVars(){let r={};for(let attr of this.items)r[attr.name]=attr.val.toString();return r}}class BaseAttr{constructor(name){this.name=name}}class Attr extends BaseAttr{constructor(name,val){super(name);this.val=val}eval(stack){return this.val.eval(stack)}}class ConstAttr extends Attr{}class RawHtmlAttr extends Attr{constructor(val){super("dangerouslySetInnerHTML",val??vp.nullConstVal)}eval(stack){return{__html:`${this.val.eval(stack)}`}}}var NOT_SET_VAL=vp.nullConstVal;class IfAttr extends BaseAttr{constructor(name,condVal){super(name);this.condVal=condVal,this.thenVal=this.elseVal=NOT_SET_VAL}get anyBranchIsSet(){return this.thenVal!==NOT_SET_VAL||this.elseVal!==NOT_SET_VAL}eval(stack){return this.condVal.eval(stack)?this.thenVal.eval(stack):this.elseVal.eval(stack)}}var _attrParser=null;function getAttrParser(px){return _attrParser??=new AttrParser(px),_attrParser.clear(px),_attrParser}class EventHandler{constructor(handlerVal,args=[]){this.handlerVal=handlerVal,this.args=args}getHandlerAndArgs(stack,_event){let argValues=Array(this.args.length);for(let i=0;i<argValues.length;i++)argValues[i]=this.args[i].eval(stack);return[this.handlerVal.evalAsHandler(stack),argValues]}static parse(s,px){let r=vp.parseInputHandler(s,px);return r===null?null:new EventHandler(r.handlerVal,r.args)}}class RequestHandler{constructor(name,fn){this.name=name,this.fn=fn}toHandlerArg(disp){let f=(...args)=>disp.request(this.name,args);return f.withOpts=(...args)=>disp.request(this.name,args.slice(0,-1),args.at(-1)),f}}var isHtmlAttribute=(propName)=>propName[4]==="-"&&(propName[0]==="d"||propName[0]==="a"),HTML_NS="http://www.w3.org/1999/xhtml",isNamespaced=(node)=>{let ns=node.namespaceURI;return ns!==null&&ns!=="http://www.w3.org/1999/xhtml"};function applyProperties(node,props,previous){let namespaced=isNamespaced(node);for(let propName in props){let propValue=props[propName];if(propValue===void 0)removeProperty(node,propName,previous);else if(propName==="dangerouslySetInnerHTML")node.innerHTML=propValue.__html??"";else if(propName==="className")node.setAttribute("class",propValue);else if(namespaced||isHtmlAttribute(propName))node.setAttribute(propName,propValue);else node[propName]=propValue}}function removeProperty(node,propName,previous){let previousValue=previous[propName];if(propName==="dangerouslySetInnerHTML")node.replaceChildren();else if(propName==="className")node.removeAttribute("class");else if(propName==="htmlFor")node.removeAttribute("for");else if(isNamespaced(node)||typeof previousValue==="string"||isHtmlAttribute(propName))node.removeAttribute(propName);else node[propName]=null}class VBase{}var getKey=(child)=>child instanceof VNode2?child.key:void 0,isIterable=(obj)=>obj!=null&&typeof obj!=="string"&&typeof obj[Symbol.iterator]==="function";function childsEqual(a,b){if(a===b)return!0;for(let i=0;i<a.length;i++)if(!a[i].isEqualTo(b[i]))return!1;return!0}function appendChildNodes(parent,childs,opts){for(let child of childs)parent.appendChild(child.toDom(opts))}function addChild(normalizedChildren,child){if(child==null)return;if(isIterable(child))for(let c of child)addChild(normalizedChildren,c);else if(child instanceof VBase)if(child instanceof VFragment)normalizedChildren.push(...child.childs);else normalizedChildren.push(child);else normalizedChildren.push(new VText(child))}class VText extends VBase{constructor(text){super();this.text=String(text)}get nodeType(){return 3}isEqualTo(other){return other instanceof VText&&this.text===other.text}toDom(opts){return opts.document.createTextNode(this.text)}}class VComment extends VBase{constructor(text){super();this.text=text}get nodeType(){return 8}isEqualTo(other){return other instanceof VComment&&this.text===other.text}toDom(opts){return opts.document.createComment(this.text)}}class VFragment extends VBase{constructor(childs){super();this.childs=[],addChild(this.childs,childs)}get nodeType(){return 11}isEqualTo(other){if(!(other instanceof VFragment)||this.childs.length!==other.childs.length)return!1;return childsEqual(this.childs,other.childs)}toDom(opts){let fragment=opts.document.createDocumentFragment();return appendChildNodes(fragment,this.childs,opts),fragment}}class VNode2 extends VBase{constructor(tag,attrs,childs,key,namespace){super();this.tag=tag,this.attrs=attrs??{},this.childs=childs??[],this.key=key!=null?String(key):void 0,this.namespace=typeof namespace==="string"?namespace:null}get nodeType(){return 1}isSameKind(other){return this.tag===other.tag&&this.namespace===other.namespace&&this.key===other.key}isEqualTo(other){if(this===other)return!0;if(!(other instanceof VNode2)||!this.isSameKind(other)||this.childs.length!==other.childs.length)return!1;if(this.attrs!==other.attrs){for(let key in this.attrs)if(this.attrs[key]!==other.attrs[key])return!1;for(let key in other.attrs)if(!Object.hasOwn(this.attrs,key))return!1}return childsEqual(this.childs,other.childs)}toDom(opts){let doc=opts.document,node=this.namespace===null?doc.createElement(this.tag):doc.createElementNS(this.namespace,this.tag);if(this.tag==="SELECT"&&"value"in this.attrs){let{value,...rest}=this.attrs;applyProperties(node,rest,{}),appendChildNodes(node,this.childs,opts),applyProperties(node,{value},{})}else applyProperties(node,this.attrs,{}),appendChildNodes(node,this.childs,opts);return node}}function diffProps(a,b){if(a===b)return null;let diff=null;for(let aKey in a)if(!Object.hasOwn(b,aKey))diff??={},diff[aKey]=void 0;else if(a[aKey]!==b[aKey])diff??={},diff[aKey]=b[aKey];for(let bKey in b)if(!Object.hasOwn(a,bKey))diff??={},diff[bKey]=b[bKey];return diff}function morphNode(domNode,source,target,opts){if(source===target||source.isEqualTo(target))return domNode;let type3=source.nodeType;if(type3===target.nodeType){if(type3===3||type3===8)return domNode.data=target.text,domNode;if(type3===1&&source.isSameKind(target)){let propsDiff=diffProps(source.attrs,target.attrs),isSelect=source.tag==="SELECT";if(propsDiff)if(isSelect&&"value"in propsDiff){let{value:_v,...rest}=propsDiff;applyProperties(domNode,rest,source.attrs)}else applyProperties(domNode,propsDiff,source.attrs);if(!target.attrs.dangerouslySetInnerHTML)morphChildren(domNode,source.childs,target.childs,opts);if(isSelect&&target.attrs.value!==void 0)applyProperties(domNode,{value:target.attrs.value},source.attrs);return domNode}if(type3===11)return morphChildren(domNode,source.childs,target.childs,opts),domNode}let newNode=target.toDom(opts);return domNode.parentNode?.replaceChild(newNode,domNode),newNode}function morphChildren(parentDom,oldChilds,newChilds,opts){if(oldChilds.length===0){appendChildNodes(parentDom,newChilds,opts);return}if(newChilds.length===0){parentDom.replaceChildren();return}if(oldChilds.length===newChilds.length){let hasKey=!1;for(let i=0;i<oldChilds.length;i++)if(getKey(oldChilds[i])!=null||getKey(newChilds[i])!=null){hasKey=!0;break}if(!hasKey){let dom=parentDom.firstChild;for(let i=0;i<oldChilds.length;i++){let next=dom.nextSibling;morphNode(dom,oldChilds[i],newChilds[i],opts),dom=next}return}}let domNodes=Array.from(parentDom.childNodes),oldKeyMap=Object.create(null);for(let i=0;i<oldChilds.length;i++){let key=getKey(oldChilds[i]);if(key!=null)oldKeyMap[key]=i}let used2=new Uint8Array(oldChilds.length),unkeyedCursor=0;for(let j=0;j<newChilds.length;j++){let newChild=newChilds[j],newKey=getKey(newChild),oldIdx=-1;if(newKey!=null){if(newKey in oldKeyMap&&!used2[oldKeyMap[newKey]])oldIdx=oldKeyMap[newKey]}else while(unkeyedCursor<oldChilds.length){if(!used2[unkeyedCursor]&&getKey(oldChilds[unkeyedCursor])==null){oldIdx=unkeyedCursor++;break}unkeyedCursor++}if(oldIdx>=0){used2[oldIdx]=1;let newDom=morphNode(domNodes[oldIdx],oldChilds[oldIdx],newChild,opts),ref=parentDom.childNodes[j]??null;if(newDom!==ref)parentDom.insertBefore(newDom,ref)}else{let ref=parentDom.childNodes[j]??null;parentDom.insertBefore(newChild.toDom(opts),ref)}}for(let i=oldChilds.length-1;i>=0;i--)if(!used2[i]&&domNodes[i].parentNode===parentDom)parentDom.removeChild(domNodes[i])}function render(vnode,container,options,prev){let isFragment=vnode instanceof VFragment;if(prev&&prev.vnode instanceof VFragment===isFragment){let oldDom=isFragment?container:prev.dom,newDom=morphNode(oldDom,prev.vnode,vnode,options);return{vnode,dom:isFragment?container:newDom}}let domNode=vnode.toDom(options);return container.replaceChildren(domNode),{vnode,dom:isFragment?container:domNode}}function h(tagName,properties,children,namespace){let props={},key;if(properties)for(let propName in properties){let propVal=properties[propName];switch(propName){case"key":key=propVal;break;case"namespace":namespace=namespace??propVal;break;case"class":props.className=propVal;break;case"for":props.htmlFor=propVal;break;default:props[propName]=isHtmlAttribute(propName)?String(propVal):propVal}}let c=tagName.charCodeAt(0),tag=namespace==null&&c>=97&&c<=122?tagName.toUpperCase():tagName,normalizedChildren=[];return addChild(normalizedChildren,children),new VNode2(tag,props,normalizedChildren,key,namespace)}function resolveDynProducer(comp,dynName){let dyn=comp?.dynamic?.[dynName];if(dyn==null)return null;let producerComp,producerDyn;if(dyn.compName!=null)producerComp=comp.scope?.lookupComponent(dyn.compName),producerDyn=producerComp?.dynamic?.[dyn.dynName];else producerComp=comp,producerDyn=dyn;if(producerComp==null||producerDyn==null)return null;let pi=producerDyn.val?.toPathItem?.()??null;return{producerCompId:producerComp.id,producerSteps:pi?[pi]:[]}}class BaseNode{render(_stack,_rx){return null}setDataAttr(key,val){console.warn("setDataAttr not implemented for",this,{key,val})}isConstant(){return!1}optimize(){}}class TextNode extends BaseNode{constructor(val){super();this.val=val}render(_stack,_rx){return this.val}isWhiteSpace(){for(let i=0;i<this.val.length;i++){let c=this.val.charCodeAt(i);if(!(c===32||c===10||c===9||c===13))return!1}return!0}hasNewLine(){for(let i=0;i<this.val.length;i++){let c=this.val.charCodeAt(i);if(c===10||c===13)return!0}return!1}condenseWhiteSpace(replacement=""){this.val=replacement}isConstant(){return!0}setDataAttr(_key,_val){}}class CommentNode extends TextNode{render(_stack,rx){return rx.renderComment(this.val)}}function optimizeChilds(childs){for(let i=0;i<childs.length;i++){let child=childs[i];if(child.isConstant())childs[i]=new RenderOnceNode(child);else child.optimize()}}function optimizeNode(node){if(node.isConstant())return new RenderOnceNode(node);return node.optimize(),node}class ChildsNode extends BaseNode{constructor(childs){super();this.childs=childs}isConstant(){return this.childs.every((v)=>v.isConstant())}optimize(){optimizeChilds(this.childs)}}class DomNode extends ChildsNode{constructor(tagName,attrs,childs,namespace=null){super(childs);this.tagName=tagName,this.attrs=attrs,this.namespace=namespace}render(stack,rx){let childNodes=Array(this.childs.length);for(let i=0;i<childNodes.length;i++)childNodes[i]=this.childs[i]?.render?.(stack,rx)??null;return rx.renderTag(this.tagName,this.attrs.eval(stack),childNodes,this.namespace)}setDataAttr(key,val){this.attrs.setDataAttr(key,val)}isConstant(){return this.attrs.isConstant()&&super.isConstant()}}class FragmentNode extends ChildsNode{render(stack,rx){return rx.renderFragment(this.childs.map((c)=>c?.render(stack,rx)))}setDataAttr(key,val){for(let child of this.childs)child.setDataAttr(key,val)}}var maybeFragment=(xs)=>xs.length===1?xs[0]:new FragmentNode(xs),VALID_NODE_RE=/^[a-zA-Z][a-zA-Z0-9-]*$/;class ANode extends BaseNode{constructor(nodeId,val){super();this.nodeId=nodeId,this.val=val}toPathStep(ctx){return ctx.applyKey(this.val?.toPathItem?.()??null)}static parse(html,px){let nodes=px.parseHTML(html);if(nodes.length===0)return new CommentNode("Empty View in ANode.parse");if(nodes.length===1)return ANode.fromDOM(nodes[0],px);let childs=[];for(let i=0;i<nodes.length;i++){let child=ANode.fromDOM(nodes[i],px);if(child!==null)childs.push(child)}let trimmed=condenseChildsWhites(childs);if(trimmed.length===0)return new CommentNode("Empty View in ANode.parse");return maybeFragment(trimmed)}static fromDOM(node,px){if(node instanceof px.Text)return new TextNode(node.textContent);else if(node instanceof px.Comment)return new CommentNode(node.textContent);let{childNodes,attributes:attrs,tagName:tag}=node,childs=[];for(let i=0;i<childNodes.length;i++){let child=ANode.fromDOM(childNodes[i],px);if(child!==null)childs.push(child)}let prevTag=px.currentTag;px.currentTag=tag;try{let isPseudoX=attrs[0]?.name==="@x";if(tag==="X"||isPseudoX)return parseXOp(attrs,childs,isPseudoX?1:0,px);else if(tag.charCodeAt(1)===58&&tag.charCodeAt(0)===88){let macroName=tag.slice(2).toLowerCase();if(macroName==="slot"){let slotName=attrs.getNamedItem("name")?.value??"_";return px.frame.macroSlots[slotName]??maybeFragment(childs)}let[nAttrs,wrappers]=Attributes.parse(attrs,px,!0);return px.onAttributes(nAttrs,wrappers,null,!0,tag),wrap(px.newMacroNode(macroName,nAttrs.toMacroVars(),childs),px,wrappers)}else if(VALID_NODE_RE.test(tag)){let[nAttrs,wrappers,textChild]=Attributes.parse(attrs,px);if(px.onAttributes(nAttrs,wrappers,textChild,!1,tag),textChild)childs.unshift(new RenderTextNode(null,textChild));let domChilds=tag!=="PRE"?condenseChildsWhites(childs):childs,ns=node.namespaceURI;return wrap(new DomNode(tag,nAttrs,domChilds,ns&&ns!==HTML_NS?ns:null),px,wrappers)}return new CommentNode(`Error: InvalidTagName ${tag}`)}finally{px.currentTag=prevTag}}}function parseXOp(attrs,childs,opIdx,px){if(attrs.length===0)return maybeFragment(childs);let{name,value}=attrs[opIdx],as=attrs.getNamedItem("as")?.value??null,node;switch(name){case"slot":node=new SlotNode(null,vp.const(value),maybeFragment(childs));break;case"text":node=px.addNodeIf(RenderTextNode,parseXOpVal(name,value,px,vp.parseText));break;case"render":node=px.addNodeIf(RenderNode,parseXOpVal(name,value,px,vp.parseComponent),as);break;case"render-it":node=px.addNodeIf(RenderItNode,vp.bindValIt,as);break;case"render-each":node=RenderEachNode.parse(px,vp,value,as,attrs);break;case"show":{let val=parseXOpVal(name,value,px,vp.parseBool);node=px.addNodeIf(ShowNode,val,maybeFragment(childs));break}case"hide":{let val=parseXOpVal(name,value,px,vp.parseBool);node=px.addNodeIf(HideNode,val,maybeFragment(childs));break}default:return px.onParseIssue("unknown-x-op",{name,value}),new CommentNode(`Error: InvalidSpecialTagOp ${name}=${value}`)}return processXExtras(node,attrs,name,opIdx+1,px)}function parseXOpVal(opName,value,px,parserFn){let val=parserFn.call(vp,value,px);if(val===null)px.onParseIssue("bad-value",{role:"x-op",op:opName,value});return val}function processXExtras(node,attrs,opName,startIdx,px){let consumed=X_OP_CONSUMED[opName],wrappable=X_OP_WRAPPABLE.has(opName),wrappers=[];for(let i=startIdx;i<attrs.length;i++){let a=attrs[i],aName=a.name;if(consumed.has(aName))continue;if(wrappable&&X_ATTR_WRAPPERS[aName]){wrappers.push([X_ATTR_WRAPPERS[aName],vp.parseBool(a.value,px)]);continue}let issueInfo={op:opName,name:aName,value:a.value};px.onParseIssue("unknown-x-attr",issueInfo)}for(let i=wrappers.length-1;i>=0;i--){let[Cls,val]=wrappers[i],wrapper=px.addNodeIf(Cls,val,node);if(wrapper!==null)node=wrapper}return node}function wrap(node,px,wrappers){if(wrappers)for(let i=wrappers.length-1;i>=0;i--){let wrapperNode=makeWrapperNode(wrappers[i],px);if(wrapperNode)wrapperNode.wrapNode(node),node=wrapperNode}return node}function makeWrapperNode(data,px){let Cls=WRAPPER_NODES[data.name],node=Cls.register?px.addNodeIf(Cls,data.val):data.val&&new Cls(null,data.val);if(node!==null&&data.name==="each")node.iterInfo.enrichWithVal=data.enrichWithVal??null,node.iterInfo.whenVal=data.whenVal??null,node.iterInfo.loopWithVal=data.loopWithVal??null;return node}class MacroNode extends BaseNode{constructor(name,attrs,slots,px){super();this.name=name,this.attrs=attrs,this.slots=slots,this.px=px,this.node=null,this.dataAttrs={}}compile(scope){let{name,attrs,slots}=this;if(this.px.isInsideMacro(name))throw Error(`Recursive macro expansion: ${name}`);let macro=scope.lookupMacro(name);if(macro===null)this.node=new CommentNode(`bad macro: ${name}`);else{let vars={...macro.defaults,...attrs};this.node=macro.expand(this.px.enterMacro(name,vars,slots));for(let key in this.dataAttrs)this.node.setDataAttr(key,this.dataAttrs[key])}}render(stack,rx){return this.node.render(stack,rx)}setDataAttr(key,val){this.dataAttrs[key]=val}isConstant(){return this.node.isConstant()}optimize(){this.node=optimizeNode(this.node)}}class Macro{constructor(defaults,rawView){this.defaults=defaults,this.rawView=rawView}expand(px){return ANode.parse(this.rawView,px)}}class RenderViewId extends ANode{constructor(nodeId,val,viewId){super(nodeId,val);this.viewId=viewId}}class RenderNode extends RenderViewId{render(stack,rx){let newStack=stack.enter(this.val.eval(stack),{},!0);return rx.renderIt(newStack,this,"",this.viewId)}toPathStep(ctx){if(this.val instanceof DynVal){let p=resolveDynProducer(ctx.comp,this.val.name);return p?new DynStep(p.producerCompId,p.producerSteps):null}return super.toPathStep(ctx)}}class RenderItNode extends RenderViewId{render(stack,rx){let newStack=stack.enter(stack.it,{},!0);return rx.renderIt(newStack,this,"",this.viewId)}toPathStep(ctx){let next=ctx.next();if(next===null)return null;let nextNode=next.resolveNode();if(nextNode instanceof EachNode&&next.hasKey){if(nextNode.val instanceof DynVal){let p=resolveDynProducer(ctx.comp,nextNode.val.name);return p?new DynEachStep(p.producerCompId,p.producerSteps,next.key):null}return new EachRenderItStep(nextNode.val.name,next.key)}return null}}class RenderEachNode extends RenderViewId{constructor(nodeId,val,viewId){super(nodeId,val,viewId);this.iterInfo=new IterInfo(val,null,null,null)}render(stack,rx){return rx.renderEach(stack,this.iterInfo,this,this.viewId)}toPathStep(ctx){if(this.val instanceof DynVal){if(!ctx.hasKey)return null;let p=resolveDynProducer(ctx.comp,this.val.name);return p?new DynEachStep(p.producerCompId,p.producerSteps,ctx.key):null}return super.toPathStep(ctx)}static parse(px,vp2,s,as,attrs){let node=px.addNodeIf(RenderEachNode,parseXOpVal("render-each",s,px,vp2.parseSequence),as);if(node!==null){let attrParser=getAttrParser(px);attrParser.eachAttr=attrParser.pushWrapper("each",s,node.val);let when=attrs.getNamedItem("when");if(when)attrParser._parseWhen(when.value);let lWith=attrs.getNamedItem("loop-with");if(lWith)attrParser._parseLoopWith(lWith.value);node.iterInfo.whenVal=attrParser.eachAttr.whenVal??null,node.iterInfo.loopWithVal=attrParser.eachAttr.loopWithVal??null}return node}}class RenderTextNode extends ANode{render(stack,_rx){return this.val.eval(stack)}}class RenderOnceNode extends BaseNode{constructor(node){super();this.node=node,this._render=(stack,rx)=>{let dom=node.render(stack,rx);return this._render=(_stack,_rx)=>dom,dom}}render(stack,rx){return this._render(stack,rx)}}class WrapperNode extends ANode{constructor(nodeId,val,node=null){super(nodeId,val);this.node=node}wrapNode(node){this.node=node}setDataAttr(key,val){this.node.setDataAttr(key,val)}optimize(){this.node=optimizeNode(this.node)}static register=!1}class ShowNode extends WrapperNode{render(stack,rx){return this.val.eval(stack)?this.node.render(stack,rx):null}}class HideNode extends WrapperNode{render(stack,rx){return this.val.eval(stack)?null:this.node.render(stack,rx)}}class PushViewNameNode extends WrapperNode{render(stack,rx){return this.node.render(stack.pushViewName(this.val.eval(stack)),rx)}}class SlotNode extends WrapperNode{optimize(){this.node.optimize()}}class ScopeNode extends WrapperNode{render(stack,rx){let binds=this.val.evalAsHandler(stack)?.call(stack.it)??{};return this.node.render(stack.enter(stack.it,binds,!1),rx)}toPathStep(_ctx){return new BindStep({})}wrapNode(node){this.node=node,this.node.setDataAttr("data-nid",this.nodeId)}static register=!0}class EachNode extends WrapperNode{constructor(nodeId,val){super(nodeId,val);this.iterInfo=new IterInfo(val,null,null,null)}render(stack,rx){return rx.renderEachWhen(stack,this.iterInfo,this.node,this.nodeId)}toPathStep(ctx){return ctx.hasKey?new EachBindStep(this.val,ctx.key):null}static register=!0}class IterInfo{constructor(val,whenVal,loopWithVal,enrichWithVal){this.val=val,this.whenVal=whenVal,this.loopWithVal=loopWithVal,this.enrichWithVal=enrichWithVal}eval(stack){let seq=this.val.eval(stack)??[],filter=this.whenVal?.evalAsHandler(stack)??filterAlwaysTrue,loopWith=this.loopWithVal?.evalAsHandler(stack)??nullLoopWith,enricher=this.enrichWithVal?.evalAsHandler(stack)??null;return{seq,filter,loopWith,enricher}}}var filterAlwaysTrue=(_v,_k,_seq)=>!0,nullLoopWith=(seq)=>({iterData:{seq}}),X_OP_CONSUMED={slot:new Set,text:new Set,render:new Set(["as"]),"render-it":new Set(["as"]),"render-each":new Set(["as","when","loop-with"]),show:new Set,hide:new Set},X_OP_WRAPPABLE=new Set(["text","render","render-it","render-each"]),X_ATTR_WRAPPERS={show:ShowNode,hide:HideNode},WRAPPER_NODES={slot:SlotNode,show:ShowNode,hide:HideNode,each:EachNode,scope:ScopeNode,"push-view":PushViewNameNode};class ParseContext{constructor(document2,Text,Comment,nodes,events2,macroNodes,frame,parent){this.nodes=nodes??[],this.events=events2??[],this.macroNodes=macroNodes??[],this.parent=parent??null,this.frame=frame??{},this.document=document2??globalThis.document,this.Text=Text??globalThis.Text,this.Comment=Comment??globalThis.Comment,this.cacheConstNodes=!0,this.currentTag=null}isInsideMacro(name){return this.frame.macroName===name||this.parent?.isInsideMacro(name)}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events:events2,macroNodes}=this;return new ParseContext(document2,Text,Comment,nodes,events2,macroNodes,{macroName,macroVars,macroSlots},this)}parseHTML(html){let t=this.document.createElement("template");return t.innerHTML=html,t.content.childNodes}addNodeIf(Class,val,extra){if(val!==null){let nodeId=this.nodes.length,node=new Class(nodeId,val,extra);return this.nodes.push(node),node}return null}registerEvents(){let id=this.events.length,events2=new NodeEvents(id);return this.events.push(events2),events2}newMacroNode(macroName,mAttrs,childs){let anySlot=[],slots={_:new FragmentNode(anySlot)};for(let child of childs)if(child instanceof SlotNode)slots[child.val.val]=child.node;else if(!(child instanceof TextNode)||!child.isWhiteSpace())anySlot.push(child);let node=new MacroNode(macroName,mAttrs,slots,this);return this.macroNodes.push(node),node}compile(scope){for(let i=0;i<this.macroNodes.length;i++)this.macroNodes[i].compile(scope)}*genEventNames(){for(let event of this.events)yield*event.genEventNames()}getEventForId(id){return this.events[id]??null}getNodeForId(id){return this.nodes[id]??null}onAttributes(_attrs,_wrapperAttrs,_textChild,_isMacroCall,_tag){}onParseIssue(kind,info){console.warn(`tutuca parse issue [${kind}]`,info)}}var _htmlBlockTags="ADDRESS,ARTICLE,ASIDE,BLOCKQUOTE,CAPTION,COL,COLGROUP,DETAILS,DIALOG,DIV,DD,DL,DT,FIELDSET,FIGCAPTION,FIGURE,FOOTER,FORM,H1,H2,H3,H4,H5,H6,HEADER,HGROUP,HR,LEGEND,LI,MAIN,MENU,NAV,OL,P,PRE,SECTION,SUMMARY,TABLE,TBODY,TD,TFOOT,TH,THEAD,TR,UL",HTML_BLOCK_TAGS=new Set(_htmlBlockTags.split(",")),isBlockDomNode=(n)=>{let node=n instanceof FragmentNode?n.childs[0]:n;return node instanceof DomNode&&HTML_BLOCK_TAGS.has(node.tagName)};function condenseChildsWhites(childs){if(childs.length===0)return childs;let changed=!1;if(childs[0].isWhiteSpace?.())childs[0].condenseWhiteSpace(),changed=!0;let last=childs.length-1;if(last>0&&childs[last].isWhiteSpace?.())childs[last].condenseWhiteSpace(),changed=!0;for(let i=1;i<last;i++){let cur=childs[i];if(cur.isWhiteSpace?.()&&cur.hasNewLine()){let bothBlock=isBlockDomNode(childs[i-1])&&isBlockDomNode(childs[i+1]);if(cur.condenseWhiteSpace(bothBlock?"":" "),bothBlock)changed=!0}}return changed?childs.filter((c)=>!(c instanceof TextNode&&c.val==="")):childs}class View{constructor(name,rawView="No View Defined",style="",anode=null,ctx=null){this.name=name,this.anode=anode,this.style=style,this.ctx=ctx,this.rawView=rawView}compile(ctx,scope,cid){if(this.ctx=ctx,this.anode=ANode.parse(this.rawView,ctx),this.anode.setDataAttr("data-cid",cid),this.anode.setDataAttr("data-vid",this.name),this.ctx.compile(scope),ctx.cacheConstNodes)this.anode=optimizeNode(this.anode)}render(stack,rx){return this.anode.render(stack,rx)}}class NodeEvents{constructor(id){this.id=id,this.handlers=[]}add(name,handlerCall,modifiers){this.handlers.push(new NodeEvent(name,handlerCall,modifiers))}*genEventNames(){for(let handler of this.handlers)yield handler.name}getHandlersFor(eventName){let r=null;for(let handler of this.handlers)if(handler.handlesEventName(eventName))r??=[],r.push(handler);return r}}class NodeEvent{constructor(name,handlerCall,modifiers){this.name=name,this.handlerCall=handlerCall,this.modifierWrapper=compileModifiers(name,modifiers),this.modifiers=modifiers}handlesEventName(name){return this.name===name}getHandlerAndArgs(stack,event){let r=this.handlerCall.getHandlerAndArgs(stack,event);return r[0]=this.modifierWrapper(r[0],event),r}}var isMac=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac"),fwdIfCtxPred=(pred)=>(w)=>(that,f,args,ctx)=>pred(ctx)?w(that,f,args,ctx):that,fwdIfKey=(keyName)=>fwdIfCtxPred((ctx)=>ctx.e.key===keyName),fwdCtrl=fwdIfCtxPred(({e})=>isMac&&e.metaKey||e.ctrlKey),fwdMeta=fwdIfCtxPred(({e})=>e.metaKey),fwdAlt=fwdIfCtxPred(({e})=>e.altKey),metaWraps={ctrl:fwdCtrl,cmd:fwdCtrl,meta:fwdMeta,alt:fwdAlt},MOD_WRAPPERS_BY_EVENT={keydown:{send:fwdIfKey("Enter"),cancel:fwdIfKey("Escape"),...metaWraps},click:{...metaWraps}},identityModifierWrapper=(f,_ctx)=>f;function compileModifiers(eventName,names){if(names.length===0)return identityModifierWrapper;let wrappers=MOD_WRAPPERS_BY_EVENT[eventName]??{},w=(that,f,args,_ctx)=>f.apply(that,args);for(let name of names){let wrapper=wrappers[name];if(wrapper!==void 0)w=wrapper(w)}return(f,ctx)=>function(...args){return w(this,f,args,ctx)}}class ParseCtxClassSetCollector extends ParseContext{constructor(...args){super(...args);this.classes=new Set}_addClasses(s){for(let v of s.split(/\s+/))this.classes.add(v)}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events:events2,macroNodes}=this,v=new ParseCtxClassSetCollector(document2,Text,Comment,nodes,events2,macroNodes,{macroName,macroVars,macroSlots},this);return v.classes=this.classes,v}onAttributes(attrs,_wrapperAttrs,_textChild,_isMacroCall,_tag){if(Array.isArray(attrs.items))for(let attr of attrs.items){if(attr.name!=="class")continue;let{val,thenVal,elseVal}=attr;if(thenVal!==void 0)this._maybeAddVal(thenVal),this._maybeAddVal(elseVal);else this._maybeAddVal(val)}else{let attr=attrs.items.class;if(attr)this._addClasses(attr)}}_maybeAddVal(value){if(!this._maybeAddStrTpl(value)&&typeof value?.val==="string")this._addClasses(value.val)}_maybeAddStrTpl(value){if(value?.vals!==void 0){for(let val of value.vals)if(val instanceof ConstVal&&val.val!=="")this._addClasses(val.val);return!0}return!1}}var CharCodes={Tab:9,NewLine:10,FormFeed:12,CarriageReturn:13,Space:32,ExclamationMark:33,Number:35,SingleQuote:39,DoubleQuote:34,Dash:45,Slash:47,Zero:48,Nine:57,Semi:59,Lt:60,Eq:61,Gt:62,Questionmark:63,UpperA:65,LowerA:97,UpperF:70,LowerF:102,UpperZ:90,LowerZ:122,LowerX:120,OpeningSquareBracket:91},State={Text:1,BeforeTagName:2,InTagName:3,InSelfClosingTag:4,BeforeClosingTagName:5,InClosingTagName:6,AfterClosingTagName:7,BeforeAttributeName:8,InAttributeName:9,AfterAttributeName:10,BeforeAttributeValue:11,InAttributeValueDq:12,InAttributeValueSq:13,InAttributeValueNq:14,BeforeDeclaration:15,InDeclaration:16,InProcessingInstruction:17,BeforeComment:18,CDATASequence:19,DeclarationSequence:20,InSpecialComment:21,InCommentLike:22,SpecialStartSequence:23,InSpecialTag:24,InPlainText:25};function isWhitespace(c){return c===CharCodes.Space||c===CharCodes.NewLine||c===CharCodes.Tab||c===CharCodes.FormFeed||c===CharCodes.CarriageReturn}function isEndOfTagSection(c){return c===CharCodes.Slash||c===CharCodes.Gt||isWhitespace(c)}function isASCIIAlpha(c){return c>=CharCodes.LowerA&&c<=CharCodes.LowerZ||c>=CharCodes.UpperA&&c<=CharCodes.UpperZ}var QuoteType={NoValue:0,Unquoted:1,Single:2,Double:3},Sequences={Empty:new Uint8Array(0),Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,33,62]),Doctype:new Uint8Array([100,111,99,116,121,112,101]),IframeEnd:new Uint8Array([60,47,105,102,114,97,109,101]),NoembedEnd:new Uint8Array([60,47,110,111,101,109,98,101,100]),NoframesEnd:new Uint8Array([60,47,110,111,102,114,97,109,101,115]),Plaintext:new Uint8Array([60,47,112,108,97,105,110,116,101,120,116]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])},specialStartSequences=new Map([[Sequences.IframeEnd[2],Sequences.IframeEnd],[Sequences.NoembedEnd[2],Sequences.NoembedEnd],[Sequences.Plaintext[2],Sequences.Plaintext],[Sequences.ScriptEnd[2],Sequences.ScriptEnd],[Sequences.TitleEnd[2],Sequences.TitleEnd],[Sequences.XmpEnd[2],Sequences.XmpEnd]]);class HtmlTokenizer{constructor({xmlMode=!1,recognizeSelfClosing=xmlMode}={},cbs){this.cbs=cbs,this.xmlMode=xmlMode,this.recognizeSelfClosing=recognizeSelfClosing,this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.isSpecial=!1,this.running=!0,this.offset=0,this.currentSequence=Sequences.Empty,this.sequenceIndex=0}reset(){this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.isSpecial=!1,this.currentSequence=Sequences.Empty,this.sequenceIndex=0,this.running=!0,this.offset=0}write(chunk){this.offset+=this.buffer.length,this.buffer=chunk,this.parse()}end(){if(this.running)this.finish()}pause(){this.running=!1}resume(){if(this.running=!0,this.index<this.buffer.length+this.offset)this.parse()}stateText(c){if(c===CharCodes.Lt||this.fastForwardTo(CharCodes.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=State.BeforeTagName,this.sectionStart=this.index}}enterTagBody(){if(this.currentSequence===Sequences.Plaintext)this.currentSequence=Sequences.Empty,this.state=State.InPlainText;else if(this.isSpecial)this.state=State.InSpecialTag,this.sequenceIndex=0;else this.state=State.Text}stateSpecialStartSequence(c){let lower=c|32;if(this.sequenceIndex<this.currentSequence.length){if(lower===this.currentSequence[this.sequenceIndex]){this.sequenceIndex++;return}if(this.sequenceIndex===3){if(this.currentSequence===Sequences.ScriptEnd&&lower===Sequences.StyleEnd[3]){this.currentSequence=Sequences.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===Sequences.TitleEnd&&lower===Sequences.TextareaEnd[3]){this.currentSequence=Sequences.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===Sequences.NoembedEnd&&lower===Sequences.NoframesEnd[4]){this.currentSequence=Sequences.NoframesEnd,this.sequenceIndex=5;return}}else if(isEndOfTagSection(c)){this.sequenceIndex=0,this.state=State.InTagName,this.stateInTagName(c);return}this.isSpecial=!1,this.currentSequence=Sequences.Empty,this.sequenceIndex=0,this.state=State.InTagName,this.stateInTagName(c)}stateCDATASequence(c){if(c===Sequences.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===Sequences.Cdata.length)this.state=State.InCommentLike,this.currentSequence=Sequences.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=State.InDeclaration,this.stateInDeclaration(c);else this.state=State.InSpecialComment,this.stateInSpecialComment(c)}fastForwardTo(c){while(++this.index<this.buffer.length+this.offset)if(this.buffer.charCodeAt(this.index-this.offset)===c)return!0;return this.index=this.buffer.length+this.offset-1,!1}emitComment(offset){this.cbs.oncomment(this.sectionStart,this.index,offset),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=State.Text}stateInCommentLike(c){if(!this.xmlMode&&this.currentSequence===Sequences.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&c===CharCodes.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===Sequences.CommentEnd&&this.sequenceIndex===2&&c===CharCodes.Gt)this.emitComment(2);else if(this.currentSequence===Sequences.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&c!==CharCodes.Gt)this.sequenceIndex=Number(c===CharCodes.Dash);else if(c===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===Sequences.CdataEnd)this.cbs.oncdata(this.sectionStart,this.index,2);else this.cbs.oncomment(this.sectionStart,this.index,3);this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=State.Text}}else if(this.sequenceIndex===0){if(this.fastForwardTo(this.currentSequence[0]))this.sequenceIndex=1}else if(c!==this.currentSequence[this.sequenceIndex-1])this.sequenceIndex=0}isTagStartChar(c){return this.xmlMode?!isEndOfTagSection(c):isASCIIAlpha(c)}stateInSpecialTag(c){if(this.sequenceIndex===this.currentSequence.length){if(isEndOfTagSection(c)){let endOfText=this.index-this.currentSequence.length;if(this.sectionStart<endOfText){let actualIndex=this.index;this.index=endOfText,this.cbs.ontext(this.sectionStart,endOfText),this.index=actualIndex}this.isSpecial=!1,this.sectionStart=endOfText+2,this.stateInClosingTagName(c);return}this.sequenceIndex=0}if((c|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.fastForwardTo(CharCodes.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(c===CharCodes.Lt)}stateBeforeTagName(c){if(c===CharCodes.ExclamationMark)this.state=State.BeforeDeclaration,this.sectionStart=this.index+1;else if(c===CharCodes.Questionmark)if(this.xmlMode)this.state=State.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=State.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(c)){this.sectionStart=this.index;let special=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:specialStartSequences.get(c|32);if(special===void 0)this.state=State.InTagName;else this.isSpecial=!0,this.currentSequence=special,this.sequenceIndex=3,this.state=State.SpecialStartSequence}else if(c===CharCodes.Slash)this.state=State.BeforeClosingTagName;else this.state=State.Text,this.stateText(c)}stateInTagName(c){if(isEndOfTagSection(c))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c)}stateBeforeClosingTagName(c){if(isWhitespace(c)){if(!this.xmlMode)this.state=State.InSpecialComment,this.sectionStart=this.index}else if(c===CharCodes.Gt){if(this.state=State.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(c)?State.InClosingTagName:State.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(c){if(isEndOfTagSection(c))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.AfterClosingTagName,this.stateAfterClosingTagName(c)}stateAfterClosingTagName(c){if(c===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))this.state=State.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(c){if(c===CharCodes.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(c===CharCodes.Slash)this.state=State.InSelfClosingTag;else if(!isWhitespace(c))this.state=State.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(c){if(c===CharCodes.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=State.Text,this.isSpecial=!1,this.currentSequence=Sequences.Empty}else if(!isWhitespace(c))this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c)}stateInAttributeName(c){if(c===CharCodes.Eq||isEndOfTagSection(c))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=State.AfterAttributeName,this.stateAfterAttributeName(c)}stateAfterAttributeName(c){if(c===CharCodes.Eq)this.state=State.BeforeAttributeValue;else if(c===CharCodes.Slash||c===CharCodes.Gt)this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c);else if(!isWhitespace(c))this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.state=State.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(c){if(c===CharCodes.DoubleQuote)this.state=State.InAttributeValueDq,this.sectionStart=this.index+1;else if(c===CharCodes.SingleQuote)this.state=State.InAttributeValueSq,this.sectionStart=this.index+1;else if(!isWhitespace(c))this.sectionStart=this.index,this.state=State.InAttributeValueNq,this.stateInAttributeValueNoQuotes(c)}handleInAttributeValue(c,quote){if(c===quote||this.fastForwardTo(quote))this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(quote===CharCodes.DoubleQuote?QuoteType.Double:QuoteType.Single,this.index+1),this.state=State.BeforeAttributeName}stateInAttributeValueDoubleQuotes(c){this.handleInAttributeValue(c,CharCodes.DoubleQuote)}stateInAttributeValueSingleQuotes(c){this.handleInAttributeValue(c,CharCodes.SingleQuote)}stateInAttributeValueNoQuotes(c){if(isWhitespace(c)||c===CharCodes.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(QuoteType.Unquoted,this.index),this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c)}stateBeforeDeclaration(c){if(c===CharCodes.OpeningSquareBracket)this.state=State.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=c===CharCodes.Dash?State.BeforeComment:State.InDeclaration;else if((c|32)===Sequences.Doctype[0])this.state=State.DeclarationSequence,this.currentSequence=Sequences.Doctype,this.sequenceIndex=1;else if(c===CharCodes.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1;else if(c===CharCodes.Dash)this.state=State.BeforeComment;else this.state=State.InSpecialComment}stateDeclarationSequence(c){if(this.sequenceIndex===this.currentSequence.length)this.state=State.InDeclaration,this.stateInDeclaration(c);else if((c|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(c===CharCodes.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1;else this.state=State.InSpecialComment}stateInDeclaration(c){if(c===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=State.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(c){if(c===CharCodes.Questionmark)this.sequenceIndex=1;else if(c===CharCodes.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=State.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(CharCodes.Questionmark))}stateBeforeComment(c){if(c===CharCodes.Dash)this.state=State.InCommentLike,this.currentSequence=Sequences.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=State.InDeclaration;else if(c===CharCodes.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1;else this.state=State.InSpecialComment}stateInSpecialComment(c){if(c===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1}cleanup(){if(this.running&&this.sectionStart!==this.index){if(this.state===State.Text||this.state===State.InPlainText||this.state===State.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===State.InAttributeValueDq||this.state===State.InAttributeValueSq||this.state===State.InAttributeValueNq)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index}}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){while(this.shouldContinue()){let c=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case State.Text:this.stateText(c);break;case State.InPlainText:this.index=this.buffer.length+this.offset-1;break;case State.SpecialStartSequence:this.stateSpecialStartSequence(c);break;case State.InSpecialTag:this.stateInSpecialTag(c);break;case State.CDATASequence:this.stateCDATASequence(c);break;case State.DeclarationSequence:this.stateDeclarationSequence(c);break;case State.InAttributeValueDq:this.stateInAttributeValueDoubleQuotes(c);break;case State.InAttributeName:this.stateInAttributeName(c);break;case State.InCommentLike:this.stateInCommentLike(c);break;case State.InSpecialComment:this.stateInSpecialComment(c);break;case State.BeforeAttributeName:this.stateBeforeAttributeName(c);break;case State.InTagName:this.stateInTagName(c);break;case State.InClosingTagName:this.stateInClosingTagName(c);break;case State.BeforeTagName:this.stateBeforeTagName(c);break;case State.AfterAttributeName:this.stateAfterAttributeName(c);break;case State.InAttributeValueSq:this.stateInAttributeValueSingleQuotes(c);break;case State.BeforeAttributeValue:this.stateBeforeAttributeValue(c);break;case State.BeforeClosingTagName:this.stateBeforeClosingTagName(c);break;case State.AfterClosingTagName:this.stateAfterClosingTagName(c);break;case State.InAttributeValueNq:this.stateInAttributeValueNoQuotes(c);break;case State.InSelfClosingTag:this.stateInSelfClosingTag(c);break;case State.InDeclaration:this.stateInDeclaration(c);break;case State.BeforeDeclaration:this.stateBeforeDeclaration(c);break;case State.BeforeComment:this.stateBeforeComment(c);break;case State.InProcessingInstruction:this.stateInProcessingInstruction(c);break}this.index++}this.cleanup()}finish(){this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(endIndex){if(this.state!==State.InCommentLike)return!1;if(this.currentSequence===Sequences.CdataEnd)if(this.xmlMode){if(this.sectionStart<endIndex)this.cbs.oncdata(this.sectionStart,endIndex,0)}else{let cdataStart=this.sectionStart-Sequences.Cdata.length-1;this.cbs.oncomment(cdataStart,endIndex,0)}else{let offset=this.xmlMode?0:Math.min(this.sequenceIndex,Sequences.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,endIndex,offset)}return!0}handleTrailingMarkupDeclaration(endIndex){if(this.xmlMode)switch(this.state){case State.InSpecialComment:case State.BeforeComment:case State.CDATASequence:case State.DeclarationSequence:case State.InDeclaration:return this.cbs.ontext(this.sectionStart,endIndex),!0;default:return!1}switch(this.state){case State.BeforeDeclaration:case State.InSpecialComment:case State.BeforeComment:case State.CDATASequence:return this.cbs.oncomment(this.sectionStart,endIndex,0),!0;case State.DeclarationSequence:if(this.sequenceIndex!==Sequences.Doctype.length)this.cbs.oncomment(this.sectionStart,endIndex,0);return!0;case State.InDeclaration:return!0;default:return!1}}handleTrailingData(){let endIndex=this.buffer.length+this.offset;if(this.handleTrailingCommentLikeData(endIndex)||this.handleTrailingMarkupDeclaration(endIndex))return;if(this.sectionStart>=endIndex)return;switch(this.state){case State.InTagName:case State.BeforeAttributeName:case State.BeforeAttributeValue:case State.AfterAttributeName:case State.InAttributeName:case State.InAttributeValueSq:case State.InAttributeValueDq:case State.InAttributeValueNq:case State.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,endIndex)}}}var VOID_ELEMENTS=new Set(["area","base","br","col","embed","hr","img","input","link","meta","source","track","wbr"]),RAW_TEXT_ELEMENTS=new Set(["script","style","iframe","noembed","noframes","noscript","xmp","plaintext"]);var SPECIAL_ELEMENTS=new Set(["address","applet","area","article","aside","base","basefont","bgsound","blockquote","br","button","caption","center","col","colgroup","dd","details","dir","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","iframe","img","input","keygen","li","link","listing","main","marquee","menu","meta","nav","noembed","noframes","noscript","object","ol","p","param","plaintext","pre","script","search","section","select","source","style","summary","table","tbody","td","template","textarea","tfoot","th","thead","title","tr","track","ul","wbr","xmp"]),FORMATTING_ELEMENTS=new Set(["a","b","big","code","em","font","i","nobr","s","small","strike","strong","tt","u"]),DEFAULT_SCOPE_BOUNDARIES=new Set(["applet","caption","html","table","td","th","marquee","object","select","template"]),MATHML_TEXT_INTEGRATION_POINT_NAMES=new Set(["mi","mo","mn","ms","mtext"]),SVG_HTML_INTEGRATION_POINT_NAMES=new Set(["foreignobject","desc","title"]),SCOPE_LIST_ITEM=new Set([...DEFAULT_SCOPE_BOUNDARIES,"ol","ul"]),SCOPE_BUTTON=new Set([...DEFAULT_SCOPE_BOUNDARIES,"button"]),SCOPE_DEFAULT=DEFAULT_SCOPE_BOUNDARIES,SCOPE_TABLE=new Set(["html","table","template"]);var STANDARD_SVG_CAMEL_ELEMENTS=new Set(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"]),STANDARD_SVG_CAMEL_ATTRS=new Set(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","xChannelSelector","yChannelSelector","zoomAndPan"]),MATHML_CAMEL_ATTRS=new Set(["definitionURL"]),SVG_ATTR_LOWERCASE_TO_CAMEL=new Map;for(let camel of STANDARD_SVG_CAMEL_ATTRS)SVG_ATTR_LOWERCASE_TO_CAMEL.set(camel.toLowerCase(),camel);var MATHML_ATTR_LOWERCASE_TO_CAMEL=new Map;for(let camel of MATHML_CAMEL_ATTRS)MATHML_ATTR_LOWERCASE_TO_CAMEL.set(camel.toLowerCase(),camel);var FOREIGN_BREAKOUT_TAGS=new Set(["b","big","blockquote","body","br","center","code","dd","div","dl","dt","em","embed","h1","h2","h3","h4","h5","h6","head","hr","i","img","li","listing","menu","meta","nobr","ol","p","pre","ruby","s","small","span","strong","strike","sub","sup","table","tt","u","ul","var"]);var SELECT_BREAKOUT_TAGS=new Set(["input","keygen","textarea","select"]),MODES=Object.freeze({inBody:"inBody",inTable:"inTable",inCaption:"inCaption",inColumnGroup:"inColumnGroup",inTableBody:"inTableBody",inRow:"inRow",inCell:"inCell",inSelect:"inSelect",inSelectInTable:"inSelectInTable",inTemplate:"inTemplate"}),NS=Object.freeze({html:"html",svg:"svg",math:"math"}),FRAGMENT_CONTEXT_MODES=Object.freeze({template:{mode:MODES.inTemplate,ns:NS.html},body:{mode:MODES.inBody,ns:NS.html},div:{mode:MODES.inBody,ns:NS.html},table:{mode:MODES.inTable,ns:NS.html},tbody:{mode:MODES.inTableBody,ns:NS.html},thead:{mode:MODES.inTableBody,ns:NS.html},tfoot:{mode:MODES.inTableBody,ns:NS.html},caption:{mode:MODES.inCaption,ns:NS.html},colgroup:{mode:MODES.inColumnGroup,ns:NS.html},tr:{mode:MODES.inRow,ns:NS.html},td:{mode:MODES.inCell,ns:NS.html},th:{mode:MODES.inCell,ns:NS.html},select:{mode:MODES.inSelect,ns:NS.html},svg:{mode:MODES.inBody,ns:NS.svg},math:{mode:MODES.inBody,ns:NS.math}});var HTML_TAG_NAME_HAS_UPPERCASE="HTML_TAG_NAME_HAS_UPPERCASE",HTML_SVG_TAG_WILL_LOWERCASE="HTML_SVG_TAG_WILL_LOWERCASE",HTML_SVG_ATTR_WILL_LOWERCASE="HTML_SVG_ATTR_WILL_LOWERCASE",HTML_MATHML_ATTR_WILL_LOWERCASE="HTML_MATHML_ATTR_WILL_LOWERCASE",HTML_TAG_NOT_ALLOWED_IN_PARENT="HTML_TAG_NOT_ALLOWED_IN_PARENT",HTML_TEXT_NOT_ALLOWED_IN_PARENT="HTML_TEXT_NOT_ALLOWED_IN_PARENT",HTML_VOID_ELEMENT_HAS_CLOSE_TAG="HTML_VOID_ELEMENT_HAS_CLOSE_TAG",HTML_DUPLICATE_FORM="HTML_DUPLICATE_FORM",HTML_NESTED_INTERACTIVE="HTML_NESTED_INTERACTIVE",HTML_MISNESTED_FORMATTING="HTML_MISNESTED_FORMATTING",HTML_UNEXPECTED_END_TAG="HTML_UNEXPECTED_END_TAG",HTML_DUPLICATE_ATTRIBUTE="HTML_DUPLICATE_ATTRIBUTE",HTML_ATTRIBUTES_ON_END_TAG="HTML_ATTRIBUTES_ON_END_TAG",HTML_SELF_CLOSING_END_TAG="HTML_SELF_CLOSING_END_TAG",HTML_MISSING_ATTRIBUTE_VALUE="HTML_MISSING_ATTRIBUTE_VALUE",HTML_CDATA_IN_HTML_NAMESPACE="HTML_CDATA_IN_HTML_NAMESPACE",HTML_BOGUS_COMMENT="HTML_BOGUS_COMMENT",HTML_UNCLOSED_BEFORE_END="HTML_UNCLOSED_BEFORE_END",LEVEL_ERROR="error",LEVEL_WARN="warn",TABLE_SCOPE_TAGS=new Set(["caption","colgroup","thead","tbody","tfoot","tr","td","th","table"]),TABLE_BODY_CELL_TAGS=new Set(["td","th"]),IMPLIED_END_TAGS=new Set(["dd","dt","li","optgroup","option","p","rb","rp","rt","rtc"]);function lintHtml(html,onFinding,opts={}){let TokenizerClass=opts.TokenizerClass??HtmlTokenizer,ctx=new LinterCtx(html,onFinding,opts),tokenizer=new TokenizerClass({xmlMode:!1,decodeEntities:!1,recognizeSelfClosing:!0},ctx);return ctx.tokenizer=tokenizer,tokenizer.write(html),tokenizer.end(),ctx.findingCount}class LinterCtx{constructor(html,onFinding,opts){this.html=html,this.onFinding=onFinding,this.findingCount=0,this.lineStarts=computeLineStarts(html);let ctxName=opts.fragmentContext??"template",ctxInfo=FRAGMENT_CONTEXT_MODES[ctxName]??FRAGMENT_CONTEXT_MODES.template;if(this.openElements=[],ctxName==="tr")this.openElements.push({name:"table",ns:NS.html,start:-1}),this.openElements.push({name:"tbody",ns:NS.html,start:-1});else if(ctxName==="tbody"||ctxName==="thead"||ctxName==="tfoot")this.openElements.push({name:"table",ns:NS.html,start:-1});else if(ctxName==="td"||ctxName==="th")this.openElements.push({name:"table",ns:NS.html,start:-1}),this.openElements.push({name:"tbody",ns:NS.html,start:-1}),this.openElements.push({name:"tr",ns:NS.html,start:-1});else if(ctxName==="caption")this.openElements.push({name:"table",ns:NS.html,start:-1});else if(ctxName==="colgroup")this.openElements.push({name:"table",ns:NS.html,start:-1});else if(ctxName==="svg")this.openElements.push({name:"svg",ns:NS.svg,start:-1});else if(ctxName==="math")this.openElements.push({name:"math",ns:NS.math,start:-1});else if(ctxName==="select")this.openElements.push({name:"select",ns:NS.html,start:-1});this.insertionMode=ctxInfo.mode,this.templateInsertionModes=ctxName==="template"?[MODES.inTemplate]:[],this.activeFormatting=[],this.framesetOk=!0,this.svgCamelElements=opts.svgCamelElements??STANDARD_SVG_CAMEL_ELEMENTS,this.transparentTagPrefixes=(opts.transparentTagPrefixes??[]).map((p)=>p.toLowerCase()),this.currentTagName="",this.currentTagRawName="",this.currentTagStart=0,this.currentAttrs=[],this.currentAttr=null,this.tokenizer=null}onopentagname(start,end){let raw=this.html.slice(start,end);this.currentTagRawName=raw,this.currentTagName=raw.toLowerCase(),this.currentTagStart=start,this.currentAttrs=[],this.currentAttr=null}onattribname(start,end){let rawName=this.html.slice(start,end);this.currentAttr={name:rawName.toLowerCase(),rawName,nameStart:start,value:null,valueStart:-1,valueEnd:-1,quote:QuoteType.NoValue}}onattribdata(start,end){if(!this.currentAttr)return;this.currentAttr.valueStart=start,this.currentAttr.valueEnd=end,this.currentAttr.value=this.html.slice(start,end)}onattribend(quote,_end){let a=this.currentAttr;if(!a)return;a.quote=quote;let dup=this.currentAttrs.find((x)=>x.name===a.name);if(dup)this.report(HTML_DUPLICATE_ATTRIBUTE,LEVEL_WARN,a.nameStart,{name:a.name,firstAt:dup.nameStart},{kind:"remove",what:`the duplicate '${a.name}' attribute`});else this.currentAttrs.push(a);if(a.quote===QuoteType.Unquoted&&a.value==="")this.report(HTML_MISSING_ATTRIBUTE_VALUE,LEVEL_WARN,a.nameStart,{name:a.name});this.currentAttr=null}onattribentity(_cp){}ontextentity(_cp,_end){}getAttr(name){let a=this.currentAttrs.find((x)=>x.name===name);return a?a.value:null}hasAttr(name){return this.currentAttrs.some((x)=>x.name===name)}onopentagend(endIndex){this.handleStartTag(!1,endIndex)}onselfclosingtag(endIndex){this.handleStartTag(!0,endIndex)}onclosetag(start,end){let name=this.html.slice(start,end).toLowerCase(),i=end,lastNonWs=-1;while(i<this.html.length){let c=this.html.charCodeAt(i);if(c===62)break;if(c!==32&&c!==9&&c!==10&&c!==13&&c!==12)lastNonWs=i;i++}if(lastNonWs>=0)if(this.html.charCodeAt(lastNonWs)===47&&lastNonWs===i-1){let firstNonWs=-1;for(let j=end;j<lastNonWs;j++){let c2=this.html.charCodeAt(j);if(c2!==32&&c2!==9&&c2!==10&&c2!==13&&c2!==12){firstNonWs=j;break}}if(firstNonWs<0)this.report(HTML_SELF_CLOSING_END_TAG,LEVEL_WARN,start,{tag:name},{kind:"rewrite",from:`</${name}/>`,to:`</${name}>`});else this.report(HTML_ATTRIBUTES_ON_END_TAG,LEVEL_WARN,start,{tag:name},{kind:"remove",what:`attributes from </${name}>`})}else this.report(HTML_ATTRIBUTES_ON_END_TAG,LEVEL_WARN,start,{tag:name},{kind:"remove",what:`attributes from </${name}>`});this.handleEndTag(name,start)}ontext(start,end){if(start>=end)return;let top=this.currentNode();if(top&&top.ns!==NS.html&&!this.isIntegrationPoint(top))return;this.handleText(start,end)}oncomment(start,_end,endOffset){if(endOffset===0)this.report(HTML_BOGUS_COMMENT,LEVEL_WARN,start,{mode:this.insertionMode})}oncdata(start,_end,_endOffset){if(this.currentNamespace()===NS.html)this.report(HTML_CDATA_IN_HTML_NAMESPACE,LEVEL_WARN,start,{mode:this.insertionMode})}ondeclaration(_start,_end){}onprocessinginstruction(_start,_end){}isInForeignContext(){return this.currentNamespace()!==NS.html}onend(){}report(id,level,offset,info,suggestion=null){this.findingCount++;let{line,column}=offsetToLineCol(this.lineStarts,offset);this.onFinding({id,level,info,location:{start:offset,end:offset+(info.tag?.length??0),line,column},suggestion})}currentNode(){return this.openElements[this.openElements.length-1]??null}currentNamespace(){let top=this.currentNode();return top?top.ns:NS.html}push(name,ns,start){this.openElements.push({name,ns,start})}pop(){return this.openElements.pop()}hasInScope(target,scopeSet){for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.name===target&&f.ns===NS.html)return!0;if(f.ns===NS.html){if(scopeSet.has(f.name))return!1}else if(this.isScopeBoundary(f))return!1}return!1}isScopeBoundary(frame){if(frame.ns===NS.math)return MATHML_TEXT_INTEGRATION_POINT_NAMES.has(frame.name)||frame.name==="annotation-xml";if(frame.ns===NS.svg)return SVG_HTML_INTEGRATION_POINT_NAMES.has(frame.name);return!1}isIntegrationPoint(frame){if(frame.ns===NS.math){if(MATHML_TEXT_INTEGRATION_POINT_NAMES.has(frame.name))return!0;if(frame.name==="annotation-xml"&&frame.htmlIntegration)return!0;return!1}if(frame.ns===NS.svg)return SVG_HTML_INTEGRATION_POINT_NAMES.has(frame.name);return!1}hasInDefaultScope(target){return this.hasInScope(target,SCOPE_DEFAULT)}hasInButtonScope(target){return this.hasInScope(target,SCOPE_BUTTON)}hasInListItemScope(target){return this.hasInScope(target,SCOPE_LIST_ITEM)}hasInTableScope(target){return this.hasInScope(target,SCOPE_TABLE)}hasInSelectScope(target){for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns!==NS.html)return!1;if(f.name===target)return!0;if(f.name!=="optgroup"&&f.name!=="option")return!1}return!1}popUntilName(name){while(this.openElements.length){let f=this.openElements.pop();if(f.name===name)return f}return null}generateImpliedEndTags(except=null){let implied=new Set(["dd","dt","li","optgroup","option","p","rb","rp","rt","rtc"]);while(this.openElements.length){let top=this.currentNode();if(top.ns!==NS.html)break;if(!implied.has(top.name)||top.name===except)break;this.openElements.pop()}}isTransparentTag(name){for(let prefix of this.transparentTagPrefixes)if(name===prefix||name.startsWith(`${prefix}:`))return!0;return!1}handleStartTag(selfClosing,endIndex){let name=this.currentTagName,raw=this.currentTagRawName,start=this.currentTagStart,ns=this.currentNamespace();if(ns===NS.html){if(raw!==name)this.report(HTML_TAG_NAME_HAS_UPPERCASE,LEVEL_ERROR,start,{raw,lowercased:name},{kind:"rewrite",from:`<${raw}>`,to:`<${name}>`})}else if(ns===NS.svg){if(raw!==raw.toLowerCase()&&!this.svgCamelElements.has(raw))this.report(HTML_SVG_TAG_WILL_LOWERCASE,LEVEL_ERROR,start,{raw,lowercased:name},{kind:"rewrite",from:`<${raw}>`,to:`<${name}>`})}let targetNs=ns!==NS.html?ns:name==="svg"?NS.svg:name==="math"?NS.math:NS.html;if(targetNs===NS.svg)for(let a of this.currentAttrs){let canonical=SVG_ATTR_LOWERCASE_TO_CAMEL.get(a.name);if(canonical&&a.rawName!==canonical)this.report(HTML_SVG_ATTR_WILL_LOWERCASE,LEVEL_ERROR,a.nameStart,{raw:a.rawName,canonical},{kind:"rewrite",from:a.rawName,to:canonical})}else if(targetNs===NS.math)for(let a of this.currentAttrs){let canonical=MATHML_ATTR_LOWERCASE_TO_CAMEL.get(a.name);if(canonical&&a.rawName!==canonical)this.report(HTML_MATHML_ATTR_WILL_LOWERCASE,LEVEL_ERROR,a.nameStart,{raw:a.rawName,canonical},{kind:"rewrite",from:a.rawName,to:canonical})}if(this.isTransparentTag(name))return;let top=this.currentNode(),inForeign=ns!==NS.html&&!(top&&this.isIntegrationPoint(top));if(inForeign&&!this.shouldBreakoutFromForeign(name)){this.startTagInForeign(name,raw,selfClosing,start);return}if(inForeign&&this.shouldBreakoutFromForeign(name)){this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_WARN,start,{tag:raw,parent:this.currentNode()?.name??"(root)",mode:this.insertionMode,action:"foreign-breakout"});while(this.openElements.length&&this.currentNode()?.ns!==NS.html)this.openElements.pop()}this.dispatchStartTag(name,raw,selfClosing,start,endIndex)}shouldBreakoutFromForeign(name){if(FOREIGN_BREAKOUT_TAGS.has(name))return!0;if(name==="font")return this.hasAttr("color")||this.hasAttr("face")||this.hasAttr("size");return!1}startTagInForeign(name,raw,selfClosing,start){let ns=name==="svg"?NS.svg:name==="math"?NS.math:this.currentNamespace(),top=this.currentNode();if(top&&this.isIntegrationPoint(top)&&name!=="mglyph"&&name!=="malignmark"){this.dispatchStartTag(name,raw,selfClosing,start,start+raw.length);return}if(selfClosing)return;let frame={name,ns,start};if(ns===NS.math&&name==="annotation-xml"){let enc=(this.getAttr("encoding")??"").toLowerCase();if(enc==="text/html"||enc==="application/xhtml+xml")frame.htmlIntegration=!0}this.openElements.push(frame)}dispatchStartTag(name,raw,selfClosing,start,endIndex){switch(this.insertionMode){case MODES.inTemplate:return this.startInTemplate(name,raw,selfClosing,start,endIndex);case MODES.inBody:return this.startInBody(name,raw,selfClosing,start,endIndex);case MODES.inTable:return this.startInTable(name,raw,selfClosing,start,endIndex);case MODES.inCaption:return this.startInCaption(name,raw,selfClosing,start,endIndex);case MODES.inColumnGroup:return this.startInColumnGroup(name,raw,selfClosing,start,endIndex);case MODES.inTableBody:return this.startInTableBody(name,raw,selfClosing,start,endIndex);case MODES.inRow:return this.startInRow(name,raw,selfClosing,start,endIndex);case MODES.inCell:return this.startInCell(name,raw,selfClosing,start,endIndex);case MODES.inSelect:return this.startInSelect(name,raw,selfClosing,start,endIndex);case MODES.inSelectInTable:return this.startInSelectInTable(name,raw,selfClosing,start,endIndex)}}startInBody(name,raw,selfClosing,start,_endIndex){if(name==="html"||name==="head"||name==="body"||name==="frame"||name==="frameset"){this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_WARN,start,{tag:raw,mode:this.insertionMode,action:"ignored"});return}if(name==="address"||name==="article"||name==="aside"||name==="blockquote"||name==="center"||name==="details"||name==="dialog"||name==="dir"||name==="div"||name==="dl"||name==="fieldset"||name==="figcaption"||name==="figure"||name==="footer"||name==="header"||name==="hgroup"||name==="main"||name==="menu"||name==="nav"||name==="ol"||name==="p"||name==="search"||name==="section"||name==="summary"||name==="ul"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="h1"||name==="h2"||name==="h3"||name==="h4"||name==="h5"||name==="h6"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);let top=this.currentNode();if(top&&/^h[1-6]$/.test(top.name))this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:top.name,mode:this.insertionMode,action:"auto-close-implicit"}),this.openElements.pop();this.push(raw,NS.html,start);return}if(name==="pre"||name==="listing"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start),this.framesetOk=!1;return}if(name==="form"){if(this.openElementsHas("form")&&!this.openElementsHas("template")){this.report(HTML_DUPLICATE_FORM,LEVEL_ERROR,start,{tag:raw,mode:this.insertionMode},{kind:"remove",what:"the inner <form>"});return}if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="li"){this.framesetOk=!1;for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns!==NS.html)break;if(f.name==="li"){this.generateImpliedEndTags("li");while(this.openElements.length)if(this.openElements.pop().name==="li")break;break}if(SPECIAL_ELEMENTS.has(f.name)&&f.name!=="address"&&f.name!=="div"&&f.name!=="p")break}if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="dd"||name==="dt"){this.framesetOk=!1;for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns!==NS.html)break;if(f.name==="dd"||f.name==="dt"){this.generateImpliedEndTags(f.name);while(this.openElements.length)if(this.openElements.pop().name===f.name)break;break}if(SPECIAL_ELEMENTS.has(f.name)&&f.name!=="address"&&f.name!=="div"&&f.name!=="p")break}if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="plaintext"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start);return}if(name==="button"){if(this.hasInDefaultScope("button"))this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"button",mode:this.insertionMode,action:"auto-close-implicit"}),this.generateImpliedEndTags(),this.popUntilName("button");this.push(raw,NS.html,start),this.framesetOk=!1;return}if(name==="a"){if(this.activeFormattingHas("a"))this.report(HTML_NESTED_INTERACTIVE,LEVEL_WARN,start,{tag:raw,mode:this.insertionMode}),this.runAdoptionAgency("a");this.push(raw,NS.html,start),this.activeFormatting.push(this.currentNode());return}if(FORMATTING_ELEMENTS.has(name)){this.push(raw,NS.html,start),this.activeFormatting.push(this.currentNode());return}if(name==="nobr"){if(this.activeFormattingHas("nobr"))this.report(HTML_NESTED_INTERACTIVE,LEVEL_WARN,start,{tag:raw,mode:this.insertionMode}),this.runAdoptionAgency("nobr");this.push(raw,NS.html,start),this.activeFormatting.push(this.currentNode());return}if(name==="table"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start),this.framesetOk=!1,this.insertionMode=MODES.inTable;return}if(name==="area"||name==="br"||name==="embed"||name==="img"||name==="keygen"||name==="wbr"||name==="input"||name==="param"||name==="source"||name==="track"||name==="hr"||name==="meta"||name==="link"||name==="col"||name==="base"){this.framesetOk=!1;return}if(name==="select"){if(this.hasInButtonScope("p"))this.implicitlyClose("p",start,raw);this.push(raw,NS.html,start),this.framesetOk=!1,this.insertionMode=MODES.inSelect;return}if(name==="option"||name==="optgroup"){if(this.currentNode()?.name==="option")this.openElements.pop();this.push(raw,NS.html,start);return}if(name==="textarea"||name==="title"||RAW_TEXT_ELEMENTS.has(name)){this.push(raw,NS.html,start);return}if(name==="math"||name==="svg"){this.push(raw,name==="svg"?NS.svg:NS.math,start),this.framesetOk=!1;return}if(name==="caption"||name==="col"||name==="colgroup"||name==="frame"||name==="tbody"||name==="td"||name==="tfoot"||name==="th"||name==="thead"||name==="tr"){this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:this.currentNode()?.name??"(root)",mode:this.insertionMode,action:"ignored"});return}if(selfClosing)return;this.push(raw,NS.html,start)}openElementsHas(name){for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns===NS.html&&f.name===name)return!0}return!1}activeFormattingHas(name){for(let i=this.activeFormatting.length-1;i>=0;i--){let e=this.activeFormatting[i];if(e===null)return!1;if(e.name===name)return!0}return!1}runAdoptionAgency(name){for(let i=this.activeFormatting.length-1;i>=0;i--){let e=this.activeFormatting[i];if(e===null)break;if(e.name===name){let idx=this.openElements.indexOf(e);if(idx>=0)this.openElements.splice(idx,1);return}}}implicitlyClose(name,_start,_newTagRaw){while(this.openElements.length)if(this.openElements.pop().name===name)break}startInTemplate(name,raw,selfClosing,start,endIndex){let next;if(name==="caption"||name==="colgroup"||name==="tbody"||name==="tfoot"||name==="thead")next=MODES.inTable;else if(name==="col")next=MODES.inColumnGroup;else if(name==="tr")next=MODES.inTableBody;else if(name==="td"||name==="th")next=MODES.inRow;else return this.popTemplateMode(),this.pushTemplateMode(MODES.inBody),this.insertionMode=MODES.inBody,this.startInBody(name,raw,selfClosing,start,endIndex);return this.popTemplateMode(),this.pushTemplateMode(next),this.insertionMode=next,this.dispatchStartTag(name,raw,selfClosing,start,endIndex)}popTemplateMode(){if(this.templateInsertionModes.length)this.templateInsertionModes.pop()}pushTemplateMode(mode){this.templateInsertionModes.push(mode)}startInTable(name,raw,selfClosing,start,endIndex){if(name==="caption"){this.clearStackBackToTable(),this.activeFormatting.push(null),this.push(raw,NS.html,start),this.insertionMode=MODES.inCaption;return}if(name==="colgroup"){this.clearStackBackToTable(),this.push(raw,NS.html,start),this.insertionMode=MODES.inColumnGroup;return}if(name==="col")return this.clearStackBackToTable(),this.push("colgroup",NS.html,start),this.insertionMode=MODES.inColumnGroup,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);if(name==="tbody"||name==="thead"||name==="tfoot"){this.clearStackBackToTable(),this.push(raw,NS.html,start),this.insertionMode=MODES.inTableBody;return}if(name==="td"||name==="th"||name==="tr")return this.clearStackBackToTable(),this.push("tbody",NS.html,start),this.insertionMode=MODES.inTableBody,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);if(name==="table"){if(this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"table",mode:this.insertionMode,action:"auto-close-implicit"}),this.hasInTableScope("table"))return this.popUntilName("table"),this.resetInsertionModeAppropriately(),this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}if(name==="style"||name==="script"||name==="template")return this.startInBody(name,raw,selfClosing,start,endIndex);if(name==="input"){if((this.getAttr("type")??"").toLowerCase()==="hidden")return;this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_WARN,start,{tag:raw,parent:"table",mode:this.insertionMode,action:"foster-parent"});return}if(name==="form"){this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"table",mode:this.insertionMode,action:"ignored"});return}return this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:this.currentNode()?.name??"table",mode:this.insertionMode,action:"foster-parent"}),this.startInBody(name,raw,selfClosing,start,endIndex)}clearStackBackToTable(){while(this.openElements.length){let top=this.currentNode();if(!top)break;if(top.name==="table"||top.name==="template")break;this.openElements.pop()}}startInCaption(name,raw,selfClosing,start,endIndex){if(name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="td"||name==="tfoot"||name==="th"||name==="thead"||name==="tr"){if(this.hasInTableScope("caption"))return this.generateImpliedEndTags(),this.popUntilName("caption"),this.clearActiveFormattingToMarker(),this.insertionMode=MODES.inTable,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}return this.startInBody(name,raw,selfClosing,start,endIndex)}clearActiveFormattingToMarker(){while(this.activeFormatting.length)if(this.activeFormatting.pop()===null)return}startInColumnGroup(name,raw,selfClosing,start,endIndex){if(name==="col")return;if(name==="template")return this.startInBody(name,raw,selfClosing,start,endIndex);if(this.currentNode()?.name==="colgroup")return this.openElements.pop(),this.insertionMode=MODES.inTable,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"colgroup",mode:this.insertionMode,action:"ignored"})}startInTableBody(name,raw,selfClosing,start,endIndex){if(name==="tr"){this.clearStackBackToTableBody(),this.push(raw,NS.html,start),this.insertionMode=MODES.inRow;return}if(TABLE_BODY_CELL_TAGS.has(name))return this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_WARN,start,{tag:raw,parent:this.currentNode()?.name??"tbody",mode:this.insertionMode,action:"auto-close-implicit"}),this.clearStackBackToTableBody(),this.push("tr",NS.html,start),this.insertionMode=MODES.inRow,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);if(name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="tfoot"||name==="thead"){if(this.hasInTableScope("tbody")||this.hasInTableScope("thead")||this.hasInTableScope("tfoot"))return this.clearStackBackToTableBody(),this.openElements.pop(),this.insertionMode=MODES.inTable,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}return this.startInTable(name,raw,selfClosing,start,endIndex)}clearStackBackToTableBody(){while(this.openElements.length){let top=this.currentNode();if(!top)break;if(top.name==="tbody"||top.name==="thead"||top.name==="tfoot"||top.name==="template"||top.name==="table")break;this.openElements.pop()}}startInRow(name,raw,selfClosing,start,endIndex){if(TABLE_BODY_CELL_TAGS.has(name)){this.clearStackBackToTableRow(),this.push(raw,NS.html,start),this.insertionMode=MODES.inCell,this.activeFormatting.push(null);return}if(name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="tfoot"||name==="thead"||name==="tr"){if(this.hasInTableScope("tr"))return this.clearStackBackToTableRow(),this.openElements.pop(),this.insertionMode=MODES.inTableBody,this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}return this.startInTable(name,raw,selfClosing,start,endIndex)}clearStackBackToTableRow(){while(this.openElements.length){let top=this.currentNode();if(!top)break;if(top.name==="tr"||top.name==="template"||top.name==="table")break;this.openElements.pop()}}startInCell(name,raw,selfClosing,start,endIndex){if(name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="td"||name==="tfoot"||name==="th"||name==="thead"||name==="tr"){if(this.hasInTableScope("td")||this.hasInTableScope("th"))return this.closeCell(),this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return}return this.startInBody(name,raw,selfClosing,start,endIndex)}closeCell(){this.generateImpliedEndTags();while(this.openElements.length){let popped=this.openElements.pop();if(popped.name==="td"||popped.name==="th")break}this.clearActiveFormattingToMarker(),this.insertionMode=MODES.inRow}startInSelect(name,raw,_selfClosing,start,_endIndex){if(name==="option"){if(this.currentNode()?.name==="option")this.openElements.pop();this.push(raw,NS.html,start);return}if(name==="optgroup"){if(this.currentNode()?.name==="option")this.openElements.pop();if(this.currentNode()?.name==="optgroup")this.openElements.pop();this.push(raw,NS.html,start);return}if(name==="hr")return;if(SELECT_BREAKOUT_TAGS.has(name)){if(this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"select",mode:this.insertionMode,action:"auto-close-implicit"}),this.hasInSelectScope("select"))this.popUntilName("select"),this.resetInsertionModeAppropriately();if(name==="select")return;return this.dispatchStartTag(name,raw,!1,start,_endIndex)}if(name==="script"||name==="template")return this.startInBody(name,raw,!1,start,_endIndex);this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"select",mode:this.insertionMode,action:"ignored"})}startInSelectInTable(name,raw,selfClosing,start,endIndex){if(name==="caption"||name==="table"||name==="tbody"||name==="tfoot"||name==="thead"||name==="tr"||name==="td"||name==="th")return this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{tag:raw,parent:"select",mode:this.insertionMode,action:"auto-close-implicit"}),this.popUntilName("select"),this.resetInsertionModeAppropriately(),this.dispatchStartTag(name,raw,selfClosing,start,endIndex);return this.startInSelect(name,raw,selfClosing,start,endIndex)}resetInsertionModeAppropriately(){for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns!==NS.html)continue;let last=i===0;switch(f.name){case"select":this.insertionMode=MODES.inSelect;return;case"td":case"th":if(!last){this.insertionMode=MODES.inCell;return}break;case"tr":this.insertionMode=MODES.inRow;return;case"tbody":case"thead":case"tfoot":this.insertionMode=MODES.inTableBody;return;case"caption":this.insertionMode=MODES.inCaption;return;case"colgroup":this.insertionMode=MODES.inColumnGroup;return;case"table":this.insertionMode=MODES.inTable;return;case"template":this.insertionMode=this.templateInsertionModes[this.templateInsertionModes.length-1]??MODES.inBody;return;default:break}}this.insertionMode=MODES.inBody}handleEndTag(name,start){if(this.isTransparentTag(name))return;if(this.currentNamespace()!==NS.html){let stackIdx=this.openElements.length-1,first=!0;while(stackIdx>0){let f=this.openElements[stackIdx];if(!first&&f.ns===NS.html)break;if(f.ns!==NS.html&&f.name.toLowerCase()===name){this.openElements.length=stackIdx;return}if(first)this.report(HTML_UNEXPECTED_END_TAG,LEVEL_WARN,start,{tag:name,mode:this.insertionMode}),first=!1;stackIdx--}}if(VOID_ELEMENTS.has(name)){this.report(HTML_VOID_ELEMENT_HAS_CLOSE_TAG,LEVEL_WARN,start,{tag:name,mode:this.insertionMode},{kind:"remove",what:`the </${name}>`});return}if(FORMATTING_ELEMENTS.has(name)){let top=this.currentNode();if(top&&top.ns===NS.html&&top.name===name){this.openElements.pop(),this.removeFromActiveFormattingByRef(top);return}if(this.activeFormattingHas(name)||this.openElementsHas(name)){this.report(HTML_MISNESTED_FORMATTING,LEVEL_WARN,start,{tag:name,mode:this.insertionMode}),this.runAdoptionAgency(name);return}this.report(HTML_UNEXPECTED_END_TAG,LEVEL_WARN,start,{tag:name,mode:this.insertionMode});return}let endIsTableStructural=TABLE_SCOPE_TAGS.has(name);for(let i=this.openElements.length-1;i>=0;i--){let f=this.openElements[i];if(f.ns===NS.html&&f.name===name){for(let j=this.openElements.length-1;j>i;j--){let popped=this.openElements[j];if(popped.ns===NS.html&&popped.name!==name&&!IMPLIED_END_TAGS.has(popped.name)&&!(endIsTableStructural&&TABLE_SCOPE_TAGS.has(popped.name))){this.report(HTML_UNCLOSED_BEFORE_END,LEVEL_WARN,start,{tag:name,unclosed:popped.name,mode:this.insertionMode});break}}if(this.openElements.length=i,TABLE_SCOPE_TAGS.has(name)||name==="select"||name==="template")this.resetInsertionModeAppropriately();return}if(f.ns===NS.html&&SPECIAL_ELEMENTS.has(f.name)&&!IMPLIED_END_TAGS.has(f.name)&&!(endIsTableStructural&&TABLE_SCOPE_TAGS.has(f.name))){this.report(HTML_UNEXPECTED_END_TAG,LEVEL_WARN,start,{tag:name,mode:this.insertionMode});return}}}removeFromActiveFormattingByRef(ref){let idx=this.activeFormatting.indexOf(ref);if(idx>=0)this.activeFormatting.splice(idx,1)}handleText(start,end){if(this.insertionMode===MODES.inTable||this.insertionMode===MODES.inTableBody||this.insertionMode===MODES.inRow){let slice=this.html.slice(start,end);if(/\S/.test(slice))this.report(HTML_TEXT_NOT_ALLOWED_IN_PARENT,LEVEL_ERROR,start,{mode:this.insertionMode,snippet:slice.length>40?`${slice.slice(0,40)}…`:slice});return}if(this.insertionMode===MODES.inColumnGroup){let slice=this.html.slice(start,end);if(/\S/.test(slice)){if(this.currentNode()?.name==="colgroup")return this.openElements.pop(),this.insertionMode=MODES.inTable,this.handleText(start,end)}return}if(this.insertionMode===MODES.inSelect||this.insertionMode===MODES.inSelectInTable)return}}function computeLineStarts(html){let arr=[0];for(let i=0;i<html.length;i++)if(html.charCodeAt(i)===10)arr.push(i+1);return arr}function offsetToLineCol(lineStarts,offset){let lo=0,hi=lineStarts.length-1;while(lo<hi){let mid=lo+hi+1>>>1;if(lineStarts[mid]<=offset)lo=mid;else hi=mid-1}return{line:lo+1,column:offset-lineStarts[lo]+1}}function editDistance(a,b){if(a===b)return 0;let la=a.length,lb=b.length;if(la===0)return lb;if(lb===0)return la;let prev2=Array(lb+1),prev1=Array(lb+1),curr=Array(lb+1);for(let j=0;j<=lb;j++)prev1[j]=j;for(let i=1;i<=la;i++){curr[0]=i;let ca=a.charCodeAt(i-1);for(let j=1;j<=lb;j++){let cb=b.charCodeAt(j-1),cost=ca===cb?0:1,v=Math.min(curr[j-1]+1,prev1[j]+1,prev1[j-1]+cost);if(i>1&&j>1&&ca===b.charCodeAt(j-2)&&a.charCodeAt(i-2)===cb)v=Math.min(v,prev2[j-2]+1);curr[j]=v}for(let j=0;j<=lb;j++)prev2[j]=prev1[j],prev1[j]=curr[j]}return prev1[lb]}function closestName(name,candidates,maxDistance=2){if(!name)return null;let lower=name.toLowerCase(),best=null,bestDist=maxDistance+1;for(let cand of candidates){if(cand===name)return null;if(cand.toLowerCase()===lower)return cand;let d=editDistance(name,cand);if(d<bestDist)best=cand,bestDist=d}return bestDist<=maxDistance?best:null}var KNOWN_COMPONENT_SPEC_KEYS=new Set("name view style commonStyle globalStyle input receive bubble response alter on views dynamic fields methods statics".split(" ")),EMPTY_SET2=new Set,KNOWN_DIRECTIVE_NAMES=new Set(["dangerouslysetinnerhtml","slot","push-view","text","show","hide","each","enrich-with","when","loop-with","then","else"]),ALT_HANDLER_NOT_DEFINED="ALT_HANDLER_NOT_DEFINED",ALT_HANDLER_NOT_REFERENCED="ALT_HANDLER_NOT_REFERENCED",DYN_VAL_NOT_DEFINED="DYN_VAL_NOT_DEFINED",DYN_ALIAS_NOT_REFERENCED="DYN_ALIAS_NOT_REFERENCED",RENDER_IT_OUTSIDE_OF_LOOP="RENDER_IT_OUTSIDE_OF_LOOP",UNKNOWN_EVENT_MODIFIER="UNKNOWN_EVENT_MODIFIER",UNKNOWN_HANDLER_ARG_NAME="UNKNOWN_HANDLER_ARG_NAME",INPUT_HANDLER_NOT_IMPLEMENTED="INPUT_HANDLER_NOT_IMPLEMENTED",INPUT_HANDLER_NOT_REFERENCED="INPUT_HANDLER_NOT_REFERENCED",INPUT_HANDLER_METHOD_NOT_IMPLEMENTED="INPUT_HANDLER_METHOD_NOT_IMPLEMENTED",INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD="INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD",INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER="INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER",FIELD_VAL_NOT_DEFINED="FIELD_VAL_NOT_DEFINED",FIELD_VAL_IS_METHOD="FIELD_VAL_IS_METHOD",METHOD_VAL_NOT_DEFINED="METHOD_VAL_NOT_DEFINED",METHOD_VAL_IS_FIELD="METHOD_VAL_IS_FIELD",DUPLICATE_ATTR_DEFINITION="DUPLICATE_ATTR_DEFINITION",IF_NO_BRANCH_SET="IF_NO_BRANCH_SET",UNKNOWN_REQUEST_NAME="UNKNOWN_REQUEST_NAME",UNKNOWN_COMPONENT_NAME="UNKNOWN_COMPONENT_NAME",UNKNOWN_MACRO_ARG="UNKNOWN_MACRO_ARG",UNKNOWN_DIRECTIVE="UNKNOWN_DIRECTIVE",UNKNOWN_X_OP="UNKNOWN_X_OP",UNKNOWN_X_ATTR="UNKNOWN_X_ATTR",MAYBE_DROP_AT_PREFIX="MAYBE_DROP_AT_PREFIX",BAD_VALUE="BAD_VALUE",UNSUPPORTED_EXPR_SYNTAX="UNSUPPORTED_EXPR_SYNTAX",REDUNDANT_TEMPLATE_STRING="REDUNDANT_TEMPLATE_STRING",PLACEHOLDERLESS_TEMPLATE_STRING="PLACEHOLDERLESS_TEMPLATE_STRING",UNKNOWN_COMPONENT_SPEC_KEY="UNKNOWN_COMPONENT_SPEC_KEY",PARSE_ISSUE_KIND_TO_LINT_ID={"unknown-directive":UNKNOWN_DIRECTIVE,"unknown-x-op":UNKNOWN_X_OP,"unknown-x-attr":UNKNOWN_X_ATTR,"bad-value":BAD_VALUE},X_KNOWN_OP_NAMES=new Set(["slot","text","render","render-it","render-each","show","hide"]),X_KNOWN_ATTR_NAMES=new Set(["as","when","loop-with","show","hide"]),AT_PREFIX_HINT_KNOWN_BY_KIND={"unknown-x-op":X_KNOWN_OP_NAMES,"unknown-x-attr":X_KNOWN_ATTR_NAMES},LEVEL_WARN2="warn",LEVEL_ERROR2="error",LEVEL_HINT="hint",PARSE_ISSUE_KIND_TO_KNOWN_NAMES={"unknown-directive":KNOWN_DIRECTIVE_NAMES,"unknown-x-op":X_KNOWN_OP_NAMES,"unknown-x-attr":X_KNOWN_ATTR_NAMES};function collectProtoMethodNames(proto){let out=[],cursor=proto;while(cursor&&cursor!==Object.prototype){for(let key of Object.getOwnPropertyNames(cursor)){if(key==="constructor")continue;out.push(key)}cursor=Object.getPrototypeOf(cursor)}return out}function scopeKeysAlong(scope,mapKey){let out=[];for(let cursor=scope;cursor;cursor=cursor.parent){let map=cursor[mapKey];if(!map)continue;for(let key of Object.keys(map))out.push(key)}return out}function replaceNameSuggestion(name,candidates){let close=closestName(name,candidates);return close?{kind:"replace-name",from:name,to:close}:null}function classifyBadValue(value){if(typeof value!=="string")return null;let s=value.trim();if(s==="")return null;if(/\{[^}]*\}/.test(s)&&!s.startsWith("$'"))return"legacy-template";if(/\s\?\s.+\s:\s/.test(s))return"ternary";if(/===|!==|==|!=|<=|>=|\s<\s|\s>\s/.test(s))return"comparison";if(/&&|\|\|/.test(s))return"logical";if(/^[.$][A-Za-z_]\w*\s+\S/.test(s))return"call-with-args";return null}var UNSUPPORTED_EXPR_GUIDANCE={"legacy-template":"Unquoted {...} string templates are no longer supported. Wrap the value in $'...', e.g. $'flex {.color}'.",ternary:"Ternary expressions aren't supported in dynamic attributes. Define a method or computed field on the component that returns the value, then reference it as '$methodName'.",comparison:"Comparisons aren't supported in dynamic attributes. Define a method like 'isFooSelected' that returns the boolean, then reference it as '$isFooSelected'.",logical:"Logical operators aren't supported in dynamic attributes. Combine the conditions in a method on the component and reference it as '$methodName'.","call-with-args":"Method calls with arguments aren't supported here. Reference a no-arg method ('$methodName') and read what you need from component state, or split into per-case methods."};function checkComponent(Comp,lx=new LintContext,{wellKnownExtras=EMPTY_SET2}={}){return lx.push({componentName:Comp.name},()=>{checkUnknownSpecKeys(lx,Comp,wellKnownExtras);let referencedAlters=new Set,referencedInputs=new Set,referencedDynamics=new Set;checkEventHandlersHaveImpls(lx,Comp,referencedInputs),checkConsistentAttrs(lx,Comp,referencedAlters,referencedDynamics);for(let name in Comp.views)lx.push({viewName:name},()=>checkView(lx,Comp.views[name],Comp,referencedAlters,referencedDynamics));return checkUnreferencedAlterHandlers(lx,Comp,referencedAlters),checkUnreferencedInputHandlers(lx,Comp,referencedInputs),checkUnreferencedDynamics(lx,Comp,referencedDynamics),lx})}function checkView(lx,view,Comp,referencedAlters,referencedDynamics){checkParseIssues(lx,view),checkRenderItInLoop(lx,view),checkEventModifiers(lx,view),checkKnownHandlerNames(lx,view,Comp,referencedAlters,referencedDynamics),checkMacroCallArgs(lx,view,Comp),checkHtmlStructure(lx,view)}var HTML_LINT_OPTS={fragmentContext:"template",transparentTagPrefixes:["x"]};function checkHtmlStructure(lx,view){if(typeof view.rawView!=="string"||!view.rawView)return;lintHtml(view.rawView,(f)=>lx.report(f.id,{...f.info,location:f.location},f.level,f.suggestion??null),HTML_LINT_OPTS)}function checkParseIssues(lx,view){let issues=view.ctx.parseIssues;if(!issues)return;for(let{kind,info}of issues){let id=PARSE_ISSUE_KIND_TO_LINT_ID[kind];if(!id)continue;if(kind==="bad-value"){let detected=classifyBadValue(info.value);if(detected){lx.error(UNSUPPORTED_EXPR_SYNTAX,{...info,detected},{kind:"rephrase",from:info.value,text:UNSUPPORTED_EXPR_GUIDANCE[detected]});continue}}let atPrefixKnown=AT_PREFIX_HINT_KNOWN_BY_KIND[kind],isAtPrefixedTypo=atPrefixKnown&&info.name?.startsWith("@")&&atPrefixKnown.has(info.name.slice(1)),suggestion=null;if(isAtPrefixedTypo)suggestion={kind:"drop-prefix",from:info.name,to:info.name.slice(1)};else{let candidates=PARSE_ISSUE_KIND_TO_KNOWN_NAMES[kind];if(candidates)suggestion=replaceNameSuggestion(info.name,candidates)}if(lx.error(id,info,suggestion),isAtPrefixedTypo)lx.hint(MAYBE_DROP_AT_PREFIX,{...info,suggestion:info.name.slice(1)},{kind:"drop-prefix",from:info.name,to:info.name.slice(1)})}}function checkMacroCallArgs(lx,view,Comp){let{scope}=Comp;for(let macroNode of view.ctx.macroNodes){let macro=scope.lookupMacro(macroNode.name);if(macro===null)continue;let{defaults}=macro;for(let argName in macroNode.attrs)if(!(argName in defaults))lx.error(UNKNOWN_MACRO_ARG,{name:argName,macroName:macroNode.name,tag:`x:${macroNode.name}`},replaceNameSuggestion(argName,Object.keys(defaults)))}}function checkRenderItInLoop(lx,view){let hasRenderIt=!1;for(let node of view.ctx.nodes)if(node.constructor.name==="RenderItNode"){hasRenderIt=!0;break}if(!hasRenderIt)return;walkForRenderIt(lx,view.anode,0)}function walkForRenderIt(lx,node,loopDepth){if(node===null||node===void 0)return;switch(node.constructor.name){case"RenderItNode":if(loopDepth===0)lx.error(RENDER_IT_OUTSIDE_OF_LOOP,{node},{kind:"wrap",from:"<x render-it>",to:"<x render-each>"});return;case"EachNode":walkForRenderIt(lx,node.node,loopDepth+1);return;case"ShowNode":case"HideNode":case"ScopeNode":case"SlotNode":case"PushViewNameNode":case"MacroNode":case"RenderOnceNode":walkForRenderIt(lx,node.node,loopDepth);return;case"DomNode":case"FragmentNode":for(let child of node.childs)walkForRenderIt(lx,child,loopDepth);return;default:return}}var NO_WRAPPERS={};function checkEventModifiers(lx,view){for(let event of view.ctx.events)for(let handler of event.handlers){let{name,modifiers}=handler,modWrappers=MOD_WRAPPERS_BY_EVENT[name]??NO_WRAPPERS;for(let modifier of modifiers)if(modWrappers[modifier]===void 0){let close=closestName(modifier,Object.keys(modWrappers));lx.error(UNKNOWN_EVENT_MODIFIER,{name,modifier,handler,event,originAttr:`@on.${name}+${modifiers.join("+")}`},close?{kind:"replace-name",from:`+${modifier}`,to:`+${close}`}:null)}}}var KNOWN_HANDLER_NAMES=new Set(["value","valueAsInt","valueAsFloat","target","event","isAlt","isShift","isCtrl","isCmd","key","keyCode","isUpKey","isDownKey","isSend","isCancel","isTabKey","ctx","dragInfo"]);function isKnownHandlerName(name){return KNOWN_HANDLER_NAMES.has(name)}function checkKnownHandlerNames(lx,view,Comp,referencedAlters,referencedDynamics){let env=mkAttrValEnv(Comp,referencedAlters,referencedDynamics);for(let event of view.ctx.events)for(let handler of event.handlers){let{args,handlerVal}=handler.handlerCall,handlerName=handlerVal?.name,eventName=handler.name,errCtx={eventName,handlerName,originAttr:`@on.${eventName}`};for(let i=0;i<args.length;i++)checkConsistentAttrVal(lx,args[i],env,!1,{...errCtx,argIndex:i})}}function mkAttrValEnv(Comp,referencedAlters,referencedDynamics){let{scope,alter,dynamic,Class}=Comp,{prototype:proto}=Class,{fields}=Class.getMetaClass();return{fields,proto,scope,alter,referencedAlters,dynamicMap:dynamic,referencedDynamics}}function checkEventHandlersHaveImpls(lx,Comp,referencedInputs){let{input,views,Class}=Comp,{prototype:proto}=Class;for(let viewName in views)lx.push({viewName},()=>{let view=views[viewName];for(let event of view.ctx.events)for(let handler of event.handlers){let{handlerVal}=handler.handlerCall,hvName=handlerVal?.constructor.name,eventName=handler.name,originAttr=`@on.${eventName}`;if(hvName==="HandlerNameVal"){referencedInputs?.add(handlerVal.name);let{name}=handlerVal;if(input[name]===void 0){let isMethodFix=proto[name]!==void 0;if(lx.error(INPUT_HANDLER_NOT_IMPLEMENTED,{name,handler,event,eventName,originAttr},isMethodFix?{kind:"add-prefix",from:name,to:`$${name}`}:replaceNameSuggestion(name,Object.keys(input))),isMethodFix)lx.hint(INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER,{name,handler,event,eventName,originAttr},{kind:"add-prefix",from:name,to:`$${name}`})}}else if(hvName==="MethodVal"){referencedInputs?.add(handlerVal.name);let{name}=handlerVal;if(proto[name]===void 0){let isInputFix=input[name]!==void 0;if(lx.error(INPUT_HANDLER_METHOD_NOT_IMPLEMENTED,{name,handler,event,eventName,originAttr},isInputFix?{kind:"drop-prefix",from:`$${name}`,to:name}:replaceNameSuggestion(name,collectProtoMethodNames(proto))),isInputFix)lx.hint(INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD,{name,handler,event,eventName,originAttr},{kind:"drop-prefix",from:`$${name}`,to:name})}}}})}function checkConsistentAttrVal(lx,val,env,skipNameVal=!1,errCtx=null){let{fields,proto,scope,alter}=env,valName=val?.constructor.name;if(valName==="FieldVal"){let{name}=val;if(fields[name]===void 0)if(proto[name]!==void 0)lx.error(FIELD_VAL_IS_METHOD,{...errCtx,val,name},{kind:"rewrite",from:`.${name}`,to:`$${name}`});else lx.error(FIELD_VAL_NOT_DEFINED,{...errCtx,val,name},replaceNameSuggestion(name,Object.keys(fields)))}else if(valName==="MethodVal"){let{name}=val;if(proto[name]===void 0)if(fields[name]!==void 0)lx.error(METHOD_VAL_IS_FIELD,{...errCtx,val,name},{kind:"rewrite",from:`$${name}`,to:`.${name}`});else lx.error(METHOD_VAL_NOT_DEFINED,{...errCtx,val,name},replaceNameSuggestion(name,collectProtoMethodNames(proto)))}else if(valName==="SeqAccessVal")checkConsistentAttrVal(lx,val.seqVal,env,skipNameVal,errCtx),checkConsistentAttrVal(lx,val.keyVal,env,skipNameVal,errCtx);else if(valName==="RequestVal"){if(scope.lookupRequest(val.name)===null)lx.error(UNKNOWN_REQUEST_NAME,{...errCtx,name:val.name},replaceNameSuggestion(val.name,scopeKeysAlong(scope,"reqsByName")))}else if(valName==="TypeVal"){if(scope.lookupComponent(val.name)===null)lx.error(UNKNOWN_COMPONENT_NAME,{...errCtx,name:val.name},replaceNameSuggestion(val.name,scopeKeysAlong(scope,"byName")))}else if(valName==="NameVal"){if(!skipNameVal&&!isKnownHandlerName(val.name))lx.error(UNKNOWN_HANDLER_ARG_NAME,{...errCtx,name:val.name},replaceNameSuggestion(val.name,KNOWN_HANDLER_NAMES))}else if(valName==="StrTplVal"){let vs=val.vals,literal=val.toLiteralSource();if(literal!==null)lx.hint(PLACEHOLDERLESS_TEMPLATE_STRING,{...errCtx,literal},{kind:"rewrite",from:`$${literal}`,to:literal});else if(vs.length===1){let simpler=String(vs[0]);lx.warn(REDUNDANT_TEMPLATE_STRING,{...errCtx,simpler},{kind:"rewrite",from:`$'{${simpler}}'`,to:simpler})}for(let subVal of vs)checkConsistentAttrVal(lx,subVal,env,skipNameVal,errCtx)}else if(valName==="HandlerNameVal"){if(env.referencedAlters?.add(val.name),alter[val.name]===void 0)lx.error(ALT_HANDLER_NOT_DEFINED,{...errCtx,name:val.name},replaceNameSuggestion(val.name,Object.keys(alter)))}else if(valName==="PredicateVal")for(let arg of val.args)checkConsistentAttrVal(lx,arg,env,skipNameVal,errCtx);else if(valName==="DynVal"){if(env.referencedDynamics?.add(val.name),env.dynamicMap[val.name]===void 0)lx.error(DYN_VAL_NOT_DEFINED,{...errCtx,name:val.name},replaceNameSuggestion(val.name,Object.keys(env.dynamicMap)))}else if(valName!=="ConstVal"&&valName!=="BindVal")console.log(val)}var NODE_KIND_TO_CTX={RenderTextNode:{originAttr:"<x text>"},RenderNode:{originAttr:"<x render>"},RenderItNode:{originAttr:"<x render-it>"},RenderEachNode:{originAttr:"<x render-each>"},ShowNode:{originAttr:"<x show>"},HideNode:{originAttr:"<x hide>"},PushViewNameNode:{originAttr:"<x push-view>"}};function nodeCtxForNode(nodeKind){return NODE_KIND_TO_CTX[nodeKind]??null}function attrSourceLabel(attr){let cn=attr.constructor.name;if(cn==="ConstAttr")return"literal";if(cn==="IfAttr")return`@if.${attr.name}`;if(cn==="RawHtmlAttr")return"@dangerouslysetinnerhtml";return`:${attr.name}`}function attrOriginAttr(attr){let cn=attr.constructor.name;if(cn==="IfAttr")return`@if.${attr.name}`;if(cn==="RawHtmlAttr")return"@dangerouslysetinnerhtml";return`:${attr.name}`}function checkConsistentAttrs(lx,Comp,referencedAlters,referencedDynamics){let{views}=Comp,env=mkAttrValEnv(Comp,referencedAlters,referencedDynamics);for(let viewName in views)lx.push({viewName},()=>{let view=views[viewName];for(let entry of view.ctx.attrs){let{attrs,wrapperAttrs,textChild,isMacroCall,tag}=entry;if(attrs?.constructor.name==="DynAttrs"){let sourcesByName=new Map;for(let attr of attrs.items){let name=attr?.name;if(name!==void 0&&name!=="data-eid"){let sources=sourcesByName.get(name),label=attrSourceLabel(attr);if(sources)sources.push(label);else sourcesByName.set(name,[label])}if(attr?.constructor.name==="IfAttr"){if(!attr.anyBranchIsSet)lx.error(IF_NO_BRANCH_SET,{attr:attr.name,tag});let branches=[["@if",attr.condVal],["@then",attr.thenVal],["@else",attr.elseVal]];for(let[branch,subVal]of branches)checkConsistentAttrVal(lx,subVal,env,isMacroCall,{tag,originAttr:`@if.${attr.name}`,branch})}else if(attr?.val!==void 0)checkConsistentAttrVal(lx,attr.val,env,isMacroCall,{tag,originAttr:attrOriginAttr(attr)})}for(let[name,sources]of sourcesByName)if(sources.length>1)lx.error(DUPLICATE_ATTR_DEFINITION,{name,sources,tag})}if(wrapperAttrs!==null)for(let w of wrapperAttrs)if(w.name==="each"){if(w.whenVal)checkConsistentAttrVal(lx,w.whenVal,env,!1,{tag,originAttr:"@when"});if(w.enrichWithVal)checkConsistentAttrVal(lx,w.enrichWithVal,env,!1,{tag,originAttr:"@enrich-with"});if(w.loopWithVal)checkConsistentAttrVal(lx,w.loopWithVal,env,!1,{tag,originAttr:"@loop-with"})}else{let originAttr=w.name==="scope"?"@enrich-with":`@${w.name}`;checkConsistentAttrVal(lx,w.val,env,!1,{tag,originAttr})}if(textChild)checkConsistentAttrVal(lx,textChild,env,!1,{tag,originAttr:"@text"})}for(let node of view.ctx.nodes){let nodeKind=node.constructor.name;if(nodeKind==="ScopeNode")continue;let baseCtx=nodeCtxForNode(nodeKind);if(node.val)checkConsistentAttrVal(lx,node.val,env,!1,baseCtx);if(nodeKind==="RenderEachNode"){let iter=node.iterInfo;if(iter.whenVal)checkConsistentAttrVal(lx,iter.whenVal,env,!1,{originAttr:"<x render-each when>"});if(iter.loopWithVal)checkConsistentAttrVal(lx,iter.loopWithVal,env,!1,{originAttr:"<x render-each loop-with>"})}}})}function checkUnknownSpecKeys(lx,Comp,wellKnownExtras){let extra=Comp.extra;if(!extra)return;let candidates=null;for(let key of Object.keys(extra)){if(wellKnownExtras.has(key))continue;candidates??=[...KNOWN_COMPONENT_SPEC_KEYS,...wellKnownExtras],lx.warn(UNKNOWN_COMPONENT_SPEC_KEY,{key},replaceNameSuggestion(key,candidates))}}function checkUnreferencedAlterHandlers(lx,Comp,referencedAlters){for(let name in Comp.alter)if(!referencedAlters.has(name))lx.hint(ALT_HANDLER_NOT_REFERENCED,{name})}function checkUnreferencedInputHandlers(lx,Comp,referencedInputs){for(let name in Comp.input)if(!referencedInputs.has(name))lx.hint(INPUT_HANDLER_NOT_REFERENCED,{name})}function checkUnreferencedDynamics(lx,Comp,referencedDynamics){for(let name in Comp.dynamic)if(Comp.dynamic[name].constructor.name==="DynamicAlias"&&!referencedDynamics.has(name))lx.hint(DYN_ALIAS_NOT_REFERENCED,{name})}class LintContext{constructor(){this.reports=[],this.frame={}}push(patch,fn){let prev=this.frame;this.frame={...prev,...patch};try{return fn()}finally{this.frame=prev}}error(id,info,suggestion=null){this.report(id,info,LEVEL_ERROR2,suggestion)}warn(id,info,suggestion=null){this.report(id,info,LEVEL_WARN2,suggestion)}hint(id,info,suggestion=null){this.report(id,info,LEVEL_HINT,suggestion)}report(id,info={},level=LEVEL_ERROR2,suggestion=null){this.reports.push({id,info,level,context:{...this.frame},suggestion})}}class LintParseContext extends ParseContext{constructor(document2,Text,Comment){super(document2,Text,Comment);this.attrs=[],this.parseIssues=[]}onAttributes(attrs,wrapperAttrs,textChild,isMacroCall=!1,tag=null){this.attrs.push({attrs,wrapperAttrs,textChild,isMacroCall,tag})}onParseIssue(kind,info){let tag=this.currentTag;this.parseIssues.push({kind,info:tag&&info.tag===void 0?{...info,tag}:info})}}class ModuleInfo{constructor({path=null,present=new Set,counts={},warnings=[]}){this.path=path,this.present=present,this.counts=counts,this.warnings=warnings}}class ComponentSummary{constructor({name,views,fields}){this.name=name,this.views=views,this.fields=fields}}class ComponentList{constructor({items,total=null,truncated=!1}){this.items=items,this.total=total??items.length,this.truncated=truncated}}class ExampleIndex{constructor({sections,total=null,truncated=!1}){this.sections=sections,this.total=total??sections.reduce((n,s)=>n+(s.items?.length??0),0),this.truncated=truncated}}class ComponentDocs{constructor({items}){this.items=items}}class LintFinding{constructor({id,level,info,context={},suggestion=null}){this.id=id,this.level=level,this.info=info,this.context=context,this.suggestion=suggestion}}class LintComponentResult{constructor({componentName,findings}){this.componentName=componentName,this.findings=findings}get errorCount(){return this.findings.filter((f)=>f.level==="error").length}get warnCount(){return this.findings.filter((f)=>f.level==="warn").length}}class LintReport{constructor({components}){this.components=components}get hasErrors(){return this.components.some((c)=>c.errorCount>0)}get totalErrors(){return this.components.reduce((n,c)=>n+c.errorCount,0)}get totalWarnings(){return this.components.reduce((n,c)=>n+c.warnCount,0)}}class RenderedExample{constructor({title,description=null,componentName,view,html,error=null}){this.title=title,this.description=description,this.componentName=componentName,this.view=view,this.html=html,this.error=error}}class RenderedSection{constructor({title,description=null,items}){this.title=title,this.description=description,this.items=items}}class RenderBatch{constructor({sections}){this.sections=sections}get hasErrors(){return this.sections.some((s)=>s.items.some((i)=>i.error!==null))}}class TestResult{constructor({title,fullPath,componentName=null,status,durationMs=0,error=null}){this.title=title,this.fullPath=fullPath,this.componentName=componentName,this.status=status,this.durationMs=durationMs,this.error=error}}class DescribeResult{constructor({title,componentName=null,children=[]}){this.title=title,this.componentName=componentName,this.children=children}}class ModuleTestReport{constructor({path=null,suites=[],counts={pass:0,fail:0,skip:0,total:0}}){this.path=path,this.suites=suites,this.counts=counts}}class TestReport{constructor({modules=[]}){this.modules=modules}get totals(){return this.modules.reduce((acc,m)=>({pass:acc.pass+m.counts.pass,fail:acc.fail+m.counts.fail,skip:acc.skip+m.counts.skip,total:acc.total+m.counts.total}),{pass:0,fail:0,skip:0,total:0})}get hasFailures(){return this.modules.some((m)=>m.counts.fail>0)}}class Describe{constructor({title,componentName=null,parent=null}){this.title=title,this.componentName=componentName,this.parent=parent,this.children=[]}}class Test{constructor({title,fn,componentName=null,parent=null}){this.title=title,this.fn=fn,this.componentName=componentName,this.parent=parent}}class ModuleTests{constructor({path=null,suites=[]}={}){this.path=path,this.suites=suites}}class TestIndex{constructor({modules=[]}={}){this.modules=modules}}function isComponentObject(x){return x!==null&&typeof x==="object"&&typeof x.name==="string"&&typeof x.Class==="function"}function resolveComponentName(arg,components){if(isComponentObject(arg))return arg.name;if(typeof arg==="function"){for(let c of components)if(c.Class===arg)return c.name}return null}function titleFromArg(arg){if(typeof arg==="string")return arg;if(isComponentObject(arg))return arg.name;if(typeof arg==="function")return arg.name||"(anonymous)";return String(arg)}function makeCollector({path=null,components=[]}={}){let moduleTests=new ModuleTests({path,suites:[]}),stack=[];function describe(...args){let head,options=null,fn;if(args.length===2)[head,fn]=args;else if(args.length===3)[head,options,fn]=args;else throw Error(`describe() expects 2 or 3 arguments, got ${args.length}`);if(typeof fn!=="function")throw Error(`describe(${JSON.stringify(titleFromArg(head))}): final argument must be a function`);let componentName=null;if(typeof head!=="string")componentName=resolveComponentName(head,components);if(componentName===null&&options&&options.component!=null)componentName=resolveComponentName(options.component,components);if(componentName===null){let parent2=stack.length?stack[stack.length-1]:null;if(parent2)componentName=parent2.componentName}let parent=stack.length?stack[stack.length-1]:null,node=new Describe({title:titleFromArg(head),componentName,parent});if(parent)parent.children.push(node);else moduleTests.suites.push(node);stack.push(node);try{fn()}finally{stack.pop()}}function test2(title,fn){if(typeof title!=="string")throw Error("test(title, fn): title must be a string");if(typeof fn!=="function")throw Error(`test(${JSON.stringify(title)}): fn must be a function`);let parent=stack.length?stack[stack.length-1]:null;if(!parent)throw Error(`test(${JSON.stringify(title)}) must be called inside a describe()`);parent.children.push(new Test({title,fn,componentName:parent.componentName,parent}))}return{describe,test:test2,moduleTests}}function buildPath(node){let parts=[],cur=node;while(cur)parts.unshift(cur.title),cur=cur.parent;return parts.join(" > ")}function captureError(e){let out={message:e.message,stack:e.stack};if("expected"in e)out.expected=e.expected;if("actual"in e)out.actual=e.actual;return out}async function runTests({getTests,components=[],path=null,expect:expect2,name=null,grep=null,bail=!1}={}){let counts={pass:0,fail:0,skip:0,total:0};if(typeof getTests!=="function")return new TestReport({modules:[new ModuleTestReport({path,suites:[],counts})]});if(typeof expect2!=="function")throw Error("runTests: expect must be provided (e.g. chai's expect)");let{describe,test:test2,moduleTests}=makeCollector({path,components});await getTests({describe,test:test2,expect:expect2});let bailed=!1;async function visit(node){if(node instanceof Test){if(name!==null&&node.componentName!==name)return null;let fullPath=buildPath(node);if(grep!==null&&!fullPath.includes(grep))return null;if(counts.total++,bailed)return counts.skip++,new TestResult({title:node.title,fullPath,componentName:node.componentName,status:"skip"});let start=performance.now();try{return await node.fn(),counts.pass++,new TestResult({title:node.title,fullPath,componentName:node.componentName,status:"pass",durationMs:performance.now()-start})}catch(e){if(counts.fail++,bail)bailed=!0;return new TestResult({title:node.title,fullPath,componentName:node.componentName,status:"fail",durationMs:performance.now()-start,error:captureError(e)})}}let childResults=[];for(let child of node.children){let r=await visit(child);if(r!==null)childResults.push(r)}if(childResults.length===0)return null;return new DescribeResult({title:node.title,componentName:node.componentName,children:childResults})}let suiteResults=[];for(let suite of moduleTests.suites){let r=await visit(suite);if(r!==null)suiteResults.push(r)}return new TestReport({modules:[new ModuleTestReport({path,suites:suiteResults,counts})]})}function reportTestNode(node){if(node.children){let label=node.componentName?`${node.title} [${node.componentName}]`:node.title;console.group(label);for(let child of node.children)reportTestNode(child);console.groupEnd();return}let dur=node.status==="skip"?"":` (${Math.round(node.durationMs)}ms)`;if(node.status==="pass")console.log(`%c✓%c ${node.title}%c${dur}`,"color: #0a0; font-weight: bold","color: inherit; font-weight: normal","color: #888");else if(node.status==="skip")console.log(`%c○ ${node.title}%c (skipped)`,"color: #888","color: inherit; font-weight: normal");else{if(console.group(`%c✗%c ${node.title}%c${dur}`,"color: #c00; font-weight: bold","color: inherit; font-weight: normal","color: #888"),console.error(node.error?.message??"(no error message)"),node.error&&(("expected"in node.error)||("actual"in node.error)))console.log("expected:",node.error.expected),console.log("actual: ",node.error.actual);if(node.error?.stack)console.log(node.error.stack);console.groupEnd()}}function reportTestReportToConsole(report){for(let m of report.modules){let label=`tutuca tests${m.path?` — ${m.path}`:""}`;if(console.group(label),m.suites.length===0)console.log("(no tests)");else for(let s of m.suites)reportTestNode(s);let c=m.counts,summary=`${c.pass} passed, ${c.fail} failed, ${c.skip} skipped (${c.total} total)`;if(c.fail>0)console.error(`%c${summary}`,"color: #c00; font-weight: bold");else if(c.total===0)console.log(`%c${summary}`,"color: #888");else console.log(`%c${summary}`,"color: #0a0; font-weight: bold");console.groupEnd()}return report}var UNSUPPORTED_EXPR_LABEL={"legacy-template":"string template",ternary:"ternary expression",comparison:"comparison",logical:"logical expression","call-with-args":"method call with arguments"};function unsupportedExprMessage(info){let v=JSON.stringify(info.value),label=UNSUPPORTED_EXPR_LABEL[info.detected]??"expression";switch(info.role){case"attr":return`Unsupported ${label} ${v} in dynamic attribute ':${info.attr}'`;case"directive":return`Unsupported ${label} ${v} in directive '@${info.directive}'`;case"if":return`Unsupported ${label} ${v} in '@if.${info.attr}' condition`;case"x-op":return`Unsupported ${label} ${v} in <x ${info.op}>`;default:return`Unsupported ${label} ${v}`}}function badValueMessage(info){let v=JSON.stringify(info.value);switch(info.role){case"attr":return`Cannot parse value ${v} for attribute ':${info.attr}'`;case"directive":return`Cannot parse value ${v} for directive '@${info.directive}'`;case"if":return`Cannot parse condition ${v} for '@if.${info.attr}'`;case"x-op":return`Cannot parse value ${v} for <x ${info.op}>`;case"handler-name":return`Cannot parse handler name ${v}`;case"handler-arg":return`Cannot parse handler argument ${v}`;case"macro-var":return`Macro variable '^${info.name}' is not defined`;default:return`Cannot parse value ${v}`}}function tagDisplay(tag){return tag?String(tag).toLowerCase():null}function fmtTagSuffix(info){let t=tagDisplay(info?.tag);return t&&t!=="x"?` on <${t}>`:""}function fmtOriginSuffix(info){if(!info)return"";let parts=[];if(info.originAttr){let branch=info.branch?`[${info.branch}]`:"";parts.push(`in ${info.originAttr}${branch}`)}if(info.handlerName)parts.push(`handler '${info.handlerName}'${info.argIndex!==void 0?` arg ${info.argIndex}`:""}`);let t=tagDisplay(info.tag);if(t&&t!=="x")parts.push(`on <${t}>`);return parts.length?` (${parts.join(", ")})`:""}function fmtEventSuffix(info){if(info?.originAttr)return` in ${info.originAttr}`;if(info?.eventName)return` in @on.${info.eventName}`;return""}function lintIdToMessage(id,info){switch(id){case"RENDER_IT_OUTSIDE_OF_LOOP":return"<x render-it> used outside of a loop";case"UNKNOWN_EVENT_MODIFIER":{let mods=info.handler?.modifiers??[info.modifier],written=`@on.${info.name}+${mods.join("+")}`;return`Unknown modifier '+${info.modifier}' in '${written}'`}case"UNKNOWN_HANDLER_ARG_NAME":return`Unknown handler argument '${info.name}'${fmtOriginSuffix(info)}`;case"INPUT_HANDLER_NOT_IMPLEMENTED":return`Input handler '${info.name}' is not implemented${fmtEventSuffix(info)}`;case"INPUT_HANDLER_NOT_REFERENCED":return`Input handler '${info.name}' is defined but never used — remove it or wire it to an @on.* event`;case"INPUT_HANDLER_METHOD_NOT_IMPLEMENTED":return`Method '$${info.name}' is not implemented${fmtEventSuffix(info)}`;case"INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD":return`'$${info.name}' is a method reference, but '${info.name}' is defined as an input handler${fmtEventSuffix(info)}`;case"INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER":return`'${info.name}' is an input handler reference, but '${info.name}' is defined as a method${fmtEventSuffix(info)}`;case"FIELD_VAL_NOT_DEFINED":return`Field '.${info.name}' is not defined${fmtOriginSuffix(info)}`;case"FIELD_VAL_IS_METHOD":return`'.${info.name}' reads a field, but '${info.name}' is defined as a method — use '$${info.name}'${fmtOriginSuffix(info)}`;case"METHOD_VAL_NOT_DEFINED":return`Method '$${info.name}' is not defined${fmtOriginSuffix(info)}`;case"METHOD_VAL_IS_FIELD":return`'$${info.name}' calls a method, but '${info.name}' is defined as a field — use '.${info.name}'${fmtOriginSuffix(info)}`;case"DUPLICATE_ATTR_DEFINITION":{let sources=info.sources?.length?` (${info.sources.join(", ")})`:"",tag=info.tag?` on <${String(info.tag).toLowerCase()}>`:"";return`Attribute '${info.name}' is set ${info.sources?.length??"multiple"} times${sources}${tag}`}case"IF_NO_BRANCH_SET":return`'@if.${info.attr}' has no '@then' or '@else' branch — add '@then="…"' or '@else="…"' (or both)${fmtTagSuffix(info)}`;case"UNKNOWN_REQUEST_NAME":return`Unknown request '!${info.name}'${fmtOriginSuffix(info)}`;case"UNKNOWN_COMPONENT_NAME":return`Unknown component '${info.name}'${fmtOriginSuffix(info)}`;case"ALT_HANDLER_NOT_DEFINED":return`Alter handler '${info.name}' is not defined${fmtOriginSuffix(info)}`;case"ALT_HANDLER_NOT_REFERENCED":return`Alter handler '${info.name}' is defined but never used — remove it or reference it from @when, @enrich-with, or @loop-with`;case"DYN_VAL_NOT_DEFINED":return`Dynamic variable '*${info.name}' is not defined${fmtOriginSuffix(info)}`;case"DYN_ALIAS_NOT_REFERENCED":return`Dynamic '${info.name}' is defined but never used — remove it or reference it as '*${info.name}' in a view`;case"UNKNOWN_MACRO_ARG":return`Argument '${info.name}' is not declared in macro '${info.macroName}'`;case"UNKNOWN_DIRECTIVE":return`Unknown directive '@${info.name}=${JSON.stringify(info.value)}'${fmtTagSuffix(info)}`;case"UNKNOWN_X_OP":return`Unknown <x> op '${info.name}=${JSON.stringify(info.value)}'${fmtTagSuffix(info)}`;case"UNKNOWN_X_ATTR":return`Unknown attribute '${info.name}=${JSON.stringify(info.value)}' on <x ${info.op}>${fmtTagSuffix(info)}`;case"MAYBE_DROP_AT_PREFIX":return`'${info.value!==void 0?`${info.name}=${JSON.stringify(info.value)}`:info.name}' on <x> looks like a directive but is actually an x op/attr written with a leading '@'`;case"BAD_VALUE":return`${badValueMessage(info)}${fmtTagSuffix(info)}`;case"UNSUPPORTED_EXPR_SYNTAX":return`${unsupportedExprMessage(info)}${fmtTagSuffix(info)}`;case"REDUNDANT_TEMPLATE_STRING":return`Redundant template string — '{${info.simpler}}' should be just '${info.simpler}'${fmtOriginSuffix(info)}`;case"PLACEHOLDERLESS_TEMPLATE_STRING":return`Template string has no dynamic parts — use the string literal ${info.literal} instead${fmtOriginSuffix(info)}`;case"UNKNOWN_COMPONENT_SPEC_KEY":return`Unknown component spec key '${info.key}' — value will be ignored at runtime`;case"HTML_TAG_NAME_HAS_UPPERCASE":return`Tag <${info.raw}> will be lowercased to <${info.lowercased}>${fmtLocationSuffix(info)}`;case"HTML_SVG_TAG_WILL_LOWERCASE":return`SVG tag <${info.raw}> is not in the WHATWG case-correction list — will be lowercased to <${info.lowercased}>${fmtLocationSuffix(info)}`;case"HTML_TAG_NOT_ALLOWED_IN_PARENT":return`<${info.tag}> not allowed under <${info.parent??"?"}> in ${info.mode} — ${htmlActionPhrase(info.action,info.tag,info.parent)}${fmtLocationSuffix(info)}`;case"HTML_TEXT_NOT_ALLOWED_IN_PARENT":return`Non-whitespace text not allowed in ${info.mode}: ${JSON.stringify(info.snippet)}${fmtLocationSuffix(info)}`;case"HTML_VOID_ELEMENT_HAS_CLOSE_TAG":return`Void element <${info.tag}> has an explicit close tag${fmtLocationSuffix(info)}`;case"HTML_DUPLICATE_FORM":return`Nested <form> — the inner form will be dropped by the parser${fmtLocationSuffix(info)}`;case"HTML_NESTED_INTERACTIVE":return`<${info.tag}> nested inside another <${info.tag}> — adoption agency will reorder${fmtLocationSuffix(info)}`;case"HTML_MISNESTED_FORMATTING":return`Misnested formatting tag </${info.tag}> — adoption agency will reorder nodes${fmtLocationSuffix(info)}`;case"HTML_UNEXPECTED_END_TAG":return`Unexpected end tag </${info.tag}>${fmtLocationSuffix(info)}`;case"HTML_UNCLOSED_BEFORE_END":return`<${info.unclosed}> still open when </${info.tag}> was seen — implicitly closed${fmtLocationSuffix(info)}`;case"HTML_DUPLICATE_ATTRIBUTE":return`Duplicate attribute '${info.name}' — second occurrence dropped${fmtLocationSuffix(info)}`;case"HTML_ATTRIBUTES_ON_END_TAG":return`Attributes on end tag </${info.tag}> — dropped by the parser${fmtLocationSuffix(info)}`;case"HTML_SELF_CLOSING_END_TAG":return`Self-closing end tag </${info.tag}/> — trailing '/' is meaningless${fmtLocationSuffix(info)}`;case"HTML_MISSING_ATTRIBUTE_VALUE":return`Attribute '${info.name}' is missing a value${fmtLocationSuffix(info)}`;case"HTML_CDATA_IN_HTML_NAMESPACE":return`CDATA section in HTML namespace — reinterpreted as a bogus comment${fmtLocationSuffix(info)}`;case"HTML_BOGUS_COMMENT":return`Bogus comment — content dropped by the parser${fmtLocationSuffix(info)}`;case"HTML_SVG_ATTR_WILL_LOWERCASE":return`SVG attribute '${info.raw}' will be rewritten to '${info.canonical}'${fmtLocationSuffix(info)}`;case"HTML_MATHML_ATTR_WILL_LOWERCASE":return`MathML attribute '${info.raw}' will be rewritten to '${info.canonical}'${fmtLocationSuffix(info)}`;case"LINT_ERROR":return info.message;default:return id}}function suggestionToMessage(suggestion){if(!suggestion)return null;switch(suggestion.kind){case"replace-name":return`did you mean '${suggestion.to}'?`;case"drop-prefix":return`did you mean '${suggestion.to}'? (drop the leading '${suggestion.from.slice(0,suggestion.from.length-suggestion.to.length)}')`;case"add-prefix":return`did you mean '${suggestion.to}'? (add the leading '${suggestion.to.slice(0,suggestion.to.length-suggestion.from.length)}')`;case"remove":return`remove ${suggestion.what}`;case"rewrite":return`use '${suggestion.to}' instead of '${suggestion.from}'`;case"wrap":return`wrap it in ${suggestion.to}`;case"rephrase":return suggestion.text??null;default:return null}}function fmtLocationSuffix(info){let loc=info?.location;if(!loc)return"";return` at line ${loc.line}, col ${loc.column}`}function htmlActionPhrase(action,tag,parent){switch(action){case"ignored":return`the parser will drop this <${tag}>`;case"drop":return`the parser will drop this <${tag}>`;case"auto-close-implicit":return`the parser will close <${parent??"?"}> first, then place <${tag}> as a sibling`;case"foster-parent":return`the parser will move <${tag}> outside <${parent??"?"}> (foster-parenting)`;case"foreign-breakout":return`the parser will exit foreign content and re-process <${tag}> in HTML mode`;default:return`parser action: ${action}`}}class Components{constructor(){this.getComponentSymbol=Symbol("getComponent"),this.byId=new Map}registerComponent(comp){comp.Class.prototype[this.getComponentSymbol]=()=>comp,this.byId.set(comp.id,comp)}getComponentForId(id){return this.byId.get(id)??null}getCompFor(v){return v?.[this.getComponentSymbol]?.()??null}getOnEnterFor(v){return this.getCompFor(v)?.on.stackEnter??defaultOnStackEnter}getHandlerFor(v,name,key){return this.getCompFor(v)?.[key][name]??null}getRequestFor(v,name){return this.getCompFor(v)?.scope.lookupRequest(name)??null}compileStyles(){let styles2=[];for(let comp of this.byId.values())styles2.push(comp.compileStyle());return styles2.join(`
|
|
3
3
|
`)}}class ComponentStack{constructor(comps=new Components,parent=null){this.comps=comps,this.parent=parent,this.byName={},this.reqsByName={},this.macros={}}enter(){return new ComponentStack(this.comps,this)}registerComponents(comps,opts){let{aliases:aliases2={}}=opts??{};for(let i=0;i<comps.length;i++){let comp=comps[i];comp.scope=this.enter(),this.comps.registerComponent(comp),this.byName[comp.name]=comp}for(let alias in aliases2){let comp=this.byName[aliases2[alias]];if(console.assert(this.byName[alias]===void 0,"alias overrides component",alias),comp!==void 0)this.byName[alias]=comp;else console.warn("alias",alias,"to inexistent component",aliases2[alias])}}registerMacros(macros){for(let key in macros){let lower=key.toLowerCase();console.assert(this.macros[lower]===void 0,"macro key collision",lower),this.macros[lower]=macros[key]}}getCompFor(v){return this.comps.getCompFor(v)}registerRequestHandlers(handlers){for(let name in handlers)this.reqsByName[name]=new RequestHandler(name,handlers[name])}lookupRequest(name){return this.reqsByName[name]??this.parent?.lookupRequest(name)??null}lookupComponent(name){return this.byName[name]??this.parent?.lookupComponent(name)??null}lookupMacro(name){return this.macros[name]??this.parent?.lookupMacro(name)??null}}class Dynamic{constructor(name,val,symbol){this.name=name,this.val=val,this.symbol=symbol}getSymbol(_stack){return this.symbol}evalAndBind(stack,binds){binds[this.getSymbol(stack)]=this.val.eval(stack)}}class DynamicAlias extends Dynamic{constructor(name,val,compName,dynName){super(name,val,null);this.compName=compName,this.dynName=dynName}_resolveSymbol(stack){return stack.lookupType(this.compName)?.dynamic[this.dynName]?.symbol??null}getSymbol(stack){return this.symbol??=this._resolveSymbol(stack),this.symbol}}var isString=(v)=>typeof v==="string",_rawSpecKeys="name view style commonStyle globalStyle input receive bubble response alter on views dynamic fields methods statics",KNOWN_SPEC_KEYS=new Set(_rawSpecKeys.split(" ")),_compId=0;class Component{constructor(Class,o){this.id=_compId++,this.name=o.name??"UnkComp",this.Class=Class,this.views={main:new View("main",o.view,o.style)},this.commonStyle=o.commonStyle??"",this.globalStyle=o.globalStyle??"",this.input=o.input??{},this.receive=o.receive??{},this.bubble=o.bubble??{},this.response=o.response??{},this.alter=o.alter??{},this.on={stackEnter:o.on?.stackEnter??defaultOnStackEnter};for(let name in o.views??{}){let v=o.views[name],{view,style}=isString(v)?{view:v}:v;this.views[name]=new View(name,view,style)}this._rawDynamic=o.dynamic??{},this.dynamic={},this.scope=null,this.extra={};for(let key of Object.keys(o))if(!KNOWN_SPEC_KEYS.has(key))this.extra[key]=o[key]}compile(ParseContext2){for(let name in this.views)this.views[name].compile(new ParseContext2,this.scope,this.id);for(let key in this._rawDynamic){let dinfo=this._rawDynamic[key];if(isString(dinfo)){let val=vp.parseField(dinfo,this.views.main.ctx);this.dynamic[key]=new Dynamic(key,val,Symbol(key))}else if(isString(dinfo?.default)&&isString(dinfo?.for)){let val=vp.parseField(dinfo.default,this.views.main.ctx),[compName,dynName]=dinfo.for.split(".");if(isString(compName)&&isString(dynName))this.dynamic[key]=new DynamicAlias(key,val,compName,dynName)}}}make(args,opts){return this.Class.make(args,opts??{scope:this.scope})}getView(name){return this.views[name]??this.views.main}getEventForId(id,name="main"){return this.getView(name).ctx.getEventForId(id)}getNodeForId(id,name="main"){return this.getView(name).ctx.getNodeForId(id)}compileStyle(){let{id,commonStyle,globalStyle,views}=this,styles2=commonStyle?[`[data-cid="${id}"]{${commonStyle}}`]:[];if(globalStyle!=="")styles2.push(globalStyle);for(let name in views){let{style}=views[name];if(style!=="")styles2.push(`[data-cid="${id}"][data-vid="${name}"]{${style}}`)}return styles2.join(`
|
|
4
|
-
`)}}function defaultOnStackEnter(){return null}var STOP=Symbol("STOP"),NEXT=Symbol("NEXT");function lookup(chain,name,dv=null){let n=chain;while(n!==null){let r=n[0].lookup(name);if(r===STOP)return dv;if(r!==NEXT)return r;n=n[1]}return dv}class BindFrame{constructor(it,binds,isFrame){this.it=it,this.binds=binds,this.isFrame=isFrame}lookup(name){let v=this.binds[name];return v===void 0?this.isFrame?STOP:NEXT:v}}class ObjectFrame{constructor(binds){this.binds=binds}lookup(key){let v=this.binds[key];return v===void 0?NEXT:v}}function computeViewsId(views){let s="",n=views;while(n!==null)s+=n[0],n=n[1];return s==="main"?"":s}class Stack2{constructor(comps,it,binds,dynBinds,views,viewsId,ctx=null){this.comps=comps,this.it=it,this.binds=binds,this.dynBinds=dynBinds,this.views=views,this.viewsId=viewsId,this.ctx=ctx}_enrichOnEnter(){return this.withDynamicBinds(this.comps.getOnEnterFor(this.it).call(this.it))}static root(comps,it,ctx){let binds=[new BindFrame(it,{it},!0),null],dynBinds=[new ObjectFrame({}),null];return new Stack2(comps,it,binds,dynBinds,["main",null],"",ctx)._enrichOnEnter()}enter(it,bindings={},isFrame=!0){let{comps,binds,dynBinds,views,viewsId,ctx}=this,newBinds=[new BindFrame(it,bindings,isFrame),binds],stack=new Stack2(comps,it,newBinds,dynBinds,views,viewsId,ctx);return isFrame?stack._enrichOnEnter():stack}pushViewName(name){let{comps,it,binds,dynBinds,views,ctx}=this,newViews=[name,views];return new Stack2(comps,it,binds,dynBinds,newViews,computeViewsId(newViews),ctx)}withDynamicBinds(dynamics){if(dynamics==null||dynamics.length===0)return this;let dynObj={},comp=this.comps.getCompFor(this.it);for(let dynName of dynamics)comp.dynamic[dynName].evalAndBind(this,dynObj);let newDynBinds=[new ObjectFrame(dynObj),this.dynBinds],{comps,it,binds,views,viewsId,ctx}=this;return new Stack2(comps,it,binds,newDynBinds,views,viewsId,ctx)}_pushDynBindValuesToArray(arr,dyns){for(let k in dyns)arr.push(this._lookupDynamicWithDynVal(dyns[k]))}_lookupDynamicWithDynVal(d){return lookup(this.dynBinds,d.getSymbol(this))??d.val?.eval(this)??null}lookupDynamic(name){let d=this.comps.getCompFor(this.it)?.dynamic[name];return d?this._lookupDynamicWithDynVal(d):null}lookupBind(name){return lookup(this.binds,name)}lookupType(name){return this.comps.getCompFor(this.it).scope.lookupComponent(name)}lookupFieldRaw(name){return this.it[name]??null}lookupMethod(name){let fn=this.it[name];return fn instanceof Function?fn.call(this.it):null}lookupName(name){return this.ctx.lookupName(name)}getHandlerFor(name,key){return this.comps.getHandlerFor(this.it,name,key)}lookupRequest(name){return this.comps.getRequestFor(this.it,name)}lookupBestView(views,defaultViewName){let n=this.views;while(n!==null){let view=views[n[0]];if(view!==void 0)return view;n=n[1]}return views[defaultViewName]}}class State2{constructor(val){this.val=val,this.changeSubs=[]}onChange(cb){this.changeSubs.push(cb)}set(val,info){let old=this.val;this.val=val;for(let sub of this.changeSubs)sub({val,old,info,timestamp:Date.now()})}update(fn,info){return this.set(fn(this.val),info)}}class Transactor{constructor(comps,rootValue){this.comps=comps,this.transactions=[],this.state=new State2(rootValue),this.onTransactionPushed=()=>{}}pushTransaction(t){this.transactions.push(t),this.onTransactionPushed(t)}pushSend(path,name,args=[],opts={},parent=null){this.pushTransaction(new SendEvent(path,this,name,args,parent,opts))}pushBubble(path,name,args=[],opts={},parent=null,targetPath=null){let newOpts=opts.skipSelf?{...opts,skipSelf:!1}:opts;this.pushTransaction(new BubbleEvent(path,this,name,args,parent,newOpts,targetPath))}async pushRequest(path,name,args=[],opts={},parent=null){let curRoot=this.state.val,curLeaf=path.toTransactionPath().lookup(curRoot),handler=this.comps.getRequestFor(curLeaf,name)??mkReq404(name),resHandlerName=opts?.onResName??name,push=(specificName,baseName,singleArg,result,error)=>{let t=new ResponseEvent(path,this,specificName??baseName,specificName?[singleArg]:[result,error],parent);this.pushTransaction(t)};try{let result=await handler.fn.apply(null,args);push(opts?.onOkName,resHandlerName,result,result,null)}catch(error){push(opts?.onErrorName,resHandlerName,error,null,error)}}get hasPendingTransactions(){return this.transactions.length>0}transactNext(){if(this.hasPendingTransactions)this.transact(this.transactions.shift())}transact(transaction){let curState=this.state.val,newState=transaction.run(curState,this.comps);if(newState!==void 0)this.state.set(newState,{transaction}),transaction.afterTransaction();else console.warn("undefined new state",{curState,transaction})}transactInputNow(path,event,eventHandler,dragInfo){this.transact(new InputEvent(path,event,eventHandler,this,dragInfo))}}function mkReq404(name){return{fn:()=>{throw Error(`Request not found: ${name}`)}}}function nullHandler(){return this}class Transaction{constructor(path,transactor,parentTransaction=null){this.path=path,this.transactor=transactor,this.parentTransaction=parentTransaction,this._task=null}get task(){return this._task??=new Task,this._task}getCompletionPromise(){return this.task.promise}setParent(parentTransaction){this.parentTransaction=parentTransaction,parentTransaction.task.addDep(this.task)}run(rootValue,comps){return this.updateRootValue(rootValue,comps)}afterTransaction(){}buildRootStack(root,comps){return Stack2.root(comps,root)}buildStack(root,comps){return this.path.toTransactionPath().buildStack(this.buildRootStack(root,comps))}callHandler(root,instance,comps){let[handler,args]=this.getHandlerAndArgs(root,instance,comps);return handler.apply(instance,args)}getHandlerAndArgs(_root,_instance,_comps){return null}updateRootValue(curRoot,comps){let txnPath=this.path.toTransactionPath(),curLeaf=txnPath.lookup(curRoot),newLeaf=this.callHandler(curRoot,curLeaf,comps);return this._task?.complete?.({value:newLeaf,old:curLeaf}),curLeaf!==newLeaf?txnPath.setValue(curRoot,newLeaf):curRoot}lookupName(_name){return null}}var isMac2=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac"),toNullIfNaN=(v)=>Number.isNaN(v)?null:v;function getValue(e){return e.target.type==="checkbox"?e.target.checked:(e instanceof CustomEvent?e.detail:e.target.value)??null}class InputEvent extends Transaction{constructor(path,e,handler,transactor,dragInfo){super(path,transactor);this.e=e,this.handler=handler,this.dragInfo=dragInfo,this._dispatchPath=null}get dispatchPath(){return this._dispatchPath??=this.path.compact(),this._dispatchPath}buildRootStack(root,comps){return Stack2.root(comps,root,this)}getHandlerAndArgs(root,_instance,comps){let stack=this.buildStack(root,comps),[handler,args]=this.handler.getHandlerAndArgs(stack,this),path=this.dispatchPath,dispatcher;for(let i=0;i<args.length;i++)if(args[i]?.toHandlerArg)dispatcher??=new Dispatcher(path,this.transactor,this),args[i]=args[i].toHandlerArg(dispatcher);return args.push(new EventContext(path,this.transactor,this)),[handler,args]}lookupName(name){let{e}=this;switch(name){case"value":return getValue(e);case"valueAsInt":return toNullIfNaN(parseInt(getValue(e),10));case"valueAsFloat":return toNullIfNaN(parseFloat(getValue(e)));case"target":return e.target;case"event":return e;case"isAlt":return e.altKey;case"isShift":return e.shiftKey;case"isCtrl":case"isCmd":return isMac2&&e.metaKey||e.ctrlKey;case"key":return e.key;case"keyCode":return e.keyCode;case"isUpKey":return e.key==="ArrowUp";case"isDownKey":return e.key==="ArrowDown";case"isSend":return e.key==="Enter";case"isCancel":return e.key==="Escape";case"isTabKey":return e.key==="Tab";case"ctx":return new EventContext(this.dispatchPath,this.transactor,this);case"dragInfo":return this.dragInfo}return null}}class NameArgsTransaction extends Transaction{constructor(path,transactor,name,args,parentTransaction,opts={}){super(path,transactor,parentTransaction);this.name=name,this.args=args,this.opts=opts,this.targetPath=path}handlerProp=null;getHandlerForName(comp){let handlers=comp?.[this.handlerProp];return handlers?.[this.name]??handlers?.$unknown??nullHandler}getHandlerAndArgs(_root,instance,comps){return[this.getHandlerForName(comps.getCompFor(instance)),[...this.args,new EventContext(this.path,this.transactor,this)]]}}class ResponseEvent extends NameArgsTransaction{handlerProp="response"}class SendEvent extends NameArgsTransaction{handlerProp="receive";run(rootVal,comps){return this.opts.skipSelf?rootVal:this.updateRootValue(rootVal,comps)}afterTransaction(){let{path,name,args,opts,targetPath}=this;if(opts.bubbles&&path.steps.length>0)this.transactor.pushBubble(path.popStep(),name,args,opts,this,targetPath)}}class BubbleEvent extends SendEvent{handlerProp="bubble";constructor(path,transactor,name,args,parent,opts,targetPath){super(path,transactor,name,args,parent,opts);this.targetPath=targetPath??path}stopPropagation(){this.opts.bubbles=!1}}class Task{constructor(){this.deps=[],this.val=this.resolve=this.reject=null,this.promise=new Promise((res,rej)=>{this.resolve=res,this.reject=rej}),this.isCompleted=!1}addDep(task){console.assert(!this.isCompleted,"addDep for completed task",this,task),this.deps.push(task),task.promise.then((_)=>this._check())}complete(val){this.val=val,this._check()}_check(){if(this.deps.every((task)=>task.isCompleted))this.isCompleted=!0,this.resolve(this)}}class Dispatcher{constructor(path,transactor,parentTransaction){this.path=path,this.transactor=transactor,this.parent=parentTransaction}get at(){return new PathChanges(this)}send(name,args,opts){return this.sendAtPath(this.path,name,args,opts)}bubble(name,args,opts){return this.send(name,args,{skipSelf:!0,bubbles:!0,...opts})}sendAtPath(path,name,args,opts){return this.transactor.pushSend(path,name,args,opts,this.parent)}request(name,args,opts){return this.requestAtPath(this.path,name,args,opts)}requestAtPath(path,name,args,opts){return this.transactor.pushRequest(path,name,args,opts,this.parent)}lookupTypeFor(name,inst){return this.transactor.comps.getCompFor(inst).scope.lookupComponent(name)}}class EventContext extends Dispatcher{get name(){return this.parent?.name??null}get targetPath(){return this.parent.targetPath}stopPropagation(){return this.parent.stopPropagation()}}class PathChanges extends PathBuilder{constructor(dispatcher){super();this.dispatcher=dispatcher}send(name,args,opts){return this.dispatcher.sendAtPath(this.buildPath(),name,args,opts)}bubble(name,args,opts){return this.send(name,args,{skipSelf:!0,bubbles:!0,...opts})}buildPath(){return this.dispatcher.path.concat(this.pathChanges)}}var _evs="dragstart dragover dragend touchstart touchmove touchend touchcancel".split(" ");class App{constructor(rootNode,comps,renderer,ParseContext2){this.rootNode=rootNode,this.comps=comps,this.compStack=new ComponentStack(comps),this.transactor=new Transactor(comps,null),this.ParseContext=ParseContext2,this.renderer=renderer,this.maxEventNodeDepth=1/0,this._transactNextBatchId=this._evictCacheId=null,this._eventNames=new Set(_evs),this.dragInfo=this.curDragOver=null,this._touch=null,this.transactor.onTransactionPushed=(_transaction)=>{if(this._transactNextBatchId===null)this._scheduleNextTransactionBatchExecution()},this._compiled=!1,this._renderOpts={document:rootNode.ownerDocument},this._renderState=null}get state(){return this.transactor.state}handleEvent(e){let{type:type3}=e;if(type3[0]==="t"&&type3.startsWith("touch")){this._handleTouchEvent(e);return}this._dispatchEvent(e)}_dispatchEvent(e){let{type:type3}=e,isDrag=type3==="dragover"||type3==="dragstart"||type3==="dragend"||type3==="drop",{rootNode:root,maxEventNodeDepth:maxDepth,comps,transactor}=this,[path,handlers]=Path.fromEvent(e,root,maxDepth,comps,!isDrag);if(isDrag)this._handleDragEvent(e,type3,path);if(path!==null&&handlers!==null)for(let handler of handlers)transactor.transactInputNow(path,e,handler,this.dragInfo)}_handleTouchEvent(e){let{type:type3}=e;if(type3==="touchstart"){if(this._touch!==null||e.touches.length!==1)return;let t=e.touches[0],draggable=t.target?.closest?.('[draggable="true"]');if(!draggable)return;this._touch=makeTouchInfo(t.identifier,t.clientX,t.clientY,draggable,!1);return}if(this._touch===null)return;let touch=findTouch(e,this._touch.id);if(touch===null)return;let{rootNode,_touch}=this,{clientX,clientY}=touch,fire=(type4,target)=>{let e2={type:type4,target,clientX,clientY,preventDefault:NOOP};this._dispatchEvent(e2)};if(type3==="touchmove"){if(!_touch.active){let dx=clientX-_touch.startX,dy=clientY-_touch.startY;if(dx*dx+dy*dy<100)return;_touch.active=!0,e.preventDefault(),fire("dragstart",_touch.target)}else e.preventDefault(),fire("dragover",hitTest(rootNode,clientX,clientY));return}if(type3==="touchend"||type3==="touchcancel"){if(_touch.active){if(type3==="touchend")fire("drop",hitTest(rootNode,clientX,clientY));fire("dragend",_touch.target)}this._touch=null}}_handleDragEvent(e,type3,path){if(type3==="dragover"){let dropTarget=getClosestDropTarget(e.target,this.rootNode,1/0);if(dropTarget!==null)e.preventDefault(),this._cleanDragOverAttrs(),this.curDragOver=dropTarget,dropTarget.dataset.draggingover=this.dragInfo?.type??"_external"}else if(type3==="dragstart"){e.target.dataset.dragging=1;let rootValue=this.state.val,txnPath=path.compact().toTransactionPath(),value=txnPath.lookup(rootValue),dragType=e.target.dataset.dragtype??"?",stack=path.toTransactionPath().buildStack(this.makeStack(rootValue));this.dragInfo=new DragInfo(txnPath,stack,e,value,dragType,e.target)}else if(type3==="drop")e.preventDefault(),this._cleanDragOverAttrs();else{if(this.dragInfo!==null)delete this.dragInfo.node.dataset.dragging,this.dragInfo=null;this._cleanDragOverAttrs()}}makeStack(rootValue){return Stack2.root(this.comps,rootValue)}_cleanDragOverAttrs(){if(this.curDragOver!==null)delete this.curDragOver.dataset.draggingover,this.curDragOver=null}render(){let root=this.state.val,stack=this.makeStack(root),{renderer,rootNode,_renderOpts,_renderState}=this,newState=render(renderer.renderRoot(stack,root),rootNode,_renderOpts,_renderState);return this._renderState=newState,newState.dom}onChange(callback){this.transactor.state.onChange(callback)}compile(){for(let Comp of this.comps.byId.values()){Comp.compile(this.ParseContext);for(let key in Comp.views)for(let name of Comp.views[key].ctx.genEventNames())this._eventNames.add(name)}this._compiled=!0}subscribeToEvents(eventNames){for(let name of eventNames)this.rootNode.addEventListener(name,this,listenerOpts(name))}recompileStyles(opts){injectCss("tutuca-app",this.comps.compileStyles(),opts?.head??document.head)}start(opts){if(!this._compiled)this.compile();if(this.subscribeToEvents(this._eventNames),this.onChange((info)=>{if(info.val!==info.old)this.render()}),this.recompileStyles(opts),opts?.noCache)this.renderer.setNullCache();else this.startCacheEvictionInterval();this.render()}stop(){this.stopCacheEvictionInterval();for(let name of this._eventNames)this.rootNode.removeEventListener(name,this,listenerOpts(name))}sendAtRoot(name,args,opts){this.transactor.pushSend(new Path([]),name,args,opts)}registerComponents(comps,opts){let scope=this.compStack.enter();return scope.registerComponents(comps,opts),scope}_transactNextBatch(maxRunTimeMs=10){this._transactNextBatchId=null;let startTs=Date.now(),t=this.transactor;while(t.hasPendingTransactions&&Date.now()-startTs<maxRunTimeMs)t.transactNext();if(t.hasPendingTransactions)this._scheduleNextTransactionBatchExecution()}_scheduleNextTransactionBatchExecution(){this._transactNextBatchId=setTimeout(()=>this._transactNextBatch(),0)}startCacheEvictionInterval(intervalMs=30000){this._evictCacheId=setInterval(()=>this.renderer.cache.evict(),intervalMs)}stopCacheEvictionInterval(){clearInterval(this._evictCacheId),this._evictCacheId=null}}function injectCss(nodeId,style,styleTarget=document.head){let styleNode=document.createElement("style"),currentNodeWithId=styleTarget.querySelector(`#${nodeId}`);if(currentNodeWithId)styleTarget.removeChild(currentNodeWithId);styleNode.id=nodeId,styleNode.innerHTML=style,styleTarget.appendChild(styleNode)}var NOOP=()=>{};function findTouch(e,id){for(let t of e.changedTouches)if(t.identifier===id)return t;for(let t of e.touches)if(t.identifier===id)return t;return null}var listenerOpts=(name)=>name==="touchmove"?{passive:!1}:void 0;function makeTouchInfo(id,startX,startY,target,active){return{id,startX,startY,target,active}}function hitTest(rootNode,x,y){let el=rootNode.getRootNode().elementFromPoint?.(x,y)??null;while(el?.shadowRoot){let next=el.shadowRoot.elementFromPoint(x,y);if(next===null||next===el)break;el=next}return el??rootNode}function getClosestDropTarget(target,rootNode,count){let node=target;while(count-- >0&&node!==rootNode){if(node.dataset?.droptarget!==void 0)return node;node=node.parentNode}return null}class DragInfo{constructor(path,stack,e,val,type3,node){this.path=path,this.stack=stack,this.e=e,this.val=val,this.type=type3,this.node=node}lookupBind(name){return this.stack.lookupBind(name)}}var BAD_VALUE2=Symbol("BadValue"),nullCoercer=(v)=>v;class Field{constructor(type3,name,typeCheck,coercer,defaultValue=null){this.type=type3,this.name=name,this.typeCheck=typeCheck,this.coercer=coercer,this.checks=[],this.defaultValue=defaultValue}toDataDef(){let{type:type3,defaultValue:dv}=this;return{type:type3,defaultValue:dv?.toJS?dv.toJS():dv}}getFirstFailingCheck(v){if(!this.typeCheck.isValid(v))return this.typeCheck;for(let check of this.checks)if(!check.isValid(v))return check;return null}isValid(v){return this.getFirstFailingCheck(v)===null}addCheck(check){return this.checks.push(check),this}coerceOr(v,defaultValue=null){if(this.isValid(v))return v;let v1=this.coercer(v);return this.isValid(v1)?v1:defaultValue}coerceOrDefault(v){return this.coerceOr(v,this.defaultValue)}extendProtoForType(_proto,_uname){}extendProto(proto){let{name}=this,uname=name[0].toUpperCase()+name.slice(1),setName=`set${uname}`,that=this;proto[setName]=function(v){let v1=that.coerceOr(v,BAD_VALUE2);if(v1===BAD_VALUE2)return console.warn("invalid value",v),this;return this.set(name,v1)},proto[`update${uname}`]=function(fn){return this[setName](fn(this.get(name)))},proto[`reset${uname}`]=function(){return this.set(name,that.defaultValue)},this.extendProtoForType(proto,uname)}}class Check{isValid(_v){return!0}getMessage(_v){return"Invalid"}}class CheckTypeAny extends Check{}var CHECK_TYPE_ANY=new CheckTypeAny;class FnCheck extends Check{constructor(isValidFn,getMessageFn){super();this._isValid=isValidFn,this._getMessage=getMessageFn}isValid(v){return this._isValid(v)}getMessage(v){return this._getMessage(v)}}var CHECK_TYPE_INT=new FnCheck((v)=>Number.isInteger(v),()=>"Integer expected"),CHECK_TYPE_FLOAT=new FnCheck((v)=>Number.isFinite(v),()=>"Float expected"),CHECK_TYPE_BOOL=new FnCheck((v)=>typeof v==="boolean",()=>"Boolean expected"),CHECK_TYPE_STRING=new FnCheck((v)=>typeof v==="string",()=>"String expected"),CHECK_TYPE_LIST=new FnCheck((v)=>List.isList(v),()=>"List expected"),CHECK_TYPE_MAP=new FnCheck((v)=>Map2.isMap(v),()=>"Map expected"),CHECK_TYPE_OMAP=new FnCheck((v)=>OrderedMap.isOrderedMap(v),()=>"OrderedMap expected"),CHECK_TYPE_SET=new FnCheck((v)=>Set2.isSet(v),()=>"Set expected"),boolCoercer=(v)=>!!v;class FieldBool extends Field{constructor(name,defaultValue=!1){super("bool",name,CHECK_TYPE_BOOL,boolCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;proto[`toggle${uname}`]=function(){return this.set(name,!this.get(name,!1))},proto[`set${uname}`]=function(v){return this.set(name,!!v)}}}class FieldAny extends Field{constructor(name,defaultValue=null){super("any",name,CHECK_TYPE_ANY,nullCoercer,defaultValue)}toDataDef(){let{defaultValue:dv}=this;return{type:getTypeName(dv)??"any",defaultValue:dv?.toJS?dv.toJS():dv}}}var stringCoercer=(v)=>v?.toString?.()??"";class FieldString extends Field{constructor(name,defaultValue=""){super("text",name,CHECK_TYPE_STRING,stringCoercer,defaultValue)}extendProtoForType(proto,_uname){extendProtoSized(proto,this.name,"","length")}}var intCoercer=(v)=>Number.isFinite(v)?Math.trunc(v):null;class FieldInt extends Field{constructor(name,defaultValue=0){super("int",name,CHECK_TYPE_INT,intCoercer,defaultValue)}}var floatCoercer=(_)=>null;class FieldFloat extends Field{constructor(name,defaultValue=0){super("float",name,CHECK_TYPE_FLOAT,floatCoercer,defaultValue)}}var getTypeName=(v)=>v?.constructor?.getMetaClass?.()?.name;class CheckTypeName{constructor(typeName){this.typeName=typeName}isValid(v){return getTypeName(v)===this.typeName}getMessage(v){let got=getTypeName(v);return`Expected "${this.typeName}", got "${got}"`}}class FieldComp extends Field{constructor(type3,name,args){super(type3,name,new CheckTypeName(type3),nullCoercer,null);this.args=args}toDataDef(){return{component:this.typeName,args:this.args}}}var NONE2=Symbol("NONE");function extendProtoForKeyed(proto,name,uname){extendProtoSized(proto,name,EMPTY_LIST),proto[`setIn${uname}At`]=function(i,v){return this.set(name,this.get(name).set(i,v))},proto[`getIn${uname}At`]=function(i,dval){return this.get(name).get(i,dval)},proto[`updateIn${uname}At`]=function(i,fn){let col=this.get(name),v=col.get(i,NONE2);if(v!==NONE2)return this.set(name,col.set(i,fn(v)));return console.warn("key",i,"not found in",name,col),this},extendDeleteInAt(proto,name,`${uname}At`)}function extendDeleteInAt(proto,name,uname){proto[`deleteIn${uname}`]=function(v){return this.set(name,this.get(name).delete(v))},proto[`removeIn${uname}`]=proto[`deleteIn${uname}`]}var EMPTY_LIST=List(),listCoercer=(v)=>Array.isArray(v)?List(v):null;class FieldList extends Field{constructor(name,defaultValue=EMPTY_LIST){super("list",name,CHECK_TYPE_LIST,listCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;extendProtoForKeyed(proto,name,uname),proto[`pushIn${uname}`]=function(v){return this.set(name,this.get(name).push(v))},proto[`insertIn${uname}At`]=function(i,v){return this.set(name,this.get(name).insert(i,v))}}}var imapCoercer=(v)=>Map2(v);class FieldMap extends Field{constructor(name,defaultValue=Map2()){super("map",name,CHECK_TYPE_MAP,imapCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname)}}var omapCoercer=(v)=>OrderedMap(v);class FieldOMap extends Field{constructor(name,defaultValue=OrderedMap()){super("omap",name,CHECK_TYPE_OMAP,omapCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname)}}function extendProtoSized(proto,name,defaultEmpty,propName="size"){proto[`${name}Len`]=function(){return this.get(name,defaultEmpty)[propName]}}var EMPTY_SET3=Set2(),isetCoercer=(v)=>Array.isArray(v)?Set2(v):v instanceof Set?Set2(v):null;class FieldSet extends Field{constructor(name,defaultValue=EMPTY_SET3){super("set",name,CHECK_TYPE_SET,isetCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;extendProtoSized(proto,name,EMPTY_SET3),proto[`addIn${uname}`]=function(v){return this.set(name,this.get(name).add(v))},extendDeleteInAt(proto,name,uname),proto[`hasIn${uname}`]=function(v){return this.get(name).has(v)},proto[`toggleIn${uname}`]=function(v){let current=this.get(name);return this.set(name,current.has(v)?current.delete(v):current.add(v))}}}function mkCompField(field,scope,args){let Comp=scope.lookupComponent(field.type);return console.assert(Comp!==null,"component not found",{field}),Comp?.make({...field.args,...args},{scope})??null}class ClassBuilder{constructor(name){let fields={},compFields=new Set;this.name=name,this.fields=fields,this.compFields=compFields,this._methods={},this._statics={make:function(inArgs={},opts={}){let args={};for(let key in inArgs){let field=fields[key];if(compFields.has(key))args[key]=mkCompField(field,opts.scope,inArgs[key]);else if(field===void 0)console.warn("extra argument to constructor:",name,key,inArgs);else args[key]=field.coerceOrDefault(inArgs[key])}for(let key of compFields)if(args[key]===void 0)args[key]=mkCompField(fields[key],opts.scope,inArgs[key]);return this(args)}}}build(){let fieldVals={},proto={},{name,_methods,fields}=this;for(let fieldName in fields){let field=fields[fieldName];fieldVals[fieldName]=field.defaultValue,field.extendProto(proto)}let Class={[name]:Record(fieldVals,name)}[name];Object.assign(Class.prototype,proto,_methods);let metaClass={fields,name,methods:_methods};return Object.assign(Class,this._statics,{getMetaClass:()=>metaClass}),Class}methods(proto){for(let k in proto)this._methods[k]=proto[k]}statics(proto){for(let k in proto)this._statics[k]=proto[k]}addField(name,dval,FieldCls){let field=new FieldCls(name,dval);return this.fields[name]=field,field}addCompField(name,type3,args){let field=new FieldComp(type3,name,args);return this.compFields.add(name),this.fields[name]=field,field}}var FIELD_CLASS=Symbol.for("tutuca.fieldClass"),fieldsByTypeName={text:FieldString,int:FieldInt,float:FieldFloat,bool:FieldBool,list:FieldList,map:FieldMap,omap:FieldOMap,set:FieldSet,any:FieldAny};function classFromData(name,{fields={},methods,statics}){let b=new ClassBuilder(name);for(let field in fields){let value=fields[field],type3=typeof value;if(type3==="string")b.addField(field,value,FieldString);else if(type3==="number")b.addField(field,value,FieldFloat);else if(type3==="boolean")b.addField(field,value,FieldBool);else if(List.isList(value)||Array.isArray(value))b.addField(field,List(value),FieldList);else if(Set2.isSet(value)||value instanceof Set)b.addField(field,Set2(value),FieldSet);else if(OrderedMap.isOrderedMap(value))b.addField(field,value,FieldOMap);else if(value?.type&&value?.defaultValue!==void 0){let Field2=fieldsByTypeName[value.type]??FieldAny;b.addField(field,new Field2().coerceOr(value.defaultValue),Field2)}else if(value?.component&&value?.args!==void 0)b.addCompField(field,value.component,value.args);else if(Map2.isMap(value)||value?.constructor===Object)b.addField(field,Map2(value),FieldMap);else{let Field2=value?.[FIELD_CLASS]??FieldAny;b.addField(field,value,Field2)}}if(methods)b.methods(methods);if(statics)b.statics(statics);return b.build()}var component=(opts)=>new Component(classFromData(opts.name,opts),opts);class NullDomCache{get(_keys,_cacheKey){}set(_keys,_cacheKey,_v){}evict(){return{hit:0,miss:0,badKey:0}}}class WeakMapDomCache{constructor(){this.hit=this.miss=this.badKey=0,this.keysByLen=new Map}_returnValue(r){if(r===void 0)this.miss+=1;else this.hit+=1;return r}get(keys,cacheKey){let len=keys.length,cur=this.keysByLen.get(len);if(!cur)return this._returnValue(void 0);for(let i=0;i<len-1;i++)if(cur=cur.get(keys[i]),!cur)return this._returnValue(void 0);return this._returnValue(cur.get(keys[len-1])?.[cacheKey])}set(keys,cacheKey,v){let len=keys.length,cur=this.keysByLen.get(len);if(!cur)cur=new WeakMap,this.keysByLen.set(len,cur);for(let i=0;i<len-1;i++){let key=keys[i],next=cur.get(key);if(!next){if(typeof key!=="object"){this.badKey+=1;return}next=new WeakMap,cur.set(key,next)}cur=next}let lastKey=keys[len-1],leaf=cur.get(lastKey);if(leaf)leaf[cacheKey]=v;else if(typeof lastKey==="object")cur.set(lastKey,{[cacheKey]:v});else this.badKey+=1}evict(){let{hit,miss,badKey}=this;return this.hit=this.miss=this.badKey=0,this.keysByLen=new Map,{hit,miss,badKey}}}var DATASET_ATTRS=["nid","cid","eid","vid","si","sk"];class Renderer{constructor(comps){this.comps=comps,this.cache=new WeakMapDomCache,this.renderTag=h}renderFragment(childs){return new VFragment(childs)}renderComment(text){return new VComment(text)}setNullCache(){this.cache=new NullDomCache}renderToDOM(stack,val){let rootNode=document.createElement("div"),rOpts={document};return render(h("DIV",null,[this.renderRoot(stack,val)]),rootNode,rOpts),rootNode.childNodes[0]}renderToString(stack,val,cleanAttrs=!0){let dom=this.renderToDOM(stack,val);if(cleanAttrs){let nodes=dom.querySelectorAll("[data-nid],[data-cid],[data-eid]");for(let{dataset}of nodes)for(let name of DATASET_ATTRS)delete dataset[name]}return dom.innerHTML}renderRoot(stack,val,viewName=null){let comp=this.comps.getCompFor(val);if(comp===null)return null;return this._rValComp(stack,val,comp,comp.getView(viewName).anode,"ROOT",viewName)}renderIt(stack,node,key,viewName){let comp=this.comps.getCompFor(stack.it);return comp?this._rValComp(stack,stack.it,comp,node,key,viewName):null}_rValComp(stack,val,comp,node,key,viewName){let cacheKey=`${viewName??stack.viewsId??""}-${key}`,cachePath=[node,val];stack._pushDynBindValuesToArray(cachePath,comp.dynamic);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)return cachedNode;let view=viewName?comp.getView(viewName):stack.lookupBestView(comp.views,"main"),meta=this._renderMetadata({$:"Comp",nid:node?.nodeId??null}),dom=new VFragment([meta,this.renderView(view,stack)]);return this.cache.set(cachePath,cacheKey,dom),dom}pushEachEntry(r,nid,attrName,key,dom){r.push(this._renderMetadata({$:"Each",nid,[attrName]:key}),dom)}renderEach(stack,iterInfo,node,viewName){let{seq,filter,loopWith}=iterInfo.eval(stack),r=[],iterData=loopWith.call(stack.it,seq);return getSeqInfo(seq)(seq,(key,value,attrName)=>{if(filter.call(stack.it,key,value,iterData)){let dom=this.renderIt(stack.enter(value,{key},!0),node,key,viewName);this.pushEachEntry(r,node.nodeId,attrName,key,dom)}}),r}renderEachWhen(stack,iterInfo,view,nid){let{seq,filter,loopWith,enricher}=iterInfo.eval(stack),r=[],it=stack.it,iterData=loopWith.call(it,seq);return getSeqInfo(seq)(seq,(key,value,attrName)=>{if(filter.call(it,key,value,iterData)){let cachePath=enricher?[view,it,value]:[view,value],binds={key,value},cacheKey=`${nid}-${key}`;if(enricher)enricher.call(it,binds,key,value,iterData);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)this.pushEachEntry(r,nid,attrName,key,cachedNode);else{let dom=this.renderView(view,stack.enter(value,binds,!1));this.pushEachEntry(r,nid,attrName,key,dom),this.cache.set(cachePath,cacheKey,dom)}}}),r}renderView(view,stack){let n=stack.binds[1];while(n!==null){let b=n[0];if(b.isFrame){if(stack.it!==b.it)break;return console.error("recursion detected",stack.it,b.it),new VComment("RECURSION AVOIDED")}n=n[1]}return view.render(stack,this)}_renderMetadata(info){return new VComment(`§${JSON.stringify(info)}§`)}}var getSeqInfo=(seq)=>isIndexed(seq)?imIndexedIter:isKeyed(seq)?imKeyedIter:seq?.[SEQ_INFO]??unkIter,imIndexedIter=(seq,visit)=>{let i=0;for(let v of seq)visit(i++,v,"si")},imKeyedIter=(seq,visit)=>{for(let[k,v]of seq.toSeq().entries())visit(k,v,"sk")},unkIter=()=>{},SEQ_INFO=Symbol.for("tutuca.seqInfo");class KList{constructor(items=Map2(),order=List()){this.items=items,this.order=order,this.$=0}_clonish(items,order){return new KList(items,order,this.$)}toJS(){return this.order.toArray().map((k)=>this.items.get(k))}set(k,v){let newOrder=this.items.has(k)?this.order:this.order.push(k);return this._clonish(this.items.set(k,v),newOrder,this.$)}get(k,dval=null){return this.items.get(k,dval)}_nextFreeKey(){let cur=this.$;while(!0){let key=`§${cur}§`;if(!this.items.has(key))return[key,cur];cur+=1}}push(v){let[key,next$]=this._nextFreeKey(),newKList=this.set(key,v);return newKList.$=next$,newKList}get size(){return this.items.size}delete(k){if(this.items.has(k)){let newOrder=this.order.delete(this.order.indexOf(k));return this._clonish(this.items.delete(k),newOrder)}return this}moveKeyBeforeKey(k1,k2){let{order}=this;return this.moveKeyIndexToIndex(order.indexOf(k1),order.indexOf(k2),0)}moveKeyAfterKey(k1,k2){let{order}=this;return this.moveKeyIndexToIndex(order.indexOf(k1),order.indexOf(k2),1)}moveKeyIndexToIndex(source,target,offset){if(source===-1||target===-1||source===target)return this;let{order}=this,newPos=target+offset,oldPos=newPos<source?source+1:source,newOrder=order.insert(newPos,order.get(source)).delete(oldPos);return this._clonish(this.items,newOrder)}}var klistCoercer=(_)=>null;class CheckTypeKList{isValid(v){return v instanceof KList}getMessage(_v){return"KList expected"}}var CHECK_TYPE_KLIST=new CheckTypeKList;class FieldKList extends Field{constructor(name,defaultValue=new KList){super("KList",name,CHECK_TYPE_KLIST,klistCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname);let{name}=this;extendProtoForKeyed(proto,name,uname),proto[`pushIn${uname}`]=function(v){return this.set(name,this.get(name).push(v))}}}KList.prototype[FIELD_CLASS]=FieldKList;KList.prototype[SEQ_INFO]=(seq,visit)=>{for(let k of seq.order)visit(k,seq.items.get(k),"data-sk")};var{raw:css,raw:html}=String,macro=(defaults,rawView)=>new Macro(defaults,rawView);function tutuca(nodeOrSelector){let rootNode=typeof nodeOrSelector==="string"?document.querySelector(nodeOrSelector):nodeOrSelector,comps=new Components,renderer=new Renderer(comps);return new App(rootNode,comps,renderer,ParseContext)}async function compileClassesToStyle(app,compileClasses,styleId="margaui-css"){let t1=performance.now(),css2=await compileClassesToStyleText(app,compileClasses),t2=performance.now();return injectCss(styleId,css2),t2-t1}async function compileClassesToStyleText(app,compileClasses,Ctx=ParseCtxClassSetCollector){app.ParseContext=Ctx,app.compile();let classes=new Set;for(let Comp of app.comps.byId.values())for(let key in Comp.views){let view=Comp.views[key];for(let name of view.ctx.classes)classes.add(name)}return await compileClasses(Array.from(classes))}function getSignature(name,fn){let m=fn.toString().match(/^(?:\w+|function\s*\w*)\s*\(([^)]*)\)/),params=m?m[1].trim():"";return`${name}(${params})`}function getFieldMethods(field){let{name,type:type3}=field,uname=name[0].toUpperCase()+name.slice(1),methods=[{name:`set${uname}`,sig:`set${uname}(v)`,desc:"Set value"},{name:`update${uname}`,sig:`update${uname}(fn)`,desc:"Update value with function"},{name:`reset${uname}`,sig:`reset${uname}()`,desc:"Reset to default value"}];switch(type3){case"bool":methods[0].desc="Set value (coerces to boolean)",methods.push({name:`toggle${uname}`,sig:`toggle${uname}()`,desc:"Toggle boolean value"});break;case"int":case"float":case"any":break;case"text":methods.push({name:`${name}Len`,sig:`${name}Len()`,desc:"Get string length"});break;case"list":methods.push({name:`${name}Len`,sig:`${name}Len()`,desc:"Get list size"},{name:`setIn${uname}At`,sig:`setIn${uname}At(i, v)`,desc:"Set item at index"},{name:`getIn${uname}At`,sig:`getIn${uname}At(i, defaultValue)`,desc:"Get item at index"},{name:`updateIn${uname}At`,sig:`updateIn${uname}At(i, fn)`,desc:"Update item at index with function"},{name:`deleteIn${uname}At`,sig:`deleteIn${uname}At(i)`,desc:"Delete item at index"},{name:`removeIn${uname}At`,sig:`removeIn${uname}At(i)`,desc:"Delete item at index (alias)"},{name:`pushIn${uname}`,sig:`pushIn${uname}(v)`,desc:"Push item to end"},{name:`insertIn${uname}At`,sig:`insertIn${uname}At(i, v)`,desc:"Insert item at index"});break;case"map":case"omap":{let label=type3==="omap"?"ordered map":"map";methods.push({name:`${name}Len`,sig:`${name}Len()`,desc:`Get ${label} size`},{name:`setIn${uname}At`,sig:`setIn${uname}At(key, v)`,desc:"Set value at key"},{name:`getIn${uname}At`,sig:`getIn${uname}At(key, defaultValue)`,desc:"Get value at key"},{name:`updateIn${uname}At`,sig:`updateIn${uname}At(key, fn)`,desc:"Update value at key with function"},{name:`deleteIn${uname}At`,sig:`deleteIn${uname}At(key)`,desc:"Delete entry at key"},{name:`removeIn${uname}At`,sig:`removeIn${uname}At(key)`,desc:"Delete entry at key (alias)"});break}case"set":methods.push({name:`${name}Len`,sig:`${name}Len()`,desc:"Get set size"},{name:`addIn${uname}`,sig:`addIn${uname}(v)`,desc:"Add value to set"},{name:`deleteIn${uname}`,sig:`deleteIn${uname}(v)`,desc:"Remove value from set"},{name:`removeIn${uname}`,sig:`removeIn${uname}(v)`,desc:"Remove value from set (alias)"},{name:`hasIn${uname}`,sig:`hasIn${uname}(v)`,desc:"Check if value is in set"},{name:`toggleIn${uname}`,sig:`toggleIn${uname}(v)`,desc:"Toggle value in set"});break;default:break}return methods}function serializeDefault(v){if(v===null||v===void 0)return v;if(v?.toJS)return v.toJS();return v}function getComponentDoc(comp){let meta=comp.Class.getMetaClass(),{fields,name,methods}=meta,userMethods=Object.keys(methods).map((k)=>({name:k,sig:getSignature(k,methods[k])})),inputHandlers=Object.keys(comp.input).map((k)=>({name:k,sig:getSignature(k,comp.input[k])})),fieldDocs=[];for(let fieldName in fields){let field=fields[fieldName];fieldDocs.push({name:fieldName,type:field.type,default:serializeDefault(field.defaultValue),methods:getFieldMethods(field)})}return{name,methods:userMethods,input:inputHandlers,fields:fieldDocs}}function getComponentsDocs(components){return components.map((comp)=>getComponentDoc(comp))}function docComponents(normalized,{name=null}={}){let comps=normalized.components,picked=name===null?comps:comps.filter((c)=>c.name===name);return new ComponentDocs({items:getComponentsDocs(picked)})}var filterAlwaysTrue2=()=>!0,nullLoopWith2=(seq)=>({seq}),plainArrayIter=(seq,visit)=>{for(let i=0;i<seq.length;i++)visit(i,seq[i])},plainMapIter=(seq,visit)=>{for(let[k,v]of seq.entries())visit(k,v)};function pickIter(seq){if(Array.isArray(seq))return plainArrayIter;if(seq instanceof Map)return plainMapIter;return getSeqInfo(seq)}function resolveAlter(Comp,name){if(name==null)return null;let fn=Comp.alter?.[name];if(typeof fn!=="function")throw Error(`alter handler '${name}' not found on component '${Comp.name}'`);return fn}function collectIterBindings(Comp,compInstance,seq,opts={}){let whenFn=resolveAlter(Comp,opts.when)??filterAlwaysTrue2,loopWithFn=resolveAlter(Comp,opts.loopWith)??nullLoopWith2,enrichFn=resolveAlter(Comp,opts.enrichWith),it=compInstance,iterData=loopWithFn.call(it,seq),out=[];return pickIter(seq)(seq,(key,value)=>{if(!whenFn.call(it,key,value,iterData))return;let binds={key,value};if(enrichFn)enrichFn.call(it,binds,key,value,iterData);out.push(binds)}),out}async function test3(opts={}){let report=await runTests({expect,...opts});return reportTestReportToConsole(report),report}function check(app){let counts={error:0,warn:0,hint:0};for(let Comp of app.comps.byId.values()){let shadowViews={};for(let name in Comp.views){let rawView=Comp.views[name].rawView,ctx=new LintParseContext;ANode.parse(rawView,ctx),ctx.compile(Comp.scope),shadowViews[name]={name,ctx,rawView}}let shadowComp=Object.create(Comp);shadowComp.views=shadowViews;let{reports}=checkComponent(shadowComp);if(reports.length===0)continue;console.group(Comp.name);for(let r of reports){counts[r.level]++;let tail=suggestionToMessage(r.suggestion),suffix=tail?` — ${tail}`:"",line=`[${r.level}] ${lintIdToMessage(r.id,r.info)}${suffix}`;if(r.level==="error")console.error(line);else if(r.level==="warn")console.warn(line);else console.log(line)}console.groupEnd()}let total=counts.error+counts.warn+counts.hint;return console.log(total===0?"check: no issues":`check: ${counts.error} error, ${counts.warn} warn, ${counts.hint} hint`),counts}class LintClassCollectorCtx extends ParseCtxClassSetCollector{constructor(...args){super(...args);this.attrs=[],this.parseIssues=[]}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events:events2,macroNodes}=this,v=new LintClassCollectorCtx(document2,Text,Comment,nodes,events2,macroNodes,{macroName,macroVars,macroSlots},this);return v.classes=this.classes,v.attrs=this.attrs,v.parseIssues=this.parseIssues,v}onAttributes(attrs,wrapperAttrs,textChild,isMacroCall=!1,tag=null){super.onAttributes(attrs,wrapperAttrs,textChild,isMacroCall,tag),this.attrs.push({attrs,wrapperAttrs,textChild,isMacroCall,tag})}onParseIssue(kind,info){let tag=this.currentTag;this.parseIssues.push({kind,info:tag&&info.tag===void 0?{...info,tag}:info})}}export{version,updateIn$1 as updateIn,update$1 as update,tutuca,test3 as test,suggestionToMessage,setIn$1 as setIn,set2 as set,runTests,reportTestReportToConsole,removeIn,remove,mergeWith$1 as mergeWith,mergeDeepWith$1 as mergeDeepWith,mergeDeep$1 as mergeDeep,merge$1 as merge,makeCollector,macro,lintIdToMessage,isValueObject,isStack,isSet,isSeq,isRecord,isPlainObject,isOrderedSet,isOrderedMap,isOrdered,isOrderedMap as isOMap,isMap,isList,isKeyed,isIndexed,isImmutable,isMap as isIMap,isCollection,isAssociative,is,injectCss,html,hash,hasIn$1 as hasIn,has,getIn$1 as getIn,getComponentsDocs,get2 as get,fromJS,docComponents,css,component,compileClassesToStyleText,compileClassesToStyle,collectIterBindings,checkComponent,check,UNSUPPORTED_EXPR_SYNTAX,UNKNOWN_X_OP,UNKNOWN_X_ATTR,UNKNOWN_REQUEST_NAME,UNKNOWN_MACRO_ARG,UNKNOWN_HANDLER_ARG_NAME,UNKNOWN_EVENT_MODIFIER,UNKNOWN_DIRECTIVE,UNKNOWN_COMPONENT_SPEC_KEY,UNKNOWN_COMPONENT_NAME,TestResult,TestReport,TestIndex,Test,Stack,Set2 as Set,Seq,SEQ_INFO,Repeat,RenderedSection,RenderedExample,RenderBatch,Record,Range,RENDER_IT_OUTSIDE_OF_LOOP,REDUNDANT_TEMPLATE_STRING,ParseContext,PairSorting,PLACEHOLDERLESS_TEMPLATE_STRING,OrderedSet,OrderedMap,OrderedMap as OMap,ModuleTests,ModuleTestReport,ModuleInfo,Map2 as Map,METHOD_VAL_NOT_DEFINED,METHOD_VAL_IS_FIELD,MAYBE_DROP_AT_PREFIX,List,LintReport,LintParseContext,LintFinding,LintContext,LintComponentResult,LintClassCollectorCtx,KList,Set2 as ISet,INPUT_HANDLER_NOT_REFERENCED,INPUT_HANDLER_NOT_IMPLEMENTED,INPUT_HANDLER_METHOD_NOT_IMPLEMENTED,INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER,INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD,Map2 as IMap,IF_NO_BRANCH_SET,FIELD_VAL_NOT_DEFINED,FIELD_VAL_IS_METHOD,FIELD_CLASS,ExampleIndex,DescribeResult,Describe,DYN_VAL_NOT_DEFINED,DYN_ALIAS_NOT_REFERENCED,DUPLICATE_ATTR_DEFINITION,ComponentSummary,ComponentList,ComponentDocs,Collection,BAD_VALUE,ALT_HANDLER_NOT_REFERENCED,ALT_HANDLER_NOT_DEFINED};
|
|
4
|
+
`)}}function defaultOnStackEnter(){return null}var STOP=Symbol("STOP"),NEXT=Symbol("NEXT");function lookup(chain,name,dv=null){let n=chain;while(n!==null){let r=n[0].lookup(name);if(r===STOP)return dv;if(r!==NEXT)return r;n=n[1]}return dv}class BindFrame{constructor(it,binds,isFrame){this.it=it,this.binds=binds,this.isFrame=isFrame}lookup(name){let v=this.binds[name];return v===void 0?this.isFrame?STOP:NEXT:v}}class ObjectFrame{constructor(binds){this.binds=binds}lookup(key){let v=this.binds[key];return v===void 0?NEXT:v}}function computeViewsId(views){let s="",n=views;while(n!==null)s+=n[0],n=n[1];return s==="main"?"":s}class Stack2{constructor(comps,it,binds,dynBinds,views,viewsId,ctx=null){this.comps=comps,this.it=it,this.binds=binds,this.dynBinds=dynBinds,this.views=views,this.viewsId=viewsId,this.ctx=ctx}_enrichOnEnter(){return this.withDynamicBinds(this.comps.getOnEnterFor(this.it).call(this.it))}static root(comps,it,ctx){let binds=[new BindFrame(it,{it},!0),null],dynBinds=[new ObjectFrame({}),null];return new Stack2(comps,it,binds,dynBinds,["main",null],"",ctx)._enrichOnEnter()}enter(it,bindings={},isFrame=!0){let{comps,binds,dynBinds,views,viewsId,ctx}=this,newBinds=[new BindFrame(it,bindings,isFrame),binds],stack=new Stack2(comps,it,newBinds,dynBinds,views,viewsId,ctx);return isFrame?stack._enrichOnEnter():stack}pushViewName(name){let{comps,it,binds,dynBinds,views,ctx}=this,newViews=[name,views];return new Stack2(comps,it,binds,dynBinds,newViews,computeViewsId(newViews),ctx)}withDynamicBinds(dynamics){if(dynamics==null||dynamics.length===0)return this;let dynObj={},comp=this.comps.getCompFor(this.it);for(let dynName of dynamics)comp.dynamic[dynName].evalAndBind(this,dynObj);let newDynBinds=[new ObjectFrame(dynObj),this.dynBinds],{comps,it,binds,views,viewsId,ctx}=this;return new Stack2(comps,it,binds,newDynBinds,views,viewsId,ctx)}_pushDynBindValuesToArray(arr,dyns){for(let k in dyns)arr.push(this._lookupDynamicWithDynVal(dyns[k]))}_lookupDynamicWithDynVal(d){return lookup(this.dynBinds,d.getSymbol(this))??d.val?.eval(this)??null}lookupDynamic(name){let d=this.comps.getCompFor(this.it)?.dynamic[name];return d?this._lookupDynamicWithDynVal(d):null}lookupBind(name){return lookup(this.binds,name)}lookupType(name){return this.comps.getCompFor(this.it).scope.lookupComponent(name)}lookupFieldRaw(name){return this.it[name]??null}lookupMethod(name){let fn=this.it[name];return fn instanceof Function?fn.call(this.it):null}lookupName(name){return this.ctx.lookupName(name)}getHandlerFor(name,key){return this.comps.getHandlerFor(this.it,name,key)}lookupRequest(name){return this.comps.getRequestFor(this.it,name)}lookupBestView(views,defaultViewName){let n=this.views;while(n!==null){let view=views[n[0]];if(view!==void 0)return view;n=n[1]}return views[defaultViewName]}}class State2{constructor(val){this.val=val,this.changeSubs=[]}onChange(cb){this.changeSubs.push(cb)}set(val,info){let old=this.val;this.val=val;for(let sub of this.changeSubs)sub({val,old,info,timestamp:Date.now()})}update(fn,info){return this.set(fn(this.val),info)}}class Transactor{constructor(comps,rootValue){this.comps=comps,this.transactions=[],this.state=new State2(rootValue),this.onTransactionPushed=()=>{}}pushTransaction(t){this.transactions.push(t),this.onTransactionPushed(t)}pushSend(path,name,args=[],opts={},parent=null){this.pushTransaction(new SendEvent(path,this,name,args,parent,opts))}pushBubble(path,name,args=[],opts={},parent=null,targetPath=null){let newOpts=opts.skipSelf?{...opts,skipSelf:!1}:opts;this.pushTransaction(new BubbleEvent(path,this,name,args,parent,newOpts,targetPath))}async pushRequest(path,name,args=[],opts={},parent=null){let curRoot=this.state.val,curLeaf=path.toTransactionPath().lookup(curRoot),handler=this.comps.getRequestFor(curLeaf,name)??mkReq404(name),resHandlerName=opts?.onResName??name,push=(specificName,baseName,singleArg,result,error)=>{let t=new ResponseEvent(path,this,specificName??baseName,specificName?[singleArg]:[result,error],parent);this.pushTransaction(t)};try{let result=await handler.fn.apply(null,args);push(opts?.onOkName,resHandlerName,result,result,null)}catch(error){push(opts?.onErrorName,resHandlerName,error,null,error)}}get hasPendingTransactions(){return this.transactions.length>0}transactNext(){if(this.hasPendingTransactions)this.transact(this.transactions.shift())}transact(transaction){let curState=this.state.val,newState=transaction.run(curState,this.comps);if(newState!==void 0)this.state.set(newState,{transaction}),transaction.afterTransaction();else console.warn("undefined new state",{curState,transaction})}transactInputNow(path,event,eventHandler,dragInfo){this.transact(new InputEvent(path,event,eventHandler,this,dragInfo))}}function mkReq404(name){return{fn:()=>{throw Error(`Request not found: ${name}`)}}}function nullHandler(){return this}class Transaction{constructor(path,transactor,parentTransaction=null){this.path=path,this.transactor=transactor,this.parentTransaction=parentTransaction,this._task=null}get task(){return this._task??=new Task,this._task}getCompletionPromise(){return this.task.promise}setParent(parentTransaction){this.parentTransaction=parentTransaction,parentTransaction.task.addDep(this.task)}run(rootValue,comps){return this.updateRootValue(rootValue,comps)}afterTransaction(){}buildRootStack(root,comps){return Stack2.root(comps,root)}buildStack(root,comps){return this.path.toTransactionPath().buildStack(this.buildRootStack(root,comps))}callHandler(root,instance,comps){let[handler,args]=this.getHandlerAndArgs(root,instance,comps);return handler.apply(instance,args)}getHandlerAndArgs(_root,_instance,_comps){return null}updateRootValue(curRoot,comps){let txnPath=this.path.toTransactionPath(),curLeaf=txnPath.lookup(curRoot),newLeaf=this.callHandler(curRoot,curLeaf,comps);return this._task?.complete?.({value:newLeaf,old:curLeaf}),curLeaf!==newLeaf?txnPath.setValue(curRoot,newLeaf):curRoot}lookupName(_name){return null}}var isMac2=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac"),toNullIfNaN=(v)=>Number.isNaN(v)?null:v;function getValue(e){return e.target.type==="checkbox"?e.target.checked:(e instanceof CustomEvent?e.detail:e.target.value)??null}class InputEvent extends Transaction{constructor(path,e,handler,transactor,dragInfo){super(path,transactor);this.e=e,this.handler=handler,this.dragInfo=dragInfo,this._dispatchPath=null}get dispatchPath(){return this._dispatchPath??=this.path.compact(),this._dispatchPath}buildRootStack(root,comps){return Stack2.root(comps,root,this)}getHandlerAndArgs(root,_instance,comps){let stack=this.buildStack(root,comps),[handler,args]=this.handler.getHandlerAndArgs(stack,this),path=this.dispatchPath,dispatcher;for(let i=0;i<args.length;i++)if(args[i]?.toHandlerArg)dispatcher??=new Dispatcher(path,this.transactor,this),args[i]=args[i].toHandlerArg(dispatcher);return args.push(new EventContext(path,this.transactor,this)),[handler,args]}lookupName(name){let{e}=this;switch(name){case"value":return getValue(e);case"valueAsInt":return toNullIfNaN(parseInt(getValue(e),10));case"valueAsFloat":return toNullIfNaN(parseFloat(getValue(e)));case"target":return e.target;case"event":return e;case"isAlt":return e.altKey;case"isShift":return e.shiftKey;case"isCtrl":case"isCmd":return isMac2&&e.metaKey||e.ctrlKey;case"key":return e.key;case"keyCode":return e.keyCode;case"isUpKey":return e.key==="ArrowUp";case"isDownKey":return e.key==="ArrowDown";case"isSend":return e.key==="Enter";case"isCancel":return e.key==="Escape";case"isTabKey":return e.key==="Tab";case"ctx":return new EventContext(this.dispatchPath,this.transactor,this);case"dragInfo":return this.dragInfo}return null}}class NameArgsTransaction extends Transaction{constructor(path,transactor,name,args,parentTransaction,opts={}){super(path,transactor,parentTransaction);this.name=name,this.args=args,this.opts=opts,this.targetPath=path}handlerProp=null;getHandlerForName(comp){let handlers=comp?.[this.handlerProp];return handlers?.[this.name]??handlers?.$unknown??nullHandler}getHandlerAndArgs(_root,instance,comps){return[this.getHandlerForName(comps.getCompFor(instance)),[...this.args,new EventContext(this.path,this.transactor,this)]]}}class ResponseEvent extends NameArgsTransaction{handlerProp="response"}class SendEvent extends NameArgsTransaction{handlerProp="receive";run(rootVal,comps){return this.opts.skipSelf?rootVal:this.updateRootValue(rootVal,comps)}afterTransaction(){let{path,name,args,opts,targetPath}=this;if(opts.bubbles&&path.steps.length>0)this.transactor.pushBubble(path.popStep(),name,args,opts,this,targetPath)}}class BubbleEvent extends SendEvent{handlerProp="bubble";constructor(path,transactor,name,args,parent,opts,targetPath){super(path,transactor,name,args,parent,opts);this.targetPath=targetPath??path}stopPropagation(){this.opts.bubbles=!1}}class Task{constructor(){this.deps=[],this.val=this.resolve=this.reject=null,this.promise=new Promise((res,rej)=>{this.resolve=res,this.reject=rej}),this.isCompleted=!1}addDep(task){console.assert(!this.isCompleted,"addDep for completed task",this,task),this.deps.push(task),task.promise.then((_)=>this._check())}complete(val){this.val=val,this._check()}_check(){if(this.deps.every((task)=>task.isCompleted))this.isCompleted=!0,this.resolve(this)}}class Dispatcher{constructor(path,transactor,parentTransaction){this.path=path,this.transactor=transactor,this.parent=parentTransaction}get at(){return new PathChanges(this)}send(name,args,opts){return this.sendAtPath(this.path,name,args,opts)}bubble(name,args,opts){return this.send(name,args,{skipSelf:!0,bubbles:!0,...opts})}sendAtPath(path,name,args,opts){return this.transactor.pushSend(path,name,args,opts,this.parent)}request(name,args,opts){return this.requestAtPath(this.path,name,args,opts)}requestAtPath(path,name,args,opts){return this.transactor.pushRequest(path,name,args,opts,this.parent)}lookupTypeFor(name,inst){return this.transactor.comps.getCompFor(inst).scope.lookupComponent(name)}}class EventContext extends Dispatcher{get name(){return this.parent?.name??null}get targetPath(){return this.parent.targetPath}stopPropagation(){return this.parent.stopPropagation()}}class PathChanges extends PathBuilder{constructor(dispatcher){super();this.dispatcher=dispatcher}send(name,args,opts){return this.dispatcher.sendAtPath(this.buildPath(),name,args,opts)}bubble(name,args,opts){return this.send(name,args,{skipSelf:!0,bubbles:!0,...opts})}buildPath(){return this.dispatcher.path.concat(this.pathChanges)}}var _evs="dragstart dragover dragend touchstart touchmove touchend touchcancel".split(" ");class App{constructor(rootNode,comps,renderer,ParseContext2){this.rootNode=rootNode,this.comps=comps,this.compStack=new ComponentStack(comps),this.transactor=new Transactor(comps,null),this.ParseContext=ParseContext2,this.renderer=renderer,this.maxEventNodeDepth=1/0,this._transactNextBatchId=this._evictCacheId=null,this._eventNames=new Set(_evs),this.dragInfo=this.curDragOver=null,this._touch=null,this.transactor.onTransactionPushed=(_transaction)=>{if(this._transactNextBatchId===null)this._scheduleNextTransactionBatchExecution()},this._compiled=!1,this._renderOpts={document:rootNode.ownerDocument},this._renderState=null}get state(){return this.transactor.state}handleEvent(e){let{type:type3}=e;if(type3[0]==="t"&&type3.startsWith("touch")){this._handleTouchEvent(e);return}this._dispatchEvent(e)}_dispatchEvent(e){let{type:type3}=e,isDrag=type3==="dragover"||type3==="dragstart"||type3==="dragend"||type3==="drop",{rootNode:root,maxEventNodeDepth:maxDepth,comps,transactor}=this,[path,handlers]=Path.fromEvent(e,root,maxDepth,comps,!isDrag);if(isDrag)this._handleDragEvent(e,type3,path);if(path!==null&&handlers!==null)for(let handler of handlers)transactor.transactInputNow(path,e,handler,this.dragInfo)}_handleTouchEvent(e){let{type:type3}=e;if(type3==="touchstart"){if(this._touch!==null||e.touches.length!==1)return;let t=e.touches[0],draggable=t.target?.closest?.('[draggable="true"]');if(!draggable)return;this._touch=makeTouchInfo(t.identifier,t.clientX,t.clientY,draggable,!1);return}if(this._touch===null)return;let touch=findTouch(e,this._touch.id);if(touch===null)return;let{rootNode,_touch}=this,{clientX,clientY}=touch,fire=(type4,target)=>{let e2={type:type4,target,clientX,clientY,preventDefault:NOOP};this._dispatchEvent(e2)};if(type3==="touchmove"){if(!_touch.active){let dx=clientX-_touch.startX,dy=clientY-_touch.startY;if(dx*dx+dy*dy<100)return;_touch.active=!0,e.preventDefault(),fire("dragstart",_touch.target)}else e.preventDefault(),fire("dragover",hitTest(rootNode,clientX,clientY));return}if(type3==="touchend"||type3==="touchcancel"){if(_touch.active){if(type3==="touchend")fire("drop",hitTest(rootNode,clientX,clientY));fire("dragend",_touch.target)}this._touch=null}}_handleDragEvent(e,type3,path){if(type3==="dragover"){let dropTarget=getClosestDropTarget(e.target,this.rootNode,1/0);if(dropTarget!==null)e.preventDefault(),this._cleanDragOverAttrs(),this.curDragOver=dropTarget,dropTarget.dataset.draggingover=this.dragInfo?.type??"_external"}else if(type3==="dragstart"){e.target.dataset.dragging=1;let rootValue=this.state.val,txnPath=path.compact().toTransactionPath(),value=txnPath.lookup(rootValue),dragType=e.target.dataset.dragtype??"?",stack=path.toTransactionPath().buildStack(this.makeStack(rootValue));this.dragInfo=new DragInfo(txnPath,stack,e,value,dragType,e.target)}else if(type3==="drop")e.preventDefault(),this._cleanDragOverAttrs();else{if(this.dragInfo!==null)delete this.dragInfo.node.dataset.dragging,this.dragInfo=null;this._cleanDragOverAttrs()}}makeStack(rootValue){return Stack2.root(this.comps,rootValue)}_cleanDragOverAttrs(){if(this.curDragOver!==null)delete this.curDragOver.dataset.draggingover,this.curDragOver=null}render(){let root=this.state.val,stack=this.makeStack(root),{renderer,rootNode,_renderOpts,_renderState}=this,newState=render(renderer.renderRoot(stack,root),rootNode,_renderOpts,_renderState);return this._renderState=newState,newState.dom}onChange(callback){this.transactor.state.onChange(callback)}compile(){for(let Comp of this.comps.byId.values()){Comp.compile(this.ParseContext);for(let key in Comp.views)for(let name of Comp.views[key].ctx.genEventNames())this._eventNames.add(name)}this._compiled=!0}subscribeToEvents(eventNames){for(let name of eventNames)this.rootNode.addEventListener(name,this,listenerOpts(name))}recompileStyles(opts){injectCss("tutuca-app",this.comps.compileStyles(),opts?.head??document.head)}start(opts){if(!this._compiled)this.compile();if(this.subscribeToEvents(this._eventNames),this.onChange((info)=>{if(info.val!==info.old)this.render()}),this.recompileStyles(opts),opts?.noCache)this.renderer.setNullCache();else this.startCacheEvictionInterval();this.render()}stop(){this.stopCacheEvictionInterval();for(let name of this._eventNames)this.rootNode.removeEventListener(name,this,listenerOpts(name))}sendAtRoot(name,args,opts){this.transactor.pushSend(new Path([]),name,args,opts)}registerComponents(comps,opts){let scope=this.compStack.enter();return scope.registerComponents(comps,opts),scope}_transactNextBatch(maxRunTimeMs=10){this._transactNextBatchId=null;let startTs=Date.now(),t=this.transactor;while(t.hasPendingTransactions&&Date.now()-startTs<maxRunTimeMs)t.transactNext();if(t.hasPendingTransactions)this._scheduleNextTransactionBatchExecution()}_scheduleNextTransactionBatchExecution(){this._transactNextBatchId=setTimeout(()=>this._transactNextBatch(),0)}startCacheEvictionInterval(intervalMs=30000){this._evictCacheId=setInterval(()=>this.renderer.cache.evict(),intervalMs)}stopCacheEvictionInterval(){clearInterval(this._evictCacheId),this._evictCacheId=null}}function injectCss(nodeId,style,styleTarget=document.head){let styleNode=document.createElement("style"),currentNodeWithId=styleTarget.querySelector(`#${nodeId}`);if(currentNodeWithId)styleTarget.removeChild(currentNodeWithId);styleNode.id=nodeId,styleNode.innerHTML=style,styleTarget.appendChild(styleNode)}var NOOP=()=>{};function findTouch(e,id){for(let t of e.changedTouches)if(t.identifier===id)return t;for(let t of e.touches)if(t.identifier===id)return t;return null}var listenerOpts=(name)=>name==="touchmove"?{passive:!1}:void 0;function makeTouchInfo(id,startX,startY,target,active){return{id,startX,startY,target,active}}function hitTest(rootNode,x,y){let el=rootNode.getRootNode().elementFromPoint?.(x,y)??null;while(el?.shadowRoot){let next=el.shadowRoot.elementFromPoint(x,y);if(next===null||next===el)break;el=next}return el??rootNode}function getClosestDropTarget(target,rootNode,count){let node=target;while(count-- >0&&node!==rootNode){if(node.dataset?.droptarget!==void 0)return node;node=node.parentNode}return null}class DragInfo{constructor(path,stack,e,val,type3,node){this.path=path,this.stack=stack,this.e=e,this.val=val,this.type=type3,this.node=node}lookupBind(name){return this.stack.lookupBind(name)}}var BAD_VALUE2=Symbol("BadValue"),nullCoercer=(v)=>v;class Field{constructor(type3,name,typeCheck,coercer,defaultValue=null){this.type=type3,this.name=name,this.typeCheck=typeCheck,this.coercer=coercer,this.checks=[],this.defaultValue=defaultValue}toDataDef(){let{type:type3,defaultValue:dv}=this;return{type:type3,defaultValue:dv?.toJS?dv.toJS():dv}}getFirstFailingCheck(v){if(!this.typeCheck.isValid(v))return this.typeCheck;for(let check of this.checks)if(!check.isValid(v))return check;return null}isValid(v){return this.getFirstFailingCheck(v)===null}addCheck(check){return this.checks.push(check),this}coerceOr(v,defaultValue=null){if(this.isValid(v))return v;let v1=this.coercer(v);return this.isValid(v1)?v1:defaultValue}coerceOrDefault(v){return this.coerceOr(v,this.defaultValue)}extendProtoForType(_proto,_uname){}extendProto(proto){let{name}=this,uname=name[0].toUpperCase()+name.slice(1),setName=`set${uname}`,that=this;proto[setName]=function(v){let v1=that.coerceOr(v,BAD_VALUE2);if(v1===BAD_VALUE2)return console.warn("invalid value",v),this;return this.set(name,v1)},proto[`update${uname}`]=function(fn){return this[setName](fn(this.get(name)))},proto[`reset${uname}`]=function(){return this.set(name,that.defaultValue)},this.extendProtoForType(proto,uname)}}class Check{isValid(_v){return!0}getMessage(_v){return"Invalid"}}class CheckTypeAny extends Check{}var CHECK_TYPE_ANY=new CheckTypeAny;class FnCheck extends Check{constructor(isValidFn,getMessageFn){super();this._isValid=isValidFn,this._getMessage=getMessageFn}isValid(v){return this._isValid(v)}getMessage(v){return this._getMessage(v)}}var CHECK_TYPE_INT=new FnCheck((v)=>Number.isInteger(v),()=>"Integer expected"),CHECK_TYPE_FLOAT=new FnCheck((v)=>Number.isFinite(v),()=>"Float expected"),CHECK_TYPE_BOOL=new FnCheck((v)=>typeof v==="boolean",()=>"Boolean expected"),CHECK_TYPE_STRING=new FnCheck((v)=>typeof v==="string",()=>"String expected"),CHECK_TYPE_LIST=new FnCheck((v)=>List.isList(v),()=>"List expected"),CHECK_TYPE_MAP=new FnCheck((v)=>Map2.isMap(v),()=>"Map expected"),CHECK_TYPE_OMAP=new FnCheck((v)=>OrderedMap.isOrderedMap(v),()=>"OrderedMap expected"),CHECK_TYPE_SET=new FnCheck((v)=>Set2.isSet(v),()=>"Set expected"),boolCoercer=(v)=>!!v;class FieldBool extends Field{constructor(name,defaultValue=!1){super("bool",name,CHECK_TYPE_BOOL,boolCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;proto[`toggle${uname}`]=function(){return this.set(name,!this.get(name,!1))},proto[`set${uname}`]=function(v){return this.set(name,!!v)}}}class FieldAny extends Field{constructor(name,defaultValue=null){super("any",name,CHECK_TYPE_ANY,nullCoercer,defaultValue)}toDataDef(){let{defaultValue:dv}=this;return{type:getTypeName(dv)??"any",defaultValue:dv?.toJS?dv.toJS():dv}}}var stringCoercer=(v)=>v?.toString?.()??"";class FieldString extends Field{constructor(name,defaultValue=""){super("text",name,CHECK_TYPE_STRING,stringCoercer,defaultValue)}extendProtoForType(proto,_uname){extendProtoSized(proto,this.name,"","length")}}var intCoercer=(v)=>Number.isFinite(v)?Math.trunc(v):null;class FieldInt extends Field{constructor(name,defaultValue=0){super("int",name,CHECK_TYPE_INT,intCoercer,defaultValue)}}var floatCoercer=(_)=>null;class FieldFloat extends Field{constructor(name,defaultValue=0){super("float",name,CHECK_TYPE_FLOAT,floatCoercer,defaultValue)}}var getTypeName=(v)=>v?.constructor?.getMetaClass?.()?.name;class CheckTypeName{constructor(typeName){this.typeName=typeName}isValid(v){return getTypeName(v)===this.typeName}getMessage(v){let got=getTypeName(v);return`Expected "${this.typeName}", got "${got}"`}}class FieldComp extends Field{constructor(type3,name,args){super(type3,name,new CheckTypeName(type3),nullCoercer,null);this.args=args}toDataDef(){return{component:this.typeName,args:this.args}}}var NONE2=Symbol("NONE");function extendProtoForKeyed(proto,name,uname){extendProtoSized(proto,name,EMPTY_LIST),proto[`setIn${uname}At`]=function(i,v){return this.set(name,this.get(name).set(i,v))},proto[`getIn${uname}At`]=function(i,dval){return this.get(name).get(i,dval)},proto[`updateIn${uname}At`]=function(i,fn){let col=this.get(name),v=col.get(i,NONE2);if(v!==NONE2)return this.set(name,col.set(i,fn(v)));return console.warn("key",i,"not found in",name,col),this},extendDeleteInAt(proto,name,`${uname}At`)}function extendDeleteInAt(proto,name,uname){proto[`deleteIn${uname}`]=function(v){return this.set(name,this.get(name).delete(v))},proto[`removeIn${uname}`]=proto[`deleteIn${uname}`]}var EMPTY_LIST=List(),listCoercer=(v)=>Array.isArray(v)?List(v):null;class FieldList extends Field{constructor(name,defaultValue=EMPTY_LIST){super("list",name,CHECK_TYPE_LIST,listCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;extendProtoForKeyed(proto,name,uname),proto[`pushIn${uname}`]=function(v){return this.set(name,this.get(name).push(v))},proto[`insertIn${uname}At`]=function(i,v){return this.set(name,this.get(name).insert(i,v))}}}var imapCoercer=(v)=>Map2(v);class FieldMap extends Field{constructor(name,defaultValue=Map2()){super("map",name,CHECK_TYPE_MAP,imapCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname)}}var omapCoercer=(v)=>OrderedMap(v);class FieldOMap extends Field{constructor(name,defaultValue=OrderedMap()){super("omap",name,CHECK_TYPE_OMAP,omapCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname)}}function extendProtoSized(proto,name,defaultEmpty,propName="size"){proto[`${name}Len`]=function(){return this.get(name,defaultEmpty)[propName]}}var EMPTY_SET3=Set2(),isetCoercer=(v)=>Array.isArray(v)?Set2(v):v instanceof Set?Set2(v):null;class FieldSet extends Field{constructor(name,defaultValue=EMPTY_SET3){super("set",name,CHECK_TYPE_SET,isetCoercer,defaultValue)}extendProtoForType(proto,uname){let{name}=this;extendProtoSized(proto,name,EMPTY_SET3),proto[`addIn${uname}`]=function(v){return this.set(name,this.get(name).add(v))},extendDeleteInAt(proto,name,uname),proto[`hasIn${uname}`]=function(v){return this.get(name).has(v)},proto[`toggleIn${uname}`]=function(v){let current=this.get(name);return this.set(name,current.has(v)?current.delete(v):current.add(v))}}}function mkCompField(field,scope,args){let Comp=scope.lookupComponent(field.type);return console.assert(Comp!==null,"component not found",{field}),Comp?.make({...field.args,...args},{scope})??null}class ClassBuilder{constructor(name){let fields={},compFields=new Set;this.name=name,this.fields=fields,this.compFields=compFields,this._methods={},this._statics={make:function(inArgs={},opts={}){let args={};for(let key in inArgs){let field=fields[key];if(compFields.has(key))args[key]=mkCompField(field,opts.scope,inArgs[key]);else if(field===void 0)console.warn("extra argument to constructor:",name,key,inArgs);else args[key]=field.coerceOrDefault(inArgs[key])}for(let key of compFields)if(args[key]===void 0)args[key]=mkCompField(fields[key],opts.scope,inArgs[key]);return this(args)}}}build(){let fieldVals={},proto={},{name,_methods,fields}=this;for(let fieldName in fields){let field=fields[fieldName];fieldVals[fieldName]=field.defaultValue,field.extendProto(proto)}let Class={[name]:Record(fieldVals,name)}[name];Object.assign(Class.prototype,proto,_methods);let metaClass={fields,name,methods:_methods};return Object.assign(Class,this._statics,{getMetaClass:()=>metaClass}),Class}methods(proto){for(let k in proto)this._methods[k]=proto[k]}statics(proto){for(let k in proto)this._statics[k]=proto[k]}addField(name,dval,FieldCls){let field=new FieldCls(name,dval);return this.fields[name]=field,field}addCompField(name,type3,args){let field=new FieldComp(type3,name,args);return this.compFields.add(name),this.fields[name]=field,field}}var FIELD_CLASS=Symbol.for("tutuca.fieldClass"),fieldsByTypeName={text:FieldString,int:FieldInt,float:FieldFloat,bool:FieldBool,list:FieldList,map:FieldMap,omap:FieldOMap,set:FieldSet,any:FieldAny};function classFromData(name,{fields={},methods,statics}){let b=new ClassBuilder(name);for(let field in fields){let value=fields[field],type3=typeof value;if(type3==="string")b.addField(field,value,FieldString);else if(type3==="number")b.addField(field,value,FieldFloat);else if(type3==="boolean")b.addField(field,value,FieldBool);else if(List.isList(value)||Array.isArray(value))b.addField(field,List(value),FieldList);else if(Set2.isSet(value)||value instanceof Set)b.addField(field,Set2(value),FieldSet);else if(OrderedMap.isOrderedMap(value))b.addField(field,value,FieldOMap);else if(value?.type&&value?.defaultValue!==void 0){let Field2=fieldsByTypeName[value.type]??FieldAny;b.addField(field,new Field2().coerceOr(value.defaultValue),Field2)}else if(value?.component&&value?.args!==void 0)b.addCompField(field,value.component,value.args);else if(Map2.isMap(value)||value?.constructor===Object)b.addField(field,Map2(value),FieldMap);else{let Field2=value?.[FIELD_CLASS]??FieldAny;b.addField(field,value,Field2)}}if(methods)b.methods(methods);if(statics)b.statics(statics);return b.build()}var component=(opts)=>new Component(classFromData(opts.name,opts),opts);class NullDomCache{get(_keys,_cacheKey){}set(_keys,_cacheKey,_v){}evict(){return{hit:0,miss:0,badKey:0}}}class WeakMapDomCache{constructor(){this.hit=this.miss=this.badKey=0,this.keysByLen=new Map}_returnValue(r){if(r===void 0)this.miss+=1;else this.hit+=1;return r}get(keys,cacheKey){let len=keys.length,cur=this.keysByLen.get(len);if(!cur)return this._returnValue(void 0);for(let i=0;i<len-1;i++)if(cur=cur.get(keys[i]),!cur)return this._returnValue(void 0);return this._returnValue(cur.get(keys[len-1])?.[cacheKey])}set(keys,cacheKey,v){let len=keys.length,cur=this.keysByLen.get(len);if(!cur)cur=new WeakMap,this.keysByLen.set(len,cur);for(let i=0;i<len-1;i++){let key=keys[i],next=cur.get(key);if(!next){if(typeof key!=="object"){this.badKey+=1;return}next=new WeakMap,cur.set(key,next)}cur=next}let lastKey=keys[len-1],leaf=cur.get(lastKey);if(leaf)leaf[cacheKey]=v;else if(typeof lastKey==="object")cur.set(lastKey,{[cacheKey]:v});else this.badKey+=1}evict(){let{hit,miss,badKey}=this;return this.hit=this.miss=this.badKey=0,this.keysByLen=new Map,{hit,miss,badKey}}}var DATASET_ATTRS=["nid","cid","eid","vid","si","sk"];class Renderer{constructor(comps){this.comps=comps,this.cache=new WeakMapDomCache,this.renderTag=h}renderFragment(childs){return new VFragment(childs)}renderComment(text){return new VComment(text)}setNullCache(){this.cache=new NullDomCache}renderToDOM(stack,val){let rootNode=document.createElement("div"),rOpts={document};return render(h("DIV",null,[this.renderRoot(stack,val)]),rootNode,rOpts),rootNode.childNodes[0]}renderToString(stack,val,cleanAttrs=!0){let dom=this.renderToDOM(stack,val);if(cleanAttrs){let nodes=dom.querySelectorAll("[data-nid],[data-cid],[data-eid]");for(let{dataset}of nodes)for(let name of DATASET_ATTRS)delete dataset[name]}return dom.innerHTML}renderRoot(stack,val,viewName=null){let comp=this.comps.getCompFor(val);if(comp===null)return null;return this._rValComp(stack,val,comp,comp.getView(viewName).anode,"ROOT",viewName)}renderIt(stack,node,key,viewName){let comp=this.comps.getCompFor(stack.it);return comp?this._rValComp(stack,stack.it,comp,node,key,viewName):null}_rValComp(stack,val,comp,node,key,viewName){let cacheKey=`${viewName??stack.viewsId??""}-${key}`,cachePath=[node,val];stack._pushDynBindValuesToArray(cachePath,comp.dynamic);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)return cachedNode;let view=viewName?comp.getView(viewName):stack.lookupBestView(comp.views,"main"),meta=this._renderMetadata({$:"Comp",nid:node?.nodeId??null}),dom=new VFragment([meta,this.renderView(view,stack)]);return this.cache.set(cachePath,cacheKey,dom),dom}pushEachEntry(r,nid,attrName,key,dom){r.push(this._renderMetadata({$:"Each",nid,[attrName]:key}),dom)}renderEach(stack,iterInfo,node,viewName){let{seq,filter,loopWith}=iterInfo.eval(stack),r=[],{iterData,start,end}=unpackLoopResult(loopWith.call(stack.it,seq),seq);return getSeqInfo(seq)(seq,(key,value,attrName)=>{if(filter.call(stack.it,key,value,iterData)){let dom=this.renderIt(stack.enter(value,{key},!0),node,key,viewName);this.pushEachEntry(r,node.nodeId,attrName,key,dom)}},start,end),r}renderEachWhen(stack,iterInfo,view,nid){let{seq,filter,loopWith,enricher}=iterInfo.eval(stack),r=[],it=stack.it,{iterData,start,end}=unpackLoopResult(loopWith.call(it,seq),seq);return getSeqInfo(seq)(seq,(key,value,attrName)=>{if(filter.call(it,key,value,iterData)){let cachePath=enricher?[view,it,value]:[view,value],binds={key,value},cacheKey=`${nid}-${key}`;if(enricher)enricher.call(it,binds,key,value,iterData);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)this.pushEachEntry(r,nid,attrName,key,cachedNode);else{let dom=this.renderView(view,stack.enter(value,binds,!1));this.pushEachEntry(r,nid,attrName,key,dom),this.cache.set(cachePath,cacheKey,dom)}}},start,end),r}renderView(view,stack){let n=stack.binds[1];while(n!==null){let b=n[0];if(b.isFrame){if(stack.it!==b.it)break;return console.error("recursion detected",stack.it,b.it),new VComment("RECURSION AVOIDED")}n=n[1]}return view.render(stack,this)}_renderMetadata(info){return new VComment(`§${JSON.stringify(info)}§`)}}var getSeqInfo=(seq)=>isIndexed(seq)?imIndexedIter:isKeyed(seq)?imKeyedIter:seq?.[SEQ_INFO]??unkIter,normalizeRange=(start,end,size)=>{let s=start==null?0:start<0?size+start:start,e=end==null?size:end<0?size+end:end;return s=s<0?0:s>size?size:s,e=e<0?0:e>size?size:e,[s,e<s?s:e]},unpackLoopResult=(result,seq)=>{let r=result??{};return{iterData:r.iterData??{seq},start:r.start,end:r.end}},imIndexedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seq.size);for(let i=s;i<e;i++)visit(i,seq.get(i),"si")},imKeyedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seq.size),i=0;for(let[k,v]of seq.toSeq().entries()){if(i>=e)break;if(i>=s)visit(k,v,"sk");i++}},unkIter=()=>{},SEQ_INFO=Symbol.for("tutuca.seqInfo");class KList{constructor(items=Map2(),order=List()){this.items=items,this.order=order,this.$=0}_clonish(items,order){return new KList(items,order,this.$)}toJS(){return this.order.toArray().map((k)=>this.items.get(k))}set(k,v){let newOrder=this.items.has(k)?this.order:this.order.push(k);return this._clonish(this.items.set(k,v),newOrder,this.$)}get(k,dval=null){return this.items.get(k,dval)}_nextFreeKey(){let cur=this.$;while(!0){let key=`§${cur}§`;if(!this.items.has(key))return[key,cur];cur+=1}}push(v){let[key,next$]=this._nextFreeKey(),newKList=this.set(key,v);return newKList.$=next$,newKList}get size(){return this.items.size}delete(k){if(this.items.has(k)){let newOrder=this.order.delete(this.order.indexOf(k));return this._clonish(this.items.delete(k),newOrder)}return this}moveKeyBeforeKey(k1,k2){let{order}=this;return this.moveKeyIndexToIndex(order.indexOf(k1),order.indexOf(k2),0)}moveKeyAfterKey(k1,k2){let{order}=this;return this.moveKeyIndexToIndex(order.indexOf(k1),order.indexOf(k2),1)}moveKeyIndexToIndex(source,target,offset){if(source===-1||target===-1||source===target)return this;let{order}=this,newPos=target+offset,oldPos=newPos<source?source+1:source,newOrder=order.insert(newPos,order.get(source)).delete(oldPos);return this._clonish(this.items,newOrder)}}var klistCoercer=(_)=>null;class CheckTypeKList{isValid(v){return v instanceof KList}getMessage(_v){return"KList expected"}}var CHECK_TYPE_KLIST=new CheckTypeKList;class FieldKList extends Field{constructor(name,defaultValue=new KList){super("KList",name,CHECK_TYPE_KLIST,klistCoercer,defaultValue)}extendProtoForType(proto,uname){extendProtoForKeyed(proto,this.name,uname);let{name}=this;extendProtoForKeyed(proto,name,uname),proto[`pushIn${uname}`]=function(v){return this.set(name,this.get(name).push(v))}}}KList.prototype[FIELD_CLASS]=FieldKList;KList.prototype[SEQ_INFO]=(seq,visit)=>{for(let k of seq.order)visit(k,seq.items.get(k),"data-sk")};var{raw:css,raw:html}=String,macro=(defaults,rawView)=>new Macro(defaults,rawView);function tutuca(nodeOrSelector){let rootNode=typeof nodeOrSelector==="string"?document.querySelector(nodeOrSelector):nodeOrSelector,comps=new Components,renderer=new Renderer(comps);return new App(rootNode,comps,renderer,ParseContext)}async function compileClassesToStyle(app,compileClasses,styleId="margaui-css"){let t1=performance.now(),css2=await compileClassesToStyleText(app,compileClasses),t2=performance.now();return injectCss(styleId,css2),t2-t1}async function compileClassesToStyleText(app,compileClasses,Ctx=ParseCtxClassSetCollector){app.ParseContext=Ctx,app.compile();let classes=new Set;for(let Comp of app.comps.byId.values())for(let key in Comp.views){let view=Comp.views[key];for(let name of view.ctx.classes)classes.add(name)}return await compileClasses(Array.from(classes))}function getSignature(name,fn){let m=fn.toString().match(/^(?:\w+|function\s*\w*)\s*\(([^)]*)\)/),params=m?m[1].trim():"";return`${name}(${params})`}function getFieldMethods(field){let{name,type:type3}=field,uname=name[0].toUpperCase()+name.slice(1),methods=[{name:`set${uname}`,sig:`set${uname}(v)`,desc:"Set value"},{name:`update${uname}`,sig:`update${uname}(fn)`,desc:"Update value with function"},{name:`reset${uname}`,sig:`reset${uname}()`,desc:"Reset to default value"}];switch(type3){case"bool":methods[0].desc="Set value (coerces to boolean)",methods.push({name:`toggle${uname}`,sig:`toggle${uname}()`,desc:"Toggle boolean value"});break;case"int":case"float":case"any":break;case"text":methods.push({name:`${name}Len`,sig:`${name}Len()`,desc:"Get string length"});break;case"list":methods.push({name:`${name}Len`,sig:`${name}Len()`,desc:"Get list size"},{name:`setIn${uname}At`,sig:`setIn${uname}At(i, v)`,desc:"Set item at index"},{name:`getIn${uname}At`,sig:`getIn${uname}At(i, defaultValue)`,desc:"Get item at index"},{name:`updateIn${uname}At`,sig:`updateIn${uname}At(i, fn)`,desc:"Update item at index with function"},{name:`deleteIn${uname}At`,sig:`deleteIn${uname}At(i)`,desc:"Delete item at index"},{name:`removeIn${uname}At`,sig:`removeIn${uname}At(i)`,desc:"Delete item at index (alias)"},{name:`pushIn${uname}`,sig:`pushIn${uname}(v)`,desc:"Push item to end"},{name:`insertIn${uname}At`,sig:`insertIn${uname}At(i, v)`,desc:"Insert item at index"});break;case"map":case"omap":{let label=type3==="omap"?"ordered map":"map";methods.push({name:`${name}Len`,sig:`${name}Len()`,desc:`Get ${label} size`},{name:`setIn${uname}At`,sig:`setIn${uname}At(key, v)`,desc:"Set value at key"},{name:`getIn${uname}At`,sig:`getIn${uname}At(key, defaultValue)`,desc:"Get value at key"},{name:`updateIn${uname}At`,sig:`updateIn${uname}At(key, fn)`,desc:"Update value at key with function"},{name:`deleteIn${uname}At`,sig:`deleteIn${uname}At(key)`,desc:"Delete entry at key"},{name:`removeIn${uname}At`,sig:`removeIn${uname}At(key)`,desc:"Delete entry at key (alias)"});break}case"set":methods.push({name:`${name}Len`,sig:`${name}Len()`,desc:"Get set size"},{name:`addIn${uname}`,sig:`addIn${uname}(v)`,desc:"Add value to set"},{name:`deleteIn${uname}`,sig:`deleteIn${uname}(v)`,desc:"Remove value from set"},{name:`removeIn${uname}`,sig:`removeIn${uname}(v)`,desc:"Remove value from set (alias)"},{name:`hasIn${uname}`,sig:`hasIn${uname}(v)`,desc:"Check if value is in set"},{name:`toggleIn${uname}`,sig:`toggleIn${uname}(v)`,desc:"Toggle value in set"});break;default:break}return methods}function serializeDefault(v){if(v===null||v===void 0)return v;if(v?.toJS)return v.toJS();return v}function getComponentDoc(comp){let meta=comp.Class.getMetaClass(),{fields,name,methods}=meta,userMethods=Object.keys(methods).map((k)=>({name:k,sig:getSignature(k,methods[k])})),inputHandlers=Object.keys(comp.input).map((k)=>({name:k,sig:getSignature(k,comp.input[k])})),fieldDocs=[];for(let fieldName in fields){let field=fields[fieldName];fieldDocs.push({name:fieldName,type:field.type,default:serializeDefault(field.defaultValue),methods:getFieldMethods(field)})}return{name,methods:userMethods,input:inputHandlers,fields:fieldDocs}}function getComponentsDocs(components){return components.map((comp)=>getComponentDoc(comp))}function docComponents(normalized,{name=null}={}){let comps=normalized.components,picked=name===null?comps:comps.filter((c)=>c.name===name);return new ComponentDocs({items:getComponentsDocs(picked)})}var filterAlwaysTrue2=()=>!0,nullLoopWith2=(seq)=>({iterData:{seq}}),plainArrayIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seq.length);for(let i=s;i<e;i++)visit(i,seq[i])},plainMapIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seq.size),i=0;for(let[k,v]of seq.entries()){if(i>=e)break;if(i>=s)visit(k,v);i++}};function pickIter(seq){if(Array.isArray(seq))return plainArrayIter;if(seq instanceof Map)return plainMapIter;return getSeqInfo(seq)}function resolveAlter(Comp,name){if(name==null)return null;let fn=Comp.alter?.[name];if(typeof fn!=="function")throw Error(`alter handler '${name}' not found on component '${Comp.name}'`);return fn}function collectIterBindings(Comp,compInstance,seq,opts={}){let whenFn=resolveAlter(Comp,opts.when)??filterAlwaysTrue2,loopWithFn=resolveAlter(Comp,opts.loopWith)??nullLoopWith2,enrichFn=resolveAlter(Comp,opts.enrichWith),it=compInstance,{iterData,start,end}=unpackLoopResult(loopWithFn.call(it,seq),seq),out=[];return pickIter(seq)(seq,(key,value)=>{if(!whenFn.call(it,key,value,iterData))return;let binds={key,value};if(enrichFn)enrichFn.call(it,binds,key,value,iterData);out.push(binds)},start,end),out}async function test3(opts={}){let report=await runTests({expect,...opts});return reportTestReportToConsole(report),report}function check(app){let counts={error:0,warn:0,hint:0};for(let Comp of app.comps.byId.values()){let shadowViews={};for(let name in Comp.views){let rawView=Comp.views[name].rawView,ctx=new LintParseContext;ANode.parse(rawView,ctx),ctx.compile(Comp.scope),shadowViews[name]={name,ctx,rawView}}let shadowComp=Object.create(Comp);shadowComp.views=shadowViews;let{reports}=checkComponent(shadowComp);if(reports.length===0)continue;console.group(Comp.name);for(let r of reports){counts[r.level]++;let tail=suggestionToMessage(r.suggestion),suffix=tail?` — ${tail}`:"",line=`[${r.level}] ${lintIdToMessage(r.id,r.info)}${suffix}`;if(r.level==="error")console.error(line);else if(r.level==="warn")console.warn(line);else console.log(line)}console.groupEnd()}let total=counts.error+counts.warn+counts.hint;return console.log(total===0?"check: no issues":`check: ${counts.error} error, ${counts.warn} warn, ${counts.hint} hint`),counts}class LintClassCollectorCtx extends ParseCtxClassSetCollector{constructor(...args){super(...args);this.attrs=[],this.parseIssues=[]}enterMacro(macroName,macroVars,macroSlots){let{document:document2,Text,Comment,nodes,events:events2,macroNodes}=this,v=new LintClassCollectorCtx(document2,Text,Comment,nodes,events2,macroNodes,{macroName,macroVars,macroSlots},this);return v.classes=this.classes,v.attrs=this.attrs,v.parseIssues=this.parseIssues,v}onAttributes(attrs,wrapperAttrs,textChild,isMacroCall=!1,tag=null){super.onAttributes(attrs,wrapperAttrs,textChild,isMacroCall,tag),this.attrs.push({attrs,wrapperAttrs,textChild,isMacroCall,tag})}onParseIssue(kind,info){let tag=this.currentTag;this.parseIssues.push({kind,info:tag&&info.tag===void 0?{...info,tag}:info})}}export{version,updateIn$1 as updateIn,update$1 as update,tutuca,test3 as test,suggestionToMessage,setIn$1 as setIn,set2 as set,runTests,reportTestReportToConsole,removeIn,remove,mergeWith$1 as mergeWith,mergeDeepWith$1 as mergeDeepWith,mergeDeep$1 as mergeDeep,merge$1 as merge,makeCollector,macro,lintIdToMessage,isValueObject,isStack,isSet,isSeq,isRecord,isPlainObject,isOrderedSet,isOrderedMap,isOrdered,isOrderedMap as isOMap,isMap,isList,isKeyed,isIndexed,isImmutable,isMap as isIMap,isCollection,isAssociative,is,injectCss,html,hash,hasIn$1 as hasIn,has,getIn$1 as getIn,getComponentsDocs,get2 as get,fromJS,docComponents,css,component,compileClassesToStyleText,compileClassesToStyle,collectIterBindings,checkComponent,check,UNSUPPORTED_EXPR_SYNTAX,UNKNOWN_X_OP,UNKNOWN_X_ATTR,UNKNOWN_REQUEST_NAME,UNKNOWN_MACRO_ARG,UNKNOWN_HANDLER_ARG_NAME,UNKNOWN_EVENT_MODIFIER,UNKNOWN_DIRECTIVE,UNKNOWN_COMPONENT_SPEC_KEY,UNKNOWN_COMPONENT_NAME,TestResult,TestReport,TestIndex,Test,Stack,Set2 as Set,Seq,SEQ_INFO,Repeat,RenderedSection,RenderedExample,RenderBatch,Record,Range,RENDER_IT_OUTSIDE_OF_LOOP,REDUNDANT_TEMPLATE_STRING,ParseContext,PairSorting,PLACEHOLDERLESS_TEMPLATE_STRING,OrderedSet,OrderedMap,OrderedMap as OMap,ModuleTests,ModuleTestReport,ModuleInfo,Map2 as Map,METHOD_VAL_NOT_DEFINED,METHOD_VAL_IS_FIELD,MAYBE_DROP_AT_PREFIX,List,LintReport,LintParseContext,LintFinding,LintContext,LintComponentResult,LintClassCollectorCtx,KList,Set2 as ISet,INPUT_HANDLER_NOT_REFERENCED,INPUT_HANDLER_NOT_IMPLEMENTED,INPUT_HANDLER_METHOD_NOT_IMPLEMENTED,INPUT_HANDLER_METHOD_FOR_INPUT_HANDLER,INPUT_HANDLER_FOR_INPUT_HANDLER_METHOD,Map2 as IMap,IF_NO_BRANCH_SET,FIELD_VAL_NOT_DEFINED,FIELD_VAL_IS_METHOD,FIELD_CLASS,ExampleIndex,DescribeResult,Describe,DYN_VAL_NOT_DEFINED,DYN_ALIAS_NOT_REFERENCED,DUPLICATE_ATTR_DEFINITION,ComponentSummary,ComponentList,ComponentDocs,Collection,BAD_VALUE,ALT_HANDLER_NOT_REFERENCED,ALT_HANDLER_NOT_DEFINED};
|