@konoui/mjimage 0.4.0 → 0.5.0
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/index.cjs +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +6 -6
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -5,12 +5,12 @@
|
|
|
5
5
|
`+c+" | "+Ae("",i.column-1," ")+Ae("",u,"^")}else t+=`
|
|
6
6
|
at `+o}return t};we.buildMessage=function(n,t){var e={literal:function(l){return'"'+i(l.text)+'"'},class:function(l){var h=l.parts.map(function(u){return Array.isArray(u)?r(u[0])+"-"+r(u[1]):r(u)});return"["+(l.inverted?"^":"")+h.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(l){return l.description}};function s(l){return l.charCodeAt(0).toString(16).toUpperCase()}function i(l){return l.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(h){return"\\x0"+s(h)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(h){return"\\x"+s(h)})}function r(l){return l.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(h){return"\\x0"+s(h)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(h){return"\\x"+s(h)})}function o(l){return e[l.type](l)}function a(l){var h=l.map(o),u,d;if(h.sort(),h.length>0){for(u=1,d=1;u<h.length;u++)h[u-1]!==h[u]&&(h[d]=h[u],d++);h.length=d}switch(h.length){case 1:return h[0];case 2:return h[0]+" or "+h[1];default:return h.slice(0,-1).join(", ")+", or "+h[h.length-1]}}function c(l){return l?'"'+i(l)+'"':"end of input"}return"Expected "+a(n)+" but "+c(t)+" found."};const Ln=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",ni=Ln+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",si="["+Ln+"]["+ni+"]*",ii=new RegExp("^"+si+"$");function jn(n,t){const e=[];let s=t.exec(n);for(;s;){const i=[];i.startIndex=t.lastIndex-s[0].length;const r=s.length;for(let o=0;o<r;o++)i.push(s[o]);e.push(i),s=t.exec(n)}return e}const Qe=function(n){const t=ii.exec(n);return!(t===null||typeof t>"u")};function ri(n){return typeof n<"u"}const oi={allowBooleanAttributes:!1,unpairedTags:[]};function ai(n,t){t=Object.assign({},oi,t);const e=[];let s=!1,i=!1;n[0]==="\uFEFF"&&(n=n.substr(1));for(let r=0;r<n.length;r++)if(n[r]==="<"&&n[r+1]==="?"){if(r+=2,r=Sn(n,r),r.err)return r}else if(n[r]==="<"){let o=r;if(r++,n[r]==="!"){r=Nn(n,r);continue}else{let a=!1;n[r]==="/"&&(a=!0,r++);let c="";for(;r<n.length&&n[r]!==">"&&n[r]!==" "&&n[r]!==" "&&n[r]!==`
|
|
7
7
|
`&&n[r]!=="\r";r++)c+=n[r];if(c=c.trim(),c[c.length-1]==="/"&&(c=c.substring(0,c.length-1),r--),!gi(c)){let u;return c.trim().length===0?u="Invalid space after '<'.":u="Tag '"+c+"' is an invalid name.",k("InvalidTag",u,P(n,r))}const l=hi(n,r);if(l===!1)return k("InvalidAttr","Attributes for '"+c+"' have open quote.",P(n,r));let h=l.value;if(r=l.index,h[h.length-1]==="/"){const u=r-h.length;h=h.substring(0,h.length-1);const d=In(h,t);if(d===!0)s=!0;else return k(d.err.code,d.err.msg,P(n,u+d.err.line))}else if(a)if(l.tagClosed){if(h.trim().length>0)return k("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",P(n,o));if(e.length===0)return k("InvalidTag","Closing tag '"+c+"' has not been opened.",P(n,o));{const u=e.pop();if(c!==u.tagName){let d=P(n,u.tagStartPos);return k("InvalidTag","Expected closing tag '"+u.tagName+"' (opened in line "+d.line+", col "+d.col+") instead of closing tag '"+c+"'.",P(n,o))}e.length==0&&(i=!0)}}else return k("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",P(n,r));else{const u=In(h,t);if(u!==!0)return k(u.err.code,u.err.msg,P(n,r-h.length+u.err.line));if(i===!0)return k("InvalidXml","Multiple possible root nodes found.",P(n,r));t.unpairedTags.indexOf(c)!==-1||e.push({tagName:c,tagStartPos:o}),s=!0}for(r++;r<n.length;r++)if(n[r]==="<")if(n[r+1]==="!"){r++,r=Nn(n,r);continue}else if(n[r+1]==="?"){if(r=Sn(n,++r),r.err)return r}else break;else if(n[r]==="&"){const u=fi(n,r);if(u==-1)return k("InvalidChar","char '&' is not expected.",P(n,r));r=u}else if(i===!0&&!An(n[r]))return k("InvalidXml","Extra text at the end",P(n,r));n[r]==="<"&&r--}}else{if(An(n[r]))continue;return k("InvalidChar","char '"+n[r]+"' is not expected.",P(n,r))}if(s){if(e.length==1)return k("InvalidTag","Unclosed tag '"+e[0].tagName+"'.",P(n,e[0].tagStartPos));if(e.length>0)return k("InvalidXml","Invalid '"+JSON.stringify(e.map(r=>r.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return k("InvalidXml","Start tag expected.",1);return!0}function An(n){return n===" "||n===" "||n===`
|
|
8
|
-
`||n==="\r"}function Sn(n,t){const e=t;for(;t<n.length;t++)if(n[t]=="?"||n[t]==" "){const s=n.substr(e,t-e);if(t>5&&s==="xml")return k("InvalidXml","XML declaration allowed only at the start of the document.",P(n,t));if(n[t]=="?"&&n[t+1]==">"){t++;break}else continue}return t}function Nn(n,t){if(n.length>t+5&&n[t+1]==="-"&&n[t+2]==="-"){for(t+=3;t<n.length;t++)if(n[t]==="-"&&n[t+1]==="-"&&n[t+2]===">"){t+=2;break}}else if(n.length>t+8&&n[t+1]==="D"&&n[t+2]==="O"&&n[t+3]==="C"&&n[t+4]==="T"&&n[t+5]==="Y"&&n[t+6]==="P"&&n[t+7]==="E"){let e=1;for(t+=8;t<n.length;t++)if(n[t]==="<")e++;else if(n[t]===">"&&(e--,e===0))break}else if(n.length>t+9&&n[t+1]==="["&&n[t+2]==="C"&&n[t+3]==="D"&&n[t+4]==="A"&&n[t+5]==="T"&&n[t+6]==="A"&&n[t+7]==="["){for(t+=8;t<n.length;t++)if(n[t]==="]"&&n[t+1]==="]"&&n[t+2]===">"){t+=2;break}}return t}const ci='"',li="'";function hi(n,t){let e="",s="",i=!1;for(;t<n.length;t++){if(n[t]===ci||n[t]===li)s===""?s=n[t]:s!==n[t]||(s="");else if(n[t]===">"&&s===""){i=!0;break}e+=n[t]}return s!==""?!1:{value:e,index:t,tagClosed:i}}const ui=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function In(n,t){const e=jn(n,ui),s={};for(let i=0;i<e.length;i++){if(e[i][1].length===0)return k("InvalidAttr","Attribute '"+e[i][2]+"' has no space in starting.",zt(e[i]));if(e[i][3]!==void 0&&e[i][4]===void 0)return k("InvalidAttr","Attribute '"+e[i][2]+"' is without value.",zt(e[i]));if(e[i][3]===void 0&&!t.allowBooleanAttributes)return k("InvalidAttr","boolean attribute '"+e[i][2]+"' is not allowed.",zt(e[i]));const r=e[i][2];if(!pi(r))return k("InvalidAttr","Attribute '"+r+"' is an invalid name.",zt(e[i]));if(!s.hasOwnProperty(r))s[r]=1;else return k("InvalidAttr","Attribute '"+r+"' is repeated.",zt(e[i]))}return!0}function di(n,t){let e=/\d/;for(n[t]==="x"&&(t++,e=/[\da-fA-F]/);t<n.length;t++){if(n[t]===";")return t;if(!n[t].match(e))break}return-1}function fi(n,t){if(t++,n[t]===";")return-1;if(n[t]==="#")return t++,di(n,t);let e=0;for(;t<n.length;t++,e++)if(!(n[t].match(/\w/)&&e<20)){if(n[t]===";")break;return-1}return t}function k(n,t,e){return{err:{code:n,msg:t,line:e.line||e,col:e.col}}}function pi(n){return Qe(n)}function gi(n){return Qe(n)}function P(n,t){const e=n.substring(0,t).split(/\r?\n/);return{line:e.length,col:e[e.length-1].length+1}}function zt(n){return n.startIndex+n[1].length}const yi={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,t){return t},attributeValueProcessor:function(n,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,t,e){return n},captureMetaData:!1},mi=function(n){return Object.assign({},yi,n)};let ce;typeof Symbol!="function"?ce="@@xmlMetadata":ce=Symbol("XML Node Metadata");class pt{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),e!==void 0&&(this.child[this.child.length-1][ce]={startIndex:e})}static getMetaDataSymbol(){return ce}}function wi(n,t){const e={};if(n[t+3]==="O"&&n[t+4]==="C"&&n[t+5]==="T"&&n[t+6]==="Y"&&n[t+7]==="P"&&n[t+8]==="E"){t=t+9;let s=1,i=!1,r=!1,o="";for(;t<n.length;t++)if(n[t]==="<"&&!r){if(i&>(n,"!ENTITY",t)){t+=7;let a,c;[a,c,t]=bi(n,t+1),c.indexOf("&")===-1&&(e[a]={regx:RegExp(`&${a};`,"g"),val:c})}else if(i&>(n,"!ELEMENT",t)){t+=8;const{index:a}=Ei(n,t+1);t=a}else if(i&>(n,"!ATTLIST",t))t+=8;else if(i&>(n,"!NOTATION",t)){t+=9;const{index:a}=_i(n,t+1);t=a}else if(gt(n,"!--",t))r=!0;else throw new Error("Invalid DOCTYPE");s++,o=""}else if(n[t]===">"){if(r?n[t-1]==="-"&&n[t-2]==="-"&&(r=!1,s--):s--,s===0)break}else n[t]==="["?i=!0:o+=n[t];if(s!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:e,i:t}}const it=(n,t)=>{for(;t<n.length&&/\s/.test(n[t]);)t++;return t};function bi(n,t){t=it(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t])&&n[t]!=='"'&&n[t]!=="'";)e+=n[t],t++;if(tn(e),t=it(n,t),n.substring(t,t+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(n[t]==="%")throw new Error("Parameter entities are not supported");let s="";return[t,s]=re(n,t,"entity"),t--,[e,s,t]}function _i(n,t){t=it(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;tn(e),t=it(n,t);const s=n.substring(t,t+6).toUpperCase();if(s!=="SYSTEM"&&s!=="PUBLIC")throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);t+=s.length,t=it(n,t);let i=null,r=null;if(s==="PUBLIC")[t,i]=re(n,t,"publicIdentifier"),t=it(n,t),(n[t]==='"'||n[t]==="'")&&([t,r]=re(n,t,"systemIdentifier"));else if(s==="SYSTEM"&&([t,r]=re(n,t,"systemIdentifier"),!r))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:e,publicIdentifier:i,systemIdentifier:r,index:--t}}function re(n,t,e){let s="";const i=n[t];if(i!=='"'&&i!=="'")throw new Error(`Expected quoted string, found "${i}"`);for(t++;t<n.length&&n[t]!==i;)s+=n[t],t++;if(n[t]!==i)throw new Error(`Unterminated ${e} value`);return t++,[t,s]}function Ei(n,t){t=it(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;if(!tn(e))throw new Error(`Invalid element name: "${e}"`);t=it(n,t);let s="";if(n[t]==="E"&>(n,"MPTY",t))t+=6;else if(n[t]==="A"&>(n,"NY",t))t+=4;else if(n[t]==="("){for(t++;t<n.length&&n[t]!==")";)s+=n[t],t++;if(n[t]!==")")throw new Error("Unterminated content model")}else throw new Error(`Invalid Element Expression, found "${n[t]}"`);return{elementName:e,contentModel:s.trim(),index:t}}function gt(n,t,e){for(let s=0;s<t.length;s++)if(t[s]!==n[e+s+1])return!1;return!0}function tn(n){if(Qe(n))return n;throw new Error(`Invalid entity name ${n}`)}const Ai=/^[-+]?0x[a-fA-F0-9]+$/,Si=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Ni={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Ii(n,t={}){if(t=Object.assign({},Ni,t),!n||typeof n!="string")return n;let e=n.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return n;if(n==="0")return 0;if(t.hex&&Ai.test(e))return ki(e,16);if(e.search(/.+[eE].+/)!==-1)return Ti(n,e,t);{const s=Si.exec(e);if(s){const i=s[1]||"",r=s[2];let o=Oi(s[3]);const a=i?n[r.length+1]===".":n[r.length]===".";if(!t.leadingZeros&&(r.length>1||r.length===1&&!a))return n;{const c=Number(e),l=String(c);if(c===0)return c;if(l.search(/[eE]/)!==-1)return t.eNotation?c:n;if(e.indexOf(".")!==-1)return l==="0"||l===o||l===`${i}${o}`?c:n;let h=r?o:e;return r?h===l||i+h===l?c:n:h===l||h===i+l?c:n}}else return n}}const vi=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Ti(n,t,e){if(!e.eNotation)return n;const s=t.match(vi);if(s){let i=s[1]||"";const r=s[3].indexOf("e")===-1?"E":"e",o=s[2],a=i?n[o.length+1]===r:n[o.length]===r;return o.length>1&&a?n:o.length===1&&(s[3].startsWith(`.${r}`)||s[3][0]===r)?Number(t):e.leadingZeros&&!a?(t=(s[1]||"")+s[3],Number(t)):n}else return n}function Oi(n){return n&&n.indexOf(".")!==-1&&(n=n.replace(/0+$/,""),n==="."?n="0":n[0]==="."?n="0"+n:n[n.length-1]==="."&&(n=n.substring(0,n.length-1))),n}function ki(n,t){if(parseInt)return parseInt(n,t);if(Number.parseInt)return Number.parseInt(n,t);if(window&&window.parseInt)return window.parseInt(n,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function Un(n){return typeof n=="function"?n:Array.isArray(n)?t=>{for(const e of n)if(typeof e=="string"&&t===e||e instanceof RegExp&&e.test(t))return!0}:()=>!1}class Ci{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,16))}},this.addExternalEntities=Ri,this.parseXml=Hi,this.parseTextData=xi,this.resolveNameSpace=Mi,this.buildAttributesMap=Pi,this.isItStopNode=Ki,this.replaceEntitiesValue=Bi,this.readStopNodeData=Li,this.saveTextToParentTag=Di,this.addChild=Wi,this.ignoreAttributesFn=Un(this.options.ignoreAttributes)}}function Ri(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];this.lastEntities[s]={regex:new RegExp("&"+s+";","g"),val:n[s]}}}function xi(n,t,e,s,i,r,o){if(n!==void 0&&(this.options.trimValues&&!s&&(n=n.trim()),n.length>0)){o||(n=this.replaceEntitiesValue(n));const a=this.options.tagValueProcessor(t,n,e,i,r);return a==null?n:typeof a!=typeof n||a!==n?a:this.options.trimValues?$e(n,this.options.parseTagValue,this.options.numberParseOptions):n.trim()===n?$e(n,this.options.parseTagValue,this.options.numberParseOptions):n}}function Mi(n){if(this.options.removeNSPrefix){const t=n.split(":"),e=n.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return"";t.length===2&&(n=e+t[1])}return n}const $i=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Pi(n,t,e){if(this.options.ignoreAttributes!==!0&&typeof n=="string"){const s=jn(n,$i),i=s.length,r={};for(let o=0;o<i;o++){const a=this.resolveNameSpace(s[o][1]);if(this.ignoreAttributesFn(a,t))continue;let c=s[o][4],l=this.options.attributeNamePrefix+a;if(a.length)if(this.options.transformAttributeName&&(l=this.options.transformAttributeName(l)),l==="__proto__"&&(l="#__proto__"),c!==void 0){this.options.trimValues&&(c=c.trim()),c=this.replaceEntitiesValue(c);const h=this.options.attributeValueProcessor(a,c,t);h==null?r[l]=c:typeof h!=typeof c||h!==c?r[l]=h:r[l]=$e(c,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(r[l]=!0)}if(!Object.keys(r).length)return;if(this.options.attributesGroupName){const o={};return o[this.options.attributesGroupName]=r,o}return r}}const Hi=function(n){n=n.replace(/\r\n?/g,`
|
|
8
|
+
`||n==="\r"}function Sn(n,t){const e=t;for(;t<n.length;t++)if(n[t]=="?"||n[t]==" "){const s=n.substr(e,t-e);if(t>5&&s==="xml")return k("InvalidXml","XML declaration allowed only at the start of the document.",P(n,t));if(n[t]=="?"&&n[t+1]==">"){t++;break}else continue}return t}function Nn(n,t){if(n.length>t+5&&n[t+1]==="-"&&n[t+2]==="-"){for(t+=3;t<n.length;t++)if(n[t]==="-"&&n[t+1]==="-"&&n[t+2]===">"){t+=2;break}}else if(n.length>t+8&&n[t+1]==="D"&&n[t+2]==="O"&&n[t+3]==="C"&&n[t+4]==="T"&&n[t+5]==="Y"&&n[t+6]==="P"&&n[t+7]==="E"){let e=1;for(t+=8;t<n.length;t++)if(n[t]==="<")e++;else if(n[t]===">"&&(e--,e===0))break}else if(n.length>t+9&&n[t+1]==="["&&n[t+2]==="C"&&n[t+3]==="D"&&n[t+4]==="A"&&n[t+5]==="T"&&n[t+6]==="A"&&n[t+7]==="["){for(t+=8;t<n.length;t++)if(n[t]==="]"&&n[t+1]==="]"&&n[t+2]===">"){t+=2;break}}return t}const ci='"',li="'";function hi(n,t){let e="",s="",i=!1;for(;t<n.length;t++){if(n[t]===ci||n[t]===li)s===""?s=n[t]:s!==n[t]||(s="");else if(n[t]===">"&&s===""){i=!0;break}e+=n[t]}return s!==""?!1:{value:e,index:t,tagClosed:i}}const ui=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function In(n,t){const e=jn(n,ui),s={};for(let i=0;i<e.length;i++){if(e[i][1].length===0)return k("InvalidAttr","Attribute '"+e[i][2]+"' has no space in starting.",zt(e[i]));if(e[i][3]!==void 0&&e[i][4]===void 0)return k("InvalidAttr","Attribute '"+e[i][2]+"' is without value.",zt(e[i]));if(e[i][3]===void 0&&!t.allowBooleanAttributes)return k("InvalidAttr","boolean attribute '"+e[i][2]+"' is not allowed.",zt(e[i]));const r=e[i][2];if(!pi(r))return k("InvalidAttr","Attribute '"+r+"' is an invalid name.",zt(e[i]));if(!s.hasOwnProperty(r))s[r]=1;else return k("InvalidAttr","Attribute '"+r+"' is repeated.",zt(e[i]))}return!0}function di(n,t){let e=/\d/;for(n[t]==="x"&&(t++,e=/[\da-fA-F]/);t<n.length;t++){if(n[t]===";")return t;if(!n[t].match(e))break}return-1}function fi(n,t){if(t++,n[t]===";")return-1;if(n[t]==="#")return t++,di(n,t);let e=0;for(;t<n.length;t++,e++)if(!(n[t].match(/\w/)&&e<20)){if(n[t]===";")break;return-1}return t}function k(n,t,e){return{err:{code:n,msg:t,line:e.line||e,col:e.col}}}function pi(n){return Qe(n)}function gi(n){return Qe(n)}function P(n,t){const e=n.substring(0,t).split(/\r?\n/);return{line:e.length,col:e[e.length-1].length+1}}function zt(n){return n.startIndex+n[1].length}const yi={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,t){return t},attributeValueProcessor:function(n,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,t,e){return n},captureMetaData:!1},mi=function(n){return Object.assign({},yi,n)};let ce;typeof Symbol!="function"?ce="@@xmlMetadata":ce=Symbol("XML Node Metadata");class pt{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),e!==void 0&&(this.child[this.child.length-1][ce]={startIndex:e})}static getMetaDataSymbol(){return ce}}function wi(n,t){const e={};if(n[t+3]==="O"&&n[t+4]==="C"&&n[t+5]==="T"&&n[t+6]==="Y"&&n[t+7]==="P"&&n[t+8]==="E"){t=t+9;let s=1,i=!1,r=!1,o="";for(;t<n.length;t++)if(n[t]==="<"&&!r){if(i&>(n,"!ENTITY",t)){t+=7;let a,c;[a,c,t]=bi(n,t+1),c.indexOf("&")===-1&&(e[a]={regx:RegExp(`&${a};`,"g"),val:c})}else if(i&>(n,"!ELEMENT",t)){t+=8;const{index:a}=Ei(n,t+1);t=a}else if(i&>(n,"!ATTLIST",t))t+=8;else if(i&>(n,"!NOTATION",t)){t+=9;const{index:a}=_i(n,t+1);t=a}else if(gt(n,"!--",t))r=!0;else throw new Error("Invalid DOCTYPE");s++,o=""}else if(n[t]===">"){if(r?n[t-1]==="-"&&n[t-2]==="-"&&(r=!1,s--):s--,s===0)break}else n[t]==="["?i=!0:o+=n[t];if(s!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:e,i:t}}const it=(n,t)=>{for(;t<n.length&&/\s/.test(n[t]);)t++;return t};function bi(n,t){t=it(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t])&&n[t]!=='"'&&n[t]!=="'";)e+=n[t],t++;if(tn(e),t=it(n,t),n.substring(t,t+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(n[t]==="%")throw new Error("Parameter entities are not supported");let s="";return[t,s]=re(n,t,"entity"),t--,[e,s,t]}function _i(n,t){t=it(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;tn(e),t=it(n,t);const s=n.substring(t,t+6).toUpperCase();if(s!=="SYSTEM"&&s!=="PUBLIC")throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);t+=s.length,t=it(n,t);let i=null,r=null;if(s==="PUBLIC")[t,i]=re(n,t,"publicIdentifier"),t=it(n,t),(n[t]==='"'||n[t]==="'")&&([t,r]=re(n,t,"systemIdentifier"));else if(s==="SYSTEM"&&([t,r]=re(n,t,"systemIdentifier"),!r))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:e,publicIdentifier:i,systemIdentifier:r,index:--t}}function re(n,t,e){let s="";const i=n[t];if(i!=='"'&&i!=="'")throw new Error(`Expected quoted string, found "${i}"`);for(t++;t<n.length&&n[t]!==i;)s+=n[t],t++;if(n[t]!==i)throw new Error(`Unterminated ${e} value`);return t++,[t,s]}function Ei(n,t){t=it(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;if(!tn(e))throw new Error(`Invalid element name: "${e}"`);t=it(n,t);let s="";if(n[t]==="E"&>(n,"MPTY",t))t+=4;else if(n[t]==="A"&>(n,"NY",t))t+=2;else if(n[t]==="("){for(t++;t<n.length&&n[t]!==")";)s+=n[t],t++;if(n[t]!==")")throw new Error("Unterminated content model")}else throw new Error(`Invalid Element Expression, found "${n[t]}"`);return{elementName:e,contentModel:s.trim(),index:t}}function gt(n,t,e){for(let s=0;s<t.length;s++)if(t[s]!==n[e+s+1])return!1;return!0}function tn(n){if(Qe(n))return n;throw new Error(`Invalid entity name ${n}`)}const Ai=/^[-+]?0x[a-fA-F0-9]+$/,Si=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Ni={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Ii(n,t={}){if(t=Object.assign({},Ni,t),!n||typeof n!="string")return n;let e=n.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return n;if(n==="0")return 0;if(t.hex&&Ai.test(e))return ki(e,16);if(e.search(/.+[eE].+/)!==-1)return Ti(n,e,t);{const s=Si.exec(e);if(s){const i=s[1]||"",r=s[2];let o=Oi(s[3]);const a=i?n[r.length+1]===".":n[r.length]===".";if(!t.leadingZeros&&(r.length>1||r.length===1&&!a))return n;{const c=Number(e),l=String(c);if(c===0)return c;if(l.search(/[eE]/)!==-1)return t.eNotation?c:n;if(e.indexOf(".")!==-1)return l==="0"||l===o||l===`${i}${o}`?c:n;let h=r?o:e;return r?h===l||i+h===l?c:n:h===l||h===i+l?c:n}}else return n}}const vi=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Ti(n,t,e){if(!e.eNotation)return n;const s=t.match(vi);if(s){let i=s[1]||"";const r=s[3].indexOf("e")===-1?"E":"e",o=s[2],a=i?n[o.length+1]===r:n[o.length]===r;return o.length>1&&a?n:o.length===1&&(s[3].startsWith(`.${r}`)||s[3][0]===r)?Number(t):e.leadingZeros&&!a?(t=(s[1]||"")+s[3],Number(t)):n}else return n}function Oi(n){return n&&n.indexOf(".")!==-1&&(n=n.replace(/0+$/,""),n==="."?n="0":n[0]==="."?n="0"+n:n[n.length-1]==="."&&(n=n.substring(0,n.length-1))),n}function ki(n,t){if(parseInt)return parseInt(n,t);if(Number.parseInt)return Number.parseInt(n,t);if(window&&window.parseInt)return window.parseInt(n,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function Un(n){return typeof n=="function"?n:Array.isArray(n)?t=>{for(const e of n)if(typeof e=="string"&&t===e||e instanceof RegExp&&e.test(t))return!0}:()=>!1}class Ci{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,16))}},this.addExternalEntities=Ri,this.parseXml=Hi,this.parseTextData=xi,this.resolveNameSpace=Mi,this.buildAttributesMap=Pi,this.isItStopNode=Ki,this.replaceEntitiesValue=Bi,this.readStopNodeData=Li,this.saveTextToParentTag=Di,this.addChild=Wi,this.ignoreAttributesFn=Un(this.options.ignoreAttributes)}}function Ri(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];this.lastEntities[s]={regex:new RegExp("&"+s+";","g"),val:n[s]}}}function xi(n,t,e,s,i,r,o){if(n!==void 0&&(this.options.trimValues&&!s&&(n=n.trim()),n.length>0)){o||(n=this.replaceEntitiesValue(n));const a=this.options.tagValueProcessor(t,n,e,i,r);return a==null?n:typeof a!=typeof n||a!==n?a:this.options.trimValues?$e(n,this.options.parseTagValue,this.options.numberParseOptions):n.trim()===n?$e(n,this.options.parseTagValue,this.options.numberParseOptions):n}}function Mi(n){if(this.options.removeNSPrefix){const t=n.split(":"),e=n.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return"";t.length===2&&(n=e+t[1])}return n}const $i=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Pi(n,t,e){if(this.options.ignoreAttributes!==!0&&typeof n=="string"){const s=jn(n,$i),i=s.length,r={};for(let o=0;o<i;o++){const a=this.resolveNameSpace(s[o][1]);if(this.ignoreAttributesFn(a,t))continue;let c=s[o][4],l=this.options.attributeNamePrefix+a;if(a.length)if(this.options.transformAttributeName&&(l=this.options.transformAttributeName(l)),l==="__proto__"&&(l="#__proto__"),c!==void 0){this.options.trimValues&&(c=c.trim()),c=this.replaceEntitiesValue(c);const h=this.options.attributeValueProcessor(a,c,t);h==null?r[l]=c:typeof h!=typeof c||h!==c?r[l]=h:r[l]=$e(c,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(r[l]=!0)}if(!Object.keys(r).length)return;if(this.options.attributesGroupName){const o={};return o[this.options.attributesGroupName]=r,o}return r}}const Hi=function(n){n=n.replace(/\r\n?/g,`
|
|
9
9
|
`);const t=new pt("!xml");let e=t,s="",i="";for(let r=0;r<n.length;r++)if(n[r]==="<")if(n[r+1]==="/"){const a=mt(n,">",r,"Closing Tag is not closed.");let c=n.substring(r+2,a).trim();if(this.options.removeNSPrefix){const u=c.indexOf(":");u!==-1&&(c=c.substr(u+1))}this.options.transformTagName&&(c=this.options.transformTagName(c)),e&&(s=this.saveTextToParentTag(s,e,i));const l=i.substring(i.lastIndexOf(".")+1);if(c&&this.options.unpairedTags.indexOf(c)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${c}>`);let h=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(h=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):h=i.lastIndexOf("."),i=i.substring(0,h),e=this.tagsNodeStack.pop(),s="",r=a}else if(n[r+1]==="?"){let a=Me(n,r,!1,"?>");if(!a)throw new Error("Pi Tag is not closed.");if(s=this.saveTextToParentTag(s,e,i),!(this.options.ignoreDeclaration&&a.tagName==="?xml"||this.options.ignorePiTags)){const c=new pt(a.tagName);c.add(this.options.textNodeName,""),a.tagName!==a.tagExp&&a.attrExpPresent&&(c[":@"]=this.buildAttributesMap(a.tagExp,i,a.tagName)),this.addChild(e,c,i,r)}r=a.closeIndex+1}else if(n.substr(r+1,3)==="!--"){const a=mt(n,"-->",r+4,"Comment is not closed.");if(this.options.commentPropName){const c=n.substring(r+4,a-2);s=this.saveTextToParentTag(s,e,i),e.add(this.options.commentPropName,[{[this.options.textNodeName]:c}])}r=a}else if(n.substr(r+1,2)==="!D"){const a=wi(n,r);this.docTypeEntities=a.entities,r=a.i}else if(n.substr(r+1,2)==="!["){const a=mt(n,"]]>",r,"CDATA is not closed.")-2,c=n.substring(r+9,a);s=this.saveTextToParentTag(s,e,i);let l=this.parseTextData(c,e.tagname,i,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?e.add(this.options.cdataPropName,[{[this.options.textNodeName]:c}]):e.add(this.options.textNodeName,l),r=a+2}else{let a=Me(n,r,this.options.removeNSPrefix),c=a.tagName;const l=a.rawTagName;let h=a.tagExp,u=a.attrExpPresent,d=a.closeIndex;this.options.transformTagName&&(c=this.options.transformTagName(c)),e&&s&&e.tagname!=="!xml"&&(s=this.saveTextToParentTag(s,e,i,!1));const p=e;p&&this.options.unpairedTags.indexOf(p.tagname)!==-1&&(e=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),c!==t.tagname&&(i+=i?"."+c:c);const f=r;if(this.isItStopNode(this.options.stopNodes,i,c)){let m="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)c[c.length-1]==="/"?(c=c.substr(0,c.length-1),i=i.substr(0,i.length-1),h=c):h=h.substr(0,h.length-1),r=a.closeIndex;else if(this.options.unpairedTags.indexOf(c)!==-1)r=a.closeIndex;else{const S=this.readStopNodeData(n,l,d+1);if(!S)throw new Error(`Unexpected end of ${l}`);r=S.i,m=S.tagContent}const A=new pt(c);c!==h&&u&&(A[":@"]=this.buildAttributesMap(h,i,c)),m&&(m=this.parseTextData(m,c,i,!0,u,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),A.add(this.options.textNodeName,m),this.addChild(e,A,i,f)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){c[c.length-1]==="/"?(c=c.substr(0,c.length-1),i=i.substr(0,i.length-1),h=c):h=h.substr(0,h.length-1),this.options.transformTagName&&(c=this.options.transformTagName(c));const m=new pt(c);c!==h&&u&&(m[":@"]=this.buildAttributesMap(h,i,c)),this.addChild(e,m,i,f),i=i.substr(0,i.lastIndexOf("."))}else{const m=new pt(c);this.tagsNodeStack.push(e),c!==h&&u&&(m[":@"]=this.buildAttributesMap(h,i,c)),this.addChild(e,m,i,f),e=m}s="",r=d}}else s+=n[r];return t.child};function Wi(n,t,e,s){this.options.captureMetaData||(s=void 0);const i=this.options.updateTag(t.tagname,e,t[":@"]);i===!1||(typeof i=="string"&&(t.tagname=i),n.addChild(t,s))}const Bi=function(n){if(this.options.processEntities){for(let t in this.docTypeEntities){const e=this.docTypeEntities[t];n=n.replace(e.regx,e.val)}for(let t in this.lastEntities){const e=this.lastEntities[t];n=n.replace(e.regex,e.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const e=this.htmlEntities[t];n=n.replace(e.regex,e.val)}n=n.replace(this.ampEntity.regex,this.ampEntity.val)}return n};function Di(n,t,e,s){return n&&(s===void 0&&(s=t.child.length===0),n=this.parseTextData(n,t.tagname,e,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,s),n!==void 0&&n!==""&&t.add(this.options.textNodeName,n),n=""),n}function Ki(n,t,e){const s="*."+e;for(const i in n){const r=n[i];if(s===r||t===r)return!0}return!1}function zi(n,t,e=">"){let s,i="";for(let r=t;r<n.length;r++){let o=n[r];if(s)o===s&&(s="");else if(o==='"'||o==="'")s=o;else if(o===e[0])if(e[1]){if(n[r+1]===e[1])return{data:i,index:r}}else return{data:i,index:r};else o===" "&&(o=" ");i+=o}}function mt(n,t,e,s){const i=n.indexOf(t,e);if(i===-1)throw new Error(s);return i+t.length-1}function Me(n,t,e,s=">"){const i=zi(n,t+1,s);if(!i)return;let r=i.data;const o=i.index,a=r.search(/\s/);let c=r,l=!0;a!==-1&&(c=r.substring(0,a),r=r.substring(a+1).trimStart());const h=c;if(e){const u=c.indexOf(":");u!==-1&&(c=c.substr(u+1),l=c!==i.data.substr(u+1))}return{tagName:c,tagExp:r,closeIndex:o,attrExpPresent:l,rawTagName:h}}function Li(n,t,e){const s=e;let i=1;for(;e<n.length;e++)if(n[e]==="<")if(n[e+1]==="/"){const r=mt(n,">",e,`${t} is not closed`);if(n.substring(e+2,r).trim()===t&&(i--,i===0))return{tagContent:n.substring(s,e),i:r};e=r}else if(n[e+1]==="?")e=mt(n,"?>",e+1,"StopNode is not closed.");else if(n.substr(e+1,3)==="!--")e=mt(n,"-->",e+3,"StopNode is not closed.");else if(n.substr(e+1,2)==="![")e=mt(n,"]]>",e,"StopNode is not closed.")-2;else{const r=Me(n,e,">");r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!=="/"&&i++,e=r.closeIndex)}}function $e(n,t,e){if(t&&typeof n=="string"){const s=n.trim();return s==="true"?!0:s==="false"?!1:Ii(n,e)}else return ri(n)?n:""}const Se=pt.getMetaDataSymbol();function ji(n,t){return Fn(n,t)}function Fn(n,t,e){let s;const i={};for(let r=0;r<n.length;r++){const o=n[r],a=Ui(o);let c="";if(e===void 0?c=a:c=e+"."+a,a===t.textNodeName)s===void 0?s=o[a]:s+=""+o[a];else{if(a===void 0)continue;if(o[a]){let l=Fn(o[a],t,c);const h=Zi(l,t);o[Se]!==void 0&&(l[Se]=o[Se]),o[":@"]?Fi(l,o[":@"],c,t):Object.keys(l).length===1&&l[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?l=l[t.textNodeName]:Object.keys(l).length===0&&(t.alwaysCreateTextNode?l[t.textNodeName]="":l=""),i[a]!==void 0&&i.hasOwnProperty(a)?(Array.isArray(i[a])||(i[a]=[i[a]]),i[a].push(l)):t.isArray(a,c,h)?i[a]=[l]:i[a]=l}}}return typeof s=="string"?s.length>0&&(i[t.textNodeName]=s):s!==void 0&&(i[t.textNodeName]=s),i}function Ui(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];if(s!==":@")return s}}function Fi(n,t,e,s){if(t){const i=Object.keys(t),r=i.length;for(let o=0;o<r;o++){const a=i[o];s.isArray(a,e+"."+a,!0,!0)?n[a]=[t[a]]:n[a]=t[a]}}}function Zi(n,t){const{textNodeName:e}=t,s=Object.keys(n).length;return!!(s===0||s===1&&(n[e]||typeof n[e]=="boolean"||n[e]===0))}class Gi{constructor(t){this.externalEntities={},this.options=mi(t)}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});const r=ai(t,e);if(r!==!0)throw Error(`${r.err.msg}:${r.err.line}:${r.err.col}`)}const s=new Ci(this.options);s.addExternalEntities(this.externalEntities);const i=s.parseXml(t);return this.options.preserveOrder||i===void 0?i:ji(i,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return pt.getMetaDataSymbol()}}const Vi=`
|
|
10
10
|
`;function Ji(n,t){let e="";return t.format&&t.indentBy.length>0&&(e=Vi),Zn(n,t,"",e)}function Zn(n,t,e,s){let i="",r=!1;for(let o=0;o<n.length;o++){const a=n[o],c=Yi(a);if(c===void 0)continue;let l="";if(e.length===0?l=c:l=`${e}.${c}`,c===t.textNodeName){let f=a[c];Xi(l,t)||(f=t.tagValueProcessor(c,f),f=Gn(f,t)),r&&(i+=s),i+=f,r=!1;continue}else if(c===t.cdataPropName){r&&(i+=s),i+=`<![CDATA[${a[c][0][t.textNodeName]}]]>`,r=!1;continue}else if(c===t.commentPropName){i+=s+`<!--${a[c][0][t.textNodeName]}-->`,r=!0;continue}else if(c[0]==="?"){const f=vn(a[":@"],t),m=c==="?xml"?"":s;let A=a[c][0][t.textNodeName];A=A.length!==0?" "+A:"",i+=m+`<${c}${A}${f}?>`,r=!0;continue}let h=s;h!==""&&(h+=t.indentBy);const u=vn(a[":@"],t),d=s+`<${c}${u}`,p=Zn(a[c],t,l,h);t.unpairedTags.indexOf(c)!==-1?t.suppressUnpairedNode?i+=d+">":i+=d+"/>":(!p||p.length===0)&&t.suppressEmptyNode?i+=d+"/>":p&&p.endsWith(">")?i+=d+`>${p}${s}</${c}>`:(i+=d+">",p&&s!==""&&(p.includes("/>")||p.includes("</"))?i+=s+t.indentBy+p+s:i+=p,i+=`</${c}>`),r=!0}return i}function Yi(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];if(n.hasOwnProperty(s)&&s!==":@")return s}}function vn(n,t){let e="";if(n&&!t.ignoreAttributes)for(let s in n){if(!n.hasOwnProperty(s))continue;let i=t.attributeValueProcessor(s,n[s]);i=Gn(i,t),i===!0&&t.suppressBooleanAttributes?e+=` ${s.substr(t.attributeNamePrefix.length)}`:e+=` ${s.substr(t.attributeNamePrefix.length)}="${i}"`}return e}function Xi(n,t){n=n.substr(0,n.length-t.textNodeName.length-1);let e=n.substr(n.lastIndexOf(".")+1);for(let s in t.stopNodes)if(t.stopNodes[s]===n||t.stopNodes[s]==="*."+e)return!0;return!1}function Gn(n,t){if(n&&n.length>0&&t.processEntities)for(let e=0;e<t.entities.length;e++){const s=t.entities[e];n=n.replace(s.regex,s.val)}return n}const qi={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(n,t){return t},attributeValueProcessor:function(n,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function lt(n){this.options=Object.assign({},qi,n),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Un(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=er),this.processTextOrObjNode=Qi,this.options.format?(this.indentate=tr,this.tagEndChar=`>
|
|
11
11
|
`,this.newLine=`
|
|
12
12
|
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}lt.prototype.build=function(n){return this.options.preserveOrder?Ji(n,this.options):(Array.isArray(n)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(n={[this.options.arrayNodeName]:n}),this.j2x(n,0,[]).val)};lt.prototype.j2x=function(n,t,e){let s="",i="";const r=e.join(".");for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))if(typeof n[o]>"u")this.isAttribute(o)&&(i+="");else if(n[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+="":o[0]==="?"?i+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(n[o]instanceof Date)i+=this.buildTextValNode(n[o],o,"",t);else if(typeof n[o]!="object"){const a=this.isAttribute(o);if(a&&!this.ignoreAttributesFn(a,r))s+=this.buildAttrPairStr(a,""+n[o]);else if(!a)if(o===this.options.textNodeName){let c=this.options.tagValueProcessor(o,""+n[o]);i+=this.replaceEntitiesValue(c)}else i+=this.buildTextValNode(n[o],o,"",t)}else if(Array.isArray(n[o])){const a=n[o].length;let c="",l="";for(let h=0;h<a;h++){const u=n[o][h];if(!(typeof u>"u"))if(u===null)o[0]==="?"?i+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(typeof u=="object")if(this.options.oneListGroup){const d=this.j2x(u,t+1,e.concat(o));c+=d.val,this.options.attributesGroupName&&u.hasOwnProperty(this.options.attributesGroupName)&&(l+=d.attrStr)}else c+=this.processTextOrObjNode(u,o,t,e);else if(this.options.oneListGroup){let d=this.options.tagValueProcessor(o,u);d=this.replaceEntitiesValue(d),c+=d}else c+=this.buildTextValNode(u,o,"",t)}this.options.oneListGroup&&(c=this.buildObjectNode(c,o,l,t)),i+=c}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const a=Object.keys(n[o]),c=a.length;for(let l=0;l<c;l++)s+=this.buildAttrPairStr(a[l],""+n[o][a[l]])}else i+=this.processTextOrObjNode(n[o],o,t,e);return{attrStr:s,val:i}};lt.prototype.buildAttrPairStr=function(n,t){return t=this.options.attributeValueProcessor(n,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+n:" "+n+'="'+t+'"'};function Qi(n,t,e,s){const i=this.j2x(n,e+1,s.concat(t));return n[this.options.textNodeName]!==void 0&&Object.keys(n).length===1?this.buildTextValNode(n[this.options.textNodeName],t,i.attrStr,e):this.buildObjectNode(i.val,t,i.attrStr,e)}lt.prototype.buildObjectNode=function(n,t,e,s){if(n==="")return t[0]==="?"?this.indentate(s)+"<"+t+e+"?"+this.tagEndChar:this.indentate(s)+"<"+t+e+this.closeTag(t)+this.tagEndChar;{let i="</"+t+this.tagEndChar,r="";return t[0]==="?"&&(r="?",i=""),(e||e==="")&&n.indexOf("<")===-1?this.indentate(s)+"<"+t+e+r+">"+n+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&r.length===0?this.indentate(s)+`<!--${n}-->`+this.newLine:this.indentate(s)+"<"+t+e+r+this.tagEndChar+n+this.indentate(s)+i}};lt.prototype.closeTag=function(n){let t="";return this.options.unpairedTags.indexOf(n)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${n}`,t};lt.prototype.buildTextValNode=function(n,t,e,s){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(s)+`<![CDATA[${n}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(s)+`<!--${n}-->`+this.newLine;if(t[0]==="?")return this.indentate(s)+"<"+t+e+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(t,n);return i=this.replaceEntitiesValue(i),i===""?this.indentate(s)+"<"+t+e+this.closeTag(t)+this.tagEndChar:this.indentate(s)+"<"+t+e+">"+i+"</"+t+this.tagEndChar}};lt.prototype.replaceEntitiesValue=function(n){if(n&&n.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const e=this.options.entities[t];n=n.replace(e.regex,e.val)}return n};function tr(n){return this.options.indentBy.repeat(n)}function er(n){return n.startsWith(this.options.attributeNamePrefix)&&n!==this.options.textNodeName?n.substr(this.attrPrefixLen):!1}class ht{constructor(t){_(this,"type");_(this,"attrs",{});_(this,"styles",{});_(this,"deleteMarker",!1);this.type=t}dx(t){return this.attrs.x==null?this.attrs.x=t:this.attrs.x+=t,this}dy(t){return this.attrs.y==null?this.attrs.y=t:this.attrs.y+=t,this}x(t){return this.attrs.x=t,this}y(t){return this.attrs.y=t,this}size(t,e){return this.attrs.width=t,this.attrs.height=e,this}remove(){this.deleteMarker=!0}left(...t){return`<${[this.type,Yn(this.attrs),dr(this.styles),...t].filter(e=>e!="").join(" ")}>`}right(){return`</${this.type}>`}center(){return""}toString(){return this.deleteMarker?"":`${this.left()}${this.center()}${this.right()}`}attr(t){if(typeof t=="string")return this.attrs[t]??"";for(const[e,s]of Object.entries(t))this.attrs[e]=s;return this}css(t){return this.styles={...this.styles,...t},this}svg(){return this.toString()}}class en extends ht{constructor(e){super("image");_(this,"attrs",{});this.attrs={...this.attrs,href:e}}load(e){return this.attrs.href=e,this}}class be extends ht{constructor(e){super("use");_(this,"attrs",{});this.attrs={...this.attrs,href:this.make(e)}}use(e){return this.attrs.href=`#${e}`,this}make(e){return e==null?e:`#${e}`}}class nn extends ht{constructor(){super("rect");_(this,"attrs",{})}fill(e){return this.attrs.fill=e,this}stroke(e){return this.attrs.stroke=e,this}}class _t extends ht{constructor(e=""){super("text");_(this,"attrs");_(this,"_text","");this._text=e,this.attrs={}}plain(e){return this._text=e,this}font(e){return this.attrs.fontFamily=e.family,this.attrs.fontSize=e.size,this}center(){return this._text}}let sn=class extends ht{constructor(e){super("symbol");_(this,"raw");this.raw=e}id(){return this.attr("id")}center(){return this.raw}};class v extends ht{constructor(){super("g");_(this,"children",[]);_(this,"rotateMatrix");_(this,"translateMatrix")}add(e){return this.children.push(e),this}rotate(e,s,i){return this.rotateMatrix=qs(e,s,i),this}translate(e,s){return this.translateMatrix=xe(e,s),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){const s=[this.translateMatrix,this.rotateMatrix].filter(i=>i!=null);return s.length==0?super.left():super.left(ur(Gs(s)))}each(e,s){for(let i=0;i<this.children.length;i++){const r=this.children[i];r instanceof v&&s&&r.each(e,!0),e(i,this.children)}}}const nr=['xmlns="http://www.w3.org/2000/svg"','version="1.1"','xmlns:xlink="http://www.w3.org/1999/xlink"'];class Vn extends ht{constructor(){super("svg");_(this,"children",[]);_(this,"viewBox")}add(e){return this.children.push(e),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){return`<${[this.type,...nr,Yn(this.attrs),hr(this.viewBox)].filter(s=>s!="").join(" ")}>`}viewbox(e,s,i,r){return this.viewBox={x:e,y:s,width:i,height:r},this}importSymbol(e){for(const s of fr(e))this.add(s);return this}x(e){throw new Error("unimplemented")}y(e){throw new Error("unimplemented")}dx(e){throw new Error("unimplemented")}dy(e){throw new Error("unimplemented")}each(e,s){for(let i=0;i<this.children.length;i++){const r=this.children[i];r instanceof v&&s&&r.each(e,!0),e(i,this.children)}}}function Jn(){return new Vn}const sr=Jn,ir=v,rr=en,or=be,ar=nn,cr=_t;function lr(n){return n.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function hr(n){return n==null?"":`viewBox="${n.x} ${n.y} ${n.width} ${n.height}"`}function ur(n){return n==null?"":`transform="${Qs(n)}"`}function Yn(n){return Object.entries(n).filter(([t,e])=>e!==void 0).map(([t,e])=>`${lr(t)}="${e}"`).join(" ")}function dr(n){const t=Object.entries(n).map(([e,s])=>`${e}: ${s};`).join(" ");return t!=""?`style="${t}"`:""}function*fr(n){const t=new Gi({ignoreAttributes:!1}),e=new lt({ignoreAttributes:!1}),s=t.parse(n);for(const i of s.svg.symbol){const r=e.build(i),o=new sn(r);for(const[a,c]of Object.entries(i))a.startsWith("@_")&&(o.attrs[a.substring(2)]=c);yield o}}const G=(n,t)=>{const e=z(n.tiles[0],t),s=e.baseHeight,i=e.baseWidth;if(n.is(b.SHO_KAN))return{width:i*2+s,height:Math.max(i*2,s)};const r=n.tiles.reduce((a,c)=>{const l=z(c,t).height;return l>a?l:a},0);return{width:n.tiles.reduce((a,c)=>a+z(c,t).width,0),height:r}},z=(n,t)=>{const e=parseFloat((ot.HEIGHT*t).toPrecision(5)),s=parseFloat((ot.WIDTH*t).toPrecision(5)),i=n.has(y.HORIZONTAL)?{width:e,height:s,baseWidth:s,baseHeight:e}:{width:s,height:e,w:s,baseWidth:s,baseHeight:e};return(n.has(y.TSUMO)||n.has(y.DORA))&&(i.width+=s*ot.TEXT_SCALE),i};class Rt{constructor(t={}){_(this,"tileWidth");_(this,"tileHeight");_(this,"imageHostUrl");_(this,"imageExt");_(this,"scale");_(this,"svgSprite");this.scale=t.scale??1,this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=ot.WIDTH*this.scale,this.tileHeight=ot.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getDiffTileHeightWidth(t){const e=z(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new en().load(this.buildURL(t));return this.svgSprite&&(e=new be().use(Rt.buildID(t))),t instanceof w&&t.has(y.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,s){const i=z(t,this.scale);return this.image(t).dx(e).dy(s).size(i.baseWidth,i.baseHeight)}createTextImage(t,e,s,i){const r=this.createImage(t,e,s),o=z(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,l=o.baseHeight,h=new _t().plain(i);h.size(o.baseWidth,o.baseHeight).font({family:Ge,size:a}).dx(c).dy(l);const u=new v;return u.add(r).add(h).translate(e,s),u}createRotate90Image(t,e,s,i=!1){const r=this.createImage(t,0,0),o=z(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,l=e+this.getDiffTileHeightWidth(t),h=i?s-this.getDiffTileHeightWidth(t):s,u=new v;return u.add(r).translate(l,h).rotate(90,a,c),u}createStick(t){return this.image(t)}static buildID(t){if(t==100||t==1e3)return t==100?"stick100":"stick1000";const e=t.t==g.BACK||t.has(y.RED)?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${Rt.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:e}}class rn extends Rt{constructor(){super(...arguments);_(this,"blockMargin",ot.WIDTH*ot.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const s=e instanceof M?e.tilesWithBack:e.tiles,i=new v;let r=0;for(const o of s){const a=z(o,this.scale),c=o.has(y.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),l=o.has(y.HORIZONTAL)?this.getDiffTileHeightWidth(o):0,h=c(o,r,l);i.add(h),r+=a.width}return i}createBlockPonChiKan(e){const s=e.tiles.findIndex(o=>o.has(y.HORIZONTAL));let i=0;const r=new v;if(e.type==b.SHO_KAN){let o=s;for(let a=0;a<e.tiles.length;a++)e.tiles[a].has(y.HORIZONTAL)&&(o=a);for(let a=0;a<e.tiles.length;a++){const c=z(e.tiles[a],this.scale);if(a==o)continue;if(a==s){const u=e.tiles[s],d=e.tiles[o],p=z(u,this.scale),f=this.createRotate90Image(u,0,0,!0),m=this.createRotate90Image(d,0,p.height,!0);r.add(new v().translate(i,0).add(f).add(m)),i+=p.width;continue}const l=c.width*2-c.height,h=this.createImage(e.tiles[a],i,l);i+=c.width,r.add(h)}return r}if(e.type==b.CHI){const o=e.tiles[s],a=this.createRotate90Image(o,i,this.getDiffTileHeightWidth(o));i+=z(o,this.scale).width,r.add(a);for(let c=0;c<e.tiles.length;c++){if(c==s)continue;const l=e.tiles[c],h=z(l,this.scale),u=this.createImage(l,i,0);i+=h.width,r.add(u)}return r}for(let o=0;o<e.tiles.length;o++){const a=o==s?this.createRotate90Image.bind(this):this.createImage.bind(this),c=e.tiles[o],l=o==s?this.getDiffTileHeightWidth(c):0,h=z(c,this.scale),u=a(c,i,l);i+=h.width,r.add(u)}return r}}const pr=(n,t)=>{const e=n.scale;return{[b.CHI]:function(i){const r=G(i,e),o=n.createBlockPonChiKan(i);return{...r,e:o}},[b.PON]:function(i){const r=G(i,e),o=n.createBlockPonChiKan(i);return{...r,e:o}},[b.DAI_KAN]:function(i){const r=G(i,e),o=n.createBlockPonChiKan(i);return{...r,e:o}},[b.SHO_KAN]:function(i){const r=G(i,e),o=n.createBlockPonChiKan(i);return{...r,e:o}},[b.AN_KAN]:function(i){I(i instanceof M,`block type is not ankan: ${i.type}`);const r=G(i,e),o=n.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DORA]:function(i){i=(t==null?void 0:t.doraText)==!1?new Ct([i.tiles[0].clone({remove:y.DORA})]):i;const r=G(i,e),o=new v,a=(t==null?void 0:t.doraText)===!1?n.createImage(i.tiles[0],0,0):n.createTextImage(i.tiles[0],0,0,"(ドラ)");return o.add(a),{...r,e:o}},[b.TSUMO]:function(i){i=(t==null?void 0:t.tsumoText)==!1?new Ct([i.tiles[0].clone({remove:y.TSUMO})]):i;const r=G(i,e),o=new v,a=(t==null?void 0:t.tsumoText)===!1?n.createImage(i.tiles[0],0,0):n.createTextImage(i.tiles[0],0,0,"(ツモ)");return o.add(a),{...r,e:o}},[b.HAND]:function(i){const r=G(i,e),o=n.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DISCARD]:function(i){const r=G(i,e),o=n.createBlockHandDiscard(i);return{...r,e:o}},[b.THREE]:function(i){throw new Error("three is unsupported")},[b.RUN]:function(i){throw new Error("run is unsupported")},[b.PAIR]:function(i){throw new Error("pair is unsupported")},[b.ISOLATED]:function(i){throw new Error("isolated is unsupported")},[b.UNKNOWN]:function(i){if(i.tiles.some(a=>a.has(y.TSUMO)||a.has(y.DORA)))throw new Error("found an unknown block with operator tiles");const r=G(i,e),o=n.createBlockHandDiscard(i);return{...r,e:o}}}},Tt=(n,t,e)=>{const s=pr(n,e);let i=0,r=0;const o=[];for(const u of t){const d=s[u.type],p=d(u);r+=p.width,i=p.height>i?p.height:i,o.push(p)}const a=i,c=r+(t.length-1)*n.blockMargin,l=new v;let h=0;for(const u of o){const d=a-u.height,p=new v().translate(h,d);p.add(u.e),l.add(p),h+=u.width+n.blockMargin}return{e:l,width:c,height:a}},gr=(n,t,e={},s={responsive:!1,doraText:!0,tsumoText:!0})=>{const i=new rn(e),r=Tt(i,t,s);s.responsive||n.size(r.width,r.height),n.viewbox(0,0,r.width,r.height),n.add(r.e)},Xn=()=>{const n=[0,1,2,3,4,5,6,7,8,9],t=[];for(const e of Object.values(g)){if(e==g.BACK){t.push(Rt.buildID(new w(e,0)));continue}t.push(...n.map(s=>Rt.buildID(new w(e,s))).flat())}return t},yr=n=>{const t=Xn(),e=[];return n.each((s,i)=>{const r=i[s];if(r instanceof be){const a=r.attr("href").substring(1);t.includes(a)&&e.push(a)}},!0),e},mr=n=>{const t=Xn(),e=yr(n);n.each((s,i)=>{const r=i[s];r instanceof sn&&(t.includes(r.id())&&e.includes(r.id())||r.remove())},!0)},wr=n=>{const e=[];for(let s=0;s<n.length;s+=6){const i=n.slice(s,s+6);e.push(i)}return e},Z=(n,t,e,s,i=0,r=0)=>{const o=new v().add(n);if(s==90){const a=i,c=r-e;return o.rotate(s,0,e).translate(a,c),new v().add(o)}if(s==180){const a=i+t,c=r-e;return o.rotate(s,0,e).translate(a,c),new v().add(o)}if(s==270){const a=i+e,c=r+(t-e);return o.rotate(s,0,e).translate(a,c),new v().add(o)}return new v().add(o)},ee=(n,t)=>{const e=new v,s=wr(n);for(let i=0;i<s.length;i++){let r=s[i],o=i*t.tileHeight;const a=t.createBlockHandDiscard(new Xe(r,b.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*s.length}},br=(n,t,e)=>{const s=t.font,i=t.textWidth,r=t.textHeight,o=e.sticks.dead,a=e.sticks.reach,c=Ce.WIDTH*n.scale,l=Ce.HEIGHT*n.scale;let h=i*3,u=r;const d=(c+n.tileWidth+i-h)/2,p=new _t().plain(e.round).font(s).x(d).y(0);u+=25*n.scale;const f=n.tileHeight,m=new v().size(c,f).translate(0,u),A={family:s.family,size:s.size*.7},S=n.createStick(1e3).size(c,l).x(0).y(0),R=new _t().plain(a.toString()).font(A).dx(c).dy(l),N=n.createStick(100).size(c,l).x(0).y(l+l),T=new _t().plain(o.toString()).font(A).dx(c).dy(l*3);m.add(S),m.add(R),m.add(N),m.add(T);const W=n.createImage(e.doras[0],0,0).x(c+i).y(0);m.add(W);const $=new v;return $.add(p),$.add(p),$.add(m),{e:$,width:c+n.tileWidth+i,height:u+n.tileHeight}},_r=(n,t,e=0)=>{const s=Tt(n,t.front),i=Tt(n,t.right),r=Tt(n,t.opposite),o=Tt(n,t.left),a=[s.width,i.width,r.width,o.width].reduce((m,A)=>Math.max(m,A)),c=Math.max(e+n.tileHeight*2+n.blockMargin*2,a+n.tileWidth*2+n.blockMargin),l=c,h=Z(s.e,s.width,s.height,0).translate((c-s.width)/2,l-s.height),u=Z(i.e,i.width,i.height,270).translate(c-i.height,(c-i.width)/2),d=Z(r.e,r.width,r.height,180).translate((c-r.width)/2,0),p=Z(o.e,o.width,o.height,90).translate(0,(c-o.width)/2),f=new v().size(c,l);return f.add(h),f.add(u),f.add(d),f.add(p),{e:new v().add(f),width:c,height:l}},Er=n=>{const t=Object.values(ye),e=t.indexOf(n);return[...t.slice(e),...t.slice(0,e)]},Ar=(n,t,e)=>{const s=n.tileWidth*5+n.tileHeight*1,i=t.font,r=t.textWidth,o=t.textHeight,a=t.numWidth,c=br(n,t,e);c.e.translate(s/2-c.width/2,s/2-c.height/2);const l=(Ms,wn,$s)=>{const Ps=`${Ms} ${wn}`,Hs=new _t().plain(Ps).font(i).attr($s);return{e:new v().add(Hs),width:r+a*wn.toString().length,height:o}},[h,u,d,p]=Er(e.frontPlace),f=e.scores,A=l(h,f.front,{x:s/2,y:s,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let S=l(u,f.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const R=Z(S.e,S.width,S.height,270).translate(s,s/2-S.width);let N=l(d,f.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const T=Z(N.e,N.width,N.height,180).translate(s/2-N.width,-N.height);let W=l(p,f.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const $=Z(W.e,W.width,W.height,90).translate(-W.height,s/2),q=new v,xs=new nn().size(s,s).x(0).y(0).fill("none").stroke("#000000");return q.add(xs),q.add(c.e),q.add(A),q.add(R),q.add(T),q.add($),{e:q,width:s,height:s}},Sr=(n,t)=>{const e=ee(t.front,n),s=ee(t.right,n),i=ee(t.opposite,n),r=ee(t.left,n),o=[e.height,s.height,i.height,r.height].reduce((R,N)=>Math.max(R,N)),a=n.tileWidth*5+n.tileHeight*1,c=o,l=a+o*2+n.blockMargin,h=l,u=new v().size(l,h),d=l/2-a/2,p=h/2-a/2,f=Z(e.e,a,c,0).translate(d,h-c),m=Z(s.e,a,c,270).translate(l-c,p),A=Z(i.e,a,c,180).translate(d,0),S=Z(r.e,a,c,90).translate(0,p);return u.add(f),u.add(m),u.add(A),u.add(S),{e:new v().add(u),width:l,height:h}},qn=(n,t,e,s,i)=>{const r=new v,o=Sr(n,s),a=_r(n,e,o.height),c=Ar(n,t,i);return o.e.translate((a.width-o.width)/2,(a.height-o.height)/2),c.e.translate((a.width-c.width)/2,(a.height-c.height)/2),r.add(a.e),r.add(o.e),r.add(c.e),{e:r,width:a.width,height:a.height}},Nr=(n,t,e={},s,i={responsive:!1})=>{const r=new rn(e),o=s,{discards:a,hands:c,scoreBoard:l}=es(t),h=qn(r,o,c,a,l);i.responsive||n.size(h.width,h.height),n.viewbox(0,0,h.width,h.height),n.add(h.e)};var Q;function Qn(n){return{lang:(n==null?void 0:n.lang)??(Q==null?void 0:Q.lang),message:n==null?void 0:n.message,abortEarly:(n==null?void 0:n.abortEarly)??(Q==null?void 0:Q.abortEarly),abortPipeEarly:(n==null?void 0:n.abortPipeEarly)??(Q==null?void 0:Q.abortPipeEarly)}}var Ne;function Ir(n){return Ne==null?void 0:Ne.get(n)}var Ie;function vr(n){return Ie==null?void 0:Ie.get(n)}var ve;function Tr(n,t){var e;return(e=ve==null?void 0:ve.get(n))==null?void 0:e.get(t)}function xt(n){var e,s;const t=typeof n;return t==="string"?`"${n}"`:t==="number"||t==="bigint"||t==="boolean"?`${n}`:t==="object"||t==="function"?(n&&((s=(e=Object.getPrototypeOf(n))==null?void 0:e.constructor)==null?void 0:s.name))??"null":t}function at(n,t,e,s,i){const r=i&&"input"in i?i.input:e.value,o=(i==null?void 0:i.expected)??n.expects??null,a=(i==null?void 0:i.received)??xt(r),c={kind:n.kind,type:n.type,input:r,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:n.requirement,path:i==null?void 0:i.path,issues:i==null?void 0:i.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},l=n.kind==="schema",h=(i==null?void 0:i.message)??n.message??Tr(n.reference,c.lang)??(l?vr(c.lang):null)??s.message??Ir(c.lang);h!==void 0&&(c.message=typeof h=="function"?h(c):h),l&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function Kt(n){return{version:1,vendor:"valibot",validate(t){return n["~run"]({value:t},Qn())}}}function Or(n,t){const e=[...new Set(n)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function Pe(n,t){return{kind:"validation",type:"max_value",reference:Pe,async:!1,expects:`<=${n instanceof Date?n.toJSON():xt(n)}`,requirement:n,message:t,"~run"(e,s){return e.typed&&!(e.value<=this.requirement)&&at(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():xt(e.value)}),e}}}function He(n,t){return{kind:"validation",type:"min_value",reference:He,async:!1,expects:`>=${n instanceof Date?n.toJSON():xt(n)}`,requirement:n,message:t,"~run"(e,s){return e.typed&&!(e.value>=this.requirement)&&at(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():xt(e.value)}),e}}}function kr(n,t,e){return typeof n.fallback=="function"?n.fallback(t,e):n.fallback}function ts(n,t,e){return typeof n.default=="function"?n.default(t,e):n.default}function le(n){return{kind:"schema",type:"number",reference:le,expects:"number",async:!1,message:n,get"~standard"(){return Kt(this)},"~run"(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:at(this,"type",t,e),t}}}function j(n,t){return{kind:"schema",type:"optional",reference:j,expects:`(${n.expects} | undefined)`,async:!1,wrapped:n,default:t,get"~standard"(){return Kt(this)},"~run"(e,s){return e.value===void 0&&(this.default!==void 0&&(e.value=ts(this,e,s)),e.value===void 0)?(e.typed=!0,e):this.wrapped["~run"](e,s)}}}function We(n,t){return{kind:"schema",type:"picklist",reference:We,expects:Or(n.map(xt),"|"),async:!1,options:n,message:t,get"~standard"(){return Kt(this)},"~run"(e,s){return this.options.includes(e.value)?e.typed=!0:at(this,"type",e,s),e}}}function Mt(n,t){return{kind:"schema",type:"strict_object",reference:Mt,expects:"Object",async:!1,entries:n,message:t,get"~standard"(){return Kt(this)},"~run"(e,s){var r;const i=e.value;if(i&&typeof i=="object"){e.typed=!0,e.value={};for(const o in this.entries){const a=this.entries[o];if(o in i||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){const c=o in i?i[o]:ts(a),l=a["~run"]({value:c},s);if(l.issues){const h={type:"object",origin:"value",input:i,key:o,value:c};for(const u of l.issues)u.path?u.path.unshift(h):u.path=[h],(r=e.issues)==null||r.push(u);if(e.issues||(e.issues=l.issues),s.abortEarly){e.typed=!1;break}}l.typed||(e.typed=!1),e.value[o]=l.value}else if(a.fallback!==void 0)e.value[o]=kr(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(at(this,"key",e,s,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]}),s.abortEarly))break}if(!e.issues||!s.abortEarly){for(const o in i)if(!(o in this.entries)){at(this,"key",e,s,{input:o,expected:"never",path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]});break}}}else at(this,"type",e,s);return e}}}function he(n){return{kind:"schema",type:"string",reference:he,expects:"string",async:!1,message:n,get"~standard"(){return Kt(this)},"~run"(t,e){return typeof t.value=="string"?t.typed=!0:at(this,"type",t,e),t}}}function Tn(...n){return{...n[0],pipe:n,get"~standard"(){return Kt(this)},"~run"(t,e){for(const s of n)if(s.kind!=="metadata"){if(t.issues&&(s.kind==="schema"||s.kind==="transformation")){t.typed=!1;break}(!t.issues||!e.abortEarly&&!e.abortPipeEarly)&&(t=s["~run"](t,e))}return t}}}function Cr(n,t,e){const s=n["~run"]({value:t},Qn(e));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}const ne=j(Mt({discard:j(he(),""),hand:j(he(),""),score:j(le(),25e3)}),{discard:"",hand:"",score:25e3}),Rr=Mt({[E.E]:ne,[E.S]:ne,[E.W]:ne,[E.N]:ne}),ut={round:C.E1,sticks:{reach:0,dead:0},doras:E.S,front:E.E},xr=j(Mt({round:j(We(Object.keys(Ve)),ut.round),sticks:j(Mt({reach:j(Tn(le(),He(0,""),Pe(9,"")),ut.sticks.reach),dead:j(Tn(le(),He(0,""),Pe(9,"")),ut.sticks.dead)}),ut.sticks),doras:j(he(),ut.doras),front:j(We(Object.keys(ye)),ut.front)}),ut),Mr=Mt({...Rr.entries,board:xr}),es=n=>{const t=ns(n);return ss(t)},ns=n=>{const t=$r(n),e=Cr(Mr,t);if(!e.success)throw e.issues;return e.output},$r=n=>{const t="table",e="board",s=n.split(`
|
|
13
|
-
`).map(a=>a.trim()).filter(a=>a!="");if(s.length==0)throw new Error("empty input");const i=s.shift();if(!i.startsWith(t))throw new Error(`input does not start with table: ${i}`);const r={};let o=[E.E,E.S,E.W,E.N,e];for(;;){const a=s.shift();if(a==null)break;const c=o.find(l=>a.startsWith(l));if(c==null)throw new Error(`encountered unexpected line ${a}`);if(o=o.filter(l=>!a.startsWith(l)),c==e){const[l,h]=Hr([...s]);r.board=l;for(let u=0;u<h;u++)s.shift()}else{const[l,h]=Pr([...s]);r[c]=l;for(let u=0;u<h;u++)s.shift()}}return r},V=(n,t)=>n.replace(t,"").replace(":","").trim(),Pr=n=>{const t="hand",e="discard",s="score",i={};let r=0;for(;r<n.length;r++){const o=n[r];if(o.startsWith(t))i.hand=V(o,t);else if(o.startsWith(e))i.discard=V(o,e);else if(o.startsWith(s))i.score=Number(V(o,s));else break}return[i,r]},Hr=n=>{const t="doras",e="round",s="front",i="sticks",r="reach",o="dead",a={};let c=0;for(;c<n.length;c++){const l=n[c];if(l.startsWith(t))a.doras=V(l,t);else if(l.startsWith(e))a.round=V(l,e);else if(l.startsWith(s))a.front=V(l,s);else if(l.startsWith(i)){a.sticks={};const h=n[c+1]??"",u=n[c+2]??"";h.startsWith(r)&&(a.sticks.reach=Number(V(h,r))),h.startsWith(o)&&(a.sticks.dead=Number(V(h,o))),u.startsWith(r)&&(a.sticks.reach=Number(V(u,r))),u.startsWith(o)&&(a.sticks.dead=Number(V(u,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},ss=n=>{const t=n.board.front,e=Wr(t),s=a=>n[a].discard.replace(/\r?\n/g,""),i={front:new K(s(e.front)).tiles(),right:new K(s(e.right)).tiles(),opposite:new K(s(e.opposite)).tiles(),left:new K(s(e.left)).tiles()},r={front:new K(n[e.front].hand).parse(),right:new K(n[e.right].hand).parse(),opposite:new K(n[e.opposite].hand).parse(),left:new K(n[e.left].hand).parse()},o={round:Ve[n.board.round],frontPlace:ye[t],sticks:n.board.sticks,doras:new K(n.board.doras).tiles(),scores:{front:n[e.front].score,right:n[e.right].score,opposite:n[e.opposite].score,left:n[e.left].score}};return{discards:i,hands:r,scoreBoard:o}},Wr=n=>({front:n,right:bt(n),opposite:bt(bt(n)),left:me(n)});function*U(n){const t=n!=null&&n.filterBy&&n.filterBy.length>0?n==null?void 0:n.filterBy:Object.values(g);for(const e of t){if(n!=null&&n.skipBack&&e==g.BACK)continue;const s=e==g.Z?7:e==g.BACK?1:9;for(let i=1;i<=s;i++)yield[e,i]}}class _e{constructor(t,e=!1){_(this,"data");this.data={[g.M]:[0,0,0,0,0,0,0,0,0,0],[g.P]:[0,0,0,0,0,0,0,0,0,0],[g.S]:[0,0,0,0,0,0,0,0,0,0],[g.Z]:[0,0,0,0,0,0,0,0],[g.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const s=Array.isArray(t)?t:new K(t).parse();for(const i of s){if(i.isCalled()){this.data.called=[...this.called,i];continue}else if(i.is(b.TSUMO)){const r=i.tiles[0];this.inc([r]),this.data.tsumo=r;continue}else if(i.is(b.HAND)){this.inc(i.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(r=>r===g.BACK)){this.inc(i.tiles);continue}else if(e){this.inc(i.tiles);continue}throw new Error(`unexpected block ${i.type} ${i.toString()}`)}}get hands(){const t=[];for(const[e,s]of U()){let i=this.get(e,s);e!=g.Z&&s==5&&this.get(e,0)>0&&(i-=this.get(e,0),t.push(new w(e,s,[y.RED])));for(let r=0;r<i;r++)t.push(new w(e,s))}if(this.drawn!=null){const e=this.drawn,s=t.findIndex(i=>i.equals(e)&&e.has(y.RED)==i.has(y.RED));I(s>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[s]=t[s].clone({add:y.TSUMO})}return t}toString(){const t=this.called.length>0?`${nt}${this.called.join(nt)}`:"",e=this.drawn?`${nt}${this.drawn.toString()}`:"",s=this.hands.filter(r=>!r.has(y.TSUMO));return`${new Ct(s).toString()}${e}${t}`}get called(){return this.data.called}get reached(){return this.data.reached}get drawn(){return this.data.tsumo}get menzen(){return!this.called.some(t=>!(t instanceof M))}sum(t){let e=0;for(const[s,i]of U({filterBy:[t]}))e+=this.get(s,i);return e}get(t,e){return t==g.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const s of t){if(s.t!=g.BACK&&this.get(s.t,s.n)>=4||s.has(y.RED)&&this.get(s.t,0)>0)throw this.dec(e),new Error(`unable to increase ${s} in ${this.toString()}`);e.push(s),s.t==g.BACK?this.data[s.t][1]+=1:(this.data[s.t][s.n]+=1,s.has(y.RED)&&(this.data[s.t][0]+=1))}return e}dec(t){const e=[];for(const s of t){if(this.get(s.t,s.n)<1||s.has(y.RED)&&this.get(s.t,0)<=0)throw this.inc(e),new Error(`unable to decrease ${s.toString()} in ${this.toString()}`);if(e.push(s),s.t==g.BACK?this.data[s.t][1]-=1:(this.data[s.t][s.n]-=1,s.has(y.RED)&&(this.data[s.t][0]-=1)),x(s)&&this.get(s.t,5)==0&&this.get(s.t,0)>0){this.data[s.t][0]=0;const i=e.pop().clone({add:y.RED});e.push(i)}}return e}draw(t){const e=t.clone({add:y.TSUMO});this.inc([e]),this.data.tsumo=e}discard(t){this.dec([t]),this.data.tsumo=null}reach(){if(!this.menzen)throw new Error("cannot reach");if(this.data.reached)throw new Error("already reached");this.data.reached=!0}call(t){const e=t.tiles.filter(s=>!s.has(y.HORIZONTAL));if(e.length!=t.tiles.length-1)throw new Error(`removal: ${e} block: ${t}`);this.dec(e),this.data.called=[...this.called,t],this.data.tsumo=null}kan(t){if(t instanceof M){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof L){const e=this.data.called.findIndex(i=>i.is(b.PON)&&i.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let s=t.tiles[0];s=x(s)?s.clone({remove:y.RED}):s,this.dec([s]),this.data.called=[...this.called.slice(0,e),...this.called.slice(e+1),t],this.data.tsumo=null;return}throw new Error(`unexpected input ${t}`)}clone(){const t=new _e(this.toString());return t.data.reached=this.data.reached,t}}class qt{constructor(t){_(this,"hand");this.hand=t}calc(){return Math.min(this.sevenPairs(),this.thirteenOrphans(),this.fourSetsOnePair())}sevenPairs(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const[s,i]of U({skipBack:!0}))this.hand.get(s,i)==2&&t++,this.hand.get(s,i)==1&&e++;return t>7&&(t=7),t+e>=7&&(e=7-t),13-2*t-e}thirteenOrphans(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const s of Object.values(g)){if(s==g.BACK)continue;const i=s==g.Z?$t:J;for(const r of i)this.hand.get(s,r)>=1&&t++,this.hand.get(s,r)>=2&&e++}return e>=1?12-t:13-t}fourSetsOnePair(){const t=s=>{const i=[0,0,0];for(const[d,p]of U({filterBy:[g.Z]}))this.hand.get(d,p)>=3?i[0]++:this.hand.get(d,p)==2?i[1]++:this.hand.get(d,p)==1&&i[2]++;const r=[0,0,0],o=this.hand.get(g.BACK,0),a=o%3;r[0]=Math.floor(o/3),a==2?r[1]=1:a==1&&(r[2]=1);let c=13;const l=this.patternNumType(g.M),h=this.patternNumType(g.P),u=this.patternNumType(g.S);for(const d of[l.patternA,l.patternB])for(const p of[h.patternA,h.patternB])for(const f of[u.patternA,u.patternB]){const m=[this.hand.called.length,0,0];for(let S=0;S<3;S++)m[S]+=d[S]+p[S]+f[S]+i[S]+r[S];const A=this.calcCommon(m[0],m[1],m[2],s);A<c&&(c=A)}return c};let e=t(!1);for(const[s,i]of U())if(this.hand.get(s,i)>=2){const r=this.hand.dec(new Array(2).fill(new w(s,i))),o=t(!0);this.hand.inc(r),o<e&&(e=o)}return e}patternNumType(t,e=1){if(e>9)return this.groupRemainingTiles(t);let s=this.patternNumType(t,e+1);if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const i=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]),r=this.patternNumType(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<s.patternA[2]||r.patternA[2]==s.patternA[2]&&r.patternA[1]<s.patternA[1])&&(s.patternA=r.patternA),(r.patternB[0]>s.patternB[0]||r.patternB[0]==s.patternB[0]&&r.patternB[1]>s.patternB[1])&&(s.patternB=r.patternB)}if(this.hand.get(t,e)>=3){const i=this.hand.dec(new Array(3).fill(new w(t,e))),r=this.patternNumType(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<s.patternA[2]||r.patternA[2]==s.patternA[2]&&r.patternA[1]<s.patternA[1])&&(s.patternA=r.patternA),(r.patternB[0]>s.patternB[0]||r.patternB[0]==s.patternB[0]&&r.patternB[1]>s.patternB[1])&&(s.patternB=r.patternB)}return s}groupRemainingTiles(t){let e=0,s=0,i=0;for(const[r,o]of U({filterBy:[t]}))i+=this.hand.get(r,o),o<=7&&this.hand.get(r,o+1)==0&&this.hand.get(r,o+2)==0&&(e+=i>>1,s+=i%2,i=0);return e+=i>>1,s+=i%2,{patternA:[0,e,s],patternB:[0,e,s]}}calcCommon(t,e,s,i){let r=i?4:5;return t>4&&(e+=t-4,t=4),t+e>4&&(s+=t+e-4,e=4-t),t+e+s>r&&(s=r-t-e),i&&e++,13-t*3-e*2-s}}class is{constructor(t){_(this,"hand");this.hand=t}calc(t){return this.markDrawn([...this.sevenPairs(),...this.thirteenOrphans(),...this.nineGates(),...this.fourSetsOnePair()],t)}markDrawn(t,e){if(t.length==0)return[];const s=this.hand.drawn!=null||e.has(y.TSUMO)?y.TSUMO:y.RON,i=[];for(let o=0;o<t.length;o++){const a=t[o],c={};for(let l=0;l<a.length;l++){const h=a[l];if(h.isCalled())continue;const u=h.tiles.findIndex(p=>p.equals(e)&&e.has(y.RED)==p.has(y.RED));if(u<0)continue;const d=Ut(h);c[d]||(c[d]=!0,i.push([o,l,u]))}}if(i.length==0)throw new Error(`found no tile ${e.toString()} in hands ${t[0].toString()}`);const r=[];for(const[o,a,c]of i){const h=[...t[o]],u=h[a],d=u.tiles[c].clone({add:s});h[a]=u.clone({replace:{idx:c,tile:d}}),r.push(h)}return r}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,s]of U({skipBack:!0})){const i=this.hand.get(e,s);if(i==2){const r=this.hand.dec(new Array(2).fill(new w(e,s)));t.push(new D(r[0],r[1])),this.hand.inc(r)}else{if(i==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const s of Object.values(g)){if(s==g.BACK)continue;const i=s==g.Z?$t:J;for(let r of i)if(this.hand.get(s,r)==1)t.push(new Ye(new w(s,r)));else if(this.hand.get(s,r)==2&&e==!1)t.unshift(new D(new w(s,r),new w(s,r))),e=!0;else return[]}return[t]}nineGates(){const t=(e,s,i)=>i.includes(this.hand.get(e,s));for(const e of Object.values(g)){if(e==g.BACK||e==g.Z)continue;const s=t(e,1,[3,4])&&t(e,9,[3,4])&&t(e,2,[1,2])&&t(e,3,[1,2])&&t(e,4,[1,2])&&t(e,5,[1,2])&&t(e,6,[1,2])&&t(e,7,[1,2])&&t(e,8,[1,2]),i=this.hand.sum(e)==14;if(s&&i)return[[new Ct(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,s]of U())if(this.hand.get(e,s)>=2){const i=new Array(2).fill(new w(e,s));s==5&&this.hand.get(e,0)>0&&this.hand.get(e,s)>=3&&(i[1]=new w(e,s,[y.RED]));const r=this.hand.dec(i),o=this.patternAll().filter(a=>a.length==4).map(a=>(a.unshift(new D(r[0],r[1])),a));t=[...t,...o],this.hand.inc(r)}return t}patternAll(){return[this.addRedPattern(g.M,this.handleNumType(g.M)),this.addRedPattern(g.P,this.handleNumType(g.P)),this.addRedPattern(g.S,this.handleNumType(g.S)),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((s,i)=>i.length-s.length).reduce((s,i)=>i.length===0?s:s.flatMap(r=>i.map(o=>[...r,...o])),[[]])}handleBack(){const t=g.BACK,e=this.hand.get(t,0);if(e<3)return[];const s=new w(t,0),i=Array(Math.floor(e/3)).fill(new F([s,s,s]));return i.length==0?[]:[i]}handleZ(){const t=[];for(const[e,s]of U({filterBy:[g.Z]})){if(this.hand.get(e,s)==0)continue;if(this.hand.get(e,s)!=3)return[];const i=new w(e,s);t.push(new F([i,i,i]))}return t.length==0?[]:[t]}addRedPattern(t,e){if(!(this.hand.get(t,0)>0&&this.hand.get(t,5)>=2))return e;const s=new w(t,5),i=new w(t,5,[y.RED]),r=[],o=[];for(let c=0;c<e.length;c++){const l=e[c],h={};for(let u=0;u<l.length;u++){const d=l[u],p=d.tiles.findIndex(A=>A.equals(s)&&!A.has(y.RED)),f=d.tiles.findIndex(A=>A.equals(i)&&A.has(y.RED));if(f>-1&&o.push([c,u,f]),f>-1&&p>-1||p<0)continue;const m=Ut(d);h[m]||(h[m]=!0,r.push([c,u,p]))}}if(o.length==0)return e;const a=[];for(const[c,l,h]of r){const d=[...e[c]],p=d[l];d[l]=p.clone({replace:{idx:h,tile:i}});const f=o.find(A=>A[0]==c);if(f==null)continue;const m=d[f[1]];m==null&&console.error(f,r),d[f[1]]=m.clone({replace:{idx:f[2],tile:s}}),Ut(p)!=Ut(m)&&a.push(d)}return[...e,...a]}handleNumType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.handleNumType(t,e+1);const s=[];if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const i=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]);let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new st([i[0],i[1],i[2]])),s.push(o)}if(this.hand.get(t,e)==3){const i=this.hand.dec(new Array(3).fill(new w(t,e)));let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new F([i[0],i[1],i[2]])),s.push(o)}return s}}const $t=[1,2,3,4,5,6,7],J=[1,9],jt=n=>{var e;const t=n.boardContext;return{...n,hand:n.hand.map(O.deserialize),boardContext:{...t,doraIndicators:t.doraIndicators.map(w.from),hiddenDoraIndicators:(e=t.hiddenDoraIndicators)==null?void 0:e.map(w.from)}}},ue=n=>JSON.parse(JSON.stringify(n));class Be{constructor(t,e){_(this,"hand");_(this,"cfg");this.hand=t,this.cfg={doras:e.doraIndicators.map(s=>kn(s)),blindDoras:e.hiddenDoraIndicators==null?[]:e.hiddenDoraIndicators.map(s=>kn(s)),roundWind:w.from(e.round.substring(0,2)),myWind:w.from(e.myWind),reached:e.reached??0,sticks:e.sticks??{dead:0,reach:0},replacementWin:e.replacementWin??!1,quadWin:e.quadWin??!1,finalWallWin:e.finalWallWin??!1,finalDiscardWin:e.finalDiscardWin??!1,oneShotWin:e.oneShotWin??!1,enableRoundUp8000:e.enableRoundUp8000??!1,disableCountable32000:e.disableCountable32000??!1,disableDouble32000:e.disableDouble32000??!1,orig:e}}calc(...t){const e=this.calcPatterns(t);let s=!1,i=!1;if(e.length==0)return!1;let r=[0,0],o=0;for(let N=0;N<e.length;N++){const T=e[N];s=T.is32000??!1;const W=T.yakus.reduce(($,q)=>$+q.han,0);W>r[0]?(o=N,r=[W,T.fu]):W==r[0]&&T.fu>r[1]&&(o=N,r=[W,T.fu])}const a=(N,T=100)=>Math.ceil(N/T)*T,c=r[1]!=25?a(r[1],10):25,l=r[0];let h=Math.min(c*2**(l+2),2e3);switch(l){case 26:h=16e3;break;case 13:h=8e3;break;case 12:case 11:h=6e3;break;case 10:case 9:case 8:h=4e3;break;case 7:case 6:h=3e3;break;case 5:h=2e3;break}l>=13&&l<26&&e[o].yakus.every(N=>N.is32000==null||N.is32000==!1)&&(h=this.cfg.disableCountable32000?6e3:8e3,i=!this.cfg.disableCountable32000),this.cfg.enableRoundUp8000&&(c==30&&l==4||c==60&&l==3)&&(h=2e3);const u=e[o].hand.some(N=>N.tiles.some(T=>T.has(y.TSUMO))),d=this.cfg.orig.myWind,p=d==E.E;let f="";const m=H(0);if(u){const N=this.cfg.sticks.dead*100;if(p){const T=a(h*2);m[E.E]+=T*3+N*3,m[E.S]-=T+N,m[E.W]-=T+N,m[E.N]-=T+N,f=`${T}`}else{for(const T of Object.values(E)){if(T==d)continue;const W=T==E.E?2:1,$=a(h*W);m[T]-=$+N,m[d]+=$+N}f=`${a(h*1)}-${a(h*2)}`}}else{const N=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const $=a(h*(p?6:4))+N;m[d]+=$,m[this.cfg.orig.ronWind]-=$,f=`${$}`}const A=m[d]-this.cfg.sticks.dead*300;m[d]+=1e3*this.cfg.sticks.reach;let S;return s?S="役満":i?S="数え役満":h==2e3?S=`${c}符${l}飜 満貫${f}`:h==3e3?S=`${c}符${l}飜 跳満${f}`:h==4e3?S=`${c}符${l}飜 倍満${f}`:h==6e3?S=`${c}符${l}飜 三倍満${f}`:S=`${c}符${l}飜 ${f}`,{deltas:m,han:l,fu:c,yakus:e[o].yakus,point:m[d],rawPoint:A,hand:e[o].hand,boardContext:this.cfg.orig,description:S}}calcPatterns(t){const e=[];if(t.length==0)return e;for(const s of t){const i=[...this.dA13(s),...this.dB13(s),...this.dC13(s),...this.dD13(s),...this.dE13(s),...this.dF13(s),...this.dG13(s),...this.dH13(s),...this.dI13(s),...this.dJ13(s),...this.dK13(s)].map(r=>(this.cfg.disableDouble32000&&r.han>13&&(r.han=13),r));i.length!=0&&e.push({yakus:i,fu:30,hand:s,is32000:!0})}if(e.length>0)return e;for(const s of t){const i=this.calcFu(s),r=[...this.dA1(s),...this.dB1(s),...this.dC1(s),...this.dD1(s),...this.dE1(s),...this.dF1(s),...this.dG1(s),...this.dH1(s),...this.dI1(s),...this.dJ1(s),...this.dK1(s),...this.dA2(s),...this.dB2(s),...this.dC2(s),...this.dD2(s),...this.dE2(s),...this.dF2(s),...this.dG2(s),...this.dH2(s),...this.dI2(s),...this.dJ2(s),...this.dA3(s),...this.dB3(s),...this.dC3(s),...this.dA6(s)];r.length!=0&&(r.push(...this.dX1(s)),e.push({yakus:r,fu:i,hand:s}))}return e}minus(){return this.hand.menzen?0:1}dA1(t){return this.cfg.reached==1?[{name:"立直",han:1}]:this.cfg.reached==2?[{name:"ダブル立直",han:2}]:[]}dB1(t){return this.minus()!=0?[]:(this.hand.drawn==null,t.some(s=>s.tiles.some(i=>i.has(y.TSUMO)))?[{name:"門前清自摸和",han:1}]:[])}dC1(t){if(this.minus()!=0)return[];const e="平和",s=this.calcFu(t);return s==20?[{name:e,han:1}]:!t.some(i=>i.tiles.some(r=>r.has(y.TSUMO)))&&s==30?[{name:e,han:1}]:[]}dD1(t){return t.some(s=>s.tiles.some(i=>i.t==g.Z||J.includes(i.n)))?[]:[{name:"断么九",han:1}]}dE1(t){return this.minus()!=0?[]:On(t)==1?[{name:"一盃口",han:1}]:[]}dF1(t){const e=[];return t.forEach(s=>{if(s instanceof D)return;const i=s.tiles[0];i.t==g.Z&&(i.equals(this.cfg.myWind)&&e.push({name:"自風",han:1}),i.equals(this.cfg.roundWind)?e.push({name:"場風",han:1}):i.n==5?e.push({name:"白",han:1}):i.n==6?e.push({name:"發",han:1}):i.n==7&&e.push({name:"中",han:1}))}),e}dG1(t){return this.cfg.oneShotWin?[{name:"一発",han:1}]:[]}dH1(t){return this.cfg.replacementWin?[{name:"嶺上開花",han:1}]:[]}dI1(t){return this.cfg.quadWin?[{name:"搶槓",han:1}]:[]}dJ1(t){return this.cfg.finalWallWin?[{name:"海底摸月",han:1}]:[]}dK1(t){return this.cfg.finalDiscardWin?[{name:"河底撈魚",han:1}]:[]}dX1(t){let e=0,s=0,i=0;for(const o of t)for(const a of o.tiles){for(const c of this.cfg.doras)a.equals(c)&&e++;for(const c of this.cfg.blindDoras)a.equals(c)&&s++;a.has(y.RED)&&i++}const r=[];return e>0&&r.push({name:"ドラ",han:e}),i>0&&r.push({name:"赤ドラ",han:i}),this.hand.reached&&s>0&&r.push({name:"裏ドラ",han:s}),r}dA2(t){return t.length==7?[{name:"七対子",han:2}]:[]}dB2(t){const e=s=>s instanceof st||s instanceof Y;for(const s of t){if(!e(s))continue;const i=dt(s);if(i.t==g.Z)continue;const r=[g.M,g.P,g.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new w(r[0],i.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(r[1],i.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同順",han:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(s=>s instanceof M||s instanceof L||s instanceof et||s instanceof F||s instanceof X||s instanceof D)?[{name:"対々和",han:2}]:[]}dD2(t){return t.filter(s=>(s instanceof M||s instanceof F)&&!s.tiles.some(i=>i.has(y.RON))).length>=3?[{name:"三暗刻",han:2}]:[]}dE2(t){return t.filter(s=>s instanceof M||s instanceof L||s instanceof et).length>=3?[{name:"三槓子",han:2}]:[]}dF2(t){const e=s=>s instanceof M||s instanceof L||s instanceof et||s instanceof F||s instanceof X;for(const s of t){if(!e(s))continue;const i=dt(s);if(i.t==g.Z)continue;const r=[g.M,g.P,g.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new w(r[0],i.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(r[1],i.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同刻",han:2}]}return[]}dG2(t){return t.length==7?[]:t.filter(s=>{const i=s.tiles[0];return i.t==g.Z&&[5,6,7].includes(i.n)}).length==3?[{name:"小三元",han:2}]:[]}dH2(t){return t.every(s=>{const i=s.tiles[0].t==g.Z?$t:J;return s.tiles.every(r=>i.includes(r.n))})?[{name:"混老頭",han:2}]:[]}dI2(t){return t.length==7?[]:t.some(s=>s instanceof st||s instanceof Y)?t.some(s=>s.tiles[0].t==g.Z)?t.every(s=>{const i=s.tiles[0].t==g.Z?$t:J;return s.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",han:2-this.minus()}]:[]:[]:[]}dJ2(t){const e={[g.M]:[0,0,0],[g.S]:[0,0,0],[g.P]:[0,0,0]};for(const s of t){const i=dt(s);i.t!=g.BACK&&i.t!=g.Z&&(s instanceof st||s instanceof Y)&&(i.n==1?e[i.t][0]++:i.n==4?e[i.t][1]++:i.n==7&&e[i.t][2]++)}for(const s of Object.values(e))if(s[0]>0&&s[1]>0&&s[2]>0)return[{name:"一気通貫",han:2-this.minus()}];return[]}dA3(t){if(!t.some(s=>s.tiles[0].t==g.Z))return[];for(const s of Object.values(g))if(t.every(r=>r.tiles[0].t==g.Z||r.tiles[0].t==s))return[{name:"混一色",han:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(s=>s instanceof st||s instanceof Y)?t.some(s=>s.tiles[0].t==g.Z)?[]:t.every(s=>s.tiles.some(i=>J.includes(i.n)))?[{name:"純全帯么九色",han:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:On(t)==2?[{name:"ニ盃口",han:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==g.Z))return[];for(const e of Object.values(g)){if(e==g.Z)continue;if(t.every(i=>i.tiles[0].t==e))return[{name:"清一色",han:6-this.minus()}]}return[]}dA13(t){return t.length!=13?[]:t.some(s=>s instanceof D&&s.tiles.some(i=>i.has(y.TSUMO)||i.has(y.RON)))?[{name:"国士無双13面待ち",han:26,is32000:!0}]:[{name:"国士無双",han:13,is32000:!0}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",han:13,is32000:!0}]:[]}dC13(t){return t.length==7?[]:t.every(i=>i instanceof M||i instanceof F&&i.tiles.every(r=>!r.has(y.RON))||i instanceof D)?t.some(i=>i instanceof D&&i.tiles.some(r=>r.has(y.TSUMO)||r.has(y.RON)))?[{name:"四暗刻単騎待ち",han:26,is32000:!0}]:[{name:"四暗刻",han:13,is32000:!0}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(i=>!(i instanceof D)&&i.tiles.some(r=>r.t==g.Z&&e.includes(r.n))).length==3?[{name:"大三元",han:13,is32000:!0}]:[]}dE13(t){return t.every(s=>s.tiles[0].t==g.Z)?[{name:"字一色",han:13,is32000:!0}]:[]}dF13(t){return t.every(s=>s.tiles.every(i=>i.t!=g.Z&&J.includes(i.n)))?[{name:"清老頭",han:13,is32000:!0}]:[]}dG13(t){return t.filter(s=>s instanceof M||s instanceof L||s instanceof et).length==4?[{name:"四槓子",han:13,is32000:!0}]:[]}dH13(t){if(t.length==13)return[];if(t.length==7)return[];const e=[1,2,3,4];return t.filter(r=>r.tiles.some(o=>o.t==g.Z&&e.includes(o.n))).length==4?t.find(r=>r instanceof D).tiles.some(r=>r.t==g.Z&&e.includes(r.n))?[{name:"小四喜",han:13,is32000:!0}]:[{name:"大四喜",han:13,is32000:!0}]:[]}dI13(t){const e=s=>!!(s.equals(new w(g.Z,6))||s.t==g.S&&[2,3,4,6,8].includes(s.n));return t.every(s=>s.tiles.every(i=>e(i)))?[{name:"緑一色",han:13,is32000:!0}]:[]}dJ13(t){return[]}dK13(t){return[]}calcFu(t){let s=20;const i=this.cfg.myWind.n,r=this.cfg.roundWind.n;if(t.length==7)return 25;const o=t.find(f=>f.tiles.some(m=>m.has(y.TSUMO)||m.has(y.RON))),a=this.minus()==1,c=o.tiles.some(f=>f.has(y.TSUMO)),l=(f,m)=>{const A=f.tiles[0];return A.t==g.Z||J.includes(A.n)?m*2:m};for(const f of t)switch(!0){case f instanceof F:const m=f.tiles.some(A=>A.has(y.RON))?2:4;s+=l(f,m);break;case f instanceof X:s+=l(f,2);break;case(f instanceof et||f instanceof L):s+=l(f,8);break;case f instanceof M:s+=l(f,16);break}s+=(f=>{if(f instanceof F)return 0;if(f instanceof D)return 2;const m=f.tiles,A=m.findIndex(S=>S.has(y.TSUMO)||S.has(y.RON));return A==1||A==0&&m[2].n==9||A==2&&m[0].n==1?2:0})(o);const d=t.find(f=>f instanceof D).tiles[0];d.t==g.Z&&([5,6,7].includes(d.n)&&(s+=2),(d.n==r||d.n==i)&&(s+=2));let p=!1;return!a&&s==20&&(p=!0),c&&!p&&(s+=2),!c&&!a&&(s+=10),!c&&!a&&s==30&&(p=!0),a&&s==20&&(s=30),s}}const Ut=n=>n.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),On=n=>{const t={};for(const s of n){if(!(s instanceof st))continue;const i=Ut(s);t[i]==null?t[i]=1:t[i]++}let e=0;for(const s in t)t[s]>=2&&e++;return e},dt=n=>[...n.tiles].sort(Xt)[0],kn=n=>{const t=n.n,e=n.t;if(e==g.Z){if(t==4)return new w(e,1);if(t==7)return new w(e,5)}return new w(e,t%9+1)};class Pt{static calcCandidates(t,e,s){I(e.length>0,"choices to discard is zero");const i=new Map;let r=1/0;for(const o of e){const a=t.dec([o]),c=Pt.candidateTiles(t,s);t.inc(a);const l=s!=null&&s.arrangeRed&&o.has(y.RED)?o.clone({removeAll:!0}):o.has(y.RED)?o.clone({removeAll:!0,add:y.RED}):o.clone({removeAll:!0});c.shanten<r?(i.clear(),i.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l}),r=c.shanten):c.shanten==r&&i.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l})}return Array.from(i.values())}static candidateTiles(t,e){let s=1/0,i=[];const r=new qt(t);for(const[o,a]of U({skipBack:!0,filterBy:e==null?void 0:e.typeFilter})){if(t.get(o,a)>=4)continue;const c=new w(o,a),l=t.inc([c]),h=e!=null&&e.fourSetsOnePair?r.fourSetsOnePair():r.calc();t.dec(l),h<s?(s=h,i=[c]):h==s&&i.push(c)}return{shanten:s,candidates:i}}}const De=()=>{const n=new Set;return{on(t){n.add(t)},off(t){n.delete(t)},offAll(){n.clear()},emit(t){n.forEach(e=>e(t))}}};function rs(n){var r;const t=["RON","DAI_KAN","PON","CHI"],e=n.map(o=>o.choices),i=as(e,t).map(o=>n[o]);return{events:i,type:cs(t,(r=i[0])==null?void 0:r.choices)}}function os(n){var r;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=n.map(o=>o.choices),i=as(e,t).map(o=>n[o]);return{events:i,type:cs(t,(r=i[0])==null?void 0:r.choices)}}function as(n,t){let e=[],s=Number.POSITIVE_INFINITY;for(let i=0;i<n.length;i++){const r=n[i];if(Br(r,t)){const o=Dr(t,r);o<s?(s=o,e=[i]):o===s&&e.push(i)}}return e}function Br(n,t){return t.some(e=>!!n[e])}function Dr(n,t){for(let e=0;e<n.length;e++){const s=n[e];if(t[s])return e}return Number.POSITIVE_INFINITY}function cs(n,t){if(t==null)return!1;for(const e of n)if(t[e])return e;return!1}const Ft=()=>{const n=De(),t=De(),e={emit:n.emit,on:i=>t.on(i)},s={emit:t.emit,on:i=>n.on(i)};return[e,s]},ls=()=>{const n=De();return{emit:s=>{n.emit(s)},on:s=>{n.on(s)}}};class Vt{constructor(t){_(this,"reachValue",1e3);_(this,"m");this.m=structuredClone(t)}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}update(t,e){for(let s in e){const i=e[s],r=t[i];this.m[s]+=r}}}class Jt{constructor(t,e){_(this,"pToW",{});_(this,"wToP",H(""));_(this,"round");_(this,"sticks");this.round=(e==null?void 0:e.round)??C.E1,this.sticks=structuredClone(e==null?void 0:e.sticks)??{reach:0,dead:0},this.pToW=structuredClone(t);for(let s in this.pToW)this.wToP[this.pToW[s]]=s}update(){for(let t in this.pToW){const e=me(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Gt(this.round);this.round=t,this.update()}resetDeadStick(){this.sticks.dead=0}resetReachStick(){this.sticks.reach=0}is(t){return this.round==t}wind(t){return this.pToW[t]}playerID(t){return this.wToP[t]}get playerMap(){return structuredClone(this.pToW)}}function on(n){for(let t=n.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[n[t],n[e]]=[n[e],n[t]]}return n}class hs{constructor(t=!1){_(this,"c");_(this,"safeMap",H({},!0));this.disable=t,this.c=this.initial()}get(t){return t.t==g.BACK?0:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=g.BACK){if(this.get(e)<=0)throw new Error(`[counter] cannot decrease ${e.toString()} due to zero`);this.c[e.t][e.n]-=1,e.has(y.RED)&&(this.c[e.t][0]-=1)}}}addTileToSafeMap(t,e){this.disable||(this.safeMap[e][this.key(t.t,t.n)]=!0)}isSafeTile(t,e,s){return this.safeMap[s][this.key(t,e)]}key(t,e){return`${t}${e}`}reset(){this.c=this.initial()}initial(){return{[g.M]:[1,4,4,4,4,4,4,4,4,4],[g.S]:[1,4,4,4,4,4,4,4,4,4],[g.P]:[1,4,4,4,4,4,4,4,4,4],[g.Z]:[0,4,4,4,4,4,4,4]}}}class an{constructor(){_(this,"m",[])}discard(t,e){this.m.push({w:e,t})}discards(t){return t==null?[...this.m]:this.m.filter(e=>e.w==t)}get lastTile(){const t=this.m.at(-1);return I(t!=null,`lastTile is null(${t}). river: ${JSON.stringify(this.m,null,2)}`),t}markCalled(){this.lastTile.callMarker=!0}cannotContinue(){const t=this.discards();if(t.length!=4)return!1;let e=t[0].t;if(e.isNum())return!1;for(let s=0;s<4;s++)if(!e.equals(t[s].t))return!1;return!0}}function Kr(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function zr(){const n=Kr();if(n.__xstate__)return n.__xstate__}const Lr=n=>{if(typeof window>"u")return;const t=zr();t&&t.register(n)};class Cn{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current){this._last.next=e,this._last=e;return}this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const us=".",jr="",ds="",Ur="#",Fr="*",fs="xstate.init",Ke="xstate.stop";function Zr(n,t){return{type:`xstate.after.${n}.${t}`}}function ze(n,t){return{type:`xstate.done.state.${n}`,output:t}}function Gr(n,t){return{type:`xstate.done.actor.${n}`,output:t,actorId:n}}function Vr(n,t){return{type:`xstate.error.actor.${n}`,error:t,actorId:n}}function ps(n){return{type:fs,input:n}}function tt(n){setTimeout(()=>{throw n})}const Jr=typeof Symbol=="function"&&Symbol.observable||"@@observable";function gs(n,t){const e=Rn(n),s=Rn(t);return typeof s=="string"?typeof e=="string"?s===e:!1:typeof e=="string"?e in s:Object.keys(e).every(i=>i in s?gs(e[i],s[i]):!1)}function cn(n){if(ms(n))return n;const t=[];let e="";for(let s=0;s<n.length;s++){switch(n.charCodeAt(s)){case 92:e+=n[s+1],s++;continue;case 46:t.push(e),e="";continue}e+=n[s]}return t.push(e),t}function Rn(n){if(Co(n))return n.value;if(typeof n!="string")return n;const t=cn(n);return Yr(t)}function Yr(n){if(n.length===1)return n[0];const t={};let e=t;for(let s=0;s<n.length-1;s++)if(s===n.length-2)e[n[s]]=n[s+1];else{const i=e;e={},i[n[s]]=e}return t}function xn(n,t){const e={},s=Object.keys(n);for(let i=0;i<s.length;i++){const r=s[i];e[r]=t(n[r],r,n,i)}return e}function ys(n){return ms(n)?n:[n]}function rt(n){return n===void 0?[]:ys(n)}function Le(n,t,e,s){return typeof n=="function"?n({context:t,event:e,self:s}):n}function ms(n){return Array.isArray(n)}function Xr(n){return n.type.startsWith("xstate.error.actor")}function vt(n){return ys(n).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function ws(n){if(!(n===void 0||n===jr))return rt(n)}function je(n,t,e){var r,o,a;const s=typeof n=="object",i=s?n:void 0;return{next:(r=s?n.next:n)==null?void 0:r.bind(i),error:(o=s?n.error:t)==null?void 0:o.bind(i),complete:(a=s?n.complete:e)==null?void 0:a.bind(i)}}function Mn(n,t){return`${t}.${n}`}function ln(n,t){const e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return n.implementations.actors[t];const[,s,i]=e,o=n.getStateNodeById(i).config.invoke;return(Array.isArray(o)?o[s]:o).src}function $n(n,t){return`${n.sessionId}.${t}`}let qr=0;function Qr(n,t){const e=new Map,s=new Map,i=new WeakMap,r=new Set,o={},{clock:a,logger:c}=t,l={schedule:(d,p,f,m,A=Math.random().toString(36).slice(2))=>{const S={source:d,target:p,event:f,delay:m,id:A,startedAt:Date.now()},R=$n(d,A);u._snapshot._scheduledEvents[R]=S;const N=a.setTimeout(()=>{delete o[R],delete u._snapshot._scheduledEvents[R],u._relay(d,p,f)},m);o[R]=N},cancel:(d,p)=>{const f=$n(d,p),m=o[f];delete o[f],delete u._snapshot._scheduledEvents[f],m!==void 0&&a.clearTimeout(m)},cancelAll:d=>{for(const p in u._snapshot._scheduledEvents){const f=u._snapshot._scheduledEvents[p];f.source===d&&l.cancel(d,f.id)}}},h=d=>{if(!r.size)return;const p={...d,rootId:n.sessionId};r.forEach(f=>{var m;return(m=f.next)==null?void 0:m.call(f,p)})},u={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${qr++}`,_register:(d,p)=>(e.set(d,p),d),_unregister:d=>{e.delete(d.sessionId);const p=i.get(d);p!==void 0&&(s.delete(p),i.delete(d))},get:d=>s.get(d),_set:(d,p)=>{const f=s.get(d);if(f&&f!==p)throw new Error(`Actor with system ID '${d}' already exists.`);s.set(d,p),i.set(p,d)},inspect:d=>{const p=je(d);return r.add(p),{unsubscribe(){r.delete(p)}}},_sendInspectionEvent:h,_relay:(d,p,f)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:p,event:f}),p._send(f)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const d=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const p in d){const{source:f,target:m,event:A,delay:S,id:R}=d[p];l.schedule(f,m,A,S,R)}},_clock:a,_logger:c};return u}let Te=!1;const hn=1;let B=function(n){return n[n.NotStarted=0]="NotStarted",n[n.Running=1]="Running",n[n.Stopped=2]="Stopped",n}({});const to={clock:{setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:n=>clearTimeout(n)},logger:console.log.bind(console),devTools:!1};class eo{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Cn(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=B.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...to,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:h}=s;this.system=o?o.system:Qr(this,{clock:i,logger:r}),h&&!o&&this.system.inspect(je(h)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=(e==null?void 0:e.logger)??this.system._logger,this.clock=(e==null?void 0:e.clock)??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:u=>{this._deferred.push(u)},system:this.system,stopChild:u=>{if(u._parent!==this)throw new Error(`Cannot stop child actor ${u.id} of ${this.id} because it is not a child`);u._stop()},emit:u=>{const d=this.eventListeners.get(u.type),p=this.eventListeners.get("*");if(!d&&!p)return;const f=[...d?d.values():[],...p?p.values():[]];for(const m of f)m(u)},actionExecutor:u=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:u.type,params:u.params}}),!u.exec)return;const p=Te;try{Te=!0,u.exec(u.info,u.params)}finally{Te=p}};this._processingStatus===B.Running?d():this._deferred.push(d)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),l&&(this._systemId=l,this.system._set(l,this)),this._initState((e==null?void 0:e.snapshot)??(e==null?void 0:e.state)),l&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){var e;try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,(e=this.options)==null?void 0:e.input)}catch(s){this._snapshot={status:"error",output:void 0,error:s}}}update(t,e){var i,r;this._snapshot=t;let s;for(;s=this._deferred.shift();)try{s()}catch(o){this._deferred.length=0,this._snapshot={...t,status:"error",error:o}}switch(this._snapshot.status){case"active":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){tt(a)}break;case"done":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){tt(a)}this._stopProcedure(),this._complete(),this._doneEvent=Gr(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){var r;const i=je(t,e,s);if(this._processingStatus!==B.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{(r=i.complete)==null||r.call(i)}catch(o){tt(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)tt(o);else try{i.error(o)}catch(a){tt(a)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const i=e.bind(void 0);return s.add(i),{unsubscribe:()=>{s.delete(i)}}}start(){if(this._processingStatus===B.Running)return this;this._syncSnapshot&&this.subscribe({next:s=>{s.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:s})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=B.Running;const t=ps(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(s){return this._snapshot={...this._snapshot,status:"error",error:s},this._error(s),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){s={err:i}}if(s){const{err:i}=s;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(e,t),t.type===Ke&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===B.Stopped?this:(this.mailbox.clear(),this._processingStatus===B.NotStarted?(this._processingStatus=B.Stopped,this):(this.mailbox.enqueue({type:Ke}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var t;for(const e of this.observers)try{(t=e.complete)==null||t.call(e)}catch(s){tt(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||tt(t);return}let e=!1;for(const s of this.observers){const i=s.error;e||(e=!i);try{i==null||i(t)}catch(r){tt(r)}}this.observers.clear(),e&&tt(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Vr(this.id,t))}_stopProcedure(){return this._processingStatus!==B.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Cn(this._process.bind(this)),this._processingStatus=B.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==B.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:Lr)(this)}toJSON(){return{xstate$$type:hn,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Jr](){return this}getSnapshot(){return this._snapshot}}function Ht(n,...[t]){return new eo(n,t)}function no(n,t,e,s,{sendId:i}){const r=typeof i=="function"?i(e,s):i;return[t,{sendId:r},void 0]}function so(n,t){n.defer(()=>{n.system.scheduler.cancel(n.self,t.sendId)})}function io(n){function t(e,s){}return t.type="xstate.cancel",t.sendId=n,t.resolve=no,t.execute=so,t}function ro(n,t,e,s,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?ln(t.machine,o):o,h=typeof i=="function"?i(e):i;let u,d;return l&&(d=typeof a=="function"?a({context:t.context,event:e.event,self:n.self}):a,u=Ht(l,{id:h,src:o,parent:n.self,syncSnapshot:c,systemId:r,input:d})),[At(t,{children:{...t.children,[h]:u}}),{id:i,systemId:r,actorRef:u,src:o,input:d},void 0]}function oo(n,{actorRef:t}){t&&n.defer(()=>{t._processingStatus!==B.Stopped&&t.start()})}function ao(...[n,{id:t,systemId:e,input:s,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="xstate.spawnChild",r.id=t,r.systemId=e,r.src=n,r.input=s,r.syncSnapshot=i,r.resolve=ro,r.execute=oo,r}function co(n,t,e,s,{actorRef:i}){const r=typeof i=="function"?i(e,s):i,o=typeof r=="string"?t.children[r]:r;let a=t.children;return o&&(a={...a},delete a[o.id]),[At(t,{children:a}),o,void 0]}function lo(n,t){if(t){if(n.system._unregister(t),t._processingStatus!==B.Running){n.stopChild(t);return}n.defer(()=>{n.stopChild(t)})}}function bs(n){function t(e,s){}return t.type="xstate.stopChild",t.actorRef=n,t.resolve=co,t.execute=lo,t}function un(n,t,e,s){const{machine:i}=s,r=typeof n=="function",o=r?n:i.implementations.guards[typeof n=="string"?n:n.type];if(!r&&!o)throw new Error(`Guard '${typeof n=="string"?n:n.type}' is not implemented.'.`);if(typeof o!="function")return un(o,t,e,s);const a={context:t,event:e},c=r||typeof n=="string"?void 0:"params"in n?typeof n.params=="function"?n.params({context:t,event:e}):n.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}const dn=n=>n.type==="atomic"||n.type==="final";function Wt(n){return Object.values(n.states).filter(t=>t.type!=="history")}function Qt(n,t){const e=[];if(t===n)return e;let s=n.parent;for(;s&&s!==t;)e.push(s),s=s.parent;return e}function de(n){const t=new Set(n),e=Es(t);for(const s of t)if(s.type==="compound"&&(!e.get(s)||!e.get(s).length))Pn(s).forEach(i=>t.add(i));else if(s.type==="parallel"){for(const i of Wt(s))if(i.type!=="history"&&!t.has(i)){const r=Pn(i);for(const o of r)t.add(o)}}for(const s of t){let i=s.parent;for(;i;)t.add(i),i=i.parent}return t}function _s(n,t){const e=t.get(n);if(!e)return{};if(n.type==="compound"){const i=e[0];if(i){if(dn(i))return i.key}else return{}}const s={};for(const i of e)s[i.key]=_s(i,t);return s}function Es(n){const t=new Map;for(const e of n)t.has(e)||t.set(e,[]),e.parent&&(t.has(e.parent)||t.set(e.parent,[]),t.get(e.parent).push(e));return t}function As(n,t){const e=de(t);return _s(n,Es(e))}function fn(n,t){return t.type==="compound"?Wt(t).some(e=>e.type==="final"&&n.has(e)):t.type==="parallel"?Wt(t).every(e=>fn(n,e)):t.type==="final"}const Ee=n=>n[0]===Ur;function ho(n,t){return n.transitions.get(t)||[...n.transitions.keys()].filter(s=>{if(s===Fr)return!0;if(!s.endsWith(".*"))return!1;const i=s.split("."),r=t.split(".");for(let o=0;o<i.length;o++){const a=i[o],c=r[o];if(a==="*")return o===i.length-1;if(a!==c)return!1}return!0}).sort((s,i)=>i.length-s.length).flatMap(s=>n.transitions.get(s))}function uo(n){const t=n.config.after;if(!t)return[];const e=i=>{const r=Zr(i,n.id),o=r.type;return n.entry.push(Ko(r,{id:o,delay:i})),n.exit.push(io(o)),o};return Object.keys(t).flatMap(i=>{const r=t[i],o=typeof r=="string"?{target:r}:r,a=Number.isNaN(+i)?i:+i,c=e(a);return rt(o).map(l=>({...l,event:c,delay:a}))}).map(i=>{const{delay:r}=i;return{...yt(n,i.event,i),delay:r}})}function yt(n,t,e){const s=ws(e.target),i=e.reenter??!1,r=go(n,s),o={...e,actions:rt(e.actions),guard:e.guard,target:r,source:n,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${n.id}`,target:r?r.map(a=>`#${a.id}`):void 0})};return o}function fo(n){const t=new Map;if(n.config.on)for(const e of Object.keys(n.config.on)){if(e===ds)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=n.config.on[e];t.set(e,vt(s).map(i=>yt(n,e,i)))}if(n.config.onDone){const e=`xstate.done.state.${n.id}`;t.set(e,vt(n.config.onDone).map(s=>yt(n,e,s)))}for(const e of n.invoke){if(e.onDone){const s=`xstate.done.actor.${e.id}`;t.set(s,vt(e.onDone).map(i=>yt(n,s,i)))}if(e.onError){const s=`xstate.error.actor.${e.id}`;t.set(s,vt(e.onError).map(i=>yt(n,s,i)))}if(e.onSnapshot){const s=`xstate.snapshot.${e.id}`;t.set(s,vt(e.onSnapshot).map(i=>yt(n,s,i)))}}for(const e of n.after){let s=t.get(e.eventType);s||(s=[],t.set(e.eventType,s)),s.push(e)}return t}function po(n,t){const e=typeof t=="string"?n.states[t]:t?n.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${n.id}`);const s={source:n,actions:!t||typeof t=="string"?[]:rt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...s,source:`#${n.id}`,target:e?[`#${e.id}`]:[]})};return s}function go(n,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(Ee(e))return n.machine.getStateNodeById(e);const s=e[0]===us;if(s&&!n.parent)return fe(n,e.slice(1));const i=s?n.key+e:e;if(n.parent)try{return fe(n.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${n.id}':
|
|
13
|
+
`).map(a=>a.trim()).filter(a=>a!="");if(s.length==0)throw new Error("empty input");const i=s.shift();if(!i.startsWith(t))throw new Error(`input does not start with table: ${i}`);const r={};let o=[E.E,E.S,E.W,E.N,e];for(;;){const a=s.shift();if(a==null)break;const c=o.find(l=>a.startsWith(l));if(c==null)throw new Error(`encountered unexpected line ${a}`);if(o=o.filter(l=>!a.startsWith(l)),c==e){const[l,h]=Hr([...s]);r.board=l;for(let u=0;u<h;u++)s.shift()}else{const[l,h]=Pr([...s]);r[c]=l;for(let u=0;u<h;u++)s.shift()}}return r},V=(n,t)=>n.replace(t,"").replace(":","").trim(),Pr=n=>{const t="hand",e="discard",s="score",i={};let r=0;for(;r<n.length;r++){const o=n[r];if(o.startsWith(t))i.hand=V(o,t);else if(o.startsWith(e))i.discard=V(o,e);else if(o.startsWith(s))i.score=Number(V(o,s));else break}return[i,r]},Hr=n=>{const t="doras",e="round",s="front",i="sticks",r="reach",o="dead",a={};let c=0;for(;c<n.length;c++){const l=n[c];if(l.startsWith(t))a.doras=V(l,t);else if(l.startsWith(e))a.round=V(l,e);else if(l.startsWith(s))a.front=V(l,s);else if(l.startsWith(i)){a.sticks={};const h=n[c+1]??"",u=n[c+2]??"";h.startsWith(r)&&(a.sticks.reach=Number(V(h,r))),h.startsWith(o)&&(a.sticks.dead=Number(V(h,o))),u.startsWith(r)&&(a.sticks.reach=Number(V(u,r))),u.startsWith(o)&&(a.sticks.dead=Number(V(u,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},ss=n=>{const t=n.board.front,e=Wr(t),s=a=>n[a].discard.replace(/\r?\n/g,""),i={front:new K(s(e.front)).tiles(),right:new K(s(e.right)).tiles(),opposite:new K(s(e.opposite)).tiles(),left:new K(s(e.left)).tiles()},r={front:new K(n[e.front].hand).parse(),right:new K(n[e.right].hand).parse(),opposite:new K(n[e.opposite].hand).parse(),left:new K(n[e.left].hand).parse()},o={round:Ve[n.board.round],frontPlace:ye[t],sticks:n.board.sticks,doras:new K(n.board.doras).tiles(),scores:{front:n[e.front].score,right:n[e.right].score,opposite:n[e.opposite].score,left:n[e.left].score}};return{discards:i,hands:r,scoreBoard:o}},Wr=n=>({front:n,right:bt(n),opposite:bt(bt(n)),left:me(n)});function*U(n){const t=n!=null&&n.filterBy&&n.filterBy.length>0?n==null?void 0:n.filterBy:Object.values(g);for(const e of t){if(n!=null&&n.skipBack&&e==g.BACK)continue;const s=e==g.Z?7:e==g.BACK?1:9;for(let i=1;i<=s;i++)yield[e,i]}}class _e{constructor(t,e=!1){_(this,"data");this.data={[g.M]:[0,0,0,0,0,0,0,0,0,0],[g.P]:[0,0,0,0,0,0,0,0,0,0],[g.S]:[0,0,0,0,0,0,0,0,0,0],[g.Z]:[0,0,0,0,0,0,0,0],[g.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const s=Array.isArray(t)?t:new K(t).parse();for(const i of s){if(i.isCalled()){this.data.called=[...this.called,i];continue}else if(i.is(b.TSUMO)){const r=i.tiles[0];this.inc([r]),this.data.tsumo=r;continue}else if(i.is(b.HAND)){this.inc(i.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(r=>r===g.BACK)){this.inc(i.tiles);continue}else if(e){this.inc(i.tiles);continue}throw new Error(`unexpected block ${i.type} ${i.toString()}`)}}get hands(){const t=[];for(const[e,s]of U()){let i=this.get(e,s);e!=g.Z&&s==5&&this.get(e,0)>0&&(i-=this.get(e,0),t.push(new w(e,s,[y.RED])));for(let r=0;r<i;r++)t.push(new w(e,s))}if(this.drawn!=null){const e=this.drawn,s=t.findIndex(i=>i.equals(e)&&e.has(y.RED)==i.has(y.RED));I(s>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[s]=t[s].clone({add:y.TSUMO})}return t}toString(){const t=this.called.length>0?`${nt}${this.called.join(nt)}`:"",e=this.drawn?`${nt}${this.drawn.toString()}`:"",s=this.hands.filter(r=>!r.has(y.TSUMO));return`${new Ct(s).toString()}${e}${t}`}get called(){return this.data.called}get reached(){return this.data.reached}get drawn(){return this.data.tsumo}get menzen(){return!this.called.some(t=>!(t instanceof M))}sum(t){let e=0;for(const[s,i]of U({filterBy:[t]}))e+=this.get(s,i);return e}get(t,e){return t==g.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const s of t){if(s.t!=g.BACK&&this.get(s.t,s.n)>=4||s.has(y.RED)&&this.get(s.t,0)>0)throw this.dec(e),new Error(`unable to increase ${s} in ${this.toString()}`);e.push(s),s.t==g.BACK?this.data[s.t][1]+=1:(this.data[s.t][s.n]+=1,s.has(y.RED)&&(this.data[s.t][0]+=1))}return e}dec(t){const e=[];for(const s of t){if(this.get(s.t,s.n)<1||s.has(y.RED)&&this.get(s.t,0)<=0)throw this.inc(e),new Error(`unable to decrease ${s.toString()} in ${this.toString()}`);if(e.push(s),s.t==g.BACK?this.data[s.t][1]-=1:(this.data[s.t][s.n]-=1,s.has(y.RED)&&(this.data[s.t][0]-=1)),x(s)&&this.get(s.t,5)==0&&this.get(s.t,0)>0){this.data[s.t][0]=0;const i=e.pop().clone({add:y.RED});e.push(i)}}return e}draw(t){const e=t.clone({add:y.TSUMO});this.inc([e]),this.data.tsumo=e}discard(t){this.dec([t]),this.data.tsumo=null}reach(){if(!this.menzen)throw new Error("cannot reach");if(this.data.reached)throw new Error("already reached");this.data.reached=!0}call(t){const e=t.tiles.filter(s=>!s.has(y.HORIZONTAL));if(e.length!=t.tiles.length-1)throw new Error(`removal: ${e} block: ${t}`);this.dec(e),this.data.called=[...this.called,t],this.data.tsumo=null}kan(t){if(t instanceof M){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof L){const e=this.data.called.findIndex(i=>i.is(b.PON)&&i.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let s=t.tiles[0];s=x(s)?s.clone({remove:y.RED}):s,this.dec([s]),this.data.called=[...this.called.slice(0,e),...this.called.slice(e+1),t],this.data.tsumo=null;return}throw new Error(`unexpected input ${t}`)}clone(){const t=new _e(this.toString());return t.data.reached=this.data.reached,t}}class qt{constructor(t){_(this,"hand");this.hand=t}calc(){return Math.min(this.sevenPairs(),this.thirteenOrphans(),this.fourSetsOnePair())}sevenPairs(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const[s,i]of U({skipBack:!0}))this.hand.get(s,i)==2&&t++,this.hand.get(s,i)==1&&e++;return t>7&&(t=7),t+e>=7&&(e=7-t),13-2*t-e}thirteenOrphans(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const s of Object.values(g)){if(s==g.BACK)continue;const i=s==g.Z?$t:J;for(const r of i)this.hand.get(s,r)>=1&&t++,this.hand.get(s,r)>=2&&e++}return e>=1?12-t:13-t}fourSetsOnePair(){const t=s=>{const i=[0,0,0];for(const[d,p]of U({filterBy:[g.Z]}))this.hand.get(d,p)>=3?i[0]++:this.hand.get(d,p)==2?i[1]++:this.hand.get(d,p)==1&&i[2]++;const r=[0,0,0],o=this.hand.get(g.BACK,0),a=o%3;r[0]=Math.floor(o/3),a==2?r[1]=1:a==1&&(r[2]=1);let c=13;const l=this.patternNumType(g.M),h=this.patternNumType(g.P),u=this.patternNumType(g.S);for(const d of[l.patternA,l.patternB])for(const p of[h.patternA,h.patternB])for(const f of[u.patternA,u.patternB]){const m=[this.hand.called.length,0,0];for(let S=0;S<3;S++)m[S]+=d[S]+p[S]+f[S]+i[S]+r[S];const A=this.calcCommon(m[0],m[1],m[2],s);A<c&&(c=A)}return c};let e=t(!1);for(const[s,i]of U())if(this.hand.get(s,i)>=2){const r=this.hand.dec(new Array(2).fill(new w(s,i))),o=t(!0);this.hand.inc(r),o<e&&(e=o)}return e}patternNumType(t,e=1){if(e>9)return this.groupRemainingTiles(t);let s=this.patternNumType(t,e+1);if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const i=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]),r=this.patternNumType(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<s.patternA[2]||r.patternA[2]==s.patternA[2]&&r.patternA[1]<s.patternA[1])&&(s.patternA=r.patternA),(r.patternB[0]>s.patternB[0]||r.patternB[0]==s.patternB[0]&&r.patternB[1]>s.patternB[1])&&(s.patternB=r.patternB)}if(this.hand.get(t,e)>=3){const i=this.hand.dec(new Array(3).fill(new w(t,e))),r=this.patternNumType(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<s.patternA[2]||r.patternA[2]==s.patternA[2]&&r.patternA[1]<s.patternA[1])&&(s.patternA=r.patternA),(r.patternB[0]>s.patternB[0]||r.patternB[0]==s.patternB[0]&&r.patternB[1]>s.patternB[1])&&(s.patternB=r.patternB)}return s}groupRemainingTiles(t){let e=0,s=0,i=0;for(const[r,o]of U({filterBy:[t]}))i+=this.hand.get(r,o),o<=7&&this.hand.get(r,o+1)==0&&this.hand.get(r,o+2)==0&&(e+=i>>1,s+=i%2,i=0);return e+=i>>1,s+=i%2,{patternA:[0,e,s],patternB:[0,e,s]}}calcCommon(t,e,s,i){let r=i?4:5;return t>4&&(e+=t-4,t=4),t+e>4&&(s+=t+e-4,e=4-t),t+e+s>r&&(s=r-t-e),i&&e++,13-t*3-e*2-s}}class is{constructor(t){_(this,"hand");this.hand=t}calc(t){return this.markDrawn([...this.sevenPairs(),...this.thirteenOrphans(),...this.nineGates(),...this.fourSetsOnePair()],t)}markDrawn(t,e){if(t.length==0)return[];const s=this.hand.drawn!=null||e.has(y.TSUMO)?y.TSUMO:y.RON,i=[];for(let o=0;o<t.length;o++){const a=t[o],c={};for(let l=0;l<a.length;l++){const h=a[l];if(h.isCalled())continue;const u=h.tiles.findIndex(p=>p.equals(e)&&e.has(y.RED)==p.has(y.RED));if(u<0)continue;const d=Ut(h);c[d]||(c[d]=!0,i.push([o,l,u]))}}if(i.length==0)throw new Error(`found no tile ${e.toString()} in hands ${t[0].toString()}`);const r=[];for(const[o,a,c]of i){const h=[...t[o]],u=h[a],d=u.tiles[c].clone({add:s});h[a]=u.clone({replace:{idx:c,tile:d}}),r.push(h)}return r}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,s]of U({skipBack:!0})){const i=this.hand.get(e,s);if(i==2){const r=this.hand.dec(new Array(2).fill(new w(e,s)));t.push(new D(r[0],r[1])),this.hand.inc(r)}else{if(i==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const s of Object.values(g)){if(s==g.BACK)continue;const i=s==g.Z?$t:J;for(let r of i)if(this.hand.get(s,r)==1)t.push(new Ye(new w(s,r)));else if(this.hand.get(s,r)==2&&e==!1)t.unshift(new D(new w(s,r),new w(s,r))),e=!0;else return[]}return[t]}nineGates(){const t=(e,s,i)=>i.includes(this.hand.get(e,s));for(const e of Object.values(g)){if(e==g.BACK||e==g.Z)continue;const s=t(e,1,[3,4])&&t(e,9,[3,4])&&t(e,2,[1,2])&&t(e,3,[1,2])&&t(e,4,[1,2])&&t(e,5,[1,2])&&t(e,6,[1,2])&&t(e,7,[1,2])&&t(e,8,[1,2]),i=this.hand.sum(e)==14;if(s&&i)return[[new Ct(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,s]of U())if(this.hand.get(e,s)>=2){const i=new Array(2).fill(new w(e,s));s==5&&this.hand.get(e,0)>0&&this.hand.get(e,s)>=3&&(i[1]=new w(e,s,[y.RED]));const r=this.hand.dec(i),o=this.patternAll().filter(a=>a.length==4).map(a=>(a.unshift(new D(r[0],r[1])),a));t=[...t,...o],this.hand.inc(r)}return t}patternAll(){return[this.addRedPattern(g.M,this.handleNumType(g.M)),this.addRedPattern(g.P,this.handleNumType(g.P)),this.addRedPattern(g.S,this.handleNumType(g.S)),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((s,i)=>i.length-s.length).reduce((s,i)=>i.length===0?s:s.flatMap(r=>i.map(o=>[...r,...o])),[[]])}handleBack(){const t=g.BACK,e=this.hand.get(t,0);if(e<3)return[];const s=new w(t,0),i=Array(Math.floor(e/3)).fill(new F([s,s,s]));return i.length==0?[]:[i]}handleZ(){const t=[];for(const[e,s]of U({filterBy:[g.Z]})){if(this.hand.get(e,s)==0)continue;if(this.hand.get(e,s)!=3)return[];const i=new w(e,s);t.push(new F([i,i,i]))}return t.length==0?[]:[t]}addRedPattern(t,e){if(!(this.hand.get(t,0)>0&&this.hand.get(t,5)>=2))return e;const s=new w(t,5),i=new w(t,5,[y.RED]),r=[],o=[];for(let c=0;c<e.length;c++){const l=e[c],h={};for(let u=0;u<l.length;u++){const d=l[u],p=d.tiles.findIndex(A=>A.equals(s)&&!A.has(y.RED)),f=d.tiles.findIndex(A=>A.equals(i)&&A.has(y.RED));if(f>-1&&o.push([c,u,f]),f>-1&&p>-1||p<0)continue;const m=Ut(d);h[m]||(h[m]=!0,r.push([c,u,p]))}}if(o.length==0)return e;const a=[];for(const[c,l,h]of r){const d=[...e[c]],p=d[l];d[l]=p.clone({replace:{idx:h,tile:i}});const f=o.find(A=>A[0]==c);if(f==null)continue;const m=d[f[1]];m==null&&console.error(f,r),d[f[1]]=m.clone({replace:{idx:f[2],tile:s}}),Ut(p)!=Ut(m)&&a.push(d)}return[...e,...a]}handleNumType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.handleNumType(t,e+1);const s=[];if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const i=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]);let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new st([i[0],i[1],i[2]])),s.push(o)}if(this.hand.get(t,e)==3){const i=this.hand.dec(new Array(3).fill(new w(t,e)));let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new F([i[0],i[1],i[2]])),s.push(o)}return s}}const $t=[1,2,3,4,5,6,7],J=[1,9],jt=n=>{var e;const t=n.boardContext;return{...n,hand:n.hand.map(O.deserialize),boardContext:{...t,doraIndicators:t.doraIndicators.map(w.from),hiddenDoraIndicators:(e=t.hiddenDoraIndicators)==null?void 0:e.map(w.from)}}},ue=n=>JSON.parse(JSON.stringify(n));class Be{constructor(t,e){_(this,"hand");_(this,"cfg");this.hand=t,this.cfg={doras:e.doraIndicators.map(s=>kn(s)),blindDoras:e.hiddenDoraIndicators==null?[]:e.hiddenDoraIndicators.map(s=>kn(s)),roundWind:w.from(e.round.substring(0,2)),myWind:w.from(e.myWind),reached:e.reached??0,sticks:e.sticks??{dead:0,reach:0},replacementWin:e.replacementWin??!1,quadWin:e.quadWin??!1,finalWallWin:e.finalWallWin??!1,finalDiscardWin:e.finalDiscardWin??!1,oneShotWin:e.oneShotWin??!1,enableRoundUp8000:e.enableRoundUp8000??!1,disableCountable32000:e.disableCountable32000??!1,disableDouble32000:e.disableDouble32000??!1,orig:e}}calc(...t){const e=this.calcPatterns(t);let s=!1,i=!1;if(e.length==0)return!1;let r=[0,0],o=0;for(let N=0;N<e.length;N++){const T=e[N];s=T.is32000??!1;const W=T.yakus.reduce(($,q)=>$+q.han,0);W>r[0]?(o=N,r=[W,T.fu]):W==r[0]&&T.fu>r[1]&&(o=N,r=[W,T.fu])}const a=(N,T=100)=>Math.ceil(N/T)*T,c=r[1]!=25?a(r[1],10):25,l=r[0];let h=Math.min(c*2**(l+2),2e3);switch(l){case 26:h=16e3;break;case 13:h=8e3;break;case 12:case 11:h=6e3;break;case 10:case 9:case 8:h=4e3;break;case 7:case 6:h=3e3;break;case 5:h=2e3;break}l>=13&&l<26&&e[o].yakus.every(N=>N.is32000==null||N.is32000==!1)&&(h=this.cfg.disableCountable32000?6e3:8e3,i=!this.cfg.disableCountable32000),this.cfg.enableRoundUp8000&&(c==30&&l==4||c==60&&l==3)&&(h=2e3);const u=e[o].hand.some(N=>N.tiles.some(T=>T.has(y.TSUMO))),d=this.cfg.orig.myWind,p=d==E.E;let f="";const m=H(0);if(u){const N=this.cfg.sticks.dead*100;if(p){const T=a(h*2);m[E.E]+=T*3+N*3,m[E.S]-=T+N,m[E.W]-=T+N,m[E.N]-=T+N,f=`${T}`}else{for(const T of Object.values(E)){if(T==d)continue;const W=T==E.E?2:1,$=a(h*W);m[T]-=$+N,m[d]+=$+N}f=`${a(h*1)}-${a(h*2)}`}}else{const N=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const $=a(h*(p?6:4))+N;m[d]+=$,m[this.cfg.orig.ronWind]-=$,f=`${$}`}const A=m[d]-this.cfg.sticks.dead*300;m[d]+=1e3*this.cfg.sticks.reach;let S;return s?S="役満":i?S="数え役満":h==2e3?S=`${c}符${l}飜 満貫${f}`:h==3e3?S=`${c}符${l}飜 跳満${f}`:h==4e3?S=`${c}符${l}飜 倍満${f}`:h==6e3?S=`${c}符${l}飜 三倍満${f}`:S=`${c}符${l}飜 ${f}`,{deltas:m,han:l,fu:c,yakus:e[o].yakus,points:m[d],rawPoints:A,hand:e[o].hand,boardContext:this.cfg.orig,description:S}}calcPatterns(t){const e=[];if(t.length==0)return e;for(const s of t){const i=[...this.dA13(s),...this.dB13(s),...this.dC13(s),...this.dD13(s),...this.dE13(s),...this.dF13(s),...this.dG13(s),...this.dH13(s),...this.dI13(s),...this.dJ13(s),...this.dK13(s)].map(r=>(this.cfg.disableDouble32000&&r.han>13&&(r.han=13),r));i.length!=0&&e.push({yakus:i,fu:30,hand:s,is32000:!0})}if(e.length>0)return e;for(const s of t){const i=this.calcFu(s),r=[...this.dA1(s),...this.dB1(s),...this.dC1(s),...this.dD1(s),...this.dE1(s),...this.dF1(s),...this.dG1(s),...this.dH1(s),...this.dI1(s),...this.dJ1(s),...this.dK1(s),...this.dA2(s),...this.dB2(s),...this.dC2(s),...this.dD2(s),...this.dE2(s),...this.dF2(s),...this.dG2(s),...this.dH2(s),...this.dI2(s),...this.dJ2(s),...this.dA3(s),...this.dB3(s),...this.dC3(s),...this.dA6(s)];r.length!=0&&(r.push(...this.dX1(s)),e.push({yakus:r,fu:i,hand:s}))}return e}minus(){return this.hand.menzen?0:1}dA1(t){return this.cfg.reached==1?[{name:"立直",han:1}]:this.cfg.reached==2?[{name:"ダブル立直",han:2}]:[]}dB1(t){return this.minus()!=0?[]:(this.hand.drawn==null,t.some(s=>s.tiles.some(i=>i.has(y.TSUMO)))?[{name:"門前清自摸和",han:1}]:[])}dC1(t){if(this.minus()!=0)return[];const e="平和",s=this.calcFu(t);return s==20?[{name:e,han:1}]:!t.some(i=>i.tiles.some(r=>r.has(y.TSUMO)))&&s==30?[{name:e,han:1}]:[]}dD1(t){return t.some(s=>s.tiles.some(i=>i.t==g.Z||J.includes(i.n)))?[]:[{name:"断么九",han:1}]}dE1(t){return this.minus()!=0?[]:On(t)==1?[{name:"一盃口",han:1}]:[]}dF1(t){const e=[];return t.forEach(s=>{if(s instanceof D)return;const i=s.tiles[0];i.t==g.Z&&(i.equals(this.cfg.myWind)&&e.push({name:"自風",han:1}),i.equals(this.cfg.roundWind)?e.push({name:"場風",han:1}):i.n==5?e.push({name:"白",han:1}):i.n==6?e.push({name:"發",han:1}):i.n==7&&e.push({name:"中",han:1}))}),e}dG1(t){return this.cfg.oneShotWin?[{name:"一発",han:1}]:[]}dH1(t){return this.cfg.replacementWin?[{name:"嶺上開花",han:1}]:[]}dI1(t){return this.cfg.quadWin?[{name:"搶槓",han:1}]:[]}dJ1(t){return this.cfg.finalWallWin?[{name:"海底摸月",han:1}]:[]}dK1(t){return this.cfg.finalDiscardWin?[{name:"河底撈魚",han:1}]:[]}dX1(t){let e=0,s=0,i=0;for(const o of t)for(const a of o.tiles){for(const c of this.cfg.doras)a.equals(c)&&e++;for(const c of this.cfg.blindDoras)a.equals(c)&&s++;a.has(y.RED)&&i++}const r=[];return e>0&&r.push({name:"ドラ",han:e}),i>0&&r.push({name:"赤ドラ",han:i}),this.hand.reached&&s>0&&r.push({name:"裏ドラ",han:s}),r}dA2(t){return t.length==7?[{name:"七対子",han:2}]:[]}dB2(t){const e=s=>s instanceof st||s instanceof Y;for(const s of t){if(!e(s))continue;const i=dt(s);if(i.t==g.Z)continue;const r=[g.M,g.P,g.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new w(r[0],i.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(r[1],i.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同順",han:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(s=>s instanceof M||s instanceof L||s instanceof et||s instanceof F||s instanceof X||s instanceof D)?[{name:"対々和",han:2}]:[]}dD2(t){return t.filter(s=>(s instanceof M||s instanceof F)&&!s.tiles.some(i=>i.has(y.RON))).length>=3?[{name:"三暗刻",han:2}]:[]}dE2(t){return t.filter(s=>s instanceof M||s instanceof L||s instanceof et).length>=3?[{name:"三槓子",han:2}]:[]}dF2(t){const e=s=>s instanceof M||s instanceof L||s instanceof et||s instanceof F||s instanceof X;for(const s of t){if(!e(s))continue;const i=dt(s);if(i.t==g.Z)continue;const r=[g.M,g.P,g.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new w(r[0],i.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(r[1],i.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同刻",han:2}]}return[]}dG2(t){return t.length==7?[]:t.filter(s=>{const i=s.tiles[0];return i.t==g.Z&&[5,6,7].includes(i.n)}).length==3?[{name:"小三元",han:2}]:[]}dH2(t){return t.every(s=>{const i=s.tiles[0].t==g.Z?$t:J;return s.tiles.every(r=>i.includes(r.n))})?[{name:"混老頭",han:2}]:[]}dI2(t){return t.length==7?[]:t.some(s=>s instanceof st||s instanceof Y)?t.some(s=>s.tiles[0].t==g.Z)?t.every(s=>{const i=s.tiles[0].t==g.Z?$t:J;return s.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",han:2-this.minus()}]:[]:[]:[]}dJ2(t){const e={[g.M]:[0,0,0],[g.S]:[0,0,0],[g.P]:[0,0,0]};for(const s of t){const i=dt(s);i.t!=g.BACK&&i.t!=g.Z&&(s instanceof st||s instanceof Y)&&(i.n==1?e[i.t][0]++:i.n==4?e[i.t][1]++:i.n==7&&e[i.t][2]++)}for(const s of Object.values(e))if(s[0]>0&&s[1]>0&&s[2]>0)return[{name:"一気通貫",han:2-this.minus()}];return[]}dA3(t){if(!t.some(s=>s.tiles[0].t==g.Z))return[];for(const s of Object.values(g))if(t.every(r=>r.tiles[0].t==g.Z||r.tiles[0].t==s))return[{name:"混一色",han:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(s=>s instanceof st||s instanceof Y)?t.some(s=>s.tiles[0].t==g.Z)?[]:t.every(s=>s.tiles.some(i=>J.includes(i.n)))?[{name:"純全帯么九色",han:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:On(t)==2?[{name:"ニ盃口",han:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==g.Z))return[];for(const e of Object.values(g)){if(e==g.Z)continue;if(t.every(i=>i.tiles[0].t==e))return[{name:"清一色",han:6-this.minus()}]}return[]}dA13(t){return t.length!=13?[]:t.some(s=>s instanceof D&&s.tiles.some(i=>i.has(y.TSUMO)||i.has(y.RON)))?[{name:"国士無双13面待ち",han:26,is32000:!0}]:[{name:"国士無双",han:13,is32000:!0}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",han:13,is32000:!0}]:[]}dC13(t){return t.length==7?[]:t.every(i=>i instanceof M||i instanceof F&&i.tiles.every(r=>!r.has(y.RON))||i instanceof D)?t.some(i=>i instanceof D&&i.tiles.some(r=>r.has(y.TSUMO)||r.has(y.RON)))?[{name:"四暗刻単騎待ち",han:26,is32000:!0}]:[{name:"四暗刻",han:13,is32000:!0}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(i=>!(i instanceof D)&&i.tiles.some(r=>r.t==g.Z&&e.includes(r.n))).length==3?[{name:"大三元",han:13,is32000:!0}]:[]}dE13(t){return t.every(s=>s.tiles[0].t==g.Z)?[{name:"字一色",han:13,is32000:!0}]:[]}dF13(t){return t.every(s=>s.tiles.every(i=>i.t!=g.Z&&J.includes(i.n)))?[{name:"清老頭",han:13,is32000:!0}]:[]}dG13(t){return t.filter(s=>s instanceof M||s instanceof L||s instanceof et).length==4?[{name:"四槓子",han:13,is32000:!0}]:[]}dH13(t){if(t.length==13)return[];if(t.length==7)return[];const e=[1,2,3,4];return t.filter(r=>r.tiles.some(o=>o.t==g.Z&&e.includes(o.n))).length==4?t.find(r=>r instanceof D).tiles.some(r=>r.t==g.Z&&e.includes(r.n))?[{name:"小四喜",han:13,is32000:!0}]:[{name:"大四喜",han:13,is32000:!0}]:[]}dI13(t){const e=s=>!!(s.equals(new w(g.Z,6))||s.t==g.S&&[2,3,4,6,8].includes(s.n));return t.every(s=>s.tiles.every(i=>e(i)))?[{name:"緑一色",han:13,is32000:!0}]:[]}dJ13(t){return[]}dK13(t){return[]}calcFu(t){let s=20;const i=this.cfg.myWind.n,r=this.cfg.roundWind.n;if(t.length==7)return 25;const o=t.find(f=>f.tiles.some(m=>m.has(y.TSUMO)||m.has(y.RON))),a=this.minus()==1,c=o.tiles.some(f=>f.has(y.TSUMO)),l=(f,m)=>{const A=f.tiles[0];return A.t==g.Z||J.includes(A.n)?m*2:m};for(const f of t)switch(!0){case f instanceof F:const m=f.tiles.some(A=>A.has(y.RON))?2:4;s+=l(f,m);break;case f instanceof X:s+=l(f,2);break;case(f instanceof et||f instanceof L):s+=l(f,8);break;case f instanceof M:s+=l(f,16);break}s+=(f=>{if(f instanceof F)return 0;if(f instanceof D)return 2;const m=f.tiles,A=m.findIndex(S=>S.has(y.TSUMO)||S.has(y.RON));return A==1||A==0&&m[2].n==9||A==2&&m[0].n==1?2:0})(o);const d=t.find(f=>f instanceof D).tiles[0];d.t==g.Z&&([5,6,7].includes(d.n)&&(s+=2),(d.n==r||d.n==i)&&(s+=2));let p=!1;return!a&&s==20&&(p=!0),c&&!p&&(s+=2),!c&&!a&&(s+=10),!c&&!a&&s==30&&(p=!0),a&&s==20&&(s=30),s}}const Ut=n=>n.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),On=n=>{const t={};for(const s of n){if(!(s instanceof st))continue;const i=Ut(s);t[i]==null?t[i]=1:t[i]++}let e=0;for(const s in t)t[s]>=2&&e++;return e},dt=n=>[...n.tiles].sort(Xt)[0],kn=n=>{const t=n.n,e=n.t;if(e==g.Z){if(t==4)return new w(e,1);if(t==7)return new w(e,5)}return new w(e,t%9+1)};class Pt{static calcCandidates(t,e,s){I(e.length>0,"choices to discard is zero");const i=new Map;let r=1/0;for(const o of e){const a=t.dec([o]),c=Pt.candidateTiles(t,s);t.inc(a);const l=s!=null&&s.arrangeRed&&o.has(y.RED)?o.clone({removeAll:!0}):o.has(y.RED)?o.clone({removeAll:!0,add:y.RED}):o.clone({removeAll:!0});c.shanten<r?(i.clear(),i.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l}),r=c.shanten):c.shanten==r&&i.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l})}return Array.from(i.values())}static candidateTiles(t,e){let s=1/0,i=[];const r=new qt(t);for(const[o,a]of U({skipBack:!0,filterBy:e==null?void 0:e.typeFilter})){if(t.get(o,a)>=4)continue;const c=new w(o,a),l=t.inc([c]),h=e!=null&&e.fourSetsOnePair?r.fourSetsOnePair():r.calc();t.dec(l),h<s?(s=h,i=[c]):h==s&&i.push(c)}return{shanten:s,candidates:i}}}const De=()=>{const n=new Set;return{on(t){n.add(t)},off(t){n.delete(t)},offAll(){n.clear()},emit(t){n.forEach(e=>e(t))}}};function rs(n){var r;const t=["RON","DAI_KAN","PON","CHI"],e=n.map(o=>o.choices),i=as(e,t).map(o=>n[o]);return{events:i,type:cs(t,(r=i[0])==null?void 0:r.choices)}}function os(n){var r;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=n.map(o=>o.choices),i=as(e,t).map(o=>n[o]);return{events:i,type:cs(t,(r=i[0])==null?void 0:r.choices)}}function as(n,t){let e=[],s=Number.POSITIVE_INFINITY;for(let i=0;i<n.length;i++){const r=n[i];if(Br(r,t)){const o=Dr(t,r);o<s?(s=o,e=[i]):o===s&&e.push(i)}}return e}function Br(n,t){return t.some(e=>!!n[e])}function Dr(n,t){for(let e=0;e<n.length;e++){const s=n[e];if(t[s])return e}return Number.POSITIVE_INFINITY}function cs(n,t){if(t==null)return!1;for(const e of n)if(t[e])return e;return!1}const Ft=()=>{const n=De(),t=De(),e={emit:n.emit,on:i=>t.on(i)},s={emit:t.emit,on:i=>n.on(i)};return[e,s]},ls=()=>{const n=De();return{emit:s=>{n.emit(s)},on:s=>{n.on(s)}}};class Vt{constructor(t){_(this,"reachValue",1e3);_(this,"m");this.m=structuredClone(t)}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}update(t,e){for(let s in e){const i=e[s],r=t[i];this.m[s]+=r}}}class Jt{constructor(t,e){_(this,"pToW",{});_(this,"wToP",H(""));_(this,"round");_(this,"sticks");this.round=(e==null?void 0:e.round)??C.E1,this.sticks=structuredClone(e==null?void 0:e.sticks)??{reach:0,dead:0},this.pToW=structuredClone(t);for(let s in this.pToW)this.wToP[this.pToW[s]]=s}update(){for(let t in this.pToW){const e=me(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Gt(this.round);this.round=t,this.update()}resetDeadStick(){this.sticks.dead=0}resetReachStick(){this.sticks.reach=0}is(t){return this.round==t}wind(t){return this.pToW[t]}playerID(t){return this.wToP[t]}get playerMap(){return structuredClone(this.pToW)}}function on(n){for(let t=n.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[n[t],n[e]]=[n[e],n[t]]}return n}class hs{constructor(t=!1){_(this,"c");_(this,"safeMap",H({},!0));this.disable=t,this.c=this.initial()}get(t){return t.t==g.BACK?0:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=g.BACK){if(this.get(e)<=0)throw new Error(`[counter] cannot decrease ${e.toString()} due to zero`);this.c[e.t][e.n]-=1,e.has(y.RED)&&(this.c[e.t][0]-=1)}}}addTileToSafeMap(t,e){this.disable||(this.safeMap[e][this.key(t.t,t.n)]=!0)}isSafeTile(t,e,s){return this.safeMap[s][this.key(t,e)]}key(t,e){return`${t}${e}`}reset(){this.c=this.initial()}initial(){return{[g.M]:[1,4,4,4,4,4,4,4,4,4],[g.S]:[1,4,4,4,4,4,4,4,4,4],[g.P]:[1,4,4,4,4,4,4,4,4,4],[g.Z]:[0,4,4,4,4,4,4,4]}}}class an{constructor(){_(this,"m",[])}discard(t,e){this.m.push({w:e,t})}discards(t){return t==null?[...this.m]:this.m.filter(e=>e.w==t)}get lastTile(){const t=this.m.at(-1);return I(t!=null,`lastTile is null(${t}). river: ${JSON.stringify(this.m,null,2)}`),t}markCalled(){this.lastTile.callMarker=!0}cannotContinue(){const t=this.discards();if(t.length!=4)return!1;let e=t[0].t;if(e.isNum())return!1;for(let s=0;s<4;s++)if(!e.equals(t[s].t))return!1;return!0}}function Kr(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function zr(){const n=Kr();if(n.__xstate__)return n.__xstate__}const Lr=n=>{if(typeof window>"u")return;const t=zr();t&&t.register(n)};class Cn{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current){this._last.next=e,this._last=e;return}this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const us=".",jr="",ds="",Ur="#",Fr="*",fs="xstate.init",Ke="xstate.stop";function Zr(n,t){return{type:`xstate.after.${n}.${t}`}}function ze(n,t){return{type:`xstate.done.state.${n}`,output:t}}function Gr(n,t){return{type:`xstate.done.actor.${n}`,output:t,actorId:n}}function Vr(n,t){return{type:`xstate.error.actor.${n}`,error:t,actorId:n}}function ps(n){return{type:fs,input:n}}function tt(n){setTimeout(()=>{throw n})}const Jr=typeof Symbol=="function"&&Symbol.observable||"@@observable";function gs(n,t){const e=Rn(n),s=Rn(t);return typeof s=="string"?typeof e=="string"?s===e:!1:typeof e=="string"?e in s:Object.keys(e).every(i=>i in s?gs(e[i],s[i]):!1)}function cn(n){if(ms(n))return n;const t=[];let e="";for(let s=0;s<n.length;s++){switch(n.charCodeAt(s)){case 92:e+=n[s+1],s++;continue;case 46:t.push(e),e="";continue}e+=n[s]}return t.push(e),t}function Rn(n){if(Co(n))return n.value;if(typeof n!="string")return n;const t=cn(n);return Yr(t)}function Yr(n){if(n.length===1)return n[0];const t={};let e=t;for(let s=0;s<n.length-1;s++)if(s===n.length-2)e[n[s]]=n[s+1];else{const i=e;e={},i[n[s]]=e}return t}function xn(n,t){const e={},s=Object.keys(n);for(let i=0;i<s.length;i++){const r=s[i];e[r]=t(n[r],r,n,i)}return e}function ys(n){return ms(n)?n:[n]}function rt(n){return n===void 0?[]:ys(n)}function Le(n,t,e,s){return typeof n=="function"?n({context:t,event:e,self:s}):n}function ms(n){return Array.isArray(n)}function Xr(n){return n.type.startsWith("xstate.error.actor")}function vt(n){return ys(n).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function ws(n){if(!(n===void 0||n===jr))return rt(n)}function je(n,t,e){var r,o,a;const s=typeof n=="object",i=s?n:void 0;return{next:(r=s?n.next:n)==null?void 0:r.bind(i),error:(o=s?n.error:t)==null?void 0:o.bind(i),complete:(a=s?n.complete:e)==null?void 0:a.bind(i)}}function Mn(n,t){return`${t}.${n}`}function ln(n,t){const e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return n.implementations.actors[t];const[,s,i]=e,o=n.getStateNodeById(i).config.invoke;return(Array.isArray(o)?o[s]:o).src}function $n(n,t){return`${n.sessionId}.${t}`}let qr=0;function Qr(n,t){const e=new Map,s=new Map,i=new WeakMap,r=new Set,o={},{clock:a,logger:c}=t,l={schedule:(d,p,f,m,A=Math.random().toString(36).slice(2))=>{const S={source:d,target:p,event:f,delay:m,id:A,startedAt:Date.now()},R=$n(d,A);u._snapshot._scheduledEvents[R]=S;const N=a.setTimeout(()=>{delete o[R],delete u._snapshot._scheduledEvents[R],u._relay(d,p,f)},m);o[R]=N},cancel:(d,p)=>{const f=$n(d,p),m=o[f];delete o[f],delete u._snapshot._scheduledEvents[f],m!==void 0&&a.clearTimeout(m)},cancelAll:d=>{for(const p in u._snapshot._scheduledEvents){const f=u._snapshot._scheduledEvents[p];f.source===d&&l.cancel(d,f.id)}}},h=d=>{if(!r.size)return;const p={...d,rootId:n.sessionId};r.forEach(f=>{var m;return(m=f.next)==null?void 0:m.call(f,p)})},u={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${qr++}`,_register:(d,p)=>(e.set(d,p),d),_unregister:d=>{e.delete(d.sessionId);const p=i.get(d);p!==void 0&&(s.delete(p),i.delete(d))},get:d=>s.get(d),_set:(d,p)=>{const f=s.get(d);if(f&&f!==p)throw new Error(`Actor with system ID '${d}' already exists.`);s.set(d,p),i.set(p,d)},inspect:d=>{const p=je(d);return r.add(p),{unsubscribe(){r.delete(p)}}},_sendInspectionEvent:h,_relay:(d,p,f)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:p,event:f}),p._send(f)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const d=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const p in d){const{source:f,target:m,event:A,delay:S,id:R}=d[p];l.schedule(f,m,A,S,R)}},_clock:a,_logger:c};return u}let Te=!1;const hn=1;let B=function(n){return n[n.NotStarted=0]="NotStarted",n[n.Running=1]="Running",n[n.Stopped=2]="Stopped",n}({});const to={clock:{setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:n=>clearTimeout(n)},logger:console.log.bind(console),devTools:!1};class eo{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Cn(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=B.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...to,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:h}=s;this.system=o?o.system:Qr(this,{clock:i,logger:r}),h&&!o&&this.system.inspect(je(h)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=(e==null?void 0:e.logger)??this.system._logger,this.clock=(e==null?void 0:e.clock)??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:u=>{this._deferred.push(u)},system:this.system,stopChild:u=>{if(u._parent!==this)throw new Error(`Cannot stop child actor ${u.id} of ${this.id} because it is not a child`);u._stop()},emit:u=>{const d=this.eventListeners.get(u.type),p=this.eventListeners.get("*");if(!d&&!p)return;const f=[...d?d.values():[],...p?p.values():[]];for(const m of f)m(u)},actionExecutor:u=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:u.type,params:u.params}}),!u.exec)return;const p=Te;try{Te=!0,u.exec(u.info,u.params)}finally{Te=p}};this._processingStatus===B.Running?d():this._deferred.push(d)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),l&&(this._systemId=l,this.system._set(l,this)),this._initState((e==null?void 0:e.snapshot)??(e==null?void 0:e.state)),l&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){var e;try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,(e=this.options)==null?void 0:e.input)}catch(s){this._snapshot={status:"error",output:void 0,error:s}}}update(t,e){var i,r;this._snapshot=t;let s;for(;s=this._deferred.shift();)try{s()}catch(o){this._deferred.length=0,this._snapshot={...t,status:"error",error:o}}switch(this._snapshot.status){case"active":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){tt(a)}break;case"done":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){tt(a)}this._stopProcedure(),this._complete(),this._doneEvent=Gr(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){var r;const i=je(t,e,s);if(this._processingStatus!==B.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{(r=i.complete)==null||r.call(i)}catch(o){tt(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)tt(o);else try{i.error(o)}catch(a){tt(a)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const i=e.bind(void 0);return s.add(i),{unsubscribe:()=>{s.delete(i)}}}start(){if(this._processingStatus===B.Running)return this;this._syncSnapshot&&this.subscribe({next:s=>{s.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:s})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=B.Running;const t=ps(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(s){return this._snapshot={...this._snapshot,status:"error",error:s},this._error(s),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){s={err:i}}if(s){const{err:i}=s;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(e,t),t.type===Ke&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===B.Stopped?this:(this.mailbox.clear(),this._processingStatus===B.NotStarted?(this._processingStatus=B.Stopped,this):(this.mailbox.enqueue({type:Ke}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var t;for(const e of this.observers)try{(t=e.complete)==null||t.call(e)}catch(s){tt(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||tt(t);return}let e=!1;for(const s of this.observers){const i=s.error;e||(e=!i);try{i==null||i(t)}catch(r){tt(r)}}this.observers.clear(),e&&tt(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Vr(this.id,t))}_stopProcedure(){return this._processingStatus!==B.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Cn(this._process.bind(this)),this._processingStatus=B.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==B.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:Lr)(this)}toJSON(){return{xstate$$type:hn,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Jr](){return this}getSnapshot(){return this._snapshot}}function Ht(n,...[t]){return new eo(n,t)}function no(n,t,e,s,{sendId:i}){const r=typeof i=="function"?i(e,s):i;return[t,{sendId:r},void 0]}function so(n,t){n.defer(()=>{n.system.scheduler.cancel(n.self,t.sendId)})}function io(n){function t(e,s){}return t.type="xstate.cancel",t.sendId=n,t.resolve=no,t.execute=so,t}function ro(n,t,e,s,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?ln(t.machine,o):o,h=typeof i=="function"?i(e):i;let u,d;return l&&(d=typeof a=="function"?a({context:t.context,event:e.event,self:n.self}):a,u=Ht(l,{id:h,src:o,parent:n.self,syncSnapshot:c,systemId:r,input:d})),[At(t,{children:{...t.children,[h]:u}}),{id:i,systemId:r,actorRef:u,src:o,input:d},void 0]}function oo(n,{actorRef:t}){t&&n.defer(()=>{t._processingStatus!==B.Stopped&&t.start()})}function ao(...[n,{id:t,systemId:e,input:s,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="xstate.spawnChild",r.id=t,r.systemId=e,r.src=n,r.input=s,r.syncSnapshot=i,r.resolve=ro,r.execute=oo,r}function co(n,t,e,s,{actorRef:i}){const r=typeof i=="function"?i(e,s):i,o=typeof r=="string"?t.children[r]:r;let a=t.children;return o&&(a={...a},delete a[o.id]),[At(t,{children:a}),o,void 0]}function lo(n,t){if(t){if(n.system._unregister(t),t._processingStatus!==B.Running){n.stopChild(t);return}n.defer(()=>{n.stopChild(t)})}}function bs(n){function t(e,s){}return t.type="xstate.stopChild",t.actorRef=n,t.resolve=co,t.execute=lo,t}function un(n,t,e,s){const{machine:i}=s,r=typeof n=="function",o=r?n:i.implementations.guards[typeof n=="string"?n:n.type];if(!r&&!o)throw new Error(`Guard '${typeof n=="string"?n:n.type}' is not implemented.'.`);if(typeof o!="function")return un(o,t,e,s);const a={context:t,event:e},c=r||typeof n=="string"?void 0:"params"in n?typeof n.params=="function"?n.params({context:t,event:e}):n.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}const dn=n=>n.type==="atomic"||n.type==="final";function Wt(n){return Object.values(n.states).filter(t=>t.type!=="history")}function Qt(n,t){const e=[];if(t===n)return e;let s=n.parent;for(;s&&s!==t;)e.push(s),s=s.parent;return e}function de(n){const t=new Set(n),e=Es(t);for(const s of t)if(s.type==="compound"&&(!e.get(s)||!e.get(s).length))Pn(s).forEach(i=>t.add(i));else if(s.type==="parallel"){for(const i of Wt(s))if(i.type!=="history"&&!t.has(i)){const r=Pn(i);for(const o of r)t.add(o)}}for(const s of t){let i=s.parent;for(;i;)t.add(i),i=i.parent}return t}function _s(n,t){const e=t.get(n);if(!e)return{};if(n.type==="compound"){const i=e[0];if(i){if(dn(i))return i.key}else return{}}const s={};for(const i of e)s[i.key]=_s(i,t);return s}function Es(n){const t=new Map;for(const e of n)t.has(e)||t.set(e,[]),e.parent&&(t.has(e.parent)||t.set(e.parent,[]),t.get(e.parent).push(e));return t}function As(n,t){const e=de(t);return _s(n,Es(e))}function fn(n,t){return t.type==="compound"?Wt(t).some(e=>e.type==="final"&&n.has(e)):t.type==="parallel"?Wt(t).every(e=>fn(n,e)):t.type==="final"}const Ee=n=>n[0]===Ur;function ho(n,t){return n.transitions.get(t)||[...n.transitions.keys()].filter(s=>{if(s===Fr)return!0;if(!s.endsWith(".*"))return!1;const i=s.split("."),r=t.split(".");for(let o=0;o<i.length;o++){const a=i[o],c=r[o];if(a==="*")return o===i.length-1;if(a!==c)return!1}return!0}).sort((s,i)=>i.length-s.length).flatMap(s=>n.transitions.get(s))}function uo(n){const t=n.config.after;if(!t)return[];const e=i=>{const r=Zr(i,n.id),o=r.type;return n.entry.push(Ko(r,{id:o,delay:i})),n.exit.push(io(o)),o};return Object.keys(t).flatMap(i=>{const r=t[i],o=typeof r=="string"?{target:r}:r,a=Number.isNaN(+i)?i:+i,c=e(a);return rt(o).map(l=>({...l,event:c,delay:a}))}).map(i=>{const{delay:r}=i;return{...yt(n,i.event,i),delay:r}})}function yt(n,t,e){const s=ws(e.target),i=e.reenter??!1,r=go(n,s),o={...e,actions:rt(e.actions),guard:e.guard,target:r,source:n,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${n.id}`,target:r?r.map(a=>`#${a.id}`):void 0})};return o}function fo(n){const t=new Map;if(n.config.on)for(const e of Object.keys(n.config.on)){if(e===ds)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=n.config.on[e];t.set(e,vt(s).map(i=>yt(n,e,i)))}if(n.config.onDone){const e=`xstate.done.state.${n.id}`;t.set(e,vt(n.config.onDone).map(s=>yt(n,e,s)))}for(const e of n.invoke){if(e.onDone){const s=`xstate.done.actor.${e.id}`;t.set(s,vt(e.onDone).map(i=>yt(n,s,i)))}if(e.onError){const s=`xstate.error.actor.${e.id}`;t.set(s,vt(e.onError).map(i=>yt(n,s,i)))}if(e.onSnapshot){const s=`xstate.snapshot.${e.id}`;t.set(s,vt(e.onSnapshot).map(i=>yt(n,s,i)))}}for(const e of n.after){let s=t.get(e.eventType);s||(s=[],t.set(e.eventType,s)),s.push(e)}return t}function po(n,t){const e=typeof t=="string"?n.states[t]:t?n.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${n.id}`);const s={source:n,actions:!t||typeof t=="string"?[]:rt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...s,source:`#${n.id}`,target:e?[`#${e.id}`]:[]})};return s}function go(n,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(Ee(e))return n.machine.getStateNodeById(e);const s=e[0]===us;if(s&&!n.parent)return fe(n,e.slice(1));const i=s?n.key+e:e;if(n.parent)try{return fe(n.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${n.id}':
|
|
14
14
|
${r.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function Ss(n){const t=ws(n.config.target);return t?{target:t.map(e=>typeof e=="string"?fe(n.parent,e):e)}:n.parent.initial}function wt(n){return n.type==="history"}function Pn(n){const t=Ns(n);for(const e of t)for(const s of Qt(e,n))t.add(s);return t}function Ns(n){const t=new Set;function e(s){if(!t.has(s)){if(t.add(s),s.type==="compound")e(s.initial.target[0]);else if(s.type==="parallel")for(const i of Wt(s))e(i)}}return e(n),t}function Bt(n,t){if(Ee(t))return n.machine.getStateNodeById(t);if(!n.states)throw new Error(`Unable to retrieve child state '${t}' from '${n.id}'; no child states exist.`);const e=n.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${n.id}'`);return e}function fe(n,t){if(typeof t=="string"&&Ee(t))try{return n.machine.getStateNodeById(t)}catch{}const e=cn(t).slice();let s=n;for(;e.length;){const i=e.shift();if(!i.length)break;s=Bt(s,i)}return s}function pe(n,t){if(typeof t=="string"){const i=n.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${n.id}'`);return[n,i]}const e=Object.keys(t),s=e.map(i=>Bt(n,i)).filter(Boolean);return[n.machine.root,n].concat(s,e.reduce((i,r)=>{const o=Bt(n,r);if(!o)return i;const a=pe(o,t[r]);return i.concat(a)},[]))}function yo(n,t,e,s){const r=Bt(n,t).next(e,s);return!r||!r.length?n.next(e,s):r}function mo(n,t,e,s){const i=Object.keys(t),r=Bt(n,i[0]),o=pn(r,t[i[0]],e,s);return!o||!o.length?n.next(e,s):o}function wo(n,t,e,s){const i=[];for(const r of Object.keys(t)){const o=t[r];if(!o)continue;const a=Bt(n,r),c=pn(a,o,e,s);c&&i.push(...c)}return i.length?i:n.next(e,s)}function pn(n,t,e,s){return typeof t=="string"?yo(n,t,e,s):Object.keys(t).length===1?mo(n,t,e,s):wo(n,t,e,s)}function bo(n){return Object.keys(n.states).map(t=>n.states[t]).filter(t=>t.type==="history")}function ct(n,t){let e=n;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function _o(n,t){const e=new Set(n),s=new Set(t);for(const i of e)if(s.has(i))return!0;for(const i of s)if(e.has(i))return!0;return!1}function Is(n,t,e){const s=new Set;for(const i of n){let r=!1;const o=new Set;for(const a of s)if(_o(Ue([i],t,e),Ue([a],t,e)))if(ct(i.source,a.source))o.add(a);else{r=!0;break}if(!r){for(const a of o)s.delete(a);s.add(i)}}return Array.from(s)}function Eo(n){const[t,...e]=n;for(const s of Qt(t,void 0))if(e.every(i=>ct(i,s)))return s}function gn(n,t){if(!n.target)return[];const e=new Set;for(const s of n.target)if(wt(s))if(t[s.id])for(const i of t[s.id])e.add(i);else for(const i of gn(Ss(s),t))e.add(i);else e.add(s);return[...e]}function vs(n,t){const e=gn(n,t);if(!e)return;if(!n.reenter&&e.every(i=>i===n.source||ct(i,n.source)))return n.source;const s=Eo(e.concat(n.source));if(s)return s;if(!n.reenter)return n.source.machine.root}function Ue(n,t,e){var i;const s=new Set;for(const r of n)if((i=r.target)!=null&&i.length){const o=vs(r,e);r.reenter&&r.source===o&&s.add(o);for(const a of t)ct(a,o)&&s.add(a)}return[...s]}function Ao(n,t){if(n.length!==t.size)return!1;for(const e of n)if(!t.has(e))return!1;return!0}function Fe(n,t,e,s,i,r){if(!n.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=Is(n,o,a);let l=t;i||([l,a]=vo(l,s,e,c,o,a,r,e.actionExecutor)),l=Dt(l,s,e,c.flatMap(u=>u.actions),r,void 0),l=No(l,s,e,c,o,r,a,i);const h=[...o];l.status==="done"&&(l=Dt(l,s,e,h.sort((u,d)=>d.order-u.order).flatMap(u=>u.exit),r,void 0));try{return a===t.historyValue&&Ao(t._nodes,o)?l:At(l,{_nodes:h,historyValue:a})}catch(u){throw u}}function So(n,t,e,s,i){if(s.output===void 0)return;const r=ze(i.id,i.output!==void 0&&i.parent?Le(i.output,n.context,t,e.self):void 0);return Le(s.output,n.context,r,e.self)}function No(n,t,e,s,i,r,o,a){let c=n;const l=new Set,h=new Set;Io(s,o,h,l),a&&h.add(n.machine.root);const u=new Set;for(const d of[...l].sort((p,f)=>p.order-f.order)){i.add(d);const p=[];p.push(...d.entry);for(const f of d.invoke)p.push(ao(f.src,{...f,syncSnapshot:!!f.onSnapshot}));if(h.has(d)){const f=d.initial.actions;p.push(...f)}if(c=Dt(c,t,e,p,r,d.invoke.map(f=>f.id)),d.type==="final"){const f=d.parent;let m=(f==null?void 0:f.type)==="parallel"?f:f==null?void 0:f.parent,A=m||d;for((f==null?void 0:f.type)==="compound"&&r.push(ze(f.id,d.output!==void 0?Le(d.output,c.context,t,e.self):void 0));(m==null?void 0:m.type)==="parallel"&&!u.has(m)&&fn(i,m);)u.add(m),r.push(ze(m.id)),A=m,m=m.parent;if(m)continue;c=At(c,{status:"done",output:So(c,t,e,c.machine.root,A)})}}return c}function Io(n,t,e,s){for(const i of n){const r=vs(i,t);for(const a of i.target||[])!wt(a)&&(i.source!==a||i.source!==r||i.reenter)&&(s.add(a),e.add(a)),Ot(a,t,e,s);const o=gn(i,t);for(const a of o){const c=Qt(a,r);(r==null?void 0:r.type)==="parallel"&&c.push(r),Ts(s,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function Ot(n,t,e,s){var i;if(wt(n))if(t[n.id]){const r=t[n.id];for(const o of r)s.add(o),Ot(o,t,e,s);for(const o of r)Oe(o,n.parent,s,t,e)}else{const r=Ss(n);for(const o of r.target)s.add(o),r===((i=n.parent)==null?void 0:i.initial)&&e.add(n.parent),Ot(o,t,e,s);for(const o of r.target)Oe(o,n.parent,s,t,e)}else if(n.type==="compound"){const[r]=n.initial.target;wt(r)||(s.add(r),e.add(r)),Ot(r,t,e,s),Oe(r,n,s,t,e)}else if(n.type==="parallel")for(const r of Wt(n).filter(o=>!wt(o)))[...s].some(o=>ct(o,r))||(wt(r)||(s.add(r),e.add(r)),Ot(r,t,e,s))}function Ts(n,t,e,s,i){for(const r of s)if((!i||ct(r,i))&&n.add(r),r.type==="parallel")for(const o of Wt(r).filter(a=>!wt(a)))[...n].some(a=>ct(a,o))||(n.add(o),Ot(o,t,e,n))}function Oe(n,t,e,s,i){Ts(e,s,i,Qt(n,t))}function vo(n,t,e,s,i,r,o,a){let c=n;const l=Ue(s,i,r);l.sort((u,d)=>d.order-u.order);let h;for(const u of l)for(const d of bo(u)){let p;d.history==="deep"?p=f=>dn(f)&&ct(f,u):p=f=>f.parent===u,h??(h={...r}),h[d.id]=Array.from(i).filter(p)}for(const u of l)c=Dt(c,t,e,[...u.exit,...u.invoke.map(d=>bs(d.id))],o,void 0),i.delete(u);return[c,h||r]}function To(n,t){return n.implementations.actions[t]}function Os(n,t,e,s,i,r){const{machine:o}=n;let a=n;for(const c of s){const l=typeof c=="function",h=l?c:To(o,typeof c=="string"?c:c.type),u={context:a.context,event:t,self:e.self,system:e.system},d=l||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:t}):c.params:void 0;if(!h||!("resolve"in h)){e.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:u,params:d,exec:h});continue}const p=h,[f,m,A]=p.resolve(e,a,u,d,h,i);a=f,"retryResolve"in p&&(r==null||r.push([p,m])),"execute"in p&&e.actionExecutor({type:p.type,info:u,params:m,exec:p.execute.bind(null,e,m)}),A&&(a=Os(a,t,e,A,i,r))}return a}function Dt(n,t,e,s,i,r){const o=r?[]:void 0,a=Os(n,t,e,s,{internalQueue:i,deferredActorIds:r},o);return o==null||o.forEach(([c,l])=>{c.retryResolve(e,a,l)}),a}function ke(n,t,e,s){let i=n;const r=[];function o(l,h,u){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:h,snapshot:l,_transitions:u}),r.push(l)}if(t.type===Ke)return i=At(Hn(i,t,e),{status:"stopped"}),o(i,t,[]),{snapshot:i,microstates:r};let a=t;if(a.type!==fs){const l=a,h=Xr(l),u=Wn(l,i);if(h&&!u.length)return i=At(n,{status:"error",error:l.error}),o(i,l,[]),{snapshot:i,microstates:r};i=Fe(u,n,e,a,!1,s),o(i,l,u)}let c=!0;for(;i.status==="active";){let l=c?Oo(i,a):[];const h=l.length?i:void 0;if(!l.length){if(!s.length)break;a=s.shift(),l=Wn(a,i)}i=Fe(l,i,e,a,!1,s),c=i!==h,o(i,a,l)}return i.status!=="active"&&Hn(i,a,e),{snapshot:i,microstates:r}}function Hn(n,t,e){return Dt(n,t,e,Object.values(n.children).map(s=>bs(s)),[],void 0)}function Wn(n,t){return t.machine.getTransitionData(t,n)}function Oo(n,t){const e=new Set,s=n._nodes.filter(dn);for(const i of s)t:for(const r of[i].concat(Qt(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||un(o.guard,n.context,t,n)){e.add(o);break t}}return Is(Array.from(e),new Set(n._nodes),n.historyValue)}function ko(n,t){const e=de(pe(n,t));return As(n,[...e])}function Co(n){return!!n&&typeof n=="object"&&"machine"in n&&"value"in n}const Ro=function(t){return gs(t,this.value)},xo=function(t){return this.tags.has(t)},Mo=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(s=>s.target!==void 0||s.actions.length)},$o=function(){const{_nodes:t,tags:e,machine:s,getMeta:i,toJSON:r,can:o,hasTag:a,matches:c,...l}=this;return{...l,tags:Array.from(e)}},Po=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function oe(n,t){return{status:n.status,output:n.output,error:n.error,machine:t,context:n.context,_nodes:n._nodes,value:As(t.root,n._nodes),tags:new Set(n._nodes.flatMap(e=>e.tags)),children:n.children,historyValue:n.historyValue||{},matches:Ro,hasTag:xo,can:Mo,getMeta:Po,toJSON:$o}}function At(n,t={}){return oe({...n,...t},n.machine)}function Ho(n){if(typeof n!="object"||n===null)return{};const t={};for(const e in n){const s=n[e];Array.isArray(s)&&(t[e]=s.map(i=>({id:i.id})))}return t}function Wo(n,t){const{_nodes:e,tags:s,machine:i,children:r,context:o,can:a,hasTag:c,matches:l,getMeta:h,toJSON:u,...d}=n,p={};for(const m in r){const A=r[m];p[m]={snapshot:A.getPersistedSnapshot(t),src:A.src,systemId:A._systemId,syncSnapshot:A._syncSnapshot}}return{...d,context:ks(o),children:p,historyValue:Ho(d.historyValue)}}function ks(n){let t;for(const e in n){const s=n[e];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)t??(t=Array.isArray(n)?n.slice():{...n}),t[e]={xstate$$type:hn,id:s.id};else{const i=ks(s);i!==s&&(t??(t=Array.isArray(n)?n.slice():{...n}),t[e]=i)}}return t??n}function Bo(n,t,e,s,{event:i,id:r,delay:o},{internalQueue:a}){const c=t.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);const l=typeof i=="function"?i(e,s):i;let h;if(typeof o=="string"){const u=c&&c[o];h=typeof u=="function"?u(e,s):u}else h=typeof o=="function"?o(e,s):o;return typeof h!="number"&&a.push(l),[t,{event:l,id:r,delay:h},void 0]}function Do(n,t){const{event:e,delay:s,id:i}=t;if(typeof s=="number"){n.defer(()=>{const r=n.self;n.system.scheduler.schedule(r,r,e,s,i)});return}}function Ko(n,t){function e(s,i){}return e.type="xstate.raise",e.event=n,e.id=t==null?void 0:t.id,e.delay=t==null?void 0:t.delay,e.resolve=Bo,e.execute=Do,e}function zo(n,{machine:t,context:e},s,i){const r=(o,a)=>{if(typeof o=="string"){const c=ln(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=Ht(c,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:typeof(a==null?void 0:a.input)=="function"?a.input({context:e,event:s,self:n.self}):a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId});return i[l.id]=l,l}else return Ht(o,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId})};return(o,a)=>{const c=r(o,a);return i[c.id]=c,n.defer(()=>{c._processingStatus!==B.Stopped&&c.start()}),c}}function Lo(n,t,e,s,{assignment:i}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const r={},o={context:t.context,event:e.event,spawn:zo(n,t,e.event,r),self:n.self,system:n.system};let a={};if(typeof i=="function")a=i(o,s);else for(const l of Object.keys(i)){const h=i[l];a[l]=typeof h=="function"?h(o,s):h}const c=Object.assign({},t.context,a);return[At(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children}),void 0,void 0]}function jo(n){function t(e,s){}return t.type="xstate.assign",t.assignment=n,t.resolve=Lo,t}const Bn=new WeakMap;function It(n,t,e){let s=Bn.get(n);return s?t in s||(s[t]=e()):(s={[t]:e()},Bn.set(n,s)),s[t]}const Uo={},Lt=n=>typeof n=="string"?{type:n}:typeof n=="function"?"resolve"in n?{type:n.type}:{type:n.name}:n;class ge{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(us),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?xn(this.config.states,(s,i)=>new ge(s,{_parent:this,_key:i,_machine:this.machine})):Uo,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=rt(this.config.entry).slice(),this.exit=rt(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=rt(t.tags).slice()}_initialize(){this.transitions=fo(this),this.config.always&&(this.always=vt(this.config.always).map(t=>yt(this,ds,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(Lt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Lt),eventType:null})}:void 0,history:this.history,states:xn(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Lt)})),entry:this.entry.map(Lt),exit:this.exit.map(Lt),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return It(this,"invoke",()=>rt(this.config.invoke).map((t,e)=>{const{src:s,systemId:i}=t,r=t.id??Mn(this.id,e),o=typeof s=="string"?s:`xstate.invoke.${Mn(this.id,e)}`;return{...t,src:o,id:r,systemId:i,toJSON(){const{onDone:a,onError:c,...l}=t;return{...l,type:"xstate.invoke",src:o,id:r}}}}))}get on(){return It(this,"on",()=>[...this.transitions].flatMap(([e,s])=>s.map(i=>[e,i])).reduce((e,[s,i])=>(e[s]=e[s]||[],e[s].push(i),e),{}))}get after(){return It(this,"delayedTransitions",()=>uo(this))}get initial(){return It(this,"initial",()=>po(this,this.config.initial))}next(t,e){const s=e.type,i=[];let r;const o=It(this,`candidates-${s}`,()=>ho(this,s));for(const a of o){const{guard:c}=a,l=t.context;let h=!1;try{h=!c||un(c,l,e,t)}catch(u){const d=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${d?`'${d}' `:""}in transition for event '${s}' in state node '${this.id}':
|
|
15
15
|
${u.message}`)}if(h){i.push(...a.actions),r=a;break}}return r?[r]:void 0}get events(){return It(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const i=t[s];if(i.states)for(const r of i.events)e.add(`${r}`)}return Array.from(e)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(e=>this.transitions.get(e).some(s=>!(!s.target&&!s.actions.length&&!s.reenter))));return Array.from(t)}}const Fo="#";class yn{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:(e==null?void 0:e.actors)??{},actions:(e==null?void 0:e.actions)??{},delays:(e==null?void 0:e.delays)??{},guards:(e==null?void 0:e.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new ge(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:i,delays:r}=this.implementations;return new yn(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...i,...t.actors},delays:{...r,...t.delays}})}resolveState(t){const e=ko(this.root,t.value),s=de(pe(this.root,e));return oe({_nodes:[...s],context:t.context||{},children:{},status:fn(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return ke(t,e,s,[]).snapshot}microstep(t,e,s){return ke(t,e,s,[]).microstates}getTransitionData(t,e){return pn(this.root,t.value,t,e)||[]}getPreInitialState(t,e,s){const{context:i}=this.config,r=oe({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?Dt(r,e,t,[jo(({spawn:a,event:c,self:l})=>i({spawn:a,input:c.input,self:l}))],s,void 0):r}getInitialSnapshot(t,e){const s=ps(e),i=[],r=this.getPreInitialState(t,s,i),o=Fe([{target:[...Ns(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],r,t,s,!0,i),{snapshot:a}=ke(o,s,t,i);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=cn(t),s=e.slice(1),i=Ee(e[0])?e[0].slice(Fo.length):e[0],r=this.idMap.get(i);if(!r)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return fe(r,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return Wo(t,e)}restoreSnapshot(t,e){const s={},i=t.children;Object.keys(i).forEach(u=>{const d=i[u],p=d.snapshot,f=d.src,m=typeof f=="string"?ln(this,f):f;if(!m)return;const A=Ht(m,{id:u,parent:e.self,syncSnapshot:d.syncSnapshot,snapshot:p,src:f,systemId:d.systemId});s[u]=A});function r(u,d){if(d instanceof ge)return d;try{return u.machine.getStateNodeById(d.id)}catch{}}function o(u,d){if(!d||typeof d!="object")return{};const p={};for(const f in d){const m=d[f];for(const A of m){const S=r(u,A);S&&(p[f]??(p[f]=[]),p[f].push(S))}}return p}const a=o(this.root,t.historyValue),c=oe({...t,children:s,_nodes:Array.from(de(pe(this.root,t.value))),historyValue:a},this),l=new Set;function h(u,d){if(!l.has(u)){l.add(u);for(const p in u){const f=u[p];if(f&&typeof f=="object"){if("xstate$$type"in f&&f.xstate$$type===hn){u[p]=d[f.id];continue}h(f,d)}}}}return h(c.context,s),c}}function Zo(n,t){return new yn(n,t)}const se=n=>n===!1?!1:n.map(t=>t.serialize()),Go=n=>n===!1?!1:n.serialize(),Vo=n=>n===!1?!1:n.map(t=>({tile:t.tile.toString(),candidates:t.candidates.map(e=>e.toString()),shanten:t.shanten})),ie=n=>n===!1?!1:ue(n),Ze=n=>Zo({id:"Untitled",initial:"distribute",context:{currentWind:E.E,oneShotMap:H(!1),missingMap:H(!1),controller:n,genEventID:Cs()},states:{distribute:{on:{NEXT:{target:"drawn"}},entry:{type:"notify_distribution"}},drawn:{entry:{type:"notify_draw"},on:{NEXT:{target:"waiting_user_event_after_drawn",actions:{type:"notify_choice_after_drawn"},description:`可能なアクションとその詳細を通知\\
|
|
16
16
|
DISCARD の場合は捨てられる牌の一覧`}}},waiting_user_event_after_drawn:{description:"ツモった1ユーザからのレスポンス待ち",on:{TSUMO:{target:"tsumo",guard:"canWin"},REACH:{target:"waiting_reach_acceptance",actions:[{type:"notify_reach"},{type:"notify_choice_for_reach_acceptance"}],guard:{type:"canReach"}},SHO_KAN:{target:"an_sho_kaned"},AN_KAN:{target:"an_sho_kaned"},DISCARD:{target:"discarded",description:"入力に牌が必須",actions:{type:"disable_one_shot_for_me"}},DRAWN_GAME_BY_NINE_ORPHANS:{target:"drawn_game"}}},discarded:{entry:{type:"notify_discard"},on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"},description:`可能なアクションとその詳細を通知\\
|
package/dist/index.d.cts
CHANGED
|
@@ -1522,8 +1522,8 @@ export declare interface WinResult {
|
|
|
1522
1522
|
han: number;
|
|
1523
1523
|
fu: number;
|
|
1524
1524
|
yakus: readonly Yaku[];
|
|
1525
|
-
|
|
1526
|
-
|
|
1525
|
+
points: number;
|
|
1526
|
+
rawPoints: number;
|
|
1527
1527
|
hand: Block[];
|
|
1528
1528
|
boardContext: BoardContext;
|
|
1529
1529
|
description: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -1522,8 +1522,8 @@ export declare interface WinResult {
|
|
|
1522
1522
|
han: number;
|
|
1523
1523
|
fu: number;
|
|
1524
1524
|
yakus: readonly Yaku[];
|
|
1525
|
-
|
|
1526
|
-
|
|
1525
|
+
points: number;
|
|
1526
|
+
rawPoints: number;
|
|
1527
1527
|
hand: Block[];
|
|
1528
1528
|
boardContext: BoardContext;
|
|
1529
1529
|
description: string;
|
package/dist/index.js
CHANGED
|
@@ -1207,8 +1207,8 @@ function oi(n, t) {
|
|
|
1207
1207
|
throw new Error(`Invalid element name: "${e}"`);
|
|
1208
1208
|
t = nt(n, t);
|
|
1209
1209
|
let s = "";
|
|
1210
|
-
if (n[t] === "E" && ut(n, "MPTY", t)) t +=
|
|
1211
|
-
else if (n[t] === "A" && ut(n, "NY", t)) t +=
|
|
1210
|
+
if (n[t] === "E" && ut(n, "MPTY", t)) t += 4;
|
|
1211
|
+
else if (n[t] === "A" && ut(n, "NY", t)) t += 2;
|
|
1212
1212
|
else if (n[t] === "(") {
|
|
1213
1213
|
for (t++; t < n.length && n[t] !== ")"; )
|
|
1214
1214
|
s += n[t], t++;
|
|
@@ -3501,8 +3501,8 @@ class gn {
|
|
|
3501
3501
|
han: l,
|
|
3502
3502
|
fu: c,
|
|
3503
3503
|
yakus: e[o].yakus,
|
|
3504
|
-
|
|
3505
|
-
|
|
3504
|
+
points: m[d],
|
|
3505
|
+
rawPoints: A,
|
|
3506
3506
|
hand: e[o].hand,
|
|
3507
3507
|
boardContext: this.cfg.orig,
|
|
3508
3508
|
description: S
|
|
@@ -5995,8 +5995,8 @@ class en {
|
|
|
5995
5995
|
/**
|
|
5996
5996
|
* Clones this state machine with the provided implementations.
|
|
5997
5997
|
*
|
|
5998
|
-
* @param implementations Options (`actions`, `guards`, `actors`, `delays`)
|
|
5999
|
-
*
|
|
5998
|
+
* @param implementations Options (`actions`, `guards`, `actors`, `delays`) to
|
|
5999
|
+
* recursively merge with the existing options.
|
|
6000
6000
|
* @returns A new `StateMachine` instance with the provided implementations.
|
|
6001
6001
|
*/
|
|
6002
6002
|
provide(t) {
|