@konoui/mjimage 0.0.47 → 0.0.48
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/README.md +4 -2
- package/dist/index.cjs +16 -10
- package/dist/index.d.cts +141 -11
- package/dist/index.d.ts +141 -11
- package/dist/index.js +4003 -6420
- package/package.json +7 -8
package/dist/index.cjs
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
|
-
"use strict";var dr=Object.defineProperty;var pr=(s,t,e)=>t in s?dr(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var A=(s,t,e)=>pr(s,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Zn="MS Gothic, sans-serif",Et={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Js={BASE:40},At=",",p={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"},v={E:"1w",S:"2w",W:"3w",N:"4w"},j={E1:"1w1",E2:"1w2",E3:"1w3",E4:"1w4",S1:"2w1",S2:"2w2",S3:"2w3",S4:"2w4",W1:"3w1",W2:"3w2",W3:"3w3",W4:"3w4",N1:"4w1",N2:"4w2",N3:"4w3",N4:"4w4"},nn={[v.E]:"東",[v.S]:"南",[v.W]:"西",[v.N]:"北"},Yn={[j.E1]:"東1局",[j.E2]:"東2局",[j.E3]:"東3局",[j.E4]:"東4局",[j.S1]:"南1局",[j.S2]:"南2局",[j.S3]:"南3局",[j.S4]:"南4局",[j.W1]:"西1局",[j.W2]:"西2局",[j.W3]:"西3局",[j.W4]:"西4局",[j.N1]:"北1局",[j.N2]:"北2局",[j.N3]:"北3局",[j.N4]:"北4局"};function O(s,t){if(!s)throw new Error(t)}class mr{constructor(t="東",e="2"){A(this,"ctx",null);A(this,"strText");A(this,"numText");A(this,"measure",(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),O(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]});A(this,"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}});A(this,"measureTableFontContext",t=>{const e=this.measureFontContext(Zn,Js.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e});this.strText=t,this.numText=e}}class gr{constructor(t){A(this,"input");A(this,"position");A(this,"nextPosition");A(this,"char");A(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 Ie=(s,t)=>{if(s.t==t.t){if(z(s)&&z(t)){if(s.has(y.RED))return-1;if(t.has(y.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]},yr=(s,t)=>{const e={[y.HORIZONTAL]:1,[y.TSUMO]:2,[y.RON]:3,[y.DORA]:4,[y.COLOR_GRAYSCALE]:5,[y.RED]:6};return e[s]-e[t]},Vs=s=>{const t=[];s.forEach((n,i)=>{n.has(y.HORIZONTAL)&&t.push(i)});const e=s.filter(n=>!n.has(y.HORIZONTAL)).sort(Ie);return t.forEach(n=>{e.splice(n,0,s[n])}),e};function z(s){return s.isNum()&&s.n==5}function wr(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 Q(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(yr).join("")}${this.n}${this.t}`}toJSON(){return this.toString()}clone(t){const e=(t==null?void 0:t.t)??this.t,n=(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,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 B{constructor(t,e){A(this,"_tiles");A(this,"_type");if(this._tiles=t,this._type=e,this.isCalled()){this._tiles=Vs(this._tiles);return}if(this._type!=b.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Ie);return}}static deserialize(t){const e=new Q(t.tiles).parse();if(e.length!=1)throw new Error(`block must be 1: ${t.tiles}`);const n=e[0].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 qe(e[0].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,n=[...this.tiles];return e&&(n[e.idx]=e.tile),qe(n,this._type)}}const Ut=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}`},Xn=s=>{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 dt extends B{constructor(t){super(t,b.CHI)}static from(t){return B.deserialize({tiles:t,type:b.CHI})}toString(){return Ut(this.tiles)}}class _t extends B{constructor(t){super(t,b.PON)}static from(t){return B.deserialize({tiles:t,type:b.PON})}toString(){return Ut(this.tiles)}}class U extends B{constructor(t){const e=t.filter(i=>i.t!=p.BACK),n=e[0];if(e.length<t.length){if(z(n)){const i=new w(n.t,5);super([i.clone({add:y.RED}),i,i,i],b.AN_KAN);return}super([n,n,n,n],b.AN_KAN);return}super(t,b.AN_KAN)}get tilesWithBack(){const t=this.tiles[0].clone({remove:y.RED}),e=z(t)?t.clone({add:y.RED}):t;return[new w(p.BACK,0),e,t,new w(p.BACK,0)]}static from(t){return B.deserialize({tiles:t,type:b.AN_KAN})}toString(){return Xn(this.tilesWithBack)}}class wt extends B{constructor(t){super(t,b.DAI_KAN)}static from(t){return B.deserialize({tiles:t,type:b.DAI_KAN})}toString(){return Ut(this.tiles)}}class ct extends B{constructor(t){super(t,b.SHO_KAN)}static from(t){return B.deserialize({tiles:t,type:b.SHO_KAN})}toString(){return Ut(this.tiles)}}class Y extends B{constructor(t,e){super([t,e],b.PAIR)}toString(){return Ut(this.tiles)}}class at extends B{constructor(t){super(t,b.THREE)}static from(t){return B.deserialize({tiles:t,type:b.THREE})}toString(){return Ut(this.tiles)}}class St extends B{constructor(t){super(t,b.RUN)}static from(t){return B.deserialize({tiles:t,type:b.RUN})}toString(){return Ut(this.tiles)}}class Jn extends B{constructor(t){super([t],b.ISOLATED)}toString(){return this.tiles[0].toString()}}class ee extends B{constructor(t){super(t,b.HAND)}toString(){return Xn(this.tiles)}}class Vn extends B{constructor(t,e){super(t,e)}toString(){return this.is(b.IMAGE_DISCARD)?this.tiles.join(""):Xn(this.tiles)}}const qe=(s,t)=>{switch(t){case b.CHI:return new dt([s[0],s[1],s[2]]);case b.PON:return new _t([s[0],s[1],s[2]]);case b.AN_KAN:return new U(s);case b.DAI_KAN:return new wt(s);case b.SHO_KAN:return new ct(s);case b.THREE:return new at(s);case b.RUN:return new St(s);case b.PAIR:return new Y(s[0],s[1]);case b.ISOLATED:return new Jn(s[0]);case b.HAND:return new ee(s);default:return new Vn(s,t)}};class Q{constructor(t){A(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!=At)}tileSeparators(){const t=new gr(this.input),e=[];let n=[];for(this.validate(this.input);;){t.skipWhitespace();const i=t.char;if(i===t.eof)break;if(i==At){e.push(At),t.readChar();continue}const[r,o]=Ds(i,n);if(o){if(r==p.BACK){e.push(new w(r,0)),t.readChar();continue}e.push(...br(n,r)),n=[],t.readChar();continue}else{const[a,c]=vr(t);if(c){n.push(a),t.readChar();continue}const[h,l]=Qs(i);if(!l)throw new Error(`encounter unexpected number. n: ${h}, current: ${i}, input: ${t.input}`);n.push({n:h})}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==At){const a=Ns(e),c=qe(e,a);n.push(c),e=[];continue}e.push(o)}const i=Ns(e),r=qe(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]=Ds(e,[new w(p.BACK,1)]);if(!i)throw new Error(`last character(${e}) is not type value`)}}function Ns(s){if(s.length===0)return b.UNKNOWN;if(s.length===1)return s[0].has(y.DORA)?b.IMAGE_DORA:s[0].has(y.TSUMO)?b.TSUMO:b.HAND;const t=s.every(r=>r.equals(s[0])),e=s.filter(r=>r.has(y.HORIZONTAL)).length,n=s.filter(r=>r.has(y.TSUMO)||r.has(y.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&&_r(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 _r(s){const t=[...s].sort(Ie);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 br(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:y.RED}):n})}function Ds(s,t){const[e,n]=wr(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 Qs(s){const t=Number(s),e=0<=t&&t<=9;return[t,e]}function vr(s){const t=Object.values(y);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]=Qs(i);if(!o)break;for(const c of e)s.readChar();const a=new w(p.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(p.BACK,0),!1]}function Z(s,t=!1){const e={[v.E]:s,[v.S]:s,[v.W]:s,[v.N]:s};if(t)for(let n of Object.values(v))e[n]=structuredClone(s);return e}const ve=s=>{let t=s.substring(0,2),e=Number(s.substring(2,3));return e==4?(e=1,t=kt(t)):e++,`${t}${e}`},Ar=s=>ve(ve(ve(s))),kt=s=>{let t=Number(s.toString()[0]);return t=t%4+1,`${t}w`},Qn=s=>{let t=Number(s.toString()[0]);return t=t%2+1,`${t}w`},An=(s,t,e)=>{const n=Math.abs(Number(s[0])-Number(t[0]));return O(n==1||n==2||n==3),e==b.PON?n==3?0:n==2?1:2:n==3?0:n==1?3:2},Sn={},ti=[];function k(s,t){if(Array.isArray(s)){for(const e of s)k(e,t);return}if(typeof s=="object"){for(const e in s)k(e,s[e]);return}ei(Object.getOwnPropertyNames(t)),Sn[s]=Object.assign(Sn[s]||{},t)}function J(s){return Sn[s]||{}}function Sr(){return[...new Set(ti)]}function ei(s){ti.push(...s)}function ts(s,t){let e;const n=s.length,i=[];for(e=0;e<n;e++)i.push(t(s[e]));return i}function xr(s,t){let e;const n=s.length,i=[];for(e=0;e<n;e++)t(s[e])&&i.push(s[e]);return i}function un(s){return s%360*Math.PI/180}function Er(s){return s.replace(/([A-Z])/g,function(t,e){return"-"+e.toLowerCase()})}function ni(s){return s.charAt(0).toUpperCase()+s.slice(1)}function fe(s,t,e,n){return(t==null||e==null)&&(n=n||s.bbox(),t==null?t=n.width/n.height*e:e==null&&(e=n.height/n.width*t)),{width:t,height:e}}function xn(s,t){const e=s.origin;let n=s.ox!=null?s.ox:s.originX!=null?s.originX:"center",i=s.oy!=null?s.oy:s.originY!=null?s.originY:"center";e!=null&&([n,i]=Array.isArray(e)?e:typeof e=="object"?[e.x,e.y]:[e,e]);const r=typeof n=="string",o=typeof i=="string";if(r||o){const{height:a,width:c,x:h,y:l}=t.bbox();r&&(n=n.includes("left")?h:n.includes("right")?h+c:h+c/2),o&&(i=i.includes("top")?l:i.includes("bottom")?l+a:l+a/2)}return[n,i]}const kr=new Set(["desc","metadata","title"]),En=s=>kr.has(s.nodeName),si=(s,t,e={})=>{const n={...t};for(const i in n)n[i].valueOf()===e[i]&&delete n[i];Object.keys(n).length?s.node.setAttribute("data-svgjs",JSON.stringify(n)):(s.node.removeAttribute("data-svgjs"),s.node.removeAttribute("svgjs:data"))},es="http://www.w3.org/2000/svg",Tr="http://www.w3.org/1999/xhtml",fn="http://www.w3.org/2000/xmlns/",Ne="http://www.w3.org/1999/xlink",I={window:typeof window>"u"?null:window,document:typeof document>"u"?null:document};function Or(){return I.window}class ns{}const Bt={},ss="___SYMBOL___ROOT___";function Ae(s,t=es){return I.document.createElementNS(t,s)}function X(s,t=!1){if(s instanceof ns)return s;if(typeof s=="object")return dn(s);if(s==null)return new Bt[ss];if(typeof s=="string"&&s.charAt(0)!=="<")return dn(I.document.querySelector(s));const e=t?I.document.createElement("div"):Ae("svg");return e.innerHTML=s,s=dn(e.firstChild),e.removeChild(e.firstChild),s}function $(s,t){return t&&(t instanceof I.window.Node||t.ownerDocument&&t instanceof t.ownerDocument.defaultView.Node)?t:Ae(s)}function st(s){if(!s)return null;if(s.instance instanceof ns)return s.instance;if(s.nodeName==="#document-fragment")return new Bt.Fragment(s);let t=ni(s.nodeName||"Dom");return t==="LinearGradient"||t==="RadialGradient"?t="Gradient":Bt[t]||(t="Dom"),new Bt[t](s)}let dn=st;function N(s,t=s.name,e=!1){return Bt[t]=s,e&&(Bt[ss]=s),ei(Object.getOwnPropertyNames(s.prototype)),s}function Ir(s){return Bt[s]}let Nr=1e3;function ii(s){return"Svgjs"+ni(s)+Nr++}function ri(s){for(let t=s.children.length-1;t>=0;t--)ri(s.children[t]);return s.id&&(s.id=ii(s.nodeName)),s}function T(s,t){let e,n;for(s=Array.isArray(s)?s:[s],n=s.length-1;n>=0;n--)for(e in t)s[n].prototype[e]=t[e]}function H(s){return function(...t){const e=t[t.length-1];return e&&e.constructor===Object&&!(e instanceof Array)?s.apply(this,t.slice(0,-1)).attr(e):s.apply(this,t)}}function Dr(){return this.parent().children()}function Cr(){return this.parent().index(this)}function Mr(){return this.siblings()[this.position()+1]}function Rr(){return this.siblings()[this.position()-1]}function Hr(){const s=this.position();return this.parent().add(this.remove(),s+1),this}function $r(){const s=this.position();return this.parent().add(this.remove(),s?s-1:0),this}function Br(){return this.parent().add(this.remove()),this}function Wr(){return this.parent().add(this.remove(),0),this}function Pr(s){s=X(s),s.remove();const t=this.position();return this.parent().add(s,t),this}function jr(s){s=X(s),s.remove();const t=this.position();return this.parent().add(s,t+1),this}function zr(s){return s=X(s),s.before(this),this}function Kr(s){return s=X(s),s.after(this),this}k("Dom",{siblings:Dr,position:Cr,next:Mr,prev:Rr,forward:Hr,backward:$r,front:Br,back:Wr,before:Pr,after:jr,insertBefore:zr,insertAfter:Kr});const oi=/^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i,Lr=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,Ur=/rgb\((\d+),(\d+),(\d+)\)/,Fr=/(#[a-z_][a-z0-9\-_]*)/i,qr=/\)\s*,?\s*/,Gr=/\s/g,Cs=/^#[a-f0-9]{3}$|^#[a-f0-9]{6}$/i,Ms=/^rgb\(/,Rs=/^(\s+)?$/,Hs=/^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Zr=/\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i,bt=/[\s,]+/,is=/[MLHVCSQTAZ]/i;function Yr(){const s=this.attr("class");return s==null?[]:s.trim().split(bt)}function Xr(s){return this.classes().indexOf(s)!==-1}function Jr(s){if(!this.hasClass(s)){const t=this.classes();t.push(s),this.attr("class",t.join(" "))}return this}function Vr(s){return this.hasClass(s)&&this.attr("class",this.classes().filter(function(t){return t!==s}).join(" ")),this}function Qr(s){return this.hasClass(s)?this.removeClass(s):this.addClass(s)}k("Dom",{classes:Yr,hasClass:Xr,addClass:Jr,removeClass:Vr,toggleClass:Qr});function to(s,t){const e={};if(arguments.length===0)return this.node.style.cssText.split(/\s*;\s*/).filter(function(n){return!!n.length}).forEach(function(n){const i=n.split(/\s*:\s*/);e[i[0]]=i[1]}),e;if(arguments.length<2){if(Array.isArray(s)){for(const n of s){const i=n;e[n]=this.node.style.getPropertyValue(i)}return e}if(typeof s=="string")return this.node.style.getPropertyValue(s);if(typeof s=="object")for(const n in s)this.node.style.setProperty(n,s[n]==null||Rs.test(s[n])?"":s[n])}return arguments.length===2&&this.node.style.setProperty(s,t==null||Rs.test(t)?"":t),this}function eo(){return this.css("display","")}function no(){return this.css("display","none")}function so(){return this.css("display")!=="none"}k("Dom",{css:to,show:eo,hide:no,visible:so});function io(s,t,e){if(s==null)return this.data(ts(xr(this.node.attributes,n=>n.nodeName.indexOf("data-")===0),n=>n.nodeName.slice(5)));if(s instanceof Array){const n={};for(const i of s)n[i]=this.data(i);return n}else if(typeof s=="object")for(t in s)this.data(t,s[t]);else if(arguments.length<2)try{return JSON.parse(this.attr("data-"+s))}catch{return this.attr("data-"+s)}else this.attr("data-"+s,t===null?null:e===!0||typeof t=="string"||typeof t=="number"?t:JSON.stringify(t));return this}k("Dom",{data:io});function ro(s,t){if(typeof arguments[0]=="object")for(const e in s)this.remember(e,s[e]);else{if(arguments.length===1)return this.memory()[s];this.memory()[s]=t}return this}function oo(){if(arguments.length===0)this._memory={};else for(let s=arguments.length-1;s>=0;s--)delete this.memory()[arguments[s]];return this}function ao(){return this._memory=this._memory||{}}k("Dom",{remember:ro,forget:oo,memory:ao});function co(s){return s.length===4?["#",s.substring(1,2),s.substring(1,2),s.substring(2,3),s.substring(2,3),s.substring(3,4),s.substring(3,4)].join(""):s}function ho(s){const t=Math.round(s),n=Math.max(0,Math.min(255,t)).toString(16);return n.length===1?"0"+n:n}function qt(s,t){for(let e=t.length;e--;)if(s[t[e]]==null)return!1;return!0}function lo(s,t){const e=qt(s,"rgb")?{_a:s.r,_b:s.g,_c:s.b,_d:0,space:"rgb"}:qt(s,"xyz")?{_a:s.x,_b:s.y,_c:s.z,_d:0,space:"xyz"}:qt(s,"hsl")?{_a:s.h,_b:s.s,_c:s.l,_d:0,space:"hsl"}:qt(s,"lab")?{_a:s.l,_b:s.a,_c:s.b,_d:0,space:"lab"}:qt(s,"lch")?{_a:s.l,_b:s.c,_c:s.h,_d:0,space:"lch"}:qt(s,"cmyk")?{_a:s.c,_b:s.m,_c:s.y,_d:s.k,space:"cmyk"}:{_a:0,_b:0,_c:0,space:"rgb"};return e.space=t||e.space,e}function uo(s){return s==="lab"||s==="xyz"||s==="lch"}function pn(s,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?s+(t-s)*6*e:e<1/2?t:e<2/3?s+(t-s)*(2/3-e)*6:s}class M{constructor(...t){this.init(...t)}static isColor(t){return t&&(t instanceof M||this.isRgb(t)||this.test(t))}static isRgb(t){return t&&typeof t.r=="number"&&typeof t.g=="number"&&typeof t.b=="number"}static random(t="vibrant",e){const{random:n,round:i,sin:r,PI:o}=Math;if(t==="vibrant"){const a=24*n()+57,c=38*n()+45,h=360*n();return new M(a,c,h,"lch")}else if(t==="sine"){e=e??n();const a=i(80*r(2*o*e/.5+.01)+150),c=i(50*r(2*o*e/.5+4.6)+200),h=i(100*r(2*o*e/.5+2.3)+150);return new M(a,c,h)}else if(t==="pastel"){const a=8*n()+86,c=17*n()+9,h=360*n();return new M(a,c,h,"lch")}else if(t==="dark"){const a=10+10*n(),c=50*n()+86,h=360*n();return new M(a,c,h,"lch")}else if(t==="rgb"){const a=255*n(),c=255*n(),h=255*n();return new M(a,c,h)}else if(t==="lab"){const a=100*n(),c=256*n()-128,h=256*n()-128;return new M(a,c,h,"lab")}else if(t==="grey"){const a=255*n();return new M(a,a,a)}else throw new Error("Unsupported random color mode")}static test(t){return typeof t=="string"&&(Cs.test(t)||Ms.test(t))}cmyk(){const{_a:t,_b:e,_c:n}=this.rgb(),[i,r,o]=[t,e,n].map(f=>f/255),a=Math.min(1-i,1-r,1-o);if(a===1)return new M(0,0,0,1,"cmyk");const c=(1-i-a)/(1-a),h=(1-r-a)/(1-a),l=(1-o-a)/(1-a);return new M(c,h,l,a,"cmyk")}hsl(){const{_a:t,_b:e,_c:n}=this.rgb(),[i,r,o]=[t,e,n].map(g=>g/255),a=Math.max(i,r,o),c=Math.min(i,r,o),h=(a+c)/2,l=a===c,u=a-c,f=l?0:h>.5?u/(2-a-c):u/(a+c),m=l?0:a===i?((r-o)/u+(r<o?6:0))/6:a===r?((o-i)/u+2)/6:a===o?((i-r)/u+4)/6:0;return new M(360*m,100*f,100*h,"hsl")}init(t=0,e=0,n=0,i=0,r="rgb"){if(t=t||0,this.space)for(const u in this.space)delete this[this.space[u]];if(typeof t=="number")r=typeof i=="string"?i:r,i=typeof i=="string"?0:i,Object.assign(this,{_a:t,_b:e,_c:n,_d:i,space:r});else if(t instanceof Array)this.space=e||(typeof t[3]=="string"?t[3]:t[4])||"rgb",Object.assign(this,{_a:t[0],_b:t[1],_c:t[2],_d:t[3]||0});else if(t instanceof Object){const u=lo(t,e);Object.assign(this,u)}else if(typeof t=="string")if(Ms.test(t)){const u=t.replace(Gr,""),[f,m,d]=Ur.exec(u).slice(1,4).map(g=>parseInt(g));Object.assign(this,{_a:f,_b:m,_c:d,_d:0,space:"rgb"})}else if(Cs.test(t)){const u=g=>parseInt(g,16),[,f,m,d]=Lr.exec(co(t)).map(u);Object.assign(this,{_a:f,_b:m,_c:d,_d:0,space:"rgb"})}else throw Error("Unsupported string format, can't construct Color");const{_a:o,_b:a,_c:c,_d:h}=this,l=this.space==="rgb"?{r:o,g:a,b:c}:this.space==="xyz"?{x:o,y:a,z:c}:this.space==="hsl"?{h:o,s:a,l:c}:this.space==="lab"?{l:o,a,b:c}:this.space==="lch"?{l:o,c:a,h:c}:this.space==="cmyk"?{c:o,m:a,y:c,k:h}:{};Object.assign(this,l)}lab(){const{x:t,y:e,z:n}=this.xyz(),i=116*e-16,r=500*(t-e),o=200*(e-n);return new M(i,r,o,"lab")}lch(){const{l:t,a:e,b:n}=this.lab(),i=Math.sqrt(e**2+n**2);let r=180*Math.atan2(n,e)/Math.PI;return r<0&&(r*=-1,r=360-r),new M(t,i,r,"lch")}rgb(){if(this.space==="rgb")return this;if(uo(this.space)){let{x:t,y:e,z:n}=this;if(this.space==="lab"||this.space==="lch"){let{l:m,a:d,b:g}=this;if(this.space==="lch"){const{c:ot,h:mt}=this,Ft=Math.PI/180;d=ot*Math.cos(Ft*mt),g=ot*Math.sin(Ft*mt)}const _=(m+16)/116,S=d/500+_,D=_-g/200,R=16/116,q=.008856,L=7.787;t=.95047*(S**3>q?S**3:(S-R)/L),e=1*(_**3>q?_**3:(_-R)/L),n=1.08883*(D**3>q?D**3:(D-R)/L)}const i=t*3.2406+e*-1.5372+n*-.4986,r=t*-.9689+e*1.8758+n*.0415,o=t*.0557+e*-.204+n*1.057,a=Math.pow,c=.0031308,h=i>c?1.055*a(i,1/2.4)-.055:12.92*i,l=r>c?1.055*a(r,1/2.4)-.055:12.92*r,u=o>c?1.055*a(o,1/2.4)-.055:12.92*o;return new M(255*h,255*l,255*u)}else if(this.space==="hsl"){let{h:t,s:e,l:n}=this;if(t/=360,e/=100,n/=100,e===0)return n*=255,new M(n,n,n);const i=n<.5?n*(1+e):n+e-n*e,r=2*n-i,o=255*pn(r,i,t+1/3),a=255*pn(r,i,t),c=255*pn(r,i,t-1/3);return new M(o,a,c)}else if(this.space==="cmyk"){const{c:t,m:e,y:n,k:i}=this,r=255*(1-Math.min(1,t*(1-i)+i)),o=255*(1-Math.min(1,e*(1-i)+i)),a=255*(1-Math.min(1,n*(1-i)+i));return new M(r,o,a)}else return this}toArray(){const{_a:t,_b:e,_c:n,_d:i,space:r}=this;return[t,e,n,i,r]}toHex(){const[t,e,n]=this._clamped().map(ho);return`#${t}${e}${n}`}toRgb(){const[t,e,n]=this._clamped();return`rgb(${t},${e},${n})`}toString(){return this.toHex()}xyz(){const{_a:t,_b:e,_c:n}=this.rgb(),[i,r,o]=[t,e,n].map(S=>S/255),a=i>.04045?Math.pow((i+.055)/1.055,2.4):i/12.92,c=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92,h=o>.04045?Math.pow((o+.055)/1.055,2.4):o/12.92,l=(a*.4124+c*.3576+h*.1805)/.95047,u=(a*.2126+c*.7152+h*.0722)/1,f=(a*.0193+c*.1192+h*.9505)/1.08883,m=l>.008856?Math.pow(l,1/3):7.787*l+16/116,d=u>.008856?Math.pow(u,1/3):7.787*u+16/116,g=f>.008856?Math.pow(f,1/3):7.787*f+16/116;return new M(m,d,g,"xyz")}_clamped(){const{_a:t,_b:e,_c:n}=this.rgb(),{max:i,min:r,round:o}=Math,a=c=>i(0,r(o(c),255));return[t,e,n].map(a)}}class W{constructor(...t){this.init(...t)}clone(){return new W(this)}init(t,e){const n={x:0,y:0},i=Array.isArray(t)?{x:t[0],y:t[1]}:typeof t=="object"?{x:t.x,y:t.y}:{x:t,y:e};return this.x=i.x==null?n.x:i.x,this.y=i.y==null?n.y:i.y,this}toArray(){return[this.x,this.y]}transform(t){return this.clone().transformO(t)}transformO(t){x.isMatrixLike(t)||(t=new x(t));const{x:e,y:n}=this;return this.x=t.a*e+t.c*n+t.e,this.y=t.b*e+t.d*n+t.f,this}}function fo(s,t){return new W(s,t).transformO(this.screenCTM().inverseO())}function Gt(s,t,e){return Math.abs(t-s)<1e-6}class x{constructor(...t){this.init(...t)}static formatTransforms(t){const e=t.flip==="both"||t.flip===!0,n=t.flip&&(e||t.flip==="x")?-1:1,i=t.flip&&(e||t.flip==="y")?-1:1,r=t.skew&&t.skew.length?t.skew[0]:isFinite(t.skew)?t.skew:isFinite(t.skewX)?t.skewX:0,o=t.skew&&t.skew.length?t.skew[1]:isFinite(t.skew)?t.skew:isFinite(t.skewY)?t.skewY:0,a=t.scale&&t.scale.length?t.scale[0]*n:isFinite(t.scale)?t.scale*n:isFinite(t.scaleX)?t.scaleX*n:n,c=t.scale&&t.scale.length?t.scale[1]*i:isFinite(t.scale)?t.scale*i:isFinite(t.scaleY)?t.scaleY*i:i,h=t.shear||0,l=t.rotate||t.theta||0,u=new W(t.origin||t.around||t.ox||t.originX,t.oy||t.originY),f=u.x,m=u.y,d=new W(t.position||t.px||t.positionX||NaN,t.py||t.positionY||NaN),g=d.x,_=d.y,S=new W(t.translate||t.tx||t.translateX,t.ty||t.translateY),D=S.x,R=S.y,q=new W(t.relative||t.rx||t.relativeX,t.ry||t.relativeY),L=q.x,ot=q.y;return{scaleX:a,scaleY:c,skewX:r,skewY:o,shear:h,theta:l,rx:L,ry:ot,tx:D,ty:R,ox:f,oy:m,px:g,py:_}}static fromArray(t){return{a:t[0],b:t[1],c:t[2],d:t[3],e:t[4],f:t[5]}}static isMatrixLike(t){return t.a!=null||t.b!=null||t.c!=null||t.d!=null||t.e!=null||t.f!=null}static matrixMultiply(t,e,n){const i=t.a*e.a+t.c*e.b,r=t.b*e.a+t.d*e.b,o=t.a*e.c+t.c*e.d,a=t.b*e.c+t.d*e.d,c=t.e+t.a*e.e+t.c*e.f,h=t.f+t.b*e.e+t.d*e.f;return n.a=i,n.b=r,n.c=o,n.d=a,n.e=c,n.f=h,n}around(t,e,n){return this.clone().aroundO(t,e,n)}aroundO(t,e,n){const i=t||0,r=e||0;return this.translateO(-i,-r).lmultiplyO(n).translateO(i,r)}clone(){return new x(this)}decompose(t=0,e=0){const n=this.a,i=this.b,r=this.c,o=this.d,a=this.e,c=this.f,h=n*o-i*r,l=h>0?1:-1,u=l*Math.sqrt(n*n+i*i),f=Math.atan2(l*i,l*n),m=180/Math.PI*f,d=Math.cos(f),g=Math.sin(f),_=(n*r+i*o)/h,S=r*u/(_*n-i)||o*u/(_*i+n),D=a-t+t*d*u+e*(_*d*u-g*S),R=c-e+t*g*u+e*(_*g*u+d*S);return{scaleX:u,scaleY:S,shear:_,rotate:m,translateX:D,translateY:R,originX:t,originY:e,a:this.a,b:this.b,c:this.c,d:this.d,e:this.e,f:this.f}}equals(t){if(t===this)return!0;const e=new x(t);return Gt(this.a,e.a)&&Gt(this.b,e.b)&&Gt(this.c,e.c)&&Gt(this.d,e.d)&&Gt(this.e,e.e)&&Gt(this.f,e.f)}flip(t,e){return this.clone().flipO(t,e)}flipO(t,e){return t==="x"?this.scaleO(-1,1,e,0):t==="y"?this.scaleO(1,-1,0,e):this.scaleO(-1,-1,t,e||t)}init(t){const e=x.fromArray([1,0,0,1,0,0]);return t=t instanceof pt?t.matrixify():typeof t=="string"?x.fromArray(t.split(bt).map(parseFloat)):Array.isArray(t)?x.fromArray(t):typeof t=="object"&&x.isMatrixLike(t)?t:typeof t=="object"?new x().transform(t):arguments.length===6?x.fromArray([].slice.call(arguments)):e,this.a=t.a!=null?t.a:e.a,this.b=t.b!=null?t.b:e.b,this.c=t.c!=null?t.c:e.c,this.d=t.d!=null?t.d:e.d,this.e=t.e!=null?t.e:e.e,this.f=t.f!=null?t.f:e.f,this}inverse(){return this.clone().inverseO()}inverseO(){const t=this.a,e=this.b,n=this.c,i=this.d,r=this.e,o=this.f,a=t*i-e*n;if(!a)throw new Error("Cannot invert "+this);const c=i/a,h=-e/a,l=-n/a,u=t/a,f=-(c*r+l*o),m=-(h*r+u*o);return this.a=c,this.b=h,this.c=l,this.d=u,this.e=f,this.f=m,this}lmultiply(t){return this.clone().lmultiplyO(t)}lmultiplyO(t){const e=this,n=t instanceof x?t:new x(t);return x.matrixMultiply(n,e,this)}multiply(t){return this.clone().multiplyO(t)}multiplyO(t){const e=this,n=t instanceof x?t:new x(t);return x.matrixMultiply(e,n,this)}rotate(t,e,n){return this.clone().rotateO(t,e,n)}rotateO(t,e=0,n=0){t=un(t);const i=Math.cos(t),r=Math.sin(t),{a:o,b:a,c,d:h,e:l,f:u}=this;return this.a=o*i-a*r,this.b=a*i+o*r,this.c=c*i-h*r,this.d=h*i+c*r,this.e=l*i-u*r+n*r-e*i+e,this.f=u*i+l*r-e*r-n*i+n,this}scale(){return this.clone().scaleO(...arguments)}scaleO(t,e=t,n=0,i=0){arguments.length===3&&(i=n,n=e,e=t);const{a:r,b:o,c:a,d:c,e:h,f:l}=this;return this.a=r*t,this.b=o*e,this.c=a*t,this.d=c*e,this.e=h*t-n*t+n,this.f=l*e-i*e+i,this}shear(t,e,n){return this.clone().shearO(t,e,n)}shearO(t,e=0,n=0){const{a:i,b:r,c:o,d:a,e:c,f:h}=this;return this.a=i+r*t,this.c=o+a*t,this.e=c+h*t-n*t,this}skew(){return this.clone().skewO(...arguments)}skewO(t,e=t,n=0,i=0){arguments.length===3&&(i=n,n=e,e=t),t=un(t),e=un(e);const r=Math.tan(t),o=Math.tan(e),{a,b:c,c:h,d:l,e:u,f}=this;return this.a=a+c*r,this.b=c+a*o,this.c=h+l*r,this.d=l+h*o,this.e=u+f*r-i*r,this.f=f+u*o-n*o,this}skewX(t,e,n){return this.skew(t,0,e,n)}skewY(t,e,n){return this.skew(0,t,e,n)}toArray(){return[this.a,this.b,this.c,this.d,this.e,this.f]}toString(){return"matrix("+this.a+","+this.b+","+this.c+","+this.d+","+this.e+","+this.f+")"}transform(t){if(x.isMatrixLike(t))return new x(t).multiplyO(this);const e=x.formatTransforms(t),n=this,{x:i,y:r}=new W(e.ox,e.oy).transform(n),o=new x().translateO(e.rx,e.ry).lmultiplyO(n).translateO(-i,-r).scaleO(e.scaleX,e.scaleY).skewO(e.skewX,e.skewY).shearO(e.shear).rotateO(e.theta).translateO(i,r);if(isFinite(e.px)||isFinite(e.py)){const a=new W(i,r).transform(o),c=isFinite(e.px)?e.px-a.x:0,h=isFinite(e.py)?e.py-a.y:0;o.translateO(c,h)}return o.translateO(e.tx,e.ty),o}translate(t,e){return this.clone().translateO(t,e)}translateO(t,e){return this.e+=t||0,this.f+=e||0,this}valueOf(){return{a:this.a,b:this.b,c:this.c,d:this.d,e:this.e,f:this.f}}}function po(){return new x(this.node.getCTM())}function mo(){try{if(typeof this.isRoot=="function"&&!this.isRoot()){const s=this.rect(1,1),t=s.node.getScreenCTM();return s.remove(),new x(t)}return new x(this.node.getScreenCTM())}catch{return console.warn(`Cannot get CTM from SVG node ${this.node.nodeName}. Is the element rendered?`),new x}}N(x,"Matrix");function vt(){if(!vt.nodes){const s=X().size(2,0);s.node.style.cssText=["opacity: 0","position: absolute","left: -100%","top: -100%","overflow: hidden"].join(";"),s.attr("focusable","false"),s.attr("aria-hidden","true");const t=s.path().node;vt.nodes={svg:s,path:t}}if(!vt.nodes.svg.node.parentNode){const s=I.document.body||I.document.documentElement;vt.nodes.svg.addTo(s)}return vt.nodes}function ai(s){return!s.width&&!s.height&&!s.x&&!s.y}function go(s){return s===I.document||(I.document.documentElement.contains||function(t){for(;t.parentNode;)t=t.parentNode;return t===I.document}).call(I.document.documentElement,s)}class K{constructor(...t){this.init(...t)}addOffset(){return this.x+=I.window.pageXOffset,this.y+=I.window.pageYOffset,new K(this)}init(t){const e=[0,0,0,0];return t=typeof t=="string"?t.split(bt).map(parseFloat):Array.isArray(t)?t:typeof t=="object"?[t.left!=null?t.left:t.x,t.top!=null?t.top:t.y,t.width,t.height]:arguments.length===4?[].slice.call(arguments):e,this.x=t[0]||0,this.y=t[1]||0,this.width=this.w=t[2]||0,this.height=this.h=t[3]||0,this.x2=this.x+this.w,this.y2=this.y+this.h,this.cx=this.x+this.w/2,this.cy=this.y+this.h/2,this}isNulled(){return ai(this)}merge(t){const e=Math.min(this.x,t.x),n=Math.min(this.y,t.y),i=Math.max(this.x+this.width,t.x+t.width)-e,r=Math.max(this.y+this.height,t.y+t.height)-n;return new K(e,n,i,r)}toArray(){return[this.x,this.y,this.width,this.height]}toString(){return this.x+" "+this.y+" "+this.width+" "+this.height}transform(t){t instanceof x||(t=new x(t));let e=1/0,n=-1/0,i=1/0,r=-1/0;return[new W(this.x,this.y),new W(this.x2,this.y),new W(this.x,this.y2),new W(this.x2,this.y2)].forEach(function(a){a=a.transform(t),e=Math.min(e,a.x),n=Math.max(n,a.x),i=Math.min(i,a.y),r=Math.max(r,a.y)}),new K(e,i,n-e,r-i)}}function ci(s,t,e){let n;try{if(n=t(s.node),ai(n)&&!go(s.node))throw new Error("Element not in the dom")}catch{n=e(s)}return n}function yo(){const e=ci(this,i=>i.getBBox(),i=>{try{const r=i.clone().addTo(vt().svg).show(),o=r.node.getBBox();return r.remove(),o}catch(r){throw new Error(`Getting bbox of element "${i.node.nodeName}" is not possible: ${r.toString()}`)}});return new K(e)}function wo(s){const n=ci(this,r=>r.getBoundingClientRect(),r=>{throw new Error(`Getting rbox of element "${r.node.nodeName}" is not possible`)}),i=new K(n);return s?i.transform(s.screenCTM().inverseO()):i.addOffset()}function _o(s,t){const e=this.bbox();return s>e.x&&t>e.y&&s<e.x+e.width&&t<e.y+e.height}k({viewbox:{viewbox(s,t,e,n){return s==null?new K(this.attr("viewBox")):this.attr("viewBox",new K(s,t,e,n))},zoom(s,t){let{width:e,height:n}=this.attr(["width","height"]);if((!e&&!n||typeof e=="string"||typeof n=="string")&&(e=this.node.clientWidth,n=this.node.clientHeight),!e||!n)throw new Error("Impossible to get absolute width and height. Please provide an absolute width and height attribute on the zooming element");const i=this.viewbox(),r=e/i.width,o=n/i.height,a=Math.min(r,o);if(s==null)return a;let c=a/s;c===1/0&&(c=Number.MAX_SAFE_INTEGER/100),t=t||new W(e/2/r+i.x,n/2/o+i.y);const h=new K(i).transform(new x({scale:c,origin:t}));return this.viewbox(h)}}});N(K,"Box");class Pt extends Array{constructor(t=[],...e){if(super(t,...e),typeof t=="number")return this;this.length=0,this.push(...t)}}T([Pt],{each(s,...t){return typeof s=="function"?this.map((e,n,i)=>s.call(e,e,n,i)):this.map(e=>e[s](...t))},toArray(){return Array.prototype.concat.apply([],this)}});const bo=["toArray","constructor","each"];Pt.extend=function(s){s=s.reduce((t,e)=>(bo.includes(e)||e[0]==="_"||(e in Array.prototype&&(t["$"+e]=Array.prototype[e]),t[e]=function(...n){return this.each(e,...n)}),t),{}),T([Pt],s)};function de(s,t){return new Pt(ts((t||I.document).querySelectorAll(s),function(e){return st(e)}))}function vo(s){return de(s,this.node)}function Ao(s){return st(this.node.querySelector(s))}let So=0;const hi={};function li(s){let t=s.getEventHolder();return t===I.window&&(t=hi),t.events||(t.events={}),t.events}function rs(s){return s.getEventTarget()}function xo(s){let t=s.getEventHolder();t===I.window&&(t=hi),t.events&&(t.events={})}function kn(s,t,e,n,i){const r=e.bind(n||s),o=X(s),a=li(o),c=rs(o);t=Array.isArray(t)?t:t.split(bt),e._svgjsListenerId||(e._svgjsListenerId=++So),t.forEach(function(h){const l=h.split(".")[0],u=h.split(".")[1]||"*";a[l]=a[l]||{},a[l][u]=a[l][u]||{},a[l][u][e._svgjsListenerId]=r,c.addEventListener(l,r,i||!1)})}function Xt(s,t,e,n){const i=X(s),r=li(i),o=rs(i);typeof e=="function"&&(e=e._svgjsListenerId,!e)||(t=Array.isArray(t)?t:(t||"").split(bt),t.forEach(function(a){const c=a&&a.split(".")[0],h=a&&a.split(".")[1];let l,u;if(e)r[c]&&r[c][h||"*"]&&(o.removeEventListener(c,r[c][h||"*"][e],n||!1),delete r[c][h||"*"][e]);else if(c&&h){if(r[c]&&r[c][h]){for(u in r[c][h])Xt(o,[c,h].join("."),u);delete r[c][h]}}else if(h)for(a in r)for(l in r[a])h===l&&Xt(o,[a,h].join("."));else if(c){if(r[c]){for(l in r[c])Xt(o,[c,l].join("."));delete r[c]}}else{for(a in r)Xt(o,a);xo(i)}}))}function Eo(s,t,e,n){const i=rs(s);return t instanceof I.window.Event||(t=new I.window.CustomEvent(t,{detail:e,cancelable:!0,...n})),i.dispatchEvent(t),t}class De extends ns{addEventListener(){}dispatch(t,e,n){return Eo(this,t,e,n)}dispatchEvent(t){const e=this.getEventHolder().events;if(!e)return!0;const n=e[t.type];for(const i in n)for(const r in n[i])n[i][r](t);return!t.defaultPrevented}fire(t,e,n){return this.dispatch(t,e,n),this}getEventHolder(){return this}getEventTarget(){return this}off(t,e,n){return Xt(this,t,e,n),this}on(t,e,n,i){return kn(this,t,e,n,i),this}removeEventListener(){}}N(De,"EventTarget");function $s(){}const ye={duration:400,ease:">",delay:0},ko={"fill-opacity":1,"stroke-opacity":1,"stroke-width":0,"stroke-linejoin":"miter","stroke-linecap":"butt",fill:"#000000",stroke:"#000000",opacity:1,x:0,y:0,cx:0,cy:0,width:0,height:0,r:0,rx:0,ry:0,offset:0,"stop-opacity":1,"stop-color":"#000000","text-anchor":"start"};class ne extends Array{constructor(...t){super(...t),this.init(...t)}clone(){return new this.constructor(this)}init(t){return typeof t=="number"?this:(this.length=0,this.push(...this.parse(t)),this)}parse(t=[]){return t instanceof Array?t:t.trim().split(bt).map(parseFloat)}toArray(){return Array.prototype.concat.apply([],this)}toSet(){return new Set(this)}toString(){return this.join(" ")}valueOf(){const t=[];return t.push(...this),t}}class E{constructor(...t){this.init(...t)}convert(t){return new E(this.value,t)}divide(t){return t=new E(t),new E(this/t,this.unit||t.unit)}init(t,e){return e=Array.isArray(t)?t[1]:e,t=Array.isArray(t)?t[0]:t,this.value=0,this.unit=e||"",typeof t=="number"?this.value=isNaN(t)?0:isFinite(t)?t:t<0?-34e37:34e37:typeof t=="string"?(e=t.match(oi),e&&(this.value=parseFloat(e[1]),e[5]==="%"?this.value/=100:e[5]==="s"&&(this.value*=1e3),this.unit=e[5])):t instanceof E&&(this.value=t.valueOf(),this.unit=t.unit),this}minus(t){return t=new E(t),new E(this-t,this.unit||t.unit)}plus(t){return t=new E(t),new E(this+t,this.unit||t.unit)}times(t){return t=new E(t),new E(this*t,this.unit||t.unit)}toArray(){return[this.value,this.unit]}toJSON(){return this.toString()}toString(){return(this.unit==="%"?~~(this.value*1e8)/1e6:this.unit==="s"?this.value/1e3:this.value)+this.unit}valueOf(){return this.value}}const To=new Set(["fill","stroke","color","bgcolor","stop-color","flood-color","lighting-color"]),ui=[];function Oo(s){ui.push(s)}function Io(s,t,e){if(s==null){s={},t=this.node.attributes;for(const n of t)s[n.nodeName]=Hs.test(n.nodeValue)?parseFloat(n.nodeValue):n.nodeValue;return s}else{if(s instanceof Array)return s.reduce((n,i)=>(n[i]=this.attr(i),n),{});if(typeof s=="object"&&s.constructor===Object)for(t in s)this.attr(t,s[t]);else if(t===null)this.node.removeAttribute(s);else{if(t==null)return t=this.node.getAttribute(s),t==null?ko[s]:Hs.test(t)?parseFloat(t):t;t=ui.reduce((n,i)=>i(s,n,this),t),typeof t=="number"?t=new E(t):To.has(s)&&M.isColor(t)?t=new M(t):t.constructor===Array&&(t=new ne(t)),s==="leading"?this.leading&&this.leading(t):typeof e=="string"?this.node.setAttributeNS(e,s,t.toString()):this.node.setAttribute(s,t.toString()),this.rebuild&&(s==="font-size"||s==="x")&&this.rebuild()}}return this}class Tt extends De{constructor(t,e){super(),this.node=t,this.type=t.nodeName,e&&t!==e&&this.attr(e)}add(t,e){return t=X(t),t.removeNamespace&&this.node instanceof I.window.SVGElement&&t.removeNamespace(),e==null?this.node.appendChild(t.node):t.node!==this.node.childNodes[e]&&this.node.insertBefore(t.node,this.node.childNodes[e]),this}addTo(t,e){return X(t).put(this,e)}children(){return new Pt(ts(this.node.children,function(t){return st(t)}))}clear(){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return this}clone(t=!0,e=!0){this.writeDataToDom();let n=this.node.cloneNode(t);return e&&(n=ri(n)),new this.constructor(n)}each(t,e){const n=this.children();let i,r;for(i=0,r=n.length;i<r;i++)t.apply(n[i],[i,n]),e&&n[i].each(t,e);return this}element(t,e){return this.put(new Tt(Ae(t),e))}first(){return st(this.node.firstChild)}get(t){return st(this.node.childNodes[t])}getEventHolder(){return this.node}getEventTarget(){return this.node}has(t){return this.index(t)>=0}html(t,e){return this.xml(t,e,Tr)}id(t){return typeof t>"u"&&!this.node.id&&(this.node.id=ii(this.type)),this.attr("id",t)}index(t){return[].slice.call(this.node.childNodes).indexOf(t.node)}last(){return st(this.node.lastChild)}matches(t){const e=this.node,n=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector||null;return n&&n.call(e,t)}parent(t){let e=this;if(!e.node.parentNode)return null;if(e=st(e.node.parentNode),!t)return e;do if(typeof t=="string"?e.matches(t):e instanceof t)return e;while(e=st(e.node.parentNode));return e}put(t,e){return t=X(t),this.add(t,e),t}putIn(t,e){return X(t).add(this,e)}remove(){return this.parent()&&this.parent().removeElement(this),this}removeElement(t){return this.node.removeChild(t.node),this}replace(t){return t=X(t),this.node.parentNode&&this.node.parentNode.replaceChild(t.node,this.node),t}round(t=2,e=null){const n=10**t,i=this.attr(e);for(const r in i)typeof i[r]=="number"&&(i[r]=Math.round(i[r]*n)/n);return this.attr(i),this}svg(t,e){return this.xml(t,e,es)}toString(){return this.id()}words(t){return this.node.textContent=t,this}wrap(t){const e=this.parent();if(!e)return this.addTo(t);const n=e.index(this);return e.put(t,n).put(this)}writeDataToDom(){return this.each(function(){this.writeDataToDom()}),this}xml(t,e,n){if(typeof t=="boolean"&&(n=e,e=t,t=null),t==null||typeof t=="function"){e=e??!0,this.writeDataToDom();let a=this;if(t!=null){if(a=st(a.node.cloneNode(!0)),e){const c=t(a);if(a=c||a,c===!1)return""}a.each(function(){const c=t(this),h=c||this;c===!1?this.remove():c&&this!==h&&this.replace(h)},!0)}return e?a.node.outerHTML:a.node.innerHTML}e=e??!1;const i=Ae("wrapper",n),r=I.document.createDocumentFragment();i.innerHTML=t;for(let a=i.children.length;a--;)r.appendChild(i.firstElementChild);const o=this.parent();return e?this.replace(r)&&o:this.add(r)}}T(Tt,{attr:Io,find:vo,findOne:Ao});N(Tt,"Dom");class pt extends Tt{constructor(t,e){super(t,e),this.dom={},this.node.instance=this,(t.hasAttribute("data-svgjs")||t.hasAttribute("svgjs:data"))&&this.setData(JSON.parse(t.getAttribute("data-svgjs"))??JSON.parse(t.getAttribute("svgjs:data"))??{})}center(t,e){return this.cx(t).cy(e)}cx(t){return t==null?this.x()+this.width()/2:this.x(t-this.width()/2)}cy(t){return t==null?this.y()+this.height()/2:this.y(t-this.height()/2)}defs(){const t=this.root();return t&&t.defs()}dmove(t,e){return this.dx(t).dy(e)}dx(t=0){return this.x(new E(t).plus(this.x()))}dy(t=0){return this.y(new E(t).plus(this.y()))}getEventHolder(){return this}height(t){return this.attr("height",t)}move(t,e){return this.x(t).y(e)}parents(t=this.root()){const e=typeof t=="string";e||(t=X(t));const n=new Pt;let i=this;for(;(i=i.parent())&&i.node!==I.document&&i.nodeName!=="#document-fragment"&&(n.push(i),!(!e&&i.node===t.node||e&&i.matches(t)));)if(i.node===this.root().node)return null;return n}reference(t){if(t=this.attr(t),!t)return null;const e=(t+"").match(Fr);return e?X(e[1]):null}root(){const t=this.parent(Ir(ss));return t&&t.root()}setData(t){return this.dom=t,this}size(t,e){const n=fe(this,t,e);return this.width(new E(n.width)).height(new E(n.height))}width(t){return this.attr("width",t)}writeDataToDom(){return si(this,this.dom),super.writeDataToDom()}x(t){return this.attr("x",t)}y(t){return this.attr("y",t)}}T(pt,{bbox:yo,rbox:wo,inside:_o,point:fo,ctm:po,screenCTM:mo});N(pt,"Element");const me={stroke:["color","width","opacity","linecap","linejoin","miterlimit","dasharray","dashoffset"],fill:["color","opacity","rule"],prefix:function(s,t){return t==="color"?s:s+"-"+t}};["fill","stroke"].forEach(function(s){const t={};let e;t[s]=function(n){if(typeof n>"u")return this.attr(s);if(typeof n=="string"||n instanceof M||M.isRgb(n)||n instanceof pt)this.attr(s,n);else for(e=me[s].length-1;e>=0;e--)n[me[s][e]]!=null&&this.attr(me.prefix(s,me[s][e]),n[me[s][e]]);return this},k(["Element","Runner"],t)});k(["Element","Runner"],{matrix:function(s,t,e,n,i,r){return s==null?new x(this):this.attr("transform",new x(s,t,e,n,i,r))},rotate:function(s,t,e){return this.transform({rotate:s,ox:t,oy:e},!0)},skew:function(s,t,e,n){return arguments.length===1||arguments.length===3?this.transform({skew:s,ox:t,oy:e},!0):this.transform({skew:[s,t],ox:e,oy:n},!0)},shear:function(s,t,e){return this.transform({shear:s,ox:t,oy:e},!0)},scale:function(s,t,e,n){return arguments.length===1||arguments.length===3?this.transform({scale:s,ox:t,oy:e},!0):this.transform({scale:[s,t],ox:e,oy:n},!0)},translate:function(s,t){return this.transform({translate:[s,t]},!0)},relative:function(s,t){return this.transform({relative:[s,t]},!0)},flip:function(s="both",t="center"){return"xybothtrue".indexOf(s)===-1&&(t=s,s="both"),this.transform({flip:s,origin:t},!0)},opacity:function(s){return this.attr("opacity",s)}});k("radius",{radius:function(s,t=s){return(this._element||this).type==="radialGradient"?this.attr("r",new E(s)):this.rx(s).ry(t)}});k("Path",{length:function(){return this.node.getTotalLength()},pointAt:function(s){return new W(this.node.getPointAtLength(s))}});k(["Element","Runner"],{font:function(s,t){if(typeof s=="object"){for(t in s)this.font(t,s[t]);return this}return s==="leading"?this.leading(t):s==="anchor"?this.attr("text-anchor",t):s==="size"||s==="family"||s==="weight"||s==="stretch"||s==="variant"||s==="style"?this.attr("font-"+s,t):this.attr(s,t)}});const No=["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","touchstart","touchmove","touchleave","touchend","touchcancel","contextmenu","wheel","pointerdown","pointermove","pointerup","pointerleave","pointercancel"].reduce(function(s,t){const e=function(n){return n===null?this.off(t):this.on(t,n),this};return s[t]=e,s},{});k("Element",No);function Do(){return this.attr("transform",null)}function Co(){return(this.attr("transform")||"").split(qr).slice(0,-1).map(function(t){const e=t.trim().split("(");return[e[0],e[1].split(bt).map(function(n){return parseFloat(n)})]}).reverse().reduce(function(t,e){return e[0]==="matrix"?t.lmultiply(x.fromArray(e[1])):t[e[0]].apply(t,e[1])},new x)}function Mo(s,t){if(this===s)return this;if(En(this.node))return this.addTo(s,t);const e=this.screenCTM(),n=s.screenCTM().inverse();return this.addTo(s,t).untransform().transform(n.multiply(e)),this}function Ro(s){return this.toParent(this.root(),s)}function Ho(s,t){if(s==null||typeof s=="string"){const i=new x(this).decompose();return s==null?i:i[s]}x.isMatrixLike(s)||(s={...s,origin:xn(s,this)});const e=t===!0?this:t||!1,n=new x(e).transform(s);return this.attr("transform",n)}k("Element",{untransform:Do,matrixify:Co,toParent:Mo,toRoot:Ro,transform:Ho});class V extends pt{flatten(){return this.each(function(){if(this instanceof V)return this.flatten().ungroup()}),this}ungroup(t=this.parent(),e=t.index(this)){return e=e===-1?t.children().length:e,this.each(function(n,i){return i[i.length-n-1].toParent(t,e)}),this.remove()}}N(V,"Container");class os extends V{constructor(t,e=t){super($("defs",t),e)}flatten(){return this}ungroup(){return this}}N(os,"Defs");class nt extends pt{}N(nt,"Shape");function as(s){return this.attr("rx",s)}function cs(s){return this.attr("ry",s)}function fi(s){return s==null?this.cx()-this.rx():this.cx(s+this.rx())}function di(s){return s==null?this.cy()-this.ry():this.cy(s+this.ry())}function pi(s){return this.attr("cx",s)}function mi(s){return this.attr("cy",s)}function gi(s){return s==null?this.rx()*2:this.rx(new E(s).divide(2))}function yi(s){return s==null?this.ry()*2:this.ry(new E(s).divide(2))}const $o=Object.freeze(Object.defineProperty({__proto__:null,cx:pi,cy:mi,height:yi,rx:as,ry:cs,width:gi,x:fi,y:di},Symbol.toStringTag,{value:"Module"}));class sn extends nt{constructor(t,e=t){super($("ellipse",t),e)}size(t,e){const n=fe(this,t,e);return this.rx(new E(n.width).divide(2)).ry(new E(n.height).divide(2))}}T(sn,$o);k("Container",{ellipse:H(function(s=0,t=s){return this.put(new sn).size(s,t).move(0,0)})});N(sn,"Ellipse");class wi extends Tt{constructor(t=I.document.createDocumentFragment()){super(t)}xml(t,e,n){if(typeof t=="boolean"&&(n=e,e=t,t=null),t==null||typeof t=="function"){const i=new Tt(Ae("wrapper",n));return i.add(this.node.cloneNode(!0)),i.xml(!1,n)}return super.xml(t,!1,n)}}N(wi,"Fragment");function _i(s,t){return(this._element||this).type==="radialGradient"?this.attr({fx:new E(s),fy:new E(t)}):this.attr({x1:new E(s),y1:new E(t)})}function bi(s,t){return(this._element||this).type==="radialGradient"?this.attr({cx:new E(s),cy:new E(t)}):this.attr({x2:new E(s),y2:new E(t)})}const Bo=Object.freeze(Object.defineProperty({__proto__:null,from:_i,to:bi},Symbol.toStringTag,{value:"Module"}));class Ce extends V{constructor(t,e){super($(t+"Gradient",typeof t=="string"?null:t),e)}attr(t,e,n){return t==="transform"&&(t="gradientTransform"),super.attr(t,e,n)}bbox(){return new K}targets(){return de("svg [fill*="+this.id()+"]")}toString(){return this.url()}update(t){return this.clear(),typeof t=="function"&&t.call(this,this),this}url(){return"url(#"+this.id()+")"}}T(Ce,Bo);k({Container:{gradient(...s){return this.defs().gradient(...s)}},Defs:{gradient:H(function(s,t){return this.put(new Ce(s)).update(t)})}});N(Ce,"Gradient");class Se extends V{constructor(t,e=t){super($("pattern",t),e)}attr(t,e,n){return t==="transform"&&(t="patternTransform"),super.attr(t,e,n)}bbox(){return new K}targets(){return de("svg [fill*="+this.id()+"]")}toString(){return this.url()}update(t){return this.clear(),typeof t=="function"&&t.call(this,this),this}url(){return"url(#"+this.id()+")"}}k({Container:{pattern(...s){return this.defs().pattern(...s)}},Defs:{pattern:H(function(s,t,e){return this.put(new Se).update(e).attr({x:0,y:0,width:s,height:t,patternUnits:"userSpaceOnUse"})})}});N(Se,"Pattern");class Me extends nt{constructor(t,e=t){super($("image",t),e)}load(t,e){if(!t)return this;const n=new I.window.Image;return kn(n,"load",function(i){const r=this.parent(Se);this.width()===0&&this.height()===0&&this.size(n.width,n.height),r instanceof Se&&r.width()===0&&r.height()===0&&r.size(this.width(),this.height()),typeof e=="function"&&e.call(this,i)},this),kn(n,"load error",function(){Xt(n)}),this.attr("href",n.src=t,Ne)}}Oo(function(s,t,e){return(s==="fill"||s==="stroke")&&Zr.test(t)&&(t=e.root().defs().image(t)),t instanceof Me&&(t=e.root().defs().pattern(0,0,n=>{n.add(t)})),t});k({Container:{image:H(function(s,t){return this.put(new Me).size(0,0).load(s,t)})}});N(Me,"Image");class Ot extends ne{bbox(){let t=-1/0,e=-1/0,n=1/0,i=1/0;return this.forEach(function(r){t=Math.max(r[0],t),e=Math.max(r[1],e),n=Math.min(r[0],n),i=Math.min(r[1],i)}),new K(n,i,t-n,e-i)}move(t,e){const n=this.bbox();if(t-=n.x,e-=n.y,!isNaN(t)&&!isNaN(e))for(let i=this.length-1;i>=0;i--)this[i]=[this[i][0]+t,this[i][1]+e];return this}parse(t=[0,0]){const e=[];t instanceof Array?t=Array.prototype.concat.apply([],t):t=t.trim().split(bt).map(parseFloat),t.length%2!==0&&t.pop();for(let n=0,i=t.length;n<i;n=n+2)e.push([t[n],t[n+1]]);return e}size(t,e){let n;const i=this.bbox();for(n=this.length-1;n>=0;n--)i.width&&(this[n][0]=(this[n][0]-i.x)*t/i.width+i.x),i.height&&(this[n][1]=(this[n][1]-i.y)*e/i.height+i.y);return this}toLine(){return{x1:this[0][0],y1:this[0][1],x2:this[1][0],y2:this[1][1]}}toString(){const t=[];for(let e=0,n=this.length;e<n;e++)t.push(this[e].join(","));return t.join(" ")}transform(t){return this.clone().transformO(t)}transformO(t){x.isMatrixLike(t)||(t=new x(t));for(let e=this.length;e--;){const[n,i]=this[e];this[e][0]=t.a*n+t.c*i+t.e,this[e][1]=t.b*n+t.d*i+t.f}return this}}const Wo=Ot;function Po(s){return s==null?this.bbox().x:this.move(s,this.bbox().y)}function jo(s){return s==null?this.bbox().y:this.move(this.bbox().x,s)}function zo(s){const t=this.bbox();return s==null?t.width:this.size(s,t.height)}function Ko(s){const t=this.bbox();return s==null?t.height:this.size(t.width,s)}const hs=Object.freeze(Object.defineProperty({__proto__:null,MorphArray:Wo,height:Ko,width:zo,x:Po,y:jo},Symbol.toStringTag,{value:"Module"}));class xe extends nt{constructor(t,e=t){super($("line",t),e)}array(){return new Ot([[this.attr("x1"),this.attr("y1")],[this.attr("x2"),this.attr("y2")]])}move(t,e){return this.attr(this.array().move(t,e).toLine())}plot(t,e,n,i){return t==null?this.array():(typeof e<"u"?t={x1:t,y1:e,x2:n,y2:i}:t=new Ot(t).toLine(),this.attr(t))}size(t,e){const n=fe(this,t,e);return this.attr(this.array().size(n.width,n.height).toLine())}}T(xe,hs);k({Container:{line:H(function(...s){return xe.prototype.plot.apply(this.put(new xe),s[0]!=null?s:[0,0,0,0])})}});N(xe,"Line");class Ge extends V{constructor(t,e=t){super($("marker",t),e)}height(t){return this.attr("markerHeight",t)}orient(t){return this.attr("orient",t)}ref(t,e){return this.attr("refX",t).attr("refY",e)}toString(){return"url(#"+this.id()+")"}update(t){return this.clear(),typeof t=="function"&&t.call(this,this),this}width(t){return this.attr("markerWidth",t)}}k({Container:{marker(...s){return this.defs().marker(...s)}},Defs:{marker:H(function(s,t,e){return this.put(new Ge).size(s,t).ref(s/2,t/2).viewbox(0,0,s,t).attr("orient","auto").update(e)})},marker:{marker(s,t,e,n){let i=["marker"];return s!=="all"&&i.push(s),i=i.join("-"),s=arguments[1]instanceof Ge?arguments[1]:this.defs().marker(t,e,n),this.attr(i,s)}}});N(Ge,"Marker");function Jt(s,t){return function(e){return e==null?this[s]:(this[s]=e,t&&t.call(this),this)}}const Lo={"-":function(s){return s},"<>":function(s){return-Math.cos(s*Math.PI)/2+.5},">":function(s){return Math.sin(s*Math.PI/2)},"<":function(s){return-Math.cos(s*Math.PI/2)+1},bezier:function(s,t,e,n){return function(i){return i<0?s>0?t/s*i:e>0?n/e*i:0:i>1?e<1?(1-n)/(1-e)*i+(n-e)/(1-e):s<1?(1-t)/(1-s)*i+(t-s)/(1-s):1:3*i*(1-i)**2*t+3*i**2*(1-i)*n+i**3}},steps:function(s,t="end"){t=t.split("-").reverse()[0];let e=s;return t==="none"?--e:t==="both"&&++e,(n,i=!1)=>{let r=Math.floor(n*s);const o=n*r%1===0;return(t==="start"||t==="both")&&++r,i&&o&&--r,n>=0&&r<0&&(r=0),n<=1&&r>e&&(r=e),r/e}}};class ls{done(){return!1}}class Tn extends ls{constructor(t=ye.ease){super(),this.ease=Lo[t]||t}step(t,e,n){return typeof t!="number"?n<1?t:e:t+(e-t)*this.ease(n)}}let Ze=class extends ls{constructor(t){super(),this.stepper=t}done(t){return t.done}step(t,e,n,i){return this.stepper(t,e,n,i)}};function Bs(){const s=(this._duration||500)/1e3,t=this._overshoot||0,e=1e-10,n=Math.PI,i=Math.log(t/100+e),r=-i/Math.sqrt(n*n+i*i),o=3.9/(r*s);this.d=2*r*o,this.k=o*o}class Uo extends Ze{constructor(t=500,e=0){super(),this.duration(t).overshoot(e)}step(t,e,n,i){if(typeof t=="string")return t;if(i.done=n===1/0,n===1/0)return e;if(n===0)return t;n>100&&(n=16),n/=1e3;const r=i.velocity||0,o=-this.d*r-this.k*(t-e),a=t+r*n+o*n*n/2;return i.velocity=r+o*n,i.done=Math.abs(e-a)+Math.abs(r)<.002,i.done?e:a}}T(Uo,{duration:Jt("_duration",Bs),overshoot:Jt("_overshoot",Bs)});class Fo extends Ze{constructor(t=.1,e=.01,n=0,i=1e3){super(),this.p(t).i(e).d(n).windup(i)}step(t,e,n,i){if(typeof t=="string")return t;if(i.done=n===1/0,n===1/0)return e;if(n===0)return t;const r=e-t;let o=(i.integral||0)+r*n;const a=(r-(i.error||0))/n,c=this._windup;return c!==!1&&(o=Math.max(-c,Math.min(o,c))),i.error=r,i.integral=o,i.done=Math.abs(r)<.001,i.done?e:t+(this.P*r+this.I*o+this.D*a)}}T(Fo,{windup:Jt("_windup"),p:Jt("P"),i:Jt("I"),d:Jt("D")});const qo={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},On={M:function(s,t,e){return t.x=e.x=s[0],t.y=e.y=s[1],["M",t.x,t.y]},L:function(s,t){return t.x=s[0],t.y=s[1],["L",s[0],s[1]]},H:function(s,t){return t.x=s[0],["H",s[0]]},V:function(s,t){return t.y=s[0],["V",s[0]]},C:function(s,t){return t.x=s[4],t.y=s[5],["C",s[0],s[1],s[2],s[3],s[4],s[5]]},S:function(s,t){return t.x=s[2],t.y=s[3],["S",s[0],s[1],s[2],s[3]]},Q:function(s,t){return t.x=s[2],t.y=s[3],["Q",s[0],s[1],s[2],s[3]]},T:function(s,t){return t.x=s[0],t.y=s[1],["T",s[0],s[1]]},Z:function(s,t,e){return t.x=e.x,t.y=e.y,["Z"]},A:function(s,t){return t.x=s[5],t.y=s[6],["A",s[0],s[1],s[2],s[3],s[4],s[5],s[6]]}},mn="mlhvqtcsaz".split("");for(let s=0,t=mn.length;s<t;++s)On[mn[s]]=function(e){return function(n,i,r){if(e==="H")n[0]=n[0]+i.x;else if(e==="V")n[0]=n[0]+i.y;else if(e==="A")n[5]=n[5]+i.x,n[6]=n[6]+i.y;else for(let o=0,a=n.length;o<a;++o)n[o]=n[o]+(o%2?i.y:i.x);return On[e](n,i,r)}}(mn[s].toUpperCase());function Go(s){const t=s.segment[0];return On[t](s.segment.slice(1),s.p,s.p0)}function In(s){return s.segment.length&&s.segment.length-1===qo[s.segment[0].toUpperCase()]}function Zo(s,t){s.inNumber&&Mt(s,!1);const e=is.test(t);if(e)s.segment=[t];else{const n=s.lastCommand,i=n.toLowerCase(),r=n===i;s.segment=[i==="m"?r?"l":"L":n]}return s.inSegment=!0,s.lastCommand=s.segment[0],e}function Mt(s,t){if(!s.inNumber)throw new Error("Parser Error");s.number&&s.segment.push(parseFloat(s.number)),s.inNumber=t,s.number="",s.pointSeen=!1,s.hasExponent=!1,In(s)&&Nn(s)}function Nn(s){s.inSegment=!1,s.absolute&&(s.segment=Go(s)),s.segments.push(s.segment)}function Yo(s){if(!s.segment.length)return!1;const t=s.segment[0].toUpperCase()==="A",e=s.segment.length;return t&&(e===4||e===5)}function Xo(s){return s.lastToken.toUpperCase()==="E"}const Jo=new Set([" ",","," ",`
|
|
2
|
-
`,"\r","\f"]);function Vo(s,t=!0){let e=0,n="";const i={segment:[],inNumber:!1,number:"",lastToken:"",inSegment:!1,segments:[],pointSeen:!1,hasExponent:!1,absolute:t,p0:new W,p:new W};for(;i.lastToken=n,n=s.charAt(e++);)if(!(!i.inSegment&&Zo(i,n))){if(n==="."){if(i.pointSeen||i.hasExponent){Mt(i,!1),--e;continue}i.inNumber=!0,i.pointSeen=!0,i.number+=n;continue}if(!isNaN(parseInt(n))){if(i.number==="0"||Yo(i)){i.inNumber=!0,i.number=n,Mt(i,!0);continue}i.inNumber=!0,i.number+=n;continue}if(Jo.has(n)){i.inNumber&&Mt(i,!1);continue}if(n==="-"||n==="+"){if(i.inNumber&&!Xo(i)){Mt(i,!1),--e;continue}i.number+=n,i.inNumber=!0;continue}if(n.toUpperCase()==="E"){i.number+=n,i.hasExponent=!0;continue}if(is.test(n)){if(i.inNumber)Mt(i,!1);else if(In(i))Nn(i);else throw new Error("parser Error");--e}}return i.inNumber&&Mt(i,!1),i.inSegment&&In(i)&&Nn(i),i.segments}function Qo(s){let t="";for(let e=0,n=s.length;e<n;e++)t+=s[e][0],s[e][1]!=null&&(t+=s[e][1],s[e][2]!=null&&(t+=" ",t+=s[e][2],s[e][3]!=null&&(t+=" ",t+=s[e][3],t+=" ",t+=s[e][4],s[e][5]!=null&&(t+=" ",t+=s[e][5],t+=" ",t+=s[e][6],s[e][7]!=null&&(t+=" ",t+=s[e][7])))));return t+" "}class jt extends ne{bbox(){return vt().path.setAttribute("d",this.toString()),new K(vt.nodes.path.getBBox())}move(t,e){const n=this.bbox();if(t-=n.x,e-=n.y,!isNaN(t)&&!isNaN(e))for(let i,r=this.length-1;r>=0;r--)i=this[r][0],i==="M"||i==="L"||i==="T"?(this[r][1]+=t,this[r][2]+=e):i==="H"?this[r][1]+=t:i==="V"?this[r][1]+=e:i==="C"||i==="S"||i==="Q"?(this[r][1]+=t,this[r][2]+=e,this[r][3]+=t,this[r][4]+=e,i==="C"&&(this[r][5]+=t,this[r][6]+=e)):i==="A"&&(this[r][6]+=t,this[r][7]+=e);return this}parse(t="M0 0"){return Array.isArray(t)&&(t=Array.prototype.concat.apply([],t).toString()),Vo(t)}size(t,e){const n=this.bbox();let i,r;for(n.width=n.width===0?1:n.width,n.height=n.height===0?1:n.height,i=this.length-1;i>=0;i--)r=this[i][0],r==="M"||r==="L"||r==="T"?(this[i][1]=(this[i][1]-n.x)*t/n.width+n.x,this[i][2]=(this[i][2]-n.y)*e/n.height+n.y):r==="H"?this[i][1]=(this[i][1]-n.x)*t/n.width+n.x:r==="V"?this[i][1]=(this[i][1]-n.y)*e/n.height+n.y:r==="C"||r==="S"||r==="Q"?(this[i][1]=(this[i][1]-n.x)*t/n.width+n.x,this[i][2]=(this[i][2]-n.y)*e/n.height+n.y,this[i][3]=(this[i][3]-n.x)*t/n.width+n.x,this[i][4]=(this[i][4]-n.y)*e/n.height+n.y,r==="C"&&(this[i][5]=(this[i][5]-n.x)*t/n.width+n.x,this[i][6]=(this[i][6]-n.y)*e/n.height+n.y)):r==="A"&&(this[i][1]=this[i][1]*t/n.width,this[i][2]=this[i][2]*e/n.height,this[i][6]=(this[i][6]-n.x)*t/n.width+n.x,this[i][7]=(this[i][7]-n.y)*e/n.height+n.y);return this}toString(){return Qo(this)}}const vi=s=>{const t=typeof s;return t==="number"?E:t==="string"?M.isColor(s)?M:bt.test(s)?is.test(s)?jt:ne:oi.test(s)?E:Dn:us.indexOf(s.constructor)>-1?s.constructor:Array.isArray(s)?ne:t==="object"?Ee:Dn};class Rt{constructor(t){this._stepper=t||new Tn("-"),this._from=null,this._to=null,this._type=null,this._context=null,this._morphObj=null}at(t){return this._morphObj.morph(this._from,this._to,t,this._stepper,this._context)}done(){return this._context.map(this._stepper.done).reduce(function(e,n){return e&&n},!0)}from(t){return t==null?this._from:(this._from=this._set(t),this)}stepper(t){return t==null?this._stepper:(this._stepper=t,this)}to(t){return t==null?this._to:(this._to=this._set(t),this)}type(t){return t==null?this._type:(this._type=t,this)}_set(t){this._type||this.type(vi(t));let e=new this._type(t);return this._type===M&&(e=this._to?e[this._to[4]]():this._from?e[this._from[4]]():e),this._type===Ee&&(e=this._to?e.align(this._to):this._from?e.align(this._from):e),e=e.toConsumable(),this._morphObj=this._morphObj||new this._type,this._context=this._context||Array.apply(null,Array(e.length)).map(Object).map(function(n){return n.done=!0,n}),e}}class Dn{constructor(...t){this.init(...t)}init(t){return t=Array.isArray(t)?t[0]:t,this.value=t,this}toArray(){return[this.value]}valueOf(){return this.value}}class Re{constructor(...t){this.init(...t)}init(t){return Array.isArray(t)&&(t={scaleX:t[0],scaleY:t[1],shear:t[2],rotate:t[3],translateX:t[4],translateY:t[5],originX:t[6],originY:t[7]}),Object.assign(this,Re.defaults,t),this}toArray(){const t=this;return[t.scaleX,t.scaleY,t.shear,t.rotate,t.translateX,t.translateY,t.originX,t.originY]}}Re.defaults={scaleX:1,scaleY:1,shear:0,rotate:0,translateX:0,translateY:0,originX:0,originY:0};const ta=(s,t)=>s[0]<t[0]?-1:s[0]>t[0]?1:0;class Ee{constructor(...t){this.init(...t)}align(t){const e=this.values;for(let n=0,i=e.length;n<i;++n){if(e[n+1]===t[n+1]){if(e[n+1]===M&&t[n+7]!==e[n+7]){const a=t[n+7],c=new M(this.values.splice(n+3,5))[a]().toArray();this.values.splice(n+3,0,...c)}n+=e[n+2]+2;continue}if(!t[n+1])return this;const r=new t[n+1]().toArray(),o=e[n+2]+3;e.splice(n,o,t[n],t[n+1],t[n+2],...r),n+=e[n+2]+2}return this}init(t){if(this.values=[],Array.isArray(t)){this.values=t.slice();return}t=t||{};const e=[];for(const n in t){const i=vi(t[n]),r=new i(t[n]).toArray();e.push([n,i,r.length,...r])}return e.sort(ta),this.values=e.reduce((n,i)=>n.concat(i),[]),this}toArray(){return this.values}valueOf(){const t={},e=this.values;for(;e.length;){const n=e.shift(),i=e.shift(),r=e.shift(),o=e.splice(0,r);t[n]=new i(o)}return t}}const us=[Dn,Re,Ee];function ea(s=[]){us.push(...[].concat(s))}function na(){T(us,{to(s){return new Rt().type(this.constructor).from(this.toArray()).to(s)},fromArray(s){return this.init(s),this},toConsumable(){return this.toArray()},morph(s,t,e,n,i){const r=function(o,a){return n.step(o,t[a],e,i[a],i)};return this.fromArray(s.map(r))}})}class pe extends nt{constructor(t,e=t){super($("path",t),e)}array(){return this._array||(this._array=new jt(this.attr("d")))}clear(){return delete this._array,this}height(t){return t==null?this.bbox().height:this.size(this.bbox().width,t)}move(t,e){return this.attr("d",this.array().move(t,e))}plot(t){return t==null?this.array():this.clear().attr("d",typeof t=="string"?t:this._array=new jt(t))}size(t,e){const n=fe(this,t,e);return this.attr("d",this.array().size(n.width,n.height))}width(t){return t==null?this.bbox().width:this.size(t,this.bbox().height)}x(t){return t==null?this.bbox().x:this.move(t,this.bbox().y)}y(t){return t==null?this.bbox().y:this.move(this.bbox().x,t)}}pe.prototype.MorphArray=jt;k({Container:{path:H(function(s){return this.put(new pe).plot(s||new jt)})}});N(pe,"Path");function sa(){return this._array||(this._array=new Ot(this.attr("points")))}function ia(){return delete this._array,this}function ra(s,t){return this.attr("points",this.array().move(s,t))}function oa(s){return s==null?this.array():this.clear().attr("points",typeof s=="string"?s:this._array=new Ot(s))}function aa(s,t){const e=fe(this,s,t);return this.attr("points",this.array().size(e.width,e.height))}const Ai=Object.freeze(Object.defineProperty({__proto__:null,array:sa,clear:ia,move:ra,plot:oa,size:aa},Symbol.toStringTag,{value:"Module"}));class He extends nt{constructor(t,e=t){super($("polygon",t),e)}}k({Container:{polygon:H(function(s){return this.put(new He).plot(s||new Ot)})}});T(He,hs);T(He,Ai);N(He,"Polygon");class $e extends nt{constructor(t,e=t){super($("polyline",t),e)}}k({Container:{polyline:H(function(s){return this.put(new $e).plot(s||new Ot)})}});T($e,hs);T($e,Ai);N($e,"Polyline");class Be extends nt{constructor(t,e=t){super($("rect",t),e)}}T(Be,{rx:as,ry:cs});k({Container:{rect:H(function(s,t){return this.put(new Be).size(s,t)})}});N(Be,"Rect");class gn{constructor(){this._first=null,this._last=null}first(){return this._first&&this._first.value}last(){return this._last&&this._last.value}push(t){const e=typeof t.next<"u"?t:{value:t,next:null,prev:null};return this._last?(e.prev=this._last,this._last.next=e,this._last=e):(this._last=e,this._first=e),e}remove(t){t.prev&&(t.prev.next=t.next),t.next&&(t.next.prev=t.prev),t===this._last&&(this._last=t.prev),t===this._first&&(this._first=t.next),t.prev=null,t.next=null}shift(){const t=this._first;return t?(this._first=t.next,this._first&&(this._first.prev=null),this._last=this._first?this._last:null,t.value):null}}const C={nextDraw:null,frames:new gn,timeouts:new gn,immediates:new gn,timer:()=>I.window.performance||I.window.Date,transforms:[],frame(s){const t=C.frames.push({run:s});return C.nextDraw===null&&(C.nextDraw=I.window.requestAnimationFrame(C._draw)),t},timeout(s,t){t=t||0;const e=C.timer().now()+t,n=C.timeouts.push({run:s,time:e});return C.nextDraw===null&&(C.nextDraw=I.window.requestAnimationFrame(C._draw)),n},immediate(s){const t=C.immediates.push(s);return C.nextDraw===null&&(C.nextDraw=I.window.requestAnimationFrame(C._draw)),t},cancelFrame(s){s!=null&&C.frames.remove(s)},clearTimeout(s){s!=null&&C.timeouts.remove(s)},cancelImmediate(s){s!=null&&C.immediates.remove(s)},_draw(s){let t=null;const e=C.timeouts.last();for(;(t=C.timeouts.shift())&&(s>=t.time?t.run():C.timeouts.push(t),t!==e););let n=null;const i=C.frames.last();for(;n!==i&&(n=C.frames.shift());)n.run(s);let r=null;for(;r=C.immediates.shift();)r();C.nextDraw=C.timeouts.first()||C.frames.first()?I.window.requestAnimationFrame(C._draw):null}},ca=function(s){const t=s.start,e=s.runner.duration(),n=t+e;return{start:t,duration:e,end:n,runner:s.runner}},ha=function(){const s=I.window;return(s.performance||s.Date).now()};class Si extends De{constructor(t=ha){super(),this._timeSource=t,this.terminate()}active(){return!!this._nextFrame}finish(){return this.time(this.getEndTimeOfTimeline()+1),this.pause()}getEndTime(){const t=this.getLastRunnerInfo(),e=t?t.runner.duration():0;return(t?t.start:this._time)+e}getEndTimeOfTimeline(){const t=this._runners.map(e=>e.start+e.runner.duration());return Math.max(0,...t)}getLastRunnerInfo(){return this.getRunnerInfoById(this._lastRunnerId)}getRunnerInfoById(t){return this._runners[this._runnerIds.indexOf(t)]||null}pause(){return this._paused=!0,this._continue()}persist(t){return t==null?this._persist:(this._persist=t,this)}play(){return this._paused=!1,this.updateTime()._continue()}reverse(t){const e=this.speed();if(t==null)return this.speed(-e);const n=Math.abs(e);return this.speed(t?-n:n)}schedule(t,e,n){if(t==null)return this._runners.map(ca);let i=0;const r=this.getEndTime();if(e=e||0,n==null||n==="last"||n==="after")i=r;else if(n==="absolute"||n==="start")i=e,e=0;else if(n==="now")i=this._time;else if(n==="relative"){const c=this.getRunnerInfoById(t.id);c&&(i=c.start+e,e=0)}else if(n==="with-last"){const c=this.getLastRunnerInfo();i=c?c.start:this._time}else throw new Error('Invalid value for the "when" parameter');t.unschedule(),t.timeline(this);const o=t.persist(),a={persist:o===null?this._persist:o,start:i+e,runner:t};return this._lastRunnerId=t.id,this._runners.push(a),this._runners.sort((c,h)=>c.start-h.start),this._runnerIds=this._runners.map(c=>c.runner.id),this.updateTime()._continue(),this}seek(t){return this.time(this._time+t)}source(t){return t==null?this._timeSource:(this._timeSource=t,this)}speed(t){return t==null?this._speed:(this._speed=t,this)}stop(){return this.time(0),this.pause()}time(t){return t==null?this._time:(this._time=t,this._continue(!0))}unschedule(t){const e=this._runnerIds.indexOf(t.id);return e<0?this:(this._runners.splice(e,1),this._runnerIds.splice(e,1),t.timeline(null),this)}updateTime(){return this.active()||(this._lastSourceTime=this._timeSource()),this}_continue(t=!1){return C.cancelFrame(this._nextFrame),this._nextFrame=null,t?this._stepImmediate():this._paused?this:(this._nextFrame=C.frame(this._step),this)}_stepFn(t=!1){const e=this._timeSource();let n=e-this._lastSourceTime;t&&(n=0);const i=this._speed*n+(this._time-this._lastStepTime);this._lastSourceTime=e,t||(this._time+=i,this._time=this._time<0?0:this._time),this._lastStepTime=this._time,this.fire("time",this._time);for(let o=this._runners.length;o--;){const a=this._runners[o],c=a.runner;this._time-a.start<=0&&c.reset()}let r=!1;for(let o=0,a=this._runners.length;o<a;o++){const c=this._runners[o],h=c.runner;let l=i;const u=this._time-c.start;if(u<=0){r=!0;continue}else u<l&&(l=u);if(!h.active())continue;h.step(l).done?c.persist!==!0&&h.duration()-h.time()+this._time+c.persist<this._time&&(h.unschedule(),--o,--a):r=!0}return r&&!(this._speed<0&&this._time===0)||this._runnerIds.length&&this._speed<0&&this._time>0?this._continue():(this.pause(),this.fire("finished")),this}terminate(){this._startTime=0,this._speed=1,this._persist=0,this._nextFrame=null,this._paused=!0,this._runners=[],this._runnerIds=[],this._lastRunnerId=-1,this._time=0,this._lastSourceTime=0,this._lastStepTime=0,this._step=this._stepFn.bind(this,!1),this._stepImmediate=this._stepFn.bind(this,!0)}}k({Element:{timeline:function(s){return s==null?(this._timeline=this._timeline||new Si,this._timeline):(this._timeline=s,this)}}});class et extends De{constructor(t){super(),this.id=et.id++,t=t??ye.duration,t=typeof t=="function"?new Ze(t):t,this._element=null,this._timeline=null,this.done=!1,this._queue=[],this._duration=typeof t=="number"&&t,this._isDeclarative=t instanceof Ze,this._stepper=this._isDeclarative?t:new Tn,this._history={},this.enabled=!0,this._time=0,this._lastTime=0,this._reseted=!0,this.transforms=new x,this.transformId=1,this._haveReversed=!1,this._reverse=!1,this._loopsDone=0,this._swing=!1,this._wait=0,this._times=1,this._frameId=null,this._persist=this._isDeclarative?!0:null}static sanitise(t,e,n){let i=1,r=!1,o=0;return t=t??ye.duration,e=e??ye.delay,n=n||"last",typeof t=="object"&&!(t instanceof ls)&&(e=t.delay??e,n=t.when??n,r=t.swing||r,i=t.times??i,o=t.wait??o,t=t.duration??ye.duration),{duration:t,delay:e,swing:r,times:i,wait:o,when:n}}active(t){return t==null?this.enabled:(this.enabled=t,this)}addTransform(t){return this.transforms.lmultiplyO(t),this}after(t){return this.on("finished",t)}animate(t,e,n){const i=et.sanitise(t,e,n),r=new et(i.duration);return this._timeline&&r.timeline(this._timeline),this._element&&r.element(this._element),r.loop(i).schedule(i.delay,i.when)}clearTransform(){return this.transforms=new x,this}clearTransformsFromQueue(){(!this.done||!this._timeline||!this._timeline._runnerIds.includes(this.id))&&(this._queue=this._queue.filter(t=>!t.isTransform))}delay(t){return this.animate(0,t)}duration(){return this._times*(this._wait+this._duration)-this._wait}during(t){return this.queue(null,t)}ease(t){return this._stepper=new Tn(t),this}element(t){return t==null?this._element:(this._element=t,t._prepareRunner(),this)}finish(){return this.step(1/0)}loop(t,e,n){return typeof t=="object"&&(e=t.swing,n=t.wait,t=t.times),this._times=t||1/0,this._swing=e||!1,this._wait=n||0,this._times===!0&&(this._times=1/0),this}loops(t){const e=this._duration+this._wait;if(t==null){const o=Math.floor(this._time/e),c=(this._time-o*e)/this._duration;return Math.min(o+c,this._times)}const n=Math.floor(t),i=t%1,r=e*n+this._duration*i;return this.time(r)}persist(t){return t==null?this._persist:(this._persist=t,this)}position(t){const e=this._time,n=this._duration,i=this._wait,r=this._times,o=this._swing,a=this._reverse;let c;if(t==null){const f=function(d){const g=o*Math.floor(d%(2*(i+n))/(i+n)),_=g&&!a||!g&&a,S=Math.pow(-1,_)*(d%(i+n))/n+_;return Math.max(Math.min(S,1),0)},m=r*(i+n)-i;return c=e<=0?Math.round(f(1e-5)):e<m?f(e):Math.round(f(m-1e-5)),c}const h=Math.floor(this.loops()),l=o&&h%2===0;return c=h+(l&&!a||a&&l?t:1-t),this.loops(c)}progress(t){return t==null?Math.min(1,this._time/this.duration()):this.time(t*this.duration())}queue(t,e,n,i){return this._queue.push({initialiser:t||$s,runner:e||$s,retarget:n,isTransform:i,initialised:!1,finished:!1}),this.timeline()&&this.timeline()._continue(),this}reset(){return this._reseted?this:(this.time(0),this._reseted=!0,this)}reverse(t){return this._reverse=t??!this._reverse,this}schedule(t,e,n){if(t instanceof Si||(n=e,e=t,t=this.timeline()),!t)throw Error("Runner cannot be scheduled without timeline");return t.schedule(this,e,n),this}step(t){if(!this.enabled)return this;t=t??16,this._time+=t;const e=this.position(),n=this._lastPosition!==e&&this._time>=0;this._lastPosition=e;const i=this.duration(),r=this._lastTime<=0&&this._time>0,o=this._lastTime<i&&this._time>=i;this._lastTime=this._time,r&&this.fire("start",this);const a=this._isDeclarative;this.done=!a&&!o&&this._time>=i,this._reseted=!1;let c=!1;return(n||a)&&(this._initialise(n),this.transforms=new x,c=this._run(a?t:e),this.fire("step",this)),this.done=this.done||c&&a,o&&this.fire("finished",this),this}time(t){if(t==null)return this._time;const e=t-this._time;return this.step(e),this}timeline(t){return typeof t>"u"?this._timeline:(this._timeline=t,this)}unschedule(){const t=this.timeline();return t&&t.unschedule(this),this}_initialise(t){if(!(!t&&!this._isDeclarative))for(let e=0,n=this._queue.length;e<n;++e){const i=this._queue[e],r=this._isDeclarative||!i.initialised&&t;t=!i.finished,r&&t&&(i.initialiser.call(this),i.initialised=!0)}}_rememberMorpher(t,e){if(this._history[t]={morpher:e,caller:this._queue[this._queue.length-1]},this._isDeclarative){const n=this.timeline();n&&n.play()}}_run(t){let e=!0;for(let n=0,i=this._queue.length;n<i;++n){const r=this._queue[n],o=r.runner.call(this,t);r.finished=r.finished||o===!0,e=e&&r.finished}return e}_tryRetarget(t,e,n){if(this._history[t]){if(!this._history[t].caller.initialised){const r=this._queue.indexOf(this._history[t].caller);return this._queue.splice(r,1),!1}this._history[t].caller.retarget?this._history[t].caller.retarget.call(this,e,n):this._history[t].morpher.to(e),this._history[t].caller.finished=!1;const i=this.timeline();return i&&i.play(),!0}return!1}}et.id=0;class Ye{constructor(t=new x,e=-1,n=!0){this.transforms=t,this.id=e,this.done=n}clearTransformsFromQueue(){}}T([et,Ye],{mergeWith(s){return new Ye(s.transforms.lmultiply(this.transforms),s.id)}});const xi=(s,t)=>s.lmultiplyO(t),Ei=s=>s.transforms;function la(){const t=this._transformationRunners.runners.map(Ei).reduce(xi,new x);this.transform(t),this._transformationRunners.merge(),this._transformationRunners.length()===1&&(this._frameId=null)}class ua{constructor(){this.runners=[],this.ids=[]}add(t){if(this.runners.includes(t))return;const e=t.id+1;return this.runners.push(t),this.ids.push(e),this}clearBefore(t){const e=this.ids.indexOf(t+1)||1;return this.ids.splice(0,e,0),this.runners.splice(0,e,new Ye).forEach(n=>n.clearTransformsFromQueue()),this}edit(t,e){const n=this.ids.indexOf(t+1);return this.ids.splice(n,1,t+1),this.runners.splice(n,1,e),this}getByID(t){return this.runners[this.ids.indexOf(t+1)]}length(){return this.ids.length}merge(){let t=null;for(let e=0;e<this.runners.length;++e){const n=this.runners[e];if(t&&n.done&&t.done&&(!n._timeline||!n._timeline._runnerIds.includes(n.id))&&(!t._timeline||!t._timeline._runnerIds.includes(t.id))){this.remove(n.id);const r=n.mergeWith(t);this.edit(t.id,r),t=r,--e}else t=n}return this}remove(t){const e=this.ids.indexOf(t+1);return this.ids.splice(e,1),this.runners.splice(e,1),this}}k({Element:{animate(s,t,e){const n=et.sanitise(s,t,e),i=this.timeline();return new et(n.duration).loop(n).element(this).timeline(i.play()).schedule(n.delay,n.when)},delay(s,t){return this.animate(0,s,t)},_clearTransformRunnersBefore(s){this._transformationRunners.clearBefore(s.id)},_currentTransform(s){return this._transformationRunners.runners.filter(t=>t.id<=s.id).map(Ei).reduce(xi,new x)},_addRunner(s){this._transformationRunners.add(s),C.cancelImmediate(this._frameId),this._frameId=C.immediate(la.bind(this))},_prepareRunner(){this._frameId==null&&(this._transformationRunners=new ua().add(new Ye(new x(this))))}}});const fa=(s,t)=>s.filter(e=>!t.includes(e));T(et,{attr(s,t){return this.styleAttr("attr",s,t)},css(s,t){return this.styleAttr("css",s,t)},styleAttr(s,t,e){if(typeof t=="string")return this.styleAttr(s,{[t]:e});let n=t;if(this._tryRetarget(s,n))return this;let i=new Rt(this._stepper).to(n),r=Object.keys(n);return this.queue(function(){i=i.from(this.element()[s](r))},function(o){return this.element()[s](i.at(o).valueOf()),i.done()},function(o){const a=Object.keys(o),c=fa(a,r);if(c.length){const l=this.element()[s](c),u=new Ee(i.from()).valueOf();Object.assign(u,l),i.from(u)}const h=new Ee(i.to()).valueOf();Object.assign(h,o),i.to(h),r=a,n=o}),this._rememberMorpher(s,i),this},zoom(s,t){if(this._tryRetarget("zoom",s,t))return this;let e=new Rt(this._stepper).to(new E(s));return this.queue(function(){e=e.from(this.element().zoom())},function(n){return this.element().zoom(e.at(n),t),e.done()},function(n,i){t=i,e.to(n)}),this._rememberMorpher("zoom",e),this},transform(s,t,e){if(t=s.relative||t,this._isDeclarative&&!t&&this._tryRetarget("transform",s))return this;const n=x.isMatrixLike(s);e=s.affine!=null?s.affine:e??!n;const i=new Rt(this._stepper).type(e?Re:x);let r,o,a,c,h;function l(){o=o||this.element(),r=r||xn(s,o),h=new x(t?void 0:o),o._addRunner(this),t||o._clearTransformRunnersBefore(this)}function u(m){t||this.clearTransform();const{x:d,y:g}=new W(r).transform(o._currentTransform(this));let _=new x({...s,origin:[d,g]}),S=this._isDeclarative&&a?a:h;if(e){_=_.decompose(d,g),S=S.decompose(d,g);const R=_.rotate,q=S.rotate,L=[R-360,R,R+360],ot=L.map(ln=>Math.abs(ln-q)),mt=Math.min(...ot),Ft=ot.indexOf(mt);_.rotate=L[Ft]}t&&(n||(_.rotate=s.rotate||0),this._isDeclarative&&c&&(S.rotate=c)),i.from(S),i.to(_);const D=i.at(m);return c=D.rotate,a=new x(D),this.addTransform(a),o._addRunner(this),i.done()}function f(m){(m.origin||"center").toString()!==(s.origin||"center").toString()&&(r=xn(m,o)),s={...m,origin:r}}return this.queue(l,u,f,!0),this._isDeclarative&&this._rememberMorpher("transform",i),this},x(s){return this._queueNumber("x",s)},y(s){return this._queueNumber("y",s)},ax(s){return this._queueNumber("ax",s)},ay(s){return this._queueNumber("ay",s)},dx(s=0){return this._queueNumberDelta("x",s)},dy(s=0){return this._queueNumberDelta("y",s)},dmove(s,t){return this.dx(s).dy(t)},_queueNumberDelta(s,t){if(t=new E(t),this._tryRetarget(s,t))return this;const e=new Rt(this._stepper).to(t);let n=null;return this.queue(function(){n=this.element()[s](),e.from(n),e.to(n+t)},function(i){return this.element()[s](e.at(i)),e.done()},function(i){e.to(n+new E(i))}),this._rememberMorpher(s,e),this},_queueObject(s,t){if(this._tryRetarget(s,t))return this;const e=new Rt(this._stepper).to(t);return this.queue(function(){e.from(this.element()[s]())},function(n){return this.element()[s](e.at(n)),e.done()}),this._rememberMorpher(s,e),this},_queueNumber(s,t){return this._queueObject(s,new E(t))},cx(s){return this._queueNumber("cx",s)},cy(s){return this._queueNumber("cy",s)},move(s,t){return this.x(s).y(t)},amove(s,t){return this.ax(s).ay(t)},center(s,t){return this.cx(s).cy(t)},size(s,t){let e;return(!s||!t)&&(e=this._element.bbox()),s||(s=e.width/e.height*t),t||(t=e.height/e.width*s),this.width(s).height(t)},width(s){return this._queueNumber("width",s)},height(s){return this._queueNumber("height",s)},plot(s,t,e,n){if(arguments.length===4)return this.plot([s,t,e,n]);if(this._tryRetarget("plot",s))return this;const i=new Rt(this._stepper).type(this._element.MorphArray).to(s);return this.queue(function(){i.from(this._element.array())},function(r){return this._element.plot(i.at(r)),i.done()}),this._rememberMorpher("plot",i),this},leading(s){return this._queueNumber("leading",s)},viewbox(s,t,e,n){return this._queueObject("viewbox",new K(s,t,e,n))},update(s){return typeof s!="object"?this.update({offset:arguments[0],color:arguments[1],opacity:arguments[2]}):(s.opacity!=null&&this.attr("stop-opacity",s.opacity),s.color!=null&&this.attr("stop-color",s.color),s.offset!=null&&this.attr("offset",s.offset),this)}});T(et,{rx:as,ry:cs,from:_i,to:bi});N(et,"Runner");class fs extends V{constructor(t,e=t){super($("svg",t),e),this.namespace()}defs(){return this.isRoot()?st(this.node.querySelector("defs"))||this.put(new os):this.root().defs()}isRoot(){return!this.node.parentNode||!(this.node.parentNode instanceof I.window.SVGElement)&&this.node.parentNode.nodeName!=="#document-fragment"}namespace(){return this.isRoot()?this.attr({xmlns:es,version:"1.1"}).attr("xmlns:xlink",Ne,fn):this.root().namespace()}removeNamespace(){return this.attr({xmlns:null,version:null}).attr("xmlns:xlink",null,fn).attr("xmlns:svgjs",null,fn)}root(){return this.isRoot()?this:super.root()}}k({Container:{nested:H(function(){return this.put(new fs)})}});N(fs,"Svg",!0);let rn=class extends V{constructor(t,e=t){super($("symbol",t),e)}};k({Container:{symbol:H(function(){return this.put(new rn)})}});N(rn,"Symbol");function da(s){return this._build===!1&&this.clear(),this.node.appendChild(I.document.createTextNode(s)),this}function pa(){return this.node.getComputedTextLength()}function ma(s,t=this.bbox()){return s==null?t.x:this.attr("x",this.attr("x")+s-t.x)}function ga(s,t=this.bbox()){return s==null?t.y:this.attr("y",this.attr("y")+s-t.y)}function ya(s,t,e=this.bbox()){return this.x(s,e).y(t,e)}function wa(s,t=this.bbox()){return s==null?t.cx:this.attr("x",this.attr("x")+s-t.cx)}function _a(s,t=this.bbox()){return s==null?t.cy:this.attr("y",this.attr("y")+s-t.cy)}function ba(s,t,e=this.bbox()){return this.cx(s,e).cy(t,e)}function va(s){return this.attr("x",s)}function Aa(s){return this.attr("y",s)}function Sa(s,t){return this.ax(s).ay(t)}function xa(s){return this._build=!!s,this}const ki=Object.freeze(Object.defineProperty({__proto__:null,amove:Sa,ax:va,ay:Aa,build:xa,center:ba,cx:wa,cy:_a,length:pa,move:ya,plain:da,x:ma,y:ga},Symbol.toStringTag,{value:"Module"}));class F extends nt{constructor(t,e=t){super($("text",t),e),this.dom.leading=this.dom.leading??new E(1.3),this._rebuild=!0,this._build=!1}leading(t){return t==null?this.dom.leading:(this.dom.leading=new E(t),this.rebuild())}rebuild(t){if(typeof t=="boolean"&&(this._rebuild=t),this._rebuild){const e=this;let n=0;const i=this.dom.leading;this.each(function(r){if(En(this.node))return;const o=I.window.getComputedStyle(this.node).getPropertyValue("font-size"),a=i*new E(o);this.dom.newLined&&(this.attr("x",e.attr("x")),this.text()===`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
`:""):(typeof t=="function"?(this.clear().build(!0),t.call(this,this),this.build(!1)):this.plain(t),this)}}T(on,ki);k({Tspan:{tspan:H(function(s=""){const t=new on;return this._build||this.clear(),this.put(t).text(s)})},Text:{newLine:function(s=""){return this.tspan(s).newLine()}}});N(on,"Tspan");class ds extends nt{constructor(t,e=t){super($("circle",t),e)}radius(t){return this.attr("r",t)}rx(t){return this.attr("r",t)}ry(t){return this.rx(t)}size(t){return this.radius(new E(t).divide(2))}}T(ds,{x:fi,y:di,cx:pi,cy:mi,width:gi,height:yi});k({Container:{circle:H(function(s=0){return this.put(new ds).size(s).move(0,0)})}});N(ds,"Circle");class Cn extends V{constructor(t,e=t){super($("clipPath",t),e)}remove(){return this.targets().forEach(function(t){t.unclip()}),super.remove()}targets(){return de("svg [clip-path*="+this.id()+"]")}}k({Container:{clip:H(function(){return this.defs().put(new Cn)})},Element:{clipper(){return this.reference("clip-path")},clipWith(s){const t=s instanceof Cn?s:this.parent().clip().add(s);return this.attr("clip-path","url(#"+t.id()+")")},unclip(){return this.attr("clip-path",null)}}});N(Cn,"ClipPath");class Ti extends pt{constructor(t,e=t){super($("foreignObject",t),e)}}k({Container:{foreignObject:H(function(s,t){return this.put(new Ti).size(s,t)})}});N(Ti,"ForeignObject");function Ea(s,t){return this.children().forEach(e=>{let n;try{n=e.node instanceof Or().SVGSVGElement?new K(e.attr(["x","y","width","height"])):e.bbox()}catch{return}const i=new x(e),r=i.translate(s,t).transform(i.inverse()),o=new W(n.x,n.y).transform(r);e.move(o.x,o.y)}),this}function ka(s){return this.dmove(s,0)}function Ta(s){return this.dmove(0,s)}function Oa(s,t=this.bbox()){return s==null?t.height:this.size(t.width,s,t)}function Ia(s=0,t=0,e=this.bbox()){const n=s-e.x,i=t-e.y;return this.dmove(n,i)}function Na(s,t,e=this.bbox()){const n=fe(this,s,t,e),i=n.width/e.width,r=n.height/e.height;return this.children().forEach(o=>{const a=new W(e).transform(new x(o).inverse());o.scale(i,r,a.x,a.y)}),this}function Da(s,t=this.bbox()){return s==null?t.width:this.size(s,t.height,t)}function Ca(s,t=this.bbox()){return s==null?t.x:this.move(s,t.y,t)}function Ma(s,t=this.bbox()){return s==null?t.y:this.move(t.x,s,t)}const Oi=Object.freeze(Object.defineProperty({__proto__:null,dmove:Ea,dx:ka,dy:Ta,height:Oa,move:Ia,size:Na,width:Da,x:Ca,y:Ma},Symbol.toStringTag,{value:"Module"}));class P extends V{constructor(t,e=t){super($("g",t),e)}}T(P,Oi);k({Container:{group:H(function(){return this.put(new P)})}});N(P,"G");class Xe extends V{constructor(t,e=t){super($("a",t),e)}target(t){return this.attr("target",t)}to(t){return this.attr("href",t,Ne)}}T(Xe,Oi);k({Container:{link:H(function(s){return this.put(new Xe).to(s)})},Element:{unlink(){const s=this.linker();if(!s)return this;const t=s.parent();if(!t)return this.remove();const e=t.index(s);return t.add(this,e),s.remove(),this},linkTo(s){let t=this.linker();return t||(t=new Xe,this.wrap(t)),typeof s=="function"?s.call(t,t):t.to(s),this},linker(){const s=this.parent();return s&&s.node.nodeName.toLowerCase()==="a"?s:null}}});N(Xe,"A");class Mn extends V{constructor(t,e=t){super($("mask",t),e)}remove(){return this.targets().forEach(function(t){t.unmask()}),super.remove()}targets(){return de("svg [mask*="+this.id()+"]")}}k({Container:{mask:H(function(){return this.defs().put(new Mn)})},Element:{masker(){return this.reference("mask")},maskWith(s){const t=s instanceof Mn?s:this.parent().mask().add(s);return this.attr("mask","url(#"+t.id()+")")},unmask(){return this.attr("mask",null)}}});N(Mn,"Mask");class Ii extends pt{constructor(t,e=t){super($("stop",t),e)}update(t){return(typeof t=="number"||t instanceof E)&&(t={offset:arguments[0],color:arguments[1],opacity:arguments[2]}),t.opacity!=null&&this.attr("stop-opacity",t.opacity),t.color!=null&&this.attr("stop-color",t.color),t.offset!=null&&this.attr("offset",new E(t.offset)),this}}k({Gradient:{stop:function(s,t,e){return this.put(new Ii).update(s,t,e)}}});N(Ii,"Stop");function Ra(s,t){if(!s)return"";if(!t)return s;let e=s+"{";for(const n in t)e+=Er(n)+":"+t[n]+";";return e+="}",e}class Rn extends pt{constructor(t,e=t){super($("style",t),e)}addText(t=""){return this.node.textContent+=t,this}font(t,e,n={}){return this.rule("@font-face",{fontFamily:t,src:e,...n})}rule(t,e){return this.addText(Ra(t,e))}}k("Dom",{style(s,t){return this.put(new Rn).rule(s,t)},fontface(s,t,e){return this.put(new Rn).font(s,t,e)}});N(Rn,"Style");class ps extends F{constructor(t,e=t){super($("textPath",t),e)}array(){const t=this.track();return t?t.array():null}plot(t){const e=this.track();let n=null;return e&&(n=e.plot(t)),t==null?n:this}track(){return this.reference("href")}}k({Container:{textPath:H(function(s,t){return s instanceof F||(s=this.text(s)),s.path(t)})},Text:{path:H(function(s,t=!0){const e=new ps;s instanceof pe||(s=this.defs().path(s)),e.attr("href","#"+s,Ne);let n;if(t)for(;n=this.node.firstChild;)e.node.appendChild(n);return this.put(e)}),textPath(){return this.findOne("textPath")}},Path:{text:H(function(s){return s instanceof F||(s=new F().addTo(this.parent()).text(s)),s.path(this)}),targets(){return de("svg textPath").filter(s=>(s.attr("href")||"").includes(this.id()))}}});ps.prototype.MorphArray=jt;N(ps,"TextPath");class an extends nt{constructor(t,e=t){super($("use",t),e)}use(t,e){return this.attr("href",(e||"")+"#"+t,Ne)}}k({Container:{use:H(function(s,t){return this.put(new an).use(s,t)})}});N(an,"Use");T([fs,rn,Me,Se,Ge],J("viewbox"));T([xe,$e,He,pe],J("marker"));T(F,J("Text"));T(pe,J("Path"));T(os,J("Defs"));T([F,on],J("Tspan"));T([Be,sn,Ce,et],J("radius"));T(De,J("EventTarget"));T(Tt,J("Dom"));T(pt,J("Element"));T(nt,J("Shape"));T([V,wi],J("Container"));T(Ce,J("Gradient"));T(et,J("Runner"));Pt.extend(Sr());ea([E,M,K,x,ne,Ot,jt,W]);na();const lt=(s,t)=>{const e=tt(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 h=tt(c,t).height;return h>a?h:a},0);return{width:s.tiles.reduce((a,c)=>a+tt(c,t).width,0),height:r}},tt=(s,t)=>{const e=parseFloat((Et.HEIGHT*t).toPrecision(5)),n=parseFloat((Et.WIDTH*t).toPrecision(5)),i=s.has(y.HORIZONTAL)?{width:e,height:n,baseWidth:n,baseHeight:e}:{width:n,height:e,w:n,baseWidth:n,baseHeight:e};return(s.has(y.TSUMO)||s.has(y.DORA))&&(i.width+=n*Et.TEXT_SCALE),i};class se{constructor(t={}){A(this,"tileWidth");A(this,"tileHeight");A(this,"imageHostPath");A(this,"imageHostUrl");A(this,"imageExt");A(this,"scale");A(this,"svgSprite");this.scale=t.scale??1,this.imageHostPath=t.imageHostPath??"",this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=Et.WIDTH*this.scale,this.tileHeight=Et.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getDiffTileHeightWidth(t){const e=tt(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new Me().load(this.buildURL(t));return this.svgSprite&&(e=new an().use(se.buildID(t))),t instanceof w&&t.has(y.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,n){const i=tt(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=tt(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,h=o.baseHeight,l=new F().text(i);l.size(o.baseWidth,o.baseHeight).font({family:Zn,size:a}).dx(c).dy(h);const u=new P;return u.add(r).add(l).translate(e,n),u}createRotate90Image(t,e,n,i=!1){const r=this.createImage(t,0,0),o=tt(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,h=e+this.getDiffTileHeightWidth(t),l=i?n-this.getDiffTileHeightWidth(t):n,u=new P;return u.add(r).translate(h,l).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==p.BACK||t.has(y.RED)?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${se.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:`${this.imageHostPath}${e}`}}class ms extends se{constructor(){super(...arguments);A(this,"blockMargin",Et.WIDTH*Et.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const n=e instanceof U?e.tilesWithBack:e.tiles,i=new P;let r=0;for(const o of n){const a=tt(o,this.scale),c=o.has(y.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),h=o.has(y.HORIZONTAL)?this.getDiffTileHeightWidth(o):0,l=c(o,r,h);i.add(l),r+=a.width}return i}createBlockPonChiKan(e){const n=e.tiles.findIndex(o=>o.has(y.HORIZONTAL));let i=0;const r=new P;if(e.type==b.SHO_KAN){let o=n;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=tt(e.tiles[a],this.scale);if(a==o)continue;if(a==n){const u=e.tiles[n],f=e.tiles[o],m=tt(u,this.scale),d=this.createRotate90Image(u,0,0,!0),g=this.createRotate90Image(f,0,m.height,!0);r.add(new P().translate(i,0).add(d).add(g)),i+=m.width;continue}const h=c.width*2-c.height,l=this.createImage(e.tiles[a],i,h);i+=c.width,r.add(l)}return r}if(e.type==b.CHI){const o=e.tiles[n],a=this.createRotate90Image(o,i,this.getDiffTileHeightWidth(o));i+=tt(o,this.scale).width,r.add(a);for(let c=0;c<e.tiles.length;c++){if(c==n)continue;const h=e.tiles[c],l=tt(h,this.scale),u=this.createImage(h,i,0);i+=l.width,r.add(u)}return r}for(let o=0;o<e.tiles.length;o++){const a=o==n?this.createRotate90Image.bind(this):this.createImage.bind(this),c=e.tiles[o],h=o==n?this.getDiffTileHeightWidth(c):0,l=tt(c,this.scale),u=a(c,i,h);i+=l.width,r.add(u)}return r}}const Ha=(s,t)=>{const e=s.scale;return{[b.CHI]:function(i){const r=lt(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.PON]:function(i){const r=lt(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.DAI_KAN]:function(i){const r=lt(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.SHO_KAN]:function(i){const r=lt(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.AN_KAN]:function(i){O(i instanceof U,`block type is not ankan: ${i.type}`);const r=lt(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DORA]:function(i){i=(t==null?void 0:t.doraText)==!1?new ee([i.tiles[0].clone({remove:y.DORA})]):i;const r=lt(i,e),o=new P,a=(t==null?void 0: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==null?void 0:t.tsumoText)==!1?new ee([i.tiles[0].clone({remove:y.TSUMO})]):i;const r=lt(i,e),o=new P,a=(t==null?void 0: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=lt(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DISCARD]:function(i){const r=lt(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(y.TSUMO)||a.has(y.DORA)))throw new Error("found an unknown block with operator tiles");const r=lt(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}}}},Vt=(s,t,e)=>{const n=Ha(s,e);let i=0,r=0;const o=[];for(const u of t){const f=n[u.type],m=f(u);r+=m.width,i=m.height>i?m.height:i,o.push(m)}const a=i,c=r+(t.length-1)*s.blockMargin,h=new P;let l=0;for(const u of o){const f=a-u.height,m=new P().translate(l,f);m.add(u.e),h.add(m),l+=u.width+s.blockMargin}return{e:h,width:c,height:a}},$a=(s,t,e={},n={responsive:!1,doraText:!0,tsumoText:!0})=>{const i=new ms(e),r=Vt(i,t,n);n.responsive||s.size(r.width,r.height),s.viewbox(0,0,r.width,r.height),s.add(r.e)},Ni=()=>{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(se.buildID(new w(e,0)));continue}t.push(...s.map(n=>se.buildID(new w(e,n))).flat())}return t},Ba=s=>{const t=Ni(),e=[];return s.each((n,i)=>{const r=i[n];if(r instanceof an){const a=r.attr("href").substring(1);t.includes(a)&&e.push(a)}}),e},Wa=s=>{const t=Ni(),e=Ba(s);s.each((n,i)=>{const r=i[n];r instanceof rn&&(t.includes(r.id())&&e.includes(r.id())||r.remove())},!0)},Pa=s=>{const e=[];for(let n=0;n<s.length;n+=6){const i=s.slice(n,n+6);e.push(i)}return e},ht=(s,t,e,n,i=0,r=0)=>{const o=new P().add(s);if(n==90){const a=i,c=r-e;return o.rotate(n,0,e).translate(a,c),o}if(n==180){const a=i+t,c=r-e;return o.rotate(n,0,e).translate(a,c),o}if(n==270){const a=i+e,c=r+(t-e);return o.rotate(n,0,e).translate(a,c),o}return o},ze=(s,t)=>{const e=new P,n=Pa(s);for(let i=0;i<n.length;i++){let r=n[i],o=i*t.tileHeight;const a=t.createBlockHandDiscard(new Vn(r,b.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*n.length}},ja=(s,t,e)=>{const n=t.font,i=t.textWidth,r=t.textHeight,o=new P,a=e.sticks.dead,c=e.sticks.reach,h=125*s.scale,l=27.5*s.scale;let u=i*3,f=r;const m=(h+s.tileWidth+i-u)/2,d=new F().plain(e.round).font(n).move(m,0);o.add(d),f+=25*s.scale;const g=s.tileHeight,_=new P().size(h,g).translate(0,f),S={family:n.family,size:n.size*.7},D=s.createStick(1e3).size(h,l).move(0,0),R=new F().plain(c.toString()).font(S).attr({x:h,y:l});_.add(D),_.add(R);const q=s.createStick(100).size(h,l).move(0,l+l),L=new F().plain(a.toString()).font(S).attr({x:h,y:l*3});_.add(q),_.add(L);const ot=s.createImage(e.doras[0],0,0).move(h+i,0);return _.add(ot),o.add(d),o.add(_),{e:o,width:h+s.tileWidth+i,height:f+s.tileHeight}},za=(s,t,e=0)=>{const n=Vt(s,t.front),i=Vt(s,t.right),r=Vt(s,t.opposite),o=Vt(s,t.left),a=[n.width,i.width,r.width,o.width].reduce((g,_)=>Math.max(g,_)),c=Math.max(e+s.tileHeight*2+s.blockMargin*2,a+s.tileWidth*2+s.blockMargin),h=c,l=new P().size(c,h),u=ht(n.e,n.width,n.height,0).translate((c-n.width)/2,h-n.height),f=ht(i.e,i.width,i.height,270).translate(c-i.height,(c-i.width)/2),m=ht(r.e,r.width,r.height,180).translate((c-r.width)/2,0),d=ht(o.e,o.width,o.height,90).translate(0,(c-o.width)/2);return l.add(u),l.add(f),l.add(m),l.add(d),{e:l,width:c,height:h}},Ka=s=>{const t=Object.values(nn),e=t.indexOf(s);return[...t.slice(e),...t.slice(0,e)]},La=(s,t,e)=>{const n=s.tileWidth*5+s.tileHeight*1,i=new P,r=new Be().size(n,n).move(0,0).fill("none").stroke("#000000");i.add(r);const o=t.font,a=t.textWidth,c=t.textHeight,h=t.numWidth,l=ja(s,t,e);l.e.translate(n/2-l.width/2,n/2-l.height/2);const u=(ln,Is,lr)=>{const ur=`${ln} ${Is}`,fr=new F().plain(ur).font(o).attr(lr);return{e:new P().add(fr),width:a+h*Is.toString().length,height:c}},[f,m,d,g]=Ka(e.frontPlace),_=e.scores,D=u(f,_.front,{x:n/2,y:n,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let R=u(m,_.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const q=ht(R.e,R.width,R.height,270).translate(n,n/2-R.width);let L=u(d,_.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const ot=ht(L.e,L.width,L.height,180).translate(n/2-L.width,-L.height);let mt=u(g,_.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const Ft=ht(mt.e,mt.width,mt.height,90).translate(-mt.height,n/2);return i.add(l.e),i.add(D),i.add(q),i.add(ot),i.add(Ft),{e:i,width:n,height:n}},Ua=(s,t)=>{const e=ze(t.front,s),n=ze(t.right,s),i=ze(t.opposite,s),r=ze(t.left,s),o=[e.height,n.height,i.height,r.height].reduce((D,R)=>Math.max(D,R)),a=s.tileWidth*5+s.tileHeight*1,c=o,h=a+o*2+s.blockMargin,l=h,u=new P().size(h,l),f=h/2-a/2,m=l/2-a/2,d=ht(e.e,a,c,0).translate(f,l-c),g=ht(n.e,a,c,270).translate(h-c,m),_=ht(i.e,a,c,180).translate(f,0),S=ht(r.e,a,c,90).translate(0,m);return u.add(d),u.add(g),u.add(_),u.add(S),{e:u,width:h,height:l}},Di=(s,t,e,n,i)=>{const r=new P,o=Ua(s,n),a=za(s,e,o.height),c=La(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}},Fa=(s,t,e={},n,i={responsive:!1})=>{const r=new ms(e),o=n,{discards:a,hands:c,scoreBoard:h}=Ci(t),l=Di(r,o,c,a,h);i.responsive||s.size(l.width,l.height),s.viewbox(0,0,l.width,l.height),s.add(l.e)};var gt;function qa(s){return{lang:(s==null?void 0:s.lang)??(gt==null?void 0:gt.lang),message:s==null?void 0:s.message,abortEarly:(s==null?void 0:s.abortEarly)??(gt==null?void 0:gt.abortEarly),abortPipeEarly:(s==null?void 0:s.abortPipeEarly)??(gt==null?void 0:gt.abortPipeEarly)}}var yn;function Ga(s){return yn==null?void 0:yn.get(s)}var wn;function Za(s){return wn==null?void 0:wn.get(s)}var _n;function Ya(s,t){var e;return(e=_n==null?void 0:_n.get(s))==null?void 0:e.get(t)}function ie(s){var e,n;const t=typeof s;return t==="string"?`"${s}"`:t==="number"||t==="bigint"||t==="boolean"?`${s}`:t==="object"||t==="function"?(s&&((n=(e=Object.getPrototypeOf(s))==null?void 0:e.constructor)==null?void 0:n.name))??"null":t}function zt(s,t,e,n,i){const r=i&&"input"in i?i.input:e.value,o=(i==null?void 0:i.expected)??s.expects??null,a=(i==null?void 0:i.received)??ie(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==null?void 0:i.path,issues:i==null?void 0:i.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},h=s.kind==="schema",l=(i==null?void 0:i.message)??s.message??Ya(s.reference,c.lang)??(h?Za(c.lang):null)??n.message??Ga(c.lang);l&&(c.message=typeof l=="function"?l(c):l),h&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function Xa(s,t){const e=[...new Set(s)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function Hn(s,t){return{kind:"validation",type:"max_value",reference:Hn,async:!1,expects:`<=${s instanceof Date?s.toJSON():ie(s)}`,requirement:s,message:t,_run(e,n){return e.typed&&e.value>this.requirement&&zt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():ie(e.value)}),e}}}function $n(s,t){return{kind:"validation",type:"min_value",reference:$n,async:!1,expects:`>=${s instanceof Date?s.toJSON():ie(s)}`,requirement:s,message:t,_run(e,n){return e.typed&&e.value<this.requirement&&zt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():ie(e.value)}),e}}}function Ja(s,t,e){return typeof s.default=="function"?s.default(t,e):s.default}function Je(s){return{kind:"schema",type:"number",reference:Je,expects:"number",async:!1,message:s,_run(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:zt(this,"type",t,e),t}}}function it(s,...t){const e={kind:"schema",type:"optional",reference:it,expects:`(${s.expects} | undefined)`,async:!1,wrapped:s,_run(n,i){return n.value===void 0&&("default"in this&&(n.value=Ja(this,n,i)),n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,i)}};return 0 in t&&(e.default=t[0]),e}function Bn(s,t){return{kind:"schema",type:"picklist",reference:Bn,expects:Xa(s.map(ie),"|"),async:!1,options:s,message:t,_run(e,n){return this.options.includes(e.value)?e.typed=!0:zt(this,"type",e,n),e}}}function re(s,t){return{kind:"schema",type:"strict_object",reference:re,expects:"Object",async:!1,entries:s,message:t,_run(e,n){var r;const i=e.value;if(i&&typeof i=="object"){e.typed=!0,e.value={};for(const o in this.entries){const a=i[o],c=this.entries[o]._run({typed:!1,value:a},n);if(c.issues){const h={type:"object",origin:"value",input:i,key:o,value:a};for(const l of c.issues)l.path?l.path.unshift(h):l.path=[h],(r=e.issues)==null||r.push(l);if(e.issues||(e.issues=c.issues),n.abortEarly){e.typed=!1;break}}c.typed||(e.typed=!1),(c.value!==void 0||o in i)&&(e.value[o]=c.value)}if(!e.issues||!n.abortEarly){for(const o in i)if(!(o in this.entries)){const a=i[o];zt(this,"type",e,n,{input:a,expected:"never",path:[{type:"object",origin:"value",input:i,key:o,value:a}]});break}}}else zt(this,"type",e,n);return e}}}function Ve(s){return{kind:"schema",type:"string",reference:Ve,expects:"string",async:!1,message:s,_run(t,e){return typeof t.value=="string"?t.typed=!0:zt(this,"type",t,e),t}}}function Ws(...s){return{...s[0],pipe:s,_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 Va(s,t,e){const n=s._run({typed:!1,value:t},qa(e));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}const Ke=it(re({discard:it(Ve(),""),hand:it(Ve(),""),score:it(Je(),25e3)}),{discard:"",hand:"",score:25e3}),Qa=re({[v.E]:Ke,[v.S]:Ke,[v.W]:Ke,[v.N]:Ke}),Nt={round:j.E1,sticks:{reach:0,dead:0},doras:v.S,front:v.E},tc=it(re({round:it(Bn(Object.keys(Yn)),Nt.round),sticks:it(re({reach:it(Ws(Je(),$n(0,""),Hn(9,"")),Nt.sticks.reach),dead:it(Ws(Je(),$n(0,""),Hn(9,"")),Nt.sticks.dead)}),Nt.sticks),doras:it(Ve(),Nt.doras),front:it(Bn(Object.keys(nn)),Nt.front)}),Nt),ec=re({...Qa.entries,board:tc}),Ci=s=>{const t=Mi(s);return Ri(t)},Mi=s=>{const t=nc(s),e=Va(ec,t);if(!e.success)throw e.issues;return e.output},nc=s=>{const t="table",e="board",n=s.split(`
|
|
7
|
-
`).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=[v.E,v.S,v.W,v.N,e];for(;;){const a=n.shift();if(a==null)break;const c=o.find(h=>a.startsWith(h));if(c==null)throw new Error(`encountered unexpected line ${a}`);if(o=o.filter(h=>!a.startsWith(h)),c==e){const[h,l]=ic([...n]);r.board=h;for(let u=0;u<l;u++)n.shift()}else{const[h,l]=sc([...n]);r[c]=h;for(let u=0;u<l;u++)n.shift()}}return r},ut=(s,t)=>s.replace(t,"").replace(":","").trim(),sc=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=ut(o,t);else if(o.startsWith(e))i.discard=ut(o,e);else if(o.startsWith(n))i.score=Number(ut(o,n));else break}return[i,r]},ic=s=>{const t="doras",e="round",n="front",i="sticks",r="reach",o="dead",a={};let c=0;for(;c<s.length;c++){const h=s[c];if(h.startsWith(t))a.doras=ut(h,t);else if(h.startsWith(e))a.round=ut(h,e);else if(h.startsWith(n))a.front=ut(h,n);else if(h.startsWith(i)){a.sticks={};const l=s[c+1]??"",u=s[c+2]??"";l.startsWith(r)&&(a.sticks.reach=Number(ut(l,r))),l.startsWith(o)&&(a.sticks.dead=Number(ut(l,o))),u.startsWith(r)&&(a.sticks.reach=Number(ut(u,r))),u.startsWith(o)&&(a.sticks.dead=Number(ut(u,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},Ri=s=>{const t=s.board.front,e=rc(t),n=a=>s[a].discard.replace(/\r?\n/g,""),i={front:new Q(n(e.front)).tiles(),right:new Q(n(e.right)).tiles(),opposite:new Q(n(e.opposite)).tiles(),left:new Q(n(e.left)).tiles()},r={front:new Q(s[e.front].hand).parse(),right:new Q(s[e.right].hand).parse(),opposite:new Q(s[e.opposite].hand).parse(),left:new Q(s[e.left].hand).parse()},o={round:Yn[s.board.round],frontPlace:nn[t],sticks:s.board.sticks,doras:new Q(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}},rc=s=>({front:s,right:kt(s),opposite:kt(kt(s)),left:Qn(s)});function*rt(s){const t=s!=null&&s.filterBy&&s.filterBy.length>0?s==null?void 0:s.filterBy:Object.values(p);for(const e of t){if(s!=null&&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 cn{constructor(t,e=!1){A(this,"data");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 Q(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 rt()){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,[y.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));O(n>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[n]=t[n].clone({add:y.TSUMO})}return t}toString(){const t=this.called.length>0?`${At}${this.called.join(At)}`:"",e=this.drawn?`${At}${this.drawn.toString()}`:"",n=this.hands.filter(r=>!r.has(y.TSUMO));return`${new ee(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 U))}sum(t){let e=0;for(const[n,i]of rt({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){if(n.t!=p.BACK&&this.get(n.t,n.n)>=4||n.has(y.RED)&&this.get(n.t,0)>0)throw this.dec(e),new Error(`unable to increase ${n} 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(y.RED)&&(this.data[n.t][0]+=1))}return e}dec(t){const e=[];for(const n of t){if(this.get(n.t,n.n)<1||n.has(y.RED)&&this.get(n.t,0)<=0)throw this.inc(e),new Error(`unable to decrease ${n.toString()} 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(y.RED)&&(this.data[n.t][0]-=1)),z(n)&&this.get(n.t,5)==0&&this.get(n.t,0)>0){this.data[n.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(n=>!n.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 U){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof ct){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=z(n)?n.clone({remove:y.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 cn(this.toString());return t.data.reached=this.data.reached,t}}class We{constructor(t){A(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[n,i]of rt({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?oe:ft;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[f,m]of rt({filterBy:[p.Z]}))this.hand.get(f,m)>=3?i[0]++:this.hand.get(f,m)==2?i[1]++:this.hand.get(f,m)==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 h=this.patternByNumType(p.M),l=this.patternByNumType(p.P),u=this.patternByNumType(p.S);for(const f of[h.patternA,h.patternB])for(const m of[l.patternA,l.patternB])for(const d of[u.patternA,u.patternB]){const g=[this.hand.called.length,0,0];for(let S=0;S<3;S++)g[S]+=f[S]+m[S]+d[S]+i[S]+r[S];const _=this.calcCommon(g[0],g[1],g[2],n);_<c&&(c=_)}return c};let e=t(!1);for(const[n,i]of rt())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}patternByNumType(t,e=1){if(e>9)return this.groupRemainingTiles(t);let n=this.patternByNumType(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.patternByNumType(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.patternByNumType(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 rt({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 Hi{constructor(t){A(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 n=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 h=0;h<a.length;h++){const l=a[h];if(l.isCalled())continue;const u=l.tiles.findIndex(m=>m.equals(e)&&e.has(y.RED)==m.has(y.RED));if(u<0)continue;const f=$i(l);c[f]||(c[f]=!0,i.push([o,h,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 l=[...t[o]],u=l[a],f=u.tiles[c].clone({add:n});l[a]=u.clone({replace:{idx:c,tile:f}}),r.push(l)}return r}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,n]of rt({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 Y(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?oe:ft;for(let r of i)if(this.hand.get(n,r)==1)t.push(new Jn(new w(n,r)));else if(this.hand.get(n,r)==2&&e==!1)t.unshift(new Y(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 ee(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,n]of rt())if(this.hand.get(e,n)>=2){const i=this.hand.dec(new Array(2).fill(new w(e,n))),r=this.patternAll().filter(o=>o.length==4).map(o=>(o.unshift(new Y(i[0],i[1])),o));t=[...t,...r],this.hand.inc(i)}return t}patternAll(){const t=[this.handleNumType(p.M),this.handleNumType(p.P),this.handleNumType(p.S),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((n,i)=>i.length-n.length),e=t[0].concat();for(let n=0;n<e.length;n++)for(let i=1;i<t.length;i++)for(const r of t[i])e[n]=[...e[n],...r];return e}handleBack(){const t=[],e=p.BACK,n=this.hand.get(e,0);return n<3?[]:(Array(Math.floor(n/3)).fill(void 0).map(i=>{t.push(new at([new w(e,0),new w(e,0),new w(e,0)]))}),t.length==0?[]:[t])}handleZ(){const t=[];for(const[e,n]of rt({filterBy:[p.Z]}))if(this.hand.get(e,n)!=0){if(this.hand.get(e,n)!=3)return[];t.push(new at([new w(e,n),new w(e,n),new w(e,n)]))}return t.length==0?[]:[t]}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 St([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 at([i[0],i[1],i[2]])),n.push(o)}return n}}const oe=[1,2,3,4,5,6,7],ft=[1,9],we=s=>{var e;const t=s.boardContext;return{...s,hand:s.hand.map(B.deserialize),boardContext:{...t,doraMarkers:t.doraMarkers.map(w.from),blindDoraMarkers:(e=t.blindDoraMarkers)==null?void 0:e.map(w.from)}}};class Wn{constructor(t,e){A(this,"hand");A(this,"cfg");this.hand=t,this.cfg={doras:e.doraMarkers.map(n=>js(n)),blindDoras:e.blindDoraMarkers==null?[]:e.blindDoraMarkers.map(n=>js(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,orig:e}}calc(...t){const e=this.calcPatterns(t);if(e.length==0)return!1;let n=[0,0],i=0;for(let d=0;d<e.length;d++){const g=e[d],_=g.points.reduce((S,D)=>S+D.double,0);_>n[0]?(i=d,n=[_,g.fu]):_==n[0]&&g.fu>n[1]&&(i=d,n=[_,g.fu])}const r=(d,g=100)=>Math.ceil(d/g)*g,o=n[1]!=25?r(n[1],10):25,a=n[0];let c=Math.min(o*2**(a+2),2e3);switch(a){case 26:c=16e3;break;case 13:c=8e3;break;case 12:case 11:c=6e3;break;case 10:case 9:case 8:c=4e3;break;case 7:case 6:c=3e3;break;case 5:c=2e3;break}a>13&&a<26&&(c=8e3);const h=e[i].hand.some(d=>d.tiles.some(g=>g.has(y.TSUMO))),l=this.cfg.orig.myWind,u=l==v.E,f=Z(0);if(h){const d=this.cfg.sticks.dead*100;if(u){const g=r(c*2);f[v.E]+=g*3+d*3,f[v.S]-=g+d,f[v.W]-=g+d,f[v.N]-=g+d}else for(const g of Object.values(v)){if(g==l)continue;const _=g==v.E?2:1,S=r(c*_)+d;f[g]-=S,f[l]+=S}}else{const d=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const _=r(c*(u?6:4))+d;f[l]+=_,f[this.cfg.orig.ronWind]-=_}return f[l]+=1e3*this.cfg.sticks.reach,{deltas:f,sum:a,fu:o,points:e[i].points,point:f[l],hand:e[i].hand,boardContext:this.cfg.orig}}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)];i.length!=0&&e.push({points:i,fu:30,hand:n})}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({points:r,fu:i,hand:n})}return e}minus(){return this.hand.menzen?0:1}dA1(t){return this.cfg.reached==1?[{name:"立直",double:1}]:this.cfg.reached==2?[{name:"ダブル立直",double:2}]:[]}dB1(t){return this.minus()!=0?[]:(this.hand.drawn==null,t.some(n=>n.tiles.some(i=>i.has(y.TSUMO)))?[{name:"門前清自摸和",double:1}]:[])}dC1(t){if(this.minus()!=0)return[];const e="平和",n=this.calcFu(t);return n==20?[{name:e,double:1}]:!t.some(i=>i.tiles.some(r=>r.has(y.TSUMO)))&&n==30?[{name:e,double:1}]:[]}dD1(t){return t.some(n=>n.tiles.some(i=>i.t==p.Z||ft.includes(i.n)))?[]:[{name:"断么九",double:1}]}dE1(t){return this.minus()!=0?[]:Ps(t)==1?[{name:"一盃口",double:1}]:[]}dF1(t){const e=[];return t.forEach(n=>{if(n instanceof Y)return;const i=n.tiles[0];i.t==p.Z&&(i.equals(this.cfg.myWind)?e.push({name:"自風",double:1}):i.equals(this.cfg.roundWind)?e.push({name:"場風",double:1}):i.n==5?e.push({name:"白",double:1}):i.n==6?e.push({name:"發",double:1}):i.n==7&&e.push({name:"中",double:1}))}),e}dG1(t){return this.cfg.oneShotWin?[{name:"一発",double:1}]:[]}dH1(t){return this.cfg.replacementWin?[{name:"嶺上開花",double:1}]:[]}dI1(t){return this.cfg.quadWin?[{name:"搶槓",double:1}]:[]}dJ1(t){return this.cfg.finalWallWin?[{name:"海底摸月",double:1}]:[]}dK1(t){return this.cfg.finalDiscardWin?[{name:"河底撈魚",double: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(y.RED)&&i++}const r=[];return e>0&&r.push({name:"ドラ",double:e}),i>0&&r.push({name:"赤ドラ",double:i}),this.hand.reached&&n>0&&r.push({name:"裏ドラ",double:n}),r}dA2(t){return t.length==7?[{name:"七対子",double:2}]:[]}dB2(t){const e=n=>n instanceof St||n instanceof dt;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 h=new w(r[0],i.n);return e(c)&&h.equals(Dt(c))}),a=t.some(c=>{const h=new w(r[1],i.n);return e(c)&&h.equals(Dt(c))});if(o&&a)return[{name:"三色同順",double:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(n=>n instanceof U||n instanceof ct||n instanceof wt||n instanceof at||n instanceof _t||n instanceof Y)?[{name:"対々和",double:2}]:[]}dD2(t){return this.minus()!=0?[]:t.filter(n=>(n instanceof U||n instanceof at)&&!n.tiles.some(i=>i.has(y.RON))).length>=3?[{name:"三暗刻",double:2}]:[]}dE2(t){return t.filter(n=>n instanceof U||n instanceof ct||n instanceof wt).length>=3?[{name:"三槓子",double:2}]:[]}dF2(t){const e=n=>n instanceof U||n instanceof ct||n instanceof wt||n instanceof at||n instanceof _t;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 h=new w(r[0],i.n);return e(c)&&h.equals(Dt(c))}),a=t.some(c=>{const h=new w(r[1],i.n);return e(c)&&h.equals(Dt(c))});if(o&&a)return[{name:"三色同刻",double:2}]}return[]}dG2(t){return t.filter(n=>{const i=n.tiles[0];return i.t==p.Z&&[5,6,7].includes(i.n)}).length==3?[{name:"小三元",double:2}]:[]}dH2(t){return t.every(n=>{const i=n.tiles[0].t==p.Z?oe:ft;return n.tiles.every(r=>i.includes(r.n))})?[{name:"混老頭",double:2}]:[]}dI2(t){return t.length==7?[]:t.some(n=>n instanceof St||n instanceof dt)?t.some(n=>n.tiles[0].t==p.Z)?t.every(n=>{const i=n.tiles[0].t==p.Z?oe:ft;return n.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",double:2-this.minus()}]:[]:[]:[]}dJ2(t){if(this.minus()!=0)return[];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 St||n instanceof dt)&&(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.filter(i=>i>0).length==n.length)return[{name:"一気通貫",double: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:"混一色",double:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(n=>n instanceof St||n instanceof dt)?t.some(n=>n.tiles[0].t==p.Z)?[]:t.every(n=>n.tiles.some(i=>ft.includes(i.n)))?[{name:"純全帯么九色",double:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:Ps(t)==2?[{name:"ニ盃口",double: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:"清一色",double:6-this.minus()}]}return[]}dA13(t){return t.length!=13?[]:t.some(n=>n instanceof Y&&n.tiles.some(i=>i.has(y.TSUMO)||i.has(y.RON)))?[{name:"国士無双13面待ち",double:26}]:[{name:"国士無双",double:13}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",double:13}]:[]}dC13(t){return t.length==7?[]:t.every(i=>i instanceof U||i instanceof at&&!i.tiles.some(r=>r.has(y.RON))||i instanceof Y)?t.some(i=>i instanceof Y&&i.tiles.every(r=>r.has(y.TSUMO)||r.has(y.RON)))?[{name:"四暗刻単騎待ち",double:26}]:[{name:"四暗刻",double:13}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(i=>!(i instanceof Y)&&i.tiles.some(r=>r.t==p.Z&&e.includes(r.n))).length==3?[{name:"大三元",double:13}]:[]}dE13(t){return t.every(n=>n.tiles[0].t==p.Z)?[{name:"字一色",double:13}]:[]}dF13(t){return t.every(n=>n.tiles.every(i=>i.t!=p.Z&&ft.includes(i.n)))?[{name:"清老頭",double:13}]:[]}dG13(t){return t.filter(n=>n instanceof U||n instanceof ct||n instanceof wt).length==4?[{name:"四槓子",double:13}]:[]}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 Y).tiles.some(r=>r.t==p.Z&&e.includes(r.n))?[{name:"小四喜",double:13}]:[{name:"大四喜",double:13}]:[]}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:"緑一色",double:13}]:[]}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(d=>d.tiles.some(g=>g.has(y.TSUMO)||g.has(y.RON))),a=this.minus()==1,c=o.tiles.some(d=>d.has(y.TSUMO)),h=(d,g)=>{const _=d.tiles[0];return _.t==p.Z&&[5,6,7].includes(_.n)||_.t==p.Z&&[i,r].includes(_.n)||ft.includes(_.n)?g*2:g};for(const d of t)switch(!0){case d instanceof at:const g=d.tiles.some(_=>_.has(y.RON))?2:4;n+=h(d,g);break;case d instanceof _t:n+=h(d,2);break;case(d instanceof wt||d instanceof ct):n+=h(d,8);break;case d instanceof U:n+=h(d,16);break}n+=(d=>{if(d instanceof at)return 0;if(d instanceof Y)return 2;const g=d.tiles,_=g.findIndex(S=>S.has(y.TSUMO)||S.has(y.RON));return _==1||_==0&&g[2].n==9||_==2&&g[0].n==1?2:0})(o);const f=t.find(d=>d instanceof Y).tiles[0];f.t==p.Z&&([5,6,7].includes(f.n)&&(n+=2),f.n==r&&(n+=2),f.n==i&&(n+=2));let m=!1;return!a&&n==20&&(m=!0),c&&!m&&(n+=2),!c&&!a&&(n+=10),!c&&!a&&n==30&&(m=!0),a&&n==20&&(n=30),n}}const $i=s=>s.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),Ps=s=>{const t={};for(const n of s){if(!(n instanceof St))continue;const i=$i(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(Ie)[0],js=s=>{const t=s.n,e=s.t;return new w(e,t%9+1)};class ae{static calcCandidates(t,e,n){O(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=ae.candidateTiles(t,n);t.inc(a);const h=n!=null&&n.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(h.toString(),{shanten:c.shanten,candidates:c.candidates,tile:h}),r=c.shanten):c.shanten==r&&i.set(h.toString(),{shanten:c.shanten,candidates:c.candidates,tile:h})}return Array.from(i.values())}static candidateTiles(t,e){let n=1/0,i=[];const r=new We(t);for(const[o,a]of rt({skipBack:!0,filterBy:e==null?void 0:e.typeFilter})){if(t.get(o,a)>=4)continue;const c=new w(o,a),h=t.inc([c]),l=e!=null&&e.fourSetsOnePair?r.fourSetsOnePair():r.calc();t.dec(h),l<n?(n=l,i=[c]):l==n&&i.push(c)}return{shanten:n,candidates:i}}}const Pn=()=>{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 Bi(s){var r;const t=["RON","DAI_KAN","PON","CHI"],e=s.map(o=>o.choices),i=Pi(e,t).map(o=>s[o]);return{events:i,type:ji(t,(r=i[0])==null?void 0:r.choices)}}function Wi(s){var r;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=s.map(o=>o.choices),i=Pi(e,t).map(o=>s[o]);return{events:i,type:ji(t,(r=i[0])==null?void 0:r.choices)}}function Pi(s,t){let e=[],n=Number.POSITIVE_INFINITY;for(let i=0;i<s.length;i++){const r=s[i];if(oc(r,t)){const o=ac(t,r);o<n?(n=o,e=[i]):o===n&&e.push(i)}}return e}function oc(s,t){return t.some(e=>!!s[e])}function ac(s,t){for(let e=0;e<s.length;e++){const n=s[e];if(t[n])return e}return Number.POSITIVE_INFINITY}function ji(s,t){if(t==null)return!1;for(const e of s)if(t[e])return e;return!1}const _e=()=>{const s=Pn(),t=Pn(),e={emit:s.emit,on:i=>t.on(i)},n={emit:t.emit,on:i=>s.on(i)};return[e,n]},zi=()=>{const s=Pn();return{emit:n=>{s.emit(n)},on:n=>{s.on(n)}}};class ke{constructor(t){A(this,"reachValue",1e3);A(this,"m");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 Te{constructor(t,e){A(this,"pToW",{});A(this,"wToP",Z(""));A(this,"round");A(this,"sticks");this.round=(e==null?void 0:e.round)??j.E1,this.sticks=structuredClone(e==null?void 0: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=kt(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=ve(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 gs(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 Ki{constructor(t=!1){A(this,"c");A(this,"safeMap",Z({},!0));this.disable=t,this.c=this.initial()}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(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,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 ys{constructor(){A(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 O(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 cc(){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 hc(){const s=cc();if(s.__xstate__)return s.__xstate__}const lc=s=>{if(typeof window>"u")return;const t=hc();t&&t.register(s)};class zs{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 Li=".",uc="",Ui="",fc="#",dc="*",Fi="xstate.init",jn="xstate.stop";function pc(s,t){return{type:`xstate.after.${s}.${t}`}}function zn(s,t){return{type:`xstate.done.state.${s}`,output:t}}function mc(s,t){return{type:`xstate.done.actor.${s}`,output:t,actorId:s}}function gc(s,t){return{type:`xstate.error.actor.${s}`,error:t,actorId:s}}function qi(s){return{type:Fi,input:s}}function yt(s){setTimeout(()=>{throw s})}const yc=typeof Symbol=="function"&&Symbol.observable||"@@observable";function Gi(s,t){const e=Ks(s),n=Ks(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?Gi(e[i],n[i]):!1)}function ws(s){if(Yi(s))return s;let t=[],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 Ks(s){if(Xc(s))return s.value;if(typeof s!="string")return s;const t=ws(s);return wc(t)}function wc(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 Ls(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 Zi(s){return Yi(s)?s:[s]}function xt(s){return s===void 0?[]:Zi(s)}function Kn(s,t,e,n){return typeof s=="function"?s({context:t,event:e,self:n}):s}function Yi(s){return Array.isArray(s)}function _c(s){return s.type.startsWith("xstate.error.actor")}function Yt(s){return Zi(s).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function Xi(s){if(!(s===void 0||s===uc))return xt(s)}function Ln(s,t,e){var r,o,a;const n=typeof s=="object",i=n?s:void 0;return{next:(r=n?s.next:s)==null?void 0:r.bind(i),error:(o=n?s.error:t)==null?void 0:o.bind(i),complete:(a=n?s.complete:e)==null?void 0:a.bind(i)}}function Us(s,t){return`${t}.${s}`}function _s(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 Fs(s,t){return`${s.sessionId}.${t}`}let bc=0;function vc(s,t){const e=new Map,n=new Map,i=new WeakMap,r=new Set,o={},{clock:a,logger:c}=t,h={schedule:(f,m,d,g,_=Math.random().toString(36).slice(2))=>{const S={source:f,target:m,event:d,delay:g,id:_,startedAt:Date.now()},D=Fs(f,_);u._snapshot._scheduledEvents[D]=S;const R=a.setTimeout(()=>{delete o[D],delete u._snapshot._scheduledEvents[D],u._relay(f,m,d)},g);o[D]=R},cancel:(f,m)=>{const d=Fs(f,m),g=o[d];delete o[d],delete u._snapshot._scheduledEvents[d],g!==void 0&&a.clearTimeout(g)},cancelAll:f=>{for(const m in u._snapshot._scheduledEvents){const d=u._snapshot._scheduledEvents[m];d.source===f&&h.cancel(f,d.id)}}},l=f=>{if(!r.size)return;const m={...f,rootId:s.sessionId};r.forEach(d=>{var g;return(g=d.next)==null?void 0:g.call(d,m)})},u={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${bc++}`,_register:(f,m)=>(e.set(f,m),f),_unregister:f=>{e.delete(f.sessionId);const m=i.get(f);m!==void 0&&(n.delete(m),i.delete(f))},get:f=>n.get(f),_set:(f,m)=>{const d=n.get(f);if(d&&d!==m)throw new Error(`Actor with system ID '${f}' already exists.`);n.set(f,m),i.set(m,f)},inspect:f=>{const m=Ln(f);return r.add(m),{unsubscribe(){r.delete(m)}}},_sendInspectionEvent:l,_relay:(f,m,d)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:f,actorRef:m,event:d}),m._send(d)},scheduler:h,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const f=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const m in f){const{source:d,target:g,event:_,delay:S,id:D}=f[m];h.schedule(d,g,_,S,D)}},_clock:a,_logger:c};return u}const bs=1;let G=function(s){return s[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Stopped=2]="Stopped",s}({});const Ac={clock:{setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s)},logger:console.log.bind(console),devTools:!1};class Sc{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 zs(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=G.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={...Ac,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:h,inspect:l}=n;this.system=o?o.system:vc(this,{clock:i,logger:r}),l&&!o&&this.system.inspect(Ln(l)),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=n,this.src=n.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 f=this.eventListeners.get(u.type),m=this.eventListeners.get("*");if(!f&&!m)return;const d=new Set([...f?f.values():[],...m?m.values():[]]);for(const g of Array.from(d))g(u)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),h&&(this._systemId=h,this.system._set(h,this)),this._initState((e==null?void 0:e.snapshot)??(e==null?void 0:e.state)),h&&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(n){this._snapshot={status:"error",output:void 0,error:n}}}update(t,e){var i,r;this._snapshot=t;let n;for(;n=this._deferred.shift();)try{n()}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){yt(a)}break;case"done":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){yt(a)}this._stopProcedure(),this._complete(),this._doneEvent=mc(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){var r;const i=Ln(t,e,n);if(this._processingStatus!==G.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{(r=i.complete)==null||r.call(i)}catch(o){yt(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)yt(o);else try{i.error(o)}catch(a){yt(a)}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===G.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=G.Running;const t=qi(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===jn&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===G.Stopped?this:(this.mailbox.clear(),this._processingStatus===G.NotStarted?(this._processingStatus=G.Stopped,this):(this.mailbox.enqueue({type:jn}),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(n){yt(n)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||yt(t);return}let e=!1;for(const n of this.observers){const i=n.error;e||(e=!i);try{i==null||i(t)}catch(r){yt(r)}}this.observers.clear(),e&&yt(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,gc(this.id,t))}_stopProcedure(){return this._processingStatus!==G.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new zs(this._process.bind(this)),this._processingStatus=G.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==G.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:lc)(this)}toJSON(){return{xstate$$type:bs,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[yc](){return this}getSnapshot(){return this._snapshot}}function ce(s,...[t]){return new Sc(s,t)}function xc(s,t,e,n,{sendId:i}){const r=typeof i=="function"?i(e,n):i;return[t,r]}function Ec(s,t){s.defer(()=>{s.system.scheduler.cancel(s.self,t)})}function kc(s){function t(e,n){}return t.type="xstate.cancel",t.sendId=s,t.resolve=xc,t.execute=Ec,t}function Tc(s,t,e,n,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const h=typeof o=="string"?_s(t.machine,o):o,l=typeof i=="function"?i(e):i;let u;return h&&(u=ce(h,{id:l,src:o,parent:s.self,syncSnapshot:c,systemId:r,input:typeof a=="function"?a({context:t.context,event:e.event,self:s.self}):a})),[Kt(t,{children:{...t.children,[l]:u}}),{id:i,actorRef:u}]}function Oc(s,{id:t,actorRef:e}){e&&s.defer(()=>{e._processingStatus!==G.Stopped&&e.start()})}function Ic(...[s,{id:t,systemId:e,input:n,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="snapshot.spawnChild",r.id=t,r.systemId=e,r.src=s,r.input=n,r.syncSnapshot=i,r.resolve=Tc,r.execute=Oc,r}function Nc(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]),[Kt(t,{children:a}),o]}function Dc(s,t){if(t){if(s.system._unregister(t),t._processingStatus!==G.Running){s.stopChild(t);return}s.defer(()=>{s.stopChild(t)})}}function Ji(s){function t(e,n){}return t.type="xstate.stopChild",t.actorRef=s,t.resolve=Nc,t.execute=Dc,t}function vs(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 vs(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 As=s=>s.type==="atomic"||s.type==="final";function he(s){return Object.values(s.states).filter(t=>t.type!=="history")}function Pe(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 Qe(s){const t=new Set(s),e=Qi(t);for(const n of t)if(n.type==="compound"&&(!e.get(n)||!e.get(n).length))qs(n).forEach(i=>t.add(i));else if(n.type==="parallel"){for(const i of he(n))if(i.type!=="history"&&!t.has(i)){const r=qs(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 Vi(s,t){const e=t.get(s);if(!e)return{};if(s.type==="compound"){const i=e[0];if(i){if(As(i))return i.key}else return{}}const n={};for(const i of e)n[i.key]=Vi(i,t);return n}function Qi(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 tr(s,t){const e=Qe(t);return Vi(s,Qi(e))}function Ss(s,t){return t.type==="compound"?he(t).some(e=>e.type==="final"&&s.has(e)):t.type==="parallel"?he(t).every(e=>Ss(s,e)):t.type==="final"}const hn=s=>s[0]===fc;function Cc(s,t){return s.transitions.get(t)||[...s.transitions.keys()].filter(n=>{if(n===dc)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 Mc(s){const t=s.config.after;if(!t)return[];const e=(i,r)=>{const o=pc(i,s.id),a=o.type;return s.entry.push(rh(o,{id:a,delay:i})),s.exit.push(kc(a)),a};return Object.keys(t).flatMap((i,r)=>{const o=t[i],a=typeof o=="string"?{target:o}:o,c=Number.isNaN(+i)?i:+i,h=e(c);return xt(a).map(l=>({...l,event:h,delay:c}))}).map(i=>{const{delay:r}=i;return{...Ht(s,i.event,i),delay:r}})}function Ht(s,t,e){const n=Xi(e.target),i=e.reenter??!1,r=$c(s,n),o={...e,actions:xt(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 Rc(s){const t=new Map;if(s.config.on)for(const e of Object.keys(s.config.on)){if(e===Ui)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=s.config.on[e];t.set(e,Yt(n).map(i=>Ht(s,e,i)))}if(s.config.onDone){const e=`xstate.done.state.${s.id}`;t.set(e,Yt(s.config.onDone).map(n=>Ht(s,e,n)))}for(const e of s.invoke){if(e.onDone){const n=`xstate.done.actor.${e.id}`;t.set(n,Yt(e.onDone).map(i=>Ht(s,n,i)))}if(e.onError){const n=`xstate.error.actor.${e.id}`;t.set(n,Yt(e.onError).map(i=>Ht(s,n,i)))}if(e.onSnapshot){const n=`xstate.snapshot.${e.id}`;t.set(n,Yt(e.onSnapshot).map(i=>Ht(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 Hc(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"?[]:xt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...n,source:`#${s.id}`,target:e?[`#${e.id}`]:[]})};return n}function $c(s,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(hn(e))return s.machine.getStateNodeById(e);const n=e[0]===Li;if(n&&!s.parent)return tn(s,e.slice(1));const i=n?s.key+e:e;if(s.parent)try{return tn(s.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${s.id}':
|
|
8
|
-
${r.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function er(s){const t=Xi(s.config.target);return t?{target:t.map(e=>typeof e=="string"?tn(s.parent,e):e)}:s.parent.initial}function $t(s){return s.type==="history"}function qs(s){const t=nr(s);for(const e of t)for(const n of Pe(e,s))t.add(n);return t}function nr(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 he(n))e(i)}}return e(s),t}function le(s,t){if(hn(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 tn(s,t){if(typeof t=="string"&&hn(t))try{return s.machine.getStateNodeById(t)}catch{}const e=ws(t).slice();let n=s;for(;e.length;){const i=e.shift();if(!i.length)break;n=le(n,i)}return n}function en(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=>le(s,i)).filter(Boolean);return[s.machine.root,s].concat(n,e.reduce((i,r)=>{const o=le(s,r);if(!o)return i;const a=en(o,t[r]);return i.concat(a)},[]))}function Bc(s,t,e,n){const r=le(s,t).next(e,n);return!r||!r.length?s.next(e,n):r}function Wc(s,t,e,n){const i=Object.keys(t),r=le(s,i[0]),o=xs(r,t[i[0]],e,n);return!o||!o.length?s.next(e,n):o}function Pc(s,t,e,n){const i=[];for(const r of Object.keys(t)){const o=t[r];if(!o)continue;const a=le(s,r),c=xs(a,o,e,n);c&&i.push(...c)}return i.length?i:s.next(e,n)}function xs(s,t,e,n){return typeof t=="string"?Bc(s,t,e,n):Object.keys(t).length===1?Wc(s,t,e,n):Pc(s,t,e,n)}function jc(s){return Object.keys(s.states).map(t=>s.states[t]).filter(t=>t.type==="history")}function It(s,t){let e=s;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function zc(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 sr(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(zc(Un([i],t,e),Un([a],t,e)))if(It(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 Kc(s){const[t,...e]=s;for(const n of Pe(t,void 0))if(e.every(i=>It(i,n)))return n}function Es(s,t){if(!s.target)return[];const e=new Set;for(const n of s.target)if($t(n))if(t[n.id])for(const i of t[n.id])e.add(i);else for(const i of Es(er(n),t))e.add(i);else e.add(n);return[...e]}function ir(s,t){const e=Es(s,t);if(!e)return;if(!s.reenter&&e.every(i=>i===s.source||It(i,s.source)))return s.source;const n=Kc(e.concat(s.source));if(n)return n;if(!s.reenter)return s.source.machine.root}function Un(s,t,e){var i;const n=new Set;for(const r of s)if((i=r.target)!=null&&i.length){const o=ir(r,e);r.reenter&&r.source===o&&n.add(o);for(const a of t)It(a,o)&&n.add(a)}return[...n]}function Lc(s,t){if(s.length!==t.size)return!1;for(const e of s)if(!t.has(e))return!1;return!0}function Fn(s,t,e,n,i,r){if(!s.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=sr(s,o,a);let h=t;i||([h,a]=Gc(h,n,e,c,o,a,r)),h=ue(h,n,e,c.flatMap(u=>u.actions),r),h=Fc(h,n,e,c,o,r,a,i);const l=[...o];h.status==="done"&&(h=ue(h,n,e,l.sort((u,f)=>f.order-u.order).flatMap(u=>u.exit),r));try{return a===t.historyValue&&Lc(t._nodes,o)?h:Kt(h,{_nodes:l,historyValue:a})}catch(u){throw u}}function Uc(s,t,e,n,i){if(n.output===void 0)return;const r=zn(i.id,i.output!==void 0&&i.parent?Kn(i.output,s.context,t,e.self):void 0);return Kn(n.output,s.context,r,e.self)}function Fc(s,t,e,n,i,r,o,a){let c=s;const h=new Set,l=new Set;qc(n,o,l,h),a&&l.add(s.machine.root);const u=new Set;for(const f of[...h].sort((m,d)=>m.order-d.order)){i.add(f);const m=[];m.push(...f.entry);for(const d of f.invoke)m.push(Ic(d.src,{...d,syncSnapshot:!!d.onSnapshot}));if(l.has(f)){const d=f.initial.actions;m.push(...d)}if(c=ue(c,t,e,m,r,f.invoke.map(d=>d.id)),f.type==="final"){const d=f.parent;let g=(d==null?void 0:d.type)==="parallel"?d:d==null?void 0:d.parent,_=g||f;for((d==null?void 0:d.type)==="compound"&&r.push(zn(d.id,f.output!==void 0?Kn(f.output,c.context,t,e.self):void 0));(g==null?void 0:g.type)==="parallel"&&!u.has(g)&&Ss(i,g);)u.add(g),r.push(zn(g.id)),_=g,g=g.parent;if(g)continue;c=Kt(c,{status:"done",output:Uc(c,t,e,c.machine.root,_)})}}return c}function qc(s,t,e,n){for(const i of s){const r=ir(i,t);for(const a of i.target||[])!$t(a)&&(i.source!==a||i.source!==r||i.reenter)&&(n.add(a),e.add(a)),Qt(a,t,e,n);const o=Es(i,t);for(const a of o){const c=Pe(a,r);(r==null?void 0:r.type)==="parallel"&&c.push(r),rr(n,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function Qt(s,t,e,n){var i;if($t(s))if(t[s.id]){const r=t[s.id];for(const o of r)n.add(o),Qt(o,t,e,n);for(const o of r)bn(o,s.parent,n,t,e)}else{const r=er(s);for(const o of r.target)n.add(o),r===((i=s.parent)==null?void 0:i.initial)&&e.add(s.parent),Qt(o,t,e,n);for(const o of r.target)bn(o,s.parent,n,t,e)}else if(s.type==="compound"){const[r]=s.initial.target;$t(r)||(n.add(r),e.add(r)),Qt(r,t,e,n),bn(r,s,n,t,e)}else if(s.type==="parallel")for(const r of he(s).filter(o=>!$t(o)))[...n].some(o=>It(o,r))||($t(r)||(n.add(r),e.add(r)),Qt(r,t,e,n))}function rr(s,t,e,n,i){for(const r of n)if((!i||It(r,i))&&s.add(r),r.type==="parallel")for(const o of he(r).filter(a=>!$t(a)))[...s].some(a=>It(a,o))||(s.add(o),Qt(o,t,e,s))}function bn(s,t,e,n,i){rr(e,n,i,Pe(s,t))}function Gc(s,t,e,n,i,r,o){let a=s;const c=Un(n,i,r);c.sort((l,u)=>u.order-l.order);let h;for(const l of c)for(const u of jc(l)){let f;u.history==="deep"?f=m=>As(m)&&It(m,l):f=m=>m.parent===l,h??(h={...r}),h[u.id]=Array.from(i).filter(f)}for(const l of c)a=ue(a,t,e,[...l.exit,...l.invoke.map(u=>Ji(u.id))],o),i.delete(l);return[a,h||r]}let Gs=!1;function or(s,t,e,n,i,r){const{machine:o}=s;let a=s;for(const c of n){let m=function(){e.system._sendInspectionEvent({type:"@xstate.action",actorRef:e.self,action:{type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",params:f}});try{Gs=l,l(u,f)}finally{Gs=!1}};const h=typeof c=="function",l=h?c:o.implementations.actions[typeof c=="string"?c:c.type];if(!l)continue;const u={context:a.context,event:t,self:e.self,system:e.system},f=h||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:t}):c.params:void 0;if(!("resolve"in l)){e.self._processingStatus===G.Running?m():e.defer(()=>{m()});continue}const d=l,[g,_,S]=d.resolve(e,a,u,f,l,i);a=g,"retryResolve"in d&&(r==null||r.push([d,_])),"execute"in d&&(e.self._processingStatus===G.Running?d.execute(e,_):e.defer(d.execute.bind(null,e,_))),S&&(a=or(a,t,e,S,i,r))}return a}function ue(s,t,e,n,i,r){const o=r?[]:void 0,a=or(s,t,e,n,{internalQueue:i,deferredActorIds:r},o);return o==null||o.forEach(([c,h])=>{c.retryResolve(e,a,h)}),a}function vn(s,t,e,n=[]){let i=s;const r=[];function o(h,l,u){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:l,snapshot:h,_transitions:u}),r.push(h)}if(t.type===jn)return i=Kt(Zs(i,t,e),{status:"stopped"}),o(i,t,[]),{snapshot:i,microstates:r};let a=t;if(a.type!==Fi){const h=a,l=_c(h),u=Ys(h,i);if(l&&!u.length)return i=Kt(s,{status:"error",error:h.error}),o(i,h,[]),{snapshot:i,microstates:r};i=Fn(u,s,e,a,!1,n),o(i,h,u)}let c=!0;for(;i.status==="active";){let h=c?Zc(i,a):[];const l=h.length?i:void 0;if(!h.length){if(!n.length)break;a=n.shift(),h=Ys(a,i)}i=Fn(h,i,e,a,!1,n),c=i!==l,o(i,a,h)}return i.status!=="active"&&Zs(i,a,e),{snapshot:i,microstates:r}}function Zs(s,t,e){return ue(s,t,e,Object.values(s.children).map(n=>Ji(n)),[])}function Ys(s,t){return t.machine.getTransitionData(t,s)}function Zc(s,t){const e=new Set,n=s._nodes.filter(As);for(const i of n)t:for(const r of[i].concat(Pe(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||vs(o.guard,s.context,t,s)){e.add(o);break t}}return sr(Array.from(e),new Set(s._nodes),s.historyValue)}function Yc(s,t){const e=Qe(en(s,t));return tr(s,[...e])}function Xc(s){return!!s&&typeof s=="object"&&"machine"in s&&"value"in s}const Jc=function(t){return Gi(t,this.value)},Vc=function(t){return this.tags.has(t)},Qc=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(n=>n.target!==void 0||n.actions.length)},th=function(){const{_nodes:t,tags:e,machine:n,getMeta:i,toJSON:r,can:o,hasTag:a,matches:c,...h}=this;return{...h,tags:Array.from(e)}},eh=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function Fe(s,t){return{status:s.status,output:s.output,error:s.error,machine:t,context:s.context,_nodes:s._nodes,value:tr(t.root,s._nodes),tags:new Set(s._nodes.flatMap(e=>e.tags)),children:s.children,historyValue:s.historyValue||{},matches:Jc,hasTag:Vc,can:Qc,getMeta:eh,toJSON:th}}function Kt(s,t={}){return Fe({...s,...t},s.machine)}function nh(s,t){const{_nodes:e,tags:n,machine:i,children:r,context:o,can:a,hasTag:c,matches:h,getMeta:l,toJSON:u,...f}=s,m={};for(const g in r){const _=r[g];m[g]={snapshot:_.getPersistedSnapshot(t),src:_.src,systemId:_._systemId,syncSnapshot:_._syncSnapshot}}return{...f,context:ar(o),children:m}}function ar(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??(t=Array.isArray(s)?s.slice():{...s}),t[e]={xstate$$type:bs,id:n.id};else{const i=ar(n);i!==n&&(t??(t=Array.isArray(s)?s.slice():{...s}),t[e]=i)}}return t??s}function sh(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 h=typeof i=="function"?i(e,n):i;let l;if(typeof o=="string"){const u=c&&c[o];l=typeof u=="function"?u(e,n):u}else l=typeof o=="function"?o(e,n):o;return typeof l!="number"&&a.push(h),[t,{event:h,id:r,delay:l}]}function ih(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 rh(s,t){function e(n,i){}return e.type="xstate.raise",e.event=s,e.id=t==null?void 0:t.id,e.delay=t==null?void 0:t.delay,e.resolve=sh,e.execute=ih,e}function oh(s,{machine:t,context:e},n,i){const r=(o,a={})=>{const{systemId:c,input:h}=a;if(typeof o=="string"){const l=_s(t,o);if(!l)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const u=ce(l,{id:a.id,parent:s.self,syncSnapshot:a.syncSnapshot,input:typeof h=="function"?h({context:e,event:n,self:s.self}):h,src:o,systemId:c});return i[u.id]=u,u}else return ce(o,{id:a.id,parent:s.self,syncSnapshot:a.syncSnapshot,input:a.input,src:o,systemId:c})};return(o,a)=>{const c=r(o,a);return i[c.id]=c,s.defer(()=>{c._processingStatus!==G.Stopped&&c.start()}),c}}function ah(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:oh(s,t,e.event,r),self:s.self,system:s.system};let a={};if(typeof i=="function")a=i(o,n);else for(const h of Object.keys(i)){const l=i[h];a[h]=typeof l=="function"?l(o,n):l}const c=Object.assign({},t.context,a);return[Kt(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children})]}function ch(s){function t(e,n){}return t.type="xstate.assign",t.assignment=s,t.resolve=ah,t}const Xs=new WeakMap;function Zt(s,t,e){let n=Xs.get(s);return n?t in n||(n[t]=e()):(n={[t]:e()},Xs.set(s,n)),n[t]}const hh={},ge=s=>typeof s=="string"?{type:s}:typeof s=="function"?"resolve"in s?{type:s.type}:{type:s.name}:s;class ks{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(Li),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?Ls(this.config.states,(n,i)=>new ks(n,{_parent:this,_key:i,_machine:this.machine})):hh,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=xt(this.config.entry).slice(),this.exit=xt(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=xt(t.tags).slice()}_initialize(){this.transitions=Rc(this),this.config.always&&(this.always=Yt(this.config.always).map(t=>Ht(this,Ui,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(ge),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ge),eventType:null})}:void 0,history:this.history,states:Ls(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ge)})),entry:this.entry.map(ge),exit:this.exit.map(ge),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 Zt(this,"invoke",()=>xt(this.config.invoke).map((t,e)=>{const{src:n,systemId:i}=t,r=t.id??Us(this.id,e),o=typeof n=="string"?n:`xstate.invoke.${Us(this.id,e)}`;return{...t,src:o,id:r,systemId:i,toJSON(){const{onDone:a,onError:c,...h}=t;return{...h,type:"xstate.invoke",src:o,id:r}}}}))}get on(){return Zt(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 Zt(this,"delayedTransitions",()=>Mc(this))}get initial(){return Zt(this,"initial",()=>Hc(this,this.config.initial))}next(t,e){const n=e.type,i=[];let r;const o=Zt(this,`candidates-${n}`,()=>Cc(this,n));for(const a of o){const{guard:c}=a,h=t.context;let l=!1;try{l=!c||vs(c,h,e,t)}catch(u){const f=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${f?`'${f}' `:""}in transition for event '${n}' in state node '${this.id}':
|
|
9
|
-
|
|
1
|
+
"use strict";var Gs=Object.defineProperty;var Zs=(r,t,e)=>t in r?Gs(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var C=(r,t,e)=>Zs(r,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const en="MS Gothic, sans-serif",ft={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},De={WIDTH:125,HEIGHT:27.5},rs={BASE:40},ut=",",_={M:"m",P:"p",S:"s",Z:"z",BACK:"_"},A={TSUMO:"t",RON:"v",DORA:"d",HORIZONTAL:"-",RED:"r",COLOR_GRAYSCALE:"^"},S={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"},R={E:"1w",S:"2w",W:"3w",N:"4w"},L={E1:"1w1",E2:"1w2",E3:"1w3",E4:"1w4",S1:"2w1",S2:"2w2",S3:"2w3",S4:"2w4",W1:"3w1",W2:"3w2",W3:"3w3",W4:"3w4",N1:"4w1",N2:"4w2",N3:"4w3",N4:"4w4"},fe={[R.E]:"東",[R.S]:"南",[R.W]:"西",[R.N]:"北"},nn={[L.E1]:"東1局",[L.E2]:"東2局",[L.E3]:"東3局",[L.E4]:"東4局",[L.S1]:"南1局",[L.S2]:"南2局",[L.S3]:"南3局",[L.S4]:"南4局",[L.W1]:"西1局",[L.W2]:"西2局",[L.W3]:"西3局",[L.W4]:"西4局",[L.N1]:"北1局",[L.N2]:"北2局",[L.N3]:"北3局",[L.N4]:"北4局"};function H(r,t){if(!r)throw new Error(t)}class qs{constructor(t="東",e="2"){C(this,"ctx",null);C(this,"strText");C(this,"numText");C(this,"measure",(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),H(this.ctx,"context is null"));const n=this.ctx;n.font=e;const s=n.measureText(t);let i=s.width,o=s.actualBoundingBoxAscent+s.actualBoundingBoxDescent;return[i,o]});C(this,"measureFontContext",(t,e)=>{const n={family:t,size:e},s=`${n.size}px ${n.family}`,[i,o]=this.measure(this.strText,s),[a,c]=this.measure(this.numText,s);return{font:{family:t,size:e},textWidth:i,textHeight:o,numWidth:a,numHeight:c}});C(this,"measureTableFontContext",t=>{const e=this.measureFontContext(en,rs.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e});this.strText=t,this.numText=e}}class Xs{constructor(t){C(this,"input");C(this,"position");C(this,"nextPosition");C(this,"char");C(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 Jt=(r,t)=>{if(r.t==t.t){if(j(r)&&j(t)){if(r.has(A.RED))return-1;if(t.has(A.RED))return 1}return r.n-t.n}const e={[_.M]:1,[_.P]:2,[_.S]:3,[_.Z]:4,[_.BACK]:5};return e[r.t]-e[t.t]},Vs=(r,t)=>{const e={[A.HORIZONTAL]:1,[A.TSUMO]:2,[A.RON]:3,[A.DORA]:4,[A.COLOR_GRAYSCALE]:5,[A.RED]:6};return e[r]-e[t]},is=r=>{const t=[];r.forEach((n,s)=>{n.has(A.HORIZONTAL)&&t.push(s)});const e=r.filter(n=>!n.has(A.HORIZONTAL)).sort(Jt);return t.forEach(n=>{e.splice(n,0,r[n])}),e};function j(r){return r.isNum()&&r.n==5}function Js(r){for(const t of Object.values(_))if(t==r)return[t,!0];return[_.BACK,!1]}class v{constructor(t,e,n=[]){this.t=t,this.n=e,this.ops=n}static from(t){const e=new Z(t).tiles();if(e.length!=1)throw new Error(`input is not a single tile ${t}`);return e[0]}toString(){return this.t===_.BACK?this.t:`${[...this.ops].sort(Vs).join("")}${this.n}${this.t}`}toJSON(){return this.toString()}clone(t){const e=(t==null?void 0:t.t)??this.t,n=(t==null?void 0:t.n)??this.n,s=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),i=new Set([...s]);return t!=null&&t.add&&(Array.isArray(t.add)?t.add.forEach(o=>i.add(o)):i.add(t.add)),new v(e,n,Array.from(i))}has(t){return this.ops.includes(t)}isNum(){return this.t==_.M||this.t==_.P||this.t==_.S}equals(t){return t.t==_.BACK&&this.t==_.BACK?!0:this.t==t.t&&this.n==t.n}}class K{constructor(t,e){C(this,"_tiles");C(this,"_type");if(this._tiles=t,this._type=e,this.isCalled()){this._tiles=is(this._tiles);return}if(this._type!=S.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Jt);return}}static deserialize(t){const e=new Z(t.tiles).parse();if(e.length!=1)throw new Error(`block must be 1: ${t.tiles}`);const n=e[0].type;if(!(t.type==S.PAIR||t.type==S.ISOLATED||t.type==S.THREE||t.type==S.RUN)&&n!=t.type)throw new Error(`input type is ${t.type} but got is ${n}: ${t.tiles}`);return ae(e[0].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[S.PON.toString(),S.CHI.toString(),S.DAI_KAN.toString(),S.SHO_KAN.toString(),S.AN_KAN.toString()].includes(this._type.toString())}clone(t){const e=t==null?void 0:t.replace,n=[...this.tiles];return e&&(n[e.idx]=e.tile),ae(n,this._type)}}const It=r=>{let t="";for(const e of r){if(e.t==_.BACK)return r.join("");t+=e.toString().slice(0,-1)}return`${t}${r[0].t}`},sn=r=>{let t=r[0].t,e="";for(const s of r){const i=s.t,o=i==_.BACK?s.toString():s.toString().slice(0,-1);i!=t&&t!=_.BACK&&(e+=t),t=i,e+=o}const n=r.at(-1);return n.t!=_.BACK&&(e+=n.t),e};class it extends K{constructor(t){super(t,S.CHI)}static from(t){return K.deserialize({tiles:t,type:S.CHI})}toString(){return It(this.tiles)}}class lt extends K{constructor(t){super(t,S.PON)}static from(t){return K.deserialize({tiles:t,type:S.PON})}toString(){return It(this.tiles)}}class z extends K{constructor(t){const e=t.filter(s=>s.t!=_.BACK),n=e[0];if(e.length<t.length){if(j(n)){const s=new v(n.t,5);super([s.clone({add:A.RED}),s,s,s],S.AN_KAN);return}super([n,n,n,n],S.AN_KAN);return}super(t,S.AN_KAN)}get tilesWithBack(){const t=this.tiles[0].clone({remove:A.RED}),e=j(t)?t.clone({add:A.RED}):t;return[new v(_.BACK,0),e,t,new v(_.BACK,0)]}static from(t){return K.deserialize({tiles:t,type:S.AN_KAN})}toString(){return sn(this.tilesWithBack)}}class ct extends K{constructor(t){super(t,S.DAI_KAN)}static from(t){return K.deserialize({tiles:t,type:S.DAI_KAN})}toString(){return It(this.tiles)}}class tt extends K{constructor(t){super(t,S.SHO_KAN)}static from(t){return K.deserialize({tiles:t,type:S.SHO_KAN})}toString(){return It(this.tiles)}}class G extends K{constructor(t,e){super([t,e],S.PAIR)}toString(){return It(this.tiles)}}class Q extends K{constructor(t){super(t,S.THREE)}static from(t){return K.deserialize({tiles:t,type:S.THREE})}toString(){return It(this.tiles)}}class ht extends K{constructor(t){super(t,S.RUN)}static from(t){return K.deserialize({tiles:t,type:S.RUN})}toString(){return It(this.tiles)}}class rn extends K{constructor(t){super([t],S.ISOLATED)}toString(){return this.tiles[0].toString()}}class Mt extends K{constructor(t){super(t,S.HAND)}toString(){return sn(this.tiles)}}class on extends K{constructor(t,e){super(t,e)}toString(){return this.is(S.IMAGE_DISCARD)?this.tiles.join(""):sn(this.tiles)}}const ae=(r,t)=>{switch(t){case S.CHI:return new it([r[0],r[1],r[2]]);case S.PON:return new lt([r[0],r[1],r[2]]);case S.AN_KAN:return new z(r);case S.DAI_KAN:return new ct(r);case S.SHO_KAN:return new tt(r);case S.THREE:return new Q(r);case S.RUN:return new ht(r);case S.PAIR:return new G(r[0],r[1]);case S.ISOLATED:return new rn(r[0]);case S.HAND:return new Mt(r);default:return new on(r,t)}};class Z{constructor(t){C(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!=ut)}tileSeparators(){const t=new Xs(this.input),e=[];let n=[];for(this.validate(this.input);;){t.skipWhitespace();const s=t.char;if(s===t.eof)break;if(s==ut){e.push(ut),t.readChar();continue}const[i,o]=Cn(s,n);if(o){if(i==_.BACK){e.push(new v(i,0)),t.readChar();continue}e.push(...Qs(n,i)),n=[],t.readChar();continue}else{const[a,c]=tr(t);if(c){n.push(a),t.readChar();continue}const[l,u]=os(s);if(!u)throw new Error(`encounter unexpected number. n: ${l}, current: ${s}, 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==ut){const a=kn(e),c=ae(e,a);n.push(c),e=[];continue}e.push(o)}const s=kn(e),i=ae(e,s);return n.push(i),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,s]=Cn(e,[new v(_.BACK,1)]);if(!s)throw new Error(`last character(${e}) is not type value`)}}function kn(r){if(r.length===0)return S.UNKNOWN;if(r.length===1)return r[0].has(A.DORA)?S.IMAGE_DORA:r[0].has(A.TSUMO)?S.TSUMO:S.HAND;const t=r.every(i=>i.equals(r[0])),e=r.filter(i=>i.has(A.HORIZONTAL)).length,n=r.filter(i=>i.has(A.TSUMO)||i.has(A.DORA)).length,s=r.filter(i=>i.t==_.BACK).length;if(n>0)return S.UNKNOWN;if(e==0&&s==0)return S.HAND;if(r.length===3&&s===0)return t?S.PON:e==1&&Ys(r)?S.CHI:S.IMAGE_DISCARD;if(r.length==4&&s==2)return S.AN_KAN;if(r.length==4&&t){if(e==1)return S.DAI_KAN;if(e==2)return S.SHO_KAN}return e==1||n==0?S.IMAGE_DISCARD:S.UNKNOWN}function Ys(r){const t=[...r].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 Qs(r,t){return r.map(e=>{const n=new v(t,e.n,e.ops);return n.isNum()&&n.n==0?n.clone({n:5,add:A.RED}):n})}function Cn(r,t){const[e,n]=Js(r);if(n)return[e,!0];if((r==="w"||r==="d")&&t.length>0){for(let i=0;i<t.length;i++){const o=t[i];r==="d"&&(t[i].n=o.n+4)}return[_.Z,!0]}return[_.BACK,!1]}function os(r){const t=Number(r),e=0<=t&&t<=9;return[t,e]}function tr(r){const t=Object.values(A);if(!t.includes(r.char))return[new v(_.BACK,0),!1];const e=[];for(let n=0;n<4;n++){const s=r.peekCharN(n);if(t.includes(s))e.push(s);else{const[i,o]=os(s);if(!o)break;for(const c of e)r.readChar();const a=new v(_.BACK,i,e);if(a.has(A.RED)&&a.n!=5)throw new Error(`found ${A.RED} but number is not 5: ${i}`);if(a.has(A.DORA)&&a.has(A.TSUMO))throw new Error(`unable to specify both ${A.DORA} and ${A.TSUMO}`);return[a,!0]}}return[new v(_.BACK,0),!1]}function F(r,t=!1){const e={[R.E]:r,[R.S]:r,[R.W]:r,[R.N]:r};if(t)for(let n of Object.values(R))e[n]=structuredClone(r);return e}const Zt=r=>{let t=r.substring(0,2),e=Number(r.substring(2,3));return e==4?(e=1,t=pt(t)):e++,`${t}${e}`},er=r=>Zt(Zt(Zt(r))),pt=r=>{let t=Number(r.toString()[0]);return t=t%4+1,`${t}w`},an=r=>{let t=Number(r.toString()[0]);return t=t%2+1,`${t}w`},Ke=(r,t,e)=>{const n=Math.abs(Number(r[0])-Number(t[0]));return H(n==1||n==2||n==3),e==S.PON?n==3?0:n==2?1:2:n==3?0:n==1?3:2};function Rn(r){return typeof r>"u"}function Le(r,t=0){return{a:1,c:0,e:r,b:0,d:1,f:t}}function cn(...r){r=Array.isArray(r[0])?r[0]:r;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(r.length){case 0:throw new Error("no matrices provided");case 1:return r[0];case 2:return t(r[0],r[1]);default:{const[e,n,...s]=r,i=t(e,n);return cn(i,...s)}}}function nr(...r){return cn(...r)}const{cos:sr,sin:rr,PI:ir}=Math;function or(r,t,e){const n=sr(r),s=rr(r),i={a:n,c:-s,e:0,b:s,d:n,f:0};return Rn(t)||Rn(e)?i:cn([Le(t,e),i,Le(-t,-e)])}function ar(r,t=void 0,e=void 0){return or(r*ir/180,t,e)}function cr(r){return lr(r)}function lr(r){return`matrix(${r.a},${r.b},${r.c},${r.d},${r.e},${r.f})`}function ur(r,t){function e(){this.constructor=r}e.prototype=t.prototype,r.prototype=new e}function pe(r,t,e,n){var s=Error.call(this,r);return Object.setPrototypeOf&&Object.setPrototypeOf(s,pe.prototype),s.expected=t,s.found=e,s.location=n,s.name="SyntaxError",s}ur(pe,Error);function _e(r,t,e){return e=e||" ",r.length>t?r:(t-=r.length,e+=e.repeat(t),r+e.slice(0,t))}pe.prototype.format=function(r){var t="Error: "+this.message;if(this.location){var e=null,n;for(n=0;n<r.length;n++)if(r[n].source===this.location.source){e=r[n].text.split(/\r\n|\n|\r/g);break}var s=this.location.start,i=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(s):s,o=this.location.source+":"+i.line+":"+i.column;if(e){var a=this.location.end,c=_e("",i.line.toString().length," "),l=e[s.line-1],u=s.line===a.line?a.column:l.length+1,h=u-s.column||1;t+=`
|
|
2
|
+
--> `+o+`
|
|
3
|
+
`+c+` |
|
|
4
|
+
`+i.line+" | "+l+`
|
|
5
|
+
`+c+" | "+_e("",s.column-1," ")+_e("",h,"^")}else t+=`
|
|
6
|
+
at `+o}return t};pe.buildMessage=function(r,t){var e={literal:function(l){return'"'+s(l.text)+'"'},class:function(l){var u=l.parts.map(function(h){return Array.isArray(h)?i(h[0])+"-"+i(h[1]):i(h)});return"["+(l.inverted?"^":"")+u.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(l){return l.description}};function n(l){return l.charCodeAt(0).toString(16).toUpperCase()}function s(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(u){return"\\x0"+n(u)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(u){return"\\x"+n(u)})}function i(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(u){return"\\x0"+n(u)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(u){return"\\x"+n(u)})}function o(l){return e[l.type](l)}function a(l){var u=l.map(o),h,d;if(u.sort(),u.length>0){for(h=1,d=1;h<u.length;h++)u[h-1]!==u[h]&&(u[d]=u[h],d++);u.length=d}switch(u.length){case 1:return u[0];case 2:return u[0]+" or "+u[1];default:return u.slice(0,-1).join(", ")+", or "+u[u.length-1]}}function c(l){return l?'"'+s(l)+'"':"end of input"}return"Expected "+a(r)+" but "+c(t)+" found."};var Ae={},Ee={},xn;function ln(){return xn||(xn=1,function(r){const t=":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",e=t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+t+"]["+e+"]*",s=new RegExp("^"+n+"$"),i=function(a,c){const l=[];let u=c.exec(a);for(;u;){const h=[];h.startIndex=c.lastIndex-u[0].length;const d=u.length;for(let p=0;p<d;p++)h.push(u[p]);l.push(h),u=c.exec(a)}return l},o=function(a){const c=s.exec(a);return!(c===null||typeof c>"u")};r.isExist=function(a){return typeof a<"u"},r.isEmptyObject=function(a){return Object.keys(a).length===0},r.merge=function(a,c,l){if(c){const u=Object.keys(c),h=u.length;for(let d=0;d<h;d++)l==="strict"?a[u[d]]=[c[u[d]]]:a[u[d]]=c[u[d]]}},r.getValue=function(a){return r.isExist(a)?a:""},r.isName=o,r.getAllMatches=i,r.nameRegexp=n}(Ee)),Ee}var Mn;function as(){if(Mn)return Ae;Mn=1;const r=ln(),t={allowBooleanAttributes:!1,unpairedTags:[]};Ae.validate=function(f,w){w=Object.assign({},t,w);const T=[];let $=!1,m=!1;f[0]==="\uFEFF"&&(f=f.substr(1));for(let b=0;b<f.length;b++)if(f[b]==="<"&&f[b+1]==="?"){if(b+=2,b=n(f,b),b.err)return b}else if(f[b]==="<"){let E=b;if(b++,f[b]==="!"){b=s(f,b);continue}else{let M=!1;f[b]==="/"&&(M=!0,b++);let N="";for(;b<f.length&&f[b]!==">"&&f[b]!==" "&&f[b]!==" "&&f[b]!==`
|
|
7
|
+
`&&f[b]!=="\r";b++)N+=f[b];if(N=N.trim(),N[N.length-1]==="/"&&(N=N.substring(0,N.length-1),b--),!g(N)){let x;return N.trim().length===0?x="Invalid space after '<'.":x="Tag '"+N+"' is an invalid name.",d("InvalidTag",x,y(f,b))}const k=a(f,b);if(k===!1)return d("InvalidAttr","Attributes for '"+N+"' have open quote.",y(f,b));let P=k.value;if(b=k.index,P[P.length-1]==="/"){const x=b-P.length;P=P.substring(0,P.length-1);const I=l(P,w);if(I===!0)$=!0;else return d(I.err.code,I.err.msg,y(f,x+I.err.line))}else if(M)if(k.tagClosed){if(P.trim().length>0)return d("InvalidTag","Closing tag '"+N+"' can't have attributes or invalid starting.",y(f,E));if(T.length===0)return d("InvalidTag","Closing tag '"+N+"' has not been opened.",y(f,E));{const x=T.pop();if(N!==x.tagName){let I=y(f,x.tagStartPos);return d("InvalidTag","Expected closing tag '"+x.tagName+"' (opened in line "+I.line+", col "+I.col+") instead of closing tag '"+N+"'.",y(f,E))}T.length==0&&(m=!0)}}else return d("InvalidTag","Closing tag '"+N+"' doesn't have proper closing.",y(f,b));else{const x=l(P,w);if(x!==!0)return d(x.err.code,x.err.msg,y(f,b-P.length+x.err.line));if(m===!0)return d("InvalidXml","Multiple possible root nodes found.",y(f,b));w.unpairedTags.indexOf(N)!==-1||T.push({tagName:N,tagStartPos:E}),$=!0}for(b++;b<f.length;b++)if(f[b]==="<")if(f[b+1]==="!"){b++,b=s(f,b);continue}else if(f[b+1]==="?"){if(b=n(f,++b),b.err)return b}else break;else if(f[b]==="&"){const x=h(f,b);if(x==-1)return d("InvalidChar","char '&' is not expected.",y(f,b));b=x}else if(m===!0&&!e(f[b]))return d("InvalidXml","Extra text at the end",y(f,b));f[b]==="<"&&b--}}else{if(e(f[b]))continue;return d("InvalidChar","char '"+f[b]+"' is not expected.",y(f,b))}if($){if(T.length==1)return d("InvalidTag","Unclosed tag '"+T[0].tagName+"'.",y(f,T[0].tagStartPos));if(T.length>0)return d("InvalidXml","Invalid '"+JSON.stringify(T.map(b=>b.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return d("InvalidXml","Start tag expected.",1);return!0};function e(f){return f===" "||f===" "||f===`
|
|
8
|
+
`||f==="\r"}function n(f,w){const T=w;for(;w<f.length;w++)if(f[w]=="?"||f[w]==" "){const $=f.substr(T,w-T);if(w>5&&$==="xml")return d("InvalidXml","XML declaration allowed only at the start of the document.",y(f,w));if(f[w]=="?"&&f[w+1]==">"){w++;break}else continue}return w}function s(f,w){if(f.length>w+5&&f[w+1]==="-"&&f[w+2]==="-"){for(w+=3;w<f.length;w++)if(f[w]==="-"&&f[w+1]==="-"&&f[w+2]===">"){w+=2;break}}else if(f.length>w+8&&f[w+1]==="D"&&f[w+2]==="O"&&f[w+3]==="C"&&f[w+4]==="T"&&f[w+5]==="Y"&&f[w+6]==="P"&&f[w+7]==="E"){let T=1;for(w+=8;w<f.length;w++)if(f[w]==="<")T++;else if(f[w]===">"&&(T--,T===0))break}else if(f.length>w+9&&f[w+1]==="["&&f[w+2]==="C"&&f[w+3]==="D"&&f[w+4]==="A"&&f[w+5]==="T"&&f[w+6]==="A"&&f[w+7]==="["){for(w+=8;w<f.length;w++)if(f[w]==="]"&&f[w+1]==="]"&&f[w+2]===">"){w+=2;break}}return w}const i='"',o="'";function a(f,w){let T="",$="",m=!1;for(;w<f.length;w++){if(f[w]===i||f[w]===o)$===""?$=f[w]:$!==f[w]||($="");else if(f[w]===">"&&$===""){m=!0;break}T+=f[w]}return $!==""?!1:{value:T,index:w,tagClosed:m}}const c=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function l(f,w){const T=r.getAllMatches(f,c),$={};for(let m=0;m<T.length;m++){if(T[m][1].length===0)return d("InvalidAttr","Attribute '"+T[m][2]+"' has no space in starting.",O(T[m]));if(T[m][3]!==void 0&&T[m][4]===void 0)return d("InvalidAttr","Attribute '"+T[m][2]+"' is without value.",O(T[m]));if(T[m][3]===void 0&&!w.allowBooleanAttributes)return d("InvalidAttr","boolean attribute '"+T[m][2]+"' is not allowed.",O(T[m]));const b=T[m][2];if(!p(b))return d("InvalidAttr","Attribute '"+b+"' is an invalid name.",O(T[m]));if(!$.hasOwnProperty(b))$[b]=1;else return d("InvalidAttr","Attribute '"+b+"' is repeated.",O(T[m]))}return!0}function u(f,w){let T=/\d/;for(f[w]==="x"&&(w++,T=/[\da-fA-F]/);w<f.length;w++){if(f[w]===";")return w;if(!f[w].match(T))break}return-1}function h(f,w){if(w++,f[w]===";")return-1;if(f[w]==="#")return w++,u(f,w);let T=0;for(;w<f.length;w++,T++)if(!(f[w].match(/\w/)&&T<20)){if(f[w]===";")break;return-1}return w}function d(f,w,T){return{err:{code:f,msg:w,line:T.line||T,col:T.col}}}function p(f){return r.isName(f)}function g(f){return r.isName(f)}function y(f,w){const T=f.substring(0,w).split(/\r?\n/);return{line:T.length,col:T[T.length-1].length+1}}function O(f){return f.startIndex+f[1].length}return Ae}var ee={},$n;function hr(){if($n)return ee;$n=1;const r={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(e,n){return n},attributeValueProcessor:function(e,n){return n},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,n,s){return e}},t=function(e){return Object.assign({},r,e)};return ee.buildOptions=t,ee.defaultOptions=r,ee}var Ne,Pn;function dr(){if(Pn)return Ne;Pn=1;class r{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,n){e==="__proto__"&&(e="#__proto__"),this.child.push({[e]:n})}addChild(e){e.tagname==="__proto__"&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}}return Ne=r,Ne}var ve,Hn;function fr(){if(Hn)return ve;Hn=1;const r=ln();function t(l,u){const h={};if(l[u+3]==="O"&&l[u+4]==="C"&&l[u+5]==="T"&&l[u+6]==="Y"&&l[u+7]==="P"&&l[u+8]==="E"){u=u+9;let d=1,p=!1,g=!1,y="";for(;u<l.length;u++)if(l[u]==="<"&&!g){if(p&&s(l,u)){u+=7;let O,f;[O,f,u]=e(l,u+1),f.indexOf("&")===-1&&(h[c(O)]={regx:RegExp(`&${O};`,"g"),val:f})}else if(p&&i(l,u))u+=8;else if(p&&o(l,u))u+=8;else if(p&&a(l,u))u+=9;else if(n)g=!0;else throw new Error("Invalid DOCTYPE");d++,y=""}else if(l[u]===">"){if(g?l[u-1]==="-"&&l[u-2]==="-"&&(g=!1,d--):d--,d===0)break}else l[u]==="["?p=!0:y+=l[u];if(d!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:h,i:u}}function e(l,u){let h="";for(;u<l.length&&l[u]!=="'"&&l[u]!=='"';u++)h+=l[u];if(h=h.trim(),h.indexOf(" ")!==-1)throw new Error("External entites are not supported");const d=l[u++];let p="";for(;u<l.length&&l[u]!==d;u++)p+=l[u];return[h,p,u]}function n(l,u){return l[u+1]==="!"&&l[u+2]==="-"&&l[u+3]==="-"}function s(l,u){return l[u+1]==="!"&&l[u+2]==="E"&&l[u+3]==="N"&&l[u+4]==="T"&&l[u+5]==="I"&&l[u+6]==="T"&&l[u+7]==="Y"}function i(l,u){return l[u+1]==="!"&&l[u+2]==="E"&&l[u+3]==="L"&&l[u+4]==="E"&&l[u+5]==="M"&&l[u+6]==="E"&&l[u+7]==="N"&&l[u+8]==="T"}function o(l,u){return l[u+1]==="!"&&l[u+2]==="A"&&l[u+3]==="T"&&l[u+4]==="T"&&l[u+5]==="L"&&l[u+6]==="I"&&l[u+7]==="S"&&l[u+8]==="T"}function a(l,u){return l[u+1]==="!"&&l[u+2]==="N"&&l[u+3]==="O"&&l[u+4]==="T"&&l[u+5]==="A"&&l[u+6]==="T"&&l[u+7]==="I"&&l[u+8]==="O"&&l[u+9]==="N"}function c(l){if(r.isName(l))return l;throw new Error(`Invalid entity name ${l}`)}return ve=t,ve}var Se,Bn;function pr(){if(Bn)return Se;Bn=1;const r=/^[-+]?0x[a-fA-F0-9]+$/,t=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);const e={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function n(i,o={}){if(o=Object.assign({},e,o),!i||typeof i!="string")return i;let a=i.trim();if(o.skipLike!==void 0&&o.skipLike.test(a))return i;if(o.hex&&r.test(a))return Number.parseInt(a,16);{const c=t.exec(a);if(c){const l=c[1],u=c[2];let h=s(c[3]);const d=c[4]||c[6];if(!o.leadingZeros&&u.length>0&&l&&a[2]!==".")return i;if(!o.leadingZeros&&u.length>0&&!l&&a[1]!==".")return i;{const p=Number(a),g=""+p;return g.search(/[eE]/)!==-1||d?o.eNotation?p:i:a.indexOf(".")!==-1?g==="0"&&h===""||g===h||l&&g==="-"+h?p:i:u?h===g||l+h===g?p:i:a===g||a===l+g?p:i}}else return i}}function s(i){return i&&i.indexOf(".")!==-1&&(i=i.replace(/0+$/,""),i==="."?i="0":i[0]==="."?i="0"+i:i[i.length-1]==="."&&(i=i.substr(0,i.length-1))),i}return Se=n,Se}var Te,Wn;function cs(){if(Wn)return Te;Wn=1;function r(t){return typeof t=="function"?t:Array.isArray(t)?e=>{for(const n of t)if(typeof n=="string"&&e===n||n instanceof RegExp&&n.test(e))return!0}:()=>!1}return Te=r,Te}var Ie,Dn;function gr(){if(Dn)return Ie;Dn=1;const r=ln(),t=dr(),e=fr(),n=pr(),s=cs();class i{constructor(b){this.options=b,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,M)=>String.fromCharCode(Number.parseInt(M,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,M)=>String.fromCharCode(Number.parseInt(M,16))}},this.addExternalEntities=o,this.parseXml=h,this.parseTextData=a,this.resolveNameSpace=c,this.buildAttributesMap=u,this.isItStopNode=y,this.replaceEntitiesValue=p,this.readStopNodeData=T,this.saveTextToParentTag=g,this.addChild=d,this.ignoreAttributesFn=s(this.options.ignoreAttributes)}}function o(m){const b=Object.keys(m);for(let E=0;E<b.length;E++){const M=b[E];this.lastEntities[M]={regex:new RegExp("&"+M+";","g"),val:m[M]}}}function a(m,b,E,M,N,k,P){if(m!==void 0&&(this.options.trimValues&&!M&&(m=m.trim()),m.length>0)){P||(m=this.replaceEntitiesValue(m));const x=this.options.tagValueProcessor(b,m,E,N,k);return x==null?m:typeof x!=typeof m||x!==m?x:this.options.trimValues?$(m,this.options.parseTagValue,this.options.numberParseOptions):m.trim()===m?$(m,this.options.parseTagValue,this.options.numberParseOptions):m}}function c(m){if(this.options.removeNSPrefix){const b=m.split(":"),E=m.charAt(0)==="/"?"/":"";if(b[0]==="xmlns")return"";b.length===2&&(m=E+b[1])}return m}const l=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function u(m,b,E){if(this.options.ignoreAttributes!==!0&&typeof m=="string"){const M=r.getAllMatches(m,l),N=M.length,k={};for(let P=0;P<N;P++){const x=this.resolveNameSpace(M[P][1]);if(this.ignoreAttributesFn(x,b))continue;let I=M[P][4],D=this.options.attributeNamePrefix+x;if(x.length)if(this.options.transformAttributeName&&(D=this.options.transformAttributeName(D)),D==="__proto__"&&(D="#__proto__"),I!==void 0){this.options.trimValues&&(I=I.trim()),I=this.replaceEntitiesValue(I);const B=this.options.attributeValueProcessor(x,I,b);B==null?k[D]=I:typeof B!=typeof I||B!==I?k[D]=B:k[D]=$(I,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(k[D]=!0)}if(!Object.keys(k).length)return;if(this.options.attributesGroupName){const P={};return P[this.options.attributesGroupName]=k,P}return k}}const h=function(m){m=m.replace(/\r\n?/g,`
|
|
9
|
+
`);const b=new t("!xml");let E=b,M="",N="";for(let k=0;k<m.length;k++)if(m[k]==="<")if(m[k+1]==="/"){const x=f(m,">",k,"Closing Tag is not closed.");let I=m.substring(k+2,x).trim();if(this.options.removeNSPrefix){const Y=I.indexOf(":");Y!==-1&&(I=I.substr(Y+1))}this.options.transformTagName&&(I=this.options.transformTagName(I)),E&&(M=this.saveTextToParentTag(M,E,N));const D=N.substring(N.lastIndexOf(".")+1);if(I&&this.options.unpairedTags.indexOf(I)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${I}>`);let B=0;D&&this.options.unpairedTags.indexOf(D)!==-1?(B=N.lastIndexOf(".",N.lastIndexOf(".")-1),this.tagsNodeStack.pop()):B=N.lastIndexOf("."),N=N.substring(0,B),E=this.tagsNodeStack.pop(),M="",k=x}else if(m[k+1]==="?"){let x=w(m,k,!1,"?>");if(!x)throw new Error("Pi Tag is not closed.");if(M=this.saveTextToParentTag(M,E,N),!(this.options.ignoreDeclaration&&x.tagName==="?xml"||this.options.ignorePiTags)){const I=new t(x.tagName);I.add(this.options.textNodeName,""),x.tagName!==x.tagExp&&x.attrExpPresent&&(I[":@"]=this.buildAttributesMap(x.tagExp,N,x.tagName)),this.addChild(E,I,N)}k=x.closeIndex+1}else if(m.substr(k+1,3)==="!--"){const x=f(m,"-->",k+4,"Comment is not closed.");if(this.options.commentPropName){const I=m.substring(k+4,x-2);M=this.saveTextToParentTag(M,E,N),E.add(this.options.commentPropName,[{[this.options.textNodeName]:I}])}k=x}else if(m.substr(k+1,2)==="!D"){const x=e(m,k);this.docTypeEntities=x.entities,k=x.i}else if(m.substr(k+1,2)==="!["){const x=f(m,"]]>",k,"CDATA is not closed.")-2,I=m.substring(k+9,x);M=this.saveTextToParentTag(M,E,N);let D=this.parseTextData(I,E.tagname,N,!0,!1,!0,!0);D==null&&(D=""),this.options.cdataPropName?E.add(this.options.cdataPropName,[{[this.options.textNodeName]:I}]):E.add(this.options.textNodeName,D),k=x+2}else{let x=w(m,k,this.options.removeNSPrefix),I=x.tagName;const D=x.rawTagName;let B=x.tagExp,Y=x.attrExpPresent,In=x.closeIndex;this.options.transformTagName&&(I=this.options.transformTagName(I)),E&&M&&E.tagname!=="!xml"&&(M=this.saveTextToParentTag(M,E,N,!1));const On=E;if(On&&this.options.unpairedTags.indexOf(On.tagname)!==-1&&(E=this.tagsNodeStack.pop(),N=N.substring(0,N.lastIndexOf("."))),I!==b.tagname&&(N+=N?"."+I:I),this.isItStopNode(this.options.stopNodes,N,I)){let X="";if(B.length>0&&B.lastIndexOf("/")===B.length-1)I[I.length-1]==="/"?(I=I.substr(0,I.length-1),N=N.substr(0,N.length-1),B=I):B=B.substr(0,B.length-1),k=x.closeIndex;else if(this.options.unpairedTags.indexOf(I)!==-1)k=x.closeIndex;else{const be=this.readStopNodeData(m,D,In+1);if(!be)throw new Error(`Unexpected end of ${D}`);k=be.i,X=be.tagContent}const we=new t(I);I!==B&&Y&&(we[":@"]=this.buildAttributesMap(B,N,I)),X&&(X=this.parseTextData(X,I,N,!0,Y,!0,!0)),N=N.substr(0,N.lastIndexOf(".")),we.add(this.options.textNodeName,X),this.addChild(E,we,N)}else{if(B.length>0&&B.lastIndexOf("/")===B.length-1){I[I.length-1]==="/"?(I=I.substr(0,I.length-1),N=N.substr(0,N.length-1),B=I):B=B.substr(0,B.length-1),this.options.transformTagName&&(I=this.options.transformTagName(I));const X=new t(I);I!==B&&Y&&(X[":@"]=this.buildAttributesMap(B,N,I)),this.addChild(E,X,N),N=N.substr(0,N.lastIndexOf("."))}else{const X=new t(I);this.tagsNodeStack.push(E),I!==B&&Y&&(X[":@"]=this.buildAttributesMap(B,N,I)),this.addChild(E,X,N),E=X}M="",k=In}}else M+=m[k];return b.child};function d(m,b,E){const M=this.options.updateTag(b.tagname,E,b[":@"]);M===!1||(typeof M=="string"&&(b.tagname=M),m.addChild(b))}const p=function(m){if(this.options.processEntities){for(let b in this.docTypeEntities){const E=this.docTypeEntities[b];m=m.replace(E.regx,E.val)}for(let b in this.lastEntities){const E=this.lastEntities[b];m=m.replace(E.regex,E.val)}if(this.options.htmlEntities)for(let b in this.htmlEntities){const E=this.htmlEntities[b];m=m.replace(E.regex,E.val)}m=m.replace(this.ampEntity.regex,this.ampEntity.val)}return m};function g(m,b,E,M){return m&&(M===void 0&&(M=Object.keys(b.child).length===0),m=this.parseTextData(m,b.tagname,E,!1,b[":@"]?Object.keys(b[":@"]).length!==0:!1,M),m!==void 0&&m!==""&&b.add(this.options.textNodeName,m),m=""),m}function y(m,b,E){const M="*."+E;for(const N in m){const k=m[N];if(M===k||b===k)return!0}return!1}function O(m,b,E=">"){let M,N="";for(let k=b;k<m.length;k++){let P=m[k];if(M)P===M&&(M="");else if(P==='"'||P==="'")M=P;else if(P===E[0])if(E[1]){if(m[k+1]===E[1])return{data:N,index:k}}else return{data:N,index:k};else P===" "&&(P=" ");N+=P}}function f(m,b,E,M){const N=m.indexOf(b,E);if(N===-1)throw new Error(M);return N+b.length-1}function w(m,b,E,M=">"){const N=O(m,b+1,M);if(!N)return;let k=N.data;const P=N.index,x=k.search(/\s/);let I=k,D=!0;x!==-1&&(I=k.substring(0,x),k=k.substring(x+1).trimStart());const B=I;if(E){const Y=I.indexOf(":");Y!==-1&&(I=I.substr(Y+1),D=I!==N.data.substr(Y+1))}return{tagName:I,tagExp:k,closeIndex:P,attrExpPresent:D,rawTagName:B}}function T(m,b,E){const M=E;let N=1;for(;E<m.length;E++)if(m[E]==="<")if(m[E+1]==="/"){const k=f(m,">",E,`${b} is not closed`);if(m.substring(E+2,k).trim()===b&&(N--,N===0))return{tagContent:m.substring(M,E),i:k};E=k}else if(m[E+1]==="?")E=f(m,"?>",E+1,"StopNode is not closed.");else if(m.substr(E+1,3)==="!--")E=f(m,"-->",E+3,"StopNode is not closed.");else if(m.substr(E+1,2)==="![")E=f(m,"]]>",E,"StopNode is not closed.")-2;else{const k=w(m,E,">");k&&((k&&k.tagName)===b&&k.tagExp[k.tagExp.length-1]!=="/"&&N++,E=k.closeIndex)}}function $(m,b,E){if(b&&typeof m=="string"){const M=m.trim();return M==="true"?!0:M==="false"?!1:n(m,E)}else return r.isExist(m)?m:""}return Ie=i,Ie}var Oe={},Kn;function yr(){if(Kn)return Oe;Kn=1;function r(i,o){return t(i,o)}function t(i,o,a){let c;const l={};for(let u=0;u<i.length;u++){const h=i[u],d=e(h);let p="";if(a===void 0?p=d:p=a+"."+d,d===o.textNodeName)c===void 0?c=h[d]:c+=""+h[d];else{if(d===void 0)continue;if(h[d]){let g=t(h[d],o,p);const y=s(g,o);h[":@"]?n(g,h[":@"],p,o):Object.keys(g).length===1&&g[o.textNodeName]!==void 0&&!o.alwaysCreateTextNode?g=g[o.textNodeName]:Object.keys(g).length===0&&(o.alwaysCreateTextNode?g[o.textNodeName]="":g=""),l[d]!==void 0&&l.hasOwnProperty(d)?(Array.isArray(l[d])||(l[d]=[l[d]]),l[d].push(g)):o.isArray(d,p,y)?l[d]=[g]:l[d]=g}}}return typeof c=="string"?c.length>0&&(l[o.textNodeName]=c):c!==void 0&&(l[o.textNodeName]=c),l}function e(i){const o=Object.keys(i);for(let a=0;a<o.length;a++){const c=o[a];if(c!==":@")return c}}function n(i,o,a,c){if(o){const l=Object.keys(o),u=l.length;for(let h=0;h<u;h++){const d=l[h];c.isArray(d,a+"."+d,!0,!0)?i[d]=[o[d]]:i[d]=o[d]}}}function s(i,o){const{textNodeName:a}=o,c=Object.keys(i).length;return!!(c===0||c===1&&(i[a]||typeof i[a]=="boolean"||i[a]===0))}return Oe.prettify=r,Oe}var ke,Ln;function mr(){if(Ln)return ke;Ln=1;const{buildOptions:r}=hr(),t=gr(),{prettify:e}=yr(),n=as();class s{constructor(o){this.externalEntities={},this.options=r(o)}parse(o,a){if(typeof o!="string")if(o.toString)o=o.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(a){a===!0&&(a={});const u=n.validate(o,a);if(u!==!0)throw Error(`${u.err.msg}:${u.err.line}:${u.err.col}`)}const c=new t(this.options);c.addExternalEntities(this.externalEntities);const l=c.parseXml(o);return this.options.preserveOrder||l===void 0?l:e(l,this.options)}addEntity(o,a){if(a.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(o.indexOf("&")!==-1||o.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(a==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[o]=a}}return ke=s,ke}var Ce,jn;function wr(){if(jn)return Ce;jn=1;const r=`
|
|
10
|
+
`;function t(a,c){let l="";return c.format&&c.indentBy.length>0&&(l=r),e(a,c,"",l)}function e(a,c,l,u){let h="",d=!1;for(let p=0;p<a.length;p++){const g=a[p],y=n(g);if(y===void 0)continue;let O="";if(l.length===0?O=y:O=`${l}.${y}`,y===c.textNodeName){let m=g[y];i(O,c)||(m=c.tagValueProcessor(y,m),m=o(m,c)),d&&(h+=u),h+=m,d=!1;continue}else if(y===c.cdataPropName){d&&(h+=u),h+=`<![CDATA[${g[y][0][c.textNodeName]}]]>`,d=!1;continue}else if(y===c.commentPropName){h+=u+`<!--${g[y][0][c.textNodeName]}-->`,d=!0;continue}else if(y[0]==="?"){const m=s(g[":@"],c),b=y==="?xml"?"":u;let E=g[y][0][c.textNodeName];E=E.length!==0?" "+E:"",h+=b+`<${y}${E}${m}?>`,d=!0;continue}let f=u;f!==""&&(f+=c.indentBy);const w=s(g[":@"],c),T=u+`<${y}${w}`,$=e(g[y],c,O,f);c.unpairedTags.indexOf(y)!==-1?c.suppressUnpairedNode?h+=T+">":h+=T+"/>":(!$||$.length===0)&&c.suppressEmptyNode?h+=T+"/>":$&&$.endsWith(">")?h+=T+`>${$}${u}</${y}>`:(h+=T+">",$&&u!==""&&($.includes("/>")||$.includes("</"))?h+=u+c.indentBy+$+u:h+=$,h+=`</${y}>`),d=!0}return h}function n(a){const c=Object.keys(a);for(let l=0;l<c.length;l++){const u=c[l];if(a.hasOwnProperty(u)&&u!==":@")return u}}function s(a,c){let l="";if(a&&!c.ignoreAttributes)for(let u in a){if(!a.hasOwnProperty(u))continue;let h=c.attributeValueProcessor(u,a[u]);h=o(h,c),h===!0&&c.suppressBooleanAttributes?l+=` ${u.substr(c.attributeNamePrefix.length)}`:l+=` ${u.substr(c.attributeNamePrefix.length)}="${h}"`}return l}function i(a,c){a=a.substr(0,a.length-c.textNodeName.length-1);let l=a.substr(a.lastIndexOf(".")+1);for(let u in c.stopNodes)if(c.stopNodes[u]===a||c.stopNodes[u]==="*."+l)return!0;return!1}function o(a,c){if(a&&a.length>0&&c.processEntities)for(let l=0;l<c.entities.length;l++){const u=c.entities[l];a=a.replace(u.regex,u.val)}return a}return Ce=t,Ce}var Re,zn;function br(){if(zn)return Re;zn=1;const r=wr(),t=cs(),e={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(a,c){return c},attributeValueProcessor:function(a,c){return c},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 n(a){this.options=Object.assign({},e,a),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=t(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=o),this.processTextOrObjNode=s,this.options.format?(this.indentate=i,this.tagEndChar=`>
|
|
11
|
+
`,this.newLine=`
|
|
12
|
+
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}n.prototype.build=function(a){return this.options.preserveOrder?r(a,this.options):(Array.isArray(a)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(a={[this.options.arrayNodeName]:a}),this.j2x(a,0,[]).val)},n.prototype.j2x=function(a,c,l){let u="",h="";const d=l.join(".");for(let p in a)if(Object.prototype.hasOwnProperty.call(a,p))if(typeof a[p]>"u")this.isAttribute(p)&&(h+="");else if(a[p]===null)this.isAttribute(p)?h+="":p[0]==="?"?h+=this.indentate(c)+"<"+p+"?"+this.tagEndChar:h+=this.indentate(c)+"<"+p+"/"+this.tagEndChar;else if(a[p]instanceof Date)h+=this.buildTextValNode(a[p],p,"",c);else if(typeof a[p]!="object"){const g=this.isAttribute(p);if(g&&!this.ignoreAttributesFn(g,d))u+=this.buildAttrPairStr(g,""+a[p]);else if(!g)if(p===this.options.textNodeName){let y=this.options.tagValueProcessor(p,""+a[p]);h+=this.replaceEntitiesValue(y)}else h+=this.buildTextValNode(a[p],p,"",c)}else if(Array.isArray(a[p])){const g=a[p].length;let y="",O="";for(let f=0;f<g;f++){const w=a[p][f];if(!(typeof w>"u"))if(w===null)p[0]==="?"?h+=this.indentate(c)+"<"+p+"?"+this.tagEndChar:h+=this.indentate(c)+"<"+p+"/"+this.tagEndChar;else if(typeof w=="object")if(this.options.oneListGroup){const T=this.j2x(w,c+1,l.concat(p));y+=T.val,this.options.attributesGroupName&&w.hasOwnProperty(this.options.attributesGroupName)&&(O+=T.attrStr)}else y+=this.processTextOrObjNode(w,p,c,l);else if(this.options.oneListGroup){let T=this.options.tagValueProcessor(p,w);T=this.replaceEntitiesValue(T),y+=T}else y+=this.buildTextValNode(w,p,"",c)}this.options.oneListGroup&&(y=this.buildObjectNode(y,p,O,c)),h+=y}else if(this.options.attributesGroupName&&p===this.options.attributesGroupName){const g=Object.keys(a[p]),y=g.length;for(let O=0;O<y;O++)u+=this.buildAttrPairStr(g[O],""+a[p][g[O]])}else h+=this.processTextOrObjNode(a[p],p,c,l);return{attrStr:u,val:h}},n.prototype.buildAttrPairStr=function(a,c){return c=this.options.attributeValueProcessor(a,""+c),c=this.replaceEntitiesValue(c),this.options.suppressBooleanAttributes&&c==="true"?" "+a:" "+a+'="'+c+'"'};function s(a,c,l,u){const h=this.j2x(a,l+1,u.concat(c));return a[this.options.textNodeName]!==void 0&&Object.keys(a).length===1?this.buildTextValNode(a[this.options.textNodeName],c,h.attrStr,l):this.buildObjectNode(h.val,c,h.attrStr,l)}n.prototype.buildObjectNode=function(a,c,l,u){if(a==="")return c[0]==="?"?this.indentate(u)+"<"+c+l+"?"+this.tagEndChar:this.indentate(u)+"<"+c+l+this.closeTag(c)+this.tagEndChar;{let h="</"+c+this.tagEndChar,d="";return c[0]==="?"&&(d="?",h=""),(l||l==="")&&a.indexOf("<")===-1?this.indentate(u)+"<"+c+l+d+">"+a+h:this.options.commentPropName!==!1&&c===this.options.commentPropName&&d.length===0?this.indentate(u)+`<!--${a}-->`+this.newLine:this.indentate(u)+"<"+c+l+d+this.tagEndChar+a+this.indentate(u)+h}},n.prototype.closeTag=function(a){let c="";return this.options.unpairedTags.indexOf(a)!==-1?this.options.suppressUnpairedNode||(c="/"):this.options.suppressEmptyNode?c="/":c=`></${a}`,c},n.prototype.buildTextValNode=function(a,c,l,u){if(this.options.cdataPropName!==!1&&c===this.options.cdataPropName)return this.indentate(u)+`<![CDATA[${a}]]>`+this.newLine;if(this.options.commentPropName!==!1&&c===this.options.commentPropName)return this.indentate(u)+`<!--${a}-->`+this.newLine;if(c[0]==="?")return this.indentate(u)+"<"+c+l+"?"+this.tagEndChar;{let h=this.options.tagValueProcessor(c,a);return h=this.replaceEntitiesValue(h),h===""?this.indentate(u)+"<"+c+l+this.closeTag(c)+this.tagEndChar:this.indentate(u)+"<"+c+l+">"+h+"</"+c+this.tagEndChar}},n.prototype.replaceEntitiesValue=function(a){if(a&&a.length>0&&this.options.processEntities)for(let c=0;c<this.options.entities.length;c++){const l=this.options.entities[c];a=a.replace(l.regex,l.val)}return a};function i(a){return this.options.indentBy.repeat(a)}function o(a){return a.startsWith(this.options.attributeNamePrefix)&&a!==this.options.textNodeName?a.substr(this.attrPrefixLen):!1}return Re=n,Re}var xe,Fn;function _r(){if(Fn)return xe;Fn=1;const r=as(),t=mr(),e=br();return xe={XMLParser:t,XMLValidator:r,XMLBuilder:e},xe}var Un=_r();class yt{constructor(t){C(this,"type");C(this,"attrs",{});C(this,"styles",{});C(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,hs(this.attrs),Rr(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 un extends yt{constructor(e){super("image");C(this,"attrs",{});this.attrs={...this.attrs,href:e}}load(e){return this.attrs.href=e,this}}class ge extends yt{constructor(e){super("use");C(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 hn extends yt{constructor(){super("rect");C(this,"attrs",{})}fill(e){return this.attrs.fill=e,this}stroke(e){return this.attrs.stroke=e,this}}class Et extends yt{constructor(e=""){super("text");C(this,"attrs");C(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 dn=class extends yt{constructor(e){super("symbol");C(this,"raw");this.raw=e}id(){return this.attr("id")}center(){return this.raw}};class W extends yt{constructor(){super("g");C(this,"children",[]);C(this,"rotateMatrix");C(this,"translateMatrix")}add(e){return this.children.push(e),this}rotate(e,n,s){return this.rotateMatrix=ar(e,n,s),this}translate(e,n){return this.translateMatrix=Le(e,n),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){const n=[this.translateMatrix,this.rotateMatrix].filter(s=>s!=null);return n.length==0?super.left():super.left(Cr(nr(n)))}each(e,n){for(let s=0;s<this.children.length;s++){const i=this.children[s];i instanceof W&&n&&i.each(e,!0),e(s,this.children)}}}const Ar=['xmlns="http://www.w3.org/2000/svg"','version="1.1"','xmlns:xlink="http://www.w3.org/1999/xlink"'];class ls extends yt{constructor(){super("svg");C(this,"children",[]);C(this,"viewBox")}add(e){return this.children.push(e),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){return`<${[this.type,...Ar,hs(this.attrs),kr(this.viewBox)].filter(n=>n!="").join(" ")}>`}viewbox(e,n,s,i){return this.viewBox={x:e,y:n,width:s,height:i},this}importSymbol(e){for(const n of xr(e))this.add(n);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,n){for(let s=0;s<this.children.length;s++){const i=this.children[s];i instanceof W&&n&&i.each(e,!0),e(s,this.children)}}}function us(){return new ls}const Er=us,Nr=W,vr=un,Sr=ge,Tr=hn,Ir=Et;function Or(r){return r.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function kr(r){return r==null?"":`viewBox="${r.x} ${r.y} ${r.width} ${r.height}"`}function Cr(r){return r==null?"":`transform="${cr(r)}"`}function hs(r){return Object.entries(r).filter(([t,e])=>e!==void 0).map(([t,e])=>`${Or(t)}="${e}"`).join(" ")}function Rr(r){const t=Object.entries(r).map(([e,n])=>`${e}: ${n};`).join(" ");return t!=""?`style="${t}"`:""}function*xr(r){const t=new Un.XMLParser({ignoreAttributes:!1}),e=new Un.XMLBuilder({ignoreAttributes:!1}),n=t.parse(r);for(const s of n.svg.symbol){const i=e.build(s),o=new dn(i);for(const[a,c]of Object.entries(s))a.startsWith("@_")&&(o.attrs[a.substring(2)]=c);yield o}}const nt=(r,t)=>{const e=q(r.tiles[0],t),n=e.baseHeight,s=e.baseWidth;if(r.is(S.SHO_KAN))return{width:s*2+n,height:Math.max(s*2,n)};const i=r.tiles.reduce((a,c)=>{const l=q(c,t).height;return l>a?l:a},0);return{width:r.tiles.reduce((a,c)=>a+q(c,t).width,0),height:i}},q=(r,t)=>{const e=parseFloat((ft.HEIGHT*t).toPrecision(5)),n=parseFloat((ft.WIDTH*t).toPrecision(5)),s=r.has(A.HORIZONTAL)?{width:e,height:n,baseWidth:n,baseHeight:e}:{width:n,height:e,w:n,baseWidth:n,baseHeight:e};return(r.has(A.TSUMO)||r.has(A.DORA))&&(s.width+=n*ft.TEXT_SCALE),s};class $t{constructor(t={}){C(this,"tileWidth");C(this,"tileHeight");C(this,"imageHostUrl");C(this,"imageExt");C(this,"scale");C(this,"svgSprite");this.scale=t.scale??1,this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=ft.WIDTH*this.scale,this.tileHeight=ft.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getDiffTileHeightWidth(t){const e=q(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new un().load(this.buildURL(t));return this.svgSprite&&(e=new ge().use($t.buildID(t))),t instanceof v&&t.has(A.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,n){const s=q(t,this.scale);return this.image(t).dx(e).dy(n).size(s.baseWidth,s.baseHeight)}createTextImage(t,e,n,s){const i=this.createImage(t,e,n),o=q(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,l=o.baseHeight,u=new Et().plain(s);u.size(o.baseWidth,o.baseHeight).font({family:en,size:a}).dx(c).dy(l);const h=new W;return h.add(i).add(u).translate(e,n),h}createRotate90Image(t,e,n,s=!1){const i=this.createImage(t,0,0),o=q(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,l=e+this.getDiffTileHeightWidth(t),u=s?n-this.getDiffTileHeightWidth(t):n,h=new W;return h.add(i).translate(l,u).rotate(90,a,c),h}createStick(t){return this.image(t)}static buildID(t){if(t==100||t==1e3)return t==100?"stick100":"stick1000";const e=t.t==_.BACK||t.has(A.RED)?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${$t.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:e}}class fn extends $t{constructor(){super(...arguments);C(this,"blockMargin",ft.WIDTH*ft.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const n=e instanceof z?e.tilesWithBack:e.tiles,s=new W;let i=0;for(const o of n){const a=q(o,this.scale),c=o.has(A.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),l=o.has(A.HORIZONTAL)?this.getDiffTileHeightWidth(o):0,u=c(o,i,l);s.add(u),i+=a.width}return s}createBlockPonChiKan(e){const n=e.tiles.findIndex(o=>o.has(A.HORIZONTAL));let s=0;const i=new W;if(e.type==S.SHO_KAN){let o=n;for(let a=0;a<e.tiles.length;a++)e.tiles[a].has(A.HORIZONTAL)&&(o=a);for(let a=0;a<e.tiles.length;a++){const c=q(e.tiles[a],this.scale);if(a==o)continue;if(a==n){const h=e.tiles[n],d=e.tiles[o],p=q(h,this.scale),g=this.createRotate90Image(h,0,0,!0),y=this.createRotate90Image(d,0,p.height,!0);i.add(new W().translate(s,0).add(g).add(y)),s+=p.width;continue}const l=c.width*2-c.height,u=this.createImage(e.tiles[a],s,l);s+=c.width,i.add(u)}return i}if(e.type==S.CHI){const o=e.tiles[n],a=this.createRotate90Image(o,s,this.getDiffTileHeightWidth(o));s+=q(o,this.scale).width,i.add(a);for(let c=0;c<e.tiles.length;c++){if(c==n)continue;const l=e.tiles[c],u=q(l,this.scale),h=this.createImage(l,s,0);s+=u.width,i.add(h)}return i}for(let o=0;o<e.tiles.length;o++){const a=o==n?this.createRotate90Image.bind(this):this.createImage.bind(this),c=e.tiles[o],l=o==n?this.getDiffTileHeightWidth(c):0,u=q(c,this.scale),h=a(c,s,l);s+=u.width,i.add(h)}return i}}const Mr=(r,t)=>{const e=r.scale;return{[S.CHI]:function(s){const i=nt(s,e),o=r.createBlockPonChiKan(s);return{...i,e:o}},[S.PON]:function(s){const i=nt(s,e),o=r.createBlockPonChiKan(s);return{...i,e:o}},[S.DAI_KAN]:function(s){const i=nt(s,e),o=r.createBlockPonChiKan(s);return{...i,e:o}},[S.SHO_KAN]:function(s){const i=nt(s,e),o=r.createBlockPonChiKan(s);return{...i,e:o}},[S.AN_KAN]:function(s){H(s instanceof z,`block type is not ankan: ${s.type}`);const i=nt(s,e),o=r.createBlockHandDiscard(s);return{...i,e:o}},[S.IMAGE_DORA]:function(s){s=(t==null?void 0:t.doraText)==!1?new Mt([s.tiles[0].clone({remove:A.DORA})]):s;const i=nt(s,e),o=new W,a=(t==null?void 0:t.doraText)===!1?r.createImage(s.tiles[0],0,0):r.createTextImage(s.tiles[0],0,0,"(ドラ)");return o.add(a),{...i,e:o}},[S.TSUMO]:function(s){s=(t==null?void 0:t.tsumoText)==!1?new Mt([s.tiles[0].clone({remove:A.TSUMO})]):s;const i=nt(s,e),o=new W,a=(t==null?void 0:t.tsumoText)===!1?r.createImage(s.tiles[0],0,0):r.createTextImage(s.tiles[0],0,0,"(ツモ)");return o.add(a),{...i,e:o}},[S.HAND]:function(s){const i=nt(s,e),o=r.createBlockHandDiscard(s);return{...i,e:o}},[S.IMAGE_DISCARD]:function(s){const i=nt(s,e),o=r.createBlockHandDiscard(s);return{...i,e:o}},[S.THREE]:function(s){throw new Error("three is unsupported")},[S.RUN]:function(s){throw new Error("run is unsupported")},[S.PAIR]:function(s){throw new Error("pair is unsupported")},[S.ISOLATED]:function(s){throw new Error("isolated is unsupported")},[S.UNKNOWN]:function(s){if(s.tiles.some(a=>a.has(A.TSUMO)||a.has(A.DORA)))throw new Error("found an unknown block with operator tiles");const i=nt(s,e),o=r.createBlockHandDiscard(s);return{...i,e:o}}}},Ct=(r,t,e)=>{const n=Mr(r,e);let s=0,i=0;const o=[];for(const h of t){const d=n[h.type],p=d(h);i+=p.width,s=p.height>s?p.height:s,o.push(p)}const a=s,c=i+(t.length-1)*r.blockMargin,l=new W;let u=0;for(const h of o){const d=a-h.height,p=new W().translate(u,d);p.add(h.e),l.add(p),u+=h.width+r.blockMargin}return{e:l,width:c,height:a}},$r=(r,t,e={},n={responsive:!1,doraText:!0,tsumoText:!0})=>{const s=new fn(e),i=Ct(s,t,n);n.responsive||r.size(i.width,i.height),r.viewbox(0,0,i.width,i.height),r.add(i.e)},ds=()=>{const r=[0,1,2,3,4,5,6,7,8,9],t=[];for(const e of Object.values(_)){if(e==_.BACK){t.push($t.buildID(new v(e,0)));continue}t.push(...r.map(n=>$t.buildID(new v(e,n))).flat())}return t},Pr=r=>{const t=ds(),e=[];return r.each((n,s)=>{const i=s[n];if(i instanceof ge){const a=i.attr("href").substring(1);t.includes(a)&&e.push(a)}},!0),e},Hr=r=>{const t=ds(),e=Pr(r);r.each((n,s)=>{const i=s[n];i instanceof dn&&(t.includes(i.id())&&e.includes(i.id())||i.remove())},!0)},Br=r=>{const e=[];for(let n=0;n<r.length;n+=6){const s=r.slice(n,n+6);e.push(s)}return e},et=(r,t,e,n,s=0,i=0)=>{const o=new W().add(r);if(n==90){const a=s,c=i-e;return o.rotate(n,0,e).translate(a,c),new W().add(o)}if(n==180){const a=s+t,c=i-e;return o.rotate(n,0,e).translate(a,c),new W().add(o)}if(n==270){const a=s+e,c=i+(t-e);return o.rotate(n,0,e).translate(a,c),new W().add(o)}return new W().add(o)},ne=(r,t)=>{const e=new W,n=Br(r);for(let s=0;s<n.length;s++){let i=n[s],o=s*t.tileHeight;const a=t.createBlockHandDiscard(new on(i,S.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*n.length}},Wr=(r,t,e)=>{const n=t.font,s=t.textWidth,i=t.textHeight,o=e.sticks.dead,a=e.sticks.reach,c=De.WIDTH*r.scale,l=De.HEIGHT*r.scale;let u=s*3,h=i;const d=(c+r.tileWidth+s-u)/2,p=new Et().plain(e.round).font(n).x(d).y(0);h+=25*r.scale;const g=r.tileHeight,y=new W().size(c,g).translate(0,h),O={family:n.family,size:n.size*.7},f=r.createStick(1e3).size(c,l).x(0).y(0),w=new Et().plain(a.toString()).font(O).dx(c).dy(l),T=r.createStick(100).size(c,l).x(0).y(l+l),$=new Et().plain(o.toString()).font(O).dx(c).dy(l*3);y.add(f),y.add(w),y.add(T),y.add($);const m=r.createImage(e.doras[0],0,0).x(c+s).y(0);y.add(m);const b=new W;return b.add(p),b.add(p),b.add(y),{e:b,width:c+r.tileWidth+s,height:h+r.tileHeight}},Dr=(r,t,e=0)=>{const n=Ct(r,t.front),s=Ct(r,t.right),i=Ct(r,t.opposite),o=Ct(r,t.left),a=[n.width,s.width,i.width,o.width].reduce((y,O)=>Math.max(y,O)),c=Math.max(e+r.tileHeight*2+r.blockMargin*2,a+r.tileWidth*2+r.blockMargin),l=c,u=et(n.e,n.width,n.height,0).translate((c-n.width)/2,l-n.height),h=et(s.e,s.width,s.height,270).translate(c-s.height,(c-s.width)/2),d=et(i.e,i.width,i.height,180).translate((c-i.width)/2,0),p=et(o.e,o.width,o.height,90).translate(0,(c-o.width)/2),g=new W().size(c,l);return g.add(u),g.add(h),g.add(d),g.add(p),{e:new W().add(g),width:c,height:l}},Kr=r=>{const t=Object.values(fe),e=t.indexOf(r);return[...t.slice(e),...t.slice(0,e)]},Lr=(r,t,e)=>{const n=r.tileWidth*5+r.tileHeight*1,s=t.font,i=t.textWidth,o=t.textHeight,a=t.numWidth,c=Wr(r,t,e);c.e.translate(n/2-c.width/2,n/2-c.height/2);const l=(N,k,P)=>{const x=`${N} ${k}`,I=new Et().plain(x).font(s).attr(P);return{e:new W().add(I),width:i+a*k.toString().length,height:o}},[u,h,d,p]=Kr(e.frontPlace),g=e.scores,O=l(u,g.front,{x:n/2,y:n,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let f=l(h,g.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const w=et(f.e,f.width,f.height,270).translate(n,n/2-f.width);let T=l(d,g.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const $=et(T.e,T.width,T.height,180).translate(n/2-T.width,-T.height);let m=l(p,g.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const b=et(m.e,m.width,m.height,90).translate(-m.height,n/2),E=new W,M=new hn().size(n,n).x(0).y(0).fill("none").stroke("#000000");return E.add(M),E.add(c.e),E.add(O),E.add(w),E.add($),E.add(b),{e:E,width:n,height:n}},jr=(r,t)=>{const e=ne(t.front,r),n=ne(t.right,r),s=ne(t.opposite,r),i=ne(t.left,r),o=[e.height,n.height,s.height,i.height].reduce((w,T)=>Math.max(w,T)),a=r.tileWidth*5+r.tileHeight*1,c=o,l=a+o*2+r.blockMargin,u=l,h=new W().size(l,u),d=l/2-a/2,p=u/2-a/2,g=et(e.e,a,c,0).translate(d,u-c),y=et(n.e,a,c,270).translate(l-c,p),O=et(s.e,a,c,180).translate(d,0),f=et(i.e,a,c,90).translate(0,p);return h.add(g),h.add(y),h.add(O),h.add(f),{e:new W().add(h),width:l,height:u}},fs=(r,t,e,n,s)=>{const i=new W,o=jr(r,n),a=Dr(r,e,o.height),c=Lr(r,t,s);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),i.add(a.e),i.add(o.e),i.add(c.e),{e:i,width:a.width,height:a.height}},zr=(r,t,e={},n,s={responsive:!1})=>{const i=new fn(e),o=n,{discards:a,hands:c,scoreBoard:l}=ps(t),u=fs(i,o,c,a,l);s.responsive||r.size(u.width,u.height),r.viewbox(0,0,u.width,u.height),r.add(u.e)};var ot;function Fr(r){return{lang:(r==null?void 0:r.lang)??(ot==null?void 0:ot.lang),message:r==null?void 0:r.message,abortEarly:(r==null?void 0:r.abortEarly)??(ot==null?void 0:ot.abortEarly),abortPipeEarly:(r==null?void 0:r.abortPipeEarly)??(ot==null?void 0:ot.abortPipeEarly)}}var Me;function Ur(r){return Me==null?void 0:Me.get(r)}var $e;function Gr(r){return $e==null?void 0:$e.get(r)}var Pe;function Zr(r,t){var e;return(e=Pe==null?void 0:Pe.get(r))==null?void 0:e.get(t)}function Pt(r){var e,n;const t=typeof r;return t==="string"?`"${r}"`:t==="number"||t==="bigint"||t==="boolean"?`${r}`:t==="object"||t==="function"?(r&&((n=(e=Object.getPrototypeOf(r))==null?void 0:e.constructor)==null?void 0:n.name))??"null":t}function vt(r,t,e,n,s){const i=s&&"input"in s?s.input:e.value,o=(s==null?void 0:s.expected)??r.expects??null,a=(s==null?void 0:s.received)??Pt(i),c={kind:r.kind,type:r.type,input:i,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:r.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},l=r.kind==="schema",u=(s==null?void 0:s.message)??r.message??Zr(r.reference,c.lang)??(l?Gr(c.lang):null)??n.message??Ur(c.lang);u&&(c.message=typeof u=="function"?u(c):u),l&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function qr(r,t){const e=[...new Set(r)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function je(r,t){return{kind:"validation",type:"max_value",reference:je,async:!1,expects:`<=${r instanceof Date?r.toJSON():Pt(r)}`,requirement:r,message:t,_run(e,n){return e.typed&&e.value>this.requirement&&vt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():Pt(e.value)}),e}}}function ze(r,t){return{kind:"validation",type:"min_value",reference:ze,async:!1,expects:`>=${r instanceof Date?r.toJSON():Pt(r)}`,requirement:r,message:t,_run(e,n){return e.typed&&e.value<this.requirement&&vt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():Pt(e.value)}),e}}}function Xr(r,t,e){return typeof r.default=="function"?r.default(t,e):r.default}function ce(r){return{kind:"schema",type:"number",reference:ce,expects:"number",async:!1,message:r,_run(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:vt(this,"type",t,e),t}}}function V(r,...t){const e={kind:"schema",type:"optional",reference:V,expects:`(${r.expects} | undefined)`,async:!1,wrapped:r,_run(n,s){return n.value===void 0&&("default"in this&&(n.value=Xr(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in t&&(e.default=t[0]),e}function Fe(r,t){return{kind:"schema",type:"picklist",reference:Fe,expects:qr(r.map(Pt),"|"),async:!1,options:r,message:t,_run(e,n){return this.options.includes(e.value)?e.typed=!0:vt(this,"type",e,n),e}}}function Ht(r,t){return{kind:"schema",type:"strict_object",reference:Ht,expects:"Object",async:!1,entries:r,message:t,_run(e,n){var i;const s=e.value;if(s&&typeof s=="object"){e.typed=!0,e.value={};for(const o in this.entries){const a=s[o],c=this.entries[o]._run({typed:!1,value:a},n);if(c.issues){const l={type:"object",origin:"value",input:s,key:o,value:a};for(const u of c.issues)u.path?u.path.unshift(l):u.path=[l],(i=e.issues)==null||i.push(u);if(e.issues||(e.issues=c.issues),n.abortEarly){e.typed=!1;break}}c.typed||(e.typed=!1),(c.value!==void 0||o in s)&&(e.value[o]=c.value)}if(!e.issues||!n.abortEarly){for(const o in s)if(!(o in this.entries)){const a=s[o];vt(this,"type",e,n,{input:a,expected:"never",path:[{type:"object",origin:"value",input:s,key:o,value:a}]});break}}}else vt(this,"type",e,n);return e}}}function le(r){return{kind:"schema",type:"string",reference:le,expects:"string",async:!1,message:r,_run(t,e){return typeof t.value=="string"?t.typed=!0:vt(this,"type",t,e),t}}}function Gn(...r){return{...r[0],pipe:r,_run(t,e){for(const n of r)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 Vr(r,t,e){const n=r._run({typed:!1,value:t},Fr(e));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}const se=V(Ht({discard:V(le(),""),hand:V(le(),""),score:V(ce(),25e3)}),{discard:"",hand:"",score:25e3}),Jr=Ht({[R.E]:se,[R.S]:se,[R.W]:se,[R.N]:se}),mt={round:L.E1,sticks:{reach:0,dead:0},doras:R.S,front:R.E},Yr=V(Ht({round:V(Fe(Object.keys(nn)),mt.round),sticks:V(Ht({reach:V(Gn(ce(),ze(0,""),je(9,"")),mt.sticks.reach),dead:V(Gn(ce(),ze(0,""),je(9,"")),mt.sticks.dead)}),mt.sticks),doras:V(le(),mt.doras),front:V(Fe(Object.keys(fe)),mt.front)}),mt),Qr=Ht({...Jr.entries,board:Yr}),ps=r=>{const t=gs(r);return ys(t)},gs=r=>{const t=ti(r),e=Vr(Qr,t);if(!e.success)throw e.issues;return e.output},ti=r=>{const t="table",e="board",n=r.split(`
|
|
13
|
+
`).map(a=>a.trim()).filter(a=>a!="");if(n.length==0)throw new Error("empty input");const s=n.shift();if(!s.startsWith(t))throw new Error(`input does not start with table: ${s}`);const i={};let o=[R.E,R.S,R.W,R.N,e];for(;;){const a=n.shift();if(a==null)break;const c=o.find(l=>a.startsWith(l));if(c==null)throw new Error(`encountered unexpected line ${a}`);if(o=o.filter(l=>!a.startsWith(l)),c==e){const[l,u]=ni([...n]);i.board=l;for(let h=0;h<u;h++)n.shift()}else{const[l,u]=ei([...n]);i[c]=l;for(let h=0;h<u;h++)n.shift()}}return i},st=(r,t)=>r.replace(t,"").replace(":","").trim(),ei=r=>{const t="hand",e="discard",n="score",s={};let i=0;for(;i<r.length;i++){const o=r[i];if(o.startsWith(t))s.hand=st(o,t);else if(o.startsWith(e))s.discard=st(o,e);else if(o.startsWith(n))s.score=Number(st(o,n));else break}return[s,i]},ni=r=>{const t="doras",e="round",n="front",s="sticks",i="reach",o="dead",a={};let c=0;for(;c<r.length;c++){const l=r[c];if(l.startsWith(t))a.doras=st(l,t);else if(l.startsWith(e))a.round=st(l,e);else if(l.startsWith(n))a.front=st(l,n);else if(l.startsWith(s)){a.sticks={};const u=r[c+1]??"",h=r[c+2]??"";u.startsWith(i)&&(a.sticks.reach=Number(st(u,i))),u.startsWith(o)&&(a.sticks.dead=Number(st(u,o))),h.startsWith(i)&&(a.sticks.reach=Number(st(h,i))),h.startsWith(o)&&(a.sticks.dead=Number(st(h,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},ys=r=>{const t=r.board.front,e=si(t),n=a=>r[a].discard.replace(/\r?\n/g,""),s={front:new Z(n(e.front)).tiles(),right:new Z(n(e.right)).tiles(),opposite:new Z(n(e.opposite)).tiles(),left:new Z(n(e.left)).tiles()},i={front:new Z(r[e.front].hand).parse(),right:new Z(r[e.right].hand).parse(),opposite:new Z(r[e.opposite].hand).parse(),left:new Z(r[e.left].hand).parse()},o={round:nn[r.board.round],frontPlace:fe[t],sticks:r.board.sticks,doras:new Z(r.board.doras).tiles(),scores:{front:r[e.front].score,right:r[e.right].score,opposite:r[e.opposite].score,left:r[e.left].score}};return{discards:s,hands:i,scoreBoard:o}},si=r=>({front:r,right:pt(r),opposite:pt(pt(r)),left:an(r)});function*J(r){const t=r!=null&&r.filterBy&&r.filterBy.length>0?r==null?void 0:r.filterBy:Object.values(_);for(const e of t){if(r!=null&&r.skipBack&&e==_.BACK)continue;const n=e==_.Z?7:e==_.BACK?1:9;for(let s=1;s<=n;s++)yield[e,s]}}class ye{constructor(t,e=!1){C(this,"data");this.data={[_.M]:[0,0,0,0,0,0,0,0,0,0],[_.P]:[0,0,0,0,0,0,0,0,0,0],[_.S]:[0,0,0,0,0,0,0,0,0,0],[_.Z]:[0,0,0,0,0,0,0,0],[_.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const n=Array.isArray(t)?t:new Z(t).parse();for(const s of n){if(s.isCalled()){this.data.called=[...this.called,s];continue}else if(s.is(S.TSUMO)){const i=s.tiles[0];this.inc([i]),this.data.tsumo=i;continue}else if(s.is(S.HAND)){this.inc(s.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(i=>i===_.BACK)){this.inc(s.tiles);continue}else if(e){this.inc(s.tiles);continue}throw new Error(`unexpected block ${s.type} ${s.toString()}`)}}get hands(){const t=[];for(const[e,n]of J()){let s=this.get(e,n);e!=_.Z&&n==5&&this.get(e,0)>0&&(s-=this.get(e,0),t.push(new v(e,n,[A.RED])));for(let i=0;i<s;i++)t.push(new v(e,n))}if(this.drawn!=null){const e=this.drawn,n=t.findIndex(s=>s.equals(e));H(n>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[n]=t[n].clone({add:A.TSUMO})}return t}toString(){const t=this.called.length>0?`${ut}${this.called.join(ut)}`:"",e=this.drawn?`${ut}${this.drawn.toString()}`:"",n=this.hands.filter(i=>!i.has(A.TSUMO));return`${new Mt(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 z))}sum(t){let e=0;for(const[n,s]of J({filterBy:[t]}))e+=this.get(n,s);return e}get(t,e){return t==_.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const n of t){if(n.t!=_.BACK&&this.get(n.t,n.n)>=4||n.has(A.RED)&&this.get(n.t,0)>0)throw this.dec(e),new Error(`unable to increase ${n} in ${this.toString()}`);e.push(n),n.t==_.BACK?this.data[n.t][1]+=1:(this.data[n.t][n.n]+=1,n.has(A.RED)&&(this.data[n.t][0]+=1))}return e}dec(t){const e=[];for(const n of t){if(this.get(n.t,n.n)<1||n.has(A.RED)&&this.get(n.t,0)<=0)throw this.inc(e),new Error(`unable to decrease ${n.toString()} in ${this.toString()}`);if(e.push(n),n.t==_.BACK?this.data[n.t][1]-=1:(this.data[n.t][n.n]-=1,n.has(A.RED)&&(this.data[n.t][0]-=1)),j(n)&&this.get(n.t,5)==0&&this.get(n.t,0)>0){this.data[n.t][0]=0;const s=e.pop().clone({add:A.RED});e.push(s)}}return e}draw(t){const e=t.clone({add:A.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(A.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 z){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof tt){const e=this.data.called.findIndex(s=>s.is(S.PON)&&s.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let n=t.tiles[0];n=j(n)?n.clone({remove:A.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 ye(this.toString());return t.data.reached=this.data.reached,t}}class Yt{constructor(t){C(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[n,s]of J({skipBack:!0}))this.hand.get(n,s)==2&&t++,this.hand.get(n,s)==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(_)){if(n==_.BACK)continue;const s=n==_.Z?Bt:rt;for(const i of s)this.hand.get(n,i)>=1&&t++,this.hand.get(n,i)>=2&&e++}return e>=1?12-t:13-t}fourSetsOnePair(){const t=n=>{const s=[0,0,0];for(const[d,p]of J({filterBy:[_.Z]}))this.hand.get(d,p)>=3?s[0]++:this.hand.get(d,p)==2?s[1]++:this.hand.get(d,p)==1&&s[2]++;const i=[0,0,0],o=this.hand.get(_.BACK,0),a=o%3;i[0]=Math.floor(o/3),a==2?i[1]=1:a==1&&(i[2]=1);let c=13;const l=this.patternNumType(_.M),u=this.patternNumType(_.P),h=this.patternNumType(_.S);for(const d of[l.patternA,l.patternB])for(const p of[u.patternA,u.patternB])for(const g of[h.patternA,h.patternB]){const y=[this.hand.called.length,0,0];for(let f=0;f<3;f++)y[f]+=d[f]+p[f]+g[f]+s[f]+i[f];const O=this.calcCommon(y[0],y[1],y[2],n);O<c&&(c=O)}return c};let e=t(!1);for(const[n,s]of J())if(this.hand.get(n,s)>=2){const i=this.hand.dec(new Array(2).fill(new v(n,s))),o=t(!0);this.hand.inc(i),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 s=this.hand.dec([new v(t,e),new v(t,e+1),new v(t,e+2)]),i=this.patternNumType(t,e);this.hand.inc(s),i.patternA[0]++,i.patternB[0]++,(i.patternA[2]<n.patternA[2]||i.patternA[2]==n.patternA[2]&&i.patternA[1]<n.patternA[1])&&(n.patternA=i.patternA),(i.patternB[0]>n.patternB[0]||i.patternB[0]==n.patternB[0]&&i.patternB[1]>n.patternB[1])&&(n.patternB=i.patternB)}if(this.hand.get(t,e)>=3){const s=this.hand.dec(new Array(3).fill(new v(t,e))),i=this.patternNumType(t,e);this.hand.inc(s),i.patternA[0]++,i.patternB[0]++,(i.patternA[2]<n.patternA[2]||i.patternA[2]==n.patternA[2]&&i.patternA[1]<n.patternA[1])&&(n.patternA=i.patternA),(i.patternB[0]>n.patternB[0]||i.patternB[0]==n.patternB[0]&&i.patternB[1]>n.patternB[1])&&(n.patternB=i.patternB)}return n}groupRemainingTiles(t){let e=0,n=0,s=0;for(const[i,o]of J({filterBy:[t]}))s+=this.hand.get(i,o),o<=7&&this.hand.get(i,o+1)==0&&this.hand.get(i,o+2)==0&&(e+=s>>1,n+=s%2,s=0);return e+=s>>1,n+=s%2,{patternA:[0,e,n],patternB:[0,e,n]}}calcCommon(t,e,n,s){let i=s?4:5;return t>4&&(e+=t-4,t=4),t+e>4&&(n+=t+e-4,e=4-t),t+e+n>i&&(n=i-t-e),s&&e++,13-t*3-e*2-n}}class ms{constructor(t){C(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 n=this.hand.drawn!=null||e.has(A.TSUMO)?A.TSUMO:A.RON,s=[];for(let o=0;o<t.length;o++){const a=t[o],c={};for(let l=0;l<a.length;l++){const u=a[l];if(u.isCalled())continue;const h=u.tiles.findIndex(p=>p.equals(e)&&e.has(A.RED)==p.has(A.RED));if(h<0)continue;const d=ws(u);c[d]||(c[d]=!0,s.push([o,l,h]))}}if(s.length==0)throw new Error(`found no tile ${e.toString()} in hands ${t[0].toString()}`);const i=[];for(const[o,a,c]of s){const u=[...t[o]],h=u[a],d=h.tiles[c].clone({add:n});u[a]=h.clone({replace:{idx:c,tile:d}}),i.push(u)}return i}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,n]of J({skipBack:!0})){const s=this.hand.get(e,n);if(s==2){const i=this.hand.dec(new Array(2).fill(new v(e,n)));t.push(new G(i[0],i[1])),this.hand.inc(i)}else{if(s==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const n of Object.values(_)){if(n==_.BACK)continue;const s=n==_.Z?Bt:rt;for(let i of s)if(this.hand.get(n,i)==1)t.push(new rn(new v(n,i)));else if(this.hand.get(n,i)==2&&e==!1)t.unshift(new G(new v(n,i),new v(n,i))),e=!0;else return[]}return[t]}nineGates(){const t=(e,n,s)=>s.includes(this.hand.get(e,n));for(const e of Object.values(_)){if(e==_.BACK||e==_.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]),s=this.hand.sum(e)==14;if(n&&s)return[[new Mt(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,n]of J())if(this.hand.get(e,n)>=2){const s=this.hand.dec(new Array(2).fill(new v(e,n))),i=this.patternAll().filter(o=>o.length==4).map(o=>(o.unshift(new G(s[0],s[1])),o));t=[...t,...i],this.hand.inc(s)}return t}patternAll(){const t=[this.handleNumType(_.M),this.handleNumType(_.P),this.handleNumType(_.S),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((n,s)=>s.length-n.length),e=t[0].concat();for(let n=0;n<e.length;n++)for(let s=1;s<t.length;s++)for(const i of t[s])e[n]=[...e[n],...i];return e}handleBack(){const t=_.BACK,e=this.hand.get(t,0);if(e<3)return[];const n=new v(t,0),s=Array(Math.floor(e/3)).fill(new Q([n,n,n]));return s.length==0?[]:[s]}handleZ(){const t=[];for(const[e,n]of J({filterBy:[_.Z]})){if(this.hand.get(e,n)==0)continue;if(this.hand.get(e,n)!=3)return[];const s=new v(e,n);t.push(new Q([s,s,s]))}return t.length==0?[]:[t]}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 s=this.hand.dec([new v(t,e),new v(t,e+1),new v(t,e+2)]);let i=this.handleNumType(t,e);this.hand.inc(s),i.length==0&&(i=[[]]);for(const o of i)o.unshift(new ht([s[0],s[1],s[2]])),n.push(o)}if(this.hand.get(t,e)==3){const s=this.hand.dec(new Array(3).fill(new v(t,e)));let i=this.handleNumType(t,e);this.hand.inc(s),i.length==0&&(i=[[]]);for(const o of i)o.unshift(new Q([s[0],s[1],s[2]])),n.push(o)}return n}}const Bt=[1,2,3,4,5,6,7],rt=[1,9],Ft=r=>{var e;const t=r.boardContext;return{...r,hand:r.hand.map(K.deserialize),boardContext:{...t,doraMarkers:t.doraMarkers.map(v.from),blindDoraMarkers:(e=t.blindDoraMarkers)==null?void 0:e.map(v.from)}}};class Ue{constructor(t,e){C(this,"hand");C(this,"cfg");this.hand=t,this.cfg={doras:e.doraMarkers.map(n=>qn(n)),blindDoras:e.blindDoraMarkers==null?[]:e.blindDoraMarkers.map(n=>qn(n)),roundWind:v.from(e.round.substring(0,2)),myWind:v.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,orig:e}}calc(...t){const e=this.calcPatterns(t);if(e.length==0)return!1;let n=[0,0],s=0;for(let g=0;g<e.length;g++){const y=e[g],O=y.points.reduce((f,w)=>f+w.double,0);O>n[0]?(s=g,n=[O,y.fu]):O==n[0]&&y.fu>n[1]&&(s=g,n=[O,y.fu])}const i=(g,y=100)=>Math.ceil(g/y)*y,o=n[1]!=25?i(n[1],10):25,a=n[0];let c=Math.min(o*2**(a+2),2e3);switch(a){case 26:c=16e3;break;case 13:c=8e3;break;case 12:case 11:c=6e3;break;case 10:case 9:case 8:c=4e3;break;case 7:case 6:c=3e3;break;case 5:c=2e3;break}a>13&&a<26&&(c=8e3);const l=e[s].hand.some(g=>g.tiles.some(y=>y.has(A.TSUMO))),u=this.cfg.orig.myWind,h=u==R.E,d=F(0);if(l){const g=this.cfg.sticks.dead*100;if(h){const y=i(c*2);d[R.E]+=y*3+g*3,d[R.S]-=y+g,d[R.W]-=y+g,d[R.N]-=y+g}else for(const y of Object.values(R)){if(y==u)continue;const O=y==R.E?2:1,f=i(c*O)+g;d[y]-=f,d[u]+=f}}else{const g=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const O=i(c*(h?6:4))+g;d[u]+=O,d[this.cfg.orig.ronWind]-=O}return d[u]+=1e3*this.cfg.sticks.reach,{deltas:d,sum:a,fu:o,points:e[s].points,point:d[u],hand:e[s].hand,boardContext:this.cfg.orig}}calcPatterns(t){const e=[];if(t.length==0)return e;for(const n of t){const s=[...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)];s.length!=0&&e.push({points:s,fu:30,hand:n})}if(e.length>0)return e;for(const n of t){const s=this.calcFu(n),i=[...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)];i.length>0&&i.push(...this.dX1(n)),e.push({points:i,fu:s,hand:n})}return e}minus(){return this.hand.menzen?0:1}dA1(t){return this.cfg.reached==1?[{name:"立直",double:1}]:this.cfg.reached==2?[{name:"ダブル立直",double:2}]:[]}dB1(t){return this.minus()!=0?[]:(this.hand.drawn==null,t.some(n=>n.tiles.some(s=>s.has(A.TSUMO)))?[{name:"門前清自摸和",double:1}]:[])}dC1(t){if(this.minus()!=0)return[];const e="平和",n=this.calcFu(t);return n==20?[{name:e,double:1}]:!t.some(s=>s.tiles.some(i=>i.has(A.TSUMO)))&&n==30?[{name:e,double:1}]:[]}dD1(t){return t.some(n=>n.tiles.some(s=>s.t==_.Z||rt.includes(s.n)))?[]:[{name:"断么九",double:1}]}dE1(t){return this.minus()!=0?[]:Zn(t)==1?[{name:"一盃口",double:1}]:[]}dF1(t){const e=[];return t.forEach(n=>{if(n instanceof G)return;const s=n.tiles[0];s.t==_.Z&&(s.equals(this.cfg.myWind)?e.push({name:"自風",double:1}):s.equals(this.cfg.roundWind)?e.push({name:"場風",double:1}):s.n==5?e.push({name:"白",double:1}):s.n==6?e.push({name:"發",double:1}):s.n==7&&e.push({name:"中",double:1}))}),e}dG1(t){return this.cfg.oneShotWin?[{name:"一発",double:1}]:[]}dH1(t){return this.cfg.replacementWin?[{name:"嶺上開花",double:1}]:[]}dI1(t){return this.cfg.quadWin?[{name:"搶槓",double:1}]:[]}dJ1(t){return this.cfg.finalWallWin?[{name:"海底摸月",double:1}]:[]}dK1(t){return this.cfg.finalDiscardWin?[{name:"河底撈魚",double:1}]:[]}dX1(t){let e=0,n=0,s=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(A.RED)&&s++}const i=[];return e>0&&i.push({name:"ドラ",double:e}),s>0&&i.push({name:"赤ドラ",double:s}),this.hand.reached&&n>0&&i.push({name:"裏ドラ",double:n}),i}dA2(t){return t.length==7?[{name:"七対子",double:2}]:[]}dB2(t){const e=n=>n instanceof ht||n instanceof it;for(const n of t){if(!e(n))continue;const s=wt(n);if(s.t==_.Z)continue;const i=[_.M,_.P,_.S].filter(c=>c!=s.t),o=t.some(c=>{const l=new v(i[0],s.n);return e(c)&&l.equals(wt(c))}),a=t.some(c=>{const l=new v(i[1],s.n);return e(c)&&l.equals(wt(c))});if(o&&a)return[{name:"三色同順",double:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(n=>n instanceof z||n instanceof tt||n instanceof ct||n instanceof Q||n instanceof lt||n instanceof G)?[{name:"対々和",double:2}]:[]}dD2(t){return this.minus()!=0?[]:t.filter(n=>(n instanceof z||n instanceof Q)&&!n.tiles.some(s=>s.has(A.RON))).length>=3?[{name:"三暗刻",double:2}]:[]}dE2(t){return t.filter(n=>n instanceof z||n instanceof tt||n instanceof ct).length>=3?[{name:"三槓子",double:2}]:[]}dF2(t){const e=n=>n instanceof z||n instanceof tt||n instanceof ct||n instanceof Q||n instanceof lt;for(const n of t){if(!e(n))continue;const s=wt(n);if(s.t==_.Z)continue;const i=[_.M,_.P,_.S].filter(c=>c!=s.t),o=t.some(c=>{const l=new v(i[0],s.n);return e(c)&&l.equals(wt(c))}),a=t.some(c=>{const l=new v(i[1],s.n);return e(c)&&l.equals(wt(c))});if(o&&a)return[{name:"三色同刻",double:2}]}return[]}dG2(t){return t.filter(n=>{const s=n.tiles[0];return s.t==_.Z&&[5,6,7].includes(s.n)}).length==3?[{name:"小三元",double:2}]:[]}dH2(t){return t.every(n=>{const s=n.tiles[0].t==_.Z?Bt:rt;return n.tiles.every(i=>s.includes(i.n))})?[{name:"混老頭",double:2}]:[]}dI2(t){return t.length==7?[]:t.some(n=>n instanceof ht||n instanceof it)?t.some(n=>n.tiles[0].t==_.Z)?t.every(n=>{const s=n.tiles[0].t==_.Z?Bt:rt;return n.tiles.some(i=>s.includes(i.n))})?[{name:"混全帯么九",double:2-this.minus()}]:[]:[]:[]}dJ2(t){if(this.minus()!=0)return[];const e={[_.M]:[0,0,0],[_.S]:[0,0,0],[_.P]:[0,0,0]};for(const n of t){const s=wt(n);s.t!=_.BACK&&s.t!=_.Z&&(n instanceof ht||n instanceof it)&&(s.n==1?e[s.t][0]++:s.n==4?e[s.t][1]++:s.n==7&&e[s.t][2]++)}for(const n of Object.values(e))if(n.filter(s=>s>0).length==n.length)return[{name:"一気通貫",double:2-this.minus()}];return[]}dA3(t){if(!t.some(n=>n.tiles[0].t==_.Z))return[];for(const n of Object.values(_))if(t.every(i=>i.tiles[0].t==_.Z||i.tiles[0].t==n))return[{name:"混一色",double:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(n=>n instanceof ht||n instanceof it)?t.some(n=>n.tiles[0].t==_.Z)?[]:t.every(n=>n.tiles.some(s=>rt.includes(s.n)))?[{name:"純全帯么九色",double:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:Zn(t)==2?[{name:"ニ盃口",double:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==_.Z))return[];for(const e of Object.values(_)){if(e==_.Z)continue;if(t.every(s=>s.tiles[0].t==e))return[{name:"清一色",double:6-this.minus()}]}return[]}dA13(t){return t.length!=13?[]:t.some(n=>n instanceof G&&n.tiles.some(s=>s.has(A.TSUMO)||s.has(A.RON)))?[{name:"国士無双13面待ち",double:26}]:[{name:"国士無双",double:13}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",double:13}]:[]}dC13(t){return t.length==7?[]:t.every(s=>s instanceof z||s instanceof Q&&!s.tiles.some(i=>i.has(A.RON))||s instanceof G)?t.some(s=>s instanceof G&&s.tiles.every(i=>i.has(A.TSUMO)||i.has(A.RON)))?[{name:"四暗刻単騎待ち",double:26}]:[{name:"四暗刻",double:13}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(s=>!(s instanceof G)&&s.tiles.some(i=>i.t==_.Z&&e.includes(i.n))).length==3?[{name:"大三元",double:13}]:[]}dE13(t){return t.every(n=>n.tiles[0].t==_.Z)?[{name:"字一色",double:13}]:[]}dF13(t){return t.every(n=>n.tiles.every(s=>s.t!=_.Z&&rt.includes(s.n)))?[{name:"清老頭",double:13}]:[]}dG13(t){return t.filter(n=>n instanceof z||n instanceof tt||n instanceof ct).length==4?[{name:"四槓子",double:13}]:[]}dH13(t){if(t.length==13)return[];if(t.length==7)return[];const e=[1,2,3,4];return t.filter(i=>i.tiles.some(o=>o.t==_.Z&&e.includes(o.n))).length==4?t.find(i=>i instanceof G).tiles.some(i=>i.t==_.Z&&e.includes(i.n))?[{name:"小四喜",double:13}]:[{name:"大四喜",double:13}]:[]}dI13(t){const e=n=>!!(n.equals(new v(_.Z,6))||n.t==_.S&&[2,3,4,6,8].includes(n.n));return t.every(n=>n.tiles.every(s=>e(s)))?[{name:"緑一色",double:13}]:[]}dJ13(t){return[]}dK13(t){return[]}calcFu(t){let n=20;const s=this.cfg.myWind.n,i=this.cfg.roundWind.n;if(t.length==7)return 25;const o=t.find(g=>g.tiles.some(y=>y.has(A.TSUMO)||y.has(A.RON))),a=this.minus()==1,c=o.tiles.some(g=>g.has(A.TSUMO)),l=(g,y)=>{const O=g.tiles[0];return O.t==_.Z&&[5,6,7].includes(O.n)||O.t==_.Z&&[s,i].includes(O.n)||rt.includes(O.n)?y*2:y};for(const g of t)switch(!0){case g instanceof Q:const y=g.tiles.some(O=>O.has(A.RON))?2:4;n+=l(g,y);break;case g instanceof lt:n+=l(g,2);break;case(g instanceof ct||g instanceof tt):n+=l(g,8);break;case g instanceof z:n+=l(g,16);break}n+=(g=>{if(g instanceof Q)return 0;if(g instanceof G)return 2;const y=g.tiles,O=y.findIndex(f=>f.has(A.TSUMO)||f.has(A.RON));return O==1||O==0&&y[2].n==9||O==2&&y[0].n==1?2:0})(o);const d=t.find(g=>g instanceof G).tiles[0];d.t==_.Z&&([5,6,7].includes(d.n)&&(n+=2),d.n==i&&(n+=2),d.n==s&&(n+=2));let p=!1;return!a&&n==20&&(p=!0),c&&!p&&(n+=2),!c&&!a&&(n+=10),!c&&!a&&n==30&&(p=!0),a&&n==20&&(n=30),n}}const ws=r=>r.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),Zn=r=>{const t={};for(const n of r){if(!(n instanceof ht))continue;const s=ws(n);t[s]==null?t[s]=1:t[s]++}let e=0;for(const n in t)t[n]>=2&&e++;return e},wt=r=>[...r.tiles].sort(Jt)[0],qn=r=>{const t=r.n,e=r.t;return new v(e,t%9+1)};class Wt{static calcCandidates(t,e,n){H(e.length>0,"choices to discard is zero");const s=new Map;let i=1/0;for(const o of e){const a=t.dec([o]),c=Wt.candidateTiles(t,n);t.inc(a);const l=n!=null&&n.arrangeRed&&o.has(A.RED)?o.clone({removeAll:!0}):o.has(A.RED)?o.clone({removeAll:!0,add:A.RED}):o.clone({removeAll:!0});c.shanten<i?(s.clear(),s.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l}),i=c.shanten):c.shanten==i&&s.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l})}return Array.from(s.values())}static candidateTiles(t,e){let n=1/0,s=[];const i=new Yt(t);for(const[o,a]of J({skipBack:!0,filterBy:e==null?void 0:e.typeFilter})){if(t.get(o,a)>=4)continue;const c=new v(o,a),l=t.inc([c]),u=e!=null&&e.fourSetsOnePair?i.fourSetsOnePair():i.calc();t.dec(l),u<n?(n=u,s=[c]):u==n&&s.push(c)}return{shanten:n,candidates:s}}}const Ge=()=>{const r=new Set;return{on(t){r.add(t)},off(t){r.delete(t)},offAll(){r.clear()},emit(t){r.forEach(e=>e(t))}}};function bs(r){var i;const t=["RON","DAI_KAN","PON","CHI"],e=r.map(o=>o.choices),s=As(e,t).map(o=>r[o]);return{events:s,type:Es(t,(i=s[0])==null?void 0:i.choices)}}function _s(r){var i;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=r.map(o=>o.choices),s=As(e,t).map(o=>r[o]);return{events:s,type:Es(t,(i=s[0])==null?void 0:i.choices)}}function As(r,t){let e=[],n=Number.POSITIVE_INFINITY;for(let s=0;s<r.length;s++){const i=r[s];if(ri(i,t)){const o=ii(t,i);o<n?(n=o,e=[s]):o===n&&e.push(s)}}return e}function ri(r,t){return t.some(e=>!!r[e])}function ii(r,t){for(let e=0;e<r.length;e++){const n=r[e];if(t[n])return e}return Number.POSITIVE_INFINITY}function Es(r,t){if(t==null)return!1;for(const e of r)if(t[e])return e;return!1}const Ut=()=>{const r=Ge(),t=Ge(),e={emit:r.emit,on:s=>t.on(s)},n={emit:t.emit,on:s=>r.on(s)};return[e,n]},Ns=()=>{const r=Ge();return{emit:n=>{r.emit(n)},on:n=>{r.on(n)}}};class qt{constructor(t){C(this,"reachValue",1e3);C(this,"m");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 s=e[n],i=t[s];this.m[n]+=i}}}class Xt{constructor(t,e){C(this,"pToW",{});C(this,"wToP",F(""));C(this,"round");C(this,"sticks");this.round=(e==null?void 0:e.round)??L.E1,this.sticks=structuredClone(e==null?void 0: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=pt(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Zt(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 pn(r){for(let t=r.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[r[t],r[e]]=[r[e],r[t]]}return r}class vs{constructor(t=!1){C(this,"c");C(this,"safeMap",F({},!0));this.disable=t,this.c=this.initial()}get(t){return t.t==_.BACK?0:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=_.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(A.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{[_.M]:[1,4,4,4,4,4,4,4,4,4],[_.S]:[1,4,4,4,4,4,4,4,4,4],[_.P]:[1,4,4,4,4,4,4,4,4,4],[_.Z]:[0,4,4,4,4,4,4,4]}}}class gn{constructor(){C(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 H(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 oi(){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 ai(){const r=oi();if(r.__xstate__)return r.__xstate__}const ci=r=>{if(typeof window>"u")return;const t=ai();t&&t.register(r)};class Xn{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 Ss=".",li="",Ts="",ui="#",hi="*",Is="xstate.init",Ze="xstate.stop";function di(r,t){return{type:`xstate.after.${r}.${t}`}}function qe(r,t){return{type:`xstate.done.state.${r}`,output:t}}function fi(r,t){return{type:`xstate.done.actor.${r}`,output:t,actorId:r}}function pi(r,t){return{type:`xstate.error.actor.${r}`,error:t,actorId:r}}function Os(r){return{type:Is,input:r}}function at(r){setTimeout(()=>{throw r})}const gi=typeof Symbol=="function"&&Symbol.observable||"@@observable";function ks(r,t){const e=Vn(r),n=Vn(t);return typeof n=="string"?typeof e=="string"?n===e:!1:typeof e=="string"?e in n:Object.keys(e).every(s=>s in n?ks(e[s],n[s]):!1)}function yn(r){if(Rs(r))return r;const t=[];let e="";for(let n=0;n<r.length;n++){switch(r.charCodeAt(n)){case 92:e+=r[n+1],n++;continue;case 46:t.push(e),e="";continue}e+=r[n]}return t.push(e),t}function Vn(r){if(Xi(r))return r.value;if(typeof r!="string")return r;const t=yn(r);return yi(t)}function yi(r){if(r.length===1)return r[0];const t={};let e=t;for(let n=0;n<r.length-1;n++)if(n===r.length-2)e[r[n]]=r[n+1];else{const s=e;e={},s[r[n]]=e}return t}function Jn(r,t){const e={},n=Object.keys(r);for(let s=0;s<n.length;s++){const i=n[s];e[i]=t(r[i],i,r,s)}return e}function Cs(r){return Rs(r)?r:[r]}function dt(r){return r===void 0?[]:Cs(r)}function Xe(r,t,e,n){return typeof r=="function"?r({context:t,event:e,self:n}):r}function Rs(r){return Array.isArray(r)}function mi(r){return r.type.startsWith("xstate.error.actor")}function kt(r){return Cs(r).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function xs(r){if(!(r===void 0||r===li))return dt(r)}function Ve(r,t,e){var i,o,a;const n=typeof r=="object",s=n?r:void 0;return{next:(i=n?r.next:r)==null?void 0:i.bind(s),error:(o=n?r.error:t)==null?void 0:o.bind(s),complete:(a=n?r.complete:e)==null?void 0:a.bind(s)}}function Yn(r,t){return`${t}.${r}`}function mn(r,t){const e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return r.implementations.actors[t];const[,n,s]=e,o=r.getStateNodeById(s).config.invoke;return(Array.isArray(o)?o[n]:o).src}function Qn(r,t){return`${r.sessionId}.${t}`}let wi=0;function bi(r,t){const e=new Map,n=new Map,s=new WeakMap,i=new Set,o={},{clock:a,logger:c}=t,l={schedule:(d,p,g,y,O=Math.random().toString(36).slice(2))=>{const f={source:d,target:p,event:g,delay:y,id:O,startedAt:Date.now()},w=Qn(d,O);h._snapshot._scheduledEvents[w]=f;const T=a.setTimeout(()=>{delete o[w],delete h._snapshot._scheduledEvents[w],h._relay(d,p,g)},y);o[w]=T},cancel:(d,p)=>{const g=Qn(d,p),y=o[g];delete o[g],delete h._snapshot._scheduledEvents[g],y!==void 0&&a.clearTimeout(y)},cancelAll:d=>{for(const p in h._snapshot._scheduledEvents){const g=h._snapshot._scheduledEvents[p];g.source===d&&l.cancel(d,g.id)}}},u=d=>{if(!i.size)return;const p={...d,rootId:r.sessionId};i.forEach(g=>{var y;return(y=g.next)==null?void 0:y.call(g,p)})},h={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${wi++}`,_register:(d,p)=>(e.set(d,p),d),_unregister:d=>{e.delete(d.sessionId);const p=s.get(d);p!==void 0&&(n.delete(p),s.delete(d))},get:d=>n.get(d),_set:(d,p)=>{const g=n.get(d);if(g&&g!==p)throw new Error(`Actor with system ID '${d}' already exists.`);n.set(d,p),s.set(p,d)},inspect:d=>{const p=Ve(d);return i.add(p),{unsubscribe(){i.delete(p)}}},_sendInspectionEvent:u,_relay:(d,p,g)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:p,event:g}),p._send(g)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const d=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const p in d){const{source:g,target:y,event:O,delay:f,id:w}=d[p];l.schedule(g,y,O,f,w)}},_clock:a,_logger:c};return h}let He=!1;const wn=1;let U=function(r){return r[r.NotStarted=0]="NotStarted",r[r.Running=1]="Running",r[r.Stopped=2]="Stopped",r}({});const _i={clock:{setTimeout:(r,t)=>setTimeout(r,t),clearTimeout:r=>clearTimeout(r)},logger:console.log.bind(console),devTools:!1};class Ai{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 Xn(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=U.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={..._i,...e},{clock:s,logger:i,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:u}=n;this.system=o?o.system:bi(this,{clock:s,logger:i}),u&&!o&&this.system.inspect(Ve(u)),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=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:h=>{this._deferred.push(h)},system:this.system,stopChild:h=>{if(h._parent!==this)throw new Error(`Cannot stop child actor ${h.id} of ${this.id} because it is not a child`);h._stop()},emit:h=>{const d=this.eventListeners.get(h.type),p=this.eventListeners.get("*");if(!d&&!p)return;const g=[...d?d.values():[],...p?p.values():[]];for(const y of g)y(h)},actionExecutor:h=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:h.type,params:h.params}}),!h.exec)return;const p=He;try{He=!0,h.exec(h.info,h.params)}finally{He=p}};this._processingStatus===U.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(n){this._snapshot={status:"error",output:void 0,error:n}}}update(t,e){var s,i;this._snapshot=t;let n;for(;n=this._deferred.shift();)try{n()}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{(s=o.next)==null||s.call(o,t)}catch(a){at(a)}break;case"done":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){at(a)}this._stopProcedure(),this._complete(),this._doneEvent=fi(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){var i;const s=Ve(t,e,n);if(this._processingStatus!==U.Stopped)this.observers.add(s);else switch(this._snapshot.status){case"done":try{(i=s.complete)==null||i.call(s)}catch(o){at(o)}break;case"error":{const o=this._snapshot.error;if(!s.error)at(o);else try{s.error(o)}catch(a){at(a)}break}}return{unsubscribe:()=>{this.observers.delete(s)}}}on(t,e){let n=this.eventListeners.get(t);n||(n=new Set,this.eventListeners.set(t,n));const s=e.bind(void 0);return n.add(s),{unsubscribe:()=>{n.delete(s)}}}start(){if(this._processingStatus===U.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=U.Running;const t=Os(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(s){n={err:s}}if(n){const{err:s}=n;this._snapshot={...this._snapshot,status:"error",error:s},this._error(s);return}this.update(e,t),t.type===Ze&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===U.Stopped?this:(this.mailbox.clear(),this._processingStatus===U.NotStarted?(this._processingStatus=U.Stopped,this):(this.mailbox.enqueue({type:Ze}),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(n){at(n)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||at(t);return}let e=!1;for(const n of this.observers){const s=n.error;e||(e=!s);try{s==null||s(t)}catch(i){at(i)}}this.observers.clear(),e&&at(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,pi(this.id,t))}_stopProcedure(){return this._processingStatus!==U.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Xn(this._process.bind(this)),this._processingStatus=U.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==U.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:ci)(this)}toJSON(){return{xstate$$type:wn,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[gi](){return this}getSnapshot(){return this._snapshot}}function Dt(r,...[t]){return new Ai(r,t)}function Ei(r,t,e,n,{sendId:s}){const i=typeof s=="function"?s(e,n):s;return[t,{sendId:i},void 0]}function Ni(r,t){r.defer(()=>{r.system.scheduler.cancel(r.self,t.sendId)})}function vi(r){function t(e,n){}return t.type="xstate.cancel",t.sendId=r,t.resolve=Ei,t.execute=Ni,t}function Si(r,t,e,n,{id:s,systemId:i,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?mn(t.machine,o):o,u=typeof s=="function"?s(e):s;let h,d;return l&&(d=typeof a=="function"?a({context:t.context,event:e.event,self:r.self}):a,h=Dt(l,{id:u,src:o,parent:r.self,syncSnapshot:c,systemId:i,input:d})),[St(t,{children:{...t.children,[u]:h}}),{id:s,systemId:i,actorRef:h,src:o,input:d},void 0]}function Ti(r,{actorRef:t}){t&&r.defer(()=>{t._processingStatus!==U.Stopped&&t.start()})}function Ii(...[r,{id:t,systemId:e,input:n,syncSnapshot:s=!1}={}]){function i(o,a){}return i.type="xstate.spawnChild",i.id=t,i.systemId=e,i.src=r,i.input=n,i.syncSnapshot=s,i.resolve=Si,i.execute=Ti,i}function Oi(r,t,e,n,{actorRef:s}){const i=typeof s=="function"?s(e,n):s,o=typeof i=="string"?t.children[i]:i;let a=t.children;return o&&(a={...a},delete a[o.id]),[St(t,{children:a}),o,void 0]}function ki(r,t){if(t){if(r.system._unregister(t),t._processingStatus!==U.Running){r.stopChild(t);return}r.defer(()=>{r.stopChild(t)})}}function Ms(r){function t(e,n){}return t.type="xstate.stopChild",t.actorRef=r,t.resolve=Oi,t.execute=ki,t}function bn(r,t,e,n){const{machine:s}=n,i=typeof r=="function",o=i?r:s.implementations.guards[typeof r=="string"?r:r.type];if(!i&&!o)throw new Error(`Guard '${typeof r=="string"?r:r.type}' is not implemented.'.`);if(typeof o!="function")return bn(o,t,e,n);const a={context:t,event:e},c=i||typeof r=="string"?void 0:"params"in r?typeof r.params=="function"?r.params({context:t,event:e}):r.params:void 0;return"check"in o?o.check(n,a,o):o(a,c)}const _n=r=>r.type==="atomic"||r.type==="final";function Kt(r){return Object.values(r.states).filter(t=>t.type!=="history")}function Qt(r,t){const e=[];if(t===r)return e;let n=r.parent;for(;n&&n!==t;)e.push(n),n=n.parent;return e}function ue(r){const t=new Set(r),e=Ps(t);for(const n of t)if(n.type==="compound"&&(!e.get(n)||!e.get(n).length))ts(n).forEach(s=>t.add(s));else if(n.type==="parallel"){for(const s of Kt(n))if(s.type!=="history"&&!t.has(s)){const i=ts(s);for(const o of i)t.add(o)}}for(const n of t){let s=n.parent;for(;s;)t.add(s),s=s.parent}return t}function $s(r,t){const e=t.get(r);if(!e)return{};if(r.type==="compound"){const s=e[0];if(s){if(_n(s))return s.key}else return{}}const n={};for(const s of e)n[s.key]=$s(s,t);return n}function Ps(r){const t=new Map;for(const e of r)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 Hs(r,t){const e=ue(t);return $s(r,Ps(e))}function An(r,t){return t.type==="compound"?Kt(t).some(e=>e.type==="final"&&r.has(e)):t.type==="parallel"?Kt(t).every(e=>An(r,e)):t.type==="final"}const me=r=>r[0]===ui;function Ci(r,t){return r.transitions.get(t)||[...r.transitions.keys()].filter(n=>{if(n===hi)return!0;if(!n.endsWith(".*"))return!1;const s=n.split("."),i=t.split(".");for(let o=0;o<s.length;o++){const a=s[o],c=i[o];if(a==="*")return o===s.length-1;if(a!==c)return!1}return!0}).sort((n,s)=>s.length-n.length).flatMap(n=>r.transitions.get(n))}function Ri(r){const t=r.config.after;if(!t)return[];const e=s=>{const i=di(s,r.id),o=i.type;return r.entry.push(ro(i,{id:o,delay:s})),r.exit.push(vi(o)),o};return Object.keys(t).flatMap(s=>{const i=t[s],o=typeof i=="string"?{target:i}:i,a=Number.isNaN(+s)?s:+s,c=e(a);return dt(o).map(l=>({...l,event:c,delay:a}))}).map(s=>{const{delay:i}=s;return{..._t(r,s.event,s),delay:i}})}function _t(r,t,e){const n=xs(e.target),s=e.reenter??!1,i=$i(r,n),o={...e,actions:dt(e.actions),guard:e.guard,target:i,source:r,reenter:s,eventType:t,toJSON:()=>({...o,source:`#${r.id}`,target:i?i.map(a=>`#${a.id}`):void 0})};return o}function xi(r){const t=new Map;if(r.config.on)for(const e of Object.keys(r.config.on)){if(e===Ts)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=r.config.on[e];t.set(e,kt(n).map(s=>_t(r,e,s)))}if(r.config.onDone){const e=`xstate.done.state.${r.id}`;t.set(e,kt(r.config.onDone).map(n=>_t(r,e,n)))}for(const e of r.invoke){if(e.onDone){const n=`xstate.done.actor.${e.id}`;t.set(n,kt(e.onDone).map(s=>_t(r,n,s)))}if(e.onError){const n=`xstate.error.actor.${e.id}`;t.set(n,kt(e.onError).map(s=>_t(r,n,s)))}if(e.onSnapshot){const n=`xstate.snapshot.${e.id}`;t.set(n,kt(e.onSnapshot).map(s=>_t(r,n,s)))}}for(const e of r.after){let n=t.get(e.eventType);n||(n=[],t.set(e.eventType,n)),n.push(e)}return t}function Mi(r,t){const e=typeof t=="string"?r.states[t]:t?r.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${r.id}`);const n={source:r,actions:!t||typeof t=="string"?[]:dt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...n,source:`#${r.id}`,target:e?[`#${e.id}`]:[]})};return n}function $i(r,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(me(e))return r.machine.getStateNodeById(e);const n=e[0]===Ss;if(n&&!r.parent)return he(r,e.slice(1));const s=n?r.key+e:e;if(r.parent)try{return he(r.parent,s)}catch(i){throw new Error(`Invalid transition definition for state node '${r.id}':
|
|
14
|
+
${i.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function Bs(r){const t=xs(r.config.target);return t?{target:t.map(e=>typeof e=="string"?he(r.parent,e):e)}:r.parent.initial}function At(r){return r.type==="history"}function ts(r){const t=Ws(r);for(const e of t)for(const n of Qt(e,r))t.add(n);return t}function Ws(r){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 s of Kt(n))e(s)}}return e(r),t}function Lt(r,t){if(me(t))return r.machine.getStateNodeById(t);if(!r.states)throw new Error(`Unable to retrieve child state '${t}' from '${r.id}'; no child states exist.`);const e=r.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${r.id}'`);return e}function he(r,t){if(typeof t=="string"&&me(t))try{return r.machine.getStateNodeById(t)}catch{}const e=yn(t).slice();let n=r;for(;e.length;){const s=e.shift();if(!s.length)break;n=Lt(n,s)}return n}function de(r,t){if(typeof t=="string"){const s=r.states[t];if(!s)throw new Error(`State '${t}' does not exist on '${r.id}'`);return[r,s]}const e=Object.keys(t),n=e.map(s=>Lt(r,s)).filter(Boolean);return[r.machine.root,r].concat(n,e.reduce((s,i)=>{const o=Lt(r,i);if(!o)return s;const a=de(o,t[i]);return s.concat(a)},[]))}function Pi(r,t,e,n){const i=Lt(r,t).next(e,n);return!i||!i.length?r.next(e,n):i}function Hi(r,t,e,n){const s=Object.keys(t),i=Lt(r,s[0]),o=En(i,t[s[0]],e,n);return!o||!o.length?r.next(e,n):o}function Bi(r,t,e,n){const s=[];for(const i of Object.keys(t)){const o=t[i];if(!o)continue;const a=Lt(r,i),c=En(a,o,e,n);c&&s.push(...c)}return s.length?s:r.next(e,n)}function En(r,t,e,n){return typeof t=="string"?Pi(r,t,e,n):Object.keys(t).length===1?Hi(r,t,e,n):Bi(r,t,e,n)}function Wi(r){return Object.keys(r.states).map(t=>r.states[t]).filter(t=>t.type==="history")}function gt(r,t){let e=r;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function Di(r,t){const e=new Set(r),n=new Set(t);for(const s of e)if(n.has(s))return!0;for(const s of n)if(e.has(s))return!0;return!1}function Ds(r,t,e){const n=new Set;for(const s of r){let i=!1;const o=new Set;for(const a of n)if(Di(Je([s],t,e),Je([a],t,e)))if(gt(s.source,a.source))o.add(a);else{i=!0;break}if(!i){for(const a of o)n.delete(a);n.add(s)}}return Array.from(n)}function Ki(r){const[t,...e]=r;for(const n of Qt(t,void 0))if(e.every(s=>gt(s,n)))return n}function Nn(r,t){if(!r.target)return[];const e=new Set;for(const n of r.target)if(At(n))if(t[n.id])for(const s of t[n.id])e.add(s);else for(const s of Nn(Bs(n),t))e.add(s);else e.add(n);return[...e]}function Ks(r,t){const e=Nn(r,t);if(!e)return;if(!r.reenter&&e.every(s=>s===r.source||gt(s,r.source)))return r.source;const n=Ki(e.concat(r.source));if(n)return n;if(!r.reenter)return r.source.machine.root}function Je(r,t,e){var s;const n=new Set;for(const i of r)if((s=i.target)!=null&&s.length){const o=Ks(i,e);i.reenter&&i.source===o&&n.add(o);for(const a of t)gt(a,o)&&n.add(a)}return[...n]}function Li(r,t){if(r.length!==t.size)return!1;for(const e of r)if(!t.has(e))return!1;return!0}function Ye(r,t,e,n,s,i){if(!r.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=Ds(r,o,a);let l=t;s||([l,a]=Ui(l,n,e,c,o,a,i,e.actionExecutor)),l=jt(l,n,e,c.flatMap(h=>h.actions),i,void 0),l=zi(l,n,e,c,o,i,a,s);const u=[...o];l.status==="done"&&(l=jt(l,n,e,u.sort((h,d)=>d.order-h.order).flatMap(h=>h.exit),i,void 0));try{return a===t.historyValue&&Li(t._nodes,o)?l:St(l,{_nodes:u,historyValue:a})}catch(h){throw h}}function ji(r,t,e,n,s){if(n.output===void 0)return;const i=qe(s.id,s.output!==void 0&&s.parent?Xe(s.output,r.context,t,e.self):void 0);return Xe(n.output,r.context,i,e.self)}function zi(r,t,e,n,s,i,o,a){let c=r;const l=new Set,u=new Set;Fi(n,o,u,l),a&&u.add(r.machine.root);const h=new Set;for(const d of[...l].sort((p,g)=>p.order-g.order)){s.add(d);const p=[];p.push(...d.entry);for(const g of d.invoke)p.push(Ii(g.src,{...g,syncSnapshot:!!g.onSnapshot}));if(u.has(d)){const g=d.initial.actions;p.push(...g)}if(c=jt(c,t,e,p,i,d.invoke.map(g=>g.id)),d.type==="final"){const g=d.parent;let y=(g==null?void 0:g.type)==="parallel"?g:g==null?void 0:g.parent,O=y||d;for((g==null?void 0:g.type)==="compound"&&i.push(qe(g.id,d.output!==void 0?Xe(d.output,c.context,t,e.self):void 0));(y==null?void 0:y.type)==="parallel"&&!h.has(y)&&An(s,y);)h.add(y),i.push(qe(y.id)),O=y,y=y.parent;if(y)continue;c=St(c,{status:"done",output:ji(c,t,e,c.machine.root,O)})}}return c}function Fi(r,t,e,n){for(const s of r){const i=Ks(s,t);for(const a of s.target||[])!At(a)&&(s.source!==a||s.source!==i||s.reenter)&&(n.add(a),e.add(a)),Rt(a,t,e,n);const o=Nn(s,t);for(const a of o){const c=Qt(a,i);(i==null?void 0:i.type)==="parallel"&&c.push(i),Ls(n,t,e,c,!s.source.parent&&s.reenter?void 0:i)}}}function Rt(r,t,e,n){var s;if(At(r))if(t[r.id]){const i=t[r.id];for(const o of i)n.add(o),Rt(o,t,e,n);for(const o of i)Be(o,r.parent,n,t,e)}else{const i=Bs(r);for(const o of i.target)n.add(o),i===((s=r.parent)==null?void 0:s.initial)&&e.add(r.parent),Rt(o,t,e,n);for(const o of i.target)Be(o,r.parent,n,t,e)}else if(r.type==="compound"){const[i]=r.initial.target;At(i)||(n.add(i),e.add(i)),Rt(i,t,e,n),Be(i,r,n,t,e)}else if(r.type==="parallel")for(const i of Kt(r).filter(o=>!At(o)))[...n].some(o=>gt(o,i))||(At(i)||(n.add(i),e.add(i)),Rt(i,t,e,n))}function Ls(r,t,e,n,s){for(const i of n)if((!s||gt(i,s))&&r.add(i),i.type==="parallel")for(const o of Kt(i).filter(a=>!At(a)))[...r].some(a=>gt(a,o))||(r.add(o),Rt(o,t,e,r))}function Be(r,t,e,n,s){Ls(e,n,s,Qt(r,t))}function Ui(r,t,e,n,s,i,o,a){let c=r;const l=Je(n,s,i);l.sort((h,d)=>d.order-h.order);let u;for(const h of l)for(const d of Wi(h)){let p;d.history==="deep"?p=g=>_n(g)&>(g,h):p=g=>g.parent===h,u??(u={...i}),u[d.id]=Array.from(s).filter(p)}for(const h of l)c=jt(c,t,e,[...h.exit,...h.invoke.map(d=>Ms(d.id))],o,void 0),s.delete(h);return[c,u||i]}function Gi(r,t){return r.implementations.actions[t]}function js(r,t,e,n,s,i){const{machine:o}=r;let a=r;for(const c of n){const l=typeof c=="function",u=l?c:Gi(o,typeof c=="string"?c:c.type),h={context:a.context,event:t,self:e.self,system:e.system},d=l||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:t}):c.params:void 0;if(!u||!("resolve"in u)){e.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:h,params:d,exec:u});continue}const p=u,[g,y,O]=p.resolve(e,a,h,d,u,s);a=g,"retryResolve"in p&&(i==null||i.push([p,y])),"execute"in p&&e.actionExecutor({type:p.type,info:h,params:y,exec:p.execute.bind(null,e,y)}),O&&(a=js(a,t,e,O,s,i))}return a}function jt(r,t,e,n,s,i){const o=i?[]:void 0,a=js(r,t,e,n,{internalQueue:s,deferredActorIds:i},o);return o==null||o.forEach(([c,l])=>{c.retryResolve(e,a,l)}),a}function We(r,t,e,n){let s=r;const i=[];function o(l,u,h){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:u,snapshot:l,_transitions:h}),i.push(l)}if(t.type===Ze)return s=St(es(s,t,e),{status:"stopped"}),o(s,t,[]),{snapshot:s,microstates:i};let a=t;if(a.type!==Is){const l=a,u=mi(l),h=ns(l,s);if(u&&!h.length)return s=St(r,{status:"error",error:l.error}),o(s,l,[]),{snapshot:s,microstates:i};s=Ye(h,r,e,a,!1,n),o(s,l,h)}let c=!0;for(;s.status==="active";){let l=c?Zi(s,a):[];const u=l.length?s:void 0;if(!l.length){if(!n.length)break;a=n.shift(),l=ns(a,s)}s=Ye(l,s,e,a,!1,n),c=s!==u,o(s,a,l)}return s.status!=="active"&&es(s,a,e),{snapshot:s,microstates:i}}function es(r,t,e){return jt(r,t,e,Object.values(r.children).map(n=>Ms(n)),[],void 0)}function ns(r,t){return t.machine.getTransitionData(t,r)}function Zi(r,t){const e=new Set,n=r._nodes.filter(_n);for(const s of n)t:for(const i of[s].concat(Qt(s,void 0)))if(i.always){for(const o of i.always)if(o.guard===void 0||bn(o.guard,r.context,t,r)){e.add(o);break t}}return Ds(Array.from(e),new Set(r._nodes),r.historyValue)}function qi(r,t){const e=ue(de(r,t));return Hs(r,[...e])}function Xi(r){return!!r&&typeof r=="object"&&"machine"in r&&"value"in r}const Vi=function(t){return ks(t,this.value)},Ji=function(t){return this.tags.has(t)},Yi=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(n=>n.target!==void 0||n.actions.length)},Qi=function(){const{_nodes:t,tags:e,machine:n,getMeta:s,toJSON:i,can:o,hasTag:a,matches:c,...l}=this;return{...l,tags:Array.from(e)}},to=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function oe(r,t){return{status:r.status,output:r.output,error:r.error,machine:t,context:r.context,_nodes:r._nodes,value:Hs(t.root,r._nodes),tags:new Set(r._nodes.flatMap(e=>e.tags)),children:r.children,historyValue:r.historyValue||{},matches:Vi,hasTag:Ji,can:Yi,getMeta:to,toJSON:Qi}}function St(r,t={}){return oe({...r,...t},r.machine)}function eo(r,t){const{_nodes:e,tags:n,machine:s,children:i,context:o,can:a,hasTag:c,matches:l,getMeta:u,toJSON:h,...d}=r,p={};for(const y in i){const O=i[y];p[y]={snapshot:O.getPersistedSnapshot(t),src:O.src,systemId:O._systemId,syncSnapshot:O._syncSnapshot}}return{...d,context:zs(o),children:p}}function zs(r){let t;for(const e in r){const n=r[e];if(n&&typeof n=="object")if("sessionId"in n&&"send"in n&&"ref"in n)t??(t=Array.isArray(r)?r.slice():{...r}),t[e]={xstate$$type:wn,id:n.id};else{const s=zs(n);s!==n&&(t??(t=Array.isArray(r)?r.slice():{...r}),t[e]=s)}}return t??r}function no(r,t,e,n,{event:s,id:i,delay:o},{internalQueue:a}){const c=t.machine.implementations.delays;if(typeof s=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${s}" }) instead`);const l=typeof s=="function"?s(e,n):s;let u;if(typeof o=="string"){const h=c&&c[o];u=typeof h=="function"?h(e,n):h}else u=typeof o=="function"?o(e,n):o;return typeof u!="number"&&a.push(l),[t,{event:l,id:i,delay:u},void 0]}function so(r,t){const{event:e,delay:n,id:s}=t;if(typeof n=="number"){r.defer(()=>{const i=r.self;r.system.scheduler.schedule(i,i,e,n,s)});return}}function ro(r,t){function e(n,s){}return e.type="xstate.raise",e.event=r,e.id=t==null?void 0:t.id,e.delay=t==null?void 0:t.delay,e.resolve=no,e.execute=so,e}function io(r,{machine:t,context:e},n,s){const i=(o,a)=>{if(typeof o=="string"){const c=mn(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=Dt(c,{id:a==null?void 0:a.id,parent:r.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:typeof(a==null?void 0:a.input)=="function"?a.input({context:e,event:n,self:r.self}):a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId});return s[l.id]=l,l}else return Dt(o,{id:a==null?void 0:a.id,parent:r.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=i(o,a);return s[c.id]=c,r.defer(()=>{c._processingStatus!==U.Stopped&&c.start()}),c}}function oo(r,t,e,n,{assignment:s}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},o={context:t.context,event:e.event,spawn:io(r,t,e.event,i),self:r.self,system:r.system};let a={};if(typeof s=="function")a=s(o,n);else for(const l of Object.keys(s)){const u=s[l];a[l]=typeof u=="function"?u(o,n):u}const c=Object.assign({},t.context,a);return[St(t,{context:c,children:Object.keys(i).length?{...t.children,...i}:t.children}),void 0,void 0]}function ao(r){function t(e,n){}return t.type="xstate.assign",t.assignment=r,t.resolve=oo,t}const ss=new WeakMap;function Ot(r,t,e){let n=ss.get(r);return n?t in n||(n[t]=e()):(n={[t]:e()},ss.set(r,n)),n[t]}const co={},zt=r=>typeof r=="string"?{type:r}:typeof r=="function"?"resolve"in r?{type:r.type}:{type:r.name}:r;class vn{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(Ss),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?Jn(this.config.states,(n,s)=>new vn(n,{_parent:this,_key:s,_machine:this.machine})):co,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=dt(this.config.entry).slice(),this.exit=dt(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=dt(t.tags).slice()}_initialize(){this.transitions=xi(this),this.config.always&&(this.always=kt(this.config.always).map(t=>_t(this,Ts,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:Jn(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 Ot(this,"invoke",()=>dt(this.config.invoke).map((t,e)=>{const{src:n,systemId:s}=t,i=t.id??Yn(this.id,e),o=typeof n=="string"?n:`xstate.invoke.${Yn(this.id,e)}`;return{...t,src:o,id:i,systemId:s,toJSON(){const{onDone:a,onError:c,...l}=t;return{...l,type:"xstate.invoke",src:o,id:i}}}}))}get on(){return Ot(this,"on",()=>[...this.transitions].flatMap(([e,n])=>n.map(s=>[e,s])).reduce((e,[n,s])=>(e[n]=e[n]||[],e[n].push(s),e),{}))}get after(){return Ot(this,"delayedTransitions",()=>Ri(this))}get initial(){return Ot(this,"initial",()=>Mi(this,this.config.initial))}next(t,e){const n=e.type,s=[];let i;const o=Ot(this,`candidates-${n}`,()=>Ci(this,n));for(const a of o){const{guard:c}=a,l=t.context;let u=!1;try{u=!c||bn(c,l,e,t)}catch(h){const d=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${d?`'${d}' `:""}in transition for event '${n}' in state node '${this.id}':
|
|
15
|
+
${h.message}`)}if(u){s.push(...a.actions),i=a;break}}return i?[i]:void 0}get events(){return Ot(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const n of Object.keys(t)){const s=t[n];if(s.states)for(const i of s.events)e.add(`${i}`)}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 lo="#";class Sn{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:(e==null?void 0:e.actors)??{},actions:(e==null?void 0:e.actions)??{},delays:(e==null?void 0:e.delays)??{},guards:(e==null?void 0:e.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new vn(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:s,delays:i}=this.implementations;return new Sn(this.config,{actions:{...e,...t.actions},guards:{...n,...t.guards},actors:{...s,...t.actors},delays:{...i,...t.delays}})}resolveState(t){const e=qi(this.root,t.value),n=ue(de(this.root,e));return oe({_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 We(t,e,n,[]).snapshot}microstep(t,e,n){return We(t,e,n,[]).microstates}getTransitionData(t,e){return En(this.root,t.value,t,e)||[]}getPreInitialState(t,e,n){const{context:s}=this.config,i=oe({context:typeof s!="function"&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);return typeof s=="function"?jt(i,e,t,[ao(({spawn:a,event:c,self:l})=>s({spawn:a,input:c.input,self:l}))],n,void 0):i}getInitialSnapshot(t,e){const n=Os(e),s=[],i=this.getPreInitialState(t,n,s),o=Ye([{target:[...Ws(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],i,t,n,!0,s),{snapshot:a}=We(o,n,t,s);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=yn(t),n=e.slice(1),s=me(e[0])?e[0].slice(lo.length):e[0],i=this.idMap.get(s);if(!i)throw new Error(`Child state node '#${s}' does not exist on machine '${this.id}'`);return he(i,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return eo(t,e)}restoreSnapshot(t,e){const n={},s=t.children;Object.keys(s).forEach(c=>{const l=s[c],u=l.snapshot,h=l.src,d=typeof h=="string"?mn(this,h):h;if(!d)return;const p=Dt(d,{id:c,parent:e.self,syncSnapshot:l.syncSnapshot,snapshot:u,src:h,systemId:l.systemId});n[c]=p});const i=oe({...t,children:n,_nodes:Array.from(ue(de(this.root,t.value)))},this),o=new Set;function a(c,l){if(!o.has(c)){o.add(c);for(const u in c){const h=c[u];if(h&&typeof h=="object"){if("xstate$$type"in h&&h.xstate$$type===wn){c[u]=l[h.id];continue}a(h,l)}}}}return a(i.context,n),i}}function uo(r,t){return new Sn(r,t)}const re=r=>r===!1?!1:r.map(t=>t.serialize()),ho=r=>r===!1?!1:r.serialize(),fo=r=>r===!1?!1:r.map(t=>({tile:t.tile.toString(),candidates:t.candidates.map(e=>e.toString()),shanten:t.shanten})),Qe=r=>JSON.parse(JSON.stringify(r)),ie=r=>r===!1?!1:Qe(r),tn=r=>uo({id:"Untitled",initial:"distribute",context:{currentWind:R.E,oneShotMap:F(!1),missingMap:F(!1),controller:r,genEventID:Fs()},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:`可能なアクションとその詳細を通知\\
|
|
10
16
|
DISCARD の場合は捨てられる牌の一覧`}}},waiting_user_event_after_drawn:{description:"ツモった1ユーザからのレスポンス待ち",on:{TSUMO:{target:"tsumo",guard:"canWin"},REACH:{target:"waiting_reach_acceptance",actions:[{type:"notify_reach"},{type:"notify_choice_for_reach_acceptance"}],guard:{type:"canReach"}},SHO_KAN:{target:"an_sho_kaned"},AN_KAN:{target:"an_sho_kaned"},DISCARD:{target:"discarded",description:"入力に牌が必須",actions:{type:"disable_one_shot_for_me"}},DRAWN_GAME_BY_NINE_ORPHANS:{target:"drawn_game"}}},discarded:{entry:{type:"notify_discard"},on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"},description:`可能なアクションとその詳細を通知\\
|
|
11
17
|
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 に対するレスポンスを待つ\\
|
|
12
18
|
ユーザからではなく、controller が優先順位を考慮して遷移させる必要がある\\
|
|
13
|
-
通知する 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=kt(n)},notify_distribution:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.initialHands();for(const r of Object.values(v)){const o=Z("_____________");o[r]=i[r].toString();const a={id:n,type:"DISTRIBUTE",hands:o,wind:r,doraMarker:t.controller.wall.doraMarkers[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:Ue(t.controller.doWin(i,r,{oneShot:t.oneShotMap[i],replacementWin:n==null?void 0:n.replacementWin})),REACH:dh(t.controller.doReach(i)),AN_KAN:Le(t.controller.doAnKan(i)),SHO_KAN:Le(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:y.HORIZONTAL});for(const o of Object.values(v)){const a={id:n,type:"CHOICE_AFTER_DISCARDED",wind:o,discarterInfo:{wind:i.w,tile:i.t.toString()},choices:{RON:Ue(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:Le(t.controller.doPon(o,i.w,r)),CHI:Le(t.controller.doChi(o,i.w,r)),DAI_KAN:fh(t.controller.doDaiKan(o,i.w,r))}};a.choices.RON&&(t.missingMap[o]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(v))},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 dt||a instanceof _t)&&(o=t.controller.doDiscard(r,a));const c={id:i,type:"CHOICE_AFTER_CALLED",wind:r,choices:{DISCARD:o.map(h=>h.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:y.HORIZONTAL});for(const o of Object.values(v)){const a={id:n,type:"CHOICE_FOR_REACH_ACCEPTANCE",wind:o,reacherInfo:{wind:i.w,tile:r.toString()},choices:{RON:Ue(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(v))},notify_choice_for_chankan:({context:t,event:e})=>{O(e.type=="SHO_KAN"||e.type=="AN_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.block.tiles[0].clone({remove:y.HORIZONTAL});for(const r of Object.values(v)){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:n,type:"CHOICE_FOR_CHAN_KAN",wind:r,callerInfo:{wind:e.iam,tile:i.toString()},choices:{RON:e.type=="SHO_KAN"?Ue(o):!1}};a.choices.RON&&(t.missingMap[r]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(v))},notify_call:({context:t,event:e})=>{O(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(v)){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})=>{O(e.type=="DISCARD",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind,r=e.tile;for(const o of Object.values(v)){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==null?void 0: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(v)){let h=new w(p.BACK,0,[y.TSUMO]);c==a&&(h=o);const l={id:i,type:"DRAW",subType:r,iam:a,wind:c,tile:h.toString()};t.controller.emit(l)}t.controller.next()},notify_ron:({context:t,event:e})=>{O(e.type=="RON");const n=t.genEventID(),i=e.iam;for(const r of Object.values(v)){const o={id:n,type:e.type,iam:i,wind:r,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:qn(e.ret)};t.controller.emit(o)}},notify_tsumo:({context:t,event:e})=>{O(e.type=="TSUMO",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind;for(const r of Object.values(v)){const o={id:n,type:e.type,iam:i,wind:r,lastTile:t.controller.hand(i).drawn.toString(),ret:qn(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{O(e.type=="REACH",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam,r=e.tile.clone({add:y.HORIZONTAL});t.oneShotMap[i]=!0;for(const o of Object.values(v)){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})=>{O(e.type=="REACH_ACCEPT");const n=t.genEventID();for(const i of Object.values(v)){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.openDoraMarker();for(const r of Object.values(v)){const o={id:n,type:"NEW_DORA",wind:r,doraMarker:i.toString()};t.controller.emit(o)}}e.type=="SHO_KAN"},disable_one_shot:({context:t,event:e})=>{for(const n of Object.values(v))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=Z("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){i[e.iam]=t.controller.hand(e.iam).toString();for(const r of Object.values(v)){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:Z(0),hands:i};t.controller.emit(o)}}else if(e.type=="RON"||e.type=="TSUMO"){const r=e.iam==v.E,o=t.controller.finalResult(e.ret,e.iam);for(const a of Object.values(v)){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(v)){const a={id:n,type:"END_GAME",subType:r,wind:o,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:Z(0),hands:Z("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const r=[];for(const h of Object.values(v)){const l=t.controller.hand(h);new We(l).calc()==0&&(r.push(h),i[h]=l.toString())}const o=r.length==0||r.length==4,a=Z(0);for(const h of Object.values(v))r.includes(h)?a[h]+=o?0:3e3/r.length:a[h]-=o?0:3e3/(4-r.length);const c=r.length==4||a[v.E]>0;for(const h of Object.values(v)){const l={id:n,type:"END_GAME",subType:"DRAWN_GAME",wind:h,shouldContinue:c,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:a,hands:i};t.controller.emit(l)}}}}},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 cr(s=0){let t=s;return()=>(t++).toString()}class Wt{constructor(t){A(this,"walls",{replacement:[],dead:[],doraMarkers:[],blindDoraMarkers:[],drawable:[]});A(this,"backup");A(this,"openedDoraCount",1);this.init(t),this.backup=Wt.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())}openDoraMarker(){if(this.openedDoraCount>=4)throw new Error("exceeded maximum open dora");return this.openedDoraCount++,w.from(this.walls.doraMarkers[this.openedDoraCount-1])}get doraMarkers(){return this.walls.doraMarkers.slice(0,this.openedDoraCount).map(w.from)}get blindDoraMarkers(){return this.walls.blindDoraMarkers.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=Z("");for(let e=0;e<3;e++)for(const n of Object.values(v))for(let i=0;i<4;i++)t[n]+=this.draw().toString();for(const e of Object.values(v))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=Wt.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:y.RED})),this.walls.drawable.push(o.toString())}}gs(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.blindDoraMarkers.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.doraMarkers.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(),doraMarkers:t.doraMarkers.concat(),blindDoraMarkers:t.blindDoraMarkers.concat(),replacement:t.replacement.concat()}}}class je{constructor(t,e){A(this,"wall",new Wt);A(this,"playerIDs");A(this,"actor",ce(Gn(this),{}));A(this,"observer");A(this,"handlers",{});A(this,"mailBox",{});A(this,"histories",[]);A(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 n=zi();this.observer=new hr(n),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const i=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new ke(i);const r=(e==null?void 0:e.shuffle)==!1?this.playerIDs:gs([...this.playerIDs]);this.observer.placeManager=new Te({[r[0]]:v.E,[r[1]]:v.S,[r[2]]:v.W,[r[3]]:v.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(y.HORIZONTAL)?2:1}return{doraMarkers:this.observer.doraMarkers,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=Bi(n);if(r.events.length==0){this.actor.send({type:""});return}const o=r.events[0];switch(r.type){case"RON":O(o.choices.RON,"ron choice is none"),this.actor.send({type:r.type,iam:o.wind,ret:we(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:w.from(o.discarterInfo.tile)}});break;case"DAI_KAN":O(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:r.type,iam:o.wind,block:wt.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[r.type];O(a,`${r.type} choice is none`),O(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const c=B.deserialize(a[0]);this.actor.send({type:r.type,iam:o.wind,block:c})}}else if(i.type=="CHOICE_AFTER_DRAWN"){const r=Wi(n);O(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":O(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:r.type,ret:we(o.choices.TSUMO),lastTile:w.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[r.type];O(c,`${r.type} candidates is none`),this.actor.send({type:"REACH",tile:w.from(c[0].tile),iam:a});break;case"DISCARD":const h=o.choices[r.type];O(h,`${r.type} choice is none`),this.actor.send({type:r.type,tile:w.from(h[0]).clone({remove:y.TSUMO}),iam:a});break;case"AN_KAN":{const l=o.choices[r.type];O(l,`${r.type} choice is none`),this.actor.send({type:r.type,block:U.from(l[0].tiles),iam:a});break}case"SHO_KAN":{const l=o.choices[r.type];O(l,`${r.type} choice is none`),this.actor.send({type:r.type,block:ct.from(l[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"){O(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=>(O(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:we(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];O(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:we(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 je(r);return o.playerIDs=n,o.mailBox=e,o.observer.placeManager=new Te(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new ke(t.scores),o.wall=new Wt(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 Wt,this.observer.applied={},this.mailBox={},this.actor=ce(Gn(this)),!this.placeManager.is(j.W1););}finalResult(t,e){const n=this.hand(e),i=n.reached?this.wall.blindDoraMarkers:void 0,r=new Wn(n,{...t.boardContext,sticks:this.placeManager.sticks,blindDoraMarkers:i}).calc(t.hand);return O(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==null?void 0:n.replacementWin;r.oneShotWin=n==null?void 0:n.oneShot;const o=new Hi(i),a=new Wn(i,r),c=o.calc(e),h=a.calc(...c);if(!h||h.points.length==0)return!1;if(i.draw==null){const l=ae.candidateTiles(this.hand(t)).candidates;if(this.river.discards(t).some(u=>l.some(f=>f.equals(u.t))))return!1}return h}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=An(t,e,b.PON),a=[],c=new _t([r,r,r]).clone({replace:{idx:o,tile:n.clone({add:y.HORIZONTAL})}});let h=c;z(n)&&n.has(y.RED)&&(h=c.clone({replace:{idx:o,tile:r.clone({add:[y.RED,y.HORIZONTAL]})}}));const l=o%2+1;if(z(n)&&i.get(n.t,0)>0&&(h=c.clone({replace:{idx:l,tile:r.clone({add:y.RED})}})),a.push(h),z(r)&&i.get(r.t,5)==3){const u=c.clone({replace:{idx:l,tile:r}});a.push(u)}return a}doChi(t,e,n){if(n==null||!n.isNum()||kt(e)!=t)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3)return!1;const r=n.clone({remove:y.TSUMO,add:[y.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 dt([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 dt([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 dt([r,new w(n.t,r.n-1),new w(n.t,r.n+1)]));for(let f=0;f<o.length;f++){const m=o[f],d=this.cannotDiscardTile(m),g=[];for(const D of d){const R=i.get(D.t,D.n);for(let q=0;q<R;q++)g.push(D.clone({remove:y.RED}))}const _=i.dec([...g,m.tiles[1],m.tiles[2]]),S=i.hands.length==0;i.inc(_),S&&o.splice(f,1)}if(o.length==0)return!1;const u=i.get(n.t,0)>0?this.redPattern(o):[];return u.length>0&&i.get(n.t,5)==1?u:[...o,...u]}redPattern(t){return t.length==0?[]:t.filter(n=>z(n.tiles[1])||z(n.tiles[2])).map(n=>{if(z(n.tiles[1])){const i=n.tiles[1].clone({add:y.RED});return n.clone({replace:{idx:1,tile:i}})}else if(z(n.tiles[2])){const i=n.tiles[2].clone({add:y.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 We(e).calc()>0?!1:ae.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 _t)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 O(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 rt())if(e.get(i,r)==4){const o=new w(i,r),a=[o,o,o,o];z(o)&&(a[1]=o.clone({add:y.RED})),n.push(new U(a))}if(n.length==0)return!1;for(const i of n)O(i.tiles.filter(r=>r.has(y.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 _t);if(n.length==0)return!1;const i=[];for(const r of n){const o=r.tiles[0].clone({removeAll:!0,add:y.HORIZONTAL});if(e.get(o.t,o.n)==1){const a=z(o)&&e.get(o.t,0)>0?o.clone({add:y.RED}):o;i.push(new ct([...r.tiles,a]))}}if(i.length==0)return!1;for(const r of i)O(r.tiles.filter(o=>o.has(y.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=An(t,e,b.DAI_KAN);let a=new wt([r,r,r,r]).clone({replace:{idx:o,tile:r.clone({add:y.HORIZONTAL})}});if(z(n)&&n.has(y.RED))a=a.clone({replace:{idx:o,tile:r.clone({add:[y.HORIZONTAL,y.RED]})}});else if(z(n)&&!n.has(y.RED)){O(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:y.RED})}})}return O(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 n=0;for(const i of Object.values(p)){if(i==p.BACK)continue;const r=i==p.Z?oe:ft;for(const o of r)e.get(i,o)>0&&n++}return n>=9}initialHands(){return this.wall.initialHands()}}class Lt extends cn{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 Lt(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 Os{constructor(t,e){A(this,"id");A(this,"river",new ys);A(this,"placeManager",new Te({}));A(this,"scoreManager",new ke({}));A(this,"hands",Z(new Lt("")));A(this,"counter",new Ki);A(this,"doraMarkers",[]);A(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.doraMarker);this.setHands(t),this.placeManager=new Te(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new ke(structuredClone(t.scores)),this.doraMarkers=[e],this.counter.dec(e);for(const i of Object.values(v))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(v))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"PON":case"CHI":case"DAI_KAN":{const i=B.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=ct.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=U.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(v))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.doraMarker);this.doraMarkers.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 hr extends Os{constructor(e){super("observer",e);A(this,"applied",{});this.counter.disable=!0,this.hands=Z(new Lt("_____________"))}setHands(e){this.hands[e.wind]=new Lt(e.hands[e.wind])}handleEvent(e){switch(super.handleEvent(e),e.type){case"DISTRIBUTE":let n=!0;for(const i of Object.values(v))n&&(n=this.hand(i).get(p.BACK,0)==0);if(!n)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(v))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(v))console.debug(`${this.placeManager.playerID(i)}(${Qn(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 be extends Os{constructor(e,n){super(e,n);A(this,"river",new ys);A(this,"doras",[]);this.eventHandler.on(i=>this.handleEvent(i))}get myWind(){return this.placeManager.wind(this.id)}setHands(e){for(const n of Object.values(v))this.hands[n]=new Lt(e.hands[n])}handleDiscard(e){const n=Object.values(v).filter(l=>l==this.myWind?!1:this.hand(l).reached),i=new We(this.hand(this.myWind)).calc();if(n.length>0&&i>=2)return te.selectTile(this.counter,n,e);const r=ae.calcCandidates(this.hand(this.myWind),e),a=Oe.calcPlayerCandidates(this.counter,r).sort((l,u)=>u.sum-l.sum),c=a.filter(l=>l.sum==a[0].sum);return Oe.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 n=this.handleDiscard(e.choices.DISCARD.map(w.from));e.choices.DISCARD=[n.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 ph{constructor(t){A(this,"index",0);A(this,"histories",[]);this.histories=JSON.parse(t)}next(){O(this.index<this.histories.length),this.index++}prev(){this.index--,O(this.index<0)}start(){je.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const mh=s=>{const[t,e]=_e(),[n,i]=_e(),[r,o]=_e(),[a,c]=_e(),h=["player-1","player-2","player-3","player-4"],l=s==null?void 0:s.playerInjection,u=(l==null?void 0:l.p1)??be,f=(l==null?void 0:l.p2)??be,m=(l==null?void 0:l.p3)??be,d=(l==null?void 0:l.p4)??be,g=new u(h[0],e),_=new f(h[1],i),S=new m(h[2],o),D=new d(h[3],c),R=[{handler:t,id:h[0]},{handler:n,id:h[1]},{handler:r,id:h[2]},{handler:a,id:h[3]}];return{c:new je(R,{debug:s==null?void 0:s.debug,shuffle:s==null?void 0:s.shuffle}),p1:g,p2:_,p3:S,p4:D}},Ct=(s,t)=>{let n=1;for(let i of t)i.equals(s)&&(n*=2);return n};class Oe{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){O(e.length>0);let i=0,r=0;for(let o=0;o<e.length;o++){const a=Oe.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*Ct(i,n);{const o=t.get(i);r+=o*Ct(i,n);const a=t.get(new w(i.t,i.n+1)),c=t.get(new w(i.t,i.n+2)),h=t.get(new w(i.t,i.n-1)),l=t.get(new w(i.t,i.n-2)),u=i.n-2>0?Math.min(h,l):0,f=i.n+2<=9?Math.min(a,c):0,m=i.n-1>=1&&i.n+1<=9?Math.min(a,h):0,d=Math.max(u,m),g=Math.max(m,f);return r+=o*Ct(i,n),r+=u*Ct(new w(i.t,i.n-2),n),r+=f*Ct(new w(i.t,i.n+2),n),r+=d*Ct(new w(i.t,i.n-1),n),r+=g*Ct(new w(i.t,i.n+1),n),i.n==0,r}}}class te{static selectTile(t,e,n){O(e.length>0&&n.length>0);let i=n[0],r=Number.POSITIVE_INFINITY;for(let o of n){const a=te.rank(t,e,o);a<r&&(i=o,r=a)}return i}static rank(t,e,n){let i=0;const r=n.isNum()?te.rankN:te.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=Lt;exports.BLOCK=b;exports.BaseActor=Os;exports.Block=B;exports.BlockAnKan=U;exports.BlockCalculator=Hi;exports.BlockChi=dt;exports.BlockDaiKan=wt;exports.BlockHand=ee;exports.BlockIsolated=Jn;exports.BlockOther=Vn;exports.BlockPair=Y;exports.BlockPon=_t;exports.BlockRun=St;exports.BlockShoKan=ct;exports.BlockThree=at;exports.Controller=je;exports.Counter=Ki;exports.DoubleCalculator=Wn;exports.Efficiency=ae;exports.FONT_FAMILY=Zn;exports.Hand=cn;exports.INPUT_SEPARATOR=At;exports.ImageHelper=ms;exports.MeasureText=mr;exports.N19=ft;exports.NZ=oe;exports.OPERATOR=y;exports.Observer=hr;exports.Parser=Q;exports.PlaceManager=Te;exports.Player=be;exports.PlayerEfficiency=Oe;exports.ROUND=j;exports.ROUND_MAP=Yn;exports.Replayer=ph;exports.RiskRank=te;exports.River=ys;exports.ScoreManager=ke;exports.ShantenCalculator=We;exports.TABLE_CONTEXT=Js;exports.TILE_CONTEXT=Et;exports.TYPE=p;exports.Tile=w;exports.WIND=v;exports.WIND_MAP=nn;exports.Wall=Wt;exports.callBlockIndex=An;exports.convertInput=Ri;exports.createControllerMachine=Gn;exports.createEventEmitter=zi;exports.createEventPipe=_e;exports.createHand=Vt;exports.createLocalGame=mh;exports.createTable=Di;exports.createWindMap=Z;exports.deserializeWinResult=we;exports.drawBlocks=$a;exports.drawTable=Fa;exports.forHand=rt;exports.incrementalIDGenerator=cr;exports.isNum5=z;exports.nextRound=ve;exports.nextWind=kt;exports.optimizeSVG=Wa;exports.parse=Ci;exports.parseTableInput=Mi;exports.prevRound=Ar;exports.prevWind=Qn;exports.prioritizeDiscardedEvents=Bi;exports.prioritizeDrawnEvents=Wi;exports.shuffle=gs;exports.sortCalledTiles=Vs;exports.tileSortFunc=Ie;
|
|
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 n=t.currentWind;t.currentWind=pt(n)},notify_distribution:({context:t,event:e})=>{const n=t.genEventID(),s=t.controller.initialHands();for(const i of Object.values(R)){const o=F("_____________");o[i]=s[i].toString();const a={id:n,type:"DISTRIBUTE",hands:o,wind:i,doraMarker:t.controller.wall.doraMarkers[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 s=t.currentWind,i=t.controller.hand(s).drawn,o=t.genEventID(),a={id:o,type:"CHOICE_AFTER_DRAWN",wind:s,drawerInfo:{wind:s,tile:i.toString()},choices:{TSUMO:ie(t.controller.doWin(s,i,{oneShot:t.oneShotMap[s],replacementWin:n==null?void 0:n.replacementWin})),REACH:fo(t.controller.doReach(s)),AN_KAN:re(t.controller.doAnKan(s)),SHO_KAN:re(t.controller.doShoKan(s)),DISCARD:t.controller.doDiscard(s).map(c=>c.toString()),DRAWN_GAME_BY_NINE_ORPHANS:t.controller.canDrawnGame(s)}};t.controller.emit(a),t.controller.pollReplies(o,[s])},notify_choice_after_discarded:({context:t,event:e})=>{const n=t.genEventID(),s=t.controller.river.lastTile,i=s.t.clone({add:A.HORIZONTAL});for(const o of Object.values(R)){const a={id:n,type:"CHOICE_AFTER_DISCARDED",wind:o,discarterInfo:{wind:s.w,tile:s.t.toString()},choices:{RON:ie(t.controller.doWin(o,i,{discardedBy:s.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:re(t.controller.doPon(o,s.w,i)),CHI:re(t.controller.doChi(o,s.w,i)),DAI_KAN:ho(t.controller.doDaiKan(o,s.w,i))}};a.choices.RON&&(t.missingMap[o]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(R))},notify_choice_after_called:({context:t,event:e},n)=>{const s=t.genEventID(),i=t.currentWind;let o=t.controller.doDiscard(i);const a=t.controller.hand(t.currentWind).called.at(-1);(a instanceof it||a instanceof lt)&&(o=t.controller.doDiscard(i,a));const c={id:s,type:"CHOICE_AFTER_CALLED",wind:i,choices:{DISCARD:o.map(l=>l.toString())}};t.controller.emit(c),t.controller.pollReplies(s,[i])},notify_choice_for_reach_acceptance:({context:t,event:e})=>{const n=t.genEventID(),s=t.controller.river.lastTile,i=s.t.clone({add:A.HORIZONTAL});for(const o of Object.values(R)){const a={id:n,type:"CHOICE_FOR_REACH_ACCEPTANCE",wind:o,reacherInfo:{wind:s.w,tile:i.toString()},choices:{RON:ie(t.controller.doWin(o,i,{discardedBy:s.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]}))}};t.controller.emit(a)}t.controller.pollReplies(n,Object.values(R))},notify_choice_for_chankan:({context:t,event:e})=>{H(e.type=="SHO_KAN"||e.type=="AN_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),s=e.block.tiles[0].clone({remove:A.HORIZONTAL});for(const i of Object.values(R)){const o=t.controller.doWin(i,e.block.tiles[0].clone({remove:A.HORIZONTAL}),{discardedBy:e.iam,quadWin:!0,oneShot:t.oneShotMap[i],missingRon:t.missingMap[e.iam]}),a={id:n,type:"CHOICE_FOR_CHAN_KAN",wind:i,callerInfo:{wind:e.iam,tile:s.toString()},choices:{RON:e.type=="SHO_KAN"?ie(o):!1}};a.choices.RON&&(t.missingMap[i]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(R))},notify_call:({context:t,event:e})=>{H(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(),s=e.iam;t.currentWind=s;for(const i of Object.values(R)){const o={id:n,type:e.type,iam:s,wind:i,block:e.block.serialize()};t.controller.emit(o)}t.controller.next()},notify_discard:({context:t,event:e})=>{H(e.type=="DISCARD",`unexpected event ${e.type}`);const n=t.genEventID(),s=t.currentWind,i=e.tile;for(const o of Object.values(R)){const a={id:n,type:"DISCARD",iam:s,wind:o,tile:i.toString()};t.controller.emit(a)}t.controller.next()},notify_draw:({context:t,event:e},n)=>{const s=t.genEventID(),i=n==null?void 0:n.action;let o;i=="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(R)){let l=new v(_.BACK,0,[A.TSUMO]);c==a&&(l=o);const u={id:s,type:"DRAW",subType:i,iam:a,wind:c,tile:l.toString()};t.controller.emit(u)}t.controller.next()},notify_ron:({context:t,event:e})=>{H(e.type=="RON");const n=t.genEventID(),s=e.iam;for(const i of Object.values(R)){const o={id:n,type:e.type,iam:s,wind:i,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:Qe(e.ret)};t.controller.emit(o)}},notify_tsumo:({context:t,event:e})=>{H(e.type=="TSUMO",`unexpected event ${e.type}`);const n=t.genEventID(),s=t.currentWind;for(const i of Object.values(R)){const o={id:n,type:e.type,iam:s,wind:i,lastTile:t.controller.hand(s).drawn.toString(),ret:Qe(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{H(e.type=="REACH",`unexpected event ${e.type}`);const n=t.genEventID(),s=e.iam,i=e.tile.clone({add:A.HORIZONTAL});t.oneShotMap[s]=!0;for(const o of Object.values(R)){const a={id:n,type:e.type,iam:s,wind:o,tile:i.toString()};t.controller.emit(a)}},notify_reach_accepted:({context:t,event:e})=>{H(e.type=="REACH_ACCEPT");const n=t.genEventID();for(const s of Object.values(R)){const i={id:n,type:"REACH_ACCEPTED",reacherInfo:{wind:e.reacherInfo.wind,tile:e.reacherInfo.tile.toString()},wind:s};t.controller.emit(i)}t.controller.next()},notify_new_dora_if_needed:({context:t,event:e})=>{const n=t.genEventID();if(e.type=="AN_KAN"){const s=t.controller.wall.openDoraMarker();for(const i of Object.values(R)){const o={id:n,type:"NEW_DORA",wind:i,doraMarker:s.toString()};t.controller.emit(o)}}e.type=="SHO_KAN"},disable_one_shot:({context:t,event:e})=>{for(const n of Object.values(R))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(),s=F("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){s[e.iam]=t.controller.hand(e.iam).toString();for(const i of Object.values(R)){const o={id:n,type:"END_GAME",subType:"NINE_TILES",wind:i,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:F(0),hands:s};t.controller.emit(o)}}else if(e.type=="RON"||e.type=="TSUMO"){const i=e.iam==R.E,o=t.controller.finalResult(e.ret,e.iam);for(const a of Object.values(R)){s[e.iam]=t.controller.hand(e.iam).toString();const c={id:n,type:"END_GAME",subType:"WIN_GAME",wind:a,shouldContinue:i,sticks:{reach:0,dead:0},scores:t.controller.scoreManager.summary,deltas:o.deltas,hands:s};t.controller.emit(c)}}else if(!t.controller.wall.canKan||t.controller.river.cannotContinue()){const i=t.controller.wall.canKan?"FOUR_WIND":"FOUR_KAN";for(const o of Object.values(R)){const a={id:n,type:"END_GAME",subType:i,wind:o,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:F(0),hands:F("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const i=[];for(const l of Object.values(R)){const u=t.controller.hand(l);new Yt(u).calc()==0&&(i.push(l),s[l]=u.toString())}const o=i.length==0||i.length==4,a=F(0);for(const l of Object.values(R))i.includes(l)?a[l]+=o?0:3e3/i.length:a[l]-=o?0:3e3/(4-i.length);const c=i.length==4||a[R.E]>0;for(const l of Object.values(R)){const u={id:n,type:"END_GAME",subType:"DRAWN_GAME",wind:l,shouldContinue:c,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:a,hands:s};t.controller.emit(u)}}}}},actors:{},guards:{canChi:({context:t,event:e},n)=>e.type=="CHI"?!!t.controller.doChi(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canChi receive ${e.type}`),!1),canPon:({context:t,event:e},n)=>e.type=="PON"?!!t.controller.doPon(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canPon receive ${e.type}`),!1),canWin:({context:t,event:e},n)=>e.type=="TSUMO"||e.type=="RON"?!0:(console.error(`guards.canWin receive ${e.type}`),!1),canReach:({context:t,event:e},n)=>e.type=="REACH"?!!t.controller.doReach(e.iam):(console.error(`guards.canReach receive ${e.type}`),!1),cannotContinue:({context:t,event:e},n)=>!t.controller.wall.canDraw||!t.controller.wall.canKan||t.controller.river.cannotContinue()},delays:{}});function Fs(r=0){let t=r;return()=>(t++).toString()}class Nt{constructor(t){C(this,"walls",{replacement:[],dead:[],doraMarkers:[],blindDoraMarkers:[],drawable:[]});C(this,"backup");C(this,"openedDoraCount",1);this.init(t),this.backup=Nt.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(),v.from(t)}draw(){if(!this.walls.drawable)throw new Error("cannot draw any more");return v.from(this.walls.drawable.pop())}openDoraMarker(){if(this.openedDoraCount>=4)throw new Error("exceeded maximum open dora");return this.openedDoraCount++,v.from(this.walls.doraMarkers[this.openedDoraCount-1])}get doraMarkers(){return this.walls.doraMarkers.slice(0,this.openedDoraCount).map(v.from)}get blindDoraMarkers(){return this.walls.blindDoraMarkers.slice(0,this.openedDoraCount).map(v.from)}get canKan(){return this.walls.replacement.length>0}get canDraw(){return this.walls.drawable.length>0}initialHands(){const t=F("");for(let e=0;e<3;e++)for(const n of Object.values(R))for(let s=0;s<4;s++)t[n]+=this.draw().toString();for(const e of Object.values(R))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=Nt.clone(t);return}else{for(let e of Object.values(_)){if(e==_.BACK)continue;const n=e==_.Z?[1,2,3,4,5,6,7]:[1,2,3,4,5,6,7,8,9];for(let s=0;s<4;s++)for(let i of n){let o=new v(e,i);e!=_.Z&&s==3&&i==5&&(o=o.clone({add:A.RED})),this.walls.drawable.push(o.toString())}}pn(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.blindDoraMarkers.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.doraMarkers.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(),doraMarkers:t.doraMarkers.concat(),blindDoraMarkers:t.blindDoraMarkers.concat(),replacement:t.replacement.concat()}}}class te{constructor(t,e){C(this,"wall",new Nt);C(this,"playerIDs");C(this,"actor",Dt(tn(this),{}));C(this,"observer");C(this,"handlers",{});C(this,"mailBox",{});C(this,"histories",[]);C(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 n=Ns();this.observer=new Us(n),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const s=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new qt(s);const i=(e==null?void 0:e.shuffle)==!1?this.playerIDs:pn([...this.playerIDs]);this.observer.placeManager=new Xt({[i[0]]:R.E,[i[1]]:R.S,[i[2]]:R.W,[i[3]]:R.N})}boardParams(t){let n=this.hand(t).reached?1:void 0;if(n){const s=this.river.discards(t);n=s.length==0||s.length==1&&s[0].t.has(A.HORIZONTAL)?2:1}return{doraMarkers:this.observer.doraMarkers,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 s=n[0];if(s.type=="CHOICE_AFTER_DISCARDED"){const i=bs(n);if(i.events.length==0){this.actor.send({type:""});return}const o=i.events[0];switch(i.type){case"RON":H(o.choices.RON,"ron choice is none"),this.actor.send({type:i.type,iam:o.wind,ret:Ft(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:v.from(o.discarterInfo.tile)}});break;case"DAI_KAN":H(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:i.type,iam:o.wind,block:ct.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[i.type];H(a,`${i.type} choice is none`),H(i.events.length==1,`found more than one selected: ${JSON.stringify(i,null,2)}`);const c=K.deserialize(a[0]);this.actor.send({type:i.type,iam:o.wind,block:c})}}else if(s.type=="CHOICE_AFTER_DRAWN"){const i=_s(n);H(i.events.length==1,`found more than one selected: ${JSON.stringify(i,null,2)}`);const o=i.events[0],a=o.wind;switch(i.type){case"TSUMO":H(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:i.type,ret:Ft(o.choices.TSUMO),lastTile:v.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[i.type];H(c,`${i.type} candidates is none`),this.actor.send({type:"REACH",tile:v.from(c[0].tile),iam:a});break;case"DISCARD":const l=o.choices[i.type];H(l,`${i.type} choice is none`),this.actor.send({type:i.type,tile:v.from(l[0]).clone({remove:A.TSUMO}),iam:a});break;case"AN_KAN":{const u=o.choices[i.type];H(u,`${i.type} choice is none`),this.actor.send({type:i.type,block:z.from(u[0].tiles),iam:a});break}case"SHO_KAN":{const u=o.choices[i.type];H(u,`${i.type} choice is none`),this.actor.send({type:i.type,block:tt.from(u[0].tiles),iam:a});break}case"DRAWN_GAME_BY_NINE_ORPHANS":this.actor.send({type:"DRAWN_GAME_BY_NINE_ORPHANS",iam:a});break}}else if(s.type=="CHOICE_AFTER_CALLED"){H(s.choices.DISCARD,`discard candidate tile is none: ${JSON.stringify(s,null,2)} ${this.hand(s.wind).toString()}`);const i=s.wind,o=v.from(s.choices.DISCARD[0]);this.actor.send({type:"DISCARD",tile:o,iam:i})}else if(s.type=="CHOICE_FOR_REACH_ACCEPTANCE"){const i=n.filter(a=>(H(a.type=="CHOICE_FOR_REACH_ACCEPTANCE"),a.choices.RON!==!1));if(i.length==0){this.actor.send({type:"REACH_ACCEPT",reacherInfo:{tile:v.from(s.reacherInfo.tile),wind:s.reacherInfo.wind}});return}const o=i[0];this.actor.send({type:"RON",iam:o.wind,ret:Ft(o.choices.RON),targetInfo:{wind:o.reacherInfo.wind,tile:v.from(o.reacherInfo.tile)}});return}else if(s.type=="CHOICE_FOR_CHAN_KAN"){const i=n.filter(a=>a.choices.RON!==!1);if(i.length==0){this.actor.send({type:""});return}const o=i[0];H(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:Ft(o.choices.RON),quadWin:!0,targetInfo:{wind:o.callerInfo.wind,tile:v.from(o.callerInfo.tile)}});return}else console.warn(`controller found unexpected event: ${s.type}`)}export(){return this.histories.concat()}static load(t){const e=t.choiceEvents,n=Object.keys(t.players),s={emit:a=>{},on:a=>{}},i=n.map(a=>({id:a,handler:s})),o=new te(i);return o.playerIDs=n,o.mailBox=e,o.observer.placeManager=new Xt(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new qt(t.scores),o.wall=new Nt(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 Nt,this.observer.applied={},this.mailBox={},this.actor=Dt(tn(this)),!this.placeManager.is(L.W1););}finalResult(t,e){const n=this.hand(e),s=n.reached?this.wall.blindDoraMarkers:void 0,i=new Ue(n,{...t.boardContext,sticks:this.placeManager.sticks,blindDoraMarkers:s}).calc(t.hand);return H(i),i}doWin(t,e,n){if(e==null)return!1;let s=this.hand(t);const i=this.boardParams(t);if(s.drawn==null){if(n==null)throw new Error("should ron but params == null");if(n.discardedBy==t||n.missingRon)return!1;s=s.clone(),i.ronWind=n.discardedBy,i.finalDiscardWin=!this.wall.canDraw,i.quadWin=n.quadWin,s.inc([e])}else i.finalWallWin=!this.wall.canDraw,i.replacementWin=n==null?void 0:n.replacementWin;i.oneShotWin=n==null?void 0:n.oneShot;const o=new ms(s),a=new Ue(s,i),c=o.calc(e),l=a.calc(...c);if(!l||l.points.length==0)return!1;if(s.draw==null){const u=Wt.candidateTiles(this.hand(t)).candidates;if(this.river.discards(t).some(h=>u.some(d=>d.equals(h.t))))return!1}return l}doPon(t,e,n){if(n==null||t==e)return!1;const s=this.hand(t);if(s.reached||s.hands.length<3||s.get(n.t,n.n)<2)return!1;const i=n.clone({removeAll:!0}),o=Ke(t,e,S.PON),a=[],c=new lt([i,i,i]).clone({replace:{idx:o,tile:n.clone({add:A.HORIZONTAL})}});let l=c;j(n)&&n.has(A.RED)&&(l=c.clone({replace:{idx:o,tile:i.clone({add:[A.RED,A.HORIZONTAL]})}}));const u=o%2+1;if(j(n)&&s.get(n.t,0)>0&&(l=c.clone({replace:{idx:u,tile:i.clone({add:A.RED})}})),a.push(l),j(i)&&s.get(i.t,5)==3){const h=c.clone({replace:{idx:u,tile:i}});a.push(h)}return a}doChi(t,e,n){if(n==null||!n.isNum()||pt(e)!=t)return!1;const s=this.hand(t);if(s.reached||s.hands.length<3)return!1;const i=n.clone({remove:A.TSUMO,add:[A.HORIZONTAL]}),o=[];i.n-2>=1&&s.get(n.t,i.n-2)>0&&s.get(n.t,i.n-1)>0&&o.push(new it([i,new v(n.t,i.n-1),new v(n.t,i.n-2)])),i.n+2<=9&&s.get(n.t,i.n+1)>0&&s.get(n.t,i.n+2)>0&&o.push(new it([i,new v(n.t,i.n+1),new v(n.t,i.n+2)])),i.n-1>=1&&i.n+1<=9&&s.get(n.t,i.n-1)>0&&s.get(n.t,i.n+1)>0&&o.push(new it([i,new v(n.t,i.n-1),new v(n.t,i.n+1)]));for(let d=0;d<o.length;d++){const p=o[d],g=this.cannotDiscardTile(p),y=[];for(const w of g){const T=s.get(w.t,w.n);for(let $=0;$<T;$++)y.push(w.clone({remove:A.RED}))}const O=s.dec([...y,p.tiles[1],p.tiles[2]]),f=s.hands.length==0;s.inc(O),f&&o.splice(d,1)}if(o.length==0)return!1;const h=s.get(n.t,0)>0?this.redPattern(o):[];return h.length>0&&s.get(n.t,5)==1?h:[...o,...h]}redPattern(t){return t.length==0?[]:t.filter(n=>j(n.tiles[1])||j(n.tiles[2])).map(n=>{if(j(n.tiles[1])){const s=n.tiles[1].clone({add:A.RED});return n.clone({replace:{idx:1,tile:s}})}else if(j(n.tiles[2])){const s=n.tiles[2].clone({add:A.RED});return n.clone({replace:{idx:2,tile:s}})}}).filter(n=>n!=null)}doReach(t){const e=this.hand(t);return e.reached||!e.menzen||new Yt(e).calc()>0?!1:Wt.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 lt)return n.filter(o=>!o.equals(e.tiles[0]));const s=this.cannotDiscardTile(e),i=n.filter(o=>!s.some(a=>o.equals(a)));return H(i.length>0,`no tiles to discard. hand: ${this.hand(t)}, suji: ${s}, block-chi: ${e}`),i}cannotDiscardTile(t){const e=t.tiles[0],n=t.tiles[1].n;return n!=1&&e.n-2==n?[new v(e.t,e.n-3),e]:n!=8&&e.n+1==n?[new v(e.t,e.n+3),e]:[e]}doAnKan(t){const e=this.hand(t),n=[];if(e.reached)return!1;for(const[s,i]of J())if(e.get(s,i)==4){const o=new v(s,i),a=[o,o,o,o];j(o)&&(a[1]=o.clone({add:A.RED})),n.push(new z(a))}if(n.length==0)return!1;for(const s of n)H(s.tiles.filter(i=>i.has(A.HORIZONTAL)).length==0,`h op ${s.toString()}`);return n}doShoKan(t){const e=this.hand(t);if(e.reached)return!1;const n=e.called.filter(i=>i instanceof lt);if(n.length==0)return!1;const s=[];for(const i of n){const o=i.tiles[0].clone({removeAll:!0,add:A.HORIZONTAL});if(e.get(o.t,o.n)==1){const a=j(o)&&e.get(o.t,0)>0?o.clone({add:A.RED}):o;s.push(new tt([...i.tiles,a]))}}if(s.length==0)return!1;for(const i of s)H(i.tiles.filter(o=>o.has(A.HORIZONTAL)).length==2,`h op ${i.toString()}`);return s}doDaiKan(t,e,n){const s=this.hand(t);if(s.reached||t==e)return!1;const i=n.clone({removeAll:!0});if(s.get(i.t,i.n)!=3)return!1;const o=Ke(t,e,S.DAI_KAN);let a=new ct([i,i,i,i]).clone({replace:{idx:o,tile:i.clone({add:A.HORIZONTAL})}});if(j(n)&&n.has(A.RED))a=a.clone({replace:{idx:o,tile:i.clone({add:[A.HORIZONTAL,A.RED]})}});else if(j(n)&&!n.has(A.RED)){H(s.get(n.t,0)>0,`hand does not have red tile: ${s.toString()}`);const c=o%3+1;a=a.clone({replace:{idx:c,tile:i.clone({add:A.RED})}})}return H(a.tiles.filter(c=>c.has(A.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 s of Object.values(_)){if(s==_.BACK)continue;const i=s==_.Z?Bt:rt;for(const o of i)e.get(s,o)>0&&n++}return n>=9}initialHands(){return this.wall.initialHands()}}class Tt extends ye{isBackHand(){for(const t of Object.values(_))if(t!=_.BACK&&this.sum(t)>0)return!1;return this.sum(_.BACK)>0}clone(){const t=new Tt(this.toString());return t.data.reached=this.data.reached,t}dec(t){return this.isBackHand()?(super.dec(t.map(()=>new v(_.BACK,0))),[...t]):super.dec(t)}}class Tn{constructor(t,e){C(this,"id");C(this,"river",new gn);C(this,"placeManager",new Xt({}));C(this,"scoreManager",new qt({}));C(this,"hands",F(new Tt("")));C(this,"counter",new vs);C(this,"doraMarkers",[]);C(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=v.from(t.doraMarker);this.setHands(t),this.placeManager=new Xt(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new qt(structuredClone(t.scores)),this.doraMarkers=[e],this.counter.dec(e);for(const s of Object.values(R))s==t.wind&&this.counter.dec(...this.hand(s).hands);break;case"DRAW":{const s=v.from(t.tile);this.hands[t.iam].draw(s),this.counter.dec(s);break}case"DISCARD":{const s=v.from(t.tile);if(this.river.discard(s,t.iam),this.hands[t.iam].discard(s),t.iam!=t.wind){this.counter.dec(s),this.counter.addTileToSafeMap(s,t.iam);for(const i of Object.values(R))this.hand(i).reached&&this.counter.addTileToSafeMap(s,i)}break}case"PON":case"CHI":case"DAI_KAN":{const s=K.deserialize(t.block);this.hands[t.iam].call(s),this.river.markCalled(),t.iam!=t.wind&&this.counter.dec(...s.tiles.filter(i=>!i.has(A.HORIZONTAL)));break}case"SHO_KAN":{const s=tt.from(t.block.tiles);this.hands[t.iam].kan(s),t.iam!=t.wind&&this.counter.dec(s.tiles.filter(i=>i.has(A.HORIZONTAL))[0]);break}case"AN_KAN":{const s=z.from(t.block.tiles);this.hands[t.iam].kan(s),t.iam!=t.wind&&this.counter.dec(...s.tiles.filter(i=>!i.has(A.HORIZONTAL)));break}case"REACH":{this.hands[t.iam].reach();const s=v.from(t.tile);if(this.river.discard(s,t.iam),this.hands[t.iam].discard(s),t.iam!=t.wind){this.counter.dec(s),this.counter.addTileToSafeMap(s,t.iam);for(const i of Object.values(R))this.hand(i).reached&&this.counter.addTileToSafeMap(s,i)}break}case"REACH_ACCEPTED":const n=this.placeManager.playerID(t.reacherInfo.wind);this.scoreManager.reach(n),this.placeManager.incrementReachStick();break;case"NEW_DORA":{const s=v.from(t.doraMarker);this.doraMarkers.push(s),this.counter.dec(s);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 s=this.placeManager.playerMap;this.scoreManager.update(t.deltas,s),this.placeManager.incrementDeadStick(),t.shouldContinue||this.placeManager.nextRound();break}case"WIN_GAME":{const s=this.placeManager.playerMap;this.scoreManager.update(t.deltas,s),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 Us extends Tn{constructor(e){super("observer",e);C(this,"applied",{});this.counter.disable=!0,this.hands=F(new Tt("_____________"))}setHands(e){this.hands[e.wind]=new Tt(e.hands[e.wind])}handleEvent(e){switch(super.handleEvent(e),e.type){case"DISTRIBUTE":let n=!0;for(const s of Object.values(R))n&&(n=this.hand(s).get(_.BACK,0)==0);if(!n)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 s of Object.values(R))console.debug(`${this.placeManager.playerID(s)}(${s})`,`init hand: ${this.hand(s).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 s of Object.values(R))console.debug(`${this.placeManager.playerID(s)}(${an(s)})`,`end hand: ${this.hand(s).toString()}`);console.debug("END_GAME",e.subType,"scores",JSON.stringify(this.scoreManager.summary,null,2),`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`)}}}class Gt extends Tn{constructor(e,n){super(e,n);C(this,"river",new gn);C(this,"doras",[]);this.eventHandler.on(s=>this.handleEvent(s))}get myWind(){return this.placeManager.wind(this.id)}setHands(e){for(const n of Object.values(R))this.hands[n]=new Tt(e.hands[n])}handleDiscard(e){const n=Object.values(R).filter(u=>u==this.myWind?!1:this.hand(u).reached),s=new Yt(this.hand(this.myWind)).calc();if(n.length>0&&s>=2)return xt.selectTile(this.counter,n,e);const i=Wt.calcCandidates(this.hand(this.myWind),e),a=Vt.calcPlayerCandidates(this.counter,i).sort((u,h)=>h.sum-u.sum),c=a.filter(u=>u.sum==a[0].sum);return Vt.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 n=this.handleDiscard(e.choices.DISCARD.map(v.from));e.choices.DISCARD=[n.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 po{constructor(t){C(this,"index",0);C(this,"histories",[]);this.histories=JSON.parse(t)}next(){H(this.index<this.histories.length),this.index++}prev(){this.index--,H(this.index<0)}start(){te.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const go=r=>{const[t,e]=Ut(),[n,s]=Ut(),[i,o]=Ut(),[a,c]=Ut(),l=["player-1","player-2","player-3","player-4"],u=r==null?void 0:r.playerInjection,h=(u==null?void 0:u.p1)??Gt,d=(u==null?void 0:u.p2)??Gt,p=(u==null?void 0:u.p3)??Gt,g=(u==null?void 0:u.p4)??Gt,y=new h(l[0],e),O=new d(l[1],s),f=new p(l[2],o),w=new g(l[3],c),T=[{handler:t,id:l[0]},{handler:n,id:l[1]},{handler:i,id:l[2]},{handler:a,id:l[3]}];return{c:new te(T,{debug:r==null?void 0:r.debug,shuffle:r==null?void 0:r.shuffle}),p1:y,p2:O,p3:f,p4:w}},bt=(r,t)=>{let n=1;for(let s of t)s.equals(r)&&(n*=2);return n};class Vt{static calcPlayerCandidates(t,e){let n=[];for(let s of e){let i=0,o=[];for(let a of s.candidates)o.push({tile:a.clone(),n:t.get(a)}),i+=t.get(a);n.push({sum:i,tile:s.tile,candidates:o,shanten:s.shanten})}return n}static selectMinPriority(t,e,n){H(e.length>0);let s=0,i=0;for(let o=0;o<e.length;o++){const a=Vt.calcPriority(t,e[o],n);a<s&&(s=a,i=o)}return e[i]}static calcPriority(t,e,n){const s=e.tile;let i=0;if(s.t==_.Z)return i=t.get(s),(s.n==5||s.n==6||s.n==7)&&(i*=2),i*bt(s,n);{const o=t.get(s);i+=o*bt(s,n);const a=t.get(new v(s.t,s.n+1)),c=t.get(new v(s.t,s.n+2)),l=t.get(new v(s.t,s.n-1)),u=t.get(new v(s.t,s.n-2)),h=s.n-2>0?Math.min(l,u):0,d=s.n+2<=9?Math.min(a,c):0,p=s.n-1>=1&&s.n+1<=9?Math.min(a,l):0,g=Math.max(h,p),y=Math.max(p,d);return i+=o*bt(s,n),i+=h*bt(new v(s.t,s.n-2),n),i+=d*bt(new v(s.t,s.n+2),n),i+=g*bt(new v(s.t,s.n-1),n),i+=y*bt(new v(s.t,s.n+1),n),s.n==0,i}}}class xt{static selectTile(t,e,n){H(e.length>0&&n.length>0);let s=n[0],i=Number.POSITIVE_INFINITY;for(let o of n){const a=xt.rank(t,e,o);a<i&&(s=o,i=a)}return s}static rank(t,e,n){let s=0;const i=n.isNum()?xt.rankN:xt.rankZ;for(let o of e){const a=i(t,o,n);s<a&&(s=a)}return s}static rankZ(t,e,n){if(n.t!=_.Z)throw new Error(`expected TYPE.Z but ${n.toString()}`);if(t.isSafeTile(n.t,n.n,e))return 0;const s=t.get(n);return Math.min(s,3)}static rankN(t,e,n){if(!n.isNum())throw new Error(`expected TYPE.NUMBER but ${n.toString()}`);const s=n.n,i=n.t;if(t.isSafeTile(i,s,e))return 0;if(s==1)return t.isSafeTile(i,4,e)?3:6;if(s==9)return t.isSafeTile(i,6,e)?3:6;if(s==2||s==8)return t.isSafeTile(i,5,e)?4:8;if(s==3)return t.isSafeTile(i,6,e)?5:8;if(s==7)return t.isSafeTile(i,4,e)?5:8;const o=t.isSafeTile(i,s-3,e),a=t.isSafeTile(i,s+3,e);return o&&a?4:o||a?8:12}}exports.ActorHand=Tt;exports.BLOCK=S;exports.BaseActor=Tn;exports.Block=K;exports.BlockAnKan=z;exports.BlockCalculator=ms;exports.BlockChi=it;exports.BlockDaiKan=ct;exports.BlockHand=Mt;exports.BlockIsolated=rn;exports.BlockOther=on;exports.BlockPair=G;exports.BlockPon=lt;exports.BlockRun=ht;exports.BlockShoKan=tt;exports.BlockThree=Q;exports.Controller=te;exports.Counter=vs;exports.DoubleCalculator=Ue;exports.Efficiency=Wt;exports.FONT_FAMILY=en;exports.G=W;exports.Hand=ye;exports.INPUT_SEPARATOR=ut;exports.Image=un;exports.ImageHelper=fn;exports.Mark=yt;exports.MeasureText=qs;exports.MyG=Nr;exports.MyImage=vr;exports.MyRect=Tr;exports.MySVG=Er;exports.MyText=Ir;exports.MyUse=Sr;exports.N19=rt;exports.NZ=Bt;exports.OP=A;exports.Observer=Us;exports.Parser=Z;exports.PlaceManager=Xt;exports.Player=Gt;exports.PlayerEfficiency=Vt;exports.ROUND=L;exports.ROUND_MAP=nn;exports.Rect=hn;exports.Replayer=po;exports.RiskRank=xt;exports.River=gn;exports.STICK_CONTEXT=De;exports.SVG=us;exports.ScoreManager=qt;exports.ShantenCalculator=Yt;exports.Svg=ls;exports.Symbol=dn;exports.TABLE_CONTEXT=rs;exports.TILE_CONTEXT=ft;exports.TYPE=_;exports.Text=Et;exports.Tile=v;exports.Use=ge;exports.WIND=R;exports.WIND_MAP=fe;exports.Wall=Nt;exports.callBlockIndex=Ke;exports.convertInput=ys;exports.createControllerMachine=tn;exports.createEventEmitter=Ns;exports.createEventPipe=Ut;exports.createHand=Ct;exports.createLocalGame=go;exports.createTable=fs;exports.createWindMap=F;exports.deserializeWinResult=Ft;exports.drawBlocks=$r;exports.drawTable=zr;exports.forHand=J;exports.incrementalIDGenerator=Fs;exports.isNum5=j;exports.nextRound=Zt;exports.nextWind=pt;exports.optimizeSVG=Hr;exports.parse=ps;exports.parseTableInput=gs;exports.prevRound=er;exports.prevWind=an;exports.prioritizeDiscardedEvents=bs;exports.prioritizeDrawnEvents=_s;exports.shuffle=pn;exports.sortCalledTiles=is;exports.tileSortFunc=Jt;
|