@konoui/mjimage 0.6.1 → 0.7.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 +10 -10
- package/dist/index.d.cts +1 -3
- package/dist/index.d.ts +1 -3
- package/dist/index.js +704 -706
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Fe="MS Gothic, sans-serif",st={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Oe={WIDTH:125,HEIGHT:27.5},Pn={BASE:40},Q=",",f={M:"m",P:"p",S:"s",Z:"z",BACK:"_"},m={TSUMO:"t",RON:"v",DORA:"d",HORIZONTAL:"-",RED:"r",COLOR_GRAYSCALE:"^"},w={PON:"pon",CHI:"chi",SHO_KAN:"shokan",DAI_KAN:"daikan",AN_KAN:"ankan",TSUMO:"tsumo",PAIR:"pair",ISOLATED:"isolated",THREE:"three",RUN:"run",HAND:"hand",IMAGE_DORA:"dora",IMAGE_DISCARD:"simple-discard",UNKNOWN:"unknown"},_={E:"1z",S:"2z",W:"3z",N:"4z"},O={E1:"1z1",E2:"1z2",E3:"1z3",E4:"1z4",S1:"2z1",S2:"2z2",S3:"2z3",S4:"2z4",W1:"3z1",W2:"3z2",W3:"3z3",W4:"3z4",N1:"4z1",N2:"4z2",N3:"4z3",N4:"4z4"},ye={[_.E]:"東",[_.S]:"南",[_.W]:"西",[_.N]:"北"},Ze={[O.E1]:"東1局",[O.E2]:"東2局",[O.E3]:"東3局",[O.E4]:"東4局",[O.S1]:"南1局",[O.S2]:"南2局",[O.S3]:"南3局",[O.S4]:"南4局",[O.W1]:"西1局",[O.W2]:"西2局",[O.W3]:"西3局",[O.W4]:"西4局",[O.N1]:"北1局",[O.N2]:"北2局",[O.N3]:"北3局",[O.N4]:"北4局"};function b(s,t){if(!s)throw new Error(t)}class $s{ctx=null;strText;numText;constructor(t="東",e="2"){this.strText=t,this.numText=e}measure=(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),b(this.ctx,"context is null"));const n=this.ctx;n.font=e;const i=n.measureText(t);let r=i.width,o=i.actualBoundingBoxAscent+i.actualBoundingBoxDescent;return[r,o]};measureFontContext=(t,e)=>{const n={family:t,size:e},i=`${n.size}px ${n.family}`,[r,o]=this.measure(this.strText,i),[a,c]=this.measure(this.numText,i);return{font:{family:t,size:e},textWidth:r,textHeight:o,numWidth:a,numHeight:c}};measureTableFontContext=t=>{const e=this.measureFontContext(Fe,Pn.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e}}class Ps{input;position;nextPosition;char;eof="\0";constructor(t){this.input=t,this.position=0,this.nextPosition=0,this.char=this.readChar()}readChar(){return this.nextPosition>=this.input.length?(this.char=this.eof,this.char):(this.char=this.input[this.nextPosition],this.position=this.nextPosition,this.nextPosition++,this.char)}peekChar(){return this.nextPosition>=this.input.length?this.eof:this.input[this.nextPosition]}peekCharN(t){if(t<0)throw new Error("arg must be positive value");return this.position+t>=this.input.length?this.eof:this.input[this.position+t]}prevChar(){return this.position>=this.input.length?this.eof:this.position>0?this.input[this.position-1]:this.eof}skipWhitespace(){for(;this.isWhitespace(this.char);)this.readChar()}isWhitespace(t){return/\s/.test(t)}}const Qt=(s,t)=>{if(s.t==t.t){if(k(s)&&k(t)){if(s.has(m.RED))return-1;if(t.has(m.RED))return 1}return s.n-t.n}const e=[f.M,f.P,f.S,f.Z,f.BACK];return e.indexOf(s.t)-e.indexOf(t.t)},Hs=(s,t)=>{const e=[m.HORIZONTAL,m.TSUMO,m.RON,m.DORA,m.COLOR_GRAYSCALE,m.RED];return e.indexOf(s)-e.indexOf(t)},Hn=s=>{const t=[];s.forEach((n,i)=>{n.has(m.HORIZONTAL)&&t.push(i)});const e=s.filter(n=>!n.has(m.HORIZONTAL)).sort(Qt);return t.forEach(n=>{e.splice(n,0,s[n])}),e};function k(s){return s.isNum()&&s.n==5}function Bs(s){for(const t of Object.values(f))if(t==s)return[t,!0];return[f.BACK,!1]}class y{constructor(t,e,n=[]){this.t=t,this.n=e,this.ops=n}static from(t){const e=new D(t).tiles();if(e.length!=1)throw new Error(`input is not a single tile ${t}`);return e[0]}toString(){return this.t===f.BACK?this.t:`${[...this.ops].sort(Hs).join("")}${this.n}${this.t}`}toJSON(){return this.toString()}clone(t){const e=t?.t??this.t,n=t?.n??this.n,i=t?.removeAll?[]:this.ops.filter(o=>Array.isArray(t?.remove)?!t.remove.includes(o):t?.remove!=o),r=new Set([...i]);return t?.add&&(Array.isArray(t.add)?t.add.forEach(o=>r.add(o)):r.add(t.add)),new y(e,n,Array.from(r))}has(t){return this.ops.includes(t)}isNum(){return this.t==f.M||this.t==f.P||this.t==f.S}equals(t){return t.t==f.BACK&&this.t==f.BACK?!0:this.t==t.t&&this.n==t.n}}class I{_tiles;_type;constructor(t,e){if(this._tiles=t,this._type=e,this.isCalled()){this._tiles=Hn(this._tiles);return}if(this._type!=w.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Qt);return}}static from(t){const e=new D(t).parse();if(e.length!=1)throw new Error(`block must be 1: ${t}`);return e[0]}static deserialize(t){const e=I.from(t.tiles),n=e.type;if(!(t.type==w.PAIR||t.type==w.ISOLATED||t.type==w.THREE||t.type==w.RUN)&&n!=t.type)throw new Error(`input type is ${t.type} but got is ${n}: ${t.tiles}`);return ce(e.tiles,t.type)}serialize(){return{tiles:this.toString(),type:this.type}}toJSON(){return this.serialize()}get type(){return this._type}get tiles(){return this._tiles}is(t){return this._type==t}isCalled(){switch(this._type){case w.PON:case w.CHI:case w.DAI_KAN:case w.SHO_KAN:case w.AN_KAN:return!0;default:return!1}}clone(t){const e=t?.replace,n=[...this.tiles];return e&&(n[e.idx]=e.tile),ce(n,this._type)}}const bt=s=>{let t="";for(const e of s){if(e.t==f.BACK)return s.join("");t+=e.toString().slice(0,-1)}return`${t}${s[0].t}`},Ye=s=>{if(s.length==0)return"";let t=s[0].t,e="";for(const i of s){const r=i.t,o=r==f.BACK?i.toString():i.toString().slice(0,-1);r!=t&&t!=f.BACK&&(e+=t),t=r,e+=o}const n=s.at(-1);return n.t!=f.BACK&&(e+=n.t),e};class J extends I{constructor(t){super(t,w.CHI)}static from(t){return I.deserialize({tiles:t,type:w.CHI})}toString(){return bt(this.tiles)}}class X extends I{constructor(t){super(t,w.PON)}static from(t){return I.deserialize({tiles:t,type:w.PON})}toString(){return bt(this.tiles)}}class R extends I{constructor(t){const e=t.filter(i=>i.t!=f.BACK),n=e[0];if(e.length<t.length){if(k(n)){const i=new y(n.t,5);super([i.clone({add:m.RED}),i,i,i],w.AN_KAN);return}super([n,n,n,n],w.AN_KAN);return}super(t,w.AN_KAN)}get tiles(){return super.tiles}get tilesWithBack(){const t=this.tiles[0].clone({remove:m.RED}),e=k(t)?t.clone({add:m.RED}):t;return[new y(f.BACK,0),e,t,new y(f.BACK,0)]}static from(t){return I.deserialize({tiles:t,type:w.AN_KAN})}toString(){return Ye(this.tilesWithBack)}}class q extends I{constructor(t){super(t,w.DAI_KAN)}static from(t){return I.deserialize({tiles:t,type:w.DAI_KAN})}toString(){return bt(this.tiles)}}class K extends I{constructor(t){super(t,w.SHO_KAN)}static from(t){return I.deserialize({tiles:t,type:w.SHO_KAN})}static fromPon(t,e){const n=t.tiles.findIndex(r=>r.has(m.HORIZONTAL)),i=[...t.tiles];return i.splice(n,0,e.clone({add:m.HORIZONTAL})),new K(i)}toString(){return bt(this.tiles)}}class B extends I{constructor(t,e){super([t,e],w.PAIR)}toString(){return bt(this.tiles)}static from(t){return I.deserialize({tiles:t,type:w.PAIR})}}class U extends I{constructor(t){super(t,w.THREE)}static from(t){return I.deserialize({tiles:t,type:w.THREE})}toString(){return bt(this.tiles)}}class tt extends I{constructor(t){super(t,w.RUN)}static from(t){return I.deserialize({tiles:t,type:w.RUN})}toString(){return bt(this.tiles)}}class Ve extends I{constructor(t){super([t],w.ISOLATED)}static from(t){return I.deserialize({tiles:t,type:w.ISOLATED})}toString(){return this.tiles[0].toString()}}class Rt extends I{constructor(t){super(t,w.HAND)}static from(t){return I.deserialize({tiles:t,type:w.HAND})}toString(){return Ye(this.tiles)}}class Je extends I{constructor(t,e){super(t,e)}toString(){return this.is(w.IMAGE_DISCARD)?this.tiles.join(""):Ye(this.tiles)}}const ce=(s,t)=>{switch(t){case w.CHI:return new J([s[0],s[1],s[2]]);case w.PON:return new X([s[0],s[1],s[2]]);case w.AN_KAN:return new R(s);case w.DAI_KAN:return new q(s);case w.SHO_KAN:return new K(s);case w.THREE:return new U(s);case w.RUN:return new tt(s);case w.PAIR:return new B(s[0],s[1]);case w.ISOLATED:return new Ve(s[0]);case w.HAND:return new Rt(s);default:return new Je(s,t)}};class D{constructor(t){this.input=t,this.input=t.replace(/\s/g,"")}maxInputLength=600;parse(){const t=this.tileSeparators();return this.makeBlocks(t)}tiles(){return this.tileSeparators().filter(t=>t!=Q)}tileSeparators(){const t=new Ps(this.input),e=[];let n=[];for(this.validate(this.input);;){t.skipWhitespace();const i=t.char;if(i===t.eof)break;if(i==Q){e.push(Q),t.readChar();continue}const[r,o]=yn(i,n);if(o){if(r==f.BACK){e.push(new y(r,0)),t.readChar();continue}e.push(...Ws(n,r)),n=[],t.readChar();continue}else{const[a,c]=Ks(t);if(c){n.push(a),t.readChar();continue}const[l,u]=Bn(i);if(!u)throw new Error(`encounter unexpected number. n: ${l}, current: ${i}, input: ${t.input}`);n.push({n:l})}t.readChar()}if(n.length>0)throw new Error(`remaining values ${n.toString()}`);return e}makeBlocks(t){let e=[];const n=[];if(t.length==0)return n;for(const o of t){if(o==Q){const a=mn(e),c=ce(e,a);n.push(c),e=[];continue}e.push(o)}const i=mn(e),r=ce(e,i);return n.push(r),e=[],n}validate(t){if(t.length==0)return;if(t.length>this.maxInputLength)throw new Error(`exceeded maximum input length(${t.length})`);const e=t.charAt(t.length-1),[n,i]=yn(e,[new y(f.BACK,1)]);if(!i)throw new Error(`last character: ${e} is not type value: ${t}`)}}function mn(s){if(s.length===0)return w.UNKNOWN;if(s.length===1)return s[0].has(m.DORA)?w.IMAGE_DORA:s[0].has(m.TSUMO)?w.TSUMO:w.HAND;const t=s.every(r=>r.equals(s[0])),e=s.filter(r=>r.has(m.HORIZONTAL)).length,n=s.filter(r=>r.has(m.TSUMO)||r.has(m.DORA)).length,i=s.filter(r=>r.t==f.BACK).length;if(n>0)return w.UNKNOWN;if(e==0&&i==0)return w.HAND;if(s.length===3&&i===0)return t?w.PON:e==1&&Ds(s)?w.CHI:w.IMAGE_DISCARD;if(s.length==4&&i==2)return w.AN_KAN;if(s.length==4&&t){if(e==1)return w.DAI_KAN;if(e==2)return w.SHO_KAN}return e==1||n==0?w.IMAGE_DISCARD:w.UNKNOWN}function Ds(s){const t=[...s].sort(Qt);if(t.some(n=>t[0].t!=n.t))return!1;const e=t.map(n=>n.n);for(let n=0;n<e.length-1;n++)if(e[n]!=e[n+1]-1)return!1;return!0}function Ws(s,t){return s.map(e=>{const n=new y(t,e.n,e.ops);return n.isNum()&&n.n==0?n.clone({n:5,add:m.RED}):n})}function yn(s,t){const[e,n]=Bs(s);if(n)return[e,!0];if((s==="w"||s==="d")&&t.length>0){for(let r=0;r<t.length;r++){const o=t[r];s==="d"&&(t[r].n=o.n+4)}return[f.Z,!0]}return[f.BACK,!1]}function Bn(s){const t=Number(s),e=0<=t&&t<=9;return[t,e]}function Ks(s){const t=Object.values(m);if(!t.includes(s.char))return[new y(f.BACK,0),!1];const e=[];for(let n=0;n<4;n++){const i=s.peekCharN(n);if(t.includes(i))e.push(i);else{const[r,o]=Bn(i);if(!o)break;for(const c of e)s.readChar();const a=new y(f.BACK,r,e);if(a.has(m.RED)&&a.n!=5)throw new Error(`found ${m.RED} but number is not 5: ${r}`);if(a.has(m.DORA)&&a.has(m.TSUMO))throw new Error(`unable to specify both ${m.DORA} and ${m.TSUMO}`);return[a,!0]}}return[new y(f.BACK,0),!1]}function $(s,t=!1){const e={[_.E]:s,[_.S]:s,[_.W]:s,[_.N]:s};if(t)for(let n of Object.values(_))e[n]=structuredClone(s);return e}const Vt=s=>{let t=s.substring(0,2),e=Number(s.substring(2,3));return e==4?(e=1,t=yt(t)):e++,`${t}${e}`},Ls=s=>Vt(Vt(Vt(s))),yt=s=>{let t=Number(s.toString()[0]);return t=t%4+1,`${t}${f.Z}`},we=s=>{let t=Number(s.toString()[0]);const e=[1,4,3,2],n=e.indexOf(t);return`${e[(n+1)%e.length]}${f.Z}`},ke=(s,t,e)=>{const n=Math.abs(Number(s[0])-Number(t[0]));return b(n==1||n==2||n==3),e==w.PON?n==3?0:n==2?1:2:n==3?0:n==1?3:2};function wn(s){return typeof s>"u"}function Ce(s,t=0){return{a:1,c:0,e:s,b:0,d:1,f:t}}function Xe(...s){s=Array.isArray(s[0])?s[0]:s;const t=(e,n)=>({a:e.a*n.a+e.c*n.b,c:e.a*n.c+e.c*n.d,e:e.a*n.e+e.c*n.f+e.e,b:e.b*n.a+e.d*n.b,d:e.b*n.c+e.d*n.d,f:e.b*n.e+e.d*n.f+e.f});switch(s.length){case 0:throw new Error("no matrices provided");case 1:return s[0];case 2:return t(s[0],s[1]);default:{const[e,n,...i]=s,r=t(e,n);return Xe(r,...i)}}}function zs(...s){return Xe(...s)}const{cos:Us,sin:js,PI:Gs}=Math;function Fs(s,t,e){const n=Us(s),i=js(s),r={a:n,c:-i,e:0,b:i,d:n,f:0};return wn(t)||wn(e)?r:Xe([Ce(t,e),r,Ce(-t,-e)])}function Zs(s,t=void 0,e=void 0){return Fs(s*Gs/180,t,e)}function Ys(s){return Vs(s)}function Vs(s){return`matrix(${s.a},${s.b},${s.c},${s.d},${s.e},${s.f})`}const Dn=":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",Js=Dn+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Xs="["+Dn+"]["+Js+"]*",qs=new RegExp("^"+Xs+"$");function Wn(s,t){const e=[];let n=t.exec(s);for(;n;){const i=[];i.startIndex=t.lastIndex-n[0].length;const r=n.length;for(let o=0;o<r;o++)i.push(n[o]);e.push(i),n=t.exec(s)}return e}const Ee=function(s){const t=qs.exec(s);return!(t===null||typeof t>"u")};function Qs(s){return typeof s<"u"}const ti={allowBooleanAttributes:!1,unpairedTags:[]};function ei(s,t){t=Object.assign({},ti,t);const e=[];let n=!1,i=!1;s[0]==="\uFEFF"&&(s=s.substr(1));for(let r=0;r<s.length;r++)if(s[r]==="<"&&s[r+1]==="?"){if(r+=2,r=_n(s,r),r.err)return r}else if(s[r]==="<"){let o=r;if(r++,s[r]==="!"){r=An(s,r);continue}else{let a=!1;s[r]==="/"&&(a=!0,r++);let c="";for(;r<s.length&&s[r]!==">"&&s[r]!==" "&&s[r]!==" "&&s[r]!==`
|
|
2
|
-
`&&s[r]!=="\r";r++)c+=s[r];if(c=c.trim(),c[c.length-1]==="/"&&(c=c.substring(0,c.length-1),r--),!li(c)){let h;return c.trim().length===0?h="Invalid space after '<'.":h="Tag '"+c+"' is an invalid name.",S("InvalidTag",h
|
|
3
|
-
`||s==="\r"}function _n(s,t){const e=t;for(;t<s.length;t++)if(s[t]=="?"||s[t]==" "){const n=s.substr(e,t-e);if(t>5&&n==="xml")return S("InvalidXml","XML declaration allowed only at the start of the document.",x(s,t));if(s[t]=="?"&&s[t+1]==">"){t++;break}else continue}return t}function An(s,t){if(s.length>t+5&&s[t+1]==="-"&&s[t+2]==="-"){for(t+=3;t<s.length;t++)if(s[t]==="-"&&s[t+1]==="-"&&s[t+2]===">"){t+=2;break}}else if(s.length>t+8&&s[t+1]==="D"&&s[t+2]==="O"&&s[t+3]==="C"&&s[t+4]==="T"&&s[t+5]==="Y"&&s[t+6]==="P"&&s[t+7]==="E"){let e=1;for(t+=8;t<s.length;t++)if(s[t]==="<")e++;else if(s[t]===">"&&(e--,e===0))break}else if(s.length>t+9&&s[t+1]==="["&&s[t+2]==="C"&&s[t+3]==="D"&&s[t+4]==="A"&&s[t+5]==="T"&&s[t+6]==="A"&&s[t+7]==="["){for(t+=8;t<s.length;t++)if(s[t]==="]"&&s[t+1]==="]"&&s[t+2]===">"){t+=2;break}}return t}const ni='"',si="'";function ii(s,t){let e="",n="",i=!1;for(;t<s.length;t++){if(s[t]===ni||s[t]===si)n===""?n=s[t]:n!==s[t]||(n="");else if(s[t]===">"&&n===""){i=!0;break}e+=s[t]}return n!==""?!1:{value:e,index:t,tagClosed:i}}const ri=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function bn(s,t){const e=Wn(s,ri),n={};for(let i=0;i<e.length;i++){if(e[i][1].length===0)return S("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 S("InvalidAttr","Attribute '"+e[i][2]+"' is without value.",zt(e[i]));if(e[i][3]===void 0&&!t.allowBooleanAttributes)return S("InvalidAttr","boolean attribute '"+e[i][2]+"' is not allowed.",zt(e[i]));const r=e[i][2];if(!ci(r))return S("InvalidAttr","Attribute '"+r+"' is an invalid name.",zt(e[i]));if(!n.hasOwnProperty(r))n[r]=1;else return S("InvalidAttr","Attribute '"+r+"' is repeated.",zt(e[i]))}return!0}function oi(s,t){let e=/\d/;for(s[t]==="x"&&(t++,e=/[\da-fA-F]/);t<s.length;t++){if(s[t]===";")return t;if(!s[t].match(e))break}return-1}function ai(s,t){if(t++,s[t]===";")return-1;if(s[t]==="#")return t++,oi(s,t);let e=0;for(;t<s.length;t++,e++)if(!(s[t].match(/\w/)&&e<20)){if(s[t]===";")break;return-1}return t}function S(s,t,e){return{err:{code:s,msg:t,line:e.line||e,col:e.col}}}function ci(s){return Ee(s)}function li(s){return Ee(s)}function x(s,t){const e=s.substring(0,t).split(/\r?\n/);return{line:e.length,col:e[e.length-1].length+1}}function zt(s){return s.startIndex+s[1].length}const hi={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(s,t){return t},attributeValueProcessor:function(s,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(s,t,e){return s},captureMetaData:!1},ui=function(s){return Object.assign({},hi,s)};let le;typeof Symbol!="function"?le="@@xmlMetadata":le=Symbol("XML Node Metadata");class ft{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][le]={startIndex:e})}static getMetaDataSymbol(){return le}}class di{constructor(t){this.suppressValidationErr=!t}readDocType(t,e){const n={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let i=1,r=!1,o=!1,a="";for(;e<t.length;e++)if(t[e]==="<"&&!o){if(r&<(t,"!ENTITY",e)){e+=7;let c,l;[c,l,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),l.indexOf("&")===-1&&(n[c]={regx:RegExp(`&${c};`,"g"),val:l})}else if(r&<(t,"!ELEMENT",e)){e+=8;const{index:c}=this.readElementExp(t,e+1);e=c}else if(r&<(t,"!ATTLIST",e))e+=8;else if(r&<(t,"!NOTATION",e)){e+=9;const{index:c}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=c}else if(lt(t,"!--",e))o=!0;else throw new Error("Invalid DOCTYPE");i++,a=""}else if(t[e]===">"){if(o?t[e-1]==="-"&&t[e-2]==="-"&&(o=!1,i--):i--,i===0)break}else t[e]==="["?r=!0:a+=t[e];if(i!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:n,i:e}}readEntityExp(t,e){e=P(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e])&&t[e]!=='"'&&t[e]!=="'";)n+=t[e],e++;if(Ut(n),e=P(t,e),!this.suppressValidationErr){if(t.substring(e,e+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(t[e]==="%")throw new Error("Parameter entities are not supported")}let i="";return[e,i]=this.readIdentifierVal(t,e,"entity"),e--,[n,i,e]}readNotationExp(t,e){e=P(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;!this.suppressValidationErr&&Ut(n),e=P(t,e);const i=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&i!=="SYSTEM"&&i!=="PUBLIC")throw new Error(`Expected SYSTEM or PUBLIC, found "${i}"`);e+=i.length,e=P(t,e);let r=null,o=null;if(i==="PUBLIC")[e,r]=this.readIdentifierVal(t,e,"publicIdentifier"),e=P(t,e),(t[e]==='"'||t[e]==="'")&&([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"));else if(i==="SYSTEM"&&([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!o))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:n,publicIdentifier:r,systemIdentifier:o,index:--e}}readIdentifierVal(t,e,n){let i="";const r=t[e];if(r!=='"'&&r!=="'")throw new Error(`Expected quoted string, found "${r}"`);for(e++;e<t.length&&t[e]!==r;)i+=t[e],e++;if(t[e]!==r)throw new Error(`Unterminated ${n} value`);return e++,[e,i]}readElementExp(t,e){e=P(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;if(!this.suppressValidationErr&&!Ee(n))throw new Error(`Invalid element name: "${n}"`);e=P(t,e);let i="";if(t[e]==="E"&<(t,"MPTY",e))e+=4;else if(t[e]==="A"&<(t,"NY",e))e+=2;else if(t[e]==="("){for(e++;e<t.length&&t[e]!==")";)i+=t[e],e++;if(t[e]!==")")throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:n,contentModel:i.trim(),index:e}}readAttlistExp(t,e){e=P(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;Ut(n),e=P(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;if(!Ut(i))throw new Error(`Invalid attribute name: "${i}"`);e=P(t,e);let r="";if(t.substring(e,e+8).toUpperCase()==="NOTATION"){if(r="NOTATION",e+=8,e=P(t,e),t[e]!=="(")throw new Error(`Expected '(', found "${t[e]}"`);e++;let a=[];for(;e<t.length&&t[e]!==")";){let c="";for(;e<t.length&&t[e]!=="|"&&t[e]!==")";)c+=t[e],e++;if(c=c.trim(),!Ut(c))throw new Error(`Invalid notation name: "${c}"`);a.push(c),t[e]==="|"&&(e++,e=P(t,e))}if(t[e]!==")")throw new Error("Unterminated list of notations");e++,r+=" ("+a.join("|")+")"}else{for(;e<t.length&&!/\s/.test(t[e]);)r+=t[e],e++;const a=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!a.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}e=P(t,e);let o="";return t.substring(e,e+8).toUpperCase()==="#REQUIRED"?(o="#REQUIRED",e+=8):t.substring(e,e+7).toUpperCase()==="#IMPLIED"?(o="#IMPLIED",e+=7):[e,o]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:n,attributeName:i,attributeType:r,defaultValue:o,index:e}}}const P=(s,t)=>{for(;t<s.length&&/\s/.test(s[t]);)t++;return t};function lt(s,t,e){for(let n=0;n<t.length;n++)if(t[n]!==s[e+n+1])return!1;return!0}function Ut(s){if(Ee(s))return s;throw new Error(`Invalid entity name ${s}`)}const fi=/^[-+]?0x[a-fA-F0-9]+$/,pi=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,gi={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function mi(s,t={}){if(t=Object.assign({},gi,t),!s||typeof s!="string")return s;let e=s.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return s;if(s==="0")return 0;if(t.hex&&fi.test(e))return _i(e,16);if(e.search(/.+[eE].+/)!==-1)return wi(s,e,t);{const n=pi.exec(e);if(n){const i=n[1]||"",r=n[2];let o=Ei(n[3]);const a=i?s[r.length+1]===".":s[r.length]===".";if(!t.leadingZeros&&(r.length>1||r.length===1&&!a))return s;{const c=Number(e),l=String(c);if(c===0)return c;if(l.search(/[eE]/)!==-1)return t.eNotation?c:s;if(e.indexOf(".")!==-1)return l==="0"||l===o||l===`${i}${o}`?c:s;let u=r?o:e;return r?u===l||i+u===l?c:s:u===l||u===i+l?c:s}}else return s}}const yi=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function wi(s,t,e){if(!e.eNotation)return s;const n=t.match(yi);if(n){let i=n[1]||"";const r=n[3].indexOf("e")===-1?"E":"e",o=n[2],a=i?s[o.length+1]===r:s[o.length]===r;return o.length>1&&a?s:o.length===1&&(n[3].startsWith(`.${r}`)||n[3][0]===r)?Number(t):e.leadingZeros&&!a?(t=(n[1]||"")+n[3],Number(t)):s}else return s}function Ei(s){return s&&s.indexOf(".")!==-1&&(s=s.replace(/0+$/,""),s==="."?s="0":s[0]==="."?s="0"+s:s[s.length-1]==="."&&(s=s.substring(0,s.length-1))),s}function _i(s,t){if(parseInt)return parseInt(s,t);if(Number.parseInt)return Number.parseInt(s,t);if(window&&window.parseInt)return window.parseInt(s,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function Kn(s){return typeof s=="function"?s:Array.isArray(s)?t=>{for(const e of s)if(typeof e=="string"&&t===e||e instanceof RegExp&&e.test(t))return!0}:()=>!1}class Ai{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,n)=>String.fromCodePoint(Number.parseInt(n,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,n)=>String.fromCodePoint(Number.parseInt(n,16))}},this.addExternalEntities=bi,this.parseXml=Si,this.parseTextData=Ti,this.resolveNameSpace=Ni,this.buildAttributesMap=vi,this.isItStopNode=Ri,this.replaceEntitiesValue=ki,this.readStopNodeData=xi,this.saveTextToParentTag=Ci,this.addChild=Oi,this.ignoreAttributesFn=Kn(this.options.ignoreAttributes)}}function bi(s){const t=Object.keys(s);for(let e=0;e<t.length;e++){const n=t[e];this.lastEntities[n]={regex:new RegExp("&"+n+";","g"),val:s[n]}}}function Ti(s,t,e,n,i,r,o){if(s!==void 0&&(this.options.trimValues&&!n&&(s=s.trim()),s.length>0)){o||(s=this.replaceEntitiesValue(s));const a=this.options.tagValueProcessor(t,s,e,i,r);return a==null?s:typeof a!=typeof s||a!==s?a:this.options.trimValues?Me(s,this.options.parseTagValue,this.options.numberParseOptions):s.trim()===s?Me(s,this.options.parseTagValue,this.options.numberParseOptions):s}}function Ni(s){if(this.options.removeNSPrefix){const t=s.split(":"),e=s.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return"";t.length===2&&(s=e+t[1])}return s}const Ii=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function vi(s,t,e){if(this.options.ignoreAttributes!==!0&&typeof s=="string"){const n=Wn(s,Ii),i=n.length,r={};for(let o=0;o<i;o++){const a=this.resolveNameSpace(n[o][1]);if(this.ignoreAttributesFn(a,t))continue;let c=n[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 u=this.options.attributeValueProcessor(a,c,t);u==null?r[l]=c:typeof u!=typeof c||u!==c?r[l]=u:r[l]=Me(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 Si=function(s){s=s.replace(/\r\n?/g,`
|
|
4
|
-
`);const t=new ft("!xml");let e=t,n="",i="";const r=new di(this.options.processEntities);for(let o=0;o<s.length;o++)if(s[o]==="<")if(s[o+1]==="/"){const c=gt(s,">",o,"Closing Tag is not closed.");let l=s.substring(o+2,c).trim();if(this.options.removeNSPrefix){const d=l.indexOf(":");d!==-1&&(l=l.substr(d+1))}this.options.transformTagName&&(l=this.options.transformTagName(l)),e&&(n=this.saveTextToParentTag(n,e,i));const u=i.substring(i.lastIndexOf(".")+1);if(l&&this.options.unpairedTags.indexOf(l)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${l}>`);let h=0;u&&this.options.unpairedTags.indexOf(u)!==-1?(h=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):h=i.lastIndexOf("."),i=i.substring(0,h),e=this.tagsNodeStack.pop(),n="",o=c}else if(s[o+1]==="?"){let c=Re(s,o,!1,"?>");if(!c)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,e,i),!(this.options.ignoreDeclaration&&c.tagName==="?xml"||this.options.ignorePiTags)){const l=new ft(c.tagName);l.add(this.options.textNodeName,""),c.tagName!==c.tagExp&&c.attrExpPresent&&(l[":@"]=this.buildAttributesMap(c.tagExp,i,c.tagName)),this.addChild(e,l,i,o)}o=c.closeIndex+1}else if(s.substr(o+1,3)==="!--"){const c=gt(s,"-->",o+4,"Comment is not closed.");if(this.options.commentPropName){const l=s.substring(o+4,c-2);n=this.saveTextToParentTag(n,e,i),e.add(this.options.commentPropName,[{[this.options.textNodeName]:l}])}o=c}else if(s.substr(o+1,2)==="!D"){const c=r.readDocType(s,o);this.docTypeEntities=c.entities,o=c.i}else if(s.substr(o+1,2)==="!["){const c=gt(s,"]]>",o,"CDATA is not closed.")-2,l=s.substring(o+9,c);n=this.saveTextToParentTag(n,e,i);let u=this.parseTextData(l,e.tagname,i,!0,!1,!0,!0);u==null&&(u=""),this.options.cdataPropName?e.add(this.options.cdataPropName,[{[this.options.textNodeName]:l}]):e.add(this.options.textNodeName,u),o=c+2}else{let c=Re(s,o,this.options.removeNSPrefix),l=c.tagName;const u=c.rawTagName;let h=c.tagExp,d=c.attrExpPresent,g=c.closeIndex;this.options.transformTagName&&(l=this.options.transformTagName(l)),e&&n&&e.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,e,i,!1));const p=e;p&&this.options.unpairedTags.indexOf(p.tagname)!==-1&&(e=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),l!==t.tagname&&(i+=i?"."+l:l);const E=o;if(this.isItStopNode(this.options.stopNodes,i,l)){let A="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)l[l.length-1]==="/"?(l=l.substr(0,l.length-1),i=i.substr(0,i.length-1),h=l):h=h.substr(0,h.length-1),o=c.closeIndex;else if(this.options.unpairedTags.indexOf(l)!==-1)o=c.closeIndex;else{const v=this.readStopNodeData(s,u,g+1);if(!v)throw new Error(`Unexpected end of ${u}`);o=v.i,A=v.tagContent}const
|
|
5
|
-
`;function Ki(s,t){let e="";return t.format&&t.indentBy.length>0&&(e=Wi),zn(s,t,"",e)}function zn(s,t,e,n){let i="",r=!1;for(let o=0;o<s.length;o++){const a=s[o],c=Li(a);if(c===void 0)continue;let l="";if(e.length===0?l=c:l=`${e}.${c}`,c===t.textNodeName){let p=a[c];zi(l,t)||(p=t.tagValueProcessor(c,p),p=Un(p,t)),r&&(i+=n),i+=p,r=!1;continue}else if(c===t.cdataPropName){r&&(i+=n),i+=`<![CDATA[${a[c][0][t.textNodeName]}]]>`,r=!1;continue}else if(c===t.commentPropName){i+=n+`<!--${a[c][0][t.textNodeName]}-->`,r=!0;continue}else if(c[0]==="?"){const p=
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ge="MS Gothic, sans-serif",st={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Oe={WIDTH:125,HEIGHT:27.5},Pn={BASE:40},Q=",",f={M:"m",P:"p",S:"s",Z:"z",BACK:"_"},m={TSUMO:"t",RON:"v",DORA:"d",HORIZONTAL:"-",RED:"r",COLOR_GRAYSCALE:"^"},w={PON:"pon",CHI:"chi",SHO_KAN:"shokan",DAI_KAN:"daikan",AN_KAN:"ankan",TSUMO:"tsumo",PAIR:"pair",ISOLATED:"isolated",THREE:"three",RUN:"run",HAND:"hand",IMAGE_DORA:"dora",IMAGE_DISCARD:"simple-discard",UNKNOWN:"unknown"},_={E:"1z",S:"2z",W:"3z",N:"4z"},O={E1:"1z1",E2:"1z2",E3:"1z3",E4:"1z4",S1:"2z1",S2:"2z2",S3:"2z3",S4:"2z4",W1:"3z1",W2:"3z2",W3:"3z3",W4:"3z4",N1:"4z1",N2:"4z2",N3:"4z3",N4:"4z4"},ye={[_.E]:"東",[_.S]:"南",[_.W]:"西",[_.N]:"北"},Ye={[O.E1]:"東1局",[O.E2]:"東2局",[O.E3]:"東3局",[O.E4]:"東4局",[O.S1]:"南1局",[O.S2]:"南2局",[O.S3]:"南3局",[O.S4]:"南4局",[O.W1]:"西1局",[O.W2]:"西2局",[O.W3]:"西3局",[O.W4]:"西4局",[O.N1]:"北1局",[O.N2]:"北2局",[O.N3]:"北3局",[O.N4]:"北4局"};function b(s,t){if(!s)throw new Error(t)}class $s{ctx=null;strText;numText;constructor(t="東",e="2"){this.strText=t,this.numText=e}measure=(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),b(this.ctx,"context is null"));const n=this.ctx;n.font=e;const i=n.measureText(t);let r=i.width,o=i.actualBoundingBoxAscent+i.actualBoundingBoxDescent;return[r,o]};measureFontContext=(t,e)=>{const n={family:t,size:e},i=`${n.size}px ${n.family}`,[r,o]=this.measure(this.strText,i),[a,c]=this.measure(this.numText,i);return{font:{family:t,size:e},textWidth:r,textHeight:o,numWidth:a,numHeight:c}};measureTableFontContext=t=>{const e=this.measureFontContext(Ge,Pn.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e}}class Ps{input;position;nextPosition;char;eof="\0";constructor(t){this.input=t,this.position=0,this.nextPosition=0,this.char=this.readChar()}readChar(){return this.nextPosition>=this.input.length?(this.char=this.eof,this.char):(this.char=this.input[this.nextPosition],this.position=this.nextPosition,this.nextPosition++,this.char)}peekChar(){return this.nextPosition>=this.input.length?this.eof:this.input[this.nextPosition]}peekCharN(t){if(t<0)throw new Error("arg must be positive value");return this.position+t>=this.input.length?this.eof:this.input[this.position+t]}prevChar(){return this.position>=this.input.length?this.eof:this.position>0?this.input[this.position-1]:this.eof}skipWhitespace(){for(;this.isWhitespace(this.char);)this.readChar()}isWhitespace(t){return/\s/.test(t)}}const Qt=(s,t)=>{if(s.t==t.t){if(k(s)&&k(t)){if(s.has(m.RED))return-1;if(t.has(m.RED))return 1}return s.n-t.n}const e=[f.M,f.P,f.S,f.Z,f.BACK];return e.indexOf(s.t)-e.indexOf(t.t)},Hs=(s,t)=>{const e=[m.HORIZONTAL,m.TSUMO,m.RON,m.DORA,m.COLOR_GRAYSCALE,m.RED];return e.indexOf(s)-e.indexOf(t)},Hn=s=>{const t=[];s.forEach((n,i)=>{n.has(m.HORIZONTAL)&&t.push(i)});const e=s.filter(n=>!n.has(m.HORIZONTAL)).sort(Qt);return t.forEach(n=>{e.splice(n,0,s[n])}),e};function k(s){return s.isNum()&&s.n==5}function Bs(s){for(const t of Object.values(f))if(t==s)return[t,!0];return[f.BACK,!1]}class y{constructor(t,e,n=[]){this.t=t,this.n=e,this.ops=n}static from(t){const e=new W(t).tiles();if(e.length!=1)throw new Error(`input is not a single tile ${t}`);return e[0]}toString(){return this.t===f.BACK?this.t:`${[...this.ops].sort(Hs).join("")}${this.n}${this.t}`}toJSON(){return this.toString()}clone(t){const e=t?.t??this.t,n=t?.n??this.n,i=t?.removeAll?[]:this.ops.filter(o=>Array.isArray(t?.remove)?!t.remove.includes(o):t?.remove!=o),r=new Set([...i]);return t?.add&&(Array.isArray(t.add)?t.add.forEach(o=>r.add(o)):r.add(t.add)),new y(e,n,Array.from(r))}has(t){return this.ops.includes(t)}isNum(){return this.t==f.M||this.t==f.P||this.t==f.S}equals(t){return t.t==f.BACK&&this.t==f.BACK?!0:this.t==t.t&&this.n==t.n}}class T{_tiles;_type;constructor(t,e){if(this._tiles=t,this._type=e,this.isCalled()){this._tiles=Hn(this._tiles);return}if(this._type!=w.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Qt);return}}static from(t){const e=new W(t).parse();if(e.length!=1)throw new Error(`block must be 1: ${t}`);return e[0]}static deserialize(t){const e=T.from(t.tiles),n=e.type;if(!(t.type==w.PAIR||t.type==w.ISOLATED||t.type==w.THREE||t.type==w.RUN)&&n!=t.type)throw new Error(`input type is ${t.type} but got is ${n}: ${t.tiles}`);return ce(e.tiles,t.type)}serialize(){return{tiles:this.toString(),type:this.type}}toJSON(){return this.serialize()}get type(){return this._type}get tiles(){return this._tiles}is(t){return this._type==t}isCalled(){switch(this._type){case w.PON:case w.CHI:case w.DAI_KAN:case w.SHO_KAN:case w.AN_KAN:return!0;default:return!1}}clone(t){const e=t?.replace,n=[...this.tiles];return e&&(n[e.idx]=e.tile),ce(n,this._type)}}const bt=s=>{let t="";for(const e of s){if(e.t==f.BACK)return s.join("");t+=e.toString().slice(0,-1)}return`${t}${s[0].t}`},Ze=s=>{if(s.length==0)return"";let t=s[0].t,e="";for(const i of s){const r=i.t,o=r==f.BACK?i.toString():i.toString().slice(0,-1);r!=t&&t!=f.BACK&&(e+=t),t=r,e+=o}const n=s.at(-1);return n.t!=f.BACK&&(e+=n.t),e};class q extends T{constructor(t){super(t,w.CHI)}static from(t){return T.deserialize({tiles:t,type:w.CHI})}toString(){return bt(this.tiles)}}class U extends T{constructor(t){super(t,w.PON)}static from(t){return T.deserialize({tiles:t,type:w.PON})}toString(){return bt(this.tiles)}}class C extends T{constructor(t){const e=t.filter(i=>i.t!=f.BACK),n=e[0];if(e.length<t.length){if(k(n)){const i=new y(n.t,5);super([i.clone({add:m.RED}),i,i,i],w.AN_KAN);return}super([n,n,n,n],w.AN_KAN);return}super(t,w.AN_KAN)}get tiles(){return super.tiles}get tilesWithBack(){const t=this.tiles[0].clone({remove:m.RED}),e=k(t)?t.clone({add:m.RED}):t;return[new y(f.BACK,0),e,t,new y(f.BACK,0)]}static from(t){return T.deserialize({tiles:t,type:w.AN_KAN})}toString(){return Ze(this.tilesWithBack)}}class F extends T{constructor(t){super(t,w.DAI_KAN)}static from(t){return T.deserialize({tiles:t,type:w.DAI_KAN})}toString(){return bt(this.tiles)}}class H extends T{constructor(t){super(t,w.SHO_KAN)}static from(t){return T.deserialize({tiles:t,type:w.SHO_KAN})}static fromPon(t,e){const n=t.tiles.findIndex(r=>r.has(m.HORIZONTAL)),i=[...t.tiles];return i.splice(n,0,e.clone({add:m.HORIZONTAL})),new H(i)}toString(){return bt(this.tiles)}}class R extends T{constructor(t,e){super([t,e],w.PAIR)}toString(){return bt(this.tiles)}static from(t){return T.deserialize({tiles:t,type:w.PAIR})}}class K extends T{constructor(t){super(t,w.THREE)}static from(t){return T.deserialize({tiles:t,type:w.THREE})}toString(){return bt(this.tiles)}}class tt extends T{constructor(t){super(t,w.RUN)}static from(t){return T.deserialize({tiles:t,type:w.RUN})}toString(){return bt(this.tiles)}}class Ve extends T{constructor(t){super([t],w.ISOLATED)}static from(t){return T.deserialize({tiles:t,type:w.ISOLATED})}toString(){return this.tiles[0].toString()}}class Rt extends T{constructor(t){super(t,w.HAND)}static from(t){return T.deserialize({tiles:t,type:w.HAND})}toString(){return Ze(this.tiles)}}class Je extends T{constructor(t,e){super(t,e)}toString(){return this.is(w.IMAGE_DISCARD)?this.tiles.join(""):Ze(this.tiles)}}const ce=(s,t)=>{switch(t){case w.CHI:return new q([s[0],s[1],s[2]]);case w.PON:return new U([s[0],s[1],s[2]]);case w.AN_KAN:return new C(s);case w.DAI_KAN:return new F(s);case w.SHO_KAN:return new H(s);case w.THREE:return new K(s);case w.RUN:return new tt(s);case w.PAIR:return new R(s[0],s[1]);case w.ISOLATED:return new Ve(s[0]);case w.HAND:return new Rt(s);default:return new Je(s,t)}};class W{constructor(t){this.input=t,this.input=t.replace(/\s/g,"")}maxInputLength=600;parse(){const t=this.tileSeparators();return this.makeBlocks(t)}tiles(){return this.tileSeparators().filter(t=>t!=Q)}tileSeparators(){const t=new Ps(this.input),e=[];let n=[];for(this.validate(this.input);;){t.skipWhitespace();const i=t.char;if(i===t.eof)break;if(i==Q){e.push(Q),t.readChar();continue}const[r,o]=yn(i,n);if(o){if(r==f.BACK){e.push(new y(r,0)),t.readChar();continue}e.push(...Ws(n,r)),n=[],t.readChar();continue}else{const[a,c]=Ks(t);if(c){n.push(a),t.readChar();continue}const[l,u]=Bn(i);if(!u)throw new Error(`encounter unexpected number. n: ${l}, current: ${i}, input: ${t.input}`);n.push({n:l})}t.readChar()}if(n.length>0)throw new Error(`remaining values ${n.toString()}`);return e}makeBlocks(t){let e=[];const n=[];if(t.length==0)return n;for(const o of t){if(o==Q){const a=mn(e),c=ce(e,a);n.push(c),e=[];continue}e.push(o)}const i=mn(e),r=ce(e,i);return n.push(r),e=[],n}validate(t){if(t.length==0)return;if(t.length>this.maxInputLength)throw new Error(`exceeded maximum input length(${t.length})`);const e=t.charAt(t.length-1),[n,i]=yn(e,[new y(f.BACK,1)]);if(!i)throw new Error(`last character: ${e} is not type value: ${t}`)}}function mn(s){if(s.length===0)return w.UNKNOWN;if(s.length===1)return s[0].has(m.DORA)?w.IMAGE_DORA:s[0].has(m.TSUMO)?w.TSUMO:w.HAND;const t=s.every(r=>r.equals(s[0])),e=s.filter(r=>r.has(m.HORIZONTAL)).length,n=s.filter(r=>r.has(m.TSUMO)||r.has(m.DORA)).length,i=s.filter(r=>r.t==f.BACK).length;if(n>0)return w.UNKNOWN;if(e==0&&i==0)return w.HAND;if(s.length===3&&i===0)return t?w.PON:e==1&&Ds(s)?w.CHI:w.IMAGE_DISCARD;if(s.length==4&&i==2)return w.AN_KAN;if(s.length==4&&t){if(e==1)return w.DAI_KAN;if(e==2)return w.SHO_KAN}return e==1||n==0?w.IMAGE_DISCARD:w.UNKNOWN}function Ds(s){const t=[...s].sort(Qt);if(t.some(n=>t[0].t!=n.t))return!1;const e=t.map(n=>n.n);for(let n=0;n<e.length-1;n++)if(e[n]!=e[n+1]-1)return!1;return!0}function Ws(s,t){return s.map(e=>{const n=new y(t,e.n,e.ops);return n.isNum()&&n.n==0?n.clone({n:5,add:m.RED}):n})}function yn(s,t){const[e,n]=Bs(s);if(n)return[e,!0];if((s==="w"||s==="d")&&t.length>0){for(let r=0;r<t.length;r++){const o=t[r];s==="d"&&(t[r].n=o.n+4)}return[f.Z,!0]}return[f.BACK,!1]}function Bn(s){const t=Number(s),e=0<=t&&t<=9;return[t,e]}function Ks(s){const t=Object.values(m);if(!t.includes(s.char))return[new y(f.BACK,0),!1];const e=[];for(let n=0;n<4;n++){const i=s.peekCharN(n);if(t.includes(i))e.push(i);else{const[r,o]=Bn(i);if(!o)break;for(const c of e)s.readChar();const a=new y(f.BACK,r,e);if(a.has(m.RED)&&a.n!=5)throw new Error(`found ${m.RED} but number is not 5: ${r}`);if(a.has(m.DORA)&&a.has(m.TSUMO))throw new Error(`unable to specify both ${m.DORA} and ${m.TSUMO}`);return[a,!0]}}return[new y(f.BACK,0),!1]}function P(s,t=!1){const e={[_.E]:s,[_.S]:s,[_.W]:s,[_.N]:s};if(t)for(let n of Object.values(_))e[n]=structuredClone(s);return e}const Vt=s=>{let t=s.substring(0,2),e=Number(s.substring(2,3));return e==4?(e=1,t=yt(t)):e++,`${t}${e}`},Ls=s=>Vt(Vt(Vt(s))),yt=s=>{let t=Number(s.toString()[0]);return t=t%4+1,`${t}${f.Z}`},we=s=>{let t=Number(s.toString()[0]);const e=[1,4,3,2],n=e.indexOf(t);return`${e[(n+1)%e.length]}${f.Z}`},ke=(s,t,e)=>{const n=Math.abs(Number(s[0])-Number(t[0]));return b(n==1||n==2||n==3),e==w.PON?n==3?0:n==2?1:2:n==3?0:n==1?3:2};function wn(s){return typeof s>"u"}function Ce(s,t=0){return{a:1,c:0,e:s,b:0,d:1,f:t}}function Xe(...s){s=Array.isArray(s[0])?s[0]:s;const t=(e,n)=>({a:e.a*n.a+e.c*n.b,c:e.a*n.c+e.c*n.d,e:e.a*n.e+e.c*n.f+e.e,b:e.b*n.a+e.d*n.b,d:e.b*n.c+e.d*n.d,f:e.b*n.e+e.d*n.f+e.f});switch(s.length){case 0:throw new Error("no matrices provided");case 1:return s[0];case 2:return t(s[0],s[1]);default:{const[e,n,...i]=s,r=t(e,n);return Xe(r,...i)}}}function zs(...s){return Xe(...s)}const{cos:Us,sin:js,PI:Fs}=Math;function Gs(s,t,e){const n=Us(s),i=js(s),r={a:n,c:-i,e:0,b:i,d:n,f:0};return wn(t)||wn(e)?r:Xe([Ce(t,e),r,Ce(-t,-e)])}function Ys(s,t=void 0,e=void 0){return Gs(s*Fs/180,t,e)}function Zs(s){return Vs(s)}function Vs(s){return`matrix(${s.a},${s.b},${s.c},${s.d},${s.e},${s.f})`}const Dn=":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",Js=Dn+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Xs="["+Dn+"]["+Js+"]*",qs=new RegExp("^"+Xs+"$");function Wn(s,t){const e=[];let n=t.exec(s);for(;n;){const i=[];i.startIndex=t.lastIndex-n[0].length;const r=n.length;for(let o=0;o<r;o++)i.push(n[o]);e.push(i),n=t.exec(s)}return e}const Ee=function(s){const t=qs.exec(s);return!(t===null||typeof t>"u")};function Qs(s){return typeof s<"u"}const ti={allowBooleanAttributes:!1,unpairedTags:[]};function ei(s,t){t=Object.assign({},ti,t);const e=[];let n=!1,i=!1;s[0]==="\uFEFF"&&(s=s.substr(1));for(let r=0;r<s.length;r++)if(s[r]==="<"&&s[r+1]==="?"){if(r+=2,r=_n(s,r),r.err)return r}else if(s[r]==="<"){let o=r;if(r++,s[r]==="!"){r=An(s,r);continue}else{let a=!1;s[r]==="/"&&(a=!0,r++);let c="";for(;r<s.length&&s[r]!==">"&&s[r]!==" "&&s[r]!==" "&&s[r]!==`
|
|
2
|
+
`&&s[r]!=="\r";r++)c+=s[r];if(c=c.trim(),c[c.length-1]==="/"&&(c=c.substring(0,c.length-1),r--),!li(c)){let h;return c.trim().length===0?h="Invalid space after '<'.":h="Tag '"+c+"' is an invalid name.",S("InvalidTag",h,$(s,r))}const l=ii(s,r);if(l===!1)return S("InvalidAttr","Attributes for '"+c+"' have open quote.",$(s,r));let u=l.value;if(r=l.index,u[u.length-1]==="/"){const h=r-u.length;u=u.substring(0,u.length-1);const d=bn(u,t);if(d===!0)n=!0;else return S(d.err.code,d.err.msg,$(s,h+d.err.line))}else if(a)if(l.tagClosed){if(u.trim().length>0)return S("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",$(s,o));if(e.length===0)return S("InvalidTag","Closing tag '"+c+"' has not been opened.",$(s,o));{const h=e.pop();if(c!==h.tagName){let d=$(s,h.tagStartPos);return S("InvalidTag","Expected closing tag '"+h.tagName+"' (opened in line "+d.line+", col "+d.col+") instead of closing tag '"+c+"'.",$(s,o))}e.length==0&&(i=!0)}}else return S("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",$(s,r));else{const h=bn(u,t);if(h!==!0)return S(h.err.code,h.err.msg,$(s,r-u.length+h.err.line));if(i===!0)return S("InvalidXml","Multiple possible root nodes found.",$(s,r));t.unpairedTags.indexOf(c)!==-1||e.push({tagName:c,tagStartPos:o}),n=!0}for(r++;r<s.length;r++)if(s[r]==="<")if(s[r+1]==="!"){r++,r=An(s,r);continue}else if(s[r+1]==="?"){if(r=_n(s,++r),r.err)return r}else break;else if(s[r]==="&"){const h=ai(s,r);if(h==-1)return S("InvalidChar","char '&' is not expected.",$(s,r));r=h}else if(i===!0&&!En(s[r]))return S("InvalidXml","Extra text at the end",$(s,r));s[r]==="<"&&r--}}else{if(En(s[r]))continue;return S("InvalidChar","char '"+s[r]+"' is not expected.",$(s,r))}if(n){if(e.length==1)return S("InvalidTag","Unclosed tag '"+e[0].tagName+"'.",$(s,e[0].tagStartPos));if(e.length>0)return S("InvalidXml","Invalid '"+JSON.stringify(e.map(r=>r.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return S("InvalidXml","Start tag expected.",1);return!0}function En(s){return s===" "||s===" "||s===`
|
|
3
|
+
`||s==="\r"}function _n(s,t){const e=t;for(;t<s.length;t++)if(s[t]=="?"||s[t]==" "){const n=s.substr(e,t-e);if(t>5&&n==="xml")return S("InvalidXml","XML declaration allowed only at the start of the document.",$(s,t));if(s[t]=="?"&&s[t+1]==">"){t++;break}else continue}return t}function An(s,t){if(s.length>t+5&&s[t+1]==="-"&&s[t+2]==="-"){for(t+=3;t<s.length;t++)if(s[t]==="-"&&s[t+1]==="-"&&s[t+2]===">"){t+=2;break}}else if(s.length>t+8&&s[t+1]==="D"&&s[t+2]==="O"&&s[t+3]==="C"&&s[t+4]==="T"&&s[t+5]==="Y"&&s[t+6]==="P"&&s[t+7]==="E"){let e=1;for(t+=8;t<s.length;t++)if(s[t]==="<")e++;else if(s[t]===">"&&(e--,e===0))break}else if(s.length>t+9&&s[t+1]==="["&&s[t+2]==="C"&&s[t+3]==="D"&&s[t+4]==="A"&&s[t+5]==="T"&&s[t+6]==="A"&&s[t+7]==="["){for(t+=8;t<s.length;t++)if(s[t]==="]"&&s[t+1]==="]"&&s[t+2]===">"){t+=2;break}}return t}const ni='"',si="'";function ii(s,t){let e="",n="",i=!1;for(;t<s.length;t++){if(s[t]===ni||s[t]===si)n===""?n=s[t]:n!==s[t]||(n="");else if(s[t]===">"&&n===""){i=!0;break}e+=s[t]}return n!==""?!1:{value:e,index:t,tagClosed:i}}const ri=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function bn(s,t){const e=Wn(s,ri),n={};for(let i=0;i<e.length;i++){if(e[i][1].length===0)return S("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 S("InvalidAttr","Attribute '"+e[i][2]+"' is without value.",zt(e[i]));if(e[i][3]===void 0&&!t.allowBooleanAttributes)return S("InvalidAttr","boolean attribute '"+e[i][2]+"' is not allowed.",zt(e[i]));const r=e[i][2];if(!ci(r))return S("InvalidAttr","Attribute '"+r+"' is an invalid name.",zt(e[i]));if(!n.hasOwnProperty(r))n[r]=1;else return S("InvalidAttr","Attribute '"+r+"' is repeated.",zt(e[i]))}return!0}function oi(s,t){let e=/\d/;for(s[t]==="x"&&(t++,e=/[\da-fA-F]/);t<s.length;t++){if(s[t]===";")return t;if(!s[t].match(e))break}return-1}function ai(s,t){if(t++,s[t]===";")return-1;if(s[t]==="#")return t++,oi(s,t);let e=0;for(;t<s.length;t++,e++)if(!(s[t].match(/\w/)&&e<20)){if(s[t]===";")break;return-1}return t}function S(s,t,e){return{err:{code:s,msg:t,line:e.line||e,col:e.col}}}function ci(s){return Ee(s)}function li(s){return Ee(s)}function $(s,t){const e=s.substring(0,t).split(/\r?\n/);return{line:e.length,col:e[e.length-1].length+1}}function zt(s){return s.startIndex+s[1].length}const hi={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(s,t){return t},attributeValueProcessor:function(s,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(s,t,e){return s},captureMetaData:!1},ui=function(s){return Object.assign({},hi,s)};let le;typeof Symbol!="function"?le="@@xmlMetadata":le=Symbol("XML Node Metadata");class ft{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][le]={startIndex:e})}static getMetaDataSymbol(){return le}}class di{constructor(t){this.suppressValidationErr=!t}readDocType(t,e){const n={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let i=1,r=!1,o=!1,a="";for(;e<t.length;e++)if(t[e]==="<"&&!o){if(r&<(t,"!ENTITY",e)){e+=7;let c,l;[c,l,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),l.indexOf("&")===-1&&(n[c]={regx:RegExp(`&${c};`,"g"),val:l})}else if(r&<(t,"!ELEMENT",e)){e+=8;const{index:c}=this.readElementExp(t,e+1);e=c}else if(r&<(t,"!ATTLIST",e))e+=8;else if(r&<(t,"!NOTATION",e)){e+=9;const{index:c}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=c}else if(lt(t,"!--",e))o=!0;else throw new Error("Invalid DOCTYPE");i++,a=""}else if(t[e]===">"){if(o?t[e-1]==="-"&&t[e-2]==="-"&&(o=!1,i--):i--,i===0)break}else t[e]==="["?r=!0:a+=t[e];if(i!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:n,i:e}}readEntityExp(t,e){e=B(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e])&&t[e]!=='"'&&t[e]!=="'";)n+=t[e],e++;if(Ut(n),e=B(t,e),!this.suppressValidationErr){if(t.substring(e,e+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(t[e]==="%")throw new Error("Parameter entities are not supported")}let i="";return[e,i]=this.readIdentifierVal(t,e,"entity"),e--,[n,i,e]}readNotationExp(t,e){e=B(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;!this.suppressValidationErr&&Ut(n),e=B(t,e);const i=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&i!=="SYSTEM"&&i!=="PUBLIC")throw new Error(`Expected SYSTEM or PUBLIC, found "${i}"`);e+=i.length,e=B(t,e);let r=null,o=null;if(i==="PUBLIC")[e,r]=this.readIdentifierVal(t,e,"publicIdentifier"),e=B(t,e),(t[e]==='"'||t[e]==="'")&&([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"));else if(i==="SYSTEM"&&([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!o))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:n,publicIdentifier:r,systemIdentifier:o,index:--e}}readIdentifierVal(t,e,n){let i="";const r=t[e];if(r!=='"'&&r!=="'")throw new Error(`Expected quoted string, found "${r}"`);for(e++;e<t.length&&t[e]!==r;)i+=t[e],e++;if(t[e]!==r)throw new Error(`Unterminated ${n} value`);return e++,[e,i]}readElementExp(t,e){e=B(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;if(!this.suppressValidationErr&&!Ee(n))throw new Error(`Invalid element name: "${n}"`);e=B(t,e);let i="";if(t[e]==="E"&<(t,"MPTY",e))e+=4;else if(t[e]==="A"&<(t,"NY",e))e+=2;else if(t[e]==="("){for(e++;e<t.length&&t[e]!==")";)i+=t[e],e++;if(t[e]!==")")throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:n,contentModel:i.trim(),index:e}}readAttlistExp(t,e){e=B(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;Ut(n),e=B(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;if(!Ut(i))throw new Error(`Invalid attribute name: "${i}"`);e=B(t,e);let r="";if(t.substring(e,e+8).toUpperCase()==="NOTATION"){if(r="NOTATION",e+=8,e=B(t,e),t[e]!=="(")throw new Error(`Expected '(', found "${t[e]}"`);e++;let a=[];for(;e<t.length&&t[e]!==")";){let c="";for(;e<t.length&&t[e]!=="|"&&t[e]!==")";)c+=t[e],e++;if(c=c.trim(),!Ut(c))throw new Error(`Invalid notation name: "${c}"`);a.push(c),t[e]==="|"&&(e++,e=B(t,e))}if(t[e]!==")")throw new Error("Unterminated list of notations");e++,r+=" ("+a.join("|")+")"}else{for(;e<t.length&&!/\s/.test(t[e]);)r+=t[e],e++;const a=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!a.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}e=B(t,e);let o="";return t.substring(e,e+8).toUpperCase()==="#REQUIRED"?(o="#REQUIRED",e+=8):t.substring(e,e+7).toUpperCase()==="#IMPLIED"?(o="#IMPLIED",e+=7):[e,o]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:n,attributeName:i,attributeType:r,defaultValue:o,index:e}}}const B=(s,t)=>{for(;t<s.length&&/\s/.test(s[t]);)t++;return t};function lt(s,t,e){for(let n=0;n<t.length;n++)if(t[n]!==s[e+n+1])return!1;return!0}function Ut(s){if(Ee(s))return s;throw new Error(`Invalid entity name ${s}`)}const fi=/^[-+]?0x[a-fA-F0-9]+$/,pi=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,gi={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function mi(s,t={}){if(t=Object.assign({},gi,t),!s||typeof s!="string")return s;let e=s.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return s;if(s==="0")return 0;if(t.hex&&fi.test(e))return _i(e,16);if(e.search(/.+[eE].+/)!==-1)return wi(s,e,t);{const n=pi.exec(e);if(n){const i=n[1]||"",r=n[2];let o=Ei(n[3]);const a=i?s[r.length+1]===".":s[r.length]===".";if(!t.leadingZeros&&(r.length>1||r.length===1&&!a))return s;{const c=Number(e),l=String(c);if(c===0)return c;if(l.search(/[eE]/)!==-1)return t.eNotation?c:s;if(e.indexOf(".")!==-1)return l==="0"||l===o||l===`${i}${o}`?c:s;let u=r?o:e;return r?u===l||i+u===l?c:s:u===l||u===i+l?c:s}}else return s}}const yi=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function wi(s,t,e){if(!e.eNotation)return s;const n=t.match(yi);if(n){let i=n[1]||"";const r=n[3].indexOf("e")===-1?"E":"e",o=n[2],a=i?s[o.length+1]===r:s[o.length]===r;return o.length>1&&a?s:o.length===1&&(n[3].startsWith(`.${r}`)||n[3][0]===r)?Number(t):e.leadingZeros&&!a?(t=(n[1]||"")+n[3],Number(t)):s}else return s}function Ei(s){return s&&s.indexOf(".")!==-1&&(s=s.replace(/0+$/,""),s==="."?s="0":s[0]==="."?s="0"+s:s[s.length-1]==="."&&(s=s.substring(0,s.length-1))),s}function _i(s,t){if(parseInt)return parseInt(s,t);if(Number.parseInt)return Number.parseInt(s,t);if(window&&window.parseInt)return window.parseInt(s,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function Kn(s){return typeof s=="function"?s:Array.isArray(s)?t=>{for(const e of s)if(typeof e=="string"&&t===e||e instanceof RegExp&&e.test(t))return!0}:()=>!1}class Ai{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,n)=>String.fromCodePoint(Number.parseInt(n,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,n)=>String.fromCodePoint(Number.parseInt(n,16))}},this.addExternalEntities=bi,this.parseXml=Si,this.parseTextData=Ii,this.resolveNameSpace=Ni,this.buildAttributesMap=vi,this.isItStopNode=Ri,this.replaceEntitiesValue=ki,this.readStopNodeData=xi,this.saveTextToParentTag=Ci,this.addChild=Oi,this.ignoreAttributesFn=Kn(this.options.ignoreAttributes)}}function bi(s){const t=Object.keys(s);for(let e=0;e<t.length;e++){const n=t[e];this.lastEntities[n]={regex:new RegExp("&"+n+";","g"),val:s[n]}}}function Ii(s,t,e,n,i,r,o){if(s!==void 0&&(this.options.trimValues&&!n&&(s=s.trim()),s.length>0)){o||(s=this.replaceEntitiesValue(s));const a=this.options.tagValueProcessor(t,s,e,i,r);return a==null?s:typeof a!=typeof s||a!==s?a:this.options.trimValues?Me(s,this.options.parseTagValue,this.options.numberParseOptions):s.trim()===s?Me(s,this.options.parseTagValue,this.options.numberParseOptions):s}}function Ni(s){if(this.options.removeNSPrefix){const t=s.split(":"),e=s.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return"";t.length===2&&(s=e+t[1])}return s}const Ti=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function vi(s,t,e){if(this.options.ignoreAttributes!==!0&&typeof s=="string"){const n=Wn(s,Ti),i=n.length,r={};for(let o=0;o<i;o++){const a=this.resolveNameSpace(n[o][1]);if(this.ignoreAttributesFn(a,t))continue;let c=n[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 u=this.options.attributeValueProcessor(a,c,t);u==null?r[l]=c:typeof u!=typeof c||u!==c?r[l]=u:r[l]=Me(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 Si=function(s){s=s.replace(/\r\n?/g,`
|
|
4
|
+
`);const t=new ft("!xml");let e=t,n="",i="";const r=new di(this.options.processEntities);for(let o=0;o<s.length;o++)if(s[o]==="<")if(s[o+1]==="/"){const c=gt(s,">",o,"Closing Tag is not closed.");let l=s.substring(o+2,c).trim();if(this.options.removeNSPrefix){const d=l.indexOf(":");d!==-1&&(l=l.substr(d+1))}this.options.transformTagName&&(l=this.options.transformTagName(l)),e&&(n=this.saveTextToParentTag(n,e,i));const u=i.substring(i.lastIndexOf(".")+1);if(l&&this.options.unpairedTags.indexOf(l)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${l}>`);let h=0;u&&this.options.unpairedTags.indexOf(u)!==-1?(h=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):h=i.lastIndexOf("."),i=i.substring(0,h),e=this.tagsNodeStack.pop(),n="",o=c}else if(s[o+1]==="?"){let c=Re(s,o,!1,"?>");if(!c)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,e,i),!(this.options.ignoreDeclaration&&c.tagName==="?xml"||this.options.ignorePiTags)){const l=new ft(c.tagName);l.add(this.options.textNodeName,""),c.tagName!==c.tagExp&&c.attrExpPresent&&(l[":@"]=this.buildAttributesMap(c.tagExp,i,c.tagName)),this.addChild(e,l,i,o)}o=c.closeIndex+1}else if(s.substr(o+1,3)==="!--"){const c=gt(s,"-->",o+4,"Comment is not closed.");if(this.options.commentPropName){const l=s.substring(o+4,c-2);n=this.saveTextToParentTag(n,e,i),e.add(this.options.commentPropName,[{[this.options.textNodeName]:l}])}o=c}else if(s.substr(o+1,2)==="!D"){const c=r.readDocType(s,o);this.docTypeEntities=c.entities,o=c.i}else if(s.substr(o+1,2)==="!["){const c=gt(s,"]]>",o,"CDATA is not closed.")-2,l=s.substring(o+9,c);n=this.saveTextToParentTag(n,e,i);let u=this.parseTextData(l,e.tagname,i,!0,!1,!0,!0);u==null&&(u=""),this.options.cdataPropName?e.add(this.options.cdataPropName,[{[this.options.textNodeName]:l}]):e.add(this.options.textNodeName,u),o=c+2}else{let c=Re(s,o,this.options.removeNSPrefix),l=c.tagName;const u=c.rawTagName;let h=c.tagExp,d=c.attrExpPresent,g=c.closeIndex;this.options.transformTagName&&(l=this.options.transformTagName(l)),e&&n&&e.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,e,i,!1));const p=e;p&&this.options.unpairedTags.indexOf(p.tagname)!==-1&&(e=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),l!==t.tagname&&(i+=i?"."+l:l);const E=o;if(this.isItStopNode(this.options.stopNodes,i,l)){let A="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)l[l.length-1]==="/"?(l=l.substr(0,l.length-1),i=i.substr(0,i.length-1),h=l):h=h.substr(0,h.length-1),o=c.closeIndex;else if(this.options.unpairedTags.indexOf(l)!==-1)o=c.closeIndex;else{const v=this.readStopNodeData(s,u,g+1);if(!v)throw new Error(`Unexpected end of ${u}`);o=v.i,A=v.tagContent}const I=new ft(l);l!==h&&d&&(I[":@"]=this.buildAttributesMap(h,i,l)),A&&(A=this.parseTextData(A,l,i,!0,d,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),I.add(this.options.textNodeName,A),this.addChild(e,I,i,E)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){l[l.length-1]==="/"?(l=l.substr(0,l.length-1),i=i.substr(0,i.length-1),h=l):h=h.substr(0,h.length-1),this.options.transformTagName&&(l=this.options.transformTagName(l));const A=new ft(l);l!==h&&d&&(A[":@"]=this.buildAttributesMap(h,i,l)),this.addChild(e,A,i,E),i=i.substr(0,i.lastIndexOf("."))}else{const A=new ft(l);this.tagsNodeStack.push(e),l!==h&&d&&(A[":@"]=this.buildAttributesMap(h,i,l)),this.addChild(e,A,i,E),e=A}n="",o=g}}else n+=s[o];return t.child};function Oi(s,t,e,n){this.options.captureMetaData||(n=void 0);const i=this.options.updateTag(t.tagname,e,t[":@"]);i===!1||(typeof i=="string"&&(t.tagname=i),s.addChild(t,n))}const ki=function(s){if(this.options.processEntities){for(let t in this.docTypeEntities){const e=this.docTypeEntities[t];s=s.replace(e.regx,e.val)}for(let t in this.lastEntities){const e=this.lastEntities[t];s=s.replace(e.regex,e.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const e=this.htmlEntities[t];s=s.replace(e.regex,e.val)}s=s.replace(this.ampEntity.regex,this.ampEntity.val)}return s};function Ci(s,t,e,n){return s&&(n===void 0&&(n=t.child.length===0),s=this.parseTextData(s,t.tagname,e,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,n),s!==void 0&&s!==""&&t.add(this.options.textNodeName,s),s=""),s}function Ri(s,t,e){const n="*."+e;for(const i in s){const r=s[i];if(n===r||t===r)return!0}return!1}function Mi(s,t,e=">"){let n,i="";for(let r=t;r<s.length;r++){let o=s[r];if(n)o===n&&(n="");else if(o==='"'||o==="'")n=o;else if(o===e[0])if(e[1]){if(s[r+1]===e[1])return{data:i,index:r}}else return{data:i,index:r};else o===" "&&(o=" ");i+=o}}function gt(s,t,e,n){const i=s.indexOf(t,e);if(i===-1)throw new Error(n);return i+t.length-1}function Re(s,t,e,n=">"){const i=Mi(s,t+1,n);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 u=c;if(e){const h=c.indexOf(":");h!==-1&&(c=c.substr(h+1),l=c!==i.data.substr(h+1))}return{tagName:c,tagExp:r,closeIndex:o,attrExpPresent:l,rawTagName:u}}function xi(s,t,e){const n=e;let i=1;for(;e<s.length;e++)if(s[e]==="<")if(s[e+1]==="/"){const r=gt(s,">",e,`${t} is not closed`);if(s.substring(e+2,r).trim()===t&&(i--,i===0))return{tagContent:s.substring(n,e),i:r};e=r}else if(s[e+1]==="?")e=gt(s,"?>",e+1,"StopNode is not closed.");else if(s.substr(e+1,3)==="!--")e=gt(s,"-->",e+3,"StopNode is not closed.");else if(s.substr(e+1,2)==="![")e=gt(s,"]]>",e,"StopNode is not closed.")-2;else{const r=Re(s,e,">");r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!=="/"&&i++,e=r.closeIndex)}}function Me(s,t,e){if(t&&typeof s=="string"){const n=s.trim();return n==="true"?!0:n==="false"?!1:mi(s,e)}else return Qs(s)?s:""}const Ie=ft.getMetaDataSymbol();function $i(s,t){return Ln(s,t)}function Ln(s,t,e){let n;const i={};for(let r=0;r<s.length;r++){const o=s[r],a=Pi(o);let c="";if(e===void 0?c=a:c=e+"."+a,a===t.textNodeName)n===void 0?n=o[a]:n+=""+o[a];else{if(a===void 0)continue;if(o[a]){let l=Ln(o[a],t,c);const u=Bi(l,t);o[Ie]!==void 0&&(l[Ie]=o[Ie]),o[":@"]?Hi(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,u)?i[a]=[l]:i[a]=l}}}return typeof n=="string"?n.length>0&&(i[t.textNodeName]=n):n!==void 0&&(i[t.textNodeName]=n),i}function Pi(s){const t=Object.keys(s);for(let e=0;e<t.length;e++){const n=t[e];if(n!==":@")return n}}function Hi(s,t,e,n){if(t){const i=Object.keys(t),r=i.length;for(let o=0;o<r;o++){const a=i[o];n.isArray(a,e+"."+a,!0,!0)?s[a]=[t[a]]:s[a]=t[a]}}}function Bi(s,t){const{textNodeName:e}=t,n=Object.keys(s).length;return!!(n===0||n===1&&(s[e]||typeof s[e]=="boolean"||s[e]===0))}class Di{constructor(t){this.externalEntities={},this.options=ui(t)}parse(t,e){if(typeof t!="string"&&t.toString)t=t.toString();else if(typeof t!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});const r=ei(t,e);if(r!==!0)throw Error(`${r.err.msg}:${r.err.line}:${r.err.col}`)}const n=new Ai(this.options);n.addExternalEntities(this.externalEntities);const i=n.parseXml(t);return this.options.preserveOrder||i===void 0?i:$i(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 ft.getMetaDataSymbol()}}const Wi=`
|
|
5
|
+
`;function Ki(s,t){let e="";return t.format&&t.indentBy.length>0&&(e=Wi),zn(s,t,"",e)}function zn(s,t,e,n){let i="",r=!1;for(let o=0;o<s.length;o++){const a=s[o],c=Li(a);if(c===void 0)continue;let l="";if(e.length===0?l=c:l=`${e}.${c}`,c===t.textNodeName){let p=a[c];zi(l,t)||(p=t.tagValueProcessor(c,p),p=Un(p,t)),r&&(i+=n),i+=p,r=!1;continue}else if(c===t.cdataPropName){r&&(i+=n),i+=`<![CDATA[${a[c][0][t.textNodeName]}]]>`,r=!1;continue}else if(c===t.commentPropName){i+=n+`<!--${a[c][0][t.textNodeName]}-->`,r=!0;continue}else if(c[0]==="?"){const p=In(a[":@"],t),E=c==="?xml"?"":n;let A=a[c][0][t.textNodeName];A=A.length!==0?" "+A:"",i+=E+`<${c}${A}${p}?>`,r=!0;continue}let u=n;u!==""&&(u+=t.indentBy);const h=In(a[":@"],t),d=n+`<${c}${h}`,g=zn(a[c],t,l,u);t.unpairedTags.indexOf(c)!==-1?t.suppressUnpairedNode?i+=d+">":i+=d+"/>":(!g||g.length===0)&&t.suppressEmptyNode?i+=d+"/>":g&&g.endsWith(">")?i+=d+`>${g}${n}</${c}>`:(i+=d+">",g&&n!==""&&(g.includes("/>")||g.includes("</"))?i+=n+t.indentBy+g+n:i+=g,i+=`</${c}>`),r=!0}return i}function Li(s){const t=Object.keys(s);for(let e=0;e<t.length;e++){const n=t[e];if(s.hasOwnProperty(n)&&n!==":@")return n}}function In(s,t){let e="";if(s&&!t.ignoreAttributes)for(let n in s){if(!s.hasOwnProperty(n))continue;let i=t.attributeValueProcessor(n,s[n]);i=Un(i,t),i===!0&&t.suppressBooleanAttributes?e+=` ${n.substr(t.attributeNamePrefix.length)}`:e+=` ${n.substr(t.attributeNamePrefix.length)}="${i}"`}return e}function zi(s,t){s=s.substr(0,s.length-t.textNodeName.length-1);let e=s.substr(s.lastIndexOf(".")+1);for(let n in t.stopNodes)if(t.stopNodes[n]===s||t.stopNodes[n]==="*."+e)return!0;return!1}function Un(s,t){if(s&&s.length>0&&t.processEntities)for(let e=0;e<t.entities.length;e++){const n=t.entities[e];s=s.replace(n.regex,n.val)}return s}const Ui={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(s,t){return t},attributeValueProcessor:function(s,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 ot(s){this.options=Object.assign({},Ui,s),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Kn(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Gi),this.processTextOrObjNode=ji,this.options.format?(this.indentate=Fi,this.tagEndChar=`>
|
|
6
6
|
`,this.newLine=`
|
|
7
|
-
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}ot.prototype.build=function(s){return this.options.preserveOrder?Ki(s,this.options):(Array.isArray(s)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(s={[this.options.arrayNodeName]:s}),this.j2x(s,0,[]).val)};ot.prototype.j2x=function(s,t,e){let n="",i="";const r=e.join(".");for(let o in s)if(Object.prototype.hasOwnProperty.call(s,o))if(typeof s[o]>"u")this.isAttribute(o)&&(i+="");else if(s[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(s[o]instanceof Date)i+=this.buildTextValNode(s[o],o,"",t);else if(typeof s[o]!="object"){const a=this.isAttribute(o);if(a&&!this.ignoreAttributesFn(a,r))n+=this.buildAttrPairStr(a,""+s[o]);else if(!a)if(o===this.options.textNodeName){let c=this.options.tagValueProcessor(o,""+s[o]);i+=this.replaceEntitiesValue(c)}else i+=this.buildTextValNode(s[o],o,"",t)}else if(Array.isArray(s[o])){const a=s[o].length;let c="",l="";for(let u=0;u<a;u++){const h=s[o][u];if(!(typeof h>"u"))if(h===null)o[0]==="?"?i+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(typeof h=="object")if(this.options.oneListGroup){const d=this.j2x(h,t+1,e.concat(o));c+=d.val,this.options.attributesGroupName&&h.hasOwnProperty(this.options.attributesGroupName)&&(l+=d.attrStr)}else c+=this.processTextOrObjNode(h,o,t,e);else if(this.options.oneListGroup){let d=this.options.tagValueProcessor(o,h);d=this.replaceEntitiesValue(d),c+=d}else c+=this.buildTextValNode(h,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(s[o]),c=a.length;for(let l=0;l<c;l++)n+=this.buildAttrPairStr(a[l],""+s[o][a[l]])}else i+=this.processTextOrObjNode(s[o],o,t,e);return{attrStr:n,val:i}};ot.prototype.buildAttrPairStr=function(s,t){return t=this.options.attributeValueProcessor(s,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+s:" "+s+'="'+t+'"'};function ji(s,t,e,n){const i=this.j2x(s,e+1,n.concat(t));return s[this.options.textNodeName]!==void 0&&Object.keys(s).length===1?this.buildTextValNode(s[this.options.textNodeName],t,i.attrStr,e):this.buildObjectNode(i.val,t,i.attrStr,e)}ot.prototype.buildObjectNode=function(s,t,e,n){if(s==="")return t[0]==="?"?this.indentate(n)+"<"+t+e+"?"+this.tagEndChar:this.indentate(n)+"<"+t+e+this.closeTag(t)+this.tagEndChar;{let i="</"+t+this.tagEndChar,r="";return t[0]==="?"&&(r="?",i=""),(e||e==="")&&s.indexOf("<")===-1?this.indentate(n)+"<"+t+e+r+">"+s+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&r.length===0?this.indentate(n)+`<!--${s}-->`+this.newLine:this.indentate(n)+"<"+t+e+r+this.tagEndChar+s+this.indentate(n)+i}};ot.prototype.closeTag=function(s){let t="";return this.options.unpairedTags.indexOf(s)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${s}`,t};ot.prototype.buildTextValNode=function(s,t,e,n){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${s}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(n)+`<!--${s}-->`+this.newLine;if(t[0]==="?")return this.indentate(n)+"<"+t+e+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(t,s);return i=this.replaceEntitiesValue(i),i===""?this.indentate(n)+"<"+t+e+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+e+">"+i+"</"+t+this.tagEndChar}};ot.prototype.replaceEntitiesValue=function(s){if(s&&s.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const e=this.options.entities[t];s=s.replace(e.regex,e.val)}return s};function Gi(s){return this.options.indentBy.repeat(s)}function Fi(s){return s.startsWith(this.options.attributeNamePrefix)&&s!==this.options.textNodeName?s.substr(this.attrPrefixLen):!1}class at{type;attrs={};styles={};deleteMarker=!1;constructor(t){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,Fn(this.attrs),sr(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,n]of Object.entries(t))this.attrs[e]=n;return this}css(t){return this.styles={...this.styles,...t},this}svg(){return this.toString()}}class qe extends at{attrs={};constructor(t){super("image"),this.attrs={...this.attrs,href:t}}load(t){return this.attrs.href=t,this}}class _e extends at{attrs={};constructor(t){super("use"),this.attrs={...this.attrs,href:this.make(t)}}use(t){return this.attrs.href=`#${t}`,this}make(t){return t==null?t:`#${t}`}}class Qe extends at{attrs={};constructor(){super("rect")}fill(t){return this.attrs.fill=t,this}stroke(t){return this.attrs.stroke=t,this}}class wt extends at{attrs;_text="";constructor(t=""){super("text"),this._text=t,this.attrs={}}plain(t){return this._text=t,this}font(t){return this.attrs.fontFamily=t.family,this.attrs.fontSize=t.size,this}center(){return this._text}}let tn=class extends at{raw;constructor(t){super("symbol"),this.raw=t}id(){return this.attr("id")}center(){return this.raw}};class N extends at{children=[];rotateMatrix;translateMatrix;constructor(){super("g")}add(t){return this.children.push(t),this}rotate(t,e,n){return this.rotateMatrix=Zs(t,e,n),this}translate(t,e){return this.translateMatrix=Ce(t,e),this}center(){return this.children.map(t=>t.toString()).join("")}left(...t){const e=[this.translateMatrix,this.rotateMatrix].filter(n=>n!=null);return e.length==0?super.left():super.left(nr(zs(e)))}each(t,e){for(let n=0;n<this.children.length;n++){const i=this.children[n];i instanceof N&&e&&i.each(t,!0),t(n,this.children)}}}const Zi=['xmlns="http://www.w3.org/2000/svg"','version="1.1"','xmlns:xlink="http://www.w3.org/1999/xlink"'];class jn extends at{children=[];constructor(){super("svg")}viewBox;add(t){return this.children.push(t),this}center(){return this.children.map(t=>t.toString()).join("")}left(...t){return`<${[this.type,...Zi,Fn(this.attrs),er(this.viewBox)].filter(e=>e!="").join(" ")}>`}viewbox(t,e,n,i){return this.viewBox={x:t,y:e,width:n,height:i},this}importSymbol(t){for(const e of ir(t))this.add(e);return this}x(t){throw new Error("unimplemented")}y(t){throw new Error("unimplemented")}dx(t){throw new Error("unimplemented")}dy(t){throw new Error("unimplemented")}each(t,e){for(let n=0;n<this.children.length;n++){const i=this.children[n];i instanceof N&&e&&i.each(t,!0),t(n,this.children)}}}function Gn(){return new jn}const Yi=Gn,Vi=N,Ji=qe,Xi=_e,qi=Qe,Qi=wt;function tr(s){return s.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function er(s){return s==null?"":`viewBox="${s.x} ${s.y} ${s.width} ${s.height}"`}function nr(s){return s==null?"":`transform="${Ys(s)}"`}function Fn(s){return Object.entries(s).filter(([t,e])=>e!==void 0).map(([t,e])=>`${tr(t)}="${e}"`).join(" ")}function sr(s){const t=Object.entries(s).map(([e,n])=>`${e}: ${n};`).join(" ");return t!=""?`style="${t}"`:""}function*ir(s){const t=new Di({ignoreAttributes:!1}),e=new ot({ignoreAttributes:!1}),n=t.parse(s);for(const i of n.svg.symbol){const r=e.build(i),o=new tn(r);for(const[a,c]of Object.entries(i))a.startsWith("@_")&&(o.attrs[a.substring(2)]=c);yield o}}const G=(s,t)=>{const e=W(s.tiles[0],t),n=e.baseHeight,i=e.baseWidth;if(s.is(w.SHO_KAN))return{width:i*2+n,height:Math.max(i*2,n)};const r=s.tiles.reduce((a,c)=>{const l=W(c,t).height;return l>a?l:a},0);return{width:s.tiles.reduce((a,c)=>a+W(c,t).width,0),height:r}},W=(s,t)=>{const e=parseFloat((st.HEIGHT*t).toPrecision(5)),n=parseFloat((st.WIDTH*t).toPrecision(5)),i=s.has(m.HORIZONTAL)?{width:e,height:n,baseWidth:n,baseHeight:e}:{width:n,height:e,w:n,baseWidth:n,baseHeight:e};return(s.has(m.TSUMO)||s.has(m.DORA))&&(i.width+=n*st.TEXT_SCALE),i};class Mt{tileWidth;tileHeight;imageHostUrl;imageExt;scale;svgSprite;constructor(t={}){this.scale=t.scale??1,this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=st.WIDTH*this.scale,this.tileHeight=st.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getHorizontalTileYOffset(t){const e=W(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new qe().load(this.buildURL(t));return this.svgSprite&&(e=new _e().use(Mt.buildID(t))),t instanceof y&&t.has(m.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,n){const i=W(t,this.scale);return this.image(t).dx(e).dy(n).size(i.baseWidth,i.baseHeight)}createTextImage(t,e,n,i){const r=this.createImage(t,e,n),o=W(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,l=o.baseHeight,u=new wt().plain(i);u.size(o.baseWidth,o.baseHeight).font({family:Fe,size:a}).dx(c).dy(l);const h=new N;return h.add(r).add(u).translate(e,n),h}createRotate90Image(t,e,n,i=!1){const r=this.createImage(t,0,0),o=W(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,l=e+this.getHorizontalTileYOffset(t),u=i?n-this.getHorizontalTileYOffset(t):n,h=new N;return h.add(r).translate(l,u).rotate(90,a,c),h}createStick(t){return this.image(t)}static buildID(t){if(t==100||t==1e3)return t==100?"stick100":"stick1000";const e=t.t==f.BACK||t.has(m.RED)?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${Mt.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:e}}class en extends Mt{blockMargin=st.WIDTH*st.BLOCK_MARGIN_SCALE*this.scale;createBlockHandDiscard(t){const e=t instanceof R?t.tilesWithBack:t.tiles,n=new N;let i=0;for(const r of e){const o=W(r,this.scale),a=r.has(m.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),c=r.has(m.HORIZONTAL)?this.getHorizontalTileYOffset(r):0,l=a(r,i,c);n.add(l),i+=o.width}return n}createBlockPonChiKan(t){const e=t.tiles.findIndex(r=>r.has(m.HORIZONTAL));let n=0;const i=new N;if(t.type==w.SHO_KAN){let r=e;for(let o=0;o<t.tiles.length;o++)t.tiles[o].has(m.HORIZONTAL)&&(r=o);for(let o=0;o<t.tiles.length;o++){const a=W(t.tiles[o],this.scale);if(o==r)continue;if(o==e){const u=t.tiles[e],h=t.tiles[r],d=W(u,this.scale),g=this.createRotate90Image(u,0,0,!0),p=this.createRotate90Image(h,0,d.height,!0);i.add(new N().translate(n,0).add(g).add(p)),n+=d.width;continue}const c=a.width*2-a.height,l=this.createImage(t.tiles[o],n,c);n+=a.width,i.add(l)}return i}if(t.type==w.CHI){const r=t.tiles[e],o=this.createRotate90Image(r,n,this.getHorizontalTileYOffset(r));n+=W(r,this.scale).width,i.add(o);for(let a=0;a<t.tiles.length;a++){if(a==e)continue;const c=t.tiles[a],l=W(c,this.scale),u=this.createImage(c,n,0);n+=l.width,i.add(u)}return i}for(let r=0;r<t.tiles.length;r++){const o=r==e?this.createRotate90Image.bind(this):this.createImage.bind(this),a=t.tiles[r],c=r==e?this.getHorizontalTileYOffset(a):0,l=W(a,this.scale),u=o(a,n,c);n+=l.width,i.add(u)}return i}}const rr=(s,t)=>{const e=s.scale;return{[w.CHI]:function(i){const r=G(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[w.PON]:function(i){const r=G(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[w.DAI_KAN]:function(i){const r=G(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[w.SHO_KAN]:function(i){const r=G(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[w.AN_KAN]:function(i){b(i instanceof R,`block type is not ankan: ${i.type}`);const r=G(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[w.IMAGE_DORA]:function(i){i=t?.doraText==!1?new Rt([i.tiles[0].clone({remove:m.DORA})]):i;const r=G(i,e),o=new N,a=t?.doraText===!1?s.createImage(i.tiles[0],0,0):s.createTextImage(i.tiles[0],0,0,"(ドラ)");return o.add(a),{...r,e:o}},[w.TSUMO]:function(i){i=t?.tsumoText==!1?new Rt([i.tiles[0].clone({remove:m.TSUMO})]):i;const r=G(i,e),o=new N,a=t?.tsumoText===!1?s.createImage(i.tiles[0],0,0):s.createTextImage(i.tiles[0],0,0,"(ツモ)");return o.add(a),{...r,e:o}},[w.HAND]:function(i){const r=G(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[w.IMAGE_DISCARD]:function(i){const r=G(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[w.THREE]:function(i){throw new Error("three is unsupported")},[w.RUN]:function(i){throw new Error("run is unsupported")},[w.PAIR]:function(i){throw new Error("pair is unsupported")},[w.ISOLATED]:function(i){throw new Error("isolated is unsupported")},[w.UNKNOWN]:function(i){if(i.tiles.some(a=>a.has(m.TSUMO)||a.has(m.DORA)))throw new Error("found an unknown block with operator tiles");const r=G(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}}}},Ot=(s,t,e)=>{const n=rr(s,e);let i=0,r=0;const o=[];for(const h of t){const d=n[h.type],g=d(h);r+=g.width,i=g.height>i?g.height:i,o.push(g)}const a=i,c=r+(t.length-1)*s.blockMargin,l=new N;let u=0;for(const h of o){const d=a-h.height,g=new N().translate(u,d);g.add(h.e),l.add(g),u+=h.width+s.blockMargin}return{e:l,width:c,height:a}},or=(s,t,e={},n={responsive:!1,doraText:!0,tsumoText:!0})=>{const i=new en(e),r=Ot(i,t,n);n.responsive||s.size(r.width,r.height),s.viewbox(0,0,r.width,r.height),s.add(r.e)},Zn=()=>{const s=[0,1,2,3,4,5,6,7,8,9],t=[];for(const e of Object.values(f)){if(e==f.BACK){t.push(Mt.buildID(new y(e,0)));continue}t.push(...s.map(n=>Mt.buildID(new y(e,n))).flat())}return t},ar=s=>{const t=Zn(),e=[];return s.each((n,i)=>{const r=i[n];if(r instanceof _e){const a=r.attr("href").substring(1);t.includes(a)&&e.push(a)}},!0),e},cr=s=>{const t=Zn(),e=ar(s);s.each((n,i)=>{const r=i[n];r instanceof tn&&(t.includes(r.id())&&e.includes(r.id())||r.remove())},!0)},lr=s=>{const e=[];for(let n=0;n<s.length;n+=6){const i=s.slice(n,n+6);e.push(i)}return e},j=(s,t,e,n,i=0,r=0)=>{const o=new N().add(s);if(n==90){const a=i,c=r-e;return o.rotate(n,0,e).translate(a,c),new N().add(o)}if(n==180){const a=i+t,c=r-e;return o.rotate(n,0,e).translate(a,c),new N().add(o)}if(n==270){const a=i+e,c=r+(t-e);return o.rotate(n,0,e).translate(a,c),new N().add(o)}return new N().add(o)},se=(s,t)=>{const e=new N,n=lr(s);for(let i=0;i<n.length;i++){let r=n[i],o=i*t.tileHeight;const a=t.createBlockHandDiscard(new Je(r,w.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*n.length}},hr=(s,t,e)=>{const n=t.font,i=t.textWidth,r=t.textHeight,o=e.sticks.dead,a=e.sticks.reach,c=Oe.WIDTH*s.scale,l=Oe.HEIGHT*s.scale;let u=i*3,h=r;const d=(c+s.tileWidth+i-u)/2,g=new wt().plain(e.round).font(n).x(d).y(0);h+=25*s.scale;const p=s.tileHeight,E=new N().size(c,p).translate(0,h),A={family:n.family,size:n.size*.7},T=s.createStick(1e3).size(c,l).x(0).y(0),v=new wt().plain(a.toString()).font(A).dx(c).dy(l),M=s.createStick(100).size(c,l).x(0).y(l+l),Tt=new wt().plain(o.toString()).font(A).dx(c).dy(l*3);E.add(T),E.add(v),E.add(M),E.add(Tt);const Nt=s.createImage(e.doras[0],0,0).x(c+i).y(0);E.add(Nt);const It=new N;return It.add(g),It.add(g),It.add(E),{e:It,width:c+s.tileWidth+i,height:h+s.tileHeight}},ur=(s,t,e=0)=>{const n=Ot(s,t.front),i=Ot(s,t.right),r=Ot(s,t.opposite),o=Ot(s,t.left),a=[n.width,i.width,r.width,o.width].reduce((E,A)=>Math.max(E,A)),c=Math.max(e+s.tileHeight*2+s.blockMargin*2,a+s.tileWidth*2+s.blockMargin),l=c,u=j(n.e,n.width,n.height,0).translate((c-n.width)/2,l-n.height),h=j(i.e,i.width,i.height,270).translate(c-i.height,(c-i.width)/2),d=j(r.e,r.width,r.height,180).translate((c-r.width)/2,0),g=j(o.e,o.width,o.height,90).translate(0,(c-o.width)/2),p=new N().size(c,l);return p.add(u),p.add(h),p.add(d),p.add(g),{e:new N().add(p),width:c,height:l}},dr=s=>{const t=Object.values(ye),e=t.indexOf(s);return[...t.slice(e),...t.slice(0,e)]},fr=(s,t,e)=>{const n=s.tileWidth*5+s.tileHeight*1,i=t.font,r=t.textWidth,o=t.textHeight,a=t.numWidth,c=hr(s,t,e);c.e.translate(n/2-c.width/2,n/2-c.height/2);const l=(Cs,gn,Rs)=>{const Ms=`${Cs} ${gn}`,xs=new wt().plain(Ms).font(i).attr(Rs);return{e:new N().add(xs),width:r+a*gn.toString().length,height:o}},[u,h,d,g]=dr(e.frontPlace),p=e.scores,A=l(u,p.front,{x:n/2,y:n,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let T=l(h,p.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const v=j(T.e,T.width,T.height,270).translate(n,n/2-T.width);let M=l(d,p.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const Tt=j(M.e,M.width,M.height,180).translate(n/2-M.width,-M.height);let Nt=l(g,p.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const It=j(Nt.e,Nt.width,Nt.height,90).translate(-Nt.height,n/2),ct=new N,ks=new Qe().size(n,n).x(0).y(0).fill("none").stroke("#000000");return ct.add(ks),ct.add(c.e),ct.add(A),ct.add(v),ct.add(Tt),ct.add(It),{e:ct,width:n,height:n}},pr=(s,t)=>{const e=se(t.front,s),n=se(t.right,s),i=se(t.opposite,s),r=se(t.left,s),o=[e.height,n.height,i.height,r.height].reduce((v,M)=>Math.max(v,M)),a=s.tileWidth*5+s.tileHeight*1,c=o,l=a+o*2+s.blockMargin,u=l,h=new N().size(l,u),d=l/2-a/2,g=u/2-a/2,p=j(e.e,a,c,0).translate(d,u-c),E=j(n.e,a,c,270).translate(l-c,g),A=j(i.e,a,c,180).translate(d,0),T=j(r.e,a,c,90).translate(0,g);return h.add(p),h.add(E),h.add(A),h.add(T),{e:new N().add(h),width:l,height:u}},Yn=(s,t,e,n,i)=>{const r=new N,o=pr(s,n),a=ur(s,e,o.height),c=fr(s,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}},gr=(s,t,e={},n,i={responsive:!1})=>{const r=new en(e),o=n,{discards:a,hands:c,scoreBoard:l}=Xn(t),u=Yn(r,o,c,a,l);i.responsive||s.size(u.width,u.height),s.viewbox(0,0,u.width,u.height),s.add(u.e)};var Ne;function Vn(s){return{lang:s?.lang??Ne?.lang,message:s?.message,abortEarly:s?.abortEarly??Ne?.abortEarly,abortPipeEarly:s?.abortPipeEarly??Ne?.abortPipeEarly}}var mr;function yr(s){return mr?.get(s)}var wr;function Er(s){return wr?.get(s)}var _r;function Ar(s,t){return _r?.get(s)?.get(t)}function xt(s){const t=typeof s;return t==="string"?`"${s}"`:t==="number"||t==="bigint"||t==="boolean"?`${s}`:t==="object"||t==="function"?(s&&Object.getPrototypeOf(s)?.constructor?.name)??"null":t}function it(s,t,e,n,i){const r=i&&"input"in i?i.input:e.value,o=i?.expected??s.expects??null,a=i?.received??xt(r),c={kind:s.kind,type:s.type,input:r,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:s.requirement,path:i?.path,issues:i?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},l=s.kind==="schema",u=i?.message??s.message??Ar(s.reference,c.lang)??(l?Er(c.lang):null)??n.message??yr(c.lang);u!==void 0&&(c.message=typeof u=="function"?u(c):u),l&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function Lt(s){return{version:1,vendor:"valibot",validate(t){return s["~run"]({value:t},Vn())}}}function br(s,t){const e=[...new Set(s)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function xe(s,t){return{kind:"validation",type:"max_value",reference:xe,async:!1,expects:`<=${s instanceof Date?s.toJSON():xt(s)}`,requirement:s,message:t,"~run"(e,n){return e.typed&&!(e.value<=this.requirement)&&it(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():xt(e.value)}),e}}}function $e(s,t){return{kind:"validation",type:"min_value",reference:$e,async:!1,expects:`>=${s instanceof Date?s.toJSON():xt(s)}`,requirement:s,message:t,"~run"(e,n){return e.typed&&!(e.value>=this.requirement)&&it(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():xt(e.value)}),e}}}function Tr(s,t,e){return typeof s.fallback=="function"?s.fallback(t,e):s.fallback}function Jn(s,t,e){return typeof s.default=="function"?s.default(t,e):s.default}function he(s){return{kind:"schema",type:"number",reference:he,expects:"number",async:!1,message:s,get"~standard"(){return Lt(this)},"~run"(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:it(this,"type",t,e),t}}}function L(s,t){return{kind:"schema",type:"optional",reference:L,expects:`(${s.expects} | undefined)`,async:!1,wrapped:s,default:t,get"~standard"(){return Lt(this)},"~run"(e,n){return e.value===void 0&&(this.default!==void 0&&(e.value=Jn(this,e,n)),e.value===void 0)?(e.typed=!0,e):this.wrapped["~run"](e,n)}}}function Pe(s,t){return{kind:"schema",type:"picklist",reference:Pe,expects:br(s.map(xt),"|"),async:!1,options:s,message:t,get"~standard"(){return Lt(this)},"~run"(e,n){return this.options.includes(e.value)?e.typed=!0:it(this,"type",e,n),e}}}function $t(s,t){return{kind:"schema",type:"strict_object",reference:$t,expects:"Object",async:!1,entries:s,message:t,get"~standard"(){return Lt(this)},"~run"(e,n){const i=e.value;if(i&&typeof i=="object"){e.typed=!0,e.value={};for(const r in this.entries){const o=this.entries[r];if(r in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=r in i?i[r]:Jn(o),c=o["~run"]({value:a},n);if(c.issues){const l={type:"object",origin:"value",input:i,key:r,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],e.issues?.push(u);if(e.issues||(e.issues=c.issues),n.abortEarly){e.typed=!1;break}}c.typed||(e.typed=!1),e.value[r]=c.value}else if(o.fallback!==void 0)e.value[r]=Tr(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(it(this,"key",e,n,{input:void 0,expected:`"${r}"`,path:[{type:"object",origin:"key",input:i,key:r,value:i[r]}]}),n.abortEarly))break}if(!e.issues||!n.abortEarly){for(const r in i)if(!(r in this.entries)){it(this,"key",e,n,{input:r,expected:"never",path:[{type:"object",origin:"key",input:i,key:r,value:i[r]}]});break}}}else it(this,"type",e,n);return e}}}function ue(s){return{kind:"schema",type:"string",reference:ue,expects:"string",async:!1,message:s,get"~standard"(){return Lt(this)},"~run"(t,e){return typeof t.value=="string"?t.typed=!0:it(this,"type",t,e),t}}}function Nn(...s){return{...s[0],pipe:s,get"~standard"(){return Lt(this)},"~run"(t,e){for(const n of s)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!e.abortEarly&&!e.abortPipeEarly)&&(t=n["~run"](t,e))}return t}}}function Nr(s,t,e){const n=s["~run"]({value:t},Vn(e));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}const ie=L($t({discard:L(ue(),""),hand:L(ue(),""),score:L(he(),25e3)}),{discard:"",hand:"",score:25e3}),Ir=$t({[_.E]:ie,[_.S]:ie,[_.W]:ie,[_.N]:ie}),ht={round:O.E1,sticks:{reach:0,dead:0},doras:_.S,front:_.E},vr=L($t({round:L(Pe(Object.keys(Ze)),ht.round),sticks:L($t({reach:L(Nn(he(),$e(0,""),xe(9,"")),ht.sticks.reach),dead:L(Nn(he(),$e(0,""),xe(9,"")),ht.sticks.dead)}),ht.sticks),doras:L(ue(),ht.doras),front:L(Pe(Object.keys(ye)),ht.front)}),ht),Sr=$t({...Ir.entries,board:vr}),Xn=s=>{const t=qn(s);return Qn(t)},qn=s=>{const t=Or(s),e=Nr(Sr,t);if(!e.success)throw e.issues;return e.output},Or=s=>{const t="table",e="board",n=s.split(`
|
|
8
|
-
`).map(a=>a.trim()).filter(a=>a!="");if(n.length==0)throw new Error("empty input");const i=n.shift();if(!i.startsWith(t))throw new Error(`input does not start with table: ${i}`);const r={};let o=[_.E,_.S,_.W,_.N,e];for(;;){const a=n.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,u]=Cr([...n]);r.board=l;for(let h=0;h<u;h++)n.shift()}else{const[l,u]=kr([...n]);r[c]=l;for(let h=0;h<u;h++)n.shift()}}return r},Z=(s,t)=>s.replace(t,"").replace(":","").trim(),kr=s=>{const t="hand",e="discard",n="score",i={};let r=0;for(;r<s.length;r++){const o=s[r];if(o.startsWith(t))i.hand=Z(o,t);else if(o.startsWith(e))i.discard=Z(o,e);else if(o.startsWith(n))i.score=Number(Z(o,n));else break}return[i,r]},Cr=s=>{const t="doras",e="round",n="front",i="sticks",r="reach",o="dead",a={};let c=0;for(;c<s.length;c++){const l=s[c];if(l.startsWith(t))a.doras=Z(l,t);else if(l.startsWith(e))a.round=Z(l,e);else if(l.startsWith(n))a.front=Z(l,n);else if(l.startsWith(i)){a.sticks={};const u=s[c+1]??"",h=s[c+2]??"";u.startsWith(r)&&(a.sticks.reach=Number(Z(u,r))),u.startsWith(o)&&(a.sticks.dead=Number(Z(u,o))),h.startsWith(r)&&(a.sticks.reach=Number(Z(h,r))),h.startsWith(o)&&(a.sticks.dead=Number(Z(h,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},Qn=s=>{const t=s.board.front,e=Rr(t),n=a=>s[a].discard.replace(/\r?\n/g,""),i={front:new D(n(e.front)).tiles(),right:new D(n(e.right)).tiles(),opposite:new D(n(e.opposite)).tiles(),left:new D(n(e.left)).tiles()},r={front:new D(s[e.front].hand).parse(),right:new D(s[e.right].hand).parse(),opposite:new D(s[e.opposite].hand).parse(),left:new D(s[e.left].hand).parse()},o={round:Ze[s.board.round],frontPlace:ye[t],sticks:s.board.sticks,doras:new D(s.board.doras).tiles(),scores:{front:s[e.front].score,right:s[e.right].score,opposite:s[e.opposite].score,left:s[e.left].score}};return{discards:i,hands:r,scoreBoard:o}},Rr=s=>({front:s,right:yt(s),opposite:yt(yt(s)),left:we(s)});function*z(s){const t=s?.filterBy&&s.filterBy.length>0?s?.filterBy:Object.values(f);for(const e of t){if(s?.skipBack&&e==f.BACK)continue;const n=e==f.Z?7:e==f.BACK?1:9;for(let i=1;i<=n;i++)yield[e,i]}}class Ae{data;constructor(t,e=!1){this.data={[f.M]:[0,0,0,0,0,0,0,0,0,0],[f.P]:[0,0,0,0,0,0,0,0,0,0],[f.S]:[0,0,0,0,0,0,0,0,0,0],[f.Z]:[0,0,0,0,0,0,0,0],[f.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const n=Array.isArray(t)?t:new D(t).parse();for(const i of n){if(i.isCalled()){this.data.called=[...this.called,i];continue}else if(i.is(w.TSUMO)){const r=i.tiles[0];this.inc([r]),this.data.tsumo=r;continue}else if(i.is(w.HAND)){this.inc(i.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(r=>r===f.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,n]of z()){let i=this.get(e,n);e!=f.Z&&n==5&&this.get(e,0)>0&&(i-=this.get(e,0),t.push(new y(e,n,[m.RED])));for(let r=0;r<i;r++)t.push(new y(e,n))}if(this.drawn!=null){const e=this.drawn,n=t.findIndex(i=>i.equals(e)&&e.has(m.RED)==i.has(m.RED));b(n>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[n]=t[n].clone({add:m.TSUMO})}return t}toString(){const t=this.called.length>0?`${Q}${this.called.join(Q)}`:"",e=this.drawn?`${Q}${this.drawn.toString()}`:"",n=this.hands.filter(r=>!r.has(m.TSUMO));return`${new Rt(n).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 R))}sum(t){let e=0;for(const[n,i]of z({filterBy:[t]}))e+=this.get(n,i);return e}get(t,e){return t==f.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const n of t){const i=n.t!=f.BACK&&this.get(n.t,n.n)>=4,r=n.has(m.RED)&&this.get(n.t,0)>0;if(i||r){this.dec(e);const o=i?`tile ${n} exists more than 4 times`:`red tile ${n} appears more than 1 times`;throw new Error(`invalid hand: ${o} in ${this.toString()}`)}e.push(n),n.t==f.BACK?this.data[n.t][1]+=1:(this.data[n.t][n.n]+=1,n.has(m.RED)&&(this.data[n.t][0]+=1))}return e}dec(t){const e=[];for(const n of t){const i=this.get(n.t,n.n)<1,r=n.has(m.RED)&&this.get(n.t,0)<=0;if(i||r){this.inc(e);const o=i?`tile ${n} is not in`:`red tile ${n} is not in`;throw new Error(`invalid hand: ${o} in ${this.toString()}`)}if(e.push(n),n.t==f.BACK?this.data[n.t][1]-=1:(this.data[n.t][n.n]-=1,n.has(m.RED)&&(this.data[n.t][0]-=1)),k(n)&&this.get(n.t,5)==0&&this.get(n.t,0)>0){this.data[n.t][0]=0;const o=e.pop().clone({add:m.RED});e.push(o)}}return e}draw(t){const e=t.clone({add:m.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(n=>!n.has(m.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 R){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof K){const e=this.data.called.findIndex(i=>i.is(w.PON)&&i.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let n=t.tiles[0];n=k(n)?n.clone({remove:m.RED}):n,this.dec([n]),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 Ae(this.toString());return t.data.reached=this.data.reached,t}}class te{hand;constructor(t){this.hand=t}calc(){return Math.min(this.sevenPairs(),this.thirteenOrphans(),this.standardType())}sevenPairs(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const[n,i]of z({skipBack:!0}))this.hand.get(n,i)==2&&t++,this.hand.get(n,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 n of Object.values(f)){if(n==f.BACK)continue;const i=n==f.Z?Pt:Y;for(const r of i)this.hand.get(n,r)>=1&&t++,this.hand.get(n,r)>=2&&e++}return e>=1?12-t:13-t}standardType(){const t=n=>{const i=[0,0,0];for(const[d,g]of z({filterBy:[f.Z]}))this.hand.get(d,g)>=3?i[0]++:this.hand.get(d,g)==2?i[1]++:this.hand.get(d,g)==1&&i[2]++;const r=[0,0,0],o=this.hand.get(f.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.calcNumberTilePatterns(f.M),u=this.calcNumberTilePatterns(f.P),h=this.calcNumberTilePatterns(f.S);for(const d of[l.patternA,l.patternB])for(const g of[u.patternA,u.patternB])for(const p of[h.patternA,h.patternB]){const E=[this.hand.called.length,0,0];for(let T=0;T<3;T++)E[T]+=d[T]+g[T]+p[T]+i[T]+r[T];const A=this.calcStandardType(E[0],E[1],E[2],n);A<c&&(c=A)}return c};let e=t(!1);for(const[n,i]of z())if(this.hand.get(n,i)>=2){const r=this.hand.dec(new Array(2).fill(new y(n,i))),o=t(!0);this.hand.inc(r),o<e&&(e=o)}return e}calcNumberTilePatterns(t,e=1){if(e>9)return this.groupRemainingTiles(t);let n=this.calcNumberTilePatterns(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 y(t,e),new y(t,e+1),new y(t,e+2)]),r=this.calcNumberTilePatterns(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<n.patternA[2]||r.patternA[2]==n.patternA[2]&&r.patternA[1]<n.patternA[1])&&(n.patternA=r.patternA),(r.patternB[0]>n.patternB[0]||r.patternB[0]==n.patternB[0]&&r.patternB[1]>n.patternB[1])&&(n.patternB=r.patternB)}if(this.hand.get(t,e)>=3){const i=this.hand.dec(new Array(3).fill(new y(t,e))),r=this.calcNumberTilePatterns(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<n.patternA[2]||r.patternA[2]==n.patternA[2]&&r.patternA[1]<n.patternA[1])&&(n.patternA=r.patternA),(r.patternB[0]>n.patternB[0]||r.patternB[0]==n.patternB[0]&&r.patternB[1]>n.patternB[1])&&(n.patternB=r.patternB)}return n}groupRemainingTiles(t){let e=0,n=0,i=0;for(const[r,o]of z({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,n+=i%2,i=0);return e+=i>>1,n+=i%2,{patternA:[0,e,n],patternB:[0,e,n]}}calcStandardType(t,e,n,i){let r=i?4:5;return t>4&&(e+=t-4,t=4),t+e>4&&(n+=t+e-4,e=4-t),t+e+n>r&&(n=r-t-e),i&&e++,13-t*3-e*2-n}}class ts{hand;constructor(t){this.hand=t}calc(t){return this.markedHands([...this.sevenPairs(),...this.thirteenOrphans(),...this.nineGates(),...this.standardType()],t)}markedHands(t,e){if(t.length==0)return[];const n=[];for(let i=0;i<t.length;i++)n.push(...this.markedHand(t[i],e));return n}markedHand(t,e){if(t.length==0)return[];const n=this.hand.drawn!=null||e.has(m.TSUMO)?m.TSUMO:m.RON,i=[],r={};for(let a=0;a<t.length;a++){const c=t[a];if(c.isCalled())continue;const l=c.tiles.findIndex(h=>h.equals(e)&&e.has(m.RED)==h.has(m.RED));if(l<0)continue;const u=Ft(c);r[u]||(r[u]=!0,i.push([a,l]))}if(i.length==0)throw new Error(`found no tile ${e.toString()} in hand: ${t.toString()}`);const o=[];for(const[a,c]of i){const l=[...t],u=l[a],h=u.tiles[c].clone({add:n});l[a]=u.clone({replace:{idx:c,tile:h}}),o.push(l)}return o}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,n]of z({skipBack:!0})){const i=this.hand.get(e,n);if(i==2){const r=this.hand.dec(new Array(2).fill(new y(e,n)));t.push(new B(r[0],r[1])),this.hand.inc(r)}else{if(i==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const n of Object.values(f)){if(n==f.BACK)continue;const i=n==f.Z?Pt:Y;for(let r of i)if(this.hand.get(n,r)==1)t.push(new Ve(new y(n,r)));else if(this.hand.get(n,r)==2&&e==!1)t.unshift(new B(new y(n,r),new y(n,r))),e=!0;else return[]}return[t]}nineGates(){const t=(e,n,i)=>i.includes(this.hand.get(e,n));for(const e of Object.values(f)){if(e==f.BACK||e==f.Z)continue;const n=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(n&&i)return[[new Rt(this.hand.hands)]]}return[]}standardType(){let t=[];for(const[e,n]of z())if(this.hand.get(e,n)>=2){const i=new Array(2).fill(new y(e,n));n==5&&this.hand.get(e,0)>0&&this.hand.get(e,n)>=3&&(i[1]=new y(e,n,[m.RED]));const r=this.hand.dec(i),o=this.calcAllBlockCombinations().filter(a=>a.length==4).map(a=>(a.unshift(new B(r[0],r[1])),a));t=[...t,...o],this.hand.inc(r)}return t}calcAllBlockCombinations(){return[this.addRedPatterns(f.M,this.handleNumType(f.M)),this.addRedPatterns(f.P,this.handleNumType(f.P)),this.addRedPatterns(f.S,this.handleNumType(f.S)),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((n,i)=>i.length-n.length).reduce((n,i)=>i.length===0?n:n.flatMap(r=>i.map(o=>[...r,...o])),[[]])}handleBack(){const t=f.BACK,e=this.hand.get(t,0);if(e<3)return[];const n=new y(t,0),i=Array(Math.floor(e/3)).fill(new U([n,n,n]));return i.length==0?[]:[i]}handleZ(){const t=[];for(const[e,n]of z({filterBy:[f.Z]})){if(this.hand.get(e,n)==0)continue;if(this.hand.get(e,n)!=3)return[];const i=new y(e,n);t.push(new U([i,i,i]))}return t.length==0?[]:[t]}addRedPattern(t,e){const n=new y(t,5),i=new y(t,5,[m.RED]),r=[];let o=null;const a={};for(let l=0;l<e.length;l++){const u=e[l],h=u.tiles.findIndex(p=>k(p)&&!p.has(m.RED)),d=u.tiles.findIndex(p=>k(p)&&p.has(m.RED));if(d>-1&&(o=[l,d]),d>-1&&h>-1||h<0)continue;const g=Ft(u);a[g]||(a[g]=!0,r.push([l,h]))}if(o==null)return[e];const c=[e];for(const[l,u]of r){const h=[...e],d=h[l];h[l]=d.clone({replace:{idx:u,tile:i}});const g=h[o[0]];h[o[0]]=g.clone({replace:{idx:o[1],tile:n}}),Ft(d)!=Ft(g)&&c.push(h)}return c}addRedPatterns(t,e){if(!(this.hand.get(t,0)>0&&this.hand.get(t,5)>=2))return e;const n=[];for(let i=0;i<e.length;i++){const r=e[i];n.push(...this.addRedPattern(t,r))}return n}handleNumType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.handleNumType(t,e+1);const n=[];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 y(t,e),new y(t,e+1),new y(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 tt([i[0],i[1],i[2]])),n.push(o)}if(this.hand.get(t,e)==3){const i=this.hand.dec(new Array(3).fill(new y(t,e)));let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new U([i[0],i[1],i[2]])),n.push(o)}return n}}const Pt=[1,2,3,4,5,6,7],Y=[1,9],Gt=s=>{const t=s.boardContext;return{...s,hand:s.hand.map(I.deserialize),boardContext:{...t,doraIndicators:t.doraIndicators.map(y.from),hiddenDoraIndicators:t.hiddenDoraIndicators?.map(y.from)}}},de=s=>JSON.parse(JSON.stringify(s)),C={MANGAN:2e3,HANEMAN:3e3,DOUBLE:4e3,TRIPLE:6e3,YAKUMAN:8e3,DOUBLE_YAKUMAN:16e3,DEAD_STICK:300,REACH_STICK:1e3},Mr=[{minHan:26,points:C.DOUBLE_YAKUMAN},{minHan:13,points:C.YAKUMAN},{minHan:11,points:C.TRIPLE},{minHan:8,points:C.DOUBLE},{minHan:6,points:C.HANEMAN},{minHan:5,points:C.MANGAN}],xr={[C.MANGAN]:"満貫",[C.HANEMAN]:"跳満",[C.DOUBLE]:"倍満",[C.TRIPLE]:"三倍満"},V={PARENT_RON:6,CHILD_RON:4,PARENT_TSUMO:2,CHILD_TUMO_FROM_PARENT:2,CHILD_TUMO_FROM_CHILD:1};function es(s){if(s.isYakuman)return"役満";if(s.isCountableYakuman)return"数え役満";const t=$r(s.base,s.isTsumo,s.isParent),e=xr[s.base];return e?`${s.fu}符${s.han}飜 ${e}${t}`:`${s.fu}符${s.han}飜 ${t}`}function $r(s,t,e){if(t)return e?`${et(s*V.PARENT_TSUMO)}`:`${et(s*V.CHILD_TUMO_FROM_CHILD)}-${et(s*V.CHILD_TUMO_FROM_PARENT)}`;{const n=e?V.PARENT_RON:V.CHILD_RON;return`${et(s*n)}`}}const et=(s,t=100)=>Math.ceil(s/t)*t;class He{hand;cfg;constructor(t,e){this.hand=t,this.cfg={doras:e.doraIndicators.map(n=>Be(n)),hiddenDoras:e.hiddenDoraIndicators==null?[]:e.hiddenDoraIndicators.map(n=>Be(n)),roundWind:y.from(e.round.substring(0,2)),myWind:y.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,enableRoundUpMangan:e.enableRoundUpMangan??!1,disableCountableYakuman:e.disableCountableYakuman??!1,disableDoubleYakuman:e.disableDoubleYakuman??!1,orig:e}}calc(...t){const e=this.getWinningHands(t);if(e.length===0)return!1;const n=this.selectBestHand(e),i=this.calculateScore(n),r=this.calculateDeltas(i.base,i.isTsumo,i.isParent,i.myWind,this.cfg.orig.ronWind),o=r[i.myWind]-this.cfg.sticks.dead*C.DEAD_STICK,a=es({base:i.base,fu:i.fu,han:i.han,isTsumo:i.isTsumo,isParent:i.isParent,isYakuman:i.isYakuman,isCountableYakuman:i.isCountableYakuman});return{...n,fu:i.fu,deltas:r,points:r[i.myWind],basePoints:o,boardContext:this.cfg.orig,description:a}}getWinningHands(t){const e=[];if(t.length==0)return e;for(const n of t){const i=[...this.dA13(n),...this.dB13(n),...this.dC13(n),...this.dD13(n),...this.dE13(n),...this.dF13(n),...this.dG13(n),...this.dH13(n),...this.dI13(n),...this.dJ13(n),...this.dK13(n)].map(r=>(this.cfg.disableDoubleYakuman&&r.han>13&&(r.han=13),r));i.length!=0&&e.push({yakus:i,han:i.reduce((r,o)=>r+o.han,0),fu:30,hand:n,isYakuman:!0})}if(e.length>0)return e;for(const n of t){const i=this.calcFu(n),r=[...this.dA1(n),...this.dB1(n),...this.dC1(n),...this.dD1(n),...this.dE1(n),...this.dF1(n),...this.dG1(n),...this.dH1(n),...this.dI1(n),...this.dJ1(n),...this.dK1(n),...this.dA2(n),...this.dB2(n),...this.dC2(n),...this.dD2(n),...this.dE2(n),...this.dF2(n),...this.dG2(n),...this.dH2(n),...this.dI2(n),...this.dJ2(n),...this.dA3(n),...this.dB3(n),...this.dC3(n),...this.dA6(n)];r.length!=0&&(r.push(...this.dX1(n)),e.push({yakus:r,han:r.reduce((o,a)=>o+a.han,0),fu:i,hand:n}))}return e}selectBestHand(t){let e=0,n=[0,0];for(let i=0;i<t.length;i++){const{han:r,fu:o}=t[i];(r>n[0]||r===n[0]&&o>n[1])&&(e=i,n=[r,o])}return t[e]}calculateScore(t){const{han:e}=t,n=t.fu!==25?et(t.fu,10):25,i=t.isYakuman??!1;let r=this.getBasePoints(e,n),o=!1;e>=13&&e<26&&!this.hasYakuman(t.yakus)&&(r=this.cfg.disableCountableYakuman?C.TRIPLE:C.YAKUMAN,o=!this.cfg.disableCountableYakuman),this.cfg.enableRoundUpMangan&&this.isRoundUpMangan(n,e)&&(r=C.MANGAN);const a=this.isTsumoWin(t.hand),c=this.cfg.orig.myWind,l=c===_.E;return{base:r,fu:n,han:e,isYakuman:o?!0:i,isCountableYakuman:o,isTsumo:a,myWind:c,isParent:l}}hasYakuman(t){return t.some(e=>e.isYakuman)}isRoundUpMangan(t,e){return t===30&&e===4||t===60&&e===3}isTsumoWin(t){return t.some(e=>e.tiles.some(n=>n.has(m.TSUMO)))}calculateDeltas(t,e,n,i,r){const o=$(0);return e?this.calculateTsumoDeltas(o,t,n,i):this.calculateRonDeltas(o,t,n,i,r),this.addStickPoints(o,i),o}calculateRonDeltas(t,e,n,i,r){if(r==null)throw new Error("ron wind is not specified in the parameters");const o=n?V.PARENT_RON:V.CHILD_RON,a=et(e*o),c=this.cfg.sticks.dead*C.DEAD_STICK,l=a+c;t[i]+=l,t[r]-=l}calculateTsumoDeltas(t,e,n,i){const r=this.cfg.sticks.dead*(C.DEAD_STICK/3);n?this.calculateParentTsumoDeltas(t,e,r):this.calculateChildTsumoDeltas(t,e,i,r)}calculateParentTsumoDeltas(t,e,n){const i=et(e*V.PARENT_TSUMO);t[_.E]+=i*3+n*3,t[_.S]-=i+n,t[_.W]-=i+n,t[_.N]-=i+n}calculateChildTsumoDeltas(t,e,n,i){for(const r of Object.values(_)){if(r==n)continue;const o=r==_.E?V.CHILD_TUMO_FROM_PARENT:V.CHILD_TUMO_FROM_CHILD,a=et(e*o);t[r]-=a+i,t[n]+=a+i}}addStickPoints(t,e){t[e]+=C.REACH_STICK*this.cfg.sticks.reach}getBasePoints(t,e){for(const{minHan:n,points:i}of Mr)if(t>=n)return i;return Math.min(e*2**(t+2),C.MANGAN)}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(n=>n.tiles.some(i=>i.has(m.TSUMO)))?[{name:"門前清自摸和",han:1}]:[])}dC1(t){if(this.minus()!=0)return[];const e="平和",n=this.calcFu(t);return n==20?[{name:e,han:1}]:!t.some(i=>i.tiles.some(r=>r.has(m.TSUMO)))&&n==30?[{name:e,han:1}]:[]}dD1(t){return t.some(n=>n.tiles.some(i=>i.t==f.Z||Y.includes(i.n)))?[]:[{name:"断么九",han:1}]}dE1(t){return this.minus()!=0?[]:In(t)==1?[{name:"一盃口",han:1}]:[]}dF1(t){const e=[];return t.forEach(n=>{if(n instanceof B)return;const i=n.tiles[0];i.t==f.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,n=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.hiddenDoras)a.equals(c)&&n++;a.has(m.RED)&&i++}const r=[];return e>0&&r.push({name:"ドラ",han:e}),i>0&&r.push({name:"赤ドラ",han:i}),this.hand.reached&&n>0&&r.push({name:"裏ドラ",han:n}),r}dA2(t){return t.length==7?[{name:"七対子",han:2}]:[]}dB2(t){const e=n=>n instanceof tt||n instanceof J;for(const n of t){if(!e(n))continue;const i=ut(n);if(i.t==f.Z)continue;const r=[f.M,f.P,f.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new y(r[0],i.n);return e(c)&&l.equals(ut(c))}),a=t.some(c=>{const l=new y(r[1],i.n);return e(c)&&l.equals(ut(c))});if(o&&a)return[{name:"三色同順",han:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(n=>n instanceof R||n instanceof K||n instanceof q||n instanceof U||n instanceof X||n instanceof B)?[{name:"対々和",han:2}]:[]}dD2(t){return t.filter(n=>(n instanceof R||n instanceof U)&&!n.tiles.some(i=>i.has(m.RON))).length>=3?[{name:"三暗刻",han:2}]:[]}dE2(t){return t.filter(n=>n instanceof R||n instanceof K||n instanceof q).length>=3?[{name:"三槓子",han:2}]:[]}dF2(t){const e=n=>n instanceof R||n instanceof K||n instanceof q||n instanceof U||n instanceof X;for(const n of t){if(!e(n))continue;const i=ut(n);if(i.t==f.Z)continue;const r=[f.M,f.P,f.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new y(r[0],i.n);return e(c)&&l.equals(ut(c))}),a=t.some(c=>{const l=new y(r[1],i.n);return e(c)&&l.equals(ut(c))});if(o&&a)return[{name:"三色同刻",han:2}]}return[]}dG2(t){return t.length==7?[]:t.filter(n=>{const i=n.tiles[0];return i.t==f.Z&&[5,6,7].includes(i.n)}).length==3?[{name:"小三元",han:2}]:[]}dH2(t){return t.every(n=>{const i=n.tiles[0].t==f.Z?Pt:Y;return n.tiles.every(r=>i.includes(r.n))})?[{name:"混老頭",han:2}]:[]}dI2(t){return t.length==7?[]:t.some(n=>n instanceof tt||n instanceof J)?t.some(n=>n.tiles[0].t==f.Z)?t.every(n=>{const i=n.tiles[0].t==f.Z?Pt:Y;return n.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",han:2-this.minus()}]:[]:[]:[]}dJ2(t){const e={[f.M]:[0,0,0],[f.S]:[0,0,0],[f.P]:[0,0,0]};for(const n of t){const i=ut(n);i.t!=f.BACK&&i.t!=f.Z&&(n instanceof tt||n instanceof J)&&(i.n==1?e[i.t][0]++:i.n==4?e[i.t][1]++:i.n==7&&e[i.t][2]++)}for(const n of Object.values(e))if(n[0]>0&&n[1]>0&&n[2]>0)return[{name:"一気通貫",han:2-this.minus()}];return[]}dA3(t){if(!t.some(n=>n.tiles[0].t==f.Z))return[];for(const n of Object.values(f))if(t.every(r=>r.tiles[0].t==f.Z||r.tiles[0].t==n))return[{name:"混一色",han:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(n=>n instanceof tt||n instanceof J)?t.some(n=>n.tiles[0].t==f.Z)?[]:t.every(n=>n.tiles.some(i=>Y.includes(i.n)))?[{name:"純全帯么九色",han:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:In(t)==2?[{name:"ニ盃口",han:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==f.Z))return[];for(const e of Object.values(f)){if(e==f.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(n=>n instanceof B&&n.tiles.some(i=>i.has(m.TSUMO)||i.has(m.RON)))?[{name:"国士無双13面待ち",han:26,isYakuman:!0}]:[{name:"国士無双",han:13,isYakuman:!0}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",han:13,isYakuman:!0}]:[]}dC13(t){return t.length==7?[]:t.every(i=>i instanceof R||i instanceof U&&i.tiles.every(r=>!r.has(m.RON))||i instanceof B)?t.some(i=>i instanceof B&&i.tiles.some(r=>r.has(m.TSUMO)||r.has(m.RON)))?[{name:"四暗刻単騎待ち",han:26,isYakuman:!0}]:[{name:"四暗刻",han:13,isYakuman:!0}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(i=>!(i instanceof B)&&i.tiles.some(r=>r.t==f.Z&&e.includes(r.n))).length==3?[{name:"大三元",han:13,isYakuman:!0}]:[]}dE13(t){return t.every(n=>n.tiles[0].t==f.Z)?[{name:"字一色",han:13,isYakuman:!0}]:[]}dF13(t){return t.every(n=>n.tiles.every(i=>i.t!=f.Z&&Y.includes(i.n)))?[{name:"清老頭",han:13,isYakuman:!0}]:[]}dG13(t){return t.filter(n=>n instanceof R||n instanceof K||n instanceof q).length==4?[{name:"四槓子",han:13,isYakuman:!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==f.Z&&e.includes(o.n))).length==4?t.find(r=>r instanceof B).tiles.some(r=>r.t==f.Z&&e.includes(r.n))?[{name:"小四喜",han:13,isYakuman:!0}]:[{name:"大四喜",han:13,isYakuman:!0}]:[]}dI13(t){const e=n=>!!(n.equals(new y(f.Z,6))||n.t==f.S&&[2,3,4,6,8].includes(n.n));return t.every(n=>n.tiles.every(i=>e(i)))?[{name:"緑一色",han:13,isYakuman:!0}]:[]}dJ13(t){return[]}dK13(t){return[]}calcFu(t){let n=20;const i=this.cfg.myWind.n,r=this.cfg.roundWind.n;if(t.length==7)return 25;const o=t.find(p=>p.tiles.some(E=>E.has(m.TSUMO)||E.has(m.RON))),a=this.minus()==1,c=o.tiles.some(p=>p.has(m.TSUMO)),l=(p,E)=>{const A=p.tiles[0];return A.t==f.Z||Y.includes(A.n)?E*2:E};for(const p of t)switch(!0){case p instanceof U:const E=p.tiles.some(A=>A.has(m.RON))?2:4;n+=l(p,E);break;case p instanceof X:n+=l(p,2);break;case(p instanceof q||p instanceof K):n+=l(p,8);break;case p instanceof R:n+=l(p,16);break}n+=(p=>{if(p instanceof U)return 0;if(p instanceof B)return 2;const E=p.tiles,A=E.findIndex(T=>T.has(m.TSUMO)||T.has(m.RON));return A==1||A==0&&E[2].n==9||A==2&&E[0].n==1?2:0})(o);const d=t.find(p=>p instanceof B).tiles[0];d.t==f.Z&&([5,6,7].includes(d.n)&&(n+=2),(d.n==r||d.n==i)&&(n+=2));let g=!1;return!a&&n==20&&(g=!0),c&&!g&&(n+=2),!c&&!a&&(n+=10),!c&&!a&&n==30&&(g=!0),a&&n==20&&(n=30),n}}const Ft=s=>s.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),In=s=>{const t={};for(const n of s){if(!(n instanceof tt))continue;const i=Ft(n);t[i]==null?t[i]=1:t[i]++}let e=0;for(const n in t)t[n]>=2&&e++;return e},ut=s=>[...s.tiles].sort(Qt)[0],Be=s=>{const t=s.n,e=s.t;if(e==f.Z){if(t==4)return new y(e,1);if(t==7)return new y(e,5)}return new y(e,t%9+1)};class Ht{static calcEffectiveTiles(t,e,n){b(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=Ht.getEffectiveTiles(t,n);t.inc(a);const l=n?.arrangeRed&&o.has(m.RED)?o.clone({removeAll:!0}):o.has(m.RED)?o.clone({removeAll:!0,add:m.RED}):o.clone({removeAll:!0});c.shanten<r?(i.clear(),i.set(l.toString(),{shanten:c.shanten,effectiveTiles:c.effectiveTiles,tile:l}),r=c.shanten):c.shanten==r&&i.set(l.toString(),{shanten:c.shanten,effectiveTiles:c.effectiveTiles,tile:l})}return Array.from(i.values())}static getEffectiveTiles(t,e){let n=1/0,i=[];const r=new te(t);for(const[o,a]of z({skipBack:!0,filterBy:e?.typeFilter})){if(t.get(o,a)>=4)continue;const c=new y(o,a),l=t.inc([c]),u=e?.standardTypeOnly?r.standardType():r.calc();t.dec(l),u<n?(n=u,i=[c]):u==n&&i.push(c)}return{shanten:n,effectiveTiles:i}}}const De=()=>{const s=new Set;return{on(t){s.add(t)},off(t){s.delete(t)},offAll(){s.clear()},emit(t){s.forEach(e=>e(t))}}};function ns(s){const t=["RON","DAI_KAN","PON","CHI"],e=s.map(r=>r.choices),i=is(e,t).map(r=>s[r]);return{events:i,type:rs(t,i[0]?.choices)}}function ss(s){const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=s.map(r=>r.choices),i=is(e,t).map(r=>s[r]);return{events:i,type:rs(t,i[0]?.choices)}}function is(s,t){let e=[],n=Number.POSITIVE_INFINITY;for(let i=0;i<s.length;i++){const r=s[i];if(Pr(r,t)){const o=Hr(t,r);o<n?(n=o,e=[i]):o===n&&e.push(i)}}return e}function Pr(s,t){return t.some(e=>!!s[e])}function Hr(s,t){for(let e=0;e<s.length;e++){const n=s[e];if(t[n])return e}return Number.POSITIVE_INFINITY}function rs(s,t){if(t==null)return!1;for(const e of s)if(t[e])return e;return!1}const Zt=()=>{const s=De(),t=De(),e={emit:s.emit,on:i=>t.on(i)},n={emit:t.emit,on:i=>s.on(i)};return[e,n]},os=()=>{const s=De();return{emit:n=>{s.emit(n)},on:n=>{s.on(n)}}};class Jt{reachValue=1e3;m;constructor(t){this.m=structuredClone(t)}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}update(t,e){for(let n in e){const i=e[n],r=t[i];this.m[n]+=r}}}class Xt{playerToWind={};windToPlayer=$("");round;sticks;constructor(t,e){this.round=e?.round??O.E1,this.sticks=structuredClone(e?.sticks)??{reach:0,dead:0},this.playerToWind=structuredClone(t);for(let n in this.playerToWind)this.windToPlayer[this.playerToWind[n]]=n}update(){for(let t in this.playerToWind){const e=we(this.playerToWind[t]);this.playerToWind[t]=e,this.windToPlayer[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Vt(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.playerToWind[t]}playerID(t){return this.windToPlayer[t]}get playerMap(){return structuredClone(this.playerToWind)}}function nn(s){for(let t=s.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[s[t],s[e]]=[s[e],s[t]]}return s}class as{constructor(t=!1){this.disable=t,this.c=this.initial()}c;safeTileMap=$({},!0);get(t){return t.t==f.BACK?0:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=f.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(m.RED)&&(this.c[e.t][0]-=1)}}}addTileToSafeMap(t,e){this.disable||(this.safeTileMap[e][this.key(t.t,t.n)]=!0)}isSafeTile(t,e,n){return this.safeTileMap[n][this.key(t,e)]}key(t,e){return`${t}${e}`}reset(){this.c=this.initial()}initial(){return{[f.M]:[1,4,4,4,4,4,4,4,4,4],[f.S]:[1,4,4,4,4,4,4,4,4,4],[f.P]:[1,4,4,4,4,4,4,4,4,4],[f.Z]:[0,4,4,4,4,4,4,4]}}}class sn{m=[];constructor(){}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 b(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 n=0;n<4;n++)if(!e.equals(t[n].t))return!1;return!0}}function Br(){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 Dr(){const s=Br();if(s.__xstate__)return s.__xstate__}const Wr=s=>{if(typeof window>"u")return;const t=Dr();t&&t.register(s)};class vn{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 cs=".",Kr="",ls="",Lr="#",zr="*",hs="xstate.init",We="xstate.stop";function Ur(s,t){return{type:`xstate.after.${s}.${t}`}}function Ke(s,t){return{type:`xstate.done.state.${s}`,output:t}}function jr(s,t){return{type:`xstate.done.actor.${s}`,output:t,actorId:s}}function Gr(s,t){return{type:`xstate.error.actor.${s}`,error:t,actorId:s}}function us(s){return{type:hs,input:s}}function F(s){setTimeout(()=>{throw s})}const Fr=typeof Symbol=="function"&&Symbol.observable||"@@observable";function ds(s,t){const e=Sn(s),n=Sn(t);return typeof n=="string"?typeof e=="string"?n===e:!1:typeof e=="string"?e in n:Object.keys(e).every(i=>i in n?ds(e[i],n[i]):!1)}function rn(s){if(ps(s))return s;const t=[];let e="";for(let n=0;n<s.length;n++){switch(s.charCodeAt(n)){case 92:e+=s[n+1],n++;continue;case 46:t.push(e),e="";continue}e+=s[n]}return t.push(e),t}function Sn(s){if(So(s))return s.value;if(typeof s!="string")return s;const t=rn(s);return Zr(t)}function Zr(s){if(s.length===1)return s[0];const t={};let e=t;for(let n=0;n<s.length-1;n++)if(n===s.length-2)e[s[n]]=s[n+1];else{const i=e;e={},i[s[n]]=e}return t}function On(s,t){const e={},n=Object.keys(s);for(let i=0;i<n.length;i++){const r=n[i];e[r]=t(s[r],r,s,i)}return e}function fs(s){return ps(s)?s:[s]}function nt(s){return s===void 0?[]:fs(s)}function Le(s,t,e,n){return typeof s=="function"?s({context:t,event:e,self:n}):s}function ps(s){return Array.isArray(s)}function Yr(s){return s.type.startsWith("xstate.error.actor")}function St(s){return fs(s).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function gs(s){if(!(s===void 0||s===Kr))return nt(s)}function ze(s,t,e){const n=typeof s=="object",i=n?s:void 0;return{next:(n?s.next:s)?.bind(i),error:(n?s.error:t)?.bind(i),complete:(n?s.complete:e)?.bind(i)}}function kn(s,t){return`${t}.${s}`}function on(s,t){const e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return s.implementations.actors[t];const[,n,i]=e,o=s.getStateNodeById(i).config.invoke;return(Array.isArray(o)?o[n]:o).src}function Cn(s,t){return`${s.sessionId}.${t}`}let Vr=0;function Jr(s,t){const e=new Map,n=new Map,i=new WeakMap,r=new Set,o={},{clock:a,logger:c}=t,l={schedule:(d,g,p,E,A=Math.random().toString(36).slice(2))=>{const T={source:d,target:g,event:p,delay:E,id:A,startedAt:Date.now()},v=Cn(d,A);h._snapshot._scheduledEvents[v]=T;const M=a.setTimeout(()=>{delete o[v],delete h._snapshot._scheduledEvents[v],h._relay(d,g,p)},E);o[v]=M},cancel:(d,g)=>{const p=Cn(d,g),E=o[p];delete o[p],delete h._snapshot._scheduledEvents[p],E!==void 0&&a.clearTimeout(E)},cancelAll:d=>{for(const g in h._snapshot._scheduledEvents){const p=h._snapshot._scheduledEvents[g];p.source===d&&l.cancel(d,p.id)}}},u=d=>{if(!r.size)return;const g={...d,rootId:s.sessionId};r.forEach(p=>p.next?.(g))},h={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Vr++}`,_register:(d,g)=>(e.set(d,g),d),_unregister:d=>{e.delete(d.sessionId);const g=i.get(d);g!==void 0&&(n.delete(g),i.delete(d))},get:d=>n.get(d),getAll:()=>Object.fromEntries(n.entries()),_set:(d,g)=>{const p=n.get(d);if(p&&p!==g)throw new Error(`Actor with system ID '${d}' already exists.`);n.set(d,g),i.set(g,d)},inspect:d=>{const g=ze(d);return r.add(g),{unsubscribe(){r.delete(g)}}},_sendInspectionEvent:u,_relay:(d,g,p)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:g,event:p}),g._send(p)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const d=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const g in d){const{source:p,target:E,event:A,delay:T,id:v}=d[g];l.schedule(p,E,A,T,v)}},_clock:a,_logger:c};return h}let Ie=!1;const an=1;let H=(function(s){return s[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Stopped=2]="Stopped",s})({});const Xr={clock:{setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s)},logger:console.log.bind(console),devTools:!1};class qr{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 vn(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=H.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 n={...Xr,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:u}=n;this.system=o?o.system:Jr(this,{clock:i,logger:r}),u&&!o&&this.system.inspect(ze(u)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:h=>{this._deferred.push(h)},system:this.system,stopChild:h=>{if(h._parent!==this)throw new Error(`Cannot stop child actor ${h.id} of ${this.id} because it is not a child`);h._stop()},emit:h=>{const d=this.eventListeners.get(h.type),g=this.eventListeners.get("*");if(!d&&!g)return;const p=[...d?d.values():[],...g?g.values():[]];for(const E of p)try{E(h)}catch(A){F(A)}},actionExecutor:h=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:h.type,params:h.params}}),!h.exec)return;const g=Ie;try{Ie=!0,h.exec(h.info,h.params)}finally{Ie=g}};this._processingStatus===H.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?.snapshot??e?.state),l&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(e){this._snapshot={status:"error",output:void 0,error:e}}}update(t,e){this._snapshot=t;let n;for(;n=this._deferred.shift();)try{n()}catch(i){this._deferred.length=0,this._snapshot={...t,status:"error",error:i}}switch(this._snapshot.status){case"active":for(const i of this.observers)try{i.next?.(t)}catch(r){F(r)}break;case"done":for(const i of this.observers)try{i.next?.(t)}catch(r){F(r)}this._stopProcedure(),this._complete(),this._doneEvent=jr(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,n){const i=ze(t,e,n);if(this._processingStatus!==H.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(r){F(r)}break;case"error":{const r=this._snapshot.error;if(!i.error)F(r);else try{i.error(r)}catch(o){F(o)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,e){let n=this.eventListeners.get(t);n||(n=new Set,this.eventListeners.set(t,n));const i=e.bind(void 0);return n.add(i),{unsubscribe:()=>{n.delete(i)}}}start(){if(this._processingStatus===H.Running)return this;this._syncSnapshot&&this.subscribe({next:n=>{n.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:n})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=H.Running;const t=us(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(n){return this._snapshot={...this._snapshot,status:"error",error:n},this._error(n),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,n;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){n={err:i}}if(n){const{err:i}=n;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(e,t),t.type===We&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===H.Stopped?this:(this.mailbox.clear(),this._processingStatus===H.NotStarted?(this._processingStatus=H.Stopped,this):(this.mailbox.enqueue({type:We}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(e){F(e)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||F(t);return}let e=!1;for(const n of this.observers){const i=n.error;e||=!i;try{i?.(t)}catch(r){F(r)}}this.observers.clear(),e&&F(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Gr(this.id,t))}_stopProcedure(){return this._processingStatus!==H.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new vn(this._process.bind(this)),this._processingStatus=H.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==H.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:Wr)(this)}toJSON(){return{xstate$$type:an,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Fr](){return this}getSnapshot(){return this._snapshot}}function Bt(s,...[t]){return new qr(s,t)}function Qr(s,t,e,n,{sendId:i}){const r=typeof i=="function"?i(e,n):i;return[t,{sendId:r},void 0]}function to(s,t){s.defer(()=>{s.system.scheduler.cancel(s.self,t.sendId)})}function eo(s){function t(e,n){}return t.type="xstate.cancel",t.sendId=s,t.resolve=Qr,t.execute=to,t}function no(s,t,e,n,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?on(t.machine,o):o,u=typeof i=="function"?i(e):i;let h,d;return l&&(d=typeof a=="function"?a({context:t.context,event:e.event,self:s.self}):a,h=Bt(l,{id:u,src:o,parent:s.self,syncSnapshot:c,systemId:r,input:d})),[_t(t,{children:{...t.children,[u]:h}}),{id:i,systemId:r,actorRef:h,src:o,input:d},void 0]}function so(s,{actorRef:t}){t&&s.defer(()=>{t._processingStatus!==H.Stopped&&t.start()})}function io(...[s,{id:t,systemId:e,input:n,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="xstate.spawnChild",r.id=t,r.systemId=e,r.src=s,r.input=n,r.syncSnapshot=i,r.resolve=no,r.execute=so,r}function ro(s,t,e,n,{actorRef:i}){const r=typeof i=="function"?i(e,n):i,o=typeof r=="string"?t.children[r]:r;let a=t.children;return o&&(a={...a},delete a[o.id]),[_t(t,{children:a}),o,void 0]}function oo(s,t){if(t){if(s.system._unregister(t),t._processingStatus!==H.Running){s.stopChild(t);return}s.defer(()=>{s.stopChild(t)})}}function ms(s){function t(e,n){}return t.type="xstate.stopChild",t.actorRef=s,t.resolve=ro,t.execute=oo,t}function cn(s,t,e,n){const{machine:i}=n,r=typeof s=="function",o=r?s:i.implementations.guards[typeof s=="string"?s:s.type];if(!r&&!o)throw new Error(`Guard '${typeof s=="string"?s:s.type}' is not implemented.'.`);if(typeof o!="function")return cn(o,t,e,n);const a={context:t,event:e},c=r||typeof s=="string"?void 0:"params"in s?typeof s.params=="function"?s.params({context:t,event:e}):s.params:void 0;return"check"in o?o.check(n,a,o):o(a,c)}const ln=s=>s.type==="atomic"||s.type==="final";function Dt(s){return Object.values(s.states).filter(t=>t.type!=="history")}function ee(s,t){const e=[];if(t===s)return e;let n=s.parent;for(;n&&n!==t;)e.push(n),n=n.parent;return e}function fe(s){const t=new Set(s),e=ws(t);for(const n of t)if(n.type==="compound"&&(!e.get(n)||!e.get(n).length))Rn(n).forEach(i=>t.add(i));else if(n.type==="parallel"){for(const i of Dt(n))if(i.type!=="history"&&!t.has(i)){const r=Rn(i);for(const o of r)t.add(o)}}for(const n of t){let i=n.parent;for(;i;)t.add(i),i=i.parent}return t}function ys(s,t){const e=t.get(s);if(!e)return{};if(s.type==="compound"){const i=e[0];if(i){if(ln(i))return i.key}else return{}}const n={};for(const i of e)n[i.key]=ys(i,t);return n}function ws(s){const t=new Map;for(const e of s)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 Es(s,t){const e=fe(t);return ys(s,ws(e))}function hn(s,t){return t.type==="compound"?Dt(t).some(e=>e.type==="final"&&s.has(e)):t.type==="parallel"?Dt(t).every(e=>hn(s,e)):t.type==="final"}const be=s=>s[0]===Lr;function ao(s,t){return s.transitions.get(t)||[...s.transitions.keys()].filter(n=>{if(n===zr)return!0;if(!n.endsWith(".*"))return!1;const i=n.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((n,i)=>i.length-n.length).flatMap(n=>s.transitions.get(n))}function co(s){const t=s.config.after;if(!t)return[];const e=i=>{const r=Ur(i,s.id),o=r.type;return s.entry.push(Bo(r,{id:o,delay:i})),s.exit.push(eo(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 nt(o).map(l=>({...l,event:c,delay:a}))}).map(i=>{const{delay:r}=i;return{...pt(s,i.event,i),delay:r}})}function pt(s,t,e){const n=gs(e.target),i=e.reenter??!1,r=uo(s,n),o={...e,actions:nt(e.actions),guard:e.guard,target:r,source:s,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${s.id}`,target:r?r.map(a=>`#${a.id}`):void 0})};return o}function lo(s){const t=new Map;if(s.config.on)for(const e of Object.keys(s.config.on)){if(e===ls)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=s.config.on[e];t.set(e,St(n).map(i=>pt(s,e,i)))}if(s.config.onDone){const e=`xstate.done.state.${s.id}`;t.set(e,St(s.config.onDone).map(n=>pt(s,e,n)))}for(const e of s.invoke){if(e.onDone){const n=`xstate.done.actor.${e.id}`;t.set(n,St(e.onDone).map(i=>pt(s,n,i)))}if(e.onError){const n=`xstate.error.actor.${e.id}`;t.set(n,St(e.onError).map(i=>pt(s,n,i)))}if(e.onSnapshot){const n=`xstate.snapshot.${e.id}`;t.set(n,St(e.onSnapshot).map(i=>pt(s,n,i)))}}for(const e of s.after){let n=t.get(e.eventType);n||(n=[],t.set(e.eventType,n)),n.push(e)}return t}function ho(s,t){const e=typeof t=="string"?s.states[t]:t?s.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${s.id}`);const n={source:s,actions:!t||typeof t=="string"?[]:nt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...n,source:`#${s.id}`,target:e?[`#${e.id}`]:[]})};return n}function uo(s,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(be(e))return s.machine.getStateNodeById(e);const n=e[0]===cs;if(n&&!s.parent)return pe(s,e.slice(1));const i=n?s.key+e:e;if(s.parent)try{return pe(s.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${s.id}':
|
|
9
|
-
${r.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function _s(s){const t=gs(s.config.target);return t?{target:t.map(e=>typeof e=="string"?pe(s.parent,e):e)}:s.parent.initial}function mt(s){return s.type==="history"}function Rn(s){const t=As(s);for(const e of t)for(const n of ee(e,s))t.add(n);return t}function As(s){const t=new Set;function e(n){if(!t.has(n)){if(t.add(n),n.type==="compound")e(n.initial.target[0]);else if(n.type==="parallel")for(const i of Dt(n))e(i)}}return e(s),t}function Wt(s,t){if(be(t))return s.machine.getStateNodeById(t);if(!s.states)throw new Error(`Unable to retrieve child state '${t}' from '${s.id}'; no child states exist.`);const e=s.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${s.id}'`);return e}function pe(s,t){if(typeof t=="string"&&be(t))try{return s.machine.getStateNodeById(t)}catch{}const e=rn(t).slice();let n=s;for(;e.length;){const i=e.shift();if(!i.length)break;n=Wt(n,i)}return n}function ge(s,t){if(typeof t=="string"){const i=s.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${s.id}'`);return[s,i]}const e=Object.keys(t),n=e.map(i=>Wt(s,i)).filter(Boolean);return[s.machine.root,s].concat(n,e.reduce((i,r)=>{const o=Wt(s,r);if(!o)return i;const a=ge(o,t[r]);return i.concat(a)},[]))}function fo(s,t,e,n){const r=Wt(s,t).next(e,n);return!r||!r.length?s.next(e,n):r}function po(s,t,e,n){const i=Object.keys(t),r=Wt(s,i[0]),o=un(r,t[i[0]],e,n);return!o||!o.length?s.next(e,n):o}function go(s,t,e,n){const i=[];for(const r of Object.keys(t)){const o=t[r];if(!o)continue;const a=Wt(s,r),c=un(a,o,e,n);c&&i.push(...c)}return i.length?i:s.next(e,n)}function un(s,t,e,n){return typeof t=="string"?fo(s,t,e,n):Object.keys(t).length===1?po(s,t,e,n):go(s,t,e,n)}function mo(s){return Object.keys(s.states).map(t=>s.states[t]).filter(t=>t.type==="history")}function rt(s,t){let e=s;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function yo(s,t){const e=new Set(s),n=new Set(t);for(const i of e)if(n.has(i))return!0;for(const i of n)if(e.has(i))return!0;return!1}function bs(s,t,e){const n=new Set;for(const i of s){let r=!1;const o=new Set;for(const a of n)if(yo(Ue([i],t,e),Ue([a],t,e)))if(rt(i.source,a.source))o.add(a);else{r=!0;break}if(!r){for(const a of o)n.delete(a);n.add(i)}}return Array.from(n)}function wo(s){const[t,...e]=s;for(const n of ee(t,void 0))if(e.every(i=>rt(i,n)))return n}function dn(s,t){if(!s.target)return[];const e=new Set;for(const n of s.target)if(mt(n))if(t[n.id])for(const i of t[n.id])e.add(i);else for(const i of dn(_s(n),t))e.add(i);else e.add(n);return[...e]}function Ts(s,t){const e=dn(s,t);if(!e)return;if(!s.reenter&&e.every(i=>i===s.source||rt(i,s.source)))return s.source;const n=wo(e.concat(s.source));if(n)return n;if(!s.reenter)return s.source.machine.root}function Ue(s,t,e){const n=new Set;for(const i of s)if(i.target?.length){const r=Ts(i,e);i.reenter&&i.source===r&&n.add(r);for(const o of t)rt(o,r)&&n.add(o)}return[...n]}function Eo(s,t){if(s.length!==t.size)return!1;for(const e of s)if(!t.has(e))return!1;return!0}function je(s,t,e,n,i,r){if(!s.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=bs(s,o,a);let l=t;i||([l,a]=To(l,n,e,c,o,a,r,e.actionExecutor)),l=Kt(l,n,e,c.flatMap(h=>h.actions),r,void 0),l=Ao(l,n,e,c,o,r,a,i);const u=[...o];l.status==="done"&&(l=Kt(l,n,e,u.sort((h,d)=>d.order-h.order).flatMap(h=>h.exit),r,void 0));try{return a===t.historyValue&&Eo(t._nodes,o)?l:_t(l,{_nodes:u,historyValue:a})}catch(h){throw h}}function _o(s,t,e,n,i){if(n.output===void 0)return;const r=Ke(i.id,i.output!==void 0&&i.parent?Le(i.output,s.context,t,e.self):void 0);return Le(n.output,s.context,r,e.self)}function Ao(s,t,e,n,i,r,o,a){let c=s;const l=new Set,u=new Set;bo(n,o,u,l),a&&u.add(s.machine.root);const h=new Set;for(const d of[...l].sort((g,p)=>g.order-p.order)){i.add(d);const g=[];g.push(...d.entry);for(const p of d.invoke)g.push(io(p.src,{...p,syncSnapshot:!!p.onSnapshot}));if(u.has(d)){const p=d.initial.actions;g.push(...p)}if(c=Kt(c,t,e,g,r,d.invoke.map(p=>p.id)),d.type==="final"){const p=d.parent;let E=p?.type==="parallel"?p:p?.parent,A=E||d;for(p?.type==="compound"&&r.push(Ke(p.id,d.output!==void 0?Le(d.output,c.context,t,e.self):void 0));E?.type==="parallel"&&!h.has(E)&&hn(i,E);)h.add(E),r.push(Ke(E.id)),A=E,E=E.parent;if(E)continue;c=_t(c,{status:"done",output:_o(c,t,e,c.machine.root,A)})}}return c}function bo(s,t,e,n){for(const i of s){const r=Ts(i,t);for(const a of i.target||[])!mt(a)&&(i.source!==a||i.source!==r||i.reenter)&&(n.add(a),e.add(a)),kt(a,t,e,n);const o=dn(i,t);for(const a of o){const c=ee(a,r);r?.type==="parallel"&&c.push(r),Ns(n,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function kt(s,t,e,n){if(mt(s))if(t[s.id]){const i=t[s.id];for(const r of i)n.add(r),kt(r,t,e,n);for(const r of i)ve(r,s.parent,n,t,e)}else{const i=_s(s);for(const r of i.target)n.add(r),i===s.parent?.initial&&e.add(s.parent),kt(r,t,e,n);for(const r of i.target)ve(r,s.parent,n,t,e)}else if(s.type==="compound"){const[i]=s.initial.target;mt(i)||(n.add(i),e.add(i)),kt(i,t,e,n),ve(i,s,n,t,e)}else if(s.type==="parallel")for(const i of Dt(s).filter(r=>!mt(r)))[...n].some(r=>rt(r,i))||(mt(i)||(n.add(i),e.add(i)),kt(i,t,e,n))}function Ns(s,t,e,n,i){for(const r of n)if((!i||rt(r,i))&&s.add(r),r.type==="parallel")for(const o of Dt(r).filter(a=>!mt(a)))[...s].some(a=>rt(a,o))||(s.add(o),kt(o,t,e,s))}function ve(s,t,e,n,i){Ns(e,n,i,ee(s,t))}function To(s,t,e,n,i,r,o,a){let c=s;const l=Ue(n,i,r);l.sort((h,d)=>d.order-h.order);let u;for(const h of l)for(const d of mo(h)){let g;d.history==="deep"?g=p=>ln(p)&&rt(p,h):g=p=>p.parent===h,u??={...r},u[d.id]=Array.from(i).filter(g)}for(const h of l)c=Kt(c,t,e,[...h.exit,...h.invoke.map(d=>ms(d.id))],o,void 0),i.delete(h);return[c,u||r]}function No(s,t){return s.implementations.actions[t]}function Is(s,t,e,n,i,r){const{machine:o}=s;let a=s;for(const c of n){const l=typeof c=="function",u=l?c:No(o,typeof c=="string"?c:c.type),h={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(!u||!("resolve"in u)){e.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:h,params:d,exec:u});continue}const g=u,[p,E,A]=g.resolve(e,a,h,d,u,i);a=p,"retryResolve"in g&&r?.push([g,E]),"execute"in g&&e.actionExecutor({type:g.type,info:h,params:E,exec:g.execute.bind(null,e,E)}),A&&(a=Is(a,t,e,A,i,r))}return a}function Kt(s,t,e,n,i,r){const o=r?[]:void 0,a=Is(s,t,e,n,{internalQueue:i,deferredActorIds:r},o);return o?.forEach(([c,l])=>{c.retryResolve(e,a,l)}),a}function Se(s,t,e,n){let i=s;const r=[];function o(l,u,h){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:u,snapshot:l,_transitions:h}),r.push(l)}if(t.type===We)return i=_t(Mn(i,t,e),{status:"stopped"}),o(i,t,[]),{snapshot:i,microstates:r};let a=t;if(a.type!==hs){const l=a,u=Yr(l),h=xn(l,i);if(u&&!h.length)return i=_t(s,{status:"error",error:l.error}),o(i,l,[]),{snapshot:i,microstates:r};i=je(h,s,e,a,!1,n),o(i,l,h)}let c=!0;for(;i.status==="active";){let l=c?Io(i,a):[];const u=l.length?i:void 0;if(!l.length){if(!n.length)break;a=n.shift(),l=xn(a,i)}i=je(l,i,e,a,!1,n),c=i!==u,o(i,a,l)}return i.status!=="active"&&Mn(i,a,e),{snapshot:i,microstates:r}}function Mn(s,t,e){return Kt(s,t,e,Object.values(s.children).map(n=>ms(n)),[],void 0)}function xn(s,t){return t.machine.getTransitionData(t,s)}function Io(s,t){const e=new Set,n=s._nodes.filter(ln);for(const i of n)t:for(const r of[i].concat(ee(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||cn(o.guard,s.context,t,s)){e.add(o);break t}}return bs(Array.from(e),new Set(s._nodes),s.historyValue)}function vo(s,t){const e=fe(ge(s,t));return Es(s,[...e])}function So(s){return!!s&&typeof s=="object"&&"machine"in s&&"value"in s}const Oo=function(t){return ds(t,this.value)},ko=function(t){return this.tags.has(t)},Co=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(n=>n.target!==void 0||n.actions.length)},Ro=function(){const{_nodes:t,tags:e,machine:n,getMeta:i,toJSON:r,can:o,hasTag:a,matches:c,...l}=this;return{...l,tags:Array.from(e)}},Mo=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function ae(s,t){return{status:s.status,output:s.output,error:s.error,machine:t,context:s.context,_nodes:s._nodes,value:Es(t.root,s._nodes),tags:new Set(s._nodes.flatMap(e=>e.tags)),children:s.children,historyValue:s.historyValue||{},matches:Oo,hasTag:ko,can:Co,getMeta:Mo,toJSON:Ro}}function _t(s,t={}){return ae({...s,...t},s.machine)}function xo(s){if(typeof s!="object"||s===null)return{};const t={};for(const e in s){const n=s[e];Array.isArray(n)&&(t[e]=n.map(i=>({id:i.id})))}return t}function $o(s,t){const{_nodes:e,tags:n,machine:i,children:r,context:o,can:a,hasTag:c,matches:l,getMeta:u,toJSON:h,...d}=s,g={};for(const E in r){const A=r[E];g[E]={snapshot:A.getPersistedSnapshot(t),src:A.src,systemId:A.systemId,syncSnapshot:A._syncSnapshot}}return{...d,context:vs(o),children:g,historyValue:xo(d.historyValue)}}function vs(s){let t;for(const e in s){const n=s[e];if(n&&typeof n=="object")if("sessionId"in n&&"send"in n&&"ref"in n)t??=Array.isArray(s)?s.slice():{...s},t[e]={xstate$$type:an,id:n.id};else{const i=vs(n);i!==n&&(t??=Array.isArray(s)?s.slice():{...s},t[e]=i)}}return t??s}function Po(s,t,e,n,{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,n):i;let u;if(typeof o=="string"){const h=c&&c[o];u=typeof h=="function"?h(e,n):h}else u=typeof o=="function"?o(e,n):o;return typeof u!="number"&&a.push(l),[t,{event:l,id:r,delay:u},void 0]}function Ho(s,t){const{event:e,delay:n,id:i}=t;if(typeof n=="number"){s.defer(()=>{const r=s.self;s.system.scheduler.schedule(r,r,e,n,i)});return}}function Bo(s,t){function e(n,i){}return e.type="xstate.raise",e.event=s,e.id=t?.id,e.delay=t?.delay,e.resolve=Po,e.execute=Ho,e}function Do(s,{machine:t,context:e},n,i){const r=(o,a)=>{if(typeof o=="string"){const c=on(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=Bt(c,{id:a?.id,parent:s.self,syncSnapshot:a?.syncSnapshot,input:typeof a?.input=="function"?a.input({context:e,event:n,self:s.self}):a?.input,src:o,systemId:a?.systemId});return i[l.id]=l,l}else return Bt(o,{id:a?.id,parent:s.self,syncSnapshot:a?.syncSnapshot,input:a?.input,src:o,systemId:a?.systemId})};return(o,a)=>{const c=r(o,a);return i[c.id]=c,s.defer(()=>{c._processingStatus!==H.Stopped&&c.start()}),c}}function Wo(s,t,e,n,{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:Do(s,t,e.event,r),self:s.self,system:s.system};let a={};if(typeof i=="function")a=i(o,n);else for(const l of Object.keys(i)){const u=i[l];a[l]=typeof u=="function"?u(o,n):u}const c=Object.assign({},t.context,a);return[_t(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children}),void 0,void 0]}function Ko(s){function t(e,n){}return t.type="xstate.assign",t.assignment=s,t.resolve=Wo,t}const $n=new WeakMap;function vt(s,t,e){let n=$n.get(s);return n?t in n||(n[t]=e()):(n={[t]:e()},$n.set(s,n)),n[t]}const Lo={},jt=s=>typeof s=="string"?{type:s}:typeof s=="function"?"resolve"in s?{type:s.type}:{type:s.name}:s;class me{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(cs),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?On(this.config.states,(n,i)=>new me(n,{_parent:this,_key:i,_machine:this.machine})):Lo,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=nt(this.config.entry).slice(),this.exit=nt(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=nt(t.tags).slice()}_initialize(){this.transitions=lo(this),this.config.always&&(this.always=St(this.config.always).map(t=>pt(this,ls,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(jt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(jt),eventType:null})}:void 0,history:this.history,states:On(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(jt)})),entry:this.entry.map(jt),exit:this.exit.map(jt),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 vt(this,"invoke",()=>nt(this.config.invoke).map((t,e)=>{const{src:n,systemId:i}=t,r=t.id??kn(this.id,e),o=typeof n=="string"?n:`xstate.invoke.${kn(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 vt(this,"on",()=>[...this.transitions].flatMap(([e,n])=>n.map(i=>[e,i])).reduce((e,[n,i])=>(e[n]=e[n]||[],e[n].push(i),e),{}))}get after(){return vt(this,"delayedTransitions",()=>co(this))}get initial(){return vt(this,"initial",()=>ho(this,this.config.initial))}next(t,e){const n=e.type,i=[];let r;const o=vt(this,`candidates-${n}`,()=>ao(this,n));for(const a of o){const{guard:c}=a,l=t.context;let u=!1;try{u=!c||cn(c,l,e,t)}catch(h){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 '${n}' in state node '${this.id}':
|
|
10
|
-
${h.message}`)}if(u){i.push(...a.actions),r=a;break}}return r?[r]:void 0}get events(){return vt(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const n of Object.keys(t)){const i=t[n];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(n=>!(!n.target&&!n.actions.length&&!n.reenter))));return Array.from(t)}}const zo="#";class fn{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?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards: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 me(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:n,actors:i,delays:r}=this.implementations;return new fn(this.config,{actions:{...e,...t.actions},guards:{...n,...t.guards},actors:{...i,...t.actors},delays:{...r,...t.delays}})}resolveState(t){const e=vo(this.root,t.value),n=fe(ge(this.root,e));return ae({_nodes:[...n],context:t.context||{},children:{},status:hn(n,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,n){return Se(t,e,n,[]).snapshot}microstep(t,e,n){return Se(t,e,n,[]).microstates}getTransitionData(t,e){return un(this.root,t.value,t,e)||[]}getPreInitialState(t,e,n){const{context:i}=this.config,r=ae({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?Kt(r,e,t,[Ko(({spawn:a,event:c,self:l})=>i({spawn:a,input:c.input,self:l}))],n,void 0):r}getInitialSnapshot(t,e){const n=us(e),i=[],r=this.getPreInitialState(t,n,i),o=je([{target:[...As(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],r,t,n,!0,i),{snapshot:a}=Se(o,n,t,i);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=rn(t),n=e.slice(1),i=be(e[0])?e[0].slice(zo.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 pe(r,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return $o(t,e)}restoreSnapshot(t,e){const n={},i=t.children;Object.keys(i).forEach(h=>{const d=i[h],g=d.snapshot,p=d.src,E=typeof p=="string"?on(this,p):p;if(!E)return;const A=Bt(E,{id:h,parent:e.self,syncSnapshot:d.syncSnapshot,snapshot:g,src:p,systemId:d.systemId});n[h]=A});function r(h,d){if(d instanceof me)return d;try{return h.machine.getStateNodeById(d.id)}catch{}}function o(h,d){if(!d||typeof d!="object")return{};const g={};for(const p in d){const E=d[p];for(const A of E){const
|
|
7
|
+
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}ot.prototype.build=function(s){return this.options.preserveOrder?Ki(s,this.options):(Array.isArray(s)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(s={[this.options.arrayNodeName]:s}),this.j2x(s,0,[]).val)};ot.prototype.j2x=function(s,t,e){let n="",i="";const r=e.join(".");for(let o in s)if(Object.prototype.hasOwnProperty.call(s,o))if(typeof s[o]>"u")this.isAttribute(o)&&(i+="");else if(s[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(s[o]instanceof Date)i+=this.buildTextValNode(s[o],o,"",t);else if(typeof s[o]!="object"){const a=this.isAttribute(o);if(a&&!this.ignoreAttributesFn(a,r))n+=this.buildAttrPairStr(a,""+s[o]);else if(!a)if(o===this.options.textNodeName){let c=this.options.tagValueProcessor(o,""+s[o]);i+=this.replaceEntitiesValue(c)}else i+=this.buildTextValNode(s[o],o,"",t)}else if(Array.isArray(s[o])){const a=s[o].length;let c="",l="";for(let u=0;u<a;u++){const h=s[o][u];if(!(typeof h>"u"))if(h===null)o[0]==="?"?i+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(typeof h=="object")if(this.options.oneListGroup){const d=this.j2x(h,t+1,e.concat(o));c+=d.val,this.options.attributesGroupName&&h.hasOwnProperty(this.options.attributesGroupName)&&(l+=d.attrStr)}else c+=this.processTextOrObjNode(h,o,t,e);else if(this.options.oneListGroup){let d=this.options.tagValueProcessor(o,h);d=this.replaceEntitiesValue(d),c+=d}else c+=this.buildTextValNode(h,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(s[o]),c=a.length;for(let l=0;l<c;l++)n+=this.buildAttrPairStr(a[l],""+s[o][a[l]])}else i+=this.processTextOrObjNode(s[o],o,t,e);return{attrStr:n,val:i}};ot.prototype.buildAttrPairStr=function(s,t){return t=this.options.attributeValueProcessor(s,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+s:" "+s+'="'+t+'"'};function ji(s,t,e,n){const i=this.j2x(s,e+1,n.concat(t));return s[this.options.textNodeName]!==void 0&&Object.keys(s).length===1?this.buildTextValNode(s[this.options.textNodeName],t,i.attrStr,e):this.buildObjectNode(i.val,t,i.attrStr,e)}ot.prototype.buildObjectNode=function(s,t,e,n){if(s==="")return t[0]==="?"?this.indentate(n)+"<"+t+e+"?"+this.tagEndChar:this.indentate(n)+"<"+t+e+this.closeTag(t)+this.tagEndChar;{let i="</"+t+this.tagEndChar,r="";return t[0]==="?"&&(r="?",i=""),(e||e==="")&&s.indexOf("<")===-1?this.indentate(n)+"<"+t+e+r+">"+s+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&r.length===0?this.indentate(n)+`<!--${s}-->`+this.newLine:this.indentate(n)+"<"+t+e+r+this.tagEndChar+s+this.indentate(n)+i}};ot.prototype.closeTag=function(s){let t="";return this.options.unpairedTags.indexOf(s)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${s}`,t};ot.prototype.buildTextValNode=function(s,t,e,n){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${s}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(n)+`<!--${s}-->`+this.newLine;if(t[0]==="?")return this.indentate(n)+"<"+t+e+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(t,s);return i=this.replaceEntitiesValue(i),i===""?this.indentate(n)+"<"+t+e+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+e+">"+i+"</"+t+this.tagEndChar}};ot.prototype.replaceEntitiesValue=function(s){if(s&&s.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const e=this.options.entities[t];s=s.replace(e.regex,e.val)}return s};function Fi(s){return this.options.indentBy.repeat(s)}function Gi(s){return s.startsWith(this.options.attributeNamePrefix)&&s!==this.options.textNodeName?s.substr(this.attrPrefixLen):!1}class at{type;attrs={};styles={};deleteMarker=!1;constructor(t){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,Gn(this.attrs),sr(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,n]of Object.entries(t))this.attrs[e]=n;return this}css(t){return this.styles={...this.styles,...t},this}svg(){return this.toString()}}class qe extends at{attrs={};constructor(t){super("image"),this.attrs={...this.attrs,href:t}}load(t){return this.attrs.href=t,this}}class _e extends at{attrs={};constructor(t){super("use"),this.attrs={...this.attrs,href:this.make(t)}}use(t){return this.attrs.href=`#${t}`,this}make(t){return t==null?t:`#${t}`}}class Qe extends at{attrs={};constructor(){super("rect")}fill(t){return this.attrs.fill=t,this}stroke(t){return this.attrs.stroke=t,this}}class wt extends at{attrs;_text="";constructor(t=""){super("text"),this._text=t,this.attrs={}}plain(t){return this._text=t,this}font(t){return this.attrs.fontFamily=t.family,this.attrs.fontSize=t.size,this}center(){return this._text}}let tn=class extends at{raw;constructor(t){super("symbol"),this.raw=t}id(){return this.attr("id")}center(){return this.raw}};class N extends at{children=[];rotateMatrix;translateMatrix;constructor(){super("g")}add(t){return this.children.push(t),this}rotate(t,e,n){return this.rotateMatrix=Ys(t,e,n),this}translate(t,e){return this.translateMatrix=Ce(t,e),this}center(){return this.children.map(t=>t.toString()).join("")}left(...t){const e=[this.translateMatrix,this.rotateMatrix].filter(n=>n!=null);return e.length==0?super.left():super.left(nr(zs(e)))}each(t,e){for(let n=0;n<this.children.length;n++){const i=this.children[n];i instanceof N&&e&&i.each(t,!0),t(n,this.children)}}}const Yi=['xmlns="http://www.w3.org/2000/svg"','version="1.1"','xmlns:xlink="http://www.w3.org/1999/xlink"'];class jn extends at{children=[];constructor(){super("svg")}viewBox;add(t){return this.children.push(t),this}center(){return this.children.map(t=>t.toString()).join("")}left(...t){return`<${[this.type,...Yi,Gn(this.attrs),er(this.viewBox)].filter(e=>e!="").join(" ")}>`}viewbox(t,e,n,i){return this.viewBox={x:t,y:e,width:n,height:i},this}importSymbol(t){for(const e of ir(t))this.add(e);return this}x(t){throw new Error("unimplemented")}y(t){throw new Error("unimplemented")}dx(t){throw new Error("unimplemented")}dy(t){throw new Error("unimplemented")}each(t,e){for(let n=0;n<this.children.length;n++){const i=this.children[n];i instanceof N&&e&&i.each(t,!0),t(n,this.children)}}}function Fn(){return new jn}const Zi=Fn,Vi=N,Ji=qe,Xi=_e,qi=Qe,Qi=wt;function tr(s){return s.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function er(s){return s==null?"":`viewBox="${s.x} ${s.y} ${s.width} ${s.height}"`}function nr(s){return s==null?"":`transform="${Zs(s)}"`}function Gn(s){return Object.entries(s).filter(([t,e])=>e!==void 0).map(([t,e])=>`${tr(t)}="${e}"`).join(" ")}function sr(s){const t=Object.entries(s).map(([e,n])=>`${e}: ${n};`).join(" ");return t!=""?`style="${t}"`:""}function*ir(s){const t=new Di({ignoreAttributes:!1}),e=new ot({ignoreAttributes:!1}),n=t.parse(s);for(const i of n.svg.symbol){const r=e.build(i),o=new tn(r);for(const[a,c]of Object.entries(i))a.startsWith("@_")&&(o.attrs[a.substring(2)]=c);yield o}}const Y=(s,t)=>{const e=L(s.tiles[0],t),n=e.baseHeight,i=e.baseWidth;if(s.is(w.SHO_KAN))return{width:i*2+n,height:Math.max(i*2,n)};const r=s.tiles.reduce((a,c)=>{const l=L(c,t).height;return l>a?l:a},0);return{width:s.tiles.reduce((a,c)=>a+L(c,t).width,0),height:r}},L=(s,t)=>{const e=parseFloat((st.HEIGHT*t).toPrecision(5)),n=parseFloat((st.WIDTH*t).toPrecision(5)),i=s.has(m.HORIZONTAL)?{width:e,height:n,baseWidth:n,baseHeight:e}:{width:n,height:e,w:n,baseWidth:n,baseHeight:e};return(s.has(m.TSUMO)||s.has(m.DORA))&&(i.width+=n*st.TEXT_SCALE),i};class Mt{tileWidth;tileHeight;imageHostUrl;imageExt;scale;svgSprite;constructor(t={}){this.scale=t.scale??1,this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=st.WIDTH*this.scale,this.tileHeight=st.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getHorizontalTileYOffset(t){const e=L(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new qe().load(this.buildURL(t));return this.svgSprite&&(e=new _e().use(Mt.buildID(t))),t instanceof y&&t.has(m.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,n){const i=L(t,this.scale);return this.image(t).dx(e).dy(n).size(i.baseWidth,i.baseHeight)}createTextImage(t,e,n,i){const r=this.createImage(t,e,n),o=L(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,l=o.baseHeight,u=new wt().plain(i);u.size(o.baseWidth,o.baseHeight).font({family:Ge,size:a}).dx(c).dy(l);const h=new N;return h.add(r).add(u).translate(e,n),h}createRotate90Image(t,e,n,i=!1){const r=this.createImage(t,0,0),o=L(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,l=e+this.getHorizontalTileYOffset(t),u=i?n-this.getHorizontalTileYOffset(t):n,h=new N;return h.add(r).translate(l,u).rotate(90,a,c),h}createStick(t){return this.image(t)}static buildID(t){if(t==100||t==1e3)return t==100?"stick100":"stick1000";const e=t.t==f.BACK||t.has(m.RED)?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${Mt.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:e}}class en extends Mt{blockMargin=st.WIDTH*st.BLOCK_MARGIN_SCALE*this.scale;createBlockHandDiscard(t){const e=t instanceof C?t.tilesWithBack:t.tiles,n=new N;let i=0;for(const r of e){const o=L(r,this.scale),a=r.has(m.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),c=r.has(m.HORIZONTAL)?this.getHorizontalTileYOffset(r):0,l=a(r,i,c);n.add(l),i+=o.width}return n}createBlockPonChiKan(t){const e=t.tiles.findIndex(r=>r.has(m.HORIZONTAL));let n=0;const i=new N;if(t.type==w.SHO_KAN){let r=e;for(let o=0;o<t.tiles.length;o++)t.tiles[o].has(m.HORIZONTAL)&&(r=o);for(let o=0;o<t.tiles.length;o++){const a=L(t.tiles[o],this.scale);if(o==r)continue;if(o==e){const u=t.tiles[e],h=t.tiles[r],d=L(u,this.scale),g=this.createRotate90Image(u,0,0,!0),p=this.createRotate90Image(h,0,d.height,!0);i.add(new N().translate(n,0).add(g).add(p)),n+=d.width;continue}const c=a.width*2-a.height,l=this.createImage(t.tiles[o],n,c);n+=a.width,i.add(l)}return i}if(t.type==w.CHI){const r=t.tiles[e],o=this.createRotate90Image(r,n,this.getHorizontalTileYOffset(r));n+=L(r,this.scale).width,i.add(o);for(let a=0;a<t.tiles.length;a++){if(a==e)continue;const c=t.tiles[a],l=L(c,this.scale),u=this.createImage(c,n,0);n+=l.width,i.add(u)}return i}for(let r=0;r<t.tiles.length;r++){const o=r==e?this.createRotate90Image.bind(this):this.createImage.bind(this),a=t.tiles[r],c=r==e?this.getHorizontalTileYOffset(a):0,l=L(a,this.scale),u=o(a,n,c);n+=l.width,i.add(u)}return i}}const rr=(s,t)=>{const e=s.scale;return{[w.CHI]:function(i){const r=Y(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[w.PON]:function(i){const r=Y(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[w.DAI_KAN]:function(i){const r=Y(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[w.SHO_KAN]:function(i){const r=Y(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[w.AN_KAN]:function(i){b(i instanceof C,`block type is not ankan: ${i.type}`);const r=Y(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[w.IMAGE_DORA]:function(i){i=t?.doraText==!1?new Rt([i.tiles[0].clone({remove:m.DORA})]):i;const r=Y(i,e),o=new N,a=t?.doraText===!1?s.createImage(i.tiles[0],0,0):s.createTextImage(i.tiles[0],0,0,"(ドラ)");return o.add(a),{...r,e:o}},[w.TSUMO]:function(i){i=t?.tsumoText==!1?new Rt([i.tiles[0].clone({remove:m.TSUMO})]):i;const r=Y(i,e),o=new N,a=t?.tsumoText===!1?s.createImage(i.tiles[0],0,0):s.createTextImage(i.tiles[0],0,0,"(ツモ)");return o.add(a),{...r,e:o}},[w.HAND]:function(i){const r=Y(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[w.IMAGE_DISCARD]:function(i){const r=Y(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[w.THREE]:function(i){throw new Error("three is unsupported")},[w.RUN]:function(i){throw new Error("run is unsupported")},[w.PAIR]:function(i){throw new Error("pair is unsupported")},[w.ISOLATED]:function(i){throw new Error("isolated is unsupported")},[w.UNKNOWN]:function(i){if(i.tiles.some(a=>a.has(m.TSUMO)||a.has(m.DORA)))throw new Error("found an unknown block with operator tiles");const r=Y(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}}}},Ot=(s,t,e)=>{const n=rr(s,e);let i=0,r=0;const o=[];for(const h of t){const d=n[h.type],g=d(h);r+=g.width,i=g.height>i?g.height:i,o.push(g)}const a=i,c=r+(t.length-1)*s.blockMargin,l=new N;let u=0;for(const h of o){const d=a-h.height,g=new N().translate(u,d);g.add(h.e),l.add(g),u+=h.width+s.blockMargin}return{e:l,width:c,height:a}},or=(s,t,e={},n={responsive:!1,doraText:!0,tsumoText:!0})=>{const i=new en(e),r=Ot(i,t,n);n.responsive||s.size(r.width,r.height),s.viewbox(0,0,r.width,r.height),s.add(r.e)},Yn=()=>{const s=[0,1,2,3,4,5,6,7,8,9],t=[];for(const e of Object.values(f)){if(e==f.BACK){t.push(Mt.buildID(new y(e,0)));continue}t.push(...s.map(n=>Mt.buildID(new y(e,n))).flat())}return t},ar=s=>{const t=Yn(),e=[];return s.each((n,i)=>{const r=i[n];if(r instanceof _e){const a=r.attr("href").substring(1);t.includes(a)&&e.push(a)}},!0),e},cr=s=>{const t=Yn(),e=ar(s);s.each((n,i)=>{const r=i[n];r instanceof tn&&(t.includes(r.id())&&e.includes(r.id())||r.remove())},!0)},lr=s=>{const e=[];for(let n=0;n<s.length;n+=6){const i=s.slice(n,n+6);e.push(i)}return e},G=(s,t,e,n,i=0,r=0)=>{const o=new N().add(s);if(n==90){const a=i,c=r-e;return o.rotate(n,0,e).translate(a,c),new N().add(o)}if(n==180){const a=i+t,c=r-e;return o.rotate(n,0,e).translate(a,c),new N().add(o)}if(n==270){const a=i+e,c=r+(t-e);return o.rotate(n,0,e).translate(a,c),new N().add(o)}return new N().add(o)},se=(s,t)=>{const e=new N,n=lr(s);for(let i=0;i<n.length;i++){let r=n[i],o=i*t.tileHeight;const a=t.createBlockHandDiscard(new Je(r,w.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*n.length}},hr=(s,t,e)=>{const n=t.font,i=t.textWidth,r=t.textHeight,o=e.sticks.dead,a=e.sticks.reach,c=Oe.WIDTH*s.scale,l=Oe.HEIGHT*s.scale;let u=i*3,h=r;const d=(c+s.tileWidth+i-u)/2,g=new wt().plain(e.round).font(n).x(d).y(0);h+=25*s.scale;const p=s.tileHeight,E=new N().size(c,p).translate(0,h),A={family:n.family,size:n.size*.7},I=s.createStick(1e3).size(c,l).x(0).y(0),v=new wt().plain(a.toString()).font(A).dx(c).dy(l),x=s.createStick(100).size(c,l).x(0).y(l+l),It=new wt().plain(o.toString()).font(A).dx(c).dy(l*3);E.add(I),E.add(v),E.add(x),E.add(It);const Nt=s.createImage(e.doras[0],0,0).x(c+i).y(0);E.add(Nt);const Tt=new N;return Tt.add(g),Tt.add(g),Tt.add(E),{e:Tt,width:c+s.tileWidth+i,height:h+s.tileHeight}},ur=(s,t,e=0)=>{const n=Ot(s,t.front),i=Ot(s,t.right),r=Ot(s,t.opposite),o=Ot(s,t.left),a=[n.width,i.width,r.width,o.width].reduce((E,A)=>Math.max(E,A)),c=Math.max(e+s.tileHeight*2+s.blockMargin*2,a+s.tileWidth*2+s.blockMargin),l=c,u=G(n.e,n.width,n.height,0).translate((c-n.width)/2,l-n.height),h=G(i.e,i.width,i.height,270).translate(c-i.height,(c-i.width)/2),d=G(r.e,r.width,r.height,180).translate((c-r.width)/2,0),g=G(o.e,o.width,o.height,90).translate(0,(c-o.width)/2),p=new N().size(c,l);return p.add(u),p.add(h),p.add(d),p.add(g),{e:new N().add(p),width:c,height:l}},dr=s=>{const t=Object.values(ye),e=t.indexOf(s);return[...t.slice(e),...t.slice(0,e)]},fr=(s,t,e)=>{const n=s.tileWidth*5+s.tileHeight*1,i=t.font,r=t.textWidth,o=t.textHeight,a=t.numWidth,c=hr(s,t,e);c.e.translate(n/2-c.width/2,n/2-c.height/2);const l=(Cs,gn,Rs)=>{const Ms=`${Cs} ${gn}`,xs=new wt().plain(Ms).font(i).attr(Rs);return{e:new N().add(xs),width:r+a*gn.toString().length,height:o}},[u,h,d,g]=dr(e.frontPlace),p=e.scores,A=l(u,p.front,{x:n/2,y:n,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let I=l(h,p.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const v=G(I.e,I.width,I.height,270).translate(n,n/2-I.width);let x=l(d,p.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const It=G(x.e,x.width,x.height,180).translate(n/2-x.width,-x.height);let Nt=l(g,p.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const Tt=G(Nt.e,Nt.width,Nt.height,90).translate(-Nt.height,n/2),ct=new N,ks=new Qe().size(n,n).x(0).y(0).fill("none").stroke("#000000");return ct.add(ks),ct.add(c.e),ct.add(A),ct.add(v),ct.add(It),ct.add(Tt),{e:ct,width:n,height:n}},pr=(s,t)=>{const e=se(t.front,s),n=se(t.right,s),i=se(t.opposite,s),r=se(t.left,s),o=[e.height,n.height,i.height,r.height].reduce((v,x)=>Math.max(v,x)),a=s.tileWidth*5+s.tileHeight*1,c=o,l=a+o*2+s.blockMargin,u=l,h=new N().size(l,u),d=l/2-a/2,g=u/2-a/2,p=G(e.e,a,c,0).translate(d,u-c),E=G(n.e,a,c,270).translate(l-c,g),A=G(i.e,a,c,180).translate(d,0),I=G(r.e,a,c,90).translate(0,g);return h.add(p),h.add(E),h.add(A),h.add(I),{e:new N().add(h),width:l,height:u}},Zn=(s,t,e,n,i)=>{const r=new N,o=pr(s,n),a=ur(s,e,o.height),c=fr(s,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}},gr=(s,t,e={},n,i={responsive:!1})=>{const r=new en(e),o=n,{discards:a,hands:c,scoreBoard:l}=Xn(t),u=Zn(r,o,c,a,l);i.responsive||s.size(u.width,u.height),s.viewbox(0,0,u.width,u.height),s.add(u.e)};var Ne;function Vn(s){return{lang:s?.lang??Ne?.lang,message:s?.message,abortEarly:s?.abortEarly??Ne?.abortEarly,abortPipeEarly:s?.abortPipeEarly??Ne?.abortPipeEarly}}var mr;function yr(s){return mr?.get(s)}var wr;function Er(s){return wr?.get(s)}var _r;function Ar(s,t){return _r?.get(s)?.get(t)}function xt(s){const t=typeof s;return t==="string"?`"${s}"`:t==="number"||t==="bigint"||t==="boolean"?`${s}`:t==="object"||t==="function"?(s&&Object.getPrototypeOf(s)?.constructor?.name)??"null":t}function it(s,t,e,n,i){const r=i&&"input"in i?i.input:e.value,o=i?.expected??s.expects??null,a=i?.received??xt(r),c={kind:s.kind,type:s.type,input:r,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:s.requirement,path:i?.path,issues:i?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},l=s.kind==="schema",u=i?.message??s.message??Ar(s.reference,c.lang)??(l?Er(c.lang):null)??n.message??yr(c.lang);u!==void 0&&(c.message=typeof u=="function"?u(c):u),l&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function Lt(s){return{version:1,vendor:"valibot",validate(t){return s["~run"]({value:t},Vn())}}}function br(s,t){const e=[...new Set(s)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function xe(s,t){return{kind:"validation",type:"max_value",reference:xe,async:!1,expects:`<=${s instanceof Date?s.toJSON():xt(s)}`,requirement:s,message:t,"~run"(e,n){return e.typed&&!(e.value<=this.requirement)&&it(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():xt(e.value)}),e}}}function $e(s,t){return{kind:"validation",type:"min_value",reference:$e,async:!1,expects:`>=${s instanceof Date?s.toJSON():xt(s)}`,requirement:s,message:t,"~run"(e,n){return e.typed&&!(e.value>=this.requirement)&&it(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():xt(e.value)}),e}}}function Ir(s,t,e){return typeof s.fallback=="function"?s.fallback(t,e):s.fallback}function Jn(s,t,e){return typeof s.default=="function"?s.default(t,e):s.default}function he(s){return{kind:"schema",type:"number",reference:he,expects:"number",async:!1,message:s,get"~standard"(){return Lt(this)},"~run"(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:it(this,"type",t,e),t}}}function z(s,t){return{kind:"schema",type:"optional",reference:z,expects:`(${s.expects} | undefined)`,async:!1,wrapped:s,default:t,get"~standard"(){return Lt(this)},"~run"(e,n){return e.value===void 0&&(this.default!==void 0&&(e.value=Jn(this,e,n)),e.value===void 0)?(e.typed=!0,e):this.wrapped["~run"](e,n)}}}function Pe(s,t){return{kind:"schema",type:"picklist",reference:Pe,expects:br(s.map(xt),"|"),async:!1,options:s,message:t,get"~standard"(){return Lt(this)},"~run"(e,n){return this.options.includes(e.value)?e.typed=!0:it(this,"type",e,n),e}}}function $t(s,t){return{kind:"schema",type:"strict_object",reference:$t,expects:"Object",async:!1,entries:s,message:t,get"~standard"(){return Lt(this)},"~run"(e,n){const i=e.value;if(i&&typeof i=="object"){e.typed=!0,e.value={};for(const r in this.entries){const o=this.entries[r];if(r in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=r in i?i[r]:Jn(o),c=o["~run"]({value:a},n);if(c.issues){const l={type:"object",origin:"value",input:i,key:r,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],e.issues?.push(u);if(e.issues||(e.issues=c.issues),n.abortEarly){e.typed=!1;break}}c.typed||(e.typed=!1),e.value[r]=c.value}else if(o.fallback!==void 0)e.value[r]=Ir(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(it(this,"key",e,n,{input:void 0,expected:`"${r}"`,path:[{type:"object",origin:"key",input:i,key:r,value:i[r]}]}),n.abortEarly))break}if(!e.issues||!n.abortEarly){for(const r in i)if(!(r in this.entries)){it(this,"key",e,n,{input:r,expected:"never",path:[{type:"object",origin:"key",input:i,key:r,value:i[r]}]});break}}}else it(this,"type",e,n);return e}}}function ue(s){return{kind:"schema",type:"string",reference:ue,expects:"string",async:!1,message:s,get"~standard"(){return Lt(this)},"~run"(t,e){return typeof t.value=="string"?t.typed=!0:it(this,"type",t,e),t}}}function Nn(...s){return{...s[0],pipe:s,get"~standard"(){return Lt(this)},"~run"(t,e){for(const n of s)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!e.abortEarly&&!e.abortPipeEarly)&&(t=n["~run"](t,e))}return t}}}function Nr(s,t,e){const n=s["~run"]({value:t},Vn(e));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}const ie=z($t({discard:z(ue(),""),hand:z(ue(),""),score:z(he(),25e3)}),{discard:"",hand:"",score:25e3}),Tr=$t({[_.E]:ie,[_.S]:ie,[_.W]:ie,[_.N]:ie}),ht={round:O.E1,sticks:{reach:0,dead:0},doras:_.S,front:_.E},vr=z($t({round:z(Pe(Object.keys(Ye)),ht.round),sticks:z($t({reach:z(Nn(he(),$e(0,""),xe(9,"")),ht.sticks.reach),dead:z(Nn(he(),$e(0,""),xe(9,"")),ht.sticks.dead)}),ht.sticks),doras:z(ue(),ht.doras),front:z(Pe(Object.keys(ye)),ht.front)}),ht),Sr=$t({...Tr.entries,board:vr}),Xn=s=>{const t=qn(s);return Qn(t)},qn=s=>{const t=Or(s),e=Nr(Sr,t);if(!e.success)throw e.issues;return e.output},Or=s=>{const t="table",e="board",n=s.split(`
|
|
8
|
+
`).map(a=>a.trim()).filter(a=>a!="");if(n.length==0)throw new Error("empty input");const i=n.shift();if(!i.startsWith(t))throw new Error(`input does not start with table: ${i}`);const r={};let o=[_.E,_.S,_.W,_.N,e];for(;;){const a=n.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,u]=Cr([...n]);r.board=l;for(let h=0;h<u;h++)n.shift()}else{const[l,u]=kr([...n]);r[c]=l;for(let h=0;h<u;h++)n.shift()}}return r},V=(s,t)=>s.replace(t,"").replace(":","").trim(),kr=s=>{const t="hand",e="discard",n="score",i={};let r=0;for(;r<s.length;r++){const o=s[r];if(o.startsWith(t))i.hand=V(o,t);else if(o.startsWith(e))i.discard=V(o,e);else if(o.startsWith(n))i.score=Number(V(o,n));else break}return[i,r]},Cr=s=>{const t="doras",e="round",n="front",i="sticks",r="reach",o="dead",a={};let c=0;for(;c<s.length;c++){const l=s[c];if(l.startsWith(t))a.doras=V(l,t);else if(l.startsWith(e))a.round=V(l,e);else if(l.startsWith(n))a.front=V(l,n);else if(l.startsWith(i)){a.sticks={};const u=s[c+1]??"",h=s[c+2]??"";u.startsWith(r)&&(a.sticks.reach=Number(V(u,r))),u.startsWith(o)&&(a.sticks.dead=Number(V(u,o))),h.startsWith(r)&&(a.sticks.reach=Number(V(h,r))),h.startsWith(o)&&(a.sticks.dead=Number(V(h,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},Qn=s=>{const t=s.board.front,e=Rr(t),n=a=>s[a].discard.replace(/\r?\n/g,""),i={front:new W(n(e.front)).tiles(),right:new W(n(e.right)).tiles(),opposite:new W(n(e.opposite)).tiles(),left:new W(n(e.left)).tiles()},r={front:new W(s[e.front].hand).parse(),right:new W(s[e.right].hand).parse(),opposite:new W(s[e.opposite].hand).parse(),left:new W(s[e.left].hand).parse()},o={round:Ye[s.board.round],frontPlace:ye[t],sticks:s.board.sticks,doras:new W(s.board.doras).tiles(),scores:{front:s[e.front].score,right:s[e.right].score,opposite:s[e.opposite].score,left:s[e.left].score}};return{discards:i,hands:r,scoreBoard:o}},Rr=s=>({front:s,right:yt(s),opposite:yt(yt(s)),left:we(s)});function*j(s){const t=s?.filterBy&&s.filterBy.length>0?s?.filterBy:Object.values(f);for(const e of t){if(s?.skipBack&&e==f.BACK)continue;const n=e==f.Z?7:e==f.BACK?1:9;for(let i=1;i<=n;i++)yield[e,i]}}class Ae{data;constructor(t,e=!1){this.data={[f.M]:[0,0,0,0,0,0,0,0,0,0],[f.P]:[0,0,0,0,0,0,0,0,0,0],[f.S]:[0,0,0,0,0,0,0,0,0,0],[f.Z]:[0,0,0,0,0,0,0,0],[f.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const n=Array.isArray(t)?t:new W(t).parse();for(const i of n){if(i.isCalled()){this.data.called=[...this.called,i];continue}else if(i.is(w.TSUMO)){const r=i.tiles[0];this.inc([r]),this.data.tsumo=r;continue}else if(i.is(w.HAND)){this.inc(i.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(r=>r===f.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,n]of j()){let i=this.get(e,n);e!=f.Z&&n==5&&this.get(e,0)>0&&(i-=this.get(e,0),t.push(new y(e,n,[m.RED])));for(let r=0;r<i;r++)t.push(new y(e,n))}if(this.drawn!=null){const e=this.drawn,n=t.findIndex(i=>i.equals(e)&&e.has(m.RED)==i.has(m.RED));b(n>=0,`drawn tile exists: ${this.drawn} but no tile in hand: ${t.join("")}`),t[n]=t[n].clone({add:m.TSUMO})}return t}toString(){const t=this.called.length>0?`${Q}${this.called.join(Q)}`:"",e=this.drawn?`${Q}${this.drawn.toString()}`:"",n=this.hands.filter(r=>!r.has(m.TSUMO));return`${new Rt(n).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 C))}sum(t){let e=0;for(const[n,i]of j({filterBy:[t]}))e+=this.get(n,i);return e}get(t,e){return t==f.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const n of t){const i=n.t!=f.BACK&&this.get(n.t,n.n)>=4,r=n.has(m.RED)&&this.get(n.t,0)>0;if(i||r){this.dec(e);const o=i?`tile ${n} exists more than 4 times`:`red tile ${n} appears more than 1 times`;throw new Error(`invalid hand: ${o} in hand: ${this.toString()}`)}e.push(n),n.t==f.BACK?this.data[n.t][1]+=1:(this.data[n.t][n.n]+=1,n.has(m.RED)&&(this.data[n.t][0]+=1))}return e}dec(t){const e=[];for(const n of t){const i=this.get(n.t,n.n)<1,r=n.has(m.RED)&&this.get(n.t,0)<=0;if(i||r){this.inc(e);const o=i?`tile ${n} is not`:`red tile ${n} is not`;throw new Error(`invalid hand: ${o} in hand: ${this.toString()}`)}if(e.push(n),n.t==f.BACK?this.data[n.t][1]-=1:(this.data[n.t][n.n]-=1,n.has(m.RED)&&(this.data[n.t][0]-=1)),k(n)&&this.get(n.t,5)==0&&this.get(n.t,0)>0){this.data[n.t][0]=0;const o=e.pop().clone({add:m.RED});e.push(o)}}return e}draw(t){const e=t.clone({add:m.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(n=>!n.has(m.HORIZONTAL));if(e.length!=t.tiles.length-1)throw new Error(`invalid block: removal tiles: ${e}, block: ${t}`);this.dec(e),this.data.called=[...this.called,t],this.data.tsumo=null}kan(t){if(t instanceof C){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof H){const e=this.data.called.findIndex(i=>i.is(w.PON)&&i.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find pon block ${t.tiles[0]} for shokan: ${t}`);let n=t.tiles[0];n=k(n)?n.clone({remove:m.RED}):n,this.dec([n]),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 Ae(this.toString());return t.data.reached=this.data.reached,t}}class te{hand;constructor(t){this.hand=t}calc(){return Math.min(this.sevenPairs(),this.thirteenOrphans(),this.standardType())}sevenPairs(){if(this.hand.called.length>0)return Number.POSITIVE_INFINITY;let t=0,e=0;for(const[n,i]of j({skipBack:!0}))this.hand.get(n,i)==2&&t++,this.hand.get(n,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 Number.POSITIVE_INFINITY;let t=0,e=0;for(const n of Object.values(f)){if(n==f.BACK)continue;const i=n==f.Z?Pt:J;for(const r of i)this.hand.get(n,r)>=1&&t++,this.hand.get(n,r)>=2&&e++}return e>=1?12-t:13-t}standardType(){const t=n=>{const i=[0,0,0];for(const[d,g]of j({filterBy:[f.Z]}))this.hand.get(d,g)>=3?i[0]++:this.hand.get(d,g)==2?i[1]++:this.hand.get(d,g)==1&&i[2]++;const r=[0,0,0],o=this.hand.get(f.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.calcNumberTilePatterns(f.M),u=this.calcNumberTilePatterns(f.P),h=this.calcNumberTilePatterns(f.S);for(const d of[l.patternA,l.patternB])for(const g of[u.patternA,u.patternB])for(const p of[h.patternA,h.patternB]){const E=[this.hand.called.length,0,0];for(let I=0;I<3;I++)E[I]+=d[I]+g[I]+p[I]+i[I]+r[I];const A=this.getStandardTypeShanten(E[0],E[1],E[2],n);A<c&&(c=A)}return c};let e=t(!1);for(const[n,i]of j())if(this.hand.get(n,i)>=2){const r=this.hand.dec(new Array(2).fill(new y(n,i))),o=t(!0);this.hand.inc(r),o<e&&(e=o)}return e}calcNumberTilePatterns(t,e=1){if(e>9)return this.groupRemainingTiles(t);let n=this.calcNumberTilePatterns(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 y(t,e),new y(t,e+1),new y(t,e+2)]),r=this.calcNumberTilePatterns(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<n.patternA[2]||r.patternA[2]==n.patternA[2]&&r.patternA[1]<n.patternA[1])&&(n.patternA=r.patternA),(r.patternB[0]>n.patternB[0]||r.patternB[0]==n.patternB[0]&&r.patternB[1]>n.patternB[1])&&(n.patternB=r.patternB)}if(this.hand.get(t,e)>=3){const i=this.hand.dec(new Array(3).fill(new y(t,e))),r=this.calcNumberTilePatterns(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<n.patternA[2]||r.patternA[2]==n.patternA[2]&&r.patternA[1]<n.patternA[1])&&(n.patternA=r.patternA),(r.patternB[0]>n.patternB[0]||r.patternB[0]==n.patternB[0]&&r.patternB[1]>n.patternB[1])&&(n.patternB=r.patternB)}return n}groupRemainingTiles(t){let e=0,n=0,i=0;for(const[r,o]of j({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,n+=i%2,i=0);return e+=i>>1,n+=i%2,{patternA:[0,e,n],patternB:[0,e,n]}}getStandardTypeShanten(t,e,n,i){let r=i?4:5;return t>4&&(e+=t-4,t=4),t+e>4&&(n+=t+e-4,e=4-t),t+e+n>r&&(n=r-t-e),i&&e++,13-t*3-e*2-n}}class ts{hand;constructor(t){this.hand=t}calc(t){return this.markedHands([...this.sevenPairs(),...this.thirteenOrphans(),...this.nineGates(),...this.standardType()],t)}markedHands(t,e){return t.length==0?[]:t.map(n=>this.markedHand(n,e)).flat()}markedHand(t,e){if(t.length==0)return[];const n=this.hand.drawn!=null||e.has(m.TSUMO)?m.TSUMO:m.RON,i=[],r={};for(let a=0;a<t.length;a++){const c=t[a];if(c.isCalled())continue;const l=c.tiles.findIndex(h=>h.equals(e)&&e.has(m.RED)==h.has(m.RED));if(l<0)continue;const u=Gt(c);r[u]||(r[u]=!0,i.push([a,l]))}if(i.length==0)throw new Error(`found no tile ${e.toString()} in hand: ${t.toString()}`);const o=[];for(const[a,c]of i){const l=[...t],u=l[a],h=u.tiles[c].clone({add:n});l[a]=u.clone({replace:{idx:c,tile:h}}),o.push(l)}return o}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,n]of j({skipBack:!0})){const i=this.hand.get(e,n);if(i!=0)if(i==2){const r=this.hand.dec(new Array(2).fill(new y(e,n)));t.push(new R(r[0],r[1])),this.hand.inc(r)}else return[]}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const n of Object.values(f)){if(n==f.BACK)continue;const i=n==f.Z?Pt:J;for(let r of i)if(this.hand.get(n,r)==1)t.push(new Ve(new y(n,r)));else if(this.hand.get(n,r)==2&&e==!1)t.unshift(new R(new y(n,r),new y(n,r))),e=!0;else return[]}return[t]}nineGates(){const t=(e,n,i)=>i.includes(this.hand.get(e,n));for(const e of Object.values(f)){if(e==f.BACK||e==f.Z)continue;const n=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(n&&i)return[[new Rt(this.hand.hands)]]}return[]}standardType(){let t=[];for(const[e,n]of j())if(this.hand.get(e,n)>=2){const i=new Array(2).fill(new y(e,n));n==5&&this.hand.get(e,0)>0&&this.hand.get(e,n)>=3&&(i[1]=new y(e,n,[m.RED]));const r=this.hand.dec(i),o=this.calcAllBlockCombinations().filter(a=>a.length==4).map(a=>(a.unshift(new R(r[0],r[1])),a));t=[...t,...o],this.hand.inc(r)}return t}calcAllBlockCombinations(){return[this.addRedPatterns(f.M,this.handleNumType(f.M)),this.addRedPatterns(f.P,this.handleNumType(f.P)),this.addRedPatterns(f.S,this.handleNumType(f.S)),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((n,i)=>i.length-n.length).reduce((n,i)=>i.length===0?n:n.flatMap(r=>i.map(o=>[...r,...o])),[[]])}handleBack(){const t=f.BACK,e=this.hand.get(t,0);if(e<3)return[];const n=new y(t,0),i=Array(Math.floor(e/3)).fill(new K([n,n,n]));return i.length==0?[]:[i]}handleZ(){const t=[];for(const[e,n]of j({filterBy:[f.Z]})){if(this.hand.get(e,n)==0)continue;if(this.hand.get(e,n)!=3)return[];const i=new y(e,n);t.push(new K([i,i,i]))}return t.length==0?[]:[t]}addRedPattern(t,e){const n=new y(t,5),i=new y(t,5,[m.RED]),r=[];let o=null;const a={};for(let l=0;l<e.length;l++){const u=e[l],h=u.tiles.findIndex(p=>k(p)&&!p.has(m.RED)),d=u.tiles.findIndex(p=>k(p)&&p.has(m.RED));if(d>-1&&(o=[l,d]),d>-1&&h>-1||h<0)continue;const g=Gt(u);a[g]||(a[g]=!0,r.push([l,h]))}if(o==null)return[e];const c=[e];for(const[l,u]of r){const h=[...e],d=h[l];h[l]=d.clone({replace:{idx:u,tile:i}});const g=h[o[0]];h[o[0]]=g.clone({replace:{idx:o[1],tile:n}}),Gt(d)!=Gt(g)&&c.push(h)}return c}addRedPatterns(t,e){return this.hand.get(t,0)>0&&this.hand.get(t,5)>=2?e.map(n=>this.addRedPattern(t,n)).flat():e}handleNumType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.handleNumType(t,e+1);const n=[];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 y(t,e),new y(t,e+1),new y(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 tt([i[0],i[1],i[2]])),n.push(o)}if(this.hand.get(t,e)==3){const i=this.hand.dec(new Array(3).fill(new y(t,e)));let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new K([i[0],i[1],i[2]])),n.push(o)}return n}}const Pt=[1,2,3,4,5,6,7],J=[1,9],Ft=s=>{const t=s.boardContext;return{...s,hand:s.hand.map(T.deserialize),boardContext:{...t,doraIndicators:t.doraIndicators.map(y.from),hiddenDoraIndicators:t.hiddenDoraIndicators?.map(y.from)}}},de=s=>JSON.parse(JSON.stringify(s)),M={MANGAN:2e3,HANEMAN:3e3,DOUBLE:4e3,TRIPLE:6e3,YAKUMAN:8e3,DOUBLE_YAKUMAN:16e3,DEAD_STICK:300,REACH_STICK:1e3},Mr=[{minHan:26,points:M.DOUBLE_YAKUMAN},{minHan:13,points:M.YAKUMAN},{minHan:11,points:M.TRIPLE},{minHan:8,points:M.DOUBLE},{minHan:6,points:M.HANEMAN},{minHan:5,points:M.MANGAN}],xr={[M.MANGAN]:"満貫",[M.HANEMAN]:"跳満",[M.DOUBLE]:"倍満",[M.TRIPLE]:"三倍満"},X={PARENT_RON:6,CHILD_RON:4,PARENT_TSUMO:2,CHILD_TUMO_FROM_PARENT:2,CHILD_TUMO_FROM_CHILD:1};function es(s){if(s.isYakuman)return"役満";if(s.isCountableYakuman)return"数え役満";const t=$r(s.base,s.isTsumo,s.isParent),e=xr[s.base];return e?`${s.fu}符${s.han}飜 ${e}${t}`:`${s.fu}符${s.han}飜 ${t}`}function $r(s,t,e){if(t)return e?`${et(s*X.PARENT_TSUMO)}`:`${et(s*X.CHILD_TUMO_FROM_CHILD)}-${et(s*X.CHILD_TUMO_FROM_PARENT)}`;{const n=e?X.PARENT_RON:X.CHILD_RON;return`${et(s*n)}`}}const et=(s,t=100)=>Math.ceil(s/t)*t;class He{hand;cfg;constructor(t,e){this.hand=t,this.cfg={doras:e.doraIndicators.map(n=>Be(n)),hiddenDoras:e.hiddenDoraIndicators==null?[]:e.hiddenDoraIndicators.map(n=>Be(n)),roundWind:y.from(e.round.substring(0,2)),myWind:y.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,enableRoundUpMangan:e.enableRoundUpMangan??!1,disableCountableYakuman:e.disableCountableYakuman??!1,disableDoubleYakuman:e.disableDoubleYakuman??!1,orig:e}}calc(...t){const e=this.getWinningHands(t);if(e.length===0)return!1;const n=this.selectBestHand(e),i=this.calculateScore(n),r=this.calculateDeltas(i.base,i.isTsumo,i.isParent,i.myWind,this.cfg.orig.ronWind),o=r[i.myWind];this.addStickPoints(r,i.myWind,this.cfg.orig.ronWind);const a=es({base:i.base,fu:i.fu,han:i.han,isTsumo:i.isTsumo,isParent:i.isParent,isYakuman:i.isYakuman,isCountableYakuman:i.isCountableYakuman});return{...n,fu:i.fu,deltas:r,points:r[i.myWind],basePoints:o,boardContext:this.cfg.orig,description:a}}getWinningHands(t){const e=[];if(t.length==0)return e;for(const n of t){const i=[...this.dA13(n),...this.dB13(n),...this.dC13(n),...this.dD13(n),...this.dE13(n),...this.dF13(n),...this.dG13(n),...this.dH13(n),...this.dI13(n),...this.dJ13(n),...this.dK13(n)].map(r=>(this.cfg.disableDoubleYakuman&&r.han>13&&(r.han=13),r));i.length!=0&&e.push({yakus:i,han:i.reduce((r,o)=>r+o.han,0),fu:30,hand:n,isYakuman:!0})}if(e.length>0)return e;for(const n of t){const i=this.calcFu(n),r=[...this.dA1(n),...this.dB1(n),...this.dC1(n),...this.dD1(n),...this.dE1(n),...this.dF1(n),...this.dG1(n),...this.dH1(n),...this.dI1(n),...this.dJ1(n),...this.dK1(n),...this.dA2(n),...this.dB2(n),...this.dC2(n),...this.dD2(n),...this.dE2(n),...this.dF2(n),...this.dG2(n),...this.dH2(n),...this.dI2(n),...this.dJ2(n),...this.dA3(n),...this.dB3(n),...this.dC3(n),...this.dA6(n)];r.length!=0&&(r.push(...this.dX1(n)),e.push({yakus:r,han:r.reduce((o,a)=>o+a.han,0),fu:i,hand:n}))}return e}selectBestHand(t){let e=0,n=[0,0];for(let i=0;i<t.length;i++){const{han:r,fu:o}=t[i];(r>n[0]||r===n[0]&&o>n[1])&&(e=i,n=[r,o])}return t[e]}calculateScore(t){const{han:e}=t,n=t.fu!==25?et(t.fu,10):25,i=t.isYakuman??!1;let r=this.getBasePoints(e,n),o=!1;e>=13&&e<26&&!this.hasYakuman(t.yakus)&&(r=this.cfg.disableCountableYakuman?M.TRIPLE:M.YAKUMAN,o=!this.cfg.disableCountableYakuman),this.cfg.enableRoundUpMangan&&this.isRoundUpMangan(n,e)&&(r=M.MANGAN);const a=this.isTsumoWin(t.hand),c=this.cfg.orig.myWind,l=c===_.E;return{base:r,fu:n,han:e,isYakuman:o?!0:i,isCountableYakuman:o,isTsumo:a,myWind:c,isParent:l}}hasYakuman(t){return t.some(e=>e.isYakuman)}isRoundUpMangan(t,e){return t===30&&e===4||t===60&&e===3}isTsumoWin(t){return t.some(e=>e.tiles.some(n=>n.has(m.TSUMO)))}calculateDeltas(t,e,n,i,r){const o=P(0);return e?this.calculateTsumoDeltas(o,t,n,i):(b(r!=null,"tumo is false but ron wind is null"),this.calculateRonDeltas(o,t,n,i,r)),o}calculateRonDeltas(t,e,n,i,r){const o=n?X.PARENT_RON:X.CHILD_RON,a=et(e*o);t[i]+=a,t[r]-=a}calculateTsumoDeltas(t,e,n,i){if(n){const r=et(e*X.PARENT_TSUMO);t[_.E]+=r*3,t[_.S]-=r,t[_.W]-=r,t[_.N]-=r;return}for(const r of Object.values(_)){if(r==i)continue;const o=r==_.E?X.CHILD_TUMO_FROM_PARENT:X.CHILD_TUMO_FROM_CHILD,a=et(e*o);t[r]-=a,t[i]+=a}}addStickPoints(t,e,n){t[e]+=M.REACH_STICK*this.cfg.sticks.reach;const i=M.DEAD_STICK*this.cfg.sticks.dead;if(n!=null){t[e]+=i,t[n]-=i;return}for(const r of Object.values(_))r==e?t[r]+=i:t[r]-=i/3}getBasePoints(t,e){for(const{minHan:n,points:i}of Mr)if(t>=n)return i;return Math.min(e*2**(t+2),M.MANGAN)}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.hand.drawn==null,this.minus()!=0?[]:t.some(n=>n.tiles.some(i=>i.has(m.TSUMO)))?[{name:"門前清自摸和",han:1}]:[]}dC1(t){if(this.minus()!=0)return[];const e="平和",n=this.calcFu(t);return n==20?[{name:e,han:1}]:!t.some(i=>i.tiles.some(r=>r.has(m.TSUMO)))&&n==30?[{name:e,han:1}]:[]}dD1(t){return t.some(n=>n.tiles.some(i=>i.t==f.Z||J.includes(i.n)))?[]:[{name:"断么九",han:1}]}dE1(t){return this.minus()!=0?[]:Tn(t)==1?[{name:"一盃口",han:1}]:[]}dF1(t){const e=[];return t.forEach(n=>{if(n instanceof R)return;const i=n.tiles[0];i.t==f.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,n=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.hiddenDoras)a.equals(c)&&n++;a.has(m.RED)&&i++}const r=[];return e>0&&r.push({name:"ドラ",han:e}),i>0&&r.push({name:"赤ドラ",han:i}),this.hand.reached&&n>0&&r.push({name:"裏ドラ",han:n}),r}dA2(t){return t.length==7?[{name:"七対子",han:2}]:[]}dB2(t){const e=n=>n instanceof tt||n instanceof q;for(const n of t){if(!e(n)||n.tiles[0].t==f.Z)continue;const i=ut(n),r=[f.M,f.P,f.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new y(r[0],i.n);return e(c)&&l.equals(ut(c))}),a=t.some(c=>{const l=new y(r[1],i.n);return e(c)&&l.equals(ut(c))});if(o&&a)return[{name:"三色同順",han:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(n=>n instanceof C||n instanceof H||n instanceof F||n instanceof K||n instanceof U||n instanceof R)?[{name:"対々和",han:2}]:[]}dD2(t){return t.filter(n=>(n instanceof C||n instanceof K)&&!n.tiles.some(i=>i.has(m.RON))).length>=3?[{name:"三暗刻",han:2}]:[]}dE2(t){return t.filter(n=>n instanceof C||n instanceof H||n instanceof F).length>=3?[{name:"三槓子",han:2}]:[]}dF2(t){const e=n=>n instanceof C||n instanceof H||n instanceof F||n instanceof K||n instanceof U;for(const n of t){if(!e(n))continue;const i=ut(n);if(i.t==f.Z)continue;const r=[f.M,f.P,f.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new y(r[0],i.n);return e(c)&&l.equals(ut(c))}),a=t.some(c=>{const l=new y(r[1],i.n);return e(c)&&l.equals(ut(c))});if(o&&a)return[{name:"三色同刻",han:2}]}return[]}dG2(t){return t.length==7?[]:t.filter(n=>{const i=n.tiles[0];return i.t==f.Z&&[5,6,7].includes(i.n)}).length==3?[{name:"小三元",han:2}]:[]}dH2(t){return t.every(n=>{const i=n.tiles[0],r=i.t==f.Z?Pt:J;return(n instanceof C||n instanceof H||n instanceof F||n instanceof K||n instanceof U||n instanceof R)&&r.includes(i.n)})?[{name:"混老頭",han:2}]:[]}dI2(t){return t.length==7?[]:t.some(n=>n instanceof tt||n instanceof q)?t.some(n=>n.tiles[0].t==f.Z)?t.every(n=>{const i=n.tiles[0].t==f.Z?Pt:J;return n.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",han:2-this.minus()}]:[]:[]:[]}dJ2(t){const e={[f.M]:[0,0,0],[f.S]:[0,0,0],[f.P]:[0,0,0]};for(const n of t){const i=ut(n);i.t!=f.BACK&&i.t!=f.Z&&(n instanceof tt||n instanceof q)&&(i.n==1?e[i.t][0]++:i.n==4?e[i.t][1]++:i.n==7&&e[i.t][2]++)}for(const n of Object.values(e))if(n[0]>0&&n[1]>0&&n[2]>0)return[{name:"一気通貫",han:2-this.minus()}];return[]}dA3(t){if(!t.some(n=>n.tiles[0].t==f.Z))return[];for(const n of Object.values(f))if(t.every(r=>r.tiles[0].t==f.Z||r.tiles[0].t==n))return[{name:"混一色",han:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(n=>n instanceof tt||n instanceof q)?t.some(n=>n.tiles[0].t==f.Z)?[]:t.every(n=>n.tiles.some(i=>J.includes(i.n)))?[{name:"純全帯么九色",han:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:Tn(t)==2?[{name:"ニ盃口",han:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==f.Z))return[];for(const e of Object.values(f)){if(e==f.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(n=>n instanceof R&&n.tiles.some(i=>i.has(m.TSUMO)||i.has(m.RON)))?[{name:"国士無双13面待ち",han:26,isYakuman:!0}]:[{name:"国士無双",han:13,isYakuman:!0}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",han:13,isYakuman:!0}]:[]}dC13(t){return t.length==7?[]:t.every(i=>i instanceof C||i instanceof K&&i.tiles.every(r=>!r.has(m.RON))||i instanceof R)?t.some(i=>i instanceof R&&i.tiles.some(r=>r.has(m.TSUMO)||r.has(m.RON)))?[{name:"四暗刻単騎待ち",han:26,isYakuman:!0}]:[{name:"四暗刻",han:13,isYakuman:!0}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(i=>!(i instanceof R)&&i.tiles.some(r=>r.t==f.Z&&e.includes(r.n))).length==3?[{name:"大三元",han:13,isYakuman:!0}]:[]}dE13(t){return t.every(n=>n.tiles[0].t==f.Z)?[{name:"字一色",han:13,isYakuman:!0}]:[]}dF13(t){return t.every(n=>(n instanceof C||n instanceof H||n instanceof F||n instanceof K||n instanceof U||n instanceof R)&&J.includes(n.tiles[0].n))?[{name:"清老頭",han:13,isYakuman:!0}]:[]}dG13(t){return t.length==7?[]:t.every(n=>n instanceof C||n instanceof H||n instanceof F||n instanceof R)?[{name:"四槓子",han:13,isYakuman:!0}]:[]}dH13(t){if(t.length==13)return[];if(t.length==7)return[];const e=[1,2,3,4];return t.filter(r=>{const o=r.tiles[0];return o.t==f.Z&&e.includes(o.n)}).length==4?t.find(r=>r instanceof R).tiles.some(r=>r.t==f.Z&&e.includes(r.n))?[{name:"小四喜",han:13,isYakuman:!0}]:[{name:"大四喜",han:13,isYakuman:!0}]:[]}dI13(t){const e=n=>!!(n.equals(new y(f.Z,6))||n.t==f.S&&[2,3,4,6,8].includes(n.n));return t.every(n=>n.tiles.every(i=>e(i)))?[{name:"緑一色",han:13,isYakuman:!0}]:[]}dJ13(t){return[]}dK13(t){return[]}calcFu(t){if(t.length==7)return 25;const e=20;let n=e;const i=this.cfg.myWind.n,r=this.cfg.roundWind.n,o=t.find(p=>p.tiles.some(E=>E.has(m.TSUMO)||E.has(m.RON))),a=this.minus()==1,c=o.tiles.some(p=>p.has(m.TSUMO)),l=(p,E)=>{const A=p.tiles[0];return A.t==f.Z||J.includes(A.n)?E*2:E};for(const p of t)switch(!0){case p instanceof K:const E=p.tiles.some(A=>A.has(m.RON))?2:4;n+=l(p,E);break;case p instanceof U:n+=l(p,2);break;case(p instanceof F||p instanceof H):n+=l(p,8);break;case p instanceof C:n+=l(p,16);break}n+=(p=>{if(p instanceof K)return 0;if(p instanceof R)return 2;const E=p.tiles,A=E.findIndex(I=>I.has(m.TSUMO)||I.has(m.RON));return A==1||A==0&&E[2].n==9||A==2&&E[0].n==1?2:0})(o);const d=t.find(p=>p instanceof R).tiles[0];d.t==f.Z&&([5,6,7].includes(d.n)&&(n+=2),(d.n==r||d.n==i)&&(n+=2));let g=!1;return!a&&n==e&&(g=!0),c&&!g&&(n+=2),!c&&!a&&(n+=10),!c&&!a&&n==30&&(g=!0),a&&n==e&&(n=30),n}}const Gt=s=>s.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),Tn=s=>{const t={};for(const n of s){if(!(n instanceof tt))continue;const i=Gt(n);t[i]==null?t[i]=1:t[i]++}let e=0;for(const n in t)t[n]>=2&&e++;return e},ut=s=>[...s.tiles].sort(Qt)[0],Be=s=>{const t=s.n,e=s.t;if(e==f.Z){if(t==4)return new y(e,1);if(t==7)return new y(e,5)}return new y(e,t%9+1)};class Ht{static calcEffectiveTiles(t,e,n){if(e.length==0)throw new Error("choices to discard is zero");const i=new Map;let r=Number.POSITIVE_INFINITY;for(const o of e){const a=t.dec([o]),c=Ht.getEffectiveTiles(t,n);t.inc(a);const l=n?.arrangeRed&&o.has(m.RED)?o.clone({removeAll:!0}):o.has(m.RED)?o.clone({removeAll:!0,add:m.RED}):o.clone({removeAll:!0});c.shanten<r?(i.clear(),i.set(l.toString(),{shanten:c.shanten,effectiveTiles:c.effectiveTiles,tile:l}),r=c.shanten):c.shanten==r&&i.set(l.toString(),{shanten:c.shanten,effectiveTiles:c.effectiveTiles,tile:l})}return Array.from(i.values())}static getEffectiveTiles(t,e){let n=Number.POSITIVE_INFINITY,i=[];const r=new te(t);for(const[o,a]of j({skipBack:!0,filterBy:e?.typeFilter})){if(t.get(o,a)>=4)continue;const c=new y(o,a),l=t.inc([c]),u=e?.standardTypeOnly?r.standardType():r.calc();t.dec(l),u<n?(n=u,i=[c]):u==n&&i.push(c)}return{shanten:n,effectiveTiles:i}}}const De=()=>{const s=new Set;return{on(t){s.add(t)},off(t){s.delete(t)},offAll(){s.clear()},emit(t){s.forEach(e=>e(t))}}};function ns(s){const t=["RON","DAI_KAN","PON","CHI"],e=s.map(r=>r.choices),i=is(e,t).map(r=>s[r]);return{events:i,type:rs(t,i[0]?.choices)}}function ss(s){const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=s.map(r=>r.choices),i=is(e,t).map(r=>s[r]);return{events:i,type:rs(t,i[0]?.choices)}}function is(s,t){let e=[],n=Number.POSITIVE_INFINITY;for(let i=0;i<s.length;i++){const r=s[i];if(Pr(r,t)){const o=Hr(t,r);o<n?(n=o,e=[i]):o===n&&e.push(i)}}return e}function Pr(s,t){return t.some(e=>!!s[e])}function Hr(s,t){for(let e=0;e<s.length;e++){const n=s[e];if(t[n])return e}return Number.POSITIVE_INFINITY}function rs(s,t){if(t==null)return!1;for(const e of s)if(t[e])return e;return!1}const Yt=()=>{const s=De(),t=De(),e={emit:s.emit,on:i=>t.on(i)},n={emit:t.emit,on:i=>s.on(i)};return[e,n]},os=()=>{const s=De();return{emit:n=>{s.emit(n)},on:n=>{s.on(n)}}};class Jt{reachValue=1e3;m;constructor(t){this.m=structuredClone(t)}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}update(t,e){for(let n in e){const i=e[n],r=t[i];this.m[n]+=r}}}class Xt{playerToWind={};windToPlayer=P("");round;sticks;constructor(t,e){this.round=e?.round??O.E1,this.sticks=structuredClone(e?.sticks)??{reach:0,dead:0},this.playerToWind=structuredClone(t);for(let n in this.playerToWind)this.windToPlayer[this.playerToWind[n]]=n}update(){for(let t in this.playerToWind){const e=we(this.playerToWind[t]);this.playerToWind[t]=e,this.windToPlayer[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Vt(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.playerToWind[t]}playerID(t){return this.windToPlayer[t]}get playerMap(){return structuredClone(this.playerToWind)}}function nn(s){for(let t=s.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[s[t],s[e]]=[s[e],s[t]]}return s}class as{constructor(t=!1){this.disable=t,this.c=this.initial()}c;safeTileMap=P({},!0);get(t){return t.t==f.BACK?0:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=f.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(m.RED)&&(this.c[e.t][0]-=1)}}}addTileToSafeMap(t,e){this.disable||(this.safeTileMap[e][this.key(t.t,t.n)]=!0)}isSafeTile(t,e,n){return this.safeTileMap[n][this.key(t,e)]}key(t,e){return`${t}${e}`}reset(){this.c=this.initial()}initial(){return{[f.M]:[1,4,4,4,4,4,4,4,4,4],[f.S]:[1,4,4,4,4,4,4,4,4,4],[f.P]:[1,4,4,4,4,4,4,4,4,4],[f.Z]:[0,4,4,4,4,4,4,4]}}}class sn{m=[];constructor(){}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 b(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 n=0;n<4;n++)if(!e.equals(t[n].t))return!1;return!0}}function Br(){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 Dr(){const s=Br();if(s.__xstate__)return s.__xstate__}const Wr=s=>{if(typeof window>"u")return;const t=Dr();t&&t.register(s)};class vn{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 cs=".",Kr="",ls="",Lr="#",zr="*",hs="xstate.init",We="xstate.stop";function Ur(s,t){return{type:`xstate.after.${s}.${t}`}}function Ke(s,t){return{type:`xstate.done.state.${s}`,output:t}}function jr(s,t){return{type:`xstate.done.actor.${s}`,output:t,actorId:s}}function Fr(s,t){return{type:`xstate.error.actor.${s}`,error:t,actorId:s}}function us(s){return{type:hs,input:s}}function Z(s){setTimeout(()=>{throw s})}const Gr=typeof Symbol=="function"&&Symbol.observable||"@@observable";function ds(s,t){const e=Sn(s),n=Sn(t);return typeof n=="string"?typeof e=="string"?n===e:!1:typeof e=="string"?e in n:Object.keys(e).every(i=>i in n?ds(e[i],n[i]):!1)}function rn(s){if(ps(s))return s;const t=[];let e="";for(let n=0;n<s.length;n++){switch(s.charCodeAt(n)){case 92:e+=s[n+1],n++;continue;case 46:t.push(e),e="";continue}e+=s[n]}return t.push(e),t}function Sn(s){if(So(s))return s.value;if(typeof s!="string")return s;const t=rn(s);return Yr(t)}function Yr(s){if(s.length===1)return s[0];const t={};let e=t;for(let n=0;n<s.length-1;n++)if(n===s.length-2)e[s[n]]=s[n+1];else{const i=e;e={},i[s[n]]=e}return t}function On(s,t){const e={},n=Object.keys(s);for(let i=0;i<n.length;i++){const r=n[i];e[r]=t(s[r],r,s,i)}return e}function fs(s){return ps(s)?s:[s]}function nt(s){return s===void 0?[]:fs(s)}function Le(s,t,e,n){return typeof s=="function"?s({context:t,event:e,self:n}):s}function ps(s){return Array.isArray(s)}function Zr(s){return s.type.startsWith("xstate.error.actor")}function St(s){return fs(s).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function gs(s){if(!(s===void 0||s===Kr))return nt(s)}function ze(s,t,e){const n=typeof s=="object",i=n?s:void 0;return{next:(n?s.next:s)?.bind(i),error:(n?s.error:t)?.bind(i),complete:(n?s.complete:e)?.bind(i)}}function kn(s,t){return`${t}.${s}`}function on(s,t){const e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return s.implementations.actors[t];const[,n,i]=e,o=s.getStateNodeById(i).config.invoke;return(Array.isArray(o)?o[n]:o).src}function Cn(s,t){return`${s.sessionId}.${t}`}let Vr=0;function Jr(s,t){const e=new Map,n=new Map,i=new WeakMap,r=new Set,o={},{clock:a,logger:c}=t,l={schedule:(d,g,p,E,A=Math.random().toString(36).slice(2))=>{const I={source:d,target:g,event:p,delay:E,id:A,startedAt:Date.now()},v=Cn(d,A);h._snapshot._scheduledEvents[v]=I;const x=a.setTimeout(()=>{delete o[v],delete h._snapshot._scheduledEvents[v],h._relay(d,g,p)},E);o[v]=x},cancel:(d,g)=>{const p=Cn(d,g),E=o[p];delete o[p],delete h._snapshot._scheduledEvents[p],E!==void 0&&a.clearTimeout(E)},cancelAll:d=>{for(const g in h._snapshot._scheduledEvents){const p=h._snapshot._scheduledEvents[g];p.source===d&&l.cancel(d,p.id)}}},u=d=>{if(!r.size)return;const g={...d,rootId:s.sessionId};r.forEach(p=>p.next?.(g))},h={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Vr++}`,_register:(d,g)=>(e.set(d,g),d),_unregister:d=>{e.delete(d.sessionId);const g=i.get(d);g!==void 0&&(n.delete(g),i.delete(d))},get:d=>n.get(d),getAll:()=>Object.fromEntries(n.entries()),_set:(d,g)=>{const p=n.get(d);if(p&&p!==g)throw new Error(`Actor with system ID '${d}' already exists.`);n.set(d,g),i.set(g,d)},inspect:d=>{const g=ze(d);return r.add(g),{unsubscribe(){r.delete(g)}}},_sendInspectionEvent:u,_relay:(d,g,p)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:g,event:p}),g._send(p)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const d=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const g in d){const{source:p,target:E,event:A,delay:I,id:v}=d[g];l.schedule(p,E,A,I,v)}},_clock:a,_logger:c};return h}let Te=!1;const an=1;let D=(function(s){return s[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Stopped=2]="Stopped",s})({});const Xr={clock:{setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s)},logger:console.log.bind(console),devTools:!1};class qr{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 vn(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=D.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 n={...Xr,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:u}=n;this.system=o?o.system:Jr(this,{clock:i,logger:r}),u&&!o&&this.system.inspect(ze(u)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:h=>{this._deferred.push(h)},system:this.system,stopChild:h=>{if(h._parent!==this)throw new Error(`Cannot stop child actor ${h.id} of ${this.id} because it is not a child`);h._stop()},emit:h=>{const d=this.eventListeners.get(h.type),g=this.eventListeners.get("*");if(!d&&!g)return;const p=[...d?d.values():[],...g?g.values():[]];for(const E of p)try{E(h)}catch(A){Z(A)}},actionExecutor:h=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:h.type,params:h.params}}),!h.exec)return;const g=Te;try{Te=!0,h.exec(h.info,h.params)}finally{Te=g}};this._processingStatus===D.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?.snapshot??e?.state),l&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(e){this._snapshot={status:"error",output:void 0,error:e}}}update(t,e){this._snapshot=t;let n;for(;n=this._deferred.shift();)try{n()}catch(i){this._deferred.length=0,this._snapshot={...t,status:"error",error:i}}switch(this._snapshot.status){case"active":for(const i of this.observers)try{i.next?.(t)}catch(r){Z(r)}break;case"done":for(const i of this.observers)try{i.next?.(t)}catch(r){Z(r)}this._stopProcedure(),this._complete(),this._doneEvent=jr(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,n){const i=ze(t,e,n);if(this._processingStatus!==D.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(r){Z(r)}break;case"error":{const r=this._snapshot.error;if(!i.error)Z(r);else try{i.error(r)}catch(o){Z(o)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,e){let n=this.eventListeners.get(t);n||(n=new Set,this.eventListeners.set(t,n));const i=e.bind(void 0);return n.add(i),{unsubscribe:()=>{n.delete(i)}}}start(){if(this._processingStatus===D.Running)return this;this._syncSnapshot&&this.subscribe({next:n=>{n.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:n})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=D.Running;const t=us(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(n){return this._snapshot={...this._snapshot,status:"error",error:n},this._error(n),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,n;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){n={err:i}}if(n){const{err:i}=n;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(e,t),t.type===We&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===D.Stopped?this:(this.mailbox.clear(),this._processingStatus===D.NotStarted?(this._processingStatus=D.Stopped,this):(this.mailbox.enqueue({type:We}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(e){Z(e)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||Z(t);return}let e=!1;for(const n of this.observers){const i=n.error;e||=!i;try{i?.(t)}catch(r){Z(r)}}this.observers.clear(),e&&Z(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Fr(this.id,t))}_stopProcedure(){return this._processingStatus!==D.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new vn(this._process.bind(this)),this._processingStatus=D.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==D.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:Wr)(this)}toJSON(){return{xstate$$type:an,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Gr](){return this}getSnapshot(){return this._snapshot}}function Bt(s,...[t]){return new qr(s,t)}function Qr(s,t,e,n,{sendId:i}){const r=typeof i=="function"?i(e,n):i;return[t,{sendId:r},void 0]}function to(s,t){s.defer(()=>{s.system.scheduler.cancel(s.self,t.sendId)})}function eo(s){function t(e,n){}return t.type="xstate.cancel",t.sendId=s,t.resolve=Qr,t.execute=to,t}function no(s,t,e,n,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?on(t.machine,o):o,u=typeof i=="function"?i(e):i;let h,d;return l&&(d=typeof a=="function"?a({context:t.context,event:e.event,self:s.self}):a,h=Bt(l,{id:u,src:o,parent:s.self,syncSnapshot:c,systemId:r,input:d})),[_t(t,{children:{...t.children,[u]:h}}),{id:i,systemId:r,actorRef:h,src:o,input:d},void 0]}function so(s,{actorRef:t}){t&&s.defer(()=>{t._processingStatus!==D.Stopped&&t.start()})}function io(...[s,{id:t,systemId:e,input:n,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="xstate.spawnChild",r.id=t,r.systemId=e,r.src=s,r.input=n,r.syncSnapshot=i,r.resolve=no,r.execute=so,r}function ro(s,t,e,n,{actorRef:i}){const r=typeof i=="function"?i(e,n):i,o=typeof r=="string"?t.children[r]:r;let a=t.children;return o&&(a={...a},delete a[o.id]),[_t(t,{children:a}),o,void 0]}function oo(s,t){if(t){if(s.system._unregister(t),t._processingStatus!==D.Running){s.stopChild(t);return}s.defer(()=>{s.stopChild(t)})}}function ms(s){function t(e,n){}return t.type="xstate.stopChild",t.actorRef=s,t.resolve=ro,t.execute=oo,t}function cn(s,t,e,n){const{machine:i}=n,r=typeof s=="function",o=r?s:i.implementations.guards[typeof s=="string"?s:s.type];if(!r&&!o)throw new Error(`Guard '${typeof s=="string"?s:s.type}' is not implemented.'.`);if(typeof o!="function")return cn(o,t,e,n);const a={context:t,event:e},c=r||typeof s=="string"?void 0:"params"in s?typeof s.params=="function"?s.params({context:t,event:e}):s.params:void 0;return"check"in o?o.check(n,a,o):o(a,c)}const ln=s=>s.type==="atomic"||s.type==="final";function Dt(s){return Object.values(s.states).filter(t=>t.type!=="history")}function ee(s,t){const e=[];if(t===s)return e;let n=s.parent;for(;n&&n!==t;)e.push(n),n=n.parent;return e}function fe(s){const t=new Set(s),e=ws(t);for(const n of t)if(n.type==="compound"&&(!e.get(n)||!e.get(n).length))Rn(n).forEach(i=>t.add(i));else if(n.type==="parallel"){for(const i of Dt(n))if(i.type!=="history"&&!t.has(i)){const r=Rn(i);for(const o of r)t.add(o)}}for(const n of t){let i=n.parent;for(;i;)t.add(i),i=i.parent}return t}function ys(s,t){const e=t.get(s);if(!e)return{};if(s.type==="compound"){const i=e[0];if(i){if(ln(i))return i.key}else return{}}const n={};for(const i of e)n[i.key]=ys(i,t);return n}function ws(s){const t=new Map;for(const e of s)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 Es(s,t){const e=fe(t);return ys(s,ws(e))}function hn(s,t){return t.type==="compound"?Dt(t).some(e=>e.type==="final"&&s.has(e)):t.type==="parallel"?Dt(t).every(e=>hn(s,e)):t.type==="final"}const be=s=>s[0]===Lr;function ao(s,t){return s.transitions.get(t)||[...s.transitions.keys()].filter(n=>{if(n===zr)return!0;if(!n.endsWith(".*"))return!1;const i=n.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((n,i)=>i.length-n.length).flatMap(n=>s.transitions.get(n))}function co(s){const t=s.config.after;if(!t)return[];const e=i=>{const r=Ur(i,s.id),o=r.type;return s.entry.push(Bo(r,{id:o,delay:i})),s.exit.push(eo(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 nt(o).map(l=>({...l,event:c,delay:a}))}).map(i=>{const{delay:r}=i;return{...pt(s,i.event,i),delay:r}})}function pt(s,t,e){const n=gs(e.target),i=e.reenter??!1,r=uo(s,n),o={...e,actions:nt(e.actions),guard:e.guard,target:r,source:s,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${s.id}`,target:r?r.map(a=>`#${a.id}`):void 0})};return o}function lo(s){const t=new Map;if(s.config.on)for(const e of Object.keys(s.config.on)){if(e===ls)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=s.config.on[e];t.set(e,St(n).map(i=>pt(s,e,i)))}if(s.config.onDone){const e=`xstate.done.state.${s.id}`;t.set(e,St(s.config.onDone).map(n=>pt(s,e,n)))}for(const e of s.invoke){if(e.onDone){const n=`xstate.done.actor.${e.id}`;t.set(n,St(e.onDone).map(i=>pt(s,n,i)))}if(e.onError){const n=`xstate.error.actor.${e.id}`;t.set(n,St(e.onError).map(i=>pt(s,n,i)))}if(e.onSnapshot){const n=`xstate.snapshot.${e.id}`;t.set(n,St(e.onSnapshot).map(i=>pt(s,n,i)))}}for(const e of s.after){let n=t.get(e.eventType);n||(n=[],t.set(e.eventType,n)),n.push(e)}return t}function ho(s,t){const e=typeof t=="string"?s.states[t]:t?s.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${s.id}`);const n={source:s,actions:!t||typeof t=="string"?[]:nt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...n,source:`#${s.id}`,target:e?[`#${e.id}`]:[]})};return n}function uo(s,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(be(e))return s.machine.getStateNodeById(e);const n=e[0]===cs;if(n&&!s.parent)return pe(s,e.slice(1));const i=n?s.key+e:e;if(s.parent)try{return pe(s.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${s.id}':
|
|
9
|
+
${r.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function _s(s){const t=gs(s.config.target);return t?{target:t.map(e=>typeof e=="string"?pe(s.parent,e):e)}:s.parent.initial}function mt(s){return s.type==="history"}function Rn(s){const t=As(s);for(const e of t)for(const n of ee(e,s))t.add(n);return t}function As(s){const t=new Set;function e(n){if(!t.has(n)){if(t.add(n),n.type==="compound")e(n.initial.target[0]);else if(n.type==="parallel")for(const i of Dt(n))e(i)}}return e(s),t}function Wt(s,t){if(be(t))return s.machine.getStateNodeById(t);if(!s.states)throw new Error(`Unable to retrieve child state '${t}' from '${s.id}'; no child states exist.`);const e=s.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${s.id}'`);return e}function pe(s,t){if(typeof t=="string"&&be(t))try{return s.machine.getStateNodeById(t)}catch{}const e=rn(t).slice();let n=s;for(;e.length;){const i=e.shift();if(!i.length)break;n=Wt(n,i)}return n}function ge(s,t){if(typeof t=="string"){const i=s.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${s.id}'`);return[s,i]}const e=Object.keys(t),n=e.map(i=>Wt(s,i)).filter(Boolean);return[s.machine.root,s].concat(n,e.reduce((i,r)=>{const o=Wt(s,r);if(!o)return i;const a=ge(o,t[r]);return i.concat(a)},[]))}function fo(s,t,e,n){const r=Wt(s,t).next(e,n);return!r||!r.length?s.next(e,n):r}function po(s,t,e,n){const i=Object.keys(t),r=Wt(s,i[0]),o=un(r,t[i[0]],e,n);return!o||!o.length?s.next(e,n):o}function go(s,t,e,n){const i=[];for(const r of Object.keys(t)){const o=t[r];if(!o)continue;const a=Wt(s,r),c=un(a,o,e,n);c&&i.push(...c)}return i.length?i:s.next(e,n)}function un(s,t,e,n){return typeof t=="string"?fo(s,t,e,n):Object.keys(t).length===1?po(s,t,e,n):go(s,t,e,n)}function mo(s){return Object.keys(s.states).map(t=>s.states[t]).filter(t=>t.type==="history")}function rt(s,t){let e=s;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function yo(s,t){const e=new Set(s),n=new Set(t);for(const i of e)if(n.has(i))return!0;for(const i of n)if(e.has(i))return!0;return!1}function bs(s,t,e){const n=new Set;for(const i of s){let r=!1;const o=new Set;for(const a of n)if(yo(Ue([i],t,e),Ue([a],t,e)))if(rt(i.source,a.source))o.add(a);else{r=!0;break}if(!r){for(const a of o)n.delete(a);n.add(i)}}return Array.from(n)}function wo(s){const[t,...e]=s;for(const n of ee(t,void 0))if(e.every(i=>rt(i,n)))return n}function dn(s,t){if(!s.target)return[];const e=new Set;for(const n of s.target)if(mt(n))if(t[n.id])for(const i of t[n.id])e.add(i);else for(const i of dn(_s(n),t))e.add(i);else e.add(n);return[...e]}function Is(s,t){const e=dn(s,t);if(!e)return;if(!s.reenter&&e.every(i=>i===s.source||rt(i,s.source)))return s.source;const n=wo(e.concat(s.source));if(n)return n;if(!s.reenter)return s.source.machine.root}function Ue(s,t,e){const n=new Set;for(const i of s)if(i.target?.length){const r=Is(i,e);i.reenter&&i.source===r&&n.add(r);for(const o of t)rt(o,r)&&n.add(o)}return[...n]}function Eo(s,t){if(s.length!==t.size)return!1;for(const e of s)if(!t.has(e))return!1;return!0}function je(s,t,e,n,i,r){if(!s.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=bs(s,o,a);let l=t;i||([l,a]=Io(l,n,e,c,o,a,r,e.actionExecutor)),l=Kt(l,n,e,c.flatMap(h=>h.actions),r,void 0),l=Ao(l,n,e,c,o,r,a,i);const u=[...o];l.status==="done"&&(l=Kt(l,n,e,u.sort((h,d)=>d.order-h.order).flatMap(h=>h.exit),r,void 0));try{return a===t.historyValue&&Eo(t._nodes,o)?l:_t(l,{_nodes:u,historyValue:a})}catch(h){throw h}}function _o(s,t,e,n,i){if(n.output===void 0)return;const r=Ke(i.id,i.output!==void 0&&i.parent?Le(i.output,s.context,t,e.self):void 0);return Le(n.output,s.context,r,e.self)}function Ao(s,t,e,n,i,r,o,a){let c=s;const l=new Set,u=new Set;bo(n,o,u,l),a&&u.add(s.machine.root);const h=new Set;for(const d of[...l].sort((g,p)=>g.order-p.order)){i.add(d);const g=[];g.push(...d.entry);for(const p of d.invoke)g.push(io(p.src,{...p,syncSnapshot:!!p.onSnapshot}));if(u.has(d)){const p=d.initial.actions;g.push(...p)}if(c=Kt(c,t,e,g,r,d.invoke.map(p=>p.id)),d.type==="final"){const p=d.parent;let E=p?.type==="parallel"?p:p?.parent,A=E||d;for(p?.type==="compound"&&r.push(Ke(p.id,d.output!==void 0?Le(d.output,c.context,t,e.self):void 0));E?.type==="parallel"&&!h.has(E)&&hn(i,E);)h.add(E),r.push(Ke(E.id)),A=E,E=E.parent;if(E)continue;c=_t(c,{status:"done",output:_o(c,t,e,c.machine.root,A)})}}return c}function bo(s,t,e,n){for(const i of s){const r=Is(i,t);for(const a of i.target||[])!mt(a)&&(i.source!==a||i.source!==r||i.reenter)&&(n.add(a),e.add(a)),kt(a,t,e,n);const o=dn(i,t);for(const a of o){const c=ee(a,r);r?.type==="parallel"&&c.push(r),Ns(n,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function kt(s,t,e,n){if(mt(s))if(t[s.id]){const i=t[s.id];for(const r of i)n.add(r),kt(r,t,e,n);for(const r of i)ve(r,s.parent,n,t,e)}else{const i=_s(s);for(const r of i.target)n.add(r),i===s.parent?.initial&&e.add(s.parent),kt(r,t,e,n);for(const r of i.target)ve(r,s.parent,n,t,e)}else if(s.type==="compound"){const[i]=s.initial.target;mt(i)||(n.add(i),e.add(i)),kt(i,t,e,n),ve(i,s,n,t,e)}else if(s.type==="parallel")for(const i of Dt(s).filter(r=>!mt(r)))[...n].some(r=>rt(r,i))||(mt(i)||(n.add(i),e.add(i)),kt(i,t,e,n))}function Ns(s,t,e,n,i){for(const r of n)if((!i||rt(r,i))&&s.add(r),r.type==="parallel")for(const o of Dt(r).filter(a=>!mt(a)))[...s].some(a=>rt(a,o))||(s.add(o),kt(o,t,e,s))}function ve(s,t,e,n,i){Ns(e,n,i,ee(s,t))}function Io(s,t,e,n,i,r,o,a){let c=s;const l=Ue(n,i,r);l.sort((h,d)=>d.order-h.order);let u;for(const h of l)for(const d of mo(h)){let g;d.history==="deep"?g=p=>ln(p)&&rt(p,h):g=p=>p.parent===h,u??={...r},u[d.id]=Array.from(i).filter(g)}for(const h of l)c=Kt(c,t,e,[...h.exit,...h.invoke.map(d=>ms(d.id))],o,void 0),i.delete(h);return[c,u||r]}function No(s,t){return s.implementations.actions[t]}function Ts(s,t,e,n,i,r){const{machine:o}=s;let a=s;for(const c of n){const l=typeof c=="function",u=l?c:No(o,typeof c=="string"?c:c.type),h={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(!u||!("resolve"in u)){e.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:h,params:d,exec:u});continue}const g=u,[p,E,A]=g.resolve(e,a,h,d,u,i);a=p,"retryResolve"in g&&r?.push([g,E]),"execute"in g&&e.actionExecutor({type:g.type,info:h,params:E,exec:g.execute.bind(null,e,E)}),A&&(a=Ts(a,t,e,A,i,r))}return a}function Kt(s,t,e,n,i,r){const o=r?[]:void 0,a=Ts(s,t,e,n,{internalQueue:i,deferredActorIds:r},o);return o?.forEach(([c,l])=>{c.retryResolve(e,a,l)}),a}function Se(s,t,e,n){let i=s;const r=[];function o(l,u,h){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:u,snapshot:l,_transitions:h}),r.push(l)}if(t.type===We)return i=_t(Mn(i,t,e),{status:"stopped"}),o(i,t,[]),{snapshot:i,microstates:r};let a=t;if(a.type!==hs){const l=a,u=Zr(l),h=xn(l,i);if(u&&!h.length)return i=_t(s,{status:"error",error:l.error}),o(i,l,[]),{snapshot:i,microstates:r};i=je(h,s,e,a,!1,n),o(i,l,h)}let c=!0;for(;i.status==="active";){let l=c?To(i,a):[];const u=l.length?i:void 0;if(!l.length){if(!n.length)break;a=n.shift(),l=xn(a,i)}i=je(l,i,e,a,!1,n),c=i!==u,o(i,a,l)}return i.status!=="active"&&Mn(i,a,e),{snapshot:i,microstates:r}}function Mn(s,t,e){return Kt(s,t,e,Object.values(s.children).map(n=>ms(n)),[],void 0)}function xn(s,t){return t.machine.getTransitionData(t,s)}function To(s,t){const e=new Set,n=s._nodes.filter(ln);for(const i of n)t:for(const r of[i].concat(ee(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||cn(o.guard,s.context,t,s)){e.add(o);break t}}return bs(Array.from(e),new Set(s._nodes),s.historyValue)}function vo(s,t){const e=fe(ge(s,t));return Es(s,[...e])}function So(s){return!!s&&typeof s=="object"&&"machine"in s&&"value"in s}const Oo=function(t){return ds(t,this.value)},ko=function(t){return this.tags.has(t)},Co=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(n=>n.target!==void 0||n.actions.length)},Ro=function(){const{_nodes:t,tags:e,machine:n,getMeta:i,toJSON:r,can:o,hasTag:a,matches:c,...l}=this;return{...l,tags:Array.from(e)}},Mo=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function ae(s,t){return{status:s.status,output:s.output,error:s.error,machine:t,context:s.context,_nodes:s._nodes,value:Es(t.root,s._nodes),tags:new Set(s._nodes.flatMap(e=>e.tags)),children:s.children,historyValue:s.historyValue||{},matches:Oo,hasTag:ko,can:Co,getMeta:Mo,toJSON:Ro}}function _t(s,t={}){return ae({...s,...t},s.machine)}function xo(s){if(typeof s!="object"||s===null)return{};const t={};for(const e in s){const n=s[e];Array.isArray(n)&&(t[e]=n.map(i=>({id:i.id})))}return t}function $o(s,t){const{_nodes:e,tags:n,machine:i,children:r,context:o,can:a,hasTag:c,matches:l,getMeta:u,toJSON:h,...d}=s,g={};for(const E in r){const A=r[E];g[E]={snapshot:A.getPersistedSnapshot(t),src:A.src,systemId:A.systemId,syncSnapshot:A._syncSnapshot}}return{...d,context:vs(o),children:g,historyValue:xo(d.historyValue)}}function vs(s){let t;for(const e in s){const n=s[e];if(n&&typeof n=="object")if("sessionId"in n&&"send"in n&&"ref"in n)t??=Array.isArray(s)?s.slice():{...s},t[e]={xstate$$type:an,id:n.id};else{const i=vs(n);i!==n&&(t??=Array.isArray(s)?s.slice():{...s},t[e]=i)}}return t??s}function Po(s,t,e,n,{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,n):i;let u;if(typeof o=="string"){const h=c&&c[o];u=typeof h=="function"?h(e,n):h}else u=typeof o=="function"?o(e,n):o;return typeof u!="number"&&a.push(l),[t,{event:l,id:r,delay:u},void 0]}function Ho(s,t){const{event:e,delay:n,id:i}=t;if(typeof n=="number"){s.defer(()=>{const r=s.self;s.system.scheduler.schedule(r,r,e,n,i)});return}}function Bo(s,t){function e(n,i){}return e.type="xstate.raise",e.event=s,e.id=t?.id,e.delay=t?.delay,e.resolve=Po,e.execute=Ho,e}function Do(s,{machine:t,context:e},n,i){const r=(o,a)=>{if(typeof o=="string"){const c=on(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=Bt(c,{id:a?.id,parent:s.self,syncSnapshot:a?.syncSnapshot,input:typeof a?.input=="function"?a.input({context:e,event:n,self:s.self}):a?.input,src:o,systemId:a?.systemId});return i[l.id]=l,l}else return Bt(o,{id:a?.id,parent:s.self,syncSnapshot:a?.syncSnapshot,input:a?.input,src:o,systemId:a?.systemId})};return(o,a)=>{const c=r(o,a);return i[c.id]=c,s.defer(()=>{c._processingStatus!==D.Stopped&&c.start()}),c}}function Wo(s,t,e,n,{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:Do(s,t,e.event,r),self:s.self,system:s.system};let a={};if(typeof i=="function")a=i(o,n);else for(const l of Object.keys(i)){const u=i[l];a[l]=typeof u=="function"?u(o,n):u}const c=Object.assign({},t.context,a);return[_t(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children}),void 0,void 0]}function Ko(s){function t(e,n){}return t.type="xstate.assign",t.assignment=s,t.resolve=Wo,t}const $n=new WeakMap;function vt(s,t,e){let n=$n.get(s);return n?t in n||(n[t]=e()):(n={[t]:e()},$n.set(s,n)),n[t]}const Lo={},jt=s=>typeof s=="string"?{type:s}:typeof s=="function"?"resolve"in s?{type:s.type}:{type:s.name}:s;class me{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(cs),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?On(this.config.states,(n,i)=>new me(n,{_parent:this,_key:i,_machine:this.machine})):Lo,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=nt(this.config.entry).slice(),this.exit=nt(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=nt(t.tags).slice()}_initialize(){this.transitions=lo(this),this.config.always&&(this.always=St(this.config.always).map(t=>pt(this,ls,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(jt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(jt),eventType:null})}:void 0,history:this.history,states:On(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(jt)})),entry:this.entry.map(jt),exit:this.exit.map(jt),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 vt(this,"invoke",()=>nt(this.config.invoke).map((t,e)=>{const{src:n,systemId:i}=t,r=t.id??kn(this.id,e),o=typeof n=="string"?n:`xstate.invoke.${kn(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 vt(this,"on",()=>[...this.transitions].flatMap(([e,n])=>n.map(i=>[e,i])).reduce((e,[n,i])=>(e[n]=e[n]||[],e[n].push(i),e),{}))}get after(){return vt(this,"delayedTransitions",()=>co(this))}get initial(){return vt(this,"initial",()=>ho(this,this.config.initial))}next(t,e){const n=e.type,i=[];let r;const o=vt(this,`candidates-${n}`,()=>ao(this,n));for(const a of o){const{guard:c}=a,l=t.context;let u=!1;try{u=!c||cn(c,l,e,t)}catch(h){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 '${n}' in state node '${this.id}':
|
|
10
|
+
${h.message}`)}if(u){i.push(...a.actions),r=a;break}}return r?[r]:void 0}get events(){return vt(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const n of Object.keys(t)){const i=t[n];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(n=>!(!n.target&&!n.actions.length&&!n.reenter))));return Array.from(t)}}const zo="#";class fn{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?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards: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 me(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:n,actors:i,delays:r}=this.implementations;return new fn(this.config,{actions:{...e,...t.actions},guards:{...n,...t.guards},actors:{...i,...t.actors},delays:{...r,...t.delays}})}resolveState(t){const e=vo(this.root,t.value),n=fe(ge(this.root,e));return ae({_nodes:[...n],context:t.context||{},children:{},status:hn(n,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,n){return Se(t,e,n,[]).snapshot}microstep(t,e,n){return Se(t,e,n,[]).microstates}getTransitionData(t,e){return un(this.root,t.value,t,e)||[]}getPreInitialState(t,e,n){const{context:i}=this.config,r=ae({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?Kt(r,e,t,[Ko(({spawn:a,event:c,self:l})=>i({spawn:a,input:c.input,self:l}))],n,void 0):r}getInitialSnapshot(t,e){const n=us(e),i=[],r=this.getPreInitialState(t,n,i),o=je([{target:[...As(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],r,t,n,!0,i),{snapshot:a}=Se(o,n,t,i);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=rn(t),n=e.slice(1),i=be(e[0])?e[0].slice(zo.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 pe(r,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return $o(t,e)}restoreSnapshot(t,e){const n={},i=t.children;Object.keys(i).forEach(h=>{const d=i[h],g=d.snapshot,p=d.src,E=typeof p=="string"?on(this,p):p;if(!E)return;const A=Bt(E,{id:h,parent:e.self,syncSnapshot:d.syncSnapshot,snapshot:g,src:p,systemId:d.systemId});n[h]=A});function r(h,d){if(d instanceof me)return d;try{return h.machine.getStateNodeById(d.id)}catch{}}function o(h,d){if(!d||typeof d!="object")return{};const g={};for(const p in d){const E=d[p];for(const A of E){const I=r(h,A);I&&(g[p]??=[],g[p].push(I))}}return g}const a=o(this.root,t.historyValue),c=ae({...t,children:n,_nodes:Array.from(fe(ge(this.root,t.value))),historyValue:a},this),l=new Set;function u(h,d){if(!l.has(h)){l.add(h);for(const g in h){const p=h[g];if(p&&typeof p=="object"){if("xstate$$type"in p&&p.xstate$$type===an){h[g]=d[p.id];continue}u(p,d)}}}}return u(c.context,n),c}}function Uo(s,t){return new fn(s,t)}const re=s=>s===!1?!1:s.map(t=>t.serialize()),jo=s=>s===!1?!1:s.serialize(),Fo=s=>s===!1?!1:s.map(t=>({tile:t.tile.toString(),effectiveTiles:t.effectiveTiles.map(e=>e.toString()),shanten:t.shanten})),oe=s=>s===!1?!1:de(s),Fe=s=>Uo({id:"Untitled",initial:"distribute",context:{currentWind:_.E,oneShotMap:P(!1),missingMap:P(!1),controller:s,genEventID:Ss()},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:`可能なアクションとその詳細を通知\\
|
|
11
11
|
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:`可能なアクションとその詳細を通知\\
|
|
12
12
|
CHI/PON の場合は鳴ける組み合わせの一覧`}}},tsumo:{exit:[{type:"notify_tsumo"},{type:"notify_end"}],type:"final"},waiting_reach_acceptance:{on:{REACH_ACCEPT:{target:"reached"},RON:{target:"roned",guard:{type:"canWin"}}},description:"リーチに対するアクションは RON か ACCEPT のみである"},waiting_user_event_after_discarded:{description:`最大 4人から choice に対するレスポンスを待つ\\
|
|
13
13
|
ユーザからではなく、controller が優先順位を考慮して遷移させる必要がある\\
|
|
14
|
-
通知する choice がない場合、controller が\\*で遷移させる`,on:{RON:{target:"roned",guard:"canWin"},PON:{target:"poned",guard:"canPon"},CHI:{target:"chied",guard:"canChi"},DAI_KAN:{target:"dai_kaned"},"*":{target:"wildcard_after_discarded"}}},reached:{on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"}}},entry:{type:"notify_reach_accepted"}},roned:{exit:[{type:"notify_ron"},{type:"notify_end"}],type:"final"},poned:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called"}}},entry:[{type:"notify_call"},{type:"disable_none_shot"}]},chied:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called",params:{action:"chi"}}}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},wildcard_after_discarded:{exit:[],always:[{target:"drawn_game",guard:"cannotContinue"},{target:"drawn",actions:[{type:"updateNextWind"}]}]},waiting_discard_event:{description:"鳴いたユーザからの DISCARD イベントを待つ",on:{DISCARD:{target:"discarded"}}},dai_kaned:{on:{NEXT:{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},an_sho_kaned:{always:{target:"waiting_chankan_event"},entry:[{type:"notify_call"},{type:"disable_one_shot"},{type:"notify_new_dora_if_needed"},{type:"notify_choice_for_chankan"}]},waiting_chankan_event:{description:"チャンカンを待つ",on:{"*":{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]},RON:{target:"roned",guard:{type:"canWin"}}}},drawn_game:{exit:{type:"notify_end",params:{}},type:"final"}},types:{events:{},context:{}}},{actions:{updateNextWind:({context:t,event:e})=>{const n=t.currentWind;t.currentWind=yt(n)},notify_distribution:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.initialHands();for(const r of Object.values(_)){const o=$("_____________");o[r]=i[r].toString();const a={id:n,type:"DISTRIBUTE",hands:o,wind:r,doraIndicator:t.controller.wall.doraIndicators[0].toString(),sticks:t.controller.placeManager.sticks,round:t.controller.placeManager.round,players:t.controller.playerIDs,places:t.controller.placeManager.playerMap,scores:t.controller.scoreManager.summary};t.controller.emit(a)}t.controller.next()},notify_choice_after_drawn:({context:t,event:e},n)=>{const i=t.currentWind,r=t.controller.hand(i).drawn,o=t.genEventID(),a={id:o,type:"CHOICE_AFTER_DRAWN",wind:i,drawerInfo:{wind:i,tile:r.toString()},choices:{TSUMO:oe(t.controller.doWin(i,r,{oneShot:t.oneShotMap[i],replacementWin:n?.replacementWin})),REACH:Go(t.controller.doReach(i)),AN_KAN:re(t.controller.doAnKan(i)),SHO_KAN:re(t.controller.doShoKan(i)),DISCARD:t.controller.doDiscard(i).map(c=>c.toString()),DRAWN_GAME_BY_NINE_ORPHANS:t.controller.canDrawnGame(i)}};t.controller.emit(a),t.controller.pollReplies(o,[i])},notify_choice_after_discarded:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:m.HORIZONTAL});for(const o of Object.values(_)){const a={id:n,type:"CHOICE_AFTER_DISCARDED",wind:o,discarterInfo:{wind:i.w,tile:i.t.toString()},choices:{RON:oe(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:re(t.controller.doPon(o,i.w,r)),CHI:re(t.controller.doChi(o,i.w,r)),DAI_KAN:jo(t.controller.doDaiKan(o,i.w,r))}};a.choices.RON&&(t.missingMap[o]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(_))},notify_choice_after_called:({context:t,event:e},n)=>{const i=t.genEventID(),r=t.currentWind;let o=t.controller.doDiscard(r);const a=t.controller.hand(t.currentWind).called.at(-1);(a instanceof J||a instanceof X)&&(o=t.controller.doDiscard(r,a));const c={id:i,type:"CHOICE_AFTER_CALLED",wind:r,choices:{DISCARD:o.map(l=>l.toString())}};t.controller.emit(c),t.controller.pollReplies(i,[r])},notify_choice_for_reach_acceptance:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:m.HORIZONTAL});for(const o of Object.values(_)){const a={id:n,type:"CHOICE_FOR_REACH_ACCEPTANCE",wind:o,reacherInfo:{wind:i.w,tile:r.toString()},choices:{RON:oe(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]}))}};t.controller.emit(a)}t.controller.pollReplies(n,Object.values(_))},notify_choice_for_chankan:({context:t,event:e})=>{b(e.type=="SHO_KAN"||e.type=="AN_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.block.tiles[0].clone({remove:m.HORIZONTAL});for(const r of Object.values(_)){const o=t.controller.doWin(r,e.block.tiles[0].clone({remove:m.HORIZONTAL}),{discardedBy:e.iam,quadWin:!0,oneShot:t.oneShotMap[r],missingRon:t.missingMap[e.iam]}),a={id:n,type:"CHOICE_FOR_CHAN_KAN",wind:r,callerInfo:{wind:e.iam,tile:i.toString()},choices:{RON:e.type=="SHO_KAN"?oe(o):!1}};a.choices.RON&&(t.missingMap[r]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(_))},notify_call:({context:t,event:e})=>{b(e.type=="CHI"||e.type=="PON"||e.type=="DAI_KAN"||e.type=="AN_KAN"||e.type=="SHO_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam;t.currentWind=i;for(const r of Object.values(_)){const o={id:n,type:e.type,iam:i,wind:r,block:e.block.serialize()};t.controller.emit(o)}t.controller.next()},notify_discard:({context:t,event:e})=>{b(e.type=="DISCARD",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind,r=e.tile;for(const o of Object.values(_)){const a={id:n,type:"DISCARD",iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}t.controller.next()},notify_draw:({context:t,event:e},n)=>{const i=t.genEventID(),r=n?.action;let o;r=="kan"?o=t.controller.wall.kan():o=t.controller.wall.draw();const a=t.currentWind;t.controller.hand(a).reached||(t.missingMap[a]=!1);for(const c of Object.values(_)){let l=new y(f.BACK,0,[m.TSUMO]);c==a&&(l=o);const u={id:i,type:"DRAW",subType:r,iam:a,wind:c,tile:l.toString()};t.controller.emit(u)}t.controller.next()},notify_ron:({context:t,event:e})=>{b(e.type=="RON");const n=t.genEventID(),i=e.iam;for(const r of Object.values(_)){const o={id:n,type:e.type,iam:i,wind:r,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:de(e.ret)};t.controller.emit(o)}},notify_tsumo:({context:t,event:e})=>{b(e.type=="TSUMO",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind;for(const r of Object.values(_)){const o={id:n,type:e.type,iam:i,wind:r,lastTile:t.controller.hand(i).drawn.toString(),ret:de(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{b(e.type=="REACH",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam,r=e.tile.clone({add:m.HORIZONTAL});t.oneShotMap[i]=!0;for(const o of Object.values(_)){const a={id:n,type:e.type,iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}},notify_reach_accepted:({context:t,event:e})=>{b(e.type=="REACH_ACCEPT");const n=t.genEventID();for(const i of Object.values(_)){const r={id:n,type:"REACH_ACCEPTED",reacherInfo:{wind:e.reacherInfo.wind,tile:e.reacherInfo.tile.toString()},wind:i};t.controller.emit(r)}t.controller.next()},notify_new_dora_if_needed:({context:t,event:e})=>{const n=t.genEventID();if(e.type=="AN_KAN"){const i=t.controller.wall.openDoraIndicator();for(const r of Object.values(_)){const o={id:n,type:"NEW_DORA",wind:r,doraIndicator:i.toString()};t.controller.emit(o)}}e.type=="SHO_KAN"},disable_one_shot:({context:t,event:e})=>{for(const n of Object.values(_))t.oneShotMap[n]=!1},disable_one_shot_for_me:({context:t,event:e})=>{t.oneShotMap[t.currentWind]=!1},notify_end:({context:t,event:e})=>{const n=t.genEventID(),i=$("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){i[e.iam]=t.controller.hand(e.iam).toString();for(const r of Object.values(_)){const o={id:n,type:"END_GAME",subType:"NINE_TILES",wind:r,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:$(0),hands:i};t.controller.emit(o)}}else if(e.type=="RON"||e.type=="TSUMO"){const r=e.iam==_.E,o=t.controller.finalResult(e.ret,e.iam);for(const a of Object.values(_)){i[e.iam]=t.controller.hand(e.iam).toString();const c={id:n,type:"END_GAME",subType:"WIN_GAME",wind:a,shouldContinue:r,sticks:{reach:0,dead:0},scores:t.controller.scoreManager.summary,deltas:o.deltas,hands:i};t.controller.emit(c)}}else if(!t.controller.wall.canKan||t.controller.river.cannotContinue()){const r=t.controller.wall.canKan?"FOUR_WIND":"FOUR_KAN";for(const o of Object.values(_)){const a={id:n,type:"END_GAME",subType:r,wind:o,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:$(0),hands:$("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const r=[];for(const l of Object.values(_)){const u=t.controller.hand(l);new te(u).calc()==0&&(r.push(l),i[l]=u.toString())}const o=r.length==0||r.length==4,a=$(0);for(const l of Object.values(_))r.includes(l)?a[l]+=o?0:3e3/r.length:a[l]-=o?0:3e3/(4-r.length);const c=r.length==4||a[_.E]>0;for(const l of Object.values(_)){const u={id:n,type:"END_GAME",subType:"DRAWN_GAME",wind:l,shouldContinue:c,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:a,hands:i};t.controller.emit(u)}}}}},actors:{},guards:{canChi:({context:t,event:e},n)=>e.type=="CHI"?!!t.controller.doChi(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canChi receive ${e.type}`),!1),canPon:({context:t,event:e},n)=>e.type=="PON"?!!t.controller.doPon(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canPon receive ${e.type}`),!1),canWin:({context:t,event:e},n)=>e.type=="TSUMO"||e.type=="RON"?!0:(console.error(`guards.canWin receive ${e.type}`),!1),canReach:({context:t,event:e},n)=>e.type=="REACH"?!!t.controller.doReach(e.iam):(console.error(`guards.canReach receive ${e.type}`),!1),cannotContinue:({context:t,event:e},n)=>!t.controller.wall.canDraw||!t.controller.wall.canKan||t.controller.river.cannotContinue()},delays:{}});function Ss(s=0){let t=s;return()=>(t++).toString()}class Et{walls={replacement:[],dead:[],doraIndicators:[],hiddenDoraIndicators:[],drawable:[]};backup;openedDoraCount=1;constructor(t){this.init(t),this.backup=Et.clone(this.walls)}kan(){if(this.walls.replacement.length==0)throw new Error("exceeded maximum kan");const t=this.walls.replacement.pop();return this.walls.drawable.pop(),y.from(t)}draw(){if(!this.walls.drawable)throw new Error("cannot draw any more");return y.from(this.walls.drawable.pop())}openDoraIndicator(){if(this.openedDoraCount>=4)throw new Error("exceeded maximum open dora");return this.openedDoraCount++,y.from(this.walls.doraIndicators[this.openedDoraCount-1])}get doraIndicators(){return this.walls.doraIndicators.slice(0,this.openedDoraCount).map(y.from)}get hiddenDoraIndicators(){return this.walls.hiddenDoraIndicators.slice(0,this.openedDoraCount).map(y.from)}get canKan(){return this.walls.replacement.length>0}get canDraw(){return this.walls.drawable.length>0}initialHands(){const t=$("");for(let e=0;e<3;e++)for(const n of Object.values(_))for(let i=0;i<4;i++)t[n]+=this.draw().toString();for(const e of Object.values(_))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=Et.clone(t);return}else{for(let e of Object.values(f)){if(e==f.BACK)continue;const n=e==f.Z?[1,2,3,4,5,6,7]:[1,2,3,4,5,6,7,8,9];for(let i=0;i<4;i++)for(let r of n){let o=new y(e,r);e!=f.Z&&i==3&&r==5&&(o=o.clone({add:m.RED})),this.walls.drawable.push(o.toString())}}nn(this.walls.drawable)}for(let e=0;e<14;e++)this.walls.dead.push(this.walls.drawable.pop());for(let e=0;e<4;e++)this.walls.hiddenDoraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.doraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.replacement.push(this.walls.dead.pop())}export(){return this.backup}static clone(t){return{drawable:t.drawable.concat(),dead:t.dead.concat(),doraIndicators:t.doraIndicators.concat(),hiddenDoraIndicators:t.hiddenDoraIndicators.concat(),replacement:t.replacement.concat()}}}class ne{wall=new Et;playerIDs;actor=Bt(Ge(this),{});observer;handlers={};mailBox={};histories=[];debugMode;constructor(t,e){this.debugMode=e?.debug??!1,this.handlers=Object.fromEntries(t.map(o=>[o.id,o.handler])),this.playerIDs=t.map(o=>o.id),t.forEach(o=>o.handler.on(a=>this.enqueue(a)));const n=os();this.observer=new Os(n),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const i=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new Jt(i);const r=e?.shuffle==!1?this.playerIDs:nn([...this.playerIDs]);this.observer.placeManager=new Xt({[r[0]]:_.E,[r[1]]:_.S,[r[2]]:_.W,[r[3]]:_.N})}boardParams(t){let n=this.hand(t).reached?1:void 0;if(n){const i=this.river.discards(t);n=i.length==0||i.length==1&&i[0].t.has(m.HORIZONTAL)?2:1}return{doraIndicators:this.observer.doraIndicators,round:this.placeManager.round,myWind:t,sticks:this.observer.placeManager.sticks,reached:n}}hand(t){return this.observer.hand(t)}get placeManager(){return this.observer.placeManager}get scoreManager(){return this.observer.scoreManager}get river(){return this.observer.river}next(t){(!this.debugMode||t)&&this.actor.send({type:"NEXT"})}emit(t){const e=this.observer.placeManager.playerID(t.wind);this.handlers[e].emit(t);const n=t.iam;t.wind==n?this.observer.eventHandler.emit(t):n==null&&(!this.observer.applied[t.id]||t.type=="DISTRIBUTE")&&(this.observer.eventHandler.emit(t),this.observer.applied[t.id]=!0)}enqueue(t){this.mailBox[t.id]==null&&(this.mailBox[t.id]=[]),this.mailBox[t.id].push(t)}pollReplies(t,e){const n=this.mailBox[t];if(n==null)throw new Error(`not enqueued ${t} at ${this.actor.getSnapshot().value}`);if(n.length!=e.length)throw new Error(`${t}: num of event: got: ${e.length}, want: ${n.length}`);if(e.length==0){console.warn("no events to handle");return}const i=n[0];if(i.type=="CHOICE_AFTER_DISCARDED"){const r=ns(n);if(r.events.length==0){this.actor.send({type:""});return}const o=r.events[0];switch(r.type){case"RON":b(o.choices.RON,"ron choice is none"),this.actor.send({type:r.type,iam:o.wind,ret:Gt(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:y.from(o.discarterInfo.tile)}});break;case"DAI_KAN":b(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:r.type,iam:o.wind,block:q.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[r.type];b(a,`${r.type} choice is none`),b(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const c=X.deserialize(a[0]);this.actor.send({type:r.type,iam:o.wind,block:c})}}else if(i.type=="CHOICE_AFTER_DRAWN"){const r=ss(n);b(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const o=r.events[0],a=o.wind;switch(r.type){case"TSUMO":b(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:r.type,ret:Gt(o.choices.TSUMO),lastTile:y.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[r.type];b(c,`${r.type} candidates is none`),this.actor.send({type:"REACH",tile:y.from(c[0].tile),iam:a});break;case"DISCARD":const l=o.choices[r.type];b(l,`${r.type} choice is none`),this.actor.send({type:r.type,tile:y.from(l[0]).clone({remove:m.TSUMO}),iam:a});break;case"AN_KAN":{const u=o.choices[r.type];b(u,`${r.type} choice is none`),this.actor.send({type:r.type,block:R.from(u[0].tiles),iam:a});break}case"SHO_KAN":{const u=o.choices[r.type];b(u,`${r.type} choice is none`),this.actor.send({type:r.type,block:K.from(u[0].tiles),iam:a});break}case"DRAWN_GAME_BY_NINE_ORPHANS":this.actor.send({type:"DRAWN_GAME_BY_NINE_ORPHANS",iam:a});break}}else if(i.type=="CHOICE_AFTER_CALLED"){b(i.choices.DISCARD,`discard candidate tile is none: ${JSON.stringify(i,null,2)} ${this.hand(i.wind).toString()}`);const r=i.wind,o=y.from(i.choices.DISCARD[0]);this.actor.send({type:"DISCARD",tile:o,iam:r})}else if(i.type=="CHOICE_FOR_REACH_ACCEPTANCE"){const r=n.filter(a=>(b(a.type=="CHOICE_FOR_REACH_ACCEPTANCE"),a.choices.RON!==!1));if(r.length==0){this.actor.send({type:"REACH_ACCEPT",reacherInfo:{tile:y.from(i.reacherInfo.tile),wind:i.reacherInfo.wind}});return}const o=r[0];this.actor.send({type:"RON",iam:o.wind,ret:Gt(o.choices.RON),targetInfo:{wind:o.reacherInfo.wind,tile:y.from(o.reacherInfo.tile)}});return}else if(i.type=="CHOICE_FOR_CHAN_KAN"){const r=n.filter(a=>a.choices.RON!==!1);if(r.length==0){this.actor.send({type:""});return}const o=r[0];b(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:Gt(o.choices.RON),quadWin:!0,targetInfo:{wind:o.callerInfo.wind,tile:y.from(o.callerInfo.tile)}});return}else console.warn(`controller found unexpected event: ${i.type}`)}export(){return this.histories.concat()}static load(t){const e=t.choiceEvents,n=Object.keys(t.players),i={emit:a=>{},on:a=>{}},r=n.map(a=>({id:a,handler:i})),o=new ne(r);return o.playerIDs=n,o.mailBox=e,o.observer.placeManager=new Xt(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new Jt(t.scores),o.wall=new Et(t.wall),o}start(){this.actor.subscribe(n=>{console.debug("State:",n.value)});const t={scores:this.scoreManager.summary,round:this.placeManager.round,players:this.placeManager.playerMap,wall:this.wall.export(),choiceEvents:this.mailBox,sticks:this.placeManager.sticks};this.actor.start(),this.histories.push(t);const e=this.actor.getSnapshot().status;if(e!="done")throw new Error(`unexpected state ${this.actor.getSnapshot().value}(${e})`)}startGame(){for(;console.debug(`start========${this.placeManager.round}=============`),this.start(),this.wall=new Et,this.observer.applied={},this.mailBox={},this.actor=Bt(Ge(this)),!this.placeManager.is(O.W1););}finalResult(t,e){const n=this.hand(e),i=n.reached?this.wall.hiddenDoraIndicators:void 0,r=new He(n,{...t.boardContext,sticks:this.placeManager.sticks,hiddenDoraIndicators:i}).calc(t.hand);return b(r),r}doWin(t,e,n){if(e==null)return!1;let i=this.hand(t);const r=this.boardParams(t);if(i.drawn==null){if(n==null)throw new Error("should ron but params == null");if(n.discardedBy==t||n.missingRon)return!1;i=i.clone(),r.ronWind=n.discardedBy,r.finalDiscardWin=!this.wall.canDraw,r.quadWin=n.quadWin,i.inc([e])}else r.finalWallWin=!this.wall.canDraw,r.replacementWin=n?.replacementWin;r.oneShotWin=n?.oneShot;const o=new ts(i),a=new He(i,r),c=o.calc(e),l=a.calc(...c);if(!l||l.yakus.length==0)return!1;if(i.draw==null){const u=Ht.getEffectiveTiles(this.hand(t)).effectiveTiles;if(this.river.discards(t).some(h=>u.some(d=>d.equals(h.t))))return!1}return l}doPon(t,e,n){if(n==null||t==e)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3||i.get(n.t,n.n)<2)return!1;const r=n.clone({removeAll:!0}),o=ke(t,e,w.PON),a=[],c=new X([r,r,r]).clone({replace:{idx:o,tile:n.clone({add:m.HORIZONTAL})}});let l=c;k(n)&&n.has(m.RED)&&(l=c.clone({replace:{idx:o,tile:r.clone({add:[m.RED,m.HORIZONTAL]})}}));const u=o%2+1;if(k(n)&&i.get(n.t,0)>0&&(l=c.clone({replace:{idx:u,tile:r.clone({add:m.RED})}})),a.push(l),k(r)&&i.get(r.t,5)==3){const h=c.clone({replace:{idx:u,tile:r}});a.push(h)}return a}doChi(t,e,n){if(n==null||!n.isNum()||yt(e)!=t)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3)return!1;const r=n.clone({remove:m.TSUMO,add:[m.HORIZONTAL]}),o=[];r.n-2>=1&&i.get(n.t,r.n-2)>0&&i.get(n.t,r.n-1)>0&&o.push(new J([r,new y(n.t,r.n-1),new y(n.t,r.n-2)])),r.n+2<=9&&i.get(n.t,r.n+1)>0&&i.get(n.t,r.n+2)>0&&o.push(new J([r,new y(n.t,r.n+1),new y(n.t,r.n+2)])),r.n-1>=1&&r.n+1<=9&&i.get(n.t,r.n-1)>0&&i.get(n.t,r.n+1)>0&&o.push(new J([r,new y(n.t,r.n-1),new y(n.t,r.n+1)]));for(let d=0;d<o.length;d++){const g=o[d],p=this.cannotDiscardTile(g),E=[];for(const v of p){const M=i.get(v.t,v.n);for(let Tt=0;Tt<M;Tt++)E.push(v.clone({remove:m.RED}))}const A=i.dec([...E,g.tiles[1],g.tiles[2]]),T=i.hands.length==0;i.inc(A),T&&o.splice(d,1)}if(o.length==0)return!1;const h=i.get(n.t,0)>0?this.redPattern(o):[];return h.length>0&&i.get(n.t,5)==1?h:[...o,...h]}redPattern(t){return t.length==0?[]:t.filter(n=>k(n.tiles[1])||k(n.tiles[2])).map(n=>{if(k(n.tiles[1])){const i=n.tiles[1].clone({add:m.RED});return n.clone({replace:{idx:1,tile:i}})}else if(k(n.tiles[2])){const i=n.tiles[2].clone({add:m.RED});return n.clone({replace:{idx:2,tile:i}})}}).filter(n=>n!=null)}doReach(t){const e=this.hand(t);return e.reached||!e.menzen||new te(e).calc()>0?!1:Ht.calcEffectiveTiles(e,e.hands)}doDiscard(t,e){if(this.hand(t).reached)return[this.hand(t).drawn];const n=this.hand(t).hands;if(e==null)return n;if(e instanceof X)return n.filter(o=>!o.equals(e.tiles[0]));const i=this.cannotDiscardTile(e),r=n.filter(o=>!i.some(a=>o.equals(a)));return b(r.length>0,`no tiles to discard. hand: ${this.hand(t)}, suji: ${i}, block-chi: ${e}`),r}cannotDiscardTile(t){const e=t.tiles[0],n=t.tiles[1].n;return n!=1&&e.n-2==n?[new y(e.t,e.n-3),e]:n!=8&&e.n+1==n?[new y(e.t,e.n+3),e]:[e]}doAnKan(t){const e=this.hand(t),n=[];if(e.reached)return!1;for(const[i,r]of z())if(e.get(i,r)==4){const o=new y(i,r),a=[o,o,o,o];k(o)&&(a[1]=o.clone({add:m.RED})),n.push(new R(a))}if(n.length==0)return!1;for(const i of n)b(i.tiles.filter(r=>r.has(m.HORIZONTAL)).length==0,`h op ${i.toString()}`);return n}doShoKan(t){const e=this.hand(t);if(e.reached)return!1;const n=e.called.filter(r=>r instanceof X);if(n.length==0)return!1;const i=[];for(const r of n){const o=r.tiles[0].clone({removeAll:!0,add:m.HORIZONTAL});if(e.get(o.t,o.n)==1){const a=k(o)&&e.get(o.t,0)>0?o.clone({add:m.RED}):o;i.push(new K([...r.tiles,a]))}}if(i.length==0)return!1;for(const r of i)b(r.tiles.filter(o=>o.has(m.HORIZONTAL)).length==2,`h op ${r.toString()}`);return i}doDaiKan(t,e,n){const i=this.hand(t);if(i.reached||t==e)return!1;const r=n.clone({removeAll:!0});if(i.get(r.t,r.n)!=3)return!1;const o=ke(t,e,w.DAI_KAN);let a=new q([r,r,r,r]).clone({replace:{idx:o,tile:r.clone({add:m.HORIZONTAL})}});if(k(n)&&n.has(m.RED))a=a.clone({replace:{idx:o,tile:r.clone({add:[m.HORIZONTAL,m.RED]})}});else if(k(n)&&!n.has(m.RED)){b(i.get(n.t,0)>0,`hand does not have red tile: ${i.toString()}`);const c=o%3+1;a=a.clone({replace:{idx:c,tile:r.clone({add:m.RED})}})}return b(a.tiles.filter(c=>c.has(m.HORIZONTAL)).length==1,`h op ${a.toString()}`),a}canDrawnGame(t){if(this.river.discards(t).length!=0)return!1;const e=this.hand(t);let n=0;for(const i of Object.values(f)){if(i==f.BACK)continue;const r=i==f.Z?Pt:Y;for(const o of r)e.get(i,o)>0&&n++}return n>=9}initialHands(){return this.wall.initialHands()}}class At extends Ae{isBackHand(){for(const t of Object.values(f))if(t!=f.BACK&&this.sum(t)>0)return!1;return this.sum(f.BACK)>0}clone(){const t=new At(this.toString());return t.data.reached=this.data.reached,t}dec(t){return this.isBackHand()?(super.dec(t.map(()=>new y(f.BACK,0))),[...t]):super.dec(t)}}class pn{id;river=new sn;placeManager=new Xt({});scoreManager=new Jt({});hands=$(new At(""));counter=new as;doraIndicators=[];eventHandler;constructor(t,e){this.id=t,this.eventHandler=e}hand(t){return this.hands[t]}handleEvent(t){switch(t.type){case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DISCARDED":case"CHOICE_AFTER_DRAWN":case"CHOICE_FOR_CHAN_KAN":case"CHOICE_FOR_REACH_ACCEPTANCE":break;case"DISTRIBUTE":this.counter.reset();const e=y.from(t.doraIndicator);this.setHands(t),this.placeManager=new Xt(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new Jt(structuredClone(t.scores)),this.doraIndicators=[e],this.counter.dec(e);for(const i of Object.values(_))i==t.wind&&this.counter.dec(...this.hand(i).hands);break;case"DRAW":{const i=y.from(t.tile);this.hands[t.iam].draw(i),this.counter.dec(i);break}case"DISCARD":{const i=y.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(_))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"PON":case"CHI":case"DAI_KAN":{const i=I.deserialize(t.block);this.hands[t.iam].call(i),this.river.markCalled(),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(m.HORIZONTAL)));break}case"SHO_KAN":{const i=K.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(i.tiles.filter(r=>r.has(m.HORIZONTAL))[0]);break}case"AN_KAN":{const i=R.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(m.HORIZONTAL)));break}case"REACH":{this.hands[t.iam].reach();const i=y.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(_))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"REACH_ACCEPTED":const n=this.placeManager.playerID(t.reacherInfo.wind);this.scoreManager.reach(n),this.placeManager.incrementReachStick();break;case"NEW_DORA":{const i=y.from(t.doraIndicator);this.doraIndicators.push(i),this.counter.dec(i);break}case"TSUMO":break;case"RON":break;case"END_GAME":switch(t.subType){case"NINE_TILES":case"FOUR_KAN":case"FOUR_WIND":this.placeManager.incrementDeadStick();break;case"DRAWN_GAME":{const i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),this.placeManager.incrementDeadStick(),t.shouldContinue||this.placeManager.nextRound();break}case"WIN_GAME":{const i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),t.shouldContinue?this.placeManager.incrementDeadStick():(this.placeManager.nextRound(),this.placeManager.resetDeadStick()),this.placeManager.resetReachStick();break}}break;default:throw new Error(`unexpected event ${JSON.stringify(t,null,2)}`)}}}class Os extends pn{applied={};constructor(t){super("observer",t),this.counter.disable=!0,this.hands=$(new At("_____________"))}setHands(t){this.hands[t.wind]=new At(t.hands[t.wind])}handleEvent(t){switch(super.handleEvent(t),t.type){case"DISTRIBUTE":let e=!0;for(const n of Object.values(_))e&&=this.hand(n).get(f.BACK,0)==0;if(!e)break;console.debug("DISTRIBUTE:",`round: ${this.placeManager.round}`,`scores: ${JSON.stringify(this.scoreManager.summary,null,2)}`,`map: ${JSON.stringify(this.placeManager.playerMap,null,2)}`,`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`);for(const n of Object.values(_))console.debug(`${this.placeManager.playerID(n)}(${n})`,`init hand: ${this.hand(n).toString()}`);break;case"DRAW":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`draw: ${this.hand(t.iam).drawn}`,`hand: ${this.hand(t.iam).toString()}`);break;case"DISCARD":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`discard: ${t.tile.toString()}`,`hand: ${this.hand(t.iam).toString()}`);break;case"CHI":case"PON":case"DAI_KAN":case"AN_KAN":case"SHO_KAN":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`call: ${t.block.tiles}`,`hand: ${this.hand(t.iam).toString()}`);break;case"REACH":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`reach: ${t.tile}`,`hand: ${this.hand(t.iam).toString()}`);break;case"TSUMO":case"RON":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`ron/tsumo: ${JSON.stringify(t.ret,null,2)}`,`hand: ${this.hand(t.iam).toString()}`);break;case"END_GAME":for(const n of Object.values(_))console.debug(`${this.placeManager.playerID(n)}(${we(n)})`,`end hand: ${this.hand(n).toString()}`);console.debug("END_GAME",t.subType,"scores",JSON.stringify(this.scoreManager.summary,null,2),`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`)}}}class Yt extends pn{river=new sn;doras=[];constructor(t,e){super(t,e),this.eventHandler.on(n=>this.handleEvent(n))}get myWind(){return this.placeManager.wind(this.id)}setHands(t){for(const e of Object.values(_))this.hands[e]=new At(t.hands[e])}handleDiscard(t){const e=Object.values(_).filter(l=>l==this.myWind?!1:this.hand(l).reached),n=new te(this.hand(this.myWind)).calc();if(e.length>0&&n>=2)return Ct.selectTile(this.counter,e,t);const i=Ht.calcEffectiveTiles(this.hand(this.myWind),t),o=qt.analyzePlayerEfficiency(this.counter,i).sort((l,u)=>u.sum-l.sum),a=o.filter(l=>l.sum==o[0].sum);return qt.selectMinPriority(this.counter,a,this.doras).tile}handleEvent(t){switch(t.type){case"CHOICE_AFTER_DISCARDED":t.choices.CHI=!1,t.choices.DAI_KAN=!1,t.choices.PON=!1,this.eventHandler.emit(t);break;case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DRAWN":if(t.choices.DISCARD){const e=this.handleDiscard(t.choices.DISCARD.map(y.from));t.choices.DISCARD=[e.toString()]}this.eventHandler.emit(t);break;case"CHOICE_FOR_REACH_ACCEPTANCE":this.eventHandler.emit(t);break;case"CHOICE_FOR_CHAN_KAN":this.eventHandler.emit(t);break;default:super.handleEvent(t)}}}class Fo{index=0;histories=[];constructor(t){this.histories=JSON.parse(t)}next(){b(this.index<this.histories.length),this.index++}prev(){this.index--,b(this.index<0)}start(){ne.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const Zo=s=>{const[t,e]=Zt(),[n,i]=Zt(),[r,o]=Zt(),[a,c]=Zt(),l=["player-1","player-2","player-3","player-4"],u=s?.playerInjection,h=u?.p1??Yt,d=u?.p2??Yt,g=u?.p3??Yt,p=u?.p4??Yt,E=new h(l[0],e),A=new d(l[1],i),T=new g(l[2],o),v=new p(l[3],c),M=[{handler:t,id:l[0]},{handler:n,id:l[1]},{handler:r,id:l[2]},{handler:a,id:l[3]}];return{c:new ne(M,{debug:s?.debug,shuffle:s?.shuffle}),p1:E,p2:A,p3:T,p4:v}},dt=(s,t)=>{let n=1;for(let i of t)i.equals(s)&&(n*=2);return n};class qt{static analyzePlayerEfficiency(t,e){let n=[];for(let i of e){let r=0,o=[];for(let a of i.effectiveTiles)o.push({tile:a.clone(),count:t.get(a)}),r+=t.get(a);n.push({sum:r,tile:i.tile,effectiveTiles:o,shanten:i.shanten})}return n}static selectMinPriority(t,e,n){b(e.length>0);let i=0,r=0;for(let o=0;o<e.length;o++){const a=qt.calcPriority(t,e[o],n);a<i&&(i=a,r=o)}return e[r]}static calcPriority(t,e,n){const i=e.tile;let r=0;if(i.t==f.Z)return r=t.get(i),(i.n==5||i.n==6||i.n==7)&&(r*=2),r*dt(i,n);{const o=t.get(i);r+=o*dt(i,n);const a=t.get(new y(i.t,i.n+1)),c=t.get(new y(i.t,i.n+2)),l=t.get(new y(i.t,i.n-1)),u=t.get(new y(i.t,i.n-2)),h=i.n-2>0?Math.min(l,u):0,d=i.n+2<=9?Math.min(a,c):0,g=i.n-1>=1&&i.n+1<=9?Math.min(a,l):0,p=Math.max(h,g),E=Math.max(g,d);return r+=o*dt(i,n),r+=h*dt(new y(i.t,i.n-2),n),r+=d*dt(new y(i.t,i.n+2),n),r+=p*dt(new y(i.t,i.n-1),n),r+=E*dt(new y(i.t,i.n+1),n),i.n==0,r}}}class Ct{static selectTile(t,e,n){b(e.length>0&&n.length>0);let i=n[0],r=Number.POSITIVE_INFINITY;for(let o of n){const a=Ct.rank(t,e,o);a<r&&(i=o,r=a)}return i}static rank(t,e,n){let i=0;const r=n.isNum()?Ct.rankN:Ct.rankZ;for(let o of e){const a=r(t,o,n);i<a&&(i=a)}return i}static rankZ(t,e,n){if(n.t!=f.Z)throw new Error(`expected TYPE.Z but ${n.toString()}`);if(t.isSafeTile(n.t,n.n,e))return 0;const i=t.get(n);return Math.min(i,3)}static rankN(t,e,n){if(!n.isNum())throw new Error(`expected TYPE.NUMBER but ${n.toString()}`);const i=n.n,r=n.t;if(t.isSafeTile(r,i,e))return 0;if(i==1)return t.isSafeTile(r,4,e)?3:6;if(i==9)return t.isSafeTile(r,6,e)?3:6;if(i==2||i==8)return t.isSafeTile(r,5,e)?4:8;if(i==3)return t.isSafeTile(r,6,e)?5:8;if(i==7)return t.isSafeTile(r,4,e)?5:8;const o=t.isSafeTile(r,i-3,e),a=t.isSafeTile(r,i+3,e);return o&&a?4:o||a?8:12}}exports.ActorHand=At;exports.BLOCK=w;exports.BaseActor=pn;exports.Block=I;exports.BlockAnKan=R;exports.BlockCalculator=ts;exports.BlockChi=J;exports.BlockDaiKan=q;exports.BlockHand=Rt;exports.BlockIsolated=Ve;exports.BlockOther=Je;exports.BlockPair=B;exports.BlockPon=X;exports.BlockRun=tt;exports.BlockShoKan=K;exports.BlockThree=U;exports.Controller=ne;exports.Counter=as;exports.Efficiency=Ht;exports.FONT_FAMILY=Fe;exports.G=N;exports.Hand=Ae;exports.INPUT_SEPARATOR=Q;exports.Image=qe;exports.ImageHelper=en;exports.Mark=at;exports.MeasureText=$s;exports.MyG=Vi;exports.MyImage=Ji;exports.MyRect=qi;exports.MySVG=Yi;exports.MyText=Qi;exports.MyUse=Xi;exports.N19=Y;exports.NZ=Pt;exports.OP=m;exports.Observer=Os;exports.Parser=D;exports.PlaceManager=Xt;exports.Player=Yt;exports.PlayerEfficiency=qt;exports.PointCalculator=He;exports.ROUND=O;exports.ROUND_MAP=Ze;exports.Rect=Qe;exports.Replayer=Fo;exports.RiskRank=Ct;exports.River=sn;exports.STICK_CONTEXT=Oe;exports.SVG=Gn;exports.ScoreManager=Jt;exports.ShantenCalculator=te;exports.Svg=jn;exports.Symbol=tn;exports.TABLE_CONTEXT=Pn;exports.TILE_CONTEXT=st;exports.TYPE=f;exports.Text=wt;exports.Tile=y;exports.Use=_e;exports.WIND=_;exports.WIND_MAP=ye;exports.Wall=Et;exports.compareTiles=Qt;exports.convertInput=Qn;exports.createControllerMachine=Ge;exports.createEventEmitter=os;exports.createEventPipe=Zt;exports.createHand=Ot;exports.createLocalGame=Zo;exports.createTable=Yn;exports.createWindMap=$;exports.deserializeWinResult=Gt;exports.drawBlocks=or;exports.drawTable=gr;exports.forHand=z;exports.getCallBlockIndex=ke;exports.getPointDescription=es;exports.incrementalIDGenerator=Ss;exports.is5Tile=k;exports.nextRound=Vt;exports.nextWind=yt;exports.optimizeSVG=cr;exports.parse=Xn;exports.parseTableInput=qn;exports.prevRound=Ls;exports.prevWind=we;exports.prioritizeDiscardedEvents=ns;exports.prioritizeDrawnEvents=ss;exports.serializeWinResult=de;exports.shuffle=nn;exports.sortCalledTiles=Hn;exports.toDora=Be;
|
|
14
|
+
通知する choice がない場合、controller が\\*で遷移させる`,on:{RON:{target:"roned",guard:"canWin"},PON:{target:"poned",guard:"canPon"},CHI:{target:"chied",guard:"canChi"},DAI_KAN:{target:"dai_kaned"},"*":{target:"wildcard_after_discarded"}}},reached:{on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"}}},entry:{type:"notify_reach_accepted"}},roned:{exit:[{type:"notify_ron"},{type:"notify_end"}],type:"final"},poned:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called"}}},entry:[{type:"notify_call"},{type:"disable_none_shot"}]},chied:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called",params:{action:"chi"}}}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},wildcard_after_discarded:{exit:[],always:[{target:"drawn_game",guard:"cannotContinue"},{target:"drawn",actions:[{type:"updateNextWind"}]}]},waiting_discard_event:{description:"鳴いたユーザからの DISCARD イベントを待つ",on:{DISCARD:{target:"discarded"}}},dai_kaned:{on:{NEXT:{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},an_sho_kaned:{always:{target:"waiting_chankan_event"},entry:[{type:"notify_call"},{type:"disable_one_shot"},{type:"notify_new_dora_if_needed"},{type:"notify_choice_for_chankan"}]},waiting_chankan_event:{description:"チャンカンを待つ",on:{"*":{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]},RON:{target:"roned",guard:{type:"canWin"}}}},drawn_game:{exit:{type:"notify_end",params:{}},type:"final"}},types:{events:{},context:{}}},{actions:{updateNextWind:({context:t,event:e})=>{const n=t.currentWind;t.currentWind=yt(n)},notify_distribution:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.initialHands();for(const r of Object.values(_)){const o=P("_____________");o[r]=i[r].toString();const a={id:n,type:"DISTRIBUTE",hands:o,wind:r,doraIndicator:t.controller.wall.doraIndicators[0].toString(),sticks:t.controller.placeManager.sticks,round:t.controller.placeManager.round,players:t.controller.playerIDs,places:t.controller.placeManager.playerMap,scores:t.controller.scoreManager.summary};t.controller.emit(a)}t.controller.next()},notify_choice_after_drawn:({context:t,event:e},n)=>{const i=t.currentWind,r=t.controller.hand(i).drawn,o=t.genEventID(),a={id:o,type:"CHOICE_AFTER_DRAWN",wind:i,drawerInfo:{wind:i,tile:r.toString()},choices:{TSUMO:oe(t.controller.doWin(i,r,{oneShot:t.oneShotMap[i],replacementWin:n?.replacementWin})),REACH:Fo(t.controller.doReach(i)),AN_KAN:re(t.controller.doAnKan(i)),SHO_KAN:re(t.controller.doShoKan(i)),DISCARD:t.controller.doDiscard(i).map(c=>c.toString()),DRAWN_GAME_BY_NINE_ORPHANS:t.controller.canDrawnGame(i)}};t.controller.emit(a),t.controller.pollReplies(o,[i])},notify_choice_after_discarded:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:m.HORIZONTAL});for(const o of Object.values(_)){const a={id:n,type:"CHOICE_AFTER_DISCARDED",wind:o,discarterInfo:{wind:i.w,tile:i.t.toString()},choices:{RON:oe(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:re(t.controller.doPon(o,i.w,r)),CHI:re(t.controller.doChi(o,i.w,r)),DAI_KAN:jo(t.controller.doDaiKan(o,i.w,r))}};a.choices.RON&&(t.missingMap[o]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(_))},notify_choice_after_called:({context:t,event:e},n)=>{const i=t.genEventID(),r=t.currentWind;let o=t.controller.doDiscard(r);const a=t.controller.hand(t.currentWind).called.at(-1);(a instanceof q||a instanceof U)&&(o=t.controller.doDiscard(r,a));const c={id:i,type:"CHOICE_AFTER_CALLED",wind:r,choices:{DISCARD:o.map(l=>l.toString())}};t.controller.emit(c),t.controller.pollReplies(i,[r])},notify_choice_for_reach_acceptance:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:m.HORIZONTAL});for(const o of Object.values(_)){const a={id:n,type:"CHOICE_FOR_REACH_ACCEPTANCE",wind:o,reacherInfo:{wind:i.w,tile:r.toString()},choices:{RON:oe(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]}))}};t.controller.emit(a)}t.controller.pollReplies(n,Object.values(_))},notify_choice_for_chankan:({context:t,event:e})=>{b(e.type=="SHO_KAN"||e.type=="AN_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.block.tiles[0].clone({remove:m.HORIZONTAL});for(const r of Object.values(_)){const o=t.controller.doWin(r,e.block.tiles[0].clone({remove:m.HORIZONTAL}),{discardedBy:e.iam,quadWin:!0,oneShot:t.oneShotMap[r],missingRon:t.missingMap[e.iam]}),a={id:n,type:"CHOICE_FOR_CHAN_KAN",wind:r,callerInfo:{wind:e.iam,tile:i.toString()},choices:{RON:e.type=="SHO_KAN"?oe(o):!1}};a.choices.RON&&(t.missingMap[r]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(_))},notify_call:({context:t,event:e})=>{b(e.type=="CHI"||e.type=="PON"||e.type=="DAI_KAN"||e.type=="AN_KAN"||e.type=="SHO_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam;t.currentWind=i;for(const r of Object.values(_)){const o={id:n,type:e.type,iam:i,wind:r,block:e.block.serialize()};t.controller.emit(o)}t.controller.next()},notify_discard:({context:t,event:e})=>{b(e.type=="DISCARD",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind,r=e.tile;for(const o of Object.values(_)){const a={id:n,type:"DISCARD",iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}t.controller.next()},notify_draw:({context:t,event:e},n)=>{const i=t.genEventID(),r=n?.action;let o;r=="kan"?o=t.controller.wall.kan():o=t.controller.wall.draw();const a=t.currentWind;t.controller.hand(a).reached||(t.missingMap[a]=!1);for(const c of Object.values(_)){let l=new y(f.BACK,0,[m.TSUMO]);c==a&&(l=o);const u={id:i,type:"DRAW",subType:r,iam:a,wind:c,tile:l.toString()};t.controller.emit(u)}t.controller.next()},notify_ron:({context:t,event:e})=>{b(e.type=="RON");const n=t.genEventID(),i=e.iam;for(const r of Object.values(_)){const o={id:n,type:e.type,iam:i,wind:r,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:de(e.ret)};t.controller.emit(o)}},notify_tsumo:({context:t,event:e})=>{b(e.type=="TSUMO",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind;for(const r of Object.values(_)){const o={id:n,type:e.type,iam:i,wind:r,lastTile:t.controller.hand(i).drawn.toString(),ret:de(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{b(e.type=="REACH",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam,r=e.tile.clone({add:m.HORIZONTAL});t.oneShotMap[i]=!0;for(const o of Object.values(_)){const a={id:n,type:e.type,iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}},notify_reach_accepted:({context:t,event:e})=>{b(e.type=="REACH_ACCEPT");const n=t.genEventID();for(const i of Object.values(_)){const r={id:n,type:"REACH_ACCEPTED",reacherInfo:{wind:e.reacherInfo.wind,tile:e.reacherInfo.tile.toString()},wind:i};t.controller.emit(r)}t.controller.next()},notify_new_dora_if_needed:({context:t,event:e})=>{const n=t.genEventID();if(e.type=="AN_KAN"){const i=t.controller.wall.openDoraIndicator();for(const r of Object.values(_)){const o={id:n,type:"NEW_DORA",wind:r,doraIndicator:i.toString()};t.controller.emit(o)}}e.type=="SHO_KAN"},disable_one_shot:({context:t,event:e})=>{for(const n of Object.values(_))t.oneShotMap[n]=!1},disable_one_shot_for_me:({context:t,event:e})=>{t.oneShotMap[t.currentWind]=!1},notify_end:({context:t,event:e})=>{const n=t.genEventID(),i=P("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){i[e.iam]=t.controller.hand(e.iam).toString();for(const r of Object.values(_)){const o={id:n,type:"END_GAME",subType:"NINE_TILES",wind:r,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:P(0),hands:i};t.controller.emit(o)}}else if(e.type=="RON"||e.type=="TSUMO"){const r=e.iam==_.E,o=t.controller.finalResult(e.ret,e.iam);for(const a of Object.values(_)){i[e.iam]=t.controller.hand(e.iam).toString();const c={id:n,type:"END_GAME",subType:"WIN_GAME",wind:a,shouldContinue:r,sticks:{reach:0,dead:0},scores:t.controller.scoreManager.summary,deltas:o.deltas,hands:i};t.controller.emit(c)}}else if(!t.controller.wall.canKan||t.controller.river.cannotContinue()){const r=t.controller.wall.canKan?"FOUR_WIND":"FOUR_KAN";for(const o of Object.values(_)){const a={id:n,type:"END_GAME",subType:r,wind:o,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:P(0),hands:P("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const r=[];for(const l of Object.values(_)){const u=t.controller.hand(l);new te(u).calc()==0&&(r.push(l),i[l]=u.toString())}const o=r.length==0||r.length==4,a=P(0);for(const l of Object.values(_))r.includes(l)?a[l]+=o?0:3e3/r.length:a[l]-=o?0:3e3/(4-r.length);const c=r.length==4||a[_.E]>0;for(const l of Object.values(_)){const u={id:n,type:"END_GAME",subType:"DRAWN_GAME",wind:l,shouldContinue:c,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:a,hands:i};t.controller.emit(u)}}}}},actors:{},guards:{canChi:({context:t,event:e},n)=>e.type=="CHI"?!!t.controller.doChi(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canChi receive ${e.type}`),!1),canPon:({context:t,event:e},n)=>e.type=="PON"?!!t.controller.doPon(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canPon receive ${e.type}`),!1),canWin:({context:t,event:e},n)=>e.type=="TSUMO"||e.type=="RON"?!0:(console.error(`guards.canWin receive ${e.type}`),!1),canReach:({context:t,event:e},n)=>e.type=="REACH"?!!t.controller.doReach(e.iam):(console.error(`guards.canReach receive ${e.type}`),!1),cannotContinue:({context:t,event:e},n)=>!t.controller.wall.canDraw||!t.controller.wall.canKan||t.controller.river.cannotContinue()},delays:{}});function Ss(s=0){let t=s;return()=>(t++).toString()}class Et{walls={replacement:[],dead:[],doraIndicators:[],hiddenDoraIndicators:[],drawable:[]};backup;openedDoraCount=1;constructor(t){this.init(t),this.backup=Et.clone(this.walls)}kan(){if(this.walls.replacement.length==0)throw new Error("exceeded maximum kan");const t=this.walls.replacement.pop();return this.walls.drawable.pop(),y.from(t)}draw(){if(!this.walls.drawable)throw new Error("cannot draw any more");return y.from(this.walls.drawable.pop())}openDoraIndicator(){if(this.openedDoraCount>=4)throw new Error("exceeded maximum open dora");return this.openedDoraCount++,y.from(this.walls.doraIndicators[this.openedDoraCount-1])}get doraIndicators(){return this.walls.doraIndicators.slice(0,this.openedDoraCount).map(y.from)}get hiddenDoraIndicators(){return this.walls.hiddenDoraIndicators.slice(0,this.openedDoraCount).map(y.from)}get canKan(){return this.walls.replacement.length>0}get canDraw(){return this.walls.drawable.length>0}initialHands(){const t=P("");for(let e=0;e<3;e++)for(const n of Object.values(_))for(let i=0;i<4;i++)t[n]+=this.draw().toString();for(const e of Object.values(_))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=Et.clone(t);return}else{for(let e of Object.values(f)){if(e==f.BACK)continue;const n=e==f.Z?[1,2,3,4,5,6,7]:[1,2,3,4,5,6,7,8,9];for(let i=0;i<4;i++)for(let r of n){let o=new y(e,r);e!=f.Z&&i==3&&r==5&&(o=o.clone({add:m.RED})),this.walls.drawable.push(o.toString())}}nn(this.walls.drawable)}for(let e=0;e<14;e++)this.walls.dead.push(this.walls.drawable.pop());for(let e=0;e<4;e++)this.walls.hiddenDoraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.doraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.replacement.push(this.walls.dead.pop())}export(){return this.backup}static clone(t){return{drawable:t.drawable.concat(),dead:t.dead.concat(),doraIndicators:t.doraIndicators.concat(),hiddenDoraIndicators:t.hiddenDoraIndicators.concat(),replacement:t.replacement.concat()}}}class ne{wall=new Et;playerIDs;actor=Bt(Fe(this),{});observer;handlers={};mailBox={};histories=[];debugMode;constructor(t,e){this.debugMode=e?.debug??!1,this.handlers=Object.fromEntries(t.map(o=>[o.id,o.handler])),this.playerIDs=t.map(o=>o.id),t.forEach(o=>o.handler.on(a=>this.enqueue(a)));const n=os();this.observer=new Os(n),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const i=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new Jt(i);const r=e?.shuffle==!1?this.playerIDs:nn([...this.playerIDs]);this.observer.placeManager=new Xt({[r[0]]:_.E,[r[1]]:_.S,[r[2]]:_.W,[r[3]]:_.N})}boardParams(t){let n=this.hand(t).reached?1:void 0;if(n){const i=this.river.discards(t);n=i.length==0||i.length==1&&i[0].t.has(m.HORIZONTAL)?2:1}return{doraIndicators:this.observer.doraIndicators,round:this.placeManager.round,myWind:t,sticks:this.observer.placeManager.sticks,reached:n}}hand(t){return this.observer.hand(t)}get placeManager(){return this.observer.placeManager}get scoreManager(){return this.observer.scoreManager}get river(){return this.observer.river}next(t){(!this.debugMode||t)&&this.actor.send({type:"NEXT"})}emit(t){const e=this.observer.placeManager.playerID(t.wind);this.handlers[e].emit(t);const n=t.iam;t.wind==n?this.observer.eventHandler.emit(t):n==null&&(!this.observer.applied[t.id]||t.type=="DISTRIBUTE")&&(this.observer.eventHandler.emit(t),this.observer.applied[t.id]=!0)}enqueue(t){this.mailBox[t.id]==null&&(this.mailBox[t.id]=[]),this.mailBox[t.id].push(t)}pollReplies(t,e){const n=this.mailBox[t];if(n==null)throw new Error(`not enqueued ${t} at ${this.actor.getSnapshot().value}`);if(n.length!=e.length)throw new Error(`${t}: num of event: got: ${e.length}, want: ${n.length}`);if(e.length==0){console.warn("no events to handle");return}const i=n[0];if(i.type=="CHOICE_AFTER_DISCARDED"){const r=ns(n);if(r.events.length==0){this.actor.send({type:""});return}const o=r.events[0];switch(r.type){case"RON":b(o.choices.RON,"ron choice is none"),this.actor.send({type:r.type,iam:o.wind,ret:Ft(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:y.from(o.discarterInfo.tile)}});break;case"DAI_KAN":b(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:r.type,iam:o.wind,block:F.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[r.type];b(a,`${r.type} choice is none`),b(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const c=U.deserialize(a[0]);this.actor.send({type:r.type,iam:o.wind,block:c})}}else if(i.type=="CHOICE_AFTER_DRAWN"){const r=ss(n);b(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const o=r.events[0],a=o.wind;switch(r.type){case"TSUMO":b(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:r.type,ret:Ft(o.choices.TSUMO),lastTile:y.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[r.type];b(c,`${r.type} candidates is none`),this.actor.send({type:"REACH",tile:y.from(c[0].tile),iam:a});break;case"DISCARD":const l=o.choices[r.type];b(l,`${r.type} choice is none`),this.actor.send({type:r.type,tile:y.from(l[0]).clone({remove:m.TSUMO}),iam:a});break;case"AN_KAN":{const u=o.choices[r.type];b(u,`${r.type} choice is none`),this.actor.send({type:r.type,block:C.from(u[0].tiles),iam:a});break}case"SHO_KAN":{const u=o.choices[r.type];b(u,`${r.type} choice is none`),this.actor.send({type:r.type,block:H.from(u[0].tiles),iam:a});break}case"DRAWN_GAME_BY_NINE_ORPHANS":this.actor.send({type:"DRAWN_GAME_BY_NINE_ORPHANS",iam:a});break}}else if(i.type=="CHOICE_AFTER_CALLED"){b(i.choices.DISCARD,`discard candidate tile is none: ${JSON.stringify(i,null,2)} ${this.hand(i.wind).toString()}`);const r=i.wind,o=y.from(i.choices.DISCARD[0]);this.actor.send({type:"DISCARD",tile:o,iam:r})}else if(i.type=="CHOICE_FOR_REACH_ACCEPTANCE"){const r=n.filter(a=>(b(a.type=="CHOICE_FOR_REACH_ACCEPTANCE"),a.choices.RON!==!1));if(r.length==0){this.actor.send({type:"REACH_ACCEPT",reacherInfo:{tile:y.from(i.reacherInfo.tile),wind:i.reacherInfo.wind}});return}const o=r[0];this.actor.send({type:"RON",iam:o.wind,ret:Ft(o.choices.RON),targetInfo:{wind:o.reacherInfo.wind,tile:y.from(o.reacherInfo.tile)}});return}else if(i.type=="CHOICE_FOR_CHAN_KAN"){const r=n.filter(a=>a.choices.RON!==!1);if(r.length==0){this.actor.send({type:""});return}const o=r[0];b(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:Ft(o.choices.RON),quadWin:!0,targetInfo:{wind:o.callerInfo.wind,tile:y.from(o.callerInfo.tile)}});return}else console.warn(`controller found unexpected event: ${i.type}`)}export(){return this.histories.concat()}static load(t){const e=t.choiceEvents,n=Object.keys(t.players),i={emit:a=>{},on:a=>{}},r=n.map(a=>({id:a,handler:i})),o=new ne(r);return o.playerIDs=n,o.mailBox=e,o.observer.placeManager=new Xt(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new Jt(t.scores),o.wall=new Et(t.wall),o}start(){this.actor.subscribe(n=>{console.debug("State:",n.value)});const t={scores:this.scoreManager.summary,round:this.placeManager.round,players:this.placeManager.playerMap,wall:this.wall.export(),choiceEvents:this.mailBox,sticks:this.placeManager.sticks};this.actor.start(),this.histories.push(t);const e=this.actor.getSnapshot().status;if(e!="done")throw new Error(`unexpected state ${this.actor.getSnapshot().value}(${e})`)}startGame(){for(;console.debug(`start========${this.placeManager.round}=============`),this.start(),this.wall=new Et,this.observer.applied={},this.mailBox={},this.actor=Bt(Fe(this)),!this.placeManager.is(O.W1););}finalResult(t,e){const n=this.hand(e),i=n.reached?this.wall.hiddenDoraIndicators:void 0,r=new He(n,{...t.boardContext,sticks:this.placeManager.sticks,hiddenDoraIndicators:i}).calc(t.hand);return b(r),r}doWin(t,e,n){if(e==null)return!1;let i=this.hand(t);const r=this.boardParams(t);if(i.drawn==null){if(n==null)throw new Error("should ron but params == null");if(n.discardedBy==t||n.missingRon)return!1;i=i.clone(),r.ronWind=n.discardedBy,r.finalDiscardWin=!this.wall.canDraw,r.quadWin=n.quadWin,i.inc([e])}else r.finalWallWin=!this.wall.canDraw,r.replacementWin=n?.replacementWin;r.oneShotWin=n?.oneShot;const o=new ts(i),a=new He(i,r),c=o.calc(e),l=a.calc(...c);if(!l||l.yakus.length==0)return!1;if(i.draw==null){const u=Ht.getEffectiveTiles(this.hand(t)).effectiveTiles;if(this.river.discards(t).some(h=>u.some(d=>d.equals(h.t))))return!1}return l}doPon(t,e,n){if(n==null||t==e)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3||i.get(n.t,n.n)<2)return!1;const r=n.clone({removeAll:!0}),o=ke(t,e,w.PON),a=[],c=new U([r,r,r]).clone({replace:{idx:o,tile:n.clone({add:m.HORIZONTAL})}});let l=c;k(n)&&n.has(m.RED)&&(l=c.clone({replace:{idx:o,tile:r.clone({add:[m.RED,m.HORIZONTAL]})}}));const u=o%2+1;if(k(n)&&i.get(n.t,0)>0&&(l=c.clone({replace:{idx:u,tile:r.clone({add:m.RED})}})),a.push(l),k(r)&&i.get(r.t,5)==3){const h=c.clone({replace:{idx:u,tile:r}});a.push(h)}return a}doChi(t,e,n){if(n==null||!n.isNum()||yt(e)!=t)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3)return!1;const r=n.clone({remove:m.TSUMO,add:[m.HORIZONTAL]}),o=[];r.n-2>=1&&i.get(n.t,r.n-2)>0&&i.get(n.t,r.n-1)>0&&o.push(new q([r,new y(n.t,r.n-1),new y(n.t,r.n-2)])),r.n+2<=9&&i.get(n.t,r.n+1)>0&&i.get(n.t,r.n+2)>0&&o.push(new q([r,new y(n.t,r.n+1),new y(n.t,r.n+2)])),r.n-1>=1&&r.n+1<=9&&i.get(n.t,r.n-1)>0&&i.get(n.t,r.n+1)>0&&o.push(new q([r,new y(n.t,r.n-1),new y(n.t,r.n+1)]));for(let d=0;d<o.length;d++){const g=o[d],p=this.cannotDiscardTile(g),E=[];for(const v of p){const x=i.get(v.t,v.n);for(let It=0;It<x;It++)E.push(v.clone({remove:m.RED}))}const A=i.dec([...E,g.tiles[1],g.tiles[2]]),I=i.hands.length==0;i.inc(A),I&&o.splice(d,1)}if(o.length==0)return!1;const h=i.get(n.t,0)>0?this.redPattern(o):[];return h.length>0&&i.get(n.t,5)==1?h:[...o,...h]}redPattern(t){return t.length==0?[]:t.filter(n=>k(n.tiles[1])||k(n.tiles[2])).map(n=>{if(k(n.tiles[1])){const i=n.tiles[1].clone({add:m.RED});return n.clone({replace:{idx:1,tile:i}})}else if(k(n.tiles[2])){const i=n.tiles[2].clone({add:m.RED});return n.clone({replace:{idx:2,tile:i}})}}).filter(n=>n!=null)}doReach(t){const e=this.hand(t);return e.reached||!e.menzen||new te(e).calc()>0?!1:Ht.calcEffectiveTiles(e,e.hands)}doDiscard(t,e){if(this.hand(t).reached)return[this.hand(t).drawn];const n=this.hand(t).hands;if(e==null)return n;if(e instanceof U)return n.filter(o=>!o.equals(e.tiles[0]));const i=this.cannotDiscardTile(e),r=n.filter(o=>!i.some(a=>o.equals(a)));return b(r.length>0,`no tiles to discard. hand: ${this.hand(t)}, suji: ${i}, block-chi: ${e}`),r}cannotDiscardTile(t){const e=t.tiles[0],n=t.tiles[1].n;return n!=1&&e.n-2==n?[new y(e.t,e.n-3),e]:n!=8&&e.n+1==n?[new y(e.t,e.n+3),e]:[e]}doAnKan(t){const e=this.hand(t),n=[];if(e.reached)return!1;for(const[i,r]of j())if(e.get(i,r)==4){const o=new y(i,r),a=[o,o,o,o];k(o)&&(a[1]=o.clone({add:m.RED})),n.push(new C(a))}if(n.length==0)return!1;for(const i of n)b(i.tiles.filter(r=>r.has(m.HORIZONTAL)).length==0,`h op ${i.toString()}`);return n}doShoKan(t){const e=this.hand(t);if(e.reached)return!1;const n=e.called.filter(r=>r instanceof U);if(n.length==0)return!1;const i=[];for(const r of n){const o=r.tiles[0].clone({removeAll:!0,add:m.HORIZONTAL});if(e.get(o.t,o.n)==1){const a=k(o)&&e.get(o.t,0)>0?o.clone({add:m.RED}):o;i.push(new H([...r.tiles,a]))}}if(i.length==0)return!1;for(const r of i)b(r.tiles.filter(o=>o.has(m.HORIZONTAL)).length==2,`h op ${r.toString()}`);return i}doDaiKan(t,e,n){const i=this.hand(t);if(i.reached||t==e)return!1;const r=n.clone({removeAll:!0});if(i.get(r.t,r.n)!=3)return!1;const o=ke(t,e,w.DAI_KAN);let a=new F([r,r,r,r]).clone({replace:{idx:o,tile:r.clone({add:m.HORIZONTAL})}});if(k(n)&&n.has(m.RED))a=a.clone({replace:{idx:o,tile:r.clone({add:[m.HORIZONTAL,m.RED]})}});else if(k(n)&&!n.has(m.RED)){b(i.get(n.t,0)>0,`hand does not have red tile: ${i.toString()}`);const c=o%3+1;a=a.clone({replace:{idx:c,tile:r.clone({add:m.RED})}})}return b(a.tiles.filter(c=>c.has(m.HORIZONTAL)).length==1,`h op ${a.toString()}`),a}canDrawnGame(t){if(this.river.discards(t).length!=0)return!1;const e=this.hand(t);let n=0;for(const i of Object.values(f)){if(i==f.BACK)continue;const r=i==f.Z?Pt:J;for(const o of r)e.get(i,o)>0&&n++}return n>=9}initialHands(){return this.wall.initialHands()}}class At extends Ae{isBackHand(){for(const t of Object.values(f))if(t!=f.BACK&&this.sum(t)>0)return!1;return this.sum(f.BACK)>0}clone(){const t=new At(this.toString());return t.data.reached=this.data.reached,t}dec(t){return this.isBackHand()?(super.dec(t.map(()=>new y(f.BACK,0))),[...t]):super.dec(t)}}class pn{id;river=new sn;placeManager=new Xt({});scoreManager=new Jt({});hands=P(new At(""));counter=new as;doraIndicators=[];eventHandler;constructor(t,e){this.id=t,this.eventHandler=e}hand(t){return this.hands[t]}handleEvent(t){switch(t.type){case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DISCARDED":case"CHOICE_AFTER_DRAWN":case"CHOICE_FOR_CHAN_KAN":case"CHOICE_FOR_REACH_ACCEPTANCE":break;case"DISTRIBUTE":this.counter.reset();const e=y.from(t.doraIndicator);this.setHands(t),this.placeManager=new Xt(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new Jt(structuredClone(t.scores)),this.doraIndicators=[e],this.counter.dec(e);for(const i of Object.values(_))i==t.wind&&this.counter.dec(...this.hand(i).hands);break;case"DRAW":{const i=y.from(t.tile);this.hands[t.iam].draw(i),this.counter.dec(i);break}case"DISCARD":{const i=y.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(_))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"PON":case"CHI":case"DAI_KAN":{const i=T.deserialize(t.block);this.hands[t.iam].call(i),this.river.markCalled(),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(m.HORIZONTAL)));break}case"SHO_KAN":{const i=H.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(i.tiles.filter(r=>r.has(m.HORIZONTAL))[0]);break}case"AN_KAN":{const i=C.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(m.HORIZONTAL)));break}case"REACH":{this.hands[t.iam].reach();const i=y.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(_))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"REACH_ACCEPTED":const n=this.placeManager.playerID(t.reacherInfo.wind);this.scoreManager.reach(n),this.placeManager.incrementReachStick();break;case"NEW_DORA":{const i=y.from(t.doraIndicator);this.doraIndicators.push(i),this.counter.dec(i);break}case"TSUMO":break;case"RON":break;case"END_GAME":switch(t.subType){case"NINE_TILES":case"FOUR_KAN":case"FOUR_WIND":this.placeManager.incrementDeadStick();break;case"DRAWN_GAME":{const i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),this.placeManager.incrementDeadStick(),t.shouldContinue||this.placeManager.nextRound();break}case"WIN_GAME":{const i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),t.shouldContinue?this.placeManager.incrementDeadStick():(this.placeManager.nextRound(),this.placeManager.resetDeadStick()),this.placeManager.resetReachStick();break}}break;default:throw new Error(`unexpected event ${JSON.stringify(t,null,2)}`)}}}class Os extends pn{applied={};constructor(t){super("observer",t),this.counter.disable=!0,this.hands=P(new At("_____________"))}setHands(t){this.hands[t.wind]=new At(t.hands[t.wind])}handleEvent(t){switch(super.handleEvent(t),t.type){case"DISTRIBUTE":let e=!0;for(const n of Object.values(_))e&&=this.hand(n).get(f.BACK,0)==0;if(!e)break;console.debug("DISTRIBUTE:",`round: ${this.placeManager.round}`,`scores: ${JSON.stringify(this.scoreManager.summary,null,2)}`,`map: ${JSON.stringify(this.placeManager.playerMap,null,2)}`,`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`);for(const n of Object.values(_))console.debug(`${this.placeManager.playerID(n)}(${n})`,`init hand: ${this.hand(n).toString()}`);break;case"DRAW":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`draw: ${this.hand(t.iam).drawn}`,`hand: ${this.hand(t.iam).toString()}`);break;case"DISCARD":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`discard: ${t.tile.toString()}`,`hand: ${this.hand(t.iam).toString()}`);break;case"CHI":case"PON":case"DAI_KAN":case"AN_KAN":case"SHO_KAN":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`call: ${t.block.tiles}`,`hand: ${this.hand(t.iam).toString()}`);break;case"REACH":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`reach: ${t.tile}`,`hand: ${this.hand(t.iam).toString()}`);break;case"TSUMO":case"RON":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`ron/tsumo: ${JSON.stringify(t.ret,null,2)}`,`hand: ${this.hand(t.iam).toString()}`);break;case"END_GAME":for(const n of Object.values(_))console.debug(`${this.placeManager.playerID(n)}(${we(n)})`,`end hand: ${this.hand(n).toString()}`);console.debug("END_GAME",t.subType,"scores",JSON.stringify(this.scoreManager.summary,null,2),`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`)}}}class Zt extends pn{river=new sn;doras=[];constructor(t,e){super(t,e),this.eventHandler.on(n=>this.handleEvent(n))}get myWind(){return this.placeManager.wind(this.id)}setHands(t){for(const e of Object.values(_))this.hands[e]=new At(t.hands[e])}handleDiscard(t){const e=Object.values(_).filter(l=>l==this.myWind?!1:this.hand(l).reached),n=new te(this.hand(this.myWind)).calc();if(e.length>0&&n>=2)return Ct.selectTile(this.counter,e,t);const i=Ht.calcEffectiveTiles(this.hand(this.myWind),t),o=qt.analyzePlayerEfficiency(this.counter,i).sort((l,u)=>u.sum-l.sum),a=o.filter(l=>l.sum==o[0].sum);return qt.selectMinPriority(this.counter,a,this.doras).tile}handleEvent(t){switch(t.type){case"CHOICE_AFTER_DISCARDED":t.choices.CHI=!1,t.choices.DAI_KAN=!1,t.choices.PON=!1,this.eventHandler.emit(t);break;case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DRAWN":if(t.choices.DISCARD){const e=this.handleDiscard(t.choices.DISCARD.map(y.from));t.choices.DISCARD=[e.toString()]}this.eventHandler.emit(t);break;case"CHOICE_FOR_REACH_ACCEPTANCE":this.eventHandler.emit(t);break;case"CHOICE_FOR_CHAN_KAN":this.eventHandler.emit(t);break;default:super.handleEvent(t)}}}class Go{index=0;histories=[];constructor(t){this.histories=JSON.parse(t)}next(){b(this.index<this.histories.length),this.index++}prev(){this.index--,b(this.index<0)}start(){ne.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const Yo=s=>{const[t,e]=Yt(),[n,i]=Yt(),[r,o]=Yt(),[a,c]=Yt(),l=["player-1","player-2","player-3","player-4"],u=s?.playerInjection,h=u?.p1??Zt,d=u?.p2??Zt,g=u?.p3??Zt,p=u?.p4??Zt,E=new h(l[0],e),A=new d(l[1],i),I=new g(l[2],o),v=new p(l[3],c),x=[{handler:t,id:l[0]},{handler:n,id:l[1]},{handler:r,id:l[2]},{handler:a,id:l[3]}];return{c:new ne(x,{debug:s?.debug,shuffle:s?.shuffle}),p1:E,p2:A,p3:I,p4:v}},dt=(s,t)=>{let n=1;for(let i of t)i.equals(s)&&(n*=2);return n};class qt{static analyzePlayerEfficiency(t,e){let n=[];for(let i of e){let r=0,o=[];for(let a of i.effectiveTiles)o.push({tile:a.clone(),count:t.get(a)}),r+=t.get(a);n.push({sum:r,tile:i.tile,effectiveTiles:o,shanten:i.shanten})}return n}static selectMinPriority(t,e,n){b(e.length>0);let i=0,r=0;for(let o=0;o<e.length;o++){const a=qt.calcPriority(t,e[o],n);a<i&&(i=a,r=o)}return e[r]}static calcPriority(t,e,n){const i=e.tile;let r=0;if(i.t==f.Z)return r=t.get(i),(i.n==5||i.n==6||i.n==7)&&(r*=2),r*dt(i,n);{const o=t.get(i);r+=o*dt(i,n);const a=t.get(new y(i.t,i.n+1)),c=t.get(new y(i.t,i.n+2)),l=t.get(new y(i.t,i.n-1)),u=t.get(new y(i.t,i.n-2)),h=i.n-2>0?Math.min(l,u):0,d=i.n+2<=9?Math.min(a,c):0,g=i.n-1>=1&&i.n+1<=9?Math.min(a,l):0,p=Math.max(h,g),E=Math.max(g,d);return r+=o*dt(i,n),r+=h*dt(new y(i.t,i.n-2),n),r+=d*dt(new y(i.t,i.n+2),n),r+=p*dt(new y(i.t,i.n-1),n),r+=E*dt(new y(i.t,i.n+1),n),i.n==0,r}}}class Ct{static selectTile(t,e,n){b(e.length>0&&n.length>0);let i=n[0],r=Number.POSITIVE_INFINITY;for(let o of n){const a=Ct.rank(t,e,o);a<r&&(i=o,r=a)}return i}static rank(t,e,n){let i=0;const r=n.isNum()?Ct.rankN:Ct.rankZ;for(let o of e){const a=r(t,o,n);i<a&&(i=a)}return i}static rankZ(t,e,n){if(n.t!=f.Z)throw new Error(`expected TYPE.Z but ${n.toString()}`);if(t.isSafeTile(n.t,n.n,e))return 0;const i=t.get(n);return Math.min(i,3)}static rankN(t,e,n){if(!n.isNum())throw new Error(`expected TYPE.NUMBER but ${n.toString()}`);const i=n.n,r=n.t;if(t.isSafeTile(r,i,e))return 0;if(i==1)return t.isSafeTile(r,4,e)?3:6;if(i==9)return t.isSafeTile(r,6,e)?3:6;if(i==2||i==8)return t.isSafeTile(r,5,e)?4:8;if(i==3)return t.isSafeTile(r,6,e)?5:8;if(i==7)return t.isSafeTile(r,4,e)?5:8;const o=t.isSafeTile(r,i-3,e),a=t.isSafeTile(r,i+3,e);return o&&a?4:o||a?8:12}}exports.ActorHand=At;exports.BLOCK=w;exports.BaseActor=pn;exports.Block=T;exports.BlockAnKan=C;exports.BlockCalculator=ts;exports.BlockChi=q;exports.BlockDaiKan=F;exports.BlockHand=Rt;exports.BlockIsolated=Ve;exports.BlockOther=Je;exports.BlockPair=R;exports.BlockPon=U;exports.BlockRun=tt;exports.BlockShoKan=H;exports.BlockThree=K;exports.Controller=ne;exports.Counter=as;exports.Efficiency=Ht;exports.FONT_FAMILY=Ge;exports.G=N;exports.Hand=Ae;exports.INPUT_SEPARATOR=Q;exports.Image=qe;exports.ImageHelper=en;exports.Mark=at;exports.MeasureText=$s;exports.MyG=Vi;exports.MyImage=Ji;exports.MyRect=qi;exports.MySVG=Zi;exports.MyText=Qi;exports.MyUse=Xi;exports.N19=J;exports.NZ=Pt;exports.OP=m;exports.Observer=Os;exports.Parser=W;exports.PlaceManager=Xt;exports.Player=Zt;exports.PlayerEfficiency=qt;exports.PointCalculator=He;exports.ROUND=O;exports.ROUND_MAP=Ye;exports.Rect=Qe;exports.Replayer=Go;exports.RiskRank=Ct;exports.River=sn;exports.STICK_CONTEXT=Oe;exports.SVG=Fn;exports.ScoreManager=Jt;exports.ShantenCalculator=te;exports.Svg=jn;exports.Symbol=tn;exports.TABLE_CONTEXT=Pn;exports.TILE_CONTEXT=st;exports.TYPE=f;exports.Text=wt;exports.Tile=y;exports.Use=_e;exports.WIND=_;exports.WIND_MAP=ye;exports.Wall=Et;exports.compareTiles=Qt;exports.convertInput=Qn;exports.createControllerMachine=Fe;exports.createEventEmitter=os;exports.createEventPipe=Yt;exports.createHand=Ot;exports.createLocalGame=Yo;exports.createTable=Zn;exports.createWindMap=P;exports.deserializeWinResult=Ft;exports.drawBlocks=or;exports.drawTable=gr;exports.forHand=j;exports.getCallBlockIndex=ke;exports.getPointDescription=es;exports.incrementalIDGenerator=Ss;exports.is5Tile=k;exports.nextRound=Vt;exports.nextWind=yt;exports.optimizeSVG=cr;exports.parse=Xn;exports.parseTableInput=qn;exports.prevRound=Ls;exports.prevWind=we;exports.prioritizeDiscardedEvents=ns;exports.prioritizeDrawnEvents=ss;exports.serializeWinResult=de;exports.shuffle=nn;exports.sortCalledTiles=Hn;exports.toDora=Be;
|