tutuca 0.13.2 → 0.13.3
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 +39 -79
- package/dist/tutuca-dev.ext.js +37 -77
- package/dist/tutuca-dev.js +37 -77
- package/dist/tutuca-dev.min.js +2 -2
- package/dist/tutuca-extra.ext.js +37 -77
- package/dist/tutuca-extra.js +37 -77
- package/dist/tutuca-extra.min.js +2 -2
- package/dist/tutuca.ext.js +37 -77
- package/dist/tutuca.js +37 -77
- package/dist/tutuca.min.js +2 -2
- package/package.json +1 -1
- package/skill/tutuca/core.md +6 -0
- package/skill/tutuca-source/tutuca.ext.js +37 -77
package/dist/tutuca-dev.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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:()=>isNaN22,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){return isErrorInstance(errorLike)?thrown.constructor===errorLike.constructor||thrown instanceof errorLike.constructor:(typeof errorLike=="object"||typeof errorLike=="function")&&errorLike.prototype?thrown.constructor===errorLike||thrown instanceof errorLike:!1}__name(compatibleConstructor,"compatibleConstructor");function compatibleMessage(thrown,errMatcher){let comparisonString=typeof thrown=="string"?thrown:thrown.message;return isRegExp(errMatcher)?errMatcher.test(comparisonString):typeof errMatcher=="string"?comparisonString.indexOf(errMatcher)!==-1:!1}__name(compatibleMessage,"compatibleMessage");function getConstructorName(errorLike){let constructorName=errorLike;return isErrorInstance(errorLike)?constructorName=errorLike.constructor.name:typeof errorLike=="function"&&(constructorName=errorLike.name,constructorName===""&&(constructorName=new errorLike().name||constructorName)),constructorName}__name(getConstructorName,"getConstructorName");function getMessage(errorLike){let msg="";return errorLike&&errorLike.message?msg=errorLike.message:typeof errorLike=="string"&&(msg=errorLike),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];return typeof stringTag=="string"?stringTag: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),__publicField(this,"message"),this.message=message,canElideFrames&&Error.captureStackTrace(this,ssf||_AssertionError2);for(let key in props)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]||"";return color?`\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m`:String(value)}__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:!!showHidden,depth:Number(depth),colors:!!colors,customInspect:!!customInspect,showProxy:!!showProxy,maxArrayLength:Number(maxArrayLength),breakLength:Number(breakLength),truncate:Number(truncate2),seen,inspect:inspect3,stylize};return options.colors&&(options.stylize=colorise),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;return end>0&&isHighSurrogate(string[end-1])&&(end=end-1),`${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="",peek2="",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=peek2||inspectItem(value,options)+(last?"":separator),nextLength=output.length+string.length,truncatedLength=nextLength+truncated.length;if(last&&nextLength>originalLength&&output.length+truncated.length<=originalLength||!last&&!secondToLast&&truncatedLength>originalLength||(peek2=last?"":inspectItem(list[i+1],options)+(secondToLast?"":separator),!last&&secondToLast&&truncatedLength>originalLength&&nextLength+peek2.length>originalLength))break;if(output+=string,!last&&!secondToLast&&nextLength+peek2.length>=originalLength){truncated=`${truncator}(${list.length-i-1})`;break}truncated=""}return`${output}${truncated}`}__name(inspectList,"inspectList");function quoteComplexKey(key){return key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)?key:JSON.stringify(key).replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'")}__name(quoteComplexKey,"quoteComplexKey");function inspectProperty([key,value],options){return options.truncate-=2,typeof key=="string"?key=quoteComplexKey(key):typeof key!="number"&&(key=`[${options.inspect(key,options)}]`),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="";return nonIndexProperties.length&&(propertyContents=inspectList(nonIndexProperties.map(key=>[key,array[key]]),options,inspectProperty)),`[ ${listContents}${propertyContents?`, ${propertyContents}`:""} ]`}__name(inspectArray,"inspectArray");var getArrayName=__name(array=>typeof Buffer=="function"&&array instanceof Buffer?"Buffer":array[Symbol.toStringTag]?array[Symbol.toStringTag]: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="";return nonIndexProperties.length&&(propertyContents=inspectList(nonIndexProperties.map(key=>[key,array[key]]),options,inspectProperty)),`${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;return name?options.stylize(`[${functionType} ${truncate(name,options.truncate-11)}]`,"special"):options.stylize(`[${functionType}]`,"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){return map.size===0?"Map{}":(options.truncate-=7,`Map{ ${inspectList(mapToEntries(map),options,inspectMapEntry)} }`)}__name(inspectMap,"inspectMap");var isNaN2=Number.isNaN||(i=>i!==i);function inspectNumber(number,options){return isNaN2(number)?options.stylize("NaN","number"):number===1/0?options.stylize("Infinity","number"):number===-1/0?options.stylize("-Infinity","number"):number===0?options.stylize(1/number===1/0?"+0":"-0","number"):options.stylize(truncate(String(number),options.truncate),"number")}__name(inspectNumber,"inspectNumber");function inspectBigInt(number,options){let nums=truncate(number.toString(),options.truncate-1);return nums!==truncator&&(nums+="n"),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(set22){let values=[];return set22.forEach(value=>{values.push(value)}),values}__name(arrayFromSet,"arrayFromSet");function inspectSet(set22,options){return set22.size===0?"Set{}":(options.truncate-=7,`Set{ ${inspectList(arrayFromSet(set22),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","\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){return stringEscapeChars.test(string)&&(string=string.replace(stringEscapeChars,escape)),options.stylize(`'${truncate(string,options.truncate-2)}'`,"string")}__name(inspectString,"inspectString");function inspectSymbol(value){return"description"in Symbol.prototype?value.description?`Symbol(${value.description})`:"Symbol()":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="";return propertyContents&&symbolContents&&(sep=", "),`{ ${propertyContents}${sep}${symbolContents} }`}__name(inspectObject,"inspectObject");var toStringTag=typeof Symbol<"u"&&Symbol.toStringTag?Symbol.toStringTag:!1;function inspectClass(value,options){let name="";return toStringTag&&toStringTag in value&&(name=value[toStringTag]),name=name||value.constructor.name,(!name||name==="_class")&&(name="<Anonymous Class>"),options.truncate-=name.length,`${name}${inspectObject(value,options)}`}__name(inspectClass,"inspectClass");function inspectArguments(args,options){return args.length===0?"Arguments[]":(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):properties.unshift("message"),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){return options.truncate-=3,value?`${options.stylize(String(key),"yellow")}=${options.stylize(`"${value}"`,"string")}`:`${options.stylize(String(key),"yellow")}`}__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="";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);return children&&children.length>truncate2&&(children=`${truncator}(${element.children.length})`),`${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)=>chaiInspect in value&&typeof value[chaiInspect]=="function"?value[chaiInspect](options):nodeInspect in value&&typeof value[nodeInspect]=="function"?value[nodeInspect](options.depth,options,inspectFn):"inspect"in value&&typeof value.inspect=="function"?value.inspect(options.depth,options):"constructor"in value&&constructorMap.has(value.constructor)?constructorMap.get(value.constructor)(value,options):stringTagMap[type3]?stringTagMap[type3](value,options):"","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)),type3 in baseTypesMap)return baseTypesMap[type3](value,options);if(customInspect&&value){let output=inspectCustom(value,options,type3,inspect);if(output)return typeof output=="string"?output:inspect(output,options)}let proto=value?Object.getPrototypeOf(value):!1;return proto===Object.prototype||proto===null?inspectObject(value,options):value&&typeof HTMLElement=="function"&&value instanceof HTMLElement?inspectHTML(value,options):"constructor"in value?value.constructor!==Object?inspectClass(value,options):inspectObject(value,options):value===Object(value)?inspectObject(value,options):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+"]";if(type3==="[object Array]")return"[ Array("+obj.length+") ]";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");return typeof msg=="function"&&(msg=msg()),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));object.__flags||(object.__flags=Object.create(null)),includeAll=arguments.length===3?includeAll:!0;for(let flag3 in flags)(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];return typeof stringTag=="string"?stringTag:Object.prototype.toString.call(obj).slice(8,-1)}__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){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))){var leftHandMap=memoizeMap.get(leftHandOperand);leftHandMap?leftHandMap.set(rightHandOperand,result):(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);return simpleResult!==null?simpleResult:extensiveDeepEqual(leftHandOperand,rightHandOperand,options)}__name(deepEqual,"deepEqual");function simpleEqual(leftHandOperand,rightHandOperand){return leftHandOperand===rightHandOperand?leftHandOperand!==0||1/leftHandOperand===1/rightHandOperand:leftHandOperand!==leftHandOperand&&rightHandOperand!==rightHandOperand?!0:isPrimitive(leftHandOperand)||isPrimitive(rightHandOperand)?!1: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{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;for(var index=-1;++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{return[]}return[]}__name(getIteratorEntries,"getIteratorEntries");function getGeneratorEntries(generator){for(var generatorResult=generator.next(),accumulator=[generatorResult.value];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){for(var keys=[],allKeys=Object.getOwnPropertySymbols(target),i=0;i<allKeys.length;i+=1){var key=allKeys[i];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)return iterableEqual(mapSymbols(leftHandKeys).sort(),mapSymbols(rightHandKeys).sort())===!1?!1:keysEqual(leftHandOperand,rightHandOperand,leftHandKeys,options);var leftHandEntries=getIteratorEntries(leftHandOperand),rightHandEntries=getIteratorEntries(rightHandOperand);return leftHandEntries.length&&leftHandEntries.length===rightHandEntries.length?(leftHandEntries.sort(),rightHandEntries.sort(),iterableEqual(leftHandEntries,rightHandEntries,options)):leftHandKeys.length===0&&leftHandEntries.length===0&&rightHandKeys.length===0&&rightHandEntries.length===0}__name(objectEqual,"objectEqual");function isPrimitive(value){return value===null||typeof value!="object"}__name(isPrimitive,"isPrimitive");function mapSymbols(arr){return arr.map(__name(function(entry){return typeof entry=="symbol"?entry.toString():entry},"mapSymbol"))}__name(mapSymbols,"mapSymbols");function hasProperty(obj,name){return typeof obj>"u"||obj===null?!1: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;return mArr?parsed={i:parseFloat(mArr[1])}:parsed={p:value.replace(/\\([.[\]])/g,"$1")},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];temporaryValue&&(typeof part.p>"u"?temporaryValue=temporaryValue[part.i]:temporaryValue=temporaryValue[part.p],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),expected===void 0&&_actual===void 0&&(showDiff=!1),config.showDiff!==!0&&(showDiff=!1),!ok){msg=getMessage2(this,arguments);let assertionErrorObjectProperties={actual:getActual(this,arguments),expected,showDiff},operator=getOperator(this,arguments);throw operator&&(assertionErrorObjectProperties.operator=operator),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(){!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){return fnLengthDesc.configurable&&Object.defineProperty(fn,"length",{get:__name(function(){throw Error(isChainable?"Invalid Chai property: "+assertionName+'.length. Due to a compatibility issue, "length" cannot directly follow "'+assertionName+'". Use "'+assertionName+'.lengthOf" instead.':"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){result.indexOf(property)===-1&&result.push(property)}__name(addProperty2,"addProperty");let proto=Object.getPrototypeOf(object);for(;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){return isProxyEnabled()?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;throw getProperties(target).forEach(function(prop){if(!Object.prototype.hasOwnProperty(prop)&&builtins.indexOf(prop)===-1){let dist=stringDistanceCapped(property,prop,suggestionDistance);dist<suggestionDistance&&(suggestion=prop,suggestionDistance=dist)}}),Error(suggestion!==null?"Invalid Chai property: "+property+'. Did you mean "'+suggestion+'"?':"Invalid Chai property: "+property)}return builtins.indexOf(property)===-1&&!flag(target,"lockSsfi")&&flag(target,"ssfi",proxyGetter),Reflect.get(target,property)},"proxyGetter")}):obj}__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(){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");_get&&typeof _get.get=="function"&&(_super=_get.get),Object.defineProperty(ctx,name,{get:__name(function overwritingPropertyGetter(){!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 new Error(name+" is not a function")},"_super");_method&&typeof _method=="function"&&(_super=_method);let overwritingMethodWrapper=__name(function(){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);return typeof propDesc!="object"?!0:!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){typeof chainingBehavior!="function"&&(chainingBehavior=__name(function(){},"chainingBehavior"));let chainableBehavior={method,chainingBehavior};ctx.__methods||(ctx.__methods={}),ctx.__methods[name]=chainableBehavior,Object.defineProperty(ctx,name,{get:__name(function(){chainableBehavior.chainingBehavior.call(this);let chainableMethodWrapper=__name(function(){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){return typeof Object.getOwnPropertySymbols!="function"?[]: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 isNaN22=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()),msg=msg||"",!msg||/\shave\s/.test(msg))return;let isObject=isObjectType(expected);return/\snot\s/.test(msg)?isObject?"notDeepStrictEqual":"notStrictEqual":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){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();functionTypes.function.includes(type3)?this.assert(functionTypes[type3].includes(detectedType),"expected #{this} to be "+article+type3,"expected #{this} not to be "+article+type3):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 isNaN22(a)&&isNaN22(b)||a===b}__name(SameValueZero,"SameValueZero");function includeChainingBehavior(){flag2(this,"contains",!0)}__name(includeChainingBehavior,"includeChainingBehavior");function include(val,msg){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":isDeep?obj.forEach(function(item){included=included||isEql(item,val)}):included=obj.has(val);break;case"array":isDeep?included=obj.some(function(item){return isEql(item,val)}):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;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"))});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"))});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"))});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(isNaN22(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,"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){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){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){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"),!doLength&&objType==="date"&&nType!=="date")throw new AssertionError(msgPrefix+"the argument to above must be a date",void 0,ssfi);if(!isNumeric(n)&&(doLength||isNumeric(obj)))throw new AssertionError(msgPrefix+"the argument to above must be a number",void 0,ssfi);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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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"),!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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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"),!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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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"),!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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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"),!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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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){throw err instanceof TypeError?(flagMsg=flagMsg?flagMsg+": ":"",new AssertionError(flagMsg+"The instanceof assertion needs a constructor but "+type(constructor)+" was given.",void 0,ssfi)):err}let name=getName(constructor);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){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)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="";isDeep&&(descriptor+="deep "),isOwn&&(descriptor+="own "),isNested&&(descriptor+="nested "),descriptor+="property ";let hasProperty2;isOwn?hasProperty2=Object.prototype.hasOwnProperty.call(obj,name):isNested?hasProperty2=pathInfo.exists:hasProperty2=hasProperty(obj,name),(!negate||arguments.length===1)&&this.assert(hasProperty2,"expected #{this} to have "+descriptor+inspect2(name),"expected #{this} to not have "+descriptor+inspect2(name)),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){typeof descriptor=="string"&&(msg=descriptor,descriptor=null),msg&&flag2(this,"message",msg);let obj=flag2(this,"object"),actualDescriptor=Object.getOwnPropertyDescriptor(Object(obj),name),eql=flag2(this,"eql");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):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){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){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){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")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),any&&(ok=expected.some(function(expectedKey){return actual.some(function(actualKey){return isEql(expectedKey,actualKey)})})),all&&(ok=expected.every(function(expectedKey){return actual.some(function(actualKey){return isEql(expectedKey,actualKey)})}),flag2(this,"contains")||(ok=ok&&keys.length==actual.length)),len>1){keys=keys.map(function(key){return inspect2(key)});let last=keys.pop();all&&(str=keys.join(", ")+", and "+last),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){msg&&flag2(this,"message",msg);let obj=flag2(this,"object"),ssfi=flag2(this,"ssfi"),flagMsg=flag2(this,"message"),negate=flag2(this,"negate")||!1;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=!!(errorLike&&errMsgMatcher),errorLikeFail=!1,errMsgMatcherFail=!1;if(everyArgIsUndefined||!everyArgIsUndefined&&!negate){let errorLikeString="an error";errorLike instanceof Error?errorLikeString="#{exp}":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{}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&&(errorLike instanceof Error&&check_error_exports.compatibleInstance(caughtErr,errorLike)===negate&&(everyArgIsDefined&&negate?errorLikeFail=!0: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())),check_error_exports.compatibleConstructor(caughtErr,errorLike)===negate&&(everyArgIsDefined&&negate?errorLikeFail=!0: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)))),caughtErr&&errMsgMatcher!==void 0&&errMsgMatcher!==null){let placeholder="including";isRegExp2(errMsgMatcher)&&(placeholder="matching"),check_error_exports.compatibleMessage(caughtErr,errMsgMatcher)===negate&&(everyArgIsDefined&&negate?errMsgMatcherFail=!0: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)))}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){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){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"),result)}__name(satisfy,"satisfy");Assertion.addMethod("satisfy",satisfy);Assertion.addMethod("satisfies",satisfy);function closeTo(expected,delta,msg){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);return matchIdx===-1?!1:(contains||superset.splice(matchIdx,1),!0)}return superset.some(function(elem2,matchIdx){return cmp(elem,elem2)?(contains||superset.splice(matchIdx,1),!0):!1})})}__name(isSubsetOf,"isSubsetOf");Assertion.addMethod("members",function(subset,msg){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;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}"):(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){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){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");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):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):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){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;prop?(new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop]):(new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject()),fn();let final=prop==null?subject():subject[prop],msgObj=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){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;prop?(new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop]):(new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject()),new Assertion(initial,flagMsg,ssfi,!0).is.a("number"),fn();let final=prop==null?subject():subject[prop],msgObj=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){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;prop?(new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop]):(new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject()),new Assertion(initial,flagMsg,ssfi,!0).is.a("number"),fn();let final=prop==null?subject():subject[prop],msgObj=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){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;behavior==="change"?expression=Math.abs(final-initial)===Math.abs(delta):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"),isFrozen2=obj===Object(obj)?Object.isFrozen(obj):!0;this.assert(isFrozen2,"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){return expected===actual?!0:typeof actual!=typeof expected?!1:typeof expected!="object"||expected===null?expected===actual:actual?Array.isArray(expected)?Array.isArray(actual)?expected.every(function(exp){return actual.some(function(act){return compareSubset(exp,act)})}):!1:expected instanceof Date?actual instanceof Date?expected.getTime()===actual.getTime():!1:Object.keys(expected).every(function(key){let expectedValue=expected[key],actualValue=actual[key];return typeof expectedValue=="object"&&expectedValue!==null&&actualValue!==null?compareSubset(expectedValue,actualValue):typeof expectedValue=="function"?expectedValue(actualValue):actualValue===expectedValue}):!1}__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){throw arguments.length<2&&(message=actual,actual=void 0),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(){return this instanceof String||this instanceof Number||this instanceof Boolean||typeof Symbol=="function"&&this instanceof Symbol||typeof BigInt=="function"&&this instanceof BigInt?new Assertion(this.valueOf(),null,shouldGetter):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){throw arguments.length<2&&(message=actual,actual=void 0),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){throw arguments.length<2&&(message=actual,actual=void 0),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 test22=new Assertion(act,msg,assert.equal,!0);test22.assert(exp==flag(test22,"object"),"expected #{this} to equal #{exp}","expected #{this} to not equal #{act}",exp,act,!0)};assert.notEqual=function(act,exp,msg){let test22=new Assertion(act,msg,assert.notEqual,!0);test22.assert(exp!=flag(test22,"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){(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){(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+": ",new AssertionError(msg+'Invalid operator "'+operator+'"',void 0,assert.operator)}let test22=new Assertion(ok,msg,assert.operator,!0);test22.assert(flag(test22,"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,set22,msg){new Assertion(set1,msg,assert.sameMembers,!0).to.have.same.members(set22)};assert.notSameMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.notSameMembers,!0).to.not.have.same.members(set22)};assert.sameDeepMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.sameDeepMembers,!0).to.have.same.deep.members(set22)};assert.notSameDeepMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.notSameDeepMembers,!0).to.not.have.same.deep.members(set22)};assert.sameOrderedMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.sameOrderedMembers,!0).to.have.same.ordered.members(set22)};assert.notSameOrderedMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.notSameOrderedMembers,!0).to.not.have.same.ordered.members(set22)};assert.sameDeepOrderedMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.sameDeepOrderedMembers,!0).to.have.same.deep.ordered.members(set22)};assert.notSameDeepOrderedMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.notSameDeepOrderedMembers,!0).to.not.have.same.deep.ordered.members(set22)};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){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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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 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};return~used.indexOf(fn)||(fn(exports,utils_exports),used.push(fn)),exports}__name(use,"use");function jestMatchers(chai,utils){let A=chai.Assertion,m=(name,fn)=>A.addMethod(name,fn);m("toBe",function(expected){this.assert(Object.is(this._obj,expected),"expected #{this} to be #{exp}","expected #{this} not to be #{exp}",expected,this._obj)}),m("toEqual",function(expected){this.assert(utils.eql(this._obj,expected),"expected #{this} to deeply equal #{exp}","expected #{this} not to deeply equal #{exp}",expected,this._obj,!0)}),m("toBeTruthy",function(){this.assert(!!this._obj,"expected #{this} to be truthy","expected #{this} not to be truthy")}),m("toBeFalsy",function(){this.assert(!this._obj,"expected #{this} to be falsy","expected #{this} not to be falsy")}),m("toBeNull",function(){this.assert(this._obj===null,"expected #{this} to be null","expected #{this} not to be null")}),m("toBeUndefined",function(){this.assert(this._obj===void 0,"expected #{this} to be undefined","expected #{this} not to be undefined")}),m("toBeDefined",function(){this.assert(this._obj!==void 0,"expected #{this} to be defined","expected #{this} to be undefined")}),m("toBeNaN",function(){this.assert(Number.isNaN(this._obj),"expected #{this} to be NaN","expected #{this} not to be NaN")});let compare=(name,op,word)=>m(name,function(expected){this.assert(op(this._obj,expected),`expected #{this} to be ${word} #{exp}`,`expected #{this} not to be ${word} #{exp}`,expected)});compare("toBeGreaterThan",(a,b)=>a>b,"greater than"),compare("toBeGreaterThanOrEqual",(a,b)=>a>=b,"greater than or equal to"),compare("toBeLessThan",(a,b)=>a<b,"less than"),compare("toBeLessThanOrEqual",(a,b)=>a<=b,"less than or equal to"),m("toBeCloseTo",function(expected,numDigits=2){let pass=Math.abs(expected-this._obj)<10**-numDigits/2;this.assert(pass,`expected #{this} to be close to #{exp} (${numDigits} digits)`,`expected #{this} not to be close to #{exp} (${numDigits} digits)`,expected)}),m("toContain",function(item){let obj=this._obj,ok=typeof obj=="string"?obj.includes(item):Array.from(obj).includes(item);this.assert(ok,"expected #{this} to contain #{exp}","expected #{this} not to contain #{exp}",item)}),m("toHaveLength",function(length){let actual=this._obj==null?void 0:this._obj.length;this.assert(actual===length,"expected #{this} to have length #{exp}","expected #{this} not to have length #{exp}",length,actual)}),m("toMatch",function(expected){let obj=this._obj,ok=expected instanceof RegExp?expected.test(obj):String(obj).includes(expected);this.assert(ok,"expected #{this} to match #{exp}","expected #{this} not to match #{exp}",expected)}),m("toHaveProperty",function(path,...rest){let keys=Array.isArray(path)?path:String(path).split("."),cur=this._obj,found=!0;for(let k of keys)if(cur!=null&&k in Object(cur))cur=cur[k];else{found=!1;break}let pass=found&&(rest.length===0||utils.eql(cur,rest[0]));this.assert(pass,"expected #{this} to have property #{exp}","expected #{this} not to have property #{exp}",path)}),m("toBeInstanceOf",function(ctor){this.assert(this._obj instanceof ctor,"expected #{this} to be an instance of #{exp}","expected #{this} not to be an instance of #{exp}",ctor.name??ctor)}),m("toThrow",function(expected){let a=new chai.Assertion(this._obj);utils.flag(this,"negate")?expected===void 0?a.to.not.throw():a.to.not.throw(expected):expected===void 0?a.to.throw():a.to.throw(expected)})}use(jestMatchers);var isPlainObject=value=>{if(value===null||typeof value!="object")return!1;let proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null},seqSize=seq=>seq==null?0:typeof seq.length=="number"?seq.length:typeof seq.size=="number"?seq.size:isPlainObject(seq)?Object.keys(seq).length:0,seqGet=(seq,key,dval=null)=>seq==null?dval:seq instanceof Map?seq.has(key)?seq.get(key):dval:seq instanceof Set?seq.has(key)?key:dval:Object.hasOwn(seq,key)?seq[key]:typeof seq.get=="function"?seq.get(key,dval):dval,isIndexedSeq=seq=>Array.isArray(seq),isKeyedSeq=seq=>seq instanceof Map||isPlainObject(seq),isSetSeq=seq=>seq instanceof Set;function*seqEntries(seq){if(seq instanceof Map)yield*seq.entries();else if(seq instanceof Set)for(let value of seq)yield[value,value];else if(isPlainObject(seq))yield*Object.entries(seq);else if(Array.isArray(seq))for(let i=0;i<seq.length;i++)yield[i,seq[i]]}var NOTHING=Symbol.for("immer-nothing"),DRAFTABLE=Symbol.for("immer-draftable"),DRAFT_STATE=Symbol.for("immer-state"),errors=[function(plugin){return`The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`},function(thing){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`},"This object has been frozen and should not be mutated",function(data){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+data},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(thing){return`'current' expects a draft, got: ${thing}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(thing){return`'original' expects a draft, got: ${thing}`}];function die(error,...args){{let e=errors[error],msg=typeof e=="function"?e.apply(null,args):e;throw new Error(`[Immer] ${msg}`)}throw new Error(`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`)}var getPrototypeOf=Object.getPrototypeOf;function isDraft(value){return!!value&&!!value[DRAFT_STATE]}function isDraftable(value){return value?isPlainObject2(value)||Array.isArray(value)||!!value[DRAFTABLE]||!!value.constructor?.[DRAFTABLE]||isMap(value)||isSet(value):!1}var objectCtorString=Object.prototype.constructor.toString(),cachedCtorStrings=new WeakMap;function isPlainObject2(value){if(!value||typeof value!="object")return!1;let proto=Object.getPrototypeOf(value);if(proto===null||proto===Object.prototype)return!0;let Ctor=Object.hasOwnProperty.call(proto,"constructor")&&proto.constructor;if(Ctor===Object)return!0;if(typeof Ctor!="function")return!1;let ctorString=cachedCtorStrings.get(Ctor);return ctorString===void 0&&(ctorString=Function.toString.call(Ctor),cachedCtorStrings.set(Ctor,ctorString)),ctorString===objectCtorString}function each(obj,iter,strict=!0){getArchtype(obj)===0?(strict?Reflect.ownKeys(obj):Object.keys(obj)).forEach(key=>{iter(key,obj[key],obj)}):obj.forEach((entry,index)=>iter(index,entry,obj))}function getArchtype(thing){let state=thing[DRAFT_STATE];return state?state.type_:Array.isArray(thing)?1:isMap(thing)?2:isSet(thing)?3:0}function has(thing,prop){return getArchtype(thing)===2?thing.has(prop):Object.prototype.hasOwnProperty.call(thing,prop)}function set2(thing,propOrOldValue,value){let t=getArchtype(thing);t===2?thing.set(propOrOldValue,value):t===3?thing.add(value):thing[propOrOldValue]=value}function is(x,y){return x===y?x!==0||1/x===1/y:x!==x&&y!==y}function isMap(target){return target instanceof Map}function isSet(target){return target instanceof Set}function latest(state){return state.copy_||state.base_}function shallowCopy(base,strict){if(isMap(base))return new Map(base);if(isSet(base))return new Set(base);if(Array.isArray(base))return Array.prototype.slice.call(base);let isPlain=isPlainObject2(base);if(strict===!0||strict==="class_only"&&!isPlain){let descriptors=Object.getOwnPropertyDescriptors(base);delete descriptors[DRAFT_STATE];let keys=Reflect.ownKeys(descriptors);for(let i=0;i<keys.length;i++){let key=keys[i],desc=descriptors[key];desc.writable===!1&&(desc.writable=!0,desc.configurable=!0),(desc.get||desc.set)&&(descriptors[key]={configurable:!0,writable:!0,enumerable:desc.enumerable,value:base[key]})}return Object.create(getPrototypeOf(base),descriptors)}else{let proto=getPrototypeOf(base);if(proto!==null&&isPlain)return{...base};let obj=Object.create(proto);return Object.assign(obj,base)}}function freeze(obj,deep=!1){return isFrozen(obj)||isDraft(obj)||!isDraftable(obj)||(getArchtype(obj)>1&&Object.defineProperties(obj,{set:dontMutateMethodOverride,add:dontMutateMethodOverride,clear:dontMutateMethodOverride,delete:dontMutateMethodOverride}),Object.freeze(obj),deep&&Object.values(obj).forEach(value=>freeze(value,!0))),obj}function dontMutateFrozenCollections(){die(2)}var dontMutateMethodOverride={value:dontMutateFrozenCollections};function isFrozen(obj){return obj===null||typeof obj!="object"?!0:Object.isFrozen(obj)}var plugins={};function getPlugin(pluginKey){let plugin=plugins[pluginKey];return plugin||die(0,pluginKey),plugin}var currentScope;function getCurrentScope(){return currentScope}function createScope(parent_,immer_){return{drafts_:[],parent_,immer_,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function usePatchesInScope(scope,patchListener){patchListener&&(getPlugin("Patches"),scope.patches_=[],scope.inversePatches_=[],scope.patchListener_=patchListener)}function revokeScope(scope){leaveScope(scope),scope.drafts_.forEach(revokeDraft),scope.drafts_=null}function leaveScope(scope){scope===currentScope&&(currentScope=scope.parent_)}function enterScope(immer2){return currentScope=createScope(currentScope,immer2)}function revokeDraft(draft){let state=draft[DRAFT_STATE];state.type_===0||state.type_===1?state.revoke_():state.revoked_=!0}function processResult(result,scope){scope.unfinalizedDrafts_=scope.drafts_.length;let baseDraft=scope.drafts_[0];return result!==void 0&&result!==baseDraft?(baseDraft[DRAFT_STATE].modified_&&(revokeScope(scope),die(4)),isDraftable(result)&&(result=finalize(scope,result),scope.parent_||maybeFreeze(scope,result)),scope.patches_&&getPlugin("Patches").generateReplacementPatches_(baseDraft[DRAFT_STATE].base_,result,scope.patches_,scope.inversePatches_)):result=finalize(scope,baseDraft,[]),revokeScope(scope),scope.patches_&&scope.patchListener_(scope.patches_,scope.inversePatches_),result!==NOTHING?result:void 0}function finalize(rootScope,value,path){if(isFrozen(value))return value;let useStrictIteration=rootScope.immer_.shouldUseStrictIteration(),state=value[DRAFT_STATE];if(!state)return each(value,(key,childValue)=>finalizeProperty(rootScope,state,value,key,childValue,path),useStrictIteration),value;if(state.scope_!==rootScope)return value;if(!state.modified_)return maybeFreeze(rootScope,state.base_,!0),state.base_;if(!state.finalized_){state.finalized_=!0,state.scope_.unfinalizedDrafts_--;let result=state.copy_,resultEach=result,isSet2=!1;state.type_===3&&(resultEach=new Set(result),result.clear(),isSet2=!0),each(resultEach,(key,childValue)=>finalizeProperty(rootScope,state,result,key,childValue,path,isSet2),useStrictIteration),maybeFreeze(rootScope,result,!1),path&&rootScope.patches_&&getPlugin("Patches").generatePatches_(state,path,rootScope.patches_,rootScope.inversePatches_)}return state.copy_}function finalizeProperty(rootScope,parentState,targetObject,prop,childValue,rootPath,targetIsSet){if(childValue==null||typeof childValue!="object"&&!targetIsSet)return;let childIsFrozen=isFrozen(childValue);if(!(childIsFrozen&&!targetIsSet)){if(childValue===targetObject&&die(5),isDraft(childValue)){let path=rootPath&&parentState&&parentState.type_!==3&&!has(parentState.assigned_,prop)?rootPath.concat(prop):void 0,res=finalize(rootScope,childValue,path);if(set2(targetObject,prop,res),isDraft(res))rootScope.canAutoFreeze_=!1;else return}else targetIsSet&&targetObject.add(childValue);if(isDraftable(childValue)&&!childIsFrozen){if(!rootScope.immer_.autoFreeze_&&rootScope.unfinalizedDrafts_<1||parentState&&parentState.base_&&parentState.base_[prop]===childValue&&childIsFrozen)return;finalize(rootScope,childValue),(!parentState||!parentState.scope_.parent_)&&typeof prop!="symbol"&&(isMap(targetObject)?targetObject.has(prop):Object.prototype.propertyIsEnumerable.call(targetObject,prop))&&maybeFreeze(rootScope,childValue)}}}function maybeFreeze(scope,value,deep=!1){!scope.parent_&&scope.immer_.autoFreeze_&&scope.canAutoFreeze_&&freeze(value,deep)}function createProxyProxy(base,parent){let isArray=Array.isArray(base),state={type_:isArray?1:0,scope_:parent?parent.scope_:getCurrentScope(),modified_:!1,finalized_:!1,assigned_:{},parent_:parent,base_:base,draft_:null,copy_:null,revoke_:null,isManual_:!1},target=state,traps=objectTraps;isArray&&(target=[state],traps=arrayTraps);let{revoke,proxy}=Proxy.revocable(target,traps);return state.draft_=proxy,state.revoke_=revoke,proxy}var objectTraps={get(state,prop){if(prop===DRAFT_STATE)return state;let source=latest(state);if(!has(source,prop))return readPropFromProto(state,source,prop);let value=source[prop];return state.finalized_||!isDraftable(value)?value:value===peek(state.base_,prop)?(prepareCopy(state),state.copy_[prop]=createProxy(value,state)):value},has(state,prop){return prop in latest(state)},ownKeys(state){return Reflect.ownKeys(latest(state))},set(state,prop,value){let desc=getDescriptorFromProto(latest(state),prop);if(desc?.set)return desc.set.call(state.draft_,value),!0;if(!state.modified_){let current2=peek(latest(state),prop),currentState=current2?.[DRAFT_STATE];if(currentState&¤tState.base_===value)return state.copy_[prop]=value,state.assigned_[prop]=!1,!0;if(is(value,current2)&&(value!==void 0||has(state.base_,prop)))return!0;prepareCopy(state),markChanged(state)}return state.copy_[prop]===value&&(value!==void 0||prop in state.copy_)||Number.isNaN(value)&&Number.isNaN(state.copy_[prop])||(state.copy_[prop]=value,state.assigned_[prop]=!0),!0},deleteProperty(state,prop){return peek(state.base_,prop)!==void 0||prop in state.base_?(state.assigned_[prop]=!1,prepareCopy(state),markChanged(state)):delete state.assigned_[prop],state.copy_&&delete state.copy_[prop],!0},getOwnPropertyDescriptor(state,prop){let owner=latest(state),desc=Reflect.getOwnPropertyDescriptor(owner,prop);return desc&&{writable:!0,configurable:state.type_!==1||prop!=="length",enumerable:desc.enumerable,value:owner[prop]}},defineProperty(){die(11)},getPrototypeOf(state){return getPrototypeOf(state.base_)},setPrototypeOf(){die(12)}},arrayTraps={};each(objectTraps,(key,fn)=>{arrayTraps[key]=function(){return arguments[0]=arguments[0][0],fn.apply(this,arguments)}});arrayTraps.deleteProperty=function(state,prop){return isNaN(parseInt(prop))&&die(13),arrayTraps.set.call(this,state,prop,void 0)};arrayTraps.set=function(state,prop,value){return prop!=="length"&&isNaN(parseInt(prop))&&die(14),objectTraps.set.call(this,state[0],prop,value,state[0])};function peek(draft,prop){let state=draft[DRAFT_STATE];return(state?latest(state):draft)[prop]}function readPropFromProto(state,source,prop){let desc=getDescriptorFromProto(source,prop);return desc?"value"in desc?desc.value:desc.get?.call(state.draft_):void 0}function getDescriptorFromProto(source,prop){if(!(prop in source))return;let proto=getPrototypeOf(source);for(;proto;){let desc=Object.getOwnPropertyDescriptor(proto,prop);if(desc)return desc;proto=getPrototypeOf(proto)}}function markChanged(state){state.modified_||(state.modified_=!0,state.parent_&&markChanged(state.parent_))}function prepareCopy(state){state.copy_||(state.copy_=shallowCopy(state.base_,state.scope_.immer_.useStrictShallowCopy_))}var Immer2=class{constructor(config2){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(base,recipe,patchListener)=>{if(typeof base=="function"&&typeof recipe!="function"){let defaultBase=recipe;recipe=base;let self=this;return function(base2=defaultBase,...args){return self.produce(base2,draft=>recipe.call(this,draft,...args))}}typeof recipe!="function"&&die(6),patchListener!==void 0&&typeof patchListener!="function"&&die(7);let result;if(isDraftable(base)){let scope=enterScope(this),proxy=createProxy(base,void 0),hasError=!0;try{result=recipe(proxy),hasError=!1}finally{hasError?revokeScope(scope):leaveScope(scope)}return usePatchesInScope(scope,patchListener),processResult(result,scope)}else if(!base||typeof base!="object"){if(result=recipe(base),result===void 0&&(result=base),result===NOTHING&&(result=void 0),this.autoFreeze_&&freeze(result,!0),patchListener){let p=[],ip=[];getPlugin("Patches").generateReplacementPatches_(base,result,p,ip),patchListener(p,ip)}return result}else die(1,base)},this.produceWithPatches=(base,recipe)=>{if(typeof base=="function")return(state,...args)=>this.produceWithPatches(state,draft=>base(draft,...args));let patches,inversePatches;return[this.produce(base,recipe,(p,ip)=>{patches=p,inversePatches=ip}),patches,inversePatches]},typeof config2?.autoFreeze=="boolean"&&this.setAutoFreeze(config2.autoFreeze),typeof config2?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(config2.useStrictShallowCopy),typeof config2?.useStrictIteration=="boolean"&&this.setUseStrictIteration(config2.useStrictIteration)}createDraft(base){isDraftable(base)||die(8),isDraft(base)&&(base=current(base));let scope=enterScope(this),proxy=createProxy(base,void 0);return proxy[DRAFT_STATE].isManual_=!0,leaveScope(scope),proxy}finishDraft(draft,patchListener){let state=draft&&draft[DRAFT_STATE];(!state||!state.isManual_)&&die(9);let{scope_:scope}=state;return usePatchesInScope(scope,patchListener),processResult(void 0,scope)}setAutoFreeze(value){this.autoFreeze_=value}setUseStrictShallowCopy(value){this.useStrictShallowCopy_=value}setUseStrictIteration(value){this.useStrictIteration_=value}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(base,patches){let i;for(i=patches.length-1;i>=0;i--){let patch=patches[i];if(patch.path.length===0&&patch.op==="replace"){base=patch.value;break}}i>-1&&(patches=patches.slice(i+1));let applyPatchesImpl=getPlugin("Patches").applyPatches_;return isDraft(base)?applyPatchesImpl(base,patches):this.produce(base,draft=>applyPatchesImpl(draft,patches))}};function createProxy(value,parent){let draft=isMap(value)?getPlugin("MapSet").proxyMap_(value,parent):isSet(value)?getPlugin("MapSet").proxySet_(value,parent):createProxyProxy(value,parent);return(parent?parent.scope_:getCurrentScope()).drafts_.push(draft),draft}function current(value){return isDraft(value)||die(10,value),currentImpl(value)}function currentImpl(value){if(!isDraftable(value)||isFrozen(value))return value;let state=value[DRAFT_STATE],copy,strict=!0;if(state){if(!state.modified_)return state.base_;state.finalized_=!0,copy=shallowCopy(value,state.scope_.immer_.useStrictShallowCopy_),strict=state.scope_.immer_.shouldUseStrictIteration()}else copy=shallowCopy(value,!0);return each(copy,(key,childValue)=>{set2(copy,key,currentImpl(childValue))},strict),state&&(state.finalized_=!1),copy}var immer=new Immer2,produce=immer.produce;var NONE=Symbol("NONE"),readKey=(value,key,dval=null)=>value==null?dval:value instanceof Map?value.has(key)?value.get(key):dval:value instanceof Set?value.has(key)?key:dval:Object.hasOwn(value,key)?value[key]:dval,writeKey=(value,key,next)=>{value instanceof Map?value.set(key,next):value instanceof Set?(value.delete(key),value.add(next)):value[key]=next},writeSeqKey=(value,key,next)=>{value instanceof Map||value instanceof Set||Array.isArray(value)||Object.hasOwn(value,key)?writeKey(value,key,next):typeof value?.set=="function"?value.set(key,next):writeKey(value,key,next)},Step=class{lookup(_v,dval=null){return dval}setDraftValue(_root,_v){}enterFrame(stack,next){return stack.enter(next,{},!0)}toAbstractPathStep(){return this}pinKey(_v){return this}toKey(){return null}},BindStep=class _BindStep extends Step{constructor(binds){super(),this.binds=binds}lookup(v,_dval){return v}enterFrame(stack,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}},ScopeBindStep=class _ScopeBindStep extends BindStep{constructor(val,binds={}){super(binds),this.val=val}enterFrame(stack,next){let dyn=this.val.evalAsHandler(stack)?.call(stack.it)??{};return stack.enter(next,{...this.binds,...dyn},!1)}withIndex(i){return new _ScopeBindStep(this.val,{...this.binds,key:i})}withKey(key){return new _ScopeBindStep(this.val,{...this.binds,key})}},FieldStep=class extends Step{constructor(field){super(),this.field=field}lookup(v,dval=null){return readKey(v,this.field,dval)}setDraftValue(root,v){writeKey(root,this.field,v)}withIndex(i){return new SeqStep(this.field,i)}withKey(k){return new SeqStep(this.field,k)}toKey(){return{field:this.field}}},SeqStep=class extends Step{constructor(field,key){super(),this.field=field,this.key=key}lookup(v,dval=null){return seqGet(readKey(v,this.field,null),this.key,dval)}setDraftValue(root,v){let seq=readKey(root,this.field,null);seq!=null&&writeSeqKey(seq,this.key,v)}enterFrame(stack,next){return stack.enter(next,{key:this.key},!0)}toKey(){return{field:this.field,key:this.key}}},SeqAccessStep=class extends Step{constructor(seqField,keyField){super(),this.seqField=seqField,this.keyField=keyField}lookup(v,dval=null){let seq=readKey(v,this.seqField,NONE),key=readKey(v,this.keyField,NONE);return key!==NONE&&seq!==NONE?seqGet(seq,key,dval):dval}setDraftValue(root,v){let seq=readKey(root,this.seqField,NONE),key=readKey(root,this.keyField,NONE);seq!==NONE&&key!==NONE&&writeSeqKey(seq,key,v)}pinKey(v){let key=readKey(v,this.keyField,NONE);return key===NONE?this:new SeqStep(this.seqField,key)}toKey(){return{field:this.seqField}}},EachBindStep=class extends Step{constructor(iterInfo,key){super(),this.iterInfo=iterInfo,this.key=key}lookup(v,_dval){return v}enterFrame(stack,next){return stack.enter(next,this.iterInfo.enrichBinds(stack,this.key),!1)}toAbstractPathStep(){return null}},EachRenderItStep=class extends SeqStep{enterFrame(stack,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)}var DynStep=class 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}enterFrame(stack,_next){return warnRawDynStep("enterFrame",this),stack}},DynEachStep=class 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];return last instanceof FieldStep?producerSteps.slice(0,-1).concat(new SeqStep(last.field,key)):(console.warn("DynEachStep: seq-access dynamic cannot be iterated",this),producerSteps)}},Path=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();s!==null&&(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){for(;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)}pinKeys(root){let curVal=root,out=null;for(let i=0;i<this.steps.length;i++){let step=this.steps[i],pinned=step.pinKey(curVal);if(pinned!==step&&((out??=this.steps.slice())[i]=pinned),curVal=step.lookup(curVal,NONE),curVal===NONE)break}return out?new _Path(out):this}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}resolveChain(root){let out=[root],curVal=root;for(let step of this.steps){if(curVal=step.lookup(curVal,NONE),curVal===NONE)break;out.push(curVal)}return out}toKeys(){let out=[];for(let step of this.steps){let k=step.toKey();k!==null&&out.push(k)}return out}setValue(root,v){return this.steps.length===0?v:produce(root,draft=>{let parent=draft;for(let i=0;i<this.steps.length-1;i++)if(parent=this.steps[i].lookup(parent,NONE),parent===NONE)return;this.steps.at(-1).setDraftValue(parent,v)})}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,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,crossComponent=(cidNum,vid)=>{let 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!1}else 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);step&&(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--)pendingDyns[i].producerCompId===cidNum&&pendingDyns.splice(i,1);return eventIds=[],nodeIds=[],!0};for(;node&&node!==rootNode&&depth<maxDepth;){if(node?.dataset){let{eid,cid,vid}=node.dataset;eid!==void 0&&eventIds.push(eid);let metas=metaChain(node.previousSibling),sawComp=!1;for(let m of metas)if(m.$==="Comp"){if(sawComp=!0,!crossComponent(m.cid,m.vid))return NO_EVENT_INFO;nodeIds.push({nid:m.nid})}else nodeIds.push({nid:m.nid,si:m.si,sk:m.sk});if(!sawComp&&cid!==void 0&&!crossComponent(+cid,vid))return NO_EVENT_INFO}depth+=1,node=node.parentNode}return pendingDyns.length>0&&console.warn("event reconstruction: dynamic-var producer not found",pendingDyns),[new _Path(pathSteps.reverse()),handlers]}};function metaChain(n){let out=[];for(;n?.nodeType===8&&n.textContent[0]==="§";){try{out.push(JSON.parse(n.textContent.slice(1,-1)))}catch(err){console.warn(err,n)}n=n.previousSibling}return out}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}var StepCtx=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;return m.si!==void 0?pi.withIndex(+m.si):m.sk!==void 0?pi.withKey(m.sk):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"]),PathBuilder=class{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 isMac=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac");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_SEQ=256,K_METHOD=1024,K_EVENT=2048,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_PROVIDE=K_FIELD|K_SEQ,G_FIELD=K_FIELD|K_METHOD|K_CONST|K_SEQ,G_VALUE=K_FIELD|K_METHOD|K_BIND|K_DYN|K_NAME|K_CONST,G_HANDLER_ARG=G_VALUE&~K_NAME|K_EVENT,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:isPlainObject(v)?Object.keys(v).length:null}var 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}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)=>Object.is(a,b)}};function 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))):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 _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=parseToken(tokens[0],px);return val instanceof ConstVal&&(val.fromMacroVar=!0),val}return px.onParseIssue("bad-value",{role:"macro-var",name,value:s}),null}case 36:return mkVal(s.slice(1),MethodVal);case 64:{let dot=s.indexOf(".",1);if(dot===-1)return mkVal(s.slice(1),BindVal);let name=s.slice(1,dot),member=s.slice(dot+1);return isValidValId(name)&&isValidValId(member)?new BindMemberVal(name,member):null}case 42:return mkVal(s.slice(1),DynVal);case 46:return mkVal(s.slice(1),FieldVal)}let num=VALID_FLOAT_RE.test(s)?parseFloat(s):null;return Number.isFinite(num)?new ConstVal(num):s==="true"||s==="false"?new ConstVal(s==="true"):c0===101&&/^e(\.[a-zA-Z][a-zA-Z0-9_]*)+$/.exec(s)!==null?new EventMemberVal(s.split(".").slice(1)):c0>=97&&c0<=122?mkVal(s,NameVal):null}function _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=parseToken(s.slice(0,open),px),right=parseToken(s.slice(open+1,close),px);return left instanceof FieldVal&&right instanceof FieldVal?new SeqAccessVal(left,right):null}function _parseSingle(s,px,group){let tokens=tokenizeValue(s.trim());if(tokens.length!==1)return null;let val=parseToken(tokens[0],px);return val!==null&&kindOf(val)&group?val:null}function parseBool(s,px){let t=s.trim(),tokens=tokenizeValue(t);if(tokens.length!==1)return tokens.length===0?null:_parsePredicate(t,tokens,px);let val=parseToken(tokens[0],px);return val!==null&&kindOf(val)&G_BOOL?val:null}function parseText(s,px){return _parseSingle(s,px,G_TEXT)}function parseComponent(s,px){return _parseSingle(s,px,G_COMPONENT)}function parseSequence(s,px){return _parseSingle(s,px,G_SEQUENCE)}function parseField(s,px){return _parseSingle(s,px,G_FIELD)}function parseProvide(s,px){return _parseSingle(s,px,G_PROVIDE)}function parseMacroAttr(s,px){return _parseSingle(s,px,G_ALL)}function parseReceiveHandler(s,px){return _parseHandler(s,px,"receive",!0,!0,!1)}function parseAlterHandler(s,px){let r=_parseHandler(s,px,"alter",!1,!1,!0);return r===null?null:r.handlerVal}function _parseHandler(s,px,namespace,allowArgs,report,allowMethod){let tokens=tokenizeValue(s.trim()),headTok=tokens[0]??"",head=headTok===""?null:parseToken(headTok,px),hk=kindOf(head),handlerVal;if(hk&K_METHOD&&allowMethod)handlerVal=head;else{if(hk&K_METHOD)return report&&px.onParseIssue("event-method-handler",{name:head.name,role:"handler-name",value:headTok}),null;if(hk&K_NAME)handlerVal=new HandlerNameVal(head.name,namespace);else return report&&px.onParseIssue("bad-value",{role:"handler-name",value:headTok}),null}if(!allowArgs)return tokens.length===1?{handlerVal,args:[]}:null;let args=new Array(tokens.length-1);for(let i=1;i<tokens.length;i++){let val=parseToken(tokens[i],px);val!==null&&kindOf(val)&G_HANDLER_ARG?args[i-1]=val:(report&&px.onParseIssue("bad-value",{role:"handler-arg",value:tokens[i]}),args[i-1]=NULL_CONST_VAL)}return{handlerVal,args}}function _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=new Array(arity);for(let i=0;i<arity;i++){let tok=tokens[i+1],val=parseToken(tok,px);if(val===null||!(kindOf(val)&G_BOOL))return px.onParseIssue("bad-value",{role:"predicate-arg",value:tok}),null;args[i]=val}return new PredicateVal(pred,args)}function kindOf(val){return val===null?0:val instanceof ConstVal||val instanceof StrTplVal?val.kind:val instanceof SeqAccessVal?K_SEQ:val instanceof FieldVal?K_FIELD:val instanceof MethodVal?K_METHOD:val instanceof BindVal?K_BIND:val instanceof DynVal?K_DYN:val instanceof NameVal?K_NAME:val instanceof EventMemberVal?K_EVENT:0}var BaseVal=class{render(_stack,_rx){}eval(_stack){}toPathItem(){return null}evalAsHandler(stack){return this.eval(stack)}},ConstVal=class 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}`}},NULL_CONST_VAL=new ConstVal(null),PredicateVal=class extends BaseVal{constructor(pred,args){super(),this.pred=pred,this.args=args}eval(stack){let n=this.args.length,vals=new 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(" ")}`}},VarVal=class extends BaseVal{},StrTplVal=class _StrTplVal extends VarVal{constructor(vals){super(),this.vals=vals,this.kind=this.isLiteral()?K_CONST:K_STRTPL}isLiteral(){for(let v of this.vals)if(!(v instanceof ConstVal)||v.fromMacroVar)return!1;return!0}render(stack,_rx){return this.eval(stack)}eval(stack){let strs=new Array(this.vals.length);for(let i=0;i<this.vals.length;i++)strs[i]=this.vals[i]?.eval(stack,"");return strs.join("")}toLiteralSource(){if(!this.isLiteral())return null;let out="";for(let v of this.vals)out+=v.val;return new ConstVal(out).toString()}static parse(s,px){let parts=unescapeStr(s).split(STR_TPL_SPLIT_RE),vals=new Array(parts.length);for(let i=0;i<parts.length;i++){let part=parts[i],isExpr=part[0]==="{"&&part.at(-1)==="}";vals[i]=isExpr?parseText(part.slice(1,-1),px):new ConstVal(part)}let lo=0,hi=vals.length,isTrimmable=v=>v instanceof ConstVal&&v.val===""&&!v.fromMacroVar;for(;lo<hi&&isTrimmable(vals[lo]);)lo++;for(;hi>lo&&isTrimmable(vals[hi-1]);)hi--;return new _StrTplVal(lo===0&&hi===vals.length?vals:vals.slice(lo,hi))}},NameVal=class extends VarVal{constructor(name){super(),this.name=name}toString(){return this.name}},HandlerNameVal=class extends NameVal{constructor(name,namespace){super(name),this.namespace=namespace}eval(stack){return stack.getHandlerFor(this.name,this.namespace)??mk404Handler(stack,this.namespace,this.name)}},mk404Handler=(stack,type3,name)=>function(...args){let transactor=stack?.ctx?.transactor;return transactor?transactor.refuse("NO_HANDLER",{namespace:type3,name,argCount:args.length}):console.warn("handler not found",{type:type3,name}),this},keyIs=k=>e=>e.key===k,macCtrl=e=>isMac&&e.metaKey||e.ctrlKey,nullSafe=fn=>(e,stack)=>{let info=stack.lookupDragInfo();return info==null?null:fn(info)},EVENT_CONVENIENCES={value:e=>getValue(e),valueAsInt:e=>toNullIfNaN(parseInt(getValue(e),10)),valueAsFloat:e=>toNullIfNaN(parseFloat(getValue(e))),isAlt:e=>e.altKey,isShift:e=>e.shiftKey,isCtrl:macCtrl,isCmd:macCtrl,isUpKey:keyIs("ArrowUp"),isDownKey:keyIs("ArrowDown"),isSend:keyIs("Enter"),isCancel:keyIs("Escape"),isTabKey:keyIs("Tab"),dragInfo:(_e,stack)=>stack.lookupDragInfo(),dragType:nullSafe(info=>info.type),dragValue:nullSafe(info=>info.val),dragKey:nullSafe(info=>info.lookupBind("key"))},EventMemberVal=class extends BaseVal{constructor(members){super(),this.members=members}eval(stack){let e=stack.lookupEvent();if(e==null)return null;if(this.members.length===1){let convenience=EVENT_CONVENIENCES[this.members[0]];if(convenience!==void 0)return convenience(e,stack)}let v=e;for(let member of this.members){if(v==null)return null;v=v[member]}return v??null}toString(){return`e.${this.members.join(".")}`}},RenderVal=class extends BaseVal{render(stack,_rx){return this.eval(stack)}},RenderNameVal=class extends RenderVal{constructor(name){super(),this.name=name}},BindVal=class extends RenderNameVal{eval(stack){return stack.lookupBind(this.name)}toString(){return`@${this.name}`}},BindMemberVal=class extends BindVal{constructor(name,member){super(name),this.member=member}eval(stack){let v=stack.lookupBind(this.name);return seqGet(v,this.member,null)}toString(){return`@${this.name}.${this.member}`}},DynVal=class extends RenderNameVal{eval(stack){return stack.lookupDynamic(this.name)}toString(){return`*${this.name}`}},FieldVal=class extends RenderNameVal{eval(stack){return stack.lookupFieldRaw(this.name)}toPathItem(){return new FieldStep(this.name)}toString(){return`.${this.name}`}},MethodVal=class extends RenderNameVal{eval(stack){return stack.lookupMethod(this.name)}evalAsHandler(stack){return stack.lookupFieldRaw(this.name)}toString(){return`$${this.name}`}},SeqAccessVal=class 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 seqGet(this.seqVal.eval(stack),key,null)}toString(){return`${this.seqVal}[${this.keyVal}]`}};var Attributes=class{constructor(items){this.items=items}static parse(attributes,px,parseAll=!1){return new AttrParser(px).parse(attributes,parseAll)}isConstant(){return!1}},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(","));function parseDirectiveValue(px,directiveName,source,parser){let val=parser(source,px);return val===null&&px.onParseIssue("bad-value",{role:"directive",directive:directiveName,value:source}),val}function parseIterationDirectives(attributes,px){let parseNamed=name=>{let attr=attributes.getNamedItem(`@${name}`);return attr?parseDirectiveValue(px,name,attr.value,parseAlterHandler):null};return{whenVal:parseNamed("when"),loopWithVal:parseNamed("loop-with")}}var AttrParser=class{constructor(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?parseMacroAttr(value,this.px):parseText(value,this.px);val!==null?(this.attrs??=[],this.attrs.push(new Attr(name,val)),this.hasDynamic||=!(val instanceof ConstVal)):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=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){this.ifAttr&&(this.ifAttr.thenVal=parseText(s,this.px)??NOT_SET_VAL)}parseElse(value){this.ifAttr&&(this.ifAttr.elseVal=parseText(value,this.px)??NOT_SET_VAL)}parseEvent(directiveName,value){let[eventName,...modifiers]=directiveName.slice(3).split("+"),handler=EventHandler.parse(value,this.px);handler&&(this.events===null&&(this.events=this.px.registerEvents(),this.attrs??=[],this.attrs.push(new ConstAttr("data-eid",new ConstVal(this.events.id)))),this.events.add(eventName,handler,modifiers))}_parseDirectiveValue(directiveName,s,parserFn){return parseDirectiveValue(this.px,directiveName,s,parserFn)}parseDirective(s,directiveName){switch(directiveName){case"dangerouslysetinnerhtml":this.attrs??=[],this.attrs.push(new RawHtmlAttr(this._parseDirectiveValue(directiveName,s,parseText))),this.hasDynamic=!0;return;case"push-view":this.pushWrapper("push-view",s,this._parseDirectiveValue(directiveName,s,parseText));return;case"text":this.textChild=this._parseDirectiveValue(directiveName,s,parseText);return;case"show":this.pushWrapper("show",s,this._parseDirectiveValue(directiveName,s,parseBool));return;case"hide":this.pushWrapper("hide",s,this._parseDirectiveValue(directiveName,s,parseBool));return;case"each":{let val=this._parseDirectiveValue(directiveName,s,parseSequence);this.eachAttr=this.pushWrapper("each",s,val);return}case"enrich-with":this.eachAttr!==null?this.eachAttr.enrichWithVal=this._parseDirectiveValue(directiveName,s,parseAlterHandler):this.pushWrapper("scope",s,this._parseDirectiveValue(directiveName,s,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){this.eachAttr!==null&&(this.eachAttr.whenVal=this._parseDirectiveValue("when",s,parseAlterHandler))}_parseLoopWith(s){this.eachAttr!==null&&(this.eachAttr.loopWithVal=this._parseDirectiveValue("loop-with",s,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,new ConstVal(constVal)))}}let{attrs,hasDynamic}=this;return[hasDynamic?new DynAttrs(attrs):ConstAttrs.fromAttrs(attrs??[]),this.wrapperAttrs,this.textChild]}},ConstAttrs=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]=new ConstVal(`${this.items[name]}`).toString();return r}isConstant(){return!0}},DynAttrs=class 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}},BaseAttr=class{constructor(name){this.name=name}},Attr=class extends BaseAttr{constructor(name,val){super(name),this.val=val}eval(stack){return this.val.eval(stack)}},ConstAttr=class extends Attr{},RawHtmlAttr=class extends Attr{constructor(val){super("dangerouslySetInnerHTML",val??NULL_CONST_VAL)}eval(stack){return{__html:`${this.val.eval(stack)}`}}},NOT_SET_VAL=NULL_CONST_VAL,IfAttr=class 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)}},EventHandler=class _EventHandler{constructor(handlerVal,args=[]){this.handlerVal=handlerVal,this.args=args}getHandlerAndArgs(stack,_event){let argValues=new 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=parseReceiveHandler(s,px);return r===null?null:new _EventHandler(r.handlerVal,r.args)}};var SEQ_INFO=Symbol.for("tutuca.seqInfo"),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]},nativeIndexedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seqSize(seq));for(let i=s;i<e;i++)visit(i,seq[i],"si")},nativeKeyedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seqSize(seq)),i=0;for(let[key,value]of seqEntries(seq)){if(i>=e)break;i>=s&&visit(key,value,"sk"),i++}},unknownIter=()=>{},getSeqInfo=seq=>isIndexedSeq(seq)?nativeIndexedIter:isKeyedSeq(seq)||isSetSeq(seq)?nativeKeyedIter:seq?.[SEQ_INFO]??unknownIter,filterAlwaysTrue=(_key,_value,_iterData)=>!0,nullLoopWith=seq=>({iterData:{seq}}),unpackLoopResult=(result,seq)=>{let value=result??{};return{iterData:value.iterData??{seq},start:value.start,end:value.end,keys:value.keys}},makeLoopCtx=(stack,filter)=>({lookup:name=>stack.lookupBind(name),filter:(key,value,iterData)=>filter.call(stack.it,key,value,iterData)}),callEnricher=(enricher,it,binds,key,value,iterData)=>{enricher.call(it,binds,key,value,iterData),console.assert(binds.key===key&&binds.value===value,"@enrich-with handlers must not overwrite binds.key or binds.value"),binds.key=key,binds.value=value};function bindsForKey({seq,it,loopWith,enricher,ctx},key){let value=seqGet(seq,key,null),binds={key,value};if(enricher){let{iterData}=unpackLoopResult(loopWith.call(it,seq,ctx),seq);callEnricher(enricher,it,binds,key,value,iterData)}return binds}var visitKeys=(seq,keys,visit)=>{let attrName=isIndexedSeq(seq)?"si":"sk";for(let key of keys)visit(key,seqGet(seq,key),attrName)};function walkLoopBindings({seq,it,filter,loopWith,enricher,ctx},visit){let{iterData,start,end,keys}=unpackLoopResult(loopWith.call(it,seq,ctx),seq),visitOne=(key,value,attrName)=>{let binds={key,value};enricher&&callEnricher(enricher,it,binds,key,value,iterData),visit(key,value,attrName,binds)};keys?visitKeys(seq,keys,visitOne):getSeqInfo(seq)(seq,(key,value,attrName)=>{filter.call(it,key,value,iterData)&&visitOne(key,value,attrName)},start,end)}var HTML_NS="http://www.w3.org/1999/xhtml",SVG_NS="http://www.w3.org/2000/svg",MATH_NS="http://www.w3.org/1998/Math/MathML",isNamespaced=node=>{let ns=node.namespaceURI;return ns!==null&&ns!==HTML_NS},isForeignObject=tag=>tag.length===13&&tag.toLowerCase()==="foreignobject",effectiveNs=(vnode,opts)=>vnode.namespace??opts.namespace??null;function childOpts(vnode,ns,opts){let target=ns===SVG_NS&&isForeignObject(vnode.tag)?null:ns;return target===(opts.namespace??null)?opts:{...opts,namespace:target}}var NEVER_ASSIGN=new Set(["width","height","href","list","form","tabIndex","download","rowSpan","colSpan","role","popover"]),PROP_ATTR_NAME={className:"class",htmlFor:"for"};function applyProperties(node,props){let namespaced=isNamespaced(node);for(let name in props)setProp(node,name,props[name],namespaced)}function setProp(node,name,value,namespaced){if(name==="dangerouslySetInnerHTML"){if(value===void 0)node.replaceChildren();else{let html2=value.__html??"";html2!==node.innerHTML&&(node.innerHTML=html2)}return}if(typeof value=="function")return;let usesProp=!namespaced&&!NEVER_ASSIGN.has(name)&&name in node;if(usesProp&&value!=null)try{node[name]=value;return}catch{}if(value==null||value===!1&&name[4]!=="-")if(usesProp){try{node[name]=""}catch{}node.removeAttribute(PROP_ATTR_NAME[name]??name)}else node.removeAttribute(name);else node.setAttribute(name,value)}function applyValueLast(node,value){node.tagName==="PROGRESS"&&(value==null||value===0)?node.removeAttribute("value"):setProp(node,"value",value,isNamespaced(node))}var VBase=class{},getKey=child=>child instanceof VNode?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)if(isIterable(child))for(let c of child)addChild(normalizedChildren,c);else child instanceof VBase?child instanceof VFragment?normalizedChildren.push(...child.childs):normalizedChildren.push(child):normalizedChildren.push(new VText(child))}var VText=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)}},VComment=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)}},VFragment=class _VFragment extends VBase{constructor(childs){super(),this.childs=[],addChild(this.childs,childs)}get nodeType(){return 11}isEqualTo(other){return!(other instanceof _VFragment)||this.childs.length!==other.childs.length?!1:childsEqual(this.childs,other.childs)}toDom(opts){let fragment=opts.document.createDocumentFragment();return appendChildNodes(fragment,this.childs,opts),fragment}},VNode=class _VNode 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 _VNode)||!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,ns=effectiveNs(this,opts),tag=ns!==null&&this.tag===this.tag.toUpperCase()?this.tag.toLowerCase():this.tag,attrs=this.attrs,createOpts=attrs.is!=null?{is:attrs.is}:void 0,node=ns===null?doc.createElement(tag,createOpts):doc.createElementNS(ns,tag,createOpts),cOpts=childOpts(this,ns,opts);if("value"in attrs||"checked"in attrs){let{value,checked,...rest}=attrs;applyProperties(node,rest),appendChildNodes(node,this.childs,cOpts),value!==void 0&&applyValueLast(node,value),checked!==void 0&&setProp(node,"checked",checked,!1)}else applyProperties(node,attrs),appendChildNodes(node,this.childs,cOpts);return node}};function diffProps(a,b){if(a===b)return null;let diff=null;for(let aKey in a)Object.hasOwn(b,aKey)?a[aKey]!==b[aKey]&&(diff??={},diff[aKey]=b[aKey]):(diff??={},diff[aKey]=void 0);for(let bKey in b)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),hasValue=propsDiff!=null&&"value"in propsDiff,hasChecked=propsDiff!=null&&"checked"in propsDiff;if(propsDiff)if(hasValue||hasChecked){let{value:_v,checked:_c,...rest}=propsDiff;applyProperties(domNode,rest)}else applyProperties(domNode,propsDiff);if(!target.attrs.dangerouslySetInnerHTML){let ns=effectiveNs(target,opts);morphChildren(domNode,source.childs,target.childs,childOpts(target,ns,opts))}return hasValue?applyValueLast(domNode,propsDiff.value):source.tag==="SELECT"&&target.attrs.value!==void 0&&applyValueLast(domNode,target.attrs.value),hasChecked&&setProp(domNode,"checked",propsDiff.checked,!1),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]);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)newKey in oldKeyMap&&!used2[oldKeyMap[newKey]]&&(oldIdx=oldKeyMap[newKey]);else for(;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;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--)!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];propName==="key"?key=propVal:propName==="namespace"?namespace=namespace??propVal:props[propName]=propVal}if(namespace==null){let lower=tagName.toLowerCase();lower==="svg"?(namespace=SVG_NS,tagName="svg"):lower==="math"&&(namespace=MATH_NS,tagName="math")}let c=tagName.charCodeAt(0),tag=namespace==null&&c>=97&&c<=122&&tagName===tagName.toLowerCase()?tagName.toUpperCase():tagName,normalizedChildren=[];return addChild(normalizedChildren,children),new VNode(tag,props,normalizedChildren,key,namespace)}function resolveDynProducer(comp,name){let own=comp?.provide?.[name],producerComp=own!=null?comp:comp?.scope?.lookupProvider(name)??null,producerProvide=own??producerComp?.provide?.[name];if(producerComp==null||producerProvide==null)return null;let pi=producerProvide.val?.toPathItem?.()??null;return{producerCompId:producerComp.id,producerSteps:pi?[pi]:[]}}var BaseNode=class{render(_stack,_rx){return null}setDataAttr(key,val){console.warn("setDataAttr not implemented for",this,{key,val})}isConstant(){return!1}isWhiteSpace(){return!1}optimize(){}},TextNode=class 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){}},CommentNode=class 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];child.isConstant()?childs[i]=new RenderOnceNode(child):child.optimize()}}function optimizeNode(node){return node.isConstant()?new RenderOnceNode(node):(node.optimize(),node)}var ChildsNode=class extends BaseNode{constructor(childs){super(),this.childs=childs}isConstant(){return this.childs.every(v=>v.isConstant())}optimize(){optimizeChilds(this.childs)}},DomNode=class extends ChildsNode{constructor(tagName,attrs,childs,namespace=null){super(childs),this.tagName=tagName,this.attrs=attrs,this.namespace=namespace}render(stack,rx){let childNodes=new 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()}},FragmentNode=class 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)}},maybeFragment=xs=>xs.length===1?xs[0]:new FragmentNode(xs),VALID_NODE_RE=/^[a-zA-Z][a-zA-Z0-9-]*$/,ANode=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(html2,px){let nodes=px.parseHTML(html2);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);child!==null&&childs.push(child)}let trimmed=condenseChildsWhites(childs);return trimmed.length===0?new CommentNode("Empty View in ANode.parse"):maybeFragment(trimmed)}static fromDOM(node,px){if(node instanceof px.Text)return new TextNode(node.textContent);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);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);if(tag.charCodeAt(1)===58&&(tag.charCodeAt(0)===88||tag.charCodeAt(0)===120)){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);px.onAttributes(nAttrs,wrappers,textChild,!1,tag),textChild&&childs.unshift(new RenderTextNode(null,textChild));let domChilds=tag!=="PRE"?condenseChildsWhites(childs):childs,ns=node.namespaceURI,namespace=ns&&ns!==HTML_NS?ns:null;return wrap(new DomNode(tag,nAttrs,domChilds,namespace),px,wrappers)}return new CommentNode(`Error: InvalidTagName ${tag}`)}finally{px.currentTag=prevTag}}};function parseXOp(attrs,childs,opIdx,px){if(attrs.length<=opIdx)return maybeFragment(childs);let{name,value}=attrs[opIdx];X_OPS[name]?.ignoresChildren&&hasMeaningfulChilds(childs)&&px.onParseIssue("x-op-ignores-children",{op:name});let asAttr=attrs.getNamedItem("as")?.value??null,as=asAttr===null?null:parseViewName(asAttr,px),node;switch(name){case"slot":node=new SlotNode(null,new ConstVal(value),maybeFragment(childs));break;case"text":node=px.addNodeIf(RenderTextNode,parseXOpVal(name,value,px,parseText));break;case"render":node=px.addNodeIf(RenderNode,parseXOpVal(name,value,px,parseComponent),as);break;case"render-it":node=px.addNode(RenderItNode,as);break;case"render-each":node=parseRenderEach(px,value,as,attrs);break;case"show":{let val=parseXOpVal(name,value,px,parseBool);node=px.addNodeIf(ShowNode,val,maybeFragment(childs));break}case"hide":{let val=parseXOpVal(name,value,px,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(value,px);return val===null&&px.onParseIssue("bad-value",{role:"x-op",op:opName,value}),val}function parseViewName(s,px){return parseText(s,px)??new ConstVal(s)}function processXExtras(node,attrs,opName,startIdx,px){let{consumed,wrappable}=X_OPS[opName],wrappers=[];for(let i=startIdx;i<attrs.length;i++){let a=attrs[i],aName=a.name;if(consumed.has(aName))continue;if(wrappable&&aName.charCodeAt(0)===64){let wrapper=X_OPS[aName.slice(1)]?.wrapper;if(wrapper){wrappers.push([wrapper,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);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);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);return node!==null&&data.name==="each"&&(node.iterInfo.enrichWithVal=data.enrichWithVal??null,node.iterInfo.whenVal=data.whenVal??null,node.iterInfo.loopWithVal=data.loopWithVal??null),node}var MacroNode=class 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 new Error(`Recursive macro expansion: ${name}`);let macro2=scope.lookupMacro(name);if(macro2===null)this.node=new CommentNode(`bad macro: ${name}`);else{let vars={...macro2.defaults,...attrs};this.node=macro2.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)}},Macro=class{constructor(defaults,rawView){this.defaults=defaults,this.rawView=rawView}expand(px){return ANode.parse(this.rawView,px)}},RenderViewId=class extends ANode{constructor(nodeId,val,viewVal){super(nodeId,val),this.viewVal=viewVal}evalViewName(stack){return this.viewVal?this.viewVal.eval(stack):null}setDataAttr(_key,_val){}};function dynRenderStep(comp,name,key){let p=resolveDynProducer(comp,name);return p?key===void 0?new DynStep(p.producerCompId,p.producerSteps):new DynEachStep(p.producerCompId,p.producerSteps,key):null}var RenderNode=class extends RenderViewId{render(stack,rx){let newStack=stack.enter(this.val.eval(stack),{},!0);return rx.renderIt(newStack,this,"",this.evalViewName(stack))}toPathStep(ctx){return this.val instanceof DynVal?dynRenderStep(ctx.comp,this.val.name):super.toPathStep(ctx)}},RenderItNode=class extends RenderViewId{render(stack,rx){let newStack=stack.enter(stack.it,{},!0);return rx.renderIt(newStack,this,"",this.evalViewName(stack))}toPathStep(ctx){let next=ctx.next();if(next===null)return null;let nextNode=next.resolveNode();return nextNode instanceof EachNode&&next.hasKey?nextNode.val instanceof DynVal?dynRenderStep(ctx.comp,nextNode.val.name,next.key):new EachRenderItStep(nextNode.val.name,next.key):null}};function parseRenderEach(px,value,as,attrs){let seqVal=parseXOpVal("render-each",value,px,parseSequence);if(seqVal===null)return null;let renderIt=px.addNode(RenderItNode,as),{whenVal,loopWithVal}=parseIterationDirectives(attrs,px),each2=px.addNodeIf(EachNode,seqVal);return each2.iterInfo.whenVal=whenVal,each2.iterInfo.loopWithVal=loopWithVal,each2.fromRenderEach=!0,each2.wrapNode(renderIt),each2}var RenderTextNode=class extends ANode{render(stack,_rx){return this.val.eval(stack)}setDataAttr(_key,_val){}},RenderOnceNode=class 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)}},WrapperNode=class 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},ShowNode=class extends WrapperNode{render(stack,rx){return this.val.eval(stack)?this.node.render(stack,rx):null}},HideNode=class extends WrapperNode{render(stack,rx){return this.val.eval(stack)?null:this.node.render(stack,rx)}},PushViewNameNode=class extends WrapperNode{render(stack,rx){return this.node.render(stack.pushViewName(this.val.eval(stack)),rx)}},SlotNode=class extends WrapperNode{isSlotNode=!0;optimize(){this.node.optimize()}},ScopeNode=class extends WrapperNode{render(stack,rx){let binds=this.val.evalAsHandler(stack)?.call(stack.it)??{},dom=this.node.render(stack.enter(stack.it,binds,!1),rx);return rx.renderScopeMeta(this.nodeId,dom)}toPathStep(_ctx){return new ScopeBindStep(this.val)}wrapNode(node){this.node=node,this.node.setDataAttr("data-nid",this.nodeId)}static register=!0},EachNode=class 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.iterInfo,ctx.key):null}static register=!0},IterInfo=class{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}}enrichBinds(stack,key){let{seq,filter,loopWith,enricher}=this.eval(stack),ctx=makeLoopCtx(stack,filter);return bindsForKey({seq,it:stack.it,loopWith,enricher,ctx},key)}};function xOp(consumed=[],{wrappable=!1,wrapper=null,ignoresChildren=!1}={}){return{consumed:new Set(consumed),wrappable,wrapper,ignoresChildren}}var X_OPS={slot:xOp(),text:xOp([],{wrappable:!0,ignoresChildren:!0}),render:xOp(["as"],{wrappable:!0,ignoresChildren:!0}),"render-it":xOp(["as"],{wrappable:!0,ignoresChildren:!0}),"render-each":xOp(["as","@when","@loop-with"],{wrappable:!0,ignoresChildren:!0}),show:xOp([],{wrapper:ShowNode}),hide:xOp([],{wrapper:HideNode})},WRAPPER_NODES={show:ShowNode,hide:HideNode,each:EachNode,scope:ScopeNode,"push-view":PushViewNameNode},ParseContext=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,frame={macroName,macroVars,macroSlots};return new _ParseContext(document2,Text,Comment,nodes,events2,macroNodes,frame,this)}parseHTML(html2){let t=this.document.createElement("template");return t.innerHTML=html2,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}addNode(Class,extra){let nodeId=this.nodes.length,node=new Class(nodeId,null,extra);return this.nodes.push(node),node}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)child.isSlotNode?slots[child.val.val]=child.node: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)}},_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)},isEmptyText=c=>c instanceof TextNode&&c.val==="",isIgnorableXChild=c=>c instanceof CommentNode||(c.isWhiteSpace?.()??!1),hasMeaningfulChilds=childs=>childs.some(c=>!isIgnorableXChild(c));function trimEdgeWhite(node){return node.isWhiteSpace?.()?(node.condenseWhiteSpace(),!0):!1}function condenseChildsWhites(childs){if(childs.length===0)return childs;let last=childs.length-1,emptied=trimEdgeWhite(childs[0]);last>0&&trimEdgeWhite(childs[last])&&(emptied=!0);for(let i=1;i<last;i++){let cur=childs[i];if(!(cur.isWhiteSpace?.()&&cur.hasNewLine()))continue;let bothBlock=isBlockDomNode(childs[i-1])&&isBlockDomNode(childs[i+1]);cur.condenseWhiteSpace(bothBlock?"":" "),bothBlock&&(emptied=!0)}return emptied?childs.filter(c=>!isEmptyText(c)):childs}var View=class{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){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){if(this.anode===null)throw new Error(`tutuca: view "${this.name}" was rendered before it was compiled — its component is not registered in this app/scope. Source: ${String(this.rawView).slice(0,80).replace(/\s+/g," ")}…`);return this.anode.render(stack,rx)}},NodeEvents=class{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)handler.handlesEventName(eventName)&&(r??=[],r.push(handler));return r}},NodeEvent=class{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}},fwdIfCtxPred=pred=>w=>(that,f,args,ctx)=>pred(ctx)?w(that,f,args,ctx):that,fwdIfEventPred=pred=>fwdIfCtxPred(({e})=>pred(e)),fwdIfKey=keyName=>fwdIfEventPred(keyIs(keyName)),fwdCtrl=fwdIfEventPred(macCtrl),fwdMeta=fwdIfEventPred(e=>e.metaKey),fwdAlt=fwdIfEventPred(e=>e.altKey),MOD_WRAPPERS_FOR_ANY_EVENT={ctrl:fwdCtrl,cmd:fwdCtrl,meta:fwdMeta,alt:fwdAlt},MOD_WRAPPERS_BY_EVENT={keydown:{send:fwdIfKey("Enter"),cancel:fwdIfKey("Escape")}},MOD_EFFECTS={prevent:e=>e.preventDefault?.(),stop:e=>e.stopPropagation?.()},NO_WRAPPERS={},identityModifierWrapper=(f,_ctx)=>f;function compileModifiers(eventName,names){if(names.length===0)return identityModifierWrapper;let wrappers=MOD_WRAPPERS_BY_EVENT[eventName]??NO_WRAPPERS,effects=[];for(let name of names){let effect=MOD_EFFECTS[name];effect!==void 0&&effects.push(effect)}let w=effects.length===0?(that,f,args,_ctx)=>f.apply(that,args):(that,f,args,ctx)=>{for(let effect of effects)effect(ctx.e);return f.apply(that,args)};for(let name of names){let wrapper=wrappers[name]??MOD_WRAPPERS_FOR_ANY_EVENT[name];wrapper!==void 0&&(w=wrapper(w))}return(f,ctx)=>function(...args){return w(this,f,args,ctx)}}var ParseCtxClassSetCollector=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,frame={macroName,macroVars,macroSlots},v=new _ParseCtxClassSetCollector(document2,Text,Comment,nodes,events2,macroNodes,frame,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;thenVal!==void 0?(this._maybeAddVal(thenVal),this._maybeAddVal(elseVal)):this._maybeAddVal(val)}else{let attr=attrs.items.class;attr&&this._addClasses(attr)}}_maybeAddVal(value){!this._maybeAddStrTpl(value)&&typeof value?.val=="string"&&this._addClasses(value.val)}_maybeAddStrTpl(value){if(value?.vals!==void 0){for(let val of value.vals)val instanceof ConstVal&&val.val!==""&&this._addClasses(val.val);return!0}return!1}};function collectAppClassesInSet(app){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 classes}var COMPONENT=Symbol.for("tutuca.component"),Components=class{constructor(){this.byId=new Map}registerComponent(Comp){this.byId.set(Comp[COMPONENT].id,Comp)}getComponentForId(id){return this.byId.get(id)??null}getCompFor(v){let Comp=v?.constructor;return Comp?.[COMPONENT]?Comp:null}getHandlerFor(v,name,key){return this.getCompFor(v)?.[key][name]??null}getIntentChainFor(v,name){return this.getCompFor(v)?.scope.lookupIntentChain(name)??[]}compileStyles(){let styles2=[];for(let Comp of this.byId.values())styles2.push(Comp[COMPONENT].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="";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);return children&&children.length>truncate2&&(children=`${truncator}(${element.children.length})`),`${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)=>chaiInspect in value&&typeof value[chaiInspect]=="function"?value[chaiInspect](options):nodeInspect in value&&typeof value[nodeInspect]=="function"?value[nodeInspect](options.depth,options,inspectFn):"inspect"in value&&typeof value.inspect=="function"?value.inspect(options.depth,options):"constructor"in value&&constructorMap.has(value.constructor)?constructorMap.get(value.constructor)(value,options):stringTagMap[type3]?stringTagMap[type3](value,options):"","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)),type3 in baseTypesMap)return baseTypesMap[type3](value,options);if(customInspect&&value){let output=inspectCustom(value,options,type3,inspect);if(output)return typeof output=="string"?output:inspect(output,options)}let proto=value?Object.getPrototypeOf(value):!1;return proto===Object.prototype||proto===null?inspectObject(value,options):value&&typeof HTMLElement=="function"&&value instanceof HTMLElement?inspectHTML(value,options):"constructor"in value?value.constructor!==Object?inspectClass(value,options):inspectObject(value,options):value===Object(value)?inspectObject(value,options):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+"]";if(type3==="[object Array]")return"[ Array("+obj.length+") ]";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");return typeof msg=="function"&&(msg=msg()),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));object.__flags||(object.__flags=Object.create(null)),includeAll=arguments.length===3?includeAll:!0;for(let flag3 in flags)(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];return typeof stringTag=="string"?stringTag:Object.prototype.toString.call(obj).slice(8,-1)}__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){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))){var leftHandMap=memoizeMap.get(leftHandOperand);leftHandMap?leftHandMap.set(rightHandOperand,result):(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);return simpleResult!==null?simpleResult:extensiveDeepEqual(leftHandOperand,rightHandOperand,options)}__name(deepEqual,"deepEqual");function simpleEqual(leftHandOperand,rightHandOperand){return leftHandOperand===rightHandOperand?leftHandOperand!==0||1/leftHandOperand===1/rightHandOperand:leftHandOperand!==leftHandOperand&&rightHandOperand!==rightHandOperand?!0:isPrimitive(leftHandOperand)||isPrimitive(rightHandOperand)?!1: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{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;for(var index=-1;++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{return[]}return[]}__name(getIteratorEntries,"getIteratorEntries");function getGeneratorEntries(generator){for(var generatorResult=generator.next(),accumulator=[generatorResult.value];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){for(var keys=[],allKeys=Object.getOwnPropertySymbols(target),i=0;i<allKeys.length;i+=1){var key=allKeys[i];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)return iterableEqual(mapSymbols(leftHandKeys).sort(),mapSymbols(rightHandKeys).sort())===!1?!1:keysEqual(leftHandOperand,rightHandOperand,leftHandKeys,options);var leftHandEntries=getIteratorEntries(leftHandOperand),rightHandEntries=getIteratorEntries(rightHandOperand);return leftHandEntries.length&&leftHandEntries.length===rightHandEntries.length?(leftHandEntries.sort(),rightHandEntries.sort(),iterableEqual(leftHandEntries,rightHandEntries,options)):leftHandKeys.length===0&&leftHandEntries.length===0&&rightHandKeys.length===0&&rightHandEntries.length===0}__name(objectEqual,"objectEqual");function isPrimitive(value){return value===null||typeof value!="object"}__name(isPrimitive,"isPrimitive");function mapSymbols(arr){return arr.map(__name(function(entry){return typeof entry=="symbol"?entry.toString():entry},"mapSymbol"))}__name(mapSymbols,"mapSymbols");function hasProperty(obj,name){return typeof obj>"u"||obj===null?!1: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;return mArr?parsed={i:parseFloat(mArr[1])}:parsed={p:value.replace(/\\([.[\]])/g,"$1")},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];temporaryValue&&(typeof part.p>"u"?temporaryValue=temporaryValue[part.i]:temporaryValue=temporaryValue[part.p],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),expected===void 0&&_actual===void 0&&(showDiff=!1),config.showDiff!==!0&&(showDiff=!1),!ok){msg=getMessage2(this,arguments);let assertionErrorObjectProperties={actual:getActual(this,arguments),expected,showDiff},operator=getOperator(this,arguments);throw operator&&(assertionErrorObjectProperties.operator=operator),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(){!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){return fnLengthDesc.configurable&&Object.defineProperty(fn,"length",{get:__name(function(){throw Error(isChainable?"Invalid Chai property: "+assertionName+'.length. Due to a compatibility issue, "length" cannot directly follow "'+assertionName+'". Use "'+assertionName+'.lengthOf" instead.':"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){result.indexOf(property)===-1&&result.push(property)}__name(addProperty2,"addProperty");let proto=Object.getPrototypeOf(object);for(;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){return isProxyEnabled()?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;throw getProperties(target).forEach(function(prop){if(!Object.prototype.hasOwnProperty(prop)&&builtins.indexOf(prop)===-1){let dist=stringDistanceCapped(property,prop,suggestionDistance);dist<suggestionDistance&&(suggestion=prop,suggestionDistance=dist)}}),Error(suggestion!==null?"Invalid Chai property: "+property+'. Did you mean "'+suggestion+'"?':"Invalid Chai property: "+property)}return builtins.indexOf(property)===-1&&!flag(target,"lockSsfi")&&flag(target,"ssfi",proxyGetter),Reflect.get(target,property)},"proxyGetter")}):obj}__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(){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");_get&&typeof _get.get=="function"&&(_super=_get.get),Object.defineProperty(ctx,name,{get:__name(function overwritingPropertyGetter(){!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 new Error(name+" is not a function")},"_super");_method&&typeof _method=="function"&&(_super=_method);let overwritingMethodWrapper=__name(function(){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);return typeof propDesc!="object"?!0:!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){typeof chainingBehavior!="function"&&(chainingBehavior=__name(function(){},"chainingBehavior"));let chainableBehavior={method,chainingBehavior};ctx.__methods||(ctx.__methods={}),ctx.__methods[name]=chainableBehavior,Object.defineProperty(ctx,name,{get:__name(function(){chainableBehavior.chainingBehavior.call(this);let chainableMethodWrapper=__name(function(){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){return typeof Object.getOwnPropertySymbols!="function"?[]: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 isNaN22=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()),msg=msg||"",!msg||/\shave\s/.test(msg))return;let isObject=isObjectType(expected);return/\snot\s/.test(msg)?isObject?"notDeepStrictEqual":"notStrictEqual":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){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();functionTypes.function.includes(type3)?this.assert(functionTypes[type3].includes(detectedType),"expected #{this} to be "+article+type3,"expected #{this} not to be "+article+type3):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 isNaN22(a)&&isNaN22(b)||a===b}__name(SameValueZero,"SameValueZero");function includeChainingBehavior(){flag2(this,"contains",!0)}__name(includeChainingBehavior,"includeChainingBehavior");function include(val,msg){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":isDeep?obj.forEach(function(item){included=included||isEql(item,val)}):included=obj.has(val);break;case"array":isDeep?included=obj.some(function(item){return isEql(item,val)}):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;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"))});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"))});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"))});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(isNaN22(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,"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){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){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){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"),!doLength&&objType==="date"&&nType!=="date")throw new AssertionError(msgPrefix+"the argument to above must be a date",void 0,ssfi);if(!isNumeric(n)&&(doLength||isNumeric(obj)))throw new AssertionError(msgPrefix+"the argument to above must be a number",void 0,ssfi);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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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"),!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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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"),!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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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"),!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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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"),!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;objType==="map"||objType==="set"?(descriptor="size",itemsCount=obj.size):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){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){throw err instanceof TypeError?(flagMsg=flagMsg?flagMsg+": ":"",new AssertionError(flagMsg+"The instanceof assertion needs a constructor but "+type(constructor)+" was given.",void 0,ssfi)):err}let name=getName(constructor);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){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)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="";isDeep&&(descriptor+="deep "),isOwn&&(descriptor+="own "),isNested&&(descriptor+="nested "),descriptor+="property ";let hasProperty2;isOwn?hasProperty2=Object.prototype.hasOwnProperty.call(obj,name):isNested?hasProperty2=pathInfo.exists:hasProperty2=hasProperty(obj,name),(!negate||arguments.length===1)&&this.assert(hasProperty2,"expected #{this} to have "+descriptor+inspect2(name),"expected #{this} to not have "+descriptor+inspect2(name)),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){typeof descriptor=="string"&&(msg=descriptor,descriptor=null),msg&&flag2(this,"message",msg);let obj=flag2(this,"object"),actualDescriptor=Object.getOwnPropertyDescriptor(Object(obj),name),eql=flag2(this,"eql");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):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){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){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){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")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),any&&(ok=expected.some(function(expectedKey){return actual.some(function(actualKey){return isEql(expectedKey,actualKey)})})),all&&(ok=expected.every(function(expectedKey){return actual.some(function(actualKey){return isEql(expectedKey,actualKey)})}),flag2(this,"contains")||(ok=ok&&keys.length==actual.length)),len>1){keys=keys.map(function(key){return inspect2(key)});let last=keys.pop();all&&(str=keys.join(", ")+", and "+last),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){msg&&flag2(this,"message",msg);let obj=flag2(this,"object"),ssfi=flag2(this,"ssfi"),flagMsg=flag2(this,"message"),negate=flag2(this,"negate")||!1;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=!!(errorLike&&errMsgMatcher),errorLikeFail=!1,errMsgMatcherFail=!1;if(everyArgIsUndefined||!everyArgIsUndefined&&!negate){let errorLikeString="an error";errorLike instanceof Error?errorLikeString="#{exp}":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{}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&&(errorLike instanceof Error&&check_error_exports.compatibleInstance(caughtErr,errorLike)===negate&&(everyArgIsDefined&&negate?errorLikeFail=!0: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())),check_error_exports.compatibleConstructor(caughtErr,errorLike)===negate&&(everyArgIsDefined&&negate?errorLikeFail=!0: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)))),caughtErr&&errMsgMatcher!==void 0&&errMsgMatcher!==null){let placeholder="including";isRegExp2(errMsgMatcher)&&(placeholder="matching"),check_error_exports.compatibleMessage(caughtErr,errMsgMatcher)===negate&&(everyArgIsDefined&&negate?errMsgMatcherFail=!0: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)))}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){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){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"),result)}__name(satisfy,"satisfy");Assertion.addMethod("satisfy",satisfy);Assertion.addMethod("satisfies",satisfy);function closeTo(expected,delta,msg){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);return matchIdx===-1?!1:(contains||superset.splice(matchIdx,1),!0)}return superset.some(function(elem2,matchIdx){return cmp(elem,elem2)?(contains||superset.splice(matchIdx,1),!0):!1})})}__name(isSubsetOf,"isSubsetOf");Assertion.addMethod("members",function(subset,msg){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;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}"):(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){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){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");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):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):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){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;prop?(new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop]):(new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject()),fn();let final=prop==null?subject():subject[prop],msgObj=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){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;prop?(new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop]):(new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject()),new Assertion(initial,flagMsg,ssfi,!0).is.a("number"),fn();let final=prop==null?subject():subject[prop],msgObj=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){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;prop?(new Assertion(subject,flagMsg,ssfi,!0).to.have.property(prop),initial=subject[prop]):(new Assertion(subject,flagMsg,ssfi,!0).is.a("function"),initial=subject()),new Assertion(initial,flagMsg,ssfi,!0).is.a("number"),fn();let final=prop==null?subject():subject[prop],msgObj=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){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;behavior==="change"?expression=Math.abs(final-initial)===Math.abs(delta):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"),isFrozen2=obj===Object(obj)?Object.isFrozen(obj):!0;this.assert(isFrozen2,"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){return expected===actual?!0:typeof actual!=typeof expected?!1:typeof expected!="object"||expected===null?expected===actual:actual?Array.isArray(expected)?Array.isArray(actual)?expected.every(function(exp){return actual.some(function(act){return compareSubset(exp,act)})}):!1:expected instanceof Date?actual instanceof Date?expected.getTime()===actual.getTime():!1:Object.keys(expected).every(function(key){let expectedValue=expected[key],actualValue=actual[key];return typeof expectedValue=="object"&&expectedValue!==null&&actualValue!==null?compareSubset(expectedValue,actualValue):typeof expectedValue=="function"?expectedValue(actualValue):actualValue===expectedValue}):!1}__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){throw arguments.length<2&&(message=actual,actual=void 0),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(){return this instanceof String||this instanceof Number||this instanceof Boolean||typeof Symbol=="function"&&this instanceof Symbol||typeof BigInt=="function"&&this instanceof BigInt?new Assertion(this.valueOf(),null,shouldGetter):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){throw arguments.length<2&&(message=actual,actual=void 0),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){throw arguments.length<2&&(message=actual,actual=void 0),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 test22=new Assertion(act,msg,assert.equal,!0);test22.assert(exp==flag(test22,"object"),"expected #{this} to equal #{exp}","expected #{this} to not equal #{act}",exp,act,!0)};assert.notEqual=function(act,exp,msg){let test22=new Assertion(act,msg,assert.notEqual,!0);test22.assert(exp!=flag(test22,"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){(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){(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+": ",new AssertionError(msg+'Invalid operator "'+operator+'"',void 0,assert.operator)}let test22=new Assertion(ok,msg,assert.operator,!0);test22.assert(flag(test22,"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,set22,msg){new Assertion(set1,msg,assert.sameMembers,!0).to.have.same.members(set22)};assert.notSameMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.notSameMembers,!0).to.not.have.same.members(set22)};assert.sameDeepMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.sameDeepMembers,!0).to.have.same.deep.members(set22)};assert.notSameDeepMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.notSameDeepMembers,!0).to.not.have.same.deep.members(set22)};assert.sameOrderedMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.sameOrderedMembers,!0).to.have.same.ordered.members(set22)};assert.notSameOrderedMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.notSameOrderedMembers,!0).to.not.have.same.ordered.members(set22)};assert.sameDeepOrderedMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.sameDeepOrderedMembers,!0).to.have.same.deep.ordered.members(set22)};assert.notSameDeepOrderedMembers=function(set1,set22,msg){new Assertion(set1,msg,assert.notSameDeepOrderedMembers,!0).to.not.have.same.deep.ordered.members(set22)};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){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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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){return arguments.length===3&&typeof obj=="function"&&(msg=prop,prop=null),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 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 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};return~used.indexOf(fn)||(fn(exports,utils_exports),used.push(fn)),exports}__name(use,"use");function jestMatchers(chai,utils){let A=chai.Assertion,m=(name,fn)=>A.addMethod(name,fn);m("toBe",function(expected){this.assert(Object.is(this._obj,expected),"expected #{this} to be #{exp}","expected #{this} not to be #{exp}",expected,this._obj)}),m("toEqual",function(expected){this.assert(utils.eql(this._obj,expected),"expected #{this} to deeply equal #{exp}","expected #{this} not to deeply equal #{exp}",expected,this._obj,!0)}),m("toBeTruthy",function(){this.assert(!!this._obj,"expected #{this} to be truthy","expected #{this} not to be truthy")}),m("toBeFalsy",function(){this.assert(!this._obj,"expected #{this} to be falsy","expected #{this} not to be falsy")}),m("toBeNull",function(){this.assert(this._obj===null,"expected #{this} to be null","expected #{this} not to be null")}),m("toBeUndefined",function(){this.assert(this._obj===void 0,"expected #{this} to be undefined","expected #{this} not to be undefined")}),m("toBeDefined",function(){this.assert(this._obj!==void 0,"expected #{this} to be defined","expected #{this} to be undefined")}),m("toBeNaN",function(){this.assert(Number.isNaN(this._obj),"expected #{this} to be NaN","expected #{this} not to be NaN")});let compare=(name,op,word)=>m(name,function(expected){this.assert(op(this._obj,expected),`expected #{this} to be ${word} #{exp}`,`expected #{this} not to be ${word} #{exp}`,expected)});compare("toBeGreaterThan",(a,b)=>a>b,"greater than"),compare("toBeGreaterThanOrEqual",(a,b)=>a>=b,"greater than or equal to"),compare("toBeLessThan",(a,b)=>a<b,"less than"),compare("toBeLessThanOrEqual",(a,b)=>a<=b,"less than or equal to"),m("toBeCloseTo",function(expected,numDigits=2){let pass=Math.abs(expected-this._obj)<10**-numDigits/2;this.assert(pass,`expected #{this} to be close to #{exp} (${numDigits} digits)`,`expected #{this} not to be close to #{exp} (${numDigits} digits)`,expected)}),m("toContain",function(item){let obj=this._obj,ok=typeof obj=="string"?obj.includes(item):Array.from(obj).includes(item);this.assert(ok,"expected #{this} to contain #{exp}","expected #{this} not to contain #{exp}",item)}),m("toHaveLength",function(length){let actual=this._obj==null?void 0:this._obj.length;this.assert(actual===length,"expected #{this} to have length #{exp}","expected #{this} not to have length #{exp}",length,actual)}),m("toMatch",function(expected){let obj=this._obj,ok=expected instanceof RegExp?expected.test(obj):String(obj).includes(expected);this.assert(ok,"expected #{this} to match #{exp}","expected #{this} not to match #{exp}",expected)}),m("toHaveProperty",function(path,...rest){let keys=Array.isArray(path)?path:String(path).split("."),cur=this._obj,found=!0;for(let k of keys)if(cur!=null&&k in Object(cur))cur=cur[k];else{found=!1;break}let pass=found&&(rest.length===0||utils.eql(cur,rest[0]));this.assert(pass,"expected #{this} to have property #{exp}","expected #{this} not to have property #{exp}",path)}),m("toBeInstanceOf",function(ctor){this.assert(this._obj instanceof ctor,"expected #{this} to be an instance of #{exp}","expected #{this} not to be an instance of #{exp}",ctor.name??ctor)}),m("toThrow",function(expected){let a=new chai.Assertion(this._obj);utils.flag(this,"negate")?expected===void 0?a.to.not.throw():a.to.not.throw(expected):expected===void 0?a.to.throw():a.to.throw(expected)})}use(jestMatchers);var isPlainObject=value=>{if(value===null||typeof value!="object")return!1;let proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null},seqSize=seq=>seq==null?0:typeof seq.length=="number"?seq.length:typeof seq.size=="number"?seq.size:isPlainObject(seq)?Object.keys(seq).length:0,seqGet=(seq,key,dval=null)=>seq==null?dval:seq instanceof Map?seq.has(key)?seq.get(key):dval:seq instanceof Set?seq.has(key)?key:dval:Object.hasOwn(seq,key)?seq[key]:typeof seq.get=="function"?seq.get(key,dval):dval,isIndexedSeq=seq=>Array.isArray(seq),isKeyedSeq=seq=>seq instanceof Map||isPlainObject(seq),isSetSeq=seq=>seq instanceof Set;function*seqEntries(seq){if(seq instanceof Map)yield*seq.entries();else if(seq instanceof Set)for(let value of seq)yield[value,value];else if(isPlainObject(seq))yield*Object.entries(seq);else if(Array.isArray(seq))for(let i=0;i<seq.length;i++)yield[i,seq[i]]}var NOTHING=Symbol.for("immer-nothing"),DRAFTABLE=Symbol.for("immer-draftable"),DRAFT_STATE=Symbol.for("immer-state"),errors=[function(plugin){return`The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`},function(thing){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`},"This object has been frozen and should not be mutated",function(data){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+data},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(thing){return`'current' expects a draft, got: ${thing}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(thing){return`'original' expects a draft, got: ${thing}`}];function die(error,...args){{let e=errors[error],msg=typeof e=="function"?e.apply(null,args):e;throw new Error(`[Immer] ${msg}`)}throw new Error(`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`)}var getPrototypeOf=Object.getPrototypeOf;function isDraft(value){return!!value&&!!value[DRAFT_STATE]}function isDraftable(value){return value?isPlainObject2(value)||Array.isArray(value)||!!value[DRAFTABLE]||!!value.constructor?.[DRAFTABLE]||isMap(value)||isSet(value):!1}var objectCtorString=Object.prototype.constructor.toString(),cachedCtorStrings=new WeakMap;function isPlainObject2(value){if(!value||typeof value!="object")return!1;let proto=Object.getPrototypeOf(value);if(proto===null||proto===Object.prototype)return!0;let Ctor=Object.hasOwnProperty.call(proto,"constructor")&&proto.constructor;if(Ctor===Object)return!0;if(typeof Ctor!="function")return!1;let ctorString=cachedCtorStrings.get(Ctor);return ctorString===void 0&&(ctorString=Function.toString.call(Ctor),cachedCtorStrings.set(Ctor,ctorString)),ctorString===objectCtorString}function each(obj,iter,strict=!0){getArchtype(obj)===0?(strict?Reflect.ownKeys(obj):Object.keys(obj)).forEach(key=>{iter(key,obj[key],obj)}):obj.forEach((entry,index)=>iter(index,entry,obj))}function getArchtype(thing){let state=thing[DRAFT_STATE];return state?state.type_:Array.isArray(thing)?1:isMap(thing)?2:isSet(thing)?3:0}function has(thing,prop){return getArchtype(thing)===2?thing.has(prop):Object.prototype.hasOwnProperty.call(thing,prop)}function set2(thing,propOrOldValue,value){let t=getArchtype(thing);t===2?thing.set(propOrOldValue,value):t===3?thing.add(value):thing[propOrOldValue]=value}function is(x,y){return x===y?x!==0||1/x===1/y:x!==x&&y!==y}function isMap(target){return target instanceof Map}function isSet(target){return target instanceof Set}function latest(state){return state.copy_||state.base_}function shallowCopy(base,strict){if(isMap(base))return new Map(base);if(isSet(base))return new Set(base);if(Array.isArray(base))return Array.prototype.slice.call(base);let isPlain=isPlainObject2(base);if(strict===!0||strict==="class_only"&&!isPlain){let descriptors=Object.getOwnPropertyDescriptors(base);delete descriptors[DRAFT_STATE];let keys=Reflect.ownKeys(descriptors);for(let i=0;i<keys.length;i++){let key=keys[i],desc=descriptors[key];desc.writable===!1&&(desc.writable=!0,desc.configurable=!0),(desc.get||desc.set)&&(descriptors[key]={configurable:!0,writable:!0,enumerable:desc.enumerable,value:base[key]})}return Object.create(getPrototypeOf(base),descriptors)}else{let proto=getPrototypeOf(base);if(proto!==null&&isPlain)return{...base};let obj=Object.create(proto);return Object.assign(obj,base)}}function freeze(obj,deep=!1){return isFrozen(obj)||isDraft(obj)||!isDraftable(obj)||(getArchtype(obj)>1&&Object.defineProperties(obj,{set:dontMutateMethodOverride,add:dontMutateMethodOverride,clear:dontMutateMethodOverride,delete:dontMutateMethodOverride}),Object.freeze(obj),deep&&Object.values(obj).forEach(value=>freeze(value,!0))),obj}function dontMutateFrozenCollections(){die(2)}var dontMutateMethodOverride={value:dontMutateFrozenCollections};function isFrozen(obj){return obj===null||typeof obj!="object"?!0:Object.isFrozen(obj)}var plugins={};function getPlugin(pluginKey){let plugin=plugins[pluginKey];return plugin||die(0,pluginKey),plugin}var currentScope;function getCurrentScope(){return currentScope}function createScope(parent_,immer_){return{drafts_:[],parent_,immer_,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function usePatchesInScope(scope,patchListener){patchListener&&(getPlugin("Patches"),scope.patches_=[],scope.inversePatches_=[],scope.patchListener_=patchListener)}function revokeScope(scope){leaveScope(scope),scope.drafts_.forEach(revokeDraft),scope.drafts_=null}function leaveScope(scope){scope===currentScope&&(currentScope=scope.parent_)}function enterScope(immer2){return currentScope=createScope(currentScope,immer2)}function revokeDraft(draft){let state=draft[DRAFT_STATE];state.type_===0||state.type_===1?state.revoke_():state.revoked_=!0}function processResult(result,scope){scope.unfinalizedDrafts_=scope.drafts_.length;let baseDraft=scope.drafts_[0];return result!==void 0&&result!==baseDraft?(baseDraft[DRAFT_STATE].modified_&&(revokeScope(scope),die(4)),isDraftable(result)&&(result=finalize(scope,result),scope.parent_||maybeFreeze(scope,result)),scope.patches_&&getPlugin("Patches").generateReplacementPatches_(baseDraft[DRAFT_STATE].base_,result,scope.patches_,scope.inversePatches_)):result=finalize(scope,baseDraft,[]),revokeScope(scope),scope.patches_&&scope.patchListener_(scope.patches_,scope.inversePatches_),result!==NOTHING?result:void 0}function finalize(rootScope,value,path){if(isFrozen(value))return value;let useStrictIteration=rootScope.immer_.shouldUseStrictIteration(),state=value[DRAFT_STATE];if(!state)return each(value,(key,childValue)=>finalizeProperty(rootScope,state,value,key,childValue,path),useStrictIteration),value;if(state.scope_!==rootScope)return value;if(!state.modified_)return maybeFreeze(rootScope,state.base_,!0),state.base_;if(!state.finalized_){state.finalized_=!0,state.scope_.unfinalizedDrafts_--;let result=state.copy_,resultEach=result,isSet2=!1;state.type_===3&&(resultEach=new Set(result),result.clear(),isSet2=!0),each(resultEach,(key,childValue)=>finalizeProperty(rootScope,state,result,key,childValue,path,isSet2),useStrictIteration),maybeFreeze(rootScope,result,!1),path&&rootScope.patches_&&getPlugin("Patches").generatePatches_(state,path,rootScope.patches_,rootScope.inversePatches_)}return state.copy_}function finalizeProperty(rootScope,parentState,targetObject,prop,childValue,rootPath,targetIsSet){if(childValue==null||typeof childValue!="object"&&!targetIsSet)return;let childIsFrozen=isFrozen(childValue);if(!(childIsFrozen&&!targetIsSet)){if(childValue===targetObject&&die(5),isDraft(childValue)){let path=rootPath&&parentState&&parentState.type_!==3&&!has(parentState.assigned_,prop)?rootPath.concat(prop):void 0,res=finalize(rootScope,childValue,path);if(set2(targetObject,prop,res),isDraft(res))rootScope.canAutoFreeze_=!1;else return}else targetIsSet&&targetObject.add(childValue);if(isDraftable(childValue)&&!childIsFrozen){if(!rootScope.immer_.autoFreeze_&&rootScope.unfinalizedDrafts_<1||parentState&&parentState.base_&&parentState.base_[prop]===childValue&&childIsFrozen)return;finalize(rootScope,childValue),(!parentState||!parentState.scope_.parent_)&&typeof prop!="symbol"&&(isMap(targetObject)?targetObject.has(prop):Object.prototype.propertyIsEnumerable.call(targetObject,prop))&&maybeFreeze(rootScope,childValue)}}}function maybeFreeze(scope,value,deep=!1){!scope.parent_&&scope.immer_.autoFreeze_&&scope.canAutoFreeze_&&freeze(value,deep)}function createProxyProxy(base,parent){let isArray=Array.isArray(base),state={type_:isArray?1:0,scope_:parent?parent.scope_:getCurrentScope(),modified_:!1,finalized_:!1,assigned_:{},parent_:parent,base_:base,draft_:null,copy_:null,revoke_:null,isManual_:!1},target=state,traps=objectTraps;isArray&&(target=[state],traps=arrayTraps);let{revoke,proxy}=Proxy.revocable(target,traps);return state.draft_=proxy,state.revoke_=revoke,proxy}var objectTraps={get(state,prop){if(prop===DRAFT_STATE)return state;let source=latest(state);if(!has(source,prop))return readPropFromProto(state,source,prop);let value=source[prop];return state.finalized_||!isDraftable(value)?value:value===peek(state.base_,prop)?(prepareCopy(state),state.copy_[prop]=createProxy(value,state)):value},has(state,prop){return prop in latest(state)},ownKeys(state){return Reflect.ownKeys(latest(state))},set(state,prop,value){let desc=getDescriptorFromProto(latest(state),prop);if(desc?.set)return desc.set.call(state.draft_,value),!0;if(!state.modified_){let current2=peek(latest(state),prop),currentState=current2?.[DRAFT_STATE];if(currentState&¤tState.base_===value)return state.copy_[prop]=value,state.assigned_[prop]=!1,!0;if(is(value,current2)&&(value!==void 0||has(state.base_,prop)))return!0;prepareCopy(state),markChanged(state)}return state.copy_[prop]===value&&(value!==void 0||prop in state.copy_)||Number.isNaN(value)&&Number.isNaN(state.copy_[prop])||(state.copy_[prop]=value,state.assigned_[prop]=!0),!0},deleteProperty(state,prop){return peek(state.base_,prop)!==void 0||prop in state.base_?(state.assigned_[prop]=!1,prepareCopy(state),markChanged(state)):delete state.assigned_[prop],state.copy_&&delete state.copy_[prop],!0},getOwnPropertyDescriptor(state,prop){let owner=latest(state),desc=Reflect.getOwnPropertyDescriptor(owner,prop);return desc&&{writable:!0,configurable:state.type_!==1||prop!=="length",enumerable:desc.enumerable,value:owner[prop]}},defineProperty(){die(11)},getPrototypeOf(state){return getPrototypeOf(state.base_)},setPrototypeOf(){die(12)}},arrayTraps={};each(objectTraps,(key,fn)=>{arrayTraps[key]=function(){return arguments[0]=arguments[0][0],fn.apply(this,arguments)}});arrayTraps.deleteProperty=function(state,prop){return isNaN(parseInt(prop))&&die(13),arrayTraps.set.call(this,state,prop,void 0)};arrayTraps.set=function(state,prop,value){return prop!=="length"&&isNaN(parseInt(prop))&&die(14),objectTraps.set.call(this,state[0],prop,value,state[0])};function peek(draft,prop){let state=draft[DRAFT_STATE];return(state?latest(state):draft)[prop]}function readPropFromProto(state,source,prop){let desc=getDescriptorFromProto(source,prop);return desc?"value"in desc?desc.value:desc.get?.call(state.draft_):void 0}function getDescriptorFromProto(source,prop){if(!(prop in source))return;let proto=getPrototypeOf(source);for(;proto;){let desc=Object.getOwnPropertyDescriptor(proto,prop);if(desc)return desc;proto=getPrototypeOf(proto)}}function markChanged(state){state.modified_||(state.modified_=!0,state.parent_&&markChanged(state.parent_))}function prepareCopy(state){state.copy_||(state.copy_=shallowCopy(state.base_,state.scope_.immer_.useStrictShallowCopy_))}var Immer2=class{constructor(config2){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(base,recipe,patchListener)=>{if(typeof base=="function"&&typeof recipe!="function"){let defaultBase=recipe;recipe=base;let self=this;return function(base2=defaultBase,...args){return self.produce(base2,draft=>recipe.call(this,draft,...args))}}typeof recipe!="function"&&die(6),patchListener!==void 0&&typeof patchListener!="function"&&die(7);let result;if(isDraftable(base)){let scope=enterScope(this),proxy=createProxy(base,void 0),hasError=!0;try{result=recipe(proxy),hasError=!1}finally{hasError?revokeScope(scope):leaveScope(scope)}return usePatchesInScope(scope,patchListener),processResult(result,scope)}else if(!base||typeof base!="object"){if(result=recipe(base),result===void 0&&(result=base),result===NOTHING&&(result=void 0),this.autoFreeze_&&freeze(result,!0),patchListener){let p=[],ip=[];getPlugin("Patches").generateReplacementPatches_(base,result,p,ip),patchListener(p,ip)}return result}else die(1,base)},this.produceWithPatches=(base,recipe)=>{if(typeof base=="function")return(state,...args)=>this.produceWithPatches(state,draft=>base(draft,...args));let patches,inversePatches;return[this.produce(base,recipe,(p,ip)=>{patches=p,inversePatches=ip}),patches,inversePatches]},typeof config2?.autoFreeze=="boolean"&&this.setAutoFreeze(config2.autoFreeze),typeof config2?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(config2.useStrictShallowCopy),typeof config2?.useStrictIteration=="boolean"&&this.setUseStrictIteration(config2.useStrictIteration)}createDraft(base){isDraftable(base)||die(8),isDraft(base)&&(base=current(base));let scope=enterScope(this),proxy=createProxy(base,void 0);return proxy[DRAFT_STATE].isManual_=!0,leaveScope(scope),proxy}finishDraft(draft,patchListener){let state=draft&&draft[DRAFT_STATE];(!state||!state.isManual_)&&die(9);let{scope_:scope}=state;return usePatchesInScope(scope,patchListener),processResult(void 0,scope)}setAutoFreeze(value){this.autoFreeze_=value}setUseStrictShallowCopy(value){this.useStrictShallowCopy_=value}setUseStrictIteration(value){this.useStrictIteration_=value}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(base,patches){let i;for(i=patches.length-1;i>=0;i--){let patch=patches[i];if(patch.path.length===0&&patch.op==="replace"){base=patch.value;break}}i>-1&&(patches=patches.slice(i+1));let applyPatchesImpl=getPlugin("Patches").applyPatches_;return isDraft(base)?applyPatchesImpl(base,patches):this.produce(base,draft=>applyPatchesImpl(draft,patches))}};function createProxy(value,parent){let draft=isMap(value)?getPlugin("MapSet").proxyMap_(value,parent):isSet(value)?getPlugin("MapSet").proxySet_(value,parent):createProxyProxy(value,parent);return(parent?parent.scope_:getCurrentScope()).drafts_.push(draft),draft}function current(value){return isDraft(value)||die(10,value),currentImpl(value)}function currentImpl(value){if(!isDraftable(value)||isFrozen(value))return value;let state=value[DRAFT_STATE],copy,strict=!0;if(state){if(!state.modified_)return state.base_;state.finalized_=!0,copy=shallowCopy(value,state.scope_.immer_.useStrictShallowCopy_),strict=state.scope_.immer_.shouldUseStrictIteration()}else copy=shallowCopy(value,!0);return each(copy,(key,childValue)=>{set2(copy,key,currentImpl(childValue))},strict),state&&(state.finalized_=!1),copy}var immer=new Immer2,produce=immer.produce;var NONE=Symbol("NONE"),readKey=(value,key,dval=null)=>value==null?dval:value instanceof Map?value.has(key)?value.get(key):dval:value instanceof Set?value.has(key)?key:dval:Object.hasOwn(value,key)?value[key]:dval,writeKey=(value,key,next)=>{value instanceof Map?value.set(key,next):value instanceof Set?(value.delete(key),value.add(next)):value[key]=next},writeSeqKey=(value,key,next)=>{value instanceof Map||value instanceof Set||Array.isArray(value)||Object.hasOwn(value,key)?writeKey(value,key,next):typeof value?.set=="function"?value.set(key,next):writeKey(value,key,next)},Step=class{lookup(_v,dval=null){return dval}setDraftValue(_root,_v){}enterFrame(stack,next){return stack.enter(next,{},!0)}toAbstractPathStep(){return this}pinKey(_v){return this}toKey(){return null}},BindStep=class _BindStep extends Step{constructor(binds){super(),this.binds=binds}lookup(v,_dval){return v}enterFrame(stack,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}},ScopeBindStep=class _ScopeBindStep extends BindStep{constructor(val,binds={}){super(binds),this.val=val}enterFrame(stack,next){let dyn=this.val.evalAsHandler(stack)?.call(stack.it)??{};return stack.enter(next,{...this.binds,...dyn},!1)}withIndex(i){return new _ScopeBindStep(this.val,{...this.binds,key:i})}withKey(key){return new _ScopeBindStep(this.val,{...this.binds,key})}},FieldStep=class extends Step{constructor(field){super(),this.field=field}lookup(v,dval=null){return readKey(v,this.field,dval)}setDraftValue(root,v){writeKey(root,this.field,v)}withIndex(i){return new SeqStep(this.field,i)}withKey(k){return new SeqStep(this.field,k)}toKey(){return{field:this.field}}},SeqStep=class extends Step{constructor(field,key){super(),this.field=field,this.key=key}lookup(v,dval=null){return seqGet(readKey(v,this.field,null),this.key,dval)}setDraftValue(root,v){let seq=readKey(root,this.field,null);seq!=null&&writeSeqKey(seq,this.key,v)}enterFrame(stack,next){return stack.enter(next,{key:this.key},!0)}toKey(){return{field:this.field,key:this.key}}},SeqAccessStep=class extends Step{constructor(seqField,keyField){super(),this.seqField=seqField,this.keyField=keyField}lookup(v,dval=null){let seq=readKey(v,this.seqField,NONE),key=readKey(v,this.keyField,NONE);return key!==NONE&&seq!==NONE?seqGet(seq,key,dval):dval}setDraftValue(root,v){let seq=readKey(root,this.seqField,NONE),key=readKey(root,this.keyField,NONE);seq!==NONE&&key!==NONE&&writeSeqKey(seq,key,v)}pinKey(v){let key=readKey(v,this.keyField,NONE);return key===NONE?this:new SeqStep(this.seqField,key)}toKey(){return{field:this.seqField}}},EachBindStep=class extends Step{constructor(iterInfo,key){super(),this.iterInfo=iterInfo,this.key=key}lookup(v,_dval){return v}enterFrame(stack,next){return stack.enter(next,this.iterInfo.enrichBinds(stack,this.key),!1)}toAbstractPathStep(){return null}},EachRenderItStep=class extends SeqStep{enterFrame(stack,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)}var DynStep=class 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}enterFrame(stack,_next){return warnRawDynStep("enterFrame",this),stack}},DynEachStep=class 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];return last instanceof FieldStep?producerSteps.slice(0,-1).concat(new SeqStep(last.field,key)):(console.warn("DynEachStep: seq-access dynamic cannot be iterated",this),producerSteps)}},Path=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();s!==null&&(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){for(;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)}pinKeys(root){let curVal=root,out=null;for(let i=0;i<this.steps.length;i++){let step=this.steps[i],pinned=step.pinKey(curVal);if(pinned!==step&&((out??=this.steps.slice())[i]=pinned),curVal=step.lookup(curVal,NONE),curVal===NONE)break}return out?new _Path(out):this}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}resolveChain(root){let out=[root],curVal=root;for(let step of this.steps){if(curVal=step.lookup(curVal,NONE),curVal===NONE)break;out.push(curVal)}return out}toKeys(){let out=[];for(let step of this.steps){let k=step.toKey();k!==null&&out.push(k)}return out}setValue(root,v){return this.steps.length===0?v:produce(root,draft=>{let parent=draft;for(let i=0;i<this.steps.length-1;i++)if(parent=this.steps[i].lookup(parent,NONE),parent===NONE)return;this.steps.at(-1).setDraftValue(parent,v)})}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,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,crossComponent=(cidNum,vid)=>{let 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!1}else 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);step&&(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--)pendingDyns[i].producerCompId===cidNum&&pendingDyns.splice(i,1);return eventIds=[],nodeIds=[],!0};for(;node&&node!==rootNode&&depth<maxDepth;){if(node?.dataset){let{eid,cid,vid}=node.dataset;eid!==void 0&&eventIds.push(eid);let metas=metaChain(node.previousSibling),sawComp=!1;for(let m of metas)if(m.$==="Comp"){if(sawComp=!0,!crossComponent(m.cid,m.vid))return NO_EVENT_INFO;nodeIds.push({nid:m.nid})}else nodeIds.push({nid:m.nid,si:m.si,sk:m.sk});if(!sawComp&&cid!==void 0&&!crossComponent(+cid,vid))return NO_EVENT_INFO}depth+=1,node=node.parentNode}return pendingDyns.length>0&&console.warn("event reconstruction: dynamic-var producer not found",pendingDyns),[new _Path(pathSteps.reverse()),handlers]}};function metaChain(n){let out=[];for(;n?.nodeType===8&&n.textContent[0]==="§";){try{out.push(JSON.parse(n.textContent.slice(1,-1)))}catch(err){console.warn(err,n)}n=n.previousSibling}return out}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}var StepCtx=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;return m.si!==void 0?pi.withIndex(+m.si):m.sk!==void 0?pi.withKey(m.sk):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"]),PathBuilder=class{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 isMac=(globalThis.navigator?.userAgent??"").toLowerCase().includes("mac");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_SEQ=256,K_METHOD=1024,K_EVENT=2048,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_PROVIDE=K_FIELD|K_SEQ,G_FIELD=K_FIELD|K_METHOD|K_CONST|K_SEQ,G_VALUE=K_FIELD|K_METHOD|K_BIND|K_DYN|K_NAME|K_CONST,G_HANDLER_ARG=G_VALUE&~K_NAME|K_EVENT,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:isPlainObject(v)?Object.keys(v).length:null}var 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}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)=>Object.is(a,b)}};function 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))):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 _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=parseToken(tokens[0],px);return val instanceof ConstVal&&(val.fromMacroVar=!0),val}return px.onParseIssue("bad-value",{role:"macro-var",name,value:s}),null}case 36:return mkVal(s.slice(1),MethodVal);case 64:{let dot=s.indexOf(".",1);if(dot===-1)return mkVal(s.slice(1),BindVal);let name=s.slice(1,dot),member=s.slice(dot+1);return isValidValId(name)&&isValidValId(member)?new BindMemberVal(name,member):null}case 42:return mkVal(s.slice(1),DynVal);case 46:return mkVal(s.slice(1),FieldVal)}let num=VALID_FLOAT_RE.test(s)?parseFloat(s):null;return Number.isFinite(num)?new ConstVal(num):s==="true"||s==="false"?new ConstVal(s==="true"):c0===101&&/^e(\.[a-zA-Z][a-zA-Z0-9_]*)+$/.exec(s)!==null?new EventMemberVal(s.split(".").slice(1)):c0>=97&&c0<=122?mkVal(s,NameVal):null}function _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=parseToken(s.slice(0,open),px),right=parseToken(s.slice(open+1,close),px);return left instanceof FieldVal&&right instanceof FieldVal?new SeqAccessVal(left,right):null}function _parseSingle(s,px,group){let tokens=tokenizeValue(s.trim());if(tokens.length!==1)return null;let val=parseToken(tokens[0],px);return val!==null&&kindOf(val)&group?val:null}function parseBool(s,px){let t=s.trim(),tokens=tokenizeValue(t);if(tokens.length!==1)return tokens.length===0?null:_parsePredicate(t,tokens,px);let val=parseToken(tokens[0],px);return val!==null&&kindOf(val)&G_BOOL?val:null}var parseText=(s,px)=>_parseSingle(s,px,G_TEXT),parseComponent=(s,px)=>_parseSingle(s,px,G_COMPONENT),parseSequence=(s,px)=>_parseSingle(s,px,G_SEQUENCE),parseField=(s,px)=>_parseSingle(s,px,G_FIELD),parseProvide=(s,px)=>_parseSingle(s,px,G_PROVIDE),parseMacroAttr=(s,px)=>_parseSingle(s,px,G_ALL),parseReceiveHandler=(s,px)=>_parseHandler(s,px,"receive",!0,!0,!1),parseAlterHandler=(s,px)=>_parseHandler(s,px,"alter",!1,!1,!0)?.handlerVal??null;function _parseHandler(s,px,namespace,allowArgs,report,allowMethod){let tokens=tokenizeValue(s.trim()),headTok=tokens[0]??"",head=headTok===""?null:parseToken(headTok,px),hk=kindOf(head),handlerVal;if(hk&K_METHOD&&allowMethod)handlerVal=head;else{if(hk&K_METHOD)return report&&px.onParseIssue("event-method-handler",{name:head.name,role:"handler-name",value:headTok}),null;if(hk&K_NAME)handlerVal=new HandlerNameVal(head.name,namespace);else return report&&px.onParseIssue("bad-value",{role:"handler-name",value:headTok}),null}if(!allowArgs)return tokens.length===1?{handlerVal,args:[]}:null;let args=new Array(tokens.length-1);for(let i=1;i<tokens.length;i++){let val=parseToken(tokens[i],px);val!==null&&kindOf(val)&G_HANDLER_ARG?args[i-1]=val:(report&&px.onParseIssue("bad-value",{role:"handler-arg",value:tokens[i]}),args[i-1]=NULL_CONST_VAL)}return{handlerVal,args}}function _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=new Array(arity);for(let i=0;i<arity;i++){let tok=tokens[i+1],val=parseToken(tok,px);if(val===null||!(kindOf(val)&G_BOOL))return px.onParseIssue("bad-value",{role:"predicate-arg",value:tok}),null;args[i]=val}return new PredicateVal(pred,args)}function kindOf(val){return val===null?0:val instanceof ConstVal||val instanceof StrTplVal?val.kind:val instanceof SeqAccessVal?K_SEQ:val instanceof FieldVal?K_FIELD:val instanceof MethodVal?K_METHOD:val instanceof BindVal?K_BIND:val instanceof DynVal?K_DYN:val instanceof NameVal?K_NAME:val instanceof EventMemberVal?K_EVENT:0}var BaseVal=class{render(_stack,_rx){}eval(_stack){}toPathItem(){return null}evalAsHandler(stack){return this.eval(stack)}},ConstVal=class 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}`}},NULL_CONST_VAL=new ConstVal(null),PredicateVal=class extends BaseVal{constructor(pred,args){super(),this.pred=pred,this.args=args}eval(stack){let n=this.args.length,vals=new 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(" ")}`}},VarVal=class extends BaseVal{},StrTplVal=class _StrTplVal extends VarVal{constructor(vals){super(),this.vals=vals,this.kind=this.isLiteral()?K_CONST:K_STRTPL}isLiteral(){for(let v of this.vals)if(!(v instanceof ConstVal)||v.fromMacroVar)return!1;return!0}render(stack,_rx){return this.eval(stack)}eval(stack){let strs=new Array(this.vals.length);for(let i=0;i<this.vals.length;i++)strs[i]=this.vals[i]?.eval(stack,"");return strs.join("")}toLiteralSource(){if(!this.isLiteral())return null;let out="";for(let v of this.vals)out+=v.val;return new ConstVal(out).toString()}static parse(s,px){let parts=unescapeStr(s).split(STR_TPL_SPLIT_RE),vals=new Array(parts.length);for(let i=0;i<parts.length;i++){let part=parts[i],isExpr=part[0]==="{"&&part.at(-1)==="}";vals[i]=isExpr?parseText(part.slice(1,-1),px):new ConstVal(part)}let lo=0,hi=vals.length,isTrimmable=v=>v instanceof ConstVal&&v.val===""&&!v.fromMacroVar;for(;lo<hi&&isTrimmable(vals[lo]);)lo++;for(;hi>lo&&isTrimmable(vals[hi-1]);)hi--;return new _StrTplVal(lo===0&&hi===vals.length?vals:vals.slice(lo,hi))}},NameVal=class extends VarVal{constructor(name){super(),this.name=name}toString(){return this.name}},HandlerNameVal=class extends NameVal{constructor(name,namespace){super(name),this.namespace=namespace}eval(stack){return stack.getHandlerFor(this.name,this.namespace)??mk404Handler(stack,this.namespace,this.name)}},mk404Handler=(stack,type3,name)=>function(...args){let transactor=stack?.ctx?.transactor;return transactor?transactor.refuse("NO_HANDLER",{namespace:type3,name,argCount:args.length}):console.warn("handler not found",{type:type3,name}),this},keyIs=k=>e=>e.key===k,macCtrl=e=>isMac&&e.metaKey||e.ctrlKey,nullSafe=fn=>(e,stack)=>{let info=stack.lookupDragInfo();return info==null?null:fn(info)},EVENT_CONVENIENCES={value:e=>getValue(e),valueAsInt:e=>toNullIfNaN(parseInt(getValue(e),10)),valueAsFloat:e=>toNullIfNaN(parseFloat(getValue(e))),isAlt:e=>e.altKey,isShift:e=>e.shiftKey,isCtrl:macCtrl,isCmd:macCtrl,isUpKey:keyIs("ArrowUp"),isDownKey:keyIs("ArrowDown"),isSend:keyIs("Enter"),isCancel:keyIs("Escape"),isTabKey:keyIs("Tab"),dragInfo:(_e,stack)=>stack.lookupDragInfo(),dragType:nullSafe(info=>info.type),dragValue:nullSafe(info=>info.val),dragKey:nullSafe(info=>info.lookupBind("key"))},EventMemberVal=class extends BaseVal{constructor(members){super(),this.members=members}eval(stack){let e=stack.lookupEvent();if(e==null)return null;if(this.members.length===1){let convenience=EVENT_CONVENIENCES[this.members[0]];if(convenience!==void 0)return convenience(e,stack)}let v=e;for(let member of this.members){if(v==null)return null;v=v[member]}return v??null}toString(){return`e.${this.members.join(".")}`}},RenderVal=class extends BaseVal{render(stack,_rx){return this.eval(stack)}},RenderNameVal=class extends RenderVal{constructor(name){super(),this.name=name}},BindVal=class extends RenderNameVal{eval(stack){return stack.lookupBind(this.name)}toString(){return`@${this.name}`}},BindMemberVal=class extends BindVal{constructor(name,member){super(name),this.member=member}eval(stack){let v=stack.lookupBind(this.name);return seqGet(v,this.member,null)}toString(){return`@${this.name}.${this.member}`}},DynVal=class extends RenderNameVal{eval(stack){return stack.lookupDynamic(this.name)}toString(){return`*${this.name}`}},FieldVal=class extends RenderNameVal{eval(stack){return stack.lookupFieldRaw(this.name)}toPathItem(){return new FieldStep(this.name)}toString(){return`.${this.name}`}},MethodVal=class extends RenderNameVal{eval(stack){return stack.lookupMethod(this.name)}evalAsHandler(stack){return stack.lookupFieldRaw(this.name)}toString(){return`$${this.name}`}},SeqAccessVal=class 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 seqGet(this.seqVal.eval(stack),key,null)}toString(){return`${this.seqVal}[${this.keyVal}]`}};var Attributes=class{constructor(items){this.items=items}static parse(attributes,px,parseAll=!1){return new AttrParser(px).parse(attributes,parseAll)}isConstant(){return!1}},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(","));function parseDirectiveValue(px,directiveName,source,parser){let val=parser(source,px);return val===null&&px.onParseIssue("bad-value",{role:"directive",directive:directiveName,value:source}),val}function parseIterationDirectives(attributes,px){let parseNamed=name=>{let attr=attributes.getNamedItem(`@${name}`);return attr?parseDirectiveValue(px,name,attr.value,parseAlterHandler):null};return{whenVal:parseNamed("when"),loopWithVal:parseNamed("loop-with")}}var AttrParser=class{constructor(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?parseMacroAttr(value,this.px):parseText(value,this.px);val!==null?(this.attrs??=[],this.attrs.push(new Attr(name,val)),this.hasDynamic||=!(val instanceof ConstVal)):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=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){this.ifAttr&&(this.ifAttr.thenVal=parseText(s,this.px)??NOT_SET_VAL)}parseElse(value){this.ifAttr&&(this.ifAttr.elseVal=parseText(value,this.px)??NOT_SET_VAL)}parseEvent(directiveName,value){let[eventName,...modifiers]=directiveName.slice(3).split("+"),handler=EventHandler.parse(value,this.px);handler&&(this.events===null&&(this.events=this.px.registerEvents(),this.attrs??=[],this.attrs.push(new ConstAttr("data-eid",new ConstVal(this.events.id)))),this.events.add(eventName,handler,modifiers))}_parseDirectiveValue(directiveName,s,parserFn){return parseDirectiveValue(this.px,directiveName,s,parserFn)}parseDirective(s,directiveName){switch(directiveName){case"dangerouslysetinnerhtml":this.attrs??=[],this.attrs.push(new RawHtmlAttr(this._parseDirectiveValue(directiveName,s,parseText))),this.hasDynamic=!0;return;case"push-view":this.pushWrapper("push-view",s,this._parseDirectiveValue(directiveName,s,parseText));return;case"text":this.textChild=this._parseDirectiveValue(directiveName,s,parseText);return;case"show":this.pushWrapper("show",s,this._parseDirectiveValue(directiveName,s,parseBool));return;case"hide":this.pushWrapper("hide",s,this._parseDirectiveValue(directiveName,s,parseBool));return;case"each":{let val=this._parseDirectiveValue(directiveName,s,parseSequence);this.eachAttr=this.pushWrapper("each",s,val);return}case"enrich-with":this.eachAttr!==null?this.eachAttr.enrichWithVal=this._parseDirectiveValue(directiveName,s,parseAlterHandler):this.pushWrapper("scope",s,this._parseDirectiveValue(directiveName,s,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){this.eachAttr!==null&&(this.eachAttr.whenVal=this._parseDirectiveValue("when",s,parseAlterHandler))}_parseLoopWith(s){this.eachAttr!==null&&(this.eachAttr.loopWithVal=this._parseDirectiveValue("loop-with",s,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,new ConstVal(constVal)))}}let{attrs,hasDynamic}=this;return[hasDynamic?new DynAttrs(attrs):ConstAttrs.fromAttrs(attrs??[]),this.wrapperAttrs,this.textChild]}},ConstAttrs=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]=new ConstVal(`${this.items[name]}`).toString();return r}isConstant(){return!0}},DynAttrs=class 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}},BaseAttr=class{constructor(name){this.name=name}},Attr=class extends BaseAttr{constructor(name,val){super(name),this.val=val}eval(stack){return this.val.eval(stack)}},ConstAttr=class extends Attr{},RawHtmlAttr=class extends Attr{constructor(val){super("dangerouslySetInnerHTML",val??NULL_CONST_VAL)}eval(stack){return{__html:`${this.val.eval(stack)}`}}},NOT_SET_VAL=NULL_CONST_VAL,IfAttr=class 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)}},EventHandler=class _EventHandler{constructor(handlerVal,args=[]){this.handlerVal=handlerVal,this.args=args}getHandlerAndArgs(stack,_event){let argValues=new 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=parseReceiveHandler(s,px);return r===null?null:new _EventHandler(r.handlerVal,r.args)}};var SEQ_INFO=Symbol.for("tutuca.seqInfo"),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]},nativeIndexedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seqSize(seq));for(let i=s;i<e;i++)visit(i,seq[i],"si")},nativeKeyedIter=(seq,visit,start,end)=>{let[s,e]=normalizeRange(start,end,seqSize(seq)),i=0;for(let[key,value]of seqEntries(seq)){if(i>=e)break;i>=s&&visit(key,value,"sk"),i++}},unknownIter=()=>{},getSeqInfo=seq=>isIndexedSeq(seq)?nativeIndexedIter:isKeyedSeq(seq)||isSetSeq(seq)?nativeKeyedIter:seq?.[SEQ_INFO]??unknownIter,filterAlwaysTrue=(_key,_value,_iterData)=>!0,nullLoopWith=seq=>({iterData:{seq}}),unpackLoopResult=(result,seq)=>{let value=result??{};return{iterData:value.iterData??{seq},start:value.start,end:value.end,keys:value.keys}},makeLoopCtx=(stack,filter)=>({lookup:name=>stack.lookupBind(name),filter:(key,value,iterData)=>filter.call(stack.it,key,value,iterData)}),callEnricher=(enricher,it,binds,key,value,iterData)=>{enricher.call(it,binds,key,value,iterData),console.assert(binds.key===key&&binds.value===value,"@enrich-with handlers must not overwrite binds.key or binds.value"),binds.key=key,binds.value=value};function bindsForKey({seq,it,loopWith,enricher,ctx},key){let value=seqGet(seq,key,null),binds={key,value};if(enricher){let{iterData}=unpackLoopResult(loopWith.call(it,seq,ctx),seq);callEnricher(enricher,it,binds,key,value,iterData)}return binds}var visitKeys=(seq,keys,visit)=>{let attrName=isIndexedSeq(seq)?"si":"sk";for(let key of keys)visit(key,seqGet(seq,key),attrName)};function walkLoopBindings({seq,it,filter,loopWith,enricher,ctx},visit){let{iterData,start,end,keys}=unpackLoopResult(loopWith.call(it,seq,ctx),seq),visitOne=(key,value,attrName)=>{let binds={key,value};enricher&&callEnricher(enricher,it,binds,key,value,iterData),visit(key,value,attrName,binds)};keys?visitKeys(seq,keys,visitOne):getSeqInfo(seq)(seq,(key,value,attrName)=>{filter.call(it,key,value,iterData)&&visitOne(key,value,attrName)},start,end)}var HTML_NS="http://www.w3.org/1999/xhtml",SVG_NS="http://www.w3.org/2000/svg",MATH_NS="http://www.w3.org/1998/Math/MathML",isNamespaced=node=>{let ns=node.namespaceURI;return ns!==null&&ns!==HTML_NS},isForeignObject=tag=>tag.length===13&&tag.toLowerCase()==="foreignobject",effectiveNs=(vnode,opts)=>vnode.namespace??opts.namespace??null;function childOpts(vnode,ns,opts){let target=ns===SVG_NS&&isForeignObject(vnode.tag)?null:ns;return target===(opts.namespace??null)?opts:{...opts,namespace:target}}var NEVER_ASSIGN=new Set("width height href list form tabIndex download rowSpan colSpan role popover".split(" ")),PROP_ATTR_NAME={className:"class",htmlFor:"for"};function applyProperties(node,props){let namespaced=isNamespaced(node);for(let name in props)setProp(node,name,props[name],namespaced)}function setProp(node,name,value,namespaced){if(name==="dangerouslySetInnerHTML"){if(value===void 0)node.replaceChildren();else{let html2=value.__html??"";html2!==node.innerHTML&&(node.innerHTML=html2)}return}if(typeof value=="function")return;let usesProp=!namespaced&&!NEVER_ASSIGN.has(name)&&name in node;if(usesProp&&value!=null)try{node[name]=value;return}catch{}if(value==null||value===!1&&name[4]!=="-")if(usesProp){try{node[name]=""}catch{}node.removeAttribute(PROP_ATTR_NAME[name]??name)}else node.removeAttribute(name);else node.setAttribute(name,value)}function applyValueLast(node,value){node.tagName==="PROGRESS"&&(value==null||value===0)?node.removeAttribute("value"):setProp(node,"value",value,isNamespaced(node))}var VBase=class{},getKey=child=>child instanceof VNode?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)if(isIterable(child))for(let c of child)addChild(normalizedChildren,c);else child instanceof VBase?child instanceof VFragment?normalizedChildren.push(...child.childs):normalizedChildren.push(child):normalizedChildren.push(new VText(child))}var VText=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)}},VComment=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)}},VFragment=class _VFragment extends VBase{constructor(childs){super(),this.childs=[],addChild(this.childs,childs)}get nodeType(){return 11}isEqualTo(other){return!(other instanceof _VFragment)||this.childs.length!==other.childs.length?!1:childsEqual(this.childs,other.childs)}toDom(opts){let fragment=opts.document.createDocumentFragment();return appendChildNodes(fragment,this.childs,opts),fragment}},VNode=class _VNode 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 _VNode)||!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,ns=effectiveNs(this,opts),tag=ns!==null&&this.tag===this.tag.toUpperCase()?this.tag.toLowerCase():this.tag,attrs=this.attrs,createOpts=attrs.is!=null?{is:attrs.is}:void 0,node=ns===null?doc.createElement(tag,createOpts):doc.createElementNS(ns,tag,createOpts),cOpts=childOpts(this,ns,opts);if("value"in attrs||"checked"in attrs){let{value,checked,...rest}=attrs;applyProperties(node,rest),appendChildNodes(node,this.childs,cOpts),value!==void 0&&applyValueLast(node,value),checked!==void 0&&setProp(node,"checked",checked,!1)}else applyProperties(node,attrs),appendChildNodes(node,this.childs,cOpts);return node}};function diffProps(a,b){if(a===b)return null;let diff=null;for(let aKey in a)Object.hasOwn(b,aKey)?a[aKey]!==b[aKey]&&(diff??={},diff[aKey]=b[aKey]):(diff??={},diff[aKey]=void 0);for(let bKey in b)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),hasValue=propsDiff!=null&&"value"in propsDiff,hasChecked=propsDiff!=null&&"checked"in propsDiff;if(propsDiff)if(hasValue||hasChecked){let{value:_v,checked:_c,...rest}=propsDiff;applyProperties(domNode,rest)}else applyProperties(domNode,propsDiff);if(!target.attrs.dangerouslySetInnerHTML){let ns=effectiveNs(target,opts);morphChildren(domNode,source.childs,target.childs,childOpts(target,ns,opts))}return hasValue?applyValueLast(domNode,propsDiff.value):source.tag==="SELECT"&&target.attrs.value!==void 0&&applyValueLast(domNode,target.attrs.value),hasChecked&&setProp(domNode,"checked",propsDiff.checked,!1),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]);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)newKey in oldKeyMap&&!used2[oldKeyMap[newKey]]&&(oldIdx=oldKeyMap[newKey]);else for(;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;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--)!used2[i]&&domNodes[i].parentNode===parentDom&&parentDom.removeChild(domNodes[i])}function render(vnode,container,options,prev){if(vnode==null)return container.replaceChildren(),{vnode:null,dom:null};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];propName==="key"?key=propVal:propName==="namespace"?namespace=namespace??propVal:props[propName]=propVal}if(namespace==null){let lower=tagName.toLowerCase();lower==="svg"?(namespace=SVG_NS,tagName="svg"):lower==="math"&&(namespace=MATH_NS,tagName="math")}let c=tagName.charCodeAt(0),tag=namespace==null&&c>=97&&c<=122&&tagName===tagName.toLowerCase()?tagName.toUpperCase():tagName,normalizedChildren=[];return addChild(normalizedChildren,children),new VNode(tag,props,normalizedChildren,key,namespace)}function resolveDynProducer(comp,name){let own=comp?.provide?.[name],producerComp=own!=null?comp:comp?.scope?.lookupProvider(name)??null,producerProvide=own??producerComp?.provide?.[name];if(producerComp==null||producerProvide==null)return null;let pi=producerProvide.val?.toPathItem?.()??null;return{producerCompId:producerComp.id,producerSteps:pi?[pi]:[]}}var BaseNode=class{render(_stack,_rx){return null}setDataAttr(key,val){console.warn("setDataAttr not implemented for",this,{key,val})}isConstant(){return!1}isWhiteSpace(){return!1}optimize(){}},TextNode=class 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){}},CommentNode=class 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];child.isConstant()?childs[i]=new RenderOnceNode(child):child.optimize()}}function optimizeNode(node){return node.isConstant()?new RenderOnceNode(node):(node.optimize(),node)}var ChildsNode=class extends BaseNode{constructor(childs){super(),this.childs=childs}isConstant(){return this.childs.every(v=>v.isConstant())}optimize(){optimizeChilds(this.childs)}},DomNode=class extends ChildsNode{constructor(tagName,attrs,childs,namespace=null){super(childs),this.tagName=tagName,this.attrs=attrs,this.namespace=namespace}render(stack,rx){let childNodes=new 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()}},FragmentNode=class 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)}},maybeFragment=xs=>xs.length===1?xs[0]:new FragmentNode(xs),VALID_NODE_RE=/^[a-zA-Z][a-zA-Z0-9-]*$/,ANode=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(html2,px){let nodes=px.parseHTML(html2);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);child!==null&&childs.push(child)}let trimmed=condenseChildsWhites(childs);return trimmed.length===0?new CommentNode("Empty View in ANode.parse"):maybeFragment(trimmed)}static fromDOM(node,px){if(node instanceof px.Text)return new TextNode(node.textContent);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);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);if(tag.charCodeAt(1)===58&&(tag.charCodeAt(0)===88||tag.charCodeAt(0)===120)){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);px.onAttributes(nAttrs,wrappers,textChild,!1,tag),textChild&&childs.unshift(new RenderTextNode(null,textChild));let domChilds=tag!=="PRE"?condenseChildsWhites(childs):childs,ns=node.namespaceURI,namespace=ns&&ns!==HTML_NS?ns:null;return wrap(new DomNode(tag,nAttrs,domChilds,namespace),px,wrappers)}return new CommentNode(`Error: InvalidTagName ${tag}`)}finally{px.currentTag=prevTag}}};function parseXOp(attrs,childs,opIdx,px){if(attrs.length<=opIdx)return maybeFragment(childs);let{name,value}=attrs[opIdx];X_OPS[name]?.ignoresChildren&&hasMeaningfulChilds(childs)&&px.onParseIssue("x-op-ignores-children",{op:name});let asAttr=attrs.getNamedItem("as")?.value??null,as=asAttr===null?null:parseViewName(asAttr,px),node;switch(name){case"slot":node=new SlotNode(null,new ConstVal(value),maybeFragment(childs));break;case"text":node=px.addNodeIf(RenderTextNode,parseXOpVal(name,value,px,parseText));break;case"render":node=px.addNodeIf(RenderNode,parseXOpVal(name,value,px,parseComponent),as);break;case"render-it":node=px.addNode(RenderItNode,as);break;case"render-each":node=parseRenderEach(px,value,as,attrs);break;case"show":{let val=parseXOpVal(name,value,px,parseBool);node=px.addNodeIf(ShowNode,val,maybeFragment(childs));break}case"hide":{let val=parseXOpVal(name,value,px,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(value,px);return val===null&&px.onParseIssue("bad-value",{role:"x-op",op:opName,value}),val}function parseViewName(s,px){return parseText(s,px)??new ConstVal(s)}function processXExtras(node,attrs,opName,startIdx,px){let{consumed,wrappable}=X_OPS[opName],wrappers=[];for(let i=startIdx;i<attrs.length;i++){let a=attrs[i],aName=a.name;if(consumed.has(aName))continue;if(wrappable&&aName.charCodeAt(0)===64){let wrapper=X_OPS[aName.slice(1)]?.wrapper;if(wrapper){wrappers.push([wrapper,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);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);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);return node!==null&&data.name==="each"&&(node.iterInfo.enrichWithVal=data.enrichWithVal??null,node.iterInfo.whenVal=data.whenVal??null,node.iterInfo.loopWithVal=data.loopWithVal??null),node}var MacroNode=class 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 new Error(`Recursive macro expansion: ${name}`);let macro2=scope.lookupMacro(name);if(macro2===null)this.node=new CommentNode(`bad macro: ${name}`);else{let vars={...macro2.defaults,...attrs};this.node=macro2.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)}},Macro=class{constructor(defaults,rawView){this.defaults=defaults,this.rawView=rawView}expand(px){return ANode.parse(this.rawView,px)}},RenderViewId=class extends ANode{constructor(nodeId,val,viewVal){super(nodeId,val),this.viewVal=viewVal}evalViewName(stack){return this.viewVal?this.viewVal.eval(stack):null}setDataAttr(_key,_val){}};function dynRenderStep(comp,name,key){let p=resolveDynProducer(comp,name);return p?key===void 0?new DynStep(p.producerCompId,p.producerSteps):new DynEachStep(p.producerCompId,p.producerSteps,key):null}var RenderNode=class extends RenderViewId{render(stack,rx){let newStack=stack.enter(this.val.eval(stack),{},!0);return rx.renderIt(newStack,this,"",this.evalViewName(stack))}toPathStep(ctx){return this.val instanceof DynVal?dynRenderStep(ctx.comp,this.val.name):super.toPathStep(ctx)}},RenderItNode=class extends RenderViewId{render(stack,rx){let newStack=stack.enter(stack.it,{},!0);return rx.renderIt(newStack,this,"",this.evalViewName(stack))}toPathStep(ctx){let next=ctx.next();if(next===null)return null;let nextNode=next.resolveNode();return nextNode instanceof EachNode&&next.hasKey?nextNode.val instanceof DynVal?dynRenderStep(ctx.comp,nextNode.val.name,next.key):new EachRenderItStep(nextNode.val.name,next.key):null}};function parseRenderEach(px,value,as,attrs){let seqVal=parseXOpVal("render-each",value,px,parseSequence);if(seqVal===null)return null;let renderIt=px.addNode(RenderItNode,as),{whenVal,loopWithVal}=parseIterationDirectives(attrs,px),each2=px.addNodeIf(EachNode,seqVal);return each2.iterInfo.whenVal=whenVal,each2.iterInfo.loopWithVal=loopWithVal,each2.fromRenderEach=!0,each2.wrapNode(renderIt),each2}var RenderTextNode=class extends ANode{render(stack,_rx){return this.val.eval(stack)}setDataAttr(_key,_val){}},RenderOnceNode=class 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)}},WrapperNode=class 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},ShowNode=class extends WrapperNode{render(stack,rx){return this.val.eval(stack)?this.node.render(stack,rx):null}},HideNode=class extends WrapperNode{render(stack,rx){return this.val.eval(stack)?null:this.node.render(stack,rx)}},PushViewNameNode=class extends WrapperNode{render(stack,rx){return this.node.render(stack.pushViewName(this.val.eval(stack)),rx)}},SlotNode=class extends WrapperNode{isSlotNode=!0;optimize(){this.node.optimize()}},ScopeNode=class extends WrapperNode{render(stack,rx){let binds=this.val.evalAsHandler(stack)?.call(stack.it)??{},dom=this.node.render(stack.enter(stack.it,binds,!1),rx);return rx.renderScopeMeta(this.nodeId,dom)}toPathStep(_ctx){return new ScopeBindStep(this.val)}wrapNode(node){this.node=node,this.node.setDataAttr("data-nid",this.nodeId)}static register=!0},EachNode=class 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.iterInfo,ctx.key):null}static register=!0},IterInfo=class{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}}enrichBinds(stack,key){let{seq,filter,loopWith,enricher}=this.eval(stack),ctx=makeLoopCtx(stack,filter);return bindsForKey({seq,it:stack.it,loopWith,enricher,ctx},key)}};function xOp(consumed=[],{wrappable=!1,wrapper=null,ignoresChildren=!1}={}){return{consumed:new Set(consumed),wrappable,wrapper,ignoresChildren}}var X_OPS={slot:xOp(),text:xOp([],{wrappable:!0,ignoresChildren:!0}),render:xOp(["as"],{wrappable:!0,ignoresChildren:!0}),"render-it":xOp(["as"],{wrappable:!0,ignoresChildren:!0}),"render-each":xOp(["as","@when","@loop-with"],{wrappable:!0,ignoresChildren:!0}),show:xOp([],{wrapper:ShowNode}),hide:xOp([],{wrapper:HideNode})},WRAPPER_NODES={show:ShowNode,hide:HideNode,each:EachNode,scope:ScopeNode,"push-view":PushViewNameNode},ParseContext=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,frame={macroName,macroVars,macroSlots};return new _ParseContext(document2,Text,Comment,nodes,events2,macroNodes,frame,this)}parseHTML(html2){let t=this.document.createElement("template");return t.innerHTML=html2,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}addNode(Class,extra){let nodeId=this.nodes.length,node=new Class(nodeId,null,extra);return this.nodes.push(node),node}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)child.isSlotNode?slots[child.val.val]=child.node: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)}},_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)},isEmptyText=c=>c instanceof TextNode&&c.val==="",isIgnorableXChild=c=>c instanceof CommentNode||(c.isWhiteSpace?.()??!1),hasMeaningfulChilds=childs=>childs.some(c=>!isIgnorableXChild(c));function trimEdgeWhite(node){return node.isWhiteSpace?.()?(node.condenseWhiteSpace(),!0):!1}function condenseChildsWhites(childs){if(childs.length===0)return childs;let last=childs.length-1,emptied=trimEdgeWhite(childs[0]);last>0&&trimEdgeWhite(childs[last])&&(emptied=!0);for(let i=1;i<last;i++){let cur=childs[i];if(!(cur.isWhiteSpace?.()&&cur.hasNewLine()))continue;let bothBlock=isBlockDomNode(childs[i-1])&&isBlockDomNode(childs[i+1]);cur.condenseWhiteSpace(bothBlock?"":" "),bothBlock&&(emptied=!0)}return emptied?childs.filter(c=>!isEmptyText(c)):childs}var View=class{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){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){if(this.anode===null)throw new Error(`tutuca: view "${this.name}" was rendered before it was compiled — its component is not registered in this app/scope. Source: ${String(this.rawView).slice(0,80).replace(/\s+/g," ")}…`);return this.anode.render(stack,rx)}},NodeEvents=class{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)handler.handlesEventName(eventName)&&(r??=[],r.push(handler));return r}},NodeEvent=class{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}},fwdIfCtxPred=pred=>w=>(that,f,args,ctx)=>pred(ctx)?w(that,f,args,ctx):that,fwdIfEventPred=pred=>fwdIfCtxPred(({e})=>pred(e)),fwdIfKey=keyName=>fwdIfEventPred(keyIs(keyName)),fwdCtrl=fwdIfEventPred(macCtrl),fwdMeta=fwdIfEventPred(e=>e.metaKey),fwdAlt=fwdIfEventPred(e=>e.altKey),MOD_WRAPPERS_FOR_ANY_EVENT={ctrl:fwdCtrl,cmd:fwdCtrl,meta:fwdMeta,alt:fwdAlt},MOD_WRAPPERS_BY_EVENT={keydown:{send:fwdIfKey("Enter"),cancel:fwdIfKey("Escape")}},MOD_EFFECTS={prevent:e=>e.preventDefault?.(),stop:e=>e.stopPropagation?.()},NO_WRAPPERS={},identityModifierWrapper=(f,_ctx)=>f;function compileModifiers(eventName,names){if(names.length===0)return identityModifierWrapper;let wrappers=MOD_WRAPPERS_BY_EVENT[eventName]??NO_WRAPPERS,effects=[];for(let name of names){let effect=MOD_EFFECTS[name];effect!==void 0&&effects.push(effect)}let w=effects.length===0?(that,f,args,_ctx)=>f.apply(that,args):(that,f,args,ctx)=>{for(let effect of effects)effect(ctx.e);return f.apply(that,args)};for(let name of names){let wrapper=wrappers[name]??MOD_WRAPPERS_FOR_ANY_EVENT[name];wrapper!==void 0&&(w=wrapper(w))}return(f,ctx)=>function(...args){return w(this,f,args,ctx)}}var ParseCtxClassSetCollector=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,frame={macroName,macroVars,macroSlots},v=new _ParseCtxClassSetCollector(document2,Text,Comment,nodes,events2,macroNodes,frame,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;thenVal!==void 0?(this._maybeAddVal(thenVal),this._maybeAddVal(elseVal)):this._maybeAddVal(val)}else{let attr=attrs.items.class;attr&&this._addClasses(attr)}}_maybeAddVal(value){!this._maybeAddStrTpl(value)&&typeof value?.val=="string"&&this._addClasses(value.val)}_maybeAddStrTpl(value){if(value?.vals!==void 0){for(let val of value.vals)val instanceof ConstVal&&val.val!==""&&this._addClasses(val.val);return!0}return!1}};function collectAppClassesInSet(app){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 classes}var COMPONENT=Symbol.for("tutuca.component"),Components=class{constructor(){this.byId=new Map}registerComponent(Comp){this.byId.set(Comp[COMPONENT].id,Comp)}getComponentForId(id){return this.byId.get(id)??null}getCompFor(v){let Comp=v?.constructor;return Comp?.[COMPONENT]?Comp:null}getHandlerFor(v,name,key){return this.getCompFor(v)?.[key][name]??null}getIntentChainFor(v,name){return this.getCompFor(v)?.scope.lookupIntentChain(name)??[]}compileStyles(){let styles2=[];for(let Comp of this.byId.values())styles2.push(Comp[COMPONENT].compileStyle());return styles2.join(`
|
|
3
3
|
`)}},ComponentStack=class _ComponentStack{constructor(comps=new Components,parent=null){this.comps=comps,this.parent=parent,this.byName={},this.intentsByName={},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[COMPONENT].scope=this.enter(),this.comps.registerComponent(Comp),this.byName[Comp.name]=Comp}for(let alias in aliases2){let comp=this.byName[aliases2[alias]];console.assert(this.byName[alias]===void 0,"alias overrides component",alias),comp!==void 0?this.byName[alias]=comp: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)}registerIntentHandlers(handlers){for(let name in handlers){let fns=handlers[name];this.intentsByName[name]=Array.isArray(fns)?fns:[fns]}}lookupIntentChain(name){let here=this.intentsByName[name]??[],up=this.parent?.lookupIntentChain(name)??[];return up.length===0?here:here.concat(up)}lookupComponent(name){return this.byName[name]??this.parent?.lookupComponent(name)??null}lookupProvider(name){for(let compName in this.byName){let Comp=this.byName[compName];if(Comp.provide?.[name]!==void 0)return Comp}return this.parent?.lookupProvider(name)??null}lookupMacro(name){return this.macros[name]??this.parent?.lookupMacro(name)??null}},ProvideInfo=class{constructor(val){this.val=val}},LookupInfo=class{constructor(val){this.val=val}},isString=v=>typeof v=="string",isTypeName=s=>{let c=s.charCodeAt(0);return c>=65&&c<=90},_rawSpecKeys="name view style commonStyle globalStyle receive intent alter views provide lookup fields methods statics",KNOWN_SPEC_KEYS=new Set(_rawSpecKeys.split(" ")),_compId=0,Component=class{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.receive=o.receive??{},this.intent=o.intent??{},this.alter=o.alter??{};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._rawProvide=o.provide??{},this._rawLookup=o.lookup??[],this.provide={},this.provideType={},this.lookup={},this.scope=null,this.spec=o,this.extra={};for(let key of Object.keys(o))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);let ctx=this.views.main.ctx;for(let key in this._rawProvide){if(isTypeName(key)){this._rawProvide[key]==="self"&&(this.provideType[key]=this.Class);continue}let val=parseProvide(this._rawProvide[key],ctx);val&&(this.provide[key]=new ProvideInfo(val))}for(let entry of this._rawLookup){let name=isString(entry)?entry:isString(entry?.name)?entry.name:null;if(name===null)continue;let defStr=isString(entry?.default)?entry.default:null;this.lookup[name]=new LookupInfo(defStr===null?null:parseField(defStr,ctx))}for(let key in this.lookup)this.provide[key]!==void 0&&console.warn("name declared in both provide and lookup",this.name,key)}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}}`]:[];globalStyle!==""&&styles2.push(globalStyle);for(let name in views){let{style}=views[name];style!==""&&styles2.push(`[data-cid="${id}"][data-vid="${name}"]{${style}}`)}return styles2.join(`
|
|
4
4
|
`)}};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]]),HtmlTokenizer=class{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(){this.running&&this.finish()}pause(){this.running=!1}resume(){this.running=!0,this.index<this.buffer.length+this.offset&&this.parse()}stateText(c){(c===CharCodes.Lt||this.fastForwardTo(CharCodes.Lt))&&(this.index>this.sectionStart&&this.cbs.ontext(this.sectionStart,this.index),this.state=State.BeforeTagName,this.sectionStart=this.index)}enterTagBody(){this.currentSequence===Sequences.Plaintext?(this.currentSequence=Sequences.Empty,this.state=State.InPlainText):this.isSpecial?(this.state=State.InSpecialTag,this.sequenceIndex=0):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){c===Sequences.Cdata[this.sequenceIndex]?++this.sequenceIndex===Sequences.Cdata.length&&(this.state=State.InCommentLike,this.currentSequence=Sequences.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1):(this.sequenceIndex=0,this.xmlMode?(this.state=State.InDeclaration,this.stateInDeclaration(c)):(this.state=State.InSpecialComment,this.stateInSpecialComment(c)))}fastForwardTo(c){for(;++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){!this.xmlMode&&this.currentSequence===Sequences.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&c===CharCodes.Gt?this.emitComment(this.sequenceIndex):this.currentSequence===Sequences.CommentEnd&&this.sequenceIndex===2&&c===CharCodes.Gt?this.emitComment(2):this.currentSequence===Sequences.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&c!==CharCodes.Gt?this.sequenceIndex=+(c===CharCodes.Dash):c===this.currentSequence[this.sequenceIndex]?++this.sequenceIndex===this.currentSequence.length&&(this.currentSequence===Sequences.CdataEnd?this.cbs.oncdata(this.sectionStart,this.index,2):this.cbs.oncomment(this.sectionStart,this.index,3),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=State.Text):this.sequenceIndex===0?this.fastForwardTo(this.currentSequence[0])&&(this.sequenceIndex=1):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}(c|32)===this.currentSequence[this.sequenceIndex]?this.sequenceIndex+=1:this.sequenceIndex===0?this.fastForwardTo(CharCodes.Lt)&&(this.sequenceIndex=1):this.sequenceIndex=+(c===CharCodes.Lt)}stateBeforeTagName(c){if(c===CharCodes.ExclamationMark)this.state=State.BeforeDeclaration,this.sectionStart=this.index+1;else if(c===CharCodes.Questionmark)this.xmlMode?(this.state=State.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1):(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);special===void 0?this.state=State.InTagName:(this.isSpecial=!0,this.currentSequence=special,this.sequenceIndex=3,this.state=State.SpecialStartSequence)}else c===CharCodes.Slash?this.state=State.BeforeClosingTagName:(this.state=State.Text,this.stateText(c))}stateInTagName(c){isEndOfTagSection(c)&&(this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c))}stateBeforeClosingTagName(c){isWhitespace(c)?this.xmlMode||(this.state=State.InSpecialComment,this.sectionStart=this.index):c===CharCodes.Gt?(this.state=State.Text,this.xmlMode||(this.sectionStart=this.index+1)):(this.state=this.isTagStartChar(c)?State.InClosingTagName:State.InSpecialComment,this.sectionStart=this.index)}stateInClosingTagName(c){isEndOfTagSection(c)&&(this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.AfterClosingTagName,this.stateAfterClosingTagName(c))}stateAfterClosingTagName(c){(c===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))&&(this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeAttributeName(c){c===CharCodes.Gt?(this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1):c===CharCodes.Slash?this.state=State.InSelfClosingTag: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 isWhitespace(c)||(this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c))}stateInAttributeName(c){(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){c===CharCodes.Eq?this.state=State.BeforeAttributeValue:c===CharCodes.Slash||c===CharCodes.Gt?(this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c)):isWhitespace(c)||(this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.state=State.InAttributeName,this.sectionStart=this.index)}stateBeforeAttributeValue(c){c===CharCodes.DoubleQuote?(this.state=State.InAttributeValueDq,this.sectionStart=this.index+1):c===CharCodes.SingleQuote?(this.state=State.InAttributeValueSq,this.sectionStart=this.index+1):isWhitespace(c)||(this.sectionStart=this.index,this.state=State.InAttributeValueNq,this.stateInAttributeValueNoQuotes(c))}handleInAttributeValue(c,quote){(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){(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){c===CharCodes.OpeningSquareBracket?(this.state=State.CDATASequence,this.sequenceIndex=0):this.xmlMode?this.state=c===CharCodes.Dash?State.BeforeComment:State.InDeclaration:(c|32)===Sequences.Doctype[0]?(this.state=State.DeclarationSequence,this.currentSequence=Sequences.Doctype,this.sequenceIndex=1):c===CharCodes.Gt?(this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1):c===CharCodes.Dash?this.state=State.BeforeComment:this.state=State.InSpecialComment}stateDeclarationSequence(c){this.sequenceIndex===this.currentSequence.length?(this.state=State.InDeclaration,this.stateInDeclaration(c)):(c|32)===this.currentSequence[this.sequenceIndex]?this.sequenceIndex+=1:c===CharCodes.Gt?(this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1):this.state=State.InSpecialComment}stateInDeclaration(c){(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){c===CharCodes.Questionmark?this.sequenceIndex=1: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):this.sequenceIndex=Number(this.fastForwardTo(CharCodes.Questionmark))}stateBeforeComment(c){c===CharCodes.Dash?(this.state=State.InCommentLike,this.currentSequence=Sequences.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1):this.xmlMode?this.state=State.InDeclaration:c===CharCodes.Gt?(this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1):this.state=State.InSpecialComment}stateInSpecialComment(c){(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(){this.running&&this.sectionStart!==this.index&&(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):(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(){for(;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)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:return this.sequenceIndex!==Sequences.Doctype.length&&this.cbs.oncomment(this.sectionStart,endIndex,0),!0;case State.InDeclaration:return!0;default:return!1}}handleTrailingData(){let endIndex=this.buffer.length+this.offset;if(!(this.handleTrailingCommentLikeData(endIndex)||this.handleTrailingMarkupDeclaration(endIndex))&&!(this.sectionStart>=endIndex))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"]),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"]),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(html2,onFinding,opts={}){let TokenizerClass=opts.TokenizerClass??HtmlTokenizer,ctx=new LinterCtx(html2,onFinding,opts),tokenizer=new TokenizerClass({xmlMode:!1,decodeEntities:!1,recognizeSelfClosing:!0},ctx);return ctx.tokenizer=tokenizer,tokenizer.write(html2),tokenizer.end(),ctx.findingCount}var LinterCtx=class{constructor(html2,onFinding,opts){this.html=html2,this.onFinding=onFinding,this.findingCount=0,this.lineStarts=computeLineStarts(html2);let ctxName=opts.fragmentContext??"template",ctxInfo=FRAGMENT_CONTEXT_MODES[ctxName]??FRAGMENT_CONTEXT_MODES.template;this.openElements=[],ctxName==="tr"?(this.openElements.push({name:"table",ns:NS.html,start:-1}),this.openElements.push({name:"tbody",ns:NS.html,start:-1})):ctxName==="tbody"||ctxName==="thead"||ctxName==="tfoot"?this.openElements.push({name:"table",ns:NS.html,start:-1}):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})):ctxName==="caption"?this.openElements.push({name:"table",ns:NS.html,start:-1}):ctxName==="colgroup"?this.openElements.push({name:"table",ns:NS.html,start:-1}):ctxName==="svg"?this.openElements.push({name:"svg",ns:NS.svg,start:-1}):ctxName==="math"?this.openElements.push({name:"math",ns:NS.math,start:-1}):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){this.currentAttr&&(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);dup?this.report(HTML_DUPLICATE_ATTRIBUTE,LEVEL_WARN,a.nameStart,{name:a.name,firstAt:dup.nameStart},{kind:"remove",what:`the duplicate '${a.name}' attribute`}):this.currentAttrs.push(a),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;for(;i<this.html.length;){let c=this.html.charCodeAt(i);if(c===62)break;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}}firstNonWs<0?this.report(HTML_SELF_CLOSING_END_TAG,LEVEL_WARN,start,{tag:name},{kind:"rewrite",from:`</${name}/>`,to:`</${name}>`}):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();top&&top.ns!==NS.html&&!this.isIntegrationPoint(top)||this.handleText(start,end)}oncomment(start,_end,endOffset){endOffset===0&&this.report(HTML_BOGUS_COMMENT,LEVEL_WARN,start,{mode:this.insertionMode})}oncdata(start,_end,_endOffset){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){return frame.ns===NS.math?MATHML_TEXT_INTEGRATION_POINT_NAMES.has(frame.name)||frame.name==="annotation-xml":frame.ns===NS.svg?SVG_HTML_INTEGRATION_POINT_NAMES.has(frame.name):!1}isIntegrationPoint(frame){return frame.ns===NS.math?!!(MATHML_TEXT_INTEGRATION_POINT_NAMES.has(frame.name)||frame.name==="annotation-xml"&&frame.htmlIntegration):frame.ns===NS.svg?SVG_HTML_INTEGRATION_POINT_NAMES.has(frame.name):!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){for(;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"]);for(;this.openElements.length;){let top=this.currentNode();if(top.ns!==NS.html||!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();ns===NS.html?raw!==name&&this.report(HTML_TAG_NAME_HAS_UPPERCASE,LEVEL_ERROR,start,{raw,lowercased:name},{kind:"rewrite",from:`<${raw}>`,to:`<${name}>`}):ns===NS.svg&&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);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);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))for(this.report(HTML_TAG_NOT_ALLOWED_IN_PARENT,LEVEL_WARN,start,{tag:raw,parent:this.currentNode()?.name??"(root)",mode:this.insertionMode,action:"foreign-breakout"});this.openElements.length&&this.currentNode()?.ns!==NS.html;)this.openElements.pop();this.dispatchStartTag(name,raw,selfClosing,start,endIndex)}shouldBreakoutFromForeign(name){return FOREIGN_BREAKOUT_TAGS.has(name)?!0:name==="font"?this.hasAttr("color")||this.hasAttr("face")||this.hasAttr("size"):!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();(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"){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"){this.hasInButtonScope("p")&&this.implicitlyClose("p",start,raw);let top=this.currentNode();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"){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}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"){for(this.generateImpliedEndTags("li");this.openElements.length&&this.openElements.pop().name!=="li";);break}if(SPECIAL_ELEMENTS.has(f.name)&&f.name!=="address"&&f.name!=="div"&&f.name!=="p")break}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"){for(this.generateImpliedEndTags(f.name);this.openElements.length&&this.openElements.pop().name!==f.name;);break}if(SPECIAL_ELEMENTS.has(f.name)&&f.name!=="address"&&f.name!=="div"&&f.name!=="p")break}this.hasInButtonScope("p")&&this.implicitlyClose("p",start,raw),this.push(raw,NS.html,start);return}if(name==="plaintext"){this.hasInButtonScope("p")&&this.implicitlyClose("p",start,raw),this.push(raw,NS.html,start);return}if(name==="button"){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"){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"){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"){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"){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"){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}selfClosing||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);idx>=0&&this.openElements.splice(idx,1);return}}}implicitlyClose(name,_start,_newTagRaw){for(;this.openElements.length&&this.openElements.pop().name!==name;);}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(){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")return 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")?(this.popUntilName("table"),this.resetInsertionModeAppropriately(),this.dispatchStartTag(name,raw,selfClosing,start,endIndex)):void 0;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(){for(;this.openElements.length;){let top=this.currentNode();if(!top||top.name==="table"||top.name==="template")break;this.openElements.pop()}}startInCaption(name,raw,selfClosing,start,endIndex){return name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="td"||name==="tfoot"||name==="th"||name==="thead"||name==="tr"?this.hasInTableScope("caption")?(this.generateImpliedEndTags(),this.popUntilName("caption"),this.clearActiveFormattingToMarker(),this.insertionMode=MODES.inTable,this.dispatchStartTag(name,raw,selfClosing,start,endIndex)):void 0:this.startInBody(name,raw,selfClosing,start,endIndex)}clearActiveFormattingToMarker(){for(;this.activeFormatting.length;)if(this.activeFormatting.pop()===null)return}startInColumnGroup(name,raw,selfClosing,start,endIndex){if(name!=="col"){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}return TABLE_BODY_CELL_TAGS.has(name)?(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)):name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="tfoot"||name==="thead"?this.hasInTableScope("tbody")||this.hasInTableScope("thead")||this.hasInTableScope("tfoot")?(this.clearStackBackToTableBody(),this.openElements.pop(),this.insertionMode=MODES.inTable,this.dispatchStartTag(name,raw,selfClosing,start,endIndex)):void 0:this.startInTable(name,raw,selfClosing,start,endIndex)}clearStackBackToTableBody(){for(;this.openElements.length;){let top=this.currentNode();if(!top||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}return name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="tfoot"||name==="thead"||name==="tr"?this.hasInTableScope("tr")?(this.clearStackBackToTableRow(),this.openElements.pop(),this.insertionMode=MODES.inTableBody,this.dispatchStartTag(name,raw,selfClosing,start,endIndex)):void 0:this.startInTable(name,raw,selfClosing,start,endIndex)}clearStackBackToTableRow(){for(;this.openElements.length;){let top=this.currentNode();if(!top||top.name==="tr"||top.name==="template"||top.name==="table")break;this.openElements.pop()}}startInCell(name,raw,selfClosing,start,endIndex){return name==="caption"||name==="col"||name==="colgroup"||name==="tbody"||name==="td"||name==="tfoot"||name==="th"||name==="thead"||name==="tr"?this.hasInTableScope("td")||this.hasInTableScope("th")?(this.closeCell(),this.dispatchStartTag(name,raw,selfClosing,start,endIndex)):void 0:this.startInBody(name,raw,selfClosing,start,endIndex)}closeCell(){for(this.generateImpliedEndTags();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"){this.currentNode()?.name==="option"&&this.openElements.pop(),this.push(raw,NS.html,start);return}if(name==="optgroup"){this.currentNode()?.name==="option"&&this.openElements.pop(),this.currentNode()?.name==="optgroup"&&this.openElements.pop(),this.push(raw,NS.html,start);return}if(name!=="hr"){if(SELECT_BREAKOUT_TAGS.has(name))return 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()),name==="select"?void 0: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){return name==="caption"||name==="table"||name==="tbody"||name==="tfoot"||name==="thead"||name==="tr"||name==="td"||name==="th"?(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)):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;for(;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}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}}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);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);/\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);return/\S/.test(slice)&&this.currentNode()?.name==="colgroup"?(this.openElements.pop(),this.insertionMode=MODES.inTable,this.handleText(start,end)):void 0}this.insertionMode===MODES.inSelect||(this.insertionMode,MODES.inSelectInTable)}};function computeLineStarts(html2){let arr=[0];for(let i=0;i<html2.length;i++)html2.charCodeAt(i)===10&&arr.push(i+1);return arr}function offsetToLineCol(lineStarts,offset){let lo=0,hi=lineStarts.length-1;for(;lo<hi;){let mid=lo+hi+1>>>1;lineStarts[mid]<=offset?lo=mid: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=new Array(lb+1),prev1=new Array(lb+1),curr=new 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);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);d<bestDist&&(best=cand,bestDist=d)}return bestDist<=maxDistance?best:null}var KNOWN_COMPONENT_SPEC_KEYS=new Set("name view style commonStyle globalStyle receive intent alter views provide lookup fields methods statics".split(" ")),EMPTY_SET=new Set,FRAMEWORK_WELL_KNOWN_EXTRAS=new Set(["intentOverridesField"]),KNOWN_DIRECTIVE_NAMES=new Set(["dangerouslysetinnerhtml","slot","push-view","text","show","hide","each","enrich-with","when","loop-with","then","else"]),isTypeName2=s=>{let c=s.charCodeAt(0);return c>=65&&c<=90},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",PROVIDE_NOT_ADDRESSABLE="PROVIDE_NOT_ADDRESSABLE",PROVIDE_TYPE_BAD_SHAPE="PROVIDE_TYPE_BAD_SHAPE",PROVIDE_NAME_COLLISION="PROVIDE_NAME_COLLISION",LOOKUP_BAD_SHAPE="LOOKUP_BAD_SHAPE",LOOKUP_NO_PROVIDER="LOOKUP_NO_PROVIDER",RENDER_IT_OUTSIDE_OF_LOOP="RENDER_IT_OUTSIDE_OF_LOOP",UNKNOWN_EVENT_MODIFIER="UNKNOWN_EVENT_MODIFIER",RECEIVE_HANDLER_NOT_IMPLEMENTED="RECEIVE_HANDLER_NOT_IMPLEMENTED",EVENT_HANDLER_METHOD_NOT_ALLOWED="EVENT_HANDLER_METHOD_NOT_ALLOWED",HANDLER_NAME_COLLISION="HANDLER_NAME_COLLISION",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_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",X_OP_IGNORES_CHILDREN="X_OP_IGNORES_CHILDREN",MAYBE_DROP_AT_PREFIX="MAYBE_DROP_AT_PREFIX",MAYBE_ADD_AT_PREFIX="MAYBE_ADD_AT_PREFIX",BAD_VALUE="BAD_VALUE",UNSUPPORTED_EXPR_SYNTAX="UNSUPPORTED_EXPR_SYNTAX",BINDING_MEMBER_TOO_DEEP="BINDING_MEMBER_TOO_DEEP",SUGGEST_BINDING_MEMBER="SUGGEST_BINDING_MEMBER",REDUNDANT_TEMPLATE_STRING="REDUNDANT_TEMPLATE_STRING",PLACEHOLDERLESS_TEMPLATE_STRING="PLACEHOLDERLESS_TEMPLATE_STRING",CONSTANT_CONDITION="CONSTANT_CONDITION",UNKNOWN_COMPONENT_SPEC_KEY="UNKNOWN_COMPONENT_SPEC_KEY",COMP_FIELD_BAD_SHAPE="COMP_FIELD_BAD_SHAPE",ASYNC_HANDLER="ASYNC_HANDLER",TOP_LEVEL_AT_RULE_IN_SCOPED_STYLE="TOP_LEVEL_AT_RULE_IN_SCOPED_STYLE",GLOBAL_SELECTOR_IN_SCOPED_STYLE="GLOBAL_SELECTOR_IN_SCOPED_STYLE",FIELD_METHOD_NAME_COLLISION="FIELD_METHOD_NAME_COLLISION",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"]),HOST_DIRECTIVE_ONLY_NAMES=new Set(["when","enrich-with","loop-with","show","hide"]),LEVEL_WARN2="warn",LEVEL_ERROR2="error",LEVEL_HINT="hint",PARSE_ISSUES={"unknown-directive":{id:UNKNOWN_DIRECTIVE,candidates:KNOWN_DIRECTIVE_NAMES},"unknown-x-op":{id:UNKNOWN_X_OP,candidates:X_KNOWN_OP_NAMES,atPrefix:X_KNOWN_OP_NAMES},"unknown-x-attr":{id:UNKNOWN_X_ATTR,candidates:X_KNOWN_ATTR_NAMES,atPrefix:X_KNOWN_ATTR_NAMES},"bad-value":{id:BAD_VALUE},"event-method-handler":{id:EVENT_HANDLER_METHOD_NOT_ALLOWED}};function protoHasMethod(proto,name){return protoMethodValue(proto,name)!==null}function protoMethodValue(proto,name){let cursor=proto;for(;cursor&&cursor!==Object.prototype;){let desc=Object.getOwnPropertyDescriptor(cursor,name);if(desc!==void 0)return typeof desc.value=="function"?desc.value:null;cursor=Object.getPrototypeOf(cursor)}return null}function collectProtoMethodNames(proto){let out=[],cursor=proto;for(;cursor&&cursor!==Object.prototype;){for(let key of Object.getOwnPropertyNames(cursor))key!=="constructor"&&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)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();return s===""?null:/\s\?\s.+\s:\s/.test(s)?"ternary":/===|!==|==|!=|<=|>=|\s<\s|\s>\s/.test(s)?"comparison":/&&|\|\|/.test(s)?"logical":/^[.$][A-Za-z_]\w*\s+\S/.test(s)?"call-with-args":/^\.[A-Za-z_]\w*\??(\.[A-Za-z_]\w*\??)+$/.test(s)?"field-path":null}var BINDING_MEMBER_TOO_DEEP_RE=/^@[a-zA-Z]\w*\??(\.[a-zA-Z]\w*\??){2,}$/,UNSUPPORTED_EXPR_GUIDANCE={ternary:"Ternary expressions aren't supported in dynamic attributes. Define a method or computed value 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.","field-path":"Fields can't be read through a dotted path. Define a method that returns the value, render a child component for the nested data, or — inside a loop — read one member off a binding ('@value.member')."};function checkComponent(Comp,lx=new LintContext,{wellKnownExtras=EMPTY_SET}={}){return lx.push({componentName:Comp.name},()=>{checkUnknownSpecKeys(lx,Comp,wellKnownExtras),checkFieldDeclarations(lx,Comp),checkFieldMethodNameCollisions(lx,Comp),checkProvidesAreAddressable(lx,Comp),checkProvidedTypes(lx,Comp),checkProvideNameCollisions(lx,Comp),checkLookupShapes(lx,Comp),checkLookupTypesResolve(lx,Comp),checkLookupsHaveProviders(lx,Comp),checkHandlersNotAsync(lx,Comp),checkHandlerNameCollisions(lx,Comp),checkScopedStyleTopLevel(lx,Comp);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),checkUnreferencedDynamics(lx,Comp,referencedDynamics),lx})}function checkView(lx,view,Comp,referencedAlters,referencedDynamics){checkParseIssues(lx,view),checkRenderItInLoop(lx,view),checkEnrichProjection(lx,view,Comp),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){typeof view.rawView!="string"||!view.rawView||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)for(let{kind,info}of issues){if(kind==="x-op-ignores-children"){lx.warn(X_OP_IGNORES_CHILDREN,info,{kind:"remove",what:"the ignored children"});continue}if(kind==="event-method-handler"){lx.error(EVENT_HANDLER_METHOD_NOT_ALLOWED,info,{kind:"rephrase",from:info.value,text:`Move '${info.name}' to receive and reference it as '${info.name}'.`});continue}let rule=PARSE_ISSUES[kind];if(!rule)continue;let id=rule.id;if(kind==="bad-value"){if(typeof info.value=="string"&&BINDING_MEMBER_TOO_DEEP_RE.test(info.value.trim())){lx.error(BINDING_MEMBER_TOO_DEEP,info,{kind:"rephrase",from:info.value,text:"Read one level off the binding and compute the rest in a method or an '@enrich-with' handler."});continue}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=rule.atPrefix,isAtPrefixedTypo=atPrefixKnown&&info.name?.startsWith("@")&&atPrefixKnown.has(info.name.slice(1)),suggestion=null;isAtPrefixedTypo?suggestion={kind:"drop-prefix",from:info.name,to:info.name.slice(1)}:rule.candidates&&(suggestion=replaceNameSuggestion(info.name,rule.candidates)),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 macro2=scope.lookupMacro(macroNode.name);if(macro2===null)continue;let{defaults}=macro2;for(let argName in macroNode.attrs)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}hasRenderIt&&walkForRenderIt(lx,view.anode,0)}function pureProjectionBinds(fn){let src=Function.prototype.toString.call(fn),head=src.match(/^[^(]*\(([^)]*)\)\s*(?:=>)?\s*/);if(!head)return null;let params=head[1].split(",").map(p=>p.trim()),[bindsName,,valueName]=params;if(!/^\w+$/.test(bindsName??"")||!/^\w+$/.test(valueName??""))return null;let body=src.slice(head[0].length).trim();if(body.startsWith("{")){if(!body.endsWith("}"))return null;body=body.slice(1,-1)}let statements=body.split(/[;\n]/).map(s=>s.trim()).filter(s=>s!==""&&!s.startsWith("//"));if(statements.length===0)return null;let projectionRe=new RegExp(`^${bindsName}\\.(\\w+)\\s*=\\s*${valueName}(?:\\.(\\w+)|\\.get\\((['"])(\\w+)\\3\\))$`),members=[];for(let statement of statements){let m=statement.match(projectionRe);if(!m)return null;members.push({bind:m[1],member:m[2]??m[4]})}return members}function checkEnrichProjection(lx,view,Comp){for(let node of view.ctx.nodes){if(node.constructor.name!=="EachNode")continue;let enrich=node.iterInfo?.enrichWithVal;if(!enrich?.name)continue;let fn=enrich.constructor.name==="MethodVal"?protoMethodValue(Comp.prototype??Object.getPrototypeOf(Comp),enrich.name):Comp.alter?.[enrich.name];if(typeof fn!="function")continue;let members=pureProjectionBinds(fn);if(members===null)continue;let rewrites=members.map(({bind,member})=>`'@${bind}' -> '@value.${member}'`);lx.hint(SUGGEST_BINDING_MEMBER,{name:enrich.name,members},{kind:"rephrase",text:`Replace ${rewrites.join(", ")} in the view, then remove the '@enrich-with' and the '${enrich.name}' alter handler.`})}}function walkForRenderIt(lx,node,loopDepth){if(node!=null)switch(node.constructor.name){case"RenderItNode":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_WRAPPERS2={},ANY_EVENT_MODIFIERS=[...Object.keys(MOD_WRAPPERS_FOR_ANY_EVENT),...Object.keys(MOD_EFFECTS)];function checkEventModifiers(lx,view){for(let event of view.ctx.events)for(let handler of event.handlers){let{name,modifiers}=handler,known=[...Object.keys(MOD_WRAPPERS_BY_EVENT[name]??NO_WRAPPERS2),...ANY_EVENT_MODIFIERS];for(let modifier of modifiers)if(!known.includes(modifier)){let close=closestName(modifier,known);lx.error(UNKNOWN_EVENT_MODIFIER,{name,modifier,handler,event,originAttr:`@on.${name}+${modifiers.join("+")}`},close?{kind:"replace-name",from:`+${modifier}`,to:`+${close}`}:null)}}}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,provide,lookup:lookup2,fields}=Comp,proto=Comp.prototype??Object.getPrototypeOf(Comp),dynamicMap={...provide,...lookup2};return{fields,proto,scope,alter,referencedAlters,dynamicMap,referencedDynamics}}function checkEventHandlersHaveImpls(lx,Comp,referencedInputs){let{receive:input,views}=Comp,proto=Comp.prototype??Object.getPrototypeOf(Comp);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,eventName=handler.name,originAttr=`@on.${eventName}`;if(handlerVal?.constructor.name==="HandlerNameVal"){referencedInputs?.add(handlerVal.name);let{name}=handlerVal;if(input[name]===void 0){let suggestion=protoHasMethod(proto,name)?{kind:"rephrase",from:name,text:`Move '${name}' from methods to receive; event handlers are receive handlers.`}:replaceNameSuggestion(name,Object.keys(input));lx.error(RECEIVE_HANDLER_NOT_IMPLEMENTED,{name,handler,event,eventName,originAttr},suggestion)}}}})}var fixTo=(from,to)=>({kind:"rewrite",from,to});function reportUnknownName(lx,code,name,candidates,info){lx.error(code,{...info,name},replaceNameSuggestion(name,candidates))}var BOOL_CONDITION_ORIGINS=new Set(["@show","@hide","<x show>","<x hide>"]),isBoolConditionCtx=errCtx=>errCtx!=null&&(BOOL_CONDITION_ORIGINS.has(errCtx.originAttr)||errCtx.branch==="@if"),ATTR_VAL_CHECKERS={ConstVal({lx,val,errCtx,isRoot}){isRoot&&isBoolConditionCtx(errCtx)&&typeof val.val!="boolean"&&lx.warn(CONSTANT_CONDITION,{...errCtx,literal:String(val)})},FieldVal({lx,val,env,errCtx}){let{fields,proto}=env,{name}=val;fields[name]===void 0&&(protoHasMethod(proto,name)?lx.error(FIELD_VAL_IS_METHOD,{...errCtx,val,name},fixTo(`.${name}`,`$${name}`)):reportUnknownName(lx,FIELD_VAL_NOT_DEFINED,name,Object.keys(fields),{...errCtx,val}))},MethodVal({lx,val,env,errCtx}){let{fields,proto}=env,{name}=val;protoHasMethod(proto,name)||(fields[name]!==void 0?lx.error(METHOD_VAL_IS_FIELD,{...errCtx,val,name},fixTo(`$${name}`,`.${name}`)):reportUnknownName(lx,METHOD_VAL_NOT_DEFINED,name,collectProtoMethodNames(proto),{...errCtx,val}))},SeqAccessVal({val,recurse}){recurse(val.seqVal),recurse(val.keyVal)},StrTplVal({lx,val,errCtx,recurse,isRoot}){let vs=val.vals,literal=val.toLiteralSource();if(literal!==null){isRoot&&isBoolConditionCtx(errCtx)?lx.warn(CONSTANT_CONDITION,{...errCtx,literal}):lx.hint(PLACEHOLDERLESS_TEMPLATE_STRING,{...errCtx,literal},fixTo(`$${literal}`,literal));return}else if(vs.length===1){let simpler=String(vs[0]);lx.warn(REDUNDANT_TEMPLATE_STRING,{...errCtx,simpler},fixTo(`$'{${simpler}}'`,simpler))}for(let subVal of vs)recurse(subVal)},HandlerNameVal({lx,val,env,errCtx}){env.referencedAlters?.add(val.name),env.alter[val.name]===void 0&&reportUnknownName(lx,ALT_HANDLER_NOT_DEFINED,val.name,Object.keys(env.alter),errCtx)},PredicateVal({lx,val,errCtx,recurse}){let isConstArg=a=>a.constructor.name==="ConstVal"||a.constructor.name==="StrTplVal"&&a.toLiteralSource()!==null;isBoolConditionCtx(errCtx)&&val.args.every(isConstArg)&&lx.warn(CONSTANT_CONDITION,{...errCtx,literal:String(val)});for(let arg of val.args)recurse(arg)},DynVal({lx,val,env,errCtx}){env.referencedDynamics?.add(val.name),env.dynamicMap[val.name]===void 0&&reportUnknownName(lx,DYN_VAL_NOT_DEFINED,val.name,Object.keys(env.dynamicMap),errCtx)}};function checkConsistentAttrVal(lx,val,env,skipNameVal=!1,errCtx=null,isRoot=!0){let check2=ATTR_VAL_CHECKERS[val?.constructor.name];if(check2===void 0)return;check2({lx,val,env,errCtx,skipNameVal,recurse:sub=>checkConsistentAttrVal(lx,sub,env,skipNameVal,errCtx,!1),isRoot})}var NODE_KIND_TO_CTX={RenderTextNode:{originAttr:"<x text>"},RenderNode:{originAttr:"<x render>"},RenderItNode:{originAttr:"<x render-it>"},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;return cn==="ConstAttr"?"literal":cn==="IfAttr"?`@if.${attr.name}`:cn==="RawHtmlAttr"?"@dangerouslysetinnerhtml":`:${attr.name}`}function attrOriginAttr(attr){let cn=attr.constructor.name;return cn==="IfAttr"?`@if.${attr.name}`:cn==="RawHtmlAttr"?"@dangerouslysetinnerhtml":`:${attr.name}`}function checkHostBareDirectives(lx,attrs,tag,isMacroCall){if(isMacroCall||!attrs)return;let kind=attrs.constructor.name,names;if(kind==="ConstAttrs")names=Object.keys(attrs.items);else if(kind==="DynAttrs")names=attrs.items.map(a=>a?.name);else return;for(let name of names)HOST_DIRECTIVE_ONLY_NAMES.has(name)&&lx.hint(MAYBE_ADD_AT_PREFIX,{name,tag,suggestion:`@${name}`},{kind:"add-prefix",from:name,to:`@${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(checkHostBareDirectives(lx,attrs,tag,isMacroCall),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);sources?sources.push(label):sourcesByName.set(name,[label])}if(attr?.constructor.name==="IfAttr"){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 attr?.val!==void 0&&checkConsistentAttrVal(lx,attr.val,env,isMacroCall,{tag,originAttr:attrOriginAttr(attr)})}for(let[name,sources]of sourcesByName)sources.length>1&&lx.error(DUPLICATE_ATTR_DEFINITION,{name,sources,tag})}if(wrapperAttrs!==null)for(let w of wrapperAttrs)if(w.name==="each")w.whenVal&&checkConsistentAttrVal(lx,w.whenVal,env,!1,{tag,originAttr:"@when"}),w.enrichWithVal&&checkConsistentAttrVal(lx,w.enrichWithVal,env,!1,{tag,originAttr:"@enrich-with"}),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})}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),nodeKind==="EachNode"&&node.fromRenderEach){let iter=node.iterInfo;iter.whenVal&&checkConsistentAttrVal(lx,iter.whenVal,env,!1,{originAttr:"<x render-each @when>"}),iter.loopWithVal&&checkConsistentAttrVal(lx,iter.loopWithVal,env,!1,{originAttr:"<x render-each @loop-with>"})}}})}function checkHandlerNameCollisions(lx,Comp){let receive=Comp.receive??{},intent=Comp.intent??{};for(let name in intent)receive[name]!==void 0&&lx.error(HANDLER_NAME_COLLISION,{name,problem:`"${name}" is declared in both \`receive\` and \`intent\``,fix:"one is addressed and one is routed; give them different names so a reader can tell which a call site meant"});for(let name in receive)for(let suffix of["Ok","Error","Unhandled"])receive[name+suffix]!==void 0&&intent[name]===void 0&&lx.warn(HANDLER_NAME_COLLISION,{name,problem:`\`receive\` declares both "${name}" and its answer name "${name+suffix}"`,fix:`an intent named "${name}" would dispatch its answer to "${name+suffix}" - rename one unless that is what you meant`})}function checkUnknownSpecKeys(lx,Comp,wellKnownExtras){let extra=Comp.extra;if(!extra)return;let candidates=null;for(let key of Object.keys(extra))FRAMEWORK_WELL_KNOWN_EXTRAS.has(key)||wellKnownExtras.has(key)||(candidates??=[...KNOWN_COMPONENT_SPEC_KEYS,...FRAMEWORK_WELL_KNOWN_EXTRAS,...wellKnownExtras],lx.warn(UNKNOWN_COMPONENT_SPEC_KEY,{key},replaceNameSuggestion(key,candidates)))}function checkFieldDeclarations(lx,Comp){let fields=Comp[COMPONENT]?.fields;if(fields)for(let fieldName in fields){let field=fields[fieldName];Object.hasOwn(field,"args")&&(typeof field.type!="string"&&lx.error(COMP_FIELD_BAD_SHAPE,{fieldName,kind:"component-not-string",got:typeof field.type,gotName:field.type?.name??null}),(field.args==null||field.args.constructor!==Object)&&lx.error(COMP_FIELD_BAD_SHAPE,{fieldName,kind:"args-not-object",got:field.args===null?"null":typeof field.args}))}}function checkFieldMethodNameCollisions(lx,Comp){let meta=Comp[COMPONENT];if(meta)for(let name in meta.fields)Object.hasOwn(meta.methods,name)&&lx.error(FIELD_METHOD_NAME_COLLISION,{name})}function checkUnreferencedAlterHandlers(lx,Comp,referencedAlters){for(let name in Comp.alter)referencedAlters.has(name)||lx.hint(ALT_HANDLER_NOT_REFERENCED,{name})}var HANDLER_CHANNELS=["receive","intent","alter"],ASYNC_HANDLER_HELP='Move the async work into a scope-registered intent handler and trigger it with ctx.intent("name", args, { route: ["lex"] }), then read the outcome in the synchronous `receive` arms named after it: <name>Ok, <name>Error and <name>Unhandled. To coordinate other components, keep the handler synchronous and use ctx.send to address one, or ctx.intent to let a route find one.';function checkHandlersNotAsync(lx,Comp){for(let channel of HANDLER_CHANNELS){let block=Comp[channel];if(block)for(let name in block){let fn=block[name];typeof fn=="function"&&fn.constructor?.name==="AsyncFunction"&&lx.error(ASYNC_HANDLER,{name,channel},{kind:"rephrase",from:name,text:ASYNC_HANDLER_HELP})}}}var NON_NESTABLE_AT_RULE=/(?:^|[\s;{}])@(?:-[a-z]+-)?(charset|import|namespace|font-face|keyframes|page|property|counter-style|font-feature-values|font-palette-values|view-transition)\b/gi,GLOBAL_LEADING_SELECTOR=/(?:^|[{}])\s*(html|body|:root)\b[^{};]*\{/gi,IGNORE_DIRECTIVE=/\/\*\s*tutuca-lint-ignore\s*\*\//g,blankRun=m=>m.replace(/[^\n]/g," ");function blankCssNoise(css2){return css2.replace(/\/\*[\s\S]*?\*\//g,blankRun).replace(/"(?:[^"\\\n]|\\.)*"/g,blankRun).replace(/'(?:[^'\\\n]|\\.)*'/g,blankRun)}function offsetToLineCol2(str,index){let line=1,lineStart=0;for(let i=0;i<index;i++)str[i]===`
|
|
5
|
-
`&&(line++,lineStart=i+1);return{line,column:index-lineStart+1}}function suppressedLines(css2){let lines=new Set;IGNORE_DIRECTIVE.lastIndex=0;for(let m=IGNORE_DIRECTIVE.exec(css2);m!==null;m=IGNORE_DIRECTIVE.exec(css2))lines.add(offsetToLineCol2(css2,m.index).line);return lines}var STYLE_TO_GLOBAL_HELP="Move it to the component's 'globalStyle' key, which is injected without the component-scoping wrapper. To suppress a false positive, put a /* tutuca-lint-ignore */ comment on the same line.";function scanScopedCss(lx,css2,key){if(!css2)return;let ignore=suppressedLines(css2),clean=blankCssNoise(css2),report=(id,info)=>{ignore.has(info.location.line)||lx.error(id,{key,...info},{kind:"rephrase",text:STYLE_TO_GLOBAL_HELP})};NON_NESTABLE_AT_RULE.lastIndex=0;for(let m=NON_NESTABLE_AT_RULE.exec(clean);m!==null;m=NON_NESTABLE_AT_RULE.exec(clean)){let at=m.index+m[0].indexOf("@");report(TOP_LEVEL_AT_RULE_IN_SCOPED_STYLE,{atRule:m[1].toLowerCase(),location:offsetToLineCol2(clean,at)})}GLOBAL_LEADING_SELECTOR.lastIndex=0;for(let m=GLOBAL_LEADING_SELECTOR.exec(clean);m!==null;m=GLOBAL_LEADING_SELECTOR.exec(clean)){let at=m.index+m[0].indexOf(m[1]);report(GLOBAL_SELECTOR_IN_SCOPED_STYLE,{selector:m[1].toLowerCase(),location:offsetToLineCol2(clean,at)})}}function checkScopedStyleTopLevel(lx,Comp){scanScopedCss(lx,Comp.commonStyle,"commonStyle");for(let name in Comp.views){let{style}=Comp.views[name];style&&lx.push({viewName:name},()=>scanScopedCss(lx,style,"style"))}}function checkProvidesAreAddressable(lx,Comp){for(let name in Comp._rawProvide)isTypeName2(name)||Comp.provide[name]===void 0&&lx.error(PROVIDE_NOT_ADDRESSABLE,{name,value:Comp._rawProvide[name]})}function checkProvidedTypes(lx,Comp){for(let name in Comp._rawProvide){if(!isTypeName2(name))continue;let raw=Comp._rawProvide[name];raw!=="self"&&lx.error(PROVIDE_TYPE_BAD_SHAPE,{name,value:raw})}}function checkProvideNameCollisions(lx,Comp){let scope=Comp.scope;if(scope)for(let name in Comp.provide)for(let s=scope;s;s=s.parent)for(let otherName in s.byName){let Other=s.byName[otherName];Other!==Comp&&Other.provide?.[name]!==void 0&&lx.error(PROVIDE_NAME_COLLISION,{name,other:Other.name})}}var KNOWN_LOOKUP_KEYS=new Set(["name","default"]);function checkLookupShapes(lx,Comp){let raw=Comp._rawLookup;if(!Array.isArray(raw)){raw!==void 0&&Object.keys(raw).length>0&&lx.error(LOOKUP_BAD_SHAPE,{name:"lookup",problem:"must be a list of names"});return}for(let entry of raw){if(typeof entry=="string")continue;if(entry===null||typeof entry!="object"||Array.isArray(entry)){lx.error(LOOKUP_BAD_SHAPE,{name:String(entry),problem:'must be a "name" string or a { name, default } object'});continue}let extra=Object.keys(entry).filter(k=>!KNOWN_LOOKUP_KEYS.has(k));if(extra.length>0){lx.error(LOOKUP_BAD_SHAPE,{name:String(entry.name),problem:`unknown key(s): ${extra.join(", ")}`});continue}if(typeof entry.name!="string"||entry.name===""){lx.error(LOOKUP_BAD_SHAPE,{name:String(entry.name),problem:"'name' is required and must be a string"});continue}entry.default!==void 0&&typeof entry.default!="string"&&lx.error(LOOKUP_BAD_SHAPE,{name:entry.name,problem:"'default' must be a string"})}}function checkLookupsHaveProviders(lx,Comp){let scope=Comp.scope;if(scope)for(let name in Comp.lookup){if(isTypeName2(name)||scope.lookupProvider?.(name))continue;let info={name,hasDefault:Comp.lookup[name].val!=null};info.hasDefault?lx.hint(LOOKUP_NO_PROVIDER,info):lx.error(LOOKUP_NO_PROVIDER,info)}}function checkLookupTypesResolve(lx,Comp){if(Comp.scope)for(let name in Comp.lookup)isTypeName2(name)&&Comp.scope.lookupComponent(name)===null&&reportUnknownName(lx,UNKNOWN_COMPONENT_NAME,name,scopeKeysAlong(Comp.scope,"byName"),{})}function checkUnreferencedDynamics(lx,Comp,referencedDynamics){for(let name in Comp.lookup)isTypeName2(name)||referencedDynamics.has(name)||lx.hint(DYN_ALIAS_NOT_REFERENCED,{name})}var LintContext=class{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})}},LintParseContext=class 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})}};var OP_KINDS=["send","intent"];function phaseOps(phase){let ops=[];for(let type3 of OP_KINDS)for(let a of phase[type3]??[])ops.push({type:type3,...a});for(let a of phase.do??[])ops.push(a);return ops}function resolveArgs(args,self){return typeof args=="function"?args(self)??[]:args??[]}function dispatchPhase(dispatcher,targetPath,phase,self){if(phase)for(let op of phaseOps(phase)){let args=resolveArgs(op.args,self);switch(op.type){case"send":dispatcher.sendAtPath(targetPath,op.name,args);break;case"intent":dispatcher.intentAtPath(targetPath,op.name,args,op.opts);break}}}var BAD_VALUE2=Symbol("BadValue"),nullCoercer=v=>v,Field=class{constructor(type3,name,typeCheck,coercer,defaultValue=null){this.type=type3,this.name=name,this.typeCheck=typeCheck,this.coercer=coercer,this.defaultValue=defaultValue}isValid(v){return this.typeCheck(v)}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)}},CHECK_TYPE_ANY=_v=>!0,CHECK_TYPE_INT=Number.isInteger,CHECK_TYPE_FLOAT=Number.isFinite,CHECK_TYPE_BOOL=v=>typeof v=="boolean",CHECK_TYPE_STRING=v=>typeof v=="string",CHECK_TYPE_LIST=Array.isArray,CHECK_TYPE_OBJECT=isPlainObject,CHECK_TYPE_MAP=v=>v instanceof Map,CHECK_TYPE_SET=v=>v instanceof Set,FieldBool=class extends Field{constructor(name,defaultValue=!1){super("bool",name,CHECK_TYPE_BOOL,v=>!!v,defaultValue)}},FieldAny=class extends Field{constructor(name,defaultValue=null){super("any",name,CHECK_TYPE_ANY,nullCoercer,defaultValue)}},FieldString=class extends Field{constructor(name,defaultValue=""){super("text",name,CHECK_TYPE_STRING,v=>v?.toString?.()??"",defaultValue)}},FieldInt=class extends Field{constructor(name,defaultValue=0){super("int",name,CHECK_TYPE_INT,v=>Number.isFinite(v)?Math.trunc(v):null,defaultValue)}},FieldFloat=class extends Field{constructor(name,defaultValue=0){super("float",name,CHECK_TYPE_FLOAT,_=>null,defaultValue)}},metaOf=v=>v?.constructor?.[COMPONENT]??v?.constructor?.getMetaClass?.(),getTypeName=v=>metaOf(v)?.name??null,FieldComp=class extends Field{constructor(type3,name,args){super(type3,name,v=>getTypeName(v)===type3,nullCoercer,null),this.args=args}},FieldList=class extends Field{constructor(name,defaultValue=[]){super("list",name,CHECK_TYPE_LIST,v=>Array.isArray(v)?[...v]:null,defaultValue)}},FieldObject=class extends Field{constructor(name,defaultValue={}){super("object",name,CHECK_TYPE_OBJECT,v=>isPlainObject(v)?{...v}:null,defaultValue)}},FieldMap=class extends Field{constructor(name,defaultValue=new Map){super("map",name,CHECK_TYPE_MAP,v=>v instanceof Map?new Map(v):Array.isArray(v)||isPlainObject(v)?new Map(Array.isArray(v)?v:Object.entries(v)):null,defaultValue)}},FieldSet=class extends Field{constructor(name,defaultValue=new Set){super("set",name,CHECK_TYPE_SET,v=>v instanceof Set||Array.isArray(v)?new Set(v):null,defaultValue)}};function mkCompField(field,scope,args){let Comp=scope?.lookupComponent(field.type)??null;return Comp===null&&console.warn(scope?`component field "${field.name}": component "${field.type}" not found in scope`:`component field "${field.name}": cannot resolve component "${field.type}" — built without a registered scope (use ${field.type}.make({}) as the default, or build via a registered component)`),Comp?.make({...field.args,...args},{scope})??null}var ClassBuilder=class{constructor(name){this.name=name,this.fields={},this.compFields=new Set,this._methods={},this._statics={}}build(){let{name,fields,compFields,_methods}=this,defaults=Object.fromEntries(Object.entries(fields).map(([fieldName,field])=>[fieldName,field.defaultValue])),Class={[name]:class{constructor(values={}){Object.assign(this,defaults,values)}}}[name];Class[DRAFTABLE]=!0,Object.assign(Class.prototype,_methods);let metaClass={fields,name,methods:_methods};return Object.assign(Class,{getMetaClass:()=>metaClass,make(inArgs={},opts={}){let args={},scope=opts.scope??this[COMPONENT]?.scope??this.scope;for(let key in inArgs){let field=fields[key];compFields.has(key)?args[key]=mkCompField(field,scope,inArgs[key]):field===void 0?console.warn("extra argument to constructor:",name,key,inArgs):args[key]=field.coerceOrDefault(inArgs[key])}for(let key of compFields)args[key]===void 0&&(args[key]=mkCompField(fields[key],scope,inArgs[key]));return freeze(new this(args),!0)}},this._statics),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}},FIELD_CLASS=Symbol.for("tutuca.fieldClass"),fieldsByTypeName={text:FieldString,int:FieldInt,float:FieldFloat,bool:FieldBool,list:FieldList,object:FieldObject,map:FieldMap,set:FieldSet,any:FieldAny};function fieldFromDescriptor(name,value){let FieldCls=fieldsByTypeName[value.type]??FieldAny,probe=new FieldCls(name);return[FieldCls,probe.coerceOr(value.defaultValue,probe.defaultValue)]}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,Number.isInteger(value)?FieldInt:FieldFloat);else if(type3==="boolean")b.addField(field,value,FieldBool);else if(Array.isArray(value))b.addField(field,[...value],FieldList);else if(value instanceof Set)b.addField(field,new Set(value),FieldSet);else if(value instanceof Map)b.addField(field,new Map(value),FieldMap);else if(value?.type&&Object.hasOwn(value,"defaultValue")){let[FieldCls,dval]=fieldFromDescriptor(field,value);b.addField(field,dval,FieldCls)}else if(value?.component&&value?.args!==void 0)b.addCompField(field,value.component,value.args);else if(isPlainObject(value))b.addField(field,{...value},FieldObject);else{let FieldCls=value?.[FIELD_CLASS]??FieldAny;b.addField(field,value,FieldCls)}}return methods&&b.methods(methods),statics&&b.statics(statics),b.build()}function validateDraftFields(current2,draft){let meta=metaOf(current2);if(meta)for(let[name,field]of Object.entries(meta.fields)){let value=draft[name];if(field.isValid(value))continue;let coerced=field.coerceOr(value,BAD_VALUE2);coerced!==BAD_VALUE2?draft[name]=coerced:(console.warn(`invalid value for ${meta.name}.${name}`,value),draft[name]=current2[name])}}var META_KEYS="name id fields methods views receive intent alter provide provideType lookup spec extra commonStyle globalStyle scope _rawProvide _rawLookup".split(" "),RESERVED_COMPONENT_STATICS=new Set([...META_KEYS,"make","getMetaClass",...Object.getOwnPropertyNames(Component.prototype)]);function assertNoReservedComponentStatics(statics={}){for(let name in statics)if(RESERVED_COMPONENT_STATICS.has(name))throw new TypeError(`component static "${name}" is reserved by the framework`)}Component.fromSpec=opts=>{assertNoReservedComponentStatics(opts.statics);let Class=classFromData(opts.name,opts),comp=new Component(Class,opts),metaClass=Class.getMetaClass();comp.fields=metaClass.fields,comp.methods=metaClass.methods,Class.getMetaClass=()=>comp,Class[COMPONENT]=comp;for(let key of META_KEYS)Object.hasOwn(Class,key)||Object.defineProperty(Class,key,{get(){return comp[key]},set(v){comp[key]=v},configurable:!0});for(let key of Object.getOwnPropertyNames(Component.prototype))key!=="constructor"&&!Object.hasOwn(Class,key)&&(Class[key]=(...args)=>comp[key](...args));return Class};var component=opts=>Component.fromSpec(opts);var STOP=Symbol("STOP"),NEXT=Symbol("NEXT"),DEFAULT_ROUTE=["dyn","lex"];function routeLookup(route,lex,dyn){for(let i=0;i<route.length;i++){let leg=route[i];if(leg==="dyn"){let v=dyn();if(v!=null)return v}else if(leg==="lex"){let v=lex();if(v!=null)return v}else console.warn("unknown lookup route leg",leg,'- expected "dyn" or "lex"')}return null}function lookup(chain,name,dv=null){let n=chain;for(;n!==null;){let r=n[0].lookup(name);if(r===STOP)return dv;if(r!==NEXT)return r;n=n[1]}return dv}var BindFrame=class{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}},ObjectFrame=class{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;for(;n!==null;)s+=n[0],n=n[1];return s==="main"?"":s}var Stack=class _Stack{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}_pushProvides(){let comp=this.comps.getCompFor(this.it);if(comp==null)return this;let{provide,provideType}=comp,dynObj={},has2=!1;for(let k in provide)dynObj[k]=provide[k].val.eval(this),has2=!0;for(let k in provideType)dynObj[k]=provideType[k],has2=!0;if(!has2)return this;let newDynBinds=[new ObjectFrame(dynObj),this.dynBinds],{comps,it,binds,views,viewsId,ctx}=this;return new _Stack(comps,it,binds,newDynBinds,views,viewsId,ctx)}static root(comps,it,ctx){let binds=[new BindFrame(it,{},!0),null],dynBinds=[new ObjectFrame({}),null],views=["main",null];return new _Stack(comps,it,binds,dynBinds,views,"",ctx)._pushProvides()}enter(it,bindings={},isFrame=!0){let{comps,binds,dynBinds,views,viewsId,ctx}=this,newBinds=[new BindFrame(it,bindings,isFrame),binds],stack=new _Stack(comps,it,newBinds,dynBinds,views,viewsId,ctx);return isFrame?stack._pushProvides():stack}pushViewName(name){let{comps,it,binds,dynBinds,views,ctx}=this,newViews=[name,views];return new _Stack(comps,it,binds,dynBinds,newViews,computeViewsId(newViews),ctx)}_pushDynBindValuesToArray(arr,comp){for(let k in comp.provide)arr.push(this.lookupDynamic(k));for(let k in comp.lookup)arr.push(this.lookupDynamic(k))}lookupDynamic(name){let v=lookup(this.dynBinds,name);return v??this.comps.getCompFor(this.it)?.lookup[name]?.val?.eval(this)??null}lookupBind(name){return lookup(this.binds,name)}lookupFieldRaw(name){return this.it[name]??null}lookupMethod(name){let fn=this.it[name];return fn instanceof Function?fn.call(this.it):null}lookupEvent(){return this.ctx?.event??null}lookupDragInfo(){return this.ctx?.dragInfo??null}getHandlerFor(name,key){return this.comps.getHandlerFor(this.it,name,key)}lookupBestView(views,defaultViewName){let n=this.views;for(;n!==null;){let view=views[n[0]];if(view!==void 0)return view;n=n[1]}return views[defaultViewName]}};var State2=class{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()})}},Transactor=class{constructor(comps,rootValue){this.comps=comps,this.transactions=[],this.state=new State2(rootValue),this.onTransactionPushed=()=>{},this._observers=[],this.refusals=[],this._refusalObservers=[],this._inflight=new Set}pushTransaction(t){this.transactions.push(t),this.onTransactionPushed(t)}observe(cb){return this._observers.push(cb),()=>{let i=this._observers.indexOf(cb);i!==-1&&this._observers.splice(i,1)}}_emit(record){for(let cb of this._observers)cb(record)}refuse(kind,info={}){let record={kind,info,timestamp:Date.now()};this.refusals.push(record),this.refusals.length>REFUSAL_RING_CAP&&this.refusals.shift(),console.warn(`tutuca refusal [${kind}]`,info);for(let cb of this._refusalObservers)cb(record);return record}observeRefusals(cb){return this._refusalObservers.push(cb),()=>{let i=this._refusalObservers.indexOf(cb);i!==-1&&this._refusalObservers.splice(i,1)}}_emitRecord(root,{kind,name,args,path,targetPath,handler,handlerName,matched,before,after,parent}){if(this._observers.length===0)return;let pinned=path.pinKeys(root);this._emit({kind,name,args:args??null,path:pinned,pathKeys:pinned.toKeys(),targetPath,handler:handler??null,handlerName:handlerName??(handler?.name||null),matched:matched??null,before,after,parent,timestamp:Date.now()})}_emitTransaction(transaction,root){this._observers.length!==0&&transaction._resolvedHandler!==void 0&&this._emitRecord(root,{kind:transaction.observeKind,name:transaction.observeName,args:transaction.args,path:transaction.getTransactionPath(),targetPath:transaction.targetPath??transaction.path,handler:transaction._resolvedHandler,matched:transaction._matched,before:transaction._before,after:transaction._after,parent:transaction.parentTransaction})}_link(child,parent){if(parent){let release=parent.completion.track();child.completion.whenSubtreeSettled().then(release)}return child}pushSend(path,name,args=[],parent=null,origin=null){let t=new SendEvent(path,this,name,args,parent);return t.origin=origin===null?null:origin.toTransactionPath().pinKeys(this.state.val),this.pushTransaction(t),this._link(t,parent)}pushIntent(path,name,args=[],opts={},parent=null){let release=parent?parent.completion.track():null,walk=new IntentWalk(this,path,name,args,opts,parent,release);return walk.advance(),walk}async settle(maxTurns=1e4){for(;(this.hasPendingTransactions||this._inflight.size)&&maxTurns-- >0;){for(;this.hasPendingTransactions;)this.transactNext();this._inflight.size&&await Promise.allSettled([...this._inflight])}}get hasPendingTransactions(){return this.transactions.length>0}transactNext(){this.hasPendingTransactions&&this.transact(this.transactions.shift())}transact(transaction){try{let curState=this.state.val,newState=transaction.run(curState,this.comps);newState!==void 0?(this.state.set(newState,{transaction}),transaction.afterTransaction(),this._emitTransaction(transaction,curState)):console.warn("undefined new state",{curState,transaction})}finally{transaction.ensureWalkAdvanced?.(),transaction._completion?.ensureSelfSettled(),transaction._completion?.releaseSelf()}}transactInputNow(path,event,eventHandler,dragInfo){this.transact(new InputEvent(path,event,eventHandler,this,dragInfo))}};function nullHandler(){return this}var Transaction=class{constructor(path,transactor,parentTransaction=null){this.path=path,this.transactor=transactor,this.parentTransaction=parentTransaction,this._completion=null}get completion(){return this._completion??=new Completion,this._completion}whenSettled(){return this.completion.whenSettled()}whenSubtreeSettled(){return this.completion.whenSubtreeSettled()}afterTransaction(){}stop(){warnNotIntent("stop")}forward(_opts){console.warn('ctx.forward() needs a "receive" or "intent" handler - ignored')}get observeKind(){return null}get observeName(){return null}callHandler(root,instance,draft,comps){let[handler,args]=this.getHandlerAndArgs(root,instance,comps);return this._resolvedHandler=handler,handler.apply(instance,[draft,...args])}getHandlerAndArgs(_root,_instance,_comps){return null}getTransactionPath(){return this.path.toTransactionPath().compact()}run(curRoot,comps){let txnPath=this.getTransactionPath(),curLeaf=txnPath.lookup(curRoot),newLeaf=produce(curLeaf,draft=>{let result=this.callHandler(curRoot,curLeaf,draft,comps);return(result===void 0||result===draft)&&validateDraftFields(curLeaf,draft),result});return this._before=curLeaf,this._after=newLeaf,this._completion?.markSelfSettled({value:newLeaf,old:curLeaf}),curLeaf!==newLeaf?txnPath.setValue(curRoot,newLeaf):curRoot}},InputEvent=class 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}get observeKind(){return"receive"}get observeName(){return this.e?.type??null}forward(opts){this._forward=opts??{}}afterTransaction(){let f=this._forward;if(f===void 0)return;this._forward=void 0;let{args=this._handlerArgs??[],...rest}=f,name=(this.handler?.handlerCall?.handlerVal??this.handler?.handlerVal)?.name;if(name===void 0){this.transactor.refuse("FORWARD_NO_NAME",{});return}this.transactor.pushIntent(this.dispatchPath,name,args,rest,this)}getHandlerAndArgs(root,_instance,comps){let stack=this.path.toTransactionPath().buildStack(Stack.root(comps,root,this)),[handler,args]=this.handler.getHandlerAndArgs(stack,this);this._handlerArgs=[...args];let path=this.dispatchPath;return args.push(new EventContext(path,this.transactor,this)),[handler,args]}get event(){return this.e}},NameArgsTransaction=class extends Transaction{constructor(path,transactor,name,args,parentTransaction){super(path,transactor,parentTransaction),this.name=name,this.args=args,this.targetPath=path}handlerProp=null;get observeKind(){return this.handlerProp}get observeName(){return this.name}getHandlerForName(comp){let handlers=comp?.[this.handlerProp],exact=handlers?.[this.name];if(exact)return this._matched="exact",exact;let unknown=handlers?.$unknown;return unknown?(this._matched="unknown",unknown):(this._matched="none",nullHandler)}getHandlerAndArgs(_root,instance,comps){return[this.getHandlerForName(comps.getCompFor(instance)),[...this.args,new EventContext(this.path,this.transactor,this)]]}},SendEvent=class extends NameArgsTransaction{handlerProp="receive";get observeKind(){return this._isAnswer?"answer":"receive"}forward(opts){this._forward=opts??{}}afterTransaction(){let f=this._forward;if(f===void 0)return;this._forward=void 0;let{args=this.args,...rest}=f;this.transactor.pushIntent(this.path,this.name,args,rest,this)}},IntentEvent=class extends NameArgsTransaction{handlerProp="intent";constructor(path,transactor,walk){super(path,transactor,walk.name,walk.args,walk.parent),this.walk=walk,this.targetPath=walk.origin}forward(opts){this.walk.amend(opts,this.path)}stop(){this.walk.finish(null,null)}afterTransaction(){this.ensureWalkAdvanced()}ensureWalkAdvanced(){this._advanced||(this._advanced=!0,this.walk.advance())}},PASS=Symbol.for("tutuca.intent.pass"),REFUSAL_RING_CAP=200,INTENT_DEPTH=64,IntentWalk=class{constructor(transactor,path,name,args,opts,parent,release){this.transactor=transactor,this.name=name,this.args=args,this.route=opts?.route??DEFAULT_ROUTE,this.parent=parent,this.release=release,this.origin=path,this.answerPath=opts?.livePath?null:path.toTransactionPath().pinKeys(transactor.state.val),this.legIndex=0,this.dynAt=path,this.hops=0,this.ended=!1}advance(){if(!this.ended){if(this.hops++>=INTENT_DEPTH)return this.exhaust("intentDepth");for(;this.legIndex<this.route.length;){let leg=this.route[this.legIndex];if(leg==="dyn"){if(this.dynAt.steps.length===0){this.legIndex++;continue}this.dynAt=this.dynAt.popStep(),this.transactor.pushTransaction(new IntentEvent(this.dynAt,this.transactor,this));return}if(leg==="lex")return this.legIndex++,this._tryLex();console.warn("unknown intent route leg",leg,'- expected "dyn" or "lex"'),this.legIndex++}this.exhaust("noHandler")}}_tryLex(){let root=this.transactor.state.val,txnPath=this.origin.toTransactionPath(),leaf=txnPath.lookup(root),chain=this.transactor.comps.getIntentChainFor(leaf,this.name);if(this.transactor._emitRecord(root,{kind:"intent",name:this.name,args:this.args,path:txnPath,targetPath:this.origin,handler:chain[0],handlerName:chain[0]?.name||this.name,matched:chain.length>0?"exact":"none",before:leaf,after:void 0,parent:this.parent}),chain.length===0)return this.advance();let p=this._runLex(chain,0);this.transactor._inflight.add(p),p.finally(()=>this.transactor._inflight.delete(p))}async _runLex(chain,i){if(this.ended)return;if(i>=chain.length)return this.advance();let ctx=new Dispatcher(this.origin,this.transactor,this.parent);try{let res=await chain[i].apply(null,[...this.args,ctx]);if(res===PASS)return this._runLex(chain,i+1);this.answer("Ok",res)}catch(error){this.answer("Error",error)}}answer(suffix,value){this.finish(`${this.name}${suffix}`,[value])}amend(opts,from){opts?.args!==void 0&&(this.args=opts.args),opts?.route!==void 0&&(this.route=opts.route,this.legIndex=0,this.dynAt=from??this.dynAt)}exhaust(reason){if(this.ended)return;let{name,args}=this,comp=this.transactor.comps.getCompFor(this.origin.toTransactionPath().lookup(this.transactor.state.val)),declares=n=>comp?.receive?.[n]!==void 0;declares(`${name}Unhandled`)?this.finish(`${name}Unhandled`,args):declares(`${name}Error`)?this.finish(`${name}Error`,[reason]):(declares(`${name}Ok`)&&console.warn(`intent "${name}" was not answered (${reason}) and this component declares only "${name}Ok" - add "${name}Unhandled" or "${name}Error" to handle it`),this.finish(null,null))}finish(name,args){if(this.ended)return;if(this.ended=!0,name===null)return this.release?.();let path=this.answerPath??this.origin,t=new SendEvent(path,this.transactor,name,args,this.parent);t._isAnswer=!0,this.transactor.pushTransaction(t),this.release&&t.completion.whenSubtreeSettled().then(this.release)}},Completion=class{constructor(){this.val=void 0,this.selfSettled=!1,this.subtreeSettled=!1,this.pending=1,this._selfResolve=null,this._selfPromise=null,this._subtreeResolve=null,this._subtreePromise=null,this._selfReleased=!1}whenSettled(){return this.selfSettled?Promise.resolve(this.val):(this._selfPromise??=new Promise(res=>{this._selfResolve=res}),this._selfPromise)}whenSubtreeSettled(){return this.subtreeSettled?Promise.resolve(this.val):(this._subtreePromise??=new Promise(res=>{this._subtreeResolve=res}),this._subtreePromise)}markSelfSettled(val){this.selfSettled||(this.selfSettled=!0,this.val=val,this._selfResolve?.(val))}ensureSelfSettled(){this.selfSettled||this.markSelfSettled(this.val)}track(){this.pending++;let done=!1;return()=>{done||(done=!0,this._release())}}releaseSelf(){this._selfReleased||(this._selfReleased=!0,this._release())}_release(){--this.pending===0&&(this.subtreeSettled=!0,this._subtreeResolve?.(this.val))}},Dispatcher=class{constructor(path,transactor,parentTransaction,root=transactor.state.val){this.path=path,this.transactor=transactor,this.parent=parentTransaction,this.root=root}walkPath(callback){let comps=this.transactor.comps,chain=this.path.toTransactionPath().resolveChain(this.root);for(let i=chain.length-1;i>=0;i--){let comp=comps.getCompFor(chain[i]);if(comp&&callback(comp,chain[i])===!1)return}}get at(){return new PathChanges(this)}_stack(){return this._stackMemo??=this.path.toTransactionPath().buildStack(Stack.root(this.transactor.comps,this.root,this.parent)),this._stackMemo}lookup(name,opts){return routeLookup(opts?.route??DEFAULT_ROUTE,()=>this._lookupLex(name),()=>this._stack()?.lookupDynamic(name)??null)}_lookupLex(name){let Comp=null;return this.walkPath(c=>(Comp=c,!1)),Comp?.scope?.lookupComponent(name)??null}lookupType(name,opts){let route=opts?.route??DEFAULT_ROUTE,v=this.lookup(name,{route});return v==null?(this.transactor.refuse("TYPE_NOT_FOUND",{name,route}),null):v?.[COMPONENT]==null?(this.transactor.refuse("TYPE_NOT_COMPONENT",{name,got:typeof v}),null):v}send(name,args){return this.sendAtPath(this.path,name,args)}sendAtPath(path,name,args){return this.transactor.pushSend(path,name,args,this.parent,this.path)}intent(name,args,opts){return this.intentAtPath(this.path,name,args,opts)}intentAtPath(path,name,args,opts){return this.transactor.pushIntent(path,name,args,opts,this.parent)}},EventContext=class extends Dispatcher{get name(){return this.parent?.name??null}get targetPath(){return this.parent.targetPath}reply(value){return this.parent.walk===void 0?warnNotIntent("reply"):this.parent.walk.answer("Ok",value)}fail(error){return this.parent.walk===void 0?warnNotIntent("fail"):this.parent.walk.answer("Error",error)}sendReply(name,args){let origin=this.parent?.origin??null;return origin==null?(this.transactor.refuse("NO_SENDER",{name}),null):this.sendAtPath(origin,name,args)}stop(){return this.parent.stop()}forward(opts){return this.parent.forward(opts)}};function warnNotIntent(verb){console.warn(`ctx.${verb}() is only meaningful in an "intent" handler - ignored`)}var PathChanges=class extends PathBuilder{constructor(dispatcher){super(),this.dispatcher=dispatcher}send(name,args){return this.dispatcher.sendAtPath(this.buildPath(),name,args)}intent(name,args,opts){return this.dispatcher.intentAtPath(this.buildPath(),name,args,opts)}buildPath(){return this.dispatcher.path.concat(this.pathChanges)}};function rootDispatcher(transactor){return new Dispatcher(new Path([]),transactor,null)}var ModuleInfo=class{constructor({path=null,present=new Set,counts={},warnings=[]}){this.path=path,this.present=present,this.counts=counts,this.warnings=warnings}},ComponentSummary=class{constructor({name,views,fields}){this.name=name,this.views=views,this.fields=fields}},ComponentList=class{constructor({items,total=null,truncated=!1}){this.items=items,this.total=total??items.length,this.truncated=truncated}},ExampleIndex=class{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}},ComponentDocs=class{constructor({items}){this.items=items}},LintFinding=class{constructor({id,level,info,context={},suggestion=null}){this.id=id,this.level=level,this.info=info,this.context=context,this.suggestion=suggestion}},LintComponentResult=class{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}},LintReport=class{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)}},RenderedExample=class{constructor({title,description=null,componentName,view,html:html2,error=null}){this.title=title,this.description=description,this.componentName=componentName,this.view=view,this.html=html2,this.error=error}},RenderedSection=class{constructor({title,description=null,items}){this.title=title,this.description=description,this.items=items}},RenderBatch=class{constructor({sections}){this.sections=sections}get hasErrors(){return this.sections.some(s=>s.items.some(i=>i.error!==null))}},TestResult=class{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}},DescribeResult=class{constructor({title,componentName=null,children=[]}){this.title=title,this.componentName=componentName,this.children=children}},ModuleTestReport=class{constructor({path=null,suites=[],counts={pass:0,fail:0,skip:0,total:0}}){this.path=path,this.suites=suites,this.counts=counts}},TestReport=class{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)}};var Describe=class{constructor({title,componentName=null,parent=null}){this.title=title,this.componentName=componentName,this.parent=parent,this.children=[]}},Test=class{constructor({title,fn,componentName=null,parent=null}){this.title=title,this.fn=fn,this.componentName=componentName,this.parent=parent}},ModuleTests=class{constructor({path=null,suites=[]}={}){this.path=path,this.suites=suites}};function isComponentObject(x){return x===null?!1:typeof x=="function"?x[COMPONENT]!=null: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===arg)return c.name}return null}function titleFromArg(arg){return typeof arg=="string"?arg:isComponentObject(arg)?arg.name:typeof arg=="function"?arg.name||"(anonymous)":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 new Error(`describe() expects 2 or 3 arguments, got ${args.length}`);if(typeof fn!="function")throw new Error(`describe(${JSON.stringify(titleFromArg(head))}): final argument must be a function`);let componentName=null;if(typeof head!="string"&&(componentName=resolveComponentName(head,components)),componentName===null&&options&&options.component!=null&&(componentName=resolveComponentName(options.component,components)),componentName===null){let parent2=stack.length?stack[stack.length-1]:null;parent2&&(componentName=parent2.componentName)}let parent=stack.length?stack[stack.length-1]:null,node=new Describe({title:titleFromArg(head),componentName,parent});parent?parent.children.push(node):moduleTests.suites.push(node),stack.push(node);try{fn()}finally{stack.pop()}}function test3(title,fn){if(typeof title!="string")throw new Error("test(title, fn): title must be a string");if(typeof fn!="function")throw new Error(`test(${JSON.stringify(title)}): fn must be a function`);let parent=stack.length?stack[stack.length-1]:null;if(!parent)throw new 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:test3,moduleTests}}function buildPath(node){let parts=[],cur=node;for(;cur;)parts.unshift(cur.title),cur=cur.parent;return parts.join(" > ")}function captureError(e){let out={message:e.message,stack:e.stack};return"expected"in e&&(out.expected=e.expected),"actual"in e&&(out.actual=e.actual),out}function buildStack({components=[],macros=null,intentHandlers=null}={}){let stack=new ComponentStack;return stack.registerComponents(components),macros&&stack.registerMacros(macros),intentHandlers&&stack.registerIntentHandlers(intentHandlers),stack}async function driveStack(stack,value,phase,opts={}){let transactor=new Transactor(stack.comps,value);return opts.onMessage&&transactor.state.onChange(({val,old,info})=>{let t=info?.transaction;opts.onMessage({kind:t?.handlerProp??"receive",name:t?.name,args:t?.args,path:t?.path},old,val)}),dispatchPhase(rootDispatcher(transactor),new Path([]),phase,value),await transactor.settle(),transactor.state.val}async function drive(cfg,value,phase,opts={}){return driveStack(buildStack(cfg),value,phase,opts)}async function runTests({getTests,components=[],path=null,expect:expect2,name=null,grep=null,bail=!1,intentHandlers=null,macros=null}={}){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 new Error("runTests: expect must be provided (e.g. chai's expect)");let{describe,test:test3,moduleTests}=makeCollector({path,components}),_stack=null,getStack=()=>_stack??=buildStack({components,macros,intentHandlers});await getTests({describe,test:test3,expect:expect2,drive:(value,phase,opts={})=>driveStack(getStack(),value,phase,opts)});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){return counts.fail++,bail&&(bailed=!0),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);r!==null&&childResults.push(r)}return childResults.length===0?null:new DescribeResult({title:node.title,componentName:node.componentName,children:childResults})}let suiteResults=[];for(let suite of moduleTests.suites){let r=await visit(suite);r!==null&&suiteResults.push(r)}return new TestReport({modules:[new ModuleTestReport({path,suites:suiteResults,counts})]})}var PASS2="color: #0a0; font-weight: bold",FAIL="color: #c00; font-weight: bold",SKIP="color: #888",DIM="color: #888",RESET="color: inherit; font-weight: normal";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)`;node.status==="pass"?console.log(`%c✓%c ${node.title}%c${dur}`,PASS2,RESET,DIM):node.status==="skip"?console.log(`%c○ ${node.title}%c (skipped)`,SKIP,RESET):(console.group(`%c✗%c ${node.title}%c${dur}`,FAIL,RESET,DIM),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)),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)`;c.fail>0?console.error(`%c${summary}`,FAIL):c.total===0?console.log(`%c${summary}`,DIM):console.log(`%c${summary}`,PASS2),console.groupEnd()}return report}var UNSUPPORTED_EXPR_LABEL={ternary:"ternary expression",comparison:"comparison",logical:"logical expression","call-with-args":"method call with arguments","field-path":"dotted field path"};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 parameter '^${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}`)}info.handlerName&&parts.push(`handler '${info.handlerName}'${info.argIndex!==void 0?` arg ${info.argIndex}`:""}`);let t=tagDisplay(info.tag);return t&&t!=="x"&&parts.push(`on <${t}>`),parts.length?` (${parts.join(", ")})`:""}function fmtEventSuffix(info){return info?.originAttr?` in ${info.originAttr}`:info?.eventName?` in @on.${info.eventName}`:""}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"HANDLER_NAME_COLLISION":return`${info.problem} — ${info.fix}`;case"RECEIVE_HANDLER_NOT_IMPLEMENTED":return`Receive handler '${info.name}' is not implemented${fmtEventSuffix(info)}`;case"EVENT_HANDLER_METHOD_NOT_ALLOWED":return`Event handler '$${info.name}' is a method reference — move it to receive and use '${info.name}'`;case"FIELD_METHOD_NAME_COLLISION":return`Field '${info.name}' shadows a method with the same name — rename either the field or method`;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_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 binding '*${info.name}' is not defined${fmtOriginSuffix(info)}`;case"DYN_ALIAS_NOT_REFERENCED":return`Lookup '${info.name}' is defined but never used — remove it or reference it as '*${info.name}' in a view`;case"PROVIDE_NOT_ADDRESSABLE":return`Provide '${info.name}' value '${info.value}' must be a field ('.f') or seq-access ('.s[.k]') — a method/constant can't be a render target`;case"LOOKUP_BAD_SHAPE":return`Lookup '${info.name}' has an invalid shape: ${info.problem}`;case"LOOKUP_NO_PROVIDER":return info.hasDefault?`Lookup '${info.name}' is provided by no component in scope, so it always resolves to its default`:`Lookup '${info.name}' is provided by no component in scope — add a 'provide' for it, or give this lookup a default`;case"PROVIDE_TYPE_BAD_SHAPE":return`Provide '${info.name}' starts uppercase, so it publishes a component type — its value must be 'self', not '${info.value}'`;case"PROVIDE_NAME_COLLISION":return`Provide '${info.name}' is also provided by '${info.other}' in the same scope — one name, one provider, so a lookup can find it`;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"X_OP_IGNORES_CHILDREN":return`<x ${info.op}> has child content, but the '${info.op}' op ignores its children — they are silently dropped when the template is parsed; remove them${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"MAYBE_ADD_AT_PREFIX":return`'${info.name}' on <${(info.tag??"").toLowerCase()}> is a plain attribute, but '@${info.name}' is a directive — add the leading '@'`;case"BAD_VALUE":return`${badValueMessage(info)}${fmtTagSuffix(info)}`;case"UNSUPPORTED_EXPR_SYNTAX":return`${unsupportedExprMessage(info)}${fmtTagSuffix(info)}`;case"BINDING_MEMBER_TOO_DEEP":return`Binding member read ${JSON.stringify(info.value)} goes more than one level deep — only one member is allowed (like '@value.title')${fmtTagSuffix(info)}`;case"SUGGEST_BINDING_MEMBER":{let reads=(info.members??[]).map(({member})=>`'@value.${member}'`).join(", ");return`Enrich handler '${info.name}' only copies members of the loop value — read them directly${reads?` (${reads})`:""} and remove the '@enrich-with'`}case"REDUNDANT_TEMPLATE_STRING":return`Redundant string template — '{${info.simpler}}' should be just '${info.simpler}'${fmtOriginSuffix(info)}`;case"PLACEHOLDERLESS_TEMPLATE_STRING":return`String template has no dynamic parts — use the string literal ${info.literal} instead${fmtOriginSuffix(info)}`;case"CONSTANT_CONDITION":return`Condition is the constant literal ${info.literal} — it never changes; reference a field ('.name') or a method ('$name') instead${fmtOriginSuffix(info)}`;case"UNKNOWN_COMPONENT_SPEC_KEY":return`Unknown component spec key '${info.key}' — value will be ignored at runtime`;case"COMP_FIELD_BAD_SHAPE":return info.kind==="args-not-object"?`Field '${info.fieldName}': in { component, args }, 'args' must be a plain object, got ${info.got}`:`Field '${info.fieldName}': in { component, args }, 'component' must be the component name as a string, got ${info.gotName?`the ${info.gotName} class`:info.got}`;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"ASYNC_HANDLER":return`Handler '${info.name}' in '${info.channel}' is an async function — handlers must be synchronous and return the updated state (an async function returns a Promise the framework won't await)`;case"TOP_LEVEL_AT_RULE_IN_SCOPED_STYLE":return`'@${info.atRule}' is a top-level-only at-rule, but '${info.key}' is wrapped in a component-scoped selector ([data-cid=…]{…}) where it is invalid and silently dropped — move it to 'globalStyle'${fmtLocationSuffix(info)}`;case"GLOBAL_SELECTOR_IN_SCOPED_STYLE":return`Selector '${info.selector}' targets the document root, but '${info.key}' is wrapped in a component-scoped selector, so it becomes a descendant selector that never matches — move it to 'globalStyle'${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;return loc?` 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}`}}var _evs="dragstart dragover dragend touchstart touchmove touchend touchcancel".split(" "),App=class{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=>{this._transactNextBatchId===null&&this._scheduleNextTransactionBatchExecution()},this._compiled=!1,this._renderOpts={document:rootNode.ownerDocument},this._renderState=null,this.rootViewName=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.fromNodeAndEventName(e.target,type3,root,maxDepth,comps,!isDrag);if(isDrag&&this._handleDragEvent(e,type3,path),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)e.preventDefault(),fire("dragover",hitTest(rootNode,clientX,clientY));else{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)}return}(type3==="touchend"||type3==="touchcancel")&&(_touch.active&&(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);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,value=path.compact().toTransactionPath().lookup(rootValue),dragType=e.target.dataset.dragtype??"?",stack=path.toTransactionPath().buildStack(this.makeStack(rootValue));this.dragInfo=new DragInfo(stack,value,dragType,e.target)}else type3==="drop"?(e.preventDefault(),this._cleanDragOverAttrs()):(this.dragInfo!==null&&(delete this.dragInfo.node.dataset.dragging,this.dragInfo=null),this._cleanDragOverAttrs())}makeStack(rootValue){return Stack.root(this.comps,rootValue)}_cleanDragOverAttrs(){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,this.rootViewName),rootNode,_renderOpts,_renderState);return this._renderState=newState,newState.dom}onChange(callback){this.transactor.state.onChange(callback)}observe(callback){return this.transactor.observe(callback)}compile(){for(let Comp of this.comps.byId.values()){let meta=Comp[COMPONENT];meta.compile(this.ParseContext);for(let key in meta.views)for(let name of meta.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){this._compiled||this.compile(),this.subscribeToEvents(this._eventNames),this.onChange(info=>{info.val!==info.old&&this.render()}),this.recompileStyles(opts),opts?.noCache?this.renderer.setNullCache():this.startCacheEvictionInterval(),this.render()}stop(){this.stopCacheEvictionInterval();for(let name of this._eventNames)this.rootNode.removeEventListener(name,this,listenerOpts(name))}sendAtRoot(name,args){this.transactor.pushSend(new Path([]),name,args)}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;for(;t.hasPendingTransactions&&Date.now()-startTs<maxRunTimeMs;)t.transactNext();t.hasPendingTransactions&&this._scheduleNextTransactionBatchExecution()}_scheduleNextTransactionBatchExecution(){this._transactNextBatchId=setTimeout(()=>this._transactNextBatch(),0)}startCacheEvictionInterval(intervalMs=3e4){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}`);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;for(;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;for(;count-- >0&&node!==rootNode;){if(node.dataset?.droptarget!==void 0)return node;node=node.parentNode}return null}var DragInfo=class{constructor(stack,val,type3,node){this.stack=stack,this.val=val,this.type=type3,this.node=node}lookupBind(name){return this.stack.lookupBind(name)}};var isWeakKey=k=>k!==null&&(typeof k=="object"||typeof k=="function"),NullDomCache=class{get(_keys,_cacheKey){}set(_keys,_cacheKey,_v){}evict(){return{hit:0,miss:0,badKey:0}}},WeakMapDomCache=class{constructor(){this.hit=this.miss=this.badKey=0,this.keysByLen=new Map}_returnValue(r){return r===void 0?this.miss+=1:this.hit+=1,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);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(!isWeakKey(key)){this.badKey+=1;return}next=new WeakMap,cur.set(key,next)}cur=next}let lastKey=keys[len-1],leaf=cur.get(lastKey);leaf?leaf[cacheKey]=v:isWeakKey(lastKey)?cur.set(lastKey,{[cacheKey]:v}):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"],Renderer=class{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);return comp===null?null: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);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)return cachedNode;let view=viewName?comp.getView(viewName):stack.lookupBestView(comp.views,"main"),body=this.renderView(view,stack);if(body==null)return null;let meta=this._renderMetadata({$:"Comp",nid:node?.nodeId??null,cid:comp.id,vid:view.name}),dom=new VFragment([meta,body]);return this.cache.set(cachePath,cacheKey,dom),dom}pushEachEntry(r,nid,attrName,key,dom){r.push(this._renderMetadata({$:"Each",nid,[attrName]:key}),dom)}renderEachWhen(stack,iterInfo,view,nid){let{seq,filter,loopWith,enricher}=iterInfo.eval(stack),r=[],it=stack.it,renderOne=(key,value,attrName,binds)=>{let cachePath=enricher?[view,it,value]:[view,value],cacheKey=`${stack.viewsId??""}${nid}${key}`,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));dom!=null&&this.pushEachEntry(r,nid,attrName,key,dom),this.cache.set(cachePath,cacheKey,dom)}};return walkLoopBindings({seq,it,filter,loopWith,enricher,ctx:makeLoopCtx(stack,filter)},renderOne),r}renderView(view,stack){let n=stack.binds[1];for(;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)}§`)}renderScopeMeta(nid,dom){return new VFragment([this._renderMetadata({$:"Scope",nid}),dom])}};var css=String.raw,html=String.raw,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){return app.ParseContext=Ctx,app.compile(),await compileClasses(Array.from(collectAppClassesInSet(app)))}function resolveAlter(Comp,name){if(name==null)return null;let fn=Comp.alter?.[name];if(typeof fn!="function")throw new Error(`alter handler '${name}' not found on component '${Comp.name}'`);return fn}function collectIterBindings(Comp,compInstance,seq,opts={}){let whenFn=resolveAlter(Comp,opts.when)??filterAlwaysTrue,loopWithFn=resolveAlter(Comp,opts.loopWith)??nullLoopWith,enrichFn=resolveAlter(Comp,opts.enrichWith),scopeEnrichFn=resolveAlter(Comp,opts.scopeEnrich),it=compInstance,scope=scopeEnrichFn?scopeEnrichFn.call(it)??{}:opts.scope??{},ctx={lookup:name=>scope[name],filter:(key,value,iterData)=>whenFn.call(it,key,value,iterData)},out=[];return walkLoopBindings({seq,it,filter:whenFn,loopWith:loopWithFn,enricher:enrichFn,ctx},(_key,_value,_attrName,binds)=>out.push(binds)),out}function getSignature(name,fn){let m=fn.toString().match(/^(?:\w+|function\s*\w*)\s*\(([^)]*)\)/),params=m?m[1].trim():"";return`${name}(${params})`}function serializeDefault(v){return v==null?v:v instanceof Map?Object.fromEntries(v):v instanceof Set?[...v]:v}function getComponentDoc(comp){let{fields,name,methods}=comp,userMethods=Object.keys(methods).map(k=>({name:k,sig:getSignature(k,methods[k])})),sigs=bucket=>Object.keys(bucket??{}).map(k=>({name:k,sig:getSignature(k,bucket[k])})),receiveHandlers=sigs(comp.receive),intentHandlers=sigs(comp.intent),fieldDocs=[];for(let fieldName in fields){let field=fields[fieldName];fieldDocs.push({name:fieldName,type:field.type,default:serializeDefault(field.defaultValue),methods:[]})}return{name,methods:userMethods,receive:receiveHandlers,intent:intentHandlers,fields:fieldDocs}}function docComponents(normalized,{name=null}={}){let comps=normalized.components,picked=name===null?comps:comps.filter(c=>c.name===name);return new ComponentDocs({items:picked.map(comp=>getComponentDoc(comp))})}async function test2(opts={}){let report=await runTests({expect,...opts});return reportTestReportToConsole(report),report}function shadowCheckComponent(Comp){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);return Object.defineProperty(shadowComp,"views",{value:shadowViews,writable:!0,enumerable:!0,configurable:!0}),checkComponent(shadowComp).reports}function check(app){let counts={error:0,warn:0,hint:0};for(let Comp of app.comps.byId.values()){let reports=shadowCheckComponent(Comp);if(reports.length!==0){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}`;r.level==="error"?console.error(line):r.level==="warn"?console.warn(line):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}var LintClassCollectorCtx=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,frame={macroName,macroVars,macroSlots},v=new _LintClassCollectorCtx(document2,Text,Comment,nodes,events2,macroNodes,frame,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{ALT_HANDLER_NOT_DEFINED,ALT_HANDLER_NOT_REFERENCED,ASYNC_HANDLER,BAD_VALUE,BINDING_MEMBER_TOO_DEEP,COMPONENT,COMP_FIELD_BAD_SHAPE,CONSTANT_CONDITION,ComponentDocs,ComponentList,ComponentSummary,DUPLICATE_ATTR_DEFINITION,DYN_ALIAS_NOT_REFERENCED,DYN_VAL_NOT_DEFINED,Describe,DescribeResult,EVENT_HANDLER_METHOD_NOT_ALLOWED,ExampleIndex,FIELD_CLASS,FIELD_METHOD_NAME_COLLISION,FIELD_VAL_IS_METHOD,FIELD_VAL_NOT_DEFINED,GLOBAL_SELECTOR_IN_SCOPED_STYLE,HANDLER_NAME_COLLISION,IF_NO_BRANCH_SET,LOOKUP_BAD_SHAPE,LOOKUP_NO_PROVIDER,LintClassCollectorCtx,LintComponentResult,LintContext,LintFinding,LintParseContext,LintReport,MAYBE_ADD_AT_PREFIX,MAYBE_DROP_AT_PREFIX,METHOD_VAL_IS_FIELD,METHOD_VAL_NOT_DEFINED,ModuleInfo,ModuleTestReport,ModuleTests,PASS,PLACEHOLDERLESS_TEMPLATE_STRING,PROVIDE_NAME_COLLISION,PROVIDE_NOT_ADDRESSABLE,PROVIDE_TYPE_BAD_SHAPE,ParseContext,RECEIVE_HANDLER_NOT_IMPLEMENTED,REDUNDANT_TEMPLATE_STRING,RENDER_IT_OUTSIDE_OF_LOOP,RenderBatch,RenderedExample,RenderedSection,SEQ_INFO,SUGGEST_BINDING_MEMBER,TOP_LEVEL_AT_RULE_IN_SCOPED_STYLE,Test,TestReport,TestResult,UNKNOWN_COMPONENT_NAME,UNKNOWN_COMPONENT_SPEC_KEY,UNKNOWN_DIRECTIVE,UNKNOWN_EVENT_MODIFIER,UNKNOWN_MACRO_ARG,UNKNOWN_X_ATTR,UNKNOWN_X_OP,UNSUPPORTED_EXPR_SYNTAX,X_OP_IGNORES_CHILDREN,check,checkComponent,collectIterBindings,compileClassesToStyle,compileClassesToStyleText,component,css,dispatchPhase,docComponents,drive,expect,html,injectCss,lintIdToMessage,macro,makeCollector,phaseOps,reportTestReportToConsole,resolveArgs,rootDispatcher,runTests,shadowCheckComponent,suggestionToMessage,test2 as test,tutuca};
|
|
5
|
+
`&&(line++,lineStart=i+1);return{line,column:index-lineStart+1}}function suppressedLines(css2){let lines=new Set;IGNORE_DIRECTIVE.lastIndex=0;for(let m=IGNORE_DIRECTIVE.exec(css2);m!==null;m=IGNORE_DIRECTIVE.exec(css2))lines.add(offsetToLineCol2(css2,m.index).line);return lines}var STYLE_TO_GLOBAL_HELP="Move it to the component's 'globalStyle' key, which is injected without the component-scoping wrapper. To suppress a false positive, put a /* tutuca-lint-ignore */ comment on the same line.";function scanScopedCss(lx,css2,key){if(!css2)return;let ignore=suppressedLines(css2),clean=blankCssNoise(css2),report=(id,info)=>{ignore.has(info.location.line)||lx.error(id,{key,...info},{kind:"rephrase",text:STYLE_TO_GLOBAL_HELP})};NON_NESTABLE_AT_RULE.lastIndex=0;for(let m=NON_NESTABLE_AT_RULE.exec(clean);m!==null;m=NON_NESTABLE_AT_RULE.exec(clean)){let at=m.index+m[0].indexOf("@");report(TOP_LEVEL_AT_RULE_IN_SCOPED_STYLE,{atRule:m[1].toLowerCase(),location:offsetToLineCol2(clean,at)})}GLOBAL_LEADING_SELECTOR.lastIndex=0;for(let m=GLOBAL_LEADING_SELECTOR.exec(clean);m!==null;m=GLOBAL_LEADING_SELECTOR.exec(clean)){let at=m.index+m[0].indexOf(m[1]);report(GLOBAL_SELECTOR_IN_SCOPED_STYLE,{selector:m[1].toLowerCase(),location:offsetToLineCol2(clean,at)})}}function checkScopedStyleTopLevel(lx,Comp){scanScopedCss(lx,Comp.commonStyle,"commonStyle");for(let name in Comp.views){let{style}=Comp.views[name];style&&lx.push({viewName:name},()=>scanScopedCss(lx,style,"style"))}}function checkProvidesAreAddressable(lx,Comp){for(let name in Comp._rawProvide)isTypeName2(name)||Comp.provide[name]===void 0&&lx.error(PROVIDE_NOT_ADDRESSABLE,{name,value:Comp._rawProvide[name]})}function checkProvidedTypes(lx,Comp){for(let name in Comp._rawProvide){if(!isTypeName2(name))continue;let raw=Comp._rawProvide[name];raw!=="self"&&lx.error(PROVIDE_TYPE_BAD_SHAPE,{name,value:raw})}}function checkProvideNameCollisions(lx,Comp){let scope=Comp.scope;if(scope)for(let name in Comp.provide)for(let s=scope;s;s=s.parent)for(let otherName in s.byName){let Other=s.byName[otherName];Other!==Comp&&Other.provide?.[name]!==void 0&&lx.error(PROVIDE_NAME_COLLISION,{name,other:Other.name})}}var KNOWN_LOOKUP_KEYS=new Set(["name","default"]);function checkLookupShapes(lx,Comp){let raw=Comp._rawLookup;if(!Array.isArray(raw)){raw!==void 0&&Object.keys(raw).length>0&&lx.error(LOOKUP_BAD_SHAPE,{name:"lookup",problem:"must be a list of names"});return}for(let entry of raw){if(typeof entry=="string")continue;if(entry===null||typeof entry!="object"||Array.isArray(entry)){lx.error(LOOKUP_BAD_SHAPE,{name:String(entry),problem:'must be a "name" string or a { name, default } object'});continue}let extra=Object.keys(entry).filter(k=>!KNOWN_LOOKUP_KEYS.has(k));if(extra.length>0){lx.error(LOOKUP_BAD_SHAPE,{name:String(entry.name),problem:`unknown key(s): ${extra.join(", ")}`});continue}if(typeof entry.name!="string"||entry.name===""){lx.error(LOOKUP_BAD_SHAPE,{name:String(entry.name),problem:"'name' is required and must be a string"});continue}entry.default!==void 0&&typeof entry.default!="string"&&lx.error(LOOKUP_BAD_SHAPE,{name:entry.name,problem:"'default' must be a string"})}}function checkLookupsHaveProviders(lx,Comp){let scope=Comp.scope;if(scope)for(let name in Comp.lookup){if(isTypeName2(name)||scope.lookupProvider?.(name))continue;let info={name,hasDefault:Comp.lookup[name].val!=null};info.hasDefault?lx.hint(LOOKUP_NO_PROVIDER,info):lx.error(LOOKUP_NO_PROVIDER,info)}}function checkLookupTypesResolve(lx,Comp){if(Comp.scope)for(let name in Comp.lookup)isTypeName2(name)&&Comp.scope.lookupComponent(name)===null&&reportUnknownName(lx,UNKNOWN_COMPONENT_NAME,name,scopeKeysAlong(Comp.scope,"byName"),{})}function checkUnreferencedDynamics(lx,Comp,referencedDynamics){for(let name in Comp.lookup)isTypeName2(name)||referencedDynamics.has(name)||lx.hint(DYN_ALIAS_NOT_REFERENCED,{name})}var LintContext=class{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})}},LintParseContext=class 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})}};var OP_KINDS=["send","intent"];function phaseOps(phase){let ops=[];for(let type3 of OP_KINDS)for(let a of phase[type3]??[])ops.push({type:type3,...a});for(let a of phase.do??[])ops.push(a);return ops}function resolveArgs(args,self){return typeof args=="function"?args(self)??[]:args??[]}function dispatchPhase(dispatcher,targetPath,phase,self){if(phase)for(let op of phaseOps(phase)){let args=resolveArgs(op.args,self);switch(op.type){case"send":dispatcher.sendAtPath(targetPath,op.name,args);break;case"intent":dispatcher.intentAtPath(targetPath,op.name,args,op.opts);break}}}var BAD_VALUE2=Symbol("BadValue"),nullCoercer=v=>v,Field=class{constructor(type3,name,typeCheck,coercer,defaultValue=null){this.type=type3,this.name=name,this.typeCheck=typeCheck,this.coercer=coercer,this.defaultValue=defaultValue}isValid(v){return this.typeCheck(v)}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)}},CHECK_TYPE_ANY=_v=>!0,CHECK_TYPE_INT=Number.isInteger,CHECK_TYPE_FLOAT=Number.isFinite,CHECK_TYPE_BOOL=v=>typeof v=="boolean",CHECK_TYPE_STRING=v=>typeof v=="string",CHECK_TYPE_LIST=Array.isArray,CHECK_TYPE_OBJECT=isPlainObject,CHECK_TYPE_MAP=v=>v instanceof Map,CHECK_TYPE_SET=v=>v instanceof Set,COERCE_NONE=_v=>null,COERCE_BOOL=v=>!!v,COERCE_STRING=v=>v?.toString?.()??"",COERCE_INT=v=>Number.isFinite(v)?Math.trunc(v):null,COERCE_LIST=v=>Array.isArray(v)?[...v]:null,COERCE_OBJECT=v=>isPlainObject(v)?{...v}:null,COERCE_MAP=v=>v instanceof Map?new Map(v):Array.isArray(v)||isPlainObject(v)?new Map(Array.isArray(v)?v:Object.entries(v)):null,COERCE_SET=v=>v instanceof Set||Array.isArray(v)?new Set(v):null,FieldBool=class extends Field{constructor(name,defaultValue=!1){super("bool",name,CHECK_TYPE_BOOL,COERCE_BOOL,defaultValue)}},FieldAny=class extends Field{constructor(name,defaultValue=null){super("any",name,CHECK_TYPE_ANY,nullCoercer,defaultValue)}},FieldString=class extends Field{constructor(name,defaultValue=""){super("text",name,CHECK_TYPE_STRING,COERCE_STRING,defaultValue)}},FieldInt=class extends Field{constructor(name,defaultValue=0){super("int",name,CHECK_TYPE_INT,COERCE_INT,defaultValue)}},FieldFloat=class extends Field{constructor(name,defaultValue=0){super("float",name,CHECK_TYPE_FLOAT,COERCE_NONE,defaultValue)}},metaOf=v=>v?.constructor?.[COMPONENT]??v?.constructor?.getMetaClass?.(),getTypeName=v=>metaOf(v)?.name??null,FieldComp=class extends Field{constructor(type3,name,args){super(type3,name,v=>getTypeName(v)===type3,nullCoercer,null),this.args=args}},FieldList=class extends Field{constructor(name,defaultValue=[]){super("list",name,CHECK_TYPE_LIST,COERCE_LIST,defaultValue)}},FieldObject=class extends Field{constructor(name,defaultValue={}){super("object",name,CHECK_TYPE_OBJECT,COERCE_OBJECT,defaultValue)}},FieldMap=class extends Field{constructor(name,defaultValue=new Map){super("map",name,CHECK_TYPE_MAP,COERCE_MAP,defaultValue)}},FieldSet=class extends Field{constructor(name,defaultValue=new Set){super("set",name,CHECK_TYPE_SET,COERCE_SET,defaultValue)}};function mkCompField(field,scope,args){let Comp=scope?.lookupComponent(field.type)??null;return Comp===null&&console.warn(scope?`component field "${field.name}": component "${field.type}" not found in scope`:`component field "${field.name}": cannot resolve component "${field.type}" — built without a registered scope (use ${field.type}.make({}) as the default, or build via a registered component)`),Comp?.make({...field.args,...args},{scope})??null}var ClassBuilder=class{constructor(name){this.name=name,this.fields={},this.compFields=new Set,this._methods={},this._statics={}}build(){let{name,fields,compFields,_methods}=this,defaults=Object.fromEntries(Object.entries(fields).map(([fieldName,field])=>[fieldName,field.defaultValue])),Class={[name]:class{constructor(values={}){Object.assign(this,defaults,values)}}}[name];Class[DRAFTABLE]=!0,Object.assign(Class.prototype,_methods);let metaClass={fields,name,methods:_methods};return Object.assign(Class,{getMetaClass:()=>metaClass,make(inArgs={},opts={}){let args={},scope=opts.scope??this[COMPONENT]?.scope??this.scope;for(let key in inArgs){let field=fields[key];compFields.has(key)?args[key]=mkCompField(field,scope,inArgs[key]):field===void 0?console.warn("extra argument to constructor:",name,key,inArgs):args[key]=field.coerceOrDefault(inArgs[key])}for(let key of compFields)args[key]===void 0&&(args[key]=mkCompField(fields[key],scope,inArgs[key]));return freeze(new this(args),!0)}},this._statics),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}},FIELD_CLASS=Symbol.for("tutuca.fieldClass"),fieldsByTypeName={text:FieldString,int:FieldInt,float:FieldFloat,bool:FieldBool,list:FieldList,object:FieldObject,map:FieldMap,set:FieldSet,any:FieldAny};function fieldFromDescriptor(name,value){let FieldCls=fieldsByTypeName[value.type]??FieldAny,probe=new FieldCls(name);return[FieldCls,probe.coerceOr(value.defaultValue,probe.defaultValue)]}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(Array.isArray(value))b.addField(field,[...value],FieldList);else if(value instanceof Set)b.addField(field,new Set(value),FieldSet);else if(value instanceof Map)b.addField(field,new Map(value),FieldMap);else if(value?.type&&Object.hasOwn(value,"defaultValue")){let[FieldCls,dval]=fieldFromDescriptor(field,value);b.addField(field,dval,FieldCls)}else if(value?.component&&value?.args!==void 0)b.addCompField(field,value.component,value.args);else if(isPlainObject(value))b.addField(field,{...value},FieldObject);else{let FieldCls=value?.[FIELD_CLASS]??FieldAny;b.addField(field,value,FieldCls)}}return methods&&b.methods(methods),statics&&b.statics(statics),b.build()}function validateDraftFields(current2,draft){let meta=metaOf(current2);if(meta)for(let[name,field]of Object.entries(meta.fields)){let value=draft[name];if(field.isValid(value))continue;let coerced=field.coerceOr(value,BAD_VALUE2);coerced!==BAD_VALUE2?draft[name]=coerced:(console.warn(`invalid value for ${meta.name}.${name}`,value),draft[name]=current2[name])}}var META_KEYS="name id fields methods views receive intent alter provide provideType lookup spec extra commonStyle globalStyle scope _rawProvide _rawLookup".split(" "),RESERVED_COMPONENT_STATICS=new Set([...META_KEYS,"make","getMetaClass",...Object.getOwnPropertyNames(Component.prototype)]);function assertNoReservedComponentStatics(statics={}){for(let name in statics)if(RESERVED_COMPONENT_STATICS.has(name))throw new TypeError(`component static "${name}" is reserved by the framework`)}Component.fromSpec=opts=>{assertNoReservedComponentStatics(opts.statics);let Class=classFromData(opts.name,opts),comp=new Component(Class,opts),metaClass=Class.getMetaClass();comp.fields=metaClass.fields,comp.methods=metaClass.methods,Class.getMetaClass=()=>comp,Class[COMPONENT]=comp;for(let key of META_KEYS)Object.hasOwn(Class,key)||Object.defineProperty(Class,key,{get(){return comp[key]},set(v){comp[key]=v},configurable:!0});for(let key of Object.getOwnPropertyNames(Component.prototype))key!=="constructor"&&!Object.hasOwn(Class,key)&&(Class[key]=(...args)=>comp[key](...args));return Class};var component=opts=>Component.fromSpec(opts);var STOP=Symbol("STOP"),NEXT=Symbol("NEXT"),DEFAULT_ROUTE=["dyn","lex"];function routeLookup(route,lex,dyn){for(let i=0;i<route.length;i++){let leg=route[i];if(leg==="dyn"){let v=dyn();if(v!=null)return v}else if(leg==="lex"){let v=lex();if(v!=null)return v}else console.warn("unknown lookup route leg",leg,'- expected "dyn" or "lex"')}return null}function lookup(chain,name,dv=null){let n=chain;for(;n!==null;){let r=n[0].lookup(name);if(r===STOP)return dv;if(r!==NEXT)return r;n=n[1]}return dv}var BindFrame=class{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}},ObjectFrame=class{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;for(;n!==null;)s+=n[0],n=n[1];return s==="main"?"":s}var Stack=class _Stack{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}_pushProvides(){let comp=this.comps.getCompFor(this.it);if(comp==null)return this;let{provide,provideType}=comp,dynObj={},has2=!1;for(let k in provide)dynObj[k]=provide[k].val.eval(this),has2=!0;for(let k in provideType)dynObj[k]=provideType[k],has2=!0;if(!has2)return this;let newDynBinds=[new ObjectFrame(dynObj),this.dynBinds],{comps,it,binds,views,viewsId,ctx}=this;return new _Stack(comps,it,binds,newDynBinds,views,viewsId,ctx)}static root(comps,it,ctx){let binds=[new BindFrame(it,{},!0),null],dynBinds=[new ObjectFrame({}),null],views=["main",null];return new _Stack(comps,it,binds,dynBinds,views,"",ctx)._pushProvides()}enter(it,bindings={},isFrame=!0){let{comps,binds,dynBinds,views,viewsId,ctx}=this,newBinds=[new BindFrame(it,bindings,isFrame),binds],stack=new _Stack(comps,it,newBinds,dynBinds,views,viewsId,ctx);return isFrame?stack._pushProvides():stack}pushViewName(name){let{comps,it,binds,dynBinds,views,ctx}=this,newViews=[name,views];return new _Stack(comps,it,binds,dynBinds,newViews,computeViewsId(newViews),ctx)}_pushDynBindValuesToArray(arr,comp){for(let k in comp.provide)arr.push(this.lookupDynamic(k));for(let k in comp.lookup)arr.push(this.lookupDynamic(k))}lookupDynamic(name){let v=lookup(this.dynBinds,name);return v??this.comps.getCompFor(this.it)?.lookup[name]?.val?.eval(this)??null}lookupBind(name){return lookup(this.binds,name)}lookupFieldRaw(name){return this.it[name]??null}lookupMethod(name){let fn=this.it[name];return fn instanceof Function?fn.call(this.it):null}lookupEvent(){return this.ctx?.event??null}lookupDragInfo(){return this.ctx?.dragInfo??null}getHandlerFor(name,key){return this.comps.getHandlerFor(this.it,name,key)}lookupBestView(views,defaultViewName){let n=this.views;for(;n!==null;){let view=views[n[0]];if(view!==void 0)return view;n=n[1]}return views[defaultViewName]}};var State2=class{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()})}},Transactor=class{constructor(comps,rootValue){this.comps=comps,this.transactions=[],this.state=new State2(rootValue),this.onTransactionPushed=()=>{},this._observers=[],this.refusals=[],this._refusalObservers=[],this._inflight=new Set}pushTransaction(t){this.transactions.push(t),this.onTransactionPushed(t)}observe(cb){return this._observers.push(cb),()=>{let i=this._observers.indexOf(cb);i!==-1&&this._observers.splice(i,1)}}_emit(record){for(let cb of this._observers)cb(record)}refuse(kind,info={}){let record={kind,info,timestamp:Date.now()};this.refusals.push(record),this.refusals.length>REFUSAL_RING_CAP&&this.refusals.shift(),console.warn(`tutuca refusal [${kind}]`,info);for(let cb of this._refusalObservers)cb(record);return record}observeRefusals(cb){return this._refusalObservers.push(cb),()=>{let i=this._refusalObservers.indexOf(cb);i!==-1&&this._refusalObservers.splice(i,1)}}_emitRecord(root,{kind,name,args,path,targetPath,handler,handlerName,matched,before,after,parent}){if(this._observers.length===0)return;let pinned=path.pinKeys(root);this._emit({kind,name,args:args??null,path:pinned,pathKeys:pinned.toKeys(),targetPath,handler:handler??null,handlerName:handlerName??(handler?.name||null),matched:matched??null,before,after,parent,timestamp:Date.now()})}_emitTransaction(transaction,root){this._observers.length!==0&&transaction._resolvedHandler!==void 0&&this._emitRecord(root,{kind:transaction.observeKind,name:transaction.observeName,args:transaction.args,path:transaction.getTransactionPath(),targetPath:transaction.targetPath??transaction.path,handler:transaction._resolvedHandler,matched:transaction._matched,before:transaction._before,after:transaction._after,parent:transaction.parentTransaction})}_link(child,parent){if(parent){let release=parent.completion.track();child.completion.whenSubtreeSettled().then(release)}return child}pushSend(path,name,args=[],parent=null,origin=null){let t=new SendEvent(path,this,name,args,parent);return t.origin=origin===null?null:origin.toTransactionPath().pinKeys(this.state.val),this.pushTransaction(t),this._link(t,parent)}pushIntent(path,name,args=[],opts={},parent=null){let release=parent?parent.completion.track():null,walk=new IntentWalk(this,path,name,args,opts,parent,release);return walk.advance(),walk}async settle(maxTurns=1e4){for(;(this.hasPendingTransactions||this._inflight.size)&&maxTurns-- >0;){for(;this.hasPendingTransactions;)this.transactNext();this._inflight.size&&await Promise.allSettled([...this._inflight])}}get hasPendingTransactions(){return this.transactions.length>0}transactNext(){this.hasPendingTransactions&&this.transact(this.transactions.shift())}transact(transaction){try{let curState=this.state.val,newState=transaction.run(curState,this.comps);newState!==void 0?(this.state.set(newState,{transaction}),transaction.afterTransaction(),this._emitTransaction(transaction,curState)):console.warn("undefined new state",{curState,transaction})}finally{transaction.ensureWalkAdvanced?.(),transaction._completion?.ensureSelfSettled(),transaction._completion?.releaseSelf()}}transactInputNow(path,event,eventHandler,dragInfo){this.transact(new InputEvent(path,event,eventHandler,this,dragInfo))}};function nullHandler(){return this}var Transaction=class{constructor(path,transactor,parentTransaction=null){this.path=path,this.transactor=transactor,this.parentTransaction=parentTransaction,this._completion=null}get completion(){return this._completion??=new Completion,this._completion}whenSettled(){return this.completion.whenSettled()}whenSubtreeSettled(){return this.completion.whenSubtreeSettled()}afterTransaction(){}stop(){warnNotIntent("stop")}forward(_opts){console.warn('ctx.forward() needs a "receive" or "intent" handler - ignored')}get observeKind(){return null}get observeName(){return null}callHandler(root,instance,draft,comps){let[handler,args]=this.getHandlerAndArgs(root,instance,comps);return this._resolvedHandler=handler,handler.apply(instance,[draft,...args])}getHandlerAndArgs(_root,_instance,_comps){return null}getTransactionPath(){return this.path.toTransactionPath().compact()}run(curRoot,comps){let txnPath=this.getTransactionPath(),curLeaf=txnPath.lookup(curRoot),newLeaf=produce(curLeaf,draft=>{let result=this.callHandler(curRoot,curLeaf,draft,comps);return(result===void 0||result===draft)&&validateDraftFields(curLeaf,draft),result});return this._before=curLeaf,this._after=newLeaf,this._completion?.markSelfSettled({value:newLeaf,old:curLeaf}),curLeaf!==newLeaf?txnPath.setValue(curRoot,newLeaf):curRoot}},InputEvent=class 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}get observeKind(){return"receive"}get observeName(){return this.e?.type??null}forward(opts){this._forward=opts??{}}afterTransaction(){let f=this._forward;if(f===void 0)return;this._forward=void 0;let{args=this._handlerArgs??[],...rest}=f,name=(this.handler?.handlerCall?.handlerVal??this.handler?.handlerVal)?.name;if(name===void 0){this.transactor.refuse("FORWARD_NO_NAME",{});return}this.transactor.pushIntent(this.dispatchPath,name,args,rest,this)}getHandlerAndArgs(root,_instance,comps){let stack=this.path.toTransactionPath().buildStack(Stack.root(comps,root,this)),[handler,args]=this.handler.getHandlerAndArgs(stack,this);this._handlerArgs=[...args];let path=this.dispatchPath;return args.push(new EventContext(path,this.transactor,this)),[handler,args]}get event(){return this.e}},NameArgsTransaction=class extends Transaction{constructor(path,transactor,name,args,parentTransaction){super(path,transactor,parentTransaction),this.name=name,this.args=args,this.targetPath=path}handlerProp=null;get observeKind(){return this.handlerProp}get observeName(){return this.name}getHandlerForName(comp){let handlers=comp?.[this.handlerProp],exact=handlers?.[this.name];if(exact)return this._matched="exact",exact;let unknown=handlers?.$unknown;return unknown?(this._matched="unknown",unknown):(this._matched="none",nullHandler)}getHandlerAndArgs(_root,instance,comps){return[this.getHandlerForName(comps.getCompFor(instance)),[...this.args,new EventContext(this.path,this.transactor,this)]]}},SendEvent=class extends NameArgsTransaction{handlerProp="receive";get observeKind(){return this._isAnswer?"answer":"receive"}forward(opts){this._forward=opts??{}}afterTransaction(){let f=this._forward;if(f===void 0)return;this._forward=void 0;let{args=this.args,...rest}=f;this.transactor.pushIntent(this.path,this.name,args,rest,this)}},IntentEvent=class extends NameArgsTransaction{handlerProp="intent";constructor(path,transactor,walk){super(path,transactor,walk.name,walk.args,walk.parent),this.walk=walk,this.targetPath=walk.origin}forward(opts){this.walk.amend(opts,this.path)}stop(){this.walk.finish(null,null)}afterTransaction(){this.ensureWalkAdvanced()}ensureWalkAdvanced(){this._advanced||(this._advanced=!0,this.walk.advance())}},PASS=Symbol.for("tutuca.intent.pass"),REFUSAL_RING_CAP=200,INTENT_DEPTH=64,IntentWalk=class{constructor(transactor,path,name,args,opts,parent,release){this.transactor=transactor,this.name=name,this.args=args,this.route=opts?.route??DEFAULT_ROUTE,this.parent=parent,this.release=release,this.origin=path,this.answerPath=opts?.livePath?null:path.toTransactionPath().pinKeys(transactor.state.val),this.legIndex=0,this.dynAt=path,this.hops=0,this.ended=!1}advance(){if(!this.ended){if(this.hops++>=INTENT_DEPTH)return this.exhaust("intentDepth");for(;this.legIndex<this.route.length;){let leg=this.route[this.legIndex];if(leg==="dyn"){if(this.dynAt.steps.length===0){this.legIndex++;continue}this.dynAt=this.dynAt.popStep(),this.transactor.pushTransaction(new IntentEvent(this.dynAt,this.transactor,this));return}if(leg==="lex")return this.legIndex++,this._tryLex();console.warn("unknown intent route leg",leg,'- expected "dyn" or "lex"'),this.legIndex++}this.exhaust("noHandler")}}_tryLex(){let root=this.transactor.state.val,txnPath=this.origin.toTransactionPath(),leaf=txnPath.lookup(root),chain=this.transactor.comps.getIntentChainFor(leaf,this.name);if(this.transactor._emitRecord(root,{kind:"intent",name:this.name,args:this.args,path:txnPath,targetPath:this.origin,handler:chain[0],handlerName:chain[0]?.name||this.name,matched:chain.length>0?"exact":"none",before:leaf,after:void 0,parent:this.parent}),chain.length===0)return this.advance();let p=this._runLex(chain,0);this.transactor._inflight.add(p),p.finally(()=>this.transactor._inflight.delete(p))}async _runLex(chain,i){if(this.ended)return;if(i>=chain.length)return this.advance();let ctx=new Dispatcher(this.origin,this.transactor,this.parent);try{let res=await chain[i].apply(null,[...this.args,ctx]);if(res===PASS)return this._runLex(chain,i+1);this.answer("Ok",res)}catch(error){this.answer("Error",error)}}answer(suffix,value){this.finish(`${this.name}${suffix}`,[value])}amend(opts,from){opts?.args!==void 0&&(this.args=opts.args),opts?.route!==void 0&&(this.route=opts.route,this.legIndex=0,this.dynAt=from??this.dynAt)}exhaust(reason){if(this.ended)return;let{name,args}=this,comp=this.transactor.comps.getCompFor(this.origin.toTransactionPath().lookup(this.transactor.state.val)),declares=n=>comp?.receive?.[n]!==void 0;declares(`${name}Unhandled`)?this.finish(`${name}Unhandled`,args):declares(`${name}Error`)?this.finish(`${name}Error`,[reason]):(declares(`${name}Ok`)&&console.warn(`intent "${name}" was not answered (${reason}) and this component declares only "${name}Ok" - add "${name}Unhandled" or "${name}Error" to handle it`),this.finish(null,null))}finish(name,args){if(this.ended)return;if(this.ended=!0,name===null)return this.release?.();let path=this.answerPath??this.origin,t=new SendEvent(path,this.transactor,name,args,this.parent);t._isAnswer=!0,this.transactor.pushTransaction(t),this.release&&t.completion.whenSubtreeSettled().then(this.release)}},Completion=class{constructor(){this.val=void 0,this.selfSettled=!1,this.subtreeSettled=!1,this.pending=1,this._selfResolve=null,this._selfPromise=null,this._subtreeResolve=null,this._subtreePromise=null,this._selfReleased=!1}whenSettled(){return this.selfSettled?Promise.resolve(this.val):(this._selfPromise??=new Promise(res=>{this._selfResolve=res}),this._selfPromise)}whenSubtreeSettled(){return this.subtreeSettled?Promise.resolve(this.val):(this._subtreePromise??=new Promise(res=>{this._subtreeResolve=res}),this._subtreePromise)}markSelfSettled(val){this.selfSettled||(this.selfSettled=!0,this.val=val,this._selfResolve?.(val))}ensureSelfSettled(){this.selfSettled||this.markSelfSettled(this.val)}track(){this.pending++;let done=!1;return()=>{done||(done=!0,this._release())}}releaseSelf(){this._selfReleased||(this._selfReleased=!0,this._release())}_release(){--this.pending===0&&(this.subtreeSettled=!0,this._subtreeResolve?.(this.val))}},Dispatcher=class{constructor(path,transactor,parentTransaction,root=transactor.state.val){this.path=path,this.transactor=transactor,this.parent=parentTransaction,this.root=root}walkPath(callback){let comps=this.transactor.comps,chain=this.path.toTransactionPath().resolveChain(this.root);for(let i=chain.length-1;i>=0;i--){let comp=comps.getCompFor(chain[i]);if(comp&&callback(comp,chain[i])===!1)return}}get at(){return new PathChanges(this)}_stack(){return this._stackMemo??=this.path.toTransactionPath().buildStack(Stack.root(this.transactor.comps,this.root,this.parent)),this._stackMemo}lookup(name,opts){return routeLookup(opts?.route??DEFAULT_ROUTE,()=>this._lookupLex(name),()=>this._stack()?.lookupDynamic(name)??null)}_lookupLex(name){let Comp=null;return this.walkPath(c=>(Comp=c,!1)),Comp?.scope?.lookupComponent(name)??null}lookupType(name,opts){let route=opts?.route??DEFAULT_ROUTE,v=this.lookup(name,{route});return v==null?(this.transactor.refuse("TYPE_NOT_FOUND",{name,route}),null):v?.[COMPONENT]==null?(this.transactor.refuse("TYPE_NOT_COMPONENT",{name,got:typeof v}),null):v}send(name,args){return this.sendAtPath(this.path,name,args)}sendAtPath(path,name,args){return this.transactor.pushSend(path,name,args,this.parent,this.path)}intent(name,args,opts){return this.intentAtPath(this.path,name,args,opts)}intentAtPath(path,name,args,opts){return this.transactor.pushIntent(path,name,args,opts,this.parent)}},EventContext=class extends Dispatcher{get name(){return this.parent?.name??null}get targetPath(){return this.parent.targetPath}reply(value){return this.parent.walk===void 0?warnNotIntent("reply"):this.parent.walk.answer("Ok",value)}fail(error){return this.parent.walk===void 0?warnNotIntent("fail"):this.parent.walk.answer("Error",error)}sendReply(name,args){let origin=this.parent?.origin??null;return origin==null?(this.transactor.refuse("NO_SENDER",{name}),null):this.sendAtPath(origin,name,args)}stop(){return this.parent.stop()}forward(opts){return this.parent.forward(opts)}};function warnNotIntent(verb){console.warn(`ctx.${verb}() is only meaningful in an "intent" handler - ignored`)}var PathChanges=class extends PathBuilder{constructor(dispatcher){super(),this.dispatcher=dispatcher}send(name,args){return this.dispatcher.sendAtPath(this.buildPath(),name,args)}intent(name,args,opts){return this.dispatcher.intentAtPath(this.buildPath(),name,args,opts)}buildPath(){return this.dispatcher.path.concat(this.pathChanges)}};function rootDispatcher(transactor){return new Dispatcher(new Path([]),transactor,null)}var ModuleInfo=class{constructor({path=null,present=new Set,counts={},warnings=[]}){this.path=path,this.present=present,this.counts=counts,this.warnings=warnings}},ComponentSummary=class{constructor({name,views,fields}){this.name=name,this.views=views,this.fields=fields}},ComponentList=class{constructor({items,total=null,truncated=!1}){this.items=items,this.total=total??items.length,this.truncated=truncated}},ExampleIndex=class{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}},ComponentDocs=class{constructor({items}){this.items=items}},LintFinding=class{constructor({id,level,info,context={},suggestion=null}){this.id=id,this.level=level,this.info=info,this.context=context,this.suggestion=suggestion}},LintComponentResult=class{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}},LintReport=class{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)}},RenderedExample=class{constructor({title,description=null,componentName,view,html:html2,error=null}){this.title=title,this.description=description,this.componentName=componentName,this.view=view,this.html=html2,this.error=error}},RenderedSection=class{constructor({title,description=null,items}){this.title=title,this.description=description,this.items=items}},RenderBatch=class{constructor({sections}){this.sections=sections}get hasErrors(){return this.sections.some(s=>s.items.some(i=>i.error!==null))}},TestResult=class{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}},DescribeResult=class{constructor({title,componentName=null,children=[]}){this.title=title,this.componentName=componentName,this.children=children}},ModuleTestReport=class{constructor({path=null,suites=[],counts={pass:0,fail:0,skip:0,total:0}}){this.path=path,this.suites=suites,this.counts=counts}},TestReport=class{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)}};var Describe=class{constructor({title,componentName=null,parent=null}){this.title=title,this.componentName=componentName,this.parent=parent,this.children=[]}},Test=class{constructor({title,fn,componentName=null,parent=null}){this.title=title,this.fn=fn,this.componentName=componentName,this.parent=parent}},ModuleTests=class{constructor({path=null,suites=[]}={}){this.path=path,this.suites=suites}};function isComponentObject(x){return x===null?!1:typeof x=="function"?x[COMPONENT]!=null: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===arg)return c.name}return null}function titleFromArg(arg){return typeof arg=="string"?arg:isComponentObject(arg)?arg.name:typeof arg=="function"?arg.name||"(anonymous)":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 new Error(`describe() expects 2 or 3 arguments, got ${args.length}`);if(typeof fn!="function")throw new Error(`describe(${JSON.stringify(titleFromArg(head))}): final argument must be a function`);let componentName=null;if(typeof head!="string"&&(componentName=resolveComponentName(head,components)),componentName===null&&options&&options.component!=null&&(componentName=resolveComponentName(options.component,components)),componentName===null){let parent2=stack.length?stack[stack.length-1]:null;parent2&&(componentName=parent2.componentName)}let parent=stack.length?stack[stack.length-1]:null,node=new Describe({title:titleFromArg(head),componentName,parent});parent?parent.children.push(node):moduleTests.suites.push(node),stack.push(node);try{fn()}finally{stack.pop()}}function test3(title,fn){if(typeof title!="string")throw new Error("test(title, fn): title must be a string");if(typeof fn!="function")throw new Error(`test(${JSON.stringify(title)}): fn must be a function`);let parent=stack.length?stack[stack.length-1]:null;if(!parent)throw new 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:test3,moduleTests}}function buildPath(node){let parts=[],cur=node;for(;cur;)parts.unshift(cur.title),cur=cur.parent;return parts.join(" > ")}function captureError(e){let out={message:e.message,stack:e.stack};return"expected"in e&&(out.expected=e.expected),"actual"in e&&(out.actual=e.actual),out}function buildStack({components=[],macros=null,intentHandlers=null}={}){let stack=new ComponentStack;return stack.registerComponents(components),macros&&stack.registerMacros(macros),intentHandlers&&stack.registerIntentHandlers(intentHandlers),stack}async function driveStack(stack,value,phase,opts={}){let transactor=new Transactor(stack.comps,value);return opts.onMessage&&transactor.state.onChange(({val,old,info})=>{let t=info?.transaction;opts.onMessage({kind:t?.handlerProp??"receive",name:t?.name,args:t?.args,path:t?.path},old,val)}),dispatchPhase(rootDispatcher(transactor),new Path([]),phase,value),await transactor.settle(),transactor.state.val}async function drive(cfg,value,phase,opts={}){return driveStack(buildStack(cfg),value,phase,opts)}async function runTests({getTests,components=[],path=null,expect:expect2,name=null,grep=null,bail=!1,intentHandlers=null,macros=null}={}){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 new Error("runTests: expect must be provided (e.g. chai's expect)");let{describe,test:test3,moduleTests}=makeCollector({path,components}),_stack=null,getStack=()=>_stack??=buildStack({components,macros,intentHandlers});await getTests({describe,test:test3,expect:expect2,drive:(value,phase,opts={})=>driveStack(getStack(),value,phase,opts)});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){return counts.fail++,bail&&(bailed=!0),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);r!==null&&childResults.push(r)}return childResults.length===0?null:new DescribeResult({title:node.title,componentName:node.componentName,children:childResults})}let suiteResults=[];for(let suite of moduleTests.suites){let r=await visit(suite);r!==null&&suiteResults.push(r)}return new TestReport({modules:[new ModuleTestReport({path,suites:suiteResults,counts})]})}var PASS2="color: #0a0; font-weight: bold",FAIL="color: #c00; font-weight: bold",SKIP="color: #888",DIM="color: #888",RESET="color: inherit; font-weight: normal";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)`;node.status==="pass"?console.log(`%c✓%c ${node.title}%c${dur}`,PASS2,RESET,DIM):node.status==="skip"?console.log(`%c○ ${node.title}%c (skipped)`,SKIP,RESET):(console.group(`%c✗%c ${node.title}%c${dur}`,FAIL,RESET,DIM),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)),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)`;c.fail>0?console.error(`%c${summary}`,FAIL):c.total===0?console.log(`%c${summary}`,DIM):console.log(`%c${summary}`,PASS2),console.groupEnd()}return report}var UNSUPPORTED_EXPR_LABEL={ternary:"ternary expression",comparison:"comparison",logical:"logical expression","call-with-args":"method call with arguments","field-path":"dotted field path"};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 parameter '^${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}`)}info.handlerName&&parts.push(`handler '${info.handlerName}'${info.argIndex!==void 0?` arg ${info.argIndex}`:""}`);let t=tagDisplay(info.tag);return t&&t!=="x"&&parts.push(`on <${t}>`),parts.length?` (${parts.join(", ")})`:""}function fmtEventSuffix(info){return info?.originAttr?` in ${info.originAttr}`:info?.eventName?` in @on.${info.eventName}`:""}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"HANDLER_NAME_COLLISION":return`${info.problem} — ${info.fix}`;case"RECEIVE_HANDLER_NOT_IMPLEMENTED":return`Receive handler '${info.name}' is not implemented${fmtEventSuffix(info)}`;case"EVENT_HANDLER_METHOD_NOT_ALLOWED":return`Event handler '$${info.name}' is a method reference — move it to receive and use '${info.name}'`;case"FIELD_METHOD_NAME_COLLISION":return`Field '${info.name}' shadows a method with the same name — rename either the field or method`;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_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 binding '*${info.name}' is not defined${fmtOriginSuffix(info)}`;case"DYN_ALIAS_NOT_REFERENCED":return`Lookup '${info.name}' is defined but never used — remove it or reference it as '*${info.name}' in a view`;case"PROVIDE_NOT_ADDRESSABLE":return`Provide '${info.name}' value '${info.value}' must be a field ('.f') or seq-access ('.s[.k]') — a method/constant can't be a render target`;case"LOOKUP_BAD_SHAPE":return`Lookup '${info.name}' has an invalid shape: ${info.problem}`;case"LOOKUP_NO_PROVIDER":return info.hasDefault?`Lookup '${info.name}' is provided by no component in scope, so it always resolves to its default`:`Lookup '${info.name}' is provided by no component in scope — add a 'provide' for it, or give this lookup a default`;case"PROVIDE_TYPE_BAD_SHAPE":return`Provide '${info.name}' starts uppercase, so it publishes a component type — its value must be 'self', not '${info.value}'`;case"PROVIDE_NAME_COLLISION":return`Provide '${info.name}' is also provided by '${info.other}' in the same scope — one name, one provider, so a lookup can find it`;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"X_OP_IGNORES_CHILDREN":return`<x ${info.op}> has child content, but the '${info.op}' op ignores its children — they are silently dropped when the template is parsed; remove them${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"MAYBE_ADD_AT_PREFIX":return`'${info.name}' on <${(info.tag??"").toLowerCase()}> is a plain attribute, but '@${info.name}' is a directive — add the leading '@'`;case"BAD_VALUE":return`${badValueMessage(info)}${fmtTagSuffix(info)}`;case"UNSUPPORTED_EXPR_SYNTAX":return`${unsupportedExprMessage(info)}${fmtTagSuffix(info)}`;case"BINDING_MEMBER_TOO_DEEP":return`Binding member read ${JSON.stringify(info.value)} goes more than one level deep — only one member is allowed (like '@value.title')${fmtTagSuffix(info)}`;case"SUGGEST_BINDING_MEMBER":{let reads=(info.members??[]).map(({member})=>`'@value.${member}'`).join(", ");return`Enrich handler '${info.name}' only copies members of the loop value — read them directly${reads?` (${reads})`:""} and remove the '@enrich-with'`}case"REDUNDANT_TEMPLATE_STRING":return`Redundant string template — '{${info.simpler}}' should be just '${info.simpler}'${fmtOriginSuffix(info)}`;case"PLACEHOLDERLESS_TEMPLATE_STRING":return`String template has no dynamic parts — use the string literal ${info.literal} instead${fmtOriginSuffix(info)}`;case"CONSTANT_CONDITION":return`Condition is the constant literal ${info.literal} — it never changes; reference a field ('.name') or a method ('$name') instead${fmtOriginSuffix(info)}`;case"UNKNOWN_COMPONENT_SPEC_KEY":return`Unknown component spec key '${info.key}' — value will be ignored at runtime`;case"COMP_FIELD_BAD_SHAPE":return info.kind==="args-not-object"?`Field '${info.fieldName}': in { component, args }, 'args' must be a plain object, got ${info.got}`:`Field '${info.fieldName}': in { component, args }, 'component' must be the component name as a string, got ${info.gotName?`the ${info.gotName} class`:info.got}`;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"ASYNC_HANDLER":return`Handler '${info.name}' in '${info.channel}' is an async function — handlers must be synchronous and return the updated state (an async function returns a Promise the framework won't await)`;case"TOP_LEVEL_AT_RULE_IN_SCOPED_STYLE":return`'@${info.atRule}' is a top-level-only at-rule, but '${info.key}' is wrapped in a component-scoped selector ([data-cid=…]{…}) where it is invalid and silently dropped — move it to 'globalStyle'${fmtLocationSuffix(info)}`;case"GLOBAL_SELECTOR_IN_SCOPED_STYLE":return`Selector '${info.selector}' targets the document root, but '${info.key}' is wrapped in a component-scoped selector, so it becomes a descendant selector that never matches — move it to 'globalStyle'${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;return loc?` 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}`}}var _evs="dragstart dragover dragend touchstart touchmove touchend touchcancel".split(" "),App=class{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=>{this._transactNextBatchId===null&&this._scheduleNextTransactionBatchExecution()},this._compiled=!1,this._renderOpts={document:rootNode.ownerDocument},this._renderState=null,this.rootViewName=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.fromNodeAndEventName(e.target,type3,root,maxDepth,comps,!isDrag);if(isDrag&&this._handleDragEvent(e,type3,path),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)e.preventDefault(),fire("dragover",hitTest(rootNode,clientX,clientY));else{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)}return}(type3==="touchend"||type3==="touchcancel")&&(_touch.active&&(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);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,value=path.compact().toTransactionPath().lookup(rootValue),dragType=e.target.dataset.dragtype??"?",stack=path.toTransactionPath().buildStack(this.makeStack(rootValue));this.dragInfo=new DragInfo(stack,value,dragType,e.target)}else type3==="drop"?(e.preventDefault(),this._cleanDragOverAttrs()):(this.dragInfo!==null&&(delete this.dragInfo.node.dataset.dragging,this.dragInfo=null),this._cleanDragOverAttrs())}makeStack(rootValue){return Stack.root(this.comps,rootValue)}_cleanDragOverAttrs(){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,this.rootViewName),rootNode,_renderOpts,_renderState);return this._renderState=newState,newState.dom}onChange(callback){this.transactor.state.onChange(callback)}observe(callback){return this.transactor.observe(callback)}compile(){for(let Comp of this.comps.byId.values()){let meta=Comp[COMPONENT];meta.compile(this.ParseContext);for(let key in meta.views)for(let name of meta.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){this._compiled||this.compile(),this.subscribeToEvents(this._eventNames),this.onChange(info=>{info.val!==info.old&&this.render()}),this.recompileStyles(opts),opts?.noCache?this.renderer.setNullCache():this.startCacheEvictionInterval(),this.render()}stop(){this.stopCacheEvictionInterval();for(let name of this._eventNames)this.rootNode.removeEventListener(name,this,listenerOpts(name))}sendAtRoot(name,args){this.transactor.pushSend(new Path([]),name,args)}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;for(;t.hasPendingTransactions&&Date.now()-startTs<maxRunTimeMs;)t.transactNext();t.hasPendingTransactions&&this._scheduleNextTransactionBatchExecution()}_scheduleNextTransactionBatchExecution(){this._transactNextBatchId=setTimeout(()=>this._transactNextBatch(),0)}startCacheEvictionInterval(intervalMs=3e4){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}`);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;for(;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;for(;count-- >0&&node!==rootNode;){if(node.dataset?.droptarget!==void 0)return node;node=node.parentNode}return null}var DragInfo=class{constructor(stack,val,type3,node){this.stack=stack,this.val=val,this.type=type3,this.node=node}lookupBind(name){return this.stack.lookupBind(name)}};var isWeakKey=k=>k!==null&&(typeof k=="object"||typeof k=="function"),NullDomCache=class{get(_keys,_cacheKey){}set(_keys,_cacheKey,_v){}evict(){return{hit:0,miss:0,badKey:0}}},WeakMapDomCache=class{constructor(){this.hit=this.miss=this.badKey=0,this.keysByLen=new Map}_returnValue(r){return r===void 0?this.miss+=1:this.hit+=1,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);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(!isWeakKey(key)){this.badKey+=1;return}next=new WeakMap,cur.set(key,next)}cur=next}let lastKey=keys[len-1],leaf=cur.get(lastKey);leaf?leaf[cacheKey]=v:isWeakKey(lastKey)?cur.set(lastKey,{[cacheKey]:v}):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"],Renderer=class{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);return comp===null?null: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);let cachedNode=this.cache.get(cachePath,cacheKey);if(cachedNode)return cachedNode;let view=viewName?comp.getView(viewName):stack.lookupBestView(comp.views,"main"),body=this.renderView(view,stack);if(body==null)return null;let meta=this._renderMetadata({$:"Comp",nid:node?.nodeId??null,cid:comp.id,vid:view.name}),dom=new VFragment([meta,body]);return this.cache.set(cachePath,cacheKey,dom),dom}pushEachEntry(r,nid,attrName,key,dom){r.push(this._renderMetadata({$:"Each",nid,[attrName]:key}),dom)}renderEachWhen(stack,iterInfo,view,nid){let{seq,filter,loopWith,enricher}=iterInfo.eval(stack),r=[],it=stack.it,renderOne=(key,value,attrName,binds)=>{let cachePath=enricher?[view,it,value]:[view,value],cacheKey=`${stack.viewsId??""}${nid}${key}`,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));dom!=null&&this.pushEachEntry(r,nid,attrName,key,dom),this.cache.set(cachePath,cacheKey,dom)}};return walkLoopBindings({seq,it,filter,loopWith,enricher,ctx:makeLoopCtx(stack,filter)},renderOne),r}renderView(view,stack){let n=stack.binds[1];for(;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)}§`)}renderScopeMeta(nid,dom){return new VFragment([this._renderMetadata({$:"Scope",nid}),dom])}};var css=String.raw,html=String.raw,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){return app.ParseContext=Ctx,app.compile(),await compileClasses(Array.from(collectAppClassesInSet(app)))}function resolveAlter(Comp,name){if(name==null)return null;let fn=Comp.alter?.[name];if(typeof fn!="function")throw new Error(`alter handler '${name}' not found on component '${Comp.name}'`);return fn}function collectIterBindings(Comp,compInstance,seq,opts={}){let whenFn=resolveAlter(Comp,opts.when)??filterAlwaysTrue,loopWithFn=resolveAlter(Comp,opts.loopWith)??nullLoopWith,enrichFn=resolveAlter(Comp,opts.enrichWith),scopeEnrichFn=resolveAlter(Comp,opts.scopeEnrich),it=compInstance,scope=scopeEnrichFn?scopeEnrichFn.call(it)??{}:opts.scope??{},ctx={lookup:name=>scope[name],filter:(key,value,iterData)=>whenFn.call(it,key,value,iterData)},out=[];return walkLoopBindings({seq,it,filter:whenFn,loopWith:loopWithFn,enricher:enrichFn,ctx},(_key,_value,_attrName,binds)=>out.push(binds)),out}function getSignature(name,fn){let m=fn.toString().match(/^(?:\w+|function\s*\w*)\s*\(([^)]*)\)/),params=m?m[1].trim():"";return`${name}(${params})`}function serializeDefault(v){return v==null?v:v instanceof Map?Object.fromEntries(v):v instanceof Set?[...v]:v}function getComponentDoc(comp){let{fields,name,methods}=comp,userMethods=Object.keys(methods).map(k=>({name:k,sig:getSignature(k,methods[k])})),sigs=bucket=>Object.keys(bucket??{}).map(k=>({name:k,sig:getSignature(k,bucket[k])})),receiveHandlers=sigs(comp.receive),intentHandlers=sigs(comp.intent),fieldDocs=[];for(let fieldName in fields){let field=fields[fieldName];fieldDocs.push({name:fieldName,type:field.type,default:serializeDefault(field.defaultValue),methods:[]})}return{name,methods:userMethods,receive:receiveHandlers,intent:intentHandlers,fields:fieldDocs}}function docComponents(normalized,{name=null}={}){let comps=normalized.components,picked=name===null?comps:comps.filter(c=>c.name===name);return new ComponentDocs({items:picked.map(comp=>getComponentDoc(comp))})}async function test2(opts={}){let report=await runTests({expect,...opts});return reportTestReportToConsole(report),report}function shadowCheckComponent(Comp){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);return Object.defineProperty(shadowComp,"views",{value:shadowViews,writable:!0,enumerable:!0,configurable:!0}),checkComponent(shadowComp).reports}function check(app){let counts={error:0,warn:0,hint:0};for(let Comp of app.comps.byId.values()){let reports=shadowCheckComponent(Comp);if(reports.length!==0){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}`;r.level==="error"?console.error(line):r.level==="warn"?console.warn(line):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}var LintClassCollectorCtx=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,frame={macroName,macroVars,macroSlots},v=new _LintClassCollectorCtx(document2,Text,Comment,nodes,events2,macroNodes,frame,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{ALT_HANDLER_NOT_DEFINED,ALT_HANDLER_NOT_REFERENCED,ASYNC_HANDLER,BAD_VALUE,BINDING_MEMBER_TOO_DEEP,COMPONENT,COMP_FIELD_BAD_SHAPE,CONSTANT_CONDITION,ComponentDocs,ComponentList,ComponentSummary,DUPLICATE_ATTR_DEFINITION,DYN_ALIAS_NOT_REFERENCED,DYN_VAL_NOT_DEFINED,Describe,DescribeResult,EVENT_HANDLER_METHOD_NOT_ALLOWED,ExampleIndex,FIELD_CLASS,FIELD_METHOD_NAME_COLLISION,FIELD_VAL_IS_METHOD,FIELD_VAL_NOT_DEFINED,GLOBAL_SELECTOR_IN_SCOPED_STYLE,HANDLER_NAME_COLLISION,IF_NO_BRANCH_SET,LOOKUP_BAD_SHAPE,LOOKUP_NO_PROVIDER,LintClassCollectorCtx,LintComponentResult,LintContext,LintFinding,LintParseContext,LintReport,MAYBE_ADD_AT_PREFIX,MAYBE_DROP_AT_PREFIX,METHOD_VAL_IS_FIELD,METHOD_VAL_NOT_DEFINED,ModuleInfo,ModuleTestReport,ModuleTests,PASS,PLACEHOLDERLESS_TEMPLATE_STRING,PROVIDE_NAME_COLLISION,PROVIDE_NOT_ADDRESSABLE,PROVIDE_TYPE_BAD_SHAPE,ParseContext,RECEIVE_HANDLER_NOT_IMPLEMENTED,REDUNDANT_TEMPLATE_STRING,RENDER_IT_OUTSIDE_OF_LOOP,RenderBatch,RenderedExample,RenderedSection,SEQ_INFO,SUGGEST_BINDING_MEMBER,TOP_LEVEL_AT_RULE_IN_SCOPED_STYLE,Test,TestReport,TestResult,UNKNOWN_COMPONENT_NAME,UNKNOWN_COMPONENT_SPEC_KEY,UNKNOWN_DIRECTIVE,UNKNOWN_EVENT_MODIFIER,UNKNOWN_MACRO_ARG,UNKNOWN_X_ATTR,UNKNOWN_X_OP,UNSUPPORTED_EXPR_SYNTAX,X_OP_IGNORES_CHILDREN,check,checkComponent,collectIterBindings,compileClassesToStyle,compileClassesToStyleText,component,css,dispatchPhase,docComponents,drive,expect,html,injectCss,lintIdToMessage,macro,makeCollector,phaseOps,reportTestReportToConsole,resolveArgs,rootDispatcher,runTests,shadowCheckComponent,suggestionToMessage,test2 as test,tutuca};
|