@konoui/mjimage 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +10 -15
- package/dist/index.d.cts +8 -7
- package/dist/index.d.ts +8 -7
- package/dist/index.js +3333 -3229
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -1,19 +1,14 @@
|
|
|
1
|
-
"use strict";var Ws=Object.defineProperty;var Bs=(n,t,e)=>t in n?Ws(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var _=(n,t,e)=>Bs(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ge="MS Gothic, sans-serif",ot={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Ce={WIDTH:125,HEIGHT:27.5},Dn={BASE:40},nt=",",g={M:"m",P:"p",S:"s",Z:"z",BACK:"_"},y={TSUMO:"t",RON:"v",DORA:"d",HORIZONTAL:"-",RED:"r",COLOR_GRAYSCALE:"^"},b={PON:"pon",CHI:"chi",SHO_KAN:"shokan",DAI_KAN:"daikan",AN_KAN:"ankan",TSUMO:"tsumo",PAIR:"pair",ISOLATED:"isolated",THREE:"three",RUN:"run",HAND:"hand",IMAGE_DORA:"dora",IMAGE_DISCARD:"simple-discard",UNKNOWN:"unknown"},E={E:"1z",S:"2z",W:"3z",N:"4z"},C={E1:"1z1",E2:"1z2",E3:"1z3",E4:"1z4",S1:"2z1",S2:"2z2",S3:"2z3",S4:"2z4",W1:"3z1",W2:"3z2",W3:"3z3",W4:"3z4",N1:"4z1",N2:"4z2",N3:"4z3",N4:"4z4"},ye={[E.E]:"東",[E.S]:"南",[E.W]:"西",[E.N]:"北"},Ve={[C.E1]:"東1局",[C.E2]:"東2局",[C.E3]:"東3局",[C.E4]:"東4局",[C.S1]:"南1局",[C.S2]:"南2局",[C.S3]:"南3局",[C.S4]:"南4局",[C.W1]:"西1局",[C.W2]:"西2局",[C.W3]:"西3局",[C.W4]:"西4局",[C.N1]:"北1局",[C.N2]:"北2局",[C.N3]:"北3局",[C.N4]:"北4局"};function I(n,t){if(!n)throw new Error(t)}class Ds{constructor(t="東",e="2"){_(this,"ctx",null);_(this,"strText");_(this,"numText");_(this,"measure",(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),I(this.ctx,"context is null"));const s=this.ctx;s.font=e;const i=s.measureText(t);let r=i.width,o=i.actualBoundingBoxAscent+i.actualBoundingBoxDescent;return[r,o]});_(this,"measureFontContext",(t,e)=>{const s={family:t,size:e},i=`${s.size}px ${s.family}`,[r,o]=this.measure(this.strText,i),[a,c]=this.measure(this.numText,i);return{font:{family:t,size:e},textWidth:r,textHeight:o,numWidth:a,numHeight:c}});_(this,"measureTableFontContext",t=>{const e=this.measureFontContext(Ge,Dn.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e});this.strText=t,this.numText=e}}class Ks{constructor(t){_(this,"input");_(this,"position");_(this,"nextPosition");_(this,"char");_(this,"eof","\0");this.input=t,this.position=0,this.nextPosition=0,this.char=this.readChar()}readChar(){return this.nextPosition>=this.input.length?(this.char=this.eof,this.char):(this.char=this.input[this.nextPosition],this.position=this.nextPosition,this.nextPosition++,this.char)}peekChar(){return this.nextPosition>=this.input.length?this.eof:this.input[this.nextPosition]}peekCharN(t){if(t<0)throw new Error("arg must be positive value");return this.position+t>=this.input.length?this.eof:this.input[this.position+t]}prevChar(){return this.position>=this.input.length?this.eof:this.position>0?this.input[this.position-1]:this.eof}skipWhitespace(){for(;this.isWhitespace(this.char);)this.readChar()}isWhitespace(t){return/\s/.test(t)}}const Xt=(n,t)=>{if(n.t==t.t){if(x(n)&&x(t)){if(n.has(y.RED))return-1;if(t.has(y.RED))return 1}return n.n-t.n}const e={[g.M]:1,[g.P]:2,[g.S]:3,[g.Z]:4,[g.BACK]:5};return e[n.t]-e[t.t]},zs=(n,t)=>{const e={[y.HORIZONTAL]:1,[y.TSUMO]:2,[y.RON]:3,[y.DORA]:4,[y.COLOR_GRAYSCALE]:5,[y.RED]:6};return e[n]-e[t]},Kn=n=>{const t=[];n.forEach((s,i)=>{s.has(y.HORIZONTAL)&&t.push(i)});const e=n.filter(s=>!s.has(y.HORIZONTAL)).sort(Xt);return t.forEach(s=>{e.splice(s,0,n[s])}),e};function x(n){return n.isNum()&&n.n==5}function Ls(n){for(const t of Object.values(g))if(t==n)return[t,!0];return[g.BACK,!1]}class w{constructor(t,e,s=[]){this.t=t,this.n=e,this.ops=s}static from(t){const e=new K(t).tiles();if(e.length!=1)throw new Error(`input is not a single tile ${t}`);return e[0]}toString(){return this.t===g.BACK?this.t:`${[...this.ops].sort(zs).join("")}${this.n}${this.t}`}toJSON(){return this.toString()}clone(t){const e=(t==null?void 0:t.t)??this.t,s=(t==null?void 0:t.n)??this.n,i=t!=null&&t.removeAll?[]:this.ops.filter(o=>Array.isArray(t==null?void 0:t.remove)?!t.remove.includes(o):(t==null?void 0:t.remove)!=o),r=new Set([...i]);return t!=null&&t.add&&(Array.isArray(t.add)?t.add.forEach(o=>r.add(o)):r.add(t.add)),new w(e,s,Array.from(r))}has(t){return this.ops.includes(t)}isNum(){return this.t==g.M||this.t==g.P||this.t==g.S}equals(t){return t.t==g.BACK&&this.t==g.BACK?!0:this.t==t.t&&this.n==t.n}}class O{constructor(t,e){_(this,"_tiles");_(this,"_type");if(this._tiles=t,this._type=e,this.isCalled()){this._tiles=Kn(this._tiles);return}if(this._type!=b.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Xt);return}}static from(t){const e=new K(t).parse();if(e.length!=1)throw new Error(`block must be 1: ${t}`);return e[0]}static deserialize(t){const e=O.from(t.tiles),s=e.type;if(!(t.type==b.PAIR||t.type==b.ISOLATED||t.type==b.THREE||t.type==b.RUN)&&s!=t.type)throw new Error(`input type is ${t.type} but got is ${s}: ${t.tiles}`);return ae(e.tiles,t.type)}serialize(){return{tiles:this.toString(),type:this.type}}toJSON(){return this.serialize()}get type(){return this._type}get tiles(){return this._tiles}is(t){return this._type==t}isCalled(){return[b.PON.toString(),b.CHI.toString(),b.DAI_KAN.toString(),b.SHO_KAN.toString(),b.AN_KAN.toString()].includes(this._type.toString())}clone(t){const e=t==null?void 0:t.replace,s=[...this.tiles];return e&&(s[e.idx]=e.tile),ae(s,this._type)}}const Nt=n=>{let t="";for(const e of n){if(e.t==g.BACK)return n.join("");t+=e.toString().slice(0,-1)}return`${t}${n[0].t}`},Je=n=>{let t=n[0].t,e="";for(const i of n){const r=i.t,o=r==g.BACK?i.toString():i.toString().slice(0,-1);r!=t&&t!=g.BACK&&(e+=t),t=r,e+=o}const s=n.at(-1);return s.t!=g.BACK&&(e+=s.t),e};class Y extends O{constructor(t){super(t,b.CHI)}static from(t){return O.deserialize({tiles:t,type:b.CHI})}toString(){return Nt(this.tiles)}}class X extends O{constructor(t){super(t,b.PON)}static from(t){return O.deserialize({tiles:t,type:b.PON})}toString(){return Nt(this.tiles)}}class M extends O{constructor(t){const e=t.filter(i=>i.t!=g.BACK),s=e[0];if(e.length<t.length){if(x(s)){const i=new w(s.t,5);super([i.clone({add:y.RED}),i,i,i],b.AN_KAN);return}super([s,s,s,s],b.AN_KAN);return}super(t,b.AN_KAN)}get tilesWithBack(){const t=this.tiles[0].clone({remove:y.RED}),e=x(t)?t.clone({add:y.RED}):t;return[new w(g.BACK,0),e,t,new w(g.BACK,0)]}static from(t){return O.deserialize({tiles:t,type:b.AN_KAN})}toString(){return Je(this.tilesWithBack)}}class et extends O{constructor(t){super(t,b.DAI_KAN)}static from(t){return O.deserialize({tiles:t,type:b.DAI_KAN})}toString(){return Nt(this.tiles)}}class L extends O{constructor(t){super(t,b.SHO_KAN)}static from(t){return O.deserialize({tiles:t,type:b.SHO_KAN})}static fromPon(t,e){const s=t.tiles.findIndex(r=>r.has(y.HORIZONTAL)),i=[...t.tiles];return i.splice(s,0,e.clone({add:y.HORIZONTAL})),new L(i)}toString(){return Nt(this.tiles)}}class D extends O{constructor(t,e){super([t,e],b.PAIR)}toString(){return Nt(this.tiles)}static from(t){return O.deserialize({tiles:t,type:b.PAIR})}}class F extends O{constructor(t){super(t,b.THREE)}static from(t){return O.deserialize({tiles:t,type:b.THREE})}toString(){return Nt(this.tiles)}}class st extends O{constructor(t){super(t,b.RUN)}static from(t){return O.deserialize({tiles:t,type:b.RUN})}toString(){return Nt(this.tiles)}}class Ye extends O{constructor(t){super([t],b.ISOLATED)}static from(t){return O.deserialize({tiles:t,type:b.ISOLATED})}toString(){return this.tiles[0].toString()}}class Ct extends O{constructor(t){super(t,b.HAND)}static from(t){return O.deserialize({tiles:t,type:b.HAND})}toString(){return Je(this.tiles)}}class Xe extends O{constructor(t,e){super(t,e)}toString(){return this.is(b.IMAGE_DISCARD)?this.tiles.join(""):Je(this.tiles)}}const ae=(n,t)=>{switch(t){case b.CHI:return new Y([n[0],n[1],n[2]]);case b.PON:return new X([n[0],n[1],n[2]]);case b.AN_KAN:return new M(n);case b.DAI_KAN:return new et(n);case b.SHO_KAN:return new L(n);case b.THREE:return new F(n);case b.RUN:return new st(n);case b.PAIR:return new D(n[0],n[1]);case b.ISOLATED:return new Ye(n[0]);case b.HAND:return new Ct(n);default:return new Xe(n,t)}};class K{constructor(t){_(this,"maxInputLength",600);this.input=t,this.input=t.replace(/\s/g,"")}parse(){const t=this.tileSeparators();return this.makeBlocks(t)}tiles(){return this.tileSeparators().filter(t=>t!=nt)}tileSeparators(){const t=new Ks(this.input),e=[];let s=[];for(this.validate(this.input);;){t.skipWhitespace();const i=t.char;if(i===t.eof)break;if(i==nt){e.push(nt),t.readChar();continue}const[r,o]=_n(i,s);if(o){if(r==g.BACK){e.push(new w(r,0)),t.readChar();continue}e.push(...Us(s,r)),s=[],t.readChar();continue}else{const[a,c]=Fs(t);if(c){s.push(a),t.readChar();continue}const[l,h]=zn(i);if(!h)throw new Error(`encounter unexpected number. n: ${l}, current: ${i}, input: ${t.input}`);s.push({n:l})}t.readChar()}if(s.length>0)throw new Error(`remaining values ${s.toString()}`);return e}makeBlocks(t){let e=[];const s=[];if(t.length==0)return s;for(const o of t){if(o==nt){const a=bn(e),c=ae(e,a);s.push(c),e=[];continue}e.push(o)}const i=bn(e),r=ae(e,i);return s.push(r),e=[],s}validate(t){if(t.length==0)return;if(t.length>this.maxInputLength)throw new Error(`exceeded maximum input length(${t.length})`);const e=t.charAt(t.length-1),[s,i]=_n(e,[new w(g.BACK,1)]);if(!i)throw new Error(`last character: ${e} is not type value: ${t}`)}}function bn(n){if(n.length===0)return b.UNKNOWN;if(n.length===1)return n[0].has(y.DORA)?b.IMAGE_DORA:n[0].has(y.TSUMO)?b.TSUMO:b.HAND;const t=n.every(r=>r.equals(n[0])),e=n.filter(r=>r.has(y.HORIZONTAL)).length,s=n.filter(r=>r.has(y.TSUMO)||r.has(y.DORA)).length,i=n.filter(r=>r.t==g.BACK).length;if(s>0)return b.UNKNOWN;if(e==0&&i==0)return b.HAND;if(n.length===3&&i===0)return t?b.PON:e==1&&js(n)?b.CHI:b.IMAGE_DISCARD;if(n.length==4&&i==2)return b.AN_KAN;if(n.length==4&&t){if(e==1)return b.DAI_KAN;if(e==2)return b.SHO_KAN}return e==1||s==0?b.IMAGE_DISCARD:b.UNKNOWN}function js(n){const t=[...n].sort(Xt);if(t.some(s=>t[0].t!=s.t))return!1;const e=t.map(s=>s.n);for(let s=0;s<e.length-1;s++)if(e[s]!=e[s+1]-1)return!1;return!0}function Us(n,t){return n.map(e=>{const s=new w(t,e.n,e.ops);return s.isNum()&&s.n==0?s.clone({n:5,add:y.RED}):s})}function _n(n,t){const[e,s]=Ls(n);if(s)return[e,!0];if((n==="w"||n==="d")&&t.length>0){for(let r=0;r<t.length;r++){const o=t[r];n==="d"&&(t[r].n=o.n+4)}return[g.Z,!0]}return[g.BACK,!1]}function zn(n){const t=Number(n),e=0<=t&&t<=9;return[t,e]}function Fs(n){const t=Object.values(y);if(!t.includes(n.char))return[new w(g.BACK,0),!1];const e=[];for(let s=0;s<4;s++){const i=n.peekCharN(s);if(t.includes(i))e.push(i);else{const[r,o]=zn(i);if(!o)break;for(const c of e)n.readChar();const a=new w(g.BACK,r,e);if(a.has(y.RED)&&a.n!=5)throw new Error(`found ${y.RED} but number is not 5: ${r}`);if(a.has(y.DORA)&&a.has(y.TSUMO))throw new Error(`unable to specify both ${y.DORA} and ${y.TSUMO}`);return[a,!0]}}return[new w(g.BACK,0),!1]}function H(n,t=!1){const e={[E.E]:n,[E.S]:n,[E.W]:n,[E.N]:n};if(t)for(let s of Object.values(E))e[s]=structuredClone(n);return e}const Gt=n=>{let t=n.substring(0,2),e=Number(n.substring(2,3));return e==4?(e=1,t=bt(t)):e++,`${t}${e}`},Zs=n=>Gt(Gt(Gt(n))),bt=n=>{let t=Number(n.toString()[0]);return t=t%4+1,`${t}${g.Z}`},me=n=>{let t=Number(n.toString()[0]);const e=[1,4,3,2],s=e.indexOf(t);return`${e[(s+1)%e.length]}${g.Z}`},Re=(n,t,e)=>{const s=Math.abs(Number(n[0])-Number(t[0]));return I(s==1||s==2||s==3),e==b.PON?s==3?0:s==2?1:2:s==3?0:s==1?3:2};function En(n){return typeof n>"u"}function xe(n,t=0){return{a:1,c:0,e:n,b:0,d:1,f:t}}function qe(...n){n=Array.isArray(n[0])?n[0]:n;const t=(e,s)=>({a:e.a*s.a+e.c*s.b,c:e.a*s.c+e.c*s.d,e:e.a*s.e+e.c*s.f+e.e,b:e.b*s.a+e.d*s.b,d:e.b*s.c+e.d*s.d,f:e.b*s.e+e.d*s.f+e.f});switch(n.length){case 0:throw new Error("no matrices provided");case 1:return n[0];case 2:return t(n[0],n[1]);default:{const[e,s,...i]=n,r=t(e,s);return qe(r,...i)}}}function Gs(...n){return qe(...n)}const{cos:Vs,sin:Js,PI:Ys}=Math;function Xs(n,t,e){const s=Vs(n),i=Js(n),r={a:s,c:-i,e:0,b:i,d:s,f:0};return En(t)||En(e)?r:qe([xe(t,e),r,xe(-t,-e)])}function qs(n,t=void 0,e=void 0){return Xs(n*Ys/180,t,e)}function Qs(n){return ti(n)}function ti(n){return`matrix(${n.a},${n.b},${n.c},${n.d},${n.e},${n.f})`}function ei(n,t){function e(){this.constructor=n}e.prototype=t.prototype,n.prototype=new e}function we(n,t,e,s){var i=Error.call(this,n);return Object.setPrototypeOf&&Object.setPrototypeOf(i,we.prototype),i.expected=t,i.found=e,i.location=s,i.name="SyntaxError",i}ei(we,Error);function Ae(n,t,e){return e=e||" ",n.length>t?n:(t-=n.length,e+=e.repeat(t),n+e.slice(0,t))}we.prototype.format=function(n){var t="Error: "+this.message;if(this.location){var e=null,s;for(s=0;s<n.length;s++)if(n[s].source===this.location.source){e=n[s].text.split(/\r\n|\n|\r/g);break}var i=this.location.start,r=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(i):i,o=this.location.source+":"+r.line+":"+r.column;if(e){var a=this.location.end,c=Ae("",r.line.toString().length," "),l=e[i.line-1],h=i.line===a.line?a.column:l.length+1,u=h-i.column||1;t+=`
|
|
2
|
-
|
|
3
|
-
`+c+` |
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
at `+o}return t};we.buildMessage=function(n,t){var e={literal:function(l){return'"'+i(l.text)+'"'},class:function(l){var h=l.parts.map(function(u){return Array.isArray(u)?r(u[0])+"-"+r(u[1]):r(u)});return"["+(l.inverted?"^":"")+h.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(l){return l.description}};function s(l){return l.charCodeAt(0).toString(16).toUpperCase()}function i(l){return l.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(h){return"\\x0"+s(h)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(h){return"\\x"+s(h)})}function r(l){return l.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(h){return"\\x0"+s(h)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(h){return"\\x"+s(h)})}function o(l){return e[l.type](l)}function a(l){var h=l.map(o),u,d;if(h.sort(),h.length>0){for(u=1,d=1;u<h.length;u++)h[u-1]!==h[u]&&(h[d]=h[u],d++);h.length=d}switch(h.length){case 1:return h[0];case 2:return h[0]+" or "+h[1];default:return h.slice(0,-1).join(", ")+", or "+h[h.length-1]}}function c(l){return l?'"'+i(l)+'"':"end of input"}return"Expected "+a(n)+" but "+c(t)+" found."};const Ln=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",ni=Ln+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",si="["+Ln+"]["+ni+"]*",ii=new RegExp("^"+si+"$");function jn(n,t){const e=[];let s=t.exec(n);for(;s;){const i=[];i.startIndex=t.lastIndex-s[0].length;const r=s.length;for(let o=0;o<r;o++)i.push(s[o]);e.push(i),s=t.exec(n)}return e}const Qe=function(n){const t=ii.exec(n);return!(t===null||typeof t>"u")};function ri(n){return typeof n<"u"}const oi={allowBooleanAttributes:!1,unpairedTags:[]};function ai(n,t){t=Object.assign({},oi,t);const e=[];let s=!1,i=!1;n[0]==="\uFEFF"&&(n=n.substr(1));for(let r=0;r<n.length;r++)if(n[r]==="<"&&n[r+1]==="?"){if(r+=2,r=Sn(n,r),r.err)return r}else if(n[r]==="<"){let o=r;if(r++,n[r]==="!"){r=Nn(n,r);continue}else{let a=!1;n[r]==="/"&&(a=!0,r++);let c="";for(;r<n.length&&n[r]!==">"&&n[r]!==" "&&n[r]!==" "&&n[r]!==`
|
|
7
|
-
`&&n[r]!=="\r";r++)c+=n[r];if(c=c.trim(),c[c.length-1]==="/"&&(c=c.substring(0,c.length-1),r--),!gi(c)){let u;return c.trim().length===0?u="Invalid space after '<'.":u="Tag '"+c+"' is an invalid name.",k("InvalidTag",u,P(n,r))}const l=hi(n,r);if(l===!1)return k("InvalidAttr","Attributes for '"+c+"' have open quote.",P(n,r));let h=l.value;if(r=l.index,h[h.length-1]==="/"){const u=r-h.length;h=h.substring(0,h.length-1);const d=In(h,t);if(d===!0)s=!0;else return k(d.err.code,d.err.msg,P(n,u+d.err.line))}else if(a)if(l.tagClosed){if(h.trim().length>0)return k("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",P(n,o));if(e.length===0)return k("InvalidTag","Closing tag '"+c+"' has not been opened.",P(n,o));{const u=e.pop();if(c!==u.tagName){let d=P(n,u.tagStartPos);return k("InvalidTag","Expected closing tag '"+u.tagName+"' (opened in line "+d.line+", col "+d.col+") instead of closing tag '"+c+"'.",P(n,o))}e.length==0&&(i=!0)}}else return k("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",P(n,r));else{const u=In(h,t);if(u!==!0)return k(u.err.code,u.err.msg,P(n,r-h.length+u.err.line));if(i===!0)return k("InvalidXml","Multiple possible root nodes found.",P(n,r));t.unpairedTags.indexOf(c)!==-1||e.push({tagName:c,tagStartPos:o}),s=!0}for(r++;r<n.length;r++)if(n[r]==="<")if(n[r+1]==="!"){r++,r=Nn(n,r);continue}else if(n[r+1]==="?"){if(r=Sn(n,++r),r.err)return r}else break;else if(n[r]==="&"){const u=fi(n,r);if(u==-1)return k("InvalidChar","char '&' is not expected.",P(n,r));r=u}else if(i===!0&&!An(n[r]))return k("InvalidXml","Extra text at the end",P(n,r));n[r]==="<"&&r--}}else{if(An(n[r]))continue;return k("InvalidChar","char '"+n[r]+"' is not expected.",P(n,r))}if(s){if(e.length==1)return k("InvalidTag","Unclosed tag '"+e[0].tagName+"'.",P(n,e[0].tagStartPos));if(e.length>0)return k("InvalidXml","Invalid '"+JSON.stringify(e.map(r=>r.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return k("InvalidXml","Start tag expected.",1);return!0}function An(n){return n===" "||n===" "||n===`
|
|
8
|
-
`||n==="\r"}function Sn(n,t){const e=t;for(;t<n.length;t++)if(n[t]=="?"||n[t]==" "){const s=n.substr(e,t-e);if(t>5&&s==="xml")return k("InvalidXml","XML declaration allowed only at the start of the document.",P(n,t));if(n[t]=="?"&&n[t+1]==">"){t++;break}else continue}return t}function Nn(n,t){if(n.length>t+5&&n[t+1]==="-"&&n[t+2]==="-"){for(t+=3;t<n.length;t++)if(n[t]==="-"&&n[t+1]==="-"&&n[t+2]===">"){t+=2;break}}else if(n.length>t+8&&n[t+1]==="D"&&n[t+2]==="O"&&n[t+3]==="C"&&n[t+4]==="T"&&n[t+5]==="Y"&&n[t+6]==="P"&&n[t+7]==="E"){let e=1;for(t+=8;t<n.length;t++)if(n[t]==="<")e++;else if(n[t]===">"&&(e--,e===0))break}else if(n.length>t+9&&n[t+1]==="["&&n[t+2]==="C"&&n[t+3]==="D"&&n[t+4]==="A"&&n[t+5]==="T"&&n[t+6]==="A"&&n[t+7]==="["){for(t+=8;t<n.length;t++)if(n[t]==="]"&&n[t+1]==="]"&&n[t+2]===">"){t+=2;break}}return t}const ci='"',li="'";function hi(n,t){let e="",s="",i=!1;for(;t<n.length;t++){if(n[t]===ci||n[t]===li)s===""?s=n[t]:s!==n[t]||(s="");else if(n[t]===">"&&s===""){i=!0;break}e+=n[t]}return s!==""?!1:{value:e,index:t,tagClosed:i}}const ui=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function In(n,t){const e=jn(n,ui),s={};for(let i=0;i<e.length;i++){if(e[i][1].length===0)return k("InvalidAttr","Attribute '"+e[i][2]+"' has no space in starting.",zt(e[i]));if(e[i][3]!==void 0&&e[i][4]===void 0)return k("InvalidAttr","Attribute '"+e[i][2]+"' is without value.",zt(e[i]));if(e[i][3]===void 0&&!t.allowBooleanAttributes)return k("InvalidAttr","boolean attribute '"+e[i][2]+"' is not allowed.",zt(e[i]));const r=e[i][2];if(!pi(r))return k("InvalidAttr","Attribute '"+r+"' is an invalid name.",zt(e[i]));if(!s.hasOwnProperty(r))s[r]=1;else return k("InvalidAttr","Attribute '"+r+"' is repeated.",zt(e[i]))}return!0}function di(n,t){let e=/\d/;for(n[t]==="x"&&(t++,e=/[\da-fA-F]/);t<n.length;t++){if(n[t]===";")return t;if(!n[t].match(e))break}return-1}function fi(n,t){if(t++,n[t]===";")return-1;if(n[t]==="#")return t++,di(n,t);let e=0;for(;t<n.length;t++,e++)if(!(n[t].match(/\w/)&&e<20)){if(n[t]===";")break;return-1}return t}function k(n,t,e){return{err:{code:n,msg:t,line:e.line||e,col:e.col}}}function pi(n){return Qe(n)}function gi(n){return Qe(n)}function P(n,t){const e=n.substring(0,t).split(/\r?\n/);return{line:e.length,col:e[e.length-1].length+1}}function zt(n){return n.startIndex+n[1].length}const yi={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,t){return t},attributeValueProcessor:function(n,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,t,e){return n},captureMetaData:!1},mi=function(n){return Object.assign({},yi,n)};let ce;typeof Symbol!="function"?ce="@@xmlMetadata":ce=Symbol("XML Node Metadata");class pt{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),e!==void 0&&(this.child[this.child.length-1][ce]={startIndex:e})}static getMetaDataSymbol(){return ce}}function wi(n,t){const e={};if(n[t+3]==="O"&&n[t+4]==="C"&&n[t+5]==="T"&&n[t+6]==="Y"&&n[t+7]==="P"&&n[t+8]==="E"){t=t+9;let s=1,i=!1,r=!1,o="";for(;t<n.length;t++)if(n[t]==="<"&&!r){if(i&>(n,"!ENTITY",t)){t+=7;let a,c;[a,c,t]=bi(n,t+1),c.indexOf("&")===-1&&(e[a]={regx:RegExp(`&${a};`,"g"),val:c})}else if(i&>(n,"!ELEMENT",t)){t+=8;const{index:a}=Ei(n,t+1);t=a}else if(i&>(n,"!ATTLIST",t))t+=8;else if(i&>(n,"!NOTATION",t)){t+=9;const{index:a}=_i(n,t+1);t=a}else if(gt(n,"!--",t))r=!0;else throw new Error("Invalid DOCTYPE");s++,o=""}else if(n[t]===">"){if(r?n[t-1]==="-"&&n[t-2]==="-"&&(r=!1,s--):s--,s===0)break}else n[t]==="["?i=!0:o+=n[t];if(s!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:e,i:t}}const it=(n,t)=>{for(;t<n.length&&/\s/.test(n[t]);)t++;return t};function bi(n,t){t=it(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t])&&n[t]!=='"'&&n[t]!=="'";)e+=n[t],t++;if(tn(e),t=it(n,t),n.substring(t,t+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(n[t]==="%")throw new Error("Parameter entities are not supported");let s="";return[t,s]=re(n,t,"entity"),t--,[e,s,t]}function _i(n,t){t=it(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;tn(e),t=it(n,t);const s=n.substring(t,t+6).toUpperCase();if(s!=="SYSTEM"&&s!=="PUBLIC")throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);t+=s.length,t=it(n,t);let i=null,r=null;if(s==="PUBLIC")[t,i]=re(n,t,"publicIdentifier"),t=it(n,t),(n[t]==='"'||n[t]==="'")&&([t,r]=re(n,t,"systemIdentifier"));else if(s==="SYSTEM"&&([t,r]=re(n,t,"systemIdentifier"),!r))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:e,publicIdentifier:i,systemIdentifier:r,index:--t}}function re(n,t,e){let s="";const i=n[t];if(i!=='"'&&i!=="'")throw new Error(`Expected quoted string, found "${i}"`);for(t++;t<n.length&&n[t]!==i;)s+=n[t],t++;if(n[t]!==i)throw new Error(`Unterminated ${e} value`);return t++,[t,s]}function Ei(n,t){t=it(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;if(!tn(e))throw new Error(`Invalid element name: "${e}"`);t=it(n,t);let s="";if(n[t]==="E"&>(n,"MPTY",t))t+=4;else if(n[t]==="A"&>(n,"NY",t))t+=2;else if(n[t]==="("){for(t++;t<n.length&&n[t]!==")";)s+=n[t],t++;if(n[t]!==")")throw new Error("Unterminated content model")}else throw new Error(`Invalid Element Expression, found "${n[t]}"`);return{elementName:e,contentModel:s.trim(),index:t}}function gt(n,t,e){for(let s=0;s<t.length;s++)if(t[s]!==n[e+s+1])return!1;return!0}function tn(n){if(Qe(n))return n;throw new Error(`Invalid entity name ${n}`)}const Ai=/^[-+]?0x[a-fA-F0-9]+$/,Si=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Ni={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Ii(n,t={}){if(t=Object.assign({},Ni,t),!n||typeof n!="string")return n;let e=n.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return n;if(n==="0")return 0;if(t.hex&&Ai.test(e))return ki(e,16);if(e.search(/.+[eE].+/)!==-1)return Ti(n,e,t);{const s=Si.exec(e);if(s){const i=s[1]||"",r=s[2];let o=Oi(s[3]);const a=i?n[r.length+1]===".":n[r.length]===".";if(!t.leadingZeros&&(r.length>1||r.length===1&&!a))return n;{const c=Number(e),l=String(c);if(c===0)return c;if(l.search(/[eE]/)!==-1)return t.eNotation?c:n;if(e.indexOf(".")!==-1)return l==="0"||l===o||l===`${i}${o}`?c:n;let h=r?o:e;return r?h===l||i+h===l?c:n:h===l||h===i+l?c:n}}else return n}}const vi=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Ti(n,t,e){if(!e.eNotation)return n;const s=t.match(vi);if(s){let i=s[1]||"";const r=s[3].indexOf("e")===-1?"E":"e",o=s[2],a=i?n[o.length+1]===r:n[o.length]===r;return o.length>1&&a?n:o.length===1&&(s[3].startsWith(`.${r}`)||s[3][0]===r)?Number(t):e.leadingZeros&&!a?(t=(s[1]||"")+s[3],Number(t)):n}else return n}function Oi(n){return n&&n.indexOf(".")!==-1&&(n=n.replace(/0+$/,""),n==="."?n="0":n[0]==="."?n="0"+n:n[n.length-1]==="."&&(n=n.substring(0,n.length-1))),n}function ki(n,t){if(parseInt)return parseInt(n,t);if(Number.parseInt)return Number.parseInt(n,t);if(window&&window.parseInt)return window.parseInt(n,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function Un(n){return typeof n=="function"?n:Array.isArray(n)?t=>{for(const e of n)if(typeof e=="string"&&t===e||e instanceof RegExp&&e.test(t))return!0}:()=>!1}class Ci{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,16))}},this.addExternalEntities=Ri,this.parseXml=Hi,this.parseTextData=xi,this.resolveNameSpace=Mi,this.buildAttributesMap=Pi,this.isItStopNode=Ki,this.replaceEntitiesValue=Bi,this.readStopNodeData=Li,this.saveTextToParentTag=Di,this.addChild=Wi,this.ignoreAttributesFn=Un(this.options.ignoreAttributes)}}function Ri(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];this.lastEntities[s]={regex:new RegExp("&"+s+";","g"),val:n[s]}}}function xi(n,t,e,s,i,r,o){if(n!==void 0&&(this.options.trimValues&&!s&&(n=n.trim()),n.length>0)){o||(n=this.replaceEntitiesValue(n));const a=this.options.tagValueProcessor(t,n,e,i,r);return a==null?n:typeof a!=typeof n||a!==n?a:this.options.trimValues?$e(n,this.options.parseTagValue,this.options.numberParseOptions):n.trim()===n?$e(n,this.options.parseTagValue,this.options.numberParseOptions):n}}function Mi(n){if(this.options.removeNSPrefix){const t=n.split(":"),e=n.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return"";t.length===2&&(n=e+t[1])}return n}const $i=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Pi(n,t,e){if(this.options.ignoreAttributes!==!0&&typeof n=="string"){const s=jn(n,$i),i=s.length,r={};for(let o=0;o<i;o++){const a=this.resolveNameSpace(s[o][1]);if(this.ignoreAttributesFn(a,t))continue;let c=s[o][4],l=this.options.attributeNamePrefix+a;if(a.length)if(this.options.transformAttributeName&&(l=this.options.transformAttributeName(l)),l==="__proto__"&&(l="#__proto__"),c!==void 0){this.options.trimValues&&(c=c.trim()),c=this.replaceEntitiesValue(c);const h=this.options.attributeValueProcessor(a,c,t);h==null?r[l]=c:typeof h!=typeof c||h!==c?r[l]=h:r[l]=$e(c,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(r[l]=!0)}if(!Object.keys(r).length)return;if(this.options.attributesGroupName){const o={};return o[this.options.attributesGroupName]=r,o}return r}}const Hi=function(n){n=n.replace(/\r\n?/g,`
|
|
9
|
-
`);const t=new pt("!xml");let e=t,s="",i="";for(let r=0;r<n.length;r++)if(n[r]==="<")if(n[r+1]==="/"){const a=mt(n,">",r,"Closing Tag is not closed.");let c=n.substring(r+2,a).trim();if(this.options.removeNSPrefix){const u=c.indexOf(":");u!==-1&&(c=c.substr(u+1))}this.options.transformTagName&&(c=this.options.transformTagName(c)),e&&(s=this.saveTextToParentTag(s,e,i));const l=i.substring(i.lastIndexOf(".")+1);if(c&&this.options.unpairedTags.indexOf(c)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${c}>`);let h=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(h=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):h=i.lastIndexOf("."),i=i.substring(0,h),e=this.tagsNodeStack.pop(),s="",r=a}else if(n[r+1]==="?"){let a=Me(n,r,!1,"?>");if(!a)throw new Error("Pi Tag is not closed.");if(s=this.saveTextToParentTag(s,e,i),!(this.options.ignoreDeclaration&&a.tagName==="?xml"||this.options.ignorePiTags)){const c=new pt(a.tagName);c.add(this.options.textNodeName,""),a.tagName!==a.tagExp&&a.attrExpPresent&&(c[":@"]=this.buildAttributesMap(a.tagExp,i,a.tagName)),this.addChild(e,c,i,r)}r=a.closeIndex+1}else if(n.substr(r+1,3)==="!--"){const a=mt(n,"-->",r+4,"Comment is not closed.");if(this.options.commentPropName){const c=n.substring(r+4,a-2);s=this.saveTextToParentTag(s,e,i),e.add(this.options.commentPropName,[{[this.options.textNodeName]:c}])}r=a}else if(n.substr(r+1,2)==="!D"){const a=wi(n,r);this.docTypeEntities=a.entities,r=a.i}else if(n.substr(r+1,2)==="!["){const a=mt(n,"]]>",r,"CDATA is not closed.")-2,c=n.substring(r+9,a);s=this.saveTextToParentTag(s,e,i);let l=this.parseTextData(c,e.tagname,i,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?e.add(this.options.cdataPropName,[{[this.options.textNodeName]:c}]):e.add(this.options.textNodeName,l),r=a+2}else{let a=Me(n,r,this.options.removeNSPrefix),c=a.tagName;const l=a.rawTagName;let h=a.tagExp,u=a.attrExpPresent,d=a.closeIndex;this.options.transformTagName&&(c=this.options.transformTagName(c)),e&&s&&e.tagname!=="!xml"&&(s=this.saveTextToParentTag(s,e,i,!1));const p=e;p&&this.options.unpairedTags.indexOf(p.tagname)!==-1&&(e=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),c!==t.tagname&&(i+=i?"."+c:c);const f=r;if(this.isItStopNode(this.options.stopNodes,i,c)){let m="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)c[c.length-1]==="/"?(c=c.substr(0,c.length-1),i=i.substr(0,i.length-1),h=c):h=h.substr(0,h.length-1),r=a.closeIndex;else if(this.options.unpairedTags.indexOf(c)!==-1)r=a.closeIndex;else{const S=this.readStopNodeData(n,l,d+1);if(!S)throw new Error(`Unexpected end of ${l}`);r=S.i,m=S.tagContent}const A=new pt(c);c!==h&&u&&(A[":@"]=this.buildAttributesMap(h,i,c)),m&&(m=this.parseTextData(m,c,i,!0,u,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),A.add(this.options.textNodeName,m),this.addChild(e,A,i,f)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){c[c.length-1]==="/"?(c=c.substr(0,c.length-1),i=i.substr(0,i.length-1),h=c):h=h.substr(0,h.length-1),this.options.transformTagName&&(c=this.options.transformTagName(c));const m=new pt(c);c!==h&&u&&(m[":@"]=this.buildAttributesMap(h,i,c)),this.addChild(e,m,i,f),i=i.substr(0,i.lastIndexOf("."))}else{const m=new pt(c);this.tagsNodeStack.push(e),c!==h&&u&&(m[":@"]=this.buildAttributesMap(h,i,c)),this.addChild(e,m,i,f),e=m}s="",r=d}}else s+=n[r];return t.child};function Wi(n,t,e,s){this.options.captureMetaData||(s=void 0);const i=this.options.updateTag(t.tagname,e,t[":@"]);i===!1||(typeof i=="string"&&(t.tagname=i),n.addChild(t,s))}const Bi=function(n){if(this.options.processEntities){for(let t in this.docTypeEntities){const e=this.docTypeEntities[t];n=n.replace(e.regx,e.val)}for(let t in this.lastEntities){const e=this.lastEntities[t];n=n.replace(e.regex,e.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const e=this.htmlEntities[t];n=n.replace(e.regex,e.val)}n=n.replace(this.ampEntity.regex,this.ampEntity.val)}return n};function Di(n,t,e,s){return n&&(s===void 0&&(s=t.child.length===0),n=this.parseTextData(n,t.tagname,e,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,s),n!==void 0&&n!==""&&t.add(this.options.textNodeName,n),n=""),n}function Ki(n,t,e){const s="*."+e;for(const i in n){const r=n[i];if(s===r||t===r)return!0}return!1}function zi(n,t,e=">"){let s,i="";for(let r=t;r<n.length;r++){let o=n[r];if(s)o===s&&(s="");else if(o==='"'||o==="'")s=o;else if(o===e[0])if(e[1]){if(n[r+1]===e[1])return{data:i,index:r}}else return{data:i,index:r};else o===" "&&(o=" ");i+=o}}function mt(n,t,e,s){const i=n.indexOf(t,e);if(i===-1)throw new Error(s);return i+t.length-1}function Me(n,t,e,s=">"){const i=zi(n,t+1,s);if(!i)return;let r=i.data;const o=i.index,a=r.search(/\s/);let c=r,l=!0;a!==-1&&(c=r.substring(0,a),r=r.substring(a+1).trimStart());const h=c;if(e){const u=c.indexOf(":");u!==-1&&(c=c.substr(u+1),l=c!==i.data.substr(u+1))}return{tagName:c,tagExp:r,closeIndex:o,attrExpPresent:l,rawTagName:h}}function Li(n,t,e){const s=e;let i=1;for(;e<n.length;e++)if(n[e]==="<")if(n[e+1]==="/"){const r=mt(n,">",e,`${t} is not closed`);if(n.substring(e+2,r).trim()===t&&(i--,i===0))return{tagContent:n.substring(s,e),i:r};e=r}else if(n[e+1]==="?")e=mt(n,"?>",e+1,"StopNode is not closed.");else if(n.substr(e+1,3)==="!--")e=mt(n,"-->",e+3,"StopNode is not closed.");else if(n.substr(e+1,2)==="![")e=mt(n,"]]>",e,"StopNode is not closed.")-2;else{const r=Me(n,e,">");r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!=="/"&&i++,e=r.closeIndex)}}function $e(n,t,e){if(t&&typeof n=="string"){const s=n.trim();return s==="true"?!0:s==="false"?!1:Ii(n,e)}else return ri(n)?n:""}const Se=pt.getMetaDataSymbol();function ji(n,t){return Fn(n,t)}function Fn(n,t,e){let s;const i={};for(let r=0;r<n.length;r++){const o=n[r],a=Ui(o);let c="";if(e===void 0?c=a:c=e+"."+a,a===t.textNodeName)s===void 0?s=o[a]:s+=""+o[a];else{if(a===void 0)continue;if(o[a]){let l=Fn(o[a],t,c);const h=Zi(l,t);o[Se]!==void 0&&(l[Se]=o[Se]),o[":@"]?Fi(l,o[":@"],c,t):Object.keys(l).length===1&&l[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?l=l[t.textNodeName]:Object.keys(l).length===0&&(t.alwaysCreateTextNode?l[t.textNodeName]="":l=""),i[a]!==void 0&&i.hasOwnProperty(a)?(Array.isArray(i[a])||(i[a]=[i[a]]),i[a].push(l)):t.isArray(a,c,h)?i[a]=[l]:i[a]=l}}}return typeof s=="string"?s.length>0&&(i[t.textNodeName]=s):s!==void 0&&(i[t.textNodeName]=s),i}function Ui(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];if(s!==":@")return s}}function Fi(n,t,e,s){if(t){const i=Object.keys(t),r=i.length;for(let o=0;o<r;o++){const a=i[o];s.isArray(a,e+"."+a,!0,!0)?n[a]=[t[a]]:n[a]=t[a]}}}function Zi(n,t){const{textNodeName:e}=t,s=Object.keys(n).length;return!!(s===0||s===1&&(n[e]||typeof n[e]=="boolean"||n[e]===0))}class Gi{constructor(t){this.externalEntities={},this.options=mi(t)}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});const r=ai(t,e);if(r!==!0)throw Error(`${r.err.msg}:${r.err.line}:${r.err.col}`)}const s=new Ci(this.options);s.addExternalEntities(this.externalEntities);const i=s.parseXml(t);return this.options.preserveOrder||i===void 0?i:ji(i,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return pt.getMetaDataSymbol()}}const Vi=`
|
|
10
|
-
`;function Ji(n,t){let e="";return t.format&&t.indentBy.length>0&&(e=Vi),Zn(n,t,"",e)}function Zn(n,t,e,s){let i="",r=!1;for(let o=0;o<n.length;o++){const a=n[o],c=Yi(a);if(c===void 0)continue;let l="";if(e.length===0?l=c:l=`${e}.${c}`,c===t.textNodeName){let f=a[c];Xi(l,t)||(f=t.tagValueProcessor(c,f),f=Gn(f,t)),r&&(i+=s),i+=f,r=!1;continue}else if(c===t.cdataPropName){r&&(i+=s),i+=`<![CDATA[${a[c][0][t.textNodeName]}]]>`,r=!1;continue}else if(c===t.commentPropName){i+=s+`<!--${a[c][0][t.textNodeName]}-->`,r=!0;continue}else if(c[0]==="?"){const f=vn(a[":@"],t),m=c==="?xml"?"":s;let A=a[c][0][t.textNodeName];A=A.length!==0?" "+A:"",i+=m+`<${c}${A}${f}?>`,r=!0;continue}let h=s;h!==""&&(h+=t.indentBy);const u=vn(a[":@"],t),d=s+`<${c}${u}`,p=Zn(a[c],t,l,h);t.unpairedTags.indexOf(c)!==-1?t.suppressUnpairedNode?i+=d+">":i+=d+"/>":(!p||p.length===0)&&t.suppressEmptyNode?i+=d+"/>":p&&p.endsWith(">")?i+=d+`>${p}${s}</${c}>`:(i+=d+">",p&&s!==""&&(p.includes("/>")||p.includes("</"))?i+=s+t.indentBy+p+s:i+=p,i+=`</${c}>`),r=!0}return i}function Yi(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];if(n.hasOwnProperty(s)&&s!==":@")return s}}function vn(n,t){let e="";if(n&&!t.ignoreAttributes)for(let s in n){if(!n.hasOwnProperty(s))continue;let i=t.attributeValueProcessor(s,n[s]);i=Gn(i,t),i===!0&&t.suppressBooleanAttributes?e+=` ${s.substr(t.attributeNamePrefix.length)}`:e+=` ${s.substr(t.attributeNamePrefix.length)}="${i}"`}return e}function Xi(n,t){n=n.substr(0,n.length-t.textNodeName.length-1);let e=n.substr(n.lastIndexOf(".")+1);for(let s in t.stopNodes)if(t.stopNodes[s]===n||t.stopNodes[s]==="*."+e)return!0;return!1}function Gn(n,t){if(n&&n.length>0&&t.processEntities)for(let e=0;e<t.entities.length;e++){const s=t.entities[e];n=n.replace(s.regex,s.val)}return n}const qi={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(n,t){return t},attributeValueProcessor:function(n,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function lt(n){this.options=Object.assign({},qi,n),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Un(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=er),this.processTextOrObjNode=Qi,this.options.format?(this.indentate=tr,this.tagEndChar=`>
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const je="MS Gothic, sans-serif",it={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Ne={WIDTH:125,HEIGHT:27.5},xn={BASE:40},et=",",p={M:"m",P:"p",S:"s",Z:"z",BACK:"_"},m={TSUMO:"t",RON:"v",DORA:"d",HORIZONTAL:"-",RED:"r",COLOR_GRAYSCALE:"^"},b={PON:"pon",CHI:"chi",SHO_KAN:"shokan",DAI_KAN:"daikan",AN_KAN:"ankan",TSUMO:"tsumo",PAIR:"pair",ISOLATED:"isolated",THREE:"three",RUN:"run",HAND:"hand",IMAGE_DORA:"dora",IMAGE_DISCARD:"simple-discard",UNKNOWN:"unknown"},_={E:"1z",S:"2z",W:"3z",N:"4z"},C={E1:"1z1",E2:"1z2",E3:"1z3",E4:"1z4",S1:"2z1",S2:"2z2",S3:"2z3",S4:"2z4",W1:"3z1",W2:"3z2",W3:"3z3",W4:"3z4",N1:"4z1",N2:"4z2",N3:"4z3",N4:"4z4"},pe={[_.E]:"東",[_.S]:"南",[_.W]:"西",[_.N]:"北"},Ue={[C.E1]:"東1局",[C.E2]:"東2局",[C.E3]:"東3局",[C.E4]:"東4局",[C.S1]:"南1局",[C.S2]:"南2局",[C.S3]:"南3局",[C.S4]:"南4局",[C.W1]:"西1局",[C.W2]:"西2局",[C.W3]:"西3局",[C.W4]:"西4局",[C.N1]:"北1局",[C.N2]:"北2局",[C.N3]:"北3局",[C.N4]:"北4局"};function I(s,t){if(!s)throw new Error(t)}class Cs{ctx=null;strText;numText;constructor(t="東",e="2"){this.strText=t,this.numText=e}measure=(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),I(this.ctx,"context is null"));const n=this.ctx;n.font=e;const i=n.measureText(t);let r=i.width,o=i.actualBoundingBoxAscent+i.actualBoundingBoxDescent;return[r,o]};measureFontContext=(t,e)=>{const n={family:t,size:e},i=`${n.size}px ${n.family}`,[r,o]=this.measure(this.strText,i),[a,c]=this.measure(this.numText,i);return{font:{family:t,size:e},textWidth:r,textHeight:o,numWidth:a,numHeight:c}};measureTableFontContext=t=>{const e=this.measureFontContext(je,xn.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e}}class Rs{input;position;nextPosition;char;eof="\0";constructor(t){this.input=t,this.position=0,this.nextPosition=0,this.char=this.readChar()}readChar(){return this.nextPosition>=this.input.length?(this.char=this.eof,this.char):(this.char=this.input[this.nextPosition],this.position=this.nextPosition,this.nextPosition++,this.char)}peekChar(){return this.nextPosition>=this.input.length?this.eof:this.input[this.nextPosition]}peekCharN(t){if(t<0)throw new Error("arg must be positive value");return this.position+t>=this.input.length?this.eof:this.input[this.position+t]}prevChar(){return this.position>=this.input.length?this.eof:this.position>0?this.input[this.position-1]:this.eof}skipWhitespace(){for(;this.isWhitespace(this.char);)this.readChar()}isWhitespace(t){return/\s/.test(t)}}const Jt=(s,t)=>{if(s.t==t.t){if(R(s)&&R(t)){if(s.has(m.RED))return-1;if(t.has(m.RED))return 1}return s.n-t.n}const e={[p.M]:1,[p.P]:2,[p.S]:3,[p.Z]:4,[p.BACK]:5};return e[s.t]-e[t.t]},xs=(s,t)=>{const e={[m.HORIZONTAL]:1,[m.TSUMO]:2,[m.RON]:3,[m.DORA]:4,[m.COLOR_GRAYSCALE]:5,[m.RED]:6};return e[s]-e[t]},Mn=s=>{const t=[];s.forEach((n,i)=>{n.has(m.HORIZONTAL)&&t.push(i)});const e=s.filter(n=>!n.has(m.HORIZONTAL)).sort(Jt);return t.forEach(n=>{e.splice(n,0,s[n])}),e};function R(s){return s.isNum()&&s.n==5}function Ms(s){for(const t of Object.values(p))if(t==s)return[t,!0];return[p.BACK,!1]}class w{constructor(t,e,n=[]){this.t=t,this.n=e,this.ops=n}static from(t){const e=new K(t).tiles();if(e.length!=1)throw new Error(`input is not a single tile ${t}`);return e[0]}toString(){return this.t===p.BACK?this.t:`${[...this.ops].sort(xs).join("")}${this.n}${this.t}`}toJSON(){return this.toString()}clone(t){const e=t?.t??this.t,n=t?.n??this.n,i=t?.removeAll?[]:this.ops.filter(o=>Array.isArray(t?.remove)?!t.remove.includes(o):t?.remove!=o),r=new Set([...i]);return t?.add&&(Array.isArray(t.add)?t.add.forEach(o=>r.add(o)):r.add(t.add)),new w(e,n,Array.from(r))}has(t){return this.ops.includes(t)}isNum(){return this.t==p.M||this.t==p.P||this.t==p.S}equals(t){return t.t==p.BACK&&this.t==p.BACK?!0:this.t==t.t&&this.n==t.n}}class T{_tiles;_type;constructor(t,e){if(this._tiles=t,this._type=e,this.isCalled()){this._tiles=Mn(this._tiles);return}if(this._type!=b.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Jt);return}}static from(t){const e=new K(t).parse();if(e.length!=1)throw new Error(`block must be 1: ${t}`);return e[0]}static deserialize(t){const e=T.from(t.tiles),n=e.type;if(!(t.type==b.PAIR||t.type==b.ISOLATED||t.type==b.THREE||t.type==b.RUN)&&n!=t.type)throw new Error(`input type is ${t.type} but got is ${n}: ${t.tiles}`);return re(e.tiles,t.type)}serialize(){return{tiles:this.toString(),type:this.type}}toJSON(){return this.serialize()}get type(){return this._type}get tiles(){return this._tiles}is(t){return this._type==t}isCalled(){return[b.PON.toString(),b.CHI.toString(),b.DAI_KAN.toString(),b.SHO_KAN.toString(),b.AN_KAN.toString()].includes(this._type.toString())}clone(t){const e=t?.replace,n=[...this.tiles];return e&&(n[e.idx]=e.tile),re(n,this._type)}}const At=s=>{let t="";for(const e of s){if(e.t==p.BACK)return s.join("");t+=e.toString().slice(0,-1)}return`${t}${s[0].t}`},Ze=s=>{if(s.length==0)return"";let t=s[0].t,e="";for(const i of s){const r=i.t,o=r==p.BACK?i.toString():i.toString().slice(0,-1);r!=t&&t!=p.BACK&&(e+=t),t=r,e+=o}const n=s.at(-1);return n.t!=p.BACK&&(e+=n.t),e};class X extends T{constructor(t){super(t,b.CHI)}static from(t){return T.deserialize({tiles:t,type:b.CHI})}toString(){return At(this.tiles)}}class q extends T{constructor(t){super(t,b.PON)}static from(t){return T.deserialize({tiles:t,type:b.PON})}toString(){return At(this.tiles)}}class x extends T{constructor(t){const e=t.filter(i=>i.t!=p.BACK),n=e[0];if(e.length<t.length){if(R(n)){const i=new w(n.t,5);super([i.clone({add:m.RED}),i,i,i],b.AN_KAN);return}super([n,n,n,n],b.AN_KAN);return}super(t,b.AN_KAN)}get tiles(){return super.tiles}get tilesWithBack(){const t=this.tiles[0].clone({remove:m.RED}),e=R(t)?t.clone({add:m.RED}):t;return[new w(p.BACK,0),e,t,new w(p.BACK,0)]}static from(t){return T.deserialize({tiles:t,type:b.AN_KAN})}toString(){return Ze(this.tilesWithBack)}}class tt extends T{constructor(t){super(t,b.DAI_KAN)}static from(t){return T.deserialize({tiles:t,type:b.DAI_KAN})}toString(){return At(this.tiles)}}class L extends T{constructor(t){super(t,b.SHO_KAN)}static from(t){return T.deserialize({tiles:t,type:b.SHO_KAN})}static fromPon(t,e){const n=t.tiles.findIndex(r=>r.has(m.HORIZONTAL)),i=[...t.tiles];return i.splice(n,0,e.clone({add:m.HORIZONTAL})),new L(i)}toString(){return At(this.tiles)}}class D extends T{constructor(t,e){super([t,e],b.PAIR)}toString(){return At(this.tiles)}static from(t){return T.deserialize({tiles:t,type:b.PAIR})}}class Z extends T{constructor(t){super(t,b.THREE)}static from(t){return T.deserialize({tiles:t,type:b.THREE})}toString(){return At(this.tiles)}}class nt extends T{constructor(t){super(t,b.RUN)}static from(t){return T.deserialize({tiles:t,type:b.RUN})}toString(){return At(this.tiles)}}class Ge extends T{constructor(t){super([t],b.ISOLATED)}static from(t){return T.deserialize({tiles:t,type:b.ISOLATED})}toString(){return this.tiles[0].toString()}}class Ot extends T{constructor(t){super(t,b.HAND)}static from(t){return T.deserialize({tiles:t,type:b.HAND})}toString(){return Ze(this.tiles)}}class Fe extends T{constructor(t,e){super(t,e)}toString(){return this.is(b.IMAGE_DISCARD)?this.tiles.join(""):Ze(this.tiles)}}const re=(s,t)=>{switch(t){case b.CHI:return new X([s[0],s[1],s[2]]);case b.PON:return new q([s[0],s[1],s[2]]);case b.AN_KAN:return new x(s);case b.DAI_KAN:return new tt(s);case b.SHO_KAN:return new L(s);case b.THREE:return new Z(s);case b.RUN:return new nt(s);case b.PAIR:return new D(s[0],s[1]);case b.ISOLATED:return new Ge(s[0]);case b.HAND:return new Ot(s);default:return new Fe(s,t)}};class K{constructor(t){this.input=t,this.input=t.replace(/\s/g,"")}maxInputLength=600;parse(){const t=this.tileSeparators();return this.makeBlocks(t)}tiles(){return this.tileSeparators().filter(t=>t!=et)}tileSeparators(){const t=new Rs(this.input),e=[];let n=[];for(this.validate(this.input);;){t.skipWhitespace();const i=t.char;if(i===t.eof)break;if(i==et){e.push(et),t.readChar();continue}const[r,o]=pn(i,n);if(o){if(r==p.BACK){e.push(new w(r,0)),t.readChar();continue}e.push(...Ps(n,r)),n=[],t.readChar();continue}else{const[a,c]=Hs(t);if(c){n.push(a),t.readChar();continue}const[l,d]=$n(i);if(!d)throw new Error(`encounter unexpected number. n: ${l}, current: ${i}, input: ${t.input}`);n.push({n:l})}t.readChar()}if(n.length>0)throw new Error(`remaining values ${n.toString()}`);return e}makeBlocks(t){let e=[];const n=[];if(t.length==0)return n;for(const o of t){if(o==et){const a=fn(e),c=re(e,a);n.push(c),e=[];continue}e.push(o)}const i=fn(e),r=re(e,i);return n.push(r),e=[],n}validate(t){if(t.length==0)return;if(t.length>this.maxInputLength)throw new Error(`exceeded maximum input length(${t.length})`);const e=t.charAt(t.length-1),[n,i]=pn(e,[new w(p.BACK,1)]);if(!i)throw new Error(`last character: ${e} is not type value: ${t}`)}}function fn(s){if(s.length===0)return b.UNKNOWN;if(s.length===1)return s[0].has(m.DORA)?b.IMAGE_DORA:s[0].has(m.TSUMO)?b.TSUMO:b.HAND;const t=s.every(r=>r.equals(s[0])),e=s.filter(r=>r.has(m.HORIZONTAL)).length,n=s.filter(r=>r.has(m.TSUMO)||r.has(m.DORA)).length,i=s.filter(r=>r.t==p.BACK).length;if(n>0)return b.UNKNOWN;if(e==0&&i==0)return b.HAND;if(s.length===3&&i===0)return t?b.PON:e==1&&$s(s)?b.CHI:b.IMAGE_DISCARD;if(s.length==4&&i==2)return b.AN_KAN;if(s.length==4&&t){if(e==1)return b.DAI_KAN;if(e==2)return b.SHO_KAN}return e==1||n==0?b.IMAGE_DISCARD:b.UNKNOWN}function $s(s){const t=[...s].sort(Jt);if(t.some(n=>t[0].t!=n.t))return!1;const e=t.map(n=>n.n);for(let n=0;n<e.length-1;n++)if(e[n]!=e[n+1]-1)return!1;return!0}function Ps(s,t){return s.map(e=>{const n=new w(t,e.n,e.ops);return n.isNum()&&n.n==0?n.clone({n:5,add:m.RED}):n})}function pn(s,t){const[e,n]=Ms(s);if(n)return[e,!0];if((s==="w"||s==="d")&&t.length>0){for(let r=0;r<t.length;r++){const o=t[r];s==="d"&&(t[r].n=o.n+4)}return[p.Z,!0]}return[p.BACK,!1]}function $n(s){const t=Number(s),e=0<=t&&t<=9;return[t,e]}function Hs(s){const t=Object.values(m);if(!t.includes(s.char))return[new w(p.BACK,0),!1];const e=[];for(let n=0;n<4;n++){const i=s.peekCharN(n);if(t.includes(i))e.push(i);else{const[r,o]=$n(i);if(!o)break;for(const c of e)s.readChar();const a=new w(p.BACK,r,e);if(a.has(m.RED)&&a.n!=5)throw new Error(`found ${m.RED} but number is not 5: ${r}`);if(a.has(m.DORA)&&a.has(m.TSUMO))throw new Error(`unable to specify both ${m.DORA} and ${m.TSUMO}`);return[a,!0]}}return[new w(p.BACK,0),!1]}function P(s,t=!1){const e={[_.E]:s,[_.S]:s,[_.W]:s,[_.N]:s};if(t)for(let n of Object.values(_))e[n]=structuredClone(s);return e}const Gt=s=>{let t=s.substring(0,2),e=Number(s.substring(2,3));return e==4?(e=1,t=yt(t)):e++,`${t}${e}`},Ws=s=>Gt(Gt(Gt(s))),yt=s=>{let t=Number(s.toString()[0]);return t=t%4+1,`${t}${p.Z}`},ge=s=>{let t=Number(s.toString()[0]);const e=[1,4,3,2],n=e.indexOf(t);return`${e[(n+1)%e.length]}${p.Z}`},Se=(s,t,e)=>{const n=Math.abs(Number(s[0])-Number(t[0]));return I(n==1||n==2||n==3),e==b.PON?n==3?0:n==2?1:2:n==3?0:n==1?3:2};function gn(s){return typeof s>"u"}function Te(s,t=0){return{a:1,c:0,e:s,b:0,d:1,f:t}}function Ve(...s){s=Array.isArray(s[0])?s[0]:s;const t=(e,n)=>({a:e.a*n.a+e.c*n.b,c:e.a*n.c+e.c*n.d,e:e.a*n.e+e.c*n.f+e.e,b:e.b*n.a+e.d*n.b,d:e.b*n.c+e.d*n.d,f:e.b*n.e+e.d*n.f+e.f});switch(s.length){case 0:throw new Error("no matrices provided");case 1:return s[0];case 2:return t(s[0],s[1]);default:{const[e,n,...i]=s,r=t(e,n);return Ve(r,...i)}}}function Bs(...s){return Ve(...s)}const{cos:Ds,sin:Ks,PI:zs}=Math;function Ls(s,t,e){const n=Ds(s),i=Ks(s),r={a:n,c:-i,e:0,b:i,d:n,f:0};return gn(t)||gn(e)?r:Ve([Te(t,e),r,Te(-t,-e)])}function js(s,t=void 0,e=void 0){return Ls(s*zs/180,t,e)}function Us(s){return Zs(s)}function Zs(s){return`matrix(${s.a},${s.b},${s.c},${s.d},${s.e},${s.f})`}const Pn=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",Gs=Pn+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Fs="["+Pn+"]["+Gs+"]*",Vs=new RegExp("^"+Fs+"$");function Hn(s,t){const e=[];let n=t.exec(s);for(;n;){const i=[];i.startIndex=t.lastIndex-n[0].length;const r=n.length;for(let o=0;o<r;o++)i.push(n[o]);e.push(i),n=t.exec(s)}return e}const me=function(s){const t=Vs.exec(s);return!(t===null||typeof t>"u")};function Ys(s){return typeof s<"u"}const Js={allowBooleanAttributes:!1,unpairedTags:[]};function Xs(s,t){t=Object.assign({},Js,t);const e=[];let n=!1,i=!1;s[0]==="\uFEFF"&&(s=s.substr(1));for(let r=0;r<s.length;r++)if(s[r]==="<"&&s[r+1]==="?"){if(r+=2,r=yn(s,r),r.err)return r}else if(s[r]==="<"){let o=r;if(r++,s[r]==="!"){r=wn(s,r);continue}else{let a=!1;s[r]==="/"&&(a=!0,r++);let c="";for(;r<s.length&&s[r]!==">"&&s[r]!==" "&&s[r]!==" "&&s[r]!==`
|
|
2
|
+
`&&s[r]!=="\r";r++)c+=s[r];if(c=c.trim(),c[c.length-1]==="/"&&(c=c.substring(0,c.length-1),r--),!ri(c)){let h;return c.trim().length===0?h="Invalid space after '<'.":h="Tag '"+c+"' is an invalid name.",k("InvalidTag",h,$(s,r))}const l=ti(s,r);if(l===!1)return k("InvalidAttr","Attributes for '"+c+"' have open quote.",$(s,r));let d=l.value;if(r=l.index,d[d.length-1]==="/"){const h=r-d.length;d=d.substring(0,d.length-1);const u=bn(d,t);if(u===!0)n=!0;else return k(u.err.code,u.err.msg,$(s,h+u.err.line))}else if(a)if(l.tagClosed){if(d.trim().length>0)return k("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",$(s,o));if(e.length===0)return k("InvalidTag","Closing tag '"+c+"' has not been opened.",$(s,o));{const h=e.pop();if(c!==h.tagName){let u=$(s,h.tagStartPos);return k("InvalidTag","Expected closing tag '"+h.tagName+"' (opened in line "+u.line+", col "+u.col+") instead of closing tag '"+c+"'.",$(s,o))}e.length==0&&(i=!0)}}else return k("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",$(s,r));else{const h=bn(d,t);if(h!==!0)return k(h.err.code,h.err.msg,$(s,r-d.length+h.err.line));if(i===!0)return k("InvalidXml","Multiple possible root nodes found.",$(s,r));t.unpairedTags.indexOf(c)!==-1||e.push({tagName:c,tagStartPos:o}),n=!0}for(r++;r<s.length;r++)if(s[r]==="<")if(s[r+1]==="!"){r++,r=wn(s,r);continue}else if(s[r+1]==="?"){if(r=yn(s,++r),r.err)return r}else break;else if(s[r]==="&"){const h=si(s,r);if(h==-1)return k("InvalidChar","char '&' is not expected.",$(s,r));r=h}else if(i===!0&&!mn(s[r]))return k("InvalidXml","Extra text at the end",$(s,r));s[r]==="<"&&r--}}else{if(mn(s[r]))continue;return k("InvalidChar","char '"+s[r]+"' is not expected.",$(s,r))}if(n){if(e.length==1)return k("InvalidTag","Unclosed tag '"+e[0].tagName+"'.",$(s,e[0].tagStartPos));if(e.length>0)return k("InvalidXml","Invalid '"+JSON.stringify(e.map(r=>r.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return k("InvalidXml","Start tag expected.",1);return!0}function mn(s){return s===" "||s===" "||s===`
|
|
3
|
+
`||s==="\r"}function yn(s,t){const e=t;for(;t<s.length;t++)if(s[t]=="?"||s[t]==" "){const n=s.substr(e,t-e);if(t>5&&n==="xml")return k("InvalidXml","XML declaration allowed only at the start of the document.",$(s,t));if(s[t]=="?"&&s[t+1]==">"){t++;break}else continue}return t}function wn(s,t){if(s.length>t+5&&s[t+1]==="-"&&s[t+2]==="-"){for(t+=3;t<s.length;t++)if(s[t]==="-"&&s[t+1]==="-"&&s[t+2]===">"){t+=2;break}}else if(s.length>t+8&&s[t+1]==="D"&&s[t+2]==="O"&&s[t+3]==="C"&&s[t+4]==="T"&&s[t+5]==="Y"&&s[t+6]==="P"&&s[t+7]==="E"){let e=1;for(t+=8;t<s.length;t++)if(s[t]==="<")e++;else if(s[t]===">"&&(e--,e===0))break}else if(s.length>t+9&&s[t+1]==="["&&s[t+2]==="C"&&s[t+3]==="D"&&s[t+4]==="A"&&s[t+5]==="T"&&s[t+6]==="A"&&s[t+7]==="["){for(t+=8;t<s.length;t++)if(s[t]==="]"&&s[t+1]==="]"&&s[t+2]===">"){t+=2;break}}return t}const qs='"',Qs="'";function ti(s,t){let e="",n="",i=!1;for(;t<s.length;t++){if(s[t]===qs||s[t]===Qs)n===""?n=s[t]:n!==s[t]||(n="");else if(s[t]===">"&&n===""){i=!0;break}e+=s[t]}return n!==""?!1:{value:e,index:t,tagClosed:i}}const ei=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function bn(s,t){const e=Hn(s,ei),n={};for(let i=0;i<e.length;i++){if(e[i][1].length===0)return k("InvalidAttr","Attribute '"+e[i][2]+"' has no space in starting.",Dt(e[i]));if(e[i][3]!==void 0&&e[i][4]===void 0)return k("InvalidAttr","Attribute '"+e[i][2]+"' is without value.",Dt(e[i]));if(e[i][3]===void 0&&!t.allowBooleanAttributes)return k("InvalidAttr","boolean attribute '"+e[i][2]+"' is not allowed.",Dt(e[i]));const r=e[i][2];if(!ii(r))return k("InvalidAttr","Attribute '"+r+"' is an invalid name.",Dt(e[i]));if(!n.hasOwnProperty(r))n[r]=1;else return k("InvalidAttr","Attribute '"+r+"' is repeated.",Dt(e[i]))}return!0}function ni(s,t){let e=/\d/;for(s[t]==="x"&&(t++,e=/[\da-fA-F]/);t<s.length;t++){if(s[t]===";")return t;if(!s[t].match(e))break}return-1}function si(s,t){if(t++,s[t]===";")return-1;if(s[t]==="#")return t++,ni(s,t);let e=0;for(;t<s.length;t++,e++)if(!(s[t].match(/\w/)&&e<20)){if(s[t]===";")break;return-1}return t}function k(s,t,e){return{err:{code:s,msg:t,line:e.line||e,col:e.col}}}function ii(s){return me(s)}function ri(s){return me(s)}function $(s,t){const e=s.substring(0,t).split(/\r?\n/);return{line:e.length,col:e[e.length-1].length+1}}function Dt(s){return s.startIndex+s[1].length}const oi={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(s,t){return t},attributeValueProcessor:function(s,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(s,t,e){return s},captureMetaData:!1},ai=function(s){return Object.assign({},oi,s)};let oe;typeof Symbol!="function"?oe="@@xmlMetadata":oe=Symbol("XML Node Metadata");class ft{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),e!==void 0&&(this.child[this.child.length-1][oe]={startIndex:e})}static getMetaDataSymbol(){return oe}}class ci{constructor(t){this.suppressValidationErr=!t}readDocType(t,e){const n={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let i=1,r=!1,o=!1,a="";for(;e<t.length;e++)if(t[e]==="<"&&!o){if(r&<(t,"!ENTITY",e)){e+=7;let c,l;[c,l,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),l.indexOf("&")===-1&&(n[c]={regx:RegExp(`&${c};`,"g"),val:l})}else if(r&<(t,"!ELEMENT",e)){e+=8;const{index:c}=this.readElementExp(t,e+1);e=c}else if(r&<(t,"!ATTLIST",e))e+=8;else if(r&<(t,"!NOTATION",e)){e+=9;const{index:c}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=c}else if(lt(t,"!--",e))o=!0;else throw new Error("Invalid DOCTYPE");i++,a=""}else if(t[e]===">"){if(o?t[e-1]==="-"&&t[e-2]==="-"&&(o=!1,i--):i--,i===0)break}else t[e]==="["?r=!0:a+=t[e];if(i!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:n,i:e}}readEntityExp(t,e){e=W(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e])&&t[e]!=='"'&&t[e]!=="'";)n+=t[e],e++;if(Kt(n),e=W(t,e),!this.suppressValidationErr){if(t.substring(e,e+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(t[e]==="%")throw new Error("Parameter entities are not supported")}let i="";return[e,i]=this.readIdentifierVal(t,e,"entity"),e--,[n,i,e]}readNotationExp(t,e){e=W(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;!this.suppressValidationErr&&Kt(n),e=W(t,e);const i=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&i!=="SYSTEM"&&i!=="PUBLIC")throw new Error(`Expected SYSTEM or PUBLIC, found "${i}"`);e+=i.length,e=W(t,e);let r=null,o=null;if(i==="PUBLIC")[e,r]=this.readIdentifierVal(t,e,"publicIdentifier"),e=W(t,e),(t[e]==='"'||t[e]==="'")&&([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"));else if(i==="SYSTEM"&&([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!o))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:n,publicIdentifier:r,systemIdentifier:o,index:--e}}readIdentifierVal(t,e,n){let i="";const r=t[e];if(r!=='"'&&r!=="'")throw new Error(`Expected quoted string, found "${r}"`);for(e++;e<t.length&&t[e]!==r;)i+=t[e],e++;if(t[e]!==r)throw new Error(`Unterminated ${n} value`);return e++,[e,i]}readElementExp(t,e){e=W(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;if(!this.suppressValidationErr&&!me(n))throw new Error(`Invalid element name: "${n}"`);e=W(t,e);let i="";if(t[e]==="E"&<(t,"MPTY",e))e+=4;else if(t[e]==="A"&<(t,"NY",e))e+=2;else if(t[e]==="("){for(e++;e<t.length&&t[e]!==")";)i+=t[e],e++;if(t[e]!==")")throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:n,contentModel:i.trim(),index:e}}readAttlistExp(t,e){e=W(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;Kt(n),e=W(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;if(!Kt(i))throw new Error(`Invalid attribute name: "${i}"`);e=W(t,e);let r="";if(t.substring(e,e+8).toUpperCase()==="NOTATION"){if(r="NOTATION",e+=8,e=W(t,e),t[e]!=="(")throw new Error(`Expected '(', found "${t[e]}"`);e++;let a=[];for(;e<t.length&&t[e]!==")";){let c="";for(;e<t.length&&t[e]!=="|"&&t[e]!==")";)c+=t[e],e++;if(c=c.trim(),!Kt(c))throw new Error(`Invalid notation name: "${c}"`);a.push(c),t[e]==="|"&&(e++,e=W(t,e))}if(t[e]!==")")throw new Error("Unterminated list of notations");e++,r+=" ("+a.join("|")+")"}else{for(;e<t.length&&!/\s/.test(t[e]);)r+=t[e],e++;const a=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!a.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}e=W(t,e);let o="";return t.substring(e,e+8).toUpperCase()==="#REQUIRED"?(o="#REQUIRED",e+=8):t.substring(e,e+7).toUpperCase()==="#IMPLIED"?(o="#IMPLIED",e+=7):[e,o]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:n,attributeName:i,attributeType:r,defaultValue:o,index:e}}}const W=(s,t)=>{for(;t<s.length&&/\s/.test(s[t]);)t++;return t};function lt(s,t,e){for(let n=0;n<t.length;n++)if(t[n]!==s[e+n+1])return!1;return!0}function Kt(s){if(me(s))return s;throw new Error(`Invalid entity name ${s}`)}const li=/^[-+]?0x[a-fA-F0-9]+$/,hi=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,di={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function ui(s,t={}){if(t=Object.assign({},di,t),!s||typeof s!="string")return s;let e=s.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return s;if(s==="0")return 0;if(t.hex&&li.test(e))return mi(e,16);if(e.search(/.+[eE].+/)!==-1)return pi(s,e,t);{const n=hi.exec(e);if(n){const i=n[1]||"",r=n[2];let o=gi(n[3]);const a=i?s[r.length+1]===".":s[r.length]===".";if(!t.leadingZeros&&(r.length>1||r.length===1&&!a))return s;{const c=Number(e),l=String(c);if(c===0)return c;if(l.search(/[eE]/)!==-1)return t.eNotation?c:s;if(e.indexOf(".")!==-1)return l==="0"||l===o||l===`${i}${o}`?c:s;let d=r?o:e;return r?d===l||i+d===l?c:s:d===l||d===i+l?c:s}}else return s}}const fi=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function pi(s,t,e){if(!e.eNotation)return s;const n=t.match(fi);if(n){let i=n[1]||"";const r=n[3].indexOf("e")===-1?"E":"e",o=n[2],a=i?s[o.length+1]===r:s[o.length]===r;return o.length>1&&a?s:o.length===1&&(n[3].startsWith(`.${r}`)||n[3][0]===r)?Number(t):e.leadingZeros&&!a?(t=(n[1]||"")+n[3],Number(t)):s}else return s}function gi(s){return s&&s.indexOf(".")!==-1&&(s=s.replace(/0+$/,""),s==="."?s="0":s[0]==="."?s="0"+s:s[s.length-1]==="."&&(s=s.substring(0,s.length-1))),s}function mi(s,t){if(parseInt)return parseInt(s,t);if(Number.parseInt)return Number.parseInt(s,t);if(window&&window.parseInt)return window.parseInt(s,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function Wn(s){return typeof s=="function"?s:Array.isArray(s)?t=>{for(const e of s)if(typeof e=="string"&&t===e||e instanceof RegExp&&e.test(t))return!0}:()=>!1}class yi{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,n)=>String.fromCodePoint(Number.parseInt(n,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,n)=>String.fromCodePoint(Number.parseInt(n,16))}},this.addExternalEntities=wi,this.parseXml=vi,this.parseTextData=bi,this.resolveNameSpace=Ei,this.buildAttributesMap=Ai,this.isItStopNode=Ti,this.replaceEntitiesValue=Ni,this.readStopNodeData=ki,this.saveTextToParentTag=Si,this.addChild=Ii,this.ignoreAttributesFn=Wn(this.options.ignoreAttributes)}}function wi(s){const t=Object.keys(s);for(let e=0;e<t.length;e++){const n=t[e];this.lastEntities[n]={regex:new RegExp("&"+n+";","g"),val:s[n]}}}function bi(s,t,e,n,i,r,o){if(s!==void 0&&(this.options.trimValues&&!n&&(s=s.trim()),s.length>0)){o||(s=this.replaceEntitiesValue(s));const a=this.options.tagValueProcessor(t,s,e,i,r);return a==null?s:typeof a!=typeof s||a!==s?a:this.options.trimValues?ke(s,this.options.parseTagValue,this.options.numberParseOptions):s.trim()===s?ke(s,this.options.parseTagValue,this.options.numberParseOptions):s}}function Ei(s){if(this.options.removeNSPrefix){const t=s.split(":"),e=s.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return"";t.length===2&&(s=e+t[1])}return s}const _i=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Ai(s,t,e){if(this.options.ignoreAttributes!==!0&&typeof s=="string"){const n=Hn(s,_i),i=n.length,r={};for(let o=0;o<i;o++){const a=this.resolveNameSpace(n[o][1]);if(this.ignoreAttributesFn(a,t))continue;let c=n[o][4],l=this.options.attributeNamePrefix+a;if(a.length)if(this.options.transformAttributeName&&(l=this.options.transformAttributeName(l)),l==="__proto__"&&(l="#__proto__"),c!==void 0){this.options.trimValues&&(c=c.trim()),c=this.replaceEntitiesValue(c);const d=this.options.attributeValueProcessor(a,c,t);d==null?r[l]=c:typeof d!=typeof c||d!==c?r[l]=d:r[l]=ke(c,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(r[l]=!0)}if(!Object.keys(r).length)return;if(this.options.attributesGroupName){const o={};return o[this.options.attributesGroupName]=r,o}return r}}const vi=function(s){s=s.replace(/\r\n?/g,`
|
|
4
|
+
`);const t=new ft("!xml");let e=t,n="",i="";const r=new ci(this.options.processEntities);for(let o=0;o<s.length;o++)if(s[o]==="<")if(s[o+1]==="/"){const c=gt(s,">",o,"Closing Tag is not closed.");let l=s.substring(o+2,c).trim();if(this.options.removeNSPrefix){const u=l.indexOf(":");u!==-1&&(l=l.substr(u+1))}this.options.transformTagName&&(l=this.options.transformTagName(l)),e&&(n=this.saveTextToParentTag(n,e,i));const d=i.substring(i.lastIndexOf(".")+1);if(l&&this.options.unpairedTags.indexOf(l)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${l}>`);let h=0;d&&this.options.unpairedTags.indexOf(d)!==-1?(h=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):h=i.lastIndexOf("."),i=i.substring(0,h),e=this.tagsNodeStack.pop(),n="",o=c}else if(s[o+1]==="?"){let c=Oe(s,o,!1,"?>");if(!c)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,e,i),!(this.options.ignoreDeclaration&&c.tagName==="?xml"||this.options.ignorePiTags)){const l=new ft(c.tagName);l.add(this.options.textNodeName,""),c.tagName!==c.tagExp&&c.attrExpPresent&&(l[":@"]=this.buildAttributesMap(c.tagExp,i,c.tagName)),this.addChild(e,l,i,o)}o=c.closeIndex+1}else if(s.substr(o+1,3)==="!--"){const c=gt(s,"-->",o+4,"Comment is not closed.");if(this.options.commentPropName){const l=s.substring(o+4,c-2);n=this.saveTextToParentTag(n,e,i),e.add(this.options.commentPropName,[{[this.options.textNodeName]:l}])}o=c}else if(s.substr(o+1,2)==="!D"){const c=r.readDocType(s,o);this.docTypeEntities=c.entities,o=c.i}else if(s.substr(o+1,2)==="!["){const c=gt(s,"]]>",o,"CDATA is not closed.")-2,l=s.substring(o+9,c);n=this.saveTextToParentTag(n,e,i);let d=this.parseTextData(l,e.tagname,i,!0,!1,!0,!0);d==null&&(d=""),this.options.cdataPropName?e.add(this.options.cdataPropName,[{[this.options.textNodeName]:l}]):e.add(this.options.textNodeName,d),o=c+2}else{let c=Oe(s,o,this.options.removeNSPrefix),l=c.tagName;const d=c.rawTagName;let h=c.tagExp,u=c.attrExpPresent,g=c.closeIndex;this.options.transformTagName&&(l=this.options.transformTagName(l)),e&&n&&e.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,e,i,!1));const f=e;f&&this.options.unpairedTags.indexOf(f.tagname)!==-1&&(e=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),l!==t.tagname&&(i+=i?"."+l:l);const y=o;if(this.isItStopNode(this.options.stopNodes,i,l)){let E="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)l[l.length-1]==="/"?(l=l.substr(0,l.length-1),i=i.substr(0,i.length-1),h=l):h=h.substr(0,h.length-1),o=c.closeIndex;else if(this.options.unpairedTags.indexOf(l)!==-1)o=c.closeIndex;else{const O=this.readStopNodeData(s,d,g+1);if(!O)throw new Error(`Unexpected end of ${d}`);o=O.i,E=O.tagContent}const A=new ft(l);l!==h&&u&&(A[":@"]=this.buildAttributesMap(h,i,l)),E&&(E=this.parseTextData(E,l,i,!0,u,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),A.add(this.options.textNodeName,E),this.addChild(e,A,i,y)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){l[l.length-1]==="/"?(l=l.substr(0,l.length-1),i=i.substr(0,i.length-1),h=l):h=h.substr(0,h.length-1),this.options.transformTagName&&(l=this.options.transformTagName(l));const E=new ft(l);l!==h&&u&&(E[":@"]=this.buildAttributesMap(h,i,l)),this.addChild(e,E,i,y),i=i.substr(0,i.lastIndexOf("."))}else{const E=new ft(l);this.tagsNodeStack.push(e),l!==h&&u&&(E[":@"]=this.buildAttributesMap(h,i,l)),this.addChild(e,E,i,y),e=E}n="",o=g}}else n+=s[o];return t.child};function Ii(s,t,e,n){this.options.captureMetaData||(n=void 0);const i=this.options.updateTag(t.tagname,e,t[":@"]);i===!1||(typeof i=="string"&&(t.tagname=i),s.addChild(t,n))}const Ni=function(s){if(this.options.processEntities){for(let t in this.docTypeEntities){const e=this.docTypeEntities[t];s=s.replace(e.regx,e.val)}for(let t in this.lastEntities){const e=this.lastEntities[t];s=s.replace(e.regex,e.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const e=this.htmlEntities[t];s=s.replace(e.regex,e.val)}s=s.replace(this.ampEntity.regex,this.ampEntity.val)}return s};function Si(s,t,e,n){return s&&(n===void 0&&(n=t.child.length===0),s=this.parseTextData(s,t.tagname,e,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,n),s!==void 0&&s!==""&&t.add(this.options.textNodeName,s),s=""),s}function Ti(s,t,e){const n="*."+e;for(const i in s){const r=s[i];if(n===r||t===r)return!0}return!1}function Oi(s,t,e=">"){let n,i="";for(let r=t;r<s.length;r++){let o=s[r];if(n)o===n&&(n="");else if(o==='"'||o==="'")n=o;else if(o===e[0])if(e[1]){if(s[r+1]===e[1])return{data:i,index:r}}else return{data:i,index:r};else o===" "&&(o=" ");i+=o}}function gt(s,t,e,n){const i=s.indexOf(t,e);if(i===-1)throw new Error(n);return i+t.length-1}function Oe(s,t,e,n=">"){const i=Oi(s,t+1,n);if(!i)return;let r=i.data;const o=i.index,a=r.search(/\s/);let c=r,l=!0;a!==-1&&(c=r.substring(0,a),r=r.substring(a+1).trimStart());const d=c;if(e){const h=c.indexOf(":");h!==-1&&(c=c.substr(h+1),l=c!==i.data.substr(h+1))}return{tagName:c,tagExp:r,closeIndex:o,attrExpPresent:l,rawTagName:d}}function ki(s,t,e){const n=e;let i=1;for(;e<s.length;e++)if(s[e]==="<")if(s[e+1]==="/"){const r=gt(s,">",e,`${t} is not closed`);if(s.substring(e+2,r).trim()===t&&(i--,i===0))return{tagContent:s.substring(n,e),i:r};e=r}else if(s[e+1]==="?")e=gt(s,"?>",e+1,"StopNode is not closed.");else if(s.substr(e+1,3)==="!--")e=gt(s,"-->",e+3,"StopNode is not closed.");else if(s.substr(e+1,2)==="![")e=gt(s,"]]>",e,"StopNode is not closed.")-2;else{const r=Oe(s,e,">");r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!=="/"&&i++,e=r.closeIndex)}}function ke(s,t,e){if(t&&typeof s=="string"){const n=s.trim();return n==="true"?!0:n==="false"?!1:ui(s,e)}else return Ys(s)?s:""}const Ee=ft.getMetaDataSymbol();function Ci(s,t){return Bn(s,t)}function Bn(s,t,e){let n;const i={};for(let r=0;r<s.length;r++){const o=s[r],a=Ri(o);let c="";if(e===void 0?c=a:c=e+"."+a,a===t.textNodeName)n===void 0?n=o[a]:n+=""+o[a];else{if(a===void 0)continue;if(o[a]){let l=Bn(o[a],t,c);const d=Mi(l,t);o[Ee]!==void 0&&(l[Ee]=o[Ee]),o[":@"]?xi(l,o[":@"],c,t):Object.keys(l).length===1&&l[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?l=l[t.textNodeName]:Object.keys(l).length===0&&(t.alwaysCreateTextNode?l[t.textNodeName]="":l=""),i[a]!==void 0&&i.hasOwnProperty(a)?(Array.isArray(i[a])||(i[a]=[i[a]]),i[a].push(l)):t.isArray(a,c,d)?i[a]=[l]:i[a]=l}}}return typeof n=="string"?n.length>0&&(i[t.textNodeName]=n):n!==void 0&&(i[t.textNodeName]=n),i}function Ri(s){const t=Object.keys(s);for(let e=0;e<t.length;e++){const n=t[e];if(n!==":@")return n}}function xi(s,t,e,n){if(t){const i=Object.keys(t),r=i.length;for(let o=0;o<r;o++){const a=i[o];n.isArray(a,e+"."+a,!0,!0)?s[a]=[t[a]]:s[a]=t[a]}}}function Mi(s,t){const{textNodeName:e}=t,n=Object.keys(s).length;return!!(n===0||n===1&&(s[e]||typeof s[e]=="boolean"||s[e]===0))}class $i{constructor(t){this.externalEntities={},this.options=ai(t)}parse(t,e){if(typeof t!="string"&&t.toString)t=t.toString();else if(typeof t!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});const r=Xs(t,e);if(r!==!0)throw Error(`${r.err.msg}:${r.err.line}:${r.err.col}`)}const n=new yi(this.options);n.addExternalEntities(this.externalEntities);const i=n.parseXml(t);return this.options.preserveOrder||i===void 0?i:Ci(i,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return ft.getMetaDataSymbol()}}const Pi=`
|
|
5
|
+
`;function Hi(s,t){let e="";return t.format&&t.indentBy.length>0&&(e=Pi),Dn(s,t,"",e)}function Dn(s,t,e,n){let i="",r=!1;for(let o=0;o<s.length;o++){const a=s[o],c=Wi(a);if(c===void 0)continue;let l="";if(e.length===0?l=c:l=`${e}.${c}`,c===t.textNodeName){let f=a[c];Bi(l,t)||(f=t.tagValueProcessor(c,f),f=Kn(f,t)),r&&(i+=n),i+=f,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 f=En(a[":@"],t),y=c==="?xml"?"":n;let E=a[c][0][t.textNodeName];E=E.length!==0?" "+E:"",i+=y+`<${c}${E}${f}?>`,r=!0;continue}let d=n;d!==""&&(d+=t.indentBy);const h=En(a[":@"],t),u=n+`<${c}${h}`,g=Dn(a[c],t,l,d);t.unpairedTags.indexOf(c)!==-1?t.suppressUnpairedNode?i+=u+">":i+=u+"/>":(!g||g.length===0)&&t.suppressEmptyNode?i+=u+"/>":g&&g.endsWith(">")?i+=u+`>${g}${n}</${c}>`:(i+=u+">",g&&n!==""&&(g.includes("/>")||g.includes("</"))?i+=n+t.indentBy+g+n:i+=g,i+=`</${c}>`),r=!0}return i}function Wi(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 En(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=Kn(i,t),i===!0&&t.suppressBooleanAttributes?e+=` ${n.substr(t.attributeNamePrefix.length)}`:e+=` ${n.substr(t.attributeNamePrefix.length)}="${i}"`}return e}function Bi(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 Kn(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 Di={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(s,t){return t},attributeValueProcessor:function(s,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function at(s){this.options=Object.assign({},Di,s),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Wn(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Li),this.processTextOrObjNode=Ki,this.options.format?(this.indentate=zi,this.tagEndChar=`>
|
|
11
6
|
`,this.newLine=`
|
|
12
|
-
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}lt.prototype.build=function(n){return this.options.preserveOrder?Ji(n,this.options):(Array.isArray(n)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(n={[this.options.arrayNodeName]:n}),this.j2x(n,0,[]).val)};lt.prototype.j2x=function(n,t,e){let s="",i="";const r=e.join(".");for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))if(typeof n[o]>"u")this.isAttribute(o)&&(i+="");else if(n[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+="":o[0]==="?"?i+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(n[o]instanceof Date)i+=this.buildTextValNode(n[o],o,"",t);else if(typeof n[o]!="object"){const a=this.isAttribute(o);if(a&&!this.ignoreAttributesFn(a,r))s+=this.buildAttrPairStr(a,""+n[o]);else if(!a)if(o===this.options.textNodeName){let c=this.options.tagValueProcessor(o,""+n[o]);i+=this.replaceEntitiesValue(c)}else i+=this.buildTextValNode(n[o],o,"",t)}else if(Array.isArray(n[o])){const a=n[o].length;let c="",l="";for(let h=0;h<a;h++){const u=n[o][h];if(!(typeof u>"u"))if(u===null)o[0]==="?"?i+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(typeof u=="object")if(this.options.oneListGroup){const d=this.j2x(u,t+1,e.concat(o));c+=d.val,this.options.attributesGroupName&&u.hasOwnProperty(this.options.attributesGroupName)&&(l+=d.attrStr)}else c+=this.processTextOrObjNode(u,o,t,e);else if(this.options.oneListGroup){let d=this.options.tagValueProcessor(o,u);d=this.replaceEntitiesValue(d),c+=d}else c+=this.buildTextValNode(u,o,"",t)}this.options.oneListGroup&&(c=this.buildObjectNode(c,o,l,t)),i+=c}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const a=Object.keys(n[o]),c=a.length;for(let l=0;l<c;l++)s+=this.buildAttrPairStr(a[l],""+n[o][a[l]])}else i+=this.processTextOrObjNode(n[o],o,t,e);return{attrStr:s,val:i}};lt.prototype.buildAttrPairStr=function(n,t){return t=this.options.attributeValueProcessor(n,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+n:" "+n+'="'+t+'"'};function Qi(n,t,e,s){const i=this.j2x(n,e+1,s.concat(t));return n[this.options.textNodeName]!==void 0&&Object.keys(n).length===1?this.buildTextValNode(n[this.options.textNodeName],t,i.attrStr,e):this.buildObjectNode(i.val,t,i.attrStr,e)}lt.prototype.buildObjectNode=function(n,t,e,s){if(n==="")return t[0]==="?"?this.indentate(s)+"<"+t+e+"?"+this.tagEndChar:this.indentate(s)+"<"+t+e+this.closeTag(t)+this.tagEndChar;{let i="</"+t+this.tagEndChar,r="";return t[0]==="?"&&(r="?",i=""),(e||e==="")&&n.indexOf("<")===-1?this.indentate(s)+"<"+t+e+r+">"+n+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&r.length===0?this.indentate(s)+`<!--${n}-->`+this.newLine:this.indentate(s)+"<"+t+e+r+this.tagEndChar+n+this.indentate(s)+i}};lt.prototype.closeTag=function(n){let t="";return this.options.unpairedTags.indexOf(n)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${n}`,t};lt.prototype.buildTextValNode=function(n,t,e,s){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(s)+`<![CDATA[${n}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(s)+`<!--${n}-->`+this.newLine;if(t[0]==="?")return this.indentate(s)+"<"+t+e+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(t,n);return i=this.replaceEntitiesValue(i),i===""?this.indentate(s)+"<"+t+e+this.closeTag(t)+this.tagEndChar:this.indentate(s)+"<"+t+e+">"+i+"</"+t+this.tagEndChar}};lt.prototype.replaceEntitiesValue=function(n){if(n&&n.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const e=this.options.entities[t];n=n.replace(e.regex,e.val)}return n};function tr(n){return this.options.indentBy.repeat(n)}function er(n){return n.startsWith(this.options.attributeNamePrefix)&&n!==this.options.textNodeName?n.substr(this.attrPrefixLen):!1}class ht{constructor(t){_(this,"type");_(this,"attrs",{});_(this,"styles",{});_(this,"deleteMarker",!1);this.type=t}dx(t){return this.attrs.x==null?this.attrs.x=t:this.attrs.x+=t,this}dy(t){return this.attrs.y==null?this.attrs.y=t:this.attrs.y+=t,this}x(t){return this.attrs.x=t,this}y(t){return this.attrs.y=t,this}size(t,e){return this.attrs.width=t,this.attrs.height=e,this}remove(){this.deleteMarker=!0}left(...t){return`<${[this.type,Yn(this.attrs),dr(this.styles),...t].filter(e=>e!="").join(" ")}>`}right(){return`</${this.type}>`}center(){return""}toString(){return this.deleteMarker?"":`${this.left()}${this.center()}${this.right()}`}attr(t){if(typeof t=="string")return this.attrs[t]??"";for(const[e,s]of Object.entries(t))this.attrs[e]=s;return this}css(t){return this.styles={...this.styles,...t},this}svg(){return this.toString()}}class en extends ht{constructor(e){super("image");_(this,"attrs",{});this.attrs={...this.attrs,href:e}}load(e){return this.attrs.href=e,this}}class be extends ht{constructor(e){super("use");_(this,"attrs",{});this.attrs={...this.attrs,href:this.make(e)}}use(e){return this.attrs.href=`#${e}`,this}make(e){return e==null?e:`#${e}`}}class nn extends ht{constructor(){super("rect");_(this,"attrs",{})}fill(e){return this.attrs.fill=e,this}stroke(e){return this.attrs.stroke=e,this}}class _t extends ht{constructor(e=""){super("text");_(this,"attrs");_(this,"_text","");this._text=e,this.attrs={}}plain(e){return this._text=e,this}font(e){return this.attrs.fontFamily=e.family,this.attrs.fontSize=e.size,this}center(){return this._text}}let sn=class extends ht{constructor(e){super("symbol");_(this,"raw");this.raw=e}id(){return this.attr("id")}center(){return this.raw}};class v extends ht{constructor(){super("g");_(this,"children",[]);_(this,"rotateMatrix");_(this,"translateMatrix")}add(e){return this.children.push(e),this}rotate(e,s,i){return this.rotateMatrix=qs(e,s,i),this}translate(e,s){return this.translateMatrix=xe(e,s),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){const s=[this.translateMatrix,this.rotateMatrix].filter(i=>i!=null);return s.length==0?super.left():super.left(ur(Gs(s)))}each(e,s){for(let i=0;i<this.children.length;i++){const r=this.children[i];r instanceof v&&s&&r.each(e,!0),e(i,this.children)}}}const nr=['xmlns="http://www.w3.org/2000/svg"','version="1.1"','xmlns:xlink="http://www.w3.org/1999/xlink"'];class Vn extends ht{constructor(){super("svg");_(this,"children",[]);_(this,"viewBox")}add(e){return this.children.push(e),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){return`<${[this.type,...nr,Yn(this.attrs),hr(this.viewBox)].filter(s=>s!="").join(" ")}>`}viewbox(e,s,i,r){return this.viewBox={x:e,y:s,width:i,height:r},this}importSymbol(e){for(const s of fr(e))this.add(s);return this}x(e){throw new Error("unimplemented")}y(e){throw new Error("unimplemented")}dx(e){throw new Error("unimplemented")}dy(e){throw new Error("unimplemented")}each(e,s){for(let i=0;i<this.children.length;i++){const r=this.children[i];r instanceof v&&s&&r.each(e,!0),e(i,this.children)}}}function Jn(){return new Vn}const sr=Jn,ir=v,rr=en,or=be,ar=nn,cr=_t;function lr(n){return n.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function hr(n){return n==null?"":`viewBox="${n.x} ${n.y} ${n.width} ${n.height}"`}function ur(n){return n==null?"":`transform="${Qs(n)}"`}function Yn(n){return Object.entries(n).filter(([t,e])=>e!==void 0).map(([t,e])=>`${lr(t)}="${e}"`).join(" ")}function dr(n){const t=Object.entries(n).map(([e,s])=>`${e}: ${s};`).join(" ");return t!=""?`style="${t}"`:""}function*fr(n){const t=new Gi({ignoreAttributes:!1}),e=new lt({ignoreAttributes:!1}),s=t.parse(n);for(const i of s.svg.symbol){const r=e.build(i),o=new sn(r);for(const[a,c]of Object.entries(i))a.startsWith("@_")&&(o.attrs[a.substring(2)]=c);yield o}}const G=(n,t)=>{const e=z(n.tiles[0],t),s=e.baseHeight,i=e.baseWidth;if(n.is(b.SHO_KAN))return{width:i*2+s,height:Math.max(i*2,s)};const r=n.tiles.reduce((a,c)=>{const l=z(c,t).height;return l>a?l:a},0);return{width:n.tiles.reduce((a,c)=>a+z(c,t).width,0),height:r}},z=(n,t)=>{const e=parseFloat((ot.HEIGHT*t).toPrecision(5)),s=parseFloat((ot.WIDTH*t).toPrecision(5)),i=n.has(y.HORIZONTAL)?{width:e,height:s,baseWidth:s,baseHeight:e}:{width:s,height:e,w:s,baseWidth:s,baseHeight:e};return(n.has(y.TSUMO)||n.has(y.DORA))&&(i.width+=s*ot.TEXT_SCALE),i};class Rt{constructor(t={}){_(this,"tileWidth");_(this,"tileHeight");_(this,"imageHostUrl");_(this,"imageExt");_(this,"scale");_(this,"svgSprite");this.scale=t.scale??1,this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=ot.WIDTH*this.scale,this.tileHeight=ot.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getDiffTileHeightWidth(t){const e=z(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new en().load(this.buildURL(t));return this.svgSprite&&(e=new be().use(Rt.buildID(t))),t instanceof w&&t.has(y.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,s){const i=z(t,this.scale);return this.image(t).dx(e).dy(s).size(i.baseWidth,i.baseHeight)}createTextImage(t,e,s,i){const r=this.createImage(t,e,s),o=z(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,l=o.baseHeight,h=new _t().plain(i);h.size(o.baseWidth,o.baseHeight).font({family:Ge,size:a}).dx(c).dy(l);const u=new v;return u.add(r).add(h).translate(e,s),u}createRotate90Image(t,e,s,i=!1){const r=this.createImage(t,0,0),o=z(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,l=e+this.getDiffTileHeightWidth(t),h=i?s-this.getDiffTileHeightWidth(t):s,u=new v;return u.add(r).translate(l,h).rotate(90,a,c),u}createStick(t){return this.image(t)}static buildID(t){if(t==100||t==1e3)return t==100?"stick100":"stick1000";const e=t.t==g.BACK||t.has(y.RED)?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${Rt.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:e}}class rn extends Rt{constructor(){super(...arguments);_(this,"blockMargin",ot.WIDTH*ot.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const s=e instanceof M?e.tilesWithBack:e.tiles,i=new v;let r=0;for(const o of s){const a=z(o,this.scale),c=o.has(y.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),l=o.has(y.HORIZONTAL)?this.getDiffTileHeightWidth(o):0,h=c(o,r,l);i.add(h),r+=a.width}return i}createBlockPonChiKan(e){const s=e.tiles.findIndex(o=>o.has(y.HORIZONTAL));let i=0;const r=new v;if(e.type==b.SHO_KAN){let o=s;for(let a=0;a<e.tiles.length;a++)e.tiles[a].has(y.HORIZONTAL)&&(o=a);for(let a=0;a<e.tiles.length;a++){const c=z(e.tiles[a],this.scale);if(a==o)continue;if(a==s){const u=e.tiles[s],d=e.tiles[o],p=z(u,this.scale),f=this.createRotate90Image(u,0,0,!0),m=this.createRotate90Image(d,0,p.height,!0);r.add(new v().translate(i,0).add(f).add(m)),i+=p.width;continue}const l=c.width*2-c.height,h=this.createImage(e.tiles[a],i,l);i+=c.width,r.add(h)}return r}if(e.type==b.CHI){const o=e.tiles[s],a=this.createRotate90Image(o,i,this.getDiffTileHeightWidth(o));i+=z(o,this.scale).width,r.add(a);for(let c=0;c<e.tiles.length;c++){if(c==s)continue;const l=e.tiles[c],h=z(l,this.scale),u=this.createImage(l,i,0);i+=h.width,r.add(u)}return r}for(let o=0;o<e.tiles.length;o++){const a=o==s?this.createRotate90Image.bind(this):this.createImage.bind(this),c=e.tiles[o],l=o==s?this.getDiffTileHeightWidth(c):0,h=z(c,this.scale),u=a(c,i,l);i+=h.width,r.add(u)}return r}}const pr=(n,t)=>{const e=n.scale;return{[b.CHI]:function(i){const r=G(i,e),o=n.createBlockPonChiKan(i);return{...r,e:o}},[b.PON]:function(i){const r=G(i,e),o=n.createBlockPonChiKan(i);return{...r,e:o}},[b.DAI_KAN]:function(i){const r=G(i,e),o=n.createBlockPonChiKan(i);return{...r,e:o}},[b.SHO_KAN]:function(i){const r=G(i,e),o=n.createBlockPonChiKan(i);return{...r,e:o}},[b.AN_KAN]:function(i){I(i instanceof M,`block type is not ankan: ${i.type}`);const r=G(i,e),o=n.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DORA]:function(i){i=(t==null?void 0:t.doraText)==!1?new Ct([i.tiles[0].clone({remove:y.DORA})]):i;const r=G(i,e),o=new v,a=(t==null?void 0:t.doraText)===!1?n.createImage(i.tiles[0],0,0):n.createTextImage(i.tiles[0],0,0,"(ドラ)");return o.add(a),{...r,e:o}},[b.TSUMO]:function(i){i=(t==null?void 0:t.tsumoText)==!1?new Ct([i.tiles[0].clone({remove:y.TSUMO})]):i;const r=G(i,e),o=new v,a=(t==null?void 0:t.tsumoText)===!1?n.createImage(i.tiles[0],0,0):n.createTextImage(i.tiles[0],0,0,"(ツモ)");return o.add(a),{...r,e:o}},[b.HAND]:function(i){const r=G(i,e),o=n.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DISCARD]:function(i){const r=G(i,e),o=n.createBlockHandDiscard(i);return{...r,e:o}},[b.THREE]:function(i){throw new Error("three is unsupported")},[b.RUN]:function(i){throw new Error("run is unsupported")},[b.PAIR]:function(i){throw new Error("pair is unsupported")},[b.ISOLATED]:function(i){throw new Error("isolated is unsupported")},[b.UNKNOWN]:function(i){if(i.tiles.some(a=>a.has(y.TSUMO)||a.has(y.DORA)))throw new Error("found an unknown block with operator tiles");const r=G(i,e),o=n.createBlockHandDiscard(i);return{...r,e:o}}}},Tt=(n,t,e)=>{const s=pr(n,e);let i=0,r=0;const o=[];for(const u of t){const d=s[u.type],p=d(u);r+=p.width,i=p.height>i?p.height:i,o.push(p)}const a=i,c=r+(t.length-1)*n.blockMargin,l=new v;let h=0;for(const u of o){const d=a-u.height,p=new v().translate(h,d);p.add(u.e),l.add(p),h+=u.width+n.blockMargin}return{e:l,width:c,height:a}},gr=(n,t,e={},s={responsive:!1,doraText:!0,tsumoText:!0})=>{const i=new rn(e),r=Tt(i,t,s);s.responsive||n.size(r.width,r.height),n.viewbox(0,0,r.width,r.height),n.add(r.e)},Xn=()=>{const n=[0,1,2,3,4,5,6,7,8,9],t=[];for(const e of Object.values(g)){if(e==g.BACK){t.push(Rt.buildID(new w(e,0)));continue}t.push(...n.map(s=>Rt.buildID(new w(e,s))).flat())}return t},yr=n=>{const t=Xn(),e=[];return n.each((s,i)=>{const r=i[s];if(r instanceof be){const a=r.attr("href").substring(1);t.includes(a)&&e.push(a)}},!0),e},mr=n=>{const t=Xn(),e=yr(n);n.each((s,i)=>{const r=i[s];r instanceof sn&&(t.includes(r.id())&&e.includes(r.id())||r.remove())},!0)},wr=n=>{const e=[];for(let s=0;s<n.length;s+=6){const i=n.slice(s,s+6);e.push(i)}return e},Z=(n,t,e,s,i=0,r=0)=>{const o=new v().add(n);if(s==90){const a=i,c=r-e;return o.rotate(s,0,e).translate(a,c),new v().add(o)}if(s==180){const a=i+t,c=r-e;return o.rotate(s,0,e).translate(a,c),new v().add(o)}if(s==270){const a=i+e,c=r+(t-e);return o.rotate(s,0,e).translate(a,c),new v().add(o)}return new v().add(o)},ee=(n,t)=>{const e=new v,s=wr(n);for(let i=0;i<s.length;i++){let r=s[i],o=i*t.tileHeight;const a=t.createBlockHandDiscard(new Xe(r,b.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*s.length}},br=(n,t,e)=>{const s=t.font,i=t.textWidth,r=t.textHeight,o=e.sticks.dead,a=e.sticks.reach,c=Ce.WIDTH*n.scale,l=Ce.HEIGHT*n.scale;let h=i*3,u=r;const d=(c+n.tileWidth+i-h)/2,p=new _t().plain(e.round).font(s).x(d).y(0);u+=25*n.scale;const f=n.tileHeight,m=new v().size(c,f).translate(0,u),A={family:s.family,size:s.size*.7},S=n.createStick(1e3).size(c,l).x(0).y(0),R=new _t().plain(a.toString()).font(A).dx(c).dy(l),N=n.createStick(100).size(c,l).x(0).y(l+l),T=new _t().plain(o.toString()).font(A).dx(c).dy(l*3);m.add(S),m.add(R),m.add(N),m.add(T);const W=n.createImage(e.doras[0],0,0).x(c+i).y(0);m.add(W);const $=new v;return $.add(p),$.add(p),$.add(m),{e:$,width:c+n.tileWidth+i,height:u+n.tileHeight}},_r=(n,t,e=0)=>{const s=Tt(n,t.front),i=Tt(n,t.right),r=Tt(n,t.opposite),o=Tt(n,t.left),a=[s.width,i.width,r.width,o.width].reduce((m,A)=>Math.max(m,A)),c=Math.max(e+n.tileHeight*2+n.blockMargin*2,a+n.tileWidth*2+n.blockMargin),l=c,h=Z(s.e,s.width,s.height,0).translate((c-s.width)/2,l-s.height),u=Z(i.e,i.width,i.height,270).translate(c-i.height,(c-i.width)/2),d=Z(r.e,r.width,r.height,180).translate((c-r.width)/2,0),p=Z(o.e,o.width,o.height,90).translate(0,(c-o.width)/2),f=new v().size(c,l);return f.add(h),f.add(u),f.add(d),f.add(p),{e:new v().add(f),width:c,height:l}},Er=n=>{const t=Object.values(ye),e=t.indexOf(n);return[...t.slice(e),...t.slice(0,e)]},Ar=(n,t,e)=>{const s=n.tileWidth*5+n.tileHeight*1,i=t.font,r=t.textWidth,o=t.textHeight,a=t.numWidth,c=br(n,t,e);c.e.translate(s/2-c.width/2,s/2-c.height/2);const l=(Ms,wn,$s)=>{const Ps=`${Ms} ${wn}`,Hs=new _t().plain(Ps).font(i).attr($s);return{e:new v().add(Hs),width:r+a*wn.toString().length,height:o}},[h,u,d,p]=Er(e.frontPlace),f=e.scores,A=l(h,f.front,{x:s/2,y:s,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let S=l(u,f.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const R=Z(S.e,S.width,S.height,270).translate(s,s/2-S.width);let N=l(d,f.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const T=Z(N.e,N.width,N.height,180).translate(s/2-N.width,-N.height);let W=l(p,f.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const $=Z(W.e,W.width,W.height,90).translate(-W.height,s/2),q=new v,xs=new nn().size(s,s).x(0).y(0).fill("none").stroke("#000000");return q.add(xs),q.add(c.e),q.add(A),q.add(R),q.add(T),q.add($),{e:q,width:s,height:s}},Sr=(n,t)=>{const e=ee(t.front,n),s=ee(t.right,n),i=ee(t.opposite,n),r=ee(t.left,n),o=[e.height,s.height,i.height,r.height].reduce((R,N)=>Math.max(R,N)),a=n.tileWidth*5+n.tileHeight*1,c=o,l=a+o*2+n.blockMargin,h=l,u=new v().size(l,h),d=l/2-a/2,p=h/2-a/2,f=Z(e.e,a,c,0).translate(d,h-c),m=Z(s.e,a,c,270).translate(l-c,p),A=Z(i.e,a,c,180).translate(d,0),S=Z(r.e,a,c,90).translate(0,p);return u.add(f),u.add(m),u.add(A),u.add(S),{e:new v().add(u),width:l,height:h}},qn=(n,t,e,s,i)=>{const r=new v,o=Sr(n,s),a=_r(n,e,o.height),c=Ar(n,t,i);return o.e.translate((a.width-o.width)/2,(a.height-o.height)/2),c.e.translate((a.width-c.width)/2,(a.height-c.height)/2),r.add(a.e),r.add(o.e),r.add(c.e),{e:r,width:a.width,height:a.height}},Nr=(n,t,e={},s,i={responsive:!1})=>{const r=new rn(e),o=s,{discards:a,hands:c,scoreBoard:l}=es(t),h=qn(r,o,c,a,l);i.responsive||n.size(h.width,h.height),n.viewbox(0,0,h.width,h.height),n.add(h.e)};var Q;function Qn(n){return{lang:(n==null?void 0:n.lang)??(Q==null?void 0:Q.lang),message:n==null?void 0:n.message,abortEarly:(n==null?void 0:n.abortEarly)??(Q==null?void 0:Q.abortEarly),abortPipeEarly:(n==null?void 0:n.abortPipeEarly)??(Q==null?void 0:Q.abortPipeEarly)}}var Ne;function Ir(n){return Ne==null?void 0:Ne.get(n)}var Ie;function vr(n){return Ie==null?void 0:Ie.get(n)}var ve;function Tr(n,t){var e;return(e=ve==null?void 0:ve.get(n))==null?void 0:e.get(t)}function xt(n){var e,s;const t=typeof n;return t==="string"?`"${n}"`:t==="number"||t==="bigint"||t==="boolean"?`${n}`:t==="object"||t==="function"?(n&&((s=(e=Object.getPrototypeOf(n))==null?void 0:e.constructor)==null?void 0:s.name))??"null":t}function at(n,t,e,s,i){const r=i&&"input"in i?i.input:e.value,o=(i==null?void 0:i.expected)??n.expects??null,a=(i==null?void 0:i.received)??xt(r),c={kind:n.kind,type:n.type,input:r,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:n.requirement,path:i==null?void 0:i.path,issues:i==null?void 0:i.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},l=n.kind==="schema",h=(i==null?void 0:i.message)??n.message??Tr(n.reference,c.lang)??(l?vr(c.lang):null)??s.message??Ir(c.lang);h!==void 0&&(c.message=typeof h=="function"?h(c):h),l&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function Kt(n){return{version:1,vendor:"valibot",validate(t){return n["~run"]({value:t},Qn())}}}function Or(n,t){const e=[...new Set(n)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function Pe(n,t){return{kind:"validation",type:"max_value",reference:Pe,async:!1,expects:`<=${n instanceof Date?n.toJSON():xt(n)}`,requirement:n,message:t,"~run"(e,s){return e.typed&&!(e.value<=this.requirement)&&at(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():xt(e.value)}),e}}}function He(n,t){return{kind:"validation",type:"min_value",reference:He,async:!1,expects:`>=${n instanceof Date?n.toJSON():xt(n)}`,requirement:n,message:t,"~run"(e,s){return e.typed&&!(e.value>=this.requirement)&&at(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():xt(e.value)}),e}}}function kr(n,t,e){return typeof n.fallback=="function"?n.fallback(t,e):n.fallback}function ts(n,t,e){return typeof n.default=="function"?n.default(t,e):n.default}function le(n){return{kind:"schema",type:"number",reference:le,expects:"number",async:!1,message:n,get"~standard"(){return Kt(this)},"~run"(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:at(this,"type",t,e),t}}}function j(n,t){return{kind:"schema",type:"optional",reference:j,expects:`(${n.expects} | undefined)`,async:!1,wrapped:n,default:t,get"~standard"(){return Kt(this)},"~run"(e,s){return e.value===void 0&&(this.default!==void 0&&(e.value=ts(this,e,s)),e.value===void 0)?(e.typed=!0,e):this.wrapped["~run"](e,s)}}}function We(n,t){return{kind:"schema",type:"picklist",reference:We,expects:Or(n.map(xt),"|"),async:!1,options:n,message:t,get"~standard"(){return Kt(this)},"~run"(e,s){return this.options.includes(e.value)?e.typed=!0:at(this,"type",e,s),e}}}function Mt(n,t){return{kind:"schema",type:"strict_object",reference:Mt,expects:"Object",async:!1,entries:n,message:t,get"~standard"(){return Kt(this)},"~run"(e,s){var r;const i=e.value;if(i&&typeof i=="object"){e.typed=!0,e.value={};for(const o in this.entries){const a=this.entries[o];if(o in i||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){const c=o in i?i[o]:ts(a),l=a["~run"]({value:c},s);if(l.issues){const h={type:"object",origin:"value",input:i,key:o,value:c};for(const u of l.issues)u.path?u.path.unshift(h):u.path=[h],(r=e.issues)==null||r.push(u);if(e.issues||(e.issues=l.issues),s.abortEarly){e.typed=!1;break}}l.typed||(e.typed=!1),e.value[o]=l.value}else if(a.fallback!==void 0)e.value[o]=kr(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(at(this,"key",e,s,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]}),s.abortEarly))break}if(!e.issues||!s.abortEarly){for(const o in i)if(!(o in this.entries)){at(this,"key",e,s,{input:o,expected:"never",path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]});break}}}else at(this,"type",e,s);return e}}}function he(n){return{kind:"schema",type:"string",reference:he,expects:"string",async:!1,message:n,get"~standard"(){return Kt(this)},"~run"(t,e){return typeof t.value=="string"?t.typed=!0:at(this,"type",t,e),t}}}function Tn(...n){return{...n[0],pipe:n,get"~standard"(){return Kt(this)},"~run"(t,e){for(const s of n)if(s.kind!=="metadata"){if(t.issues&&(s.kind==="schema"||s.kind==="transformation")){t.typed=!1;break}(!t.issues||!e.abortEarly&&!e.abortPipeEarly)&&(t=s["~run"](t,e))}return t}}}function Cr(n,t,e){const s=n["~run"]({value:t},Qn(e));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}const ne=j(Mt({discard:j(he(),""),hand:j(he(),""),score:j(le(),25e3)}),{discard:"",hand:"",score:25e3}),Rr=Mt({[E.E]:ne,[E.S]:ne,[E.W]:ne,[E.N]:ne}),ut={round:C.E1,sticks:{reach:0,dead:0},doras:E.S,front:E.E},xr=j(Mt({round:j(We(Object.keys(Ve)),ut.round),sticks:j(Mt({reach:j(Tn(le(),He(0,""),Pe(9,"")),ut.sticks.reach),dead:j(Tn(le(),He(0,""),Pe(9,"")),ut.sticks.dead)}),ut.sticks),doras:j(he(),ut.doras),front:j(We(Object.keys(ye)),ut.front)}),ut),Mr=Mt({...Rr.entries,board:xr}),es=n=>{const t=ns(n);return ss(t)},ns=n=>{const t=$r(n),e=Cr(Mr,t);if(!e.success)throw e.issues;return e.output},$r=n=>{const t="table",e="board",s=n.split(`
|
|
13
|
-
`).map(a=>a.trim()).filter(a=>a!="");if(s.length==0)throw new Error("empty input");const i=s.shift();if(!i.startsWith(t))throw new Error(`input does not start with table: ${i}`);const r={};let o=[E.E,E.S,E.W,E.N,e];for(;;){const a=s.shift();if(a==null)break;const c=o.find(l=>a.startsWith(l));if(c==null)throw new Error(`encountered unexpected line ${a}`);if(o=o.filter(l=>!a.startsWith(l)),c==e){const[l,h]=Hr([...s]);r.board=l;for(let u=0;u<h;u++)s.shift()}else{const[l,h]=Pr([...s]);r[c]=l;for(let u=0;u<h;u++)s.shift()}}return r},V=(n,t)=>n.replace(t,"").replace(":","").trim(),Pr=n=>{const t="hand",e="discard",s="score",i={};let r=0;for(;r<n.length;r++){const o=n[r];if(o.startsWith(t))i.hand=V(o,t);else if(o.startsWith(e))i.discard=V(o,e);else if(o.startsWith(s))i.score=Number(V(o,s));else break}return[i,r]},Hr=n=>{const t="doras",e="round",s="front",i="sticks",r="reach",o="dead",a={};let c=0;for(;c<n.length;c++){const l=n[c];if(l.startsWith(t))a.doras=V(l,t);else if(l.startsWith(e))a.round=V(l,e);else if(l.startsWith(s))a.front=V(l,s);else if(l.startsWith(i)){a.sticks={};const h=n[c+1]??"",u=n[c+2]??"";h.startsWith(r)&&(a.sticks.reach=Number(V(h,r))),h.startsWith(o)&&(a.sticks.dead=Number(V(h,o))),u.startsWith(r)&&(a.sticks.reach=Number(V(u,r))),u.startsWith(o)&&(a.sticks.dead=Number(V(u,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},ss=n=>{const t=n.board.front,e=Wr(t),s=a=>n[a].discard.replace(/\r?\n/g,""),i={front:new K(s(e.front)).tiles(),right:new K(s(e.right)).tiles(),opposite:new K(s(e.opposite)).tiles(),left:new K(s(e.left)).tiles()},r={front:new K(n[e.front].hand).parse(),right:new K(n[e.right].hand).parse(),opposite:new K(n[e.opposite].hand).parse(),left:new K(n[e.left].hand).parse()},o={round:Ve[n.board.round],frontPlace:ye[t],sticks:n.board.sticks,doras:new K(n.board.doras).tiles(),scores:{front:n[e.front].score,right:n[e.right].score,opposite:n[e.opposite].score,left:n[e.left].score}};return{discards:i,hands:r,scoreBoard:o}},Wr=n=>({front:n,right:bt(n),opposite:bt(bt(n)),left:me(n)});function*U(n){const t=n!=null&&n.filterBy&&n.filterBy.length>0?n==null?void 0:n.filterBy:Object.values(g);for(const e of t){if(n!=null&&n.skipBack&&e==g.BACK)continue;const s=e==g.Z?7:e==g.BACK?1:9;for(let i=1;i<=s;i++)yield[e,i]}}class _e{constructor(t,e=!1){_(this,"data");this.data={[g.M]:[0,0,0,0,0,0,0,0,0,0],[g.P]:[0,0,0,0,0,0,0,0,0,0],[g.S]:[0,0,0,0,0,0,0,0,0,0],[g.Z]:[0,0,0,0,0,0,0,0],[g.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const s=Array.isArray(t)?t:new K(t).parse();for(const i of s){if(i.isCalled()){this.data.called=[...this.called,i];continue}else if(i.is(b.TSUMO)){const r=i.tiles[0];this.inc([r]),this.data.tsumo=r;continue}else if(i.is(b.HAND)){this.inc(i.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(r=>r===g.BACK)){this.inc(i.tiles);continue}else if(e){this.inc(i.tiles);continue}throw new Error(`unexpected block ${i.type} ${i.toString()}`)}}get hands(){const t=[];for(const[e,s]of U()){let i=this.get(e,s);e!=g.Z&&s==5&&this.get(e,0)>0&&(i-=this.get(e,0),t.push(new w(e,s,[y.RED])));for(let r=0;r<i;r++)t.push(new w(e,s))}if(this.drawn!=null){const e=this.drawn,s=t.findIndex(i=>i.equals(e)&&e.has(y.RED)==i.has(y.RED));I(s>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[s]=t[s].clone({add:y.TSUMO})}return t}toString(){const t=this.called.length>0?`${nt}${this.called.join(nt)}`:"",e=this.drawn?`${nt}${this.drawn.toString()}`:"",s=this.hands.filter(r=>!r.has(y.TSUMO));return`${new Ct(s).toString()}${e}${t}`}get called(){return this.data.called}get reached(){return this.data.reached}get drawn(){return this.data.tsumo}get menzen(){return!this.called.some(t=>!(t instanceof M))}sum(t){let e=0;for(const[s,i]of U({filterBy:[t]}))e+=this.get(s,i);return e}get(t,e){return t==g.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const s of t){if(s.t!=g.BACK&&this.get(s.t,s.n)>=4||s.has(y.RED)&&this.get(s.t,0)>0)throw this.dec(e),new Error(`unable to increase ${s} in ${this.toString()}`);e.push(s),s.t==g.BACK?this.data[s.t][1]+=1:(this.data[s.t][s.n]+=1,s.has(y.RED)&&(this.data[s.t][0]+=1))}return e}dec(t){const e=[];for(const s of t){if(this.get(s.t,s.n)<1||s.has(y.RED)&&this.get(s.t,0)<=0)throw this.inc(e),new Error(`unable to decrease ${s.toString()} in ${this.toString()}`);if(e.push(s),s.t==g.BACK?this.data[s.t][1]-=1:(this.data[s.t][s.n]-=1,s.has(y.RED)&&(this.data[s.t][0]-=1)),x(s)&&this.get(s.t,5)==0&&this.get(s.t,0)>0){this.data[s.t][0]=0;const i=e.pop().clone({add:y.RED});e.push(i)}}return e}draw(t){const e=t.clone({add:y.TSUMO});this.inc([e]),this.data.tsumo=e}discard(t){this.dec([t]),this.data.tsumo=null}reach(){if(!this.menzen)throw new Error("cannot reach");if(this.data.reached)throw new Error("already reached");this.data.reached=!0}call(t){const e=t.tiles.filter(s=>!s.has(y.HORIZONTAL));if(e.length!=t.tiles.length-1)throw new Error(`removal: ${e} block: ${t}`);this.dec(e),this.data.called=[...this.called,t],this.data.tsumo=null}kan(t){if(t instanceof M){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof L){const e=this.data.called.findIndex(i=>i.is(b.PON)&&i.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let s=t.tiles[0];s=x(s)?s.clone({remove:y.RED}):s,this.dec([s]),this.data.called=[...this.called.slice(0,e),...this.called.slice(e+1),t],this.data.tsumo=null;return}throw new Error(`unexpected input ${t}`)}clone(){const t=new _e(this.toString());return t.data.reached=this.data.reached,t}}class qt{constructor(t){_(this,"hand");this.hand=t}calc(){return Math.min(this.sevenPairs(),this.thirteenOrphans(),this.fourSetsOnePair())}sevenPairs(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const[s,i]of U({skipBack:!0}))this.hand.get(s,i)==2&&t++,this.hand.get(s,i)==1&&e++;return t>7&&(t=7),t+e>=7&&(e=7-t),13-2*t-e}thirteenOrphans(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const s of Object.values(g)){if(s==g.BACK)continue;const i=s==g.Z?$t:J;for(const r of i)this.hand.get(s,r)>=1&&t++,this.hand.get(s,r)>=2&&e++}return e>=1?12-t:13-t}fourSetsOnePair(){const t=s=>{const i=[0,0,0];for(const[d,p]of U({filterBy:[g.Z]}))this.hand.get(d,p)>=3?i[0]++:this.hand.get(d,p)==2?i[1]++:this.hand.get(d,p)==1&&i[2]++;const r=[0,0,0],o=this.hand.get(g.BACK,0),a=o%3;r[0]=Math.floor(o/3),a==2?r[1]=1:a==1&&(r[2]=1);let c=13;const l=this.patternNumType(g.M),h=this.patternNumType(g.P),u=this.patternNumType(g.S);for(const d of[l.patternA,l.patternB])for(const p of[h.patternA,h.patternB])for(const f of[u.patternA,u.patternB]){const m=[this.hand.called.length,0,0];for(let S=0;S<3;S++)m[S]+=d[S]+p[S]+f[S]+i[S]+r[S];const A=this.calcCommon(m[0],m[1],m[2],s);A<c&&(c=A)}return c};let e=t(!1);for(const[s,i]of U())if(this.hand.get(s,i)>=2){const r=this.hand.dec(new Array(2).fill(new w(s,i))),o=t(!0);this.hand.inc(r),o<e&&(e=o)}return e}patternNumType(t,e=1){if(e>9)return this.groupRemainingTiles(t);let s=this.patternNumType(t,e+1);if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const i=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]),r=this.patternNumType(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<s.patternA[2]||r.patternA[2]==s.patternA[2]&&r.patternA[1]<s.patternA[1])&&(s.patternA=r.patternA),(r.patternB[0]>s.patternB[0]||r.patternB[0]==s.patternB[0]&&r.patternB[1]>s.patternB[1])&&(s.patternB=r.patternB)}if(this.hand.get(t,e)>=3){const i=this.hand.dec(new Array(3).fill(new w(t,e))),r=this.patternNumType(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<s.patternA[2]||r.patternA[2]==s.patternA[2]&&r.patternA[1]<s.patternA[1])&&(s.patternA=r.patternA),(r.patternB[0]>s.patternB[0]||r.patternB[0]==s.patternB[0]&&r.patternB[1]>s.patternB[1])&&(s.patternB=r.patternB)}return s}groupRemainingTiles(t){let e=0,s=0,i=0;for(const[r,o]of U({filterBy:[t]}))i+=this.hand.get(r,o),o<=7&&this.hand.get(r,o+1)==0&&this.hand.get(r,o+2)==0&&(e+=i>>1,s+=i%2,i=0);return e+=i>>1,s+=i%2,{patternA:[0,e,s],patternB:[0,e,s]}}calcCommon(t,e,s,i){let r=i?4:5;return t>4&&(e+=t-4,t=4),t+e>4&&(s+=t+e-4,e=4-t),t+e+s>r&&(s=r-t-e),i&&e++,13-t*3-e*2-s}}class is{constructor(t){_(this,"hand");this.hand=t}calc(t){return this.markDrawn([...this.sevenPairs(),...this.thirteenOrphans(),...this.nineGates(),...this.fourSetsOnePair()],t)}markDrawn(t,e){if(t.length==0)return[];const s=this.hand.drawn!=null||e.has(y.TSUMO)?y.TSUMO:y.RON,i=[];for(let o=0;o<t.length;o++){const a=t[o],c={};for(let l=0;l<a.length;l++){const h=a[l];if(h.isCalled())continue;const u=h.tiles.findIndex(p=>p.equals(e)&&e.has(y.RED)==p.has(y.RED));if(u<0)continue;const d=Ut(h);c[d]||(c[d]=!0,i.push([o,l,u]))}}if(i.length==0)throw new Error(`found no tile ${e.toString()} in hands ${t[0].toString()}`);const r=[];for(const[o,a,c]of i){const h=[...t[o]],u=h[a],d=u.tiles[c].clone({add:s});h[a]=u.clone({replace:{idx:c,tile:d}}),r.push(h)}return r}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,s]of U({skipBack:!0})){const i=this.hand.get(e,s);if(i==2){const r=this.hand.dec(new Array(2).fill(new w(e,s)));t.push(new D(r[0],r[1])),this.hand.inc(r)}else{if(i==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const s of Object.values(g)){if(s==g.BACK)continue;const i=s==g.Z?$t:J;for(let r of i)if(this.hand.get(s,r)==1)t.push(new Ye(new w(s,r)));else if(this.hand.get(s,r)==2&&e==!1)t.unshift(new D(new w(s,r),new w(s,r))),e=!0;else return[]}return[t]}nineGates(){const t=(e,s,i)=>i.includes(this.hand.get(e,s));for(const e of Object.values(g)){if(e==g.BACK||e==g.Z)continue;const s=t(e,1,[3,4])&&t(e,9,[3,4])&&t(e,2,[1,2])&&t(e,3,[1,2])&&t(e,4,[1,2])&&t(e,5,[1,2])&&t(e,6,[1,2])&&t(e,7,[1,2])&&t(e,8,[1,2]),i=this.hand.sum(e)==14;if(s&&i)return[[new Ct(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,s]of U())if(this.hand.get(e,s)>=2){const i=new Array(2).fill(new w(e,s));s==5&&this.hand.get(e,0)>0&&this.hand.get(e,s)>=3&&(i[1]=new w(e,s,[y.RED]));const r=this.hand.dec(i),o=this.patternAll().filter(a=>a.length==4).map(a=>(a.unshift(new D(r[0],r[1])),a));t=[...t,...o],this.hand.inc(r)}return t}patternAll(){return[this.addRedPattern(g.M,this.handleNumType(g.M)),this.addRedPattern(g.P,this.handleNumType(g.P)),this.addRedPattern(g.S,this.handleNumType(g.S)),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((s,i)=>i.length-s.length).reduce((s,i)=>i.length===0?s:s.flatMap(r=>i.map(o=>[...r,...o])),[[]])}handleBack(){const t=g.BACK,e=this.hand.get(t,0);if(e<3)return[];const s=new w(t,0),i=Array(Math.floor(e/3)).fill(new F([s,s,s]));return i.length==0?[]:[i]}handleZ(){const t=[];for(const[e,s]of U({filterBy:[g.Z]})){if(this.hand.get(e,s)==0)continue;if(this.hand.get(e,s)!=3)return[];const i=new w(e,s);t.push(new F([i,i,i]))}return t.length==0?[]:[t]}addRedPattern(t,e){if(!(this.hand.get(t,0)>0&&this.hand.get(t,5)>=2))return e;const s=new w(t,5),i=new w(t,5,[y.RED]),r=[],o=[];for(let c=0;c<e.length;c++){const l=e[c],h={};for(let u=0;u<l.length;u++){const d=l[u],p=d.tiles.findIndex(A=>A.equals(s)&&!A.has(y.RED)),f=d.tiles.findIndex(A=>A.equals(i)&&A.has(y.RED));if(f>-1&&o.push([c,u,f]),f>-1&&p>-1||p<0)continue;const m=Ut(d);h[m]||(h[m]=!0,r.push([c,u,p]))}}if(o.length==0)return e;const a=[];for(const[c,l,h]of r){const d=[...e[c]],p=d[l];d[l]=p.clone({replace:{idx:h,tile:i}});const f=o.find(A=>A[0]==c);if(f==null)continue;const m=d[f[1]];m==null&&console.error(f,r),d[f[1]]=m.clone({replace:{idx:f[2],tile:s}}),Ut(p)!=Ut(m)&&a.push(d)}return[...e,...a]}handleNumType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.handleNumType(t,e+1);const s=[];if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const i=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]);let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new st([i[0],i[1],i[2]])),s.push(o)}if(this.hand.get(t,e)==3){const i=this.hand.dec(new Array(3).fill(new w(t,e)));let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new F([i[0],i[1],i[2]])),s.push(o)}return s}}const $t=[1,2,3,4,5,6,7],J=[1,9],jt=n=>{var e;const t=n.boardContext;return{...n,hand:n.hand.map(O.deserialize),boardContext:{...t,doraIndicators:t.doraIndicators.map(w.from),hiddenDoraIndicators:(e=t.hiddenDoraIndicators)==null?void 0:e.map(w.from)}}},ue=n=>JSON.parse(JSON.stringify(n));class Be{constructor(t,e){_(this,"hand");_(this,"cfg");this.hand=t,this.cfg={doras:e.doraIndicators.map(s=>kn(s)),blindDoras:e.hiddenDoraIndicators==null?[]:e.hiddenDoraIndicators.map(s=>kn(s)),roundWind:w.from(e.round.substring(0,2)),myWind:w.from(e.myWind),reached:e.reached??0,sticks:e.sticks??{dead:0,reach:0},replacementWin:e.replacementWin??!1,quadWin:e.quadWin??!1,finalWallWin:e.finalWallWin??!1,finalDiscardWin:e.finalDiscardWin??!1,oneShotWin:e.oneShotWin??!1,enableRoundUp8000:e.enableRoundUp8000??!1,disableCountable32000:e.disableCountable32000??!1,disableDouble32000:e.disableDouble32000??!1,orig:e}}calc(...t){const e=this.calcPatterns(t);let s=!1,i=!1;if(e.length==0)return!1;let r=[0,0],o=0;for(let N=0;N<e.length;N++){const T=e[N];s=T.is32000??!1;const W=T.yakus.reduce(($,q)=>$+q.han,0);W>r[0]?(o=N,r=[W,T.fu]):W==r[0]&&T.fu>r[1]&&(o=N,r=[W,T.fu])}const a=(N,T=100)=>Math.ceil(N/T)*T,c=r[1]!=25?a(r[1],10):25,l=r[0];let h=Math.min(c*2**(l+2),2e3);switch(l){case 26:h=16e3;break;case 13:h=8e3;break;case 12:case 11:h=6e3;break;case 10:case 9:case 8:h=4e3;break;case 7:case 6:h=3e3;break;case 5:h=2e3;break}l>=13&&l<26&&e[o].yakus.every(N=>N.is32000==null||N.is32000==!1)&&(h=this.cfg.disableCountable32000?6e3:8e3,i=!this.cfg.disableCountable32000),this.cfg.enableRoundUp8000&&(c==30&&l==4||c==60&&l==3)&&(h=2e3);const u=e[o].hand.some(N=>N.tiles.some(T=>T.has(y.TSUMO))),d=this.cfg.orig.myWind,p=d==E.E;let f="";const m=H(0);if(u){const N=this.cfg.sticks.dead*100;if(p){const T=a(h*2);m[E.E]+=T*3+N*3,m[E.S]-=T+N,m[E.W]-=T+N,m[E.N]-=T+N,f=`${T}`}else{for(const T of Object.values(E)){if(T==d)continue;const W=T==E.E?2:1,$=a(h*W);m[T]-=$+N,m[d]+=$+N}f=`${a(h*1)}-${a(h*2)}`}}else{const N=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const $=a(h*(p?6:4))+N;m[d]+=$,m[this.cfg.orig.ronWind]-=$,f=`${$}`}const A=m[d]-this.cfg.sticks.dead*300;m[d]+=1e3*this.cfg.sticks.reach;let S;return s?S="役満":i?S="数え役満":h==2e3?S=`${c}符${l}飜 満貫${f}`:h==3e3?S=`${c}符${l}飜 跳満${f}`:h==4e3?S=`${c}符${l}飜 倍満${f}`:h==6e3?S=`${c}符${l}飜 三倍満${f}`:S=`${c}符${l}飜 ${f}`,{deltas:m,han:l,fu:c,yakus:e[o].yakus,points:m[d],rawPoints:A,hand:e[o].hand,boardContext:this.cfg.orig,description:S}}calcPatterns(t){const e=[];if(t.length==0)return e;for(const s of t){const i=[...this.dA13(s),...this.dB13(s),...this.dC13(s),...this.dD13(s),...this.dE13(s),...this.dF13(s),...this.dG13(s),...this.dH13(s),...this.dI13(s),...this.dJ13(s),...this.dK13(s)].map(r=>(this.cfg.disableDouble32000&&r.han>13&&(r.han=13),r));i.length!=0&&e.push({yakus:i,fu:30,hand:s,is32000:!0})}if(e.length>0)return e;for(const s of t){const i=this.calcFu(s),r=[...this.dA1(s),...this.dB1(s),...this.dC1(s),...this.dD1(s),...this.dE1(s),...this.dF1(s),...this.dG1(s),...this.dH1(s),...this.dI1(s),...this.dJ1(s),...this.dK1(s),...this.dA2(s),...this.dB2(s),...this.dC2(s),...this.dD2(s),...this.dE2(s),...this.dF2(s),...this.dG2(s),...this.dH2(s),...this.dI2(s),...this.dJ2(s),...this.dA3(s),...this.dB3(s),...this.dC3(s),...this.dA6(s)];r.length!=0&&(r.push(...this.dX1(s)),e.push({yakus:r,fu:i,hand:s}))}return e}minus(){return this.hand.menzen?0:1}dA1(t){return this.cfg.reached==1?[{name:"立直",han:1}]:this.cfg.reached==2?[{name:"ダブル立直",han:2}]:[]}dB1(t){return this.minus()!=0?[]:(this.hand.drawn==null,t.some(s=>s.tiles.some(i=>i.has(y.TSUMO)))?[{name:"門前清自摸和",han:1}]:[])}dC1(t){if(this.minus()!=0)return[];const e="平和",s=this.calcFu(t);return s==20?[{name:e,han:1}]:!t.some(i=>i.tiles.some(r=>r.has(y.TSUMO)))&&s==30?[{name:e,han:1}]:[]}dD1(t){return t.some(s=>s.tiles.some(i=>i.t==g.Z||J.includes(i.n)))?[]:[{name:"断么九",han:1}]}dE1(t){return this.minus()!=0?[]:On(t)==1?[{name:"一盃口",han:1}]:[]}dF1(t){const e=[];return t.forEach(s=>{if(s instanceof D)return;const i=s.tiles[0];i.t==g.Z&&(i.equals(this.cfg.myWind)&&e.push({name:"自風",han:1}),i.equals(this.cfg.roundWind)?e.push({name:"場風",han:1}):i.n==5?e.push({name:"白",han:1}):i.n==6?e.push({name:"發",han:1}):i.n==7&&e.push({name:"中",han:1}))}),e}dG1(t){return this.cfg.oneShotWin?[{name:"一発",han:1}]:[]}dH1(t){return this.cfg.replacementWin?[{name:"嶺上開花",han:1}]:[]}dI1(t){return this.cfg.quadWin?[{name:"搶槓",han:1}]:[]}dJ1(t){return this.cfg.finalWallWin?[{name:"海底摸月",han:1}]:[]}dK1(t){return this.cfg.finalDiscardWin?[{name:"河底撈魚",han:1}]:[]}dX1(t){let e=0,s=0,i=0;for(const o of t)for(const a of o.tiles){for(const c of this.cfg.doras)a.equals(c)&&e++;for(const c of this.cfg.blindDoras)a.equals(c)&&s++;a.has(y.RED)&&i++}const r=[];return e>0&&r.push({name:"ドラ",han:e}),i>0&&r.push({name:"赤ドラ",han:i}),this.hand.reached&&s>0&&r.push({name:"裏ドラ",han:s}),r}dA2(t){return t.length==7?[{name:"七対子",han:2}]:[]}dB2(t){const e=s=>s instanceof st||s instanceof Y;for(const s of t){if(!e(s))continue;const i=dt(s);if(i.t==g.Z)continue;const r=[g.M,g.P,g.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new w(r[0],i.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(r[1],i.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同順",han:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(s=>s instanceof M||s instanceof L||s instanceof et||s instanceof F||s instanceof X||s instanceof D)?[{name:"対々和",han:2}]:[]}dD2(t){return t.filter(s=>(s instanceof M||s instanceof F)&&!s.tiles.some(i=>i.has(y.RON))).length>=3?[{name:"三暗刻",han:2}]:[]}dE2(t){return t.filter(s=>s instanceof M||s instanceof L||s instanceof et).length>=3?[{name:"三槓子",han:2}]:[]}dF2(t){const e=s=>s instanceof M||s instanceof L||s instanceof et||s instanceof F||s instanceof X;for(const s of t){if(!e(s))continue;const i=dt(s);if(i.t==g.Z)continue;const r=[g.M,g.P,g.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new w(r[0],i.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(r[1],i.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同刻",han:2}]}return[]}dG2(t){return t.length==7?[]:t.filter(s=>{const i=s.tiles[0];return i.t==g.Z&&[5,6,7].includes(i.n)}).length==3?[{name:"小三元",han:2}]:[]}dH2(t){return t.every(s=>{const i=s.tiles[0].t==g.Z?$t:J;return s.tiles.every(r=>i.includes(r.n))})?[{name:"混老頭",han:2}]:[]}dI2(t){return t.length==7?[]:t.some(s=>s instanceof st||s instanceof Y)?t.some(s=>s.tiles[0].t==g.Z)?t.every(s=>{const i=s.tiles[0].t==g.Z?$t:J;return s.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",han:2-this.minus()}]:[]:[]:[]}dJ2(t){const e={[g.M]:[0,0,0],[g.S]:[0,0,0],[g.P]:[0,0,0]};for(const s of t){const i=dt(s);i.t!=g.BACK&&i.t!=g.Z&&(s instanceof st||s instanceof Y)&&(i.n==1?e[i.t][0]++:i.n==4?e[i.t][1]++:i.n==7&&e[i.t][2]++)}for(const s of Object.values(e))if(s[0]>0&&s[1]>0&&s[2]>0)return[{name:"一気通貫",han:2-this.minus()}];return[]}dA3(t){if(!t.some(s=>s.tiles[0].t==g.Z))return[];for(const s of Object.values(g))if(t.every(r=>r.tiles[0].t==g.Z||r.tiles[0].t==s))return[{name:"混一色",han:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(s=>s instanceof st||s instanceof Y)?t.some(s=>s.tiles[0].t==g.Z)?[]:t.every(s=>s.tiles.some(i=>J.includes(i.n)))?[{name:"純全帯么九色",han:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:On(t)==2?[{name:"ニ盃口",han:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==g.Z))return[];for(const e of Object.values(g)){if(e==g.Z)continue;if(t.every(i=>i.tiles[0].t==e))return[{name:"清一色",han:6-this.minus()}]}return[]}dA13(t){return t.length!=13?[]:t.some(s=>s instanceof D&&s.tiles.some(i=>i.has(y.TSUMO)||i.has(y.RON)))?[{name:"国士無双13面待ち",han:26,is32000:!0}]:[{name:"国士無双",han:13,is32000:!0}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",han:13,is32000:!0}]:[]}dC13(t){return t.length==7?[]:t.every(i=>i instanceof M||i instanceof F&&i.tiles.every(r=>!r.has(y.RON))||i instanceof D)?t.some(i=>i instanceof D&&i.tiles.some(r=>r.has(y.TSUMO)||r.has(y.RON)))?[{name:"四暗刻単騎待ち",han:26,is32000:!0}]:[{name:"四暗刻",han:13,is32000:!0}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(i=>!(i instanceof D)&&i.tiles.some(r=>r.t==g.Z&&e.includes(r.n))).length==3?[{name:"大三元",han:13,is32000:!0}]:[]}dE13(t){return t.every(s=>s.tiles[0].t==g.Z)?[{name:"字一色",han:13,is32000:!0}]:[]}dF13(t){return t.every(s=>s.tiles.every(i=>i.t!=g.Z&&J.includes(i.n)))?[{name:"清老頭",han:13,is32000:!0}]:[]}dG13(t){return t.filter(s=>s instanceof M||s instanceof L||s instanceof et).length==4?[{name:"四槓子",han:13,is32000:!0}]:[]}dH13(t){if(t.length==13)return[];if(t.length==7)return[];const e=[1,2,3,4];return t.filter(r=>r.tiles.some(o=>o.t==g.Z&&e.includes(o.n))).length==4?t.find(r=>r instanceof D).tiles.some(r=>r.t==g.Z&&e.includes(r.n))?[{name:"小四喜",han:13,is32000:!0}]:[{name:"大四喜",han:13,is32000:!0}]:[]}dI13(t){const e=s=>!!(s.equals(new w(g.Z,6))||s.t==g.S&&[2,3,4,6,8].includes(s.n));return t.every(s=>s.tiles.every(i=>e(i)))?[{name:"緑一色",han:13,is32000:!0}]:[]}dJ13(t){return[]}dK13(t){return[]}calcFu(t){let s=20;const i=this.cfg.myWind.n,r=this.cfg.roundWind.n;if(t.length==7)return 25;const o=t.find(f=>f.tiles.some(m=>m.has(y.TSUMO)||m.has(y.RON))),a=this.minus()==1,c=o.tiles.some(f=>f.has(y.TSUMO)),l=(f,m)=>{const A=f.tiles[0];return A.t==g.Z||J.includes(A.n)?m*2:m};for(const f of t)switch(!0){case f instanceof F:const m=f.tiles.some(A=>A.has(y.RON))?2:4;s+=l(f,m);break;case f instanceof X:s+=l(f,2);break;case(f instanceof et||f instanceof L):s+=l(f,8);break;case f instanceof M:s+=l(f,16);break}s+=(f=>{if(f instanceof F)return 0;if(f instanceof D)return 2;const m=f.tiles,A=m.findIndex(S=>S.has(y.TSUMO)||S.has(y.RON));return A==1||A==0&&m[2].n==9||A==2&&m[0].n==1?2:0})(o);const d=t.find(f=>f instanceof D).tiles[0];d.t==g.Z&&([5,6,7].includes(d.n)&&(s+=2),(d.n==r||d.n==i)&&(s+=2));let p=!1;return!a&&s==20&&(p=!0),c&&!p&&(s+=2),!c&&!a&&(s+=10),!c&&!a&&s==30&&(p=!0),a&&s==20&&(s=30),s}}const Ut=n=>n.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),On=n=>{const t={};for(const s of n){if(!(s instanceof st))continue;const i=Ut(s);t[i]==null?t[i]=1:t[i]++}let e=0;for(const s in t)t[s]>=2&&e++;return e},dt=n=>[...n.tiles].sort(Xt)[0],kn=n=>{const t=n.n,e=n.t;if(e==g.Z){if(t==4)return new w(e,1);if(t==7)return new w(e,5)}return new w(e,t%9+1)};class Pt{static calcCandidates(t,e,s){I(e.length>0,"choices to discard is zero");const i=new Map;let r=1/0;for(const o of e){const a=t.dec([o]),c=Pt.candidateTiles(t,s);t.inc(a);const l=s!=null&&s.arrangeRed&&o.has(y.RED)?o.clone({removeAll:!0}):o.has(y.RED)?o.clone({removeAll:!0,add:y.RED}):o.clone({removeAll:!0});c.shanten<r?(i.clear(),i.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l}),r=c.shanten):c.shanten==r&&i.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l})}return Array.from(i.values())}static candidateTiles(t,e){let s=1/0,i=[];const r=new qt(t);for(const[o,a]of U({skipBack:!0,filterBy:e==null?void 0:e.typeFilter})){if(t.get(o,a)>=4)continue;const c=new w(o,a),l=t.inc([c]),h=e!=null&&e.fourSetsOnePair?r.fourSetsOnePair():r.calc();t.dec(l),h<s?(s=h,i=[c]):h==s&&i.push(c)}return{shanten:s,candidates:i}}}const De=()=>{const n=new Set;return{on(t){n.add(t)},off(t){n.delete(t)},offAll(){n.clear()},emit(t){n.forEach(e=>e(t))}}};function rs(n){var r;const t=["RON","DAI_KAN","PON","CHI"],e=n.map(o=>o.choices),i=as(e,t).map(o=>n[o]);return{events:i,type:cs(t,(r=i[0])==null?void 0:r.choices)}}function os(n){var r;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=n.map(o=>o.choices),i=as(e,t).map(o=>n[o]);return{events:i,type:cs(t,(r=i[0])==null?void 0:r.choices)}}function as(n,t){let e=[],s=Number.POSITIVE_INFINITY;for(let i=0;i<n.length;i++){const r=n[i];if(Br(r,t)){const o=Dr(t,r);o<s?(s=o,e=[i]):o===s&&e.push(i)}}return e}function Br(n,t){return t.some(e=>!!n[e])}function Dr(n,t){for(let e=0;e<n.length;e++){const s=n[e];if(t[s])return e}return Number.POSITIVE_INFINITY}function cs(n,t){if(t==null)return!1;for(const e of n)if(t[e])return e;return!1}const Ft=()=>{const n=De(),t=De(),e={emit:n.emit,on:i=>t.on(i)},s={emit:t.emit,on:i=>n.on(i)};return[e,s]},ls=()=>{const n=De();return{emit:s=>{n.emit(s)},on:s=>{n.on(s)}}};class Vt{constructor(t){_(this,"reachValue",1e3);_(this,"m");this.m=structuredClone(t)}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}update(t,e){for(let s in e){const i=e[s],r=t[i];this.m[s]+=r}}}class Jt{constructor(t,e){_(this,"pToW",{});_(this,"wToP",H(""));_(this,"round");_(this,"sticks");this.round=(e==null?void 0:e.round)??C.E1,this.sticks=structuredClone(e==null?void 0:e.sticks)??{reach:0,dead:0},this.pToW=structuredClone(t);for(let s in this.pToW)this.wToP[this.pToW[s]]=s}update(){for(let t in this.pToW){const e=me(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Gt(this.round);this.round=t,this.update()}resetDeadStick(){this.sticks.dead=0}resetReachStick(){this.sticks.reach=0}is(t){return this.round==t}wind(t){return this.pToW[t]}playerID(t){return this.wToP[t]}get playerMap(){return structuredClone(this.pToW)}}function on(n){for(let t=n.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[n[t],n[e]]=[n[e],n[t]]}return n}class hs{constructor(t=!1){_(this,"c");_(this,"safeMap",H({},!0));this.disable=t,this.c=this.initial()}get(t){return t.t==g.BACK?0:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=g.BACK){if(this.get(e)<=0)throw new Error(`[counter] cannot decrease ${e.toString()} due to zero`);this.c[e.t][e.n]-=1,e.has(y.RED)&&(this.c[e.t][0]-=1)}}}addTileToSafeMap(t,e){this.disable||(this.safeMap[e][this.key(t.t,t.n)]=!0)}isSafeTile(t,e,s){return this.safeMap[s][this.key(t,e)]}key(t,e){return`${t}${e}`}reset(){this.c=this.initial()}initial(){return{[g.M]:[1,4,4,4,4,4,4,4,4,4],[g.S]:[1,4,4,4,4,4,4,4,4,4],[g.P]:[1,4,4,4,4,4,4,4,4,4],[g.Z]:[0,4,4,4,4,4,4,4]}}}class an{constructor(){_(this,"m",[])}discard(t,e){this.m.push({w:e,t})}discards(t){return t==null?[...this.m]:this.m.filter(e=>e.w==t)}get lastTile(){const t=this.m.at(-1);return I(t!=null,`lastTile is null(${t}). river: ${JSON.stringify(this.m,null,2)}`),t}markCalled(){this.lastTile.callMarker=!0}cannotContinue(){const t=this.discards();if(t.length!=4)return!1;let e=t[0].t;if(e.isNum())return!1;for(let s=0;s<4;s++)if(!e.equals(t[s].t))return!1;return!0}}function Kr(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function zr(){const n=Kr();if(n.__xstate__)return n.__xstate__}const Lr=n=>{if(typeof window>"u")return;const t=zr();t&&t.register(n)};class Cn{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current){this._last.next=e,this._last=e;return}this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const us=".",jr="",ds="",Ur="#",Fr="*",fs="xstate.init",Ke="xstate.stop";function Zr(n,t){return{type:`xstate.after.${n}.${t}`}}function ze(n,t){return{type:`xstate.done.state.${n}`,output:t}}function Gr(n,t){return{type:`xstate.done.actor.${n}`,output:t,actorId:n}}function Vr(n,t){return{type:`xstate.error.actor.${n}`,error:t,actorId:n}}function ps(n){return{type:fs,input:n}}function tt(n){setTimeout(()=>{throw n})}const Jr=typeof Symbol=="function"&&Symbol.observable||"@@observable";function gs(n,t){const e=Rn(n),s=Rn(t);return typeof s=="string"?typeof e=="string"?s===e:!1:typeof e=="string"?e in s:Object.keys(e).every(i=>i in s?gs(e[i],s[i]):!1)}function cn(n){if(ms(n))return n;const t=[];let e="";for(let s=0;s<n.length;s++){switch(n.charCodeAt(s)){case 92:e+=n[s+1],s++;continue;case 46:t.push(e),e="";continue}e+=n[s]}return t.push(e),t}function Rn(n){if(Co(n))return n.value;if(typeof n!="string")return n;const t=cn(n);return Yr(t)}function Yr(n){if(n.length===1)return n[0];const t={};let e=t;for(let s=0;s<n.length-1;s++)if(s===n.length-2)e[n[s]]=n[s+1];else{const i=e;e={},i[n[s]]=e}return t}function xn(n,t){const e={},s=Object.keys(n);for(let i=0;i<s.length;i++){const r=s[i];e[r]=t(n[r],r,n,i)}return e}function ys(n){return ms(n)?n:[n]}function rt(n){return n===void 0?[]:ys(n)}function Le(n,t,e,s){return typeof n=="function"?n({context:t,event:e,self:s}):n}function ms(n){return Array.isArray(n)}function Xr(n){return n.type.startsWith("xstate.error.actor")}function vt(n){return ys(n).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function ws(n){if(!(n===void 0||n===jr))return rt(n)}function je(n,t,e){var r,o,a;const s=typeof n=="object",i=s?n:void 0;return{next:(r=s?n.next:n)==null?void 0:r.bind(i),error:(o=s?n.error:t)==null?void 0:o.bind(i),complete:(a=s?n.complete:e)==null?void 0:a.bind(i)}}function Mn(n,t){return`${t}.${n}`}function ln(n,t){const e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return n.implementations.actors[t];const[,s,i]=e,o=n.getStateNodeById(i).config.invoke;return(Array.isArray(o)?o[s]:o).src}function $n(n,t){return`${n.sessionId}.${t}`}let qr=0;function Qr(n,t){const e=new Map,s=new Map,i=new WeakMap,r=new Set,o={},{clock:a,logger:c}=t,l={schedule:(d,p,f,m,A=Math.random().toString(36).slice(2))=>{const S={source:d,target:p,event:f,delay:m,id:A,startedAt:Date.now()},R=$n(d,A);u._snapshot._scheduledEvents[R]=S;const N=a.setTimeout(()=>{delete o[R],delete u._snapshot._scheduledEvents[R],u._relay(d,p,f)},m);o[R]=N},cancel:(d,p)=>{const f=$n(d,p),m=o[f];delete o[f],delete u._snapshot._scheduledEvents[f],m!==void 0&&a.clearTimeout(m)},cancelAll:d=>{for(const p in u._snapshot._scheduledEvents){const f=u._snapshot._scheduledEvents[p];f.source===d&&l.cancel(d,f.id)}}},h=d=>{if(!r.size)return;const p={...d,rootId:n.sessionId};r.forEach(f=>{var m;return(m=f.next)==null?void 0:m.call(f,p)})},u={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${qr++}`,_register:(d,p)=>(e.set(d,p),d),_unregister:d=>{e.delete(d.sessionId);const p=i.get(d);p!==void 0&&(s.delete(p),i.delete(d))},get:d=>s.get(d),_set:(d,p)=>{const f=s.get(d);if(f&&f!==p)throw new Error(`Actor with system ID '${d}' already exists.`);s.set(d,p),i.set(p,d)},inspect:d=>{const p=je(d);return r.add(p),{unsubscribe(){r.delete(p)}}},_sendInspectionEvent:h,_relay:(d,p,f)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:p,event:f}),p._send(f)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const d=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const p in d){const{source:f,target:m,event:A,delay:S,id:R}=d[p];l.schedule(f,m,A,S,R)}},_clock:a,_logger:c};return u}let Te=!1;const hn=1;let B=function(n){return n[n.NotStarted=0]="NotStarted",n[n.Running=1]="Running",n[n.Stopped=2]="Stopped",n}({});const to={clock:{setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:n=>clearTimeout(n)},logger:console.log.bind(console),devTools:!1};class eo{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Cn(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=B.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...to,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:h}=s;this.system=o?o.system:Qr(this,{clock:i,logger:r}),h&&!o&&this.system.inspect(je(h)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=(e==null?void 0:e.logger)??this.system._logger,this.clock=(e==null?void 0:e.clock)??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:u=>{this._deferred.push(u)},system:this.system,stopChild:u=>{if(u._parent!==this)throw new Error(`Cannot stop child actor ${u.id} of ${this.id} because it is not a child`);u._stop()},emit:u=>{const d=this.eventListeners.get(u.type),p=this.eventListeners.get("*");if(!d&&!p)return;const f=[...d?d.values():[],...p?p.values():[]];for(const m of f)m(u)},actionExecutor:u=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:u.type,params:u.params}}),!u.exec)return;const p=Te;try{Te=!0,u.exec(u.info,u.params)}finally{Te=p}};this._processingStatus===B.Running?d():this._deferred.push(d)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),l&&(this._systemId=l,this.system._set(l,this)),this._initState((e==null?void 0:e.snapshot)??(e==null?void 0:e.state)),l&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){var e;try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,(e=this.options)==null?void 0:e.input)}catch(s){this._snapshot={status:"error",output:void 0,error:s}}}update(t,e){var i,r;this._snapshot=t;let s;for(;s=this._deferred.shift();)try{s()}catch(o){this._deferred.length=0,this._snapshot={...t,status:"error",error:o}}switch(this._snapshot.status){case"active":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){tt(a)}break;case"done":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){tt(a)}this._stopProcedure(),this._complete(),this._doneEvent=Gr(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){var r;const i=je(t,e,s);if(this._processingStatus!==B.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{(r=i.complete)==null||r.call(i)}catch(o){tt(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)tt(o);else try{i.error(o)}catch(a){tt(a)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const i=e.bind(void 0);return s.add(i),{unsubscribe:()=>{s.delete(i)}}}start(){if(this._processingStatus===B.Running)return this;this._syncSnapshot&&this.subscribe({next:s=>{s.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:s})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=B.Running;const t=ps(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(s){return this._snapshot={...this._snapshot,status:"error",error:s},this._error(s),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){s={err:i}}if(s){const{err:i}=s;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(e,t),t.type===Ke&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===B.Stopped?this:(this.mailbox.clear(),this._processingStatus===B.NotStarted?(this._processingStatus=B.Stopped,this):(this.mailbox.enqueue({type:Ke}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var t;for(const e of this.observers)try{(t=e.complete)==null||t.call(e)}catch(s){tt(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||tt(t);return}let e=!1;for(const s of this.observers){const i=s.error;e||(e=!i);try{i==null||i(t)}catch(r){tt(r)}}this.observers.clear(),e&&tt(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Vr(this.id,t))}_stopProcedure(){return this._processingStatus!==B.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Cn(this._process.bind(this)),this._processingStatus=B.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==B.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:Lr)(this)}toJSON(){return{xstate$$type:hn,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Jr](){return this}getSnapshot(){return this._snapshot}}function Ht(n,...[t]){return new eo(n,t)}function no(n,t,e,s,{sendId:i}){const r=typeof i=="function"?i(e,s):i;return[t,{sendId:r},void 0]}function so(n,t){n.defer(()=>{n.system.scheduler.cancel(n.self,t.sendId)})}function io(n){function t(e,s){}return t.type="xstate.cancel",t.sendId=n,t.resolve=no,t.execute=so,t}function ro(n,t,e,s,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?ln(t.machine,o):o,h=typeof i=="function"?i(e):i;let u,d;return l&&(d=typeof a=="function"?a({context:t.context,event:e.event,self:n.self}):a,u=Ht(l,{id:h,src:o,parent:n.self,syncSnapshot:c,systemId:r,input:d})),[At(t,{children:{...t.children,[h]:u}}),{id:i,systemId:r,actorRef:u,src:o,input:d},void 0]}function oo(n,{actorRef:t}){t&&n.defer(()=>{t._processingStatus!==B.Stopped&&t.start()})}function ao(...[n,{id:t,systemId:e,input:s,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="xstate.spawnChild",r.id=t,r.systemId=e,r.src=n,r.input=s,r.syncSnapshot=i,r.resolve=ro,r.execute=oo,r}function co(n,t,e,s,{actorRef:i}){const r=typeof i=="function"?i(e,s):i,o=typeof r=="string"?t.children[r]:r;let a=t.children;return o&&(a={...a},delete a[o.id]),[At(t,{children:a}),o,void 0]}function lo(n,t){if(t){if(n.system._unregister(t),t._processingStatus!==B.Running){n.stopChild(t);return}n.defer(()=>{n.stopChild(t)})}}function bs(n){function t(e,s){}return t.type="xstate.stopChild",t.actorRef=n,t.resolve=co,t.execute=lo,t}function un(n,t,e,s){const{machine:i}=s,r=typeof n=="function",o=r?n:i.implementations.guards[typeof n=="string"?n:n.type];if(!r&&!o)throw new Error(`Guard '${typeof n=="string"?n:n.type}' is not implemented.'.`);if(typeof o!="function")return un(o,t,e,s);const a={context:t,event:e},c=r||typeof n=="string"?void 0:"params"in n?typeof n.params=="function"?n.params({context:t,event:e}):n.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}const dn=n=>n.type==="atomic"||n.type==="final";function Wt(n){return Object.values(n.states).filter(t=>t.type!=="history")}function Qt(n,t){const e=[];if(t===n)return e;let s=n.parent;for(;s&&s!==t;)e.push(s),s=s.parent;return e}function de(n){const t=new Set(n),e=Es(t);for(const s of t)if(s.type==="compound"&&(!e.get(s)||!e.get(s).length))Pn(s).forEach(i=>t.add(i));else if(s.type==="parallel"){for(const i of Wt(s))if(i.type!=="history"&&!t.has(i)){const r=Pn(i);for(const o of r)t.add(o)}}for(const s of t){let i=s.parent;for(;i;)t.add(i),i=i.parent}return t}function _s(n,t){const e=t.get(n);if(!e)return{};if(n.type==="compound"){const i=e[0];if(i){if(dn(i))return i.key}else return{}}const s={};for(const i of e)s[i.key]=_s(i,t);return s}function Es(n){const t=new Map;for(const e of n)t.has(e)||t.set(e,[]),e.parent&&(t.has(e.parent)||t.set(e.parent,[]),t.get(e.parent).push(e));return t}function As(n,t){const e=de(t);return _s(n,Es(e))}function fn(n,t){return t.type==="compound"?Wt(t).some(e=>e.type==="final"&&n.has(e)):t.type==="parallel"?Wt(t).every(e=>fn(n,e)):t.type==="final"}const Ee=n=>n[0]===Ur;function ho(n,t){return n.transitions.get(t)||[...n.transitions.keys()].filter(s=>{if(s===Fr)return!0;if(!s.endsWith(".*"))return!1;const i=s.split("."),r=t.split(".");for(let o=0;o<i.length;o++){const a=i[o],c=r[o];if(a==="*")return o===i.length-1;if(a!==c)return!1}return!0}).sort((s,i)=>i.length-s.length).flatMap(s=>n.transitions.get(s))}function uo(n){const t=n.config.after;if(!t)return[];const e=i=>{const r=Zr(i,n.id),o=r.type;return n.entry.push(Ko(r,{id:o,delay:i})),n.exit.push(io(o)),o};return Object.keys(t).flatMap(i=>{const r=t[i],o=typeof r=="string"?{target:r}:r,a=Number.isNaN(+i)?i:+i,c=e(a);return rt(o).map(l=>({...l,event:c,delay:a}))}).map(i=>{const{delay:r}=i;return{...yt(n,i.event,i),delay:r}})}function yt(n,t,e){const s=ws(e.target),i=e.reenter??!1,r=go(n,s),o={...e,actions:rt(e.actions),guard:e.guard,target:r,source:n,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${n.id}`,target:r?r.map(a=>`#${a.id}`):void 0})};return o}function fo(n){const t=new Map;if(n.config.on)for(const e of Object.keys(n.config.on)){if(e===ds)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=n.config.on[e];t.set(e,vt(s).map(i=>yt(n,e,i)))}if(n.config.onDone){const e=`xstate.done.state.${n.id}`;t.set(e,vt(n.config.onDone).map(s=>yt(n,e,s)))}for(const e of n.invoke){if(e.onDone){const s=`xstate.done.actor.${e.id}`;t.set(s,vt(e.onDone).map(i=>yt(n,s,i)))}if(e.onError){const s=`xstate.error.actor.${e.id}`;t.set(s,vt(e.onError).map(i=>yt(n,s,i)))}if(e.onSnapshot){const s=`xstate.snapshot.${e.id}`;t.set(s,vt(e.onSnapshot).map(i=>yt(n,s,i)))}}for(const e of n.after){let s=t.get(e.eventType);s||(s=[],t.set(e.eventType,s)),s.push(e)}return t}function po(n,t){const e=typeof t=="string"?n.states[t]:t?n.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${n.id}`);const s={source:n,actions:!t||typeof t=="string"?[]:rt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...s,source:`#${n.id}`,target:e?[`#${e.id}`]:[]})};return s}function go(n,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(Ee(e))return n.machine.getStateNodeById(e);const s=e[0]===us;if(s&&!n.parent)return fe(n,e.slice(1));const i=s?n.key+e:e;if(n.parent)try{return fe(n.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${n.id}':
|
|
14
|
-
${r.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function Ss(n){const t=ws(n.config.target);return t?{target:t.map(e=>typeof e=="string"?fe(n.parent,e):e)}:n.parent.initial}function wt(n){return n.type==="history"}function Pn(n){const t=Ns(n);for(const e of t)for(const s of Qt(e,n))t.add(s);return t}function Ns(n){const t=new Set;function e(s){if(!t.has(s)){if(t.add(s),s.type==="compound")e(s.initial.target[0]);else if(s.type==="parallel")for(const i of Wt(s))e(i)}}return e(n),t}function Bt(n,t){if(Ee(t))return n.machine.getStateNodeById(t);if(!n.states)throw new Error(`Unable to retrieve child state '${t}' from '${n.id}'; no child states exist.`);const e=n.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${n.id}'`);return e}function fe(n,t){if(typeof t=="string"&&Ee(t))try{return n.machine.getStateNodeById(t)}catch{}const e=cn(t).slice();let s=n;for(;e.length;){const i=e.shift();if(!i.length)break;s=Bt(s,i)}return s}function pe(n,t){if(typeof t=="string"){const i=n.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${n.id}'`);return[n,i]}const e=Object.keys(t),s=e.map(i=>Bt(n,i)).filter(Boolean);return[n.machine.root,n].concat(s,e.reduce((i,r)=>{const o=Bt(n,r);if(!o)return i;const a=pe(o,t[r]);return i.concat(a)},[]))}function yo(n,t,e,s){const r=Bt(n,t).next(e,s);return!r||!r.length?n.next(e,s):r}function mo(n,t,e,s){const i=Object.keys(t),r=Bt(n,i[0]),o=pn(r,t[i[0]],e,s);return!o||!o.length?n.next(e,s):o}function wo(n,t,e,s){const i=[];for(const r of Object.keys(t)){const o=t[r];if(!o)continue;const a=Bt(n,r),c=pn(a,o,e,s);c&&i.push(...c)}return i.length?i:n.next(e,s)}function pn(n,t,e,s){return typeof t=="string"?yo(n,t,e,s):Object.keys(t).length===1?mo(n,t,e,s):wo(n,t,e,s)}function bo(n){return Object.keys(n.states).map(t=>n.states[t]).filter(t=>t.type==="history")}function ct(n,t){let e=n;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function _o(n,t){const e=new Set(n),s=new Set(t);for(const i of e)if(s.has(i))return!0;for(const i of s)if(e.has(i))return!0;return!1}function Is(n,t,e){const s=new Set;for(const i of n){let r=!1;const o=new Set;for(const a of s)if(_o(Ue([i],t,e),Ue([a],t,e)))if(ct(i.source,a.source))o.add(a);else{r=!0;break}if(!r){for(const a of o)s.delete(a);s.add(i)}}return Array.from(s)}function Eo(n){const[t,...e]=n;for(const s of Qt(t,void 0))if(e.every(i=>ct(i,s)))return s}function gn(n,t){if(!n.target)return[];const e=new Set;for(const s of n.target)if(wt(s))if(t[s.id])for(const i of t[s.id])e.add(i);else for(const i of gn(Ss(s),t))e.add(i);else e.add(s);return[...e]}function vs(n,t){const e=gn(n,t);if(!e)return;if(!n.reenter&&e.every(i=>i===n.source||ct(i,n.source)))return n.source;const s=Eo(e.concat(n.source));if(s)return s;if(!n.reenter)return n.source.machine.root}function Ue(n,t,e){var i;const s=new Set;for(const r of n)if((i=r.target)!=null&&i.length){const o=vs(r,e);r.reenter&&r.source===o&&s.add(o);for(const a of t)ct(a,o)&&s.add(a)}return[...s]}function Ao(n,t){if(n.length!==t.size)return!1;for(const e of n)if(!t.has(e))return!1;return!0}function Fe(n,t,e,s,i,r){if(!n.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=Is(n,o,a);let l=t;i||([l,a]=vo(l,s,e,c,o,a,r,e.actionExecutor)),l=Dt(l,s,e,c.flatMap(u=>u.actions),r,void 0),l=No(l,s,e,c,o,r,a,i);const h=[...o];l.status==="done"&&(l=Dt(l,s,e,h.sort((u,d)=>d.order-u.order).flatMap(u=>u.exit),r,void 0));try{return a===t.historyValue&&Ao(t._nodes,o)?l:At(l,{_nodes:h,historyValue:a})}catch(u){throw u}}function So(n,t,e,s,i){if(s.output===void 0)return;const r=ze(i.id,i.output!==void 0&&i.parent?Le(i.output,n.context,t,e.self):void 0);return Le(s.output,n.context,r,e.self)}function No(n,t,e,s,i,r,o,a){let c=n;const l=new Set,h=new Set;Io(s,o,h,l),a&&h.add(n.machine.root);const u=new Set;for(const d of[...l].sort((p,f)=>p.order-f.order)){i.add(d);const p=[];p.push(...d.entry);for(const f of d.invoke)p.push(ao(f.src,{...f,syncSnapshot:!!f.onSnapshot}));if(h.has(d)){const f=d.initial.actions;p.push(...f)}if(c=Dt(c,t,e,p,r,d.invoke.map(f=>f.id)),d.type==="final"){const f=d.parent;let m=(f==null?void 0:f.type)==="parallel"?f:f==null?void 0:f.parent,A=m||d;for((f==null?void 0:f.type)==="compound"&&r.push(ze(f.id,d.output!==void 0?Le(d.output,c.context,t,e.self):void 0));(m==null?void 0:m.type)==="parallel"&&!u.has(m)&&fn(i,m);)u.add(m),r.push(ze(m.id)),A=m,m=m.parent;if(m)continue;c=At(c,{status:"done",output:So(c,t,e,c.machine.root,A)})}}return c}function Io(n,t,e,s){for(const i of n){const r=vs(i,t);for(const a of i.target||[])!wt(a)&&(i.source!==a||i.source!==r||i.reenter)&&(s.add(a),e.add(a)),Ot(a,t,e,s);const o=gn(i,t);for(const a of o){const c=Qt(a,r);(r==null?void 0:r.type)==="parallel"&&c.push(r),Ts(s,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function Ot(n,t,e,s){var i;if(wt(n))if(t[n.id]){const r=t[n.id];for(const o of r)s.add(o),Ot(o,t,e,s);for(const o of r)Oe(o,n.parent,s,t,e)}else{const r=Ss(n);for(const o of r.target)s.add(o),r===((i=n.parent)==null?void 0:i.initial)&&e.add(n.parent),Ot(o,t,e,s);for(const o of r.target)Oe(o,n.parent,s,t,e)}else if(n.type==="compound"){const[r]=n.initial.target;wt(r)||(s.add(r),e.add(r)),Ot(r,t,e,s),Oe(r,n,s,t,e)}else if(n.type==="parallel")for(const r of Wt(n).filter(o=>!wt(o)))[...s].some(o=>ct(o,r))||(wt(r)||(s.add(r),e.add(r)),Ot(r,t,e,s))}function Ts(n,t,e,s,i){for(const r of s)if((!i||ct(r,i))&&n.add(r),r.type==="parallel")for(const o of Wt(r).filter(a=>!wt(a)))[...n].some(a=>ct(a,o))||(n.add(o),Ot(o,t,e,n))}function Oe(n,t,e,s,i){Ts(e,s,i,Qt(n,t))}function vo(n,t,e,s,i,r,o,a){let c=n;const l=Ue(s,i,r);l.sort((u,d)=>d.order-u.order);let h;for(const u of l)for(const d of bo(u)){let p;d.history==="deep"?p=f=>dn(f)&&ct(f,u):p=f=>f.parent===u,h??(h={...r}),h[d.id]=Array.from(i).filter(p)}for(const u of l)c=Dt(c,t,e,[...u.exit,...u.invoke.map(d=>bs(d.id))],o,void 0),i.delete(u);return[c,h||r]}function To(n,t){return n.implementations.actions[t]}function Os(n,t,e,s,i,r){const{machine:o}=n;let a=n;for(const c of s){const l=typeof c=="function",h=l?c:To(o,typeof c=="string"?c:c.type),u={context:a.context,event:t,self:e.self,system:e.system},d=l||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:t}):c.params:void 0;if(!h||!("resolve"in h)){e.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:u,params:d,exec:h});continue}const p=h,[f,m,A]=p.resolve(e,a,u,d,h,i);a=f,"retryResolve"in p&&(r==null||r.push([p,m])),"execute"in p&&e.actionExecutor({type:p.type,info:u,params:m,exec:p.execute.bind(null,e,m)}),A&&(a=Os(a,t,e,A,i,r))}return a}function Dt(n,t,e,s,i,r){const o=r?[]:void 0,a=Os(n,t,e,s,{internalQueue:i,deferredActorIds:r},o);return o==null||o.forEach(([c,l])=>{c.retryResolve(e,a,l)}),a}function ke(n,t,e,s){let i=n;const r=[];function o(l,h,u){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:h,snapshot:l,_transitions:u}),r.push(l)}if(t.type===Ke)return i=At(Hn(i,t,e),{status:"stopped"}),o(i,t,[]),{snapshot:i,microstates:r};let a=t;if(a.type!==fs){const l=a,h=Xr(l),u=Wn(l,i);if(h&&!u.length)return i=At(n,{status:"error",error:l.error}),o(i,l,[]),{snapshot:i,microstates:r};i=Fe(u,n,e,a,!1,s),o(i,l,u)}let c=!0;for(;i.status==="active";){let l=c?Oo(i,a):[];const h=l.length?i:void 0;if(!l.length){if(!s.length)break;a=s.shift(),l=Wn(a,i)}i=Fe(l,i,e,a,!1,s),c=i!==h,o(i,a,l)}return i.status!=="active"&&Hn(i,a,e),{snapshot:i,microstates:r}}function Hn(n,t,e){return Dt(n,t,e,Object.values(n.children).map(s=>bs(s)),[],void 0)}function Wn(n,t){return t.machine.getTransitionData(t,n)}function Oo(n,t){const e=new Set,s=n._nodes.filter(dn);for(const i of s)t:for(const r of[i].concat(Qt(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||un(o.guard,n.context,t,n)){e.add(o);break t}}return Is(Array.from(e),new Set(n._nodes),n.historyValue)}function ko(n,t){const e=de(pe(n,t));return As(n,[...e])}function Co(n){return!!n&&typeof n=="object"&&"machine"in n&&"value"in n}const Ro=function(t){return gs(t,this.value)},xo=function(t){return this.tags.has(t)},Mo=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(s=>s.target!==void 0||s.actions.length)},$o=function(){const{_nodes:t,tags:e,machine:s,getMeta:i,toJSON:r,can:o,hasTag:a,matches:c,...l}=this;return{...l,tags:Array.from(e)}},Po=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function oe(n,t){return{status:n.status,output:n.output,error:n.error,machine:t,context:n.context,_nodes:n._nodes,value:As(t.root,n._nodes),tags:new Set(n._nodes.flatMap(e=>e.tags)),children:n.children,historyValue:n.historyValue||{},matches:Ro,hasTag:xo,can:Mo,getMeta:Po,toJSON:$o}}function At(n,t={}){return oe({...n,...t},n.machine)}function Ho(n){if(typeof n!="object"||n===null)return{};const t={};for(const e in n){const s=n[e];Array.isArray(s)&&(t[e]=s.map(i=>({id:i.id})))}return t}function Wo(n,t){const{_nodes:e,tags:s,machine:i,children:r,context:o,can:a,hasTag:c,matches:l,getMeta:h,toJSON:u,...d}=n,p={};for(const m in r){const A=r[m];p[m]={snapshot:A.getPersistedSnapshot(t),src:A.src,systemId:A._systemId,syncSnapshot:A._syncSnapshot}}return{...d,context:ks(o),children:p,historyValue:Ho(d.historyValue)}}function ks(n){let t;for(const e in n){const s=n[e];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)t??(t=Array.isArray(n)?n.slice():{...n}),t[e]={xstate$$type:hn,id:s.id};else{const i=ks(s);i!==s&&(t??(t=Array.isArray(n)?n.slice():{...n}),t[e]=i)}}return t??n}function Bo(n,t,e,s,{event:i,id:r,delay:o},{internalQueue:a}){const c=t.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);const l=typeof i=="function"?i(e,s):i;let h;if(typeof o=="string"){const u=c&&c[o];h=typeof u=="function"?u(e,s):u}else h=typeof o=="function"?o(e,s):o;return typeof h!="number"&&a.push(l),[t,{event:l,id:r,delay:h},void 0]}function Do(n,t){const{event:e,delay:s,id:i}=t;if(typeof s=="number"){n.defer(()=>{const r=n.self;n.system.scheduler.schedule(r,r,e,s,i)});return}}function Ko(n,t){function e(s,i){}return e.type="xstate.raise",e.event=n,e.id=t==null?void 0:t.id,e.delay=t==null?void 0:t.delay,e.resolve=Bo,e.execute=Do,e}function zo(n,{machine:t,context:e},s,i){const r=(o,a)=>{if(typeof o=="string"){const c=ln(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=Ht(c,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:typeof(a==null?void 0:a.input)=="function"?a.input({context:e,event:s,self:n.self}):a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId});return i[l.id]=l,l}else return Ht(o,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId})};return(o,a)=>{const c=r(o,a);return i[c.id]=c,n.defer(()=>{c._processingStatus!==B.Stopped&&c.start()}),c}}function Lo(n,t,e,s,{assignment:i}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const r={},o={context:t.context,event:e.event,spawn:zo(n,t,e.event,r),self:n.self,system:n.system};let a={};if(typeof i=="function")a=i(o,s);else for(const l of Object.keys(i)){const h=i[l];a[l]=typeof h=="function"?h(o,s):h}const c=Object.assign({},t.context,a);return[At(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children}),void 0,void 0]}function jo(n){function t(e,s){}return t.type="xstate.assign",t.assignment=n,t.resolve=Lo,t}const Bn=new WeakMap;function It(n,t,e){let s=Bn.get(n);return s?t in s||(s[t]=e()):(s={[t]:e()},Bn.set(n,s)),s[t]}const Uo={},Lt=n=>typeof n=="string"?{type:n}:typeof n=="function"?"resolve"in n?{type:n.type}:{type:n.name}:n;class ge{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(us),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?xn(this.config.states,(s,i)=>new ge(s,{_parent:this,_key:i,_machine:this.machine})):Uo,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=rt(this.config.entry).slice(),this.exit=rt(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=rt(t.tags).slice()}_initialize(){this.transitions=fo(this),this.config.always&&(this.always=vt(this.config.always).map(t=>yt(this,ds,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(Lt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Lt),eventType:null})}:void 0,history:this.history,states:xn(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Lt)})),entry:this.entry.map(Lt),exit:this.exit.map(Lt),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return It(this,"invoke",()=>rt(this.config.invoke).map((t,e)=>{const{src:s,systemId:i}=t,r=t.id??Mn(this.id,e),o=typeof s=="string"?s:`xstate.invoke.${Mn(this.id,e)}`;return{...t,src:o,id:r,systemId:i,toJSON(){const{onDone:a,onError:c,...l}=t;return{...l,type:"xstate.invoke",src:o,id:r}}}}))}get on(){return It(this,"on",()=>[...this.transitions].flatMap(([e,s])=>s.map(i=>[e,i])).reduce((e,[s,i])=>(e[s]=e[s]||[],e[s].push(i),e),{}))}get after(){return It(this,"delayedTransitions",()=>uo(this))}get initial(){return It(this,"initial",()=>po(this,this.config.initial))}next(t,e){const s=e.type,i=[];let r;const o=It(this,`candidates-${s}`,()=>ho(this,s));for(const a of o){const{guard:c}=a,l=t.context;let h=!1;try{h=!c||un(c,l,e,t)}catch(u){const d=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${d?`'${d}' `:""}in transition for event '${s}' in state node '${this.id}':
|
|
15
|
-
${
|
|
7
|
+
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}at.prototype.build=function(s){return this.options.preserveOrder?Hi(s,this.options):(Array.isArray(s)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(s={[this.options.arrayNodeName]:s}),this.j2x(s,0,[]).val)};at.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 d=0;d<a;d++){const h=s[o][d];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 u=this.j2x(h,t+1,e.concat(o));c+=u.val,this.options.attributesGroupName&&h.hasOwnProperty(this.options.attributesGroupName)&&(l+=u.attrStr)}else c+=this.processTextOrObjNode(h,o,t,e);else if(this.options.oneListGroup){let u=this.options.tagValueProcessor(o,h);u=this.replaceEntitiesValue(u),c+=u}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}};at.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 Ki(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)}at.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}};at.prototype.closeTag=function(s){let t="";return this.options.unpairedTags.indexOf(s)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${s}`,t};at.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}};at.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 zi(s){return this.options.indentBy.repeat(s)}function Li(s){return s.startsWith(this.options.attributeNamePrefix)&&s!==this.options.textNodeName?s.substr(this.attrPrefixLen):!1}class ct{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,jn(this.attrs),Qi(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 Ye extends ct{attrs={};constructor(t){super("image"),this.attrs={...this.attrs,href:t}}load(t){return this.attrs.href=t,this}}class ye extends ct{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 Je extends ct{attrs={};constructor(){super("rect")}fill(t){return this.attrs.fill=t,this}stroke(t){return this.attrs.stroke=t,this}}class wt extends ct{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 Xe=class extends ct{raw;constructor(t){super("symbol"),this.raw=t}id(){return this.attr("id")}center(){return this.raw}};class N extends ct{children=[];rotateMatrix;translateMatrix;constructor(){super("g")}add(t){return this.children.push(t),this}rotate(t,e,n){return this.rotateMatrix=js(t,e,n),this}translate(t,e){return this.translateMatrix=Te(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(qi(Bs(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 ji=['xmlns="http://www.w3.org/2000/svg"','version="1.1"','xmlns:xlink="http://www.w3.org/1999/xlink"'];class zn extends ct{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,...ji,jn(this.attrs),Xi(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 tr(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 Ln(){return new zn}const Ui=Ln,Zi=N,Gi=Ye,Fi=ye,Vi=Je,Yi=wt;function Ji(s){return s.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Xi(s){return s==null?"":`viewBox="${s.x} ${s.y} ${s.width} ${s.height}"`}function qi(s){return s==null?"":`transform="${Us(s)}"`}function jn(s){return Object.entries(s).filter(([t,e])=>e!==void 0).map(([t,e])=>`${Ji(t)}="${e}"`).join(" ")}function Qi(s){const t=Object.entries(s).map(([e,n])=>`${e}: ${n};`).join(" ");return t!=""?`style="${t}"`:""}function*tr(s){const t=new $i({ignoreAttributes:!1}),e=new at({ignoreAttributes:!1}),n=t.parse(s);for(const i of n.svg.symbol){const r=e.build(i),o=new Xe(r);for(const[a,c]of Object.entries(i))a.startsWith("@_")&&(o.attrs[a.substring(2)]=c);yield o}}const F=(s,t)=>{const e=z(s.tiles[0],t),n=e.baseHeight,i=e.baseWidth;if(s.is(b.SHO_KAN))return{width:i*2+n,height:Math.max(i*2,n)};const r=s.tiles.reduce((a,c)=>{const l=z(c,t).height;return l>a?l:a},0);return{width:s.tiles.reduce((a,c)=>a+z(c,t).width,0),height:r}},z=(s,t)=>{const e=parseFloat((it.HEIGHT*t).toPrecision(5)),n=parseFloat((it.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*it.TEXT_SCALE),i};class kt{tileWidth;tileHeight;imageHostUrl;imageExt;scale;svgSprite;constructor(t={}){this.scale=t.scale??1,this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=it.WIDTH*this.scale,this.tileHeight=it.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getDiffTileHeightWidth(t){const e=z(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new Ye().load(this.buildURL(t));return this.svgSprite&&(e=new ye().use(kt.buildID(t))),t instanceof w&&t.has(m.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,n){const i=z(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=z(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,l=o.baseHeight,d=new wt().plain(i);d.size(o.baseWidth,o.baseHeight).font({family:je,size:a}).dx(c).dy(l);const h=new N;return h.add(r).add(d).translate(e,n),h}createRotate90Image(t,e,n,i=!1){const r=this.createImage(t,0,0),o=z(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,l=e+this.getDiffTileHeightWidth(t),d=i?n-this.getDiffTileHeightWidth(t):n,h=new N;return h.add(r).translate(l,d).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==p.BACK||t.has(m.RED)?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${kt.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:e}}class qe extends kt{blockMargin=it.WIDTH*it.BLOCK_MARGIN_SCALE*this.scale;createBlockHandDiscard(t){const e=t instanceof x?t.tilesWithBack:t.tiles,n=new N;let i=0;for(const r of e){const o=z(r,this.scale),a=r.has(m.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),c=r.has(m.HORIZONTAL)?this.getDiffTileHeightWidth(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==b.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=z(t.tiles[o],this.scale);if(o==r)continue;if(o==e){const d=t.tiles[e],h=t.tiles[r],u=z(d,this.scale),g=this.createRotate90Image(d,0,0,!0),f=this.createRotate90Image(h,0,u.height,!0);i.add(new N().translate(n,0).add(g).add(f)),n+=u.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==b.CHI){const r=t.tiles[e],o=this.createRotate90Image(r,n,this.getDiffTileHeightWidth(r));n+=z(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=z(c,this.scale),d=this.createImage(c,n,0);n+=l.width,i.add(d)}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.getDiffTileHeightWidth(a):0,l=z(a,this.scale),d=o(a,n,c);n+=l.width,i.add(d)}return i}}const er=(s,t)=>{const e=s.scale;return{[b.CHI]:function(i){const r=F(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.PON]:function(i){const r=F(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.DAI_KAN]:function(i){const r=F(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.SHO_KAN]:function(i){const r=F(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.AN_KAN]:function(i){I(i instanceof x,`block type is not ankan: ${i.type}`);const r=F(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DORA]:function(i){i=t?.doraText==!1?new Ot([i.tiles[0].clone({remove:m.DORA})]):i;const r=F(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}},[b.TSUMO]:function(i){i=t?.tsumoText==!1?new Ot([i.tiles[0].clone({remove:m.TSUMO})]):i;const r=F(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}},[b.HAND]:function(i){const r=F(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DISCARD]:function(i){const r=F(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[b.THREE]:function(i){throw new Error("three is unsupported")},[b.RUN]:function(i){throw new Error("run is unsupported")},[b.PAIR]:function(i){throw new Error("pair is unsupported")},[b.ISOLATED]:function(i){throw new Error("isolated is unsupported")},[b.UNKNOWN]:function(i){if(i.tiles.some(a=>a.has(m.TSUMO)||a.has(m.DORA)))throw new Error("found an unknown block with operator tiles");const r=F(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}}}},Nt=(s,t,e)=>{const n=er(s,e);let i=0,r=0;const o=[];for(const h of t){const u=n[h.type],g=u(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 d=0;for(const h of o){const u=a-h.height,g=new N().translate(d,u);g.add(h.e),l.add(g),d+=h.width+s.blockMargin}return{e:l,width:c,height:a}},nr=(s,t,e={},n={responsive:!1,doraText:!0,tsumoText:!0})=>{const i=new qe(e),r=Nt(i,t,n);n.responsive||s.size(r.width,r.height),s.viewbox(0,0,r.width,r.height),s.add(r.e)},Un=()=>{const s=[0,1,2,3,4,5,6,7,8,9],t=[];for(const e of Object.values(p)){if(e==p.BACK){t.push(kt.buildID(new w(e,0)));continue}t.push(...s.map(n=>kt.buildID(new w(e,n))).flat())}return t},sr=s=>{const t=Un(),e=[];return s.each((n,i)=>{const r=i[n];if(r instanceof ye){const a=r.attr("href").substring(1);t.includes(a)&&e.push(a)}},!0),e},ir=s=>{const t=Un(),e=sr(s);s.each((n,i)=>{const r=i[n];r instanceof Xe&&(t.includes(r.id())&&e.includes(r.id())||r.remove())},!0)},rr=s=>{const e=[];for(let n=0;n<s.length;n+=6){const i=s.slice(n,n+6);e.push(i)}return e},G=(s,t,e,n,i=0,r=0)=>{const o=new N().add(s);if(n==90){const a=i,c=r-e;return o.rotate(n,0,e).translate(a,c),new N().add(o)}if(n==180){const a=i+t,c=r-e;return o.rotate(n,0,e).translate(a,c),new N().add(o)}if(n==270){const a=i+e,c=r+(t-e);return o.rotate(n,0,e).translate(a,c),new N().add(o)}return new N().add(o)},te=(s,t)=>{const e=new N,n=rr(s);for(let i=0;i<n.length;i++){let r=n[i],o=i*t.tileHeight;const a=t.createBlockHandDiscard(new Fe(r,b.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*n.length}},or=(s,t,e)=>{const n=t.font,i=t.textWidth,r=t.textHeight,o=e.sticks.dead,a=e.sticks.reach,c=Ne.WIDTH*s.scale,l=Ne.HEIGHT*s.scale;let d=i*3,h=r;const u=(c+s.tileWidth+i-d)/2,g=new wt().plain(e.round).font(n).x(u).y(0);h+=25*s.scale;const f=s.tileHeight,y=new N().size(c,f).translate(0,h),E={family:n.family,size:n.size*.7},A=s.createStick(1e3).size(c,l).x(0).y(0),O=new wt().plain(a.toString()).font(E).dx(c).dy(l),v=s.createStick(100).size(c,l).x(0).y(l+l),S=new wt().plain(o.toString()).font(E).dx(c).dy(l*3);y.add(A),y.add(O),y.add(v),y.add(S);const H=s.createImage(e.doras[0],0,0).x(c+i).y(0);y.add(H);const M=new N;return M.add(g),M.add(g),M.add(y),{e:M,width:c+s.tileWidth+i,height:h+s.tileHeight}},ar=(s,t,e=0)=>{const n=Nt(s,t.front),i=Nt(s,t.right),r=Nt(s,t.opposite),o=Nt(s,t.left),a=[n.width,i.width,r.width,o.width].reduce((y,E)=>Math.max(y,E)),c=Math.max(e+s.tileHeight*2+s.blockMargin*2,a+s.tileWidth*2+s.blockMargin),l=c,d=G(n.e,n.width,n.height,0).translate((c-n.width)/2,l-n.height),h=G(i.e,i.width,i.height,270).translate(c-i.height,(c-i.width)/2),u=G(r.e,r.width,r.height,180).translate((c-r.width)/2,0),g=G(o.e,o.width,o.height,90).translate(0,(c-o.width)/2),f=new N().size(c,l);return f.add(d),f.add(h),f.add(u),f.add(g),{e:new N().add(f),width:c,height:l}},cr=s=>{const t=Object.values(pe),e=t.indexOf(s);return[...t.slice(e),...t.slice(0,e)]},lr=(s,t,e)=>{const n=s.tileWidth*5+s.tileHeight*1,i=t.font,r=t.textWidth,o=t.textHeight,a=t.numWidth,c=or(s,t,e);c.e.translate(n/2-c.width/2,n/2-c.height/2);const l=(Ss,un,Ts)=>{const Os=`${Ss} ${un}`,ks=new wt().plain(Os).font(i).attr(Ts);return{e:new N().add(ks),width:r+a*un.toString().length,height:o}},[d,h,u,g]=cr(e.frontPlace),f=e.scores,E=l(d,f.front,{x:n/2,y:n,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let A=l(h,f.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const O=G(A.e,A.width,A.height,270).translate(n,n/2-A.width);let v=l(u,f.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const S=G(v.e,v.width,v.height,180).translate(n/2-v.width,-v.height);let H=l(g,f.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const M=G(H.e,H.width,H.height,90).translate(-H.height,n/2),Q=new N,Ns=new Je().size(n,n).x(0).y(0).fill("none").stroke("#000000");return Q.add(Ns),Q.add(c.e),Q.add(E),Q.add(O),Q.add(S),Q.add(M),{e:Q,width:n,height:n}},hr=(s,t)=>{const e=te(t.front,s),n=te(t.right,s),i=te(t.opposite,s),r=te(t.left,s),o=[e.height,n.height,i.height,r.height].reduce((O,v)=>Math.max(O,v)),a=s.tileWidth*5+s.tileHeight*1,c=o,l=a+o*2+s.blockMargin,d=l,h=new N().size(l,d),u=l/2-a/2,g=d/2-a/2,f=G(e.e,a,c,0).translate(u,d-c),y=G(n.e,a,c,270).translate(l-c,g),E=G(i.e,a,c,180).translate(u,0),A=G(r.e,a,c,90).translate(0,g);return h.add(f),h.add(y),h.add(E),h.add(A),{e:new N().add(h),width:l,height:d}},Zn=(s,t,e,n,i)=>{const r=new N,o=hr(s,n),a=ar(s,e,o.height),c=lr(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}},dr=(s,t,e={},n,i={responsive:!1})=>{const r=new qe(e),o=n,{discards:a,hands:c,scoreBoard:l}=Vn(t),d=Zn(r,o,c,a,l);i.responsive||s.size(d.width,d.height),s.viewbox(0,0,d.width,d.height),s.add(d.e)};var _e;function Gn(s){return{lang:s?.lang??_e?.lang,message:s?.message,abortEarly:s?.abortEarly??_e?.abortEarly,abortPipeEarly:s?.abortPipeEarly??_e?.abortPipeEarly}}var ur;function fr(s){return ur?.get(s)}var pr;function gr(s){return pr?.get(s)}var mr;function yr(s,t){return mr?.get(s)?.get(t)}function Ct(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 rt(s,t,e,n,i){const r=i&&"input"in i?i.input:e.value,o=i?.expected??s.expects??null,a=i?.received??Ct(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",d=i?.message??s.message??yr(s.reference,c.lang)??(l?gr(c.lang):null)??n.message??fr(c.lang);d!==void 0&&(c.message=typeof d=="function"?d(c):d),l&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function Bt(s){return{version:1,vendor:"valibot",validate(t){return s["~run"]({value:t},Gn())}}}function wr(s,t){const e=[...new Set(s)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function Ce(s,t){return{kind:"validation",type:"max_value",reference:Ce,async:!1,expects:`<=${s instanceof Date?s.toJSON():Ct(s)}`,requirement:s,message:t,"~run"(e,n){return e.typed&&!(e.value<=this.requirement)&&rt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():Ct(e.value)}),e}}}function Re(s,t){return{kind:"validation",type:"min_value",reference:Re,async:!1,expects:`>=${s instanceof Date?s.toJSON():Ct(s)}`,requirement:s,message:t,"~run"(e,n){return e.typed&&!(e.value>=this.requirement)&&rt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():Ct(e.value)}),e}}}function br(s,t,e){return typeof s.fallback=="function"?s.fallback(t,e):s.fallback}function Fn(s,t,e){return typeof s.default=="function"?s.default(t,e):s.default}function ae(s){return{kind:"schema",type:"number",reference:ae,expects:"number",async:!1,message:s,get"~standard"(){return Bt(this)},"~run"(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:rt(this,"type",t,e),t}}}function j(s,t){return{kind:"schema",type:"optional",reference:j,expects:`(${s.expects} | undefined)`,async:!1,wrapped:s,default:t,get"~standard"(){return Bt(this)},"~run"(e,n){return e.value===void 0&&(this.default!==void 0&&(e.value=Fn(this,e,n)),e.value===void 0)?(e.typed=!0,e):this.wrapped["~run"](e,n)}}}function xe(s,t){return{kind:"schema",type:"picklist",reference:xe,expects:wr(s.map(Ct),"|"),async:!1,options:s,message:t,get"~standard"(){return Bt(this)},"~run"(e,n){return this.options.includes(e.value)?e.typed=!0:rt(this,"type",e,n),e}}}function Rt(s,t){return{kind:"schema",type:"strict_object",reference:Rt,expects:"Object",async:!1,entries:s,message:t,get"~standard"(){return Bt(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]:Fn(o),c=o["~run"]({value:a},n);if(c.issues){const l={type:"object",origin:"value",input:i,key:r,value:a};for(const d of c.issues)d.path?d.path.unshift(l):d.path=[l],e.issues?.push(d);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]=br(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(rt(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)){rt(this,"key",e,n,{input:r,expected:"never",path:[{type:"object",origin:"key",input:i,key:r,value:i[r]}]});break}}}else rt(this,"type",e,n);return e}}}function ce(s){return{kind:"schema",type:"string",reference:ce,expects:"string",async:!1,message:s,get"~standard"(){return Bt(this)},"~run"(t,e){return typeof t.value=="string"?t.typed=!0:rt(this,"type",t,e),t}}}function _n(...s){return{...s[0],pipe:s,get"~standard"(){return Bt(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 Er(s,t,e){const n=s["~run"]({value:t},Gn(e));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}const ee=j(Rt({discard:j(ce(),""),hand:j(ce(),""),score:j(ae(),25e3)}),{discard:"",hand:"",score:25e3}),_r=Rt({[_.E]:ee,[_.S]:ee,[_.W]:ee,[_.N]:ee}),ht={round:C.E1,sticks:{reach:0,dead:0},doras:_.S,front:_.E},Ar=j(Rt({round:j(xe(Object.keys(Ue)),ht.round),sticks:j(Rt({reach:j(_n(ae(),Re(0,""),Ce(9,"")),ht.sticks.reach),dead:j(_n(ae(),Re(0,""),Ce(9,"")),ht.sticks.dead)}),ht.sticks),doras:j(ce(),ht.doras),front:j(xe(Object.keys(pe)),ht.front)}),ht),vr=Rt({..._r.entries,board:Ar}),Vn=s=>{const t=Yn(s);return Jn(t)},Yn=s=>{const t=Ir(s),e=Er(vr,t);if(!e.success)throw e.issues;return e.output},Ir=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,d]=Sr([...n]);r.board=l;for(let h=0;h<d;h++)n.shift()}else{const[l,d]=Nr([...n]);r[c]=l;for(let h=0;h<d;h++)n.shift()}}return r},Y=(s,t)=>s.replace(t,"").replace(":","").trim(),Nr=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=Y(o,t);else if(o.startsWith(e))i.discard=Y(o,e);else if(o.startsWith(n))i.score=Number(Y(o,n));else break}return[i,r]},Sr=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=Y(l,t);else if(l.startsWith(e))a.round=Y(l,e);else if(l.startsWith(n))a.front=Y(l,n);else if(l.startsWith(i)){a.sticks={};const d=s[c+1]??"",h=s[c+2]??"";d.startsWith(r)&&(a.sticks.reach=Number(Y(d,r))),d.startsWith(o)&&(a.sticks.dead=Number(Y(d,o))),h.startsWith(r)&&(a.sticks.reach=Number(Y(h,r))),h.startsWith(o)&&(a.sticks.dead=Number(Y(h,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},Jn=s=>{const t=s.board.front,e=Tr(t),n=a=>s[a].discard.replace(/\r?\n/g,""),i={front:new K(n(e.front)).tiles(),right:new K(n(e.right)).tiles(),opposite:new K(n(e.opposite)).tiles(),left:new K(n(e.left)).tiles()},r={front:new K(s[e.front].hand).parse(),right:new K(s[e.right].hand).parse(),opposite:new K(s[e.opposite].hand).parse(),left:new K(s[e.left].hand).parse()},o={round:Ue[s.board.round],frontPlace:pe[t],sticks:s.board.sticks,doras:new K(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}},Tr=s=>({front:s,right:yt(s),opposite:yt(yt(s)),left:ge(s)});function*U(s){const t=s?.filterBy&&s.filterBy.length>0?s?.filterBy:Object.values(p);for(const e of t){if(s?.skipBack&&e==p.BACK)continue;const n=e==p.Z?7:e==p.BACK?1:9;for(let i=1;i<=n;i++)yield[e,i]}}class we{data;constructor(t,e=!1){this.data={[p.M]:[0,0,0,0,0,0,0,0,0,0],[p.P]:[0,0,0,0,0,0,0,0,0,0],[p.S]:[0,0,0,0,0,0,0,0,0,0],[p.Z]:[0,0,0,0,0,0,0,0],[p.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const n=Array.isArray(t)?t:new K(t).parse();for(const i of n){if(i.isCalled()){this.data.called=[...this.called,i];continue}else if(i.is(b.TSUMO)){const r=i.tiles[0];this.inc([r]),this.data.tsumo=r;continue}else if(i.is(b.HAND)){this.inc(i.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(r=>r===p.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 U()){let i=this.get(e,n);e!=p.Z&&n==5&&this.get(e,0)>0&&(i-=this.get(e,0),t.push(new w(e,n,[m.RED])));for(let r=0;r<i;r++)t.push(new w(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));I(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?`${et}${this.called.join(et)}`:"",e=this.drawn?`${et}${this.drawn.toString()}`:"",n=this.hands.filter(r=>!r.has(m.TSUMO));return`${new Ot(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 x))}sum(t){let e=0;for(const[n,i]of U({filterBy:[t]}))e+=this.get(n,i);return e}get(t,e){return t==p.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const n of t){const i=n.t!=p.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==p.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==p.BACK?this.data[n.t][1]-=1:(this.data[n.t][n.n]-=1,n.has(m.RED)&&(this.data[n.t][0]-=1)),R(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 x){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof L){const e=this.data.called.findIndex(i=>i.is(b.PON)&&i.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let n=t.tiles[0];n=R(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 we(this.toString());return t.data.reached=this.data.reached,t}}class Xt{hand;constructor(t){this.hand=t}calc(){return Math.min(this.sevenPairs(),this.thirteenOrphans(),this.fourSetsOnePair())}sevenPairs(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const[n,i]of U({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(p)){if(n==p.BACK)continue;const i=n==p.Z?xt:J;for(const r of i)this.hand.get(n,r)>=1&&t++,this.hand.get(n,r)>=2&&e++}return e>=1?12-t:13-t}fourSetsOnePair(){const t=n=>{const i=[0,0,0];for(const[u,g]of U({filterBy:[p.Z]}))this.hand.get(u,g)>=3?i[0]++:this.hand.get(u,g)==2?i[1]++:this.hand.get(u,g)==1&&i[2]++;const r=[0,0,0],o=this.hand.get(p.BACK,0),a=o%3;r[0]=Math.floor(o/3),a==2?r[1]=1:a==1&&(r[2]=1);let c=13;const l=this.patternNumType(p.M),d=this.patternNumType(p.P),h=this.patternNumType(p.S);for(const u of[l.patternA,l.patternB])for(const g of[d.patternA,d.patternB])for(const f of[h.patternA,h.patternB]){const y=[this.hand.called.length,0,0];for(let A=0;A<3;A++)y[A]+=u[A]+g[A]+f[A]+i[A]+r[A];const E=this.calcCommon(y[0],y[1],y[2],n);E<c&&(c=E)}return c};let e=t(!1);for(const[n,i]of U())if(this.hand.get(n,i)>=2){const r=this.hand.dec(new Array(2).fill(new w(n,i))),o=t(!0);this.hand.inc(r),o<e&&(e=o)}return e}patternNumType(t,e=1){if(e>9)return this.groupRemainingTiles(t);let n=this.patternNumType(t,e+1);if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const i=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]),r=this.patternNumType(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<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 w(t,e))),r=this.patternNumType(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 U({filterBy:[t]}))i+=this.hand.get(r,o),o<=7&&this.hand.get(r,o+1)==0&&this.hand.get(r,o+2)==0&&(e+=i>>1,n+=i%2,i=0);return e+=i>>1,n+=i%2,{patternA:[0,e,n],patternB:[0,e,n]}}calcCommon(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 Xn{hand;constructor(t){this.hand=t}calc(t){return this.markDrawn([...this.sevenPairs(),...this.thirteenOrphans(),...this.nineGates(),...this.fourSetsOnePair()],t)}markDrawn(t,e){if(t.length==0)return[];const n=this.hand.drawn!=null||e.has(m.TSUMO)?m.TSUMO:m.RON,i=[];for(let o=0;o<t.length;o++){const a=t[o],c={};for(let l=0;l<a.length;l++){const d=a[l];if(d.isCalled())continue;const h=d.tiles.findIndex(g=>g.equals(e)&&e.has(m.RED)==g.has(m.RED));if(h<0)continue;const u=jt(d);c[u]||(c[u]=!0,i.push([o,l,h]))}}if(i.length==0)throw new Error(`found no tile ${e.toString()} in hands ${t[0].toString()}`);const r=[];for(const[o,a,c]of i){const d=[...t[o]],h=d[a],u=h.tiles[c].clone({add:n});d[a]=h.clone({replace:{idx:c,tile:u}}),r.push(d)}return r}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,n]of U({skipBack:!0})){const i=this.hand.get(e,n);if(i==2){const r=this.hand.dec(new Array(2).fill(new w(e,n)));t.push(new D(r[0],r[1])),this.hand.inc(r)}else{if(i==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const n of Object.values(p)){if(n==p.BACK)continue;const i=n==p.Z?xt:J;for(let r of i)if(this.hand.get(n,r)==1)t.push(new Ge(new w(n,r)));else if(this.hand.get(n,r)==2&&e==!1)t.unshift(new D(new w(n,r),new w(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(p)){if(e==p.BACK||e==p.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 Ot(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,n]of U())if(this.hand.get(e,n)>=2){const i=new Array(2).fill(new w(e,n));n==5&&this.hand.get(e,0)>0&&this.hand.get(e,n)>=3&&(i[1]=new w(e,n,[m.RED]));const r=this.hand.dec(i),o=this.patternAll().filter(a=>a.length==4).map(a=>(a.unshift(new D(r[0],r[1])),a));t=[...t,...o],this.hand.inc(r)}return t}patternAll(){return[this.addRedPattern(p.M,this.handleNumType(p.M)),this.addRedPattern(p.P,this.handleNumType(p.P)),this.addRedPattern(p.S,this.handleNumType(p.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=p.BACK,e=this.hand.get(t,0);if(e<3)return[];const n=new w(t,0),i=Array(Math.floor(e/3)).fill(new Z([n,n,n]));return i.length==0?[]:[i]}handleZ(){const t=[];for(const[e,n]of U({filterBy:[p.Z]})){if(this.hand.get(e,n)==0)continue;if(this.hand.get(e,n)!=3)return[];const i=new w(e,n);t.push(new Z([i,i,i]))}return t.length==0?[]:[t]}addRedPattern(t,e){if(!(this.hand.get(t,0)>0&&this.hand.get(t,5)>=2))return e;const n=new w(t,5),i=new w(t,5,[m.RED]),r=[],o=[];for(let c=0;c<e.length;c++){const l=e[c],d={};for(let h=0;h<l.length;h++){const u=l[h],g=u.tiles.findIndex(E=>E.equals(n)&&!E.has(m.RED)),f=u.tiles.findIndex(E=>E.equals(i)&&E.has(m.RED));if(f>-1&&o.push([c,h,f]),f>-1&&g>-1||g<0)continue;const y=jt(u);d[y]||(d[y]=!0,r.push([c,h,g]))}}if(o.length==0)return e;const a=[];for(const[c,l,d]of r){const u=[...e[c]],g=u[l];u[l]=g.clone({replace:{idx:d,tile:i}});const f=o.find(E=>E[0]==c);if(f==null)continue;const y=u[f[1]];y==null&&console.error(f,r),u[f[1]]=y.clone({replace:{idx:f[2],tile:n}}),jt(g)!=jt(y)&&a.push(u)}return[...e,...a]}handleNumType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.handleNumType(t,e+1);const 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 w(t,e),new w(t,e+1),new w(t,e+2)]);let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new nt([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 w(t,e)));let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new Z([i[0],i[1],i[2]])),n.push(o)}return n}}const xt=[1,2,3,4,5,6,7],J=[1,9],Lt=s=>{const t=s.boardContext;return{...s,hand:s.hand.map(T.deserialize),boardContext:{...t,doraIndicators:t.doraIndicators.map(w.from),hiddenDoraIndicators:t.hiddenDoraIndicators?.map(w.from)}}},le=s=>JSON.parse(JSON.stringify(s));class Me{hand;cfg;constructor(t,e){this.hand=t,this.cfg={doras:e.doraIndicators.map(n=>$e(n)),blindDoras:e.hiddenDoraIndicators==null?[]:e.hiddenDoraIndicators.map(n=>$e(n)),roundWind:w.from(e.round.substring(0,2)),myWind:w.from(e.myWind),reached:e.reached??0,sticks:e.sticks??{dead:0,reach:0},replacementWin:e.replacementWin??!1,quadWin:e.quadWin??!1,finalWallWin:e.finalWallWin??!1,finalDiscardWin:e.finalDiscardWin??!1,oneShotWin:e.oneShotWin??!1,enableRoundUp8000:e.enableRoundUp8000??!1,disableCountable32000:e.disableCountable32000??!1,disableDouble32000:e.disableDouble32000??!1,orig:e}}calc(...t){const e=this.calcPatterns(t);let n=!1,i=!1;if(e.length==0)return!1;let r=[0,0],o=0;for(let v=0;v<e.length;v++){const S=e[v];n=S.is32000??!1;const H=S.yakus.reduce((M,Q)=>M+Q.han,0);H>r[0]?(o=v,r=[H,S.fu]):H==r[0]&&S.fu>r[1]&&(o=v,r=[H,S.fu])}const a=(v,S=100)=>Math.ceil(v/S)*S,c=r[1]!=25?a(r[1],10):25,l=r[0];let d=Math.min(c*2**(l+2),2e3);switch(l){case 26:d=16e3;break;case 13:d=8e3;break;case 12:case 11:d=6e3;break;case 10:case 9:case 8:d=4e3;break;case 7:case 6:d=3e3;break;case 5:d=2e3;break}l>=13&&l<26&&e[o].yakus.every(v=>v.is32000==null||v.is32000==!1)&&(d=this.cfg.disableCountable32000?6e3:8e3,i=!this.cfg.disableCountable32000),this.cfg.enableRoundUp8000&&(c==30&&l==4||c==60&&l==3)&&(d=2e3);const h=e[o].hand.some(v=>v.tiles.some(S=>S.has(m.TSUMO))),u=this.cfg.orig.myWind,g=u==_.E;let f="";const y=P(0);if(h){const v=this.cfg.sticks.dead*100;if(g){const S=a(d*2);y[_.E]+=S*3+v*3,y[_.S]-=S+v,y[_.W]-=S+v,y[_.N]-=S+v,f=`${S}`}else{for(const S of Object.values(_)){if(S==u)continue;const H=S==_.E?2:1,M=a(d*H);y[S]-=M+v,y[u]+=M+v}f=`${a(d*1)}-${a(d*2)}`}}else{const v=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const M=a(d*(g?6:4))+v;y[u]+=M,y[this.cfg.orig.ronWind]-=M,f=`${M}`}const E=y[u]-this.cfg.sticks.dead*300;y[u]+=1e3*this.cfg.sticks.reach;let A;return n?A="役満":i?A="数え役満":d==2e3?A=`${c}符${l}飜 満貫${f}`:d==3e3?A=`${c}符${l}飜 跳満${f}`:d==4e3?A=`${c}符${l}飜 倍満${f}`:d==6e3?A=`${c}符${l}飜 三倍満${f}`:A=`${c}符${l}飜 ${f}`,{deltas:y,han:l,fu:c,yakus:e[o].yakus,points:y[u],rawPoints:E,hand:e[o].hand,boardContext:this.cfg.orig,description:A}}calcPatterns(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.disableDouble32000&&r.han>13&&(r.han=13),r));i.length!=0&&e.push({yakus:i,fu:30,hand:n,is32000:!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,fu:i,hand:n}))}return e}minus(){return this.hand.menzen?0:1}dA1(t){return this.cfg.reached==1?[{name:"立直",han:1}]:this.cfg.reached==2?[{name:"ダブル立直",han:2}]:[]}dB1(t){return this.minus()!=0?[]:(this.hand.drawn==null,t.some(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==p.Z||J.includes(i.n)))?[]:[{name:"断么九",han:1}]}dE1(t){return this.minus()!=0?[]:An(t)==1?[{name:"一盃口",han:1}]:[]}dF1(t){const e=[];return t.forEach(n=>{if(n instanceof D)return;const i=n.tiles[0];i.t==p.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.blindDoras)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 nt||n instanceof X;for(const n of t){if(!e(n))continue;const i=dt(n);if(i.t==p.Z)continue;const r=[p.M,p.P,p.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new w(r[0],i.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(r[1],i.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同順",han:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(n=>n instanceof x||n instanceof L||n instanceof tt||n instanceof Z||n instanceof q||n instanceof D)?[{name:"対々和",han:2}]:[]}dD2(t){return t.filter(n=>(n instanceof x||n instanceof Z)&&!n.tiles.some(i=>i.has(m.RON))).length>=3?[{name:"三暗刻",han:2}]:[]}dE2(t){return t.filter(n=>n instanceof x||n instanceof L||n instanceof tt).length>=3?[{name:"三槓子",han:2}]:[]}dF2(t){const e=n=>n instanceof x||n instanceof L||n instanceof tt||n instanceof Z||n instanceof q;for(const n of t){if(!e(n))continue;const i=dt(n);if(i.t==p.Z)continue;const r=[p.M,p.P,p.S].filter(c=>c!=i.t),o=t.some(c=>{const l=new w(r[0],i.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(r[1],i.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同刻",han:2}]}return[]}dG2(t){return t.length==7?[]:t.filter(n=>{const i=n.tiles[0];return i.t==p.Z&&[5,6,7].includes(i.n)}).length==3?[{name:"小三元",han:2}]:[]}dH2(t){return t.every(n=>{const i=n.tiles[0].t==p.Z?xt:J;return n.tiles.every(r=>i.includes(r.n))})?[{name:"混老頭",han:2}]:[]}dI2(t){return t.length==7?[]:t.some(n=>n instanceof nt||n instanceof X)?t.some(n=>n.tiles[0].t==p.Z)?t.every(n=>{const i=n.tiles[0].t==p.Z?xt:J;return n.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",han:2-this.minus()}]:[]:[]:[]}dJ2(t){const e={[p.M]:[0,0,0],[p.S]:[0,0,0],[p.P]:[0,0,0]};for(const n of t){const i=dt(n);i.t!=p.BACK&&i.t!=p.Z&&(n instanceof nt||n instanceof X)&&(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==p.Z))return[];for(const n of Object.values(p))if(t.every(r=>r.tiles[0].t==p.Z||r.tiles[0].t==n))return[{name:"混一色",han:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(n=>n instanceof nt||n instanceof X)?t.some(n=>n.tiles[0].t==p.Z)?[]:t.every(n=>n.tiles.some(i=>J.includes(i.n)))?[{name:"純全帯么九色",han:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:An(t)==2?[{name:"ニ盃口",han:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==p.Z))return[];for(const e of Object.values(p)){if(e==p.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 D&&n.tiles.some(i=>i.has(m.TSUMO)||i.has(m.RON)))?[{name:"国士無双13面待ち",han:26,is32000:!0}]:[{name:"国士無双",han:13,is32000:!0}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",han:13,is32000:!0}]:[]}dC13(t){return t.length==7?[]:t.every(i=>i instanceof x||i instanceof Z&&i.tiles.every(r=>!r.has(m.RON))||i instanceof D)?t.some(i=>i instanceof D&&i.tiles.some(r=>r.has(m.TSUMO)||r.has(m.RON)))?[{name:"四暗刻単騎待ち",han:26,is32000:!0}]:[{name:"四暗刻",han:13,is32000:!0}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(i=>!(i instanceof D)&&i.tiles.some(r=>r.t==p.Z&&e.includes(r.n))).length==3?[{name:"大三元",han:13,is32000:!0}]:[]}dE13(t){return t.every(n=>n.tiles[0].t==p.Z)?[{name:"字一色",han:13,is32000:!0}]:[]}dF13(t){return t.every(n=>n.tiles.every(i=>i.t!=p.Z&&J.includes(i.n)))?[{name:"清老頭",han:13,is32000:!0}]:[]}dG13(t){return t.filter(n=>n instanceof x||n instanceof L||n instanceof tt).length==4?[{name:"四槓子",han:13,is32000:!0}]:[]}dH13(t){if(t.length==13)return[];if(t.length==7)return[];const e=[1,2,3,4];return t.filter(r=>r.tiles.some(o=>o.t==p.Z&&e.includes(o.n))).length==4?t.find(r=>r instanceof D).tiles.some(r=>r.t==p.Z&&e.includes(r.n))?[{name:"小四喜",han:13,is32000:!0}]:[{name:"大四喜",han:13,is32000:!0}]:[]}dI13(t){const e=n=>!!(n.equals(new w(p.Z,6))||n.t==p.S&&[2,3,4,6,8].includes(n.n));return t.every(n=>n.tiles.every(i=>e(i)))?[{name:"緑一色",han:13,is32000:!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(f=>f.tiles.some(y=>y.has(m.TSUMO)||y.has(m.RON))),a=this.minus()==1,c=o.tiles.some(f=>f.has(m.TSUMO)),l=(f,y)=>{const E=f.tiles[0];return E.t==p.Z||J.includes(E.n)?y*2:y};for(const f of t)switch(!0){case f instanceof Z:const y=f.tiles.some(E=>E.has(m.RON))?2:4;n+=l(f,y);break;case f instanceof q:n+=l(f,2);break;case(f instanceof tt||f instanceof L):n+=l(f,8);break;case f instanceof x:n+=l(f,16);break}n+=(f=>{if(f instanceof Z)return 0;if(f instanceof D)return 2;const y=f.tiles,E=y.findIndex(A=>A.has(m.TSUMO)||A.has(m.RON));return E==1||E==0&&y[2].n==9||E==2&&y[0].n==1?2:0})(o);const u=t.find(f=>f instanceof D).tiles[0];u.t==p.Z&&([5,6,7].includes(u.n)&&(n+=2),(u.n==r||u.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 jt=s=>s.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),An=s=>{const t={};for(const n of s){if(!(n instanceof nt))continue;const i=jt(n);t[i]==null?t[i]=1:t[i]++}let e=0;for(const n in t)t[n]>=2&&e++;return e},dt=s=>[...s.tiles].sort(Jt)[0],$e=s=>{const t=s.n,e=s.t;if(e==p.Z){if(t==4)return new w(e,1);if(t==7)return new w(e,5)}return new w(e,t%9+1)};class Mt{static calcCandidates(t,e,n){I(e.length>0,"choices to discard is zero");const i=new Map;let r=1/0;for(const o of e){const a=t.dec([o]),c=Mt.candidateTiles(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,candidates:c.candidates,tile:l}),r=c.shanten):c.shanten==r&&i.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l})}return Array.from(i.values())}static candidateTiles(t,e){let n=1/0,i=[];const r=new Xt(t);for(const[o,a]of U({skipBack:!0,filterBy:e?.typeFilter})){if(t.get(o,a)>=4)continue;const c=new w(o,a),l=t.inc([c]),d=e?.fourSetsOnePair?r.fourSetsOnePair():r.calc();t.dec(l),d<n?(n=d,i=[c]):d==n&&i.push(c)}return{shanten:n,candidates:i}}}const Pe=()=>{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 qn(s){const t=["RON","DAI_KAN","PON","CHI"],e=s.map(r=>r.choices),i=ts(e,t).map(r=>s[r]);return{events:i,type:es(t,i[0]?.choices)}}function Qn(s){const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=s.map(r=>r.choices),i=ts(e,t).map(r=>s[r]);return{events:i,type:es(t,i[0]?.choices)}}function ts(s,t){let e=[],n=Number.POSITIVE_INFINITY;for(let i=0;i<s.length;i++){const r=s[i];if(Or(r,t)){const o=kr(t,r);o<n?(n=o,e=[i]):o===n&&e.push(i)}}return e}function Or(s,t){return t.some(e=>!!s[e])}function kr(s,t){for(let e=0;e<s.length;e++){const n=s[e];if(t[n])return e}return Number.POSITIVE_INFINITY}function es(s,t){if(t==null)return!1;for(const e of s)if(t[e])return e;return!1}const Ut=()=>{const s=Pe(),t=Pe(),e={emit:s.emit,on:i=>t.on(i)},n={emit:t.emit,on:i=>s.on(i)};return[e,n]},ns=()=>{const s=Pe();return{emit:n=>{s.emit(n)},on:n=>{s.on(n)}}};class Ft{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 Vt{pToW={};wToP=P("");round;sticks;constructor(t,e){this.round=e?.round??C.E1,this.sticks=structuredClone(e?.sticks)??{reach:0,dead:0},this.pToW=structuredClone(t);for(let n in this.pToW)this.wToP[this.pToW[n]]=n}update(){for(let t in this.pToW){const e=ge(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Gt(this.round);this.round=t,this.update()}resetDeadStick(){this.sticks.dead=0}resetReachStick(){this.sticks.reach=0}is(t){return this.round==t}wind(t){return this.pToW[t]}playerID(t){return this.wToP[t]}get playerMap(){return structuredClone(this.pToW)}}function Qe(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 ss{constructor(t=!1){this.disable=t,this.c=this.initial()}c;safeMap=P({},!0);get(t){return t.t==p.BACK?0:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=p.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.safeMap[e][this.key(t.t,t.n)]=!0)}isSafeTile(t,e,n){return this.safeMap[n][this.key(t,e)]}key(t,e){return`${t}${e}`}reset(){this.c=this.initial()}initial(){return{[p.M]:[1,4,4,4,4,4,4,4,4,4],[p.S]:[1,4,4,4,4,4,4,4,4,4],[p.P]:[1,4,4,4,4,4,4,4,4,4],[p.Z]:[0,4,4,4,4,4,4,4]}}}class tn{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 I(t!=null,`lastTile is null(${t}). river: ${JSON.stringify(this.m,null,2)}`),t}markCalled(){this.lastTile.callMarker=!0}cannotContinue(){const t=this.discards();if(t.length!=4)return!1;let e=t[0].t;if(e.isNum())return!1;for(let n=0;n<4;n++)if(!e.equals(t[n].t))return!1;return!0}}function Cr(){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 Rr(){const s=Cr();if(s.__xstate__)return s.__xstate__}const xr=s=>{if(typeof window>"u")return;const t=Rr();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 is=".",Mr="",rs="",$r="#",Pr="*",os="xstate.init",He="xstate.stop";function Hr(s,t){return{type:`xstate.after.${s}.${t}`}}function We(s,t){return{type:`xstate.done.state.${s}`,output:t}}function Wr(s,t){return{type:`xstate.done.actor.${s}`,output:t,actorId:s}}function Br(s,t){return{type:`xstate.error.actor.${s}`,error:t,actorId:s}}function as(s){return{type:os,input:s}}function V(s){setTimeout(()=>{throw s})}const Dr=typeof Symbol=="function"&&Symbol.observable||"@@observable";function cs(s,t){const e=In(s),n=In(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?cs(e[i],n[i]):!1)}function en(s){if(hs(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 In(s){if(Eo(s))return s.value;if(typeof s!="string")return s;const t=en(s);return Kr(t)}function Kr(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 Nn(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 ls(s){return hs(s)?s:[s]}function st(s){return s===void 0?[]:ls(s)}function Be(s,t,e,n){return typeof s=="function"?s({context:t,event:e,self:n}):s}function hs(s){return Array.isArray(s)}function zr(s){return s.type.startsWith("xstate.error.actor")}function It(s){return ls(s).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function ds(s){if(!(s===void 0||s===Mr))return st(s)}function De(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 Sn(s,t){return`${t}.${s}`}function nn(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 Tn(s,t){return`${s.sessionId}.${t}`}let Lr=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:(u,g,f,y,E=Math.random().toString(36).slice(2))=>{const A={source:u,target:g,event:f,delay:y,id:E,startedAt:Date.now()},O=Tn(u,E);h._snapshot._scheduledEvents[O]=A;const v=a.setTimeout(()=>{delete o[O],delete h._snapshot._scheduledEvents[O],h._relay(u,g,f)},y);o[O]=v},cancel:(u,g)=>{const f=Tn(u,g),y=o[f];delete o[f],delete h._snapshot._scheduledEvents[f],y!==void 0&&a.clearTimeout(y)},cancelAll:u=>{for(const g in h._snapshot._scheduledEvents){const f=h._snapshot._scheduledEvents[g];f.source===u&&l.cancel(u,f.id)}}},d=u=>{if(!r.size)return;const g={...u,rootId:s.sessionId};r.forEach(f=>f.next?.(g))},h={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Lr++}`,_register:(u,g)=>(e.set(u,g),u),_unregister:u=>{e.delete(u.sessionId);const g=i.get(u);g!==void 0&&(n.delete(g),i.delete(u))},get:u=>n.get(u),getAll:()=>Object.fromEntries(n.entries()),_set:(u,g)=>{const f=n.get(u);if(f&&f!==g)throw new Error(`Actor with system ID '${u}' already exists.`);n.set(u,g),i.set(g,u)},inspect:u=>{const g=De(u);return r.add(g),{unsubscribe(){r.delete(g)}}},_sendInspectionEvent:d,_relay:(u,g,f)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:u,actorRef:g,event:f}),g._send(f)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const u=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const g in u){const{source:f,target:y,event:E,delay:A,id:O}=u[g];l.schedule(f,y,E,A,O)}},_clock:a,_logger:c};return h}let Ae=!1;const sn=1;let B=(function(s){return s[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Stopped=2]="Stopped",s})({});const Ur={clock:{setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s)},logger:console.log.bind(console),devTools:!1};class Zr{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=B.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...Ur,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:d}=n;this.system=o?o.system:jr(this,{clock:i,logger:r}),d&&!o&&this.system.inspect(De(d)),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 u=this.eventListeners.get(h.type),g=this.eventListeners.get("*");if(!u&&!g)return;const f=[...u?u.values():[],...g?g.values():[]];for(const y of f)try{y(h)}catch(E){V(E)}},actionExecutor:h=>{const u=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:h.type,params:h.params}}),!h.exec)return;const g=Ae;try{Ae=!0,h.exec(h.info,h.params)}finally{Ae=g}};this._processingStatus===B.Running?u():this._deferred.push(u)}},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){V(r)}break;case"done":for(const i of this.observers)try{i.next?.(t)}catch(r){V(r)}this._stopProcedure(),this._complete(),this._doneEvent=Wr(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=De(t,e,n);if(this._processingStatus!==B.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(r){V(r)}break;case"error":{const r=this._snapshot.error;if(!i.error)V(r);else try{i.error(r)}catch(o){V(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===B.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=B.Running;const t=as(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===He&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===B.Stopped?this:(this.mailbox.clear(),this._processingStatus===B.NotStarted?(this._processingStatus=B.Stopped,this):(this.mailbox.enqueue({type:He}),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){V(e)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||V(t);return}let e=!1;for(const n of this.observers){const i=n.error;e||=!i;try{i?.(t)}catch(r){V(r)}}this.observers.clear(),e&&V(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Br(this.id,t))}_stopProcedure(){return this._processingStatus!==B.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new vn(this._process.bind(this)),this._processingStatus=B.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==B.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:xr)(this)}toJSON(){return{xstate$$type:sn,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Dr](){return this}getSnapshot(){return this._snapshot}}function $t(s,...[t]){return new Zr(s,t)}function Gr(s,t,e,n,{sendId:i}){const r=typeof i=="function"?i(e,n):i;return[t,{sendId:r},void 0]}function Fr(s,t){s.defer(()=>{s.system.scheduler.cancel(s.self,t.sendId)})}function Vr(s){function t(e,n){}return t.type="xstate.cancel",t.sendId=s,t.resolve=Gr,t.execute=Fr,t}function Yr(s,t,e,n,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?nn(t.machine,o):o,d=typeof i=="function"?i(e):i;let h,u;return l&&(u=typeof a=="function"?a({context:t.context,event:e.event,self:s.self}):a,h=$t(l,{id:d,src:o,parent:s.self,syncSnapshot:c,systemId:r,input:u})),[Et(t,{children:{...t.children,[d]:h}}),{id:i,systemId:r,actorRef:h,src:o,input:u},void 0]}function Jr(s,{actorRef:t}){t&&s.defer(()=>{t._processingStatus!==B.Stopped&&t.start()})}function Xr(...[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=Yr,r.execute=Jr,r}function qr(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]),[Et(t,{children:a}),o,void 0]}function Qr(s,t){if(t){if(s.system._unregister(t),t._processingStatus!==B.Running){s.stopChild(t);return}s.defer(()=>{s.stopChild(t)})}}function us(s){function t(e,n){}return t.type="xstate.stopChild",t.actorRef=s,t.resolve=qr,t.execute=Qr,t}function rn(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 rn(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 on=s=>s.type==="atomic"||s.type==="final";function Pt(s){return Object.values(s.states).filter(t=>t.type!=="history")}function qt(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 he(s){const t=new Set(s),e=ps(t);for(const n of t)if(n.type==="compound"&&(!e.get(n)||!e.get(n).length))On(n).forEach(i=>t.add(i));else if(n.type==="parallel"){for(const i of Pt(n))if(i.type!=="history"&&!t.has(i)){const r=On(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 fs(s,t){const e=t.get(s);if(!e)return{};if(s.type==="compound"){const i=e[0];if(i){if(on(i))return i.key}else return{}}const n={};for(const i of e)n[i.key]=fs(i,t);return n}function ps(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 gs(s,t){const e=he(t);return fs(s,ps(e))}function an(s,t){return t.type==="compound"?Pt(t).some(e=>e.type==="final"&&s.has(e)):t.type==="parallel"?Pt(t).every(e=>an(s,e)):t.type==="final"}const be=s=>s[0]===$r;function to(s,t){return s.transitions.get(t)||[...s.transitions.keys()].filter(n=>{if(n===Pr)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 eo(s){const t=s.config.after;if(!t)return[];const e=i=>{const r=Hr(i,s.id),o=r.type;return s.entry.push(Co(r,{id:o,delay:i})),s.exit.push(Vr(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 st(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=ds(e.target),i=e.reenter??!1,r=io(s,n),o={...e,actions:st(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 no(s){const t=new Map;if(s.config.on)for(const e of Object.keys(s.config.on)){if(e===rs)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=s.config.on[e];t.set(e,It(n).map(i=>pt(s,e,i)))}if(s.config.onDone){const e=`xstate.done.state.${s.id}`;t.set(e,It(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,It(e.onDone).map(i=>pt(s,n,i)))}if(e.onError){const n=`xstate.error.actor.${e.id}`;t.set(n,It(e.onError).map(i=>pt(s,n,i)))}if(e.onSnapshot){const n=`xstate.snapshot.${e.id}`;t.set(n,It(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 so(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"?[]:st(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...n,source:`#${s.id}`,target:e?[`#${e.id}`]:[]})};return n}function io(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]===is;if(n&&!s.parent)return de(s,e.slice(1));const i=n?s.key+e:e;if(s.parent)try{return de(s.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${s.id}':
|
|
9
|
+
${r.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function ms(s){const t=ds(s.config.target);return t?{target:t.map(e=>typeof e=="string"?de(s.parent,e):e)}:s.parent.initial}function mt(s){return s.type==="history"}function On(s){const t=ys(s);for(const e of t)for(const n of qt(e,s))t.add(n);return t}function ys(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 Pt(n))e(i)}}return e(s),t}function Ht(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 de(s,t){if(typeof t=="string"&&be(t))try{return s.machine.getStateNodeById(t)}catch{}const e=en(t).slice();let n=s;for(;e.length;){const i=e.shift();if(!i.length)break;n=Ht(n,i)}return n}function ue(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=>Ht(s,i)).filter(Boolean);return[s.machine.root,s].concat(n,e.reduce((i,r)=>{const o=Ht(s,r);if(!o)return i;const a=ue(o,t[r]);return i.concat(a)},[]))}function ro(s,t,e,n){const r=Ht(s,t).next(e,n);return!r||!r.length?s.next(e,n):r}function oo(s,t,e,n){const i=Object.keys(t),r=Ht(s,i[0]),o=cn(r,t[i[0]],e,n);return!o||!o.length?s.next(e,n):o}function ao(s,t,e,n){const i=[];for(const r of Object.keys(t)){const o=t[r];if(!o)continue;const a=Ht(s,r),c=cn(a,o,e,n);c&&i.push(...c)}return i.length?i:s.next(e,n)}function cn(s,t,e,n){return typeof t=="string"?ro(s,t,e,n):Object.keys(t).length===1?oo(s,t,e,n):ao(s,t,e,n)}function co(s){return Object.keys(s.states).map(t=>s.states[t]).filter(t=>t.type==="history")}function ot(s,t){let e=s;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function lo(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 ws(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(lo(Ke([i],t,e),Ke([a],t,e)))if(ot(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 ho(s){const[t,...e]=s;for(const n of qt(t,void 0))if(e.every(i=>ot(i,n)))return n}function ln(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 ln(ms(n),t))e.add(i);else e.add(n);return[...e]}function bs(s,t){const e=ln(s,t);if(!e)return;if(!s.reenter&&e.every(i=>i===s.source||ot(i,s.source)))return s.source;const n=ho(e.concat(s.source));if(n)return n;if(!s.reenter)return s.source.machine.root}function Ke(s,t,e){const n=new Set;for(const i of s)if(i.target?.length){const r=bs(i,e);i.reenter&&i.source===r&&n.add(r);for(const o of t)ot(o,r)&&n.add(o)}return[...n]}function uo(s,t){if(s.length!==t.size)return!1;for(const e of s)if(!t.has(e))return!1;return!0}function ze(s,t,e,n,i,r){if(!s.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=ws(s,o,a);let l=t;i||([l,a]=mo(l,n,e,c,o,a,r,e.actionExecutor)),l=Wt(l,n,e,c.flatMap(h=>h.actions),r,void 0),l=po(l,n,e,c,o,r,a,i);const d=[...o];l.status==="done"&&(l=Wt(l,n,e,d.sort((h,u)=>u.order-h.order).flatMap(h=>h.exit),r,void 0));try{return a===t.historyValue&&uo(t._nodes,o)?l:Et(l,{_nodes:d,historyValue:a})}catch(h){throw h}}function fo(s,t,e,n,i){if(n.output===void 0)return;const r=We(i.id,i.output!==void 0&&i.parent?Be(i.output,s.context,t,e.self):void 0);return Be(n.output,s.context,r,e.self)}function po(s,t,e,n,i,r,o,a){let c=s;const l=new Set,d=new Set;go(n,o,d,l),a&&d.add(s.machine.root);const h=new Set;for(const u of[...l].sort((g,f)=>g.order-f.order)){i.add(u);const g=[];g.push(...u.entry);for(const f of u.invoke)g.push(Xr(f.src,{...f,syncSnapshot:!!f.onSnapshot}));if(d.has(u)){const f=u.initial.actions;g.push(...f)}if(c=Wt(c,t,e,g,r,u.invoke.map(f=>f.id)),u.type==="final"){const f=u.parent;let y=f?.type==="parallel"?f:f?.parent,E=y||u;for(f?.type==="compound"&&r.push(We(f.id,u.output!==void 0?Be(u.output,c.context,t,e.self):void 0));y?.type==="parallel"&&!h.has(y)&&an(i,y);)h.add(y),r.push(We(y.id)),E=y,y=y.parent;if(y)continue;c=Et(c,{status:"done",output:fo(c,t,e,c.machine.root,E)})}}return c}function go(s,t,e,n){for(const i of s){const r=bs(i,t);for(const a of i.target||[])!mt(a)&&(i.source!==a||i.source!==r||i.reenter)&&(n.add(a),e.add(a)),St(a,t,e,n);const o=ln(i,t);for(const a of o){const c=qt(a,r);r?.type==="parallel"&&c.push(r),Es(n,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function St(s,t,e,n){if(mt(s))if(t[s.id]){const i=t[s.id];for(const r of i)n.add(r),St(r,t,e,n);for(const r of i)ve(r,s.parent,n,t,e)}else{const i=ms(s);for(const r of i.target)n.add(r),i===s.parent?.initial&&e.add(s.parent),St(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)),St(i,t,e,n),ve(i,s,n,t,e)}else if(s.type==="parallel")for(const i of Pt(s).filter(r=>!mt(r)))[...n].some(r=>ot(r,i))||(mt(i)||(n.add(i),e.add(i)),St(i,t,e,n))}function Es(s,t,e,n,i){for(const r of n)if((!i||ot(r,i))&&s.add(r),r.type==="parallel")for(const o of Pt(r).filter(a=>!mt(a)))[...s].some(a=>ot(a,o))||(s.add(o),St(o,t,e,s))}function ve(s,t,e,n,i){Es(e,n,i,qt(s,t))}function mo(s,t,e,n,i,r,o,a){let c=s;const l=Ke(n,i,r);l.sort((h,u)=>u.order-h.order);let d;for(const h of l)for(const u of co(h)){let g;u.history==="deep"?g=f=>on(f)&&ot(f,h):g=f=>f.parent===h,d??={...r},d[u.id]=Array.from(i).filter(g)}for(const h of l)c=Wt(c,t,e,[...h.exit,...h.invoke.map(u=>us(u.id))],o,void 0),i.delete(h);return[c,d||r]}function yo(s,t){return s.implementations.actions[t]}function _s(s,t,e,n,i,r){const{machine:o}=s;let a=s;for(const c of n){const l=typeof c=="function",d=l?c:yo(o,typeof c=="string"?c:c.type),h={context:a.context,event:t,self:e.self,system:e.system},u=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(!d||!("resolve"in d)){e.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:h,params:u,exec:d});continue}const g=d,[f,y,E]=g.resolve(e,a,h,u,d,i);a=f,"retryResolve"in g&&r?.push([g,y]),"execute"in g&&e.actionExecutor({type:g.type,info:h,params:y,exec:g.execute.bind(null,e,y)}),E&&(a=_s(a,t,e,E,i,r))}return a}function Wt(s,t,e,n,i,r){const o=r?[]:void 0,a=_s(s,t,e,n,{internalQueue:i,deferredActorIds:r},o);return o?.forEach(([c,l])=>{c.retryResolve(e,a,l)}),a}function Ie(s,t,e,n){let i=s;const r=[];function o(l,d,h){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:d,snapshot:l,_transitions:h}),r.push(l)}if(t.type===He)return i=Et(kn(i,t,e),{status:"stopped"}),o(i,t,[]),{snapshot:i,microstates:r};let a=t;if(a.type!==os){const l=a,d=zr(l),h=Cn(l,i);if(d&&!h.length)return i=Et(s,{status:"error",error:l.error}),o(i,l,[]),{snapshot:i,microstates:r};i=ze(h,s,e,a,!1,n),o(i,l,h)}let c=!0;for(;i.status==="active";){let l=c?wo(i,a):[];const d=l.length?i:void 0;if(!l.length){if(!n.length)break;a=n.shift(),l=Cn(a,i)}i=ze(l,i,e,a,!1,n),c=i!==d,o(i,a,l)}return i.status!=="active"&&kn(i,a,e),{snapshot:i,microstates:r}}function kn(s,t,e){return Wt(s,t,e,Object.values(s.children).map(n=>us(n)),[],void 0)}function Cn(s,t){return t.machine.getTransitionData(t,s)}function wo(s,t){const e=new Set,n=s._nodes.filter(on);for(const i of n)t:for(const r of[i].concat(qt(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||rn(o.guard,s.context,t,s)){e.add(o);break t}}return ws(Array.from(e),new Set(s._nodes),s.historyValue)}function bo(s,t){const e=he(ue(s,t));return gs(s,[...e])}function Eo(s){return!!s&&typeof s=="object"&&"machine"in s&&"value"in s}const _o=function(t){return cs(t,this.value)},Ao=function(t){return this.tags.has(t)},vo=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(n=>n.target!==void 0||n.actions.length)},Io=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)}},No=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function ie(s,t){return{status:s.status,output:s.output,error:s.error,machine:t,context:s.context,_nodes:s._nodes,value:gs(t.root,s._nodes),tags:new Set(s._nodes.flatMap(e=>e.tags)),children:s.children,historyValue:s.historyValue||{},matches:_o,hasTag:Ao,can:vo,getMeta:No,toJSON:Io}}function Et(s,t={}){return ie({...s,...t},s.machine)}function So(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 To(s,t){const{_nodes:e,tags:n,machine:i,children:r,context:o,can:a,hasTag:c,matches:l,getMeta:d,toJSON:h,...u}=s,g={};for(const y in r){const E=r[y];g[y]={snapshot:E.getPersistedSnapshot(t),src:E.src,systemId:E.systemId,syncSnapshot:E._syncSnapshot}}return{...u,context:As(o),children:g,historyValue:So(u.historyValue)}}function As(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:sn,id:n.id};else{const i=As(n);i!==n&&(t??=Array.isArray(s)?s.slice():{...s},t[e]=i)}}return t??s}function Oo(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 d;if(typeof o=="string"){const h=c&&c[o];d=typeof h=="function"?h(e,n):h}else d=typeof o=="function"?o(e,n):o;return typeof d!="number"&&a.push(l),[t,{event:l,id:r,delay:d},void 0]}function ko(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 Co(s,t){function e(n,i){}return e.type="xstate.raise",e.event=s,e.id=t?.id,e.delay=t?.delay,e.resolve=Oo,e.execute=ko,e}function Ro(s,{machine:t,context:e},n,i){const r=(o,a)=>{if(typeof o=="string"){const c=nn(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=$t(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 $t(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!==B.Stopped&&c.start()}),c}}function xo(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:Ro(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 d=i[l];a[l]=typeof d=="function"?d(o,n):d}const c=Object.assign({},t.context,a);return[Et(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children}),void 0,void 0]}function Mo(s){function t(e,n){}return t.type="xstate.assign",t.assignment=s,t.resolve=xo,t}const Rn=new WeakMap;function vt(s,t,e){let n=Rn.get(s);return n?t in n||(n[t]=e()):(n={[t]:e()},Rn.set(s,n)),n[t]}const $o={},zt=s=>typeof s=="string"?{type:s}:typeof s=="function"?"resolve"in s?{type:s.type}:{type:s.name}:s;class fe{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(is),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?Nn(this.config.states,(n,i)=>new fe(n,{_parent:this,_key:i,_machine:this.machine})):$o,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=st(this.config.entry).slice(),this.exit=st(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=st(t.tags).slice()}_initialize(){this.transitions=no(this),this.config.always&&(this.always=It(this.config.always).map(t=>pt(this,rs,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(zt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(zt),eventType:null})}:void 0,history:this.history,states:Nn(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(zt)})),entry:this.entry.map(zt),exit:this.exit.map(zt),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",()=>st(this.config.invoke).map((t,e)=>{const{src:n,systemId:i}=t,r=t.id??Sn(this.id,e),o=typeof n=="string"?n:`xstate.invoke.${Sn(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",()=>eo(this))}get initial(){return vt(this,"initial",()=>so(this,this.config.initial))}next(t,e){const n=e.type,i=[];let r;const o=vt(this,`candidates-${n}`,()=>to(this,n));for(const a of o){const{guard:c}=a,l=t.context;let d=!1;try{d=!c||rn(c,l,e,t)}catch(h){const u=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${u?`'${u}' `:""}in transition for event '${n}' in state node '${this.id}':
|
|
10
|
+
${h.message}`)}if(d){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 Po="#";class hn{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 fe(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 hn(this.config,{actions:{...e,...t.actions},guards:{...n,...t.guards},actors:{...i,...t.actors},delays:{...r,...t.delays}})}resolveState(t){const e=bo(this.root,t.value),n=he(ue(this.root,e));return ie({_nodes:[...n],context:t.context||{},children:{},status:an(n,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,n){return Ie(t,e,n,[]).snapshot}microstep(t,e,n){return Ie(t,e,n,[]).microstates}getTransitionData(t,e){return cn(this.root,t.value,t,e)||[]}getPreInitialState(t,e,n){const{context:i}=this.config,r=ie({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?Wt(r,e,t,[Mo(({spawn:a,event:c,self:l})=>i({spawn:a,input:c.input,self:l}))],n,void 0):r}getInitialSnapshot(t,e){const n=as(e),i=[],r=this.getPreInitialState(t,n,i),o=ze([{target:[...ys(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],r,t,n,!0,i),{snapshot:a}=Ie(o,n,t,i);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=en(t),n=e.slice(1),i=be(e[0])?e[0].slice(Po.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 de(r,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return To(t,e)}restoreSnapshot(t,e){const n={},i=t.children;Object.keys(i).forEach(h=>{const u=i[h],g=u.snapshot,f=u.src,y=typeof f=="string"?nn(this,f):f;if(!y)return;const E=$t(y,{id:h,parent:e.self,syncSnapshot:u.syncSnapshot,snapshot:g,src:f,systemId:u.systemId});n[h]=E});function r(h,u){if(u instanceof fe)return u;try{return h.machine.getStateNodeById(u.id)}catch{}}function o(h,u){if(!u||typeof u!="object")return{};const g={};for(const f in u){const y=u[f];for(const E of y){const A=r(h,E);A&&(g[f]??=[],g[f].push(A))}}return g}const a=o(this.root,t.historyValue),c=ie({...t,children:n,_nodes:Array.from(he(ue(this.root,t.value))),historyValue:a},this),l=new Set;function d(h,u){if(!l.has(h)){l.add(h);for(const g in h){const f=h[g];if(f&&typeof f=="object"){if("xstate$$type"in f&&f.xstate$$type===sn){h[g]=u[f.id];continue}d(f,u)}}}}return d(c.context,n),c}}function Ho(s,t){return new hn(s,t)}const ne=s=>s===!1?!1:s.map(t=>t.serialize()),Wo=s=>s===!1?!1:s.serialize(),Bo=s=>s===!1?!1:s.map(t=>({tile:t.tile.toString(),candidates:t.candidates.map(e=>e.toString()),shanten:t.shanten})),se=s=>s===!1?!1:le(s),Le=s=>Ho({id:"Untitled",initial:"distribute",context:{currentWind:_.E,oneShotMap:P(!1),missingMap:P(!1),controller:s,genEventID:vs()},states:{distribute:{on:{NEXT:{target:"drawn"}},entry:{type:"notify_distribution"}},drawn:{entry:{type:"notify_draw"},on:{NEXT:{target:"waiting_user_event_after_drawn",actions:{type:"notify_choice_after_drawn"},description:`可能なアクションとその詳細を通知\\
|
|
16
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:`可能なアクションとその詳細を通知\\
|
|
17
12
|
CHI/PON の場合は鳴ける組み合わせの一覧`}}},tsumo:{exit:[{type:"notify_tsumo"},{type:"notify_end"}],type:"final"},waiting_reach_acceptance:{on:{REACH_ACCEPT:{target:"reached"},RON:{target:"roned",guard:{type:"canWin"}}},description:"リーチに対するアクションは RON か ACCEPT のみである"},waiting_user_event_after_discarded:{description:`最大 4人から choice に対するレスポンスを待つ\\
|
|
18
13
|
ユーザからではなく、controller が優先順位を考慮して遷移させる必要がある\\
|
|
19
|
-
通知する choice がない場合、controller が\\*で遷移させる`,on:{RON:{target:"roned",guard:"canWin"},PON:{target:"poned",guard:"canPon"},CHI:{target:"chied",guard:"canChi"},DAI_KAN:{target:"dai_kaned"},"*":{target:"wildcard_after_discarded"}}},reached:{on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"}}},entry:{type:"notify_reach_accepted"}},roned:{exit:[{type:"notify_ron"},{type:"notify_end"}],type:"final"},poned:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called"}}},entry:[{type:"notify_call"},{type:"disable_none_shot"}]},chied:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called",params:{action:"chi"}}}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},wildcard_after_discarded:{exit:[],always:[{target:"drawn_game",guard:"cannotContinue"},{target:"drawn",actions:[{type:"updateNextWind"}]}]},waiting_discard_event:{description:"鳴いたユーザからの DISCARD イベントを待つ",on:{DISCARD:{target:"discarded"}}},dai_kaned:{on:{NEXT:{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},an_sho_kaned:{always:{target:"waiting_chankan_event"},entry:[{type:"notify_call"},{type:"disable_one_shot"},{type:"notify_new_dora_if_needed"},{type:"notify_choice_for_chankan"}]},waiting_chankan_event:{description:"チャンカンを待つ",on:{"*":{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]},RON:{target:"roned",guard:{type:"canWin"}}}},drawn_game:{exit:{type:"notify_end",params:{}},type:"final"}},types:{events:{},context:{}}},{actions:{updateNextWind:({context:t,event:e})=>{const s=t.currentWind;t.currentWind=bt(s)},notify_distribution:({context:t,event:e})=>{const s=t.genEventID(),i=t.controller.initialHands();for(const r of Object.values(E)){const o=H("_____________");o[r]=i[r].toString();const a={id:s,type:"DISTRIBUTE",hands:o,wind:r,doraIndicator:t.controller.wall.doraIndicators[0].toString(),sticks:t.controller.placeManager.sticks,round:t.controller.placeManager.round,players:t.controller.playerIDs,places:t.controller.placeManager.playerMap,scores:t.controller.scoreManager.summary};t.controller.emit(a)}t.controller.next()},notify_choice_after_drawn:({context:t,event:e},s)=>{const i=t.currentWind,r=t.controller.hand(i).drawn,o=t.genEventID(),a={id:o,type:"CHOICE_AFTER_DRAWN",wind:i,drawerInfo:{wind:i,tile:r.toString()},choices:{TSUMO:ie(t.controller.doWin(i,r,{oneShot:t.oneShotMap[i],replacementWin:s==null?void 0:s.replacementWin})),REACH:Vo(t.controller.doReach(i)),AN_KAN:se(t.controller.doAnKan(i)),SHO_KAN:se(t.controller.doShoKan(i)),DISCARD:t.controller.doDiscard(i).map(c=>c.toString()),DRAWN_GAME_BY_NINE_ORPHANS:t.controller.canDrawnGame(i)}};t.controller.emit(a),t.controller.pollReplies(o,[i])},notify_choice_after_discarded:({context:t,event:e})=>{const s=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:y.HORIZONTAL});for(const o of Object.values(E)){const a={id:s,type:"CHOICE_AFTER_DISCARDED",wind:o,discarterInfo:{wind:i.w,tile:i.t.toString()},choices:{RON:ie(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:se(t.controller.doPon(o,i.w,r)),CHI:se(t.controller.doChi(o,i.w,r)),DAI_KAN:Go(t.controller.doDaiKan(o,i.w,r))}};a.choices.RON&&(t.missingMap[o]=!0),t.controller.emit(a)}t.controller.pollReplies(s,Object.values(E))},notify_choice_after_called:({context:t,event:e},s)=>{const i=t.genEventID(),r=t.currentWind;let o=t.controller.doDiscard(r);const a=t.controller.hand(t.currentWind).called.at(-1);(a instanceof Y||a instanceof X)&&(o=t.controller.doDiscard(r,a));const c={id:i,type:"CHOICE_AFTER_CALLED",wind:r,choices:{DISCARD:o.map(l=>l.toString())}};t.controller.emit(c),t.controller.pollReplies(i,[r])},notify_choice_for_reach_acceptance:({context:t,event:e})=>{const s=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:y.HORIZONTAL});for(const o of Object.values(E)){const a={id:s,type:"CHOICE_FOR_REACH_ACCEPTANCE",wind:o,reacherInfo:{wind:i.w,tile:r.toString()},choices:{RON:ie(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]}))}};t.controller.emit(a)}t.controller.pollReplies(s,Object.values(E))},notify_choice_for_chankan:({context:t,event:e})=>{I(e.type=="SHO_KAN"||e.type=="AN_KAN",`unexpected event ${e.type}`);const s=t.genEventID(),i=e.block.tiles[0].clone({remove:y.HORIZONTAL});for(const r of Object.values(E)){const o=t.controller.doWin(r,e.block.tiles[0].clone({remove:y.HORIZONTAL}),{discardedBy:e.iam,quadWin:!0,oneShot:t.oneShotMap[r],missingRon:t.missingMap[e.iam]}),a={id:s,type:"CHOICE_FOR_CHAN_KAN",wind:r,callerInfo:{wind:e.iam,tile:i.toString()},choices:{RON:e.type=="SHO_KAN"?ie(o):!1}};a.choices.RON&&(t.missingMap[r]=!0),t.controller.emit(a)}t.controller.pollReplies(s,Object.values(E))},notify_call:({context:t,event:e})=>{I(e.type=="CHI"||e.type=="PON"||e.type=="DAI_KAN"||e.type=="AN_KAN"||e.type=="SHO_KAN",`unexpected event ${e.type}`);const s=t.genEventID(),i=e.iam;t.currentWind=i;for(const r of Object.values(E)){const o={id:s,type:e.type,iam:i,wind:r,block:e.block.serialize()};t.controller.emit(o)}t.controller.next()},notify_discard:({context:t,event:e})=>{I(e.type=="DISCARD",`unexpected event ${e.type}`);const s=t.genEventID(),i=t.currentWind,r=e.tile;for(const o of Object.values(E)){const a={id:s,type:"DISCARD",iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}t.controller.next()},notify_draw:({context:t,event:e},s)=>{const i=t.genEventID(),r=s==null?void 0:s.action;let o;r=="kan"?o=t.controller.wall.kan():o=t.controller.wall.draw();const a=t.currentWind;t.controller.hand(a).reached||(t.missingMap[a]=!1);for(const c of Object.values(E)){let l=new w(g.BACK,0,[y.TSUMO]);c==a&&(l=o);const h={id:i,type:"DRAW",subType:r,iam:a,wind:c,tile:l.toString()};t.controller.emit(h)}t.controller.next()},notify_ron:({context:t,event:e})=>{I(e.type=="RON");const s=t.genEventID(),i=e.iam;for(const r of Object.values(E)){const o={id:s,type:e.type,iam:i,wind:r,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:ue(e.ret)};t.controller.emit(o)}},notify_tsumo:({context:t,event:e})=>{I(e.type=="TSUMO",`unexpected event ${e.type}`);const s=t.genEventID(),i=t.currentWind;for(const r of Object.values(E)){const o={id:s,type:e.type,iam:i,wind:r,lastTile:t.controller.hand(i).drawn.toString(),ret:ue(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{I(e.type=="REACH",`unexpected event ${e.type}`);const s=t.genEventID(),i=e.iam,r=e.tile.clone({add:y.HORIZONTAL});t.oneShotMap[i]=!0;for(const o of Object.values(E)){const a={id:s,type:e.type,iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}},notify_reach_accepted:({context:t,event:e})=>{I(e.type=="REACH_ACCEPT");const s=t.genEventID();for(const i of Object.values(E)){const r={id:s,type:"REACH_ACCEPTED",reacherInfo:{wind:e.reacherInfo.wind,tile:e.reacherInfo.tile.toString()},wind:i};t.controller.emit(r)}t.controller.next()},notify_new_dora_if_needed:({context:t,event:e})=>{const s=t.genEventID();if(e.type=="AN_KAN"){const i=t.controller.wall.openDoraIndicator();for(const r of Object.values(E)){const o={id:s,type:"NEW_DORA",wind:r,doraIndicator:i.toString()};t.controller.emit(o)}}e.type=="SHO_KAN"},disable_one_shot:({context:t,event:e})=>{for(const s of Object.values(E))t.oneShotMap[s]=!1},disable_one_shot_for_me:({context:t,event:e})=>{t.oneShotMap[t.currentWind]=!1},notify_end:({context:t,event:e})=>{const s=t.genEventID(),i=H("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){i[e.iam]=t.controller.hand(e.iam).toString();for(const r of Object.values(E)){const o={id:s,type:"END_GAME",subType:"NINE_TILES",wind:r,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:H(0),hands:i};t.controller.emit(o)}}else if(e.type=="RON"||e.type=="TSUMO"){const r=e.iam==E.E,o=t.controller.finalResult(e.ret,e.iam);for(const a of Object.values(E)){i[e.iam]=t.controller.hand(e.iam).toString();const c={id:s,type:"END_GAME",subType:"WIN_GAME",wind:a,shouldContinue:r,sticks:{reach:0,dead:0},scores:t.controller.scoreManager.summary,deltas:o.deltas,hands:i};t.controller.emit(c)}}else if(!t.controller.wall.canKan||t.controller.river.cannotContinue()){const r=t.controller.wall.canKan?"FOUR_WIND":"FOUR_KAN";for(const o of Object.values(E)){const a={id:s,type:"END_GAME",subType:r,wind:o,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:H(0),hands:H("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const r=[];for(const l of Object.values(E)){const h=t.controller.hand(l);new qt(h).calc()==0&&(r.push(l),i[l]=h.toString())}const o=r.length==0||r.length==4,a=H(0);for(const l of Object.values(E))r.includes(l)?a[l]+=o?0:3e3/r.length:a[l]-=o?0:3e3/(4-r.length);const c=r.length==4||a[E.E]>0;for(const l of Object.values(E)){const h={id:s,type:"END_GAME",subType:"DRAWN_GAME",wind:l,shouldContinue:c,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:a,hands:i};t.controller.emit(h)}}}}},actors:{},guards:{canChi:({context:t,event:e},s)=>e.type=="CHI"?!!t.controller.doChi(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canChi receive ${e.type}`),!1),canPon:({context:t,event:e},s)=>e.type=="PON"?!!t.controller.doPon(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canPon receive ${e.type}`),!1),canWin:({context:t,event:e},s)=>e.type=="TSUMO"||e.type=="RON"?!0:(console.error(`guards.canWin receive ${e.type}`),!1),canReach:({context:t,event:e},s)=>e.type=="REACH"?!!t.controller.doReach(e.iam):(console.error(`guards.canReach receive ${e.type}`),!1),cannotContinue:({context:t,event:e},s)=>!t.controller.wall.canDraw||!t.controller.wall.canKan||t.controller.river.cannotContinue()},delays:{}});function Cs(n=0){let t=n;return()=>(t++).toString()}class Et{constructor(t){_(this,"walls",{replacement:[],dead:[],doraIndicators:[],hiddenDoraIndicators:[],drawable:[]});_(this,"backup");_(this,"openedDoraCount",1);this.init(t),this.backup=Et.clone(this.walls)}kan(){if(this.walls.replacement.length==0)throw new Error("exceeded maximum kan");const t=this.walls.replacement.pop();return this.walls.drawable.pop(),w.from(t)}draw(){if(!this.walls.drawable)throw new Error("cannot draw any more");return w.from(this.walls.drawable.pop())}openDoraIndicator(){if(this.openedDoraCount>=4)throw new Error("exceeded maximum open dora");return this.openedDoraCount++,w.from(this.walls.doraIndicators[this.openedDoraCount-1])}get doraIndicators(){return this.walls.doraIndicators.slice(0,this.openedDoraCount).map(w.from)}get hiddenDoraIndicators(){return this.walls.hiddenDoraIndicators.slice(0,this.openedDoraCount).map(w.from)}get canKan(){return this.walls.replacement.length>0}get canDraw(){return this.walls.drawable.length>0}initialHands(){const t=H("");for(let e=0;e<3;e++)for(const s of Object.values(E))for(let i=0;i<4;i++)t[s]+=this.draw().toString();for(const e of Object.values(E))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=Et.clone(t);return}else{for(let e of Object.values(g)){if(e==g.BACK)continue;const s=e==g.Z?[1,2,3,4,5,6,7]:[1,2,3,4,5,6,7,8,9];for(let i=0;i<4;i++)for(let r of s){let o=new w(e,r);e!=g.Z&&i==3&&r==5&&(o=o.clone({add:y.RED})),this.walls.drawable.push(o.toString())}}on(this.walls.drawable)}for(let e=0;e<14;e++)this.walls.dead.push(this.walls.drawable.pop());for(let e=0;e<4;e++)this.walls.hiddenDoraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.doraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.replacement.push(this.walls.dead.pop())}export(){return this.backup}static clone(t){return{drawable:t.drawable.concat(),dead:t.dead.concat(),doraIndicators:t.doraIndicators.concat(),hiddenDoraIndicators:t.hiddenDoraIndicators.concat(),replacement:t.replacement.concat()}}}class te{constructor(t,e){_(this,"wall",new Et);_(this,"playerIDs");_(this,"actor",Ht(Ze(this),{}));_(this,"observer");_(this,"handlers",{});_(this,"mailBox",{});_(this,"histories",[]);_(this,"debugMode");this.debugMode=(e==null?void 0:e.debug)??!1,this.handlers=t.reduce((o,a)=>(o[a.id]=a.handler,o),{}),this.playerIDs=t.map(o=>o.id),t.forEach(o=>o.handler.on(a=>this.enqueue(a)));const s=ls();this.observer=new Rs(s),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const i=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new Vt(i);const r=(e==null?void 0:e.shuffle)==!1?this.playerIDs:on([...this.playerIDs]);this.observer.placeManager=new Jt({[r[0]]:E.E,[r[1]]:E.S,[r[2]]:E.W,[r[3]]:E.N})}boardParams(t){let s=this.hand(t).reached?1:void 0;if(s){const i=this.river.discards(t);s=i.length==0||i.length==1&&i[0].t.has(y.HORIZONTAL)?2:1}return{doraIndicators:this.observer.doraIndicators,round:this.placeManager.round,myWind:t,sticks:this.observer.placeManager.sticks,reached:s}}hand(t){return this.observer.hand(t)}get placeManager(){return this.observer.placeManager}get scoreManager(){return this.observer.scoreManager}get river(){return this.observer.river}next(t){(!this.debugMode||t)&&this.actor.send({type:"NEXT"})}emit(t){const e=this.observer.placeManager.playerID(t.wind);this.handlers[e].emit(t);const s=t.iam;t.wind==s?this.observer.eventHandler.emit(t):s==null&&(!this.observer.applied[t.id]||t.type=="DISTRIBUTE")&&(this.observer.eventHandler.emit(t),this.observer.applied[t.id]=!0)}enqueue(t){this.mailBox[t.id]==null&&(this.mailBox[t.id]=[]),this.mailBox[t.id].push(t)}pollReplies(t,e){const s=this.mailBox[t];if(s==null)throw new Error(`not enqueued ${t} at ${this.actor.getSnapshot().value}`);if(s.length!=e.length)throw new Error(`${t}: num of event: got: ${e.length}, want: ${s.length}`);if(e.length==0){console.warn("no events to handle");return}const i=s[0];if(i.type=="CHOICE_AFTER_DISCARDED"){const r=rs(s);if(r.events.length==0){this.actor.send({type:""});return}const o=r.events[0];switch(r.type){case"RON":I(o.choices.RON,"ron choice is none"),this.actor.send({type:r.type,iam:o.wind,ret:jt(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:w.from(o.discarterInfo.tile)}});break;case"DAI_KAN":I(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:r.type,iam:o.wind,block:et.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[r.type];I(a,`${r.type} choice is none`),I(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const c=X.deserialize(a[0]);this.actor.send({type:r.type,iam:o.wind,block:c})}}else if(i.type=="CHOICE_AFTER_DRAWN"){const r=os(s);I(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const o=r.events[0],a=o.wind;switch(r.type){case"TSUMO":I(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:r.type,ret:jt(o.choices.TSUMO),lastTile:w.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[r.type];I(c,`${r.type} candidates is none`),this.actor.send({type:"REACH",tile:w.from(c[0].tile),iam:a});break;case"DISCARD":const l=o.choices[r.type];I(l,`${r.type} choice is none`),this.actor.send({type:r.type,tile:w.from(l[0]).clone({remove:y.TSUMO}),iam:a});break;case"AN_KAN":{const h=o.choices[r.type];I(h,`${r.type} choice is none`),this.actor.send({type:r.type,block:M.from(h[0].tiles),iam:a});break}case"SHO_KAN":{const h=o.choices[r.type];I(h,`${r.type} choice is none`),this.actor.send({type:r.type,block:L.from(h[0].tiles),iam:a});break}case"DRAWN_GAME_BY_NINE_ORPHANS":this.actor.send({type:"DRAWN_GAME_BY_NINE_ORPHANS",iam:a});break}}else if(i.type=="CHOICE_AFTER_CALLED"){I(i.choices.DISCARD,`discard candidate tile is none: ${JSON.stringify(i,null,2)} ${this.hand(i.wind).toString()}`);const r=i.wind,o=w.from(i.choices.DISCARD[0]);this.actor.send({type:"DISCARD",tile:o,iam:r})}else if(i.type=="CHOICE_FOR_REACH_ACCEPTANCE"){const r=s.filter(a=>(I(a.type=="CHOICE_FOR_REACH_ACCEPTANCE"),a.choices.RON!==!1));if(r.length==0){this.actor.send({type:"REACH_ACCEPT",reacherInfo:{tile:w.from(i.reacherInfo.tile),wind:i.reacherInfo.wind}});return}const o=r[0];this.actor.send({type:"RON",iam:o.wind,ret:jt(o.choices.RON),targetInfo:{wind:o.reacherInfo.wind,tile:w.from(o.reacherInfo.tile)}});return}else if(i.type=="CHOICE_FOR_CHAN_KAN"){const r=s.filter(a=>a.choices.RON!==!1);if(r.length==0){this.actor.send({type:""});return}const o=r[0];I(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:jt(o.choices.RON),quadWin:!0,targetInfo:{wind:o.callerInfo.wind,tile:w.from(o.callerInfo.tile)}});return}else console.warn(`controller found unexpected event: ${i.type}`)}export(){return this.histories.concat()}static load(t){const e=t.choiceEvents,s=Object.keys(t.players),i={emit:a=>{},on:a=>{}},r=s.map(a=>({id:a,handler:i})),o=new te(r);return o.playerIDs=s,o.mailBox=e,o.observer.placeManager=new Jt(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new Vt(t.scores),o.wall=new Et(t.wall),o}start(){this.actor.subscribe(s=>{console.debug("State:",s.value)});const t={scores:this.scoreManager.summary,round:this.placeManager.round,players:this.placeManager.playerMap,wall:this.wall.export(),choiceEvents:this.mailBox,sticks:this.placeManager.sticks};this.actor.start(),this.histories.push(t);const e=this.actor.getSnapshot().status;if(e!="done")throw new Error(`unexpected state ${this.actor.getSnapshot().value}(${e})`)}startGame(){for(;console.debug(`start========${this.placeManager.round}=============`),this.start(),this.wall=new Et,this.observer.applied={},this.mailBox={},this.actor=Ht(Ze(this)),!this.placeManager.is(C.W1););}finalResult(t,e){const s=this.hand(e),i=s.reached?this.wall.hiddenDoraIndicators:void 0,r=new Be(s,{...t.boardContext,sticks:this.placeManager.sticks,hiddenDoraIndicators:i}).calc(t.hand);return I(r),r}doWin(t,e,s){if(e==null)return!1;let i=this.hand(t);const r=this.boardParams(t);if(i.drawn==null){if(s==null)throw new Error("should ron but params == null");if(s.discardedBy==t||s.missingRon)return!1;i=i.clone(),r.ronWind=s.discardedBy,r.finalDiscardWin=!this.wall.canDraw,r.quadWin=s.quadWin,i.inc([e])}else r.finalWallWin=!this.wall.canDraw,r.replacementWin=s==null?void 0:s.replacementWin;r.oneShotWin=s==null?void 0:s.oneShot;const o=new is(i),a=new Be(i,r),c=o.calc(e),l=a.calc(...c);if(!l||l.yakus.length==0)return!1;if(i.draw==null){const h=Pt.candidateTiles(this.hand(t)).candidates;if(this.river.discards(t).some(u=>h.some(d=>d.equals(u.t))))return!1}return l}doPon(t,e,s){if(s==null||t==e)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3||i.get(s.t,s.n)<2)return!1;const r=s.clone({removeAll:!0}),o=Re(t,e,b.PON),a=[],c=new X([r,r,r]).clone({replace:{idx:o,tile:s.clone({add:y.HORIZONTAL})}});let l=c;x(s)&&s.has(y.RED)&&(l=c.clone({replace:{idx:o,tile:r.clone({add:[y.RED,y.HORIZONTAL]})}}));const h=o%2+1;if(x(s)&&i.get(s.t,0)>0&&(l=c.clone({replace:{idx:h,tile:r.clone({add:y.RED})}})),a.push(l),x(r)&&i.get(r.t,5)==3){const u=c.clone({replace:{idx:h,tile:r}});a.push(u)}return a}doChi(t,e,s){if(s==null||!s.isNum()||bt(e)!=t)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3)return!1;const r=s.clone({remove:y.TSUMO,add:[y.HORIZONTAL]}),o=[];r.n-2>=1&&i.get(s.t,r.n-2)>0&&i.get(s.t,r.n-1)>0&&o.push(new Y([r,new w(s.t,r.n-1),new w(s.t,r.n-2)])),r.n+2<=9&&i.get(s.t,r.n+1)>0&&i.get(s.t,r.n+2)>0&&o.push(new Y([r,new w(s.t,r.n+1),new w(s.t,r.n+2)])),r.n-1>=1&&r.n+1<=9&&i.get(s.t,r.n-1)>0&&i.get(s.t,r.n+1)>0&&o.push(new Y([r,new w(s.t,r.n-1),new w(s.t,r.n+1)]));for(let d=0;d<o.length;d++){const p=o[d],f=this.cannotDiscardTile(p),m=[];for(const R of f){const N=i.get(R.t,R.n);for(let T=0;T<N;T++)m.push(R.clone({remove:y.RED}))}const A=i.dec([...m,p.tiles[1],p.tiles[2]]),S=i.hands.length==0;i.inc(A),S&&o.splice(d,1)}if(o.length==0)return!1;const u=i.get(s.t,0)>0?this.redPattern(o):[];return u.length>0&&i.get(s.t,5)==1?u:[...o,...u]}redPattern(t){return t.length==0?[]:t.filter(s=>x(s.tiles[1])||x(s.tiles[2])).map(s=>{if(x(s.tiles[1])){const i=s.tiles[1].clone({add:y.RED});return s.clone({replace:{idx:1,tile:i}})}else if(x(s.tiles[2])){const i=s.tiles[2].clone({add:y.RED});return s.clone({replace:{idx:2,tile:i}})}}).filter(s=>s!=null)}doReach(t){const e=this.hand(t);return e.reached||!e.menzen||new qt(e).calc()>0?!1:Pt.calcCandidates(e,e.hands)}doDiscard(t,e){if(this.hand(t).reached)return[this.hand(t).drawn];const s=this.hand(t).hands;if(e==null)return s;if(e instanceof X)return s.filter(o=>!o.equals(e.tiles[0]));const i=this.cannotDiscardTile(e),r=s.filter(o=>!i.some(a=>o.equals(a)));return I(r.length>0,`no tiles to discard. hand: ${this.hand(t)}, suji: ${i}, block-chi: ${e}`),r}cannotDiscardTile(t){const e=t.tiles[0],s=t.tiles[1].n;return s!=1&&e.n-2==s?[new w(e.t,e.n-3),e]:s!=8&&e.n+1==s?[new w(e.t,e.n+3),e]:[e]}doAnKan(t){const e=this.hand(t),s=[];if(e.reached)return!1;for(const[i,r]of U())if(e.get(i,r)==4){const o=new w(i,r),a=[o,o,o,o];x(o)&&(a[1]=o.clone({add:y.RED})),s.push(new M(a))}if(s.length==0)return!1;for(const i of s)I(i.tiles.filter(r=>r.has(y.HORIZONTAL)).length==0,`h op ${i.toString()}`);return s}doShoKan(t){const e=this.hand(t);if(e.reached)return!1;const s=e.called.filter(r=>r instanceof X);if(s.length==0)return!1;const i=[];for(const r of s){const o=r.tiles[0].clone({removeAll:!0,add:y.HORIZONTAL});if(e.get(o.t,o.n)==1){const a=x(o)&&e.get(o.t,0)>0?o.clone({add:y.RED}):o;i.push(new L([...r.tiles,a]))}}if(i.length==0)return!1;for(const r of i)I(r.tiles.filter(o=>o.has(y.HORIZONTAL)).length==2,`h op ${r.toString()}`);return i}doDaiKan(t,e,s){const i=this.hand(t);if(i.reached||t==e)return!1;const r=s.clone({removeAll:!0});if(i.get(r.t,r.n)!=3)return!1;const o=Re(t,e,b.DAI_KAN);let a=new et([r,r,r,r]).clone({replace:{idx:o,tile:r.clone({add:y.HORIZONTAL})}});if(x(s)&&s.has(y.RED))a=a.clone({replace:{idx:o,tile:r.clone({add:[y.HORIZONTAL,y.RED]})}});else if(x(s)&&!s.has(y.RED)){I(i.get(s.t,0)>0,`hand does not have red tile: ${i.toString()}`);const c=o%3+1;a=a.clone({replace:{idx:c,tile:r.clone({add:y.RED})}})}return I(a.tiles.filter(c=>c.has(y.HORIZONTAL)).length==1,`h op ${a.toString()}`),a}canDrawnGame(t){if(this.river.discards(t).length!=0)return!1;const e=this.hand(t);let s=0;for(const i of Object.values(g)){if(i==g.BACK)continue;const r=i==g.Z?$t:J;for(const o of r)e.get(i,o)>0&&s++}return s>=9}initialHands(){return this.wall.initialHands()}}class St extends _e{isBackHand(){for(const t of Object.values(g))if(t!=g.BACK&&this.sum(t)>0)return!1;return this.sum(g.BACK)>0}clone(){const t=new St(this.toString());return t.data.reached=this.data.reached,t}dec(t){return this.isBackHand()?(super.dec(t.map(()=>new w(g.BACK,0))),[...t]):super.dec(t)}}class mn{constructor(t,e){_(this,"id");_(this,"river",new an);_(this,"placeManager",new Jt({}));_(this,"scoreManager",new Vt({}));_(this,"hands",H(new St("")));_(this,"counter",new hs);_(this,"doraIndicators",[]);_(this,"eventHandler");this.id=t,this.eventHandler=e}hand(t){return this.hands[t]}handleEvent(t){switch(t.type){case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DISCARDED":case"CHOICE_AFTER_DRAWN":case"CHOICE_FOR_CHAN_KAN":case"CHOICE_FOR_REACH_ACCEPTANCE":break;case"DISTRIBUTE":this.counter.reset();const e=w.from(t.doraIndicator);this.setHands(t),this.placeManager=new Jt(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new Vt(structuredClone(t.scores)),this.doraIndicators=[e],this.counter.dec(e);for(const i of Object.values(E))i==t.wind&&this.counter.dec(...this.hand(i).hands);break;case"DRAW":{const i=w.from(t.tile);this.hands[t.iam].draw(i),this.counter.dec(i);break}case"DISCARD":{const i=w.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(E))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"PON":case"CHI":case"DAI_KAN":{const i=O.deserialize(t.block);this.hands[t.iam].call(i),this.river.markCalled(),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(y.HORIZONTAL)));break}case"SHO_KAN":{const i=L.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(i.tiles.filter(r=>r.has(y.HORIZONTAL))[0]);break}case"AN_KAN":{const i=M.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(y.HORIZONTAL)));break}case"REACH":{this.hands[t.iam].reach();const i=w.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(E))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"REACH_ACCEPTED":const s=this.placeManager.playerID(t.reacherInfo.wind);this.scoreManager.reach(s),this.placeManager.incrementReachStick();break;case"NEW_DORA":{const i=w.from(t.doraIndicator);this.doraIndicators.push(i),this.counter.dec(i);break}case"TSUMO":break;case"RON":break;case"END_GAME":switch(t.subType){case"NINE_TILES":case"FOUR_KAN":case"FOUR_WIND":this.placeManager.incrementDeadStick();break;case"DRAWN_GAME":{const i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),this.placeManager.incrementDeadStick(),t.shouldContinue||this.placeManager.nextRound();break}case"WIN_GAME":{const i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),t.shouldContinue?this.placeManager.incrementDeadStick():(this.placeManager.nextRound(),this.placeManager.resetDeadStick()),this.placeManager.resetReachStick();break}}break;default:throw new Error(`unexpected event ${JSON.stringify(t,null,2)}`)}}}class Rs extends mn{constructor(e){super("observer",e);_(this,"applied",{});this.counter.disable=!0,this.hands=H(new St("_____________"))}setHands(e){this.hands[e.wind]=new St(e.hands[e.wind])}handleEvent(e){switch(super.handleEvent(e),e.type){case"DISTRIBUTE":let s=!0;for(const i of Object.values(E))s&&(s=this.hand(i).get(g.BACK,0)==0);if(!s)break;console.debug("DISTRIBUTE:",`round: ${this.placeManager.round}`,`scores: ${JSON.stringify(this.scoreManager.summary,null,2)}`,`map: ${JSON.stringify(this.placeManager.playerMap,null,2)}`,`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`);for(const i of Object.values(E))console.debug(`${this.placeManager.playerID(i)}(${i})`,`init hand: ${this.hand(i).toString()}`);break;case"DRAW":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`draw: ${this.hand(e.iam).drawn}`,`hand: ${this.hand(e.iam).toString()}`);break;case"DISCARD":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`discard: ${e.tile.toString()}`,`hand: ${this.hand(e.iam).toString()}`);break;case"CHI":case"PON":case"DAI_KAN":case"AN_KAN":case"SHO_KAN":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`call: ${e.block.tiles}`,`hand: ${this.hand(e.iam).toString()}`);break;case"REACH":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`reach: ${e.tile}`,`hand: ${this.hand(e.iam).toString()}`);break;case"TSUMO":case"RON":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`ron/tsumo: ${JSON.stringify(e.ret,null,2)}`,`hand: ${this.hand(e.iam).toString()}`);break;case"END_GAME":for(const i of Object.values(E))console.debug(`${this.placeManager.playerID(i)}(${me(i)})`,`end hand: ${this.hand(i).toString()}`);console.debug("END_GAME",e.subType,"scores",JSON.stringify(this.scoreManager.summary,null,2),`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`)}}}class Zt extends mn{constructor(e,s){super(e,s);_(this,"river",new an);_(this,"doras",[]);this.eventHandler.on(i=>this.handleEvent(i))}get myWind(){return this.placeManager.wind(this.id)}setHands(e){for(const s of Object.values(E))this.hands[s]=new St(e.hands[s])}handleDiscard(e){const s=Object.values(E).filter(h=>h==this.myWind?!1:this.hand(h).reached),i=new qt(this.hand(this.myWind)).calc();if(s.length>0&&i>=2)return kt.selectTile(this.counter,s,e);const r=Pt.calcCandidates(this.hand(this.myWind),e),a=Yt.calcPlayerCandidates(this.counter,r).sort((h,u)=>u.sum-h.sum),c=a.filter(h=>h.sum==a[0].sum);return Yt.selectMinPriority(this.counter,c,this.doras).tile}handleEvent(e){switch(e.type){case"CHOICE_AFTER_DISCARDED":e.choices.CHI=!1,e.choices.DAI_KAN=!1,e.choices.PON=!1,this.eventHandler.emit(e);break;case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DRAWN":if(e.choices.DISCARD){const s=this.handleDiscard(e.choices.DISCARD.map(w.from));e.choices.DISCARD=[s.toString()]}this.eventHandler.emit(e);break;case"CHOICE_FOR_REACH_ACCEPTANCE":this.eventHandler.emit(e);break;case"CHOICE_FOR_CHAN_KAN":this.eventHandler.emit(e);break;default:super.handleEvent(e)}}}class Jo{constructor(t){_(this,"index",0);_(this,"histories",[]);this.histories=JSON.parse(t)}next(){I(this.index<this.histories.length),this.index++}prev(){this.index--,I(this.index<0)}start(){te.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const Yo=n=>{const[t,e]=Ft(),[s,i]=Ft(),[r,o]=Ft(),[a,c]=Ft(),l=["player-1","player-2","player-3","player-4"],h=n==null?void 0:n.playerInjection,u=(h==null?void 0:h.p1)??Zt,d=(h==null?void 0:h.p2)??Zt,p=(h==null?void 0:h.p3)??Zt,f=(h==null?void 0:h.p4)??Zt,m=new u(l[0],e),A=new d(l[1],i),S=new p(l[2],o),R=new f(l[3],c),N=[{handler:t,id:l[0]},{handler:s,id:l[1]},{handler:r,id:l[2]},{handler:a,id:l[3]}];return{c:new te(N,{debug:n==null?void 0:n.debug,shuffle:n==null?void 0:n.shuffle}),p1:m,p2:A,p3:S,p4:R}},ft=(n,t)=>{let s=1;for(let i of t)i.equals(n)&&(s*=2);return s};class Yt{static calcPlayerCandidates(t,e){let s=[];for(let i of e){let r=0,o=[];for(let a of i.candidates)o.push({tile:a.clone(),n:t.get(a)}),r+=t.get(a);s.push({sum:r,tile:i.tile,candidates:o,shanten:i.shanten})}return s}static selectMinPriority(t,e,s){I(e.length>0);let i=0,r=0;for(let o=0;o<e.length;o++){const a=Yt.calcPriority(t,e[o],s);a<i&&(i=a,r=o)}return e[r]}static calcPriority(t,e,s){const i=e.tile;let r=0;if(i.t==g.Z)return r=t.get(i),(i.n==5||i.n==6||i.n==7)&&(r*=2),r*ft(i,s);{const o=t.get(i);r+=o*ft(i,s);const a=t.get(new w(i.t,i.n+1)),c=t.get(new w(i.t,i.n+2)),l=t.get(new w(i.t,i.n-1)),h=t.get(new w(i.t,i.n-2)),u=i.n-2>0?Math.min(l,h):0,d=i.n+2<=9?Math.min(a,c):0,p=i.n-1>=1&&i.n+1<=9?Math.min(a,l):0,f=Math.max(u,p),m=Math.max(p,d);return r+=o*ft(i,s),r+=u*ft(new w(i.t,i.n-2),s),r+=d*ft(new w(i.t,i.n+2),s),r+=f*ft(new w(i.t,i.n-1),s),r+=m*ft(new w(i.t,i.n+1),s),i.n==0,r}}}class kt{static selectTile(t,e,s){I(e.length>0&&s.length>0);let i=s[0],r=Number.POSITIVE_INFINITY;for(let o of s){const a=kt.rank(t,e,o);a<r&&(i=o,r=a)}return i}static rank(t,e,s){let i=0;const r=s.isNum()?kt.rankN:kt.rankZ;for(let o of e){const a=r(t,o,s);i<a&&(i=a)}return i}static rankZ(t,e,s){if(s.t!=g.Z)throw new Error(`expected TYPE.Z but ${s.toString()}`);if(t.isSafeTile(s.t,s.n,e))return 0;const i=t.get(s);return Math.min(i,3)}static rankN(t,e,s){if(!s.isNum())throw new Error(`expected TYPE.NUMBER but ${s.toString()}`);const i=s.n,r=s.t;if(t.isSafeTile(r,i,e))return 0;if(i==1)return t.isSafeTile(r,4,e)?3:6;if(i==9)return t.isSafeTile(r,6,e)?3:6;if(i==2||i==8)return t.isSafeTile(r,5,e)?4:8;if(i==3)return t.isSafeTile(r,6,e)?5:8;if(i==7)return t.isSafeTile(r,4,e)?5:8;const o=t.isSafeTile(r,i-3,e),a=t.isSafeTile(r,i+3,e);return o&&a?4:o||a?8:12}}exports.ActorHand=St;exports.BLOCK=b;exports.BaseActor=mn;exports.Block=O;exports.BlockAnKan=M;exports.BlockCalculator=is;exports.BlockChi=Y;exports.BlockDaiKan=et;exports.BlockHand=Ct;exports.BlockIsolated=Ye;exports.BlockOther=Xe;exports.BlockPair=D;exports.BlockPon=X;exports.BlockRun=st;exports.BlockShoKan=L;exports.BlockThree=F;exports.Controller=te;exports.Counter=hs;exports.Efficiency=Pt;exports.FONT_FAMILY=Ge;exports.G=v;exports.Hand=_e;exports.INPUT_SEPARATOR=nt;exports.Image=en;exports.ImageHelper=rn;exports.Mark=ht;exports.MeasureText=Ds;exports.MyG=ir;exports.MyImage=rr;exports.MyRect=ar;exports.MySVG=sr;exports.MyText=cr;exports.MyUse=or;exports.N19=J;exports.NZ=$t;exports.OP=y;exports.Observer=Rs;exports.Parser=K;exports.PlaceManager=Jt;exports.Player=Zt;exports.PlayerEfficiency=Yt;exports.PointCalculator=Be;exports.ROUND=C;exports.ROUND_MAP=Ve;exports.Rect=nn;exports.Replayer=Jo;exports.RiskRank=kt;exports.River=an;exports.STICK_CONTEXT=Ce;exports.SVG=Jn;exports.ScoreManager=Vt;exports.ShantenCalculator=qt;exports.Svg=Vn;exports.Symbol=sn;exports.TABLE_CONTEXT=Dn;exports.TILE_CONTEXT=ot;exports.TYPE=g;exports.Text=_t;exports.Tile=w;exports.Use=be;exports.WIND=E;exports.WIND_MAP=ye;exports.Wall=Et;exports.callBlockIndex=Re;exports.convertInput=ss;exports.createControllerMachine=Ze;exports.createEventEmitter=ls;exports.createEventPipe=Ft;exports.createHand=Tt;exports.createLocalGame=Yo;exports.createTable=qn;exports.createWindMap=H;exports.deserializeWinResult=jt;exports.drawBlocks=gr;exports.drawTable=Nr;exports.forHand=U;exports.incrementalIDGenerator=Cs;exports.isNum5=x;exports.nextRound=Gt;exports.nextWind=bt;exports.optimizeSVG=mr;exports.parse=es;exports.parseTableInput=ns;exports.prevRound=Zs;exports.prevWind=me;exports.prioritizeDiscardedEvents=rs;exports.prioritizeDrawnEvents=os;exports.serializeWinResult=ue;exports.shuffle=on;exports.sortCalledTiles=Kn;exports.tileSortFunc=Xt;
|
|
14
|
+
通知する choice がない場合、controller が\\*で遷移させる`,on:{RON:{target:"roned",guard:"canWin"},PON:{target:"poned",guard:"canPon"},CHI:{target:"chied",guard:"canChi"},DAI_KAN:{target:"dai_kaned"},"*":{target:"wildcard_after_discarded"}}},reached:{on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"}}},entry:{type:"notify_reach_accepted"}},roned:{exit:[{type:"notify_ron"},{type:"notify_end"}],type:"final"},poned:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called"}}},entry:[{type:"notify_call"},{type:"disable_none_shot"}]},chied:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called",params:{action:"chi"}}}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},wildcard_after_discarded:{exit:[],always:[{target:"drawn_game",guard:"cannotContinue"},{target:"drawn",actions:[{type:"updateNextWind"}]}]},waiting_discard_event:{description:"鳴いたユーザからの DISCARD イベントを待つ",on:{DISCARD:{target:"discarded"}}},dai_kaned:{on:{NEXT:{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},an_sho_kaned:{always:{target:"waiting_chankan_event"},entry:[{type:"notify_call"},{type:"disable_one_shot"},{type:"notify_new_dora_if_needed"},{type:"notify_choice_for_chankan"}]},waiting_chankan_event:{description:"チャンカンを待つ",on:{"*":{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]},RON:{target:"roned",guard:{type:"canWin"}}}},drawn_game:{exit:{type:"notify_end",params:{}},type:"final"}},types:{events:{},context:{}}},{actions:{updateNextWind:({context:t,event:e})=>{const n=t.currentWind;t.currentWind=yt(n)},notify_distribution:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.initialHands();for(const r of Object.values(_)){const o=P("_____________");o[r]=i[r].toString();const a={id:n,type:"DISTRIBUTE",hands:o,wind:r,doraIndicator:t.controller.wall.doraIndicators[0].toString(),sticks:t.controller.placeManager.sticks,round:t.controller.placeManager.round,players:t.controller.playerIDs,places:t.controller.placeManager.playerMap,scores:t.controller.scoreManager.summary};t.controller.emit(a)}t.controller.next()},notify_choice_after_drawn:({context:t,event:e},n)=>{const i=t.currentWind,r=t.controller.hand(i).drawn,o=t.genEventID(),a={id:o,type:"CHOICE_AFTER_DRAWN",wind:i,drawerInfo:{wind:i,tile:r.toString()},choices:{TSUMO:se(t.controller.doWin(i,r,{oneShot:t.oneShotMap[i],replacementWin:n?.replacementWin})),REACH:Bo(t.controller.doReach(i)),AN_KAN:ne(t.controller.doAnKan(i)),SHO_KAN:ne(t.controller.doShoKan(i)),DISCARD:t.controller.doDiscard(i).map(c=>c.toString()),DRAWN_GAME_BY_NINE_ORPHANS:t.controller.canDrawnGame(i)}};t.controller.emit(a),t.controller.pollReplies(o,[i])},notify_choice_after_discarded:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:m.HORIZONTAL});for(const o of Object.values(_)){const a={id:n,type:"CHOICE_AFTER_DISCARDED",wind:o,discarterInfo:{wind:i.w,tile:i.t.toString()},choices:{RON:se(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:ne(t.controller.doPon(o,i.w,r)),CHI:ne(t.controller.doChi(o,i.w,r)),DAI_KAN:Wo(t.controller.doDaiKan(o,i.w,r))}};a.choices.RON&&(t.missingMap[o]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(_))},notify_choice_after_called:({context:t,event:e},n)=>{const i=t.genEventID(),r=t.currentWind;let o=t.controller.doDiscard(r);const a=t.controller.hand(t.currentWind).called.at(-1);(a instanceof X||a instanceof q)&&(o=t.controller.doDiscard(r,a));const c={id:i,type:"CHOICE_AFTER_CALLED",wind:r,choices:{DISCARD:o.map(l=>l.toString())}};t.controller.emit(c),t.controller.pollReplies(i,[r])},notify_choice_for_reach_acceptance:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:m.HORIZONTAL});for(const o of Object.values(_)){const a={id:n,type:"CHOICE_FOR_REACH_ACCEPTANCE",wind:o,reacherInfo:{wind:i.w,tile:r.toString()},choices:{RON:se(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]}))}};t.controller.emit(a)}t.controller.pollReplies(n,Object.values(_))},notify_choice_for_chankan:({context:t,event:e})=>{I(e.type=="SHO_KAN"||e.type=="AN_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.block.tiles[0].clone({remove:m.HORIZONTAL});for(const r of Object.values(_)){const o=t.controller.doWin(r,e.block.tiles[0].clone({remove:m.HORIZONTAL}),{discardedBy:e.iam,quadWin:!0,oneShot:t.oneShotMap[r],missingRon:t.missingMap[e.iam]}),a={id:n,type:"CHOICE_FOR_CHAN_KAN",wind:r,callerInfo:{wind:e.iam,tile:i.toString()},choices:{RON:e.type=="SHO_KAN"?se(o):!1}};a.choices.RON&&(t.missingMap[r]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(_))},notify_call:({context:t,event:e})=>{I(e.type=="CHI"||e.type=="PON"||e.type=="DAI_KAN"||e.type=="AN_KAN"||e.type=="SHO_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam;t.currentWind=i;for(const r of Object.values(_)){const o={id:n,type:e.type,iam:i,wind:r,block:e.block.serialize()};t.controller.emit(o)}t.controller.next()},notify_discard:({context:t,event:e})=>{I(e.type=="DISCARD",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind,r=e.tile;for(const o of Object.values(_)){const a={id:n,type:"DISCARD",iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}t.controller.next()},notify_draw:({context:t,event:e},n)=>{const i=t.genEventID(),r=n?.action;let o;r=="kan"?o=t.controller.wall.kan():o=t.controller.wall.draw();const a=t.currentWind;t.controller.hand(a).reached||(t.missingMap[a]=!1);for(const c of Object.values(_)){let l=new w(p.BACK,0,[m.TSUMO]);c==a&&(l=o);const d={id:i,type:"DRAW",subType:r,iam:a,wind:c,tile:l.toString()};t.controller.emit(d)}t.controller.next()},notify_ron:({context:t,event:e})=>{I(e.type=="RON");const n=t.genEventID(),i=e.iam;for(const r of Object.values(_)){const o={id:n,type:e.type,iam:i,wind:r,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:le(e.ret)};t.controller.emit(o)}},notify_tsumo:({context:t,event:e})=>{I(e.type=="TSUMO",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind;for(const r of Object.values(_)){const o={id:n,type:e.type,iam:i,wind:r,lastTile:t.controller.hand(i).drawn.toString(),ret:le(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{I(e.type=="REACH",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam,r=e.tile.clone({add:m.HORIZONTAL});t.oneShotMap[i]=!0;for(const o of Object.values(_)){const a={id:n,type:e.type,iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}},notify_reach_accepted:({context:t,event:e})=>{I(e.type=="REACH_ACCEPT");const n=t.genEventID();for(const i of Object.values(_)){const r={id:n,type:"REACH_ACCEPTED",reacherInfo:{wind:e.reacherInfo.wind,tile:e.reacherInfo.tile.toString()},wind:i};t.controller.emit(r)}t.controller.next()},notify_new_dora_if_needed:({context:t,event:e})=>{const n=t.genEventID();if(e.type=="AN_KAN"){const i=t.controller.wall.openDoraIndicator();for(const r of Object.values(_)){const o={id:n,type:"NEW_DORA",wind:r,doraIndicator:i.toString()};t.controller.emit(o)}}e.type=="SHO_KAN"},disable_one_shot:({context:t,event:e})=>{for(const n of Object.values(_))t.oneShotMap[n]=!1},disable_one_shot_for_me:({context:t,event:e})=>{t.oneShotMap[t.currentWind]=!1},notify_end:({context:t,event:e})=>{const n=t.genEventID(),i=P("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){i[e.iam]=t.controller.hand(e.iam).toString();for(const r of Object.values(_)){const o={id:n,type:"END_GAME",subType:"NINE_TILES",wind:r,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:P(0),hands:i};t.controller.emit(o)}}else if(e.type=="RON"||e.type=="TSUMO"){const r=e.iam==_.E,o=t.controller.finalResult(e.ret,e.iam);for(const a of Object.values(_)){i[e.iam]=t.controller.hand(e.iam).toString();const c={id:n,type:"END_GAME",subType:"WIN_GAME",wind:a,shouldContinue:r,sticks:{reach:0,dead:0},scores:t.controller.scoreManager.summary,deltas:o.deltas,hands:i};t.controller.emit(c)}}else if(!t.controller.wall.canKan||t.controller.river.cannotContinue()){const r=t.controller.wall.canKan?"FOUR_WIND":"FOUR_KAN";for(const o of Object.values(_)){const a={id:n,type:"END_GAME",subType:r,wind:o,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:P(0),hands:P("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const r=[];for(const l of Object.values(_)){const d=t.controller.hand(l);new Xt(d).calc()==0&&(r.push(l),i[l]=d.toString())}const o=r.length==0||r.length==4,a=P(0);for(const l of Object.values(_))r.includes(l)?a[l]+=o?0:3e3/r.length:a[l]-=o?0:3e3/(4-r.length);const c=r.length==4||a[_.E]>0;for(const l of Object.values(_)){const d={id:n,type:"END_GAME",subType:"DRAWN_GAME",wind:l,shouldContinue:c,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:a,hands:i};t.controller.emit(d)}}}}},actors:{},guards:{canChi:({context:t,event:e},n)=>e.type=="CHI"?!!t.controller.doChi(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canChi receive ${e.type}`),!1),canPon:({context:t,event:e},n)=>e.type=="PON"?!!t.controller.doPon(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canPon receive ${e.type}`),!1),canWin:({context:t,event:e},n)=>e.type=="TSUMO"||e.type=="RON"?!0:(console.error(`guards.canWin receive ${e.type}`),!1),canReach:({context:t,event:e},n)=>e.type=="REACH"?!!t.controller.doReach(e.iam):(console.error(`guards.canReach receive ${e.type}`),!1),cannotContinue:({context:t,event:e},n)=>!t.controller.wall.canDraw||!t.controller.wall.canKan||t.controller.river.cannotContinue()},delays:{}});function vs(s=0){let t=s;return()=>(t++).toString()}class bt{walls={replacement:[],dead:[],doraIndicators:[],hiddenDoraIndicators:[],drawable:[]};backup;openedDoraCount=1;constructor(t){this.init(t),this.backup=bt.clone(this.walls)}kan(){if(this.walls.replacement.length==0)throw new Error("exceeded maximum kan");const t=this.walls.replacement.pop();return this.walls.drawable.pop(),w.from(t)}draw(){if(!this.walls.drawable)throw new Error("cannot draw any more");return w.from(this.walls.drawable.pop())}openDoraIndicator(){if(this.openedDoraCount>=4)throw new Error("exceeded maximum open dora");return this.openedDoraCount++,w.from(this.walls.doraIndicators[this.openedDoraCount-1])}get doraIndicators(){return this.walls.doraIndicators.slice(0,this.openedDoraCount).map(w.from)}get hiddenDoraIndicators(){return this.walls.hiddenDoraIndicators.slice(0,this.openedDoraCount).map(w.from)}get canKan(){return this.walls.replacement.length>0}get canDraw(){return this.walls.drawable.length>0}initialHands(){const t=P("");for(let e=0;e<3;e++)for(const n of Object.values(_))for(let i=0;i<4;i++)t[n]+=this.draw().toString();for(const e of Object.values(_))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=bt.clone(t);return}else{for(let e of Object.values(p)){if(e==p.BACK)continue;const n=e==p.Z?[1,2,3,4,5,6,7]:[1,2,3,4,5,6,7,8,9];for(let i=0;i<4;i++)for(let r of n){let o=new w(e,r);e!=p.Z&&i==3&&r==5&&(o=o.clone({add:m.RED})),this.walls.drawable.push(o.toString())}}Qe(this.walls.drawable)}for(let e=0;e<14;e++)this.walls.dead.push(this.walls.drawable.pop());for(let e=0;e<4;e++)this.walls.hiddenDoraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.doraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.replacement.push(this.walls.dead.pop())}export(){return this.backup}static clone(t){return{drawable:t.drawable.concat(),dead:t.dead.concat(),doraIndicators:t.doraIndicators.concat(),hiddenDoraIndicators:t.hiddenDoraIndicators.concat(),replacement:t.replacement.concat()}}}class Qt{wall=new bt;playerIDs;actor=$t(Le(this),{});observer;handlers={};mailBox={};histories=[];debugMode;constructor(t,e){this.debugMode=e?.debug??!1,this.handlers=t.reduce((o,a)=>(o[a.id]=a.handler,o),{}),this.playerIDs=t.map(o=>o.id),t.forEach(o=>o.handler.on(a=>this.enqueue(a)));const n=ns();this.observer=new Is(n),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const i=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new Ft(i);const r=e?.shuffle==!1?this.playerIDs:Qe([...this.playerIDs]);this.observer.placeManager=new Vt({[r[0]]:_.E,[r[1]]:_.S,[r[2]]:_.W,[r[3]]:_.N})}boardParams(t){let n=this.hand(t).reached?1:void 0;if(n){const i=this.river.discards(t);n=i.length==0||i.length==1&&i[0].t.has(m.HORIZONTAL)?2:1}return{doraIndicators:this.observer.doraIndicators,round:this.placeManager.round,myWind:t,sticks:this.observer.placeManager.sticks,reached:n}}hand(t){return this.observer.hand(t)}get placeManager(){return this.observer.placeManager}get scoreManager(){return this.observer.scoreManager}get river(){return this.observer.river}next(t){(!this.debugMode||t)&&this.actor.send({type:"NEXT"})}emit(t){const e=this.observer.placeManager.playerID(t.wind);this.handlers[e].emit(t);const n=t.iam;t.wind==n?this.observer.eventHandler.emit(t):n==null&&(!this.observer.applied[t.id]||t.type=="DISTRIBUTE")&&(this.observer.eventHandler.emit(t),this.observer.applied[t.id]=!0)}enqueue(t){this.mailBox[t.id]==null&&(this.mailBox[t.id]=[]),this.mailBox[t.id].push(t)}pollReplies(t,e){const n=this.mailBox[t];if(n==null)throw new Error(`not enqueued ${t} at ${this.actor.getSnapshot().value}`);if(n.length!=e.length)throw new Error(`${t}: num of event: got: ${e.length}, want: ${n.length}`);if(e.length==0){console.warn("no events to handle");return}const i=n[0];if(i.type=="CHOICE_AFTER_DISCARDED"){const r=qn(n);if(r.events.length==0){this.actor.send({type:""});return}const o=r.events[0];switch(r.type){case"RON":I(o.choices.RON,"ron choice is none"),this.actor.send({type:r.type,iam:o.wind,ret:Lt(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:w.from(o.discarterInfo.tile)}});break;case"DAI_KAN":I(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:r.type,iam:o.wind,block:tt.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[r.type];I(a,`${r.type} choice is none`),I(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const c=q.deserialize(a[0]);this.actor.send({type:r.type,iam:o.wind,block:c})}}else if(i.type=="CHOICE_AFTER_DRAWN"){const r=Qn(n);I(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const o=r.events[0],a=o.wind;switch(r.type){case"TSUMO":I(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:r.type,ret:Lt(o.choices.TSUMO),lastTile:w.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[r.type];I(c,`${r.type} candidates is none`),this.actor.send({type:"REACH",tile:w.from(c[0].tile),iam:a});break;case"DISCARD":const l=o.choices[r.type];I(l,`${r.type} choice is none`),this.actor.send({type:r.type,tile:w.from(l[0]).clone({remove:m.TSUMO}),iam:a});break;case"AN_KAN":{const d=o.choices[r.type];I(d,`${r.type} choice is none`),this.actor.send({type:r.type,block:x.from(d[0].tiles),iam:a});break}case"SHO_KAN":{const d=o.choices[r.type];I(d,`${r.type} choice is none`),this.actor.send({type:r.type,block:L.from(d[0].tiles),iam:a});break}case"DRAWN_GAME_BY_NINE_ORPHANS":this.actor.send({type:"DRAWN_GAME_BY_NINE_ORPHANS",iam:a});break}}else if(i.type=="CHOICE_AFTER_CALLED"){I(i.choices.DISCARD,`discard candidate tile is none: ${JSON.stringify(i,null,2)} ${this.hand(i.wind).toString()}`);const r=i.wind,o=w.from(i.choices.DISCARD[0]);this.actor.send({type:"DISCARD",tile:o,iam:r})}else if(i.type=="CHOICE_FOR_REACH_ACCEPTANCE"){const r=n.filter(a=>(I(a.type=="CHOICE_FOR_REACH_ACCEPTANCE"),a.choices.RON!==!1));if(r.length==0){this.actor.send({type:"REACH_ACCEPT",reacherInfo:{tile:w.from(i.reacherInfo.tile),wind:i.reacherInfo.wind}});return}const o=r[0];this.actor.send({type:"RON",iam:o.wind,ret:Lt(o.choices.RON),targetInfo:{wind:o.reacherInfo.wind,tile:w.from(o.reacherInfo.tile)}});return}else if(i.type=="CHOICE_FOR_CHAN_KAN"){const r=n.filter(a=>a.choices.RON!==!1);if(r.length==0){this.actor.send({type:""});return}const o=r[0];I(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:Lt(o.choices.RON),quadWin:!0,targetInfo:{wind:o.callerInfo.wind,tile:w.from(o.callerInfo.tile)}});return}else console.warn(`controller found unexpected event: ${i.type}`)}export(){return this.histories.concat()}static load(t){const e=t.choiceEvents,n=Object.keys(t.players),i={emit:a=>{},on:a=>{}},r=n.map(a=>({id:a,handler:i})),o=new Qt(r);return o.playerIDs=n,o.mailBox=e,o.observer.placeManager=new Vt(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new Ft(t.scores),o.wall=new bt(t.wall),o}start(){this.actor.subscribe(n=>{console.debug("State:",n.value)});const t={scores:this.scoreManager.summary,round:this.placeManager.round,players:this.placeManager.playerMap,wall:this.wall.export(),choiceEvents:this.mailBox,sticks:this.placeManager.sticks};this.actor.start(),this.histories.push(t);const e=this.actor.getSnapshot().status;if(e!="done")throw new Error(`unexpected state ${this.actor.getSnapshot().value}(${e})`)}startGame(){for(;console.debug(`start========${this.placeManager.round}=============`),this.start(),this.wall=new bt,this.observer.applied={},this.mailBox={},this.actor=$t(Le(this)),!this.placeManager.is(C.W1););}finalResult(t,e){const n=this.hand(e),i=n.reached?this.wall.hiddenDoraIndicators:void 0,r=new Me(n,{...t.boardContext,sticks:this.placeManager.sticks,hiddenDoraIndicators:i}).calc(t.hand);return I(r),r}doWin(t,e,n){if(e==null)return!1;let i=this.hand(t);const r=this.boardParams(t);if(i.drawn==null){if(n==null)throw new Error("should ron but params == null");if(n.discardedBy==t||n.missingRon)return!1;i=i.clone(),r.ronWind=n.discardedBy,r.finalDiscardWin=!this.wall.canDraw,r.quadWin=n.quadWin,i.inc([e])}else r.finalWallWin=!this.wall.canDraw,r.replacementWin=n?.replacementWin;r.oneShotWin=n?.oneShot;const o=new Xn(i),a=new Me(i,r),c=o.calc(e),l=a.calc(...c);if(!l||l.yakus.length==0)return!1;if(i.draw==null){const d=Mt.candidateTiles(this.hand(t)).candidates;if(this.river.discards(t).some(h=>d.some(u=>u.equals(h.t))))return!1}return l}doPon(t,e,n){if(n==null||t==e)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3||i.get(n.t,n.n)<2)return!1;const r=n.clone({removeAll:!0}),o=Se(t,e,b.PON),a=[],c=new q([r,r,r]).clone({replace:{idx:o,tile:n.clone({add:m.HORIZONTAL})}});let l=c;R(n)&&n.has(m.RED)&&(l=c.clone({replace:{idx:o,tile:r.clone({add:[m.RED,m.HORIZONTAL]})}}));const d=o%2+1;if(R(n)&&i.get(n.t,0)>0&&(l=c.clone({replace:{idx:d,tile:r.clone({add:m.RED})}})),a.push(l),R(r)&&i.get(r.t,5)==3){const h=c.clone({replace:{idx:d,tile:r}});a.push(h)}return a}doChi(t,e,n){if(n==null||!n.isNum()||yt(e)!=t)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3)return!1;const r=n.clone({remove:m.TSUMO,add:[m.HORIZONTAL]}),o=[];r.n-2>=1&&i.get(n.t,r.n-2)>0&&i.get(n.t,r.n-1)>0&&o.push(new X([r,new w(n.t,r.n-1),new w(n.t,r.n-2)])),r.n+2<=9&&i.get(n.t,r.n+1)>0&&i.get(n.t,r.n+2)>0&&o.push(new X([r,new w(n.t,r.n+1),new w(n.t,r.n+2)])),r.n-1>=1&&r.n+1<=9&&i.get(n.t,r.n-1)>0&&i.get(n.t,r.n+1)>0&&o.push(new X([r,new w(n.t,r.n-1),new w(n.t,r.n+1)]));for(let u=0;u<o.length;u++){const g=o[u],f=this.cannotDiscardTile(g),y=[];for(const O of f){const v=i.get(O.t,O.n);for(let S=0;S<v;S++)y.push(O.clone({remove:m.RED}))}const E=i.dec([...y,g.tiles[1],g.tiles[2]]),A=i.hands.length==0;i.inc(E),A&&o.splice(u,1)}if(o.length==0)return!1;const h=i.get(n.t,0)>0?this.redPattern(o):[];return h.length>0&&i.get(n.t,5)==1?h:[...o,...h]}redPattern(t){return t.length==0?[]:t.filter(n=>R(n.tiles[1])||R(n.tiles[2])).map(n=>{if(R(n.tiles[1])){const i=n.tiles[1].clone({add:m.RED});return n.clone({replace:{idx:1,tile:i}})}else if(R(n.tiles[2])){const i=n.tiles[2].clone({add:m.RED});return n.clone({replace:{idx:2,tile:i}})}}).filter(n=>n!=null)}doReach(t){const e=this.hand(t);return e.reached||!e.menzen||new Xt(e).calc()>0?!1:Mt.calcCandidates(e,e.hands)}doDiscard(t,e){if(this.hand(t).reached)return[this.hand(t).drawn];const n=this.hand(t).hands;if(e==null)return n;if(e instanceof q)return n.filter(o=>!o.equals(e.tiles[0]));const i=this.cannotDiscardTile(e),r=n.filter(o=>!i.some(a=>o.equals(a)));return I(r.length>0,`no tiles to discard. hand: ${this.hand(t)}, suji: ${i}, block-chi: ${e}`),r}cannotDiscardTile(t){const e=t.tiles[0],n=t.tiles[1].n;return n!=1&&e.n-2==n?[new w(e.t,e.n-3),e]:n!=8&&e.n+1==n?[new w(e.t,e.n+3),e]:[e]}doAnKan(t){const e=this.hand(t),n=[];if(e.reached)return!1;for(const[i,r]of U())if(e.get(i,r)==4){const o=new w(i,r),a=[o,o,o,o];R(o)&&(a[1]=o.clone({add:m.RED})),n.push(new x(a))}if(n.length==0)return!1;for(const i of n)I(i.tiles.filter(r=>r.has(m.HORIZONTAL)).length==0,`h op ${i.toString()}`);return n}doShoKan(t){const e=this.hand(t);if(e.reached)return!1;const n=e.called.filter(r=>r instanceof q);if(n.length==0)return!1;const i=[];for(const r of n){const o=r.tiles[0].clone({removeAll:!0,add:m.HORIZONTAL});if(e.get(o.t,o.n)==1){const a=R(o)&&e.get(o.t,0)>0?o.clone({add:m.RED}):o;i.push(new L([...r.tiles,a]))}}if(i.length==0)return!1;for(const r of i)I(r.tiles.filter(o=>o.has(m.HORIZONTAL)).length==2,`h op ${r.toString()}`);return i}doDaiKan(t,e,n){const i=this.hand(t);if(i.reached||t==e)return!1;const r=n.clone({removeAll:!0});if(i.get(r.t,r.n)!=3)return!1;const o=Se(t,e,b.DAI_KAN);let a=new tt([r,r,r,r]).clone({replace:{idx:o,tile:r.clone({add:m.HORIZONTAL})}});if(R(n)&&n.has(m.RED))a=a.clone({replace:{idx:o,tile:r.clone({add:[m.HORIZONTAL,m.RED]})}});else if(R(n)&&!n.has(m.RED)){I(i.get(n.t,0)>0,`hand does not have red tile: ${i.toString()}`);const c=o%3+1;a=a.clone({replace:{idx:c,tile:r.clone({add:m.RED})}})}return I(a.tiles.filter(c=>c.has(m.HORIZONTAL)).length==1,`h op ${a.toString()}`),a}canDrawnGame(t){if(this.river.discards(t).length!=0)return!1;const e=this.hand(t);let n=0;for(const i of Object.values(p)){if(i==p.BACK)continue;const r=i==p.Z?xt:J;for(const o of r)e.get(i,o)>0&&n++}return n>=9}initialHands(){return this.wall.initialHands()}}class _t extends we{isBackHand(){for(const t of Object.values(p))if(t!=p.BACK&&this.sum(t)>0)return!1;return this.sum(p.BACK)>0}clone(){const t=new _t(this.toString());return t.data.reached=this.data.reached,t}dec(t){return this.isBackHand()?(super.dec(t.map(()=>new w(p.BACK,0))),[...t]):super.dec(t)}}class dn{id;river=new tn;placeManager=new Vt({});scoreManager=new Ft({});hands=P(new _t(""));counter=new ss;doraIndicators=[];eventHandler;constructor(t,e){this.id=t,this.eventHandler=e}hand(t){return this.hands[t]}handleEvent(t){switch(t.type){case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DISCARDED":case"CHOICE_AFTER_DRAWN":case"CHOICE_FOR_CHAN_KAN":case"CHOICE_FOR_REACH_ACCEPTANCE":break;case"DISTRIBUTE":this.counter.reset();const e=w.from(t.doraIndicator);this.setHands(t),this.placeManager=new Vt(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new Ft(structuredClone(t.scores)),this.doraIndicators=[e],this.counter.dec(e);for(const i of Object.values(_))i==t.wind&&this.counter.dec(...this.hand(i).hands);break;case"DRAW":{const i=w.from(t.tile);this.hands[t.iam].draw(i),this.counter.dec(i);break}case"DISCARD":{const i=w.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(_))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"PON":case"CHI":case"DAI_KAN":{const i=T.deserialize(t.block);this.hands[t.iam].call(i),this.river.markCalled(),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(m.HORIZONTAL)));break}case"SHO_KAN":{const i=L.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(i.tiles.filter(r=>r.has(m.HORIZONTAL))[0]);break}case"AN_KAN":{const i=x.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(m.HORIZONTAL)));break}case"REACH":{this.hands[t.iam].reach();const i=w.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(_))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"REACH_ACCEPTED":const n=this.placeManager.playerID(t.reacherInfo.wind);this.scoreManager.reach(n),this.placeManager.incrementReachStick();break;case"NEW_DORA":{const i=w.from(t.doraIndicator);this.doraIndicators.push(i),this.counter.dec(i);break}case"TSUMO":break;case"RON":break;case"END_GAME":switch(t.subType){case"NINE_TILES":case"FOUR_KAN":case"FOUR_WIND":this.placeManager.incrementDeadStick();break;case"DRAWN_GAME":{const i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),this.placeManager.incrementDeadStick(),t.shouldContinue||this.placeManager.nextRound();break}case"WIN_GAME":{const i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),t.shouldContinue?this.placeManager.incrementDeadStick():(this.placeManager.nextRound(),this.placeManager.resetDeadStick()),this.placeManager.resetReachStick();break}}break;default:throw new Error(`unexpected event ${JSON.stringify(t,null,2)}`)}}}class Is extends dn{applied={};constructor(t){super("observer",t),this.counter.disable=!0,this.hands=P(new _t("_____________"))}setHands(t){this.hands[t.wind]=new _t(t.hands[t.wind])}handleEvent(t){switch(super.handleEvent(t),t.type){case"DISTRIBUTE":let e=!0;for(const n of Object.values(_))e&&=this.hand(n).get(p.BACK,0)==0;if(!e)break;console.debug("DISTRIBUTE:",`round: ${this.placeManager.round}`,`scores: ${JSON.stringify(this.scoreManager.summary,null,2)}`,`map: ${JSON.stringify(this.placeManager.playerMap,null,2)}`,`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`);for(const n of Object.values(_))console.debug(`${this.placeManager.playerID(n)}(${n})`,`init hand: ${this.hand(n).toString()}`);break;case"DRAW":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`draw: ${this.hand(t.iam).drawn}`,`hand: ${this.hand(t.iam).toString()}`);break;case"DISCARD":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`discard: ${t.tile.toString()}`,`hand: ${this.hand(t.iam).toString()}`);break;case"CHI":case"PON":case"DAI_KAN":case"AN_KAN":case"SHO_KAN":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`call: ${t.block.tiles}`,`hand: ${this.hand(t.iam).toString()}`);break;case"REACH":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`reach: ${t.tile}`,`hand: ${this.hand(t.iam).toString()}`);break;case"TSUMO":case"RON":console.debug(`${this.placeManager.playerID(t.iam)}(${t.iam})`,`ron/tsumo: ${JSON.stringify(t.ret,null,2)}`,`hand: ${this.hand(t.iam).toString()}`);break;case"END_GAME":for(const n of Object.values(_))console.debug(`${this.placeManager.playerID(n)}(${ge(n)})`,`end hand: ${this.hand(n).toString()}`);console.debug("END_GAME",t.subType,"scores",JSON.stringify(this.scoreManager.summary,null,2),`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`)}}}class Zt extends dn{river=new tn;doras=[];constructor(t,e){super(t,e),this.eventHandler.on(n=>this.handleEvent(n))}get myWind(){return this.placeManager.wind(this.id)}setHands(t){for(const e of Object.values(_))this.hands[e]=new _t(t.hands[e])}handleDiscard(t){const e=Object.values(_).filter(l=>l==this.myWind?!1:this.hand(l).reached),n=new Xt(this.hand(this.myWind)).calc();if(e.length>0&&n>=2)return Tt.selectTile(this.counter,e,t);const i=Mt.calcCandidates(this.hand(this.myWind),t),o=Yt.calcPlayerCandidates(this.counter,i).sort((l,d)=>d.sum-l.sum),a=o.filter(l=>l.sum==o[0].sum);return Yt.selectMinPriority(this.counter,a,this.doras).tile}handleEvent(t){switch(t.type){case"CHOICE_AFTER_DISCARDED":t.choices.CHI=!1,t.choices.DAI_KAN=!1,t.choices.PON=!1,this.eventHandler.emit(t);break;case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DRAWN":if(t.choices.DISCARD){const e=this.handleDiscard(t.choices.DISCARD.map(w.from));t.choices.DISCARD=[e.toString()]}this.eventHandler.emit(t);break;case"CHOICE_FOR_REACH_ACCEPTANCE":this.eventHandler.emit(t);break;case"CHOICE_FOR_CHAN_KAN":this.eventHandler.emit(t);break;default:super.handleEvent(t)}}}class Do{index=0;histories=[];constructor(t){this.histories=JSON.parse(t)}next(){I(this.index<this.histories.length),this.index++}prev(){this.index--,I(this.index<0)}start(){Qt.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const Ko=s=>{const[t,e]=Ut(),[n,i]=Ut(),[r,o]=Ut(),[a,c]=Ut(),l=["player-1","player-2","player-3","player-4"],d=s?.playerInjection,h=d?.p1??Zt,u=d?.p2??Zt,g=d?.p3??Zt,f=d?.p4??Zt,y=new h(l[0],e),E=new u(l[1],i),A=new g(l[2],o),O=new f(l[3],c),v=[{handler:t,id:l[0]},{handler:n,id:l[1]},{handler:r,id:l[2]},{handler:a,id:l[3]}];return{c:new Qt(v,{debug:s?.debug,shuffle:s?.shuffle}),p1:y,p2:E,p3:A,p4:O}},ut=(s,t)=>{let n=1;for(let i of t)i.equals(s)&&(n*=2);return n};class Yt{static calcPlayerCandidates(t,e){let n=[];for(let i of e){let r=0,o=[];for(let a of i.candidates)o.push({tile:a.clone(),n:t.get(a)}),r+=t.get(a);n.push({sum:r,tile:i.tile,candidates:o,shanten:i.shanten})}return n}static selectMinPriority(t,e,n){I(e.length>0);let i=0,r=0;for(let o=0;o<e.length;o++){const a=Yt.calcPriority(t,e[o],n);a<i&&(i=a,r=o)}return e[r]}static calcPriority(t,e,n){const i=e.tile;let r=0;if(i.t==p.Z)return r=t.get(i),(i.n==5||i.n==6||i.n==7)&&(r*=2),r*ut(i,n);{const o=t.get(i);r+=o*ut(i,n);const a=t.get(new w(i.t,i.n+1)),c=t.get(new w(i.t,i.n+2)),l=t.get(new w(i.t,i.n-1)),d=t.get(new w(i.t,i.n-2)),h=i.n-2>0?Math.min(l,d):0,u=i.n+2<=9?Math.min(a,c):0,g=i.n-1>=1&&i.n+1<=9?Math.min(a,l):0,f=Math.max(h,g),y=Math.max(g,u);return r+=o*ut(i,n),r+=h*ut(new w(i.t,i.n-2),n),r+=u*ut(new w(i.t,i.n+2),n),r+=f*ut(new w(i.t,i.n-1),n),r+=y*ut(new w(i.t,i.n+1),n),i.n==0,r}}}class Tt{static selectTile(t,e,n){I(e.length>0&&n.length>0);let i=n[0],r=Number.POSITIVE_INFINITY;for(let o of n){const a=Tt.rank(t,e,o);a<r&&(i=o,r=a)}return i}static rank(t,e,n){let i=0;const r=n.isNum()?Tt.rankN:Tt.rankZ;for(let o of e){const a=r(t,o,n);i<a&&(i=a)}return i}static rankZ(t,e,n){if(n.t!=p.Z)throw new Error(`expected TYPE.Z but ${n.toString()}`);if(t.isSafeTile(n.t,n.n,e))return 0;const i=t.get(n);return Math.min(i,3)}static rankN(t,e,n){if(!n.isNum())throw new Error(`expected TYPE.NUMBER but ${n.toString()}`);const i=n.n,r=n.t;if(t.isSafeTile(r,i,e))return 0;if(i==1)return t.isSafeTile(r,4,e)?3:6;if(i==9)return t.isSafeTile(r,6,e)?3:6;if(i==2||i==8)return t.isSafeTile(r,5,e)?4:8;if(i==3)return t.isSafeTile(r,6,e)?5:8;if(i==7)return t.isSafeTile(r,4,e)?5:8;const o=t.isSafeTile(r,i-3,e),a=t.isSafeTile(r,i+3,e);return o&&a?4:o||a?8:12}}exports.ActorHand=_t;exports.BLOCK=b;exports.BaseActor=dn;exports.Block=T;exports.BlockAnKan=x;exports.BlockCalculator=Xn;exports.BlockChi=X;exports.BlockDaiKan=tt;exports.BlockHand=Ot;exports.BlockIsolated=Ge;exports.BlockOther=Fe;exports.BlockPair=D;exports.BlockPon=q;exports.BlockRun=nt;exports.BlockShoKan=L;exports.BlockThree=Z;exports.Controller=Qt;exports.Counter=ss;exports.Efficiency=Mt;exports.FONT_FAMILY=je;exports.G=N;exports.Hand=we;exports.INPUT_SEPARATOR=et;exports.Image=Ye;exports.ImageHelper=qe;exports.Mark=ct;exports.MeasureText=Cs;exports.MyG=Zi;exports.MyImage=Gi;exports.MyRect=Vi;exports.MySVG=Ui;exports.MyText=Yi;exports.MyUse=Fi;exports.N19=J;exports.NZ=xt;exports.OP=m;exports.Observer=Is;exports.Parser=K;exports.PlaceManager=Vt;exports.Player=Zt;exports.PlayerEfficiency=Yt;exports.PointCalculator=Me;exports.ROUND=C;exports.ROUND_MAP=Ue;exports.Rect=Je;exports.Replayer=Do;exports.RiskRank=Tt;exports.River=tn;exports.STICK_CONTEXT=Ne;exports.SVG=Ln;exports.ScoreManager=Ft;exports.ShantenCalculator=Xt;exports.Svg=zn;exports.Symbol=Xe;exports.TABLE_CONTEXT=xn;exports.TILE_CONTEXT=it;exports.TYPE=p;exports.Text=wt;exports.Tile=w;exports.Use=ye;exports.WIND=_;exports.WIND_MAP=pe;exports.Wall=bt;exports.convertInput=Jn;exports.createControllerMachine=Le;exports.createEventEmitter=ns;exports.createEventPipe=Ut;exports.createHand=Nt;exports.createLocalGame=Ko;exports.createTable=Zn;exports.createWindMap=P;exports.deserializeWinResult=Lt;exports.drawBlocks=nr;exports.drawTable=dr;exports.forHand=U;exports.getCallBlockIndex=Se;exports.incrementalIDGenerator=vs;exports.isNum5=R;exports.nextRound=Gt;exports.nextWind=yt;exports.optimizeSVG=ir;exports.parse=Vn;exports.parseTableInput=Yn;exports.prevRound=Ws;exports.prevWind=ge;exports.prioritizeDiscardedEvents=qn;exports.prioritizeDrawnEvents=Qn;exports.serializeWinResult=le;exports.shuffle=Qe;exports.sortCalledTiles=Mn;exports.tileSortFunc=Jt;exports.toDora=$e;
|