@konoui/mjimage 0.6.0 → 0.6.1

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 CHANGED
@@ -5,7 +5,7 @@
5
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=Tn(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=Tn(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 Tn(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:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],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=Fi),this.processTextOrObjNode=ji,this.options.format?(this.indentate=Gi,this.tagEndChar=`>
6
6
  `,this.newLine=`
7
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,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}':
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
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
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 T=r(h,A);T&&(g[p]??=[],g[p].push(T))}}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(),Go=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),Ge=s=>Uo({id:"Untitled",initial:"distribute",context:{currentWind:_.E,oneShotMap:$(!1),missingMap:$(!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:`可能なアクションとその詳細を通知\\
package/dist/index.js CHANGED
@@ -3608,6 +3608,8 @@ class un {
3608
3608
  });
3609
3609
  return {
3610
3610
  ...n,
3611
+ fu: i.fu,
3612
+ // ceiled value
3611
3613
  deltas: r,
3612
3614
  points: r[i.myWind],
3613
3615
  basePoints: o,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@konoui/mjimage",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "Generates Mahjong tiles in SVG format.",
5
5
  "author": "konoui",
6
6
  "license": "MIT",