diff --git a/assets/index-BlR-1BrR.js b/assets/index-BlR-1BrR.js new file mode 100644 index 00000000..4f917c1a --- /dev/null +++ b/assets/index-BlR-1BrR.js @@ -0,0 +1,4895 @@ +var iB=Object.defineProperty;var sB=(t,e,n)=>e in t?iB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var oB=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var vt=(t,e,n)=>sB(t,typeof e!="symbol"?e+"":e,n);var Qde=oB((ks,Is)=>{(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var bo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Pl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function aB(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var AI={exports:{}},Tv={},MI={exports:{}},Jt={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var qp=Symbol.for("react.element"),lB=Symbol.for("react.portal"),cB=Symbol.for("react.fragment"),uB=Symbol.for("react.strict_mode"),hB=Symbol.for("react.profiler"),fB=Symbol.for("react.provider"),dB=Symbol.for("react.context"),pB=Symbol.for("react.forward_ref"),mB=Symbol.for("react.suspense"),gB=Symbol.for("react.memo"),_B=Symbol.for("react.lazy"),bC=Symbol.iterator;function vB(t){return t===null||typeof t!="object"?null:(t=bC&&t[bC]||t["@@iterator"],typeof t=="function"?t:null)}var CI={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},RI=Object.assign,NI={};function nd(t,e,n){this.props=t,this.context=e,this.refs=NI,this.updater=n||CI}nd.prototype.isReactComponent={};nd.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};nd.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function kI(){}kI.prototype=nd.prototype;function Zw(t,e,n){this.props=t,this.context=e,this.refs=NI,this.updater=n||CI}var Jw=Zw.prototype=new kI;Jw.constructor=Zw;RI(Jw,nd.prototype);Jw.isPureReactComponent=!0;var AC=Array.isArray,II=Object.prototype.hasOwnProperty,Qw={current:null},OI={key:!0,ref:!0,__self:!0,__source:!0};function LI(t,e,n){var r,i={},s=null,o=null;if(e!=null)for(r in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)II.call(e,r)&&!OI.hasOwnProperty(r)&&(i[r]=e[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1>8&255]+_i[t>>16&255]+_i[t>>24&255]+"-"+_i[e&255]+_i[e>>8&255]+"-"+_i[e>>16&15|64]+_i[e>>24&255]+"-"+_i[n&63|128]+_i[n>>8&255]+"-"+_i[n>>16&255]+_i[n>>24&255]+_i[r&255]+_i[r>>8&255]+_i[r>>16&255]+_i[r>>24&255]).toLowerCase()}function Pi(t,e,n){return Math.max(e,Math.min(n,t))}function aT(t,e){return(t%e+e)%e}function p5(t,e,n,r,i){return r+(t-e)*(i-r)/(n-e)}function m5(t,e,n){return t!==e?(n-t)/(e-t):0}function fp(t,e,n){return(1-n)*t+n*e}function g5(t,e,n,r){return fp(t,e,1-Math.exp(-n*r))}function _5(t,e=1){return e-Math.abs(aT(t,e*2)-e)}function v5(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))}function y5(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(t*6-15)+10))}function x5(t,e){return t+Math.floor(Math.random()*(e-t+1))}function S5(t,e){return t+Math.random()*(e-t)}function E5(t){return t*(.5-Math.random())}function w5(t){t!==void 0&&(PC=t);let e=PC+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function T5(t){return t*hp}function b5(t){return t*Sp}function A5(t){return(t&t-1)===0&&t!==0}function M5(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function C5(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function R5(t,e,n,r,i){const s=Math.cos,o=Math.sin,a=s(n/2),l=o(n/2),c=s((e+r)/2),u=o((e+r)/2),h=s((e-r)/2),p=o((e-r)/2),m=s((r-e)/2),g=o((r-e)/2);switch(i){case"XYX":t.set(a*u,l*h,l*p,a*c);break;case"YZY":t.set(l*p,a*u,l*h,a*c);break;case"ZXZ":t.set(l*h,l*p,a*u,a*c);break;case"XZX":t.set(a*u,l*g,l*m,a*c);break;case"YXY":t.set(l*m,a*u,l*g,a*c);break;case"ZYZ":t.set(l*g,l*m,a*u,a*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Jh(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Ni(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(t*4294967295);case Uint16Array:return Math.round(t*65535);case Uint8Array:return Math.round(t*255);case Int32Array:return Math.round(t*2147483647);case Int16Array:return Math.round(t*32767);case Int8Array:return Math.round(t*127);default:throw new Error("Invalid component type.")}}const N5={DEG2RAD:hp,RAD2DEG:Sp,generateUUID:id,clamp:Pi,euclideanModulo:aT,mapLinear:p5,inverseLerp:m5,lerp:fp,damp:g5,pingpong:_5,smoothstep:v5,smootherstep:y5,randInt:x5,randFloat:S5,randFloatSpread:E5,seededRandom:w5,degToRad:T5,radToDeg:b5,isPowerOfTwo:A5,ceilPowerOfTwo:M5,floorPowerOfTwo:C5,setQuaternionFromProperEuler:R5,normalize:Ni,denormalize:Jh};class St{constructor(e=0,n=0){St.prototype.isVector2=!0,this.x=e,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,n){return this.x=e,this.y=n,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const n=this.x,r=this.y,i=e.elements;return this.x=i[0]*n+i[3]*r+i[6],this.y=i[1]*n+i[4]*r+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(Pi(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y;return n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this}rotateAround(e,n){const r=Math.cos(n),i=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*i+e.x,this.y=s*i+o*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Dt{constructor(e,n,r,i,s,o,a,l,c){Dt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,a,l,c)}set(e,n,r,i,s,o,a,l,c){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=n,u[4]=s,u[5]=l,u[6]=r,u[7]=o,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],this}extractBasis(e,n,r){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const n=e.elements;return this.set(n[0],n[4],n[8],n[1],n[5],n[9],n[2],n[6],n[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],a=r[3],l=r[6],c=r[1],u=r[4],h=r[7],p=r[2],m=r[5],g=r[8],v=i[0],y=i[3],_=i[6],S=i[1],E=i[4],T=i[7],N=i[2],R=i[5],C=i[8];return s[0]=o*v+a*S+l*N,s[3]=o*y+a*E+l*R,s[6]=o*_+a*T+l*C,s[1]=c*v+u*S+h*N,s[4]=c*y+u*E+h*R,s[7]=c*_+u*T+h*C,s[2]=p*v+m*S+g*N,s[5]=p*y+m*E+g*R,s[8]=p*_+m*T+g*C,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[3]*=e,n[6]*=e,n[1]*=e,n[4]*=e,n[7]*=e,n[2]*=e,n[5]*=e,n[8]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8];return n*o*u-n*a*c-r*s*u+r*a*l+i*s*c-i*o*l}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8],h=u*o-a*c,p=a*l-u*s,m=c*s-o*l,g=n*h+r*p+i*m;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=h*v,e[1]=(i*c-u*r)*v,e[2]=(a*r-i*o)*v,e[3]=p*v,e[4]=(u*n-i*l)*v,e[5]=(i*s-a*n)*v,e[6]=m*v,e[7]=(r*l-c*n)*v,e[8]=(o*n-r*s)*v,this}transpose(){let e;const n=this.elements;return e=n[1],n[1]=n[3],n[3]=e,e=n[2],n[2]=n[6],n[6]=e,e=n[5],n[5]=n[7],n[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const n=this.elements;return e[0]=n[0],e[1]=n[3],e[2]=n[6],e[3]=n[1],e[4]=n[4],e[5]=n[7],e[6]=n[2],e[7]=n[5],e[8]=n[8],this}setUvTransform(e,n,r,i,s,o,a){const l=Math.cos(s),c=Math.sin(s);return this.set(r*l,r*c,-r*(l*o+c*a)+o+e,-i*c,i*l,-i*(-c*o+l*a)+a+n,0,0,1),this}scale(e,n){return this.premultiply(sS.makeScale(e,n)),this}rotate(e){return this.premultiply(sS.makeRotation(-e)),this}translate(e,n){return this.premultiply(sS.makeTranslation(e,n)),this}makeTranslation(e,n){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,n,0,0,1),this}makeRotation(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,r,n,0,0,0,1),this}makeScale(e,n){return this.set(e,0,0,0,n,0,0,0,1),this}equals(e){const n=this.elements,r=e.elements;for(let i=0;i<9;i++)if(n[i]!==r[i])return!1;return!0}fromArray(e,n=0){for(let r=0;r<9;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const sS=new Dt;function JI(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function Ep(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function k5(){const t=Ep("canvas");return t.style.display="block",t}const DC={};function Zd(t){t in DC||(DC[t]=!0,console.warn(t))}function I5(t,e,n){return new Promise(function(r,i){function s(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:i();break;case t.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:r()}}setTimeout(s,n)})}function O5(t){const e=t.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function L5(t){const e=t.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}const fn={enabled:!0,workingColorSpace:Hc,spaces:{},convert:function(t,e,n){return this.enabled===!1||e===n||!e||!n||(this.spaces[e].transfer===bn&&(t.r=vl(t.r),t.g=vl(t.g),t.b=vl(t.b)),this.spaces[e].primaries!==this.spaces[n].primaries&&(t.applyMatrix3(this.spaces[e].toXYZ),t.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===bn&&(t.r=vf(t.r),t.g=vf(t.g),t.b=vf(t.b))),t},fromWorkingColorSpace:function(t,e){return this.convert(t,this.workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this.workingColorSpace)},getPrimaries:function(t){return this.spaces[t].primaries},getTransfer:function(t){return t===da?Cv:this.spaces[t].transfer},getLuminanceCoefficients:function(t,e=this.workingColorSpace){return t.fromArray(this.spaces[e].luminanceCoefficients)},define:function(t){Object.assign(this.spaces,t)},_getMatrix:function(t,e,n){return t.copy(this.spaces[e].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(t){return this.spaces[t].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(t=this.workingColorSpace){return this.spaces[t].workingColorSpaceConfig.unpackColorSpace}};function vl(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function vf(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}const UC=[.64,.33,.3,.6,.15,.06],FC=[.2126,.7152,.0722],BC=[.3127,.329],zC=new Dt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),VC=new Dt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);fn.define({[Hc]:{primaries:UC,whitePoint:BC,transfer:Cv,toXYZ:zC,fromXYZ:VC,luminanceCoefficients:FC,workingColorSpaceConfig:{unpackColorSpace:pr},outputColorSpaceConfig:{drawingBufferColorSpace:pr}},[pr]:{primaries:UC,whitePoint:BC,transfer:bn,toXYZ:zC,fromXYZ:VC,luminanceCoefficients:FC,outputColorSpaceConfig:{drawingBufferColorSpace:pr}}});let kh;class P5{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{kh===void 0&&(kh=Ep("canvas")),kh.width=e.width,kh.height=e.height;const r=kh.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),n=kh}return n.width>2048||n.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),n.toDataURL("image/jpeg",.6)):n.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const n=Ep("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o0&&(r.userData=this.userData),n||(e.textures[this.uuid]=r),r}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==BI)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case $1:e.x=e.x-Math.floor(e.x);break;case Mu:e.x=e.x<0?0:1;break;case q1:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case $1:e.y=e.y-Math.floor(e.y);break;case Mu:e.y=e.y<0?0:1;break;case q1:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}or.DEFAULT_IMAGE=null;or.DEFAULT_MAPPING=BI;or.DEFAULT_ANISOTROPY=1;class gr{constructor(e=0,n=0,r=0,i=1){gr.prototype.isVector4=!0,this.x=e,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,n,r,i){return this.x=e,this.y=n,this.z=r,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;case 3:this.w=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this.w=e.w+n.w,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this.w+=e.w*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this.w=e.w-n.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*r+o[8]*i+o[12]*s,this.y=o[1]*n+o[5]*r+o[9]*i+o[13]*s,this.z=o[2]*n+o[6]*r+o[10]*i+o[14]*s,this.w=o[3]*n+o[7]*r+o[11]*i+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const n=Math.sqrt(1-e.w*e.w);return n<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/n,this.y=e.y/n,this.z=e.z/n),this}setAxisAngleFromRotationMatrix(e){let n,r,i,s;const l=e.elements,c=l[0],u=l[4],h=l[8],p=l[1],m=l[5],g=l[9],v=l[2],y=l[6],_=l[10];if(Math.abs(u-p)<.01&&Math.abs(h-v)<.01&&Math.abs(g-y)<.01){if(Math.abs(u+p)<.1&&Math.abs(h+v)<.1&&Math.abs(g+y)<.1&&Math.abs(c+m+_-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const E=(c+1)/2,T=(m+1)/2,N=(_+1)/2,R=(u+p)/4,C=(h+v)/4,O=(g+y)/4;return E>T&&E>N?E<.01?(r=0,i=.707106781,s=.707106781):(r=Math.sqrt(E),i=R/r,s=C/r):T>N?T<.01?(r=.707106781,i=0,s=.707106781):(i=Math.sqrt(T),r=R/i,s=O/i):N<.01?(r=.707106781,i=.707106781,s=0):(s=Math.sqrt(N),r=C/s,i=O/s),this.set(r,i,s,n),this}let S=Math.sqrt((y-g)*(y-g)+(h-v)*(h-v)+(p-u)*(p-u));return Math.abs(S)<.001&&(S=1),this.x=(y-g)/S,this.y=(h-v)/S,this.z=(p-u)/S,this.w=Math.acos((c+m+_-1)/2),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this.w=n[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this.w=Math.max(e.w,Math.min(n.w,this.w)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this.w=Math.max(e,Math.min(n,this.w)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this.w+=(e.w-this.w)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this.w=e.w+(n.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this.w=e[n+3],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e[n+3]=this.w,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this.w=e.getW(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class F5 extends Dl{constructor(e=1,n=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=1,this.scissor=new gr(0,0,e,n),this.scissorTest=!1,this.viewport=new gr(0,0,e,n);const i={width:e,height:n,depth:1};r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:rs,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},r);const s=new or(i,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.colorSpace);s.flipY=!1,s.generateMipmaps=r.generateMipmaps,s.internalFormat=r.internalFormat,this.textures=[];const o=r.count;for(let a=0;a=0?1:-1,E=1-_*_;if(E>Number.EPSILON){const N=Math.sqrt(E),R=Math.atan2(N,_*S);y=Math.sin(y*R)/N,a=Math.sin(a*R)/N}const T=a*S;if(l=l*y+p*T,c=c*y+m*T,u=u*y+g*T,h=h*y+v*T,y===1-a){const N=1/Math.sqrt(l*l+c*c+u*u+h*h);l*=N,c*=N,u*=N,h*=N}}e[n]=l,e[n+1]=c,e[n+2]=u,e[n+3]=h}static multiplyQuaternionsFlat(e,n,r,i,s,o){const a=r[i],l=r[i+1],c=r[i+2],u=r[i+3],h=s[o],p=s[o+1],m=s[o+2],g=s[o+3];return e[n]=a*g+u*h+l*m-c*p,e[n+1]=l*g+u*p+c*h-a*m,e[n+2]=c*g+u*m+a*p-l*h,e[n+3]=u*g-a*h-l*p-c*m,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,n,r,i){return this._x=e,this._y=n,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,n=!0){const r=e._x,i=e._y,s=e._z,o=e._order,a=Math.cos,l=Math.sin,c=a(r/2),u=a(i/2),h=a(s/2),p=l(r/2),m=l(i/2),g=l(s/2);switch(o){case"XYZ":this._x=p*u*h+c*m*g,this._y=c*m*h-p*u*g,this._z=c*u*g+p*m*h,this._w=c*u*h-p*m*g;break;case"YXZ":this._x=p*u*h+c*m*g,this._y=c*m*h-p*u*g,this._z=c*u*g-p*m*h,this._w=c*u*h+p*m*g;break;case"ZXY":this._x=p*u*h-c*m*g,this._y=c*m*h+p*u*g,this._z=c*u*g+p*m*h,this._w=c*u*h-p*m*g;break;case"ZYX":this._x=p*u*h-c*m*g,this._y=c*m*h+p*u*g,this._z=c*u*g-p*m*h,this._w=c*u*h+p*m*g;break;case"YZX":this._x=p*u*h+c*m*g,this._y=c*m*h+p*u*g,this._z=c*u*g-p*m*h,this._w=c*u*h-p*m*g;break;case"XZY":this._x=p*u*h-c*m*g,this._y=c*m*h-p*u*g,this._z=c*u*g+p*m*h,this._w=c*u*h+p*m*g;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return n===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const r=n/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,r=n[0],i=n[4],s=n[8],o=n[1],a=n[5],l=n[9],c=n[2],u=n[6],h=n[10],p=r+a+h;if(p>0){const m=.5/Math.sqrt(p+1);this._w=.25/m,this._x=(u-l)*m,this._y=(s-c)*m,this._z=(o-i)*m}else if(r>a&&r>h){const m=2*Math.sqrt(1+r-a-h);this._w=(u-l)/m,this._x=.25*m,this._y=(i+o)/m,this._z=(s+c)/m}else if(a>h){const m=2*Math.sqrt(1+a-r-h);this._w=(s-c)/m,this._x=(i+o)/m,this._y=.25*m,this._z=(l+u)/m}else{const m=2*Math.sqrt(1+h-r-a);this._w=(o-i)/m,this._x=(s+c)/m,this._y=(l+u)/m,this._z=.25*m}return this._onChangeCallback(),this}setFromUnitVectors(e,n){let r=e.dot(n)+1;return rMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*n.z-e.z*n.y,this._y=e.z*n.x-e.x*n.z,this._z=e.x*n.y-e.y*n.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Pi(this.dot(e),-1,1)))}rotateTowards(e,n){const r=this.angleTo(e);if(r===0)return this;const i=Math.min(1,n/r);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,n){const r=e._x,i=e._y,s=e._z,o=e._w,a=n._x,l=n._y,c=n._z,u=n._w;return this._x=r*u+o*a+i*c-s*l,this._y=i*u+o*l+s*a-r*c,this._z=s*u+o*c+r*l-i*a,this._w=o*u-r*a-i*l-s*c,this._onChangeCallback(),this}slerp(e,n){if(n===0)return this;if(n===1)return this.copy(e);const r=this._x,i=this._y,s=this._z,o=this._w;let a=o*e._w+r*e._x+i*e._y+s*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=o,this._x=r,this._y=i,this._z=s,this;const l=1-a*a;if(l<=Number.EPSILON){const m=1-n;return this._w=m*o+n*this._w,this._x=m*r+n*this._x,this._y=m*i+n*this._y,this._z=m*s+n*this._z,this.normalize(),this}const c=Math.sqrt(l),u=Math.atan2(c,a),h=Math.sin((1-n)*u)/c,p=Math.sin(n*u)/c;return this._w=o*h+this._w*p,this._x=r*h+this._x*p,this._y=i*h+this._y*p,this._z=s*h+this._z*p,this._onChangeCallback(),this}slerpQuaternions(e,n,r){return this.copy(e).slerp(n,r)}random(){const e=2*Math.PI*Math.random(),n=2*Math.PI*Math.random(),r=Math.random(),i=Math.sqrt(1-r),s=Math.sqrt(r);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(n),s*Math.cos(n))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,n=0){return this._x=e[n],this._y=e[n+1],this._z=e[n+2],this._w=e[n+3],this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._w,e}fromBufferAttribute(e,n){return this._x=e.getX(n),this._y=e.getY(n),this._z=e.getZ(n),this._w=e.getW(n),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class xe{constructor(e=0,n=0,r=0){xe.prototype.isVector3=!0,this.x=e,this.y=n,this.z=r}set(e,n,r){return r===void 0&&(r=this.z),this.x=e,this.y=n,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,n){return this.x=e.x*n.x,this.y=e.y*n.y,this.z=e.z*n.z,this}applyEuler(e){return this.applyQuaternion(HC.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(HC.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[3]*r+s[6]*i,this.y=s[1]*n+s[4]*r+s[7]*i,this.z=s[2]*n+s[5]*r+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*n+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*n+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*n+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*n+s[6]*r+s[10]*i+s[14])*o,this}applyQuaternion(e){const n=this.x,r=this.y,i=this.z,s=e.x,o=e.y,a=e.z,l=e.w,c=2*(o*i-a*r),u=2*(a*n-s*i),h=2*(s*r-o*n);return this.x=n+l*c+o*h-a*u,this.y=r+l*u+a*c-s*h,this.z=i+l*h+s*u-o*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[4]*r+s[8]*i,this.y=s[1]*n+s[5]*r+s[9]*i,this.z=s[2]*n+s[6]*r+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const r=e.x,i=e.y,s=e.z,o=n.x,a=n.y,l=n.z;return this.x=i*l-s*a,this.y=s*o-r*l,this.z=r*a-i*o,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const r=e.dot(this)/n;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return aS.copy(this).projectOnVector(e),this.sub(aS)}reflect(e){return this.sub(aS.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(Pi(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return n*n+r*r+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,n,r){const i=Math.sin(n)*e;return this.x=i*Math.sin(r),this.y=Math.cos(n)*e,this.z=i*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,r){return this.x=e*Math.sin(n),this.y=r,this.z=e*Math.cos(n),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this}setFromMatrixScale(e){const n=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=r,this.z=i,this}setFromMatrixColumn(e,n){return this.fromArray(e.elements,n*4)}setFromMatrix3Column(e,n){return this.fromArray(e.elements,n*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,n=Math.random()*2-1,r=Math.sqrt(1-n*n);return this.x=r*Math.cos(e),this.y=n,this.z=r*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const aS=new xe,HC=new Xp;class Kp{constructor(e=new xe(1/0,1/0,1/0),n=new xe(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=n}set(e,n){return this.min.copy(e),this.max.copy(n),this}setFromArray(e){this.makeEmpty();for(let n=0,r=e.length;n=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,n){return n.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,go),go.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,r;return e.normal.x>0?(n=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),n<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Dd),jg.subVectors(this.max,Dd),Ih.subVectors(e.a,Dd),Oh.subVectors(e.b,Dd),Lh.subVectors(e.c,Dd),ac.subVectors(Oh,Ih),lc.subVectors(Lh,Oh),ou.subVectors(Ih,Lh);let n=[0,-ac.z,ac.y,0,-lc.z,lc.y,0,-ou.z,ou.y,ac.z,0,-ac.x,lc.z,0,-lc.x,ou.z,0,-ou.x,-ac.y,ac.x,0,-lc.y,lc.x,0,-ou.y,ou.x,0];return!lS(n,Ih,Oh,Lh,jg)||(n=[1,0,0,0,1,0,0,0,1],!lS(n,Ih,Oh,Lh,jg))?!1:($g.crossVectors(ac,lc),n=[$g.x,$g.y,$g.z],lS(n,Ih,Oh,Lh,jg))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,go).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(go).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Ja[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ja[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ja[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ja[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ja[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ja[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ja[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ja[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ja),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Ja=[new xe,new xe,new xe,new xe,new xe,new xe,new xe,new xe],go=new xe,Wg=new Kp,Ih=new xe,Oh=new xe,Lh=new xe,ac=new xe,lc=new xe,ou=new xe,Dd=new xe,jg=new xe,$g=new xe,au=new xe;function lS(t,e,n,r,i){for(let s=0,o=t.length-3;s<=o;s+=3){au.fromArray(t,s);const a=i.x*Math.abs(au.x)+i.y*Math.abs(au.y)+i.z*Math.abs(au.z),l=e.dot(au),c=n.dot(au),u=r.dot(au);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>a)return!1}return!0}const z5=new Kp,Ud=new xe,cS=new xe;class Rv{constructor(e=new xe,n=-1){this.isSphere=!0,this.center=e,this.radius=n}set(e,n){return this.center.copy(e),this.radius=n,this}setFromPoints(e,n){const r=this.center;n!==void 0?r.copy(n):z5.setFromPoints(e).getCenter(r);let i=0;for(let s=0,o=e.length;sthis.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Ud.subVectors(e,this.center);const n=Ud.lengthSq();if(n>this.radius*this.radius){const r=Math.sqrt(n),i=(r-this.radius)*.5;this.center.addScaledVector(Ud,i/r),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(cS.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ud.copy(e.center).add(cS)),this.expandByPoint(Ud.copy(e.center).sub(cS))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const Qa=new xe,uS=new xe,qg=new xe,cc=new xe,hS=new xe,Xg=new xe,fS=new xe;class lT{constructor(e=new xe,n=new xe(0,0,-1)){this.origin=e,this.direction=n}set(e,n){return this.origin.copy(e),this.direction.copy(n),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,n){return n.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Qa)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const r=n.dot(this.direction);return r<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=Qa.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(Qa.copy(this.origin).addScaledVector(this.direction,n),Qa.distanceToSquared(e))}distanceSqToSegment(e,n,r,i){uS.copy(e).add(n).multiplyScalar(.5),qg.copy(n).sub(e).normalize(),cc.copy(this.origin).sub(uS);const s=e.distanceTo(n)*.5,o=-this.direction.dot(qg),a=cc.dot(this.direction),l=-cc.dot(qg),c=cc.lengthSq(),u=Math.abs(1-o*o);let h,p,m,g;if(u>0)if(h=o*l-a,p=o*a-l,g=s*u,h>=0)if(p>=-g)if(p<=g){const v=1/u;h*=v,p*=v,m=h*(h+o*p+2*a)+p*(o*h+p+2*l)+c}else p=s,h=Math.max(0,-(o*p+a)),m=-h*h+p*(p+2*l)+c;else p=-s,h=Math.max(0,-(o*p+a)),m=-h*h+p*(p+2*l)+c;else p<=-g?(h=Math.max(0,-(-o*s+a)),p=h>0?-s:Math.min(Math.max(-s,-l),s),m=-h*h+p*(p+2*l)+c):p<=g?(h=0,p=Math.min(Math.max(-s,-l),s),m=p*(p+2*l)+c):(h=Math.max(0,-(o*s+a)),p=h>0?s:Math.min(Math.max(-s,-l),s),m=-h*h+p*(p+2*l)+c);else p=o>0?-s:s,h=Math.max(0,-(o*p+a)),m=-h*h+p*(p+2*l)+c;return r&&r.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(uS).addScaledVector(qg,p),m}intersectSphere(e,n){Qa.subVectors(e.center,this.origin);const r=Qa.dot(this.direction),i=Qa.dot(Qa)-r*r,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),a=r-o,l=r+o;return l<0?null:a<0?this.at(l,n):this.at(a,n)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const n=e.normal.dot(this.direction);if(n===0)return e.distanceToPoint(this.origin)===0?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/n;return r>=0?r:null}intersectPlane(e,n){const r=this.distanceToPlane(e);return r===null?null:this.at(r,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let r,i,s,o,a,l;const c=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,p=this.origin;return c>=0?(r=(e.min.x-p.x)*c,i=(e.max.x-p.x)*c):(r=(e.max.x-p.x)*c,i=(e.min.x-p.x)*c),u>=0?(s=(e.min.y-p.y)*u,o=(e.max.y-p.y)*u):(s=(e.max.y-p.y)*u,o=(e.min.y-p.y)*u),r>o||s>i||((s>r||isNaN(r))&&(r=s),(o=0?(a=(e.min.z-p.z)*h,l=(e.max.z-p.z)*h):(a=(e.max.z-p.z)*h,l=(e.min.z-p.z)*h),r>l||a>i)||((a>r||r!==r)&&(r=a),(l=0?r:i,n)}intersectsBox(e){return this.intersectBox(e,Qa)!==null}intersectTriangle(e,n,r,i,s){hS.subVectors(n,e),Xg.subVectors(r,e),fS.crossVectors(hS,Xg);let o=this.direction.dot(fS),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;cc.subVectors(this.origin,e);const l=a*this.direction.dot(Xg.crossVectors(cc,Xg));if(l<0)return null;const c=a*this.direction.dot(hS.cross(cc));if(c<0||l+c>o)return null;const u=-a*cc.dot(fS);return u<0?null:this.at(u/o,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class ar{constructor(e,n,r,i,s,o,a,l,c,u,h,p,m,g,v,y){ar.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,a,l,c,u,h,p,m,g,v,y)}set(e,n,r,i,s,o,a,l,c,u,h,p,m,g,v,y){const _=this.elements;return _[0]=e,_[4]=n,_[8]=r,_[12]=i,_[1]=s,_[5]=o,_[9]=a,_[13]=l,_[2]=c,_[6]=u,_[10]=h,_[14]=p,_[3]=m,_[7]=g,_[11]=v,_[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ar().fromArray(this.elements)}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],n[9]=r[9],n[10]=r[10],n[11]=r[11],n[12]=r[12],n[13]=r[13],n[14]=r[14],n[15]=r[15],this}copyPosition(e){const n=this.elements,r=e.elements;return n[12]=r[12],n[13]=r[13],n[14]=r[14],this}setFromMatrix3(e){const n=e.elements;return this.set(n[0],n[3],n[6],0,n[1],n[4],n[7],0,n[2],n[5],n[8],0,0,0,0,1),this}extractBasis(e,n,r){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,n,r){return this.set(e.x,n.x,r.x,0,e.y,n.y,r.y,0,e.z,n.z,r.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,r=e.elements,i=1/Ph.setFromMatrixColumn(e,0).length(),s=1/Ph.setFromMatrixColumn(e,1).length(),o=1/Ph.setFromMatrixColumn(e,2).length();return n[0]=r[0]*i,n[1]=r[1]*i,n[2]=r[2]*i,n[3]=0,n[4]=r[4]*s,n[5]=r[5]*s,n[6]=r[6]*s,n[7]=0,n[8]=r[8]*o,n[9]=r[9]*o,n[10]=r[10]*o,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,r=e.x,i=e.y,s=e.z,o=Math.cos(r),a=Math.sin(r),l=Math.cos(i),c=Math.sin(i),u=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const p=o*u,m=o*h,g=a*u,v=a*h;n[0]=l*u,n[4]=-l*h,n[8]=c,n[1]=m+g*c,n[5]=p-v*c,n[9]=-a*l,n[2]=v-p*c,n[6]=g+m*c,n[10]=o*l}else if(e.order==="YXZ"){const p=l*u,m=l*h,g=c*u,v=c*h;n[0]=p+v*a,n[4]=g*a-m,n[8]=o*c,n[1]=o*h,n[5]=o*u,n[9]=-a,n[2]=m*a-g,n[6]=v+p*a,n[10]=o*l}else if(e.order==="ZXY"){const p=l*u,m=l*h,g=c*u,v=c*h;n[0]=p-v*a,n[4]=-o*h,n[8]=g+m*a,n[1]=m+g*a,n[5]=o*u,n[9]=v-p*a,n[2]=-o*c,n[6]=a,n[10]=o*l}else if(e.order==="ZYX"){const p=o*u,m=o*h,g=a*u,v=a*h;n[0]=l*u,n[4]=g*c-m,n[8]=p*c+v,n[1]=l*h,n[5]=v*c+p,n[9]=m*c-g,n[2]=-c,n[6]=a*l,n[10]=o*l}else if(e.order==="YZX"){const p=o*l,m=o*c,g=a*l,v=a*c;n[0]=l*u,n[4]=v-p*h,n[8]=g*h+m,n[1]=h,n[5]=o*u,n[9]=-a*u,n[2]=-c*u,n[6]=m*h+g,n[10]=p-v*h}else if(e.order==="XZY"){const p=o*l,m=o*c,g=a*l,v=a*c;n[0]=l*u,n[4]=-h,n[8]=c*u,n[1]=p*h+v,n[5]=o*u,n[9]=m*h-g,n[2]=g*h-m,n[6]=a*u,n[10]=v*h+p}return n[3]=0,n[7]=0,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromQuaternion(e){return this.compose(V5,e,H5)}lookAt(e,n,r){const i=this.elements;return ws.subVectors(e,n),ws.lengthSq()===0&&(ws.z=1),ws.normalize(),uc.crossVectors(r,ws),uc.lengthSq()===0&&(Math.abs(r.z)===1?ws.x+=1e-4:ws.z+=1e-4,ws.normalize(),uc.crossVectors(r,ws)),uc.normalize(),Kg.crossVectors(ws,uc),i[0]=uc.x,i[4]=Kg.x,i[8]=ws.x,i[1]=uc.y,i[5]=Kg.y,i[9]=ws.y,i[2]=uc.z,i[6]=Kg.z,i[10]=ws.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],a=r[4],l=r[8],c=r[12],u=r[1],h=r[5],p=r[9],m=r[13],g=r[2],v=r[6],y=r[10],_=r[14],S=r[3],E=r[7],T=r[11],N=r[15],R=i[0],C=i[4],O=i[8],M=i[12],I=i[1],U=i[5],L=i[9],P=i[13],b=i[2],H=i[6],V=i[10],B=i[14],z=i[3],W=i[7],K=i[11],j=i[15];return s[0]=o*R+a*I+l*b+c*z,s[4]=o*C+a*U+l*H+c*W,s[8]=o*O+a*L+l*V+c*K,s[12]=o*M+a*P+l*B+c*j,s[1]=u*R+h*I+p*b+m*z,s[5]=u*C+h*U+p*H+m*W,s[9]=u*O+h*L+p*V+m*K,s[13]=u*M+h*P+p*B+m*j,s[2]=g*R+v*I+y*b+_*z,s[6]=g*C+v*U+y*H+_*W,s[10]=g*O+v*L+y*V+_*K,s[14]=g*M+v*P+y*B+_*j,s[3]=S*R+E*I+T*b+N*z,s[7]=S*C+E*U+T*H+N*W,s[11]=S*O+E*L+T*V+N*K,s[15]=S*M+E*P+T*B+N*j,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[4]*=e,n[8]*=e,n[12]*=e,n[1]*=e,n[5]*=e,n[9]*=e,n[13]*=e,n[2]*=e,n[6]*=e,n[10]*=e,n[14]*=e,n[3]*=e,n[7]*=e,n[11]*=e,n[15]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[4],i=e[8],s=e[12],o=e[1],a=e[5],l=e[9],c=e[13],u=e[2],h=e[6],p=e[10],m=e[14],g=e[3],v=e[7],y=e[11],_=e[15];return g*(+s*l*h-i*c*h-s*a*p+r*c*p+i*a*m-r*l*m)+v*(+n*l*m-n*c*p+s*o*p-i*o*m+i*c*u-s*l*u)+y*(+n*c*h-n*a*m-s*o*h+r*o*m+s*a*u-r*c*u)+_*(-i*a*u-n*l*h+n*a*p+i*o*h-r*o*p+r*l*u)}transpose(){const e=this.elements;let n;return n=e[1],e[1]=e[4],e[4]=n,n=e[2],e[2]=e[8],e[8]=n,n=e[6],e[6]=e[9],e[9]=n,n=e[3],e[3]=e[12],e[12]=n,n=e[7],e[7]=e[13],e[13]=n,n=e[11],e[11]=e[14],e[14]=n,this}setPosition(e,n,r){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=n,i[14]=r),this}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8],h=e[9],p=e[10],m=e[11],g=e[12],v=e[13],y=e[14],_=e[15],S=h*y*c-v*p*c+v*l*m-a*y*m-h*l*_+a*p*_,E=g*p*c-u*y*c-g*l*m+o*y*m+u*l*_-o*p*_,T=u*v*c-g*h*c+g*a*m-o*v*m-u*a*_+o*h*_,N=g*h*l-u*v*l-g*a*p+o*v*p+u*a*y-o*h*y,R=n*S+r*E+i*T+s*N;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const C=1/R;return e[0]=S*C,e[1]=(v*p*s-h*y*s-v*i*m+r*y*m+h*i*_-r*p*_)*C,e[2]=(a*y*s-v*l*s+v*i*c-r*y*c-a*i*_+r*l*_)*C,e[3]=(h*l*s-a*p*s-h*i*c+r*p*c+a*i*m-r*l*m)*C,e[4]=E*C,e[5]=(u*y*s-g*p*s+g*i*m-n*y*m-u*i*_+n*p*_)*C,e[6]=(g*l*s-o*y*s-g*i*c+n*y*c+o*i*_-n*l*_)*C,e[7]=(o*p*s-u*l*s+u*i*c-n*p*c-o*i*m+n*l*m)*C,e[8]=T*C,e[9]=(g*h*s-u*v*s-g*r*m+n*v*m+u*r*_-n*h*_)*C,e[10]=(o*v*s-g*a*s+g*r*c-n*v*c-o*r*_+n*a*_)*C,e[11]=(u*a*s-o*h*s-u*r*c+n*h*c+o*r*m-n*a*m)*C,e[12]=N*C,e[13]=(u*v*i-g*h*i+g*r*p-n*v*p-u*r*y+n*h*y)*C,e[14]=(g*a*i-o*v*i-g*r*l+n*v*l+o*r*y-n*a*y)*C,e[15]=(o*h*i-u*a*i+u*r*l-n*h*l-o*r*p+n*a*p)*C,this}scale(e){const n=this.elements,r=e.x,i=e.y,s=e.z;return n[0]*=r,n[4]*=i,n[8]*=s,n[1]*=r,n[5]*=i,n[9]*=s,n[2]*=r,n[6]*=i,n[10]*=s,n[3]*=r,n[7]*=i,n[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,n=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,r,i))}makeTranslation(e,n,r){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,n,0,0,1,r,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,n,-r,0,0,r,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,0,r,0,0,1,0,0,-r,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,0,r,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const r=Math.cos(n),i=Math.sin(n),s=1-r,o=e.x,a=e.y,l=e.z,c=s*o,u=s*a;return this.set(c*o+r,c*a-i*l,c*l+i*a,0,c*a+i*l,u*a+r,u*l-i*o,0,c*l-i*a,u*l+i*o,s*l*l+r,0,0,0,0,1),this}makeScale(e,n,r){return this.set(e,0,0,0,0,n,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,n,r,i,s,o){return this.set(1,r,s,0,e,1,o,0,n,i,1,0,0,0,0,1),this}compose(e,n,r){const i=this.elements,s=n._x,o=n._y,a=n._z,l=n._w,c=s+s,u=o+o,h=a+a,p=s*c,m=s*u,g=s*h,v=o*u,y=o*h,_=a*h,S=l*c,E=l*u,T=l*h,N=r.x,R=r.y,C=r.z;return i[0]=(1-(v+_))*N,i[1]=(m+T)*N,i[2]=(g-E)*N,i[3]=0,i[4]=(m-T)*R,i[5]=(1-(p+_))*R,i[6]=(y+S)*R,i[7]=0,i[8]=(g+E)*C,i[9]=(y-S)*C,i[10]=(1-(p+v))*C,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,n,r){const i=this.elements;let s=Ph.set(i[0],i[1],i[2]).length();const o=Ph.set(i[4],i[5],i[6]).length(),a=Ph.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),e.x=i[12],e.y=i[13],e.z=i[14],_o.copy(this);const c=1/s,u=1/o,h=1/a;return _o.elements[0]*=c,_o.elements[1]*=c,_o.elements[2]*=c,_o.elements[4]*=u,_o.elements[5]*=u,_o.elements[6]*=u,_o.elements[8]*=h,_o.elements[9]*=h,_o.elements[10]*=h,n.setFromRotationMatrix(_o),r.x=s,r.y=o,r.z=a,this}makePerspective(e,n,r,i,s,o,a=pl){const l=this.elements,c=2*s/(n-e),u=2*s/(r-i),h=(n+e)/(n-e),p=(r+i)/(r-i);let m,g;if(a===pl)m=-(o+s)/(o-s),g=-2*o*s/(o-s);else if(a===A_)m=-o/(o-s),g=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=c,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,l[9]=p,l[13]=0,l[2]=0,l[6]=0,l[10]=m,l[14]=g,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,n,r,i,s,o,a=pl){const l=this.elements,c=1/(n-e),u=1/(r-i),h=1/(o-s),p=(n+e)*c,m=(r+i)*u;let g,v;if(a===pl)g=(o+s)*h,v=-2*h;else if(a===A_)g=s*h,v=-1*h;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-p,l[1]=0,l[5]=2*u,l[9]=0,l[13]=-m,l[2]=0,l[6]=0,l[10]=v,l[14]=-g,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const n=this.elements,r=e.elements;for(let i=0;i<16;i++)if(n[i]!==r[i])return!1;return!0}fromArray(e,n=0){for(let r=0;r<16;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e[n+9]=r[9],e[n+10]=r[10],e[n+11]=r[11],e[n+12]=r[12],e[n+13]=r[13],e[n+14]=r[14],e[n+15]=r[15],e}}const Ph=new xe,_o=new ar,V5=new xe(0,0,0),H5=new xe(1,1,1),uc=new xe,Kg=new xe,ws=new xe,GC=new ar,WC=new Xp;class Ml{constructor(e=0,n=0,r=0,i=Ml.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,n,r,i=this._order){return this._x=e,this._y=n,this._z=r,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,n=this._order,r=!0){const i=e.elements,s=i[0],o=i[4],a=i[8],l=i[1],c=i[5],u=i[9],h=i[2],p=i[6],m=i[10];switch(n){case"XYZ":this._y=Math.asin(Pi(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,m),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(p,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Pi(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,m),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(Pi(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-h,m),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-Pi(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(p,m),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(Pi(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(a,m));break;case"XZY":this._z=Math.asin(-Pi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(p,c),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-u,m),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,r){return GC.makeRotationFromQuaternion(e),this.setFromRotationMatrix(GC,n,r)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return WC.setFromEuler(this),this.setFromQuaternion(WC,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ml.DEFAULT_ORDER="XYZ";class yf{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let n=0;n1){for(let r=0;r0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(a=>({boxInitialized:a.boxInitialized,boxMin:a.box.min.toArray(),boxMax:a.box.max.toArray(),sphereInitialized:a.sphereInitialized,sphereRadius:a.sphere.radius,sphereCenter:a.sphere.center.toArray()})),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()}));function s(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const l=a.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){i.children=[];for(let a=0;a0){i.animations=[];for(let a=0;a0&&(r.geometries=a),l.length>0&&(r.materials=l),c.length>0&&(r.textures=c),u.length>0&&(r.images=u),h.length>0&&(r.shapes=h),p.length>0&&(r.skeletons=p),m.length>0&&(r.animations=m),g.length>0&&(r.nodes=g)}return r.object=i,r;function o(a){const l=[];for(const c in a){const u=a[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,n=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),n===!0)for(let r=0;r0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,n,r,i,s){vo.subVectors(i,n),tl.subVectors(r,n),pS.subVectors(e,n);const o=vo.dot(vo),a=vo.dot(tl),l=vo.dot(pS),c=tl.dot(tl),u=tl.dot(pS),h=o*c-a*a;if(h===0)return s.set(0,0,0),null;const p=1/h,m=(c*l-a*u)*p,g=(o*u-a*l)*p;return s.set(1-m-g,g,m)}static containsPoint(e,n,r,i){return this.getBarycoord(e,n,r,i,nl)===null?!1:nl.x>=0&&nl.y>=0&&nl.x+nl.y<=1}static getInterpolation(e,n,r,i,s,o,a,l){return this.getBarycoord(e,n,r,i,nl)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,nl.x),l.addScaledVector(o,nl.y),l.addScaledVector(a,nl.z),l)}static getInterpolatedAttribute(e,n,r,i,s,o){return vS.setScalar(0),yS.setScalar(0),xS.setScalar(0),vS.fromBufferAttribute(e,n),yS.fromBufferAttribute(e,r),xS.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(vS,s.x),o.addScaledVector(yS,s.y),o.addScaledVector(xS,s.z),o}static isFrontFacing(e,n,r,i){return vo.subVectors(r,n),tl.subVectors(e,n),vo.cross(tl).dot(i)<0}set(e,n,r){return this.a.copy(e),this.b.copy(n),this.c.copy(r),this}setFromPointsAndIndices(e,n,r,i){return this.a.copy(e[n]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,n,r,i){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return vo.subVectors(this.c,this.b),tl.subVectors(this.a,this.b),vo.cross(tl).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return To.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return To.getBarycoord(e,this.a,this.b,this.c,n)}getInterpolation(e,n,r,i,s){return To.getInterpolation(e,this.a,this.b,this.c,n,r,i,s)}containsPoint(e){return To.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return To.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const r=this.a,i=this.b,s=this.c;let o,a;Fh.subVectors(i,r),Bh.subVectors(s,r),mS.subVectors(e,r);const l=Fh.dot(mS),c=Bh.dot(mS);if(l<=0&&c<=0)return n.copy(r);gS.subVectors(e,i);const u=Fh.dot(gS),h=Bh.dot(gS);if(u>=0&&h<=u)return n.copy(i);const p=l*h-u*c;if(p<=0&&l>=0&&u<=0)return o=l/(l-u),n.copy(r).addScaledVector(Fh,o);_S.subVectors(e,s);const m=Fh.dot(_S),g=Bh.dot(_S);if(g>=0&&m<=g)return n.copy(s);const v=m*c-l*g;if(v<=0&&c>=0&&g<=0)return a=c/(c-g),n.copy(r).addScaledVector(Bh,a);const y=u*g-m*h;if(y<=0&&h-u>=0&&m-g>=0)return YC.subVectors(s,i),a=(h-u)/(h-u+(m-g)),n.copy(i).addScaledVector(YC,a);const _=1/(y+v+p);return o=v*_,a=p*_,n.copy(r).addScaledVector(Fh,o).addScaledVector(Bh,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const tO={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},hc={h:0,s:0,l:0},Zg={h:0,s:0,l:0};function SS(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*6*(2/3-n):t}class cn{constructor(e,n,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,r)}set(e,n,r){if(n===void 0&&r===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,n,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=pr){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,fn.toWorkingColorSpace(this,n),this}setRGB(e,n,r,i=fn.workingColorSpace){return this.r=e,this.g=n,this.b=r,fn.toWorkingColorSpace(this,i),this}setHSL(e,n,r,i=fn.workingColorSpace){if(e=aT(e,1),n=Pi(n,0,1),r=Pi(r,0,1),n===0)this.r=this.g=this.b=r;else{const s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;this.r=SS(o,s,e+1/3),this.g=SS(o,s,e),this.b=SS(o,s,e-1/3)}return fn.toWorkingColorSpace(this,i),this}setStyle(e,n=pr){function r(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,n);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,n);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,n);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,n);if(o===6)return this.setHex(parseInt(s,16),n);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=pr){const r=tO[e.toLowerCase()];return r!==void 0?this.setHex(r,n):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=vl(e.r),this.g=vl(e.g),this.b=vl(e.b),this}copyLinearToSRGB(e){return this.r=vf(e.r),this.g=vf(e.g),this.b=vf(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=pr){return fn.fromWorkingColorSpace(vi.copy(this),e),Math.round(Pi(vi.r*255,0,255))*65536+Math.round(Pi(vi.g*255,0,255))*256+Math.round(Pi(vi.b*255,0,255))}getHexString(e=pr){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=fn.workingColorSpace){fn.fromWorkingColorSpace(vi.copy(this),n);const r=vi.r,i=vi.g,s=vi.b,o=Math.max(r,i,s),a=Math.min(r,i,s);let l,c;const u=(a+o)/2;if(a===o)l=0,c=0;else{const h=o-a;switch(c=u<=.5?h/(o+a):h/(2-o-a),o){case r:l=(i-s)/h+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const n in e){const r=e[n];if(r===void 0){console.warn(`THREE.Material: parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){console.warn(`THREE.Material: '${n}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[n]=r}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const r={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(r.dispersion=this.dispersion),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapRotation!==void 0&&(r.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==gf&&(r.blending=this.blending),this.side!==Al&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==P1&&(r.blendSrc=this.blendSrc),this.blendDst!==D1&&(r.blendDst=this.blendDst),this.blendEquation!==Tu&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==Rf&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==IC&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Nh&&(r.stencilFail=this.stencilFail),this.stencilZFail!==Nh&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==Nh&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function i(s){const o=[];for(const a in s){const l=s[a];delete l.metadata,o.push(l)}return o}if(n){const s=i(e.textures),o=i(e.images);s.length>0&&(r.textures=s),o.length>0&&(r.images=o)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const n=e.clippingPlanes;let r=null;if(n!==null){const i=n.length;r=new Array(i);for(let s=0;s!==i;++s)r[s]=n[s].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class cT extends Ul{static get type(){return"MeshBasicMaterial"}constructor(e){super(),this.isMeshBasicMaterial=!0,this.color=new cn(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ml,this.combine=UI,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Er=new xe,Jg=new St;class Jn{constructor(e,n,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=r,this.usage=OC,this.updateRanges=[],this.gpuType=ga,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,n,r){e*=this.itemSize,r*=n.itemSize;for(let i=0,s=this.itemSize;in.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),n.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Kp);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new xe(-1/0,-1/0,-1/0),new xe(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let r=0,i=n.length;r0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const n=this.index;n!==null&&(e.data.index={type:n.array.constructor.name,array:Array.prototype.slice.call(n.array)});const r=this.attributes;for(const l in r){const c=r[l];e.data.attributes[l]=c.toJSON(e.data)}const i={};let s=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let h=0,p=c.length;h0&&(i[l]=u,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const n={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone(n));const i=e.attributes;for(const c in i){const u=i[c];this.setAttribute(c,u.clone(n))}const s=e.morphAttributes;for(const c in s){const u=[],h=s[c];for(let p=0,m=h.length;p0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s(e.far-e.near)**2))&&(ZC.copy(s).invert(),lu.copy(e.ray).applyMatrix4(ZC),!(r.boundingBox!==null&&lu.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,n,lu)))}_computeIntersections(e,n,r){let i;const s=this.geometry,o=this.material,a=s.index,l=s.attributes.position,c=s.attributes.uv,u=s.attributes.uv1,h=s.attributes.normal,p=s.groups,m=s.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=p.length;gn.far?null:{distance:c,point:i0.clone(),object:t}}function s0(t,e,n,r,i,s,o,a,l,c){t.getVertexPosition(a,e0),t.getVertexPosition(l,t0),t.getVertexPosition(c,n0);const u=K5(t,e,n,r,e0,t0,n0,QC);if(u){const h=new xe;To.getBarycoord(QC,e0,t0,n0,h),i&&(u.uv=To.getInterpolatedAttribute(i,a,l,c,h,new St)),s&&(u.uv1=To.getInterpolatedAttribute(s,a,l,c,h,new St)),o&&(u.normal=To.getInterpolatedAttribute(o,a,l,c,h,new xe),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));const p={a,b:l,c,normal:new xe,materialIndex:0};To.getNormal(e0,t0,n0,p.normal),u.face=p,u.barycoord=h}return u}class Yp extends Bo{constructor(e=1,n=1,r=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:r,widthSegments:i,heightSegments:s,depthSegments:o};const a=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const l=[],c=[],u=[],h=[];let p=0,m=0;g("z","y","x",-1,-1,r,n,e,o,s,0),g("z","y","x",1,-1,r,n,-e,o,s,1),g("x","z","y",1,1,e,r,n,i,o,2),g("x","z","y",1,-1,e,r,-n,i,o,3),g("x","y","z",1,-1,e,n,r,i,s,4),g("x","y","z",-1,-1,e,n,-r,i,s,5),this.setIndex(l),this.setAttribute("position",new Ou(c,3)),this.setAttribute("normal",new Ou(u,3)),this.setAttribute("uv",new Ou(h,2));function g(v,y,_,S,E,T,N,R,C,O,M){const I=T/C,U=N/O,L=T/2,P=N/2,b=R/2,H=C+1,V=O+1;let B=0,z=0;const W=new xe;for(let K=0;K0?1:-1,u.push(W.x,W.y,W.z),h.push(Y/C),h.push(1-K/O),B+=1}}for(let K=0;K0&&(n.defines=this.defines),n.vertexShader=this.vertexShader,n.fragmentShader=this.fragmentShader,n.lights=this.lights,n.clipping=this.clipping;const r={};for(const i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(n.extensions=r),n}}class Nv extends as{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ar,this.projectionMatrix=new ar,this.projectionMatrixInverse=new ar,this.coordinateSystem=pl}copy(e,n){return super.copy(e,n),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,n){super.updateWorldMatrix(e,n),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const fc=new xe,eR=new St,tR=new St;class As extends Nv{constructor(e=50,n=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=n,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const n=.5*this.getFilmHeight()/e;this.fov=Sp*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(hp*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Sp*2*Math.atan(Math.tan(hp*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,n,r){fc.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(fc.x,fc.y).multiplyScalar(-e/fc.z),fc.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),r.set(fc.x,fc.y).multiplyScalar(-e/fc.z)}getViewSize(e,n){return this.getViewBounds(e,eR,tR),n.subVectors(tR,eR)}setViewOffset(e,n,r,i,s,o){this.aspect=e/n,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let n=e*Math.tan(hp*.5*this.fov)/this.zoom,r=2*n,i=this.aspect*r,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const l=o.fullWidth,c=o.fullHeight;s+=o.offsetX*i/l,n-=o.offsetY*r/c,i*=o.width/l,r*=o.height/c}const a=this.filmOffset;a!==0&&(s+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,n,n-r,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.fov=this.fov,n.object.zoom=this.zoom,n.object.near=this.near,n.object.far=this.far,n.object.focus=this.focus,n.object.aspect=this.aspect,this.view!==null&&(n.object.view=Object.assign({},this.view)),n.object.filmGauge=this.filmGauge,n.object.filmOffset=this.filmOffset,n}}const Vh=-90,Hh=1;class ez extends as{constructor(e,n,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new As(Vh,Hh,e,n);i.layers=this.layers,this.add(i);const s=new As(Vh,Hh,e,n);s.layers=this.layers,this.add(s);const o=new As(Vh,Hh,e,n);o.layers=this.layers,this.add(o);const a=new As(Vh,Hh,e,n);a.layers=this.layers,this.add(a);const l=new As(Vh,Hh,e,n);l.layers=this.layers,this.add(l);const c=new As(Vh,Hh,e,n);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[r,i,s,o,a,l]=n;for(const c of n)this.remove(c);if(e===pl)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===A_)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of n)this.add(c),c.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,a,l,c,u]=this.children,h=e.getRenderTarget(),p=e.getActiveCubeFace(),m=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(n,s),e.setRenderTarget(r,1,i),e.render(n,o),e.setRenderTarget(r,2,i),e.render(n,a),e.setRenderTarget(r,3,i),e.render(n,l),e.setRenderTarget(r,4,i),e.render(n,c),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,i),e.render(n,u),e.setRenderTarget(h,p,m),e.xr.enabled=g,r.texture.needsPMREMUpdate=!0}}class sO extends or{constructor(e,n,r,i,s,o,a,l,c,u){e=e!==void 0?e:[],n=n!==void 0?n:Nf,super(e,n,r,i,s,o,a,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class tz extends Ps{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];this.texture=new sO(i,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=n.generateMipmaps!==void 0?n.generateMipmaps:!1,this.texture.minFilter=n.minFilter!==void 0?n.minFilter:rs}fromEquirectangularTexture(e,n){this.texture.type=n.type,this.texture.colorSpace=n.colorSpace,this.texture.generateMipmaps=n.generateMipmaps,this.texture.minFilter=n.minFilter,this.texture.magFilter=n.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},i=new Yp(5,5,5),s=new Hi({name:"CubemapFromEquirect",uniforms:If(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:ni,blending:Ro});s.uniforms.tEquirect.value=n;const o=new Ao(i,s),a=n.minFilter;return n.minFilter===Cu&&(n.minFilter=rs),new ez(1,10,this).update(e,o),n.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,n,r,i){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,r,i);e.setRenderTarget(s)}}const TS=new xe,nz=new xe,rz=new Dt;class xo{constructor(e=new xe(1,0,0),n=0){this.isPlane=!0,this.normal=e,this.constant=n}set(e,n){return this.normal.copy(e),this.constant=n,this}setComponents(e,n,r,i){return this.normal.set(e,n,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,r){const i=TS.subVectors(r,n).cross(nz.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,n){return n.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,n){const r=e.delta(TS),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:n.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return n<0&&r>0||r<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const r=n||rz.getNormalMatrix(e),i=this.coplanarPoint(TS).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const cu=new Rv,o0=new xe;class oO{constructor(e=new xo,n=new xo,r=new xo,i=new xo,s=new xo,o=new xo){this.planes=[e,n,r,i,s,o]}set(e,n,r,i,s,o){const a=this.planes;return a[0].copy(e),a[1].copy(n),a[2].copy(r),a[3].copy(i),a[4].copy(s),a[5].copy(o),this}copy(e){const n=this.planes;for(let r=0;r<6;r++)n[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,n=pl){const r=this.planes,i=e.elements,s=i[0],o=i[1],a=i[2],l=i[3],c=i[4],u=i[5],h=i[6],p=i[7],m=i[8],g=i[9],v=i[10],y=i[11],_=i[12],S=i[13],E=i[14],T=i[15];if(r[0].setComponents(l-s,p-c,y-m,T-_).normalize(),r[1].setComponents(l+s,p+c,y+m,T+_).normalize(),r[2].setComponents(l+o,p+u,y+g,T+S).normalize(),r[3].setComponents(l-o,p-u,y-g,T-S).normalize(),r[4].setComponents(l-a,p-h,y-v,T-E).normalize(),n===pl)r[5].setComponents(l+a,p+h,y+v,T+E).normalize();else if(n===A_)r[5].setComponents(a,h,v,E).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),cu.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),cu.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(cu)}intersectsSprite(e){return cu.center.set(0,0,0),cu.radius=.7071067811865476,cu.applyMatrix4(e.matrixWorld),this.intersectsSphere(cu)}intersectsSphere(e){const n=this.planes,r=e.center,i=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)0?e.max.x:e.min.x,o0.y=i.normal.y>0?e.max.y:e.min.y,o0.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(o0)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let r=0;r<6;r++)if(n[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function aO(){let t=null,e=!1,n=null,r=null;function i(s,o){n(s,o),r=t.requestAnimationFrame(i)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(i),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function iz(t){const e=new WeakMap;function n(a,l){const c=a.array,u=a.usage,h=c.byteLength,p=t.createBuffer();t.bindBuffer(l,p),t.bufferData(l,c,u),a.onUploadCallback();let m;if(c instanceof Float32Array)m=t.FLOAT;else if(c instanceof Uint16Array)a.isFloat16BufferAttribute?m=t.HALF_FLOAT:m=t.UNSIGNED_SHORT;else if(c instanceof Int16Array)m=t.SHORT;else if(c instanceof Uint32Array)m=t.UNSIGNED_INT;else if(c instanceof Int32Array)m=t.INT;else if(c instanceof Int8Array)m=t.BYTE;else if(c instanceof Uint8Array)m=t.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)m=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:p,type:m,bytesPerElement:c.BYTES_PER_ELEMENT,version:a.version,size:h}}function r(a,l,c){const u=l.array,h=l.updateRanges;if(t.bindBuffer(c,a),h.length===0)t.bufferSubData(c,0,u);else{h.sort((m,g)=>m.start-g.start);let p=0;for(let m=1;m 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,Sz=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,Ez=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,wz=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,Tz=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,bz=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,Az=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,Mz=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,Cz=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,Rz=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,Nz=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,kz=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,Iz=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,Oz=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,Lz=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,Pz="gl_FragColor = linearToOutputTexel( gl_FragColor );",Dz=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,Uz=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,Fz=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,Bz=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,zz=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,Vz=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,Hz=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,Gz=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,Wz=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,jz=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,$z=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,qz=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,Xz=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,Kz=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Yz=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,Zz=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,Jz=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,Qz=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,e8=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,t8=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,n8=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,r8=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,i8=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,s8=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,o8=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,a8=`#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,l8=`#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,c8=`#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`,u8=`#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,h8=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,f8=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,d8=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,p8=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,m8=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,g8=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,_8=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,v8=`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,y8=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,x8=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,S8=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,E8=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,w8=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,T8=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,b8=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,A8=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,M8=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,C8=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,R8=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,N8=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,k8=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,I8=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,O8=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,L8=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,P8=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,D8=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,U8=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,F8=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,B8=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,z8=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`,V8=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,H8=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,G8=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,W8=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,j8=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,$8=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,q8=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,X8=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,K8=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,Y8=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,Z8=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,J8=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,Q8=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + + #else + + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,e6=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,t6=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,n6=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,r6=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`;const i6=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,s6=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,o6=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,a6=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,l6=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,c6=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,u6=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,h6=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,f6=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,d6=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,p6=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,m6=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,g6=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,_6=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,v6=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,y6=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,x6=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,S6=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,E6=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,w6=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,T6=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,b6=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,A6=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,M6=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,C6=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,R6=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,N6=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,k6=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,I6=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,O6=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,L6=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,P6=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,D6=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,U6=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,Ft={alphahash_fragment:sz,alphahash_pars_fragment:oz,alphamap_fragment:az,alphamap_pars_fragment:lz,alphatest_fragment:cz,alphatest_pars_fragment:uz,aomap_fragment:hz,aomap_pars_fragment:fz,batching_pars_vertex:dz,batching_vertex:pz,begin_vertex:mz,beginnormal_vertex:gz,bsdfs:_z,iridescence_fragment:vz,bumpmap_pars_fragment:yz,clipping_planes_fragment:xz,clipping_planes_pars_fragment:Sz,clipping_planes_pars_vertex:Ez,clipping_planes_vertex:wz,color_fragment:Tz,color_pars_fragment:bz,color_pars_vertex:Az,color_vertex:Mz,common:Cz,cube_uv_reflection_fragment:Rz,defaultnormal_vertex:Nz,displacementmap_pars_vertex:kz,displacementmap_vertex:Iz,emissivemap_fragment:Oz,emissivemap_pars_fragment:Lz,colorspace_fragment:Pz,colorspace_pars_fragment:Dz,envmap_fragment:Uz,envmap_common_pars_fragment:Fz,envmap_pars_fragment:Bz,envmap_pars_vertex:zz,envmap_physical_pars_fragment:Zz,envmap_vertex:Vz,fog_vertex:Hz,fog_pars_vertex:Gz,fog_fragment:Wz,fog_pars_fragment:jz,gradientmap_pars_fragment:$z,lightmap_pars_fragment:qz,lights_lambert_fragment:Xz,lights_lambert_pars_fragment:Kz,lights_pars_begin:Yz,lights_toon_fragment:Jz,lights_toon_pars_fragment:Qz,lights_phong_fragment:e8,lights_phong_pars_fragment:t8,lights_physical_fragment:n8,lights_physical_pars_fragment:r8,lights_fragment_begin:i8,lights_fragment_maps:s8,lights_fragment_end:o8,logdepthbuf_fragment:a8,logdepthbuf_pars_fragment:l8,logdepthbuf_pars_vertex:c8,logdepthbuf_vertex:u8,map_fragment:h8,map_pars_fragment:f8,map_particle_fragment:d8,map_particle_pars_fragment:p8,metalnessmap_fragment:m8,metalnessmap_pars_fragment:g8,morphinstance_vertex:_8,morphcolor_vertex:v8,morphnormal_vertex:y8,morphtarget_pars_vertex:x8,morphtarget_vertex:S8,normal_fragment_begin:E8,normal_fragment_maps:w8,normal_pars_fragment:T8,normal_pars_vertex:b8,normal_vertex:A8,normalmap_pars_fragment:M8,clearcoat_normal_fragment_begin:C8,clearcoat_normal_fragment_maps:R8,clearcoat_pars_fragment:N8,iridescence_pars_fragment:k8,opaque_fragment:I8,packing:O8,premultiplied_alpha_fragment:L8,project_vertex:P8,dithering_fragment:D8,dithering_pars_fragment:U8,roughnessmap_fragment:F8,roughnessmap_pars_fragment:B8,shadowmap_pars_fragment:z8,shadowmap_pars_vertex:V8,shadowmap_vertex:H8,shadowmask_pars_fragment:G8,skinbase_vertex:W8,skinning_pars_vertex:j8,skinning_vertex:$8,skinnormal_vertex:q8,specularmap_fragment:X8,specularmap_pars_fragment:K8,tonemapping_fragment:Y8,tonemapping_pars_fragment:Z8,transmission_fragment:J8,transmission_pars_fragment:Q8,uv_pars_fragment:e6,uv_pars_vertex:t6,uv_vertex:n6,worldpos_vertex:r6,background_vert:i6,background_frag:s6,backgroundCube_vert:o6,backgroundCube_frag:a6,cube_vert:l6,cube_frag:c6,depth_vert:u6,depth_frag:h6,distanceRGBA_vert:f6,distanceRGBA_frag:d6,equirect_vert:p6,equirect_frag:m6,linedashed_vert:g6,linedashed_frag:_6,meshbasic_vert:v6,meshbasic_frag:y6,meshlambert_vert:x6,meshlambert_frag:S6,meshmatcap_vert:E6,meshmatcap_frag:w6,meshnormal_vert:T6,meshnormal_frag:b6,meshphong_vert:A6,meshphong_frag:M6,meshphysical_vert:C6,meshphysical_frag:R6,meshtoon_vert:N6,meshtoon_frag:k6,points_vert:I6,points_frag:O6,shadow_vert:L6,shadow_frag:P6,sprite_vert:D6,sprite_frag:U6},Xe={common:{diffuse:{value:new cn(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Dt},alphaMap:{value:null},alphaMapTransform:{value:new Dt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Dt}},envmap:{envMap:{value:null},envMapRotation:{value:new Dt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Dt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Dt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Dt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Dt},normalScale:{value:new St(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Dt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Dt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Dt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Dt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new cn(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new cn(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Dt},alphaTest:{value:0},uvTransform:{value:new Dt}},sprite:{diffuse:{value:new cn(16777215)},opacity:{value:1},center:{value:new St(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Dt},alphaMap:{value:null},alphaMapTransform:{value:new Dt},alphaTest:{value:0}}},ua={basic:{uniforms:ki([Xe.common,Xe.specularmap,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.fog]),vertexShader:Ft.meshbasic_vert,fragmentShader:Ft.meshbasic_frag},lambert:{uniforms:ki([Xe.common,Xe.specularmap,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.fog,Xe.lights,{emissive:{value:new cn(0)}}]),vertexShader:Ft.meshlambert_vert,fragmentShader:Ft.meshlambert_frag},phong:{uniforms:ki([Xe.common,Xe.specularmap,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.fog,Xe.lights,{emissive:{value:new cn(0)},specular:{value:new cn(1118481)},shininess:{value:30}}]),vertexShader:Ft.meshphong_vert,fragmentShader:Ft.meshphong_frag},standard:{uniforms:ki([Xe.common,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.roughnessmap,Xe.metalnessmap,Xe.fog,Xe.lights,{emissive:{value:new cn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ft.meshphysical_vert,fragmentShader:Ft.meshphysical_frag},toon:{uniforms:ki([Xe.common,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.gradientmap,Xe.fog,Xe.lights,{emissive:{value:new cn(0)}}]),vertexShader:Ft.meshtoon_vert,fragmentShader:Ft.meshtoon_frag},matcap:{uniforms:ki([Xe.common,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.fog,{matcap:{value:null}}]),vertexShader:Ft.meshmatcap_vert,fragmentShader:Ft.meshmatcap_frag},points:{uniforms:ki([Xe.points,Xe.fog]),vertexShader:Ft.points_vert,fragmentShader:Ft.points_frag},dashed:{uniforms:ki([Xe.common,Xe.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ft.linedashed_vert,fragmentShader:Ft.linedashed_frag},depth:{uniforms:ki([Xe.common,Xe.displacementmap]),vertexShader:Ft.depth_vert,fragmentShader:Ft.depth_frag},normal:{uniforms:ki([Xe.common,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,{opacity:{value:1}}]),vertexShader:Ft.meshnormal_vert,fragmentShader:Ft.meshnormal_frag},sprite:{uniforms:ki([Xe.sprite,Xe.fog]),vertexShader:Ft.sprite_vert,fragmentShader:Ft.sprite_frag},background:{uniforms:{uvTransform:{value:new Dt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ft.background_vert,fragmentShader:Ft.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Dt}},vertexShader:Ft.backgroundCube_vert,fragmentShader:Ft.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ft.cube_vert,fragmentShader:Ft.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ft.equirect_vert,fragmentShader:Ft.equirect_frag},distanceRGBA:{uniforms:ki([Xe.common,Xe.displacementmap,{referencePosition:{value:new xe},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ft.distanceRGBA_vert,fragmentShader:Ft.distanceRGBA_frag},shadow:{uniforms:ki([Xe.lights,Xe.fog,{color:{value:new cn(0)},opacity:{value:1}}]),vertexShader:Ft.shadow_vert,fragmentShader:Ft.shadow_frag}};ua.physical={uniforms:ki([ua.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Dt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Dt},clearcoatNormalScale:{value:new St(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Dt},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Dt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Dt},sheen:{value:0},sheenColor:{value:new cn(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Dt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Dt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Dt},transmissionSamplerSize:{value:new St},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Dt},attenuationDistance:{value:0},attenuationColor:{value:new cn(0)},specularColor:{value:new cn(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Dt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Dt},anisotropyVector:{value:new St},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Dt}}]),vertexShader:Ft.meshphysical_vert,fragmentShader:Ft.meshphysical_frag};const a0={r:0,b:0,g:0},uu=new Ml,F6=new ar;function B6(t,e,n,r,i,s,o){const a=new cn(0);let l=s===!0?0:1,c,u,h=null,p=0,m=null;function g(S){let E=S.isScene===!0?S.background:null;return E&&E.isTexture&&(E=(S.backgroundBlurriness>0?n:e).get(E)),E}function v(S){let E=!1;const T=g(S);T===null?_(a,l):T&&T.isColor&&(_(T,1),E=!0);const N=t.xr.getEnvironmentBlendMode();N==="additive"?r.buffers.color.setClear(0,0,0,1,o):N==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||E)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))}function y(S,E){const T=g(E);T&&(T.isCubeTexture||T.mapping===Av)?(u===void 0&&(u=new Ao(new Yp(1,1,1),new Hi({name:"BackgroundCubeMaterial",uniforms:If(ua.backgroundCube.uniforms),vertexShader:ua.backgroundCube.vertexShader,fragmentShader:ua.backgroundCube.fragmentShader,side:ni,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(N,R,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),uu.copy(E.backgroundRotation),uu.x*=-1,uu.y*=-1,uu.z*=-1,T.isCubeTexture&&T.isRenderTargetTexture===!1&&(uu.y*=-1,uu.z*=-1),u.material.uniforms.envMap.value=T,u.material.uniforms.flipEnvMap.value=T.isCubeTexture&&T.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=E.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(F6.makeRotationFromEuler(uu)),u.material.toneMapped=fn.getTransfer(T.colorSpace)!==bn,(h!==T||p!==T.version||m!==t.toneMapping)&&(u.material.needsUpdate=!0,h=T,p=T.version,m=t.toneMapping),u.layers.enableAll(),S.unshift(u,u.geometry,u.material,0,0,null)):T&&T.isTexture&&(c===void 0&&(c=new Ao(new Zp(2,2),new Hi({name:"BackgroundMaterial",uniforms:If(ua.background.uniforms),vertexShader:ua.background.vertexShader,fragmentShader:ua.background.fragmentShader,side:Al,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(c)),c.material.uniforms.t2D.value=T,c.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,c.material.toneMapped=fn.getTransfer(T.colorSpace)!==bn,T.matrixAutoUpdate===!0&&T.updateMatrix(),c.material.uniforms.uvTransform.value.copy(T.matrix),(h!==T||p!==T.version||m!==t.toneMapping)&&(c.material.needsUpdate=!0,h=T,p=T.version,m=t.toneMapping),c.layers.enableAll(),S.unshift(c,c.geometry,c.material,0,0,null))}function _(S,E){S.getRGB(a0,iO(t)),r.buffers.color.setClear(a0.r,a0.g,a0.b,E,o)}return{getClearColor:function(){return a},setClearColor:function(S,E=1){a.set(S),l=E,_(a,l)},getClearAlpha:function(){return l},setClearAlpha:function(S){l=S,_(a,l)},render:v,addToRenderList:y}}function z6(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),r={},i=p(null);let s=i,o=!1;function a(I,U,L,P,b){let H=!1;const V=h(P,L,U);s!==V&&(s=V,c(s.object)),H=m(I,P,L,b),H&&g(I,P,L,b),b!==null&&e.update(b,t.ELEMENT_ARRAY_BUFFER),(H||o)&&(o=!1,T(I,U,L,P),b!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.get(b).buffer))}function l(){return t.createVertexArray()}function c(I){return t.bindVertexArray(I)}function u(I){return t.deleteVertexArray(I)}function h(I,U,L){const P=L.wireframe===!0;let b=r[I.id];b===void 0&&(b={},r[I.id]=b);let H=b[U.id];H===void 0&&(H={},b[U.id]=H);let V=H[P];return V===void 0&&(V=p(l()),H[P]=V),V}function p(I){const U=[],L=[],P=[];for(let b=0;b=0){const K=b[z];let j=H[z];if(j===void 0&&(z==="instanceMatrix"&&I.instanceMatrix&&(j=I.instanceMatrix),z==="instanceColor"&&I.instanceColor&&(j=I.instanceColor)),K===void 0||K.attribute!==j||j&&K.data!==j.data)return!0;V++}return s.attributesNum!==V||s.index!==P}function g(I,U,L,P){const b={},H=U.attributes;let V=0;const B=L.getAttributes();for(const z in B)if(B[z].location>=0){let K=H[z];K===void 0&&(z==="instanceMatrix"&&I.instanceMatrix&&(K=I.instanceMatrix),z==="instanceColor"&&I.instanceColor&&(K=I.instanceColor));const j={};j.attribute=K,K&&K.data&&(j.data=K.data),b[z]=j,V++}s.attributes=b,s.attributesNum=V,s.index=P}function v(){const I=s.newAttributes;for(let U=0,L=I.length;U=0){let W=b[B];if(W===void 0&&(B==="instanceMatrix"&&I.instanceMatrix&&(W=I.instanceMatrix),B==="instanceColor"&&I.instanceColor&&(W=I.instanceColor)),W!==void 0){const K=W.normalized,j=W.itemSize,Y=e.get(W);if(Y===void 0)continue;const ge=Y.buffer,Q=Y.type,re=Y.bytesPerElement,we=Q===t.INT||Q===t.UNSIGNED_INT||W.gpuType===nT;if(W.isInterleavedBufferAttribute){const Ae=W.data,Ee=Ae.stride,Le=W.offset;if(Ae.isInstancedInterleavedBuffer){for(let Ve=0;Ve0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";C="mediump"}return C==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=n.precision!==void 0?n.precision:"highp";const u=l(c);u!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);const h=n.logarithmicDepthBuffer===!0,p=n.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),m=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),g=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=t.getParameter(t.MAX_TEXTURE_SIZE),y=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),_=t.getParameter(t.MAX_VERTEX_ATTRIBS),S=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),E=t.getParameter(t.MAX_VARYING_VECTORS),T=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),N=g>0,R=t.getParameter(t.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:o,textureTypeReadable:a,precision:c,logarithmicDepthBuffer:h,reverseDepthBuffer:p,maxTextures:m,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:y,maxAttributes:_,maxVertexUniforms:S,maxVaryings:E,maxFragmentUniforms:T,vertexTextures:N,maxSamples:R}}function G6(t){const e=this;let n=null,r=0,i=!1,s=!1;const o=new xo,a=new Dt,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(h,p){const m=h.length!==0||p||r!==0||i;return i=p,r=h.length,m},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,p){n=u(h,p,0)},this.setState=function(h,p,m){const g=h.clippingPlanes,v=h.clipIntersection,y=h.clipShadows,_=t.get(h);if(!i||g===null||g.length===0||s&&!y)s?u(null):c();else{const S=s?0:r,E=S*4;let T=_.clippingState||null;l.value=T,T=u(g,p,E,m);for(let N=0;N!==E;++N)T[N]=n[N];_.clippingState=T,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=S}};function c(){l.value!==n&&(l.value=n,l.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function u(h,p,m,g){const v=h!==null?h.length:0;let y=null;if(v!==0){if(y=l.value,g!==!0||y===null){const _=m+v*4,S=p.matrixWorldInverse;a.getNormalMatrix(S),(y===null||y.length<_)&&(y=new Float32Array(_));for(let E=0,T=m;E!==v;++E,T+=4)o.copy(h[E]).applyMatrix4(S,a),o.normal.toArray(y,T),y[T+3]=o.constant}l.value=y,l.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,y}}function W6(t){let e=new WeakMap;function n(o,a){return a===W1?o.mapping=Nf:a===j1&&(o.mapping=kf),o}function r(o){if(o&&o.isTexture){const a=o.mapping;if(a===W1||a===j1)if(e.has(o)){const l=e.get(o).texture;return n(l,o.mapping)}else{const l=o.image;if(l&&l.height>0){const c=new tz(l.height);return c.fromEquirectangularTexture(t,o),e.set(o,c),o.addEventListener("dispose",i),n(c.texture,o.mapping)}else return null}}return o}function i(o){const a=o.target;a.removeEventListener("dispose",i);const l=e.get(a);l!==void 0&&(e.delete(a),l.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}class kv extends Nv{constructor(e=-1,n=1,r=1,i=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=n,this.top=r,this.bottom=i,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,n,r,i,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),n=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=r-e,o=r+e,a=i+n,l=i-n;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,o=s+c*this.view.width,a-=u*this.view.offsetY,l=a-u*this.view.height}this.projectionMatrix.makeOrthographic(s,o,a,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.zoom=this.zoom,n.object.left=this.left,n.object.right=this.right,n.object.top=this.top,n.object.bottom=this.bottom,n.object.near=this.near,n.object.far=this.far,this.view!==null&&(n.object.view=Object.assign({},this.view)),n}}const af=4,nR=[.125,.215,.35,.446,.526,.582],bu=20,bS=new kv,rR=new cn;let AS=null,MS=0,CS=0,RS=!1;const xu=(1+Math.sqrt(5))/2,Gh=1/xu,iR=[new xe(-xu,Gh,0),new xe(xu,Gh,0),new xe(-Gh,0,xu),new xe(Gh,0,xu),new xe(0,xu,-Gh),new xe(0,xu,Gh),new xe(-1,1,-1),new xe(1,1,-1),new xe(-1,1,1),new xe(1,1,1)];class sR{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,n=0,r=.1,i=100){AS=this._renderer.getRenderTarget(),MS=this._renderer.getActiveCubeFace(),CS=this._renderer.getActiveMipmapLevel(),RS=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,r,i,s),n>0&&this._blur(s,0,0,n),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,n=null){return this._fromTexture(e,n)}fromCubemap(e,n=null){return this._fromTexture(e,n)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=lR(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=aR(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?E:0,E,E),u.setRenderTarget(i),v&&u.render(g,a),u.render(e,a)}g.geometry.dispose(),g.material.dispose(),u.toneMapping=p,u.autoClear=h,e.background=y}_textureToCubeUV(e,n){const r=this._renderer,i=e.mapping===Nf||e.mapping===kf;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=lR()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=aR());const s=i?this._cubemapMaterial:this._equirectMaterial,o=new Ao(this._lodPlanes[0],s),a=s.uniforms;a.envMap.value=e;const l=this._cubeSize;l0(n,0,0,3*l,2*l),r.setRenderTarget(n),r.render(o,bS)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;const i=this._lodPlanes.length;for(let s=1;sbu&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${bu}`);const _=[];let S=0;for(let C=0;CE-af?i-E+af:0),R=4*(this._cubeSize-T);l0(n,N,R,3*T,2*T),l.setRenderTarget(n),l.render(h,bS)}}function j6(t){const e=[],n=[],r=[];let i=t;const s=t-af+1+nR.length;for(let o=0;ot-af?l=nR[o-t+af-1]:o===0&&(l=0),r.push(l);const c=1/(a-2),u=-c,h=1+c,p=[u,u,h,u,h,h,u,u,h,h,u,h],m=6,g=6,v=3,y=2,_=1,S=new Float32Array(v*g*m),E=new Float32Array(y*g*m),T=new Float32Array(_*g*m);for(let R=0;R2?0:-1,M=[C,O,0,C+2/3,O,0,C+2/3,O+1,0,C,O,0,C+2/3,O+1,0,C,O+1,0];S.set(M,v*g*R),E.set(p,y*g*R);const I=[R,R,R,R,R,R];T.set(I,_*g*R)}const N=new Bo;N.setAttribute("position",new Jn(S,v)),N.setAttribute("uv",new Jn(E,y)),N.setAttribute("faceIndex",new Jn(T,_)),e.push(N),i>af&&i--}return{lodPlanes:e,sizeLods:n,sigmas:r}}function oR(t,e,n){const r=new Ps(t,e,n);return r.texture.mapping=Av,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function l0(t,e,n,r,i){t.viewport.set(e,n,r,i),t.scissor.set(e,n,r,i)}function $6(t,e,n){const r=new Float32Array(bu),i=new xe(0,1,0);return new Hi({name:"SphericalGaussianBlur",defines:{n:bu,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:uT(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:Ro,depthTest:!1,depthWrite:!1})}function aR(){return new Hi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:uT(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:Ro,depthTest:!1,depthWrite:!1})}function lR(){return new Hi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:uT(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:Ro,depthTest:!1,depthWrite:!1})}function uT(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function q6(t){let e=new WeakMap,n=null;function r(a){if(a&&a.isTexture){const l=a.mapping,c=l===W1||l===j1,u=l===Nf||l===kf;if(c||u){let h=e.get(a);const p=h!==void 0?h.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==p)return n===null&&(n=new sR(t)),h=c?n.fromEquirectangular(a,h):n.fromCubemap(a,h),h.texture.pmremVersion=a.pmremVersion,e.set(a,h),h.texture;if(h!==void 0)return h.texture;{const m=a.image;return c&&m&&m.height>0||u&&m&&i(m)?(n===null&&(n=new sR(t)),h=c?n.fromEquirectangular(a):n.fromCubemap(a),h.texture.pmremVersion=a.pmremVersion,e.set(a,h),a.addEventListener("dispose",s),h.texture):null}}}return a}function i(a){let l=0;const c=6;for(let u=0;ue.maxTextureSize&&(R=Math.ceil(N/e.maxTextureSize),N=e.maxTextureSize);const C=new Float32Array(N*R*4*h),O=new eO(C,N,R,h);O.type=ga,O.needsUpdate=!0;const M=T*4;for(let U=0;U0)return t;const i=e*n;let s=uR[i];if(s===void 0&&(s=new Float32Array(i),uR[i]=s),e!==0){r.toArray(s,0);for(let o=1,a=0;o!==e;++o)a+=n,t[o].toArray(s,a)}return s}function zr(t,e){if(t.length!==e.length)return!1;for(let n=0,r=t.length;n":" "} ${a}: ${n[o]}`)}return r.join(` +`)}const _R=new Dt;function qV(t){fn._getMatrix(_R,fn.workingColorSpace,t);const e=`mat3( ${_R.elements.map(n=>n.toFixed(4))} )`;switch(fn.getTransfer(t)){case Cv:return[e,"LinearTransferOETF"];case bn:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",t),[e,"LinearTransferOETF"]}}function vR(t,e,n){const r=t.getShaderParameter(e,t.COMPILE_STATUS),i=t.getShaderInfoLog(e).trim();if(r&&i==="")return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const o=parseInt(s[1]);return n.toUpperCase()+` + +`+i+` + +`+$V(t.getShaderSource(e),o)}else return i}function XV(t,e){const n=qV(e);return[`vec4 ${t}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(` +`)}function KV(t,e){let n;switch(e){case JB:n="Linear";break;case QB:n="Reinhard";break;case e5:n="Cineon";break;case FI:n="ACESFilmic";break;case n5:n="AgX";break;case r5:n="Neutral";break;case t5:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const c0=new xe;function YV(){fn.getLuminanceCoefficients(c0);const t=c0.x.toFixed(4),e=c0.y.toFixed(4),n=c0.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${t}, ${e}, ${n} );`," return dot( weights, rgb );","}"].join(` +`)}function ZV(t){return[t.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",t.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Jd).join(` +`)}function JV(t){const e=[];for(const n in t){const r=t[n];r!==!1&&e.push("#define "+n+" "+r)}return e.join(` +`)}function QV(t,e){const n={},r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function xE(t){return t.replace(eH,nH)}const tH=new Map;function nH(t,e){let n=Ft[e];if(n===void 0){const r=tH.get(e);if(r!==void 0)n=Ft[r],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return xE(n)}const rH=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function SR(t){return t.replace(rH,iH)}function iH(t,e,n,r){let i="";for(let s=parseInt(e);s0&&(y+=` +`),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(Jd).join(` +`),_.length>0&&(_+=` +`)):(y=[ER(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&n.flatShading===!1?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(Jd).join(` +`),_=[ER(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+c:"",n.envMap?"#define "+u:"",n.envMap?"#define "+h:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==va?"#define TONE_MAPPING":"",n.toneMapping!==va?Ft.tonemapping_pars_fragment:"",n.toneMapping!==va?KV("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Ft.colorspace_pars_fragment,XV("linearToOutputTexel",n.outputColorSpace),YV(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",` +`].filter(Jd).join(` +`)),o=xE(o),o=yR(o,n),o=xR(o,n),a=xE(a),a=yR(a,n),a=xR(a,n),o=SR(o),a=SR(a),n.isRawShaderMaterial!==!0&&(S=`#version 300 es +`,y=[m,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+y,_=["#define varying in",n.glslVersion===LC?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===LC?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+_);const E=S+y+o,T=S+_+a,N=gR(i,i.VERTEX_SHADER,E),R=gR(i,i.FRAGMENT_SHADER,T);i.attachShader(v,N),i.attachShader(v,R),n.index0AttributeName!==void 0?i.bindAttribLocation(v,0,n.index0AttributeName):n.morphTargets===!0&&i.bindAttribLocation(v,0,"position"),i.linkProgram(v);function C(U){if(t.debug.checkShaderErrors){const L=i.getProgramInfoLog(v).trim(),P=i.getShaderInfoLog(N).trim(),b=i.getShaderInfoLog(R).trim();let H=!0,V=!0;if(i.getProgramParameter(v,i.LINK_STATUS)===!1)if(H=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(i,v,N,R);else{const B=vR(i,N,"vertex"),z=vR(i,R,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(v,i.VALIDATE_STATUS)+` + +Material Name: `+U.name+` +Material Type: `+U.type+` + +Program Info Log: `+L+` +`+B+` +`+z)}else L!==""?console.warn("THREE.WebGLProgram: Program Info Log:",L):(P===""||b==="")&&(V=!1);V&&(U.diagnostics={runnable:H,programLog:L,vertexShader:{log:P,prefix:y},fragmentShader:{log:b,prefix:_}})}i.deleteShader(N),i.deleteShader(R),O=new J0(i,v),M=QV(i,v)}let O;this.getUniforms=function(){return O===void 0&&C(this),O};let M;this.getAttributes=function(){return M===void 0&&C(this),M};let I=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return I===!1&&(I=i.getProgramParameter(v,WV)),I},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=jV++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=N,this.fragmentShader=R,this}let hH=0;class fH{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(n),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){const n=this.materialCache.get(e);for(const r of n)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const n=this.materialCache;let r=n.get(e);return r===void 0&&(r=new Set,n.set(e,r)),r}_getShaderStage(e){const n=this.shaderCache;let r=n.get(e);return r===void 0&&(r=new dH(e),n.set(e,r)),r}}class dH{constructor(e){this.id=hH++,this.code=e,this.usedTimes=0}}function pH(t,e,n,r,i,s,o){const a=new yf,l=new fH,c=new Set,u=[],h=i.logarithmicDepthBuffer,p=i.vertexTextures;let m=i.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(M){return c.add(M),M===0?"uv":`uv${M}`}function y(M,I,U,L,P){const b=L.fog,H=P.geometry,V=M.isMeshStandardMaterial?L.environment:null,B=(M.isMeshStandardMaterial?n:e).get(M.envMap||V),z=B&&B.mapping===Av?B.image.height:null,W=g[M.type];M.precision!==null&&(m=i.getMaxPrecision(M.precision),m!==M.precision&&console.warn("THREE.WebGLProgram.getParameters:",M.precision,"not supported, using",m,"instead."));const K=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,j=K!==void 0?K.length:0;let Y=0;H.morphAttributes.position!==void 0&&(Y=1),H.morphAttributes.normal!==void 0&&(Y=2),H.morphAttributes.color!==void 0&&(Y=3);let ge,Q,re,we;if(W){const dn=ua[W];ge=dn.vertexShader,Q=dn.fragmentShader}else ge=M.vertexShader,Q=M.fragmentShader,l.update(M),re=l.getVertexShaderID(M),we=l.getFragmentShaderID(M);const Ae=t.getRenderTarget(),Ee=t.state.buffers.depth.getReversed(),Le=P.isInstancedMesh===!0,Ve=P.isBatchedMesh===!0,qe=!!M.map,it=!!M.matcap,De=!!B,A=!!M.aoMap,ie=!!M.lightMap,te=!!M.bumpMap,X=!!M.normalMap,$=!!M.displacementMap,ne=!!M.emissiveMap,ae=!!M.metalnessMap,G=!!M.roughnessMap,D=M.anisotropy>0,ee=M.clearcoat>0,he=M.dispersion>0,le=M.iridescence>0,_e=M.sheen>0,ze=M.transmission>0,Oe=D&&!!M.anisotropyMap,Ge=ee&&!!M.clearcoatMap,Lt=ee&&!!M.clearcoatNormalMap,Pe=ee&&!!M.clearcoatRoughnessMap,nt=le&&!!M.iridescenceMap,et=le&&!!M.iridescenceThicknessMap,yt=_e&&!!M.sheenColorMap,rt=_e&&!!M.sheenRoughnessMap,Ct=!!M.specularMap,Rt=!!M.specularColorMap,Sn=!!M.specularIntensityMap,ce=ze&&!!M.transmissionMap,je=ze&&!!M.thicknessMap,Ce=!!M.gradientMap,ke=!!M.alphaMap,$e=M.alphaTest>0,Je=!!M.alphaHash,Nt=!!M.extensions;let Gn=va;M.toneMapped&&(Ae===null||Ae.isXRRenderTarget===!0)&&(Gn=t.toneMapping);const Rr={shaderID:W,shaderType:M.type,shaderName:M.name,vertexShader:ge,fragmentShader:Q,defines:M.defines,customVertexShaderID:re,customFragmentShaderID:we,isRawShaderMaterial:M.isRawShaderMaterial===!0,glslVersion:M.glslVersion,precision:m,batching:Ve,batchingColor:Ve&&P._colorsTexture!==null,instancing:Le,instancingColor:Le&&P.instanceColor!==null,instancingMorph:Le&&P.morphTexture!==null,supportsVertexTextures:p,outputColorSpace:Ae===null?t.outputColorSpace:Ae.isXRRenderTarget===!0?Ae.texture.colorSpace:Hc,alphaToCoverage:!!M.alphaToCoverage,map:qe,matcap:it,envMap:De,envMapMode:De&&B.mapping,envMapCubeUVHeight:z,aoMap:A,lightMap:ie,bumpMap:te,normalMap:X,displacementMap:p&&$,emissiveMap:ne,normalMapObjectSpace:X&&M.normalMapType===o5,normalMapTangentSpace:X&&M.normalMapType===YI,metalnessMap:ae,roughnessMap:G,anisotropy:D,anisotropyMap:Oe,clearcoat:ee,clearcoatMap:Ge,clearcoatNormalMap:Lt,clearcoatRoughnessMap:Pe,dispersion:he,iridescence:le,iridescenceMap:nt,iridescenceThicknessMap:et,sheen:_e,sheenColorMap:yt,sheenRoughnessMap:rt,specularMap:Ct,specularColorMap:Rt,specularIntensityMap:Sn,transmission:ze,transmissionMap:ce,thicknessMap:je,gradientMap:Ce,opaque:M.transparent===!1&&M.blending===gf&&M.alphaToCoverage===!1,alphaMap:ke,alphaTest:$e,alphaHash:Je,combine:M.combine,mapUv:qe&&v(M.map.channel),aoMapUv:A&&v(M.aoMap.channel),lightMapUv:ie&&v(M.lightMap.channel),bumpMapUv:te&&v(M.bumpMap.channel),normalMapUv:X&&v(M.normalMap.channel),displacementMapUv:$&&v(M.displacementMap.channel),emissiveMapUv:ne&&v(M.emissiveMap.channel),metalnessMapUv:ae&&v(M.metalnessMap.channel),roughnessMapUv:G&&v(M.roughnessMap.channel),anisotropyMapUv:Oe&&v(M.anisotropyMap.channel),clearcoatMapUv:Ge&&v(M.clearcoatMap.channel),clearcoatNormalMapUv:Lt&&v(M.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Pe&&v(M.clearcoatRoughnessMap.channel),iridescenceMapUv:nt&&v(M.iridescenceMap.channel),iridescenceThicknessMapUv:et&&v(M.iridescenceThicknessMap.channel),sheenColorMapUv:yt&&v(M.sheenColorMap.channel),sheenRoughnessMapUv:rt&&v(M.sheenRoughnessMap.channel),specularMapUv:Ct&&v(M.specularMap.channel),specularColorMapUv:Rt&&v(M.specularColorMap.channel),specularIntensityMapUv:Sn&&v(M.specularIntensityMap.channel),transmissionMapUv:ce&&v(M.transmissionMap.channel),thicknessMapUv:je&&v(M.thicknessMap.channel),alphaMapUv:ke&&v(M.alphaMap.channel),vertexTangents:!!H.attributes.tangent&&(X||D),vertexColors:M.vertexColors,vertexAlphas:M.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,pointsUvs:P.isPoints===!0&&!!H.attributes.uv&&(qe||ke),fog:!!b,useFog:M.fog===!0,fogExp2:!!b&&b.isFogExp2,flatShading:M.flatShading===!0,sizeAttenuation:M.sizeAttenuation===!0,logarithmicDepthBuffer:h,reverseDepthBuffer:Ee,skinning:P.isSkinnedMesh===!0,morphTargets:H.morphAttributes.position!==void 0,morphNormals:H.morphAttributes.normal!==void 0,morphColors:H.morphAttributes.color!==void 0,morphTargetsCount:j,morphTextureStride:Y,numDirLights:I.directional.length,numPointLights:I.point.length,numSpotLights:I.spot.length,numSpotLightMaps:I.spotLightMap.length,numRectAreaLights:I.rectArea.length,numHemiLights:I.hemi.length,numDirLightShadows:I.directionalShadowMap.length,numPointLightShadows:I.pointShadowMap.length,numSpotLightShadows:I.spotShadowMap.length,numSpotLightShadowsWithMaps:I.numSpotLightShadowsWithMaps,numLightProbes:I.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:M.dithering,shadowMapEnabled:t.shadowMap.enabled&&U.length>0,shadowMapType:t.shadowMap.type,toneMapping:Gn,decodeVideoTexture:qe&&M.map.isVideoTexture===!0&&fn.getTransfer(M.map.colorSpace)===bn,decodeVideoTextureEmissive:ne&&M.emissiveMap.isVideoTexture===!0&&fn.getTransfer(M.emissiveMap.colorSpace)===bn,premultipliedAlpha:M.premultipliedAlpha,doubleSided:M.side===Cs,flipSided:M.side===ni,useDepthPacking:M.depthPacking>=0,depthPacking:M.depthPacking||0,index0AttributeName:M.index0AttributeName,extensionClipCullDistance:Nt&&M.extensions.clipCullDistance===!0&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Nt&&M.extensions.multiDraw===!0||Ve)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:M.customProgramCacheKey()};return Rr.vertexUv1s=c.has(1),Rr.vertexUv2s=c.has(2),Rr.vertexUv3s=c.has(3),c.clear(),Rr}function _(M){const I=[];if(M.shaderID?I.push(M.shaderID):(I.push(M.customVertexShaderID),I.push(M.customFragmentShaderID)),M.defines!==void 0)for(const U in M.defines)I.push(U),I.push(M.defines[U]);return M.isRawShaderMaterial===!1&&(S(I,M),E(I,M),I.push(t.outputColorSpace)),I.push(M.customProgramCacheKey),I.join()}function S(M,I){M.push(I.precision),M.push(I.outputColorSpace),M.push(I.envMapMode),M.push(I.envMapCubeUVHeight),M.push(I.mapUv),M.push(I.alphaMapUv),M.push(I.lightMapUv),M.push(I.aoMapUv),M.push(I.bumpMapUv),M.push(I.normalMapUv),M.push(I.displacementMapUv),M.push(I.emissiveMapUv),M.push(I.metalnessMapUv),M.push(I.roughnessMapUv),M.push(I.anisotropyMapUv),M.push(I.clearcoatMapUv),M.push(I.clearcoatNormalMapUv),M.push(I.clearcoatRoughnessMapUv),M.push(I.iridescenceMapUv),M.push(I.iridescenceThicknessMapUv),M.push(I.sheenColorMapUv),M.push(I.sheenRoughnessMapUv),M.push(I.specularMapUv),M.push(I.specularColorMapUv),M.push(I.specularIntensityMapUv),M.push(I.transmissionMapUv),M.push(I.thicknessMapUv),M.push(I.combine),M.push(I.fogExp2),M.push(I.sizeAttenuation),M.push(I.morphTargetsCount),M.push(I.morphAttributeCount),M.push(I.numDirLights),M.push(I.numPointLights),M.push(I.numSpotLights),M.push(I.numSpotLightMaps),M.push(I.numHemiLights),M.push(I.numRectAreaLights),M.push(I.numDirLightShadows),M.push(I.numPointLightShadows),M.push(I.numSpotLightShadows),M.push(I.numSpotLightShadowsWithMaps),M.push(I.numLightProbes),M.push(I.shadowMapType),M.push(I.toneMapping),M.push(I.numClippingPlanes),M.push(I.numClipIntersection),M.push(I.depthPacking)}function E(M,I){a.disableAll(),I.supportsVertexTextures&&a.enable(0),I.instancing&&a.enable(1),I.instancingColor&&a.enable(2),I.instancingMorph&&a.enable(3),I.matcap&&a.enable(4),I.envMap&&a.enable(5),I.normalMapObjectSpace&&a.enable(6),I.normalMapTangentSpace&&a.enable(7),I.clearcoat&&a.enable(8),I.iridescence&&a.enable(9),I.alphaTest&&a.enable(10),I.vertexColors&&a.enable(11),I.vertexAlphas&&a.enable(12),I.vertexUv1s&&a.enable(13),I.vertexUv2s&&a.enable(14),I.vertexUv3s&&a.enable(15),I.vertexTangents&&a.enable(16),I.anisotropy&&a.enable(17),I.alphaHash&&a.enable(18),I.batching&&a.enable(19),I.dispersion&&a.enable(20),I.batchingColor&&a.enable(21),M.push(a.mask),a.disableAll(),I.fog&&a.enable(0),I.useFog&&a.enable(1),I.flatShading&&a.enable(2),I.logarithmicDepthBuffer&&a.enable(3),I.reverseDepthBuffer&&a.enable(4),I.skinning&&a.enable(5),I.morphTargets&&a.enable(6),I.morphNormals&&a.enable(7),I.morphColors&&a.enable(8),I.premultipliedAlpha&&a.enable(9),I.shadowMapEnabled&&a.enable(10),I.doubleSided&&a.enable(11),I.flipSided&&a.enable(12),I.useDepthPacking&&a.enable(13),I.dithering&&a.enable(14),I.transmission&&a.enable(15),I.sheen&&a.enable(16),I.opaque&&a.enable(17),I.pointsUvs&&a.enable(18),I.decodeVideoTexture&&a.enable(19),I.decodeVideoTextureEmissive&&a.enable(20),I.alphaToCoverage&&a.enable(21),M.push(a.mask)}function T(M){const I=g[M.type];let U;if(I){const L=ua[I];U=Z5.clone(L.uniforms)}else U=M.uniforms;return U}function N(M,I){let U;for(let L=0,P=u.length;L0?r.push(_):m.transparent===!0?i.push(_):n.push(_)}function l(h,p,m,g,v,y){const _=o(h,p,m,g,v,y);m.transmission>0?r.unshift(_):m.transparent===!0?i.unshift(_):n.unshift(_)}function c(h,p){n.length>1&&n.sort(h||gH),r.length>1&&r.sort(p||wR),i.length>1&&i.sort(p||wR)}function u(){for(let h=e,p=t.length;h=s.length?(o=new TR,s.push(o)):o=s[i],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function vH(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new xe,color:new cn};break;case"SpotLight":n={position:new xe,direction:new xe,color:new cn,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new xe,color:new cn,distance:0,decay:0};break;case"HemisphereLight":n={direction:new xe,skyColor:new cn,groundColor:new cn};break;case"RectAreaLight":n={color:new cn,position:new xe,halfWidth:new xe,halfHeight:new xe};break}return t[e.id]=n,n}}}function yH(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new St};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new St};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new St,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let xH=0;function SH(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function EH(t){const e=new vH,n=yH(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)r.probe.push(new xe);const i=new xe,s=new ar,o=new ar;function a(c){let u=0,h=0,p=0;for(let M=0;M<9;M++)r.probe[M].set(0,0,0);let m=0,g=0,v=0,y=0,_=0,S=0,E=0,T=0,N=0,R=0,C=0;c.sort(SH);for(let M=0,I=c.length;M0&&(t.has("OES_texture_float_linear")===!0?(r.rectAreaLTC1=Xe.LTC_FLOAT_1,r.rectAreaLTC2=Xe.LTC_FLOAT_2):(r.rectAreaLTC1=Xe.LTC_HALF_1,r.rectAreaLTC2=Xe.LTC_HALF_2)),r.ambient[0]=u,r.ambient[1]=h,r.ambient[2]=p;const O=r.hash;(O.directionalLength!==m||O.pointLength!==g||O.spotLength!==v||O.rectAreaLength!==y||O.hemiLength!==_||O.numDirectionalShadows!==S||O.numPointShadows!==E||O.numSpotShadows!==T||O.numSpotMaps!==N||O.numLightProbes!==C)&&(r.directional.length=m,r.spot.length=v,r.rectArea.length=y,r.point.length=g,r.hemi.length=_,r.directionalShadow.length=S,r.directionalShadowMap.length=S,r.pointShadow.length=E,r.pointShadowMap.length=E,r.spotShadow.length=T,r.spotShadowMap.length=T,r.directionalShadowMatrix.length=S,r.pointShadowMatrix.length=E,r.spotLightMatrix.length=T+N-R,r.spotLightMap.length=N,r.numSpotLightShadowsWithMaps=R,r.numLightProbes=C,O.directionalLength=m,O.pointLength=g,O.spotLength=v,O.rectAreaLength=y,O.hemiLength=_,O.numDirectionalShadows=S,O.numPointShadows=E,O.numSpotShadows=T,O.numSpotMaps=N,O.numLightProbes=C,r.version=xH++)}function l(c,u){let h=0,p=0,m=0,g=0,v=0;const y=u.matrixWorldInverse;for(let _=0,S=c.length;_=o.length?(a=new bR(t),o.push(a)):a=o[s],a}function r(){e=new WeakMap}return{get:n,dispose:r}}class TH extends Ul{static get type(){return"MeshDepthMaterial"}constructor(e){super(),this.isMeshDepthMaterial=!0,this.depthPacking=th,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class bH extends Ul{static get type(){return"MeshDistanceMaterial"}constructor(e){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const AH=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,MH=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function CH(t,e,n){let r=new oO;const i=new St,s=new St,o=new gr,a=new TH({depthPacking:s5}),l=new bH,c={},u=n.maxTextureSize,h={[Al]:ni,[ni]:Al,[Cs]:Cs},p=new Hi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new St},radius:{value:4}},vertexShader:AH,fragmentShader:MH}),m=p.clone();m.defines.HORIZONTAL_PASS=1;const g=new Bo;g.setAttribute("position",new Jn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Ao(g,p),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=tT;let _=this.type;this.render=function(R,C,O){if(y.enabled===!1||y.autoUpdate===!1&&y.needsUpdate===!1||R.length===0)return;const M=t.getRenderTarget(),I=t.getActiveCubeFace(),U=t.getActiveMipmapLevel(),L=t.state;L.setBlending(Ro),L.buffers.color.setClear(1,1,1,1),L.buffers.depth.setTest(!0),L.setScissorTest(!1);const P=_!==la&&this.type===la,b=_===la&&this.type!==la;for(let H=0,V=R.length;Hu||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/W.x),i.x=s.x*W.x,z.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/W.y),i.y=s.y*W.y,z.mapSize.y=s.y)),z.map===null||P===!0||b===!0){const j=this.type!==la?{minFilter:vr,magFilter:vr}:{};z.map!==null&&z.map.dispose(),z.map=new Ps(i.x,i.y,j),z.map.texture.name=B.name+".shadowMap",z.camera.updateProjectionMatrix()}t.setRenderTarget(z.map),t.clear();const K=z.getViewportCount();for(let j=0;j0||C.map&&C.alphaTest>0){const L=I.uuid,P=C.uuid;let b=c[L];b===void 0&&(b={},c[L]=b);let H=b[P];H===void 0&&(H=I.clone(),b[P]=H,C.addEventListener("dispose",N)),I=H}if(I.visible=C.visible,I.wireframe=C.wireframe,M===la?I.side=C.shadowSide!==null?C.shadowSide:C.side:I.side=C.shadowSide!==null?C.shadowSide:h[C.side],I.alphaMap=C.alphaMap,I.alphaTest=C.alphaTest,I.map=C.map,I.clipShadows=C.clipShadows,I.clippingPlanes=C.clippingPlanes,I.clipIntersection=C.clipIntersection,I.displacementMap=C.displacementMap,I.displacementScale=C.displacementScale,I.displacementBias=C.displacementBias,I.wireframeLinewidth=C.wireframeLinewidth,I.linewidth=C.linewidth,O.isPointLight===!0&&I.isMeshDistanceMaterial===!0){const L=t.properties.get(I);L.light=O}return I}function T(R,C,O,M,I){if(R.visible===!1)return;if(R.layers.test(C.layers)&&(R.isMesh||R.isLine||R.isPoints)&&(R.castShadow||R.receiveShadow&&I===la)&&(!R.frustumCulled||r.intersectsObject(R))){R.modelViewMatrix.multiplyMatrices(O.matrixWorldInverse,R.matrixWorld);const P=e.update(R),b=R.material;if(Array.isArray(b)){const H=P.groups;for(let V=0,B=H.length;V=1):z.indexOf("OpenGL ES")!==-1&&(B=parseFloat(/^OpenGL ES (\d)/.exec(z)[1]),V=B>=2);let W=null,K={};const j=t.getParameter(t.SCISSOR_BOX),Y=t.getParameter(t.VIEWPORT),ge=new gr().fromArray(j),Q=new gr().fromArray(Y);function re(ce,je,Ce,ke){const $e=new Uint8Array(4),Je=t.createTexture();t.bindTexture(ce,Je),t.texParameteri(ce,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(ce,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let Nt=0;Nt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new St,u=new WeakMap;let h;const p=new WeakMap;let m=!1;try{m=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(G,D){return m?new OffscreenCanvas(G,D):Ep("canvas")}function v(G,D,ee){let he=1;const le=ae(G);if((le.width>ee||le.height>ee)&&(he=ee/Math.max(le.width,le.height)),he<1)if(typeof HTMLImageElement<"u"&&G instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&G instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&G instanceof ImageBitmap||typeof VideoFrame<"u"&&G instanceof VideoFrame){const _e=Math.floor(he*le.width),ze=Math.floor(he*le.height);h===void 0&&(h=g(_e,ze));const Oe=D?g(_e,ze):h;return Oe.width=_e,Oe.height=ze,Oe.getContext("2d").drawImage(G,0,0,_e,ze),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+le.width+"x"+le.height+") to ("+_e+"x"+ze+")."),Oe}else return"data"in G&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+le.width+"x"+le.height+")."),G;return G}function y(G){return G.generateMipmaps}function _(G){t.generateMipmap(G)}function S(G){return G.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:G.isWebGL3DRenderTarget?t.TEXTURE_3D:G.isWebGLArrayRenderTarget||G.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function E(G,D,ee,he,le=!1){if(G!==null){if(t[G]!==void 0)return t[G];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+G+"'")}let _e=D;if(D===t.RED&&(ee===t.FLOAT&&(_e=t.R32F),ee===t.HALF_FLOAT&&(_e=t.R16F),ee===t.UNSIGNED_BYTE&&(_e=t.R8)),D===t.RED_INTEGER&&(ee===t.UNSIGNED_BYTE&&(_e=t.R8UI),ee===t.UNSIGNED_SHORT&&(_e=t.R16UI),ee===t.UNSIGNED_INT&&(_e=t.R32UI),ee===t.BYTE&&(_e=t.R8I),ee===t.SHORT&&(_e=t.R16I),ee===t.INT&&(_e=t.R32I)),D===t.RG&&(ee===t.FLOAT&&(_e=t.RG32F),ee===t.HALF_FLOAT&&(_e=t.RG16F),ee===t.UNSIGNED_BYTE&&(_e=t.RG8)),D===t.RG_INTEGER&&(ee===t.UNSIGNED_BYTE&&(_e=t.RG8UI),ee===t.UNSIGNED_SHORT&&(_e=t.RG16UI),ee===t.UNSIGNED_INT&&(_e=t.RG32UI),ee===t.BYTE&&(_e=t.RG8I),ee===t.SHORT&&(_e=t.RG16I),ee===t.INT&&(_e=t.RG32I)),D===t.RGB_INTEGER&&(ee===t.UNSIGNED_BYTE&&(_e=t.RGB8UI),ee===t.UNSIGNED_SHORT&&(_e=t.RGB16UI),ee===t.UNSIGNED_INT&&(_e=t.RGB32UI),ee===t.BYTE&&(_e=t.RGB8I),ee===t.SHORT&&(_e=t.RGB16I),ee===t.INT&&(_e=t.RGB32I)),D===t.RGBA_INTEGER&&(ee===t.UNSIGNED_BYTE&&(_e=t.RGBA8UI),ee===t.UNSIGNED_SHORT&&(_e=t.RGBA16UI),ee===t.UNSIGNED_INT&&(_e=t.RGBA32UI),ee===t.BYTE&&(_e=t.RGBA8I),ee===t.SHORT&&(_e=t.RGBA16I),ee===t.INT&&(_e=t.RGBA32I)),D===t.RGB&&ee===t.UNSIGNED_INT_5_9_9_9_REV&&(_e=t.RGB9_E5),D===t.RGBA){const ze=le?Cv:fn.getTransfer(he);ee===t.FLOAT&&(_e=t.RGBA32F),ee===t.HALF_FLOAT&&(_e=t.RGBA16F),ee===t.UNSIGNED_BYTE&&(_e=ze===bn?t.SRGB8_ALPHA8:t.RGBA8),ee===t.UNSIGNED_SHORT_4_4_4_4&&(_e=t.RGBA4),ee===t.UNSIGNED_SHORT_5_5_5_1&&(_e=t.RGB5_A1)}return(_e===t.R16F||_e===t.R32F||_e===t.RG16F||_e===t.RG32F||_e===t.RGBA16F||_e===t.RGBA32F)&&e.get("EXT_color_buffer_float"),_e}function T(G,D){let ee;return G?D===null||D===Rc||D===Bu?ee=t.DEPTH24_STENCIL8:D===ga?ee=t.DEPTH32F_STENCIL8:D===xp&&(ee=t.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):D===null||D===Rc||D===Bu?ee=t.DEPTH_COMPONENT24:D===ga?ee=t.DEPTH_COMPONENT32F:D===xp&&(ee=t.DEPTH_COMPONENT16),ee}function N(G,D){return y(G)===!0||G.isFramebufferTexture&&G.minFilter!==vr&&G.minFilter!==rs?Math.log2(Math.max(D.width,D.height))+1:G.mipmaps!==void 0&&G.mipmaps.length>0?G.mipmaps.length:G.isCompressedTexture&&Array.isArray(G.image)?D.mipmaps.length:1}function R(G){const D=G.target;D.removeEventListener("dispose",R),O(D),D.isVideoTexture&&u.delete(D)}function C(G){const D=G.target;D.removeEventListener("dispose",C),I(D)}function O(G){const D=r.get(G);if(D.__webglInit===void 0)return;const ee=G.source,he=p.get(ee);if(he){const le=he[D.__cacheKey];le.usedTimes--,le.usedTimes===0&&M(G),Object.keys(he).length===0&&p.delete(ee)}r.remove(G)}function M(G){const D=r.get(G);t.deleteTexture(D.__webglTexture);const ee=G.source,he=p.get(ee);delete he[D.__cacheKey],o.memory.textures--}function I(G){const D=r.get(G);if(G.depthTexture&&(G.depthTexture.dispose(),r.remove(G.depthTexture)),G.isWebGLCubeRenderTarget)for(let he=0;he<6;he++){if(Array.isArray(D.__webglFramebuffer[he]))for(let le=0;le=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+G+" texture units while this GPU supports only "+i.maxTextures),U+=1,G}function b(G){const D=[];return D.push(G.wrapS),D.push(G.wrapT),D.push(G.wrapR||0),D.push(G.magFilter),D.push(G.minFilter),D.push(G.anisotropy),D.push(G.internalFormat),D.push(G.format),D.push(G.type),D.push(G.generateMipmaps),D.push(G.premultiplyAlpha),D.push(G.flipY),D.push(G.unpackAlignment),D.push(G.colorSpace),D.join()}function H(G,D){const ee=r.get(G);if(G.isVideoTexture&&$(G),G.isRenderTargetTexture===!1&&G.version>0&&ee.__version!==G.version){const he=G.image;if(he===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(he.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Q(ee,G,D);return}}n.bindTexture(t.TEXTURE_2D,ee.__webglTexture,t.TEXTURE0+D)}function V(G,D){const ee=r.get(G);if(G.version>0&&ee.__version!==G.version){Q(ee,G,D);return}n.bindTexture(t.TEXTURE_2D_ARRAY,ee.__webglTexture,t.TEXTURE0+D)}function B(G,D){const ee=r.get(G);if(G.version>0&&ee.__version!==G.version){Q(ee,G,D);return}n.bindTexture(t.TEXTURE_3D,ee.__webglTexture,t.TEXTURE0+D)}function z(G,D){const ee=r.get(G);if(G.version>0&&ee.__version!==G.version){re(ee,G,D);return}n.bindTexture(t.TEXTURE_CUBE_MAP,ee.__webglTexture,t.TEXTURE0+D)}const W={[$1]:t.REPEAT,[Mu]:t.CLAMP_TO_EDGE,[q1]:t.MIRRORED_REPEAT},K={[vr]:t.NEAREST,[i5]:t.NEAREST_MIPMAP_NEAREST,[Gg]:t.NEAREST_MIPMAP_LINEAR,[rs]:t.LINEAR,[iS]:t.LINEAR_MIPMAP_NEAREST,[Cu]:t.LINEAR_MIPMAP_LINEAR},j={[a5]:t.NEVER,[d5]:t.ALWAYS,[l5]:t.LESS,[ZI]:t.LEQUAL,[c5]:t.EQUAL,[f5]:t.GEQUAL,[u5]:t.GREATER,[h5]:t.NOTEQUAL};function Y(G,D){if(D.type===ga&&e.has("OES_texture_float_linear")===!1&&(D.magFilter===rs||D.magFilter===iS||D.magFilter===Gg||D.magFilter===Cu||D.minFilter===rs||D.minFilter===iS||D.minFilter===Gg||D.minFilter===Cu)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(G,t.TEXTURE_WRAP_S,W[D.wrapS]),t.texParameteri(G,t.TEXTURE_WRAP_T,W[D.wrapT]),(G===t.TEXTURE_3D||G===t.TEXTURE_2D_ARRAY)&&t.texParameteri(G,t.TEXTURE_WRAP_R,W[D.wrapR]),t.texParameteri(G,t.TEXTURE_MAG_FILTER,K[D.magFilter]),t.texParameteri(G,t.TEXTURE_MIN_FILTER,K[D.minFilter]),D.compareFunction&&(t.texParameteri(G,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(G,t.TEXTURE_COMPARE_FUNC,j[D.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(D.magFilter===vr||D.minFilter!==Gg&&D.minFilter!==Cu||D.type===ga&&e.has("OES_texture_float_linear")===!1)return;if(D.anisotropy>1||r.get(D).__currentAnisotropy){const ee=e.get("EXT_texture_filter_anisotropic");t.texParameterf(G,ee.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(D.anisotropy,i.getMaxAnisotropy())),r.get(D).__currentAnisotropy=D.anisotropy}}}function ge(G,D){let ee=!1;G.__webglInit===void 0&&(G.__webglInit=!0,D.addEventListener("dispose",R));const he=D.source;let le=p.get(he);le===void 0&&(le={},p.set(he,le));const _e=b(D);if(_e!==G.__cacheKey){le[_e]===void 0&&(le[_e]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,ee=!0),le[_e].usedTimes++;const ze=le[G.__cacheKey];ze!==void 0&&(le[G.__cacheKey].usedTimes--,ze.usedTimes===0&&M(D)),G.__cacheKey=_e,G.__webglTexture=le[_e].texture}return ee}function Q(G,D,ee){let he=t.TEXTURE_2D;(D.isDataArrayTexture||D.isCompressedArrayTexture)&&(he=t.TEXTURE_2D_ARRAY),D.isData3DTexture&&(he=t.TEXTURE_3D);const le=ge(G,D),_e=D.source;n.bindTexture(he,G.__webglTexture,t.TEXTURE0+ee);const ze=r.get(_e);if(_e.version!==ze.__version||le===!0){n.activeTexture(t.TEXTURE0+ee);const Oe=fn.getPrimaries(fn.workingColorSpace),Ge=D.colorSpace===da?null:fn.getPrimaries(D.colorSpace),Lt=D.colorSpace===da||Oe===Ge?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,D.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,D.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Lt);let Pe=v(D.image,!1,i.maxTextureSize);Pe=ne(D,Pe);const nt=s.convert(D.format,D.colorSpace),et=s.convert(D.type);let yt=E(D.internalFormat,nt,et,D.colorSpace,D.isVideoTexture);Y(he,D);let rt;const Ct=D.mipmaps,Rt=D.isVideoTexture!==!0,Sn=ze.__version===void 0||le===!0,ce=_e.dataReady,je=N(D,Pe);if(D.isDepthTexture)yt=T(D.format===zu,D.type),Sn&&(Rt?n.texStorage2D(t.TEXTURE_2D,1,yt,Pe.width,Pe.height):n.texImage2D(t.TEXTURE_2D,0,yt,Pe.width,Pe.height,0,nt,et,null));else if(D.isDataTexture)if(Ct.length>0){Rt&&Sn&&n.texStorage2D(t.TEXTURE_2D,je,yt,Ct[0].width,Ct[0].height);for(let Ce=0,ke=Ct.length;Ce0){const $e=AR(rt.width,rt.height,D.format,D.type);for(const Je of D.layerUpdates){const Nt=rt.data.subarray(Je*$e/rt.data.BYTES_PER_ELEMENT,(Je+1)*$e/rt.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Ce,0,0,Je,rt.width,rt.height,1,nt,Nt)}D.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Ce,0,0,0,rt.width,rt.height,Pe.depth,nt,rt.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,Ce,yt,rt.width,rt.height,Pe.depth,0,rt.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Rt?ce&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,Ce,0,0,0,rt.width,rt.height,Pe.depth,nt,et,rt.data):n.texImage3D(t.TEXTURE_2D_ARRAY,Ce,yt,rt.width,rt.height,Pe.depth,0,nt,et,rt.data)}else{Rt&&Sn&&n.texStorage2D(t.TEXTURE_2D,je,yt,Ct[0].width,Ct[0].height);for(let Ce=0,ke=Ct.length;Ce0){const Ce=AR(Pe.width,Pe.height,D.format,D.type);for(const ke of D.layerUpdates){const $e=Pe.data.subarray(ke*Ce/Pe.data.BYTES_PER_ELEMENT,(ke+1)*Ce/Pe.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,ke,Pe.width,Pe.height,1,nt,et,$e)}D.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,Pe.width,Pe.height,Pe.depth,nt,et,Pe.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,yt,Pe.width,Pe.height,Pe.depth,0,nt,et,Pe.data);else if(D.isData3DTexture)Rt?(Sn&&n.texStorage3D(t.TEXTURE_3D,je,yt,Pe.width,Pe.height,Pe.depth),ce&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,Pe.width,Pe.height,Pe.depth,nt,et,Pe.data)):n.texImage3D(t.TEXTURE_3D,0,yt,Pe.width,Pe.height,Pe.depth,0,nt,et,Pe.data);else if(D.isFramebufferTexture){if(Sn)if(Rt)n.texStorage2D(t.TEXTURE_2D,je,yt,Pe.width,Pe.height);else{let Ce=Pe.width,ke=Pe.height;for(let $e=0;$e>=1,ke>>=1}}else if(Ct.length>0){if(Rt&&Sn){const Ce=ae(Ct[0]);n.texStorage2D(t.TEXTURE_2D,je,yt,Ce.width,Ce.height)}for(let Ce=0,ke=Ct.length;Ce0&&je++;const ke=ae(nt[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,je,Ct,ke.width,ke.height)}for(let ke=0;ke<6;ke++)if(Pe){Rt?ce&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,nt[ke].width,nt[ke].height,yt,rt,nt[ke].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,Ct,nt[ke].width,nt[ke].height,0,yt,rt,nt[ke].data);for(let $e=0;$e>_e),et=Math.max(1,D.height>>_e);le===t.TEXTURE_3D||le===t.TEXTURE_2D_ARRAY?n.texImage3D(le,_e,Ge,nt,et,D.depth,0,ze,Oe,null):n.texImage2D(le,_e,Ge,nt,et,0,ze,Oe,null)}n.bindFramebuffer(t.FRAMEBUFFER,G),X(D)?a.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,he,le,Pe.__webglTexture,0,te(D)):(le===t.TEXTURE_2D||le>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&le<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,he,le,Pe.__webglTexture,_e),n.bindFramebuffer(t.FRAMEBUFFER,null)}function Ae(G,D,ee){if(t.bindRenderbuffer(t.RENDERBUFFER,G),D.depthBuffer){const he=D.depthTexture,le=he&&he.isDepthTexture?he.type:null,_e=T(D.stencilBuffer,le),ze=D.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Oe=te(D);X(D)?a.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Oe,_e,D.width,D.height):ee?t.renderbufferStorageMultisample(t.RENDERBUFFER,Oe,_e,D.width,D.height):t.renderbufferStorage(t.RENDERBUFFER,_e,D.width,D.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,ze,t.RENDERBUFFER,G)}else{const he=D.textures;for(let le=0;le{delete D.__boundDepthTexture,delete D.__depthDisposeCallback,he.removeEventListener("dispose",le)};he.addEventListener("dispose",le),D.__depthDisposeCallback=le}D.__boundDepthTexture=he}if(G.depthTexture&&!D.__autoAllocateDepthBuffer){if(ee)throw new Error("target.depthTexture not supported in Cube render targets");Ee(D.__webglFramebuffer,G)}else if(ee){D.__webglDepthbuffer=[];for(let he=0;he<6;he++)if(n.bindFramebuffer(t.FRAMEBUFFER,D.__webglFramebuffer[he]),D.__webglDepthbuffer[he]===void 0)D.__webglDepthbuffer[he]=t.createRenderbuffer(),Ae(D.__webglDepthbuffer[he],G,!1);else{const le=G.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,_e=D.__webglDepthbuffer[he];t.bindRenderbuffer(t.RENDERBUFFER,_e),t.framebufferRenderbuffer(t.FRAMEBUFFER,le,t.RENDERBUFFER,_e)}}else if(n.bindFramebuffer(t.FRAMEBUFFER,D.__webglFramebuffer),D.__webglDepthbuffer===void 0)D.__webglDepthbuffer=t.createRenderbuffer(),Ae(D.__webglDepthbuffer,G,!1);else{const he=G.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,le=D.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,le),t.framebufferRenderbuffer(t.FRAMEBUFFER,he,t.RENDERBUFFER,le)}n.bindFramebuffer(t.FRAMEBUFFER,null)}function Ve(G,D,ee){const he=r.get(G);D!==void 0&&we(he.__webglFramebuffer,G,G.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),ee!==void 0&&Le(G)}function qe(G){const D=G.texture,ee=r.get(G),he=r.get(D);G.addEventListener("dispose",C);const le=G.textures,_e=G.isWebGLCubeRenderTarget===!0,ze=le.length>1;if(ze||(he.__webglTexture===void 0&&(he.__webglTexture=t.createTexture()),he.__version=D.version,o.memory.textures++),_e){ee.__webglFramebuffer=[];for(let Oe=0;Oe<6;Oe++)if(D.mipmaps&&D.mipmaps.length>0){ee.__webglFramebuffer[Oe]=[];for(let Ge=0;Ge0){ee.__webglFramebuffer=[];for(let Oe=0;Oe0&&X(G)===!1){ee.__webglMultisampledFramebuffer=t.createFramebuffer(),ee.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,ee.__webglMultisampledFramebuffer);for(let Oe=0;Oe0)for(let Ge=0;Ge0)for(let Ge=0;Ge0){if(X(G)===!1){const D=G.textures,ee=G.width,he=G.height;let le=t.COLOR_BUFFER_BIT;const _e=G.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ze=r.get(G),Oe=D.length>1;if(Oe)for(let Ge=0;Ge0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&D.__useRenderToTexture!==!1}function $(G){const D=o.render.frame;u.get(G)!==D&&(u.set(G,D),G.update())}function ne(G,D){const ee=G.colorSpace,he=G.format,le=G.type;return G.isCompressedTexture===!0||G.isVideoTexture===!0||ee!==Hc&&ee!==da&&(fn.getTransfer(ee)===bn?(he!==Qs||le!==wi)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",ee)),D}function ae(G){return typeof HTMLImageElement<"u"&&G instanceof HTMLImageElement?(c.width=G.naturalWidth||G.width,c.height=G.naturalHeight||G.height):typeof VideoFrame<"u"&&G instanceof VideoFrame?(c.width=G.displayWidth,c.height=G.displayHeight):(c.width=G.width,c.height=G.height),c}this.allocateTextureUnit=P,this.resetTextureUnits=L,this.setTexture2D=H,this.setTexture2DArray=V,this.setTexture3D=B,this.setTextureCube=z,this.rebindTextures=Ve,this.setupRenderTarget=qe,this.updateRenderTargetMipmap=it,this.updateMultisampleRenderTarget=ie,this.setupDepthRenderbuffer=Le,this.setupFrameBufferTexture=we,this.useMultisampledRTT=X}function OH(t,e){function n(r,i=da){let s;const o=fn.getTransfer(i);if(r===wi)return t.UNSIGNED_BYTE;if(r===rT)return t.UNSIGNED_SHORT_4_4_4_4;if(r===iT)return t.UNSIGNED_SHORT_5_5_5_1;if(r===HI)return t.UNSIGNED_INT_5_9_9_9_REV;if(r===zI)return t.BYTE;if(r===VI)return t.SHORT;if(r===xp)return t.UNSIGNED_SHORT;if(r===nT)return t.INT;if(r===Rc)return t.UNSIGNED_INT;if(r===ga)return t.FLOAT;if(r===rd)return t.HALF_FLOAT;if(r===GI)return t.ALPHA;if(r===WI)return t.RGB;if(r===Qs)return t.RGBA;if(r===jI)return t.LUMINANCE;if(r===$I)return t.LUMINANCE_ALPHA;if(r===_f)return t.DEPTH_COMPONENT;if(r===zu)return t.DEPTH_STENCIL;if(r===qI)return t.RED;if(r===sT)return t.RED_INTEGER;if(r===XI)return t.RG;if(r===oT)return t.RG_INTEGER;if(r===Mv)return t.RGBA_INTEGER;if(r===q0||r===X0||r===K0||r===Y0)if(o===bn)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(r===q0)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===X0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===K0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===Y0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(r===q0)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===X0)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===K0)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===Y0)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===X1||r===K1||r===Y1||r===Z1)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(r===X1)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===K1)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===Y1)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===Z1)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===J1||r===Q1||r===eE)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(r===J1||r===Q1)return o===bn?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(r===eE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===tE||r===nE||r===rE||r===iE||r===sE||r===oE||r===aE||r===lE||r===cE||r===uE||r===hE||r===fE||r===dE||r===pE)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(r===tE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===nE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===rE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===iE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===sE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===oE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===aE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===lE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===cE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===uE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===hE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===fE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===dE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===pE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===Z0||r===mE||r===gE)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(r===Z0)return o===bn?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(r===mE)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(r===gE)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(r===KI||r===_E||r===vE||r===yE)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(r===Z0)return s.COMPRESSED_RED_RGTC1_EXT;if(r===_E)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===vE)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===yE)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===Bu?t.UNSIGNED_INT_24_8:t[r]!==void 0?t[r]:null}return{convert:n}}class LH extends As{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class Qd extends as{constructor(){super(),this.isGroup=!0,this.type="Group"}}const PH={type:"move"};class kS{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Qd,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Qd,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new xe,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new xe),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Qd,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new xe,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new xe),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const n=this._hand;if(n)for(const r of e.hand.values())this._getHandJoint(n,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,n,r){let i=null,s=null,o=null;const a=this._targetRay,l=this._grip,c=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(c&&e.hand){o=!0;for(const v of e.hand.values()){const y=n.getJointPose(v,r),_=this._getHandJoint(c,v);y!==null&&(_.matrix.fromArray(y.transform.matrix),_.matrix.decompose(_.position,_.rotation,_.scale),_.matrixWorldNeedsUpdate=!0,_.jointRadius=y.radius),_.visible=y!==null}const u=c.joints["index-finger-tip"],h=c.joints["thumb-tip"],p=u.position.distanceTo(h.position),m=.02,g=.005;c.inputState.pinching&&p>m+g?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&p<=m-g&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,r),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1));a!==null&&(i=n.getPose(e.targetRaySpace,r),i===null&&s!==null&&(i=s),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(PH)))}return a!==null&&(a.visible=i!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new Qd;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}}const DH=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,UH=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`;class FH{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,n,r){if(this.texture===null){const i=new or,s=e.properties.get(i);s.__webglTexture=n.texture,(n.depthNear!=r.depthNear||n.depthFar!=r.depthFar)&&(this.depthNear=n.depthNear,this.depthFar=n.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const n=e.cameras[0].viewport,r=new Hi({vertexShader:DH,fragmentShader:UH,uniforms:{depthColor:{value:this.texture},depthWidth:{value:n.z},depthHeight:{value:n.w}}});this.mesh=new Ao(new Zp(20,20),r)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class BH extends Dl{constructor(e,n){super();const r=this;let i=null,s=1,o=null,a="local-floor",l=1,c=null,u=null,h=null,p=null,m=null,g=null;const v=new FH,y=n.getContextAttributes();let _=null,S=null;const E=[],T=[],N=new St;let R=null;const C=new As;C.viewport=new gr;const O=new As;O.viewport=new gr;const M=[C,O],I=new LH;let U=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Q){let re=E[Q];return re===void 0&&(re=new kS,E[Q]=re),re.getTargetRaySpace()},this.getControllerGrip=function(Q){let re=E[Q];return re===void 0&&(re=new kS,E[Q]=re),re.getGripSpace()},this.getHand=function(Q){let re=E[Q];return re===void 0&&(re=new kS,E[Q]=re),re.getHandSpace()};function P(Q){const re=T.indexOf(Q.inputSource);if(re===-1)return;const we=E[re];we!==void 0&&(we.update(Q.inputSource,Q.frame,c||o),we.dispatchEvent({type:Q.type,data:Q.inputSource}))}function b(){i.removeEventListener("select",P),i.removeEventListener("selectstart",P),i.removeEventListener("selectend",P),i.removeEventListener("squeeze",P),i.removeEventListener("squeezestart",P),i.removeEventListener("squeezeend",P),i.removeEventListener("end",b),i.removeEventListener("inputsourceschange",H);for(let Q=0;Q=0&&(T[Ae]=null,E[Ae].disconnect(we))}for(let re=0;re=T.length){T.push(we),Ae=Le;break}else if(T[Le]===null){T[Le]=we,Ae=Le;break}if(Ae===-1)break}const Ee=E[Ae];Ee&&Ee.connect(we)}}const V=new xe,B=new xe;function z(Q,re,we){V.setFromMatrixPosition(re.matrixWorld),B.setFromMatrixPosition(we.matrixWorld);const Ae=V.distanceTo(B),Ee=re.projectionMatrix.elements,Le=we.projectionMatrix.elements,Ve=Ee[14]/(Ee[10]-1),qe=Ee[14]/(Ee[10]+1),it=(Ee[9]+1)/Ee[5],De=(Ee[9]-1)/Ee[5],A=(Ee[8]-1)/Ee[0],ie=(Le[8]+1)/Le[0],te=Ve*A,X=Ve*ie,$=Ae/(-A+ie),ne=$*-A;if(re.matrixWorld.decompose(Q.position,Q.quaternion,Q.scale),Q.translateX(ne),Q.translateZ($),Q.matrixWorld.compose(Q.position,Q.quaternion,Q.scale),Q.matrixWorldInverse.copy(Q.matrixWorld).invert(),Ee[10]===-1)Q.projectionMatrix.copy(re.projectionMatrix),Q.projectionMatrixInverse.copy(re.projectionMatrixInverse);else{const ae=Ve+$,G=qe+$,D=te-ne,ee=X+(Ae-ne),he=it*qe/G*ae,le=De*qe/G*ae;Q.projectionMatrix.makePerspective(D,ee,he,le,ae,G),Q.projectionMatrixInverse.copy(Q.projectionMatrix).invert()}}function W(Q,re){re===null?Q.matrixWorld.copy(Q.matrix):Q.matrixWorld.multiplyMatrices(re.matrixWorld,Q.matrix),Q.matrixWorldInverse.copy(Q.matrixWorld).invert()}this.updateCamera=function(Q){if(i===null)return;let re=Q.near,we=Q.far;v.texture!==null&&(v.depthNear>0&&(re=v.depthNear),v.depthFar>0&&(we=v.depthFar)),I.near=O.near=C.near=re,I.far=O.far=C.far=we,(U!==I.near||L!==I.far)&&(i.updateRenderState({depthNear:I.near,depthFar:I.far}),U=I.near,L=I.far),C.layers.mask=Q.layers.mask|2,O.layers.mask=Q.layers.mask|4,I.layers.mask=C.layers.mask|O.layers.mask;const Ae=Q.parent,Ee=I.cameras;W(I,Ae);for(let Le=0;Le0&&(y.alphaTest.value=_.alphaTest);const S=e.get(_),E=S.envMap,T=S.envMapRotation;E&&(y.envMap.value=E,hu.copy(T),hu.x*=-1,hu.y*=-1,hu.z*=-1,E.isCubeTexture&&E.isRenderTargetTexture===!1&&(hu.y*=-1,hu.z*=-1),y.envMapRotation.value.setFromMatrix4(zH.makeRotationFromEuler(hu)),y.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,y.reflectivity.value=_.reflectivity,y.ior.value=_.ior,y.refractionRatio.value=_.refractionRatio),_.lightMap&&(y.lightMap.value=_.lightMap,y.lightMapIntensity.value=_.lightMapIntensity,n(_.lightMap,y.lightMapTransform)),_.aoMap&&(y.aoMap.value=_.aoMap,y.aoMapIntensity.value=_.aoMapIntensity,n(_.aoMap,y.aoMapTransform))}function o(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,_.map&&(y.map.value=_.map,n(_.map,y.mapTransform))}function a(y,_){y.dashSize.value=_.dashSize,y.totalSize.value=_.dashSize+_.gapSize,y.scale.value=_.scale}function l(y,_,S,E){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.size.value=_.size*S,y.scale.value=E*.5,_.map&&(y.map.value=_.map,n(_.map,y.uvTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,n(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function c(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.rotation.value=_.rotation,_.map&&(y.map.value=_.map,n(_.map,y.mapTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,n(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function u(y,_){y.specular.value.copy(_.specular),y.shininess.value=Math.max(_.shininess,1e-4)}function h(y,_){_.gradientMap&&(y.gradientMap.value=_.gradientMap)}function p(y,_){y.metalness.value=_.metalness,_.metalnessMap&&(y.metalnessMap.value=_.metalnessMap,n(_.metalnessMap,y.metalnessMapTransform)),y.roughness.value=_.roughness,_.roughnessMap&&(y.roughnessMap.value=_.roughnessMap,n(_.roughnessMap,y.roughnessMapTransform)),_.envMap&&(y.envMapIntensity.value=_.envMapIntensity)}function m(y,_,S){y.ior.value=_.ior,_.sheen>0&&(y.sheenColor.value.copy(_.sheenColor).multiplyScalar(_.sheen),y.sheenRoughness.value=_.sheenRoughness,_.sheenColorMap&&(y.sheenColorMap.value=_.sheenColorMap,n(_.sheenColorMap,y.sheenColorMapTransform)),_.sheenRoughnessMap&&(y.sheenRoughnessMap.value=_.sheenRoughnessMap,n(_.sheenRoughnessMap,y.sheenRoughnessMapTransform))),_.clearcoat>0&&(y.clearcoat.value=_.clearcoat,y.clearcoatRoughness.value=_.clearcoatRoughness,_.clearcoatMap&&(y.clearcoatMap.value=_.clearcoatMap,n(_.clearcoatMap,y.clearcoatMapTransform)),_.clearcoatRoughnessMap&&(y.clearcoatRoughnessMap.value=_.clearcoatRoughnessMap,n(_.clearcoatRoughnessMap,y.clearcoatRoughnessMapTransform)),_.clearcoatNormalMap&&(y.clearcoatNormalMap.value=_.clearcoatNormalMap,n(_.clearcoatNormalMap,y.clearcoatNormalMapTransform),y.clearcoatNormalScale.value.copy(_.clearcoatNormalScale),_.side===ni&&y.clearcoatNormalScale.value.negate())),_.dispersion>0&&(y.dispersion.value=_.dispersion),_.iridescence>0&&(y.iridescence.value=_.iridescence,y.iridescenceIOR.value=_.iridescenceIOR,y.iridescenceThicknessMinimum.value=_.iridescenceThicknessRange[0],y.iridescenceThicknessMaximum.value=_.iridescenceThicknessRange[1],_.iridescenceMap&&(y.iridescenceMap.value=_.iridescenceMap,n(_.iridescenceMap,y.iridescenceMapTransform)),_.iridescenceThicknessMap&&(y.iridescenceThicknessMap.value=_.iridescenceThicknessMap,n(_.iridescenceThicknessMap,y.iridescenceThicknessMapTransform))),_.transmission>0&&(y.transmission.value=_.transmission,y.transmissionSamplerMap.value=S.texture,y.transmissionSamplerSize.value.set(S.width,S.height),_.transmissionMap&&(y.transmissionMap.value=_.transmissionMap,n(_.transmissionMap,y.transmissionMapTransform)),y.thickness.value=_.thickness,_.thicknessMap&&(y.thicknessMap.value=_.thicknessMap,n(_.thicknessMap,y.thicknessMapTransform)),y.attenuationDistance.value=_.attenuationDistance,y.attenuationColor.value.copy(_.attenuationColor)),_.anisotropy>0&&(y.anisotropyVector.value.set(_.anisotropy*Math.cos(_.anisotropyRotation),_.anisotropy*Math.sin(_.anisotropyRotation)),_.anisotropyMap&&(y.anisotropyMap.value=_.anisotropyMap,n(_.anisotropyMap,y.anisotropyMapTransform))),y.specularIntensity.value=_.specularIntensity,y.specularColor.value.copy(_.specularColor),_.specularColorMap&&(y.specularColorMap.value=_.specularColorMap,n(_.specularColorMap,y.specularColorMapTransform)),_.specularIntensityMap&&(y.specularIntensityMap.value=_.specularIntensityMap,n(_.specularIntensityMap,y.specularIntensityMapTransform))}function g(y,_){_.matcap&&(y.matcap.value=_.matcap)}function v(y,_){const S=e.get(_).light;y.referencePosition.value.setFromMatrixPosition(S.matrixWorld),y.nearDistance.value=S.shadow.camera.near,y.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function HH(t,e,n,r){let i={},s={},o=[];const a=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function l(S,E){const T=E.program;r.uniformBlockBinding(S,T)}function c(S,E){let T=i[S.id];T===void 0&&(g(S),T=u(S),i[S.id]=T,S.addEventListener("dispose",y));const N=E.program;r.updateUBOMapping(S,N);const R=e.render.frame;s[S.id]!==R&&(p(S),s[S.id]=R)}function u(S){const E=h();S.__bindingPointIndex=E;const T=t.createBuffer(),N=S.__size,R=S.usage;return t.bindBuffer(t.UNIFORM_BUFFER,T),t.bufferData(t.UNIFORM_BUFFER,N,R),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,E,T),T}function h(){for(let S=0;S0&&(T+=N-R),S.__size=T,S.__cache={},this}function v(S){const E={boundary:0,storage:0};return typeof S=="number"||typeof S=="boolean"?(E.boundary=4,E.storage=4):S.isVector2?(E.boundary=8,E.storage=8):S.isVector3||S.isColor?(E.boundary=16,E.storage=12):S.isVector4?(E.boundary=16,E.storage=16):S.isMatrix3?(E.boundary=48,E.storage=48):S.isMatrix4?(E.boundary=64,E.storage=64):S.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",S),E}function y(S){const E=S.target;E.removeEventListener("dispose",y);const T=o.indexOf(E.__bindingPointIndex);o.splice(T,1),t.deleteBuffer(i[E.id]),delete i[E.id],delete s[E.id]}function _(){for(const S in i)t.deleteBuffer(i[S]);o=[],i={},s={}}return{bind:l,update:c,dispose:_}}class GH{constructor(e={}){const{canvas:n=k5(),context:r=null,depth:i=!0,stencil:s=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:h=!1,reverseDepthBuffer:p=!1}=e;this.isWebGLRenderer=!0;let m;if(r!==null){if(typeof WebGLRenderingContext<"u"&&r instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");m=r.getContextAttributes().alpha}else m=o;const g=new Uint32Array(4),v=new Int32Array(4);let y=null,_=null;const S=[],E=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=pr,this.toneMapping=va,this.toneMappingExposure=1;const T=this;let N=!1,R=0,C=0,O=null,M=-1,I=null;const U=new gr,L=new gr;let P=null;const b=new cn(0);let H=0,V=n.width,B=n.height,z=1,W=null,K=null;const j=new gr(0,0,V,B),Y=new gr(0,0,V,B);let ge=!1;const Q=new oO;let re=!1,we=!1;const Ae=new ar,Ee=new ar,Le=new xe,Ve=new gr,qe={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let it=!1;function De(){return O===null?z:1}let A=r;function ie(q,fe){return n.getContext(q,fe)}try{const q={alpha:!0,depth:i,stencil:s,antialias:a,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:h};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${bv}`),n.addEventListener("webglcontextlost",ke,!1),n.addEventListener("webglcontextrestored",$e,!1),n.addEventListener("webglcontextcreationerror",Je,!1),A===null){const fe="webgl2";if(A=ie(fe,q),A===null)throw ie(fe)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(q){throw console.error("THREE.WebGLRenderer: "+q.message),q}let te,X,$,ne,ae,G,D,ee,he,le,_e,ze,Oe,Ge,Lt,Pe,nt,et,yt,rt,Ct,Rt,Sn,ce;function je(){te=new X6(A),te.init(),Rt=new OH(A,te),X=new H6(A,te,e,Rt),$=new NH(A,te),X.reverseDepthBuffer&&p&&$.buffers.depth.setReversed(!0),ne=new Z6(A),ae=new mH,G=new IH(A,te,$,ae,X,Rt,ne),D=new W6(T),ee=new q6(T),he=new iz(A),Sn=new z6(A,he),le=new K6(A,he,ne,Sn),_e=new Q6(A,le,he,ne),yt=new J6(A,X,G),Pe=new G6(ae),ze=new pH(T,D,ee,te,X,Sn,Pe),Oe=new VH(T,ae),Ge=new _H,Lt=new wH(te),et=new B6(T,D,ee,$,_e,m,l),nt=new CH(T,_e,X),ce=new HH(A,ne,X,$),rt=new V6(A,te,ne),Ct=new Y6(A,te,ne),ne.programs=ze.programs,T.capabilities=X,T.extensions=te,T.properties=ae,T.renderLists=Ge,T.shadowMap=nt,T.state=$,T.info=ne}je();const Ce=new BH(T,A);this.xr=Ce,this.getContext=function(){return A},this.getContextAttributes=function(){return A.getContextAttributes()},this.forceContextLoss=function(){const q=te.get("WEBGL_lose_context");q&&q.loseContext()},this.forceContextRestore=function(){const q=te.get("WEBGL_lose_context");q&&q.restoreContext()},this.getPixelRatio=function(){return z},this.setPixelRatio=function(q){q!==void 0&&(z=q,this.setSize(V,B,!1))},this.getSize=function(q){return q.set(V,B)},this.setSize=function(q,fe,Te=!0){if(Ce.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}V=q,B=fe,n.width=Math.floor(q*z),n.height=Math.floor(fe*z),Te===!0&&(n.style.width=q+"px",n.style.height=fe+"px"),this.setViewport(0,0,q,fe)},this.getDrawingBufferSize=function(q){return q.set(V*z,B*z).floor()},this.setDrawingBufferSize=function(q,fe,Te){V=q,B=fe,z=Te,n.width=Math.floor(q*Te),n.height=Math.floor(fe*Te),this.setViewport(0,0,q,fe)},this.getCurrentViewport=function(q){return q.copy(U)},this.getViewport=function(q){return q.copy(j)},this.setViewport=function(q,fe,Te,be){q.isVector4?j.set(q.x,q.y,q.z,q.w):j.set(q,fe,Te,be),$.viewport(U.copy(j).multiplyScalar(z).round())},this.getScissor=function(q){return q.copy(Y)},this.setScissor=function(q,fe,Te,be){q.isVector4?Y.set(q.x,q.y,q.z,q.w):Y.set(q,fe,Te,be),$.scissor(L.copy(Y).multiplyScalar(z).round())},this.getScissorTest=function(){return ge},this.setScissorTest=function(q){$.setScissorTest(ge=q)},this.setOpaqueSort=function(q){W=q},this.setTransparentSort=function(q){K=q},this.getClearColor=function(q){return q.copy(et.getClearColor())},this.setClearColor=function(){et.setClearColor.apply(et,arguments)},this.getClearAlpha=function(){return et.getClearAlpha()},this.setClearAlpha=function(){et.setClearAlpha.apply(et,arguments)},this.clear=function(q=!0,fe=!0,Te=!0){let be=0;if(q){let me=!1;if(O!==null){const Be=O.texture.format;me=Be===Mv||Be===oT||Be===sT}if(me){const Be=O.texture.type,Ye=Be===wi||Be===Rc||Be===xp||Be===Bu||Be===rT||Be===iT,ct=et.getClearColor(),ut=et.getClearAlpha(),At=ct.r,kt=ct.g,ht=ct.b;Ye?(g[0]=At,g[1]=kt,g[2]=ht,g[3]=ut,A.clearBufferuiv(A.COLOR,0,g)):(v[0]=At,v[1]=kt,v[2]=ht,v[3]=ut,A.clearBufferiv(A.COLOR,0,v))}else be|=A.COLOR_BUFFER_BIT}fe&&(be|=A.DEPTH_BUFFER_BIT),Te&&(be|=A.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),A.clear(be)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){n.removeEventListener("webglcontextlost",ke,!1),n.removeEventListener("webglcontextrestored",$e,!1),n.removeEventListener("webglcontextcreationerror",Je,!1),Ge.dispose(),Lt.dispose(),ae.dispose(),D.dispose(),ee.dispose(),_e.dispose(),Sn.dispose(),ce.dispose(),ze.dispose(),Ce.dispose(),Ce.removeEventListener("sessionstart",Hm),Ce.removeEventListener("sessionend",Gm),Xo.stop()};function ke(q){q.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),N=!0}function $e(){console.log("THREE.WebGLRenderer: Context Restored."),N=!1;const q=ne.autoReset,fe=nt.enabled,Te=nt.autoUpdate,be=nt.needsUpdate,me=nt.type;je(),ne.autoReset=q,nt.enabled=fe,nt.autoUpdate=Te,nt.needsUpdate=be,nt.type=me}function Je(q){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",q.statusMessage)}function Nt(q){const fe=q.target;fe.removeEventListener("dispose",Nt),Gn(fe)}function Gn(q){Rr(q),ae.remove(q)}function Rr(q){const fe=ae.get(q).programs;fe!==void 0&&(fe.forEach(function(Te){ze.releaseProgram(Te)}),q.isShaderMaterial&&ze.releaseShaderCache(q))}this.renderBufferDirect=function(q,fe,Te,be,me,Be){fe===null&&(fe=qe);const Ye=me.isMesh&&me.matrixWorld.determinant()<0,ct=Zy(q,fe,Te,be,me);$.setMaterial(be,Ye);let ut=Te.index,At=1;if(be.wireframe===!0){if(ut=le.getWireframeAttribute(Te),ut===void 0)return;At=2}const kt=Te.drawRange,ht=Te.attributes.position;let Bt=kt.start*At,nn=(kt.start+kt.count)*At;Be!==null&&(Bt=Math.max(Bt,Be.start*At),nn=Math.min(nn,(Be.start+Be.count)*At)),ut!==null?(Bt=Math.max(Bt,0),nn=Math.min(nn,ut.count)):ht!=null&&(Bt=Math.max(Bt,0),nn=Math.min(nn,ht.count));const Et=nn-Bt;if(Et<0||Et===1/0)return;Sn.setup(me,be,ct,Te,ut);let Pt,zt=rt;if(ut!==null&&(Pt=he.get(ut),zt=Ct,zt.setIndex(Pt)),me.isMesh)be.wireframe===!0?($.setLineWidth(be.wireframeLinewidth*De()),zt.setMode(A.LINES)):zt.setMode(A.TRIANGLES);else if(me.isLine){let Qe=be.linewidth;Qe===void 0&&(Qe=1),$.setLineWidth(Qe*De()),me.isLineSegments?zt.setMode(A.LINES):me.isLineLoop?zt.setMode(A.LINE_LOOP):zt.setMode(A.LINE_STRIP)}else me.isPoints?zt.setMode(A.POINTS):me.isSprite&&zt.setMode(A.TRIANGLES);if(me.isBatchedMesh)if(me._multiDrawInstances!==null)zt.renderMultiDrawInstances(me._multiDrawStarts,me._multiDrawCounts,me._multiDrawCount,me._multiDrawInstances);else if(te.get("WEBGL_multi_draw"))zt.renderMultiDraw(me._multiDrawStarts,me._multiDrawCounts,me._multiDrawCount);else{const Qe=me._multiDrawStarts,Wn=me._multiDrawCounts,qt=me._multiDrawCount,Wr=ut?he.get(ut).bytesPerElement:1,cr=ae.get(be).currentProgram.getUniforms();for(let jr=0;jr{function Be(){if(be.forEach(function(Ye){ae.get(Ye).currentProgram.isReady()&&be.delete(Ye)}),be.size===0){me(q);return}setTimeout(Be,10)}te.get("KHR_parallel_shader_compile")!==null?Be():setTimeout(Be,10)})};let Xi=null;function fo(q){Xi&&Xi(q)}function Hm(){Xo.stop()}function Gm(){Xo.start()}const Xo=new aO;Xo.setAnimationLoop(fo),typeof self<"u"&&Xo.setContext(self),this.setAnimationLoop=function(q){Xi=q,Ce.setAnimationLoop(q),q===null?Xo.stop():Xo.start()},Ce.addEventListener("sessionstart",Hm),Ce.addEventListener("sessionend",Gm),this.render=function(q,fe){if(fe!==void 0&&fe.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(N===!0)return;if(q.matrixWorldAutoUpdate===!0&&q.updateMatrixWorld(),fe.parent===null&&fe.matrixWorldAutoUpdate===!0&&fe.updateMatrixWorld(),Ce.enabled===!0&&Ce.isPresenting===!0&&(Ce.cameraAutoUpdate===!0&&Ce.updateCamera(fe),fe=Ce.getCamera()),q.isScene===!0&&q.onBeforeRender(T,q,fe,O),_=Lt.get(q,E.length),_.init(fe),E.push(_),Ee.multiplyMatrices(fe.projectionMatrix,fe.matrixWorldInverse),Q.setFromProjectionMatrix(Ee),we=this.localClippingEnabled,re=Pe.init(this.clippingPlanes,we),y=Ge.get(q,S.length),y.init(),S.push(y),Ce.enabled===!0&&Ce.isPresenting===!0){const Be=T.xr.getDepthSensingMesh();Be!==null&&Yc(Be,fe,-1/0,T.sortObjects)}Yc(q,fe,0,T.sortObjects),y.finish(),T.sortObjects===!0&&y.sort(W,K),it=Ce.enabled===!1||Ce.isPresenting===!1||Ce.hasDepthSensing()===!1,it&&et.addToRenderList(y,q),this.info.render.frame++,re===!0&&Pe.beginShadows();const Te=_.state.shadowsArray;nt.render(Te,q,fe),re===!0&&Pe.endShadows(),this.info.autoReset===!0&&this.info.reset();const be=y.opaque,me=y.transmissive;if(_.setupLights(),fe.isArrayCamera){const Be=fe.cameras;if(me.length>0)for(let Ye=0,ct=Be.length;Ye0&&Yl(be,me,q,fe),it&&et.render(q),Wm(y,q,fe);O!==null&&(G.updateMultisampleRenderTarget(O),G.updateRenderTargetMipmap(O)),q.isScene===!0&&q.onAfterRender(T,q,fe),Sn.resetDefaultState(),M=-1,I=null,E.pop(),E.length>0?(_=E[E.length-1],re===!0&&Pe.setGlobalState(T.clippingPlanes,_.state.camera)):_=null,S.pop(),S.length>0?y=S[S.length-1]:y=null};function Yc(q,fe,Te,be){if(q.visible===!1)return;if(q.layers.test(fe.layers)){if(q.isGroup)Te=q.renderOrder;else if(q.isLOD)q.autoUpdate===!0&&q.update(fe);else if(q.isLight)_.pushLight(q),q.castShadow&&_.pushShadow(q);else if(q.isSprite){if(!q.frustumCulled||Q.intersectsSprite(q)){be&&Ve.setFromMatrixPosition(q.matrixWorld).applyMatrix4(Ee);const Ye=_e.update(q),ct=q.material;ct.visible&&y.push(q,Ye,ct,Te,Ve.z,null)}}else if((q.isMesh||q.isLine||q.isPoints)&&(!q.frustumCulled||Q.intersectsObject(q))){const Ye=_e.update(q),ct=q.material;if(be&&(q.boundingSphere!==void 0?(q.boundingSphere===null&&q.computeBoundingSphere(),Ve.copy(q.boundingSphere.center)):(Ye.boundingSphere===null&&Ye.computeBoundingSphere(),Ve.copy(Ye.boundingSphere.center)),Ve.applyMatrix4(q.matrixWorld).applyMatrix4(Ee)),Array.isArray(ct)){const ut=Ye.groups;for(let At=0,kt=ut.length;At0&&gh(me,fe,Te),Be.length>0&&gh(Be,fe,Te),Ye.length>0&&gh(Ye,fe,Te),$.buffers.depth.setTest(!0),$.buffers.depth.setMask(!0),$.buffers.color.setMask(!0),$.setPolygonOffset(!1)}function Yl(q,fe,Te,be){if((Te.isScene===!0?Te.overrideMaterial:null)!==null)return;_.state.transmissionRenderTarget[be.id]===void 0&&(_.state.transmissionRenderTarget[be.id]=new Ps(1,1,{generateMipmaps:!0,type:te.has("EXT_color_buffer_half_float")||te.has("EXT_color_buffer_float")?rd:wi,minFilter:Cu,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:fn.workingColorSpace}));const Be=_.state.transmissionRenderTarget[be.id],Ye=be.viewport||U;Be.setSize(Ye.z,Ye.w);const ct=T.getRenderTarget();T.setRenderTarget(Be),T.getClearColor(b),H=T.getClearAlpha(),H<1&&T.setClearColor(16777215,.5),T.clear(),it&&et.render(Te);const ut=T.toneMapping;T.toneMapping=va;const At=be.viewport;if(be.viewport!==void 0&&(be.viewport=void 0),_.setupLightsView(be),re===!0&&Pe.setGlobalState(T.clippingPlanes,be),gh(q,Te,be),G.updateMultisampleRenderTarget(Be),G.updateRenderTargetMipmap(Be),te.has("WEBGL_multisampled_render_to_texture")===!1){let kt=!1;for(let ht=0,Bt=fe.length;ht0),ht=!!Te.morphAttributes.position,Bt=!!Te.morphAttributes.normal,nn=!!Te.morphAttributes.color;let Et=va;be.toneMapped&&(O===null||O.isXRRenderTarget===!0)&&(Et=T.toneMapping);const Pt=Te.morphAttributes.position||Te.morphAttributes.normal||Te.morphAttributes.color,zt=Pt!==void 0?Pt.length:0,Qe=ae.get(be),Wn=_.state.lights;if(re===!0&&(we===!0||q!==I)){const jn=q===I&&be.id===M;Pe.setState(be,q,jn)}let qt=!1;be.version===Qe.__version?(Qe.needsLights&&Qe.lightsStateVersion!==Wn.state.version||Qe.outputColorSpace!==ct||me.isBatchedMesh&&Qe.batching===!1||!me.isBatchedMesh&&Qe.batching===!0||me.isBatchedMesh&&Qe.batchingColor===!0&&me.colorTexture===null||me.isBatchedMesh&&Qe.batchingColor===!1&&me.colorTexture!==null||me.isInstancedMesh&&Qe.instancing===!1||!me.isInstancedMesh&&Qe.instancing===!0||me.isSkinnedMesh&&Qe.skinning===!1||!me.isSkinnedMesh&&Qe.skinning===!0||me.isInstancedMesh&&Qe.instancingColor===!0&&me.instanceColor===null||me.isInstancedMesh&&Qe.instancingColor===!1&&me.instanceColor!==null||me.isInstancedMesh&&Qe.instancingMorph===!0&&me.morphTexture===null||me.isInstancedMesh&&Qe.instancingMorph===!1&&me.morphTexture!==null||Qe.envMap!==ut||be.fog===!0&&Qe.fog!==Be||Qe.numClippingPlanes!==void 0&&(Qe.numClippingPlanes!==Pe.numPlanes||Qe.numIntersection!==Pe.numIntersection)||Qe.vertexAlphas!==At||Qe.vertexTangents!==kt||Qe.morphTargets!==ht||Qe.morphNormals!==Bt||Qe.morphColors!==nn||Qe.toneMapping!==Et||Qe.morphTargetsCount!==zt)&&(qt=!0):(qt=!0,Qe.__version=be.version);let Wr=Qe.currentProgram;qt===!0&&(Wr=_h(be,fe,me));let cr=!1,jr=!1,Zl=!1;const Tn=Wr.getUniforms(),Ai=Qe.uniforms;if($.useProgram(Wr.program)&&(cr=!0,jr=!0,Zl=!0),be.id!==M&&(M=be.id,jr=!0),cr||I!==q){$.buffers.depth.getReversed()?(Ae.copy(q.projectionMatrix),O5(Ae),L5(Ae),Tn.setValue(A,"projectionMatrix",Ae)):Tn.setValue(A,"projectionMatrix",q.projectionMatrix),Tn.setValue(A,"viewMatrix",q.matrixWorldInverse);const Ko=Tn.map.cameraPosition;Ko!==void 0&&Ko.setValue(A,Le.setFromMatrixPosition(q.matrixWorld)),X.logarithmicDepthBuffer&&Tn.setValue(A,"logDepthBufFC",2/(Math.log(q.far+1)/Math.LN2)),(be.isMeshPhongMaterial||be.isMeshToonMaterial||be.isMeshLambertMaterial||be.isMeshBasicMaterial||be.isMeshStandardMaterial||be.isShaderMaterial)&&Tn.setValue(A,"isOrthographic",q.isOrthographicCamera===!0),I!==q&&(I=q,jr=!0,Zl=!0)}if(me.isSkinnedMesh){Tn.setOptional(A,me,"bindMatrix"),Tn.setOptional(A,me,"bindMatrixInverse");const jn=me.skeleton;jn&&(jn.boneTexture===null&&jn.computeBoneTexture(),Tn.setValue(A,"boneTexture",jn.boneTexture,G))}me.isBatchedMesh&&(Tn.setOptional(A,me,"batchingTexture"),Tn.setValue(A,"batchingTexture",me._matricesTexture,G),Tn.setOptional(A,me,"batchingIdTexture"),Tn.setValue(A,"batchingIdTexture",me._indirectTexture,G),Tn.setOptional(A,me,"batchingColorTexture"),me._colorsTexture!==null&&Tn.setValue(A,"batchingColorTexture",me._colorsTexture,G));const Jl=Te.morphAttributes;if((Jl.position!==void 0||Jl.normal!==void 0||Jl.color!==void 0)&&yt.update(me,Te,Wr),(jr||Qe.receiveShadow!==me.receiveShadow)&&(Qe.receiveShadow=me.receiveShadow,Tn.setValue(A,"receiveShadow",me.receiveShadow)),be.isMeshGouraudMaterial&&be.envMap!==null&&(Ai.envMap.value=ut,Ai.flipEnvMap.value=ut.isCubeTexture&&ut.isRenderTargetTexture===!1?-1:1),be.isMeshStandardMaterial&&be.envMap===null&&fe.environment!==null&&(Ai.envMapIntensity.value=fe.environmentIntensity),jr&&(Tn.setValue(A,"toneMappingExposure",T.toneMappingExposure),Qe.needsLights&&Jy(Ai,Zl),Be&&be.fog===!0&&Oe.refreshFogUniforms(Ai,Be),Oe.refreshMaterialUniforms(Ai,be,z,B,_.state.transmissionRenderTarget[q.id]),J0.upload(A,$m(Qe),Ai,G)),be.isShaderMaterial&&be.uniformsNeedUpdate===!0&&(J0.upload(A,$m(Qe),Ai,G),be.uniformsNeedUpdate=!1),be.isSpriteMaterial&&Tn.setValue(A,"center",me.center),Tn.setValue(A,"modelViewMatrix",me.modelViewMatrix),Tn.setValue(A,"normalMatrix",me.normalMatrix),Tn.setValue(A,"modelMatrix",me.matrixWorld),be.isShaderMaterial||be.isRawShaderMaterial){const jn=be.uniformsGroups;for(let Ko=0,Yo=jn.length;Ko0&&G.useMultisampledRTT(q)===!1?me=ae.get(q).__webglMultisampledFramebuffer:Array.isArray(kt)?me=kt[Te]:me=kt,U.copy(q.viewport),L.copy(q.scissor),P=q.scissorTest}else U.copy(j).multiplyScalar(z).floor(),L.copy(Y).multiplyScalar(z).floor(),P=ge;if($.bindFramebuffer(A.FRAMEBUFFER,me)&&be&&$.drawBuffers(q,me),$.viewport(U),$.scissor(L),$.setScissorTest(P),Be){const ut=ae.get(q.texture);A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+fe,ut.__webglTexture,Te)}else if(Ye){const ut=ae.get(q.texture),At=fe||0;A.framebufferTextureLayer(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,ut.__webglTexture,Te||0,At)}M=-1},this.readRenderTargetPixels=function(q,fe,Te,be,me,Be,Ye){if(!(q&&q.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let ct=ae.get(q).__webglFramebuffer;if(q.isWebGLCubeRenderTarget&&Ye!==void 0&&(ct=ct[Ye]),ct){$.bindFramebuffer(A.FRAMEBUFFER,ct);try{const ut=q.texture,At=ut.format,kt=ut.type;if(!X.textureFormatReadable(At)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!X.textureTypeReadable(kt)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}fe>=0&&fe<=q.width-be&&Te>=0&&Te<=q.height-me&&A.readPixels(fe,Te,be,me,Rt.convert(At),Rt.convert(kt),Be)}finally{const ut=O!==null?ae.get(O).__webglFramebuffer:null;$.bindFramebuffer(A.FRAMEBUFFER,ut)}}},this.readRenderTargetPixelsAsync=async function(q,fe,Te,be,me,Be,Ye){if(!(q&&q.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let ct=ae.get(q).__webglFramebuffer;if(q.isWebGLCubeRenderTarget&&Ye!==void 0&&(ct=ct[Ye]),ct){const ut=q.texture,At=ut.format,kt=ut.type;if(!X.textureFormatReadable(At))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!X.textureTypeReadable(kt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(fe>=0&&fe<=q.width-be&&Te>=0&&Te<=q.height-me){$.bindFramebuffer(A.FRAMEBUFFER,ct);const ht=A.createBuffer();A.bindBuffer(A.PIXEL_PACK_BUFFER,ht),A.bufferData(A.PIXEL_PACK_BUFFER,Be.byteLength,A.STREAM_READ),A.readPixels(fe,Te,be,me,Rt.convert(At),Rt.convert(kt),0);const Bt=O!==null?ae.get(O).__webglFramebuffer:null;$.bindFramebuffer(A.FRAMEBUFFER,Bt);const nn=A.fenceSync(A.SYNC_GPU_COMMANDS_COMPLETE,0);return A.flush(),await I5(A,nn,4),A.bindBuffer(A.PIXEL_PACK_BUFFER,ht),A.getBufferSubData(A.PIXEL_PACK_BUFFER,0,Be),A.deleteBuffer(ht),A.deleteSync(nn),Be}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(q,fe=null,Te=0){q.isTexture!==!0&&(Zd("WebGLRenderer: copyFramebufferToTexture function signature has changed."),fe=arguments[0]||null,q=arguments[1]);const be=Math.pow(2,-Te),me=Math.floor(q.image.width*be),Be=Math.floor(q.image.height*be),Ye=fe!==null?fe.x:0,ct=fe!==null?fe.y:0;G.setTexture2D(q,0),A.copyTexSubImage2D(A.TEXTURE_2D,Te,0,0,Ye,ct,me,Be),$.unbindTexture()},this.copyTextureToTexture=function(q,fe,Te=null,be=null,me=0){q.isTexture!==!0&&(Zd("WebGLRenderer: copyTextureToTexture function signature has changed."),be=arguments[0]||null,q=arguments[1],fe=arguments[2],me=arguments[3]||0,Te=null);let Be,Ye,ct,ut,At,kt,ht,Bt,nn;const Et=q.isCompressedTexture?q.mipmaps[me]:q.image;Te!==null?(Be=Te.max.x-Te.min.x,Ye=Te.max.y-Te.min.y,ct=Te.isBox3?Te.max.z-Te.min.z:1,ut=Te.min.x,At=Te.min.y,kt=Te.isBox3?Te.min.z:0):(Be=Et.width,Ye=Et.height,ct=Et.depth||1,ut=0,At=0,kt=0),be!==null?(ht=be.x,Bt=be.y,nn=be.z):(ht=0,Bt=0,nn=0);const Pt=Rt.convert(fe.format),zt=Rt.convert(fe.type);let Qe;fe.isData3DTexture?(G.setTexture3D(fe,0),Qe=A.TEXTURE_3D):fe.isDataArrayTexture||fe.isCompressedArrayTexture?(G.setTexture2DArray(fe,0),Qe=A.TEXTURE_2D_ARRAY):(G.setTexture2D(fe,0),Qe=A.TEXTURE_2D),A.pixelStorei(A.UNPACK_FLIP_Y_WEBGL,fe.flipY),A.pixelStorei(A.UNPACK_PREMULTIPLY_ALPHA_WEBGL,fe.premultiplyAlpha),A.pixelStorei(A.UNPACK_ALIGNMENT,fe.unpackAlignment);const Wn=A.getParameter(A.UNPACK_ROW_LENGTH),qt=A.getParameter(A.UNPACK_IMAGE_HEIGHT),Wr=A.getParameter(A.UNPACK_SKIP_PIXELS),cr=A.getParameter(A.UNPACK_SKIP_ROWS),jr=A.getParameter(A.UNPACK_SKIP_IMAGES);A.pixelStorei(A.UNPACK_ROW_LENGTH,Et.width),A.pixelStorei(A.UNPACK_IMAGE_HEIGHT,Et.height),A.pixelStorei(A.UNPACK_SKIP_PIXELS,ut),A.pixelStorei(A.UNPACK_SKIP_ROWS,At),A.pixelStorei(A.UNPACK_SKIP_IMAGES,kt);const Zl=q.isDataArrayTexture||q.isData3DTexture,Tn=fe.isDataArrayTexture||fe.isData3DTexture;if(q.isRenderTargetTexture||q.isDepthTexture){const Ai=ae.get(q),Jl=ae.get(fe),jn=ae.get(Ai.__renderTarget),Ko=ae.get(Jl.__renderTarget);$.bindFramebuffer(A.READ_FRAMEBUFFER,jn.__webglFramebuffer),$.bindFramebuffer(A.DRAW_FRAMEBUFFER,Ko.__webglFramebuffer);for(let Yo=0;Yo0&&(n.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(n.object.backgroundIntensity=this.backgroundIntensity),n.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(n.object.environmentIntensity=this.environmentIntensity),n.object.environmentRotation=this.environmentRotation.toArray(),n}}class fO extends or{constructor(e=null,n=1,r=1,i,s,o,a,l,c=vr,u=vr,h,p){super(null,o,a,l,c,u,i,s,h,p),this.isDataTexture=!0,this.image={data:e,width:n,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class WH extends Ul{static get type(){return"PointsMaterial"}constructor(e){super(),this.isPointsMaterial=!0,this.color=new cn(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const MR=new ar,SE=new lT,u0=new Rv,h0=new xe;class jH extends as{constructor(e=new Bo,n=new WH){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=n,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,n){const r=this.geometry,i=this.matrixWorld,s=e.params.Points.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),u0.copy(r.boundingSphere),u0.applyMatrix4(i),u0.radius+=s,e.ray.intersectsSphere(u0)===!1)return;MR.copy(i).invert(),SE.copy(e.ray).applyMatrix4(MR);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=a*a,c=r.index,h=r.attributes.position;if(c!==null){const p=Math.max(0,o.start),m=Math.min(c.count,o.start+o.count);for(let g=p,v=m;g0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;si.far)return;s.push({distance:c,distanceToRay:Math.sqrt(a),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class $H extends or{constructor(e,n,r,i,s,o,a,l,c){super(e,n,r,i,s,o,a,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class qH extends Ul{static get type(){return"MeshNormalMaterial"}constructor(e){super(),this.isMeshNormalMaterial=!0,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=YI,this.normalScale=new St(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}const RR={enabled:!1,files:{},add:function(t,e){this.enabled!==!1&&(this.files[t]=e)},get:function(t){if(this.enabled!==!1)return this.files[t]},remove:function(t){delete this.files[t]},clear:function(){this.files={}}};class XH{constructor(e,n,r){const i=this;let s=!1,o=0,a=0,l;const c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=n,this.onError=r,this.itemStart=function(u){a++,s===!1&&i.onStart!==void 0&&i.onStart(u,o,a),s=!0},this.itemEnd=function(u){o++,i.onProgress!==void 0&&i.onProgress(u,o,a),o===a&&(s=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(u){i.onError!==void 0&&i.onError(u)},this.resolveURL=function(u){return l?l(u):u},this.setURLModifier=function(u){return l=u,this},this.addHandler=function(u,h){return c.push(u,h),this},this.removeHandler=function(u){const h=c.indexOf(u);return h!==-1&&c.splice(h,2),this},this.getHandler=function(u){for(let h=0,p=c.length;h=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,n){return n.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,OR).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:bv}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=bv);var dO={exports:{}},nh={};/** + * @license React + * react-reconciler-constants.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */nh.ConcurrentRoot=1;nh.ContinuousEventPriority=4;nh.DefaultEventPriority=16;nh.DiscreteEventPriority=1;nh.IdleEventPriority=536870912;nh.LegacyRoot=0;dO.exports=nh;var lf=dO.exports;function eG(t){let e;const n=new Set,r=(c,u)=>{const h=typeof c=="function"?c(e):c;if(h!==e){const p=e;e=u?h:Object.assign({},e,h),n.forEach(m=>m(e,p))}},i=()=>e,s=(c,u=i,h=Object.is)=>{console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware");let p=u(e);function m(){const g=u(e);if(!h(p,g)){const v=p;c(p=g,v)}}return n.add(m),()=>n.delete(m)},l={setState:r,getState:i,subscribe:(c,u,h)=>u||h?s(c,u,h):(n.add(c),()=>n.delete(c)),destroy:()=>n.clear()};return e=t(r,i,l),l}const tG=typeof window>"u"||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent),LR=tG?Ne.useEffect:Ne.useLayoutEffect;function nG(t){const e=typeof t=="function"?eG(t):t,n=(r=e.getState,i=Object.is)=>{const[,s]=Ne.useReducer(y=>y+1,0),o=e.getState(),a=Ne.useRef(o),l=Ne.useRef(r),c=Ne.useRef(i),u=Ne.useRef(!1),h=Ne.useRef();h.current===void 0&&(h.current=r(o));let p,m=!1;(a.current!==o||l.current!==r||c.current!==i||u.current)&&(p=r(o),m=!i(h.current,p)),LR(()=>{m&&(h.current=p),a.current=o,l.current=r,c.current=i,u.current=!1});const g=Ne.useRef(o);LR(()=>{const y=()=>{try{const S=e.getState(),E=l.current(S);c.current(h.current,E)||(a.current=S,h.current=E,s())}catch{u.current=!0,s()}},_=e.subscribe(y);return e.getState()!==g.current&&y(),_},[]);const v=m?p:h.current;return Ne.useDebugValue(v),v};return Object.assign(n,e),n[Symbol.iterator]=function(){console.warn("[useStore, api] = create() is deprecated and will be removed in v4");const r=[n,e];return{next(){const i=r.length<=0;return{value:r.shift(),done:i}}}},n}const rG=t=>typeof t=="object"&&typeof t.then=="function",Ru=[];function pO(t,e,n=(r,i)=>r===i){if(t===e)return!0;if(!t||!e)return!1;const r=t.length;if(e.length!==r)return!1;for(let i=0;i0&&(s.timeout&&clearTimeout(s.timeout),s.timeout=setTimeout(s.remove,r.lifespan)),s.response;if(!n)throw s.promise}const i={keys:e,equal:r.equal,remove:()=>{const s=Ru.indexOf(i);s!==-1&&Ru.splice(s,1)},promise:(rG(t)?t:t(...e)).then(s=>{i.response=s,r.lifespan&&r.lifespan>0&&(i.timeout=setTimeout(i.remove,r.lifespan))}).catch(s=>i.error=s)};if(Ru.push(i),!n)throw i.promise}const iG=(t,e,n)=>mO(t,e,!1,n),sG=(t,e,n)=>void mO(t,e,!0,n),oG=t=>{if(t===void 0||t.length===0)Ru.splice(0,Ru.length);else{const e=Ru.find(n=>pO(t,n.keys,n.equal));e&&e.remove()}};var gO={exports:{}},_O={exports:{}},vO={};/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(t){function e(z,W){var K=z.length;z.push(W);e:for(;0>>1,Y=z[j];if(0>>1;ji(re,K))wei(Ae,re)?(z[j]=Ae,z[we]=K,j=we):(z[j]=re,z[Q]=K,j=Q);else if(wei(Ae,K))z[j]=Ae,z[we]=K,j=we;else break e}}return W}function i(z,W){var K=z.sortIndex-W.sortIndex;return K!==0?K:z.id-W.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();t.unstable_now=function(){return o.now()-a}}var l=[],c=[],u=1,h=null,p=3,m=!1,g=!1,v=!1,y=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(z){for(var W=n(c);W!==null;){if(W.callback===null)r(c);else if(W.startTime<=z)r(c),W.sortIndex=W.expirationTime,e(l,W);else break;W=n(c)}}function T(z){if(v=!1,E(z),!g)if(n(l)!==null)g=!0,V(N);else{var W=n(c);W!==null&&B(T,W.startTime-z)}}function N(z,W){g=!1,v&&(v=!1,_(O),O=-1),m=!0;var K=p;try{for(E(W),h=n(l);h!==null&&(!(h.expirationTime>W)||z&&!U());){var j=h.callback;if(typeof j=="function"){h.callback=null,p=h.priorityLevel;var Y=j(h.expirationTime<=W);W=t.unstable_now(),typeof Y=="function"?h.callback=Y:h===n(l)&&r(l),E(W)}else r(l);h=n(l)}if(h!==null)var ge=!0;else{var Q=n(c);Q!==null&&B(T,Q.startTime-W),ge=!1}return ge}finally{h=null,p=K,m=!1}}var R=!1,C=null,O=-1,M=5,I=-1;function U(){return!(t.unstable_now()-Iz||125j?(z.sortIndex=K,e(c,z),n(l)===null&&z===n(c)&&(v?(_(O),O=-1):v=!0,B(T,K-j))):(z.sortIndex=Y,e(l,z),g||m||(g=!0,V(N))),z},t.unstable_shouldYield=U,t.unstable_wrapCallback=function(z){var W=p;return function(){var K=p;p=W;try{return z.apply(this,arguments)}finally{p=K}}}})(vO);_O.exports=vO;var wE=_O.exports;/** + * @license React + * react-reconciler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var aG=function(e){var n={},r=Ne,i=wE,s=Object.assign;function o(f){for(var d="https://reactjs.org/docs/error-decoder.html?invariant="+f,x=1;xoe||k[J]!==F[oe]){var Re=` +`+k[J].replace(" at new "," at ");return f.displayName&&Re.includes("")&&(Re=Re.replace("",f.displayName)),Re}while(1<=J&&0<=oe);break}}}finally{ut=!1,Error.prepareStackTrace=x}return(f=f?f.displayName||f.name:"")?ct(f):""}var kt=Object.prototype.hasOwnProperty,ht=[],Bt=-1;function nn(f){return{current:f}}function Et(f){0>Bt||(f.current=ht[Bt],ht[Bt]=null,Bt--)}function Pt(f,d){Bt++,ht[Bt]=f.current,f.current=d}var zt={},Qe=nn(zt),Wn=nn(!1),qt=zt;function Wr(f,d){var x=f.type.contextTypes;if(!x)return zt;var w=f.stateNode;if(w&&w.__reactInternalMemoizedUnmaskedChildContext===d)return w.__reactInternalMemoizedMaskedChildContext;var k={},F;for(F in x)k[F]=d[F];return w&&(f=f.stateNode,f.__reactInternalMemoizedUnmaskedChildContext=d,f.__reactInternalMemoizedMaskedChildContext=k),k}function cr(f){return f=f.childContextTypes,f!=null}function jr(){Et(Wn),Et(Qe)}function Zl(f,d,x){if(Qe.current!==zt)throw Error(o(168));Pt(Qe,d),Pt(Wn,x)}function Tn(f,d,x){var w=f.stateNode;if(d=d.childContextTypes,typeof w.getChildContext!="function")return x;w=w.getChildContext();for(var k in w)if(!(k in d))throw Error(o(108,O(f)||"Unknown",k));return s({},x,w)}function Ai(f){return f=(f=f.stateNode)&&f.__reactInternalMemoizedMergedChildContext||zt,qt=Qe.current,Pt(Qe,f),Pt(Wn,Wn.current),!0}function Jl(f,d,x){var w=f.stateNode;if(!w)throw Error(o(169));x?(f=Tn(f,d,qt),w.__reactInternalMemoizedMergedChildContext=f,Et(Wn),Et(Qe),Pt(Qe,f)):Et(Wn),Pt(Wn,x)}var jn=Math.clz32?Math.clz32:Km,Ko=Math.log,Yo=Math.LN2;function Km(f){return f>>>=0,f===0?32:31-(Ko(f)/Yo|0)|0}var Ym=64,Zm=4194304;function _d(f){switch(f&-f){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return f&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return f&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return f}}function Jm(f,d){var x=f.pendingLanes;if(x===0)return 0;var w=0,k=f.suspendedLanes,F=f.pingedLanes,J=x&268435455;if(J!==0){var oe=J&~k;oe!==0?w=_d(oe):(F&=J,F!==0&&(w=_d(F)))}else J=x&~k,J!==0?w=_d(J):F!==0&&(w=_d(F));if(w===0)return 0;if(d!==0&&d!==w&&!(d&k)&&(k=w&-w,F=d&-d,k>=F||k===16&&(F&4194240)!==0))return d;if(w&4&&(w|=x&16),d=f.entangledLanes,d!==0)for(f=f.entanglements,d&=w;0x;x++)d.push(f);return d}function vd(f,d,x){f.pendingLanes|=d,d!==536870912&&(f.suspendedLanes=0,f.pingedLanes=0),f=f.eventTimes,d=31-jn(d),f[d]=x}function vF(f,d){var x=f.pendingLanes&~d;f.pendingLanes=d,f.suspendedLanes=0,f.pingedLanes=0,f.expiredLanes&=d,f.mutableReadLanes&=d,f.entangledLanes&=d,d=f.entanglements;var w=f.eventTimes;for(f=f.expirationTimes;0>=J,k-=J,Xa=1<<32-jn(d)+k|x<mn?(Xr=Ot,Ot=null):Xr=Ot.sibling;var gn=xt(Se,Ot,Me[mn],tt);if(gn===null){Ot===null&&(Ot=Xr);break}f&&Ot&&gn.alternate===null&&d(Se,Ot),de=F(gn,de,mn),Ut===null?pt=gn:Ut.sibling=gn,Ut=gn,Ot=Xr}if(mn===Me.length)return x(Se,Ot),$n&&Jc(Se,mn),pt;if(Ot===null){for(;mnmn?(Xr=Ot,Ot=null):Xr=Ot.sibling;var oc=xt(Se,Ot,gn.value,tt);if(oc===null){Ot===null&&(Ot=Xr);break}f&&Ot&&oc.alternate===null&&d(Se,Ot),de=F(oc,de,mn),Ut===null?pt=oc:Ut.sibling=oc,Ut=oc,Ot=Xr}if(gn.done)return x(Se,Ot),$n&&Jc(Se,mn),pt;if(Ot===null){for(;!gn.done;mn++,gn=Me.next())gn=It(Se,gn.value,tt),gn!==null&&(de=F(gn,de,mn),Ut===null?pt=gn:Ut.sibling=gn,Ut=gn);return $n&&Jc(Se,mn),pt}for(Ot=w(Se,Ot);!gn.done;mn++,gn=Me.next())gn=Nn(Ot,Se,mn,gn.value,tt),gn!==null&&(f&&gn.alternate!==null&&Ot.delete(gn.key===null?mn:gn.key),de=F(gn,de,mn),Ut===null?pt=gn:Ut.sibling=gn,Ut=gn);return f&&Ot.forEach(function(rB){return d(Se,rB)}),$n&&Jc(Se,mn),pt}function Ws(Se,de,Me,tt){if(typeof Me=="object"&&Me!==null&&Me.type===u&&Me.key===null&&(Me=Me.props.children),typeof Me=="object"&&Me!==null){switch(Me.$$typeof){case l:e:{for(var pt=Me.key,Ut=de;Ut!==null;){if(Ut.key===pt){if(pt=Me.type,pt===u){if(Ut.tag===7){x(Se,Ut.sibling),de=k(Ut,Me.props.children),de.return=Se,Se=de;break e}}else if(Ut.elementType===pt||typeof pt=="object"&&pt!==null&&pt.$$typeof===E&&cM(pt)===Ut.type){x(Se,Ut.sibling),de=k(Ut,Me.props),de.ref=Sd(Se,Ut,Me),de.return=Se,Se=de;break e}x(Se,Ut);break}else d(Se,Ut);Ut=Ut.sibling}Me.type===u?(de=su(Me.props.children,Se.mode,tt,Me.key),de.return=Se,Se=de):(tt=zg(Me.type,Me.key,Me.props,null,Se.mode,tt),tt.ref=Sd(Se,de,Me),tt.return=Se,Se=tt)}return J(Se);case c:e:{for(Ut=Me.key;de!==null;){if(de.key===Ut)if(de.tag===4&&de.stateNode.containerInfo===Me.containerInfo&&de.stateNode.implementation===Me.implementation){x(Se,de.sibling),de=k(de,Me.children||[]),de.return=Se,Se=de;break e}else{x(Se,de);break}else d(Se,de);de=de.sibling}de=tS(Me,Se.mode,tt),de.return=Se,Se=de}return J(Se);case E:return Ut=Me._init,Ws(Se,de,Ut(Me._payload),tt)}if(H(Me))return gt(Se,de,Me,tt);if(R(Me))return gi(Se,de,Me,tt);cg(Se,Me)}return typeof Me=="string"&&Me!==""||typeof Me=="number"?(Me=""+Me,de!==null&&de.tag===6?(x(Se,de.sibling),de=k(de,Me),de.return=Se,Se=de):(x(Se,de),de=eS(Me,Se.mode,tt),de.return=Se,Se=de),J(Se)):x(Se,de)}return Ws}var wh=uM(!0),hM=uM(!1),Ed={},zs=nn(Ed),wd=nn(Ed),Th=nn(Ed);function ta(f){if(f===Ed)throw Error(o(174));return f}function vx(f,d){Pt(Th,d),Pt(wd,f),Pt(zs,Ed),f=B(d),Et(zs),Pt(zs,f)}function bh(){Et(zs),Et(wd),Et(Th)}function fM(f){var d=ta(Th.current),x=ta(zs.current);d=z(x,f.type,d),x!==d&&(Pt(wd,f),Pt(zs,d))}function yx(f){wd.current===f&&(Et(zs),Et(wd))}var Kn=nn(0);function ug(f){for(var d=f;d!==null;){if(d.tag===13){var x=d.memoizedState;if(x!==null&&(x=x.dehydrated,x===null||Xo(x)||Yc(x)))return d}else if(d.tag===19&&d.memoizedProps.revealOrder!==void 0){if(d.flags&128)return d}else if(d.child!==null){d.child.return=d,d=d.child;continue}if(d===f)break;for(;d.sibling===null;){if(d.return===null||d.return===f)return null;d=d.return}d.sibling.return=d.return,d=d.sibling}return null}var xx=[];function Sx(){for(var f=0;fx?x:4,f(!0);var w=Vs.transition;Vs.transition={};try{f(!1),d()}finally{pn=x,Vs.transition=w}}function AM(){return na().memoizedState}function NF(f,d,x){var w=rc(f);x={lane:w,action:x,hasEagerState:!1,eagerState:null,next:null},MM(f)?CM(d,x):(RM(f,d,x),x=Ci(),f=Hs(f,w,x),f!==null&&NM(f,d,w))}function kF(f,d,x){var w=rc(f),k={lane:w,action:x,hasEagerState:!1,eagerState:null,next:null};if(MM(f))CM(d,k);else{RM(f,d,k);var F=f.alternate;if(f.lanes===0&&(F===null||F.lanes===0)&&(F=d.lastRenderedReducer,F!==null))try{var J=d.lastRenderedState,oe=F(J,x);if(k.hasEagerState=!0,k.eagerState=oe,Jo(oe,J))return}catch{}finally{}x=Ci(),f=Hs(f,w,x),f!==null&&NM(f,d,w)}}function MM(f){var d=f.alternate;return f===er||d!==null&&d===er}function CM(f,d){Td=fg=!0;var x=f.pending;x===null?d.next=d:(d.next=x.next,x.next=d),f.pending=d}function RM(f,d,x){xr!==null&&f.mode&1&&!(Vt&2)?(f=d.interleaved,f===null?(x.next=x,ea===null?ea=[d]:ea.push(d)):(x.next=f.next,f.next=x),d.interleaved=x):(f=d.pending,f===null?x.next=x:(x.next=f.next,f.next=x),d.pending=x)}function NM(f,d,x){if(x&4194240){var w=d.lanes;w&=f.pendingLanes,x|=w,d.lanes=x,tx(f,x)}}var _g={readContext:Us,useCallback:pi,useContext:pi,useEffect:pi,useImperativeHandle:pi,useInsertionEffect:pi,useLayoutEffect:pi,useMemo:pi,useReducer:pi,useRef:pi,useState:pi,useDebugValue:pi,useDeferredValue:pi,useTransition:pi,useMutableSource:pi,useSyncExternalStore:pi,useId:pi,unstable_isNewReconciler:!1},IF={readContext:Us,useCallback:function(f,d){return Ya().memoizedState=[f,d===void 0?null:d],f},useContext:Us,useEffect:Ax,useImperativeHandle:function(f,d,x){return x=x!=null?x.concat([f]):null,mg(4194308,4,EM.bind(null,d,f),x)},useLayoutEffect:function(f,d){return mg(4194308,4,f,d)},useInsertionEffect:function(f,d){return mg(4,2,f,d)},useMemo:function(f,d){var x=Ya();return d=d===void 0?null:d,f=f(),x.memoizedState=[f,d],f},useReducer:function(f,d,x){var w=Ya();return d=x!==void 0?x(d):d,w.memoizedState=w.baseState=d,f={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:f,lastRenderedState:d},w.queue=f,f=f.dispatch=NF.bind(null,er,f),[w.memoizedState,f]},useRef:function(f){var d=Ya();return f={current:f},d.memoizedState=f},useState:bx,useDebugValue:Mx,useDeferredValue:function(f){var d=bx(f),x=d[0],w=d[1];return Ax(function(){var k=Vs.transition;Vs.transition={};try{w(f)}finally{Vs.transition=k}},[f]),x},useTransition:function(){var f=bx(!1),d=f[0];return f=RF.bind(null,f[1]),Ya().memoizedState=f,[d,f]},useMutableSource:function(){},useSyncExternalStore:function(f,d,x){var w=er,k=Ya();if($n){if(x===void 0)throw Error(o(407));x=x()}else{if(x=d(),xr===null)throw Error(o(349));Ah&30||mM(w,d,x)}k.memoizedState=x;var F={value:x,getSnapshot:d};return k.queue=F,Ax(_M.bind(null,w,F,f),[f]),w.flags|=2048,Ad(9,gM.bind(null,w,F,x,d),void 0,null),x},useId:function(){var f=Ya(),d=xr.identifierPrefix;if($n){var x=Ka,w=Xa;x=(w&~(1<<32-jn(w)-1)).toString(32)+x,d=":"+d+"R"+x,x=bd++,0$x&&(d.flags|=128,w=!0,Nd(k,!1),d.lanes=4194304)}else{if(!w)if(f=ug(F),f!==null){if(d.flags|=128,w=!0,f=f.updateQueue,f!==null&&(d.updateQueue=f,d.flags|=4),Nd(k,!0),k.tail===null&&k.tailMode==="hidden"&&!F.alternate&&!$n)return mi(d),null}else 2*$r()-k.renderingStartTime>$x&&x!==1073741824&&(d.flags|=128,w=!0,Nd(k,!1),d.lanes=4194304);k.isBackwards?(F.sibling=d.child,d.child=F):(f=k.last,f!==null?f.sibling=F:d.child=F,k.last=F)}return k.tail!==null?(d=k.tail,k.rendering=d,k.tail=d.sibling,k.renderingStartTime=$r(),d.sibling=null,f=Kn.current,Pt(Kn,w?f&1|2:f&1),d):(mi(d),null);case 22:case 23:return Zx(),w=d.memoizedState!==null,f!==null&&f.memoizedState!==null!==w&&(d.flags|=8192),w&&d.mode&1?Es&1073741824&&(mi(d),qe&&d.subtreeFlags&6&&(d.flags|=8192)):mi(d),null;case 24:return null;case 25:return null}throw Error(o(156,d.tag))}var UF=a.ReactCurrentOwner,Ss=!1;function Mi(f,d,x,w){d.child=f===null?hM(d,null,x,w):wh(d,f.child,x,w)}function FM(f,d,x,w,k){x=x.render;var F=d.ref;return yh(d,k),w=wx(f,d,x,w,F,k),x=Tx(),f!==null&&!Ss?(d.updateQueue=f.updateQueue,d.flags&=-2053,f.lanes&=~k,Za(f,d,k)):($n&&x&&dx(d),d.flags|=1,Mi(f,d,w,k),d.child)}function BM(f,d,x,w,k){if(f===null){var F=x.type;return typeof F=="function"&&!Qx(F)&&F.defaultProps===void 0&&x.compare===null&&x.defaultProps===void 0?(d.tag=15,d.type=F,zM(f,d,F,w,k)):(f=zg(x.type,null,w,d,d.mode,k),f.ref=d.ref,f.return=d,d.child=f)}if(F=f.child,!(f.lanes&k)){var J=F.memoizedProps;if(x=x.compare,x=x!==null?x:tg,x(J,w)&&f.ref===d.ref)return Za(f,d,k)}return d.flags|=1,f=sc(F,w),f.ref=d.ref,f.return=d,d.child=f}function zM(f,d,x,w,k){if(f!==null&&tg(f.memoizedProps,w)&&f.ref===d.ref)if(Ss=!1,(f.lanes&k)!==0)f.flags&131072&&(Ss=!0);else return d.lanes=f.lanes,Za(f,d,k);return Nx(f,d,x,w,k)}function VM(f,d,x){var w=d.pendingProps,k=w.children,F=f!==null?f.memoizedState:null;if(w.mode==="hidden")if(!(d.mode&1))d.memoizedState={baseLanes:0,cachePool:null},Pt(Mh,Es),Es|=x;else if(x&1073741824)d.memoizedState={baseLanes:0,cachePool:null},w=F!==null?F.baseLanes:x,Pt(Mh,Es),Es|=w;else return f=F!==null?F.baseLanes|x:x,d.lanes=d.childLanes=1073741824,d.memoizedState={baseLanes:f,cachePool:null},d.updateQueue=null,Pt(Mh,Es),Es|=f,null;else F!==null?(w=F.baseLanes|x,d.memoizedState=null):w=x,Pt(Mh,Es),Es|=w;return Mi(f,d,k,x),d.child}function HM(f,d){var x=d.ref;(f===null&&x!==null||f!==null&&f.ref!==x)&&(d.flags|=512,d.flags|=2097152)}function Nx(f,d,x,w,k){var F=cr(x)?qt:Qe.current;return F=Wr(d,F),yh(d,k),x=wx(f,d,x,w,F,k),w=Tx(),f!==null&&!Ss?(d.updateQueue=f.updateQueue,d.flags&=-2053,f.lanes&=~k,Za(f,d,k)):($n&&w&&dx(d),d.flags|=1,Mi(f,d,x,k),d.child)}function GM(f,d,x,w,k){if(cr(x)){var F=!0;Ai(d)}else F=!1;if(yh(d,k),d.stateNode===null)f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),rM(d,x,w),fx(d,x,w,k),w=!0;else if(f===null){var J=d.stateNode,oe=d.memoizedProps;J.props=oe;var Re=J.context,Fe=x.contextType;typeof Fe=="object"&&Fe!==null?Fe=Us(Fe):(Fe=cr(x)?qt:Qe.current,Fe=Wr(d,Fe));var at=x.getDerivedStateFromProps,It=typeof at=="function"||typeof J.getSnapshotBeforeUpdate=="function";It||typeof J.UNSAFE_componentWillReceiveProps!="function"&&typeof J.componentWillReceiveProps!="function"||(oe!==w||Re!==Fe)&&iM(d,J,w,Fe),Ql=!1;var xt=d.memoizedState;J.state=xt,sg(d,w,J,k),Re=d.memoizedState,oe!==w||xt!==Re||Wn.current||Ql?(typeof at=="function"&&(hx(d,x,at,w),Re=d.memoizedState),(oe=Ql||nM(d,x,oe,w,xt,Re,Fe))?(It||typeof J.UNSAFE_componentWillMount!="function"&&typeof J.componentWillMount!="function"||(typeof J.componentWillMount=="function"&&J.componentWillMount(),typeof J.UNSAFE_componentWillMount=="function"&&J.UNSAFE_componentWillMount()),typeof J.componentDidMount=="function"&&(d.flags|=4194308)):(typeof J.componentDidMount=="function"&&(d.flags|=4194308),d.memoizedProps=w,d.memoizedState=Re),J.props=w,J.state=Re,J.context=Fe,w=oe):(typeof J.componentDidMount=="function"&&(d.flags|=4194308),w=!1)}else{J=d.stateNode,JA(f,d),oe=d.memoizedProps,Fe=d.type===d.elementType?oe:po(d.type,oe),J.props=Fe,It=d.pendingProps,xt=J.context,Re=x.contextType,typeof Re=="object"&&Re!==null?Re=Us(Re):(Re=cr(x)?qt:Qe.current,Re=Wr(d,Re));var Nn=x.getDerivedStateFromProps;(at=typeof Nn=="function"||typeof J.getSnapshotBeforeUpdate=="function")||typeof J.UNSAFE_componentWillReceiveProps!="function"&&typeof J.componentWillReceiveProps!="function"||(oe!==It||xt!==Re)&&iM(d,J,w,Re),Ql=!1,xt=d.memoizedState,J.state=xt,sg(d,w,J,k);var gt=d.memoizedState;oe!==It||xt!==gt||Wn.current||Ql?(typeof Nn=="function"&&(hx(d,x,Nn,w),gt=d.memoizedState),(Fe=Ql||nM(d,x,Fe,w,xt,gt,Re)||!1)?(at||typeof J.UNSAFE_componentWillUpdate!="function"&&typeof J.componentWillUpdate!="function"||(typeof J.componentWillUpdate=="function"&&J.componentWillUpdate(w,gt,Re),typeof J.UNSAFE_componentWillUpdate=="function"&&J.UNSAFE_componentWillUpdate(w,gt,Re)),typeof J.componentDidUpdate=="function"&&(d.flags|=4),typeof J.getSnapshotBeforeUpdate=="function"&&(d.flags|=1024)):(typeof J.componentDidUpdate!="function"||oe===f.memoizedProps&&xt===f.memoizedState||(d.flags|=4),typeof J.getSnapshotBeforeUpdate!="function"||oe===f.memoizedProps&&xt===f.memoizedState||(d.flags|=1024),d.memoizedProps=w,d.memoizedState=gt),J.props=w,J.state=gt,J.context=Re,w=Fe):(typeof J.componentDidUpdate!="function"||oe===f.memoizedProps&&xt===f.memoizedState||(d.flags|=4),typeof J.getSnapshotBeforeUpdate!="function"||oe===f.memoizedProps&&xt===f.memoizedState||(d.flags|=1024),w=!1)}return kx(f,d,x,w,F,k)}function kx(f,d,x,w,k,F){HM(f,d);var J=(d.flags&128)!==0;if(!w&&!J)return k&&Jl(d,x,!1),Za(f,d,F);w=d.stateNode,UF.current=d;var oe=J&&typeof x.getDerivedStateFromError!="function"?null:w.render();return d.flags|=1,f!==null&&J?(d.child=wh(d,f.child,null,F),d.child=wh(d,null,oe,F)):Mi(f,d,oe,F),d.memoizedState=w.state,k&&Jl(d,x,!0),d.child}function WM(f){var d=f.stateNode;d.pendingContext?Zl(f,d.pendingContext,d.pendingContext!==d.context):d.context&&Zl(f,d.context,!1),vx(f,d.containerInfo)}function jM(f,d,x,w,k){return Eh(),_x(k),d.flags|=256,Mi(f,d,x,w),d.child}var xg={dehydrated:null,treeContext:null,retryLane:0};function Sg(f){return{baseLanes:f,cachePool:null}}function $M(f,d,x){var w=d.pendingProps,k=Kn.current,F=!1,J=(d.flags&128)!==0,oe;if((oe=J)||(oe=f!==null&&f.memoizedState===null?!1:(k&2)!==0),oe?(F=!0,d.flags&=-129):(f===null||f.memoizedState!==null)&&(k|=1),Pt(Kn,k&1),f===null)return gx(d),f=d.memoizedState,f!==null&&(f=f.dehydrated,f!==null)?(d.mode&1?Yc(f)?d.lanes=8:d.lanes=1073741824:d.lanes=1,null):(k=w.children,f=w.fallback,F?(w=d.mode,F=d.child,k={mode:"hidden",children:k},!(w&1)&&F!==null?(F.childLanes=0,F.pendingProps=k):F=Vg(k,w,0,null),f=su(f,w,x,null),F.return=d,f.return=d,F.sibling=f,d.child=F,d.child.memoizedState=Sg(x),d.memoizedState=xg,f):Ix(d,k));if(k=f.memoizedState,k!==null){if(oe=k.dehydrated,oe!==null){if(J)return d.flags&256?(d.flags&=-257,Eg(f,d,x,Error(o(422)))):d.memoizedState!==null?(d.child=f.child,d.flags|=128,null):(F=w.fallback,k=d.mode,w=Vg({mode:"visible",children:w.children},k,0,null),F=su(F,k,x,null),F.flags|=2,w.return=d,F.return=d,w.sibling=F,d.child=w,d.mode&1&&wh(d,f.child,null,x),d.child.memoizedState=Sg(x),d.memoizedState=xg,F);if(!(d.mode&1))d=Eg(f,d,x,null);else if(Yc(oe))d=Eg(f,d,x,Error(o(419)));else if(w=(x&f.childLanes)!==0,Ss||w){if(w=xr,w!==null){switch(x&-x){case 4:F=2;break;case 16:F=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:F=32;break;case 536870912:F=268435456;break;default:F=0}w=F&(w.suspendedLanes|x)?0:F,w!==0&&w!==k.retryLane&&(k.retryLane=w,Hs(f,w,-1))}Jx(),d=Eg(f,d,x,Error(o(421)))}else Xo(oe)?(d.flags|=128,d.child=f.child,d=YF.bind(null,f),Wm(oe,d),d=null):(x=k.treeContext,De&&(xs=_h(oe),ys=d,$n=!0,mo=null,yd=!1,x!==null&&(Fs[Bs++]=Xa,Fs[Bs++]=Ka,Fs[Bs++]=Zc,Xa=x.id,Ka=x.overflow,Zc=d)),d=Ix(d,d.pendingProps.children),d.flags|=4096);return d}return F?(w=XM(f,d,w.children,w.fallback,x),F=d.child,k=f.child.memoizedState,F.memoizedState=k===null?Sg(x):{baseLanes:k.baseLanes|x,cachePool:null},F.childLanes=f.childLanes&~x,d.memoizedState=xg,w):(x=qM(f,d,w.children,x),d.memoizedState=null,x)}return F?(w=XM(f,d,w.children,w.fallback,x),F=d.child,k=f.child.memoizedState,F.memoizedState=k===null?Sg(x):{baseLanes:k.baseLanes|x,cachePool:null},F.childLanes=f.childLanes&~x,d.memoizedState=xg,w):(x=qM(f,d,w.children,x),d.memoizedState=null,x)}function Ix(f,d){return d=Vg({mode:"visible",children:d},f.mode,0,null),d.return=f,f.child=d}function qM(f,d,x,w){var k=f.child;return f=k.sibling,x=sc(k,{mode:"visible",children:x}),!(d.mode&1)&&(x.lanes=w),x.return=d,x.sibling=null,f!==null&&(w=d.deletions,w===null?(d.deletions=[f],d.flags|=16):w.push(f)),d.child=x}function XM(f,d,x,w,k){var F=d.mode;f=f.child;var J=f.sibling,oe={mode:"hidden",children:x};return!(F&1)&&d.child!==f?(x=d.child,x.childLanes=0,x.pendingProps=oe,d.deletions=null):(x=sc(f,oe),x.subtreeFlags=f.subtreeFlags&14680064),J!==null?w=sc(J,w):(w=su(w,F,k,null),w.flags|=2),w.return=d,x.return=d,x.sibling=w,d.child=x,w}function Eg(f,d,x,w){return w!==null&&_x(w),wh(d,f.child,null,x),f=Ix(d,d.pendingProps.children),f.flags|=2,d.memoizedState=null,f}function KM(f,d,x){f.lanes|=d;var w=f.alternate;w!==null&&(w.lanes|=d),cx(f.return,d,x)}function Ox(f,d,x,w,k){var F=f.memoizedState;F===null?f.memoizedState={isBackwards:d,rendering:null,renderingStartTime:0,last:w,tail:x,tailMode:k}:(F.isBackwards=d,F.rendering=null,F.renderingStartTime=0,F.last=w,F.tail=x,F.tailMode=k)}function YM(f,d,x){var w=d.pendingProps,k=w.revealOrder,F=w.tail;if(Mi(f,d,w.children,x),w=Kn.current,w&2)w=w&1|2,d.flags|=128;else{if(f!==null&&f.flags&128)e:for(f=d.child;f!==null;){if(f.tag===13)f.memoizedState!==null&&KM(f,x,d);else if(f.tag===19)KM(f,x,d);else if(f.child!==null){f.child.return=f,f=f.child;continue}if(f===d)break e;for(;f.sibling===null;){if(f.return===null||f.return===d)break e;f=f.return}f.sibling.return=f.return,f=f.sibling}w&=1}if(Pt(Kn,w),!(d.mode&1))d.memoizedState=null;else switch(k){case"forwards":for(x=d.child,k=null;x!==null;)f=x.alternate,f!==null&&ug(f)===null&&(k=x),x=x.sibling;x=k,x===null?(k=d.child,d.child=null):(k=x.sibling,x.sibling=null),Ox(d,!1,k,x,F);break;case"backwards":for(x=null,k=d.child,d.child=null;k!==null;){if(f=k.alternate,f!==null&&ug(f)===null){d.child=k;break}f=k.sibling,k.sibling=x,x=k,k=f}Ox(d,!0,x,null,F);break;case"together":Ox(d,!1,null,null,void 0);break;default:d.memoizedState=null}return d.child}function Za(f,d,x){if(f!==null&&(d.dependencies=f.dependencies),Ch|=d.lanes,!(x&d.childLanes))return null;if(f!==null&&d.child!==f.child)throw Error(o(153));if(d.child!==null){for(f=d.child,x=sc(f,f.pendingProps),d.child=x,x.return=d;f.sibling!==null;)f=f.sibling,x=x.sibling=sc(f,f.pendingProps),x.return=d;x.sibling=null}return d.child}function FF(f,d,x){switch(d.tag){case 3:WM(d),Eh();break;case 5:fM(d);break;case 1:cr(d.type)&&Ai(d);break;case 4:vx(d,d.stateNode.containerInfo);break;case 10:ZA(d,d.type._context,d.memoizedProps.value);break;case 13:var w=d.memoizedState;if(w!==null)return w.dehydrated!==null?(Pt(Kn,Kn.current&1),d.flags|=128,null):x&d.child.childLanes?$M(f,d,x):(Pt(Kn,Kn.current&1),f=Za(f,d,x),f!==null?f.sibling:null);Pt(Kn,Kn.current&1);break;case 19:if(w=(x&d.childLanes)!==0,f.flags&128){if(w)return YM(f,d,x);d.flags|=128}var k=d.memoizedState;if(k!==null&&(k.rendering=null,k.tail=null,k.lastEffect=null),Pt(Kn,Kn.current),w)break;return null;case 22:case 23:return d.lanes=0,VM(f,d,x)}return Za(f,d,x)}function BF(f,d){switch(px(d),d.tag){case 1:return cr(d.type)&&jr(),f=d.flags,f&65536?(d.flags=f&-65537|128,d):null;case 3:return bh(),Et(Wn),Et(Qe),Sx(),f=d.flags,f&65536&&!(f&128)?(d.flags=f&-65537|128,d):null;case 5:return yx(d),null;case 13:if(Et(Kn),f=d.memoizedState,f!==null&&f.dehydrated!==null){if(d.alternate===null)throw Error(o(340));Eh()}return f=d.flags,f&65536?(d.flags=f&-65537|128,d):null;case 19:return Et(Kn),null;case 4:return bh(),null;case 10:return lx(d.type._context),null;case 22:case 23:return Zx(),null;case 24:return null;default:return null}}var wg=!1,eu=!1,zF=typeof WeakSet=="function"?WeakSet:Set,Ze=null;function Tg(f,d){var x=f.ref;if(x!==null)if(typeof x=="function")try{x(null)}catch(w){Zi(f,d,w)}else x.current=null}function Lx(f,d,x){try{x()}catch(w){Zi(f,d,w)}}var ZM=!1;function VF(f,d){for(W(f.containerInfo),Ze=d;Ze!==null;)if(f=Ze,d=f.child,(f.subtreeFlags&1028)!==0&&d!==null)d.return=f,Ze=d;else for(;Ze!==null;){f=Ze;try{var x=f.alternate;if(f.flags&1024)switch(f.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var w=x.memoizedProps,k=x.memoizedState,F=f.stateNode,J=F.getSnapshotBeforeUpdate(f.elementType===f.type?w:po(f.type,w),k);F.__reactInternalSnapshotBeforeUpdate=J}break;case 3:qe&&ke(f.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(o(163))}}catch(oe){Zi(f,f.return,oe)}if(d=f.sibling,d!==null){d.return=f.return,Ze=d;break}Ze=f.return}return x=ZM,ZM=!1,x}function tu(f,d,x){var w=d.updateQueue;if(w=w!==null?w.lastEffect:null,w!==null){var k=w=w.next;do{if((k.tag&f)===f){var F=k.destroy;k.destroy=void 0,F!==void 0&&Lx(d,x,F)}k=k.next}while(k!==w)}}function kd(f,d){if(d=d.updateQueue,d=d!==null?d.lastEffect:null,d!==null){var x=d=d.next;do{if((x.tag&f)===f){var w=x.create;x.destroy=w()}x=x.next}while(x!==d)}}function Px(f){var d=f.ref;if(d!==null){var x=f.stateNode;switch(f.tag){case 5:f=V(x);break;default:f=x}typeof d=="function"?d(f):d.current=f}}function JM(f,d,x){if(Zo&&typeof Zo.onCommitFiberUnmount=="function")try{Zo.onCommitFiberUnmount(Qm,d)}catch{}switch(d.tag){case 0:case 11:case 14:case 15:if(f=d.updateQueue,f!==null&&(f=f.lastEffect,f!==null)){var w=f=f.next;do{var k=w,F=k.destroy;k=k.tag,F!==void 0&&(k&2||k&4)&&Lx(d,x,F),w=w.next}while(w!==f)}break;case 1:if(Tg(d,x),f=d.stateNode,typeof f.componentWillUnmount=="function")try{f.props=d.memoizedProps,f.state=d.memoizedState,f.componentWillUnmount()}catch(J){Zi(d,x,J)}break;case 5:Tg(d,x);break;case 4:qe?iC(f,d,x):it&&it&&(d=d.stateNode.containerInfo,x=Je(d),Rr(d,x))}}function QM(f,d,x){for(var w=d;;)if(JM(f,w,x),w.child===null||qe&&w.tag===4){if(w===d)break;for(;w.sibling===null;){if(w.return===null||w.return===d)return;w=w.return}w.sibling.return=w.return,w=w.sibling}else w.child.return=w,w=w.child}function eC(f){var d=f.alternate;d!==null&&(f.alternate=null,eC(d)),f.child=null,f.deletions=null,f.sibling=null,f.tag===5&&(d=f.stateNode,d!==null&&X(d)),f.stateNode=null,f.return=null,f.dependencies=null,f.memoizedProps=null,f.memoizedState=null,f.pendingProps=null,f.stateNode=null,f.updateQueue=null}function tC(f){return f.tag===5||f.tag===3||f.tag===4}function nC(f){e:for(;;){for(;f.sibling===null;){if(f.return===null||tC(f.return))return null;f=f.return}for(f.sibling.return=f.return,f=f.sibling;f.tag!==5&&f.tag!==6&&f.tag!==18;){if(f.flags&2||f.child===null||f.tag===4)continue e;f.child.return=f,f=f.child}if(!(f.flags&2))return f.stateNode}}function rC(f){if(qe){e:{for(var d=f.return;d!==null;){if(tC(d))break e;d=d.return}throw Error(o(160))}var x=d;switch(x.tag){case 5:d=x.stateNode,x.flags&32&&(Rt(d),x.flags&=-33),x=nC(f),Ux(f,x,d);break;case 3:case 4:d=x.stateNode.containerInfo,x=nC(f),Dx(f,x,d);break;default:throw Error(o(161))}}}function Dx(f,d,x){var w=f.tag;if(w===5||w===6)f=f.stateNode,d?yt(x,f,d):Ge(x,f);else if(w!==4&&(f=f.child,f!==null))for(Dx(f,d,x),f=f.sibling;f!==null;)Dx(f,d,x),f=f.sibling}function Ux(f,d,x){var w=f.tag;if(w===5||w===6)f=f.stateNode,d?et(x,f,d):Oe(x,f);else if(w!==4&&(f=f.child,f!==null))for(Ux(f,d,x),f=f.sibling;f!==null;)Ux(f,d,x),f=f.sibling}function iC(f,d,x){for(var w=d,k=!1,F,J;;){if(!k){k=w.return;e:for(;;){if(k===null)throw Error(o(160));switch(F=k.stateNode,k.tag){case 5:J=!1;break e;case 3:F=F.containerInfo,J=!0;break e;case 4:F=F.containerInfo,J=!0;break e}k=k.return}k=!0}if(w.tag===5||w.tag===6)QM(f,w,x),J?Ct(F,w.stateNode):rt(F,w.stateNode);else if(w.tag===18)J?Te(F,w.stateNode):fe(F,w.stateNode);else if(w.tag===4){if(w.child!==null){F=w.stateNode.containerInfo,J=!0,w.child.return=w,w=w.child;continue}}else if(JM(f,w,x),w.child!==null){w.child.return=w,w=w.child;continue}if(w===d)break;for(;w.sibling===null;){if(w.return===null||w.return===d)return;w=w.return,w.tag===4&&(k=!1)}w.sibling.return=w.return,w=w.sibling}}function Fx(f,d){if(qe){switch(d.tag){case 0:case 11:case 14:case 15:tu(3,d,d.return),kd(3,d),tu(5,d,d.return);return;case 1:return;case 5:var x=d.stateNode;if(x!=null){var w=d.memoizedProps;f=f!==null?f.memoizedProps:w;var k=d.type,F=d.updateQueue;d.updateQueue=null,F!==null&&nt(x,F,k,f,w,d)}return;case 6:if(d.stateNode===null)throw Error(o(162));x=d.memoizedProps,Lt(d.stateNode,f!==null?f.memoizedProps:x,x);return;case 3:De&&f!==null&&f.memoizedState.isDehydrated&&Xm(d.stateNode.containerInfo);return;case 12:return;case 13:bg(d);return;case 19:bg(d);return;case 17:return}throw Error(o(163))}switch(d.tag){case 0:case 11:case 14:case 15:tu(3,d,d.return),kd(3,d),tu(5,d,d.return);return;case 12:return;case 13:bg(d);return;case 19:bg(d);return;case 3:De&&f!==null&&f.memoizedState.isDehydrated&&Xm(d.stateNode.containerInfo);break;case 22:case 23:return}e:if(it){switch(d.tag){case 1:case 5:case 6:break e;case 3:case 4:d=d.stateNode,Rr(d.containerInfo,d.pendingChildren);break e}throw Error(o(163))}}function bg(f){var d=f.updateQueue;if(d!==null){f.updateQueue=null;var x=f.stateNode;x===null&&(x=f.stateNode=new zF),d.forEach(function(w){var k=ZF.bind(null,f,w);x.has(w)||(x.add(w),w.then(k,k))})}}function HF(f,d){for(Ze=d;Ze!==null;){d=Ze;var x=d.deletions;if(x!==null)for(var w=0;w";case Mg:return":has("+(Vx(f)||"")+")";case Cg:return'[role="'+f.value+'"]';case Ng:return'"'+f.value+'"';case Rg:return'[data-testname="'+f.value+'"]';default:throw Error(o(365))}}function cC(f,d){var x=[];f=[f,0];for(var w=0;wk&&(k=J),w&=~F}if(w=k,w=$r()-w,w=(120>w?120:480>w?480:1080>w?1080:1920>w?1920:3e3>w?3e3:4320>w?4320:1960*WF(w/1960))-w,10f?16:f,nc===null)var w=!1;else{if(f=nc,nc=null,Pg=0,Vt&6)throw Error(o(331));var k=Vt;for(Vt|=4,Ze=f.current;Ze!==null;){var F=Ze,J=F.child;if(Ze.flags&16){var oe=F.deletions;if(oe!==null){for(var Re=0;Re$r()-jx?nu(f,0):Wx|=x),Yi(f,d)}function vC(f,d){d===0&&(f.mode&1?(d=Zm,Zm<<=1,!(Zm&130023424)&&(Zm=4194304)):d=1);var x=Ci();f=Fg(f,d),f!==null&&(vd(f,d,x),Yi(f,x))}function YF(f){var d=f.memoizedState,x=0;d!==null&&(x=d.retryLane),vC(f,x)}function ZF(f,d){var x=0;switch(f.tag){case 13:var w=f.stateNode,k=f.memoizedState;k!==null&&(x=k.retryLane);break;case 19:w=f.stateNode;break;default:throw Error(o(314))}w!==null&&w.delete(d),vC(f,x)}var yC;yC=function(f,d,x){if(f!==null)if(f.memoizedProps!==d.pendingProps||Wn.current)Ss=!0;else{if(!(f.lanes&x)&&!(d.flags&128))return Ss=!1,FF(f,d,x);Ss=!!(f.flags&131072)}else Ss=!1,$n&&d.flags&1048576&&sM(d,lg,d.index);switch(d.lanes=0,d.tag){case 2:var w=d.type;f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),f=d.pendingProps;var k=Wr(d,Qe.current);yh(d,x),k=wx(null,d,w,f,k,x);var F=Tx();return d.flags|=1,typeof k=="object"&&k!==null&&typeof k.render=="function"&&k.$$typeof===void 0?(d.tag=1,d.memoizedState=null,d.updateQueue=null,cr(w)?(F=!0,Ai(d)):F=!1,d.memoizedState=k.state!==null&&k.state!==void 0?k.state:null,ux(d),k.updater=og,d.stateNode=k,k._reactInternals=d,fx(d,w,f,x),d=kx(null,d,w,!0,F,x)):(d.tag=0,$n&&F&&dx(d),Mi(null,d,k,x),d=d.child),d;case 16:w=d.elementType;e:{switch(f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),f=d.pendingProps,k=w._init,w=k(w._payload),d.type=w,k=d.tag=QF(w),f=po(w,f),k){case 0:d=Nx(null,d,w,f,x);break e;case 1:d=GM(null,d,w,f,x);break e;case 11:d=FM(null,d,w,f,x);break e;case 14:d=BM(null,d,w,po(w.type,f),x);break e}throw Error(o(306,w,""))}return d;case 0:return w=d.type,k=d.pendingProps,k=d.elementType===w?k:po(w,k),Nx(f,d,w,k,x);case 1:return w=d.type,k=d.pendingProps,k=d.elementType===w?k:po(w,k),GM(f,d,w,k,x);case 3:e:{if(WM(d),f===null)throw Error(o(387));w=d.pendingProps,F=d.memoizedState,k=F.element,JA(f,d),sg(d,w,null,x);var J=d.memoizedState;if(w=J.element,De&&F.isDehydrated)if(F={element:w,isDehydrated:!1,cache:J.cache,transitions:J.transitions},d.updateQueue.baseState=F,d.memoizedState=F,d.flags&256){k=Error(o(423)),d=jM(f,d,w,x,k);break e}else if(w!==k){k=Error(o(424)),d=jM(f,d,w,x,k);break e}else for(De&&(xs=jm(d.stateNode.containerInfo),ys=d,$n=!0,mo=null,yd=!1),x=hM(d,null,w,x),d.child=x;x;)x.flags=x.flags&-3|4096,x=x.sibling;else{if(Eh(),w===k){d=Za(f,d,x);break e}Mi(f,d,w,x)}d=d.child}return d;case 5:return fM(d),f===null&&gx(d),w=d.type,k=d.pendingProps,F=f!==null?f.memoizedProps:null,J=k.children,re(w,k)?J=null:F!==null&&re(w,F)&&(d.flags|=32),HM(f,d),Mi(f,d,J,x),d.child;case 6:return f===null&&gx(d),null;case 13:return $M(f,d,x);case 4:return vx(d,d.stateNode.containerInfo),w=d.pendingProps,f===null?d.child=wh(d,null,w,x):Mi(f,d,w,x),d.child;case 11:return w=d.type,k=d.pendingProps,k=d.elementType===w?k:po(w,k),FM(f,d,w,k,x);case 7:return Mi(f,d,d.pendingProps,x),d.child;case 8:return Mi(f,d,d.pendingProps.children,x),d.child;case 12:return Mi(f,d,d.pendingProps.children,x),d.child;case 10:e:{if(w=d.type._context,k=d.pendingProps,F=d.memoizedProps,J=k.value,ZA(d,w,J),F!==null)if(Jo(F.value,J)){if(F.children===k.children&&!Wn.current){d=Za(f,d,x);break e}}else for(F=d.child,F!==null&&(F.return=d);F!==null;){var oe=F.dependencies;if(oe!==null){J=F.child;for(var Re=oe.firstContext;Re!==null;){if(Re.context===w){if(F.tag===1){Re=qa(-1,x&-x),Re.tag=2;var Fe=F.updateQueue;if(Fe!==null){Fe=Fe.shared;var at=Fe.pending;at===null?Re.next=Re:(Re.next=at.next,at.next=Re),Fe.pending=Re}}F.lanes|=x,Re=F.alternate,Re!==null&&(Re.lanes|=x),cx(F.return,x,d),oe.lanes|=x;break}Re=Re.next}}else if(F.tag===10)J=F.type===d.type?null:F.child;else if(F.tag===18){if(J=F.return,J===null)throw Error(o(341));J.lanes|=x,oe=J.alternate,oe!==null&&(oe.lanes|=x),cx(J,x,d),J=F.sibling}else J=F.child;if(J!==null)J.return=F;else for(J=F;J!==null;){if(J===d){J=null;break}if(F=J.sibling,F!==null){F.return=J.return,J=F;break}J=J.return}F=J}Mi(f,d,k.children,x),d=d.child}return d;case 9:return k=d.type,w=d.pendingProps.children,yh(d,x),k=Us(k),w=w(k),d.flags|=1,Mi(f,d,w,x),d.child;case 14:return w=d.type,k=po(w,d.pendingProps),k=po(w.type,k),BM(f,d,w,k,x);case 15:return zM(f,d,d.type,d.pendingProps,x);case 17:return w=d.type,k=d.pendingProps,k=d.elementType===w?k:po(w,k),f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),d.tag=1,cr(w)?(f=!0,Ai(d)):f=!1,yh(d,x),rM(d,w,k),fx(d,w,k,x),kx(null,d,w,!0,f,x);case 19:return YM(f,d,x);case 22:return VM(f,d,x)}throw Error(o(156,d.tag))};function xC(f,d){return nx(f,d)}function JF(f,d,x,w){this.tag=f,this.key=x,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=d,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=w,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Gs(f,d,x,w){return new JF(f,d,x,w)}function Qx(f){return f=f.prototype,!(!f||!f.isReactComponent)}function QF(f){if(typeof f=="function")return Qx(f)?1:0;if(f!=null){if(f=f.$$typeof,f===v)return 11;if(f===S)return 14}return 2}function sc(f,d){var x=f.alternate;return x===null?(x=Gs(f.tag,d,f.key,f.mode),x.elementType=f.elementType,x.type=f.type,x.stateNode=f.stateNode,x.alternate=f,f.alternate=x):(x.pendingProps=d,x.type=f.type,x.flags=0,x.subtreeFlags=0,x.deletions=null),x.flags=f.flags&14680064,x.childLanes=f.childLanes,x.lanes=f.lanes,x.child=f.child,x.memoizedProps=f.memoizedProps,x.memoizedState=f.memoizedState,x.updateQueue=f.updateQueue,d=f.dependencies,x.dependencies=d===null?null:{lanes:d.lanes,firstContext:d.firstContext},x.sibling=f.sibling,x.index=f.index,x.ref=f.ref,x}function zg(f,d,x,w,k,F){var J=2;if(w=f,typeof f=="function")Qx(f)&&(J=1);else if(typeof f=="string")J=5;else e:switch(f){case u:return su(x.children,k,F,d);case h:J=8,k|=8;break;case p:return f=Gs(12,x,d,k|2),f.elementType=p,f.lanes=F,f;case y:return f=Gs(13,x,d,k),f.elementType=y,f.lanes=F,f;case _:return f=Gs(19,x,d,k),f.elementType=_,f.lanes=F,f;case T:return Vg(x,k,F,d);default:if(typeof f=="object"&&f!==null)switch(f.$$typeof){case m:J=10;break e;case g:J=9;break e;case v:J=11;break e;case S:J=14;break e;case E:J=16,w=null;break e}throw Error(o(130,f==null?f:typeof f,""))}return d=Gs(J,x,d,k),d.elementType=f,d.type=w,d.lanes=F,d}function su(f,d,x,w){return f=Gs(7,f,w,d),f.lanes=x,f}function Vg(f,d,x,w){return f=Gs(22,f,w,d),f.elementType=T,f.lanes=x,f.stateNode={},f}function eS(f,d,x){return f=Gs(6,f,null,d),f.lanes=x,f}function tS(f,d,x){return d=Gs(4,f.children!==null?f.children:[],f.key,d),d.lanes=x,d.stateNode={containerInfo:f.containerInfo,pendingChildren:null,implementation:f.implementation},d}function eB(f,d,x,w,k){this.tag=d,this.containerInfo=f,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Le,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=ex(0),this.expirationTimes=ex(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ex(0),this.identifierPrefix=w,this.onRecoverableError=k,De&&(this.mutableSourceEagerHydrationData=null)}function SC(f,d,x,w,k,F,J,oe,Re){return f=new eB(f,d,x,oe,Re),d===1?(d=1,F===!0&&(d|=8)):d=0,F=Gs(3,null,null,d),f.current=F,F.stateNode=f,F.memoizedState={element:w,isDehydrated:x,cache:null,transitions:null},ux(F),f}function EC(f){if(!f)return zt;f=f._reactInternals;e:{if(M(f)!==f||f.tag!==1)throw Error(o(170));var d=f;do{switch(d.tag){case 3:d=d.stateNode.context;break e;case 1:if(cr(d.type)){d=d.stateNode.__reactInternalMemoizedMergedChildContext;break e}}d=d.return}while(d!==null);throw Error(o(171))}if(f.tag===1){var x=f.type;if(cr(x))return Tn(f,x,d)}return d}function wC(f){var d=f._reactInternals;if(d===void 0)throw typeof f.render=="function"?Error(o(188)):(f=Object.keys(f).join(","),Error(o(268,f)));return f=L(d),f===null?null:f.stateNode}function TC(f,d){if(f=f.memoizedState,f!==null&&f.dehydrated!==null){var x=f.retryLane;f.retryLane=x!==0&&x=Fe&&F>=It&&k<=at&&J<=xt){f.splice(d,1);break}else if(w!==Fe||x.width!==Re.width||xtJ){if(!(F!==It||x.height!==Re.height||atk)){Fe>w&&(Re.width+=Fe-w,Re.x=w),atF&&(Re.height+=It-F,Re.y=F),xtx&&(x=J)),J ")+` + +No matching component was found for: + `)+f.join(" > ")}return null},n.getPublicRootInstance=function(f){if(f=f.current,!f.child)return null;switch(f.child.tag){case 5:return V(f.child.stateNode);default:return f.child.stateNode}},n.injectIntoDevTools=function(f){if(f={bundleType:f.bundleType,version:f.version,rendererPackageName:f.rendererPackageName,rendererConfig:f.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:a.ReactCurrentDispatcher,findHostInstanceByFiber:tB,findFiberByHostInstance:f.findFiberByHostInstance||nB,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.0.0-fc46dba67-20220329"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")f=!1;else{var d=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(d.isDisabled||!d.supportsFiber)f=!0;else{try{Qm=d.inject(f),Zo=d}catch{}f=!!d.checkDCE}}return f},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(f,d,x,w){if(!ae)throw Error(o(363));f=Hx(f,d);var k=ze(f,x,w).disconnect;return{disconnect:function(){k()}}},n.registerMutableSourceForHydration=function(f,d){var x=d._getVersion;x=x(d._source),f.mutableSourceEagerHydrationData==null?f.mutableSourceEagerHydrationData=[d,x]:f.mutableSourceEagerHydrationData.push(d,x)},n.runWithPriority=function(f,d){var x=pn;try{return pn=f,d()}finally{pn=x}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(f,d,x,w){var k=d.current,F=Ci(),J=rc(k);return x=EC(x),d.context===null?d.context=x:d.pendingContext=x,d=qa(F,J),d.payload={element:f},w=w===void 0?null:w,w!==null&&(d.callback=w),ec(k,d),f=Hs(k,J,F),f!==null&&ig(f,k,J),J},n};gO.exports=aG;var lG=gO.exports;const cG=Pl(lG),pT={},mT=t=>void Object.assign(pT,t);function uG(t,e){function n(u,{args:h=[],attach:p,...m},g){let v=`${u[0].toUpperCase()}${u.slice(1)}`,y;if(u==="primitive"){if(m.object===void 0)throw new Error("R3F: Primitives without 'object' are invalid!");const _=m.object;y=Qh(_,{type:u,root:g,attach:p,primitive:!0})}else{const _=pT[v];if(!_)throw new Error(`R3F: ${v} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);if(!Array.isArray(h))throw new Error("R3F: The args prop must be an array!");y=Qh(new _(...h),{type:u,root:g,attach:p,memoizedProps:{args:h}})}return y.__r3f.attach===void 0&&(y instanceof Bo?y.__r3f.attach="geometry":y instanceof Ul&&(y.__r3f.attach="material")),v!=="inject"&&LS(y,m),y}function r(u,h){let p=!1;if(h){var m,g;(m=h.__r3f)!=null&&m.attach?OS(u,h,h.__r3f.attach):h.isObject3D&&u.isObject3D&&(u.add(h),p=!0),p||(g=u.__r3f)==null||g.objects.push(h),h.__r3f||Qh(h,{}),h.__r3f.parent=u,bE(h),ef(h)}}function i(u,h,p){let m=!1;if(h){var g,v;if((g=h.__r3f)!=null&&g.attach)OS(u,h,h.__r3f.attach);else if(h.isObject3D&&u.isObject3D){h.parent=u,h.dispatchEvent({type:"added"}),u.dispatchEvent({type:"childadded",child:h});const y=u.children.filter(S=>S!==h),_=y.indexOf(p);u.children=[...y.slice(0,_),h,...y.slice(_)],m=!0}m||(v=u.__r3f)==null||v.objects.push(h),h.__r3f||Qh(h,{}),h.__r3f.parent=u,bE(h),ef(h)}}function s(u,h,p=!1){u&&[...u].forEach(m=>o(h,m,p))}function o(u,h,p){if(h){var m,g,v;if(h.__r3f&&(h.__r3f.parent=null),(m=u.__r3f)!=null&&m.objects&&(u.__r3f.objects=u.__r3f.objects.filter(T=>T!==h)),(g=h.__r3f)!=null&&g.attach)BR(u,h,h.__r3f.attach);else if(h.isObject3D&&u.isObject3D){var y;u.remove(h),(y=h.__r3f)!=null&&y.root&&yG(Q0(h),h)}const S=(v=h.__r3f)==null?void 0:v.primitive,E=!S&&(p===void 0?h.dispose!==null:p);if(!S){var _;s((_=h.__r3f)==null?void 0:_.objects,h,E),s(h.children,h,E)}if(delete h.__r3f,E&&h.dispose&&h.type!=="Scene"){const T=()=>{try{h.dispose()}catch{}};typeof IS_REACT_ACT_ENVIRONMENT>"u"?wE.unstable_scheduleCallback(wE.unstable_IdlePriority,T):T()}ef(u)}}function a(u,h,p,m){var g;const v=(g=u.__r3f)==null?void 0:g.parent;if(!v)return;const y=n(h,p,u.__r3f.root);if(u.children){for(const _ of u.children)_.__r3f&&r(y,_);u.children=u.children.filter(_=>!_.__r3f)}u.__r3f.objects.forEach(_=>r(y,_)),u.__r3f.objects=[],u.__r3f.autoRemovedBeforeAppend||o(v,u),y.parent&&(y.__r3f.autoRemovedBeforeAppend=!0),r(v,y),y.raycast&&y.__r3f.eventCount&&Q0(y).getState().internal.interaction.push(y),[m,m.alternate].forEach(_=>{_!==null&&(_.stateNode=y,_.ref&&(typeof _.ref=="function"?_.ref(y):_.ref.current=y))})}const l=()=>{};return{reconciler:cG({createInstance:n,removeChild:o,appendChild:r,appendInitialChild:r,insertBefore:i,supportsMutation:!0,isPrimaryRenderer:!1,supportsPersistence:!1,supportsHydration:!1,noTimeout:-1,appendChildToContainer:(u,h)=>{if(!h)return;const p=u.getState().scene;p.__r3f&&(p.__r3f.root=u,r(p,h))},removeChildFromContainer:(u,h)=>{h&&o(u.getState().scene,h)},insertInContainerBefore:(u,h,p)=>{if(!h||!p)return;const m=u.getState().scene;m.__r3f&&i(m,h,p)},getRootHostContext:()=>null,getChildHostContext:u=>u,finalizeInitialChildren(u){var h;return!!((h=u==null?void 0:u.__r3f)!=null?h:{}).handlers},prepareUpdate(u,h,p,m){var g;if(((g=u==null?void 0:u.__r3f)!=null?g:{}).primitive&&m.object&&m.object!==u)return[!0];{const{args:y=[],children:_,...S}=m,{args:E=[],children:T,...N}=p;if(!Array.isArray(y))throw new Error("R3F: the args prop must be an array!");if(y.some((C,O)=>C!==E[O]))return[!0];const R=wO(u,S,N,!0);return R.changes.length?[!1,R]:null}},commitUpdate(u,[h,p],m,g,v,y){h?a(u,m,v,y):LS(u,p)},commitMount(u,h,p,m){var g;const v=(g=u.__r3f)!=null?g:{};u.raycast&&v.handlers&&v.eventCount&&Q0(u).getState().internal.interaction.push(u)},getPublicInstance:u=>u,prepareForCommit:()=>null,preparePortalMount:u=>Qh(u.getState().scene),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,hideInstance(u){var h;const{attach:p,parent:m}=(h=u.__r3f)!=null?h:{};p&&m&&BR(m,u,p),u.isObject3D&&(u.visible=!1),ef(u)},unhideInstance(u,h){var p;const{attach:m,parent:g}=(p=u.__r3f)!=null?p:{};m&&g&&OS(g,u,m),(u.isObject3D&&h.visible==null||h.visible)&&(u.visible=!0),ef(u)},createTextInstance:l,hideTextInstance:l,unhideTextInstance:l,getCurrentEventPriority:()=>e?e():lf.DefaultEventPriority,beforeActiveInstanceBlur:()=>{},afterActiveInstanceBlur:()=>{},detachDeletedInstance:()=>{},now:typeof performance<"u"&&On.fun(performance.now)?performance.now:On.fun(Date.now)?Date.now:()=>0,scheduleTimeout:On.fun(setTimeout)?setTimeout:void 0,cancelTimeout:On.fun(clearTimeout)?clearTimeout:void 0}),applyProps:LS}}var PR,DR;const IS=t=>"colorSpace"in t||"outputColorSpace"in t,yO=()=>{var t;return(t=pT.ColorManagement)!=null?t:null},xO=t=>t&&t.isOrthographicCamera,Ov=typeof window<"u"&&((PR=window.document)!=null&&PR.createElement||((DR=window.navigator)==null?void 0:DR.product)==="ReactNative")?Ne.useLayoutEffect:Ne.useEffect;function hG(t){const e=Ne.useRef(t);return Ov(()=>void(e.current=t),[t]),e}class fG extends Ne.Component{constructor(...e){super(...e),this.state={error:!1}}componentDidCatch(e){this.props.set(e)}render(){return this.state.error?null:this.props.children}}fG.getDerivedStateFromError=()=>({error:!0});const SO="__default",UR=new Map,dG=t=>t&&!!t.memoized&&!!t.changes;function EO(t){var e;const n=typeof window<"u"?(e=window.devicePixelRatio)!=null?e:2:1;return Array.isArray(t)?Math.min(Math.max(t[0],n),t[1]):t}const zd=t=>{var e;return(e=t.__r3f)==null?void 0:e.root.getState()};function Q0(t){let e=t.__r3f.root;for(;e.getState().previousRoot;)e=e.getState().previousRoot;return e}const On={obj:t=>t===Object(t)&&!On.arr(t)&&typeof t!="function",fun:t=>typeof t=="function",str:t=>typeof t=="string",num:t=>typeof t=="number",boo:t=>typeof t=="boolean",und:t=>t===void 0,arr:t=>Array.isArray(t),equ(t,e,{arrays:n="shallow",objects:r="reference",strict:i=!0}={}){if(typeof t!=typeof e||!!t!=!!e)return!1;if(On.str(t)||On.num(t)||On.boo(t))return t===e;const s=On.obj(t);if(s&&r==="reference")return t===e;const o=On.arr(t);if(o&&n==="reference")return t===e;if((o||s)&&t===e)return!0;let a;for(a in t)if(!(a in e))return!1;if(s&&n==="shallow"&&r==="shallow"){for(a in i?e:t)if(!On.equ(t[a],e[a],{strict:i,objects:"reference"}))return!1}else for(a in i?e:t)if(t[a]!==e[a])return!1;if(On.und(a)){if(o&&t.length===0&&e.length===0||s&&Object.keys(t).length===0&&Object.keys(e).length===0)return!0;if(t!==e)return!1}return!0}};function pG(t){const e={nodes:{},materials:{}};return t&&t.traverse(n=>{n.name&&(e.nodes[n.name]=n),n.material&&!e.materials[n.material.name]&&(e.materials[n.material.name]=n.material)}),e}function mG(t){t.dispose&&t.type!=="Scene"&&t.dispose();for(const e in t)e.dispose==null||e.dispose(),delete t[e]}function Qh(t,e){const n=t;return n.__r3f={type:"",root:null,previousAttach:null,memoizedProps:{},eventCount:0,handlers:{},objects:[],parent:null,...e},t}function TE(t,e){let n=t;if(e.includes("-")){const r=e.split("-"),i=r.pop();return n=r.reduce((s,o)=>s[o],t),{target:n,key:i}}else return{target:n,key:e}}const FR=/-\d+$/;function OS(t,e,n){if(On.str(n)){if(FR.test(n)){const s=n.replace(FR,""),{target:o,key:a}=TE(t,s);Array.isArray(o[a])||(o[a]=[])}const{target:r,key:i}=TE(t,n);e.__r3f.previousAttach=r[i],r[i]=e}else e.__r3f.previousAttach=n(t,e)}function BR(t,e,n){var r,i;if(On.str(n)){const{target:s,key:o}=TE(t,n),a=e.__r3f.previousAttach;a===void 0?delete s[o]:s[o]=a}else(r=e.__r3f)==null||r.previousAttach==null||r.previousAttach(t,e);(i=e.__r3f)==null||delete i.previousAttach}function wO(t,{children:e,key:n,ref:r,...i},{children:s,key:o,ref:a,...l}={},c=!1){const u=t.__r3f,h=Object.entries(i),p=[];if(c){const g=Object.keys(l);for(let v=0;v{var y;if((y=t.__r3f)!=null&&y.primitive&&g==="object"||On.equ(v,l[g]))return;if(/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(g))return p.push([g,v,!0,[]]);let _=[];g.includes("-")&&(_=g.split("-")),p.push([g,v,!1,_]);for(const S in i){const E=i[S];S.startsWith(`${g}-`)&&p.push([S,E,!1,S.split("-")])}});const m={...i};return u!=null&&u.memoizedProps&&u!=null&&u.memoizedProps.args&&(m.args=u.memoizedProps.args),u!=null&&u.memoizedProps&&u!=null&&u.memoizedProps.attach&&(m.attach=u.memoizedProps.attach),{memoized:m,changes:p}}const gG=typeof process<"u"&&!1;function LS(t,e){var n;const r=t.__r3f,i=r==null?void 0:r.root,s=i==null||i.getState==null?void 0:i.getState(),{memoized:o,changes:a}=dG(e)?e:wO(t,e),l=r==null?void 0:r.eventCount;t.__r3f&&(t.__r3f.memoizedProps=o);for(let u=0;u_[S],t),!(y&&y.set))){const[_,...S]=g.reverse();v=S.reverse().reduce((E,T)=>E[T],t),h=_}if(p===SO+"remove")if(v.constructor){let _=UR.get(v.constructor);_||(_=new v.constructor,UR.set(v.constructor,_)),p=_[h]}else p=0;if(m&&r)p?r.handlers[h]=p:delete r.handlers[h],r.eventCount=Object.keys(r.handlers).length;else if(y&&y.set&&(y.copy||y instanceof yf)){if(Array.isArray(p))y.fromArray?y.fromArray(p):y.set(...p);else if(y.copy&&p&&p.constructor&&(gG?y.constructor.name===p.constructor.name:y.constructor===p.constructor))y.copy(p);else if(p!==void 0){const _=y instanceof cn;!_&&y.setScalar?y.setScalar(p):y instanceof yf&&p instanceof yf?y.mask=p.mask:y.set(p),!yO()&&s&&!s.linear&&_&&y.convertSRGBToLinear()}}else if(v[h]=p,v[h]instanceof or&&v[h].format===Qs&&v[h].type===wi&&s){const _=v[h];IS(_)&&IS(s.gl)?_.colorSpace=s.gl.outputColorSpace:_.encoding=s.gl.outputEncoding}ef(t)}if(r&&r.parent&&t.raycast&&l!==r.eventCount){const u=Q0(t).getState().internal,h=u.interaction.indexOf(t);h>-1&&u.interaction.splice(h,1),r.eventCount&&u.interaction.push(t)}return!(a.length===1&&a[0][0]==="onUpdate")&&a.length&&(n=t.__r3f)!=null&&n.parent&&bE(t),t}function ef(t){var e,n;const r=(e=t.__r3f)==null||(n=e.root)==null||n.getState==null?void 0:n.getState();r&&r.internal.frames===0&&r.invalidate()}function bE(t){t.onUpdate==null||t.onUpdate(t)}function _G(t,e){t.manual||(xO(t)?(t.left=e.width/-2,t.right=e.width/2,t.top=e.height/2,t.bottom=e.height/-2):t.aspect=e.width/e.height,t.updateProjectionMatrix(),t.updateMatrixWorld())}function f0(t){return(t.eventObject||t.object).uuid+"/"+t.index+t.instanceId}function vG(){var t;const e=typeof self<"u"&&self||typeof window<"u"&&window;if(!e)return lf.DefaultEventPriority;switch((t=e.event)==null?void 0:t.type){case"click":case"contextmenu":case"dblclick":case"pointercancel":case"pointerdown":case"pointerup":return lf.DiscreteEventPriority;case"pointermove":case"pointerout":case"pointerover":case"pointerenter":case"pointerleave":case"wheel":return lf.ContinuousEventPriority;default:return lf.DefaultEventPriority}}function TO(t,e,n,r){const i=n.get(e);i&&(n.delete(e),n.size===0&&(t.delete(r),i.target.releasePointerCapture(r)))}function yG(t,e){const{internal:n}=t.getState();n.interaction=n.interaction.filter(r=>r!==e),n.initialHits=n.initialHits.filter(r=>r!==e),n.hovered.forEach((r,i)=>{(r.eventObject===e||r.object===e)&&n.hovered.delete(i)}),n.capturedMap.forEach((r,i)=>{TO(n.capturedMap,e,r,i)})}function xG(t){function e(l){const{internal:c}=t.getState(),u=l.offsetX-c.initialClick[0],h=l.offsetY-c.initialClick[1];return Math.round(Math.sqrt(u*u+h*h))}function n(l){return l.filter(c=>["Move","Over","Enter","Out","Leave"].some(u=>{var h;return(h=c.__r3f)==null?void 0:h.handlers["onPointer"+u]}))}function r(l,c){const u=t.getState(),h=new Set,p=[],m=c?c(u.internal.interaction):u.internal.interaction;for(let _=0;_{const E=zd(_.object),T=zd(S.object);return!E||!T?_.distance-S.distance:T.events.priority-E.events.priority||_.distance-S.distance}).filter(_=>{const S=f0(_);return h.has(S)?!1:(h.add(S),!0)});u.events.filter&&(v=u.events.filter(v,u));for(const _ of v){let S=_.object;for(;S;){var y;(y=S.__r3f)!=null&&y.eventCount&&p.push({..._,eventObject:S}),S=S.parent}}if("pointerId"in l&&u.internal.capturedMap.has(l.pointerId))for(let _ of u.internal.capturedMap.get(l.pointerId).values())h.has(f0(_.intersection))||p.push(_.intersection);return p}function i(l,c,u,h){const p=t.getState();if(l.length){const m={stopped:!1};for(const g of l){const v=zd(g.object)||p,{raycaster:y,pointer:_,camera:S,internal:E}=v,T=new xe(_.x,_.y,0).unproject(S),N=I=>{var U,L;return(U=(L=E.capturedMap.get(I))==null?void 0:L.has(g.eventObject))!=null?U:!1},R=I=>{const U={intersection:g,target:c.target};E.capturedMap.has(I)?E.capturedMap.get(I).set(g.eventObject,U):E.capturedMap.set(I,new Map([[g.eventObject,U]])),c.target.setPointerCapture(I)},C=I=>{const U=E.capturedMap.get(I);U&&TO(E.capturedMap,g.eventObject,U,I)};let O={};for(let I in c){let U=c[I];typeof U!="function"&&(O[I]=U)}let M={...g,...O,pointer:_,intersections:l,stopped:m.stopped,delta:u,unprojectedPoint:T,ray:y.ray,camera:S,stopPropagation(){const I="pointerId"in c&&E.capturedMap.get(c.pointerId);if((!I||I.has(g.eventObject))&&(M.stopped=m.stopped=!0,E.hovered.size&&Array.from(E.hovered.values()).find(U=>U.eventObject===g.eventObject))){const U=l.slice(0,l.indexOf(g));s([...U,g])}},target:{hasPointerCapture:N,setPointerCapture:R,releasePointerCapture:C},currentTarget:{hasPointerCapture:N,setPointerCapture:R,releasePointerCapture:C},nativeEvent:c};if(h(M),m.stopped===!0)break}}return l}function s(l){const{internal:c}=t.getState();for(const u of c.hovered.values())if(!l.length||!l.find(h=>h.object===u.object&&h.index===u.index&&h.instanceId===u.instanceId)){const p=u.eventObject.__r3f,m=p==null?void 0:p.handlers;if(c.hovered.delete(f0(u)),p!=null&&p.eventCount){const g={...u,intersections:l};m.onPointerOut==null||m.onPointerOut(g),m.onPointerLeave==null||m.onPointerLeave(g)}}}function o(l,c){for(let u=0;us([]);case"onLostPointerCapture":return c=>{const{internal:u}=t.getState();"pointerId"in c&&u.capturedMap.has(c.pointerId)&&requestAnimationFrame(()=>{u.capturedMap.has(c.pointerId)&&(u.capturedMap.delete(c.pointerId),s([]))})}}return function(u){const{onPointerMissed:h,internal:p}=t.getState();p.lastEvent.current=u;const m=l==="onPointerMove",g=l==="onClick"||l==="onContextMenu"||l==="onDoubleClick",y=r(u,m?n:void 0),_=g?e(u):0;l==="onPointerDown"&&(p.initialClick=[u.offsetX,u.offsetY],p.initialHits=y.map(E=>E.eventObject)),g&&!y.length&&_<=2&&(o(u,p.interaction),h&&h(u)),m&&s(y);function S(E){const T=E.eventObject,N=T.__r3f,R=N==null?void 0:N.handlers;if(N!=null&&N.eventCount)if(m){if(R.onPointerOver||R.onPointerEnter||R.onPointerOut||R.onPointerLeave){const C=f0(E),O=p.hovered.get(C);O?O.stopped&&E.stopPropagation():(p.hovered.set(C,E),R.onPointerOver==null||R.onPointerOver(E),R.onPointerEnter==null||R.onPointerEnter(E))}R.onPointerMove==null||R.onPointerMove(E)}else{const C=R[l];C?(!g||p.initialHits.includes(T))&&(o(u,p.interaction.filter(O=>!p.initialHits.includes(O))),C(E)):g&&p.initialHits.includes(T)&&o(u,p.interaction.filter(O=>!p.initialHits.includes(O)))}}i(y,u,_,S)}}return{handlePointer:a}}const bO=t=>!!(t!=null&&t.render),AO=Ne.createContext(null),SG=(t,e)=>{const n=nG((a,l)=>{const c=new xe,u=new xe,h=new xe;function p(_=l().camera,S=u,E=l().size){const{width:T,height:N,top:R,left:C}=E,O=T/N;S instanceof xe?h.copy(S):h.set(...S);const M=_.getWorldPosition(c).distanceTo(h);if(xO(_))return{width:T/_.zoom,height:N/_.zoom,top:R,left:C,factor:1,distance:M,aspect:O};{const I=_.fov*Math.PI/180,U=2*Math.tan(I/2)*M,L=U*(T/N);return{width:L,height:U,top:R,left:C,factor:T/L,distance:M,aspect:O}}}let m;const g=_=>a(S=>({performance:{...S.performance,current:_}})),v=new St;return{set:a,get:l,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},xr:null,scene:null,invalidate:(_=1)=>t(l(),_),advance:(_,S)=>e(_,S,l()),legacy:!1,linear:!1,flat:!1,controls:null,clock:new ZH,pointer:v,mouse:v,frameloop:"always",onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{const _=l();m&&clearTimeout(m),_.performance.current!==_.performance.min&&g(_.performance.min),m=setTimeout(()=>g(l().performance.max),_.performance.debounce)}},size:{width:0,height:0,top:0,left:0,updateStyle:!1},viewport:{initialDpr:0,dpr:0,width:0,height:0,top:0,left:0,aspect:0,distance:0,factor:0,getCurrentViewport:p},setEvents:_=>a(S=>({...S,events:{...S.events,..._}})),setSize:(_,S,E,T,N)=>{const R=l().camera,C={width:_,height:S,top:T||0,left:N||0,updateStyle:E};a(O=>({size:C,viewport:{...O.viewport,...p(R,u,C)}}))},setDpr:_=>a(S=>{const E=EO(_);return{viewport:{...S.viewport,dpr:E,initialDpr:S.viewport.initialDpr||E}}}),setFrameloop:(_="always")=>{const S=l().clock;S.stop(),S.elapsedTime=0,_!=="never"&&(S.start(),S.elapsedTime=0),a(()=>({frameloop:_}))},previousRoot:void 0,internal:{active:!1,priority:0,frames:0,lastEvent:Ne.createRef(),interaction:[],hovered:new Map,subscribers:[],initialClick:[0,0],initialHits:[],capturedMap:new Map,subscribe:(_,S,E)=>{const T=l().internal;return T.priority=T.priority+(S>0?1:0),T.subscribers.push({ref:_,priority:S,store:E}),T.subscribers=T.subscribers.sort((N,R)=>N.priority-R.priority),()=>{const N=l().internal;N!=null&&N.subscribers&&(N.priority=N.priority-(S>0?1:0),N.subscribers=N.subscribers.filter(R=>R.ref!==_))}}}}}),r=n.getState();let i=r.size,s=r.viewport.dpr,o=r.camera;return n.subscribe(()=>{const{camera:a,size:l,viewport:c,gl:u,set:h}=n.getState();if(l.width!==i.width||l.height!==i.height||c.dpr!==s){var p;i=l,s=c.dpr,_G(a,l),u.setPixelRatio(c.dpr);const m=(p=l.updateStyle)!=null?p:typeof HTMLCanvasElement<"u"&&u.domElement instanceof HTMLCanvasElement;u.setSize(l.width,l.height,m)}a!==o&&(o=a,h(m=>({viewport:{...m.viewport,...m.viewport.getCurrentViewport(a)}})))}),n.subscribe(a=>t(a)),n};function MO(t,e){const n={callback:t};return e.add(n),()=>void e.delete(n)}let d0,CO=new Set,RO=new Set,EG=new Set;const wG=t=>MO(t,CO),TG=t=>MO(t,RO);function PS(t,e){if(t.size)for(const{callback:n}of t.values())n(e)}function Vd(t,e){switch(t){case"before":return PS(CO,e);case"after":return PS(RO,e);case"tail":return PS(EG,e)}}let DS,US;function FS(t,e,n){let r=e.clock.getDelta();for(e.frameloop==="never"&&typeof t=="number"&&(r=t-e.clock.elapsedTime,e.clock.oldTime=e.clock.elapsedTime,e.clock.elapsedTime=t),DS=e.internal.subscribers,d0=0;d00)&&!((u=s.gl.xr)!=null&&u.isPresenting)&&(r+=FS(c,s))}if(n=!1,Vd("after",c),r===0)return Vd("tail",c),e=!1,cancelAnimationFrame(i)}function a(c,u=1){var h;if(!c)return t.forEach(p=>a(p.store.getState(),u));(h=c.gl.xr)!=null&&h.isPresenting||!c.internal.active||c.frameloop==="never"||(u>1?c.internal.frames=Math.min(60,c.internal.frames+u):n?c.internal.frames=2:c.internal.frames=1,e||(e=!0,requestAnimationFrame(o)))}function l(c,u=!0,h,p){if(u&&Vd("before",c),h)FS(c,h,p);else for(const m of t.values())FS(c,m.store.getState());u&&Vd("after",c)}return{loop:o,invalidate:a,advance:l}}function AG(t){const e=Ne.useRef(null);return Ov(()=>void(e.current=t.current.__r3f),[t]),e}function NO(){const t=Ne.useContext(AO);if(!t)throw new Error("R3F: Hooks can only be used within the Canvas component!");return t}function _a(t=n=>n,e){return NO()(t,e)}function Lv(t,e=0){const n=NO(),r=n.getState().internal.subscribe,i=hG(t);return Ov(()=>r(i,e,n),[e,r,n]),null}const zR=new WeakMap;function kO(t,e){return function(n,...r){let i=zR.get(n);return i||(i=new n,zR.set(n,i)),t&&t(i),Promise.all(r.map(s=>new Promise((o,a)=>i.load(s,l=>{l.scene&&Object.assign(l,pG(l.scene)),o(l)},e,l=>a(new Error(`Could not load ${s}: ${l==null?void 0:l.message}`))))))}}function Jp(t,e,n,r){const i=Array.isArray(e)?e:[e],s=iG(kO(n,r),[t,...i],{equal:On.equ});return Array.isArray(e)?s:s[0]}Jp.preload=function(t,e,n){const r=Array.isArray(e)?e:[e];return sG(kO(n),[t,...r])};Jp.clear=function(t,e){const n=Array.isArray(e)?e:[e];return oG([t,...n])};const Of=new Map,{invalidate:VR,advance:HR}=bG(Of),{reconciler:C_,applyProps:Wh}=uG(Of,vG),jh={objects:"shallow",strict:!1},MG=(t,e)=>{const n=typeof t=="function"?t(e):t;return bO(n)?n:new GH({powerPreference:"high-performance",canvas:e,antialias:!0,alpha:!0,...t})};function CG(t,e){const n=typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement;if(e){const{width:r,height:i,top:s,left:o,updateStyle:a=n}=e;return{width:r,height:i,top:s,left:o,updateStyle:a}}else if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement&&t.parentElement){const{width:r,height:i,top:s,left:o}=t.parentElement.getBoundingClientRect();return{width:r,height:i,top:s,left:o,updateStyle:n}}else if(typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return{width:t.width,height:t.height,top:0,left:0,updateStyle:n};return{width:0,height:0,top:0,left:0}}function RG(t){const e=Of.get(t),n=e==null?void 0:e.fiber,r=e==null?void 0:e.store;e&&console.warn("R3F.createRoot should only be called once!");const i=typeof reportError=="function"?reportError:console.error,s=r||SG(VR,HR),o=n||C_.createContainer(s,lf.ConcurrentRoot,null,!1,null,"",i,null);e||Of.set(t,{fiber:o,store:s});let a,l=!1,c;return{configure(u={}){let{gl:h,size:p,scene:m,events:g,onCreated:v,shadows:y=!1,linear:_=!1,flat:S=!1,legacy:E=!1,orthographic:T=!1,frameloop:N="always",dpr:R=[1,2],performance:C,raycaster:O,camera:M,onPointerMissed:I}=u,U=s.getState(),L=U.gl;U.gl||U.set({gl:L=MG(h,t)});let P=U.raycaster;P||U.set({raycaster:P=new JH});const{params:b,...H}=O||{};if(On.equ(H,P,jh)||Wh(P,{...H}),On.equ(b,P.params,jh)||Wh(P,{params:{...P.params,...b}}),!U.camera||U.camera===c&&!On.equ(c,M,jh)){c=M;const K=M instanceof Nv,j=K?M:T?new kv(0,0,0,0,.1,1e3):new As(75,0,.1,1e3);K||(j.position.z=5,M&&(Wh(j,M),("aspect"in M||"left"in M||"right"in M||"bottom"in M||"top"in M)&&(j.manual=!0,j.updateProjectionMatrix())),!U.camera&&!(M!=null&&M.rotation)&&j.lookAt(0,0,0)),U.set({camera:j}),P.camera=j}if(!U.scene){let K;m instanceof M_?K=m:(K=new M_,m&&Wh(K,m)),U.set({scene:Qh(K)})}if(!U.xr){var V;const K=(ge,Q)=>{const re=s.getState();re.frameloop!=="never"&&HR(ge,!0,re,Q)},j=()=>{const ge=s.getState();ge.gl.xr.enabled=ge.gl.xr.isPresenting,ge.gl.xr.setAnimationLoop(ge.gl.xr.isPresenting?K:null),ge.gl.xr.isPresenting||VR(ge)},Y={connect(){const ge=s.getState().gl;ge.xr.addEventListener("sessionstart",j),ge.xr.addEventListener("sessionend",j)},disconnect(){const ge=s.getState().gl;ge.xr.removeEventListener("sessionstart",j),ge.xr.removeEventListener("sessionend",j)}};typeof((V=L.xr)==null?void 0:V.addEventListener)=="function"&&Y.connect(),U.set({xr:Y})}if(L.shadowMap){const K=L.shadowMap.enabled,j=L.shadowMap.type;if(L.shadowMap.enabled=!!y,On.boo(y))L.shadowMap.type=$0;else if(On.str(y)){var B;const Y={basic:kB,percentage:tT,soft:$0,variance:la};L.shadowMap.type=(B=Y[y])!=null?B:$0}else On.obj(y)&&Object.assign(L.shadowMap,y);(K!==L.shadowMap.enabled||j!==L.shadowMap.type)&&(L.shadowMap.needsUpdate=!0)}const z=yO();z&&("enabled"in z?z.enabled=!E:"legacyMode"in z&&(z.legacyMode=E)),l||Wh(L,{outputEncoding:_?3e3:3001,toneMapping:S?va:FI}),U.legacy!==E&&U.set(()=>({legacy:E})),U.linear!==_&&U.set(()=>({linear:_})),U.flat!==S&&U.set(()=>({flat:S})),h&&!On.fun(h)&&!bO(h)&&!On.equ(h,L,jh)&&Wh(L,h),g&&!U.events.handlers&&U.set({events:g(s)});const W=CG(t,p);return On.equ(W,U.size,jh)||U.setSize(W.width,W.height,W.updateStyle,W.top,W.left),R&&U.viewport.dpr!==EO(R)&&U.setDpr(R),U.frameloop!==N&&U.setFrameloop(N),U.onPointerMissed||U.set({onPointerMissed:I}),C&&!On.equ(C,U.performance,jh)&&U.set(K=>({performance:{...K.performance,...C}})),a=v,l=!0,this},render(u){return l||this.configure(),C_.updateContainer(ve.jsx(NG,{store:s,children:u,onCreated:a,rootElement:t}),o,null,()=>{}),s},unmount(){kG(t)}}}function NG({store:t,children:e,onCreated:n,rootElement:r}){return Ov(()=>{const i=t.getState();i.set(s=>({internal:{...s.internal,active:!0}})),n&&n(i),t.getState().events.connected||i.events.connect==null||i.events.connect(r)},[]),ve.jsx(AO.Provider,{value:t,children:e})}function kG(t,e){const n=Of.get(t),r=n==null?void 0:n.fiber;if(r){const i=n==null?void 0:n.store.getState();i&&(i.internal.active=!1),C_.updateContainer(null,r,null,()=>{i&&setTimeout(()=>{try{var s,o,a,l;i.events.disconnect==null||i.events.disconnect(),(s=i.gl)==null||(o=s.renderLists)==null||o.dispose==null||o.dispose(),(a=i.gl)==null||a.forceContextLoss==null||a.forceContextLoss(),(l=i.gl)!=null&&l.xr&&i.xr.disconnect(),mG(i),Of.delete(t)}catch{}},500)})}}C_.injectIntoDevTools({bundleType:0,rendererPackageName:"@react-three/fiber",version:Ne.version});const BS={onClick:["click",!1],onContextMenu:["contextmenu",!1],onDoubleClick:["dblclick",!1],onWheel:["wheel",!0],onPointerDown:["pointerdown",!0],onPointerUp:["pointerup",!0],onPointerLeave:["pointerleave",!0],onPointerMove:["pointermove",!0],onPointerCancel:["pointercancel",!0],onLostPointerCapture:["lostpointercapture",!0]};function IG(t){const{handlePointer:e}=xG(t);return{priority:1,enabled:!0,compute(n,r,i){r.pointer.set(n.offsetX/r.size.width*2-1,-(n.offsetY/r.size.height)*2+1),r.raycaster.setFromCamera(r.pointer,r.camera)},connected:void 0,handlers:Object.keys(BS).reduce((n,r)=>({...n,[r]:e(r)}),{}),update:()=>{var n;const{events:r,internal:i}=t.getState();(n=i.lastEvent)!=null&&n.current&&r.handlers&&r.handlers.onPointerMove(i.lastEvent.current)},connect:n=>{var r;const{set:i,events:s}=t.getState();s.disconnect==null||s.disconnect(),i(o=>({events:{...o.events,connected:n}})),Object.entries((r=s.handlers)!=null?r:[]).forEach(([o,a])=>{const[l,c]=BS[o];n.addEventListener(l,a,{passive:c})})},disconnect:()=>{const{set:n,events:r}=t.getState();if(r.connected){var i;Object.entries((i=r.handlers)!=null?i:[]).forEach(([s,o])=>{if(r&&r.connected instanceof HTMLElement){const[a]=BS[s];r.connected.removeEventListener(a,o)}}),n(s=>({events:{...s.events,connected:void 0}}))}}}}var gT={exports:{}};function IO(t,e=100,n={}){if(typeof t!="function")throw new TypeError(`Expected the first parameter to be a function, got \`${typeof t}\`.`);if(e<0)throw new RangeError("`wait` must not be negative.");const{immediate:r}=typeof n=="boolean"?{immediate:n}:n;let i,s,o,a,l;function c(){const p=i,m=s;return i=void 0,s=void 0,l=t.apply(p,m),l}function u(){const p=Date.now()-a;p=0?o=setTimeout(u,e-p):(o=void 0,r||(l=c()))}const h=function(...p){if(i&&this!==i&&Object.getPrototypeOf(this)===Object.getPrototypeOf(i))throw new Error("Debounced method called with different contexts of the same prototype.");i=this,s=p,a=Date.now();const m=r&&!o;return o||(o=setTimeout(u,e)),m&&(l=c()),l};return Object.defineProperty(h,"isPending",{get(){return o!==void 0}}),h.clear=()=>{o&&(clearTimeout(o),o=void 0)},h.flush=()=>{o&&h.trigger()},h.trigger=()=>{l=c(),h.clear()},h}gT.exports.debounce=IO;gT.exports=IO;var OG=gT.exports;const LG=Pl(OG);var OO={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(bo,function(){return n.importState=function(i){var s=new n;return s.importState(i),s},n;function n(){return function(i){var s=0,o=0,a=0,l=1;i.length==0&&(i=[+new Date]);var c=r();s=c(" "),o=c(" "),a=c(" ");for(var u=0;u>>0,l-=i,l*=i,i=l>>>0,l-=i,i+=l*4294967296}return(i>>>0)*23283064365386963e-26};return s.version="Mash 0.9",s}})})(OO);var PG=OO.exports;const DG=Pl(PG);new St;new St;function Cn(t,e,n){return Math.max(e,Math.min(n,t))}const UG=DG("089fad0j9awfem09wavefc09uwaef");function GR(t){return 2*Math.floor(t/2)}function FG(t,e){return Math.round(t/e)*e}function BG(){return UG()}function ep(t,e){const n=Math.min(t,e),i=Math.max(t,e)-n+1;return n+Math.floor(BG()*i)}/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + */var zG=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),VG=Object.prototype.hasOwnProperty;function AE(t,e){return VG.call(t,e)}function ME(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n=48&&r<=57){e++;continue}return!1}return!0}function Su(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function LO(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function RE(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e0&&l[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&p===void 0&&(c[m]===void 0?p=l.slice(0,u).join("/"):u==h-1&&(p=e.path),p!==void 0&&g(e,0,t,p)),u++,Array.isArray(c)){if(m==="-")m=c.length;else{if(n&&!CE(m))throw new tr("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);CE(m)&&(m=~~m)}if(u>=h){if(n&&e.op==="add"&&m>c.length)throw new tr("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var o=GG[e.op].call(e,c,m,t);if(o.test===!1)throw new tr("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return o}}else if(u>=h){var o=cf[e.op].call(e,c,m,t);if(o.test===!1)throw new tr("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return o}if(c=c[m],n&&u0)throw new tr('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new tr("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new tr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&RE(t.value))throw new tr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var i=t.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new tr("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new tr("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var o={op:"_get",path:t.from,value:void 0},a=PO([o],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new tr("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new tr("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function PO(t,e,n){try{if(!Array.isArray(t))throw new tr("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Pv(Fi(e),Fi(t),n||!0);else{n=n||N_;for(var r=0;r0&&(t.patches=[],t.callback&&t.callback(r)),r}function yT(t,e,n,r,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=ME(e),o=ME(t),a=!1,l=o.length-1;l>=0;l--){var c=o[l],u=t[c];if(AE(e,c)&&!(e[c]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var h=e[c];typeof u=="object"&&u!=null&&typeof h=="object"&&h!=null&&Array.isArray(u)===Array.isArray(h)?yT(u,h,n,r+"/"+Su(c),i):u!==h&&(i&&n.push({op:"test",path:r+"/"+Su(c),value:Fi(u)}),n.push({op:"replace",path:r+"/"+Su(c),value:Fi(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&n.push({op:"test",path:r+"/"+Su(c),value:Fi(u)}),n.push({op:"remove",path:r+"/"+Su(c)}),a=!0):(i&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}))}if(!(!a&&s.length==o.length))for(var l=0;lh.length?u:h})}function i(c){return c.reduce(function(u,h){return u.lengthcrypto.getRandomValues(new Uint8Array(t)),hW=(t,e,n)=>{let r=(2<{let o="";for(;;){let a=n(i),l=i;for(;l--;)if(o+=t[a[l]&r]||"",o.length===s)return o}}},BO=(t,e=21)=>hW(t,e,uW),fW=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t));for(;t--;)e+=cW[n[t]&63];return e};var zO="abcdefghijklmnopqrstuvwxyz",VO="ABCDEFGHIJKLMNOPQRSTUVWXYZ",HO="0123456789",dW="346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz",pW="6789BCDFGHJKLMNPQRTWbcdfghjkmnpqrtwz";const mW=HO,gW=zO,_W=VO;var vW=mW+gW+_W,kE={lowercase:zO,uppercase:VO,numbers:HO,nolookalikes:dW,nolookalikesSafe:pW,alphanumeric:vW};function fr(){return`sid_${fW(12).replaceAll("-",".")}`}const yW=BO(kE.numbers,4),xW=BO(`${kE.numbers}${kE.lowercase}`,16);function SW(){return`pid_${yW()}_${xW()}`}function EW(t){return(t==null?void 0:t.startsWith("pid_"))??!1}function wW(){return lW({capitalize:!1,adjectiveCount:1})}var wn=(t=>(t[t.BLACK=0]="BLACK",t[t.DKBLUE=1]="DKBLUE",t[t.DKGREEN=2]="DKGREEN",t[t.DKCYAN=3]="DKCYAN",t[t.DKRED=4]="DKRED",t[t.DKPURPLE=5]="DKPURPLE",t[t.DKYELLOW=6]="DKYELLOW",t[t.LTGRAY=7]="LTGRAY",t[t.DKGRAY=8]="DKGRAY",t[t.BLUE=9]="BLUE",t[t.GREEN=10]="GREEN",t[t.CYAN=11]="CYAN",t[t.RED=12]="RED",t[t.PURPLE=13]="PURPLE",t[t.YELLOW=14]="YELLOW",t[t.WHITE=15]="WHITE",t[t.ONBLACK=16]="ONBLACK",t[t.ONDKBLUE=17]="ONDKBLUE",t[t.ONDKGREEN=18]="ONDKGREEN",t[t.ONDKCYAN=19]="ONDKCYAN",t[t.ONDKRED=20]="ONDKRED",t[t.ONDKPURPLE=21]="ONDKPURPLE",t[t.ONDKYELLOW=22]="ONDKYELLOW",t[t.ONLTGRAY=23]="ONLTGRAY",t[t.ONDKGRAY=24]="ONDKGRAY",t[t.ONBLUE=25]="ONBLUE",t[t.ONGREEN=26]="ONGREEN",t[t.ONCYAN=27]="ONCYAN",t[t.ONRED=28]="ONRED",t[t.ONPURPLE=29]="ONPURPLE",t[t.ONYELLOW=30]="ONYELLOW",t[t.ONWHITE=31]="ONWHITE",t[t.ONCLEAR=32]="ONCLEAR",t[t.ONSHADOW=33]="ONSHADOW",t[t.ONBORROW=34]="ONBORROW",t))(wn||{}),Vn=(t=>(t[t.ISWALK=0]="ISWALK",t[t.ISSOLID=1]="ISSOLID",t[t.ISSWIM=2]="ISSWIM",t[t.ISBULLET=3]="ISBULLET",t))(Vn||{}),k_=(t=>(t[t.ISTERRAIN=0]="ISTERRAIN",t[t.ISOBJECT=1]="ISOBJECT",t))(k_||{}),st=(t=>(t[t.IDLE=0]="IDLE",t[t.NORTH=1]="NORTH",t[t.SOUTH=2]="SOUTH",t[t.WEST=3]="WEST",t[t.EAST=4]="EAST",t[t.BY=5]="BY",t[t.AT=6]="AT",t[t.FLOW=7]="FLOW",t[t.SEEK=8]="SEEK",t[t.RNDNS=9]="RNDNS",t[t.RNDNE=10]="RNDNE",t[t.RND=11]="RND",t[t.CW=12]="CW",t[t.CCW=13]="CCW",t[t.OPP=14]="OPP",t[t.RNDP=15]="RNDP",t))(st||{}),dt=(t=>(t[t.LOADER=0]="LOADER",t[t.BOARD=1]="BOARD",t[t.OBJECT=2]="OBJECT",t[t.TERRAIN=3]="TERRAIN",t[t.CHARSET=4]="CHARSET",t[t.PALETTE=5]="PALETTE",t[t.CONST=6]="CONST",t[t.RANGE=7]="RANGE",t[t.SELECT=8]="SELECT",t[t.NUMBER=9]="NUMBER",t[t.TEXT=10]="TEXT",t[t.LINK=11]="LINK",t[t.HOTKEY=12]="HOTKEY",t[t.SCROLL=13]="SCROLL",t[t.COPYIT=14]="COPYIT",t))(dt||{});function $t(t){return t.toLowerCase().trim()}function TW(t,e,n,r){return{id:fr(),target:t,sender:e,data:n,player:r}}function GO(t){const[e,...n]=t.split(":");return{target:e,path:n.join(":")}}function rh(t,e,n){const r=fr(),i=$t(t),s=e.map($t),o={id(){return r},name(){return t},topics(){return e},emit(a,l,c){Yt.emit(a,r,l,c)},reply(a,l,c,u){o.emit(`${a.sender}:${l}`,c,u)},handle(a){const{target:l,path:c}=GO(a.target),u=$t(l);s.findIndex(h=>h==="all"||h===u)!==-1&&n(a),(r===l||u==="all"||i===u)&&n({...a,target:c})}};return Yt.connect(o),o}const zS=new Set,Yt={emit(t,e,n,r){Yt.invoke(TW(t,e,n,r))},invoke(t){zS.forEach(e=>e.handle(t))},connect(t){zS.add(t)},disconnect(t){zS.delete(t)}};function Pn(t,e,n,r){const i=r??"";return Yt.emit(`error:${e}`,t,n,i),LW(t,n,i)}function bW(t,e){Yt.emit("gadgetserver:desync",t,void 0,e)}function AW(t,e){Yt.emit("gadgetserver:clearscroll",t,void 0,e)}function MW(t,e){Yt.emit("register:dev",t,void 0,e)}function CW(t,e){Yt.emit("register:share",t,void 0,e)}function RW(t){Yt.emit("register:nuke",t)}function NW(t){Yt.emit("register:nodetrash",t)}function kW(t,e,n){Yt.emit("synth:tts",t,[e,n])}function IW(t,e,n){Yt.emit("synth:play",t,[e,n])}function VS(t,e,n,r){Yt.emit("synth:voice",t,[e,n,r])}function OW(t,e,n,r,i){Yt.emit("synth:voicefx",t,[e,n,r,i])}function to(t,...e){return Yt.emit("tape:info",t,e),!0}function LW(t,...e){return Yt.emit("tape:error",t,e),!1}function PW(t){Yt.emit("tape:terminal:open",t)}function ST(t){Yt.emit("tape:terminal:close",t)}function WO(t,e){Yt.emit("tape:terminal:inclayout",t,e)}function jR(t){Yt.emit("tape:crash",t)}function DW(t,e,n,r,i,s){Yt.emit("tape:editor:open",t,[e,n,r,i],s)}function UW(t){Yt.emit("tape:editor:close",t)}function FW(t,e){Yt.emit("vm:init",t,void 0,e)}function BW(t,e,n,r){Yt.emit("vm:books",t,[e,n],r)}function zW(t,e){Yt.emit("vm:login",t,void 0,e)}function VW(t,e){Yt.emit("vm:endgame",t,void 0,e)}function HW(t,e){Yt.emit("vm:doot",t,void 0,e)}function GW(t,e,n,r){Yt.emit("vm:input",t,[e,n],r)}function jO(t,e){return`${t}${e}`}function WW(t,e,n,r){Yt.emit("vm:codewatch",t,[e,n],r)}function jW(t,e,n,r){Yt.emit("vm:coderelease",t,[e,n],r)}function Dv(t,e,n){Yt.emit("vm:cli",t,e,n)}function tf(t){Yt.emit("vm:flush",t)}function IE(t,e,n){Yt.emit("vm:loadfile",t,e,n)}function Vu(t){"@babel/helpers - typeof";return Vu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Vu(t)}function So(){So=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,i=Object.defineProperty||function(V,B,z){V[B]=z.value},s=typeof Symbol=="function"?Symbol:{},o=s.iterator||"@@iterator",a=s.asyncIterator||"@@asyncIterator",l=s.toStringTag||"@@toStringTag";function c(V,B,z){return Object.defineProperty(V,B,{value:z,enumerable:!0,configurable:!0,writable:!0}),V[B]}try{c({},"")}catch{c=function(z,W,K){return z[W]=K}}function u(V,B,z,W){var K=B&&B.prototype instanceof _?B:_,j=Object.create(K.prototype),Y=new b(W||[]);return i(j,"_invoke",{value:I(V,z,Y)}),j}function h(V,B,z){try{return{type:"normal",arg:V.call(B,z)}}catch(W){return{type:"throw",arg:W}}}e.wrap=u;var p="suspendedStart",m="suspendedYield",g="executing",v="completed",y={};function _(){}function S(){}function E(){}var T={};c(T,o,function(){return this});var N=Object.getPrototypeOf,R=N&&N(N(H([])));R&&R!==n&&r.call(R,o)&&(T=R);var C=E.prototype=_.prototype=Object.create(T);function O(V){["next","throw","return"].forEach(function(B){c(V,B,function(z){return this._invoke(B,z)})})}function M(V,B){function z(K,j,Y,ge){var Q=h(V[K],V,j);if(Q.type!=="throw"){var re=Q.arg,we=re.value;return we&&Vu(we)=="object"&&r.call(we,"__await")?B.resolve(we.__await).then(function(Ae){z("next",Ae,Y,ge)},function(Ae){z("throw",Ae,Y,ge)}):B.resolve(we).then(function(Ae){re.value=Ae,Y(re)},function(Ae){return z("throw",Ae,Y,ge)})}ge(Q.arg)}var W;i(this,"_invoke",{value:function(j,Y){function ge(){return new B(function(Q,re){z(j,Y,Q,re)})}return W=W?W.then(ge,ge):ge()}})}function I(V,B,z){var W=p;return function(K,j){if(W===g)throw Error("Generator is already running");if(W===v){if(K==="throw")throw j;return{value:t,done:!0}}for(z.method=K,z.arg=j;;){var Y=z.delegate;if(Y){var ge=U(Y,z);if(ge){if(ge===y)continue;return ge}}if(z.method==="next")z.sent=z._sent=z.arg;else if(z.method==="throw"){if(W===p)throw W=v,z.arg;z.dispatchException(z.arg)}else z.method==="return"&&z.abrupt("return",z.arg);W=g;var Q=h(V,B,z);if(Q.type==="normal"){if(W=z.done?v:m,Q.arg===y)continue;return{value:Q.arg,done:z.done}}Q.type==="throw"&&(W=v,z.method="throw",z.arg=Q.arg)}}}function U(V,B){var z=B.method,W=V.iterator[z];if(W===t)return B.delegate=null,z==="throw"&&V.iterator.return&&(B.method="return",B.arg=t,U(V,B),B.method==="throw")||z!=="return"&&(B.method="throw",B.arg=new TypeError("The iterator does not provide a '"+z+"' method")),y;var K=h(W,V.iterator,B.arg);if(K.type==="throw")return B.method="throw",B.arg=K.arg,B.delegate=null,y;var j=K.arg;return j?j.done?(B[V.resultName]=j.value,B.next=V.nextLoc,B.method!=="return"&&(B.method="next",B.arg=t),B.delegate=null,y):j:(B.method="throw",B.arg=new TypeError("iterator result is not an object"),B.delegate=null,y)}function L(V){var B={tryLoc:V[0]};1 in V&&(B.catchLoc=V[1]),2 in V&&(B.finallyLoc=V[2],B.afterLoc=V[3]),this.tryEntries.push(B)}function P(V){var B=V.completion||{};B.type="normal",delete B.arg,V.completion=B}function b(V){this.tryEntries=[{tryLoc:"root"}],V.forEach(L,this),this.reset(!0)}function H(V){if(V||V===""){var B=V[o];if(B)return B.call(V);if(typeof V.next=="function")return V;if(!isNaN(V.length)){var z=-1,W=function K(){for(;++z=0;--K){var j=this.tryEntries[K],Y=j.completion;if(j.tryLoc==="root")return W("end");if(j.tryLoc<=this.prev){var ge=r.call(j,"catchLoc"),Q=r.call(j,"finallyLoc");if(ge&&Q){if(this.prev=0;--W){var K=this.tryEntries[W];if(K.tryLoc<=this.prev&&r.call(K,"finallyLoc")&&this.prev=0;--z){var W=this.tryEntries[z];if(W.finallyLoc===B)return this.complete(W.completion,W.afterLoc),P(W),y}},catch:function(B){for(var z=this.tryEntries.length-1;z>=0;--z){var W=this.tryEntries[z];if(W.tryLoc===B){var K=W.completion;if(K.type==="throw"){var j=K.arg;P(W)}return j}}throw Error("illegal catch attempt")},delegateYield:function(B,z,W){return this.delegate={iterator:H(B),resultName:z,nextLoc:W},this.method==="next"&&(this.arg=t),y}},e}function $R(t,e,n,r,i,s,o){try{var a=t[s](o),l=a.value}catch(c){return void n(c)}a.done?e(l):Promise.resolve(l).then(r,i)}function dp(t){return function(){var e=this,n=arguments;return new Promise(function(r,i){var s=t.apply(e,n);function o(l){$R(s,r,i,o,a,"next",l)}function a(l){$R(s,r,i,o,a,"throw",l)}o(void 0)})}}function $W(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function qW(t,e){if(Vu(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(Vu(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function $O(t){var e=qW(t,"string");return Vu(e)=="symbol"?e:e+""}function XW(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=Array(e);n').concat(e,"")},u9=function(e,n){var r=n.style;return r?'').concat(e,""):e},h9=function(e,n){var r=n.pitch,i=n.rate;return!r&&!i?e:'').concat(e,"")},f9=function(e){return''.concat(e,"")},d9=function(e,n){var r=h9(e,n);return r=u9(r,n),r=c9(r,n),r=f9(r),r},qO=typeof global=="object"&&global&&global.Object===Object&&global,p9=typeof self=="object"&&self&&self.Object===Object&&self,La=qO||p9||Function("return this")(),oo=La.Symbol,XO=Object.prototype,m9=XO.hasOwnProperty,g9=XO.toString,Hd=oo?oo.toStringTag:void 0;function _9(t){var e=m9.call(t,Hd),n=t[Hd];try{t[Hd]=void 0;var r=!0}catch{}var i=g9.call(t);return r&&(e?t[Hd]=n:delete t[Hd]),i}var v9=Object.prototype,y9=v9.toString;function x9(t){return y9.call(t)}var S9="[object Null]",E9="[object Undefined]",KR=oo?oo.toStringTag:void 0;function Gc(t){return t==null?t===void 0?E9:S9:KR&&KR in Object(t)?_9(t):x9(t)}function Io(t){return t!=null&&typeof t=="object"}var w9="[object Symbol]";function Uv(t){return typeof t=="symbol"||Io(t)&&Gc(t)==w9}function Fv(t,e){for(var n=-1,r=t==null?0:t.length,i=Array(r);++n0){if(++e>=tj)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function sj(t){return function(){return t}}var I_=function(){try{var t=sh(Object,"defineProperty");return t({},"",{}),t}catch{}}(),oj=I_?function(t,e){return I_(t,"toString",{configurable:!0,enumerable:!1,value:sj(e),writable:!0})}:Pf,aj=ij(oj);function YO(t,e){for(var n=-1,r=t==null?0:t.length;++n-1}var uj=9007199254740991,hj=/^(?:0|[1-9]\d*)$/;function zv(t,e){var n=typeof t;return e=e??uj,!!e&&(n=="number"||n!="symbol"&&hj.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=mj}function Pa(t){return t!=null&&AT(t.length)&&!Fl(t)}function QO(t,e,n){if(!ao(n))return!1;var r=typeof e;return(r=="number"?Pa(n)&&zv(e,n.length):r=="string"&&e in n)?Qp(n[e],t):!1}function gj(t){return bT(function(e,n){var r=-1,i=n.length,s=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(s=t.length>3&&typeof s=="function"?(i--,s):void 0,o&&QO(n[0],n[1],o)&&(s=i<3?void 0:s,i=1),e=Object(e);++r-1}function M$(t,e){var n=this.__data__,r=Wv(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function Bl(t){var e=-1,n=t==null?0:t.length;for(this.clear();++ei?0:i+e),n=n>i?i:n,n<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var s=Array(i);++r=r?t:OT(t,e,n)}var W$="\\ud800-\\udfff",j$="\\u0300-\\u036f",$$="\\ufe20-\\ufe2f",q$="\\u20d0-\\u20ff",X$=j$+$$+q$,K$="\\ufe0e\\ufe0f",Y$="\\u200d",Z$=RegExp("["+Y$+W$+X$+K$+"]");function cL(t){return Z$.test(t)}function J$(t){return t.split("")}var uL="\\ud800-\\udfff",Q$="\\u0300-\\u036f",eq="\\ufe20-\\ufe2f",tq="\\u20d0-\\u20ff",nq=Q$+eq+tq,rq="\\ufe0e\\ufe0f",iq="["+uL+"]",LE="["+nq+"]",PE="\\ud83c[\\udffb-\\udfff]",sq="(?:"+LE+"|"+PE+")",hL="[^"+uL+"]",fL="(?:\\ud83c[\\udde6-\\uddff]){2}",dL="[\\ud800-\\udbff][\\udc00-\\udfff]",oq="\\u200d",pL=sq+"?",mL="["+rq+"]?",aq="(?:"+oq+"(?:"+[hL,fL,dL].join("|")+")"+mL+pL+")*",lq=mL+pL+aq,cq="(?:"+[hL+LE+"?",LE,fL,dL,iq].join("|")+")",uq=RegExp(PE+"(?="+PE+")|"+cq+lq,"g");function hq(t){return t.match(uq)||[]}function fq(t){return cL(t)?hq(t):J$(t)}function dq(t){return function(e){e=aL(e);var n=cL(e)?fq(e):void 0,r=n?n[0]:e.charAt(0),i=n?G$(n,1).join(""):e.slice(1);return r[t]()+i}}var gL=dq("toUpperCase");function pq(t,e,n,r){var i=-1,s=t==null?0:t.length;for(r&&s&&(n=t[++i]);++ia))return!1;var c=s.get(t),u=s.get(e);if(c&&u)return c==e&&u==t;var h=-1,p=!0,m=n&$7?new Df:void 0;for(s.set(t,e),s.set(e,t);++h2?e[2]:void 0;for(i&&QO(e[0],e[1],i)&&(r=1);++n=DX&&(s=DT,o=!1,e=new Df(e));e:for(;++i-1?i[s?e[o]:o]:void 0}}var HX=Math.max;function GX(t,e,n){var r=t==null?0:t.length;if(!r)return-1;var i=n==null?0:Bv(n);return i<0&&(i=HX(r+i,0)),ZO(t,Da(e),i)}var Ff=VX(GX);function Oo(t){return t&&t.length?t[0]:void 0}function WX(t,e){var n=-1,r=Pa(t)?Array(t.length):[];return oh(t,function(i,s,o){r[++n]=e(i,s,o)}),r}function ot(t,e){var n=un(t)?Fv:WX;return n(t,Da(e))}function no(t,e){return IT(ot(t,e))}var jX=Object.prototype,$X=jX.hasOwnProperty,NL=LX(function(t,e,n){$X.call(t,n)?t[n].push(e):wT(t,n,[e])}),qX=Object.prototype,XX=qX.hasOwnProperty;function KX(t,e){return t!=null&&XX.call(t,e)}function wt(t,e){return t!=null&&ML(t,e,KX)}var YX="[object String]";function fs(t){return typeof t=="string"||!un(t)&&Io(t)&&Gc(t)==YX}function ZX(t,e){return Fv(e,function(n){return t[n]})}function Cr(t){return t==null?[]:ZX(t,lo(t))}var JX=Math.max;function $i(t,e,n,r){t=Pa(t)?t:Cr(t),n=n&&!r?Bv(n):0;var i=t.length;return n<0&&(n=JX(i+n,0)),fs(t)?n<=i&&t.indexOf(e,n)>-1:!!i&&ET(t,e,n)>-1}function A2(t,e,n){var r=t==null?0:t.length;if(!r)return-1;var i=0;return ET(t,e,i)}var QX="[object Map]",eK="[object Set]",tK=Object.prototype,nK=tK.hasOwnProperty;function Un(t){if(t==null)return!0;if(Pa(t)&&(un(t)||typeof t=="string"||typeof t.splice=="function"||wp(t)||MT(t)||Hv(t)))return!t.length;var e=Xs(t);if(e==QX||e==eK)return!t.size;if(em(t))return!sL(t).length;for(var n in t)if(nK.call(t,n))return!1;return!0}var rK="[object RegExp]";function iK(t){return Io(t)&&Gc(t)==rK}var M2=Nc&&Nc.isRegExp,Cl=M2?Gv(M2):iK;function Rl(t){return t===void 0}var sK="Expected a function";function oK(t){if(typeof t!="function")throw new TypeError(sK);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}function aK(t,e,n,r){if(!ao(t))return t;e=$v(e,t);for(var i=-1,s=e.length,o=s-1,a=t;a!=null&&++i=dK){var c=fK(t);if(c)return UT(c);o=!1,i=DT,l=new Df}else l=a;e:for(;++r1&&u[1]!==void 0?u[1]:{},s=i.proxyUrl,o=r.input,a=r.options,l=new Headers({accept:"*/*","accept-language":"zh-CN,zh;q=0.9",authority:"southeastasia.api.speech.microsoft.com","content-type":"application/json",customvoiceconnectionid:l9(),origin:"https://speech.microsoft.com","sec-ch-ua":'"Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-site","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"}),c=JSON.stringify({offsetInPlainText:0,properties:{SpeakTriggerSource:"AccTuningPagePlayButton"},ssml:d9(o,a),ttsAudioFormat:"audio-24khz-48kbitrate-mono-mp3"}),p.abrupt("return",fetch(s||gK,{body:c,duplex:"half",headers:l,method:"POST",responseType:"arraybuffer"}));case 6:case"end":return p.stop()}},e)}));return function(n){return t.apply(this,arguments)}}(),mc={"ar-SA":["ar-SA-HamedNeural","ar-SA-ZariyahNeural"],"de-DE":["de-DE-AmalaNeural","de-DE-BerndNeural","de-DE-ChristophNeural","de-DE-ConradNeural","de-DE-ElkeNeural","de-DE-GiselaNeural","de-DE-KasperNeural","de-DE-KatjaNeural","de-DE-KillianNeural","de-DE-KlarissaNeural","de-DE-KlausNeural","de-DE-LouisaNeural","de-DE-MajaNeural","de-DE-RalfNeural","de-DE-TanjaNeural"],"en-US":["en-US-AIGenerate1Neural","en-US-AIGenerate2Neural","en-US-AmberNeural","en-US-AnaNeural","en-US-AndrewNeural","en-US-AriaNeural","en-US-AshleyNeural","en-US-BlueNeural","en-US-BrandonNeural","en-US-BrianNeural","en-US-ChristopherNeural","en-US-CoraNeural","en-US-DavisNeural","en-US-ElizabethNeural","en-US-EmmaNeural","en-US-EricNeural","en-US-GuyNeural","en-US-JacobNeural","en-US-JaneNeural","en-US-JasonNeural","en-US-JennyNeural","en-US-JennyMultilingualNeural","en-US-JennyMultilingualV2Neural","en-US-MichelleNeural","en-US-MonicaNeural","en-US-NancyNeural","en-US-RogerNeural","en-US-RyanMultilingualNeural","en-US-SaraNeural","en-US-SteffanNeural","en-US-TonyNeural"],"es-ES":["es-ES-AbrilNeural","es-ES-AlvaroNeural","es-ES-ArnauNeural","es-ES-DarioNeural","es-ES-EliasNeural","es-ES-ElviraNeural","es-ES-EstrellaNeural","es-ES-IreneNeural","es-ES-LaiaNeural","es-ES-LiaNeural","es-ES-NilNeural","es-ES-SaulNeural","es-ES-TeoNeural","es-ES-TrianaNeural","es-ES-VeraNeural"],"fr-FR":["fr-FR-AlainNeural","fr-FR-BrigitteNeural","fr-FR-CelesteNeural","fr-FR-ClaudeNeural","fr-FR-CoralieNeural","fr-FR-DeniseNeural","fr-FR-EloiseNeural","fr-FR-HenriNeural","fr-FR-JacquelineNeural","fr-FR-JeromeNeural","fr-FR-JosephineNeural","fr-FR-MauriceNeural","fr-FR-YvesNeural","fr-FR-YvetteNeural"],"ja-JP":["ja-JP-NanamiNeural","ja-JP-KeitaNeural","ja-JP-DaichiNeural","ja-JP-ShioriNeural","ja-JP-NaokiNeural","ja-JP-MayuNeural","ja-JP-AoiNeural"],"ko-KR":["ko-KR-GookMinNeural","ko-KR-BongJinNeural","ko-KR-SeoHyeonNeural","ko-KR-SunHiNeural","ko-KR-SoonBokNeural","ko-KR-YuJinNeural","ko-KR-InJoonNeural","ko-KR-JiMinNeural"],"pt-BR":["pt-BR-AntonioNeural","pt-BR-BrendaNeural","pt-BR-DonatoNeural","pt-BR-ElzaNeural","pt-BR-FabioNeural","pt-BR-FranciscaNeural","pt-BR-GiovannaNeural","pt-BR-HumbertoNeural","pt-BR-JulioNeural","pt-BR-LeilaNeural","pt-BR-LeticiaNeural","pt-BR-ManuelaNeural","pt-BR-NicolauNeural","pt-BR-ValerioNeural","pt-BR-YaraNeural"],"ru-RU":["ru-RU-DariyaNeural","ru-RU-DmitryNeural","ru-RU-SvetlanaNeural"],"zh-CN":["zh-CN-YunjianNeural","wuu-CN-YunzheNeural","zh-CN-YunxiaNeural","zh-CN-guangxi-YunqiNeural","zh-CN-sichuan-YunxiNeural","zh-CN-YunxiNeural","zh-CN-YunyangNeural","zh-CN-YunjieNeural","yue-CN-YunSongNeural","zh-CN-YunfengNeural","zh-CN-YunzeNeural","zh-CN-henan-YundengNeural","zh-CN-YunhaoNeural","zh-CN-shandong-YunxiangNeural","zh-CN-liaoning-YunbiaoNeural","zh-CN-YunyeNeural","zh-CN-XiaoyiNeural","zh-CN-liaoning-XiaobeiNeural","zh-CN-XiaoshuangNeural","zh-CN-shaanxi-XiaoniNeural","wuu-CN-XiaotongNeural","zh-CN-XiaoyouNeural","yue-CN-XiaoMinNeural","zh-CN-XiaoxiaoNeural","zh-CN-XiaorouNeural","zh-CN-XiaomengNeural","zh-CN-XiaohanNeural","zh-CN-XiaozhenNeural","zh-CN-XiaoruiNeural","zh-CN-XiaoqiuNeural","zh-CN-XiaoxuanNeural","zh-CN-XiaochenNeural","zh-CN-XiaoyanNeural","zh-CN-XiaomoNeural"],"zh-TW":["zh-TW-HsiaoChenNeural","zh-TW-HsiaoYuNeural","zh-TW-YunJheNeural"]},_K=function(e){var n=e&&mc!==null&&mc!==void 0&&mc[e]?(mc==null?void 0:mc[e])||[]:ls(Object.values(mc));return n.map(function(r){return{label:(t_==null?void 0:t_[r])||r,value:r}})},od=function(){function t(){var e=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=n.serviceUrl,i=n.locale,s=n.headers;$W(this,t),Eo(this,"locale",void 0),Eo(this,"serviceUrl",void 0),Eo(this,"headers",void 0),Eo(this,"fetch",function(){var o=dp(So().mark(function a(l){var c;return So().wrap(function(h){for(;;)switch(h.prev=h.next){case 0:return h.next=2,e.serviceUrl?fetch(e.serviceUrl,{body:JSON.stringify(l),headers:e.headers,method:"POST"}):kL({payload:l});case 2:return c=h.sent,h.abrupt("return",c);case 4:case"end":return h.stop()}},a)}));return function(a){return o.apply(this,arguments)}}()),Eo(this,"create",function(){var o=dp(So().mark(function a(l){return So().wrap(function(u){for(;;)switch(u.prev=u.next){case 0:return u.next=2,e.fetch(l);case 2:return u.abrupt("return",u.sent);case 3:case"end":return u.stop()}},a)}));return function(a){return o.apply(this,arguments)}}()),Eo(this,"createAudio",function(){var o=dp(So().mark(function a(l){var c,u;return So().wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,e.create(l);case 2:return c=p.sent,p.next=5,c.arrayBuffer();case 5:return u=p.sent,p.abrupt("return",YW(u));case 7:case"end":return p.stop()}},a)}));return function(a){return o.apply(this,arguments)}}()),this.locale=i,this.serviceUrl=r,this.headers=s}return KW(t,[{key:"voiceOptions",get:function(){return _K(this.locale)}}]),t}();Eo(od,"localeOptions",r9());Eo(od,"createRequest",kL);Eo(od,"voiceList",mc);Eo(od,"voiceName",t_);Eo(od,"styleList",mK);const IL="15.0.4",C2=(t,e,n)=>({endTime:e,insertTime:n,type:"exponentialRampToValue",value:t}),R2=(t,e,n)=>({endTime:e,insertTime:n,type:"linearRampToValue",value:t}),BE=(t,e)=>({startTime:e,type:"setValue",value:t}),OL=(t,e,n)=>({duration:n,startTime:e,type:"setValueCurve",values:t}),LL=(t,e,{startTime:n,target:r,timeConstant:i})=>r+(e-r)*Math.exp((n-t)/i),uf=t=>t.type==="exponentialRampToValue",L_=t=>t.type==="linearRampToValue",gc=t=>uf(t)||L_(t),VT=t=>t.type==="setValue",hl=t=>t.type==="setValueCurve",P_=(t,e,n,r)=>{const i=t[e];return i===void 0?r:gc(i)||VT(i)?i.value:hl(i)?i.values[i.values.length-1]:LL(n,P_(t,e-1,i.startTime,r),i)},N2=(t,e,n,r,i)=>n===void 0?[r.insertTime,i]:gc(n)?[n.endTime,n.value]:VT(n)?[n.startTime,n.value]:hl(n)?[n.startTime+n.duration,n.values[n.values.length-1]]:[n.startTime,P_(t,e-1,n.startTime,i)],zE=t=>t.type==="cancelAndHold",VE=t=>t.type==="cancelScheduledValues",dc=t=>zE(t)||VE(t)?t.cancelTime:uf(t)||L_(t)?t.endTime:t.startTime,k2=(t,e,n,{endTime:r,value:i})=>n===i?i:0n+(t-e)/(r-e)*(i-n),vK=(t,e)=>{const n=Math.floor(e),r=Math.ceil(e);return n===r?t[n]:(1-(e-n))*t[n]+(1-(r-e))*t[r]},yK=(t,{duration:e,startTime:n,values:r})=>{const i=(t-n)/e*(r.length-1);return vK(r,i)},g0=t=>t.type==="setTarget";class xK{constructor(e){this._automationEvents=[],this._currenTime=0,this._defaultValue=e}[Symbol.iterator](){return this._automationEvents[Symbol.iterator]()}add(e){const n=dc(e);if(zE(e)||VE(e)){const r=this._automationEvents.findIndex(s=>VE(e)&&hl(s)?s.startTime+s.duration>=n:dc(s)>=n),i=this._automationEvents[r];if(r!==-1&&(this._automationEvents=this._automationEvents.slice(0,r)),zE(e)){const s=this._automationEvents[this._automationEvents.length-1];if(i!==void 0&&gc(i)){if(s!==void 0&&g0(s))throw new Error("The internal list is malformed.");const o=s===void 0?i.insertTime:hl(s)?s.startTime+s.duration:dc(s),a=s===void 0?this._defaultValue:hl(s)?s.values[s.values.length-1]:s.value,l=uf(i)?k2(n,o,a,i):I2(n,o,a,i),c=uf(i)?C2(l,n,this._currenTime):R2(l,n,this._currenTime);this._automationEvents.push(c)}if(s!==void 0&&g0(s)&&this._automationEvents.push(BE(this.getValue(n),n)),s!==void 0&&hl(s)&&s.startTime+s.duration>n){const o=n-s.startTime,a=(s.values.length-1)/s.duration,l=Math.max(2,1+Math.ceil(o*a)),c=o/(l-1)*a,u=s.values.slice(0,l);if(c<1)for(let h=1;hdc(o)>n),i=r===-1?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[r-1];if(i!==void 0&&hl(i)&&dc(i)+i.duration>n)return!1;const s=uf(e)?C2(e.value,e.endTime,this._currenTime):L_(e)?R2(e.value,n,this._currenTime):e;if(r===-1)this._automationEvents.push(s);else{if(hl(e)&&n+e.duration>dc(this._automationEvents[r]))return!1;this._automationEvents.splice(r,0,s)}}return!0}flush(e){const n=this._automationEvents.findIndex(r=>dc(r)>e);if(n>1){const r=this._automationEvents.slice(n-1),i=r[0];g0(i)&&r.unshift(BE(P_(this._automationEvents,n-2,i.startTime,this._defaultValue),i.startTime)),this._automationEvents=r}}getValue(e){if(this._automationEvents.length===0)return this._defaultValue;const n=this._automationEvents.findIndex(o=>dc(o)>e),r=this._automationEvents[n],i=(n===-1?this._automationEvents.length:n)-1,s=this._automationEvents[i];if(s!==void 0&&g0(s)&&(r===void 0||!gc(r)||r.insertTime>e))return LL(e,P_(this._automationEvents,i-1,s.startTime,this._defaultValue),s);if(s!==void 0&&VT(s)&&(r===void 0||!gc(r)))return s.value;if(s!==void 0&&hl(s)&&(r===void 0||!gc(r)||s.startTime+s.duration>e))return e({cancelTime:t,type:"cancelAndHold"}),EK=t=>({cancelTime:t,type:"cancelScheduledValues"}),wK=(t,e)=>({endTime:e,type:"exponentialRampToValue",value:t}),TK=(t,e)=>({endTime:e,type:"linearRampToValue",value:t}),bK=(t,e,n)=>({startTime:e,target:t,timeConstant:n,type:"setTarget"}),AK=()=>new DOMException("","AbortError"),MK=t=>(e,n,[r,i,s],o)=>{t(e[i],[n,r,s],a=>a[0]===n&&a[1]===r,o)},CK=t=>(e,n,r)=>{const i=[];for(let s=0;s(e,n)=>{t.set(e,{activeInputs:new Set,passiveInputs:new WeakMap,renderer:n})},Bf=new WeakSet,PL=new WeakMap,HT=new WeakMap,DL=new WeakMap,GT=new WeakMap,Yv=new WeakMap,UL=new WeakMap,HE=new WeakMap,GE=new WeakMap,WE=new WeakMap,FL={construct(){return FL}},NK=t=>{try{const e=new Proxy(t,FL);new e}catch{return!1}return!0},O2=/^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/,L2=(t,e)=>{const n=[];let r=t.replace(/^[\s]+/,""),i=r.match(O2);for(;i!==null;){const s=i[1].slice(1,-1),o=i[0].replace(/([\s]+)?;?$/,"").replace(s,new URL(s,e).toString());n.push(o),r=r.slice(i[0].length).replace(/^[\s]+/,""),i=r.match(O2)}return[n.join(";"),r]},P2=t=>{if(t!==void 0&&!Array.isArray(t))throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.")},D2=t=>{if(!NK(t))throw new TypeError("The given value for processorCtor should be a constructor.");if(t.prototype===null||typeof t.prototype!="object")throw new TypeError("The given value for processorCtor should have a prototype.")},kK=(t,e,n,r,i,s,o,a,l,c,u,h,p)=>{let m=0;return(g,v,y={credentials:"omit"})=>{const _=u.get(g);if(_!==void 0&&_.has(v))return Promise.resolve();const S=c.get(g);if(S!==void 0){const N=S.get(v);if(N!==void 0)return N}const E=s(g),T=E.audioWorklet===void 0?i(v).then(([N,R])=>{const[C,O]=L2(N,R),M=`${C};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${O} +})})(window,'_AWGS')`;return n(M)}).then(()=>{const N=p._AWGS.pop();if(N===void 0)throw new SyntaxError;r(E.currentTime,E.sampleRate,()=>N(class{},void 0,(R,C)=>{if(R.trim()==="")throw e();const O=GE.get(E);if(O!==void 0){if(O.has(R))throw e();D2(C),P2(C.parameterDescriptors),O.set(R,C)}else D2(C),P2(C.parameterDescriptors),GE.set(E,new Map([[R,C]]))},E.sampleRate,void 0,void 0))}):Promise.all([i(v),Promise.resolve(t(h,h))]).then(([[N,R],C])=>{const O=m+1;m=O;const[M,I]=L2(N,R),b=`${M};((AudioWorkletProcessor,registerProcessor)=>{${I} +})(${C?"AudioWorkletProcessor":"class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}"},(n,p)=>registerProcessor(n,class extends p{${C?"":"__c = (a) => a.forEach(e=>this.__b.add(e.buffer));"}process(i,o,p){${C?"":"i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));"}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${O}',class extends AudioWorkletProcessor{process(){return !1}})`,H=new Blob([b],{type:"application/javascript; charset=utf-8"}),V=URL.createObjectURL(H);return E.audioWorklet.addModule(V,y).then(()=>{if(a(E))return E;const B=o(E);return B.audioWorklet.addModule(V,y).then(()=>B)}).then(B=>{if(l===null)throw new SyntaxError;try{new l(B,`__sac${O}`)}catch{throw new SyntaxError}}).finally(()=>URL.revokeObjectURL(V))});return S===void 0?c.set(g,new Map([[v,T]])):S.set(v,T),T.then(()=>{const N=u.get(g);N===void 0?u.set(g,new Set([v])):N.add(v)}).finally(()=>{const N=c.get(g);N!==void 0&&N.delete(v)}),T}},Lo=(t,e)=>{const n=t.get(e);if(n===void 0)throw new Error("A value with the given key could not be found.");return n},Zv=(t,e)=>{const n=Array.from(t).filter(e);if(n.length>1)throw Error("More than one element was found.");if(n.length===0)throw Error("No element was found.");const[r]=n;return t.delete(r),r},BL=(t,e,n,r)=>{const i=Lo(t,e),s=Zv(i,o=>o[0]===n&&o[1]===r);return i.size===0&&t.delete(e),s},rm=t=>Lo(UL,t),zf=t=>{if(Bf.has(t))throw new Error("The AudioNode is already stored.");Bf.add(t),rm(t).forEach(e=>e(!0))},zL=t=>"port"in t,im=t=>{if(!Bf.has(t))throw new Error("The AudioNode is not stored.");Bf.delete(t),rm(t).forEach(e=>e(!1))},jE=(t,e)=>{!zL(t)&&e.every(n=>n.size===0)&&im(t)},IK=(t,e,n,r,i,s,o,a,l,c,u,h,p)=>{const m=new WeakMap;return(g,v,y,_,S)=>{const{activeInputs:E,passiveInputs:T}=s(v),{outputs:N}=s(g),R=a(g),C=O=>{const M=l(v),I=l(g);if(O){const U=BL(T,g,y,_);t(E,g,U,!1),!S&&!h(g)&&n(I,M,y,_),p(v)&&zf(v)}else{const U=r(E,g,y,_);e(T,_,U,!1),!S&&!h(g)&&i(I,M,y,_);const L=o(v);if(L===0)u(v)&&jE(v,E);else{const P=m.get(v);P!==void 0&&clearTimeout(P),m.set(v,setTimeout(()=>{u(v)&&jE(v,E)},L*1e3))}}};return c(N,[v,y,_],O=>O[0]===v&&O[1]===y&&O[2]===_,!0)?(R.add(C),u(g)?t(E,g,[y,_,C],!0):e(T,_,[g,y,C],!0),!0):!1}},OK=t=>(e,n,[r,i,s],o)=>{const a=e.get(r);a===void 0?e.set(r,new Set([[i,n,s]])):t(a,[i,n,s],l=>l[0]===i&&l[1]===n,o)},LK=t=>(e,n)=>{const r=t(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});n.connect(r).connect(e.destination);const i=()=>{n.removeEventListener("ended",i),n.disconnect(r),r.disconnect()};n.addEventListener("ended",i)},PK=t=>(e,n)=>{t(e).add(n)},DK={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},UK=(t,e,n,r,i,s)=>class extends t{constructor(a,l){const c=i(a),u={...DK,...l},h=r(c,u),p=s(c)?e():null;super(a,!1,h,p),this._nativeAnalyserNode=h}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(a){this._nativeAnalyserNode.fftSize=a}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(a){const l=this._nativeAnalyserNode.maxDecibels;if(this._nativeAnalyserNode.maxDecibels=a,!(a>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=l,n()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(a){const l=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=a,!(this._nativeAnalyserNode.maxDecibels>a))throw this._nativeAnalyserNode.minDecibels=l,n()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(a){this._nativeAnalyserNode.smoothingTimeConstant=a}getByteFrequencyData(a){this._nativeAnalyserNode.getByteFrequencyData(a)}getByteTimeDomainData(a){this._nativeAnalyserNode.getByteTimeDomainData(a)}getFloatFrequencyData(a){this._nativeAnalyserNode.getFloatFrequencyData(a)}getFloatTimeDomainData(a){this._nativeAnalyserNode.getFloatTimeDomainData(a)}},bi=(t,e)=>t.context===e,FK=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!bi(a,o)){const c={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,fftSize:a.fftSize,maxDecibels:a.maxDecibels,minDecibels:a.minDecibels,smoothingTimeConstant:a.smoothingTimeConstant};a=t(o,c)}return r.set(o,a),await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},D_=t=>{try{t.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0},Ua=()=>new DOMException("","IndexSizeError"),WT=t=>{t.getChannelData=(e=>n=>{try{return e.call(t,n)}catch(r){throw r.code===12?Ua():r}})(t.getChannelData)},BK={numberOfChannels:1},zK=(t,e,n,r,i,s,o,a)=>{let l=null;return class VL{constructor(u){if(i===null)throw new Error("Missing the native OfflineAudioContext constructor.");const{length:h,numberOfChannels:p,sampleRate:m}={...BK,...u};l===null&&(l=new i(1,1,44100));const g=r!==null&&e(s,s)?new r({length:h,numberOfChannels:p,sampleRate:m}):l.createBuffer(p,h,m);if(g.numberOfChannels===0)throw n();return typeof g.copyFromChannel!="function"?(o(g),WT(g)):e(D_,()=>D_(g))||a(g),t.add(g),g}static[Symbol.hasInstance](u){return u!==null&&typeof u=="object"&&Object.getPrototypeOf(u)===VL.prototype||t.has(u)}}},ts=-34028234663852886e22,Di=-ts,yl=t=>Bf.has(t),VK={buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1},HK=(t,e,n,r,i,s,o,a)=>class extends t{constructor(c,u){const h=s(c),p={...VK,...u},m=i(h,p),g=o(h),v=g?e():null;super(c,!1,m,v),this._audioBufferSourceNodeRenderer=v,this._isBufferNullified=!1,this._isBufferSet=p.buffer!==null,this._nativeAudioBufferSourceNode=m,this._onended=null,this._playbackRate=n(this,g,m.playbackRate,Di,ts)}get buffer(){return this._isBufferNullified?null:this._nativeAudioBufferSourceNode.buffer}set buffer(c){if(this._nativeAudioBufferSourceNode.buffer=c,c!==null){if(this._isBufferSet)throw r();this._isBufferSet=!0}}get loop(){return this._nativeAudioBufferSourceNode.loop}set loop(c){this._nativeAudioBufferSourceNode.loop=c}get loopEnd(){return this._nativeAudioBufferSourceNode.loopEnd}set loopEnd(c){this._nativeAudioBufferSourceNode.loopEnd=c}get loopStart(){return this._nativeAudioBufferSourceNode.loopStart}set loopStart(c){this._nativeAudioBufferSourceNode.loopStart=c}get onended(){return this._onended}set onended(c){const u=typeof c=="function"?a(this,c):null;this._nativeAudioBufferSourceNode.onended=u;const h=this._nativeAudioBufferSourceNode.onended;this._onended=h!==null&&h===u?c:h}get playbackRate(){return this._playbackRate}start(c=0,u=0,h){if(this._nativeAudioBufferSourceNode.start(c,u,h),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.start=h===void 0?[c,u]:[c,u,h]),this.context.state!=="closed"){zf(this);const p=()=>{this._nativeAudioBufferSourceNode.removeEventListener("ended",p),yl(this)&&im(this)};this._nativeAudioBufferSourceNode.addEventListener("ended",p)}}stop(c=0){this._nativeAudioBufferSourceNode.stop(c),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.stop=c)}},GK=(t,e,n,r,i)=>()=>{const s=new WeakMap;let o=null,a=null;const l=async(c,u)=>{let h=n(c);const p=bi(h,u);if(!p){const m={buffer:h.buffer,channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,loop:h.loop,loopEnd:h.loopEnd,loopStart:h.loopStart,playbackRate:h.playbackRate.value};h=e(u,m),o!==null&&h.start(...o),a!==null&&h.stop(a)}return s.set(u,h),p?await t(u,c.playbackRate,h.playbackRate):await r(u,c.playbackRate,h.playbackRate),await i(c,u,h),h};return{set start(c){o=c},set stop(c){a=c},render(c,u){const h=s.get(u);return h!==void 0?Promise.resolve(h):l(c,u)}}},WK=t=>"playbackRate"in t,jK=t=>"frequency"in t&&"gain"in t,$K=t=>"offset"in t,qK=t=>!("frequency"in t)&&"gain"in t,XK=t=>"detune"in t&&"frequency"in t&&!("gain"in t),KK=t=>"pan"in t,Bi=t=>Lo(PL,t),sm=t=>Lo(DL,t),$E=(t,e)=>{const{activeInputs:n}=Bi(t);n.forEach(i=>i.forEach(([s])=>{e.includes(t)||$E(s,[...e,t])}));const r=WK(t)?[t.playbackRate]:zL(t)?Array.from(t.parameters.values()):jK(t)?[t.Q,t.detune,t.frequency,t.gain]:$K(t)?[t.offset]:qK(t)?[t.gain]:XK(t)?[t.detune,t.frequency]:KK(t)?[t.pan]:[];for(const i of r){const s=sm(i);s!==void 0&&s.activeInputs.forEach(([o])=>$E(o,e))}yl(t)&&im(t)},HL=t=>{$E(t.destination,[])},YK=t=>t===void 0||typeof t=="number"||typeof t=="string"&&(t==="balanced"||t==="interactive"||t==="playback"),ZK=(t,e,n,r,i,s,o,a,l)=>class extends t{constructor(u={}){if(l===null)throw new Error("Missing the native AudioContext constructor.");let h;try{h=new l(u)}catch(g){throw g.code===12&&g.message==="sampleRate is not in range"?n():g}if(h===null)throw r();if(!YK(u.latencyHint))throw new TypeError(`The provided value '${u.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(u.sampleRate!==void 0&&h.sampleRate!==u.sampleRate)throw n();super(h,2);const{latencyHint:p}=u,{sampleRate:m}=h;if(this._baseLatency=typeof h.baseLatency=="number"?h.baseLatency:p==="balanced"?512/m:p==="interactive"||p===void 0?256/m:p==="playback"?1024/m:Math.max(2,Math.min(128,Math.round(p*m/128)))*128/m,this._nativeAudioContext=h,l.name==="webkitAudioContext"?(this._nativeGainNode=h.createGain(),this._nativeOscillatorNode=h.createOscillator(),this._nativeGainNode.gain.value=1e-37,this._nativeOscillatorNode.connect(this._nativeGainNode).connect(h.destination),this._nativeOscillatorNode.start()):(this._nativeGainNode=null,this._nativeOscillatorNode=null),this._state=null,h.state==="running"){this._state="suspended";const g=()=>{this._state==="suspended"&&(this._state=null),h.removeEventListener("statechange",g)};h.addEventListener("statechange",g)}}get baseLatency(){return this._baseLatency}get state(){return this._state!==null?this._state:this._nativeAudioContext.state}close(){return this.state==="closed"?this._nativeAudioContext.close().then(()=>{throw e()}):(this._state==="suspended"&&(this._state=null),this._nativeAudioContext.close().then(()=>{this._nativeGainNode!==null&&this._nativeOscillatorNode!==null&&(this._nativeOscillatorNode.stop(),this._nativeGainNode.disconnect(),this._nativeOscillatorNode.disconnect()),HL(this)}))}createMediaElementSource(u){return new i(this,{mediaElement:u})}createMediaStreamDestination(){return new s(this)}createMediaStreamSource(u){return new o(this,{mediaStream:u})}createMediaStreamTrackSource(u){return new a(this,{mediaStreamTrack:u})}resume(){return this._state==="suspended"?new Promise((u,h)=>{const p=()=>{this._nativeAudioContext.removeEventListener("statechange",p),this._nativeAudioContext.state==="running"?u():this.resume().then(u,h)};this._nativeAudioContext.addEventListener("statechange",p)}):this._nativeAudioContext.resume().catch(u=>{throw u===void 0||u.code===15?e():u})}suspend(){return this._nativeAudioContext.suspend().catch(u=>{throw u===void 0?e():u})}},JK=(t,e,n,r,i,s,o,a)=>class extends t{constructor(c,u){const h=s(c),p=o(h),m=i(h,u,p),g=p?e(a):null;super(c,!1,m,g),this._isNodeOfNativeOfflineAudioContext=p,this._nativeAudioDestinationNode=m}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(c){if(this._isNodeOfNativeOfflineAudioContext)throw r();if(c>this._nativeAudioDestinationNode.maxChannelCount)throw n();this._nativeAudioDestinationNode.channelCount=c}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(c){if(this._isNodeOfNativeOfflineAudioContext)throw r();this._nativeAudioDestinationNode.channelCountMode=c}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}},QK=t=>{const e=new WeakMap,n=async(r,i)=>{const s=i.destination;return e.set(i,s),await t(r,i,s),s};return{render(r,i){const s=e.get(i);return s!==void 0?Promise.resolve(s):n(r,i)}}},eY=(t,e,n,r,i,s,o,a)=>(l,c)=>{const u=c.listener,h=()=>{const N=new Float32Array(1),R=e(c,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:9}),C=o(c);let O=!1,M=[0,0,-1,0,1,0],I=[0,0,0];const U=()=>{if(O)return;O=!0;const H=r(c,256,9,0);H.onaudioprocess=({inputBuffer:V})=>{const B=[s(V,N,0),s(V,N,1),s(V,N,2),s(V,N,3),s(V,N,4),s(V,N,5)];B.some((W,K)=>W!==M[K])&&(u.setOrientation(...B),M=B);const z=[s(V,N,6),s(V,N,7),s(V,N,8)];z.some((W,K)=>W!==I[K])&&(u.setPosition(...z),I=z)},R.connect(H)},L=H=>V=>{V!==M[H]&&(M[H]=V,u.setOrientation(...M))},P=H=>V=>{V!==I[H]&&(I[H]=V,u.setPosition(...I))},b=(H,V,B)=>{const z=n(c,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:V});z.connect(R,0,H),z.start(),Object.defineProperty(z.offset,"defaultValue",{get(){return V}});const W=t({context:l},C,z.offset,Di,ts);return a(W,"value",K=>()=>K.call(W),K=>j=>{try{K.call(W,j)}catch(Y){if(Y.code!==9)throw Y}U(),C&&B(j)}),W.cancelAndHoldAtTime=(K=>C?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.cancelAndHoldAtTime),W.cancelScheduledValues=(K=>C?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.cancelScheduledValues),W.exponentialRampToValueAtTime=(K=>C?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.exponentialRampToValueAtTime),W.linearRampToValueAtTime=(K=>C?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.linearRampToValueAtTime),W.setTargetAtTime=(K=>C?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.setTargetAtTime),W.setValueAtTime=(K=>C?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.setValueAtTime),W.setValueCurveAtTime=(K=>C?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.setValueCurveAtTime),W};return{forwardX:b(0,0,L(0)),forwardY:b(1,0,L(1)),forwardZ:b(2,-1,L(2)),positionX:b(6,0,P(0)),positionY:b(7,0,P(1)),positionZ:b(8,0,P(2)),upX:b(3,0,L(3)),upY:b(4,1,L(4)),upZ:b(5,0,L(5))}},{forwardX:p,forwardY:m,forwardZ:g,positionX:v,positionY:y,positionZ:_,upX:S,upY:E,upZ:T}=u.forwardX===void 0?h():u;return{get forwardX(){return p},get forwardY(){return m},get forwardZ(){return g},get positionX(){return v},get positionY(){return y},get positionZ(){return _},get upX(){return S},get upY(){return E},get upZ(){return T}}},U_=t=>"context"in t,om=t=>U_(t[0]),ah=(t,e,n,r)=>{for(const i of t)if(n(i)){if(r)return!1;throw Error("The set contains at least one similar element.")}return t.add(e),!0},U2=(t,e,[n,r],i)=>{ah(t,[e,n,r],s=>s[0]===e&&s[1]===n,i)},F2=(t,[e,n,r],i)=>{const s=t.get(e);s===void 0?t.set(e,new Set([[n,r]])):ah(s,[n,r],o=>o[0]===n,i)},ad=t=>"inputs"in t,F_=(t,e,n,r)=>{if(ad(e)){const i=e.inputs[r];return t.connect(i,n,0),[i,n,0]}return t.connect(e,n,r),[e,n,r]},GL=(t,e,n)=>{for(const r of t)if(r[0]===e&&r[1]===n)return t.delete(r),r;return null},tY=(t,e,n)=>Zv(t,r=>r[0]===e&&r[1]===n),WL=(t,e)=>{if(!rm(t).delete(e))throw new Error("Missing the expected event listener.")},jL=(t,e,n)=>{const r=Lo(t,e),i=Zv(r,s=>s[0]===n);return r.size===0&&t.delete(e),i},B_=(t,e,n,r)=>{ad(e)?t.disconnect(e.inputs[r],n,0):t.disconnect(e,n,r)},Hn=t=>Lo(HT,t),Mp=t=>Lo(GT,t),Gu=t=>HE.has(t),r_=t=>!Bf.has(t),B2=(t,e)=>new Promise(n=>{if(e!==null)n(!0);else{const r=t.createScriptProcessor(256,1,1),i=t.createGain(),s=t.createBuffer(1,2,44100),o=s.getChannelData(0);o[0]=1,o[1]=1;const a=t.createBufferSource();a.buffer=s,a.loop=!0,a.connect(r).connect(t.destination),a.connect(i),a.disconnect(i),r.onaudioprocess=l=>{const c=l.inputBuffer.getChannelData(0);Array.prototype.some.call(c,u=>u===1)?n(!0):n(!1),a.stop(),r.onaudioprocess=null,a.disconnect(r),r.disconnect(t.destination)},a.start()}}),$S=(t,e)=>{const n=new Map;for(const r of t)for(const i of r){const s=n.get(i);n.set(i,s===void 0?1:s+1)}n.forEach((r,i)=>e(i,r))},z_=t=>"context"in t,nY=t=>{const e=new Map;t.connect=(n=>(r,i=0,s=0)=>{const o=z_(r)?n(r,i,s):n(r,i),a=e.get(r);return a===void 0?e.set(r,[{input:s,output:i}]):a.every(l=>l.input!==s||l.output!==i)&&a.push({input:s,output:i}),o})(t.connect.bind(t)),t.disconnect=(n=>(r,i,s)=>{if(n.apply(t),r===void 0)e.clear();else if(typeof r=="number")for(const[o,a]of e){const l=a.filter(c=>c.output!==r);l.length===0?e.delete(o):e.set(o,l)}else if(e.has(r))if(i===void 0)e.delete(r);else{const o=e.get(r);if(o!==void 0){const a=o.filter(l=>l.output!==i&&(l.input!==s||s===void 0));a.length===0?e.delete(r):e.set(r,a)}}for(const[o,a]of e)a.forEach(l=>{z_(o)?t.connect(o,l.output,l.input):t.connect(o,l.output)})})(t.disconnect)},rY=(t,e,n,r)=>{const{activeInputs:i,passiveInputs:s}=sm(e),{outputs:o}=Bi(t),a=rm(t),l=c=>{const u=Hn(t),h=Mp(e);if(c){const p=jL(s,t,n);U2(i,t,p,!1),!r&&!Gu(t)&&u.connect(h,n)}else{const p=tY(i,t,n);F2(s,p,!1),!r&&!Gu(t)&&u.disconnect(h,n)}};return ah(o,[e,n],c=>c[0]===e&&c[1]===n,!0)?(a.add(l),yl(t)?U2(i,t,[n,l],!0):F2(s,[t,n,l],!0),!0):!1},iY=(t,e,n,r)=>{const{activeInputs:i,passiveInputs:s}=Bi(e),o=GL(i[r],t,n);return o===null?[BL(s,t,n,r)[2],!1]:[o[2],!0]},sY=(t,e,n)=>{const{activeInputs:r,passiveInputs:i}=sm(e),s=GL(r,t,n);return s===null?[jL(i,t,n)[1],!1]:[s[2],!0]},jT=(t,e,n,r,i)=>{const[s,o]=iY(t,n,r,i);if(s!==null&&(WL(t,s),o&&!e&&!Gu(t)&&B_(Hn(t),Hn(n),r,i)),yl(n)){const{activeInputs:a}=Bi(n);jE(n,a)}},$T=(t,e,n,r)=>{const[i,s]=sY(t,n,r);i!==null&&(WL(t,i),s&&!e&&!Gu(t)&&Hn(t).disconnect(Mp(n),r))},oY=(t,e)=>{const n=Bi(t),r=[];for(const i of n.outputs)om(i)?jT(t,e,...i):$T(t,e,...i),r.push(i[0]);return n.outputs.clear(),r},aY=(t,e,n)=>{const r=Bi(t),i=[];for(const s of r.outputs)s[1]===n&&(om(s)?jT(t,e,...s):$T(t,e,...s),i.push(s[0]),r.outputs.delete(s));return i},lY=(t,e,n,r,i)=>{const s=Bi(t);return Array.from(s.outputs).filter(o=>o[0]===n&&(r===void 0||o[1]===r)&&(i===void 0||o[2]===i)).map(o=>(om(o)?jT(t,e,...o):$T(t,e,...o),s.outputs.delete(o),o[0]))},cY=(t,e,n,r,i,s,o,a,l,c,u,h,p,m,g,v)=>class extends c{constructor(_,S,E,T){super(E),this._context=_,this._nativeAudioNode=E;const N=u(_);h(N)&&n(B2,()=>B2(N,v))!==!0&&nY(E),HT.set(this,E),UL.set(this,new Set),_.state!=="closed"&&S&&zf(this),t(this,T,E)}get channelCount(){return this._nativeAudioNode.channelCount}set channelCount(_){this._nativeAudioNode.channelCount=_}get channelCountMode(){return this._nativeAudioNode.channelCountMode}set channelCountMode(_){this._nativeAudioNode.channelCountMode=_}get channelInterpretation(){return this._nativeAudioNode.channelInterpretation}set channelInterpretation(_){this._nativeAudioNode.channelInterpretation=_}get context(){return this._context}get numberOfInputs(){return this._nativeAudioNode.numberOfInputs}get numberOfOutputs(){return this._nativeAudioNode.numberOfOutputs}connect(_,S=0,E=0){if(S<0||S>=this._nativeAudioNode.numberOfOutputs)throw i();const T=u(this._context),N=g(T);if(p(_)||m(_))throw s();if(U_(_)){const O=Hn(_);try{const I=F_(this._nativeAudioNode,O,S,E),U=r_(this);(N||U)&&this._nativeAudioNode.disconnect(...I),this.context.state!=="closed"&&!U&&r_(_)&&zf(_)}catch(I){throw I.code===12?s():I}if(e(this,_,S,E,N)){const I=l([this],_);$S(I,r(N))}return _}const R=Mp(_);if(R.name==="playbackRate"&&R.maxValue===1024)throw o();try{this._nativeAudioNode.connect(R,S),(N||r_(this))&&this._nativeAudioNode.disconnect(R,S)}catch(O){throw O.code===12?s():O}if(rY(this,_,S,N)){const O=l([this],_);$S(O,r(N))}}disconnect(_,S,E){let T;const N=u(this._context),R=g(N);if(_===void 0)T=oY(this,R);else if(typeof _=="number"){if(_<0||_>=this.numberOfOutputs)throw i();T=aY(this,R,_)}else{if(S!==void 0&&(S<0||S>=this.numberOfOutputs)||U_(_)&&E!==void 0&&(E<0||E>=_.numberOfInputs))throw i();if(T=lY(this,R,_,S,E),T.length===0)throw s()}for(const C of T){const O=l([this],C);$S(O,a)}}},uY=(t,e,n,r,i,s,o,a,l,c,u,h,p)=>(m,g,v,y=null,_=null)=>{const S=v.value,E=new xK(S),T=g?r(E):null,N={get defaultValue(){return S},get maxValue(){return y===null?v.maxValue:y},get minValue(){return _===null?v.minValue:_},get value(){return v.value},set value(R){v.value=R,N.setValueAtTime(R,m.context.currentTime)},cancelAndHoldAtTime(R){if(typeof v.cancelAndHoldAtTime=="function")T===null&&E.flush(m.context.currentTime),E.add(i(R)),v.cancelAndHoldAtTime(R);else{const C=Array.from(E).pop();T===null&&E.flush(m.context.currentTime),E.add(i(R));const O=Array.from(E).pop();v.cancelScheduledValues(R),C!==O&&O!==void 0&&(O.type==="exponentialRampToValue"?v.exponentialRampToValueAtTime(O.value,O.endTime):O.type==="linearRampToValue"?v.linearRampToValueAtTime(O.value,O.endTime):O.type==="setValue"?v.setValueAtTime(O.value,O.startTime):O.type==="setValueCurve"&&v.setValueCurveAtTime(O.values,O.startTime,O.duration))}return N},cancelScheduledValues(R){return T===null&&E.flush(m.context.currentTime),E.add(s(R)),v.cancelScheduledValues(R),N},exponentialRampToValueAtTime(R,C){if(R===0)throw new RangeError;if(!Number.isFinite(C)||C<0)throw new RangeError;const O=m.context.currentTime;return T===null&&E.flush(O),Array.from(E).length===0&&(E.add(c(S,O)),v.setValueAtTime(S,O)),E.add(o(R,C)),v.exponentialRampToValueAtTime(R,C),N},linearRampToValueAtTime(R,C){const O=m.context.currentTime;return T===null&&E.flush(O),Array.from(E).length===0&&(E.add(c(S,O)),v.setValueAtTime(S,O)),E.add(a(R,C)),v.linearRampToValueAtTime(R,C),N},setTargetAtTime(R,C,O){return T===null&&E.flush(m.context.currentTime),E.add(l(R,C,O)),v.setTargetAtTime(R,C,O),N},setValueAtTime(R,C){return T===null&&E.flush(m.context.currentTime),E.add(c(R,C)),v.setValueAtTime(R,C),N},setValueCurveAtTime(R,C,O){const M=R instanceof Float32Array?R:new Float32Array(R);if(h!==null&&h.name==="webkitAudioContext"){const I=C+O,U=m.context.sampleRate,L=Math.ceil(C*U),P=Math.floor(I*U),b=P-L,H=new Float32Array(b);for(let B=0;B({replay(e){for(const n of t)if(n.type==="exponentialRampToValue"){const{endTime:r,value:i}=n;e.exponentialRampToValueAtTime(i,r)}else if(n.type==="linearRampToValue"){const{endTime:r,value:i}=n;e.linearRampToValueAtTime(i,r)}else if(n.type==="setTarget"){const{startTime:r,target:i,timeConstant:s}=n;e.setTargetAtTime(i,r,s)}else if(n.type==="setValue"){const{startTime:r,value:i}=n;e.setValueAtTime(i,r)}else if(n.type==="setValueCurve"){const{duration:r,startTime:i,values:s}=n;e.setValueCurveAtTime(s,i,r)}else throw new Error("Can't apply an unknown automation.")}});class $L{constructor(e){this._map=new Map(e)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(e,n=null){return this._map.forEach((r,i)=>e.call(n,r,i,this))}get(e){return this._map.get(e)}has(e){return this._map.has(e)}keys(){return this._map.keys()}values(){return this._map.values()}}const fY={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,parameterData:{},processorOptions:{}},dY=(t,e,n,r,i,s,o,a,l,c,u,h,p,m)=>class extends e{constructor(v,y,_){var S;const E=a(v),T=l(E),N=u({...fY,..._});p(N);const R=GE.get(E),C=R==null?void 0:R.get(y),O=T||E.state!=="closed"?E:(S=o(E))!==null&&S!==void 0?S:E,M=i(O,T?null:v.baseLatency,c,y,C,N),I=T?r(y,N,C):null;super(v,!0,M,I);const U=[];M.parameters.forEach((P,b)=>{const H=n(this,T,P);U.push([b,H])}),this._nativeAudioWorkletNode=M,this._onprocessorerror=null,this._parameters=new $L(U),T&&t(E,this);const{activeInputs:L}=s(this);h(M,L)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(v){const y=typeof v=="function"?m(this,v):null;this._nativeAudioWorkletNode.onprocessorerror=y;const _=this._nativeAudioWorkletNode.onprocessorerror;this._onprocessorerror=_!==null&&_===y?v:_}get parameters(){return this._parameters===null?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}};function V_(t,e,n,r,i){if(typeof t.copyFromChannel=="function")e[n].byteLength===0&&(e[n]=new Float32Array(128)),t.copyFromChannel(e[n],r,i);else{const s=t.getChannelData(r);if(e[n].byteLength===0)e[n]=s.slice(i,i+128);else{const o=new Float32Array(s.buffer,i*Float32Array.BYTES_PER_ELEMENT,128);e[n].set(o)}}}const qL=(t,e,n,r,i)=>{typeof t.copyToChannel=="function"?e[n].byteLength!==0&&t.copyToChannel(e[n],r,i):e[n].byteLength!==0&&t.getChannelData(r).set(e[n],i)},H_=(t,e)=>{const n=[];for(let r=0;r{const n=Lo(WE,t),r=Hn(e);return Lo(n,r)},mY=async(t,e,n,r,i,s,o)=>{const a=e===null?Math.ceil(t.context.length/128)*128:e.length,l=r.channelCount*r.numberOfInputs,c=i.reduce((y,_)=>y+_,0),u=c===0?null:n.createBuffer(c,a,n.sampleRate);if(s===void 0)throw new Error("Missing the processor constructor.");const h=Bi(t),p=await pY(n,t),m=H_(r.numberOfInputs,r.channelCount),g=H_(r.numberOfOutputs,i),v=Array.from(t.parameters.keys()).reduce((y,_)=>({...y,[_]:new Float32Array(128)}),{});for(let y=0;y0&&e!==null)for(let _=0;_{V_(e,v,_,l+S,y)});for(let _=0;_h.activeInputs[T].size===0?[]:E),S=o(y/n.sampleRate,n.sampleRate,()=>p.process(_,g,v));if(u!==null)for(let E=0,T=0;E(y,_,S)=>{const E=new WeakMap;let T=null;const N=async(R,C)=>{let O=u(R),M=null;const I=bi(O,C),U=Array.isArray(_.outputChannelCount)?_.outputChannelCount:Array.from(_.outputChannelCount);if(h===null){const L=U.reduce((V,B)=>V+B,0),P=i(C,{channelCount:Math.max(1,L),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,L)}),b=[];for(let V=0;V{const j=new p(W,Math.ceil(R.context.length/128)*128,C.sampleRate),Y=[],ge=[];for(let we=0;we<_.numberOfInputs;we+=1)Y.push(o(j,{channelCount:_.channelCount,channelCountMode:_.channelCountMode,channelInterpretation:_.channelInterpretation,gain:1})),ge.push(i(j,{channelCount:_.channelCount,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:_.channelCount}));const Q=await Promise.all(Array.from(R.parameters.values()).map(async we=>{const Ae=s(j,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:we.value});return await m(j,we,Ae.offset),Ae})),re=r(j,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,B+z)});for(let we=0;we<_.numberOfInputs;we+=1){Y[we].connect(ge[we]);for(let Ae=0;Ae<_.channelCount;Ae+=1)ge[we].connect(re,Ae,we*_.channelCount+Ae)}for(const[we,Ae]of Q.entries())Ae.connect(re,0,B+we),Ae.start(0);return re.connect(j.destination),await Promise.all(Y.map(we=>g(R,j,we))),v(j)})(),C,_,U,S,c)}const L=await T,P=n(C,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),[b,H,V]=M;L!==null&&(P.buffer=L,P.start(0)),P.connect(b);for(let B=0,z=0;Bclass extends g{constructor(N,R){super(N,R),this._nativeContext=N,this._audioWorklet=t===void 0?void 0:{addModule:(C,O)=>t(this,C,O)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new e(this)}createBiquadFilter(){return new i(this)}createBuffer(N,R,C){return new n({length:R,numberOfChannels:N,sampleRate:C})}createBufferSource(){return new r(this)}createChannelMerger(N=6){return new s(this,{numberOfInputs:N})}createChannelSplitter(N=6){return new o(this,{numberOfOutputs:N})}createConstantSource(){return new a(this)}createConvolver(){return new l(this)}createDelay(N=1){return new u(this,{maxDelayTime:N})}createDynamicsCompressor(){return new h(this)}createGain(){return new p(this)}createIIRFilter(N,R){return new m(this,{feedback:R,feedforward:N})}createOscillator(){return new v(this)}createPanner(){return new y(this)}createPeriodicWave(N,R,C={disableNormalization:!1}){return new _(this,{...C,imag:R,real:N})}createStereoPanner(){return new S(this)}createWaveShaper(){return new E(this)}decodeAudioData(N,R,C){return c(this._nativeContext,N).then(O=>(typeof R=="function"&&R(O),O),O=>{throw typeof C=="function"&&C(O),O})}},vY={Q:1,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:350,gain:0,type:"lowpass"},yY=(t,e,n,r,i,s,o,a)=>class extends t{constructor(c,u){const h=s(c),p={...vY,...u},m=i(h,p),g=o(h),v=g?n():null;super(c,!1,m,v),this._Q=e(this,g,m.Q,Di,ts),this._detune=e(this,g,m.detune,1200*Math.log2(Di),-1200*Math.log2(Di)),this._frequency=e(this,g,m.frequency,c.sampleRate/2,0),this._gain=e(this,g,m.gain,40*Math.log10(Di),ts),this._nativeBiquadFilterNode=m,a(this,1)}get detune(){return this._detune}get frequency(){return this._frequency}get gain(){return this._gain}get Q(){return this._Q}get type(){return this._nativeBiquadFilterNode.type}set type(c){this._nativeBiquadFilterNode.type=c}getFrequencyResponse(c,u,h){try{this._nativeBiquadFilterNode.getFrequencyResponse(c,u,h)}catch(p){throw p.code===11?r():p}if(c.length!==u.length||u.length!==h.length)throw r()}},xY=(t,e,n,r,i)=>()=>{const s=new WeakMap,o=async(a,l)=>{let c=n(a);const u=bi(c,l);if(!u){const h={Q:c.Q.value,channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,detune:c.detune.value,frequency:c.frequency.value,gain:c.gain.value,type:c.type};c=e(l,h)}return s.set(l,c),u?(await t(l,a.Q,c.Q),await t(l,a.detune,c.detune),await t(l,a.frequency,c.frequency),await t(l,a.gain,c.gain)):(await r(l,a.Q,c.Q),await r(l,a.detune,c.detune),await r(l,a.frequency,c.frequency),await r(l,a.gain,c.gain)),await i(a,l,c),c};return{render(a,l){const c=s.get(l);return c!==void 0?Promise.resolve(c):o(a,l)}}},SY=(t,e)=>(n,r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t.get(n);if(s!==void 0)return s;try{const o=r();return o instanceof Promise?(t.set(n,o),o.catch(()=>!1).then(a=>(t.delete(n),e.set(n,a),a))):(e.set(n,o),o)}catch{return e.set(n,!1),!1}},EY={channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6},wY=(t,e,n,r,i)=>class extends t{constructor(o,a){const l=r(o),c={...EY,...a},u=n(l,c),h=i(l)?e():null;super(o,!1,u,h)}},TY=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!bi(a,o)){const c={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,numberOfInputs:a.numberOfInputs};a=t(o,c)}return r.set(o,a),await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},bY={channelCount:6,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:6},AY=(t,e,n,r,i,s)=>class extends t{constructor(a,l){const c=r(a),u=s({...bY,...l}),h=n(c,u),p=i(c)?e():null;super(a,!1,h,p)}},MY=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!bi(a,o)){const c={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,numberOfOutputs:a.numberOfOutputs};a=t(o,c)}return r.set(o,a),await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},CY=t=>(e,n,r)=>t(n,e,r),RY=t=>(e,n,r=0,i=0)=>{const s=e[r];if(s===void 0)throw t();return z_(n)?s.connect(n,0,i):s.connect(n,0)},NY=t=>(e,n)=>{const r=t(e,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),i=e.createBuffer(1,2,44100);return r.buffer=i,r.loop=!0,r.connect(n),r.start(),()=>{r.stop(),r.disconnect(n)}},kY={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",offset:1},IY=(t,e,n,r,i,s,o)=>class extends t{constructor(l,c){const u=i(l),h={...kY,...c},p=r(u,h),m=s(u),g=m?n():null;super(l,!1,p,g),this._constantSourceNodeRenderer=g,this._nativeConstantSourceNode=p,this._offset=e(this,m,p.offset,Di,ts),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(l){const c=typeof l=="function"?o(this,l):null;this._nativeConstantSourceNode.onended=c;const u=this._nativeConstantSourceNode.onended;this._onended=u!==null&&u===c?l:u}start(l=0){if(this._nativeConstantSourceNode.start(l),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.start=l),this.context.state!=="closed"){zf(this);const c=()=>{this._nativeConstantSourceNode.removeEventListener("ended",c),yl(this)&&im(this)};this._nativeConstantSourceNode.addEventListener("ended",c)}}stop(l=0){this._nativeConstantSourceNode.stop(l),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.stop=l)}},OY=(t,e,n,r,i)=>()=>{const s=new WeakMap;let o=null,a=null;const l=async(c,u)=>{let h=n(c);const p=bi(h,u);if(!p){const m={channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,offset:h.offset.value};h=e(u,m),o!==null&&h.start(o),a!==null&&h.stop(a)}return s.set(u,h),p?await t(u,c.offset,h.offset):await r(u,c.offset,h.offset),await i(c,u,h),h};return{set start(c){o=c},set stop(c){a=c},render(c,u){const h=s.get(u);return h!==void 0?Promise.resolve(h):l(c,u)}}},LY=t=>e=>(t[0]=e,t[0]),PY={buffer:null,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",disableNormalization:!1},DY=(t,e,n,r,i,s)=>class extends t{constructor(a,l){const c=r(a),u={...PY,...l},h=n(c,u),m=i(c)?e():null;super(a,!1,h,m),this._isBufferNullified=!1,this._nativeConvolverNode=h,u.buffer!==null&&s(this,u.buffer.duration)}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(a){if(this._nativeConvolverNode.buffer=a,a===null&&this._nativeConvolverNode.buffer!==null){const l=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=l.createBuffer(1,1,l.sampleRate),this._isBufferNullified=!0,s(this,0)}else this._isBufferNullified=!1,s(this,this._nativeConvolverNode.buffer===null?0:this._nativeConvolverNode.buffer.duration)}get normalize(){return this._nativeConvolverNode.normalize}set normalize(a){this._nativeConvolverNode.normalize=a}},UY=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!bi(a,o)){const c={buffer:a.buffer,channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,disableNormalization:!a.normalize};a=t(o,c)}return r.set(o,a),ad(a)?await n(s,o,a.inputs[0]):await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},FY=(t,e)=>(n,r,i)=>{if(e===null)throw new Error("Missing the native OfflineAudioContext constructor.");try{return new e(n,r,i)}catch(s){throw s.name==="SyntaxError"?t():s}},BY=()=>new DOMException("","DataCloneError"),z2=t=>{const{port1:e,port2:n}=new MessageChannel;return new Promise(r=>{const i=()=>{n.onmessage=null,e.close(),n.close(),r()};n.onmessage=()=>i();try{e.postMessage(t,[t])}catch{}finally{i()}})},zY=(t,e,n,r,i,s,o,a,l,c,u)=>(h,p)=>{const m=o(h)?h:s(h);if(i.has(p)){const g=n();return Promise.reject(g)}try{i.add(p)}catch{}return e(l,()=>l(m))?m.decodeAudioData(p).then(g=>(z2(p).catch(()=>{}),e(a,()=>a(g))||u(g),t.add(g),g)):new Promise((g,v)=>{const y=async()=>{try{await z2(p)}catch{}},_=S=>{v(S),y()};try{m.decodeAudioData(p,S=>{typeof S.copyFromChannel!="function"&&(c(S),WT(S)),t.add(S),y().then(()=>g(S))},S=>{_(S===null?r():S)})}catch(S){_(S)}})},VY=(t,e,n,r,i,s,o,a)=>(l,c)=>{const u=e.get(l);if(u===void 0)throw new Error("Missing the expected cycle count.");const h=s(l.context),p=a(h);if(u===c){if(e.delete(l),!p&&o(l)){const m=r(l),{outputs:g}=n(l);for(const v of g)if(om(v)){const y=r(v[0]);t(m,y,v[1],v[2])}else{const y=i(v[0]);m.connect(y,v[1])}}}else e.set(l,u-c)},HY={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",delayTime:0,maxDelayTime:1},GY=(t,e,n,r,i,s,o)=>class extends t{constructor(l,c){const u=i(l),h={...HY,...c},p=r(u,h),m=s(u),g=m?n(h.maxDelayTime):null;super(l,!1,p,g),this._delayTime=e(this,m,p.delayTime),o(this,h.maxDelayTime)}get delayTime(){return this._delayTime}},WY=(t,e,n,r,i)=>s=>{const o=new WeakMap,a=async(l,c)=>{let u=n(l);const h=bi(u,c);if(!h){const p={channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,delayTime:u.delayTime.value,maxDelayTime:s};u=e(c,p)}return o.set(c,u),h?await t(c,l.delayTime,u.delayTime):await r(c,l.delayTime,u.delayTime),await i(l,c,u),u};return{render(l,c){const u=o.get(c);return u!==void 0?Promise.resolve(u):a(l,c)}}},jY=t=>(e,n,r,i)=>t(e[i],s=>s[0]===n&&s[1]===r),$Y=t=>(e,n)=>{t(e).delete(n)},qY=t=>"delayTime"in t,XY=(t,e,n)=>function r(i,s){const o=U_(s)?s:n(t,s);if(qY(o))return[];if(i[0]===o)return[i];if(i.includes(o))return[];const{outputs:a}=e(o);return Array.from(a).map(l=>r([...i,o],l[0])).reduce((l,c)=>l.concat(c),[])},_0=(t,e,n)=>{const r=e[n];if(r===void 0)throw t();return r},KY=t=>(e,n=void 0,r=void 0,i=0)=>n===void 0?e.forEach(s=>s.disconnect()):typeof n=="number"?_0(t,e,n).disconnect():z_(n)?r===void 0?e.forEach(s=>s.disconnect(n)):i===void 0?_0(t,e,r).disconnect(n,0):_0(t,e,r).disconnect(n,0,i):r===void 0?e.forEach(s=>s.disconnect(n)):_0(t,e,r).disconnect(n,0),YY={attack:.003,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",knee:30,ratio:12,release:.25,threshold:-24},ZY=(t,e,n,r,i,s,o,a)=>class extends t{constructor(c,u){const h=s(c),p={...YY,...u},m=r(h,p),g=o(h),v=g?n():null;super(c,!1,m,v),this._attack=e(this,g,m.attack),this._knee=e(this,g,m.knee),this._nativeDynamicsCompressorNode=m,this._ratio=e(this,g,m.ratio),this._release=e(this,g,m.release),this._threshold=e(this,g,m.threshold),a(this,.006)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(c){const u=this._nativeDynamicsCompressorNode.channelCount;if(this._nativeDynamicsCompressorNode.channelCount=c,c>2)throw this._nativeDynamicsCompressorNode.channelCount=u,i()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(c){const u=this._nativeDynamicsCompressorNode.channelCountMode;if(this._nativeDynamicsCompressorNode.channelCountMode=c,c==="max")throw this._nativeDynamicsCompressorNode.channelCountMode=u,i()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return typeof this._nativeDynamicsCompressorNode.reduction.value=="number"?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}},JY=(t,e,n,r,i)=>()=>{const s=new WeakMap,o=async(a,l)=>{let c=n(a);const u=bi(c,l);if(!u){const h={attack:c.attack.value,channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,knee:c.knee.value,ratio:c.ratio.value,release:c.release.value,threshold:c.threshold.value};c=e(l,h)}return s.set(l,c),u?(await t(l,a.attack,c.attack),await t(l,a.knee,c.knee),await t(l,a.ratio,c.ratio),await t(l,a.release,c.release),await t(l,a.threshold,c.threshold)):(await r(l,a.attack,c.attack),await r(l,a.knee,c.knee),await r(l,a.ratio,c.ratio),await r(l,a.release,c.release),await r(l,a.threshold,c.threshold)),await i(a,l,c),c};return{render(a,l){const c=s.get(l);return c!==void 0?Promise.resolve(c):o(a,l)}}},QY=()=>new DOMException("","EncodingError"),eZ=t=>e=>new Promise((n,r)=>{if(t===null){r(new SyntaxError);return}const i=t.document.head;if(i===null)r(new SyntaxError);else{const s=t.document.createElement("script"),o=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(o),l=t.onerror,c=()=>{t.onerror=l,URL.revokeObjectURL(a)};t.onerror=(u,h,p,m,g)=>{if(h===a||h===t.location.href&&p===1&&m===1)return c(),r(g),!1;if(l!==null)return l(u,h,p,m,g)},s.onerror=()=>{c(),r(new SyntaxError)},s.onload=()=>{c(),n()},s.src=a,s.type="module",i.appendChild(s)}}),tZ=t=>class{constructor(n){this._nativeEventTarget=n,this._listeners=new WeakMap}addEventListener(n,r,i){if(r!==null){let s=this._listeners.get(r);s===void 0&&(s=t(this,r),typeof r=="function"&&this._listeners.set(r,s)),this._nativeEventTarget.addEventListener(n,s,i)}}dispatchEvent(n){return this._nativeEventTarget.dispatchEvent(n)}removeEventListener(n,r,i){const s=r===null?void 0:this._listeners.get(r);this._nativeEventTarget.removeEventListener(n,s===void 0?null:s,i)}},nZ=t=>(e,n,r)=>{Object.defineProperties(t,{currentFrame:{configurable:!0,get(){return Math.round(e*n)}},currentTime:{configurable:!0,get(){return e}}});try{return r()}finally{t!==null&&(delete t.currentFrame,delete t.currentTime)}},rZ=t=>async e=>{try{const n=await fetch(e);if(n.ok)return[await n.text(),n.url]}catch{}throw t()},iZ={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",gain:1},sZ=(t,e,n,r,i,s)=>class extends t{constructor(a,l){const c=i(a),u={...iZ,...l},h=r(c,u),p=s(c),m=p?n():null;super(a,!1,h,m),this._gain=e(this,p,h.gain,Di,ts)}get gain(){return this._gain}},oZ=(t,e,n,r,i)=>()=>{const s=new WeakMap,o=async(a,l)=>{let c=n(a);const u=bi(c,l);if(!u){const h={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,gain:c.gain.value};c=e(l,h)}return s.set(l,c),u?await t(l,a.gain,c.gain):await r(l,a.gain,c.gain),await i(a,l,c),c};return{render(a,l){const c=s.get(l);return c!==void 0?Promise.resolve(c):o(a,l)}}},aZ=(t,e)=>n=>e(t,n),lZ=t=>e=>{const n=t(e);if(n.renderer===null)throw new Error("Missing the renderer of the given AudioNode in the audio graph.");return n.renderer},cZ=t=>e=>{var n;return(n=t.get(e))!==null&&n!==void 0?n:0},uZ=t=>e=>{const n=t(e);if(n.renderer===null)throw new Error("Missing the renderer of the given AudioParam in the audio graph.");return n.renderer},hZ=t=>e=>t.get(e),ii=()=>new DOMException("","InvalidStateError"),fZ=t=>e=>{const n=t.get(e);if(n===void 0)throw ii();return n},dZ=(t,e)=>n=>{let r=t.get(n);if(r!==void 0)return r;if(e===null)throw new Error("Missing the native OfflineAudioContext constructor.");return r=new e(1,1,44100),t.set(n,r),r},pZ=t=>e=>{const n=t.get(e);if(n===void 0)throw new Error("The context has no set of AudioWorkletNodes.");return n},Jv=()=>new DOMException("","InvalidAccessError"),mZ=t=>{t.getFrequencyResponse=(e=>(n,r,i)=>{if(n.length!==r.length||r.length!==i.length)throw Jv();return e.call(t,n,r,i)})(t.getFrequencyResponse)},gZ={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers"},_Z=(t,e,n,r,i,s)=>class extends t{constructor(a,l){const c=r(a),u=i(c),h={...gZ,...l},p=e(c,u?null:a.baseLatency,h),m=u?n(h.feedback,h.feedforward):null;super(a,!1,p,m),mZ(p),this._nativeIIRFilterNode=p,s(this,1)}getFrequencyResponse(a,l,c){return this._nativeIIRFilterNode.getFrequencyResponse(a,l,c)}},XL=(t,e,n,r,i,s,o,a,l,c,u)=>{const h=c.length;let p=a;for(let m=0;m{const i=n instanceof Float64Array?n:new Float64Array(n),s=r instanceof Float64Array?r:new Float64Array(r),o=i.length,a=s.length,l=Math.min(o,a);if(i[0]!==1){for(let g=0;g(s,o)=>{const a=new WeakMap;let l=null;const c=async(u,h)=>{let p=null,m=e(u);const g=bi(m,h);if(h.createIIRFilter===void 0?p=t(h,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}):g||(m=h.createIIRFilter(o,s)),a.set(h,p===null?m:p),p!==null){if(l===null){if(n===null)throw new Error("Missing the native OfflineAudioContext constructor.");const y=new n(u.context.destination.channelCount,u.context.length,h.sampleRate);l=(async()=>{await r(u,y,y.destination);const _=await i(y);return vZ(_,h,s,o)})()}const v=await l;return p.buffer=v,p.start(0),p}return await r(u,h,m),m};return{render(u,h){const p=a.get(h);return p!==void 0?Promise.resolve(p):c(u,h)}}},xZ=(t,e,n,r,i,s)=>o=>(a,l)=>{const c=t.get(a);if(c===void 0){if(!o&&s(a)){const u=r(a),{outputs:h}=n(a);for(const p of h)if(om(p)){const m=r(p[0]);e(u,m,p[1],p[2])}else{const m=i(p[0]);u.disconnect(m,p[1])}}t.set(a,l)}else t.set(a,c+l)},SZ=(t,e)=>n=>{const r=t.get(n);return e(r)||e(n)},EZ=(t,e)=>n=>t.has(n)||e(n),wZ=(t,e)=>n=>t.has(n)||e(n),TZ=(t,e)=>n=>{const r=t.get(n);return e(r)||e(n)},bZ=t=>e=>t!==null&&e instanceof t,AZ=t=>e=>t!==null&&typeof t.AudioNode=="function"&&e instanceof t.AudioNode,MZ=t=>e=>t!==null&&typeof t.AudioParam=="function"&&e instanceof t.AudioParam,CZ=(t,e)=>n=>t(n)||e(n),RZ=t=>e=>t!==null&&e instanceof t,NZ=t=>t!==null&&t.isSecureContext,kZ=(t,e,n,r)=>class extends t{constructor(s,o){const a=n(s),l=e(a,o);if(r(a))throw TypeError();super(s,!0,l,null),this._nativeMediaElementAudioSourceNode=l}get mediaElement(){return this._nativeMediaElementAudioSourceNode.mediaElement}},IZ={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers"},OZ=(t,e,n,r)=>class extends t{constructor(s,o){const a=n(s);if(r(a))throw new TypeError;const l={...IZ,...o},c=e(a,l);super(s,!1,c,null),this._nativeMediaStreamAudioDestinationNode=c}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}},LZ=(t,e,n,r)=>class extends t{constructor(s,o){const a=n(s),l=e(a,o);if(r(a))throw new TypeError;super(s,!0,l,null),this._nativeMediaStreamAudioSourceNode=l}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}},PZ=(t,e,n)=>class extends t{constructor(i,s){const o=n(i),a=e(o,s);super(i,!0,a,null)}},DZ=(t,e,n,r,i,s)=>class extends n{constructor(a,l){super(a),this._nativeContext=a,Yv.set(this,a),r(a)&&i.set(a,new Set),this._destination=new t(this,l),this._listener=e(this,a),this._onstatechange=null}get currentTime(){return this._nativeContext.currentTime}get destination(){return this._destination}get listener(){return this._listener}get onstatechange(){return this._onstatechange}set onstatechange(a){const l=typeof a=="function"?s(this,a):null;this._nativeContext.onstatechange=l;const c=this._nativeContext.onstatechange;this._onstatechange=c!==null&&c===l?a:c}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}},Cp=t=>{const e=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{const n=t.decodeAudioData(e.buffer,()=>{});return n===void 0?!1:(n.catch(()=>{}),!0)}catch{}return!1},UZ=(t,e)=>(n,r,i)=>{const s=new Set;return n.connect=(o=>(a,l=0,c=0)=>{const u=s.size===0;if(e(a))return o.call(n,a,l,c),t(s,[a,l,c],h=>h[0]===a&&h[1]===l&&h[2]===c,!0),u&&r(),a;o.call(n,a,l),t(s,[a,l],h=>h[0]===a&&h[1]===l,!0),u&&r()})(n.connect),n.disconnect=(o=>(a,l,c)=>{const u=s.size>0;if(a===void 0)o.apply(n),s.clear();else if(typeof a=="number"){o.call(n,a);for(const p of s)p[1]===a&&s.delete(p)}else{e(a)?o.call(n,a,l,c):o.call(n,a,l);for(const p of s)p[0]===a&&(l===void 0||p[1]===l)&&(c===void 0||p[2]===c)&&s.delete(p)}const h=s.size===0;u&&h&&i()})(n.disconnect),n},Xn=(t,e,n)=>{const r=e[n];r!==void 0&&r!==t[n]&&(t[n]=r)},Hr=(t,e)=>{Xn(t,e,"channelCount"),Xn(t,e,"channelCountMode"),Xn(t,e,"channelInterpretation")},V2=t=>typeof t.getFloatTimeDomainData=="function",FZ=t=>{t.getFloatTimeDomainData=e=>{const n=new Uint8Array(e.length);t.getByteTimeDomainData(n);const r=Math.max(n.length,t.fftSize);for(let i=0;i(n,r)=>{const i=n.createAnalyser();if(Hr(i,r),!(r.maxDecibels>r.minDecibels))throw e();return Xn(i,r,"fftSize"),Xn(i,r,"maxDecibels"),Xn(i,r,"minDecibels"),Xn(i,r,"smoothingTimeConstant"),t(V2,()=>V2(i))||FZ(i),i},zZ=t=>t===null?null:t.hasOwnProperty("AudioBuffer")?t.AudioBuffer:null,nr=(t,e,n)=>{const r=e[n];r!==void 0&&r!==t[n].value&&(t[n].value=r)},VZ=t=>{t.start=(e=>{let n=!1;return(r=0,i=0,s)=>{if(n)throw ii();e.call(t,r,i,s),n=!0}})(t.start)},qT=t=>{t.start=(e=>(n=0,r=0,i)=>{if(typeof i=="number"&&i<0||r<0||n<0)throw new RangeError("The parameters can't be negative.");e.call(t,n,r,i)})(t.start)},XT=t=>{t.stop=(e=>(n=0)=>{if(n<0)throw new RangeError("The parameter can't be negative.");e.call(t,n)})(t.stop)},HZ=(t,e,n,r,i,s,o,a,l,c,u)=>(h,p)=>{const m=h.createBufferSource();return Hr(m,p),nr(m,p,"playbackRate"),Xn(m,p,"buffer"),Xn(m,p,"loop"),Xn(m,p,"loopEnd"),Xn(m,p,"loopStart"),e(n,()=>n(h))||VZ(m),e(r,()=>r(h))||l(m),e(i,()=>i(h))||c(m,h),e(s,()=>s(h))||qT(m),e(o,()=>o(h))||u(m,h),e(a,()=>a(h))||XT(m),t(h,m),m},GZ=t=>t===null?null:t.hasOwnProperty("AudioContext")?t.AudioContext:t.hasOwnProperty("webkitAudioContext")?t.webkitAudioContext:null,WZ=(t,e)=>(n,r,i)=>{const s=n.destination;if(s.channelCount!==r)try{s.channelCount=r}catch{}i&&s.channelCountMode!=="explicit"&&(s.channelCountMode="explicit"),s.maxChannelCount===0&&Object.defineProperty(s,"maxChannelCount",{value:r});const o=t(n,{channelCount:r,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,gain:1});return e(o,"channelCount",a=>()=>a.call(o),a=>l=>{a.call(o,l);try{s.channelCount=l}catch(c){if(l>s.maxChannelCount)throw c}}),e(o,"channelCountMode",a=>()=>a.call(o),a=>l=>{a.call(o,l),s.channelCountMode=l}),e(o,"channelInterpretation",a=>()=>a.call(o),a=>l=>{a.call(o,l),s.channelInterpretation=l}),Object.defineProperty(o,"maxChannelCount",{get:()=>s.maxChannelCount}),o.connect(s),o},jZ=t=>t===null?null:t.hasOwnProperty("AudioWorkletNode")?t.AudioWorkletNode:null,$Z=t=>{const{port1:e}=new MessageChannel;try{e.postMessage(t)}finally{e.close()}},qZ=(t,e,n,r,i)=>(s,o,a,l,c,u)=>{if(a!==null)try{const h=new a(s,l,u),p=new Map;let m=null;if(Object.defineProperties(h,{channelCount:{get:()=>u.channelCount,set:()=>{throw t()}},channelCountMode:{get:()=>"explicit",set:()=>{throw t()}},onprocessorerror:{get:()=>m,set:g=>{typeof m=="function"&&h.removeEventListener("processorerror",m),m=typeof g=="function"?g:null,typeof m=="function"&&h.addEventListener("processorerror",m)}}}),h.addEventListener=(g=>(...v)=>{if(v[0]==="processorerror"){const y=typeof v[1]=="function"?v[1]:typeof v[1]=="object"&&v[1]!==null&&typeof v[1].handleEvent=="function"?v[1].handleEvent:null;if(y!==null){const _=p.get(v[1]);_!==void 0?v[1]=_:(v[1]=S=>{S.type==="error"?(Object.defineProperties(S,{type:{value:"processorerror"}}),y(S)):y(new ErrorEvent(v[0],{...S}))},p.set(y,v[1]))}}return g.call(h,"error",v[1],v[2]),g.call(h,...v)})(h.addEventListener),h.removeEventListener=(g=>(...v)=>{if(v[0]==="processorerror"){const y=p.get(v[1]);y!==void 0&&(p.delete(v[1]),v[1]=y)}return g.call(h,"error",v[1],v[2]),g.call(h,v[0],v[1],v[2])})(h.removeEventListener),u.numberOfOutputs!==0){const g=n(s,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return h.connect(g).connect(s.destination),i(h,()=>g.disconnect(),()=>g.connect(s.destination))}return h}catch(h){throw h.code===11?r():h}if(c===void 0)throw r();return $Z(u),e(s,o,c,u)},KL=(t,e)=>t===null?512:Math.max(512,Math.min(16384,Math.pow(2,Math.round(Math.log2(t*e))))),XZ=t=>new Promise((e,n)=>{const{port1:r,port2:i}=new MessageChannel;r.onmessage=({data:s})=>{r.close(),i.close(),e(s)},r.onmessageerror=({data:s})=>{r.close(),i.close(),n(s)},i.postMessage(t)}),KZ=async(t,e)=>{const n=await XZ(e);return new t(n)},YZ=(t,e,n,r)=>{let i=WE.get(t);i===void 0&&(i=new WeakMap,WE.set(t,i));const s=KZ(n,r);return i.set(e,s),s},ZZ=(t,e,n,r,i,s,o,a,l,c,u,h,p)=>(m,g,v,y)=>{if(y.numberOfInputs===0&&y.numberOfOutputs===0)throw l();const _=Array.isArray(y.outputChannelCount)?y.outputChannelCount:Array.from(y.outputChannelCount);if(_.some(ie=>ie<1))throw l();if(_.length!==y.numberOfOutputs)throw e();if(y.channelCountMode!=="explicit")throw l();const S=y.channelCount*y.numberOfInputs,E=_.reduce((ie,te)=>ie+te,0),T=v.parameterDescriptors===void 0?0:v.parameterDescriptors.length;if(S+T>6||E>6)throw l();const N=new MessageChannel,R=[],C=[];for(let ie=0;ieie===void 0?0:ie},maxValue:{get:()=>te===void 0?Di:te},minValue:{get:()=>X===void 0?ts:X}}),O.push(ne)}const M=r(m,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,S+T)}),I=KL(g,m.sampleRate),U=a(m,I,S+T,Math.max(1,E)),L=i(m,{channelCount:Math.max(1,E),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,E)}),P=[];for(let ie=0;ie{const X=O[te];return X.connect(M,0,S+te),X.start(0),[ie,X.offset]}));M.connect(U);let H=y.channelInterpretation,V=null;const B=y.numberOfOutputs===0?[U]:P,z={get bufferSize(){return I},get channelCount(){return y.channelCount},set channelCount(ie){throw n()},get channelCountMode(){return y.channelCountMode},set channelCountMode(ie){throw n()},get channelInterpretation(){return H},set channelInterpretation(ie){for(const te of R)te.channelInterpretation=ie;H=ie},get context(){return U.context},get inputs(){return R},get numberOfInputs(){return y.numberOfInputs},get numberOfOutputs(){return y.numberOfOutputs},get onprocessorerror(){return V},set onprocessorerror(ie){typeof V=="function"&&z.removeEventListener("processorerror",V),V=typeof ie=="function"?ie:null,typeof V=="function"&&z.addEventListener("processorerror",V)},get parameters(){return b},get port(){return N.port2},addEventListener(...ie){return U.addEventListener(ie[0],ie[1],ie[2])},connect:t.bind(null,B),disconnect:c.bind(null,B),dispatchEvent(...ie){return U.dispatchEvent(ie[0])},removeEventListener(...ie){return U.removeEventListener(ie[0],ie[1],ie[2])}},W=new Map;N.port1.addEventListener=(ie=>(...te)=>{if(te[0]==="message"){const X=typeof te[1]=="function"?te[1]:typeof te[1]=="object"&&te[1]!==null&&typeof te[1].handleEvent=="function"?te[1].handleEvent:null;if(X!==null){const $=W.get(te[1]);$!==void 0?te[1]=$:(te[1]=ne=>{u(m.currentTime,m.sampleRate,()=>X(ne))},W.set(X,te[1]))}}return ie.call(N.port1,te[0],te[1],te[2])})(N.port1.addEventListener),N.port1.removeEventListener=(ie=>(...te)=>{if(te[0]==="message"){const X=W.get(te[1]);X!==void 0&&(W.delete(te[1]),te[1]=X)}return ie.call(N.port1,te[0],te[1],te[2])})(N.port1.removeEventListener);let K=null;Object.defineProperty(N.port1,"onmessage",{get:()=>K,set:ie=>{typeof K=="function"&&N.port1.removeEventListener("message",K),K=typeof ie=="function"?ie:null,typeof K=="function"&&(N.port1.addEventListener("message",K),N.port1.start())}}),v.prototype.port=N.port1;let j=null;YZ(m,z,v,y).then(ie=>j=ie);const ge=H_(y.numberOfInputs,y.channelCount),Q=H_(y.numberOfOutputs,_),re=v.parameterDescriptors===void 0?[]:v.parameterDescriptors.reduce((ie,{name:te})=>({...ie,[te]:new Float32Array(128)}),{});let we=!0;const Ae=()=>{y.numberOfOutputs>0&&U.disconnect(L);for(let ie=0,te=0;ie{if(j!==null){const X=h(z);for(let $=0;${V_(ie,re,ne,S+ae,$)});for(let ne=0;ne{if(X[D].size>0)return Ee.set(D,I/128),G;const he=Ee.get(D);return he===void 0?[]:(G.every(le=>le.every(_e=>_e===0))&&(he===1?Ee.delete(D):Ee.set(D,he-1)),G)});we=u(m.currentTime+$/m.sampleRate,m.sampleRate,()=>j.process(ne,Q,re));for(let G=0,D=0;GU.connect(Ve).connect(m.destination),it=()=>{U.disconnect(Ve),Ve.disconnect()},De=()=>{if(we){it(),y.numberOfOutputs>0&&U.connect(L);for(let ie=0,te=0;ie{we&&(qe(),Ae()),Le=!1};return qe(),p(z,De,A)},YL=(t,e)=>{const n=t.createBiquadFilter();return Hr(n,e),nr(n,e,"Q"),nr(n,e,"detune"),nr(n,e,"frequency"),nr(n,e,"gain"),Xn(n,e,"type"),n},JZ=(t,e)=>(n,r)=>{const i=n.createChannelMerger(r.numberOfInputs);return t!==null&&t.name==="webkitAudioContext"&&e(n,i),Hr(i,r),i},QZ=t=>{const e=t.numberOfOutputs;Object.defineProperty(t,"channelCount",{get:()=>e,set:n=>{if(n!==e)throw ii()}}),Object.defineProperty(t,"channelCountMode",{get:()=>"explicit",set:n=>{if(n!=="explicit")throw ii()}}),Object.defineProperty(t,"channelInterpretation",{get:()=>"discrete",set:n=>{if(n!=="discrete")throw ii()}})},am=(t,e)=>{const n=t.createChannelSplitter(e.numberOfOutputs);return Hr(n,e),QZ(n),n},eJ=(t,e,n,r,i)=>(s,o)=>{if(s.createConstantSource===void 0)return n(s,o);const a=s.createConstantSource();return Hr(a,o),nr(a,o,"offset"),e(r,()=>r(s))||qT(a),e(i,()=>i(s))||XT(a),t(s,a),a},ld=(t,e)=>(t.connect=e.connect.bind(e),t.disconnect=e.disconnect.bind(e),t),tJ=(t,e,n,r)=>(i,{offset:s,...o})=>{const a=i.createBuffer(1,2,44100),l=e(i,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),c=n(i,{...o,gain:s}),u=a.getChannelData(0);u[0]=1,u[1]=1,l.buffer=a,l.loop=!0;const h={get bufferSize(){},get channelCount(){return c.channelCount},set channelCount(g){c.channelCount=g},get channelCountMode(){return c.channelCountMode},set channelCountMode(g){c.channelCountMode=g},get channelInterpretation(){return c.channelInterpretation},set channelInterpretation(g){c.channelInterpretation=g},get context(){return c.context},get inputs(){return[]},get numberOfInputs(){return l.numberOfInputs},get numberOfOutputs(){return c.numberOfOutputs},get offset(){return c.gain},get onended(){return l.onended},set onended(g){l.onended=g},addEventListener(...g){return l.addEventListener(g[0],g[1],g[2])},dispatchEvent(...g){return l.dispatchEvent(g[0])},removeEventListener(...g){return l.removeEventListener(g[0],g[1],g[2])},start(g=0){l.start.call(l,g)},stop(g=0){l.stop.call(l,g)}},p=()=>l.connect(c),m=()=>l.disconnect(c);return t(i,l),r(ld(h,c),p,m)},nJ=(t,e)=>(n,r)=>{const i=n.createConvolver();if(Hr(i,r),r.disableNormalization===i.normalize&&(i.normalize=!r.disableNormalization),Xn(i,r,"buffer"),r.channelCount>2||(e(i,"channelCount",s=>()=>s.call(i),s=>o=>{if(o>2)throw t();return s.call(i,o)}),r.channelCountMode==="max"))throw t();return e(i,"channelCountMode",s=>()=>s.call(i),s=>o=>{if(o==="max")throw t();return s.call(i,o)}),i},ZL=(t,e)=>{const n=t.createDelay(e.maxDelayTime);return Hr(n,e),nr(n,e,"delayTime"),n},rJ=t=>(e,n)=>{const r=e.createDynamicsCompressor();if(Hr(r,n),n.channelCount>2||n.channelCountMode==="max")throw t();return nr(r,n,"attack"),nr(r,n,"knee"),nr(r,n,"ratio"),nr(r,n,"release"),nr(r,n,"threshold"),r},ps=(t,e)=>{const n=t.createGain();return Hr(n,e),nr(n,e,"gain"),n},iJ=t=>(e,n,r)=>{if(e.createIIRFilter===void 0)return t(e,n,r);const i=e.createIIRFilter(r.feedforward,r.feedback);return Hr(i,r),i};function sJ(t,e){const n=e[0]*e[0]+e[1]*e[1];return[(t[0]*e[0]+t[1]*e[1])/n,(t[1]*e[0]-t[0]*e[1])/n]}function oJ(t,e){return[t[0]*e[0]-t[1]*e[1],t[0]*e[1]+t[1]*e[0]]}function H2(t,e){let n=[0,0];for(let r=t.length-1;r>=0;r-=1)n=oJ(n,e),n[0]+=t[r];return n}const aJ=(t,e,n,r)=>(i,s,{channelCount:o,channelCountMode:a,channelInterpretation:l,feedback:c,feedforward:u})=>{const h=KL(s,i.sampleRate),p=c instanceof Float64Array?c:new Float64Array(c),m=u instanceof Float64Array?u:new Float64Array(u),g=p.length,v=m.length,y=Math.min(g,v);if(g===0||g>20)throw r();if(p[0]===0)throw e();if(v===0||v>20)throw r();if(m[0]===0)throw e();if(p[0]!==1){for(let O=0;O{const M=O.inputBuffer,I=O.outputBuffer,U=M.numberOfChannels;for(let L=0;Lt.createMediaElementSource(e.mediaElement),cJ=(t,e)=>{const n=t.createMediaStreamDestination();return Hr(n,e),n.numberOfOutputs===1&&Object.defineProperty(n,"numberOfOutputs",{get:()=>0}),n},uJ=(t,{mediaStream:e})=>{const n=e.getAudioTracks();n.sort((s,o)=>s.ido.id?1:0);const r=n.slice(0,1),i=t.createMediaStreamSource(new MediaStream(r));return Object.defineProperty(i,"mediaStream",{value:e}),i},hJ=(t,e)=>(n,{mediaStreamTrack:r})=>{if(typeof n.createMediaStreamTrackSource=="function")return n.createMediaStreamTrackSource(r);const i=new MediaStream([r]),s=n.createMediaStreamSource(i);if(r.kind!=="audio")throw t();if(e(n))throw new TypeError;return s},fJ=t=>t===null?null:t.hasOwnProperty("OfflineAudioContext")?t.OfflineAudioContext:t.hasOwnProperty("webkitOfflineAudioContext")?t.webkitOfflineAudioContext:null,dJ=(t,e,n,r,i,s)=>(o,a)=>{const l=o.createOscillator();return Hr(l,a),nr(l,a,"detune"),nr(l,a,"frequency"),a.periodicWave!==void 0?l.setPeriodicWave(a.periodicWave):Xn(l,a,"type"),e(n,()=>n(o))||qT(l),e(r,()=>r(o))||s(l,o),e(i,()=>i(o))||XT(l),t(o,l),l},pJ=t=>(e,n)=>{const r=e.createPanner();return r.orientationX===void 0?t(e,n):(Hr(r,n),nr(r,n,"orientationX"),nr(r,n,"orientationY"),nr(r,n,"orientationZ"),nr(r,n,"positionX"),nr(r,n,"positionY"),nr(r,n,"positionZ"),Xn(r,n,"coneInnerAngle"),Xn(r,n,"coneOuterAngle"),Xn(r,n,"coneOuterGain"),Xn(r,n,"distanceModel"),Xn(r,n,"maxDistance"),Xn(r,n,"panningModel"),Xn(r,n,"refDistance"),Xn(r,n,"rolloffFactor"),r)},mJ=(t,e,n,r,i,s,o,a,l,c)=>(u,{coneInnerAngle:h,coneOuterAngle:p,coneOuterGain:m,distanceModel:g,maxDistance:v,orientationX:y,orientationY:_,orientationZ:S,panningModel:E,positionX:T,positionY:N,positionZ:R,refDistance:C,rolloffFactor:O,...M})=>{const I=u.createPanner();if(M.channelCount>2||M.channelCountMode==="max")throw o();Hr(I,M);const U={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},L=n(u,{...U,channelInterpretation:"speakers",numberOfInputs:6}),P=r(u,{...M,gain:1}),b=r(u,{...U,gain:1}),H=r(u,{...U,gain:0}),V=r(u,{...U,gain:0}),B=r(u,{...U,gain:0}),z=r(u,{...U,gain:0}),W=r(u,{...U,gain:0}),K=i(u,256,6,1),j=s(u,{...U,curve:new Float32Array([1,1]),oversample:"none"});let Y=[y,_,S],ge=[T,N,R];const Q=new Float32Array(1);K.onaudioprocess=({inputBuffer:Ee})=>{const Le=[l(Ee,Q,0),l(Ee,Q,1),l(Ee,Q,2)];Le.some((qe,it)=>qe!==Y[it])&&(I.setOrientation(...Le),Y=Le);const Ve=[l(Ee,Q,3),l(Ee,Q,4),l(Ee,Q,5)];Ve.some((qe,it)=>qe!==ge[it])&&(I.setPosition(...Ve),ge=Ve)},Object.defineProperty(H.gain,"defaultValue",{get:()=>0}),Object.defineProperty(V.gain,"defaultValue",{get:()=>0}),Object.defineProperty(B.gain,"defaultValue",{get:()=>0}),Object.defineProperty(z.gain,"defaultValue",{get:()=>0}),Object.defineProperty(W.gain,"defaultValue",{get:()=>0});const re={get bufferSize(){},get channelCount(){return I.channelCount},set channelCount(Ee){if(Ee>2)throw o();P.channelCount=Ee,I.channelCount=Ee},get channelCountMode(){return I.channelCountMode},set channelCountMode(Ee){if(Ee==="max")throw o();P.channelCountMode=Ee,I.channelCountMode=Ee},get channelInterpretation(){return I.channelInterpretation},set channelInterpretation(Ee){P.channelInterpretation=Ee,I.channelInterpretation=Ee},get coneInnerAngle(){return I.coneInnerAngle},set coneInnerAngle(Ee){I.coneInnerAngle=Ee},get coneOuterAngle(){return I.coneOuterAngle},set coneOuterAngle(Ee){I.coneOuterAngle=Ee},get coneOuterGain(){return I.coneOuterGain},set coneOuterGain(Ee){if(Ee<0||Ee>1)throw e();I.coneOuterGain=Ee},get context(){return I.context},get distanceModel(){return I.distanceModel},set distanceModel(Ee){I.distanceModel=Ee},get inputs(){return[P]},get maxDistance(){return I.maxDistance},set maxDistance(Ee){if(Ee<0)throw new RangeError;I.maxDistance=Ee},get numberOfInputs(){return I.numberOfInputs},get numberOfOutputs(){return I.numberOfOutputs},get orientationX(){return b.gain},get orientationY(){return H.gain},get orientationZ(){return V.gain},get panningModel(){return I.panningModel},set panningModel(Ee){I.panningModel=Ee},get positionX(){return B.gain},get positionY(){return z.gain},get positionZ(){return W.gain},get refDistance(){return I.refDistance},set refDistance(Ee){if(Ee<0)throw new RangeError;I.refDistance=Ee},get rolloffFactor(){return I.rolloffFactor},set rolloffFactor(Ee){if(Ee<0)throw new RangeError;I.rolloffFactor=Ee},addEventListener(...Ee){return P.addEventListener(Ee[0],Ee[1],Ee[2])},dispatchEvent(...Ee){return P.dispatchEvent(Ee[0])},removeEventListener(...Ee){return P.removeEventListener(Ee[0],Ee[1],Ee[2])}};h!==re.coneInnerAngle&&(re.coneInnerAngle=h),p!==re.coneOuterAngle&&(re.coneOuterAngle=p),m!==re.coneOuterGain&&(re.coneOuterGain=m),g!==re.distanceModel&&(re.distanceModel=g),v!==re.maxDistance&&(re.maxDistance=v),y!==re.orientationX.value&&(re.orientationX.value=y),_!==re.orientationY.value&&(re.orientationY.value=_),S!==re.orientationZ.value&&(re.orientationZ.value=S),E!==re.panningModel&&(re.panningModel=E),T!==re.positionX.value&&(re.positionX.value=T),N!==re.positionY.value&&(re.positionY.value=N),R!==re.positionZ.value&&(re.positionZ.value=R),C!==re.refDistance&&(re.refDistance=C),O!==re.rolloffFactor&&(re.rolloffFactor=O),(Y[0]!==1||Y[1]!==0||Y[2]!==0)&&I.setOrientation(...Y),(ge[0]!==0||ge[1]!==0||ge[2]!==0)&&I.setPosition(...ge);const we=()=>{P.connect(I),t(P,j,0,0),j.connect(b).connect(L,0,0),j.connect(H).connect(L,0,1),j.connect(V).connect(L,0,2),j.connect(B).connect(L,0,3),j.connect(z).connect(L,0,4),j.connect(W).connect(L,0,5),L.connect(K).connect(u.destination)},Ae=()=>{P.disconnect(I),a(P,j,0,0),j.disconnect(b),b.disconnect(L),j.disconnect(H),H.disconnect(L),j.disconnect(V),V.disconnect(L),j.disconnect(B),B.disconnect(L),j.disconnect(z),z.disconnect(L),j.disconnect(W),W.disconnect(L),L.disconnect(K),K.disconnect(u.destination)};return c(ld(re,I),we,Ae)},gJ=t=>(e,{disableNormalization:n,imag:r,real:i})=>{const s=r instanceof Float32Array?r:new Float32Array(r),o=i instanceof Float32Array?i:new Float32Array(i),a=e.createPeriodicWave(o,s,{disableNormalization:n});if(Array.from(r).length<2)throw t();return a},lm=(t,e,n,r)=>t.createScriptProcessor(e,n,r),_J=(t,e)=>(n,r)=>{const i=r.channelCountMode;if(i==="clamped-max")throw e();if(n.createStereoPanner===void 0)return t(n,r);const s=n.createStereoPanner();return Hr(s,r),nr(s,r,"pan"),Object.defineProperty(s,"channelCountMode",{get:()=>i,set:o=>{if(o!==i)throw e()}}),s},vJ=(t,e,n,r,i,s)=>{const a=new Float32Array([1,1]),l=Math.PI/2,c={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},u={...c,oversample:"none"},h=(g,v,y,_)=>{const S=new Float32Array(16385),E=new Float32Array(16385);for(let M=0;M<16385;M+=1){const I=M/16384*l;S[M]=Math.cos(I),E[M]=Math.sin(I)}const T=n(g,{...c,gain:0}),N=r(g,{...u,curve:S}),R=r(g,{...u,curve:a}),C=n(g,{...c,gain:0}),O=r(g,{...u,curve:E});return{connectGraph(){v.connect(T),v.connect(R.inputs===void 0?R:R.inputs[0]),v.connect(C),R.connect(y),y.connect(N.inputs===void 0?N:N.inputs[0]),y.connect(O.inputs===void 0?O:O.inputs[0]),N.connect(T.gain),O.connect(C.gain),T.connect(_,0,0),C.connect(_,0,1)},disconnectGraph(){v.disconnect(T),v.disconnect(R.inputs===void 0?R:R.inputs[0]),v.disconnect(C),R.disconnect(y),y.disconnect(N.inputs===void 0?N:N.inputs[0]),y.disconnect(O.inputs===void 0?O:O.inputs[0]),N.disconnect(T.gain),O.disconnect(C.gain),T.disconnect(_,0,0),C.disconnect(_,0,1)}}},p=(g,v,y,_)=>{const S=new Float32Array(16385),E=new Float32Array(16385),T=new Float32Array(16385),N=new Float32Array(16385),R=Math.floor(16385/2);for(let B=0;B<16385;B+=1)if(B>R){const z=(B-R)/(16384-R)*l;S[B]=Math.cos(z),E[B]=Math.sin(z),T[B]=0,N[B]=1}else{const z=B/(16384-R)*l;S[B]=1,E[B]=0,T[B]=Math.cos(z),N[B]=Math.sin(z)}const C=e(g,{channelCount:2,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:2}),O=n(g,{...c,gain:0}),M=r(g,{...u,curve:S}),I=n(g,{...c,gain:0}),U=r(g,{...u,curve:E}),L=r(g,{...u,curve:a}),P=n(g,{...c,gain:0}),b=r(g,{...u,curve:T}),H=n(g,{...c,gain:0}),V=r(g,{...u,curve:N});return{connectGraph(){v.connect(C),v.connect(L.inputs===void 0?L:L.inputs[0]),C.connect(O,0),C.connect(I,0),C.connect(P,1),C.connect(H,1),L.connect(y),y.connect(M.inputs===void 0?M:M.inputs[0]),y.connect(U.inputs===void 0?U:U.inputs[0]),y.connect(b.inputs===void 0?b:b.inputs[0]),y.connect(V.inputs===void 0?V:V.inputs[0]),M.connect(O.gain),U.connect(I.gain),b.connect(P.gain),V.connect(H.gain),O.connect(_,0,0),P.connect(_,0,0),I.connect(_,0,1),H.connect(_,0,1)},disconnectGraph(){v.disconnect(C),v.disconnect(L.inputs===void 0?L:L.inputs[0]),C.disconnect(O,0),C.disconnect(I,0),C.disconnect(P,1),C.disconnect(H,1),L.disconnect(y),y.disconnect(M.inputs===void 0?M:M.inputs[0]),y.disconnect(U.inputs===void 0?U:U.inputs[0]),y.disconnect(b.inputs===void 0?b:b.inputs[0]),y.disconnect(V.inputs===void 0?V:V.inputs[0]),M.disconnect(O.gain),U.disconnect(I.gain),b.disconnect(P.gain),V.disconnect(H.gain),O.disconnect(_,0,0),P.disconnect(_,0,0),I.disconnect(_,0,1),H.disconnect(_,0,1)}}},m=(g,v,y,_,S)=>{if(v===1)return h(g,y,_,S);if(v===2)return p(g,y,_,S);throw i()};return(g,{channelCount:v,channelCountMode:y,pan:_,...S})=>{if(y==="max")throw i();const E=t(g,{...S,channelCount:1,channelCountMode:y,numberOfInputs:2}),T=n(g,{...S,channelCount:v,channelCountMode:y,gain:1}),N=n(g,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:_});let{connectGraph:R,disconnectGraph:C}=m(g,v,T,N,E);Object.defineProperty(N.gain,"defaultValue",{get:()=>0}),Object.defineProperty(N.gain,"maxValue",{get:()=>1}),Object.defineProperty(N.gain,"minValue",{get:()=>-1});const O={get bufferSize(){},get channelCount(){return T.channelCount},set channelCount(L){T.channelCount!==L&&(M&&C(),{connectGraph:R,disconnectGraph:C}=m(g,L,T,N,E),M&&R()),T.channelCount=L},get channelCountMode(){return T.channelCountMode},set channelCountMode(L){if(L==="clamped-max"||L==="max")throw i();T.channelCountMode=L},get channelInterpretation(){return T.channelInterpretation},set channelInterpretation(L){T.channelInterpretation=L},get context(){return T.context},get inputs(){return[T]},get numberOfInputs(){return T.numberOfInputs},get numberOfOutputs(){return T.numberOfOutputs},get pan(){return N.gain},addEventListener(...L){return T.addEventListener(L[0],L[1],L[2])},dispatchEvent(...L){return T.dispatchEvent(L[0])},removeEventListener(...L){return T.removeEventListener(L[0],L[1],L[2])}};let M=!1;const I=()=>{R(),M=!0},U=()=>{C(),M=!1};return s(ld(O,E),I,U)}},yJ=(t,e,n,r,i,s,o)=>(a,l)=>{const c=a.createWaveShaper();if(s!==null&&s.name==="webkitAudioContext"&&a.createGain().gain.automationRate===void 0)return n(a,l);Hr(c,l);const u=l.curve===null||l.curve instanceof Float32Array?l.curve:new Float32Array(l.curve);if(u!==null&&u.length<2)throw e();Xn(c,{curve:u},"curve"),Xn(c,l,"oversample");let h=null,p=!1;return o(c,"curve",v=>()=>v.call(c),v=>y=>(v.call(c,y),p&&(r(y)&&h===null?h=t(a,c):!r(y)&&h!==null&&(h(),h=null)),y)),i(c,()=>{p=!0,r(c.curve)&&(h=t(a,c))},()=>{p=!1,h!==null&&(h(),h=null)})},xJ=(t,e,n,r,i)=>(s,{curve:o,oversample:a,...l})=>{const c=s.createWaveShaper(),u=s.createWaveShaper();Hr(c,l),Hr(u,l);const h=n(s,{...l,gain:1}),p=n(s,{...l,gain:-1}),m=n(s,{...l,gain:1}),g=n(s,{...l,gain:-1});let v=null,y=!1,_=null;const S={get bufferSize(){},get channelCount(){return c.channelCount},set channelCount(N){h.channelCount=N,p.channelCount=N,c.channelCount=N,m.channelCount=N,u.channelCount=N,g.channelCount=N},get channelCountMode(){return c.channelCountMode},set channelCountMode(N){h.channelCountMode=N,p.channelCountMode=N,c.channelCountMode=N,m.channelCountMode=N,u.channelCountMode=N,g.channelCountMode=N},get channelInterpretation(){return c.channelInterpretation},set channelInterpretation(N){h.channelInterpretation=N,p.channelInterpretation=N,c.channelInterpretation=N,m.channelInterpretation=N,u.channelInterpretation=N,g.channelInterpretation=N},get context(){return c.context},get curve(){return _},set curve(N){if(N!==null&&N.length<2)throw e();if(N===null)c.curve=N,u.curve=N;else{const R=N.length,C=new Float32Array(R+2-R%2),O=new Float32Array(R+2-R%2);C[0]=N[0],O[0]=-N[R-1];const M=Math.ceil((R+1)/2),I=(R+1)/2-1;for(let U=1;U{h.connect(c).connect(m),h.connect(p).connect(u).connect(g).connect(m),y=!0,r(_)&&(v=t(s,h))},T=()=>{h.disconnect(c),c.disconnect(m),h.disconnect(p),p.disconnect(u),u.disconnect(g),g.disconnect(m),y=!1,v!==null&&(v(),v=null)};return i(ld(S,m),E,T)},qi=()=>new DOMException("","NotSupportedError"),SJ={numberOfChannels:1},EJ=(t,e,n,r,i)=>class extends t{constructor(o,a,l){let c;if(typeof o=="number"&&a!==void 0&&l!==void 0)c={length:a,numberOfChannels:o,sampleRate:l};else if(typeof o=="object")c=o;else throw new Error("The given parameters are not valid.");const{length:u,numberOfChannels:h,sampleRate:p}={...SJ,...c},m=r(h,u,p);e(Cp,()=>Cp(m))||m.addEventListener("statechange",(()=>{let g=0;const v=y=>{this._state==="running"&&(g>0?(m.removeEventListener("statechange",v),y.stopImmediatePropagation(),this._waitForThePromiseToSettle(y)):g+=1)};return v})()),super(m,h),this._length=u,this._nativeOfflineAudioContext=m,this._state=null}get length(){return this._nativeOfflineAudioContext.length===void 0?this._length:this._nativeOfflineAudioContext.length}get state(){return this._state===null?this._nativeOfflineAudioContext.state:this._state}startRendering(){return this._state==="running"?Promise.reject(n()):(this._state="running",i(this.destination,this._nativeOfflineAudioContext).finally(()=>{this._state=null,HL(this)}))}_waitForThePromiseToSettle(o){this._state===null?this._nativeOfflineAudioContext.dispatchEvent(o):setTimeout(()=>this._waitForThePromiseToSettle(o))}},wJ={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:440,periodicWave:void 0,type:"sine"},TJ=(t,e,n,r,i,s,o)=>class extends t{constructor(l,c){const u=i(l),h={...wJ,...c},p=n(u,h),m=s(u),g=m?r():null,v=l.sampleRate/2;super(l,!1,p,g),this._detune=e(this,m,p.detune,153600,-153600),this._frequency=e(this,m,p.frequency,v,-v),this._nativeOscillatorNode=p,this._onended=null,this._oscillatorNodeRenderer=g,this._oscillatorNodeRenderer!==null&&h.periodicWave!==void 0&&(this._oscillatorNodeRenderer.periodicWave=h.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(l){const c=typeof l=="function"?o(this,l):null;this._nativeOscillatorNode.onended=c;const u=this._nativeOscillatorNode.onended;this._onended=u!==null&&u===c?l:u}get type(){return this._nativeOscillatorNode.type}set type(l){this._nativeOscillatorNode.type=l,this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(l){this._nativeOscillatorNode.setPeriodicWave(l),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=l)}start(l=0){if(this._nativeOscillatorNode.start(l),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.start=l),this.context.state!=="closed"){zf(this);const c=()=>{this._nativeOscillatorNode.removeEventListener("ended",c),yl(this)&&im(this)};this._nativeOscillatorNode.addEventListener("ended",c)}}stop(l=0){this._nativeOscillatorNode.stop(l),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.stop=l)}},bJ=(t,e,n,r,i)=>()=>{const s=new WeakMap;let o=null,a=null,l=null;const c=async(u,h)=>{let p=n(u);const m=bi(p,h);if(!m){const g={channelCount:p.channelCount,channelCountMode:p.channelCountMode,channelInterpretation:p.channelInterpretation,detune:p.detune.value,frequency:p.frequency.value,periodicWave:o===null?void 0:o,type:p.type};p=e(h,g),a!==null&&p.start(a),l!==null&&p.stop(l)}return s.set(h,p),m?(await t(h,u.detune,p.detune),await t(h,u.frequency,p.frequency)):(await r(h,u.detune,p.detune),await r(h,u.frequency,p.frequency)),await i(u,h,p),p};return{set periodicWave(u){o=u},set start(u){a=u},set stop(u){l=u},render(u,h){const p=s.get(h);return p!==void 0?Promise.resolve(p):c(u,h)}}},AJ={channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:1,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1},MJ=(t,e,n,r,i,s,o)=>class extends t{constructor(l,c){const u=i(l),h={...AJ,...c},p=n(u,h),m=s(u),g=m?r():null;super(l,!1,p,g),this._nativePannerNode=p,this._orientationX=e(this,m,p.orientationX,Di,ts),this._orientationY=e(this,m,p.orientationY,Di,ts),this._orientationZ=e(this,m,p.orientationZ,Di,ts),this._positionX=e(this,m,p.positionX,Di,ts),this._positionY=e(this,m,p.positionY,Di,ts),this._positionZ=e(this,m,p.positionZ,Di,ts),o(this,1)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(l){this._nativePannerNode.coneInnerAngle=l}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(l){this._nativePannerNode.coneOuterAngle=l}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(l){this._nativePannerNode.coneOuterGain=l}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(l){this._nativePannerNode.distanceModel=l}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(l){this._nativePannerNode.maxDistance=l}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(l){this._nativePannerNode.panningModel=l}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(l){this._nativePannerNode.refDistance=l}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(l){this._nativePannerNode.rolloffFactor=l}},CJ=(t,e,n,r,i,s,o,a,l,c)=>()=>{const u=new WeakMap;let h=null;const p=async(m,g)=>{let v=null,y=s(m);const _={channelCount:y.channelCount,channelCountMode:y.channelCountMode,channelInterpretation:y.channelInterpretation},S={..._,coneInnerAngle:y.coneInnerAngle,coneOuterAngle:y.coneOuterAngle,coneOuterGain:y.coneOuterGain,distanceModel:y.distanceModel,maxDistance:y.maxDistance,panningModel:y.panningModel,refDistance:y.refDistance,rolloffFactor:y.rolloffFactor},E=bi(y,g);if("bufferSize"in y)v=r(g,{..._,gain:1});else if(!E){const T={...S,orientationX:y.orientationX.value,orientationY:y.orientationY.value,orientationZ:y.orientationZ.value,positionX:y.positionX.value,positionY:y.positionY.value,positionZ:y.positionZ.value};y=i(g,T)}if(u.set(g,v===null?y:v),v!==null){if(h===null){if(o===null)throw new Error("Missing the native OfflineAudioContext constructor.");const U=new o(6,m.context.length,g.sampleRate),L=e(U,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6});L.connect(U.destination),h=(async()=>{const P=await Promise.all([m.orientationX,m.orientationY,m.orientationZ,m.positionX,m.positionY,m.positionZ].map(async(b,H)=>{const V=n(U,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:H===0?1:0});return await a(U,b,V.offset),V}));for(let b=0;b<6;b+=1)P[b].connect(L,0,b),P[b].start(0);return c(U)})()}const T=await h,N=r(g,{..._,gain:1});await l(m,g,N);const R=[];for(let U=0;Ub!==C[H])||P.some((b,H)=>b!==O[H])){C=L,O=P;const b=U/g.sampleRate;M.gain.setValueAtTime(0,b),M=r(g,{..._,gain:0}),I=i(g,{...S,orientationX:C[0],orientationY:C[1],orientationZ:C[2],positionX:O[0],positionY:O[1],positionZ:O[2]}),M.gain.setValueAtTime(1,b),N.connect(M).connect(I.inputs[0]),I.connect(v)}}return v}return E?(await t(g,m.orientationX,y.orientationX),await t(g,m.orientationY,y.orientationY),await t(g,m.orientationZ,y.orientationZ),await t(g,m.positionX,y.positionX),await t(g,m.positionY,y.positionY),await t(g,m.positionZ,y.positionZ)):(await a(g,m.orientationX,y.orientationX),await a(g,m.orientationY,y.orientationY),await a(g,m.orientationZ,y.orientationZ),await a(g,m.positionX,y.positionX),await a(g,m.positionY,y.positionY),await a(g,m.positionZ,y.positionZ)),ad(y)?await l(m,g,y.inputs[0]):await l(m,g,y),y};return{render(m,g){const v=u.get(g);return v!==void 0?Promise.resolve(v):p(m,g)}}},RJ={disableNormalization:!1},NJ=(t,e,n,r)=>class JL{constructor(s,o){const a=e(s),l=r({...RJ,...o}),c=t(a,l);return n.add(c),c}static[Symbol.hasInstance](s){return s!==null&&typeof s=="object"&&Object.getPrototypeOf(s)===JL.prototype||n.has(s)}},kJ=(t,e)=>(n,r,i)=>(t(r).replay(i),e(r,n,i)),IJ=(t,e,n)=>async(r,i,s)=>{const o=t(r);await Promise.all(o.activeInputs.map((a,l)=>Array.from(a).map(async([c,u])=>{const p=await e(c).render(c,i),m=r.context.destination;!n(c)&&(r!==m||!n(r))&&p.connect(s,u,l)})).reduce((a,l)=>[...a,...l],[]))},OJ=(t,e,n)=>async(r,i,s)=>{const o=e(r);await Promise.all(Array.from(o.activeInputs).map(async([a,l])=>{const u=await t(a).render(a,i);n(a)||u.connect(s,l)}))},LJ=(t,e,n,r)=>i=>t(Cp,()=>Cp(i))?Promise.resolve(t(r,r)).then(s=>{if(!s){const o=n(i,512,0,1);i.oncomplete=()=>{o.onaudioprocess=null,o.disconnect()},o.onaudioprocess=()=>i.currentTime,o.connect(i.destination)}return i.startRendering()}):new Promise(s=>{const o=e(i,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});i.oncomplete=a=>{o.disconnect(),s(a.renderedBuffer)},o.connect(i.destination),i.startRendering()}),PJ=t=>(e,n)=>{t.set(e,n)},DJ=t=>(e,n)=>t.set(e,n),UJ=(t,e,n,r,i,s,o,a)=>(l,c)=>n(l).render(l,c).then(()=>Promise.all(Array.from(r(c)).map(u=>n(u).render(u,c)))).then(()=>i(c)).then(u=>(typeof u.copyFromChannel!="function"?(o(u),WT(u)):e(s,()=>s(u))||a(u),t.add(u),u)),FJ={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",pan:0},BJ=(t,e,n,r,i,s)=>class extends t{constructor(a,l){const c=i(a),u={...FJ,...l},h=n(c,u),p=s(c),m=p?r():null;super(a,!1,h,m),this._pan=e(this,p,h.pan)}get pan(){return this._pan}},zJ=(t,e,n,r,i)=>()=>{const s=new WeakMap,o=async(a,l)=>{let c=n(a);const u=bi(c,l);if(!u){const h={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,pan:c.pan.value};c=e(l,h)}return s.set(l,c),u?await t(l,a.pan,c.pan):await r(l,a.pan,c.pan),ad(c)?await i(a,l,c.inputs[0]):await i(a,l,c),c};return{render(a,l){const c=s.get(l);return c!==void 0?Promise.resolve(c):o(a,l)}}},VJ=t=>()=>{if(t===null)return!1;try{new t({length:1,sampleRate:44100})}catch{return!1}return!0},HJ=(t,e)=>async()=>{if(t===null)return!0;if(e===null)return!1;const n=new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),r=new e(1,128,44100),i=URL.createObjectURL(n);let s=!1,o=!1;try{await r.audioWorklet.addModule(i);const a=new t(r,"a",{numberOfOutputs:0}),l=r.createOscillator();a.port.onmessage=()=>s=!0,a.onprocessorerror=()=>o=!0,l.connect(a),l.start(0),await r.startRendering(),await new Promise(c=>setTimeout(c))}catch{}finally{URL.revokeObjectURL(i)}return s&&!o},GJ=(t,e)=>()=>{if(e===null)return Promise.resolve(!1);const n=new e(1,1,44100),r=t(n,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return new Promise(i=>{n.oncomplete=()=>{r.disconnect(),i(n.currentTime!==0)},n.startRendering()})},WJ=()=>new DOMException("","UnknownError"),jJ={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",curve:null,oversample:"none"},$J=(t,e,n,r,i,s,o)=>class extends t{constructor(l,c){const u=i(l),h={...jJ,...c},p=n(u,h),g=s(u)?r():null;super(l,!0,p,g),this._isCurveNullified=!1,this._nativeWaveShaperNode=p,o(this,1)}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(l){if(l===null)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(l.length<2)throw e();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=l}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(l){this._nativeWaveShaperNode.oversample=l}},qJ=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!bi(a,o)){const c={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,curve:a.curve,oversample:a.oversample};a=t(o,c)}return r.set(o,a),ad(a)?await n(s,o,a.inputs[0]):await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},XJ=()=>typeof window>"u"?null:window,KJ=(t,e)=>n=>{n.copyFromChannel=(r,i,s=0)=>{const o=t(s),a=t(i);if(a>=n.numberOfChannels)throw e();const l=n.length,c=n.getChannelData(a),u=r.length;for(let h=o<0?-o:0;h+o{const o=t(s),a=t(i);if(a>=n.numberOfChannels)throw e();const l=n.length,c=n.getChannelData(a),u=r.length;for(let h=o<0?-o:0;h+oe=>{e.copyFromChannel=(n=>(r,i,s=0)=>{const o=t(s),a=t(i);if(o(r,i,s=0)=>{const o=t(s),a=t(i);if(o(e,n)=>{const r=n.createBuffer(1,1,44100);e.buffer===null&&(e.buffer=r),t(e,"buffer",i=>()=>{const s=i.call(e);return s===r?null:s},i=>s=>i.call(e,s===null?r:s))},JJ=(t,e)=>(n,r)=>{r.channelCount=1,r.channelCountMode="explicit",Object.defineProperty(r,"channelCount",{get:()=>1,set:()=>{throw t()}}),Object.defineProperty(r,"channelCountMode",{get:()=>"explicit",set:()=>{throw t()}});const i=n.createBufferSource();e(r,()=>{const a=r.numberOfInputs;for(let l=0;li.disconnect(r))},QL=(t,e,n)=>t.copyFromChannel===void 0?t.getChannelData(n)[0]:(t.copyFromChannel(e,n),e[0]),eP=t=>{if(t===null)return!1;const e=t.length;return e%2!==0?t[Math.floor(e/2)]!==0:t[e/2-1]+t[e/2]!==0},cm=(t,e,n,r)=>{let i=t;for(;!i.hasOwnProperty(e);)i=Object.getPrototypeOf(i);const{get:s,set:o}=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,{get:n(s),set:r(o)})},QJ=t=>({...t,outputChannelCount:t.outputChannelCount!==void 0?t.outputChannelCount:t.numberOfInputs===1&&t.numberOfOutputs===1?[t.channelCount]:Array.from({length:t.numberOfOutputs},()=>1)}),eQ=t=>({...t,channelCount:t.numberOfOutputs}),tQ=t=>{const{imag:e,real:n}=t;return e===void 0?n===void 0?{...t,imag:[0,0],real:[0,0]}:{...t,imag:Array.from(n,()=>0),real:n}:n===void 0?{...t,imag:e,real:Array.from(e,()=>0)}:{...t,imag:e,real:n}},tP=(t,e,n)=>{try{t.setValueAtTime(e,n)}catch(r){if(r.code!==9)throw r;tP(t,e,n+1e-7)}},nQ=t=>{const e=t.createBufferSource();e.start();try{e.start()}catch{return!0}return!1},rQ=t=>{const e=t.createBufferSource(),n=t.createBuffer(1,1,44100);e.buffer=n;try{e.start(0,1)}catch{return!1}return!0},iQ=t=>{const e=t.createBufferSource();e.start();try{e.stop()}catch{return!1}return!0},KT=t=>{const e=t.createOscillator();try{e.start(-1)}catch(n){return n instanceof RangeError}return!1},nP=t=>{const e=t.createBuffer(1,1,44100),n=t.createBufferSource();n.buffer=e,n.start(),n.stop();try{return n.stop(),!0}catch{return!1}},YT=t=>{const e=t.createOscillator();try{e.stop(-1)}catch(n){return n instanceof RangeError}return!1},sQ=t=>{const{port1:e,port2:n}=new MessageChannel;try{e.postMessage(t)}finally{e.close(),n.close()}},oQ=t=>{t.start=(e=>(n=0,r=0,i)=>{const s=t.buffer,o=s===null?r:Math.min(s.duration,r);s!==null&&o>s.duration-.5/t.context.sampleRate?e.call(t,n,0,0):e.call(t,n,o,i)})(t.start)},rP=(t,e)=>{const n=e.createGain();t.connect(n);const r=(i=>()=>{i.call(t,n),t.removeEventListener("ended",r)})(t.disconnect);t.addEventListener("ended",r),ld(t,n),t.stop=(i=>{let s=!1;return(o=0)=>{if(s)try{i.call(t,o)}catch{n.gain.setValueAtTime(0,o)}else i.call(t,o),s=!0}})(t.stop)},cd=(t,e)=>n=>{const r={value:t};return Object.defineProperties(n,{currentTarget:r,target:r}),typeof e=="function"?e.call(t,n):e.handleEvent.call(t,n)},aQ=MK(ah),lQ=OK(ah),cQ=jY(Zv),iP=new WeakMap,uQ=cZ(iP),Vo=SY(new Map,new WeakMap),Ta=XJ(),sP=BZ(Vo,Ua),ZT=lZ(Bi),fi=IJ(Bi,ZT,Gu),hQ=FK(sP,Hn,fi),Bn=fZ(Yv),Vl=fJ(Ta),Rn=RZ(Vl),oP=new WeakMap,aP=tZ(cd),um=GZ(Ta),JT=bZ(um),QT=AZ(Ta),lP=MZ(Ta),Rp=jZ(Ta),yr=cY(CK(PL),IK(aQ,lQ,F_,cQ,B_,Bi,uQ,rm,Hn,ah,yl,Gu,r_),Vo,xZ(HE,B_,Bi,Hn,Mp,yl),Ua,Jv,qi,VY(F_,HE,Bi,Hn,Mp,Bn,yl,Rn),XY(oP,Bi,Lo),aP,Bn,JT,QT,lP,Rn,Rp),fQ=UK(yr,hQ,Ua,sP,Bn,Rn),eb=new WeakSet,G2=zZ(Ta),cP=LY(new Uint32Array(1)),tb=KJ(cP,Ua),nb=YJ(cP),uP=zK(eb,Vo,qi,G2,Vl,VJ(G2),tb,nb),Qv=LK(ps),hP=OJ(ZT,sm,Gu),Fa=CY(hP),ud=HZ(Qv,Vo,nQ,rQ,iQ,KT,nP,YT,oQ,ZJ(cm),rP),Ba=kJ(uZ(sm),hP),dQ=GK(Fa,ud,Hn,Ba,fi),Ho=uY(RK(DL),oP,GT,hY,SK,EK,wK,TK,bK,BE,OL,um,tP),pQ=HK(yr,dQ,Ho,ii,ud,Bn,Rn,cd),mQ=JK(yr,QK,Ua,ii,WZ(ps,cm),Bn,Rn,fi),gQ=xY(Fa,YL,Hn,Ba,fi),lh=DJ(iP),_Q=yY(yr,Ho,gQ,Jv,YL,Bn,Rn,lh),Wc=UZ(ah,QT),vQ=JJ(ii,Wc),jc=JZ(um,vQ),yQ=TY(jc,Hn,fi),xQ=wY(yr,yQ,jc,Bn,Rn),SQ=MY(am,Hn,fi),EQ=AY(yr,SQ,am,Bn,Rn,eQ),wQ=tJ(Qv,ud,ps,Wc),hd=eJ(Qv,Vo,wQ,KT,YT),TQ=OY(Fa,hd,Hn,Ba,fi),bQ=IY(yr,Ho,TQ,hd,Bn,Rn,cd),fP=nJ(qi,cm),AQ=UY(fP,Hn,fi),MQ=DY(yr,AQ,fP,Bn,Rn,lh),CQ=WY(Fa,ZL,Hn,Ba,fi),RQ=GY(yr,Ho,CQ,ZL,Bn,Rn,lh),dP=rJ(qi),NQ=JY(Fa,dP,Hn,Ba,fi),kQ=ZY(yr,Ho,NQ,dP,qi,Bn,Rn,lh),IQ=oZ(Fa,ps,Hn,Ba,fi),OQ=sZ(yr,Ho,IQ,ps,Bn,Rn),LQ=aJ(Jv,ii,lm,qi),ey=LJ(Vo,ps,lm,GJ(ps,Vl)),PQ=yZ(ud,Hn,Vl,fi,ey),DQ=iJ(LQ),UQ=_Z(yr,DQ,PQ,Bn,Rn,lh),FQ=eY(Ho,jc,hd,lm,qi,QL,Rn,cm),pP=new WeakMap,BQ=DZ(mQ,FQ,aP,Rn,pP,cd),mP=dJ(Qv,Vo,KT,nP,YT,rP),zQ=bJ(Fa,mP,Hn,Ba,fi),VQ=TJ(yr,Ho,mP,zQ,Bn,Rn,cd),gP=NY(ud),HQ=xJ(gP,ii,ps,eP,Wc),ty=yJ(gP,ii,HQ,eP,Wc,um,cm),GQ=mJ(F_,ii,jc,ps,lm,ty,qi,B_,QL,Wc),_P=pJ(GQ),WQ=CJ(Fa,jc,hd,ps,_P,Hn,Vl,Ba,fi,ey),jQ=MJ(yr,Ho,_P,WQ,Bn,Rn,lh),$Q=gJ(Ua),qQ=NJ($Q,Bn,new WeakSet,tQ),XQ=vJ(jc,am,ps,ty,qi,Wc),vP=_J(XQ,qi),KQ=zJ(Fa,vP,Hn,Ba,fi),YQ=BJ(yr,Ho,vP,KQ,Bn,Rn),ZQ=qJ(ty,Hn,fi),JQ=$J(yr,ii,ty,ZQ,Bn,Rn,lh),yP=NZ(Ta),rb=nZ(Ta),xP=new WeakMap,QQ=dZ(xP,Vl),eee=yP?kK(Vo,qi,eZ(Ta),rb,rZ(AK),Bn,QQ,Rn,Rp,new WeakMap,new WeakMap,HJ(Rp,Vl),Ta):void 0,tee=CZ(JT,Rn),nee=zY(eb,Vo,BY,QY,new WeakSet,Bn,tee,D_,Cp,tb,nb),SP=_Y(eee,fQ,uP,pQ,_Q,xQ,EQ,bQ,MQ,nee,RQ,kQ,OQ,UQ,BQ,VQ,jQ,qQ,YQ,JQ),ree=kZ(yr,lJ,Bn,Rn),iee=OZ(yr,cJ,Bn,Rn),see=LZ(yr,uJ,Bn,Rn),oee=hJ(ii,Rn),aee=PZ(yr,oee,Bn),lee=ZK(SP,ii,qi,WJ,ree,iee,see,aee,um),ib=pZ(pP),cee=PK(ib),EP=RY(Ua),uee=$Y(ib),wP=KY(Ua),TP=new WeakMap,hee=aZ(TP,Lo),fee=ZZ(EP,Ua,ii,jc,am,hd,ps,lm,qi,wP,rb,hee,Wc),dee=qZ(ii,fee,ps,qi,Wc),pee=gY(Fa,EP,ud,jc,am,hd,ps,uee,wP,rb,Hn,Rp,Vl,Ba,fi,ey),mee=hZ(xP),gee=PJ(TP),W2=yP?dY(cee,yr,Ho,pee,dee,Bi,mee,Bn,Rn,Rp,QJ,gee,sQ,cd):void 0,_ee=FY(qi,Vl),vee=UJ(eb,Vo,ZT,ib,ey,D_,tb,nb),yee=EJ(SP,Vo,ii,_ee,vee),xee=SZ(Yv,JT),See=EZ(HT,QT),Eee=wZ(GT,lP),wee=TZ(Yv,Rn);function Os(t){return t===void 0}function Wt(t){return t!==void 0}function Tee(t){return typeof t=="function"}function Po(t){return typeof t=="number"}function wc(t){return Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object}function bP(t){return typeof t=="boolean"}function cs(t){return Array.isArray(t)}function Nl(t){return typeof t=="string"}function v0(t){return Nl(t)&&/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(t)}function Tt(t,e){if(!t)throw new Error(e)}function ba(t,e,n=1/0){if(!(e<=t&&t<=n))throw new RangeError(`Value must be within [${e}, ${n}], got: ${t}`)}function AP(t){!t.isOffline&&t.state!=="running"&&ny('The AudioContext is "suspended". Invoke Tone.start() from a user action to start the audio.')}let MP=!1,j2=!1;function $2(t){MP=t}function bee(t){Os(t)&&MP&&!j2&&(j2=!0,ny("Events scheduled inside of scheduled callbacks should use the passed in scheduling time. See https://github.com/Tonejs/Tone.js/wiki/Accurate-Timing"))}let CP=console;function Aee(...t){CP.log(...t)}function ny(...t){CP.warn(...t)}function Mee(t){return new lee(t)}function Cee(t,e,n){return new yee(t,e,n)}const Ms=typeof self=="object"?self:null,Ree=Ms&&(Ms.hasOwnProperty("AudioContext")||Ms.hasOwnProperty("webkitAudioContext"));function Nee(t,e,n){return Tt(Wt(W2),"AudioWorkletNode only works in a secure context (https or localhost)"),new(t instanceof(Ms==null?void 0:Ms.BaseAudioContext)?Ms==null?void 0:Ms.AudioWorkletNode:W2)(t,e,n)}function Go(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function _r(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}class kee{constructor(e,n,r,i){this._callback=e,this._type=n,this._minimumUpdateInterval=Math.max(128/(i||44100),.001),this.updateInterval=r,this._createClock()}_createWorker(){const e=new Blob([` + // the initial timeout time + let timeoutTime = ${(this._updateInterval*1e3).toFixed(1)}; + // onmessage callback + self.onmessage = function(msg){ + timeoutTime = parseInt(msg.data); + }; + // the tick function which posts a message + // and schedules a new tick + function tick(){ + setTimeout(tick, timeoutTime); + self.postMessage('tick'); + } + // call tick initially + tick(); + `],{type:"text/javascript"}),n=URL.createObjectURL(e),r=new Worker(n);r.onmessage=this._callback.bind(this),this._worker=r}_createTimeout(){this._timeout=setTimeout(()=>{this._createTimeout(),this._callback()},this._updateInterval*1e3)}_createClock(){if(this._type==="worker")try{this._createWorker()}catch{this._type="timeout",this._createClock()}else this._type==="timeout"&&this._createTimeout()}_disposeClock(){this._timeout&&clearTimeout(this._timeout),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(e){var n;this._updateInterval=Math.max(e,this._minimumUpdateInterval),this._type==="worker"&&((n=this._worker)===null||n===void 0||n.postMessage(this._updateInterval*1e3))}get type(){return this._type}set type(e){this._disposeClock(),this._type=e,this._createClock()}dispose(){this._disposeClock()}}function Wu(t){return Eee(t)}function Tc(t){return See(t)}function i_(t){return wee(t)}function nf(t){return xee(t)}function Iee(t){return t instanceof uP}function Oee(t,e){return t==="value"||Wu(e)||Tc(e)||Iee(e)}function Pu(t,...e){if(!e.length)return t;const n=e.shift();if(wc(t)&&wc(n))for(const r in n)Oee(r,n[r])?t[r]=n[r]:wc(n[r])?(t[r]||Object.assign(t,{[r]:{}}),Pu(t[r],n[r])):Object.assign(t,{[r]:n[r]});return Pu(t,...e)}function Lee(t,e){return t.length===e.length&&t.every((n,r)=>e[r]===n)}function lt(t,e,n=[],r){const i={},s=Array.from(e);if(wc(s[0])&&r&&!Reflect.has(s[0],r)&&(Object.keys(s[0]).some(a=>Reflect.has(t,a))||(Pu(i,{[r]:s[0]}),n.splice(n.indexOf(r),1),s.shift())),s.length===1&&wc(s[0]))Pu(i,s[0]);else for(let o=0;o{Reflect.has(t,n)&&delete t[n]}),t}/** + * Tone.js + * @author Yotam Mann + * @license http://opensource.org/licenses/MIT MIT License + * @copyright 2014-2024 Yotam Mann + */class Hl{constructor(){this.debug=!1,this._wasDisposed=!1}static getDefaults(){return{}}log(...e){(this.debug||Ms&&this.toString()===Ms.TONE_DEBUG_CLASS)&&Aee(this,...e)}dispose(){return this._wasDisposed=!0,this}get disposed(){return this._wasDisposed}toString(){return this.name}}Hl.version=IL;const sb=1e-6;function Vf(t,e){return t>e+sb}function qE(t,e){return Vf(t,e)||wo(t,e)}function G_(t,e){return t+sbthis.memory){const n=this.length-this.memory;this._timeline.splice(0,n)}return this}remove(e){const n=this._timeline.indexOf(e);return n!==-1&&this._timeline.splice(n,1),this}get(e,n="time"){const r=this._search(e,n);return r!==-1?this._timeline[r]:null}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(e,n="time"){const r=this._search(e,n);return r+10&&this._timeline[n-1].time=0?this._timeline[r-1]:null}cancel(e){if(this._timeline.length>1){let n=this._search(e);if(n>=0)if(wo(this._timeline[n].time,e)){for(let r=n;r>=0&&wo(this._timeline[r].time,e);r--)n=r;this._timeline=this._timeline.slice(0,n)}else this._timeline=this._timeline.slice(0,n+1);else this._timeline=[]}else this._timeline.length===1&&qE(this._timeline[0].time,e)&&(this._timeline=[]);return this}cancelBefore(e){const n=this._search(e);return n>=0&&(this._timeline=this._timeline.slice(n+1)),this}previousEvent(e){const n=this._timeline.indexOf(e);return n>0?this._timeline[n-1]:null}_search(e,n="time"){if(this._timeline.length===0)return-1;let r=0;const i=this._timeline.length;let s=i;if(i>0&&this._timeline[i-1][n]<=e)return i-1;for(;r=0&&this._timeline[r].time>=e;)r--;return this._iterate(n,r+1),this}forEachAtTime(e,n){const r=this._search(e);if(r!==-1&&wo(this._timeline[r].time,e)){let i=r;for(let s=r;s>=0&&wo(this._timeline[s].time,e);s--)i=s;this._iterate(s=>{n(s)},i,r)}return this}dispose(){return super.dispose(),this._timeline=[],this}}const RP=[];function ry(t){RP.push(t)}function Uee(t){RP.forEach(e=>e(t))}const NP=[];function iy(t){NP.push(t)}function Fee(t){NP.forEach(e=>e(t))}class hm extends Hl{constructor(){super(...arguments),this.name="Emitter"}on(e,n){return e.split(/\W+/).forEach(i=>{Os(this._events)&&(this._events={}),this._events.hasOwnProperty(i)||(this._events[i]=[]),this._events[i].push(n)}),this}once(e,n){const r=(...i)=>{n(...i),this.off(e,r)};return this.on(e,r),this}off(e,n){return e.split(/\W+/).forEach(i=>{if(Os(this._events)&&(this._events={}),this._events.hasOwnProperty(i))if(Os(n))this._events[i]=[];else{const s=this._events[i];for(let o=s.length-1;o>=0;o--)s[o]===n&&s.splice(o,1)}}),this}emit(e,...n){if(this._events&&this._events.hasOwnProperty(e)){const r=this._events[e].slice(0);for(let i=0,s=r.length;i{const r=Object.getOwnPropertyDescriptor(hm.prototype,n);Object.defineProperty(e.prototype,n,r)})}dispose(){return super.dispose(),this._events=void 0,this}}class kP extends hm{constructor(){super(...arguments),this.isOffline=!1}toJSON(){return{}}}class fm extends kP{constructor(){var e,n;super(),this.name="Context",this._constants=new Map,this._timeouts=new ro,this._timeoutIds=0,this._initialized=!1,this._closeStarted=!1,this.isOffline=!1,this._workletPromise=null;const r=lt(fm.getDefaults(),arguments,["context"]);r.context?(this._context=r.context,this._latencyHint=((e=arguments[0])===null||e===void 0?void 0:e.latencyHint)||""):(this._context=Mee({latencyHint:r.latencyHint}),this._latencyHint=r.latencyHint),this._ticker=new kee(this.emit.bind(this,"tick"),r.clockSource,r.updateInterval,this._context.sampleRate),this.on("tick",this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit("statechange",this.state)},this[!((n=arguments[0])===null||n===void 0)&&n.hasOwnProperty("updateInterval")?"_lookAhead":"lookAhead"]=r.lookAhead}static getDefaults(){return{clockSource:"worker",latencyHint:"interactive",lookAhead:.1,updateInterval:.05}}initialize(){return this._initialized||(Uee(this),this._initialized=!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(e,n,r){return this._context.createBuffer(e,n,r)}createChannelMerger(e){return this._context.createChannelMerger(e)}createChannelSplitter(e){return this._context.createChannelSplitter(e)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(e){return this._context.createDelay(e)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(e,n){return this._context.createIIRFilter(e,n)}createPanner(){return this._context.createPanner()}createPeriodicWave(e,n,r){return this._context.createPeriodicWave(e,n,r)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(e){return Tt(nf(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamSource(e)}createMediaElementSource(e){return Tt(nf(this._context),"Not available if OfflineAudioContext"),this._context.createMediaElementSource(e)}createMediaStreamDestination(){return Tt(nf(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamDestination()}decodeAudioData(e){return this._context.decodeAudioData(e)}get currentTime(){return this._context.currentTime}get state(){return this._context.state}get sampleRate(){return this._context.sampleRate}get listener(){return this.initialize(),this._listener}set listener(e){Tt(!this._initialized,"The listener cannot be set after initialization."),this._listener=e}get transport(){return this.initialize(),this._transport}set transport(e){Tt(!this._initialized,"The transport cannot be set after initialization."),this._transport=e}get draw(){return this.initialize(),this._draw}set draw(e){Tt(!this._initialized,"Draw cannot be set after initialization."),this._draw=e}get destination(){return this.initialize(),this._destination}set destination(e){Tt(!this._initialized,"The destination cannot be set after initialization."),this._destination=e}createAudioWorkletNode(e,n){return Nee(this.rawContext,e,n)}addAudioWorkletModule(e){return _r(this,void 0,void 0,function*(){Tt(Wt(this.rawContext.audioWorklet),"AudioWorkletNode is only available in a secure context (https or localhost)"),this._workletPromise||(this._workletPromise=this.rawContext.audioWorklet.addModule(e)),yield this._workletPromise})}workletsAreReady(){return _r(this,void 0,void 0,function*(){(yield this._workletPromise)?this._workletPromise:Promise.resolve()})}get updateInterval(){return this._ticker.updateInterval}set updateInterval(e){this._ticker.updateInterval=e}get clockSource(){return this._ticker.type}set clockSource(e){this._ticker.type=e}get lookAhead(){return this._lookAhead}set lookAhead(e){this._lookAhead=e,this.updateInterval=e?e/2:.01}get latencyHint(){return this._latencyHint}get rawContext(){return this._context}now(){return this._context.currentTime+this._lookAhead}immediate(){return this._context.currentTime}resume(){return nf(this._context)?this._context.resume():Promise.resolve()}close(){return _r(this,void 0,void 0,function*(){nf(this._context)&&this.state!=="closed"&&!this._closeStarted&&(this._closeStarted=!0,yield this._context.close()),this._initialized&&Fee(this)})}getConstant(e){if(this._constants.has(e))return this._constants.get(e);{const n=this._context.createBuffer(1,128,this._context.sampleRate),r=n.getChannelData(0);for(let s=0;sthis._constants[e].disconnect()),this.close(),this}_timeoutLoop(){const e=this.now();let n=this._timeouts.peek();for(;this._timeouts.length&&n&&n.time<=e;)n.callback(),this._timeouts.shift(),n=this._timeouts.peek()}setTimeout(e,n){this._timeoutIds++;const r=this.now();return this._timeouts.add({callback:e,id:this._timeoutIds,time:r+n}),this._timeoutIds}clearTimeout(e){return this._timeouts.forEach(n=>{n.id===e&&this._timeouts.remove(n)}),this}clearInterval(e){return this.clearTimeout(e)}setInterval(e,n){const r=++this._timeoutIds,i=()=>{const s=this.now();this._timeouts.add({callback:()=>{e(),i()},id:r,time:s+n})};return i(),r}}class Bee extends kP{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(e,n,r){return{}}createChannelMerger(e){return{}}createChannelSplitter(e){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(e){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(e,n){return{}}createPanner(){return{}}createPeriodicWave(e,n,r){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(e){return{}}createMediaElementSource(e){return{}}createMediaStreamDestination(){return{}}decodeAudioData(e){return Promise.resolve({})}createAudioWorkletNode(e,n){return{}}get rawContext(){return{}}addAudioWorkletModule(e){return _r(this,void 0,void 0,function*(){return Promise.resolve()})}resume(){return Promise.resolve()}setTimeout(e,n){return 0}clearTimeout(e){return this}setInterval(e,n){return 0}clearInterval(e){return this}getConstant(e){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(e){}get destination(){return{}}set destination(e){}now(){return 0}immediate(){return 0}}function Zt(t,e){cs(e)?e.forEach(n=>Zt(t,n)):Object.defineProperty(t,e,{enumerable:!0,writable:!1})}function dm(t,e){cs(e)?e.forEach(n=>dm(t,n)):Object.defineProperty(t,e,{writable:!0})}const En=()=>{};class An extends Hl{constructor(){super(),this.name="ToneAudioBuffer",this.onload=En;const e=lt(An.getDefaults(),arguments,["url","onload","onerror"]);this.reverse=e.reverse,this.onload=e.onload,Nl(e.url)?this.load(e.url).catch(e.onerror):e.url&&this.set(e.url)}static getDefaults(){return{onerror:En,onload:En,reverse:!1}}get sampleRate(){return this._buffer?this._buffer.sampleRate:zi().sampleRate}set(e){return e instanceof An?e.loaded?this._buffer=e.get():e.onload=()=>{this.set(e),this.onload(this)}:this._buffer=e,this._reversed&&this._reverse(),this}get(){return this._buffer}load(e){return _r(this,void 0,void 0,function*(){const n=An.load(e).then(r=>{this.set(r),this.onload(this)});An.downloads.push(n);try{yield n}finally{const r=An.downloads.indexOf(n);An.downloads.splice(r,1)}return this})}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(e){const n=cs(e)&&e[0].length>0,r=n?e.length:1,i=n?e[0].length:e.length,s=zi(),o=s.createBuffer(r,i,s.sampleRate),a=!n&&r===1?[e]:e;for(let l=0;li/r),this.fromArray(n)}return this}toArray(e){if(Po(e))return this.getChannelData(e);if(this.numberOfChannels===1)return this.toArray(0);{const n=[];for(let r=0;r0}get duration(){return this._buffer?this._buffer.duration:0}get length(){return this._buffer?this._buffer.length:0}get numberOfChannels(){return this._buffer?this._buffer.numberOfChannels:0}get reverse(){return this._reversed}set reverse(e){this._reversed!==e&&(this._reversed=e,this._reverse())}static fromArray(e){return new An().fromArray(e)}static fromUrl(e){return _r(this,void 0,void 0,function*(){return yield new An().load(e)})}static load(e){return _r(this,void 0,void 0,function*(){const n=e.match(/\[([^\]\[]+\|.+)\]$/);if(n){const l=n[1].split("|");let c=l[0];for(const u of l)if(An.supportsType(u)){c=u;break}e=e.replace(n[0],c)}const r=An.baseUrl===""||An.baseUrl.endsWith("/")?An.baseUrl:An.baseUrl+"/",i=document.createElement("a");i.href=r+e,i.pathname=(i.pathname+i.hash).split("/").map(encodeURIComponent).join("/");const s=yield fetch(i.href);if(!s.ok)throw new Error(`could not load url: ${e}`);const o=yield s.arrayBuffer();return yield zi().decodeAudioData(o)})}static supportsType(e){const n=e.split("."),r=n[n.length-1];return document.createElement("audio").canPlayType("audio/"+r)!==""}static loaded(){return _r(this,void 0,void 0,function*(){for(yield Promise.resolve();An.downloads.length;)yield An.downloads[0]})}}An.baseUrl="";An.downloads=[];class sy extends fm{constructor(){super({clockSource:"offline",context:i_(arguments[0])?arguments[0]:Cee(arguments[0],arguments[1]*arguments[2],arguments[2]),lookAhead:0,updateInterval:i_(arguments[0])?128/arguments[0].sampleRate:128/arguments[2]}),this.name="OfflineContext",this._currentTime=0,this.isOffline=!0,this._duration=i_(arguments[0])?arguments[0].length/arguments[0].sampleRate:arguments[1]}now(){return this._currentTime}get currentTime(){return this._currentTime}_renderClock(e){return _r(this,void 0,void 0,function*(){let n=0;for(;this._duration-this._currentTime>=0;){this.emit("tick"),this._currentTime+=128/this.sampleRate,n++;const r=Math.floor(this.sampleRate/128);e&&n%r===0&&(yield new Promise(i=>setTimeout(i,1)))}})}render(){return _r(this,arguments,void 0,function*(e=!0){yield this.workletsAreReady(),yield this._renderClock(e);const n=yield this._context.startRendering();return new An(n)})}close(){return Promise.resolve()}}const IP=new Bee;let Nu=IP;function zi(){return Nu===IP&&Ree&&zee(new fm),Nu}function zee(t,e=!1){e&&Nu.dispose(),nf(t)?Nu=new fm(t):i_(t)?Nu=new sy(t):Nu=t}function Vee(){return Nu.resume()}if(Ms&&!Ms.TONE_SILENCE_LOGGING){const e=` * Tone.js v${IL} * `;console.log(`%c${e}`,"background: #000; color: #fff")}function Hee(t){return Math.pow(10,t/20)}function Gee(t){return 20*(Math.log(t)/Math.LN10)}function OP(t){return Math.pow(2,t/12)}let oy=440;function Wee(){return oy}function jee(t){oy=t}function ku(t){return Math.round(LP(t))}function LP(t){return 69+12*Math.log2(t/oy)}function PP(t){return oy*Math.pow(2,(t-69)/12)}class ob extends Hl{constructor(e,n,r){super(),this.defaultUnits="s",this._val=n,this._units=r,this.context=e,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:e=>this._frequencyToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:e=>this._ticksToUnits(parseInt(e,10)),regexp:/^(\d+)i$/i},m:{method:e=>this._beatsToUnits(parseInt(e,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(e,n)=>{const r=parseInt(e,10),i=n==="."?1.5:1;return r===1?this._beatsToUnits(this._getTimeSignature())*i:this._beatsToUnits(4/r)*i},regexp:/^(\d+)n(\.?)$/i},number:{method:e=>this._expressions[this.defaultUnits].method.call(this,e),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:e=>this._secondsToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:e=>parseInt(e,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:e=>{const n=parseInt(e,10);return this._beatsToUnits(8/(Math.floor(n)*3))},regexp:/^(\d+)t$/i},tr:{method:(e,n,r)=>{let i=0;return e&&e!=="0"&&(i+=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),n&&n!=="0"&&(i+=this._beatsToUnits(parseFloat(n))),r&&r!=="0"&&(i+=this._beatsToUnits(parseFloat(r)/4)),i},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof ob&&this.fromType(this._val),Os(this._val))return this._noArg();if(Nl(this._val)&&Os(this._units)){for(const e in this._expressions)if(this._expressions[e].regexp.test(this._val.trim())){this._units=e;break}}else if(wc(this._val)){let e=0;for(const n in this._val)if(Wt(this._val[n])){const r=this._val[n],i=new this.constructor(this.context,n).valueOf()*r;e+=i}return e}if(Wt(this._units)){const e=this._expressions[this._units],n=this._val.toString().trim().match(e.regexp);return n?e.method.apply(this,n.slice(1)):e.method.call(this,this._val)}else return Nl(this._val)?parseFloat(this._val):this._val}_frequencyToUnits(e){return 1/e}_beatsToUnits(e){return 60/this._getBpm()*e}_secondsToUnits(e){return e}_ticksToUnits(e){return e*this._beatsToUnits(1)/this._getPPQ()}_noArg(){return this._now()}_getBpm(){return this.context.transport.bpm.value}_getTimeSignature(){return this.context.transport.timeSignature}_getPPQ(){return this.context.transport.PPQ}fromType(e){switch(this._units=void 0,this.defaultUnits){case"s":this._val=e.toSeconds();break;case"i":this._val=e.toTicks();break;case"hz":this._val=e.toFrequency();break;case"midi":this._val=e.toMidi();break}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return this.toSeconds()*1e3}}class eo extends ob{constructor(){super(...arguments),this.name="TimeClass"}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:e=>this._now()+new this.constructor(this.context,e).valueOf(),regexp:/^\+(.+)/},quantize:{method:e=>{const n=new eo(this.context,e).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(n))},regexp:/^@(.+)/}})}quantize(e,n=1){const r=new this.constructor(this.context,e).valueOf(),i=this.valueOf(),a=Math.round(i/r)*r-i;return i+a*n}toNotation(){const e=this.toSeconds(),n=["1m"];for(let s=1;s<9;s++){const o=Math.pow(2,s);n.push(o+"n."),n.push(o+"n"),n.push(o+"t")}n.push("0");let r=n[0],i=new eo(this.context,n[0]).toSeconds();return n.forEach(s=>{const o=new eo(this.context,s).toSeconds();Math.abs(o-e)3&&(i=parseFloat(parseFloat(s).toFixed(3))),[r,n,i].join(":")}toTicks(){const e=this._beatsToUnits(1);return this.valueOf()/e*this._getPPQ()}toSeconds(){return this.valueOf()}toMidi(){return ku(this.toFrequency())}_now(){return this.context.now()}}function kr(t,e){return new eo(zi(),t,e)}class is extends eo{constructor(){super(...arguments),this.name="Frequency",this.defaultUnits="hz"}static get A4(){return Wee()}static set A4(e){jee(e)}_getExpressions(){return Object.assign({},super._getExpressions(),{midi:{regexp:/^(\d+(?:\.\d+)?midi)/,method(e){return this.defaultUnits==="midi"?e:is.mtof(e)}},note:{regexp:/^([a-g]{1}(?:b|#|##|x|bb|###|#x|x#|bbb)?)(-?[0-9]+)/i,method(e,n){const i=$ee[e.toLowerCase()]+(parseInt(n,10)+1)*12;return this.defaultUnits==="midi"?i:is.mtof(i)}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method(e,n,r){let i=1;return e&&e!=="0"&&(i*=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),n&&n!=="0"&&(i*=this._beatsToUnits(parseFloat(n))),r&&r!=="0"&&(i*=this._beatsToUnits(parseFloat(r)/4)),i}}})}transpose(e){return new is(this.context,this.valueOf()*OP(e))}harmonize(e){return e.map(n=>this.transpose(n))}toMidi(){return ku(this.valueOf())}toNote(){const e=this.toFrequency(),n=Math.log2(e/is.A4);let r=Math.round(12*n)+57;const i=Math.floor(r/12);return i<0&&(r+=-12*i),qee[r%12]+i.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){const e=this._beatsToUnits(1),n=this.valueOf()/e;return Math.floor(n*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(e){return e}_ticksToUnits(e){return 1/(e*60/(this._getBpm()*this._getPPQ()))}_beatsToUnits(e){return 1/super._beatsToUnits(e)}_secondsToUnits(e){return 1/e}static mtof(e){return PP(e)}static ftom(e){return ku(e)}}const $ee={cbbb:-3,cbb:-2,cb:-1,c:0,"c#":1,cx:2,"c##":2,"c###":3,"cx#":3,"c#x":3,dbbb:-1,dbb:0,db:1,d:2,"d#":3,dx:4,"d##":4,"d###":5,"dx#":5,"d#x":5,ebbb:1,ebb:2,eb:3,e:4,"e#":5,ex:6,"e##":6,"e###":7,"ex#":7,"e#x":7,fbbb:2,fbb:3,fb:4,f:5,"f#":6,fx:7,"f##":7,"f###":8,"fx#":8,"f#x":8,gbbb:4,gbb:5,gb:6,g:7,"g#":8,gx:9,"g##":9,"g###":10,"gx#":10,"g#x":10,abbb:6,abb:7,ab:8,a:9,"a#":10,ax:11,"a##":11,"a###":12,"ax#":12,"a#x":12,bbbb:8,bbb:9,bb:10,b:11,"b#":12,bx:13,"b##":13,"b###":14,"bx#":14,"b#x":14},qee=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function q2(t,e){return new is(zi(),t,e)}class Sf extends eo{constructor(){super(...arguments),this.name="TransportTime"}_now(){return this.context.transport.seconds}}class Si extends Hl{constructor(){super();const e=lt(Si.getDefaults(),arguments,["context"]);this.defaultContext?this.context=this.defaultContext:this.context=e.context}static getDefaults(){return{context:zi()}}now(){return this.context.currentTime+this.context.lookAhead}immediate(){return this.context.currentTime}get sampleTime(){return 1/this.context.sampleRate}get blockTime(){return 128/this.context.sampleRate}toSeconds(e){return bee(e),new eo(this.context,e).toSeconds()}toFrequency(e){return new is(this.context,e).toFrequency()}toTicks(e){return new Sf(this.context,e).toTicks()}_getPartialProperties(e){const n=this.get();return Object.keys(n).forEach(r=>{Os(e[r])&&delete n[r]}),n}get(){const e=Pee(this);return Object.keys(e).forEach(n=>{if(Reflect.has(this,n)){const r=this[n];Wt(r)&&Wt(r.value)&&Wt(r.setValueAtTime)?e[n]=r.value:r instanceof Si?e[n]=r._getPartialProperties(e[n]):cs(r)||Po(r)||Nl(r)||bP(r)?e[n]=r:delete e[n]}}),e}set(e){return Object.keys(e).forEach(n=>{Reflect.has(this,n)&&Wt(this[n])&&(this[n]&&Wt(this[n].value)&&Wt(this[n].setValueAtTime)?this[n].value!==e[n]&&(this[n].value=e[n]):this[n]instanceof Si?this[n].set(e[n]):this[n]=e[n])}),this}}class pm extends ro{constructor(e="stopped"){super(),this.name="StateTimeline",this._initial=e,this.setStateAtTime(this._initial,0)}getValueAtTime(e){const n=this.get(e);return n!==null?n.state:this._initial}setStateAtTime(e,n,r){return ba(n,0),this.add(Object.assign({},r,{state:e,time:n})),this}getLastState(e,n){const r=this._search(n);for(let i=r;i>=0;i--){const s=this._timeline[i];if(s.state===e)return s}}getNextState(e,n){const r=this._search(n);if(r!==-1)for(let i=r;i0,"timeConstant must be a number greater than 0");const s=this.toSeconds(n);return this._assertRange(i),Tt(isFinite(i)&&isFinite(s),`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(e)}, ${JSON.stringify(n)}`),this._events.add({constant:r,time:s,type:"setTargetAtTime",value:i}),this.log(this.units,"setTargetAtTime",e,s,r),this._param.setTargetAtTime(i,s,r),this}setValueCurveAtTime(e,n,r,i=1){r=this.toSeconds(r),n=this.toSeconds(n);const s=this._fromType(e[0])*i;this.setValueAtTime(this._toType(s),n);const o=r/(e.length-1);for(let a=1;a{i.type==="cancelScheduledValues"?e.cancelScheduledValues(i.time):i.type==="setTargetAtTime"?e.setTargetAtTime(i.value,i.time,i.constant):e[i.type](i.value,i.time)}),this}setParam(e){Tt(this._swappable,"The Param must be assigned as 'swappable' in the constructor");const n=this.input;return n.disconnect(this._param),this.apply(e),this._param=e,n.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(e,n,r,i,s){return r+(n-r)*Math.exp(-(s-e)/i)}_linearInterpolate(e,n,r,i,s){return n+(i-n)*((s-e)/(r-e))}_exponentialInterpolate(e,n,r,i,s){return n*Math.pow(i/n,(s-e)/(r-e))}}class ft extends Si{constructor(){super(...arguments),this._internalChannels=[]}get numberOfInputs(){return Wt(this.input)?Wu(this.input)||this.input instanceof Xt?1:this.input.numberOfInputs:0}get numberOfOutputs(){return Wt(this.output)?this.output.numberOfOutputs:0}_isAudioNode(e){return Wt(e)&&(e instanceof ft||Tc(e))}_getInternalNodes(){const e=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&e.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&e.push(this.output),e}_setChannelProperties(e){this._getInternalNodes().forEach(r=>{r.channelCount=e.channelCount,r.channelCountMode=e.channelCountMode,r.channelInterpretation=e.channelInterpretation})}_getChannelProperties(){const e=this._getInternalNodes();Tt(e.length>0,"ToneAudioNode does not have any internal nodes");const n=e[0];return{channelCount:n.channelCount,channelCountMode:n.channelCountMode,channelInterpretation:n.channelInterpretation}}get channelCount(){return this._getChannelProperties().channelCount}set channelCount(e){const n=this._getChannelProperties();this._setChannelProperties(Object.assign(n,{channelCount:e}))}get channelCountMode(){return this._getChannelProperties().channelCountMode}set channelCountMode(e){const n=this._getChannelProperties();this._setChannelProperties(Object.assign(n,{channelCountMode:e}))}get channelInterpretation(){return this._getChannelProperties().channelInterpretation}set channelInterpretation(e){const n=this._getChannelProperties();this._setChannelProperties(Object.assign(n,{channelInterpretation:e}))}connect(e,n=0,r=0){return Do(this,e,n,r),this}toDestination(){return this.connect(this.context.destination),this}toMaster(){return ny("toMaster() has been renamed toDestination()"),this.toDestination()}disconnect(e,n=0,r=0){return DP(this,e,n,r),this}chain(...e){return ju(this,...e),this}fan(...e){return e.forEach(n=>this.connect(n)),this}dispose(){return super.dispose(),Wt(this.input)&&(this.input instanceof ft?this.input.dispose():Tc(this.input)&&this.input.disconnect()),Wt(this.output)&&(this.output instanceof ft?this.output.dispose():Tc(this.output)&&this.output.disconnect()),this._internalChannels=[],this}}function ju(...t){const e=t.shift();t.reduce((n,r)=>(n instanceof ft?n.connect(r):Tc(n)&&Do(n,r),r),e)}function Do(t,e,n=0,r=0){for(Tt(Wt(t),"Cannot connect from undefined node"),Tt(Wt(e),"Cannot connect to undefined node"),(e instanceof ft||Tc(e))&&Tt(e.numberOfInputs>0,"Cannot connect to node with no inputs"),Tt(t.numberOfOutputs>0,"Cannot connect from node with no outputs");e instanceof ft||e instanceof Xt;)Wt(e.input)&&(e=e.input);for(;t instanceof ft;)Wt(t.output)&&(t=t.output);Wu(e)?t.connect(e,n):t.connect(e,n,r)}function DP(t,e,n=0,r=0){if(Wt(e))for(;e instanceof ft;)e=e.input;for(;!Tc(t);)Wt(t.output)&&(t=t.output);Wu(e)?t.disconnect(e,n):Tc(e)?t.disconnect(e,n,r):t.disconnect()}class jt extends ft{constructor(){const e=lt(jt.getDefaults(),arguments,["gain","units"]);super(e),this.name="Gain",this._gainNode=this.context.createGain(),this.input=this._gainNode,this.output=this._gainNode,this.gain=new Xt({context:this.context,convert:e.convert,param:this._gainNode.gain,units:e.units,value:e.gain,minValue:e.minValue,maxValue:e.maxValue}),Zt(this,"gain")}static getDefaults(){return Object.assign(ft.getDefaults(),{convert:!0,gain:1,units:"gain"})}dispose(){return super.dispose(),this._gainNode.disconnect(),this.gain.dispose(),this}}class Hf extends ft{constructor(e){super(e),this.onended=En,this._startTime=-1,this._stopTime=-1,this._timeout=-1,this.output=new jt({context:this.context,gain:0}),this._gainNode=this.output,this.getStateAtTime=function(n){const r=this.toSeconds(n);return this._startTime!==-1&&r>=this._startTime&&(this._stopTime===-1||r<=this._stopTime)?"started":"stopped"},this._fadeIn=e.fadeIn,this._fadeOut=e.fadeOut,this._curve=e.curve,this.onended=e.onended}static getDefaults(){return Object.assign(ft.getDefaults(),{curve:"linear",fadeIn:0,fadeOut:0,onended:En})}_startGain(e,n=1){Tt(this._startTime===-1,"Source cannot be started more than once");const r=this.toSeconds(this._fadeIn);return this._startTime=e+r,this._startTime=Math.max(this._startTime,this.context.currentTime),r>0?(this._gainNode.gain.setValueAtTime(0,e),this._curve==="linear"?this._gainNode.gain.linearRampToValueAtTime(n,e+r):this._gainNode.gain.exponentialApproachValueAtTime(n,e,r)):this._gainNode.gain.setValueAtTime(n,e),this}stop(e){return this.log("stop",e),this._stopGain(this.toSeconds(e)),this}_stopGain(e){Tt(this._startTime!==-1,"'start' must be called before 'stop'"),this.cancelStop();const n=this.toSeconds(this._fadeOut);return this._stopTime=this.toSeconds(e)+n,this._stopTime=Math.max(this._stopTime,this.now()),n>0?this._curve==="linear"?this._gainNode.gain.linearRampTo(0,n,e):this._gainNode.gain.targetRampTo(0,n,e):(this._gainNode.gain.cancelAndHoldAtTime(e),this._gainNode.gain.setValueAtTime(0,e)),this.context.clearTimeout(this._timeout),this._timeout=this.context.setTimeout(()=>{const r=this._curve==="exponential"?n*2:0;this._stopSource(this.now()+r),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){if(this.onended!==En&&(this.onended(this),this.onended=En,!this.context.isOffline)){const e=()=>this.dispose();typeof window.requestIdleCallback<"u"?window.requestIdleCallback(e):setTimeout(e,1e3)}}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log("cancelStop"),Tt(this._startTime!==-1,"Source is not started"),this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1,this}dispose(){return super.dispose(),this._gainNode.dispose(),this.onended=En,this}}class ab extends Hf{constructor(){const e=lt(ab.getDefaults(),arguments,["offset"]);super(e),this.name="ToneConstantSource",this._source=this.context.createConstantSource(),Do(this._source,this._gainNode),this.offset=new Xt({context:this.context,convert:e.convert,param:this._source.offset,units:e.units,value:e.offset,minValue:e.minValue,maxValue:e.maxValue})}static getDefaults(){return Object.assign(Hf.getDefaults(),{convert:!0,offset:1,units:"number"})}start(e){const n=this.toSeconds(e);return this.log("start",n),this._startGain(n),this._source.start(n),this}_stopSource(e){this._source.stop(e)}dispose(){return super.dispose(),this.state==="started"&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}}class yn extends ft{constructor(){const e=lt(yn.getDefaults(),arguments,["value","units"]);super(e),this.name="Signal",this.override=!0,this.output=this._constantSource=new ab({context:this.context,convert:e.convert,offset:e.value,units:e.units,minValue:e.minValue,maxValue:e.maxValue}),this._constantSource.start(0),this.input=this._param=this._constantSource.offset}static getDefaults(){return Object.assign(ft.getDefaults(),{convert:!0,units:"number",value:0})}connect(e,n=0,r=0){return ay(this,e,n,r),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(e,n){return this._param.setValueAtTime(e,n),this}getValueAtTime(e){return this._param.getValueAtTime(e)}setRampPoint(e){return this._param.setRampPoint(e),this}linearRampToValueAtTime(e,n){return this._param.linearRampToValueAtTime(e,n),this}exponentialRampToValueAtTime(e,n){return this._param.exponentialRampToValueAtTime(e,n),this}exponentialRampTo(e,n,r){return this._param.exponentialRampTo(e,n,r),this}linearRampTo(e,n,r){return this._param.linearRampTo(e,n,r),this}targetRampTo(e,n,r){return this._param.targetRampTo(e,n,r),this}exponentialApproachValueAtTime(e,n,r){return this._param.exponentialApproachValueAtTime(e,n,r),this}setTargetAtTime(e,n,r){return this._param.setTargetAtTime(e,n,r),this}setValueCurveAtTime(e,n,r,i){return this._param.setValueCurveAtTime(e,n,r,i),this}cancelScheduledValues(e){return this._param.cancelScheduledValues(e),this}cancelAndHoldAtTime(e){return this._param.cancelAndHoldAtTime(e),this}rampTo(e,n,r){return this._param.rampTo(e,n,r),this}get value(){return this._param.value}set value(e){this._param.value=e}get convert(){return this._param.convert}set convert(e){this._param.convert=e}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(e){this._param.overridden=e}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(e){return this._param.apply(e),this}}function ay(t,e,n,r){(e instanceof Xt||Wu(e)||e instanceof yn&&e.override)&&(e.cancelScheduledValues(0),e.setValueAtTime(0,0),e instanceof yn&&(e.overridden=!0)),Do(t,e,n,r)}class lb extends Xt{constructor(){const e=lt(lb.getDefaults(),arguments,["value"]);super(e),this.name="TickParam",this._events=new ro(1/0),this._multiplier=1,this._multiplier=e.multiplier,this._events.cancel(0),this._events.add({ticks:0,time:0,type:"setValueAtTime",value:this._fromType(e.value)}),this.setValueAtTime(e.value,0)}static getDefaults(){return Object.assign(Xt.getDefaults(),{multiplier:1,units:"hertz",value:1})}setTargetAtTime(e,n,r){n=this.toSeconds(n),this.setRampPoint(n);const i=this._fromType(e),s=this._events.get(n),o=Math.round(Math.max(1/r,1));for(let a=0;a<=o;a++){const l=r*a+n,c=this._exponentialApproach(s.time,s.value,i,r,l);this.linearRampToValueAtTime(this._toType(c),l)}return this}setValueAtTime(e,n){const r=this.toSeconds(n);super.setValueAtTime(e,n);const i=this._events.get(r),s=this._events.previousEvent(i),o=this._getTicksUntilEvent(s,r);return i.ticks=Math.max(o,0),this}linearRampToValueAtTime(e,n){const r=this.toSeconds(n);super.linearRampToValueAtTime(e,n);const i=this._events.get(r),s=this._events.previousEvent(i),o=this._getTicksUntilEvent(s,r);return i.ticks=Math.max(o,0),this}exponentialRampToValueAtTime(e,n){n=this.toSeconds(n);const r=this._fromType(e),i=this._events.get(n),s=Math.round(Math.max((n-i.time)*10,1)),o=(n-i.time)/s;for(let a=0;a<=s;a++){const l=o*a+i.time,c=this._exponentialInterpolate(i.time,i.value,n,r,l);this.linearRampToValueAtTime(this._toType(c),l)}return this}_getTicksUntilEvent(e,n){if(e===null)e={ticks:0,time:0,type:"setValueAtTime",value:0};else if(Os(e.ticks)){const o=this._events.previousEvent(e);e.ticks=this._getTicksUntilEvent(o,e.time)}const r=this._fromType(this.getValueAtTime(e.time));let i=this._fromType(this.getValueAtTime(n));const s=this._events.get(n);return s&&s.time===n&&s.type==="setValueAtTime"&&(i=this._fromType(this.getValueAtTime(n-this.sampleTime))),.5*(n-e.time)*(r+i)+e.ticks}getTicksAtTime(e){const n=this.toSeconds(e),r=this._events.get(n);return Math.max(this._getTicksUntilEvent(r,n),0)}getDurationOfTicks(e,n){const r=this.toSeconds(n),i=this.getTicksAtTime(n);return this.getTimeOfTick(i+e)-r}getTimeOfTick(e){const n=this._events.get(e,"ticks"),r=this._events.getAfter(e,"ticks");if(n&&n.ticks===e)return n.time;if(n&&r&&r.type==="linearRampToValueAtTime"&&n.value!==r.value){const i=this._fromType(this.getValueAtTime(n.time)),o=(this._fromType(this.getValueAtTime(r.time))-i)/(r.time-n.time),a=Math.sqrt(Math.pow(i,2)-2*o*(n.ticks-e)),l=(-i+a)/o,c=(-i-a)/o;return(l>0?l:c)+n.time}else return n?n.value===0?1/0:n.time+(e-n.ticks)/n.value:e/this._initialValue}ticksToTime(e,n){return this.getDurationOfTicks(e,n)}timeToTicks(e,n){const r=this.toSeconds(n),i=this.toSeconds(e),s=this.getTicksAtTime(r);return this.getTicksAtTime(r+i)-s}_fromType(e){return this.units==="bpm"&&this.multiplier?1/(60/e/this.multiplier):super._fromType(e)}_toType(e){return this.units==="bpm"&&this.multiplier?e/this.multiplier*60:super._toType(e)}get multiplier(){return this._multiplier}set multiplier(e){const n=this.value;this._multiplier=e,this.cancelScheduledValues(0),this.setValueAtTime(n,0)}}class cb extends yn{constructor(){const e=lt(cb.getDefaults(),arguments,["value"]);super(e),this.name="TickSignal",this.input=this._param=new lb({context:this.context,convert:e.convert,multiplier:e.multiplier,param:this._constantSource.offset,units:e.units,value:e.value})}static getDefaults(){return Object.assign(yn.getDefaults(),{multiplier:1,units:"hertz",value:1})}ticksToTime(e,n){return this._param.ticksToTime(e,n)}timeToTicks(e,n){return this._param.timeToTicks(e,n)}getTimeOfTick(e){return this._param.getTimeOfTick(e)}getDurationOfTicks(e,n){return this._param.getDurationOfTicks(e,n)}getTicksAtTime(e){return this._param.getTicksAtTime(e)}get multiplier(){return this._param.multiplier}set multiplier(e){this._param.multiplier=e}dispose(){return super.dispose(),this._param.dispose(),this}}class ub extends Si{constructor(){const e=lt(ub.getDefaults(),arguments,["frequency"]);super(e),this.name="TickSource",this._state=new pm,this._tickOffset=new ro,this._ticksAtTime=new ro,this._secondsAtTime=new ro,this.frequency=new cb({context:this.context,units:e.units,value:e.frequency}),Zt(this,"frequency"),this._state.setStateAtTime("stopped",0),this.setTicksAtTime(0,0)}static getDefaults(){return Object.assign({frequency:1,units:"hertz"},Si.getDefaults())}get state(){return this.getStateAtTime(this.now())}start(e,n){const r=this.toSeconds(e);return this._state.getValueAtTime(r)!=="started"&&(this._state.setStateAtTime("started",r),Wt(n)&&this.setTicksAtTime(n,r),this._ticksAtTime.cancel(r),this._secondsAtTime.cancel(r)),this}stop(e){const n=this.toSeconds(e);if(this._state.getValueAtTime(n)==="stopped"){const r=this._state.get(n);r&&r.time>0&&(this._tickOffset.cancel(r.time),this._state.cancel(r.time))}return this._state.cancel(n),this._state.setStateAtTime("stopped",n),this.setTicksAtTime(0,n),this._ticksAtTime.cancel(n),this._secondsAtTime.cancel(n),this}pause(e){const n=this.toSeconds(e);return this._state.getValueAtTime(n)==="started"&&(this._state.setStateAtTime("paused",n),this._ticksAtTime.cancel(n),this._secondsAtTime.cancel(n)),this}cancel(e){return e=this.toSeconds(e),this._state.cancel(e),this._tickOffset.cancel(e),this._ticksAtTime.cancel(e),this._secondsAtTime.cancel(e),this}getTicksAtTime(e){const n=this.toSeconds(e),r=this._state.getLastState("stopped",n),i=this._ticksAtTime.get(n),s={state:"paused",time:n};this._state.add(s);let o=i||r,a=i?i.ticks:0,l=null;return this._state.forEachBetween(o.time,n+this.sampleTime,c=>{let u=o.time;const h=this._tickOffset.get(c.time);h&&h.time>=o.time&&(a=h.ticks,u=h.time),o.state==="started"&&c.state!=="started"&&(a+=this.frequency.getTicksAtTime(c.time)-this.frequency.getTicksAtTime(u),c.time!==s.time&&(l={state:c.state,time:c.time,ticks:a})),o=c}),this._state.remove(s),l&&this._ticksAtTime.add(l),a}get ticks(){return this.getTicksAtTime(this.now())}set ticks(e){this.setTicksAtTime(e,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(e){const n=this.now(),r=this.frequency.timeToTicks(e,n);this.setTicksAtTime(r,n)}getSecondsAtTime(e){e=this.toSeconds(e);const n=this._state.getLastState("stopped",e),r={state:"paused",time:e};this._state.add(r);const i=this._secondsAtTime.get(e);let s=i||n,o=i?i.seconds:0,a=null;return this._state.forEachBetween(s.time,e+this.sampleTime,l=>{let c=s.time;const u=this._tickOffset.get(l.time);u&&u.time>=s.time&&(o=u.seconds,c=u.time),s.state==="started"&&l.state!=="started"&&(o+=l.time-c,l.time!==r.time&&(a={state:l.state,time:l.time,seconds:o})),s=l}),this._state.remove(r),a&&this._secondsAtTime.add(a),o}setTicksAtTime(e,n){return n=this.toSeconds(n),this._tickOffset.cancel(n),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(e,n),ticks:e,time:n}),this._ticksAtTime.cancel(n),this._secondsAtTime.cancel(n),this}getStateAtTime(e){return e=this.toSeconds(e),this._state.getValueAtTime(e)}getTimeOfTick(e,n=this.now()){const r=this._tickOffset.get(n),i=this._state.get(n),s=Math.max(r.time,i.time),o=this.frequency.getTicksAtTime(s)+e-r.ticks;return this.frequency.getTimeOfTick(o)}forEachTickBetween(e,n,r){let i=this._state.get(e);this._state.forEachBetween(e,n,o=>{i&&i.state==="started"&&o.state!=="started"&&this.forEachTickBetween(Math.max(i.time,e),o.time-this.sampleTime,r),i=o});let s=null;if(i&&i.state==="started"){const o=Math.max(i.time,e),a=this.frequency.getTicksAtTime(o),l=this.frequency.getTicksAtTime(i.time),c=a-l;let u=Math.ceil(c)-c;u=wo(u,1)?0:u;let h=this.frequency.getTimeOfTick(a+u);for(;h{switch(r.state){case"started":const i=this._tickSource.getTicksAtTime(r.time);this.emit("start",r.time,i);break;case"stopped":r.time!==0&&this.emit("stop",r.time);break;case"paused":this.emit("pause",r.time);break}}),this._tickSource.forEachTickBetween(e,n,(r,i)=>{this.callback(r,i)}))}getStateAtTime(e){const n=this.toSeconds(e);return this._state.getValueAtTime(n)}dispose(){return super.dispose(),this.context.off("tick",this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}}hm.mixin(ly);class Gf extends ft{constructor(){const e=lt(Gf.getDefaults(),arguments,["delayTime","maxDelay"]);super(e),this.name="Delay";const n=this.toSeconds(e.maxDelay);this._maxDelay=Math.max(n,this.toSeconds(e.delayTime)),this._delayNode=this.input=this.output=this.context.createDelay(n),this.delayTime=new Xt({context:this.context,param:this._delayNode.delayTime,units:"time",value:e.delayTime,minValue:0,maxValue:this.maxDelay}),Zt(this,"delayTime")}static getDefaults(){return Object.assign(ft.getDefaults(),{delayTime:0,maxDelay:1})}get maxDelay(){return this._maxDelay}dispose(){return super.dispose(),this._delayNode.disconnect(),this.delayTime.dispose(),this}}class kc extends ft{constructor(){const e=lt(kc.getDefaults(),arguments,["volume"]);super(e),this.name="Volume",this.input=this.output=new jt({context:this.context,gain:e.volume,units:"decibels"}),this.volume=this.output.gain,Zt(this,"volume"),this._unmutedVolume=e.volume,this.mute=e.mute}static getDefaults(){return Object.assign(ft.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(e){!this.mute&&e?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!e&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}}class hb extends ft{constructor(){const e=lt(hb.getDefaults(),arguments);super(e),this.name="Destination",this.input=new kc({context:this.context}),this.output=new jt({context:this.context}),this.volume=this.input.volume,ju(this.input,this.output,this.context.rawContext.destination),this.mute=e.mute,this._internalChannels=[this.input,this.context.rawContext.destination,this.output]}static getDefaults(){return Object.assign(ft.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(e){this.input.mute=e}chain(...e){return this.input.disconnect(),e.unshift(this.input),e.push(this.output),ju(...e),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}}ry(t=>{t.destination=new hb({context:t})});iy(t=>{t.destination.dispose()});class Xee extends ft{constructor(){super(...arguments),this.name="Listener",this.positionX=new Xt({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new Xt({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new Xt({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new Xt({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new Xt({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new Xt({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new Xt({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new Xt({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new Xt({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(ft.getDefaults(),{positionX:0,positionY:0,positionZ:0,forwardX:0,forwardY:0,forwardZ:-1,upX:0,upY:1,upZ:0})}dispose(){return super.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this.forwardX.dispose(),this.forwardY.dispose(),this.forwardZ.dispose(),this.upX.dispose(),this.upY.dispose(),this.upZ.dispose(),this}}ry(t=>{t.listener=new Xee({context:t})});iy(t=>{t.listener.dispose()});class fb extends Hl{constructor(){super(),this.name="ToneAudioBuffers",this._buffers=new Map,this._loadingCount=0;const e=lt(fb.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");this.baseUrl=e.baseUrl,Object.keys(e.urls).forEach(n=>{this._loadingCount++;const r=e.urls[n];this.add(n,r,this._bufferLoaded.bind(this,e.onload),e.onerror)})}static getDefaults(){return{baseUrl:"",onerror:En,onload:En,urls:{}}}has(e){return this._buffers.has(e.toString())}get(e){return Tt(this.has(e),`ToneAudioBuffers has no buffer named: ${e}`),this._buffers.get(e.toString())}_bufferLoaded(e){this._loadingCount--,this._loadingCount===0&&e&&e()}get loaded(){return Array.from(this._buffers).every(([e,n])=>n.loaded)}add(e,n,r=En,i=En){return Nl(n)?(this.baseUrl&&n.trim().substring(0,11).toLowerCase()==="data:audio/"&&(this.baseUrl=""),this._buffers.set(e.toString(),new An(this.baseUrl+n,r,i))):this._buffers.set(e.toString(),new An(n,r,i)),this}dispose(){return super.dispose(),this._buffers.forEach(e=>e.dispose()),this._buffers.clear(),this}}class W_ extends is{constructor(){super(...arguments),this.name="MidiClass",this.defaultUnits="midi"}_frequencyToUnits(e){return ku(super._frequencyToUnits(e))}_ticksToUnits(e){return ku(super._ticksToUnits(e))}_beatsToUnits(e){return ku(super._beatsToUnits(e))}_secondsToUnits(e){return ku(super._secondsToUnits(e))}toMidi(){return this.valueOf()}toFrequency(){return PP(this.toMidi())}transpose(e){return new W_(this.context,this.toMidi()+e)}}class Pr extends Sf{constructor(){super(...arguments),this.name="Ticks",this.defaultUnits="i"}_now(){return this.context.transport.ticks}_beatsToUnits(e){return this._getPPQ()*e}_secondsToUnits(e){return Math.floor(e/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(e){return e}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}}class Kee extends Si{constructor(){super(...arguments),this.name="Draw",this.expiration=.25,this.anticipation=.008,this._events=new ro,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(e,n){return this._events.add({callback:e,time:this.toSeconds(n)}),this._events.length===1&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(e){return this._events.cancel(this.toSeconds(e)),this}_drawLoop(){const e=this.context.currentTime;for(;this._events.length&&this._events.peek().time-this.anticipation<=e;){const n=this._events.shift();n&&e-n.time<=this.expiration&&n.callback()}this._events.length>0&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop))}dispose(){return super.dispose(),this._events.dispose(),cancelAnimationFrame(this._animationFrame),this}}ry(t=>{t.draw=new Kee({context:t})});iy(t=>{t.draw.dispose()});class Yee extends Hl{constructor(){super(...arguments),this.name="IntervalTimeline",this._root=null,this._length=0}add(e){Tt(Wt(e.time),"Events must have a time property"),Tt(Wt(e.duration),"Events must have a duration parameter"),e.time=e.time.valueOf();let n=new Zee(e.time,e.time+e.duration,e);for(this._root===null?this._root=n:this._root.insert(n),this._length++;n!==null;)n.updateHeight(),n.updateMax(),this._rebalance(n),n=n.parent;return this}remove(e){if(this._root!==null){const n=[];this._root.search(e.time,n);for(const r of n)if(r.event===e){this._removeNode(r),this._length--;break}}return this}get length(){return this._length}cancel(e){return this.forEachFrom(e,n=>this.remove(n)),this}_setRoot(e){this._root=e,this._root!==null&&(this._root.parent=null)}_replaceNodeInParent(e,n){e.parent!==null?(e.isLeftChild()?e.parent.left=n:e.parent.right=n,this._rebalance(e.parent)):this._setRoot(n)}_removeNode(e){if(e.left===null&&e.right===null)this._replaceNodeInParent(e,null);else if(e.right===null)this._replaceNodeInParent(e,e.left);else if(e.left===null)this._replaceNodeInParent(e,e.right);else{const n=e.getBalance();let r,i=null;if(n>0)if(e.left.right===null)r=e.left,r.right=e.right,i=r;else{for(r=e.left.right;r.right!==null;)r=r.right;r.parent&&(r.parent.right=r.left,i=r.parent,r.left=e.left,r.right=e.right)}else if(e.right.left===null)r=e.right,r.left=e.left,i=r;else{for(r=e.right.left;r.left!==null;)r=r.left;r.parent&&(r.parent.left=r.right,i=r.parent,r.left=e.left,r.right=e.right)}e.parent!==null?e.isLeftChild()?e.parent.left=r:e.parent.right=r:this._setRoot(r),i&&this._rebalance(i)}e.dispose()}_rotateLeft(e){const n=e.parent,r=e.isLeftChild(),i=e.right;i&&(e.right=i.left,i.left=e),n!==null?r?n.left=i:n.right=i:this._setRoot(i)}_rotateRight(e){const n=e.parent,r=e.isLeftChild(),i=e.left;i&&(e.left=i.right,i.right=e),n!==null?r?n.left=i:n.right=i:this._setRoot(i)}_rebalance(e){const n=e.getBalance();n>1&&e.left?e.left.getBalance()<0?this._rotateLeft(e.left):this._rotateRight(e):n<-1&&e.right&&(e.right.getBalance()>0?this._rotateRight(e.right):this._rotateLeft(e))}get(e){if(this._root!==null){const n=[];if(this._root.search(e,n),n.length>0){let r=n[0];for(let i=1;ir.low&&(r=n[i]);return r.event}}return null}forEach(e){if(this._root!==null){const n=[];this._root.traverse(r=>n.push(r)),n.forEach(r=>{r.event&&e(r.event)})}return this}forEachAtTime(e,n){if(this._root!==null){const r=[];this._root.search(e,r),r.forEach(i=>{i.event&&n(i.event)})}return this}forEachFrom(e,n){if(this._root!==null){const r=[];this._root.searchAfter(e,r),r.forEach(i=>{i.event&&n(i.event)})}return this}dispose(){return super.dispose(),this._root!==null&&this._root.traverse(e=>e.dispose()),this._root=null,this}}class Zee{constructor(e,n,r){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=r,this.low=e,this.high=n,this.max=this.high}insert(e){e.low<=this.low?this.left===null?this.left=e:this.left.insert(e):this.right===null?this.right=e:this.right.insert(e)}search(e,n){e>this.max||(this.left!==null&&this.left.search(e,n),this.low<=e&&this.high>e&&n.push(this),!(this.low>e)&&this.right!==null&&this.right.search(e,n))}searchAfter(e,n){this.low>=e&&(n.push(this),this.left!==null&&this.left.searchAfter(e,n)),this.right!==null&&this.right.searchAfter(e,n)}traverse(e){e(this),this.left!==null&&this.left.traverse(e),this.right!==null&&this.right.traverse(e)}updateHeight(){this.left!==null&&this.right!==null?this.height=Math.max(this.left.height,this.right.height)+1:this.right!==null?this.height=this.right.height+1:this.left!==null?this.height=this.left.height+1:this.height=0}updateMax(){this.max=this.high,this.left!==null&&(this.max=Math.max(this.max,this.left.max)),this.right!==null&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let e=0;return this.left!==null&&this.right!==null?e=this.left.height-this.right.height:this.left!==null?e=this.left.height+1:this.right!==null&&(e=-(this.right.height+1)),e}isLeftChild(){return this.parent!==null&&this.parent.left===this}get left(){return this._left}set left(e){this._left=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(e){this._right=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}}class Jee extends Hl{constructor(e){super(),this.name="TimelineValue",this._timeline=new ro({memory:10}),this._initialValue=e}set(e,n){return this._timeline.add({value:e,time:n}),this}get(e){const n=this._timeline.get(e);return n?n.value:this._initialValue}}class Aa extends ft{constructor(){super(lt(Aa.getDefaults(),arguments,["context"]))}connect(e,n=0,r=0){return ay(this,e,n,r),this}}class ch extends Aa{constructor(){const e=lt(ch.getDefaults(),arguments,["mapping","length"]);super(e),this.name="WaveShaper",this._shaper=this.context.createWaveShaper(),this.input=this._shaper,this.output=this._shaper,cs(e.mapping)||e.mapping instanceof Float32Array?this.curve=Float32Array.from(e.mapping):Tee(e.mapping)&&this.setMap(e.mapping,e.length)}static getDefaults(){return Object.assign(yn.getDefaults(),{length:1024})}setMap(e,n=1024){const r=new Float32Array(n);for(let i=0,s=n;ir.includes(e));Tt(n,"oversampling must be either 'none', '2x', or '4x'"),this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.disconnect(),this}}class db extends Aa{constructor(){const e=lt(db.getDefaults(),arguments,["value"]);super(e),this.name="Pow",this._exponentScaler=this.input=this.output=new ch({context:this.context,mapping:this._expFunc(e.value),length:8192}),this._exponent=e.value}static getDefaults(){return Object.assign(Aa.getDefaults(),{value:1})}_expFunc(e){return n=>Math.pow(Math.abs(n),e)}get value(){return this._exponent}set value(e){this._exponent=e,this._exponentScaler.setMap(this._expFunc(this._exponent))}dispose(){return super.dispose(),this._exponentScaler.dispose(),this}}class Ic{constructor(e,n){this.id=Ic._eventId++,this._remainderTime=0;const r=Object.assign(Ic.getDefaults(),n);this.transport=e,this.callback=r.callback,this._once=r.once,this.time=Math.floor(r.time),this._remainderTime=r.time-this.time}static getDefaults(){return{callback:En,once:!1,time:0}}get floatTime(){return this.time+this._remainderTime}invoke(e){if(this.callback){const n=this.transport.bpm.getDurationOfTicks(1,e);this.callback(e+this._remainderTime*n),this._once&&this.transport.clear(this.id)}}dispose(){return this.callback=void 0,this}}Ic._eventId=0;class pb extends Ic{constructor(e,n){super(e,n),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);const r=Object.assign(pb.getDefaults(),n);this.duration=r.duration,this._interval=r.interval,this._nextTick=r.time,this.transport.on("start",this._boundRestart),this.transport.on("loopStart",this._boundRestart),this.transport.on("ticks",this._boundRestart),this.context=this.transport.context,this._restart()}static getDefaults(){return Object.assign({},Ic.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(e){this._createEvents(e),super.invoke(e)}_createEvent(){return G_(this._nextTick,this.floatTime+this.duration)?this.transport.scheduleOnce(this.invoke.bind(this),new Pr(this.context,this._nextTick).toSeconds()):-1}_createEvents(e){G_(this._nextTick+this._interval,this.floatTime+this.duration)&&(this._nextTick+=this._interval,this._currentId=this._nextId,this._nextId=this.transport.scheduleOnce(this.invoke.bind(this),new Pr(this.context,this._nextTick).toSeconds()))}_restart(e){this.transport.clear(this._currentId),this.transport.clear(this._nextId),this._nextTick=this.floatTime;const n=this.transport.getTicksAtTime(e);Vf(n,this.time)&&(this._nextTick=this.floatTime+Math.ceil((n-this.floatTime)/this._interval)*this._interval),this._currentId=this._createEvent(),this._nextTick+=this._interval,this._nextId=this._createEvent()}dispose(){return super.dispose(),this.transport.clear(this._currentId),this.transport.clear(this._nextId),this.transport.off("start",this._boundRestart),this.transport.off("loopStart",this._boundRestart),this.transport.off("ticks",this._boundRestart),this}}class cy extends Si{constructor(){const e=lt(cy.getDefaults(),arguments);super(e),this.name="Transport",this._loop=new Jee(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new ro,this._repeatedEvents=new Yee,this._syncedSignals=[],this._swingAmount=0,this._ppq=e.ppq,this._clock=new ly({callback:this._processTick.bind(this),context:this.context,frequency:0,units:"bpm"}),this._bindClockEvents(),this.bpm=this._clock.frequency,this._clock.frequency.multiplier=e.ppq,this.bpm.setValueAtTime(e.bpm,0),Zt(this,"bpm"),this._timeSignature=e.timeSignature,this._swingTicks=e.ppq/2}static getDefaults(){return Object.assign(Si.getDefaults(),{bpm:120,loopEnd:"4m",loopStart:0,ppq:192,swing:0,swingSubdivision:"8n",timeSignature:4})}_processTick(e,n){if(this._loop.get(e)&&n>=this._loopEnd&&(this.emit("loopEnd",e),this._clock.setTicksAtTime(this._loopStart,e),n=this._loopStart,this.emit("loopStart",e,this._clock.getSecondsAtTime(e)),this.emit("loop",e)),this._swingAmount>0&&n%this._ppq!==0&&n%(this._swingTicks*2)!==0){const r=n%(this._swingTicks*2)/(this._swingTicks*2),i=Math.sin(r*Math.PI)*this._swingAmount;e+=new Pr(this.context,this._swingTicks*2/3).toSeconds()*i}$2(!0),this._timeline.forEachAtTime(n,r=>r.invoke(e)),$2(!1)}schedule(e,n){const r=new Ic(this,{callback:e,time:new Sf(this.context,n).toTicks()});return this._addEvent(r,this._timeline)}scheduleRepeat(e,n,r,i=1/0){const s=new pb(this,{callback:e,duration:new eo(this.context,i).toTicks(),interval:new eo(this.context,n).toTicks(),time:new Sf(this.context,r).toTicks()});return this._addEvent(s,this._repeatedEvents)}scheduleOnce(e,n){const r=new Ic(this,{callback:e,once:!0,time:new Sf(this.context,n).toTicks()});return this._addEvent(r,this._timeline)}clear(e){if(this._scheduledEvents.hasOwnProperty(e)){const n=this._scheduledEvents[e.toString()];n.timeline.remove(n.event),n.event.dispose(),delete this._scheduledEvents[e.toString()]}return this}_addEvent(e,n){return this._scheduledEvents[e.id.toString()]={event:e,timeline:n},n.add(e),e.id}cancel(e=0){const n=this.toTicks(e);return this._timeline.forEachFrom(n,r=>this.clear(r.id)),this._repeatedEvents.forEachFrom(n,r=>this.clear(r.id)),this}_bindClockEvents(){this._clock.on("start",(e,n)=>{n=new Pr(this.context,n).toSeconds(),this.emit("start",e,n)}),this._clock.on("stop",e=>{this.emit("stop",e)}),this._clock.on("pause",e=>{this.emit("pause",e)})}get state(){return this._clock.getStateAtTime(this.now())}start(e,n){this.context.resume();let r;return Wt(n)&&(r=this.toTicks(n)),this._clock.start(e,r),this}stop(e){return this._clock.stop(e),this}pause(e){return this._clock.pause(e),this}toggle(e){return e=this.toSeconds(e),this._clock.getStateAtTime(e)!=="started"?this.start(e):this.stop(e),this}get timeSignature(){return this._timeSignature}set timeSignature(e){cs(e)&&(e=e[0]/e[1]*4),this._timeSignature=e}get loopStart(){return new eo(this.context,this._loopStart,"i").toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e)}get loopEnd(){return new eo(this.context,this._loopEnd,"i").toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e)}get loop(){return this._loop.get(this.now())}set loop(e){this._loop.set(e,this.now())}setLoopPoints(e,n){return this.loopStart=e,this.loopEnd=n,this}get swing(){return this._swingAmount}set swing(e){this._swingAmount=e}get swingSubdivision(){return new Pr(this.context,this._swingTicks).toNotation()}set swingSubdivision(e){this._swingTicks=this.toTicks(e)}get position(){const e=this.now(),n=this._clock.getTicksAtTime(e);return new Pr(this.context,n).toBarsBeatsSixteenths()}set position(e){const n=this.toTicks(e);this.ticks=n}get seconds(){return this._clock.seconds}set seconds(e){const n=this.now(),r=this._clock.frequency.timeToTicks(e,n);this.ticks=r}get progress(){if(this.loop){const e=this.now();return(this._clock.getTicksAtTime(e)-this._loopStart)/(this._loopEnd-this._loopStart)}else return 0}get ticks(){return this._clock.ticks}set ticks(e){if(this._clock.ticks!==e){const n=this.now();if(this.state==="started"){const r=this._clock.getTicksAtTime(n),i=this._clock.frequency.getDurationOfTicks(Math.ceil(r)-r,n),s=n+i;this.emit("stop",s),this._clock.setTicksAtTime(e,s),this.emit("start",s,this._clock.getSecondsAtTime(s))}else this.emit("ticks",n),this._clock.setTicksAtTime(e,n)}}getTicksAtTime(e){return this._clock.getTicksAtTime(e)}getSecondsAtTime(e){return this._clock.getSecondsAtTime(e)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(e){this._clock.frequency.multiplier=e}nextSubdivision(e){if(e=this.toTicks(e),this.state!=="started")return 0;{const n=this.now(),r=this.getTicksAtTime(n),i=e-r%e;return this._clock.nextTickTime(i,n)}}syncSignal(e,n){const r=this.now();let i=this.bpm,s=1/(60/i.getValueAtTime(r)/this.PPQ),o=[];if(e.units==="time"){const l=.015625/s,c=new jt(l),u=new db(-1),h=new jt(l);i.chain(c,u,h),i=h,s=1/s,o=[c,u,h]}n||(e.getValueAtTime(r)!==0?n=e.getValueAtTime(r)/s:n=0);const a=new jt(n);return i.connect(a),a.connect(e._param),o.push(a),this._syncedSignals.push({initial:e.value,nodes:o,signal:e}),e.value=0,this}unsyncSignal(e){for(let n=this._syncedSignals.length-1;n>=0;n--){const r=this._syncedSignals[n];r.signal===e&&(r.nodes.forEach(i=>i.dispose()),r.signal.value=r.initial,this._syncedSignals.splice(n,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),dm(this,"bpm"),this._timeline.dispose(),this._repeatedEvents.dispose(),this}}hm.mixin(cy);ry(t=>{t.transport=new cy({context:t})});iy(t=>{t.transport.dispose()});class Ti extends ft{constructor(e){super(e),this.input=void 0,this._state=new pm("stopped"),this._synced=!1,this._scheduled=[],this._syncedStart=En,this._syncedStop=En,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new kc({context:this.context,mute:e.mute,volume:e.volume}),this.volume=this._volume.volume,Zt(this,"volume"),this.onstop=e.onstop}static getDefaults(){return Object.assign(ft.getDefaults(),{mute:!1,onstop:En,volume:0})}get state(){return this._synced?this.context.transport.state==="started"?this._state.getValueAtTime(this.context.transport.seconds):"stopped":this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}_clampToCurrentTime(e){return this._synced?e:Math.max(e,this.context.currentTime)}start(e,n,r){let i=Os(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(i=this._clampToCurrentTime(i),!this._synced&&this._state.getValueAtTime(i)==="started")Tt(Vf(i,this._state.get(i).time),"Start time must be strictly greater than previous start time"),this._state.cancel(i),this._state.setStateAtTime("started",i),this.log("restart",i),this.restart(i,n,r);else if(this.log("start",i),this._state.setStateAtTime("started",i),this._synced){const s=this._state.get(i);s&&(s.offset=this.toSeconds(xa(n,0)),s.duration=r?this.toSeconds(r):void 0);const o=this.context.transport.schedule(a=>{this._start(a,n,r)},i);this._scheduled.push(o),this.context.transport.state==="started"&&this.context.transport.getSecondsAtTime(this.immediate())>i&&this._syncedStart(this.now(),this.context.transport.seconds)}else AP(this.context),this._start(i,n,r);return this}stop(e){let n=Os(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(n=this._clampToCurrentTime(n),this._state.getValueAtTime(n)==="started"||Wt(this._state.getNextState("started",n))){if(this.log("stop",n),!this._synced)this._stop(n);else{const r=this.context.transport.schedule(this._stop.bind(this),n);this._scheduled.push(r)}this._state.cancel(n),this._state.setStateAtTime("stopped",n)}return this}restart(e,n,r){return e=this.toSeconds(e),this._state.getValueAtTime(e)==="started"&&(this._state.cancel(e),this._restart(e,n,r)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(e,n)=>{if(Vf(n,0)){const r=this._state.get(n);if(r&&r.state==="started"&&r.time!==n){const i=n-this.toSeconds(r.time);let s;r.duration&&(s=this.toSeconds(r.duration)-i),this._start(e,this.toSeconds(r.offset)+i,s)}}},this._syncedStop=e=>{const n=this.context.transport.getSecondsAtTime(Math.max(e-this.sampleTime,0));this._state.getValueAtTime(n)==="started"&&this._stop(e)},this.context.transport.on("start",this._syncedStart),this.context.transport.on("loopStart",this._syncedStart),this.context.transport.on("stop",this._syncedStop),this.context.transport.on("pause",this._syncedStop),this.context.transport.on("loopEnd",this._syncedStop)),this}unsync(){return this._synced&&(this.context.transport.off("stop",this._syncedStop),this.context.transport.off("pause",this._syncedStop),this.context.transport.off("loopEnd",this._syncedStop),this.context.transport.off("start",this._syncedStart),this.context.transport.off("loopStart",this._syncedStart)),this._synced=!1,this._scheduled.forEach(e=>this.context.transport.clear(e)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=En,this.unsync(),this._volume.dispose(),this._state.dispose(),this}}class mm extends Hf{constructor(){const e=lt(mm.getDefaults(),arguments,["url","onload"]);super(e),this.name="ToneBufferSource",this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1,Do(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new Xt({context:this.context,param:this._source.playbackRate,units:"positive",value:e.playbackRate}),this.loop=e.loop,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this._buffer=new An(e.url,e.onload,e.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(Hf.getDefaults(),{url:new An,loop:!1,loopEnd:0,loopStart:0,onload:En,onerror:En,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e}get curve(){return this._curve}set curve(e){this._curve=e}start(e,n,r,i=1){Tt(this.buffer.loaded,"buffer is either not set or not loaded");const s=this.toSeconds(e);this._startGain(s,i),this.loop?n=xa(n,this.loopStart):n=xa(n,0);let o=Math.max(this.toSeconds(n),0);if(this.loop){const a=this.toSeconds(this.loopEnd)||this.buffer.duration,l=this.toSeconds(this.loopStart),c=a-l;qE(o,a)&&(o=(o-l)%c+l),wo(o,this.buffer.duration)&&(o=0)}if(this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,G_(o,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(s,o)),Wt(r)){let a=this.toSeconds(r);a=Math.max(a,0),this.stop(s+a)}return this}_stopSource(e){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(e)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(e){this._source.loopStart=this.toSeconds(e)}get loopEnd(){return this._source.loopEnd}set loopEnd(e){this._source.loopEnd=this.toSeconds(e)}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._source.loop}set loop(e){this._source.loop=e,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}}class Wf extends Ti{constructor(){const e=lt(Wf.getDefaults(),arguments,["type"]);super(e),this.name="Noise",this._source=null,this._playbackRate=e.playbackRate,this.type=e.type,this._fadeIn=e.fadeIn,this._fadeOut=e.fadeOut}static getDefaults(){return Object.assign(Ti.getDefaults(),{fadeIn:0,fadeOut:0,playbackRate:1,type:"white"})}get type(){return this._type}set type(e){if(Tt(e in X2,"Noise: invalid type: "+e),this._type!==e&&(this._type=e,this.state==="started")){const n=this.now();this._stop(n),this._start(n)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._source&&(this._source.playbackRate.value=e)}_start(e){const n=X2[this._type];this._source=new mm({url:n,context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,loop:!0,onended:()=>this.onstop(this),playbackRate:this._playbackRate}).connect(this.output),this._source.start(this.toSeconds(e),Math.random()*(n.duration-.001))}_stop(e){this._source&&(this._source.stop(this.toSeconds(e)),this._source=null)}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e,this._source&&(this._source.fadeIn=this._fadeIn)}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e,this._source&&(this._source.fadeOut=this._fadeOut)}_restart(e){this._stop(e),this._start(e)}dispose(){return super.dispose(),this._source&&this._source.disconnect(),this}}const $h=44100*5,qS=2,rl={brown:null,pink:null,white:null},X2={get brown(){if(!rl.brown){const t=[];for(let e=0;ethis.onstop(this)});this._oscillator=r,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.start(n)}_stop(e){const n=this.toSeconds(e);this._oscillator&&this._oscillator.stop(n)}_restart(e){const n=this.toSeconds(e);return this.log("restart",n),this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(n),this}syncFrequency(){return this.context.transport.syncSignal(this.frequency),this}unsyncFrequency(){return this.context.transport.unsyncSignal(this.frequency),this}_getCachedPeriodicWave(){if(this._type==="custom")return rr._periodicWaveCache.find(n=>n.phase===this._phase&&Lee(n.partials,this._partials));{const e=rr._periodicWaveCache.find(n=>n.type===this._type&&n.phase===this._phase);return this._partialCount=e?e.partialCount:this._partialCount,e}}get type(){return this._type}set type(e){this._type=e;const n=["sine","square","sawtooth","triangle"].indexOf(e)!==-1;if(this._phase===0&&n)this._wave=void 0,this._partialCount=0,this._oscillator!==null&&(this._oscillator.type=e);else{const r=this._getCachedPeriodicWave();if(Wt(r)){const{partials:i,wave:s}=r;this._wave=s,this._partials=i,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave)}else{const[i,s]=this._getRealImaginary(e,this._phase),o=this.context.createPeriodicWave(i,s);this._wave=o,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave),rr._periodicWaveCache.push({imag:s,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:i,type:this._type,wave:this._wave}),rr._periodicWaveCache.length>100&&rr._periodicWaveCache.shift()}}}get baseType(){return this._type.replace(this.partialCount.toString(),"")}set baseType(e){this.partialCount&&this._type!=="custom"&&e!=="custom"?this.type=e+this.partialCount:this.type=e}get partialCount(){return this._partialCount}set partialCount(e){ba(e,0);let n=this._type;const r=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(this._type);if(r&&(n=r[1]),this._type!=="custom")e===0?this.type=n:this.type=n+e.toString();else{const i=new Float32Array(e);this._partials.forEach((s,o)=>i[o]=s),this._partials=Array.from(i),this.type=this._type}}_getRealImaginary(e,n){let i=2048;const s=new Float32Array(i),o=new Float32Array(i);let a=1;if(e==="custom"){if(a=this._partials.length+1,this._partialCount=this._partials.length,i=a,this._partials.length===0)return[s,o]}else{const l=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(e);l?(a=parseInt(l[2],10)+1,this._partialCount=parseInt(l[2],10),e=l[1],a=Math.max(a,2),i=a):this._partialCount=0,this._partials=[]}for(let l=1;l>1&1?-1:1):u=0,this._partials[l-1]=u;break;case"custom":u=this._partials[l-1];break;default:throw new TypeError("Oscillator: invalid type: "+e)}u!==0?(s[l]=-u*Math.sin(n*l),o[l]=u*Math.cos(n*l)):(s[l]=0,o[l]=0)}return[s,o]}_inverseFFT(e,n,r){let i=0;const s=e.length;for(let o=0;o(e+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class $u extends yn{constructor(){const e=lt($u.getDefaults(),arguments,["value"]);super(e),this.name="Multiply",this.override=!1,this._mult=this.input=this.output=new jt({context:this.context,minValue:e.minValue,maxValue:e.maxValue}),this.factor=this._param=this._mult.gain,this.factor.setValueAtTime(e.value,0)}static getDefaults(){return Object.assign(yn.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}}class uy extends Ti{constructor(){const e=lt(uy.getDefaults(),arguments,["frequency","type","modulationType"]);super(e),this.name="AMOscillator",this._modulationScale=new UP({context:this.context}),this._modulationNode=new jt({context:this.context}),this._carrier=new rr({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase,type:e.type}),this.frequency=this._carrier.frequency,this.detune=this._carrier.detune,this._modulator=new rr({context:this.context,phase:e.phase,type:e.modulationType}),this.harmonicity=new $u({context:this.context,units:"positive",value:e.harmonicity}),this.frequency.chain(this.harmonicity,this._modulator.frequency),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output),Zt(this,["frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(rr.getDefaults(),{harmonicity:1,modulationType:"square"})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){this._modulator.restart(e),this._carrier.restart(e)}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return uh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this._modulationScale.dispose(),this}}class hy extends Ti{constructor(){const e=lt(hy.getDefaults(),arguments,["frequency","type","modulationType"]);super(e),this.name="FMOscillator",this._modulationNode=new jt({context:this.context,gain:0}),this._carrier=new rr({context:this.context,detune:e.detune,frequency:0,onstop:()=>this.onstop(this),phase:e.phase,type:e.type}),this.detune=this._carrier.detune,this.frequency=new yn({context:this.context,units:"frequency",value:e.frequency}),this._modulator=new rr({context:this.context,phase:e.phase,type:e.modulationType}),this.harmonicity=new $u({context:this.context,units:"positive",value:e.harmonicity}),this.modulationIndex=new $u({context:this.context,units:"positive",value:e.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output),this.detune.connect(this._modulator.detune),Zt(this,["modulationIndex","frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(rr.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:"square"})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){return this._modulator.restart(e),this._carrier.restart(e),this}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return uh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}}class gm extends Ti{constructor(){const e=lt(gm.getDefaults(),arguments,["frequency","width"]);super(e),this.name="PulseOscillator",this._widthGate=new jt({context:this.context,gain:0}),this._thresh=new ch({context:this.context,mapping:n=>n<=0?-1:1}),this.width=new yn({context:this.context,units:"audioRange",value:e.width}),this._triangle=new rr({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase,type:"triangle"}),this.frequency=this._triangle.frequency,this.detune=this._triangle.detune,this._triangle.chain(this._thresh,this.output),this.width.chain(this._widthGate,this._thresh),Zt(this,["width","frequency","detune"])}static getDefaults(){return Object.assign(Ti.getDefaults(),{detune:0,frequency:440,phase:0,type:"pulse",width:.2})}_start(e){e=this.toSeconds(e),this._triangle.start(e),this._widthGate.gain.setValueAtTime(1,e)}_stop(e){e=this.toSeconds(e),this._triangle.stop(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(0,e)}_restart(e){this._triangle.restart(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(1,e)}get phase(){return this._triangle.phase}set phase(e){this._triangle.phase=e}get type(){return"pulse"}get baseType(){return"pulse"}get partials(){return[]}get partialCount(){return 0}set carrierType(e){this._triangle.type=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return uh(this,e)})}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}}class fy extends Ti{constructor(){const e=lt(fy.getDefaults(),arguments,["frequency","type","spread"]);super(e),this.name="FatOscillator",this._oscillators=[],this.frequency=new yn({context:this.context,units:"frequency",value:e.frequency}),this.detune=new yn({context:this.context,units:"cents",value:e.detune}),this._spread=e.spread,this._type=e.type,this._phase=e.phase,this._partials=e.partials,this._partialCount=e.partialCount,this.count=e.count,Zt(this,["frequency","detune"])}static getDefaults(){return Object.assign(rr.getDefaults(),{count:3,spread:20,type:"sawtooth"})}_start(e){e=this.toSeconds(e),this._forEach(n=>n.start(e))}_stop(e){e=this.toSeconds(e),this._forEach(n=>n.stop(e))}_restart(e){this._forEach(n=>n.restart(e))}_forEach(e){for(let n=0;nn.type=e)}get spread(){return this._spread}set spread(e){if(this._spread=e,this._oscillators.length>1){const n=-e/2,r=e/(this._oscillators.length-1);this._forEach((i,s)=>i.detune.value=n+r*s)}}get count(){return this._oscillators.length}set count(e){if(ba(e,1),this._oscillators.length!==e){this._forEach(n=>n.dispose()),this._oscillators=[];for(let n=0;nthis.onstop(this):En});this.type==="custom"&&(r.partials=this._partials),this.frequency.connect(r.frequency),this.detune.connect(r.detune),r.detune.overridden=!1,r.connect(this.output),this._oscillators[n]=r}this.spread=this._spread,this.state==="started"&&this._forEach(n=>n.start())}}get phase(){return this._phase}set phase(e){this._phase=e,this._forEach((n,r)=>n.phase=this._phase+r/this.count*360)}get baseType(){return this._oscillators[0].baseType}set baseType(e){this._forEach(n=>n.baseType=e),this._type=this._oscillators[0].type}get partials(){return this._oscillators[0].partials}set partials(e){this._partials=e,this._partialCount=this._partials.length,e.length&&(this._type="custom",this._forEach(n=>n.partials=e))}get partialCount(){return this._oscillators[0].partialCount}set partialCount(e){this._partialCount=e,this._forEach(n=>n.partialCount=e),this._type=this._oscillators[0].type}asArray(){return _r(this,arguments,void 0,function*(e=1024){return uh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(e=>e.dispose()),this}}class dy extends Ti{constructor(){const e=lt(dy.getDefaults(),arguments,["frequency","modulationFrequency"]);super(e),this.name="PWMOscillator",this.sourceType="pwm",this._scale=new $u({context:this.context,value:2}),this._pulse=new gm({context:this.context,frequency:e.modulationFrequency}),this._pulse.carrierType="sine",this.modulationFrequency=this._pulse.frequency,this._modulator=new rr({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase}),this.frequency=this._modulator.frequency,this.detune=this._modulator.detune,this._modulator.chain(this._scale,this._pulse.width),this._pulse.connect(this.output),Zt(this,["modulationFrequency","frequency","detune"])}static getDefaults(){return Object.assign(Ti.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:"pwm"})}_start(e){e=this.toSeconds(e),this._modulator.start(e),this._pulse.start(e)}_stop(e){e=this.toSeconds(e),this._modulator.stop(e),this._pulse.stop(e)}_restart(e){this._modulator.restart(e),this._pulse.restart(e)}get type(){return"pwm"}get baseType(){return"pwm"}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(e){this._modulator.phase=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return uh(this,e)})}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}}const K2={am:uy,fat:fy,fm:hy,oscillator:rr,pulse:gm,pwm:dy};class j_ extends Ti{constructor(){const e=lt(j_.getDefaults(),arguments,["frequency","type"]);super(e),this.name="OmniOscillator",this.frequency=new yn({context:this.context,units:"frequency",value:e.frequency}),this.detune=new yn({context:this.context,units:"cents",value:e.detune}),Zt(this,["frequency","detune"]),this.set(e)}static getDefaults(){return Object.assign(rr.getDefaults(),hy.getDefaults(),uy.getDefaults(),fy.getDefaults(),gm.getDefaults(),dy.getDefaults())}_start(e){this._oscillator.start(e)}_stop(e){this._oscillator.stop(e)}_restart(e){return this._oscillator.restart(e),this}get type(){let e="";return["am","fm","fat"].some(n=>this._sourceType===n)&&(e=this._sourceType),e+this._oscillator.type}set type(e){e.substr(0,2)==="fm"?(this._createNewOscillator("fm"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,2)==="am"?(this._createNewOscillator("am"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,3)==="fat"?(this._createNewOscillator("fat"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(3)):e==="pwm"?(this._createNewOscillator("pwm"),this._oscillator=this._oscillator):e==="pulse"?this._createNewOscillator("pulse"):(this._createNewOscillator("oscillator"),this._oscillator=this._oscillator,this._oscillator.type=e)}get partials(){return this._oscillator.partials}set partials(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&(this._oscillator.partials=e)}get partialCount(){return this._oscillator.partialCount}set partialCount(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&(this._oscillator.partialCount=e)}set(e){return Reflect.has(e,"type")&&e.type&&(this.type=e.type),super.set(e),this}_createNewOscillator(e){if(e!==this._sourceType){this._sourceType=e;const n=K2[e],r=this.now();if(this._oscillator){const i=this._oscillator;i.stop(r),this.context.setTimeout(()=>i.dispose(),this.blockTime)}this._oscillator=new n({context:this.context}),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.connect(this.output),this._oscillator.onstop=()=>this.onstop(this),this.state==="started"&&this._oscillator.start(r)}}get phase(){return this._oscillator.phase}set phase(e){this._oscillator.phase=e}get sourceType(){return this._sourceType}set sourceType(e){let n="sine";this._oscillator.type!=="pwm"&&this._oscillator.type!=="pulse"&&(n=this._oscillator.type),e==="fm"?this.type="fm"+n:e==="am"?this.type="am"+n:e==="fat"?this.type="fat"+n:e==="oscillator"?this.type=n:e==="pulse"?this.type="pulse":e==="pwm"&&(this.type="pwm")}_getOscType(e,n){return e instanceof K2[n]}get baseType(){return this._oscillator.baseType}set baseType(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&e!=="pulse"&&e!=="pwm"&&(this._oscillator.baseType=e)}get width(){if(this._getOscType(this._oscillator,"pulse"))return this._oscillator.width}get count(){if(this._getOscType(this._oscillator,"fat"))return this._oscillator.count}set count(e){this._getOscType(this._oscillator,"fat")&&Po(e)&&(this._oscillator.count=e)}get spread(){if(this._getOscType(this._oscillator,"fat"))return this._oscillator.spread}set spread(e){this._getOscType(this._oscillator,"fat")&&Po(e)&&(this._oscillator.spread=e)}get modulationType(){if(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))return this._oscillator.modulationType}set modulationType(e){(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))&&Nl(e)&&(this._oscillator.modulationType=e)}get modulationIndex(){if(this._getOscType(this._oscillator,"fm"))return this._oscillator.modulationIndex}get harmonicity(){if(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))return this._oscillator.harmonicity}get modulationFrequency(){if(this._getOscType(this._oscillator,"pwm"))return this._oscillator.modulationFrequency}asArray(){return _r(this,arguments,void 0,function*(e=1024){return uh(this,e)})}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}}class gb extends yn{constructor(){super(lt(gb.getDefaults(),arguments,["value"])),this.override=!1,this.name="Add",this._sum=new jt({context:this.context}),this.input=this._sum,this.output=this._sum,this.addend=this._param,ju(this._constantSource,this._sum)}static getDefaults(){return Object.assign(yn.getDefaults(),{value:0})}dispose(){return super.dispose(),this._sum.dispose(),this}}class _b extends Aa{constructor(){const e=lt(_b.getDefaults(),arguments,["min","max"]);super(e),this.name="Scale",this._mult=this.input=new $u({context:this.context,value:e.max-e.min}),this._add=this.output=new gb({context:this.context,value:e.min}),this._min=e.min,this._max=e.max,this.input.connect(this.output)}static getDefaults(){return Object.assign(Aa.getDefaults(),{max:1,min:0})}get min(){return this._min}set min(e){this._min=e,this._setRange()}get max(){return this._max}set max(e){this._max=e,this._setRange()}_setRange(){this._add.value=this._min,this._mult.value=this._max-this._min}dispose(){return super.dispose(),this._add.dispose(),this._mult.dispose(),this}}class vb extends Aa{constructor(){super(lt(vb.getDefaults(),arguments)),this.name="Zero",this._gain=new jt({context:this.context}),this.output=this._gain,this.input=void 0,Do(this.context.getConstant(0),this._gain)}dispose(){return super.dispose(),DP(this.context.getConstant(0),this._gain),this}}class qu extends ft{constructor(){const e=lt(qu.getDefaults(),arguments,["frequency","min","max"]);super(e),this.name="LFO",this._stoppedValue=0,this._units="number",this.convert=!0,this._fromType=Xt.prototype._fromType,this._toType=Xt.prototype._toType,this._is=Xt.prototype._is,this._clampValue=Xt.prototype._clampValue,this._oscillator=new rr(e),this.frequency=this._oscillator.frequency,this._amplitudeGain=new jt({context:this.context,gain:e.amplitude,units:"normalRange"}),this.amplitude=this._amplitudeGain.gain,this._stoppedSignal=new yn({context:this.context,units:"audioRange",value:0}),this._zeros=new vb({context:this.context}),this._a2g=new UP({context:this.context}),this._scaler=this.output=new _b({context:this.context,max:e.max,min:e.min}),this.units=e.units,this.min=e.min,this.max=e.max,this._oscillator.chain(this._amplitudeGain,this._a2g,this._scaler),this._zeros.connect(this._a2g),this._stoppedSignal.connect(this._a2g),Zt(this,["amplitude","frequency"]),this.phase=e.phase}static getDefaults(){return Object.assign(rr.getDefaults(),{amplitude:1,frequency:"4n",max:1,min:0,type:"sine",units:"number"})}start(e){return e=this.toSeconds(e),this._stoppedSignal.setValueAtTime(0,e),this._oscillator.start(e),this}stop(e){return e=this.toSeconds(e),this._stoppedSignal.setValueAtTime(this._stoppedValue,e),this._oscillator.stop(e),this}sync(){return this._oscillator.sync(),this._oscillator.syncFrequency(),this}unsync(){return this._oscillator.unsync(),this._oscillator.unsyncFrequency(),this}_setStoppedValue(){this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get min(){return this._toType(this._scaler.min)}set min(e){e=this._fromType(e),this._scaler.min=e}get max(){return this._toType(this._scaler.max)}set max(e){e=this._fromType(e),this._scaler.max=e}get type(){return this._oscillator.type}set type(e){this._oscillator.type=e,this._setStoppedValue()}get partials(){return this._oscillator.partials}set partials(e){this._oscillator.partials=e,this._setStoppedValue()}get phase(){return this._oscillator.phase}set phase(e){this._oscillator.phase=e,this._setStoppedValue()}get units(){return this._units}set units(e){const n=this.min,r=this.max;this._units=e,this.min=n,this.max=r}get state(){return this._oscillator.state}connect(e,n,r){return(e instanceof Xt||e instanceof yn)&&(this.convert=e.convert,this.units=e.units),ay(this,e,n,r),this}dispose(){return super.dispose(),this._oscillator.dispose(),this._stoppedSignal.dispose(),this._zeros.dispose(),this._scaler.dispose(),this._a2g.dispose(),this._amplitudeGain.dispose(),this.amplitude.dispose(),this}}function FP(t,e=1/0){const n=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){ba(s,t,e),n.set(this,s)}})}}function Gl(t,e=1/0){const n=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){ba(this.toSeconds(s),t,e),n.set(this,s)}})}}class _m extends Ti{constructor(){const e=lt(_m.getDefaults(),arguments,["url","onload"]);super(e),this.name="Player",this._activeSources=new Set,this._buffer=new An({onload:this._onload.bind(this,e.onload),onerror:e.onerror,reverse:e.reverse,url:e.url}),this.autostart=e.autostart,this._loop=e.loop,this._loopStart=e.loopStart,this._loopEnd=e.loopEnd,this._playbackRate=e.playbackRate,this.fadeIn=e.fadeIn,this.fadeOut=e.fadeOut}static getDefaults(){return Object.assign(Ti.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:En,onerror:En,playbackRate:1,reverse:!1})}load(e){return _r(this,void 0,void 0,function*(){return yield this._buffer.load(e),this._onload(),this})}_onload(e=En){e(),this.autostart&&this.start()}_onSourceEnd(e){this.onstop(this),this._activeSources.delete(e),this._activeSources.size===0&&!this._synced&&this._state.getValueAtTime(this.now())==="started"&&(this._state.cancel(this.now()),this._state.setStateAtTime("stopped",this.now()))}start(e,n,r){return super.start(e,n,r),this}_start(e,n,r){this._loop?n=xa(n,this._loopStart):n=xa(n,0);const i=this.toSeconds(n),s=r;r=xa(r,Math.max(this._buffer.duration-i,0));let o=this.toSeconds(r);o=o/this._playbackRate,e=this.toSeconds(e);const a=new mm({url:this._buffer,context:this.context,fadeIn:this.fadeIn,fadeOut:this.fadeOut,loop:this._loop,loopEnd:this._loopEnd,loopStart:this._loopStart,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate}).connect(this.output);!this._loop&&!this._synced&&(this._state.cancel(e+o),this._state.setStateAtTime("stopped",e+o,{implicitEnd:!0})),this._activeSources.add(a),this._loop&&Os(s)?a.start(e,i):a.start(e,i,o-this.toSeconds(this.fadeOut))}_stop(e){const n=this.toSeconds(e);this._activeSources.forEach(r=>r.stop(n))}restart(e,n,r){return super.restart(e,n,r),this}_restart(e,n,r){var i;(i=[...this._activeSources].pop())===null||i===void 0||i.stop(e),this._start(e,n,r)}seek(e,n){const r=this.toSeconds(n);if(this._state.getValueAtTime(r)==="started"){const i=this.toSeconds(e);this._stop(r),this._start(r,i)}return this}setLoopPoints(e,n){return this.loopStart=e,this.loopEnd=n,this}get loopStart(){return this._loopStart}set loopStart(e){this._loopStart=e,this.buffer.loaded&&ba(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(n=>{n.loopStart=e})}get loopEnd(){return this._loopEnd}set loopEnd(e){this._loopEnd=e,this.buffer.loaded&&ba(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(n=>{n.loopEnd=e})}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._loop}set loop(e){if(this._loop!==e&&(this._loop=e,this._activeSources.forEach(n=>{n.loop=e}),e)){const n=this._state.getNextState("stopped",this.now());n&&this._state.cancel(n.time)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e;const n=this.now(),r=this._state.getNextState("stopped",n);r&&r.implicitEnd&&(this._state.cancel(r.time),this._activeSources.forEach(i=>i.cancelStop())),this._activeSources.forEach(i=>{i.playbackRate.setValueAtTime(e,n)})}get reverse(){return this._buffer.reverse}set reverse(e){this._buffer.reverse=e}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(e=>e.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}}Go([Gl(0)],_m.prototype,"fadeIn",void 0);Go([Gl(0)],_m.prototype,"fadeOut",void 0);class Qee extends Aa{constructor(){super(...arguments),this.name="GainToAudio",this._norm=new ch({context:this.context,mapping:e=>Math.abs(e)*2-1}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class Wl extends ft{constructor(){const e=lt(Wl.getDefaults(),arguments,["attack","decay","sustain","release"]);super(e),this.name="Envelope",this._sig=new yn({context:this.context,value:0}),this.output=this._sig,this.input=void 0,this.attack=e.attack,this.decay=e.decay,this.sustain=e.sustain,this.release=e.release,this.attackCurve=e.attackCurve,this.releaseCurve=e.releaseCurve,this.decayCurve=e.decayCurve}static getDefaults(){return Object.assign(ft.getDefaults(),{attack:.01,attackCurve:"linear",decay:.1,decayCurve:"exponential",release:1,releaseCurve:"exponential",sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(e,n){if(Nl(e))return e;{let r;for(r in y0)if(y0[r][n]===e)return r;return e}}_setCurve(e,n,r){if(Nl(r)&&Reflect.has(y0,r)){const i=y0[r];wc(i)?e!=="_decayCurve"&&(this[e]=i[n]):this[e]=i}else if(cs(r)&&e!=="_decayCurve")this[e]=r;else throw new Error("Envelope: invalid curve: "+r)}get attackCurve(){return this._getCurve(this._attackCurve,"In")}set attackCurve(e){this._setCurve("_attackCurve","In",e)}get releaseCurve(){return this._getCurve(this._releaseCurve,"Out")}set releaseCurve(e){this._setCurve("_releaseCurve","Out",e)}get decayCurve(){return this._getCurve(this._decayCurve,"Out")}set decayCurve(e){this._setCurve("_decayCurve","Out",e)}triggerAttack(e,n=1){this.log("triggerAttack",e,n),e=this.toSeconds(e);let i=this.toSeconds(this.attack);const s=this.toSeconds(this.decay),o=this.getValueAtTime(e);if(o>0){const a=1/i;i=(1-o)/a}if(i0){const r=this.toSeconds(this.release);r{let e,n;const r=[];for(e=0;e<128;e++)r[e]=Math.sin(e/127*(Math.PI/2));const i=[],s=6.4;for(e=0;e<127;e++){n=e/127;const p=Math.sin(n*(Math.PI*2)*s-Math.PI/2)+1;i[e]=p/10+n*.83}i[127]=1;const o=[],a=5;for(e=0;e<128;e++)o[e]=Math.ceil(e/127*a)/a;const l=[];for(e=0;e<128;e++)n=e/127,l[e]=.5*(1-Math.cos(Math.PI*n));const c=[];for(e=0;e<128;e++){n=e/127;const p=Math.pow(n,3)*4+.2,m=Math.cos(p*Math.PI*2*n);c[e]=Math.abs(m*(1-n))}function u(p){const m=new Array(p.length);for(let g=0;gthis._original_triggerRelease(n),this._volume=this.output=new kc({context:this.context,volume:e.volume}),this.volume=this._volume.volume,Zt(this,"volume")}static getDefaults(){return Object.assign(ft.getDefaults(),{volume:0})}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",0),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}_syncState(){let e=!1;return this._synced||(this._synced=!0,e=!0),e}_syncMethod(e,n){const r=this["_original_"+e]=this[e];this[e]=(...i)=>{const s=i[n],o=this.context.transport.schedule(a=>{i[n]=a,r.apply(this,i)},s);this._scheduledEvents.push(o)}}unsync(){return this._scheduledEvents.forEach(e=>this.context.transport.clear(e)),this._scheduledEvents=[],this._synced&&(this._synced=!1,this.triggerAttack=this._original_triggerAttack,this.triggerRelease=this._original_triggerRelease,this.context.transport.off("stop",this._syncedRelease),this.context.transport.off("pause",this._syncedRelease),this.context.transport.off("loopEnd",this._syncedRelease)),this}triggerAttackRelease(e,n,r,i){const s=this.toSeconds(r),o=this.toSeconds(n);return this.triggerAttack(e,s,i),this.triggerRelease(s+o),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}}class Xu extends Ma{constructor(){const e=lt(Xu.getDefaults(),arguments);super(e),this.portamento=e.portamento,this.onsilence=e.onsilence}static getDefaults(){return Object.assign(Ma.getDefaults(),{detune:0,onsilence:En,portamento:0})}triggerAttack(e,n,r=1){this.log("triggerAttack",e,n,r);const i=this.toSeconds(n);return this._triggerEnvelopeAttack(i,r),this.setNote(e,i),this}triggerRelease(e){this.log("triggerRelease",e);const n=this.toSeconds(e);return this._triggerEnvelopeRelease(n),this}setNote(e,n){const r=this.toSeconds(n),i=e instanceof is?e.toFrequency():e;if(this.portamento>0&&this.getLevelAtTime(r)>.05){const s=this.toSeconds(this.portamento);this.frequency.exponentialRampTo(i,s,r)}else this.frequency.setValueAtTime(i,r);return this}}Go([Gl(0)],Xu.prototype,"portamento",void 0);class py extends Wl{constructor(){super(lt(py.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="AmplitudeEnvelope",this._gainNode=new jt({context:this.context,gain:0}),this.output=this._gainNode,this.input=this._gainNode,this._sig.connect(this._gainNode.gain),this.output=this._gainNode,this.input=this._gainNode}dispose(){return super.dispose(),this._gainNode.dispose(),this}}class Oi extends Xu{constructor(){const e=lt(Oi.getDefaults(),arguments);super(e),this.name="Synth",this.oscillator=new j_(Object.assign({context:this.context,detune:e.detune,onstop:()=>this.onsilence(this)},e.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new py(Object.assign({context:this.context},e.envelope)),this.oscillator.chain(this.envelope,this.output),Zt(this,["oscillator","frequency","detune","envelope"])}static getDefaults(){return Object.assign(Xu.getDefaults(),{envelope:Object.assign(Np(Wl.getDefaults(),Object.keys(ft.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(Np(j_.getDefaults(),[...Object.keys(Ti.getDefaults()),"frequency","detune"]),{type:"triangle"})})}_triggerEnvelopeAttack(e,n){if(this.envelope.triggerAttack(e,n),this.oscillator.start(e),this.envelope.sustain===0){const r=this.toSeconds(this.envelope.attack),i=this.toSeconds(this.envelope.decay);this.oscillator.stop(e+r+i)}}_triggerEnvelopeRelease(e){this.envelope.triggerRelease(e),this.oscillator.stop(e+this.toSeconds(this.envelope.release))}getLevelAtTime(e){return e=this.toSeconds(e),this.envelope.getValueAtTime(e)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}}class $_ extends ft{constructor(){const e=lt($_.getDefaults(),arguments,["frequency","type"]);super(e),this.name="BiquadFilter",this._filter=this.context.createBiquadFilter(),this.input=this.output=this._filter,this.Q=new Xt({context:this.context,units:"number",value:e.Q,param:this._filter.Q}),this.frequency=new Xt({context:this.context,units:"frequency",value:e.frequency,param:this._filter.frequency}),this.detune=new Xt({context:this.context,units:"cents",value:e.detune,param:this._filter.detune}),this.gain=new Xt({context:this.context,units:"decibels",convert:!1,value:e.gain,param:this._filter.gain}),this.type=e.type}static getDefaults(){return Object.assign(ft.getDefaults(),{Q:1,type:"lowpass",frequency:350,detune:0,gain:0})}get type(){return this._filter.type}set type(e){Tt(["lowpass","highpass","bandpass","lowshelf","highshelf","notch","allpass","peaking"].indexOf(e)!==-1,`Invalid filter type: ${e}`),this._filter.type=e}getFrequencyResponse(e=128){const n=new Float32Array(e);for(let o=0;or.type=e)}get rolloff(){return this._rolloff}set rolloff(e){const n=Po(e)?e:parseInt(e,10),r=[-12,-24,-48,-96];let i=r.indexOf(n);Tt(i!==-1,`rolloff can only be ${r.join(", ")}`),i+=1,this._rolloff=n,this.input.disconnect(),this._filters.forEach(s=>s.disconnect()),this._filters=new Array(i);for(let s=0;s1);return this._filters.forEach(()=>{n.getFrequencyResponse(e).forEach((s,o)=>r[o]*=s)}),n.dispose(),r}dispose(){return super.dispose(),this._filters.forEach(e=>{e.dispose()}),dm(this,["detune","frequency","gain","Q"]),this.frequency.dispose(),this.Q.dispose(),this.detune.dispose(),this.gain.dispose(),this}}class vm extends Oi{constructor(){const e=lt(vm.getDefaults(),arguments);super(e),this.name="MembraneSynth",this.portamento=0,this.pitchDecay=e.pitchDecay,this.octaves=e.octaves,Zt(this,["oscillator","envelope"])}static getDefaults(){return Pu(Xu.getDefaults(),Oi.getDefaults(),{envelope:{attack:.001,attackCurve:"exponential",decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:"sine"},pitchDecay:.05})}setNote(e,n){const r=this.toSeconds(n),i=this.toFrequency(e instanceof is?e.toFrequency():e),s=i*this.octaves;return this.oscillator.frequency.setValueAtTime(s,r),this.oscillator.frequency.exponentialRampToValueAtTime(i,r+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}}Go([FP(0)],vm.prototype,"octaves",void 0);Go([Gl(0)],vm.prototype,"pitchDecay",void 0);class hf extends Ma{constructor(){const e=lt(hf.getDefaults(),arguments);super(e),this.name="NoiseSynth",this.noise=new Wf(Object.assign({context:this.context},e.noise)),this.envelope=new py(Object.assign({context:this.context},e.envelope)),this.noise.chain(this.envelope,this.output)}static getDefaults(){return Object.assign(Ma.getDefaults(),{envelope:Object.assign(Np(Wl.getDefaults(),Object.keys(ft.getDefaults())),{decay:.1,sustain:0}),noise:Object.assign(Np(Wf.getDefaults(),Object.keys(Ti.getDefaults())),{type:"white"})})}triggerAttack(e,n=1){return e=this.toSeconds(e),this.envelope.triggerAttack(e,n),this.noise.start(e),this.envelope.sustain===0&&this.noise.stop(e+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay)),this}triggerRelease(e){return e=this.toSeconds(e),this.envelope.triggerRelease(e),this.noise.stop(e+this.toSeconds(this.envelope.release)),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",0),this._syncMethod("triggerRelease",0)),this}triggerAttackRelease(e,n,r=1){return n=this.toSeconds(n),e=this.toSeconds(e),this.triggerAttack(n,r),this.triggerRelease(n+e),this}dispose(){return super.dispose(),this.noise.dispose(),this.envelope.dispose(),this}}const BP=new Set;function yb(t){BP.add(t)}function zP(t,e){const n=`registerProcessor("${t}", ${e})`;BP.add(n)}const ete=` + /** + * The base AudioWorkletProcessor for use in Tone.js. Works with the {@link ToneAudioWorklet}. + */ + class ToneAudioWorkletProcessor extends AudioWorkletProcessor { + + constructor(options) { + + super(options); + /** + * If the processor was disposed or not. Keep alive until it's disposed. + */ + this.disposed = false; + /** + * The number of samples in the processing block + */ + this.blockSize = 128; + /** + * the sample rate + */ + this.sampleRate = sampleRate; + + this.port.onmessage = (event) => { + // when it receives a dispose + if (event.data === "dispose") { + this.disposed = true; + } + }; + } + } +`;yb(ete);const tte=` + /** + * Abstract class for a single input/output processor. + * has a 'generate' function which processes one sample at a time + */ + class SingleIOProcessor extends ToneAudioWorkletProcessor { + + constructor(options) { + super(Object.assign(options, { + numberOfInputs: 1, + numberOfOutputs: 1 + })); + /** + * Holds the name of the parameter and a single value of that + * parameter at the current sample + * @type { [name: string]: number } + */ + this.params = {} + } + + /** + * Generate an output sample from the input sample and parameters + * @abstract + * @param input number + * @param channel number + * @param parameters { [name: string]: number } + * @returns number + */ + generate(){} + + /** + * Update the private params object with the + * values of the parameters at the given index + * @param parameters { [name: string]: Float32Array }, + * @param index number + */ + updateParams(parameters, index) { + for (const paramName in parameters) { + const param = parameters[paramName]; + if (param.length > 1) { + this.params[paramName] = parameters[paramName][index]; + } else { + this.params[paramName] = parameters[paramName][0]; + } + } + } + + /** + * Process a single frame of the audio + * @param inputs Float32Array[][] + * @param outputs Float32Array[][] + */ + process(inputs, outputs, parameters) { + const input = inputs[0]; + const output = outputs[0]; + // get the parameter values + const channelCount = Math.max(input && input.length || 0, output.length); + for (let sample = 0; sample < this.blockSize; sample++) { + this.updateParams(parameters, sample); + for (let channel = 0; channel < channelCount; channel++) { + const inputSample = input && input.length ? input[channel][sample] : 0; + output[channel][sample] = this.generate(inputSample, channel, this.params); + } + } + return !this.disposed; + } + }; +`;yb(tte);const nte=` + /** + * A multichannel buffer for use within an AudioWorkletProcessor as a delay line + */ + class DelayLine { + + constructor(size, channels) { + this.buffer = []; + this.writeHead = [] + this.size = size; + + // create the empty channels + for (let i = 0; i < channels; i++) { + this.buffer[i] = new Float32Array(this.size); + this.writeHead[i] = 0; + } + } + + /** + * Push a value onto the end + * @param channel number + * @param value number + */ + push(channel, value) { + this.writeHead[channel] += 1; + if (this.writeHead[channel] > this.size) { + this.writeHead[channel] = 0; + } + this.buffer[channel][this.writeHead[channel]] = value; + } + + /** + * Get the recorded value of the channel given the delay + * @param channel number + * @param delay number delay samples + */ + get(channel, delay) { + let readHead = this.writeHead[channel] - Math.floor(delay); + if (readHead < 0) { + readHead += this.size; + } + return this.buffer[channel][readHead]; + } + } +`;yb(nte);const rte="feedback-comb-filter",ite=` + class FeedbackCombFilterWorklet extends SingleIOProcessor { + + constructor(options) { + super(options); + this.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2); + } + + static get parameterDescriptors() { + return [{ + name: "delayTime", + defaultValue: 0.1, + minValue: 0, + maxValue: 1, + automationRate: "k-rate" + }, { + name: "feedback", + defaultValue: 0.5, + minValue: 0, + maxValue: 0.9999, + automationRate: "k-rate" + }]; + } + + generate(input, channel, parameters) { + const delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate); + this.delayLine.push(channel, input + delayedSample * parameters.feedback); + return delayedSample; + } + } +`;zP(rte,ite);class q_ extends Ma{constructor(){const e=lt(q_.getDefaults(),arguments,["voice","options"]);super(e),this.name="PolySynth",this._availableVoices=[],this._activeVoices=[],this._voices=[],this._gcTimeout=-1,this._averageActiveVoices=0,this._syncedRelease=i=>this.releaseAll(i),Tt(!Po(e.voice),"DEPRECATED: The polyphony count is no longer the first argument.");const n=e.voice.getDefaults();this.options=Object.assign(n,e.options),this.voice=e.voice,this.maxPolyphony=e.maxPolyphony,this._dummyVoice=this._getNextAvailableVoice();const r=this._voices.indexOf(this._dummyVoice);this._voices.splice(r,1),this._gcTimeout=this.context.setInterval(this._collectGarbage.bind(this),1)}static getDefaults(){return Object.assign(Ma.getDefaults(),{maxPolyphony:32,options:{},voice:Oi})}get activeVoices(){return this._activeVoices.length}_makeVoiceAvailable(e){this._availableVoices.push(e);const n=this._activeVoices.findIndex(r=>r.voice===e);this._activeVoices.splice(n,1)}_getNextAvailableVoice(){if(this._availableVoices.length)return this._availableVoices.shift();if(this._voices.lengthMath.ceil(this._averageActiveVoices+1)){const e=this._availableVoices.shift(),n=this._voices.indexOf(e);this._voices.splice(n,1),this.context.isOffline||e.dispose()}}_triggerAttack(e,n,r){e.forEach(i=>{const s=new W_(this.context,i).toMidi(),o=this._getNextAvailableVoice();o&&(o.triggerAttack(i,n,r),this._activeVoices.push({midi:s,voice:o,released:!1}),this.log("triggerAttack",i,n))})}_triggerRelease(e,n){e.forEach(r=>{const i=new W_(this.context,r).toMidi(),s=this._activeVoices.find(({midi:o,released:a})=>o===i&&!a);s&&(s.voice.triggerRelease(n),s.released=!0,this.log("triggerRelease",r,n))})}_scheduleEvent(e,n,r,i){Tt(!this.disposed,"Synth was already disposed"),r<=this.now()?e==="attack"?this._triggerAttack(n,r,i):this._triggerRelease(n,r):this.context.setTimeout(()=>{this.disposed||this._scheduleEvent(e,n,r,i)},r-this.now())}triggerAttack(e,n,r){Array.isArray(e)||(e=[e]);const i=this.toSeconds(n);return this._scheduleEvent("attack",e,i,r),this}triggerRelease(e,n){Array.isArray(e)||(e=[e]);const r=this.toSeconds(n);return this._scheduleEvent("release",e,r),this}triggerAttackRelease(e,n,r,i){const s=this.toSeconds(r);if(this.triggerAttack(e,s,i),cs(n)){Tt(cs(e),"If the duration is an array, the notes must also be an array"),e=e;for(let o=0;o0,"The duration must be greater than 0"),this.triggerRelease(e[o],s+l)}}else{const o=this.toSeconds(n);Tt(o>0,"The duration must be greater than 0"),this.triggerRelease(e,s+o)}return this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}set(e){const n=Np(e,["onsilence","context"]);return this.options=Pu(this.options,n),this._voices.forEach(r=>r.set(n)),this._dummyVoice.set(n),this}get(){return this._dummyVoice.get()}releaseAll(e){const n=this.toSeconds(e);return this._activeVoices.forEach(({voice:r})=>{r.triggerRelease(n)}),this}dispose(){return super.dispose(),this._dummyVoice.dispose(),this._voices.forEach(e=>e.dispose()),this._activeVoices=[],this._availableVoices=[],this.context.clearInterval(this._gcTimeout),this}}class my extends Ma{constructor(){const e=lt(my.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");super(e),this.name="Sampler",this._activeSources=new Map;const n={};Object.keys(e.urls).forEach(r=>{const i=parseInt(r,10);if(Tt(v0(r)||Po(i)&&isFinite(i),`url key is neither a note or midi pitch: ${r}`),v0(r)){const s=new is(this.context,r).toMidi();n[s]=e.urls[r]}else Po(i)&&isFinite(i)&&(n[i]=e.urls[i])}),this._buffers=new fb({urls:n,onload:e.onload,baseUrl:e.baseUrl,onerror:e.onerror}),this.attack=e.attack,this.release=e.release,this.curve=e.curve,this._buffers.loaded&&Promise.resolve().then(e.onload)}static getDefaults(){return Object.assign(Ma.getDefaults(),{attack:0,baseUrl:"",curve:"exponential",onload:En,onerror:En,release:.1,urls:{}})}_findClosest(e){let r=0;for(;r<96;){if(this._buffers.has(e+r))return-r;if(this._buffers.has(e-r))return r;r++}throw new Error(`No available buffers for note: ${e}`)}triggerAttack(e,n,r=1){return this.log("triggerAttack",e,n,r),Array.isArray(e)||(e=[e]),e.forEach(i=>{const s=LP(new is(this.context,i).toFrequency()),o=Math.round(s),a=s-o,l=this._findClosest(o),c=o-l,u=this._buffers.get(c),h=OP(l+a),p=new mm({url:u,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:h}).connect(this.output);p.start(n,0,u.duration/h,r),cs(this._activeSources.get(o))||this._activeSources.set(o,[]),this._activeSources.get(o).push(p),p.onended=()=>{if(this._activeSources&&this._activeSources.has(o)){const m=this._activeSources.get(o),g=m.indexOf(p);g!==-1&&m.splice(g,1)}}}),this}triggerRelease(e,n){return this.log("triggerRelease",e,n),Array.isArray(e)||(e=[e]),e.forEach(r=>{const i=new is(this.context,r).toMidi();if(this._activeSources.has(i)&&this._activeSources.get(i).length){const s=this._activeSources.get(i);n=this.toSeconds(n),s.forEach(o=>{o.stop(n)}),this._activeSources.set(i,[])}}),this}releaseAll(e){const n=this.toSeconds(e);return this._activeSources.forEach(r=>{for(;r.length;)r.shift().stop(n)}),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1)),this}triggerAttackRelease(e,n,r,i=1){const s=this.toSeconds(r);return this.triggerAttack(e,s,i),cs(n)?(Tt(cs(e),"notes must be an array when duration is array"),e.forEach((o,a)=>{const l=n[Math.min(a,n.length-1)];this.triggerRelease(o,s+this.toSeconds(l))})):this.triggerRelease(e,s+this.toSeconds(n)),this}add(e,n,r){if(Tt(v0(e)||isFinite(e),`note must be a pitch or midi: ${e}`),v0(e)){const i=new is(this.context,e).toMidi();this._buffers.add(i,n,r)}else this._buffers.add(e,n,r);return this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(e=>{e.forEach(n=>n.dispose())}),this._activeSources.clear(),this}}Go([Gl(0)],my.prototype,"attack",void 0);Go([Gl(0)],my.prototype,"release",void 0);class ff extends Si{constructor(){const e=lt(ff.getDefaults(),arguments,["callback","value"]);super(e),this.name="ToneEvent",this._state=new pm("stopped"),this._startOffset=0,this._loop=e.loop,this.callback=e.callback,this.value=e.value,this._loopStart=this.toTicks(e.loopStart),this._loopEnd=this.toTicks(e.loopEnd),this._playbackRate=e.playbackRate,this._probability=e.probability,this._humanize=e.humanize,this.mute=e.mute,this._playbackRate=e.playbackRate,this._state.increasing=!0,this._rescheduleEvents()}static getDefaults(){return Object.assign(Si.getDefaults(),{callback:En,humanize:!1,loop:!1,loopEnd:"1m",loopStart:0,mute:!1,playbackRate:1,probability:1,value:null})}_rescheduleEvents(e=-1){this._state.forEachFrom(e,n=>{let r;if(n.state==="started"){n.id!==-1&&this.context.transport.clear(n.id);const i=n.time+Math.round(this.startOffset/this._playbackRate);if(this._loop===!0||Po(this._loop)&&this._loop>1){r=1/0,Po(this._loop)&&(r=this._loop*this._getLoopDuration());const s=this._state.getAfter(i);s!==null&&(r=Math.min(r,s.time-i)),r!==1/0&&(r=new Pr(this.context,r));const o=new Pr(this.context,this._getLoopDuration());n.id=this.context.transport.scheduleRepeat(this._tick.bind(this),o,new Pr(this.context,i),r)}else n.id=this.context.transport.schedule(this._tick.bind(this),new Pr(this.context,i))}})}get state(){return this._state.getValueAtTime(this.context.transport.ticks)}get startOffset(){return this._startOffset}set startOffset(e){this._startOffset=e}get probability(){return this._probability}set probability(e){this._probability=e}get humanize(){return this._humanize}set humanize(e){this._humanize=e}start(e){const n=this.toTicks(e);return this._state.getValueAtTime(n)==="stopped"&&(this._state.add({id:-1,state:"started",time:n}),this._rescheduleEvents(n)),this}stop(e){this.cancel(e);const n=this.toTicks(e);if(this._state.getValueAtTime(n)==="started"){this._state.setStateAtTime("stopped",n,{id:-1});const r=this._state.getBefore(n);let i=n;r!==null&&(i=r.time),this._rescheduleEvents(i)}return this}cancel(e){e=xa(e,-1/0);const n=this.toTicks(e);return this._state.forEachFrom(n,r=>{this.context.transport.clear(r.id)}),this._state.cancel(n),this}_tick(e){const n=this.context.transport.getTicksAtTime(e);if(!this.mute&&this._state.getValueAtTime(n)==="started"){if(this.probability<1&&Math.random()>this.probability)return;if(this.humanize){let r=.02;bP(this.humanize)||(r=this.toSeconds(this.humanize)),e+=(Math.random()*2-1)*r}this.callback(e,this.value)}}_getLoopDuration(){return(this._loopEnd-this._loopStart)/this._playbackRate}get loop(){return this._loop}set loop(e){this._loop=e,this._rescheduleEvents()}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._rescheduleEvents()}get loopEnd(){return new Pr(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._rescheduleEvents()}get loopStart(){return new Pr(this.context,this._loopStart).toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e),this._loop&&this._rescheduleEvents()}get progress(){if(this._loop){const e=this.context.transport.ticks,n=this._state.get(e);if(n!==null&&n.state==="started"){const r=this._getLoopDuration();return(e-n.time)%r/r}else return 0}else return 0}dispose(){return super.dispose(),this.cancel(),this._state.dispose(),this}}class X_ extends ff{constructor(){const e=lt(X_.getDefaults(),arguments,["callback","events"]);super(e),this.name="Part",this._state=new pm("stopped"),this._events=new Set,this._state.increasing=!0,e.events.forEach(n=>{cs(n)?this.add(n[0],n[1]):this.add(n)})}static getDefaults(){return Object.assign(ff.getDefaults(),{events:[]})}start(e,n){const r=this.toTicks(e);if(this._state.getValueAtTime(r)!=="started"){n=xa(n,this._loop?this._loopStart:0),this._loop?n=xa(n,this._loopStart):n=xa(n,0);const i=this.toTicks(n);this._state.add({id:-1,offset:i,state:"started",time:r}),this._forEach(s=>{this._startNote(s,r,i)})}return this}_startNote(e,n,r){n-=r,this._loop?e.startOffset>=this._loopStart&&e.startOffset=r&&(e.loop=!1,e.start(new Pr(this.context,n))):e.startOffset>=r&&e.start(new Pr(this.context,n))}get startOffset(){return this._startOffset}set startOffset(e){this._startOffset=e,this._forEach(n=>{n.startOffset+=this._startOffset})}stop(e){const n=this.toTicks(e);return this._state.cancel(n),this._state.setStateAtTime("stopped",n),this._forEach(r=>{r.stop(e)}),this}at(e,n){const r=new Sf(this.context,e).toTicks(),i=new Pr(this.context,1).toSeconds(),s=this._events.values();let o=s.next();for(;!o.done;){const a=o.value;if(Math.abs(r-a.startOffset){n.state==="started"?this._startNote(e,n.time,n.offset):e.stop(new Pr(this.context,n.time))})}remove(e,n){return wc(e)&&e.hasOwnProperty("time")&&(n=e,e=n.time),e=this.toTicks(e),this._events.forEach(r=>{r.startOffset===e&&(Os(n)||Wt(n)&&r.value===n)&&(this._events.delete(r),r.dispose())}),this}clear(){return this._forEach(e=>e.dispose()),this._events.clear(),this}cancel(e){return this._forEach(n=>n.cancel(e)),this._state.cancel(this.toTicks(e)),this}_forEach(e){return this._events&&this._events.forEach(n=>{n instanceof X_?n._forEach(e):e(n)}),this}_setAll(e,n){this._forEach(r=>{r[e]=n})}_tick(e,n){this.mute||this.callback(e,n)}_testLoopBoundries(e){this._loop&&(e.startOffset=this._loopEnd)?e.cancel(0):e.state==="stopped"&&this._restartEvent(e)}get probability(){return this._probability}set probability(e){this._probability=e,this._setAll("probability",e)}get humanize(){return this._humanize}set humanize(e){this._humanize=e,this._setAll("humanize",e)}get loop(){return this._loop}set loop(e){this._loop=e,this._forEach(n=>{n.loopStart=this.loopStart,n.loopEnd=this.loopEnd,n.loop=e,this._testLoopBoundries(n)})}get loopEnd(){return new Pr(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._forEach(n=>{n.loopEnd=e,this._testLoopBoundries(n)})}get loopStart(){return new Pr(this.context,this._loopStart).toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e),this._loop&&this._forEach(n=>{n.loopStart=this.loopStart,this._testLoopBoundries(n)})}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._setAll("playbackRate",e)}get length(){return this._events.size}dispose(){return super.dispose(),this.clear(),this}}class gy extends ft{constructor(){const e=lt(gy.getDefaults(),arguments,["fade"]);super(e),this.name="CrossFade",this._panner=this.context.createStereoPanner(),this._split=this.context.createChannelSplitter(2),this._g2a=new Qee({context:this.context}),this.a=new jt({context:this.context,gain:0}),this.b=new jt({context:this.context,gain:0}),this.output=new jt({context:this.context}),this._internalChannels=[this.a,this.b],this.fade=new yn({context:this.context,units:"normalRange",value:e.fade}),Zt(this,"fade"),this.context.getConstant(1).connect(this._panner),this._panner.connect(this._split),this._panner.channelCount=1,this._panner.channelCountMode="explicit",Do(this._split,this.a.gain,0),Do(this._split,this.b.gain,1),this.fade.chain(this._g2a,this._panner.pan),this.a.connect(this.output),this.b.connect(this.output)}static getDefaults(){return Object.assign(ft.getDefaults(),{fade:.5})}dispose(){return super.dispose(),this.a.dispose(),this.b.dispose(),this.output.dispose(),this.fade.dispose(),this._g2a.dispose(),this._panner.disconnect(),this._split.disconnect(),this}}let Oc=class extends ft{constructor(e){super(e),this.name="Effect",this._dryWet=new gy({context:this.context}),this.wet=this._dryWet.fade,this.effectSend=new jt({context:this.context}),this.effectReturn=new jt({context:this.context}),this.input=new jt({context:this.context}),this.output=this._dryWet,this.input.fan(this._dryWet.a,this.effectSend),this.effectReturn.connect(this._dryWet.b),this.wet.setValueAtTime(e.wet,0),this._internalChannels=[this.effectReturn,this.effectSend],Zt(this,"wet")}static getDefaults(){return Object.assign(ft.getDefaults(),{wet:1})}connectEffect(e){return this._internalChannels.push(e),this.effectSend.chain(e,this.effectReturn),this}dispose(){return super.dispose(),this._dryWet.dispose(),this.effectSend.dispose(),this.effectReturn.dispose(),this.wet.dispose(),this}};class xb extends ft{constructor(){const e=lt(xb.getDefaults(),arguments,["pan"]);super(e),this.name="Panner",this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner,this.pan=new Xt({context:this.context,param:this._panner.pan,value:e.pan,minValue:-1,maxValue:1}),this._panner.channelCount=e.channelCount,this._panner.channelCountMode="explicit",Zt(this,"pan")}static getDefaults(){return Object.assign(ft.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}}const ste="bit-crusher",ote=` + class BitCrusherWorklet extends SingleIOProcessor { + + static get parameterDescriptors() { + return [{ + name: "bits", + defaultValue: 12, + minValue: 1, + maxValue: 16, + automationRate: 'k-rate' + }]; + } + + generate(input, _channel, parameters) { + const step = Math.pow(0.5, parameters.bits - 1); + const val = step * Math.floor(input / step + 0.5); + return val; + } + } +`;zP(ste,ote);class _y extends ft{constructor(){const e=lt(_y.getDefaults(),arguments,["channels"]);super(e),this.name="Split",this._splitter=this.input=this.output=this.context.createChannelSplitter(e.channels),this._internalChannels=[this._splitter]}static getDefaults(){return Object.assign(ft.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._splitter.disconnect(),this}}class ym extends ft{constructor(){const e=lt(ym.getDefaults(),arguments,["channels"]);super(e),this.name="Merge",this._merger=this.output=this.input=this.context.createChannelMerger(e.channels)}static getDefaults(){return Object.assign(ft.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._merger.disconnect(),this}}class K_ extends ft{constructor(e){super(e),this.name="StereoEffect",this.input=new jt({context:this.context}),this.input.channelCount=2,this.input.channelCountMode="explicit",this._dryWet=this.output=new gy({context:this.context,fade:e.wet}),this.wet=this._dryWet.fade,this._split=new _y({context:this.context,channels:2}),this._merge=new ym({context:this.context,channels:2}),this.input.connect(this._split),this.input.connect(this._dryWet.a),this._merge.connect(this._dryWet.b),Zt(this,["wet"])}connectEffectLeft(...e){this._split.connect(e[0],0,0),ju(...e),Do(e[e.length-1],this._merge,0,0)}connectEffectRight(...e){this._split.connect(e[0],1,0),ju(...e),Do(e[e.length-1],this._merge,0,1)}static getDefaults(){return Object.assign(ft.getDefaults(),{wet:1})}dispose(){return super.dispose(),this._dryWet.dispose(),this._split.dispose(),this._merge.dispose(),this}}class Y2 extends K_{constructor(e){super(e),this.feedback=new yn({context:this.context,value:e.feedback,units:"normalRange"}),this._feedbackL=new jt({context:this.context}),this._feedbackR=new jt({context:this.context}),this._feedbackSplit=new _y({context:this.context,channels:2}),this._feedbackMerge=new ym({context:this.context,channels:2}),this._merge.connect(this._feedbackSplit),this._feedbackMerge.connect(this._split),this._feedbackSplit.connect(this._feedbackL,0,0),this._feedbackL.connect(this._feedbackMerge,0,0),this._feedbackSplit.connect(this._feedbackR,1,0),this._feedbackR.connect(this._feedbackMerge,0,1),this.feedback.fan(this._feedbackL.gain,this._feedbackR.gain),Zt(this,["feedback"])}static getDefaults(){return Object.assign(K_.getDefaults(),{feedback:.5})}dispose(){return super.dispose(),this.feedback.dispose(),this._feedbackL.dispose(),this._feedbackR.dispose(),this._feedbackSplit.dispose(),this._feedbackMerge.dispose(),this}}class Sb extends Y2{constructor(){const e=lt(Sb.getDefaults(),arguments,["frequency","delayTime","depth"]);super(e),this.name="Chorus",this._depth=e.depth,this._delayTime=e.delayTime/1e3,this._lfoL=new qu({context:this.context,frequency:e.frequency,min:0,max:1}),this._lfoR=new qu({context:this.context,frequency:e.frequency,min:0,max:1,phase:180}),this._delayNodeL=new Gf({context:this.context}),this._delayNodeR=new Gf({context:this.context}),this.frequency=this._lfoL.frequency,Zt(this,["frequency"]),this._lfoL.frequency.connect(this._lfoR.frequency),this.connectEffectLeft(this._delayNodeL),this.connectEffectRight(this._delayNodeR),this._lfoL.connect(this._delayNodeL.delayTime),this._lfoR.connect(this._delayNodeR.delayTime),this.depth=this._depth,this.type=e.type,this.spread=e.spread}static getDefaults(){return Object.assign(Y2.getDefaults(),{frequency:1.5,delayTime:3.5,depth:.7,type:"sine",spread:180,feedback:0,wet:.5})}get depth(){return this._depth}set depth(e){this._depth=e;const n=this._delayTime*e;this._lfoL.min=Math.max(this._delayTime-n,0),this._lfoL.max=this._delayTime+n,this._lfoR.min=Math.max(this._delayTime-n,0),this._lfoR.max=this._delayTime+n}get delayTime(){return this._delayTime*1e3}set delayTime(e){this._delayTime=e/1e3,this.depth=this._depth}get type(){return this._lfoL.type}set type(e){this._lfoL.type=e,this._lfoR.type=e}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(e){this._lfoL.phase=90-e/2,this._lfoR.phase=e/2+90}start(e){return this._lfoL.start(e),this._lfoR.start(e),this}stop(e){return this._lfoL.stop(e),this._lfoR.stop(e),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._delayNodeL.dispose(),this._delayNodeR.dispose(),this.frequency.dispose(),this}}class kp extends Oc{constructor(){const e=lt(kp.getDefaults(),arguments,["distortion"]);super(e),this.name="Distortion",this._shaper=new ch({context:this.context,length:4096}),this._distortion=e.distortion,this.connectEffect(this._shaper),this.distortion=e.distortion,this.oversample=e.oversample}static getDefaults(){return Object.assign(Oc.getDefaults(),{distortion:.4,oversample:"none"})}get distortion(){return this._distortion}set distortion(e){this._distortion=e;const n=e*100,r=Math.PI/180;this._shaper.setMap(i=>Math.abs(i)<.001?0:(3+n)*i*20*r/(Math.PI+n*Math.abs(i)))}get oversample(){return this._shaper.oversample}set oversample(e){this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.dispose(),this}}class Z2 extends Oc{constructor(e){super(e),this.name="FeedbackEffect",this._feedbackGain=new jt({context:this.context,gain:e.feedback,units:"normalRange"}),this.feedback=this._feedbackGain.gain,Zt(this,"feedback"),this.effectReturn.chain(this._feedbackGain,this.effectSend)}static getDefaults(){return Object.assign(Oc.getDefaults(),{feedback:.125})}dispose(){return super.dispose(),this._feedbackGain.dispose(),this.feedback.dispose(),this}}class vy extends Z2{constructor(){const e=lt(vy.getDefaults(),arguments,["delayTime","feedback"]);super(e),this.name="FeedbackDelay",this._delayNode=new Gf({context:this.context,delayTime:e.delayTime,maxDelay:e.maxDelay}),this.delayTime=this._delayNode.delayTime,this.connectEffect(this._delayNode),Zt(this,"delayTime")}static getDefaults(){return Object.assign(Z2.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._delayNode.dispose(),this.delayTime.dispose(),this}}class Eb extends K_{constructor(){const e=lt(Eb.getDefaults(),arguments,["frequency","octaves","baseFrequency"]);super(e),this.name="Phaser",this._lfoL=new qu({context:this.context,frequency:e.frequency,min:0,max:1}),this._lfoR=new qu({context:this.context,frequency:e.frequency,min:0,max:1,phase:180}),this._baseFrequency=this.toFrequency(e.baseFrequency),this._octaves=e.octaves,this.Q=new yn({context:this.context,value:e.Q,units:"positive"}),this._filtersL=this._makeFilters(e.stages,this._lfoL),this._filtersR=this._makeFilters(e.stages,this._lfoR),this.frequency=this._lfoL.frequency,this.frequency.value=e.frequency,this.connectEffectLeft(...this._filtersL),this.connectEffectRight(...this._filtersR),this._lfoL.frequency.connect(this._lfoR.frequency),this.baseFrequency=e.baseFrequency,this.octaves=e.octaves,this._lfoL.start(),this._lfoR.start(),Zt(this,["frequency","Q"])}static getDefaults(){return Object.assign(K_.getDefaults(),{frequency:.5,octaves:3,stages:10,Q:10,baseFrequency:350})}_makeFilters(e,n){const r=[];for(let i=0;ie.disconnect()),this._filtersR.forEach(e=>e.disconnect()),this.frequency.dispose(),this}}class wb extends Oc{constructor(){const e=lt(wb.getDefaults(),arguments,["decay"]);super(e),this.name="Reverb",this._convolver=this.context.createConvolver(),this.ready=Promise.resolve(),this._decay=e.decay,this._preDelay=e.preDelay,this.generate(),this.connectEffect(this._convolver)}static getDefaults(){return Object.assign(Oc.getDefaults(),{decay:1.5,preDelay:.01})}get decay(){return this._decay}set decay(e){e=this.toSeconds(e),ba(e,.001),this._decay=e,this.generate()}get preDelay(){return this._preDelay}set preDelay(e){e=this.toSeconds(e),ba(e,0),this._preDelay=e,this.generate()}generate(){return _r(this,void 0,void 0,function*(){const e=this.ready,n=new sy(2,this._decay+this._preDelay,this.context.sampleRate),r=new Wf({context:n}),i=new Wf({context:n}),s=new ym({context:n});r.connect(s,0,0),i.connect(s,0,1);const o=new jt({context:n}).toDestination();s.connect(o),r.start(0),i.start(0),o.gain.setValueAtTime(0,0),o.gain.setValueAtTime(1,this._preDelay),o.gain.exponentialApproachValueAtTime(0,this._preDelay,this.decay);const a=n.render();return this.ready=a.then(En),yield e,this._convolver.buffer=(yield a).get(),this})}dispose(){return super.dispose(),this._convolver.disconnect(),this}}class Tb extends Oc{constructor(){const e=lt(Tb.getDefaults(),arguments,["frequency","depth"]);super(e),this.name="Vibrato",this._delayNode=new Gf({context:this.context,delayTime:0,maxDelay:e.maxDelay}),this._lfo=new qu({context:this.context,type:e.type,min:0,max:e.maxDelay,frequency:e.frequency,phase:-90}).start().connect(this._delayNode.delayTime),this.frequency=this._lfo.frequency,this.depth=this._lfo.amplitude,this.depth.value=e.depth,Zt(this,["frequency","depth"]),this.effectSend.chain(this._delayNode,this.effectReturn)}static getDefaults(){return Object.assign(Oc.getDefaults(),{maxDelay:.005,frequency:5,depth:.1,type:"sine"})}get type(){return this._lfo.type}set type(e){this._lfo.type=e}dispose(){return super.dispose(),this._delayNode.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class br extends ft{constructor(){const e=lt(br.getDefaults(),arguments,["solo"]);super(e),this.name="Solo",this.input=this.output=new jt({context:this.context}),br._allSolos.has(this.context)||br._allSolos.set(this.context,new Set),br._allSolos.get(this.context).add(this),this.solo=e.solo}static getDefaults(){return Object.assign(ft.getDefaults(),{solo:!1})}get solo(){return this._isSoloed()}set solo(e){e?this._addSolo():this._removeSolo(),br._allSolos.get(this.context).forEach(n=>n._updateSolo())}get muted(){return this.input.gain.value===0}_addSolo(){br._soloed.has(this.context)||br._soloed.set(this.context,new Set),br._soloed.get(this.context).add(this)}_removeSolo(){br._soloed.has(this.context)&&br._soloed.get(this.context).delete(this)}_isSoloed(){return br._soloed.has(this.context)&&br._soloed.get(this.context).has(this)}_noSolos(){return!br._soloed.has(this.context)||br._soloed.has(this.context)&&br._soloed.get(this.context).size===0}_updateSolo(){this._isSoloed()?this.input.gain.value=1:this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),br._allSolos.get(this.context).delete(this),this._removeSolo(),this}}br._allSolos=new Map;br._soloed=new Map;class bb extends ft{constructor(){const e=lt(bb.getDefaults(),arguments,["pan","volume"]);super(e),this.name="PanVol",this._panner=this.input=new xb({context:this.context,pan:e.pan,channelCount:e.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new kc({context:this.context,volume:e.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=e.mute,Zt(this,["pan","volume"])}static getDefaults(){return Object.assign(ft.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}}class df extends ft{constructor(){const e=lt(df.getDefaults(),arguments,["volume","pan"]);super(e),this.name="Channel",this._solo=this.input=new br({solo:e.solo,context:this.context}),this._panVol=this.output=new bb({context:this.context,pan:e.pan,volume:e.volume,mute:e.mute,channelCount:e.channelCount}),this.pan=this._panVol.pan,this.volume=this._panVol.volume,this._solo.connect(this._panVol),Zt(this,["pan","volume"])}static getDefaults(){return Object.assign(ft.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(e){this._solo.solo=e}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(e){this._panVol.mute=e}_getBus(e){return df.buses.has(e)||df.buses.set(e,new jt({context:this.context})),df.buses.get(e)}send(e,n=0){const r=this._getBus(e),i=new jt({context:this.context,units:"decibels",gain:n});return this.connect(i),i.connect(r),i}receive(e){return this._getBus(e).connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}}df.buses=new Map;class Ab extends ft{constructor(){const e=lt(Ab.getDefaults(),arguments,["lowFrequency","highFrequency"]);super(e),this.name="MultibandSplit",this.input=new jt({context:this.context}),this.output=void 0,this.low=new Ks({context:this.context,frequency:0,type:"lowpass"}),this._lowMidFilter=new Ks({context:this.context,frequency:0,type:"highpass"}),this.mid=new Ks({context:this.context,frequency:0,type:"lowpass"}),this.high=new Ks({context:this.context,frequency:0,type:"highpass"}),this._internalChannels=[this.low,this.mid,this.high],this.lowFrequency=new yn({context:this.context,units:"frequency",value:e.lowFrequency}),this.highFrequency=new yn({context:this.context,units:"frequency",value:e.highFrequency}),this.Q=new yn({context:this.context,units:"positive",value:e.Q}),this.input.fan(this.low,this.high),this.input.chain(this._lowMidFilter,this.mid),this.lowFrequency.fan(this.low.frequency,this._lowMidFilter.frequency),this.highFrequency.fan(this.mid.frequency,this.high.frequency),this.Q.connect(this.low.Q),this.Q.connect(this._lowMidFilter.Q),this.Q.connect(this.mid.Q),this.Q.connect(this.high.Q),Zt(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(ft.getDefaults(),{Q:1,highFrequency:2500,lowFrequency:400})}dispose(){return super.dispose(),dm(this,["high","mid","low","highFrequency","lowFrequency"]),this.low.dispose(),this._lowMidFilter.dispose(),this.mid.dispose(),this.high.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this.Q.dispose(),this}}class Mb extends ft{constructor(){const e=lt(Mb.getDefaults(),arguments,["threshold","ratio"]);super(e),this.name="Compressor",this._compressor=this.context.createDynamicsCompressor(),this.input=this._compressor,this.output=this._compressor,this.threshold=new Xt({minValue:this._compressor.threshold.minValue,maxValue:this._compressor.threshold.maxValue,context:this.context,convert:!1,param:this._compressor.threshold,units:"decibels",value:e.threshold}),this.attack=new Xt({minValue:this._compressor.attack.minValue,maxValue:this._compressor.attack.maxValue,context:this.context,param:this._compressor.attack,units:"time",value:e.attack}),this.release=new Xt({minValue:this._compressor.release.minValue,maxValue:this._compressor.release.maxValue,context:this.context,param:this._compressor.release,units:"time",value:e.release}),this.knee=new Xt({minValue:this._compressor.knee.minValue,maxValue:this._compressor.knee.maxValue,context:this.context,convert:!1,param:this._compressor.knee,units:"decibels",value:e.knee}),this.ratio=new Xt({minValue:this._compressor.ratio.minValue,maxValue:this._compressor.ratio.maxValue,context:this.context,convert:!1,param:this._compressor.ratio,units:"positive",value:e.ratio}),Zt(this,["knee","release","attack","ratio","threshold"])}static getDefaults(){return Object.assign(ft.getDefaults(),{attack:.003,knee:30,ratio:12,release:.25,threshold:-24})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.disconnect(),this.attack.dispose(),this.release.dispose(),this.threshold.dispose(),this.ratio.dispose(),this.knee.dispose(),this}}class Cb extends ft{constructor(){const e=lt(Cb.getDefaults(),arguments,["low","mid","high"]);super(e),this.name="EQ3",this.output=new jt({context:this.context}),this._internalChannels=[],this.input=this._multibandSplit=new Ab({context:this.context,highFrequency:e.highFrequency,lowFrequency:e.lowFrequency}),this._lowGain=new jt({context:this.context,gain:e.low,units:"decibels"}),this._midGain=new jt({context:this.context,gain:e.mid,units:"decibels"}),this._highGain=new jt({context:this.context,gain:e.high,units:"decibels"}),this.low=this._lowGain.gain,this.mid=this._midGain.gain,this.high=this._highGain.gain,this.Q=this._multibandSplit.Q,this.lowFrequency=this._multibandSplit.lowFrequency,this.highFrequency=this._multibandSplit.highFrequency,this._multibandSplit.low.chain(this._lowGain,this.output),this._multibandSplit.mid.chain(this._midGain,this.output),this._multibandSplit.high.chain(this._highGain,this.output),Zt(this,["low","mid","high","lowFrequency","highFrequency"]),this._internalChannels=[this._multibandSplit]}static getDefaults(){return Object.assign(ft.getDefaults(),{high:0,highFrequency:2500,low:0,lowFrequency:400,mid:0})}dispose(){return super.dispose(),dm(this,["low","mid","high","lowFrequency","highFrequency"]),this._multibandSplit.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this._lowGain.dispose(),this._midGain.dispose(),this._highGain.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.Q.dispose(),this}}zi().transport;function Rb(){return zi().transport}zi().destination;zi().destination;function ate(){return zi().destination}zi().listener;zi().draw;zi();const XE=kr("256n").toSeconds(),lte=kr("8n").toSeconds();function cte(){const t=new wb;t.set({wet:0});const e=new vy;e.set({wet:0,delayTime:XE,maxDelay:"1n",feedback:.666});const n=new Sb;n.set({wet:0,depth:.999,frequency:7,feedback:.666});const r=new Eb;r.set({wet:0,Q:10});const i=new kp;i.set({wet:0,distortion:.9});const s=new Tb;return s.set({wet:0,depth:.2}),{reverb:t,echo:e,chorus:n,phaser:r,distortion:i,vibrato:s}}const ute={a:1,b:2,c:3,d:4,e:5,f:6,g:7,x:8,"#":9,"!":10,y:13,t:14,s:15,i:16,q:17,h:18,w:19,3:20,".":21,"+":11,"-":12,0:22,1:23,2:24,p:25,4:26,5:27,6:29,7:28,8:30,9:31};let hte=0;function fte(t,e,n){let r=e,i=3,s="32n",o="",a="";const l=[];function c(){a="",o="",r+=kr(s).toSeconds()}function u(){a===null?(l.push([r,[t,s,a]]),c()):mt(a)?(l.push([r,[t,s,a]]),c()):a!==""&&(l.push([r,[t,s,`${a}${o}${i}`]]),c())}for(let h=0;h{if(!s_){const t=Rb();t.bpm.value=107,t.start(),to("synth","audio is enabled!"),s_=!0}}).catch(()=>{})}function pte(){const t=ate(),e=new kc(8);e.connect(t);const n=new Mb({threshold:-24,ratio:4,attack:.003,release:.25,knee:30});n.connect(e);const r=new jt;r.connect(n);const i=new kc(2);i.connect(n);const s=[il(r),il(r),il(r),il(r),il(r),il(r),il(r),il(r),il(r)],o=new q_().connect(i);o.maxPolyphony=8,o.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"square"}});function a(De){o.triggerAttackRelease("C6","1i",De)}const l=new Oi().connect(i);o.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"square"}});function c(De){const A=kr("64n").toSeconds();l.triggerAttackRelease("C6","8n",De),l.frequency.exponentialRampToValueAtTime("C11",A+De)}const u=new Ks(350,"bandpass").connect(i),h=new jt().connect(u);h.gain.value=0;const p=new q_().connect(h);p.maxPolyphony=8,p.set({envelope:{attack:.001,decay:.01,sustain:.1,release:.1},oscillator:{type:"square"}});function m(De,A){const ie=kr("64n").toSeconds()+kr(De).toSeconds();h.gain.setValueAtTime(.5,A),h.gain.exponentialRampToValueAtTime(.01,ie+A),p.triggerAttackRelease([800,540],De,A)}const g=new Cb(-10,10,-1).connect(i),v=new Ks(800,"highpass",-12);v.connect(g);const y=new hf;y.set({envelope:{attack:.01,decay:.1,sustain:.1,release:.1}}),y.connect(v);function _(De,A){y.triggerAttackRelease(De,A)}const S=new kp().connect(i);S.set({distortion:.666});const E=new Oi;E.set({envelope:{attack:0,decay:.1,sustain:0,release:1},oscillator:{type:"triangle"}}),E.connect(S);const T=new Ks;T.set({type:"highpass",frequency:1e4}),T.connect(S);const N=new hf;N.set({envelope:{attack:.01,decay:.1,sustain:0,release:.1}}),N.connect(T);function R(De,A){const ie=kr("512n").toSeconds(),te=kr("32n").toSeconds();E.triggerAttackRelease(1e4,De,A,1),E.frequency.exponentialRampToValueAtTime(300,A+ie),E.frequency.exponentialRampToValueAtTime(100,A+te),N.triggerAttackRelease("8n",A,.333),N.volume.setValueAtTime(1,A),N.volume.exponentialRampToValueAtTime(0,A+kr("32n").toSeconds())}const C=new Ks;C.set({type:"bandpass",frequency:256,Q:.17}),C.connect(i);const O=new Oi;O.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"sawtooth"}}),O.connect(C);const M=new Oi;M.set({envelope:{attack:.001,decay:.1,sustain:.001,release:.1},oscillator:{type:"sine"}}),M.connect(C);function I(De,A){O.triggerAttackRelease(2e3,De,A),O.frequency.exponentialRampToValueAtTime(1e3,A+kr("32n").toSeconds()),M.triggerAttackRelease(999,De,A),M.frequency.exponentialRampToValueAtTime(888,A+kr("256n").toSeconds())}const U=new kp().connect(i);U.set({distortion:.876});const L=new Oi;L.set({envelope:{attack:0,decay:.1,sustain:0,release:1},oscillator:{type:"triangle"}}),L.connect(U);const P=new Ks;P.set({type:"highpass",frequency:1e4}),P.connect(U);const b=new hf;b.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1}}),b.connect(P);function H(De,A){const ie=kr("512n").toSeconds(),te=kr("32n").toSeconds();L.triggerAttackRelease(1e4,De,A,1),L.frequency.exponentialRampToValueAtTime(150,A+ie),L.frequency.exponentialRampToValueAtTime(100,A+te),b.triggerAttackRelease("8n",A,.25),b.volume.setValueAtTime(1,A),b.volume.exponentialRampToValueAtTime(0,A+kr("32n").toSeconds())}const V=new Oi().connect(i);V.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1},oscillator:{type:"sawtooth"}});const B=new Oi().connect(i);V.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1},oscillator:{type:"triangle"}});const z=new hf().connect(i);z.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1}});function W(De,A){const ie=kr("256n").toSeconds(),te=kr(De).toSeconds()-ie;V.triggerAttackRelease("C4",te,A,1),V.frequency.exponentialRampToValueAtTime(q2("C0").toFrequency(),A+te),B.triggerAttackRelease("C5",te,A,.5),B.frequency.exponentialRampToValueAtTime(q2("C0").toFrequency(),A+te);const X=kr("4n").toSeconds();z.triggerAttackRelease("8n",A),z.volume.setValueAtTime(1,A),z.volume.exponentialRampToValueAtTime(0,A+X)}const K=new Ks;K.set({type:"bandpass",frequency:256,Q:.17}),K.connect(i);const j=new Oi;j.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"sawtooth"}}),j.connect(K);const Y=new Oi;Y.set({envelope:{attack:.001,decay:.1,sustain:.001,release:.1},oscillator:{type:"sine"}}),Y.connect(K);function ge(De,A){j.triggerAttackRelease(2e3,De,A),j.frequency.exponentialRampToValueAtTime(100,A+kr("32n").toSeconds()),Y.triggerAttackRelease(699,De,A),Y.frequency.exponentialRampToValueAtTime(399,A+kr("256n").toSeconds())}const Q=new vm().connect(i);Q.set({octaves:8});function re(De){Q.triggerAttackRelease("C1","8n",De)}const we=new X_(Ae);function Ae(De,A){if(A===null)return;const[ie,te,X]=A;if(Kt(X)&&Z(s[ie])&&s[ie].source.triggerAttackRelease(X,te,De),mt(X))switch(X){case 0:a(De);break;case 1:c(De);break;case 2:m(te,De);break;case 3:_(te,De);break;case 4:R(te,De);break;case 5:I(te,De);break;case 6:H(te,De);break;case 7:W(te,De);break;case 8:ge(te,De);break;case 9:re(De);break;case-1:--Ve,Ve===0&&(Le=-1),synthsfxpriority=-1;break}}function Ee(De,A,ie){let te=A;const X=fte(De,A,ie),$=X[X.length-1];Z($)&&(te=Math.max(te,$[0]));for(let ne=0;ne{if(s_&&!Z(fu)&&(fu=pte()),!!Z(fu))switch(t.target){case"tts":tp("tts",async()=>{if(ln(t.data)){const[e,n]=t.data;await vte(e===""?"en-US-JacobNeural":e,n)}});break;case"play":if(ln(t.data)){const[e,n]=t.data;n===""?fu.stopplay():fu.addplay(e,n)}break;case"voice":if(ln(t.data)){const[e,n,r]=t.data,i=fu.SOURCE[e];if(!Z(i)){Pn(sl.name(),t.target,`unknown voice ${e}`);return}switch(n){case"bpm":if(mt(r)){Rb().bpm.value=r;return}break;case"vol":case"volume":if(mt(r)){i.source.volume.value=r;return}break;case"port":case"portamento":if(mt(r)){i.source.portamento=r;return}break;case"env":case"envelope":if(ln(r)){const[s,o,a,l]=r;i.source.set({envelope:{attack:s,decay:o,sustain:a,release:l}});return}break;default:if(Kt(n)){if(mte(n,r)){i.source.set({oscillator:{type:n}}),ln(r)&&i.source.set({oscillator:{partials:r}}),mt(r)&&i.source.set({oscillator:{partials:[r]}});return}const s=i.source.get().oscillator.type;switch(s){case"pwm":switch(n){case"modfreq":case"modulationfrequency":if(mt(r)){i.source.set({oscillator:{modulationFrequency:r}});return}break}break;case"pulse":switch(n){case"width":if(mt(r)){i.source.set({oscillator:{width:r}});return}break}break;case"custom":case"sine":case"square":case"triangle":case"sawtooth":switch(n){case"phase":if(mt(r)){i.source.set({oscillator:{phase:r}});return}break}break;case"amcustom":case"amsine":case"amsquare":case"amtriangle":case"amsawtooth":switch(n){case"harmonicity":if(mt(r)){i.source.set({oscillator:{harmonicity:r}});return}break;case"modtype":case"modulationtype":if(Kt(r)){i.source.set({oscillator:{modulationType:r}});return}break;case"modenv":case"modulationenvelope":if(ln(r)){const[o,a,l,c]=r;i.source.set({oscillator:{modulationEnvelope:{attack:o,decay:a,sustain:l,release:c}}});return}break}break;case"fmcustom":case"fmsine":case"fmsquare":case"fmtriangle":case"fmsawtooth":switch(n){case"harmonicity":if(mt(r)){i.source.set({oscillator:{harmonicity:r}});return}break;case"modindex":if(mt(r)){i.source.set({oscillator:{modulationIndex:r}});return}break;case"modtype":if(Kt(r)){i.source.set({oscillator:{modulationType:r}});return}break;case"modenv":if(ln(r)){const[o,a,l,c]=r;i.source.set({oscillator:{modulationEnvelope:{attack:o,decay:a,sustain:l,release:c}}});return}break}break;case"fatcustom":case"fatsine":case"fatsquare":case"fattriangle":case"fatsawtooth":switch(n){case"count":if(mt(r)){i.source.set({oscillator:{count:r}});return}break;case"phase":if(mt(r)){i.source.set({oscillator:{phase:r}});return}break;case"spread":if(mt(r)){i.source.set({oscillator:{spread:r}});return}break}break}Pn(sl.name(),t.target,`unknown ${s} config ${n}`)}break}}break;case"voicefx":if(ln(t.data)){const[e,n,r,i]=t.data,s=fu.SOURCE[e],o=s==null?void 0:s.fx[n];if(Z(o)){switch(r){case"on":o.wet.value=.2;break;case"off":o.wet.value=0;break;default:if(mt(r))o.wet.value=Cn(.01*r,0,1);else switch(n){case"vibrato":{switch(r){default:Pn(sl.name(),t.target,`unknown ${n} config ${r}`);break}break}case"chorus":{switch(r){default:Pn(sl.name(),t.target,`unknown ${n} config ${r}`);break}break}case"phaser":{const a=o;switch(r){case"q":mt(i)&&(a.Q.value=i);break;case"octaves":mt(i)&&(a.octaves=i);break;case"basefrequency":mt(i)&&(a.baseFrequency=i);break;default:Pn(sl.name(),t.target,`unknown ${n} config ${r}`);break}break}case"distortion":{const a=o;switch(r){case"distortion":mt(i)&&(a.distortion=i);break;case"oversample":switch(i){case"2x":case"4x":case"none":a.oversample=i;break}break;default:Pn(sl.name(),t.target,`unknown ${n} config ${r}`);break}break}case"echo":{const a=o;switch(r){case"delaytime":a.delayTime.value=i;break;default:Pn(sl.name(),t.target,`unknown ${n} config ${r}`);break}break}case"reverb":{const a=o;switch(r){case"decay":a.decay=i;break;case"predelay":a.preDelay=i;break;default:Pn(sl.name(),t.target,`unknown ${n} config ${r}`);break}break}}break}o instanceof vy&&(o.wet.value===0?o.set({delayTime:XE}):o.get().delayTime===XE&&o.set({delayTime:lte}));return}Pn(sl.name(),t.target,`unknown fx ${n}`)}break}}),J2=t=>{let e;const n=new Set,r=(c,u)=>{const h=typeof c=="function"?c(e):c;if(!Object.is(h,e)){const p=e;e=u??(typeof h!="object"||h===null)?h:Object.assign({},e,h),n.forEach(m=>m(e,p))}},i=()=>e,a={setState:r,getState:i,getInitialState:()=>l,subscribe:c=>(n.add(c),()=>n.delete(c))},l=e=t(r,i,a);return a},Nb=t=>t?J2(t):J2,yte=t=>t;function kb(t,e=yte){const n=Co.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return Co.useDebugValue(n),n}const Q2=t=>{const e=Nb(t),n=r=>kb(e,r);return Object.assign(n,e),n},xm=t=>t?Q2(t):Q2;function xte(t){const e=Ne.useRef();return n=>{const r=t(n);return(e.current===void 0||r===void 0?e.current===r:DO(e.current,r))?e.current:e.current=r}}const ss=xm(()=>({desync:!1,gadget:{player:"",layers:[],panels:[],reset:!1,focus:""}}));function Ib(){return ss(t=>t.gadget.player)}function Y_(){return ss.getState().gadget.player}var o_=(t=>(t[t.OFF=0]="OFF",t[t.INFO=1]="INFO",t[t.DEBUG=2]="DEBUG",t))(o_||{});const eN=128;var Li=(t=>(t[t.TOP=0]="TOP",t[t.BOTTOM=1]="BOTTOM",t[t.FULL=2]="FULL",t[t.SPLIT_Y=3]="SPLIT_Y",t[t.SPLIT_Y_ALT=4]="SPLIT_Y_ALT",t[t.MAX=5]="MAX",t))(Li||{});const es=xm(()=>({layout:1,terminal:{open:!1,level:1,logs:[]},editor:{open:!1,player:"",book:"",page:"",type:"",title:""}})),Tr=xm(()=>({scroll:0,xcursor:0,ycursor:0,xselect:void 0,yselect:void 0,bufferindex:0,buffer:[""]})),hr=xm(()=>({id:"",xscroll:0,yscroll:0,cursor:0,select:void 0}));/** + * postprocessing v6.36.4 build Tue Nov 05 2024 + * https://github.com/pmndrs/postprocessing + * Copyright 2015-2024 Raoul van Rüschen + * @license Zlib + */var XS=1/1e3,Ste=1e3,Ete=class{constructor(){this.startTime=performance.now(),this.previousTime=0,this.currentTime=0,this._delta=0,this._elapsed=0,this._fixedDelta=1e3/60,this.timescale=1,this.useFixedDelta=!1,this._autoReset=!1}get autoReset(){return this._autoReset}set autoReset(t){typeof document<"u"&&document.hidden!==void 0&&(t?document.addEventListener("visibilitychange",this):document.removeEventListener("visibilitychange",this),this._autoReset=t)}get delta(){return this._delta*XS}get fixedDelta(){return this._fixedDelta*XS}set fixedDelta(t){this._fixedDelta=t*Ste}get elapsed(){return this._elapsed*XS}update(t){this.useFixedDelta?this._delta=this.fixedDelta:(this.previousTime=this.currentTime,this.currentTime=(t!==void 0?t:performance.now())-this.startTime,this._delta=this.currentTime-this.previousTime),this._delta*=this.timescale,this._elapsed+=this._delta}reset(){this._delta=0,this._elapsed=0,this.currentTime=performance.now()-this.startTime}getDelta(){return this.delta}getElapsed(){return this.elapsed}handleEvent(t){document.hidden||(this.currentTime=performance.now()-this.startTime)}dispose(){this.autoReset=!1}},wte=(()=>{const t=new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),e=new Float32Array([0,0,2,0,0,2]),n=new Bo;return n.setAttribute("position",new Jn(t,3)),n.setAttribute("uv",new Jn(e,2)),n})(),Wo=class KE{static get fullscreenGeometry(){return wte}constructor(e="Pass",n=new M_,r=new Nv){this.name=e,this.renderer=null,this.scene=n,this.camera=r,this.screen=null,this.rtt=!0,this.needsSwap=!0,this.needsDepthTexture=!1,this.enabled=!0}get renderToScreen(){return!this.rtt}set renderToScreen(e){if(this.rtt===e){const n=this.fullscreenMaterial;n!==null&&(n.needsUpdate=!0),this.rtt=!e}}set mainScene(e){}set mainCamera(e){}setRenderer(e){this.renderer=e}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}get fullscreenMaterial(){return this.screen!==null?this.screen.material:null}set fullscreenMaterial(e){let n=this.screen;n!==null?n.material=e:(n=new Ao(KE.fullscreenGeometry,e),n.frustumCulled=!1,this.scene===null&&(this.scene=new M_),this.scene.add(n),this.screen=n)}getFullscreenMaterial(){return this.fullscreenMaterial}setFullscreenMaterial(e){this.fullscreenMaterial=e}getDepthTexture(){return null}setDepthTexture(e,n=th){}render(e,n,r,i,s){throw new Error("Render method not implemented!")}setSize(e,n){}initialize(e,n,r){}dispose(){for(const e of Object.keys(this)){const n=this[e];(n instanceof Ps||n instanceof Ul||n instanceof or||n instanceof KE)&&this[e].dispose()}this.fullscreenMaterial!==null&&this.fullscreenMaterial.dispose()}},Tte=class extends Wo{constructor(){super("ClearMaskPass",null,null),this.needsSwap=!1}render(t,e,n,r,i){const s=t.state.buffers.stencil;s.setLocked(!1),s.setTest(!1)}},bte=`#include +#include +#ifdef FRAMEBUFFER_PRECISION_HIGH +uniform mediump sampler2D inputBuffer; +#else +uniform lowp sampler2D inputBuffer; +#endif +uniform float opacity;varying vec2 vUv;void main(){vec4 texel=texture2D(inputBuffer,vUv);gl_FragColor=opacity*texel; +#include +#include +}`,Ate="varying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,1.0,1.0);}",Mte=class extends Hi{constructor(){super({name:"CopyMaterial",uniforms:{inputBuffer:new Mn(null),opacity:new Mn(1)},blending:Ro,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:bte,vertexShader:Ate})}set inputBuffer(t){this.uniforms.inputBuffer.value=t}setInputBuffer(t){this.uniforms.inputBuffer.value=t}getOpacity(t){return this.uniforms.opacity.value}setOpacity(t){this.uniforms.opacity.value=t}},Cte=class extends Wo{constructor(t,e=!0){super("CopyPass"),this.fullscreenMaterial=new Mte,this.needsSwap=!1,this.renderTarget=t,t===void 0&&(this.renderTarget=new Ps(1,1,{minFilter:rs,magFilter:rs,stencilBuffer:!1,depthBuffer:!1}),this.renderTarget.texture.name="CopyPass.Target"),this.autoResize=e}get resize(){return this.autoResize}set resize(t){this.autoResize=t}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}setAutoResizeEnabled(t){this.autoResize=t}render(t,e,n,r,i){this.fullscreenMaterial.inputBuffer=e.texture,t.setRenderTarget(this.renderToScreen?null:this.renderTarget),t.render(this.scene,this.camera)}setSize(t,e){this.autoResize&&this.renderTarget.setSize(t,e)}initialize(t,e,n){n!==void 0&&(this.renderTarget.texture.type=n,n!==wi?this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1":t!==null&&t.outputColorSpace===pr&&(this.renderTarget.texture.colorSpace=pr))}},tN=new cn,VP=class extends Wo{constructor(t=!0,e=!0,n=!1){super("ClearPass",null,null),this.needsSwap=!1,this.color=t,this.depth=e,this.stencil=n,this.overrideClearColor=null,this.overrideClearAlpha=-1}setClearFlags(t,e,n){this.color=t,this.depth=e,this.stencil=n}getOverrideClearColor(){return this.overrideClearColor}setOverrideClearColor(t){this.overrideClearColor=t}getOverrideClearAlpha(){return this.overrideClearAlpha}setOverrideClearAlpha(t){this.overrideClearAlpha=t}render(t,e,n,r,i){const s=this.overrideClearColor,o=this.overrideClearAlpha,a=t.getClearAlpha(),l=s!==null,c=o>=0;l?(t.getClearColor(tN),t.setClearColor(s,c?o:a)):c&&t.setClearAlpha(o),t.setRenderTarget(this.renderToScreen?null:e),t.clear(this.color,this.depth,this.stencil),l?t.setClearColor(tN,a):c&&t.setClearAlpha(a)}},Rte=class extends Wo{constructor(t,e){super("MaskPass",t,e),this.needsSwap=!1,this.clearPass=new VP(!1,!1,!0),this.inverse=!1}set mainScene(t){this.scene=t}set mainCamera(t){this.camera=t}get inverted(){return this.inverse}set inverted(t){this.inverse=t}get clear(){return this.clearPass.enabled}set clear(t){this.clearPass.enabled=t}getClearPass(){return this.clearPass}isInverted(){return this.inverted}setInverted(t){this.inverted=t}render(t,e,n,r,i){const s=t.getContext(),o=t.state.buffers,a=this.scene,l=this.camera,c=this.clearPass,u=this.inverted?0:1,h=1-u;o.color.setMask(!1),o.depth.setMask(!1),o.color.setLocked(!0),o.depth.setLocked(!0),o.stencil.setTest(!0),o.stencil.setOp(s.REPLACE,s.REPLACE,s.REPLACE),o.stencil.setFunc(s.ALWAYS,u,4294967295),o.stencil.setClear(h),o.stencil.setLocked(!0),this.clearPass.enabled&&(this.renderToScreen?c.render(t,null):(c.render(t,e),c.render(t,n))),this.renderToScreen?(t.setRenderTarget(null),t.render(a,l)):(t.setRenderTarget(e),t.render(a,l),t.setRenderTarget(n),t.render(a,l)),o.color.setLocked(!1),o.depth.setLocked(!1),o.stencil.setLocked(!1),o.stencil.setFunc(s.EQUAL,1,4294967295),o.stencil.setOp(s.KEEP,s.KEEP,s.KEEP),o.stencil.setLocked(!0)}},Nte=class{constructor(e=null,{depthBuffer:n=!0,stencilBuffer:r=!1,multisampling:i=0,frameBufferType:s}={}){this.renderer=null,this.inputBuffer=this.createBuffer(n,r,s,i),this.outputBuffer=this.inputBuffer.clone(),this.copyPass=new Cte,this.depthTexture=null,this.passes=[],this.timer=new Ete,this.autoRenderToScreen=!0,this.setRenderer(e)}get multisampling(){return this.inputBuffer.samples||0}set multisampling(e){const n=this.inputBuffer,r=this.multisampling;r>0&&e>0?(this.inputBuffer.samples=e,this.outputBuffer.samples=e,this.inputBuffer.dispose(),this.outputBuffer.dispose()):r!==e&&(this.inputBuffer.dispose(),this.outputBuffer.dispose(),this.inputBuffer=this.createBuffer(n.depthBuffer,n.stencilBuffer,n.texture.type,e),this.inputBuffer.depthTexture=this.depthTexture,this.outputBuffer=this.inputBuffer.clone())}getTimer(){return this.timer}getRenderer(){return this.renderer}setRenderer(e){if(this.renderer=e,e!==null){const n=e.getSize(new St),r=e.getContext().getContextAttributes().alpha,i=this.inputBuffer.texture.type;i===wi&&e.outputColorSpace===pr&&(this.inputBuffer.texture.colorSpace=pr,this.outputBuffer.texture.colorSpace=pr,this.inputBuffer.dispose(),this.outputBuffer.dispose()),e.autoClear=!1,this.setSize(n.width,n.height);for(const s of this.passes)s.initialize(e,r,i)}}replaceRenderer(e,n=!0){const r=this.renderer,i=r.domElement.parentNode;return this.setRenderer(e),n&&i!==null&&(i.removeChild(r.domElement),i.appendChild(e.domElement)),r}createDepthTexture(){const e=this.depthTexture=new hT;return this.inputBuffer.depthTexture=e,this.inputBuffer.dispose(),this.inputBuffer.stencilBuffer?(e.format=zu,e.type=Bu):e.type=Rc,e}deleteDepthTexture(){if(this.depthTexture!==null){this.depthTexture.dispose(),this.depthTexture=null,this.inputBuffer.depthTexture=null,this.inputBuffer.dispose();for(const e of this.passes)e.setDepthTexture(null)}}createBuffer(e,n,r,i){const s=this.renderer,o=s===null?new St:s.getDrawingBufferSize(new St),a={minFilter:rs,magFilter:rs,stencilBuffer:n,depthBuffer:e,type:r},l=new Ps(o.width,o.height,a);return i>0&&(l.ignoreDepthForMultisampleCopy=!1,l.samples=i),r===wi&&s!==null&&s.outputColorSpace===pr&&(l.texture.colorSpace=pr),l.texture.name="EffectComposer.Buffer",l.texture.generateMipmaps=!1,l}setMainScene(e){for(const n of this.passes)n.mainScene=e}setMainCamera(e){for(const n of this.passes)n.mainCamera=e}addPass(e,n){const r=this.passes,i=this.renderer,s=i.getDrawingBufferSize(new St),o=i.getContext().getContextAttributes().alpha,a=this.inputBuffer.texture.type;if(e.setRenderer(i),e.setSize(s.width,s.height),e.initialize(i,o,a),this.autoRenderToScreen&&(r.length>0&&(r[r.length-1].renderToScreen=!1),e.renderToScreen&&(this.autoRenderToScreen=!1)),n!==void 0?r.splice(n,0,e):r.push(e),this.autoRenderToScreen&&(r[r.length-1].renderToScreen=!0),e.needsDepthTexture||this.depthTexture!==null)if(this.depthTexture===null){const l=this.createDepthTexture();for(e of r)e.setDepthTexture(l)}else e.setDepthTexture(this.depthTexture)}removePass(e){const n=this.passes,r=n.indexOf(e);if(r!==-1&&n.splice(r,1).length>0){if(this.depthTexture!==null){const o=(l,c)=>l||c.needsDepthTexture;n.reduce(o,!1)||(e.getDepthTexture()===this.depthTexture&&e.setDepthTexture(null),this.deleteDepthTexture())}this.autoRenderToScreen&&r===n.length&&(e.renderToScreen=!1,n.length>0&&(n[n.length-1].renderToScreen=!0))}}removeAllPasses(){const e=this.passes;this.deleteDepthTexture(),e.length>0&&(this.autoRenderToScreen&&(e[e.length-1].renderToScreen=!1),this.passes=[])}render(e){const n=this.renderer,r=this.copyPass;let i=this.inputBuffer,s=this.outputBuffer,o=!1,a,l,c;e===void 0&&(this.timer.update(),e=this.timer.getDelta());for(const u of this.passes)u.enabled&&(u.render(n,i,s,e,o),u.needsSwap&&(o&&(r.renderToScreen=u.renderToScreen,a=n.getContext(),l=n.state.buffers.stencil,l.setFunc(a.NOTEQUAL,1,4294967295),r.render(n,i,s,e,o),l.setFunc(a.EQUAL,1,4294967295)),c=i,i=s,s=c),u instanceof Rte?o=!0:u instanceof Tte&&(o=!1))}setSize(e,n,r){const i=this.renderer,s=i.getSize(new St);(e===void 0||n===void 0)&&(e=s.width,n=s.height),(s.width!==e||s.height!==n)&&i.setSize(e,n,r);const o=i.getDrawingBufferSize(new St);this.inputBuffer.setSize(o.width,o.height),this.outputBuffer.setSize(o.width,o.height);for(const a of this.passes)a.setSize(o.width,o.height)}reset(){this.dispose(),this.autoRenderToScreen=!0}dispose(){for(const e of this.passes)e.dispose();this.passes=[],this.inputBuffer!==null&&this.inputBuffer.dispose(),this.outputBuffer!==null&&this.outputBuffer.dispose(),this.deleteDepthTexture(),this.copyPass.dispose(),this.timer.dispose(),Wo.fullscreenGeometry.dispose()}},Sa={NONE:0,DEPTH:1,CONVOLUTION:2},_n={FRAGMENT_HEAD:"FRAGMENT_HEAD",FRAGMENT_MAIN_UV:"FRAGMENT_MAIN_UV",FRAGMENT_MAIN_IMAGE:"FRAGMENT_MAIN_IMAGE",VERTEX_HEAD:"VERTEX_HEAD",VERTEX_MAIN_SUPPORT:"VERTEX_MAIN_SUPPORT"},kte=class{constructor(){this.shaderParts=new Map([[_n.FRAGMENT_HEAD,null],[_n.FRAGMENT_MAIN_UV,null],[_n.FRAGMENT_MAIN_IMAGE,null],[_n.VERTEX_HEAD,null],[_n.VERTEX_MAIN_SUPPORT,null]]),this.defines=new Map,this.uniforms=new Map,this.blendModes=new Map,this.extensions=new Set,this.attributes=Sa.NONE,this.varyings=new Set,this.uvTransformation=!1,this.readDepth=!1,this.colorSpace=Hc}},KS=!1,nN=class{constructor(t=null){this.originalMaterials=new Map,this.material=null,this.materials=null,this.materialsBackSide=null,this.materialsDoubleSide=null,this.materialsFlatShaded=null,this.materialsFlatShadedBackSide=null,this.materialsFlatShadedDoubleSide=null,this.setMaterial(t),this.meshCount=0,this.replaceMaterial=e=>{if(e.isMesh){let n;if(e.material.flatShading)switch(e.material.side){case Cs:n=this.materialsFlatShadedDoubleSide;break;case ni:n=this.materialsFlatShadedBackSide;break;default:n=this.materialsFlatShaded;break}else switch(e.material.side){case Cs:n=this.materialsDoubleSide;break;case ni:n=this.materialsBackSide;break;default:n=this.materials;break}this.originalMaterials.set(e,e.material),e.isSkinnedMesh?e.material=n[2]:e.isInstancedMesh?e.material=n[1]:e.material=n[0],++this.meshCount}}}cloneMaterial(t){if(!(t instanceof Hi))return t.clone();const e=t.uniforms,n=new Map;for(const i in e){const s=e[i].value;s.isRenderTargetTexture&&(e[i].value=null,n.set(i,s))}const r=t.clone();for(const i of n)e[i[0]].value=i[1],r.uniforms[i[0]].value=i[1];return r}setMaterial(t){if(this.disposeMaterials(),this.material=t,t!==null){const e=this.materials=[this.cloneMaterial(t),this.cloneMaterial(t),this.cloneMaterial(t)];for(const n of e)n.uniforms=Object.assign({},t.uniforms),n.side=Al;e[2].skinning=!0,this.materialsBackSide=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.side=ni,r}),this.materialsDoubleSide=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.side=Cs,r}),this.materialsFlatShaded=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.flatShading=!0,r}),this.materialsFlatShadedBackSide=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.flatShading=!0,r.side=ni,r}),this.materialsFlatShadedDoubleSide=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.flatShading=!0,r.side=Cs,r})}}render(t,e,n){const r=t.shadowMap.enabled;if(t.shadowMap.enabled=!1,KS){const i=this.originalMaterials;this.meshCount=0,e.traverse(this.replaceMaterial),t.render(e,n);for(const s of i)s[0].material=s[1];this.meshCount!==i.size&&i.clear()}else{const i=e.overrideMaterial;e.overrideMaterial=this.material,t.render(e,n),e.overrideMaterial=i}t.shadowMap.enabled=r}disposeMaterials(){if(this.material!==null){const t=this.materials.concat(this.materialsBackSide).concat(this.materialsDoubleSide).concat(this.materialsFlatShaded).concat(this.materialsFlatShadedBackSide).concat(this.materialsFlatShadedDoubleSide);for(const e of t)e.dispose()}}dispose(){this.originalMaterials.clear(),this.disposeMaterials()}static get workaroundEnabled(){return KS}static set workaroundEnabled(t){KS=t}},pc=-1,Ef=class extends Dl{constructor(t,e=pc,n=pc,r=1){super(),this.resizable=t,this.baseSize=new St(1,1),this.preferredSize=new St(e,n),this.target=this.preferredSize,this.s=r,this.effectiveSize=new St,this.addEventListener("change",()=>this.updateEffectiveSize()),this.updateEffectiveSize()}updateEffectiveSize(){const t=this.baseSize,e=this.preferredSize,n=this.effectiveSize,r=this.scale;e.width!==pc?n.width=e.width:e.height!==pc?n.width=Math.round(e.height*(t.width/Math.max(t.height,1))):n.width=Math.round(t.width*r),e.height!==pc?n.height=e.height:e.width!==pc?n.height=Math.round(e.width/Math.max(t.width/Math.max(t.height,1),1)):n.height=Math.round(t.height*r)}get width(){return this.effectiveSize.width}set width(t){this.preferredWidth=t}get height(){return this.effectiveSize.height}set height(t){this.preferredHeight=t}getWidth(){return this.width}getHeight(){return this.height}get scale(){return this.s}set scale(t){this.s!==t&&(this.s=t,this.preferredSize.setScalar(pc),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getScale(){return this.scale}setScale(t){this.scale=t}get baseWidth(){return this.baseSize.width}set baseWidth(t){this.baseSize.width!==t&&(this.baseSize.width=t,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseWidth(){return this.baseWidth}setBaseWidth(t){this.baseWidth=t}get baseHeight(){return this.baseSize.height}set baseHeight(t){this.baseSize.height!==t&&(this.baseSize.height=t,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseHeight(){return this.baseHeight}setBaseHeight(t){this.baseHeight=t}setBaseSize(t,e){(this.baseSize.width!==t||this.baseSize.height!==e)&&(this.baseSize.set(t,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}get preferredWidth(){return this.preferredSize.width}set preferredWidth(t){this.preferredSize.width!==t&&(this.preferredSize.width=t,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredWidth(){return this.preferredWidth}setPreferredWidth(t){this.preferredWidth=t}get preferredHeight(){return this.preferredSize.height}set preferredHeight(t){this.preferredSize.height!==t&&(this.preferredSize.height=t,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredHeight(){return this.preferredHeight}setPreferredHeight(t){this.preferredHeight=t}setPreferredSize(t,e){(this.preferredSize.width!==t||this.preferredSize.height!==e)&&(this.preferredSize.set(t,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}copy(t){this.s=t.scale,this.baseSize.set(t.baseWidth,t.baseHeight),this.preferredSize.set(t.preferredWidth,t.preferredHeight),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height)}static get AUTO_SIZE(){return pc}},Qt={SKIP:9,SET:30,ADD:0,ALPHA:1,AVERAGE:2,COLOR:3,COLOR_BURN:4,COLOR_DODGE:5,DARKEN:6,DIFFERENCE:7,DIVIDE:8,DST:9,EXCLUSION:10,HARD_LIGHT:11,HARD_MIX:12,HUE:13,INVERT:14,INVERT_RGB:15,LIGHTEN:16,LINEAR_BURN:17,LINEAR_DODGE:18,LINEAR_LIGHT:19,LUMINOSITY:20,MULTIPLY:21,NEGATION:22,NORMAL:23,OVERLAY:24,PIN_LIGHT:25,REFLECT:26,SATURATION:27,SCREEN:28,SOFT_LIGHT:29,SRC:30,SUBTRACT:31,VIVID_LIGHT:32},Ite="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x+y,opacity);}",Ote="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,min(y.a,opacity));}",Lte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,(x+y)*0.5,opacity);}",Pte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.rg,xHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",Dte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(step(0.0,y)*(1.0-min(vec4(1.0),(1.0-x)/y)),vec4(1.0),step(1.0,x));return mix(x,z,opacity);}",Ute="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=step(0.0,x)*mix(min(vec4(1.0),x/max(1.0-y,1e-9)),vec4(1.0),step(1.0,y));return mix(x,z,opacity);}",Fte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,min(x,y),opacity);}",Bte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,abs(x-y),opacity);}",zte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x/max(y,1e-12),opacity);}",Vte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,(x+y-2.0*x*y),opacity);}",Hte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 a=min(x,1.0),b=min(y,1.0);vec4 z=mix(2.0*a*b,1.0-2.0*(1.0-a)*(1.0-b),step(0.5,y));return mix(x,z,opacity);}",Gte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,step(1.0,x+y),opacity);}",Wte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.r,xHSL.gb));return vec4(mix(x.rgb,z,opacity),y.a);}",jte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,1.0-y,opacity);}",$te="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y*(1.0-x),opacity);}",qte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,max(x,y),opacity);}",Xte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,clamp(y+x-1.0,0.0,1.0),opacity);}",Kte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,min(x+y,1.0),opacity);}",Yte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,clamp(2.0*y+x-1.0,0.0,1.0),opacity);}",Zte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.rg,yHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",Jte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x*y,opacity);}",Qte="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,1.0-abs(1.0-x-y),opacity);}",ene="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,opacity);}",tne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(2.0*y*x,1.0-2.0*(1.0-y)*(1.0-x),step(0.5,x));return mix(x,z,opacity);}",nne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 y2=2.0*y;vec4 z=mix(mix(y2,x,step(0.5*x,y)),max(vec4(0.0),y2-1.0),step(x,(y2-1.0)));return mix(x,z,opacity);}",rne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(min(x*x/max(1.0-y,1e-12),1.0),y,step(1.0,y));return mix(x,z,opacity);}",ine="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.r,yHSL.g,xHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",sne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x+y-min(x*y,1.0),opacity);}",one="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 y2=2.0*y;vec4 w=step(0.5,y);vec4 z=mix(x-(1.0-y2)*x*(1.0-x),mix(x+(y2-1.0)*(sqrt(x)-x),x+(y2-1.0)*x*((16.0*x-12.0)*x+3.0),w*(1.0-step(0.25,x))),w);return mix(x,z,opacity);}",ane="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return y;}",lne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,max(x+y-1.0,0.0),opacity);}",cne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(max(1.0-min((1.0-x)/(2.0*y),1.0),0.0),min(x/(2.0*(1.0-y)),1.0),step(0.5,y));return mix(x,z,opacity);}",une=new Map([[Qt.ADD,Ite],[Qt.ALPHA,Ote],[Qt.AVERAGE,Lte],[Qt.COLOR,Pte],[Qt.COLOR_BURN,Dte],[Qt.COLOR_DODGE,Ute],[Qt.DARKEN,Fte],[Qt.DIFFERENCE,Bte],[Qt.DIVIDE,zte],[Qt.DST,null],[Qt.EXCLUSION,Vte],[Qt.HARD_LIGHT,Hte],[Qt.HARD_MIX,Gte],[Qt.HUE,Wte],[Qt.INVERT,jte],[Qt.INVERT_RGB,$te],[Qt.LIGHTEN,qte],[Qt.LINEAR_BURN,Xte],[Qt.LINEAR_DODGE,Kte],[Qt.LINEAR_LIGHT,Yte],[Qt.LUMINOSITY,Zte],[Qt.MULTIPLY,Jte],[Qt.NEGATION,Qte],[Qt.NORMAL,ene],[Qt.OVERLAY,tne],[Qt.PIN_LIGHT,nne],[Qt.REFLECT,rne],[Qt.SATURATION,ine],[Qt.SCREEN,sne],[Qt.SOFT_LIGHT,one],[Qt.SRC,ane],[Qt.SUBTRACT,lne],[Qt.VIVID_LIGHT,cne]]),hne=class extends Dl{constructor(t,e=1){super(),this._blendFunction=t,this.opacity=new Mn(e)}getOpacity(){return this.opacity.value}setOpacity(t){this.opacity.value=t}get blendFunction(){return this._blendFunction}set blendFunction(t){this._blendFunction=t,this.dispatchEvent({type:"change"})}getBlendFunction(){return this.blendFunction}setBlendFunction(t){this.blendFunction=t}getShaderCode(){return une.get(this.blendFunction)}},YE=class extends Dl{constructor(t,e,{attributes:n=Sa.NONE,blendFunction:r=Qt.NORMAL,defines:i=new Map,uniforms:s=new Map,extensions:o=null,vertexShader:a=null}={}){super(),this.name=t,this.renderer=null,this.attributes=n,this.fragmentShader=e,this.vertexShader=a,this.defines=i,this.uniforms=s,this.extensions=o,this.blendMode=new hne(r),this.blendMode.addEventListener("change",l=>this.setChanged()),this._inputColorSpace=Hc,this._outputColorSpace=da}get inputColorSpace(){return this._inputColorSpace}set inputColorSpace(t){this._inputColorSpace=t,this.setChanged()}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t,this.setChanged()}set mainScene(t){}set mainCamera(t){}getName(){return this.name}setRenderer(t){this.renderer=t}getDefines(){return this.defines}getUniforms(){return this.uniforms}getExtensions(){return this.extensions}getBlendMode(){return this.blendMode}getAttributes(){return this.attributes}setAttributes(t){this.attributes=t,this.setChanged()}getFragmentShader(){return this.fragmentShader}setFragmentShader(t){this.fragmentShader=t,this.setChanged()}getVertexShader(){return this.vertexShader}setVertexShader(t){this.vertexShader=t,this.setChanged()}setChanged(){this.dispatchEvent({type:"change"})}setDepthTexture(t,e=th){}update(t,e,n){}setSize(t,e){}initialize(t,e,n){}dispose(){for(const t of Object.keys(this)){const e=this[t];(e instanceof Ps||e instanceof Ul||e instanceof or||e instanceof Wo)&&this[t].dispose()}}},x0={RED:0,GREEN:1,BLUE:2,ALPHA:3},HP=class extends Wo{constructor(t,e,n=null){super("RenderPass",t,e),this.needsSwap=!1,this.clearPass=new VP,this.overrideMaterialManager=n===null?null:new nN(n),this.ignoreBackground=!1,this.skipShadowMapUpdate=!1,this.selection=null}set mainScene(t){this.scene=t}set mainCamera(t){this.camera=t}get renderToScreen(){return super.renderToScreen}set renderToScreen(t){super.renderToScreen=t,this.clearPass.renderToScreen=t}get overrideMaterial(){const t=this.overrideMaterialManager;return t!==null?t.material:null}set overrideMaterial(t){const e=this.overrideMaterialManager;t!==null?e!==null?e.setMaterial(t):this.overrideMaterialManager=new nN(t):e!==null&&(e.dispose(),this.overrideMaterialManager=null)}getOverrideMaterial(){return this.overrideMaterial}setOverrideMaterial(t){this.overrideMaterial=t}get clear(){return this.clearPass.enabled}set clear(t){this.clearPass.enabled=t}getSelection(){return this.selection}setSelection(t){this.selection=t}isBackgroundDisabled(){return this.ignoreBackground}setBackgroundDisabled(t){this.ignoreBackground=t}isShadowMapDisabled(){return this.skipShadowMapUpdate}setShadowMapDisabled(t){this.skipShadowMapUpdate=t}getClearPass(){return this.clearPass}render(t,e,n,r,i){const s=this.scene,o=this.camera,a=this.selection,l=o.layers.mask,c=s.background,u=t.shadowMap.autoUpdate,h=this.renderToScreen?null:e;a!==null&&o.layers.set(a.getLayer()),this.skipShadowMapUpdate&&(t.shadowMap.autoUpdate=!1),(this.ignoreBackground||this.clearPass.overrideClearColor!==null)&&(s.background=null),this.clearPass.enabled&&this.clearPass.render(t,e),t.setRenderTarget(h),this.overrideMaterialManager!==null?this.overrideMaterialManager.render(t,s,o):t.render(s,o),o.layers.mask=l,s.background=c,t.shadowMap.autoUpdate=u}},fne=`#include +#ifdef GL_FRAGMENT_PRECISION_HIGH +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +#ifdef DOWNSAMPLE_NORMALS +uniform lowp sampler2D normalBuffer; +#endif +varying vec2 vUv0;varying vec2 vUv1;varying vec2 vUv2;varying vec2 vUv3;float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +return unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +return texture2D(depthBuffer,uv).r; +#endif +}int findBestDepth(const in float samples[4]){float c=(samples[0]+samples[1]+samples[2]+samples[3])*0.25;float distances[4];distances[0]=abs(c-samples[0]);distances[1]=abs(c-samples[1]);distances[2]=abs(c-samples[2]);distances[3]=abs(c-samples[3]);float maxDistance=max(max(distances[0],distances[1]),max(distances[2],distances[3]));int remaining[3];int rejected[3];int i,j,k;for(i=0,j=0,k=0;i<4;++i){if(distances[i]this.setSize(a.baseWidth,a.baseHeight))}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}setDepthTexture(t,e=th){this.fullscreenMaterial.depthBuffer=t,this.fullscreenMaterial.depthPacking=e}render(t,e,n,r,i){t.setRenderTarget(this.renderToScreen?null:this.renderTarget),t.render(this.scene,this.camera)}setSize(t,e){const n=this.resolution;n.setBaseSize(t,e),this.renderTarget.setSize(n.width,n.height),this.fullscreenMaterial.setSize(t,e)}initialize(t,e,n){const r=t.getContext();if(!(r.getExtension("EXT_color_buffer_float")||r.getExtension("EXT_color_buffer_half_float")))throw new Error("Rendering to float texture is not supported.")}},gne=`#include +#include +#include +#define packFloatToRGBA(v) packDepthToRGBA(v) +#define unpackRGBAToFloat(v) unpackRGBAToDepth(v) +#ifdef FRAMEBUFFER_PRECISION_HIGH +uniform mediump sampler2D inputBuffer; +#else +uniform lowp sampler2D inputBuffer; +#endif +#if DEPTH_PACKING == 3201 +uniform lowp sampler2D depthBuffer; +#elif defined(GL_FRAGMENT_PRECISION_HIGH) +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;vec4 sRGBToLinear(const in vec4 value){return vec4(mix(pow(value.rgb*0.9478672986+vec3(0.0521327014),vec3(2.4)),value.rgb*0.0773993808,vec3(lessThanEqual(value.rgb,vec3(0.04045)))),value.a);}float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +return unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +return texture2D(depthBuffer,uv).r; +#endif +}float getViewZ(const in float depth){ +#ifdef PERSPECTIVE_CAMERA +return perspectiveDepthToViewZ(depth,cameraNear,cameraFar); +#else +return orthographicDepthToViewZ(depth,cameraNear,cameraFar); +#endif +}vec3 RGBToHCV(const in vec3 RGB){vec4 P=mix(vec4(RGB.bg,-1.0,2.0/3.0),vec4(RGB.gb,0.0,-1.0/3.0),step(RGB.b,RGB.g));vec4 Q=mix(vec4(P.xyw,RGB.r),vec4(RGB.r,P.yzx),step(P.x,RGB.r));float C=Q.x-min(Q.w,Q.y);float H=abs((Q.w-Q.y)/(6.0*C+EPSILON)+Q.z);return vec3(H,C,Q.x);}vec3 RGBToHSL(const in vec3 RGB){vec3 HCV=RGBToHCV(RGB);float L=HCV.z-HCV.y*0.5;float S=HCV.y/(1.0-abs(L*2.0-1.0)+EPSILON);return vec3(HCV.x,S,L);}vec3 HueToRGB(const in float H){float R=abs(H*6.0-3.0)-1.0;float G=2.0-abs(H*6.0-2.0);float B=2.0-abs(H*6.0-4.0);return clamp(vec3(R,G,B),0.0,1.0);}vec3 HSLToRGB(const in vec3 HSL){vec3 RGB=HueToRGB(HSL.x);float C=(1.0-abs(2.0*HSL.z-1.0))*HSL.y;return(RGB-0.5)*C+HSL.z;}FRAGMENT_HEAD void main(){FRAGMENT_MAIN_UV vec4 color0=texture2D(inputBuffer,UV);vec4 color1=vec4(0.0);FRAGMENT_MAIN_IMAGE color0.a=clamp(color0.a,0.0,1.0);gl_FragColor=color0; +#ifdef ENCODE_OUTPUT +#include +#endif +#include +}`,_ne="uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;VERTEX_HEAD void main(){vUv=position.xy*0.5+0.5;VERTEX_MAIN_SUPPORT gl_Position=vec4(position.xy,1.0,1.0);}",vne=class extends Hi{constructor(t,e,n,r,i=!1){super({name:"EffectMaterial",defines:{THREE_REVISION:bv.replace(/\D+/g,""),DEPTH_PACKING:"0",ENCODE_OUTPUT:"1"},uniforms:{inputBuffer:new Mn(null),depthBuffer:new Mn(null),resolution:new Mn(new St),texelSize:new Mn(new St),cameraNear:new Mn(.3),cameraFar:new Mn(1e3),aspect:new Mn(1),time:new Mn(0)},blending:Ro,toneMapped:!1,depthWrite:!1,depthTest:!1,dithering:i}),t&&this.setShaderParts(t),e&&this.setDefines(e),n&&this.setUniforms(n),this.copyCameraSettings(r)}set inputBuffer(t){this.uniforms.inputBuffer.value=t}setInputBuffer(t){this.uniforms.inputBuffer.value=t}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(t){this.uniforms.depthBuffer.value=t}get depthPacking(){return Number(this.defines.DEPTH_PACKING)}set depthPacking(t){this.defines.DEPTH_PACKING=t.toFixed(0),this.needsUpdate=!0}setDepthBuffer(t,e=th){this.depthBuffer=t,this.depthPacking=e}setShaderData(t){this.setShaderParts(t.shaderParts),this.setDefines(t.defines),this.setUniforms(t.uniforms),this.setExtensions(t.extensions)}setShaderParts(t){return this.fragmentShader=gne.replace(_n.FRAGMENT_HEAD,t.get(_n.FRAGMENT_HEAD)||"").replace(_n.FRAGMENT_MAIN_UV,t.get(_n.FRAGMENT_MAIN_UV)||"").replace(_n.FRAGMENT_MAIN_IMAGE,t.get(_n.FRAGMENT_MAIN_IMAGE)||""),this.vertexShader=_ne.replace(_n.VERTEX_HEAD,t.get(_n.VERTEX_HEAD)||"").replace(_n.VERTEX_MAIN_SUPPORT,t.get(_n.VERTEX_MAIN_SUPPORT)||""),this.needsUpdate=!0,this}setDefines(t){for(const e of t.entries())this.defines[e[0]]=e[1];return this.needsUpdate=!0,this}setUniforms(t){for(const e of t.entries())this.uniforms[e[0]]=e[1];return this}setExtensions(t){this.extensions={};for(const e of t)this.extensions[e]=!0;return this}get encodeOutput(){return this.defines.ENCODE_OUTPUT!==void 0}set encodeOutput(t){this.encodeOutput!==t&&(t?this.defines.ENCODE_OUTPUT="1":delete this.defines.ENCODE_OUTPUT,this.needsUpdate=!0)}isOutputEncodingEnabled(t){return this.encodeOutput}setOutputEncodingEnabled(t){this.encodeOutput=t}get time(){return this.uniforms.time.value}set time(t){this.uniforms.time.value=t}setDeltaTime(t){this.uniforms.time.value+=t}adoptCameraSettings(t){this.copyCameraSettings(t)}copyCameraSettings(t){t&&(this.uniforms.cameraNear.value=t.near,this.uniforms.cameraFar.value=t.far,t instanceof As?this.defines.PERSPECTIVE_CAMERA="1":delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0)}setSize(t,e){const n=this.uniforms;n.resolution.value.set(t,e),n.texelSize.value.set(1/t,1/e),n.aspect.value=t/e}static get Section(){return _n}};function rN(t,e,n){for(const r of e){const i="$1"+t+r.charAt(0).toUpperCase()+r.slice(1),s=new RegExp("([^\\.])(\\b"+r+"\\b)","g");for(const o of n.entries())o[1]!==null&&n.set(o[0],o[1].replace(s,i))}}function yne(t,e,n){let r=e.getFragmentShader(),i=e.getVertexShader();const s=r!==void 0&&/mainImage/.test(r),o=r!==void 0&&/mainUv/.test(r);if(n.attributes|=e.getAttributes(),r===void 0)throw new Error(`Missing fragment shader (${e.name})`);if(o&&n.attributes&Sa.CONVOLUTION)throw new Error(`Effects that transform UVs are incompatible with convolution effects (${e.name})`);if(!s&&!o)throw new Error(`Could not find mainImage or mainUv function (${e.name})`);{const a=/\w+\s+(\w+)\([\w\s,]*\)\s*{/g,l=n.shaderParts;let c=l.get(_n.FRAGMENT_HEAD)||"",u=l.get(_n.FRAGMENT_MAIN_UV)||"",h=l.get(_n.FRAGMENT_MAIN_IMAGE)||"",p=l.get(_n.VERTEX_HEAD)||"",m=l.get(_n.VERTEX_MAIN_SUPPORT)||"";const g=new Set,v=new Set;if(o&&(u+=` ${t}MainUv(UV); +`,n.uvTransformation=!0),i!==null&&/mainSupport/.test(i)){const S=/mainSupport *\([\w\s]*?uv\s*?\)/.test(i);m+=` ${t}MainSupport(`,m+=S?`vUv); +`:`); +`;for(const E of i.matchAll(/(?:varying\s+\w+\s+([\S\s]*?);)/g))for(const T of E[1].split(/\s*,\s*/))n.varyings.add(T),g.add(T),v.add(T);for(const E of i.matchAll(a))v.add(E[1])}for(const S of r.matchAll(a))v.add(S[1]);for(const S of e.defines.keys())v.add(S.replace(/\([\w\s,]*\)/g,""));for(const S of e.uniforms.keys())v.add(S);v.delete("while"),v.delete("for"),v.delete("if"),e.uniforms.forEach((S,E)=>n.uniforms.set(t+E.charAt(0).toUpperCase()+E.slice(1),S)),e.defines.forEach((S,E)=>n.defines.set(t+E.charAt(0).toUpperCase()+E.slice(1),S));const y=new Map([["fragment",r],["vertex",i]]);rN(t,v,n.defines),rN(t,v,y),r=y.get("fragment"),i=y.get("vertex");const _=e.blendMode;if(n.blendModes.set(_.blendFunction,_),s){e.inputColorSpace!==null&&e.inputColorSpace!==n.colorSpace&&(h+=e.inputColorSpace===pr?`color0 = sRGBTransferOETF(color0); + `:`color0 = sRGBToLinear(color0); + `),e.outputColorSpace!==da?n.colorSpace=e.outputColorSpace:e.inputColorSpace!==null&&(n.colorSpace=e.inputColorSpace);const S=/MainImage *\([\w\s,]*?depth[\w\s,]*?\)/;h+=`${t}MainImage(color0, UV, `,n.attributes&Sa.DEPTH&&S.test(r)&&(h+="depth, ",n.readDepth=!0),h+=`color1); + `;const E=t+"BlendOpacity";n.uniforms.set(E,_.opacity),h+=`color0 = blend${_.blendFunction}(color0, color1, ${E}); + + `,c+=`uniform float ${E}; + +`}if(c+=r+` +`,i!==null&&(p+=i+` +`),l.set(_n.FRAGMENT_HEAD,c),l.set(_n.FRAGMENT_MAIN_UV,u),l.set(_n.FRAGMENT_MAIN_IMAGE,h),l.set(_n.VERTEX_HEAD,p),l.set(_n.VERTEX_MAIN_SUPPORT,m),e.extensions!==null)for(const S of e.extensions)n.extensions.add(S)}}var xne=class extends Wo{constructor(t,...e){super("EffectPass"),this.fullscreenMaterial=new vne(null,null,null,t),this.listener=n=>this.handleEvent(n),this.effects=[],this.setEffects(e),this.skipRendering=!1,this.minTime=1,this.maxTime=Number.POSITIVE_INFINITY,this.timeScale=1}set mainScene(t){for(const e of this.effects)e.mainScene=t}set mainCamera(t){this.fullscreenMaterial.copyCameraSettings(t);for(const e of this.effects)e.mainCamera=t}get encodeOutput(){return this.fullscreenMaterial.encodeOutput}set encodeOutput(t){this.fullscreenMaterial.encodeOutput=t}get dithering(){return this.fullscreenMaterial.dithering}set dithering(t){const e=this.fullscreenMaterial;e.dithering=t,e.needsUpdate=!0}setEffects(t){for(const e of this.effects)e.removeEventListener("change",this.listener);this.effects=t.sort((e,n)=>n.attributes-e.attributes);for(const e of this.effects)e.addEventListener("change",this.listener)}updateMaterial(){const t=new kte;let e=0;for(const o of this.effects)if(o.blendMode.blendFunction===Qt.DST)t.attributes|=o.getAttributes()&Sa.DEPTH;else{if(t.attributes&o.getAttributes()&Sa.CONVOLUTION)throw new Error(`Convolution effects cannot be merged (${o.name})`);yne("e"+e++,o,t)}let n=t.shaderParts.get(_n.FRAGMENT_HEAD),r=t.shaderParts.get(_n.FRAGMENT_MAIN_IMAGE),i=t.shaderParts.get(_n.FRAGMENT_MAIN_UV);const s=/\bblend\b/g;for(const o of t.blendModes.values())n+=o.getShaderCode().replace(s,`blend${o.blendFunction}`)+` +`;t.attributes&Sa.DEPTH?(t.readDepth&&(r=`float depth = readDepth(UV); + + `+r),this.needsDepthTexture=this.getDepthTexture()===null):this.needsDepthTexture=!1,t.colorSpace===pr&&(r+=`color0 = sRGBToLinear(color0); + `),t.uvTransformation?(i=`vec2 transformedUv = vUv; +`+i,t.defines.set("UV","transformedUv")):t.defines.set("UV","vUv"),t.shaderParts.set(_n.FRAGMENT_HEAD,n),t.shaderParts.set(_n.FRAGMENT_MAIN_IMAGE,r),t.shaderParts.set(_n.FRAGMENT_MAIN_UV,i);for(const[o,a]of t.shaderParts)a!==null&&t.shaderParts.set(o,a.trim().replace(/^#/,` +#`));this.skipRendering=e===0,this.needsSwap=!this.skipRendering,this.fullscreenMaterial.setShaderData(t)}recompile(){this.updateMaterial()}getDepthTexture(){return this.fullscreenMaterial.depthBuffer}setDepthTexture(t,e=th){this.fullscreenMaterial.depthBuffer=t,this.fullscreenMaterial.depthPacking=e;for(const n of this.effects)n.setDepthTexture(t,e)}render(t,e,n,r,i){for(const s of this.effects)s.update(t,e,r);if(!this.skipRendering||this.renderToScreen){const s=this.fullscreenMaterial;s.inputBuffer=e.texture,s.time+=r*this.timeScale,t.setRenderTarget(this.renderToScreen?null:n),t.render(this.scene,this.camera)}}setSize(t,e){this.fullscreenMaterial.setSize(t,e);for(const n of this.effects)n.setSize(t,e)}initialize(t,e,n){this.renderer=t;for(const r of this.effects)r.initialize(t,e,n);this.updateMaterial(),n!==void 0&&n!==wi&&(this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}dispose(){super.dispose();for(const t of this.effects)t.removeEventListener("change",this.listener),t.dispose()}handleEvent(t){switch(t.type){case"change":this.recompile();break}}},Sne=class extends Wo{constructor(t,e,{renderTarget:n,resolutionScale:r=1,width:i=Ef.AUTO_SIZE,height:s=Ef.AUTO_SIZE,resolutionX:o=i,resolutionY:a=s}={}){super("NormalPass"),this.needsSwap=!1,this.renderPass=new HP(t,e,new qH);const l=this.renderPass;l.ignoreBackground=!0,l.skipShadowMapUpdate=!0;const c=l.getClearPass();c.overrideClearColor=new cn(7829503),c.overrideClearAlpha=1,this.renderTarget=n,this.renderTarget===void 0&&(this.renderTarget=new Ps(1,1,{minFilter:vr,magFilter:vr}),this.renderTarget.texture.name="NormalPass.Target");const u=this.resolution=new Ef(this,o,a,r);u.addEventListener("change",h=>this.setSize(u.baseWidth,u.baseHeight))}set mainScene(t){this.renderPass.mainScene=t}set mainCamera(t){this.renderPass.mainCamera=t}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}getResolutionScale(){return this.resolution.scale}setResolutionScale(t){this.resolution.scale=t}render(t,e,n,r,i){const s=this.renderToScreen?null:this.renderTarget;this.renderPass.render(t,s,s)}setSize(t,e){const n=this.resolution;n.setBaseSize(t,e),this.renderTarget.setSize(n.width,n.height)}};let Gd;function Ene(){var t;if(Gd!==void 0)return Gd;try{let e;const n=document.createElement("canvas");return Gd=!!(window.WebGL2RenderingContext&&(e=n.getContext("webgl2"))),e&&((t=e.getExtension("WEBGL_lose_context"))==null||t.loseContext()),Gd}catch{return Gd=!1}}const wne=Ne.createContext(null),iN=t=>(t.getAttributes()&Sa.CONVOLUTION)===Sa.CONVOLUTION,Tne=Co.memo(Ne.forwardRef(({children:t,camera:e,scene:n,resolutionScale:r,enabled:i=!0,renderPriority:s=1,autoClear:o=!0,depthBuffer:a,enableNormalPass:l,stencilBuffer:c,multisampling:u=8,frameBufferType:h=rd},p)=>{const{gl:m,scene:g,camera:v,size:y}=_a(),_=n||g,S=e||v,[E,T,N]=Ne.useMemo(()=>{const M=Ene(),I=new Nte(m,{depthBuffer:a,stencilBuffer:c,multisampling:u>0&&M?u:0,frameBufferType:h});I.addPass(new HP(_,S));let U=null,L=null;return l&&(L=new Sne(_,S),L.enabled=!1,I.addPass(L),r!==void 0&&M&&(U=new mne({normalBuffer:L.texture,resolutionScale:r}),U.enabled=!1,I.addPass(U))),[I,L,U]},[S,m,a,c,u,h,_,l,r]);Ne.useEffect(()=>E==null?void 0:E.setSize(y.width,y.height),[E,y]),Lv((M,I)=>{if(i){const U=m.autoClear;m.autoClear=o,c&&!o&&m.clearStencil(),E.render(I),m.autoClear=U}},i?s:0);const R=Ne.useRef(null),C=AG(R);Ne.useLayoutEffect(()=>{const M=[];if(R.current&&C.current&&E){const I=C.current.objects;for(let U=0;U{for(const I of M)E==null||E.removePass(I);T&&(T.enabled=!1),N&&(N.enabled=!1)}},[E,t,S,T,N,C]),Ne.useEffect(()=>{const M=m.toneMapping;return m.toneMapping=va,()=>{m.toneMapping=M}},[]);const O=Ne.useMemo(()=>({composer:E,normalPass:T,downSamplingPass:N,resolutionScale:r,camera:S,scene:_}),[E,T,N,r,S,_]);return Ne.useImperativeHandle(p,()=>E,[E]),ve.jsx(wne.Provider,{value:O,children:ve.jsx("group",{ref:R,children:t})})}));let bne=0;const sN=new WeakMap,Ane=(t,e)=>Co.forwardRef(function({blendFunction:r=void 0,opacity:i=void 0,...s},o){let a=sN.get(t);if(!a){const u=`@react-three/postprocessing/${t.name}-${bne++}`;mT({[u]:t}),sN.set(t,a=u)}const l=_a(u=>u.camera),c=Co.useMemo(()=>{var u,h;return[...(u=void 0)!=null?u:[],...(h=s.args)!=null?h:[{...e,...s}]]},[JSON.stringify(s)]);return ve.jsx(a,{camera:l,"blendMode-blendFunction":r,"blendMode-opacity-value":i,...s,ref:o,args:c})});function YS(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(c){try{l(r.next(c))}catch(u){s(u)}}function a(c){try{l(r.throw(c))}catch(u){s(u)}}function l(c){var u;c.done?i(c.value):(u=c.value,u instanceof n?u:new n(function(h){h(u)})).then(o,a)}l((r=r.apply(t,[])).next())})}const Mne=["geforce 320m","geforce 8600","geforce 8600m gt","geforce 8800 gs","geforce 8800 gt","geforce 9400","geforce 9400m g","geforce 9400m","geforce 9600m gt","geforce 9600m","geforce fx go5200","geforce gt 120","geforce gt 130","geforce gt 330m","geforce gtx 285","google swiftshader","intel g41","intel g45","intel gma 4500mhd","intel gma x3100","intel hd 3000","intel q45","legacy","mali-2","mali-3","mali-4","quadro fx 1500","quadro fx 4","quadro fx 5","radeon hd 2400","radeon hd 2600","radeon hd 4670","radeon hd 4850","radeon hd 4870","radeon hd 5670","radeon hd 5750","radeon hd 6290","radeon hd 6300","radeon hd 6310","radeon hd 6320","radeon hd 6490m","radeon hd 6630m","radeon hd 6750m","radeon hd 6770m","radeon hd 6970m","sgx 543","sgx543"];function oN(t){return t=t.toLowerCase().replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i,"$1").replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g,"").replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/,"$1")}const GP=typeof window>"u",ca=(()=>{if(GP)return;const{userAgent:t,platform:e,maxTouchPoints:n}=window.navigator,r=/(iphone|ipod|ipad)/i.test(t),i=e==="iPad"||e==="MacIntel"&&n>0&&!window.MSStream;return{isIpad:i,isMobile:/android/i.test(t)||r||i,isSafari12:/Version\/12.+Safari/.test(t),isFirefox:/Firefox/.test(t)}})();function Cne(t,e,n){if(!n)return[e];const r=function(c){const u=` + precision highp float; + attribute vec3 aPosition; + varying float vvv; + void main() { + vvv = 0.31622776601683794; + gl_Position = vec4(aPosition, 1.0); + } + `,h=` + precision highp float; + varying float vvv; + void main() { + vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * vvv; + enc = fract(enc); + enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); + gl_FragColor = enc; + } + `,p=c.createShader(35633),m=c.createShader(35632),g=c.createProgram();if(!(m&&p&&g))return;c.shaderSource(p,u),c.shaderSource(m,h),c.compileShader(p),c.compileShader(m),c.attachShader(g,p),c.attachShader(g,m),c.linkProgram(g),c.detachShader(g,p),c.detachShader(g,m),c.deleteShader(p),c.deleteShader(m),c.useProgram(g);const v=c.createBuffer();c.bindBuffer(34962,v),c.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const y=c.getAttribLocation(g,"aPosition");c.vertexAttribPointer(y,3,5126,!1,0,0),c.enableVertexAttribArray(y),c.clearColor(1,1,1,1),c.clear(16384),c.viewport(0,0,1,1),c.drawArrays(4,0,3);const _=new Uint8Array(4);return c.readPixels(0,0,1,1,6408,5121,_),c.deleteProgram(g),c.deleteBuffer(v),_.join("")}(t),i="801621810",s="8016218135",o="80162181161",a=ca!=null&&ca.isIpad?[["a7",o,12],["a8",s,15],["a8x",s,15],["a9",s,15],["a9x",s,15],["a10",s,15],["a10x",s,15],["a12",i,15],["a12x",i,15],["a12z",i,15],["a14",i,15],["a15",i,15],["m1",i,15],["m2",i,15]]:[["a7",o,12],["a8",s,12],["a9",s,15],["a10",s,15],["a11",i,15],["a12",i,15],["a13",i,15],["a14",i,15],["a15",i,15],["a16",i,15],["a17",i,15]];let l;return r==="80162181255"?l=a.filter(([,,c])=>c>=14):(l=a.filter(([,c])=>c===r),l.length||(l=a)),l.map(([c])=>`apple ${c} gpu`)}class aN extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const ZS=[],lN=[];function Rne(t,e){if(t===e)return 0;const n=t;t.length>e.length&&(t=e,e=n);let r=t.length,i=e.length;for(;r>0&&t.charCodeAt(~-r)===e.charCodeAt(~-i);)r--,i--;let s,o=0;for(;oc?l>c?c+1:l:l>a?a+1:l;return c}function Nne(t){return t!=null}const kne=({mobileTiers:t=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:n={},glContext:r,failIfMajorPerformanceCaveat:i=!1,benchmarksURL:s="https://unpkg.com/detect-gpu@5.0.56/dist/benchmarks"}={})=>YS(void 0,void 0,void 0,function*(){const o={};if(GP)return{tier:0,type:"SSR"};const{isIpad:a=!!(ca!=null&&ca.isIpad),isMobile:l=!!(ca!=null&&ca.isMobile),screenSize:c=window.screen,loadBenchmarks:u=N=>YS(void 0,void 0,void 0,function*(){const R=yield fetch(`${s}/${N}`).then(C=>C.json());if(parseInt(R.shift().split(".")[0],10)<4)throw new aN("Detect GPU benchmark data is out of date. Please update to version 4x");return R})}=n;let{renderer:h}=n;const p=(N,R,C,O,M)=>({device:M,fps:O,gpu:C,isMobile:l,tier:N,type:R});let m,g="";if(h)h=oN(h),m=[h];else{const N=r||function(C,O=!1){const M={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:O,powerPreference:"high-performance",stencil:!1};C&&delete M.powerPreference;const I=window.document.createElement("canvas"),U=I.getContext("webgl",M)||I.getContext("experimental-webgl",M);return U??void 0}(ca==null?void 0:ca.isSafari12,i);if(!N)return p(0,"WEBGL_UNSUPPORTED");const R=ca!=null&&ca.isFirefox?null:N.getExtension("WEBGL_debug_renderer_info");if(h=R?N.getParameter(R.UNMASKED_RENDERER_WEBGL):N.getParameter(N.RENDERER),!h)return p(1,"FALLBACK");g=h,h=oN(h),m=function(C,O,M){return O==="apple gpu"?Cne(C,O,M):[O]}(N,h,l)}const v=(yield Promise.all(m.map(function(N){var R;return YS(this,void 0,void 0,function*(){const C=(ge=>{const Q=l?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const re of Q)if(ge.includes(re))return re})(N);if(!C)return;const O=`${l?"m":"d"}-${C}${a?"-ipad":""}.json`,M=o[O]=(R=o[O])!==null&&R!==void 0?R:u(O);let I;try{I=yield M}catch(ge){if(ge instanceof aN)throw ge;return}const U=function(ge){var Q;const re=(ge=ge.replace(/\([^)]+\)/,"")).match(/\d+/)||ge.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(Q=re==null?void 0:re.join("").replace(/\W|amd/g,""))!==null&&Q!==void 0?Q:""}(N);let L=I.filter(([,ge])=>ge===U);L.length||(L=I.filter(([ge])=>ge.includes(N)));const P=L.length;if(P===0)return;const b=N.split(/[.,()\[\]/\s]/g).sort().filter((ge,Q,re)=>Q===0||ge!==re[Q-1]).join(" ");let H,[V,,,,B]=P>1?L.map(ge=>[ge,Rne(b,ge[2])]).sort(([,ge],[,Q])=>ge-Q)[0][0]:L[0],z=Number.MAX_VALUE;const{devicePixelRatio:W}=window,K=c.width*W*c.height*W;for(const ge of B){const[Q,re]=ge,we=Q*re,Ae=Math.abs(K-we);AeN===C?R-O:N-C);if(!v.length){const N=Mne.find(R=>h.includes(R));return N?p(0,"BLOCKLISTED",N):p(1,"FALLBACK",`${h} (${g})`)}const[,y,_,S]=v[0];if(y===-1)return p(0,"BLOCKLISTED",_,y,S);const E=l?t:e;let T=0;for(let N=0;N=E[N]&&(T=N);return p(T,"BENCHMARK",_,y,S)});var WP={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(bo,function(){var n=function(){function r(m){return o.appendChild(m.dom),m}function i(m){for(var g=0;gl+1e3&&(u.update(1e3*c/(m-l),100),l=m,c=0,p)){var g=performance.memory;p.update(g.usedJSHeapSize/1048576,g.jsHeapSizeLimit/1048576)}return m},update:function(){a=this.end()},domElement:o,setMode:i}};return n.Panel=function(r,i,s){var o=1/0,a=0,l=Math.round,c=l(window.devicePixelRatio||1),u=80*c,h=48*c,p=3*c,m=2*c,g=3*c,v=15*c,y=74*c,_=30*c,S=document.createElement("canvas");S.width=u,S.height=h,S.style.cssText="width:80px;height:48px";var E=S.getContext("2d");return E.font="bold "+9*c+"px Helvetica,Arial,sans-serif",E.textBaseline="top",E.fillStyle=s,E.fillRect(0,0,u,h),E.fillStyle=i,E.fillText(r,p,m),E.fillRect(g,v,y,_),E.fillStyle=s,E.globalAlpha=.9,E.fillRect(g,v,y,_),{dom:S,update:function(T,N){o=Math.min(o,T),a=Math.max(a,T),E.fillStyle=s,E.globalAlpha=1,E.fillRect(0,0,u,v),E.fillStyle=i,E.fillText(l(T)+" "+r+" ("+l(o)+"-"+l(a)+")",p,m),E.drawImage(S,g+c,v,y-c,_,g,v,y-c,_),E.fillRect(g+y-c,v,c,_),E.fillStyle=s,E.globalAlpha=.9,E.fillRect(g+y-c,v,c,l((1-T/N)*_))}}},n})})(WP);var Ine=WP.exports;const One=Pl(Ine),Ca=!!JSON.parse("false"),Lne=!!JSON.parse("false"),Pne=!!JSON.parse("false"),Dne=!!JSON.parse("false");JSON.parse("false");const Une=!!JSON.parse("false"),Fne=` +vec3 halftone(vec3 texcolor, vec2 st, float frequency) { + float n = 0.1 * snoise(st * 200.0); // Fractal noise + n += 0.05 * snoise(st * 400.0); + n += 0.025 * snoise(st * 800.0); + + // Perform a rough RGB-to-CMYK conversion + vec4 cmyk; + // CMY = 1-RGB + cmyk.xyz = 1.0 - texcolor; + // Black generation: K = min(C,M,Y) + cmyk.w = min(cmyk.x, min(cmyk.y, cmyk.z)); + // Grey component replacement: subtract K from CMY + cmyk.xyz -= cmyk.w; + + // K based modifier + float flex = pow(cmyk.w, 3.11); + + // Distance to nearest point in a grid of + // (frequency x frequency) points over the unit square + + float t = 0.1 + 0.1 * n + 0.11 * flex + 0.1 * cmyk.y; + + // K component: 45 degrees screen angle + vec2 Kst = frequency * mat2(0.707, -0.707, 0.707, 0.707) * st; + vec2 Kuv = 2.0 * fract(Kst) - 1.0; + float k = aastep(0.0, sqrt(cmyk.w) + t - length(Kuv) + n); + + // C component: 15 degrees screen angle + vec2 Cst = frequency*mat2(0.966, -0.259, 0.259, 0.966) * st; + vec2 Cuv = 2.0 * fract(Cst) - 1.0; + float c = aastep(0.0, sqrt(cmyk.x) + t - length(Cuv) + n); + + // M component: -15 degrees screen angle + vec2 Mst = frequency * mat2(0.966, 0.259, -0.259, 0.966) * st; + vec2 Muv = 2.0 * fract(Mst) - 1.0; + float m = aastep(0.0, sqrt(cmyk.y) + t - length(Muv) + n); + + // Y component: 0 degrees screen angle + vec2 Yst = frequency * st; // 0 deg + vec2 Yuv = 2.0 * fract(Yst) - 1.0; + float y = aastep(0.0, sqrt(cmyk.z) + t - length(Yuv) + n); + + // CMY screen in RGB + vec3 black = vec3(n + 0.01); + vec3 rgbscreen = 1.0 - vec3(c,m,y) + n; + + // Blend in K for final color + vec3 factor = mix(rgbscreen, black, 1.1 * k + 0.3 * n); + + // Blend with og color + return mix(factor, texcolor, 0.777); +} + +vec3 halftone(vec3 texcolor, vec2 st) { + return halftone(texcolor, st, 412.321); +} +`,Bne=` +float blendLighten(float base, float blend) { + return max(blend,base); +} + +vec3 blendLighten(vec3 base, vec3 blend) { + return vec3(blendLighten(base.r,blend.r),blendLighten(base.g,blend.g),blendLighten(base.b,blend.b)); +} + +vec3 blendLighten(vec3 base, vec3 blend, float opacity) { + return (blendLighten(base, blend) * opacity + base * (1.0 - opacity)); +} + +float blendDarken(float base, float blend) { + return min(blend,base); +} + +vec3 blendDarken(vec3 base, vec3 blend) { + return vec3(blendDarken(base.r,blend.r),blendDarken(base.g,blend.g),blendDarken(base.b,blend.b)); +} + +vec3 blendDarken(vec3 base, vec3 blend, float opacity) { + return (blendDarken(base, blend) * opacity + base * (1.0 - opacity)); +} +`,zne=` +float aastep(float threshold, float value) { + float afwidth = length(vec2(dFdx(value), dFdy(value))) * 0.70710678118654757; + return smoothstep(threshold-afwidth, threshold+afwidth, value); +} +`,Vne=` +// +// Description : Array and textureless GLSL 2D simplex noise function. +// Author : Ian McEwan, Ashima Arts. +// Maintainer : ijm +// Lastmod : 20110822 (ijm) +// License : Copyright (C) 2011 Ashima Arts. All rights reserved. +// Distributed under the MIT License. See LICENSE file. +// https://github.com/ashima/webgl-noise +// + +vec3 mod289(vec3 x) { + return x - floor(x * (1.0 / 289.0)) * 289.0; +} + +vec2 mod289(vec2 x) { + return x - floor(x * (1.0 / 289.0)) * 289.0; +} + +vec3 permute(vec3 x) { + return mod289(((x*34.0)+1.0)*x); +} + +float snoise(vec2 v) { + const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0 + 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) + -0.577350269189626, // -1.0 + 2.0 * C.x + 0.024390243902439); // 1.0 / 41.0 +// First corner + vec2 i = floor(v + dot(v, C.yy) ); + vec2 x0 = v - i + dot(i, C.xx); + +// Other corners + vec2 i1; + //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0 + //i1.y = 1.0 - i1.x; + i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); + // x0 = x0 - 0.0 + 0.0 * C.xx ; + // x1 = x0 - i1 + 1.0 * C.xx ; + // x2 = x0 - 1.0 + 2.0 * C.xx ; + vec4 x12 = x0.xyxy + C.xxzz; + x12.xy -= i1; + +// Permutations + i = mod289(i); // Avoid truncation effects in permutation + vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 )) + + i.x + vec3(0.0, i1.x, 1.0 )); + + vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0); + m = m*m ; + m = m*m ; + +// Gradients: 41 points uniformly over a line, mapped onto a diamond. +// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) + + vec3 x = 2.0 * fract(p * C.www) - 1.0; + vec3 h = abs(x) - 0.5; + vec3 ox = floor(x + 0.5); + vec3 a0 = x - ox; + +// Normalise gradients implicitly by scaling m +// Approximation of: m *= inversesqrt( a0*a0 + h*h ); + m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ); + +// Compute final noise value at P + vec3 g; + g.x = a0.x * x0.x + h.x * x0.y; + g.yz = a0.yz * x12.xz + h.yz * x12.yw; + return 130.0 * dot(m, g); +} +`,Hne=` +#ifdef ASPECT_CORRECTION + uniform float scale; +#else + uniform mat3 uvTransform; +#endif + +varying vec2 vUv2; + +void mainSupport(const in vec2 uv) { + #ifdef ASPECT_CORRECTION + vUv2 = uv * vec2(aspect, 1.0) * scale; + #else + vUv2 = (uvTransform * vec3(uv, 1.0)).xy; + #endif +} +`,Gne=` +uniform float viewheight; +uniform sampler2D splat; + +${Bne} +${zne} +${Vne} +${Fne} + +float rectdistance(vec2 uv) { + vec2 tl = vec2(-1.0); + vec2 br = vec2(1.0); + vec2 d = max(tl - uv, uv - br); + return abs(length(max(vec2(0.0), d)) + min(0.0, max(d.x, d.y))); +} + +vec2 bendy(const in vec2 xn, float dn, float sn) { + // config + float distortion = 0.0173 + dn; // 0.0173, 0.511 + float scale = 0.991 + sn; // 1.0, 0.7 + // calc + vec3 xDistorted = vec3((1.0 + vec2(distortion, distortion) * dot(xn, xn)) * xn, 1.0); + mat3 kk = mat3( + vec3(1.0, 0.0, 0.0), + vec3(0.0, 1.0, 0.0), + vec3(0.0, 0.0, 1.0) + ); + return (kk * xDistorted).xy * scale; +} + +void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) { + #ifdef UV_TRANSFORM + vec4 bright = texture2D(splat, vUv2); + vec4 dark = texture2D(splat, 1.0 - vUv2); + #else + vec4 bright = texture2D(splat, uv); + vec4 dark = texture2D(splat, 1.0 - uv); + #endif + + float n = 0.1 * snoise(uv.st * 200.0); // Fractal noise + n += 0.05 * snoise(uv.st * 400.0); + n += 0.025 * snoise(uv.st * 800.0); + + vec2 xn = 2.0 * (uv.st - 0.5); + vec2 edge = bendy(xn, 0.0091 * n, 0.0011 * -n); + vec2 bent = edge.xy * 0.5 + 0.5; + + float dx = rectdistance(xn); + float bx = rectdistance(edge); + + // apply shape + float doot = max(abs(edge.x), abs(edge.y)); + if (doot < 1.0) { + // display + outputColor = texture2D(inputBuffer, bent); + + // apply scratches + outputColor.rgb = blendLighten(outputColor.rgb, bright.rgb, 0.111); + outputColor.rgb = blendDarken(outputColor.rgb, dark.rgb, 0.111); + + // apply halftones + outputColor.rgb = halftone(outputColor.rgb, uv.st); + + } else if (doot > 1.004) { + // display shell + // rbgb 205 205 193 + vec3 matte = vec3(205.0 / 255.0, 205.0 / 255.0, 193.0 / 255.0); + vec3 dkmatte = mix(matte, vec3(0.0), 0.5); + float mx = pow(1.0 - bx, 16.0) + n; + outputColor = vec4(mix(matte, dkmatte, mx), inputColor.a); + + } else { + // border + outputColor = vec4(mix(vec3(0.0), outputColor.rgb, 0.5), inputColor.a); + } + + // apply inner shade + if (doot >= 0.5 && doot < 1.0) { + float sh = clamp(0.0, 1.0, 1.0 - bx - 0.7); + vec3 shade = mix(outputColor.rgb, vec3(0.0), pow(sh, 4.0)); + outputColor = vec4(shade, inputColor.a); + } + + // apply outer shade + if (doot >= 0.97) { + float sh = clamp(0.0, 1.0, bx * 24.0); + vec3 dkout = mix(vec3(0.0), outputColor.rgb, 0.81); + vec3 shade = mix(dkout, outputColor.rgb, sh); + outputColor = vec4(shade, inputColor.a); + } +} +`;class Wne extends YE{constructor({splat:e,viewheight:n}={}){super("CRTShapeEffect",Gne,{blendFunction:Qt.NORMAL,attributes:Sa.CONVOLUTION,defines:new Map([["TEXEL","texel"],["TEXTURE_PRECISION_HIGH","1"]]),uniforms:new Map([["splat",new Mn(e)],["viewheight",new Mn(n??128)]])})}get splat(){var e;return(e=this.uniforms.get("splat"))==null?void 0:e.value}set splat(e){const{splat:n,uniforms:r,defines:i}=this,s=r.get("splat"),o=r.get("uvTransform");n!==e&&s&&o&&(s.value=e,o.value=e.matrix,i.delete("TEXTURE_PRECISION_HIGH"),e!==null&&(e.matrixAutoUpdate?(i.set("UV_TRANSFORM","1"),this.setVertexShader(Hne)):(i.delete("UV_TRANSFORM"),this.setVertexShader(null)),e.type!==wi&&i.set("TEXTURE_PRECISION_HIGH","1"),(n===null||(n==null?void 0:n.type)!==e.type)&&this.setChanged()))}getTexture(){return this.splat}setTexture(e){this.splat=e}get aspectCorrection(){return this.defines.has("ASPECT_CORRECTION")}set aspectCorrection(e){this.aspectCorrection!==e&&(e?this.defines.set("ASPECT_CORRECTION","1"):this.defines.delete("ASPECT_CORRECTION"),this.setChanged())}get uvTransform(){const e=this.splat;return!!(e!=null&&e.matrixAutoUpdate)}set uvTransform(e){const n=this.splat;Z(n)&&(n.matrixAutoUpdate=e)}setTextureSwizzleRGBA(e,n=e,r=e,i=e){const s="rgba";let o="";(e!==x0.RED||n!==x0.GREEN||r!==x0.BLUE||i!==x0.ALPHA)&&(o=[".",s[e],s[n],s[r],s[i]].join("")),this.defines.set("TEXEL","texel"+o),this.setChanged()}update(){var e;(e=this.splat)!=null&&e.matrixAutoUpdate&&this.splat.updateMatrix()}}const jne=Ane(Wne),$ne="/assets/scratches-BBiC0fzb.gif",JS=t=>t===Object(t)&&!Array.isArray(t)&&typeof t!="function";function Ob(t,e){const n=_a(s=>s.gl),r=Jp(dT,JS(t)?Object.values(t):t);return Ne.useLayoutEffect(()=>{e==null||e(r)},[e,r]),Ne.useEffect(()=>{if("initTexture"in n){let s=[];Array.isArray(r)?s=r:r instanceof or?s=[r]:JS(r)&&(s=Object.values(r)),s.forEach(o=>{o instanceof or&&n.initTexture(o)})}},[n,r]),Ne.useMemo(()=>{if(JS(t)){const s={};let o=0;for(const a in t)s[a]=r[o++];return s}else return r},[t,r])}Ob.preload=t=>Jp.preload(dT,t);Ob.clear=t=>Jp.clear(dT,t);function qne(t){const e=new Set;function n(r){e.has(r.id)||(e.add(r.id),Yt.invoke(r))}return rh("forward",["all"],r=>{e.has(r.id)||(e.add(r.id),t(r))}),n}function Xne(t){return new Worker("/assets/instance-BmWSmEhW.js",{name:t==null?void 0:t.name})}const Kne=rh("gadgetclient",[],t=>{const{desync:e,gadget:n}=ss.getState();switch(t.target){case"reset":t.player===n.player&&ss.setState({desync:!1,gadget:t.data});break;case"patch":t.player===n.player&&!e&&ss.setState(r=>{try{const{newDocument:i}=Pv(r.gadget,t.data,!0,!1);return{...r,gadget:i}}catch(i){i instanceof _T&&(ss.setState({desync:!0}),Kne.reply(t,"desync",void 0,t.player))}return r});break}});function Ip(){return Ip=Object.assign||function(t){for(var e=1;e0}function JE(t){a_++;try{return t()}finally{a_--,a_===0&&ere()}}var QE=!1;function XP(){return QE}function KP(t){QE=!0;try{t()}finally{QE=!1}}function Qne(t){return function(){return KP(t)}}var ew=[];function ere(){var t=[].concat(ew);ew=[],YP(t)}function YP(t){var e=new Set;t.forEach(function(n){var r;(n.type==="add"||n.type==="delete")&&n.observable[Fr].connections.iterate.forEach(function(i){e.add(i)}),(r=n.observable[Fr].connections.byKey.get(n.key))==null||r.forEach(function(i){e.add(i)})}),e.forEach(function(n){n.trigger()})}function S0(t){if(qP()){ew.push(t);return}YP([t])}function cN(t,e){if(t.type==="iterate")t.observable[Fr].connections.iterate.add(e);else{var n=t.observable[Fr].connections.byKey.get(t.key);n||(n=new Set,t.observable[Fr].connections.byKey.set(t.key,n)),n.add(e)}}function E0(t,e){if(!XP()){var n=$P();n&&(cN(t,n),n.registerConnection(t)),e&&(cN(t,e),e.registerConnection(t))}}var Pb=Symbol("$skipreactive"),Fr=Symbol("$reactive"),co=Symbol("$reactiveproxy");function Sm(t,e){return!!(t&&t[co]&&t[co].implicitObserver===e)}function Db(t){return t[Pb]=!0,t}function ZP(t){return!!(t&&!Sm(t)&&t[Fr])}function tw(t,e,n){if(n===void 0&&(n=!1),t[Pb]||Sm(t,e))return t;var r=tre(t,n);if(!e)return r;var i=r[Fr].proxiesWithImplicitObserver.get(e);if(!i){var s={implicitObserver:e};Object.setPrototypeOf(s,JP),i=new Proxy(r[Fr].raw,s),r[Fr].proxiesWithImplicitObserver.set(e,i)}return i}var jf=tw;function tre(t,e){if(e===void 0&&(e=!1),Sm(t))return t;if(ZP(t))return t[Fr].proxy;if(t[Fr]||t[co])throw new Error("unexpected");var n={connections:{iterate:new Set,byKey:new Map},proxy:{},raw:t,proxiesWithImplicitObserver:new Map,shallow:e};Object.defineProperty(t,Fr,{enumerable:!1,writable:!0,configurable:!0,value:n});var r=new Proxy(t,JP);return n.proxy=r,r}var JP={has:function(e,n){var r=Reflect.has(e,n);return typeof n=="symbol"||E0({observable:e,key:n,type:"has"},this.implicitObserver),r},get:function(e,n,r){if(n===co)return{implicitObserver:this.implicitObserver};var i=Reflect.get(e,n,r);if(typeof n=="symbol")return n.toString()==="Symbol($reactiveproxy)"&&console.error("warning, Symbol($reactiveproxy) passed, but does not match $reactiveproxy. Multiple Reactive libraries loaded?"),i;if(n==="length"&&Array.isArray(e)?E0({observable:e,type:"iterate"},this.implicitObserver):E0({observable:e,key:n,type:"get"},this.implicitObserver),ZP(i))return tw(i,this.implicitObserver);if(e[Fr].shallow)return i;if(typeof i=="object"&&i!==null&&!Sm(i,this.implicitObserver)&&!Object.isFrozen(i)){var s=Reflect.getOwnPropertyDescriptor(e,n);if((!s||!(s.writable===!1&&s.configurable===!1))&&(jP()||this.implicitObserver))return tw(i,this.implicitObserver)}return i},ownKeys:function(e){return E0({observable:e,type:"iterate"},this.implicitObserver),Reflect.ownKeys(e)},set:function(e,n,r,i){return JE(function(){if(typeof n=="symbol")return Reflect.set(e,n,r,i);var s=Object.hasOwnProperty.call(e,n),o=Reflect.get(e,n,i),a=Reflect.set(e,n,r,i);if(!s)S0({observable:e,key:n,value:r,type:"add"});else if(r!==o)if(n==="length"&&Array.isArray(e)){if(!(onew Map,nw=t=>{const e=ko();return t.forEach((n,r)=>{e.set(r,n)}),e},$c=(t,e,n)=>{let r=t.get(e);return r===void 0&&t.set(e,r=n()),r},ore=(t,e)=>{const n=[];for(const[r,i]of t)n.push(e(i,r));return n},are=(t,e)=>{for(const[n,r]of t)if(e(r,n))return!0;return!1},$f=()=>new Set,QS=t=>t[t.length-1],lre=(t,e)=>{for(let n=0;n{this.off(e,r),n(...i)};this.on(e,r)}off(e,n){const r=this._observers.get(e);r!==void 0&&(r.delete(n),r.size===0&&this._observers.delete(e))}emit(e,n){return Lc((this._observers.get(e)||ko()).values()).forEach(r=>r(...n))}destroy(){this._observers=ko()}}const Pc=Math.floor,l_=Math.abs,eD=(t,e)=>tt>e?t:e,tD=t=>t!==0?t<0:1/t<0,uN=1,hN=2,e1=4,t1=8,Op=32,xl=64,Ls=128,xy=31,rw=63,Uu=127,hre=2147483647,nD=Number.MAX_SAFE_INTEGER,fre=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Pc(t)===t),dre=t=>t.toLowerCase(),pre=/^\s*/g,mre=t=>t.replace(pre,""),gre=/([A-Z])/g,fN=(t,e)=>mre(t.replace(gre,n=>`${e}${dre(n)}`)),_re=t=>{const e=unescape(encodeURIComponent(t)),n=e.length,r=new Uint8Array(n);for(let i=0;iLp.encode(t),yre=Lp?vre:_re;let mp=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});mp&&mp.decode(new Uint8Array).length===1&&(mp=null);class Em{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const bc=()=>new Em,xre=t=>{let e=t.cpos;for(let n=0;n{const e=new Uint8Array(xre(t));let n=0;for(let r=0;r{const n=t.cbuf.length;n-t.cpos{const n=t.cbuf.length;t.cpos===n&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(n*2),t.cpos=0),t.cbuf[t.cpos++]=e},iw=Qr,Ht=(t,e)=>{for(;e>Uu;)Qr(t,Ls|Uu&e),e=Pc(e/128);Qr(t,Uu&e)},Ub=(t,e)=>{const n=tD(e);for(n&&(e=-e),Qr(t,(e>rw?Ls:0)|(n?xl:0)|rw&e),e=Pc(e/64);e>0;)Qr(t,(e>Uu?Ls:0)|Uu&e),e=Pc(e/128)},sw=new Uint8Array(3e4),Ere=sw.length/3,wre=(t,e)=>{if(e.length{const n=unescape(encodeURIComponent(e)),r=n.length;Ht(t,r);for(let i=0;i{const n=t.cbuf.length,r=t.cpos,i=eD(n-r,e.length),s=e.length-i;t.cbuf.set(e.subarray(0,i),r),t.cpos+=i,s>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(hh(n*2,s)),t.cbuf.set(e.subarray(i)),t.cpos=s)},yi=(t,e)=>{Ht(t,e.byteLength),Sy(t,e)},Fb=(t,e)=>{Sre(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},bre=(t,e)=>Fb(t,4).setFloat32(0,e,!1),Are=(t,e)=>Fb(t,8).setFloat64(0,e,!1),Mre=(t,e)=>Fb(t,8).setBigInt64(0,e,!1),dN=new DataView(new ArrayBuffer(4)),Cre=t=>(dN.setFloat32(0,t),dN.getFloat32(0)===t),Pp=(t,e)=>{switch(typeof e){case"string":Qr(t,119),wf(t,e);break;case"number":fre(e)&&l_(e)<=hre?(Qr(t,125),Ub(t,e)):Cre(e)?(Qr(t,124),bre(t,e)):(Qr(t,123),Are(t,e));break;case"bigint":Qr(t,122),Mre(t,e);break;case"object":if(e===null)Qr(t,126);else if(cre(e)){Qr(t,117),Ht(t,e.length);for(let n=0;n0&&Ht(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const mN=t=>{t.count>0&&(Ub(t.encoder,t.count===1?t.s:-t.s),t.count>1&&Ht(t.encoder,t.count-2))};class c_{constructor(){this.encoder=new Em,this.s=0,this.count=0}write(e){this.s===e?this.count++:(mN(this),this.count=1,this.s=e)}toUint8Array(){return mN(this),Mo(this.encoder)}}const gN=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Ub(t.encoder,e),t.count>1&&Ht(t.encoder,t.count-2)}};class n1{constructor(){this.encoder=new Em,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(gN(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return gN(this),Mo(this.encoder)}}class Rre{constructor(){this.sarr=[],this.s="",this.lensE=new c_}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new Em;return this.sarr.push(this.s),this.s="",wf(e,this.sarr.join("")),Sy(e,this.lensE.toUint8Array()),Mo(e)}}const Dc=t=>new Error(t),Ea=()=>{throw Dc("Method unimplemented")},Ra=()=>{throw Dc("Unexpected case")},rD=Dc("Unexpected end of array"),iD=Dc("Integer out of Range");class Ey{constructor(e){this.arr=e,this.pos=0}}const fh=t=>new Ey(t),Nre=t=>t.pos!==t.arr.length,kre=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},Ii=t=>kre(t,Gt(t)),qf=t=>t.arr[t.pos++],Gt=t=>{let e=0,n=1;const r=t.arr.length;for(;t.posnD)throw iD}throw rD},Bb=t=>{let e=t.arr[t.pos++],n=e&rw,r=64;const i=(e&xl)>0?-1:1;if(!(e&Ls))return i*n;const s=t.arr.length;for(;t.posnD)throw iD}throw rD},Ire=t=>{let e=Gt(t);if(e===0)return"";{let n=String.fromCodePoint(qf(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(qf(t));else for(;e>0;){const r=e<1e4?e:1e4,i=t.arr.subarray(t.pos,t.pos+r);t.pos+=r,n+=String.fromCodePoint.apply(null,i),e-=r}return decodeURIComponent(escape(n))}},Ore=t=>mp.decode(Ii(t)),Tf=mp?Ore:Ire,zb=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},Lre=t=>zb(t,4).getFloat32(0,!1),Pre=t=>zb(t,8).getFloat64(0,!1),Dre=t=>zb(t,8).getBigInt64(0,!1),Ure=[t=>{},t=>null,Bb,Lre,Pre,Dre,t=>!1,t=>!0,Tf,t=>{const e=Gt(t),n={};for(let r=0;r{const e=Gt(t),n=[];for(let r=0;rUre[127-qf(t)](t);class _N extends Ey{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Nre(this)?this.count=Gt(this)+1:this.count=-1),this.count--,this.s}}class u_ extends Ey{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Bb(this);const e=tD(this.s);this.count=1,e&&(this.s=-this.s,this.count=Gt(this)+2)}return this.count--,this.s}}class r1 extends Ey{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=Bb(this),n=e&1;this.diff=Pc(e/2),this.count=1,n&&(this.count=Gt(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Fre{constructor(e){this.decoder=new u_(e),this.str=Tf(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),n=this.str.slice(this.spos,e);return this.spos=e,n}}const Bre=crypto.getRandomValues.bind(crypto),sD=()=>Bre(new Uint32Array(1))[0],zre="10000000-1000-4000-8000"+-1e11,Vre=()=>zre.replace(/[018]/g,t=>(t^sD()&15>>t/4).toString(16)),vN=t=>new Promise(t);Promise.all.bind(Promise);const yN=t=>t===void 0?null:t;class Hre{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let oD=new Hre,Gre=!0;try{typeof localStorage<"u"&&localStorage&&(oD=localStorage,Gre=!1)}catch{}const Wre=oD,jre=Object.assign,$re=Object.keys,qre=(t,e)=>{for(const n in t)e(t[n],n)},xN=t=>$re(t).length,Xre=t=>{for(const e in t)return!1;return!0},Kre=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},Yre=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Zre=(t,e)=>t===e||xN(t)===xN(e)&&Kre(t,(n,r)=>(n!==void 0||Yre(e,r))&&e[r]===n),Jre=Object.freeze,aD=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&aD(t[e])}return Jre(t)},Vb=(t,e,n=0)=>{try{for(;nt,eie=(t,e)=>e.includes(t);var lD={};const Up=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let ia;const tie=()=>{if(ia===void 0)if(Up){ia=ko();const t=process.argv;let e=null;for(let n=0;n{if(t.length!==0){const[e,n]=t.split("=");ia.set(`--${fN(e,"-")}`,n),ia.set(`-${fN(e,"-")}`,n)}})):ia=ko();return ia},ow=t=>tie().has(t),Z_=t=>yN(Up?lD[t.toUpperCase().replaceAll("-","_")]:Wre.getItem(t)),cD=t=>ow("--"+t)||Z_(t)!==null;cD("production");const nie=Up&&eie(lD.FORCE_COLOR,["true","1","2"]),rie=nie||!ow("--no-colors")&&!cD("no-color")&&(!Up||process.stdout.isTTY)&&(!Up||ow("--color")||Z_("COLORTERM")!==null||(Z_("TERM")||"").includes("color")),iie=t=>new Uint8Array(t),sie=t=>{const e=iie(t.byteLength);return e.set(t),e};class oie{constructor(e,n){this.left=e,this.right=n}}const ol=(t,e)=>new oie(t,e);typeof DOMParser<"u"&&new DOMParser;const aie=t=>ore(t,(e,n)=>`${n}:${e};`).join(""),jl=Symbol,uD=jl(),hD=jl(),lie=jl(),cie=jl(),uie=jl(),fD=jl(),hie=jl(),Hb=jl(),fie=jl(),die=t=>{var i;t.length===1&&((i=t[0])==null?void 0:i.constructor)===Function&&(t=t[0]());const e=[],n=[];let r=0;for(;r0&&n.push(e.join(""));r{var o;t.length===1&&((o=t[0])==null?void 0:o.constructor)===Function&&(t=t[0]());const e=[],n=[],r=ko();let i=[],s=0;for(;s0||c.length>0?(e.push("%c"+a),n.push(c)):e.push(a)}else break}}for(s>0&&(i=n,i.unshift(e.join("")));s{console.log(...dD(t)),pD.forEach(e=>e.print(t))},_ie=(...t)=>{console.warn(...dD(t)),t.unshift(Hb),pD.forEach(e=>e.print(t))},pD=$f(),mD=t=>({[Symbol.iterator](){return this},next:t}),vie=(t,e)=>mD(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),i1=(t,e)=>mD(()=>{const{done:n,value:r}=t.next();return{done:n,value:n?void 0:e(r)}});class Gb{constructor(e,n){this.clock=e,this.len=n}}class wm{constructor(){this.clients=new Map}}const gD=(t,e,n)=>e.clients.forEach((r,i)=>{const s=t.doc.store.clients.get(i);for(let o=0;o{let n=0,r=t.length-1;for(;n<=r;){const i=Pc((n+r)/2),s=t[i],o=s.clock;if(o<=e){if(e{const n=t.clients.get(e.client);return n!==void 0&&yie(n,e.clock)!==null},Wb=t=>{t.clients.forEach(e=>{e.sort((i,s)=>i.clock-s.clock);let n,r;for(n=1,r=1;n=s.clock?i.len=hh(i.len,s.clock+s.len-i.clock):(r{const e=new wm;for(let n=0;n{if(!e.clients.has(i)){const s=r.slice();for(let o=n+1;o{$c(t.clients,e,()=>[]).push(new Gb(n,r))},Sie=()=>new wm,Eie=t=>{const e=Sie();return t.clients.forEach((n,r)=>{const i=[];for(let s=0;s0&&e.clients.set(r,i)}),e},dd=(t,e)=>{Ht(t.restEncoder,e.clients.size),Lc(e.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{t.resetDsCurVal(),Ht(t.restEncoder,n);const i=r.length;Ht(t.restEncoder,i);for(let s=0;s{const e=new wm,n=Gt(t.restDecoder);for(let r=0;r0){const o=$c(e.clients,i,()=>[]);for(let a=0;a{const r=new wm,i=Gt(t.restDecoder);for(let s=0;s0){const s=new Ku;return Ht(s.restEncoder,0),dd(s,r),s.toUint8Array()}return null},vD=sD;class $l extends ure{constructor({guid:e=Vre(),collectionid:n=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=vD(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new MD,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=vN(c=>{this.on("load",()=>{this.isLoaded=!0,c(this)})});const l=()=>vN(c=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),c())};this.on("sync",u)});this.on("sync",c=>{c===!1&&this.isSynced&&(this.whenSynced=l()),this.isSynced=c===void 0||c===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const e=this._item;e!==null&&!this.shouldLoad&&Dn(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Lc(this.subdocs).map(e=>e.guid))}transact(e,n=null){return Dn(this,e,n)}get(e,n=lr){const r=$c(this.share,e,()=>{const s=new n;return s._integrate(this,null),s}),i=r.constructor;if(n!==lr&&i!==n)if(i===lr){const s=new n;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(e,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,wa)}getText(e=""){return this.get(e,Fo)}getMap(e=""){return this.get(e,Na)}getXmlElement(e=""){return this.get(e,kl)}getXmlFragment(e=""){return this.get(e,ka)}toJSON(){const e={};return this.share.forEach((n,r)=>{e[r]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,Lc(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new $l({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,Dn(e.parent.doc,r=>{const i=n.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class yD{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Gt(this.restDecoder)}readDsLen(){return Gt(this.restDecoder)}}class xD extends yD{readLeftID(){return an(Gt(this.restDecoder),Gt(this.restDecoder))}readRightID(){return an(Gt(this.restDecoder),Gt(this.restDecoder))}readClient(){return Gt(this.restDecoder)}readInfo(){return qf(this.restDecoder)}readString(){return Tf(this.restDecoder)}readParentInfo(){return Gt(this.restDecoder)===1}readTypeRef(){return Gt(this.restDecoder)}readLen(){return Gt(this.restDecoder)}readAny(){return Dp(this.restDecoder)}readBuf(){return sie(Ii(this.restDecoder))}readJSON(){return JSON.parse(Tf(this.restDecoder))}readKey(){return Tf(this.restDecoder)}}class wie{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Gt(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Gt(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Xf extends wie{constructor(e){super(e),this.keys=[],Gt(e),this.keyClockDecoder=new r1(Ii(e)),this.clientDecoder=new u_(Ii(e)),this.leftClockDecoder=new r1(Ii(e)),this.rightClockDecoder=new r1(Ii(e)),this.infoDecoder=new _N(Ii(e),qf),this.stringDecoder=new Fre(Ii(e)),this.parentInfoDecoder=new _N(Ii(e),qf),this.typeRefDecoder=new u_(Ii(e)),this.lenDecoder=new u_(Ii(e))}readLeftID(){return new bf(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new bf(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Dp(this.restDecoder)}readBuf(){return Ii(this.restDecoder)}readJSON(){return Dp(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e{r=hh(r,e[0].id.clock);const i=Uo(e,r);Ht(t.restEncoder,e.length-i),t.writeClient(n),Ht(t.restEncoder,r);const s=e[i];s.write(t,r-s.id.clock);for(let o=i+1;o{const r=new Map;n.forEach((i,s)=>{ri(e,s)>i&&r.set(s,i)}),wy(e).forEach((i,s)=>{n.has(s)||r.set(s,0)}),Ht(t.restEncoder,r.size),Lc(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{Tie(t,e.clients.get(i),i,s)})},bie=(t,e)=>{const n=ko(),r=Gt(t.restDecoder);for(let i=0;i{const r=[];let i=Lc(n.keys()).sort((m,g)=>m-g);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let m=n.get(i[i.length-1]);for(;m.refs.length===m.i;)if(i.pop(),i.length>0)m=n.get(i[i.length-1]);else return null;return m};let o=s();if(o===null)return null;const a=new MD,l=new Map,c=(m,g)=>{const v=l.get(m);(v==null||v>g)&&l.set(m,g)};let u=o.refs[o.i++];const h=new Map,p=()=>{for(const m of r){const g=m.id.client,v=n.get(g);v?(v.i--,a.clients.set(g,v.refs.slice(v.i)),n.delete(g),v.i=0,v.refs=[]):a.clients.set(g,[m]),i=i.filter(y=>y!==g)}r.length=0};for(;;){if(u.constructor!==Zs){const g=$c(h,u.id.client,()=>ri(e,u.id.client))-u.id.clock;if(g<0)r.push(u),c(u.id.client,u.id.clock-1),p();else{const v=u.getMissing(t,e);if(v!==null){r.push(u);const y=n.get(v)||{refs:[],i:0};if(y.refs.length===y.i)c(v,ri(e,v)),p();else{u=y.refs[y.i++];continue}}else(g===0||g0)u=r.pop();else if(o!==null&&o.i0){const m=new Ku;return $b(m,a,new Map),Ht(m.restEncoder,0),{missing:l,update:m.toUint8Array()}}return null},Mie=(t,e)=>$b(t,e.doc.store,e.beforeState),Cie=(t,e,n,r=new Xf(t))=>Dn(e,i=>{i.local=!1;let s=!1;const o=i.doc,a=o.store,l=bie(r,o),c=Aie(i,a,l),u=a.pendingStructs;if(u){for(const[p,m]of u.missing)if(mm)&&u.missing.set(p,m)}u.update=Q_([u.update,c.update])}}else a.pendingStructs=c;const h=SN(r,i,a);if(a.pendingDs){const p=new Xf(fh(a.pendingDs));Gt(p.restDecoder);const m=SN(p,i,a);h&&m?a.pendingDs=Q_([h,m]):a.pendingDs=h||m}else a.pendingDs=h;if(s){const p=a.pendingStructs.update;a.pendingStructs=null,wD(i.doc,p)}},n,!1),wD=(t,e,n,r=Xf)=>{const i=fh(e);Cie(i,t,n,new r(i))},Rie=(t,e,n)=>wD(t,e,n,xD),Nie=(t,e,n=new Map)=>{$b(t,e.store,n),dd(t,Eie(e.store))},kie=(t,e=new Uint8Array([0]),n=new Ku)=>{const r=TD(e);Nie(n,t,r);const i=[n.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(qie(t.store.pendingStructs.update,e)),i.length>1){if(n.constructor===Tm)return jie(i.map((s,o)=>o===0?s:Kie(s)));if(n.constructor===Ku)return Q_(i)}return i[0]},Iie=(t,e)=>kie(t,e,new Tm),Oie=t=>{const e=new Map,n=Gt(t.restDecoder);for(let r=0;rOie(new yD(fh(t))),bD=(t,e)=>(Ht(t.restEncoder,e.size),Lc(e.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{Ht(t.restEncoder,n),Ht(t.restEncoder,r)}),t),Lie=(t,e)=>bD(t,wy(e.store)),Pie=(t,e=new ED)=>(t instanceof Map?bD(e,t):Lie(e,t),e.toUint8Array()),Die=t=>Pie(t,new SD);class Uie{constructor(){this.l=[]}}const EN=()=>new Uie,wN=(t,e)=>t.l.push(e),TN=(t,e)=>{const n=t.l,r=n.length;t.l=n.filter(i=>e!==i),r===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},AD=(t,e,n)=>Vb(t.l,[e,n]);class bf{constructor(e,n){this.client=e,this.clock=n}}const w0=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,an=(t,e)=>new bf(t,e),Fie=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw Ra()},rf=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!_D(e.ds,t.id),aw=(t,e)=>{const n=$c(t.meta,aw,$f),r=t.doc.store;n.has(e)||(e.sv.forEach((i,s)=>{i{}),n.add(e))};class MD{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const wy=t=>{const e=new Map;return t.clients.forEach((n,r)=>{const i=n[n.length-1];e.set(r,i.id.clock+i.length)}),e},ri=(t,e)=>{const n=t.clients.get(e);if(n===void 0)return 0;const r=n[n.length-1];return r.id.clock+r.length},CD=(t,e)=>{let n=t.clients.get(e.id.client);if(n===void 0)n=[],t.clients.set(e.id.client,n);else{const r=n[n.length-1];if(r.id.clock+r.length!==e.id.clock)throw Ra()}n.push(e)},Uo=(t,e)=>{let n=0,r=t.length-1,i=t[r],s=i.id.clock;if(s===e)return r;let o=Pc(e/(s+i.length-1)*r);for(;n<=r;){if(i=t[o],s=i.id.clock,s<=e){if(e{const n=t.clients.get(e.client);return n[Uo(n,e.clock)]},s1=Bie,lw=(t,e,n)=>{const r=Uo(e,n),i=e[r];return i.id.clock{const n=t.doc.store.clients.get(e.client);return n[lw(t,n,e.clock)]},bN=(t,e,n)=>{const r=e.clients.get(n.client),i=Uo(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==Rs&&r.splice(i+1,0,rv(t,s,n.clock-s.id.clock+1)),s},zie=(t,e,n)=>{const r=t.clients.get(e.id.client);r[Uo(r,e.id.clock)]=n},RD=(t,e,n,r,i)=>{if(r===0)return;const s=n+r;let o=lw(t,e,n),a;do a=e[o++],se.deleteSet.clients.size===0&&!are(e.afterState,(n,r)=>e.beforeState.get(r)!==n)?!1:(Wb(e.deleteSet),Mie(t,e),dd(t,e.deleteSet),!0),MN=(t,e,n)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&$c(t.changed,e,$f).add(n)},h_=(t,e)=>{let n=t[e],r=t[e-1],i=e;for(;i>0;n=r,r=t[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof Ur&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}const s=e-i;return s&&t.splice(e+1-s,s),s},Hie=(t,e,n)=>{for(const[r,i]of t.clients.entries()){const s=e.clients.get(r);for(let o=i.length-1;o>=0;o--){const a=i[o],l=a.clock+a.len;for(let c=Uo(s,a.clock),u=s[c];c{t.clients.forEach((n,r)=>{const i=e.clients.get(r);for(let s=n.length-1;s>=0;s--){const o=n[s],a=eD(i.length-1,1+Uo(i,o.clock+o.len-1));for(let l=a,c=i[l];l>0&&c.id.clock>=o.clock;c=i[l])l-=1+h_(i,l)}})},ND=(t,e)=>{if(ea.push(()=>{(c._item===null||!c._item.deleted)&&c._callObserver(n,l)})),a.push(()=>{n.changedParentTypes.forEach((l,c)=>{c._dEH.l.length>0&&(c._item===null||!c._item.deleted)&&(l=l.filter(u=>u.target._item===null||!u.target._item.deleted),l.forEach(u=>{u.currentTarget=c,u._path=null}),l.sort((u,h)=>u.path.length-h.path.length),AD(c._dEH,l,n))})}),a.push(()=>r.emit("afterTransaction",[n,r])),Vb(a,[]),n._needFormattingCleanup&&cse(n)}finally{r.gc&&Hie(s,i,r.gcFilter),Gie(s,i),n.afterState.forEach((u,h)=>{const p=n.beforeState.get(h)||0;if(p!==u){const m=i.clients.get(h),g=hh(Uo(m,p),1);for(let v=m.length-1;v>=g;)v-=1+h_(m,v)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:p}=o[u].id,m=i.clients.get(h),g=Uo(m,p);g+11||g>0&&h_(m,g)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(gie(Hb,uD,"[yjs] ",hD,fD,"Changed the client-id because another client seems to be using it."),r.clientID=vD()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const u=new Tm;AN(u,n)&&r.emit("update",[u.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const u=new Ku;AN(u,n)&&r.emit("updateV2",[u.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:l,subdocsRemoved:c}=n;(a.size>0||c.size>0||l.size>0)&&(a.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),c.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:l,added:a,removed:c},r,n]),c.forEach(u=>u.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):ND(t,e+1)}}},Dn=(t,e,n=null,r=!0)=>{const i=t._transactionCleanups;let s=!1,o=null;t._transaction===null&&(s=!0,t._transaction=new Vie(t,n,r),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{o=e(t._transaction)}finally{if(s){const a=t._transaction===i[0];t._transaction=null,a&&ND(i,0)}}return o};function*Wie(t){const e=Gt(t.restDecoder);for(let n=0;nQ_(t,xD,Tm),$ie=(t,e)=>{if(t.constructor===Rs){const{client:n,clock:r}=t.id;return new Rs(an(n,r+e),t.length-e)}else if(t.constructor===Zs){const{client:n,clock:r}=t.id;return new Zs(an(n,r+e),t.length-e)}else{const n=t,{client:r,clock:i}=n.id;return new Ur(an(r,i+e),null,an(r,i+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},Q_=(t,e=Xf,n=Ku)=>{if(t.length===1)return t[0];const r=t.map(u=>new e(fh(u)));let i=r.map(u=>new qb(u,!0)),s=null;const o=new n,a=new Xb(o);for(;i=i.filter(p=>p.curr!==null),i.sort((p,m)=>{if(p.curr.id.client===m.curr.id.client){const g=p.curr.id.clock-m.curr.id.clock;return g===0?p.curr.constructor===m.curr.constructor?0:p.curr.constructor===Zs?1:-1:g}else return m.curr.id.client-p.curr.id.client}),i.length!==0;){const u=i[0],h=u.curr.id.client;if(s!==null){let p=u.curr,m=!1;for(;p!==null&&p.id.clock+p.length<=s.struct.id.clock+s.struct.length&&p.id.client>=s.struct.id.client;)p=u.next(),m=!0;if(p===null||p.id.client!==h||m&&p.id.clock>s.struct.id.clock+s.struct.length)continue;if(h!==s.struct.id.client)vc(a,s.struct,s.offset),s={struct:p,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===Zs?s.struct.length-=g:p=$ie(p,g)),s.struct.mergeWith(p)||(vc(a,s.struct,s.offset),s={struct:p,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let p=u.curr;p!==null&&p.id.client===h&&p.id.clock===s.struct.id.clock+s.struct.length&&p.constructor!==Zs;p=u.next())vc(a,s.struct,s.offset),s={struct:p,offset:0}}s!==null&&(vc(a,s.struct,s.offset),s=null),Kb(a);const l=r.map(u=>jb(u)),c=xie(l);return dd(o,c),o.toUint8Array()},qie=(t,e,n=Xf,r=Ku)=>{const i=TD(e),s=new r,o=new Xb(s),a=new n(fh(t)),l=new qb(a,!1);for(;l.curr;){const u=l.curr,h=u.id.client,p=i.get(h)||0;if(l.curr.constructor===Zs){l.next();continue}if(u.id.clock+u.length>p)for(vc(o,u,hh(p-u.id.clock,0)),l.next();l.curr&&l.curr.id.client===h;)vc(o,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===h&&l.curr.id.clock+l.curr.length<=p;)l.next()}Kb(o);const c=jb(a);return dd(s,c),s.toUint8Array()},kD=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Mo(t.encoder.restEncoder)}),t.encoder.restEncoder=bc(),t.written=0)},vc=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&kD(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),Ht(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},Kb=t=>{kD(t);const e=t.encoder.restEncoder;Ht(e,t.clientStructs.length);for(let n=0;n{const i=new n(fh(t)),s=new qb(i,!1),o=new r,a=new Xb(o);for(let c=s.curr;c!==null;c=s.next())vc(a,e(c),0);Kb(a);const l=jb(i);return dd(o,l),o.toUint8Array()},Kie=t=>Xie(t,Qre,Xf,Tm),CN="You must not compute changes after the event-handler fired.";class Ty{constructor(e,n){this.target=e,this.currentTarget=e,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Yie(this.currentTarget,this.target))}deletes(e){return _D(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Dc(CN);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(i=>{if(i!==null){const s=n._map.get(i);let o,a;if(this.adds(s)){let l=s.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(s))if(l!==null&&this.deletes(l))o="delete",a=QS(l.content.getContent());else return;else l!==null&&this.deletes(l)?(o="update",a=QS(l.content.getContent())):(o="add",a=void 0)}else if(this.deletes(s))o="delete",a=QS(s.content.getContent());else return;e.set(i,{action:o,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Dc(CN);const n=this.target,r=$f(),i=$f(),s=[];if(e={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const l=()=>{a&&s.push(a)};for(let c=n._start;c!==null;c=c.right)c.deleted?this.deletes(c)&&!this.adds(c)&&((a===null||a.delete===void 0)&&(l(),a={delete:0}),a.delete+=c.length,i.add(c)):this.adds(c)?((a===null||a.insert===void 0)&&(l(),a={insert:[]}),a.insert=a.insert.concat(c.content.getContent()),r.add(c)):((a===null||a.retain===void 0)&&(l(),a={retain:0}),a.retain+=c.length);a!==null&&a.retain===void 0&&l()}this._changes=e}return e}}const Yie=(t,e)=>{const n=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)n.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;n.unshift(r)}e=e._item.parent}return n},Ei=()=>{_ie("Invalid access: Add Yjs type to a document before reading data.")},ID=80;let Yb=0;class Zie{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=Yb++}}const Jie=t=>{t.timestamp=Yb++},OD=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=Yb++},Qie=(t,e,n)=>{if(t.length>=ID){const r=t.reduce((i,s)=>i.timestamp{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((s,o)=>l_(e-s.index)e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&l_(n.index-i){for(let r=t.length-1;r>=0;r--){const i=t[r];if(n>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){t.splice(r,1);continue}i.p=s,s.marker=!0}(e0&&e===i.index)&&(i.index=hh(e,i.index+n))}},Ay=(t,e,n)=>{const r=t,i=e.changedParentTypes;for(;$c(i,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;AD(r._eH,n,e)};class lr{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=EN(),this._dEH=EN(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw Ea()}clone(){throw Ea()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,n){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){wN(this._eH,e)}observeDeep(e){wN(this._dEH,e)}unobserve(e){TN(this._eH,e)}unobserveDeep(e){TN(this._dEH,e)}toJSON(){}}const LD=(t,e,n)=>{t.doc??Ei(),e<0&&(e=t._length+e),n<0&&(n=t._length+n);let r=n-e;const i=[];let s=t._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=e)e-=o.length;else{for(let a=e;a0;a++)i.push(o[a]),r--;e=0}}s=s.right}return i},PD=t=>{t.doc??Ei();const e=[];let n=t._start;for(;n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let i=0;i{let n=0,r=t._start;for(t.doc??Ei();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const n=[];return Bp(t,(r,i)=>{n.push(e(r,i,t))}),n},ese=t=>{let e=t._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};n=e.content.getContent(),r=0,e=e.right}const i=n[r++];return n.length<=r&&(n=null),{done:!1,value:i}}}},UD=(t,e)=>{t.doc??Ei();const n=by(t,e);let r=t._start;for(n!==null&&(r=n.p,e-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e{let i=n;const s=t.doc,o=s.clientID,a=s.store,l=n===null?e._start:n.right;let c=[];const u=()=>{c.length>0&&(i=new Ur(an(o,ri(a,o)),i,i&&i.lastId,l,l&&l.id,e,null,new Zu(c)),i.integrate(t,0),c=[])};r.forEach(h=>{if(h===null)c.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:c.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:i=new Ur(an(o,ri(a,o)),i,i&&i.lastId,l,l&&l.id,e,null,new bm(new Uint8Array(h))),i.integrate(t,0);break;case $l:i=new Ur(an(o,ri(a,o)),i,i&&i.lastId,l,l&&l.id,e,null,new Am(h)),i.integrate(t,0);break;default:if(h instanceof lr)i=new Ur(an(o,ri(a,o)),i,i&&i.lastId,l,l&&l.id,e,null,new ql(h)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},FD=()=>Dc("Length exceeded!"),BD=(t,e,n,r)=>{if(n>e._length)throw FD();if(n===0)return e._searchMarker&&Fp(e._searchMarker,n,r.length),ev(t,e,null,r);const i=n,s=by(e,n);let o=e._start;for(s!==null&&(o=s.p,n-=s.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let i=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return ev(t,e,i,n)},zD=(t,e,n,r)=>{if(r===0)return;const i=n,s=r,o=by(e,n);let a=e._start;for(o!==null&&(a=o.p,n-=o.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n0&&a!==null;)a.deleted||(r0)throw FD();e._searchMarker&&Fp(e._searchMarker,i,-s+r)},tv=(t,e,n)=>{const r=e._map.get(n);r!==void 0&&r.delete(t)},Zb=(t,e,n,r)=>{const i=e._map.get(n)||null,s=t.doc,o=s.clientID;let a;if(r==null)a=new Zu([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:a=new Zu([r]);break;case Uint8Array:a=new bm(r);break;case $l:a=new Am(r);break;default:if(r instanceof lr)a=new ql(r);else throw new Error("Unexpected content type")}new Ur(an(o,ri(s.store,o)),i,i&&i.lastId,null,null,e,n,a).integrate(t,0)},Jb=(t,e)=>{t.doc??Ei();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},VD=t=>{const e={};return t.doc??Ei(),t._map.forEach((n,r)=>{n.deleted||(e[r]=n.content.getContent()[n.length-1])}),e},HD=(t,e)=>{t.doc??Ei();const n=t._map.get(e);return n!==void 0&&!n.deleted},nse=(t,e)=>{const n={};return t._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&rf(s,e)&&(n[i]=s.content.getContent()[s.length-1])}),n},T0=t=>(t.doc??Ei(),vie(t._map.entries(),e=>!e[1].deleted));class rse extends Ty{}class wa extends lr{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new wa;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new wa}clone(){const e=new wa;return e.insert(0,this.toArray().map(n=>n instanceof lr?n.clone():n)),e}get length(){return this.doc??Ei(),this._length}_callObserver(e,n){super._callObserver(e,n),Ay(this,e,new rse(this,e))}insert(e,n){this.doc!==null?Dn(this.doc,r=>{BD(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?Dn(this.doc,n=>{tse(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?Dn(this.doc,r=>{zD(r,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return UD(this,e)}toArray(){return PD(this)}slice(e=0,n=this.length){return LD(this,e,n)}toJSON(){return this.map(e=>e instanceof lr?e.toJSON():e)}map(e){return DD(this,e)}forEach(e){Bp(this,e)}[Symbol.iterator](){return ese(this)}_write(e){e.writeTypeRef(Cse)}}const ise=t=>new wa;class sse extends Ty{constructor(e,n,r){super(e,n),this.keysChanged=r}}class Na extends lr{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,n){super._integrate(e,n),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new Na}clone(){const e=new Na;return this.forEach((n,r)=>{e.set(r,n instanceof lr?n.clone():n)}),e}_callObserver(e,n){Ay(this,e,new sse(this,e,n))}toJSON(){this.doc??Ei();const e={};return this._map.forEach((n,r)=>{if(!n.deleted){const i=n.content.getContent()[n.length-1];e[r]=i instanceof lr?i.toJSON():i}}),e}get size(){return[...T0(this)].length}keys(){return i1(T0(this),e=>e[0])}values(){return i1(T0(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return i1(T0(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Ei(),this._map.forEach((n,r)=>{n.deleted||e(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?Dn(this.doc,n=>{tv(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?Dn(this.doc,r=>{Zb(r,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return Jb(this,e)}has(e){return HD(this,e)}clear(){this.doc!==null?Dn(this.doc,e=>{this.forEach(function(n,r,i){tv(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Rse)}}const ose=t=>new Na,xc=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&Zre(t,e);class cw{constructor(e,n,r,i){this.left=e,this.right=n,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Ra(),this.right.content.constructor){case Gr:this.right.deleted||pd(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const RN=(t,e,n)=>{for(;e.right!==null&&n>0;){switch(e.right.content.constructor){case Gr:e.right.deleted||pd(e.currentAttributes,e.right.content);break;default:e.right.deleted||(n{const i=new Map,s=r?by(e,n):null;if(s){const o=new cw(s.p.left,s.p,s.index,i);return RN(t,o,n-s.index)}else{const o=new cw(null,e._start,0,i);return RN(t,o,n)}},GD=(t,e,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Gr&&xc(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=t.doc,s=i.clientID;r.forEach((o,a)=>{const l=n.left,c=n.right,u=new Ur(an(s,ri(i.store,s)),l,l&&l.lastId,c,c&&c.id,e,null,new Gr(a,o));u.integrate(t,0),n.right=u,n.forward()})},pd=(t,e)=>{const{key:n,value:r}=e;r===null?t.delete(n):t.set(n,r)},WD=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Gr&&xc(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},jD=(t,e,n,r)=>{const i=t.doc,s=i.clientID,o=new Map;for(const a in r){const l=r[a],c=n.currentAttributes.get(a)??null;if(!xc(c,l)){o.set(a,c);const{left:u,right:h}=n;n.right=new Ur(an(s,ri(i.store,s)),u,u&&u.lastId,h,h&&h.id,e,null,new Gr(a,l)),n.right.integrate(t,0),n.forward()}}return o},o1=(t,e,n,r,i)=>{n.currentAttributes.forEach((p,m)=>{i[m]===void 0&&(i[m]=null)});const s=t.doc,o=s.clientID;WD(n,i);const a=jD(t,e,n,i),l=r.constructor===String?new Ia(r):r instanceof lr?new ql(r):new dh(r);let{left:c,right:u,index:h}=n;e._searchMarker&&Fp(e._searchMarker,n.index,l.getLength()),u=new Ur(an(o,ri(s.store,o)),c,c&&c.lastId,u,u&&u.id,e,null,l),u.integrate(t,0),n.right=u,n.index=h,n.forward(),GD(t,e,n,a)},NN=(t,e,n,r,i)=>{const s=t.doc,o=s.clientID;WD(n,i);const a=jD(t,e,n,i);e:for(;n.right!==null&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Gr));){if(!n.right.deleted)switch(n.right.content.constructor){case Gr:{const{key:l,value:c}=n.right.content,u=i[l];if(u!==void 0){if(xc(u,c))a.delete(l);else{if(r===0)break e;a.set(l,c)}n.right.delete(t)}else n.currentAttributes.set(l,c);break}default:r0){let l="";for(;r>0;r--)l+=` +`;n.right=new Ur(an(o,ri(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Ia(l)),n.right.integrate(t,0),n.forward()}GD(t,e,n,a)},$D=(t,e,n,r,i)=>{let s=e;const o=ko();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===Gr){const c=s.content;o.set(c.key,c)}s=s.right}let a=0,l=!1;for(;e!==s;){if(n===e&&(l=!0),!e.deleted){const c=e.content;switch(c.constructor){case Gr:{const{key:u,value:h}=c,p=r.get(u)??null;(o.get(u)!==c||p===h)&&(e.delete(t),a++,!l&&(i.get(u)??null)===h&&p!==h&&(p===null?i.delete(u):i.set(u,p))),!l&&!e.deleted&&pd(i,c);break}}}e=e.right}return a},ase=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const n=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===Gr){const r=e.content.key;n.has(r)?e.delete(t):n.add(r)}e=e.left}},lse=t=>{let e=0;return Dn(t.doc,n=>{let r=t._start,i=t._start,s=ko();const o=nw(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Gr:pd(o,i.content);break;default:e+=$D(n,r,i,s,o),s=nw(o),r=i;break}i=i.right}}),e},cse=t=>{const e=new Set,n=t.doc;for(const[r,i]of t.afterState.entries()){const s=t.beforeState.get(r)||0;i!==s&&RD(t,n.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===Gr&&o.constructor!==Rs&&e.add(o.parent)})}Dn(n,r=>{gD(t,t.deleteSet,i=>{if(i instanceof Rs||!i.parent._hasFormatting||e.has(i.parent))return;const s=i.parent;i.content.constructor===Gr?e.add(s):ase(r,i)});for(const i of e)lse(i)})},kN=(t,e,n)=>{const r=n,i=nw(e.currentAttributes),s=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case ql:case dh:case Ia:n{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,n=[];Dn(e,r=>{const i=new Map,s=new Map;let o=this.target._start,a=null;const l={};let c="",u=0,h=0;const p=()=>{if(a!==null){let m=null;switch(a){case"delete":h>0&&(m={delete:h}),h=0;break;case"insert":(typeof c=="object"||c.length>0)&&(m={insert:c},i.size>0&&(m.attributes={},i.forEach((g,v)=>{g!==null&&(m.attributes[v]=g)}))),c="";break;case"retain":u>0&&(m={retain:u},Xre(l)||(m.attributes=jre({},l))),u=0;break}m&&n.push(m),a=null}};for(;o!==null;){switch(o.content.constructor){case ql:case dh:this.adds(o)?this.deletes(o)||(p(),a="insert",c=o.content.getContent()[0],p()):this.deletes(o)?(a!=="delete"&&(p(),a="delete"),h+=1):o.deleted||(a!=="retain"&&(p(),a="retain"),u+=1);break;case Ia:this.adds(o)?this.deletes(o)||(a!=="insert"&&(p(),a="insert"),c+=o.content.str):this.deletes(o)?(a!=="delete"&&(p(),a="delete"),h+=o.length):o.deleted||(a!=="retain"&&(p(),a="retain"),u+=o.length);break;case Gr:{const{key:m,value:g}=o.content;if(this.adds(o)){if(!this.deletes(o)){const v=i.get(m)??null;xc(v,g)?g!==null&&o.delete(r):(a==="retain"&&p(),xc(g,s.get(m)??null)?delete l[m]:l[m]=g)}}else if(this.deletes(o)){s.set(m,g);const v=i.get(m)??null;xc(v,g)||(a==="retain"&&p(),l[m]=v)}else if(!o.deleted){s.set(m,g);const v=l[m];v!==void 0&&(xc(v,g)?v!==null&&o.delete(r):(a==="retain"&&p(),g===null?delete l[m]:l[m]=g))}o.deleted||(a==="insert"&&p(),pd(i,o.content));break}}o=o.right}for(p();n.length>0;){const m=n[n.length-1];if(m.retain!==void 0&&m.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Fo extends lr{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ei(),this._length}_integrate(e,n){super._integrate(e,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new Fo}clone(){const e=new Fo;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const r=new use(this,e,n);Ay(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ei();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Ia&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?Dn(this.doc,r=>{const i=new cw(null,this._start,0,new Map);for(let s=0;s0)&&o1(r,this,i,a,o.attributes||{})}else o.retain!==void 0?NN(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&kN(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,r){this.doc??Ei();const i=[],s=new Map,o=this.doc;let a="",l=this._start;function c(){if(a.length>0){const h={};let p=!1;s.forEach((g,v)=>{p=!0,h[v]=g});const m={insert:a};p&&(m.attributes=h),i.push(m),a=""}}const u=()=>{for(;l!==null;){if(rf(l,e)||n!==void 0&&rf(l,n))switch(l.content.constructor){case Ia:{const h=s.get("ychange");e!==void 0&&!rf(l,e)?(h===void 0||h.user!==l.id.client||h.type!=="removed")&&(c(),s.set("ychange",r?r("removed",l.id):{type:"removed"})):n!==void 0&&!rf(l,n)?(h===void 0||h.user!==l.id.client||h.type!=="added")&&(c(),s.set("ychange",r?r("added",l.id):{type:"added"})):h!==void 0&&(c(),s.delete("ychange")),a+=l.content.str;break}case ql:case dh:{c();const h={insert:l.content.getContent()[0]};if(s.size>0){const p={};h.attributes=p,s.forEach((m,g)=>{p[g]=m})}i.push(h);break}case Gr:rf(l,e)&&(c(),pd(s,l.content));break}l=l.right}c()};return e||n?Dn(o,h=>{e&&aw(h,e),n&&aw(h,n),u()},"cleanup"):u(),i}insert(e,n,r){if(n.length<=0)return;const i=this.doc;i!==null?Dn(i,s=>{const o=b0(s,this,e,!r);r||(r={},o.currentAttributes.forEach((a,l)=>{r[l]=a})),o1(s,this,o,n,r)}):this._pending.push(()=>this.insert(e,n,r))}insertEmbed(e,n,r){const i=this.doc;i!==null?Dn(i,s=>{const o=b0(s,this,e,!r);o1(s,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(e,n,r||{}))}delete(e,n){if(n===0)return;const r=this.doc;r!==null?Dn(r,i=>{kN(i,b0(i,this,e,!0),n)}):this._pending.push(()=>this.delete(e,n))}format(e,n,r){if(n===0)return;const i=this.doc;i!==null?Dn(i,s=>{const o=b0(s,this,e,!1);o.right!==null&&NN(s,this,o,n,r)}):this._pending.push(()=>this.format(e,n,r))}removeAttribute(e){this.doc!==null?Dn(this.doc,n=>{tv(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?Dn(this.doc,r=>{Zb(r,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return Jb(this,e)}getAttributes(){return VD(this)}_write(e){e.writeTypeRef(Nse)}}const hse=t=>new Fo;class a1{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ei()}[Symbol.iterator](){return this}next(){let e=this._currentNode,n=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(n)))do if(n=e.content.type,!e.deleted&&(n.constructor===kl||n.constructor===ka)&&n._start!==null)e=n._start;else for(;e!==null;)if(e.right!==null){e=e.right;break}else e.parent===this._root?e=null:e=e.parent._item;while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class ka extends lr{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ka}clone(){const e=new ka;return e.insert(0,this.toArray().map(n=>n instanceof lr?n.clone():n)),e}get length(){return this.doc??Ei(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new a1(this,e)}querySelector(e){e=e.toUpperCase();const r=new a1(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),Lc(new a1(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Ay(this,e,new pse(this,n,e))}toString(){return DD(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,n={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),Bp(this,s=>{i.insertBefore(s.toDOM(e,n,r),null)}),i}insert(e,n){this.doc!==null?Dn(this.doc,r=>{BD(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)Dn(this.doc,r=>{const i=e&&e instanceof lr?e._item:e;ev(r,this,i,n)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(s=>s===e)+1;if(i===0&&e!==null)throw Dc("Reference item not found");r.splice(i,0,...n)}}delete(e,n=1){this.doc!==null?Dn(this.doc,r=>{zD(r,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return PD(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return UD(this,e)}slice(e=0,n=this.length){return LD(this,e,n)}forEach(e){Bp(this,e)}_write(e){e.writeTypeRef(Ise)}}const fse=t=>new ka;class kl extends ka{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,n){super._integrate(e,n),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new kl(this.nodeName)}clone(){const e=new kl(this.nodeName),n=this.getAttributes();return qre(n,(r,i)=>{typeof r=="string"&&e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof lr?r.clone():r)),e}toString(){const e=this.getAttributes(),n=[],r=[];for(const a in e)r.push(a);r.sort();const i=r.length;for(let a=0;a0?" "+n.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(e){this.doc!==null?Dn(this.doc,n=>{tv(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?Dn(this.doc,r=>{Zb(r,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return Jb(this,e)}hasAttribute(e){return HD(this,e)}getAttributes(e){return e?nse(this,e):VD(this)}toDOM(e=document,n={},r){const i=e.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const a=s[o];typeof a=="string"&&i.setAttribute(o,a)}return Bp(this,o=>{i.appendChild(o.toDOM(e,n,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(kse),e.writeKey(this.nodeName)}}const dse=t=>new kl(t.readKey());class pse extends Ty{constructor(e,n,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class Kf extends Na{constructor(e){super(),this.hookName=e}_copy(){return new Kf(this.hookName)}clone(){const e=new Kf(this.hookName);return this.forEach((n,r)=>{e.set(r,n)}),e}toDOM(e=document,n={},r){const i=n[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(e){e.writeTypeRef(Ose),e.writeKey(this.hookName)}}const mse=t=>new Kf(t.readKey());class Yu extends Fo{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new Yu}clone(){const e=new Yu;return e.applyDelta(this.toDelta()),e}toDOM(e=document,n,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const n=[];for(const i in e.attributes){const s=[];for(const o in e.attributes[i])s.push({key:o,value:e.attributes[i][o]});s.sort((o,a)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Lse)}}const gse=t=>new Yu;class Qb{constructor(e,n){this.id=e,this.length=n}get deleted(){throw Ea()}mergeWith(e){return!1}write(e,n,r){throw Ea()}integrate(e,n){throw Ea()}}const _se=0;class Rs extends Qb{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){n>0&&(this.id.clock+=n,this.length-=n),CD(e.doc.store,this)}write(e,n){e.writeInfo(_se),e.writeLen(this.length-n)}getMissing(e,n){return null}}class bm{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new bm(this.content)}splice(e){throw Ea()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const vse=t=>new bm(t.readBuf());class zp{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new zp(this.len)}splice(e){const n=new zp(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){J_(e.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(e){}gc(e){}write(e,n){e.writeLen(this.len-n)}getRef(){return 1}}const yse=t=>new zp(t.readLen()),qD=(t,e)=>new $l({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Am{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const n={};this.opts=n,e.gc||(n.gc=!1),e.autoLoad&&(n.autoLoad=!0),e.meta!==null&&(n.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Am(qD(this.doc.guid,this.opts))}splice(e){throw Ea()}mergeWith(e){return!1}integrate(e,n){this.doc._item=n,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,n){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const xse=t=>new Am(qD(t.readString(),t.readAny()));class dh{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new dh(this.embed)}splice(e){throw Ea()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const Sse=t=>new dh(t.readJSON());class Gr{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Gr(this.key,this.value)}splice(e){throw Ea()}mergeWith(e){return!1}integrate(e,n){const r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,n){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const Ese=t=>new Gr(t.readKey(),t.readJSON());class nv{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new nv(this.arr)}splice(e){const n=new nv(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const r=this.arr.length;e.writeLen(r-n);for(let i=n;i{const e=t.readLen(),n=[];for(let r=0;r{const e=t.readLen(),n=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const Ase=t=>new Ia(t.readString()),Mse=[ise,ose,hse,dse,fse,mse,gse],Cse=0,Rse=1,Nse=2,kse=3,Ise=4,Ose=5,Lse=6;class ql{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new ql(this.type._copy())}splice(e){throw Ea()}mergeWith(e){return!1}integrate(e,n){this.type._integrate(e.doc,n)}delete(e){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let n=this.type._start;for(;n!==null;)n.gc(e,!0),n=n.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,n){this.type._write(e)}getRef(){return 7}}const Pse=t=>new ql(Mse[t.readTypeRef()](t)),rv=(t,e,n)=>{const{client:r,clock:i}=e.id,s=new Ur(an(r,i+n),e,an(r,i+n-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(n));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=an(e.redone.client,e.redone.clock+n)),e.right=s,s.right!==null&&(s.right.left=s),t._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=n,s};class Ur extends Qb{constructor(e,n,r,i,s,o,a,l){super(e,l.getLength()),this.origin=r,this.left=n,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=a,this.redone=null,this.content=l,this.info=this.content.isCountable()?hN:0}set marker(e){(this.info&t1)>0!==e&&(this.info^=t1)}get marker(){return(this.info&t1)>0}get keep(){return(this.info&uN)>0}set keep(e){this.keep!==e&&(this.info^=uN)}get countable(){return(this.info&hN)>0}get deleted(){return(this.info&e1)>0}set deleted(e){this.deleted!==e&&(this.info^=e1)}markDeleted(){this.info|=e1}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=ri(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=ri(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===bf&&this.id.client!==this.parent.client&&this.parent.clock>=ri(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=bN(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Uc(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Rs||this.right&&this.right.constructor===Rs)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Ur&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===Ur&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===bf){const r=s1(n,this.parent);r.constructor===Rs?this.parent=null:this.parent=r.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=bN(e,e.doc.store,an(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),w0(this.origin,i.origin)){if(i.id.client{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),J_(e.deleteSet,this.id.client,this.id.clock,this.length),MN(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw Ra();this.content.gc(e),n?zie(e,this,new Rs(this.id,this.length)):this.content=new zp(this.length)}write(e,n){const r=n>0?an(this.id.client,this.id.clock+n-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&xy|(r===null?0:Ls)|(i===null?0:xl)|(s===null?0:Op);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const a=this.parent;if(a._item!==void 0){const l=a._item;if(l===null){const c=Fie(a);e.writeParentInfo(!0),e.writeString(c)}else e.writeParentInfo(!1),e.writeLeftID(l.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===bf?(e.writeParentInfo(!1),e.writeLeftID(a)):Ra();s!==null&&e.writeString(s)}this.content.write(e,n)}}const XD=(t,e)=>Dse[e&xy](t),Dse=[()=>{Ra()},yse,wse,vse,Ase,Sse,Ese,Pse,bse,xse,()=>{Ra()}],Use=10;class Zs extends Qb{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){Ra()}write(e,n){e.writeInfo(Use),Ht(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const KD=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},YD="__ $YJS$ __";KD[YD]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");KD[YD]=!0;let uw,hw,Fse=t=>t();function Bse(t,e){if(hw)return hw(t,e);Fse(t)}function Ju(t,e,n){if(uw)return uw.apply(null,arguments);throw new Error("observable implementation not provided. Call enableReactiveBindings, enableVueBindings or enableMobxBindings.")}function zse(t){uw=function(e,n,r){const i=t.createAtom(e);return n&&n(),i},hw=(e,n)=>t.reaction(e,n,{fireImmediately:!1})}const IN=new WeakSet;function Vse(t){if(IN.has(t))return t;IN.add(t);let e;const n=new Map;function r(){if(!e){const h=p=>{(p.changes.added.size||p.changes.deleted.size||p.changes.keys.size||p.changes.delta.length)&&e.reportChanged()};e=Ju("map",()=>{t.observe(h)},()=>{t.unobserve(h)})}e.reportObserved(t._implicitObserver)}function i(h){let p=n.get(h);if(!p){const m=g=>{p.reportChanged()};p=Ju(h+"",()=>{t.observe(m)},()=>{t.unobserve(m)}),n.set(h,p)}p.reportObserved(t._implicitObserver)}const s=t.get;t.get=function(h){if(typeof h!="number")throw new Error("unexpected");return i(h),Reflect.apply(s,this,arguments)};function o(h){const p=t[h];t[h]=function(){return r(),Reflect.apply(p,this,arguments)}}function a(h){let p=t,m=Object.getOwnPropertyDescriptor(p,h);if(m||(p=Object.getPrototypeOf(p),m=Object.getOwnPropertyDescriptor(p,h)),m||(p=Object.getPrototypeOf(p),m=Object.getOwnPropertyDescriptor(p,h)),!m)throw new Error("property not found");const g=m.get;m.get=function(){return this._disableTracking||r(),Reflect.apply(g,this,arguments)},Object.defineProperty(t,h,m)}function l(h,p){let m=t,g=Object.getOwnPropertyDescriptor(m,h);if(g||(m=Object.getPrototypeOf(m),g=Object.getOwnPropertyDescriptor(m,h)),g||(m=Object.getPrototypeOf(m),g=Object.getOwnPropertyDescriptor(m,h)),!g)throw new Error("property not found");Object.defineProperty(t,p,g)}o("forEach"),o("toJSON"),o("toArray"),o("slice"),o("map"),l("length","lengthUntracked"),a("length");const c=t.push;t.push=function(h){this._disableTracking=!0;const p=c.call(this,h);return this._disableTracking=!1,p};const u=t.slice;return t.slice=function(h,p){this._disableTracking=!0;const m=u.call(this,h,p);return this._disableTracking=!1,m},t}const ON=new WeakSet;function Hse(t){if(ON.has(t))return t;ON.add(t);let e;function n(){if(!e){let s=Array.from(t.share.keys());const o=a=>{const l=Array.from(t.share.keys());JSON.stringify(s)!==JSON.stringify(l)&&(s=l,e.reportChanged())};e=Ju("map",()=>{t.on("beforeObserverCalls",o)},()=>{t.off("beforeObserverCalls",o)})}e.reportObserved(t._implicitObserver)}const r=t.get;t.get=function(s){if(typeof s!="string")throw new Error("unexpected");const o=Reflect.apply(r,this,arguments);return My(o),o};function i(s){const o=t[s];let a;t[s]=function(){let l,c=arguments;return n(),a&&a.removeObservers(),a=Bse(()=>(l=Reflect.apply(o,t,c),l),()=>e.reportChanged()),l}}return i("toJSON"),Object.defineProperty(t,"keys",{get:()=>(n(),Object.keys(t.share))}),t}const LN=new WeakSet;function Gse(t){if(LN.has(t))return t;LN.add(t);let e;const n=new Map;function r(){if(!e){const a=l=>{(l.changes.added.size||l.changes.deleted.size||l.changes.keys.size||l.changes.delta.length)&&e.reportChanged()};e=Ju("map",()=>{t.observe(a)},()=>{t.unobserve(a)})}e.reportObserved(t._implicitObserver)}function i(a){let l=n.get(a);if(!l){const c=u=>{u.keysChanged.has(a)&&(u.changes.added.size||u.changes.deleted.size||u.changes.keys.size||u.changes.delta.length)&&l.reportChanged()};l=Ju(a,()=>{t.observe(c)},()=>{t.unobserve(c)}),n.set(a,l)}l.reportObserved(t._implicitObserver)}const s=t.get;t.get=function(a){if(typeof a!="string")throw new Error("unexpected");return i(a),Reflect.apply(s,this,arguments)};function o(a){const l=t[a];t[a]=function(){return r(),Reflect.apply(l,this,arguments)}}return o("values"),o("entries"),o("keys"),o("forEach"),o("toJSON"),t}const PN=new WeakSet;function DN(t){if(PN.has(t))return t;PN.add(t);let e;const n=i=>{e.reportChanged()};e=Ju("text",()=>{t.observe(n)},()=>{t.unobserve(n)});function r(i){const s=t[i];t[i]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(s,this,arguments)}}return r("toString"),r("toJSON"),t}const UN=new WeakSet;function FN(t){if(UN.has(t))return t;UN.add(t);let e;const n=s=>{(s.changes.added.size||s.changes.deleted.size||s.changes.keys.size||s.changes.delta.length)&&e.reportChanged()};e=Ju("xml",()=>{t.observe(n)},()=>{t.unobserve(n)});function r(s){const o=t[s];t[s]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(o,this,arguments)}}function i(s){let o=t,a=Object.getOwnPropertyDescriptor(o,s);if(a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),!a)throw new Error("property not found");const l=a.get;a.get=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(l,this,arguments)},Object.defineProperty(t,s,a)}return r("toString"),r("toDOM"),r("toArray"),r("getAttribute"),i("firstChild"),t}function My(t){return t instanceof Yu||t instanceof Fo?DN(t):t instanceof wa?Vse(t):t instanceof Na?Gse(t):t instanceof $l||Object.prototype.hasOwnProperty.call(t,"autoLoad")?Hse(t):t instanceof ka||t instanceof kl?FN(t):t}function BN(t){t.share.forEach(e=>{e.constructor!==lr&&My(e)})}function zN(t,e){for(let r=t.length-1;r>=e;r--){let i=t[r];if(!i.deleted){var n;if(i instanceof Rs)continue;(n=i.content)==null||n.getContent().forEach(s=>{s instanceof lr&&My(s)})}}}const VN=new WeakSet;function Wse(t){VN.has(t)||(VN.add(t),My(t),t.store.clients.forEach(e=>{e&&zN(e,0)}),BN(t),t.on("beforeObserverCalls",e=>{BN(t),e.afterState.forEach((n,r)=>{const i=e.beforeState.get(r)||0;if(i!==n){const s=e.doc.store.clients.get(r);if(!s)return;const o=Uo(s,i);zN(s,o)}})}))}class Vp{constructor(e){this.value=void 0,this.value=e}}function jse(t){return ArrayBuffer.isView(t)?new Vp(t):new Vp(Object.freeze(t))}function $se(t){const e=function(){var a;let l=(a=this[co])==null?void 0:a.implicitObserver;return t._implicitObserver=l,t.slice.bind(t).apply(t,arguments).map(u=>{const h=Cy(u,l);return l&&typeof h=="object"?jf(h,l):h})},n=function(a){return a.map(l=>{const c=eA(l);let u=Fc(c)||c;if(u instanceof Vp&&(u=u.value),u instanceof lr&&u.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return u})},r=function(){return[].findIndex.apply(e.apply(this),arguments)},i={slice:e,unshift:(...o)=>(t.unshift(n(o)),t.lengthUntracked),push:(...o)=>(t.push(n(o)),t.lengthUntracked),insert:t.insert.bind(t),toJSON:t.toJSON.bind(t),forEach:function(){return[].forEach.apply(e.apply(this),arguments)},every:function(){return[].every.apply(e.apply(this),arguments)},filter:function(){return[].filter.apply(e.apply(this),arguments)},find:function(){return[].find.apply(e.apply(this),arguments)},findIndex:r,some:function(){return[].some.apply(e.apply(this),arguments)},includes:function(){return[].includes.apply(e.apply(this),arguments)},map:function(){return[].map.apply(e.apply(this),arguments)},indexOf:function(){const o=arguments[0];return r.call(this,a=>Zse(a,o))},splice:function(){let o=arguments[0]<0?t.length-Math.abs(arguments[0]):arguments[0],a=arguments[1],l=Array.from(Array.from(arguments).slice(2)),c=e.apply(this,[o,Number.isInteger(a)?o+a:void 0]);return t.doc?t.doc.transact(()=>{t.delete(o,a),t.insert(o,n(l))}):(t.delete(o,a),t.insert(o,n(l))),c}},s=[];for(let o in i)s[o]=i[o];return s}function Wd(t){if(typeof t=="string"&&t.trim().length){const e=Number(t);if(Number.isInteger(e))return e}return t}function HN(t,e=new wa){if(e[Fr])throw new Error("unexpected");const n=$se(e),r=new Proxy(n,{set:(i,s,o)=>{throw typeof Wd(s)!="number"?new Error:new Error("array assignment is not implemented / supported")},get:(i,s,o)=>{const a=Wd(s);if(a===Ry)return e;if(typeof a=="number"){let u;if(o&&o[co]){var l;u=(l=o[co])==null?void 0:l.implicitObserver,e._implicitObserver=u}let h=e.get(a);return h=Cy(h,u),h}if(a===Symbol.toStringTag)return"Array";if(a===Symbol.iterator){const u=e.slice();return Reflect.get(u,a)}return a==="length"?e.length:Reflect.get(i,a,o)},deleteProperty:(i,s)=>{const o=Wd(s);if(typeof o!="number")throw new Error;return o=0?(e.delete(o),!0):!1},has:(i,s)=>{const o=Wd(s);return typeof o!="number"?Reflect.has(i,o):o=0},getOwnPropertyDescriptor(i,s){const o=Wd(s);if(o==="length")return{enumerable:!1,configurable:!1,writable:!0};if(typeof o=="number"&&o>=0&&o{const s=[];for(let o=0;o{if(typeof i!="string")throw new Error;const o=eA(s);let a=Fc(o)||o;if(a instanceof Vp&&(a=a.value),a instanceof lr&&a.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return e.set(i,a),!0},get:(r,i,s)=>{if(i===Ry)return e;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[co]){var a;o=(a=s[co])==null?void 0:a.implicitObserver,e._implicitObserver=o}let l=e.get(i);return l=Cy(l,o),l},deleteProperty:(r,i)=>{if(typeof i!="string")throw new Error;return e.has(i)?(e.delete(i),!0):!1},has:(r,i)=>!!(typeof i=="string"&&e.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&e.has(i))return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(e.keys())});gp.set(e,n);for(let r in t)n[r]=t[r];return n}function qse(t){return t instanceof lr}const gp=new WeakMap;function Cy(t,e){if(qse(t)){if(t._implicitObserver=e,t instanceof wa||t instanceof Na){if(!gp.has(t)){const n=eA(t);gp.set(t,n)}t=gp.get(t)}else if(t instanceof kl||t instanceof ka||t instanceof Yu||t instanceof Kf||t instanceof Fo)Db(t),t.__v_skip=!0;else throw new Error("unknown YType");return t}else{if(t===null)return null;if(typeof t=="object")return jse(t)}return t}function eA(t){if(t==null)return t;if(t=Fc(t)||t,t instanceof wa)return HN([],t);if(t instanceof Na)return GN({},t);if(typeof t=="string")return t;if(Array.isArray(t))return HN(t);if(t instanceof kl||t instanceof ka||t instanceof Yu||t instanceof Kf)return t;if(t instanceof Fo)return t;if(typeof t=="object")return t instanceof Vp?t:GN(t);if(typeof t=="number"||typeof t=="boolean")return t;throw new Error("invalid")}function Xse(t){for(let[e,n]of Object.entries(t))if(Array.isArray(n)){if(n.length!==0)throw new Error("Root Array initializer must always be empty array")}else if(n&&typeof n=="object"){if(Object.keys(n).length!==0||Object.getPrototypeOf(n)!==Object.prototype)throw new Error("Root Object initializer must always be {}")}else if(n!=="xml"&&n!=="text")throw new Error("unknown Root initializer")}function WN(t,e,n){let r=e[n];if(!r){n!=="__v_raw"&&n!=="__v_isRef"&&n!=="__v_isReadonly"&&console.warn("property not found on root doc",n);return}return r==="xml"?t.getXmlFragment(n):r==="text"?t.getText(n):Array.isArray(r)?t.getArray(n):t.getMap(n)}function Kse(t,e){if(t[Fr])throw new Error("unexpected");Xse(e);const n=new Proxy({},{set:(r,i,s)=>{throw typeof i!="string"?new Error:new Error("cannot set new elements on root doc")},get:(r,i,s)=>{if(i===Ry)return t;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[co]){var a;o=(a=s[co])==null?void 0:a.implicitObserver,t._implicitObserver=o}if(i==="toJSON"){for(let u of Object.keys(e))WN(t,e,u);return Reflect.get(t,i)}let l=WN(t,e,i);return l=Cy(l,o),l},deleteProperty:(r,i)=>{throw new Error("deleteProperty not available for doc")},has:(r,i)=>!!(typeof i=="string"&&t.share.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&t.share.has(i)||i==="toJSON")return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(t.share.keys())});return gp.set(t,n),n}zse(sre);const Ry=Symbol("INTERNAL_SYMBOL");function jN(t,e){const n=Fc(t)||t;if(!n)throw new Error("not a valid synced object");return n instanceof $l?(n.on("update",e),()=>{n.off("update",e)}):(n.observeDeep(e),()=>{n.unobserveDeep(e)})}function Yse(t){const e=Fc(t);if(!(e instanceof $l))throw new Error("store is not a valid syncedStore that maps to a Y.Doc");return e}function Fc(t){if(typeof t!="object"||t===null)return;const e=t[Ry];return e&&(Db(e),e.__v_skip=!0),e}function Zse(t,e){if(t===e)return!0;if(typeof t=="object"&&typeof e=="object"){const n=Fc(t),r=Fc(e);return!n||!r?!1:n===r}return!1}function Jse(t,e=new $l){return Wse(e),Kse(e,t)}function Qse(t,e){var n=Ne.useReducer(function(a){return a+1},0),r=n[1],i=Ne.useRef(),s=Ne.useRef(!1);i.current||(i.current=new Lb(function(){s.current&&r()}));var o=Ne.useMemo(function(){var a;return(a=i.current)==null||a.removeObservers(),jf(t,i.current)},[]);return Ne.useEffect(function(){return s.current=!0,i.current||r(),function(){var a;s.current=!1,(a=i.current)==null||a.removeObservers(),i.current=null}},[]),o}function eoe(t,e){if(!Fc(t))throw new Error("syncedObject passed to useSyncedStore is not a SyncedStore Store or internal data type.");return Qse(t)}const tA=0,ZD=1,JD=2,toe=(t,e)=>{Ht(t,tA);const n=Die(e);yi(t,n)},QD=(t,e,n)=>{Ht(t,ZD),yi(t,Iie(e,n))},noe=(t,e,n)=>QD(e,n,Ii(t)),eU=(t,e,n)=>{try{Rie(e,Ii(t),n)}catch(r){console.error("Caught error while handling a Yjs update",r)}},roe=(t,e)=>{Ht(t,JD),yi(t,e)},ioe=eU,soe=(t,e,n,r)=>{const i=Gt(t);switch(i){case tA:noe(t,e,n);break;case ZD:eU(t,n,r);break;case JD:ioe(t,n,r);break;default:throw new Error("Unknown message type")}return i},Oa=Jse({shared:[]});function Mm(t,e,n){return t.find(r=>r.key===e&&r.type===n)}function ooe(){return eoe(Oa)}function tU(t,e){const n=ooe(),r=Mm(n.shared,t,e);return Z(r)?r:void 0}function nA(t){return tU(t,0)}function nU(t){return tU(t,1)}function rU(t,e,n){const r=Mm(Oa.shared,t,e);Z(r)||Oa.shared.push({key:t,type:e,value:n})}function aoe(t,e){rU(t,0,e)}function iU(t,e){const n=new Fo(e);rU(t,1,n)}function Ac(t,e){const n=Mm(Oa.shared,t,0);if(Z(n)){n.value=e;return}Oa.shared.push({key:t,type:0,value:e})}function loe(t,e){const n=new Fo(e),r=Mm(Oa.shared,t,1);if(Z(r)){r.value=n;return}Oa.shared.push({key:t,type:1,value:n})}function sU(t,e,n){let r;function i(){const o=Mm(Oa.shared,t,e);Z(o)&&(s(),r=jN(o,()=>n(o.value)))}const s=jN(Oa.shared,i);return i(),()=>r==null?void 0:r()}function coe(t,e){return sU(t,0,e)}function uoe(t,e){return sU(t,1,n=>e(n.toJSON()))}function f_(t){return Mo(t)}let $N=!1;const Sc=Yse(Oa),ul=rh("modem",["second"],t=>{switch(t.target){case"second":!$N&&t.data%2===0&&ul.emit("modem:join");break;case"join":if(t.sender!==ul.id()){ul.reply(t,"joinack");const e=bc();toe(e,Sc),ul.reply(t,"sync",f_(e));const n=bc();QD(n,Sc),ul.reply(t,"sync",f_(n))}break;case"joinack":$N=!0;break;case"sync":{if(Z(t.data)&&t.sender!==ul.id()){const e=fh(t.data),n=bc();soe(e,n,Sc,ul)===tA&&ul.emit("modem:sync",f_(n))}break}}});function oU(t){const e=bc();roe(e,t),ul.emit("modem:sync",f_(e))}Sc.on("update",oU);Sc.on("destroy",()=>{Sc==null||Sc.off("update",oU)});const fw=66.666,iv=Math.round(1e3/fw),hoe=3;function qh(t){return new Promise(e=>setTimeout(e,t))}const Bc="$dkpurple",foe="$196",doe="$205";function bs(t,e){return`$${t}${e}$blue`}function qN(t,e){return`$${t}${e}$ondkblue`}function qn(t,e){to(t,e)}function poe(t,e){const n=foe.repeat(e);qn(t,`${Bc}${n}`)}function rA(t,e){const n=doe.repeat(e);qn(t,`${Bc}${n}`)}function fl(t,e){qn(t,`${Bc} ${" ".repeat(e.length)} `),poe(t,e.length+2),qn(t,`${Bc} $white${e} `),rA(t,e.length+2)}function al(t,e){qn(t,`${Bc} ${" ".repeat(e.length)} `),qn(t,`${Bc} $gray${e} `),rA(t,e.length+2)}function rn(t,e,n){qn(t,`${Bc} $white${e} $blue${n}`)}function hn(t,e){qn(t,`${Bc}$blue${e}`)}function XN(t,e,n){qn(t,`!copyit ${e};${n}`)}function moe(){try{const t=window.location.hash.slice(1);if(t.length)return t}catch(t){Pn("register","crash",t.message)}return""}let dw=!0;window.addEventListener("hashchange",()=>{dw?window.location.reload():dw=!0});function goe(t){const e=`#${t}`;window.location.hash!==e&&(dw=!1,window.location.hash=e,to(Or.name(),`wrote ${(t==null?void 0:t.length)??0} chars [${t.slice(0,8)}...${t.slice(-8)}]`))}const d_="bios-node";function _oe(t){try{const e=localStorage.getItem(d_);return Z(e)?e:(localStorage.setItem(d_,t),t)}catch(e){Pn(Or.name(),d_,e.message)}}function voe(){localStorage.removeItem(d_)}const sv="bios-select";function yoe(){try{return localStorage.getItem(sv)??""}catch(t){Pn(Or.name(),sv,t.message)}return""}function xoe(t){try{localStorage.setItem(sv,t)}catch(e){Pn(Or.name(),sv,e.message)}}async function KN(t){const e=new FormData;e.append("url",t);const n=new Request("https://bytes.zed.cafe",{method:"POST",body:e});return await(await fetch(n)).text()}let l1=0;const YN=1,Or=rh("register",["second","ready","error"],function(t){const e=ss.getState();switch(t.target){case"error:login:main":case"error:login:title":case"error:login:player":jR(Or.name());break;case"dev":tp("register:dev",async function(){if(window.location.href.includes("/locked/")?"locked":""){const r=await KN(window.location.href);XN("devshare",r,r)}else fl(Or.name(),"creating locked terminal"),await qh(100),window.location.href=window.location.href.replace("/#","/locked/#")});break;case"share":tp("register:share",async function(){const n=await KN(window.location.href.replace(/cafe.*locked/,"cafe"));XN("share",n,n)});break;case"refresh":tp("register:refresh",async function(){fl(Or.name(),"BYE"),await qh(100),window.location.reload()});break;case"nuke":tp("register:nuke",async function(){fl(Or.name(),"nuke in"),rn(Or.name(),"3","..."),await qh(1e3),rn(Or.name(),"2","..."),await qh(1e3),rn(Or.name(),"1","..."),await qh(1e3),fl(Or.name(),"BYE"),await qh(100),window.location.hash="",window.location.reload()});break;case"ready":{if(!Z(t.player))return;const n=_oe(t.player);if(!Z(n))return;e.gadget.player||(ss.setState(r=>({...r,gadget:{...r.gadget,player:n}})),setTimeout(()=>FW("register",n),256));break}case"ackinit":{if(!Z(t.player))return;const n=moe();if(n.length===0){Pn(Or.name(),"content","no content found"),jR(Or.name());return}BW(Or.name(),n,yoe(),t.player);break}case"ackbooks":Z(t.player)&&zW(Or.name(),t.player);break;case"acklogin":if(Z(t.player)){const{player:n}=t;ST(Or.name()),setTimeout(()=>bW(Or.name(),n),1e3)}break;case"flush":if(ln(t.data)){const[n,r]=t.data;Kt(n)&&Kt(r)&&(document.title=n,goe(r))}break;case"select":Kt(t.data)&&xoe(t.data);break;case"nodetrash":voe();break;case"second":++l1,l1>=YN&&(l1-=YN,e.gadget.player&&HW(Or.name(),e.gadget.player));break}});rh("tape",[],t=>{const{layout:e,terminal:n,editor:r}=es.getState();function i(o){let a=[[fr(),o.target,o.sender,...o.data],...n.logs];a.length>eN&&(a=a.slice(0,eN)),es.setState(l=>({terminal:{...l.terminal,logs:a}}))}function s(o){let l=e+(o?1:-1);if(l<0&&(l+=Li.MAX),l>=Li.MAX&&(l-=Li.MAX),!r.open)switch(l){case Li.SPLIT_Y:case Li.SPLIT_Y_ALT:l=Li.TOP;break}es.setState({layout:l})}switch(t.target){case"info":n.level>=o_.INFO&&i(t);break;case"debug":n.level>=o_.DEBUG&&i(t);break;case"error":n.level>o_.OFF&&i(t);break;case"crash":es.setState(o=>({layout:Li.FULL,terminal:{...o.terminal,open:!0}}));break;case"terminal:open":es.setState(o=>({terminal:{...o.terminal,open:!0}}));break;case"terminal:close":es.setState(o=>({terminal:{...o.terminal,open:!1}}));break;case"terminal:inclayout":oW(t.data)&&s(t.data);break;case"editor:open":if(ln(t.data)&&Z(t.player)){const{player:o}=t,[a,l,c,u]=t.data??["","",""];es.setState(h=>({terminal:{...h.terminal,open:!0},editor:{open:!0,player:o,book:a,page:l,type:c,title:u}}))}break;case"editor:close":es.setState(o=>({editor:{...o.editor,open:!1}}));break}});const c1=rh("clock",[],()=>{});let u1=0,A0=0,h1=0,ZN=performance.now();function aU(){const t=performance.now(),e=t-ZN,n=window.location.href.includes("/locked/")?"locked":"";h1+=e,h1>=fw&&(h1%=fw,c1.emit("tick",A0,n),c1.emit("tock",A0,n),++u1,++A0,u1>=iv&&(u1%=iv,c1.emit("second",A0,n))),ZN=t,setTimeout(aU,1)}aU();let M0;function Soe(){if(Z(M0))return;M0=new Xne;const t=qne(e=>M0.postMessage(e));M0.addEventListener("message",e=>t(e.data))}const pw=3,lU=2,Af=8,Mf=14,os=Af*lU,Vi=Mf*lU,ml=16;var np=(t=>(t[t.BLANK=0]="BLANK",t[t.TILES=1]="TILES",t[t.SPRITES=2]="SPRITES",t[t.DITHER=3]="DITHER",t[t.MEDIA=4]="MEDIA",t[t.CONTROL=5]="CONTROL",t))(np||{});function Eoe(t){let e=0,n=0,r=0,i=0,s=1;return t.forEach(o=>{switch(o.type){case 1:e=Math.max(e,o.width),n=Math.max(n,o.height);break;case 3:e=Math.max(e,o.width),n=Math.max(n,o.height);break;case 5:r=o.focusx,i=o.focusy,s=o.viewscale;break}}),{width:e,height:n,focusx:r,focusy:i,viewscale:s}}var xi=(t=>(t[t.START=0]="START",t[t.LEFT=1]="LEFT",t[t.RIGHT=2]="RIGHT",t[t.TOP=3]="TOP",t[t.BOTTOM=4]="BOTTOM",t[t.SCROLL=5]="SCROLL",t))(xi||{});const woe={start:0,left:1,right:2,top:3,bottom:4,scroll:5},Toe={0:1,1:20,2:20,3:1,4:1,5:40};function md(t,e){return`${t}:${e}`}const cU=1,uU=16,hU=256;var Ue=(t=>(t[t.NONE=0]="NONE",t[t.ALT=1]="ALT",t[t.CTRL=2]="CTRL",t[t.SHIFT=3]="SHIFT",t[t.MOVE_UP=4]="MOVE_UP",t[t.MOVE_DOWN=5]="MOVE_DOWN",t[t.MOVE_LEFT=6]="MOVE_LEFT",t[t.MOVE_RIGHT=7]="MOVE_RIGHT",t[t.OK_BUTTON=8]="OK_BUTTON",t[t.CANCEL_BUTTON=9]="CANCEL_BUTTON",t[t.MENU_BUTTON=10]="MENU_BUTTON",t[t.SHOOT_UP=11]="SHOOT_UP",t[t.SHOOT_DOWN=12]="SHOOT_DOWN",t[t.SHOOT_LEFT=13]="SHOOT_LEFT",t[t.SHOOT_RIGHT=14]="SHOOT_RIGHT",t))(Ue||{});const boe=new xe,fU=Ne.createContext([]);function Ny(){return Ne.useContext(fU)}function Aoe({width:t=0,height:e=0,children:n,...r}){const i=Ne.useRef(null),[s]=Ne.useState(()=>{const a=[];return t&&a.push(new xo,new xo),e&&a.push(new xo,new xo),a}),[o]=Ne.useState(()=>[new xe(0,0,0),new xe(0,0,0),new xe(0,0,0),new xe(0,0,0),new xe(0,0,0)]);return Lv(()=>{if(i.current){const a=i.current.localToWorld(o[0].set(0,0,0)),l=[];if(t){const c=t*.5;l.push(i.current.localToWorld(o[3].set(c,0,0)),i.current.localToWorld(o[4].set(-c,0,0)))}if(e){const c=e*.5;l.push(i.current.localToWorld(o[1].set(0,c,0)),i.current.localToWorld(o[2].set(0,-c,0)))}for(let c=0;cSymbol.iterator in t,QN=t=>"entries"in t,ek=(t,e)=>{const n=t instanceof Map?t:new Map(t.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[i,s]of n)if(!Object.is(s,r.get(i)))return!1;return!0},Moe=(t,e)=>{const n=t[Symbol.iterator](),r=e[Symbol.iterator]();let i=n.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=n.next(),s=r.next()}return!!i.done&&!!s.done};function Coe(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null?!1:!JN(t)||!JN(e)?ek({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)}):QN(t)&&QN(e)?ek(t,e):Moe(t,e)}function qc(t){const e=Co.useRef();return n=>{const r=t(n);return Coe(e.current,r)?e.current:e.current=r}}const Roe=Date.now(),yo={get value(){return(Date.now()-Roe)/1e3%1e6}},Noe=120;let dU=0;function koe(t){dU=Noe/t}koe(150);const iA={get value(){return dU}};function sA(t){const e=t.clone();return e.uniforms.time=yo,e.uniforms.interval=iA,e}function Ioe(t,e,n,r){const i=e*n*4;for(let s=0,o=0;s + + varying vec2 vUv; + + void main() { + vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); + gl_Position = projectionMatrix * mvPosition; + + vUv = uv; + + #include + } + `,fragmentShader:` + #include + + uniform vec3 color; + uniform sampler2D data; + + varying vec2 vUv; + + // adapted from https://www.shadertoy.com/view/Mlt3z8 + float bayerDither2x2( vec2 v ) { + return mod( 3.0 * v.y + 2.0 * v.x, 4.0 ); + } + + float bayerDither4x4( vec2 v ) { + vec2 P1 = mod( v, 2.0 ); + vec2 P2 = mod( floor( 0.5 * v ), 2.0 ); + return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 ); + } + + void main() { + #include + + float alpha = texture2D(data, vUv).r; + if (alpha < 1.0) { + vec2 ditherCoord = floor( mod( gl_FragCoord.xy, 4.0 ) ); + if ( bayerDither4x4( ditherCoord ) / 16.0 >= alpha ) { + discard; + } + } + + gl_FragColor.rgba = vec4(color.xyz, 1.0); + } + `});function Poe(){return sA(Loe)}function ky(t,e,n){typeof t!="number"&&(t=0,e=0,n=1),typeof e!="number"&&(e=t,t=0,n=1),typeof n!="number"&&(n=1);const r=[],i=Math.min(t,e),s=Math.max(t,e);for(let o=i;o<=s;o+=n)r.push(o);return r}function Doe(t){return t[ep(0,t.length-1)]}function dl(...t){return Doe(t.flat())}function pU(t,e=16){return t?ky(e-1).map(n=>{const r=n*pw;return new cn(t.bits[r]/63,t.bits[r+1]/63,t.bits[r+2]/63)}):[]}function Uoe(t){const e=document.createElement("canvas");if(e.width=(t==null?void 0:t.width)||1,e.height=(t==null?void 0:t.height)||1,t){const n=e.getContext("2d"),r=n==null?void 0:n.getImageData(0,0,t.width,t.height);if(r&&n){let i=0;const{data:s}=r;for(let o=0;ooA(t),[t])}const ov=[0,1,0],vU=[1,1,0],av=[1,0,0],yU=[0,0,0],$oe=new Float32Array([...ov,...av,...vU,...ov,...yU,...av]),qoe=new Float32Array([...ov.slice(0,2),...av.slice(0,2),...vU.slice(0,2),...ov.slice(0,2),...yU.slice(0,2),...av.slice(0,2)]);function Xoe(t,e,n,r,i,s){const o=e*n*4;for(let a=0,l=0;a{switch(a%3){case 0:return o*r;case 1:return o*i;default:return o}});t.setAttribute("position",new Jn(s,3)),t.setAttribute("uv",new Jn(qoe,2)),t.computeBoundingBox(),t.computeBoundingSphere()}const Yoe=pU(gU()),nk=oA(Iy()),Zoe=new Hi({transparent:!1,uniforms:{time:yo,interval:iA,map:new Mn(nk),alt:new Mn(nk),data:new Mn(null),palette:new Mn(Yoe),size:{value:new St},step:{value:new St}},vertexShader:` + #include + varying vec2 vUv; + void main() { + vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); + gl_Position = projectionMatrix * mvPosition; + vUv = uv; + #include + } + `,fragmentShader:` + #include + + uniform float time; + uniform float interval; + uniform sampler2D map; + uniform sampler2D alt; + uniform usampler2D data; + uniform vec3 palette[16]; + uniform vec2 size; + uniform vec2 step; + varying vec2 vUv; + + void main() { + #include + + uvec4 tiledata = texture(data, vUv); + int colori = int(tiledata.z); + int bgi = int(tiledata.w); + + vec2 charPosition = mod(vUv, size) / size; + vec2 uv = vec2(charPosition.x * step.x, charPosition.y * step.y); + vec3 color = palette[colori]; + + uv.x += step.x * float(tiledata.x); + uv.y += step.y * float(tiledata.y); + uv.y = 1.0 - uv.y; + + bool useAlt = mod(time, interval * 2.0) > interval; + vec3 blip = useAlt ? texture(alt, uv).rgb : texture(map, uv).rgb; + + if (blip.r == 0.0) { + if (bgi >= ${wn.ONCLEAR}) { + discard; + } + color = palette[bgi]; + } + + gl_FragColor.rgb = color; + gl_FragColor.a = 1.0; + } + `});function Joe(){return sA(Zoe)}function Oy({width:t,height:e,alphas:n}){const r=Ny(),i=Ne.useRef(null),[s]=Ne.useState(()=>Poe());return Ne.useEffect(()=>{s.uniforms.data.value=Ooe(t,e)},[s.uniforms.data,t,e]),Ne.useEffect(()=>{Ioe(s.uniforms.data.value,t,e,n)},[s.uniforms.data.value,t,e,n]),Ne.useEffect(()=>{i.current&&(xU(i.current,t,e),s.clipping=r.length>0,s.clippingPlanes=r,s.needsUpdate=!0)},[s,r,t,e]),ve.jsx("mesh",{material:s,children:ve.jsx("bufferGeometry",{ref:i})})}function Qoe({width:t,height:e,alpha:n}){const r=Ne.useMemo(()=>new Array(t*e).fill(n),[t,e,n]);return ve.jsx(Oy,{width:t,height:e,alphas:r})}const jd=new QH,du=new St;function eae({width:t,height:e,top:n,left:r,right:i,bottom:s,scale:o=.125,alpha:a=.25}){const l=Ne.useMemo(()=>{const c=new Array(t*e);jd.min.x=r,jd.min.y=n,jd.max.x=i,jd.max.y=s,du.x=0,du.y=0;for(let u=0;u=t&&(du.x=0,++du.y);return c},[t,e,n,r,i,s,o,a]);return ve.jsx(Oy,{width:t,height:e,alphas:l})}const tae=pU(gU()),rk=oA(Iy()),nae=iv*2,rae=new Hi({transparent:!1,uniforms:{time:yo,interval:iA,smoothrate:new Mn(nae),map:new Mn(rk),alt:new Mn(rk),palette:new Mn(tae),pointSize:{value:new St(os,Vi)},rows:new Mn(1),step:new Mn(new St)},vertexShader:` + #include + + attribute float visible; + attribute vec4 charData; + attribute vec3 lastPosition; + attribute vec2 lastColor; + attribute vec2 lastBg; + attribute vec2 animShake; + attribute vec2 animBounce; + + uniform float smoothrate; + uniform float time; + uniform float interval; + uniform vec2 pointSize; + uniform vec3 palette[16]; + uniform float tindex; + + varying float vVisible; + varying vec2 vCharData; + varying vec3 vColor; + varying vec4 vBg; + + float rand(float co) { + return fract(sin(co*(91.3458)) * 47453.5453); + } + + vec3 colorFromIndex(float index) { + return palette[int(index)]; + } + + vec4 empty; + + vec4 bgFromIndex(float index) { + if (int(index) >= ${wn.ONCLEAR}) { + return empty; + } + vec4 bg; + bg.rgb = colorFromIndex(index); + bg.a = 1.0; + return bg; + } + + float animDelta(float startTime, float deltaMod, float maxDelta) { + float delta = time - startTime; + if (delta < 0.0) { + return maxDelta; + } + return clamp(delta * deltaMod, 0.0, maxDelta); + } + + void main() { + vVisible = visible; + + float deltaPosition = clamp((time - lastPosition.z) * smoothrate, 0.0, 1.0); + vec2 animPosition = mix(lastPosition.xy, position.xy, deltaPosition); + + float deltaShake = 1.0 - animDelta(animShake.y, smoothrate * 0.5, 1.0); + animPosition += vec2( + deltaShake - rand(cos(time) + animShake.x) * deltaShake * 2.0, + deltaShake - rand(sin(time) + animShake.x) * deltaShake * 2.0 + ) * 0.5; + + float deltaBounce = 1.0 - abs(1.0 - animDelta(animBounce.y, smoothrate, 2.0)); + animPosition.y -= smoothstep(0.0, 1.0, deltaBounce); + + float deltaColor = animDelta(lastColor.y, smoothrate, 1.0); + vec3 sourceColor = colorFromIndex(lastColor.x); + vec3 destColor = colorFromIndex(charData.z); + vColor = mix(sourceColor, destColor, deltaColor); + + float deltaBg = animDelta(lastBg.y, smoothrate, 1.0); + vec4 sourceBg = bgFromIndex(lastBg.x); + vec4 destBg = bgFromIndex(charData.w); + vBg = mix(sourceBg, destBg, deltaBg); + + vCharData.xy = charData.xy; + + animPosition = animPosition * pointSize; + animPosition += pointSize * 0.5; + animPosition.x += (pointSize.y - pointSize.x) * 0.5; + + vec4 mvPosition = modelViewMatrix * vec4(animPosition, 0.0, 1.0); + gl_Position = projectionMatrix * mvPosition; + + // this handles things being scaled + gl_PointSize = pointSize.y * modelViewMatrix[0][0]; + + #include + } + `,fragmentShader:` + #include + + uniform float time; + uniform float interval; + uniform sampler2D map; + uniform sampler2D alt; + uniform float rows; + uniform vec2 step; + uniform vec2 pointSize; + + varying float vVisible; + varying vec2 vCharData; + varying vec3 vColor; + varying vec4 vBg; + + void main() { + #include + + float xscale = pointSize.y / pointSize.x; + float px = gl_PointCoord.x * xscale; + + if (vVisible == 0.0 || px >= 1.0) { + discard; + } + + vec2 lookup = vec2(vCharData.x, vCharData.y); + + vec2 idx = vec2(px, 1.0 - gl_PointCoord.y); + vec2 char = vec2(lookup.x * step.x, (rows - lookup.y) * step.y); + vec2 uv = idx * step + char; + + bool useAlt = mod(time, interval * 2.0) > interval; + vec3 blip = useAlt ? texture2D(alt, uv).rgb : texture2D(map, uv).rgb; + + if (blip.r == 0.0) { + gl_FragColor = vBg; + } else { + gl_FragColor.rgb = vColor; + gl_FragColor.a = 1.0; + } + } + `});function iae(){return sA(rae)}const sae=Iy(),ik=2048;function oae({sprites:t}){const e=_U(sae),n=Ny(),r=Ne.useRef(null),i=Ne.useRef([]),[s]=Ne.useState(()=>iae()),{width:o=0,height:a=0}=(e==null?void 0:e.image)??{};return Ne.useMemo(()=>{var h;i.current.length===0&&(i.current=Array.from({length:ik},()=>({id:"",x:0,y:0,char:0,color:0,bg:0})));const l={};for(let p=0;pp.id));let u=0;for(let p=0;p{const{current:l}=r,{current:c}=i;if(!l||!c)return;let u=l.getAttribute("visible"),h=l.getAttribute("lastVisible"),p=l.getAttribute("position"),m=l.getAttribute("charData"),g=l.getAttribute("lastPosition"),v=l.getAttribute("lastColor"),y=l.getAttribute("lastBg"),_=l.getAttribute("animShake"),S=l.getAttribute("animBounce");if(!u||u.count!==c.length){u=new Jn(new Float32Array(c.length),1),h=new Jn(new Float32Array(c.length),1),p=new Jn(new Float32Array(c.length*3),3),m=new Jn(new Float32Array(c.length*4),4),g=new Jn(new Float32Array(c.length*3),3),v=new Jn(new Float32Array(c.length*2),2),y=new Jn(new Float32Array(c.length*2),2),_=new Jn(new Float32Array(c.length*2),2),S=new Jn(new Float32Array(c.length*2),2);for(let E=0;E{if(!e||!r.current)return;const l=Math.round(o/Af),c=Math.round(a/Mf);s.uniforms.rows.value=c-1,s.uniforms.step.value.x=1/l,s.uniforms.step.value.y=1/c,s.clipping=n.length>0,s.clippingPlanes=n,s.needsUpdate=!0},[e,s,o,a,n]),ve.jsx("points",{frustumCulled:!1,material:s,children:ve.jsx("bufferGeometry",{ref:r})})}const aae=Iy();function SU({width:t,height:e,char:n,color:r,bg:i}){const s=_U(aae),o=Ny(),[a]=Ne.useState(()=>Joe()),l=Ne.useRef(null),{width:c=0,height:u=0}=(s==null?void 0:s.image)??{};return Ne.useEffect(()=>{t===0||e===0||(a.uniforms.data.value=Koe(t,e))},[a.uniforms.data,t,e]),Ne.useEffect(()=>{t===0||e===0||Xoe(a.uniforms.data.value,t,e,n,r,i)},[a.uniforms.data.value,t,e,n,r,i]),Ne.useEffect(()=>{t===0||e===0||!l.current||!s||(xU(l.current,t,e),a.uniforms.size.value.x=1/t,a.uniforms.size.value.y=1/e,a.uniforms.step.value.x=1/Math.round(c/Af),a.uniforms.step.value.y=1/Math.round(u/Mf),a.clipping=o.length>0,a.clippingPlanes=o,a.needsUpdate=!0)},[s,a,t,e,c,u,o]),ve.jsx("mesh",{material:a,children:ve.jsx("bufferGeometry",{ref:l})})}function lae({id:t,z:e}){const n=ss(qc(r=>r.gadget.layers.find(i=>i.id===t)));switch(n==null?void 0:n.type){default:case np.BLANK:return null;case np.TILES:return ve.jsx("group",{position:[0,0,e],children:ve.jsx(SU,{width:n.width,height:n.height,char:[...n.char],color:[...n.color],bg:[...n.bg]})},n.id);case np.SPRITES:return ve.jsx("group",{position:[0,0,e],children:ve.jsx(oae,{sprites:[...n.sprites]})},n.id);case np.DITHER:return ve.jsx("group",{position:[0,0,e],children:ve.jsx(Oy,{width:n.width,height:n.height,alphas:[...n.alphas]})},n.id)}}var aA={};Object.defineProperty(aA,"__esModule",{value:!0});var EU=aA.GamepadHelper=void 0;const Yn=class Yn{static getButtonValue(e,n){var r,i;return(i=(r=Yn.gamepads[e])==null?void 0:r.buttons[n])==null?void 0:i.value}static getAxisValue(e,n){var r;return(r=Yn.gamepads[e])==null?void 0:r.axes[n]}static update(){Yn.checkForNewGamepads(),!(!Yn.gamepads||Object.keys(Yn.gamepads).length<1)&&(Yn.gamepadsLastUpdate&&Object.keys(Yn.gamepadsLastUpdate).length>0&&Object.values(Yn.gamepads).forEach(e=>{var n;for(let r=0;r1;m&&(p=p.slice(0,-1));var g=cA(p),v=f1[g];if(p.length>1&&!v&&!wU[p]&&!lA[g])throw new TypeError('Unknown modifier: "'+p+'"');(s===1||!v)&&(n?r.key=g:r.which=AU(p)),v&&(r[v]=m?null:!0)}}catch(y){l=!0,c=y}finally{try{!a&&u.return&&u.return()}finally{if(l)throw c}}return r}function bU(t,e){for(var n in t){var r=t[n],i=void 0;if(r!=null&&(n==="key"&&e.key!=null?i=e.key.toLowerCase():n==="which"?i=r===91&&e.which===93?91:e.which:i=e[n],!(i==null&&r===!1)&&i!==r))return!1}return!0}function AU(t){t=cA(t);var e=lA[t]||t.toUpperCase().charCodeAt(0);return e}function cA(t){return t=t.toLowerCase(),t=wU[t]||t,t}var fae=Xl.default=Ly;Xl.isHotkey=Ly;Xl.isCodeHotkey=uae;Xl.isKeyHotkey=hae;Xl.parseHotkey=TU;Xl.compareHotkey=bU;Xl.toKeyCode=AU;Xl.toKeyName=cA;function MU(t){return{all:t=t||new Map,on:function(e,n){var r=t.get(e);r?r.push(n):t.set(e,[n])},off:function(e,n){var r=t.get(e);r&&(n?r.splice(r.indexOf(n)>>>0,1):t.set(e,[]))},emit:function(e,n){var r=t.get(e);r&&r.slice().map(function(i){i(n)}),(r=t.get("*"))&&r.slice().map(function(i){i(e,n)})}}}const Yf=navigator.userAgent.includes("Mac"),dae=Yf?"cmd":"ctrl",pa={[Ue.NONE]:!1,[Ue.ALT]:!1,[Ue.CTRL]:!1,[Ue.SHIFT]:!1,[Ue.MOVE_UP]:!1,[Ue.MOVE_DOWN]:!1,[Ue.MOVE_LEFT]:!1,[Ue.MOVE_RIGHT]:!1,[Ue.OK_BUTTON]:!1,[Ue.CANCEL_BUTTON]:!1,[Ue.MENU_BUTTON]:!1,[Ue.SHOOT_UP]:!1,[Ue.SHOOT_DOWN]:!1,[Ue.SHOOT_LEFT]:!1,[Ue.SHOOT_RIGHT]:!1};let p_=0,sk=performance.now();const ok=250;function Ji(t){pa[t]||(p_=0,RU(t,{alt:pa[Ue.ALT],ctrl:pa[Ue.CTRL],shift:pa[Ue.SHIFT]})),pa[t]=!0}function Qi(t){pa[t]=!1}const ha={root:MU(),ignorehotkeys:!1},CU=Ne.createContext(ha.root);function Py(t){return{alt:t.altKey,ctrl:Yf?t.metaKey:t.ctrlKey,shift:t.shiftKey}}function RU(t,e){ha.root.emit(Ue[t],e)}document.addEventListener("keydown",t=>{const e=$t(t.key),n=Py(t);switch(e){case"s":n.ctrl&&Dv("tape","#save",Y_()),t.preventDefault();break;case"v":case"r":n.ctrl||t.preventDefault();break;case"i":!Yf&&n.shift&&n.ctrl||t.preventDefault();break;case"dead":Yf&&n.alt&&n.ctrl||t.preventDefault();break;case"alt":case"meta":case"shift":case"control":break;default:t.preventDefault();break}switch(n.alt?Ji(Ue.ALT):Qi(Ue.ALT),n.ctrl?Ji(Ue.CTRL):Qi(Ue.CTRL),n.shift?Ji(Ue.SHIFT):Qi(Ue.SHIFT),e){case"arrowleft":Ji(Ue.MOVE_LEFT);break;case"arrowright":Ji(Ue.MOVE_RIGHT);break;case"arrowup":Ji(Ue.MOVE_UP);break;case"arrowdown":Ji(Ue.MOVE_DOWN);break;case"enter":Ji(Ue.OK_BUTTON);break;case"esc":case"escape":Ji(Ue.CANCEL_BUTTON);break;case"tab":Ji(Ue.MENU_BUTTON);break}ha.root.emit("keydown",t)},{capture:!0});document.addEventListener("keyup",t=>{const e=$t(t.key),n=Py(t);switch(n.alt?Ji(Ue.ALT):Qi(Ue.ALT),n.ctrl?Ji(Ue.CTRL):Qi(Ue.CTRL),n.shift?Ji(Ue.SHIFT):Qi(Ue.SHIFT),e){case"arrowleft":Qi(Ue.MOVE_LEFT);break;case"arrowright":Qi(Ue.MOVE_RIGHT);break;case"arrowup":Qi(Ue.MOVE_UP);break;case"arrowdown":Qi(Ue.MOVE_DOWN);break;case"enter":Qi(Ue.OK_BUTTON);break;case"esc":case"escape":Qi(Ue.CANCEL_BUTTON);break;case"tab":Qi(Ue.MENU_BUTTON);break}},{capture:!0});const pae=0,mae=1,gae=2,_ae=3,vae=4,yae=5,xae=6,Sae=7,Eae=9,wae=12,Tae=13,bae=14,Aae=15,NU={[pae]:Ue.OK_BUTTON,[mae]:Ue.CANCEL_BUTTON,[gae]:Ue.OK_BUTTON,[_ae]:Ue.CANCEL_BUTTON,[vae]:Ue.ALT,[yae]:Ue.ALT,[xae]:Ue.CTRL,[Sae]:Ue.CTRL,[Eae]:Ue.MENU_BUTTON,[wae]:Ue.MOVE_UP,[Tae]:Ue.MOVE_DOWN,[bae]:Ue.MOVE_LEFT,[Aae]:Ue.MOVE_RIGHT};document.addEventListener("gamepadbuttondown",t=>{Ji(NU[t.detail.button])});document.addEventListener("gamepadbuttonup",t=>{Qi(NU[t.detail.button])});function kU(){const t=performance.now(),e=t-sk;if(p_+=e,p_>=ok){p_%=ok;const n={alt:!!pa[Ue.ALT],ctrl:!!pa[Ue.CTRL],shift:!!pa[Ue.SHIFT]};[Ue.MOVE_UP,Ue.MOVE_DOWN,Ue.MOVE_LEFT,Ue.MOVE_RIGHT,Ue.OK_BUTTON,Ue.CANCEL_BUTTON,Ue.MENU_BUTTON,Ue.SHOOT_UP,Ue.SHOOT_DOWN,Ue.SHOOT_LEFT,Ue.SHOOT_RIGHT].forEach(i=>{pa[i]&&RU(i,n)})}sk=t,EU.update(),setTimeout(kU,1)}kU();const ak="keyup";function _p({hotkey:t,children:e}){return Ne.useEffect(()=>{const n=fae(t,{byKey:!0});function r(i){ha.ignorehotkeys===!1&&n(i)&&e()}return document.addEventListener(ak,r,!1),()=>document.removeEventListener(ak,r,!1)},[t,e]),null}function ms(t){const e=Ne.useContext(CU);return Ne.useEffect(()=>{const n=Object.entries(t);return n.forEach(([r,i])=>e.on(r,i)),()=>{n.forEach(([r,i])=>e.off(r,i))}},[e,t]),null}function Cm({blockhotkeys:t,children:e}){const[n]=Ne.useState(()=>MU());return Ne.useEffect(()=>{const r=ha.root,i=ha.ignorehotkeys;return ha.root=n,ha.ignorehotkeys=!!t,()=>{ha.root=r,ha.ignorehotkeys=i}},[n,t]),ve.jsx(CU.Provider,{value:n,children:e})}const Mae=new St(0,0);function pu(t,e,n){let r=0;n.alt&&(r|=cU),n.ctrl&&(r|=uU),n.shift&&(r|=hU),GW("framed",e,r,t)}function Cae({width:t,height:e}){const n=t*os,r=e*Vi,i=Ne.useRef(null);Lv((a,l)=>{const{current:c}=i;if(!c)return;const u=Eoe(ss.getState().gadget.layers),h=u.width*os*u.viewscale,p=h-n,m=u.height*Vi*u.viewscale,g=m-r,v=Math.round(Math.min(n,r)*.3333),y=-u.focusx*os*u.viewscale,_=n*.5+y,S=-u.focusy*Vi*u.viewscale,E=r*.5+S,T=h=v){const O=C<0?-v:v;c.userData.focus.x=Math.round(T-O)}}if(g<0)c.userData.focus.y=N;else{const C=c.position.y-N;if(Math.abs(C)>=v){const O=C<0?-v:v;c.userData.focus.y=Math.round(N-O*.5)}}const R=6;c.position.x+=(c.userData.focus.x-c.position.x)*l*R,c.position.y+=(c.userData.focus.y-c.position.y)*l*R,p>=0&&(c.position.x=Cn(c.position.x,-p,0)),g>=0&&(c.position.y=Cn(c.position.y,-g,0))});const s=ss(a=>a.gadget.player);ss(a=>a.gadget.layers.length);const{layers:o}=ss.getState().gadget;return ve.jsxs(ve.Fragment,{children:[ve.jsx(ms,{MOVE_LEFT:a=>pu(s,Ue.MOVE_LEFT,a),MOVE_RIGHT:a=>pu(s,Ue.MOVE_RIGHT,a),MOVE_UP:a=>pu(s,Ue.MOVE_UP,a),MOVE_DOWN:a=>pu(s,Ue.MOVE_DOWN,a),OK_BUTTON:a=>pu(s,Ue.OK_BUTTON,a),CANCEL_BUTTON:a=>pu(s,Ue.CANCEL_BUTTON,a),MENU_BUTTON:a=>pu(s,Ue.MENU_BUTTON,a)}),ve.jsx(Aoe,{width:n,height:r,children:ve.jsx("group",{ref:i,children:o.map((a,l)=>ve.jsx(lae,{id:a.id,z:l*2},a.id))})})]})}function gw(t){console&&console.error&&console.error(`Error: ${t}`)}function IU(t){console&&console.warn&&console.warn(`Warning: ${t}`)}function OU(t){const e=new Date().getTime(),n=t();return{time:new Date().getTime()-e,value:n}}function LU(t){function e(){}e.prototype=t;const n=new e;function r(){return typeof n.bar}return r(),r(),t}function Rae(t){return Nae(t)?t.LABEL:t.name}function Nae(t){return fs(t.LABEL)&&t.LABEL!==""}class za{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){this._definition=e}accept(e){e.visit(this),bt(this.definition,n=>{n.accept(e)})}}class gs extends za{constructor(e){super([]),this.idx=1,hs(this,zo(e,n=>n!==void 0))}set definition(e){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(e){e.visit(this)}}class gd extends za{constructor(e){super(e.definition),this.orgText="",hs(this,zo(e,n=>n!==void 0))}}class _s extends za{constructor(e){super(e.definition),this.ignoreAmbiguities=!1,hs(this,zo(e,n=>n!==void 0))}}class us extends za{constructor(e){super(e.definition),this.idx=1,hs(this,zo(e,n=>n!==void 0))}}class Va extends za{constructor(e){super(e.definition),this.idx=1,hs(this,zo(e,n=>n!==void 0))}}class Ha extends za{constructor(e){super(e.definition),this.idx=1,hs(this,zo(e,n=>n!==void 0))}}class Dr extends za{constructor(e){super(e.definition),this.idx=1,hs(this,zo(e,n=>n!==void 0))}}class jo extends za{constructor(e){super(e.definition),this.idx=1,hs(this,zo(e,n=>n!==void 0))}}class $o extends za{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,hs(this,zo(e,n=>n!==void 0))}}let Qn=class{constructor(e){this.idx=1,hs(this,zo(e,n=>n!==void 0))}accept(e){e.visit(this)}};function kae(t){return ot(t,m_)}function m_(t){function e(n){return ot(n,m_)}if(t instanceof gs){const n={type:"NonTerminal",name:t.nonTerminalName,idx:t.idx};return fs(t.label)&&(n.label=t.label),n}else{if(t instanceof _s)return{type:"Alternative",definition:e(t.definition)};if(t instanceof us)return{type:"Option",idx:t.idx,definition:e(t.definition)};if(t instanceof Va)return{type:"RepetitionMandatory",idx:t.idx,definition:e(t.definition)};if(t instanceof Ha)return{type:"RepetitionMandatoryWithSeparator",idx:t.idx,separator:m_(new Qn({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof jo)return{type:"RepetitionWithSeparator",idx:t.idx,separator:m_(new Qn({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof Dr)return{type:"Repetition",idx:t.idx,definition:e(t.definition)};if(t instanceof $o)return{type:"Alternation",idx:t.idx,definition:e(t.definition)};if(t instanceof Qn){const n={type:"Terminal",name:t.terminalType.name,label:Rae(t.terminalType),idx:t.idx};fs(t.label)&&(n.terminalLabel=t.label);const r=t.terminalType.PATTERN;return t.terminalType.PATTERN&&(n.pattern=Cl(r)?r.source:r),n}else{if(t instanceof gd)return{type:"Rule",name:t.name,orgText:t.orgText,definition:e(t.definition)};throw Error("non exhaustive match")}}}class ph{visit(e){const n=e;switch(n.constructor){case gs:return this.visitNonTerminal(n);case _s:return this.visitAlternative(n);case us:return this.visitOption(n);case Va:return this.visitRepetitionMandatory(n);case Ha:return this.visitRepetitionMandatoryWithSeparator(n);case jo:return this.visitRepetitionWithSeparator(n);case Dr:return this.visitRepetition(n);case $o:return this.visitAlternation(n);case Qn:return this.visitTerminal(n);case gd:return this.visitRule(n);default:throw Error("non exhaustive match")}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}}function Iae(t){return t instanceof _s||t instanceof us||t instanceof Dr||t instanceof Va||t instanceof Ha||t instanceof jo||t instanceof Qn||t instanceof gd}function lv(t,e=[]){return t instanceof us||t instanceof Dr||t instanceof jo?!0:t instanceof $o?zT(t.definition,r=>lv(r,e)):t instanceof gs&&$i(e,t)?!1:t instanceof za?(t instanceof gs&&e.push(t),No(t.definition,r=>lv(r,e))):!1}function Oae(t){return t instanceof $o}function fa(t){if(t instanceof gs)return"SUBRULE";if(t instanceof us)return"OPTION";if(t instanceof $o)return"OR";if(t instanceof Va)return"AT_LEAST_ONE";if(t instanceof Ha)return"AT_LEAST_ONE_SEP";if(t instanceof jo)return"MANY_SEP";if(t instanceof Dr)return"MANY";if(t instanceof Qn)return"CONSUME";throw Error("non exhaustive match")}class Dy{walk(e,n=[]){bt(e.definition,(r,i)=>{const s=ai(e.definition,i+1);if(r instanceof gs)this.walkProdRef(r,s,n);else if(r instanceof Qn)this.walkTerminal(r,s,n);else if(r instanceof _s)this.walkFlat(r,s,n);else if(r instanceof us)this.walkOption(r,s,n);else if(r instanceof Va)this.walkAtLeastOne(r,s,n);else if(r instanceof Ha)this.walkAtLeastOneSep(r,s,n);else if(r instanceof jo)this.walkManySep(r,s,n);else if(r instanceof Dr)this.walkMany(r,s,n);else if(r instanceof $o)this.walkOr(r,s,n);else throw Error("non exhaustive match")})}walkTerminal(e,n,r){}walkProdRef(e,n,r){}walkFlat(e,n,r){const i=n.concat(r);this.walk(e,i)}walkOption(e,n,r){const i=n.concat(r);this.walk(e,i)}walkAtLeastOne(e,n,r){const i=[new us({definition:e.definition})].concat(n,r);this.walk(e,i)}walkAtLeastOneSep(e,n,r){const i=lk(e,n,r);this.walk(e,i)}walkMany(e,n,r){const i=[new us({definition:e.definition})].concat(n,r);this.walk(e,i)}walkManySep(e,n,r){const i=lk(e,n,r);this.walk(e,i)}walkOr(e,n,r){const i=n.concat(r);bt(e.definition,s=>{const o=new _s({definition:[s]});this.walk(o,i)})}}function lk(t,e,n){return[new us({definition:[new Qn({terminalType:t.separator})].concat(t.definition)})].concat(e,n)}function Rm(t){if(t instanceof gs)return Rm(t.referencedRule);if(t instanceof Qn)return Dae(t);if(Iae(t))return Lae(t);if(Oae(t))return Pae(t);throw Error("non exhaustive match")}function Lae(t){let e=[];const n=t.definition;let r=0,i=n.length>r,s,o=!0;for(;i&&o;)s=n[r],o=lv(s),e=e.concat(Rm(s)),r=r+1,i=n.length>r;return Kv(e)}function Pae(t){const e=ot(t.definition,n=>Rm(n));return Kv(ls(e))}function Dae(t){return[t.terminalType]}const PU="_~IN~_";class Uae extends Dy{constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,n,r){}walkProdRef(e,n,r){const i=Bae(e.referencedRule,e.idx)+this.topProd.name,s=n.concat(r),o=new _s({definition:s}),a=Rm(o);this.follows[i]=a}}function Fae(t){const e={};return bt(t,n=>{const r=new Uae(n).startWalking();hs(e,r)}),e}function Bae(t,e){return t.name+e+PU}function Mt(t){return t.charCodeAt(0)}function d1(t,e){Array.isArray(t)?t.forEach(function(n){e.push(n)}):e.push(t)}function $d(t,e){if(t[e]===!0)throw"duplicate flag "+e;t[e],t[e]=!0}function Xh(t){if(t===void 0)throw Error("Internal Error - Should never get here!");return!0}function zae(){throw Error("Internal Error - Should never get here!")}function ck(t){return t.type==="Character"}const cv=[];for(let t=Mt("0");t<=Mt("9");t++)cv.push(t);const uv=[Mt("_")].concat(cv);for(let t=Mt("a");t<=Mt("z");t++)uv.push(t);for(let t=Mt("A");t<=Mt("Z");t++)uv.push(t);const uk=[Mt(" "),Mt("\f"),Mt(` +`),Mt("\r"),Mt(" "),Mt("\v"),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt("\u2028"),Mt("\u2029"),Mt(" "),Mt(" "),Mt(" "),Mt("\uFEFF")],Vae=/[0-9a-fA-F]/,R0=/[0-9]/,Hae=/[1-9]/;class Gae{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar("/");const n=this.disjunction();this.consumeChar("/");const r={type:"Flags",loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":$d(r,"global");break;case"i":$d(r,"ignoreCase");break;case"m":$d(r,"multiLine");break;case"u":$d(r,"unicode");break;case"y":$d(r,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:n,loc:this.loc(0)}}disjunction(){const e=[],n=this.idx;for(e.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),e.push(this.alternative());return{type:"Disjunction",value:e,loc:this.loc(n)}}alternative(){const e=[],n=this.idx;for(;this.isTerm();)e.push(this.term());return{type:"Alternative",value:e,loc:this.loc(n)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){const e=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(e)};case"$":return{type:"EndAnchor",loc:this.loc(e)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(e)};case"B":return{type:"NonWordBoundary",loc:this.loc(e)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let n;switch(this.popChar()){case"=":n="Lookahead";break;case"!":n="NegativeLookahead";break}Xh(n);const r=this.disjunction();return this.consumeChar(")"),{type:n,value:r,loc:this.loc(e)}}return zae()}quantifier(e=!1){let n;const r=this.idx;switch(this.popChar()){case"*":n={atLeast:0,atMost:1/0};break;case"+":n={atLeast:1,atMost:1/0};break;case"?":n={atLeast:0,atMost:1};break;case"{":const i=this.integerIncludingZero();switch(this.popChar()){case"}":n={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),n={atLeast:i,atMost:s}):n={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(e===!0&&n===void 0)return;Xh(n);break}if(!(e===!0&&n===void 0)&&Xh(n))return this.peekChar(0)==="?"?(this.consumeChar("?"),n.greedy=!1):n.greedy=!0,n.type="Quantifier",n.loc=this.loc(r),n}atom(){let e;const n=this.idx;switch(this.peekChar()){case".":e=this.dotAll();break;case"\\":e=this.atomEscape();break;case"[":e=this.characterClass();break;case"(":e=this.group();break}if(e===void 0&&this.isPatternCharacter()&&(e=this.patternCharacter()),Xh(e))return e.loc=this.loc(n),this.isQuantifier()&&(e.quantifier=this.quantifier()),e}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[Mt(` +`),Mt("\r"),Mt("\u2028"),Mt("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let e,n=!1;switch(this.popChar()){case"d":e=cv;break;case"D":e=cv,n=!0;break;case"s":e=uk;break;case"S":e=uk,n=!0;break;case"w":e=uv;break;case"W":e=uv,n=!0;break}if(Xh(e))return{type:"Set",value:e,complement:n}}controlEscapeAtom(){let e;switch(this.popChar()){case"f":e=Mt("\f");break;case"n":e=Mt(` +`);break;case"r":e=Mt("\r");break;case"t":e=Mt(" ");break;case"v":e=Mt("\v");break}if(Xh(e))return{type:"Character",value:e}}controlLetterEscapeAtom(){this.consumeChar("c");const e=this.popChar();if(/[a-zA-Z]/.test(e)===!1)throw Error("Invalid ");return{type:"Character",value:e.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:Mt("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){const e=this.popChar();return{type:"Character",value:Mt(e)}}classPatternCharacterAtom(){switch(this.peekChar()){case` +`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:const e=this.popChar();return{type:"Character",value:Mt(e)}}}characterClass(){const e=[];let n=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),n=!0);this.isClassAtom();){const r=this.classAtom();if(r.type,ck(r)&&this.isRangeDash()){this.consumeChar("-");const i=this.classAtom();if(i.type,ck(i)){if(i.value=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(e){return{begin:e,end:this.idx}}}class uA{visitChildren(e){for(const n in e){const r=e[n];e.hasOwnProperty(n)&&(r.type!==void 0?this.visit(r):Array.isArray(r)&&r.forEach(i=>{this.visit(i)},this))}}visit(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e);break}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}}let g_={};const Wae=new Gae;function Uy(t){const e=t.toString();if(g_.hasOwnProperty(e))return g_[e];{const n=Wae.pattern(e);return g_[e]=n,n}}function jae(){g_={}}const DU="Complement Sets are not supported for first char optimization",hv=`Unable to use "first char" lexer optimizations: +`;function $ae(t,e=!1){try{const n=Uy(t);return _w(n.value,{},n.flags.ignoreCase)}catch(n){if(n.message===DU)e&&IU(`${hv} Unable to optimize: < ${t.toString()} > + Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let r="";e&&(r=` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),gw(`${hv} + Failed parsing: < ${t.toString()} > + Using the @chevrotain/regexp-to-ast library + Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}function _w(t,e,n){switch(t.type){case"Disjunction":for(let i=0;i{if(typeof l=="number")N0(l,e,n);else{const c=l;if(n===!0)for(let u=c.from;u<=c.to;u++)N0(u,e,n);else{for(let u=c.from;u<=c.to&&u=ip){const u=c.from>=ip?c.from:ip,h=c.to,p=zc(u),m=zc(h);for(let g=p;g<=m;g++)e[g]=g}}}});break;case"Group":_w(o.value,e,n);break;default:throw Error("Non Exhaustive Match")}const a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&vw(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return Cr(e)}function N0(t,e,n){const r=zc(t);e[r]=r,n===!0&&qae(t,e)}function qae(t,e){const n=String.fromCharCode(t),r=n.toUpperCase();if(r!==n){const i=zc(r.charCodeAt(0));e[i]=i}else{const i=n.toLowerCase();if(i!==n){const s=zc(i.charCodeAt(0));e[s]=s}}}function hk(t,e){return Ff(t.value,n=>{if(typeof n=="number")return $i(e,n);{const r=n;return Ff(e,i=>r.from<=i&&i<=r.to)!==void 0}})}function vw(t){const e=t.quantifier;return e&&e.atLeast===0?!0:t.value?un(t.value)?No(t.value,vw):vw(t.value):!1}class Xae extends uA{constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(this.found!==!0){switch(e.type){case"Lookahead":this.visitLookahead(e);return;case"NegativeLookahead":this.visitNegativeLookahead(e);return}super.visitChildren(e)}}visitCharacter(e){$i(this.targetCharCodes,e.value)&&(this.found=!0)}visitSet(e){e.complement?hk(e,this.targetCharCodes)===void 0&&(this.found=!0):hk(e,this.targetCharCodes)!==void 0&&(this.found=!0)}}function hA(t,e){if(e instanceof RegExp){const n=Uy(e),r=new Xae(t);return r.visit(n),r.found}else return Ff(e,n=>$i(t,n.charCodeAt(0)))!==void 0}const Qu="PATTERN",rp="defaultMode",k0="modes";let UU=typeof new RegExp("(?:)").sticky=="boolean";function Kae(t,e){e=BT(e,{useSticky:UU,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` +`],tracer:(S,E)=>E()});const n=e.tracer;n("initCharCodeToOptimizedIndexMap",()=>{vle()});let r;n("Reject Lexer.NA",()=>{r=Xv(t,S=>S[Qu]===Br.NA)});let i=!1,s;n("Transform Patterns",()=>{i=!1,s=ot(r,S=>{const E=S[Qu];if(Cl(E)){const T=E.source;return T.length===1&&T!=="^"&&T!=="$"&&T!=="."&&!E.ignoreCase?T:T.length===2&&T[0]==="\\"&&!$i(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],T[1])?T[1]:e.useSticky?dk(E):fk(E)}else{if(Fl(E))return i=!0,{exec:E};if(typeof E=="object")return i=!0,E;if(typeof E=="string"){if(E.length===1)return E;{const T=E.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),N=new RegExp(T);return e.useSticky?dk(N):fk(N)}}else throw Error("non exhaustive match")}})});let o,a,l,c,u;n("misc mapping",()=>{o=ot(r,S=>S.tokenTypeIdx),a=ot(r,S=>{const E=S.GROUP;if(E!==Br.SKIPPED){if(fs(E))return E;if(Rl(E))return!1;throw Error("non exhaustive match")}}),l=ot(r,S=>{const E=S.LONGER_ALT;if(E)return un(E)?ot(E,N=>A2(r,N)):[A2(r,E)]}),c=ot(r,S=>S.PUSH_MODE),u=ot(r,S=>wt(S,"POP_MODE"))});let h;n("Line Terminator Handling",()=>{const S=zU(e.lineTerminatorCharacters);h=ot(r,E=>!1),e.positionTracking!=="onlyOffset"&&(h=ot(r,E=>wt(E,"LINE_BREAKS")?!!E.LINE_BREAKS:BU(E,S)===!1&&hA(S,E.PATTERN)))});let p,m,g,v;n("Misc Mapping #2",()=>{p=ot(r,FU),m=ot(s,mle),g=ds(r,(S,E)=>{const T=E.GROUP;return fs(T)&&T!==Br.SKIPPED&&(S[T]=[]),S},{}),v=ot(s,(S,E)=>({pattern:s[E],longerAlt:l[E],canLineTerminator:h[E],isCustom:p[E],short:m[E],group:a[E],push:c[E],pop:u[E],tokenTypeIdx:o[E],tokenType:r[E]}))});let y=!0,_=[];return e.safeMode||n("First Char Optimization",()=>{_=ds(r,(S,E,T)=>{if(typeof E.PATTERN=="string"){const N=E.PATTERN.charCodeAt(0),R=zc(N);p1(S,R,v[T])}else if(un(E.START_CHARS_HINT)){let N;bt(E.START_CHARS_HINT,R=>{const C=typeof R=="string"?R.charCodeAt(0):R,O=zc(C);N!==O&&(N=O,p1(S,O,v[T]))})}else if(Cl(E.PATTERN))if(E.PATTERN.unicode)y=!1,e.ensureOptimizations&&gw(`${hv} Unable to analyze < ${E.PATTERN.toString()} > pattern. + The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{const N=$ae(E.PATTERN,e.ensureOptimizations);Un(N)&&(y=!1),bt(N,R=>{p1(S,R,v[T])})}else e.ensureOptimizations&&gw(`${hv} TokenType: <${E.name}> is using a custom token pattern without providing parameter. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),y=!1;return S},[])}),{emptyGroups:g,patternIdxToConfig:v,charCodeToPatternIdxToConfig:_,hasCustom:i,canBeOptimized:y}}function Yae(t,e){let n=[];const r=Jae(t);n=n.concat(r.errors);const i=Qae(r.valid),s=i.valid;return n=n.concat(i.errors),n=n.concat(Zae(s)),n=n.concat(ale(s)),n=n.concat(lle(s,e)),n=n.concat(cle(s)),n}function Zae(t){let e=[];const n=uo(t,r=>Cl(r[Qu]));return e=e.concat(tle(n)),e=e.concat(ile(n)),e=e.concat(sle(n)),e=e.concat(ole(n)),e=e.concat(nle(n)),e}function Jae(t){const e=uo(t,i=>!wt(i,Qu)),n=ot(e,i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:sr.MISSING_PATTERN,tokenTypes:[i]})),r=qv(t,e);return{errors:n,valid:r}}function Qae(t){const e=uo(t,i=>{const s=i[Qu];return!Cl(s)&&!Fl(s)&&!wt(s,"exec")&&!fs(s)}),n=ot(e,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:sr.INVALID_PATTERN,tokenTypes:[i]})),r=qv(t,e);return{errors:n,valid:r}}const ele=/[^\\][$]/;function tle(t){class e extends uA{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}const n=uo(t,i=>{const s=i.PATTERN;try{const o=Uy(s),a=new e;return a.visit(o),a.found}catch{return ele.test(s.source)}});return ot(n,i=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:sr.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function nle(t){const e=uo(t,r=>r.PATTERN.test(""));return ot(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' must not match an empty string",type:sr.EMPTY_MATCH_PATTERN,tokenTypes:[r]}))}const rle=/[^\\[][\^]|^\^/;function ile(t){class e extends uA{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}const n=uo(t,i=>{const s=i.PATTERN;try{const o=Uy(s),a=new e;return a.visit(o),a.found}catch{return rle.test(s.source)}});return ot(n,i=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:sr.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function sle(t){const e=uo(t,r=>{const i=r[Qu];return i instanceof RegExp&&(i.multiline||i.global)});return ot(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:sr.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[r]}))}function ole(t){const e=[];let n=ot(t,s=>ds(t,(o,a)=>(s.PATTERN.source===a.PATTERN.source&&!$i(e,a)&&a.PATTERN!==Br.NA&&(e.push(a),o.push(a)),o),[]));n=nm(n);const r=uo(n,s=>s.length>1);return ot(r,s=>{const o=ot(s,l=>l.name);return{message:`The same RegExp pattern ->${Oo(s).PATTERN}<-has been used in all of the following Token Types: ${o.join(", ")} <-`,type:sr.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function ale(t){const e=uo(t,r=>{if(!wt(r,"GROUP"))return!1;const i=r.GROUP;return i!==Br.SKIPPED&&i!==Br.NA&&!fs(i)});return ot(e,r=>({message:"Token Type: ->"+r.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:sr.INVALID_GROUP_TYPE_FOUND,tokenTypes:[r]}))}function lle(t,e){const n=uo(t,i=>i.PUSH_MODE!==void 0&&!$i(e,i.PUSH_MODE));return ot(n,i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:sr.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function cle(t){const e=[],n=ds(t,(r,i,s)=>{const o=i.PATTERN;return o===Br.NA||(fs(o)?r.push({str:o,idx:s,tokenType:i}):Cl(o)&&hle(o)&&r.push({str:o.source,idx:s,tokenType:i})),r},[]);return bt(t,(r,i)=>{bt(n,({str:s,idx:o,tokenType:a})=>{if(i${a.name}<- can never be matched. +Because it appears AFTER the Token Type ->${r.name}<-in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:l,type:sr.UNREACHABLE_PATTERN,tokenTypes:[r,a]})}})}),e}function ule(t,e){if(Cl(e)){const n=e.exec(t);return n!==null&&n.index===0}else{if(Fl(e))return e(t,0,[],{});if(wt(e,"exec"))return e.exec(t,0,[],{});if(typeof e=="string")return e===t;throw Error("non exhaustive match")}}function hle(t){return Ff([".","\\","[","]","|","^","$","(",")","?","*","+","{"],n=>t.source.indexOf(n)!==-1)===void 0}function fk(t){const e=t.ignoreCase?"i":"";return new RegExp(`^(?:${t.source})`,e)}function dk(t){const e=t.ignoreCase?"iy":"y";return new RegExp(`${t.source}`,e)}function fle(t,e,n){const r=[];return wt(t,rp)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+rp+`> property in its definition +`,type:sr.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),wt(t,k0)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+k0+`> property in its definition +`,type:sr.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),wt(t,k0)&&wt(t,rp)&&!wt(t.modes,t.defaultMode)&&r.push({message:`A MultiMode Lexer cannot be initialized with a ${rp}: <${t.defaultMode}>which does not exist +`,type:sr.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),wt(t,k0)&&bt(t.modes,(i,s)=>{bt(i,(o,a)=>{if(Rl(o))r.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${s}> at index: <${a}> +`,type:sr.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if(wt(o,"LONGER_ALT")){const l=un(o.LONGER_ALT)?o.LONGER_ALT:[o.LONGER_ALT];bt(l,c=>{!Rl(c)&&!$i(i,c)&&r.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${c.name}> on token <${o.name}> outside of mode <${s}> +`,type:sr.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),r}function dle(t,e,n){const r=[];let i=!1;const s=nm(ls(Cr(t.modes))),o=Xv(s,l=>l[Qu]===Br.NA),a=zU(n);return e&&bt(o,l=>{const c=BU(l,a);if(c!==!1){const h={message:_le(l,c),type:c.issue,tokenType:l};r.push(h)}else wt(l,"LINE_BREAKS")?l.LINE_BREAKS===!0&&(i=!0):hA(a,l.PATTERN)&&(i=!0)}),e&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`,type:sr.NO_LINE_BREAKS_FLAGS}),r}function ple(t){const e={},n=lo(t);return bt(n,r=>{const i=t[r];if(un(i))e[r]=[];else throw Error("non exhaustive match")}),e}function FU(t){const e=t.PATTERN;if(Cl(e))return!1;if(Fl(e))return!0;if(wt(e,"exec"))return!0;if(fs(e))return!1;throw Error("non exhaustive match")}function mle(t){return fs(t)&&t.length===1?t.charCodeAt(0):!1}const gle={test:function(t){const e=t.length;for(let n=this.lastIndex;n Token Type + Root cause: ${e.errMsg}. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(e.issue===sr.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. + The problem is in the <${t.name}> Token Type + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function zU(t){return ot(t,n=>fs(n)?n.charCodeAt(0):n)}function p1(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}const ip=256;let __=[];function zc(t){return t255?255+~~(t/255):t}}function Nm(t,e){const n=t.tokenTypeIdx;return n===e.tokenTypeIdx?!0:e.isParent===!0&&e.categoryMatchesMap[n]===!0}function fv(t,e){return t.tokenTypeIdx===e.tokenTypeIdx}let pk=1;const VU={};function km(t){const e=yle(t);xle(e),Ele(e),Sle(e),bt(e,n=>{n.isParent=n.categoryMatches.length>0})}function yle(t){let e=hi(t),n=t,r=!0;for(;r;){n=nm(ls(ot(n,s=>s.CATEGORIES)));const i=qv(n,e);e=e.concat(i),Un(i)?r=!1:n=i}return e}function xle(t){bt(t,e=>{GU(e)||(VU[pk]=e,e.tokenTypeIdx=pk++),mk(e)&&!un(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),mk(e)||(e.CATEGORIES=[]),wle(e)||(e.categoryMatches=[]),Tle(e)||(e.categoryMatchesMap={})})}function Sle(t){bt(t,e=>{e.categoryMatches=[],bt(e.categoryMatchesMap,(n,r)=>{e.categoryMatches.push(VU[r].tokenTypeIdx)})})}function Ele(t){bt(t,e=>{HU([],e)})}function HU(t,e){bt(t,n=>{e.categoryMatchesMap[n.tokenTypeIdx]=!0}),bt(e.CATEGORIES,n=>{const r=t.concat(e);$i(r,n)||HU(r,n)})}function GU(t){return wt(t,"tokenTypeIdx")}function mk(t){return wt(t,"CATEGORIES")}function wle(t){return wt(t,"categoryMatches")}function Tle(t){return wt(t,"categoryMatchesMap")}function ble(t){return wt(t,"tokenTypeIdx")}const Ale={buildUnableToPopLexerModeMessage(t){return`Unable to pop Lexer Mode after encountering Token ->${t.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(t,e,n,r,i){return`unexpected character: ->${t.charAt(e)}<- at offset: ${e}, skipped ${n} characters.`}};var sr;(function(t){t[t.MISSING_PATTERN=0]="MISSING_PATTERN",t[t.INVALID_PATTERN=1]="INVALID_PATTERN",t[t.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",t[t.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",t[t.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",t[t.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",t[t.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",t[t.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",t[t.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",t[t.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",t[t.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",t[t.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",t[t.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",t[t.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",t[t.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",t[t.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",t[t.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",t[t.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(sr||(sr={}));const sp={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` +`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:Ale,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(sp);class Br{constructor(e,n=sp){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;const o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${i}>`);const{time:a,value:l}=OU(s),c=a>10?console.warn:console.log;return this.traceInitIndent time: ${a}ms`),this.traceInitIndent--,l}else return s()},typeof n=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`);this.config=hs({},sp,n);const r=this.config.traceInitPerf;r===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof r=="number"&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===sp.lineTerminatorsPattern)this.config.lineTerminatorsPattern=gle;else if(this.config.lineTerminatorCharacters===sp.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(n.safeMode&&n.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),un(e)?i={modes:{defaultMode:hi(e)},defaultMode:rp}:(s=!1,i=hi(e))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(fle(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(dle(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},bt(i.modes,(a,l)=>{i.modes[l]=Xv(a,c=>Rl(c))});const o=lo(i.modes);if(bt(i.modes,(a,l)=>{this.TRACE_INIT(`Mode: <${l}> processing`,()=>{if(this.modes.push(l),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(Yae(a,o))}),Un(this.lexerDefinitionErrors)){km(a);let c;this.TRACE_INIT("analyzeTokenTypes",()=>{c=Kae(a,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:n.positionTracking,ensureOptimizations:n.ensureOptimizations,safeMode:n.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[l]=c.patternIdxToConfig,this.charCodeToPatternIdxToConfig[l]=c.charCodeToPatternIdxToConfig,this.emptyGroups=hs({},this.emptyGroups,c.emptyGroups),this.hasCustom=c.hasCustom||this.hasCustom,this.canModeBeOptimized[l]=c.canBeOptimized}})}),this.defaultMode=i.defaultMode,!Un(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){const l=ot(this.lexerDefinitionErrors,c=>c.message).join(`----------------------- +`);throw new Error(`Errors detected in definition of Lexer: +`+l)}bt(this.lexerDefinitionWarning,a=>{IU(a.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(UU?(this.chopInput=Pf,this.match=this.matchWithTest):(this.updateLastIndex=Ir,this.match=this.matchWithExec),s&&(this.handleModes=Ir),this.trackStartLines===!1&&(this.computeNewColumn=Pf),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=Ir),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{const a=ds(this.canModeBeOptimized,(l,c,u)=>(c===!1&&l.push(u),l),[]);if(n.ensureOptimizations&&!Un(a))throw Error(`Lexer Modes: < ${a.join(", ")} > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{jae()}),this.TRACE_INIT("toFastProperties",()=>{LU(this)})})}tokenize(e,n=this.defaultMode){if(!Un(this.lexerDefinitionErrors)){const i=ot(this.lexerDefinitionErrors,s=>s.message).join(`----------------------- +`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: +`+i)}return this.tokenizeInternal(e,n)}tokenizeInternal(e,n){let r,i,s,o,a,l,c,u,h,p,m,g,v,y,_;const S=e,E=S.length;let T=0,N=0;const R=this.hasCustom?0:Math.floor(e.length/10),C=new Array(R),O=[];let M=this.trackStartLines?1:void 0,I=this.trackStartLines?1:void 0;const U=ple(this.emptyGroups),L=this.trackStartLines,P=this.config.lineTerminatorsPattern;let b=0,H=[],V=[];const B=[],z=[];Object.freeze(z);let W;function K(){return H}function j(we){const Ae=zc(we),Ee=V[Ae];return Ee===void 0?z:Ee}const Y=we=>{if(B.length===1&&we.tokenType.PUSH_MODE===void 0){const Ae=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(we);O.push({offset:we.startOffset,line:we.startLine,column:we.startColumn,length:we.image.length,message:Ae})}else{B.pop();const Ae=Uf(B);H=this.patternIdxToConfig[Ae],V=this.charCodeToPatternIdxToConfig[Ae],b=H.length;const Ee=this.canModeBeOptimized[Ae]&&this.config.safeMode===!1;V&&Ee?W=j:W=K}};function ge(we){B.push(we),V=this.charCodeToPatternIdxToConfig[we],H=this.patternIdxToConfig[we],b=H.length,b=H.length;const Ae=this.canModeBeOptimized[we]&&this.config.safeMode===!1;V&&Ae?W=j:W=K}ge.call(this,n);let Q;const re=this.config.recoveryEnabled;for(;Tl.length){l=o,c=u,Q=it;break}}}break}}if(l!==null){if(h=l.length,p=Q.group,p!==void 0&&(m=Q.tokenTypeIdx,g=this.createTokenInstance(l,T,m,Q.tokenType,M,I,h),this.handlePayload(g,c),p===!1?N=this.addToken(C,N,g):U[p].push(g)),e=this.chopInput(e,h),T=T+h,I=this.computeNewColumn(I,h),L===!0&&Q.canLineTerminator===!0){let Le=0,Ve,qe;P.lastIndex=0;do Ve=P.test(l),Ve===!0&&(qe=P.lastIndex-1,Le++);while(Ve===!0);Le!==0&&(M=M+Le,I=h-qe,this.updateTokenEndLineColumnLocation(g,p,qe,Le,M,I,h))}this.handleModes(Q,Y,ge,g)}else{const Le=T,Ve=M,qe=I;let it=re===!1;for(;it===!1&&T ${vp(t)} <--`:`token of type --> ${t.name} <--`} but found --> '${e.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:t,ruleName:e}){return"Redundant input, expecting EOF but found: "+t.image},buildNoViableAltMessage({expectedPathsPerAlt:t,actual:e,previous:n,customUserDescription:r,ruleName:i}){const s="Expecting: ",a=` +but found: '`+Oo(e).image+"'";if(r)return s+r+a;{const l=ds(t,(p,m)=>p.concat(m),[]),c=ot(l,p=>`[${ot(p,m=>vp(m)).join(", ")}]`),h=`one of these possible Token sequences: +${ot(c,(p,m)=>` ${m+1}. ${p}`).join(` +`)}`;return s+h+a}},buildEarlyExitMessage({expectedIterationPaths:t,actual:e,customUserDescription:n,ruleName:r}){const i="Expecting: ",o=` +but found: '`+Oo(e).image+"'";if(n)return i+n+o;{const l=`expecting at least one iteration which starts with one of these possible Token sequences:: + <${ot(t,c=>`[${ot(c,u=>vp(u)).join(",")}]`).join(" ,")}>`;return i+l+o}}};Object.freeze(jU);const Nle={buildRuleNotFoundError(t,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- +inside top level rule: ->`+t.name+"<-"}},Iu={buildDuplicateFoundError(t,e){function n(u){return u instanceof Qn?u.terminalType.name:u instanceof gs?u.nonTerminalName:""}const r=t.name,i=Oo(e),s=i.idx,o=fa(i),a=n(i),l=s>0;let c=`->${o}${l?s:""}<- ${a?`with argument: ->${a}<-`:""} + appears more than once (${e.length} times) in the top level rule: ->${r}<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `;return c=c.replace(/[ \t]+/g," "),c=c.replace(/\s\s+/g,` +`),c},buildNamespaceConflictError(t){return`Namespace conflict found in grammar. +The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${t.name}>. +To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(t){const e=ot(t.prefixPath,i=>vp(i)).join(", "),n=t.alternation.idx===0?"":t.alternation.idx;return`Ambiguous alternatives: <${t.ambiguityIndices.join(" ,")}> due to common lookahead prefix +in inside <${t.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`},buildAlternationAmbiguityError(t){const e=ot(t.prefixPath,i=>vp(i)).join(", "),n=t.alternation.idx===0?"":t.alternation.idx;let r=`Ambiguous Alternatives Detected: <${t.ambiguityIndices.join(" ,")}> in inside <${t.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +`;return r=r+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,r},buildEmptyRepetitionError(t){let e=fa(t.repetition);return t.repetition.idx!==0&&(e+=t.repetition.idx),`The repetition <${e}> within Rule <${t.topLevelRule.name}> can never consume any tokens. +This could lead to an infinite loop.`},buildTokenNameError(t){return"deprecated"},buildEmptyAlternationError(t){return`Ambiguous empty alternative: <${t.emptyChoiceIdx+1}> in inside <${t.topLevelRule.name}> Rule. +Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(t){return`An Alternation cannot have more than 256 alternatives: + inside <${t.topLevelRule.name}> Rule. + has ${t.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(t){const e=t.topLevelRule.name,n=ot(t.leftRecursionPath,s=>s.name),r=`${e} --> ${n.concat([e]).join(" --> ")}`;return`Left Recursion found in grammar. +rule: <${e}> can be invoked from itself (directly or indirectly) +without consuming any Tokens. The grammar path that causes this is: + ${r} + To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(t){return"deprecated"},buildDuplicateRuleNameError(t){let e;return t.topLevelRule instanceof gd?e=t.topLevelRule.name:e=t.topLevelRule,`Duplicate definition, rule: ->${e}<- is already defined in the grammar: ->${t.grammarName}<-`}};function kle(t,e){const n=new Ile(t,e);return n.resolveRefs(),n.errors}class Ile extends ph{constructor(e,n){super(),this.nameToTopRule=e,this.errMsgProvider=n,this.errors=[]}resolveRefs(){bt(Cr(this.nameToTopRule),e=>{this.currTopLevel=e,e.accept(this)})}visitNonTerminal(e){const n=this.nameToTopRule[e.nonTerminalName];if(n)e.referencedRule=n;else{const r=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:r,type:Gi.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}}}class Ole extends Dy{constructor(e,n){super(),this.topProd=e,this.path=n,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=hi(this.path.ruleStack).reverse(),this.occurrenceStack=hi(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(e,n=[]){this.found||super.walk(e,n)}walkProdRef(e,n,r){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){const i=n.concat(r);this.updateExpectedNext(),this.walk(e.referencedRule,i)}}updateExpectedNext(){Un(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}}class Lle extends Ole{constructor(e,n){super(e,n),this.path=n,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(e,n,r){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){const i=n.concat(r),s=new _s({definition:i});this.possibleTokTypes=Rm(s),this.found=!0}}}class Fy extends Dy{constructor(e,n){super(),this.topRule=e,this.occurrence=n,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}}class Ple extends Fy{walkMany(e,n,r){if(e.idx===this.occurrence){const i=Oo(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Qn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkMany(e,n,r)}}class Tk extends Fy{walkManySep(e,n,r){if(e.idx===this.occurrence){const i=Oo(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Qn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkManySep(e,n,r)}}class Dle extends Fy{walkAtLeastOne(e,n,r){if(e.idx===this.occurrence){const i=Oo(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Qn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOne(e,n,r)}}class bk extends Fy{walkAtLeastOneSep(e,n,r){if(e.idx===this.occurrence){const i=Oo(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Qn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOneSep(e,n,r)}}function yw(t,e,n=[]){n=hi(n);let r=[],i=0;function s(a){return a.concat(ai(t,i+1))}function o(a){const l=yw(s(a),e,n);return r.concat(l)}for(;n.length{Un(l.definition)===!1&&(r=o(l.definition))}),r;if(a instanceof Qn)n.push(a.terminalType);else throw Error("non exhaustive match")}i++}return r.push({partialPath:n,suffixDef:ai(t,i)}),r}function $U(t,e,n,r){const i="EXIT_NONE_TERMINAL",s=[i],o="EXIT_ALTERNATIVE";let a=!1;const l=e.length,c=l-r-1,u=[],h=[];for(h.push({idx:-1,def:t,ruleStack:[],occurrenceStack:[]});!Un(h);){const p=h.pop();if(p===o){a&&Uf(h).idx<=c&&h.pop();continue}const m=p.def,g=p.idx,v=p.ruleStack,y=p.occurrenceStack;if(Un(m))continue;const _=m[0];if(_===i){const S={idx:g,def:ai(m),ruleStack:Ap(v),occurrenceStack:Ap(y)};h.push(S)}else if(_ instanceof Qn)if(g=0;S--){const E=_.definition[S],T={idx:g,def:E.definition.concat(ai(m)),ruleStack:v,occurrenceStack:y};h.push(T),h.push(o)}else if(_ instanceof _s)h.push({idx:g,def:_.definition.concat(ai(m)),ruleStack:v,occurrenceStack:y});else if(_ instanceof gd)h.push(Ule(_,g,v,y));else throw Error("non exhaustive match")}return u}function Ule(t,e,n,r){const i=hi(n);i.push(t.name);const s=hi(r);return s.push(1),{idx:e,def:t.definition,ruleStack:i,occurrenceStack:s}}var ir;(function(t){t[t.OPTION=0]="OPTION",t[t.REPETITION=1]="REPETITION",t[t.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",t[t.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",t[t.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",t[t.ALTERNATION=5]="ALTERNATION"})(ir||(ir={}));function qU(t){if(t instanceof us||t==="Option")return ir.OPTION;if(t instanceof Dr||t==="Repetition")return ir.REPETITION;if(t instanceof Va||t==="RepetitionMandatory")return ir.REPETITION_MANDATORY;if(t instanceof Ha||t==="RepetitionMandatoryWithSeparator")return ir.REPETITION_MANDATORY_WITH_SEPARATOR;if(t instanceof jo||t==="RepetitionWithSeparator")return ir.REPETITION_WITH_SEPARATOR;if(t instanceof $o||t==="Alternation")return ir.ALTERNATION;throw Error("non exhaustive match")}function Fle(t,e,n,r,i,s){const o=fA(t,e,n),a=YU(o)?fv:Nm;return s(o,r,a,i)}function Ble(t,e,n,r,i,s){const o=dA(t,e,i,n),a=YU(o)?fv:Nm;return s(o[0],a,r)}function zle(t,e,n,r){const i=t.length,s=No(t,o=>No(o,a=>a.length===1));if(e)return function(o){const a=ot(o,l=>l.GATE);for(let l=0;lls(l)),a=ds(o,(l,c,u)=>(bt(c,h=>{wt(l,h.tokenTypeIdx)||(l[h.tokenTypeIdx]=u),bt(h.categoryMatches,p=>{wt(l,p)||(l[p]=u)})}),l),{});return function(){const l=this.LA(1);return a[l.tokenTypeIdx]}}else return function(){for(let o=0;os.length===1),i=t.length;if(r&&!n){const s=ls(t);if(s.length===1&&Un(s[0].categoryMatches)){const a=s[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===a}}else{const o=ds(s,(a,l,c)=>(a[l.tokenTypeIdx]=!0,bt(l.categoryMatches,u=>{a[u]=!0}),a),[]);return function(){const a=this.LA(1);return o[a.tokenTypeIdx]===!0}}}else return function(){e:for(let s=0;syw([o],1)),r=Ak(n.length),i=ot(n,o=>{const a={};return bt(o,l=>{const c=m1(l.partialPath);bt(c,u=>{a[u]=!0})}),a});let s=n;for(let o=1;o<=e;o++){const a=s;s=Ak(a.length);for(let l=0;l{const _=m1(y.partialPath);bt(_,S=>{i[l][S]=!0})})}}}}return r}function fA(t,e,n,r){const i=new XU(t,ir.ALTERNATION,r);return e.accept(i),KU(i.result,n)}function dA(t,e,n,r){const i=new XU(t,n);e.accept(i);const s=i.result,a=new Hle(e,t,n).startWalking(),l=new _s({definition:s}),c=new _s({definition:a});return KU([l,c],r)}function xw(t,e){e:for(let n=0;n{const i=e[r];return n===i||i.categoryMatchesMap[n.tokenTypeIdx]})}function YU(t){return No(t,e=>No(e,n=>No(n,r=>Un(r.categoryMatches))))}function jle(t){const e=t.lookaheadStrategy.validate({rules:t.rules,tokenTypes:t.tokenTypes,grammarName:t.grammarName});return ot(e,n=>Object.assign({type:Gi.CUSTOM_LOOKAHEAD_VALIDATION},n))}function $le(t,e,n,r){const i=no(t,l=>qle(l,n)),s=sce(t,e,n),o=no(t,l=>tce(l,n)),a=no(t,l=>Yle(l,t,r,n));return i.concat(s,o,a)}function qle(t,e){const n=new Kle;t.accept(n);const r=n.allProductions,i=NL(r,Xle),s=zo(i,a=>a.length>1);return ot(Cr(s),a=>{const l=Oo(a),c=e.buildDuplicateFoundError(t,a),u=fa(l),h={message:c,type:Gi.DUPLICATE_PRODUCTIONS,ruleName:t.name,dslName:u,occurrence:l.idx},p=ZU(l);return p&&(h.parameter=p),h})}function Xle(t){return`${fa(t)}_#_${t.idx}_#_${ZU(t)}`}function ZU(t){return t instanceof Qn?t.terminalType.name:t instanceof gs?t.nonTerminalName:""}class Kle extends ph{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(e){this.allProductions.push(e)}visitOption(e){this.allProductions.push(e)}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}visitAlternation(e){this.allProductions.push(e)}visitTerminal(e){this.allProductions.push(e)}}function Yle(t,e,n,r){const i=[];if(ds(e,(o,a)=>a.name===t.name?o+1:o,0)>1){const o=r.buildDuplicateRuleNameError({topLevelRule:t,grammarName:n});i.push({message:o,type:Gi.DUPLICATE_RULE_NAME,ruleName:t.name})}return i}function Zle(t,e,n){const r=[];let i;return $i(e,t)||(i=`Invalid rule override, rule: ->${t}<- cannot be overridden in the grammar: ->${n}<-as it is not defined in any of the super grammars `,r.push({message:i,type:Gi.INVALID_RULE_OVERRIDE,ruleName:t})),r}function JU(t,e,n,r=[]){const i=[],s=v_(e.definition);if(Un(s))return[];{const o=t.name;$i(s,t)&&i.push({message:n.buildLeftRecursionError({topLevelRule:t,leftRecursionPath:r}),type:Gi.LEFT_RECURSION,ruleName:o});const l=qv(s,r.concat([t])),c=no(l,u=>{const h=hi(r);return h.push(u),JU(t,u,n,h)});return i.concat(c)}}function v_(t){let e=[];if(Un(t))return e;const n=Oo(t);if(n instanceof gs)e.push(n.referencedRule);else if(n instanceof _s||n instanceof us||n instanceof Va||n instanceof Ha||n instanceof jo||n instanceof Dr)e=e.concat(v_(n.definition));else if(n instanceof $o)e=ls(ot(n.definition,s=>v_(s.definition)));else if(!(n instanceof Qn))throw Error("non exhaustive match");const r=lv(n),i=t.length>1;if(r&&i){const s=ai(t);return e.concat(v_(s))}else return e}class pA extends ph{constructor(){super(...arguments),this.alternations=[]}visitAlternation(e){this.alternations.push(e)}}function Jle(t,e){const n=new pA;t.accept(n);const r=n.alternations;return no(r,s=>{const o=Ap(s.definition);return no(o,(a,l)=>{const c=$U([a],[],Nm,1);return Un(c)?[{message:e.buildEmptyAlternationError({topLevelRule:t,alternation:s,emptyChoiceIdx:l}),type:Gi.NONE_LAST_EMPTY_ALT,ruleName:t.name,occurrence:s.idx,alternative:l+1}]:[]})})}function Qle(t,e,n){const r=new pA;t.accept(r);let i=r.alternations;return i=Xv(i,o=>o.ignoreAmbiguities===!0),no(i,o=>{const a=o.idx,l=o.maxLookahead||e,c=fA(a,t,l,o),u=rce(c,o,t,n),h=ice(c,o,t,n);return u.concat(h)})}class ece extends ph{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}}function tce(t,e){const n=new pA;t.accept(n);const r=n.alternations;return no(r,s=>s.definition.length>255?[{message:e.buildTooManyAlternativesError({topLevelRule:t,alternation:s}),type:Gi.TOO_MANY_ALTS,ruleName:t.name,occurrence:s.idx}]:[])}function nce(t,e,n){const r=[];return bt(t,i=>{const s=new ece;i.accept(s);const o=s.allProductions;bt(o,a=>{const l=qU(a),c=a.maxLookahead||e,u=a.idx,p=dA(u,i,l,c)[0];if(Un(ls(p))){const m=n.buildEmptyRepetitionError({topLevelRule:i,repetition:a});r.push({message:m,type:Gi.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),r}function rce(t,e,n,r){const i=[],s=ds(t,(a,l,c)=>(e.definition[c].ignoreAmbiguities===!0||bt(l,u=>{const h=[c];bt(t,(p,m)=>{c!==m&&xw(p,u)&&e.definition[m].ignoreAmbiguities!==!0&&h.push(m)}),h.length>1&&!xw(i,u)&&(i.push(u),a.push({alts:h,path:u}))}),a),[]);return ot(s,a=>{const l=ot(a.alts,u=>u+1);return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:e,ambiguityIndices:l,prefixPath:a.path}),type:Gi.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:e.idx,alternatives:a.alts}})}function ice(t,e,n,r){const i=ds(t,(o,a,l)=>{const c=ot(a,u=>({idx:l,path:u}));return o.concat(c)},[]);return nm(no(i,o=>{if(e.definition[o.idx].ignoreAmbiguities===!0)return[];const l=o.idx,c=o.path,u=uo(i,p=>e.definition[p.idx].ignoreAmbiguities!==!0&&p.idx{const m=[p.idx+1,l+1],g=e.idx===0?"":e.idx;return{message:r.buildAlternationPrefixAmbiguityError({topLevelRule:n,alternation:e,ambiguityIndices:m,prefixPath:p.path}),type:Gi.AMBIGUOUS_PREFIX_ALTS,ruleName:n.name,occurrence:g,alternatives:m}})}))}function sce(t,e,n){const r=[],i=ot(e,s=>s.name);return bt(t,s=>{const o=s.name;if($i(i,o)){const a=n.buildNamespaceConflictError(s);r.push({message:a,type:Gi.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:o})}}),r}function oce(t){const e=BT(t,{errMsgProvider:Nle}),n={};return bt(t.rules,r=>{n[r.name]=r}),kle(n,e.errMsgProvider)}function ace(t){return t=BT(t,{errMsgProvider:Iu}),$le(t.rules,t.tokenTypes,t.errMsgProvider,t.grammarName)}const QU="MismatchedTokenException",e3="NoViableAltException",t3="EarlyExitException",n3="NotAllInputParsedException",r3=[QU,e3,t3,n3];Object.freeze(r3);function dv(t){return $i(r3,t.name)}class By extends Error{constructor(e,n){super(e),this.token=n,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class i3 extends By{constructor(e,n,r){super(e,n),this.previousToken=r,this.name=QU}}class lce extends By{constructor(e,n,r){super(e,n),this.previousToken=r,this.name=e3}}class cce extends By{constructor(e,n){super(e,n),this.name=n3}}class uce extends By{constructor(e,n,r){super(e,n),this.previousToken=r,this.name=t3}}const g1={},s3="InRuleRecoveryException";class hce extends Error{constructor(e){super(e),this.name=s3}}class fce{initRecoverable(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=wt(e,"recoveryEnabled")?e.recoveryEnabled:Il.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=dce)}getTokenToInsert(e){const n=Im(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return n.isInsertedInRecovery=!0,n}canTokenTypeBeInsertedInRecovery(e){return!0}canTokenTypeBeDeletedInRecovery(e){return!0}tryInRepetitionRecovery(e,n,r,i){const s=this.findReSyncTokenType(),o=this.exportLexerState(),a=[];let l=!1;const c=this.LA(1);let u=this.LA(1);const h=()=>{const p=this.LA(0),m=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:c,previous:p,ruleName:this.getCurrRuleFullName()}),g=new i3(m,c,this.LA(0));g.resyncedTokens=Ap(a),this.SAVE_ERROR(g)};for(;!l;)if(this.tokenMatcher(u,i)){h();return}else if(r.call(this)){h(),e.apply(this,n);return}else this.tokenMatcher(u,s)?l=!0:(u=this.SKIP_TOKEN(),this.addToResyncTokens(u,a));this.importLexerState(o)}shouldInRepetitionRecoveryBeTried(e,n,r){return!(r===!1||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,n)))}getFollowsForInRuleRecovery(e,n){const r=this.getCurrentGrammarPath(e,n);return this.getNextPossibleTokenTypes(r)}tryInRuleRecovery(e,n){if(this.canRecoverWithSingleTokenInsertion(e,n))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){const r=this.SKIP_TOKEN();return this.consumeToken(),r}throw new hce("sad sad panda")}canPerformInRuleRecovery(e,n){return this.canRecoverWithSingleTokenInsertion(e,n)||this.canRecoverWithSingleTokenDeletion(e)}canRecoverWithSingleTokenInsertion(e,n){if(!this.canTokenTypeBeInsertedInRecovery(e)||Un(n))return!1;const r=this.LA(1);return Ff(n,s=>this.tokenMatcher(r,s))!==void 0}canRecoverWithSingleTokenDeletion(e){return this.canTokenTypeBeDeletedInRecovery(e)?this.tokenMatcher(this.LA(2),e):!1}isInCurrentRuleReSyncSet(e){const n=this.getCurrFollowKey(),r=this.getFollowSetFromFollowKey(n);return $i(r,e)}findReSyncTokenType(){const e=this.flattenFollowSet();let n=this.LA(1),r=2;for(;;){const i=Ff(e,s=>Rle(n,s));if(i!==void 0)return i;n=this.LA(r),r++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return g1;const e=this.getLastExplicitRuleShortName(),n=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:n,inRule:this.shortRuleNameToFullName(r)}}buildFullFollowKeyStack(){const e=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return ot(e,(r,i)=>i===0?g1:{ruleName:this.shortRuleNameToFullName(r),idxInCallingRule:n[i],inRule:this.shortRuleNameToFullName(e[i-1])})}flattenFollowSet(){const e=ot(this.buildFullFollowKeyStack(),n=>this.getFollowSetFromFollowKey(n));return ls(e)}getFollowSetFromFollowKey(e){if(e===g1)return[eh];const n=e.ruleName+e.idxInCallingRule+PU+e.inRule;return this.resyncFollows[n]}addToResyncTokens(e,n){return this.tokenMatcher(e,eh)||n.push(e),n}reSyncTo(e){const n=[];let r=this.LA(1);for(;this.tokenMatcher(r,e)===!1;)r=this.SKIP_TOKEN(),this.addToResyncTokens(r,n);return Ap(n)}attemptInRepetitionRecovery(e,n,r,i,s,o,a){}getCurrentGrammarPath(e,n){const r=this.getHumanReadableRuleStack(),i=hi(this.RULE_OCCURRENCE_STACK);return{ruleStack:r,occurrenceStack:i,lastTok:e,lastTokOccurrence:n}}getHumanReadableRuleStack(){return ot(this.RULE_STACK,e=>this.shortRuleNameToFullName(e))}}function dce(t,e,n,r,i,s,o){const a=this.getKeyForAutomaticLookahead(r,i);let l=this.firstAfterRepMap[a];if(l===void 0){const p=this.getCurrRuleFullName(),m=this.getGAstProductions()[p];l=new s(m,i).startWalking(),this.firstAfterRepMap[a]=l}let c=l.token,u=l.occurrence;const h=l.isEndOfRule;this.RULE_STACK.length===1&&h&&c===void 0&&(c=eh,u=1),!(c===void 0||u===void 0)&&this.shouldInRepetitionRecoveryBeTried(c,u,o)&&this.tryInRepetitionRecovery(t,e,n,c)}const pce=4,Xc=8,o3=1<JU(n,n,Iu))}validateEmptyOrAlternatives(e){return no(e,n=>Jle(n,Iu))}validateAmbiguousAlternationAlternatives(e,n){return no(e,r=>Qle(r,n,Iu))}validateSomeNonEmptyLookaheadPath(e,n){return nce(e,n,Iu)}buildLookaheadForAlternation(e){return Fle(e.prodOccurrence,e.rule,e.maxLookahead,e.hasPredicates,e.dynamicTokensEnabled,zle)}buildLookaheadForOptional(e){return Ble(e.prodOccurrence,e.rule,e.maxLookahead,e.dynamicTokensEnabled,qU(e.prodType),Vle)}}class gce{initLooksAhead(e){this.dynamicTokensEnabled=wt(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:Il.dynamicTokensEnabled,this.maxLookahead=wt(e,"maxLookahead")?e.maxLookahead:Il.maxLookahead,this.lookaheadStrategy=wt(e,"lookaheadStrategy")?e.lookaheadStrategy:new mce({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(e){bt(e,n=>{this.TRACE_INIT(`${n.name} Rule Lookahead`,()=>{const{alternation:r,repetition:i,option:s,repetitionMandatory:o,repetitionMandatoryWithSeparator:a,repetitionWithSeparator:l}=vce(n);bt(r,c=>{const u=c.idx===0?"":c.idx;this.TRACE_INIT(`${fa(c)}${u}`,()=>{const h=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:c.idx,rule:n,maxLookahead:c.maxLookahead||this.maxLookahead,hasPredicates:c.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),p=_1(this.fullRuleNameToShort[n.name],o3,c.idx);this.setLaFuncCache(p,h)})}),bt(i,c=>{this.computeLookaheadFunc(n,c.idx,Sw,"Repetition",c.maxLookahead,fa(c))}),bt(s,c=>{this.computeLookaheadFunc(n,c.idx,a3,"Option",c.maxLookahead,fa(c))}),bt(o,c=>{this.computeLookaheadFunc(n,c.idx,Ew,"RepetitionMandatory",c.maxLookahead,fa(c))}),bt(a,c=>{this.computeLookaheadFunc(n,c.idx,y_,"RepetitionMandatoryWithSeparator",c.maxLookahead,fa(c))}),bt(l,c=>{this.computeLookaheadFunc(n,c.idx,ww,"RepetitionWithSeparator",c.maxLookahead,fa(c))})})})}computeLookaheadFunc(e,n,r,i,s,o){this.TRACE_INIT(`${o}${n===0?"":n}`,()=>{const a=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:n,rule:e,maxLookahead:s||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),l=_1(this.fullRuleNameToShort[e.name],r,n);this.setLaFuncCache(l,a)})}getKeyForAutomaticLookahead(e,n){const r=this.getLastExplicitRuleShortName();return _1(r,e,n)}getLaFuncFromCache(e){return this.lookAheadFuncsCache.get(e)}setLaFuncCache(e,n){this.lookAheadFuncsCache.set(e,n)}}class _ce extends ph{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(e){this.dslMethods.option.push(e)}visitRepetitionWithSeparator(e){this.dslMethods.repetitionWithSeparator.push(e)}visitRepetitionMandatory(e){this.dslMethods.repetitionMandatory.push(e)}visitRepetitionMandatoryWithSeparator(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)}visitRepetition(e){this.dslMethods.repetition.push(e)}visitAlternation(e){this.dslMethods.alternation.push(e)}}const I0=new _ce;function vce(t){I0.reset(),t.accept(I0);const e=I0.dslMethods;return I0.reset(),e}function Mk(t,e){isNaN(t.startOffset)===!0?(t.startOffset=e.startOffset,t.endOffset=e.endOffset):t.endOffseto.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: + ${s.join(` + +`).replace(/\n/g,` + `)}`)}}};return n.prototype=r,n.prototype.constructor=n,n._RULE_NAMES=e,n}function Tce(t,e,n){const r=function(){};l3(r,t+"BaseSemanticsWithDefaults");const i=Object.create(n.prototype);return bt(e,s=>{i[s]=Ece}),r.prototype=i,r.prototype.constructor=r,r}var Tw;(function(t){t[t.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",t[t.MISSING_METHOD=1]="MISSING_METHOD"})(Tw||(Tw={}));function bce(t,e){return Ace(t,e)}function Ace(t,e){const n=uo(e,i=>Fl(t[i])===!1),r=ot(n,i=>({msg:`Missing visitor method: <${i}> on ${t.constructor.name} CST Visitor.`,type:Tw.MISSING_METHOD,methodName:i}));return nm(r)}class Mce{initTreeBuilder(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=wt(e,"nodeLocationTracking")?e.nodeLocationTracking:Il.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=Ir,this.cstFinallyStateUpdate=Ir,this.cstPostTerminal=Ir,this.cstPostNonTerminal=Ir,this.cstPostRule=Ir;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Ck,this.setNodeLocationFromNode=Ck,this.cstPostRule=Ir,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=Ir,this.setNodeLocationFromNode=Ir,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Mk,this.setNodeLocationFromNode=Mk,this.cstPostRule=Ir,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=Ir,this.setNodeLocationFromNode=Ir,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=Ir,this.setNodeLocationFromNode=Ir,this.cstPostRule=Ir,this.setInitialNodeLocation=Ir;else throw Error(`Invalid config option: "${e.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(e){e.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(e){const n=this.LA(1);e.location={startOffset:n.startOffset,startLine:n.startLine,startColumn:n.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(e){const n={name:e,children:Object.create(null)};this.setInitialNodeLocation(n),this.CST_STACK.push(n)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(e){const n=this.LA(0),r=e.location;r.startOffset<=n.startOffset?(r.endOffset=n.endOffset,r.endLine=n.endLine,r.endColumn=n.endColumn):(r.startOffset=NaN,r.startLine=NaN,r.startColumn=NaN)}cstPostRuleOnlyOffset(e){const n=this.LA(0),r=e.location;r.startOffset<=n.startOffset?r.endOffset=n.endOffset:r.startOffset=NaN}cstPostTerminal(e,n){const r=this.CST_STACK[this.CST_STACK.length-1];yce(r,n,e),this.setNodeLocationFromToken(r.location,n)}cstPostNonTerminal(e,n){const r=this.CST_STACK[this.CST_STACK.length-1];xce(r,n,e),this.setNodeLocationFromNode(r.location,e.location)}getBaseCstVisitorConstructor(){if(Rl(this.baseCstVisitorConstructor)){const e=wce(this.className,lo(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(Rl(this.baseCstVisitorWithDefaultsConstructor)){const e=Tce(this.className,lo(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-1]}getPreviousExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-2]}getLastExplicitRuleOccurrenceIndex(){const e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]}}class Cce{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(e){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):mv}LA(e){const n=this.currIdx+e;return n<0||this.tokVectorLength<=n?mv:this.tokVector[n]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(e){this.currIdx=e}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}}class Rce{ACTION(e){return e.call(this)}consume(e,n,r){return this.consumeInternal(n,e,r)}subrule(e,n,r){return this.subruleInternal(n,e,r)}option(e,n){return this.optionInternal(n,e)}or(e,n){return this.orInternal(n,e)}many(e,n){return this.manyInternal(e,n)}atLeastOne(e,n){return this.atLeastOneInternal(e,n)}CONSUME(e,n){return this.consumeInternal(e,0,n)}CONSUME1(e,n){return this.consumeInternal(e,1,n)}CONSUME2(e,n){return this.consumeInternal(e,2,n)}CONSUME3(e,n){return this.consumeInternal(e,3,n)}CONSUME4(e,n){return this.consumeInternal(e,4,n)}CONSUME5(e,n){return this.consumeInternal(e,5,n)}CONSUME6(e,n){return this.consumeInternal(e,6,n)}CONSUME7(e,n){return this.consumeInternal(e,7,n)}CONSUME8(e,n){return this.consumeInternal(e,8,n)}CONSUME9(e,n){return this.consumeInternal(e,9,n)}SUBRULE(e,n){return this.subruleInternal(e,0,n)}SUBRULE1(e,n){return this.subruleInternal(e,1,n)}SUBRULE2(e,n){return this.subruleInternal(e,2,n)}SUBRULE3(e,n){return this.subruleInternal(e,3,n)}SUBRULE4(e,n){return this.subruleInternal(e,4,n)}SUBRULE5(e,n){return this.subruleInternal(e,5,n)}SUBRULE6(e,n){return this.subruleInternal(e,6,n)}SUBRULE7(e,n){return this.subruleInternal(e,7,n)}SUBRULE8(e,n){return this.subruleInternal(e,8,n)}SUBRULE9(e,n){return this.subruleInternal(e,9,n)}OPTION(e){return this.optionInternal(e,0)}OPTION1(e){return this.optionInternal(e,1)}OPTION2(e){return this.optionInternal(e,2)}OPTION3(e){return this.optionInternal(e,3)}OPTION4(e){return this.optionInternal(e,4)}OPTION5(e){return this.optionInternal(e,5)}OPTION6(e){return this.optionInternal(e,6)}OPTION7(e){return this.optionInternal(e,7)}OPTION8(e){return this.optionInternal(e,8)}OPTION9(e){return this.optionInternal(e,9)}OR(e){return this.orInternal(e,0)}OR1(e){return this.orInternal(e,1)}OR2(e){return this.orInternal(e,2)}OR3(e){return this.orInternal(e,3)}OR4(e){return this.orInternal(e,4)}OR5(e){return this.orInternal(e,5)}OR6(e){return this.orInternal(e,6)}OR7(e){return this.orInternal(e,7)}OR8(e){return this.orInternal(e,8)}OR9(e){return this.orInternal(e,9)}MANY(e){this.manyInternal(0,e)}MANY1(e){this.manyInternal(1,e)}MANY2(e){this.manyInternal(2,e)}MANY3(e){this.manyInternal(3,e)}MANY4(e){this.manyInternal(4,e)}MANY5(e){this.manyInternal(5,e)}MANY6(e){this.manyInternal(6,e)}MANY7(e){this.manyInternal(7,e)}MANY8(e){this.manyInternal(8,e)}MANY9(e){this.manyInternal(9,e)}MANY_SEP(e){this.manySepFirstInternal(0,e)}MANY_SEP1(e){this.manySepFirstInternal(1,e)}MANY_SEP2(e){this.manySepFirstInternal(2,e)}MANY_SEP3(e){this.manySepFirstInternal(3,e)}MANY_SEP4(e){this.manySepFirstInternal(4,e)}MANY_SEP5(e){this.manySepFirstInternal(5,e)}MANY_SEP6(e){this.manySepFirstInternal(6,e)}MANY_SEP7(e){this.manySepFirstInternal(7,e)}MANY_SEP8(e){this.manySepFirstInternal(8,e)}MANY_SEP9(e){this.manySepFirstInternal(9,e)}AT_LEAST_ONE(e){this.atLeastOneInternal(0,e)}AT_LEAST_ONE1(e){return this.atLeastOneInternal(1,e)}AT_LEAST_ONE2(e){this.atLeastOneInternal(2,e)}AT_LEAST_ONE3(e){this.atLeastOneInternal(3,e)}AT_LEAST_ONE4(e){this.atLeastOneInternal(4,e)}AT_LEAST_ONE5(e){this.atLeastOneInternal(5,e)}AT_LEAST_ONE6(e){this.atLeastOneInternal(6,e)}AT_LEAST_ONE7(e){this.atLeastOneInternal(7,e)}AT_LEAST_ONE8(e){this.atLeastOneInternal(8,e)}AT_LEAST_ONE9(e){this.atLeastOneInternal(9,e)}AT_LEAST_ONE_SEP(e){this.atLeastOneSepFirstInternal(0,e)}AT_LEAST_ONE_SEP1(e){this.atLeastOneSepFirstInternal(1,e)}AT_LEAST_ONE_SEP2(e){this.atLeastOneSepFirstInternal(2,e)}AT_LEAST_ONE_SEP3(e){this.atLeastOneSepFirstInternal(3,e)}AT_LEAST_ONE_SEP4(e){this.atLeastOneSepFirstInternal(4,e)}AT_LEAST_ONE_SEP5(e){this.atLeastOneSepFirstInternal(5,e)}AT_LEAST_ONE_SEP6(e){this.atLeastOneSepFirstInternal(6,e)}AT_LEAST_ONE_SEP7(e){this.atLeastOneSepFirstInternal(7,e)}AT_LEAST_ONE_SEP8(e){this.atLeastOneSepFirstInternal(8,e)}AT_LEAST_ONE_SEP9(e){this.atLeastOneSepFirstInternal(9,e)}RULE(e,n,r=gv){if($i(this.definedRulesNames,e)){const o={message:Iu.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:Gi.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(o)}this.definedRulesNames.push(e);const i=this.defineRule(e,n,r);return this[e]=i,i}OVERRIDE_RULE(e,n,r=gv){const i=Zle(e,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);const s=this.defineRule(e,n,r);return this[e]=s,s}BACKTRACK(e,n){return function(){this.isBackTrackingStack.push(1);const r=this.saveRecogState();try{return e.apply(this,n),!0}catch(i){if(dv(i))return!1;throw i}finally{this.reloadRecogState(r),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return kae(Cr(this.gastProductionsCache))}}class Nce{initRecognizerEngine(e,n){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=fv,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},wt(n,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`);if(un(e)){if(Un(e))throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`)}if(un(e))this.tokensMap=ds(e,(s,o)=>(s[o.name]=o,s),{});else if(wt(e,"modes")&&No(ls(Cr(e.modes)),ble)){const s=ls(Cr(e.modes)),o=Kv(s);this.tokensMap=ds(o,(a,l)=>(a[l.name]=l,a),{})}else if(ao(e))this.tokensMap=hi(e);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=eh;const r=wt(e,"modes")?ls(Cr(e.modes)):Cr(e),i=No(r,s=>Un(s.categoryMatches));this.tokenMatcher=i?fv:Nm,km(Cr(this.tokensMap))}defineRule(e,n,r){if(this.selfAnalysisDone)throw Error(`Grammar rule <${e}> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);const i=wt(r,"resyncEnabled")?r.resyncEnabled:gv.resyncEnabled,s=wt(r,"recoveryValueFunc")?r.recoveryValueFunc:gv.recoveryValueFunc,o=this.ruleShortNameIdx<o.call(this)&&a.call(this)}}else s=e;if(i.call(this)===!0)return s.call(this)}atLeastOneInternal(e,n){const r=this.getKeyForAutomaticLookahead(Ew,e);return this.atLeastOneInternalLogic(e,n,r)}atLeastOneInternalLogic(e,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const o=n.GATE;if(o!==void 0){const a=i;i=()=>o.call(this)&&a.call(this)}}else s=n;if(i.call(this)===!0){let o=this.doSingleRepetition(s);for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s)}else throw this.raiseEarlyExitException(e,ir.REPETITION_MANDATORY,n.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[e,n],i,Ew,e,Dle)}atLeastOneSepFirstInternal(e,n){const r=this.getKeyForAutomaticLookahead(y_,e);this.atLeastOneSepFirstInternalLogic(e,n,r)}atLeastOneSepFirstInternalLogic(e,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,bk],a,y_,e,bk)}else throw this.raiseEarlyExitException(e,ir.REPETITION_MANDATORY_WITH_SEPARATOR,n.ERR_MSG)}manyInternal(e,n){const r=this.getKeyForAutomaticLookahead(Sw,e);return this.manyInternalLogic(e,n,r)}manyInternalLogic(e,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const a=n.GATE;if(a!==void 0){const l=i;i=()=>a.call(this)&&l.call(this)}}else s=n;let o=!0;for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s);this.attemptInRepetitionRecovery(this.manyInternal,[e,n],i,Sw,e,Ple,o)}manySepFirstInternal(e,n){const r=this.getKeyForAutomaticLookahead(ww,e);this.manySepFirstInternalLogic(e,n,r)}manySepFirstInternalLogic(e,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,Tk],a,ww,e,Tk)}}repetitionSepSecondInternal(e,n,r,i,s){for(;r();)this.CONSUME(n),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,n,r,i,s],r,y_,e,s)}doSingleRepetition(e){const n=this.getLexerPosition();return e.call(this),this.getLexerPosition()>n}orInternal(e,n){const r=this.getKeyForAutomaticLookahead(o3,n),i=un(e)?e:e.DEF,o=this.getLaFuncFromCache(r).call(this,i);if(o!==void 0)return i[o].ALT.call(this);this.raiseNoAltException(n,e.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){const e=this.LA(1),n=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new cce(n,e))}}subruleInternal(e,n,r){let i;try{const s=r!==void 0?r.ARGS:void 0;return this.subruleIdx=n,i=e.apply(this,s),this.cstPostNonTerminal(i,r!==void 0&&r.LABEL!==void 0?r.LABEL:e.ruleName),i}catch(s){throw this.subruleInternalError(s,r,e.ruleName)}}subruleInternalError(e,n,r){throw dv(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,n!==void 0&&n.LABEL!==void 0?n.LABEL:r),delete e.partialCstResult),e}consumeInternal(e,n,r){let i;try{const s=this.LA(1);this.tokenMatcher(s,e)===!0?(this.consumeToken(),i=s):this.consumeInternalError(e,s,r)}catch(s){i=this.consumeInternalRecovery(e,n,s)}return this.cstPostTerminal(r!==void 0&&r.LABEL!==void 0?r.LABEL:e.name,i),i}consumeInternalError(e,n,r){let i;const s=this.LA(0);throw r!==void 0&&r.ERR_MSG?i=r.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:n,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new i3(i,n,s))}consumeInternalRecovery(e,n,r){if(this.recoveryEnabled&&r.name==="MismatchedTokenException"&&!this.isBackTracking()){const i=this.getFollowsForInRuleRecovery(e,n);try{return this.tryInRuleRecovery(e,i)}catch(s){throw s.name===s3?r:s}}else throw r}saveRecogState(){const e=this.errors,n=hi(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:n,CST_STACK:this.CST_STACK}}reloadRecogState(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK}ruleInvocationStateUpdate(e,n,r){this.RULE_OCCURRENCE_STACK.push(r),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(n)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){const e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]}shortRuleNameToFullName(e){return this.shortRuleNameToFull[e]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),eh)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}}class kce{initErrorHandler(e){this._errors=[],this.errorMessageProvider=wt(e,"errorMessageProvider")?e.errorMessageProvider:Il.errorMessageProvider}SAVE_ERROR(e){if(dv(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:hi(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return hi(this._errors)}set errors(e){this._errors=e}raiseEarlyExitException(e,n,r){const i=this.getCurrRuleFullName(),s=this.getGAstProductions()[i],a=dA(e,s,n,this.maxLookahead)[0],l=[];for(let u=1;u<=this.maxLookahead;u++)l.push(this.LA(u));const c=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:l,previous:this.LA(0),customUserDescription:r,ruleName:i});throw this.SAVE_ERROR(new uce(c,this.LA(1),this.LA(0)))}raiseNoAltException(e,n){const r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],s=fA(e,i,this.maxLookahead),o=[];for(let c=1;c<=this.maxLookahead;c++)o.push(this.LA(c));const a=this.LA(0),l=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:o,previous:a,customUserDescription:n,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new lce(l,this.LA(1),a))}}class Ice{initContentAssist(){}computeContentAssist(e,n){const r=this.gastProductionsCache[e];if(Rl(r))throw Error(`Rule ->${e}<- does not exist in this grammar.`);return $U([r],n,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(e){const n=Oo(e.ruleStack),i=this.getGAstProductions()[n];return new Lle(i,e).startWalking()}}const zy={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(zy);const Rk=!0,Nk=Math.pow(2,Xc)-1,c3=Ds({name:"RECORDING_PHASE_TOKEN",pattern:Br.NA});km([c3]);const u3=Im(c3,`This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(u3);const Oce={name:`This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}};class Lce{initGastRecorder(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let e=0;e<10;e++){const n=e>0?e:"";this[`CONSUME${n}`]=function(r,i){return this.consumeInternalRecord(r,e,i)},this[`SUBRULE${n}`]=function(r,i){return this.subruleInternalRecord(r,e,i)},this[`OPTION${n}`]=function(r){return this.optionInternalRecord(r,e)},this[`OR${n}`]=function(r){return this.orInternalRecord(r,e)},this[`MANY${n}`]=function(r){this.manyInternalRecord(e,r)},this[`MANY_SEP${n}`]=function(r){this.manySepFirstInternalRecord(e,r)},this[`AT_LEAST_ONE${n}`]=function(r){this.atLeastOneInternalRecord(e,r)},this[`AT_LEAST_ONE_SEP${n}`]=function(r){this.atLeastOneSepFirstInternalRecord(e,r)}}this.consume=function(e,n,r){return this.consumeInternalRecord(n,e,r)},this.subrule=function(e,n,r){return this.subruleInternalRecord(n,e,r)},this.option=function(e,n){return this.optionInternalRecord(n,e)},this.or=function(e,n){return this.orInternalRecord(n,e)},this.many=function(e,n){this.manyInternalRecord(e,n)},this.atLeastOne=function(e,n){this.atLeastOneInternalRecord(e,n)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{const e=this;for(let n=0;n<10;n++){const r=n>0?n:"";delete e[`CONSUME${r}`],delete e[`SUBRULE${r}`],delete e[`OPTION${r}`],delete e[`OR${r}`],delete e[`MANY${r}`],delete e[`MANY_SEP${r}`],delete e[`AT_LEAST_ONE${r}`],delete e[`AT_LEAST_ONE_SEP${r}`]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})}ACTION_RECORD(e){}BACKTRACK_RECORD(e,n){return()=>!0}LA_RECORD(e){return mv}topLevelRuleRecord(e,n){try{const r=new gd({definition:[],name:e});return r.name=e,this.recordingProdStack.push(r),n.call(this),this.recordingProdStack.pop(),r}catch(r){if(r.KNOWN_RECORDER_ERROR!==!0)try{r.message=r.message+` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw r}throw r}}optionInternalRecord(e,n){return qd.call(this,us,e,n)}atLeastOneInternalRecord(e,n){qd.call(this,Va,n,e)}atLeastOneSepFirstInternalRecord(e,n){qd.call(this,Ha,n,e,Rk)}manyInternalRecord(e,n){qd.call(this,Dr,n,e)}manySepFirstInternalRecord(e,n){qd.call(this,jo,n,e,Rk)}orInternalRecord(e,n){return Pce.call(this,e,n)}subruleInternalRecord(e,n,r){if(pv(n),!e||wt(e,"ruleName")===!1){const a=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw a.KNOWN_RECORDER_ERROR=!0,a}const i=Uf(this.recordingProdStack),s=e.ruleName,o=new gs({idx:n,nonTerminalName:s,label:r==null?void 0:r.LABEL,referencedRule:void 0});return i.definition.push(o),this.outputCst?Oce:zy}consumeInternalRecord(e,n,r){if(pv(n),!GU(e)){const o=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw o.KNOWN_RECORDER_ERROR=!0,o}const i=Uf(this.recordingProdStack),s=new Qn({idx:n,terminalType:e,label:r==null?void 0:r.LABEL});return i.definition.push(s),u3}}function qd(t,e,n,r=!1){pv(n);const i=Uf(this.recordingProdStack),s=Fl(e)?e:e.DEF,o=new t({definition:[],idx:n});return r&&(o.separator=e.SEP),wt(e,"MAX_LOOKAHEAD")&&(o.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(o),s.call(this),i.definition.push(o),this.recordingProdStack.pop(),zy}function Pce(t,e){pv(e);const n=Uf(this.recordingProdStack),r=un(t)===!1,i=r===!1?t:t.DEF,s=new $o({definition:[],idx:e,ignoreAmbiguities:r&&t.IGNORE_AMBIGUITIES===!0});wt(t,"MAX_LOOKAHEAD")&&(s.maxLookahead=t.MAX_LOOKAHEAD);const o=zT(i,a=>Fl(a.GATE));return s.hasPredicates=o,n.definition.push(s),bt(i,a=>{const l=new _s({definition:[]});s.definition.push(l),wt(a,"IGNORE_AMBIGUITIES")?l.ignoreAmbiguities=a.IGNORE_AMBIGUITIES:wt(a,"GATE")&&(l.ignoreAmbiguities=!0),this.recordingProdStack.push(l),a.ALT.call(this),this.recordingProdStack.pop()}),zy}function kk(t){return t===0?"":`${t}`}function pv(t){if(t<0||t>Nk){const e=new Error(`Invalid DSL Method idx value: <${t}> + Idx value must be a none negative value smaller than ${Nk+1}`);throw e.KNOWN_RECORDER_ERROR=!0,e}}class Dce{initPerformanceTracer(e){if(wt(e,"traceInitPerf")){const n=e.traceInitPerf,r=typeof n=="number";this.traceInitMaxIdent=r?n:1/0,this.traceInitPerf=r?n>0:n}else this.traceInitMaxIdent=0,this.traceInitPerf=Il.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(e,n){if(this.traceInitPerf===!0){this.traceInitIndent++;const r=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${e}>`);const{time:i,value:s}=OU(n),o=i>10?console.warn:console.log;return this.traceInitIndent time: ${i}ms`),this.traceInitIndent--,s}else return n()}}function Uce(t,e){e.forEach(n=>{const r=n.prototype;Object.getOwnPropertyNames(r).forEach(i=>{if(i==="constructor")return;const s=Object.getOwnPropertyDescriptor(r,i);s&&(s.get||s.set)?Object.defineProperty(t.prototype,i,s):t.prototype[i]=n.prototype[i]})})}const mv=Im(eh,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(mv);const Il=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:jU,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),gv=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0});var Gi;(function(t){t[t.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",t[t.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",t[t.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",t[t.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",t[t.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",t[t.LEFT_RECURSION=5]="LEFT_RECURSION",t[t.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",t[t.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",t[t.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",t[t.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",t[t.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",t[t.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",t[t.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",t[t.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(Gi||(Gi={}));class Om{static performSelfAnalysis(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let e;this.selfAnalysisDone=!0;const n=this.className;this.TRACE_INIT("toFastProps",()=>{LU(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),bt(this.definedRulesNames,i=>{const o=this[i].originalGrammarAction;let a;this.TRACE_INIT(`${i} Rule`,()=>{a=this.topLevelRuleRecord(i,o)}),this.gastProductionsCache[i]=a})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT("Grammar Resolving",()=>{r=oce({rules:Cr(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT("Grammar Validations",()=>{if(Un(r)&&this.skipValidations===!1){const i=ace({rules:Cr(this.gastProductionsCache),tokenTypes:Cr(this.tokensMap),errMsgProvider:Iu,grammarName:n}),s=jle({lookaheadStrategy:this.lookaheadStrategy,rules:Cr(this.gastProductionsCache),tokenTypes:Cr(this.tokensMap),grammarName:n});this.definitionErrors=this.definitionErrors.concat(i,s)}}),Un(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{const i=Fae(Cr(this.gastProductionsCache));this.resyncFollows=i}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var i,s;(s=(i=this.lookaheadStrategy).initialize)===null||s===void 0||s.call(i,{rules:Cr(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(Cr(this.gastProductionsCache))})),!Om.DEFER_DEFINITION_ERRORS_HANDLING&&!Un(this.definitionErrors))throw e=ot(this.definitionErrors,i=>i.message),new Error(`Parser Definition Errors detected: + ${e.join(` +------------------------------- +`)}`)})}constructor(e,n){this.definitionErrors=[],this.selfAnalysisDone=!1;const r=this;if(r.initErrorHandler(n),r.initLexerAdapter(),r.initLooksAhead(n),r.initRecognizerEngine(e,n),r.initRecoverable(n),r.initTreeBuilder(n),r.initContentAssist(),r.initGastRecorder(n),r.initPerformanceTracer(n),wt(n,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`);this.skipValidations=wt(n,"skipValidations")?n.skipValidations:Il.skipValidations}}Om.DEFER_DEFINITION_ERRORS_HANDLING=!1;Uce(Om,[fce,gce,Mce,Cce,Nce,Rce,kce,Ice,Lce,Dce]);class Fce extends Om{constructor(e,n=Il){const r=hi(n);r.outputCst=!0,super(e,r)}}function Bce(t){const e=new zce,n=Cr(t);return ot(n,r=>e.visitRule(r))}class zce extends ph{visitRule(e){const n=this.visitEach(e.definition),r=NL(n,s=>s.propertyName),i=ot(r,(s,o)=>{const a=!zT(s,c=>!c.canBeNull);let l=s[0].type;return s.length>1&&(l=ot(s,c=>c.type)),{name:o,type:l,optional:a}});return{name:e.name,properties:i}}visitAlternative(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitOption(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetition(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetitionMandatory(e){return this.visitEach(e.definition)}visitRepetitionMandatoryWithSeparator(e){return this.visitEach(e.definition).concat({propertyName:e.separator.name,canBeNull:!0,type:O0(e.separator)})}visitRepetitionWithSeparator(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0}).concat({propertyName:e.separator.name,canBeNull:!0,type:O0(e.separator)})}visitAlternation(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitTerminal(e){return[{propertyName:e.label||e.terminalType.name,canBeNull:!1,type:O0(e)}]}visitNonTerminal(e){return[{propertyName:e.label||e.nonTerminalName,canBeNull:!1,type:O0(e)}]}visitEachAndOverrideWith(e,n){return ot(this.visitEach(e),r=>hs({},r,n))}visitEach(e){return ls(ot(e,n=>this.visit(n)))}}function O0(t){return t instanceof gs?{kind:"rule",name:t.referencedRule.name}:{kind:"token"}}function Vce(t,e){let n=[];return n=n.concat('import type { CstNode, ICstVisitor, IToken } from "chevrotain";'),n=n.concat(ls(ot(t,r=>Hce(r)))),e.includeVisitorInterface&&(n=n.concat($ce(e.visitorInterfaceName,t))),n.join(` + +`)+` +`}function Hce(t){const e=Gce(t),n=Wce(t);return[e,n]}function Gce(t){const e=h3(t.name),n=mA(t.name);return`export interface ${e} extends CstNode { + name: "${t.name}"; + children: ${n}; +}`}function Wce(t){return`export type ${mA(t.name)} = { + ${ot(t.properties,n=>jce(n)).join(` + `)} +};`}function jce(t){const e=Xce(t.type);return`${t.name}${t.optional?"?":""}: ${e}[];`}function $ce(t,e){return`export interface ${t} extends ICstVisitor { + ${ot(e,n=>qce(n)).join(` + `)} +}`}function qce(t){const e=mA(t.name);return`${t.name}(children: ${e}, param?: IN): OUT;`}function Xce(t){if(un(t)){const e=Kv(ot(t,r=>Ik(r)));return"("+ds(e,(r,i)=>r+" | "+i)+")"}else return Ik(t)}function Ik(t){return t.kind==="token"?"IToken":h3(t.name)}function h3(t){return gL(t)+"CstNode"}function mA(t){return gL(t)+"CstChildren"}const Kce={includeVisitorInterface:!0,visitorInterfaceName:"ICstNodeVisitor"};function Yce(t,e){const n=Object.assign(Object.assign({},Kce),e),r=Bce(t);return Vce(r,n)}var f3={exports:{}},v1={exports:{}},Ok;function Zce(){return Ok||(Ok=1,function(t,e){(function(n,r){t.exports=r()})(bo,function(){function n(v){return!isNaN(parseFloat(v))&&isFinite(v)}function r(v){return v.charAt(0).toUpperCase()+v.substring(1)}function i(v){return function(){return this[v]}}var s=["isConstructor","isEval","isNative","isToplevel"],o=["columnNumber","lineNumber"],a=["fileName","functionName","source"],l=["args"],c=["evalOrigin"],u=s.concat(o,a,l,c);function h(v){if(v)for(var y=0;y-1&&(u=u.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var h=u.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),p=h.match(/ (\(.+\)$)/);h=p?h.replace(p[0],""):h;var m=this.extractLocation(p?p[1]:h),g=p&&h||void 0,v=["eval",""].indexOf(m[0])>-1?void 0:m[0];return new r({functionName:g,fileName:v,lineNumber:m[1],columnNumber:m[2],source:u})},this)},parseFFOrSafari:function(l){var c=l.stack.split(` +`).filter(function(u){return!u.match(o)},this);return c.map(function(u){if(u.indexOf(" > eval")>-1&&(u=u.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),u.indexOf("@")===-1&&u.indexOf(":")===-1)return new r({functionName:u});var h=/((.*".+"[^@]*)?[^@]*)(?:@)/,p=u.match(h),m=p&&p[1]?p[1]:void 0,g=this.extractLocation(u.replace(h,""));return new r({functionName:m,fileName:g[0],lineNumber:g[1],columnNumber:g[2],source:u})},this)},parseOpera:function(l){return!l.stacktrace||l.message.indexOf(` +`)>-1&&l.message.split(` +`).length>l.stacktrace.split(` +`).length?this.parseOpera9(l):l.stack?this.parseOpera11(l):this.parseOpera10(l)},parseOpera9:function(l){for(var c=/Line (\d+).*script (?:in )?(\S+)/i,u=l.message.split(` +`),h=[],p=2,m=u.length;p/,"$2").replace(/\([^)]*\)/g,"")||void 0,v;m.match(/\(([^)]*)\)/)&&(v=m.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var y=v===void 0||v==="[arguments not available]"?void 0:v.split(",");return new r({functionName:g,args:y,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:u})},this)}}})})(f3);var Jce=f3.exports;const Qce=Pl(Jce);function Kl(t){const e={},n={get(){return[!1,void 0]},set(){return[!1,void 0]},tick(){},everytick(){},...t,getcommand(r){return e[r]},command(r,i){return e[r]=i,n}};return n}function gl(t){return Z(t)&&Z(t.x)&&Z(t.y)}function Yr(t,e){switch(e){case st.NORTH:--t.y;break;case st.SOUTH:++t.y;break;case st.WEST:--t.x;break;case st.EAST:++t.x;break}return t}function Kh(t,e){const n=e.x-t.x,r=e.y-t.y;if(n<0)return st.WEST;if(n>0)return st.EAST;if(r<0)return st.NORTH;if(r>0)return st.SOUTH}const d3={idle:"IDLE",up:"NORTH",down:"SOUTH",left:"WEST",right:"EAST",by:"BY",at:"AT",flow:"FLOW",seek:"SEEK",rndns:"RNDNS",rndne:"RNDNE",rnd:"RND",cw:"CW",ccw:"CCW",opp:"OPP",rndp:"RNDP",i:"IDLE",u:"NORTH",north:"NORTH",n:"NORTH",d:"SOUTH",south:"SOUTH",s:"SOUTH",l:"WEST",west:"WEST",w:"WEST",r:"EAST",east:"EAST",e:"EAST",edit:"EDIT"};function Sl(t){return ln(t)&&p3(t[0])}function p3(t){return Z(st[t])&&Kt(t)}function eue(t){const e=st[t];return Z(e)?e:st.IDLE}function m3(t){if(Kt(t))return d3[$t(t)]}function Lk(t){if(Sl(t))return t;if(p3(t))return[t];const e=m3(t);if(Z(e))return[e]}function Pk(t){const e=se.words[t],n=Lk(e);if(Sl(n))return[n,t+1];const[r,i]=Ui(t),s=Lk(r);return Sl(s)?[s,i]:[void 0,t]}function bw(t){const e=[];let[n,r]=Pk(t);for(;Sl(n);){if(e.push(...n),(n[0]==="AT"||n[0]==="BY")&&n.length<2){const[o,a,l]=He(se.words,r,[Ie.NUMBER,Ie.NUMBER]);e.push(o,a),r=l}const[i,s]=Pk(r);n=i,r=s}return e.length?[e,r]:[void 0,t]}function Zf(t){return ln(t)&&typeof t[0]=="string"}function Dk(t){const e=se.words[t];if(Zf(e))return[e,t+1];const[n,r]=Ev(t),[i,s]=Ui(r,!1);return Kt(i)?[[i,n],s]:[void 0,t]}function _v(t){if(!Zf(t))return;const[e]=t;return e}function g3(t){if(!Zf(t))return;const[,e]=t,n=Z(e)?Wfe(e):void 0;return Z(n)?n:void 0}function _3(t){if(!Zf(t))return;const[,e]=t,n=Z(e)?jfe(e):void 0;return Z(n)?n:void 0}const ui=60,mh=25;var vn=(t=>(t[t.ERROR=0]="ERROR",t[t.LOADER=1]="LOADER",t[t.BOARD=2]="BOARD",t[t.OBJECT=3]="OBJECT",t[t.TERRAIN=4]="TERRAIN",t[t.CHARSET=5]="CHARSET",t[t.PALETTE=6]="PALETTE",t))(vn||{});function v3(t,e){const n=t??Vn.ISWALK,r=e??Vn.ISWALK;switch(n){case Vn.ISWALK:return r!==Vn.ISWALK;case Vn.ISSWIM:return r!==Vn.ISSWIM;case Vn.ISSOLID:return!0;case Vn.ISBULLET:return r!==Vn.ISWALK&&r!==Vn.ISSWIM}}function Uk(t,e,n){const r=t==null?void 0:t.objects[n];if(Z(r))return r;if(Z(e)){const i=Lm(t,"player"),s={x:e.x??0,y:e.y??0};x3(s,i)}}function Lm(t,e){var r,i;return[...((i=(r=t==null?void 0:t.named)==null?void 0:r[e])==null?void 0:i.values())??[]].map(s=>typeof s=="string"?t==null?void 0:t.objects[s]:t==null?void 0:t.terrain[s]).filter(Z)}function y3(t,e){const n=_v(e),r=g3(e),i=_3(e);return t.filter(s=>!(Z(n)&&wA(s)!==n||Z(r)&&Hue(s)!==r||Z(i)&&Gue(s)!==i)).filter(Z)}function y1(t,e){return Z(t)?e.map(n=>{var r;if(typeof n=="string"){const i=t.objects[n];if(Z(i))return i;const s=Lm(t,$t(n));if(s.length)return s}else if(gl(n)&&n.x>=0&&n.x=0&&n.y=0;r--){const i=t[r];let s=gA[i];s*=n,e+=s,n*=Jf}return e}ci.s_to_int=_A;function E3(t){let e=BigInt(0),n=BigInt(1);const r=BigInt(Jf);for(let i=t.length-1;i>=0;i--){const s=t[i];let o=BigInt(gA[s]);o*=n,e+=o,n*=r}return e}ci.s_to_big_int=E3;function vA(t){if(t===0)return Ol[0];const e=[];for(;t!==0;){const n=t%Jf,r=Ol[n];e.push(r),t-=n,t/=Jf}return e.reverse().join("")}ci.int_to_s=vA;function w3(t){const e=BigInt(0),n=BigInt(Jf);if(t===e)return Ol[0];const r=[];for(;t!==e;){const i=t%n,s=Ol[Number(i)];r.push(s),t/=n}return r.reverse().join("")}ci.big_int_to_s=w3;function T3(t){return t.split("").reverse().join("")}function b3(t){if(t<0)return"-"+b3(-t);let[e,n]=t.toString().split(".");if(!n)return vA(t);let r;n&&([n,r]=n.split("e")),e=x_(e),n=T3(n),n=x_(n);let i=e+"."+n;if(r){switch(i+=".",r[0]){case"+":r=r.slice(1);break;case"-":i+="-",r=r.slice(1);break}r=x_(r),i+=r}return i}ci.num_to_s=b3;function x_(t){const e=+t;return e.toString()===t&&e+1!==e&&e-1!==e?vA(e):":"+w3(BigInt(t))}ci.int_str_to_s=x_;function x1(t){return t[0]===":"?E3(t.substring(1)).toString():_A(t).toString()}function A3(t){if(t[0]==="-")return-A3(t.substr(1));let[e,n,r]=t.split(".");if(!n)return _A(e);e=x1(e),n=x1(n),n=T3(n);let i=e+"."+n;if(r){i+="e";let s=!1;r[0]==="-"&&(s=!0,r=r.slice(1)),r=x1(r),i+=s?-r:+r}return+i}ci.s_to_num=A3;Object.defineProperty(li,"__esModule",{value:!0});li.decodeStr=li.encodeStr=li.decodeBool=li.encodeBool=li.decodeKey=li.decodeNum=li.encodeNum=void 0;const yA=ci;function iue(t){return"n|"+(0,yA.num_to_s)(t)}li.encodeNum=iue;function sue(t){return t=t.replace("n|",""),(0,yA.s_to_num)(t)}li.decodeNum=sue;function oue(t){return typeof t=="number"?t:(0,yA.s_to_int)(t)}li.decodeKey=oue;function aue(t){return t?"b|T":"b|F"}li.encodeBool=aue;function lue(t){switch(t){case"b|T":return!0;case"b|F":return!1}return!!t}li.decodeBool=lue;function cue(t){switch(t[0]+t[1]){case"b|":case"o|":case"n|":case"a|":case"s|":t="s|"+t}return t}li.encodeStr=cue;function uue(t){return t[0]+t[1]==="s|"?t.substr(2):t}li.decodeStr=uue;var Ns={},Pm={};Object.defineProperty(Pm,"__esModule",{value:!0});Pm.config=void 0;Pm.config={sort_key:!1,error_on_nan:!1,error_on_infinite:!1};Object.defineProperty(Ns,"__esModule",{value:!0});Ns.addValue=Ns.makeInMemoryMemory=Ns.makeInMemoryCache=Ns.makeInMemoryStore=Ns.memToValues=void 0;const Aw=Pm,S1=wl,E1=li,hue=ci;function fue(t){return t.store.toArray()}Ns.memToValues=fue;function M3(){const t=[];return{forEach(e){for(let n=0;n(Rw(),this?this.unpack(e,n):Gp.prototype.unpack.call(Fk,e,n)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof n=="object"?(Js=n.end||e.length,ue=n.start||0):(ue=0,Js=n>-1?n:e.length),ma=0,Ec=null,ei=null,We=e;try{en=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw We=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof Gp){if(Ln=this,this.structures)return on=this.structures,P0(n);(!on||on.length>0)&&(on=[])}else Ln=Fk,(!on||on.length>0)&&(on=[]);return P0(n)}unpackMultiple(e,n){let r,i=0;try{Mc=!0;let s=e.length,o=this?this.unpack(e,s):Vy.unpack(e,s);if(n){if(n(o,i,ue)===!1)return;for(;uer.slice(0)));for(let r=0,i=e.length;r=32&&(s.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in n||[])if(r>=0){let i=e[r],s=n[r];s&&(i&&((e.restoreStructures||(e.restoreStructures=[]))[r]=i),e[r]=s)}return this.structures=e}decode(e,n){return this.unpack(e,n)}}function P0(t){try{if(!Ln.trusted&&!Mc){let n=on.sharedLength||0;n=32&&Bk?(e=Bk(We,ue,Js,Ln),We=null,!(t&&t.lazy)&&e&&(e=e.toJSON()),ue=Js):e=mr(),ei&&(ue=ei.postBundlePosition,ei=null),Mc&&(on.restoreStructures=null),ue==Js)on&&on.restoreStructures&&zk(),on=null,We=null,Tl&&(Tl=null);else{if(ue>Js)throw new Error("Unexpected end of MessagePack data");if(!Mc){let n;try{n=JSON.stringify(e,(r,i)=>typeof i=="bigint"?`${i}n`:i).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return e}catch(e){throw on&&on.restoreStructures&&zk(),Rw(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||ue>Js)&&(e.incomplete=!0),e}}function zk(){for(let t in on.restoreStructures)on[t]=on.restoreStructures[t];on.restoreStructures=null}function mr(){let t=We[ue++];if(t<160)if(t<128){if(t<64)return t;{let e=on[t&63]||Ln.getStructures&&O3()[t&63];return e?(e.read||(e.read=xA(e,t&63)),e.read()):t}}else if(t<144)if(t-=128,Ln.mapsAsObjects){let e={};for(let n=0;n=ue)return Ec.slice(ue-qs,(ue+=e)-qs);if(ma==0&&Js<140){let n=e<16?SA(e):L3(e);if(n!=null)return n}return Cw(e)}else{let e;switch(t){case 192:return null;case 193:return ei?(e=mr(),e>0?ei[1].slice(ei.position1,ei.position1+=e):ei[0].slice(ei.position0,ei.position0-=e)):k3;case 194:return!1;case 195:return!0;case 196:if(e=We[ue++],e===void 0)throw new Error("Unexpected end of buffer");return T1(e);case 197:return e=en.getUint16(ue),ue+=2,T1(e);case 198:return e=en.getUint32(ue),ue+=4,T1(e);case 199:return gu(We[ue++]);case 200:return e=en.getUint16(ue),ue+=2,gu(e);case 201:return e=en.getUint32(ue),ue+=4,gu(e);case 202:if(e=en.getFloat32(ue),Ln.useFloat32>2){let n=EA[(We[ue]&127)<<1|We[ue+1]>>7];return ue+=4,(n*e+(e>0?.5:-.5)>>0)/n}return ue+=4,e;case 203:return e=en.getFloat64(ue),ue+=8,e;case 204:return We[ue++];case 205:return e=en.getUint16(ue),ue+=2,e;case 206:return e=en.getUint32(ue),ue+=4,e;case 207:return Ln.int64AsType==="number"?(e=en.getUint32(ue)*4294967296,e+=en.getUint32(ue+4)):Ln.int64AsType==="string"?e=en.getBigUint64(ue).toString():Ln.int64AsType==="auto"?(e=en.getBigUint64(ue),e<=BigInt(2)<=BigInt(-2)<=ue?Ec.slice(ue-qs,(ue+=e)-qs):wue(e);case 218:return e=en.getUint16(ue),ue+=2,ma>=ue?Ec.slice(ue-qs,(ue+=e)-qs):Tue(e);case 219:return e=en.getUint32(ue),ue+=4,ma>=ue?Ec.slice(ue-qs,(ue+=e)-qs):bue(e);case 220:return e=en.getUint16(ue),ue+=2,Hk(e);case 221:return e=en.getUint32(ue),ue+=4,Hk(e);case 222:return e=en.getUint16(ue),ue+=2,Gk(e);case 223:return e=en.getUint32(ue),ue+=4,Gk(e);default:if(t>=224)return t-256;if(t===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+t)}}}const Eue=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function xA(t,e){function n(){if(n.count++>I3){let i=t.read=new Function("r","return function(){return "+(Ln.freezeData?"Object.freeze":"")+"({"+t.map(s=>s==="__proto__"?"__proto_:r()":Eue.test(s)?s+":r()":"["+JSON.stringify(s)+"]:r()").join(",")+"})}")(mr);return t.highByte===0&&(t.read=Vk(e,t.read)),i()}let r={};for(let i=0,s=t.length;ifunction(){let n=We[ue++];if(n===0)return e();let r=t<32?-(t+(n<<5)):t+(n<<5),i=on[r]||O3()[r];if(!i)throw new Error("Record id is not defined for "+r);return i.read||(i.read=xA(i,t)),i.read()};function O3(){let t=F3(()=>(We=null,Ln.getStructures()));return on=Ln._mergeStructures(t,on)}var Cw=Dm,wue=Dm,Tue=Dm,bue=Dm;function Dm(t){let e;if(t<16&&(e=SA(t)))return e;if(t>64&&Mw)return Mw.decode(We.subarray(ue,ue+=t));const n=ue+t,r=[];for(e="";ue65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|l&1023),r.push(l)}else r.push(i);r.length>=4096&&(e+=Jr.apply(String,r),r.length=0)}return r.length>0&&(e+=Jr.apply(String,r)),e}function Hk(t){let e=new Array(t);for(let n=0;n0){ue=e;return}n[r]=i}return Jr.apply(String,n)}function SA(t){if(t<4)if(t<2){if(t===0)return"";{let e=We[ue++];if((e&128)>1){ue-=1;return}return Jr(e)}}else{let e=We[ue++],n=We[ue++];if((e&128)>0||(n&128)>0){ue-=2;return}if(t<3)return Jr(e,n);let r=We[ue++];if((r&128)>0){ue-=3;return}return Jr(e,n,r)}else{let e=We[ue++],n=We[ue++],r=We[ue++],i=We[ue++];if((e&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){ue-=4;return}if(t<6){if(t===4)return Jr(e,n,r,i);{let s=We[ue++];if((s&128)>0){ue-=5;return}return Jr(e,n,r,i,s)}}else if(t<8){let s=We[ue++],o=We[ue++];if((s&128)>0||(o&128)>0){ue-=6;return}if(t<7)return Jr(e,n,r,i,s,o);let a=We[ue++];if((a&128)>0){ue-=7;return}return Jr(e,n,r,i,s,o,a)}else{let s=We[ue++],o=We[ue++],a=We[ue++],l=We[ue++];if((s&128)>0||(o&128)>0||(a&128)>0||(l&128)>0){ue-=8;return}if(t<10){if(t===8)return Jr(e,n,r,i,s,o,a,l);{let c=We[ue++];if((c&128)>0){ue-=9;return}return Jr(e,n,r,i,s,o,a,l,c)}}else if(t<12){let c=We[ue++],u=We[ue++];if((c&128)>0||(u&128)>0){ue-=10;return}if(t<11)return Jr(e,n,r,i,s,o,a,l,c,u);let h=We[ue++];if((h&128)>0){ue-=11;return}return Jr(e,n,r,i,s,o,a,l,c,u,h)}else{let c=We[ue++],u=We[ue++],h=We[ue++],p=We[ue++];if((c&128)>0||(u&128)>0||(h&128)>0||(p&128)>0){ue-=12;return}if(t<14){if(t===12)return Jr(e,n,r,i,s,o,a,l,c,u,h,p);{let m=We[ue++];if((m&128)>0){ue-=13;return}return Jr(e,n,r,i,s,o,a,l,c,u,h,p,m)}}else{let m=We[ue++],g=We[ue++];if((m&128)>0||(g&128)>0){ue-=14;return}if(t<15)return Jr(e,n,r,i,s,o,a,l,c,u,h,p,m,g);let v=We[ue++];if((v&128)>0){ue-=15;return}return Jr(e,n,r,i,s,o,a,l,c,u,h,p,m,g,v)}}}}}function Wk(){let t=We[ue++],e;if(t<192)e=t-160;else switch(t){case 217:e=We[ue++];break;case 218:e=en.getUint16(ue),ue+=2;break;case 219:e=en.getUint32(ue),ue+=4;break;default:throw new Error("Expected string")}return Dm(e)}function T1(t){return Ln.copyBuffers?Uint8Array.prototype.slice.call(We,ue,ue+=t):We.subarray(ue,ue+=t)}function gu(t){let e=We[ue++];if(vs[e]){let n;return vs[e](We.subarray(ue,n=ue+=t),r=>{ue=r;try{return mr()}finally{ue=n}})}else throw new Error("Unknown extension type "+e)}var jk=new Array(4096);function P3(){let t=We[ue++];if(t>=160&&t<192){if(t=t-160,ma>=ue)return Ec.slice(ue-qs,(ue+=t)-qs);if(!(ma==0&&Js<180))return Cw(t)}else return ue--,D3(mr());let e=(t<<5^(t>1?en.getUint16(ue):t>0?We[ue]:0))&4095,n=jk[e],r=ue,i=ue+t-3,s,o=0;if(n&&n.bytes==t){for(;r{let n=mr().map(D3),r=t;e!==void 0&&(t=t<32?-((e<<5)+t):(e<<5)+t,n.highByte=e);let i=on[t];return i&&(i.isShared||Mc)&&((on.restoreStructures||(on.restoreStructures=[]))[t]=i),on[t]=n,n.read=xA(n,r),n.read()};vs[0]=()=>{};vs[0].noBuffer=!0;vs[66]=t=>{let e=t.length,n=BigInt(t[0]&128?t[0]-256:t[0]);for(let r=1;r{let t=mr();return(Aue[t[0]]||Error)(t[1],{cause:t[2]})};vs[105]=t=>{if(Ln.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=en.getUint32(ue-4);Tl||(Tl=new Map);let n=We[ue],r;n>=144&&n<160||n==220||n==221?r=[]:r={};let i={target:r};Tl.set(e,i);let s=mr();return i.used?Object.assign(r,s):(i.target=s,s)};vs[112]=t=>{if(Ln.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=en.getUint32(ue-4),n=Tl.get(e);return n.used=!0,n.target};vs[115]=()=>new Set(mr());const U3=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(t=>t+"Array");let Mue=typeof globalThis=="object"?globalThis:window;vs[116]=t=>{let e=t[0],n=U3[e];if(!n){if(e===16){let r=new ArrayBuffer(t.length-1);return new Uint8Array(r).set(t.subarray(1)),r}throw new Error("Could not find typed array for code "+e)}return new Mue[n](Uint8Array.prototype.slice.call(t,1).buffer)};vs[120]=()=>{let t=mr();return new RegExp(t[0],t[1])};const Cue=[];vs[98]=t=>{let e=(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3],n=ue;return ue+=e-t.length,ei=Cue,ei=[Wk(),Wk()],ei.position0=0,ei.position1=0,ei.postBundlePosition=ue,ue=n,mr()};vs[255]=t=>t.length==4?new Date((t[0]*16777216+(t[1]<<16)+(t[2]<<8)+t[3])*1e3):t.length==8?new Date(((t[0]<<22)+(t[1]<<14)+(t[2]<<6)+(t[3]>>2))/1e6+((t[3]&3)*4294967296+t[4]*16777216+(t[5]<<16)+(t[6]<<8)+t[7])*1e3):t.length==12?new Date(((t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3])/1e6+((t[4]&128?-281474976710656:0)+t[6]*1099511627776+t[7]*4294967296+t[8]*16777216+(t[9]<<16)+(t[10]<<8)+t[11])*1e3):new Date("invalid");function F3(t){let e=Js,n=ue,r=qs,i=ma,s=Ec,o=Tl,a=ei,l=new Uint8Array(We.slice(0,Js)),c=on,u=on.slice(0,on.length),h=Ln,p=Mc,m=t();return Js=e,ue=n,qs=r,ma=i,Ec=s,Tl=o,ei=a,We=l,Mc=p,on=c,on.splice(0,on.length,...u),Ln=h,en=new DataView(We.buffer,We.byteOffset,We.byteLength),m}function Rw(){We=null,Tl=null,on=null}const EA=new Array(147);for(let t=0;t<256;t++)EA[t]=+("1e"+Math.floor(45.15-t*.30103));var Vy=new Gp({useRecords:!1});Vy.unpack;Vy.unpackMultiple;Vy.unpack;let Rue=new Float32Array(1);new Uint8Array(Rue.buffer,0,4);let S_;try{S_=new TextEncoder}catch{}let Nw,B3;const Hy=typeof Buffer<"u",D0=Hy?function(t){return Buffer.allocUnsafeSlow(t)}:Uint8Array,z3=Hy?Buffer:Uint8Array,qk=Hy?4294967296:2144337920;let ye,Xd,kn,pe=0,Ri,Zn=null,Nue;const kue=21760,Iue=/[\u0080-\uFFFF]/,Yh=Symbol("record-id");class Oue extends Gp{constructor(e){super(e),this.offset=0;let n,r,i,s,o=z3.prototype.utf8Write?function(P,b){return ye.utf8Write(P,b,ye.byteLength-b)}:S_&&S_.encodeInto?function(P,b){return S_.encodeInto(P,ye.subarray(b)).written}:!1,a=this;e||(e={});let l=e&&e.sequential,c=e.structures||e.saveStructures,u=e.maxSharedStructures;if(u==null&&(u=c?32:0),u>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let h=e.maxOwnStructures;h==null&&(h=c?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let p=u>32||h+u>64,m=u+64,g=u+h+64;if(g>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let v=[],y=0,_=0;this.pack=this.encode=function(P,b){if(ye||(ye=new D0(8192),kn=ye.dataView||(ye.dataView=new DataView(ye.buffer,0,8192)),pe=0),Ri=ye.length-10,Ri-pe<2048?(ye=new D0(ye.length),kn=ye.dataView||(ye.dataView=new DataView(ye.buffer,0,ye.length)),Ri=ye.length-10,pe=0):pe=pe+7&2147483640,n=pe,b&Bue&&(pe+=b&255),s=a.structuredClone?new Map:null,a.bundleStrings&&typeof P!="string"?(Zn=[],Zn.size=1/0):Zn=null,i=a.structures,i){i.uninitialized&&(i=a._mergeStructures(a.getStructures()));let V=i.sharedLength||0;if(V>u)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let B=0;Bj.offset>Y.offset?1:-1),z=B.length,W=-1;for(;V&&z>0;){let j=B[--z].offset+n;jV.position+n?W>=0&&(W+=6):(W>=0&&(kn.setUint32(V.position+n,kn.getUint32(V.position+n)+W),W=-1),V=V.previous,z++)}W>=0&&V&&kn.setUint32(V.position+n,kn.getUint32(V.position+n)+W),pe+=B.length*6,pe>Ri&&M(pe),a.offset=pe;let K=Pue(ye.subarray(n,pe),B);return s=null,K}return a.offset=pe,b&Uue?(ye.start=n,ye.end=pe,ye):ye.subarray(n,pe)}catch(V){throw H=V,V}finally{if(i&&(S(),r&&a.saveStructures)){let V=i.sharedLength||0,B=ye.subarray(n,pe),z=Due(i,a);if(!H)return a.saveStructures(z,z.isCompatible)===!1?a.pack(P,b):(a.lastNamedStructuresLength=V,ye.length>1073741824&&(ye=null),B)}ye.length>1073741824&&(ye=null),b&Fue&&(pe=n)}};const S=()=>{_<10&&_++;let P=i.sharedLength||0;if(i.length>P&&!l&&(i.length=P),y>1e4)i.transitions=null,_=0,y=0,v.length>0&&(v=[]);else if(v.length>0&&!l){for(let b=0,H=v.length;b{var b=P.length;b<16?ye[pe++]=144|b:b<65536?(ye[pe++]=220,ye[pe++]=b>>8,ye[pe++]=b&255):(ye[pe++]=221,kn.setUint32(pe,b),pe+=4);for(let H=0;H{pe>Ri&&(ye=M(pe));var b=typeof P,H;if(b==="string"){let V=P.length;if(Zn&&V>=4&&V<4096){if((Zn.size+=V)>kue){let K,j=(Zn[0]?Zn[0].length*3+Zn[1].length:0)+10;pe+j>Ri&&(ye=M(pe+j));let Y;Zn.position?(Y=Zn,ye[pe]=200,pe+=3,ye[pe++]=98,K=pe-n,pe+=4,Yk(n,T,0),kn.setUint16(K+n-3,pe-n-K)):(ye[pe++]=214,ye[pe++]=98,K=pe-n,pe+=4),Zn=["",""],Zn.previous=Y,Zn.size=0,Zn.position=K}let W=Iue.test(P);Zn[W?0:1]+=P,ye[pe++]=193,T(W?-V:V);return}let B;V<32?B=1:V<256?B=2:V<65536?B=3:B=5;let z=V*3;if(pe+z>Ri&&(ye=M(pe+z)),V<64||!o){let W,K,j,Y=pe+B;for(W=0;W>6|192,ye[Y++]=K&63|128):(K&64512)===55296&&((j=P.charCodeAt(W+1))&64512)===56320?(K=65536+((K&1023)<<10)+(j&1023),W++,ye[Y++]=K>>18|240,ye[Y++]=K>>12&63|128,ye[Y++]=K>>6&63|128,ye[Y++]=K&63|128):(ye[Y++]=K>>12|224,ye[Y++]=K>>6&63|128,ye[Y++]=K&63|128);H=Y-pe-B}else H=o(P,pe+B);H<32?ye[pe++]=160|H:H<256?(B<2&&ye.copyWithin(pe+2,pe+1,pe+1+H),ye[pe++]=217,ye[pe++]=H):H<65536?(B<3&&ye.copyWithin(pe+3,pe+2,pe+2+H),ye[pe++]=218,ye[pe++]=H>>8,ye[pe++]=H&255):(B<5&&ye.copyWithin(pe+5,pe+3,pe+3+H),ye[pe++]=219,kn.setUint32(pe,H),pe+=4),pe+=H}else if(b==="number")if(P>>>0===P)P<32||P<128&&this.useRecords===!1||P<64&&!this.randomAccessStructure?ye[pe++]=P:P<256?(ye[pe++]=204,ye[pe++]=P):P<65536?(ye[pe++]=205,ye[pe++]=P>>8,ye[pe++]=P&255):(ye[pe++]=206,kn.setUint32(pe,P),pe+=4);else if(P>>0===P)P>=-32?ye[pe++]=256+P:P>=-128?(ye[pe++]=208,ye[pe++]=P+256):P>=-32768?(ye[pe++]=209,kn.setInt16(pe,P),pe+=2):(ye[pe++]=210,kn.setInt32(pe,P),pe+=4);else{let V;if((V=this.useFloat32)>0&&P<4294967296&&P>=-2147483648){ye[pe++]=202,kn.setFloat32(pe,P);let B;if(V<4||(B=P*EA[(ye[pe]&127)<<1|ye[pe+1]>>7])>>0===B){pe+=4;return}else pe--}ye[pe++]=203,kn.setFloat64(pe,P),pe+=8}else if(b==="object"||b==="function")if(!P)ye[pe++]=192;else{if(s){let B=s.get(P);if(B){if(!B.id){let z=s.idsToInsert||(s.idsToInsert=[]);B.id=z.push(B)}ye[pe++]=214,ye[pe++]=112,kn.setUint32(pe,B.id),pe+=4;return}else s.set(P,{offset:pe-n})}let V=P.constructor;if(V===Object)O(P);else if(V===Array)E(P);else if(V===Map)if(this.mapAsEmptyObject)ye[pe++]=128;else{H=P.size,H<16?ye[pe++]=128|H:H<65536?(ye[pe++]=222,ye[pe++]=H>>8,ye[pe++]=H&255):(ye[pe++]=223,kn.setUint32(pe,H),pe+=4);for(let[B,z]of P)T(B),T(z)}else{for(let B=0,z=Nw.length;B(ye=j,j=null,pe+=re,pe>Ri&&M(pe),{target:ye,targetView:kn,position:pe-re}),T)}finally{j&&(ye=j,kn=Y,pe=ge,Ri=ye.length-10)}Q&&(Q.length+pe>Ri&&M(Q.length+pe),pe=Lue(Q,ye,pe,K.type));return}}if(Array.isArray(P))E(P);else{if(P.toJSON){const B=P.toJSON();if(B!==P)return T(B)}if(b==="function")return T(this.writeFunction&&this.writeFunction(P));O(P)}}}else if(b==="boolean")ye[pe++]=P?195:194;else if(b==="bigint"){if(P=-(BigInt(1)<0)ye[pe++]=207,kn.setBigUint64(pe,P);else if(this.largeBigIntToFloat)ye[pe++]=203,kn.setFloat64(pe,Number(P));else{if(this.largeBigIntToString)return T(P.toString());if(this.useBigIntExtension&&P-(BigInt(2)**BigInt(1023))){ye[pe++]=199,pe++,ye[pe++]=66;let V=[],B;do{let z=P&BigInt(255);B=(z&BigInt(128))===(P>=BigInt(8)}while(!((P===BigInt(0)||P===BigInt(-1))&&B));ye[pe-2]=V.length;for(let z=V.length;z>0;)ye[pe++]=Number(V[--z]);return}else throw new RangeError(P+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}pe+=8}else if(b==="undefined")this.encodeUndefinedAsNil?ye[pe++]=192:(ye[pe++]=212,ye[pe++]=0,ye[pe++]=0);else throw new Error("Unknown type: "+b)},N=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?P=>{let b;if(this.skipValues){b=[];for(let B in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(B))&&!this.skipValues.includes(P[B])&&b.push(B)}else b=Object.keys(P);let H=b.length;H<16?ye[pe++]=128|H:H<65536?(ye[pe++]=222,ye[pe++]=H>>8,ye[pe++]=H&255):(ye[pe++]=223,kn.setUint32(pe,H),pe+=4);let V;if(this.coercibleKeyAsNumber)for(let B=0;B{ye[pe++]=222;let b=pe-n;pe+=2;let H=0;for(let V in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(V))&&(T(V),T(P[V]),H++);if(H>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');ye[b+++n]=H>>8,ye[b+n]=H&255},R=this.useRecords===!1?N:e.progressiveRecords&&!p?P=>{let b,H=i.transitions||(i.transitions=Object.create(null)),V=pe++-n,B;for(let z in P)if(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(z)){if(b=H[z],b)H=b;else{let W=Object.keys(P),K=H;H=i.transitions;let j=0;for(let Y=0,ge=W.length;Y{let b,H=i.transitions||(i.transitions=Object.create(null)),V=0;for(let z in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(z))&&(b=H[z],b||(b=H[z]=Object.create(null),V++),H=b);let B=H[Yh];B?B>=96&&p?(ye[pe++]=((B-=96)&31)+96,ye[pe++]=B>>5):ye[pe++]=B:I(H,H.__keys__||Object.keys(P),V);for(let z in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(z))&&T(P[z])},C=typeof this.useRecords=="function"&&this.useRecords,O=C?P=>{C(P)?R(P):N(P)}:R,M=P=>{let b;if(P>16777216){if(P-n>qk)throw new Error("Packed buffer would be larger than maximum buffer size");b=Math.min(qk,Math.round(Math.max((P-n)*(P>67108864?1.25:2),4194304)/4096)*4096)}else b=(Math.max(P-n<<2,ye.length-1)>>12)+1<<12;let H=new D0(b);return kn=H.dataView||(H.dataView=new DataView(H.buffer,0,b)),P=Math.min(P,ye.length),ye.copy?ye.copy(H,0,n,P):H.set(ye.slice(n,P)),pe-=n,n=0,Ri=H.length-10,ye=H},I=(P,b,H)=>{let V=i.nextId;V||(V=64),V=g&&(V=m),i.nextId=V+1);let B=b.highByte=V>=96&&p?V-96>>5:-1;P[Yh]=V,P.__keys__=b,i[V-64]=b,V=0?(ye[pe++]=(V&31)+96,ye[pe++]=B):ye[pe++]=V):(B>=0?(ye[pe++]=213,ye[pe++]=114,ye[pe++]=(V&31)+96,ye[pe++]=B):(ye[pe++]=212,ye[pe++]=114,ye[pe++]=V),H&&(y+=_*H),v.length>=h&&(v.shift()[Yh]=0),v.push(P),T(b))},U=(P,b,H,V)=>{let B=ye,z=pe,W=Ri,K=n;ye=Xd,pe=0,n=0,ye||(Xd=ye=new D0(8192)),Ri=ye.length-10,I(P,b,V),Xd=ye;let j=pe;if(ye=B,pe=z,Ri=W,n=K,j>1){let Y=pe+j-1;Y>Ri&&M(Y);let ge=H+n;ye.copyWithin(ge+j,ge+1,pe),ye.set(Xd.slice(0,j),ge),pe=Y}else ye[H+n]=Xd[0]},L=P=>{let b=Nue(P,ye,n,pe,i,M,(H,V,B)=>{if(B)return r=!0;pe=V;let z=ye;return T(H),S(),z!==ye?{position:pe,targetView:kn,target:ye}:pe},this);if(b===0)return O(P);pe=b}}useBuffer(e){ye=e,ye.dataView||(ye.dataView=new DataView(ye.buffer,ye.byteOffset,ye.byteLength)),pe=0}set position(e){pe=e}get position(){return pe}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}}B3=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,N3];Nw=[{pack(t,e,n){let r=t.getTime()/1e3;if((this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:i,targetView:s,position:o}=e(6);i[o++]=214,i[o++]=255,s.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:i,targetView:s,position:o}=e(10);i[o++]=215,i[o++]=255,s.setUint32(o,t.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),s.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),n(this.onInvalidDate());let{target:i,targetView:s,position:o}=e(3);i[o++]=212,i[o++]=255,i[o++]=255}else{let{target:i,targetView:s,position:o}=e(15);i[o++]=199,i[o++]=12,i[o++]=255,s.setUint32(o,t.getMilliseconds()*1e6),s.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(t,e,n){if(this.setAsEmptyObject)return e(0),n({});let r=Array.from(t),{target:i,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(i[s++]=212,i[s++]=115,i[s++]=0),n(r)}},{pack(t,e,n){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),n([t.name,t.message,t.cause])}},{pack(t,e,n){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),n([t.source,t.flags])}},{pack(t,e){this.moreTypes?Xk(t,16,e):Kk(Hy?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let n=t.constructor;n!==z3&&this.moreTypes?Xk(t,U3.indexOf(n.name),e):Kk(t,e)}},{pack(t,e){let{target:n,position:r}=e(1);n[r]=193}}];function Xk(t,e,n,r){let i=t.byteLength;if(i+1<256){var{target:s,position:o}=n(4+i);s[o++]=199,s[o++]=i+1}else if(i+1<65536){var{target:s,position:o}=n(5+i);s[o++]=200,s[o++]=i+1>>8,s[o++]=i+1&255}else{var{target:s,position:o,targetView:a}=n(7+i);s[o++]=201,a.setUint32(o,i+1),o+=4}s[o++]=116,s[o++]=e,t.buffer||(t=new Uint8Array(t)),s.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o)}function Kk(t,e){let n=t.byteLength;var r,i;if(n<256){var{target:r,position:i}=e(n+2);r[i++]=196,r[i++]=n}else if(n<65536){var{target:r,position:i}=e(n+3);r[i++]=197,r[i++]=n>>8,r[i++]=n&255}else{var{target:r,position:i,targetView:s}=e(n+5);r[i++]=198,s.setUint32(i,n),i+=4}r.set(t,i)}function Lue(t,e,n,r){let i=t.length;switch(i){case 1:e[n++]=212;break;case 2:e[n++]=213;break;case 4:e[n++]=214;break;case 8:e[n++]=215;break;case 16:e[n++]=216;break;default:i<256?(e[n++]=199,e[n++]=i):i<65536?(e[n++]=200,e[n++]=i>>8,e[n++]=i&255):(e[n++]=201,e[n++]=i>>24,e[n++]=i>>16&255,e[n++]=i>>8&255,e[n++]=i&255)}return e[n++]=r,e.set(t,n),n+=i,n}function Pue(t,e){let n,r=e.length*6,i=t.length-r;for(;n=e.pop();){let s=n.offset,o=n.id;t.copyWithin(s+r,s,i),r-=6;let a=s+r;t[a++]=214,t[a++]=105,t[a++]=o>>24,t[a++]=o>>16&255,t[a++]=o>>8&255,t[a++]=o&255,i=s}return t}function Yk(t,e,n){if(Zn.length>0){kn.setUint32(Zn.position+t,pe+n-Zn.position-t),Zn.stringsPosition=pe-t;let r=Zn;Zn=null,e(r[0]),e(r[1])}}function Due(t,e){return t.isCompatible=n=>{let r=!n||(e.lastNamedStructuresLength||0)===n.length;return r||e._mergeStructures(n),r},t}let V3=new Oue({useRecords:!1});V3.pack;V3.pack;const Uue=512,Fue=1024,Bue=2048;function Zk(){return{id:fr()}}function zue(){return new Array(ui*mh).map(()=>{})}function Vue(t=aW){const e={terrain:zue(),objects:{},id:""};return t(e)}function wA(t){var e;return $t((t==null?void 0:t.name)??((e=t==null?void 0:t.kinddata)==null?void 0:e.name)??"object")}function Hue(t){var e;return(t==null?void 0:t.color)??((e=t==null?void 0:t.kinddata)==null?void 0:e.color)??wn.BLACK}function Gue(t){var e;return(t==null?void 0:t.bg)??((e=t==null?void 0:t.kinddata)==null?void 0:e.bg)??wn.BLACK}function vv(t,e){if(!Z(t)||!io(e))return;const{color:n,bg:r}=$fe(e);Z(n)&&(t.color=n),Z(r)&&(t.bg=r)}function Wue(t,e){if(!Z(t)||!Z(e)||!Z(e.x)||!Z(e.y)||e.x<0||e.x>=ui||e.y<0||e.y>=mh)return;const n={...e},r=e.x+e.y*ui;return t.terrain[r]=n,e}function jue(t,e){if(!Z(t)||!Z(e))return;const n={...e,id:e.id??fr()};return t.objects[n.id]=n,n}function H3(t,e,n){return Wue(t,{...e,kind:n})}function G3(t,e,n,r){return jue(t,{...e,id:void 0,kind:n})}function yv(t,e){if(t)return t.objects[e]}function kw(t,e,n,r,i){if(!Z(t)||!Z(e))return{x:0,y:0};const s={x:e.x??0,y:e.y??0},o={x:e.lx??s.x,y:e.ly??s.y},a=Kh(o,s),l=ui-1,c=mh-1;for(let u=0;u(t[t.CATEGORY=0]="CATEGORY",t[t.COLLISION=1]="COLLISION",t[t.COLOR=2]="COLOR",t[t.KIND=3]="KIND",t[t.DIR=4]="DIR",t[t.NUMBER=5]="NUMBER",t[t.STRING=6]="STRING",t[t.NUMBER_OR_STRING=7]="NUMBER_OR_STRING",t[t.MAYBE_CATEGORY=8]="MAYBE_CATEGORY",t[t.MAYBE_COLLISION=9]="MAYBE_COLLISION",t[t.MAYBE_COLOR=10]="MAYBE_COLOR",t[t.MAYBE_KIND=11]="MAYBE_KIND",t[t.MAYBE_DIR=12]="MAYBE_DIR",t[t.MAYBE_NUMBER=13]="MAYBE_NUMBER",t[t.MAYBE_STRING=14]="MAYBE_STRING",t[t.MAYBE_NUMBER_OR_STRING=15]="MAYBE_NUMBER_OR_STRING",t[t.ANY=16]="ANY",t))(Ie||{});function Zr(t,e){throw new Error(`Invalid arg, expected: ${t} but got ${JSON.stringify(e)}`)}function He(t,e,n){var o,a,l,c;const r=se.words;se.words=t;const i=[];let s=e;for(let u=0;u(Qk(1,t,e),0)).command("synth",(t,e)=>{for(let n=1;n<=8;++n)sa(n,e);return 0}).command("synth1",(t,e)=>(sa(1,e),0)).command("synth2",(t,e)=>(sa(2,e),0)).command("synth3",(t,e)=>(sa(3,e),0)).command("synth4",(t,e)=>(sa(4,e),0)).command("synth5",(t,e)=>(sa(5,e),0)).command("synth6",(t,e)=>(sa(6,e),0)).command("synth7",(t,e)=>(sa(7,e),0)).command("synth8",(t,e)=>(sa(8,e),0)).command("bgplay",(t,e)=>(Qk(0,t,e),0)).command("bgsynth",(t,e)=>(sa(0,e),0)).command("tts",(t,e)=>{const[n,r]=He(e,0,[Ie.STRING,Ie.MAYBE_STRING]);return kW("audio",r??"",n),0}),TA=ky(32,126).map(t=>String.fromCharCode(t));function tn(t){return Ds({...t,name:`token_${t.name}`})}function ho(t,e=!1){return tn(e?{name:t,pattern:new RegExp(t.toLowerCase(),"i"),longer_alt:Wi,group:Br.SKIPPED}:{name:t,pattern:new RegExp(t.toLowerCase(),"i"),longer_alt:Wi})}const Wp=tn({name:"newline",line_breaks:!0,start_chars_hint:[` +`,"\r"],pattern:/\n|\r\n?/}),Yue=tn({name:"whitespace",pattern:/ +/,group:Br.SKIPPED}),Zue=tn({name:"whitespace",pattern:/\s+/,line_breaks:!0,group:Br.SKIPPED}),bA=tn({name:"stat",pattern:/@.*/,start_chars_hint:["@"]}),sf=tn({name:"command",pattern:/#/,start_chars_hint:["#"]});let K3=!1;function Jue(t,e,n){if(!K3)return null;const[r]=n.slice(-1);if(r&&r.tokenType!==Wp)return null;let i=e;for(;t[i]===" ";)i++;if("@#/?':!".includes(t[i]))return null;let s=e+1;for(;s"@#/?':!".includes(t)===!1)}),Z3=tn({name:"comment",pattern:/'.*/,start_chars_hint:["'"]}),J3=tn({name:"label",pattern:/:[^;:\n]*/,start_chars_hint:[":"]}),Q3=tn({name:"hyperlink",pattern:/!/,start_chars_hint:["!"]}),e4=tn({name:"hyperlinktext",pattern:/;[^;\n]*/,start_chars_hint:[";"]}),Wi=tn({name:"stringliteral",pattern:/[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/,start_chars_hint:TA}),t4=tn({name:"stringliteraldouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),n4=tn({name:"numberliteral",pattern:/-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?/}),r4=tn({name:"iseq",pattern:/=|is|eq|equal/,longer_alt:Wi}),i4=tn({name:"isnoteq",pattern:/!=|not ?eq|not ?equal/,longer_alt:Wi}),s4=tn({name:"islessthan",pattern:/<|below/,longer_alt:Wi}),o4=tn({name:"isgreaterthan",pattern:/>|above/,longer_alt:Wi}),a4=tn({name:"islessthanorequal",pattern:/<=|below ?or ?eq|below ?or ?equal/,longer_alt:Wi}),l4=tn({name:"isgreaterthanorequal",pattern:/>=|above ?or ?eq|above ?or ?equal/,longer_alt:Wi}),Ow=tn({name:"or",pattern:/or/i,longer_alt:Wi}),Lw=tn({name:"not",pattern:/not/i,longer_alt:Wi}),Pw=tn({name:"and",pattern:/and/i,longer_alt:Wi}),Dw=tn({name:"plus",pattern:/\+/}),Uw=tn({name:"minus",pattern:/-/}),c4=tn({name:"power",pattern:/\*\*/}),u4=tn({name:"multiply",pattern:/\*/}),Fw=tn({name:"divide",pattern:/\//}),h4=tn({name:"moddivide",pattern:/%/}),f4=tn({name:"floordivide",pattern:/%%/}),d4=tn({name:"query",pattern:/\?/}),p4=tn({name:"lparen",pattern:/\(/,push_mode:"ignore_newlines"}),m4=tn({name:"rparen",pattern:/\)/,pop_mode:!0}),g4=tn({name:"command_play",pattern:/(play|bgplay) .*/,start_chars_hint:TA,longer_alt:Wi}),_4=ho("debugger"),Bw=ho("if"),w_=ho("do"),Que=ho("to",!0),zw=ho("done"),ehe=ho("then",!0),Vw=ho("else"),v4=ho("while"),y4=ho("repeat"),x4=ho("waitfor"),S4=tn({name:"foreach",pattern:/foreach|for/,longer_alt:Wi}),E4=ho("break"),w4=ho("continue");function T4(t){return[...t,n4,r4,i4,a4,s4,l4,o4,Ow,Lw,Pw,Dw,Uw,c4,u4,Fw,f4,h4,d4,p4,m4,t4,Wi]}const b4=T4([Y3,bA,g4,sf,Z3,J3,Q3,e4,Wp,Yue,E4,w4,_4,zw,w_,Vw,S4,Bw,y4,ehe,Que,x4,v4]),the=new Br({defaultMode:"use_newlines",modes:{use_newlines:b4,ignore_newlines:T4([Zue])}},{skipValidations:!Ca,ensureOptimizations:Ca});function A4(t){K3=!0;const e=the.tokenize(t||` +`),[n]=(ln(e.tokens)?e.tokens:[]).slice(-1);return n&&n.tokenType.name!=="Newline"&&e.tokens.push(Im(Wp,` +`,n.startOffset,n.endOffset??NaN,n.startLine??NaN,n.endLine??NaN,n.startColumn??NaN,n.endColumn??NaN)),e}function M4(t,e=!0){const[n,...r]=t;switch($t(n)){default:return e?{type:dt.OBJECT,values:t}:{type:dt.CONST,values:t};case"loader":return{type:dt.LOADER,values:r};case"board":return{type:dt.BOARD,values:r};case"object":return{type:dt.OBJECT,values:r};case"terrain":return{type:dt.TERRAIN,values:r};case"charset":return{type:dt.CHARSET,values:r};case"palette":return{type:dt.PALETTE,values:r};case"rn":case"range":return{type:dt.RANGE,values:r};case"sl":case"select":return{type:dt.SELECT,values:r};case"nm":case"number":return{type:dt.NUMBER,values:r};case"tx":case"text":return{type:dt.TEXT,values:r};case"ln":case"link":return{type:dt.LINK,values:r};case"hk":case"hotkey":return{type:dt.HOTKEY,values:r};case"scroll":return{type:dt.SCROLL,values:r};case"copyit":return{type:dt.COPYIT,values:r}}}function Ys(t){switch(t){case dt.LOADER:return"loader";case dt.BOARD:return"board";case dt.OBJECT:return"object";case dt.TERRAIN:return"terrain";case dt.CHARSET:return"charset";case dt.PALETTE:return"palette";case dt.CONST:return"const";case dt.RANGE:return"range";case dt.SELECT:return"select";case dt.NUMBER:return"number";case dt.TEXT:return"text";case dt.LINK:return"link";case dt.HOTKEY:return"hotkey";case dt.SCROLL:return"scroll";case dt.COPYIT:return"copyit"}}function nhe(t,e){return{id:fr(),code:t,...e}}function rhe(t){const e={...AA(t)};return Object.keys(e).forEach(n=>{switch(n){case"type":case"name":delete e[n];break}}),e}function AA(t){var r;if(!Z(t))return{};if(Z((r=t.stats)==null?void 0:r.type))return t.stats;t.stats={};const e=A4(t.code);let n=!0;for(let i=0;ii.id===e||n===_l(i))}function k4(t,e,n){if(!Z(t))return;const r=$t(n);return t.pages.find(s=>MA(s)===e&&(s.id===n||r===_l(s)))}function ihe(t,e){if(!Z(t)||!Z(e))return!1;const n=Um(t,e.id);return Z(n)?!1:(t.pages.push(e),!0)}function she(t,e){const n=Um(t,e);if(Z(t)&&Z(n)){const r=$t(e);return t.pages=t.pages.filter(i=>i.id!==e&&r!==_l(i)),n}}function Ll(t,e){if(Z(e)&&Z(e.kind))return Z(e.kinddata)||(e.kinddata=Z(e.id)?CA(t,e.kind):I4(t,e.kind)),e.kinddata}function ohe(t,e){const n=Ll(t,e);return{char:(e==null?void 0:e.char)??(n==null?void 0:n.char)??1,color:(e==null?void 0:e.color)??(n==null?void 0:n.color)??wn.WHITE,bg:(e==null?void 0:e.bg)??(n==null?void 0:n.bg)??wn.ONBORROW}}function CA(t,e){const n=e??"",r=k4(t,vn.OBJECT,n);if(Z(r)){const i=R4(r);return{...xT(i),name:n,code:r.code}}}function I4(t,e){const n=e??"",r=k4(t,vn.TERRAIN,n);if(Z(r)){const i=R4(r);return{...xT(i),name:n,code:r.code}}}function ahe(t,e){return t?(t.flags[e]=t.flags[e]??{},t.flags[e]):{}}function lhe(t,e){t&&delete t.flags[e]}function che(t,e,n,r){const i=yv(e,(n==null?void 0:n.id)??"");if(!Z(t)||!Z(e)||!Z(i)||!Z(i.x)||!Z(i.y)||!Z(e.lookup)||r.x<0||r.x>=ui||r.y<0||r.y>=mh||i.x-r.x===0&&i.y-r.y===0)return!0;const s=r.x+r.y*ui,o=Ll(t,i),a=i.collision??(o==null?void 0:o.collision),l=yv(e,e.lookup[s]??"");if(Z(l))return!0;const c=e.terrain[s];if(Z(c)){const u=Ll(t,c),h=c.collision??(u==null?void 0:u.collision);if(v3(a,h))return!0}return!1}function uhe(t,e,n,r){const i=yv(e,(n==null?void 0:n.id)??"");if(!Z(t)||!Z(e)||!Z(i)||!Z(i.x)||!Z(i.y)||!Z(e.lookup)||r.x<0||r.x>=ui||r.y<0||r.y>=mh)return{kind:"edge",collision:Vn.ISSOLID,x:r.x,y:r.y};if(i.x-r.x===0&&i.y-r.y===0)return;const s=i.x+i.y*ui,o=r.x+r.y*ui,a=Ll(t,i),l=i.collision??(a==null?void 0:a.collision),c=yv(e,e.lookup[o]??"");if(Z(c))return{...c};const u=e.terrain[o];if(Z(u)){const h=Ll(t,u),p=u.collision??(h==null?void 0:h.collision);if(v3(l,p))return{...u,x:r.x,y:r.y}}i.x=r.x,i.y=r.y,Z(i.removed)||(e.lookup[s]=void 0,e.lookup[o]=i.id??"")}function ed(t,e){const n=Ll(t,e);return Z(e==null?void 0:e.id)&&Z(e.x)&&Z(e.y)?$t(e.name??(n==null?void 0:n.name)??"object"):$t((e==null?void 0:e.name)??(n==null?void 0:n.name)??"terrain")}function Hw(t,e,n,r){if(!Z(t)||!Z(e)||!Z(e.named)||!Z(n))return;const i=ed(t,n);e.named[i]||(e.named[i]=new Set),e.named[i].add((n==null?void 0:n.id)??r??"")}function hhe(t,e,n){if(!(!Z(t)||!Z(e)||!Z(e.lookup)||!Z(n==null?void 0:n.id))&&!Z(n.removed)){const r=n.x??0,i=n.y??0;e.lookup[r+i*ui]=n.id}}function Gw(t,e){if(!Z(t)||!Z(e)||Z(e.lookup)&&Z(e.named))return;const n=new Array(ui*mh).fill(void 0),r={},i=Object.values(e.objects);for(let a=0;a=ui&&(s=0,++o)}e.lookup=n,e.named=r}function RA(t,e,n){return ed(t,e)!=="player"&&Z(e)?(e.removed=n,!0):!1}function Gy(t,e,n){var r;if(Z(t)&&Z(e)&&Z(n==null?void 0:n.id)){if(Z(e.lookup)&&Z(n.x)&&Z(n.y)){const s=n.x+n.y*ui;e.lookup[s]===n.id&&e.lookup.splice(s,1)}const i=ed(t,n);Z((r=e.named)==null?void 0:r[i])&&Z(n.id)&&e.named[i].delete(n.id)}}function fhe(t,e,n,r){if(Z(t)&&Z(e)&&Z(n)){const[i,s]=n,o=CA(t,i);if(Z(o)&&Z(o.name)){const a=G3(e,r,i);return vv(a,s),Hw(t,e,a),a}}}function Ww(t,e,n,r){if(Z(t)&&Z(e)&&Z(n)){const[i,s]=n,o=I4(t,i);if(Z(o)){const l=H3(e,r,i);vv(l,s);const c=r.x+r.y*ui;return Hw(t,e,l,c),l}const a=CA(t,i);if(Z(a)&&Z(a.name)){const l=G3(e,r,i);return vv(l,s),hhe(t,e,l),Hw(t,e,l),l}}}function F0(t,e,n,r){const i=Kt(e)?e:e.id,s=Kt(e)?void 0:{x:e.x??0,y:e.y??0},o=Kt(n)?n:n.id,a=i??s;Z(o)&&Z(a)&&t.send(o,r,a)}function dhe(t,e,n,r){Z(n==null?void 0:n.id)?(n.headless=!0,Gy(t,e,n)):H3(e,r,"empty")}function tI(t,e,n,r,i){const s=uhe(e,n,r,i);if(Z(s)){F0(t,s,t.id(),"thud"),r.kind===Ar.PLAYER?F0(t,t.id(),s,"touch"):r.collision===Vn.ISBULLET?F0(t,t.id(),s,"shot"):F0(t,t.id(),s,"bump");const o=Ll(e,s);return(s.destructible??(o==null?void 0:o.destructible))&&dhe(e,n,s,i),!1}return!0}function nI(t,e,n){if(!gl(se.element))return 0;const[r,i]=He(e,0,[Ie.DIR,Ie.MAYBE_KIND]),s=i??["bullet"],o=fhe(se.book,se.board,s,{x:se.element.x,y:se.element.y});if(Z(o)){o.arg=n,o.collision=Vn.ISBULLET,o.stepx=r.x-se.element.x,o.stepy=r.y-se.element.y;const a=Ll(se.book,o),l=o.code??(a==null?void 0:a.code)??"";Vfe(se.book,se.board,o,l,1),o.x===se.element.x&&o.y===se.element.y?o.headless=!0:t.bucket(o.id)}return t.yield(),0}const phe=Kl().command("change",(t,e)=>{if(!Z(se.book)||!Z(se.board))return 0;const[n,r]=He(e,0,[Ie.KIND,Ie.KIND]);Gw(se.book,se.board);const i=_v(n)??"",s=Lm(se.board,i),o=y3(s,n),a=_v(r),l=g3(r),c=_3(r);return o.forEach(u=>{if(ed(se.book,u)===a)Z(l)&&(u.color=l),Z(c)&&(u.bg=c);else{if(Z(u.id)&&(Gy(se.book,se.board,u),!RA(se.book,u,se.timestamp)))return;gl(u)&&Ww(se.book,se.board,r,u)}}),0}).command("put",(t,e)=>{if(!Z(se.book)||!Z(se.board))return 0;const[n,r]=He(e,0,[Ie.DIR,Ie.KIND]);return Gw(se.book,se.board),Ww(se.book,se.board,r,n),0}).command("shootwith",(t,e)=>{const[n,r]=He(e,0,[Ie.ANY]);return nI(t,e.slice(r),n)}).command("shoot",nI).command("throwstar",()=>0),mhe=Kl().command("send",(t,e)=>{const[n,r]=He(e,0,[Ie.STRING,Ie.ANY]);switch(n){case"helpmenu":fl("cli","H E L P"),rn("cli","#help controls","zss controls and inputs"),qn("cli","!helpcontrols;read help controls"),qn("cli",""),rn("cli","#help text","text formatting"),qn("cli","!helptext;read help text"),qn("cli",""),rn("cli","#help developer","developer commands"),qn("cli","!helpdeveloper;read help developer"),qn("cli",""),rn("cli","#help player","player settings"),qn("cli","!helpplayer;read help player"),al("cli","keyboard input"),rn("cli","?","open console"),rn("cli","esc","close console"),rn("cli","tab","move console"),rn("cli","up / down arrow keys","navigate console items"),rn("cli","left / right arrow keys","change console items"),rn("cli","enter","interact with console items"),rn("cli","alt + arrow keys","skip words and console lines"),rn("cli",`${dae} + up / down arrow keys`,"input history");break;case"helpcontrols":fl("cli","zss controls and inputs"),al("cli","keyboard input"),rn("cli","arrow keys","move"),rn("cli","shift + arrow keys","shoot"),rn("cli","enter","ok / accept"),rn("cli","escape","cancel / close"),rn("cli","tab","menu / action"),al("cli","mouse input"),hn("cli","todo ???"),al("cli","controller input"),rn("cli","left stick","move"),rn("cli","right stick","aim"),rn("cli","a","ok / accept"),rn("cli","b","cancel / close"),rn("cli","y","menu / action"),rn("cli","x","shoot"),rn("cli","triggers","shoot");break;case"helptext":fl("cli","text formatting"),al("cli","typography"),hn("cli","plain text"),hn("cli","$centering text"),hn("cli",'"\\"@quoted strings for special chars\\""'),hn("cli","$$0-255 for ascii chars $159$176$240"),hn("cli",`use color names like ${bs("red","$$red")} to change foreground color`),hn("cli",`use color names like ${qN("ongreen","$$ongreen")} to change background color`),hn("cli",`use clear ${qN("onclear","to change background to")} transparent`),al("cli","hyperlinks"),hn("cli",`${bs("white",'"!hotkey"')} message shortcut;${bs("gray","Label")}`),hn("cli",`${bs("white",'"!range"')} flag [labelmin] [labelmax];${bs("gray","Input Label")}`),hn("cli",`${bs("white",'"!select"')} flag ...list of values;${bs("gray","Input Label")}`),hn("cli",`${bs("white",'"!number"')} flag [minvalue] [maxvalue];${bs("gray","Input Label")}`),hn("cli",`${bs("white",'"!text"')} flag;${bs("gray","Input Label")}`),hn("cli",`${bs("white",'"!copyit"')} flag;${bs("gray","Input Label")}`);break;case"helpdeveloper":fl("cli","developer commands"),rn("cli","#books","list books in memory"),rn("cli","#pages","list pages in opened book"),rn("cli","@[pagetype:]page name","create & edit a new codepage in the currently opened book"),rn("cli","#trash","list books and pages from open book you can delete"),rn("cli","#save","flush state to register");break;case"helpplayer":fl("cli","player settings"),hn("cli","todo");break;default:to("$2",`${n} ${r??""}`);break}return 0}).command("stat",(t,e)=>{let n;const[r,...i]=e.map(ti),s=i.join(" ");switch($t(r)){case Ys(dt.LOADER):n=yu(Ar.CONTENT,s,vn.LOADER);break;default:n=yu(Ar.CONTENT,[r,...i].join(" "),vn.OBJECT);break;case Ys(dt.BOARD):n=yu(Ar.CONTENT,s,vn.BOARD);break;case Ys(dt.OBJECT):n=yu(Ar.CONTENT,s,vn.OBJECT);break;case Ys(dt.TERRAIN):n=yu(Ar.CONTENT,s,vn.TERRAIN);break;case Ys(dt.CHARSET):n=yu(Ar.CONTENT,s,vn.CHARSET);break;case Ys(dt.PALETTE):n=yu(Ar.CONTENT,s,vn.PALETTE);break}return Z(n)&&t.command("pageopen",n.id),0}).command("text",(t,e)=>{const n=e.map(ti).join(" ");return to("$2",n),0}).command("hyperlink",(t,e)=>{const[n,...r]=e,i=ti(n),s=r.map(ti).join(" ");return to("$2",`!${s};${i}`),0}).command("dev",()=>(tf("cli"),MW("cli",se.player),0)).command("share",()=>(tf("cli"),CW("cli",se.player),0)).command("bookcreate",(t,e)=>{const[n]=He(e,0,[Ie.MAYBE_STRING]),r=J4(n);return Z(r)&&t.command("bookopen",r.id),0}).command("bookopen",(t,e)=>{const[n]=He(e,0,[Ie.STRING]),r=td(n);return Z(r)?(hn("cli",`opened [book] ${r.name}`),Yw(Ar.MAIN,r.id),t.command("pages")):Pn("cli","bookopen",`book ${n} not found`,se.player),0}).command("booktrash",(t,e)=>{const[n]=He(e,0,[Ie.STRING]),r=cp(Ar.MAIN),i=td(n);return Z(i)&&(r===i&&Yw(Ar.MAIN,""),Bfe(n),hn("cli",`trashed [book] ${i.name}`),tf("cli"),t.command("pages")),0}).command("pageopen",(t,e)=>{const[n]=He(e,0,[Ie.STRING]),r=bl(Ar.MAIN);if(!Z(r))return 0;const i=Um(r,n);if(Z(i)){const s=_l(i),o=U0(i);hn("cli",`opened [${o}] ${s}`),iU(jO(r.id,i.id),i.code);const a=U0(i);DW("cli",r.id,i.id,a,`${s} - ${r.name}`,se.player)}else Pn("cli","pageopen",`page ${n} not found`,se.player);return 0}).command("pagetrash",(t,e)=>{const[n]=He(e,0,[Ie.STRING]),r=bl(Ar.MAIN),i=she(r,n);if(Z(n)){const s=_l(i),o=U0(i);hn("cli",`trashed [${o}] ${s}`),tf("cli"),t.command("pages")}return 0}).command("nodetrash",()=>(NW("cli"),hn("cli","node id changed, refreshing page recommended"),0)).command("help",(t,e)=>{const n=e.map(ti).join(" ")||"menu";return t.command(`help${n}`),0}).command("books",()=>{al("cli","books");const t=cp(Ar.MAIN);rn("cli","main",`${(t==null?void 0:t.name)??"empty"} $GREEN${(t==null?void 0:t.id)??""}`);const e=cp(Ar.CONTENT);rn("cli","content",`${(e==null?void 0:e.name)??"empty"} ${(e==null?void 0:e.id)??""}`),rA("cli",7);const n=Kw();return n.length?n.forEach(r=>{qn("cli",`!bookopen ${r.id};${r.name}`)}):hn("cli","no books found"),qn("cli","!bookcreate;create a new book"),0}).command("pages",()=>{al("cli","pages");const t=bl(Ar.MAIN);return Z(t)&&(rn("cli","main",`${t.name} $GREEN${t.id}`),t.pages.length?t.pages.forEach(e=>{const n=_l(e),r=U0(e);qn("cli",`!pageopen ${e.id};[${r}] ${n}`)}):(qn("cli",""),hn("cli","no pages found"),hn("cli","use @ to create a page"),hn("cli","@board name of board"),hn("cli","@object name of object"),hn("cli","@terrain name of terrain"),hn("cli","You can omit the type and it will default to object"),hn("cli","@object name of object"),hn("cli","@name of object"))),0}).command("trash",()=>{al("cli","$REDTRASH"),hn("cli","books");const t=Kw();t.length&&(t.forEach(n=>{qn("cli",`!booktrash ${n.id};$REDTRASH ${n.name}`)}),qn("cli",""));const e=cp(Ar.MAIN);return Z(e)&&(hn("cli",`pages in open ${e.name} book`),e.pages.forEach(n=>{const r=_l(n);qn("cli",`!pagetrash ${n.id};$REDTRASH ${r}`)}),qn("cli","")),0}).command("save",()=>(tf("cli"),0)).command("nuke",()=>(RW("cli"),0));function ghe(t){const e=W3[t];if(Z(e))return e;const n=q3[t];if(Z(n))return n;const r=$y[t];if(Z(r))return r;const i=d3[t];if(Z(i))return i}const _he=Kl({get(t,e){const n=ghe(e);return Z(n)?[!0,n]:[!1,void 0]}}),vhe=new Set(["inputmove","inputalt","inputctrl","inputshift","inputok","inputcancel","inputmenu"]),rI=new Set(["player","pushable","collision","destructible","p1","p2","p3","cycle","stepx","stepy","sender","arg"]),yhe=["NORTH","SOUTH","WEST","EAST"];function xhe(){const t=jp(se.player);if(ln(t.inputqueue)||(t.inputqueue=[],t.inputcurrent=0),mt(t.inputcurrent)&&t.inputcurrent>0)return;const[e]=t.inputqueue,[n=Ue.NONE,r=0]=e??[Ue.NONE,0];switch(t.inputmove=[],t.inputok=0,t.inputcancel=0,t.inputmenu=0,t.inputalt=r&cU?1:0,t.inputctrl=r&uU?1:0,t.inputshift=r&hU?1:0,n){case Ue.MOVE_UP:case Ue.MOVE_DOWN:case Ue.MOVE_LEFT:case Ue.MOVE_RIGHT:t.inputmove=[yhe[n-Ue.MOVE_UP]];break;case Ue.OK_BUTTON:t.inputok=1;break;case Ue.CANCEL_BUTTON:t.inputcancel=1;break;case Ue.MENU_BUTTON:t.inputmenu=1;break}t.inputcurrent=n,t.inputqueue=t.inputqueue.filter(i=>{const[s]=i;return s!==Ue.NONE&&s!==n})}const She=Kl({get(t,e){var s;se.isplayer&&vhe.has(e)&&xhe();const n=(s=se.element)==null?void 0:s[e];if(Z(n)||rI.has(e))return[!0,n];const i=jp(se.player)[e];return[Z(i),i]},set(t,e,n){var s;const r=(s=se.element)==null?void 0:s[e];if(Z(r)||rI.has(e))return Z(se.element)&&(se.element[e]=n),[!0,n];const i=jp(se.player);return i[e]=n,[!0,n]},everytick(t){var e,n;Z((e=se.element)==null?void 0:e.x)&&Z(se.element.y)&&Z(se.element.stepx)&&Z(se.element.stepy)&&tI(t,se.book,se.board,se.element,{x:se.element.x+se.element.stepx,y:se.element.y+se.element.stepy})===!1&&(se.element.stepx=0,se.element.stepy=0),(n=se.element)!=null&&n.headless&&t.command("die")}}).command("become",(t,e)=>{var i,s;const n={x:((i=se.element)==null?void 0:i.x)??0,y:((s=se.element)==null?void 0:s.y)??0},[r]=He(e,0,[Ie.KIND]);return Gw(se.book,se.board),Gy(se.book,se.board,se.element),RA(se.book,se.element,se.timestamp)&&Ww(se.book,se.board,r,n),t.endofprogram(),0}).command("bind",()=>0).command("char",(t,e)=>{const[n]=He(e,0,[Ie.NUMBER]);return Z(se.element)&&(se.element.char=n),0}).command("color",(t,e)=>{const[n]=He(e,0,[Ie.COLOR]);return Z(se.element)&&Z(n)&&vv(se.element,n),0}).command("go",(t,e)=>{if(Z(se.element)){const[n]=He(e,0,[Ie.DIR]);if(tI(t,se.book,se.board,se.element,n),t.yield(),se.element.x===n.x&&se.element.y===n.y)return 0}return 1}).command("try",(t,e)=>{const[,n]=He(e,0,[Ie.DIR]);return t.command("go",...e)&&n{if(!Z(se.element))return 0;const[n]=He(e,0,[Ie.DIR]),r=se.element.x??0,i=se.element.y??0;return se.element.stepx=n.x-r,se.element.stepy=n.y-i,0}),Ehe=Kl().command("clear",(t,e)=>(e.forEach(n=>t.set(ti(n),0)),0)).command("set",(t,e)=>{const[n,r]=He(e,0,[Ie.STRING,Ie.ANY]);return t.set(n,r),0}).command("take",(t,e)=>{const[n,r,i]=He(e,0,[Ie.STRING,Ie.MAYBE_NUMBER]),s=t.get(n),o=r??1;if(!mt(s))return 1;const a=s-o;return a<0?(i{const[n,r,i]=He(e,0,[Ie.STRING,Ie.MAYBE_NUMBER]),s=t.get(n),o=mt(s)?s:0,a=r??1;if(!mt(a))return 0;const l=s===void 0?1:0;return l&&i0&&y<_.lastIndexOf(" ")?l.low.call(g):g})},sentence:function(m,g,v){return m=c.lower(m).replace(a.sentence,function(y,_,S){return _+l.up.call(S)}),g&&g.forEach(function(y){m=m.replace(new RegExp("\\b"+c.lower(y)+"\\b","g"),l.cap)}),v&&v.forEach(function(y){m=m.replace(new RegExp("(\\b"+c.lower(y)+"\\. +)(\\w)"),function(_,S,E){return S+l.low.call(E)})}),m}};u.squish=u.pascal,c.default=c;for(var h in u)c.type(h,u[h]);var p=typeof p=="function"?p:function(){};p(t.exports?t.exports=c:this.Case=c)}).call(bo)})(O4);var whe=O4.exports;const The=Pl(whe),yc={};function bhe(t){return{player:t,layers:[],panels:[],reset:!0,focus:"scroll"}}function L4(t){t.text=[],Object.values(yc[t.id]??{}).forEach(e=>e==null?void 0:e()),yc[t.id]={}}function P4(t){const e=t.panels.find(n=>n.name===t.focus);if(!e){const n={id:fr(),name:t.focus,edge:xi.RIGHT,size:20,text:[]};return t.panels.push(n),t.reset=!1,n}return e}const Ahe=new Set(["hk","hotkey","rn","range","sl","select","nm","number","tx","text"]),Mhe=new Set(["rn","range","sl","select","nm","number","tx","text"]),Che=new Set(["tx","text"]),Rhe={rn:1,range:1,sl:0,select:0,nm:0,number:0,tx:"",text:""},iI={};let Nhe=t=>{let e=iI[t];return Z(e)||(iI[t]=e=bhe(t)),e};function Wy(t){return Nhe(t)}function khe(t,e,n){Object.values(yc).forEach(r=>{if(r[e]!==void 0){const i=md(t.id(),e);mt(n)&&Ac(i,n),Kt(n)&&loe(i,n)}})}function Ihe(t){let e="";const n=Wy(t);return n.panels=n.panels.filter(r=>{if(r.edge===xi.SCROLL){const[i]=r.text;return Kt(i)&&r.text.length===1&&(e=i),r.text.length>1}return!0}),e}function b1(t,e,n,r,i){const s=Wy(t),o=r,a=i??The.capital(e),l=s.panels.find(c=>c.name===a);if(l)s.reset=!0,s.focus=a,mt(o)&&(l.size=o);else switch(n){case xi.START:break;case xi.LEFT:case xi.RIGHT:case xi.TOP:case xi.BOTTOM:case xi.SCROLL:{const c={id:fr(),name:a,edge:n,size:o??Toe[n],text:[]};s.panels.push(c),s.focus=a;break}}}function Ohe(t,e){const n=Wy(t),r=P4(n);n.reset&&(n.reset=!1,L4(r)),r.text.push(e)}function Lhe(t,e,n,r,i){const s=Wy(t),o=P4(s);s.reset&&(s.reset=!1,L4(o));const a=$t(r),l=[e.id(),n,...Ahe.has(a)?[a]:["hyperlink",r],...i],c=l[2];if(Mhe.has(c)){const u=`${l[3]??""}`;yc[o.id]=yc[o.id]??{};const h=e.get(u)??Rhe[c];if(yc[o.id][u]===void 0){const p=md(e.id(),u);mt(h)&&aoe(p,h),Kt(h)&&iU(p,h),Che.has(c)?yc[o.id][u]=uoe(p,m=>{Z(m)&&m!==e.get(u)&&e.set(u,m)}):yc[o.id][u]=coe(p,m=>{Z(m)&&m!==e.get(u)&&e.set(u,m)})}}o.text.push(l)}const Phe=Kl({get(){return[!1,void 0]},set(t,e,n){return khe(t,e,n),[!1,void 0]},tick(){var e;const t=((e=se.element)==null?void 0:e.name)??"scroll";b1(se.player,"scroll",xi.SCROLL,void 0,t)},everytick(){const t=Ihe(se.player);if(t&&Z(se.element)){se.element.tickertext=t,se.element.tickertime=se.timestamp;const e=ohe(se.book,se.element);to(`$${wn[e.color]}$${e.char}`,t)}}}).command("send",(t,e)=>{var u,h;const[n,r]=He(e,0,[Ie.STRING,Ie.ANY]),[i,s]=n.split(":"),o=Z(s)?i:"self",a=s??i;function l(p){p.forEach(m=>{Z(m.id)&&t.send(m.id,a,r)})}const c=$t(o);switch(c){case"all":for(const p of Object.keys(((u=se.board)==null?void 0:u.objects)??{}))t.send(p,a,r);break;case"self":t.message({id:fr(),sender:t.id(),target:a,data:r});break;case"others":for(const p of Object.keys(((h=se.board)==null?void 0:h.objects)??{}))p!==t.id()&&t.send(p,a,r);break;default:{l(y1(se.board,[o]));const p=t.get(c);ln(p)?l(y1(se.board,p)):l(y1(se.board,[p]));break}}return 0}).command("stat",(t,e)=>{const n=M4(e.map(ti));switch(n.type){case dt.OBJECT:Z(se.element)&&(se.element.name=n.values.join(" "));break}return 0}).command("text",(t,e)=>{const n=e.map(ti).join("");return Ohe(se.player,n),0}).command("hyperlink",(t,e)=>{const[n,r,...i]=e,s=ti(n),o=ti(r);return Lhe(se.player,t,s,o,i),0}).command("gadget",(t,e)=>{const[n]=He(e,0,[Ie.STRING]),r=woe[$t(n)];if(r===xi.SCROLL){const[,i,s]=He(e,0,[Ie.STRING,Ie.MAYBE_STRING,Ie.MAYBE_NUMBER]);b1(se.player,n,r,s,i)}else{const[,i,s]=He(e,0,[Ie.STRING,Ie.MAYBE_NUMBER,Ie.MAYBE_STRING]);b1(se.player,n,r,i,s)}return 0}),Dhe=Kl().command("idle",t=>(t.yield(),0)).command("end",t=>(t.endofprogram(),0)).command("endwith",(t,e)=>{const[n]=He(e,0,[Ie.ANY]);return t.set("arg",n),t.command("end")}).command("lock",t=>(t.lock(t.id()),0)).command("restore",(t,e)=>(t.restore(ti(e[0])),0)).command("unlock",t=>(t.unlock(),0)).command("zap",(t,e)=>(t.zap(ti(e[0])),0)).command("cycle",(t,e)=>{if(Z(se.element)){const[n]=He(e,0,[Ie.NUMBER]);se.element.cycle=Cn(Math.round(n),1,255)}return 0}).command("die",t=>{var e;return(e=se.element)!=null&&e.headless&&Gy(se.book,se.board,se.element),RA(se.book,se.element,se.timestamp),t.endofprogram(),0}).command("endgame",()=>(VW("element",se.player),0)).command("run",(t,e)=>{const[n]=He(e,0,[Ie.STRING]);return Sv(n),0}).command("runwith",(t,e)=>{const[n,r]=He(e,0,[Ie.ANY,Ie.STRING]);return t.set("arg",n),Sv(r),0});function sI(t,e){if(!Z(t))return;const n=$t(e),r=n.endsWith("le");switch(n){case"float32":case"float32le":{const i=t.dataview.getFloat32(t.cursor,r);return t.cursor+=4,i}case"float64":case"float64le":{const i=t.dataview.getFloat64(t.cursor,r);return t.cursor+=8,i}case"int8":case"int8le":{const i=t.dataview.getInt8(t.cursor);return t.cursor+=1,i}case"int16":case"int16le":{const i=t.dataview.getInt16(t.cursor,r);return t.cursor+=2,i}case"int32":case"int32le":{const i=t.dataview.getInt32(t.cursor,r);return t.cursor+=4,i}case"int64":case"int64le":{const i=t.dataview.getBigInt64(t.cursor,r);return t.cursor+=8,i}case"uint8":case"uint8le":{const i=t.dataview.getUint8(t.cursor);return t.cursor+=1,i}case"uint16":case"uint16le":{const i=t.dataview.getUint16(t.cursor,r);return t.cursor+=2,i}case"uint32":case"uint32le":{const i=t.dataview.getUint32(t.cursor,r);return t.cursor+=4,i}case"uint64":case"uint64le":{const i=t.dataview.getBigUint64(t.cursor,r);return t.cursor+=8,i}}}const Uhe=(t,e)=>{const n=eF(t.id());if(!Z(n))return 0;const[r]=He(e,0,[Ie.STRING]),i=$t(r);switch(i){case"seek":{const[s]=He(e,1,[Ie.NUMBER]);n.cursor=s;break}case"float32":case"float32le":case"float64":case"float64le":case"int8":case"int8le":case"int16":case"int16le":case"int32":case"int32le":case"int64":case"int64le":case"uint8":case"uint8le":case"uint16":case"uint16le":case"uint32":case"uint32le":case"uint64":case"uint64le":{const[s]=He(e,1,[Ie.STRING]);t.set(s,sI(n,i));break}case"text":{const[s,o]=He(e,1,[Ie.STRING,Ie.STRING]),a=sI(n,s);if(mt(a)&&Kt(o)){const l=new Uint8Array(n.bytes.buffer,n.cursor,a),u=new TextDecoder("utf-8").decode(l);t.set(o,u),n.cursor+=a}break}}return 0},Fhe=Kl({get(t,e){const n=eF(t.id());if(Z(n))switch($t(e)){case"filename":return[Z(n.filename),n.filename];case"cursor":return[Z(n.cursor),n.cursor]}return[!1,void 0]}}).command("send",(t,e)=>{const[n,r]=He(e,0,[Ie.STRING,Ie.ANY]);return t.message({id:fr(),sender:t.id(),target:n,data:r}),0}).command("stat",()=>0).command("text",(t,e)=>{const n=e.map(ti).join(" ");return to("$2",n),0}).command("hyperlink",(t,e)=>{const[n,...r]=e,i=ti(n),s=r.map(ti).join(" ");return to("$2",`!${s};${i}`),0}).command("load",(t,e)=>{const n=e.map(ti).join(" "),r=t.get(n)??n;return bl(Ar.CONTENT,r),0}).command("reload",(t,e)=>{const n=e.map(ti).join(" "),r=t.get(n)??n,i=bl(Ar.CONTENT,r);return i.pages=[],0}).command("bin",Uhe);var NA=(t=>(t[t.ERROR=0]="ERROR",t[t.CLI=1]="CLI",t[t.LOADER=2]="LOADER",t[t.CODE_PAGE=3]="CODE_PAGE",t))(NA||{});const Bhe={audio:Kue,board:phe,cli:mhe,const:_he,element:She,flags:Ehe,gadget:Phe,lifecycle:Dhe,loader:Fhe},A1=["const","flags","audio","board","lifecycle","element"],zhe={0:[],1:["cli",...A1],2:["loader",...A1],3:["gadget",...A1]},Vhe={0:new Map,1:new Map,2:new Map,3:new Map};function Fm(t){return(zhe[t]??[]).map(n=>Bhe[n]).filter(Z)}function Hhe(t,e){const n=Vhe[t];if(!n.has(e)){let r;const i=Fm(t);for(let s=0;s>>=B4,i>0&&(r|=Xhe),n+=$he.encode(r);while(i>0);return n};var Bm={};(function(t){function e(R,C,O){if(C in R)return R[C];if(arguments.length===3)return O;throw new Error('"'+C+'" is a required argument.')}t.getArg=e;const n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(R){const C=R.match(n);return C?{scheme:C[1],auth:C[2],host:C[3],port:C[4],path:C[5]}:null}t.urlParse=i;function s(R){let C="";return R.scheme&&(C+=R.scheme+":"),C+="//",R.auth&&(C+=R.auth+"@"),R.host&&(C+=R.host),R.port&&(C+=":"+R.port),R.path&&(C+=R.path),C}t.urlGenerate=s;const o=32;function a(R){const C=[];return function(O){for(let I=0;Io&&C.pop(),M}}const l=a(function(C){let O=C;const M=i(C);if(M){if(!M.path)return C;O=M.path}const I=t.isAbsolute(O),U=[];let L=0,P=0;for(;;)if(L=P,P=O.indexOf("/",L),P===-1){U.push(O.slice(L));break}else for(U.push(O.slice(L,P));P=0;P--){const H=U[P];H==="."?U.splice(P,1):H===".."?b++:b>0&&(H===""?(U.splice(P+1,b),b=0):(U.splice(P,2),b--))}return O=U.join("/"),O===""&&(O=I?"/":"."),M?(M.path=O,s(M)):O});t.normalize=l;function c(R,C){R===""&&(R="."),C===""&&(C=".");const O=i(C),M=i(R);if(M&&(R=M.path||"/"),O&&!O.scheme)return M&&(O.scheme=M.scheme),s(O);if(O||C.match(r))return C;if(M&&!M.host&&!M.path)return M.host=C,s(M);const I=C.charAt(0)==="/"?C:l(R.replace(/\/+$/,"")+"/"+C);return M?(M.path=I,s(M)):I}t.join=c,t.isAbsolute=function(R){return R.charAt(0)==="/"||n.test(R)};function u(R,C){R===""&&(R="."),R=R.replace(/\/$/,"");let O=0;for(;C.indexOf(R+"/")!==0;){const M=R.lastIndexOf("/");if(M<0||(R=R.slice(0,M),R.match(/^([^\/]+:\/)?\/*$/)))return C;++O}return Array(O+1).join("../")+C.substr(R.length+1)}t.relative=u;const h=function(){return!("__proto__"in Object.create(null))}();function p(R){return R}function m(R){return v(R)?"$"+R:R}t.toSetString=h?p:m;function g(R){return v(R)?R.slice(1):R}t.fromSetString=h?p:g;function v(R){if(!R)return!1;const C=R.length;if(C<9||R.charCodeAt(C-1)!==95||R.charCodeAt(C-2)!==95||R.charCodeAt(C-3)!==111||R.charCodeAt(C-4)!==116||R.charCodeAt(C-5)!==111||R.charCodeAt(C-6)!==114||R.charCodeAt(C-7)!==112||R.charCodeAt(C-8)!==95||R.charCodeAt(C-9)!==95)return!1;for(let O=C-10;O>=0;O--)if(R.charCodeAt(O)!==36)return!1;return!0}function y(R,C,O){let M=S(R.source,C.source);return M!==0||(M=R.originalLine-C.originalLine,M!==0)||(M=R.originalColumn-C.originalColumn,M!==0||O)||(M=R.generatedColumn-C.generatedColumn,M!==0)||(M=R.generatedLine-C.generatedLine,M!==0)?M:S(R.name,C.name)}t.compareByOriginalPositions=y;function _(R,C,O){let M=R.generatedLine-C.generatedLine;return M!==0||(M=R.generatedColumn-C.generatedColumn,M!==0||O)||(M=S(R.source,C.source),M!==0)||(M=R.originalLine-C.originalLine,M!==0)||(M=R.originalColumn-C.originalColumn,M!==0)?M:S(R.name,C.name)}t.compareByGeneratedPositionsDeflated=_;function S(R,C){return R===C?0:R===null?1:C===null?-1:R>C?1:-1}function E(R,C){let O=R.generatedLine-C.generatedLine;return O!==0||(O=R.generatedColumn-C.generatedColumn,O!==0)||(O=S(R.source,C.source),O!==0)||(O=R.originalLine-C.originalLine,O!==0)||(O=R.originalColumn-C.originalColumn,O!==0)?O:S(R.name,C.name)}t.compareByGeneratedPositionsInflated=E;function T(R){return JSON.parse(R.replace(/^\)]}'[^\n]*\n/,""))}t.parseSourceMapInput=T;function N(R,C,O){if(C=C||"",R&&(R[R.length-1]!=="/"&&C[0]!=="/"&&(R+="/"),C=R+C),O){const M=i(O);if(!M)throw new Error("sourceMapURL could not be parsed");if(M.path){const I=M.path.lastIndexOf("/");I>=0&&(M.path=M.path.substring(0,I+1))}C=c(s(M),C)}return l(C)}t.computeSourceURL=N})(Bm);var kA={};let Yhe=class V4{constructor(){this._array=[],this._set=new Map}static fromArray(e,n){const r=new V4;for(let i=0,s=e.length;i=0)return n;throw new Error('"'+e+'" is not in the set.')}at(e){if(e>=0&&en||r==n&&s>=i||G4.compareByGeneratedPositionsInflated(t,e)<=0}let Jhe=class{constructor(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}unsortedForEach(e,n){this._array.forEach(e,n)}add(e){Zhe(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))}toArray(){return this._sorted||(this._array.sort(G4.compareByGeneratedPositionsInflated),this._sorted=!0),this._array}};H4.MappingList=Jhe;const Kd=U4,wr=Bm,B0=kA.ArraySet,Qhe=H4.MappingList;let W4=class j4{constructor(e){e||(e={}),this._file=wr.getArg(e,"file",null),this._sourceRoot=wr.getArg(e,"sourceRoot",null),this._skipValidation=wr.getArg(e,"skipValidation",!1),this._sources=new B0,this._names=new B0,this._mappings=new Qhe,this._sourcesContents=null}static fromSourceMap(e){const n=e.sourceRoot,r=new j4({file:e.file,sourceRoot:n});return e.eachMapping(function(i){const s={generated:{line:i.generatedLine,column:i.generatedColumn}};i.source!=null&&(s.source=i.source,n!=null&&(s.source=wr.relative(n,s.source)),s.original={line:i.originalLine,column:i.originalColumn},i.name!=null&&(s.name=i.name)),r.addMapping(s)}),e.sources.forEach(function(i){let s=i;n!==null&&(s=wr.relative(n,i)),r._sources.has(s)||r._sources.add(s);const o=e.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r}addMapping(e){const n=wr.getArg(e,"generated"),r=wr.getArg(e,"original",null);let i=wr.getArg(e,"source",null),s=wr.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,i,s),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:s})}setSourceContent(e,n){let r=e;this._sourceRoot!=null&&(r=wr.relative(this._sourceRoot,r)),n!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[wr.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[wr.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))}applySourceMap(e,n,r){let i=n;if(n==null){if(e.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=e.file}const s=this._sourceRoot;s!=null&&(i=wr.relative(s,i));const o=this._mappings.toArray().length>0?new B0:this._sources,a=new B0;this._mappings.unsortedForEach(function(l){if(l.source===i&&l.originalLine!=null){const h=e.originalPositionFor({line:l.originalLine,column:l.originalColumn});h.source!=null&&(l.source=h.source,r!=null&&(l.source=wr.join(r,l.source)),s!=null&&(l.source=wr.relative(s,l.source)),l.originalLine=h.line,l.originalColumn=h.column,h.name!=null&&(l.name=h.name))}const c=l.source;c!=null&&!o.has(c)&&o.add(c);const u=l.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=o,this._names=a,e.sources.forEach(function(l){const c=e.sourceContentFor(l);c!=null&&(r!=null&&(l=wr.join(r,l)),s!=null&&(l=wr.relative(s,l)),this.setSourceContent(l,c))},this)}_validateMapping(e,n,r,i){if(n&&typeof n.line!="number"&&typeof n.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!n&&!r&&!i)){if(!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:i}))}}_serializeMappings(){let e=0,n=1,r=0,i=0,s=0,o=0,a="",l,c,u,h;const p=this._mappings.toArray();for(let m=0,g=p.length;m0){if(!wr.compareByGeneratedPositionsInflated(c,p[m-1]))continue;l+=","}l+=Kd.encode(c.generatedColumn-e),e=c.generatedColumn,c.source!=null&&(h=this._sources.indexOf(c.source),l+=Kd.encode(h-o),o=h,l+=Kd.encode(c.originalLine-1-i),i=c.originalLine-1,l+=Kd.encode(c.originalColumn-r),r=c.originalColumn,c.name!=null&&(u=this._names.indexOf(c.name),l+=Kd.encode(u-s),s=u)),a+=l}return a}_generateSourcesContent(e,n){return e.map(function(r){if(!this._sourcesContents)return null;n!=null&&(r=wr.relative(n,r));const i=wr.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)}toJSON(){const e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e}toString(){return JSON.stringify(this.toJSON())}};W4.prototype._version=3;D4.SourceMapGenerator=W4;var $4={};(function(t){t.GREATEST_LOWER_BOUND=1,t.LEAST_UPPER_BOUND=2;function e(n,r,i,s,o,a){const l=Math.floor((r-n)/2)+n,c=o(i,s[l],!0);return c===0?l:c>0?r-l>1?e(l,r,i,s,o,a):a==t.LEAST_UPPER_BOUND?r1?e(n,l,i,s,o,a):a==t.LEAST_UPPER_BOUND?l:n<0?-1:n}t.search=function(r,i,s,o){if(i.length===0)return-1;let a=e(-1,i.length,r,i,s,o||t.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&s(i[a],i[a-1],!0)===0;)--a;return a}})($4);var op={exports:{}};const efe={},tfe=Object.freeze(Object.defineProperty({__proto__:null,default:efe},Symbol.toStringTag,{value:"Module"})),lI=aB(tfe),nfe=(function(){return typeof window<"u"&&this===window}).call();if(nfe){let t=null;op.exports=function(){if(typeof t=="string")return fetch(t).then(n=>n.arrayBuffer());if(t instanceof ArrayBuffer)return Promise.resolve(t);throw new Error("You must provide the string URL or ArrayBuffer contents of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer")},op.exports.initialize=e=>t=e}else{const t=lI,e=lI;op.exports=function(){return new Promise((r,i)=>{const s=e.join(__dirname,"mappings.wasm");t.readFile(s,null,(o,a)=>{if(o){i(o);return}r(a.buffer)})})},op.exports.initialize=n=>{console.debug("SourceMapConsumer.initialize is a no-op when running in node.js")}}var q4=op.exports;const rfe=q4;function ife(){this.generatedLine=0,this.generatedColumn=0,this.lastGeneratedColumn=null,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}let Yd=null;var sfe=function(){if(Yd)return Yd;const e=[];return Yd=rfe().then(n=>WebAssembly.instantiate(n,{env:{mapping_callback(r,i,s,o,a,l,c,u,h,p){const m=new ife;m.generatedLine=r+1,m.generatedColumn=i,s&&(m.lastGeneratedColumn=o-1),a&&(m.source=l,m.originalLine=c+1,m.originalColumn=u,h&&(m.name=p)),e[e.length-1](m)},start_all_generated_locations_for(){console.time("all_generated_locations_for")},end_all_generated_locations_for(){console.timeEnd("all_generated_locations_for")},start_compute_column_spans(){console.time("compute_column_spans")},end_compute_column_spans(){console.timeEnd("compute_column_spans")},start_generated_location_for(){console.time("generated_location_for")},end_generated_location_for(){console.timeEnd("generated_location_for")},start_original_location_for(){console.time("original_location_for")},end_original_location_for(){console.timeEnd("original_location_for")},start_parse_mappings(){console.time("parse_mappings")},end_parse_mappings(){console.timeEnd("parse_mappings")},start_sort_by_generated_location(){console.time("sort_by_generated_location")},end_sort_by_generated_location(){console.timeEnd("sort_by_generated_location")},start_sort_by_original_location(){console.time("sort_by_original_location")},end_sort_by_original_location(){console.timeEnd("sort_by_original_location")}}})).then(n=>({exports:n.instance.exports,withMappingCallback:(r,i)=>{e.push(r);try{i()}finally{e.pop()}}})).then(null,n=>{throw Yd=null,n}),Yd};const _t=Bm,M1=$4,xv=kA.ArraySet,ofe=q4,afe=sfe,IA=Symbol("smcInternal");class dr{constructor(e,n){return e==IA?Promise.resolve(this):cfe(e,n)}static initialize(e){ofe.initialize(e["lib/mappings.wasm"])}static fromSourceMap(e,n){return ufe(e,n)}static async with(e,n,r){const i=await new dr(e,n);try{return await r(i)}finally{i.destroy()}}_parseMappings(e,n){throw new Error("Subclasses must implement _parseMappings")}eachMapping(e,n,r){throw new Error("Subclasses must implement eachMapping")}allGeneratedPositionsFor(e){throw new Error("Subclasses must implement allGeneratedPositionsFor")}destroy(){throw new Error("Subclasses must implement destroy")}}dr.prototype._version=3;dr.GENERATED_ORDER=1;dr.ORIGINAL_ORDER=2;dr.GREATEST_LOWER_BOUND=1;dr.LEAST_UPPER_BOUND=2;class zm extends dr{constructor(e,n){return super(IA).then(r=>{let i=e;typeof e=="string"&&(i=_t.parseSourceMapInput(e));const s=_t.getArg(i,"version");let o=_t.getArg(i,"sources");const a=_t.getArg(i,"names",[]);let l=_t.getArg(i,"sourceRoot",null);const c=_t.getArg(i,"sourcesContent",null),u=_t.getArg(i,"mappings"),h=_t.getArg(i,"file",null);if(s!=r._version)throw new Error("Unsupported version: "+s);return l&&(l=_t.normalize(l)),o=o.map(String).map(_t.normalize).map(function(p){return l&&_t.isAbsolute(l)&&_t.isAbsolute(p)?_t.relative(l,p):p}),r._names=xv.fromArray(a.map(String),!0),r._sources=xv.fromArray(o,!0),r._absoluteSources=r._sources.toArray().map(function(p){return _t.computeSourceURL(l,p,n)}),r.sourceRoot=l,r.sourcesContent=c,r._mappings=u,r._sourceMapURL=n,r.file=h,r._computedColumnSpans=!1,r._mappingsPtr=0,r._wasm=null,afe().then(p=>(r._wasm=p,r))})}_findSourceIndex(e){let n=e;if(this.sourceRoot!=null&&(n=_t.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);for(let r=0;r{a.source!==null&&(a.source=this._sources.at(a.source),a.source=_t.computeSourceURL(o,a.source,this._sourceMapURL),a.name!==null&&(a.name=this._names.at(a.name))),e.call(i,a)},()=>{switch(s){case dr.GENERATED_ORDER:this._wasm.exports.by_generated_location(this._getMappingsPtr());break;case dr.ORIGINAL_ORDER:this._wasm.exports.by_original_location(this._getMappingsPtr());break;default:throw new Error("Unknown order of iteration.")}})}allGeneratedPositionsFor(e){let n=_t.getArg(e,"source");const r=_t.getArg(e,"line"),i=e.column||0;if(n=this._findSourceIndex(n),n<0)return[];if(r<1)throw new Error("Line numbers must be >= 1");if(i<0)throw new Error("Column numbers must be >= 0");const s=[];return this._wasm.withMappingCallback(o=>{let a=o.lastGeneratedColumn;this._computedColumnSpans&&a===null&&(a=1/0),s.push({line:o.generatedLine,column:o.generatedColumn,lastColumn:a})},()=>{this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(),n,r-1,"column"in e,i)}),s}destroy(){this._mappingsPtr!==0&&(this._wasm.exports.free_mappings(this._mappingsPtr),this._mappingsPtr=0)}computeColumnSpans(){this._computedColumnSpans||(this._wasm.exports.compute_column_spans(this._getMappingsPtr()),this._computedColumnSpans=!0)}originalPositionFor(e){const n={generatedLine:_t.getArg(e,"line"),generatedColumn:_t.getArg(e,"column")};if(n.generatedLine<1)throw new Error("Line numbers must be >= 1");if(n.generatedColumn<0)throw new Error("Column numbers must be >= 0");let r=_t.getArg(e,"bias",dr.GREATEST_LOWER_BOUND);r==null&&(r=dr.GREATEST_LOWER_BOUND);let i;if(this._wasm.withMappingCallback(s=>i=s,()=>{this._wasm.exports.original_location_for(this._getMappingsPtr(),n.generatedLine-1,n.generatedColumn,r)}),i&&i.generatedLine===n.generatedLine){let s=_t.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=_t.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));let o=_t.getArg(i,"name",null);return o!==null&&(o=this._names.at(o)),{source:s,line:_t.getArg(i,"originalLine",null),column:_t.getArg(i,"originalColumn",null),name:o}}return{source:null,line:null,column:null,name:null}}hasContentsOfAllSources(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1}sourceContentFor(e,n){if(!this.sourcesContent)return null;const r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];let i=e;this.sourceRoot!=null&&(i=_t.relative(this.sourceRoot,i));let s;if(this.sourceRoot!=null&&(s=_t.urlParse(this.sourceRoot))){const o=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(n)return null;throw new Error('"'+i+'" is not in the SourceMap.')}generatedPositionFor(e){let n=_t.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};const r={source:n,originalLine:_t.getArg(e,"line"),originalColumn:_t.getArg(e,"column")};if(r.originalLine<1)throw new Error("Line numbers must be >= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");let i=_t.getArg(e,"bias",dr.GREATEST_LOWER_BOUND);i==null&&(i=dr.GREATEST_LOWER_BOUND);let s;if(this._wasm.withMappingCallback(o=>s=o,()=>{this._wasm.exports.generated_location_for(this._getMappingsPtr(),r.source,r.originalLine-1,r.originalColumn,i)}),s&&s.source===r.source){let o=s.lastGeneratedColumn;return this._computedColumnSpans&&o===null&&(o=1/0),{line:_t.getArg(s,"generatedLine",null),column:_t.getArg(s,"generatedColumn",null),lastColumn:o}}return{line:null,column:null,lastColumn:null}}}zm.prototype.consumer=dr;class lfe extends dr{constructor(e,n){return super(IA).then(r=>{let i=e;typeof e=="string"&&(i=_t.parseSourceMapInput(e));const s=_t.getArg(i,"version"),o=_t.getArg(i,"sections");if(s!=r._version)throw new Error("Unsupported version: "+s);r._sources=new xv,r._names=new xv,r.__generatedMappings=null,r.__originalMappings=null,r.__generatedMappingsUnsorted=null,r.__originalMappingsUnsorted=null;let a={line:-1,column:0};return Promise.all(o.map(l=>{if(l.url)throw new Error("Support for url field in sections not implemented.");const c=_t.getArg(l,"offset"),u=_t.getArg(c,"line"),h=_t.getArg(c,"column");if(u({generatedOffset:{generatedLine:u+1,generatedColumn:h+1},consumer:m}))})).then(l=>(r._sections=l,r))})}get _generatedMappings(){return this.__generatedMappings||this._sortGeneratedMappings(),this.__generatedMappings}get _originalMappings(){return this.__originalMappings||this._sortOriginalMappings(),this.__originalMappings}get _generatedMappingsUnsorted(){return this.__generatedMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappingsUnsorted}get _originalMappingsUnsorted(){return this.__originalMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappingsUnsorted}_sortGeneratedMappings(){const e=this._generatedMappingsUnsorted;e.sort(_t.compareByGeneratedPositionsDeflated),this.__generatedMappings=e}_sortOriginalMappings(){const e=this._originalMappingsUnsorted;e.sort(_t.compareByOriginalPositions),this.__originalMappings=e}get sources(){const e=[];for(let n=0;na.push(l));for(let l=0;l= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");const i=[];let s=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",_t.compareByOriginalPositions,M1.LEAST_UPPER_BOUND);if(s>=0){let o=this._originalMappings[s];if(e.column===void 0){const a=o.originalLine;for(;o&&o.originalLine===a;){let l=o.lastGeneratedColumn;this._computedColumnSpans&&l===null&&(l=1/0),i.push({line:_t.getArg(o,"generatedLine",null),column:_t.getArg(o,"generatedColumn",null),lastColumn:l}),o=this._originalMappings[++s]}}else{const a=o.originalColumn;for(;o&&o.originalLine===n&&o.originalColumn==a;){let l=o.lastGeneratedColumn;this._computedColumnSpans&&l===null&&(l=1/0),i.push({line:_t.getArg(o,"generatedLine",null),column:_t.getArg(o,"generatedColumn",null),lastColumn:l}),o=this._originalMappings[++s]}}}return i}destroy(){for(let e=0;e=0;n--)this.prepend(e[n]);else if(e[Zh]||typeof e=="string")this.children.unshift(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this}walk(e){let n;for(let r=0,i=this.children.length;r0){for(n=[],r=0;r{this.MANY(()=>this.SUBRULE(this.line))}));vt(this,"line",this.RULED("line",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt)},{ALT:()=>this.CONSUME(Wp)}])}));vt(this,"stmt",this.RULED("stmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.short_commands)),this.MANY(()=>this.SUBRULE(this.commands))}}])}));vt(this,"inline",this.RULED("inline",()=>{this.SUBRULE(this.instmt)}));vt(this,"instmt",this.RULED("instmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}])}));vt(this,"stmt_label",this.RULED("stmt_label",()=>{this.CONSUME(J3)}));vt(this,"stmt_stat",this.RULED("stmt_stat",()=>{this.CONSUME(bA)}));vt(this,"stmt_text",this.RULED("stmt_text",()=>{this.OR([{ALT:()=>this.CONSUME(Y3)}])}));vt(this,"stmt_comment",this.RULED("stmt_comment",()=>{this.CONSUME(Z3)}));vt(this,"stmt_hyperlink",this.RULED("stmt_hyperlink",()=>{this.CONSUME(Q3),this.SUBRULE(this.words),this.CONSUME(e4)}));vt(this,"stmt_command",this.RULED("stmt_command",()=>{this.CONSUME(sf),this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}));vt(this,"short_commands",this.RULED("short_commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)}])}));vt(this,"commands",this.RULED("commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.words)},{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)},{ALT:()=>this.SUBRULE(this.command_play)},{ALT:()=>this.SUBRULE(this.structured_cmd)}])}));vt(this,"structured_cmd",this.RULED("structured_cmd",()=>{this.OR([{ALT:()=>this.SUBRULE(this.command_debugger)},{ALT:()=>this.SUBRULE(this.command_if)},{ALT:()=>this.SUBRULE(this.command_while)},{ALT:()=>this.SUBRULE(this.command_repeat)},{ALT:()=>this.SUBRULE(this.command_waitfor)},{ALT:()=>this.SUBRULE(this.command_foreach)},{ALT:()=>this.SUBRULE(this.command_break)},{ALT:()=>this.SUBRULE(this.command_continue)}])}));vt(this,"short_go",this.RULED("short_go",()=>{this.CONSUME(Fw),this.SUBRULE(this.words)}));vt(this,"short_try",this.RULED("short_try",()=>{this.CONSUME(d4),this.SUBRULE(this.words)}));vt(this,"command_debugger",this.RULED("command_debugger",()=>{this.CONSUME(_4)}));vt(this,"command_if",this.RULED("command_if",()=>{this.CONSUME(Bw),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_if_block))}));vt(this,"command_if_block",this.RULED("command_if_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(w_),this.MANY(()=>this.SUBRULE(this.line)),this.MANY2({GATE:this.BACKTRACK(this.command_else_if),DEF:()=>this.SUBRULE(this.command_else_if)}),this.OPTION(()=>this.SUBRULE(this.command_else)),this.MANY3(()=>this.CONSUME3(Wp)),this.CONSUME4(sf),this.CONSUME4(zw)}}])}));vt(this,"command_block",this.RULED("command_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(w_),this.MANY(()=>this.SUBRULE(this.line)),this.CONSUME(sf),this.CONSUME(zw)}}])}));vt(this,"command_fork",this.RULED("command_fork",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(w_),this.MANY({GATE:this.BACKTRACK(this.line),DEF:()=>this.SUBRULE(this.line)})}}])}));vt(this,"command_else_if",this.RULED("command_else_if",()=>{this.CONSUME(sf),this.CONSUME(Vw),this.CONSUME(Bw),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_fork))}));vt(this,"command_else",this.RULED("command_else",()=>{this.CONSUME(sf),this.CONSUME(Vw),this.OPTION(()=>this.SUBRULE(this.command_fork))}));vt(this,"command_while",this.RULED("command_while",()=>{this.CONSUME(v4),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));vt(this,"command_repeat",this.RULED("command_repeat",()=>{this.CONSUME(y4),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));vt(this,"command_waitfor",this.RULED("command_waitfor",()=>{this.CONSUME(x4),this.SUBRULE(this.words)}));vt(this,"command_foreach",this.RULED("command_foreach",()=>{this.CONSUME(S4),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));vt(this,"command_break",this.RULED("command_break",()=>{this.CONSUME(E4)}));vt(this,"command_continue",this.RULED("command_continue",()=>{this.CONSUME(w4)}));vt(this,"command_play",this.RULED("command_play",()=>{this.CONSUME(g4)}));vt(this,"expr",this.RULED("expr",()=>{this.SUBRULE1(this.and_test),this.MANY(()=>{this.CONSUME(Ow),this.SUBRULE2(this.and_test)})}));vt(this,"and_test",this.RULED("and_test",()=>{this.SUBRULE1(this.not_test),this.MANY(()=>{this.CONSUME(Pw),this.SUBRULE2(this.not_test)})}));vt(this,"not_test",this.RULED("not_test",()=>{this.OR([{ALT:()=>{this.CONSUME(Lw),this.SUBRULE1(this.not_test)}},{ALT:()=>this.SUBRULE2(this.comparison)}])}));vt(this,"comparison",this.RULED("comparison",()=>{this.SUBRULE1(this.arith_expr),this.MANY(()=>{this.SUBRULE(this.comp_op),this.SUBRULE2(this.arith_expr)})}));vt(this,"comp_op",this.RULED("comp_op",()=>{this.OR([{ALT:()=>this.CONSUME(r4)},{ALT:()=>this.CONSUME(i4)},{ALT:()=>this.CONSUME(s4)},{ALT:()=>this.CONSUME(o4)},{ALT:()=>this.CONSUME(a4)},{ALT:()=>this.CONSUME(l4)}])}));vt(this,"expr_value",this.RULED("expr_value",()=>{this.SUBRULE1(this.and_test_value),this.MANY(()=>{this.CONSUME(Ow),this.SUBRULE2(this.and_test_value)})}));vt(this,"and_test_value",this.RULED("and_test_value",()=>{this.SUBRULE1(this.not_test_value),this.MANY(()=>{this.CONSUME(Pw),this.SUBRULE2(this.not_test_value)})}));vt(this,"not_test_value",this.RULED("not_test_value",()=>{this.OR([{ALT:()=>{this.CONSUME(Lw),this.SUBRULE1(this.not_test_value)}},{ALT:()=>this.SUBRULE2(this.arith_expr)}])}));vt(this,"arith_expr",this.RULED("arith_expr",()=>{this.SUBRULE1(this.term),this.MANY(()=>this.SUBRULE2(this.arith_expr_item))}));vt(this,"arith_expr_item",this.RULED("arith_expr_item",()=>{this.OR([{ALT:()=>this.CONSUME(Dw)},{ALT:()=>this.CONSUME(Uw)}]),this.SUBRULE(this.term)}));vt(this,"term",this.RULED("term",()=>{this.SUBRULE1(this.factor),this.MANY(()=>this.SUBRULE2(this.term_item))}));vt(this,"term_item",this.RULED("term_item",()=>{this.OR([{ALT:()=>this.CONSUME(u4)},{ALT:()=>this.CONSUME(Fw)},{ALT:()=>this.CONSUME(h4)},{ALT:()=>this.CONSUME(f4)}]),this.SUBRULE(this.factor)}));vt(this,"factor",this.RULED("factor",()=>{this.OR1([{ALT:()=>{this.OR2([{ALT:()=>this.CONSUME(Dw)},{ALT:()=>this.CONSUME(Uw)}]),this.SUBRULE(this.factor)}},{ALT:()=>this.SUBRULE(this.power)}])}));vt(this,"power",this.RULED("power",()=>{this.SUBRULE(this.token),this.OPTION(()=>{this.CONSUME(c4),this.SUBRULE(this.factor)})}));vt(this,"words",this.RULED("words",()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.expr))}));vt(this,"token",this.RULED("token",()=>{this.OR([{ALT:()=>this.CONSUME(t4)},{ALT:()=>this.CONSUME(Wi)},{ALT:()=>this.CONSUME(n4)},{ALT:()=>{this.CONSUME(p4),this.SUBRULE(this.expr),this.CONSUME(m4)}}])}));this.performSelfAnalysis()}PEEK(n,r,...i){console.info(n,i.map(s=>[s.image,s.tokenType]),r)}RULED(n,r,i){const s=gfe.some(o=>n.includes(o));return this.RULE(n,()=>{const a=(cI++).toString().padStart(3),l=s?"font-weight: bold;":"";if(uI&&!this.RECORDING_PHASE){const c=[this.LA(1),this.LA(2),this.LA(3)].map(u=>`[${u.tokenType.name} ${u.image.replaceAll(` +`,"\\n")}]`);console.info(`${a}%c> ${n} ${c.join(" ")}`,l)}r(),uI&&!this.RECORDING_PHASE&&console.info(`${a}%c< ${n} `,l),cI--},i)}}const pf=new _fe;if(Lne){const t=pf.getGAstProductions(),e=Yce(t);console.info(e)}const vfe=pf.getBaseCstVisitorConstructor();var Ke=(t=>(t[t.PROGRAM=0]="PROGRAM",t[t.API=1]="API",t[t.LINE=2]="LINE",t[t.MARK=3]="MARK",t[t.GOTO=4]="GOTO",t[t.COUNT=5]="COUNT",t[t.TEXT=6]="TEXT",t[t.LABEL=7]="LABEL",t[t.HYPERLINK=8]="HYPERLINK",t[t.STAT=9]="STAT",t[t.MOVE=10]="MOVE",t[t.COMMAND=11]="COMMAND",t[t.LITERAL=12]="LITERAL",t[t.IF=13]="IF",t[t.IF_CHECK=14]="IF_CHECK",t[t.IF_BLOCK=15]="IF_BLOCK",t[t.ELSE_IF=16]="ELSE_IF",t[t.ELSE=17]="ELSE",t[t.WHILE=18]="WHILE",t[t.BREAK=19]="BREAK",t[t.CONTINUE=20]="CONTINUE",t[t.REPEAT=21]="REPEAT",t[t.WAITFOR=22]="WAITFOR",t[t.FOREACH=23]="FOREACH",t[t.OR=24]="OR",t[t.AND=25]="AND",t[t.NOT=26]="NOT",t[t.COMPARE=27]="COMPARE",t[t.COMPARE_ITEM=28]="COMPARE_ITEM",t[t.OPERATOR=29]="OPERATOR",t[t.OPERATOR_ITEM=30]="OPERATOR_ITEM",t[t.EXPR=31]="EXPR",t))(Ke||{}),Eu=(t=>(t[t.IS_EQ=0]="IS_EQ",t[t.IS_NOT_EQ=1]="IS_NOT_EQ",t[t.IS_LESS_THAN=2]="IS_LESS_THAN",t[t.IS_GREATER_THAN=3]="IS_GREATER_THAN",t[t.IS_LESS_THAN_OR_EQ=4]="IS_LESS_THAN_OR_EQ",t[t.IS_GREATER_THAN_OR_EQ=5]="IS_GREATER_THAN_OR_EQ",t))(Eu||{}),oa=(t=>(t[t.EMPTY=0]="EMPTY",t[t.PLUS=1]="PLUS",t[t.MINUS=2]="MINUS",t[t.POWER=3]="POWER",t[t.MULTIPLY=4]="MULTIPLY",t[t.DIVIDE=5]="DIVIDE",t[t.MOD_DIVIDE=6]="MOD_DIVIDE",t[t.FLOOR_DIVIDE=7]="FLOOR_DIVIDE",t[t.UNI_PLUS=8]="UNI_PLUS",t[t.UNI_MINUS=9]="UNI_MINUS",t))(oa||{}),T_=(t=>(t[t.NUMBER=0]="NUMBER",t[t.STRING=1]="STRING",t[t.TEMPLATE=2]="TEMPLATE",t))(T_||{});function yfe(t){return!!(t!=null&&t.tokenType)}function ll(t,e){const[n]=t??[];return((n==null?void 0:n.image)??e).trimStart().replaceAll(/^"|"$/g,"")}class xfe extends vfe{constructor(){super();vt(this,"unique",0);Ca&&this.validateVisitor()}getnodelocation(n){const r=Object.values(n).flat().filter(i=>!!i).map(i=>i&&yfe(i)?{startLine:i.startLine,startColumn:i.startColumn,startOffset:i.startOffset,endLine:i.endLine,endColumn:i.endColumn,endOffset:i.endOffset}:i!=null&&i.location?{...i.location}:{startLine:0,startColumn:0,startOffset:0,endLine:0,endColumn:0,endOffset:0}).filter(i=>i.startLine!==0&&i.endLine!==0);return{startLine:Math.min(...r.map(i=>i.startLine??1)),startColumn:Math.min(...r.map(i=>i.startColumn??1)),startOffset:Math.min(...r.map(i=>i.startOffset??1)),endLine:Math.max(...r.map(i=>i.endLine??1)),endColumn:Math.max(...r.map(i=>i.endColumn??1)),endOffset:Math.max(...r.map(i=>i.endOffset??1))}}createcodenode(n,r){return[{...r,...this.getnodelocation(n),lineindex:0}]}createstringnode(n,r){return this.createcodenode(n,{type:12,literal:1,value:r})}createmarknode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:3,id:r,comment:i}))}creategotonode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:4,id:r,comment:i}))}createlinenode(n,r){return this.createcodenode(n,{type:2,stmts:r})}createapinode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:1,words:i,method:r}))}createlogicnode(n,r,i,s){return this.createlinenode(n,this.createcodenode(n,{type:14,skip:i,words:s,method:r}))}createcountnode(n){return this.createcodenode(n,{type:5,index:this.unique++})}go(n){return Array.isArray(n)?n.map(r=>this.visit(r)).flat():Z(n)?[this.visit(n)].flat():[]}program(n){return this.unique=0,this.createcodenode(n,{type:0,lines:[this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:"restart"})),this.go(n.line)].flat()})}line(n){return n.stmt?this.go(n.stmt):[]}stmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.short_commands?[this.go(n.short_commands),this.go(n.commands)].flat():[]}inline(n){return this.go(n.instmt)}instmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.commands?this.go(n.commands):[]}stmt_label(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:ll(n.token_label,":").slice(1).trim()}))}stmt_stat(n){return this.createlinenode(n,this.createcodenode(n,{type:9,value:ll(n.token_stat,"@").slice(1)}))}stmt_text(n){return this.createlinenode(n,this.createcodenode(n,{type:6,value:ll(n.token_text,"")}))}stmt_comment(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!1,name:ll(n.token_comment,"'").slice(1).trim()}))}stmt_hyperlink(n){return this.createlinenode(n,this.createcodenode(n,{type:8,link:this.go(n.words),text:ll(n.token_hyperlinktext,";").slice(1)}))}stmt_command(n){return n.commands?this.go(n.commands):[]}short_commands(n){return n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):[]}commands(n){return n.words?this.createlinenode(n,this.createcodenode(n,{type:11,words:this.go(n.words)})):n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):n.command_play?this.go(n.command_play):n.structured_cmd?this.go(n.structured_cmd):[]}structured_cmd(n){return n.command_if?this.go(n.command_if):n.command_while?this.go(n.command_while):n.command_repeat?this.go(n.command_repeat):n.command_waitfor?this.go(n.command_waitfor):n.command_foreach?this.go(n.command_foreach):n.command_break?this.go(n.command_break):n.command_continue?this.go(n.command_continue):[]}short_go(n){return n.token_divide?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!0,words:this.go(n.words)})):[]}short_try(n){return n.token_query?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!1,words:this.go(n.words)})):[]}command_if(n){const[r]=this.createlogicnode(n,"if","",this.go(n.words)),[i]=this.go(n.command_if_block)??[];return this.createcodenode(n,{type:13,check:r,block:i})}command_if_block(n){const r=fr(),i=fr();return this.createcodenode(n,{type:15,skip:r,done:i,lines:[this.go(n.inline),this.go(n.line),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"alt logic")].flat(),altlines:[this.go(n.command_else_if),this.go(n.command_else),this.createmarknode(n,i,"end of if")].flat()})}command_block(n){return[this.go(n.inline),this.go(n.line)].flat()}command_fork(n){return[this.go(n.inline),this.go(n.line)].flat()}command_else_if(n){const r=fr(),i=fr();return this.createcodenode(n,{type:16,done:i,lines:[this.createlogicnode(n,"if",r,this.go(n.words)),this.go(n.command_fork),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"skip")].flat()})}command_else(n){return this.createcodenode(n,{type:17,lines:this.go(n.command_fork)})}command_while(n){const r=fr(),i=fr();return this.createcodenode(n,{type:18,loop:r,done:i,lines:[this.createmarknode(n,r,"start of while"),this.createlogicnode(n,"if",i,this.go(n.words)),this.go(n.command_block),this.creategotonode(n,r,"loop of while"),this.createmarknode(n,i,"end of while")].flat()})}command_repeat(n){const r=fr(),i=fr(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:21,loop:r,done:i,lines:[this.createapinode(n,"repeatstart",o),this.createmarknode(n,r,"start of repeat"),this.createlogicnode(n,"repeat",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of repeat"),this.createmarknode(n,i,"end of repeat")].flat()})}command_foreach(n){const r=fr(),i=fr(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:23,loop:r,done:i,lines:[this.createapinode(n,"foreachstart",o),this.createmarknode(n,r,"start of foreach"),this.createlogicnode(n,"foreach",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of foreach"),this.createmarknode(n,i,"end of foreach")].flat()})}command_waitfor(n){return this.createcodenode(n,{type:22,words:this.go(n.words)})}command_break(n){return this.createcodenode(n,{type:19,goto:0})}command_continue(n){return this.createcodenode(n,{type:20,goto:0})}command_play(n){const r=ll(n.token_command_play,""),i=r.replace("bgplay","").replace("play","").trim(),s=r.includes("bgplay");return this.createlinenode(n,this.createcodenode(n,{type:11,words:[this.createstringnode(n,s?"bgplay":"play"),this.createstringnode(n,i)].flat()}))}expr(n){return n.and_test.length===1?this.go(n.and_test):this.createcodenode(n,{type:24,items:this.go(n.and_test)})}and_test(n){return n.not_test.length===1?this.go(n.not_test):this.createcodenode(n,{type:25,items:this.go(n.not_test)})}not_test(n){return n.comparison?this.go(n.comparison):n.not_test?this.createcodenode(n,{type:26,items:this.go(n.not_test)}):[]}comparison(n){if(n.arith_expr.length===1)return this.go(n.arith_expr);const[r,i]=this.go(n.arith_expr),[s]=this.go(n.comp_op);return this.createcodenode(n,{type:27,lhs:r,compare:s,rhs:i})}comp_op(n){return n.token_iseq?this.createcodenode(n,{type:28,method:0}):n.token_isnoteq?this.createcodenode(n,{type:28,method:1}):n.token_islessthan?this.createcodenode(n,{type:28,method:2}):n.token_isgreaterthan?this.createcodenode(n,{type:28,method:3}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:4}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:5}):[]}expr_value(n){return n.and_test_value.length===1?this.go(n.and_test_value):this.createcodenode(n,{type:24,items:this.go(n.and_test_value)})}and_test_value(n){return n.not_test_value.length===1?this.go(n.not_test_value):this.createcodenode(n,{type:25,items:this.go(n.not_test_value)})}not_test_value(n){return n.arith_expr?this.go(n.arith_expr):n.not_test_value?this.createcodenode(n,{type:26,items:this.go(n.not_test_value)}):[]}arith_expr(n){const r=this.go(n.term);return n.arith_expr_item?this.createcodenode(n,{type:29,lhs:r[0],items:this.go(n.arith_expr_item)}):r}arith_expr_item(n){return this.createcodenode(n,{type:30,operator:n.token_plus?1:2,rhs:this.go(n.term)[0]})}term(n){return n.term_item?this.createcodenode(n,{type:29,lhs:this.go(n.factor)[0],items:this.go(n.term_item)}):this.go(n.factor)}term_item(n){let r=0;return n.token_multiply&&(r=4),n.token_divide&&(r=5),n.token_moddivide&&(r=6),n.token_floordivide&&(r=7),this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})}factor(n){if(n.power)return this.go(n.power);let r=0;return n.token_plus&&(r=8),n.token_minus&&(r=9),this.createcodenode(n,{type:29,lhs:void 0,items:this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})})}power(n){const r=this.go(n.token);return n.factor?this.createcodenode(n,{type:29,lhs:r[0],items:this.createcodenode(n,{type:30,operator:3,rhs:this.go(n.factor)[0]})}):r}words(n){return this.go(n.expr)}token(n){if(n.token_stringliteraldouble){const r=ll(n.token_stringliteraldouble,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:2,value:r})}if(n.token_stringliteral){const r=ll(n.token_stringliteral,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:1,value:r})}if(n.token_numberliteral){const r=parseFloat(ll(n.token_numberliteral,"0"));return this.createcodenode(n,{type:12,literal:0,value:r})}return n.token_lparen?this.createcodenode(n,{type:31,words:this.go(n.expr)}):[]}}const Sfe=new xfe,ns={labels:{},internal:0,lineindex:0,linelookup:{},isfirststat:!1},jy="zss.js";function sn(t,e){return new mfe(t.startLine??1,t.startColumn??1,jy,e)}function $w(t){return t.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function C1(t){return`'${$w(t)}'`}function b_(t){if(t.startsWith('"'))return b_(t.replaceAll(/(^"|"$)/g,""));const e=qy(t);return e.errors.length?t:`['${e.tokens.map(r=>r.tokenType===UA?`', api.get('${$w(r.image.substring(1))}'), '`:$w(r.image)).join("")}'].join('')`}function _u(t){return t.filter(e=>e!==void 0).map(xn)}function hI(t){return sn(t,"")}function Efe(t,e){const n=[];return t.forEach(r=>{n.push(r,e)}),n.pop(),n}function Mr(t,e,n){return sn(t,[`api.${e}(`,...Efe(n,", "),")"])}function wfe(t){if(t.type===Ke.COMPARE&&t.compare.type===Ke.COMPARE_ITEM)switch(t.compare.method){case Eu.IS_EQ:return Mr(t,"isEq",[xn(t.lhs),xn(t.rhs)]);case Eu.IS_NOT_EQ:return Mr(t,"isNotEq",[xn(t.lhs),xn(t.rhs)]);case Eu.IS_LESS_THAN:return Mr(t,"isLessThan",[xn(t.lhs),xn(t.rhs)]);case Eu.IS_GREATER_THAN:return Mr(t,"isGreaterThan",[xn(t.lhs),xn(t.rhs)]);case Eu.IS_LESS_THAN_OR_EQ:return Mr(t,"isLessThanOrEq",[xn(t.lhs),xn(t.rhs)]);case Eu.IS_GREATER_THAN_OR_EQ:return Mr(t,"isGreaterThanOrEq",[xn(t.lhs),xn(t.rhs)])}return sn(t,"")}function vu(t,e,n){return t.prepend(`api.${e}(`),t.add([", ",xn(n),")"])}function fI(t,e,n){return t.prepend(`api.${e}(`),t.add([xn(n),")"])}function Tfe(t,e){if(t.type===Ke.OPERATOR_ITEM)switch(t.operator){case oa.PLUS:return vu(e,"opPlus",t.rhs);case oa.MINUS:return vu(e,"opMinus",t.rhs);case oa.POWER:return vu(e,"opPower",t.rhs);case oa.MULTIPLY:return vu(e,"opMultiply",t.rhs);case oa.DIVIDE:return vu(e,"opDivide",t.rhs);case oa.MOD_DIVIDE:return vu(e,"opModDivide",t.rhs);case oa.FLOOR_DIVIDE:return vu(e,"opFloorDivide",t.rhs);case oa.UNI_PLUS:return fI(e,"opUniPlus",t.rhs);case oa.UNI_MINUS:return fI(e,"opUniMinus",t.rhs)}return sn(t,"")}function bfe(t){if(t.type===Ke.OPERATOR){const e=t.lhs?xn(t.lhs):sn(t,"");return t.items.forEach(n=>Tfe(n,e)),e}return sn(t,"")}function V0(t,e){return sn(t,[Mr(t,"jump",[`${e}`]),"; continue;"])}function cl(t){return ns.linelookup[t??""]??-1}function qw(t,e){ns.linelookup[t]=e}function ap(t,e,n){for(let r=0;rr.add(xn(i))),K4(n.altlines,Ke.ELSE_IF,cl(n.done)),n.altlines.forEach(i=>r.add(xn(i))),r}return sn(t,xn(t.check))}case Ke.IF_CHECK:{const n=cl(t.skip);return n===-1?sn(t,[" ",Mr(t,t.method,_u(t.words)),`; +`]):sn(t,[" if (!",Mr(t,t.method,_u(t.words)),") { ",V0(t,n),` } +`])}case Ke.ELSE_IF:case Ke.ELSE:{const n=sn(t,"");return t.lines.forEach(r=>n.add(xn(r))),n}case Ke.WHILE:{const n=cl(t.loop),r=cl(t.done),i=sn(t,"");return ap(t.lines,Ke.IF_CHECK,t.done),t.lines.forEach(s=>{switch(s.type){case Ke.BREAK:s.goto=r;break;case Ke.CONTINUE:s.goto=n;break}i.add(xn(s))}),i}case Ke.REPEAT:{const n=cl(t.loop),r=cl(t.done),i=sn(t,"");return ap(t.lines,Ke.IF_CHECK,t.done),t.lines.forEach(s=>{switch(s.type){case Ke.BREAK:s.goto=r;break;case Ke.CONTINUE:s.goto=n;break}i.add(xn(s))}),i}case Ke.WAITFOR:{const n=sn(t,"");return n.add([" if (!",Mr(t,"if",_u(t.words)),`) { api.i(${t.lineindex-1}); } +`]),n}case Ke.FOREACH:{const n=cl(t.loop),r=cl(t.done),i=sn(t,"");return ap(t.lines,Ke.IF_CHECK,t.done),t.lines.forEach(s=>{switch(s.type){case Ke.BREAK:s.goto=r;break;case Ke.CONTINUE:s.goto=n;break}i.add(xn(s))}),i}case Ke.BREAK:return sn(t,[" ",V0(t,t.goto),` +`]);case Ke.CONTINUE:return sn(t,[" ",V0(t,t.goto),` +`]);case Ke.OR:return Mr(t,"or",t.items.map(xn));case Ke.AND:return Mr(t,"and",t.items.map(xn));case Ke.NOT:return Mr(t,"not",t.items.map(xn));case Ke.COMPARE:return wfe(t);case Ke.OPERATOR:return bfe(t);case Ke.EXPR:return Mr(t,"expr",t.words.map(xn));default:return console.error("",t.type,t),hI(t)}}function aa(t){if(Z(t))switch(t.type===Ke.LINE&&++ns.lineindex,t.lineindex=ns.lineindex,t.type){case Ke.PROGRAM:t.lines.forEach(aa);break;case Ke.LINE:t.stmts.forEach(aa);break;case Ke.MARK:qw(t.id,t.lineindex);break;case Ke.IF:aa(t.check),aa(t.block);break;case Ke.IF_BLOCK:t.lines.forEach(aa),t.altlines.forEach(aa);break;case Ke.ELSE_IF:t.lines.forEach(aa);break;case Ke.ELSE:case Ke.WHILE:case Ke.REPEAT:case Ke.FOREACH:t.lines.forEach(aa);break;case Ke.MOVE:case Ke.COMMAND:case Ke.WAITFOR:case Ke.IF_CHECK:t.words.forEach(aa);break}}function Afe(t){return ns.labels={},ns.internal=1,ns.lineindex=0,ns.isfirststat=!0,aa(t),{...xn(t).toStringWithSourceMap({file:`${jy}.map`}),...ns}}const Mfe={HALT_AT_COUNT:256};function Cfe(t){return ln(t)?t.length>0?1:0:t??0}function ti(t){return`${t??""}`}function Rfe(t){return`${t}_chip`}function Nfe(t,e,n){var l,c;const r=Rfe(t),i=jp(r);let s;ln(i.lb)||(i.lb=xT(Object.entries(n.labels??{})),i.lk="",i.mg=void 0,i.ec=1,i.lc=0,i.ys=0,i.ps=0,i.es=(((l=n.errors)==null?void 0:l.length)??0)!==0?1:0);function o(u,h){se.words=h,se.get=a.get;const p=Hhe(e,u);return Z(p)?p(a,h):u!=="send"?o("send",[u,...h]):0}const a={halt(){Ffe(r)},id(){return t},senderid(u=t){return`vm:${u??t}`},set(u,h){const[p,m]=Whe(e,a,u,h);if(p)return m},get(u){const[h,p]=Ghe(e,a,u);if(h)return p},bucket(u){const h=a.get("bucket");ln(h)?h.push(u):a.set("bucket",[u])},tick(u){const h=mt(i.ps)?i.ps:0,p=h%u===0;if(i.ps=h+1,p===!1)return!1;if(a.shouldtick()===!1)return oI(e,a),!1;i.lc=0,i.ys=0,jhe(e,a);try{const m=s==null?void 0:s.next();m!=null&&m.done&&(Pn("chip","crash","generator logic unexpectedly exited"),i.es=1)}catch(m){Pn("chip","crash",m.message),i.es=1}return oI(e,a),!0},isended(){return i.es===1},shouldtick(){return i.es===0||a.hm()!==0},shouldhalt(){return mt(i.lc)?++i.lc>Mfe.HALT_AT_COUNT:!0},hm(){if(ln(i.mg)&&ln(i.lb)){const[,u]=i.mg;if(Z(u))for(let h=0;hmt(g)&&g>0)??0}}return 0},yield(){i.ys=1},jump(u){i.ec=u},sy(){return!!i.ys||a.shouldhalt()},emit(u,h,p){Yt.emit(u,a.senderid(),h,p)},send(u,h,p,m){Yt.emit(`${a.senderid(u)}:${h}`,t,p,m)},lock(u){i.lk=u},unlock(){i.lk=""},message(u){i.lk&&u.sender!==i.lk||(i.mg=[u.id,u.target,u.data,u.sender,u.player])},zap(u){if(ln(i.lb))for(let h=0;hv>0);g>=0&&(m[g]*=-1)}}},restore(u){if(ln(i.lb))for(let h=0;hm.fileName===jy);return{line:(p==null?void 0:p.lineNumber)??0,column:(p==null?void 0:p.columnNumber)??0}},text(u){return o("text",[u])},stat(...u){return o("stat",u)},hyperlink(...u){return o("hyperlink",u)},command(...u){if(u.length===0)return 0;const[h,...p]=u;return o(ti(h),p)},if(...u){const[h,p]=He(u,0,[Ie.ANY]),m=Cfe(h);return m&&p0,v=i[p];return g&&ln(v)&&a.command(...v),g?1:0},foreachstart(u,...h){const[p,m,g,v]=He(h,0,[Ie.STRING,Ie.NUMBER,Ie.NUMBER,Ie.MAYBE_NUMBER]);let y=Math.min(m,g),_=Math.max(m,g);const S=(v??0)||1;if(S<0){const E=y;y=_,_=E}return a.set(p,y-S),0},foreach(u,...h){const[p,m,g,v,y]=He(h,0,[Ie.STRING,Ie.NUMBER,Ie.NUMBER,Ie.MAYBE_NUMBER]);let _=Math.min(m,g),S=Math.max(m,g);const E=(v??0)||1;if(E<0){const R=_;_=S,S=R}let T=a.get(p);!mt(T)||T<_||T>S?T=_:T+=E;const N=T<=S?1:0;return N&&(a.set(p,T),ym?1:0},isLessThanOrEq(u,h){const[p]=He([u],0,[Ie.NUMBER]),[m]=He([h],0,[Ie.NUMBER]);return p<=m?1:0},isGreaterThanOrEq(u,h){const[p]=He([u],0,[Ie.NUMBER]),[m]=He([h],0,[Ie.NUMBER]);return p>=m?1:0},opPlus(u,h){const[p]=He([u],0,[Ie.ANY]),[m]=He([h],0,[Ie.ANY]);return p+m},opMinus(u,h){const[p]=He([u],0,[Ie.ANY]),[m]=He([h],0,[Ie.ANY]);return p-m},opPower(u,h){const[p]=He([u],0,[Ie.NUMBER]),[m]=He([h],0,[Ie.NUMBER]);return Math.pow(p,m)},opMultiply(u,h){const[p]=He([u],0,[Ie.NUMBER]),[m]=He([h],0,[Ie.NUMBER]);return p*m},opDivide(u,h){const[p]=He([u],0,[Ie.NUMBER]),[m]=He([h],0,[Ie.NUMBER]);return p/m},opModDivide(u,h){const[p]=He([u],0,[Ie.NUMBER]),[m]=He([h],0,[Ie.NUMBER]);return p%m},opFloorDivide(u,h){const[p]=He([u],0,[Ie.NUMBER]),[m]=He([h],0,[Ie.NUMBER]);return Math.floor(p/m)},opUniPlus(u){const[h]=He([u],0,[Ie.NUMBER]);return+h},opUniMinus(u){const[h]=He([u],0,[Ie.NUMBER]);return-h}};return s=(c=n.code)==null?void 0:c.call(n,a),a}function H0(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var kfe={exports:{}};/*! + +JSZip v3.10.1 - A JavaScript class for generating and reading zip files + + +(c) 2009-2016 Stuart Knightley +Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. + +JSZip uses the library pako released under the MIT license : +https://github.com/nodeca/pako/blob/main/LICENSE +*/(function(t,e){(function(n){t.exports=n()})(function(){return function n(r,i,s){function o(c,u){if(!i[c]){if(!r[c]){var h=typeof H0=="function"&&H0;if(!u&&h)return h(c,!0);if(a)return a(c,!0);var p=new Error("Cannot find module '"+c+"'");throw p.code="MODULE_NOT_FOUND",p}var m=i[c]={exports:{}};r[c][0].call(m.exports,function(g){var v=r[c][1][g];return o(v||g)},m,m.exports,n,r,i,s)}return i[c].exports}for(var a=typeof H0=="function"&&H0,l=0;l>2,m=(3&c)<<4|u>>4,g=1>6:64,v=2>4,u=(15&p)<<4|(m=a.indexOf(l.charAt(v++)))>>2,h=(3&m)<<6|(g=a.indexOf(l.charAt(v++))),S[y++]=c,m!==64&&(S[y++]=u),g!==64&&(S[y++]=h);return S}},{"./support":30,"./utils":32}],2:[function(n,r,i){var s=n("./external"),o=n("./stream/DataWorker"),a=n("./stream/Crc32Probe"),l=n("./stream/DataLengthProbe");function c(u,h,p,m,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=p,this.compression=m,this.compressedContent=g}c.prototype={getContentWorker:function(){var u=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},c.createWorkerFrom=function(u,h,p){return u.pipe(new a).pipe(new l("uncompressedSize")).pipe(h.compressWorker(p)).pipe(new l("compressedSize")).withStreamInfo("compression",h)},r.exports=c},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,i){var s=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,i){var s=n("./utils"),o=function(){for(var a,l=[],c=0;c<256;c++){a=c;for(var u=0;u<8;u++)a=1&a?3988292384^a>>>1:a>>>1;l[c]=a}return l}();r.exports=function(a,l){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(c,u,h,p){var m=o,g=p+h;c^=-1;for(var v=p;v>>8^m[255&(c^u[v])];return-1^c}(0|l,a,a.length,0):function(c,u,h,p){var m=o,g=p+h;c^=-1;for(var v=p;v>>8^m[255&(c^u.charCodeAt(v))];return-1^c}(0|l,a,a.length,0):0}},{"./utils":32}],5:[function(n,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,r,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),a=n("./utils"),l=n("./stream/GenericWorker"),c=s?"uint8array":"array";function u(h,p){l.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=p,this.meta={}}i.magic="\b\0",a.inherits(u,l),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(c,h.data),!1)},u.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(p){h.push({data:p,meta:h.meta})}},i.compressWorker=function(h){return new u("Deflate",h)},i.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(m,g){var v,y="";for(v=0;v>>=8;return y}function o(m,g,v,y,_,S){var E,T,N=m.file,R=m.compression,C=S!==c.utf8encode,O=a.transformTo("string",S(N.name)),M=a.transformTo("string",c.utf8encode(N.name)),I=N.comment,U=a.transformTo("string",S(I)),L=a.transformTo("string",c.utf8encode(I)),P=M.length!==N.name.length,b=L.length!==I.length,H="",V="",B="",z=N.dir,W=N.date,K={crc32:0,compressedSize:0,uncompressedSize:0};g&&!v||(K.crc32=m.crc32,K.compressedSize=m.compressedSize,K.uncompressedSize=m.uncompressedSize);var j=0;g&&(j|=8),C||!P&&!b||(j|=2048);var Y=0,ge=0;z&&(Y|=16),_==="UNIX"?(ge=798,Y|=function(re,we){var Ae=re;return re||(Ae=we?16893:33204),(65535&Ae)<<16}(N.unixPermissions,z)):(ge=20,Y|=function(re){return 63&(re||0)}(N.dosPermissions)),E=W.getUTCHours(),E<<=6,E|=W.getUTCMinutes(),E<<=5,E|=W.getUTCSeconds()/2,T=W.getUTCFullYear()-1980,T<<=4,T|=W.getUTCMonth()+1,T<<=5,T|=W.getUTCDate(),P&&(V=s(1,1)+s(u(O),4)+M,H+="up"+s(V.length,2)+V),b&&(B=s(1,1)+s(u(U),4)+L,H+="uc"+s(B.length,2)+B);var Q="";return Q+=` +\0`,Q+=s(j,2),Q+=R.magic,Q+=s(E,2),Q+=s(T,2),Q+=s(K.crc32,4),Q+=s(K.compressedSize,4),Q+=s(K.uncompressedSize,4),Q+=s(O.length,2),Q+=s(H.length,2),{fileRecord:h.LOCAL_FILE_HEADER+Q+O+H,dirRecord:h.CENTRAL_FILE_HEADER+s(ge,2)+Q+s(U.length,2)+"\0\0\0\0"+s(Y,4)+s(y,4)+O+H+U}}var a=n("../utils"),l=n("../stream/GenericWorker"),c=n("../utf8"),u=n("../crc32"),h=n("../signature");function p(m,g,v,y){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=v,this.encodeFileName=y,this.streamFiles=m,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(p,l),p.prototype.push=function(m){var g=m.meta.percent||0,v=this.entriesCount,y=this._sources.length;this.accumulate?this.contentBuffer.push(m):(this.bytesWritten+=m.data.length,l.prototype.push.call(this,{data:m.data,meta:{currentFile:this.currentFile,percent:v?(g+100*(v-y-1))/v:100}}))},p.prototype.openedSource=function(m){this.currentSourceOffset=this.bytesWritten,this.currentFile=m.file.name;var g=this.streamFiles&&!m.file.dir;if(g){var v=o(m,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:v.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(m){this.accumulate=!1;var g=this.streamFiles&&!m.file.dir,v=o(m,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(v.dirRecord),g)this.push({data:function(y){return h.DATA_DESCRIPTOR+s(y.crc32,4)+s(y.compressedSize,4)+s(y.uncompressedSize,4)}(m),meta:{percent:100}});else for(this.push({data:v.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var m=this.bytesWritten,g=0;g=this.index;l--)c=(c<<8)+this.byteAt(l);return this.index+=a,c},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},r.exports=o},{"../utils":32}],19:[function(n,r,i){var s=n("./Uint8ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,i){var s=n("./DataReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,r,i){var s=n("./ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var l=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,i){var s=n("../utils"),o=n("../support"),a=n("./ArrayReader"),l=n("./StringReader"),c=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var p=s.getTypeOf(h);return s.checkSupport(p),p!=="string"||o.uint8array?p==="nodebuffer"?new c(h):o.uint8array?new u(s.transformTo("uint8array",h)):new a(s.transformTo("array",h)):new l(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,i){var s=n("./GenericWorker"),o=n("../utils");function a(l){s.call(this,"ConvertWorker to "+l),this.destType=l}o.inherits(a,s),a.prototype.processChunk=function(l){this.push({data:o.transformTo(this.destType,l.data),meta:l.meta})},r.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,i){var s=n("./GenericWorker"),o=n("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(a,s),a.prototype.processChunk=function(l){this.streamInfo.crc32=o(l.data,this.streamInfo.crc32||0),this.push(l)},r.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(l){o.call(this,"DataLengthProbe for "+l),this.propName=l,this.withStreamInfo(l,0)}s.inherits(a,o),a.prototype.processChunk=function(l){if(l){var c=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=c+l.data.length}o.prototype.processChunk.call(this,l)},r.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(l){o.call(this,"DataWorker");var c=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,l.then(function(u){c.dataIsReady=!0,c.data=u,c.max=u&&u.length||0,c.type=s.getTypeOf(u),c.isPaused||c._tickAndRepeat()},function(u){c.error(u)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var l=null,c=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":l=this.data.substring(this.index,c);break;case"uint8array":l=this.data.subarray(this.index,c);break;case"array":case"nodebuffer":l=this.data.slice(this.index,c)}return this.index=c,this.push({data:l,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var l=0;l "+o:o}},r.exports=s},{}],29:[function(n,r,i){var s=n("../utils"),o=n("./ConvertWorker"),a=n("./GenericWorker"),l=n("../base64"),c=n("../support"),u=n("../external"),h=null;if(c.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(g,v){return new u.Promise(function(y,_){var S=[],E=g._internalType,T=g._outputType,N=g._mimeType;g.on("data",function(R,C){S.push(R),v&&v(C)}).on("error",function(R){S=[],_(R)}).on("end",function(){try{var R=function(C,O,M){switch(C){case"blob":return s.newBlob(s.transformTo("arraybuffer",O),M);case"base64":return l.encode(O);default:return s.transformTo(C,O)}}(T,function(C,O){var M,I=0,U=null,L=0;for(M=0;M"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,i){for(var s=n("./utils"),o=n("./support"),a=n("./nodejsUtils"),l=n("./stream/GenericWorker"),c=new Array(256),u=0;u<256;u++)c[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;c[254]=c[254]=1;function h(){l.call(this,"utf-8 decode"),this.leftOver=null}function p(){l.call(this,"utf-8 encode")}i.utf8encode=function(m){return o.nodebuffer?a.newBufferFrom(m,"utf-8"):function(g){var v,y,_,S,E,T=g.length,N=0;for(S=0;S>>6:(y<65536?v[E++]=224|y>>>12:(v[E++]=240|y>>>18,v[E++]=128|y>>>12&63),v[E++]=128|y>>>6&63),v[E++]=128|63&y);return v}(m)},i.utf8decode=function(m){return o.nodebuffer?s.transformTo("nodebuffer",m).toString("utf-8"):function(g){var v,y,_,S,E=g.length,T=new Array(2*E);for(v=y=0;v>10&1023,T[y++]=56320|1023&_)}return T.length!==y&&(T.subarray?T=T.subarray(0,y):T.length=y),s.applyFromCharCode(T)}(m=s.transformTo(o.uint8array?"uint8array":"array",m))},s.inherits(h,l),h.prototype.processChunk=function(m){var g=s.transformTo(o.uint8array?"uint8array":"array",m.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var v=g;(g=new Uint8Array(v.length+this.leftOver.length)).set(this.leftOver,0),g.set(v,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var y=function(S,E){var T;for((E=E||S.length)>S.length&&(E=S.length),T=E-1;0<=T&&(192&S[T])==128;)T--;return T<0||T===0?E:T+c[S[T]]>E?T:E}(g),_=g;y!==g.length&&(o.uint8array?(_=g.subarray(0,y),this.leftOver=g.subarray(y,g.length)):(_=g.slice(0,y),this.leftOver=g.slice(y,g.length))),this.push({data:i.utf8decode(_),meta:m.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=h,s.inherits(p,l),p.prototype.processChunk=function(m){this.push({data:i.utf8encode(m.data),meta:m.meta})},i.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,i){var s=n("./support"),o=n("./base64"),a=n("./nodejsUtils"),l=n("./external");function c(v){return v}function u(v,y){for(var _=0;_>8;this.dir=!!(16&this.externalFileAttributes),m==0&&(this.dosPermissions=63&this.externalFileAttributes),m==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var m=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=m.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=m.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=m.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=m.readInt(4))}},readExtraFields:function(m){var g,v,y,_=m.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});m.index+4<_;)g=m.readInt(2),v=m.readInt(2),y=m.readData(v),this.extraFields[g]={id:g,length:v,value:y};m.setIndex(_)},handleUTF8:function(){var m=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=c.utf8decode(this.fileName),this.fileCommentStr=c.utf8decode(this.fileComment);else{var g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var v=o.transformTo(m,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(v)}var y=this.findExtraFieldUnicodeComment();if(y!==null)this.fileCommentStr=y;else{var _=o.transformTo(m,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(_)}}},findExtraFieldUnicodePath:function(){var m=this.extraFields[28789];if(m){var g=s(m.value);return g.readInt(1)!==1||l(this.fileName)!==g.readInt(4)?null:c.utf8decode(g.readData(m.length-5))}return null},findExtraFieldUnicodeComment:function(){var m=this.extraFields[25461];if(m){var g=s(m.value);return g.readInt(1)!==1||l(this.fileComment)!==g.readInt(4)?null:c.utf8decode(g.readData(m.length-5))}return null}},r.exports=p},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,i){function s(g,v,y){this.name=g,this.dir=y.dir,this.date=y.date,this.comment=y.comment,this.unixPermissions=y.unixPermissions,this.dosPermissions=y.dosPermissions,this._data=v,this._dataBinary=y.binary,this.options={compression:y.compression,compressionOptions:y.compressionOptions}}var o=n("./stream/StreamHelper"),a=n("./stream/DataWorker"),l=n("./utf8"),c=n("./compressedObject"),u=n("./stream/GenericWorker");s.prototype={internalStream:function(g){var v=null,y="string";try{if(!g)throw new Error("No output type specified.");var _=(y=g.toLowerCase())==="string"||y==="text";y!=="binarystring"&&y!=="text"||(y="string"),v=this._decompressWorker();var S=!this._dataBinary;S&&!_&&(v=v.pipe(new l.Utf8EncodeWorker)),!S&&_&&(v=v.pipe(new l.Utf8DecodeWorker))}catch(E){(v=new u("error")).error(E)}return new o(v,y,"")},async:function(g,v){return this.internalStream(g).accumulate(v)},nodeStream:function(g,v){return this.internalStream(g||"nodebuffer").toNodejsStream(v)},_compressWorker:function(g,v){if(this._data instanceof c&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var y=this._decompressWorker();return this._dataBinary||(y=y.pipe(new l.Utf8EncodeWorker)),c.createWorkerFrom(y,g,v)},_decompressWorker:function(){return this._data instanceof c?this._data.getContentWorker():this._data instanceof u?this._data:new a(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],p=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},m=0;m>>6:(m<65536?p[y++]=224|m>>>12:(p[y++]=240|m>>>18,p[y++]=128|m>>>12&63),p[y++]=128|m>>>6&63),p[y++]=128|63&m);return p},i.buf2binstring=function(h){return u(h,h.length)},i.binstring2buf=function(h){for(var p=new s.Buf8(h.length),m=0,g=p.length;m>10&1023,S[g++]=56320|1023&v)}return u(S,g)},i.utf8border=function(h,p){var m;for((p=p||h.length)>h.length&&(p=h.length),m=p-1;0<=m&&(192&h[m])==128;)m--;return m<0||m===0?p:m+l[h[m]]>p?m:p}},{"./common":41}],43:[function(n,r,i){r.exports=function(s,o,a,l){for(var c=65535&s|0,u=s>>>16&65535|0,h=0;a!==0;){for(a-=h=2e3>>1:o>>>1;a[l]=o}return a}();r.exports=function(o,a,l,c){var u=s,h=c+l;o^=-1;for(var p=c;p>>8^u[255&(o^a[p])];return-1^o}},{}],46:[function(n,r,i){var s,o=n("../utils/common"),a=n("./trees"),l=n("./adler32"),c=n("./crc32"),u=n("./messages"),h=0,p=4,m=0,g=-2,v=-1,y=4,_=2,S=8,E=9,T=286,N=30,R=19,C=2*T+1,O=15,M=3,I=258,U=I+M+1,L=42,P=113,b=1,H=2,V=3,B=4;function z(A,ie){return A.msg=u[ie],ie}function W(A){return(A<<1)-(4A.avail_out&&(te=A.avail_out),te!==0&&(o.arraySet(A.output,ie.pending_buf,ie.pending_out,te,A.next_out),A.next_out+=te,ie.pending_out+=te,A.total_out+=te,A.avail_out-=te,ie.pending-=te,ie.pending===0&&(ie.pending_out=0))}function Y(A,ie){a._tr_flush_block(A,0<=A.block_start?A.block_start:-1,A.strstart-A.block_start,ie),A.block_start=A.strstart,j(A.strm)}function ge(A,ie){A.pending_buf[A.pending++]=ie}function Q(A,ie){A.pending_buf[A.pending++]=ie>>>8&255,A.pending_buf[A.pending++]=255&ie}function re(A,ie){var te,X,$=A.max_chain_length,ne=A.strstart,ae=A.prev_length,G=A.nice_match,D=A.strstart>A.w_size-U?A.strstart-(A.w_size-U):0,ee=A.window,he=A.w_mask,le=A.prev,_e=A.strstart+I,ze=ee[ne+ae-1],Oe=ee[ne+ae];A.prev_length>=A.good_match&&($>>=2),G>A.lookahead&&(G=A.lookahead);do if(ee[(te=ie)+ae]===Oe&&ee[te+ae-1]===ze&&ee[te]===ee[ne]&&ee[++te]===ee[ne+1]){ne+=2,te++;do;while(ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ne<_e);if(X=I-(_e-ne),ne=_e-I,aeD&&--$!=0);return ae<=A.lookahead?ae:A.lookahead}function we(A){var ie,te,X,$,ne,ae,G,D,ee,he,le=A.w_size;do{if($=A.window_size-A.lookahead-A.strstart,A.strstart>=le+(le-U)){for(o.arraySet(A.window,A.window,le,le,0),A.match_start-=le,A.strstart-=le,A.block_start-=le,ie=te=A.hash_size;X=A.head[--ie],A.head[ie]=le<=X?X-le:0,--te;);for(ie=te=le;X=A.prev[--ie],A.prev[ie]=le<=X?X-le:0,--te;);$+=le}if(A.strm.avail_in===0)break;if(ae=A.strm,G=A.window,D=A.strstart+A.lookahead,ee=$,he=void 0,he=ae.avail_in,ee=M)for(ne=A.strstart-A.insert,A.ins_h=A.window[ne],A.ins_h=(A.ins_h<=M&&(A.ins_h=(A.ins_h<=M)if(X=a._tr_tally(A,A.strstart-A.match_start,A.match_length-M),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=M){for(A.match_length--;A.strstart++,A.ins_h=(A.ins_h<=M&&(A.ins_h=(A.ins_h<=M&&A.match_length<=A.prev_length){for($=A.strstart+A.lookahead-M,X=a._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-M),A.lookahead-=A.prev_length-1,A.prev_length-=2;++A.strstart<=$&&(A.ins_h=(A.ins_h<A.pending_buf_size-5&&(te=A.pending_buf_size-5);;){if(A.lookahead<=1){if(we(A),A.lookahead===0&&ie===h)return b;if(A.lookahead===0)break}A.strstart+=A.lookahead,A.lookahead=0;var X=A.block_start+te;if((A.strstart===0||A.strstart>=X)&&(A.lookahead=A.strstart-X,A.strstart=X,Y(A,!1),A.strm.avail_out===0)||A.strstart-A.block_start>=A.w_size-U&&(Y(A,!1),A.strm.avail_out===0))return b}return A.insert=0,ie===p?(Y(A,!0),A.strm.avail_out===0?V:B):(A.strstart>A.block_start&&(Y(A,!1),A.strm.avail_out),b)}),new Le(4,4,8,4,Ae),new Le(4,5,16,8,Ae),new Le(4,6,32,32,Ae),new Le(4,4,16,16,Ee),new Le(8,16,32,32,Ee),new Le(8,16,128,128,Ee),new Le(8,32,128,256,Ee),new Le(32,128,258,1024,Ee),new Le(32,258,258,4096,Ee)],i.deflateInit=function(A,ie){return De(A,ie,S,15,8,0)},i.deflateInit2=De,i.deflateReset=it,i.deflateResetKeep=qe,i.deflateSetHeader=function(A,ie){return A&&A.state?A.state.wrap!==2?g:(A.state.gzhead=ie,m):g},i.deflate=function(A,ie){var te,X,$,ne;if(!A||!A.state||5>8&255),ge(X,X.gzhead.time>>16&255),ge(X,X.gzhead.time>>24&255),ge(X,X.level===9?2:2<=X.strategy||X.level<2?4:0),ge(X,255&X.gzhead.os),X.gzhead.extra&&X.gzhead.extra.length&&(ge(X,255&X.gzhead.extra.length),ge(X,X.gzhead.extra.length>>8&255)),X.gzhead.hcrc&&(A.adler=c(A.adler,X.pending_buf,X.pending,0)),X.gzindex=0,X.status=69):(ge(X,0),ge(X,0),ge(X,0),ge(X,0),ge(X,0),ge(X,X.level===9?2:2<=X.strategy||X.level<2?4:0),ge(X,3),X.status=P);else{var ae=S+(X.w_bits-8<<4)<<8;ae|=(2<=X.strategy||X.level<2?0:X.level<6?1:X.level===6?2:3)<<6,X.strstart!==0&&(ae|=32),ae+=31-ae%31,X.status=P,Q(X,ae),X.strstart!==0&&(Q(X,A.adler>>>16),Q(X,65535&A.adler)),A.adler=1}if(X.status===69)if(X.gzhead.extra){for($=X.pending;X.gzindex<(65535&X.gzhead.extra.length)&&(X.pending!==X.pending_buf_size||(X.gzhead.hcrc&&X.pending>$&&(A.adler=c(A.adler,X.pending_buf,X.pending-$,$)),j(A),$=X.pending,X.pending!==X.pending_buf_size));)ge(X,255&X.gzhead.extra[X.gzindex]),X.gzindex++;X.gzhead.hcrc&&X.pending>$&&(A.adler=c(A.adler,X.pending_buf,X.pending-$,$)),X.gzindex===X.gzhead.extra.length&&(X.gzindex=0,X.status=73)}else X.status=73;if(X.status===73)if(X.gzhead.name){$=X.pending;do{if(X.pending===X.pending_buf_size&&(X.gzhead.hcrc&&X.pending>$&&(A.adler=c(A.adler,X.pending_buf,X.pending-$,$)),j(A),$=X.pending,X.pending===X.pending_buf_size)){ne=1;break}ne=X.gzindex$&&(A.adler=c(A.adler,X.pending_buf,X.pending-$,$)),ne===0&&(X.gzindex=0,X.status=91)}else X.status=91;if(X.status===91)if(X.gzhead.comment){$=X.pending;do{if(X.pending===X.pending_buf_size&&(X.gzhead.hcrc&&X.pending>$&&(A.adler=c(A.adler,X.pending_buf,X.pending-$,$)),j(A),$=X.pending,X.pending===X.pending_buf_size)){ne=1;break}ne=X.gzindex$&&(A.adler=c(A.adler,X.pending_buf,X.pending-$,$)),ne===0&&(X.status=103)}else X.status=103;if(X.status===103&&(X.gzhead.hcrc?(X.pending+2>X.pending_buf_size&&j(A),X.pending+2<=X.pending_buf_size&&(ge(X,255&A.adler),ge(X,A.adler>>8&255),A.adler=0,X.status=P)):X.status=P),X.pending!==0){if(j(A),A.avail_out===0)return X.last_flush=-1,m}else if(A.avail_in===0&&W(ie)<=W(te)&&ie!==p)return z(A,-5);if(X.status===666&&A.avail_in!==0)return z(A,-5);if(A.avail_in!==0||X.lookahead!==0||ie!==h&&X.status!==666){var G=X.strategy===2?function(D,ee){for(var he;;){if(D.lookahead===0&&(we(D),D.lookahead===0)){if(ee===h)return b;break}if(D.match_length=0,he=a._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++,he&&(Y(D,!1),D.strm.avail_out===0))return b}return D.insert=0,ee===p?(Y(D,!0),D.strm.avail_out===0?V:B):D.last_lit&&(Y(D,!1),D.strm.avail_out===0)?b:H}(X,ie):X.strategy===3?function(D,ee){for(var he,le,_e,ze,Oe=D.window;;){if(D.lookahead<=I){if(we(D),D.lookahead<=I&&ee===h)return b;if(D.lookahead===0)break}if(D.match_length=0,D.lookahead>=M&&0D.lookahead&&(D.match_length=D.lookahead)}if(D.match_length>=M?(he=a._tr_tally(D,1,D.match_length-M),D.lookahead-=D.match_length,D.strstart+=D.match_length,D.match_length=0):(he=a._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++),he&&(Y(D,!1),D.strm.avail_out===0))return b}return D.insert=0,ee===p?(Y(D,!0),D.strm.avail_out===0?V:B):D.last_lit&&(Y(D,!1),D.strm.avail_out===0)?b:H}(X,ie):s[X.level].func(X,ie);if(G!==V&&G!==B||(X.status=666),G===b||G===V)return A.avail_out===0&&(X.last_flush=-1),m;if(G===H&&(ie===1?a._tr_align(X):ie!==5&&(a._tr_stored_block(X,0,0,!1),ie===3&&(K(X.head),X.lookahead===0&&(X.strstart=0,X.block_start=0,X.insert=0))),j(A),A.avail_out===0))return X.last_flush=-1,m}return ie!==p?m:X.wrap<=0?1:(X.wrap===2?(ge(X,255&A.adler),ge(X,A.adler>>8&255),ge(X,A.adler>>16&255),ge(X,A.adler>>24&255),ge(X,255&A.total_in),ge(X,A.total_in>>8&255),ge(X,A.total_in>>16&255),ge(X,A.total_in>>24&255)):(Q(X,A.adler>>>16),Q(X,65535&A.adler)),j(A),0=te.w_size&&(ne===0&&(K(te.head),te.strstart=0,te.block_start=0,te.insert=0),ee=new o.Buf8(te.w_size),o.arraySet(ee,ie,he-te.w_size,te.w_size,0),ie=ee,he=te.w_size),ae=A.avail_in,G=A.next_in,D=A.input,A.avail_in=he,A.next_in=0,A.input=ie,we(te);te.lookahead>=M;){for(X=te.strstart,$=te.lookahead-(M-1);te.ins_h=(te.ins_h<>>=M=O>>>24,E-=M,(M=O>>>16&255)===0)H[u++]=65535&O;else{if(!(16&M)){if(!(64&M)){O=T[(65535&O)+(S&(1<>>=M,E-=M),E<15&&(S+=b[l++]<>>=M=O>>>24,E-=M,!(16&(M=O>>>16&255))){if(!(64&M)){O=N[(65535&O)+(S&(1<>>=M,E-=M,(M=u-h)>3,S&=(1<<(E-=I<<3))-1,s.next_in=l,s.next_out=u,s.avail_in=l>>24&255)+(L>>>8&65280)+((65280&L)<<8)+((255&L)<<24)}function S(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function E(L){var P;return L&&L.state?(P=L.state,L.total_in=L.total_out=P.total=0,L.msg="",P.wrap&&(L.adler=1&P.wrap),P.mode=g,P.last=0,P.havedict=0,P.dmax=32768,P.head=null,P.hold=0,P.bits=0,P.lencode=P.lendyn=new s.Buf32(v),P.distcode=P.distdyn=new s.Buf32(y),P.sane=1,P.back=-1,p):m}function T(L){var P;return L&&L.state?((P=L.state).wsize=0,P.whave=0,P.wnext=0,E(L)):m}function N(L,P){var b,H;return L&&L.state?(H=L.state,P<0?(b=0,P=-P):(b=1+(P>>4),P<48&&(P&=15)),P&&(P<8||15=B.wsize?(s.arraySet(B.window,P,b-B.wsize,B.wsize,0),B.wnext=0,B.whave=B.wsize):(H<(V=B.wsize-B.wnext)&&(V=H),s.arraySet(B.window,P,b-H,V,B.wnext),(H-=V)?(s.arraySet(B.window,P,b-H,H,0),B.wnext=H,B.whave=B.wsize):(B.wnext+=V,B.wnext===B.wsize&&(B.wnext=0),B.whave>>8&255,b.check=a(b.check,ne,2,0),Y=j=0,b.mode=2;break}if(b.flags=0,b.head&&(b.head.done=!1),!(1&b.wrap)||(((255&j)<<8)+(j>>8))%31){L.msg="incorrect header check",b.mode=30;break}if((15&j)!=8){L.msg="unknown compression method",b.mode=30;break}if(Y-=4,A=8+(15&(j>>>=4)),b.wbits===0)b.wbits=A;else if(A>b.wbits){L.msg="invalid window size",b.mode=30;break}b.dmax=1<>8&1),512&b.flags&&(ne[0]=255&j,ne[1]=j>>>8&255,b.check=a(b.check,ne,2,0)),Y=j=0,b.mode=3;case 3:for(;Y<32;){if(W===0)break e;W--,j+=H[B++]<>>8&255,ne[2]=j>>>16&255,ne[3]=j>>>24&255,b.check=a(b.check,ne,4,0)),Y=j=0,b.mode=4;case 4:for(;Y<16;){if(W===0)break e;W--,j+=H[B++]<>8),512&b.flags&&(ne[0]=255&j,ne[1]=j>>>8&255,b.check=a(b.check,ne,2,0)),Y=j=0,b.mode=5;case 5:if(1024&b.flags){for(;Y<16;){if(W===0)break e;W--,j+=H[B++]<>>8&255,b.check=a(b.check,ne,2,0)),Y=j=0}else b.head&&(b.head.extra=null);b.mode=6;case 6:if(1024&b.flags&&(W<(re=b.length)&&(re=W),re&&(b.head&&(A=b.head.extra_len-b.length,b.head.extra||(b.head.extra=new Array(b.head.extra_len)),s.arraySet(b.head.extra,H,B,re,A)),512&b.flags&&(b.check=a(b.check,H,re,B)),W-=re,B+=re,b.length-=re),b.length))break e;b.length=0,b.mode=7;case 7:if(2048&b.flags){if(W===0)break e;for(re=0;A=H[B+re++],b.head&&A&&b.length<65536&&(b.head.name+=String.fromCharCode(A)),A&&re>9&1,b.head.done=!0),L.adler=b.check=0,b.mode=12;break;case 10:for(;Y<32;){if(W===0)break e;W--,j+=H[B++]<>>=7&Y,Y-=7&Y,b.mode=27;break}for(;Y<3;){if(W===0)break e;W--,j+=H[B++]<>>=1)){case 0:b.mode=14;break;case 1:if(I(b),b.mode=20,P!==6)break;j>>>=2,Y-=2;break e;case 2:b.mode=17;break;case 3:L.msg="invalid block type",b.mode=30}j>>>=2,Y-=2;break;case 14:for(j>>>=7&Y,Y-=7&Y;Y<32;){if(W===0)break e;W--,j+=H[B++]<>>16^65535)){L.msg="invalid stored block lengths",b.mode=30;break}if(b.length=65535&j,Y=j=0,b.mode=15,P===6)break e;case 15:b.mode=16;case 16:if(re=b.length){if(W>>=5,Y-=5,b.ndist=1+(31&j),j>>>=5,Y-=5,b.ncode=4+(15&j),j>>>=4,Y-=4,286>>=3,Y-=3}for(;b.have<19;)b.lens[ae[b.have++]]=0;if(b.lencode=b.lendyn,b.lenbits=7,te={bits:b.lenbits},ie=c(0,b.lens,0,19,b.lencode,0,b.work,te),b.lenbits=te.bits,ie){L.msg="invalid code lengths set",b.mode=30;break}b.have=0,b.mode=19;case 19:for(;b.have>>16&255,Ve=65535&$,!((Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>>=Ee,Y-=Ee,b.lens[b.have++]=Ve;else{if(Ve===16){for(X=Ee+2;Y>>=Ee,Y-=Ee,b.have===0){L.msg="invalid bit length repeat",b.mode=30;break}A=b.lens[b.have-1],re=3+(3&j),j>>>=2,Y-=2}else if(Ve===17){for(X=Ee+3;Y>>=Ee)),j>>>=3,Y-=3}else{for(X=Ee+7;Y>>=Ee)),j>>>=7,Y-=7}if(b.have+re>b.nlen+b.ndist){L.msg="invalid bit length repeat",b.mode=30;break}for(;re--;)b.lens[b.have++]=A}}if(b.mode===30)break;if(b.lens[256]===0){L.msg="invalid code -- missing end-of-block",b.mode=30;break}if(b.lenbits=9,te={bits:b.lenbits},ie=c(u,b.lens,0,b.nlen,b.lencode,0,b.work,te),b.lenbits=te.bits,ie){L.msg="invalid literal/lengths set",b.mode=30;break}if(b.distbits=6,b.distcode=b.distdyn,te={bits:b.distbits},ie=c(h,b.lens,b.nlen,b.ndist,b.distcode,0,b.work,te),b.distbits=te.bits,ie){L.msg="invalid distances set",b.mode=30;break}if(b.mode=20,P===6)break e;case 20:b.mode=21;case 21:if(6<=W&&258<=K){L.next_out=z,L.avail_out=K,L.next_in=B,L.avail_in=W,b.hold=j,b.bits=Y,l(L,Q),z=L.next_out,V=L.output,K=L.avail_out,B=L.next_in,H=L.input,W=L.avail_in,j=b.hold,Y=b.bits,b.mode===12&&(b.back=-1);break}for(b.back=0;Le=($=b.lencode[j&(1<>>16&255,Ve=65535&$,!((Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>qe)])>>>16&255,Ve=65535&$,!(qe+(Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>>=qe,Y-=qe,b.back+=qe}if(j>>>=Ee,Y-=Ee,b.back+=Ee,b.length=Ve,Le===0){b.mode=26;break}if(32&Le){b.back=-1,b.mode=12;break}if(64&Le){L.msg="invalid literal/length code",b.mode=30;break}b.extra=15&Le,b.mode=22;case 22:if(b.extra){for(X=b.extra;Y>>=b.extra,Y-=b.extra,b.back+=b.extra}b.was=b.length,b.mode=23;case 23:for(;Le=($=b.distcode[j&(1<>>16&255,Ve=65535&$,!((Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>qe)])>>>16&255,Ve=65535&$,!(qe+(Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>>=qe,Y-=qe,b.back+=qe}if(j>>>=Ee,Y-=Ee,b.back+=Ee,64&Le){L.msg="invalid distance code",b.mode=30;break}b.offset=Ve,b.extra=15&Le,b.mode=24;case 24:if(b.extra){for(X=b.extra;Y>>=b.extra,Y-=b.extra,b.back+=b.extra}if(b.offset>b.dmax){L.msg="invalid distance too far back",b.mode=30;break}b.mode=25;case 25:if(K===0)break e;if(re=Q-K,b.offset>re){if((re=b.offset-re)>b.whave&&b.sane){L.msg="invalid distance too far back",b.mode=30;break}we=re>b.wnext?(re-=b.wnext,b.wsize-re):b.wnext-re,re>b.length&&(re=b.length),Ae=b.window}else Ae=V,we=z-b.offset,re=b.length;for(KC?(M=we[Ae+y[P]],Y[ge+y[P]]):(M=96,0),S=1<>z)+(E-=S)]=O<<24|M<<16|I|0,E!==0;);for(S=1<>=1;if(S!==0?(j&=S-1,j+=S):j=0,P++,--Q[L]==0){if(L===H)break;L=h[p+y[P]]}if(V>>7)]}function ge($,ne){$.pending_buf[$.pending++]=255&ne,$.pending_buf[$.pending++]=ne>>>8&255}function Q($,ne,ae){$.bi_valid>_-ae?($.bi_buf|=ne<<$.bi_valid&65535,ge($,$.bi_buf),$.bi_buf=ne>>_-$.bi_valid,$.bi_valid+=ae-_):($.bi_buf|=ne<<$.bi_valid&65535,$.bi_valid+=ae)}function re($,ne,ae){Q($,ae[2*ne],ae[2*ne+1])}function we($,ne){for(var ae=0;ae|=1&$,$>>>=1,ae<<=1,0<--ne;);return ae>>>1}function Ae($,ne,ae){var G,D,ee=new Array(y+1),he=0;for(G=1;G<=y;G++)ee[G]=he=he+ae[G-1]<<1;for(D=0;D<=ne;D++){var le=$[2*D+1];le!==0&&($[2*D]=we(ee[le]++,le))}}function Ee($){var ne;for(ne=0;ne>1;1<=ae;ae--)qe($,ee,ae);for(D=_e;ae=$.heap[1],$.heap[1]=$.heap[$.heap_len--],qe($,ee,1),G=$.heap[1],$.heap[--$.heap_max]=ae,$.heap[--$.heap_max]=G,ee[2*D]=ee[2*ae]+ee[2*G],$.depth[D]=($.depth[ae]>=$.depth[G]?$.depth[ae]:$.depth[G])+1,ee[2*ae+1]=ee[2*G+1]=D,$.heap[1]=D++,qe($,ee,1),2<=$.heap_len;);$.heap[--$.heap_max]=$.heap[1],function(Oe,Ge){var Lt,Pe,nt,et,yt,rt,Ct=Ge.dyn_tree,Rt=Ge.max_code,Sn=Ge.stat_desc.static_tree,ce=Ge.stat_desc.has_stree,je=Ge.stat_desc.extra_bits,Ce=Ge.stat_desc.extra_base,ke=Ge.stat_desc.max_length,$e=0;for(et=0;et<=y;et++)Oe.bl_count[et]=0;for(Ct[2*Oe.heap[Oe.heap_max]+1]=0,Lt=Oe.heap_max+1;Lt>=7;D>>=1)if(1&ze&&le.dyn_ltree[2*_e]!==0)return o;if(le.dyn_ltree[18]!==0||le.dyn_ltree[20]!==0||le.dyn_ltree[26]!==0)return a;for(_e=32;_e>>3,(ee=$.static_len+3+7>>>3)<=D&&(D=ee)):D=ee=ae+5,ae+4<=D&&ne!==-1?X($,ne,ae,G):$.strategy===4||ee===D?(Q($,2+(G?1:0),3),it($,U,L)):(Q($,4+(G?1:0),3),function(le,_e,ze,Oe){var Ge;for(Q(le,_e-257,5),Q(le,ze-1,5),Q(le,Oe-4,4),Ge=0;Ge>>8&255,$.pending_buf[$.d_buf+2*$.last_lit+1]=255&ne,$.pending_buf[$.l_buf+$.last_lit]=255&ae,$.last_lit++,ne===0?$.dyn_ltree[2*ae]++:($.matches++,ne--,$.dyn_ltree[2*(b[ae]+h+1)]++,$.dyn_dtree[2*Y(ne)]++),$.last_lit===$.lit_bufsize-1},i._tr_align=function($){Q($,2,3),re($,E,U),function(ne){ne.bi_valid===16?(ge(ne,ne.bi_buf),ne.bi_buf=0,ne.bi_valid=0):8<=ne.bi_valid&&(ne.pending_buf[ne.pending++]=255&ne.bi_buf,ne.bi_buf>>=8,ne.bi_valid-=8)}($)}},{"../utils/common":41}],53:[function(n,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,i){(function(s){(function(o,a){if(!o.setImmediate){var l,c,u,h,p=1,m={},g=!1,v=o.document,y=Object.getPrototypeOf&&Object.getPrototypeOf(o);y=y&&y.setTimeout?y:o,l={}.toString.call(o.process)==="[object process]"?function(T){process.nextTick(function(){S(T)})}:function(){if(o.postMessage&&!o.importScripts){var T=!0,N=o.onmessage;return o.onmessage=function(){T=!1},o.postMessage("","*"),o.onmessage=N,T}}()?(h="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",E,!1):o.attachEvent("onmessage",E),function(T){o.postMessage(h+T,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(T){S(T.data)},function(T){u.port2.postMessage(T)}):v&&"onreadystatechange"in v.createElement("script")?(c=v.documentElement,function(T){var N=v.createElement("script");N.onreadystatechange=function(){S(T),N.onreadystatechange=null,c.removeChild(N),N=null},c.appendChild(N)}):function(T){setTimeout(S,0,T)},y.setImmediate=function(T){typeof T!="function"&&(T=new Function(""+T));for(var N=new Array(arguments.length-1),R=0;R"u"?s===void 0?this:s:self)}).call(this,typeof bo<"u"?bo:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(kfe);const Y4={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(Y4);var $s=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},of,lp,wu;class Ife{constructor(...e){of.set(this,new Map),lp.set(this,new Map),wu.set(this,new Map);for(const n of e)this.define(n)}define(e,n=!1){for(let[r,i]of Object.entries(e)){r=r.toLowerCase(),i=i.map(a=>a.toLowerCase()),$s(this,wu,"f").has(r)||$s(this,wu,"f").set(r,new Set);const s=$s(this,wu,"f").get(r);let o=!0;for(let a of i){const l=a.startsWith("*");if(a=l?a.slice(1):a,s==null||s.add(a),o&&$s(this,lp,"f").set(r,a),o=!1,l)continue;const c=$s(this,of,"f").get(a);if(c&&c!=r&&!n)throw new Error(`"${r} -> ${a}" conflicts with "${c} -> ${a}". Pass \`force=true\` to override this definition.`);$s(this,of,"f").set(a,r)}}return this}getType(e){if(typeof e!="string")return null;const n=e.replace(/^.*[/\\]/,"").toLowerCase(),r=n.replace(/^.*\./,"").toLowerCase(),i=n.length{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(const e of $s(this,wu,"f").values())Object.freeze(e);return this}_getTestState(){return{types:$s(this,of,"f"),extensions:$s(this,lp,"f")}}}of=new WeakMap,lp=new WeakMap,wu=new WeakMap;new Ife(Y4)._freeze();function Xw(t){if(!t||t.type===void 0)return;const e=[{start:t.startOffset,end:t.endOffset??0}];return Object.keys(t).forEach(n=>{if(n!=="parent"){const r=t[n];ln(r)?r.forEach(i=>{e.push(Xw(i))}):e.push(Xw(r))}}),t.range={start:Math.min(...e.filter(n=>n).map(n=>(n==null?void 0:n.start)??0)),end:Math.max(...e.filter(n=>n).map(n=>(n==null?void 0:n.end)??0))},t.range}function Ofe(t){const e=A4(`${t} +`);if(e.errors.length>0)return e;pf.input=e.tokens;const n=pf.program();if(pf.errors.length>0)return{tokens:e.tokens,errors:pf.errors.map(i=>({offset:i.token.startOffset,line:i.token.startLine,column:i.token.startColumn,length:i.token.image.length,message:i.message}))};const[r]=Sfe.go(n);return r?(Xw(r),{tokens:e.tokens,cst:n,ast:r}):{tokens:e.tokens,cst:n,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]}}const R1=Object.getPrototypeOf(function*(){}).constructor;function Lfe(t,e){const n=`compile-${t}`;console.time(n);const r=Ofe(e);if(console.timeEnd(n),r.errors&&r.errors.length>0)return r;if(!r.ast)return{...r,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]};const i=Afe(r.ast);if(i.code){Dne&&console.info(i.code);try{return{...r,...i,source:i.code,code:new R1("api",i.code)}}catch(s){return{errors:[{message:`unexpected error ${s.message}`,offset:0,line:0,column:0,length:0}],source:"",code:new R1("api"," ")}}}return{...r,...i,source:"",code:new R1("api"," ")}}function Pfe(){const t={},e={};function n(i,s){const o=t[s];if(o)return o;const a=Lfe(i,s);return t[s]=a,a}const r={ids(){return Object.keys(e)},has(i){return Z(e[i])},isended(i){const s=e[i];return Z(s)?s.isended():!0},halt(i){const s=e[i];return Z(s)&&(s.halt(),delete e[i]),!!s},gc(){const i=r.ids();for(let s=0;s[_,S]);g.slice(m-5,m).forEach(([_,S])=>{Pn("os","build",`$grey${S+1} $grey${_}`)});const[v,y]=g[m]??[];if(Kt(v)&&Z(y)){const _=(p.column??1)-1,S=_+p.length,E=_{Pn("os","build",_)}),!1}}return!!(c!=null&&c.tick(o))},once(i,s,o,a){const l=r.tick(i,s,1,o,a);return r.halt(i)&&l},message(i){const{target:s,path:o}=GO(i.target),a=e[s];if(Z(a)){const l={...i,target:o};a.message(l)}}};return r}const Z4=Pfe();var Ar=(t=>(t.MAIN="main",t.TITLE="title",t.PLAYER="player",t.CONTENT="content",t.GADGETSTORE="gadgetstore",t.GADGETSYNC="gadgetsync",t))(Ar||{});const Ga={defaultplayer:SW(),software:{main:"",content:""},books:new Map,chips:new Map,loaders:new Map,chipindex:new Map,codepageindex:new Map,binaryfiles:new Map};function Kw(){return[...Ga.books.values()]}function Dfe(){const[t]=Ga.books.values();return t}function td(t){const e=$t(t);return Ga.books.get(t)??Kw().find(n=>n.name===e)}function Yw(t,e){Z(td(e))&&(Ga.software[t]=e)}function cp(t){return td(Ga.software[t])}function J4(t){const e=N4([]);return Kt(t)&&(e.name=t),Q4(e),to("memory",`created [book] ${e.name}`),e}function Ufe(t){let e=td(t);return Z(e)||(e=N4([]),e.name=t),Q4(e),to("memory",`created [book] ${e.name}`),e}function bl(t,e){let n=Z(e)?Ufe(e):cp(t);return Z(n)||(Z(n)||(n=Dfe()),Z(n)||(n=J4(e)),Z(n)&&to("memory",`opened [book] ${n.name} for ${t}`)),Yw(t,n.id),n}function yu(t,e,n){const r=bl(t);let i=Um(r,e);if(Z(i))return i;const s=C4(n);return i=nhe(s==="object"?`@${e} +`:`@${s} ${e} +`,{}),ihe(r,i),zfe(i.id,r.id),tf("memory"),i}function jp(t){const e=bl("main");return ahe(e,t)}function Ffe(t){const e=bl("main");return lhe(e,t)}function Q4(t){return Ga.books.set(t.id,t),t.id}function Bfe(t){const e=td(t);e&&Ga.books.delete(e.id)}function zfe(t,e){Ga.codepageindex.set(t,e)}function Vfe(t,e,n,r,i=hoe){if(!Z(t)||!Z(e)||!Z(n))return;const s={...se};se.book=t,se.board=e,se.element=n,se.player=n.player??Ga.defaultplayer,se.isplayer=EW(n.id??"");const o=Ll(t,n),a=n.cycle??(o==null?void 0:o.cycle)??i,l=n.id??"",c=wA(n);if(Z4.tick(l,NA.CODE_PAGE,mt(a)?a:i,c,r),mt(n==null?void 0:n.tickertime)&&se.timestamp-n.tickertime>iv*5&&(n.tickertime=0,n.tickertext=""),se.isplayer){const u=jp(se.player);u.inputcurrent=0}UO(s).forEach(u=>{se[u]=s[u]})}function Sv(t){const e=bl("main"),n=Um(e,t);if(!Z(e)||!Z(n)||!Z(se.element))return;const r=`${t}_run`,i=wA(se.element),s=(n==null?void 0:n.code)??"";Z4.once(r,NA.CODE_PAGE,i,s)}function eF(t){return Ga.binaryfiles.get(t)}function Ui(t,e=!0){var r,i,s,o,a;const n=se.words[t];if($3(n)){const[l,c]=E_(t);if(Z(l))return[l,c]}if(que(n)){const[l,c]=X3(t);if(Z(l))return[l,c]}if(nF(n)){const[l,c]=Ev(t);if(Z(l))return[l,c]}if(Kt(n)&&$t(n)==="rnd"){const[l,c]=Ui(t+1),[u,h]=Ui(c);return mt(l)&&mt(u)?[ep(l,u),h]:mt(l)?[ep(0,l),c]:[ep(0,1),t+1]}if(m3(n)){const[l,c]=bw(t);if(Z(l))return[l,c]}if(!Z(n))return[void 0,t];if(gl(n)||mt(n)||ln(n))return[n,t+1];if(Kt(n)){const l=$t(n);if(e){const c=(r=se.get)==null?void 0:r.call(se,n);if(Z(c))return[c,t+1]}switch(l){case"aligned":case"alligned":{const c=Uk(se.board,se.element,se.player);return!Z(se.element)||!Z(c)?[0,t+1]:[se.element.x===c.x||se.element.y===c.y?1:0,t+1]}case"contact":{const c=Uk(se.board,se.element,se.player);if(!Z(se.element)||!Z(c))return[0,t+1];const u=(c.x??0)-(((i=se.element)==null?void 0:i.x)??0),h=(c.y??0)-(((s=se.element)==null?void 0:s.y)??0);return[u===0&&Math.abs(h)<2||h===0&&Math.abs(u)<2?1:0,t+1]}case"blocked":{const[c,u]=He(se.words,t+1,[Ie.DIR]);return[che(se.book,se.board,se.element,c)?1:0,u]}case"any":{const[c,u]=He(se.words,t+1,[Ie.KIND]),h=_v(c)??"",p=Lm(se.board,h);return[y3(p,c).length?1:0,u]}case"rnd":return[ep(0,1),t+1];case"abs":{const[c,u]=He(se.words,t+1,[Ie.NUMBER]);return[Math.abs(c),u]}case"ceil":{const[c,u]=He(se.words,t+1,[Ie.NUMBER]);return[Math.ceil(c),u]}case"floor":{const[c,u]=He(se.words,t+1,[Ie.NUMBER]);return[Math.floor(c),u]}case"round":{const[c,u]=He(se.words,t+1,[Ie.NUMBER]);return[Math.round(c),u]}case"min":{const c=[];for(let u=t+1;uwn.WHITE&&twn[e]).find(e=>Z(e)&&ewn[e]).find(e=>Z(e)&&e>=wn.ONBLACK)}function pI(t){if(io(t))return t;if(tF(t))return[t];const e=nF(t);if(Z(e))return[e]}function mI(t){const e=se.words[t],n=pI(e);if(io(n))return[n,t+1];const[r,i]=Ui(t),s=pI(r);return io(s)?[s,i]:[void 0,t]}function Ev(t){const e=[];let n=t;const[r,i]=mI(t);if(io(r)&&(e.push(...r),n=i),io(e)&&!dI(e)){const[s,o]=mI(i);dI(s)&&(n=o)}return e.length?[e,n]:[void 0,t]}function $fe(t){const e={};return t.every(n=>{const r=wn[n];Z(r)&&(rString.fromCharCode(t)),Xfe=Ds({name:"Whitespace",pattern:/ +/}),Kfe=Ds({name:"WhitespaceSkipped",pattern:/ +/,group:Br.SKIPPED}),OA=Ds({name:"Newline",line_breaks:!0,start_chars_hint:[` +`,"\r"],pattern:/\n|\r\n?/}),LA=Ds({name:"StringLiteral",pattern:/[^ $;\r\n]+/,start_chars_hint:qfe}),PA=Ds({name:"StringLiteralDouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),DA=Ds({name:"EscapedDollar",pattern:"$$"}),UA=Ds({name:"MaybeFlag",pattern:/\$[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/}),FA=Ds({name:"NumberLiteral",pattern:/\$-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?\+?/}),BA=Ds({name:"HyperLinkText",pattern:/;[^;\r\n]*/,start_chars_hint:[";"]});function Yfe(t,e=""){return Ds({name:e||t,pattern:new RegExp(t.toLowerCase(),"i")})}const Zfe=Object.keys($y),rF=Zfe.map(t=>Yfe(`\\$(${t})`,t)),Jfe=[Xfe,OA,...rF,PA,LA,FA,DA,BA,UA],Qfe=new Br(Jfe,{skipValidations:!Ca,ensureOptimizations:Ca}),ede=new Br([Kfe,OA,...rF,PA,LA,FA,DA,BA,UA],{skipValidations:!Ca,ensureOptimizations:Ca});function qy(t,e=!1){return e?ede.tokenize(t):Qfe.tokenize(t)}function Vm(t,e,n,r,i,s,o,a){return{disablewrap:!1,measureonly:!1,measuredwidth:0,writefullwidth:void 0,x:0,y:0,iseven:!0,active:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},reset:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},width:t,height:e,char:[],color:[],bg:[],changed(){}}}function zA(t){t.active={...t.reset}}function VA(t,e){const n=e.y;function r(){++e.x;const a=e.active.rightedge??e.width-1;!e.disablewrap&&e.x>a&&(e.x=e.active.leftedge??0,++e.y),e.x>e.measuredwidth&&(e.measuredwidth=e.x)}function i(){return e.x>=(e.active.leftedge??0)&&e.x<=(e.active.rightedge??e.width-1)&&e.y>=(e.active.topedge??0)&&e.y<=(e.active.bottomedge??e.height-1)}function s(a){for(let l=0;le.measuredwidth&&(e.measuredwidth=e.x+1);const o=e.active.leftedge??0;if(Z(e.writefullwidth)&&(e.x>o||e.y===n)){const l=(e.active.rightedge??e.width-1)-e.x;if(l>0){zA(e);const c=String.fromCharCode(e.writefullwidth).repeat(l),u=e.x+e.y*e.width;Ky(u,u+c.length,e.active.color,e.active.bg,e),Xy(u,c,e)}}}function Fn(t,e,n){const r=qy(t);r.tokens&&(VA(r.tokens,e),n&&zA(e))}function HA(t,e,n){const r=qy(t);if(!r.tokens)return;const i=Vm(e,n,wn.WHITE,wn.BLACK);return i.measureonly=!0,VA(r.tokens,i),i.x>0&&++i.y,i}function Xy(t,e,n){let r=0;const i=t+e.length;for(let s=t;s({blink:!1}));setInterval(()=>{iF.setState(t=>({blink:!t.blink}))},333);function ja(){return iF(t=>t.blink)}function sF(){return Nb(t=>{function e(){t({render:Math.random()})}return{dither:[],render:0,changed(){setTimeout(e,0)}}})}function nde(t){t.fill(0)}function N1(t,e,n,r,i,s){if(r<0||r>=e||i<0||i>=n)return-1;t[r+i*e]=s}const oF=Ne.createContext(sF());function rde(t,e,n){const[r]=Ne.useState(()=>sF()),i=t*e,s=r.getState();return s.dither.length!==i&&(s.dither=new Array(i).fill(n),s.render=0),r}function aF(){return Nb(t=>{function e(){t({render:Math.random()})}return{width:0,height:0,char:[],color:[],bg:[],render:0,changed(){setTimeout(e,0)}}})}function ide(t,e,n,r){t.char.fill(e),t.color.fill(n),t.bg.fill(r)}function Lr(t,e,n,r,i,s){if(r<0||r>=e||i<0||i>=n)return;const o=r+i*e;UO(s).forEach(a=>{const l=s[a];Z(l)&&(t[a][o]=l)})}const GA=Ne.createContext(aF());function WA(t,e,n,r,i){const[s]=Ne.useState(()=>aF()),o=t*e,a=s.getState();return a.char.length!==o&&(a.width=t,a.height=e,a.char=new Array(o).fill(n),a.color=new Array(o).fill(r),a.bg=new Array(o).fill(i),a.render=0),s}function sde(){return Ne.useContext(GA).getState()}function ode({item:t,context:e}){return Fn(`${t} +`,e,!0),null}const Yy=Ne.createContext({sendmessage(){},sendclose(){},didclose(){}}),gI={input:{color:"$white",active:"$yellow"}};function Kc(t){return t?gI.input.active:gI.input.color}function so(t,e){return typeof t==typeof e?t:e}function lF(t,e){return`vm:${t}:${e}`}function up(t,e,n=0,r=""){return`${t.substring(0,e)}${r}${t.substring(e+n)}`}function ade({chip:t,active:e,label:n,args:r,context:i}){var p;const[s,o,a]=[so(r[0],""),so(r[1],((p=r[1])==null?void 0:p.toString())??""),so(r[2],"")],l=a||` ${o.toUpperCase()} `,c=Kc(e);Fn(`${i.iseven?"$black$onltgray":"$black$ondkcyan"}${l}${c}$onclear ${n} +`,i,!0);const u=Ne.useContext(Yy),h=Ne.useCallback(()=>{u.sendmessage(lF(t,s)),u.sendclose()},[t,u,s]);return ve.jsxs(ve.Fragment,{children:[e&&ve.jsx(ms,{OK_BUTTON:h}),ve.jsx(_p,{hotkey:o,children:h})]})}function lde({chip:t,active:e,label:n,args:r,context:i}){const[s,o]=[so(r[0],""),r[1]],a=Kc(e);Fn(` $purple$16 ${a}${n} +`,i,!0);const l=Ne.useContext(Yy),c=Ne.useCallback(()=>{l.sendmessage(lF(t,s),o),l.sendclose()},[l,t,s,o]);return e&&ve.jsx(ms,{OK_BUTTON:c})}function cde({chip:t,active:e,label:n,args:r,context:i}){const[s,o,a]=[so(r[0],""),so(r[1],-1),so(r[2],-1)];let l,c;o===-1?(l=0,c=31):a===-1?(l=0,c=o):(l=o,c=a);const u=md(t,s),h=nA(u),p=h==null?void 0:h.value,m=p??0,g=ja(),[v,y]=Ne.useState(""),[_,S]=Ne.useState(0),[E,T]=Ne.useState(!1);let N=`${m}`;const R=n.trim(),C=Kc(e);E&&(N=g?up(v,_,1,"$219+"):v),i.writefullwidth=32,Fn(` # ${C}${R} $green${N}`,i,!1),i.writefullwidth=void 0,Fn(` +`,i,!1);const O=Ne.useCallback(U=>{const L=U.alt?10:1;Ac(u,Math.min(c,m+L))},[c,m,u]),M=Ne.useCallback(U=>{const L=U.alt?10:1;Ac(u,Math.max(l,m-L))},[l,m,u]),I=Ne.useCallback(()=>{T(U=>{const L=!U;if(L){const P=`${p}`;y(P),S(P.length)}else{const P=parseFloat(v),b=isNaN(P)?0:P;Ac(s,Math.min(c,Math.max(l,b)))}return L})},[c,l,v,s,p]);return p!==void 0&&ve.jsxs(ve.Fragment,{children:[e&&ve.jsx(ms,{MOVE_LEFT:M,MOVE_RIGHT:O,OK_BUTTON:I}),E&&ve.jsxs(Cm,{blockhotkeys:!0,children:[ve.jsx(_p,{hotkey:"ctrl+c",children:()=>{console.info("copy")}}),ve.jsx(_p,{hotkey:"ctrl+v",children:()=>{console.info("paste")}}),ve.jsx(_p,{hotkey:"ctrl+a",children:()=>{console.info("select all")}}),ve.jsx(ms,{MOVE_LEFT:()=>{S(U=>Math.max(0,U-1))},MOVE_RIGHT:()=>{S(U=>Math.min(v.length,U+1))},CANCEL_BUTTON:I,OK_BUTTON:I,keydown:U=>{switch($t(U.key)){case"delete":v.length>0&&y(L=>up(L,_,1));break;case"backspace":_>0&&(y(L=>up(L,_-1,1)),S(L=>Math.max(0,L-1)));break}U.key.length===1&&v.lengthup(L,_,0,U.key)),S(L=>L+1))}})]})]})}function ude({chip:t,active:e,label:n,args:r,context:i}){const[s,o,a]=[so(r[0],""),so(r[1],""),so(r[2],"")];let l,c;o===""?(l="L ",c=" H"):a===""?(l="L ",c=` ${o}`):(l=`${o} `,c=` ${a}`);const u=0,h=8,p=md(t,s),m=nA(p),g=(m==null?void 0:m.value)??0,v=ja(),y=n.trim(),_=Kc(e);Fn(` $red $29 ${_}${y} `,i,!1);const E=up("----:----",g,1,`$green${e?v?"$26":"$27":"$4"}${_}`).replaceAll("-","$7").replaceAll(":","$9");Fn(`${_}${l}${E}${c} $green${g+1} +`,i,!1);const T=Ne.useCallback(R=>{const C=R.alt?10:1;Ac(p,Math.min(h,g+C))},[h,g,p]),N=Ne.useCallback(R=>{const C=R.alt?10:1;Ac(p,Math.max(u,g-C))},[u,g,p]);return ve.jsx(ve.Fragment,{children:e&&ve.jsx(ms,{MOVE_LEFT:N,MOVE_RIGHT:T})})}function hde({chip:t,active:e,label:n,args:r,context:i}){const[s,...o]=[so(r[0],""),...r.slice(1)],a=0,l=o.length-1,c=md(t,s),u=nA(c),h=(u==null?void 0:u.value)??0,p=ja(),m=`${o[h]}`,g=n.trim(),v=Kc(e);Fn(` $dkred ? ${v}${g} `,i,!1);const y=e?p?"$26":"$27":"/";Fn(`${h+1}$green${y}${v}${l+1}`,i,!1),i.writefullwidth=32,Fn(` $green${m}`,i,!1),i.writefullwidth=void 0,Fn(` +`,i,!1);const _=Ne.useCallback(E=>{const T=E.alt?10:1;Ac(c,Math.min(l,h+T))},[l,h,c]),S=Ne.useCallback(E=>{const T=E.alt?10:1;Ac(c,Math.max(a,h-T))},[a,h,c]);return ve.jsx(ve.Fragment,{children:e&&ve.jsx(ms,{MOVE_LEFT:S,MOVE_RIGHT:_})})}function fde({chip:t,active:e,label:n,args:r,context:i}){const s=so(r[0],""),o=md(t,s),a=nU(o),l=a==null?void 0:a.value,c=(l==null?void 0:l.toJSON())??"",u=ja(),[h,p]=Ne.useState(0),[m,g]=Ne.useState(!1),[v,y]=Ne.useState(void 0),_=`${c} `,S=n.trim(),E=Kc(e);Fn(`$green $20 ${E}${S} $green`,i,!1);const T=i.x,R=i.y*i.width;i.writefullwidth=32,Fn(`${_}`,i,!1),i.writefullwidth=void 0,Fn(` +`,i,!1);const C=Z(v),O=i.width-T-2,M=C?Math.min(v,h):h;let I=C?Math.max(v,h):h;C&&(I!==M&&I===h&&--I,Ky(T+M+R,T+I+R,15,8,i)),m&&u&&Xy(T+h+R,"Û",i);function U(){Z(l)&&(p(M),y(void 0),l.delete(M,I-M+1))}return ve.jsxs(ve.Fragment,{children:[e&&ve.jsx(ms,{OK_BUTTON:()=>{l&&(g(!0),p(l.length),y(void 0))}}),m&&ve.jsx(Cm,{blockhotkeys:!0,children:ve.jsx(ms,{MOVE_LEFT:L=>{L.shift?Z(v)||y(Cn(h-1,0,c.length)):y(void 0),p(P=>Cn(P-1,0,c.length))},MOVE_RIGHT:L=>{L.shift?Z(v)||y(h):y(void 0),p(P=>Cn(P+1,0,c.length))},CANCEL_BUTTON:()=>{g(!1),p(c.length),y(void 0)},OK_BUTTON:()=>g(!1),keydown:L=>{if(!l)return;const{key:P}=L,b=$t(P),H={alt:L.altKey,ctrl:Yf?L.metaKey:L.ctrlKey,shift:L.shiftKey},V=l.toJSON();switch(b){case"delete":C?U():V.length>0&&l.delete(h,1);break;case"backspace":C?U():h>0&&(l.delete(h-1,1),p(B=>Math.max(0,B-1)));break;default:if(H.ctrl)switch(b){case"a":y(0),p(V.length);break;case"c":Z(navigator.clipboard)&&navigator.clipboard.writeText(l.toJSON()).catch(B=>console.error(B));break;case"v":Z(navigator.clipboard)&&navigator.clipboard.readText().then(B=>{C&&U(),l.insert(h,B),p(h+B.length)}).catch(B=>console.error(B));break;case"x":Z(navigator.clipboard)&&navigator.clipboard.writeText(l.toJSON()).then(()=>U()).catch(B=>console.error(B));break}else H.alt||P.length===1&&V.lengthB+1));break}}})})]})}function dde({item:t,active:e}){const n=Ib(),r=Wa();if(r.iseven=r.y%2===0,typeof t=="string")return ve.jsx(ode,{player:n,item:t,context:r});if(ln(t)){const[i,s,o,...a]=t;if(typeof i!="string"||typeof s!="string"||typeof o!="string")return null;const l={player:n,chip:i,active:e,label:s,args:a,context:r};switch($t(o)){case"hk":case"hotkey":return ve.jsx(ade,{...l});case"hyperlink":return ve.jsx(lde,{...l});case"rn":case"range":return ve.jsx(ude,{...l});case"sl":case"select":return ve.jsx(hde,{...l});case"nm":case"number":return ve.jsx(cde,{...l});case"tx":case"text":return ve.jsx(fde,{...l})}zA(r)}return null}function jA({store:t,children:e}){return ve.jsx(GA.Provider,{value:t,children:e})}function $A({width:t,height:e}){const n=Ne.useContext(GA),[r,i,s]=kb(n,qc(o=>[o.char,o.color,o.bg,o.render]));return t>0&&e>0&&ve.jsx(SU,{char:r.slice(),color:i.slice(),bg:s.slice(),width:t,height:e})}function cF({margin:t=1,selected:e=-1,width:n,height:r,color:i,bg:s,text:o}){const a=WA(n,r,0,i,s),l=a.getState(),c={...Vm(n,r,i,s,0,t,n-t,r),...a.getState(),x:t};return ide(l,0,i,s),l.changed(),ve.jsxs(jA,{store:a,children:[ve.jsx(Au.Provider,{value:c,children:o.map((u,h)=>ve.jsx(dde,{item:u,active:h===e},h))}),ve.jsx($A,{width:n,height:r})]})}var pde=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.01,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1/(2*Math.PI);return r/Math.atan(1/n)*Math.atan(Math.sin(2*Math.PI*e*i)/n)},mde=function(e){return 1/(1+e+.48*e*e+.235*e*e*e)};function gde(t,e,n){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:.25,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:.01,s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1/0,o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:mde,a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:.001,l="velocity_"+e;if(t.__damp===void 0&&(t.__damp={}),t.__damp[l]===void 0&&(t.__damp[l]=0),Math.abs(t[e]-n)<=a)return t[e]=n,!1;r=Math.max(1e-4,r);var c=2/r,u=o(c*i),h=t[e]-n,p=n,m=s*r;h=Math.min(Math.max(h,-m),m),n=t[e]-h;var g=(t.__damp[l]+c*h)*i;t.__damp[l]=(t.__damp[l]-c*g)*u;var v=n+(h+g)*u;return p-t[e]>0==v>p&&(v=p,t.__damp[l]=(v-p)/i),t[e]=v,!0}const _de=2,vde=14,uF=vde*_de;function yde(t){return FG(t,uF*.5)}function xde(t,e,n,r,i=1.235){function s(a){return pde(a,r)}gde(t.userData,e,n,i,r,uF*12,s),t.position[e]=yde(t.userData[e]);const o=n-t.position.y;return Math.abs(o)<.1}function _I({x:t,y:e,color:n,on:r=232,off:i=7,alt:s}){const o=ja(),a=sde(),l=Ne.useRef(0),c=Z(s)?l.current%2===0?r:s:r;return Lr(a,a.width,a.height,t,e,{char:o?c:i,color:n}),a.changed(),o&&++l.current,null}function Sde({store:t,children:e}){return ve.jsx(oF.Provider,{value:t,children:e})}function Ede({width:t,height:e}){const n=Ne.useContext(oF),[r]=kb(n,qc(i=>[i.dither,i.render]));return t>0&&e>0&&ve.jsx(Oy,{alphas:r.slice(),width:t,height:e})}function wde({name:t,width:e,height:n,color:r,bg:i,text:s,shouldclose:o}){const{viewport:a}=_a(),l=e-3,c=n-3,u=WA(e,n,0,r,i),h=rde(l,c,0),p=Ne.useContext(Yy),m=u.getState();for(let b=1;b2&&b{o&&p.didclose()},[o,p]);Ne.useEffect(()=>{if(I.current&&!o){const b=a.height;I.current.position.y=b,I.current.userData.y=b,I.current.userData.vy=0}},[o]),Lv(Ne.useCallback((b,H)=>{if(Z(I.current)){const V=o?n*2*-Vi:0;xde(I.current,"y",V,H)&&U()}},[o,U,n]));const L=Ne.useCallback(b=>{const H=b.alt?10:1;E(V=>Math.max(0,V-H))},[E]),P=Ne.useCallback(b=>{const H=b.alt?10:1;E(V=>Math.min(s.length,V+H))},[E,s.length]);return ve.jsx(jA,{store:u,children:ve.jsx(Sde,{store:h,children:ve.jsx("group",{ref:I,"position-y":1e6,children:ve.jsxs(Cm,{children:[ve.jsx(ms,{MOVE_UP:L,MOVE_DOWN:P,CANCEL_BUTTON:p.sendclose}),ve.jsx($A,{width:e,height:n}),ve.jsxs("group",{position:[2*os,2*Vi,0],children:[ve.jsx(Ede,{width:l,height:c}),ve.jsx(cF,{name:t,width:l,height:c,margin:0,color:r,bg:wn.ONCLEAR,text:N,selected:R}),ve.jsx(_I,{x:1,y:1}),ve.jsx(_I,{x:1,y:2+R,on:26,alt:27,off:45,color:12})]})]})})})})}function vI({rect:t,shouldclose:e=!1}){switch(t.type){case 0:return ve.jsx(cF,{name:t.name,width:t.width,height:t.height,color:14,bg:1,text:t.text});case 1:return ve.jsx(wde,{name:t.name,width:t.width,height:t.height,color:14,bg:1,text:t.text,shouldclose:e});case 2:return ve.jsx(Cae,{width:t.width,height:t.height})}return null}function Tde(){const t=_a(g=>g.viewport),{width:e,height:n}=t.getCurrentViewport(),r=Math.floor(e/os),i=Math.floor(n/Vi),s=e-r*os,o=n-i*Vi,[a,l]=Ne.useState(),[c,u]=ss(xte(g=>[g.gadget.player,g.gadget.panels]));if(r<1||i<1)return null;const h={name:"main",type:2,x:0,y:0,width:r,height:i,text:[]},p=[];let m=!0;return u.forEach(g=>{let v;switch(g.edge){case xi.LEFT:v={name:g.name,type:0,x:h.x,y:h.y,width:g.size,height:h.height,text:g.text},h.x+=g.size,h.width-=g.size,p.push(v);break;default:case xi.RIGHT:v={name:g.name,type:0,x:h.x+h.width-g.size,y:h.y,width:g.size,height:h.height,text:g.text},h.width-=g.size,p.push(v);break;case xi.TOP:v={name:g.name,type:0,x:h.x,y:h.y,width:h.width,height:g.size,text:g.text},h.y+=g.size,h.height-=g.size,p.push(v);break;case xi.BOTTOM:v={name:g.name,type:0,x:h.x,y:h.y+h.height-g.size,width:h.width,height:g.size,text:g.text},h.height-=g.size,p.push(v);break;case xi.SCROLL:v={name:g.name,type:1,x:0,y:0,width:Cn(g.size||50,24,h.width-2),height:Cn(18,8,h.height-8),text:g.text},v.x=h.x+Math.floor((h.width-v.width)*.5),v.y=h.y+Math.floor((h.height-v.height)*.5),m=!1,Lf(a,v)||l(Fi(v))}}),p.unshift(h),ve.jsx(Yy.Provider,{value:{sendmessage(g,v){Yt.emit(g,"gadget",v,c)},sendclose(){AW("gadget",c)},didclose(){l(void 0)}},children:ve.jsxs("group",{position:[s*.5,o*.5,-512],children:[p.map(g=>ve.jsx("group",{position:[g.x*os,g.y*Vi,0],children:ve.jsx(vI,{rect:g})},g.name)),a&&ve.jsxs(Co.Fragment,{children:[ve.jsx("group",{position:[0,0,800],children:ve.jsx(Qoe,{width:r,height:i,alpha:.14})}),ve.jsx("group",{position:[a.x*os,a.y*Vi,900],children:ve.jsx(vI,{rect:a,shouldclose:m})})]},a.name)]})})}const bde=250,Ade=249,$p=wn.BLUE,Mde=wn.WHITE,Vc=wn.DKBLUE,Cde=wn.DKGRAY,hF=wn.BLACK,wv=1,k1=os*wv,I1=Vi*wv,fF=Ne.createContext({sendmessage(){}});function Cf(t,e,n,r,i){const s=qo(i);i.iseven=i.y%2===0,i.active.bg=e&&!t?hF:Vc,i.active.leftedge=s.left,i.active.rightedge=s.right,i.active.topedge=s.top,i.active.bottomedge=s.bottom,i.x=i.active.leftedge+n,i.y=i.active.topedge+r}function mf(t,e,n,r,i,s,o,a){const l=qo(i);i.iseven=i.y%2===0,i.active.bg=Vc,i.active.leftedge=l.left+s,i.active.rightedge=l.right-s,i.active.topedge=l.top+o,i.active.bottomedge=l.bottom-a,i.x=i.active.leftedge+n,i.y=i.active.topedge+r}function Rde(t){let e=0;return t.split(/\r?\n/).map(r=>{const i=e,s=`${r} +`;return e+=s.length,{start:i,code:s,end:i+r.length}})}function Nde(t){return t.reduce((e,n)=>{const r=n.code.length;return r>e?r:e},0)}function kde(t,e){for(let n=0;n{const e="nativeEvent"in t?t.nativeEvent:t;return{deltaX:e.deltaX||0,deltaY:e.deltaY||0,deltaZ:e.deltaZ||0,timeStamp:e.timeStamp}},Pde=t=>[t.deltaX,t.deltaY,t.deltaZ],G0=t=>{const e=Pde(t).map(Math.abs);return Math.max(...e)};var _c;(function(t){t.ALL_OTHER_CHECKS_FAILED="ALL_OTHER_CHECKS_FAILED",t.NO_PREVIOUS_EVENT_TO_COMPARE="NO_PREVIOUS_EVENT_TO_COMPARE",t.PAST_TIMESTAMP_EVENT="PAST_TIMESTAMP_EVENT",t.ENOUGH_TIME_PASSED="ENOUGH_TIME_PASSED",t.NON_DECREASING_DELTAS_OF_KNOWN_HUMAN="NON_DECREASING_DELTAS_OF_KNOWN_HUMAN",t.DELTA_MODULE_HAS_BEEN_INCREASING="DELTA_MODULE_HAS_BEEN_INCREASING"})(_c||(_c={}));class Dde{constructor({sensitivity:e=2,delay:n=100,increasingDeltasThreshold:r=3}={}){vt(this,"sensitivity");vt(this,"delay");vt(this,"increasingDeltasThreshold");vt(this,"previousEvents");this.sensitivity=Math.max(1,e),this.delay=Math.max(1,n),this.increasingDeltasThreshold=Math.max(2,r),this.previousEvents=[]}check(e){var s;if(!(("nativeEvent"in e?e.nativeEvent:e)instanceof Event))throw new Error(`"${e}" is not a valid event`);const r=Lde(e);if(G0(r)(((s=this.previousEvents.at(-1))==null?void 0:s.timeStamp)||0)&&this.previousEvents.push(r),i}isHuman(e){const n=this.previousEvents.at(-1);if(!n)return{isHuman:!0,reason:_c.NO_PREVIOUS_EVENT_TO_COMPARE};if(e.timeStampn.timeStamp+this.delay)return{isHuman:!0,reason:_c.ENOUGH_TIME_PASSED};const s=G0(e),o=G0(n);if(s>=o){if(this.previousEvents.length===1)return{isHuman:!0,reason:_c.NON_DECREASING_DELTAS_OF_KNOWN_HUMAN};if(this.increasingDeltasThreshold<=2||this.previousEvents.length>=this.increasingDeltasThreshold&&this.previousEvents.slice(-this.increasingDeltasThreshold).map(G0).every((u,h,p)=>h===0||u>p[h-1]))return{isHuman:!0,reason:_c.DELTA_MODULE_HAS_BEEN_INCREASING}}return{isHuman:!1,reason:_c.ALL_OTHER_CHECKS_FAILED}}}function yI(){}const Ude=Co.forwardRef(function({args:e,children:n,...r},i){const s=Co.useRef(null);return Co.useImperativeHandle(i,()=>s.current),ve.jsxs("mesh",{ref:s,...r,children:[ve.jsx("planeGeometry",{attach:"geometry",args:e}),n]})}),Fde=Co.forwardRef(function({blocking:e=!1,cursor:n="default",x:r=0,y:i=0,width:s=1,height:o=1,opacity:a=1,visible:l=!0,...c},u){const h=s*.5,p=o*.5,m=[(r+h)*os,(i+p)*Vi,0],g=Ny();return ve.jsx(Ude,{ref:u,args:[s*os,o*Vi],userData:{blocking:e,cursor:n,clippingPlanes:g},onClick:e?yI:void 0,onPointerMove:e?yI:void 0,position:m,...c,children:ve.jsx("meshBasicMaterial",{color:"white",opacity:a,visible:l,transparent:a!==1,clippingPlanes:g})})}),Bde=new Dde({sensitivity:Yf?7:2}),xI=4,zde=.75;function Vde(t){const e=Cn(t,-xI,xI);return Math.round(e*zde)}function pF({debug:t=!1,disabled:e=!1,blocking:n=!0,cursor:r="pointer",x:i=0,y:s=0,width:o=30,height:a=10,children:l,onScroll:c,...u}){return ve.jsxs("group",{...u,children:[ve.jsx(Fde,{blocking:n,cursor:r,visible:t,x:i,y:s,width:o,height:a,onWheel:h=>{e||!Bde.check(h)||c==null||c(Vde(h.deltaY))}}),l]})}function Hde({tapeycursor:t,logrowtotalheight:e}){const n=ja(),r=Wa(),i=Tr(),s=Ib(),o=qo(r),a=i.buffer[i.bufferindex];let l=i.xcursor,c=i.xcursor,u=!1;Z(i.xselect)&&Z(i.yselect)&&(u=!0,l=Math.min(i.xcursor,i.xselect),c=Math.max(i.xcursor,i.xselect),i.xcursor!==i.xselect&&--c);const h=c-l+1,p=i.ycursor===0,m=u?a.substring(l,c+1):a;function g(O,M,I){i.bufferindex>0&&Tr.setState({bufferindex:0}),i.buffer[0]=Ide(a,O,M,I),Tr.setState({buffer:i.buffer,xselect:void 0,xcursor:O+(I??"").length})}function v(O){const M=i.buffer.length-1,I=Cn(O,0,M);Tr.setState({bufferindex:I,xcursor:i.buffer[I].length,ycursor:0,xselect:void 0,yselect:void 0})}function y(O){O?Z(i.xselect)||Tr.setState({xselect:i.xcursor,yselect:i.ycursor}):Tr.setState({xselect:void 0,yselect:void 0})}function _(){Z(i.xselect)&&(Tr.setState({xcursor:l,xselect:void 0,yselect:void 0}),g(l,h))}function S(){Tr.setState({xcursor:a.length,ycursor:0,xselect:void 0,yselect:void 0})}Cf(!1,!1,0,0,r);const E="main:0.20.27 - if lost try #help";r.x=o.right-E.length,Fn(`$dkcyan${E}`,r,!0);const T="$196",R="$205".repeat(o.width-6);Cf(!1,!1,0,o.height-2,r),Fn(` ${T}${R}${T} `,r,!0);const C=a.padEnd(o.width," ");if(Cf(!1,!1,0,o.height-1,r),Fn(C,r,!0),Z(i.xselect)&&Z(i.yselect)&&i.xcursor!==i.xselect){const O=Math.min(i.xcursor,i.xselect),M=Math.min(i.ycursor,i.yselect),I=Math.max(i.xcursor,i.xselect)-1,U=Math.max(i.ycursor,i.yselect);for(let L=M;L<=U;++L){const P=O+(o.bottom-L)*o.width,b=I+(o.bottom-L)*o.width;Ky(P,b,15,8,r)}}if(n){const O=o.left+i.xcursor,M=o.top+t;Xy(O+M*r.width,"Ý",r)}return Ne.useEffect(()=>{let O=i.scroll;t<4&&O++,t>o.bottom-4&&O--,Tr.setState({scroll:Math.round(Cn(O,0,e))})},[i.scroll,t,e,o.bottom]),r.changed(),ve.jsxs(ve.Fragment,{children:[ve.jsx(pF,{blocking:!0,x:o.left,y:o.top,width:o.width,height:o.height,onScroll:O=>{y(!1),Tr.setState({ycursor:Cn(Math.round(i.ycursor-O),0,e)})}}),ve.jsx(ms,{keydown:O=>{const{key:M}=O,I=$t(M),U=Py(O);switch(I){case"arrowleft":y(U.shift),U.ctrl?Tr.setState({xcursor:0}):Tr.setState({xcursor:Cn(i.xcursor-(U.alt?10:1),0,o.right)});break;case"arrowright":y(U.shift),U.ctrl?Tr.setState({xcursor:p?a.length:o.right}):Tr.setState({xcursor:Cn(i.xcursor+(U.alt?10:1),0,o.right)});break;case"arrowup":U.ctrl?v(i.bufferindex+1):(y(U.shift),Tr.setState({ycursor:Cn(Math.round(i.ycursor+(U.alt?10:1)),0,e)}));break;case"arrowdown":U.ctrl?v(i.bufferindex-1):(y(U.shift),Tr.setState({ycursor:Cn(Math.round(i.ycursor-(U.alt?10:1)),0,e)}));break;case"enter":{const L=u?m:a;L.length&&(p?(Tr.setState({xcursor:0,bufferindex:0,xselect:void 0,yselect:void 0,buffer:["",L,...i.buffer.slice(1).filter(P=>P!==L)]}),Dv("tape",L,s)):S());break}case"esc":case"escape":ST("tape");break;case"tab":WO("tape",!U.shift);break;case"delete":p?u?_():a.length>0&&g(i.xcursor,1):S();break;case"backspace":p?u?_():i.xcursor>0&&g(i.xcursor-1,1):S();break;default:if(U.ctrl)switch(I){case"a":Tr.setState({xselect:0,yselect:0,xcursor:a.length,ycursor:0});break;case"c":p&&Z(navigator.clipboard)?navigator.clipboard.writeText(m).catch(L=>console.error(L)):S();break;case"v":p&&Z(navigator.clipboard)?navigator.clipboard.readText().then(L=>{const P=L.replaceAll("\r","");u?g(l,h,P):g(i.xcursor,0,P)}).catch(L=>console.error(L)):S();break;case"x":p&&Z(navigator.clipboard)?navigator.clipboard.writeText(m).then(()=>_()).catch(L=>console.error(L)):S();break}else U.alt||M.length===1&&(p&&i.xcursor<=a.length?u?(g(l,h,M),Tr.setState({xselect:void 0})):g(i.xcursor,0,M):S());break}}})]})}function Gde({blink:t,active:e,prefix:n,label:r,words:i,y:s}){const o=Wa(),a=Ne.useCallback(()=>{if(Z(navigator.clipboard)){const[,...c]=i,u=c.join(" ");navigator.clipboard.writeText(u).then(()=>hn("copyit","copied!")).catch(h=>console.error(h))}},[i]),l=Kc(!!e);return Cf(!!t,!!e,0,s,o),Fn(`${n} $purple$16 $yellowCOPYIT ${l}${r}`,o,!0),o.changed(),e&&ve.jsx(ms,{OK_BUTTON:a})}function Wde({blink:t,active:e,prefix:n,label:r,words:i,y:s}){const o=Wa(),a=Ne.useContext(fF),l=Ne.useCallback(()=>{const[u,h]=i;a.sendmessage(u,h)},[i,a]),c=Kc(!!e);return Cf(!!t,!!e,0,s,o),Fn(`${n} $purple$16 ${c}${r}`,o,!0),o.changed(),e&&ve.jsx(ms,{OK_BUTTON:l})}function mF({blink:t,active:e,text:n,y:r}){const i=Wa(),s=qo(i),o=n.startsWith("!");if(Cf(!!t,!!e,0,r,i),i.active.bottomedge=s.bottom,Fn(o?"":n,i,!0),o){const[a,...l]=n.slice(1).split("!"),c=`${l.join("!")}`;let u="PRESS ME";const h=[];qy(c,!0).tokens.forEach(y=>{switch(y.tokenType){case BA:u=y.image.slice(1);break;default:h.push(y.image);break}});const[m,...g]=h,v={blink:t,active:e,prefix:a,label:u,words:g,y:r};switch($t(m)){case"hk":case"hotkey":return null;case"rn":case"range":return null;case"sl":case"select":return null;case"nm":case"number":return null;case"tx":case"text":return null;case"copyit":return ve.jsx(Gde,{...v,words:h});default:case"hyperlink":return ve.jsx(Wde,{...v,words:h})}}return null}function jde(t){const e=ja();return ve.jsx(mF,{active:!0,blink:e,...t})}function O1(){const t=Ib(),[e,n]=es(qc(p=>[p.terminal.logs,p.editor.open])),r=Wa(),i=Tr(),s=qo(r),o=e.map(p=>{const[,m,g,...v]=p;let y="$white";switch(m){case"debug":y="$yellow";break;case"error":y="$red";break}const _=v.map(T=>`${T}`).join(" "),S=_.startsWith("!"),E=`$blue[${y}${g}$blue]`;return`${S?"!":""}${E} ${_}`}),a=o.map(p=>{if(p.startsWith("!"))return 1;const m=HA(p,s.width,s.height);return(m==null?void 0:m.y)??1});let l=0,c=s.bottom-1;const u=a.map(p=>(c-=p,l+=p,c));++l;const h=s.bottom-i.ycursor+i.scroll;return ve.jsxs(ve.Fragment,{children:[ve.jsx(qA,{context:r}),ve.jsxs(fF.Provider,{value:{sendmessage(p,m){const[g,v]=Ode(p);if(g==="self"){const y=`#${v} ${m??""}`;Dv("tape",y,t)}else Yt.emit(`${g}:${v}`,"gadget",m,t)}},children:[o.map((p,m)=>{const g=u[m]+i.scroll,v=a[m],y=g+v;return y<0||g>s.bottom-1?null:!n&&h>=g&&h[m.editor.type,m.editor.title])),o=ja(),a="$205".repeat(e.width-4);mf(!1,!1,0,1,t,0,0,0),Fn(`$179$${o?"7":"232"}$200${a}$181`,t,!0);const c=` ${`[${i}] `}${s} `,u=HA(c,e.width,e.height),h=(u==null?void 0:u.measuredwidth)??1,p=Math.round(e.width*.5)-Math.round(h*.5);return mf(!1,!1,p,0,t,0,0,0),Fn(c,t,!0),t.changed(),null}function qde({xcursor:t,ycursor:e,xoffset:n,yoffset:r,rows:i,codepage:s}){var P,b;const o=ja(),a=Wa(),l=Ne.useRef(),c=hr(),u=qo(a),h=es(H=>H.editor.player),p=dF(s),m=Z(p)?p.toJSON():"",g=i.length-1,v=t+1-n,y=e+2-r;if(Z(s)){const H=((P=l.current)==null?void 0:P.x)!==v||((b=l.current)==null?void 0:b.y)!==y;if(o||H){const V=u.left+v,B=u.top+y;B>u.top+1&&Bu.left&&V0&&(p==null||p.delete(H,V)),Z(B)&&(p==null||p.insert(H,B)),hr.setState({cursor:H+(B??"").length,select:void 0})}function I(){Z(c.select)&&(hr.setState({cursor:E}),M(E,R))}function U(){hr.setState({cursor:_,select:void 0})}const L=Ne.useCallback(function(V){const B=Math.round(e+V);if(B<0)hr.setState({cursor:0});else if(B>g)hr.setState({cursor:_});else{const z=i[B];hr.setState({cursor:z.start+Math.min(t,z.code.length-1)})}},[_,i,g,t,e]);return a.changed(),ve.jsxs(ve.Fragment,{children:[ve.jsx(pF,{blocking:!0,x:u.left,y:u.top,width:u.width,height:u.height,onScroll:H=>L(H*.75)}),ve.jsx(ms,{keydown:H=>{if(!Z(p))return;const{key:V}=H,B=$t(V),z=Py(H);switch(B){case"arrowleft":if(O(z.shift),z.ctrl)hr.setState({cursor:S.start});else{const W=c.cursor-(z.alt?10:1);hr.setState({cursor:Cn(W,0,_)})}break;case"arrowright":if(O(z.shift),z.ctrl)hr.setState({cursor:S.end});else{const W=c.cursor+(z.alt?10:1);hr.setState({cursor:Cn(W,0,_)})}break;case"arrowup":O(z.shift),z.ctrl?hr.setState({cursor:0}):L(z.alt?-10:-1);break;case"arrowdown":O(z.shift),z.ctrl?hr.setState({cursor:_}):L(z.alt?10:1);break;case"enter":Z(p)&&(p.insert(c.cursor,` +`),hr.setState({cursor:c.cursor+1}));break;case"esc":case"escape":z.shift||z.alt||z.ctrl?ST("tape"):UW("editor");break;case"tab":WO("editor",!z.shift);break;case"delete":N?I():M(c.cursor,1);break;case"backspace":N?I():m.length>0&&M(Math.max(c.cursor-1,0),1);break;default:if(z.ctrl)switch(B){case"a":hr.setState({cursor:_,select:0});break;case"c":Z(navigator.clipboard)?navigator.clipboard.writeText(C).catch(W=>Pn("tape","clipboard",W)):U();break;case"v":Z(navigator.clipboard)?navigator.clipboard.readText().then(W=>{const K=W.replaceAll("\r","");N?M(E,R,K):M(c.cursor,0,K)}).catch(W=>Pn("tape","clipboard",W)):U();break;case"x":Z(navigator.clipboard)?navigator.clipboard.writeText(C).then(()=>I()).catch(W=>Pn("tape","clipboard",W)):U();break;case"p":Dv("editor",C,h),hn("editor",`running: ${C}`);break}else if(!z.alt){if(V.length===1)if(N)M(E,R,V);else{const W=c.cursor+V.length;p.insert(c.cursor,V),hr.setState({cursor:W})}}break}}})]})}function Xde({ycursor:t,xoffset:e,yoffset:n,rows:r,codepage:i}){const s=ja(),o=Wa(),a=hr(),l=qo(o);if(!Z(i)){const m=(s?"|":"-").repeat(3);return mf(!1,!1,0,0,o,1,2,1),Fn(` ${m} LOADING ${m}`,o,!0),null}let c=a.cursor,u=a.cursor,h=!1;Z(a.select)&&(h=!0,c=Math.min(a.cursor,a.select),u=Math.max(a.cursor,a.select),a.cursor!==a.select&&--u);const p=l.left+1;mf(!1,!1,-e,-n,o,1,2,1);for(let m=0;m=c){const _=Math.max(g.start,c)-g.start-e,S=Math.min(g.end,u)-g.start-e,E=l.width-3,T=1+o.y*o.width,N=Math.max(0,_),R=Math.min(E,S);N<=E&&R>=p&&Ky(T+N,T+R,Mde,Cde,o)}if(++o.y,o.y>=l.bottom)break}return o.disablewrap=!1,null}function L1(){const[t]=es(qc(v=>[v.editor])),e=Wa(),n=hr(),r=nU(jO(t.book,t.page)),i=qo(e);Ne.useEffect(()=>(WW("editor",t.book,t.page,t.player),()=>{jW("editor",t.book,t.page,t.player)}),[t.book,t.page,t.player]);const s=dF(r),o=Z(s)?s.toJSON():"",a=Rde(o),l=kde(n.cursor,a),c=n.cursor-a[l].start,u=Nde(a),h={rows:a,xcursor:c,ycursor:l,codepage:r,xoffset:n.xscroll,yoffset:n.yscroll},p=32,m=(Math.round(u/p)+1)*p,g=a.length;return Ne.useEffect(()=>{let v=n.xscroll;const y=c-v,_=i.width-3;let S=Math.round(Cn(Math.abs(y)*.5,1,p));S<8&&(S=1),y>_-8&&(v+=S),y<8&&(v-=S);let E=n.yscroll;const T=l-E,N=i.height-4,R=Math.round(N*.5);let C=Math.round(Cn(Math.abs(T)*.25,1,R));C<8&&(C=1),T>N-4&&(E+=C),T<4&&(E-=C),setTimeout(()=>hr.setState({xscroll:Math.round(Cn(v,0,m)),yscroll:Math.round(Cn(E,0,g))}),16)},[c,m,n.xscroll,l,g,n.yscroll,i.width,i.height]),ve.jsxs(ve.Fragment,{children:[ve.jsx(qA,{context:e}),ve.jsx($de,{}),ve.jsx(Xde,{...h}),ve.jsx(qde,{...h})]})}function SI(t,e,n,r,i){return{...i,x:t,y:e,reset:{...i.reset,topedge:e,leftedge:t,rightedge:n,bottomedge:r},active:{...i.reset,topedge:e,leftedge:t,rightedge:n,bottomedge:r}}}function Kde({context:t}){const[e,n]=es(qc(c=>[c.layout,c.editor.open])),r=t.width-1,i=t.height-1,s=qo(t),o=Math.floor(s.height*.5),a=Ne.useMemo(()=>SI(0,0,r,o-1,t),[o,r,t]),l=Ne.useMemo(()=>SI(0,o,r,i,t),[o,r,i,t]);if(n){let c,u;switch(e){case Li.SPLIT_Y:case Li.SPLIT_Y_ALT:c=a,u=l;break}if(Z(c)&&Z(u))switch(e){case Li.SPLIT_Y:return ve.jsxs(ve.Fragment,{children:[ve.jsx(Au.Provider,{value:c,children:ve.jsx(O1,{})}),ve.jsx(Au.Provider,{value:u,children:ve.jsx(L1,{})})]});case Li.SPLIT_Y_ALT:return ve.jsxs(ve.Fragment,{children:[ve.jsx(Au.Provider,{value:c,children:ve.jsx(L1,{})}),ve.jsx(Au.Provider,{value:u,children:ve.jsx(O1,{})})]})}}return ve.jsx(ve.Fragment,{children:ve.jsx(Au.Provider,{value:t,children:n?ve.jsx(L1,{}):ve.jsx(O1,{})})})}function Yde(){const t=_a(_=>_.viewport),{width:e,height:n}=t.getCurrentViewport(),r=Math.floor(e/os),i=Math.floor(n/Vi),s=Math.floor(e/k1),o=Math.floor(n/I1),a=e-s*k1,l=n-o*I1;let c=0;const u=0,h=s;let p=o;const[m,g]=es(qc(_=>[_.layout,_.terminal.open]));switch(m){case Li.TOP:p=Math.round(o*.5);break;case Li.BOTTOM:p=Math.round(o*.5),c=o-p;break;default:case Li.FULL:break}const v=WA(h,p,0,$p,Vc),y={...Vm(h,p,$p,Vc),...v.getState()};return h<1||p<1?null:ve.jsx(jA,{store:v,children:ve.jsxs("group",{position:[0,0,900],children:[g&&ve.jsx(eae,{width:r,height:i,top:c,left:u,right:u+h-1,bottom:c+p-1}),ve.jsx("group",{position:[a*.5+u*k1,l+c*I1,1],scale:[wv,wv,1],children:g?ve.jsxs(Cm,{blockhotkeys:!0,children:[ve.jsx(qA,{context:y}),ve.jsx(Kde,{context:y}),ve.jsx($A,{width:h,height:p})]}):ve.jsx(_p,{hotkey:"Shift+?",children:()=>PW("tape")})})]})})}mT({OrthographicCamera:kv});Soe();function Zde(){const t=_a(p=>p.viewport),e=Ne.useRef(null),{width:n,height:r}=t.getCurrentViewport(),i=Ob($ne);i.minFilter=vr,i.magFilter=vr;const[s]=Ne.useState(()=>new One);Ne.useEffect(()=>{if(!Pne)return;document.body.appendChild(s.dom),s.showPanel(0),s.dom.style.cssText="position:fixed;bottom:0;left:0;";const p=wG(()=>s.begin()),m=TG(()=>s.end());return()=>{document.body.removeChild(s.dom),p(),m()}},[s]);const[o,a]=Ne.useState();Ne.useEffect(()=>{kne({benchmarksURL:"/benchmarks-min"}).then(a).catch(p=>Pn("gpu","detect",p))},[]);const l=!Une&&o&&o.tier>2&&!o.isMobile,c=_a(({set:p})=>p),u=_a(({size:p})=>p),h=_a(({camera:p})=>p);return Ne.useLayoutEffect(()=>{var p;(p=e.current)==null||p.updateProjectionMatrix()}),Ne.useLayoutEffect(()=>{const p=h;return c(()=>({camera:e.current})),()=>c(()=>({camera:p}))},[c,h,e]),ve.jsxs(ve.Fragment,{children:[ve.jsx("orthographicCamera",{ref:e,left:u.width/-2,right:u.width/2,top:u.height/2,bottom:u.height/-2,near:1,far:2e3,position:[0,0,1e3]}),ve.jsx("group",{"scale-x":-1,"rotation-z":Math.PI,children:ve.jsx("group",{position:[n*-.5,r*-.5,0],children:ve.jsxs(Cm,{children:[ve.jsx(Tde,{}),ve.jsx(Yde,{})]})})}),l&&ve.jsx(Tne,{children:ve.jsx(jne,{splat:i,viewheight:r})})]})}mT({BufferGeometry:Bo,Group:Qd,Mesh:Ao,MeshBasicMaterial:cT,OrthographicCamera:kv,PlaneGeometry:Zp,Points:jH});document.addEventListener("keydown",()=>{fd()});window.addEventListener("touchstart",()=>{fd()});window.addEventListener("click",()=>{fd()});window.addEventListener("dragover",t=>{t.preventDefault()});window.addEventListener("contextmenu",t=>{fd(),t.preventDefault()});window.addEventListener("paste",t=>{var n;if(!((n=t.clipboardData)!=null&&n.files.length))return;fd(),t.preventDefault(),[...t.clipboardData.files].forEach(r=>IE("loadfile",r,Y_()))});window.addEventListener("drop",t=>{var e,n;fd(),t.preventDefault(),(e=t.dataTransfer)!=null&&e.items?[...t.dataTransfer.items].forEach(i=>{if(i.kind==="file"){const s=i.getAsFile();Z(s)&&IE("loadfile",s,Y_())}}):[...((n=t.dataTransfer)==null?void 0:n.files)??[]].forEach(i=>IE("loadfile",i,Y_()))});function Jde(){return ve.jsx(Zde,{})}const EI=new xe,wI=new xe,TI=t=>({...IG(t),filter:e=>{const n=e.filter(o=>!(!o.object.visible||(o.object.userData.clippingPlanes??[]).some(l=>(l.projectPoint(o.point,EI),wI.subVectors(o.point,EI).normalize().round(),l.normal.equals(wI)===!1)))),r=n.findIndex(o=>o.object.userData.blocking),i=r===-1?n:n.slice(0,r+1);let s="default";return i.some(o=>o.object.userData.cursor?(s=o.object.userData.cursor,!0):!1),document.querySelectorAll("html, body").forEach(o=>{o.style.cursor=s}),i}}),bI=document.querySelector("canvas");if(Z(bI)){const t=RG(bI),e={dpr:1,flat:!0,linear:!0,shadows:!1,gl:{alpha:!1,stencil:!1,antialias:!1,preserveDrawingBuffer:!0}};t.configure({...e,events:TI,onCreated({gl:r}){r.localClippingEnabled=!0}});const n=LG((r,i)=>{t.configure({...e,events:TI,size:{width:r,height:i,top:0,left:0},onCreated({gl:s}){s.localClippingEnabled=!0}})},256);window.addEventListener("resize",()=>{n(GR(window.innerWidth),GR(window.innerHeight))}),t.render(ve.jsx(Jde,{}))}});export default Qde(); diff --git a/assets/index-D23shaEj.js b/assets/index-D23shaEj.js deleted file mode 100644 index 43e8fc3c..00000000 --- a/assets/index-D23shaEj.js +++ /dev/null @@ -1,4894 +0,0 @@ -var GF=Object.defineProperty;var WF=(n,e,t)=>e in n?GF(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var jF=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var vt=(n,e,t)=>WF(n,typeof e!="symbol"?e+"":e,t);var lde=jF((Rs,ks)=>{(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=t(i);fetch(i.href,s)}})();var Eo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Nc(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function $F(n){if(n.__esModule)return n;var e=n.default;if(typeof e=="function"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(r){var i=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return n[r]}})}),t}var dN={exports:{}},pv={},pN={exports:{}},Qt={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Bp=Symbol.for("react.element"),qF=Symbol.for("react.portal"),XF=Symbol.for("react.fragment"),KF=Symbol.for("react.strict_mode"),YF=Symbol.for("react.profiler"),ZF=Symbol.for("react.provider"),QF=Symbol.for("react.context"),JF=Symbol.for("react.forward_ref"),eB=Symbol.for("react.suspense"),tB=Symbol.for("react.memo"),nB=Symbol.for("react.lazy"),mC=Symbol.iterator;function rB(n){return n===null||typeof n!="object"?null:(n=mC&&n[mC]||n["@@iterator"],typeof n=="function"?n:null)}var mN={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},gN=Object.assign,_N={};function Zf(n,e,t){this.props=n,this.context=e,this.refs=_N,this.updater=t||mN}Zf.prototype.isReactComponent={};Zf.prototype.setState=function(n,e){if(typeof n!="object"&&typeof n!="function"&&n!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,n,e,"setState")};Zf.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function vN(){}vN.prototype=Zf.prototype;function Vw(n,e,t){this.props=n,this.context=e,this.refs=_N,this.updater=t||mN}var Hw=Vw.prototype=new vN;Hw.constructor=Vw;gN(Hw,Zf.prototype);Hw.isPureReactComponent=!0;var gC=Array.isArray,yN=Object.prototype.hasOwnProperty,Gw={current:null},xN={key:!0,ref:!0,__self:!0,__source:!0};function SN(n,e,t){var r,i={},s=null,o=null;if(e!=null)for(r in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)yN.call(e,r)&&!xN.hasOwnProperty(r)&&(i[r]=e[r]);var a=arguments.length-2;if(a===1)i.children=t;else if(1>8&255]+gi[n>>16&255]+gi[n>>24&255]+"-"+gi[e&255]+gi[e>>8&255]+"-"+gi[e>>16&15|64]+gi[e>>24&255]+"-"+gi[t&63|128]+gi[t>>8&255]+"-"+gi[t>>16&255]+gi[t>>24&255]+gi[r&255]+gi[r>>8&255]+gi[r>>16&255]+gi[r>>24&255]).toLowerCase()}function Li(n,e,t){return Math.max(e,Math.min(t,n))}function Zw(n,e){return(n%e+e)%e}function JB(n,e,t,r,i){return r+(n-e)*(i-r)/(t-e)}function e5(n,e,t){return n!==e?(t-n)/(e-n):0}function sp(n,e,t){return(1-t)*n+t*e}function t5(n,e,t,r){return sp(n,e,1-Math.exp(-t*r))}function n5(n,e=1){return e-Math.abs(Zw(n,e*2)-e)}function r5(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function i5(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function s5(n,e){return n+Math.floor(Math.random()*(e-n+1))}function o5(n,e){return n+Math.random()*(e-n)}function a5(n){return n*(.5-Math.random())}function c5(n){n!==void 0&&(bC=n);let e=bC+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function l5(n){return n*ip}function u5(n){return n*dp}function h5(n){return(n&n-1)===0&&n!==0}function f5(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function d5(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function p5(n,e,t,r,i){const s=Math.cos,o=Math.sin,a=s(t/2),c=o(t/2),l=s((e+r)/2),u=o((e+r)/2),h=s((e-r)/2),p=o((e-r)/2),m=s((r-e)/2),g=o((r-e)/2);switch(i){case"XYX":n.set(a*u,c*h,c*p,a*l);break;case"YZY":n.set(c*p,a*u,c*h,a*l);break;case"ZXZ":n.set(c*h,c*p,a*u,a*l);break;case"XZX":n.set(a*u,c*g,c*m,a*l);break;case"YXY":n.set(c*m,a*u,c*g,a*l);break;case"ZYZ":n.set(c*g,c*m,a*u,a*l);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function qh(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function Ri(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const m5={DEG2RAD:ip,RAD2DEG:dp,generateUUID:Jf,clamp:Li,euclideanModulo:Zw,mapLinear:JB,inverseLerp:e5,lerp:sp,damp:t5,pingpong:n5,smoothstep:r5,smootherstep:i5,randInt:s5,randFloat:o5,randFloatSpread:a5,seededRandom:c5,degToRad:l5,radToDeg:u5,isPowerOfTwo:h5,ceilPowerOfTwo:f5,floorPowerOfTwo:d5,setQuaternionFromProperEuler:p5,normalize:Ri,denormalize:qh};class St{constructor(e=0,t=0){St.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,r=this.y,i=e.elements;return this.x=i[0]*t+i[3]*r+i[6],this.y=i[1]*t+i[4]*r+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const r=this.dot(e)/t;return Math.acos(Li(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,r=this.y-e.y;return t*t+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const r=Math.cos(t),i=Math.sin(t),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*i+e.x,this.y=s*i+o*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Dt{constructor(e,t,r,i,s,o,a,c,l){Dt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,r,i,s,o,a,c,l)}set(e,t,r,i,s,o,a,c,l){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=t,u[4]=s,u[5]=c,u[6]=r,u[7]=o,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,r=e.elements;return t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=r[3],t[4]=r[4],t[5]=r[5],t[6]=r[6],t[7]=r[7],t[8]=r[8],this}extractBasis(e,t,r){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const r=e.elements,i=t.elements,s=this.elements,o=r[0],a=r[3],c=r[6],l=r[1],u=r[4],h=r[7],p=r[2],m=r[5],g=r[8],v=i[0],y=i[3],_=i[6],S=i[1],w=i[4],T=i[7],k=i[2],R=i[5],C=i[8];return s[0]=o*v+a*S+c*k,s[3]=o*y+a*w+c*R,s[6]=o*_+a*T+c*C,s[1]=l*v+u*S+h*k,s[4]=l*y+u*w+h*R,s[7]=l*_+u*T+h*C,s[2]=p*v+m*S+g*k,s[5]=p*y+m*w+g*R,s[8]=p*_+m*T+g*C,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],u=e[8];return t*o*u-t*a*l-r*s*u+r*a*c+i*s*l-i*o*c}invert(){const e=this.elements,t=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],u=e[8],h=u*o-a*l,p=a*c-u*s,m=l*s-o*c,g=t*h+r*p+i*m;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=h*v,e[1]=(i*l-u*r)*v,e[2]=(a*r-i*o)*v,e[3]=p*v,e[4]=(u*t-i*c)*v,e[5]=(i*s-a*t)*v,e[6]=m*v,e[7]=(r*c-l*t)*v,e[8]=(o*t-r*s)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,r,i,s,o,a){const c=Math.cos(s),l=Math.sin(s);return this.set(r*c,r*l,-r*(c*o+l*a)+o+e,-i*l,i*c,-i*(-l*o+c*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Yx.makeScale(e,t)),this}rotate(e){return this.premultiply(Yx.makeRotation(-e)),this}translate(e,t){return this.premultiply(Yx.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,-r,0,r,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,r=e.elements;for(let i=0;i<9;i++)if(t[i]!==r[i])return!1;return!0}fromArray(e,t=0){for(let r=0;r<9;r++)this.elements[r]=e[r+t];return this}toArray(e=[],t=0){const r=this.elements;return e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3],e[t+4]=r[4],e[t+5]=r[5],e[t+6]=r[6],e[t+7]=r[7],e[t+8]=r[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Yx=new Dt;function BN(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function pp(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function g5(){const n=pp("canvas");return n.style.display="block",n}const AC={};function jd(n){n in AC||(AC[n]=!0,console.warn(n))}function _5(n,e,t){return new Promise(function(r,i){function s(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:i();break;case n.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:r()}}setTimeout(s,t)})}function v5(n){const e=n.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function y5(n){const e=n.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}const hn={enabled:!0,workingColorSpace:Fl,spaces:{},convert:function(n,e,t){return this.enabled===!1||e===t||!e||!t||(this.spaces[e].transfer===bn&&(n.r=mc(n.r),n.g=mc(n.g),n.b=mc(n.b)),this.spaces[e].primaries!==this.spaces[t].primaries&&(n.applyMatrix3(this.spaces[e].toXYZ),n.applyMatrix3(this.spaces[t].fromXYZ)),this.spaces[t].transfer===bn&&(n.r=df(n.r),n.g=df(n.g),n.b=df(n.b))),n},fromWorkingColorSpace:function(n,e){return this.convert(n,this.workingColorSpace,e)},toWorkingColorSpace:function(n,e){return this.convert(n,e,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===ua?vv:this.spaces[n].transfer},getLuminanceCoefficients:function(n,e=this.workingColorSpace){return n.fromArray(this.spaces[e].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,e,t){return n.copy(this.spaces[e].toXYZ).multiply(this.spaces[t].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace}};function mc(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function df(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}const MC=[.64,.33,.3,.6,.15,.06],CC=[.2126,.7152,.0722],RC=[.3127,.329],kC=new Dt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),IC=new Dt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);hn.define({[Fl]:{primaries:MC,whitePoint:RC,transfer:vv,toXYZ:kC,fromXYZ:IC,luminanceCoefficients:CC,workingColorSpaceConfig:{unpackColorSpace:pr},outputColorSpaceConfig:{drawingBufferColorSpace:pr}},[pr]:{primaries:MC,whitePoint:RC,transfer:bn,toXYZ:kC,fromXYZ:IC,luminanceCoefficients:CC,outputColorSpaceConfig:{drawingBufferColorSpace:pr}}});let Ah;class x5{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{Ah===void 0&&(Ah=pp("canvas")),Ah.width=e.width,Ah.height=e.height;const r=Ah.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),t=Ah}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=pp("canvas");t.width=e.width,t.height=e.height;const r=t.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o0&&(r.userData=this.userData),t||(e.textures[this.uuid]=r),r}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==AN)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case D1:e.x=e.x-Math.floor(e.x);break;case wu:e.x=e.x<0?0:1;break;case U1:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case D1:e.y=e.y-Math.floor(e.y);break;case wu:e.y=e.y<0?0:1;break;case U1:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}or.DEFAULT_IMAGE=null;or.DEFAULT_MAPPING=AN;or.DEFAULT_ANISOTROPY=1;class gr{constructor(e=0,t=0,r=0,i=1){gr.prototype.isVector4=!0,this.x=e,this.y=t,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,r,i){return this.x=e,this.y=t,this.z=r,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,r=this.y,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*t+o[4]*r+o[8]*i+o[12]*s,this.y=o[1]*t+o[5]*r+o[9]*i+o[13]*s,this.z=o[2]*t+o[6]*r+o[10]*i+o[14]*s,this.w=o[3]*t+o[7]*r+o[11]*i+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,r,i,s;const c=e.elements,l=c[0],u=c[4],h=c[8],p=c[1],m=c[5],g=c[9],v=c[2],y=c[6],_=c[10];if(Math.abs(u-p)<.01&&Math.abs(h-v)<.01&&Math.abs(g-y)<.01){if(Math.abs(u+p)<.1&&Math.abs(h+v)<.1&&Math.abs(g+y)<.1&&Math.abs(l+m+_-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const w=(l+1)/2,T=(m+1)/2,k=(_+1)/2,R=(u+p)/4,C=(h+v)/4,O=(g+y)/4;return w>T&&w>k?w<.01?(r=0,i=.707106781,s=.707106781):(r=Math.sqrt(w),i=R/r,s=C/r):T>k?T<.01?(r=.707106781,i=0,s=.707106781):(i=Math.sqrt(T),r=R/i,s=O/i):k<.01?(r=.707106781,i=.707106781,s=0):(s=Math.sqrt(k),r=C/s,i=O/s),this.set(r,i,s,t),this}let S=Math.sqrt((y-g)*(y-g)+(h-v)*(h-v)+(p-u)*(p-u));return Math.abs(S)<.001&&(S=1),this.x=(y-g)/S,this.y=(h-v)/S,this.z=(p-u)/S,this.w=Math.acos((l+m+_-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this.z=e.z+(t.z-e.z)*r,this.w=e.w+(t.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class w5 extends Oc{constructor(e=1,t=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new gr(0,0,e,t),this.scissorTest=!1,this.viewport=new gr(0,0,e,t);const i={width:e,height:t,depth:1};r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:ns,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},r);const s=new or(i,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.colorSpace);s.flipY=!1,s.generateMipmaps=r.generateMipmaps,s.internalFormat=r.internalFormat,this.textures=[];const o=r.count;for(let a=0;a=0?1:-1,w=1-_*_;if(w>Number.EPSILON){const k=Math.sqrt(w),R=Math.atan2(k,_*S);y=Math.sin(y*R)/k,a=Math.sin(a*R)/k}const T=a*S;if(c=c*y+p*T,l=l*y+m*T,u=u*y+g*T,h=h*y+v*T,y===1-a){const k=1/Math.sqrt(c*c+l*l+u*u+h*h);c*=k,l*=k,u*=k,h*=k}}e[t]=c,e[t+1]=l,e[t+2]=u,e[t+3]=h}static multiplyQuaternionsFlat(e,t,r,i,s,o){const a=r[i],c=r[i+1],l=r[i+2],u=r[i+3],h=s[o],p=s[o+1],m=s[o+2],g=s[o+3];return e[t]=a*g+u*h+c*m-l*p,e[t+1]=c*g+u*p+l*h-a*m,e[t+2]=l*g+u*m+a*p-c*h,e[t+3]=u*g-a*h-c*p-l*m,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,r,i){return this._x=e,this._y=t,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const r=e._x,i=e._y,s=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(r/2),u=a(i/2),h=a(s/2),p=c(r/2),m=c(i/2),g=c(s/2);switch(o){case"XYZ":this._x=p*u*h+l*m*g,this._y=l*m*h-p*u*g,this._z=l*u*g+p*m*h,this._w=l*u*h-p*m*g;break;case"YXZ":this._x=p*u*h+l*m*g,this._y=l*m*h-p*u*g,this._z=l*u*g-p*m*h,this._w=l*u*h+p*m*g;break;case"ZXY":this._x=p*u*h-l*m*g,this._y=l*m*h+p*u*g,this._z=l*u*g+p*m*h,this._w=l*u*h-p*m*g;break;case"ZYX":this._x=p*u*h-l*m*g,this._y=l*m*h+p*u*g,this._z=l*u*g-p*m*h,this._w=l*u*h+p*m*g;break;case"YZX":this._x=p*u*h+l*m*g,this._y=l*m*h+p*u*g,this._z=l*u*g-p*m*h,this._w=l*u*h-p*m*g;break;case"XZY":this._x=p*u*h-l*m*g,this._y=l*m*h-p*u*g,this._z=l*u*g+p*m*h,this._w=l*u*h+p*m*g;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const r=t/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,r=t[0],i=t[4],s=t[8],o=t[1],a=t[5],c=t[9],l=t[2],u=t[6],h=t[10],p=r+a+h;if(p>0){const m=.5/Math.sqrt(p+1);this._w=.25/m,this._x=(u-c)*m,this._y=(s-l)*m,this._z=(o-i)*m}else if(r>a&&r>h){const m=2*Math.sqrt(1+r-a-h);this._w=(u-c)/m,this._x=.25*m,this._y=(i+o)/m,this._z=(s+l)/m}else if(a>h){const m=2*Math.sqrt(1+a-r-h);this._w=(s-l)/m,this._x=(i+o)/m,this._y=.25*m,this._z=(c+u)/m}else{const m=2*Math.sqrt(1+h-r-a);this._w=(o-i)/m,this._x=(s+l)/m,this._y=(c+u)/m,this._z=.25*m}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let r=e.dot(t)+1;return rMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Li(this.dot(e),-1,1)))}rotateTowards(e,t){const r=this.angleTo(e);if(r===0)return this;const i=Math.min(1,t/r);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const r=e._x,i=e._y,s=e._z,o=e._w,a=t._x,c=t._y,l=t._z,u=t._w;return this._x=r*u+o*a+i*l-s*c,this._y=i*u+o*c+s*a-r*l,this._z=s*u+o*l+r*c-i*a,this._w=o*u-r*a-i*c-s*l,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const r=this._x,i=this._y,s=this._z,o=this._w;let a=o*e._w+r*e._x+i*e._y+s*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=o,this._x=r,this._y=i,this._z=s,this;const c=1-a*a;if(c<=Number.EPSILON){const m=1-t;return this._w=m*o+t*this._w,this._x=m*r+t*this._x,this._y=m*i+t*this._y,this._z=m*s+t*this._z,this.normalize(),this}const l=Math.sqrt(c),u=Math.atan2(l,a),h=Math.sin((1-t)*u)/l,p=Math.sin(t*u)/l;return this._w=o*h+this._w*p,this._x=r*h+this._x*p,this._y=i*h+this._y*p,this._z=s*h+this._z*p,this._onChangeCallback(),this}slerpQuaternions(e,t,r){return this.copy(e).slerp(t,r)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),r=Math.random(),i=Math.sqrt(1-r),s=Math.sqrt(r);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class xe{constructor(e=0,t=0,r=0){xe.prototype.isVector3=!0,this.x=e,this.y=t,this.z=r}set(e,t,r){return r===void 0&&(r=this.z),this.x=e,this.y=t,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(NC.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(NC.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[3]*r+s[6]*i,this.y=s[1]*t+s[4]*r+s[7]*i,this.z=s[2]*t+s[5]*r+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*t+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*t+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*t+s[6]*r+s[10]*i+s[14])*o,this}applyQuaternion(e){const t=this.x,r=this.y,i=this.z,s=e.x,o=e.y,a=e.z,c=e.w,l=2*(o*i-a*r),u=2*(a*t-s*i),h=2*(s*r-o*t);return this.x=t+c*l+o*h-a*u,this.y=r+c*u+a*l-s*h,this.z=i+c*h+s*u-o*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[4]*r+s[8]*i,this.y=s[1]*t+s[5]*r+s[9]*i,this.z=s[2]*t+s[6]*r+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this.z=e.z+(t.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const r=e.x,i=e.y,s=e.z,o=t.x,a=t.y,c=t.z;return this.x=i*c-s*a,this.y=s*o-r*c,this.z=r*a-i*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const r=e.dot(this)/t;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return Qx.copy(this).projectOnVector(e),this.sub(Qx)}reflect(e){return this.sub(Qx.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const r=this.dot(e)/t;return Math.acos(Li(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return t*t+r*r+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,r){const i=Math.sin(t)*e;return this.x=i*Math.sin(r),this.y=Math.cos(t)*e,this.z=i*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,r){return this.x=e*Math.sin(t),this.y=r,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=r,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,r=Math.sqrt(1-t*t);return this.x=r*Math.cos(e),this.y=t,this.z=r*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Qx=new xe,NC=new zp;class Vp{constructor(e=new xe(1/0,1/0,1/0),t=new xe(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,r=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,mo),mo.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,r;return e.normal.x>0?(t=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),t<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(kd),Dg.subVectors(this.max,kd),Mh.subVectors(e.a,kd),Ch.subVectors(e.b,kd),Rh.subVectors(e.c,kd),il.subVectors(Ch,Mh),sl.subVectors(Rh,Ch),nu.subVectors(Mh,Rh);let t=[0,-il.z,il.y,0,-sl.z,sl.y,0,-nu.z,nu.y,il.z,0,-il.x,sl.z,0,-sl.x,nu.z,0,-nu.x,-il.y,il.x,0,-sl.y,sl.x,0,-nu.y,nu.x,0];return!Jx(t,Mh,Ch,Rh,Dg)||(t=[1,0,0,0,1,0,0,0,1],!Jx(t,Mh,Ch,Rh,Dg))?!1:(Ug.crossVectors(il,sl),t=[Ug.x,Ug.y,Ug.z],Jx(t,Mh,Ch,Rh,Dg))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,mo).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(mo).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Ka[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ka[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ka[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ka[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ka[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ka[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ka[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ka[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ka),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Ka=[new xe,new xe,new xe,new xe,new xe,new xe,new xe,new xe],mo=new xe,Pg=new Vp,Mh=new xe,Ch=new xe,Rh=new xe,il=new xe,sl=new xe,nu=new xe,kd=new xe,Dg=new xe,Ug=new xe,ru=new xe;function Jx(n,e,t,r,i){for(let s=0,o=n.length-3;s<=o;s+=3){ru.fromArray(n,s);const a=i.x*Math.abs(ru.x)+i.y*Math.abs(ru.y)+i.z*Math.abs(ru.z),c=e.dot(ru),l=t.dot(ru),u=r.dot(ru);if(Math.max(-Math.max(c,l,u),Math.min(c,l,u))>a)return!1}return!0}const b5=new Vp,Id=new xe,eS=new xe;class yv{constructor(e=new xe,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const r=this.center;t!==void 0?r.copy(t):b5.setFromPoints(e).getCenter(r);let i=0;for(let s=0,o=e.length;sthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Id.subVectors(e,this.center);const t=Id.lengthSq();if(t>this.radius*this.radius){const r=Math.sqrt(t),i=(r-this.radius)*.5;this.center.addScaledVector(Id,i/r),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(eS.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Id.copy(e.center).add(eS)),this.expandByPoint(Id.copy(e.center).sub(eS))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const Ya=new xe,tS=new xe,Fg=new xe,ol=new xe,nS=new xe,Bg=new xe,rS=new xe;class Qw{constructor(e=new xe,t=new xe(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Ya)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const r=t.dot(this.direction);return r<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Ya.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ya.copy(this.origin).addScaledVector(this.direction,t),Ya.distanceToSquared(e))}distanceSqToSegment(e,t,r,i){tS.copy(e).add(t).multiplyScalar(.5),Fg.copy(t).sub(e).normalize(),ol.copy(this.origin).sub(tS);const s=e.distanceTo(t)*.5,o=-this.direction.dot(Fg),a=ol.dot(this.direction),c=-ol.dot(Fg),l=ol.lengthSq(),u=Math.abs(1-o*o);let h,p,m,g;if(u>0)if(h=o*c-a,p=o*a-c,g=s*u,h>=0)if(p>=-g)if(p<=g){const v=1/u;h*=v,p*=v,m=h*(h+o*p+2*a)+p*(o*h+p+2*c)+l}else p=s,h=Math.max(0,-(o*p+a)),m=-h*h+p*(p+2*c)+l;else p=-s,h=Math.max(0,-(o*p+a)),m=-h*h+p*(p+2*c)+l;else p<=-g?(h=Math.max(0,-(-o*s+a)),p=h>0?-s:Math.min(Math.max(-s,-c),s),m=-h*h+p*(p+2*c)+l):p<=g?(h=0,p=Math.min(Math.max(-s,-c),s),m=p*(p+2*c)+l):(h=Math.max(0,-(o*s+a)),p=h>0?s:Math.min(Math.max(-s,-c),s),m=-h*h+p*(p+2*c)+l);else p=o>0?-s:s,h=Math.max(0,-(o*p+a)),m=-h*h+p*(p+2*c)+l;return r&&r.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(tS).addScaledVector(Fg,p),m}intersectSphere(e,t){Ya.subVectors(e.center,this.origin);const r=Ya.dot(this.direction),i=Ya.dot(Ya)-r*r,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),a=r-o,c=r+o;return c<0?null:a<0?this.at(c,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/t;return r>=0?r:null}intersectPlane(e,t){const r=this.distanceToPlane(e);return r===null?null:this.at(r,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let r,i,s,o,a,c;const l=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,p=this.origin;return l>=0?(r=(e.min.x-p.x)*l,i=(e.max.x-p.x)*l):(r=(e.max.x-p.x)*l,i=(e.min.x-p.x)*l),u>=0?(s=(e.min.y-p.y)*u,o=(e.max.y-p.y)*u):(s=(e.max.y-p.y)*u,o=(e.min.y-p.y)*u),r>o||s>i||((s>r||isNaN(r))&&(r=s),(o=0?(a=(e.min.z-p.z)*h,c=(e.max.z-p.z)*h):(a=(e.max.z-p.z)*h,c=(e.min.z-p.z)*h),r>c||a>i)||((a>r||r!==r)&&(r=a),(c=0?r:i,t)}intersectsBox(e){return this.intersectBox(e,Ya)!==null}intersectTriangle(e,t,r,i,s){nS.subVectors(t,e),Bg.subVectors(r,e),rS.crossVectors(nS,Bg);let o=this.direction.dot(rS),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;ol.subVectors(this.origin,e);const c=a*this.direction.dot(Bg.crossVectors(ol,Bg));if(c<0)return null;const l=a*this.direction.dot(nS.cross(ol));if(l<0||c+l>o)return null;const u=-a*ol.dot(rS);return u<0?null:this.at(u/o,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class ar{constructor(e,t,r,i,s,o,a,c,l,u,h,p,m,g,v,y){ar.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,r,i,s,o,a,c,l,u,h,p,m,g,v,y)}set(e,t,r,i,s,o,a,c,l,u,h,p,m,g,v,y){const _=this.elements;return _[0]=e,_[4]=t,_[8]=r,_[12]=i,_[1]=s,_[5]=o,_[9]=a,_[13]=c,_[2]=l,_[6]=u,_[10]=h,_[14]=p,_[3]=m,_[7]=g,_[11]=v,_[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ar().fromArray(this.elements)}copy(e){const t=this.elements,r=e.elements;return t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=r[3],t[4]=r[4],t[5]=r[5],t[6]=r[6],t[7]=r[7],t[8]=r[8],t[9]=r[9],t[10]=r[10],t[11]=r[11],t[12]=r[12],t[13]=r[13],t[14]=r[14],t[15]=r[15],this}copyPosition(e){const t=this.elements,r=e.elements;return t[12]=r[12],t[13]=r[13],t[14]=r[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,r){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,t,r){return this.set(e.x,t.x,r.x,0,e.y,t.y,r.y,0,e.z,t.z,r.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,r=e.elements,i=1/kh.setFromMatrixColumn(e,0).length(),s=1/kh.setFromMatrixColumn(e,1).length(),o=1/kh.setFromMatrixColumn(e,2).length();return t[0]=r[0]*i,t[1]=r[1]*i,t[2]=r[2]*i,t[3]=0,t[4]=r[4]*s,t[5]=r[5]*s,t[6]=r[6]*s,t[7]=0,t[8]=r[8]*o,t[9]=r[9]*o,t[10]=r[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,r=e.x,i=e.y,s=e.z,o=Math.cos(r),a=Math.sin(r),c=Math.cos(i),l=Math.sin(i),u=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const p=o*u,m=o*h,g=a*u,v=a*h;t[0]=c*u,t[4]=-c*h,t[8]=l,t[1]=m+g*l,t[5]=p-v*l,t[9]=-a*c,t[2]=v-p*l,t[6]=g+m*l,t[10]=o*c}else if(e.order==="YXZ"){const p=c*u,m=c*h,g=l*u,v=l*h;t[0]=p+v*a,t[4]=g*a-m,t[8]=o*l,t[1]=o*h,t[5]=o*u,t[9]=-a,t[2]=m*a-g,t[6]=v+p*a,t[10]=o*c}else if(e.order==="ZXY"){const p=c*u,m=c*h,g=l*u,v=l*h;t[0]=p-v*a,t[4]=-o*h,t[8]=g+m*a,t[1]=m+g*a,t[5]=o*u,t[9]=v-p*a,t[2]=-o*l,t[6]=a,t[10]=o*c}else if(e.order==="ZYX"){const p=o*u,m=o*h,g=a*u,v=a*h;t[0]=c*u,t[4]=g*l-m,t[8]=p*l+v,t[1]=c*h,t[5]=v*l+p,t[9]=m*l-g,t[2]=-l,t[6]=a*c,t[10]=o*c}else if(e.order==="YZX"){const p=o*c,m=o*l,g=a*c,v=a*l;t[0]=c*u,t[4]=v-p*h,t[8]=g*h+m,t[1]=h,t[5]=o*u,t[9]=-a*u,t[2]=-l*u,t[6]=m*h+g,t[10]=p-v*h}else if(e.order==="XZY"){const p=o*c,m=o*l,g=a*c,v=a*l;t[0]=c*u,t[4]=-h,t[8]=l*u,t[1]=p*h+v,t[5]=o*u,t[9]=m*h-g,t[2]=g*h-m,t[6]=a*u,t[10]=v*h+p}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(A5,e,M5)}lookAt(e,t,r){const i=this.elements;return Ss.subVectors(e,t),Ss.lengthSq()===0&&(Ss.z=1),Ss.normalize(),al.crossVectors(r,Ss),al.lengthSq()===0&&(Math.abs(r.z)===1?Ss.x+=1e-4:Ss.z+=1e-4,Ss.normalize(),al.crossVectors(r,Ss)),al.normalize(),zg.crossVectors(Ss,al),i[0]=al.x,i[4]=zg.x,i[8]=Ss.x,i[1]=al.y,i[5]=zg.y,i[9]=Ss.y,i[2]=al.z,i[6]=zg.z,i[10]=Ss.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const r=e.elements,i=t.elements,s=this.elements,o=r[0],a=r[4],c=r[8],l=r[12],u=r[1],h=r[5],p=r[9],m=r[13],g=r[2],v=r[6],y=r[10],_=r[14],S=r[3],w=r[7],T=r[11],k=r[15],R=i[0],C=i[4],O=i[8],M=i[12],N=i[1],U=i[5],L=i[9],P=i[13],b=i[2],B=i[6],W=i[10],V=i[14],G=i[3],$=i[7],Z=i[11],X=i[15];return s[0]=o*R+a*N+c*b+l*G,s[4]=o*C+a*U+c*B+l*$,s[8]=o*O+a*L+c*W+l*Z,s[12]=o*M+a*P+c*V+l*X,s[1]=u*R+h*N+p*b+m*G,s[5]=u*C+h*U+p*B+m*$,s[9]=u*O+h*L+p*W+m*Z,s[13]=u*M+h*P+p*V+m*X,s[2]=g*R+v*N+y*b+_*G,s[6]=g*C+v*U+y*B+_*$,s[10]=g*O+v*L+y*W+_*Z,s[14]=g*M+v*P+y*V+_*X,s[3]=S*R+w*N+T*b+k*G,s[7]=S*C+w*U+T*B+k*$,s[11]=S*O+w*L+T*W+k*Z,s[15]=S*M+w*P+T*V+k*X,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],r=e[4],i=e[8],s=e[12],o=e[1],a=e[5],c=e[9],l=e[13],u=e[2],h=e[6],p=e[10],m=e[14],g=e[3],v=e[7],y=e[11],_=e[15];return g*(+s*c*h-i*l*h-s*a*p+r*l*p+i*a*m-r*c*m)+v*(+t*c*m-t*l*p+s*o*p-i*o*m+i*l*u-s*c*u)+y*(+t*l*h-t*a*m-s*o*h+r*o*m+s*a*u-r*l*u)+_*(-i*a*u-t*c*h+t*a*p+i*o*h-r*o*p+r*c*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,r){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=r),this}invert(){const e=this.elements,t=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],u=e[8],h=e[9],p=e[10],m=e[11],g=e[12],v=e[13],y=e[14],_=e[15],S=h*y*l-v*p*l+v*c*m-a*y*m-h*c*_+a*p*_,w=g*p*l-u*y*l-g*c*m+o*y*m+u*c*_-o*p*_,T=u*v*l-g*h*l+g*a*m-o*v*m-u*a*_+o*h*_,k=g*h*c-u*v*c-g*a*p+o*v*p+u*a*y-o*h*y,R=t*S+r*w+i*T+s*k;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const C=1/R;return e[0]=S*C,e[1]=(v*p*s-h*y*s-v*i*m+r*y*m+h*i*_-r*p*_)*C,e[2]=(a*y*s-v*c*s+v*i*l-r*y*l-a*i*_+r*c*_)*C,e[3]=(h*c*s-a*p*s-h*i*l+r*p*l+a*i*m-r*c*m)*C,e[4]=w*C,e[5]=(u*y*s-g*p*s+g*i*m-t*y*m-u*i*_+t*p*_)*C,e[6]=(g*c*s-o*y*s-g*i*l+t*y*l+o*i*_-t*c*_)*C,e[7]=(o*p*s-u*c*s+u*i*l-t*p*l-o*i*m+t*c*m)*C,e[8]=T*C,e[9]=(g*h*s-u*v*s-g*r*m+t*v*m+u*r*_-t*h*_)*C,e[10]=(o*v*s-g*a*s+g*r*l-t*v*l-o*r*_+t*a*_)*C,e[11]=(u*a*s-o*h*s-u*r*l+t*h*l+o*r*m-t*a*m)*C,e[12]=k*C,e[13]=(u*v*i-g*h*i+g*r*p-t*v*p-u*r*y+t*h*y)*C,e[14]=(g*a*i-o*v*i-g*r*c+t*v*c+o*r*y-t*a*y)*C,e[15]=(o*h*i-u*a*i+u*r*c-t*h*c-o*r*p+t*a*p)*C,this}scale(e){const t=this.elements,r=e.x,i=e.y,s=e.z;return t[0]*=r,t[4]*=i,t[8]*=s,t[1]*=r,t[5]*=i,t[9]*=s,t[2]*=r,t[6]*=i,t[10]*=s,t[3]*=r,t[7]*=i,t[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,r,i))}makeTranslation(e,t,r){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,r,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,t,-r,0,0,r,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,0,r,0,0,1,0,0,-r,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,-r,0,0,r,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const r=Math.cos(t),i=Math.sin(t),s=1-r,o=e.x,a=e.y,c=e.z,l=s*o,u=s*a;return this.set(l*o+r,l*a-i*c,l*c+i*a,0,l*a+i*c,u*a+r,u*c-i*o,0,l*c-i*a,u*c+i*o,s*c*c+r,0,0,0,0,1),this}makeScale(e,t,r){return this.set(e,0,0,0,0,t,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,t,r,i,s,o){return this.set(1,r,s,0,e,1,o,0,t,i,1,0,0,0,0,1),this}compose(e,t,r){const i=this.elements,s=t._x,o=t._y,a=t._z,c=t._w,l=s+s,u=o+o,h=a+a,p=s*l,m=s*u,g=s*h,v=o*u,y=o*h,_=a*h,S=c*l,w=c*u,T=c*h,k=r.x,R=r.y,C=r.z;return i[0]=(1-(v+_))*k,i[1]=(m+T)*k,i[2]=(g-w)*k,i[3]=0,i[4]=(m-T)*R,i[5]=(1-(p+_))*R,i[6]=(y+S)*R,i[7]=0,i[8]=(g+w)*C,i[9]=(y-S)*C,i[10]=(1-(p+v))*C,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,r){const i=this.elements;let s=kh.set(i[0],i[1],i[2]).length();const o=kh.set(i[4],i[5],i[6]).length(),a=kh.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),e.x=i[12],e.y=i[13],e.z=i[14],go.copy(this);const l=1/s,u=1/o,h=1/a;return go.elements[0]*=l,go.elements[1]*=l,go.elements[2]*=l,go.elements[4]*=u,go.elements[5]*=u,go.elements[6]*=u,go.elements[8]*=h,go.elements[9]*=h,go.elements[10]*=h,t.setFromRotationMatrix(go),r.x=s,r.y=o,r.z=a,this}makePerspective(e,t,r,i,s,o,a=hc){const c=this.elements,l=2*s/(t-e),u=2*s/(r-i),h=(t+e)/(t-e),p=(r+i)/(r-i);let m,g;if(a===hc)m=-(o+s)/(o-s),g=-2*o*s/(o-s);else if(a===g_)m=-o/(o-s),g=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=l,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=u,c[9]=p,c[13]=0,c[2]=0,c[6]=0,c[10]=m,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,r,i,s,o,a=hc){const c=this.elements,l=1/(t-e),u=1/(r-i),h=1/(o-s),p=(t+e)*l,m=(r+i)*u;let g,v;if(a===hc)g=(o+s)*h,v=-2*h;else if(a===g_)g=s*h,v=-1*h;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=2*l,c[4]=0,c[8]=0,c[12]=-p,c[1]=0,c[5]=2*u,c[9]=0,c[13]=-m,c[2]=0,c[6]=0,c[10]=v,c[14]=-g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,r=e.elements;for(let i=0;i<16;i++)if(t[i]!==r[i])return!1;return!0}fromArray(e,t=0){for(let r=0;r<16;r++)this.elements[r]=e[r+t];return this}toArray(e=[],t=0){const r=this.elements;return e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3],e[t+4]=r[4],e[t+5]=r[5],e[t+6]=r[6],e[t+7]=r[7],e[t+8]=r[8],e[t+9]=r[9],e[t+10]=r[10],e[t+11]=r[11],e[t+12]=r[12],e[t+13]=r[13],e[t+14]=r[14],e[t+15]=r[15],e}}const kh=new xe,go=new ar,A5=new xe(0,0,0),M5=new xe(1,1,1),al=new xe,zg=new xe,Ss=new xe,OC=new ar,LC=new zp;class Tc{constructor(e=0,t=0,r=0,i=Tc.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,r,i=this._order){return this._x=e,this._y=t,this._z=r,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,r=!0){const i=e.elements,s=i[0],o=i[4],a=i[8],c=i[1],l=i[5],u=i[9],h=i[2],p=i[6],m=i[10];switch(t){case"XYZ":this._y=Math.asin(Li(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,m),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(p,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Li(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,m),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(Li(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-h,m),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-Li(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(p,m),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(Li(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(a,m));break;case"XZY":this._z=Math.asin(-Li(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(p,l),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-u,m),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,r){return OC.makeRotationFromQuaternion(e),this.setFromRotationMatrix(OC,t,r)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return LC.setFromEuler(this),this.setFromQuaternion(LC,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Tc.DEFAULT_ORDER="XYZ";class pf{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let r=0;r0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(a=>({boxInitialized:a.boxInitialized,boxMin:a.box.min.toArray(),boxMax:a.box.max.toArray(),sphereInitialized:a.sphereInitialized,sphereRadius:a.sphere.radius,sphereCenter:a.sphere.center.toArray()})),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()}));function s(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,u=c.length;l0){i.children=[];for(let a=0;a0){i.animations=[];for(let a=0;a0&&(r.geometries=a),c.length>0&&(r.materials=c),l.length>0&&(r.textures=l),u.length>0&&(r.images=u),h.length>0&&(r.shapes=h),p.length>0&&(r.skeletons=p),m.length>0&&(r.animations=m),g.length>0&&(r.nodes=g)}return r.object=i,r;function o(a){const c=[];for(const l in a){const u=a[l];delete u.metadata,c.push(u)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let r=0;r0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,t,r,i,s){_o.subVectors(i,t),Qa.subVectors(r,t),sS.subVectors(e,t);const o=_o.dot(_o),a=_o.dot(Qa),c=_o.dot(sS),l=Qa.dot(Qa),u=Qa.dot(sS),h=o*l-a*a;if(h===0)return s.set(0,0,0),null;const p=1/h,m=(l*c-a*u)*p,g=(o*u-a*c)*p;return s.set(1-m-g,g,m)}static containsPoint(e,t,r,i){return this.getBarycoord(e,t,r,i,Ja)===null?!1:Ja.x>=0&&Ja.y>=0&&Ja.x+Ja.y<=1}static getInterpolation(e,t,r,i,s,o,a,c){return this.getBarycoord(e,t,r,i,Ja)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,Ja.x),c.addScaledVector(o,Ja.y),c.addScaledVector(a,Ja.z),c)}static getInterpolatedAttribute(e,t,r,i,s,o){return lS.setScalar(0),uS.setScalar(0),hS.setScalar(0),lS.fromBufferAttribute(e,t),uS.fromBufferAttribute(e,r),hS.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(lS,s.x),o.addScaledVector(uS,s.y),o.addScaledVector(hS,s.z),o}static isFrontFacing(e,t,r,i){return _o.subVectors(r,t),Qa.subVectors(e,t),_o.cross(Qa).dot(i)<0}set(e,t,r){return this.a.copy(e),this.b.copy(t),this.c.copy(r),this}setFromPointsAndIndices(e,t,r,i){return this.a.copy(e[t]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,r,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return _o.subVectors(this.c,this.b),Qa.subVectors(this.a,this.b),_o.cross(Qa).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return So.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return So.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,r,i,s){return So.getInterpolation(e,this.a,this.b,this.c,t,r,i,s)}containsPoint(e){return So.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return So.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const r=this.a,i=this.b,s=this.c;let o,a;Oh.subVectors(i,r),Lh.subVectors(s,r),oS.subVectors(e,r);const c=Oh.dot(oS),l=Lh.dot(oS);if(c<=0&&l<=0)return t.copy(r);aS.subVectors(e,i);const u=Oh.dot(aS),h=Lh.dot(aS);if(u>=0&&h<=u)return t.copy(i);const p=c*h-u*l;if(p<=0&&c>=0&&u<=0)return o=c/(c-u),t.copy(r).addScaledVector(Oh,o);cS.subVectors(e,s);const m=Oh.dot(cS),g=Lh.dot(cS);if(g>=0&&m<=g)return t.copy(s);const v=m*l-c*g;if(v<=0&&l>=0&&g<=0)return a=l/(l-g),t.copy(r).addScaledVector(Lh,a);const y=u*g-m*h;if(y<=0&&h-u>=0&&m-g>=0)return zC.subVectors(s,i),a=(h-u)/(h-u+(m-g)),t.copy(i).addScaledVector(zC,a);const _=1/(y+v+p);return o=v*_,a=p*_,t.copy(r).addScaledVector(Oh,o).addScaledVector(Lh,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const HN={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},cl={h:0,s:0,l:0},Hg={h:0,s:0,l:0};function fS(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class cn{constructor(e,t,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,r)}set(e,t,r){if(t===void 0&&r===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=pr){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,hn.toWorkingColorSpace(this,t),this}setRGB(e,t,r,i=hn.workingColorSpace){return this.r=e,this.g=t,this.b=r,hn.toWorkingColorSpace(this,i),this}setHSL(e,t,r,i=hn.workingColorSpace){if(e=Zw(e,1),t=Li(t,0,1),r=Li(r,0,1),t===0)this.r=this.g=this.b=r;else{const s=r<=.5?r*(1+t):r+t-r*t,o=2*r-s;this.r=fS(o,s,e+1/3),this.g=fS(o,s,e),this.b=fS(o,s,e-1/3)}return hn.toWorkingColorSpace(this,i),this}setStyle(e,t=pr){function r(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=pr){const r=HN[e.toLowerCase()];return r!==void 0?this.setHex(r,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=mc(e.r),this.g=mc(e.g),this.b=mc(e.b),this}copyLinearToSRGB(e){return this.r=df(e.r),this.g=df(e.g),this.b=df(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=pr){return hn.fromWorkingColorSpace(_i.copy(this),e),Math.round(Li(_i.r*255,0,255))*65536+Math.round(Li(_i.g*255,0,255))*256+Math.round(Li(_i.b*255,0,255))}getHexString(e=pr){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=hn.workingColorSpace){hn.fromWorkingColorSpace(_i.copy(this),t);const r=_i.r,i=_i.g,s=_i.b,o=Math.max(r,i,s),a=Math.min(r,i,s);let c,l;const u=(a+o)/2;if(a===o)c=0,l=0;else{const h=o-a;switch(l=u<=.5?h/(o+a):h/(2-o-a),o){case r:c=(i-s)/h+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const r=e[t];if(r===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[t]=r}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const r={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(r.dispersion=this.dispersion),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapRotation!==void 0&&(r.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==hf&&(r.blending=this.blending),this.side!==wc&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==b1&&(r.blendSrc=this.blendSrc),this.blendDst!==A1&&(r.blendDst=this.blendDst),this.blendEquation!==xu&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==Tf&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==EC&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==bh&&(r.stencilFail=this.stencilFail),this.stencilZFail!==bh&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==bh&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function i(s){const o=[];for(const a in s){const c=s[a];delete c.metadata,o.push(c)}return o}if(t){const s=i(e.textures),o=i(e.images);s.length>0&&(r.textures=s),o.length>0&&(r.images=o)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let r=null;if(t!==null){const i=t.length;r=new Array(i);for(let s=0;s!==i;++s)r[s]=t[s].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Jw extends Lc{static get type(){return"MeshBasicMaterial"}constructor(e){super(),this.isMeshBasicMaterial=!0,this.color=new cn(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Tc,this.combine=TN,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Er=new xe,Gg=new St;class Qn{constructor(e,t,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=r,this.usage=wC,this.updateRanges=[],this.gpuType=da,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,r){e*=this.itemSize,r*=t.itemSize;for(let i=0,s=this.itemSize;it.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Vp);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new xe(-1/0,-1/0,-1/0),new xe(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let r=0,i=t.length;r0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const r=this.attributes;for(const c in r){const l=r[c];e.data.attributes[c]=l.toJSON(e.data)}const i={};let s=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],u=[];for(let h=0,p=l.length;h0&&(i[c]=u,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone(t));const i=e.attributes;for(const l in i){const u=i[l];this.setAttribute(l,u.clone(t))}const s=e.morphAttributes;for(const l in s){const u=[],h=s[l];for(let p=0,m=h.length;p0){const i=t[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s(e.far-e.near)**2))&&(VC.copy(s).invert(),iu.copy(e.ray).applyMatrix4(VC),!(r.boundingBox!==null&&iu.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,t,iu)))}_computeIntersections(e,t,r){let i;const s=this.geometry,o=this.material,a=s.index,c=s.attributes.position,l=s.attributes.uv,u=s.attributes.uv1,h=s.attributes.normal,p=s.groups,m=s.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=p.length;gt.far?null:{distance:l,point:Kg.clone(),object:n}}function Yg(n,e,t,r,i,s,o,a,c,l){n.getVertexPosition(a,jg),n.getVertexPosition(c,$g),n.getVertexPosition(l,qg);const u=L5(n,e,t,r,jg,$g,qg,GC);if(u){const h=new xe;So.getBarycoord(GC,jg,$g,qg,h),i&&(u.uv=So.getInterpolatedAttribute(i,a,c,l,h,new St)),s&&(u.uv1=So.getInterpolatedAttribute(s,a,c,l,h,new St)),o&&(u.normal=So.getInterpolatedAttribute(o,a,c,l,h,new xe),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));const p={a,b:c,c:l,normal:new xe,materialIndex:0};So.getNormal(jg,$g,qg,p.normal),u.face=p,u.barycoord=h}return u}class Hp extends Do{constructor(e=1,t=1,r=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:r,widthSegments:i,heightSegments:s,depthSegments:o};const a=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const c=[],l=[],u=[],h=[];let p=0,m=0;g("z","y","x",-1,-1,r,t,e,o,s,0),g("z","y","x",1,-1,r,t,-e,o,s,1),g("x","z","y",1,1,e,r,t,i,o,2),g("x","z","y",1,-1,e,r,-t,i,o,3),g("x","y","z",1,-1,e,t,r,i,s,4),g("x","y","z",-1,-1,e,t,-r,i,s,5),this.setIndex(c),this.setAttribute("position",new Ru(l,3)),this.setAttribute("normal",new Ru(u,3)),this.setAttribute("uv",new Ru(h,2));function g(v,y,_,S,w,T,k,R,C,O,M){const N=T/C,U=k/O,L=T/2,P=k/2,b=R/2,B=C+1,W=O+1;let V=0,G=0;const $=new xe;for(let Z=0;Z0?1:-1,u.push($.x,$.y,$.z),h.push(Y/C),h.push(1-Z/O),V+=1}}for(let Z=0;Z0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const r={};for(const i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(t.extensions=r),t}}class xv extends os{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ar,this.projectionMatrix=new ar,this.projectionMatrixInverse=new ar,this.coordinateSystem=hc}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ll=new xe,WC=new St,jC=new St;class Ts extends xv{constructor(e=50,t=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=dp*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(ip*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return dp*2*Math.atan(Math.tan(ip*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,r){ll.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ll.x,ll.y).multiplyScalar(-e/ll.z),ll.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),r.set(ll.x,ll.y).multiplyScalar(-e/ll.z)}getViewSize(e,t){return this.getViewBounds(e,WC,jC),t.subVectors(jC,WC)}setViewOffset(e,t,r,i,s,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(ip*.5*this.fov)/this.zoom,r=2*t,i=this.aspect*r,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,l=o.fullHeight;s+=o.offsetX*i/c,t-=o.offsetY*r/l,i*=o.width/c,r*=o.height/l}const a=this.filmOffset;a!==0&&(s+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,t,t-r,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Dh=-90,Uh=1;class B5 extends os{constructor(e,t,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ts(Dh,Uh,e,t);i.layers=this.layers,this.add(i);const s=new Ts(Dh,Uh,e,t);s.layers=this.layers,this.add(s);const o=new Ts(Dh,Uh,e,t);o.layers=this.layers,this.add(o);const a=new Ts(Dh,Uh,e,t);a.layers=this.layers,this.add(a);const c=new Ts(Dh,Uh,e,t);c.layers=this.layers,this.add(c);const l=new Ts(Dh,Uh,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[r,i,s,o,a,c]=t;for(const l of t)this.remove(l);if(e===hc)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===g_)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,a,c,l,u]=this.children,h=e.getRenderTarget(),p=e.getActiveCubeFace(),m=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(t,s),e.setRenderTarget(r,1,i),e.render(t,o),e.setRenderTarget(r,2,i),e.render(t,a),e.setRenderTarget(r,3,i),e.render(t,c),e.setRenderTarget(r,4,i),e.render(t,l),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,i),e.render(t,u),e.setRenderTarget(h,p,m),e.xr.enabled=g,r.texture.needsPMREMUpdate=!0}}class $N extends or{constructor(e,t,r,i,s,o,a,c,l,u){e=e!==void 0?e:[],t=t!==void 0?t:bf,super(e,t,r,i,s,o,a,c,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class z5 extends Ls{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];this.texture=new $N(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:ns}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:` - - varying vec3 vWorldDirection; - - vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); - - } - - void main() { - - vWorldDirection = transformDirection( position, modelMatrix ); - - #include - #include - - } - `,fragmentShader:` - - uniform sampler2D tEquirect; - - varying vec3 vWorldDirection; - - #include - - void main() { - - vec3 direction = normalize( vWorldDirection ); - - vec2 sampleUV = equirectUv( direction ); - - gl_FragColor = texture2D( tEquirect, sampleUV ); - - } - `},i=new Hp(5,5,5),s=new Vi({name:"CubemapFromEquirect",uniforms:Mf(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:ni,blending:Ao});s.uniforms.tEquirect.value=t;const o=new wo(i,s),a=t.minFilter;return t.minFilter===Tu&&(t.minFilter=ns),new B5(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t,r,i){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,r,i);e.setRenderTarget(s)}}const mS=new xe,V5=new xe,H5=new Dt;class yo{constructor(e=new xe(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,r,i){return this.normal.set(e,t,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,r){const i=mS.subVectors(r,t).cross(V5.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const r=e.delta(mS),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:t.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const t=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return t<0&&r>0||r<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const r=t||H5.getNormalMatrix(e),i=this.coplanarPoint(mS).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const su=new yv,Zg=new xe;class qN{constructor(e=new yo,t=new yo,r=new yo,i=new yo,s=new yo,o=new yo){this.planes=[e,t,r,i,s,o]}set(e,t,r,i,s,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(r),a[3].copy(i),a[4].copy(s),a[5].copy(o),this}copy(e){const t=this.planes;for(let r=0;r<6;r++)t[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,t=hc){const r=this.planes,i=e.elements,s=i[0],o=i[1],a=i[2],c=i[3],l=i[4],u=i[5],h=i[6],p=i[7],m=i[8],g=i[9],v=i[10],y=i[11],_=i[12],S=i[13],w=i[14],T=i[15];if(r[0].setComponents(c-s,p-l,y-m,T-_).normalize(),r[1].setComponents(c+s,p+l,y+m,T+_).normalize(),r[2].setComponents(c+o,p+u,y+g,T+S).normalize(),r[3].setComponents(c-o,p-u,y-g,T-S).normalize(),r[4].setComponents(c-a,p-h,y-v,T-w).normalize(),t===hc)r[5].setComponents(c+a,p+h,y+v,T+w).normalize();else if(t===g_)r[5].setComponents(a,h,v,w).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),su.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),su.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(su)}intersectsSprite(e){return su.center.set(0,0,0),su.radius=.7071067811865476,su.applyMatrix4(e.matrixWorld),this.intersectsSphere(su)}intersectsSphere(e){const t=this.planes,r=e.center,i=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(r)0?e.max.x:e.min.x,Zg.y=i.normal.y>0?e.max.y:e.min.y,Zg.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Zg)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let r=0;r<6;r++)if(t[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function XN(){let n=null,e=!1,t=null,r=null;function i(s,o){t(s,o),r=n.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&(r=n.requestAnimationFrame(i),e=!0)},stop:function(){n.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){n=s}}}function G5(n){const e=new WeakMap;function t(a,c){const l=a.array,u=a.usage,h=l.byteLength,p=n.createBuffer();n.bindBuffer(c,p),n.bufferData(c,l,u),a.onUploadCallback();let m;if(l instanceof Float32Array)m=n.FLOAT;else if(l instanceof Uint16Array)a.isFloat16BufferAttribute?m=n.HALF_FLOAT:m=n.UNSIGNED_SHORT;else if(l instanceof Int16Array)m=n.SHORT;else if(l instanceof Uint32Array)m=n.UNSIGNED_INT;else if(l instanceof Int32Array)m=n.INT;else if(l instanceof Int8Array)m=n.BYTE;else if(l instanceof Uint8Array)m=n.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)m=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:p,type:m,bytesPerElement:l.BYTES_PER_ELEMENT,version:a.version,size:h}}function r(a,c,l){const u=c.array,h=c.updateRanges;if(n.bindBuffer(l,a),h.length===0)n.bufferSubData(l,0,u);else{h.sort((m,g)=>m.start-g.start);let p=0;for(let m=1;m 0 - vec4 plane; - #ifdef ALPHA_TO_COVERAGE - float distanceToPlane, distanceGradient; - float clipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - if ( clipOpacity == 0.0 ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - float unionClipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - } - #pragma unroll_loop_end - clipOpacity *= 1.0 - unionClipOpacity; - #endif - diffuseColor.a *= clipOpacity; - if ( diffuseColor.a == 0.0 ) discard; - #else - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - bool clipped = true; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; - } - #pragma unroll_loop_end - if ( clipped ) discard; - #endif - #endif -#endif`,oz=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; - uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,az=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; -#endif`,cz=`#if NUM_CLIPPING_PLANES > 0 - vClipPosition = - mvPosition.xyz; -#endif`,lz=`#if defined( USE_COLOR_ALPHA ) - diffuseColor *= vColor; -#elif defined( USE_COLOR ) - diffuseColor.rgb *= vColor; -#endif`,uz=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) - varying vec3 vColor; -#endif`,hz=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - varying vec3 vColor; -#endif`,fz=`#if defined( USE_COLOR_ALPHA ) - vColor = vec4( 1.0 ); -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - vColor = vec3( 1.0 ); -#endif -#ifdef USE_COLOR - vColor *= color; -#endif -#ifdef USE_INSTANCING_COLOR - vColor.xyz *= instanceColor.xyz; -#endif -#ifdef USE_BATCHING_COLOR - vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); - vColor.xyz *= batchingColor.xyz; -#endif`,dz=`#define PI 3.141592653589793 -#define PI2 6.283185307179586 -#define PI_HALF 1.5707963267948966 -#define RECIPROCAL_PI 0.3183098861837907 -#define RECIPROCAL_PI2 0.15915494309189535 -#define EPSILON 1e-6 -#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -#define whiteComplement( a ) ( 1.0 - saturate( a ) ) -float pow2( const in float x ) { return x*x; } -vec3 pow2( const in vec3 x ) { return x*x; } -float pow3( const in float x ) { return x*x*x; } -float pow4( const in float x ) { float x2 = x*x; return x2*x2; } -float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } -float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } -highp float rand( const in vec2 uv ) { - const highp float a = 12.9898, b = 78.233, c = 43758.5453; - highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); - return fract( sin( sn ) * c ); -} -#ifdef HIGH_PRECISION - float precisionSafeLength( vec3 v ) { return length( v ); } -#else - float precisionSafeLength( vec3 v ) { - float maxComponent = max3( abs( v ) ); - return length( v / maxComponent ) * maxComponent; - } -#endif -struct IncidentLight { - vec3 color; - vec3 direction; - bool visible; -}; -struct ReflectedLight { - vec3 directDiffuse; - vec3 directSpecular; - vec3 indirectDiffuse; - vec3 indirectSpecular; -}; -#ifdef USE_ALPHAHASH - varying vec3 vPosition; -#endif -vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); -} -vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); -} -mat3 transposeMat3( const in mat3 m ) { - mat3 tmp; - tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); - tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); - tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); - return tmp; -} -bool isPerspectiveMatrix( mat4 m ) { - return m[ 2 ][ 3 ] == - 1.0; -} -vec2 equirectUv( in vec3 dir ) { - float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; - float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; - return vec2( u, v ); -} -vec3 BRDF_Lambert( const in vec3 diffuseColor ) { - return RECIPROCAL_PI * diffuseColor; -} -vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} -float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,pz=`#ifdef ENVMAP_TYPE_CUBE_UV - #define cubeUV_minMipLevel 4.0 - #define cubeUV_minTileSize 16.0 - float getFace( vec3 direction ) { - vec3 absDirection = abs( direction ); - float face = - 1.0; - if ( absDirection.x > absDirection.z ) { - if ( absDirection.x > absDirection.y ) - face = direction.x > 0.0 ? 0.0 : 3.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } else { - if ( absDirection.z > absDirection.y ) - face = direction.z > 0.0 ? 2.0 : 5.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } - return face; - } - vec2 getUV( vec3 direction, float face ) { - vec2 uv; - if ( face == 0.0 ) { - uv = vec2( direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 1.0 ) { - uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); - } else if ( face == 2.0 ) { - uv = vec2( - direction.x, direction.y ) / abs( direction.z ); - } else if ( face == 3.0 ) { - uv = vec2( - direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 4.0 ) { - uv = vec2( - direction.x, direction.z ) / abs( direction.y ); - } else { - uv = vec2( direction.x, direction.y ) / abs( direction.z ); - } - return 0.5 * ( uv + 1.0 ); - } - vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { - float face = getFace( direction ); - float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); - mipInt = max( mipInt, cubeUV_minMipLevel ); - float faceSize = exp2( mipInt ); - highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; - if ( face > 2.0 ) { - uv.y += faceSize; - face -= 3.0; - } - uv.x += face * faceSize; - uv.x += filterInt * 3.0 * cubeUV_minTileSize; - uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); - uv.x *= CUBEUV_TEXEL_WIDTH; - uv.y *= CUBEUV_TEXEL_HEIGHT; - #ifdef texture2DGradEXT - return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; - #else - return texture2D( envMap, uv ).rgb; - #endif - } - #define cubeUV_r0 1.0 - #define cubeUV_m0 - 2.0 - #define cubeUV_r1 0.8 - #define cubeUV_m1 - 1.0 - #define cubeUV_r4 0.4 - #define cubeUV_m4 2.0 - #define cubeUV_r5 0.305 - #define cubeUV_m5 3.0 - #define cubeUV_r6 0.21 - #define cubeUV_m6 4.0 - float roughnessToMip( float roughness ) { - float mip = 0.0; - if ( roughness >= cubeUV_r1 ) { - mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; - } else if ( roughness >= cubeUV_r4 ) { - mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; - } else if ( roughness >= cubeUV_r5 ) { - mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; - } else if ( roughness >= cubeUV_r6 ) { - mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; - } else { - mip = - 2.0 * log2( 1.16 * roughness ); } - return mip; - } - vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { - float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); - float mipF = fract( mip ); - float mipInt = floor( mip ); - vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); - if ( mipF == 0.0 ) { - return vec4( color0, 1.0 ); - } else { - vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); - return vec4( mix( color0, color1, mipF ), 1.0 ); - } - } -#endif`,mz=`vec3 transformedNormal = objectNormal; -#ifdef USE_TANGENT - vec3 transformedTangent = objectTangent; -#endif -#ifdef USE_BATCHING - mat3 bm = mat3( batchingMatrix ); - transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); - transformedNormal = bm * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = bm * transformedTangent; - #endif -#endif -#ifdef USE_INSTANCING - mat3 im = mat3( instanceMatrix ); - transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); - transformedNormal = im * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = im * transformedTangent; - #endif -#endif -transformedNormal = normalMatrix * transformedNormal; -#ifdef FLIP_SIDED - transformedNormal = - transformedNormal; -#endif -#ifdef USE_TANGENT - transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; - #ifdef FLIP_SIDED - transformedTangent = - transformedTangent; - #endif -#endif`,gz=`#ifdef USE_DISPLACEMENTMAP - uniform sampler2D displacementMap; - uniform float displacementScale; - uniform float displacementBias; -#endif`,_z=`#ifdef USE_DISPLACEMENTMAP - transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,vz=`#ifdef USE_EMISSIVEMAP - vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); - #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE - emissiveColor = sRGBTransferEOTF( emissiveColor ); - #endif - totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,yz=`#ifdef USE_EMISSIVEMAP - uniform sampler2D emissiveMap; -#endif`,xz="gl_FragColor = linearToOutputTexel( gl_FragColor );",Sz=`vec4 LinearTransferOETF( in vec4 value ) { - return value; -} -vec4 sRGBTransferEOTF( in vec4 value ) { - return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); -} -vec4 sRGBTransferOETF( in vec4 value ) { - return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -}`,Ez=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vec3 cameraToFrag; - if ( isOrthographic ) { - cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToFrag = normalize( vWorldPosition - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vec3 reflectVec = reflect( cameraToFrag, worldNormal ); - #else - vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); - #endif - #else - vec3 reflectVec = vReflect; - #endif - #ifdef ENVMAP_TYPE_CUBE - vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); - #else - vec4 envColor = vec4( 0.0 ); - #endif - #ifdef ENVMAP_BLENDING_MULTIPLY - outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_MIX ) - outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_ADD ) - outgoingLight += envColor.xyz * specularStrength * reflectivity; - #endif -#endif`,wz=`#ifdef USE_ENVMAP - uniform float envMapIntensity; - uniform float flipEnvMap; - uniform mat3 envMapRotation; - #ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; - #else - uniform sampler2D envMap; - #endif - -#endif`,Tz=`#ifdef USE_ENVMAP - uniform float reflectivity; - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - varying vec3 vWorldPosition; - uniform float refractionRatio; - #else - varying vec3 vReflect; - #endif -#endif`,bz=`#ifdef USE_ENVMAP - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - - varying vec3 vWorldPosition; - #else - varying vec3 vReflect; - uniform float refractionRatio; - #endif -#endif`,Az=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vWorldPosition = worldPosition.xyz; - #else - vec3 cameraToVertex; - if ( isOrthographic ) { - cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vReflect = reflect( cameraToVertex, worldNormal ); - #else - vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); - #endif - #endif -#endif`,Mz=`#ifdef USE_FOG - vFogDepth = - mvPosition.z; -#endif`,Cz=`#ifdef USE_FOG - varying float vFogDepth; -#endif`,Rz=`#ifdef USE_FOG - #ifdef FOG_EXP2 - float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); - #else - float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); - #endif - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,kz=`#ifdef USE_FOG - uniform vec3 fogColor; - varying float vFogDepth; - #ifdef FOG_EXP2 - uniform float fogDensity; - #else - uniform float fogNear; - uniform float fogFar; - #endif -#endif`,Iz=`#ifdef USE_GRADIENTMAP - uniform sampler2D gradientMap; -#endif -vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { - float dotNL = dot( normal, lightDirection ); - vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); - #ifdef USE_GRADIENTMAP - return vec3( texture2D( gradientMap, coord ).r ); - #else - vec2 fw = fwidth( coord ) * 0.5; - return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); - #endif -}`,Nz=`#ifdef USE_LIGHTMAP - uniform sampler2D lightMap; - uniform float lightMapIntensity; -#endif`,Oz=`LambertMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,Lz=`varying vec3 vViewPosition; -struct LambertMaterial { - vec3 diffuseColor; - float specularStrength; -}; -void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Pz=`uniform bool receiveShadow; -uniform vec3 ambientLightColor; -#if defined( USE_LIGHT_PROBES ) - uniform vec3 lightProbe[ 9 ]; -#endif -vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { - float x = normal.x, y = normal.y, z = normal.z; - vec3 result = shCoefficients[ 0 ] * 0.886227; - result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; - result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; - result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; - result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; - result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; - result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); - result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; - result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); - return result; -} -vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); - return irradiance; -} -vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { - vec3 irradiance = ambientLightColor; - return irradiance; -} -float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { - float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); - if ( cutoffDistance > 0.0 ) { - distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); - } - return distanceFalloff; -} -float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { - return smoothstep( coneCosine, penumbraCosine, angleCosine ); -} -#if NUM_DIR_LIGHTS > 0 - struct DirectionalLight { - vec3 direction; - vec3 color; - }; - uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; - void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { - light.color = directionalLight.color; - light.direction = directionalLight.direction; - light.visible = true; - } -#endif -#if NUM_POINT_LIGHTS > 0 - struct PointLight { - vec3 position; - vec3 color; - float distance; - float decay; - }; - uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; - void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = pointLight.position - geometryPosition; - light.direction = normalize( lVector ); - float lightDistance = length( lVector ); - light.color = pointLight.color; - light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } -#endif -#if NUM_SPOT_LIGHTS > 0 - struct SpotLight { - vec3 position; - vec3 direction; - vec3 color; - float distance; - float decay; - float coneCos; - float penumbraCos; - }; - uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; - void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = spotLight.position - geometryPosition; - light.direction = normalize( lVector ); - float angleCos = dot( light.direction, spotLight.direction ); - float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); - if ( spotAttenuation > 0.0 ) { - float lightDistance = length( lVector ); - light.color = spotLight.color * spotAttenuation; - light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } else { - light.color = vec3( 0.0 ); - light.visible = false; - } - } -#endif -#if NUM_RECT_AREA_LIGHTS > 0 - struct RectAreaLight { - vec3 color; - vec3 position; - vec3 halfWidth; - vec3 halfHeight; - }; - uniform sampler2D ltc_1; uniform sampler2D ltc_2; - uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; -#endif -#if NUM_HEMI_LIGHTS > 0 - struct HemisphereLight { - vec3 direction; - vec3 skyColor; - vec3 groundColor; - }; - uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; - vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { - float dotNL = dot( normal, hemiLight.direction ); - float hemiDiffuseWeight = 0.5 * dotNL + 0.5; - vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); - return irradiance; - } -#endif`,Dz=`#ifdef USE_ENVMAP - vec3 getIBLIrradiance( const in vec3 normal ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); - return PI * envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 reflectVec = reflect( - viewDir, normal ); - reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); - reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); - return envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - #ifdef USE_ANISOTROPY - vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 bentNormal = cross( bitangent, viewDir ); - bentNormal = normalize( cross( bentNormal, bitangent ) ); - bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); - return getIBLRadiance( viewDir, bentNormal, roughness ); - #else - return vec3( 0.0 ); - #endif - } - #endif -#endif`,Uz=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,Fz=`varying vec3 vViewPosition; -struct ToonMaterial { - vec3 diffuseColor; -}; -void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Bz=`BlinnPhongMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularColor = specular; -material.specularShininess = shininess; -material.specularStrength = specularStrength;`,zz=`varying vec3 vViewPosition; -struct BlinnPhongMaterial { - vec3 diffuseColor; - vec3 specularColor; - float specularShininess; - float specularStrength; -}; -void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); - reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; -} -void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,Vz=`PhysicalMaterial material; -material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); -vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); -float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); -material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; -material.roughness = min( material.roughness, 1.0 ); -#ifdef IOR - material.ior = ior; - #ifdef USE_SPECULAR - float specularIntensityFactor = specularIntensity; - vec3 specularColorFactor = specularColor; - #ifdef USE_SPECULAR_COLORMAP - specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; - #endif - material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); - #else - float specularIntensityFactor = 1.0; - vec3 specularColorFactor = vec3( 1.0 ); - material.specularF90 = 1.0; - #endif - material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); -#else - material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); - material.specularF90 = 1.0; -#endif -#ifdef USE_CLEARCOAT - material.clearcoat = clearcoat; - material.clearcoatRoughness = clearcoatRoughness; - material.clearcoatF0 = vec3( 0.04 ); - material.clearcoatF90 = 1.0; - #ifdef USE_CLEARCOATMAP - material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; - #endif - #ifdef USE_CLEARCOAT_ROUGHNESSMAP - material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; - #endif - material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); - material.clearcoatRoughness += geometryRoughness; - material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); -#endif -#ifdef USE_DISPERSION - material.dispersion = dispersion; -#endif -#ifdef USE_IRIDESCENCE - material.iridescence = iridescence; - material.iridescenceIOR = iridescenceIOR; - #ifdef USE_IRIDESCENCEMAP - material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; - #endif - #ifdef USE_IRIDESCENCE_THICKNESSMAP - material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; - #else - material.iridescenceThickness = iridescenceThicknessMaximum; - #endif -#endif -#ifdef USE_SHEEN - material.sheenColor = sheenColor; - #ifdef USE_SHEEN_COLORMAP - material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; - #endif - material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); - #ifdef USE_SHEEN_ROUGHNESSMAP - material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; - #endif -#endif -#ifdef USE_ANISOTROPY - #ifdef USE_ANISOTROPYMAP - mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); - vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; - vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; - #else - vec2 anisotropyV = anisotropyVector; - #endif - material.anisotropy = length( anisotropyV ); - if( material.anisotropy == 0.0 ) { - anisotropyV = vec2( 1.0, 0.0 ); - } else { - anisotropyV /= material.anisotropy; - material.anisotropy = saturate( material.anisotropy ); - } - material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); - material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; - material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,Hz=`struct PhysicalMaterial { - vec3 diffuseColor; - float roughness; - vec3 specularColor; - float specularF90; - float dispersion; - #ifdef USE_CLEARCOAT - float clearcoat; - float clearcoatRoughness; - vec3 clearcoatF0; - float clearcoatF90; - #endif - #ifdef USE_IRIDESCENCE - float iridescence; - float iridescenceIOR; - float iridescenceThickness; - vec3 iridescenceFresnel; - vec3 iridescenceF0; - #endif - #ifdef USE_SHEEN - vec3 sheenColor; - float sheenRoughness; - #endif - #ifdef IOR - float ior; - #endif - #ifdef USE_TRANSMISSION - float transmission; - float transmissionAlpha; - float thickness; - float attenuationDistance; - vec3 attenuationColor; - #endif - #ifdef USE_ANISOTROPY - float anisotropy; - float alphaT; - vec3 anisotropyT; - vec3 anisotropyB; - #endif -}; -vec3 clearcoatSpecularDirect = vec3( 0.0 ); -vec3 clearcoatSpecularIndirect = vec3( 0.0 ); -vec3 sheenSpecularDirect = vec3( 0.0 ); -vec3 sheenSpecularIndirect = vec3(0.0 ); -vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { - float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); - float x2 = x * x; - float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); - return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); -} -float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { - float a2 = pow2( alpha ); - float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - return 0.5 / max( gv + gl, EPSILON ); -} -float D_GGX( const in float alpha, const in float dotNH ) { - float a2 = pow2( alpha ); - float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; - return RECIPROCAL_PI * a2 / pow2( denom ); -} -#ifdef USE_ANISOTROPY - float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { - float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); - float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); - float v = 0.5 / ( gv + gl ); - return saturate(v); - } - float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { - float a2 = alphaT * alphaB; - highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); - highp float v2 = dot( v, v ); - float w2 = a2 / v2; - return RECIPROCAL_PI * a2 * pow2 ( w2 ); - } -#endif -#ifdef USE_CLEARCOAT - vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { - vec3 f0 = material.clearcoatF0; - float f90 = material.clearcoatF90; - float roughness = material.clearcoatRoughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - return F * ( V * D ); - } -#endif -vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { - vec3 f0 = material.specularColor; - float f90 = material.specularF90; - float roughness = material.roughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - #ifdef USE_IRIDESCENCE - F = mix( F, material.iridescenceFresnel, material.iridescence ); - #endif - #ifdef USE_ANISOTROPY - float dotTL = dot( material.anisotropyT, lightDir ); - float dotTV = dot( material.anisotropyT, viewDir ); - float dotTH = dot( material.anisotropyT, halfDir ); - float dotBL = dot( material.anisotropyB, lightDir ); - float dotBV = dot( material.anisotropyB, viewDir ); - float dotBH = dot( material.anisotropyB, halfDir ); - float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); - float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); - #else - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - #endif - return F * ( V * D ); -} -vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { - const float LUT_SIZE = 64.0; - const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; - const float LUT_BIAS = 0.5 / LUT_SIZE; - float dotNV = saturate( dot( N, V ) ); - vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); - uv = uv * LUT_SCALE + LUT_BIAS; - return uv; -} -float LTC_ClippedSphereFormFactor( const in vec3 f ) { - float l = length( f ); - return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); -} -vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { - float x = dot( v1, v2 ); - float y = abs( x ); - float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; - float b = 3.4175940 + ( 4.1616724 + y ) * y; - float v = a / b; - float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; - return cross( v1, v2 ) * theta_sintheta; -} -vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { - vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; - vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; - vec3 lightNormal = cross( v1, v2 ); - if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); - vec3 T1, T2; - T1 = normalize( V - N * dot( V, N ) ); - T2 = - cross( N, T1 ); - mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); - vec3 coords[ 4 ]; - coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); - coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); - coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); - coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); - coords[ 0 ] = normalize( coords[ 0 ] ); - coords[ 1 ] = normalize( coords[ 1 ] ); - coords[ 2 ] = normalize( coords[ 2 ] ); - coords[ 3 ] = normalize( coords[ 3 ] ); - vec3 vectorFormFactor = vec3( 0.0 ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); - float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); - return vec3( result ); -} -#if defined( USE_SHEEN ) -float D_Charlie( float roughness, float dotNH ) { - float alpha = pow2( roughness ); - float invAlpha = 1.0 / alpha; - float cos2h = dotNH * dotNH; - float sin2h = max( 1.0 - cos2h, 0.0078125 ); - return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); -} -float V_Neubelt( float dotNV, float dotNL ) { - return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); -} -vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float D = D_Charlie( sheenRoughness, dotNH ); - float V = V_Neubelt( dotNV, dotNL ); - return sheenColor * ( D * V ); -} -#endif -float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - float r2 = roughness * roughness; - float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; - float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; - float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); - return saturate( DG * RECIPROCAL_PI ); -} -vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); - const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); - vec4 r = roughness * c0 + c1; - float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; - vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; - return fab; -} -vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { - vec2 fab = DFGApprox( normal, viewDir, roughness ); - return specularColor * fab.x + specularF90 * fab.y; -} -#ifdef USE_IRIDESCENCE -void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#else -void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#endif - vec2 fab = DFGApprox( normal, viewDir, roughness ); - #ifdef USE_IRIDESCENCE - vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); - #else - vec3 Fr = specularColor; - #endif - vec3 FssEss = Fr * fab.x + specularF90 * fab.y; - float Ess = fab.x + fab.y; - float Ems = 1.0 - Ess; - vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); - singleScatter += FssEss; - multiScatter += Fms * Ems; -} -#if NUM_RECT_AREA_LIGHTS > 0 - void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - vec3 normal = geometryNormal; - vec3 viewDir = geometryViewDir; - vec3 position = geometryPosition; - vec3 lightPos = rectAreaLight.position; - vec3 halfWidth = rectAreaLight.halfWidth; - vec3 halfHeight = rectAreaLight.halfHeight; - vec3 lightColor = rectAreaLight.color; - float roughness = material.roughness; - vec3 rectCoords[ 4 ]; - rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; - rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; - rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; - vec2 uv = LTC_Uv( normal, viewDir, roughness ); - vec4 t1 = texture2D( ltc_1, uv ); - vec4 t2 = texture2D( ltc_2, uv ); - mat3 mInv = mat3( - vec3( t1.x, 0, t1.y ), - vec3( 0, 1, 0 ), - vec3( t1.z, 0, t1.w ) - ); - vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); - reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); - reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); - } -#endif -void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - #ifdef USE_CLEARCOAT - float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); - vec3 ccIrradiance = dotNLcc * directLight.color; - clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); - #endif - #ifdef USE_SHEEN - sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); - #endif - reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { - #ifdef USE_CLEARCOAT - clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); - #endif - #ifdef USE_SHEEN - sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); - #endif - vec3 singleScattering = vec3( 0.0 ); - vec3 multiScattering = vec3( 0.0 ); - vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; - #ifdef USE_IRIDESCENCE - computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); - #else - computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); - #endif - vec3 totalScattering = singleScattering + multiScattering; - vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); - reflectedLight.indirectSpecular += radiance * singleScattering; - reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; - reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; -} -#define RE_Direct RE_Direct_Physical -#define RE_Direct_RectArea RE_Direct_RectArea_Physical -#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical -#define RE_IndirectSpecular RE_IndirectSpecular_Physical -float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { - return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,Gz=` -vec3 geometryPosition = - vViewPosition; -vec3 geometryNormal = normal; -vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); -vec3 geometryClearcoatNormal = vec3( 0.0 ); -#ifdef USE_CLEARCOAT - geometryClearcoatNormal = clearcoatNormal; -#endif -#ifdef USE_IRIDESCENCE - float dotNVi = saturate( dot( normal, geometryViewDir ) ); - if ( material.iridescenceThickness == 0.0 ) { - material.iridescence = 0.0; - } else { - material.iridescence = saturate( material.iridescence ); - } - if ( material.iridescence > 0.0 ) { - material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); - material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); - } -#endif -IncidentLight directLight; -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - pointLight = pointLights[ i ]; - getPointLightInfo( pointLight, geometryPosition, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - SpotLight spotLight; - vec4 spotColor; - vec3 spotLightCoord; - bool inSpotLightMap; - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - spotLight = spotLights[ i ]; - getSpotLightInfo( spotLight, geometryPosition, directLight ); - #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX - #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS - #else - #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #endif - #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) - spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; - inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); - spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); - directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; - #endif - #undef SPOT_LIGHT_MAP_INDEX - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) - RectAreaLight rectAreaLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if defined( RE_IndirectDiffuse ) - vec3 iblIrradiance = vec3( 0.0 ); - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - #if defined( USE_LIGHT_PROBES ) - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - #endif - #if ( NUM_HEMI_LIGHTS > 0 ) - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - } - #pragma unroll_loop_end - #endif -#endif -#if defined( RE_IndirectSpecular ) - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,Wz=`#if defined( RE_IndirectDiffuse ) - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - irradiance += lightMapIrradiance; - #endif - #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) - iblIrradiance += getIBLIrradiance( geometryNormal ); - #endif -#endif -#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) - #ifdef USE_ANISOTROPY - radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); - #else - radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); - #endif - #ifdef USE_CLEARCOAT - clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); - #endif -#endif`,jz=`#if defined( RE_IndirectDiffuse ) - RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif -#if defined( RE_IndirectSpecular ) - RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,$z=`#if defined( USE_LOGDEPTHBUF ) - gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,qz=`#if defined( USE_LOGDEPTHBUF ) - uniform float logDepthBufFC; - varying float vFragDepth; - varying float vIsPerspective; -#endif`,Xz=`#ifdef USE_LOGDEPTHBUF - varying float vFragDepth; - varying float vIsPerspective; -#endif`,Kz=`#ifdef USE_LOGDEPTHBUF - vFragDepth = 1.0 + gl_Position.w; - vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,Yz=`#ifdef USE_MAP - vec4 sampledDiffuseColor = texture2D( map, vMapUv ); - #ifdef DECODE_VIDEO_TEXTURE - sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); - #endif - diffuseColor *= sampledDiffuseColor; -#endif`,Zz=`#ifdef USE_MAP - uniform sampler2D map; -#endif`,Qz=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - #if defined( USE_POINTS_UV ) - vec2 uv = vUv; - #else - vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; - #endif -#endif -#ifdef USE_MAP - diffuseColor *= texture2D( map, uv ); -#endif -#ifdef USE_ALPHAMAP - diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,Jz=`#if defined( USE_POINTS_UV ) - varying vec2 vUv; -#else - #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - uniform mat3 uvTransform; - #endif -#endif -#ifdef USE_MAP - uniform sampler2D map; -#endif -#ifdef USE_ALPHAMAP - uniform sampler2D alphaMap; -#endif`,e8=`float metalnessFactor = metalness; -#ifdef USE_METALNESSMAP - vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); - metalnessFactor *= texelMetalness.b; -#endif`,t8=`#ifdef USE_METALNESSMAP - uniform sampler2D metalnessMap; -#endif`,n8=`#ifdef USE_INSTANCING_MORPH - float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; - } -#endif`,r8=`#if defined( USE_MORPHCOLORS ) - vColor *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - #if defined( USE_COLOR_ALPHA ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; - #elif defined( USE_COLOR ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; - #endif - } -#endif`,i8=`#ifdef USE_MORPHNORMALS - objectNormal *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,s8=`#ifdef USE_MORPHTARGETS - #ifndef USE_INSTANCING_MORPH - uniform float morphTargetBaseInfluence; - uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - #endif - uniform sampler2DArray morphTargetsTexture; - uniform ivec2 morphTargetsTextureSize; - vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { - int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; - int y = texelIndex / morphTargetsTextureSize.x; - int x = texelIndex - y * morphTargetsTextureSize.x; - ivec3 morphUV = ivec3( x, y, morphTargetIndex ); - return texelFetch( morphTargetsTexture, morphUV, 0 ); - } -#endif`,o8=`#ifdef USE_MORPHTARGETS - transformed *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,a8=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; -#ifdef FLAT_SHADED - vec3 fdx = dFdx( vViewPosition ); - vec3 fdy = dFdy( vViewPosition ); - vec3 normal = normalize( cross( fdx, fdy ) ); -#else - vec3 normal = normalize( vNormal ); - #ifdef DOUBLE_SIDED - normal *= faceDirection; - #endif -#endif -#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) - #ifdef USE_TANGENT - mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn = getTangentFrame( - vViewPosition, normal, - #if defined( USE_NORMALMAP ) - vNormalMapUv - #elif defined( USE_CLEARCOAT_NORMALMAP ) - vClearcoatNormalMapUv - #else - vUv - #endif - ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn[0] *= faceDirection; - tbn[1] *= faceDirection; - #endif -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - #ifdef USE_TANGENT - mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn2[0] *= faceDirection; - tbn2[1] *= faceDirection; - #endif -#endif -vec3 nonPerturbedNormal = normal;`,c8=`#ifdef USE_NORMALMAP_OBJECTSPACE - normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - #ifdef FLIP_SIDED - normal = - normal; - #endif - #ifdef DOUBLE_SIDED - normal = normal * faceDirection; - #endif - normal = normalize( normalMatrix * normal ); -#elif defined( USE_NORMALMAP_TANGENTSPACE ) - vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - mapN.xy *= normalScale; - normal = normalize( tbn * mapN ); -#elif defined( USE_BUMPMAP ) - normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,l8=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,u8=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,h8=`#ifndef FLAT_SHADED - vNormal = normalize( transformedNormal ); - #ifdef USE_TANGENT - vTangent = normalize( transformedTangent ); - vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); - #endif -#endif`,f8=`#ifdef USE_NORMALMAP - uniform sampler2D normalMap; - uniform vec2 normalScale; -#endif -#ifdef USE_NORMALMAP_OBJECTSPACE - uniform mat3 normalMatrix; -#endif -#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) - mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { - vec3 q0 = dFdx( eye_pos.xyz ); - vec3 q1 = dFdy( eye_pos.xyz ); - vec2 st0 = dFdx( uv.st ); - vec2 st1 = dFdy( uv.st ); - vec3 N = surf_norm; - vec3 q1perp = cross( q1, N ); - vec3 q0perp = cross( N, q0 ); - vec3 T = q1perp * st0.x + q0perp * st1.x; - vec3 B = q1perp * st0.y + q0perp * st1.y; - float det = max( dot( T, T ), dot( B, B ) ); - float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); - return mat3( T * scale, B * scale, N ); - } -#endif`,d8=`#ifdef USE_CLEARCOAT - vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,p8=`#ifdef USE_CLEARCOAT_NORMALMAP - vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; - clearcoatMapN.xy *= clearcoatNormalScale; - clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,m8=`#ifdef USE_CLEARCOATMAP - uniform sampler2D clearcoatMap; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform sampler2D clearcoatNormalMap; - uniform vec2 clearcoatNormalScale; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform sampler2D clearcoatRoughnessMap; -#endif`,g8=`#ifdef USE_IRIDESCENCEMAP - uniform sampler2D iridescenceMap; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform sampler2D iridescenceThicknessMap; -#endif`,_8=`#ifdef OPAQUE -diffuseColor.a = 1.0; -#endif -#ifdef USE_TRANSMISSION -diffuseColor.a *= material.transmissionAlpha; -#endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,v8=`vec3 packNormalToRGB( const in vec3 normal ) { - return normalize( normal ) * 0.5 + 0.5; -} -vec3 unpackRGBToNormal( const in vec3 rgb ) { - return 2.0 * rgb.xyz - 1.0; -} -const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; -const float Inv255 = 1. / 255.; -const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); -const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); -const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); -const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); -vec4 packDepthToRGBA( const in float v ) { - if( v <= 0.0 ) - return vec4( 0., 0., 0., 0. ); - if( v >= 1.0 ) - return vec4( 1., 1., 1., 1. ); - float vuf; - float af = modf( v * PackFactors.a, vuf ); - float bf = modf( vuf * ShiftRight8, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); -} -vec3 packDepthToRGB( const in float v ) { - if( v <= 0.0 ) - return vec3( 0., 0., 0. ); - if( v >= 1.0 ) - return vec3( 1., 1., 1. ); - float vuf; - float bf = modf( v * PackFactors.b, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec3( vuf * Inv255, gf * PackUpscale, bf ); -} -vec2 packDepthToRG( const in float v ) { - if( v <= 0.0 ) - return vec2( 0., 0. ); - if( v >= 1.0 ) - return vec2( 1., 1. ); - float vuf; - float gf = modf( v * 256., vuf ); - return vec2( vuf * Inv255, gf ); -} -float unpackRGBAToDepth( const in vec4 v ) { - return dot( v, UnpackFactors4 ); -} -float unpackRGBToDepth( const in vec3 v ) { - return dot( v, UnpackFactors3 ); -} -float unpackRGToDepth( const in vec2 v ) { - return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; -} -vec4 pack2HalfToRGBA( const in vec2 v ) { - vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); - return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); -} -vec2 unpackRGBATo2Half( const in vec4 v ) { - return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); -} -float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { - return ( viewZ + near ) / ( near - far ); -} -float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { - return depth * ( near - far ) - near; -} -float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { - return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); -} -float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { - return ( near * far ) / ( ( far - near ) * depth - far ); -}`,y8=`#ifdef PREMULTIPLIED_ALPHA - gl_FragColor.rgb *= gl_FragColor.a; -#endif`,x8=`vec4 mvPosition = vec4( transformed, 1.0 ); -#ifdef USE_BATCHING - mvPosition = batchingMatrix * mvPosition; -#endif -#ifdef USE_INSTANCING - mvPosition = instanceMatrix * mvPosition; -#endif -mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,S8=`#ifdef DITHERING - gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,E8=`#ifdef DITHERING - vec3 dithering( vec3 color ) { - float grid_position = rand( gl_FragCoord.xy ); - vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); - dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); - return color + dither_shift_RGB; - } -#endif`,w8=`float roughnessFactor = roughness; -#ifdef USE_ROUGHNESSMAP - vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); - roughnessFactor *= texelRoughness.g; -#endif`,T8=`#ifdef USE_ROUGHNESSMAP - uniform sampler2D roughnessMap; -#endif`,b8=`#if NUM_SPOT_LIGHT_COORDS > 0 - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#if NUM_SPOT_LIGHT_MAPS > 0 - uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif - float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { - return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); - } - vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { - return unpackRGBATo2Half( texture2D( shadow, uv ) ); - } - float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ - float occlusion = 1.0; - vec2 distribution = texture2DDistribution( shadow, uv ); - float hard_shadow = step( compare , distribution.x ); - if (hard_shadow != 1.0 ) { - float distance = compare - distribution.x ; - float variance = max( 0.00000, distribution.y * distribution.y ); - float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); - } - return occlusion; - } - float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - float shadow = 1.0; - shadowCoord.xyz /= shadowCoord.w; - shadowCoord.z += shadowBias; - bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; - bool frustumTest = inFrustum && shadowCoord.z <= 1.0; - if ( frustumTest ) { - #if defined( SHADOWMAP_TYPE_PCF ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx0 = - texelSize.x * shadowRadius; - float dy0 = - texelSize.y * shadowRadius; - float dx1 = + texelSize.x * shadowRadius; - float dy1 = + texelSize.y * shadowRadius; - float dx2 = dx0 / 2.0; - float dy2 = dy0 / 2.0; - float dx3 = dx1 / 2.0; - float dy3 = dy1 / 2.0; - shadow = ( - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) - ) * ( 1.0 / 17.0 ); - #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx = texelSize.x; - float dy = texelSize.y; - vec2 uv = shadowCoord.xy; - vec2 f = fract( uv * shadowMapSize + 0.5 ); - uv -= f * texelSize; - shadow = ( - texture2DCompare( shadowMap, uv, shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), - f.x ), - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), - f.x ), - f.y ) - ) * ( 1.0 / 9.0 ); - #elif defined( SHADOWMAP_TYPE_VSM ) - shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); - #else - shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } - vec2 cubeToUV( vec3 v, float texelSizeY ) { - vec3 absV = abs( v ); - float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); - absV *= scaleToCube; - v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); - vec2 planar = v.xy; - float almostATexel = 1.5 * texelSizeY; - float almostOne = 1.0 - almostATexel; - if ( absV.z >= almostOne ) { - if ( v.z > 0.0 ) - planar.x = 4.0 - v.x; - } else if ( absV.x >= almostOne ) { - float signX = sign( v.x ); - planar.x = v.z * signX + 2.0 * signX; - } else if ( absV.y >= almostOne ) { - float signY = sign( v.y ); - planar.x = v.x + 2.0 * signY + 2.0; - planar.y = v.z * signY - 2.0; - } - return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); - } - float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { - float shadow = 1.0; - vec3 lightToPosition = shadowCoord.xyz; - - float lightToPositionLength = length( lightToPosition ); - if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { - float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; - vec3 bd3D = normalize( lightToPosition ); - vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); - #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) - vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; - shadow = ( - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) - ) * ( 1.0 / 9.0 ); - #else - shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } -#endif`,A8=`#if NUM_SPOT_LIGHT_COORDS > 0 - uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif -#endif`,M8=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) - vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - vec4 shadowWorldPosition; -#endif -#if defined( USE_SHADOWMAP ) - #if NUM_DIR_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); - vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); - vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif -#endif -#if NUM_SPOT_LIGHT_COORDS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { - shadowWorldPosition = worldPosition; - #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; - #endif - vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end -#endif`,C8=`float getShadowMask() { - float shadow = 1.0; - #ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - directionalLight = directionalLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { - spotLight = spotLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - pointLight = pointLightShadows[ i ]; - shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; - } - #pragma unroll_loop_end - #endif - #endif - return shadow; -}`,R8=`#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,k8=`#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif`,I8=`#ifdef USE_SKINNING - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,N8=`#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - #ifdef USE_TANGENT - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - #endif -#endif`,O8=`float specularStrength; -#ifdef USE_SPECULARMAP - vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); - specularStrength = texelSpecular.r; -#else - specularStrength = 1.0; -#endif`,L8=`#ifdef USE_SPECULARMAP - uniform sampler2D specularMap; -#endif`,P8=`#if defined( TONE_MAPPING ) - gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,D8=`#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -uniform float toneMappingExposure; -vec3 LinearToneMapping( vec3 color ) { - return saturate( toneMappingExposure * color ); -} -vec3 ReinhardToneMapping( vec3 color ) { - color *= toneMappingExposure; - return saturate( color / ( vec3( 1.0 ) + color ) ); -} -vec3 CineonToneMapping( vec3 color ) { - color *= toneMappingExposure; - color = max( vec3( 0.0 ), color - 0.004 ); - return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); -} -vec3 RRTAndODTFit( vec3 v ) { - vec3 a = v * ( v + 0.0245786 ) - 0.000090537; - vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; - return a / b; -} -vec3 ACESFilmicToneMapping( vec3 color ) { - const mat3 ACESInputMat = mat3( - vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), - vec3( 0.04823, 0.01566, 0.83777 ) - ); - const mat3 ACESOutputMat = mat3( - vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), - vec3( -0.07367, -0.00605, 1.07602 ) - ); - color *= toneMappingExposure / 0.6; - color = ACESInputMat * color; - color = RRTAndODTFit( color ); - color = ACESOutputMat * color; - return saturate( color ); -} -const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( - vec3( 1.6605, - 0.1246, - 0.0182 ), - vec3( - 0.5876, 1.1329, - 0.1006 ), - vec3( - 0.0728, - 0.0083, 1.1187 ) -); -const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( - vec3( 0.6274, 0.0691, 0.0164 ), - vec3( 0.3293, 0.9195, 0.0880 ), - vec3( 0.0433, 0.0113, 0.8956 ) -); -vec3 agxDefaultContrastApprox( vec3 x ) { - vec3 x2 = x * x; - vec3 x4 = x2 * x2; - return + 15.5 * x4 * x2 - - 40.14 * x4 * x - + 31.96 * x4 - - 6.868 * x2 * x - + 0.4298 * x2 - + 0.1191 * x - - 0.00232; -} -vec3 AgXToneMapping( vec3 color ) { - const mat3 AgXInsetMatrix = mat3( - vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), - vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), - vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) - ); - const mat3 AgXOutsetMatrix = mat3( - vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), - vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), - vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) - ); - const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; - color *= toneMappingExposure; - color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; - color = AgXInsetMatrix * color; - color = max( color, 1e-10 ); color = log2( color ); - color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); - color = clamp( color, 0.0, 1.0 ); - color = agxDefaultContrastApprox( color ); - color = AgXOutsetMatrix * color; - color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); - color = LINEAR_REC2020_TO_LINEAR_SRGB * color; - color = clamp( color, 0.0, 1.0 ); - return color; -} -vec3 NeutralToneMapping( vec3 color ) { - const float StartCompression = 0.8 - 0.04; - const float Desaturation = 0.15; - color *= toneMappingExposure; - float x = min( color.r, min( color.g, color.b ) ); - float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; - color -= offset; - float peak = max( color.r, max( color.g, color.b ) ); - if ( peak < StartCompression ) return color; - float d = 1. - StartCompression; - float newPeak = 1. - d * d / ( peak + d - StartCompression ); - color *= newPeak / peak; - float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); - return mix( color, vec3( newPeak ), g ); -} -vec3 CustomToneMapping( vec3 color ) { return color; }`,U8=`#ifdef USE_TRANSMISSION - material.transmission = transmission; - material.transmissionAlpha = 1.0; - material.thickness = thickness; - material.attenuationDistance = attenuationDistance; - material.attenuationColor = attenuationColor; - #ifdef USE_TRANSMISSIONMAP - material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; - #endif - #ifdef USE_THICKNESSMAP - material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; - #endif - vec3 pos = vWorldPosition; - vec3 v = normalize( cameraPosition - pos ); - vec3 n = inverseTransformDirection( normal, viewMatrix ); - vec4 transmitted = getIBLVolumeRefraction( - n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, - pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, - material.attenuationColor, material.attenuationDistance ); - material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); - totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,F8=`#ifdef USE_TRANSMISSION - uniform float transmission; - uniform float thickness; - uniform float attenuationDistance; - uniform vec3 attenuationColor; - #ifdef USE_TRANSMISSIONMAP - uniform sampler2D transmissionMap; - #endif - #ifdef USE_THICKNESSMAP - uniform sampler2D thicknessMap; - #endif - uniform vec2 transmissionSamplerSize; - uniform sampler2D transmissionSamplerMap; - uniform mat4 modelMatrix; - uniform mat4 projectionMatrix; - varying vec3 vWorldPosition; - float w0( float a ) { - return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); - } - float w1( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); - } - float w2( float a ){ - return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); - } - float w3( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * a ); - } - float g0( float a ) { - return w0( a ) + w1( a ); - } - float g1( float a ) { - return w2( a ) + w3( a ); - } - float h0( float a ) { - return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); - } - float h1( float a ) { - return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); - } - vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { - uv = uv * texelSize.zw + 0.5; - vec2 iuv = floor( uv ); - vec2 fuv = fract( uv ); - float g0x = g0( fuv.x ); - float g1x = g1( fuv.x ); - float h0x = h0( fuv.x ); - float h1x = h1( fuv.x ); - float h0y = h0( fuv.y ); - float h1y = h1( fuv.y ); - vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + - g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); - } - vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { - vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); - vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); - vec2 fLodSizeInv = 1.0 / fLodSize; - vec2 cLodSizeInv = 1.0 / cLodSize; - vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); - vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); - return mix( fSample, cSample, fract( lod ) ); - } - vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { - vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); - vec3 modelScale; - modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); - modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); - modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); - return normalize( refractionVector ) * thickness * modelScale; - } - float applyIorToRoughness( const in float roughness, const in float ior ) { - return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); - } - vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { - float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); - return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); - } - vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { - if ( isinf( attenuationDistance ) ) { - return vec3( 1.0 ); - } else { - vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; - vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; - } - } - vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, - const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, - const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, - const in vec3 attenuationColor, const in float attenuationDistance ) { - vec4 transmittedLight; - vec3 transmittance; - #ifdef USE_DISPERSION - float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; - vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); - for ( int i = 0; i < 3; i ++ ) { - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - - vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); - transmittedLight[ i ] = transmissionSample[ i ]; - transmittedLight.a += transmissionSample.a; - transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; - } - transmittedLight.a /= 3.0; - - #else - - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); - transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); - - #endif - vec3 attenuatedColor = transmittance * transmittedLight.rgb; - vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); - float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; - return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); - } -#endif`,B8=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - varying vec2 vNormalMapUv; -#endif -#ifdef USE_EMISSIVEMAP - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_SPECULARMAP - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,z8=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - uniform mat3 mapTransform; - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - uniform mat3 alphaMapTransform; - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - uniform mat3 lightMapTransform; - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - uniform mat3 aoMapTransform; - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - uniform mat3 bumpMapTransform; - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - uniform mat3 normalMapTransform; - varying vec2 vNormalMapUv; -#endif -#ifdef USE_DISPLACEMENTMAP - uniform mat3 displacementMapTransform; - varying vec2 vDisplacementMapUv; -#endif -#ifdef USE_EMISSIVEMAP - uniform mat3 emissiveMapTransform; - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - uniform mat3 metalnessMapTransform; - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - uniform mat3 roughnessMapTransform; - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - uniform mat3 anisotropyMapTransform; - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - uniform mat3 clearcoatMapTransform; - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform mat3 clearcoatNormalMapTransform; - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform mat3 clearcoatRoughnessMapTransform; - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - uniform mat3 sheenColorMapTransform; - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - uniform mat3 sheenRoughnessMapTransform; - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - uniform mat3 iridescenceMapTransform; - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform mat3 iridescenceThicknessMapTransform; - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SPECULARMAP - uniform mat3 specularMapTransform; - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - uniform mat3 specularColorMapTransform; - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - uniform mat3 specularIntensityMapTransform; - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,V8=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - vUv = vec3( uv, 1 ).xy; -#endif -#ifdef USE_MAP - vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ALPHAMAP - vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_LIGHTMAP - vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_AOMAP - vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_BUMPMAP - vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_NORMALMAP - vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_DISPLACEMENTMAP - vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_EMISSIVEMAP - vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_METALNESSMAP - vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ROUGHNESSMAP - vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ANISOTROPYMAP - vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOATMAP - vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCEMAP - vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_COLORMAP - vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULARMAP - vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_COLORMAP - vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_TRANSMISSIONMAP - vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_THICKNESSMAP - vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,H8=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 - vec4 worldPosition = vec4( transformed, 1.0 ); - #ifdef USE_BATCHING - worldPosition = batchingMatrix * worldPosition; - #endif - #ifdef USE_INSTANCING - worldPosition = instanceMatrix * worldPosition; - #endif - worldPosition = modelMatrix * worldPosition; -#endif`;const G8=`varying vec2 vUv; -uniform mat3 uvTransform; -void main() { - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,W8=`uniform sampler2D t2D; -uniform float backgroundIntensity; -varying vec2 vUv; -void main() { - vec4 texColor = texture2D( t2D, vUv ); - #ifdef DECODE_VIDEO_TEXTURE - texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,j8=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,$8=`#ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; -#elif defined( ENVMAP_TYPE_CUBE_UV ) - uniform sampler2D envMap; -#endif -uniform float flipEnvMap; -uniform float backgroundBlurriness; -uniform float backgroundIntensity; -uniform mat3 backgroundRotation; -varying vec3 vWorldDirection; -#include -void main() { - #ifdef ENVMAP_TYPE_CUBE - vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); - #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); - #else - vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,q8=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,X8=`uniform samplerCube tCube; -uniform float tFlip; -uniform float opacity; -varying vec3 vWorldDirection; -void main() { - vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); - gl_FragColor = texColor; - gl_FragColor.a *= opacity; - #include - #include -}`,K8=`#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vHighPrecisionZW = gl_Position.zw; -}`,Y8=`#if DEPTH_PACKING == 3200 - uniform float opacity; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - vec4 diffuseColor = vec4( 1.0 ); - #include - #if DEPTH_PACKING == 3200 - diffuseColor.a = opacity; - #endif - #include - #include - #include - #include - #include - float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; - #if DEPTH_PACKING == 3200 - gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); - #elif DEPTH_PACKING == 3201 - gl_FragColor = packDepthToRGBA( fragCoordZ ); - #elif DEPTH_PACKING == 3202 - gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); - #elif DEPTH_PACKING == 3203 - gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); - #endif -}`,Z8=`#define DISTANCE -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vWorldPosition = worldPosition.xyz; -}`,Q8=`#define DISTANCE -uniform vec3 referencePosition; -uniform float nearDistance; -uniform float farDistance; -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -#include -void main () { - vec4 diffuseColor = vec4( 1.0 ); - #include - #include - #include - #include - #include - float dist = length( vWorldPosition - referencePosition ); - dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); - dist = saturate( dist ); - gl_FragColor = packDepthToRGBA( dist ); -}`,J8=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include -}`,e6=`uniform sampler2D tEquirect; -varying vec3 vWorldDirection; -#include -void main() { - vec3 direction = normalize( vWorldDirection ); - vec2 sampleUV = equirectUv( direction ); - gl_FragColor = texture2D( tEquirect, sampleUV ); - #include - #include -}`,t6=`uniform float scale; -attribute float lineDistance; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vLineDistance = scale * lineDistance; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,n6=`uniform vec3 diffuse; -uniform float opacity; -uniform float dashSize; -uniform float totalSize; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - if ( mod( vLineDistance, totalSize ) > dashSize ) { - discard; - } - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,r6=`#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) - #include - #include - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,i6=`uniform vec3 diffuse; -uniform float opacity; -#ifndef FLAT_SHADED - varying vec3 vNormal; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; - #else - reflectedLight.indirectDiffuse += vec3( 1.0 ); - #endif - #include - reflectedLight.indirectDiffuse *= diffuseColor.rgb; - vec3 outgoingLight = reflectedLight.indirectDiffuse; - #include - #include - #include - #include - #include - #include - #include -}`,s6=`#define LAMBERT -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,o6=`#define LAMBERT -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,a6=`#define MATCAP -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; -}`,c6=`#define MATCAP -uniform vec3 diffuse; -uniform float opacity; -uniform sampler2D matcap; -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 viewDir = normalize( vViewPosition ); - vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); - vec3 y = cross( viewDir, x ); - vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; - #ifdef USE_MATCAP - vec4 matcapColor = texture2D( matcap, uv ); - #else - vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); - #endif - vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; - #include - #include - #include - #include - #include - #include -}`,l6=`#define NORMAL -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - vViewPosition = - mvPosition.xyz; -#endif -}`,u6=`#define NORMAL -uniform float opacity; -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); - #include - #include - #include - #include - gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); - #ifdef OPAQUE - gl_FragColor.a = 1.0; - #endif -}`,h6=`#define PHONG -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,f6=`#define PHONG -uniform vec3 diffuse; -uniform vec3 emissive; -uniform vec3 specular; -uniform float shininess; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,d6=`#define STANDARD -varying vec3 vViewPosition; -#ifdef USE_TRANSMISSION - varying vec3 vWorldPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -#ifdef USE_TRANSMISSION - vWorldPosition = worldPosition.xyz; -#endif -}`,p6=`#define STANDARD -#ifdef PHYSICAL - #define IOR - #define USE_SPECULAR -#endif -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float roughness; -uniform float metalness; -uniform float opacity; -#ifdef IOR - uniform float ior; -#endif -#ifdef USE_SPECULAR - uniform float specularIntensity; - uniform vec3 specularColor; - #ifdef USE_SPECULAR_COLORMAP - uniform sampler2D specularColorMap; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - uniform sampler2D specularIntensityMap; - #endif -#endif -#ifdef USE_CLEARCOAT - uniform float clearcoat; - uniform float clearcoatRoughness; -#endif -#ifdef USE_DISPERSION - uniform float dispersion; -#endif -#ifdef USE_IRIDESCENCE - uniform float iridescence; - uniform float iridescenceIOR; - uniform float iridescenceThicknessMinimum; - uniform float iridescenceThicknessMaximum; -#endif -#ifdef USE_SHEEN - uniform vec3 sheenColor; - uniform float sheenRoughness; - #ifdef USE_SHEEN_COLORMAP - uniform sampler2D sheenColorMap; - #endif - #ifdef USE_SHEEN_ROUGHNESSMAP - uniform sampler2D sheenRoughnessMap; - #endif -#endif -#ifdef USE_ANISOTROPY - uniform vec2 anisotropyVector; - #ifdef USE_ANISOTROPYMAP - uniform sampler2D anisotropyMap; - #endif -#endif -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; - vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; - #include - vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; - #ifdef USE_SHEEN - float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); - outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; - #endif - #ifdef USE_CLEARCOAT - float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); - vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); - outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; - #endif - #include - #include - #include - #include - #include - #include -}`,m6=`#define TOON -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -}`,g6=`#define TOON -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include -}`,_6=`uniform float size; -uniform float scale; -#include -#include -#include -#include -#include -#include -#ifdef USE_POINTS_UV - varying vec2 vUv; - uniform mat3 uvTransform; -#endif -void main() { - #ifdef USE_POINTS_UV - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - #endif - #include - #include - #include - #include - #include - #include - gl_PointSize = size; - #ifdef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); - #endif - #include - #include - #include - #include -}`,v6=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,y6=`#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,x6=`uniform vec3 color; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); - #include - #include - #include -}`,S6=`uniform float rotation; -uniform vec2 center; -#include -#include -#include -#include -#include -void main() { - #include - vec4 mvPosition = modelViewMatrix[ 3 ]; - vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); - #ifndef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) scale *= - mvPosition.z; - #endif - vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; - vec2 rotatedPosition; - rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; - rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; - mvPosition.xy += rotatedPosition; - gl_Position = projectionMatrix * mvPosition; - #include - #include - #include -}`,E6=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include -}`,Ft={alphahash_fragment:W5,alphahash_pars_fragment:j5,alphamap_fragment:$5,alphamap_pars_fragment:q5,alphatest_fragment:X5,alphatest_pars_fragment:K5,aomap_fragment:Y5,aomap_pars_fragment:Z5,batching_pars_vertex:Q5,batching_vertex:J5,begin_vertex:ez,beginnormal_vertex:tz,bsdfs:nz,iridescence_fragment:rz,bumpmap_pars_fragment:iz,clipping_planes_fragment:sz,clipping_planes_pars_fragment:oz,clipping_planes_pars_vertex:az,clipping_planes_vertex:cz,color_fragment:lz,color_pars_fragment:uz,color_pars_vertex:hz,color_vertex:fz,common:dz,cube_uv_reflection_fragment:pz,defaultnormal_vertex:mz,displacementmap_pars_vertex:gz,displacementmap_vertex:_z,emissivemap_fragment:vz,emissivemap_pars_fragment:yz,colorspace_fragment:xz,colorspace_pars_fragment:Sz,envmap_fragment:Ez,envmap_common_pars_fragment:wz,envmap_pars_fragment:Tz,envmap_pars_vertex:bz,envmap_physical_pars_fragment:Dz,envmap_vertex:Az,fog_vertex:Mz,fog_pars_vertex:Cz,fog_fragment:Rz,fog_pars_fragment:kz,gradientmap_pars_fragment:Iz,lightmap_pars_fragment:Nz,lights_lambert_fragment:Oz,lights_lambert_pars_fragment:Lz,lights_pars_begin:Pz,lights_toon_fragment:Uz,lights_toon_pars_fragment:Fz,lights_phong_fragment:Bz,lights_phong_pars_fragment:zz,lights_physical_fragment:Vz,lights_physical_pars_fragment:Hz,lights_fragment_begin:Gz,lights_fragment_maps:Wz,lights_fragment_end:jz,logdepthbuf_fragment:$z,logdepthbuf_pars_fragment:qz,logdepthbuf_pars_vertex:Xz,logdepthbuf_vertex:Kz,map_fragment:Yz,map_pars_fragment:Zz,map_particle_fragment:Qz,map_particle_pars_fragment:Jz,metalnessmap_fragment:e8,metalnessmap_pars_fragment:t8,morphinstance_vertex:n8,morphcolor_vertex:r8,morphnormal_vertex:i8,morphtarget_pars_vertex:s8,morphtarget_vertex:o8,normal_fragment_begin:a8,normal_fragment_maps:c8,normal_pars_fragment:l8,normal_pars_vertex:u8,normal_vertex:h8,normalmap_pars_fragment:f8,clearcoat_normal_fragment_begin:d8,clearcoat_normal_fragment_maps:p8,clearcoat_pars_fragment:m8,iridescence_pars_fragment:g8,opaque_fragment:_8,packing:v8,premultiplied_alpha_fragment:y8,project_vertex:x8,dithering_fragment:S8,dithering_pars_fragment:E8,roughnessmap_fragment:w8,roughnessmap_pars_fragment:T8,shadowmap_pars_fragment:b8,shadowmap_pars_vertex:A8,shadowmap_vertex:M8,shadowmask_pars_fragment:C8,skinbase_vertex:R8,skinning_pars_vertex:k8,skinning_vertex:I8,skinnormal_vertex:N8,specularmap_fragment:O8,specularmap_pars_fragment:L8,tonemapping_fragment:P8,tonemapping_pars_fragment:D8,transmission_fragment:U8,transmission_pars_fragment:F8,uv_pars_fragment:B8,uv_pars_vertex:z8,uv_vertex:V8,worldpos_vertex:H8,background_vert:G8,background_frag:W8,backgroundCube_vert:j8,backgroundCube_frag:$8,cube_vert:q8,cube_frag:X8,depth_vert:K8,depth_frag:Y8,distanceRGBA_vert:Z8,distanceRGBA_frag:Q8,equirect_vert:J8,equirect_frag:e6,linedashed_vert:t6,linedashed_frag:n6,meshbasic_vert:r6,meshbasic_frag:i6,meshlambert_vert:s6,meshlambert_frag:o6,meshmatcap_vert:a6,meshmatcap_frag:c6,meshnormal_vert:l6,meshnormal_frag:u6,meshphong_vert:h6,meshphong_frag:f6,meshphysical_vert:d6,meshphysical_frag:p6,meshtoon_vert:m6,meshtoon_frag:g6,points_vert:_6,points_frag:v6,shadow_vert:y6,shadow_frag:x6,sprite_vert:S6,sprite_frag:E6},qe={common:{diffuse:{value:new cn(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Dt},alphaMap:{value:null},alphaMapTransform:{value:new Dt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Dt}},envmap:{envMap:{value:null},envMapRotation:{value:new Dt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Dt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Dt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Dt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Dt},normalScale:{value:new St(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Dt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Dt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Dt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Dt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new cn(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new cn(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Dt},alphaTest:{value:0},uvTransform:{value:new Dt}},sprite:{diffuse:{value:new cn(16777215)},opacity:{value:1},center:{value:new St(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Dt},alphaMap:{value:null},alphaMapTransform:{value:new Dt},alphaTest:{value:0}}},aa={basic:{uniforms:ki([qe.common,qe.specularmap,qe.envmap,qe.aomap,qe.lightmap,qe.fog]),vertexShader:Ft.meshbasic_vert,fragmentShader:Ft.meshbasic_frag},lambert:{uniforms:ki([qe.common,qe.specularmap,qe.envmap,qe.aomap,qe.lightmap,qe.emissivemap,qe.bumpmap,qe.normalmap,qe.displacementmap,qe.fog,qe.lights,{emissive:{value:new cn(0)}}]),vertexShader:Ft.meshlambert_vert,fragmentShader:Ft.meshlambert_frag},phong:{uniforms:ki([qe.common,qe.specularmap,qe.envmap,qe.aomap,qe.lightmap,qe.emissivemap,qe.bumpmap,qe.normalmap,qe.displacementmap,qe.fog,qe.lights,{emissive:{value:new cn(0)},specular:{value:new cn(1118481)},shininess:{value:30}}]),vertexShader:Ft.meshphong_vert,fragmentShader:Ft.meshphong_frag},standard:{uniforms:ki([qe.common,qe.envmap,qe.aomap,qe.lightmap,qe.emissivemap,qe.bumpmap,qe.normalmap,qe.displacementmap,qe.roughnessmap,qe.metalnessmap,qe.fog,qe.lights,{emissive:{value:new cn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ft.meshphysical_vert,fragmentShader:Ft.meshphysical_frag},toon:{uniforms:ki([qe.common,qe.aomap,qe.lightmap,qe.emissivemap,qe.bumpmap,qe.normalmap,qe.displacementmap,qe.gradientmap,qe.fog,qe.lights,{emissive:{value:new cn(0)}}]),vertexShader:Ft.meshtoon_vert,fragmentShader:Ft.meshtoon_frag},matcap:{uniforms:ki([qe.common,qe.bumpmap,qe.normalmap,qe.displacementmap,qe.fog,{matcap:{value:null}}]),vertexShader:Ft.meshmatcap_vert,fragmentShader:Ft.meshmatcap_frag},points:{uniforms:ki([qe.points,qe.fog]),vertexShader:Ft.points_vert,fragmentShader:Ft.points_frag},dashed:{uniforms:ki([qe.common,qe.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ft.linedashed_vert,fragmentShader:Ft.linedashed_frag},depth:{uniforms:ki([qe.common,qe.displacementmap]),vertexShader:Ft.depth_vert,fragmentShader:Ft.depth_frag},normal:{uniforms:ki([qe.common,qe.bumpmap,qe.normalmap,qe.displacementmap,{opacity:{value:1}}]),vertexShader:Ft.meshnormal_vert,fragmentShader:Ft.meshnormal_frag},sprite:{uniforms:ki([qe.sprite,qe.fog]),vertexShader:Ft.sprite_vert,fragmentShader:Ft.sprite_frag},background:{uniforms:{uvTransform:{value:new Dt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ft.background_vert,fragmentShader:Ft.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Dt}},vertexShader:Ft.backgroundCube_vert,fragmentShader:Ft.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ft.cube_vert,fragmentShader:Ft.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ft.equirect_vert,fragmentShader:Ft.equirect_frag},distanceRGBA:{uniforms:ki([qe.common,qe.displacementmap,{referencePosition:{value:new xe},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ft.distanceRGBA_vert,fragmentShader:Ft.distanceRGBA_frag},shadow:{uniforms:ki([qe.lights,qe.fog,{color:{value:new cn(0)},opacity:{value:1}}]),vertexShader:Ft.shadow_vert,fragmentShader:Ft.shadow_frag}};aa.physical={uniforms:ki([aa.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Dt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Dt},clearcoatNormalScale:{value:new St(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Dt},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Dt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Dt},sheen:{value:0},sheenColor:{value:new cn(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Dt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Dt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Dt},transmissionSamplerSize:{value:new St},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Dt},attenuationDistance:{value:0},attenuationColor:{value:new cn(0)},specularColor:{value:new cn(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Dt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Dt},anisotropyVector:{value:new St},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Dt}}]),vertexShader:Ft.meshphysical_vert,fragmentShader:Ft.meshphysical_frag};const Qg={r:0,b:0,g:0},ou=new Tc,w6=new ar;function T6(n,e,t,r,i,s,o){const a=new cn(0);let c=s===!0?0:1,l,u,h=null,p=0,m=null;function g(S){let w=S.isScene===!0?S.background:null;return w&&w.isTexture&&(w=(S.backgroundBlurriness>0?t:e).get(w)),w}function v(S){let w=!1;const T=g(S);T===null?_(a,c):T&&T.isColor&&(_(T,1),w=!0);const k=n.xr.getEnvironmentBlendMode();k==="additive"?r.buffers.color.setClear(0,0,0,1,o):k==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(n.autoClear||w)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function y(S,w){const T=g(w);T&&(T.isCubeTexture||T.mapping===gv)?(u===void 0&&(u=new wo(new Hp(1,1,1),new Vi({name:"BackgroundCubeMaterial",uniforms:Mf(aa.backgroundCube.uniforms),vertexShader:aa.backgroundCube.vertexShader,fragmentShader:aa.backgroundCube.fragmentShader,side:ni,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(k,R,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),ou.copy(w.backgroundRotation),ou.x*=-1,ou.y*=-1,ou.z*=-1,T.isCubeTexture&&T.isRenderTargetTexture===!1&&(ou.y*=-1,ou.z*=-1),u.material.uniforms.envMap.value=T,u.material.uniforms.flipEnvMap.value=T.isCubeTexture&&T.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=w.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=w.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(w6.makeRotationFromEuler(ou)),u.material.toneMapped=hn.getTransfer(T.colorSpace)!==bn,(h!==T||p!==T.version||m!==n.toneMapping)&&(u.material.needsUpdate=!0,h=T,p=T.version,m=n.toneMapping),u.layers.enableAll(),S.unshift(u,u.geometry,u.material,0,0,null)):T&&T.isTexture&&(l===void 0&&(l=new wo(new Gp(2,2),new Vi({name:"BackgroundMaterial",uniforms:Mf(aa.background.uniforms),vertexShader:aa.background.vertexShader,fragmentShader:aa.background.fragmentShader,side:wc,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=T,l.material.uniforms.backgroundIntensity.value=w.backgroundIntensity,l.material.toneMapped=hn.getTransfer(T.colorSpace)!==bn,T.matrixAutoUpdate===!0&&T.updateMatrix(),l.material.uniforms.uvTransform.value.copy(T.matrix),(h!==T||p!==T.version||m!==n.toneMapping)&&(l.material.needsUpdate=!0,h=T,p=T.version,m=n.toneMapping),l.layers.enableAll(),S.unshift(l,l.geometry,l.material,0,0,null))}function _(S,w){S.getRGB(Qg,jN(n)),r.buffers.color.setClear(Qg.r,Qg.g,Qg.b,w,o)}return{getClearColor:function(){return a},setClearColor:function(S,w=1){a.set(S),c=w,_(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(S){c=S,_(a,c)},render:v,addToRenderList:y}}function b6(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),r={},i=p(null);let s=i,o=!1;function a(N,U,L,P,b){let B=!1;const W=h(P,L,U);s!==W&&(s=W,l(s.object)),B=m(N,P,L,b),B&&g(N,P,L,b),b!==null&&e.update(b,n.ELEMENT_ARRAY_BUFFER),(B||o)&&(o=!1,T(N,U,L,P),b!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(b).buffer))}function c(){return n.createVertexArray()}function l(N){return n.bindVertexArray(N)}function u(N){return n.deleteVertexArray(N)}function h(N,U,L){const P=L.wireframe===!0;let b=r[N.id];b===void 0&&(b={},r[N.id]=b);let B=b[U.id];B===void 0&&(B={},b[U.id]=B);let W=B[P];return W===void 0&&(W=p(c()),B[P]=W),W}function p(N){const U=[],L=[],P=[];for(let b=0;b=0){const Z=b[G];let X=B[G];if(X===void 0&&(G==="instanceMatrix"&&N.instanceMatrix&&(X=N.instanceMatrix),G==="instanceColor"&&N.instanceColor&&(X=N.instanceColor)),Z===void 0||Z.attribute!==X||X&&Z.data!==X.data)return!0;W++}return s.attributesNum!==W||s.index!==P}function g(N,U,L,P){const b={},B=U.attributes;let W=0;const V=L.getAttributes();for(const G in V)if(V[G].location>=0){let Z=B[G];Z===void 0&&(G==="instanceMatrix"&&N.instanceMatrix&&(Z=N.instanceMatrix),G==="instanceColor"&&N.instanceColor&&(Z=N.instanceColor));const X={};X.attribute=Z,Z&&Z.data&&(X.data=Z.data),b[G]=X,W++}s.attributes=b,s.attributesNum=W,s.index=P}function v(){const N=s.newAttributes;for(let U=0,L=N.length;U=0){let $=b[V];if($===void 0&&(V==="instanceMatrix"&&N.instanceMatrix&&($=N.instanceMatrix),V==="instanceColor"&&N.instanceColor&&($=N.instanceColor)),$!==void 0){const Z=$.normalized,X=$.itemSize,Y=e.get($);if(Y===void 0)continue;const ve=Y.buffer,ne=Y.type,ie=Y.bytesPerElement,be=ne===n.INT||ne===n.UNSIGNED_INT||$.gpuType===$w;if($.isInterleavedBufferAttribute){const Ce=$.data,Ee=Ce.stride,Le=$.offset;if(Ce.isInstancedInterleavedBuffer){for(let ze=0;ze0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";C="mediump"}return C==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const u=c(l);u!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",u,"instead."),l=u);const h=t.logarithmicDepthBuffer===!0,p=t.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),m=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),g=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=n.getParameter(n.MAX_TEXTURE_SIZE),y=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),_=n.getParameter(n.MAX_VERTEX_ATTRIBS),S=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),w=n.getParameter(n.MAX_VARYING_VECTORS),T=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),k=g>0,R=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:h,reverseDepthBuffer:p,maxTextures:m,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:y,maxAttributes:_,maxVertexUniforms:S,maxVaryings:w,maxFragmentUniforms:T,vertexTextures:k,maxSamples:R}}function C6(n){const e=this;let t=null,r=0,i=!1,s=!1;const o=new yo,a=new Dt,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(h,p){const m=h.length!==0||p||r!==0||i;return i=p,r=h.length,m},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,p){t=u(h,p,0)},this.setState=function(h,p,m){const g=h.clippingPlanes,v=h.clipIntersection,y=h.clipShadows,_=n.get(h);if(!i||g===null||g.length===0||s&&!y)s?u(null):l();else{const S=s?0:r,w=S*4;let T=_.clippingState||null;c.value=T,T=u(g,p,w,m);for(let k=0;k!==w;++k)T[k]=t[k];_.clippingState=T,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=S}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function u(h,p,m,g){const v=h!==null?h.length:0;let y=null;if(v!==0){if(y=c.value,g!==!0||y===null){const _=m+v*4,S=p.matrixWorldInverse;a.getNormalMatrix(S),(y===null||y.length<_)&&(y=new Float32Array(_));for(let w=0,T=m;w!==v;++w,T+=4)o.copy(h[w]).applyMatrix4(S,a),o.normal.toArray(y,T),y[T+3]=o.constant}c.value=y,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,y}}function R6(n){let e=new WeakMap;function t(o,a){return a===L1?o.mapping=bf:a===P1&&(o.mapping=Af),o}function r(o){if(o&&o.isTexture){const a=o.mapping;if(a===L1||a===P1)if(e.has(o)){const c=e.get(o).texture;return t(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const l=new z5(c.height);return l.fromEquirectangularTexture(n,o),e.set(o,l),o.addEventListener("dispose",i),t(l.texture,o.mapping)}else return null}}return o}function i(o){const a=o.target;a.removeEventListener("dispose",i);const c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}class Sv extends xv{constructor(e=-1,t=1,r=1,i=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=r,this.bottom=i,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,r,i,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=r-e,o=r+e,a=i+t,c=i-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=l*this.view.offsetX,o=s+l*this.view.width,a-=u*this.view.offsetY,c=a-u*this.view.height}this.projectionMatrix.makeOrthographic(s,o,a,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const tf=4,$C=[.125,.215,.35,.446,.526,.582],Su=20,gS=new Sv,qC=new cn;let _S=null,vS=0,yS=0,xS=!1;const gu=(1+Math.sqrt(5))/2,Fh=1/gu,XC=[new xe(-gu,Fh,0),new xe(gu,Fh,0),new xe(-Fh,0,gu),new xe(Fh,0,gu),new xe(0,gu,-Fh),new xe(0,gu,Fh),new xe(-1,1,-1),new xe(1,1,-1),new xe(-1,1,1),new xe(1,1,1)];class KC{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,r=.1,i=100){_S=this._renderer.getRenderTarget(),vS=this._renderer.getActiveCubeFace(),yS=this._renderer.getActiveMipmapLevel(),xS=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,r,i,s),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=QC(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=ZC(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?w:0,w,w),u.setRenderTarget(i),v&&u.render(g,a),u.render(e,a)}g.geometry.dispose(),g.material.dispose(),u.toneMapping=p,u.autoClear=h,e.background=y}_textureToCubeUV(e,t){const r=this._renderer,i=e.mapping===bf||e.mapping===Af;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=QC()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=ZC());const s=i?this._cubemapMaterial:this._equirectMaterial,o=new wo(this._lodPlanes[0],s),a=s.uniforms;a.envMap.value=e;const c=this._cubeSize;Jg(t,0,0,3*c,2*c),r.setRenderTarget(t),r.render(o,gS)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let s=1;sSu&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${Su}`);const _=[];let S=0;for(let C=0;Cw-tf?i-w+tf:0),R=4*(this._cubeSize-T);Jg(t,k,R,3*T,2*T),c.setRenderTarget(t),c.render(h,gS)}}function k6(n){const e=[],t=[],r=[];let i=n;const s=n-tf+1+$C.length;for(let o=0;on-tf?c=$C[o-n+tf-1]:o===0&&(c=0),r.push(c);const l=1/(a-2),u=-l,h=1+l,p=[u,u,h,u,h,h,u,u,h,h,u,h],m=6,g=6,v=3,y=2,_=1,S=new Float32Array(v*g*m),w=new Float32Array(y*g*m),T=new Float32Array(_*g*m);for(let R=0;R2?0:-1,M=[C,O,0,C+2/3,O,0,C+2/3,O+1,0,C,O,0,C+2/3,O+1,0,C,O+1,0];S.set(M,v*g*R),w.set(p,y*g*R);const N=[R,R,R,R,R,R];T.set(N,_*g*R)}const k=new Do;k.setAttribute("position",new Qn(S,v)),k.setAttribute("uv",new Qn(w,y)),k.setAttribute("faceIndex",new Qn(T,_)),e.push(k),i>tf&&i--}return{lodPlanes:e,sizeLods:t,sigmas:r}}function YC(n,e,t){const r=new Ls(n,e,t);return r.texture.mapping=gv,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function Jg(n,e,t,r,i){n.viewport.set(e,t,r,i),n.scissor.set(e,t,r,i)}function I6(n,e,t){const r=new Float32Array(Su),i=new xe(0,1,0);return new Vi({name:"SphericalGaussianBlur",defines:{n:Su,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:eT(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - uniform int samples; - uniform float weights[ n ]; - uniform bool latitudinal; - uniform float dTheta; - uniform float mipInt; - uniform vec3 poleAxis; - - #define ENVMAP_TYPE_CUBE_UV - #include - - vec3 getSample( float theta, vec3 axis ) { - - float cosTheta = cos( theta ); - // Rodrigues' axis-angle rotation - vec3 sampleDirection = vOutputDirection * cosTheta - + cross( axis, vOutputDirection ) * sin( theta ) - + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); - - return bilinearCubeUV( envMap, sampleDirection, mipInt ); - - } - - void main() { - - vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); - - if ( all( equal( axis, vec3( 0.0 ) ) ) ) { - - axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); - - } - - axis = normalize( axis ); - - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); - - for ( int i = 1; i < n; i++ ) { - - if ( i >= samples ) { - - break; - - } - - float theta = dTheta * float( i ); - gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); - gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); - - } - - } - `,blending:Ao,depthTest:!1,depthWrite:!1})}function ZC(){return new Vi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:eT(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - - #include - - void main() { - - vec3 outputDirection = normalize( vOutputDirection ); - vec2 uv = equirectUv( outputDirection ); - - gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); - - } - `,blending:Ao,depthTest:!1,depthWrite:!1})}function QC(){return new Vi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:eT(),fragmentShader:` - - precision mediump float; - precision mediump int; - - uniform float flipEnvMap; - - varying vec3 vOutputDirection; - - uniform samplerCube envMap; - - void main() { - - gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); - - } - `,blending:Ao,depthTest:!1,depthWrite:!1})}function eT(){return` - - precision mediump float; - precision mediump int; - - attribute float faceIndex; - - varying vec3 vOutputDirection; - - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { - - uv = 2.0 * uv - 1.0; - - vec3 direction = vec3( uv, 1.0 ); - - if ( face == 0.0 ) { - - direction = direction.zyx; // ( 1, v, u ) pos x - - } else if ( face == 1.0 ) { - - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y - - } else if ( face == 2.0 ) { - - direction.x *= -1.0; // ( -u, v, 1 ) pos z - - } else if ( face == 3.0 ) { - - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x - - } else if ( face == 4.0 ) { - - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y - - } else if ( face == 5.0 ) { - - direction.z *= -1.0; // ( u, v, -1 ) neg z - - } - - return direction; - - } - - void main() { - - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); - - } - `}function N6(n){let e=new WeakMap,t=null;function r(a){if(a&&a.isTexture){const c=a.mapping,l=c===L1||c===P1,u=c===bf||c===Af;if(l||u){let h=e.get(a);const p=h!==void 0?h.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==p)return t===null&&(t=new KC(n)),h=l?t.fromEquirectangular(a,h):t.fromCubemap(a,h),h.texture.pmremVersion=a.pmremVersion,e.set(a,h),h.texture;if(h!==void 0)return h.texture;{const m=a.image;return l&&m&&m.height>0||u&&m&&i(m)?(t===null&&(t=new KC(n)),h=l?t.fromEquirectangular(a):t.fromCubemap(a),h.texture.pmremVersion=a.pmremVersion,e.set(a,h),a.addEventListener("dispose",s),h.texture):null}}}return a}function i(a){let c=0;const l=6;for(let u=0;ue.maxTextureSize&&(R=Math.ceil(k/e.maxTextureSize),k=e.maxTextureSize);const C=new Float32Array(k*R*4*h),O=new VN(C,k,R,h);O.type=da,O.needsUpdate=!0;const M=T*4;for(let U=0;U0)return n;const i=e*t;let s=eR[i];if(s===void 0&&(s=new Float32Array(i),eR[i]=s),e!==0){r.toArray(s,0);for(let o=1,a=0;o!==e;++o)a+=t,n[o].toArray(s,a)}return s}function zr(n,e){if(n.length!==e.length)return!1;for(let t=0,r=n.length;t":" "} ${a}: ${t[o]}`)}return r.join(` -`)}const aR=new Dt;function NV(n){hn._getMatrix(aR,hn.workingColorSpace,n);const e=`mat3( ${aR.elements.map(t=>t.toFixed(4))} )`;switch(hn.getTransfer(n)){case vv:return[e,"LinearTransferOETF"];case bn:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function cR(n,e,t){const r=n.getShaderParameter(e,n.COMPILE_STATUS),i=n.getShaderInfoLog(e).trim();if(r&&i==="")return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const o=parseInt(s[1]);return t.toUpperCase()+` - -`+i+` - -`+IV(n.getShaderSource(e),o)}else return i}function OV(n,e){const t=NV(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` -`)}function LV(n,e){let t;switch(e){case UB:t="Linear";break;case FB:t="Reinhard";break;case BB:t="Cineon";break;case bN:t="ACESFilmic";break;case VB:t="AgX";break;case HB:t="Neutral";break;case zB:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const e0=new xe;function PV(){hn.getLuminanceCoefficients(e0);const n=e0.x.toFixed(4),e=e0.y.toFixed(4),t=e0.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` -`)}function DV(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter($d).join(` -`)}function UV(n){const e=[];for(const t in n){const r=n[t];r!==!1&&e.push("#define "+t+" "+r)}return e.join(` -`)}function FV(n,e){const t={},r=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function uE(n){return n.replace(BV,VV)}const zV=new Map;function VV(n,e){let t=Ft[e];if(t===void 0){const r=zV.get(e);if(r!==void 0)t=Ft[r],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return uE(t)}const HV=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function hR(n){return n.replace(HV,GV)}function GV(n,e,t,r){let i="";for(let s=parseInt(e);s0&&(y+=` -`),_=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g].filter($d).join(` -`),_.length>0&&(_+=` -`)):(y=[fR(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` -`].filter($d).join(` -`),_=[fR(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+u:"",t.envMap?"#define "+h:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==ma?"#define TONE_MAPPING":"",t.toneMapping!==ma?Ft.tonemapping_pars_fragment:"",t.toneMapping!==ma?LV("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Ft.colorspace_pars_fragment,OV("linearToOutputTexel",t.outputColorSpace),PV(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` -`].filter($d).join(` -`)),o=uE(o),o=lR(o,t),o=uR(o,t),a=uE(a),a=lR(a,t),a=uR(a,t),o=hR(o),a=hR(a),t.isRawShaderMaterial!==!0&&(S=`#version 300 es -`,y=[m,"#define attribute in","#define varying out","#define texture2D texture"].join(` -`)+` -`+y,_=["#define varying in",t.glslVersion===TC?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===TC?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` -`)+` -`+_);const w=S+y+o,T=S+_+a,k=oR(i,i.VERTEX_SHADER,w),R=oR(i,i.FRAGMENT_SHADER,T);i.attachShader(v,k),i.attachShader(v,R),t.index0AttributeName!==void 0?i.bindAttribLocation(v,0,t.index0AttributeName):t.morphTargets===!0&&i.bindAttribLocation(v,0,"position"),i.linkProgram(v);function C(U){if(n.debug.checkShaderErrors){const L=i.getProgramInfoLog(v).trim(),P=i.getShaderInfoLog(k).trim(),b=i.getShaderInfoLog(R).trim();let B=!0,W=!0;if(i.getProgramParameter(v,i.LINK_STATUS)===!1)if(B=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(i,v,k,R);else{const V=cR(i,k,"vertex"),G=cR(i,R,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(v,i.VALIDATE_STATUS)+` - -Material Name: `+U.name+` -Material Type: `+U.type+` - -Program Info Log: `+L+` -`+V+` -`+G)}else L!==""?console.warn("THREE.WebGLProgram: Program Info Log:",L):(P===""||b==="")&&(W=!1);W&&(U.diagnostics={runnable:B,programLog:L,vertexShader:{log:P,prefix:y},fragmentShader:{log:b,prefix:_}})}i.deleteShader(k),i.deleteShader(R),O=new G0(i,v),M=FV(i,v)}let O;this.getUniforms=function(){return O===void 0&&C(this),O};let M;this.getAttributes=function(){return M===void 0&&C(this),M};let N=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return N===!1&&(N=i.getProgramParameter(v,RV)),N},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=kV++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=k,this.fragmentShader=R,this}let YV=0;class ZV{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(t),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const r of t)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let r=t.get(e);return r===void 0&&(r=new Set,t.set(e,r)),r}_getShaderStage(e){const t=this.shaderCache;let r=t.get(e);return r===void 0&&(r=new QV(e),t.set(e,r)),r}}class QV{constructor(e){this.id=YV++,this.code=e,this.usedTimes=0}}function JV(n,e,t,r,i,s,o){const a=new pf,c=new ZV,l=new Set,u=[],h=i.logarithmicDepthBuffer,p=i.vertexTextures;let m=i.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(M){return l.add(M),M===0?"uv":`uv${M}`}function y(M,N,U,L,P){const b=L.fog,B=P.geometry,W=M.isMeshStandardMaterial?L.environment:null,V=(M.isMeshStandardMaterial?t:e).get(M.envMap||W),G=V&&V.mapping===gv?V.image.height:null,$=g[M.type];M.precision!==null&&(m=i.getMaxPrecision(M.precision),m!==M.precision&&console.warn("THREE.WebGLProgram.getParameters:",M.precision,"not supported, using",m,"instead."));const Z=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,X=Z!==void 0?Z.length:0;let Y=0;B.morphAttributes.position!==void 0&&(Y=1),B.morphAttributes.normal!==void 0&&(Y=2),B.morphAttributes.color!==void 0&&(Y=3);let ve,ne,ie,be;if($){const dn=aa[$];ve=dn.vertexShader,ne=dn.fragmentShader}else ve=M.vertexShader,ne=M.fragmentShader,c.update(M),ie=c.getVertexShaderID(M),be=c.getFragmentShaderID(M);const Ce=n.getRenderTarget(),Ee=n.state.buffers.depth.getReversed(),Le=P.isInstancedMesh===!0,ze=P.isBatchedMesh===!0,Ge=!!M.map,rt=!!M.matcap,ft=!!V,A=!!M.aoMap,J=!!M.lightMap,re=!!M.bumpMap,j=!!M.normalMap,H=!!M.displacementMap,te=!!M.emissiveMap,oe=!!M.metalnessMap,z=!!M.roughnessMap,D=M.anisotropy>0,ee=M.clearcoat>0,he=M.dispersion>0,ce=M.iridescence>0,ge=M.sheen>0,Be=M.transmission>0,Oe=D&&!!M.anisotropyMap,He=ee&&!!M.clearcoatMap,Lt=ee&&!!M.clearcoatNormalMap,Pe=ee&&!!M.clearcoatRoughnessMap,tt=ce&&!!M.iridescenceMap,Je=ce&&!!M.iridescenceThicknessMap,yt=ge&&!!M.sheenColorMap,nt=ge&&!!M.sheenRoughnessMap,Ct=!!M.specularMap,Rt=!!M.specularColorMap,Sn=!!M.specularIntensityMap,le=Be&&!!M.transmissionMap,je=Be&&!!M.thicknessMap,Me=!!M.gradientMap,Ie=!!M.alphaMap,$e=M.alphaTest>0,Ze=!!M.alphaHash,kt=!!M.extensions;let Gn=ma;M.toneMapped&&(Ce===null||Ce.isXRRenderTarget===!0)&&(Gn=n.toneMapping);const Rr={shaderID:$,shaderType:M.type,shaderName:M.name,vertexShader:ve,fragmentShader:ne,defines:M.defines,customVertexShaderID:ie,customFragmentShaderID:be,isRawShaderMaterial:M.isRawShaderMaterial===!0,glslVersion:M.glslVersion,precision:m,batching:ze,batchingColor:ze&&P._colorsTexture!==null,instancing:Le,instancingColor:Le&&P.instanceColor!==null,instancingMorph:Le&&P.morphTexture!==null,supportsVertexTextures:p,outputColorSpace:Ce===null?n.outputColorSpace:Ce.isXRRenderTarget===!0?Ce.texture.colorSpace:Fl,alphaToCoverage:!!M.alphaToCoverage,map:Ge,matcap:rt,envMap:ft,envMapMode:ft&&V.mapping,envMapCubeUVHeight:G,aoMap:A,lightMap:J,bumpMap:re,normalMap:j,displacementMap:p&&H,emissiveMap:te,normalMapObjectSpace:j&&M.normalMapType===jB,normalMapTangentSpace:j&&M.normalMapType===UN,metalnessMap:oe,roughnessMap:z,anisotropy:D,anisotropyMap:Oe,clearcoat:ee,clearcoatMap:He,clearcoatNormalMap:Lt,clearcoatRoughnessMap:Pe,dispersion:he,iridescence:ce,iridescenceMap:tt,iridescenceThicknessMap:Je,sheen:ge,sheenColorMap:yt,sheenRoughnessMap:nt,specularMap:Ct,specularColorMap:Rt,specularIntensityMap:Sn,transmission:Be,transmissionMap:le,thicknessMap:je,gradientMap:Me,opaque:M.transparent===!1&&M.blending===hf&&M.alphaToCoverage===!1,alphaMap:Ie,alphaTest:$e,alphaHash:Ze,combine:M.combine,mapUv:Ge&&v(M.map.channel),aoMapUv:A&&v(M.aoMap.channel),lightMapUv:J&&v(M.lightMap.channel),bumpMapUv:re&&v(M.bumpMap.channel),normalMapUv:j&&v(M.normalMap.channel),displacementMapUv:H&&v(M.displacementMap.channel),emissiveMapUv:te&&v(M.emissiveMap.channel),metalnessMapUv:oe&&v(M.metalnessMap.channel),roughnessMapUv:z&&v(M.roughnessMap.channel),anisotropyMapUv:Oe&&v(M.anisotropyMap.channel),clearcoatMapUv:He&&v(M.clearcoatMap.channel),clearcoatNormalMapUv:Lt&&v(M.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Pe&&v(M.clearcoatRoughnessMap.channel),iridescenceMapUv:tt&&v(M.iridescenceMap.channel),iridescenceThicknessMapUv:Je&&v(M.iridescenceThicknessMap.channel),sheenColorMapUv:yt&&v(M.sheenColorMap.channel),sheenRoughnessMapUv:nt&&v(M.sheenRoughnessMap.channel),specularMapUv:Ct&&v(M.specularMap.channel),specularColorMapUv:Rt&&v(M.specularColorMap.channel),specularIntensityMapUv:Sn&&v(M.specularIntensityMap.channel),transmissionMapUv:le&&v(M.transmissionMap.channel),thicknessMapUv:je&&v(M.thicknessMap.channel),alphaMapUv:Ie&&v(M.alphaMap.channel),vertexTangents:!!B.attributes.tangent&&(j||D),vertexColors:M.vertexColors,vertexAlphas:M.vertexColors===!0&&!!B.attributes.color&&B.attributes.color.itemSize===4,pointsUvs:P.isPoints===!0&&!!B.attributes.uv&&(Ge||Ie),fog:!!b,useFog:M.fog===!0,fogExp2:!!b&&b.isFogExp2,flatShading:M.flatShading===!0,sizeAttenuation:M.sizeAttenuation===!0,logarithmicDepthBuffer:h,reverseDepthBuffer:Ee,skinning:P.isSkinnedMesh===!0,morphTargets:B.morphAttributes.position!==void 0,morphNormals:B.morphAttributes.normal!==void 0,morphColors:B.morphAttributes.color!==void 0,morphTargetsCount:X,morphTextureStride:Y,numDirLights:N.directional.length,numPointLights:N.point.length,numSpotLights:N.spot.length,numSpotLightMaps:N.spotLightMap.length,numRectAreaLights:N.rectArea.length,numHemiLights:N.hemi.length,numDirLightShadows:N.directionalShadowMap.length,numPointLightShadows:N.pointShadowMap.length,numSpotLightShadows:N.spotShadowMap.length,numSpotLightShadowsWithMaps:N.numSpotLightShadowsWithMaps,numLightProbes:N.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:M.dithering,shadowMapEnabled:n.shadowMap.enabled&&U.length>0,shadowMapType:n.shadowMap.type,toneMapping:Gn,decodeVideoTexture:Ge&&M.map.isVideoTexture===!0&&hn.getTransfer(M.map.colorSpace)===bn,decodeVideoTextureEmissive:te&&M.emissiveMap.isVideoTexture===!0&&hn.getTransfer(M.emissiveMap.colorSpace)===bn,premultipliedAlpha:M.premultipliedAlpha,doubleSided:M.side===As,flipSided:M.side===ni,useDepthPacking:M.depthPacking>=0,depthPacking:M.depthPacking||0,index0AttributeName:M.index0AttributeName,extensionClipCullDistance:kt&&M.extensions.clipCullDistance===!0&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(kt&&M.extensions.multiDraw===!0||ze)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:M.customProgramCacheKey()};return Rr.vertexUv1s=l.has(1),Rr.vertexUv2s=l.has(2),Rr.vertexUv3s=l.has(3),l.clear(),Rr}function _(M){const N=[];if(M.shaderID?N.push(M.shaderID):(N.push(M.customVertexShaderID),N.push(M.customFragmentShaderID)),M.defines!==void 0)for(const U in M.defines)N.push(U),N.push(M.defines[U]);return M.isRawShaderMaterial===!1&&(S(N,M),w(N,M),N.push(n.outputColorSpace)),N.push(M.customProgramCacheKey),N.join()}function S(M,N){M.push(N.precision),M.push(N.outputColorSpace),M.push(N.envMapMode),M.push(N.envMapCubeUVHeight),M.push(N.mapUv),M.push(N.alphaMapUv),M.push(N.lightMapUv),M.push(N.aoMapUv),M.push(N.bumpMapUv),M.push(N.normalMapUv),M.push(N.displacementMapUv),M.push(N.emissiveMapUv),M.push(N.metalnessMapUv),M.push(N.roughnessMapUv),M.push(N.anisotropyMapUv),M.push(N.clearcoatMapUv),M.push(N.clearcoatNormalMapUv),M.push(N.clearcoatRoughnessMapUv),M.push(N.iridescenceMapUv),M.push(N.iridescenceThicknessMapUv),M.push(N.sheenColorMapUv),M.push(N.sheenRoughnessMapUv),M.push(N.specularMapUv),M.push(N.specularColorMapUv),M.push(N.specularIntensityMapUv),M.push(N.transmissionMapUv),M.push(N.thicknessMapUv),M.push(N.combine),M.push(N.fogExp2),M.push(N.sizeAttenuation),M.push(N.morphTargetsCount),M.push(N.morphAttributeCount),M.push(N.numDirLights),M.push(N.numPointLights),M.push(N.numSpotLights),M.push(N.numSpotLightMaps),M.push(N.numHemiLights),M.push(N.numRectAreaLights),M.push(N.numDirLightShadows),M.push(N.numPointLightShadows),M.push(N.numSpotLightShadows),M.push(N.numSpotLightShadowsWithMaps),M.push(N.numLightProbes),M.push(N.shadowMapType),M.push(N.toneMapping),M.push(N.numClippingPlanes),M.push(N.numClipIntersection),M.push(N.depthPacking)}function w(M,N){a.disableAll(),N.supportsVertexTextures&&a.enable(0),N.instancing&&a.enable(1),N.instancingColor&&a.enable(2),N.instancingMorph&&a.enable(3),N.matcap&&a.enable(4),N.envMap&&a.enable(5),N.normalMapObjectSpace&&a.enable(6),N.normalMapTangentSpace&&a.enable(7),N.clearcoat&&a.enable(8),N.iridescence&&a.enable(9),N.alphaTest&&a.enable(10),N.vertexColors&&a.enable(11),N.vertexAlphas&&a.enable(12),N.vertexUv1s&&a.enable(13),N.vertexUv2s&&a.enable(14),N.vertexUv3s&&a.enable(15),N.vertexTangents&&a.enable(16),N.anisotropy&&a.enable(17),N.alphaHash&&a.enable(18),N.batching&&a.enable(19),N.dispersion&&a.enable(20),N.batchingColor&&a.enable(21),M.push(a.mask),a.disableAll(),N.fog&&a.enable(0),N.useFog&&a.enable(1),N.flatShading&&a.enable(2),N.logarithmicDepthBuffer&&a.enable(3),N.reverseDepthBuffer&&a.enable(4),N.skinning&&a.enable(5),N.morphTargets&&a.enable(6),N.morphNormals&&a.enable(7),N.morphColors&&a.enable(8),N.premultipliedAlpha&&a.enable(9),N.shadowMapEnabled&&a.enable(10),N.doubleSided&&a.enable(11),N.flipSided&&a.enable(12),N.useDepthPacking&&a.enable(13),N.dithering&&a.enable(14),N.transmission&&a.enable(15),N.sheen&&a.enable(16),N.opaque&&a.enable(17),N.pointsUvs&&a.enable(18),N.decodeVideoTexture&&a.enable(19),N.decodeVideoTextureEmissive&&a.enable(20),N.alphaToCoverage&&a.enable(21),M.push(a.mask)}function T(M){const N=g[M.type];let U;if(N){const L=aa[N];U=D5.clone(L.uniforms)}else U=M.uniforms;return U}function k(M,N){let U;for(let L=0,P=u.length;L0?r.push(_):m.transparent===!0?i.push(_):t.push(_)}function c(h,p,m,g,v,y){const _=o(h,p,m,g,v,y);m.transmission>0?r.unshift(_):m.transparent===!0?i.unshift(_):t.unshift(_)}function l(h,p){t.length>1&&t.sort(h||tH),r.length>1&&r.sort(p||dR),i.length>1&&i.sort(p||dR)}function u(){for(let h=e,p=n.length;h=s.length?(o=new pR,s.push(o)):o=s[i],o}function t(){n=new WeakMap}return{get:e,dispose:t}}function rH(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new xe,color:new cn};break;case"SpotLight":t={position:new xe,direction:new xe,color:new cn,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new xe,color:new cn,distance:0,decay:0};break;case"HemisphereLight":t={direction:new xe,skyColor:new cn,groundColor:new cn};break;case"RectAreaLight":t={color:new cn,position:new xe,halfWidth:new xe,halfHeight:new xe};break}return n[e.id]=t,t}}}function iH(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new St};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new St};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new St,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let sH=0;function oH(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function aH(n){const e=new rH,t=iH(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)r.probe.push(new xe);const i=new xe,s=new ar,o=new ar;function a(l){let u=0,h=0,p=0;for(let M=0;M<9;M++)r.probe[M].set(0,0,0);let m=0,g=0,v=0,y=0,_=0,S=0,w=0,T=0,k=0,R=0,C=0;l.sort(oH);for(let M=0,N=l.length;M0&&(n.has("OES_texture_float_linear")===!0?(r.rectAreaLTC1=qe.LTC_FLOAT_1,r.rectAreaLTC2=qe.LTC_FLOAT_2):(r.rectAreaLTC1=qe.LTC_HALF_1,r.rectAreaLTC2=qe.LTC_HALF_2)),r.ambient[0]=u,r.ambient[1]=h,r.ambient[2]=p;const O=r.hash;(O.directionalLength!==m||O.pointLength!==g||O.spotLength!==v||O.rectAreaLength!==y||O.hemiLength!==_||O.numDirectionalShadows!==S||O.numPointShadows!==w||O.numSpotShadows!==T||O.numSpotMaps!==k||O.numLightProbes!==C)&&(r.directional.length=m,r.spot.length=v,r.rectArea.length=y,r.point.length=g,r.hemi.length=_,r.directionalShadow.length=S,r.directionalShadowMap.length=S,r.pointShadow.length=w,r.pointShadowMap.length=w,r.spotShadow.length=T,r.spotShadowMap.length=T,r.directionalShadowMatrix.length=S,r.pointShadowMatrix.length=w,r.spotLightMatrix.length=T+k-R,r.spotLightMap.length=k,r.numSpotLightShadowsWithMaps=R,r.numLightProbes=C,O.directionalLength=m,O.pointLength=g,O.spotLength=v,O.rectAreaLength=y,O.hemiLength=_,O.numDirectionalShadows=S,O.numPointShadows=w,O.numSpotShadows=T,O.numSpotMaps=k,O.numLightProbes=C,r.version=sH++)}function c(l,u){let h=0,p=0,m=0,g=0,v=0;const y=u.matrixWorldInverse;for(let _=0,S=l.length;_=o.length?(a=new mR(n),o.push(a)):a=o[s],a}function r(){e=new WeakMap}return{get:t,dispose:r}}class lH extends Lc{static get type(){return"MeshDepthMaterial"}constructor(e){super(),this.isMeshDepthMaterial=!0,this.depthPacking=Yu,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class uH extends Lc{static get type(){return"MeshDistanceMaterial"}constructor(e){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const hH=`void main() { - gl_Position = vec4( position, 1.0 ); -}`,fH=`uniform sampler2D shadow_pass; -uniform vec2 resolution; -uniform float radius; -#include -void main() { - const float samples = float( VSM_SAMPLES ); - float mean = 0.0; - float squared_mean = 0.0; - float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); - float uvStart = samples <= 1.0 ? 0.0 : - 1.0; - for ( float i = 0.0; i < samples; i ++ ) { - float uvOffset = uvStart + i * uvStride; - #ifdef HORIZONTAL_PASS - vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); - mean += distribution.x; - squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; - #else - float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); - mean += depth; - squared_mean += depth * depth; - #endif - } - mean = mean / samples; - squared_mean = squared_mean / samples; - float std_dev = sqrt( squared_mean - mean * mean ); - gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function dH(n,e,t){let r=new qN;const i=new St,s=new St,o=new gr,a=new lH({depthPacking:WB}),c=new uH,l={},u=t.maxTextureSize,h={[wc]:ni,[ni]:wc,[As]:As},p=new Vi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new St},radius:{value:4}},vertexShader:hH,fragmentShader:fH}),m=p.clone();m.defines.HORIZONTAL_PASS=1;const g=new Do;g.setAttribute("position",new Qn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new wo(g,p),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=jw;let _=this.type;this.render=function(R,C,O){if(y.enabled===!1||y.autoUpdate===!1&&y.needsUpdate===!1||R.length===0)return;const M=n.getRenderTarget(),N=n.getActiveCubeFace(),U=n.getActiveMipmapLevel(),L=n.state;L.setBlending(Ao),L.buffers.color.setClear(1,1,1,1),L.buffers.depth.setTest(!0),L.setScissorTest(!1);const P=_!==sa&&this.type===sa,b=_===sa&&this.type!==sa;for(let B=0,W=R.length;Bu||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/$.x),i.x=s.x*$.x,G.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/$.y),i.y=s.y*$.y,G.mapSize.y=s.y)),G.map===null||P===!0||b===!0){const X=this.type!==sa?{minFilter:vr,magFilter:vr}:{};G.map!==null&&G.map.dispose(),G.map=new Ls(i.x,i.y,X),G.map.texture.name=V.name+".shadowMap",G.camera.updateProjectionMatrix()}n.setRenderTarget(G.map),n.clear();const Z=G.getViewportCount();for(let X=0;X0||C.map&&C.alphaTest>0){const L=N.uuid,P=C.uuid;let b=l[L];b===void 0&&(b={},l[L]=b);let B=b[P];B===void 0&&(B=N.clone(),b[P]=B,C.addEventListener("dispose",k)),N=B}if(N.visible=C.visible,N.wireframe=C.wireframe,M===sa?N.side=C.shadowSide!==null?C.shadowSide:C.side:N.side=C.shadowSide!==null?C.shadowSide:h[C.side],N.alphaMap=C.alphaMap,N.alphaTest=C.alphaTest,N.map=C.map,N.clipShadows=C.clipShadows,N.clippingPlanes=C.clippingPlanes,N.clipIntersection=C.clipIntersection,N.displacementMap=C.displacementMap,N.displacementScale=C.displacementScale,N.displacementBias=C.displacementBias,N.wireframeLinewidth=C.wireframeLinewidth,N.linewidth=C.linewidth,O.isPointLight===!0&&N.isMeshDistanceMaterial===!0){const L=n.properties.get(N);L.light=O}return N}function T(R,C,O,M,N){if(R.visible===!1)return;if(R.layers.test(C.layers)&&(R.isMesh||R.isLine||R.isPoints)&&(R.castShadow||R.receiveShadow&&N===sa)&&(!R.frustumCulled||r.intersectsObject(R))){R.modelViewMatrix.multiplyMatrices(O.matrixWorldInverse,R.matrixWorld);const P=e.update(R),b=R.material;if(Array.isArray(b)){const B=P.groups;for(let W=0,V=B.length;W=1):G.indexOf("OpenGL ES")!==-1&&(V=parseFloat(/^OpenGL ES (\d)/.exec(G)[1]),W=V>=2);let $=null,Z={};const X=n.getParameter(n.SCISSOR_BOX),Y=n.getParameter(n.VIEWPORT),ve=new gr().fromArray(X),ne=new gr().fromArray(Y);function ie(le,je,Me,Ie){const $e=new Uint8Array(4),Ze=n.createTexture();n.bindTexture(le,Ze),n.texParameteri(le,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(le,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let kt=0;kt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new St,u=new WeakMap;let h;const p=new WeakMap;let m=!1;try{m=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(z,D){return m?new OffscreenCanvas(z,D):pp("canvas")}function v(z,D,ee){let he=1;const ce=oe(z);if((ce.width>ee||ce.height>ee)&&(he=ee/Math.max(ce.width,ce.height)),he<1)if(typeof HTMLImageElement<"u"&&z instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&z instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&z instanceof ImageBitmap||typeof VideoFrame<"u"&&z instanceof VideoFrame){const ge=Math.floor(he*ce.width),Be=Math.floor(he*ce.height);h===void 0&&(h=g(ge,Be));const Oe=D?g(ge,Be):h;return Oe.width=ge,Oe.height=Be,Oe.getContext("2d").drawImage(z,0,0,ge,Be),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+ce.width+"x"+ce.height+") to ("+ge+"x"+Be+")."),Oe}else return"data"in z&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+ce.width+"x"+ce.height+")."),z;return z}function y(z){return z.generateMipmaps}function _(z){n.generateMipmap(z)}function S(z){return z.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:z.isWebGL3DRenderTarget?n.TEXTURE_3D:z.isWebGLArrayRenderTarget||z.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function w(z,D,ee,he,ce=!1){if(z!==null){if(n[z]!==void 0)return n[z];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+z+"'")}let ge=D;if(D===n.RED&&(ee===n.FLOAT&&(ge=n.R32F),ee===n.HALF_FLOAT&&(ge=n.R16F),ee===n.UNSIGNED_BYTE&&(ge=n.R8)),D===n.RED_INTEGER&&(ee===n.UNSIGNED_BYTE&&(ge=n.R8UI),ee===n.UNSIGNED_SHORT&&(ge=n.R16UI),ee===n.UNSIGNED_INT&&(ge=n.R32UI),ee===n.BYTE&&(ge=n.R8I),ee===n.SHORT&&(ge=n.R16I),ee===n.INT&&(ge=n.R32I)),D===n.RG&&(ee===n.FLOAT&&(ge=n.RG32F),ee===n.HALF_FLOAT&&(ge=n.RG16F),ee===n.UNSIGNED_BYTE&&(ge=n.RG8)),D===n.RG_INTEGER&&(ee===n.UNSIGNED_BYTE&&(ge=n.RG8UI),ee===n.UNSIGNED_SHORT&&(ge=n.RG16UI),ee===n.UNSIGNED_INT&&(ge=n.RG32UI),ee===n.BYTE&&(ge=n.RG8I),ee===n.SHORT&&(ge=n.RG16I),ee===n.INT&&(ge=n.RG32I)),D===n.RGB_INTEGER&&(ee===n.UNSIGNED_BYTE&&(ge=n.RGB8UI),ee===n.UNSIGNED_SHORT&&(ge=n.RGB16UI),ee===n.UNSIGNED_INT&&(ge=n.RGB32UI),ee===n.BYTE&&(ge=n.RGB8I),ee===n.SHORT&&(ge=n.RGB16I),ee===n.INT&&(ge=n.RGB32I)),D===n.RGBA_INTEGER&&(ee===n.UNSIGNED_BYTE&&(ge=n.RGBA8UI),ee===n.UNSIGNED_SHORT&&(ge=n.RGBA16UI),ee===n.UNSIGNED_INT&&(ge=n.RGBA32UI),ee===n.BYTE&&(ge=n.RGBA8I),ee===n.SHORT&&(ge=n.RGBA16I),ee===n.INT&&(ge=n.RGBA32I)),D===n.RGB&&ee===n.UNSIGNED_INT_5_9_9_9_REV&&(ge=n.RGB9_E5),D===n.RGBA){const Be=ce?vv:hn.getTransfer(he);ee===n.FLOAT&&(ge=n.RGBA32F),ee===n.HALF_FLOAT&&(ge=n.RGBA16F),ee===n.UNSIGNED_BYTE&&(ge=Be===bn?n.SRGB8_ALPHA8:n.RGBA8),ee===n.UNSIGNED_SHORT_4_4_4_4&&(ge=n.RGBA4),ee===n.UNSIGNED_SHORT_5_5_5_1&&(ge=n.RGB5_A1)}return(ge===n.R16F||ge===n.R32F||ge===n.RG16F||ge===n.RG32F||ge===n.RGBA16F||ge===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ge}function T(z,D){let ee;return z?D===null||D===bl||D===Pu?ee=n.DEPTH24_STENCIL8:D===da?ee=n.DEPTH32F_STENCIL8:D===fp&&(ee=n.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):D===null||D===bl||D===Pu?ee=n.DEPTH_COMPONENT24:D===da?ee=n.DEPTH_COMPONENT32F:D===fp&&(ee=n.DEPTH_COMPONENT16),ee}function k(z,D){return y(z)===!0||z.isFramebufferTexture&&z.minFilter!==vr&&z.minFilter!==ns?Math.log2(Math.max(D.width,D.height))+1:z.mipmaps!==void 0&&z.mipmaps.length>0?z.mipmaps.length:z.isCompressedTexture&&Array.isArray(z.image)?D.mipmaps.length:1}function R(z){const D=z.target;D.removeEventListener("dispose",R),O(D),D.isVideoTexture&&u.delete(D)}function C(z){const D=z.target;D.removeEventListener("dispose",C),N(D)}function O(z){const D=r.get(z);if(D.__webglInit===void 0)return;const ee=z.source,he=p.get(ee);if(he){const ce=he[D.__cacheKey];ce.usedTimes--,ce.usedTimes===0&&M(z),Object.keys(he).length===0&&p.delete(ee)}r.remove(z)}function M(z){const D=r.get(z);n.deleteTexture(D.__webglTexture);const ee=z.source,he=p.get(ee);delete he[D.__cacheKey],o.memory.textures--}function N(z){const D=r.get(z);if(z.depthTexture&&(z.depthTexture.dispose(),r.remove(z.depthTexture)),z.isWebGLCubeRenderTarget)for(let he=0;he<6;he++){if(Array.isArray(D.__webglFramebuffer[he]))for(let ce=0;ce=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+z+" texture units while this GPU supports only "+i.maxTextures),U+=1,z}function b(z){const D=[];return D.push(z.wrapS),D.push(z.wrapT),D.push(z.wrapR||0),D.push(z.magFilter),D.push(z.minFilter),D.push(z.anisotropy),D.push(z.internalFormat),D.push(z.format),D.push(z.type),D.push(z.generateMipmaps),D.push(z.premultiplyAlpha),D.push(z.flipY),D.push(z.unpackAlignment),D.push(z.colorSpace),D.join()}function B(z,D){const ee=r.get(z);if(z.isVideoTexture&&H(z),z.isRenderTargetTexture===!1&&z.version>0&&ee.__version!==z.version){const he=z.image;if(he===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(he.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{ne(ee,z,D);return}}t.bindTexture(n.TEXTURE_2D,ee.__webglTexture,n.TEXTURE0+D)}function W(z,D){const ee=r.get(z);if(z.version>0&&ee.__version!==z.version){ne(ee,z,D);return}t.bindTexture(n.TEXTURE_2D_ARRAY,ee.__webglTexture,n.TEXTURE0+D)}function V(z,D){const ee=r.get(z);if(z.version>0&&ee.__version!==z.version){ne(ee,z,D);return}t.bindTexture(n.TEXTURE_3D,ee.__webglTexture,n.TEXTURE0+D)}function G(z,D){const ee=r.get(z);if(z.version>0&&ee.__version!==z.version){ie(ee,z,D);return}t.bindTexture(n.TEXTURE_CUBE_MAP,ee.__webglTexture,n.TEXTURE0+D)}const $={[D1]:n.REPEAT,[wu]:n.CLAMP_TO_EDGE,[U1]:n.MIRRORED_REPEAT},Z={[vr]:n.NEAREST,[GB]:n.NEAREST_MIPMAP_NEAREST,[Lg]:n.NEAREST_MIPMAP_LINEAR,[ns]:n.LINEAR,[Kx]:n.LINEAR_MIPMAP_NEAREST,[Tu]:n.LINEAR_MIPMAP_LINEAR},X={[$B]:n.NEVER,[QB]:n.ALWAYS,[qB]:n.LESS,[FN]:n.LEQUAL,[XB]:n.EQUAL,[ZB]:n.GEQUAL,[KB]:n.GREATER,[YB]:n.NOTEQUAL};function Y(z,D){if(D.type===da&&e.has("OES_texture_float_linear")===!1&&(D.magFilter===ns||D.magFilter===Kx||D.magFilter===Lg||D.magFilter===Tu||D.minFilter===ns||D.minFilter===Kx||D.minFilter===Lg||D.minFilter===Tu)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(z,n.TEXTURE_WRAP_S,$[D.wrapS]),n.texParameteri(z,n.TEXTURE_WRAP_T,$[D.wrapT]),(z===n.TEXTURE_3D||z===n.TEXTURE_2D_ARRAY)&&n.texParameteri(z,n.TEXTURE_WRAP_R,$[D.wrapR]),n.texParameteri(z,n.TEXTURE_MAG_FILTER,Z[D.magFilter]),n.texParameteri(z,n.TEXTURE_MIN_FILTER,Z[D.minFilter]),D.compareFunction&&(n.texParameteri(z,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(z,n.TEXTURE_COMPARE_FUNC,X[D.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(D.magFilter===vr||D.minFilter!==Lg&&D.minFilter!==Tu||D.type===da&&e.has("OES_texture_float_linear")===!1)return;if(D.anisotropy>1||r.get(D).__currentAnisotropy){const ee=e.get("EXT_texture_filter_anisotropic");n.texParameterf(z,ee.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(D.anisotropy,i.getMaxAnisotropy())),r.get(D).__currentAnisotropy=D.anisotropy}}}function ve(z,D){let ee=!1;z.__webglInit===void 0&&(z.__webglInit=!0,D.addEventListener("dispose",R));const he=D.source;let ce=p.get(he);ce===void 0&&(ce={},p.set(he,ce));const ge=b(D);if(ge!==z.__cacheKey){ce[ge]===void 0&&(ce[ge]={texture:n.createTexture(),usedTimes:0},o.memory.textures++,ee=!0),ce[ge].usedTimes++;const Be=ce[z.__cacheKey];Be!==void 0&&(ce[z.__cacheKey].usedTimes--,Be.usedTimes===0&&M(D)),z.__cacheKey=ge,z.__webglTexture=ce[ge].texture}return ee}function ne(z,D,ee){let he=n.TEXTURE_2D;(D.isDataArrayTexture||D.isCompressedArrayTexture)&&(he=n.TEXTURE_2D_ARRAY),D.isData3DTexture&&(he=n.TEXTURE_3D);const ce=ve(z,D),ge=D.source;t.bindTexture(he,z.__webglTexture,n.TEXTURE0+ee);const Be=r.get(ge);if(ge.version!==Be.__version||ce===!0){t.activeTexture(n.TEXTURE0+ee);const Oe=hn.getPrimaries(hn.workingColorSpace),He=D.colorSpace===ua?null:hn.getPrimaries(D.colorSpace),Lt=D.colorSpace===ua||Oe===He?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,D.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,D.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,Lt);let Pe=v(D.image,!1,i.maxTextureSize);Pe=te(D,Pe);const tt=s.convert(D.format,D.colorSpace),Je=s.convert(D.type);let yt=w(D.internalFormat,tt,Je,D.colorSpace,D.isVideoTexture);Y(he,D);let nt;const Ct=D.mipmaps,Rt=D.isVideoTexture!==!0,Sn=Be.__version===void 0||ce===!0,le=ge.dataReady,je=k(D,Pe);if(D.isDepthTexture)yt=T(D.format===Du,D.type),Sn&&(Rt?t.texStorage2D(n.TEXTURE_2D,1,yt,Pe.width,Pe.height):t.texImage2D(n.TEXTURE_2D,0,yt,Pe.width,Pe.height,0,tt,Je,null));else if(D.isDataTexture)if(Ct.length>0){Rt&&Sn&&t.texStorage2D(n.TEXTURE_2D,je,yt,Ct[0].width,Ct[0].height);for(let Me=0,Ie=Ct.length;Me0){const $e=gR(nt.width,nt.height,D.format,D.type);for(const Ze of D.layerUpdates){const kt=nt.data.subarray(Ze*$e/nt.data.BYTES_PER_ELEMENT,(Ze+1)*$e/nt.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Me,0,0,Ze,nt.width,nt.height,1,tt,kt)}D.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Me,0,0,0,nt.width,nt.height,Pe.depth,tt,nt.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,Me,yt,nt.width,nt.height,Pe.depth,0,nt.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Rt?le&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,Me,0,0,0,nt.width,nt.height,Pe.depth,tt,Je,nt.data):t.texImage3D(n.TEXTURE_2D_ARRAY,Me,yt,nt.width,nt.height,Pe.depth,0,tt,Je,nt.data)}else{Rt&&Sn&&t.texStorage2D(n.TEXTURE_2D,je,yt,Ct[0].width,Ct[0].height);for(let Me=0,Ie=Ct.length;Me0){const Me=gR(Pe.width,Pe.height,D.format,D.type);for(const Ie of D.layerUpdates){const $e=Pe.data.subarray(Ie*Me/Pe.data.BYTES_PER_ELEMENT,(Ie+1)*Me/Pe.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,Ie,Pe.width,Pe.height,1,tt,Je,$e)}D.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,Pe.width,Pe.height,Pe.depth,tt,Je,Pe.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,yt,Pe.width,Pe.height,Pe.depth,0,tt,Je,Pe.data);else if(D.isData3DTexture)Rt?(Sn&&t.texStorage3D(n.TEXTURE_3D,je,yt,Pe.width,Pe.height,Pe.depth),le&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,Pe.width,Pe.height,Pe.depth,tt,Je,Pe.data)):t.texImage3D(n.TEXTURE_3D,0,yt,Pe.width,Pe.height,Pe.depth,0,tt,Je,Pe.data);else if(D.isFramebufferTexture){if(Sn)if(Rt)t.texStorage2D(n.TEXTURE_2D,je,yt,Pe.width,Pe.height);else{let Me=Pe.width,Ie=Pe.height;for(let $e=0;$e>=1,Ie>>=1}}else if(Ct.length>0){if(Rt&&Sn){const Me=oe(Ct[0]);t.texStorage2D(n.TEXTURE_2D,je,yt,Me.width,Me.height)}for(let Me=0,Ie=Ct.length;Me0&&je++;const Ie=oe(tt[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,je,Ct,Ie.width,Ie.height)}for(let Ie=0;Ie<6;Ie++)if(Pe){Rt?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,0,0,0,tt[Ie].width,tt[Ie].height,yt,nt,tt[Ie].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,0,Ct,tt[Ie].width,tt[Ie].height,0,yt,nt,tt[Ie].data);for(let $e=0;$e>ge),Je=Math.max(1,D.height>>ge);ce===n.TEXTURE_3D||ce===n.TEXTURE_2D_ARRAY?t.texImage3D(ce,ge,He,tt,Je,D.depth,0,Be,Oe,null):t.texImage2D(ce,ge,He,tt,Je,0,Be,Oe,null)}t.bindFramebuffer(n.FRAMEBUFFER,z),j(D)?a.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,he,ce,Pe.__webglTexture,0,re(D)):(ce===n.TEXTURE_2D||ce>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&ce<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,he,ce,Pe.__webglTexture,ge),t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ce(z,D,ee){if(n.bindRenderbuffer(n.RENDERBUFFER,z),D.depthBuffer){const he=D.depthTexture,ce=he&&he.isDepthTexture?he.type:null,ge=T(D.stencilBuffer,ce),Be=D.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Oe=re(D);j(D)?a.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Oe,ge,D.width,D.height):ee?n.renderbufferStorageMultisample(n.RENDERBUFFER,Oe,ge,D.width,D.height):n.renderbufferStorage(n.RENDERBUFFER,ge,D.width,D.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,Be,n.RENDERBUFFER,z)}else{const he=D.textures;for(let ce=0;ce{delete D.__boundDepthTexture,delete D.__depthDisposeCallback,he.removeEventListener("dispose",ce)};he.addEventListener("dispose",ce),D.__depthDisposeCallback=ce}D.__boundDepthTexture=he}if(z.depthTexture&&!D.__autoAllocateDepthBuffer){if(ee)throw new Error("target.depthTexture not supported in Cube render targets");Ee(D.__webglFramebuffer,z)}else if(ee){D.__webglDepthbuffer=[];for(let he=0;he<6;he++)if(t.bindFramebuffer(n.FRAMEBUFFER,D.__webglFramebuffer[he]),D.__webglDepthbuffer[he]===void 0)D.__webglDepthbuffer[he]=n.createRenderbuffer(),Ce(D.__webglDepthbuffer[he],z,!1);else{const ce=z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ge=D.__webglDepthbuffer[he];n.bindRenderbuffer(n.RENDERBUFFER,ge),n.framebufferRenderbuffer(n.FRAMEBUFFER,ce,n.RENDERBUFFER,ge)}}else if(t.bindFramebuffer(n.FRAMEBUFFER,D.__webglFramebuffer),D.__webglDepthbuffer===void 0)D.__webglDepthbuffer=n.createRenderbuffer(),Ce(D.__webglDepthbuffer,z,!1);else{const he=z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ce=D.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ce),n.framebufferRenderbuffer(n.FRAMEBUFFER,he,n.RENDERBUFFER,ce)}t.bindFramebuffer(n.FRAMEBUFFER,null)}function ze(z,D,ee){const he=r.get(z);D!==void 0&&be(he.__webglFramebuffer,z,z.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),ee!==void 0&&Le(z)}function Ge(z){const D=z.texture,ee=r.get(z),he=r.get(D);z.addEventListener("dispose",C);const ce=z.textures,ge=z.isWebGLCubeRenderTarget===!0,Be=ce.length>1;if(Be||(he.__webglTexture===void 0&&(he.__webglTexture=n.createTexture()),he.__version=D.version,o.memory.textures++),ge){ee.__webglFramebuffer=[];for(let Oe=0;Oe<6;Oe++)if(D.mipmaps&&D.mipmaps.length>0){ee.__webglFramebuffer[Oe]=[];for(let He=0;He0){ee.__webglFramebuffer=[];for(let Oe=0;Oe0&&j(z)===!1){ee.__webglMultisampledFramebuffer=n.createFramebuffer(),ee.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,ee.__webglMultisampledFramebuffer);for(let Oe=0;Oe0)for(let He=0;He0)for(let He=0;He0){if(j(z)===!1){const D=z.textures,ee=z.width,he=z.height;let ce=n.COLOR_BUFFER_BIT;const ge=z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Be=r.get(z),Oe=D.length>1;if(Oe)for(let He=0;He0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&D.__useRenderToTexture!==!1}function H(z){const D=o.render.frame;u.get(z)!==D&&(u.set(z,D),z.update())}function te(z,D){const ee=z.colorSpace,he=z.format,ce=z.type;return z.isCompressedTexture===!0||z.isVideoTexture===!0||ee!==Fl&&ee!==ua&&(hn.getTransfer(ee)===bn?(he!==Qs||ce!==Ei)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",ee)),D}function oe(z){return typeof HTMLImageElement<"u"&&z instanceof HTMLImageElement?(l.width=z.naturalWidth||z.width,l.height=z.naturalHeight||z.height):typeof VideoFrame<"u"&&z instanceof VideoFrame?(l.width=z.displayWidth,l.height=z.displayHeight):(l.width=z.width,l.height=z.height),l}this.allocateTextureUnit=P,this.resetTextureUnits=L,this.setTexture2D=B,this.setTexture2DArray=W,this.setTexture3D=V,this.setTextureCube=G,this.rebindTextures=ze,this.setupRenderTarget=Ge,this.updateRenderTargetMipmap=rt,this.updateMultisampleRenderTarget=J,this.setupDepthRenderbuffer=Le,this.setupFrameBufferTexture=be,this.useMultisampledRTT=j}function vH(n,e){function t(r,i=ua){let s;const o=hn.getTransfer(i);if(r===Ei)return n.UNSIGNED_BYTE;if(r===qw)return n.UNSIGNED_SHORT_4_4_4_4;if(r===Xw)return n.UNSIGNED_SHORT_5_5_5_1;if(r===RN)return n.UNSIGNED_INT_5_9_9_9_REV;if(r===MN)return n.BYTE;if(r===CN)return n.SHORT;if(r===fp)return n.UNSIGNED_SHORT;if(r===$w)return n.INT;if(r===bl)return n.UNSIGNED_INT;if(r===da)return n.FLOAT;if(r===Qf)return n.HALF_FLOAT;if(r===kN)return n.ALPHA;if(r===IN)return n.RGB;if(r===Qs)return n.RGBA;if(r===NN)return n.LUMINANCE;if(r===ON)return n.LUMINANCE_ALPHA;if(r===ff)return n.DEPTH_COMPONENT;if(r===Du)return n.DEPTH_STENCIL;if(r===LN)return n.RED;if(r===Kw)return n.RED_INTEGER;if(r===PN)return n.RG;if(r===Yw)return n.RG_INTEGER;if(r===_v)return n.RGBA_INTEGER;if(r===F0||r===B0||r===z0||r===V0)if(o===bn)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(r===F0)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===B0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===z0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===V0)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(r===F0)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===B0)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===z0)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===V0)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===F1||r===B1||r===z1||r===V1)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(r===F1)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===B1)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===z1)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===V1)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===H1||r===G1||r===W1)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(r===H1||r===G1)return o===bn?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(r===W1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===j1||r===$1||r===q1||r===X1||r===K1||r===Y1||r===Z1||r===Q1||r===J1||r===eE||r===tE||r===nE||r===rE||r===iE)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(r===j1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===$1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===q1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===X1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===K1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===Y1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===Z1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===Q1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===J1)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===eE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===tE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===nE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===rE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===iE)return o===bn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===H0||r===sE||r===oE)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(r===H0)return o===bn?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(r===sE)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(r===oE)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(r===DN||r===aE||r===cE||r===lE)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(r===H0)return s.COMPRESSED_RED_RGTC1_EXT;if(r===aE)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===cE)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===lE)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===Pu?n.UNSIGNED_INT_24_8:n[r]!==void 0?n[r]:null}return{convert:t}}class yH extends Ts{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class qd extends os{constructor(){super(),this.isGroup=!0,this.type="Group"}}const xH={type:"move"};class ES{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new qd,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new qd,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new xe,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new xe),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new qd,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new xe,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new xe),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const r of e.hand.values())this._getHandJoint(t,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,r){let i=null,s=null,o=null;const a=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(const v of e.hand.values()){const y=t.getJointPose(v,r),_=this._getHandJoint(l,v);y!==null&&(_.matrix.fromArray(y.transform.matrix),_.matrix.decompose(_.position,_.rotation,_.scale),_.matrixWorldNeedsUpdate=!0,_.jointRadius=y.radius),_.visible=y!==null}const u=l.joints["index-finger-tip"],h=l.joints["thumb-tip"],p=u.position.distanceTo(h.position),m=.02,g=.005;l.inputState.pinching&&p>m+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&p<=m-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,r),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));a!==null&&(i=t.getPose(e.targetRaySpace,r),i===null&&s!==null&&(i=s),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(xH)))}return a!==null&&(a.visible=i!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const r=new qd;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[t.jointName]=r,e.add(r)}return e.joints[t.jointName]}}const SH=` -void main() { - - gl_Position = vec4( position, 1.0 ); - -}`,EH=` -uniform sampler2DArray depthColor; -uniform float depthWidth; -uniform float depthHeight; - -void main() { - - vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); - - if ( coord.x >= 1.0 ) { - - gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; - - } else { - - gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; - - } - -}`;class wH{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,r){if(this.texture===null){const i=new or,s=e.properties.get(i);s.__webglTexture=t.texture,(t.depthNear!=r.depthNear||t.depthFar!=r.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,r=new Vi({vertexShader:SH,fragmentShader:EH,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new wo(new Gp(20,20),r)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class TH extends Oc{constructor(e,t){super();const r=this;let i=null,s=1,o=null,a="local-floor",c=1,l=null,u=null,h=null,p=null,m=null,g=null;const v=new wH,y=t.getContextAttributes();let _=null,S=null;const w=[],T=[],k=new St;let R=null;const C=new Ts;C.viewport=new gr;const O=new Ts;O.viewport=new gr;const M=[C,O],N=new yH;let U=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ne){let ie=w[ne];return ie===void 0&&(ie=new ES,w[ne]=ie),ie.getTargetRaySpace()},this.getControllerGrip=function(ne){let ie=w[ne];return ie===void 0&&(ie=new ES,w[ne]=ie),ie.getGripSpace()},this.getHand=function(ne){let ie=w[ne];return ie===void 0&&(ie=new ES,w[ne]=ie),ie.getHandSpace()};function P(ne){const ie=T.indexOf(ne.inputSource);if(ie===-1)return;const be=w[ie];be!==void 0&&(be.update(ne.inputSource,ne.frame,l||o),be.dispatchEvent({type:ne.type,data:ne.inputSource}))}function b(){i.removeEventListener("select",P),i.removeEventListener("selectstart",P),i.removeEventListener("selectend",P),i.removeEventListener("squeeze",P),i.removeEventListener("squeezestart",P),i.removeEventListener("squeezeend",P),i.removeEventListener("end",b),i.removeEventListener("inputsourceschange",B);for(let ne=0;ne=0&&(T[Ce]=null,w[Ce].disconnect(be))}for(let ie=0;ie=T.length){T.push(be),Ce=Le;break}else if(T[Le]===null){T[Le]=be,Ce=Le;break}if(Ce===-1)break}const Ee=w[Ce];Ee&&Ee.connect(be)}}const W=new xe,V=new xe;function G(ne,ie,be){W.setFromMatrixPosition(ie.matrixWorld),V.setFromMatrixPosition(be.matrixWorld);const Ce=W.distanceTo(V),Ee=ie.projectionMatrix.elements,Le=be.projectionMatrix.elements,ze=Ee[14]/(Ee[10]-1),Ge=Ee[14]/(Ee[10]+1),rt=(Ee[9]+1)/Ee[5],ft=(Ee[9]-1)/Ee[5],A=(Ee[8]-1)/Ee[0],J=(Le[8]+1)/Le[0],re=ze*A,j=ze*J,H=Ce/(-A+J),te=H*-A;if(ie.matrixWorld.decompose(ne.position,ne.quaternion,ne.scale),ne.translateX(te),ne.translateZ(H),ne.matrixWorld.compose(ne.position,ne.quaternion,ne.scale),ne.matrixWorldInverse.copy(ne.matrixWorld).invert(),Ee[10]===-1)ne.projectionMatrix.copy(ie.projectionMatrix),ne.projectionMatrixInverse.copy(ie.projectionMatrixInverse);else{const oe=ze+H,z=Ge+H,D=re-te,ee=j+(Ce-te),he=rt*Ge/z*oe,ce=ft*Ge/z*oe;ne.projectionMatrix.makePerspective(D,ee,he,ce,oe,z),ne.projectionMatrixInverse.copy(ne.projectionMatrix).invert()}}function $(ne,ie){ie===null?ne.matrixWorld.copy(ne.matrix):ne.matrixWorld.multiplyMatrices(ie.matrixWorld,ne.matrix),ne.matrixWorldInverse.copy(ne.matrixWorld).invert()}this.updateCamera=function(ne){if(i===null)return;let ie=ne.near,be=ne.far;v.texture!==null&&(v.depthNear>0&&(ie=v.depthNear),v.depthFar>0&&(be=v.depthFar)),N.near=O.near=C.near=ie,N.far=O.far=C.far=be,(U!==N.near||L!==N.far)&&(i.updateRenderState({depthNear:N.near,depthFar:N.far}),U=N.near,L=N.far),C.layers.mask=ne.layers.mask|2,O.layers.mask=ne.layers.mask|4,N.layers.mask=C.layers.mask|O.layers.mask;const Ce=ne.parent,Ee=N.cameras;$(N,Ce);for(let Le=0;Le0&&(y.alphaTest.value=_.alphaTest);const S=e.get(_),w=S.envMap,T=S.envMapRotation;w&&(y.envMap.value=w,au.copy(T),au.x*=-1,au.y*=-1,au.z*=-1,w.isCubeTexture&&w.isRenderTargetTexture===!1&&(au.y*=-1,au.z*=-1),y.envMapRotation.value.setFromMatrix4(bH.makeRotationFromEuler(au)),y.flipEnvMap.value=w.isCubeTexture&&w.isRenderTargetTexture===!1?-1:1,y.reflectivity.value=_.reflectivity,y.ior.value=_.ior,y.refractionRatio.value=_.refractionRatio),_.lightMap&&(y.lightMap.value=_.lightMap,y.lightMapIntensity.value=_.lightMapIntensity,t(_.lightMap,y.lightMapTransform)),_.aoMap&&(y.aoMap.value=_.aoMap,y.aoMapIntensity.value=_.aoMapIntensity,t(_.aoMap,y.aoMapTransform))}function o(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,_.map&&(y.map.value=_.map,t(_.map,y.mapTransform))}function a(y,_){y.dashSize.value=_.dashSize,y.totalSize.value=_.dashSize+_.gapSize,y.scale.value=_.scale}function c(y,_,S,w){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.size.value=_.size*S,y.scale.value=w*.5,_.map&&(y.map.value=_.map,t(_.map,y.uvTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,t(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function l(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.rotation.value=_.rotation,_.map&&(y.map.value=_.map,t(_.map,y.mapTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,t(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function u(y,_){y.specular.value.copy(_.specular),y.shininess.value=Math.max(_.shininess,1e-4)}function h(y,_){_.gradientMap&&(y.gradientMap.value=_.gradientMap)}function p(y,_){y.metalness.value=_.metalness,_.metalnessMap&&(y.metalnessMap.value=_.metalnessMap,t(_.metalnessMap,y.metalnessMapTransform)),y.roughness.value=_.roughness,_.roughnessMap&&(y.roughnessMap.value=_.roughnessMap,t(_.roughnessMap,y.roughnessMapTransform)),_.envMap&&(y.envMapIntensity.value=_.envMapIntensity)}function m(y,_,S){y.ior.value=_.ior,_.sheen>0&&(y.sheenColor.value.copy(_.sheenColor).multiplyScalar(_.sheen),y.sheenRoughness.value=_.sheenRoughness,_.sheenColorMap&&(y.sheenColorMap.value=_.sheenColorMap,t(_.sheenColorMap,y.sheenColorMapTransform)),_.sheenRoughnessMap&&(y.sheenRoughnessMap.value=_.sheenRoughnessMap,t(_.sheenRoughnessMap,y.sheenRoughnessMapTransform))),_.clearcoat>0&&(y.clearcoat.value=_.clearcoat,y.clearcoatRoughness.value=_.clearcoatRoughness,_.clearcoatMap&&(y.clearcoatMap.value=_.clearcoatMap,t(_.clearcoatMap,y.clearcoatMapTransform)),_.clearcoatRoughnessMap&&(y.clearcoatRoughnessMap.value=_.clearcoatRoughnessMap,t(_.clearcoatRoughnessMap,y.clearcoatRoughnessMapTransform)),_.clearcoatNormalMap&&(y.clearcoatNormalMap.value=_.clearcoatNormalMap,t(_.clearcoatNormalMap,y.clearcoatNormalMapTransform),y.clearcoatNormalScale.value.copy(_.clearcoatNormalScale),_.side===ni&&y.clearcoatNormalScale.value.negate())),_.dispersion>0&&(y.dispersion.value=_.dispersion),_.iridescence>0&&(y.iridescence.value=_.iridescence,y.iridescenceIOR.value=_.iridescenceIOR,y.iridescenceThicknessMinimum.value=_.iridescenceThicknessRange[0],y.iridescenceThicknessMaximum.value=_.iridescenceThicknessRange[1],_.iridescenceMap&&(y.iridescenceMap.value=_.iridescenceMap,t(_.iridescenceMap,y.iridescenceMapTransform)),_.iridescenceThicknessMap&&(y.iridescenceThicknessMap.value=_.iridescenceThicknessMap,t(_.iridescenceThicknessMap,y.iridescenceThicknessMapTransform))),_.transmission>0&&(y.transmission.value=_.transmission,y.transmissionSamplerMap.value=S.texture,y.transmissionSamplerSize.value.set(S.width,S.height),_.transmissionMap&&(y.transmissionMap.value=_.transmissionMap,t(_.transmissionMap,y.transmissionMapTransform)),y.thickness.value=_.thickness,_.thicknessMap&&(y.thicknessMap.value=_.thicknessMap,t(_.thicknessMap,y.thicknessMapTransform)),y.attenuationDistance.value=_.attenuationDistance,y.attenuationColor.value.copy(_.attenuationColor)),_.anisotropy>0&&(y.anisotropyVector.value.set(_.anisotropy*Math.cos(_.anisotropyRotation),_.anisotropy*Math.sin(_.anisotropyRotation)),_.anisotropyMap&&(y.anisotropyMap.value=_.anisotropyMap,t(_.anisotropyMap,y.anisotropyMapTransform))),y.specularIntensity.value=_.specularIntensity,y.specularColor.value.copy(_.specularColor),_.specularColorMap&&(y.specularColorMap.value=_.specularColorMap,t(_.specularColorMap,y.specularColorMapTransform)),_.specularIntensityMap&&(y.specularIntensityMap.value=_.specularIntensityMap,t(_.specularIntensityMap,y.specularIntensityMapTransform))}function g(y,_){_.matcap&&(y.matcap.value=_.matcap)}function v(y,_){const S=e.get(_).light;y.referencePosition.value.setFromMatrixPosition(S.matrixWorld),y.nearDistance.value=S.shadow.camera.near,y.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function MH(n,e,t,r){let i={},s={},o=[];const a=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function c(S,w){const T=w.program;r.uniformBlockBinding(S,T)}function l(S,w){let T=i[S.id];T===void 0&&(g(S),T=u(S),i[S.id]=T,S.addEventListener("dispose",y));const k=w.program;r.updateUBOMapping(S,k);const R=e.render.frame;s[S.id]!==R&&(p(S),s[S.id]=R)}function u(S){const w=h();S.__bindingPointIndex=w;const T=n.createBuffer(),k=S.__size,R=S.usage;return n.bindBuffer(n.UNIFORM_BUFFER,T),n.bufferData(n.UNIFORM_BUFFER,k,R),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,w,T),T}function h(){for(let S=0;S0&&(T+=k-R),S.__size=T,S.__cache={},this}function v(S){const w={boundary:0,storage:0};return typeof S=="number"||typeof S=="boolean"?(w.boundary=4,w.storage=4):S.isVector2?(w.boundary=8,w.storage=8):S.isVector3||S.isColor?(w.boundary=16,w.storage=12):S.isVector4?(w.boundary=16,w.storage=16):S.isMatrix3?(w.boundary=48,w.storage=48):S.isMatrix4?(w.boundary=64,w.storage=64):S.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",S),w}function y(S){const w=S.target;w.removeEventListener("dispose",y);const T=o.indexOf(w.__bindingPointIndex);o.splice(T,1),n.deleteBuffer(i[w.id]),delete i[w.id],delete s[w.id]}function _(){for(const S in i)n.deleteBuffer(i[S]);o=[],i={},s={}}return{bind:c,update:l,dispose:_}}class CH{constructor(e={}){const{canvas:t=g5(),context:r=null,depth:i=!0,stencil:s=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:h=!1,reverseDepthBuffer:p=!1}=e;this.isWebGLRenderer=!0;let m;if(r!==null){if(typeof WebGLRenderingContext<"u"&&r instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");m=r.getContextAttributes().alpha}else m=o;const g=new Uint32Array(4),v=new Int32Array(4);let y=null,_=null;const S=[],w=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=pr,this.toneMapping=ma,this.toneMappingExposure=1;const T=this;let k=!1,R=0,C=0,O=null,M=-1,N=null;const U=new gr,L=new gr;let P=null;const b=new cn(0);let B=0,W=t.width,V=t.height,G=1,$=null,Z=null;const X=new gr(0,0,W,V),Y=new gr(0,0,W,V);let ve=!1;const ne=new qN;let ie=!1,be=!1;const Ce=new ar,Ee=new ar,Le=new xe,ze=new gr,Ge={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let rt=!1;function ft(){return O===null?G:1}let A=r;function J(q,fe){return t.getContext(q,fe)}try{const q={alpha:!0,depth:i,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:u,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${mv}`),t.addEventListener("webglcontextlost",Ie,!1),t.addEventListener("webglcontextrestored",$e,!1),t.addEventListener("webglcontextcreationerror",Ze,!1),A===null){const fe="webgl2";if(A=J(fe,q),A===null)throw J(fe)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(q){throw console.error("THREE.WebGLRenderer: "+q.message),q}let re,j,H,te,oe,z,D,ee,he,ce,ge,Be,Oe,He,Lt,Pe,tt,Je,yt,nt,Ct,Rt,Sn,le;function je(){re=new O6(A),re.init(),Rt=new vH(A,re),j=new M6(A,re,e,Rt),H=new mH(A,re),j.reverseDepthBuffer&&p&&H.buffers.depth.setReversed(!0),te=new D6(A),oe=new eH,z=new _H(A,re,H,oe,j,Rt,te),D=new R6(T),ee=new N6(T),he=new G5(A),Sn=new b6(A,he),ce=new L6(A,he,te,Sn),ge=new F6(A,ce,he,te),yt=new U6(A,j,z),Pe=new C6(oe),Be=new JV(T,D,ee,re,j,Sn,Pe),Oe=new AH(T,oe),He=new nH,Lt=new cH(re),Je=new T6(T,D,ee,H,ge,m,c),tt=new dH(T,ge,j),le=new MH(A,te,j,H),nt=new A6(A,re,te),Ct=new P6(A,re,te),te.programs=Be.programs,T.capabilities=j,T.extensions=re,T.properties=oe,T.renderLists=He,T.shadowMap=tt,T.state=H,T.info=te}je();const Me=new TH(T,A);this.xr=Me,this.getContext=function(){return A},this.getContextAttributes=function(){return A.getContextAttributes()},this.forceContextLoss=function(){const q=re.get("WEBGL_lose_context");q&&q.loseContext()},this.forceContextRestore=function(){const q=re.get("WEBGL_lose_context");q&&q.restoreContext()},this.getPixelRatio=function(){return G},this.setPixelRatio=function(q){q!==void 0&&(G=q,this.setSize(W,V,!1))},this.getSize=function(q){return q.set(W,V)},this.setSize=function(q,fe,we=!0){if(Me.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}W=q,V=fe,t.width=Math.floor(q*G),t.height=Math.floor(fe*G),we===!0&&(t.style.width=q+"px",t.style.height=fe+"px"),this.setViewport(0,0,q,fe)},this.getDrawingBufferSize=function(q){return q.set(W*G,V*G).floor()},this.setDrawingBufferSize=function(q,fe,we){W=q,V=fe,G=we,t.width=Math.floor(q*we),t.height=Math.floor(fe*we),this.setViewport(0,0,q,fe)},this.getCurrentViewport=function(q){return q.copy(U)},this.getViewport=function(q){return q.copy(X)},this.setViewport=function(q,fe,we,Te){q.isVector4?X.set(q.x,q.y,q.z,q.w):X.set(q,fe,we,Te),H.viewport(U.copy(X).multiplyScalar(G).round())},this.getScissor=function(q){return q.copy(Y)},this.setScissor=function(q,fe,we,Te){q.isVector4?Y.set(q.x,q.y,q.z,q.w):Y.set(q,fe,we,Te),H.scissor(L.copy(Y).multiplyScalar(G).round())},this.getScissorTest=function(){return ve},this.setScissorTest=function(q){H.setScissorTest(ve=q)},this.setOpaqueSort=function(q){$=q},this.setTransparentSort=function(q){Z=q},this.getClearColor=function(q){return q.copy(Je.getClearColor())},this.setClearColor=function(){Je.setClearColor.apply(Je,arguments)},this.getClearAlpha=function(){return Je.getClearAlpha()},this.setClearAlpha=function(){Je.setClearAlpha.apply(Je,arguments)},this.clear=function(q=!0,fe=!0,we=!0){let Te=0;if(q){let me=!1;if(O!==null){const Fe=O.texture.format;me=Fe===_v||Fe===Yw||Fe===Kw}if(me){const Fe=O.texture.type,Ke=Fe===Ei||Fe===bl||Fe===fp||Fe===Pu||Fe===qw||Fe===Xw,ct=Je.getClearColor(),lt=Je.getClearAlpha(),At=ct.r,It=ct.g,ut=ct.b;Ke?(g[0]=At,g[1]=It,g[2]=ut,g[3]=lt,A.clearBufferuiv(A.COLOR,0,g)):(v[0]=At,v[1]=It,v[2]=ut,v[3]=lt,A.clearBufferiv(A.COLOR,0,v))}else Te|=A.COLOR_BUFFER_BIT}fe&&(Te|=A.DEPTH_BUFFER_BIT),we&&(Te|=A.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),A.clear(Te)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Ie,!1),t.removeEventListener("webglcontextrestored",$e,!1),t.removeEventListener("webglcontextcreationerror",Ze,!1),He.dispose(),Lt.dispose(),oe.dispose(),D.dispose(),ee.dispose(),ge.dispose(),Sn.dispose(),le.dispose(),Be.dispose(),Me.dispose(),Me.removeEventListener("sessionstart",Om),Me.removeEventListener("sessionend",Lm),jo.stop()};function Ie(q){q.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),k=!0}function $e(){console.log("THREE.WebGLRenderer: Context Restored."),k=!1;const q=te.autoReset,fe=tt.enabled,we=tt.autoUpdate,Te=tt.needsUpdate,me=tt.type;je(),te.autoReset=q,tt.enabled=fe,tt.autoUpdate=we,tt.needsUpdate=Te,tt.type=me}function Ze(q){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",q.statusMessage)}function kt(q){const fe=q.target;fe.removeEventListener("dispose",kt),Gn(fe)}function Gn(q){Rr(q),oe.remove(q)}function Rr(q){const fe=oe.get(q).programs;fe!==void 0&&(fe.forEach(function(we){Be.releaseProgram(we)}),q.isShaderMaterial&&Be.releaseShaderCache(q))}this.renderBufferDirect=function(q,fe,we,Te,me,Fe){fe===null&&(fe=Ge);const Ke=me.isMesh&&me.matrixWorld.determinant()<0,ct=Hy(q,fe,we,Te,me);H.setMaterial(Te,Ke);let lt=we.index,At=1;if(Te.wireframe===!0){if(lt=ce.getWireframeAttribute(we),lt===void 0)return;At=2}const It=we.drawRange,ut=we.attributes.position;let Bt=It.start*At,nn=(It.start+It.count)*At;Fe!==null&&(Bt=Math.max(Bt,Fe.start*At),nn=Math.min(nn,(Fe.start+Fe.count)*At)),lt!==null?(Bt=Math.max(Bt,0),nn=Math.min(nn,lt.count)):ut!=null&&(Bt=Math.max(Bt,0),nn=Math.min(nn,ut.count));const Et=nn-Bt;if(Et<0||Et===1/0)return;Sn.setup(me,Te,ct,we,lt);let Pt,zt=nt;if(lt!==null&&(Pt=he.get(lt),zt=Ct,zt.setIndex(Pt)),me.isMesh)Te.wireframe===!0?(H.setLineWidth(Te.wireframeLinewidth*ft()),zt.setMode(A.LINES)):zt.setMode(A.TRIANGLES);else if(me.isLine){let Qe=Te.linewidth;Qe===void 0&&(Qe=1),H.setLineWidth(Qe*ft()),me.isLineSegments?zt.setMode(A.LINES):me.isLineLoop?zt.setMode(A.LINE_LOOP):zt.setMode(A.LINE_STRIP)}else me.isPoints?zt.setMode(A.POINTS):me.isSprite&&zt.setMode(A.TRIANGLES);if(me.isBatchedMesh)if(me._multiDrawInstances!==null)zt.renderMultiDrawInstances(me._multiDrawStarts,me._multiDrawCounts,me._multiDrawCount,me._multiDrawInstances);else if(re.get("WEBGL_multi_draw"))zt.renderMultiDraw(me._multiDrawStarts,me._multiDrawCounts,me._multiDrawCount);else{const Qe=me._multiDrawStarts,Wn=me._multiDrawCounts,qt=me._multiDrawCount,Wr=lt?he.get(lt).bytesPerElement:1,lr=oe.get(Te).currentProgram.getUniforms();for(let jr=0;jr{function Fe(){if(Te.forEach(function(Ke){oe.get(Ke).currentProgram.isReady()&&Te.delete(Ke)}),Te.size===0){me(q);return}setTimeout(Fe,10)}re.get("KHR_parallel_shader_compile")!==null?Fe():setTimeout(Fe,10)})};let qi=null;function ho(q){qi&&qi(q)}function Om(){jo.stop()}function Lm(){jo.start()}const jo=new XN;jo.setAnimationLoop(ho),typeof self<"u"&&jo.setContext(self),this.setAnimationLoop=function(q){qi=q,Me.setAnimationLoop(q),q===null?jo.stop():jo.start()},Me.addEventListener("sessionstart",Om),Me.addEventListener("sessionend",Lm),this.render=function(q,fe){if(fe!==void 0&&fe.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(k===!0)return;if(q.matrixWorldAutoUpdate===!0&&q.updateMatrixWorld(),fe.parent===null&&fe.matrixWorldAutoUpdate===!0&&fe.updateMatrixWorld(),Me.enabled===!0&&Me.isPresenting===!0&&(Me.cameraAutoUpdate===!0&&Me.updateCamera(fe),fe=Me.getCamera()),q.isScene===!0&&q.onBeforeRender(T,q,fe,O),_=Lt.get(q,w.length),_.init(fe),w.push(_),Ee.multiplyMatrices(fe.projectionMatrix,fe.matrixWorldInverse),ne.setFromProjectionMatrix(Ee),be=this.localClippingEnabled,ie=Pe.init(this.clippingPlanes,be),y=He.get(q,S.length),y.init(),S.push(y),Me.enabled===!0&&Me.isPresenting===!0){const Fe=T.xr.getDepthSensingMesh();Fe!==null&&$l(Fe,fe,-1/0,T.sortObjects)}$l(q,fe,0,T.sortObjects),y.finish(),T.sortObjects===!0&&y.sort($,Z),rt=Me.enabled===!1||Me.isPresenting===!1||Me.hasDepthSensing()===!1,rt&&Je.addToRenderList(y,q),this.info.render.frame++,ie===!0&&Pe.beginShadows();const we=_.state.shadowsArray;tt.render(we,q,fe),ie===!0&&Pe.endShadows(),this.info.autoReset===!0&&this.info.reset();const Te=y.opaque,me=y.transmissive;if(_.setupLights(),fe.isArrayCamera){const Fe=fe.cameras;if(me.length>0)for(let Ke=0,ct=Fe.length;Ke0&&qc(Te,me,q,fe),rt&&Je.render(q),Pm(y,q,fe);O!==null&&(z.updateMultisampleRenderTarget(O),z.updateRenderTargetMipmap(O)),q.isScene===!0&&q.onAfterRender(T,q,fe),Sn.resetDefaultState(),M=-1,N=null,w.pop(),w.length>0?(_=w[w.length-1],ie===!0&&Pe.setGlobalState(T.clippingPlanes,_.state.camera)):_=null,S.pop(),S.length>0?y=S[S.length-1]:y=null};function $l(q,fe,we,Te){if(q.visible===!1)return;if(q.layers.test(fe.layers)){if(q.isGroup)we=q.renderOrder;else if(q.isLOD)q.autoUpdate===!0&&q.update(fe);else if(q.isLight)_.pushLight(q),q.castShadow&&_.pushShadow(q);else if(q.isSprite){if(!q.frustumCulled||ne.intersectsSprite(q)){Te&&ze.setFromMatrixPosition(q.matrixWorld).applyMatrix4(Ee);const Ke=ge.update(q),ct=q.material;ct.visible&&y.push(q,Ke,ct,we,ze.z,null)}}else if((q.isMesh||q.isLine||q.isPoints)&&(!q.frustumCulled||ne.intersectsObject(q))){const Ke=ge.update(q),ct=q.material;if(Te&&(q.boundingSphere!==void 0?(q.boundingSphere===null&&q.computeBoundingSphere(),ze.copy(q.boundingSphere.center)):(Ke.boundingSphere===null&&Ke.computeBoundingSphere(),ze.copy(Ke.boundingSphere.center)),ze.applyMatrix4(q.matrixWorld).applyMatrix4(Ee)),Array.isArray(ct)){const lt=Ke.groups;for(let At=0,It=lt.length;At0&&hh(me,fe,we),Fe.length>0&&hh(Fe,fe,we),Ke.length>0&&hh(Ke,fe,we),H.buffers.depth.setTest(!0),H.buffers.depth.setMask(!0),H.buffers.color.setMask(!0),H.setPolygonOffset(!1)}function qc(q,fe,we,Te){if((we.isScene===!0?we.overrideMaterial:null)!==null)return;_.state.transmissionRenderTarget[Te.id]===void 0&&(_.state.transmissionRenderTarget[Te.id]=new Ls(1,1,{generateMipmaps:!0,type:re.has("EXT_color_buffer_half_float")||re.has("EXT_color_buffer_float")?Qf:Ei,minFilter:Tu,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:hn.workingColorSpace}));const Fe=_.state.transmissionRenderTarget[Te.id],Ke=Te.viewport||U;Fe.setSize(Ke.z,Ke.w);const ct=T.getRenderTarget();T.setRenderTarget(Fe),T.getClearColor(b),B=T.getClearAlpha(),B<1&&T.setClearColor(16777215,.5),T.clear(),rt&&Je.render(we);const lt=T.toneMapping;T.toneMapping=ma;const At=Te.viewport;if(Te.viewport!==void 0&&(Te.viewport=void 0),_.setupLightsView(Te),ie===!0&&Pe.setGlobalState(T.clippingPlanes,Te),hh(q,we,Te),z.updateMultisampleRenderTarget(Fe),z.updateRenderTargetMipmap(Fe),re.has("WEBGL_multisampled_render_to_texture")===!1){let It=!1;for(let ut=0,Bt=fe.length;ut0),ut=!!we.morphAttributes.position,Bt=!!we.morphAttributes.normal,nn=!!we.morphAttributes.color;let Et=ma;Te.toneMapped&&(O===null||O.isXRRenderTarget===!0)&&(Et=T.toneMapping);const Pt=we.morphAttributes.position||we.morphAttributes.normal||we.morphAttributes.color,zt=Pt!==void 0?Pt.length:0,Qe=oe.get(Te),Wn=_.state.lights;if(ie===!0&&(be===!0||q!==N)){const jn=q===N&&Te.id===M;Pe.setState(Te,q,jn)}let qt=!1;Te.version===Qe.__version?(Qe.needsLights&&Qe.lightsStateVersion!==Wn.state.version||Qe.outputColorSpace!==ct||me.isBatchedMesh&&Qe.batching===!1||!me.isBatchedMesh&&Qe.batching===!0||me.isBatchedMesh&&Qe.batchingColor===!0&&me.colorTexture===null||me.isBatchedMesh&&Qe.batchingColor===!1&&me.colorTexture!==null||me.isInstancedMesh&&Qe.instancing===!1||!me.isInstancedMesh&&Qe.instancing===!0||me.isSkinnedMesh&&Qe.skinning===!1||!me.isSkinnedMesh&&Qe.skinning===!0||me.isInstancedMesh&&Qe.instancingColor===!0&&me.instanceColor===null||me.isInstancedMesh&&Qe.instancingColor===!1&&me.instanceColor!==null||me.isInstancedMesh&&Qe.instancingMorph===!0&&me.morphTexture===null||me.isInstancedMesh&&Qe.instancingMorph===!1&&me.morphTexture!==null||Qe.envMap!==lt||Te.fog===!0&&Qe.fog!==Fe||Qe.numClippingPlanes!==void 0&&(Qe.numClippingPlanes!==Pe.numPlanes||Qe.numIntersection!==Pe.numIntersection)||Qe.vertexAlphas!==At||Qe.vertexTangents!==It||Qe.morphTargets!==ut||Qe.morphNormals!==Bt||Qe.morphColors!==nn||Qe.toneMapping!==Et||Qe.morphTargetsCount!==zt)&&(qt=!0):(qt=!0,Qe.__version=Te.version);let Wr=Qe.currentProgram;qt===!0&&(Wr=fh(Te,fe,me));let lr=!1,jr=!1,Xc=!1;const Tn=Wr.getUniforms(),bi=Qe.uniforms;if(H.useProgram(Wr.program)&&(lr=!0,jr=!0,Xc=!0),Te.id!==M&&(M=Te.id,jr=!0),lr||N!==q){H.buffers.depth.getReversed()?(Ce.copy(q.projectionMatrix),v5(Ce),y5(Ce),Tn.setValue(A,"projectionMatrix",Ce)):Tn.setValue(A,"projectionMatrix",q.projectionMatrix),Tn.setValue(A,"viewMatrix",q.matrixWorldInverse);const $o=Tn.map.cameraPosition;$o!==void 0&&$o.setValue(A,Le.setFromMatrixPosition(q.matrixWorld)),j.logarithmicDepthBuffer&&Tn.setValue(A,"logDepthBufFC",2/(Math.log(q.far+1)/Math.LN2)),(Te.isMeshPhongMaterial||Te.isMeshToonMaterial||Te.isMeshLambertMaterial||Te.isMeshBasicMaterial||Te.isMeshStandardMaterial||Te.isShaderMaterial)&&Tn.setValue(A,"isOrthographic",q.isOrthographicCamera===!0),N!==q&&(N=q,jr=!0,Xc=!0)}if(me.isSkinnedMesh){Tn.setOptional(A,me,"bindMatrix"),Tn.setOptional(A,me,"bindMatrixInverse");const jn=me.skeleton;jn&&(jn.boneTexture===null&&jn.computeBoneTexture(),Tn.setValue(A,"boneTexture",jn.boneTexture,z))}me.isBatchedMesh&&(Tn.setOptional(A,me,"batchingTexture"),Tn.setValue(A,"batchingTexture",me._matricesTexture,z),Tn.setOptional(A,me,"batchingIdTexture"),Tn.setValue(A,"batchingIdTexture",me._indirectTexture,z),Tn.setOptional(A,me,"batchingColorTexture"),me._colorsTexture!==null&&Tn.setValue(A,"batchingColorTexture",me._colorsTexture,z));const Kc=we.morphAttributes;if((Kc.position!==void 0||Kc.normal!==void 0||Kc.color!==void 0)&&yt.update(me,we,Wr),(jr||Qe.receiveShadow!==me.receiveShadow)&&(Qe.receiveShadow=me.receiveShadow,Tn.setValue(A,"receiveShadow",me.receiveShadow)),Te.isMeshGouraudMaterial&&Te.envMap!==null&&(bi.envMap.value=lt,bi.flipEnvMap.value=lt.isCubeTexture&<.isRenderTargetTexture===!1?-1:1),Te.isMeshStandardMaterial&&Te.envMap===null&&fe.environment!==null&&(bi.envMapIntensity.value=fe.environmentIntensity),jr&&(Tn.setValue(A,"toneMappingExposure",T.toneMappingExposure),Qe.needsLights&&Gy(bi,Xc),Fe&&Te.fog===!0&&Oe.refreshFogUniforms(bi,Fe),Oe.refreshMaterialUniforms(bi,Te,G,V,_.state.transmissionRenderTarget[q.id]),G0.upload(A,Um(Qe),bi,z)),Te.isShaderMaterial&&Te.uniformsNeedUpdate===!0&&(G0.upload(A,Um(Qe),bi,z),Te.uniformsNeedUpdate=!1),Te.isSpriteMaterial&&Tn.setValue(A,"center",me.center),Tn.setValue(A,"modelViewMatrix",me.modelViewMatrix),Tn.setValue(A,"normalMatrix",me.normalMatrix),Tn.setValue(A,"modelMatrix",me.matrixWorld),Te.isShaderMaterial||Te.isRawShaderMaterial){const jn=Te.uniformsGroups;for(let $o=0,qo=jn.length;$o0&&z.useMultisampledRTT(q)===!1?me=oe.get(q).__webglMultisampledFramebuffer:Array.isArray(It)?me=It[we]:me=It,U.copy(q.viewport),L.copy(q.scissor),P=q.scissorTest}else U.copy(X).multiplyScalar(G).floor(),L.copy(Y).multiplyScalar(G).floor(),P=ve;if(H.bindFramebuffer(A.FRAMEBUFFER,me)&&Te&&H.drawBuffers(q,me),H.viewport(U),H.scissor(L),H.setScissorTest(P),Fe){const lt=oe.get(q.texture);A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+fe,lt.__webglTexture,we)}else if(Ke){const lt=oe.get(q.texture),At=fe||0;A.framebufferTextureLayer(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,lt.__webglTexture,we||0,At)}M=-1},this.readRenderTargetPixels=function(q,fe,we,Te,me,Fe,Ke){if(!(q&&q.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let ct=oe.get(q).__webglFramebuffer;if(q.isWebGLCubeRenderTarget&&Ke!==void 0&&(ct=ct[Ke]),ct){H.bindFramebuffer(A.FRAMEBUFFER,ct);try{const lt=q.texture,At=lt.format,It=lt.type;if(!j.textureFormatReadable(At)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!j.textureTypeReadable(It)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}fe>=0&&fe<=q.width-Te&&we>=0&&we<=q.height-me&&A.readPixels(fe,we,Te,me,Rt.convert(At),Rt.convert(It),Fe)}finally{const lt=O!==null?oe.get(O).__webglFramebuffer:null;H.bindFramebuffer(A.FRAMEBUFFER,lt)}}},this.readRenderTargetPixelsAsync=async function(q,fe,we,Te,me,Fe,Ke){if(!(q&&q.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let ct=oe.get(q).__webglFramebuffer;if(q.isWebGLCubeRenderTarget&&Ke!==void 0&&(ct=ct[Ke]),ct){const lt=q.texture,At=lt.format,It=lt.type;if(!j.textureFormatReadable(At))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!j.textureTypeReadable(It))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(fe>=0&&fe<=q.width-Te&&we>=0&&we<=q.height-me){H.bindFramebuffer(A.FRAMEBUFFER,ct);const ut=A.createBuffer();A.bindBuffer(A.PIXEL_PACK_BUFFER,ut),A.bufferData(A.PIXEL_PACK_BUFFER,Fe.byteLength,A.STREAM_READ),A.readPixels(fe,we,Te,me,Rt.convert(At),Rt.convert(It),0);const Bt=O!==null?oe.get(O).__webglFramebuffer:null;H.bindFramebuffer(A.FRAMEBUFFER,Bt);const nn=A.fenceSync(A.SYNC_GPU_COMMANDS_COMPLETE,0);return A.flush(),await _5(A,nn,4),A.bindBuffer(A.PIXEL_PACK_BUFFER,ut),A.getBufferSubData(A.PIXEL_PACK_BUFFER,0,Fe),A.deleteBuffer(ut),A.deleteSync(nn),Fe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(q,fe=null,we=0){q.isTexture!==!0&&(jd("WebGLRenderer: copyFramebufferToTexture function signature has changed."),fe=arguments[0]||null,q=arguments[1]);const Te=Math.pow(2,-we),me=Math.floor(q.image.width*Te),Fe=Math.floor(q.image.height*Te),Ke=fe!==null?fe.x:0,ct=fe!==null?fe.y:0;z.setTexture2D(q,0),A.copyTexSubImage2D(A.TEXTURE_2D,we,0,0,Ke,ct,me,Fe),H.unbindTexture()},this.copyTextureToTexture=function(q,fe,we=null,Te=null,me=0){q.isTexture!==!0&&(jd("WebGLRenderer: copyTextureToTexture function signature has changed."),Te=arguments[0]||null,q=arguments[1],fe=arguments[2],me=arguments[3]||0,we=null);let Fe,Ke,ct,lt,At,It,ut,Bt,nn;const Et=q.isCompressedTexture?q.mipmaps[me]:q.image;we!==null?(Fe=we.max.x-we.min.x,Ke=we.max.y-we.min.y,ct=we.isBox3?we.max.z-we.min.z:1,lt=we.min.x,At=we.min.y,It=we.isBox3?we.min.z:0):(Fe=Et.width,Ke=Et.height,ct=Et.depth||1,lt=0,At=0,It=0),Te!==null?(ut=Te.x,Bt=Te.y,nn=Te.z):(ut=0,Bt=0,nn=0);const Pt=Rt.convert(fe.format),zt=Rt.convert(fe.type);let Qe;fe.isData3DTexture?(z.setTexture3D(fe,0),Qe=A.TEXTURE_3D):fe.isDataArrayTexture||fe.isCompressedArrayTexture?(z.setTexture2DArray(fe,0),Qe=A.TEXTURE_2D_ARRAY):(z.setTexture2D(fe,0),Qe=A.TEXTURE_2D),A.pixelStorei(A.UNPACK_FLIP_Y_WEBGL,fe.flipY),A.pixelStorei(A.UNPACK_PREMULTIPLY_ALPHA_WEBGL,fe.premultiplyAlpha),A.pixelStorei(A.UNPACK_ALIGNMENT,fe.unpackAlignment);const Wn=A.getParameter(A.UNPACK_ROW_LENGTH),qt=A.getParameter(A.UNPACK_IMAGE_HEIGHT),Wr=A.getParameter(A.UNPACK_SKIP_PIXELS),lr=A.getParameter(A.UNPACK_SKIP_ROWS),jr=A.getParameter(A.UNPACK_SKIP_IMAGES);A.pixelStorei(A.UNPACK_ROW_LENGTH,Et.width),A.pixelStorei(A.UNPACK_IMAGE_HEIGHT,Et.height),A.pixelStorei(A.UNPACK_SKIP_PIXELS,lt),A.pixelStorei(A.UNPACK_SKIP_ROWS,At),A.pixelStorei(A.UNPACK_SKIP_IMAGES,It);const Xc=q.isDataArrayTexture||q.isData3DTexture,Tn=fe.isDataArrayTexture||fe.isData3DTexture;if(q.isRenderTargetTexture||q.isDepthTexture){const bi=oe.get(q),Kc=oe.get(fe),jn=oe.get(bi.__renderTarget),$o=oe.get(Kc.__renderTarget);H.bindFramebuffer(A.READ_FRAMEBUFFER,jn.__webglFramebuffer),H.bindFramebuffer(A.DRAW_FRAMEBUFFER,$o.__webglFramebuffer);for(let qo=0;qo0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class JN extends or{constructor(e=null,t=1,r=1,i,s,o,a,c,l=vr,u=vr,h,p){super(null,o,a,c,l,u,i,s,h,p),this.isDataTexture=!0,this.image={data:e,width:t,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class RH extends Lc{static get type(){return"PointsMaterial"}constructor(e){super(),this.isPointsMaterial=!0,this.color=new cn(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const _R=new ar,hE=new Qw,t0=new yv,n0=new xe;class kH extends os{constructor(e=new Do,t=new RH){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const r=this.geometry,i=this.matrixWorld,s=e.params.Points.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),t0.copy(r.boundingSphere),t0.applyMatrix4(i),t0.radius+=s,e.ray.intersectsSphere(t0)===!1)return;_R.copy(i).invert(),hE.copy(e.ray).applyMatrix4(_R);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=r.index,h=r.attributes.position;if(l!==null){const p=Math.max(0,o.start),m=Math.min(l.count,o.start+o.count);for(let g=p,v=m;g0){const i=t[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;si.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class IH extends or{constructor(e,t,r,i,s,o,a,c,l){super(e,t,r,i,s,o,a,c,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class NH extends Lc{static get type(){return"MeshNormalMaterial"}constructor(e){super(),this.isMeshNormalMaterial=!0,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=UN,this.normalScale=new St(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}const yR={enabled:!1,files:{},add:function(n,e){this.enabled!==!1&&(this.files[n]=e)},get:function(n){if(this.enabled!==!1)return this.files[n]},remove:function(n){delete this.files[n]},clear:function(){this.files={}}};class OH{constructor(e,t,r){const i=this;let s=!1,o=0,a=0,c;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=r,this.itemStart=function(u){a++,s===!1&&i.onStart!==void 0&&i.onStart(u,o,a),s=!0},this.itemEnd=function(u){o++,i.onProgress!==void 0&&i.onProgress(u,o,a),o===a&&(s=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(u){i.onError!==void 0&&i.onError(u)},this.resolveURL=function(u){return c?c(u):u},this.setURLModifier=function(u){return c=u,this},this.addHandler=function(u,h){return l.push(u,h),this},this.removeHandler=function(u){const h=l.indexOf(u);return h!==-1&&l.splice(h,2),this},this.getHandler=function(u){for(let h=0,p=l.length;h=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,wR).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:mv}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=mv);var eO={exports:{}},Zu={};/** - * @license React - * react-reconciler-constants.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */Zu.ConcurrentRoot=1;Zu.ContinuousEventPriority=4;Zu.DefaultEventPriority=16;Zu.DiscreteEventPriority=1;Zu.IdleEventPriority=536870912;Zu.LegacyRoot=0;eO.exports=Zu;var nf=eO.exports;function BH(n){let e;const t=new Set,r=(l,u)=>{const h=typeof l=="function"?l(e):l;if(h!==e){const p=e;e=u?h:Object.assign({},e,h),t.forEach(m=>m(e,p))}},i=()=>e,s=(l,u=i,h=Object.is)=>{console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware");let p=u(e);function m(){const g=u(e);if(!h(p,g)){const v=p;l(p=g,v)}}return t.add(m),()=>t.delete(m)},c={setState:r,getState:i,subscribe:(l,u,h)=>u||h?s(l,u,h):(t.add(l),()=>t.delete(l)),destroy:()=>t.clear()};return e=n(r,i,c),c}const zH=typeof window>"u"||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent),TR=zH?ke.useEffect:ke.useLayoutEffect;function VH(n){const e=typeof n=="function"?BH(n):n,t=(r=e.getState,i=Object.is)=>{const[,s]=ke.useReducer(y=>y+1,0),o=e.getState(),a=ke.useRef(o),c=ke.useRef(r),l=ke.useRef(i),u=ke.useRef(!1),h=ke.useRef();h.current===void 0&&(h.current=r(o));let p,m=!1;(a.current!==o||c.current!==r||l.current!==i||u.current)&&(p=r(o),m=!i(h.current,p)),TR(()=>{m&&(h.current=p),a.current=o,c.current=r,l.current=i,u.current=!1});const g=ke.useRef(o);TR(()=>{const y=()=>{try{const S=e.getState(),w=c.current(S);l.current(h.current,w)||(a.current=S,h.current=w,s())}catch{u.current=!0,s()}},_=e.subscribe(y);return e.getState()!==g.current&&y(),_},[]);const v=m?p:h.current;return ke.useDebugValue(v),v};return Object.assign(t,e),t[Symbol.iterator]=function(){console.warn("[useStore, api] = create() is deprecated and will be removed in v4");const r=[t,e];return{next(){const i=r.length<=0;return{value:r.shift(),done:i}}}},t}const HH=n=>typeof n=="object"&&typeof n.then=="function",bu=[];function tO(n,e,t=(r,i)=>r===i){if(n===e)return!0;if(!n||!e)return!1;const r=n.length;if(e.length!==r)return!1;for(let i=0;i0&&(s.timeout&&clearTimeout(s.timeout),s.timeout=setTimeout(s.remove,r.lifespan)),s.response;if(!t)throw s.promise}const i={keys:e,equal:r.equal,remove:()=>{const s=bu.indexOf(i);s!==-1&&bu.splice(s,1)},promise:(HH(n)?n:n(...e)).then(s=>{i.response=s,r.lifespan&&r.lifespan>0&&(i.timeout=setTimeout(i.remove,r.lifespan))}).catch(s=>i.error=s)};if(bu.push(i),!t)throw i.promise}const GH=(n,e,t)=>nO(n,e,!1,t),WH=(n,e,t)=>void nO(n,e,!0,t),jH=n=>{if(n===void 0||n.length===0)bu.splice(0,bu.length);else{const e=bu.find(t=>tO(n,t.keys,t.equal));e&&e.remove()}};var rO={exports:{}},iO={exports:{}},sO={};/** - * @license React - * scheduler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */(function(n){function e(G,$){var Z=G.length;G.push($);e:for(;0>>1,Y=G[X];if(0>>1;Xi(ie,Z))bei(Ce,ie)?(G[X]=Ce,G[be]=Z,X=be):(G[X]=ie,G[ne]=Z,X=ne);else if(bei(Ce,Z))G[X]=Ce,G[be]=Z,X=be;else break e}}return $}function i(G,$){var Z=G.sortIndex-$.sortIndex;return Z!==0?Z:G.id-$.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;n.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();n.unstable_now=function(){return o.now()-a}}var c=[],l=[],u=1,h=null,p=3,m=!1,g=!1,v=!1,y=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(G){for(var $=t(l);$!==null;){if($.callback===null)r(l);else if($.startTime<=G)r(l),$.sortIndex=$.expirationTime,e(c,$);else break;$=t(l)}}function T(G){if(v=!1,w(G),!g)if(t(c)!==null)g=!0,W(k);else{var $=t(l);$!==null&&V(T,$.startTime-G)}}function k(G,$){g=!1,v&&(v=!1,_(O),O=-1),m=!0;var Z=p;try{for(w($),h=t(c);h!==null&&(!(h.expirationTime>$)||G&&!U());){var X=h.callback;if(typeof X=="function"){h.callback=null,p=h.priorityLevel;var Y=X(h.expirationTime<=$);$=n.unstable_now(),typeof Y=="function"?h.callback=Y:h===t(c)&&r(c),w($)}else r(c);h=t(c)}if(h!==null)var ve=!0;else{var ne=t(l);ne!==null&&V(T,ne.startTime-$),ve=!1}return ve}finally{h=null,p=Z,m=!1}}var R=!1,C=null,O=-1,M=5,N=-1;function U(){return!(n.unstable_now()-NG||125X?(G.sortIndex=Z,e(l,G),t(c)===null&&G===t(l)&&(v?(_(O),O=-1):v=!0,V(T,Z-X))):(G.sortIndex=Y,e(c,G),g||m||(g=!0,W(k))),G},n.unstable_shouldYield=U,n.unstable_wrapCallback=function(G){var $=p;return function(){var Z=p;p=$;try{return G.apply(this,arguments)}finally{p=Z}}}})(sO);iO.exports=sO;var dE=iO.exports;/** - * @license React - * react-reconciler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var $H=function(e){var t={},r=ke,i=dE,s=Object.assign;function o(f){for(var d="https://reactjs.org/docs/error-decoder.html?invariant="+f,x=1;xae||I[Q]!==F[ae]){var Re=` -`+I[Q].replace(" at new "," at ");return f.displayName&&Re.includes("")&&(Re=Re.replace("",f.displayName)),Re}while(1<=Q&&0<=ae);break}}}finally{lt=!1,Error.prepareStackTrace=x}return(f=f?f.displayName||f.name:"")?ct(f):""}var It=Object.prototype.hasOwnProperty,ut=[],Bt=-1;function nn(f){return{current:f}}function Et(f){0>Bt||(f.current=ut[Bt],ut[Bt]=null,Bt--)}function Pt(f,d){Bt++,ut[Bt]=f.current,f.current=d}var zt={},Qe=nn(zt),Wn=nn(!1),qt=zt;function Wr(f,d){var x=f.type.contextTypes;if(!x)return zt;var E=f.stateNode;if(E&&E.__reactInternalMemoizedUnmaskedChildContext===d)return E.__reactInternalMemoizedMaskedChildContext;var I={},F;for(F in x)I[F]=d[F];return E&&(f=f.stateNode,f.__reactInternalMemoizedUnmaskedChildContext=d,f.__reactInternalMemoizedMaskedChildContext=I),I}function lr(f){return f=f.childContextTypes,f!=null}function jr(){Et(Wn),Et(Qe)}function Xc(f,d,x){if(Qe.current!==zt)throw Error(o(168));Pt(Qe,d),Pt(Wn,x)}function Tn(f,d,x){var E=f.stateNode;if(d=d.childContextTypes,typeof E.getChildContext!="function")return x;E=E.getChildContext();for(var I in E)if(!(I in d))throw Error(o(108,O(f)||"Unknown",I));return s({},x,E)}function bi(f){return f=(f=f.stateNode)&&f.__reactInternalMemoizedMergedChildContext||zt,qt=Qe.current,Pt(Qe,f),Pt(Wn,Wn.current),!0}function Kc(f,d,x){var E=f.stateNode;if(!E)throw Error(o(169));x?(f=Tn(f,d,qt),E.__reactInternalMemoizedMergedChildContext=f,Et(Wn),Et(Qe),Pt(Qe,f)):Et(Wn),Pt(Wn,x)}var jn=Math.clz32?Math.clz32:zm,$o=Math.log,qo=Math.LN2;function zm(f){return f>>>=0,f===0?32:31-($o(f)/qo|0)|0}var Vm=64,Hm=4194304;function hd(f){switch(f&-f){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return f&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return f&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return f}}function Gm(f,d){var x=f.pendingLanes;if(x===0)return 0;var E=0,I=f.suspendedLanes,F=f.pingedLanes,Q=x&268435455;if(Q!==0){var ae=Q&~I;ae!==0?E=hd(ae):(F&=Q,F!==0&&(E=hd(F)))}else Q=x&~I,Q!==0?E=hd(Q):F!==0&&(E=hd(F));if(E===0)return 0;if(d!==0&&d!==E&&!(d&I)&&(I=E&-E,F=d&-d,I>=F||I===16&&(F&4194240)!==0))return d;if(E&4&&(E|=x&16),d=f.entangledLanes,d!==0)for(f=f.entanglements,d&=E;0x;x++)d.push(f);return d}function fd(f,d,x){f.pendingLanes|=d,d!==536870912&&(f.suspendedLanes=0,f.pingedLanes=0),f=f.eventTimes,d=31-jn(d),f[d]=x}function rF(f,d){var x=f.pendingLanes&~d;f.pendingLanes=d,f.suspendedLanes=0,f.pingedLanes=0,f.expiredLanes&=d,f.mutableReadLanes&=d,f.entangledLanes&=d,d=f.entanglements;var E=f.eventTimes;for(f=f.expirationTimes;0>=Q,I-=Q,ja=1<<32-jn(d)+I|x<mn?(Xr=Ot,Ot=null):Xr=Ot.sibling;var gn=xt(Se,Ot,Ae[mn],et);if(gn===null){Ot===null&&(Ot=Xr);break}f&&Ot&&gn.alternate===null&&d(Se,Ot),de=F(gn,de,mn),Ut===null?pt=gn:Ut.sibling=gn,Ut=gn,Ot=Xr}if(mn===Ae.length)return x(Se,Ot),$n&&Xl(Se,mn),pt;if(Ot===null){for(;mnmn?(Xr=Ot,Ot=null):Xr=Ot.sibling;var rl=xt(Se,Ot,gn.value,et);if(rl===null){Ot===null&&(Ot=Xr);break}f&&Ot&&rl.alternate===null&&d(Se,Ot),de=F(rl,de,mn),Ut===null?pt=rl:Ut.sibling=rl,Ut=rl,Ot=Xr}if(gn.done)return x(Se,Ot),$n&&Xl(Se,mn),pt;if(Ot===null){for(;!gn.done;mn++,gn=Ae.next())gn=Nt(Se,gn.value,et),gn!==null&&(de=F(gn,de,mn),Ut===null?pt=gn:Ut.sibling=gn,Ut=gn);return $n&&Xl(Se,mn),pt}for(Ot=E(Se,Ot);!gn.done;mn++,gn=Ae.next())gn=kn(Ot,Se,mn,gn.value,et),gn!==null&&(f&&gn.alternate!==null&&Ot.delete(gn.key===null?mn:gn.key),de=F(gn,de,mn),Ut===null?pt=gn:Ut.sibling=gn,Ut=gn);return f&&Ot.forEach(function(HF){return d(Se,HF)}),$n&&Xl(Se,mn),pt}function Gs(Se,de,Ae,et){if(typeof Ae=="object"&&Ae!==null&&Ae.type===u&&Ae.key===null&&(Ae=Ae.props.children),typeof Ae=="object"&&Ae!==null){switch(Ae.$$typeof){case c:e:{for(var pt=Ae.key,Ut=de;Ut!==null;){if(Ut.key===pt){if(pt=Ae.type,pt===u){if(Ut.tag===7){x(Se,Ut.sibling),de=I(Ut,Ae.props.children),de.return=Se,Se=de;break e}}else if(Ut.elementType===pt||typeof pt=="object"&&pt!==null&&pt.$$typeof===w&&JA(pt)===Ut.type){x(Se,Ut.sibling),de=I(Ut,Ae.props),de.ref=md(Se,Ut,Ae),de.return=Se,Se=de;break e}x(Se,Ut);break}else d(Se,Ut);Ut=Ut.sibling}Ae.type===u?(de=tu(Ae.props.children,Se.mode,et,Ae.key),de.return=Se,Se=de):(et=Ig(Ae.type,Ae.key,Ae.props,null,Se.mode,et),et.ref=md(Se,de,Ae),et.return=Se,Se=et)}return Q(Se);case l:e:{for(Ut=Ae.key;de!==null;){if(de.key===Ut)if(de.tag===4&&de.stateNode.containerInfo===Ae.containerInfo&&de.stateNode.implementation===Ae.implementation){x(Se,de.sibling),de=I(de,Ae.children||[]),de.return=Se,Se=de;break e}else{x(Se,de);break}else d(Se,de);de=de.sibling}de=$x(Ae,Se.mode,et),de.return=Se,Se=de}return Q(Se);case w:return Ut=Ae._init,Gs(Se,de,Ut(Ae._payload),et)}if(B(Ae))return gt(Se,de,Ae,et);if(R(Ae))return mi(Se,de,Ae,et);eg(Se,Ae)}return typeof Ae=="string"&&Ae!==""||typeof Ae=="number"?(Ae=""+Ae,de!==null&&de.tag===6?(x(Se,de.sibling),de=I(de,Ae),de.return=Se,Se=de):(x(Se,de),de=jx(Ae,Se.mode,et),de.return=Se,Se=de),Q(Se)):x(Se,de)}return Gs}var vh=eM(!0),tM=eM(!1),gd={},Bs=nn(gd),_d=nn(gd),yh=nn(gd);function Qo(f){if(f===gd)throw Error(o(174));return f}function lx(f,d){Pt(yh,d),Pt(_d,f),Pt(Bs,gd),f=V(d),Et(Bs),Pt(Bs,f)}function xh(){Et(Bs),Et(_d),Et(yh)}function nM(f){var d=Qo(yh.current),x=Qo(Bs.current);d=G(x,f.type,d),x!==d&&(Pt(_d,f),Pt(Bs,d))}function ux(f){_d.current===f&&(Et(Bs),Et(_d))}var Kn=nn(0);function tg(f){for(var d=f;d!==null;){if(d.tag===13){var x=d.memoizedState;if(x!==null&&(x=x.dehydrated,x===null||jo(x)||$l(x)))return d}else if(d.tag===19&&d.memoizedProps.revealOrder!==void 0){if(d.flags&128)return d}else if(d.child!==null){d.child.return=d,d=d.child;continue}if(d===f)break;for(;d.sibling===null;){if(d.return===null||d.return===f)return null;d=d.return}d.sibling.return=d.return,d=d.sibling}return null}var hx=[];function fx(){for(var f=0;fx?x:4,f(!0);var E=zs.transition;zs.transition={};try{f(!1),d()}finally{pn=x,zs.transition=E}}function gM(){return Jo().memoizedState}function mF(f,d,x){var E=el(f);x={lane:E,action:x,hasEagerState:!1,eagerState:null,next:null},_M(f)?vM(d,x):(yM(f,d,x),x=Mi(),f=Vs(f,E,x),f!==null&&xM(f,d,E))}function gF(f,d,x){var E=el(f),I={lane:E,action:x,hasEagerState:!1,eagerState:null,next:null};if(_M(f))vM(d,I);else{yM(f,d,I);var F=f.alternate;if(f.lanes===0&&(F===null||F.lanes===0)&&(F=d.lastRenderedReducer,F!==null))try{var Q=d.lastRenderedState,ae=F(Q,x);if(I.hasEagerState=!0,I.eagerState=ae,Ko(ae,Q))return}catch{}finally{}x=Mi(),f=Vs(f,E,x),f!==null&&xM(f,d,E)}}function _M(f){var d=f.alternate;return f===er||d!==null&&d===er}function vM(f,d){vd=rg=!0;var x=f.pending;x===null?d.next=d:(d.next=x.next,x.next=d),f.pending=d}function yM(f,d,x){xr!==null&&f.mode&1&&!(Vt&2)?(f=d.interleaved,f===null?(x.next=x,Zo===null?Zo=[d]:Zo.push(d)):(x.next=f.next,f.next=x),d.interleaved=x):(f=d.pending,f===null?x.next=x:(x.next=f.next,f.next=x),d.pending=x)}function xM(f,d,x){if(x&4194240){var E=d.lanes;E&=f.pendingLanes,x|=E,d.lanes=x,$y(f,x)}}var cg={readContext:Ds,useCallback:di,useContext:di,useEffect:di,useImperativeHandle:di,useInsertionEffect:di,useLayoutEffect:di,useMemo:di,useReducer:di,useRef:di,useState:di,useDebugValue:di,useDeferredValue:di,useTransition:di,useMutableSource:di,useSyncExternalStore:di,useId:di,unstable_isNewReconciler:!1},_F={readContext:Ds,useCallback:function(f,d){return qa().memoizedState=[f,d===void 0?null:d],f},useContext:Ds,useEffect:_x,useImperativeHandle:function(f,d,x){return x=x!=null?x.concat([f]):null,og(4194308,4,fM.bind(null,d,f),x)},useLayoutEffect:function(f,d){return og(4194308,4,f,d)},useInsertionEffect:function(f,d){return og(4,2,f,d)},useMemo:function(f,d){var x=qa();return d=d===void 0?null:d,f=f(),x.memoizedState=[f,d],f},useReducer:function(f,d,x){var E=qa();return d=x!==void 0?x(d):d,E.memoizedState=E.baseState=d,f={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:f,lastRenderedState:d},E.queue=f,f=f.dispatch=mF.bind(null,er,f),[E.memoizedState,f]},useRef:function(f){var d=qa();return f={current:f},d.memoizedState=f},useState:gx,useDebugValue:vx,useDeferredValue:function(f){var d=gx(f),x=d[0],E=d[1];return _x(function(){var I=zs.transition;zs.transition={};try{E(f)}finally{zs.transition=I}},[f]),x},useTransition:function(){var f=gx(!1),d=f[0];return f=pF.bind(null,f[1]),qa().memoizedState=f,[d,f]},useMutableSource:function(){},useSyncExternalStore:function(f,d,x){var E=er,I=qa();if($n){if(x===void 0)throw Error(o(407));x=x()}else{if(x=d(),xr===null)throw Error(o(349));Sh&30||sM(E,d,x)}I.memoizedState=x;var F={value:x,getSnapshot:d};return I.queue=F,_x(aM.bind(null,E,F,f),[f]),E.flags|=2048,xd(9,oM.bind(null,E,F,x,d),void 0,null),x},useId:function(){var f=qa(),d=xr.identifierPrefix;if($n){var x=$a,E=ja;x=(E&~(1<<32-jn(E)-1)).toString(32)+x,d=":"+d+"R"+x,x=yd++,0Ux&&(d.flags|=128,E=!0,Td(I,!1),d.lanes=4194304)}else{if(!E)if(f=tg(F),f!==null){if(d.flags|=128,E=!0,f=f.updateQueue,f!==null&&(d.updateQueue=f,d.flags|=4),Td(I,!0),I.tail===null&&I.tailMode==="hidden"&&!F.alternate&&!$n)return pi(d),null}else 2*$r()-I.renderingStartTime>Ux&&x!==1073741824&&(d.flags|=128,E=!0,Td(I,!1),d.lanes=4194304);I.isBackwards?(F.sibling=d.child,d.child=F):(f=I.last,f!==null?f.sibling=F:d.child=F,I.last=F)}return I.tail!==null?(d=I.tail,I.rendering=d,I.tail=d.sibling,I.renderingStartTime=$r(),d.sibling=null,f=Kn.current,Pt(Kn,E?f&1|2:f&1),d):(pi(d),null);case 22:case 23:return Hx(),E=d.memoizedState!==null,f!==null&&f.memoizedState!==null!==E&&(d.flags|=8192),E&&d.mode&1?xs&1073741824&&(pi(d),Ge&&d.subtreeFlags&6&&(d.flags|=8192)):pi(d),null;case 24:return null;case 25:return null}throw Error(o(156,d.tag))}var EF=a.ReactCurrentOwner,ys=!1;function Ai(f,d,x,E){d.child=f===null?tM(d,null,x,E):vh(d,f.child,x,E)}function CM(f,d,x,E,I){x=x.render;var F=d.ref;return ph(d,I),E=px(f,d,x,E,F,I),x=mx(),f!==null&&!ys?(d.updateQueue=f.updateQueue,d.flags&=-2053,f.lanes&=~I,Xa(f,d,I)):($n&&x&&ix(d),d.flags|=1,Ai(f,d,E,I),d.child)}function RM(f,d,x,E,I){if(f===null){var F=x.type;return typeof F=="function"&&!Wx(F)&&F.defaultProps===void 0&&x.compare===null&&x.defaultProps===void 0?(d.tag=15,d.type=F,kM(f,d,F,E,I)):(f=Ig(x.type,null,E,d,d.mode,I),f.ref=d.ref,f.return=d,d.child=f)}if(F=f.child,!(f.lanes&I)){var Q=F.memoizedProps;if(x=x.compare,x=x!==null?x:$m,x(Q,E)&&f.ref===d.ref)return Xa(f,d,I)}return d.flags|=1,f=nl(F,E),f.ref=d.ref,f.return=d,d.child=f}function kM(f,d,x,E,I){if(f!==null&&$m(f.memoizedProps,E)&&f.ref===d.ref)if(ys=!1,(f.lanes&I)!==0)f.flags&131072&&(ys=!0);else return d.lanes=f.lanes,Xa(f,d,I);return Sx(f,d,x,E,I)}function IM(f,d,x){var E=d.pendingProps,I=E.children,F=f!==null?f.memoizedState:null;if(E.mode==="hidden")if(!(d.mode&1))d.memoizedState={baseLanes:0,cachePool:null},Pt(Eh,xs),xs|=x;else if(x&1073741824)d.memoizedState={baseLanes:0,cachePool:null},E=F!==null?F.baseLanes:x,Pt(Eh,xs),xs|=E;else return f=F!==null?F.baseLanes|x:x,d.lanes=d.childLanes=1073741824,d.memoizedState={baseLanes:f,cachePool:null},d.updateQueue=null,Pt(Eh,xs),xs|=f,null;else F!==null?(E=F.baseLanes|x,d.memoizedState=null):E=x,Pt(Eh,xs),xs|=E;return Ai(f,d,I,x),d.child}function NM(f,d){var x=d.ref;(f===null&&x!==null||f!==null&&f.ref!==x)&&(d.flags|=512,d.flags|=2097152)}function Sx(f,d,x,E,I){var F=lr(x)?qt:Qe.current;return F=Wr(d,F),ph(d,I),x=px(f,d,x,E,F,I),E=mx(),f!==null&&!ys?(d.updateQueue=f.updateQueue,d.flags&=-2053,f.lanes&=~I,Xa(f,d,I)):($n&&E&&ix(d),d.flags|=1,Ai(f,d,x,I),d.child)}function OM(f,d,x,E,I){if(lr(x)){var F=!0;bi(d)}else F=!1;if(ph(d,I),d.stateNode===null)f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),qA(d,x,E),rx(d,x,E,I),E=!0;else if(f===null){var Q=d.stateNode,ae=d.memoizedProps;Q.props=ae;var Re=Q.context,Ue=x.contextType;typeof Ue=="object"&&Ue!==null?Ue=Ds(Ue):(Ue=lr(x)?qt:Qe.current,Ue=Wr(d,Ue));var ot=x.getDerivedStateFromProps,Nt=typeof ot=="function"||typeof Q.getSnapshotBeforeUpdate=="function";Nt||typeof Q.UNSAFE_componentWillReceiveProps!="function"&&typeof Q.componentWillReceiveProps!="function"||(ae!==E||Re!==Ue)&&XA(d,Q,E,Ue),Yc=!1;var xt=d.memoizedState;Q.state=xt,Ym(d,E,Q,I),Re=d.memoizedState,ae!==E||xt!==Re||Wn.current||Yc?(typeof ot=="function"&&(nx(d,x,ot,E),Re=d.memoizedState),(ae=Yc||$A(d,x,ae,E,xt,Re,Ue))?(Nt||typeof Q.UNSAFE_componentWillMount!="function"&&typeof Q.componentWillMount!="function"||(typeof Q.componentWillMount=="function"&&Q.componentWillMount(),typeof Q.UNSAFE_componentWillMount=="function"&&Q.UNSAFE_componentWillMount()),typeof Q.componentDidMount=="function"&&(d.flags|=4194308)):(typeof Q.componentDidMount=="function"&&(d.flags|=4194308),d.memoizedProps=E,d.memoizedState=Re),Q.props=E,Q.state=Re,Q.context=Ue,E=ae):(typeof Q.componentDidMount=="function"&&(d.flags|=4194308),E=!1)}else{Q=d.stateNode,HA(f,d),ae=d.memoizedProps,Ue=d.type===d.elementType?ae:fo(d.type,ae),Q.props=Ue,Nt=d.pendingProps,xt=Q.context,Re=x.contextType,typeof Re=="object"&&Re!==null?Re=Ds(Re):(Re=lr(x)?qt:Qe.current,Re=Wr(d,Re));var kn=x.getDerivedStateFromProps;(ot=typeof kn=="function"||typeof Q.getSnapshotBeforeUpdate=="function")||typeof Q.UNSAFE_componentWillReceiveProps!="function"&&typeof Q.componentWillReceiveProps!="function"||(ae!==Nt||xt!==Re)&&XA(d,Q,E,Re),Yc=!1,xt=d.memoizedState,Q.state=xt,Ym(d,E,Q,I);var gt=d.memoizedState;ae!==Nt||xt!==gt||Wn.current||Yc?(typeof kn=="function"&&(nx(d,x,kn,E),gt=d.memoizedState),(Ue=Yc||$A(d,x,Ue,E,xt,gt,Re)||!1)?(ot||typeof Q.UNSAFE_componentWillUpdate!="function"&&typeof Q.componentWillUpdate!="function"||(typeof Q.componentWillUpdate=="function"&&Q.componentWillUpdate(E,gt,Re),typeof Q.UNSAFE_componentWillUpdate=="function"&&Q.UNSAFE_componentWillUpdate(E,gt,Re)),typeof Q.componentDidUpdate=="function"&&(d.flags|=4),typeof Q.getSnapshotBeforeUpdate=="function"&&(d.flags|=1024)):(typeof Q.componentDidUpdate!="function"||ae===f.memoizedProps&&xt===f.memoizedState||(d.flags|=4),typeof Q.getSnapshotBeforeUpdate!="function"||ae===f.memoizedProps&&xt===f.memoizedState||(d.flags|=1024),d.memoizedProps=E,d.memoizedState=gt),Q.props=E,Q.state=gt,Q.context=Re,E=Ue):(typeof Q.componentDidUpdate!="function"||ae===f.memoizedProps&&xt===f.memoizedState||(d.flags|=4),typeof Q.getSnapshotBeforeUpdate!="function"||ae===f.memoizedProps&&xt===f.memoizedState||(d.flags|=1024),E=!1)}return Ex(f,d,x,E,F,I)}function Ex(f,d,x,E,I,F){NM(f,d);var Q=(d.flags&128)!==0;if(!E&&!Q)return I&&Kc(d,x,!1),Xa(f,d,F);E=d.stateNode,EF.current=d;var ae=Q&&typeof x.getDerivedStateFromError!="function"?null:E.render();return d.flags|=1,f!==null&&Q?(d.child=vh(d,f.child,null,F),d.child=vh(d,null,ae,F)):Ai(f,d,ae,F),d.memoizedState=E.state,I&&Kc(d,x,!0),d.child}function LM(f){var d=f.stateNode;d.pendingContext?Xc(f,d.pendingContext,d.pendingContext!==d.context):d.context&&Xc(f,d.context,!1),lx(f,d.containerInfo)}function PM(f,d,x,E,I){return _h(),cx(I),d.flags|=256,Ai(f,d,x,E),d.child}var hg={dehydrated:null,treeContext:null,retryLane:0};function fg(f){return{baseLanes:f,cachePool:null}}function DM(f,d,x){var E=d.pendingProps,I=Kn.current,F=!1,Q=(d.flags&128)!==0,ae;if((ae=Q)||(ae=f!==null&&f.memoizedState===null?!1:(I&2)!==0),ae?(F=!0,d.flags&=-129):(f===null||f.memoizedState!==null)&&(I|=1),Pt(Kn,I&1),f===null)return ax(d),f=d.memoizedState,f!==null&&(f=f.dehydrated,f!==null)?(d.mode&1?$l(f)?d.lanes=8:d.lanes=1073741824:d.lanes=1,null):(I=E.children,f=E.fallback,F?(E=d.mode,F=d.child,I={mode:"hidden",children:I},!(E&1)&&F!==null?(F.childLanes=0,F.pendingProps=I):F=Ng(I,E,0,null),f=tu(f,E,x,null),F.return=d,f.return=d,F.sibling=f,d.child=F,d.child.memoizedState=fg(x),d.memoizedState=hg,f):wx(d,I));if(I=f.memoizedState,I!==null){if(ae=I.dehydrated,ae!==null){if(Q)return d.flags&256?(d.flags&=-257,dg(f,d,x,Error(o(422)))):d.memoizedState!==null?(d.child=f.child,d.flags|=128,null):(F=E.fallback,I=d.mode,E=Ng({mode:"visible",children:E.children},I,0,null),F=tu(F,I,x,null),F.flags|=2,E.return=d,F.return=d,E.sibling=F,d.child=E,d.mode&1&&vh(d,f.child,null,x),d.child.memoizedState=fg(x),d.memoizedState=hg,F);if(!(d.mode&1))d=dg(f,d,x,null);else if($l(ae))d=dg(f,d,x,Error(o(419)));else if(E=(x&f.childLanes)!==0,ys||E){if(E=xr,E!==null){switch(x&-x){case 4:F=2;break;case 16:F=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:F=32;break;case 536870912:F=268435456;break;default:F=0}E=F&(E.suspendedLanes|x)?0:F,E!==0&&E!==I.retryLane&&(I.retryLane=E,Vs(f,E,-1))}Gx(),d=dg(f,d,x,Error(o(421)))}else jo(ae)?(d.flags|=128,d.child=f.child,d=PF.bind(null,f),Pm(ae,d),d=null):(x=I.treeContext,ft&&(vs=fh(ae),_s=d,$n=!0,po=null,dd=!1,x!==null&&(Us[Fs++]=ja,Us[Fs++]=$a,Us[Fs++]=ql,ja=x.id,$a=x.overflow,ql=d)),d=wx(d,d.pendingProps.children),d.flags|=4096);return d}return F?(E=FM(f,d,E.children,E.fallback,x),F=d.child,I=f.child.memoizedState,F.memoizedState=I===null?fg(x):{baseLanes:I.baseLanes|x,cachePool:null},F.childLanes=f.childLanes&~x,d.memoizedState=hg,E):(x=UM(f,d,E.children,x),d.memoizedState=null,x)}return F?(E=FM(f,d,E.children,E.fallback,x),F=d.child,I=f.child.memoizedState,F.memoizedState=I===null?fg(x):{baseLanes:I.baseLanes|x,cachePool:null},F.childLanes=f.childLanes&~x,d.memoizedState=hg,E):(x=UM(f,d,E.children,x),d.memoizedState=null,x)}function wx(f,d){return d=Ng({mode:"visible",children:d},f.mode,0,null),d.return=f,f.child=d}function UM(f,d,x,E){var I=f.child;return f=I.sibling,x=nl(I,{mode:"visible",children:x}),!(d.mode&1)&&(x.lanes=E),x.return=d,x.sibling=null,f!==null&&(E=d.deletions,E===null?(d.deletions=[f],d.flags|=16):E.push(f)),d.child=x}function FM(f,d,x,E,I){var F=d.mode;f=f.child;var Q=f.sibling,ae={mode:"hidden",children:x};return!(F&1)&&d.child!==f?(x=d.child,x.childLanes=0,x.pendingProps=ae,d.deletions=null):(x=nl(f,ae),x.subtreeFlags=f.subtreeFlags&14680064),Q!==null?E=nl(Q,E):(E=tu(E,F,I,null),E.flags|=2),E.return=d,x.return=d,x.sibling=E,d.child=x,E}function dg(f,d,x,E){return E!==null&&cx(E),vh(d,f.child,null,x),f=wx(d,d.pendingProps.children),f.flags|=2,d.memoizedState=null,f}function BM(f,d,x){f.lanes|=d;var E=f.alternate;E!==null&&(E.lanes|=d),ex(f.return,d,x)}function Tx(f,d,x,E,I){var F=f.memoizedState;F===null?f.memoizedState={isBackwards:d,rendering:null,renderingStartTime:0,last:E,tail:x,tailMode:I}:(F.isBackwards=d,F.rendering=null,F.renderingStartTime=0,F.last=E,F.tail=x,F.tailMode=I)}function zM(f,d,x){var E=d.pendingProps,I=E.revealOrder,F=E.tail;if(Ai(f,d,E.children,x),E=Kn.current,E&2)E=E&1|2,d.flags|=128;else{if(f!==null&&f.flags&128)e:for(f=d.child;f!==null;){if(f.tag===13)f.memoizedState!==null&&BM(f,x,d);else if(f.tag===19)BM(f,x,d);else if(f.child!==null){f.child.return=f,f=f.child;continue}if(f===d)break e;for(;f.sibling===null;){if(f.return===null||f.return===d)break e;f=f.return}f.sibling.return=f.return,f=f.sibling}E&=1}if(Pt(Kn,E),!(d.mode&1))d.memoizedState=null;else switch(I){case"forwards":for(x=d.child,I=null;x!==null;)f=x.alternate,f!==null&&tg(f)===null&&(I=x),x=x.sibling;x=I,x===null?(I=d.child,d.child=null):(I=x.sibling,x.sibling=null),Tx(d,!1,I,x,F);break;case"backwards":for(x=null,I=d.child,d.child=null;I!==null;){if(f=I.alternate,f!==null&&tg(f)===null){d.child=I;break}f=I.sibling,I.sibling=x,x=I,I=f}Tx(d,!0,x,null,F);break;case"together":Tx(d,!1,null,null,void 0);break;default:d.memoizedState=null}return d.child}function Xa(f,d,x){if(f!==null&&(d.dependencies=f.dependencies),wh|=d.lanes,!(x&d.childLanes))return null;if(f!==null&&d.child!==f.child)throw Error(o(153));if(d.child!==null){for(f=d.child,x=nl(f,f.pendingProps),d.child=x,x.return=d;f.sibling!==null;)f=f.sibling,x=x.sibling=nl(f,f.pendingProps),x.return=d;x.sibling=null}return d.child}function wF(f,d,x){switch(d.tag){case 3:LM(d),_h();break;case 5:nM(d);break;case 1:lr(d.type)&&bi(d);break;case 4:lx(d,d.stateNode.containerInfo);break;case 10:VA(d,d.type._context,d.memoizedProps.value);break;case 13:var E=d.memoizedState;if(E!==null)return E.dehydrated!==null?(Pt(Kn,Kn.current&1),d.flags|=128,null):x&d.child.childLanes?DM(f,d,x):(Pt(Kn,Kn.current&1),f=Xa(f,d,x),f!==null?f.sibling:null);Pt(Kn,Kn.current&1);break;case 19:if(E=(x&d.childLanes)!==0,f.flags&128){if(E)return zM(f,d,x);d.flags|=128}var I=d.memoizedState;if(I!==null&&(I.rendering=null,I.tail=null,I.lastEffect=null),Pt(Kn,Kn.current),E)break;return null;case 22:case 23:return d.lanes=0,IM(f,d,x)}return Xa(f,d,x)}function TF(f,d){switch(sx(d),d.tag){case 1:return lr(d.type)&&jr(),f=d.flags,f&65536?(d.flags=f&-65537|128,d):null;case 3:return xh(),Et(Wn),Et(Qe),fx(),f=d.flags,f&65536&&!(f&128)?(d.flags=f&-65537|128,d):null;case 5:return ux(d),null;case 13:if(Et(Kn),f=d.memoizedState,f!==null&&f.dehydrated!==null){if(d.alternate===null)throw Error(o(340));_h()}return f=d.flags,f&65536?(d.flags=f&-65537|128,d):null;case 19:return Et(Kn),null;case 4:return xh(),null;case 10:return Jy(d.type._context),null;case 22:case 23:return Hx(),null;case 24:return null;default:return null}}var pg=!1,Yl=!1,bF=typeof WeakSet=="function"?WeakSet:Set,Ye=null;function mg(f,d){var x=f.ref;if(x!==null)if(typeof x=="function")try{x(null)}catch(E){Yi(f,d,E)}else x.current=null}function bx(f,d,x){try{x()}catch(E){Yi(f,d,E)}}var VM=!1;function AF(f,d){for($(f.containerInfo),Ye=d;Ye!==null;)if(f=Ye,d=f.child,(f.subtreeFlags&1028)!==0&&d!==null)d.return=f,Ye=d;else for(;Ye!==null;){f=Ye;try{var x=f.alternate;if(f.flags&1024)switch(f.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var E=x.memoizedProps,I=x.memoizedState,F=f.stateNode,Q=F.getSnapshotBeforeUpdate(f.elementType===f.type?E:fo(f.type,E),I);F.__reactInternalSnapshotBeforeUpdate=Q}break;case 3:Ge&&Ie(f.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(o(163))}}catch(ae){Yi(f,f.return,ae)}if(d=f.sibling,d!==null){d.return=f.return,Ye=d;break}Ye=f.return}return x=VM,VM=!1,x}function Zl(f,d,x){var E=d.updateQueue;if(E=E!==null?E.lastEffect:null,E!==null){var I=E=E.next;do{if((I.tag&f)===f){var F=I.destroy;I.destroy=void 0,F!==void 0&&bx(d,x,F)}I=I.next}while(I!==E)}}function bd(f,d){if(d=d.updateQueue,d=d!==null?d.lastEffect:null,d!==null){var x=d=d.next;do{if((x.tag&f)===f){var E=x.create;x.destroy=E()}x=x.next}while(x!==d)}}function Ax(f){var d=f.ref;if(d!==null){var x=f.stateNode;switch(f.tag){case 5:f=W(x);break;default:f=x}typeof d=="function"?d(f):d.current=f}}function HM(f,d,x){if(Xo&&typeof Xo.onCommitFiberUnmount=="function")try{Xo.onCommitFiberUnmount(Wm,d)}catch{}switch(d.tag){case 0:case 11:case 14:case 15:if(f=d.updateQueue,f!==null&&(f=f.lastEffect,f!==null)){var E=f=f.next;do{var I=E,F=I.destroy;I=I.tag,F!==void 0&&(I&2||I&4)&&bx(d,x,F),E=E.next}while(E!==f)}break;case 1:if(mg(d,x),f=d.stateNode,typeof f.componentWillUnmount=="function")try{f.props=d.memoizedProps,f.state=d.memoizedState,f.componentWillUnmount()}catch(Q){Yi(d,x,Q)}break;case 5:mg(d,x);break;case 4:Ge?XM(f,d,x):rt&&rt&&(d=d.stateNode.containerInfo,x=Ze(d),Rr(d,x))}}function GM(f,d,x){for(var E=d;;)if(HM(f,E,x),E.child===null||Ge&&E.tag===4){if(E===d)break;for(;E.sibling===null;){if(E.return===null||E.return===d)return;E=E.return}E.sibling.return=E.return,E=E.sibling}else E.child.return=E,E=E.child}function WM(f){var d=f.alternate;d!==null&&(f.alternate=null,WM(d)),f.child=null,f.deletions=null,f.sibling=null,f.tag===5&&(d=f.stateNode,d!==null&&j(d)),f.stateNode=null,f.return=null,f.dependencies=null,f.memoizedProps=null,f.memoizedState=null,f.pendingProps=null,f.stateNode=null,f.updateQueue=null}function jM(f){return f.tag===5||f.tag===3||f.tag===4}function $M(f){e:for(;;){for(;f.sibling===null;){if(f.return===null||jM(f.return))return null;f=f.return}for(f.sibling.return=f.return,f=f.sibling;f.tag!==5&&f.tag!==6&&f.tag!==18;){if(f.flags&2||f.child===null||f.tag===4)continue e;f.child.return=f,f=f.child}if(!(f.flags&2))return f.stateNode}}function qM(f){if(Ge){e:{for(var d=f.return;d!==null;){if(jM(d))break e;d=d.return}throw Error(o(160))}var x=d;switch(x.tag){case 5:d=x.stateNode,x.flags&32&&(Rt(d),x.flags&=-33),x=$M(f),Cx(f,x,d);break;case 3:case 4:d=x.stateNode.containerInfo,x=$M(f),Mx(f,x,d);break;default:throw Error(o(161))}}}function Mx(f,d,x){var E=f.tag;if(E===5||E===6)f=f.stateNode,d?yt(x,f,d):He(x,f);else if(E!==4&&(f=f.child,f!==null))for(Mx(f,d,x),f=f.sibling;f!==null;)Mx(f,d,x),f=f.sibling}function Cx(f,d,x){var E=f.tag;if(E===5||E===6)f=f.stateNode,d?Je(x,f,d):Oe(x,f);else if(E!==4&&(f=f.child,f!==null))for(Cx(f,d,x),f=f.sibling;f!==null;)Cx(f,d,x),f=f.sibling}function XM(f,d,x){for(var E=d,I=!1,F,Q;;){if(!I){I=E.return;e:for(;;){if(I===null)throw Error(o(160));switch(F=I.stateNode,I.tag){case 5:Q=!1;break e;case 3:F=F.containerInfo,Q=!0;break e;case 4:F=F.containerInfo,Q=!0;break e}I=I.return}I=!0}if(E.tag===5||E.tag===6)GM(f,E,x),Q?Ct(F,E.stateNode):nt(F,E.stateNode);else if(E.tag===18)Q?we(F,E.stateNode):fe(F,E.stateNode);else if(E.tag===4){if(E.child!==null){F=E.stateNode.containerInfo,Q=!0,E.child.return=E,E=E.child;continue}}else if(HM(f,E,x),E.child!==null){E.child.return=E,E=E.child;continue}if(E===d)break;for(;E.sibling===null;){if(E.return===null||E.return===d)return;E=E.return,E.tag===4&&(I=!1)}E.sibling.return=E.return,E=E.sibling}}function Rx(f,d){if(Ge){switch(d.tag){case 0:case 11:case 14:case 15:Zl(3,d,d.return),bd(3,d),Zl(5,d,d.return);return;case 1:return;case 5:var x=d.stateNode;if(x!=null){var E=d.memoizedProps;f=f!==null?f.memoizedProps:E;var I=d.type,F=d.updateQueue;d.updateQueue=null,F!==null&&tt(x,F,I,f,E,d)}return;case 6:if(d.stateNode===null)throw Error(o(162));x=d.memoizedProps,Lt(d.stateNode,f!==null?f.memoizedProps:x,x);return;case 3:ft&&f!==null&&f.memoizedState.isDehydrated&&Bm(d.stateNode.containerInfo);return;case 12:return;case 13:gg(d);return;case 19:gg(d);return;case 17:return}throw Error(o(163))}switch(d.tag){case 0:case 11:case 14:case 15:Zl(3,d,d.return),bd(3,d),Zl(5,d,d.return);return;case 12:return;case 13:gg(d);return;case 19:gg(d);return;case 3:ft&&f!==null&&f.memoizedState.isDehydrated&&Bm(d.stateNode.containerInfo);break;case 22:case 23:return}e:if(rt){switch(d.tag){case 1:case 5:case 6:break e;case 3:case 4:d=d.stateNode,Rr(d.containerInfo,d.pendingChildren);break e}throw Error(o(163))}}function gg(f){var d=f.updateQueue;if(d!==null){f.updateQueue=null;var x=f.stateNode;x===null&&(x=f.stateNode=new bF),d.forEach(function(E){var I=DF.bind(null,f,E);x.has(E)||(x.add(E),E.then(I,I))})}}function MF(f,d){for(Ye=d;Ye!==null;){d=Ye;var x=d.deletions;if(x!==null)for(var E=0;E";case vg:return":has("+(Nx(f)||"")+")";case yg:return'[role="'+f.value+'"]';case Sg:return'"'+f.value+'"';case xg:return'[data-testname="'+f.value+'"]';default:throw Error(o(365))}}function JM(f,d){var x=[];f=[f,0];for(var E=0;EI&&(I=Q),E&=~F}if(E=I,E=$r()-E,E=(120>E?120:480>E?480:1080>E?1080:1920>E?1920:3e3>E?3e3:4320>E?4320:1960*RF(E/1960))-E,10f?16:f,Jc===null)var E=!1;else{if(f=Jc,Jc=null,Ag=0,Vt&6)throw Error(o(331));var I=Vt;for(Vt|=4,Ye=f.current;Ye!==null;){var F=Ye,Q=F.child;if(Ye.flags&16){var ae=F.deletions;if(ae!==null){for(var Re=0;Re$r()-Dx?Ql(f,0):Px|=x),Ki(f,d)}function cC(f,d){d===0&&(f.mode&1?(d=Hm,Hm<<=1,!(Hm&130023424)&&(Hm=4194304)):d=1);var x=Mi();f=Rg(f,d),f!==null&&(fd(f,d,x),Ki(f,x))}function PF(f){var d=f.memoizedState,x=0;d!==null&&(x=d.retryLane),cC(f,x)}function DF(f,d){var x=0;switch(f.tag){case 13:var E=f.stateNode,I=f.memoizedState;I!==null&&(x=I.retryLane);break;case 19:E=f.stateNode;break;default:throw Error(o(314))}E!==null&&E.delete(d),cC(f,x)}var lC;lC=function(f,d,x){if(f!==null)if(f.memoizedProps!==d.pendingProps||Wn.current)ys=!0;else{if(!(f.lanes&x)&&!(d.flags&128))return ys=!1,wF(f,d,x);ys=!!(f.flags&131072)}else ys=!1,$n&&d.flags&1048576&&KA(d,Jm,d.index);switch(d.lanes=0,d.tag){case 2:var E=d.type;f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),f=d.pendingProps;var I=Wr(d,Qe.current);ph(d,x),I=px(null,d,E,f,I,x);var F=mx();return d.flags|=1,typeof I=="object"&&I!==null&&typeof I.render=="function"&&I.$$typeof===void 0?(d.tag=1,d.memoizedState=null,d.updateQueue=null,lr(E)?(F=!0,bi(d)):F=!1,d.memoizedState=I.state!==null&&I.state!==void 0?I.state:null,tx(d),I.updater=Zm,d.stateNode=I,I._reactInternals=d,rx(d,E,f,x),d=Ex(null,d,E,!0,F,x)):(d.tag=0,$n&&F&&ix(d),Ai(null,d,I,x),d=d.child),d;case 16:E=d.elementType;e:{switch(f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),f=d.pendingProps,I=E._init,E=I(E._payload),d.type=E,I=d.tag=FF(E),f=fo(E,f),I){case 0:d=Sx(null,d,E,f,x);break e;case 1:d=OM(null,d,E,f,x);break e;case 11:d=CM(null,d,E,f,x);break e;case 14:d=RM(null,d,E,fo(E.type,f),x);break e}throw Error(o(306,E,""))}return d;case 0:return E=d.type,I=d.pendingProps,I=d.elementType===E?I:fo(E,I),Sx(f,d,E,I,x);case 1:return E=d.type,I=d.pendingProps,I=d.elementType===E?I:fo(E,I),OM(f,d,E,I,x);case 3:e:{if(LM(d),f===null)throw Error(o(387));E=d.pendingProps,F=d.memoizedState,I=F.element,HA(f,d),Ym(d,E,null,x);var Q=d.memoizedState;if(E=Q.element,ft&&F.isDehydrated)if(F={element:E,isDehydrated:!1,cache:Q.cache,transitions:Q.transitions},d.updateQueue.baseState=F,d.memoizedState=F,d.flags&256){I=Error(o(423)),d=PM(f,d,E,x,I);break e}else if(E!==I){I=Error(o(424)),d=PM(f,d,E,x,I);break e}else for(ft&&(vs=Dm(d.stateNode.containerInfo),_s=d,$n=!0,po=null,dd=!1),x=tM(d,null,E,x),d.child=x;x;)x.flags=x.flags&-3|4096,x=x.sibling;else{if(_h(),E===I){d=Xa(f,d,x);break e}Ai(f,d,E,x)}d=d.child}return d;case 5:return nM(d),f===null&&ax(d),E=d.type,I=d.pendingProps,F=f!==null?f.memoizedProps:null,Q=I.children,ie(E,I)?Q=null:F!==null&&ie(E,F)&&(d.flags|=32),NM(f,d),Ai(f,d,Q,x),d.child;case 6:return f===null&&ax(d),null;case 13:return DM(f,d,x);case 4:return lx(d,d.stateNode.containerInfo),E=d.pendingProps,f===null?d.child=vh(d,null,E,x):Ai(f,d,E,x),d.child;case 11:return E=d.type,I=d.pendingProps,I=d.elementType===E?I:fo(E,I),CM(f,d,E,I,x);case 7:return Ai(f,d,d.pendingProps,x),d.child;case 8:return Ai(f,d,d.pendingProps.children,x),d.child;case 12:return Ai(f,d,d.pendingProps.children,x),d.child;case 10:e:{if(E=d.type._context,I=d.pendingProps,F=d.memoizedProps,Q=I.value,VA(d,E,Q),F!==null)if(Ko(F.value,Q)){if(F.children===I.children&&!Wn.current){d=Xa(f,d,x);break e}}else for(F=d.child,F!==null&&(F.return=d);F!==null;){var ae=F.dependencies;if(ae!==null){Q=F.child;for(var Re=ae.firstContext;Re!==null;){if(Re.context===E){if(F.tag===1){Re=Wa(-1,x&-x),Re.tag=2;var Ue=F.updateQueue;if(Ue!==null){Ue=Ue.shared;var ot=Ue.pending;ot===null?Re.next=Re:(Re.next=ot.next,ot.next=Re),Ue.pending=Re}}F.lanes|=x,Re=F.alternate,Re!==null&&(Re.lanes|=x),ex(F.return,x,d),ae.lanes|=x;break}Re=Re.next}}else if(F.tag===10)Q=F.type===d.type?null:F.child;else if(F.tag===18){if(Q=F.return,Q===null)throw Error(o(341));Q.lanes|=x,ae=Q.alternate,ae!==null&&(ae.lanes|=x),ex(Q,x,d),Q=F.sibling}else Q=F.child;if(Q!==null)Q.return=F;else for(Q=F;Q!==null;){if(Q===d){Q=null;break}if(F=Q.sibling,F!==null){F.return=Q.return,Q=F;break}Q=Q.return}F=Q}Ai(f,d,I.children,x),d=d.child}return d;case 9:return I=d.type,E=d.pendingProps.children,ph(d,x),I=Ds(I),E=E(I),d.flags|=1,Ai(f,d,E,x),d.child;case 14:return E=d.type,I=fo(E,d.pendingProps),I=fo(E.type,I),RM(f,d,E,I,x);case 15:return kM(f,d,d.type,d.pendingProps,x);case 17:return E=d.type,I=d.pendingProps,I=d.elementType===E?I:fo(E,I),f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),d.tag=1,lr(E)?(f=!0,bi(d)):f=!1,ph(d,x),qA(d,E,I),rx(d,E,I,x),Ex(null,d,E,!0,f,x);case 19:return zM(f,d,x);case 22:return IM(f,d,x)}throw Error(o(156,d.tag))};function uC(f,d){return qy(f,d)}function UF(f,d,x,E){this.tag=f,this.key=x,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=d,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=E,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Hs(f,d,x,E){return new UF(f,d,x,E)}function Wx(f){return f=f.prototype,!(!f||!f.isReactComponent)}function FF(f){if(typeof f=="function")return Wx(f)?1:0;if(f!=null){if(f=f.$$typeof,f===v)return 11;if(f===S)return 14}return 2}function nl(f,d){var x=f.alternate;return x===null?(x=Hs(f.tag,d,f.key,f.mode),x.elementType=f.elementType,x.type=f.type,x.stateNode=f.stateNode,x.alternate=f,f.alternate=x):(x.pendingProps=d,x.type=f.type,x.flags=0,x.subtreeFlags=0,x.deletions=null),x.flags=f.flags&14680064,x.childLanes=f.childLanes,x.lanes=f.lanes,x.child=f.child,x.memoizedProps=f.memoizedProps,x.memoizedState=f.memoizedState,x.updateQueue=f.updateQueue,d=f.dependencies,x.dependencies=d===null?null:{lanes:d.lanes,firstContext:d.firstContext},x.sibling=f.sibling,x.index=f.index,x.ref=f.ref,x}function Ig(f,d,x,E,I,F){var Q=2;if(E=f,typeof f=="function")Wx(f)&&(Q=1);else if(typeof f=="string")Q=5;else e:switch(f){case u:return tu(x.children,I,F,d);case h:Q=8,I|=8;break;case p:return f=Hs(12,x,d,I|2),f.elementType=p,f.lanes=F,f;case y:return f=Hs(13,x,d,I),f.elementType=y,f.lanes=F,f;case _:return f=Hs(19,x,d,I),f.elementType=_,f.lanes=F,f;case T:return Ng(x,I,F,d);default:if(typeof f=="object"&&f!==null)switch(f.$$typeof){case m:Q=10;break e;case g:Q=9;break e;case v:Q=11;break e;case S:Q=14;break e;case w:Q=16,E=null;break e}throw Error(o(130,f==null?f:typeof f,""))}return d=Hs(Q,x,d,I),d.elementType=f,d.type=E,d.lanes=F,d}function tu(f,d,x,E){return f=Hs(7,f,E,d),f.lanes=x,f}function Ng(f,d,x,E){return f=Hs(22,f,E,d),f.elementType=T,f.lanes=x,f.stateNode={},f}function jx(f,d,x){return f=Hs(6,f,null,d),f.lanes=x,f}function $x(f,d,x){return d=Hs(4,f.children!==null?f.children:[],f.key,d),d.lanes=x,d.stateNode={containerInfo:f.containerInfo,pendingChildren:null,implementation:f.implementation},d}function BF(f,d,x,E,I){this.tag=d,this.containerInfo=f,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Le,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=jy(0),this.expirationTimes=jy(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=jy(0),this.identifierPrefix=E,this.onRecoverableError=I,ft&&(this.mutableSourceEagerHydrationData=null)}function hC(f,d,x,E,I,F,Q,ae,Re){return f=new BF(f,d,x,ae,Re),d===1?(d=1,F===!0&&(d|=8)):d=0,F=Hs(3,null,null,d),f.current=F,F.stateNode=f,F.memoizedState={element:E,isDehydrated:x,cache:null,transitions:null},tx(F),f}function fC(f){if(!f)return zt;f=f._reactInternals;e:{if(M(f)!==f||f.tag!==1)throw Error(o(170));var d=f;do{switch(d.tag){case 3:d=d.stateNode.context;break e;case 1:if(lr(d.type)){d=d.stateNode.__reactInternalMemoizedMergedChildContext;break e}}d=d.return}while(d!==null);throw Error(o(171))}if(f.tag===1){var x=f.type;if(lr(x))return Tn(f,x,d)}return d}function dC(f){var d=f._reactInternals;if(d===void 0)throw typeof f.render=="function"?Error(o(188)):(f=Object.keys(f).join(","),Error(o(268,f)));return f=L(d),f===null?null:f.stateNode}function pC(f,d){if(f=f.memoizedState,f!==null&&f.dehydrated!==null){var x=f.retryLane;f.retryLane=x!==0&&x=Ue&&F>=Nt&&I<=ot&&Q<=xt){f.splice(d,1);break}else if(E!==Ue||x.width!==Re.width||xtQ){if(!(F!==Nt||x.height!==Re.height||otI)){Ue>E&&(Re.width+=Ue-E,Re.x=E),otF&&(Re.height+=Nt-F,Re.y=F),xtx&&(x=Q)),Q ")+` - -No matching component was found for: - `)+f.join(" > ")}return null},t.getPublicRootInstance=function(f){if(f=f.current,!f.child)return null;switch(f.child.tag){case 5:return W(f.child.stateNode);default:return f.child.stateNode}},t.injectIntoDevTools=function(f){if(f={bundleType:f.bundleType,version:f.version,rendererPackageName:f.rendererPackageName,rendererConfig:f.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:a.ReactCurrentDispatcher,findHostInstanceByFiber:zF,findFiberByHostInstance:f.findFiberByHostInstance||VF,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.0.0-fc46dba67-20220329"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")f=!1;else{var d=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(d.isDisabled||!d.supportsFiber)f=!0;else{try{Wm=d.inject(f),Xo=d}catch{}f=!!d.checkDCE}}return f},t.isAlreadyRendering=function(){return!1},t.observeVisibleRects=function(f,d,x,E){if(!oe)throw Error(o(363));f=Ox(f,d);var I=Be(f,x,E).disconnect;return{disconnect:function(){I()}}},t.registerMutableSourceForHydration=function(f,d){var x=d._getVersion;x=x(d._source),f.mutableSourceEagerHydrationData==null?f.mutableSourceEagerHydrationData=[d,x]:f.mutableSourceEagerHydrationData.push(d,x)},t.runWithPriority=function(f,d){var x=pn;try{return pn=f,d()}finally{pn=x}},t.shouldError=function(){return null},t.shouldSuspend=function(){return!1},t.updateContainer=function(f,d,x,E){var I=d.current,F=Mi(),Q=el(I);return x=fC(x),d.context===null?d.context=x:d.pendingContext=x,d=Wa(F,Q),d.payload={element:f},E=E===void 0?null:E,E!==null&&(d.callback=E),Zc(I,d),f=Vs(I,Q,F),f!==null&&Km(f,I,Q),Q},t};rO.exports=$H;var qH=rO.exports;const XH=Nc(qH),iT={},sT=n=>void Object.assign(iT,n);function KH(n,e){function t(u,{args:h=[],attach:p,...m},g){let v=`${u[0].toUpperCase()}${u.slice(1)}`,y;if(u==="primitive"){if(m.object===void 0)throw new Error("R3F: Primitives without 'object' are invalid!");const _=m.object;y=Xh(_,{type:u,root:g,attach:p,primitive:!0})}else{const _=iT[v];if(!_)throw new Error(`R3F: ${v} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);if(!Array.isArray(h))throw new Error("R3F: The args prop must be an array!");y=Xh(new _(...h),{type:u,root:g,attach:p,memoizedProps:{args:h}})}return y.__r3f.attach===void 0&&(y instanceof Do?y.__r3f.attach="geometry":y instanceof Lc&&(y.__r3f.attach="material")),v!=="inject"&&bS(y,m),y}function r(u,h){let p=!1;if(h){var m,g;(m=h.__r3f)!=null&&m.attach?TS(u,h,h.__r3f.attach):h.isObject3D&&u.isObject3D&&(u.add(h),p=!0),p||(g=u.__r3f)==null||g.objects.push(h),h.__r3f||Xh(h,{}),h.__r3f.parent=u,mE(h),Kh(h)}}function i(u,h,p){let m=!1;if(h){var g,v;if((g=h.__r3f)!=null&&g.attach)TS(u,h,h.__r3f.attach);else if(h.isObject3D&&u.isObject3D){h.parent=u,h.dispatchEvent({type:"added"}),u.dispatchEvent({type:"childadded",child:h});const y=u.children.filter(S=>S!==h),_=y.indexOf(p);u.children=[...y.slice(0,_),h,...y.slice(_)],m=!0}m||(v=u.__r3f)==null||v.objects.push(h),h.__r3f||Xh(h,{}),h.__r3f.parent=u,mE(h),Kh(h)}}function s(u,h,p=!1){u&&[...u].forEach(m=>o(h,m,p))}function o(u,h,p){if(h){var m,g,v;if(h.__r3f&&(h.__r3f.parent=null),(m=u.__r3f)!=null&&m.objects&&(u.__r3f.objects=u.__r3f.objects.filter(T=>T!==h)),(g=h.__r3f)!=null&&g.attach)RR(u,h,h.__r3f.attach);else if(h.isObject3D&&u.isObject3D){var y;u.remove(h),(y=h.__r3f)!=null&&y.root&&iG(W0(h),h)}const S=(v=h.__r3f)==null?void 0:v.primitive,w=!S&&(p===void 0?h.dispose!==null:p);if(!S){var _;s((_=h.__r3f)==null?void 0:_.objects,h,w),s(h.children,h,w)}if(delete h.__r3f,w&&h.dispose&&h.type!=="Scene"){const T=()=>{try{h.dispose()}catch{}};typeof IS_REACT_ACT_ENVIRONMENT>"u"?dE.unstable_scheduleCallback(dE.unstable_IdlePriority,T):T()}Kh(u)}}function a(u,h,p,m){var g;const v=(g=u.__r3f)==null?void 0:g.parent;if(!v)return;const y=t(h,p,u.__r3f.root);if(u.children){for(const _ of u.children)_.__r3f&&r(y,_);u.children=u.children.filter(_=>!_.__r3f)}u.__r3f.objects.forEach(_=>r(y,_)),u.__r3f.objects=[],u.__r3f.autoRemovedBeforeAppend||o(v,u),y.parent&&(y.__r3f.autoRemovedBeforeAppend=!0),r(v,y),y.raycast&&y.__r3f.eventCount&&W0(y).getState().internal.interaction.push(y),[m,m.alternate].forEach(_=>{_!==null&&(_.stateNode=y,_.ref&&(typeof _.ref=="function"?_.ref(y):_.ref.current=y))})}const c=()=>{};return{reconciler:XH({createInstance:t,removeChild:o,appendChild:r,appendInitialChild:r,insertBefore:i,supportsMutation:!0,isPrimaryRenderer:!1,supportsPersistence:!1,supportsHydration:!1,noTimeout:-1,appendChildToContainer:(u,h)=>{if(!h)return;const p=u.getState().scene;p.__r3f&&(p.__r3f.root=u,r(p,h))},removeChildFromContainer:(u,h)=>{h&&o(u.getState().scene,h)},insertInContainerBefore:(u,h,p)=>{if(!h||!p)return;const m=u.getState().scene;m.__r3f&&i(m,h,p)},getRootHostContext:()=>null,getChildHostContext:u=>u,finalizeInitialChildren(u){var h;return!!((h=u==null?void 0:u.__r3f)!=null?h:{}).handlers},prepareUpdate(u,h,p,m){var g;if(((g=u==null?void 0:u.__r3f)!=null?g:{}).primitive&&m.object&&m.object!==u)return[!0];{const{args:y=[],children:_,...S}=m,{args:w=[],children:T,...k}=p;if(!Array.isArray(y))throw new Error("R3F: the args prop must be an array!");if(y.some((C,O)=>C!==w[O]))return[!0];const R=uO(u,S,k,!0);return R.changes.length?[!1,R]:null}},commitUpdate(u,[h,p],m,g,v,y){h?a(u,m,v,y):bS(u,p)},commitMount(u,h,p,m){var g;const v=(g=u.__r3f)!=null?g:{};u.raycast&&v.handlers&&v.eventCount&&W0(u).getState().internal.interaction.push(u)},getPublicInstance:u=>u,prepareForCommit:()=>null,preparePortalMount:u=>Xh(u.getState().scene),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,hideInstance(u){var h;const{attach:p,parent:m}=(h=u.__r3f)!=null?h:{};p&&m&&RR(m,u,p),u.isObject3D&&(u.visible=!1),Kh(u)},unhideInstance(u,h){var p;const{attach:m,parent:g}=(p=u.__r3f)!=null?p:{};m&&g&&TS(g,u,m),(u.isObject3D&&h.visible==null||h.visible)&&(u.visible=!0),Kh(u)},createTextInstance:c,hideTextInstance:c,unhideTextInstance:c,getCurrentEventPriority:()=>e?e():nf.DefaultEventPriority,beforeActiveInstanceBlur:()=>{},afterActiveInstanceBlur:()=>{},detachDeletedInstance:()=>{},now:typeof performance<"u"&&On.fun(performance.now)?performance.now:On.fun(Date.now)?Date.now:()=>0,scheduleTimeout:On.fun(setTimeout)?setTimeout:void 0,cancelTimeout:On.fun(clearTimeout)?clearTimeout:void 0}),applyProps:bS}}var bR,AR;const wS=n=>"colorSpace"in n||"outputColorSpace"in n,oO=()=>{var n;return(n=iT.ColorManagement)!=null?n:null},aO=n=>n&&n.isOrthographicCamera,wv=typeof window<"u"&&((bR=window.document)!=null&&bR.createElement||((AR=window.navigator)==null?void 0:AR.product)==="ReactNative")?ke.useLayoutEffect:ke.useEffect;function YH(n){const e=ke.useRef(n);return wv(()=>void(e.current=n),[n]),e}class ZH extends ke.Component{constructor(...e){super(...e),this.state={error:!1}}componentDidCatch(e){this.props.set(e)}render(){return this.state.error?null:this.props.children}}ZH.getDerivedStateFromError=()=>({error:!0});const cO="__default",MR=new Map,QH=n=>n&&!!n.memoized&&!!n.changes;function lO(n){var e;const t=typeof window<"u"?(e=window.devicePixelRatio)!=null?e:2:1;return Array.isArray(n)?Math.min(Math.max(n[0],t),n[1]):n}const Ld=n=>{var e;return(e=n.__r3f)==null?void 0:e.root.getState()};function W0(n){let e=n.__r3f.root;for(;e.getState().previousRoot;)e=e.getState().previousRoot;return e}const On={obj:n=>n===Object(n)&&!On.arr(n)&&typeof n!="function",fun:n=>typeof n=="function",str:n=>typeof n=="string",num:n=>typeof n=="number",boo:n=>typeof n=="boolean",und:n=>n===void 0,arr:n=>Array.isArray(n),equ(n,e,{arrays:t="shallow",objects:r="reference",strict:i=!0}={}){if(typeof n!=typeof e||!!n!=!!e)return!1;if(On.str(n)||On.num(n)||On.boo(n))return n===e;const s=On.obj(n);if(s&&r==="reference")return n===e;const o=On.arr(n);if(o&&t==="reference")return n===e;if((o||s)&&n===e)return!0;let a;for(a in n)if(!(a in e))return!1;if(s&&t==="shallow"&&r==="shallow"){for(a in i?e:n)if(!On.equ(n[a],e[a],{strict:i,objects:"reference"}))return!1}else for(a in i?e:n)if(n[a]!==e[a])return!1;if(On.und(a)){if(o&&n.length===0&&e.length===0||s&&Object.keys(n).length===0&&Object.keys(e).length===0)return!0;if(n!==e)return!1}return!0}};function JH(n){const e={nodes:{},materials:{}};return n&&n.traverse(t=>{t.name&&(e.nodes[t.name]=t),t.material&&!e.materials[t.material.name]&&(e.materials[t.material.name]=t.material)}),e}function eG(n){n.dispose&&n.type!=="Scene"&&n.dispose();for(const e in n)e.dispose==null||e.dispose(),delete n[e]}function Xh(n,e){const t=n;return t.__r3f={type:"",root:null,previousAttach:null,memoizedProps:{},eventCount:0,handlers:{},objects:[],parent:null,...e},n}function pE(n,e){let t=n;if(e.includes("-")){const r=e.split("-"),i=r.pop();return t=r.reduce((s,o)=>s[o],n),{target:t,key:i}}else return{target:t,key:e}}const CR=/-\d+$/;function TS(n,e,t){if(On.str(t)){if(CR.test(t)){const s=t.replace(CR,""),{target:o,key:a}=pE(n,s);Array.isArray(o[a])||(o[a]=[])}const{target:r,key:i}=pE(n,t);e.__r3f.previousAttach=r[i],r[i]=e}else e.__r3f.previousAttach=t(n,e)}function RR(n,e,t){var r,i;if(On.str(t)){const{target:s,key:o}=pE(n,t),a=e.__r3f.previousAttach;a===void 0?delete s[o]:s[o]=a}else(r=e.__r3f)==null||r.previousAttach==null||r.previousAttach(n,e);(i=e.__r3f)==null||delete i.previousAttach}function uO(n,{children:e,key:t,ref:r,...i},{children:s,key:o,ref:a,...c}={},l=!1){const u=n.__r3f,h=Object.entries(i),p=[];if(l){const g=Object.keys(c);for(let v=0;v{var y;if((y=n.__r3f)!=null&&y.primitive&&g==="object"||On.equ(v,c[g]))return;if(/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(g))return p.push([g,v,!0,[]]);let _=[];g.includes("-")&&(_=g.split("-")),p.push([g,v,!1,_]);for(const S in i){const w=i[S];S.startsWith(`${g}-`)&&p.push([S,w,!1,S.split("-")])}});const m={...i};return u!=null&&u.memoizedProps&&u!=null&&u.memoizedProps.args&&(m.args=u.memoizedProps.args),u!=null&&u.memoizedProps&&u!=null&&u.memoizedProps.attach&&(m.attach=u.memoizedProps.attach),{memoized:m,changes:p}}const tG=typeof process<"u"&&!1;function bS(n,e){var t;const r=n.__r3f,i=r==null?void 0:r.root,s=i==null||i.getState==null?void 0:i.getState(),{memoized:o,changes:a}=QH(e)?e:uO(n,e),c=r==null?void 0:r.eventCount;n.__r3f&&(n.__r3f.memoizedProps=o);for(let u=0;u_[S],n),!(y&&y.set))){const[_,...S]=g.reverse();v=S.reverse().reduce((w,T)=>w[T],n),h=_}if(p===cO+"remove")if(v.constructor){let _=MR.get(v.constructor);_||(_=new v.constructor,MR.set(v.constructor,_)),p=_[h]}else p=0;if(m&&r)p?r.handlers[h]=p:delete r.handlers[h],r.eventCount=Object.keys(r.handlers).length;else if(y&&y.set&&(y.copy||y instanceof pf)){if(Array.isArray(p))y.fromArray?y.fromArray(p):y.set(...p);else if(y.copy&&p&&p.constructor&&(tG?y.constructor.name===p.constructor.name:y.constructor===p.constructor))y.copy(p);else if(p!==void 0){const _=y instanceof cn;!_&&y.setScalar?y.setScalar(p):y instanceof pf&&p instanceof pf?y.mask=p.mask:y.set(p),!oO()&&s&&!s.linear&&_&&y.convertSRGBToLinear()}}else if(v[h]=p,v[h]instanceof or&&v[h].format===Qs&&v[h].type===Ei&&s){const _=v[h];wS(_)&&wS(s.gl)?_.colorSpace=s.gl.outputColorSpace:_.encoding=s.gl.outputEncoding}Kh(n)}if(r&&r.parent&&n.raycast&&c!==r.eventCount){const u=W0(n).getState().internal,h=u.interaction.indexOf(n);h>-1&&u.interaction.splice(h,1),r.eventCount&&u.interaction.push(n)}return!(a.length===1&&a[0][0]==="onUpdate")&&a.length&&(t=n.__r3f)!=null&&t.parent&&mE(n),n}function Kh(n){var e,t;const r=(e=n.__r3f)==null||(t=e.root)==null||t.getState==null?void 0:t.getState();r&&r.internal.frames===0&&r.invalidate()}function mE(n){n.onUpdate==null||n.onUpdate(n)}function nG(n,e){n.manual||(aO(n)?(n.left=e.width/-2,n.right=e.width/2,n.top=e.height/2,n.bottom=e.height/-2):n.aspect=e.width/e.height,n.updateProjectionMatrix(),n.updateMatrixWorld())}function r0(n){return(n.eventObject||n.object).uuid+"/"+n.index+n.instanceId}function rG(){var n;const e=typeof self<"u"&&self||typeof window<"u"&&window;if(!e)return nf.DefaultEventPriority;switch((n=e.event)==null?void 0:n.type){case"click":case"contextmenu":case"dblclick":case"pointercancel":case"pointerdown":case"pointerup":return nf.DiscreteEventPriority;case"pointermove":case"pointerout":case"pointerover":case"pointerenter":case"pointerleave":case"wheel":return nf.ContinuousEventPriority;default:return nf.DefaultEventPriority}}function hO(n,e,t,r){const i=t.get(e);i&&(t.delete(e),t.size===0&&(n.delete(r),i.target.releasePointerCapture(r)))}function iG(n,e){const{internal:t}=n.getState();t.interaction=t.interaction.filter(r=>r!==e),t.initialHits=t.initialHits.filter(r=>r!==e),t.hovered.forEach((r,i)=>{(r.eventObject===e||r.object===e)&&t.hovered.delete(i)}),t.capturedMap.forEach((r,i)=>{hO(t.capturedMap,e,r,i)})}function sG(n){function e(c){const{internal:l}=n.getState(),u=c.offsetX-l.initialClick[0],h=c.offsetY-l.initialClick[1];return Math.round(Math.sqrt(u*u+h*h))}function t(c){return c.filter(l=>["Move","Over","Enter","Out","Leave"].some(u=>{var h;return(h=l.__r3f)==null?void 0:h.handlers["onPointer"+u]}))}function r(c,l){const u=n.getState(),h=new Set,p=[],m=l?l(u.internal.interaction):u.internal.interaction;for(let _=0;_{const w=Ld(_.object),T=Ld(S.object);return!w||!T?_.distance-S.distance:T.events.priority-w.events.priority||_.distance-S.distance}).filter(_=>{const S=r0(_);return h.has(S)?!1:(h.add(S),!0)});u.events.filter&&(v=u.events.filter(v,u));for(const _ of v){let S=_.object;for(;S;){var y;(y=S.__r3f)!=null&&y.eventCount&&p.push({..._,eventObject:S}),S=S.parent}}if("pointerId"in c&&u.internal.capturedMap.has(c.pointerId))for(let _ of u.internal.capturedMap.get(c.pointerId).values())h.has(r0(_.intersection))||p.push(_.intersection);return p}function i(c,l,u,h){const p=n.getState();if(c.length){const m={stopped:!1};for(const g of c){const v=Ld(g.object)||p,{raycaster:y,pointer:_,camera:S,internal:w}=v,T=new xe(_.x,_.y,0).unproject(S),k=N=>{var U,L;return(U=(L=w.capturedMap.get(N))==null?void 0:L.has(g.eventObject))!=null?U:!1},R=N=>{const U={intersection:g,target:l.target};w.capturedMap.has(N)?w.capturedMap.get(N).set(g.eventObject,U):w.capturedMap.set(N,new Map([[g.eventObject,U]])),l.target.setPointerCapture(N)},C=N=>{const U=w.capturedMap.get(N);U&&hO(w.capturedMap,g.eventObject,U,N)};let O={};for(let N in l){let U=l[N];typeof U!="function"&&(O[N]=U)}let M={...g,...O,pointer:_,intersections:c,stopped:m.stopped,delta:u,unprojectedPoint:T,ray:y.ray,camera:S,stopPropagation(){const N="pointerId"in l&&w.capturedMap.get(l.pointerId);if((!N||N.has(g.eventObject))&&(M.stopped=m.stopped=!0,w.hovered.size&&Array.from(w.hovered.values()).find(U=>U.eventObject===g.eventObject))){const U=c.slice(0,c.indexOf(g));s([...U,g])}},target:{hasPointerCapture:k,setPointerCapture:R,releasePointerCapture:C},currentTarget:{hasPointerCapture:k,setPointerCapture:R,releasePointerCapture:C},nativeEvent:l};if(h(M),m.stopped===!0)break}}return c}function s(c){const{internal:l}=n.getState();for(const u of l.hovered.values())if(!c.length||!c.find(h=>h.object===u.object&&h.index===u.index&&h.instanceId===u.instanceId)){const p=u.eventObject.__r3f,m=p==null?void 0:p.handlers;if(l.hovered.delete(r0(u)),p!=null&&p.eventCount){const g={...u,intersections:c};m.onPointerOut==null||m.onPointerOut(g),m.onPointerLeave==null||m.onPointerLeave(g)}}}function o(c,l){for(let u=0;us([]);case"onLostPointerCapture":return l=>{const{internal:u}=n.getState();"pointerId"in l&&u.capturedMap.has(l.pointerId)&&requestAnimationFrame(()=>{u.capturedMap.has(l.pointerId)&&(u.capturedMap.delete(l.pointerId),s([]))})}}return function(u){const{onPointerMissed:h,internal:p}=n.getState();p.lastEvent.current=u;const m=c==="onPointerMove",g=c==="onClick"||c==="onContextMenu"||c==="onDoubleClick",y=r(u,m?t:void 0),_=g?e(u):0;c==="onPointerDown"&&(p.initialClick=[u.offsetX,u.offsetY],p.initialHits=y.map(w=>w.eventObject)),g&&!y.length&&_<=2&&(o(u,p.interaction),h&&h(u)),m&&s(y);function S(w){const T=w.eventObject,k=T.__r3f,R=k==null?void 0:k.handlers;if(k!=null&&k.eventCount)if(m){if(R.onPointerOver||R.onPointerEnter||R.onPointerOut||R.onPointerLeave){const C=r0(w),O=p.hovered.get(C);O?O.stopped&&w.stopPropagation():(p.hovered.set(C,w),R.onPointerOver==null||R.onPointerOver(w),R.onPointerEnter==null||R.onPointerEnter(w))}R.onPointerMove==null||R.onPointerMove(w)}else{const C=R[c];C?(!g||p.initialHits.includes(T))&&(o(u,p.interaction.filter(O=>!p.initialHits.includes(O))),C(w)):g&&p.initialHits.includes(T)&&o(u,p.interaction.filter(O=>!p.initialHits.includes(O)))}}i(y,u,_,S)}}return{handlePointer:a}}const fO=n=>!!(n!=null&&n.render),dO=ke.createContext(null),oG=(n,e)=>{const t=VH((a,c)=>{const l=new xe,u=new xe,h=new xe;function p(_=c().camera,S=u,w=c().size){const{width:T,height:k,top:R,left:C}=w,O=T/k;S instanceof xe?h.copy(S):h.set(...S);const M=_.getWorldPosition(l).distanceTo(h);if(aO(_))return{width:T/_.zoom,height:k/_.zoom,top:R,left:C,factor:1,distance:M,aspect:O};{const N=_.fov*Math.PI/180,U=2*Math.tan(N/2)*M,L=U*(T/k);return{width:L,height:U,top:R,left:C,factor:T/L,distance:M,aspect:O}}}let m;const g=_=>a(S=>({performance:{...S.performance,current:_}})),v=new St;return{set:a,get:c,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},xr:null,scene:null,invalidate:(_=1)=>n(c(),_),advance:(_,S)=>e(_,S,c()),legacy:!1,linear:!1,flat:!1,controls:null,clock:new DH,pointer:v,mouse:v,frameloop:"always",onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{const _=c();m&&clearTimeout(m),_.performance.current!==_.performance.min&&g(_.performance.min),m=setTimeout(()=>g(c().performance.max),_.performance.debounce)}},size:{width:0,height:0,top:0,left:0,updateStyle:!1},viewport:{initialDpr:0,dpr:0,width:0,height:0,top:0,left:0,aspect:0,distance:0,factor:0,getCurrentViewport:p},setEvents:_=>a(S=>({...S,events:{...S.events,..._}})),setSize:(_,S,w,T,k)=>{const R=c().camera,C={width:_,height:S,top:T||0,left:k||0,updateStyle:w};a(O=>({size:C,viewport:{...O.viewport,...p(R,u,C)}}))},setDpr:_=>a(S=>{const w=lO(_);return{viewport:{...S.viewport,dpr:w,initialDpr:S.viewport.initialDpr||w}}}),setFrameloop:(_="always")=>{const S=c().clock;S.stop(),S.elapsedTime=0,_!=="never"&&(S.start(),S.elapsedTime=0),a(()=>({frameloop:_}))},previousRoot:void 0,internal:{active:!1,priority:0,frames:0,lastEvent:ke.createRef(),interaction:[],hovered:new Map,subscribers:[],initialClick:[0,0],initialHits:[],capturedMap:new Map,subscribe:(_,S,w)=>{const T=c().internal;return T.priority=T.priority+(S>0?1:0),T.subscribers.push({ref:_,priority:S,store:w}),T.subscribers=T.subscribers.sort((k,R)=>k.priority-R.priority),()=>{const k=c().internal;k!=null&&k.subscribers&&(k.priority=k.priority-(S>0?1:0),k.subscribers=k.subscribers.filter(R=>R.ref!==_))}}}}}),r=t.getState();let i=r.size,s=r.viewport.dpr,o=r.camera;return t.subscribe(()=>{const{camera:a,size:c,viewport:l,gl:u,set:h}=t.getState();if(c.width!==i.width||c.height!==i.height||l.dpr!==s){var p;i=c,s=l.dpr,nG(a,c),u.setPixelRatio(l.dpr);const m=(p=c.updateStyle)!=null?p:typeof HTMLCanvasElement<"u"&&u.domElement instanceof HTMLCanvasElement;u.setSize(c.width,c.height,m)}a!==o&&(o=a,h(m=>({viewport:{...m.viewport,...m.viewport.getCurrentViewport(a)}})))}),t.subscribe(a=>n(a)),t};function pO(n,e){const t={callback:n};return e.add(t),()=>void e.delete(t)}let i0,mO=new Set,gO=new Set,aG=new Set;const cG=n=>pO(n,mO),lG=n=>pO(n,gO);function AS(n,e){if(n.size)for(const{callback:t}of n.values())t(e)}function Pd(n,e){switch(n){case"before":return AS(mO,e);case"after":return AS(gO,e);case"tail":return AS(aG,e)}}let MS,CS;function RS(n,e,t){let r=e.clock.getDelta();for(e.frameloop==="never"&&typeof n=="number"&&(r=n-e.clock.elapsedTime,e.clock.oldTime=e.clock.elapsedTime,e.clock.elapsedTime=n),MS=e.internal.subscribers,i0=0;i00)&&!((u=s.gl.xr)!=null&&u.isPresenting)&&(r+=RS(l,s))}if(t=!1,Pd("after",l),r===0)return Pd("tail",l),e=!1,cancelAnimationFrame(i)}function a(l,u=1){var h;if(!l)return n.forEach(p=>a(p.store.getState(),u));(h=l.gl.xr)!=null&&h.isPresenting||!l.internal.active||l.frameloop==="never"||(u>1?l.internal.frames=Math.min(60,l.internal.frames+u):t?l.internal.frames=2:l.internal.frames=1,e||(e=!0,requestAnimationFrame(o)))}function c(l,u=!0,h,p){if(u&&Pd("before",l),h)RS(l,h,p);else for(const m of n.values())RS(l,m.store.getState());u&&Pd("after",l)}return{loop:o,invalidate:a,advance:c}}function hG(n){const e=ke.useRef(null);return wv(()=>void(e.current=n.current.__r3f),[n]),e}function _O(){const n=ke.useContext(dO);if(!n)throw new Error("R3F: Hooks can only be used within the Canvas component!");return n}function pa(n=t=>t,e){return _O()(n,e)}function Tv(n,e=0){const t=_O(),r=t.getState().internal.subscribe,i=YH(n);return wv(()=>r(i,e,t),[e,r,t]),null}const kR=new WeakMap;function vO(n,e){return function(t,...r){let i=kR.get(t);return i||(i=new t,kR.set(t,i)),n&&n(i),Promise.all(r.map(s=>new Promise((o,a)=>i.load(s,c=>{c.scene&&Object.assign(c,JH(c.scene)),o(c)},e,c=>a(new Error(`Could not load ${s}: ${c==null?void 0:c.message}`))))))}}function Wp(n,e,t,r){const i=Array.isArray(e)?e:[e],s=GH(vO(t,r),[n,...i],{equal:On.equ});return Array.isArray(e)?s:s[0]}Wp.preload=function(n,e,t){const r=Array.isArray(e)?e:[e];return WH(vO(t),[n,...r])};Wp.clear=function(n,e){const t=Array.isArray(e)?e:[e];return jH([n,...t])};const Cf=new Map,{invalidate:IR,advance:NR}=uG(Cf),{reconciler:v_,applyProps:Bh}=KH(Cf,rG),zh={objects:"shallow",strict:!1},fG=(n,e)=>{const t=typeof n=="function"?n(e):n;return fO(t)?t:new CH({powerPreference:"high-performance",canvas:e,antialias:!0,alpha:!0,...n})};function dG(n,e){const t=typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement;if(e){const{width:r,height:i,top:s,left:o,updateStyle:a=t}=e;return{width:r,height:i,top:s,left:o,updateStyle:a}}else if(typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&n.parentElement){const{width:r,height:i,top:s,left:o}=n.parentElement.getBoundingClientRect();return{width:r,height:i,top:s,left:o,updateStyle:t}}else if(typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas)return{width:n.width,height:n.height,top:0,left:0,updateStyle:t};return{width:0,height:0,top:0,left:0}}function pG(n){const e=Cf.get(n),t=e==null?void 0:e.fiber,r=e==null?void 0:e.store;e&&console.warn("R3F.createRoot should only be called once!");const i=typeof reportError=="function"?reportError:console.error,s=r||oG(IR,NR),o=t||v_.createContainer(s,nf.ConcurrentRoot,null,!1,null,"",i,null);e||Cf.set(n,{fiber:o,store:s});let a,c=!1,l;return{configure(u={}){let{gl:h,size:p,scene:m,events:g,onCreated:v,shadows:y=!1,linear:_=!1,flat:S=!1,legacy:w=!1,orthographic:T=!1,frameloop:k="always",dpr:R=[1,2],performance:C,raycaster:O,camera:M,onPointerMissed:N}=u,U=s.getState(),L=U.gl;U.gl||U.set({gl:L=fG(h,n)});let P=U.raycaster;P||U.set({raycaster:P=new UH});const{params:b,...B}=O||{};if(On.equ(B,P,zh)||Bh(P,{...B}),On.equ(b,P.params,zh)||Bh(P,{params:{...P.params,...b}}),!U.camera||U.camera===l&&!On.equ(l,M,zh)){l=M;const Z=M instanceof xv,X=Z?M:T?new Sv(0,0,0,0,.1,1e3):new Ts(75,0,.1,1e3);Z||(X.position.z=5,M&&(Bh(X,M),("aspect"in M||"left"in M||"right"in M||"bottom"in M||"top"in M)&&(X.manual=!0,X.updateProjectionMatrix())),!U.camera&&!(M!=null&&M.rotation)&&X.lookAt(0,0,0)),U.set({camera:X}),P.camera=X}if(!U.scene){let Z;m instanceof __?Z=m:(Z=new __,m&&Bh(Z,m)),U.set({scene:Xh(Z)})}if(!U.xr){var W;const Z=(ve,ne)=>{const ie=s.getState();ie.frameloop!=="never"&&NR(ve,!0,ie,ne)},X=()=>{const ve=s.getState();ve.gl.xr.enabled=ve.gl.xr.isPresenting,ve.gl.xr.setAnimationLoop(ve.gl.xr.isPresenting?Z:null),ve.gl.xr.isPresenting||IR(ve)},Y={connect(){const ve=s.getState().gl;ve.xr.addEventListener("sessionstart",X),ve.xr.addEventListener("sessionend",X)},disconnect(){const ve=s.getState().gl;ve.xr.removeEventListener("sessionstart",X),ve.xr.removeEventListener("sessionend",X)}};typeof((W=L.xr)==null?void 0:W.addEventListener)=="function"&&Y.connect(),U.set({xr:Y})}if(L.shadowMap){const Z=L.shadowMap.enabled,X=L.shadowMap.type;if(L.shadowMap.enabled=!!y,On.boo(y))L.shadowMap.type=U0;else if(On.str(y)){var V;const Y={basic:gB,percentage:jw,soft:U0,variance:sa};L.shadowMap.type=(V=Y[y])!=null?V:U0}else On.obj(y)&&Object.assign(L.shadowMap,y);(Z!==L.shadowMap.enabled||X!==L.shadowMap.type)&&(L.shadowMap.needsUpdate=!0)}const G=oO();G&&("enabled"in G?G.enabled=!w:"legacyMode"in G&&(G.legacyMode=w)),c||Bh(L,{outputEncoding:_?3e3:3001,toneMapping:S?ma:bN}),U.legacy!==w&&U.set(()=>({legacy:w})),U.linear!==_&&U.set(()=>({linear:_})),U.flat!==S&&U.set(()=>({flat:S})),h&&!On.fun(h)&&!fO(h)&&!On.equ(h,L,zh)&&Bh(L,h),g&&!U.events.handlers&&U.set({events:g(s)});const $=dG(n,p);return On.equ($,U.size,zh)||U.setSize($.width,$.height,$.updateStyle,$.top,$.left),R&&U.viewport.dpr!==lO(R)&&U.setDpr(R),U.frameloop!==k&&U.setFrameloop(k),U.onPointerMissed||U.set({onPointerMissed:N}),C&&!On.equ(C,U.performance,zh)&&U.set(Z=>({performance:{...Z.performance,...C}})),a=v,c=!0,this},render(u){return c||this.configure(),v_.updateContainer(_e.jsx(mG,{store:s,children:u,onCreated:a,rootElement:n}),o,null,()=>{}),s},unmount(){gG(n)}}}function mG({store:n,children:e,onCreated:t,rootElement:r}){return wv(()=>{const i=n.getState();i.set(s=>({internal:{...s.internal,active:!0}})),t&&t(i),n.getState().events.connected||i.events.connect==null||i.events.connect(r)},[]),_e.jsx(dO.Provider,{value:n,children:e})}function gG(n,e){const t=Cf.get(n),r=t==null?void 0:t.fiber;if(r){const i=t==null?void 0:t.store.getState();i&&(i.internal.active=!1),v_.updateContainer(null,r,null,()=>{i&&setTimeout(()=>{try{var s,o,a,c;i.events.disconnect==null||i.events.disconnect(),(s=i.gl)==null||(o=s.renderLists)==null||o.dispose==null||o.dispose(),(a=i.gl)==null||a.forceContextLoss==null||a.forceContextLoss(),(c=i.gl)!=null&&c.xr&&i.xr.disconnect(),eG(i),Cf.delete(n)}catch{}},500)})}}v_.injectIntoDevTools({bundleType:0,rendererPackageName:"@react-three/fiber",version:ke.version});const kS={onClick:["click",!1],onContextMenu:["contextmenu",!1],onDoubleClick:["dblclick",!1],onWheel:["wheel",!0],onPointerDown:["pointerdown",!0],onPointerUp:["pointerup",!0],onPointerLeave:["pointerleave",!0],onPointerMove:["pointermove",!0],onPointerCancel:["pointercancel",!0],onLostPointerCapture:["lostpointercapture",!0]};function _G(n){const{handlePointer:e}=sG(n);return{priority:1,enabled:!0,compute(t,r,i){r.pointer.set(t.offsetX/r.size.width*2-1,-(t.offsetY/r.size.height)*2+1),r.raycaster.setFromCamera(r.pointer,r.camera)},connected:void 0,handlers:Object.keys(kS).reduce((t,r)=>({...t,[r]:e(r)}),{}),update:()=>{var t;const{events:r,internal:i}=n.getState();(t=i.lastEvent)!=null&&t.current&&r.handlers&&r.handlers.onPointerMove(i.lastEvent.current)},connect:t=>{var r;const{set:i,events:s}=n.getState();s.disconnect==null||s.disconnect(),i(o=>({events:{...o.events,connected:t}})),Object.entries((r=s.handlers)!=null?r:[]).forEach(([o,a])=>{const[c,l]=kS[o];t.addEventListener(c,a,{passive:l})})},disconnect:()=>{const{set:t,events:r}=n.getState();if(r.connected){var i;Object.entries((i=r.handlers)!=null?i:[]).forEach(([s,o])=>{if(r&&r.connected instanceof HTMLElement){const[a]=kS[s];r.connected.removeEventListener(a,o)}}),t(s=>({events:{...s.events,connected:void 0}}))}}}}var oT={exports:{}};function yO(n,e=100,t={}){if(typeof n!="function")throw new TypeError(`Expected the first parameter to be a function, got \`${typeof n}\`.`);if(e<0)throw new RangeError("`wait` must not be negative.");const{immediate:r}=typeof t=="boolean"?{immediate:t}:t;let i,s,o,a,c;function l(){const p=i,m=s;return i=void 0,s=void 0,c=n.apply(p,m),c}function u(){const p=Date.now()-a;p=0?o=setTimeout(u,e-p):(o=void 0,r||(c=l()))}const h=function(...p){if(i&&this!==i&&Object.getPrototypeOf(this)===Object.getPrototypeOf(i))throw new Error("Debounced method called with different contexts of the same prototype.");i=this,s=p,a=Date.now();const m=r&&!o;return o||(o=setTimeout(u,e)),m&&(c=l()),c};return Object.defineProperty(h,"isPending",{get(){return o!==void 0}}),h.clear=()=>{o&&(clearTimeout(o),o=void 0)},h.flush=()=>{o&&h.trigger()},h.trigger=()=>{c=l(),h.clear()},h}oT.exports.debounce=yO;oT.exports=yO;var vG=oT.exports;const yG=Nc(vG);var xO={exports:{}};(function(n,e){(function(t,r){n.exports=r()})(Eo,function(){return t.importState=function(i){var s=new t;return s.importState(i),s},t;function t(){return function(i){var s=0,o=0,a=0,c=1;i.length==0&&(i=[+new Date]);var l=r();s=l(" "),o=l(" "),a=l(" ");for(var u=0;u>>0,c-=i,c*=i,i=c>>>0,c-=i,i+=c*4294967296}return(i>>>0)*23283064365386963e-26};return s.version="Mash 0.9",s}})})(xO);var xG=xO.exports;const SG=Nc(xG);new St;new St;function Cn(n,e,t){return Math.max(e,Math.min(t,n))}const EG=SG("089fad0j9awfem09wavefc09uwaef");function OR(n){return 2*Math.floor(n/2)}function wG(n,e){return Math.round(n/e)*e}function TG(){return EG()}function Xd(n,e){const t=Math.min(n,e),i=Math.max(n,e)-t+1;return t+Math.floor(TG()*i)}/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2017-2022 Joachim Wester - * MIT licensed - */var bG=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),AG=Object.prototype.hasOwnProperty;function gE(n,e){return AG.call(n,e)}function _E(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t=48&&r<=57){e++;continue}return!1}return!0}function _u(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}function SO(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function yE(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&p===void 0&&(l[m]===void 0?p=c.slice(0,u).join("/"):u==h-1&&(p=e.path),p!==void 0&&g(e,0,n,p)),u++,Array.isArray(l)){if(m==="-")m=l.length;else{if(t&&!vE(m))throw new tr("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);vE(m)&&(m=~~m)}if(u>=h){if(t&&e.op==="add"&&m>l.length)throw new tr("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var o=CG[e.op].call(e,l,m,n);if(o.test===!1)throw new tr("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o}}else if(u>=h){var o=rf[e.op].call(e,l,m,n);if(o.test===!1)throw new tr("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o}if(l=l[m],t&&u0)throw new tr('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new tr("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new tr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&yE(n.value))throw new tr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new tr("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new tr("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var o={op:"_get",path:n.from,value:void 0},a=EO([o],t);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new tr("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new tr("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}function EO(n,e,t){try{if(!Array.isArray(n))throw new tr("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)bv(Ui(e),Ui(n),t||!0);else{t=t||x_;for(var r=0;r0&&(n.patches=[],n.callback&&n.callback(r)),r}function lT(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=_E(e),o=_E(n),a=!1,c=o.length-1;c>=0;c--){var l=o[c],u=n[l];if(gE(e,l)&&!(e[l]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var h=e[l];typeof u=="object"&&u!=null&&typeof h=="object"&&h!=null&&Array.isArray(u)===Array.isArray(h)?lT(u,h,t,r+"/"+_u(l),i):u!==h&&(i&&t.push({op:"test",path:r+"/"+_u(l),value:Ui(u)}),t.push({op:"replace",path:r+"/"+_u(l),value:Ui(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+_u(l),value:Ui(u)}),t.push({op:"remove",path:r+"/"+_u(l)}),a=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}))}if(!(!a&&s.length==o.length))for(var c=0;ch.length?u:h})}function i(l){return l.reduce(function(u,h){return u.lengthcrypto.getRandomValues(new Uint8Array(n)),YG=(n,e,t)=>{let r=(2<{let o="";for(;;){let a=t(i),c=i;for(;c--;)if(o+=n[a[c]&r]||"",o.length===s)return o}}},AO=(n,e=21)=>YG(n,e,KG),ZG=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n));for(;n--;)e+=XG[t[n]&63];return e};var MO="abcdefghijklmnopqrstuvwxyz",CO="ABCDEFGHIJKLMNOPQRSTUVWXYZ",RO="0123456789",QG="346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz",JG="6789BCDFGHJKLMNPQRTWbcdfghjkmnpqrtwz";const eW=RO,tW=MO,nW=CO;var rW=eW+tW+nW,SE={lowercase:MO,uppercase:CO,numbers:RO,nolookalikes:QG,nolookalikesSafe:JG,alphanumeric:rW};function fr(){return`sid_${ZG(12).replaceAll("-",".")}`}const iW=AO(SE.numbers,4),sW=AO(`${SE.numbers}${SE.lowercase}`,16);function oW(){return`pid_${iW()}_${sW()}`}function aW(n){return(n==null?void 0:n.startsWith("pid_"))??!1}function cW(){return qG({capitalize:!1,adjectiveCount:1})}var wn=(n=>(n[n.BLACK=0]="BLACK",n[n.DKBLUE=1]="DKBLUE",n[n.DKGREEN=2]="DKGREEN",n[n.DKCYAN=3]="DKCYAN",n[n.DKRED=4]="DKRED",n[n.DKPURPLE=5]="DKPURPLE",n[n.DKYELLOW=6]="DKYELLOW",n[n.LTGRAY=7]="LTGRAY",n[n.DKGRAY=8]="DKGRAY",n[n.BLUE=9]="BLUE",n[n.GREEN=10]="GREEN",n[n.CYAN=11]="CYAN",n[n.RED=12]="RED",n[n.PURPLE=13]="PURPLE",n[n.YELLOW=14]="YELLOW",n[n.WHITE=15]="WHITE",n[n.ONBLACK=16]="ONBLACK",n[n.ONDKBLUE=17]="ONDKBLUE",n[n.ONDKGREEN=18]="ONDKGREEN",n[n.ONDKCYAN=19]="ONDKCYAN",n[n.ONDKRED=20]="ONDKRED",n[n.ONDKPURPLE=21]="ONDKPURPLE",n[n.ONDKYELLOW=22]="ONDKYELLOW",n[n.ONLTGRAY=23]="ONLTGRAY",n[n.ONDKGRAY=24]="ONDKGRAY",n[n.ONBLUE=25]="ONBLUE",n[n.ONGREEN=26]="ONGREEN",n[n.ONCYAN=27]="ONCYAN",n[n.ONRED=28]="ONRED",n[n.ONPURPLE=29]="ONPURPLE",n[n.ONYELLOW=30]="ONYELLOW",n[n.ONWHITE=31]="ONWHITE",n[n.ONCLEAR=32]="ONCLEAR",n[n.ONSHADOW=33]="ONSHADOW",n[n.ONBORROW=34]="ONBORROW",n))(wn||{}),Vn=(n=>(n[n.ISWALK=0]="ISWALK",n[n.ISSOLID=1]="ISSOLID",n[n.ISSWIM=2]="ISSWIM",n[n.ISBULLET=3]="ISBULLET",n))(Vn||{}),S_=(n=>(n[n.ISTERRAIN=0]="ISTERRAIN",n[n.ISOBJECT=1]="ISOBJECT",n))(S_||{}),it=(n=>(n[n.IDLE=0]="IDLE",n[n.NORTH=1]="NORTH",n[n.SOUTH=2]="SOUTH",n[n.WEST=3]="WEST",n[n.EAST=4]="EAST",n[n.BY=5]="BY",n[n.AT=6]="AT",n[n.FLOW=7]="FLOW",n[n.SEEK=8]="SEEK",n[n.RNDNS=9]="RNDNS",n[n.RNDNE=10]="RNDNE",n[n.RND=11]="RND",n[n.CW=12]="CW",n[n.CCW=13]="CCW",n[n.OPP=14]="OPP",n[n.RNDP=15]="RNDP",n))(it||{}),dt=(n=>(n[n.LOADER=0]="LOADER",n[n.BOARD=1]="BOARD",n[n.OBJECT=2]="OBJECT",n[n.TERRAIN=3]="TERRAIN",n[n.CHARSET=4]="CHARSET",n[n.PALETTE=5]="PALETTE",n[n.CONST=6]="CONST",n[n.RANGE=7]="RANGE",n[n.SELECT=8]="SELECT",n[n.NUMBER=9]="NUMBER",n[n.TEXT=10]="TEXT",n[n.LINK=11]="LINK",n[n.HOTKEY=12]="HOTKEY",n[n.SCROLL=13]="SCROLL",n[n.COPYIT=14]="COPYIT",n))(dt||{});function $t(n){return n.toLowerCase().trim()}function lW(n,e,t,r){return{id:fr(),target:n,sender:e,data:t,player:r}}function kO(n){const[e,...t]=n.split(":");return{target:e,path:t.join(":")}}function Qu(n,e,t){const r=fr(),i=$t(n),s=e.map($t),o={id(){return r},name(){return n},topics(){return e},emit(a,c,l){Yt.emit(a,r,c,l)},reply(a,c,l,u){o.emit(`${a.sender}:${c}`,l,u)},handle(a){const{target:c,path:l}=kO(a.target),u=$t(c);s.findIndex(h=>h==="all"||h===u)!==-1&&t(a),(r===c||u==="all"||i===u)&&t({...a,target:l})}};return Yt.connect(o),o}const IS=new Set,Yt={emit(n,e,t,r){Yt.invoke(lW(n,e,t,r))},invoke(n){IS.forEach(e=>e.handle(n))},connect(n){IS.add(n)},disconnect(n){IS.delete(n)}};function Pn(n,e,t,r){const i=r??"";return Yt.emit(`error:${e}`,n,t,i),vW(n,t,i)}function uW(n,e){Yt.emit("gadgetserver:desync",n,void 0,e)}function hW(n,e){Yt.emit("gadgetserver:clearscroll",n,void 0,e)}function fW(n,e){Yt.emit("register:dev",n,void 0,e)}function dW(n,e){Yt.emit("register:share",n,void 0,e)}function pW(n){Yt.emit("register:nuke",n)}function mW(n){Yt.emit("register:nodetrash",n)}function gW(n,e,t){Yt.emit("synth:play",n,[e,t])}function NS(n,e,t,r){Yt.emit("synth:voice",n,[e,t,r])}function _W(n,e,t,r,i){Yt.emit("synth:voicefx",n,[e,t,r,i])}function eo(n,...e){return Yt.emit("tape:info",n,e),!0}function vW(n,...e){return Yt.emit("tape:error",n,e),!1}function yW(n){Yt.emit("tape:terminal:open",n)}function hT(n){Yt.emit("tape:terminal:close",n)}function IO(n,e){Yt.emit("tape:terminal:inclayout",n,e)}function PR(n){Yt.emit("tape:crash",n)}function xW(n,e,t,r,i,s){Yt.emit("tape:editor:open",n,[e,t,r,i],s)}function SW(n){Yt.emit("tape:editor:close",n)}function EW(n,e){Yt.emit("vm:init",n,void 0,e)}function wW(n,e,t,r){Yt.emit("vm:books",n,[e,t],r)}function TW(n,e){Yt.emit("vm:login",n,void 0,e)}function bW(n,e){Yt.emit("vm:endgame",n,void 0,e)}function AW(n,e){Yt.emit("vm:doot",n,void 0,e)}function MW(n,e,t,r){Yt.emit("vm:input",n,[e,t],r)}function NO(n,e){return`${n}${e}`}function CW(n,e,t,r){Yt.emit("vm:codewatch",n,[e,t],r)}function RW(n,e,t,r){Yt.emit("vm:coderelease",n,[e,t],r)}function Av(n,e,t){Yt.emit("vm:cli",n,e,t)}function Yh(n){Yt.emit("vm:flush",n)}function EE(n,e,t){Yt.emit("vm:loadfile",n,e,t)}const OO="15.0.4",DR=(n,e,t)=>({endTime:e,insertTime:t,type:"exponentialRampToValue",value:n}),UR=(n,e,t)=>({endTime:e,insertTime:t,type:"linearRampToValue",value:n}),wE=(n,e)=>({startTime:e,type:"setValue",value:n}),LO=(n,e,t)=>({duration:t,startTime:e,type:"setValueCurve",values:n}),PO=(n,e,{startTime:t,target:r,timeConstant:i})=>r+(e-r)*Math.exp((t-n)/i),sf=n=>n.type==="exponentialRampToValue",E_=n=>n.type==="linearRampToValue",fl=n=>sf(n)||E_(n),fT=n=>n.type==="setValue",cc=n=>n.type==="setValueCurve",w_=(n,e,t,r)=>{const i=n[e];return i===void 0?r:fl(i)||fT(i)?i.value:cc(i)?i.values[i.values.length-1]:PO(t,w_(n,e-1,i.startTime,r),i)},FR=(n,e,t,r,i)=>t===void 0?[r.insertTime,i]:fl(t)?[t.endTime,t.value]:fT(t)?[t.startTime,t.value]:cc(t)?[t.startTime+t.duration,t.values[t.values.length-1]]:[t.startTime,w_(n,e-1,t.startTime,i)],TE=n=>n.type==="cancelAndHold",bE=n=>n.type==="cancelScheduledValues",ul=n=>TE(n)||bE(n)?n.cancelTime:sf(n)||E_(n)?n.endTime:n.startTime,BR=(n,e,t,{endTime:r,value:i})=>t===i?i:0t+(n-e)/(r-e)*(i-t),kW=(n,e)=>{const t=Math.floor(e),r=Math.ceil(e);return t===r?n[t]:(1-(e-t))*n[t]+(1-(r-e))*n[r]},IW=(n,{duration:e,startTime:t,values:r})=>{const i=(n-t)/e*(r.length-1);return kW(r,i)},s0=n=>n.type==="setTarget";class NW{constructor(e){this._automationEvents=[],this._currenTime=0,this._defaultValue=e}[Symbol.iterator](){return this._automationEvents[Symbol.iterator]()}add(e){const t=ul(e);if(TE(e)||bE(e)){const r=this._automationEvents.findIndex(s=>bE(e)&&cc(s)?s.startTime+s.duration>=t:ul(s)>=t),i=this._automationEvents[r];if(r!==-1&&(this._automationEvents=this._automationEvents.slice(0,r)),TE(e)){const s=this._automationEvents[this._automationEvents.length-1];if(i!==void 0&&fl(i)){if(s!==void 0&&s0(s))throw new Error("The internal list is malformed.");const o=s===void 0?i.insertTime:cc(s)?s.startTime+s.duration:ul(s),a=s===void 0?this._defaultValue:cc(s)?s.values[s.values.length-1]:s.value,c=sf(i)?BR(t,o,a,i):zR(t,o,a,i),l=sf(i)?DR(c,t,this._currenTime):UR(c,t,this._currenTime);this._automationEvents.push(l)}if(s!==void 0&&s0(s)&&this._automationEvents.push(wE(this.getValue(t),t)),s!==void 0&&cc(s)&&s.startTime+s.duration>t){const o=t-s.startTime,a=(s.values.length-1)/s.duration,c=Math.max(2,1+Math.ceil(o*a)),l=o/(c-1)*a,u=s.values.slice(0,c);if(l<1)for(let h=1;hul(o)>t),i=r===-1?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[r-1];if(i!==void 0&&cc(i)&&ul(i)+i.duration>t)return!1;const s=sf(e)?DR(e.value,e.endTime,this._currenTime):E_(e)?UR(e.value,t,this._currenTime):e;if(r===-1)this._automationEvents.push(s);else{if(cc(e)&&t+e.duration>ul(this._automationEvents[r]))return!1;this._automationEvents.splice(r,0,s)}}return!0}flush(e){const t=this._automationEvents.findIndex(r=>ul(r)>e);if(t>1){const r=this._automationEvents.slice(t-1),i=r[0];s0(i)&&r.unshift(wE(w_(this._automationEvents,t-2,i.startTime,this._defaultValue),i.startTime)),this._automationEvents=r}}getValue(e){if(this._automationEvents.length===0)return this._defaultValue;const t=this._automationEvents.findIndex(o=>ul(o)>e),r=this._automationEvents[t],i=(t===-1?this._automationEvents.length:t)-1,s=this._automationEvents[i];if(s!==void 0&&s0(s)&&(r===void 0||!fl(r)||r.insertTime>e))return PO(e,w_(this._automationEvents,i-1,s.startTime,this._defaultValue),s);if(s!==void 0&&fT(s)&&(r===void 0||!fl(r)))return s.value;if(s!==void 0&&cc(s)&&(r===void 0||!fl(r)||s.startTime+s.duration>e))return e({cancelTime:n,type:"cancelAndHold"}),LW=n=>({cancelTime:n,type:"cancelScheduledValues"}),PW=(n,e)=>({endTime:e,type:"exponentialRampToValue",value:n}),DW=(n,e)=>({endTime:e,type:"linearRampToValue",value:n}),UW=(n,e,t)=>({startTime:e,target:n,timeConstant:t,type:"setTarget"}),FW=()=>new DOMException("","AbortError"),BW=n=>(e,t,[r,i,s],o)=>{n(e[i],[t,r,s],a=>a[0]===t&&a[1]===r,o)},zW=n=>(e,t,r)=>{const i=[];for(let s=0;s(e,t)=>{n.set(e,{activeInputs:new Set,passiveInputs:new WeakMap,renderer:t})},kf=new WeakSet,DO=new WeakMap,dT=new WeakMap,UO=new WeakMap,pT=new WeakMap,Mv=new WeakMap,FO=new WeakMap,AE=new WeakMap,ME=new WeakMap,CE=new WeakMap,BO={construct(){return BO}},HW=n=>{try{const e=new Proxy(n,BO);new e}catch{return!1}return!0},VR=/^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/,HR=(n,e)=>{const t=[];let r=n.replace(/^[\s]+/,""),i=r.match(VR);for(;i!==null;){const s=i[1].slice(1,-1),o=i[0].replace(/([\s]+)?;?$/,"").replace(s,new URL(s,e).toString());t.push(o),r=r.slice(i[0].length).replace(/^[\s]+/,""),i=r.match(VR)}return[t.join(";"),r]},GR=n=>{if(n!==void 0&&!Array.isArray(n))throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.")},WR=n=>{if(!HW(n))throw new TypeError("The given value for processorCtor should be a constructor.");if(n.prototype===null||typeof n.prototype!="object")throw new TypeError("The given value for processorCtor should have a prototype.")},GW=(n,e,t,r,i,s,o,a,c,l,u,h,p)=>{let m=0;return(g,v,y={credentials:"omit"})=>{const _=u.get(g);if(_!==void 0&&_.has(v))return Promise.resolve();const S=l.get(g);if(S!==void 0){const k=S.get(v);if(k!==void 0)return k}const w=s(g),T=w.audioWorklet===void 0?i(v).then(([k,R])=>{const[C,O]=HR(k,R),M=`${C};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${O} -})})(window,'_AWGS')`;return t(M)}).then(()=>{const k=p._AWGS.pop();if(k===void 0)throw new SyntaxError;r(w.currentTime,w.sampleRate,()=>k(class{},void 0,(R,C)=>{if(R.trim()==="")throw e();const O=ME.get(w);if(O!==void 0){if(O.has(R))throw e();WR(C),GR(C.parameterDescriptors),O.set(R,C)}else WR(C),GR(C.parameterDescriptors),ME.set(w,new Map([[R,C]]))},w.sampleRate,void 0,void 0))}):Promise.all([i(v),Promise.resolve(n(h,h))]).then(([[k,R],C])=>{const O=m+1;m=O;const[M,N]=HR(k,R),b=`${M};((AudioWorkletProcessor,registerProcessor)=>{${N} -})(${C?"AudioWorkletProcessor":"class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}"},(n,p)=>registerProcessor(n,class extends p{${C?"":"__c = (a) => a.forEach(e=>this.__b.add(e.buffer));"}process(i,o,p){${C?"":"i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));"}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${O}',class extends AudioWorkletProcessor{process(){return !1}})`,B=new Blob([b],{type:"application/javascript; charset=utf-8"}),W=URL.createObjectURL(B);return w.audioWorklet.addModule(W,y).then(()=>{if(a(w))return w;const V=o(w);return V.audioWorklet.addModule(W,y).then(()=>V)}).then(V=>{if(c===null)throw new SyntaxError;try{new c(V,`__sac${O}`)}catch{throw new SyntaxError}}).finally(()=>URL.revokeObjectURL(W))});return S===void 0?l.set(g,new Map([[v,T]])):S.set(v,T),T.then(()=>{const k=u.get(g);k===void 0?u.set(g,new Set([v])):k.add(v)}).finally(()=>{const k=l.get(g);k!==void 0&&k.delete(v)}),T}},Ro=(n,e)=>{const t=n.get(e);if(t===void 0)throw new Error("A value with the given key could not be found.");return t},Cv=(n,e)=>{const t=Array.from(n).filter(e);if(t.length>1)throw Error("More than one element was found.");if(t.length===0)throw Error("No element was found.");const[r]=t;return n.delete(r),r},zO=(n,e,t,r)=>{const i=Ro(n,e),s=Cv(i,o=>o[0]===t&&o[1]===r);return i.size===0&&n.delete(e),s},jp=n=>Ro(FO,n),If=n=>{if(kf.has(n))throw new Error("The AudioNode is already stored.");kf.add(n),jp(n).forEach(e=>e(!0))},VO=n=>"port"in n,$p=n=>{if(!kf.has(n))throw new Error("The AudioNode is not stored.");kf.delete(n),jp(n).forEach(e=>e(!1))},RE=(n,e)=>{!VO(n)&&e.every(t=>t.size===0)&&$p(n)},WW=(n,e,t,r,i,s,o,a,c,l,u,h,p)=>{const m=new WeakMap;return(g,v,y,_,S)=>{const{activeInputs:w,passiveInputs:T}=s(v),{outputs:k}=s(g),R=a(g),C=O=>{const M=c(v),N=c(g);if(O){const U=zO(T,g,y,_);n(w,g,U,!1),!S&&!h(g)&&t(N,M,y,_),p(v)&&If(v)}else{const U=r(w,g,y,_);e(T,_,U,!1),!S&&!h(g)&&i(N,M,y,_);const L=o(v);if(L===0)u(v)&&RE(v,w);else{const P=m.get(v);P!==void 0&&clearTimeout(P),m.set(v,setTimeout(()=>{u(v)&&RE(v,w)},L*1e3))}}};return l(k,[v,y,_],O=>O[0]===v&&O[1]===y&&O[2]===_,!0)?(R.add(C),u(g)?n(w,g,[y,_,C],!0):e(T,_,[g,y,C],!0),!0):!1}},jW=n=>(e,t,[r,i,s],o)=>{const a=e.get(r);a===void 0?e.set(r,new Set([[i,t,s]])):n(a,[i,t,s],c=>c[0]===i&&c[1]===t,o)},$W=n=>(e,t)=>{const r=n(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});t.connect(r).connect(e.destination);const i=()=>{t.removeEventListener("ended",i),t.disconnect(r),r.disconnect()};t.addEventListener("ended",i)},qW=n=>(e,t)=>{n(e).add(t)},XW={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},KW=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=i(a),u={...XW,...c},h=r(l,u),p=s(l)?e():null;super(a,!1,h,p),this._nativeAnalyserNode=h}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(a){this._nativeAnalyserNode.fftSize=a}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(a){const c=this._nativeAnalyserNode.maxDecibels;if(this._nativeAnalyserNode.maxDecibels=a,!(a>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=c,t()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(a){const c=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=a,!(this._nativeAnalyserNode.maxDecibels>a))throw this._nativeAnalyserNode.minDecibels=c,t()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(a){this._nativeAnalyserNode.smoothingTimeConstant=a}getByteFrequencyData(a){this._nativeAnalyserNode.getByteFrequencyData(a)}getByteTimeDomainData(a){this._nativeAnalyserNode.getByteTimeDomainData(a)}getFloatFrequencyData(a){this._nativeAnalyserNode.getFloatFrequencyData(a)}getFloatTimeDomainData(a){this._nativeAnalyserNode.getFloatTimeDomainData(a)}},Ti=(n,e)=>n.context===e,YW=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ti(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,fftSize:a.fftSize,maxDecibels:a.maxDecibels,minDecibels:a.minDecibels,smoothingTimeConstant:a.smoothingTimeConstant};a=n(o,l)}return r.set(o,a),await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},T_=n=>{try{n.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0},Ia=()=>new DOMException("","IndexSizeError"),mT=n=>{n.getChannelData=(e=>t=>{try{return e.call(n,t)}catch(r){throw r.code===12?Ia():r}})(n.getChannelData)},ZW={numberOfChannels:1},QW=(n,e,t,r,i,s,o,a)=>{let c=null;return class HO{constructor(u){if(i===null)throw new Error("Missing the native OfflineAudioContext constructor.");const{length:h,numberOfChannels:p,sampleRate:m}={...ZW,...u};c===null&&(c=new i(1,1,44100));const g=r!==null&&e(s,s)?new r({length:h,numberOfChannels:p,sampleRate:m}):c.createBuffer(p,h,m);if(g.numberOfChannels===0)throw t();return typeof g.copyFromChannel!="function"?(o(g),mT(g)):e(T_,()=>T_(g))||a(g),n.add(g),g}static[Symbol.hasInstance](u){return u!==null&&typeof u=="object"&&Object.getPrototypeOf(u)===HO.prototype||n.has(u)}}},es=-34028234663852886e22,Pi=-es,gc=n=>kf.has(n),JW={buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1},e9=(n,e,t,r,i,s,o,a)=>class extends n{constructor(l,u){const h=s(l),p={...JW,...u},m=i(h,p),g=o(h),v=g?e():null;super(l,!1,m,v),this._audioBufferSourceNodeRenderer=v,this._isBufferNullified=!1,this._isBufferSet=p.buffer!==null,this._nativeAudioBufferSourceNode=m,this._onended=null,this._playbackRate=t(this,g,m.playbackRate,Pi,es)}get buffer(){return this._isBufferNullified?null:this._nativeAudioBufferSourceNode.buffer}set buffer(l){if(this._nativeAudioBufferSourceNode.buffer=l,l!==null){if(this._isBufferSet)throw r();this._isBufferSet=!0}}get loop(){return this._nativeAudioBufferSourceNode.loop}set loop(l){this._nativeAudioBufferSourceNode.loop=l}get loopEnd(){return this._nativeAudioBufferSourceNode.loopEnd}set loopEnd(l){this._nativeAudioBufferSourceNode.loopEnd=l}get loopStart(){return this._nativeAudioBufferSourceNode.loopStart}set loopStart(l){this._nativeAudioBufferSourceNode.loopStart=l}get onended(){return this._onended}set onended(l){const u=typeof l=="function"?a(this,l):null;this._nativeAudioBufferSourceNode.onended=u;const h=this._nativeAudioBufferSourceNode.onended;this._onended=h!==null&&h===u?l:h}get playbackRate(){return this._playbackRate}start(l=0,u=0,h){if(this._nativeAudioBufferSourceNode.start(l,u,h),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.start=h===void 0?[l,u]:[l,u,h]),this.context.state!=="closed"){If(this);const p=()=>{this._nativeAudioBufferSourceNode.removeEventListener("ended",p),gc(this)&&$p(this)};this._nativeAudioBufferSourceNode.addEventListener("ended",p)}}stop(l=0){this._nativeAudioBufferSourceNode.stop(l),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.stop=l)}},t9=(n,e,t,r,i)=>()=>{const s=new WeakMap;let o=null,a=null;const c=async(l,u)=>{let h=t(l);const p=Ti(h,u);if(!p){const m={buffer:h.buffer,channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,loop:h.loop,loopEnd:h.loopEnd,loopStart:h.loopStart,playbackRate:h.playbackRate.value};h=e(u,m),o!==null&&h.start(...o),a!==null&&h.stop(a)}return s.set(u,h),p?await n(u,l.playbackRate,h.playbackRate):await r(u,l.playbackRate,h.playbackRate),await i(l,u,h),h};return{set start(l){o=l},set stop(l){a=l},render(l,u){const h=s.get(u);return h!==void 0?Promise.resolve(h):c(l,u)}}},n9=n=>"playbackRate"in n,r9=n=>"frequency"in n&&"gain"in n,i9=n=>"offset"in n,s9=n=>!("frequency"in n)&&"gain"in n,o9=n=>"detune"in n&&"frequency"in n&&!("gain"in n),a9=n=>"pan"in n,Fi=n=>Ro(DO,n),qp=n=>Ro(UO,n),kE=(n,e)=>{const{activeInputs:t}=Fi(n);t.forEach(i=>i.forEach(([s])=>{e.includes(n)||kE(s,[...e,n])}));const r=n9(n)?[n.playbackRate]:VO(n)?Array.from(n.parameters.values()):r9(n)?[n.Q,n.detune,n.frequency,n.gain]:i9(n)?[n.offset]:s9(n)?[n.gain]:o9(n)?[n.detune,n.frequency]:a9(n)?[n.pan]:[];for(const i of r){const s=qp(i);s!==void 0&&s.activeInputs.forEach(([o])=>kE(o,e))}gc(n)&&$p(n)},GO=n=>{kE(n.destination,[])},c9=n=>n===void 0||typeof n=="number"||typeof n=="string"&&(n==="balanced"||n==="interactive"||n==="playback"),l9=(n,e,t,r,i,s,o,a,c)=>class extends n{constructor(u={}){if(c===null)throw new Error("Missing the native AudioContext constructor.");let h;try{h=new c(u)}catch(g){throw g.code===12&&g.message==="sampleRate is not in range"?t():g}if(h===null)throw r();if(!c9(u.latencyHint))throw new TypeError(`The provided value '${u.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(u.sampleRate!==void 0&&h.sampleRate!==u.sampleRate)throw t();super(h,2);const{latencyHint:p}=u,{sampleRate:m}=h;if(this._baseLatency=typeof h.baseLatency=="number"?h.baseLatency:p==="balanced"?512/m:p==="interactive"||p===void 0?256/m:p==="playback"?1024/m:Math.max(2,Math.min(128,Math.round(p*m/128)))*128/m,this._nativeAudioContext=h,c.name==="webkitAudioContext"?(this._nativeGainNode=h.createGain(),this._nativeOscillatorNode=h.createOscillator(),this._nativeGainNode.gain.value=1e-37,this._nativeOscillatorNode.connect(this._nativeGainNode).connect(h.destination),this._nativeOscillatorNode.start()):(this._nativeGainNode=null,this._nativeOscillatorNode=null),this._state=null,h.state==="running"){this._state="suspended";const g=()=>{this._state==="suspended"&&(this._state=null),h.removeEventListener("statechange",g)};h.addEventListener("statechange",g)}}get baseLatency(){return this._baseLatency}get state(){return this._state!==null?this._state:this._nativeAudioContext.state}close(){return this.state==="closed"?this._nativeAudioContext.close().then(()=>{throw e()}):(this._state==="suspended"&&(this._state=null),this._nativeAudioContext.close().then(()=>{this._nativeGainNode!==null&&this._nativeOscillatorNode!==null&&(this._nativeOscillatorNode.stop(),this._nativeGainNode.disconnect(),this._nativeOscillatorNode.disconnect()),GO(this)}))}createMediaElementSource(u){return new i(this,{mediaElement:u})}createMediaStreamDestination(){return new s(this)}createMediaStreamSource(u){return new o(this,{mediaStream:u})}createMediaStreamTrackSource(u){return new a(this,{mediaStreamTrack:u})}resume(){return this._state==="suspended"?new Promise((u,h)=>{const p=()=>{this._nativeAudioContext.removeEventListener("statechange",p),this._nativeAudioContext.state==="running"?u():this.resume().then(u,h)};this._nativeAudioContext.addEventListener("statechange",p)}):this._nativeAudioContext.resume().catch(u=>{throw u===void 0||u.code===15?e():u})}suspend(){return this._nativeAudioContext.suspend().catch(u=>{throw u===void 0?e():u})}},u9=(n,e,t,r,i,s,o,a)=>class extends n{constructor(l,u){const h=s(l),p=o(h),m=i(h,u,p),g=p?e(a):null;super(l,!1,m,g),this._isNodeOfNativeOfflineAudioContext=p,this._nativeAudioDestinationNode=m}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(l){if(this._isNodeOfNativeOfflineAudioContext)throw r();if(l>this._nativeAudioDestinationNode.maxChannelCount)throw t();this._nativeAudioDestinationNode.channelCount=l}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(l){if(this._isNodeOfNativeOfflineAudioContext)throw r();this._nativeAudioDestinationNode.channelCountMode=l}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}},h9=n=>{const e=new WeakMap,t=async(r,i)=>{const s=i.destination;return e.set(i,s),await n(r,i,s),s};return{render(r,i){const s=e.get(i);return s!==void 0?Promise.resolve(s):t(r,i)}}},f9=(n,e,t,r,i,s,o,a)=>(c,l)=>{const u=l.listener,h=()=>{const k=new Float32Array(1),R=e(l,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:9}),C=o(l);let O=!1,M=[0,0,-1,0,1,0],N=[0,0,0];const U=()=>{if(O)return;O=!0;const B=r(l,256,9,0);B.onaudioprocess=({inputBuffer:W})=>{const V=[s(W,k,0),s(W,k,1),s(W,k,2),s(W,k,3),s(W,k,4),s(W,k,5)];V.some(($,Z)=>$!==M[Z])&&(u.setOrientation(...V),M=V);const G=[s(W,k,6),s(W,k,7),s(W,k,8)];G.some(($,Z)=>$!==N[Z])&&(u.setPosition(...G),N=G)},R.connect(B)},L=B=>W=>{W!==M[B]&&(M[B]=W,u.setOrientation(...M))},P=B=>W=>{W!==N[B]&&(N[B]=W,u.setPosition(...N))},b=(B,W,V)=>{const G=t(l,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:W});G.connect(R,0,B),G.start(),Object.defineProperty(G.offset,"defaultValue",{get(){return W}});const $=n({context:c},C,G.offset,Pi,es);return a($,"value",Z=>()=>Z.call($),Z=>X=>{try{Z.call($,X)}catch(Y){if(Y.code!==9)throw Y}U(),C&&V(X)}),$.cancelAndHoldAtTime=(Z=>C?()=>{throw i()}:(...X)=>{const Y=Z.apply($,X);return U(),Y})($.cancelAndHoldAtTime),$.cancelScheduledValues=(Z=>C?()=>{throw i()}:(...X)=>{const Y=Z.apply($,X);return U(),Y})($.cancelScheduledValues),$.exponentialRampToValueAtTime=(Z=>C?()=>{throw i()}:(...X)=>{const Y=Z.apply($,X);return U(),Y})($.exponentialRampToValueAtTime),$.linearRampToValueAtTime=(Z=>C?()=>{throw i()}:(...X)=>{const Y=Z.apply($,X);return U(),Y})($.linearRampToValueAtTime),$.setTargetAtTime=(Z=>C?()=>{throw i()}:(...X)=>{const Y=Z.apply($,X);return U(),Y})($.setTargetAtTime),$.setValueAtTime=(Z=>C?()=>{throw i()}:(...X)=>{const Y=Z.apply($,X);return U(),Y})($.setValueAtTime),$.setValueCurveAtTime=(Z=>C?()=>{throw i()}:(...X)=>{const Y=Z.apply($,X);return U(),Y})($.setValueCurveAtTime),$};return{forwardX:b(0,0,L(0)),forwardY:b(1,0,L(1)),forwardZ:b(2,-1,L(2)),positionX:b(6,0,P(0)),positionY:b(7,0,P(1)),positionZ:b(8,0,P(2)),upX:b(3,0,L(3)),upY:b(4,1,L(4)),upZ:b(5,0,L(5))}},{forwardX:p,forwardY:m,forwardZ:g,positionX:v,positionY:y,positionZ:_,upX:S,upY:w,upZ:T}=u.forwardX===void 0?h():u;return{get forwardX(){return p},get forwardY(){return m},get forwardZ(){return g},get positionX(){return v},get positionY(){return y},get positionZ(){return _},get upX(){return S},get upY(){return w},get upZ(){return T}}},b_=n=>"context"in n,Xp=n=>b_(n[0]),Ju=(n,e,t,r)=>{for(const i of n)if(t(i)){if(r)return!1;throw Error("The set contains at least one similar element.")}return n.add(e),!0},jR=(n,e,[t,r],i)=>{Ju(n,[e,t,r],s=>s[0]===e&&s[1]===t,i)},$R=(n,[e,t,r],i)=>{const s=n.get(e);s===void 0?n.set(e,new Set([[t,r]])):Ju(s,[t,r],o=>o[0]===t,i)},td=n=>"inputs"in n,A_=(n,e,t,r)=>{if(td(e)){const i=e.inputs[r];return n.connect(i,t,0),[i,t,0]}return n.connect(e,t,r),[e,t,r]},WO=(n,e,t)=>{for(const r of n)if(r[0]===e&&r[1]===t)return n.delete(r),r;return null},d9=(n,e,t)=>Cv(n,r=>r[0]===e&&r[1]===t),jO=(n,e)=>{if(!jp(n).delete(e))throw new Error("Missing the expected event listener.")},$O=(n,e,t)=>{const r=Ro(n,e),i=Cv(r,s=>s[0]===t);return r.size===0&&n.delete(e),i},M_=(n,e,t,r)=>{td(e)?n.disconnect(e.inputs[r],t,0):n.disconnect(e,t,r)},Hn=n=>Ro(dT,n),mp=n=>Ro(pT,n),Uu=n=>AE.has(n),$0=n=>!kf.has(n),qR=(n,e)=>new Promise(t=>{if(e!==null)t(!0);else{const r=n.createScriptProcessor(256,1,1),i=n.createGain(),s=n.createBuffer(1,2,44100),o=s.getChannelData(0);o[0]=1,o[1]=1;const a=n.createBufferSource();a.buffer=s,a.loop=!0,a.connect(r).connect(n.destination),a.connect(i),a.disconnect(i),r.onaudioprocess=c=>{const l=c.inputBuffer.getChannelData(0);Array.prototype.some.call(l,u=>u===1)?t(!0):t(!1),a.stop(),r.onaudioprocess=null,a.disconnect(r),r.disconnect(n.destination)},a.start()}}),OS=(n,e)=>{const t=new Map;for(const r of n)for(const i of r){const s=t.get(i);t.set(i,s===void 0?1:s+1)}t.forEach((r,i)=>e(i,r))},C_=n=>"context"in n,p9=n=>{const e=new Map;n.connect=(t=>(r,i=0,s=0)=>{const o=C_(r)?t(r,i,s):t(r,i),a=e.get(r);return a===void 0?e.set(r,[{input:s,output:i}]):a.every(c=>c.input!==s||c.output!==i)&&a.push({input:s,output:i}),o})(n.connect.bind(n)),n.disconnect=(t=>(r,i,s)=>{if(t.apply(n),r===void 0)e.clear();else if(typeof r=="number")for(const[o,a]of e){const c=a.filter(l=>l.output!==r);c.length===0?e.delete(o):e.set(o,c)}else if(e.has(r))if(i===void 0)e.delete(r);else{const o=e.get(r);if(o!==void 0){const a=o.filter(c=>c.output!==i&&(c.input!==s||s===void 0));a.length===0?e.delete(r):e.set(r,a)}}for(const[o,a]of e)a.forEach(c=>{C_(o)?n.connect(o,c.output,c.input):n.connect(o,c.output)})})(n.disconnect)},m9=(n,e,t,r)=>{const{activeInputs:i,passiveInputs:s}=qp(e),{outputs:o}=Fi(n),a=jp(n),c=l=>{const u=Hn(n),h=mp(e);if(l){const p=$O(s,n,t);jR(i,n,p,!1),!r&&!Uu(n)&&u.connect(h,t)}else{const p=d9(i,n,t);$R(s,p,!1),!r&&!Uu(n)&&u.disconnect(h,t)}};return Ju(o,[e,t],l=>l[0]===e&&l[1]===t,!0)?(a.add(c),gc(n)?jR(i,n,[t,c],!0):$R(s,[n,t,c],!0),!0):!1},g9=(n,e,t,r)=>{const{activeInputs:i,passiveInputs:s}=Fi(e),o=WO(i[r],n,t);return o===null?[zO(s,n,t,r)[2],!1]:[o[2],!0]},_9=(n,e,t)=>{const{activeInputs:r,passiveInputs:i}=qp(e),s=WO(r,n,t);return s===null?[$O(i,n,t)[1],!1]:[s[2],!0]},gT=(n,e,t,r,i)=>{const[s,o]=g9(n,t,r,i);if(s!==null&&(jO(n,s),o&&!e&&!Uu(n)&&M_(Hn(n),Hn(t),r,i)),gc(t)){const{activeInputs:a}=Fi(t);RE(t,a)}},_T=(n,e,t,r)=>{const[i,s]=_9(n,t,r);i!==null&&(jO(n,i),s&&!e&&!Uu(n)&&Hn(n).disconnect(mp(t),r))},v9=(n,e)=>{const t=Fi(n),r=[];for(const i of t.outputs)Xp(i)?gT(n,e,...i):_T(n,e,...i),r.push(i[0]);return t.outputs.clear(),r},y9=(n,e,t)=>{const r=Fi(n),i=[];for(const s of r.outputs)s[1]===t&&(Xp(s)?gT(n,e,...s):_T(n,e,...s),i.push(s[0]),r.outputs.delete(s));return i},x9=(n,e,t,r,i)=>{const s=Fi(n);return Array.from(s.outputs).filter(o=>o[0]===t&&(r===void 0||o[1]===r)&&(i===void 0||o[2]===i)).map(o=>(Xp(o)?gT(n,e,...o):_T(n,e,...o),s.outputs.delete(o),o[0]))},S9=(n,e,t,r,i,s,o,a,c,l,u,h,p,m,g,v)=>class extends l{constructor(_,S,w,T){super(w),this._context=_,this._nativeAudioNode=w;const k=u(_);h(k)&&t(qR,()=>qR(k,v))!==!0&&p9(w),dT.set(this,w),FO.set(this,new Set),_.state!=="closed"&&S&&If(this),n(this,T,w)}get channelCount(){return this._nativeAudioNode.channelCount}set channelCount(_){this._nativeAudioNode.channelCount=_}get channelCountMode(){return this._nativeAudioNode.channelCountMode}set channelCountMode(_){this._nativeAudioNode.channelCountMode=_}get channelInterpretation(){return this._nativeAudioNode.channelInterpretation}set channelInterpretation(_){this._nativeAudioNode.channelInterpretation=_}get context(){return this._context}get numberOfInputs(){return this._nativeAudioNode.numberOfInputs}get numberOfOutputs(){return this._nativeAudioNode.numberOfOutputs}connect(_,S=0,w=0){if(S<0||S>=this._nativeAudioNode.numberOfOutputs)throw i();const T=u(this._context),k=g(T);if(p(_)||m(_))throw s();if(b_(_)){const O=Hn(_);try{const N=A_(this._nativeAudioNode,O,S,w),U=$0(this);(k||U)&&this._nativeAudioNode.disconnect(...N),this.context.state!=="closed"&&!U&&$0(_)&&If(_)}catch(N){throw N.code===12?s():N}if(e(this,_,S,w,k)){const N=c([this],_);OS(N,r(k))}return _}const R=mp(_);if(R.name==="playbackRate"&&R.maxValue===1024)throw o();try{this._nativeAudioNode.connect(R,S),(k||$0(this))&&this._nativeAudioNode.disconnect(R,S)}catch(O){throw O.code===12?s():O}if(m9(this,_,S,k)){const O=c([this],_);OS(O,r(k))}}disconnect(_,S,w){let T;const k=u(this._context),R=g(k);if(_===void 0)T=v9(this,R);else if(typeof _=="number"){if(_<0||_>=this.numberOfOutputs)throw i();T=y9(this,R,_)}else{if(S!==void 0&&(S<0||S>=this.numberOfOutputs)||b_(_)&&w!==void 0&&(w<0||w>=_.numberOfInputs))throw i();if(T=x9(this,R,_,S,w),T.length===0)throw s()}for(const C of T){const O=c([this],C);OS(O,a)}}},E9=(n,e,t,r,i,s,o,a,c,l,u,h,p)=>(m,g,v,y=null,_=null)=>{const S=v.value,w=new NW(S),T=g?r(w):null,k={get defaultValue(){return S},get maxValue(){return y===null?v.maxValue:y},get minValue(){return _===null?v.minValue:_},get value(){return v.value},set value(R){v.value=R,k.setValueAtTime(R,m.context.currentTime)},cancelAndHoldAtTime(R){if(typeof v.cancelAndHoldAtTime=="function")T===null&&w.flush(m.context.currentTime),w.add(i(R)),v.cancelAndHoldAtTime(R);else{const C=Array.from(w).pop();T===null&&w.flush(m.context.currentTime),w.add(i(R));const O=Array.from(w).pop();v.cancelScheduledValues(R),C!==O&&O!==void 0&&(O.type==="exponentialRampToValue"?v.exponentialRampToValueAtTime(O.value,O.endTime):O.type==="linearRampToValue"?v.linearRampToValueAtTime(O.value,O.endTime):O.type==="setValue"?v.setValueAtTime(O.value,O.startTime):O.type==="setValueCurve"&&v.setValueCurveAtTime(O.values,O.startTime,O.duration))}return k},cancelScheduledValues(R){return T===null&&w.flush(m.context.currentTime),w.add(s(R)),v.cancelScheduledValues(R),k},exponentialRampToValueAtTime(R,C){if(R===0)throw new RangeError;if(!Number.isFinite(C)||C<0)throw new RangeError;const O=m.context.currentTime;return T===null&&w.flush(O),Array.from(w).length===0&&(w.add(l(S,O)),v.setValueAtTime(S,O)),w.add(o(R,C)),v.exponentialRampToValueAtTime(R,C),k},linearRampToValueAtTime(R,C){const O=m.context.currentTime;return T===null&&w.flush(O),Array.from(w).length===0&&(w.add(l(S,O)),v.setValueAtTime(S,O)),w.add(a(R,C)),v.linearRampToValueAtTime(R,C),k},setTargetAtTime(R,C,O){return T===null&&w.flush(m.context.currentTime),w.add(c(R,C,O)),v.setTargetAtTime(R,C,O),k},setValueAtTime(R,C){return T===null&&w.flush(m.context.currentTime),w.add(l(R,C)),v.setValueAtTime(R,C),k},setValueCurveAtTime(R,C,O){const M=R instanceof Float32Array?R:new Float32Array(R);if(h!==null&&h.name==="webkitAudioContext"){const N=C+O,U=m.context.sampleRate,L=Math.ceil(C*U),P=Math.floor(N*U),b=P-L,B=new Float32Array(b);for(let V=0;V({replay(e){for(const t of n)if(t.type==="exponentialRampToValue"){const{endTime:r,value:i}=t;e.exponentialRampToValueAtTime(i,r)}else if(t.type==="linearRampToValue"){const{endTime:r,value:i}=t;e.linearRampToValueAtTime(i,r)}else if(t.type==="setTarget"){const{startTime:r,target:i,timeConstant:s}=t;e.setTargetAtTime(i,r,s)}else if(t.type==="setValue"){const{startTime:r,value:i}=t;e.setValueAtTime(i,r)}else if(t.type==="setValueCurve"){const{duration:r,startTime:i,values:s}=t;e.setValueCurveAtTime(s,i,r)}else throw new Error("Can't apply an unknown automation.")}});class qO{constructor(e){this._map=new Map(e)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(e,t=null){return this._map.forEach((r,i)=>e.call(t,r,i,this))}get(e){return this._map.get(e)}has(e){return this._map.has(e)}keys(){return this._map.keys()}values(){return this._map.values()}}const T9={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,parameterData:{},processorOptions:{}},b9=(n,e,t,r,i,s,o,a,c,l,u,h,p,m)=>class extends e{constructor(v,y,_){var S;const w=a(v),T=c(w),k=u({...T9,..._});p(k);const R=ME.get(w),C=R==null?void 0:R.get(y),O=T||w.state!=="closed"?w:(S=o(w))!==null&&S!==void 0?S:w,M=i(O,T?null:v.baseLatency,l,y,C,k),N=T?r(y,k,C):null;super(v,!0,M,N);const U=[];M.parameters.forEach((P,b)=>{const B=t(this,T,P);U.push([b,B])}),this._nativeAudioWorkletNode=M,this._onprocessorerror=null,this._parameters=new qO(U),T&&n(w,this);const{activeInputs:L}=s(this);h(M,L)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(v){const y=typeof v=="function"?m(this,v):null;this._nativeAudioWorkletNode.onprocessorerror=y;const _=this._nativeAudioWorkletNode.onprocessorerror;this._onprocessorerror=_!==null&&_===y?v:_}get parameters(){return this._parameters===null?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}};function R_(n,e,t,r,i){if(typeof n.copyFromChannel=="function")e[t].byteLength===0&&(e[t]=new Float32Array(128)),n.copyFromChannel(e[t],r,i);else{const s=n.getChannelData(r);if(e[t].byteLength===0)e[t]=s.slice(i,i+128);else{const o=new Float32Array(s.buffer,i*Float32Array.BYTES_PER_ELEMENT,128);e[t].set(o)}}}const XO=(n,e,t,r,i)=>{typeof n.copyToChannel=="function"?e[t].byteLength!==0&&n.copyToChannel(e[t],r,i):e[t].byteLength!==0&&n.getChannelData(r).set(e[t],i)},k_=(n,e)=>{const t=[];for(let r=0;r{const t=Ro(CE,n),r=Hn(e);return Ro(t,r)},M9=async(n,e,t,r,i,s,o)=>{const a=e===null?Math.ceil(n.context.length/128)*128:e.length,c=r.channelCount*r.numberOfInputs,l=i.reduce((y,_)=>y+_,0),u=l===0?null:t.createBuffer(l,a,t.sampleRate);if(s===void 0)throw new Error("Missing the processor constructor.");const h=Fi(n),p=await A9(t,n),m=k_(r.numberOfInputs,r.channelCount),g=k_(r.numberOfOutputs,i),v=Array.from(n.parameters.keys()).reduce((y,_)=>({...y,[_]:new Float32Array(128)}),{});for(let y=0;y0&&e!==null)for(let _=0;_{R_(e,v,_,c+S,y)});for(let _=0;_h.activeInputs[T].size===0?[]:w),S=o(y/t.sampleRate,t.sampleRate,()=>p.process(_,g,v));if(u!==null)for(let w=0,T=0;w(y,_,S)=>{const w=new WeakMap;let T=null;const k=async(R,C)=>{let O=u(R),M=null;const N=Ti(O,C),U=Array.isArray(_.outputChannelCount)?_.outputChannelCount:Array.from(_.outputChannelCount);if(h===null){const L=U.reduce((W,V)=>W+V,0),P=i(C,{channelCount:Math.max(1,L),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,L)}),b=[];for(let W=0;W{const X=new p($,Math.ceil(R.context.length/128)*128,C.sampleRate),Y=[],ve=[];for(let be=0;be<_.numberOfInputs;be+=1)Y.push(o(X,{channelCount:_.channelCount,channelCountMode:_.channelCountMode,channelInterpretation:_.channelInterpretation,gain:1})),ve.push(i(X,{channelCount:_.channelCount,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:_.channelCount}));const ne=await Promise.all(Array.from(R.parameters.values()).map(async be=>{const Ce=s(X,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:be.value});return await m(X,be,Ce.offset),Ce})),ie=r(X,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,V+G)});for(let be=0;be<_.numberOfInputs;be+=1){Y[be].connect(ve[be]);for(let Ce=0;Ce<_.channelCount;Ce+=1)ve[be].connect(ie,Ce,be*_.channelCount+Ce)}for(const[be,Ce]of ne.entries())Ce.connect(ie,0,V+be),Ce.start(0);return ie.connect(X.destination),await Promise.all(Y.map(be=>g(R,X,be))),v(X)})(),C,_,U,S,l)}const L=await T,P=t(C,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),[b,B,W]=M;L!==null&&(P.buffer=L,P.start(0)),P.connect(b);for(let V=0,G=0;Vclass extends g{constructor(k,R){super(k,R),this._nativeContext=k,this._audioWorklet=n===void 0?void 0:{addModule:(C,O)=>n(this,C,O)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new e(this)}createBiquadFilter(){return new i(this)}createBuffer(k,R,C){return new t({length:R,numberOfChannels:k,sampleRate:C})}createBufferSource(){return new r(this)}createChannelMerger(k=6){return new s(this,{numberOfInputs:k})}createChannelSplitter(k=6){return new o(this,{numberOfOutputs:k})}createConstantSource(){return new a(this)}createConvolver(){return new c(this)}createDelay(k=1){return new u(this,{maxDelayTime:k})}createDynamicsCompressor(){return new h(this)}createGain(){return new p(this)}createIIRFilter(k,R){return new m(this,{feedback:R,feedforward:k})}createOscillator(){return new v(this)}createPanner(){return new y(this)}createPeriodicWave(k,R,C={disableNormalization:!1}){return new _(this,{...C,imag:R,real:k})}createStereoPanner(){return new S(this)}createWaveShaper(){return new w(this)}decodeAudioData(k,R,C){return l(this._nativeContext,k).then(O=>(typeof R=="function"&&R(O),O),O=>{throw typeof C=="function"&&C(O),O})}},k9={Q:1,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:350,gain:0,type:"lowpass"},I9=(n,e,t,r,i,s,o,a)=>class extends n{constructor(l,u){const h=s(l),p={...k9,...u},m=i(h,p),g=o(h),v=g?t():null;super(l,!1,m,v),this._Q=e(this,g,m.Q,Pi,es),this._detune=e(this,g,m.detune,1200*Math.log2(Pi),-1200*Math.log2(Pi)),this._frequency=e(this,g,m.frequency,l.sampleRate/2,0),this._gain=e(this,g,m.gain,40*Math.log10(Pi),es),this._nativeBiquadFilterNode=m,a(this,1)}get detune(){return this._detune}get frequency(){return this._frequency}get gain(){return this._gain}get Q(){return this._Q}get type(){return this._nativeBiquadFilterNode.type}set type(l){this._nativeBiquadFilterNode.type=l}getFrequencyResponse(l,u,h){try{this._nativeBiquadFilterNode.getFrequencyResponse(l,u,h)}catch(p){throw p.code===11?r():p}if(l.length!==u.length||u.length!==h.length)throw r()}},N9=(n,e,t,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=t(a);const u=Ti(l,c);if(!u){const h={Q:l.Q.value,channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,detune:l.detune.value,frequency:l.frequency.value,gain:l.gain.value,type:l.type};l=e(c,h)}return s.set(c,l),u?(await n(c,a.Q,l.Q),await n(c,a.detune,l.detune),await n(c,a.frequency,l.frequency),await n(c,a.gain,l.gain)):(await r(c,a.Q,l.Q),await r(c,a.detune,l.detune),await r(c,a.frequency,l.frequency),await r(c,a.gain,l.gain)),await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},O9=(n,e)=>(t,r)=>{const i=e.get(t);if(i!==void 0)return i;const s=n.get(t);if(s!==void 0)return s;try{const o=r();return o instanceof Promise?(n.set(t,o),o.catch(()=>!1).then(a=>(n.delete(t),e.set(t,a),a))):(e.set(t,o),o)}catch{return e.set(t,!1),!1}},L9={channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6},P9=(n,e,t,r,i)=>class extends n{constructor(o,a){const c=r(o),l={...L9,...a},u=t(c,l),h=i(c)?e():null;super(o,!1,u,h)}},D9=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ti(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,numberOfInputs:a.numberOfInputs};a=n(o,l)}return r.set(o,a),await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},U9={channelCount:6,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:6},F9=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=r(a),u=s({...U9,...c}),h=t(l,u),p=i(l)?e():null;super(a,!1,h,p)}},B9=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ti(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,numberOfOutputs:a.numberOfOutputs};a=n(o,l)}return r.set(o,a),await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},z9=n=>(e,t,r)=>n(t,e,r),V9=n=>(e,t,r=0,i=0)=>{const s=e[r];if(s===void 0)throw n();return C_(t)?s.connect(t,0,i):s.connect(t,0)},H9=n=>(e,t)=>{const r=n(e,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),i=e.createBuffer(1,2,44100);return r.buffer=i,r.loop=!0,r.connect(t),r.start(),()=>{r.stop(),r.disconnect(t)}},G9={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",offset:1},W9=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...G9,...l},p=r(u,h),m=s(u),g=m?t():null;super(c,!1,p,g),this._constantSourceNodeRenderer=g,this._nativeConstantSourceNode=p,this._offset=e(this,m,p.offset,Pi,es),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(c){const l=typeof c=="function"?o(this,c):null;this._nativeConstantSourceNode.onended=l;const u=this._nativeConstantSourceNode.onended;this._onended=u!==null&&u===l?c:u}start(c=0){if(this._nativeConstantSourceNode.start(c),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.start=c),this.context.state!=="closed"){If(this);const l=()=>{this._nativeConstantSourceNode.removeEventListener("ended",l),gc(this)&&$p(this)};this._nativeConstantSourceNode.addEventListener("ended",l)}}stop(c=0){this._nativeConstantSourceNode.stop(c),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.stop=c)}},j9=(n,e,t,r,i)=>()=>{const s=new WeakMap;let o=null,a=null;const c=async(l,u)=>{let h=t(l);const p=Ti(h,u);if(!p){const m={channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,offset:h.offset.value};h=e(u,m),o!==null&&h.start(o),a!==null&&h.stop(a)}return s.set(u,h),p?await n(u,l.offset,h.offset):await r(u,l.offset,h.offset),await i(l,u,h),h};return{set start(l){o=l},set stop(l){a=l},render(l,u){const h=s.get(u);return h!==void 0?Promise.resolve(h):c(l,u)}}},$9=n=>e=>(n[0]=e,n[0]),q9={buffer:null,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",disableNormalization:!1},X9=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=r(a),u={...q9,...c},h=t(l,u),m=i(l)?e():null;super(a,!1,h,m),this._isBufferNullified=!1,this._nativeConvolverNode=h,u.buffer!==null&&s(this,u.buffer.duration)}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(a){if(this._nativeConvolverNode.buffer=a,a===null&&this._nativeConvolverNode.buffer!==null){const c=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=c.createBuffer(1,1,c.sampleRate),this._isBufferNullified=!0,s(this,0)}else this._isBufferNullified=!1,s(this,this._nativeConvolverNode.buffer===null?0:this._nativeConvolverNode.buffer.duration)}get normalize(){return this._nativeConvolverNode.normalize}set normalize(a){this._nativeConvolverNode.normalize=a}},K9=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ti(a,o)){const l={buffer:a.buffer,channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,disableNormalization:!a.normalize};a=n(o,l)}return r.set(o,a),td(a)?await t(s,o,a.inputs[0]):await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},Y9=(n,e)=>(t,r,i)=>{if(e===null)throw new Error("Missing the native OfflineAudioContext constructor.");try{return new e(t,r,i)}catch(s){throw s.name==="SyntaxError"?n():s}},Z9=()=>new DOMException("","DataCloneError"),XR=n=>{const{port1:e,port2:t}=new MessageChannel;return new Promise(r=>{const i=()=>{t.onmessage=null,e.close(),t.close(),r()};t.onmessage=()=>i();try{e.postMessage(n,[n])}catch{}finally{i()}})},Q9=(n,e,t,r,i,s,o,a,c,l,u)=>(h,p)=>{const m=o(h)?h:s(h);if(i.has(p)){const g=t();return Promise.reject(g)}try{i.add(p)}catch{}return e(c,()=>c(m))?m.decodeAudioData(p).then(g=>(XR(p).catch(()=>{}),e(a,()=>a(g))||u(g),n.add(g),g)):new Promise((g,v)=>{const y=async()=>{try{await XR(p)}catch{}},_=S=>{v(S),y()};try{m.decodeAudioData(p,S=>{typeof S.copyFromChannel!="function"&&(l(S),mT(S)),n.add(S),y().then(()=>g(S))},S=>{_(S===null?r():S)})}catch(S){_(S)}})},J9=(n,e,t,r,i,s,o,a)=>(c,l)=>{const u=e.get(c);if(u===void 0)throw new Error("Missing the expected cycle count.");const h=s(c.context),p=a(h);if(u===l){if(e.delete(c),!p&&o(c)){const m=r(c),{outputs:g}=t(c);for(const v of g)if(Xp(v)){const y=r(v[0]);n(m,y,v[1],v[2])}else{const y=i(v[0]);m.connect(y,v[1])}}}else e.set(c,u-l)},ej={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",delayTime:0,maxDelayTime:1},tj=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...ej,...l},p=r(u,h),m=s(u),g=m?t(h.maxDelayTime):null;super(c,!1,p,g),this._delayTime=e(this,m,p.delayTime),o(this,h.maxDelayTime)}get delayTime(){return this._delayTime}},nj=(n,e,t,r,i)=>s=>{const o=new WeakMap,a=async(c,l)=>{let u=t(c);const h=Ti(u,l);if(!h){const p={channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,delayTime:u.delayTime.value,maxDelayTime:s};u=e(l,p)}return o.set(l,u),h?await n(l,c.delayTime,u.delayTime):await r(l,c.delayTime,u.delayTime),await i(c,l,u),u};return{render(c,l){const u=o.get(l);return u!==void 0?Promise.resolve(u):a(c,l)}}},rj=n=>(e,t,r,i)=>n(e[i],s=>s[0]===t&&s[1]===r),ij=n=>(e,t)=>{n(e).delete(t)},sj=n=>"delayTime"in n,oj=(n,e,t)=>function r(i,s){const o=b_(s)?s:t(n,s);if(sj(o))return[];if(i[0]===o)return[i];if(i.includes(o))return[];const{outputs:a}=e(o);return Array.from(a).map(c=>r([...i,o],c[0])).reduce((c,l)=>c.concat(l),[])},o0=(n,e,t)=>{const r=e[t];if(r===void 0)throw n();return r},aj=n=>(e,t=void 0,r=void 0,i=0)=>t===void 0?e.forEach(s=>s.disconnect()):typeof t=="number"?o0(n,e,t).disconnect():C_(t)?r===void 0?e.forEach(s=>s.disconnect(t)):i===void 0?o0(n,e,r).disconnect(t,0):o0(n,e,r).disconnect(t,0,i):r===void 0?e.forEach(s=>s.disconnect(t)):o0(n,e,r).disconnect(t,0),cj={attack:.003,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",knee:30,ratio:12,release:.25,threshold:-24},lj=(n,e,t,r,i,s,o,a)=>class extends n{constructor(l,u){const h=s(l),p={...cj,...u},m=r(h,p),g=o(h),v=g?t():null;super(l,!1,m,v),this._attack=e(this,g,m.attack),this._knee=e(this,g,m.knee),this._nativeDynamicsCompressorNode=m,this._ratio=e(this,g,m.ratio),this._release=e(this,g,m.release),this._threshold=e(this,g,m.threshold),a(this,.006)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(l){const u=this._nativeDynamicsCompressorNode.channelCount;if(this._nativeDynamicsCompressorNode.channelCount=l,l>2)throw this._nativeDynamicsCompressorNode.channelCount=u,i()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(l){const u=this._nativeDynamicsCompressorNode.channelCountMode;if(this._nativeDynamicsCompressorNode.channelCountMode=l,l==="max")throw this._nativeDynamicsCompressorNode.channelCountMode=u,i()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return typeof this._nativeDynamicsCompressorNode.reduction.value=="number"?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}},uj=(n,e,t,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=t(a);const u=Ti(l,c);if(!u){const h={attack:l.attack.value,channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,knee:l.knee.value,ratio:l.ratio.value,release:l.release.value,threshold:l.threshold.value};l=e(c,h)}return s.set(c,l),u?(await n(c,a.attack,l.attack),await n(c,a.knee,l.knee),await n(c,a.ratio,l.ratio),await n(c,a.release,l.release),await n(c,a.threshold,l.threshold)):(await r(c,a.attack,l.attack),await r(c,a.knee,l.knee),await r(c,a.ratio,l.ratio),await r(c,a.release,l.release),await r(c,a.threshold,l.threshold)),await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},hj=()=>new DOMException("","EncodingError"),fj=n=>e=>new Promise((t,r)=>{if(n===null){r(new SyntaxError);return}const i=n.document.head;if(i===null)r(new SyntaxError);else{const s=n.document.createElement("script"),o=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(o),c=n.onerror,l=()=>{n.onerror=c,URL.revokeObjectURL(a)};n.onerror=(u,h,p,m,g)=>{if(h===a||h===n.location.href&&p===1&&m===1)return l(),r(g),!1;if(c!==null)return c(u,h,p,m,g)},s.onerror=()=>{l(),r(new SyntaxError)},s.onload=()=>{l(),t()},s.src=a,s.type="module",i.appendChild(s)}}),dj=n=>class{constructor(t){this._nativeEventTarget=t,this._listeners=new WeakMap}addEventListener(t,r,i){if(r!==null){let s=this._listeners.get(r);s===void 0&&(s=n(this,r),typeof r=="function"&&this._listeners.set(r,s)),this._nativeEventTarget.addEventListener(t,s,i)}}dispatchEvent(t){return this._nativeEventTarget.dispatchEvent(t)}removeEventListener(t,r,i){const s=r===null?void 0:this._listeners.get(r);this._nativeEventTarget.removeEventListener(t,s===void 0?null:s,i)}},pj=n=>(e,t,r)=>{Object.defineProperties(n,{currentFrame:{configurable:!0,get(){return Math.round(e*t)}},currentTime:{configurable:!0,get(){return e}}});try{return r()}finally{n!==null&&(delete n.currentFrame,delete n.currentTime)}},mj=n=>async e=>{try{const t=await fetch(e);if(t.ok)return[await t.text(),t.url]}catch{}throw n()},gj={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",gain:1},_j=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=i(a),u={...gj,...c},h=r(l,u),p=s(l),m=p?t():null;super(a,!1,h,m),this._gain=e(this,p,h.gain,Pi,es)}get gain(){return this._gain}},vj=(n,e,t,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=t(a);const u=Ti(l,c);if(!u){const h={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,gain:l.gain.value};l=e(c,h)}return s.set(c,l),u?await n(c,a.gain,l.gain):await r(c,a.gain,l.gain),await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},yj=(n,e)=>t=>e(n,t),xj=n=>e=>{const t=n(e);if(t.renderer===null)throw new Error("Missing the renderer of the given AudioNode in the audio graph.");return t.renderer},Sj=n=>e=>{var t;return(t=n.get(e))!==null&&t!==void 0?t:0},Ej=n=>e=>{const t=n(e);if(t.renderer===null)throw new Error("Missing the renderer of the given AudioParam in the audio graph.");return t.renderer},wj=n=>e=>n.get(e),ii=()=>new DOMException("","InvalidStateError"),Tj=n=>e=>{const t=n.get(e);if(t===void 0)throw ii();return t},bj=(n,e)=>t=>{let r=n.get(t);if(r!==void 0)return r;if(e===null)throw new Error("Missing the native OfflineAudioContext constructor.");return r=new e(1,1,44100),n.set(t,r),r},Aj=n=>e=>{const t=n.get(e);if(t===void 0)throw new Error("The context has no set of AudioWorkletNodes.");return t},Rv=()=>new DOMException("","InvalidAccessError"),Mj=n=>{n.getFrequencyResponse=(e=>(t,r,i)=>{if(t.length!==r.length||r.length!==i.length)throw Rv();return e.call(n,t,r,i)})(n.getFrequencyResponse)},Cj={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers"},Rj=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=r(a),u=i(l),h={...Cj,...c},p=e(l,u?null:a.baseLatency,h),m=u?t(h.feedback,h.feedforward):null;super(a,!1,p,m),Mj(p),this._nativeIIRFilterNode=p,s(this,1)}getFrequencyResponse(a,c,l){return this._nativeIIRFilterNode.getFrequencyResponse(a,c,l)}},KO=(n,e,t,r,i,s,o,a,c,l,u)=>{const h=l.length;let p=a;for(let m=0;m{const i=t instanceof Float64Array?t:new Float64Array(t),s=r instanceof Float64Array?r:new Float64Array(r),o=i.length,a=s.length,c=Math.min(o,a);if(i[0]!==1){for(let g=0;g(s,o)=>{const a=new WeakMap;let c=null;const l=async(u,h)=>{let p=null,m=e(u);const g=Ti(m,h);if(h.createIIRFilter===void 0?p=n(h,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}):g||(m=h.createIIRFilter(o,s)),a.set(h,p===null?m:p),p!==null){if(c===null){if(t===null)throw new Error("Missing the native OfflineAudioContext constructor.");const y=new t(u.context.destination.channelCount,u.context.length,h.sampleRate);c=(async()=>{await r(u,y,y.destination);const _=await i(y);return kj(_,h,s,o)})()}const v=await c;return p.buffer=v,p.start(0),p}return await r(u,h,m),m};return{render(u,h){const p=a.get(h);return p!==void 0?Promise.resolve(p):l(u,h)}}},Nj=(n,e,t,r,i,s)=>o=>(a,c)=>{const l=n.get(a);if(l===void 0){if(!o&&s(a)){const u=r(a),{outputs:h}=t(a);for(const p of h)if(Xp(p)){const m=r(p[0]);e(u,m,p[1],p[2])}else{const m=i(p[0]);u.disconnect(m,p[1])}}n.set(a,c)}else n.set(a,l+c)},Oj=(n,e)=>t=>{const r=n.get(t);return e(r)||e(t)},Lj=(n,e)=>t=>n.has(t)||e(t),Pj=(n,e)=>t=>n.has(t)||e(t),Dj=(n,e)=>t=>{const r=n.get(t);return e(r)||e(t)},Uj=n=>e=>n!==null&&e instanceof n,Fj=n=>e=>n!==null&&typeof n.AudioNode=="function"&&e instanceof n.AudioNode,Bj=n=>e=>n!==null&&typeof n.AudioParam=="function"&&e instanceof n.AudioParam,zj=(n,e)=>t=>n(t)||e(t),Vj=n=>e=>n!==null&&e instanceof n,Hj=n=>n!==null&&n.isSecureContext,Gj=(n,e,t,r)=>class extends n{constructor(s,o){const a=t(s),c=e(a,o);if(r(a))throw TypeError();super(s,!0,c,null),this._nativeMediaElementAudioSourceNode=c}get mediaElement(){return this._nativeMediaElementAudioSourceNode.mediaElement}},Wj={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers"},jj=(n,e,t,r)=>class extends n{constructor(s,o){const a=t(s);if(r(a))throw new TypeError;const c={...Wj,...o},l=e(a,c);super(s,!1,l,null),this._nativeMediaStreamAudioDestinationNode=l}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}},$j=(n,e,t,r)=>class extends n{constructor(s,o){const a=t(s),c=e(a,o);if(r(a))throw new TypeError;super(s,!0,c,null),this._nativeMediaStreamAudioSourceNode=c}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}},qj=(n,e,t)=>class extends n{constructor(i,s){const o=t(i),a=e(o,s);super(i,!0,a,null)}},Xj=(n,e,t,r,i,s)=>class extends t{constructor(a,c){super(a),this._nativeContext=a,Mv.set(this,a),r(a)&&i.set(a,new Set),this._destination=new n(this,c),this._listener=e(this,a),this._onstatechange=null}get currentTime(){return this._nativeContext.currentTime}get destination(){return this._destination}get listener(){return this._listener}get onstatechange(){return this._onstatechange}set onstatechange(a){const c=typeof a=="function"?s(this,a):null;this._nativeContext.onstatechange=c;const l=this._nativeContext.onstatechange;this._onstatechange=l!==null&&l===c?a:l}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}},gp=n=>{const e=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{const t=n.decodeAudioData(e.buffer,()=>{});return t===void 0?!1:(t.catch(()=>{}),!0)}catch{}return!1},Kj=(n,e)=>(t,r,i)=>{const s=new Set;return t.connect=(o=>(a,c=0,l=0)=>{const u=s.size===0;if(e(a))return o.call(t,a,c,l),n(s,[a,c,l],h=>h[0]===a&&h[1]===c&&h[2]===l,!0),u&&r(),a;o.call(t,a,c),n(s,[a,c],h=>h[0]===a&&h[1]===c,!0),u&&r()})(t.connect),t.disconnect=(o=>(a,c,l)=>{const u=s.size>0;if(a===void 0)o.apply(t),s.clear();else if(typeof a=="number"){o.call(t,a);for(const p of s)p[1]===a&&s.delete(p)}else{e(a)?o.call(t,a,c,l):o.call(t,a,c);for(const p of s)p[0]===a&&(c===void 0||p[1]===c)&&(l===void 0||p[2]===l)&&s.delete(p)}const h=s.size===0;u&&h&&i()})(t.disconnect),t},Xn=(n,e,t)=>{const r=e[t];r!==void 0&&r!==n[t]&&(n[t]=r)},Hr=(n,e)=>{Xn(n,e,"channelCount"),Xn(n,e,"channelCountMode"),Xn(n,e,"channelInterpretation")},KR=n=>typeof n.getFloatTimeDomainData=="function",Yj=n=>{n.getFloatTimeDomainData=e=>{const t=new Uint8Array(e.length);n.getByteTimeDomainData(t);const r=Math.max(t.length,n.fftSize);for(let i=0;i(t,r)=>{const i=t.createAnalyser();if(Hr(i,r),!(r.maxDecibels>r.minDecibels))throw e();return Xn(i,r,"fftSize"),Xn(i,r,"maxDecibels"),Xn(i,r,"minDecibels"),Xn(i,r,"smoothingTimeConstant"),n(KR,()=>KR(i))||Yj(i),i},Qj=n=>n===null?null:n.hasOwnProperty("AudioBuffer")?n.AudioBuffer:null,nr=(n,e,t)=>{const r=e[t];r!==void 0&&r!==n[t].value&&(n[t].value=r)},Jj=n=>{n.start=(e=>{let t=!1;return(r=0,i=0,s)=>{if(t)throw ii();e.call(n,r,i,s),t=!0}})(n.start)},vT=n=>{n.start=(e=>(t=0,r=0,i)=>{if(typeof i=="number"&&i<0||r<0||t<0)throw new RangeError("The parameters can't be negative.");e.call(n,t,r,i)})(n.start)},yT=n=>{n.stop=(e=>(t=0)=>{if(t<0)throw new RangeError("The parameter can't be negative.");e.call(n,t)})(n.stop)},e$=(n,e,t,r,i,s,o,a,c,l,u)=>(h,p)=>{const m=h.createBufferSource();return Hr(m,p),nr(m,p,"playbackRate"),Xn(m,p,"buffer"),Xn(m,p,"loop"),Xn(m,p,"loopEnd"),Xn(m,p,"loopStart"),e(t,()=>t(h))||Jj(m),e(r,()=>r(h))||c(m),e(i,()=>i(h))||l(m,h),e(s,()=>s(h))||vT(m),e(o,()=>o(h))||u(m,h),e(a,()=>a(h))||yT(m),n(h,m),m},t$=n=>n===null?null:n.hasOwnProperty("AudioContext")?n.AudioContext:n.hasOwnProperty("webkitAudioContext")?n.webkitAudioContext:null,n$=(n,e)=>(t,r,i)=>{const s=t.destination;if(s.channelCount!==r)try{s.channelCount=r}catch{}i&&s.channelCountMode!=="explicit"&&(s.channelCountMode="explicit"),s.maxChannelCount===0&&Object.defineProperty(s,"maxChannelCount",{value:r});const o=n(t,{channelCount:r,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,gain:1});return e(o,"channelCount",a=>()=>a.call(o),a=>c=>{a.call(o,c);try{s.channelCount=c}catch(l){if(c>s.maxChannelCount)throw l}}),e(o,"channelCountMode",a=>()=>a.call(o),a=>c=>{a.call(o,c),s.channelCountMode=c}),e(o,"channelInterpretation",a=>()=>a.call(o),a=>c=>{a.call(o,c),s.channelInterpretation=c}),Object.defineProperty(o,"maxChannelCount",{get:()=>s.maxChannelCount}),o.connect(s),o},r$=n=>n===null?null:n.hasOwnProperty("AudioWorkletNode")?n.AudioWorkletNode:null,i$=n=>{const{port1:e}=new MessageChannel;try{e.postMessage(n)}finally{e.close()}},s$=(n,e,t,r,i)=>(s,o,a,c,l,u)=>{if(a!==null)try{const h=new a(s,c,u),p=new Map;let m=null;if(Object.defineProperties(h,{channelCount:{get:()=>u.channelCount,set:()=>{throw n()}},channelCountMode:{get:()=>"explicit",set:()=>{throw n()}},onprocessorerror:{get:()=>m,set:g=>{typeof m=="function"&&h.removeEventListener("processorerror",m),m=typeof g=="function"?g:null,typeof m=="function"&&h.addEventListener("processorerror",m)}}}),h.addEventListener=(g=>(...v)=>{if(v[0]==="processorerror"){const y=typeof v[1]=="function"?v[1]:typeof v[1]=="object"&&v[1]!==null&&typeof v[1].handleEvent=="function"?v[1].handleEvent:null;if(y!==null){const _=p.get(v[1]);_!==void 0?v[1]=_:(v[1]=S=>{S.type==="error"?(Object.defineProperties(S,{type:{value:"processorerror"}}),y(S)):y(new ErrorEvent(v[0],{...S}))},p.set(y,v[1]))}}return g.call(h,"error",v[1],v[2]),g.call(h,...v)})(h.addEventListener),h.removeEventListener=(g=>(...v)=>{if(v[0]==="processorerror"){const y=p.get(v[1]);y!==void 0&&(p.delete(v[1]),v[1]=y)}return g.call(h,"error",v[1],v[2]),g.call(h,v[0],v[1],v[2])})(h.removeEventListener),u.numberOfOutputs!==0){const g=t(s,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return h.connect(g).connect(s.destination),i(h,()=>g.disconnect(),()=>g.connect(s.destination))}return h}catch(h){throw h.code===11?r():h}if(l===void 0)throw r();return i$(u),e(s,o,l,u)},YO=(n,e)=>n===null?512:Math.max(512,Math.min(16384,Math.pow(2,Math.round(Math.log2(n*e))))),o$=n=>new Promise((e,t)=>{const{port1:r,port2:i}=new MessageChannel;r.onmessage=({data:s})=>{r.close(),i.close(),e(s)},r.onmessageerror=({data:s})=>{r.close(),i.close(),t(s)},i.postMessage(n)}),a$=async(n,e)=>{const t=await o$(e);return new n(t)},c$=(n,e,t,r)=>{let i=CE.get(n);i===void 0&&(i=new WeakMap,CE.set(n,i));const s=a$(t,r);return i.set(e,s),s},l$=(n,e,t,r,i,s,o,a,c,l,u,h,p)=>(m,g,v,y)=>{if(y.numberOfInputs===0&&y.numberOfOutputs===0)throw c();const _=Array.isArray(y.outputChannelCount)?y.outputChannelCount:Array.from(y.outputChannelCount);if(_.some(J=>J<1))throw c();if(_.length!==y.numberOfOutputs)throw e();if(y.channelCountMode!=="explicit")throw c();const S=y.channelCount*y.numberOfInputs,w=_.reduce((J,re)=>J+re,0),T=v.parameterDescriptors===void 0?0:v.parameterDescriptors.length;if(S+T>6||w>6)throw c();const k=new MessageChannel,R=[],C=[];for(let J=0;JJ===void 0?0:J},maxValue:{get:()=>re===void 0?Pi:re},minValue:{get:()=>j===void 0?es:j}}),O.push(te)}const M=r(m,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,S+T)}),N=YO(g,m.sampleRate),U=a(m,N,S+T,Math.max(1,w)),L=i(m,{channelCount:Math.max(1,w),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,w)}),P=[];for(let J=0;J{const j=O[re];return j.connect(M,0,S+re),j.start(0),[J,j.offset]}));M.connect(U);let B=y.channelInterpretation,W=null;const V=y.numberOfOutputs===0?[U]:P,G={get bufferSize(){return N},get channelCount(){return y.channelCount},set channelCount(J){throw t()},get channelCountMode(){return y.channelCountMode},set channelCountMode(J){throw t()},get channelInterpretation(){return B},set channelInterpretation(J){for(const re of R)re.channelInterpretation=J;B=J},get context(){return U.context},get inputs(){return R},get numberOfInputs(){return y.numberOfInputs},get numberOfOutputs(){return y.numberOfOutputs},get onprocessorerror(){return W},set onprocessorerror(J){typeof W=="function"&&G.removeEventListener("processorerror",W),W=typeof J=="function"?J:null,typeof W=="function"&&G.addEventListener("processorerror",W)},get parameters(){return b},get port(){return k.port2},addEventListener(...J){return U.addEventListener(J[0],J[1],J[2])},connect:n.bind(null,V),disconnect:l.bind(null,V),dispatchEvent(...J){return U.dispatchEvent(J[0])},removeEventListener(...J){return U.removeEventListener(J[0],J[1],J[2])}},$=new Map;k.port1.addEventListener=(J=>(...re)=>{if(re[0]==="message"){const j=typeof re[1]=="function"?re[1]:typeof re[1]=="object"&&re[1]!==null&&typeof re[1].handleEvent=="function"?re[1].handleEvent:null;if(j!==null){const H=$.get(re[1]);H!==void 0?re[1]=H:(re[1]=te=>{u(m.currentTime,m.sampleRate,()=>j(te))},$.set(j,re[1]))}}return J.call(k.port1,re[0],re[1],re[2])})(k.port1.addEventListener),k.port1.removeEventListener=(J=>(...re)=>{if(re[0]==="message"){const j=$.get(re[1]);j!==void 0&&($.delete(re[1]),re[1]=j)}return J.call(k.port1,re[0],re[1],re[2])})(k.port1.removeEventListener);let Z=null;Object.defineProperty(k.port1,"onmessage",{get:()=>Z,set:J=>{typeof Z=="function"&&k.port1.removeEventListener("message",Z),Z=typeof J=="function"?J:null,typeof Z=="function"&&(k.port1.addEventListener("message",Z),k.port1.start())}}),v.prototype.port=k.port1;let X=null;c$(m,G,v,y).then(J=>X=J);const ve=k_(y.numberOfInputs,y.channelCount),ne=k_(y.numberOfOutputs,_),ie=v.parameterDescriptors===void 0?[]:v.parameterDescriptors.reduce((J,{name:re})=>({...J,[re]:new Float32Array(128)}),{});let be=!0;const Ce=()=>{y.numberOfOutputs>0&&U.disconnect(L);for(let J=0,re=0;J{if(X!==null){const j=h(G);for(let H=0;H{R_(J,ie,te,S+oe,H)});for(let te=0;te{if(j[D].size>0)return Ee.set(D,N/128),z;const he=Ee.get(D);return he===void 0?[]:(z.every(ce=>ce.every(ge=>ge===0))&&(he===1?Ee.delete(D):Ee.set(D,he-1)),z)});be=u(m.currentTime+H/m.sampleRate,m.sampleRate,()=>X.process(te,ne,ie));for(let z=0,D=0;zU.connect(ze).connect(m.destination),rt=()=>{U.disconnect(ze),ze.disconnect()},ft=()=>{if(be){rt(),y.numberOfOutputs>0&&U.connect(L);for(let J=0,re=0;J{be&&(Ge(),Ce()),Le=!1};return Ge(),p(G,ft,A)},ZO=(n,e)=>{const t=n.createBiquadFilter();return Hr(t,e),nr(t,e,"Q"),nr(t,e,"detune"),nr(t,e,"frequency"),nr(t,e,"gain"),Xn(t,e,"type"),t},u$=(n,e)=>(t,r)=>{const i=t.createChannelMerger(r.numberOfInputs);return n!==null&&n.name==="webkitAudioContext"&&e(t,i),Hr(i,r),i},h$=n=>{const e=n.numberOfOutputs;Object.defineProperty(n,"channelCount",{get:()=>e,set:t=>{if(t!==e)throw ii()}}),Object.defineProperty(n,"channelCountMode",{get:()=>"explicit",set:t=>{if(t!=="explicit")throw ii()}}),Object.defineProperty(n,"channelInterpretation",{get:()=>"discrete",set:t=>{if(t!=="discrete")throw ii()}})},Kp=(n,e)=>{const t=n.createChannelSplitter(e.numberOfOutputs);return Hr(t,e),h$(t),t},f$=(n,e,t,r,i)=>(s,o)=>{if(s.createConstantSource===void 0)return t(s,o);const a=s.createConstantSource();return Hr(a,o),nr(a,o,"offset"),e(r,()=>r(s))||vT(a),e(i,()=>i(s))||yT(a),n(s,a),a},nd=(n,e)=>(n.connect=e.connect.bind(e),n.disconnect=e.disconnect.bind(e),n),d$=(n,e,t,r)=>(i,{offset:s,...o})=>{const a=i.createBuffer(1,2,44100),c=e(i,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),l=t(i,{...o,gain:s}),u=a.getChannelData(0);u[0]=1,u[1]=1,c.buffer=a,c.loop=!0;const h={get bufferSize(){},get channelCount(){return l.channelCount},set channelCount(g){l.channelCount=g},get channelCountMode(){return l.channelCountMode},set channelCountMode(g){l.channelCountMode=g},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(g){l.channelInterpretation=g},get context(){return l.context},get inputs(){return[]},get numberOfInputs(){return c.numberOfInputs},get numberOfOutputs(){return l.numberOfOutputs},get offset(){return l.gain},get onended(){return c.onended},set onended(g){c.onended=g},addEventListener(...g){return c.addEventListener(g[0],g[1],g[2])},dispatchEvent(...g){return c.dispatchEvent(g[0])},removeEventListener(...g){return c.removeEventListener(g[0],g[1],g[2])},start(g=0){c.start.call(c,g)},stop(g=0){c.stop.call(c,g)}},p=()=>c.connect(l),m=()=>c.disconnect(l);return n(i,c),r(nd(h,l),p,m)},p$=(n,e)=>(t,r)=>{const i=t.createConvolver();if(Hr(i,r),r.disableNormalization===i.normalize&&(i.normalize=!r.disableNormalization),Xn(i,r,"buffer"),r.channelCount>2||(e(i,"channelCount",s=>()=>s.call(i),s=>o=>{if(o>2)throw n();return s.call(i,o)}),r.channelCountMode==="max"))throw n();return e(i,"channelCountMode",s=>()=>s.call(i),s=>o=>{if(o==="max")throw n();return s.call(i,o)}),i},QO=(n,e)=>{const t=n.createDelay(e.maxDelayTime);return Hr(t,e),nr(t,e,"delayTime"),t},m$=n=>(e,t)=>{const r=e.createDynamicsCompressor();if(Hr(r,t),t.channelCount>2||t.channelCountMode==="max")throw n();return nr(r,t,"attack"),nr(r,t,"knee"),nr(r,t,"ratio"),nr(r,t,"release"),nr(r,t,"threshold"),r},ls=(n,e)=>{const t=n.createGain();return Hr(t,e),nr(t,e,"gain"),t},g$=n=>(e,t,r)=>{if(e.createIIRFilter===void 0)return n(e,t,r);const i=e.createIIRFilter(r.feedforward,r.feedback);return Hr(i,r),i};function _$(n,e){const t=e[0]*e[0]+e[1]*e[1];return[(n[0]*e[0]+n[1]*e[1])/t,(n[1]*e[0]-n[0]*e[1])/t]}function v$(n,e){return[n[0]*e[0]-n[1]*e[1],n[0]*e[1]+n[1]*e[0]]}function YR(n,e){let t=[0,0];for(let r=n.length-1;r>=0;r-=1)t=v$(t,e),t[0]+=n[r];return t}const y$=(n,e,t,r)=>(i,s,{channelCount:o,channelCountMode:a,channelInterpretation:c,feedback:l,feedforward:u})=>{const h=YO(s,i.sampleRate),p=l instanceof Float64Array?l:new Float64Array(l),m=u instanceof Float64Array?u:new Float64Array(u),g=p.length,v=m.length,y=Math.min(g,v);if(g===0||g>20)throw r();if(p[0]===0)throw e();if(v===0||v>20)throw r();if(m[0]===0)throw e();if(p[0]!==1){for(let O=0;O{const M=O.inputBuffer,N=O.outputBuffer,U=M.numberOfChannels;for(let L=0;Ln.createMediaElementSource(e.mediaElement),S$=(n,e)=>{const t=n.createMediaStreamDestination();return Hr(t,e),t.numberOfOutputs===1&&Object.defineProperty(t,"numberOfOutputs",{get:()=>0}),t},E$=(n,{mediaStream:e})=>{const t=e.getAudioTracks();t.sort((s,o)=>s.ido.id?1:0);const r=t.slice(0,1),i=n.createMediaStreamSource(new MediaStream(r));return Object.defineProperty(i,"mediaStream",{value:e}),i},w$=(n,e)=>(t,{mediaStreamTrack:r})=>{if(typeof t.createMediaStreamTrackSource=="function")return t.createMediaStreamTrackSource(r);const i=new MediaStream([r]),s=t.createMediaStreamSource(i);if(r.kind!=="audio")throw n();if(e(t))throw new TypeError;return s},T$=n=>n===null?null:n.hasOwnProperty("OfflineAudioContext")?n.OfflineAudioContext:n.hasOwnProperty("webkitOfflineAudioContext")?n.webkitOfflineAudioContext:null,b$=(n,e,t,r,i,s)=>(o,a)=>{const c=o.createOscillator();return Hr(c,a),nr(c,a,"detune"),nr(c,a,"frequency"),a.periodicWave!==void 0?c.setPeriodicWave(a.periodicWave):Xn(c,a,"type"),e(t,()=>t(o))||vT(c),e(r,()=>r(o))||s(c,o),e(i,()=>i(o))||yT(c),n(o,c),c},A$=n=>(e,t)=>{const r=e.createPanner();return r.orientationX===void 0?n(e,t):(Hr(r,t),nr(r,t,"orientationX"),nr(r,t,"orientationY"),nr(r,t,"orientationZ"),nr(r,t,"positionX"),nr(r,t,"positionY"),nr(r,t,"positionZ"),Xn(r,t,"coneInnerAngle"),Xn(r,t,"coneOuterAngle"),Xn(r,t,"coneOuterGain"),Xn(r,t,"distanceModel"),Xn(r,t,"maxDistance"),Xn(r,t,"panningModel"),Xn(r,t,"refDistance"),Xn(r,t,"rolloffFactor"),r)},M$=(n,e,t,r,i,s,o,a,c,l)=>(u,{coneInnerAngle:h,coneOuterAngle:p,coneOuterGain:m,distanceModel:g,maxDistance:v,orientationX:y,orientationY:_,orientationZ:S,panningModel:w,positionX:T,positionY:k,positionZ:R,refDistance:C,rolloffFactor:O,...M})=>{const N=u.createPanner();if(M.channelCount>2||M.channelCountMode==="max")throw o();Hr(N,M);const U={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},L=t(u,{...U,channelInterpretation:"speakers",numberOfInputs:6}),P=r(u,{...M,gain:1}),b=r(u,{...U,gain:1}),B=r(u,{...U,gain:0}),W=r(u,{...U,gain:0}),V=r(u,{...U,gain:0}),G=r(u,{...U,gain:0}),$=r(u,{...U,gain:0}),Z=i(u,256,6,1),X=s(u,{...U,curve:new Float32Array([1,1]),oversample:"none"});let Y=[y,_,S],ve=[T,k,R];const ne=new Float32Array(1);Z.onaudioprocess=({inputBuffer:Ee})=>{const Le=[c(Ee,ne,0),c(Ee,ne,1),c(Ee,ne,2)];Le.some((Ge,rt)=>Ge!==Y[rt])&&(N.setOrientation(...Le),Y=Le);const ze=[c(Ee,ne,3),c(Ee,ne,4),c(Ee,ne,5)];ze.some((Ge,rt)=>Ge!==ve[rt])&&(N.setPosition(...ze),ve=ze)},Object.defineProperty(B.gain,"defaultValue",{get:()=>0}),Object.defineProperty(W.gain,"defaultValue",{get:()=>0}),Object.defineProperty(V.gain,"defaultValue",{get:()=>0}),Object.defineProperty(G.gain,"defaultValue",{get:()=>0}),Object.defineProperty($.gain,"defaultValue",{get:()=>0});const ie={get bufferSize(){},get channelCount(){return N.channelCount},set channelCount(Ee){if(Ee>2)throw o();P.channelCount=Ee,N.channelCount=Ee},get channelCountMode(){return N.channelCountMode},set channelCountMode(Ee){if(Ee==="max")throw o();P.channelCountMode=Ee,N.channelCountMode=Ee},get channelInterpretation(){return N.channelInterpretation},set channelInterpretation(Ee){P.channelInterpretation=Ee,N.channelInterpretation=Ee},get coneInnerAngle(){return N.coneInnerAngle},set coneInnerAngle(Ee){N.coneInnerAngle=Ee},get coneOuterAngle(){return N.coneOuterAngle},set coneOuterAngle(Ee){N.coneOuterAngle=Ee},get coneOuterGain(){return N.coneOuterGain},set coneOuterGain(Ee){if(Ee<0||Ee>1)throw e();N.coneOuterGain=Ee},get context(){return N.context},get distanceModel(){return N.distanceModel},set distanceModel(Ee){N.distanceModel=Ee},get inputs(){return[P]},get maxDistance(){return N.maxDistance},set maxDistance(Ee){if(Ee<0)throw new RangeError;N.maxDistance=Ee},get numberOfInputs(){return N.numberOfInputs},get numberOfOutputs(){return N.numberOfOutputs},get orientationX(){return b.gain},get orientationY(){return B.gain},get orientationZ(){return W.gain},get panningModel(){return N.panningModel},set panningModel(Ee){N.panningModel=Ee},get positionX(){return V.gain},get positionY(){return G.gain},get positionZ(){return $.gain},get refDistance(){return N.refDistance},set refDistance(Ee){if(Ee<0)throw new RangeError;N.refDistance=Ee},get rolloffFactor(){return N.rolloffFactor},set rolloffFactor(Ee){if(Ee<0)throw new RangeError;N.rolloffFactor=Ee},addEventListener(...Ee){return P.addEventListener(Ee[0],Ee[1],Ee[2])},dispatchEvent(...Ee){return P.dispatchEvent(Ee[0])},removeEventListener(...Ee){return P.removeEventListener(Ee[0],Ee[1],Ee[2])}};h!==ie.coneInnerAngle&&(ie.coneInnerAngle=h),p!==ie.coneOuterAngle&&(ie.coneOuterAngle=p),m!==ie.coneOuterGain&&(ie.coneOuterGain=m),g!==ie.distanceModel&&(ie.distanceModel=g),v!==ie.maxDistance&&(ie.maxDistance=v),y!==ie.orientationX.value&&(ie.orientationX.value=y),_!==ie.orientationY.value&&(ie.orientationY.value=_),S!==ie.orientationZ.value&&(ie.orientationZ.value=S),w!==ie.panningModel&&(ie.panningModel=w),T!==ie.positionX.value&&(ie.positionX.value=T),k!==ie.positionY.value&&(ie.positionY.value=k),R!==ie.positionZ.value&&(ie.positionZ.value=R),C!==ie.refDistance&&(ie.refDistance=C),O!==ie.rolloffFactor&&(ie.rolloffFactor=O),(Y[0]!==1||Y[1]!==0||Y[2]!==0)&&N.setOrientation(...Y),(ve[0]!==0||ve[1]!==0||ve[2]!==0)&&N.setPosition(...ve);const be=()=>{P.connect(N),n(P,X,0,0),X.connect(b).connect(L,0,0),X.connect(B).connect(L,0,1),X.connect(W).connect(L,0,2),X.connect(V).connect(L,0,3),X.connect(G).connect(L,0,4),X.connect($).connect(L,0,5),L.connect(Z).connect(u.destination)},Ce=()=>{P.disconnect(N),a(P,X,0,0),X.disconnect(b),b.disconnect(L),X.disconnect(B),B.disconnect(L),X.disconnect(W),W.disconnect(L),X.disconnect(V),V.disconnect(L),X.disconnect(G),G.disconnect(L),X.disconnect($),$.disconnect(L),L.disconnect(Z),Z.disconnect(u.destination)};return l(nd(ie,N),be,Ce)},C$=n=>(e,{disableNormalization:t,imag:r,real:i})=>{const s=r instanceof Float32Array?r:new Float32Array(r),o=i instanceof Float32Array?i:new Float32Array(i),a=e.createPeriodicWave(o,s,{disableNormalization:t});if(Array.from(r).length<2)throw n();return a},Yp=(n,e,t,r)=>n.createScriptProcessor(e,t,r),R$=(n,e)=>(t,r)=>{const i=r.channelCountMode;if(i==="clamped-max")throw e();if(t.createStereoPanner===void 0)return n(t,r);const s=t.createStereoPanner();return Hr(s,r),nr(s,r,"pan"),Object.defineProperty(s,"channelCountMode",{get:()=>i,set:o=>{if(o!==i)throw e()}}),s},k$=(n,e,t,r,i,s)=>{const a=new Float32Array([1,1]),c=Math.PI/2,l={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},u={...l,oversample:"none"},h=(g,v,y,_)=>{const S=new Float32Array(16385),w=new Float32Array(16385);for(let M=0;M<16385;M+=1){const N=M/16384*c;S[M]=Math.cos(N),w[M]=Math.sin(N)}const T=t(g,{...l,gain:0}),k=r(g,{...u,curve:S}),R=r(g,{...u,curve:a}),C=t(g,{...l,gain:0}),O=r(g,{...u,curve:w});return{connectGraph(){v.connect(T),v.connect(R.inputs===void 0?R:R.inputs[0]),v.connect(C),R.connect(y),y.connect(k.inputs===void 0?k:k.inputs[0]),y.connect(O.inputs===void 0?O:O.inputs[0]),k.connect(T.gain),O.connect(C.gain),T.connect(_,0,0),C.connect(_,0,1)},disconnectGraph(){v.disconnect(T),v.disconnect(R.inputs===void 0?R:R.inputs[0]),v.disconnect(C),R.disconnect(y),y.disconnect(k.inputs===void 0?k:k.inputs[0]),y.disconnect(O.inputs===void 0?O:O.inputs[0]),k.disconnect(T.gain),O.disconnect(C.gain),T.disconnect(_,0,0),C.disconnect(_,0,1)}}},p=(g,v,y,_)=>{const S=new Float32Array(16385),w=new Float32Array(16385),T=new Float32Array(16385),k=new Float32Array(16385),R=Math.floor(16385/2);for(let V=0;V<16385;V+=1)if(V>R){const G=(V-R)/(16384-R)*c;S[V]=Math.cos(G),w[V]=Math.sin(G),T[V]=0,k[V]=1}else{const G=V/(16384-R)*c;S[V]=1,w[V]=0,T[V]=Math.cos(G),k[V]=Math.sin(G)}const C=e(g,{channelCount:2,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:2}),O=t(g,{...l,gain:0}),M=r(g,{...u,curve:S}),N=t(g,{...l,gain:0}),U=r(g,{...u,curve:w}),L=r(g,{...u,curve:a}),P=t(g,{...l,gain:0}),b=r(g,{...u,curve:T}),B=t(g,{...l,gain:0}),W=r(g,{...u,curve:k});return{connectGraph(){v.connect(C),v.connect(L.inputs===void 0?L:L.inputs[0]),C.connect(O,0),C.connect(N,0),C.connect(P,1),C.connect(B,1),L.connect(y),y.connect(M.inputs===void 0?M:M.inputs[0]),y.connect(U.inputs===void 0?U:U.inputs[0]),y.connect(b.inputs===void 0?b:b.inputs[0]),y.connect(W.inputs===void 0?W:W.inputs[0]),M.connect(O.gain),U.connect(N.gain),b.connect(P.gain),W.connect(B.gain),O.connect(_,0,0),P.connect(_,0,0),N.connect(_,0,1),B.connect(_,0,1)},disconnectGraph(){v.disconnect(C),v.disconnect(L.inputs===void 0?L:L.inputs[0]),C.disconnect(O,0),C.disconnect(N,0),C.disconnect(P,1),C.disconnect(B,1),L.disconnect(y),y.disconnect(M.inputs===void 0?M:M.inputs[0]),y.disconnect(U.inputs===void 0?U:U.inputs[0]),y.disconnect(b.inputs===void 0?b:b.inputs[0]),y.disconnect(W.inputs===void 0?W:W.inputs[0]),M.disconnect(O.gain),U.disconnect(N.gain),b.disconnect(P.gain),W.disconnect(B.gain),O.disconnect(_,0,0),P.disconnect(_,0,0),N.disconnect(_,0,1),B.disconnect(_,0,1)}}},m=(g,v,y,_,S)=>{if(v===1)return h(g,y,_,S);if(v===2)return p(g,y,_,S);throw i()};return(g,{channelCount:v,channelCountMode:y,pan:_,...S})=>{if(y==="max")throw i();const w=n(g,{...S,channelCount:1,channelCountMode:y,numberOfInputs:2}),T=t(g,{...S,channelCount:v,channelCountMode:y,gain:1}),k=t(g,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:_});let{connectGraph:R,disconnectGraph:C}=m(g,v,T,k,w);Object.defineProperty(k.gain,"defaultValue",{get:()=>0}),Object.defineProperty(k.gain,"maxValue",{get:()=>1}),Object.defineProperty(k.gain,"minValue",{get:()=>-1});const O={get bufferSize(){},get channelCount(){return T.channelCount},set channelCount(L){T.channelCount!==L&&(M&&C(),{connectGraph:R,disconnectGraph:C}=m(g,L,T,k,w),M&&R()),T.channelCount=L},get channelCountMode(){return T.channelCountMode},set channelCountMode(L){if(L==="clamped-max"||L==="max")throw i();T.channelCountMode=L},get channelInterpretation(){return T.channelInterpretation},set channelInterpretation(L){T.channelInterpretation=L},get context(){return T.context},get inputs(){return[T]},get numberOfInputs(){return T.numberOfInputs},get numberOfOutputs(){return T.numberOfOutputs},get pan(){return k.gain},addEventListener(...L){return T.addEventListener(L[0],L[1],L[2])},dispatchEvent(...L){return T.dispatchEvent(L[0])},removeEventListener(...L){return T.removeEventListener(L[0],L[1],L[2])}};let M=!1;const N=()=>{R(),M=!0},U=()=>{C(),M=!1};return s(nd(O,w),N,U)}},I$=(n,e,t,r,i,s,o)=>(a,c)=>{const l=a.createWaveShaper();if(s!==null&&s.name==="webkitAudioContext"&&a.createGain().gain.automationRate===void 0)return t(a,c);Hr(l,c);const u=c.curve===null||c.curve instanceof Float32Array?c.curve:new Float32Array(c.curve);if(u!==null&&u.length<2)throw e();Xn(l,{curve:u},"curve"),Xn(l,c,"oversample");let h=null,p=!1;return o(l,"curve",v=>()=>v.call(l),v=>y=>(v.call(l,y),p&&(r(y)&&h===null?h=n(a,l):!r(y)&&h!==null&&(h(),h=null)),y)),i(l,()=>{p=!0,r(l.curve)&&(h=n(a,l))},()=>{p=!1,h!==null&&(h(),h=null)})},N$=(n,e,t,r,i)=>(s,{curve:o,oversample:a,...c})=>{const l=s.createWaveShaper(),u=s.createWaveShaper();Hr(l,c),Hr(u,c);const h=t(s,{...c,gain:1}),p=t(s,{...c,gain:-1}),m=t(s,{...c,gain:1}),g=t(s,{...c,gain:-1});let v=null,y=!1,_=null;const S={get bufferSize(){},get channelCount(){return l.channelCount},set channelCount(k){h.channelCount=k,p.channelCount=k,l.channelCount=k,m.channelCount=k,u.channelCount=k,g.channelCount=k},get channelCountMode(){return l.channelCountMode},set channelCountMode(k){h.channelCountMode=k,p.channelCountMode=k,l.channelCountMode=k,m.channelCountMode=k,u.channelCountMode=k,g.channelCountMode=k},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(k){h.channelInterpretation=k,p.channelInterpretation=k,l.channelInterpretation=k,m.channelInterpretation=k,u.channelInterpretation=k,g.channelInterpretation=k},get context(){return l.context},get curve(){return _},set curve(k){if(k!==null&&k.length<2)throw e();if(k===null)l.curve=k,u.curve=k;else{const R=k.length,C=new Float32Array(R+2-R%2),O=new Float32Array(R+2-R%2);C[0]=k[0],O[0]=-k[R-1];const M=Math.ceil((R+1)/2),N=(R+1)/2-1;for(let U=1;U{h.connect(l).connect(m),h.connect(p).connect(u).connect(g).connect(m),y=!0,r(_)&&(v=n(s,h))},T=()=>{h.disconnect(l),l.disconnect(m),h.disconnect(p),p.disconnect(u),u.disconnect(g),g.disconnect(m),y=!1,v!==null&&(v(),v=null)};return i(nd(S,m),w,T)},ji=()=>new DOMException("","NotSupportedError"),O$={numberOfChannels:1},L$=(n,e,t,r,i)=>class extends n{constructor(o,a,c){let l;if(typeof o=="number"&&a!==void 0&&c!==void 0)l={length:a,numberOfChannels:o,sampleRate:c};else if(typeof o=="object")l=o;else throw new Error("The given parameters are not valid.");const{length:u,numberOfChannels:h,sampleRate:p}={...O$,...l},m=r(h,u,p);e(gp,()=>gp(m))||m.addEventListener("statechange",(()=>{let g=0;const v=y=>{this._state==="running"&&(g>0?(m.removeEventListener("statechange",v),y.stopImmediatePropagation(),this._waitForThePromiseToSettle(y)):g+=1)};return v})()),super(m,h),this._length=u,this._nativeOfflineAudioContext=m,this._state=null}get length(){return this._nativeOfflineAudioContext.length===void 0?this._length:this._nativeOfflineAudioContext.length}get state(){return this._state===null?this._nativeOfflineAudioContext.state:this._state}startRendering(){return this._state==="running"?Promise.reject(t()):(this._state="running",i(this.destination,this._nativeOfflineAudioContext).finally(()=>{this._state=null,GO(this)}))}_waitForThePromiseToSettle(o){this._state===null?this._nativeOfflineAudioContext.dispatchEvent(o):setTimeout(()=>this._waitForThePromiseToSettle(o))}},P$={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:440,periodicWave:void 0,type:"sine"},D$=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...P$,...l},p=t(u,h),m=s(u),g=m?r():null,v=c.sampleRate/2;super(c,!1,p,g),this._detune=e(this,m,p.detune,153600,-153600),this._frequency=e(this,m,p.frequency,v,-v),this._nativeOscillatorNode=p,this._onended=null,this._oscillatorNodeRenderer=g,this._oscillatorNodeRenderer!==null&&h.periodicWave!==void 0&&(this._oscillatorNodeRenderer.periodicWave=h.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(c){const l=typeof c=="function"?o(this,c):null;this._nativeOscillatorNode.onended=l;const u=this._nativeOscillatorNode.onended;this._onended=u!==null&&u===l?c:u}get type(){return this._nativeOscillatorNode.type}set type(c){this._nativeOscillatorNode.type=c,this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(c){this._nativeOscillatorNode.setPeriodicWave(c),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=c)}start(c=0){if(this._nativeOscillatorNode.start(c),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.start=c),this.context.state!=="closed"){If(this);const l=()=>{this._nativeOscillatorNode.removeEventListener("ended",l),gc(this)&&$p(this)};this._nativeOscillatorNode.addEventListener("ended",l)}}stop(c=0){this._nativeOscillatorNode.stop(c),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.stop=c)}},U$=(n,e,t,r,i)=>()=>{const s=new WeakMap;let o=null,a=null,c=null;const l=async(u,h)=>{let p=t(u);const m=Ti(p,h);if(!m){const g={channelCount:p.channelCount,channelCountMode:p.channelCountMode,channelInterpretation:p.channelInterpretation,detune:p.detune.value,frequency:p.frequency.value,periodicWave:o===null?void 0:o,type:p.type};p=e(h,g),a!==null&&p.start(a),c!==null&&p.stop(c)}return s.set(h,p),m?(await n(h,u.detune,p.detune),await n(h,u.frequency,p.frequency)):(await r(h,u.detune,p.detune),await r(h,u.frequency,p.frequency)),await i(u,h,p),p};return{set periodicWave(u){o=u},set start(u){a=u},set stop(u){c=u},render(u,h){const p=s.get(h);return p!==void 0?Promise.resolve(p):l(u,h)}}},F$={channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:1,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1},B$=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...F$,...l},p=t(u,h),m=s(u),g=m?r():null;super(c,!1,p,g),this._nativePannerNode=p,this._orientationX=e(this,m,p.orientationX,Pi,es),this._orientationY=e(this,m,p.orientationY,Pi,es),this._orientationZ=e(this,m,p.orientationZ,Pi,es),this._positionX=e(this,m,p.positionX,Pi,es),this._positionY=e(this,m,p.positionY,Pi,es),this._positionZ=e(this,m,p.positionZ,Pi,es),o(this,1)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(c){this._nativePannerNode.coneInnerAngle=c}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(c){this._nativePannerNode.coneOuterAngle=c}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(c){this._nativePannerNode.coneOuterGain=c}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(c){this._nativePannerNode.distanceModel=c}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(c){this._nativePannerNode.maxDistance=c}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(c){this._nativePannerNode.panningModel=c}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(c){this._nativePannerNode.refDistance=c}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(c){this._nativePannerNode.rolloffFactor=c}},z$=(n,e,t,r,i,s,o,a,c,l)=>()=>{const u=new WeakMap;let h=null;const p=async(m,g)=>{let v=null,y=s(m);const _={channelCount:y.channelCount,channelCountMode:y.channelCountMode,channelInterpretation:y.channelInterpretation},S={..._,coneInnerAngle:y.coneInnerAngle,coneOuterAngle:y.coneOuterAngle,coneOuterGain:y.coneOuterGain,distanceModel:y.distanceModel,maxDistance:y.maxDistance,panningModel:y.panningModel,refDistance:y.refDistance,rolloffFactor:y.rolloffFactor},w=Ti(y,g);if("bufferSize"in y)v=r(g,{..._,gain:1});else if(!w){const T={...S,orientationX:y.orientationX.value,orientationY:y.orientationY.value,orientationZ:y.orientationZ.value,positionX:y.positionX.value,positionY:y.positionY.value,positionZ:y.positionZ.value};y=i(g,T)}if(u.set(g,v===null?y:v),v!==null){if(h===null){if(o===null)throw new Error("Missing the native OfflineAudioContext constructor.");const U=new o(6,m.context.length,g.sampleRate),L=e(U,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6});L.connect(U.destination),h=(async()=>{const P=await Promise.all([m.orientationX,m.orientationY,m.orientationZ,m.positionX,m.positionY,m.positionZ].map(async(b,B)=>{const W=t(U,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:B===0?1:0});return await a(U,b,W.offset),W}));for(let b=0;b<6;b+=1)P[b].connect(L,0,b),P[b].start(0);return l(U)})()}const T=await h,k=r(g,{..._,gain:1});await c(m,g,k);const R=[];for(let U=0;Ub!==C[B])||P.some((b,B)=>b!==O[B])){C=L,O=P;const b=U/g.sampleRate;M.gain.setValueAtTime(0,b),M=r(g,{..._,gain:0}),N=i(g,{...S,orientationX:C[0],orientationY:C[1],orientationZ:C[2],positionX:O[0],positionY:O[1],positionZ:O[2]}),M.gain.setValueAtTime(1,b),k.connect(M).connect(N.inputs[0]),N.connect(v)}}return v}return w?(await n(g,m.orientationX,y.orientationX),await n(g,m.orientationY,y.orientationY),await n(g,m.orientationZ,y.orientationZ),await n(g,m.positionX,y.positionX),await n(g,m.positionY,y.positionY),await n(g,m.positionZ,y.positionZ)):(await a(g,m.orientationX,y.orientationX),await a(g,m.orientationY,y.orientationY),await a(g,m.orientationZ,y.orientationZ),await a(g,m.positionX,y.positionX),await a(g,m.positionY,y.positionY),await a(g,m.positionZ,y.positionZ)),td(y)?await c(m,g,y.inputs[0]):await c(m,g,y),y};return{render(m,g){const v=u.get(g);return v!==void 0?Promise.resolve(v):p(m,g)}}},V$={disableNormalization:!1},H$=(n,e,t,r)=>class JO{constructor(s,o){const a=e(s),c=r({...V$,...o}),l=n(a,c);return t.add(l),l}static[Symbol.hasInstance](s){return s!==null&&typeof s=="object"&&Object.getPrototypeOf(s)===JO.prototype||t.has(s)}},G$=(n,e)=>(t,r,i)=>(n(r).replay(i),e(r,t,i)),W$=(n,e,t)=>async(r,i,s)=>{const o=n(r);await Promise.all(o.activeInputs.map((a,c)=>Array.from(a).map(async([l,u])=>{const p=await e(l).render(l,i),m=r.context.destination;!t(l)&&(r!==m||!t(r))&&p.connect(s,u,c)})).reduce((a,c)=>[...a,...c],[]))},j$=(n,e,t)=>async(r,i,s)=>{const o=e(r);await Promise.all(Array.from(o.activeInputs).map(async([a,c])=>{const u=await n(a).render(a,i);t(a)||u.connect(s,c)}))},$$=(n,e,t,r)=>i=>n(gp,()=>gp(i))?Promise.resolve(n(r,r)).then(s=>{if(!s){const o=t(i,512,0,1);i.oncomplete=()=>{o.onaudioprocess=null,o.disconnect()},o.onaudioprocess=()=>i.currentTime,o.connect(i.destination)}return i.startRendering()}):new Promise(s=>{const o=e(i,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});i.oncomplete=a=>{o.disconnect(),s(a.renderedBuffer)},o.connect(i.destination),i.startRendering()}),q$=n=>(e,t)=>{n.set(e,t)},X$=n=>(e,t)=>n.set(e,t),K$=(n,e,t,r,i,s,o,a)=>(c,l)=>t(c).render(c,l).then(()=>Promise.all(Array.from(r(l)).map(u=>t(u).render(u,l)))).then(()=>i(l)).then(u=>(typeof u.copyFromChannel!="function"?(o(u),mT(u)):e(s,()=>s(u))||a(u),n.add(u),u)),Y$={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",pan:0},Z$=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=i(a),u={...Y$,...c},h=t(l,u),p=s(l),m=p?r():null;super(a,!1,h,m),this._pan=e(this,p,h.pan)}get pan(){return this._pan}},Q$=(n,e,t,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=t(a);const u=Ti(l,c);if(!u){const h={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,pan:l.pan.value};l=e(c,h)}return s.set(c,l),u?await n(c,a.pan,l.pan):await r(c,a.pan,l.pan),td(l)?await i(a,c,l.inputs[0]):await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},J$=n=>()=>{if(n===null)return!1;try{new n({length:1,sampleRate:44100})}catch{return!1}return!0},eq=(n,e)=>async()=>{if(n===null)return!0;if(e===null)return!1;const t=new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),r=new e(1,128,44100),i=URL.createObjectURL(t);let s=!1,o=!1;try{await r.audioWorklet.addModule(i);const a=new n(r,"a",{numberOfOutputs:0}),c=r.createOscillator();a.port.onmessage=()=>s=!0,a.onprocessorerror=()=>o=!0,c.connect(a),c.start(0),await r.startRendering(),await new Promise(l=>setTimeout(l))}catch{}finally{URL.revokeObjectURL(i)}return s&&!o},tq=(n,e)=>()=>{if(e===null)return Promise.resolve(!1);const t=new e(1,1,44100),r=n(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return new Promise(i=>{t.oncomplete=()=>{r.disconnect(),i(t.currentTime!==0)},t.startRendering()})},nq=()=>new DOMException("","UnknownError"),rq={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",curve:null,oversample:"none"},iq=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...rq,...l},p=t(u,h),g=s(u)?r():null;super(c,!0,p,g),this._isCurveNullified=!1,this._nativeWaveShaperNode=p,o(this,1)}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(c){if(c===null)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(c.length<2)throw e();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=c}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(c){this._nativeWaveShaperNode.oversample=c}},sq=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ti(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,curve:a.curve,oversample:a.oversample};a=n(o,l)}return r.set(o,a),td(a)?await t(s,o,a.inputs[0]):await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},oq=()=>typeof window>"u"?null:window,aq=(n,e)=>t=>{t.copyFromChannel=(r,i,s=0)=>{const o=n(s),a=n(i);if(a>=t.numberOfChannels)throw e();const c=t.length,l=t.getChannelData(a),u=r.length;for(let h=o<0?-o:0;h+o{const o=n(s),a=n(i);if(a>=t.numberOfChannels)throw e();const c=t.length,l=t.getChannelData(a),u=r.length;for(let h=o<0?-o:0;h+oe=>{e.copyFromChannel=(t=>(r,i,s=0)=>{const o=n(s),a=n(i);if(o(r,i,s=0)=>{const o=n(s),a=n(i);if(o(e,t)=>{const r=t.createBuffer(1,1,44100);e.buffer===null&&(e.buffer=r),n(e,"buffer",i=>()=>{const s=i.call(e);return s===r?null:s},i=>s=>i.call(e,s===null?r:s))},uq=(n,e)=>(t,r)=>{r.channelCount=1,r.channelCountMode="explicit",Object.defineProperty(r,"channelCount",{get:()=>1,set:()=>{throw n()}}),Object.defineProperty(r,"channelCountMode",{get:()=>"explicit",set:()=>{throw n()}});const i=t.createBufferSource();e(r,()=>{const a=r.numberOfInputs;for(let c=0;ci.disconnect(r))},eL=(n,e,t)=>n.copyFromChannel===void 0?n.getChannelData(t)[0]:(n.copyFromChannel(e,t),e[0]),tL=n=>{if(n===null)return!1;const e=n.length;return e%2!==0?n[Math.floor(e/2)]!==0:n[e/2-1]+n[e/2]!==0},Zp=(n,e,t,r)=>{let i=n;for(;!i.hasOwnProperty(e);)i=Object.getPrototypeOf(i);const{get:s,set:o}=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(n,e,{get:t(s),set:r(o)})},hq=n=>({...n,outputChannelCount:n.outputChannelCount!==void 0?n.outputChannelCount:n.numberOfInputs===1&&n.numberOfOutputs===1?[n.channelCount]:Array.from({length:n.numberOfOutputs},()=>1)}),fq=n=>({...n,channelCount:n.numberOfOutputs}),dq=n=>{const{imag:e,real:t}=n;return e===void 0?t===void 0?{...n,imag:[0,0],real:[0,0]}:{...n,imag:Array.from(t,()=>0),real:t}:t===void 0?{...n,imag:e,real:Array.from(e,()=>0)}:{...n,imag:e,real:t}},nL=(n,e,t)=>{try{n.setValueAtTime(e,t)}catch(r){if(r.code!==9)throw r;nL(n,e,t+1e-7)}},pq=n=>{const e=n.createBufferSource();e.start();try{e.start()}catch{return!0}return!1},mq=n=>{const e=n.createBufferSource(),t=n.createBuffer(1,1,44100);e.buffer=t;try{e.start(0,1)}catch{return!1}return!0},gq=n=>{const e=n.createBufferSource();e.start();try{e.stop()}catch{return!1}return!0},xT=n=>{const e=n.createOscillator();try{e.start(-1)}catch(t){return t instanceof RangeError}return!1},rL=n=>{const e=n.createBuffer(1,1,44100),t=n.createBufferSource();t.buffer=e,t.start(),t.stop();try{return t.stop(),!0}catch{return!1}},ST=n=>{const e=n.createOscillator();try{e.stop(-1)}catch(t){return t instanceof RangeError}return!1},_q=n=>{const{port1:e,port2:t}=new MessageChannel;try{e.postMessage(n)}finally{e.close(),t.close()}},vq=n=>{n.start=(e=>(t=0,r=0,i)=>{const s=n.buffer,o=s===null?r:Math.min(s.duration,r);s!==null&&o>s.duration-.5/n.context.sampleRate?e.call(n,t,0,0):e.call(n,t,o,i)})(n.start)},iL=(n,e)=>{const t=e.createGain();n.connect(t);const r=(i=>()=>{i.call(n,t),n.removeEventListener("ended",r)})(n.disconnect);n.addEventListener("ended",r),nd(n,t),n.stop=(i=>{let s=!1;return(o=0)=>{if(s)try{i.call(n,o)}catch{t.gain.setValueAtTime(0,o)}else i.call(n,o),s=!0}})(n.stop)},rd=(n,e)=>t=>{const r={value:n};return Object.defineProperties(t,{currentTarget:r,target:r}),typeof e=="function"?e.call(n,t):e.handleEvent.call(n,t)},yq=BW(Ju),xq=jW(Ju),Sq=rj(Cv),sL=new WeakMap,Eq=Sj(sL),Uo=O9(new Map,new WeakMap),Sa=oq(),oL=Zj(Uo,Ia),ET=xj(Fi),hi=W$(Fi,ET,Uu),wq=YW(oL,Hn,hi),Bn=Tj(Mv),Pc=T$(Sa),Rn=Vj(Pc),aL=new WeakMap,cL=dj(rd),Qp=t$(Sa),wT=Uj(Qp),TT=Fj(Sa),lL=Bj(Sa),_p=r$(Sa),yr=S9(zW(DO),WW(yq,xq,A_,Sq,M_,Fi,Eq,jp,Hn,Ju,gc,Uu,$0),Uo,Nj(AE,M_,Fi,Hn,mp,gc),Ia,Rv,ji,J9(A_,AE,Fi,Hn,mp,Bn,gc,Rn),oj(aL,Fi,Ro),cL,Bn,wT,TT,lL,Rn,_p),Tq=KW(yr,wq,Ia,oL,Bn,Rn),bT=new WeakSet,ZR=Qj(Sa),uL=$9(new Uint32Array(1)),AT=aq(uL,Ia),MT=cq(uL),hL=QW(bT,Uo,ji,ZR,Pc,J$(ZR),AT,MT),kv=$W(ls),fL=j$(ET,qp,Uu),Na=z9(fL),id=e$(kv,Uo,pq,mq,gq,xT,rL,ST,vq,lq(Zp),iL),Oa=G$(Ej(qp),fL),bq=t9(Na,id,Hn,Oa,hi),Fo=E9(VW(UO),aL,pT,w9,OW,LW,PW,DW,UW,wE,LO,Qp,nL),Aq=e9(yr,bq,Fo,ii,id,Bn,Rn,rd),Mq=u9(yr,h9,Ia,ii,n$(ls,Zp),Bn,Rn,hi),Cq=N9(Na,ZO,Hn,Oa,hi),eh=X$(sL),Rq=I9(yr,Fo,Cq,Rv,ZO,Bn,Rn,eh),Bl=Kj(Ju,TT),kq=uq(ii,Bl),zl=u$(Qp,kq),Iq=D9(zl,Hn,hi),Nq=P9(yr,Iq,zl,Bn,Rn),Oq=B9(Kp,Hn,hi),Lq=F9(yr,Oq,Kp,Bn,Rn,fq),Pq=d$(kv,id,ls,Bl),sd=f$(kv,Uo,Pq,xT,ST),Dq=j9(Na,sd,Hn,Oa,hi),Uq=W9(yr,Fo,Dq,sd,Bn,Rn,rd),dL=p$(ji,Zp),Fq=K9(dL,Hn,hi),Bq=X9(yr,Fq,dL,Bn,Rn,eh),zq=nj(Na,QO,Hn,Oa,hi),Vq=tj(yr,Fo,zq,QO,Bn,Rn,eh),pL=m$(ji),Hq=uj(Na,pL,Hn,Oa,hi),Gq=lj(yr,Fo,Hq,pL,ji,Bn,Rn,eh),Wq=vj(Na,ls,Hn,Oa,hi),jq=_j(yr,Fo,Wq,ls,Bn,Rn),$q=y$(Rv,ii,Yp,ji),Iv=$$(Uo,ls,Yp,tq(ls,Pc)),qq=Ij(id,Hn,Pc,hi,Iv),Xq=g$($q),Kq=Rj(yr,Xq,qq,Bn,Rn,eh),Yq=f9(Fo,zl,sd,Yp,ji,eL,Rn,Zp),mL=new WeakMap,Zq=Xj(Mq,Yq,cL,Rn,mL,rd),gL=b$(kv,Uo,xT,rL,ST,iL),Qq=U$(Na,gL,Hn,Oa,hi),Jq=D$(yr,Fo,gL,Qq,Bn,Rn,rd),_L=H9(id),e7=N$(_L,ii,ls,tL,Bl),Nv=I$(_L,ii,e7,tL,Bl,Qp,Zp),t7=M$(A_,ii,zl,ls,Yp,Nv,ji,M_,eL,Bl),vL=A$(t7),n7=z$(Na,zl,sd,ls,vL,Hn,Pc,Oa,hi,Iv),r7=B$(yr,Fo,vL,n7,Bn,Rn,eh),i7=C$(Ia),s7=H$(i7,Bn,new WeakSet,dq),o7=k$(zl,Kp,ls,Nv,ji,Bl),yL=R$(o7,ji),a7=Q$(Na,yL,Hn,Oa,hi),c7=Z$(yr,Fo,yL,a7,Bn,Rn),l7=sq(Nv,Hn,hi),u7=iq(yr,ii,Nv,l7,Bn,Rn,eh),xL=Hj(Sa),CT=pj(Sa),SL=new WeakMap,h7=bj(SL,Pc),f7=xL?GW(Uo,ji,fj(Sa),CT,mj(FW),Bn,h7,Rn,_p,new WeakMap,new WeakMap,eq(_p,Pc),Sa):void 0,d7=zj(wT,Rn),p7=Q9(bT,Uo,Z9,hj,new WeakSet,Bn,d7,T_,gp,AT,MT),EL=R9(f7,Tq,hL,Aq,Rq,Nq,Lq,Uq,Bq,p7,Vq,Gq,jq,Kq,Zq,Jq,r7,s7,c7,u7),m7=Gj(yr,x$,Bn,Rn),g7=jj(yr,S$,Bn,Rn),_7=$j(yr,E$,Bn,Rn),v7=w$(ii,Rn),y7=qj(yr,v7,Bn),x7=l9(EL,ii,ji,nq,m7,g7,_7,y7,Qp),RT=Aj(mL),S7=qW(RT),wL=V9(Ia),E7=ij(RT),TL=aj(Ia),bL=new WeakMap,w7=yj(bL,Ro),T7=l$(wL,Ia,ii,zl,Kp,sd,ls,Yp,ji,TL,CT,w7,Bl),b7=s$(ii,T7,ls,ji,Bl),A7=C9(Na,wL,id,zl,Kp,sd,ls,E7,TL,CT,Hn,_p,Pc,Oa,hi,Iv),M7=wj(SL),C7=q$(bL),QR=xL?b9(S7,yr,Fo,A7,b7,Fi,M7,Bn,Rn,_p,hq,C7,_q,rd):void 0,R7=Y9(ji,Pc),k7=K$(bT,Uo,ET,RT,Iv,T_,AT,MT),I7=L$(EL,Uo,ii,R7,k7),N7=Oj(Mv,wT),O7=Lj(dT,TT),L7=Pj(pT,lL),P7=Dj(Mv,Rn);function Is(n){return n===void 0}function Wt(n){return n!==void 0}function D7(n){return typeof n=="function"}function ko(n){return typeof n=="number"}function yl(n){return Object.prototype.toString.call(n)==="[object Object]"&&n.constructor===Object}function AL(n){return typeof n=="boolean"}function as(n){return Array.isArray(n)}function bc(n){return typeof n=="string"}function a0(n){return bc(n)&&/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(n)}function Tt(n,e){if(!n)throw new Error(e)}function Ea(n,e,t=1/0){if(!(e<=n&&n<=t))throw new RangeError(`Value must be within [${e}, ${t}], got: ${n}`)}function ML(n){!n.isOffline&&n.state!=="running"&&Ov('The AudioContext is "suspended". Invoke Tone.start() from a user action to start the audio.')}let CL=!1,JR=!1;function e2(n){CL=n}function U7(n){Is(n)&&CL&&!JR&&(JR=!0,Ov("Events scheduled inside of scheduled callbacks should use the passed in scheduling time. See https://github.com/Tonejs/Tone.js/wiki/Accurate-Timing"))}let RL=console;function F7(...n){RL.log(...n)}function Ov(...n){RL.warn(...n)}function B7(n){return new x7(n)}function z7(n,e,t){return new I7(n,e,t)}const bs=typeof self=="object"?self:null,V7=bs&&(bs.hasOwnProperty("AudioContext")||bs.hasOwnProperty("webkitAudioContext"));function H7(n,e,t){return Tt(Wt(QR),"AudioWorkletNode only works in a secure context (https or localhost)"),new(n instanceof(bs==null?void 0:bs.BaseAudioContext)?bs==null?void 0:bs.AudioWorkletNode:QR)(n,e,t)}function Bo(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(o=n[a])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s}function _r(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(r.next(u))}catch(h){o(h)}}function c(u){try{l(r.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((r=r.apply(n,e||[])).next())})}class G7{constructor(e,t,r,i){this._callback=e,this._type=t,this._minimumUpdateInterval=Math.max(128/(i||44100),.001),this.updateInterval=r,this._createClock()}_createWorker(){const e=new Blob([` - // the initial timeout time - let timeoutTime = ${(this._updateInterval*1e3).toFixed(1)}; - // onmessage callback - self.onmessage = function(msg){ - timeoutTime = parseInt(msg.data); - }; - // the tick function which posts a message - // and schedules a new tick - function tick(){ - setTimeout(tick, timeoutTime); - self.postMessage('tick'); - } - // call tick initially - tick(); - `],{type:"text/javascript"}),t=URL.createObjectURL(e),r=new Worker(t);r.onmessage=this._callback.bind(this),this._worker=r}_createTimeout(){this._timeout=setTimeout(()=>{this._createTimeout(),this._callback()},this._updateInterval*1e3)}_createClock(){if(this._type==="worker")try{this._createWorker()}catch{this._type="timeout",this._createClock()}else this._type==="timeout"&&this._createTimeout()}_disposeClock(){this._timeout&&clearTimeout(this._timeout),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(e){var t;this._updateInterval=Math.max(e,this._minimumUpdateInterval),this._type==="worker"&&((t=this._worker)===null||t===void 0||t.postMessage(this._updateInterval*1e3))}get type(){return this._type}set type(e){this._disposeClock(),this._type=e,this._createClock()}dispose(){this._disposeClock()}}function Fu(n){return L7(n)}function xl(n){return O7(n)}function q0(n){return P7(n)}function Zh(n){return N7(n)}function W7(n){return n instanceof hL}function j7(n,e){return n==="value"||Fu(e)||xl(e)||W7(e)}function Iu(n,...e){if(!e.length)return n;const t=e.shift();if(yl(n)&&yl(t))for(const r in t)j7(r,t[r])?n[r]=t[r]:yl(t[r])?(n[r]||Object.assign(n,{[r]:{}}),Iu(n[r],t[r])):Object.assign(n,{[r]:t[r]});return Iu(n,...e)}function $7(n,e){return n.length===e.length&&n.every((t,r)=>e[r]===t)}function at(n,e,t=[],r){const i={},s=Array.from(e);if(yl(s[0])&&r&&!Reflect.has(s[0],r)&&(Object.keys(s[0]).some(a=>Reflect.has(n,a))||(Iu(i,{[r]:s[0]}),t.splice(t.indexOf(r),1),s.shift())),s.length===1&&yl(s[0]))Iu(i,s[0]);else for(let o=0;o{Reflect.has(n,t)&&delete n[t]}),n}/** - * Tone.js - * @author Yotam Mann - * @license http://opensource.org/licenses/MIT MIT License - * @copyright 2014-2024 Yotam Mann - */class Dc{constructor(){this.debug=!1,this._wasDisposed=!1}static getDefaults(){return{}}log(...e){(this.debug||bs&&this.toString()===bs.TONE_DEBUG_CLASS)&&F7(this,...e)}dispose(){return this._wasDisposed=!0,this}get disposed(){return this._wasDisposed}toString(){return this.name}}Dc.version=OO;const kT=1e-6;function Nf(n,e){return n>e+kT}function IE(n,e){return Nf(n,e)||xo(n,e)}function I_(n,e){return n+kTthis.memory){const t=this.length-this.memory;this._timeline.splice(0,t)}return this}remove(e){const t=this._timeline.indexOf(e);return t!==-1&&this._timeline.splice(t,1),this}get(e,t="time"){const r=this._search(e,t);return r!==-1?this._timeline[r]:null}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(e,t="time"){const r=this._search(e,t);return r+10&&this._timeline[t-1].time=0?this._timeline[r-1]:null}cancel(e){if(this._timeline.length>1){let t=this._search(e);if(t>=0)if(xo(this._timeline[t].time,e)){for(let r=t;r>=0&&xo(this._timeline[r].time,e);r--)t=r;this._timeline=this._timeline.slice(0,t)}else this._timeline=this._timeline.slice(0,t+1);else this._timeline=[]}else this._timeline.length===1&&IE(this._timeline[0].time,e)&&(this._timeline=[]);return this}cancelBefore(e){const t=this._search(e);return t>=0&&(this._timeline=this._timeline.slice(t+1)),this}previousEvent(e){const t=this._timeline.indexOf(e);return t>0?this._timeline[t-1]:null}_search(e,t="time"){if(this._timeline.length===0)return-1;let r=0;const i=this._timeline.length;let s=i;if(i>0&&this._timeline[i-1][t]<=e)return i-1;for(;r=0&&this._timeline[r].time>=e;)r--;return this._iterate(t,r+1),this}forEachAtTime(e,t){const r=this._search(e);if(r!==-1&&xo(this._timeline[r].time,e)){let i=r;for(let s=r;s>=0&&xo(this._timeline[s].time,e);s--)i=s;this._iterate(s=>{t(s)},i,r)}return this}dispose(){return super.dispose(),this._timeline=[],this}}const kL=[];function Lv(n){kL.push(n)}function K7(n){kL.forEach(e=>e(n))}const IL=[];function Pv(n){IL.push(n)}function Y7(n){IL.forEach(e=>e(n))}class Jp extends Dc{constructor(){super(...arguments),this.name="Emitter"}on(e,t){return e.split(/\W+/).forEach(i=>{Is(this._events)&&(this._events={}),this._events.hasOwnProperty(i)||(this._events[i]=[]),this._events[i].push(t)}),this}once(e,t){const r=(...i)=>{t(...i),this.off(e,r)};return this.on(e,r),this}off(e,t){return e.split(/\W+/).forEach(i=>{if(Is(this._events)&&(this._events={}),this._events.hasOwnProperty(i))if(Is(t))this._events[i]=[];else{const s=this._events[i];for(let o=s.length-1;o>=0;o--)s[o]===t&&s.splice(o,1)}}),this}emit(e,...t){if(this._events&&this._events.hasOwnProperty(e)){const r=this._events[e].slice(0);for(let i=0,s=r.length;i{const r=Object.getOwnPropertyDescriptor(Jp.prototype,t);Object.defineProperty(e.prototype,t,r)})}dispose(){return super.dispose(),this._events=void 0,this}}class NL extends Jp{constructor(){super(...arguments),this.isOffline=!1}toJSON(){return{}}}class em extends NL{constructor(){var e,t;super(),this.name="Context",this._constants=new Map,this._timeouts=new to,this._timeoutIds=0,this._initialized=!1,this._closeStarted=!1,this.isOffline=!1,this._workletPromise=null;const r=at(em.getDefaults(),arguments,["context"]);r.context?(this._context=r.context,this._latencyHint=((e=arguments[0])===null||e===void 0?void 0:e.latencyHint)||""):(this._context=B7({latencyHint:r.latencyHint}),this._latencyHint=r.latencyHint),this._ticker=new G7(this.emit.bind(this,"tick"),r.clockSource,r.updateInterval,this._context.sampleRate),this.on("tick",this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit("statechange",this.state)},this[!((t=arguments[0])===null||t===void 0)&&t.hasOwnProperty("updateInterval")?"_lookAhead":"lookAhead"]=r.lookAhead}static getDefaults(){return{clockSource:"worker",latencyHint:"interactive",lookAhead:.1,updateInterval:.05}}initialize(){return this._initialized||(K7(this),this._initialized=!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(e,t,r){return this._context.createBuffer(e,t,r)}createChannelMerger(e){return this._context.createChannelMerger(e)}createChannelSplitter(e){return this._context.createChannelSplitter(e)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(e){return this._context.createDelay(e)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(e,t){return this._context.createIIRFilter(e,t)}createPanner(){return this._context.createPanner()}createPeriodicWave(e,t,r){return this._context.createPeriodicWave(e,t,r)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(e){return Tt(Zh(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamSource(e)}createMediaElementSource(e){return Tt(Zh(this._context),"Not available if OfflineAudioContext"),this._context.createMediaElementSource(e)}createMediaStreamDestination(){return Tt(Zh(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamDestination()}decodeAudioData(e){return this._context.decodeAudioData(e)}get currentTime(){return this._context.currentTime}get state(){return this._context.state}get sampleRate(){return this._context.sampleRate}get listener(){return this.initialize(),this._listener}set listener(e){Tt(!this._initialized,"The listener cannot be set after initialization."),this._listener=e}get transport(){return this.initialize(),this._transport}set transport(e){Tt(!this._initialized,"The transport cannot be set after initialization."),this._transport=e}get draw(){return this.initialize(),this._draw}set draw(e){Tt(!this._initialized,"Draw cannot be set after initialization."),this._draw=e}get destination(){return this.initialize(),this._destination}set destination(e){Tt(!this._initialized,"The destination cannot be set after initialization."),this._destination=e}createAudioWorkletNode(e,t){return H7(this.rawContext,e,t)}addAudioWorkletModule(e){return _r(this,void 0,void 0,function*(){Tt(Wt(this.rawContext.audioWorklet),"AudioWorkletNode is only available in a secure context (https or localhost)"),this._workletPromise||(this._workletPromise=this.rawContext.audioWorklet.addModule(e)),yield this._workletPromise})}workletsAreReady(){return _r(this,void 0,void 0,function*(){(yield this._workletPromise)?this._workletPromise:Promise.resolve()})}get updateInterval(){return this._ticker.updateInterval}set updateInterval(e){this._ticker.updateInterval=e}get clockSource(){return this._ticker.type}set clockSource(e){this._ticker.type=e}get lookAhead(){return this._lookAhead}set lookAhead(e){this._lookAhead=e,this.updateInterval=e?e/2:.01}get latencyHint(){return this._latencyHint}get rawContext(){return this._context}now(){return this._context.currentTime+this._lookAhead}immediate(){return this._context.currentTime}resume(){return Zh(this._context)?this._context.resume():Promise.resolve()}close(){return _r(this,void 0,void 0,function*(){Zh(this._context)&&this.state!=="closed"&&!this._closeStarted&&(this._closeStarted=!0,yield this._context.close()),this._initialized&&Y7(this)})}getConstant(e){if(this._constants.has(e))return this._constants.get(e);{const t=this._context.createBuffer(1,128,this._context.sampleRate),r=t.getChannelData(0);for(let s=0;sthis._constants[e].disconnect()),this.close(),this}_timeoutLoop(){const e=this.now();let t=this._timeouts.peek();for(;this._timeouts.length&&t&&t.time<=e;)t.callback(),this._timeouts.shift(),t=this._timeouts.peek()}setTimeout(e,t){this._timeoutIds++;const r=this.now();return this._timeouts.add({callback:e,id:this._timeoutIds,time:r+t}),this._timeoutIds}clearTimeout(e){return this._timeouts.forEach(t=>{t.id===e&&this._timeouts.remove(t)}),this}clearInterval(e){return this.clearTimeout(e)}setInterval(e,t){const r=++this._timeoutIds,i=()=>{const s=this.now();this._timeouts.add({callback:()=>{e(),i()},id:r,time:s+t})};return i(),r}}class Z7 extends NL{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(e,t,r){return{}}createChannelMerger(e){return{}}createChannelSplitter(e){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(e){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(e,t){return{}}createPanner(){return{}}createPeriodicWave(e,t,r){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(e){return{}}createMediaElementSource(e){return{}}createMediaStreamDestination(){return{}}decodeAudioData(e){return Promise.resolve({})}createAudioWorkletNode(e,t){return{}}get rawContext(){return{}}addAudioWorkletModule(e){return _r(this,void 0,void 0,function*(){return Promise.resolve()})}resume(){return Promise.resolve()}setTimeout(e,t){return 0}clearTimeout(e){return this}setInterval(e,t){return 0}clearInterval(e){return this}getConstant(e){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(e){}get destination(){return{}}set destination(e){}now(){return 0}immediate(){return 0}}function Zt(n,e){as(e)?e.forEach(t=>Zt(n,t)):Object.defineProperty(n,e,{enumerable:!0,writable:!1})}function tm(n,e){as(e)?e.forEach(t=>tm(n,t)):Object.defineProperty(n,e,{writable:!0})}const En=()=>{};class An extends Dc{constructor(){super(),this.name="ToneAudioBuffer",this.onload=En;const e=at(An.getDefaults(),arguments,["url","onload","onerror"]);this.reverse=e.reverse,this.onload=e.onload,bc(e.url)?this.load(e.url).catch(e.onerror):e.url&&this.set(e.url)}static getDefaults(){return{onerror:En,onload:En,reverse:!1}}get sampleRate(){return this._buffer?this._buffer.sampleRate:Bi().sampleRate}set(e){return e instanceof An?e.loaded?this._buffer=e.get():e.onload=()=>{this.set(e),this.onload(this)}:this._buffer=e,this._reversed&&this._reverse(),this}get(){return this._buffer}load(e){return _r(this,void 0,void 0,function*(){const t=An.load(e).then(r=>{this.set(r),this.onload(this)});An.downloads.push(t);try{yield t}finally{const r=An.downloads.indexOf(t);An.downloads.splice(r,1)}return this})}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(e){const t=as(e)&&e[0].length>0,r=t?e.length:1,i=t?e[0].length:e.length,s=Bi(),o=s.createBuffer(r,i,s.sampleRate),a=!t&&r===1?[e]:e;for(let c=0;ci/r),this.fromArray(t)}return this}toArray(e){if(ko(e))return this.getChannelData(e);if(this.numberOfChannels===1)return this.toArray(0);{const t=[];for(let r=0;r0}get duration(){return this._buffer?this._buffer.duration:0}get length(){return this._buffer?this._buffer.length:0}get numberOfChannels(){return this._buffer?this._buffer.numberOfChannels:0}get reverse(){return this._reversed}set reverse(e){this._reversed!==e&&(this._reversed=e,this._reverse())}static fromArray(e){return new An().fromArray(e)}static fromUrl(e){return _r(this,void 0,void 0,function*(){return yield new An().load(e)})}static load(e){return _r(this,void 0,void 0,function*(){const t=e.match(/\[([^\]\[]+\|.+)\]$/);if(t){const c=t[1].split("|");let l=c[0];for(const u of c)if(An.supportsType(u)){l=u;break}e=e.replace(t[0],l)}const r=An.baseUrl===""||An.baseUrl.endsWith("/")?An.baseUrl:An.baseUrl+"/",i=document.createElement("a");i.href=r+e,i.pathname=(i.pathname+i.hash).split("/").map(encodeURIComponent).join("/");const s=yield fetch(i.href);if(!s.ok)throw new Error(`could not load url: ${e}`);const o=yield s.arrayBuffer();return yield Bi().decodeAudioData(o)})}static supportsType(e){const t=e.split("."),r=t[t.length-1];return document.createElement("audio").canPlayType("audio/"+r)!==""}static loaded(){return _r(this,void 0,void 0,function*(){for(yield Promise.resolve();An.downloads.length;)yield An.downloads[0]})}}An.baseUrl="";An.downloads=[];class Dv extends em{constructor(){super({clockSource:"offline",context:q0(arguments[0])?arguments[0]:z7(arguments[0],arguments[1]*arguments[2],arguments[2]),lookAhead:0,updateInterval:q0(arguments[0])?128/arguments[0].sampleRate:128/arguments[2]}),this.name="OfflineContext",this._currentTime=0,this.isOffline=!0,this._duration=q0(arguments[0])?arguments[0].length/arguments[0].sampleRate:arguments[1]}now(){return this._currentTime}get currentTime(){return this._currentTime}_renderClock(e){return _r(this,void 0,void 0,function*(){let t=0;for(;this._duration-this._currentTime>=0;){this.emit("tick"),this._currentTime+=128/this.sampleRate,t++;const r=Math.floor(this.sampleRate/128);e&&t%r===0&&(yield new Promise(i=>setTimeout(i,1)))}})}render(){return _r(this,arguments,void 0,function*(e=!0){yield this.workletsAreReady(),yield this._renderClock(e);const t=yield this._context.startRendering();return new An(t)})}close(){return Promise.resolve()}}const OL=new Z7;let Au=OL;function Bi(){return Au===OL&&V7&&Q7(new em),Au}function Q7(n,e=!1){e&&Au.dispose(),Zh(n)?Au=new em(n):q0(n)?Au=new Dv(n):Au=n}function J7(){return Au.resume()}if(bs&&!bs.TONE_SILENCE_LOGGING){const e=` * Tone.js v${OO} * `;console.log(`%c${e}`,"background: #000; color: #fff")}function eX(n){return Math.pow(10,n/20)}function tX(n){return 20*(Math.log(n)/Math.LN10)}function LL(n){return Math.pow(2,n/12)}let Uv=440;function nX(){return Uv}function rX(n){Uv=n}function Mu(n){return Math.round(PL(n))}function PL(n){return 69+12*Math.log2(n/Uv)}function DL(n){return Uv*Math.pow(2,(n-69)/12)}class IT extends Dc{constructor(e,t,r){super(),this.defaultUnits="s",this._val=t,this._units=r,this.context=e,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:e=>this._frequencyToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:e=>this._ticksToUnits(parseInt(e,10)),regexp:/^(\d+)i$/i},m:{method:e=>this._beatsToUnits(parseInt(e,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(e,t)=>{const r=parseInt(e,10),i=t==="."?1.5:1;return r===1?this._beatsToUnits(this._getTimeSignature())*i:this._beatsToUnits(4/r)*i},regexp:/^(\d+)n(\.?)$/i},number:{method:e=>this._expressions[this.defaultUnits].method.call(this,e),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:e=>this._secondsToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:e=>parseInt(e,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:e=>{const t=parseInt(e,10);return this._beatsToUnits(8/(Math.floor(t)*3))},regexp:/^(\d+)t$/i},tr:{method:(e,t,r)=>{let i=0;return e&&e!=="0"&&(i+=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),t&&t!=="0"&&(i+=this._beatsToUnits(parseFloat(t))),r&&r!=="0"&&(i+=this._beatsToUnits(parseFloat(r)/4)),i},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof IT&&this.fromType(this._val),Is(this._val))return this._noArg();if(bc(this._val)&&Is(this._units)){for(const e in this._expressions)if(this._expressions[e].regexp.test(this._val.trim())){this._units=e;break}}else if(yl(this._val)){let e=0;for(const t in this._val)if(Wt(this._val[t])){const r=this._val[t],i=new this.constructor(this.context,t).valueOf()*r;e+=i}return e}if(Wt(this._units)){const e=this._expressions[this._units],t=this._val.toString().trim().match(e.regexp);return t?e.method.apply(this,t.slice(1)):e.method.call(this,this._val)}else return bc(this._val)?parseFloat(this._val):this._val}_frequencyToUnits(e){return 1/e}_beatsToUnits(e){return 60/this._getBpm()*e}_secondsToUnits(e){return e}_ticksToUnits(e){return e*this._beatsToUnits(1)/this._getPPQ()}_noArg(){return this._now()}_getBpm(){return this.context.transport.bpm.value}_getTimeSignature(){return this.context.transport.timeSignature}_getPPQ(){return this.context.transport.PPQ}fromType(e){switch(this._units=void 0,this.defaultUnits){case"s":this._val=e.toSeconds();break;case"i":this._val=e.toTicks();break;case"hz":this._val=e.toFrequency();break;case"midi":this._val=e.toMidi();break}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return this.toSeconds()*1e3}}class Js extends IT{constructor(){super(...arguments),this.name="TimeClass"}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:e=>this._now()+new this.constructor(this.context,e).valueOf(),regexp:/^\+(.+)/},quantize:{method:e=>{const t=new Js(this.context,e).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(t))},regexp:/^@(.+)/}})}quantize(e,t=1){const r=new this.constructor(this.context,e).valueOf(),i=this.valueOf(),a=Math.round(i/r)*r-i;return i+a*t}toNotation(){const e=this.toSeconds(),t=["1m"];for(let s=1;s<9;s++){const o=Math.pow(2,s);t.push(o+"n."),t.push(o+"n"),t.push(o+"t")}t.push("0");let r=t[0],i=new Js(this.context,t[0]).toSeconds();return t.forEach(s=>{const o=new Js(this.context,s).toSeconds();Math.abs(o-e)3&&(i=parseFloat(parseFloat(s).toFixed(3))),[r,t,i].join(":")}toTicks(){const e=this._beatsToUnits(1);return this.valueOf()/e*this._getPPQ()}toSeconds(){return this.valueOf()}toMidi(){return Mu(this.toFrequency())}_now(){return this.context.now()}}function Ir(n,e){return new Js(Bi(),n,e)}class rs extends Js{constructor(){super(...arguments),this.name="Frequency",this.defaultUnits="hz"}static get A4(){return nX()}static set A4(e){rX(e)}_getExpressions(){return Object.assign({},super._getExpressions(),{midi:{regexp:/^(\d+(?:\.\d+)?midi)/,method(e){return this.defaultUnits==="midi"?e:rs.mtof(e)}},note:{regexp:/^([a-g]{1}(?:b|#|##|x|bb|###|#x|x#|bbb)?)(-?[0-9]+)/i,method(e,t){const i=iX[e.toLowerCase()]+(parseInt(t,10)+1)*12;return this.defaultUnits==="midi"?i:rs.mtof(i)}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method(e,t,r){let i=1;return e&&e!=="0"&&(i*=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),t&&t!=="0"&&(i*=this._beatsToUnits(parseFloat(t))),r&&r!=="0"&&(i*=this._beatsToUnits(parseFloat(r)/4)),i}}})}transpose(e){return new rs(this.context,this.valueOf()*LL(e))}harmonize(e){return e.map(t=>this.transpose(t))}toMidi(){return Mu(this.valueOf())}toNote(){const e=this.toFrequency(),t=Math.log2(e/rs.A4);let r=Math.round(12*t)+57;const i=Math.floor(r/12);return i<0&&(r+=-12*i),sX[r%12]+i.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){const e=this._beatsToUnits(1),t=this.valueOf()/e;return Math.floor(t*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(e){return e}_ticksToUnits(e){return 1/(e*60/(this._getBpm()*this._getPPQ()))}_beatsToUnits(e){return 1/super._beatsToUnits(e)}_secondsToUnits(e){return 1/e}static mtof(e){return DL(e)}static ftom(e){return Mu(e)}}const iX={cbbb:-3,cbb:-2,cb:-1,c:0,"c#":1,cx:2,"c##":2,"c###":3,"cx#":3,"c#x":3,dbbb:-1,dbb:0,db:1,d:2,"d#":3,dx:4,"d##":4,"d###":5,"dx#":5,"d#x":5,ebbb:1,ebb:2,eb:3,e:4,"e#":5,ex:6,"e##":6,"e###":7,"ex#":7,"e#x":7,fbbb:2,fbb:3,fb:4,f:5,"f#":6,fx:7,"f##":7,"f###":8,"fx#":8,"f#x":8,gbbb:4,gbb:5,gb:6,g:7,"g#":8,gx:9,"g##":9,"g###":10,"gx#":10,"g#x":10,abbb:6,abb:7,ab:8,a:9,"a#":10,ax:11,"a##":11,"a###":12,"ax#":12,"a#x":12,bbbb:8,bbb:9,bb:10,b:11,"b#":12,bx:13,"b##":13,"b###":14,"bx#":14,"b#x":14},sX=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function t2(n,e){return new rs(Bi(),n,e)}class mf extends Js{constructor(){super(...arguments),this.name="TransportTime"}_now(){return this.context.transport.seconds}}class xi extends Dc{constructor(){super();const e=at(xi.getDefaults(),arguments,["context"]);this.defaultContext?this.context=this.defaultContext:this.context=e.context}static getDefaults(){return{context:Bi()}}now(){return this.context.currentTime+this.context.lookAhead}immediate(){return this.context.currentTime}get sampleTime(){return 1/this.context.sampleRate}get blockTime(){return 128/this.context.sampleRate}toSeconds(e){return U7(e),new Js(this.context,e).toSeconds()}toFrequency(e){return new rs(this.context,e).toFrequency()}toTicks(e){return new mf(this.context,e).toTicks()}_getPartialProperties(e){const t=this.get();return Object.keys(t).forEach(r=>{Is(e[r])&&delete t[r]}),t}get(){const e=q7(this);return Object.keys(e).forEach(t=>{if(Reflect.has(this,t)){const r=this[t];Wt(r)&&Wt(r.value)&&Wt(r.setValueAtTime)?e[t]=r.value:r instanceof xi?e[t]=r._getPartialProperties(e[t]):as(r)||ko(r)||bc(r)||AL(r)?e[t]=r:delete e[t]}}),e}set(e){return Object.keys(e).forEach(t=>{Reflect.has(this,t)&&Wt(this[t])&&(this[t]&&Wt(this[t].value)&&Wt(this[t].setValueAtTime)?this[t].value!==e[t]&&(this[t].value=e[t]):this[t]instanceof xi?this[t].set(e[t]):this[t]=e[t])}),this}}class nm extends to{constructor(e="stopped"){super(),this.name="StateTimeline",this._initial=e,this.setStateAtTime(this._initial,0)}getValueAtTime(e){const t=this.get(e);return t!==null?t.state:this._initial}setStateAtTime(e,t,r){return Ea(t,0),this.add(Object.assign({},r,{state:e,time:t})),this}getLastState(e,t){const r=this._search(t);for(let i=r;i>=0;i--){const s=this._timeline[i];if(s.state===e)return s}}getNextState(e,t){const r=this._search(t);if(r!==-1)for(let i=r;i0,"timeConstant must be a number greater than 0");const s=this.toSeconds(t);return this._assertRange(i),Tt(isFinite(i)&&isFinite(s),`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(e)}, ${JSON.stringify(t)}`),this._events.add({constant:r,time:s,type:"setTargetAtTime",value:i}),this.log(this.units,"setTargetAtTime",e,s,r),this._param.setTargetAtTime(i,s,r),this}setValueCurveAtTime(e,t,r,i=1){r=this.toSeconds(r),t=this.toSeconds(t);const s=this._fromType(e[0])*i;this.setValueAtTime(this._toType(s),t);const o=r/(e.length-1);for(let a=1;a{i.type==="cancelScheduledValues"?e.cancelScheduledValues(i.time):i.type==="setTargetAtTime"?e.setTargetAtTime(i.value,i.time,i.constant):e[i.type](i.value,i.time)}),this}setParam(e){Tt(this._swappable,"The Param must be assigned as 'swappable' in the constructor");const t=this.input;return t.disconnect(this._param),this.apply(e),this._param=e,t.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(e,t,r,i,s){return r+(t-r)*Math.exp(-(s-e)/i)}_linearInterpolate(e,t,r,i,s){return t+(i-t)*((s-e)/(r-e))}_exponentialInterpolate(e,t,r,i,s){return t*Math.pow(i/t,(s-e)/(r-e))}}class ht extends xi{constructor(){super(...arguments),this._internalChannels=[]}get numberOfInputs(){return Wt(this.input)?Fu(this.input)||this.input instanceof Xt?1:this.input.numberOfInputs:0}get numberOfOutputs(){return Wt(this.output)?this.output.numberOfOutputs:0}_isAudioNode(e){return Wt(e)&&(e instanceof ht||xl(e))}_getInternalNodes(){const e=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&e.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&e.push(this.output),e}_setChannelProperties(e){this._getInternalNodes().forEach(r=>{r.channelCount=e.channelCount,r.channelCountMode=e.channelCountMode,r.channelInterpretation=e.channelInterpretation})}_getChannelProperties(){const e=this._getInternalNodes();Tt(e.length>0,"ToneAudioNode does not have any internal nodes");const t=e[0];return{channelCount:t.channelCount,channelCountMode:t.channelCountMode,channelInterpretation:t.channelInterpretation}}get channelCount(){return this._getChannelProperties().channelCount}set channelCount(e){const t=this._getChannelProperties();this._setChannelProperties(Object.assign(t,{channelCount:e}))}get channelCountMode(){return this._getChannelProperties().channelCountMode}set channelCountMode(e){const t=this._getChannelProperties();this._setChannelProperties(Object.assign(t,{channelCountMode:e}))}get channelInterpretation(){return this._getChannelProperties().channelInterpretation}set channelInterpretation(e){const t=this._getChannelProperties();this._setChannelProperties(Object.assign(t,{channelInterpretation:e}))}connect(e,t=0,r=0){return Io(this,e,t,r),this}toDestination(){return this.connect(this.context.destination),this}toMaster(){return Ov("toMaster() has been renamed toDestination()"),this.toDestination()}disconnect(e,t=0,r=0){return UL(this,e,t,r),this}chain(...e){return Bu(this,...e),this}fan(...e){return e.forEach(t=>this.connect(t)),this}dispose(){return super.dispose(),Wt(this.input)&&(this.input instanceof ht?this.input.dispose():xl(this.input)&&this.input.disconnect()),Wt(this.output)&&(this.output instanceof ht?this.output.dispose():xl(this.output)&&this.output.disconnect()),this._internalChannels=[],this}}function Bu(...n){const e=n.shift();n.reduce((t,r)=>(t instanceof ht?t.connect(r):xl(t)&&Io(t,r),r),e)}function Io(n,e,t=0,r=0){for(Tt(Wt(n),"Cannot connect from undefined node"),Tt(Wt(e),"Cannot connect to undefined node"),(e instanceof ht||xl(e))&&Tt(e.numberOfInputs>0,"Cannot connect to node with no inputs"),Tt(n.numberOfOutputs>0,"Cannot connect from node with no outputs");e instanceof ht||e instanceof Xt;)Wt(e.input)&&(e=e.input);for(;n instanceof ht;)Wt(n.output)&&(n=n.output);Fu(e)?n.connect(e,t):n.connect(e,t,r)}function UL(n,e,t=0,r=0){if(Wt(e))for(;e instanceof ht;)e=e.input;for(;!xl(n);)Wt(n.output)&&(n=n.output);Fu(e)?n.disconnect(e,t):xl(e)?n.disconnect(e,t,r):n.disconnect()}class jt extends ht{constructor(){const e=at(jt.getDefaults(),arguments,["gain","units"]);super(e),this.name="Gain",this._gainNode=this.context.createGain(),this.input=this._gainNode,this.output=this._gainNode,this.gain=new Xt({context:this.context,convert:e.convert,param:this._gainNode.gain,units:e.units,value:e.gain,minValue:e.minValue,maxValue:e.maxValue}),Zt(this,"gain")}static getDefaults(){return Object.assign(ht.getDefaults(),{convert:!0,gain:1,units:"gain"})}dispose(){return super.dispose(),this._gainNode.disconnect(),this.gain.dispose(),this}}class Of extends ht{constructor(e){super(e),this.onended=En,this._startTime=-1,this._stopTime=-1,this._timeout=-1,this.output=new jt({context:this.context,gain:0}),this._gainNode=this.output,this.getStateAtTime=function(t){const r=this.toSeconds(t);return this._startTime!==-1&&r>=this._startTime&&(this._stopTime===-1||r<=this._stopTime)?"started":"stopped"},this._fadeIn=e.fadeIn,this._fadeOut=e.fadeOut,this._curve=e.curve,this.onended=e.onended}static getDefaults(){return Object.assign(ht.getDefaults(),{curve:"linear",fadeIn:0,fadeOut:0,onended:En})}_startGain(e,t=1){Tt(this._startTime===-1,"Source cannot be started more than once");const r=this.toSeconds(this._fadeIn);return this._startTime=e+r,this._startTime=Math.max(this._startTime,this.context.currentTime),r>0?(this._gainNode.gain.setValueAtTime(0,e),this._curve==="linear"?this._gainNode.gain.linearRampToValueAtTime(t,e+r):this._gainNode.gain.exponentialApproachValueAtTime(t,e,r)):this._gainNode.gain.setValueAtTime(t,e),this}stop(e){return this.log("stop",e),this._stopGain(this.toSeconds(e)),this}_stopGain(e){Tt(this._startTime!==-1,"'start' must be called before 'stop'"),this.cancelStop();const t=this.toSeconds(this._fadeOut);return this._stopTime=this.toSeconds(e)+t,this._stopTime=Math.max(this._stopTime,this.now()),t>0?this._curve==="linear"?this._gainNode.gain.linearRampTo(0,t,e):this._gainNode.gain.targetRampTo(0,t,e):(this._gainNode.gain.cancelAndHoldAtTime(e),this._gainNode.gain.setValueAtTime(0,e)),this.context.clearTimeout(this._timeout),this._timeout=this.context.setTimeout(()=>{const r=this._curve==="exponential"?t*2:0;this._stopSource(this.now()+r),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){if(this.onended!==En&&(this.onended(this),this.onended=En,!this.context.isOffline)){const e=()=>this.dispose();typeof window.requestIdleCallback<"u"?window.requestIdleCallback(e):setTimeout(e,1e3)}}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log("cancelStop"),Tt(this._startTime!==-1,"Source is not started"),this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1,this}dispose(){return super.dispose(),this._gainNode.dispose(),this.onended=En,this}}class NT extends Of{constructor(){const e=at(NT.getDefaults(),arguments,["offset"]);super(e),this.name="ToneConstantSource",this._source=this.context.createConstantSource(),Io(this._source,this._gainNode),this.offset=new Xt({context:this.context,convert:e.convert,param:this._source.offset,units:e.units,value:e.offset,minValue:e.minValue,maxValue:e.maxValue})}static getDefaults(){return Object.assign(Of.getDefaults(),{convert:!0,offset:1,units:"number"})}start(e){const t=this.toSeconds(e);return this.log("start",t),this._startGain(t),this._source.start(t),this}_stopSource(e){this._source.stop(e)}dispose(){return super.dispose(),this.state==="started"&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}}class yn extends ht{constructor(){const e=at(yn.getDefaults(),arguments,["value","units"]);super(e),this.name="Signal",this.override=!0,this.output=this._constantSource=new NT({context:this.context,convert:e.convert,offset:e.value,units:e.units,minValue:e.minValue,maxValue:e.maxValue}),this._constantSource.start(0),this.input=this._param=this._constantSource.offset}static getDefaults(){return Object.assign(ht.getDefaults(),{convert:!0,units:"number",value:0})}connect(e,t=0,r=0){return Fv(this,e,t,r),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(e,t){return this._param.setValueAtTime(e,t),this}getValueAtTime(e){return this._param.getValueAtTime(e)}setRampPoint(e){return this._param.setRampPoint(e),this}linearRampToValueAtTime(e,t){return this._param.linearRampToValueAtTime(e,t),this}exponentialRampToValueAtTime(e,t){return this._param.exponentialRampToValueAtTime(e,t),this}exponentialRampTo(e,t,r){return this._param.exponentialRampTo(e,t,r),this}linearRampTo(e,t,r){return this._param.linearRampTo(e,t,r),this}targetRampTo(e,t,r){return this._param.targetRampTo(e,t,r),this}exponentialApproachValueAtTime(e,t,r){return this._param.exponentialApproachValueAtTime(e,t,r),this}setTargetAtTime(e,t,r){return this._param.setTargetAtTime(e,t,r),this}setValueCurveAtTime(e,t,r,i){return this._param.setValueCurveAtTime(e,t,r,i),this}cancelScheduledValues(e){return this._param.cancelScheduledValues(e),this}cancelAndHoldAtTime(e){return this._param.cancelAndHoldAtTime(e),this}rampTo(e,t,r){return this._param.rampTo(e,t,r),this}get value(){return this._param.value}set value(e){this._param.value=e}get convert(){return this._param.convert}set convert(e){this._param.convert=e}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(e){this._param.overridden=e}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(e){return this._param.apply(e),this}}function Fv(n,e,t,r){(e instanceof Xt||Fu(e)||e instanceof yn&&e.override)&&(e.cancelScheduledValues(0),e.setValueAtTime(0,0),e instanceof yn&&(e.overridden=!0)),Io(n,e,t,r)}class OT extends Xt{constructor(){const e=at(OT.getDefaults(),arguments,["value"]);super(e),this.name="TickParam",this._events=new to(1/0),this._multiplier=1,this._multiplier=e.multiplier,this._events.cancel(0),this._events.add({ticks:0,time:0,type:"setValueAtTime",value:this._fromType(e.value)}),this.setValueAtTime(e.value,0)}static getDefaults(){return Object.assign(Xt.getDefaults(),{multiplier:1,units:"hertz",value:1})}setTargetAtTime(e,t,r){t=this.toSeconds(t),this.setRampPoint(t);const i=this._fromType(e),s=this._events.get(t),o=Math.round(Math.max(1/r,1));for(let a=0;a<=o;a++){const c=r*a+t,l=this._exponentialApproach(s.time,s.value,i,r,c);this.linearRampToValueAtTime(this._toType(l),c)}return this}setValueAtTime(e,t){const r=this.toSeconds(t);super.setValueAtTime(e,t);const i=this._events.get(r),s=this._events.previousEvent(i),o=this._getTicksUntilEvent(s,r);return i.ticks=Math.max(o,0),this}linearRampToValueAtTime(e,t){const r=this.toSeconds(t);super.linearRampToValueAtTime(e,t);const i=this._events.get(r),s=this._events.previousEvent(i),o=this._getTicksUntilEvent(s,r);return i.ticks=Math.max(o,0),this}exponentialRampToValueAtTime(e,t){t=this.toSeconds(t);const r=this._fromType(e),i=this._events.get(t),s=Math.round(Math.max((t-i.time)*10,1)),o=(t-i.time)/s;for(let a=0;a<=s;a++){const c=o*a+i.time,l=this._exponentialInterpolate(i.time,i.value,t,r,c);this.linearRampToValueAtTime(this._toType(l),c)}return this}_getTicksUntilEvent(e,t){if(e===null)e={ticks:0,time:0,type:"setValueAtTime",value:0};else if(Is(e.ticks)){const o=this._events.previousEvent(e);e.ticks=this._getTicksUntilEvent(o,e.time)}const r=this._fromType(this.getValueAtTime(e.time));let i=this._fromType(this.getValueAtTime(t));const s=this._events.get(t);return s&&s.time===t&&s.type==="setValueAtTime"&&(i=this._fromType(this.getValueAtTime(t-this.sampleTime))),.5*(t-e.time)*(r+i)+e.ticks}getTicksAtTime(e){const t=this.toSeconds(e),r=this._events.get(t);return Math.max(this._getTicksUntilEvent(r,t),0)}getDurationOfTicks(e,t){const r=this.toSeconds(t),i=this.getTicksAtTime(t);return this.getTimeOfTick(i+e)-r}getTimeOfTick(e){const t=this._events.get(e,"ticks"),r=this._events.getAfter(e,"ticks");if(t&&t.ticks===e)return t.time;if(t&&r&&r.type==="linearRampToValueAtTime"&&t.value!==r.value){const i=this._fromType(this.getValueAtTime(t.time)),o=(this._fromType(this.getValueAtTime(r.time))-i)/(r.time-t.time),a=Math.sqrt(Math.pow(i,2)-2*o*(t.ticks-e)),c=(-i+a)/o,l=(-i-a)/o;return(c>0?c:l)+t.time}else return t?t.value===0?1/0:t.time+(e-t.ticks)/t.value:e/this._initialValue}ticksToTime(e,t){return this.getDurationOfTicks(e,t)}timeToTicks(e,t){const r=this.toSeconds(t),i=this.toSeconds(e),s=this.getTicksAtTime(r);return this.getTicksAtTime(r+i)-s}_fromType(e){return this.units==="bpm"&&this.multiplier?1/(60/e/this.multiplier):super._fromType(e)}_toType(e){return this.units==="bpm"&&this.multiplier?e/this.multiplier*60:super._toType(e)}get multiplier(){return this._multiplier}set multiplier(e){const t=this.value;this._multiplier=e,this.cancelScheduledValues(0),this.setValueAtTime(t,0)}}class LT extends yn{constructor(){const e=at(LT.getDefaults(),arguments,["value"]);super(e),this.name="TickSignal",this.input=this._param=new OT({context:this.context,convert:e.convert,multiplier:e.multiplier,param:this._constantSource.offset,units:e.units,value:e.value})}static getDefaults(){return Object.assign(yn.getDefaults(),{multiplier:1,units:"hertz",value:1})}ticksToTime(e,t){return this._param.ticksToTime(e,t)}timeToTicks(e,t){return this._param.timeToTicks(e,t)}getTimeOfTick(e){return this._param.getTimeOfTick(e)}getDurationOfTicks(e,t){return this._param.getDurationOfTicks(e,t)}getTicksAtTime(e){return this._param.getTicksAtTime(e)}get multiplier(){return this._param.multiplier}set multiplier(e){this._param.multiplier=e}dispose(){return super.dispose(),this._param.dispose(),this}}class PT extends xi{constructor(){const e=at(PT.getDefaults(),arguments,["frequency"]);super(e),this.name="TickSource",this._state=new nm,this._tickOffset=new to,this._ticksAtTime=new to,this._secondsAtTime=new to,this.frequency=new LT({context:this.context,units:e.units,value:e.frequency}),Zt(this,"frequency"),this._state.setStateAtTime("stopped",0),this.setTicksAtTime(0,0)}static getDefaults(){return Object.assign({frequency:1,units:"hertz"},xi.getDefaults())}get state(){return this.getStateAtTime(this.now())}start(e,t){const r=this.toSeconds(e);return this._state.getValueAtTime(r)!=="started"&&(this._state.setStateAtTime("started",r),Wt(t)&&this.setTicksAtTime(t,r),this._ticksAtTime.cancel(r),this._secondsAtTime.cancel(r)),this}stop(e){const t=this.toSeconds(e);if(this._state.getValueAtTime(t)==="stopped"){const r=this._state.get(t);r&&r.time>0&&(this._tickOffset.cancel(r.time),this._state.cancel(r.time))}return this._state.cancel(t),this._state.setStateAtTime("stopped",t),this.setTicksAtTime(0,t),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t),this}pause(e){const t=this.toSeconds(e);return this._state.getValueAtTime(t)==="started"&&(this._state.setStateAtTime("paused",t),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t)),this}cancel(e){return e=this.toSeconds(e),this._state.cancel(e),this._tickOffset.cancel(e),this._ticksAtTime.cancel(e),this._secondsAtTime.cancel(e),this}getTicksAtTime(e){const t=this.toSeconds(e),r=this._state.getLastState("stopped",t),i=this._ticksAtTime.get(t),s={state:"paused",time:t};this._state.add(s);let o=i||r,a=i?i.ticks:0,c=null;return this._state.forEachBetween(o.time,t+this.sampleTime,l=>{let u=o.time;const h=this._tickOffset.get(l.time);h&&h.time>=o.time&&(a=h.ticks,u=h.time),o.state==="started"&&l.state!=="started"&&(a+=this.frequency.getTicksAtTime(l.time)-this.frequency.getTicksAtTime(u),l.time!==s.time&&(c={state:l.state,time:l.time,ticks:a})),o=l}),this._state.remove(s),c&&this._ticksAtTime.add(c),a}get ticks(){return this.getTicksAtTime(this.now())}set ticks(e){this.setTicksAtTime(e,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(e){const t=this.now(),r=this.frequency.timeToTicks(e,t);this.setTicksAtTime(r,t)}getSecondsAtTime(e){e=this.toSeconds(e);const t=this._state.getLastState("stopped",e),r={state:"paused",time:e};this._state.add(r);const i=this._secondsAtTime.get(e);let s=i||t,o=i?i.seconds:0,a=null;return this._state.forEachBetween(s.time,e+this.sampleTime,c=>{let l=s.time;const u=this._tickOffset.get(c.time);u&&u.time>=s.time&&(o=u.seconds,l=u.time),s.state==="started"&&c.state!=="started"&&(o+=c.time-l,c.time!==r.time&&(a={state:c.state,time:c.time,seconds:o})),s=c}),this._state.remove(r),a&&this._secondsAtTime.add(a),o}setTicksAtTime(e,t){return t=this.toSeconds(t),this._tickOffset.cancel(t),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(e,t),ticks:e,time:t}),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t),this}getStateAtTime(e){return e=this.toSeconds(e),this._state.getValueAtTime(e)}getTimeOfTick(e,t=this.now()){const r=this._tickOffset.get(t),i=this._state.get(t),s=Math.max(r.time,i.time),o=this.frequency.getTicksAtTime(s)+e-r.ticks;return this.frequency.getTimeOfTick(o)}forEachTickBetween(e,t,r){let i=this._state.get(e);this._state.forEachBetween(e,t,o=>{i&&i.state==="started"&&o.state!=="started"&&this.forEachTickBetween(Math.max(i.time,e),o.time-this.sampleTime,r),i=o});let s=null;if(i&&i.state==="started"){const o=Math.max(i.time,e),a=this.frequency.getTicksAtTime(o),c=this.frequency.getTicksAtTime(i.time),l=a-c;let u=Math.ceil(l)-l;u=xo(u,1)?0:u;let h=this.frequency.getTimeOfTick(a+u);for(;h{switch(r.state){case"started":const i=this._tickSource.getTicksAtTime(r.time);this.emit("start",r.time,i);break;case"stopped":r.time!==0&&this.emit("stop",r.time);break;case"paused":this.emit("pause",r.time);break}}),this._tickSource.forEachTickBetween(e,t,(r,i)=>{this.callback(r,i)}))}getStateAtTime(e){const t=this.toSeconds(e);return this._state.getValueAtTime(t)}dispose(){return super.dispose(),this.context.off("tick",this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}}Jp.mixin(Bv);class Lf extends ht{constructor(){const e=at(Lf.getDefaults(),arguments,["delayTime","maxDelay"]);super(e),this.name="Delay";const t=this.toSeconds(e.maxDelay);this._maxDelay=Math.max(t,this.toSeconds(e.delayTime)),this._delayNode=this.input=this.output=this.context.createDelay(t),this.delayTime=new Xt({context:this.context,param:this._delayNode.delayTime,units:"time",value:e.delayTime,minValue:0,maxValue:this.maxDelay}),Zt(this,"delayTime")}static getDefaults(){return Object.assign(ht.getDefaults(),{delayTime:0,maxDelay:1})}get maxDelay(){return this._maxDelay}dispose(){return super.dispose(),this._delayNode.disconnect(),this.delayTime.dispose(),this}}class Al extends ht{constructor(){const e=at(Al.getDefaults(),arguments,["volume"]);super(e),this.name="Volume",this.input=this.output=new jt({context:this.context,gain:e.volume,units:"decibels"}),this.volume=this.output.gain,Zt(this,"volume"),this._unmutedVolume=e.volume,this.mute=e.mute}static getDefaults(){return Object.assign(ht.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(e){!this.mute&&e?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!e&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}}class DT extends ht{constructor(){const e=at(DT.getDefaults(),arguments);super(e),this.name="Destination",this.input=new Al({context:this.context}),this.output=new jt({context:this.context}),this.volume=this.input.volume,Bu(this.input,this.output,this.context.rawContext.destination),this.mute=e.mute,this._internalChannels=[this.input,this.context.rawContext.destination,this.output]}static getDefaults(){return Object.assign(ht.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(e){this.input.mute=e}chain(...e){return this.input.disconnect(),e.unshift(this.input),e.push(this.output),Bu(...e),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}}Lv(n=>{n.destination=new DT({context:n})});Pv(n=>{n.destination.dispose()});class oX extends ht{constructor(){super(...arguments),this.name="Listener",this.positionX=new Xt({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new Xt({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new Xt({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new Xt({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new Xt({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new Xt({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new Xt({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new Xt({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new Xt({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(ht.getDefaults(),{positionX:0,positionY:0,positionZ:0,forwardX:0,forwardY:0,forwardZ:-1,upX:0,upY:1,upZ:0})}dispose(){return super.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this.forwardX.dispose(),this.forwardY.dispose(),this.forwardZ.dispose(),this.upX.dispose(),this.upY.dispose(),this.upZ.dispose(),this}}Lv(n=>{n.listener=new oX({context:n})});Pv(n=>{n.listener.dispose()});class UT extends Dc{constructor(){super(),this.name="ToneAudioBuffers",this._buffers=new Map,this._loadingCount=0;const e=at(UT.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");this.baseUrl=e.baseUrl,Object.keys(e.urls).forEach(t=>{this._loadingCount++;const r=e.urls[t];this.add(t,r,this._bufferLoaded.bind(this,e.onload),e.onerror)})}static getDefaults(){return{baseUrl:"",onerror:En,onload:En,urls:{}}}has(e){return this._buffers.has(e.toString())}get(e){return Tt(this.has(e),`ToneAudioBuffers has no buffer named: ${e}`),this._buffers.get(e.toString())}_bufferLoaded(e){this._loadingCount--,this._loadingCount===0&&e&&e()}get loaded(){return Array.from(this._buffers).every(([e,t])=>t.loaded)}add(e,t,r=En,i=En){return bc(t)?(this.baseUrl&&t.trim().substring(0,11).toLowerCase()==="data:audio/"&&(this.baseUrl=""),this._buffers.set(e.toString(),new An(this.baseUrl+t,r,i))):this._buffers.set(e.toString(),new An(t,r,i)),this}dispose(){return super.dispose(),this._buffers.forEach(e=>e.dispose()),this._buffers.clear(),this}}class N_ extends rs{constructor(){super(...arguments),this.name="MidiClass",this.defaultUnits="midi"}_frequencyToUnits(e){return Mu(super._frequencyToUnits(e))}_ticksToUnits(e){return Mu(super._ticksToUnits(e))}_beatsToUnits(e){return Mu(super._beatsToUnits(e))}_secondsToUnits(e){return Mu(super._secondsToUnits(e))}toMidi(){return this.valueOf()}toFrequency(){return DL(this.toMidi())}transpose(e){return new N_(this.context,this.toMidi()+e)}}class Pr extends mf{constructor(){super(...arguments),this.name="Ticks",this.defaultUnits="i"}_now(){return this.context.transport.ticks}_beatsToUnits(e){return this._getPPQ()*e}_secondsToUnits(e){return Math.floor(e/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(e){return e}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}}class aX extends xi{constructor(){super(...arguments),this.name="Draw",this.expiration=.25,this.anticipation=.008,this._events=new to,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(e,t){return this._events.add({callback:e,time:this.toSeconds(t)}),this._events.length===1&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(e){return this._events.cancel(this.toSeconds(e)),this}_drawLoop(){const e=this.context.currentTime;for(;this._events.length&&this._events.peek().time-this.anticipation<=e;){const t=this._events.shift();t&&e-t.time<=this.expiration&&t.callback()}this._events.length>0&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop))}dispose(){return super.dispose(),this._events.dispose(),cancelAnimationFrame(this._animationFrame),this}}Lv(n=>{n.draw=new aX({context:n})});Pv(n=>{n.draw.dispose()});class cX extends Dc{constructor(){super(...arguments),this.name="IntervalTimeline",this._root=null,this._length=0}add(e){Tt(Wt(e.time),"Events must have a time property"),Tt(Wt(e.duration),"Events must have a duration parameter"),e.time=e.time.valueOf();let t=new lX(e.time,e.time+e.duration,e);for(this._root===null?this._root=t:this._root.insert(t),this._length++;t!==null;)t.updateHeight(),t.updateMax(),this._rebalance(t),t=t.parent;return this}remove(e){if(this._root!==null){const t=[];this._root.search(e.time,t);for(const r of t)if(r.event===e){this._removeNode(r),this._length--;break}}return this}get length(){return this._length}cancel(e){return this.forEachFrom(e,t=>this.remove(t)),this}_setRoot(e){this._root=e,this._root!==null&&(this._root.parent=null)}_replaceNodeInParent(e,t){e.parent!==null?(e.isLeftChild()?e.parent.left=t:e.parent.right=t,this._rebalance(e.parent)):this._setRoot(t)}_removeNode(e){if(e.left===null&&e.right===null)this._replaceNodeInParent(e,null);else if(e.right===null)this._replaceNodeInParent(e,e.left);else if(e.left===null)this._replaceNodeInParent(e,e.right);else{const t=e.getBalance();let r,i=null;if(t>0)if(e.left.right===null)r=e.left,r.right=e.right,i=r;else{for(r=e.left.right;r.right!==null;)r=r.right;r.parent&&(r.parent.right=r.left,i=r.parent,r.left=e.left,r.right=e.right)}else if(e.right.left===null)r=e.right,r.left=e.left,i=r;else{for(r=e.right.left;r.left!==null;)r=r.left;r.parent&&(r.parent.left=r.right,i=r.parent,r.left=e.left,r.right=e.right)}e.parent!==null?e.isLeftChild()?e.parent.left=r:e.parent.right=r:this._setRoot(r),i&&this._rebalance(i)}e.dispose()}_rotateLeft(e){const t=e.parent,r=e.isLeftChild(),i=e.right;i&&(e.right=i.left,i.left=e),t!==null?r?t.left=i:t.right=i:this._setRoot(i)}_rotateRight(e){const t=e.parent,r=e.isLeftChild(),i=e.left;i&&(e.left=i.right,i.right=e),t!==null?r?t.left=i:t.right=i:this._setRoot(i)}_rebalance(e){const t=e.getBalance();t>1&&e.left?e.left.getBalance()<0?this._rotateLeft(e.left):this._rotateRight(e):t<-1&&e.right&&(e.right.getBalance()>0?this._rotateRight(e.right):this._rotateLeft(e))}get(e){if(this._root!==null){const t=[];if(this._root.search(e,t),t.length>0){let r=t[0];for(let i=1;ir.low&&(r=t[i]);return r.event}}return null}forEach(e){if(this._root!==null){const t=[];this._root.traverse(r=>t.push(r)),t.forEach(r=>{r.event&&e(r.event)})}return this}forEachAtTime(e,t){if(this._root!==null){const r=[];this._root.search(e,r),r.forEach(i=>{i.event&&t(i.event)})}return this}forEachFrom(e,t){if(this._root!==null){const r=[];this._root.searchAfter(e,r),r.forEach(i=>{i.event&&t(i.event)})}return this}dispose(){return super.dispose(),this._root!==null&&this._root.traverse(e=>e.dispose()),this._root=null,this}}class lX{constructor(e,t,r){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=r,this.low=e,this.high=t,this.max=this.high}insert(e){e.low<=this.low?this.left===null?this.left=e:this.left.insert(e):this.right===null?this.right=e:this.right.insert(e)}search(e,t){e>this.max||(this.left!==null&&this.left.search(e,t),this.low<=e&&this.high>e&&t.push(this),!(this.low>e)&&this.right!==null&&this.right.search(e,t))}searchAfter(e,t){this.low>=e&&(t.push(this),this.left!==null&&this.left.searchAfter(e,t)),this.right!==null&&this.right.searchAfter(e,t)}traverse(e){e(this),this.left!==null&&this.left.traverse(e),this.right!==null&&this.right.traverse(e)}updateHeight(){this.left!==null&&this.right!==null?this.height=Math.max(this.left.height,this.right.height)+1:this.right!==null?this.height=this.right.height+1:this.left!==null?this.height=this.left.height+1:this.height=0}updateMax(){this.max=this.high,this.left!==null&&(this.max=Math.max(this.max,this.left.max)),this.right!==null&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let e=0;return this.left!==null&&this.right!==null?e=this.left.height-this.right.height:this.left!==null?e=this.left.height+1:this.right!==null&&(e=-(this.right.height+1)),e}isLeftChild(){return this.parent!==null&&this.parent.left===this}get left(){return this._left}set left(e){this._left=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(e){this._right=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}}class uX extends Dc{constructor(e){super(),this.name="TimelineValue",this._timeline=new to({memory:10}),this._initialValue=e}set(e,t){return this._timeline.add({value:e,time:t}),this}get(e){const t=this._timeline.get(e);return t?t.value:this._initialValue}}class wa extends ht{constructor(){super(at(wa.getDefaults(),arguments,["context"]))}connect(e,t=0,r=0){return Fv(this,e,t,r),this}}class th extends wa{constructor(){const e=at(th.getDefaults(),arguments,["mapping","length"]);super(e),this.name="WaveShaper",this._shaper=this.context.createWaveShaper(),this.input=this._shaper,this.output=this._shaper,as(e.mapping)||e.mapping instanceof Float32Array?this.curve=Float32Array.from(e.mapping):D7(e.mapping)&&this.setMap(e.mapping,e.length)}static getDefaults(){return Object.assign(yn.getDefaults(),{length:1024})}setMap(e,t=1024){const r=new Float32Array(t);for(let i=0,s=t;ir.includes(e));Tt(t,"oversampling must be either 'none', '2x', or '4x'"),this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.disconnect(),this}}class FT extends wa{constructor(){const e=at(FT.getDefaults(),arguments,["value"]);super(e),this.name="Pow",this._exponentScaler=this.input=this.output=new th({context:this.context,mapping:this._expFunc(e.value),length:8192}),this._exponent=e.value}static getDefaults(){return Object.assign(wa.getDefaults(),{value:1})}_expFunc(e){return t=>Math.pow(Math.abs(t),e)}get value(){return this._exponent}set value(e){this._exponent=e,this._exponentScaler.setMap(this._expFunc(this._exponent))}dispose(){return super.dispose(),this._exponentScaler.dispose(),this}}class Ml{constructor(e,t){this.id=Ml._eventId++,this._remainderTime=0;const r=Object.assign(Ml.getDefaults(),t);this.transport=e,this.callback=r.callback,this._once=r.once,this.time=Math.floor(r.time),this._remainderTime=r.time-this.time}static getDefaults(){return{callback:En,once:!1,time:0}}get floatTime(){return this.time+this._remainderTime}invoke(e){if(this.callback){const t=this.transport.bpm.getDurationOfTicks(1,e);this.callback(e+this._remainderTime*t),this._once&&this.transport.clear(this.id)}}dispose(){return this.callback=void 0,this}}Ml._eventId=0;class BT extends Ml{constructor(e,t){super(e,t),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);const r=Object.assign(BT.getDefaults(),t);this.duration=r.duration,this._interval=r.interval,this._nextTick=r.time,this.transport.on("start",this._boundRestart),this.transport.on("loopStart",this._boundRestart),this.transport.on("ticks",this._boundRestart),this.context=this.transport.context,this._restart()}static getDefaults(){return Object.assign({},Ml.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(e){this._createEvents(e),super.invoke(e)}_createEvent(){return I_(this._nextTick,this.floatTime+this.duration)?this.transport.scheduleOnce(this.invoke.bind(this),new Pr(this.context,this._nextTick).toSeconds()):-1}_createEvents(e){I_(this._nextTick+this._interval,this.floatTime+this.duration)&&(this._nextTick+=this._interval,this._currentId=this._nextId,this._nextId=this.transport.scheduleOnce(this.invoke.bind(this),new Pr(this.context,this._nextTick).toSeconds()))}_restart(e){this.transport.clear(this._currentId),this.transport.clear(this._nextId),this._nextTick=this.floatTime;const t=this.transport.getTicksAtTime(e);Nf(t,this.time)&&(this._nextTick=this.floatTime+Math.ceil((t-this.floatTime)/this._interval)*this._interval),this._currentId=this._createEvent(),this._nextTick+=this._interval,this._nextId=this._createEvent()}dispose(){return super.dispose(),this.transport.clear(this._currentId),this.transport.clear(this._nextId),this.transport.off("start",this._boundRestart),this.transport.off("loopStart",this._boundRestart),this.transport.off("ticks",this._boundRestart),this}}class zv extends xi{constructor(){const e=at(zv.getDefaults(),arguments);super(e),this.name="Transport",this._loop=new uX(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new to,this._repeatedEvents=new cX,this._syncedSignals=[],this._swingAmount=0,this._ppq=e.ppq,this._clock=new Bv({callback:this._processTick.bind(this),context:this.context,frequency:0,units:"bpm"}),this._bindClockEvents(),this.bpm=this._clock.frequency,this._clock.frequency.multiplier=e.ppq,this.bpm.setValueAtTime(e.bpm,0),Zt(this,"bpm"),this._timeSignature=e.timeSignature,this._swingTicks=e.ppq/2}static getDefaults(){return Object.assign(xi.getDefaults(),{bpm:120,loopEnd:"4m",loopStart:0,ppq:192,swing:0,swingSubdivision:"8n",timeSignature:4})}_processTick(e,t){if(this._loop.get(e)&&t>=this._loopEnd&&(this.emit("loopEnd",e),this._clock.setTicksAtTime(this._loopStart,e),t=this._loopStart,this.emit("loopStart",e,this._clock.getSecondsAtTime(e)),this.emit("loop",e)),this._swingAmount>0&&t%this._ppq!==0&&t%(this._swingTicks*2)!==0){const r=t%(this._swingTicks*2)/(this._swingTicks*2),i=Math.sin(r*Math.PI)*this._swingAmount;e+=new Pr(this.context,this._swingTicks*2/3).toSeconds()*i}e2(!0),this._timeline.forEachAtTime(t,r=>r.invoke(e)),e2(!1)}schedule(e,t){const r=new Ml(this,{callback:e,time:new mf(this.context,t).toTicks()});return this._addEvent(r,this._timeline)}scheduleRepeat(e,t,r,i=1/0){const s=new BT(this,{callback:e,duration:new Js(this.context,i).toTicks(),interval:new Js(this.context,t).toTicks(),time:new mf(this.context,r).toTicks()});return this._addEvent(s,this._repeatedEvents)}scheduleOnce(e,t){const r=new Ml(this,{callback:e,once:!0,time:new mf(this.context,t).toTicks()});return this._addEvent(r,this._timeline)}clear(e){if(this._scheduledEvents.hasOwnProperty(e)){const t=this._scheduledEvents[e.toString()];t.timeline.remove(t.event),t.event.dispose(),delete this._scheduledEvents[e.toString()]}return this}_addEvent(e,t){return this._scheduledEvents[e.id.toString()]={event:e,timeline:t},t.add(e),e.id}cancel(e=0){const t=this.toTicks(e);return this._timeline.forEachFrom(t,r=>this.clear(r.id)),this._repeatedEvents.forEachFrom(t,r=>this.clear(r.id)),this}_bindClockEvents(){this._clock.on("start",(e,t)=>{t=new Pr(this.context,t).toSeconds(),this.emit("start",e,t)}),this._clock.on("stop",e=>{this.emit("stop",e)}),this._clock.on("pause",e=>{this.emit("pause",e)})}get state(){return this._clock.getStateAtTime(this.now())}start(e,t){this.context.resume();let r;return Wt(t)&&(r=this.toTicks(t)),this._clock.start(e,r),this}stop(e){return this._clock.stop(e),this}pause(e){return this._clock.pause(e),this}toggle(e){return e=this.toSeconds(e),this._clock.getStateAtTime(e)!=="started"?this.start(e):this.stop(e),this}get timeSignature(){return this._timeSignature}set timeSignature(e){as(e)&&(e=e[0]/e[1]*4),this._timeSignature=e}get loopStart(){return new Js(this.context,this._loopStart,"i").toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e)}get loopEnd(){return new Js(this.context,this._loopEnd,"i").toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e)}get loop(){return this._loop.get(this.now())}set loop(e){this._loop.set(e,this.now())}setLoopPoints(e,t){return this.loopStart=e,this.loopEnd=t,this}get swing(){return this._swingAmount}set swing(e){this._swingAmount=e}get swingSubdivision(){return new Pr(this.context,this._swingTicks).toNotation()}set swingSubdivision(e){this._swingTicks=this.toTicks(e)}get position(){const e=this.now(),t=this._clock.getTicksAtTime(e);return new Pr(this.context,t).toBarsBeatsSixteenths()}set position(e){const t=this.toTicks(e);this.ticks=t}get seconds(){return this._clock.seconds}set seconds(e){const t=this.now(),r=this._clock.frequency.timeToTicks(e,t);this.ticks=r}get progress(){if(this.loop){const e=this.now();return(this._clock.getTicksAtTime(e)-this._loopStart)/(this._loopEnd-this._loopStart)}else return 0}get ticks(){return this._clock.ticks}set ticks(e){if(this._clock.ticks!==e){const t=this.now();if(this.state==="started"){const r=this._clock.getTicksAtTime(t),i=this._clock.frequency.getDurationOfTicks(Math.ceil(r)-r,t),s=t+i;this.emit("stop",s),this._clock.setTicksAtTime(e,s),this.emit("start",s,this._clock.getSecondsAtTime(s))}else this.emit("ticks",t),this._clock.setTicksAtTime(e,t)}}getTicksAtTime(e){return this._clock.getTicksAtTime(e)}getSecondsAtTime(e){return this._clock.getSecondsAtTime(e)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(e){this._clock.frequency.multiplier=e}nextSubdivision(e){if(e=this.toTicks(e),this.state!=="started")return 0;{const t=this.now(),r=this.getTicksAtTime(t),i=e-r%e;return this._clock.nextTickTime(i,t)}}syncSignal(e,t){const r=this.now();let i=this.bpm,s=1/(60/i.getValueAtTime(r)/this.PPQ),o=[];if(e.units==="time"){const c=.015625/s,l=new jt(c),u=new FT(-1),h=new jt(c);i.chain(l,u,h),i=h,s=1/s,o=[l,u,h]}t||(e.getValueAtTime(r)!==0?t=e.getValueAtTime(r)/s:t=0);const a=new jt(t);return i.connect(a),a.connect(e._param),o.push(a),this._syncedSignals.push({initial:e.value,nodes:o,signal:e}),e.value=0,this}unsyncSignal(e){for(let t=this._syncedSignals.length-1;t>=0;t--){const r=this._syncedSignals[t];r.signal===e&&(r.nodes.forEach(i=>i.dispose()),r.signal.value=r.initial,this._syncedSignals.splice(t,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),tm(this,"bpm"),this._timeline.dispose(),this._repeatedEvents.dispose(),this}}Jp.mixin(zv);Lv(n=>{n.transport=new zv({context:n})});Pv(n=>{n.transport.dispose()});class wi extends ht{constructor(e){super(e),this.input=void 0,this._state=new nm("stopped"),this._synced=!1,this._scheduled=[],this._syncedStart=En,this._syncedStop=En,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new Al({context:this.context,mute:e.mute,volume:e.volume}),this.volume=this._volume.volume,Zt(this,"volume"),this.onstop=e.onstop}static getDefaults(){return Object.assign(ht.getDefaults(),{mute:!1,onstop:En,volume:0})}get state(){return this._synced?this.context.transport.state==="started"?this._state.getValueAtTime(this.context.transport.seconds):"stopped":this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}_clampToCurrentTime(e){return this._synced?e:Math.max(e,this.context.currentTime)}start(e,t,r){let i=Is(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(i=this._clampToCurrentTime(i),!this._synced&&this._state.getValueAtTime(i)==="started")Tt(Nf(i,this._state.get(i).time),"Start time must be strictly greater than previous start time"),this._state.cancel(i),this._state.setStateAtTime("started",i),this.log("restart",i),this.restart(i,t,r);else if(this.log("start",i),this._state.setStateAtTime("started",i),this._synced){const s=this._state.get(i);s&&(s.offset=this.toSeconds(ga(t,0)),s.duration=r?this.toSeconds(r):void 0);const o=this.context.transport.schedule(a=>{this._start(a,t,r)},i);this._scheduled.push(o),this.context.transport.state==="started"&&this.context.transport.getSecondsAtTime(this.immediate())>i&&this._syncedStart(this.now(),this.context.transport.seconds)}else ML(this.context),this._start(i,t,r);return this}stop(e){let t=Is(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(t=this._clampToCurrentTime(t),this._state.getValueAtTime(t)==="started"||Wt(this._state.getNextState("started",t))){if(this.log("stop",t),!this._synced)this._stop(t);else{const r=this.context.transport.schedule(this._stop.bind(this),t);this._scheduled.push(r)}this._state.cancel(t),this._state.setStateAtTime("stopped",t)}return this}restart(e,t,r){return e=this.toSeconds(e),this._state.getValueAtTime(e)==="started"&&(this._state.cancel(e),this._restart(e,t,r)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(e,t)=>{if(Nf(t,0)){const r=this._state.get(t);if(r&&r.state==="started"&&r.time!==t){const i=t-this.toSeconds(r.time);let s;r.duration&&(s=this.toSeconds(r.duration)-i),this._start(e,this.toSeconds(r.offset)+i,s)}}},this._syncedStop=e=>{const t=this.context.transport.getSecondsAtTime(Math.max(e-this.sampleTime,0));this._state.getValueAtTime(t)==="started"&&this._stop(e)},this.context.transport.on("start",this._syncedStart),this.context.transport.on("loopStart",this._syncedStart),this.context.transport.on("stop",this._syncedStop),this.context.transport.on("pause",this._syncedStop),this.context.transport.on("loopEnd",this._syncedStop)),this}unsync(){return this._synced&&(this.context.transport.off("stop",this._syncedStop),this.context.transport.off("pause",this._syncedStop),this.context.transport.off("loopEnd",this._syncedStop),this.context.transport.off("start",this._syncedStart),this.context.transport.off("loopStart",this._syncedStart)),this._synced=!1,this._scheduled.forEach(e=>this.context.transport.clear(e)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=En,this.unsync(),this._volume.dispose(),this._state.dispose(),this}}class rm extends Of{constructor(){const e=at(rm.getDefaults(),arguments,["url","onload"]);super(e),this.name="ToneBufferSource",this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1,Io(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new Xt({context:this.context,param:this._source.playbackRate,units:"positive",value:e.playbackRate}),this.loop=e.loop,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this._buffer=new An(e.url,e.onload,e.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(Of.getDefaults(),{url:new An,loop:!1,loopEnd:0,loopStart:0,onload:En,onerror:En,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e}get curve(){return this._curve}set curve(e){this._curve=e}start(e,t,r,i=1){Tt(this.buffer.loaded,"buffer is either not set or not loaded");const s=this.toSeconds(e);this._startGain(s,i),this.loop?t=ga(t,this.loopStart):t=ga(t,0);let o=Math.max(this.toSeconds(t),0);if(this.loop){const a=this.toSeconds(this.loopEnd)||this.buffer.duration,c=this.toSeconds(this.loopStart),l=a-c;IE(o,a)&&(o=(o-c)%l+c),xo(o,this.buffer.duration)&&(o=0)}if(this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,I_(o,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(s,o)),Wt(r)){let a=this.toSeconds(r);a=Math.max(a,0),this.stop(s+a)}return this}_stopSource(e){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(e)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(e){this._source.loopStart=this.toSeconds(e)}get loopEnd(){return this._source.loopEnd}set loopEnd(e){this._source.loopEnd=this.toSeconds(e)}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._source.loop}set loop(e){this._source.loop=e,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}}class Pf extends wi{constructor(){const e=at(Pf.getDefaults(),arguments,["type"]);super(e),this.name="Noise",this._source=null,this._playbackRate=e.playbackRate,this.type=e.type,this._fadeIn=e.fadeIn,this._fadeOut=e.fadeOut}static getDefaults(){return Object.assign(wi.getDefaults(),{fadeIn:0,fadeOut:0,playbackRate:1,type:"white"})}get type(){return this._type}set type(e){if(Tt(e in n2,"Noise: invalid type: "+e),this._type!==e&&(this._type=e,this.state==="started")){const t=this.now();this._stop(t),this._start(t)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._source&&(this._source.playbackRate.value=e)}_start(e){const t=n2[this._type];this._source=new rm({url:t,context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,loop:!0,onended:()=>this.onstop(this),playbackRate:this._playbackRate}).connect(this.output),this._source.start(this.toSeconds(e),Math.random()*(t.duration-.001))}_stop(e){this._source&&(this._source.stop(this.toSeconds(e)),this._source=null)}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e,this._source&&(this._source.fadeIn=this._fadeIn)}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e,this._source&&(this._source.fadeOut=this._fadeOut)}_restart(e){this._stop(e),this._start(e)}dispose(){return super.dispose(),this._source&&this._source.disconnect(),this}}const Vh=44100*5,LS=2,ec={brown:null,pink:null,white:null},n2={get brown(){if(!ec.brown){const n=[];for(let e=0;ethis.onstop(this)});this._oscillator=r,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.start(t)}_stop(e){const t=this.toSeconds(e);this._oscillator&&this._oscillator.stop(t)}_restart(e){const t=this.toSeconds(e);return this.log("restart",t),this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(t),this}syncFrequency(){return this.context.transport.syncSignal(this.frequency),this}unsyncFrequency(){return this.context.transport.unsyncSignal(this.frequency),this}_getCachedPeriodicWave(){if(this._type==="custom")return rr._periodicWaveCache.find(t=>t.phase===this._phase&&$7(t.partials,this._partials));{const e=rr._periodicWaveCache.find(t=>t.type===this._type&&t.phase===this._phase);return this._partialCount=e?e.partialCount:this._partialCount,e}}get type(){return this._type}set type(e){this._type=e;const t=["sine","square","sawtooth","triangle"].indexOf(e)!==-1;if(this._phase===0&&t)this._wave=void 0,this._partialCount=0,this._oscillator!==null&&(this._oscillator.type=e);else{const r=this._getCachedPeriodicWave();if(Wt(r)){const{partials:i,wave:s}=r;this._wave=s,this._partials=i,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave)}else{const[i,s]=this._getRealImaginary(e,this._phase),o=this.context.createPeriodicWave(i,s);this._wave=o,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave),rr._periodicWaveCache.push({imag:s,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:i,type:this._type,wave:this._wave}),rr._periodicWaveCache.length>100&&rr._periodicWaveCache.shift()}}}get baseType(){return this._type.replace(this.partialCount.toString(),"")}set baseType(e){this.partialCount&&this._type!=="custom"&&e!=="custom"?this.type=e+this.partialCount:this.type=e}get partialCount(){return this._partialCount}set partialCount(e){Ea(e,0);let t=this._type;const r=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(this._type);if(r&&(t=r[1]),this._type!=="custom")e===0?this.type=t:this.type=t+e.toString();else{const i=new Float32Array(e);this._partials.forEach((s,o)=>i[o]=s),this._partials=Array.from(i),this.type=this._type}}_getRealImaginary(e,t){let i=2048;const s=new Float32Array(i),o=new Float32Array(i);let a=1;if(e==="custom"){if(a=this._partials.length+1,this._partialCount=this._partials.length,i=a,this._partials.length===0)return[s,o]}else{const c=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(e);c?(a=parseInt(c[2],10)+1,this._partialCount=parseInt(c[2],10),e=c[1],a=Math.max(a,2),i=a):this._partialCount=0,this._partials=[]}for(let c=1;c>1&1?-1:1):u=0,this._partials[c-1]=u;break;case"custom":u=this._partials[c-1];break;default:throw new TypeError("Oscillator: invalid type: "+e)}u!==0?(s[c]=-u*Math.sin(t*c),o[c]=u*Math.cos(t*c)):(s[c]=0,o[c]=0)}return[s,o]}_inverseFFT(e,t,r){let i=0;const s=e.length;for(let o=0;o(e+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class zu extends yn{constructor(){const e=at(zu.getDefaults(),arguments,["value"]);super(e),this.name="Multiply",this.override=!1,this._mult=this.input=this.output=new jt({context:this.context,minValue:e.minValue,maxValue:e.maxValue}),this.factor=this._param=this._mult.gain,this.factor.setValueAtTime(e.value,0)}static getDefaults(){return Object.assign(yn.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}}class Vv extends wi{constructor(){const e=at(Vv.getDefaults(),arguments,["frequency","type","modulationType"]);super(e),this.name="AMOscillator",this._modulationScale=new FL({context:this.context}),this._modulationNode=new jt({context:this.context}),this._carrier=new rr({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase,type:e.type}),this.frequency=this._carrier.frequency,this.detune=this._carrier.detune,this._modulator=new rr({context:this.context,phase:e.phase,type:e.modulationType}),this.harmonicity=new zu({context:this.context,units:"positive",value:e.harmonicity}),this.frequency.chain(this.harmonicity,this._modulator.frequency),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output),Zt(this,["frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(rr.getDefaults(),{harmonicity:1,modulationType:"square"})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){this._modulator.restart(e),this._carrier.restart(e)}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return nh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this._modulationScale.dispose(),this}}class Hv extends wi{constructor(){const e=at(Hv.getDefaults(),arguments,["frequency","type","modulationType"]);super(e),this.name="FMOscillator",this._modulationNode=new jt({context:this.context,gain:0}),this._carrier=new rr({context:this.context,detune:e.detune,frequency:0,onstop:()=>this.onstop(this),phase:e.phase,type:e.type}),this.detune=this._carrier.detune,this.frequency=new yn({context:this.context,units:"frequency",value:e.frequency}),this._modulator=new rr({context:this.context,phase:e.phase,type:e.modulationType}),this.harmonicity=new zu({context:this.context,units:"positive",value:e.harmonicity}),this.modulationIndex=new zu({context:this.context,units:"positive",value:e.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output),this.detune.connect(this._modulator.detune),Zt(this,["modulationIndex","frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(rr.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:"square"})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){return this._modulator.restart(e),this._carrier.restart(e),this}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return nh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}}class im extends wi{constructor(){const e=at(im.getDefaults(),arguments,["frequency","width"]);super(e),this.name="PulseOscillator",this._widthGate=new jt({context:this.context,gain:0}),this._thresh=new th({context:this.context,mapping:t=>t<=0?-1:1}),this.width=new yn({context:this.context,units:"audioRange",value:e.width}),this._triangle=new rr({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase,type:"triangle"}),this.frequency=this._triangle.frequency,this.detune=this._triangle.detune,this._triangle.chain(this._thresh,this.output),this.width.chain(this._widthGate,this._thresh),Zt(this,["width","frequency","detune"])}static getDefaults(){return Object.assign(wi.getDefaults(),{detune:0,frequency:440,phase:0,type:"pulse",width:.2})}_start(e){e=this.toSeconds(e),this._triangle.start(e),this._widthGate.gain.setValueAtTime(1,e)}_stop(e){e=this.toSeconds(e),this._triangle.stop(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(0,e)}_restart(e){this._triangle.restart(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(1,e)}get phase(){return this._triangle.phase}set phase(e){this._triangle.phase=e}get type(){return"pulse"}get baseType(){return"pulse"}get partials(){return[]}get partialCount(){return 0}set carrierType(e){this._triangle.type=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return nh(this,e)})}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}}class Gv extends wi{constructor(){const e=at(Gv.getDefaults(),arguments,["frequency","type","spread"]);super(e),this.name="FatOscillator",this._oscillators=[],this.frequency=new yn({context:this.context,units:"frequency",value:e.frequency}),this.detune=new yn({context:this.context,units:"cents",value:e.detune}),this._spread=e.spread,this._type=e.type,this._phase=e.phase,this._partials=e.partials,this._partialCount=e.partialCount,this.count=e.count,Zt(this,["frequency","detune"])}static getDefaults(){return Object.assign(rr.getDefaults(),{count:3,spread:20,type:"sawtooth"})}_start(e){e=this.toSeconds(e),this._forEach(t=>t.start(e))}_stop(e){e=this.toSeconds(e),this._forEach(t=>t.stop(e))}_restart(e){this._forEach(t=>t.restart(e))}_forEach(e){for(let t=0;tt.type=e)}get spread(){return this._spread}set spread(e){if(this._spread=e,this._oscillators.length>1){const t=-e/2,r=e/(this._oscillators.length-1);this._forEach((i,s)=>i.detune.value=t+r*s)}}get count(){return this._oscillators.length}set count(e){if(Ea(e,1),this._oscillators.length!==e){this._forEach(t=>t.dispose()),this._oscillators=[];for(let t=0;tthis.onstop(this):En});this.type==="custom"&&(r.partials=this._partials),this.frequency.connect(r.frequency),this.detune.connect(r.detune),r.detune.overridden=!1,r.connect(this.output),this._oscillators[t]=r}this.spread=this._spread,this.state==="started"&&this._forEach(t=>t.start())}}get phase(){return this._phase}set phase(e){this._phase=e,this._forEach((t,r)=>t.phase=this._phase+r/this.count*360)}get baseType(){return this._oscillators[0].baseType}set baseType(e){this._forEach(t=>t.baseType=e),this._type=this._oscillators[0].type}get partials(){return this._oscillators[0].partials}set partials(e){this._partials=e,this._partialCount=this._partials.length,e.length&&(this._type="custom",this._forEach(t=>t.partials=e))}get partialCount(){return this._oscillators[0].partialCount}set partialCount(e){this._partialCount=e,this._forEach(t=>t.partialCount=e),this._type=this._oscillators[0].type}asArray(){return _r(this,arguments,void 0,function*(e=1024){return nh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(e=>e.dispose()),this}}class Wv extends wi{constructor(){const e=at(Wv.getDefaults(),arguments,["frequency","modulationFrequency"]);super(e),this.name="PWMOscillator",this.sourceType="pwm",this._scale=new zu({context:this.context,value:2}),this._pulse=new im({context:this.context,frequency:e.modulationFrequency}),this._pulse.carrierType="sine",this.modulationFrequency=this._pulse.frequency,this._modulator=new rr({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase}),this.frequency=this._modulator.frequency,this.detune=this._modulator.detune,this._modulator.chain(this._scale,this._pulse.width),this._pulse.connect(this.output),Zt(this,["modulationFrequency","frequency","detune"])}static getDefaults(){return Object.assign(wi.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:"pwm"})}_start(e){e=this.toSeconds(e),this._modulator.start(e),this._pulse.start(e)}_stop(e){e=this.toSeconds(e),this._modulator.stop(e),this._pulse.stop(e)}_restart(e){this._modulator.restart(e),this._pulse.restart(e)}get type(){return"pwm"}get baseType(){return"pwm"}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(e){this._modulator.phase=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return nh(this,e)})}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}}const r2={am:Vv,fat:Gv,fm:Hv,oscillator:rr,pulse:im,pwm:Wv};class O_ extends wi{constructor(){const e=at(O_.getDefaults(),arguments,["frequency","type"]);super(e),this.name="OmniOscillator",this.frequency=new yn({context:this.context,units:"frequency",value:e.frequency}),this.detune=new yn({context:this.context,units:"cents",value:e.detune}),Zt(this,["frequency","detune"]),this.set(e)}static getDefaults(){return Object.assign(rr.getDefaults(),Hv.getDefaults(),Vv.getDefaults(),Gv.getDefaults(),im.getDefaults(),Wv.getDefaults())}_start(e){this._oscillator.start(e)}_stop(e){this._oscillator.stop(e)}_restart(e){return this._oscillator.restart(e),this}get type(){let e="";return["am","fm","fat"].some(t=>this._sourceType===t)&&(e=this._sourceType),e+this._oscillator.type}set type(e){e.substr(0,2)==="fm"?(this._createNewOscillator("fm"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,2)==="am"?(this._createNewOscillator("am"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,3)==="fat"?(this._createNewOscillator("fat"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(3)):e==="pwm"?(this._createNewOscillator("pwm"),this._oscillator=this._oscillator):e==="pulse"?this._createNewOscillator("pulse"):(this._createNewOscillator("oscillator"),this._oscillator=this._oscillator,this._oscillator.type=e)}get partials(){return this._oscillator.partials}set partials(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&(this._oscillator.partials=e)}get partialCount(){return this._oscillator.partialCount}set partialCount(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&(this._oscillator.partialCount=e)}set(e){return Reflect.has(e,"type")&&e.type&&(this.type=e.type),super.set(e),this}_createNewOscillator(e){if(e!==this._sourceType){this._sourceType=e;const t=r2[e],r=this.now();if(this._oscillator){const i=this._oscillator;i.stop(r),this.context.setTimeout(()=>i.dispose(),this.blockTime)}this._oscillator=new t({context:this.context}),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.connect(this.output),this._oscillator.onstop=()=>this.onstop(this),this.state==="started"&&this._oscillator.start(r)}}get phase(){return this._oscillator.phase}set phase(e){this._oscillator.phase=e}get sourceType(){return this._sourceType}set sourceType(e){let t="sine";this._oscillator.type!=="pwm"&&this._oscillator.type!=="pulse"&&(t=this._oscillator.type),e==="fm"?this.type="fm"+t:e==="am"?this.type="am"+t:e==="fat"?this.type="fat"+t:e==="oscillator"?this.type=t:e==="pulse"?this.type="pulse":e==="pwm"&&(this.type="pwm")}_getOscType(e,t){return e instanceof r2[t]}get baseType(){return this._oscillator.baseType}set baseType(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&e!=="pulse"&&e!=="pwm"&&(this._oscillator.baseType=e)}get width(){if(this._getOscType(this._oscillator,"pulse"))return this._oscillator.width}get count(){if(this._getOscType(this._oscillator,"fat"))return this._oscillator.count}set count(e){this._getOscType(this._oscillator,"fat")&&ko(e)&&(this._oscillator.count=e)}get spread(){if(this._getOscType(this._oscillator,"fat"))return this._oscillator.spread}set spread(e){this._getOscType(this._oscillator,"fat")&&ko(e)&&(this._oscillator.spread=e)}get modulationType(){if(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))return this._oscillator.modulationType}set modulationType(e){(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))&&bc(e)&&(this._oscillator.modulationType=e)}get modulationIndex(){if(this._getOscType(this._oscillator,"fm"))return this._oscillator.modulationIndex}get harmonicity(){if(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))return this._oscillator.harmonicity}get modulationFrequency(){if(this._getOscType(this._oscillator,"pwm"))return this._oscillator.modulationFrequency}asArray(){return _r(this,arguments,void 0,function*(e=1024){return nh(this,e)})}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}}class VT extends yn{constructor(){super(at(VT.getDefaults(),arguments,["value"])),this.override=!1,this.name="Add",this._sum=new jt({context:this.context}),this.input=this._sum,this.output=this._sum,this.addend=this._param,Bu(this._constantSource,this._sum)}static getDefaults(){return Object.assign(yn.getDefaults(),{value:0})}dispose(){return super.dispose(),this._sum.dispose(),this}}class HT extends wa{constructor(){const e=at(HT.getDefaults(),arguments,["min","max"]);super(e),this.name="Scale",this._mult=this.input=new zu({context:this.context,value:e.max-e.min}),this._add=this.output=new VT({context:this.context,value:e.min}),this._min=e.min,this._max=e.max,this.input.connect(this.output)}static getDefaults(){return Object.assign(wa.getDefaults(),{max:1,min:0})}get min(){return this._min}set min(e){this._min=e,this._setRange()}get max(){return this._max}set max(e){this._max=e,this._setRange()}_setRange(){this._add.value=this._min,this._mult.value=this._max-this._min}dispose(){return super.dispose(),this._add.dispose(),this._mult.dispose(),this}}class GT extends wa{constructor(){super(at(GT.getDefaults(),arguments)),this.name="Zero",this._gain=new jt({context:this.context}),this.output=this._gain,this.input=void 0,Io(this.context.getConstant(0),this._gain)}dispose(){return super.dispose(),UL(this.context.getConstant(0),this._gain),this}}class Vu extends ht{constructor(){const e=at(Vu.getDefaults(),arguments,["frequency","min","max"]);super(e),this.name="LFO",this._stoppedValue=0,this._units="number",this.convert=!0,this._fromType=Xt.prototype._fromType,this._toType=Xt.prototype._toType,this._is=Xt.prototype._is,this._clampValue=Xt.prototype._clampValue,this._oscillator=new rr(e),this.frequency=this._oscillator.frequency,this._amplitudeGain=new jt({context:this.context,gain:e.amplitude,units:"normalRange"}),this.amplitude=this._amplitudeGain.gain,this._stoppedSignal=new yn({context:this.context,units:"audioRange",value:0}),this._zeros=new GT({context:this.context}),this._a2g=new FL({context:this.context}),this._scaler=this.output=new HT({context:this.context,max:e.max,min:e.min}),this.units=e.units,this.min=e.min,this.max=e.max,this._oscillator.chain(this._amplitudeGain,this._a2g,this._scaler),this._zeros.connect(this._a2g),this._stoppedSignal.connect(this._a2g),Zt(this,["amplitude","frequency"]),this.phase=e.phase}static getDefaults(){return Object.assign(rr.getDefaults(),{amplitude:1,frequency:"4n",max:1,min:0,type:"sine",units:"number"})}start(e){return e=this.toSeconds(e),this._stoppedSignal.setValueAtTime(0,e),this._oscillator.start(e),this}stop(e){return e=this.toSeconds(e),this._stoppedSignal.setValueAtTime(this._stoppedValue,e),this._oscillator.stop(e),this}sync(){return this._oscillator.sync(),this._oscillator.syncFrequency(),this}unsync(){return this._oscillator.unsync(),this._oscillator.unsyncFrequency(),this}_setStoppedValue(){this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get min(){return this._toType(this._scaler.min)}set min(e){e=this._fromType(e),this._scaler.min=e}get max(){return this._toType(this._scaler.max)}set max(e){e=this._fromType(e),this._scaler.max=e}get type(){return this._oscillator.type}set type(e){this._oscillator.type=e,this._setStoppedValue()}get partials(){return this._oscillator.partials}set partials(e){this._oscillator.partials=e,this._setStoppedValue()}get phase(){return this._oscillator.phase}set phase(e){this._oscillator.phase=e,this._setStoppedValue()}get units(){return this._units}set units(e){const t=this.min,r=this.max;this._units=e,this.min=t,this.max=r}get state(){return this._oscillator.state}connect(e,t,r){return(e instanceof Xt||e instanceof yn)&&(this.convert=e.convert,this.units=e.units),Fv(this,e,t,r),this}dispose(){return super.dispose(),this._oscillator.dispose(),this._stoppedSignal.dispose(),this._zeros.dispose(),this._scaler.dispose(),this._a2g.dispose(),this._amplitudeGain.dispose(),this.amplitude.dispose(),this}}function BL(n,e=1/0){const t=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return t.get(this)},set:function(s){Ea(s,n,e),t.set(this,s)}})}}function Uc(n,e=1/0){const t=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return t.get(this)},set:function(s){Ea(this.toSeconds(s),n,e),t.set(this,s)}})}}class jv extends wi{constructor(){const e=at(jv.getDefaults(),arguments,["url","onload"]);super(e),this.name="Player",this._activeSources=new Set,this._buffer=new An({onload:this._onload.bind(this,e.onload),onerror:e.onerror,reverse:e.reverse,url:e.url}),this.autostart=e.autostart,this._loop=e.loop,this._loopStart=e.loopStart,this._loopEnd=e.loopEnd,this._playbackRate=e.playbackRate,this.fadeIn=e.fadeIn,this.fadeOut=e.fadeOut}static getDefaults(){return Object.assign(wi.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:En,onerror:En,playbackRate:1,reverse:!1})}load(e){return _r(this,void 0,void 0,function*(){return yield this._buffer.load(e),this._onload(),this})}_onload(e=En){e(),this.autostart&&this.start()}_onSourceEnd(e){this.onstop(this),this._activeSources.delete(e),this._activeSources.size===0&&!this._synced&&this._state.getValueAtTime(this.now())==="started"&&(this._state.cancel(this.now()),this._state.setStateAtTime("stopped",this.now()))}start(e,t,r){return super.start(e,t,r),this}_start(e,t,r){this._loop?t=ga(t,this._loopStart):t=ga(t,0);const i=this.toSeconds(t),s=r;r=ga(r,Math.max(this._buffer.duration-i,0));let o=this.toSeconds(r);o=o/this._playbackRate,e=this.toSeconds(e);const a=new rm({url:this._buffer,context:this.context,fadeIn:this.fadeIn,fadeOut:this.fadeOut,loop:this._loop,loopEnd:this._loopEnd,loopStart:this._loopStart,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate}).connect(this.output);!this._loop&&!this._synced&&(this._state.cancel(e+o),this._state.setStateAtTime("stopped",e+o,{implicitEnd:!0})),this._activeSources.add(a),this._loop&&Is(s)?a.start(e,i):a.start(e,i,o-this.toSeconds(this.fadeOut))}_stop(e){const t=this.toSeconds(e);this._activeSources.forEach(r=>r.stop(t))}restart(e,t,r){return super.restart(e,t,r),this}_restart(e,t,r){var i;(i=[...this._activeSources].pop())===null||i===void 0||i.stop(e),this._start(e,t,r)}seek(e,t){const r=this.toSeconds(t);if(this._state.getValueAtTime(r)==="started"){const i=this.toSeconds(e);this._stop(r),this._start(r,i)}return this}setLoopPoints(e,t){return this.loopStart=e,this.loopEnd=t,this}get loopStart(){return this._loopStart}set loopStart(e){this._loopStart=e,this.buffer.loaded&&Ea(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(t=>{t.loopStart=e})}get loopEnd(){return this._loopEnd}set loopEnd(e){this._loopEnd=e,this.buffer.loaded&&Ea(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(t=>{t.loopEnd=e})}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._loop}set loop(e){if(this._loop!==e&&(this._loop=e,this._activeSources.forEach(t=>{t.loop=e}),e)){const t=this._state.getNextState("stopped",this.now());t&&this._state.cancel(t.time)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e;const t=this.now(),r=this._state.getNextState("stopped",t);r&&r.implicitEnd&&(this._state.cancel(r.time),this._activeSources.forEach(i=>i.cancelStop())),this._activeSources.forEach(i=>{i.playbackRate.setValueAtTime(e,t)})}get reverse(){return this._buffer.reverse}set reverse(e){this._buffer.reverse=e}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(e=>e.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}}Bo([Uc(0)],jv.prototype,"fadeIn",void 0);Bo([Uc(0)],jv.prototype,"fadeOut",void 0);class hX extends wa{constructor(){super(...arguments),this.name="GainToAudio",this._norm=new th({context:this.context,mapping:e=>Math.abs(e)*2-1}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class Fc extends ht{constructor(){const e=at(Fc.getDefaults(),arguments,["attack","decay","sustain","release"]);super(e),this.name="Envelope",this._sig=new yn({context:this.context,value:0}),this.output=this._sig,this.input=void 0,this.attack=e.attack,this.decay=e.decay,this.sustain=e.sustain,this.release=e.release,this.attackCurve=e.attackCurve,this.releaseCurve=e.releaseCurve,this.decayCurve=e.decayCurve}static getDefaults(){return Object.assign(ht.getDefaults(),{attack:.01,attackCurve:"linear",decay:.1,decayCurve:"exponential",release:1,releaseCurve:"exponential",sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(e,t){if(bc(e))return e;{let r;for(r in c0)if(c0[r][t]===e)return r;return e}}_setCurve(e,t,r){if(bc(r)&&Reflect.has(c0,r)){const i=c0[r];yl(i)?e!=="_decayCurve"&&(this[e]=i[t]):this[e]=i}else if(as(r)&&e!=="_decayCurve")this[e]=r;else throw new Error("Envelope: invalid curve: "+r)}get attackCurve(){return this._getCurve(this._attackCurve,"In")}set attackCurve(e){this._setCurve("_attackCurve","In",e)}get releaseCurve(){return this._getCurve(this._releaseCurve,"Out")}set releaseCurve(e){this._setCurve("_releaseCurve","Out",e)}get decayCurve(){return this._getCurve(this._decayCurve,"Out")}set decayCurve(e){this._setCurve("_decayCurve","Out",e)}triggerAttack(e,t=1){this.log("triggerAttack",e,t),e=this.toSeconds(e);let i=this.toSeconds(this.attack);const s=this.toSeconds(this.decay),o=this.getValueAtTime(e);if(o>0){const a=1/i;i=(1-o)/a}if(i0){const r=this.toSeconds(this.release);r{let e,t;const r=[];for(e=0;e<128;e++)r[e]=Math.sin(e/127*(Math.PI/2));const i=[],s=6.4;for(e=0;e<127;e++){t=e/127;const p=Math.sin(t*(Math.PI*2)*s-Math.PI/2)+1;i[e]=p/10+t*.83}i[127]=1;const o=[],a=5;for(e=0;e<128;e++)o[e]=Math.ceil(e/127*a)/a;const c=[];for(e=0;e<128;e++)t=e/127,c[e]=.5*(1-Math.cos(Math.PI*t));const l=[];for(e=0;e<128;e++){t=e/127;const p=Math.pow(t,3)*4+.2,m=Math.cos(p*Math.PI*2*t);l[e]=Math.abs(m*(1-t))}function u(p){const m=new Array(p.length);for(let g=0;gthis._original_triggerRelease(t),this._volume=this.output=new Al({context:this.context,volume:e.volume}),this.volume=this._volume.volume,Zt(this,"volume")}static getDefaults(){return Object.assign(ht.getDefaults(),{volume:0})}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",0),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}_syncState(){let e=!1;return this._synced||(this._synced=!0,e=!0),e}_syncMethod(e,t){const r=this["_original_"+e]=this[e];this[e]=(...i)=>{const s=i[t],o=this.context.transport.schedule(a=>{i[t]=a,r.apply(this,i)},s);this._scheduledEvents.push(o)}}unsync(){return this._scheduledEvents.forEach(e=>this.context.transport.clear(e)),this._scheduledEvents=[],this._synced&&(this._synced=!1,this.triggerAttack=this._original_triggerAttack,this.triggerRelease=this._original_triggerRelease,this.context.transport.off("stop",this._syncedRelease),this.context.transport.off("pause",this._syncedRelease),this.context.transport.off("loopEnd",this._syncedRelease)),this}triggerAttackRelease(e,t,r,i){const s=this.toSeconds(r),o=this.toSeconds(t);return this.triggerAttack(e,s,i),this.triggerRelease(s+o),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}}class Hu extends Ta{constructor(){const e=at(Hu.getDefaults(),arguments);super(e),this.portamento=e.portamento,this.onsilence=e.onsilence}static getDefaults(){return Object.assign(Ta.getDefaults(),{detune:0,onsilence:En,portamento:0})}triggerAttack(e,t,r=1){this.log("triggerAttack",e,t,r);const i=this.toSeconds(t);return this._triggerEnvelopeAttack(i,r),this.setNote(e,i),this}triggerRelease(e){this.log("triggerRelease",e);const t=this.toSeconds(e);return this._triggerEnvelopeRelease(t),this}setNote(e,t){const r=this.toSeconds(t),i=e instanceof rs?e.toFrequency():e;if(this.portamento>0&&this.getLevelAtTime(r)>.05){const s=this.toSeconds(this.portamento);this.frequency.exponentialRampTo(i,s,r)}else this.frequency.setValueAtTime(i,r);return this}}Bo([Uc(0)],Hu.prototype,"portamento",void 0);class $v extends Fc{constructor(){super(at($v.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="AmplitudeEnvelope",this._gainNode=new jt({context:this.context,gain:0}),this.output=this._gainNode,this.input=this._gainNode,this._sig.connect(this._gainNode.gain),this.output=this._gainNode,this.input=this._gainNode}dispose(){return super.dispose(),this._gainNode.dispose(),this}}class Ni extends Hu{constructor(){const e=at(Ni.getDefaults(),arguments);super(e),this.name="Synth",this.oscillator=new O_(Object.assign({context:this.context,detune:e.detune,onstop:()=>this.onsilence(this)},e.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new $v(Object.assign({context:this.context},e.envelope)),this.oscillator.chain(this.envelope,this.output),Zt(this,["oscillator","frequency","detune","envelope"])}static getDefaults(){return Object.assign(Hu.getDefaults(),{envelope:Object.assign(vp(Fc.getDefaults(),Object.keys(ht.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(vp(O_.getDefaults(),[...Object.keys(wi.getDefaults()),"frequency","detune"]),{type:"triangle"})})}_triggerEnvelopeAttack(e,t){if(this.envelope.triggerAttack(e,t),this.oscillator.start(e),this.envelope.sustain===0){const r=this.toSeconds(this.envelope.attack),i=this.toSeconds(this.envelope.decay);this.oscillator.stop(e+r+i)}}_triggerEnvelopeRelease(e){this.envelope.triggerRelease(e),this.oscillator.stop(e+this.toSeconds(this.envelope.release))}getLevelAtTime(e){return e=this.toSeconds(e),this.envelope.getValueAtTime(e)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}}class L_ extends ht{constructor(){const e=at(L_.getDefaults(),arguments,["frequency","type"]);super(e),this.name="BiquadFilter",this._filter=this.context.createBiquadFilter(),this.input=this.output=this._filter,this.Q=new Xt({context:this.context,units:"number",value:e.Q,param:this._filter.Q}),this.frequency=new Xt({context:this.context,units:"frequency",value:e.frequency,param:this._filter.frequency}),this.detune=new Xt({context:this.context,units:"cents",value:e.detune,param:this._filter.detune}),this.gain=new Xt({context:this.context,units:"decibels",convert:!1,value:e.gain,param:this._filter.gain}),this.type=e.type}static getDefaults(){return Object.assign(ht.getDefaults(),{Q:1,type:"lowpass",frequency:350,detune:0,gain:0})}get type(){return this._filter.type}set type(e){Tt(["lowpass","highpass","bandpass","lowshelf","highshelf","notch","allpass","peaking"].indexOf(e)!==-1,`Invalid filter type: ${e}`),this._filter.type=e}getFrequencyResponse(e=128){const t=new Float32Array(e);for(let o=0;or.type=e)}get rolloff(){return this._rolloff}set rolloff(e){const t=ko(e)?e:parseInt(e,10),r=[-12,-24,-48,-96];let i=r.indexOf(t);Tt(i!==-1,`rolloff can only be ${r.join(", ")}`),i+=1,this._rolloff=t,this.input.disconnect(),this._filters.forEach(s=>s.disconnect()),this._filters=new Array(i);for(let s=0;s1);return this._filters.forEach(()=>{t.getFrequencyResponse(e).forEach((s,o)=>r[o]*=s)}),t.dispose(),r}dispose(){return super.dispose(),this._filters.forEach(e=>{e.dispose()}),tm(this,["detune","frequency","gain","Q"]),this.frequency.dispose(),this.Q.dispose(),this.detune.dispose(),this.gain.dispose(),this}}class sm extends Ni{constructor(){const e=at(sm.getDefaults(),arguments);super(e),this.name="MembraneSynth",this.portamento=0,this.pitchDecay=e.pitchDecay,this.octaves=e.octaves,Zt(this,["oscillator","envelope"])}static getDefaults(){return Iu(Hu.getDefaults(),Ni.getDefaults(),{envelope:{attack:.001,attackCurve:"exponential",decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:"sine"},pitchDecay:.05})}setNote(e,t){const r=this.toSeconds(t),i=this.toFrequency(e instanceof rs?e.toFrequency():e),s=i*this.octaves;return this.oscillator.frequency.setValueAtTime(s,r),this.oscillator.frequency.exponentialRampToValueAtTime(i,r+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}}Bo([BL(0)],sm.prototype,"octaves",void 0);Bo([Uc(0)],sm.prototype,"pitchDecay",void 0);class of extends Ta{constructor(){const e=at(of.getDefaults(),arguments);super(e),this.name="NoiseSynth",this.noise=new Pf(Object.assign({context:this.context},e.noise)),this.envelope=new $v(Object.assign({context:this.context},e.envelope)),this.noise.chain(this.envelope,this.output)}static getDefaults(){return Object.assign(Ta.getDefaults(),{envelope:Object.assign(vp(Fc.getDefaults(),Object.keys(ht.getDefaults())),{decay:.1,sustain:0}),noise:Object.assign(vp(Pf.getDefaults(),Object.keys(wi.getDefaults())),{type:"white"})})}triggerAttack(e,t=1){return e=this.toSeconds(e),this.envelope.triggerAttack(e,t),this.noise.start(e),this.envelope.sustain===0&&this.noise.stop(e+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay)),this}triggerRelease(e){return e=this.toSeconds(e),this.envelope.triggerRelease(e),this.noise.stop(e+this.toSeconds(this.envelope.release)),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",0),this._syncMethod("triggerRelease",0)),this}triggerAttackRelease(e,t,r=1){return t=this.toSeconds(t),e=this.toSeconds(e),this.triggerAttack(t,r),this.triggerRelease(t+e),this}dispose(){return super.dispose(),this.noise.dispose(),this.envelope.dispose(),this}}const zL=new Set;function WT(n){zL.add(n)}function VL(n,e){const t=`registerProcessor("${n}", ${e})`;zL.add(t)}const fX=` - /** - * The base AudioWorkletProcessor for use in Tone.js. Works with the {@link ToneAudioWorklet}. - */ - class ToneAudioWorkletProcessor extends AudioWorkletProcessor { - - constructor(options) { - - super(options); - /** - * If the processor was disposed or not. Keep alive until it's disposed. - */ - this.disposed = false; - /** - * The number of samples in the processing block - */ - this.blockSize = 128; - /** - * the sample rate - */ - this.sampleRate = sampleRate; - - this.port.onmessage = (event) => { - // when it receives a dispose - if (event.data === "dispose") { - this.disposed = true; - } - }; - } - } -`;WT(fX);const dX=` - /** - * Abstract class for a single input/output processor. - * has a 'generate' function which processes one sample at a time - */ - class SingleIOProcessor extends ToneAudioWorkletProcessor { - - constructor(options) { - super(Object.assign(options, { - numberOfInputs: 1, - numberOfOutputs: 1 - })); - /** - * Holds the name of the parameter and a single value of that - * parameter at the current sample - * @type { [name: string]: number } - */ - this.params = {} - } - - /** - * Generate an output sample from the input sample and parameters - * @abstract - * @param input number - * @param channel number - * @param parameters { [name: string]: number } - * @returns number - */ - generate(){} - - /** - * Update the private params object with the - * values of the parameters at the given index - * @param parameters { [name: string]: Float32Array }, - * @param index number - */ - updateParams(parameters, index) { - for (const paramName in parameters) { - const param = parameters[paramName]; - if (param.length > 1) { - this.params[paramName] = parameters[paramName][index]; - } else { - this.params[paramName] = parameters[paramName][0]; - } - } - } - - /** - * Process a single frame of the audio - * @param inputs Float32Array[][] - * @param outputs Float32Array[][] - */ - process(inputs, outputs, parameters) { - const input = inputs[0]; - const output = outputs[0]; - // get the parameter values - const channelCount = Math.max(input && input.length || 0, output.length); - for (let sample = 0; sample < this.blockSize; sample++) { - this.updateParams(parameters, sample); - for (let channel = 0; channel < channelCount; channel++) { - const inputSample = input && input.length ? input[channel][sample] : 0; - output[channel][sample] = this.generate(inputSample, channel, this.params); - } - } - return !this.disposed; - } - }; -`;WT(dX);const pX=` - /** - * A multichannel buffer for use within an AudioWorkletProcessor as a delay line - */ - class DelayLine { - - constructor(size, channels) { - this.buffer = []; - this.writeHead = [] - this.size = size; - - // create the empty channels - for (let i = 0; i < channels; i++) { - this.buffer[i] = new Float32Array(this.size); - this.writeHead[i] = 0; - } - } - - /** - * Push a value onto the end - * @param channel number - * @param value number - */ - push(channel, value) { - this.writeHead[channel] += 1; - if (this.writeHead[channel] > this.size) { - this.writeHead[channel] = 0; - } - this.buffer[channel][this.writeHead[channel]] = value; - } - - /** - * Get the recorded value of the channel given the delay - * @param channel number - * @param delay number delay samples - */ - get(channel, delay) { - let readHead = this.writeHead[channel] - Math.floor(delay); - if (readHead < 0) { - readHead += this.size; - } - return this.buffer[channel][readHead]; - } - } -`;WT(pX);const mX="feedback-comb-filter",gX=` - class FeedbackCombFilterWorklet extends SingleIOProcessor { - - constructor(options) { - super(options); - this.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2); - } - - static get parameterDescriptors() { - return [{ - name: "delayTime", - defaultValue: 0.1, - minValue: 0, - maxValue: 1, - automationRate: "k-rate" - }, { - name: "feedback", - defaultValue: 0.5, - minValue: 0, - maxValue: 0.9999, - automationRate: "k-rate" - }]; - } - - generate(input, channel, parameters) { - const delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate); - this.delayLine.push(channel, input + delayedSample * parameters.feedback); - return delayedSample; - } - } -`;VL(mX,gX);class P_ extends Ta{constructor(){const e=at(P_.getDefaults(),arguments,["voice","options"]);super(e),this.name="PolySynth",this._availableVoices=[],this._activeVoices=[],this._voices=[],this._gcTimeout=-1,this._averageActiveVoices=0,this._syncedRelease=i=>this.releaseAll(i),Tt(!ko(e.voice),"DEPRECATED: The polyphony count is no longer the first argument.");const t=e.voice.getDefaults();this.options=Object.assign(t,e.options),this.voice=e.voice,this.maxPolyphony=e.maxPolyphony,this._dummyVoice=this._getNextAvailableVoice();const r=this._voices.indexOf(this._dummyVoice);this._voices.splice(r,1),this._gcTimeout=this.context.setInterval(this._collectGarbage.bind(this),1)}static getDefaults(){return Object.assign(Ta.getDefaults(),{maxPolyphony:32,options:{},voice:Ni})}get activeVoices(){return this._activeVoices.length}_makeVoiceAvailable(e){this._availableVoices.push(e);const t=this._activeVoices.findIndex(r=>r.voice===e);this._activeVoices.splice(t,1)}_getNextAvailableVoice(){if(this._availableVoices.length)return this._availableVoices.shift();if(this._voices.lengthMath.ceil(this._averageActiveVoices+1)){const e=this._availableVoices.shift(),t=this._voices.indexOf(e);this._voices.splice(t,1),this.context.isOffline||e.dispose()}}_triggerAttack(e,t,r){e.forEach(i=>{const s=new N_(this.context,i).toMidi(),o=this._getNextAvailableVoice();o&&(o.triggerAttack(i,t,r),this._activeVoices.push({midi:s,voice:o,released:!1}),this.log("triggerAttack",i,t))})}_triggerRelease(e,t){e.forEach(r=>{const i=new N_(this.context,r).toMidi(),s=this._activeVoices.find(({midi:o,released:a})=>o===i&&!a);s&&(s.voice.triggerRelease(t),s.released=!0,this.log("triggerRelease",r,t))})}_scheduleEvent(e,t,r,i){Tt(!this.disposed,"Synth was already disposed"),r<=this.now()?e==="attack"?this._triggerAttack(t,r,i):this._triggerRelease(t,r):this.context.setTimeout(()=>{this.disposed||this._scheduleEvent(e,t,r,i)},r-this.now())}triggerAttack(e,t,r){Array.isArray(e)||(e=[e]);const i=this.toSeconds(t);return this._scheduleEvent("attack",e,i,r),this}triggerRelease(e,t){Array.isArray(e)||(e=[e]);const r=this.toSeconds(t);return this._scheduleEvent("release",e,r),this}triggerAttackRelease(e,t,r,i){const s=this.toSeconds(r);if(this.triggerAttack(e,s,i),as(t)){Tt(as(e),"If the duration is an array, the notes must also be an array"),e=e;for(let o=0;o0,"The duration must be greater than 0"),this.triggerRelease(e[o],s+c)}}else{const o=this.toSeconds(t);Tt(o>0,"The duration must be greater than 0"),this.triggerRelease(e,s+o)}return this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}set(e){const t=vp(e,["onsilence","context"]);return this.options=Iu(this.options,t),this._voices.forEach(r=>r.set(t)),this._dummyVoice.set(t),this}get(){return this._dummyVoice.get()}releaseAll(e){const t=this.toSeconds(e);return this._activeVoices.forEach(({voice:r})=>{r.triggerRelease(t)}),this}dispose(){return super.dispose(),this._dummyVoice.dispose(),this._voices.forEach(e=>e.dispose()),this._activeVoices=[],this._availableVoices=[],this.context.clearInterval(this._gcTimeout),this}}class qv extends Ta{constructor(){const e=at(qv.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");super(e),this.name="Sampler",this._activeSources=new Map;const t={};Object.keys(e.urls).forEach(r=>{const i=parseInt(r,10);if(Tt(a0(r)||ko(i)&&isFinite(i),`url key is neither a note or midi pitch: ${r}`),a0(r)){const s=new rs(this.context,r).toMidi();t[s]=e.urls[r]}else ko(i)&&isFinite(i)&&(t[i]=e.urls[i])}),this._buffers=new UT({urls:t,onload:e.onload,baseUrl:e.baseUrl,onerror:e.onerror}),this.attack=e.attack,this.release=e.release,this.curve=e.curve,this._buffers.loaded&&Promise.resolve().then(e.onload)}static getDefaults(){return Object.assign(Ta.getDefaults(),{attack:0,baseUrl:"",curve:"exponential",onload:En,onerror:En,release:.1,urls:{}})}_findClosest(e){let r=0;for(;r<96;){if(this._buffers.has(e+r))return-r;if(this._buffers.has(e-r))return r;r++}throw new Error(`No available buffers for note: ${e}`)}triggerAttack(e,t,r=1){return this.log("triggerAttack",e,t,r),Array.isArray(e)||(e=[e]),e.forEach(i=>{const s=PL(new rs(this.context,i).toFrequency()),o=Math.round(s),a=s-o,c=this._findClosest(o),l=o-c,u=this._buffers.get(l),h=LL(c+a),p=new rm({url:u,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:h}).connect(this.output);p.start(t,0,u.duration/h,r),as(this._activeSources.get(o))||this._activeSources.set(o,[]),this._activeSources.get(o).push(p),p.onended=()=>{if(this._activeSources&&this._activeSources.has(o)){const m=this._activeSources.get(o),g=m.indexOf(p);g!==-1&&m.splice(g,1)}}}),this}triggerRelease(e,t){return this.log("triggerRelease",e,t),Array.isArray(e)||(e=[e]),e.forEach(r=>{const i=new rs(this.context,r).toMidi();if(this._activeSources.has(i)&&this._activeSources.get(i).length){const s=this._activeSources.get(i);t=this.toSeconds(t),s.forEach(o=>{o.stop(t)}),this._activeSources.set(i,[])}}),this}releaseAll(e){const t=this.toSeconds(e);return this._activeSources.forEach(r=>{for(;r.length;)r.shift().stop(t)}),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1)),this}triggerAttackRelease(e,t,r,i=1){const s=this.toSeconds(r);return this.triggerAttack(e,s,i),as(t)?(Tt(as(e),"notes must be an array when duration is array"),e.forEach((o,a)=>{const c=t[Math.min(a,t.length-1)];this.triggerRelease(o,s+this.toSeconds(c))})):this.triggerRelease(e,s+this.toSeconds(t)),this}add(e,t,r){if(Tt(a0(e)||isFinite(e),`note must be a pitch or midi: ${e}`),a0(e)){const i=new rs(this.context,e).toMidi();this._buffers.add(i,t,r)}else this._buffers.add(e,t,r);return this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(e=>{e.forEach(t=>t.dispose())}),this._activeSources.clear(),this}}Bo([Uc(0)],qv.prototype,"attack",void 0);Bo([Uc(0)],qv.prototype,"release",void 0);class af extends xi{constructor(){const e=at(af.getDefaults(),arguments,["callback","value"]);super(e),this.name="ToneEvent",this._state=new nm("stopped"),this._startOffset=0,this._loop=e.loop,this.callback=e.callback,this.value=e.value,this._loopStart=this.toTicks(e.loopStart),this._loopEnd=this.toTicks(e.loopEnd),this._playbackRate=e.playbackRate,this._probability=e.probability,this._humanize=e.humanize,this.mute=e.mute,this._playbackRate=e.playbackRate,this._state.increasing=!0,this._rescheduleEvents()}static getDefaults(){return Object.assign(xi.getDefaults(),{callback:En,humanize:!1,loop:!1,loopEnd:"1m",loopStart:0,mute:!1,playbackRate:1,probability:1,value:null})}_rescheduleEvents(e=-1){this._state.forEachFrom(e,t=>{let r;if(t.state==="started"){t.id!==-1&&this.context.transport.clear(t.id);const i=t.time+Math.round(this.startOffset/this._playbackRate);if(this._loop===!0||ko(this._loop)&&this._loop>1){r=1/0,ko(this._loop)&&(r=this._loop*this._getLoopDuration());const s=this._state.getAfter(i);s!==null&&(r=Math.min(r,s.time-i)),r!==1/0&&(r=new Pr(this.context,r));const o=new Pr(this.context,this._getLoopDuration());t.id=this.context.transport.scheduleRepeat(this._tick.bind(this),o,new Pr(this.context,i),r)}else t.id=this.context.transport.schedule(this._tick.bind(this),new Pr(this.context,i))}})}get state(){return this._state.getValueAtTime(this.context.transport.ticks)}get startOffset(){return this._startOffset}set startOffset(e){this._startOffset=e}get probability(){return this._probability}set probability(e){this._probability=e}get humanize(){return this._humanize}set humanize(e){this._humanize=e}start(e){const t=this.toTicks(e);return this._state.getValueAtTime(t)==="stopped"&&(this._state.add({id:-1,state:"started",time:t}),this._rescheduleEvents(t)),this}stop(e){this.cancel(e);const t=this.toTicks(e);if(this._state.getValueAtTime(t)==="started"){this._state.setStateAtTime("stopped",t,{id:-1});const r=this._state.getBefore(t);let i=t;r!==null&&(i=r.time),this._rescheduleEvents(i)}return this}cancel(e){e=ga(e,-1/0);const t=this.toTicks(e);return this._state.forEachFrom(t,r=>{this.context.transport.clear(r.id)}),this._state.cancel(t),this}_tick(e){const t=this.context.transport.getTicksAtTime(e);if(!this.mute&&this._state.getValueAtTime(t)==="started"){if(this.probability<1&&Math.random()>this.probability)return;if(this.humanize){let r=.02;AL(this.humanize)||(r=this.toSeconds(this.humanize)),e+=(Math.random()*2-1)*r}this.callback(e,this.value)}}_getLoopDuration(){return(this._loopEnd-this._loopStart)/this._playbackRate}get loop(){return this._loop}set loop(e){this._loop=e,this._rescheduleEvents()}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._rescheduleEvents()}get loopEnd(){return new Pr(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._rescheduleEvents()}get loopStart(){return new Pr(this.context,this._loopStart).toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e),this._loop&&this._rescheduleEvents()}get progress(){if(this._loop){const e=this.context.transport.ticks,t=this._state.get(e);if(t!==null&&t.state==="started"){const r=this._getLoopDuration();return(e-t.time)%r/r}else return 0}else return 0}dispose(){return super.dispose(),this.cancel(),this._state.dispose(),this}}class D_ extends af{constructor(){const e=at(D_.getDefaults(),arguments,["callback","events"]);super(e),this.name="Part",this._state=new nm("stopped"),this._events=new Set,this._state.increasing=!0,e.events.forEach(t=>{as(t)?this.add(t[0],t[1]):this.add(t)})}static getDefaults(){return Object.assign(af.getDefaults(),{events:[]})}start(e,t){const r=this.toTicks(e);if(this._state.getValueAtTime(r)!=="started"){t=ga(t,this._loop?this._loopStart:0),this._loop?t=ga(t,this._loopStart):t=ga(t,0);const i=this.toTicks(t);this._state.add({id:-1,offset:i,state:"started",time:r}),this._forEach(s=>{this._startNote(s,r,i)})}return this}_startNote(e,t,r){t-=r,this._loop?e.startOffset>=this._loopStart&&e.startOffset=r&&(e.loop=!1,e.start(new Pr(this.context,t))):e.startOffset>=r&&e.start(new Pr(this.context,t))}get startOffset(){return this._startOffset}set startOffset(e){this._startOffset=e,this._forEach(t=>{t.startOffset+=this._startOffset})}stop(e){const t=this.toTicks(e);return this._state.cancel(t),this._state.setStateAtTime("stopped",t),this._forEach(r=>{r.stop(e)}),this}at(e,t){const r=new mf(this.context,e).toTicks(),i=new Pr(this.context,1).toSeconds(),s=this._events.values();let o=s.next();for(;!o.done;){const a=o.value;if(Math.abs(r-a.startOffset){t.state==="started"?this._startNote(e,t.time,t.offset):e.stop(new Pr(this.context,t.time))})}remove(e,t){return yl(e)&&e.hasOwnProperty("time")&&(t=e,e=t.time),e=this.toTicks(e),this._events.forEach(r=>{r.startOffset===e&&(Is(t)||Wt(t)&&r.value===t)&&(this._events.delete(r),r.dispose())}),this}clear(){return this._forEach(e=>e.dispose()),this._events.clear(),this}cancel(e){return this._forEach(t=>t.cancel(e)),this._state.cancel(this.toTicks(e)),this}_forEach(e){return this._events&&this._events.forEach(t=>{t instanceof D_?t._forEach(e):e(t)}),this}_setAll(e,t){this._forEach(r=>{r[e]=t})}_tick(e,t){this.mute||this.callback(e,t)}_testLoopBoundries(e){this._loop&&(e.startOffset=this._loopEnd)?e.cancel(0):e.state==="stopped"&&this._restartEvent(e)}get probability(){return this._probability}set probability(e){this._probability=e,this._setAll("probability",e)}get humanize(){return this._humanize}set humanize(e){this._humanize=e,this._setAll("humanize",e)}get loop(){return this._loop}set loop(e){this._loop=e,this._forEach(t=>{t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.loop=e,this._testLoopBoundries(t)})}get loopEnd(){return new Pr(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._forEach(t=>{t.loopEnd=e,this._testLoopBoundries(t)})}get loopStart(){return new Pr(this.context,this._loopStart).toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e),this._loop&&this._forEach(t=>{t.loopStart=this.loopStart,this._testLoopBoundries(t)})}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._setAll("playbackRate",e)}get length(){return this._events.size}dispose(){return super.dispose(),this.clear(),this}}class Xv extends ht{constructor(){const e=at(Xv.getDefaults(),arguments,["fade"]);super(e),this.name="CrossFade",this._panner=this.context.createStereoPanner(),this._split=this.context.createChannelSplitter(2),this._g2a=new hX({context:this.context}),this.a=new jt({context:this.context,gain:0}),this.b=new jt({context:this.context,gain:0}),this.output=new jt({context:this.context}),this._internalChannels=[this.a,this.b],this.fade=new yn({context:this.context,units:"normalRange",value:e.fade}),Zt(this,"fade"),this.context.getConstant(1).connect(this._panner),this._panner.connect(this._split),this._panner.channelCount=1,this._panner.channelCountMode="explicit",Io(this._split,this.a.gain,0),Io(this._split,this.b.gain,1),this.fade.chain(this._g2a,this._panner.pan),this.a.connect(this.output),this.b.connect(this.output)}static getDefaults(){return Object.assign(ht.getDefaults(),{fade:.5})}dispose(){return super.dispose(),this.a.dispose(),this.b.dispose(),this.output.dispose(),this.fade.dispose(),this._g2a.dispose(),this._panner.disconnect(),this._split.disconnect(),this}}let Cl=class extends ht{constructor(e){super(e),this.name="Effect",this._dryWet=new Xv({context:this.context}),this.wet=this._dryWet.fade,this.effectSend=new jt({context:this.context}),this.effectReturn=new jt({context:this.context}),this.input=new jt({context:this.context}),this.output=this._dryWet,this.input.fan(this._dryWet.a,this.effectSend),this.effectReturn.connect(this._dryWet.b),this.wet.setValueAtTime(e.wet,0),this._internalChannels=[this.effectReturn,this.effectSend],Zt(this,"wet")}static getDefaults(){return Object.assign(ht.getDefaults(),{wet:1})}connectEffect(e){return this._internalChannels.push(e),this.effectSend.chain(e,this.effectReturn),this}dispose(){return super.dispose(),this._dryWet.dispose(),this.effectSend.dispose(),this.effectReturn.dispose(),this.wet.dispose(),this}};class jT extends ht{constructor(){const e=at(jT.getDefaults(),arguments,["pan"]);super(e),this.name="Panner",this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner,this.pan=new Xt({context:this.context,param:this._panner.pan,value:e.pan,minValue:-1,maxValue:1}),this._panner.channelCount=e.channelCount,this._panner.channelCountMode="explicit",Zt(this,"pan")}static getDefaults(){return Object.assign(ht.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}}const _X="bit-crusher",vX=` - class BitCrusherWorklet extends SingleIOProcessor { - - static get parameterDescriptors() { - return [{ - name: "bits", - defaultValue: 12, - minValue: 1, - maxValue: 16, - automationRate: 'k-rate' - }]; - } - - generate(input, _channel, parameters) { - const step = Math.pow(0.5, parameters.bits - 1); - const val = step * Math.floor(input / step + 0.5); - return val; - } - } -`;VL(_X,vX);class Kv extends ht{constructor(){const e=at(Kv.getDefaults(),arguments,["channels"]);super(e),this.name="Split",this._splitter=this.input=this.output=this.context.createChannelSplitter(e.channels),this._internalChannels=[this._splitter]}static getDefaults(){return Object.assign(ht.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._splitter.disconnect(),this}}class om extends ht{constructor(){const e=at(om.getDefaults(),arguments,["channels"]);super(e),this.name="Merge",this._merger=this.output=this.input=this.context.createChannelMerger(e.channels)}static getDefaults(){return Object.assign(ht.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._merger.disconnect(),this}}class U_ extends ht{constructor(e){super(e),this.name="StereoEffect",this.input=new jt({context:this.context}),this.input.channelCount=2,this.input.channelCountMode="explicit",this._dryWet=this.output=new Xv({context:this.context,fade:e.wet}),this.wet=this._dryWet.fade,this._split=new Kv({context:this.context,channels:2}),this._merge=new om({context:this.context,channels:2}),this.input.connect(this._split),this.input.connect(this._dryWet.a),this._merge.connect(this._dryWet.b),Zt(this,["wet"])}connectEffectLeft(...e){this._split.connect(e[0],0,0),Bu(...e),Io(e[e.length-1],this._merge,0,0)}connectEffectRight(...e){this._split.connect(e[0],1,0),Bu(...e),Io(e[e.length-1],this._merge,0,1)}static getDefaults(){return Object.assign(ht.getDefaults(),{wet:1})}dispose(){return super.dispose(),this._dryWet.dispose(),this._split.dispose(),this._merge.dispose(),this}}class i2 extends U_{constructor(e){super(e),this.feedback=new yn({context:this.context,value:e.feedback,units:"normalRange"}),this._feedbackL=new jt({context:this.context}),this._feedbackR=new jt({context:this.context}),this._feedbackSplit=new Kv({context:this.context,channels:2}),this._feedbackMerge=new om({context:this.context,channels:2}),this._merge.connect(this._feedbackSplit),this._feedbackMerge.connect(this._split),this._feedbackSplit.connect(this._feedbackL,0,0),this._feedbackL.connect(this._feedbackMerge,0,0),this._feedbackSplit.connect(this._feedbackR,1,0),this._feedbackR.connect(this._feedbackMerge,0,1),this.feedback.fan(this._feedbackL.gain,this._feedbackR.gain),Zt(this,["feedback"])}static getDefaults(){return Object.assign(U_.getDefaults(),{feedback:.5})}dispose(){return super.dispose(),this.feedback.dispose(),this._feedbackL.dispose(),this._feedbackR.dispose(),this._feedbackSplit.dispose(),this._feedbackMerge.dispose(),this}}class $T extends i2{constructor(){const e=at($T.getDefaults(),arguments,["frequency","delayTime","depth"]);super(e),this.name="Chorus",this._depth=e.depth,this._delayTime=e.delayTime/1e3,this._lfoL=new Vu({context:this.context,frequency:e.frequency,min:0,max:1}),this._lfoR=new Vu({context:this.context,frequency:e.frequency,min:0,max:1,phase:180}),this._delayNodeL=new Lf({context:this.context}),this._delayNodeR=new Lf({context:this.context}),this.frequency=this._lfoL.frequency,Zt(this,["frequency"]),this._lfoL.frequency.connect(this._lfoR.frequency),this.connectEffectLeft(this._delayNodeL),this.connectEffectRight(this._delayNodeR),this._lfoL.connect(this._delayNodeL.delayTime),this._lfoR.connect(this._delayNodeR.delayTime),this.depth=this._depth,this.type=e.type,this.spread=e.spread}static getDefaults(){return Object.assign(i2.getDefaults(),{frequency:1.5,delayTime:3.5,depth:.7,type:"sine",spread:180,feedback:0,wet:.5})}get depth(){return this._depth}set depth(e){this._depth=e;const t=this._delayTime*e;this._lfoL.min=Math.max(this._delayTime-t,0),this._lfoL.max=this._delayTime+t,this._lfoR.min=Math.max(this._delayTime-t,0),this._lfoR.max=this._delayTime+t}get delayTime(){return this._delayTime*1e3}set delayTime(e){this._delayTime=e/1e3,this.depth=this._depth}get type(){return this._lfoL.type}set type(e){this._lfoL.type=e,this._lfoR.type=e}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(e){this._lfoL.phase=90-e/2,this._lfoR.phase=e/2+90}start(e){return this._lfoL.start(e),this._lfoR.start(e),this}stop(e){return this._lfoL.stop(e),this._lfoR.stop(e),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._delayNodeL.dispose(),this._delayNodeR.dispose(),this.frequency.dispose(),this}}class yp extends Cl{constructor(){const e=at(yp.getDefaults(),arguments,["distortion"]);super(e),this.name="Distortion",this._shaper=new th({context:this.context,length:4096}),this._distortion=e.distortion,this.connectEffect(this._shaper),this.distortion=e.distortion,this.oversample=e.oversample}static getDefaults(){return Object.assign(Cl.getDefaults(),{distortion:.4,oversample:"none"})}get distortion(){return this._distortion}set distortion(e){this._distortion=e;const t=e*100,r=Math.PI/180;this._shaper.setMap(i=>Math.abs(i)<.001?0:(3+t)*i*20*r/(Math.PI+t*Math.abs(i)))}get oversample(){return this._shaper.oversample}set oversample(e){this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.dispose(),this}}class s2 extends Cl{constructor(e){super(e),this.name="FeedbackEffect",this._feedbackGain=new jt({context:this.context,gain:e.feedback,units:"normalRange"}),this.feedback=this._feedbackGain.gain,Zt(this,"feedback"),this.effectReturn.chain(this._feedbackGain,this.effectSend)}static getDefaults(){return Object.assign(Cl.getDefaults(),{feedback:.125})}dispose(){return super.dispose(),this._feedbackGain.dispose(),this.feedback.dispose(),this}}class Yv extends s2{constructor(){const e=at(Yv.getDefaults(),arguments,["delayTime","feedback"]);super(e),this.name="FeedbackDelay",this._delayNode=new Lf({context:this.context,delayTime:e.delayTime,maxDelay:e.maxDelay}),this.delayTime=this._delayNode.delayTime,this.connectEffect(this._delayNode),Zt(this,"delayTime")}static getDefaults(){return Object.assign(s2.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._delayNode.dispose(),this.delayTime.dispose(),this}}class qT extends U_{constructor(){const e=at(qT.getDefaults(),arguments,["frequency","octaves","baseFrequency"]);super(e),this.name="Phaser",this._lfoL=new Vu({context:this.context,frequency:e.frequency,min:0,max:1}),this._lfoR=new Vu({context:this.context,frequency:e.frequency,min:0,max:1,phase:180}),this._baseFrequency=this.toFrequency(e.baseFrequency),this._octaves=e.octaves,this.Q=new yn({context:this.context,value:e.Q,units:"positive"}),this._filtersL=this._makeFilters(e.stages,this._lfoL),this._filtersR=this._makeFilters(e.stages,this._lfoR),this.frequency=this._lfoL.frequency,this.frequency.value=e.frequency,this.connectEffectLeft(...this._filtersL),this.connectEffectRight(...this._filtersR),this._lfoL.frequency.connect(this._lfoR.frequency),this.baseFrequency=e.baseFrequency,this.octaves=e.octaves,this._lfoL.start(),this._lfoR.start(),Zt(this,["frequency","Q"])}static getDefaults(){return Object.assign(U_.getDefaults(),{frequency:.5,octaves:3,stages:10,Q:10,baseFrequency:350})}_makeFilters(e,t){const r=[];for(let i=0;ie.disconnect()),this._filtersR.forEach(e=>e.disconnect()),this.frequency.dispose(),this}}class XT extends Cl{constructor(){const e=at(XT.getDefaults(),arguments,["decay"]);super(e),this.name="Reverb",this._convolver=this.context.createConvolver(),this.ready=Promise.resolve(),this._decay=e.decay,this._preDelay=e.preDelay,this.generate(),this.connectEffect(this._convolver)}static getDefaults(){return Object.assign(Cl.getDefaults(),{decay:1.5,preDelay:.01})}get decay(){return this._decay}set decay(e){e=this.toSeconds(e),Ea(e,.001),this._decay=e,this.generate()}get preDelay(){return this._preDelay}set preDelay(e){e=this.toSeconds(e),Ea(e,0),this._preDelay=e,this.generate()}generate(){return _r(this,void 0,void 0,function*(){const e=this.ready,t=new Dv(2,this._decay+this._preDelay,this.context.sampleRate),r=new Pf({context:t}),i=new Pf({context:t}),s=new om({context:t});r.connect(s,0,0),i.connect(s,0,1);const o=new jt({context:t}).toDestination();s.connect(o),r.start(0),i.start(0),o.gain.setValueAtTime(0,0),o.gain.setValueAtTime(1,this._preDelay),o.gain.exponentialApproachValueAtTime(0,this._preDelay,this.decay);const a=t.render();return this.ready=a.then(En),yield e,this._convolver.buffer=(yield a).get(),this})}dispose(){return super.dispose(),this._convolver.disconnect(),this}}class KT extends Cl{constructor(){const e=at(KT.getDefaults(),arguments,["frequency","depth"]);super(e),this.name="Vibrato",this._delayNode=new Lf({context:this.context,delayTime:0,maxDelay:e.maxDelay}),this._lfo=new Vu({context:this.context,type:e.type,min:0,max:e.maxDelay,frequency:e.frequency,phase:-90}).start().connect(this._delayNode.delayTime),this.frequency=this._lfo.frequency,this.depth=this._lfo.amplitude,this.depth.value=e.depth,Zt(this,["frequency","depth"]),this.effectSend.chain(this._delayNode,this.effectReturn)}static getDefaults(){return Object.assign(Cl.getDefaults(),{maxDelay:.005,frequency:5,depth:.1,type:"sine"})}get type(){return this._lfo.type}set type(e){this._lfo.type=e}dispose(){return super.dispose(),this._delayNode.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class br extends ht{constructor(){const e=at(br.getDefaults(),arguments,["solo"]);super(e),this.name="Solo",this.input=this.output=new jt({context:this.context}),br._allSolos.has(this.context)||br._allSolos.set(this.context,new Set),br._allSolos.get(this.context).add(this),this.solo=e.solo}static getDefaults(){return Object.assign(ht.getDefaults(),{solo:!1})}get solo(){return this._isSoloed()}set solo(e){e?this._addSolo():this._removeSolo(),br._allSolos.get(this.context).forEach(t=>t._updateSolo())}get muted(){return this.input.gain.value===0}_addSolo(){br._soloed.has(this.context)||br._soloed.set(this.context,new Set),br._soloed.get(this.context).add(this)}_removeSolo(){br._soloed.has(this.context)&&br._soloed.get(this.context).delete(this)}_isSoloed(){return br._soloed.has(this.context)&&br._soloed.get(this.context).has(this)}_noSolos(){return!br._soloed.has(this.context)||br._soloed.has(this.context)&&br._soloed.get(this.context).size===0}_updateSolo(){this._isSoloed()?this.input.gain.value=1:this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),br._allSolos.get(this.context).delete(this),this._removeSolo(),this}}br._allSolos=new Map;br._soloed=new Map;class YT extends ht{constructor(){const e=at(YT.getDefaults(),arguments,["pan","volume"]);super(e),this.name="PanVol",this._panner=this.input=new jT({context:this.context,pan:e.pan,channelCount:e.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new Al({context:this.context,volume:e.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=e.mute,Zt(this,["pan","volume"])}static getDefaults(){return Object.assign(ht.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}}class cf extends ht{constructor(){const e=at(cf.getDefaults(),arguments,["volume","pan"]);super(e),this.name="Channel",this._solo=this.input=new br({solo:e.solo,context:this.context}),this._panVol=this.output=new YT({context:this.context,pan:e.pan,volume:e.volume,mute:e.mute,channelCount:e.channelCount}),this.pan=this._panVol.pan,this.volume=this._panVol.volume,this._solo.connect(this._panVol),Zt(this,["pan","volume"])}static getDefaults(){return Object.assign(ht.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(e){this._solo.solo=e}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(e){this._panVol.mute=e}_getBus(e){return cf.buses.has(e)||cf.buses.set(e,new jt({context:this.context})),cf.buses.get(e)}send(e,t=0){const r=this._getBus(e),i=new jt({context:this.context,units:"decibels",gain:t});return this.connect(i),i.connect(r),i}receive(e){return this._getBus(e).connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}}cf.buses=new Map;class ZT extends ht{constructor(){const e=at(ZT.getDefaults(),arguments,["lowFrequency","highFrequency"]);super(e),this.name="MultibandSplit",this.input=new jt({context:this.context}),this.output=void 0,this.low=new qs({context:this.context,frequency:0,type:"lowpass"}),this._lowMidFilter=new qs({context:this.context,frequency:0,type:"highpass"}),this.mid=new qs({context:this.context,frequency:0,type:"lowpass"}),this.high=new qs({context:this.context,frequency:0,type:"highpass"}),this._internalChannels=[this.low,this.mid,this.high],this.lowFrequency=new yn({context:this.context,units:"frequency",value:e.lowFrequency}),this.highFrequency=new yn({context:this.context,units:"frequency",value:e.highFrequency}),this.Q=new yn({context:this.context,units:"positive",value:e.Q}),this.input.fan(this.low,this.high),this.input.chain(this._lowMidFilter,this.mid),this.lowFrequency.fan(this.low.frequency,this._lowMidFilter.frequency),this.highFrequency.fan(this.mid.frequency,this.high.frequency),this.Q.connect(this.low.Q),this.Q.connect(this._lowMidFilter.Q),this.Q.connect(this.mid.Q),this.Q.connect(this.high.Q),Zt(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(ht.getDefaults(),{Q:1,highFrequency:2500,lowFrequency:400})}dispose(){return super.dispose(),tm(this,["high","mid","low","highFrequency","lowFrequency"]),this.low.dispose(),this._lowMidFilter.dispose(),this.mid.dispose(),this.high.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this.Q.dispose(),this}}class QT extends ht{constructor(){const e=at(QT.getDefaults(),arguments,["threshold","ratio"]);super(e),this.name="Compressor",this._compressor=this.context.createDynamicsCompressor(),this.input=this._compressor,this.output=this._compressor,this.threshold=new Xt({minValue:this._compressor.threshold.minValue,maxValue:this._compressor.threshold.maxValue,context:this.context,convert:!1,param:this._compressor.threshold,units:"decibels",value:e.threshold}),this.attack=new Xt({minValue:this._compressor.attack.minValue,maxValue:this._compressor.attack.maxValue,context:this.context,param:this._compressor.attack,units:"time",value:e.attack}),this.release=new Xt({minValue:this._compressor.release.minValue,maxValue:this._compressor.release.maxValue,context:this.context,param:this._compressor.release,units:"time",value:e.release}),this.knee=new Xt({minValue:this._compressor.knee.minValue,maxValue:this._compressor.knee.maxValue,context:this.context,convert:!1,param:this._compressor.knee,units:"decibels",value:e.knee}),this.ratio=new Xt({minValue:this._compressor.ratio.minValue,maxValue:this._compressor.ratio.maxValue,context:this.context,convert:!1,param:this._compressor.ratio,units:"positive",value:e.ratio}),Zt(this,["knee","release","attack","ratio","threshold"])}static getDefaults(){return Object.assign(ht.getDefaults(),{attack:.003,knee:30,ratio:12,release:.25,threshold:-24})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.disconnect(),this.attack.dispose(),this.release.dispose(),this.threshold.dispose(),this.ratio.dispose(),this.knee.dispose(),this}}class JT extends ht{constructor(){const e=at(JT.getDefaults(),arguments,["low","mid","high"]);super(e),this.name="EQ3",this.output=new jt({context:this.context}),this._internalChannels=[],this.input=this._multibandSplit=new ZT({context:this.context,highFrequency:e.highFrequency,lowFrequency:e.lowFrequency}),this._lowGain=new jt({context:this.context,gain:e.low,units:"decibels"}),this._midGain=new jt({context:this.context,gain:e.mid,units:"decibels"}),this._highGain=new jt({context:this.context,gain:e.high,units:"decibels"}),this.low=this._lowGain.gain,this.mid=this._midGain.gain,this.high=this._highGain.gain,this.Q=this._multibandSplit.Q,this.lowFrequency=this._multibandSplit.lowFrequency,this.highFrequency=this._multibandSplit.highFrequency,this._multibandSplit.low.chain(this._lowGain,this.output),this._multibandSplit.mid.chain(this._midGain,this.output),this._multibandSplit.high.chain(this._highGain,this.output),Zt(this,["low","mid","high","lowFrequency","highFrequency"]),this._internalChannels=[this._multibandSplit]}static getDefaults(){return Object.assign(ht.getDefaults(),{high:0,highFrequency:2500,low:0,lowFrequency:400,mid:0})}dispose(){return super.dispose(),tm(this,["low","mid","high","lowFrequency","highFrequency"]),this._multibandSplit.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this._lowGain.dispose(),this._midGain.dispose(),this._highGain.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.Q.dispose(),this}}Bi().transport;function eb(){return Bi().transport}Bi().destination;Bi().destination;function yX(){return Bi().destination}Bi().listener;Bi().draw;Bi();const NE=Ir("256n").toSeconds(),xX=Ir("8n").toSeconds();function SX(){const n=new XT;n.set({wet:0});const e=new Yv;e.set({wet:0,delayTime:NE,maxDelay:"1n",feedback:.666});const t=new $T;t.set({wet:0,depth:.999,frequency:7,feedback:.666});const r=new qT;r.set({wet:0,Q:10});const i=new yp;i.set({wet:0,distortion:.9});const s=new KT;return s.set({wet:0,depth:.2}),{reverb:n,echo:e,chorus:t,phaser:r,distortion:i,vibrato:s}}const EX={a:1,b:2,c:3,d:4,e:5,f:6,g:7,x:8,"#":9,"!":10,y:13,t:14,s:15,i:16,q:17,h:18,w:19,3:20,".":21,"+":11,"-":12,0:22,1:23,2:24,p:25,4:26,5:27,6:29,7:28,8:30,9:31};let wX=0;function TX(n,e,t){let r=e,i=3,s="32n",o="",a="";const c=[];function l(){a="",o="",r+=Ir(s).toSeconds()}function u(){a===null?(c.push([r,[n,s,a]]),l()):mt(a)?(c.push([r,[n,s,a]]),l()):a!==""&&(c.push([r,[n,s,`${a}${o}${i}`]]),l())}for(let h=0;h{if(!X0){const n=eb();n.bpm.value=107,n.start(),eo("synth","audio is enabled!"),X0=!0}}).catch(()=>{})}function AX(){const n=yX(),e=new Al(8);e.connect(n);const t=new QT({threshold:-24,ratio:4,attack:.003,release:.25,knee:30});t.connect(e);const r=new jt;r.connect(t);const i=new Al(2);i.connect(t);const s=[tc(r),tc(r),tc(r),tc(r),tc(r),tc(r),tc(r),tc(r),tc(r)],o=new P_().connect(i);o.maxPolyphony=8,o.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"square"}});function a(A){o.triggerAttackRelease("C6","1i",A)}const c=new Ni().connect(i);o.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"square"}});function l(A){const J=Ir("64n").toSeconds();c.triggerAttackRelease("C6","8n",A),c.frequency.exponentialRampToValueAtTime("C11",J+A)}const u=new qs(350,"bandpass").connect(i),h=new jt().connect(u);h.gain.value=0;const p=new P_().connect(h);p.maxPolyphony=8,p.set({envelope:{attack:.001,decay:.01,sustain:.1,release:.1},oscillator:{type:"square"}});function m(A,J){const re=Ir("64n").toSeconds()+Ir(A).toSeconds();h.gain.setValueAtTime(.5,J),h.gain.exponentialRampToValueAtTime(.01,re+J),p.triggerAttackRelease([800,540],A,J)}const g=new JT(-10,10,-1).connect(i),v=new qs(800,"highpass",-12);v.connect(g);const y=new of;y.set({envelope:{attack:.01,decay:.1,sustain:.1,release:.1}}),y.connect(v);function _(A,J){y.triggerAttackRelease(A,J)}const S=new yp().connect(i);S.set({distortion:.666});const w=new Ni;w.set({envelope:{attack:0,decay:.1,sustain:0,release:1},oscillator:{type:"triangle"}}),w.connect(S);const T=new qs;T.set({type:"highpass",frequency:1e4}),T.connect(S);const k=new of;k.set({envelope:{attack:.01,decay:.1,sustain:0,release:.1}}),k.connect(T);function R(A,J){const re=Ir("512n").toSeconds(),j=Ir("32n").toSeconds();w.triggerAttackRelease(1e4,A,J,1),w.frequency.exponentialRampToValueAtTime(300,J+re),w.frequency.exponentialRampToValueAtTime(100,J+j),k.triggerAttackRelease("8n",J,.333),k.volume.setValueAtTime(1,J),k.volume.exponentialRampToValueAtTime(0,J+Ir("32n").toSeconds())}const C=new qs;C.set({type:"bandpass",frequency:256,Q:.17}),C.connect(i);const O=new Ni;O.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"sawtooth"}}),O.connect(C);const M=new Ni;M.set({envelope:{attack:.001,decay:.1,sustain:.001,release:.1},oscillator:{type:"sine"}}),M.connect(C);function N(A,J){O.triggerAttackRelease(2e3,A,J),O.frequency.exponentialRampToValueAtTime(1e3,J+Ir("32n").toSeconds()),M.triggerAttackRelease(999,A,J),M.frequency.exponentialRampToValueAtTime(888,J+Ir("256n").toSeconds())}const U=new yp().connect(i);U.set({distortion:.876});const L=new Ni;L.set({envelope:{attack:0,decay:.1,sustain:0,release:1},oscillator:{type:"triangle"}}),L.connect(U);const P=new qs;P.set({type:"highpass",frequency:1e4}),P.connect(U);const b=new of;b.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1}}),b.connect(P);function B(A,J){const re=Ir("512n").toSeconds(),j=Ir("32n").toSeconds();L.triggerAttackRelease(1e4,A,J,1),L.frequency.exponentialRampToValueAtTime(150,J+re),L.frequency.exponentialRampToValueAtTime(100,J+j),b.triggerAttackRelease("8n",J,.25),b.volume.setValueAtTime(1,J),b.volume.exponentialRampToValueAtTime(0,J+Ir("32n").toSeconds())}const W=new Ni().connect(i);W.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1},oscillator:{type:"sawtooth"}});const V=new Ni().connect(i);W.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1},oscillator:{type:"triangle"}});const G=new of().connect(i);G.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1}});function $(A,J){const re=Ir("256n").toSeconds(),j=Ir(A).toSeconds()-re;W.triggerAttackRelease("C4",j,J,1),W.frequency.exponentialRampToValueAtTime(t2("C0").toFrequency(),J+j),V.triggerAttackRelease("C5",j,J,.5),V.frequency.exponentialRampToValueAtTime(t2("C0").toFrequency(),J+j);const H=Ir("4n").toSeconds();G.triggerAttackRelease("8n",J),G.volume.setValueAtTime(1,J),G.volume.exponentialRampToValueAtTime(0,J+H)}const Z=new qs;Z.set({type:"bandpass",frequency:256,Q:.17}),Z.connect(i);const X=new Ni;X.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"sawtooth"}}),X.connect(Z);const Y=new Ni;Y.set({envelope:{attack:.001,decay:.1,sustain:.001,release:.1},oscillator:{type:"sine"}}),Y.connect(Z);function ve(A,J){X.triggerAttackRelease(2e3,A,J),X.frequency.exponentialRampToValueAtTime(100,J+Ir("32n").toSeconds()),Y.triggerAttackRelease(699,A,J),Y.frequency.exponentialRampToValueAtTime(399,J+Ir("256n").toSeconds())}const ne=new sm().connect(i);ne.set({octaves:8});function ie(A){ne.triggerAttackRelease("C1","8n",A)}const be=new D_(Ce);function Ce(A,J){if(J===null)return;const[re,j,H]=J;if(Kt(H)&&K(s[re])&&s[re].source.triggerAttackRelease(H,j,A),mt(H))switch(H){case 0:a(A);break;case 1:l(A);break;case 2:m(j,A);break;case 3:_(j,A);break;case 4:R(j,A);break;case 5:N(j,A);break;case 6:B(j,A);break;case 7:$(j,A);break;case 8:ve(j,A);break;case 9:ie(A);break;case-1:--ze,ze===0&&(Le=-1),Ge=-1;break}}function Ee(A,J,re){let j=J;const H=TX(A,J,re),te=H[H.length-1];K(te)&&(j=Math.max(j,te[0]));for(let oe=0;oe=Ge){Ge=A;for(let H=0;H{if(X0&&!K(cu)&&(cu=AX()),!!K(cu))switch(n.target){case"play":if(fn(n.data)){const[e,t]=n.data;t===""?cu.stopplay():cu.addplay(e,t)}break;case"voice":if(fn(n.data)){const[e,t,r]=n.data,i=cu.SOURCE[e];if(!K(i)){Pn(nc.name(),n.target,`unknown voice ${e}`);return}switch(t){case"bpm":if(mt(r)){eb().bpm.value=r;return}break;case"vol":case"volume":if(mt(r)){i.source.volume.value=r;return}break;case"port":case"portamento":if(mt(r)){i.source.portamento=r;return}break;case"env":case"envelope":if(fn(r)){const[s,o,a,c]=r;i.source.set({envelope:{attack:s,decay:o,sustain:a,release:c}});return}break;default:if(Kt(t)){if(MX(t,r)){i.source.set({oscillator:{type:t}}),fn(r)&&i.source.set({oscillator:{partials:r}}),mt(r)&&i.source.set({oscillator:{partials:[r]}});return}const s=i.source.get().oscillator.type;switch(s){case"pwm":switch(t){case"modfreq":case"modulationfrequency":if(mt(r)){i.source.set({oscillator:{modulationFrequency:r}});return}break}break;case"pulse":switch(t){case"width":if(mt(r)){i.source.set({oscillator:{width:r}});return}break}break;case"custom":case"sine":case"square":case"triangle":case"sawtooth":switch(t){case"phase":if(mt(r)){i.source.set({oscillator:{phase:r}});return}break}break;case"amcustom":case"amsine":case"amsquare":case"amtriangle":case"amsawtooth":switch(t){case"harmonicity":if(mt(r)){i.source.set({oscillator:{harmonicity:r}});return}break;case"modtype":case"modulationtype":if(Kt(r)){i.source.set({oscillator:{modulationType:r}});return}break;case"modenv":case"modulationenvelope":if(fn(r)){const[o,a,c,l]=r;i.source.set({oscillator:{modulationEnvelope:{attack:o,decay:a,sustain:c,release:l}}});return}break}break;case"fmcustom":case"fmsine":case"fmsquare":case"fmtriangle":case"fmsawtooth":switch(t){case"harmonicity":if(mt(r)){i.source.set({oscillator:{harmonicity:r}});return}break;case"modindex":if(mt(r)){i.source.set({oscillator:{modulationIndex:r}});return}break;case"modtype":if(Kt(r)){i.source.set({oscillator:{modulationType:r}});return}break;case"modenv":if(fn(r)){const[o,a,c,l]=r;i.source.set({oscillator:{modulationEnvelope:{attack:o,decay:a,sustain:c,release:l}}});return}break}break;case"fatcustom":case"fatsine":case"fatsquare":case"fattriangle":case"fatsawtooth":switch(t){case"count":if(mt(r)){i.source.set({oscillator:{count:r}});return}break;case"phase":if(mt(r)){i.source.set({oscillator:{phase:r}});return}break;case"spread":if(mt(r)){i.source.set({oscillator:{spread:r}});return}break}break}Pn(nc.name(),n.target,`unknown ${s} config ${t}`)}break}}break;case"voicefx":if(fn(n.data)){const[e,t,r,i]=n.data,s=cu.SOURCE[e],o=s==null?void 0:s.fx[t];if(K(o)){switch(r){case"on":o.wet.value=.2;break;case"off":o.wet.value=0;break;default:if(mt(r))o.wet.value=Cn(.01*r,0,1);else switch(t){case"vibrato":{switch(r){default:Pn(nc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"chorus":{switch(r){default:Pn(nc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"phaser":{const a=o;switch(r){case"q":mt(i)&&(a.Q.value=i);break;case"octaves":mt(i)&&(a.octaves=i);break;case"basefrequency":mt(i)&&(a.baseFrequency=i);break;default:Pn(nc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"distortion":{const a=o;switch(r){case"distortion":mt(i)&&(a.distortion=i);break;case"oversample":switch(i){case"2x":case"4x":case"none":a.oversample=i;break}break;default:Pn(nc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"echo":{const a=o;switch(r){case"delaytime":a.delayTime.value=i;break;default:Pn(nc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"reverb":{const a=o;switch(r){case"decay":a.decay=i;break;case"predelay":a.preDelay=i;break;default:Pn(nc.name(),n.target,`unknown ${t} config ${r}`);break}break}}break}o instanceof Yv&&(o.wet.value===0?o.set({delayTime:NE}):o.get().delayTime===NE&&o.set({delayTime:xX}));return}Pn(nc.name(),n.target,`unknown fx ${t}`)}break}}),o2=n=>{let e;const t=new Set,r=(l,u)=>{const h=typeof l=="function"?l(e):l;if(!Object.is(h,e)){const p=e;e=u??(typeof h!="object"||h===null)?h:Object.assign({},e,h),t.forEach(m=>m(e,p))}},i=()=>e,a={setState:r,getState:i,getInitialState:()=>c,subscribe:l=>(t.add(l),()=>t.delete(l))},c=e=n(r,i,a);return a},tb=n=>n?o2(n):o2,CX=n=>n;function nb(n,e=CX){const t=bo.useSyncExternalStore(n.subscribe,()=>e(n.getState()),()=>e(n.getInitialState()));return bo.useDebugValue(t),t}const a2=n=>{const e=tb(n),t=r=>nb(e,r);return Object.assign(t,e),t},am=n=>n?a2(n):a2;function RX(n){const e=ke.useRef();return t=>{const r=n(t);return(e.current===void 0||r===void 0?e.current===r:wO(e.current,r))?e.current:e.current=r}}const is=am(()=>({desync:!1,gadget:{player:"",layers:[],panels:[],reset:!1,focus:""}}));function rb(){return is(n=>n.gadget.player)}function F_(){return is.getState().gadget.player}var K0=(n=>(n[n.OFF=0]="OFF",n[n.INFO=1]="INFO",n[n.DEBUG=2]="DEBUG",n))(K0||{});const c2=128;var Oi=(n=>(n[n.TOP=0]="TOP",n[n.BOTTOM=1]="BOTTOM",n[n.FULL=2]="FULL",n[n.SPLIT_Y=3]="SPLIT_Y",n[n.SPLIT_Y_ALT=4]="SPLIT_Y_ALT",n[n.MAX=5]="MAX",n))(Oi||{});const Ji=am(()=>({layout:1,terminal:{open:!1,level:1,logs:[]},editor:{open:!1,player:"",book:"",page:"",type:"",title:""}})),Tr=am(()=>({scroll:0,xcursor:0,ycursor:0,xselect:void 0,yselect:void 0,bufferindex:0,buffer:[""]})),hr=am(()=>({id:"",xscroll:0,yscroll:0,cursor:0,select:void 0}));/** - * postprocessing v6.36.4 build Tue Nov 05 2024 - * https://github.com/pmndrs/postprocessing - * Copyright 2015-2024 Raoul van Rüschen - * @license Zlib - */var PS=1/1e3,kX=1e3,IX=class{constructor(){this.startTime=performance.now(),this.previousTime=0,this.currentTime=0,this._delta=0,this._elapsed=0,this._fixedDelta=1e3/60,this.timescale=1,this.useFixedDelta=!1,this._autoReset=!1}get autoReset(){return this._autoReset}set autoReset(n){typeof document<"u"&&document.hidden!==void 0&&(n?document.addEventListener("visibilitychange",this):document.removeEventListener("visibilitychange",this),this._autoReset=n)}get delta(){return this._delta*PS}get fixedDelta(){return this._fixedDelta*PS}set fixedDelta(n){this._fixedDelta=n*kX}get elapsed(){return this._elapsed*PS}update(n){this.useFixedDelta?this._delta=this.fixedDelta:(this.previousTime=this.currentTime,this.currentTime=(n!==void 0?n:performance.now())-this.startTime,this._delta=this.currentTime-this.previousTime),this._delta*=this.timescale,this._elapsed+=this._delta}reset(){this._delta=0,this._elapsed=0,this.currentTime=performance.now()-this.startTime}getDelta(){return this.delta}getElapsed(){return this.elapsed}handleEvent(n){document.hidden||(this.currentTime=performance.now()-this.startTime)}dispose(){this.autoReset=!1}},NX=(()=>{const n=new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),e=new Float32Array([0,0,2,0,0,2]),t=new Do;return t.setAttribute("position",new Qn(n,3)),t.setAttribute("uv",new Qn(e,2)),t})(),zo=class OE{static get fullscreenGeometry(){return NX}constructor(e="Pass",t=new __,r=new xv){this.name=e,this.renderer=null,this.scene=t,this.camera=r,this.screen=null,this.rtt=!0,this.needsSwap=!0,this.needsDepthTexture=!1,this.enabled=!0}get renderToScreen(){return!this.rtt}set renderToScreen(e){if(this.rtt===e){const t=this.fullscreenMaterial;t!==null&&(t.needsUpdate=!0),this.rtt=!e}}set mainScene(e){}set mainCamera(e){}setRenderer(e){this.renderer=e}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}get fullscreenMaterial(){return this.screen!==null?this.screen.material:null}set fullscreenMaterial(e){let t=this.screen;t!==null?t.material=e:(t=new wo(OE.fullscreenGeometry,e),t.frustumCulled=!1,this.scene===null&&(this.scene=new __),this.scene.add(t),this.screen=t)}getFullscreenMaterial(){return this.fullscreenMaterial}setFullscreenMaterial(e){this.fullscreenMaterial=e}getDepthTexture(){return null}setDepthTexture(e,t=Yu){}render(e,t,r,i,s){throw new Error("Render method not implemented!")}setSize(e,t){}initialize(e,t,r){}dispose(){for(const e of Object.keys(this)){const t=this[e];(t instanceof Ls||t instanceof Lc||t instanceof or||t instanceof OE)&&this[e].dispose()}this.fullscreenMaterial!==null&&this.fullscreenMaterial.dispose()}},OX=class extends zo{constructor(){super("ClearMaskPass",null,null),this.needsSwap=!1}render(n,e,t,r,i){const s=n.state.buffers.stencil;s.setLocked(!1),s.setTest(!1)}},LX=`#include -#include -#ifdef FRAMEBUFFER_PRECISION_HIGH -uniform mediump sampler2D inputBuffer; -#else -uniform lowp sampler2D inputBuffer; -#endif -uniform float opacity;varying vec2 vUv;void main(){vec4 texel=texture2D(inputBuffer,vUv);gl_FragColor=opacity*texel; -#include -#include -}`,PX="varying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,1.0,1.0);}",DX=class extends Vi{constructor(){super({name:"CopyMaterial",uniforms:{inputBuffer:new Mn(null),opacity:new Mn(1)},blending:Ao,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:LX,vertexShader:PX})}set inputBuffer(n){this.uniforms.inputBuffer.value=n}setInputBuffer(n){this.uniforms.inputBuffer.value=n}getOpacity(n){return this.uniforms.opacity.value}setOpacity(n){this.uniforms.opacity.value=n}},UX=class extends zo{constructor(n,e=!0){super("CopyPass"),this.fullscreenMaterial=new DX,this.needsSwap=!1,this.renderTarget=n,n===void 0&&(this.renderTarget=new Ls(1,1,{minFilter:ns,magFilter:ns,stencilBuffer:!1,depthBuffer:!1}),this.renderTarget.texture.name="CopyPass.Target"),this.autoResize=e}get resize(){return this.autoResize}set resize(n){this.autoResize=n}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}setAutoResizeEnabled(n){this.autoResize=n}render(n,e,t,r,i){this.fullscreenMaterial.inputBuffer=e.texture,n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){this.autoResize&&this.renderTarget.setSize(n,e)}initialize(n,e,t){t!==void 0&&(this.renderTarget.texture.type=t,t!==Ei?this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1":n!==null&&n.outputColorSpace===pr&&(this.renderTarget.texture.colorSpace=pr))}},l2=new cn,HL=class extends zo{constructor(n=!0,e=!0,t=!1){super("ClearPass",null,null),this.needsSwap=!1,this.color=n,this.depth=e,this.stencil=t,this.overrideClearColor=null,this.overrideClearAlpha=-1}setClearFlags(n,e,t){this.color=n,this.depth=e,this.stencil=t}getOverrideClearColor(){return this.overrideClearColor}setOverrideClearColor(n){this.overrideClearColor=n}getOverrideClearAlpha(){return this.overrideClearAlpha}setOverrideClearAlpha(n){this.overrideClearAlpha=n}render(n,e,t,r,i){const s=this.overrideClearColor,o=this.overrideClearAlpha,a=n.getClearAlpha(),c=s!==null,l=o>=0;c?(n.getClearColor(l2),n.setClearColor(s,l?o:a)):l&&n.setClearAlpha(o),n.setRenderTarget(this.renderToScreen?null:e),n.clear(this.color,this.depth,this.stencil),c?n.setClearColor(l2,a):l&&n.setClearAlpha(a)}},FX=class extends zo{constructor(n,e){super("MaskPass",n,e),this.needsSwap=!1,this.clearPass=new HL(!1,!1,!0),this.inverse=!1}set mainScene(n){this.scene=n}set mainCamera(n){this.camera=n}get inverted(){return this.inverse}set inverted(n){this.inverse=n}get clear(){return this.clearPass.enabled}set clear(n){this.clearPass.enabled=n}getClearPass(){return this.clearPass}isInverted(){return this.inverted}setInverted(n){this.inverted=n}render(n,e,t,r,i){const s=n.getContext(),o=n.state.buffers,a=this.scene,c=this.camera,l=this.clearPass,u=this.inverted?0:1,h=1-u;o.color.setMask(!1),o.depth.setMask(!1),o.color.setLocked(!0),o.depth.setLocked(!0),o.stencil.setTest(!0),o.stencil.setOp(s.REPLACE,s.REPLACE,s.REPLACE),o.stencil.setFunc(s.ALWAYS,u,4294967295),o.stencil.setClear(h),o.stencil.setLocked(!0),this.clearPass.enabled&&(this.renderToScreen?l.render(n,null):(l.render(n,e),l.render(n,t))),this.renderToScreen?(n.setRenderTarget(null),n.render(a,c)):(n.setRenderTarget(e),n.render(a,c),n.setRenderTarget(t),n.render(a,c)),o.color.setLocked(!1),o.depth.setLocked(!1),o.stencil.setLocked(!1),o.stencil.setFunc(s.EQUAL,1,4294967295),o.stencil.setOp(s.KEEP,s.KEEP,s.KEEP),o.stencil.setLocked(!0)}},BX=class{constructor(e=null,{depthBuffer:t=!0,stencilBuffer:r=!1,multisampling:i=0,frameBufferType:s}={}){this.renderer=null,this.inputBuffer=this.createBuffer(t,r,s,i),this.outputBuffer=this.inputBuffer.clone(),this.copyPass=new UX,this.depthTexture=null,this.passes=[],this.timer=new IX,this.autoRenderToScreen=!0,this.setRenderer(e)}get multisampling(){return this.inputBuffer.samples||0}set multisampling(e){const t=this.inputBuffer,r=this.multisampling;r>0&&e>0?(this.inputBuffer.samples=e,this.outputBuffer.samples=e,this.inputBuffer.dispose(),this.outputBuffer.dispose()):r!==e&&(this.inputBuffer.dispose(),this.outputBuffer.dispose(),this.inputBuffer=this.createBuffer(t.depthBuffer,t.stencilBuffer,t.texture.type,e),this.inputBuffer.depthTexture=this.depthTexture,this.outputBuffer=this.inputBuffer.clone())}getTimer(){return this.timer}getRenderer(){return this.renderer}setRenderer(e){if(this.renderer=e,e!==null){const t=e.getSize(new St),r=e.getContext().getContextAttributes().alpha,i=this.inputBuffer.texture.type;i===Ei&&e.outputColorSpace===pr&&(this.inputBuffer.texture.colorSpace=pr,this.outputBuffer.texture.colorSpace=pr,this.inputBuffer.dispose(),this.outputBuffer.dispose()),e.autoClear=!1,this.setSize(t.width,t.height);for(const s of this.passes)s.initialize(e,r,i)}}replaceRenderer(e,t=!0){const r=this.renderer,i=r.domElement.parentNode;return this.setRenderer(e),t&&i!==null&&(i.removeChild(r.domElement),i.appendChild(e.domElement)),r}createDepthTexture(){const e=this.depthTexture=new tT;return this.inputBuffer.depthTexture=e,this.inputBuffer.dispose(),this.inputBuffer.stencilBuffer?(e.format=Du,e.type=Pu):e.type=bl,e}deleteDepthTexture(){if(this.depthTexture!==null){this.depthTexture.dispose(),this.depthTexture=null,this.inputBuffer.depthTexture=null,this.inputBuffer.dispose();for(const e of this.passes)e.setDepthTexture(null)}}createBuffer(e,t,r,i){const s=this.renderer,o=s===null?new St:s.getDrawingBufferSize(new St),a={minFilter:ns,magFilter:ns,stencilBuffer:t,depthBuffer:e,type:r},c=new Ls(o.width,o.height,a);return i>0&&(c.ignoreDepthForMultisampleCopy=!1,c.samples=i),r===Ei&&s!==null&&s.outputColorSpace===pr&&(c.texture.colorSpace=pr),c.texture.name="EffectComposer.Buffer",c.texture.generateMipmaps=!1,c}setMainScene(e){for(const t of this.passes)t.mainScene=e}setMainCamera(e){for(const t of this.passes)t.mainCamera=e}addPass(e,t){const r=this.passes,i=this.renderer,s=i.getDrawingBufferSize(new St),o=i.getContext().getContextAttributes().alpha,a=this.inputBuffer.texture.type;if(e.setRenderer(i),e.setSize(s.width,s.height),e.initialize(i,o,a),this.autoRenderToScreen&&(r.length>0&&(r[r.length-1].renderToScreen=!1),e.renderToScreen&&(this.autoRenderToScreen=!1)),t!==void 0?r.splice(t,0,e):r.push(e),this.autoRenderToScreen&&(r[r.length-1].renderToScreen=!0),e.needsDepthTexture||this.depthTexture!==null)if(this.depthTexture===null){const c=this.createDepthTexture();for(e of r)e.setDepthTexture(c)}else e.setDepthTexture(this.depthTexture)}removePass(e){const t=this.passes,r=t.indexOf(e);if(r!==-1&&t.splice(r,1).length>0){if(this.depthTexture!==null){const o=(c,l)=>c||l.needsDepthTexture;t.reduce(o,!1)||(e.getDepthTexture()===this.depthTexture&&e.setDepthTexture(null),this.deleteDepthTexture())}this.autoRenderToScreen&&r===t.length&&(e.renderToScreen=!1,t.length>0&&(t[t.length-1].renderToScreen=!0))}}removeAllPasses(){const e=this.passes;this.deleteDepthTexture(),e.length>0&&(this.autoRenderToScreen&&(e[e.length-1].renderToScreen=!1),this.passes=[])}render(e){const t=this.renderer,r=this.copyPass;let i=this.inputBuffer,s=this.outputBuffer,o=!1,a,c,l;e===void 0&&(this.timer.update(),e=this.timer.getDelta());for(const u of this.passes)u.enabled&&(u.render(t,i,s,e,o),u.needsSwap&&(o&&(r.renderToScreen=u.renderToScreen,a=t.getContext(),c=t.state.buffers.stencil,c.setFunc(a.NOTEQUAL,1,4294967295),r.render(t,i,s,e,o),c.setFunc(a.EQUAL,1,4294967295)),l=i,i=s,s=l),u instanceof FX?o=!0:u instanceof OX&&(o=!1))}setSize(e,t,r){const i=this.renderer,s=i.getSize(new St);(e===void 0||t===void 0)&&(e=s.width,t=s.height),(s.width!==e||s.height!==t)&&i.setSize(e,t,r);const o=i.getDrawingBufferSize(new St);this.inputBuffer.setSize(o.width,o.height),this.outputBuffer.setSize(o.width,o.height);for(const a of this.passes)a.setSize(o.width,o.height)}reset(){this.dispose(),this.autoRenderToScreen=!0}dispose(){for(const e of this.passes)e.dispose();this.passes=[],this.inputBuffer!==null&&this.inputBuffer.dispose(),this.outputBuffer!==null&&this.outputBuffer.dispose(),this.deleteDepthTexture(),this.copyPass.dispose(),this.timer.dispose(),zo.fullscreenGeometry.dispose()}},_a={NONE:0,DEPTH:1,CONVOLUTION:2},_n={FRAGMENT_HEAD:"FRAGMENT_HEAD",FRAGMENT_MAIN_UV:"FRAGMENT_MAIN_UV",FRAGMENT_MAIN_IMAGE:"FRAGMENT_MAIN_IMAGE",VERTEX_HEAD:"VERTEX_HEAD",VERTEX_MAIN_SUPPORT:"VERTEX_MAIN_SUPPORT"},zX=class{constructor(){this.shaderParts=new Map([[_n.FRAGMENT_HEAD,null],[_n.FRAGMENT_MAIN_UV,null],[_n.FRAGMENT_MAIN_IMAGE,null],[_n.VERTEX_HEAD,null],[_n.VERTEX_MAIN_SUPPORT,null]]),this.defines=new Map,this.uniforms=new Map,this.blendModes=new Map,this.extensions=new Set,this.attributes=_a.NONE,this.varyings=new Set,this.uvTransformation=!1,this.readDepth=!1,this.colorSpace=Fl}},DS=!1,u2=class{constructor(n=null){this.originalMaterials=new Map,this.material=null,this.materials=null,this.materialsBackSide=null,this.materialsDoubleSide=null,this.materialsFlatShaded=null,this.materialsFlatShadedBackSide=null,this.materialsFlatShadedDoubleSide=null,this.setMaterial(n),this.meshCount=0,this.replaceMaterial=e=>{if(e.isMesh){let t;if(e.material.flatShading)switch(e.material.side){case As:t=this.materialsFlatShadedDoubleSide;break;case ni:t=this.materialsFlatShadedBackSide;break;default:t=this.materialsFlatShaded;break}else switch(e.material.side){case As:t=this.materialsDoubleSide;break;case ni:t=this.materialsBackSide;break;default:t=this.materials;break}this.originalMaterials.set(e,e.material),e.isSkinnedMesh?e.material=t[2]:e.isInstancedMesh?e.material=t[1]:e.material=t[0],++this.meshCount}}}cloneMaterial(n){if(!(n instanceof Vi))return n.clone();const e=n.uniforms,t=new Map;for(const i in e){const s=e[i].value;s.isRenderTargetTexture&&(e[i].value=null,t.set(i,s))}const r=n.clone();for(const i of t)e[i[0]].value=i[1],r.uniforms[i[0]].value=i[1];return r}setMaterial(n){if(this.disposeMaterials(),this.material=n,n!==null){const e=this.materials=[this.cloneMaterial(n),this.cloneMaterial(n),this.cloneMaterial(n)];for(const t of e)t.uniforms=Object.assign({},n.uniforms),t.side=wc;e[2].skinning=!0,this.materialsBackSide=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.side=ni,r}),this.materialsDoubleSide=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.side=As,r}),this.materialsFlatShaded=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.flatShading=!0,r}),this.materialsFlatShadedBackSide=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.flatShading=!0,r.side=ni,r}),this.materialsFlatShadedDoubleSide=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.flatShading=!0,r.side=As,r})}}render(n,e,t){const r=n.shadowMap.enabled;if(n.shadowMap.enabled=!1,DS){const i=this.originalMaterials;this.meshCount=0,e.traverse(this.replaceMaterial),n.render(e,t);for(const s of i)s[0].material=s[1];this.meshCount!==i.size&&i.clear()}else{const i=e.overrideMaterial;e.overrideMaterial=this.material,n.render(e,t),e.overrideMaterial=i}n.shadowMap.enabled=r}disposeMaterials(){if(this.material!==null){const n=this.materials.concat(this.materialsBackSide).concat(this.materialsDoubleSide).concat(this.materialsFlatShaded).concat(this.materialsFlatShadedBackSide).concat(this.materialsFlatShadedDoubleSide);for(const e of n)e.dispose()}}dispose(){this.originalMaterials.clear(),this.disposeMaterials()}static get workaroundEnabled(){return DS}static set workaroundEnabled(n){DS=n}},hl=-1,gf=class extends Oc{constructor(n,e=hl,t=hl,r=1){super(),this.resizable=n,this.baseSize=new St(1,1),this.preferredSize=new St(e,t),this.target=this.preferredSize,this.s=r,this.effectiveSize=new St,this.addEventListener("change",()=>this.updateEffectiveSize()),this.updateEffectiveSize()}updateEffectiveSize(){const n=this.baseSize,e=this.preferredSize,t=this.effectiveSize,r=this.scale;e.width!==hl?t.width=e.width:e.height!==hl?t.width=Math.round(e.height*(n.width/Math.max(n.height,1))):t.width=Math.round(n.width*r),e.height!==hl?t.height=e.height:e.width!==hl?t.height=Math.round(e.width/Math.max(n.width/Math.max(n.height,1),1)):t.height=Math.round(n.height*r)}get width(){return this.effectiveSize.width}set width(n){this.preferredWidth=n}get height(){return this.effectiveSize.height}set height(n){this.preferredHeight=n}getWidth(){return this.width}getHeight(){return this.height}get scale(){return this.s}set scale(n){this.s!==n&&(this.s=n,this.preferredSize.setScalar(hl),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getScale(){return this.scale}setScale(n){this.scale=n}get baseWidth(){return this.baseSize.width}set baseWidth(n){this.baseSize.width!==n&&(this.baseSize.width=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseWidth(){return this.baseWidth}setBaseWidth(n){this.baseWidth=n}get baseHeight(){return this.baseSize.height}set baseHeight(n){this.baseSize.height!==n&&(this.baseSize.height=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseHeight(){return this.baseHeight}setBaseHeight(n){this.baseHeight=n}setBaseSize(n,e){(this.baseSize.width!==n||this.baseSize.height!==e)&&(this.baseSize.set(n,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}get preferredWidth(){return this.preferredSize.width}set preferredWidth(n){this.preferredSize.width!==n&&(this.preferredSize.width=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredWidth(){return this.preferredWidth}setPreferredWidth(n){this.preferredWidth=n}get preferredHeight(){return this.preferredSize.height}set preferredHeight(n){this.preferredSize.height!==n&&(this.preferredSize.height=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredHeight(){return this.preferredHeight}setPreferredHeight(n){this.preferredHeight=n}setPreferredSize(n,e){(this.preferredSize.width!==n||this.preferredSize.height!==e)&&(this.preferredSize.set(n,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}copy(n){this.s=n.scale,this.baseSize.set(n.baseWidth,n.baseHeight),this.preferredSize.set(n.preferredWidth,n.preferredHeight),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height)}static get AUTO_SIZE(){return hl}},Jt={SKIP:9,SET:30,ADD:0,ALPHA:1,AVERAGE:2,COLOR:3,COLOR_BURN:4,COLOR_DODGE:5,DARKEN:6,DIFFERENCE:7,DIVIDE:8,DST:9,EXCLUSION:10,HARD_LIGHT:11,HARD_MIX:12,HUE:13,INVERT:14,INVERT_RGB:15,LIGHTEN:16,LINEAR_BURN:17,LINEAR_DODGE:18,LINEAR_LIGHT:19,LUMINOSITY:20,MULTIPLY:21,NEGATION:22,NORMAL:23,OVERLAY:24,PIN_LIGHT:25,REFLECT:26,SATURATION:27,SCREEN:28,SOFT_LIGHT:29,SRC:30,SUBTRACT:31,VIVID_LIGHT:32},VX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x+y,opacity);}",HX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,min(y.a,opacity));}",GX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,(x+y)*0.5,opacity);}",WX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.rg,xHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",jX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(step(0.0,y)*(1.0-min(vec4(1.0),(1.0-x)/y)),vec4(1.0),step(1.0,x));return mix(x,z,opacity);}",$X="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=step(0.0,x)*mix(min(vec4(1.0),x/max(1.0-y,1e-9)),vec4(1.0),step(1.0,y));return mix(x,z,opacity);}",qX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,min(x,y),opacity);}",XX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,abs(x-y),opacity);}",KX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x/max(y,1e-12),opacity);}",YX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,(x+y-2.0*x*y),opacity);}",ZX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 a=min(x,1.0),b=min(y,1.0);vec4 z=mix(2.0*a*b,1.0-2.0*(1.0-a)*(1.0-b),step(0.5,y));return mix(x,z,opacity);}",QX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,step(1.0,x+y),opacity);}",JX="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.r,xHSL.gb));return vec4(mix(x.rgb,z,opacity),y.a);}",eK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,1.0-y,opacity);}",tK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y*(1.0-x),opacity);}",nK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,max(x,y),opacity);}",rK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,clamp(y+x-1.0,0.0,1.0),opacity);}",iK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,min(x+y,1.0),opacity);}",sK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,clamp(2.0*y+x-1.0,0.0,1.0),opacity);}",oK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.rg,yHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",aK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x*y,opacity);}",cK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,1.0-abs(1.0-x-y),opacity);}",lK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,opacity);}",uK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(2.0*y*x,1.0-2.0*(1.0-y)*(1.0-x),step(0.5,x));return mix(x,z,opacity);}",hK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 y2=2.0*y;vec4 z=mix(mix(y2,x,step(0.5*x,y)),max(vec4(0.0),y2-1.0),step(x,(y2-1.0)));return mix(x,z,opacity);}",fK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(min(x*x/max(1.0-y,1e-12),1.0),y,step(1.0,y));return mix(x,z,opacity);}",dK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.r,yHSL.g,xHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",pK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x+y-min(x*y,1.0),opacity);}",mK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 y2=2.0*y;vec4 w=step(0.5,y);vec4 z=mix(x-(1.0-y2)*x*(1.0-x),mix(x+(y2-1.0)*(sqrt(x)-x),x+(y2-1.0)*x*((16.0*x-12.0)*x+3.0),w*(1.0-step(0.25,x))),w);return mix(x,z,opacity);}",gK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return y;}",_K="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,max(x+y-1.0,0.0),opacity);}",vK="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(max(1.0-min((1.0-x)/(2.0*y),1.0),0.0),min(x/(2.0*(1.0-y)),1.0),step(0.5,y));return mix(x,z,opacity);}",yK=new Map([[Jt.ADD,VX],[Jt.ALPHA,HX],[Jt.AVERAGE,GX],[Jt.COLOR,WX],[Jt.COLOR_BURN,jX],[Jt.COLOR_DODGE,$X],[Jt.DARKEN,qX],[Jt.DIFFERENCE,XX],[Jt.DIVIDE,KX],[Jt.DST,null],[Jt.EXCLUSION,YX],[Jt.HARD_LIGHT,ZX],[Jt.HARD_MIX,QX],[Jt.HUE,JX],[Jt.INVERT,eK],[Jt.INVERT_RGB,tK],[Jt.LIGHTEN,nK],[Jt.LINEAR_BURN,rK],[Jt.LINEAR_DODGE,iK],[Jt.LINEAR_LIGHT,sK],[Jt.LUMINOSITY,oK],[Jt.MULTIPLY,aK],[Jt.NEGATION,cK],[Jt.NORMAL,lK],[Jt.OVERLAY,uK],[Jt.PIN_LIGHT,hK],[Jt.REFLECT,fK],[Jt.SATURATION,dK],[Jt.SCREEN,pK],[Jt.SOFT_LIGHT,mK],[Jt.SRC,gK],[Jt.SUBTRACT,_K],[Jt.VIVID_LIGHT,vK]]),xK=class extends Oc{constructor(n,e=1){super(),this._blendFunction=n,this.opacity=new Mn(e)}getOpacity(){return this.opacity.value}setOpacity(n){this.opacity.value=n}get blendFunction(){return this._blendFunction}set blendFunction(n){this._blendFunction=n,this.dispatchEvent({type:"change"})}getBlendFunction(){return this.blendFunction}setBlendFunction(n){this.blendFunction=n}getShaderCode(){return yK.get(this.blendFunction)}},LE=class extends Oc{constructor(n,e,{attributes:t=_a.NONE,blendFunction:r=Jt.NORMAL,defines:i=new Map,uniforms:s=new Map,extensions:o=null,vertexShader:a=null}={}){super(),this.name=n,this.renderer=null,this.attributes=t,this.fragmentShader=e,this.vertexShader=a,this.defines=i,this.uniforms=s,this.extensions=o,this.blendMode=new xK(r),this.blendMode.addEventListener("change",c=>this.setChanged()),this._inputColorSpace=Fl,this._outputColorSpace=ua}get inputColorSpace(){return this._inputColorSpace}set inputColorSpace(n){this._inputColorSpace=n,this.setChanged()}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(n){this._outputColorSpace=n,this.setChanged()}set mainScene(n){}set mainCamera(n){}getName(){return this.name}setRenderer(n){this.renderer=n}getDefines(){return this.defines}getUniforms(){return this.uniforms}getExtensions(){return this.extensions}getBlendMode(){return this.blendMode}getAttributes(){return this.attributes}setAttributes(n){this.attributes=n,this.setChanged()}getFragmentShader(){return this.fragmentShader}setFragmentShader(n){this.fragmentShader=n,this.setChanged()}getVertexShader(){return this.vertexShader}setVertexShader(n){this.vertexShader=n,this.setChanged()}setChanged(){this.dispatchEvent({type:"change"})}setDepthTexture(n,e=Yu){}update(n,e,t){}setSize(n,e){}initialize(n,e,t){}dispose(){for(const n of Object.keys(this)){const e=this[n];(e instanceof Ls||e instanceof Lc||e instanceof or||e instanceof zo)&&this[n].dispose()}}},l0={RED:0,GREEN:1,BLUE:2,ALPHA:3},GL=class extends zo{constructor(n,e,t=null){super("RenderPass",n,e),this.needsSwap=!1,this.clearPass=new HL,this.overrideMaterialManager=t===null?null:new u2(t),this.ignoreBackground=!1,this.skipShadowMapUpdate=!1,this.selection=null}set mainScene(n){this.scene=n}set mainCamera(n){this.camera=n}get renderToScreen(){return super.renderToScreen}set renderToScreen(n){super.renderToScreen=n,this.clearPass.renderToScreen=n}get overrideMaterial(){const n=this.overrideMaterialManager;return n!==null?n.material:null}set overrideMaterial(n){const e=this.overrideMaterialManager;n!==null?e!==null?e.setMaterial(n):this.overrideMaterialManager=new u2(n):e!==null&&(e.dispose(),this.overrideMaterialManager=null)}getOverrideMaterial(){return this.overrideMaterial}setOverrideMaterial(n){this.overrideMaterial=n}get clear(){return this.clearPass.enabled}set clear(n){this.clearPass.enabled=n}getSelection(){return this.selection}setSelection(n){this.selection=n}isBackgroundDisabled(){return this.ignoreBackground}setBackgroundDisabled(n){this.ignoreBackground=n}isShadowMapDisabled(){return this.skipShadowMapUpdate}setShadowMapDisabled(n){this.skipShadowMapUpdate=n}getClearPass(){return this.clearPass}render(n,e,t,r,i){const s=this.scene,o=this.camera,a=this.selection,c=o.layers.mask,l=s.background,u=n.shadowMap.autoUpdate,h=this.renderToScreen?null:e;a!==null&&o.layers.set(a.getLayer()),this.skipShadowMapUpdate&&(n.shadowMap.autoUpdate=!1),(this.ignoreBackground||this.clearPass.overrideClearColor!==null)&&(s.background=null),this.clearPass.enabled&&this.clearPass.render(n,e),n.setRenderTarget(h),this.overrideMaterialManager!==null?this.overrideMaterialManager.render(n,s,o):n.render(s,o),o.layers.mask=c,s.background=l,n.shadowMap.autoUpdate=u}},SK=`#include -#ifdef GL_FRAGMENT_PRECISION_HIGH -uniform highp sampler2D depthBuffer; -#else -uniform mediump sampler2D depthBuffer; -#endif -#ifdef DOWNSAMPLE_NORMALS -uniform lowp sampler2D normalBuffer; -#endif -varying vec2 vUv0;varying vec2 vUv1;varying vec2 vUv2;varying vec2 vUv3;float readDepth(const in vec2 uv){ -#if DEPTH_PACKING == 3201 -return unpackRGBAToDepth(texture2D(depthBuffer,uv)); -#else -return texture2D(depthBuffer,uv).r; -#endif -}int findBestDepth(const in float samples[4]){float c=(samples[0]+samples[1]+samples[2]+samples[3])*0.25;float distances[4];distances[0]=abs(c-samples[0]);distances[1]=abs(c-samples[1]);distances[2]=abs(c-samples[2]);distances[3]=abs(c-samples[3]);float maxDistance=max(max(distances[0],distances[1]),max(distances[2],distances[3]));int remaining[3];int rejected[3];int i,j,k;for(i=0,j=0,k=0;i<4;++i){if(distances[i]this.setSize(a.baseWidth,a.baseHeight))}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}setDepthTexture(n,e=Yu){this.fullscreenMaterial.depthBuffer=n,this.fullscreenMaterial.depthPacking=e}render(n,e,t,r,i){n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height),this.fullscreenMaterial.setSize(n,e)}initialize(n,e,t){const r=n.getContext();if(!(r.getExtension("EXT_color_buffer_float")||r.getExtension("EXT_color_buffer_half_float")))throw new Error("Rendering to float texture is not supported.")}},bK=`#include -#include -#include -#define packFloatToRGBA(v) packDepthToRGBA(v) -#define unpackRGBAToFloat(v) unpackRGBAToDepth(v) -#ifdef FRAMEBUFFER_PRECISION_HIGH -uniform mediump sampler2D inputBuffer; -#else -uniform lowp sampler2D inputBuffer; -#endif -#if DEPTH_PACKING == 3201 -uniform lowp sampler2D depthBuffer; -#elif defined(GL_FRAGMENT_PRECISION_HIGH) -uniform highp sampler2D depthBuffer; -#else -uniform mediump sampler2D depthBuffer; -#endif -uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;vec4 sRGBToLinear(const in vec4 value){return vec4(mix(pow(value.rgb*0.9478672986+vec3(0.0521327014),vec3(2.4)),value.rgb*0.0773993808,vec3(lessThanEqual(value.rgb,vec3(0.04045)))),value.a);}float readDepth(const in vec2 uv){ -#if DEPTH_PACKING == 3201 -return unpackRGBAToDepth(texture2D(depthBuffer,uv)); -#else -return texture2D(depthBuffer,uv).r; -#endif -}float getViewZ(const in float depth){ -#ifdef PERSPECTIVE_CAMERA -return perspectiveDepthToViewZ(depth,cameraNear,cameraFar); -#else -return orthographicDepthToViewZ(depth,cameraNear,cameraFar); -#endif -}vec3 RGBToHCV(const in vec3 RGB){vec4 P=mix(vec4(RGB.bg,-1.0,2.0/3.0),vec4(RGB.gb,0.0,-1.0/3.0),step(RGB.b,RGB.g));vec4 Q=mix(vec4(P.xyw,RGB.r),vec4(RGB.r,P.yzx),step(P.x,RGB.r));float C=Q.x-min(Q.w,Q.y);float H=abs((Q.w-Q.y)/(6.0*C+EPSILON)+Q.z);return vec3(H,C,Q.x);}vec3 RGBToHSL(const in vec3 RGB){vec3 HCV=RGBToHCV(RGB);float L=HCV.z-HCV.y*0.5;float S=HCV.y/(1.0-abs(L*2.0-1.0)+EPSILON);return vec3(HCV.x,S,L);}vec3 HueToRGB(const in float H){float R=abs(H*6.0-3.0)-1.0;float G=2.0-abs(H*6.0-2.0);float B=2.0-abs(H*6.0-4.0);return clamp(vec3(R,G,B),0.0,1.0);}vec3 HSLToRGB(const in vec3 HSL){vec3 RGB=HueToRGB(HSL.x);float C=(1.0-abs(2.0*HSL.z-1.0))*HSL.y;return(RGB-0.5)*C+HSL.z;}FRAGMENT_HEAD void main(){FRAGMENT_MAIN_UV vec4 color0=texture2D(inputBuffer,UV);vec4 color1=vec4(0.0);FRAGMENT_MAIN_IMAGE color0.a=clamp(color0.a,0.0,1.0);gl_FragColor=color0; -#ifdef ENCODE_OUTPUT -#include -#endif -#include -}`,AK="uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;VERTEX_HEAD void main(){vUv=position.xy*0.5+0.5;VERTEX_MAIN_SUPPORT gl_Position=vec4(position.xy,1.0,1.0);}",MK=class extends Vi{constructor(n,e,t,r,i=!1){super({name:"EffectMaterial",defines:{THREE_REVISION:mv.replace(/\D+/g,""),DEPTH_PACKING:"0",ENCODE_OUTPUT:"1"},uniforms:{inputBuffer:new Mn(null),depthBuffer:new Mn(null),resolution:new Mn(new St),texelSize:new Mn(new St),cameraNear:new Mn(.3),cameraFar:new Mn(1e3),aspect:new Mn(1),time:new Mn(0)},blending:Ao,toneMapped:!1,depthWrite:!1,depthTest:!1,dithering:i}),n&&this.setShaderParts(n),e&&this.setDefines(e),t&&this.setUniforms(t),this.copyCameraSettings(r)}set inputBuffer(n){this.uniforms.inputBuffer.value=n}setInputBuffer(n){this.uniforms.inputBuffer.value=n}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(n){this.uniforms.depthBuffer.value=n}get depthPacking(){return Number(this.defines.DEPTH_PACKING)}set depthPacking(n){this.defines.DEPTH_PACKING=n.toFixed(0),this.needsUpdate=!0}setDepthBuffer(n,e=Yu){this.depthBuffer=n,this.depthPacking=e}setShaderData(n){this.setShaderParts(n.shaderParts),this.setDefines(n.defines),this.setUniforms(n.uniforms),this.setExtensions(n.extensions)}setShaderParts(n){return this.fragmentShader=bK.replace(_n.FRAGMENT_HEAD,n.get(_n.FRAGMENT_HEAD)||"").replace(_n.FRAGMENT_MAIN_UV,n.get(_n.FRAGMENT_MAIN_UV)||"").replace(_n.FRAGMENT_MAIN_IMAGE,n.get(_n.FRAGMENT_MAIN_IMAGE)||""),this.vertexShader=AK.replace(_n.VERTEX_HEAD,n.get(_n.VERTEX_HEAD)||"").replace(_n.VERTEX_MAIN_SUPPORT,n.get(_n.VERTEX_MAIN_SUPPORT)||""),this.needsUpdate=!0,this}setDefines(n){for(const e of n.entries())this.defines[e[0]]=e[1];return this.needsUpdate=!0,this}setUniforms(n){for(const e of n.entries())this.uniforms[e[0]]=e[1];return this}setExtensions(n){this.extensions={};for(const e of n)this.extensions[e]=!0;return this}get encodeOutput(){return this.defines.ENCODE_OUTPUT!==void 0}set encodeOutput(n){this.encodeOutput!==n&&(n?this.defines.ENCODE_OUTPUT="1":delete this.defines.ENCODE_OUTPUT,this.needsUpdate=!0)}isOutputEncodingEnabled(n){return this.encodeOutput}setOutputEncodingEnabled(n){this.encodeOutput=n}get time(){return this.uniforms.time.value}set time(n){this.uniforms.time.value=n}setDeltaTime(n){this.uniforms.time.value+=n}adoptCameraSettings(n){this.copyCameraSettings(n)}copyCameraSettings(n){n&&(this.uniforms.cameraNear.value=n.near,this.uniforms.cameraFar.value=n.far,n instanceof Ts?this.defines.PERSPECTIVE_CAMERA="1":delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0)}setSize(n,e){const t=this.uniforms;t.resolution.value.set(n,e),t.texelSize.value.set(1/n,1/e),t.aspect.value=n/e}static get Section(){return _n}};function h2(n,e,t){for(const r of e){const i="$1"+n+r.charAt(0).toUpperCase()+r.slice(1),s=new RegExp("([^\\.])(\\b"+r+"\\b)","g");for(const o of t.entries())o[1]!==null&&t.set(o[0],o[1].replace(s,i))}}function CK(n,e,t){let r=e.getFragmentShader(),i=e.getVertexShader();const s=r!==void 0&&/mainImage/.test(r),o=r!==void 0&&/mainUv/.test(r);if(t.attributes|=e.getAttributes(),r===void 0)throw new Error(`Missing fragment shader (${e.name})`);if(o&&t.attributes&_a.CONVOLUTION)throw new Error(`Effects that transform UVs are incompatible with convolution effects (${e.name})`);if(!s&&!o)throw new Error(`Could not find mainImage or mainUv function (${e.name})`);{const a=/\w+\s+(\w+)\([\w\s,]*\)\s*{/g,c=t.shaderParts;let l=c.get(_n.FRAGMENT_HEAD)||"",u=c.get(_n.FRAGMENT_MAIN_UV)||"",h=c.get(_n.FRAGMENT_MAIN_IMAGE)||"",p=c.get(_n.VERTEX_HEAD)||"",m=c.get(_n.VERTEX_MAIN_SUPPORT)||"";const g=new Set,v=new Set;if(o&&(u+=` ${n}MainUv(UV); -`,t.uvTransformation=!0),i!==null&&/mainSupport/.test(i)){const S=/mainSupport *\([\w\s]*?uv\s*?\)/.test(i);m+=` ${n}MainSupport(`,m+=S?`vUv); -`:`); -`;for(const w of i.matchAll(/(?:varying\s+\w+\s+([\S\s]*?);)/g))for(const T of w[1].split(/\s*,\s*/))t.varyings.add(T),g.add(T),v.add(T);for(const w of i.matchAll(a))v.add(w[1])}for(const S of r.matchAll(a))v.add(S[1]);for(const S of e.defines.keys())v.add(S.replace(/\([\w\s,]*\)/g,""));for(const S of e.uniforms.keys())v.add(S);v.delete("while"),v.delete("for"),v.delete("if"),e.uniforms.forEach((S,w)=>t.uniforms.set(n+w.charAt(0).toUpperCase()+w.slice(1),S)),e.defines.forEach((S,w)=>t.defines.set(n+w.charAt(0).toUpperCase()+w.slice(1),S));const y=new Map([["fragment",r],["vertex",i]]);h2(n,v,t.defines),h2(n,v,y),r=y.get("fragment"),i=y.get("vertex");const _=e.blendMode;if(t.blendModes.set(_.blendFunction,_),s){e.inputColorSpace!==null&&e.inputColorSpace!==t.colorSpace&&(h+=e.inputColorSpace===pr?`color0 = sRGBTransferOETF(color0); - `:`color0 = sRGBToLinear(color0); - `),e.outputColorSpace!==ua?t.colorSpace=e.outputColorSpace:e.inputColorSpace!==null&&(t.colorSpace=e.inputColorSpace);const S=/MainImage *\([\w\s,]*?depth[\w\s,]*?\)/;h+=`${n}MainImage(color0, UV, `,t.attributes&_a.DEPTH&&S.test(r)&&(h+="depth, ",t.readDepth=!0),h+=`color1); - `;const w=n+"BlendOpacity";t.uniforms.set(w,_.opacity),h+=`color0 = blend${_.blendFunction}(color0, color1, ${w}); - - `,l+=`uniform float ${w}; - -`}if(l+=r+` -`,i!==null&&(p+=i+` -`),c.set(_n.FRAGMENT_HEAD,l),c.set(_n.FRAGMENT_MAIN_UV,u),c.set(_n.FRAGMENT_MAIN_IMAGE,h),c.set(_n.VERTEX_HEAD,p),c.set(_n.VERTEX_MAIN_SUPPORT,m),e.extensions!==null)for(const S of e.extensions)t.extensions.add(S)}}var RK=class extends zo{constructor(n,...e){super("EffectPass"),this.fullscreenMaterial=new MK(null,null,null,n),this.listener=t=>this.handleEvent(t),this.effects=[],this.setEffects(e),this.skipRendering=!1,this.minTime=1,this.maxTime=Number.POSITIVE_INFINITY,this.timeScale=1}set mainScene(n){for(const e of this.effects)e.mainScene=n}set mainCamera(n){this.fullscreenMaterial.copyCameraSettings(n);for(const e of this.effects)e.mainCamera=n}get encodeOutput(){return this.fullscreenMaterial.encodeOutput}set encodeOutput(n){this.fullscreenMaterial.encodeOutput=n}get dithering(){return this.fullscreenMaterial.dithering}set dithering(n){const e=this.fullscreenMaterial;e.dithering=n,e.needsUpdate=!0}setEffects(n){for(const e of this.effects)e.removeEventListener("change",this.listener);this.effects=n.sort((e,t)=>t.attributes-e.attributes);for(const e of this.effects)e.addEventListener("change",this.listener)}updateMaterial(){const n=new zX;let e=0;for(const o of this.effects)if(o.blendMode.blendFunction===Jt.DST)n.attributes|=o.getAttributes()&_a.DEPTH;else{if(n.attributes&o.getAttributes()&_a.CONVOLUTION)throw new Error(`Convolution effects cannot be merged (${o.name})`);CK("e"+e++,o,n)}let t=n.shaderParts.get(_n.FRAGMENT_HEAD),r=n.shaderParts.get(_n.FRAGMENT_MAIN_IMAGE),i=n.shaderParts.get(_n.FRAGMENT_MAIN_UV);const s=/\bblend\b/g;for(const o of n.blendModes.values())t+=o.getShaderCode().replace(s,`blend${o.blendFunction}`)+` -`;n.attributes&_a.DEPTH?(n.readDepth&&(r=`float depth = readDepth(UV); - - `+r),this.needsDepthTexture=this.getDepthTexture()===null):this.needsDepthTexture=!1,n.colorSpace===pr&&(r+=`color0 = sRGBToLinear(color0); - `),n.uvTransformation?(i=`vec2 transformedUv = vUv; -`+i,n.defines.set("UV","transformedUv")):n.defines.set("UV","vUv"),n.shaderParts.set(_n.FRAGMENT_HEAD,t),n.shaderParts.set(_n.FRAGMENT_MAIN_IMAGE,r),n.shaderParts.set(_n.FRAGMENT_MAIN_UV,i);for(const[o,a]of n.shaderParts)a!==null&&n.shaderParts.set(o,a.trim().replace(/^#/,` -#`));this.skipRendering=e===0,this.needsSwap=!this.skipRendering,this.fullscreenMaterial.setShaderData(n)}recompile(){this.updateMaterial()}getDepthTexture(){return this.fullscreenMaterial.depthBuffer}setDepthTexture(n,e=Yu){this.fullscreenMaterial.depthBuffer=n,this.fullscreenMaterial.depthPacking=e;for(const t of this.effects)t.setDepthTexture(n,e)}render(n,e,t,r,i){for(const s of this.effects)s.update(n,e,r);if(!this.skipRendering||this.renderToScreen){const s=this.fullscreenMaterial;s.inputBuffer=e.texture,s.time+=r*this.timeScale,n.setRenderTarget(this.renderToScreen?null:t),n.render(this.scene,this.camera)}}setSize(n,e){this.fullscreenMaterial.setSize(n,e);for(const t of this.effects)t.setSize(n,e)}initialize(n,e,t){this.renderer=n;for(const r of this.effects)r.initialize(n,e,t);this.updateMaterial(),t!==void 0&&t!==Ei&&(this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}dispose(){super.dispose();for(const n of this.effects)n.removeEventListener("change",this.listener),n.dispose()}handleEvent(n){switch(n.type){case"change":this.recompile();break}}},kK=class extends zo{constructor(n,e,{renderTarget:t,resolutionScale:r=1,width:i=gf.AUTO_SIZE,height:s=gf.AUTO_SIZE,resolutionX:o=i,resolutionY:a=s}={}){super("NormalPass"),this.needsSwap=!1,this.renderPass=new GL(n,e,new NH);const c=this.renderPass;c.ignoreBackground=!0,c.skipShadowMapUpdate=!0;const l=c.getClearPass();l.overrideClearColor=new cn(7829503),l.overrideClearAlpha=1,this.renderTarget=t,this.renderTarget===void 0&&(this.renderTarget=new Ls(1,1,{minFilter:vr,magFilter:vr}),this.renderTarget.texture.name="NormalPass.Target");const u=this.resolution=new gf(this,o,a,r);u.addEventListener("change",h=>this.setSize(u.baseWidth,u.baseHeight))}set mainScene(n){this.renderPass.mainScene=n}set mainCamera(n){this.renderPass.mainCamera=n}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}getResolutionScale(){return this.resolution.scale}setResolutionScale(n){this.resolution.scale=n}render(n,e,t,r,i){const s=this.renderToScreen?null:this.renderTarget;this.renderPass.render(n,s,s)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height)}};let Dd;function IK(){var n;if(Dd!==void 0)return Dd;try{let e;const t=document.createElement("canvas");return Dd=!!(window.WebGL2RenderingContext&&(e=t.getContext("webgl2"))),e&&((n=e.getExtension("WEBGL_lose_context"))==null||n.loseContext()),Dd}catch{return Dd=!1}}const NK=ke.createContext(null),f2=n=>(n.getAttributes()&_a.CONVOLUTION)===_a.CONVOLUTION,OK=bo.memo(ke.forwardRef(({children:n,camera:e,scene:t,resolutionScale:r,enabled:i=!0,renderPriority:s=1,autoClear:o=!0,depthBuffer:a,enableNormalPass:c,stencilBuffer:l,multisampling:u=8,frameBufferType:h=Qf},p)=>{const{gl:m,scene:g,camera:v,size:y}=pa(),_=t||g,S=e||v,[w,T,k]=ke.useMemo(()=>{const M=IK(),N=new BX(m,{depthBuffer:a,stencilBuffer:l,multisampling:u>0&&M?u:0,frameBufferType:h});N.addPass(new GL(_,S));let U=null,L=null;return c&&(L=new kK(_,S),L.enabled=!1,N.addPass(L),r!==void 0&&M&&(U=new TK({normalBuffer:L.texture,resolutionScale:r}),U.enabled=!1,N.addPass(U))),[N,L,U]},[S,m,a,l,u,h,_,c,r]);ke.useEffect(()=>w==null?void 0:w.setSize(y.width,y.height),[w,y]),Tv((M,N)=>{if(i){const U=m.autoClear;m.autoClear=o,l&&!o&&m.clearStencil(),w.render(N),m.autoClear=U}},i?s:0);const R=ke.useRef(null),C=hG(R);ke.useLayoutEffect(()=>{const M=[];if(R.current&&C.current&&w){const N=C.current.objects;for(let U=0;U{for(const N of M)w==null||w.removePass(N);T&&(T.enabled=!1),k&&(k.enabled=!1)}},[w,n,S,T,k,C]),ke.useEffect(()=>{const M=m.toneMapping;return m.toneMapping=ma,()=>{m.toneMapping=M}},[]);const O=ke.useMemo(()=>({composer:w,normalPass:T,downSamplingPass:k,resolutionScale:r,camera:S,scene:_}),[w,T,k,r,S,_]);return ke.useImperativeHandle(p,()=>w,[w]),_e.jsx(NK.Provider,{value:O,children:_e.jsx("group",{ref:R,children:n})})}));let LK=0;const d2=new WeakMap,PK=(n,e)=>bo.forwardRef(function({blendFunction:r=void 0,opacity:i=void 0,...s},o){let a=d2.get(n);if(!a){const u=`@react-three/postprocessing/${n.name}-${LK++}`;sT({[u]:n}),d2.set(n,a=u)}const c=pa(u=>u.camera),l=bo.useMemo(()=>{var u,h;return[...(u=void 0)!=null?u:[],...(h=s.args)!=null?h:[{...e,...s}]]},[JSON.stringify(s)]);return _e.jsx(a,{camera:c,"blendMode-blendFunction":r,"blendMode-opacity-value":i,...s,ref:o,args:l})});function US(n,e,t,r){return new(t||(t=Promise))(function(i,s){function o(l){try{c(r.next(l))}catch(u){s(u)}}function a(l){try{c(r.throw(l))}catch(u){s(u)}}function c(l){var u;l.done?i(l.value):(u=l.value,u instanceof t?u:new t(function(h){h(u)})).then(o,a)}c((r=r.apply(n,[])).next())})}const DK=["geforce 320m","geforce 8600","geforce 8600m gt","geforce 8800 gs","geforce 8800 gt","geforce 9400","geforce 9400m g","geforce 9400m","geforce 9600m gt","geforce 9600m","geforce fx go5200","geforce gt 120","geforce gt 130","geforce gt 330m","geforce gtx 285","google swiftshader","intel g41","intel g45","intel gma 4500mhd","intel gma x3100","intel hd 3000","intel q45","legacy","mali-2","mali-3","mali-4","quadro fx 1500","quadro fx 4","quadro fx 5","radeon hd 2400","radeon hd 2600","radeon hd 4670","radeon hd 4850","radeon hd 4870","radeon hd 5670","radeon hd 5750","radeon hd 6290","radeon hd 6300","radeon hd 6310","radeon hd 6320","radeon hd 6490m","radeon hd 6630m","radeon hd 6750m","radeon hd 6770m","radeon hd 6970m","sgx 543","sgx543"];function p2(n){return n=n.toLowerCase().replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i,"$1").replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g,"").replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/,"$1")}const WL=typeof window>"u",oa=(()=>{if(WL)return;const{userAgent:n,platform:e,maxTouchPoints:t}=window.navigator,r=/(iphone|ipod|ipad)/i.test(n),i=e==="iPad"||e==="MacIntel"&&t>0&&!window.MSStream;return{isIpad:i,isMobile:/android/i.test(n)||r||i,isSafari12:/Version\/12.+Safari/.test(n),isFirefox:/Firefox/.test(n)}})();function UK(n,e,t){if(!t)return[e];const r=function(l){const u=` - precision highp float; - attribute vec3 aPosition; - varying float vvv; - void main() { - vvv = 0.31622776601683794; - gl_Position = vec4(aPosition, 1.0); - } - `,h=` - precision highp float; - varying float vvv; - void main() { - vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * vvv; - enc = fract(enc); - enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); - gl_FragColor = enc; - } - `,p=l.createShader(35633),m=l.createShader(35632),g=l.createProgram();if(!(m&&p&&g))return;l.shaderSource(p,u),l.shaderSource(m,h),l.compileShader(p),l.compileShader(m),l.attachShader(g,p),l.attachShader(g,m),l.linkProgram(g),l.detachShader(g,p),l.detachShader(g,m),l.deleteShader(p),l.deleteShader(m),l.useProgram(g);const v=l.createBuffer();l.bindBuffer(34962,v),l.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const y=l.getAttribLocation(g,"aPosition");l.vertexAttribPointer(y,3,5126,!1,0,0),l.enableVertexAttribArray(y),l.clearColor(1,1,1,1),l.clear(16384),l.viewport(0,0,1,1),l.drawArrays(4,0,3);const _=new Uint8Array(4);return l.readPixels(0,0,1,1,6408,5121,_),l.deleteProgram(g),l.deleteBuffer(v),_.join("")}(n),i="801621810",s="8016218135",o="80162181161",a=oa!=null&&oa.isIpad?[["a7",o,12],["a8",s,15],["a8x",s,15],["a9",s,15],["a9x",s,15],["a10",s,15],["a10x",s,15],["a12",i,15],["a12x",i,15],["a12z",i,15],["a14",i,15],["a15",i,15],["m1",i,15],["m2",i,15]]:[["a7",o,12],["a8",s,12],["a9",s,15],["a10",s,15],["a11",i,15],["a12",i,15],["a13",i,15],["a14",i,15],["a15",i,15],["a16",i,15],["a17",i,15]];let c;return r==="80162181255"?c=a.filter(([,,l])=>l>=14):(c=a.filter(([,l])=>l===r),c.length||(c=a)),c.map(([l])=>`apple ${l} gpu`)}class m2 extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const FS=[],g2=[];function FK(n,e){if(n===e)return 0;const t=n;n.length>e.length&&(n=e,e=t);let r=n.length,i=e.length;for(;r>0&&n.charCodeAt(~-r)===e.charCodeAt(~-i);)r--,i--;let s,o=0;for(;ol?c>l?l+1:c:c>a?a+1:c;return l}function BK(n){return n!=null}const zK=({mobileTiers:n=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:t={},glContext:r,failIfMajorPerformanceCaveat:i=!1,benchmarksURL:s="https://unpkg.com/detect-gpu@5.0.56/dist/benchmarks"}={})=>US(void 0,void 0,void 0,function*(){const o={};if(WL)return{tier:0,type:"SSR"};const{isIpad:a=!!(oa!=null&&oa.isIpad),isMobile:c=!!(oa!=null&&oa.isMobile),screenSize:l=window.screen,loadBenchmarks:u=k=>US(void 0,void 0,void 0,function*(){const R=yield fetch(`${s}/${k}`).then(C=>C.json());if(parseInt(R.shift().split(".")[0],10)<4)throw new m2("Detect GPU benchmark data is out of date. Please update to version 4x");return R})}=t;let{renderer:h}=t;const p=(k,R,C,O,M)=>({device:M,fps:O,gpu:C,isMobile:c,tier:k,type:R});let m,g="";if(h)h=p2(h),m=[h];else{const k=r||function(C,O=!1){const M={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:O,powerPreference:"high-performance",stencil:!1};C&&delete M.powerPreference;const N=window.document.createElement("canvas"),U=N.getContext("webgl",M)||N.getContext("experimental-webgl",M);return U??void 0}(oa==null?void 0:oa.isSafari12,i);if(!k)return p(0,"WEBGL_UNSUPPORTED");const R=oa!=null&&oa.isFirefox?null:k.getExtension("WEBGL_debug_renderer_info");if(h=R?k.getParameter(R.UNMASKED_RENDERER_WEBGL):k.getParameter(k.RENDERER),!h)return p(1,"FALLBACK");g=h,h=p2(h),m=function(C,O,M){return O==="apple gpu"?UK(C,O,M):[O]}(k,h,c)}const v=(yield Promise.all(m.map(function(k){var R;return US(this,void 0,void 0,function*(){const C=(ve=>{const ne=c?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const ie of ne)if(ve.includes(ie))return ie})(k);if(!C)return;const O=`${c?"m":"d"}-${C}${a?"-ipad":""}.json`,M=o[O]=(R=o[O])!==null&&R!==void 0?R:u(O);let N;try{N=yield M}catch(ve){if(ve instanceof m2)throw ve;return}const U=function(ve){var ne;const ie=(ve=ve.replace(/\([^)]+\)/,"")).match(/\d+/)||ve.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(ne=ie==null?void 0:ie.join("").replace(/\W|amd/g,""))!==null&&ne!==void 0?ne:""}(k);let L=N.filter(([,ve])=>ve===U);L.length||(L=N.filter(([ve])=>ve.includes(k)));const P=L.length;if(P===0)return;const b=k.split(/[.,()\[\]/\s]/g).sort().filter((ve,ne,ie)=>ne===0||ve!==ie[ne-1]).join(" ");let B,[W,,,,V]=P>1?L.map(ve=>[ve,FK(b,ve[2])]).sort(([,ve],[,ne])=>ve-ne)[0][0]:L[0],G=Number.MAX_VALUE;const{devicePixelRatio:$}=window,Z=l.width*$*l.height*$;for(const ve of V){const[ne,ie]=ve,be=ne*ie,Ce=Math.abs(Z-be);Cek===C?R-O:k-C);if(!v.length){const k=DK.find(R=>h.includes(R));return k?p(0,"BLOCKLISTED",k):p(1,"FALLBACK",`${h} (${g})`)}const[,y,_,S]=v[0];if(y===-1)return p(0,"BLOCKLISTED",_,y,S);const w=c?n:e;let T=0;for(let k=0;k=w[k]&&(T=k);return p(T,"BENCHMARK",_,y,S)});var jL={exports:{}};(function(n,e){(function(t,r){n.exports=r()})(Eo,function(){var t=function(){function r(m){return o.appendChild(m.dom),m}function i(m){for(var g=0;gc+1e3&&(u.update(1e3*l/(m-c),100),c=m,l=0,p)){var g=performance.memory;p.update(g.usedJSHeapSize/1048576,g.jsHeapSizeLimit/1048576)}return m},update:function(){a=this.end()},domElement:o,setMode:i}};return t.Panel=function(r,i,s){var o=1/0,a=0,c=Math.round,l=c(window.devicePixelRatio||1),u=80*l,h=48*l,p=3*l,m=2*l,g=3*l,v=15*l,y=74*l,_=30*l,S=document.createElement("canvas");S.width=u,S.height=h,S.style.cssText="width:80px;height:48px";var w=S.getContext("2d");return w.font="bold "+9*l+"px Helvetica,Arial,sans-serif",w.textBaseline="top",w.fillStyle=s,w.fillRect(0,0,u,h),w.fillStyle=i,w.fillText(r,p,m),w.fillRect(g,v,y,_),w.fillStyle=s,w.globalAlpha=.9,w.fillRect(g,v,y,_),{dom:S,update:function(T,k){o=Math.min(o,T),a=Math.max(a,T),w.fillStyle=s,w.globalAlpha=1,w.fillRect(0,0,u,v),w.fillStyle=i,w.fillText(c(T)+" "+r+" ("+c(o)+"-"+c(a)+")",p,m),w.drawImage(S,g+l,v,y-l,_,g,v,y-l,_),w.fillRect(g+y-l,v,l,_),w.fillStyle=s,w.globalAlpha=.9,w.fillRect(g+y-l,v,l,c((1-T/k)*_))}}},t})})(jL);var VK=jL.exports;const HK=Nc(VK),ba=!!JSON.parse("false"),GK=!!JSON.parse("false"),WK=!!JSON.parse("false"),jK=!!JSON.parse("false");JSON.parse("false");const $K=!!JSON.parse("false"),qK=` -vec3 halftone(vec3 texcolor, vec2 st, float frequency) { - float n = 0.1 * snoise(st * 200.0); // Fractal noise - n += 0.05 * snoise(st * 400.0); - n += 0.025 * snoise(st * 800.0); - - // Perform a rough RGB-to-CMYK conversion - vec4 cmyk; - // CMY = 1-RGB - cmyk.xyz = 1.0 - texcolor; - // Black generation: K = min(C,M,Y) - cmyk.w = min(cmyk.x, min(cmyk.y, cmyk.z)); - // Grey component replacement: subtract K from CMY - cmyk.xyz -= cmyk.w; - - // K based modifier - float flex = pow(cmyk.w, 3.11); - - // Distance to nearest point in a grid of - // (frequency x frequency) points over the unit square - - float t = 0.1 + 0.1 * n + 0.11 * flex + 0.1 * cmyk.y; - - // K component: 45 degrees screen angle - vec2 Kst = frequency * mat2(0.707, -0.707, 0.707, 0.707) * st; - vec2 Kuv = 2.0 * fract(Kst) - 1.0; - float k = aastep(0.0, sqrt(cmyk.w) + t - length(Kuv) + n); - - // C component: 15 degrees screen angle - vec2 Cst = frequency*mat2(0.966, -0.259, 0.259, 0.966) * st; - vec2 Cuv = 2.0 * fract(Cst) - 1.0; - float c = aastep(0.0, sqrt(cmyk.x) + t - length(Cuv) + n); - - // M component: -15 degrees screen angle - vec2 Mst = frequency * mat2(0.966, 0.259, -0.259, 0.966) * st; - vec2 Muv = 2.0 * fract(Mst) - 1.0; - float m = aastep(0.0, sqrt(cmyk.y) + t - length(Muv) + n); - - // Y component: 0 degrees screen angle - vec2 Yst = frequency * st; // 0 deg - vec2 Yuv = 2.0 * fract(Yst) - 1.0; - float y = aastep(0.0, sqrt(cmyk.z) + t - length(Yuv) + n); - - // CMY screen in RGB - vec3 black = vec3(n + 0.01); - vec3 rgbscreen = 1.0 - vec3(c,m,y) + n; - - // Blend in K for final color - vec3 factor = mix(rgbscreen, black, 1.1 * k + 0.3 * n); - - // Blend with og color - return mix(factor, texcolor, 0.777); -} - -vec3 halftone(vec3 texcolor, vec2 st) { - return halftone(texcolor, st, 412.321); -} -`,XK=` -float blendLighten(float base, float blend) { - return max(blend,base); -} - -vec3 blendLighten(vec3 base, vec3 blend) { - return vec3(blendLighten(base.r,blend.r),blendLighten(base.g,blend.g),blendLighten(base.b,blend.b)); -} - -vec3 blendLighten(vec3 base, vec3 blend, float opacity) { - return (blendLighten(base, blend) * opacity + base * (1.0 - opacity)); -} - -float blendDarken(float base, float blend) { - return min(blend,base); -} - -vec3 blendDarken(vec3 base, vec3 blend) { - return vec3(blendDarken(base.r,blend.r),blendDarken(base.g,blend.g),blendDarken(base.b,blend.b)); -} - -vec3 blendDarken(vec3 base, vec3 blend, float opacity) { - return (blendDarken(base, blend) * opacity + base * (1.0 - opacity)); -} -`,KK=` -float aastep(float threshold, float value) { - float afwidth = length(vec2(dFdx(value), dFdy(value))) * 0.70710678118654757; - return smoothstep(threshold-afwidth, threshold+afwidth, value); -} -`,YK=` -// -// Description : Array and textureless GLSL 2D simplex noise function. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : ijm -// Lastmod : 20110822 (ijm) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -vec3 mod289(vec3 x) { - return x - floor(x * (1.0 / 289.0)) * 289.0; -} - -vec2 mod289(vec2 x) { - return x - floor(x * (1.0 / 289.0)) * 289.0; -} - -vec3 permute(vec3 x) { - return mod289(((x*34.0)+1.0)*x); -} - -float snoise(vec2 v) { - const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0 - 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) - -0.577350269189626, // -1.0 + 2.0 * C.x - 0.024390243902439); // 1.0 / 41.0 -// First corner - vec2 i = floor(v + dot(v, C.yy) ); - vec2 x0 = v - i + dot(i, C.xx); - -// Other corners - vec2 i1; - //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0 - //i1.y = 1.0 - i1.x; - i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - // x0 = x0 - 0.0 + 0.0 * C.xx ; - // x1 = x0 - i1 + 1.0 * C.xx ; - // x2 = x0 - 1.0 + 2.0 * C.xx ; - vec4 x12 = x0.xyxy + C.xxzz; - x12.xy -= i1; - -// Permutations - i = mod289(i); // Avoid truncation effects in permutation - vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 )) - + i.x + vec3(0.0, i1.x, 1.0 )); - - vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0); - m = m*m ; - m = m*m ; - -// Gradients: 41 points uniformly over a line, mapped onto a diamond. -// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) - - vec3 x = 2.0 * fract(p * C.www) - 1.0; - vec3 h = abs(x) - 0.5; - vec3 ox = floor(x + 0.5); - vec3 a0 = x - ox; - -// Normalise gradients implicitly by scaling m -// Approximation of: m *= inversesqrt( a0*a0 + h*h ); - m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ); - -// Compute final noise value at P - vec3 g; - g.x = a0.x * x0.x + h.x * x0.y; - g.yz = a0.yz * x12.xz + h.yz * x12.yw; - return 130.0 * dot(m, g); -} -`,ZK=` -#ifdef ASPECT_CORRECTION - uniform float scale; -#else - uniform mat3 uvTransform; -#endif - -varying vec2 vUv2; - -void mainSupport(const in vec2 uv) { - #ifdef ASPECT_CORRECTION - vUv2 = uv * vec2(aspect, 1.0) * scale; - #else - vUv2 = (uvTransform * vec3(uv, 1.0)).xy; - #endif -} -`,QK=` -uniform float viewheight; -uniform sampler2D splat; - -${XK} -${KK} -${YK} -${qK} - -float rectdistance(vec2 uv) { - vec2 tl = vec2(-1.0); - vec2 br = vec2(1.0); - vec2 d = max(tl - uv, uv - br); - return abs(length(max(vec2(0.0), d)) + min(0.0, max(d.x, d.y))); -} - -vec2 bendy(const in vec2 xn, float dn, float sn) { - // config - float distortion = 0.0173 + dn; // 0.0173, 0.511 - float scale = 0.991 + sn; // 1.0, 0.7 - // calc - vec3 xDistorted = vec3((1.0 + vec2(distortion, distortion) * dot(xn, xn)) * xn, 1.0); - mat3 kk = mat3( - vec3(1.0, 0.0, 0.0), - vec3(0.0, 1.0, 0.0), - vec3(0.0, 0.0, 1.0) - ); - return (kk * xDistorted).xy * scale; -} - -void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) { - #ifdef UV_TRANSFORM - vec4 bright = texture2D(splat, vUv2); - vec4 dark = texture2D(splat, 1.0 - vUv2); - #else - vec4 bright = texture2D(splat, uv); - vec4 dark = texture2D(splat, 1.0 - uv); - #endif - - float n = 0.1 * snoise(uv.st * 200.0); // Fractal noise - n += 0.05 * snoise(uv.st * 400.0); - n += 0.025 * snoise(uv.st * 800.0); - - vec2 xn = 2.0 * (uv.st - 0.5); - vec2 edge = bendy(xn, 0.0091 * n, 0.0011 * -n); - vec2 bent = edge.xy * 0.5 + 0.5; - - float dx = rectdistance(xn); - float bx = rectdistance(edge); - - // apply shape - float doot = max(abs(edge.x), abs(edge.y)); - if (doot < 1.0) { - // display - outputColor = texture2D(inputBuffer, bent); - - // apply scratches - outputColor.rgb = blendLighten(outputColor.rgb, bright.rgb, 0.111); - outputColor.rgb = blendDarken(outputColor.rgb, dark.rgb, 0.111); - - // apply halftones - outputColor.rgb = halftone(outputColor.rgb, uv.st); - - } else if (doot > 1.004) { - // display shell - // rbgb 205 205 193 - vec3 matte = vec3(205.0 / 255.0, 205.0 / 255.0, 193.0 / 255.0); - vec3 dkmatte = mix(matte, vec3(0.0), 0.5); - float mx = pow(1.0 - bx, 16.0) + n; - outputColor = vec4(mix(matte, dkmatte, mx), inputColor.a); - - } else { - // border - outputColor = vec4(mix(vec3(0.0), outputColor.rgb, 0.5), inputColor.a); - } - - // apply inner shade - if (doot >= 0.5 && doot < 1.0) { - float sh = clamp(0.0, 1.0, 1.0 - bx - 0.7); - vec3 shade = mix(outputColor.rgb, vec3(0.0), pow(sh, 4.0)); - outputColor = vec4(shade, inputColor.a); - } - - // apply outer shade - if (doot >= 0.97) { - float sh = clamp(0.0, 1.0, bx * 24.0); - vec3 dkout = mix(vec3(0.0), outputColor.rgb, 0.81); - vec3 shade = mix(dkout, outputColor.rgb, sh); - outputColor = vec4(shade, inputColor.a); - } -} -`;class JK extends LE{constructor({splat:e,viewheight:t}={}){super("CRTShapeEffect",QK,{blendFunction:Jt.NORMAL,attributes:_a.CONVOLUTION,defines:new Map([["TEXEL","texel"],["TEXTURE_PRECISION_HIGH","1"]]),uniforms:new Map([["splat",new Mn(e)],["viewheight",new Mn(t??128)]])})}get splat(){var e;return(e=this.uniforms.get("splat"))==null?void 0:e.value}set splat(e){const{splat:t,uniforms:r,defines:i}=this,s=r.get("splat"),o=r.get("uvTransform");t!==e&&s&&o&&(s.value=e,o.value=e.matrix,i.delete("TEXTURE_PRECISION_HIGH"),e!==null&&(e.matrixAutoUpdate?(i.set("UV_TRANSFORM","1"),this.setVertexShader(ZK)):(i.delete("UV_TRANSFORM"),this.setVertexShader(null)),e.type!==Ei&&i.set("TEXTURE_PRECISION_HIGH","1"),(t===null||(t==null?void 0:t.type)!==e.type)&&this.setChanged()))}getTexture(){return this.splat}setTexture(e){this.splat=e}get aspectCorrection(){return this.defines.has("ASPECT_CORRECTION")}set aspectCorrection(e){this.aspectCorrection!==e&&(e?this.defines.set("ASPECT_CORRECTION","1"):this.defines.delete("ASPECT_CORRECTION"),this.setChanged())}get uvTransform(){const e=this.splat;return!!(e!=null&&e.matrixAutoUpdate)}set uvTransform(e){const t=this.splat;K(t)&&(t.matrixAutoUpdate=e)}setTextureSwizzleRGBA(e,t=e,r=e,i=e){const s="rgba";let o="";(e!==l0.RED||t!==l0.GREEN||r!==l0.BLUE||i!==l0.ALPHA)&&(o=[".",s[e],s[t],s[r],s[i]].join("")),this.defines.set("TEXEL","texel"+o),this.setChanged()}update(){var e;(e=this.splat)!=null&&e.matrixAutoUpdate&&this.splat.updateMatrix()}}const eY=PK(JK),tY="/assets/scratches-BBiC0fzb.gif",BS=n=>n===Object(n)&&!Array.isArray(n)&&typeof n!="function";function ib(n,e){const t=pa(s=>s.gl),r=Wp(rT,BS(n)?Object.values(n):n);return ke.useLayoutEffect(()=>{e==null||e(r)},[e,r]),ke.useEffect(()=>{if("initTexture"in t){let s=[];Array.isArray(r)?s=r:r instanceof or?s=[r]:BS(r)&&(s=Object.values(r)),s.forEach(o=>{o instanceof or&&t.initTexture(o)})}},[t,r]),ke.useMemo(()=>{if(BS(n)){const s={};let o=0;for(const a in n)s[a]=r[o++];return s}else return r},[n,r])}ib.preload=n=>Wp.preload(rT,n);ib.clear=n=>Wp.clear(rT,n);function nY(n){const e=new Set;function t(r){e.has(r.id)||(e.add(r.id),Yt.invoke(r))}return Qu("forward",["all"],r=>{e.has(r.id)||(e.add(r.id),n(r))}),t}function rY(n){return new Worker("/assets/instance-Bxjt_sve.js",{name:n==null?void 0:n.name})}const iY=Qu("gadgetclient",[],n=>{const{desync:e,gadget:t}=is.getState();switch(n.target){case"reset":n.player===t.player&&is.setState({desync:!1,gadget:n.data});break;case"patch":n.player===t.player&&!e&&is.setState(r=>{try{const{newDocument:i}=bv(r.gadget,n.data,!0,!1);return{...r,gadget:i}}catch(i){i instanceof aT&&(is.setState({desync:!0}),iY.reply(n,"desync",void 0,n.player))}return r});break}});function xp(){return xp=Object.assign||function(n){for(var e=1;e0}function DE(n){Y0++;try{return n()}finally{Y0--,Y0===0&&lY()}}var UE=!1;function KL(){return UE}function YL(n){UE=!0;try{n()}finally{UE=!1}}function cY(n){return function(){return YL(n)}}var FE=[];function lY(){var n=[].concat(FE);FE=[],ZL(n)}function ZL(n){var e=new Set;n.forEach(function(t){var r;(t.type==="add"||t.type==="delete")&&t.observable[Fr].connections.iterate.forEach(function(i){e.add(i)}),(r=t.observable[Fr].connections.byKey.get(t.key))==null||r.forEach(function(i){e.add(i)})}),e.forEach(function(t){t.trigger()})}function u0(n){if(XL()){FE.push(n);return}ZL([n])}function _2(n,e){if(n.type==="iterate")n.observable[Fr].connections.iterate.add(e);else{var t=n.observable[Fr].connections.byKey.get(n.key);t||(t=new Set,n.observable[Fr].connections.byKey.set(n.key,t)),t.add(e)}}function h0(n,e){if(!KL()){var t=qL();t&&(_2(n,t),t.registerConnection(n)),e&&(_2(n,e),e.registerConnection(n))}}var ob=Symbol("$skipreactive"),Fr=Symbol("$reactive"),so=Symbol("$reactiveproxy");function cm(n,e){return!!(n&&n[so]&&n[so].implicitObserver===e)}function ab(n){return n[ob]=!0,n}function QL(n){return!!(n&&!cm(n)&&n[Fr])}function BE(n,e,t){if(t===void 0&&(t=!1),n[ob]||cm(n,e))return n;var r=uY(n,t);if(!e)return r;var i=r[Fr].proxiesWithImplicitObserver.get(e);if(!i){var s={implicitObserver:e};Object.setPrototypeOf(s,JL),i=new Proxy(r[Fr].raw,s),r[Fr].proxiesWithImplicitObserver.set(e,i)}return i}var Df=BE;function uY(n,e){if(e===void 0&&(e=!1),cm(n))return n;if(QL(n))return n[Fr].proxy;if(n[Fr]||n[so])throw new Error("unexpected");var t={connections:{iterate:new Set,byKey:new Map},proxy:{},raw:n,proxiesWithImplicitObserver:new Map,shallow:e};Object.defineProperty(n,Fr,{enumerable:!1,writable:!0,configurable:!0,value:t});var r=new Proxy(n,JL);return t.proxy=r,r}var JL={has:function(e,t){var r=Reflect.has(e,t);return typeof t=="symbol"||h0({observable:e,key:t,type:"has"},this.implicitObserver),r},get:function(e,t,r){if(t===so)return{implicitObserver:this.implicitObserver};var i=Reflect.get(e,t,r);if(typeof t=="symbol")return t.toString()==="Symbol($reactiveproxy)"&&console.error("warning, Symbol($reactiveproxy) passed, but does not match $reactiveproxy. Multiple Reactive libraries loaded?"),i;if(t==="length"&&Array.isArray(e)?h0({observable:e,type:"iterate"},this.implicitObserver):h0({observable:e,key:t,type:"get"},this.implicitObserver),QL(i))return BE(i,this.implicitObserver);if(e[Fr].shallow)return i;if(typeof i=="object"&&i!==null&&!cm(i,this.implicitObserver)&&!Object.isFrozen(i)){var s=Reflect.getOwnPropertyDescriptor(e,t);if((!s||!(s.writable===!1&&s.configurable===!1))&&($L()||this.implicitObserver))return BE(i,this.implicitObserver)}return i},ownKeys:function(e){return h0({observable:e,type:"iterate"},this.implicitObserver),Reflect.ownKeys(e)},set:function(e,t,r,i){return DE(function(){if(typeof t=="symbol")return Reflect.set(e,t,r,i);var s=Object.hasOwnProperty.call(e,t),o=Reflect.get(e,t,i),a=Reflect.set(e,t,r,i);if(!s)u0({observable:e,key:t,value:r,type:"add"});else if(r!==o)if(t==="length"&&Array.isArray(e)){if(!(onew Map,zE=n=>{const e=Mo();return n.forEach((t,r)=>{e.set(r,t)}),e},Vl=(n,e,t)=>{let r=n.get(e);return r===void 0&&n.set(e,r=t()),r},mY=(n,e)=>{const t=[];for(const[r,i]of n)t.push(e(i,r));return t},gY=(n,e)=>{for(const[t,r]of n)if(e(r,t))return!0;return!1},Uf=()=>new Set,zS=n=>n[n.length-1],_Y=(n,e)=>{for(let t=0;t{this.off(e,r),t(...i)};this.on(e,r)}off(e,t){const r=this._observers.get(e);r!==void 0&&(r.delete(t),r.size===0&&this._observers.delete(e))}emit(e,t){return Rl((this._observers.get(e)||Mo()).values()).forEach(r=>r(...t))}destroy(){this._observers=Mo()}}const kl=Math.floor,Z0=Math.abs,tP=(n,e)=>nn>e?n:e,nP=n=>n!==0?n<0:1/n<0,v2=1,y2=2,VS=4,HS=8,Sp=32,_c=64,Ns=128,Qv=31,VE=63,Ou=127,xY=2147483647,rP=Number.MAX_SAFE_INTEGER,SY=Number.isInteger||(n=>typeof n=="number"&&isFinite(n)&&kl(n)===n),EY=n=>n.toLowerCase(),wY=/^\s*/g,TY=n=>n.replace(wY,""),bY=/([A-Z])/g,x2=(n,e)=>TY(n.replace(bY,t=>`${e}${EY(t)}`)),AY=n=>{const e=unescape(encodeURIComponent(n)),t=e.length,r=new Uint8Array(t);for(let i=0;iEp.encode(n),CY=Ep?MY:AY;let op=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});op&&op.decode(new Uint8Array).length===1&&(op=null);class lm{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Sl=()=>new lm,RY=n=>{let e=n.cpos;for(let t=0;t{const e=new Uint8Array(RY(n));let t=0;for(let r=0;r{const t=n.cbuf.length;t-n.cpos{const t=n.cbuf.length;n.cpos===t&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(t*2),n.cpos=0),n.cbuf[n.cpos++]=e},HE=Jr,Ht=(n,e)=>{for(;e>Ou;)Jr(n,Ns|Ou&e),e=kl(e/128);Jr(n,Ou&e)},cb=(n,e)=>{const t=nP(e);for(t&&(e=-e),Jr(n,(e>VE?Ns:0)|(t?_c:0)|VE&e),e=kl(e/64);e>0;)Jr(n,(e>Ou?Ns:0)|Ou&e),e=kl(e/128)},GE=new Uint8Array(3e4),IY=GE.length/3,NY=(n,e)=>{if(e.length{const t=unescape(encodeURIComponent(e)),r=t.length;Ht(n,r);for(let i=0;i{const t=n.cbuf.length,r=n.cpos,i=tP(t-r,e.length),s=e.length-i;n.cbuf.set(e.subarray(0,i),r),n.cpos+=i,s>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(rh(t*2,s)),n.cbuf.set(e.subarray(i)),n.cpos=s)},vi=(n,e)=>{Ht(n,e.byteLength),Jv(n,e)},lb=(n,e)=>{kY(n,e);const t=new DataView(n.cbuf.buffer,n.cpos,e);return n.cpos+=e,t},LY=(n,e)=>lb(n,4).setFloat32(0,e,!1),PY=(n,e)=>lb(n,8).setFloat64(0,e,!1),DY=(n,e)=>lb(n,8).setBigInt64(0,e,!1),S2=new DataView(new ArrayBuffer(4)),UY=n=>(S2.setFloat32(0,n),S2.getFloat32(0)===n),wp=(n,e)=>{switch(typeof e){case"string":Jr(n,119),_f(n,e);break;case"number":SY(e)&&Z0(e)<=xY?(Jr(n,125),cb(n,e)):UY(e)?(Jr(n,124),LY(n,e)):(Jr(n,123),PY(n,e));break;case"bigint":Jr(n,122),DY(n,e);break;case"object":if(e===null)Jr(n,126);else if(vY(e)){Jr(n,117),Ht(n,e.length);for(let t=0;t0&&Ht(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const w2=n=>{n.count>0&&(cb(n.encoder,n.count===1?n.s:-n.s),n.count>1&&Ht(n.encoder,n.count-2))};class Q0{constructor(){this.encoder=new lm,this.s=0,this.count=0}write(e){this.s===e?this.count++:(w2(this),this.count=1,this.s=e)}toUint8Array(){return w2(this),To(this.encoder)}}const T2=n=>{if(n.count>0){const e=n.diff*2+(n.count===1?0:1);cb(n.encoder,e),n.count>1&&Ht(n.encoder,n.count-2)}};class GS{constructor(){this.encoder=new lm,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(T2(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return T2(this),To(this.encoder)}}class FY{constructor(){this.sarr=[],this.s="",this.lensE=new Q0}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new lm;return this.sarr.push(this.s),this.s="",_f(e,this.sarr.join("")),Jv(e,this.lensE.toUint8Array()),To(e)}}const Il=n=>new Error(n),va=()=>{throw Il("Method unimplemented")},Aa=()=>{throw Il("Unexpected case")},iP=Il("Unexpected end of array"),sP=Il("Integer out of Range");class ey{constructor(e){this.arr=e,this.pos=0}}const ih=n=>new ey(n),BY=n=>n.pos!==n.arr.length,zY=(n,e)=>{const t=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,e);return n.pos+=e,t},Ii=n=>zY(n,Gt(n)),Ff=n=>n.arr[n.pos++],Gt=n=>{let e=0,t=1;const r=n.arr.length;for(;n.posrP)throw sP}throw iP},ub=n=>{let e=n.arr[n.pos++],t=e&VE,r=64;const i=(e&_c)>0?-1:1;if(!(e&Ns))return i*t;const s=n.arr.length;for(;n.posrP)throw sP}throw iP},VY=n=>{let e=Gt(n);if(e===0)return"";{let t=String.fromCodePoint(Ff(n));if(--e<100)for(;e--;)t+=String.fromCodePoint(Ff(n));else for(;e>0;){const r=e<1e4?e:1e4,i=n.arr.subarray(n.pos,n.pos+r);n.pos+=r,t+=String.fromCodePoint.apply(null,i),e-=r}return decodeURIComponent(escape(t))}},HY=n=>op.decode(Ii(n)),vf=op?HY:VY,hb=(n,e)=>{const t=new DataView(n.arr.buffer,n.arr.byteOffset+n.pos,e);return n.pos+=e,t},GY=n=>hb(n,4).getFloat32(0,!1),WY=n=>hb(n,8).getFloat64(0,!1),jY=n=>hb(n,8).getBigInt64(0,!1),$Y=[n=>{},n=>null,ub,GY,WY,jY,n=>!1,n=>!0,vf,n=>{const e=Gt(n),t={};for(let r=0;r{const e=Gt(n),t=[];for(let r=0;r$Y[127-Ff(n)](n);class b2 extends ey{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),BY(this)?this.count=Gt(this)+1:this.count=-1),this.count--,this.s}}class J0 extends ey{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=ub(this);const e=nP(this.s);this.count=1,e&&(this.s=-this.s,this.count=Gt(this)+2)}return this.count--,this.s}}class WS extends ey{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=ub(this),t=e&1;this.diff=kl(e/2),this.count=1,t&&(this.count=Gt(this)+2)}return this.s+=this.diff,this.count--,this.s}}class qY{constructor(e){this.decoder=new J0(e),this.str=vf(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}}const XY=crypto.getRandomValues.bind(crypto),oP=()=>XY(new Uint32Array(1))[0],KY="10000000-1000-4000-8000"+-1e11,YY=()=>KY.replace(/[018]/g,n=>(n^oP()&15>>n/4).toString(16)),A2=n=>new Promise(n);Promise.all.bind(Promise);const M2=n=>n===void 0?null:n;class ZY{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}}let aP=new ZY,QY=!0;try{typeof localStorage<"u"&&localStorage&&(aP=localStorage,QY=!1)}catch{}const JY=aP,eZ=Object.assign,tZ=Object.keys,nZ=(n,e)=>{for(const t in n)e(n[t],t)},C2=n=>tZ(n).length,rZ=n=>{for(const e in n)return!1;return!0},iZ=(n,e)=>{for(const t in n)if(!e(n[t],t))return!1;return!0},sZ=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),oZ=(n,e)=>n===e||C2(n)===C2(e)&&iZ(n,(t,r)=>(t!==void 0||sZ(e,r))&&e[r]===t),aZ=Object.freeze,cP=n=>{for(const e in n){const t=n[e];(typeof t=="object"||typeof t=="function")&&cP(n[e])}return aZ(n)},fb=(n,e,t=0)=>{try{for(;tn,lZ=(n,e)=>e.includes(n);var lP={};const bp=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let ta;const uZ=()=>{if(ta===void 0)if(bp){ta=Mo();const n=process.argv;let e=null;for(let t=0;t{if(n.length!==0){const[e,t]=n.split("=");ta.set(`--${x2(e,"-")}`,t),ta.set(`-${x2(e,"-")}`,t)}})):ta=Mo();return ta},WE=n=>uZ().has(n),B_=n=>M2(bp?lP[n.toUpperCase().replaceAll("-","_")]:JY.getItem(n)),uP=n=>WE("--"+n)||B_(n)!==null;uP("production");const hZ=bp&&lZ(lP.FORCE_COLOR,["true","1","2"]),fZ=hZ||!WE("--no-colors")&&!uP("no-color")&&(!bp||process.stdout.isTTY)&&(!bp||WE("--color")||B_("COLORTERM")!==null||(B_("TERM")||"").includes("color")),dZ=n=>new Uint8Array(n),pZ=n=>{const e=dZ(n.byteLength);return e.set(n),e};class mZ{constructor(e,t){this.left=e,this.right=t}}const rc=(n,e)=>new mZ(n,e);typeof DOMParser<"u"&&new DOMParser;const gZ=n=>mY(n,(e,t)=>`${t}:${e};`).join(""),Bc=Symbol,hP=Bc(),fP=Bc(),_Z=Bc(),vZ=Bc(),yZ=Bc(),dP=Bc(),xZ=Bc(),db=Bc(),SZ=Bc(),EZ=n=>{var i;n.length===1&&((i=n[0])==null?void 0:i.constructor)===Function&&(n=n[0]());const e=[],t=[];let r=0;for(;r0&&t.push(e.join(""));r{var o;n.length===1&&((o=n[0])==null?void 0:o.constructor)===Function&&(n=n[0]());const e=[],t=[],r=Mo();let i=[],s=0;for(;s0||l.length>0?(e.push("%c"+a),t.push(l)):e.push(a)}else break}}for(s>0&&(i=t,i.unshift(e.join("")));s{console.log(...pP(n)),mP.forEach(e=>e.print(n))},AZ=(...n)=>{console.warn(...pP(n)),n.unshift(db),mP.forEach(e=>e.print(n))},mP=Uf(),gP=n=>({[Symbol.iterator](){return this},next:n}),MZ=(n,e)=>gP(()=>{let t;do t=n.next();while(!t.done&&!e(t.value));return t}),jS=(n,e)=>gP(()=>{const{done:t,value:r}=n.next();return{done:t,value:t?void 0:e(r)}});class pb{constructor(e,t){this.clock=e,this.len=t}}class um{constructor(){this.clients=new Map}}const _P=(n,e,t)=>e.clients.forEach((r,i)=>{const s=n.doc.store.clients.get(i);for(let o=0;o{let t=0,r=n.length-1;for(;t<=r;){const i=kl((t+r)/2),s=n[i],o=s.clock;if(o<=e){if(e{const t=n.clients.get(e.client);return t!==void 0&&CZ(t,e.clock)!==null},mb=n=>{n.clients.forEach(e=>{e.sort((i,s)=>i.clock-s.clock);let t,r;for(t=1,r=1;t=s.clock?i.len=rh(i.len,s.clock+s.len-i.clock):(r{const e=new um;for(let t=0;t{if(!e.clients.has(i)){const s=r.slice();for(let o=t+1;o{Vl(n.clients,e,()=>[]).push(new pb(t,r))},kZ=()=>new um,IZ=n=>{const e=kZ();return n.clients.forEach((t,r)=>{const i=[];for(let s=0;s0&&e.clients.set(r,i)}),e},ad=(n,e)=>{Ht(n.restEncoder,e.clients.size),Rl(e.clients.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{n.resetDsCurVal(),Ht(n.restEncoder,t);const i=r.length;Ht(n.restEncoder,i);for(let s=0;s{const e=new um,t=Gt(n.restDecoder);for(let r=0;r0){const o=Vl(e.clients,i,()=>[]);for(let a=0;a{const r=new um,i=Gt(n.restDecoder);for(let s=0;s0){const s=new Gu;return Ht(s.restEncoder,0),ad(s,r),s.toUint8Array()}return null},yP=oP;class zc extends yY{constructor({guid:e=YY(),collectionid:t=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=yP(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new CP,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=A2(l=>{this.on("load",()=>{this.isLoaded=!0,l(this)})});const c=()=>A2(l=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),l())};this.on("sync",u)});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&Dn(e.parent.doc,t=>{t.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Rl(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Dn(this,e,t)}get(e,t=cr){const r=Vl(this.share,e,()=>{const s=new t;return s._integrate(this,null),s}),i=r.constructor;if(t!==cr&&i!==t)if(i===cr){const s=new t;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(e,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,ya)}getText(e=""){return this.get(e,Oo)}getMap(e=""){return this.get(e,Ma)}getXmlElement(e=""){return this.get(e,Ac)}getXmlFragment(e=""){return this.get(e,Ca)}toJSON(){const e={};return this.share.forEach((t,r)=>{e[r]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Rl(this.subdocs).forEach(t=>t.destroy());const e=this._item;if(e!==null){this._item=null;const t=e.content;t.doc=new zc({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,Dn(e.parent.doc,r=>{const i=t.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class xP{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Gt(this.restDecoder)}readDsLen(){return Gt(this.restDecoder)}}class SP extends xP{readLeftID(){return an(Gt(this.restDecoder),Gt(this.restDecoder))}readRightID(){return an(Gt(this.restDecoder),Gt(this.restDecoder))}readClient(){return Gt(this.restDecoder)}readInfo(){return Ff(this.restDecoder)}readString(){return vf(this.restDecoder)}readParentInfo(){return Gt(this.restDecoder)===1}readTypeRef(){return Gt(this.restDecoder)}readLen(){return Gt(this.restDecoder)}readAny(){return Tp(this.restDecoder)}readBuf(){return pZ(Ii(this.restDecoder))}readJSON(){return JSON.parse(vf(this.restDecoder))}readKey(){return vf(this.restDecoder)}}class NZ{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Gt(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Gt(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Bf extends NZ{constructor(e){super(e),this.keys=[],Gt(e),this.keyClockDecoder=new WS(Ii(e)),this.clientDecoder=new J0(Ii(e)),this.leftClockDecoder=new WS(Ii(e)),this.rightClockDecoder=new WS(Ii(e)),this.infoDecoder=new b2(Ii(e),Ff),this.stringDecoder=new qY(Ii(e)),this.parentInfoDecoder=new b2(Ii(e),Ff),this.typeRefDecoder=new J0(Ii(e)),this.lenDecoder=new J0(Ii(e))}readLeftID(){return new yf(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new yf(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Tp(this.restDecoder)}readBuf(){return Ii(this.restDecoder)}readJSON(){return Tp(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e{r=rh(r,e[0].id.clock);const i=No(e,r);Ht(n.restEncoder,e.length-i),n.writeClient(t),Ht(n.restEncoder,r);const s=e[i];s.write(n,r-s.id.clock);for(let o=i+1;o{const r=new Map;t.forEach((i,s)=>{ri(e,s)>i&&r.set(s,i)}),ty(e).forEach((i,s)=>{t.has(s)||r.set(s,0)}),Ht(n.restEncoder,r.size),Rl(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{OZ(n,e.clients.get(i),i,s)})},LZ=(n,e)=>{const t=Mo(),r=Gt(n.restDecoder);for(let i=0;i{const r=[];let i=Rl(t.keys()).sort((m,g)=>m-g);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let m=t.get(i[i.length-1]);for(;m.refs.length===m.i;)if(i.pop(),i.length>0)m=t.get(i[i.length-1]);else return null;return m};let o=s();if(o===null)return null;const a=new CP,c=new Map,l=(m,g)=>{const v=c.get(m);(v==null||v>g)&&c.set(m,g)};let u=o.refs[o.i++];const h=new Map,p=()=>{for(const m of r){const g=m.id.client,v=t.get(g);v?(v.i--,a.clients.set(g,v.refs.slice(v.i)),t.delete(g),v.i=0,v.refs=[]):a.clients.set(g,[m]),i=i.filter(y=>y!==g)}r.length=0};for(;;){if(u.constructor!==Ys){const g=Vl(h,u.id.client,()=>ri(e,u.id.client))-u.id.clock;if(g<0)r.push(u),l(u.id.client,u.id.clock-1),p();else{const v=u.getMissing(n,e);if(v!==null){r.push(u);const y=t.get(v)||{refs:[],i:0};if(y.refs.length===y.i)l(v,ri(e,v)),p();else{u=y.refs[y.i++];continue}}else(g===0||g0)u=r.pop();else if(o!==null&&o.i0){const m=new Gu;return _b(m,a,new Map),Ht(m.restEncoder,0),{missing:c,update:m.toUint8Array()}}return null},DZ=(n,e)=>_b(n,e.doc.store,e.beforeState),UZ=(n,e,t,r=new Bf(n))=>Dn(e,i=>{i.local=!1;let s=!1;const o=i.doc,a=o.store,c=LZ(r,o),l=PZ(i,a,c),u=a.pendingStructs;if(u){for(const[p,m]of u.missing)if(mm)&&u.missing.set(p,m)}u.update=V_([u.update,l.update])}}else a.pendingStructs=l;const h=R2(r,i,a);if(a.pendingDs){const p=new Bf(ih(a.pendingDs));Gt(p.restDecoder);const m=R2(p,i,a);h&&m?a.pendingDs=V_([h,m]):a.pendingDs=h||m}else a.pendingDs=h;if(s){const p=a.pendingStructs.update;a.pendingStructs=null,TP(i.doc,p)}},t,!1),TP=(n,e,t,r=Bf)=>{const i=ih(e);UZ(i,n,t,new r(i))},FZ=(n,e,t)=>TP(n,e,t,SP),BZ=(n,e,t=new Map)=>{_b(n,e.store,t),ad(n,IZ(e.store))},zZ=(n,e=new Uint8Array([0]),t=new Gu)=>{const r=bP(e);BZ(t,n,r);const i=[t.toUint8Array()];if(n.store.pendingDs&&i.push(n.store.pendingDs),n.store.pendingStructs&&i.push(nQ(n.store.pendingStructs.update,e)),i.length>1){if(t.constructor===hm)return eQ(i.map((s,o)=>o===0?s:iQ(s)));if(t.constructor===Gu)return V_(i)}return i[0]},VZ=(n,e)=>zZ(n,e,new hm),HZ=n=>{const e=new Map,t=Gt(n.restDecoder);for(let r=0;rHZ(new xP(ih(n))),AP=(n,e)=>(Ht(n.restEncoder,e.size),Rl(e.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{Ht(n.restEncoder,t),Ht(n.restEncoder,r)}),n),GZ=(n,e)=>AP(n,ty(e.store)),WZ=(n,e=new wP)=>(n instanceof Map?AP(e,n):GZ(e,n),e.toUint8Array()),jZ=n=>WZ(n,new EP);class $Z{constructor(){this.l=[]}}const k2=()=>new $Z,I2=(n,e)=>n.l.push(e),N2=(n,e)=>{const t=n.l,r=t.length;n.l=t.filter(i=>e!==i),r===n.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},MP=(n,e,t)=>fb(n.l,[e,t]);class yf{constructor(e,t){this.client=e,this.clock=t}}const f0=(n,e)=>n===e||n!==null&&e!==null&&n.client===e.client&&n.clock===e.clock,an=(n,e)=>new yf(n,e),qZ=n=>{for(const[e,t]of n.doc.share.entries())if(t===n)return e;throw Aa()},Qh=(n,e)=>e===void 0?!n.deleted:e.sv.has(n.id.client)&&(e.sv.get(n.id.client)||0)>n.id.clock&&!vP(e.ds,n.id),jE=(n,e)=>{const t=Vl(n.meta,jE,Uf),r=n.doc.store;t.has(e)||(e.sv.forEach((i,s)=>{i{}),t.add(e))};class CP{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ty=n=>{const e=new Map;return n.clients.forEach((t,r)=>{const i=t[t.length-1];e.set(r,i.id.clock+i.length)}),e},ri=(n,e)=>{const t=n.clients.get(e);if(t===void 0)return 0;const r=t[t.length-1];return r.id.clock+r.length},RP=(n,e)=>{let t=n.clients.get(e.id.client);if(t===void 0)t=[],n.clients.set(e.id.client,t);else{const r=t[t.length-1];if(r.id.clock+r.length!==e.id.clock)throw Aa()}t.push(e)},No=(n,e)=>{let t=0,r=n.length-1,i=n[r],s=i.id.clock;if(s===e)return r;let o=kl(e/(s+i.length-1)*r);for(;t<=r;){if(i=n[o],s=i.id.clock,s<=e){if(e{const t=n.clients.get(e.client);return t[No(t,e.clock)]},$S=XZ,$E=(n,e,t)=>{const r=No(e,t),i=e[r];return i.id.clock{const t=n.doc.store.clients.get(e.client);return t[$E(n,t,e.clock)]},O2=(n,e,t)=>{const r=e.clients.get(t.client),i=No(r,t.clock),s=r[i];return t.clock!==s.id.clock+s.length-1&&s.constructor!==Ms&&r.splice(i+1,0,j_(n,s,t.clock-s.id.clock+1)),s},KZ=(n,e,t)=>{const r=n.clients.get(e.id.client);r[No(r,e.id.clock)]=t},kP=(n,e,t,r,i)=>{if(r===0)return;const s=t+r;let o=$E(n,e,t),a;do a=e[o++],se.deleteSet.clients.size===0&&!gY(e.afterState,(t,r)=>e.beforeState.get(r)!==t)?!1:(mb(e.deleteSet),DZ(n,e),ad(n,e.deleteSet),!0),P2=(n,e,t)=>{const r=e._item;(r===null||r.id.clock<(n.beforeState.get(r.id.client)||0)&&!r.deleted)&&Vl(n.changed,e,Uf).add(t)},e_=(n,e)=>{let t=n[e],r=n[e-1],i=e;for(;i>0;t=r,r=n[--i-1]){if(r.deleted===t.deleted&&r.constructor===t.constructor&&r.mergeWith(t)){t instanceof Ur&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,r);continue}break}const s=e-i;return s&&n.splice(e+1-s,s),s},ZZ=(n,e,t)=>{for(const[r,i]of n.clients.entries()){const s=e.clients.get(r);for(let o=i.length-1;o>=0;o--){const a=i[o],c=a.clock+a.len;for(let l=No(s,a.clock),u=s[l];l{n.clients.forEach((t,r)=>{const i=e.clients.get(r);for(let s=t.length-1;s>=0;s--){const o=t[s],a=tP(i.length-1,1+No(i,o.clock+o.len-1));for(let c=a,l=i[c];c>0&&l.id.clock>=o.clock;l=i[c])c-=1+e_(i,c)}})},IP=(n,e)=>{if(ea.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(t,c)})),a.push(()=>{t.changedParentTypes.forEach((c,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=l,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),MP(l._dEH,c,t))})}),a.push(()=>r.emit("afterTransaction",[t,r])),fb(a,[]),t._needFormattingCleanup&&vQ(t)}finally{r.gc&&ZZ(s,i,r.gcFilter),QZ(s,i),t.afterState.forEach((u,h)=>{const p=t.beforeState.get(h)||0;if(p!==u){const m=i.clients.get(h),g=rh(No(m,p),1);for(let v=m.length-1;v>=g;)v-=1+e_(m,v)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:p}=o[u].id,m=i.clients.get(h),g=No(m,p);g+11||g>0&&e_(m,g)}if(!t.local&&t.afterState.get(r.clientID)!==t.beforeState.get(r.clientID)&&(bZ(db,hP,"[yjs] ",fP,dP,"Changed the client-id because another client seems to be using it."),r.clientID=yP()),r.emit("afterTransactionCleanup",[t,r]),r._observers.has("update")){const u=new hm;L2(u,t)&&r.emit("update",[u.toUint8Array(),t.origin,r,t])}if(r._observers.has("updateV2")){const u=new Gu;L2(u,t)&&r.emit("updateV2",[u.toUint8Array(),t.origin,r,t])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=t;(a.size>0||l.size>0||c.size>0)&&(a.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),l.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,t]),l.forEach(u=>u.destroy())),n.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,n])):IP(n,e+1)}}},Dn=(n,e,t=null,r=!0)=>{const i=n._transactionCleanups;let s=!1,o=null;n._transaction===null&&(s=!0,n._transaction=new YZ(n,t,r),i.push(n._transaction),i.length===1&&n.emit("beforeAllTransactions",[n]),n.emit("beforeTransaction",[n._transaction,n]));try{o=e(n._transaction)}finally{if(s){const a=n._transaction===i[0];n._transaction=null,a&&IP(i,0)}}return o};function*JZ(n){const e=Gt(n.restDecoder);for(let t=0;tV_(n,SP,hm),tQ=(n,e)=>{if(n.constructor===Ms){const{client:t,clock:r}=n.id;return new Ms(an(t,r+e),n.length-e)}else if(n.constructor===Ys){const{client:t,clock:r}=n.id;return new Ys(an(t,r+e),n.length-e)}else{const t=n,{client:r,clock:i}=t.id;return new Ur(an(r,i+e),null,an(r,i+e-1),null,t.rightOrigin,t.parent,t.parentSub,t.content.splice(e))}},V_=(n,e=Bf,t=Gu)=>{if(n.length===1)return n[0];const r=n.map(u=>new e(ih(u)));let i=r.map(u=>new vb(u,!0)),s=null;const o=new t,a=new yb(o);for(;i=i.filter(p=>p.curr!==null),i.sort((p,m)=>{if(p.curr.id.client===m.curr.id.client){const g=p.curr.id.clock-m.curr.id.clock;return g===0?p.curr.constructor===m.curr.constructor?0:p.curr.constructor===Ys?1:-1:g}else return m.curr.id.client-p.curr.id.client}),i.length!==0;){const u=i[0],h=u.curr.id.client;if(s!==null){let p=u.curr,m=!1;for(;p!==null&&p.id.clock+p.length<=s.struct.id.clock+s.struct.length&&p.id.client>=s.struct.id.client;)p=u.next(),m=!0;if(p===null||p.id.client!==h||m&&p.id.clock>s.struct.id.clock+s.struct.length)continue;if(h!==s.struct.id.client)pl(a,s.struct,s.offset),s={struct:p,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===Ys?s.struct.length-=g:p=tQ(p,g)),s.struct.mergeWith(p)||(pl(a,s.struct,s.offset),s={struct:p,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let p=u.curr;p!==null&&p.id.client===h&&p.id.clock===s.struct.id.clock+s.struct.length&&p.constructor!==Ys;p=u.next())pl(a,s.struct,s.offset),s={struct:p,offset:0}}s!==null&&(pl(a,s.struct,s.offset),s=null),xb(a);const c=r.map(u=>gb(u)),l=RZ(c);return ad(o,l),o.toUint8Array()},nQ=(n,e,t=Bf,r=Gu)=>{const i=bP(e),s=new r,o=new yb(s),a=new t(ih(n)),c=new vb(a,!1);for(;c.curr;){const u=c.curr,h=u.id.client,p=i.get(h)||0;if(c.curr.constructor===Ys){c.next();continue}if(u.id.clock+u.length>p)for(pl(o,u,rh(p-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)pl(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=p;)c.next()}xb(o);const l=gb(a);return ad(s,l),s.toUint8Array()},NP=n=>{n.written>0&&(n.clientStructs.push({written:n.written,restEncoder:To(n.encoder.restEncoder)}),n.encoder.restEncoder=Sl(),n.written=0)},pl=(n,e,t)=>{n.written>0&&n.currClient!==e.id.client&&NP(n),n.written===0&&(n.currClient=e.id.client,n.encoder.writeClient(e.id.client),Ht(n.encoder.restEncoder,e.id.clock+t)),e.write(n.encoder,t),n.written++},xb=n=>{NP(n);const e=n.encoder.restEncoder;Ht(e,n.clientStructs.length);for(let t=0;t{const i=new t(ih(n)),s=new vb(i,!1),o=new r,a=new yb(o);for(let l=s.curr;l!==null;l=s.next())pl(a,e(l),0);xb(a);const c=gb(i);return ad(o,c),o.toUint8Array()},iQ=n=>rQ(n,cZ,Bf,hm),D2="You must not compute changes after the event-handler fired.";class ny{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=sQ(this.currentTarget,this.target))}deletes(e){return vP(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Il(D2);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach(i=>{if(i!==null){const s=t._map.get(i);let o,a;if(this.adds(s)){let c=s.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(s))if(c!==null&&this.deletes(c))o="delete",a=zS(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",a=zS(c.content.getContent())):(o="add",a=void 0)}else if(this.deletes(s))o="delete",a=zS(s.content.getContent());else return;e.set(i,{action:o,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Il(D2);const t=this.target,r=Uf(),i=Uf(),s=[];if(e={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(t).has(null)){let a=null;const c=()=>{a&&s.push(a)};for(let l=t._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=l.length,i.add(l)):this.adds(l)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(l.content.getContent()),r.add(l)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=l.length);a!==null&&a.retain===void 0&&c()}this._changes=e}return e}}const sQ=(n,e)=>{const t=[];for(;e._item!==null&&e!==n;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;t.unshift(r)}e=e._item.parent}return t},Si=()=>{AZ("Invalid access: Add Yjs type to a document before reading data.")},OP=80;let Sb=0;class oQ{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Sb++}}const aQ=n=>{n.timestamp=Sb++},LP=(n,e,t)=>{n.p.marker=!1,n.p=e,e.marker=!0,n.index=t,n.timestamp=Sb++},cQ=(n,e,t)=>{if(n.length>=OP){const r=n.reduce((i,s)=>i.timestamp{if(n._start===null||e===0||n._searchMarker===null)return null;const t=n._searchMarker.length===0?null:n._searchMarker.reduce((s,o)=>Z0(e-s.index)e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return t!==null&&Z0(t.index-i){for(let r=n.length-1;r>=0;r--){const i=n[r];if(t>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){n.splice(r,1);continue}i.p=s,s.marker=!0}(e0&&e===i.index)&&(i.index=rh(e,i.index+t))}},iy=(n,e,t)=>{const r=n,i=e.changedParentTypes;for(;Vl(i,n,()=>[]).push(t),n._item!==null;)n=n._item.parent;MP(r._eH,t,e)};class cr{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=k2(),this._dEH=k2(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw va()}clone(){throw va()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){I2(this._eH,e)}observeDeep(e){I2(this._dEH,e)}unobserve(e){N2(this._eH,e)}unobserveDeep(e){N2(this._dEH,e)}toJSON(){}}const PP=(n,e,t)=>{n.doc??Si(),e<0&&(e=n._length+e),t<0&&(t=n._length+t);let r=t-e;const i=[];let s=n._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=e)e-=o.length;else{for(let a=e;a0;a++)i.push(o[a]),r--;e=0}}s=s.right}return i},DP=n=>{n.doc??Si();const e=[];let t=n._start;for(;t!==null;){if(t.countable&&!t.deleted){const r=t.content.getContent();for(let i=0;i{let t=0,r=n._start;for(n.doc??Si();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const t=[];return Mp(n,(r,i)=>{t.push(e(r,i,n))}),t},lQ=n=>{let e=n._start,t=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(t===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};t=e.content.getContent(),r=0,e=e.right}const i=t[r++];return t.length<=r&&(t=null),{done:!1,value:i}}}},FP=(n,e)=>{n.doc??Si();const t=ry(n,e);let r=n._start;for(t!==null&&(r=t.p,e-=t.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e{let i=t;const s=n.doc,o=s.clientID,a=s.store,c=t===null?e._start:t.right;let l=[];const u=()=>{l.length>0&&(i=new Ur(an(o,ri(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new ju(l)),i.integrate(n,0),l=[])};r.forEach(h=>{if(h===null)l.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:i=new Ur(an(o,ri(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new fm(new Uint8Array(h))),i.integrate(n,0);break;case zc:i=new Ur(an(o,ri(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new dm(h)),i.integrate(n,0);break;default:if(h instanceof cr)i=new Ur(an(o,ri(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new Vc(h)),i.integrate(n,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},BP=()=>Il("Length exceeded!"),zP=(n,e,t,r)=>{if(t>e._length)throw BP();if(t===0)return e._searchMarker&&Ap(e._searchMarker,t,r.length),H_(n,e,null,r);const i=t,s=ry(e,t);let o=e._start;for(s!==null&&(o=s.p,t-=s.index,t===0&&(o=o.prev,t+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(t<=o.length){t{let i=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return H_(n,e,i,t)},VP=(n,e,t,r)=>{if(r===0)return;const i=t,s=r,o=ry(e,t);let a=e._start;for(o!==null&&(a=o.p,t-=o.index);a!==null&&t>0;a=a.right)!a.deleted&&a.countable&&(t0&&a!==null;)a.deleted||(r0)throw BP();e._searchMarker&&Ap(e._searchMarker,i,-s+r)},G_=(n,e,t)=>{const r=e._map.get(t);r!==void 0&&r.delete(n)},Eb=(n,e,t,r)=>{const i=e._map.get(t)||null,s=n.doc,o=s.clientID;let a;if(r==null)a=new ju([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:a=new ju([r]);break;case Uint8Array:a=new fm(r);break;case zc:a=new dm(r);break;default:if(r instanceof cr)a=new Vc(r);else throw new Error("Unexpected content type")}new Ur(an(o,ri(s.store,o)),i,i&&i.lastId,null,null,e,t,a).integrate(n,0)},wb=(n,e)=>{n.doc??Si();const t=n._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},HP=n=>{const e={};return n.doc??Si(),n._map.forEach((t,r)=>{t.deleted||(e[r]=t.content.getContent()[t.length-1])}),e},GP=(n,e)=>{n.doc??Si();const t=n._map.get(e);return t!==void 0&&!t.deleted},hQ=(n,e)=>{const t={};return n._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&Qh(s,e)&&(t[i]=s.content.getContent()[s.length-1])}),t},d0=n=>(n.doc??Si(),MZ(n._map.entries(),e=>!e[1].deleted));class fQ extends ny{}class ya extends cr{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new ya;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ya}clone(){const e=new ya;return e.insert(0,this.toArray().map(t=>t instanceof cr?t.clone():t)),e}get length(){return this.doc??Si(),this._length}_callObserver(e,t){super._callObserver(e,t),iy(this,e,new fQ(this,e))}insert(e,t){this.doc!==null?Dn(this.doc,r=>{zP(r,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){this.doc!==null?Dn(this.doc,t=>{uQ(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc!==null?Dn(this.doc,r=>{VP(r,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return FP(this,e)}toArray(){return DP(this)}slice(e=0,t=this.length){return PP(this,e,t)}toJSON(){return this.map(e=>e instanceof cr?e.toJSON():e)}map(e){return UP(this,e)}forEach(e){Mp(this,e)}[Symbol.iterator](){return lQ(this)}_write(e){e.writeTypeRef(UQ)}}const dQ=n=>new ya;class pQ extends ny{constructor(e,t,r){super(e,t),this.keysChanged=r}}class Ma extends cr{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new Ma}clone(){const e=new Ma;return this.forEach((t,r)=>{e.set(r,t instanceof cr?t.clone():t)}),e}_callObserver(e,t){iy(this,e,new pQ(this,e,t))}toJSON(){this.doc??Si();const e={};return this._map.forEach((t,r)=>{if(!t.deleted){const i=t.content.getContent()[t.length-1];e[r]=i instanceof cr?i.toJSON():i}}),e}get size(){return[...d0(this)].length}keys(){return jS(d0(this),e=>e[0])}values(){return jS(d0(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return jS(d0(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Si(),this._map.forEach((t,r)=>{t.deleted||e(t.content.getContent()[t.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?Dn(this.doc,t=>{G_(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return this.doc!==null?Dn(this.doc,r=>{Eb(r,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return wb(this,e)}has(e){return GP(this,e)}clear(){this.doc!==null?Dn(this.doc,e=>{this.forEach(function(t,r,i){G_(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(FQ)}}const mQ=n=>new Ma,gl=(n,e)=>n===e||typeof n=="object"&&typeof e=="object"&&n&&e&&oZ(n,e);class qE{constructor(e,t,r,i){this.left=e,this.right=t,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Aa(),this.right.content.constructor){case Gr:this.right.deleted||cd(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const U2=(n,e,t)=>{for(;e.right!==null&&t>0;){switch(e.right.content.constructor){case Gr:e.right.deleted||cd(e.currentAttributes,e.right.content);break;default:e.right.deleted||(t{const i=new Map,s=r?ry(e,t):null;if(s){const o=new qE(s.p.left,s.p,s.index,i);return U2(n,o,t-s.index)}else{const o=new qE(null,e._start,0,i);return U2(n,o,t)}},WP=(n,e,t,r)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===Gr&&gl(r.get(t.right.content.key),t.right.content.value));)t.right.deleted||r.delete(t.right.content.key),t.forward();const i=n.doc,s=i.clientID;r.forEach((o,a)=>{const c=t.left,l=t.right,u=new Ur(an(s,ri(i.store,s)),c,c&&c.lastId,l,l&&l.id,e,null,new Gr(a,o));u.integrate(n,0),t.right=u,t.forward()})},cd=(n,e)=>{const{key:t,value:r}=e;r===null?n.delete(t):n.set(t,r)},jP=(n,e)=>{for(;n.right!==null;){if(!(n.right.deleted||n.right.content.constructor===Gr&&gl(e[n.right.content.key]??null,n.right.content.value)))break;n.forward()}},$P=(n,e,t,r)=>{const i=n.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=t.currentAttributes.get(a)??null;if(!gl(l,c)){o.set(a,l);const{left:u,right:h}=t;t.right=new Ur(an(s,ri(i.store,s)),u,u&&u.lastId,h,h&&h.id,e,null,new Gr(a,c)),t.right.integrate(n,0),t.forward()}}return o},qS=(n,e,t,r,i)=>{t.currentAttributes.forEach((p,m)=>{i[m]===void 0&&(i[m]=null)});const s=n.doc,o=s.clientID;jP(t,i);const a=$P(n,e,t,i),c=r.constructor===String?new Ra(r):r instanceof cr?new Vc(r):new sh(r);let{left:l,right:u,index:h}=t;e._searchMarker&&Ap(e._searchMarker,t.index,c.getLength()),u=new Ur(an(o,ri(s.store,o)),l,l&&l.lastId,u,u&&u.id,e,null,c),u.integrate(n,0),t.right=u,t.index=h,t.forward(),WP(n,e,t,a)},F2=(n,e,t,r,i)=>{const s=n.doc,o=s.clientID;jP(t,i);const a=$P(n,e,t,i);e:for(;t.right!==null&&(r>0||a.size>0&&(t.right.deleted||t.right.content.constructor===Gr));){if(!t.right.deleted)switch(t.right.content.constructor){case Gr:{const{key:c,value:l}=t.right.content,u=i[c];if(u!==void 0){if(gl(u,l))a.delete(c);else{if(r===0)break e;a.set(c,l)}t.right.delete(n)}else t.currentAttributes.set(c,l);break}default:r0){let c="";for(;r>0;r--)c+=` -`;t.right=new Ur(an(o,ri(s.store,o)),t.left,t.left&&t.left.lastId,t.right,t.right&&t.right.id,e,null,new Ra(c)),t.right.integrate(n,0),t.forward()}WP(n,e,t,a)},qP=(n,e,t,r,i)=>{let s=e;const o=Mo();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===Gr){const l=s.content;o.set(l.key,l)}s=s.right}let a=0,c=!1;for(;e!==s;){if(t===e&&(c=!0),!e.deleted){const l=e.content;switch(l.constructor){case Gr:{const{key:u,value:h}=l,p=r.get(u)??null;(o.get(u)!==l||p===h)&&(e.delete(n),a++,!c&&(i.get(u)??null)===h&&p!==h&&(p===null?i.delete(u):i.set(u,p))),!c&&!e.deleted&&cd(i,l);break}}}e=e.right}return a},gQ=(n,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const t=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===Gr){const r=e.content.key;t.has(r)?e.delete(n):t.add(r)}e=e.left}},_Q=n=>{let e=0;return Dn(n.doc,t=>{let r=n._start,i=n._start,s=Mo();const o=zE(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Gr:cd(o,i.content);break;default:e+=qP(t,r,i,s,o),s=zE(o),r=i;break}i=i.right}}),e},vQ=n=>{const e=new Set,t=n.doc;for(const[r,i]of n.afterState.entries()){const s=n.beforeState.get(r)||0;i!==s&&kP(n,t.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===Gr&&o.constructor!==Ms&&e.add(o.parent)})}Dn(t,r=>{_P(n,n.deleteSet,i=>{if(i instanceof Ms||!i.parent._hasFormatting||e.has(i.parent))return;const s=i.parent;i.content.constructor===Gr?e.add(s):gQ(r,i)});for(const i of e)_Q(i)})},B2=(n,e,t)=>{const r=t,i=zE(e.currentAttributes),s=e.right;for(;t>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case Vc:case sh:case Ra:t{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,t=[];Dn(e,r=>{const i=new Map,s=new Map;let o=this.target._start,a=null;const c={};let l="",u=0,h=0;const p=()=>{if(a!==null){let m=null;switch(a){case"delete":h>0&&(m={delete:h}),h=0;break;case"insert":(typeof l=="object"||l.length>0)&&(m={insert:l},i.size>0&&(m.attributes={},i.forEach((g,v)=>{g!==null&&(m.attributes[v]=g)}))),l="";break;case"retain":u>0&&(m={retain:u},rZ(c)||(m.attributes=eZ({},c))),u=0;break}m&&t.push(m),a=null}};for(;o!==null;){switch(o.content.constructor){case Vc:case sh:this.adds(o)?this.deletes(o)||(p(),a="insert",l=o.content.getContent()[0],p()):this.deletes(o)?(a!=="delete"&&(p(),a="delete"),h+=1):o.deleted||(a!=="retain"&&(p(),a="retain"),u+=1);break;case Ra:this.adds(o)?this.deletes(o)||(a!=="insert"&&(p(),a="insert"),l+=o.content.str):this.deletes(o)?(a!=="delete"&&(p(),a="delete"),h+=o.length):o.deleted||(a!=="retain"&&(p(),a="retain"),u+=o.length);break;case Gr:{const{key:m,value:g}=o.content;if(this.adds(o)){if(!this.deletes(o)){const v=i.get(m)??null;gl(v,g)?g!==null&&o.delete(r):(a==="retain"&&p(),gl(g,s.get(m)??null)?delete c[m]:c[m]=g)}}else if(this.deletes(o)){s.set(m,g);const v=i.get(m)??null;gl(v,g)||(a==="retain"&&p(),c[m]=v)}else if(!o.deleted){s.set(m,g);const v=c[m];v!==void 0&&(gl(v,g)?v!==null&&o.delete(r):(a==="retain"&&p(),g===null?delete c[m]:c[m]=g))}o.deleted||(a==="insert"&&p(),cd(i,o.content));break}}o=o.right}for(p();t.length>0;){const m=t[t.length-1];if(m.retain!==void 0&&m.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}}class Oo extends cr{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Si(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new Oo}clone(){const e=new Oo;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const r=new yQ(this,e,t);iy(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Si();let e="",t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Ra&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc!==null?Dn(this.doc,r=>{const i=new qE(null,this._start,0,new Map);for(let s=0;s0)&&qS(r,this,i,a,o.attributes||{})}else o.retain!==void 0?F2(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&B2(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,r){this.doc??Si();const i=[],s=new Map,o=this.doc;let a="",c=this._start;function l(){if(a.length>0){const h={};let p=!1;s.forEach((g,v)=>{p=!0,h[v]=g});const m={insert:a};p&&(m.attributes=h),i.push(m),a=""}}const u=()=>{for(;c!==null;){if(Qh(c,e)||t!==void 0&&Qh(c,t))switch(c.content.constructor){case Ra:{const h=s.get("ychange");e!==void 0&&!Qh(c,e)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(l(),s.set("ychange",r?r("removed",c.id):{type:"removed"})):t!==void 0&&!Qh(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(l(),s.set("ychange",r?r("added",c.id):{type:"added"})):h!==void 0&&(l(),s.delete("ychange")),a+=c.content.str;break}case Vc:case sh:{l();const h={insert:c.content.getContent()[0]};if(s.size>0){const p={};h.attributes=p,s.forEach((m,g)=>{p[g]=m})}i.push(h);break}case Gr:Qh(c,e)&&(l(),cd(s,c.content));break}c=c.right}l()};return e||t?Dn(o,h=>{e&&jE(h,e),t&&jE(h,t),u()},"cleanup"):u(),i}insert(e,t,r){if(t.length<=0)return;const i=this.doc;i!==null?Dn(i,s=>{const o=p0(s,this,e,!r);r||(r={},o.currentAttributes.forEach((a,c)=>{r[c]=a})),qS(s,this,o,t,r)}):this._pending.push(()=>this.insert(e,t,r))}insertEmbed(e,t,r){const i=this.doc;i!==null?Dn(i,s=>{const o=p0(s,this,e,!r);qS(s,this,o,t,r||{})}):this._pending.push(()=>this.insertEmbed(e,t,r||{}))}delete(e,t){if(t===0)return;const r=this.doc;r!==null?Dn(r,i=>{B2(i,p0(i,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,r){if(t===0)return;const i=this.doc;i!==null?Dn(i,s=>{const o=p0(s,this,e,!1);o.right!==null&&F2(s,this,o,t,r)}):this._pending.push(()=>this.format(e,t,r))}removeAttribute(e){this.doc!==null?Dn(this.doc,t=>{G_(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){this.doc!==null?Dn(this.doc,r=>{Eb(r,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return wb(this,e)}getAttributes(){return HP(this)}_write(e){e.writeTypeRef(BQ)}}const xQ=n=>new Oo;class XS{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Si()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Ac||t.constructor===Ca)&&t._start!==null)e=t._start;else for(;e!==null;)if(e.right!==null){e=e.right;break}else e.parent===this._root?e=null:e=e.parent._item;while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Ca extends cr{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ca}clone(){const e=new Ca;return e.insert(0,this.toArray().map(t=>t instanceof cr?t.clone():t)),e}get length(){return this.doc??Si(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new XS(this,e)}querySelector(e){e=e.toUpperCase();const r=new XS(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),Rl(new XS(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){iy(this,e,new wQ(this,t,e))}toString(){return UP(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),Mp(this,s=>{i.insertBefore(s.toDOM(e,t,r),null)}),i}insert(e,t){this.doc!==null?Dn(this.doc,r=>{zP(r,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(this.doc!==null)Dn(this.doc,r=>{const i=e&&e instanceof cr?e._item:e;H_(r,this,i,t)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(s=>s===e)+1;if(i===0&&e!==null)throw Il("Reference item not found");r.splice(i,0,...t)}}delete(e,t=1){this.doc!==null?Dn(this.doc,r=>{VP(r,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return DP(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return FP(this,e)}slice(e=0,t=this.length){return PP(this,e,t)}forEach(e){Mp(this,e)}_write(e){e.writeTypeRef(VQ)}}const SQ=n=>new Ca;class Ac extends Ca{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new Ac(this.nodeName)}clone(){const e=new Ac(this.nodeName),t=this.getAttributes();return nZ(t,(r,i)=>{typeof r=="string"&&e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof cr?r.clone():r)),e}toString(){const e=this.getAttributes(),t=[],r=[];for(const a in e)r.push(a);r.sort();const i=r.length;for(let a=0;a0?" "+t.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(e){this.doc!==null?Dn(this.doc,t=>{G_(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){this.doc!==null?Dn(this.doc,r=>{Eb(r,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return wb(this,e)}hasAttribute(e){return GP(this,e)}getAttributes(e){return e?hQ(this,e):HP(this)}toDOM(e=document,t={},r){const i=e.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const a=s[o];typeof a=="string"&&i.setAttribute(o,a)}return Mp(this,o=>{i.appendChild(o.toDOM(e,t,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(zQ),e.writeKey(this.nodeName)}}const EQ=n=>new Ac(n.readKey());class wQ extends ny{constructor(e,t,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class zf extends Ma{constructor(e){super(),this.hookName=e}_copy(){return new zf(this.hookName)}clone(){const e=new zf(this.hookName);return this.forEach((t,r)=>{e.set(r,t)}),e}toDOM(e=document,t={},r){const i=t[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(e){e.writeTypeRef(HQ),e.writeKey(this.hookName)}}const TQ=n=>new zf(n.readKey());class Wu extends Oo{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new Wu}clone(){const e=new Wu;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const t=[];for(const i in e.attributes){const s=[];for(const o in e.attributes[i])s.push({key:o,value:e.attributes[i][o]});s.sort((o,a)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(GQ)}}const bQ=n=>new Wu;class Tb{constructor(e,t){this.id=e,this.length=t}get deleted(){throw va()}mergeWith(e){return!1}write(e,t,r){throw va()}integrate(e,t){throw va()}}const AQ=0;class Ms extends Tb{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),RP(e.doc.store,this)}write(e,t){e.writeInfo(AQ),e.writeLen(this.length-t)}getMissing(e,t){return null}}class fm{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new fm(this.content)}splice(e){throw va()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}const MQ=n=>new fm(n.readBuf());class Cp{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Cp(this.len)}splice(e){const t=new Cp(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){z_(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const CQ=n=>new Cp(n.readLen()),XP=(n,e)=>new zc({guid:n,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class dm{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new dm(XP(this.doc.guid,this.opts))}splice(e){throw va()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const RQ=n=>new dm(XP(n.readString(),n.readAny()));class sh{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new sh(this.embed)}splice(e){throw va()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}const kQ=n=>new sh(n.readJSON());class Gr{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Gr(this.key,this.value)}splice(e){throw va()}mergeWith(e){return!1}integrate(e,t){const r=t.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const IQ=n=>new Gr(n.readKey(),n.readJSON());class W_{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new W_(this.arr)}splice(e){const t=new W_(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const r=this.arr.length;e.writeLen(r-t);for(let i=t;i{const e=n.readLen(),t=[];for(let r=0;r{const e=n.readLen(),t=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",t.str="�"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}}const PQ=n=>new Ra(n.readString()),DQ=[dQ,mQ,xQ,EQ,SQ,TQ,bQ],UQ=0,FQ=1,BQ=2,zQ=3,VQ=4,HQ=5,GQ=6;class Vc{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Vc(this.type._copy())}splice(e){throw va()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const WQ=n=>new Vc(DQ[n.readTypeRef()](n)),j_=(n,e,t)=>{const{client:r,clock:i}=e.id,s=new Ur(an(r,i+t),e,an(r,i+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=an(e.redone.client,e.redone.clock+t)),e.right=s,s.right!==null&&(s.right.left=s),n._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=t,s};class Ur extends Tb{constructor(e,t,r,i,s,o,a,c){super(e,c.getLength()),this.origin=r,this.left=t,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?y2:0}set marker(e){(this.info&HS)>0!==e&&(this.info^=HS)}get marker(){return(this.info&HS)>0}get keep(){return(this.info&v2)>0}set keep(e){this.keep!==e&&(this.info^=v2)}get countable(){return(this.info&y2)>0}get deleted(){return(this.info&VS)>0}set deleted(e){this.deleted!==e&&(this.info^=VS)}markDeleted(){this.info|=VS}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=ri(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=ri(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===yf&&this.id.client!==this.parent.client&&this.parent.clock>=ri(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=O2(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Nl(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ms||this.right&&this.right.constructor===Ms)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Ur&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===Ur&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===yf){const r=$S(t,this.parent);r.constructor===Ms?this.parent=null:this.parent=r.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=O2(e,e.doc.store,an(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),f0(this.origin,i.origin)){if(i.id.client{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),z_(e.deleteSet,this.id.client,this.id.clock,this.length),P2(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Aa();this.content.gc(e),t?KZ(e,this,new Ms(this.id,this.length)):this.content=new Cp(this.length)}write(e,t){const r=t>0?an(this.id.client,this.id.clock+t-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&Qv|(r===null?0:Ns)|(i===null?0:_c)|(s===null?0:Sp);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const l=qZ(a);e.writeParentInfo(!0),e.writeString(l)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===yf?(e.writeParentInfo(!1),e.writeLeftID(a)):Aa();s!==null&&e.writeString(s)}this.content.write(e,t)}}const KP=(n,e)=>jQ[e&Qv](n),jQ=[()=>{Aa()},CQ,NQ,MQ,PQ,kQ,IQ,WQ,LQ,RQ,()=>{Aa()}],$Q=10;class Ys extends Tb{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){Aa()}write(e,t){e.writeInfo($Q),Ht(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const YP=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},ZP="__ $YJS$ __";YP[ZP]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");YP[ZP]=!0;let XE,KE,qQ=n=>n();function XQ(n,e){if(KE)return KE(n,e);qQ(n)}function $u(n,e,t){if(XE)return XE.apply(null,arguments);throw new Error("observable implementation not provided. Call enableReactiveBindings, enableVueBindings or enableMobxBindings.")}function KQ(n){XE=function(e,t,r){const i=n.createAtom(e);return t&&t(),i},KE=(e,t)=>n.reaction(e,t,{fireImmediately:!1})}const z2=new WeakSet;function YQ(n){if(z2.has(n))return n;z2.add(n);let e;const t=new Map;function r(){if(!e){const h=p=>{(p.changes.added.size||p.changes.deleted.size||p.changes.keys.size||p.changes.delta.length)&&e.reportChanged()};e=$u("map",()=>{n.observe(h)},()=>{n.unobserve(h)})}e.reportObserved(n._implicitObserver)}function i(h){let p=t.get(h);if(!p){const m=g=>{p.reportChanged()};p=$u(h+"",()=>{n.observe(m)},()=>{n.unobserve(m)}),t.set(h,p)}p.reportObserved(n._implicitObserver)}const s=n.get;n.get=function(h){if(typeof h!="number")throw new Error("unexpected");return i(h),Reflect.apply(s,this,arguments)};function o(h){const p=n[h];n[h]=function(){return r(),Reflect.apply(p,this,arguments)}}function a(h){let p=n,m=Object.getOwnPropertyDescriptor(p,h);if(m||(p=Object.getPrototypeOf(p),m=Object.getOwnPropertyDescriptor(p,h)),m||(p=Object.getPrototypeOf(p),m=Object.getOwnPropertyDescriptor(p,h)),!m)throw new Error("property not found");const g=m.get;m.get=function(){return this._disableTracking||r(),Reflect.apply(g,this,arguments)},Object.defineProperty(n,h,m)}function c(h,p){let m=n,g=Object.getOwnPropertyDescriptor(m,h);if(g||(m=Object.getPrototypeOf(m),g=Object.getOwnPropertyDescriptor(m,h)),g||(m=Object.getPrototypeOf(m),g=Object.getOwnPropertyDescriptor(m,h)),!g)throw new Error("property not found");Object.defineProperty(n,p,g)}o("forEach"),o("toJSON"),o("toArray"),o("slice"),o("map"),c("length","lengthUntracked"),a("length");const l=n.push;n.push=function(h){this._disableTracking=!0;const p=l.call(this,h);return this._disableTracking=!1,p};const u=n.slice;return n.slice=function(h,p){this._disableTracking=!0;const m=u.call(this,h,p);return this._disableTracking=!1,m},n}const V2=new WeakSet;function ZQ(n){if(V2.has(n))return n;V2.add(n);let e;function t(){if(!e){let s=Array.from(n.share.keys());const o=a=>{const c=Array.from(n.share.keys());JSON.stringify(s)!==JSON.stringify(c)&&(s=c,e.reportChanged())};e=$u("map",()=>{n.on("beforeObserverCalls",o)},()=>{n.off("beforeObserverCalls",o)})}e.reportObserved(n._implicitObserver)}const r=n.get;n.get=function(s){if(typeof s!="string")throw new Error("unexpected");const o=Reflect.apply(r,this,arguments);return sy(o),o};function i(s){const o=n[s];let a;n[s]=function(){let c,l=arguments;return t(),a&&a.removeObservers(),a=XQ(()=>(c=Reflect.apply(o,n,l),c),()=>e.reportChanged()),c}}return i("toJSON"),Object.defineProperty(n,"keys",{get:()=>(t(),Object.keys(n.share))}),n}const H2=new WeakSet;function QQ(n){if(H2.has(n))return n;H2.add(n);let e;const t=new Map;function r(){if(!e){const a=c=>{(c.changes.added.size||c.changes.deleted.size||c.changes.keys.size||c.changes.delta.length)&&e.reportChanged()};e=$u("map",()=>{n.observe(a)},()=>{n.unobserve(a)})}e.reportObserved(n._implicitObserver)}function i(a){let c=t.get(a);if(!c){const l=u=>{u.keysChanged.has(a)&&(u.changes.added.size||u.changes.deleted.size||u.changes.keys.size||u.changes.delta.length)&&c.reportChanged()};c=$u(a,()=>{n.observe(l)},()=>{n.unobserve(l)}),t.set(a,c)}c.reportObserved(n._implicitObserver)}const s=n.get;n.get=function(a){if(typeof a!="string")throw new Error("unexpected");return i(a),Reflect.apply(s,this,arguments)};function o(a){const c=n[a];n[a]=function(){return r(),Reflect.apply(c,this,arguments)}}return o("values"),o("entries"),o("keys"),o("forEach"),o("toJSON"),n}const G2=new WeakSet;function W2(n){if(G2.has(n))return n;G2.add(n);let e;const t=i=>{e.reportChanged()};e=$u("text",()=>{n.observe(t)},()=>{n.unobserve(t)});function r(i){const s=n[i];n[i]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(s,this,arguments)}}return r("toString"),r("toJSON"),n}const j2=new WeakSet;function $2(n){if(j2.has(n))return n;j2.add(n);let e;const t=s=>{(s.changes.added.size||s.changes.deleted.size||s.changes.keys.size||s.changes.delta.length)&&e.reportChanged()};e=$u("xml",()=>{n.observe(t)},()=>{n.unobserve(t)});function r(s){const o=n[s];n[s]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(o,this,arguments)}}function i(s){let o=n,a=Object.getOwnPropertyDescriptor(o,s);if(a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),!a)throw new Error("property not found");const c=a.get;a.get=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(c,this,arguments)},Object.defineProperty(n,s,a)}return r("toString"),r("toDOM"),r("toArray"),r("getAttribute"),i("firstChild"),n}function sy(n){return n instanceof Wu||n instanceof Oo?W2(n):n instanceof ya?YQ(n):n instanceof Ma?QQ(n):n instanceof zc||Object.prototype.hasOwnProperty.call(n,"autoLoad")?ZQ(n):n instanceof Ca||n instanceof Ac?$2(n):n}function q2(n){n.share.forEach(e=>{e.constructor!==cr&&sy(e)})}function X2(n,e){for(let r=n.length-1;r>=e;r--){let i=n[r];if(!i.deleted){var t;if(i instanceof Ms)continue;(t=i.content)==null||t.getContent().forEach(s=>{s instanceof cr&&sy(s)})}}}const K2=new WeakSet;function JQ(n){K2.has(n)||(K2.add(n),sy(n),n.store.clients.forEach(e=>{e&&X2(e,0)}),q2(n),n.on("beforeObserverCalls",e=>{q2(n),e.afterState.forEach((t,r)=>{const i=e.beforeState.get(r)||0;if(i!==t){const s=e.doc.store.clients.get(r);if(!s)return;const o=No(s,i);X2(s,o)}})}))}class Rp{constructor(e){this.value=void 0,this.value=e}}function eJ(n){return ArrayBuffer.isView(n)?new Rp(n):new Rp(Object.freeze(n))}function tJ(n){const e=function(){var a;let c=(a=this[so])==null?void 0:a.implicitObserver;return n._implicitObserver=c,n.slice.bind(n).apply(n,arguments).map(u=>{const h=oy(u,c);return c&&typeof h=="object"?Df(h,c):h})},t=function(a){return a.map(c=>{const l=bb(c);let u=Ol(l)||l;if(u instanceof Rp&&(u=u.value),u instanceof cr&&u.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return u})},r=function(){return[].findIndex.apply(e.apply(this),arguments)},i={slice:e,unshift:(...o)=>(n.unshift(t(o)),n.lengthUntracked),push:(...o)=>(n.push(t(o)),n.lengthUntracked),insert:n.insert.bind(n),toJSON:n.toJSON.bind(n),forEach:function(){return[].forEach.apply(e.apply(this),arguments)},every:function(){return[].every.apply(e.apply(this),arguments)},filter:function(){return[].filter.apply(e.apply(this),arguments)},find:function(){return[].find.apply(e.apply(this),arguments)},findIndex:r,some:function(){return[].some.apply(e.apply(this),arguments)},includes:function(){return[].includes.apply(e.apply(this),arguments)},map:function(){return[].map.apply(e.apply(this),arguments)},indexOf:function(){const o=arguments[0];return r.call(this,a=>oJ(a,o))},splice:function(){let o=arguments[0]<0?n.length-Math.abs(arguments[0]):arguments[0],a=arguments[1],c=Array.from(Array.from(arguments).slice(2)),l=e.apply(this,[o,Number.isInteger(a)?o+a:void 0]);return n.doc?n.doc.transact(()=>{n.delete(o,a),n.insert(o,t(c))}):(n.delete(o,a),n.insert(o,t(c))),l}},s=[];for(let o in i)s[o]=i[o];return s}function Ud(n){if(typeof n=="string"&&n.trim().length){const e=Number(n);if(Number.isInteger(e))return e}return n}function Y2(n,e=new ya){if(e[Fr])throw new Error("unexpected");const t=tJ(e),r=new Proxy(t,{set:(i,s,o)=>{throw typeof Ud(s)!="number"?new Error:new Error("array assignment is not implemented / supported")},get:(i,s,o)=>{const a=Ud(s);if(a===ay)return e;if(typeof a=="number"){let u;if(o&&o[so]){var c;u=(c=o[so])==null?void 0:c.implicitObserver,e._implicitObserver=u}let h=e.get(a);return h=oy(h,u),h}if(a===Symbol.toStringTag)return"Array";if(a===Symbol.iterator){const u=e.slice();return Reflect.get(u,a)}return a==="length"?e.length:Reflect.get(i,a,o)},deleteProperty:(i,s)=>{const o=Ud(s);if(typeof o!="number")throw new Error;return o=0?(e.delete(o),!0):!1},has:(i,s)=>{const o=Ud(s);return typeof o!="number"?Reflect.has(i,o):o=0},getOwnPropertyDescriptor(i,s){const o=Ud(s);if(o==="length")return{enumerable:!1,configurable:!1,writable:!0};if(typeof o=="number"&&o>=0&&o{const s=[];for(let o=0;o{if(typeof i!="string")throw new Error;const o=bb(s);let a=Ol(o)||o;if(a instanceof Rp&&(a=a.value),a instanceof cr&&a.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return e.set(i,a),!0},get:(r,i,s)=>{if(i===ay)return e;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[so]){var a;o=(a=s[so])==null?void 0:a.implicitObserver,e._implicitObserver=o}let c=e.get(i);return c=oy(c,o),c},deleteProperty:(r,i)=>{if(typeof i!="string")throw new Error;return e.has(i)?(e.delete(i),!0):!1},has:(r,i)=>!!(typeof i=="string"&&e.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&e.has(i))return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(e.keys())});ap.set(e,t);for(let r in n)t[r]=n[r];return t}function nJ(n){return n instanceof cr}const ap=new WeakMap;function oy(n,e){if(nJ(n)){if(n._implicitObserver=e,n instanceof ya||n instanceof Ma){if(!ap.has(n)){const t=bb(n);ap.set(n,t)}n=ap.get(n)}else if(n instanceof Ac||n instanceof Ca||n instanceof Wu||n instanceof zf||n instanceof Oo)ab(n),n.__v_skip=!0;else throw new Error("unknown YType");return n}else{if(n===null)return null;if(typeof n=="object")return eJ(n)}return n}function bb(n){if(n==null)return n;if(n=Ol(n)||n,n instanceof ya)return Y2([],n);if(n instanceof Ma)return Z2({},n);if(typeof n=="string")return n;if(Array.isArray(n))return Y2(n);if(n instanceof Ac||n instanceof Ca||n instanceof Wu||n instanceof zf)return n;if(n instanceof Oo)return n;if(typeof n=="object")return n instanceof Rp?n:Z2(n);if(typeof n=="number"||typeof n=="boolean")return n;throw new Error("invalid")}function rJ(n){for(let[e,t]of Object.entries(n))if(Array.isArray(t)){if(t.length!==0)throw new Error("Root Array initializer must always be empty array")}else if(t&&typeof t=="object"){if(Object.keys(t).length!==0||Object.getPrototypeOf(t)!==Object.prototype)throw new Error("Root Object initializer must always be {}")}else if(t!=="xml"&&t!=="text")throw new Error("unknown Root initializer")}function Q2(n,e,t){let r=e[t];if(!r){t!=="__v_raw"&&t!=="__v_isRef"&&t!=="__v_isReadonly"&&console.warn("property not found on root doc",t);return}return r==="xml"?n.getXmlFragment(t):r==="text"?n.getText(t):Array.isArray(r)?n.getArray(t):n.getMap(t)}function iJ(n,e){if(n[Fr])throw new Error("unexpected");rJ(e);const t=new Proxy({},{set:(r,i,s)=>{throw typeof i!="string"?new Error:new Error("cannot set new elements on root doc")},get:(r,i,s)=>{if(i===ay)return n;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[so]){var a;o=(a=s[so])==null?void 0:a.implicitObserver,n._implicitObserver=o}if(i==="toJSON"){for(let u of Object.keys(e))Q2(n,e,u);return Reflect.get(n,i)}let c=Q2(n,e,i);return c=oy(c,o),c},deleteProperty:(r,i)=>{throw new Error("deleteProperty not available for doc")},has:(r,i)=>!!(typeof i=="string"&&n.share.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&n.share.has(i)||i==="toJSON")return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(n.share.keys())});return ap.set(n,t),t}KQ(pY);const ay=Symbol("INTERNAL_SYMBOL");function J2(n,e){const t=Ol(n)||n;if(!t)throw new Error("not a valid synced object");return t instanceof zc?(t.on("update",e),()=>{t.off("update",e)}):(t.observeDeep(e),()=>{t.unobserveDeep(e)})}function sJ(n){const e=Ol(n);if(!(e instanceof zc))throw new Error("store is not a valid syncedStore that maps to a Y.Doc");return e}function Ol(n){if(typeof n!="object"||n===null)return;const e=n[ay];return e&&(ab(e),e.__v_skip=!0),e}function oJ(n,e){if(n===e)return!0;if(typeof n=="object"&&typeof e=="object"){const t=Ol(n),r=Ol(e);return!t||!r?!1:t===r}return!1}function aJ(n,e=new zc){return JQ(e),iJ(e,n)}function cJ(n,e){var t=ke.useReducer(function(a){return a+1},0),r=t[1],i=ke.useRef(),s=ke.useRef(!1);i.current||(i.current=new sb(function(){s.current&&r()}));var o=ke.useMemo(function(){var a;return(a=i.current)==null||a.removeObservers(),Df(n,i.current)},[]);return ke.useEffect(function(){return s.current=!0,i.current||r(),function(){var a;s.current=!1,(a=i.current)==null||a.removeObservers(),i.current=null}},[]),o}function lJ(n,e){if(!Ol(n))throw new Error("syncedObject passed to useSyncedStore is not a SyncedStore Store or internal data type.");return cJ(n)}const Ab=0,QP=1,JP=2,uJ=(n,e)=>{Ht(n,Ab);const t=jZ(e);vi(n,t)},eD=(n,e,t)=>{Ht(n,QP),vi(n,VZ(e,t))},hJ=(n,e,t)=>eD(e,t,Ii(n)),tD=(n,e,t)=>{try{FZ(e,Ii(n),t)}catch(r){console.error("Caught error while handling a Yjs update",r)}},fJ=(n,e)=>{Ht(n,JP),vi(n,e)},dJ=tD,pJ=(n,e,t,r)=>{const i=Gt(n);switch(i){case Ab:hJ(n,e,t);break;case QP:tD(n,t,r);break;case JP:dJ(n,t,r);break;default:throw new Error("Unknown message type")}return i},ka=aJ({shared:[]});function pm(n,e,t){return n.find(r=>r.key===e&&r.type===t)}function mJ(){return lJ(ka)}function nD(n,e){const t=mJ(),r=pm(t.shared,n,e);return K(r)?r:void 0}function Mb(n){return nD(n,0)}function rD(n){return nD(n,1)}function iD(n,e,t){const r=pm(ka.shared,n,e);K(r)||ka.shared.push({key:n,type:e,value:t})}function gJ(n,e){iD(n,0,e)}function sD(n,e){const t=new Oo(e);iD(n,1,t)}function El(n,e){const t=pm(ka.shared,n,0);if(K(t)){t.value=e;return}ka.shared.push({key:n,type:0,value:e})}function _J(n,e){const t=new Oo(e),r=pm(ka.shared,n,1);if(K(r)){r.value=t;return}ka.shared.push({key:n,type:1,value:t})}function oD(n,e,t){let r;function i(){const o=pm(ka.shared,n,e);K(o)&&(s(),r=J2(o,()=>t(o.value)))}const s=J2(ka.shared,i);return i(),()=>r==null?void 0:r()}function vJ(n,e){return oD(n,0,e)}function yJ(n,e){return oD(n,1,t=>e(t.toJSON()))}function t_(n){return To(n)}let ek=!1;const _l=sJ(ka),ac=Qu("modem",["second"],n=>{switch(n.target){case"second":!ek&&n.data%2===0&&ac.emit("modem:join");break;case"join":if(n.sender!==ac.id()){ac.reply(n,"joinack");const e=Sl();uJ(e,_l),ac.reply(n,"sync",t_(e));const t=Sl();eD(t,_l),ac.reply(n,"sync",t_(t))}break;case"joinack":ek=!0;break;case"sync":{if(K(n.data)&&n.sender!==ac.id()){const e=ih(n.data),t=Sl();pJ(e,t,_l,ac)===Ab&&ac.emit("modem:sync",t_(t))}break}}});function aD(n){const e=Sl();fJ(e,n),ac.emit("modem:sync",t_(e))}_l.on("update",aD);_l.on("destroy",()=>{_l==null||_l.off("update",aD)});function m0(n,e){function t(r){console.error(r),Pn(n,"crash",r.message)}e().catch(t)}const YE=66.666,$_=Math.round(1e3/YE),xJ=3;function Hh(n){return new Promise(e=>setTimeout(e,n))}const Ll="$dkpurple",SJ="$196",EJ="$205";function ws(n,e){return`$${n}${e}$blue`}function tk(n,e){return`$${n}${e}$ondkblue`}function qn(n,e){eo(n,e)}function wJ(n,e){const t=SJ.repeat(e);qn(n,`${Ll}${t}`)}function Cb(n,e){const t=EJ.repeat(e);qn(n,`${Ll}${t}`)}function lc(n,e){qn(n,`${Ll} ${" ".repeat(e.length)} `),wJ(n,e.length+2),qn(n,`${Ll} $white${e} `),Cb(n,e.length+2)}function ic(n,e){qn(n,`${Ll} ${" ".repeat(e.length)} `),qn(n,`${Ll} $gray${e} `),Cb(n,e.length+2)}function rn(n,e,t){qn(n,`${Ll} $white${e} $blue${t}`)}function un(n,e){qn(n,`${Ll}$blue${e}`)}function nk(n,e,t){qn(n,`!copyit ${e};${t}`)}function TJ(){try{const n=window.location.hash.slice(1);if(n.length)return n}catch(n){Pn("register","crash",n.message)}return""}let ZE=!0;window.addEventListener("hashchange",()=>{ZE?window.location.reload():ZE=!0});function bJ(n){const e=`#${n}`;window.location.hash!==e&&(ZE=!1,window.location.hash=e,eo(Nr.name(),`wrote ${(n==null?void 0:n.length)??0} chars [${n.slice(0,8)}...${n.slice(-8)}]`))}const n_="bios-node";function AJ(n){try{const e=localStorage.getItem(n_);return K(e)?e:(localStorage.setItem(n_,n),n)}catch(e){Pn(Nr.name(),n_,e.message)}}function MJ(){localStorage.removeItem(n_)}const q_="bios-select";function CJ(){try{return localStorage.getItem(q_)??""}catch(n){Pn(Nr.name(),q_,n.message)}return""}function RJ(n){try{localStorage.setItem(q_,n)}catch(e){Pn(Nr.name(),q_,e.message)}}async function rk(n){const e=new FormData;e.append("url",n);const t=new Request("https://bytes.zed.cafe",{method:"POST",body:e});return await(await fetch(t)).text()}let KS=0;const ik=1,Nr=Qu("register",["second","ready","error"],function(n){const e=is.getState();switch(n.target){case"error:login:main":case"error:login:title":case"error:login:player":PR(Nr.name());break;case"dev":m0("register:dev",async function(){if(window.location.href.includes("/locked/")?"locked":""){const r=await rk(window.location.href);nk("devshare",r,r)}else lc(Nr.name(),"creating locked terminal"),await Hh(100),window.location.href=window.location.href.replace("/#","/locked/#")});break;case"share":m0("register:share",async function(){const t=await rk(window.location.href.replace(/cafe.*locked/,"cafe"));nk("share",t,t)});break;case"refresh":m0("register:refresh",async function(){lc(Nr.name(),"BYE"),await Hh(100),window.location.reload()});break;case"nuke":m0("register:nuke",async function(){lc(Nr.name(),"nuke in"),rn(Nr.name(),"3","..."),await Hh(1e3),rn(Nr.name(),"2","..."),await Hh(1e3),rn(Nr.name(),"1","..."),await Hh(1e3),lc(Nr.name(),"BYE"),await Hh(100),window.location.hash="",window.location.reload()});break;case"ready":{if(!K(n.player))return;const t=AJ(n.player);if(!K(t))return;e.gadget.player||(is.setState(r=>({...r,gadget:{...r.gadget,player:t}})),setTimeout(()=>EW("register",t),256));break}case"ackinit":{if(!K(n.player))return;const t=TJ();if(t.length===0){Pn(Nr.name(),"content","no content found"),PR(Nr.name());return}wW(Nr.name(),t,CJ(),n.player);break}case"ackbooks":K(n.player)&&TW(Nr.name(),n.player);break;case"acklogin":if(K(n.player)){const{player:t}=n;hT(Nr.name()),setTimeout(()=>uW(Nr.name(),t),1e3)}break;case"flush":if(fn(n.data)){const[t,r]=n.data;Kt(t)&&Kt(r)&&(document.title=t,bJ(r))}break;case"select":Kt(n.data)&&RJ(n.data);break;case"nodetrash":MJ();break;case"second":++KS,KS>=ik&&(KS-=ik,e.gadget.player&&AW(Nr.name(),e.gadget.player));break}});Qu("tape",[],n=>{const{layout:e,terminal:t,editor:r}=Ji.getState();function i(o){let a=[[fr(),o.target,o.sender,...o.data],...t.logs];a.length>c2&&(a=a.slice(0,c2)),Ji.setState(c=>({terminal:{...c.terminal,logs:a}}))}function s(o){let c=e+(o?1:-1);if(c<0&&(c+=Oi.MAX),c>=Oi.MAX&&(c-=Oi.MAX),!r.open)switch(c){case Oi.SPLIT_Y:case Oi.SPLIT_Y_ALT:c=Oi.TOP;break}Ji.setState({layout:c})}switch(n.target){case"info":t.level>=K0.INFO&&i(n);break;case"debug":t.level>=K0.DEBUG&&i(n);break;case"error":t.level>K0.OFF&&i(n);break;case"crash":Ji.setState(o=>({layout:Oi.FULL,terminal:{...o.terminal,open:!0}}));break;case"terminal:open":Ji.setState(o=>({terminal:{...o.terminal,open:!0}}));break;case"terminal:close":Ji.setState(o=>({terminal:{...o.terminal,open:!1}}));break;case"terminal:inclayout":jG(n.data)&&s(n.data);break;case"editor:open":if(fn(n.data)&&K(n.player)){const{player:o}=n,[a,c,l,u]=n.data??["","",""];Ji.setState(h=>({terminal:{...h.terminal,open:!0},editor:{open:!0,player:o,book:a,page:c,type:l,title:u}}))}break;case"editor:close":Ji.setState(o=>({editor:{...o.editor,open:!1}}));break}});const YS=Qu("clock",[],()=>{});let ZS=0,g0=0,QS=0,sk=performance.now();function cD(){const n=performance.now(),e=n-sk,t=window.location.href.includes("/locked/")?"locked":"";QS+=e,QS>=YE&&(QS%=YE,YS.emit("tick",g0,t),YS.emit("tock",g0,t),++ZS,++g0,ZS>=$_&&(ZS%=$_,YS.emit("second",g0,t))),sk=n,setTimeout(cD,1)}cD();let _0;function kJ(){if(K(_0))return;_0=new rY;const n=nY(e=>_0.postMessage(e));_0.addEventListener("message",e=>n(e.data))}const QE=3,lD=2,xf=8,Sf=14,ss=xf*lD,zi=Sf*lD,fc=16;var Kd=(n=>(n[n.BLANK=0]="BLANK",n[n.TILES=1]="TILES",n[n.SPRITES=2]="SPRITES",n[n.DITHER=3]="DITHER",n[n.MEDIA=4]="MEDIA",n[n.CONTROL=5]="CONTROL",n))(Kd||{});function IJ(n){let e=0,t=0,r=0,i=0,s=1;return n.forEach(o=>{switch(o.type){case 1:e=Math.max(e,o.width),t=Math.max(t,o.height);break;case 3:e=Math.max(e,o.width),t=Math.max(t,o.height);break;case 5:r=o.focusx,i=o.focusy,s=o.viewscale;break}}),{width:e,height:t,focusx:r,focusy:i,viewscale:s}}var yi=(n=>(n[n.START=0]="START",n[n.LEFT=1]="LEFT",n[n.RIGHT=2]="RIGHT",n[n.TOP=3]="TOP",n[n.BOTTOM=4]="BOTTOM",n[n.SCROLL=5]="SCROLL",n))(yi||{});const NJ={start:0,left:1,right:2,top:3,bottom:4,scroll:5},OJ={0:1,1:20,2:20,3:1,4:1,5:40};function ld(n,e){return`${n}:${e}`}const uD=1,hD=16,fD=256;var De=(n=>(n[n.NONE=0]="NONE",n[n.ALT=1]="ALT",n[n.CTRL=2]="CTRL",n[n.SHIFT=3]="SHIFT",n[n.MOVE_UP=4]="MOVE_UP",n[n.MOVE_DOWN=5]="MOVE_DOWN",n[n.MOVE_LEFT=6]="MOVE_LEFT",n[n.MOVE_RIGHT=7]="MOVE_RIGHT",n[n.OK_BUTTON=8]="OK_BUTTON",n[n.CANCEL_BUTTON=9]="CANCEL_BUTTON",n[n.MENU_BUTTON=10]="MENU_BUTTON",n[n.SHOOT_UP=11]="SHOOT_UP",n[n.SHOOT_DOWN=12]="SHOOT_DOWN",n[n.SHOOT_LEFT=13]="SHOOT_LEFT",n[n.SHOOT_RIGHT=14]="SHOOT_RIGHT",n))(De||{});const LJ=new xe,dD=ke.createContext([]);function cy(){return ke.useContext(dD)}function PJ({width:n=0,height:e=0,children:t,...r}){const i=ke.useRef(null),[s]=ke.useState(()=>{const a=[];return n&&a.push(new yo,new yo),e&&a.push(new yo,new yo),a}),[o]=ke.useState(()=>[new xe(0,0,0),new xe(0,0,0),new xe(0,0,0),new xe(0,0,0),new xe(0,0,0)]);return Tv(()=>{if(i.current){const a=i.current.localToWorld(o[0].set(0,0,0)),c=[];if(n){const l=n*.5;c.push(i.current.localToWorld(o[3].set(l,0,0)),i.current.localToWorld(o[4].set(-l,0,0)))}if(e){const l=e*.5;c.push(i.current.localToWorld(o[1].set(0,l,0)),i.current.localToWorld(o[2].set(0,-l,0)))}for(let l=0;lSymbol.iterator in n,ak=n=>"entries"in n,ck=(n,e)=>{const t=n instanceof Map?n:new Map(n.entries()),r=e instanceof Map?e:new Map(e.entries());if(t.size!==r.size)return!1;for(const[i,s]of t)if(!Object.is(s,r.get(i)))return!1;return!0},DJ=(n,e)=>{const t=n[Symbol.iterator](),r=e[Symbol.iterator]();let i=t.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=t.next(),s=r.next()}return!!i.done&&!!s.done};function UJ(n,e){return Object.is(n,e)?!0:typeof n!="object"||n===null||typeof e!="object"||e===null?!1:!ok(n)||!ok(e)?ck({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)}):ak(n)&&ak(e)?ck(n,e):DJ(n,e)}function Hl(n){const e=bo.useRef();return t=>{const r=n(t);return UJ(e.current,r)?e.current:e.current=r}}const FJ=Date.now(),vo={get value(){return(Date.now()-FJ)/1e3%1e6}},BJ=120;let pD=0;function zJ(n){pD=BJ/n}zJ(150);const Rb={get value(){return pD}};function kb(n){const e=n.clone();return e.uniforms.time=vo,e.uniforms.interval=Rb,e}function VJ(n,e,t,r){const i=e*t*4;for(let s=0,o=0;s - - varying vec2 vUv; - - void main() { - vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); - gl_Position = projectionMatrix * mvPosition; - - vUv = uv; - - #include - } - `,fragmentShader:` - #include - - uniform vec3 color; - uniform sampler2D data; - - varying vec2 vUv; - - // adapted from https://www.shadertoy.com/view/Mlt3z8 - float bayerDither2x2( vec2 v ) { - return mod( 3.0 * v.y + 2.0 * v.x, 4.0 ); - } - - float bayerDither4x4( vec2 v ) { - vec2 P1 = mod( v, 2.0 ); - vec2 P2 = mod( floor( 0.5 * v ), 2.0 ); - return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 ); - } - - void main() { - #include - - float alpha = texture2D(data, vUv).r; - if (alpha < 1.0) { - vec2 ditherCoord = floor( mod( gl_FragCoord.xy, 4.0 ) ); - if ( bayerDither4x4( ditherCoord ) / 16.0 >= alpha ) { - discard; - } - } - - gl_FragColor.rgba = vec4(color.xyz, 1.0); - } - `});function WJ(){return kb(GJ)}function ly(n,e,t){typeof n!="number"&&(n=0,e=0,t=1),typeof e!="number"&&(e=n,n=0,t=1),typeof t!="number"&&(t=1);const r=[],i=Math.min(n,e),s=Math.max(n,e);for(let o=i;o<=s;o+=t)r.push(o);return r}function jJ(n){return n[Xd(0,n.length-1)]}function uc(...n){return jJ(n.flat())}function mD(n,e=16){return n?ly(e-1).map(t=>{const r=t*QE;return new cn(n.bits[r]/63,n.bits[r+1]/63,n.bits[r+2]/63)}):[]}function $J(n){const e=document.createElement("canvas");if(e.width=(n==null?void 0:n.width)||1,e.height=(n==null?void 0:n.height)||1,n){const t=e.getContext("2d"),r=t==null?void 0:t.getImageData(0,0,n.width,n.height);if(r&&t){let i=0;const{data:s}=r;for(let o=0;oIb(n),[n])}const X_=[0,1,0],yD=[1,1,0],K_=[1,0,0],xD=[0,0,0],tee=new Float32Array([...X_,...K_,...yD,...X_,...xD,...K_]),nee=new Float32Array([...X_.slice(0,2),...K_.slice(0,2),...yD.slice(0,2),...X_.slice(0,2),...xD.slice(0,2),...K_.slice(0,2)]);function ree(n,e,t,r,i,s){const o=e*t*4;for(let a=0,c=0;a{switch(a%3){case 0:return o*r;case 1:return o*i;default:return o}});n.setAttribute("position",new Qn(s,3)),n.setAttribute("uv",new Qn(nee,2)),n.computeBoundingBox(),n.computeBoundingSphere()}const see=mD(_D()),uk=Ib(uy()),oee=new Vi({transparent:!1,uniforms:{time:vo,interval:Rb,map:new Mn(uk),alt:new Mn(uk),data:new Mn(null),palette:new Mn(see),size:{value:new St},step:{value:new St}},vertexShader:` - #include - varying vec2 vUv; - void main() { - vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); - gl_Position = projectionMatrix * mvPosition; - vUv = uv; - #include - } - `,fragmentShader:` - #include - - uniform float time; - uniform float interval; - uniform sampler2D map; - uniform sampler2D alt; - uniform usampler2D data; - uniform vec3 palette[16]; - uniform vec2 size; - uniform vec2 step; - varying vec2 vUv; - - void main() { - #include - - uvec4 tiledata = texture(data, vUv); - int colori = int(tiledata.z); - int bgi = int(tiledata.w); - - vec2 charPosition = mod(vUv, size) / size; - vec2 uv = vec2(charPosition.x * step.x, charPosition.y * step.y); - vec3 color = palette[colori]; - - uv.x += step.x * float(tiledata.x); - uv.y += step.y * float(tiledata.y); - uv.y = 1.0 - uv.y; - - bool useAlt = mod(time, interval * 2.0) > interval; - vec3 blip = useAlt ? texture(alt, uv).rgb : texture(map, uv).rgb; - - if (blip.r == 0.0) { - if (bgi >= ${wn.ONCLEAR}) { - discard; - } - color = palette[bgi]; - } - - gl_FragColor.rgb = color; - gl_FragColor.a = 1.0; - } - `});function aee(){return kb(oee)}function hy({width:n,height:e,alphas:t}){const r=cy(),i=ke.useRef(null),[s]=ke.useState(()=>WJ());return ke.useEffect(()=>{s.uniforms.data.value=HJ(n,e)},[s.uniforms.data,n,e]),ke.useEffect(()=>{VJ(s.uniforms.data.value,n,e,t)},[s.uniforms.data.value,n,e,t]),ke.useEffect(()=>{i.current&&(SD(i.current,n,e),s.clipping=r.length>0,s.clippingPlanes=r,s.needsUpdate=!0)},[s,r,n,e]),_e.jsx("mesh",{material:s,children:_e.jsx("bufferGeometry",{ref:i})})}function cee({width:n,height:e,alpha:t}){const r=ke.useMemo(()=>new Array(n*e).fill(t),[n,e,t]);return _e.jsx(hy,{width:n,height:e,alphas:r})}const Fd=new FH,lu=new St;function lee({width:n,height:e,top:t,left:r,right:i,bottom:s,scale:o=.125,alpha:a=.25}){const c=ke.useMemo(()=>{const l=new Array(n*e);Fd.min.x=r,Fd.min.y=t,Fd.max.x=i,Fd.max.y=s,lu.x=0,lu.y=0;for(let u=0;u=n&&(lu.x=0,++lu.y);return l},[n,e,t,r,i,s,o,a]);return _e.jsx(hy,{width:n,height:e,alphas:c})}const uee=mD(_D()),hk=Ib(uy()),hee=$_*2,fee=new Vi({transparent:!1,uniforms:{time:vo,interval:Rb,smoothrate:new Mn(hee),map:new Mn(hk),alt:new Mn(hk),palette:new Mn(uee),pointSize:{value:new St(ss,zi)},rows:new Mn(1),step:new Mn(new St)},vertexShader:` - #include - - attribute float visible; - attribute vec4 charData; - attribute vec3 lastPosition; - attribute vec2 lastColor; - attribute vec2 lastBg; - attribute vec2 animShake; - attribute vec2 animBounce; - - uniform float smoothrate; - uniform float time; - uniform float interval; - uniform vec2 pointSize; - uniform vec3 palette[16]; - uniform float tindex; - - varying float vVisible; - varying vec2 vCharData; - varying vec3 vColor; - varying vec4 vBg; - - float rand(float co) { - return fract(sin(co*(91.3458)) * 47453.5453); - } - - vec3 colorFromIndex(float index) { - return palette[int(index)]; - } - - vec4 empty; - - vec4 bgFromIndex(float index) { - if (int(index) >= ${wn.ONCLEAR}) { - return empty; - } - vec4 bg; - bg.rgb = colorFromIndex(index); - bg.a = 1.0; - return bg; - } - - float animDelta(float startTime, float deltaMod, float maxDelta) { - float delta = time - startTime; - if (delta < 0.0) { - return maxDelta; - } - return clamp(delta * deltaMod, 0.0, maxDelta); - } - - void main() { - vVisible = visible; - - float deltaPosition = clamp((time - lastPosition.z) * smoothrate, 0.0, 1.0); - vec2 animPosition = mix(lastPosition.xy, position.xy, deltaPosition); - - float deltaShake = 1.0 - animDelta(animShake.y, smoothrate * 0.5, 1.0); - animPosition += vec2( - deltaShake - rand(cos(time) + animShake.x) * deltaShake * 2.0, - deltaShake - rand(sin(time) + animShake.x) * deltaShake * 2.0 - ) * 0.5; - - float deltaBounce = 1.0 - abs(1.0 - animDelta(animBounce.y, smoothrate, 2.0)); - animPosition.y -= smoothstep(0.0, 1.0, deltaBounce); - - float deltaColor = animDelta(lastColor.y, smoothrate, 1.0); - vec3 sourceColor = colorFromIndex(lastColor.x); - vec3 destColor = colorFromIndex(charData.z); - vColor = mix(sourceColor, destColor, deltaColor); - - float deltaBg = animDelta(lastBg.y, smoothrate, 1.0); - vec4 sourceBg = bgFromIndex(lastBg.x); - vec4 destBg = bgFromIndex(charData.w); - vBg = mix(sourceBg, destBg, deltaBg); - - vCharData.xy = charData.xy; - - animPosition = animPosition * pointSize; - animPosition += pointSize * 0.5; - animPosition.x += (pointSize.y - pointSize.x) * 0.5; - - vec4 mvPosition = modelViewMatrix * vec4(animPosition, 0.0, 1.0); - gl_Position = projectionMatrix * mvPosition; - - // this handles things being scaled - gl_PointSize = pointSize.y * modelViewMatrix[0][0]; - - #include - } - `,fragmentShader:` - #include - - uniform float time; - uniform float interval; - uniform sampler2D map; - uniform sampler2D alt; - uniform float rows; - uniform vec2 step; - uniform vec2 pointSize; - - varying float vVisible; - varying vec2 vCharData; - varying vec3 vColor; - varying vec4 vBg; - - void main() { - #include - - float xscale = pointSize.y / pointSize.x; - float px = gl_PointCoord.x * xscale; - - if (vVisible == 0.0 || px >= 1.0) { - discard; - } - - vec2 lookup = vec2(vCharData.x, vCharData.y); - - vec2 idx = vec2(px, 1.0 - gl_PointCoord.y); - vec2 char = vec2(lookup.x * step.x, (rows - lookup.y) * step.y); - vec2 uv = idx * step + char; - - bool useAlt = mod(time, interval * 2.0) > interval; - vec3 blip = useAlt ? texture2D(alt, uv).rgb : texture2D(map, uv).rgb; - - if (blip.r == 0.0) { - gl_FragColor = vBg; - } else { - gl_FragColor.rgb = vColor; - gl_FragColor.a = 1.0; - } - } - `});function dee(){return kb(fee)}const pee=uy(),fk=2048;function mee({sprites:n}){const e=vD(pee),t=cy(),r=ke.useRef(null),i=ke.useRef([]),[s]=ke.useState(()=>dee()),{width:o=0,height:a=0}=(e==null?void 0:e.image)??{};return ke.useMemo(()=>{var h;i.current.length===0&&(i.current=Array.from({length:fk},()=>({id:"",x:0,y:0,char:0,color:0,bg:0})));const c={};for(let p=0;pp.id));let u=0;for(let p=0;p{const{current:c}=r,{current:l}=i;if(!c||!l)return;let u=c.getAttribute("visible"),h=c.getAttribute("lastVisible"),p=c.getAttribute("position"),m=c.getAttribute("charData"),g=c.getAttribute("lastPosition"),v=c.getAttribute("lastColor"),y=c.getAttribute("lastBg"),_=c.getAttribute("animShake"),S=c.getAttribute("animBounce");if(!u||u.count!==l.length){u=new Qn(new Float32Array(l.length),1),h=new Qn(new Float32Array(l.length),1),p=new Qn(new Float32Array(l.length*3),3),m=new Qn(new Float32Array(l.length*4),4),g=new Qn(new Float32Array(l.length*3),3),v=new Qn(new Float32Array(l.length*2),2),y=new Qn(new Float32Array(l.length*2),2),_=new Qn(new Float32Array(l.length*2),2),S=new Qn(new Float32Array(l.length*2),2);for(let w=0;w{if(!e||!r.current)return;const c=Math.round(o/xf),l=Math.round(a/Sf);s.uniforms.rows.value=l-1,s.uniforms.step.value.x=1/c,s.uniforms.step.value.y=1/l,s.clipping=t.length>0,s.clippingPlanes=t,s.needsUpdate=!0},[e,s,o,a,t]),_e.jsx("points",{frustumCulled:!1,material:s,children:_e.jsx("bufferGeometry",{ref:r})})}const gee=uy();function ED({width:n,height:e,char:t,color:r,bg:i}){const s=vD(gee),o=cy(),[a]=ke.useState(()=>aee()),c=ke.useRef(null),{width:l=0,height:u=0}=(s==null?void 0:s.image)??{};return ke.useEffect(()=>{n===0||e===0||(a.uniforms.data.value=iee(n,e))},[a.uniforms.data,n,e]),ke.useEffect(()=>{n===0||e===0||ree(a.uniforms.data.value,n,e,t,r,i)},[a.uniforms.data.value,n,e,t,r,i]),ke.useEffect(()=>{n===0||e===0||!c.current||!s||(SD(c.current,n,e),a.uniforms.size.value.x=1/n,a.uniforms.size.value.y=1/e,a.uniforms.step.value.x=1/Math.round(l/xf),a.uniforms.step.value.y=1/Math.round(u/Sf),a.clipping=o.length>0,a.clippingPlanes=o,a.needsUpdate=!0)},[s,a,n,e,l,u,o]),_e.jsx("mesh",{material:a,children:_e.jsx("bufferGeometry",{ref:c})})}function _ee({id:n,z:e}){const t=is(Hl(r=>r.gadget.layers.find(i=>i.id===n)));switch(t==null?void 0:t.type){default:case Kd.BLANK:return null;case Kd.TILES:return _e.jsx("group",{position:[0,0,e],children:_e.jsx(ED,{width:t.width,height:t.height,char:[...t.char],color:[...t.color],bg:[...t.bg]})},t.id);case Kd.SPRITES:return _e.jsx("group",{position:[0,0,e],children:_e.jsx(mee,{sprites:[...t.sprites]})},t.id);case Kd.DITHER:return _e.jsx("group",{position:[0,0,e],children:_e.jsx(hy,{width:t.width,height:t.height,alphas:[...t.alphas]})},t.id)}}var Nb={};Object.defineProperty(Nb,"__esModule",{value:!0});var wD=Nb.GamepadHelper=void 0;const Yn=class Yn{static getButtonValue(e,t){var r,i;return(i=(r=Yn.gamepads[e])==null?void 0:r.buttons[t])==null?void 0:i.value}static getAxisValue(e,t){var r;return(r=Yn.gamepads[e])==null?void 0:r.axes[t]}static update(){Yn.checkForNewGamepads(),!(!Yn.gamepads||Object.keys(Yn.gamepads).length<1)&&(Yn.gamepadsLastUpdate&&Object.keys(Yn.gamepadsLastUpdate).length>0&&Object.values(Yn.gamepads).forEach(e=>{var t;for(let r=0;r1;m&&(p=p.slice(0,-1));var g=Lb(p),v=JS[g];if(p.length>1&&!v&&!TD[p]&&!Ob[g])throw new TypeError('Unknown modifier: "'+p+'"');(s===1||!v)&&(t?r.key=g:r.which=MD(p)),v&&(r[v]=m?null:!0)}}catch(y){c=!0,l=y}finally{try{!a&&u.return&&u.return()}finally{if(c)throw l}}return r}function AD(n,e){for(var t in n){var r=n[t],i=void 0;if(r!=null&&(t==="key"&&e.key!=null?i=e.key.toLowerCase():t==="which"?i=r===91&&e.which===93?91:e.which:i=e[t],!(i==null&&r===!1)&&i!==r))return!1}return!0}function MD(n){n=Lb(n);var e=Ob[n]||n.toUpperCase().charCodeAt(0);return e}function Lb(n){return n=n.toLowerCase(),n=TD[n]||n,n}var See=Hc.default=fy;Hc.isHotkey=fy;Hc.isCodeHotkey=yee;Hc.isKeyHotkey=xee;Hc.parseHotkey=bD;Hc.compareHotkey=AD;Hc.toKeyCode=MD;Hc.toKeyName=Lb;function CD(n){return{all:n=n||new Map,on:function(e,t){var r=n.get(e);r?r.push(t):n.set(e,[t])},off:function(e,t){var r=n.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):n.set(e,[]))},emit:function(e,t){var r=n.get(e);r&&r.slice().map(function(i){i(t)}),(r=n.get("*"))&&r.slice().map(function(i){i(e,t)})}}}const Vf=navigator.userAgent.includes("Mac"),Eee=Vf?"cmd":"ctrl",ha={[De.NONE]:!1,[De.ALT]:!1,[De.CTRL]:!1,[De.SHIFT]:!1,[De.MOVE_UP]:!1,[De.MOVE_DOWN]:!1,[De.MOVE_LEFT]:!1,[De.MOVE_RIGHT]:!1,[De.OK_BUTTON]:!1,[De.CANCEL_BUTTON]:!1,[De.MENU_BUTTON]:!1,[De.SHOOT_UP]:!1,[De.SHOOT_DOWN]:!1,[De.SHOOT_LEFT]:!1,[De.SHOOT_RIGHT]:!1};let r_=0,dk=performance.now();const pk=250;function Zi(n){ha[n]||(r_=0,kD(n,{alt:ha[De.ALT],ctrl:ha[De.CTRL],shift:ha[De.SHIFT]})),ha[n]=!0}function Qi(n){ha[n]=!1}const ca={root:CD(),ignorehotkeys:!1},RD=ke.createContext(ca.root);function dy(n){return{alt:n.altKey,ctrl:Vf?n.metaKey:n.ctrlKey,shift:n.shiftKey}}function kD(n,e){ca.root.emit(De[n],e)}document.addEventListener("keydown",n=>{const e=$t(n.key),t=dy(n);switch(e){case"s":t.ctrl&&Av("tape","#save",F_()),n.preventDefault();break;case"v":case"r":t.ctrl||n.preventDefault();break;case"i":!Vf&&t.shift&&t.ctrl||n.preventDefault();break;case"dead":Vf&&t.alt&&t.ctrl||n.preventDefault();break;case"alt":case"meta":case"shift":case"control":break;default:n.preventDefault();break}switch(t.alt?Zi(De.ALT):Qi(De.ALT),t.ctrl?Zi(De.CTRL):Qi(De.CTRL),t.shift?Zi(De.SHIFT):Qi(De.SHIFT),e){case"arrowleft":Zi(De.MOVE_LEFT);break;case"arrowright":Zi(De.MOVE_RIGHT);break;case"arrowup":Zi(De.MOVE_UP);break;case"arrowdown":Zi(De.MOVE_DOWN);break;case"enter":Zi(De.OK_BUTTON);break;case"esc":case"escape":Zi(De.CANCEL_BUTTON);break;case"tab":Zi(De.MENU_BUTTON);break}ca.root.emit("keydown",n)},{capture:!0});document.addEventListener("keyup",n=>{const e=$t(n.key),t=dy(n);switch(t.alt?Zi(De.ALT):Qi(De.ALT),t.ctrl?Zi(De.CTRL):Qi(De.CTRL),t.shift?Zi(De.SHIFT):Qi(De.SHIFT),e){case"arrowleft":Qi(De.MOVE_LEFT);break;case"arrowright":Qi(De.MOVE_RIGHT);break;case"arrowup":Qi(De.MOVE_UP);break;case"arrowdown":Qi(De.MOVE_DOWN);break;case"enter":Qi(De.OK_BUTTON);break;case"esc":case"escape":Qi(De.CANCEL_BUTTON);break;case"tab":Qi(De.MENU_BUTTON);break}},{capture:!0});const wee=0,Tee=1,bee=2,Aee=3,Mee=4,Cee=5,Ree=6,kee=7,Iee=9,Nee=12,Oee=13,Lee=14,Pee=15,ID={[wee]:De.OK_BUTTON,[Tee]:De.CANCEL_BUTTON,[bee]:De.OK_BUTTON,[Aee]:De.CANCEL_BUTTON,[Mee]:De.ALT,[Cee]:De.ALT,[Ree]:De.CTRL,[kee]:De.CTRL,[Iee]:De.MENU_BUTTON,[Nee]:De.MOVE_UP,[Oee]:De.MOVE_DOWN,[Lee]:De.MOVE_LEFT,[Pee]:De.MOVE_RIGHT};document.addEventListener("gamepadbuttondown",n=>{Zi(ID[n.detail.button])});document.addEventListener("gamepadbuttonup",n=>{Qi(ID[n.detail.button])});function ND(){const n=performance.now(),e=n-dk;if(r_+=e,r_>=pk){r_%=pk;const t={alt:!!ha[De.ALT],ctrl:!!ha[De.CTRL],shift:!!ha[De.SHIFT]};[De.MOVE_UP,De.MOVE_DOWN,De.MOVE_LEFT,De.MOVE_RIGHT,De.OK_BUTTON,De.CANCEL_BUTTON,De.MENU_BUTTON,De.SHOOT_UP,De.SHOOT_DOWN,De.SHOOT_LEFT,De.SHOOT_RIGHT].forEach(i=>{ha[i]&&kD(i,t)})}dk=n,wD.update(),setTimeout(ND,1)}ND();const mk="keyup";function cp({hotkey:n,children:e}){return ke.useEffect(()=>{const t=See(n,{byKey:!0});function r(i){ca.ignorehotkeys===!1&&t(i)&&e()}return document.addEventListener(mk,r,!1),()=>document.removeEventListener(mk,r,!1)},[n,e]),null}function us(n){const e=ke.useContext(RD);return ke.useEffect(()=>{const t=Object.entries(n);return t.forEach(([r,i])=>e.on(r,i)),()=>{t.forEach(([r,i])=>e.off(r,i))}},[e,n]),null}function mm({blockhotkeys:n,children:e}){const[t]=ke.useState(()=>CD());return ke.useEffect(()=>{const r=ca.root,i=ca.ignorehotkeys;return ca.root=t,ca.ignorehotkeys=!!n,()=>{ca.root=r,ca.ignorehotkeys=i}},[t,n]),_e.jsx(RD.Provider,{value:t,children:e})}const Dee=new St(0,0);function uu(n,e,t){let r=0;t.alt&&(r|=uD),t.ctrl&&(r|=hD),t.shift&&(r|=fD),MW("framed",e,r,n)}function Uee({width:n,height:e}){const t=n*ss,r=e*zi,i=ke.useRef(null);Tv((a,c)=>{const{current:l}=i;if(!l)return;const u=IJ(is.getState().gadget.layers),h=u.width*ss*u.viewscale,p=h-t,m=u.height*zi*u.viewscale,g=m-r,v=Math.round(Math.min(t,r)*.3333),y=-u.focusx*ss*u.viewscale,_=t*.5+y,S=-u.focusy*zi*u.viewscale,w=r*.5+S,T=h=v){const O=C<0?-v:v;l.userData.focus.x=Math.round(T-O)}}if(g<0)l.userData.focus.y=k;else{const C=l.position.y-k;if(Math.abs(C)>=v){const O=C<0?-v:v;l.userData.focus.y=Math.round(k-O*.5)}}const R=6;l.position.x+=(l.userData.focus.x-l.position.x)*c*R,l.position.y+=(l.userData.focus.y-l.position.y)*c*R,p>=0&&(l.position.x=Cn(l.position.x,-p,0)),g>=0&&(l.position.y=Cn(l.position.y,-g,0))});const s=is(a=>a.gadget.player);is(a=>a.gadget.layers.length);const{layers:o}=is.getState().gadget;return _e.jsxs(_e.Fragment,{children:[_e.jsx(us,{MOVE_LEFT:a=>uu(s,De.MOVE_LEFT,a),MOVE_RIGHT:a=>uu(s,De.MOVE_RIGHT,a),MOVE_UP:a=>uu(s,De.MOVE_UP,a),MOVE_DOWN:a=>uu(s,De.MOVE_DOWN,a),OK_BUTTON:a=>uu(s,De.OK_BUTTON,a),CANCEL_BUTTON:a=>uu(s,De.CANCEL_BUTTON,a),MENU_BUTTON:a=>uu(s,De.MENU_BUTTON,a)}),_e.jsx(PJ,{width:t,height:r,children:_e.jsx("group",{ref:i,children:o.map((a,c)=>_e.jsx(_ee,{id:a.id,z:c*2},a.id))})})]})}var OD=typeof global=="object"&&global&&global.Object===Object&&global,Fee=typeof self=="object"&&self&&self.Object===Object&&self,La=OD||Fee||Function("return this")(),oo=La.Symbol,LD=Object.prototype,Bee=LD.hasOwnProperty,zee=LD.toString,Bd=oo?oo.toStringTag:void 0;function Vee(n){var e=Bee.call(n,Bd),t=n[Bd];try{n[Bd]=void 0;var r=!0}catch{}var i=zee.call(n);return r&&(e?n[Bd]=t:delete n[Bd]),i}var Hee=Object.prototype,Gee=Hee.toString;function Wee(n){return Gee.call(n)}var jee="[object Null]",$ee="[object Undefined]",gk=oo?oo.toStringTag:void 0;function Gl(n){return n==null?n===void 0?$ee:jee:gk&&gk in Object(n)?Vee(n):Wee(n)}function Lo(n){return n!=null&&typeof n=="object"}var qee="[object Symbol]";function py(n){return typeof n=="symbol"||Lo(n)&&Gl(n)==qee}function my(n,e){for(var t=-1,r=n==null?0:n.length,i=Array(r);++t0){if(++e>=bte)return arguments[0]}else e=0;return n.apply(void 0,arguments)}}function Rte(n){return function(){return n}}var Y_=function(){try{var n=ah(Object,"defineProperty");return n({},"",{}),n}catch{}}(),kte=Y_?function(n,e){return Y_(n,"toString",{configurable:!0,enumerable:!1,value:Rte(e),writable:!0})}:Hf,Ite=Cte(kte);function DD(n,e){for(var t=-1,r=n==null?0:n.length;++t-1}var Lte=9007199254740991,Pte=/^(?:0|[1-9]\d*)$/;function _y(n,e){var t=typeof n;return e=e??Lte,!!e&&(t=="number"||t!="symbol"&&Pte.test(n))&&n>-1&&n%1==0&&n-1&&n%1==0&&n<=Bte}function Pa(n){return n!=null&&Bb(n.length)&&!Gc(n)}function BD(n,e,t){if(!ao(t))return!1;var r=typeof e;return(r=="number"?Pa(t)&&_y(e,t.length):r=="string"&&e in t)?gm(t[e],n):!1}function zte(n){return Fb(function(e,t){var r=-1,i=t.length,s=i>1?t[i-1]:void 0,o=i>2?t[2]:void 0;for(s=n.length>3&&typeof s=="function"?(i--,s):void 0,o&&BD(t[0],t[1],o)&&(s=i<3?void 0:s,i=1),e=Object(e);++r-1}function Zne(n,e){var t=this.__data__,r=Sy(t,n);return r<0?(++this.size,t.push([n,e])):t[r][1]=e,this}function Wc(n){var e=-1,t=n==null?0:n.length;for(this.clear();++ei?0:i+e),t=t>i?i:t,t<0&&(t+=i),i=e>t?0:t-e>>>0,e>>>=0;for(var s=Array(i);++r=r?n:$b(n,e,t)}var pre="\\ud800-\\udfff",mre="\\u0300-\\u036f",gre="\\ufe20-\\ufe2f",_re="\\u20d0-\\u20ff",vre=mre+gre+_re,yre="\\ufe0e\\ufe0f",xre="\\u200d",Sre=RegExp("["+xre+pre+vre+yre+"]");function KD(n){return Sre.test(n)}function Ere(n){return n.split("")}var YD="\\ud800-\\udfff",wre="\\u0300-\\u036f",Tre="\\ufe20-\\ufe2f",bre="\\u20d0-\\u20ff",Are=wre+Tre+bre,Mre="\\ufe0e\\ufe0f",Cre="["+YD+"]",tw="["+Are+"]",nw="\\ud83c[\\udffb-\\udfff]",Rre="(?:"+tw+"|"+nw+")",ZD="[^"+YD+"]",QD="(?:\\ud83c[\\udde6-\\uddff]){2}",JD="[\\ud800-\\udbff][\\udc00-\\udfff]",kre="\\u200d",eU=Rre+"?",tU="["+Mre+"]?",Ire="(?:"+kre+"(?:"+[ZD,QD,JD].join("|")+")"+tU+eU+")*",Nre=tU+eU+Ire,Ore="(?:"+[ZD+tw+"?",tw,QD,JD,Cre].join("|")+")",Lre=RegExp(nw+"(?="+nw+")|"+Ore+Nre,"g");function Pre(n){return n.match(Lre)||[]}function Dre(n){return KD(n)?Pre(n):Ere(n)}function Ure(n){return function(e){e=qD(e);var t=KD(e)?Dre(e):void 0,r=t?t[0]:e.charAt(0),i=t?dre(t,1).join(""):e.slice(1);return r[n]()+i}}var nU=Ure("toUpperCase");function Fre(n,e,t,r){var i=-1,s=n==null?0:n.length;for(r&&s&&(t=n[++i]);++ia))return!1;var l=s.get(n),u=s.get(e);if(l&&u)return l==e&&u==n;var h=-1,p=!0,m=t&gse?new Gf:void 0;for(s.set(n,e),s.set(e,n);++h2?e[2]:void 0;for(i&&BD(e[0],e[1],i)&&(r=1);++t=ooe&&(s=Kb,o=!1,e=new Gf(e));e:for(;++i-1?i[s?e[o]:o]:void 0}}var foe=Math.max;function doe(n,e,t){var r=n==null?0:n.length;if(!r)return-1;var i=t==null?0:gy(t);return i<0&&(i=foe(r+i,0)),UD(n,Da(e),i)}var jf=hoe(doe);function Po(n){return n&&n.length?n[0]:void 0}function poe(n,e){var t=-1,r=Pa(n)?Array(n.length):[];return ch(n,function(i,s,o){r[++t]=e(i,s,o)}),r}function st(n,e){var t=ln(n)?my:poe;return t(n,Da(e))}function no(n,e){return jb(st(n,e))}var moe=Object.prototype,goe=moe.hasOwnProperty,gU=ioe(function(n,e,t){goe.call(n,t)?n[t].push(e):Db(n,t,[e])}),_oe=Object.prototype,voe=_oe.hasOwnProperty;function yoe(n,e){return n!=null&&voe.call(n,e)}function wt(n,e){return n!=null&&dU(n,e,yoe)}var xoe="[object String]";function fs(n){return typeof n=="string"||!ln(n)&&Lo(n)&&Gl(n)==xoe}function Soe(n,e){return my(e,function(t){return n[t]})}function Cr(n){return n==null?[]:Soe(n,co(n))}var Eoe=Math.max;function $i(n,e,t,r){n=Pa(n)?n:Cr(n),t=t&&!r?gy(t):0;var i=n.length;return t<0&&(t=Eoe(i+t,0)),fs(n)?t<=i&&n.indexOf(e,t)>-1:!!i&&Pb(n,e,t)>-1}function qk(n,e,t){var r=n==null?0:n.length;if(!r)return-1;var i=0;return Pb(n,e,i)}var woe="[object Map]",Toe="[object Set]",boe=Object.prototype,Aoe=boe.hasOwnProperty;function Un(n){if(n==null)return!0;if(Pa(n)&&(ln(n)||typeof n=="string"||typeof n.splice=="function"||kp(n)||zb(n)||yy(n)))return!n.length;var e=Xs(n);if(e==woe||e==Toe)return!n.size;if(_m(n))return!jD(n).length;for(var t in n)if(Aoe.call(n,t))return!1;return!0}var Moe="[object RegExp]";function Coe(n){return Lo(n)&&Gl(n)==Moe}var Xk=Pl&&Pl.isRegExp,Mc=Xk?xy(Xk):Coe;function Cc(n){return n===void 0}var Roe="Expected a function";function koe(n){if(typeof n!="function")throw new TypeError(Roe);return function(){var e=arguments;switch(e.length){case 0:return!n.call(this);case 1:return!n.call(this,e[0]);case 2:return!n.call(this,e[0],e[1]);case 3:return!n.call(this,e[0],e[1],e[2])}return!n.apply(this,e)}}function Ioe(n,e,t,r){if(!ao(n))return n;e=wy(e,n);for(var i=-1,s=e.length,o=s-1,a=n;a!=null&&++i=Uoe){var l=Doe(n);if(l)return Yb(l);o=!1,i=Kb,c=new Gf}else c=a;e:for(;++r{t.accept(e)})}}class ps extends Ua{constructor(e){super([]),this.idx=1,hs(this,Vo(e,t=>t!==void 0))}set definition(e){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(e){e.visit(this)}}class ud extends Ua{constructor(e){super(e.definition),this.orgText="",hs(this,Vo(e,t=>t!==void 0))}}class ms extends Ua{constructor(e){super(e.definition),this.ignoreAmbiguities=!1,hs(this,Vo(e,t=>t!==void 0))}}class cs extends Ua{constructor(e){super(e.definition),this.idx=1,hs(this,Vo(e,t=>t!==void 0))}}class Fa extends Ua{constructor(e){super(e.definition),this.idx=1,hs(this,Vo(e,t=>t!==void 0))}}class Ba extends Ua{constructor(e){super(e.definition),this.idx=1,hs(this,Vo(e,t=>t!==void 0))}}class Dr extends Ua{constructor(e){super(e.definition),this.idx=1,hs(this,Vo(e,t=>t!==void 0))}}class Ho extends Ua{constructor(e){super(e.definition),this.idx=1,hs(this,Vo(e,t=>t!==void 0))}}class Go extends Ua{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,hs(this,Vo(e,t=>t!==void 0))}}let Jn=class{constructor(e){this.idx=1,hs(this,Vo(e,t=>t!==void 0))}accept(e){e.visit(this)}};function Voe(n){return st(n,s_)}function s_(n){function e(t){return st(t,s_)}if(n instanceof ps){const t={type:"NonTerminal",name:n.nonTerminalName,idx:n.idx};return fs(n.label)&&(t.label=n.label),t}else{if(n instanceof ms)return{type:"Alternative",definition:e(n.definition)};if(n instanceof cs)return{type:"Option",idx:n.idx,definition:e(n.definition)};if(n instanceof Fa)return{type:"RepetitionMandatory",idx:n.idx,definition:e(n.definition)};if(n instanceof Ba)return{type:"RepetitionMandatoryWithSeparator",idx:n.idx,separator:s_(new Jn({terminalType:n.separator})),definition:e(n.definition)};if(n instanceof Ho)return{type:"RepetitionWithSeparator",idx:n.idx,separator:s_(new Jn({terminalType:n.separator})),definition:e(n.definition)};if(n instanceof Dr)return{type:"Repetition",idx:n.idx,definition:e(n.definition)};if(n instanceof Go)return{type:"Alternation",idx:n.idx,definition:e(n.definition)};if(n instanceof Jn){const t={type:"Terminal",name:n.terminalType.name,label:Boe(n.terminalType),idx:n.idx};fs(n.label)&&(t.terminalLabel=n.label);const r=n.terminalType.PATTERN;return n.terminalType.PATTERN&&(t.pattern=Mc(r)?r.source:r),t}else{if(n instanceof ud)return{type:"Rule",name:n.name,orgText:n.orgText,definition:e(n.definition)};throw Error("non exhaustive match")}}}class lh{visit(e){const t=e;switch(t.constructor){case ps:return this.visitNonTerminal(t);case ms:return this.visitAlternative(t);case cs:return this.visitOption(t);case Fa:return this.visitRepetitionMandatory(t);case Ba:return this.visitRepetitionMandatoryWithSeparator(t);case Ho:return this.visitRepetitionWithSeparator(t);case Dr:return this.visitRepetition(t);case Go:return this.visitAlternation(t);case Jn:return this.visitTerminal(t);case ud:return this.visitRule(t);default:throw Error("non exhaustive match")}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}}function Hoe(n){return n instanceof ms||n instanceof cs||n instanceof Dr||n instanceof Fa||n instanceof Ba||n instanceof Ho||n instanceof Jn||n instanceof ud}function Q_(n,e=[]){return n instanceof cs||n instanceof Dr||n instanceof Ho?!0:n instanceof Go?Jb(n.definition,r=>Q_(r,e)):n instanceof ps&&$i(e,n)?!1:n instanceof Ua?(n instanceof ps&&e.push(n),Co(n.definition,r=>Q_(r,e))):!1}function Goe(n){return n instanceof Go}function la(n){if(n instanceof ps)return"SUBRULE";if(n instanceof cs)return"OPTION";if(n instanceof Go)return"OR";if(n instanceof Fa)return"AT_LEAST_ONE";if(n instanceof Ba)return"AT_LEAST_ONE_SEP";if(n instanceof Ho)return"MANY_SEP";if(n instanceof Dr)return"MANY";if(n instanceof Jn)return"CONSUME";throw Error("non exhaustive match")}class My{walk(e,t=[]){bt(e.definition,(r,i)=>{const s=oi(e.definition,i+1);if(r instanceof ps)this.walkProdRef(r,s,t);else if(r instanceof Jn)this.walkTerminal(r,s,t);else if(r instanceof ms)this.walkFlat(r,s,t);else if(r instanceof cs)this.walkOption(r,s,t);else if(r instanceof Fa)this.walkAtLeastOne(r,s,t);else if(r instanceof Ba)this.walkAtLeastOneSep(r,s,t);else if(r instanceof Ho)this.walkManySep(r,s,t);else if(r instanceof Dr)this.walkMany(r,s,t);else if(r instanceof Go)this.walkOr(r,s,t);else throw Error("non exhaustive match")})}walkTerminal(e,t,r){}walkProdRef(e,t,r){}walkFlat(e,t,r){const i=t.concat(r);this.walk(e,i)}walkOption(e,t,r){const i=t.concat(r);this.walk(e,i)}walkAtLeastOne(e,t,r){const i=[new cs({definition:e.definition})].concat(t,r);this.walk(e,i)}walkAtLeastOneSep(e,t,r){const i=Kk(e,t,r);this.walk(e,i)}walkMany(e,t,r){const i=[new cs({definition:e.definition})].concat(t,r);this.walk(e,i)}walkManySep(e,t,r){const i=Kk(e,t,r);this.walk(e,i)}walkOr(e,t,r){const i=t.concat(r);bt(e.definition,s=>{const o=new ms({definition:[s]});this.walk(o,i)})}}function Kk(n,e,t){return[new cs({definition:[new Jn({terminalType:n.separator})].concat(n.definition)})].concat(e,t)}function xm(n){if(n instanceof ps)return xm(n.referencedRule);if(n instanceof Jn)return $oe(n);if(Hoe(n))return Woe(n);if(Goe(n))return joe(n);throw Error("non exhaustive match")}function Woe(n){let e=[];const t=n.definition;let r=0,i=t.length>r,s,o=!0;for(;i&&o;)s=t[r],o=Q_(s),e=e.concat(xm(s)),r=r+1,i=t.length>r;return Ay(e)}function joe(n){const e=st(n.definition,t=>xm(t));return Ay(Os(e))}function $oe(n){return[n.terminalType]}const xU="_~IN~_";class qoe extends My{constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,t,r){}walkProdRef(e,t,r){const i=Koe(e.referencedRule,e.idx)+this.topProd.name,s=t.concat(r),o=new ms({definition:s}),a=xm(o);this.follows[i]=a}}function Xoe(n){const e={};return bt(n,t=>{const r=new qoe(t).startWalking();hs(e,r)}),e}function Koe(n,e){return n.name+e+xU}function Mt(n){return n.charCodeAt(0)}function r1(n,e){Array.isArray(n)?n.forEach(function(t){e.push(t)}):e.push(n)}function zd(n,e){if(n[e]===!0)throw"duplicate flag "+e;n[e],n[e]=!0}function Gh(n){if(n===void 0)throw Error("Internal Error - Should never get here!");return!0}function Yoe(){throw Error("Internal Error - Should never get here!")}function Yk(n){return n.type==="Character"}const J_=[];for(let n=Mt("0");n<=Mt("9");n++)J_.push(n);const ev=[Mt("_")].concat(J_);for(let n=Mt("a");n<=Mt("z");n++)ev.push(n);for(let n=Mt("A");n<=Mt("Z");n++)ev.push(n);const Zk=[Mt(" "),Mt("\f"),Mt(` -`),Mt("\r"),Mt(" "),Mt("\v"),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt("\u2028"),Mt("\u2029"),Mt(" "),Mt(" "),Mt(" "),Mt("\uFEFF")],Zoe=/[0-9a-fA-F]/,x0=/[0-9]/,Qoe=/[1-9]/;class Joe{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar("/");const t=this.disjunction();this.consumeChar("/");const r={type:"Flags",loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":zd(r,"global");break;case"i":zd(r,"ignoreCase");break;case"m":zd(r,"multiLine");break;case"u":zd(r,"unicode");break;case"y":zd(r,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:t,loc:this.loc(0)}}disjunction(){const e=[],t=this.idx;for(e.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),e.push(this.alternative());return{type:"Disjunction",value:e,loc:this.loc(t)}}alternative(){const e=[],t=this.idx;for(;this.isTerm();)e.push(this.term());return{type:"Alternative",value:e,loc:this.loc(t)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){const e=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(e)};case"$":return{type:"EndAnchor",loc:this.loc(e)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(e)};case"B":return{type:"NonWordBoundary",loc:this.loc(e)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let t;switch(this.popChar()){case"=":t="Lookahead";break;case"!":t="NegativeLookahead";break}Gh(t);const r=this.disjunction();return this.consumeChar(")"),{type:t,value:r,loc:this.loc(e)}}return Yoe()}quantifier(e=!1){let t;const r=this.idx;switch(this.popChar()){case"*":t={atLeast:0,atMost:1/0};break;case"+":t={atLeast:1,atMost:1/0};break;case"?":t={atLeast:0,atMost:1};break;case"{":const i=this.integerIncludingZero();switch(this.popChar()){case"}":t={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),t={atLeast:i,atMost:s}):t={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(e===!0&&t===void 0)return;Gh(t);break}if(!(e===!0&&t===void 0)&&Gh(t))return this.peekChar(0)==="?"?(this.consumeChar("?"),t.greedy=!1):t.greedy=!0,t.type="Quantifier",t.loc=this.loc(r),t}atom(){let e;const t=this.idx;switch(this.peekChar()){case".":e=this.dotAll();break;case"\\":e=this.atomEscape();break;case"[":e=this.characterClass();break;case"(":e=this.group();break}if(e===void 0&&this.isPatternCharacter()&&(e=this.patternCharacter()),Gh(e))return e.loc=this.loc(t),this.isQuantifier()&&(e.quantifier=this.quantifier()),e}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[Mt(` -`),Mt("\r"),Mt("\u2028"),Mt("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let e,t=!1;switch(this.popChar()){case"d":e=J_;break;case"D":e=J_,t=!0;break;case"s":e=Zk;break;case"S":e=Zk,t=!0;break;case"w":e=ev;break;case"W":e=ev,t=!0;break}if(Gh(e))return{type:"Set",value:e,complement:t}}controlEscapeAtom(){let e;switch(this.popChar()){case"f":e=Mt("\f");break;case"n":e=Mt(` -`);break;case"r":e=Mt("\r");break;case"t":e=Mt(" ");break;case"v":e=Mt("\v");break}if(Gh(e))return{type:"Character",value:e}}controlLetterEscapeAtom(){this.consumeChar("c");const e=this.popChar();if(/[a-zA-Z]/.test(e)===!1)throw Error("Invalid ");return{type:"Character",value:e.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:Mt("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){const e=this.popChar();return{type:"Character",value:Mt(e)}}classPatternCharacterAtom(){switch(this.peekChar()){case` -`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:const e=this.popChar();return{type:"Character",value:Mt(e)}}}characterClass(){const e=[];let t=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),t=!0);this.isClassAtom();){const r=this.classAtom();if(r.type,Yk(r)&&this.isRangeDash()){this.consumeChar("-");const i=this.classAtom();if(i.type,Yk(i)){if(i.value=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(e){return{begin:e,end:this.idx}}}class eA{visitChildren(e){for(const t in e){const r=e[t];e.hasOwnProperty(t)&&(r.type!==void 0?this.visit(r):Array.isArray(r)&&r.forEach(i=>{this.visit(i)},this))}}visit(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e);break}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}}let o_={};const eae=new Joe;function Cy(n){const e=n.toString();if(o_.hasOwnProperty(e))return o_[e];{const t=eae.pattern(e);return o_[e]=t,t}}function tae(){o_={}}const SU="Complement Sets are not supported for first char optimization",tv=`Unable to use "first char" lexer optimizations: -`;function nae(n,e=!1){try{const t=Cy(n);return aw(t.value,{},t.flags.ignoreCase)}catch(t){if(t.message===SU)e&&_U(`${tv} Unable to optimize: < ${n.toString()} > - Complement Sets cannot be automatically optimized. - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let r="";e&&(r=` - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),ow(`${tv} - Failed parsing: < ${n.toString()} > - Using the @chevrotain/regexp-to-ast library - Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}function aw(n,e,t){switch(n.type){case"Disjunction":for(let i=0;i{if(typeof c=="number")S0(c,e,t);else{const l=c;if(t===!0)for(let u=l.from;u<=l.to;u++)S0(u,e,t);else{for(let u=l.from;u<=l.to&&u=Zd){const u=l.from>=Zd?l.from:Zd,h=l.to,p=Dl(u),m=Dl(h);for(let g=p;g<=m;g++)e[g]=g}}}});break;case"Group":aw(o.value,e,t);break;default:throw Error("Non Exhaustive Match")}const a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&cw(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return Cr(e)}function S0(n,e,t){const r=Dl(n);e[r]=r,t===!0&&rae(n,e)}function rae(n,e){const t=String.fromCharCode(n),r=t.toUpperCase();if(r!==t){const i=Dl(r.charCodeAt(0));e[i]=i}else{const i=t.toLowerCase();if(i!==t){const s=Dl(i.charCodeAt(0));e[s]=s}}}function Qk(n,e){return jf(n.value,t=>{if(typeof t=="number")return $i(e,t);{const r=t;return jf(e,i=>r.from<=i&&i<=r.to)!==void 0}})}function cw(n){const e=n.quantifier;return e&&e.atLeast===0?!0:n.value?ln(n.value)?Co(n.value,cw):cw(n.value):!1}class iae extends eA{constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(this.found!==!0){switch(e.type){case"Lookahead":this.visitLookahead(e);return;case"NegativeLookahead":this.visitNegativeLookahead(e);return}super.visitChildren(e)}}visitCharacter(e){$i(this.targetCharCodes,e.value)&&(this.found=!0)}visitSet(e){e.complement?Qk(e,this.targetCharCodes)===void 0&&(this.found=!0):Qk(e,this.targetCharCodes)!==void 0&&(this.found=!0)}}function tA(n,e){if(e instanceof RegExp){const t=Cy(e),r=new iae(n);return r.visit(t),r.found}else return jf(e,t=>$i(n,t.charCodeAt(0)))!==void 0}const Xu="PATTERN",Yd="defaultMode",E0="modes";let EU=typeof new RegExp("(?:)").sticky=="boolean";function sae(n,e){e=Qb(e,{useSticky:EU,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` -`],tracer:(S,w)=>w()});const t=e.tracer;t("initCharCodeToOptimizedIndexMap",()=>{Cae()});let r;t("Reject Lexer.NA",()=>{r=by(n,S=>S[Xu]===Br.NA)});let i=!1,s;t("Transform Patterns",()=>{i=!1,s=st(r,S=>{const w=S[Xu];if(Mc(w)){const T=w.source;return T.length===1&&T!=="^"&&T!=="$"&&T!=="."&&!w.ignoreCase?T:T.length===2&&T[0]==="\\"&&!$i(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],T[1])?T[1]:e.useSticky?eI(w):Jk(w)}else{if(Gc(w))return i=!0,{exec:w};if(typeof w=="object")return i=!0,w;if(typeof w=="string"){if(w.length===1)return w;{const T=w.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),k=new RegExp(T);return e.useSticky?eI(k):Jk(k)}}else throw Error("non exhaustive match")}})});let o,a,c,l,u;t("misc mapping",()=>{o=st(r,S=>S.tokenTypeIdx),a=st(r,S=>{const w=S.GROUP;if(w!==Br.SKIPPED){if(fs(w))return w;if(Cc(w))return!1;throw Error("non exhaustive match")}}),c=st(r,S=>{const w=S.LONGER_ALT;if(w)return ln(w)?st(w,k=>qk(r,k)):[qk(r,w)]}),l=st(r,S=>S.PUSH_MODE),u=st(r,S=>wt(S,"POP_MODE"))});let h;t("Line Terminator Handling",()=>{const S=bU(e.lineTerminatorCharacters);h=st(r,w=>!1),e.positionTracking!=="onlyOffset"&&(h=st(r,w=>wt(w,"LINE_BREAKS")?!!w.LINE_BREAKS:TU(w,S)===!1&&tA(S,w.PATTERN)))});let p,m,g,v;t("Misc Mapping #2",()=>{p=st(r,wU),m=st(s,bae),g=ds(r,(S,w)=>{const T=w.GROUP;return fs(T)&&T!==Br.SKIPPED&&(S[T]=[]),S},{}),v=st(s,(S,w)=>({pattern:s[w],longerAlt:c[w],canLineTerminator:h[w],isCustom:p[w],short:m[w],group:a[w],push:l[w],pop:u[w],tokenTypeIdx:o[w],tokenType:r[w]}))});let y=!0,_=[];return e.safeMode||t("First Char Optimization",()=>{_=ds(r,(S,w,T)=>{if(typeof w.PATTERN=="string"){const k=w.PATTERN.charCodeAt(0),R=Dl(k);i1(S,R,v[T])}else if(ln(w.START_CHARS_HINT)){let k;bt(w.START_CHARS_HINT,R=>{const C=typeof R=="string"?R.charCodeAt(0):R,O=Dl(C);k!==O&&(k=O,i1(S,O,v[T]))})}else if(Mc(w.PATTERN))if(w.PATTERN.unicode)y=!1,e.ensureOptimizations&&ow(`${tv} Unable to analyze < ${w.PATTERN.toString()} > pattern. - The regexp unicode flag is not currently supported by the regexp-to-ast library. - This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{const k=nae(w.PATTERN,e.ensureOptimizations);Un(k)&&(y=!1),bt(k,R=>{i1(S,R,v[T])})}else e.ensureOptimizations&&ow(`${tv} TokenType: <${w.name}> is using a custom token pattern without providing parameter. - This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),y=!1;return S},[])}),{emptyGroups:g,patternIdxToConfig:v,charCodeToPatternIdxToConfig:_,hasCustom:i,canBeOptimized:y}}function oae(n,e){let t=[];const r=cae(n);t=t.concat(r.errors);const i=lae(r.valid),s=i.valid;return t=t.concat(i.errors),t=t.concat(aae(s)),t=t.concat(_ae(s)),t=t.concat(vae(s,e)),t=t.concat(yae(s)),t}function aae(n){let e=[];const t=lo(n,r=>Mc(r[Xu]));return e=e.concat(hae(t)),e=e.concat(pae(t)),e=e.concat(mae(t)),e=e.concat(gae(t)),e=e.concat(fae(t)),e}function cae(n){const e=lo(n,i=>!wt(i,Xu)),t=st(e,i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:sr.MISSING_PATTERN,tokenTypes:[i]})),r=Ty(n,e);return{errors:t,valid:r}}function lae(n){const e=lo(n,i=>{const s=i[Xu];return!Mc(s)&&!Gc(s)&&!wt(s,"exec")&&!fs(s)}),t=st(e,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:sr.INVALID_PATTERN,tokenTypes:[i]})),r=Ty(n,e);return{errors:t,valid:r}}const uae=/[^\\][$]/;function hae(n){class e extends eA{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}const t=lo(n,i=>{const s=i.PATTERN;try{const o=Cy(s),a=new e;return a.visit(o),a.found}catch{return uae.test(s.source)}});return st(t,i=>({message:`Unexpected RegExp Anchor Error: - Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' - See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:sr.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function fae(n){const e=lo(n,r=>r.PATTERN.test(""));return st(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' must not match an empty string",type:sr.EMPTY_MATCH_PATTERN,tokenTypes:[r]}))}const dae=/[^\\[][\^]|^\^/;function pae(n){class e extends eA{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}const t=lo(n,i=>{const s=i.PATTERN;try{const o=Cy(s),a=new e;return a.visit(o),a.found}catch{return dae.test(s.source)}});return st(t,i=>({message:`Unexpected RegExp Anchor Error: - Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:sr.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function mae(n){const e=lo(n,r=>{const i=r[Xu];return i instanceof RegExp&&(i.multiline||i.global)});return st(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:sr.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[r]}))}function gae(n){const e=[];let t=st(n,s=>ds(n,(o,a)=>(s.PATTERN.source===a.PATTERN.source&&!$i(e,a)&&a.PATTERN!==Br.NA&&(e.push(a),o.push(a)),o),[]));t=ym(t);const r=lo(t,s=>s.length>1);return st(r,s=>{const o=st(s,c=>c.name);return{message:`The same RegExp pattern ->${Po(s).PATTERN}<-has been used in all of the following Token Types: ${o.join(", ")} <-`,type:sr.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function _ae(n){const e=lo(n,r=>{if(!wt(r,"GROUP"))return!1;const i=r.GROUP;return i!==Br.SKIPPED&&i!==Br.NA&&!fs(i)});return st(e,r=>({message:"Token Type: ->"+r.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:sr.INVALID_GROUP_TYPE_FOUND,tokenTypes:[r]}))}function vae(n,e){const t=lo(n,i=>i.PUSH_MODE!==void 0&&!$i(e,i.PUSH_MODE));return st(t,i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:sr.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function yae(n){const e=[],t=ds(n,(r,i,s)=>{const o=i.PATTERN;return o===Br.NA||(fs(o)?r.push({str:o,idx:s,tokenType:i}):Mc(o)&&Sae(o)&&r.push({str:o.source,idx:s,tokenType:i})),r},[]);return bt(n,(r,i)=>{bt(t,({str:s,idx:o,tokenType:a})=>{if(i${a.name}<- can never be matched. -Because it appears AFTER the Token Type ->${r.name}<-in the lexer's definition. -See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:c,type:sr.UNREACHABLE_PATTERN,tokenTypes:[r,a]})}})}),e}function xae(n,e){if(Mc(e)){const t=e.exec(n);return t!==null&&t.index===0}else{if(Gc(e))return e(n,0,[],{});if(wt(e,"exec"))return e.exec(n,0,[],{});if(typeof e=="string")return e===n;throw Error("non exhaustive match")}}function Sae(n){return jf([".","\\","[","]","|","^","$","(",")","?","*","+","{"],t=>n.source.indexOf(t)!==-1)===void 0}function Jk(n){const e=n.ignoreCase?"i":"";return new RegExp(`^(?:${n.source})`,e)}function eI(n){const e=n.ignoreCase?"iy":"y";return new RegExp(`${n.source}`,e)}function Eae(n,e,t){const r=[];return wt(n,Yd)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+Yd+`> property in its definition -`,type:sr.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),wt(n,E0)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+E0+`> property in its definition -`,type:sr.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),wt(n,E0)&&wt(n,Yd)&&!wt(n.modes,n.defaultMode)&&r.push({message:`A MultiMode Lexer cannot be initialized with a ${Yd}: <${n.defaultMode}>which does not exist -`,type:sr.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),wt(n,E0)&&bt(n.modes,(i,s)=>{bt(i,(o,a)=>{if(Cc(o))r.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${s}> at index: <${a}> -`,type:sr.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if(wt(o,"LONGER_ALT")){const c=ln(o.LONGER_ALT)?o.LONGER_ALT:[o.LONGER_ALT];bt(c,l=>{!Cc(l)&&!$i(i,l)&&r.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${l.name}> on token <${o.name}> outside of mode <${s}> -`,type:sr.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),r}function wae(n,e,t){const r=[];let i=!1;const s=ym(Os(Cr(n.modes))),o=by(s,c=>c[Xu]===Br.NA),a=bU(t);return e&&bt(o,c=>{const l=TU(c,a);if(l!==!1){const h={message:Mae(c,l),type:l.issue,tokenType:c};r.push(h)}else wt(c,"LINE_BREAKS")?c.LINE_BREAKS===!0&&(i=!0):tA(a,c.PATTERN)&&(i=!0)}),e&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. - This Lexer has been defined to track line and column information, - But none of the Token Types can be identified as matching a line terminator. - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS - for details.`,type:sr.NO_LINE_BREAKS_FLAGS}),r}function Tae(n){const e={},t=co(n);return bt(t,r=>{const i=n[r];if(ln(i))e[r]=[];else throw Error("non exhaustive match")}),e}function wU(n){const e=n.PATTERN;if(Mc(e))return!1;if(Gc(e))return!0;if(wt(e,"exec"))return!0;if(fs(e))return!1;throw Error("non exhaustive match")}function bae(n){return fs(n)&&n.length===1?n.charCodeAt(0):!1}const Aae={test:function(n){const e=n.length;for(let t=this.lastIndex;t Token Type - Root cause: ${e.errMsg}. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(e.issue===sr.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. - The problem is in the <${n.name}> Token Type - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function bU(n){return st(n,t=>fs(t)?t.charCodeAt(0):t)}function i1(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}const Zd=256;let a_=[];function Dl(n){return n255?255+~~(n/255):n}}function Sm(n,e){const t=n.tokenTypeIdx;return t===e.tokenTypeIdx?!0:e.isParent===!0&&e.categoryMatchesMap[t]===!0}function nv(n,e){return n.tokenTypeIdx===e.tokenTypeIdx}let tI=1;const AU={};function Em(n){const e=Rae(n);kae(e),Nae(e),Iae(e),bt(e,t=>{t.isParent=t.categoryMatches.length>0})}function Rae(n){let e=ui(n),t=n,r=!0;for(;r;){t=ym(Os(st(t,s=>s.CATEGORIES)));const i=Ty(t,e);e=e.concat(i),Un(i)?r=!1:t=i}return e}function kae(n){bt(n,e=>{CU(e)||(AU[tI]=e,e.tokenTypeIdx=tI++),nI(e)&&!ln(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),nI(e)||(e.CATEGORIES=[]),Oae(e)||(e.categoryMatches=[]),Lae(e)||(e.categoryMatchesMap={})})}function Iae(n){bt(n,e=>{e.categoryMatches=[],bt(e.categoryMatchesMap,(t,r)=>{e.categoryMatches.push(AU[r].tokenTypeIdx)})})}function Nae(n){bt(n,e=>{MU([],e)})}function MU(n,e){bt(n,t=>{e.categoryMatchesMap[t.tokenTypeIdx]=!0}),bt(e.CATEGORIES,t=>{const r=n.concat(e);$i(r,t)||MU(r,t)})}function CU(n){return wt(n,"tokenTypeIdx")}function nI(n){return wt(n,"CATEGORIES")}function Oae(n){return wt(n,"categoryMatches")}function Lae(n){return wt(n,"categoryMatchesMap")}function Pae(n){return wt(n,"tokenTypeIdx")}const Dae={buildUnableToPopLexerModeMessage(n){return`Unable to pop Lexer Mode after encountering Token ->${n.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(n,e,t,r,i){return`unexpected character: ->${n.charAt(e)}<- at offset: ${e}, skipped ${t} characters.`}};var sr;(function(n){n[n.MISSING_PATTERN=0]="MISSING_PATTERN",n[n.INVALID_PATTERN=1]="INVALID_PATTERN",n[n.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",n[n.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",n[n.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",n[n.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",n[n.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",n[n.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",n[n.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",n[n.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",n[n.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",n[n.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",n[n.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",n[n.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",n[n.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",n[n.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",n[n.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",n[n.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(sr||(sr={}));const Qd={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` -`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:Dae,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(Qd);class Br{constructor(e,t=Qd){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;const o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${i}>`);const{time:a,value:c}=vU(s),l=a>10?console.warn:console.log;return this.traceInitIndent time: ${a}ms`),this.traceInitIndent--,c}else return s()},typeof t=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. -a boolean 2nd argument is no longer supported`);this.config=hs({},Qd,t);const r=this.config.traceInitPerf;r===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof r=="number"&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===Qd.lineTerminatorsPattern)this.config.lineTerminatorsPattern=Aae;else if(this.config.lineTerminatorCharacters===Qd.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(t.safeMode&&t.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),ln(e)?i={modes:{defaultMode:ui(e)},defaultMode:Yd}:(s=!1,i=ui(e))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(Eae(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(wae(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},bt(i.modes,(a,c)=>{i.modes[c]=by(a,l=>Cc(l))});const o=co(i.modes);if(bt(i.modes,(a,c)=>{this.TRACE_INIT(`Mode: <${c}> processing`,()=>{if(this.modes.push(c),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(oae(a,o))}),Un(this.lexerDefinitionErrors)){Em(a);let l;this.TRACE_INIT("analyzeTokenTypes",()=>{l=sae(a,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:t.positionTracking,ensureOptimizations:t.ensureOptimizations,safeMode:t.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[c]=l.patternIdxToConfig,this.charCodeToPatternIdxToConfig[c]=l.charCodeToPatternIdxToConfig,this.emptyGroups=hs({},this.emptyGroups,l.emptyGroups),this.hasCustom=l.hasCustom||this.hasCustom,this.canModeBeOptimized[c]=l.canBeOptimized}})}),this.defaultMode=i.defaultMode,!Un(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){const c=st(this.lexerDefinitionErrors,l=>l.message).join(`----------------------- -`);throw new Error(`Errors detected in definition of Lexer: -`+c)}bt(this.lexerDefinitionWarning,a=>{_U(a.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(EU?(this.chopInput=Hf,this.match=this.matchWithTest):(this.updateLastIndex=Or,this.match=this.matchWithExec),s&&(this.handleModes=Or),this.trackStartLines===!1&&(this.computeNewColumn=Hf),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=Or),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{const a=ds(this.canModeBeOptimized,(c,l,u)=>(l===!1&&c.push(u),c),[]);if(t.ensureOptimizations&&!Un(a))throw Error(`Lexer Modes: < ${a.join(", ")} > cannot be optimized. - Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. - Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{tae()}),this.TRACE_INIT("toFastProperties",()=>{yU(this)})})}tokenize(e,t=this.defaultMode){if(!Un(this.lexerDefinitionErrors)){const i=st(this.lexerDefinitionErrors,s=>s.message).join(`----------------------- -`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: -`+i)}return this.tokenizeInternal(e,t)}tokenizeInternal(e,t){let r,i,s,o,a,c,l,u,h,p,m,g,v,y,_;const S=e,w=S.length;let T=0,k=0;const R=this.hasCustom?0:Math.floor(e.length/10),C=new Array(R),O=[];let M=this.trackStartLines?1:void 0,N=this.trackStartLines?1:void 0;const U=Tae(this.emptyGroups),L=this.trackStartLines,P=this.config.lineTerminatorsPattern;let b=0,B=[],W=[];const V=[],G=[];Object.freeze(G);let $;function Z(){return B}function X(be){const Ce=Dl(be),Ee=W[Ce];return Ee===void 0?G:Ee}const Y=be=>{if(V.length===1&&be.tokenType.PUSH_MODE===void 0){const Ce=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(be);O.push({offset:be.startOffset,line:be.startLine,column:be.startColumn,length:be.image.length,message:Ce})}else{V.pop();const Ce=Wf(V);B=this.patternIdxToConfig[Ce],W=this.charCodeToPatternIdxToConfig[Ce],b=B.length;const Ee=this.canModeBeOptimized[Ce]&&this.config.safeMode===!1;W&&Ee?$=X:$=Z}};function ve(be){V.push(be),W=this.charCodeToPatternIdxToConfig[be],B=this.patternIdxToConfig[be],b=B.length,b=B.length;const Ce=this.canModeBeOptimized[be]&&this.config.safeMode===!1;W&&Ce?$=X:$=Z}ve.call(this,t);let ne;const ie=this.config.recoveryEnabled;for(;Tc.length){c=o,l=u,ne=rt;break}}}break}}if(c!==null){if(h=c.length,p=ne.group,p!==void 0&&(m=ne.tokenTypeIdx,g=this.createTokenInstance(c,T,m,ne.tokenType,M,N,h),this.handlePayload(g,l),p===!1?k=this.addToken(C,k,g):U[p].push(g)),e=this.chopInput(e,h),T=T+h,N=this.computeNewColumn(N,h),L===!0&&ne.canLineTerminator===!0){let Le=0,ze,Ge;P.lastIndex=0;do ze=P.test(c),ze===!0&&(Ge=P.lastIndex-1,Le++);while(ze===!0);Le!==0&&(M=M+Le,N=h-Ge,this.updateTokenEndLineColumnLocation(g,p,Ge,Le,M,N,h))}this.handleModes(ne,Y,ve,g)}else{const Le=T,ze=M,Ge=N;let rt=ie===!1;for(;rt===!1&&T ${up(n)} <--`:`token of type --> ${n.name} <--`} but found --> '${e.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:n,ruleName:e}){return"Redundant input, expecting EOF but found: "+n.image},buildNoViableAltMessage({expectedPathsPerAlt:n,actual:e,previous:t,customUserDescription:r,ruleName:i}){const s="Expecting: ",a=` -but found: '`+Po(e).image+"'";if(r)return s+r+a;{const c=ds(n,(p,m)=>p.concat(m),[]),l=st(c,p=>`[${st(p,m=>up(m)).join(", ")}]`),h=`one of these possible Token sequences: -${st(l,(p,m)=>` ${m+1}. ${p}`).join(` -`)}`;return s+h+a}},buildEarlyExitMessage({expectedIterationPaths:n,actual:e,customUserDescription:t,ruleName:r}){const i="Expecting: ",o=` -but found: '`+Po(e).image+"'";if(t)return i+t+o;{const c=`expecting at least one iteration which starts with one of these possible Token sequences:: - <${st(n,l=>`[${st(l,u=>up(u)).join(",")}]`).join(" ,")}>`;return i+c+o}}};Object.freeze(kU);const zae={buildRuleNotFoundError(n,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- -inside top level rule: ->`+n.name+"<-"}},Cu={buildDuplicateFoundError(n,e){function t(u){return u instanceof Jn?u.terminalType.name:u instanceof ps?u.nonTerminalName:""}const r=n.name,i=Po(e),s=i.idx,o=la(i),a=t(i),c=s>0;let l=`->${o}${c?s:""}<- ${a?`with argument: ->${a}<-`:""} - appears more than once (${e.length} times) in the top level rule: ->${r}<-. - For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES - `;return l=l.replace(/[ \t]+/g," "),l=l.replace(/\s\s+/g,` -`),l},buildNamespaceConflictError(n){return`Namespace conflict found in grammar. -The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${n.name}>. -To resolve this make sure each Terminal and Non-Terminal names are unique -This is easy to accomplish by using the convention that Terminal names start with an uppercase letter -and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(n){const e=st(n.prefixPath,i=>up(i)).join(", "),t=n.alternation.idx===0?"":n.alternation.idx;return`Ambiguous alternatives: <${n.ambiguityIndices.join(" ,")}> due to common lookahead prefix -in inside <${n.topLevelRule.name}> Rule, -<${e}> may appears as a prefix path in all these alternatives. -See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX -For Further details.`},buildAlternationAmbiguityError(n){const e=st(n.prefixPath,i=>up(i)).join(", "),t=n.alternation.idx===0?"":n.alternation.idx;let r=`Ambiguous Alternatives Detected: <${n.ambiguityIndices.join(" ,")}> in inside <${n.topLevelRule.name}> Rule, -<${e}> may appears as a prefix path in all these alternatives. -`;return r=r+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES -For Further details.`,r},buildEmptyRepetitionError(n){let e=la(n.repetition);return n.repetition.idx!==0&&(e+=n.repetition.idx),`The repetition <${e}> within Rule <${n.topLevelRule.name}> can never consume any tokens. -This could lead to an infinite loop.`},buildTokenNameError(n){return"deprecated"},buildEmptyAlternationError(n){return`Ambiguous empty alternative: <${n.emptyChoiceIdx+1}> in inside <${n.topLevelRule.name}> Rule. -Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(n){return`An Alternation cannot have more than 256 alternatives: - inside <${n.topLevelRule.name}> Rule. - has ${n.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(n){const e=n.topLevelRule.name,t=st(n.leftRecursionPath,s=>s.name),r=`${e} --> ${t.concat([e]).join(" --> ")}`;return`Left Recursion found in grammar. -rule: <${e}> can be invoked from itself (directly or indirectly) -without consuming any Tokens. The grammar path that causes this is: - ${r} - To fix this refactor your grammar to remove the left recursion. -see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(n){return"deprecated"},buildDuplicateRuleNameError(n){let e;return n.topLevelRule instanceof ud?e=n.topLevelRule.name:e=n.topLevelRule,`Duplicate definition, rule: ->${e}<- is already defined in the grammar: ->${n.grammarName}<-`}};function Vae(n,e){const t=new Hae(n,e);return t.resolveRefs(),t.errors}class Hae extends lh{constructor(e,t){super(),this.nameToTopRule=e,this.errMsgProvider=t,this.errors=[]}resolveRefs(){bt(Cr(this.nameToTopRule),e=>{this.currTopLevel=e,e.accept(this)})}visitNonTerminal(e){const t=this.nameToTopRule[e.nonTerminalName];if(t)e.referencedRule=t;else{const r=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:r,type:Hi.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}}}class Gae extends My{constructor(e,t){super(),this.topProd=e,this.path=t,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=ui(this.path.ruleStack).reverse(),this.occurrenceStack=ui(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(e,t=[]){this.found||super.walk(e,t)}walkProdRef(e,t,r){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){const i=t.concat(r);this.updateExpectedNext(),this.walk(e.referencedRule,i)}}updateExpectedNext(){Un(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}}class Wae extends Gae{constructor(e,t){super(e,t),this.path=t,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(e,t,r){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){const i=t.concat(r),s=new ms({definition:i});this.possibleTokTypes=xm(s),this.found=!0}}}class Ry extends My{constructor(e,t){super(),this.topRule=e,this.occurrence=t,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}}class jae extends Ry{walkMany(e,t,r){if(e.idx===this.occurrence){const i=Po(t.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Jn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkMany(e,t,r)}}class hI extends Ry{walkManySep(e,t,r){if(e.idx===this.occurrence){const i=Po(t.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Jn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkManySep(e,t,r)}}class $ae extends Ry{walkAtLeastOne(e,t,r){if(e.idx===this.occurrence){const i=Po(t.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Jn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOne(e,t,r)}}class fI extends Ry{walkAtLeastOneSep(e,t,r){if(e.idx===this.occurrence){const i=Po(t.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Jn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOneSep(e,t,r)}}function lw(n,e,t=[]){t=ui(t);let r=[],i=0;function s(a){return a.concat(oi(n,i+1))}function o(a){const c=lw(s(a),e,t);return r.concat(c)}for(;t.length{Un(c.definition)===!1&&(r=o(c.definition))}),r;if(a instanceof Jn)t.push(a.terminalType);else throw Error("non exhaustive match")}i++}return r.push({partialPath:t,suffixDef:oi(n,i)}),r}function IU(n,e,t,r){const i="EXIT_NONE_TERMINAL",s=[i],o="EXIT_ALTERNATIVE";let a=!1;const c=e.length,l=c-r-1,u=[],h=[];for(h.push({idx:-1,def:n,ruleStack:[],occurrenceStack:[]});!Un(h);){const p=h.pop();if(p===o){a&&Wf(h).idx<=l&&h.pop();continue}const m=p.def,g=p.idx,v=p.ruleStack,y=p.occurrenceStack;if(Un(m))continue;const _=m[0];if(_===i){const S={idx:g,def:oi(m),ruleStack:Op(v),occurrenceStack:Op(y)};h.push(S)}else if(_ instanceof Jn)if(g=0;S--){const w=_.definition[S],T={idx:g,def:w.definition.concat(oi(m)),ruleStack:v,occurrenceStack:y};h.push(T),h.push(o)}else if(_ instanceof ms)h.push({idx:g,def:_.definition.concat(oi(m)),ruleStack:v,occurrenceStack:y});else if(_ instanceof ud)h.push(qae(_,g,v,y));else throw Error("non exhaustive match")}return u}function qae(n,e,t,r){const i=ui(t);i.push(n.name);const s=ui(r);return s.push(1),{idx:e,def:n.definition,ruleStack:i,occurrenceStack:s}}var ir;(function(n){n[n.OPTION=0]="OPTION",n[n.REPETITION=1]="REPETITION",n[n.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",n[n.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",n[n.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",n[n.ALTERNATION=5]="ALTERNATION"})(ir||(ir={}));function NU(n){if(n instanceof cs||n==="Option")return ir.OPTION;if(n instanceof Dr||n==="Repetition")return ir.REPETITION;if(n instanceof Fa||n==="RepetitionMandatory")return ir.REPETITION_MANDATORY;if(n instanceof Ba||n==="RepetitionMandatoryWithSeparator")return ir.REPETITION_MANDATORY_WITH_SEPARATOR;if(n instanceof Ho||n==="RepetitionWithSeparator")return ir.REPETITION_WITH_SEPARATOR;if(n instanceof Go||n==="Alternation")return ir.ALTERNATION;throw Error("non exhaustive match")}function Xae(n,e,t,r,i,s){const o=nA(n,e,t),a=PU(o)?nv:Sm;return s(o,r,a,i)}function Kae(n,e,t,r,i,s){const o=rA(n,e,i,t),a=PU(o)?nv:Sm;return s(o[0],a,r)}function Yae(n,e,t,r){const i=n.length,s=Co(n,o=>Co(o,a=>a.length===1));if(e)return function(o){const a=st(o,c=>c.GATE);for(let c=0;cOs(c)),a=ds(o,(c,l,u)=>(bt(l,h=>{wt(c,h.tokenTypeIdx)||(c[h.tokenTypeIdx]=u),bt(h.categoryMatches,p=>{wt(c,p)||(c[p]=u)})}),c),{});return function(){const c=this.LA(1);return a[c.tokenTypeIdx]}}else return function(){for(let o=0;os.length===1),i=n.length;if(r&&!t){const s=Os(n);if(s.length===1&&Un(s[0].categoryMatches)){const a=s[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===a}}else{const o=ds(s,(a,c,l)=>(a[c.tokenTypeIdx]=!0,bt(c.categoryMatches,u=>{a[u]=!0}),a),[]);return function(){const a=this.LA(1);return o[a.tokenTypeIdx]===!0}}}else return function(){e:for(let s=0;slw([o],1)),r=dI(t.length),i=st(t,o=>{const a={};return bt(o,c=>{const l=s1(c.partialPath);bt(l,u=>{a[u]=!0})}),a});let s=t;for(let o=1;o<=e;o++){const a=s;s=dI(a.length);for(let c=0;c{const _=s1(y.partialPath);bt(_,S=>{i[c][S]=!0})})}}}}return r}function nA(n,e,t,r){const i=new OU(n,ir.ALTERNATION,r);return e.accept(i),LU(i.result,t)}function rA(n,e,t,r){const i=new OU(n,t);e.accept(i);const s=i.result,a=new Qae(e,n,t).startWalking(),c=new ms({definition:s}),l=new ms({definition:a});return LU([c,l],r)}function uw(n,e){e:for(let t=0;t{const i=e[r];return t===i||i.categoryMatchesMap[t.tokenTypeIdx]})}function PU(n){return Co(n,e=>Co(e,t=>Co(t,r=>Un(r.categoryMatches))))}function tce(n){const e=n.lookaheadStrategy.validate({rules:n.rules,tokenTypes:n.tokenTypes,grammarName:n.grammarName});return st(e,t=>Object.assign({type:Hi.CUSTOM_LOOKAHEAD_VALIDATION},t))}function nce(n,e,t,r){const i=no(n,c=>rce(c,t)),s=mce(n,e,t),o=no(n,c=>hce(c,t)),a=no(n,c=>oce(c,n,r,t));return i.concat(s,o,a)}function rce(n,e){const t=new sce;n.accept(t);const r=t.allProductions,i=gU(r,ice),s=Vo(i,a=>a.length>1);return st(Cr(s),a=>{const c=Po(a),l=e.buildDuplicateFoundError(n,a),u=la(c),h={message:l,type:Hi.DUPLICATE_PRODUCTIONS,ruleName:n.name,dslName:u,occurrence:c.idx},p=DU(c);return p&&(h.parameter=p),h})}function ice(n){return`${la(n)}_#_${n.idx}_#_${DU(n)}`}function DU(n){return n instanceof Jn?n.terminalType.name:n instanceof ps?n.nonTerminalName:""}class sce extends lh{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(e){this.allProductions.push(e)}visitOption(e){this.allProductions.push(e)}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}visitAlternation(e){this.allProductions.push(e)}visitTerminal(e){this.allProductions.push(e)}}function oce(n,e,t,r){const i=[];if(ds(e,(o,a)=>a.name===n.name?o+1:o,0)>1){const o=r.buildDuplicateRuleNameError({topLevelRule:n,grammarName:t});i.push({message:o,type:Hi.DUPLICATE_RULE_NAME,ruleName:n.name})}return i}function ace(n,e,t){const r=[];let i;return $i(e,n)||(i=`Invalid rule override, rule: ->${n}<- cannot be overridden in the grammar: ->${t}<-as it is not defined in any of the super grammars `,r.push({message:i,type:Hi.INVALID_RULE_OVERRIDE,ruleName:n})),r}function UU(n,e,t,r=[]){const i=[],s=c_(e.definition);if(Un(s))return[];{const o=n.name;$i(s,n)&&i.push({message:t.buildLeftRecursionError({topLevelRule:n,leftRecursionPath:r}),type:Hi.LEFT_RECURSION,ruleName:o});const c=Ty(s,r.concat([n])),l=no(c,u=>{const h=ui(r);return h.push(u),UU(n,u,t,h)});return i.concat(l)}}function c_(n){let e=[];if(Un(n))return e;const t=Po(n);if(t instanceof ps)e.push(t.referencedRule);else if(t instanceof ms||t instanceof cs||t instanceof Fa||t instanceof Ba||t instanceof Ho||t instanceof Dr)e=e.concat(c_(t.definition));else if(t instanceof Go)e=Os(st(t.definition,s=>c_(s.definition)));else if(!(t instanceof Jn))throw Error("non exhaustive match");const r=Q_(t),i=n.length>1;if(r&&i){const s=oi(n);return e.concat(c_(s))}else return e}class iA extends lh{constructor(){super(...arguments),this.alternations=[]}visitAlternation(e){this.alternations.push(e)}}function cce(n,e){const t=new iA;n.accept(t);const r=t.alternations;return no(r,s=>{const o=Op(s.definition);return no(o,(a,c)=>{const l=IU([a],[],Sm,1);return Un(l)?[{message:e.buildEmptyAlternationError({topLevelRule:n,alternation:s,emptyChoiceIdx:c}),type:Hi.NONE_LAST_EMPTY_ALT,ruleName:n.name,occurrence:s.idx,alternative:c+1}]:[]})})}function lce(n,e,t){const r=new iA;n.accept(r);let i=r.alternations;return i=by(i,o=>o.ignoreAmbiguities===!0),no(i,o=>{const a=o.idx,c=o.maxLookahead||e,l=nA(a,n,c,o),u=dce(l,o,n,t),h=pce(l,o,n,t);return u.concat(h)})}class uce extends lh{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}}function hce(n,e){const t=new iA;n.accept(t);const r=t.alternations;return no(r,s=>s.definition.length>255?[{message:e.buildTooManyAlternativesError({topLevelRule:n,alternation:s}),type:Hi.TOO_MANY_ALTS,ruleName:n.name,occurrence:s.idx}]:[])}function fce(n,e,t){const r=[];return bt(n,i=>{const s=new uce;i.accept(s);const o=s.allProductions;bt(o,a=>{const c=NU(a),l=a.maxLookahead||e,u=a.idx,p=rA(u,i,c,l)[0];if(Un(Os(p))){const m=t.buildEmptyRepetitionError({topLevelRule:i,repetition:a});r.push({message:m,type:Hi.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),r}function dce(n,e,t,r){const i=[],s=ds(n,(a,c,l)=>(e.definition[l].ignoreAmbiguities===!0||bt(c,u=>{const h=[l];bt(n,(p,m)=>{l!==m&&uw(p,u)&&e.definition[m].ignoreAmbiguities!==!0&&h.push(m)}),h.length>1&&!uw(i,u)&&(i.push(u),a.push({alts:h,path:u}))}),a),[]);return st(s,a=>{const c=st(a.alts,u=>u+1);return{message:r.buildAlternationAmbiguityError({topLevelRule:t,alternation:e,ambiguityIndices:c,prefixPath:a.path}),type:Hi.AMBIGUOUS_ALTS,ruleName:t.name,occurrence:e.idx,alternatives:a.alts}})}function pce(n,e,t,r){const i=ds(n,(o,a,c)=>{const l=st(a,u=>({idx:c,path:u}));return o.concat(l)},[]);return ym(no(i,o=>{if(e.definition[o.idx].ignoreAmbiguities===!0)return[];const c=o.idx,l=o.path,u=lo(i,p=>e.definition[p.idx].ignoreAmbiguities!==!0&&p.idx{const m=[p.idx+1,c+1],g=e.idx===0?"":e.idx;return{message:r.buildAlternationPrefixAmbiguityError({topLevelRule:t,alternation:e,ambiguityIndices:m,prefixPath:p.path}),type:Hi.AMBIGUOUS_PREFIX_ALTS,ruleName:t.name,occurrence:g,alternatives:m}})}))}function mce(n,e,t){const r=[],i=st(e,s=>s.name);return bt(n,s=>{const o=s.name;if($i(i,o)){const a=t.buildNamespaceConflictError(s);r.push({message:a,type:Hi.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:o})}}),r}function gce(n){const e=Qb(n,{errMsgProvider:zae}),t={};return bt(n.rules,r=>{t[r.name]=r}),Vae(t,e.errMsgProvider)}function _ce(n){return n=Qb(n,{errMsgProvider:Cu}),nce(n.rules,n.tokenTypes,n.errMsgProvider,n.grammarName)}const FU="MismatchedTokenException",BU="NoViableAltException",zU="EarlyExitException",VU="NotAllInputParsedException",HU=[FU,BU,zU,VU];Object.freeze(HU);function rv(n){return $i(HU,n.name)}class ky extends Error{constructor(e,t){super(e),this.token=t,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class GU extends ky{constructor(e,t,r){super(e,t),this.previousToken=r,this.name=FU}}class vce extends ky{constructor(e,t,r){super(e,t),this.previousToken=r,this.name=BU}}class yce extends ky{constructor(e,t){super(e,t),this.name=VU}}class xce extends ky{constructor(e,t,r){super(e,t),this.previousToken=r,this.name=zU}}const o1={},WU="InRuleRecoveryException";class Sce extends Error{constructor(e){super(e),this.name=WU}}class Ece{initRecoverable(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=wt(e,"recoveryEnabled")?e.recoveryEnabled:Rc.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=wce)}getTokenToInsert(e){const t=wm(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return t.isInsertedInRecovery=!0,t}canTokenTypeBeInsertedInRecovery(e){return!0}canTokenTypeBeDeletedInRecovery(e){return!0}tryInRepetitionRecovery(e,t,r,i){const s=this.findReSyncTokenType(),o=this.exportLexerState(),a=[];let c=!1;const l=this.LA(1);let u=this.LA(1);const h=()=>{const p=this.LA(0),m=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:l,previous:p,ruleName:this.getCurrRuleFullName()}),g=new GU(m,l,this.LA(0));g.resyncedTokens=Op(a),this.SAVE_ERROR(g)};for(;!c;)if(this.tokenMatcher(u,i)){h();return}else if(r.call(this)){h(),e.apply(this,t);return}else this.tokenMatcher(u,s)?c=!0:(u=this.SKIP_TOKEN(),this.addToResyncTokens(u,a));this.importLexerState(o)}shouldInRepetitionRecoveryBeTried(e,t,r){return!(r===!1||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,t)))}getFollowsForInRuleRecovery(e,t){const r=this.getCurrentGrammarPath(e,t);return this.getNextPossibleTokenTypes(r)}tryInRuleRecovery(e,t){if(this.canRecoverWithSingleTokenInsertion(e,t))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){const r=this.SKIP_TOKEN();return this.consumeToken(),r}throw new Sce("sad sad panda")}canPerformInRuleRecovery(e,t){return this.canRecoverWithSingleTokenInsertion(e,t)||this.canRecoverWithSingleTokenDeletion(e)}canRecoverWithSingleTokenInsertion(e,t){if(!this.canTokenTypeBeInsertedInRecovery(e)||Un(t))return!1;const r=this.LA(1);return jf(t,s=>this.tokenMatcher(r,s))!==void 0}canRecoverWithSingleTokenDeletion(e){return this.canTokenTypeBeDeletedInRecovery(e)?this.tokenMatcher(this.LA(2),e):!1}isInCurrentRuleReSyncSet(e){const t=this.getCurrFollowKey(),r=this.getFollowSetFromFollowKey(t);return $i(r,e)}findReSyncTokenType(){const e=this.flattenFollowSet();let t=this.LA(1),r=2;for(;;){const i=jf(e,s=>Bae(t,s));if(i!==void 0)return i;t=this.LA(r),r++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return o1;const e=this.getLastExplicitRuleShortName(),t=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:t,inRule:this.shortRuleNameToFullName(r)}}buildFullFollowKeyStack(){const e=this.RULE_STACK,t=this.RULE_OCCURRENCE_STACK;return st(e,(r,i)=>i===0?o1:{ruleName:this.shortRuleNameToFullName(r),idxInCallingRule:t[i],inRule:this.shortRuleNameToFullName(e[i-1])})}flattenFollowSet(){const e=st(this.buildFullFollowKeyStack(),t=>this.getFollowSetFromFollowKey(t));return Os(e)}getFollowSetFromFollowKey(e){if(e===o1)return[Ku];const t=e.ruleName+e.idxInCallingRule+xU+e.inRule;return this.resyncFollows[t]}addToResyncTokens(e,t){return this.tokenMatcher(e,Ku)||t.push(e),t}reSyncTo(e){const t=[];let r=this.LA(1);for(;this.tokenMatcher(r,e)===!1;)r=this.SKIP_TOKEN(),this.addToResyncTokens(r,t);return Op(t)}attemptInRepetitionRecovery(e,t,r,i,s,o,a){}getCurrentGrammarPath(e,t){const r=this.getHumanReadableRuleStack(),i=ui(this.RULE_OCCURRENCE_STACK);return{ruleStack:r,occurrenceStack:i,lastTok:e,lastTokOccurrence:t}}getHumanReadableRuleStack(){return st(this.RULE_STACK,e=>this.shortRuleNameToFullName(e))}}function wce(n,e,t,r,i,s,o){const a=this.getKeyForAutomaticLookahead(r,i);let c=this.firstAfterRepMap[a];if(c===void 0){const p=this.getCurrRuleFullName(),m=this.getGAstProductions()[p];c=new s(m,i).startWalking(),this.firstAfterRepMap[a]=c}let l=c.token,u=c.occurrence;const h=c.isEndOfRule;this.RULE_STACK.length===1&&h&&l===void 0&&(l=Ku,u=1),!(l===void 0||u===void 0)&&this.shouldInRepetitionRecoveryBeTried(l,u,o)&&this.tryInRepetitionRecovery(n,e,t,l)}const Tce=4,Wl=8,jU=1<UU(t,t,Cu))}validateEmptyOrAlternatives(e){return no(e,t=>cce(t,Cu))}validateAmbiguousAlternationAlternatives(e,t){return no(e,r=>lce(r,t,Cu))}validateSomeNonEmptyLookaheadPath(e,t){return fce(e,t,Cu)}buildLookaheadForAlternation(e){return Xae(e.prodOccurrence,e.rule,e.maxLookahead,e.hasPredicates,e.dynamicTokensEnabled,Yae)}buildLookaheadForOptional(e){return Kae(e.prodOccurrence,e.rule,e.maxLookahead,e.dynamicTokensEnabled,NU(e.prodType),Zae)}}class Ace{initLooksAhead(e){this.dynamicTokensEnabled=wt(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:Rc.dynamicTokensEnabled,this.maxLookahead=wt(e,"maxLookahead")?e.maxLookahead:Rc.maxLookahead,this.lookaheadStrategy=wt(e,"lookaheadStrategy")?e.lookaheadStrategy:new bce({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(e){bt(e,t=>{this.TRACE_INIT(`${t.name} Rule Lookahead`,()=>{const{alternation:r,repetition:i,option:s,repetitionMandatory:o,repetitionMandatoryWithSeparator:a,repetitionWithSeparator:c}=Cce(t);bt(r,l=>{const u=l.idx===0?"":l.idx;this.TRACE_INIT(`${la(l)}${u}`,()=>{const h=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:l.idx,rule:t,maxLookahead:l.maxLookahead||this.maxLookahead,hasPredicates:l.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),p=a1(this.fullRuleNameToShort[t.name],jU,l.idx);this.setLaFuncCache(p,h)})}),bt(i,l=>{this.computeLookaheadFunc(t,l.idx,hw,"Repetition",l.maxLookahead,la(l))}),bt(s,l=>{this.computeLookaheadFunc(t,l.idx,$U,"Option",l.maxLookahead,la(l))}),bt(o,l=>{this.computeLookaheadFunc(t,l.idx,fw,"RepetitionMandatory",l.maxLookahead,la(l))}),bt(a,l=>{this.computeLookaheadFunc(t,l.idx,l_,"RepetitionMandatoryWithSeparator",l.maxLookahead,la(l))}),bt(c,l=>{this.computeLookaheadFunc(t,l.idx,dw,"RepetitionWithSeparator",l.maxLookahead,la(l))})})})}computeLookaheadFunc(e,t,r,i,s,o){this.TRACE_INIT(`${o}${t===0?"":t}`,()=>{const a=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:t,rule:e,maxLookahead:s||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),c=a1(this.fullRuleNameToShort[e.name],r,t);this.setLaFuncCache(c,a)})}getKeyForAutomaticLookahead(e,t){const r=this.getLastExplicitRuleShortName();return a1(r,e,t)}getLaFuncFromCache(e){return this.lookAheadFuncsCache.get(e)}setLaFuncCache(e,t){this.lookAheadFuncsCache.set(e,t)}}class Mce extends lh{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(e){this.dslMethods.option.push(e)}visitRepetitionWithSeparator(e){this.dslMethods.repetitionWithSeparator.push(e)}visitRepetitionMandatory(e){this.dslMethods.repetitionMandatory.push(e)}visitRepetitionMandatoryWithSeparator(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)}visitRepetition(e){this.dslMethods.repetition.push(e)}visitAlternation(e){this.dslMethods.alternation.push(e)}}const w0=new Mce;function Cce(n){w0.reset(),n.accept(w0);const e=w0.dslMethods;return w0.reset(),e}function pI(n,e){isNaN(n.startOffset)===!0?(n.startOffset=e.startOffset,n.endOffset=e.endOffset):n.endOffseto.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: - ${s.join(` - -`).replace(/\n/g,` - `)}`)}}};return t.prototype=r,t.prototype.constructor=t,t._RULE_NAMES=e,t}function Lce(n,e,t){const r=function(){};qU(r,n+"BaseSemanticsWithDefaults");const i=Object.create(t.prototype);return bt(e,s=>{i[s]=Nce}),r.prototype=i,r.prototype.constructor=r,r}var pw;(function(n){n[n.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",n[n.MISSING_METHOD=1]="MISSING_METHOD"})(pw||(pw={}));function Pce(n,e){return Dce(n,e)}function Dce(n,e){const t=lo(e,i=>Gc(n[i])===!1),r=st(t,i=>({msg:`Missing visitor method: <${i}> on ${n.constructor.name} CST Visitor.`,type:pw.MISSING_METHOD,methodName:i}));return ym(r)}class Uce{initTreeBuilder(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=wt(e,"nodeLocationTracking")?e.nodeLocationTracking:Rc.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=Or,this.cstFinallyStateUpdate=Or,this.cstPostTerminal=Or,this.cstPostNonTerminal=Or,this.cstPostRule=Or;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=mI,this.setNodeLocationFromNode=mI,this.cstPostRule=Or,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=Or,this.setNodeLocationFromNode=Or,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=pI,this.setNodeLocationFromNode=pI,this.cstPostRule=Or,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=Or,this.setNodeLocationFromNode=Or,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=Or,this.setNodeLocationFromNode=Or,this.cstPostRule=Or,this.setInitialNodeLocation=Or;else throw Error(`Invalid config option: "${e.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(e){e.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(e){const t=this.LA(1);e.location={startOffset:t.startOffset,startLine:t.startLine,startColumn:t.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(e){const t={name:e,children:Object.create(null)};this.setInitialNodeLocation(t),this.CST_STACK.push(t)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(e){const t=this.LA(0),r=e.location;r.startOffset<=t.startOffset?(r.endOffset=t.endOffset,r.endLine=t.endLine,r.endColumn=t.endColumn):(r.startOffset=NaN,r.startLine=NaN,r.startColumn=NaN)}cstPostRuleOnlyOffset(e){const t=this.LA(0),r=e.location;r.startOffset<=t.startOffset?r.endOffset=t.endOffset:r.startOffset=NaN}cstPostTerminal(e,t){const r=this.CST_STACK[this.CST_STACK.length-1];Rce(r,t,e),this.setNodeLocationFromToken(r.location,t)}cstPostNonTerminal(e,t){const r=this.CST_STACK[this.CST_STACK.length-1];kce(r,t,e),this.setNodeLocationFromNode(r.location,e.location)}getBaseCstVisitorConstructor(){if(Cc(this.baseCstVisitorConstructor)){const e=Oce(this.className,co(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(Cc(this.baseCstVisitorWithDefaultsConstructor)){const e=Lce(this.className,co(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-1]}getPreviousExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-2]}getLastExplicitRuleOccurrenceIndex(){const e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]}}class Fce{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(e){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):sv}LA(e){const t=this.currIdx+e;return t<0||this.tokVectorLength<=t?sv:this.tokVector[t]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(e){this.currIdx=e}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}}class Bce{ACTION(e){return e.call(this)}consume(e,t,r){return this.consumeInternal(t,e,r)}subrule(e,t,r){return this.subruleInternal(t,e,r)}option(e,t){return this.optionInternal(t,e)}or(e,t){return this.orInternal(t,e)}many(e,t){return this.manyInternal(e,t)}atLeastOne(e,t){return this.atLeastOneInternal(e,t)}CONSUME(e,t){return this.consumeInternal(e,0,t)}CONSUME1(e,t){return this.consumeInternal(e,1,t)}CONSUME2(e,t){return this.consumeInternal(e,2,t)}CONSUME3(e,t){return this.consumeInternal(e,3,t)}CONSUME4(e,t){return this.consumeInternal(e,4,t)}CONSUME5(e,t){return this.consumeInternal(e,5,t)}CONSUME6(e,t){return this.consumeInternal(e,6,t)}CONSUME7(e,t){return this.consumeInternal(e,7,t)}CONSUME8(e,t){return this.consumeInternal(e,8,t)}CONSUME9(e,t){return this.consumeInternal(e,9,t)}SUBRULE(e,t){return this.subruleInternal(e,0,t)}SUBRULE1(e,t){return this.subruleInternal(e,1,t)}SUBRULE2(e,t){return this.subruleInternal(e,2,t)}SUBRULE3(e,t){return this.subruleInternal(e,3,t)}SUBRULE4(e,t){return this.subruleInternal(e,4,t)}SUBRULE5(e,t){return this.subruleInternal(e,5,t)}SUBRULE6(e,t){return this.subruleInternal(e,6,t)}SUBRULE7(e,t){return this.subruleInternal(e,7,t)}SUBRULE8(e,t){return this.subruleInternal(e,8,t)}SUBRULE9(e,t){return this.subruleInternal(e,9,t)}OPTION(e){return this.optionInternal(e,0)}OPTION1(e){return this.optionInternal(e,1)}OPTION2(e){return this.optionInternal(e,2)}OPTION3(e){return this.optionInternal(e,3)}OPTION4(e){return this.optionInternal(e,4)}OPTION5(e){return this.optionInternal(e,5)}OPTION6(e){return this.optionInternal(e,6)}OPTION7(e){return this.optionInternal(e,7)}OPTION8(e){return this.optionInternal(e,8)}OPTION9(e){return this.optionInternal(e,9)}OR(e){return this.orInternal(e,0)}OR1(e){return this.orInternal(e,1)}OR2(e){return this.orInternal(e,2)}OR3(e){return this.orInternal(e,3)}OR4(e){return this.orInternal(e,4)}OR5(e){return this.orInternal(e,5)}OR6(e){return this.orInternal(e,6)}OR7(e){return this.orInternal(e,7)}OR8(e){return this.orInternal(e,8)}OR9(e){return this.orInternal(e,9)}MANY(e){this.manyInternal(0,e)}MANY1(e){this.manyInternal(1,e)}MANY2(e){this.manyInternal(2,e)}MANY3(e){this.manyInternal(3,e)}MANY4(e){this.manyInternal(4,e)}MANY5(e){this.manyInternal(5,e)}MANY6(e){this.manyInternal(6,e)}MANY7(e){this.manyInternal(7,e)}MANY8(e){this.manyInternal(8,e)}MANY9(e){this.manyInternal(9,e)}MANY_SEP(e){this.manySepFirstInternal(0,e)}MANY_SEP1(e){this.manySepFirstInternal(1,e)}MANY_SEP2(e){this.manySepFirstInternal(2,e)}MANY_SEP3(e){this.manySepFirstInternal(3,e)}MANY_SEP4(e){this.manySepFirstInternal(4,e)}MANY_SEP5(e){this.manySepFirstInternal(5,e)}MANY_SEP6(e){this.manySepFirstInternal(6,e)}MANY_SEP7(e){this.manySepFirstInternal(7,e)}MANY_SEP8(e){this.manySepFirstInternal(8,e)}MANY_SEP9(e){this.manySepFirstInternal(9,e)}AT_LEAST_ONE(e){this.atLeastOneInternal(0,e)}AT_LEAST_ONE1(e){return this.atLeastOneInternal(1,e)}AT_LEAST_ONE2(e){this.atLeastOneInternal(2,e)}AT_LEAST_ONE3(e){this.atLeastOneInternal(3,e)}AT_LEAST_ONE4(e){this.atLeastOneInternal(4,e)}AT_LEAST_ONE5(e){this.atLeastOneInternal(5,e)}AT_LEAST_ONE6(e){this.atLeastOneInternal(6,e)}AT_LEAST_ONE7(e){this.atLeastOneInternal(7,e)}AT_LEAST_ONE8(e){this.atLeastOneInternal(8,e)}AT_LEAST_ONE9(e){this.atLeastOneInternal(9,e)}AT_LEAST_ONE_SEP(e){this.atLeastOneSepFirstInternal(0,e)}AT_LEAST_ONE_SEP1(e){this.atLeastOneSepFirstInternal(1,e)}AT_LEAST_ONE_SEP2(e){this.atLeastOneSepFirstInternal(2,e)}AT_LEAST_ONE_SEP3(e){this.atLeastOneSepFirstInternal(3,e)}AT_LEAST_ONE_SEP4(e){this.atLeastOneSepFirstInternal(4,e)}AT_LEAST_ONE_SEP5(e){this.atLeastOneSepFirstInternal(5,e)}AT_LEAST_ONE_SEP6(e){this.atLeastOneSepFirstInternal(6,e)}AT_LEAST_ONE_SEP7(e){this.atLeastOneSepFirstInternal(7,e)}AT_LEAST_ONE_SEP8(e){this.atLeastOneSepFirstInternal(8,e)}AT_LEAST_ONE_SEP9(e){this.atLeastOneSepFirstInternal(9,e)}RULE(e,t,r=ov){if($i(this.definedRulesNames,e)){const o={message:Cu.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:Hi.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(o)}this.definedRulesNames.push(e);const i=this.defineRule(e,t,r);return this[e]=i,i}OVERRIDE_RULE(e,t,r=ov){const i=ace(e,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);const s=this.defineRule(e,t,r);return this[e]=s,s}BACKTRACK(e,t){return function(){this.isBackTrackingStack.push(1);const r=this.saveRecogState();try{return e.apply(this,t),!0}catch(i){if(rv(i))return!1;throw i}finally{this.reloadRecogState(r),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return Voe(Cr(this.gastProductionsCache))}}class zce{initRecognizerEngine(e,t){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=nv,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},wt(t,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 - For Further details.`);if(ln(e)){if(Un(e))throw Error(`A Token Vocabulary cannot be empty. - Note that the first argument for the parser constructor - is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 - For Further details.`)}if(ln(e))this.tokensMap=ds(e,(s,o)=>(s[o.name]=o,s),{});else if(wt(e,"modes")&&Co(Os(Cr(e.modes)),Pae)){const s=Os(Cr(e.modes)),o=Ay(s);this.tokensMap=ds(o,(a,c)=>(a[c.name]=c,a),{})}else if(ao(e))this.tokensMap=ui(e);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=Ku;const r=wt(e,"modes")?Os(Cr(e.modes)):Cr(e),i=Co(r,s=>Un(s.categoryMatches));this.tokenMatcher=i?nv:Sm,Em(Cr(this.tokensMap))}defineRule(e,t,r){if(this.selfAnalysisDone)throw Error(`Grammar rule <${e}> may not be defined after the 'performSelfAnalysis' method has been called' -Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);const i=wt(r,"resyncEnabled")?r.resyncEnabled:ov.resyncEnabled,s=wt(r,"recoveryValueFunc")?r.recoveryValueFunc:ov.recoveryValueFunc,o=this.ruleShortNameIdx<o.call(this)&&a.call(this)}}else s=e;if(i.call(this)===!0)return s.call(this)}atLeastOneInternal(e,t){const r=this.getKeyForAutomaticLookahead(fw,e);return this.atLeastOneInternalLogic(e,t,r)}atLeastOneInternalLogic(e,t,r){let i=this.getLaFuncFromCache(r),s;if(typeof t!="function"){s=t.DEF;const o=t.GATE;if(o!==void 0){const a=i;i=()=>o.call(this)&&a.call(this)}}else s=t;if(i.call(this)===!0){let o=this.doSingleRepetition(s);for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s)}else throw this.raiseEarlyExitException(e,ir.REPETITION_MANDATORY,t.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[e,t],i,fw,e,$ae)}atLeastOneSepFirstInternal(e,t){const r=this.getKeyForAutomaticLookahead(l_,e);this.atLeastOneSepFirstInternalLogic(e,t,r)}atLeastOneSepFirstInternalLogic(e,t,r){const i=t.DEF,s=t.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,fI],a,l_,e,fI)}else throw this.raiseEarlyExitException(e,ir.REPETITION_MANDATORY_WITH_SEPARATOR,t.ERR_MSG)}manyInternal(e,t){const r=this.getKeyForAutomaticLookahead(hw,e);return this.manyInternalLogic(e,t,r)}manyInternalLogic(e,t,r){let i=this.getLaFuncFromCache(r),s;if(typeof t!="function"){s=t.DEF;const a=t.GATE;if(a!==void 0){const c=i;i=()=>a.call(this)&&c.call(this)}}else s=t;let o=!0;for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s);this.attemptInRepetitionRecovery(this.manyInternal,[e,t],i,hw,e,jae,o)}manySepFirstInternal(e,t){const r=this.getKeyForAutomaticLookahead(dw,e);this.manySepFirstInternalLogic(e,t,r)}manySepFirstInternalLogic(e,t,r){const i=t.DEF,s=t.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,hI],a,dw,e,hI)}}repetitionSepSecondInternal(e,t,r,i,s){for(;r();)this.CONSUME(t),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,t,r,i,s],r,l_,e,s)}doSingleRepetition(e){const t=this.getLexerPosition();return e.call(this),this.getLexerPosition()>t}orInternal(e,t){const r=this.getKeyForAutomaticLookahead(jU,t),i=ln(e)?e:e.DEF,o=this.getLaFuncFromCache(r).call(this,i);if(o!==void 0)return i[o].ALT.call(this);this.raiseNoAltException(t,e.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){const e=this.LA(1),t=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new yce(t,e))}}subruleInternal(e,t,r){let i;try{const s=r!==void 0?r.ARGS:void 0;return this.subruleIdx=t,i=e.apply(this,s),this.cstPostNonTerminal(i,r!==void 0&&r.LABEL!==void 0?r.LABEL:e.ruleName),i}catch(s){throw this.subruleInternalError(s,r,e.ruleName)}}subruleInternalError(e,t,r){throw rv(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,t!==void 0&&t.LABEL!==void 0?t.LABEL:r),delete e.partialCstResult),e}consumeInternal(e,t,r){let i;try{const s=this.LA(1);this.tokenMatcher(s,e)===!0?(this.consumeToken(),i=s):this.consumeInternalError(e,s,r)}catch(s){i=this.consumeInternalRecovery(e,t,s)}return this.cstPostTerminal(r!==void 0&&r.LABEL!==void 0?r.LABEL:e.name,i),i}consumeInternalError(e,t,r){let i;const s=this.LA(0);throw r!==void 0&&r.ERR_MSG?i=r.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:t,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new GU(i,t,s))}consumeInternalRecovery(e,t,r){if(this.recoveryEnabled&&r.name==="MismatchedTokenException"&&!this.isBackTracking()){const i=this.getFollowsForInRuleRecovery(e,t);try{return this.tryInRuleRecovery(e,i)}catch(s){throw s.name===WU?r:s}}else throw r}saveRecogState(){const e=this.errors,t=ui(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:t,CST_STACK:this.CST_STACK}}reloadRecogState(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK}ruleInvocationStateUpdate(e,t,r){this.RULE_OCCURRENCE_STACK.push(r),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(t)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){const e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]}shortRuleNameToFullName(e){return this.shortRuleNameToFull[e]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),Ku)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}}class Vce{initErrorHandler(e){this._errors=[],this.errorMessageProvider=wt(e,"errorMessageProvider")?e.errorMessageProvider:Rc.errorMessageProvider}SAVE_ERROR(e){if(rv(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:ui(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return ui(this._errors)}set errors(e){this._errors=e}raiseEarlyExitException(e,t,r){const i=this.getCurrRuleFullName(),s=this.getGAstProductions()[i],a=rA(e,s,t,this.maxLookahead)[0],c=[];for(let u=1;u<=this.maxLookahead;u++)c.push(this.LA(u));const l=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:c,previous:this.LA(0),customUserDescription:r,ruleName:i});throw this.SAVE_ERROR(new xce(l,this.LA(1),this.LA(0)))}raiseNoAltException(e,t){const r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],s=nA(e,i,this.maxLookahead),o=[];for(let l=1;l<=this.maxLookahead;l++)o.push(this.LA(l));const a=this.LA(0),c=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:o,previous:a,customUserDescription:t,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new vce(c,this.LA(1),a))}}class Hce{initContentAssist(){}computeContentAssist(e,t){const r=this.gastProductionsCache[e];if(Cc(r))throw Error(`Rule ->${e}<- does not exist in this grammar.`);return IU([r],t,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(e){const t=Po(e.ruleStack),i=this.getGAstProductions()[t];return new Wae(i,e).startWalking()}}const Iy={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(Iy);const gI=!0,_I=Math.pow(2,Wl)-1,XU=Ps({name:"RECORDING_PHASE_TOKEN",pattern:Br.NA});Em([XU]);const KU=wm(XU,`This IToken indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(KU);const Gce={name:`This CSTNode indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}};class Wce{initGastRecorder(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let e=0;e<10;e++){const t=e>0?e:"";this[`CONSUME${t}`]=function(r,i){return this.consumeInternalRecord(r,e,i)},this[`SUBRULE${t}`]=function(r,i){return this.subruleInternalRecord(r,e,i)},this[`OPTION${t}`]=function(r){return this.optionInternalRecord(r,e)},this[`OR${t}`]=function(r){return this.orInternalRecord(r,e)},this[`MANY${t}`]=function(r){this.manyInternalRecord(e,r)},this[`MANY_SEP${t}`]=function(r){this.manySepFirstInternalRecord(e,r)},this[`AT_LEAST_ONE${t}`]=function(r){this.atLeastOneInternalRecord(e,r)},this[`AT_LEAST_ONE_SEP${t}`]=function(r){this.atLeastOneSepFirstInternalRecord(e,r)}}this.consume=function(e,t,r){return this.consumeInternalRecord(t,e,r)},this.subrule=function(e,t,r){return this.subruleInternalRecord(t,e,r)},this.option=function(e,t){return this.optionInternalRecord(t,e)},this.or=function(e,t){return this.orInternalRecord(t,e)},this.many=function(e,t){this.manyInternalRecord(e,t)},this.atLeastOne=function(e,t){this.atLeastOneInternalRecord(e,t)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{const e=this;for(let t=0;t<10;t++){const r=t>0?t:"";delete e[`CONSUME${r}`],delete e[`SUBRULE${r}`],delete e[`OPTION${r}`],delete e[`OR${r}`],delete e[`MANY${r}`],delete e[`MANY_SEP${r}`],delete e[`AT_LEAST_ONE${r}`],delete e[`AT_LEAST_ONE_SEP${r}`]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})}ACTION_RECORD(e){}BACKTRACK_RECORD(e,t){return()=>!0}LA_RECORD(e){return sv}topLevelRuleRecord(e,t){try{const r=new ud({definition:[],name:e});return r.name=e,this.recordingProdStack.push(r),t.call(this),this.recordingProdStack.pop(),r}catch(r){if(r.KNOWN_RECORDER_ERROR!==!0)try{r.message=r.message+` - This error was thrown during the "grammar recording phase" For more info see: - https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw r}throw r}}optionInternalRecord(e,t){return Vd.call(this,cs,e,t)}atLeastOneInternalRecord(e,t){Vd.call(this,Fa,t,e)}atLeastOneSepFirstInternalRecord(e,t){Vd.call(this,Ba,t,e,gI)}manyInternalRecord(e,t){Vd.call(this,Dr,t,e)}manySepFirstInternalRecord(e,t){Vd.call(this,Ho,t,e,gI)}orInternalRecord(e,t){return jce.call(this,e,t)}subruleInternalRecord(e,t,r){if(iv(t),!e||wt(e,"ruleName")===!1){const a=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(e)}> - inside top level rule: <${this.recordingProdStack[0].name}>`);throw a.KNOWN_RECORDER_ERROR=!0,a}const i=Wf(this.recordingProdStack),s=e.ruleName,o=new ps({idx:t,nonTerminalName:s,label:r==null?void 0:r.LABEL,referencedRule:void 0});return i.definition.push(o),this.outputCst?Gce:Iy}consumeInternalRecord(e,t,r){if(iv(t),!CU(e)){const o=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(e)}> - inside top level rule: <${this.recordingProdStack[0].name}>`);throw o.KNOWN_RECORDER_ERROR=!0,o}const i=Wf(this.recordingProdStack),s=new Jn({idx:t,terminalType:e,label:r==null?void 0:r.LABEL});return i.definition.push(s),KU}}function Vd(n,e,t,r=!1){iv(t);const i=Wf(this.recordingProdStack),s=Gc(e)?e:e.DEF,o=new n({definition:[],idx:t});return r&&(o.separator=e.SEP),wt(e,"MAX_LOOKAHEAD")&&(o.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(o),s.call(this),i.definition.push(o),this.recordingProdStack.pop(),Iy}function jce(n,e){iv(e);const t=Wf(this.recordingProdStack),r=ln(n)===!1,i=r===!1?n:n.DEF,s=new Go({definition:[],idx:e,ignoreAmbiguities:r&&n.IGNORE_AMBIGUITIES===!0});wt(n,"MAX_LOOKAHEAD")&&(s.maxLookahead=n.MAX_LOOKAHEAD);const o=Jb(i,a=>Gc(a.GATE));return s.hasPredicates=o,t.definition.push(s),bt(i,a=>{const c=new ms({definition:[]});s.definition.push(c),wt(a,"IGNORE_AMBIGUITIES")?c.ignoreAmbiguities=a.IGNORE_AMBIGUITIES:wt(a,"GATE")&&(c.ignoreAmbiguities=!0),this.recordingProdStack.push(c),a.ALT.call(this),this.recordingProdStack.pop()}),Iy}function vI(n){return n===0?"":`${n}`}function iv(n){if(n<0||n>_I){const e=new Error(`Invalid DSL Method idx value: <${n}> - Idx value must be a none negative value smaller than ${_I+1}`);throw e.KNOWN_RECORDER_ERROR=!0,e}}class $ce{initPerformanceTracer(e){if(wt(e,"traceInitPerf")){const t=e.traceInitPerf,r=typeof t=="number";this.traceInitMaxIdent=r?t:1/0,this.traceInitPerf=r?t>0:t}else this.traceInitMaxIdent=0,this.traceInitPerf=Rc.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(e,t){if(this.traceInitPerf===!0){this.traceInitIndent++;const r=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${e}>`);const{time:i,value:s}=vU(t),o=i>10?console.warn:console.log;return this.traceInitIndent time: ${i}ms`),this.traceInitIndent--,s}else return t()}}function qce(n,e){e.forEach(t=>{const r=t.prototype;Object.getOwnPropertyNames(r).forEach(i=>{if(i==="constructor")return;const s=Object.getOwnPropertyDescriptor(r,i);s&&(s.get||s.set)?Object.defineProperty(n.prototype,i,s):n.prototype[i]=t.prototype[i]})})}const sv=wm(Ku,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(sv);const Rc=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:kU,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),ov=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0});var Hi;(function(n){n[n.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",n[n.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",n[n.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",n[n.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",n[n.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",n[n.LEFT_RECURSION=5]="LEFT_RECURSION",n[n.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",n[n.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",n[n.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",n[n.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",n[n.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",n[n.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",n[n.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",n[n.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(Hi||(Hi={}));class Tm{static performSelfAnalysis(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let e;this.selfAnalysisDone=!0;const t=this.className;this.TRACE_INIT("toFastProps",()=>{yU(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),bt(this.definedRulesNames,i=>{const o=this[i].originalGrammarAction;let a;this.TRACE_INIT(`${i} Rule`,()=>{a=this.topLevelRuleRecord(i,o)}),this.gastProductionsCache[i]=a})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT("Grammar Resolving",()=>{r=gce({rules:Cr(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT("Grammar Validations",()=>{if(Un(r)&&this.skipValidations===!1){const i=_ce({rules:Cr(this.gastProductionsCache),tokenTypes:Cr(this.tokensMap),errMsgProvider:Cu,grammarName:t}),s=tce({lookaheadStrategy:this.lookaheadStrategy,rules:Cr(this.gastProductionsCache),tokenTypes:Cr(this.tokensMap),grammarName:t});this.definitionErrors=this.definitionErrors.concat(i,s)}}),Un(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{const i=Xoe(Cr(this.gastProductionsCache));this.resyncFollows=i}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var i,s;(s=(i=this.lookaheadStrategy).initialize)===null||s===void 0||s.call(i,{rules:Cr(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(Cr(this.gastProductionsCache))})),!Tm.DEFER_DEFINITION_ERRORS_HANDLING&&!Un(this.definitionErrors))throw e=st(this.definitionErrors,i=>i.message),new Error(`Parser Definition Errors detected: - ${e.join(` -------------------------------- -`)}`)})}constructor(e,t){this.definitionErrors=[],this.selfAnalysisDone=!1;const r=this;if(r.initErrorHandler(t),r.initLexerAdapter(),r.initLooksAhead(t),r.initRecognizerEngine(e,t),r.initRecoverable(t),r.initTreeBuilder(t),r.initContentAssist(),r.initGastRecorder(t),r.initPerformanceTracer(t),wt(t,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. - Please use the flag on the relevant DSL method instead. - See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES - For further details.`);this.skipValidations=wt(t,"skipValidations")?t.skipValidations:Rc.skipValidations}}Tm.DEFER_DEFINITION_ERRORS_HANDLING=!1;qce(Tm,[Ece,Ace,Uce,Fce,zce,Bce,Vce,Hce,Wce,$ce]);class Xce extends Tm{constructor(e,t=Rc){const r=ui(t);r.outputCst=!0,super(e,r)}}function Kce(n){const e=new Yce,t=Cr(n);return st(t,r=>e.visitRule(r))}class Yce extends lh{visitRule(e){const t=this.visitEach(e.definition),r=gU(t,s=>s.propertyName),i=st(r,(s,o)=>{const a=!Jb(s,l=>!l.canBeNull);let c=s[0].type;return s.length>1&&(c=st(s,l=>l.type)),{name:o,type:c,optional:a}});return{name:e.name,properties:i}}visitAlternative(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitOption(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetition(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetitionMandatory(e){return this.visitEach(e.definition)}visitRepetitionMandatoryWithSeparator(e){return this.visitEach(e.definition).concat({propertyName:e.separator.name,canBeNull:!0,type:T0(e.separator)})}visitRepetitionWithSeparator(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0}).concat({propertyName:e.separator.name,canBeNull:!0,type:T0(e.separator)})}visitAlternation(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitTerminal(e){return[{propertyName:e.label||e.terminalType.name,canBeNull:!1,type:T0(e)}]}visitNonTerminal(e){return[{propertyName:e.label||e.nonTerminalName,canBeNull:!1,type:T0(e)}]}visitEachAndOverrideWith(e,t){return st(this.visitEach(e),r=>hs({},r,t))}visitEach(e){return Os(st(e,t=>this.visit(t)))}}function T0(n){return n instanceof ps?{kind:"rule",name:n.referencedRule.name}:{kind:"token"}}function Zce(n,e){let t=[];return t=t.concat('import type { CstNode, ICstVisitor, IToken } from "chevrotain";'),t=t.concat(Os(st(n,r=>Qce(r)))),e.includeVisitorInterface&&(t=t.concat(nle(e.visitorInterfaceName,n))),t.join(` - -`)+` -`}function Qce(n){const e=Jce(n),t=ele(n);return[e,t]}function Jce(n){const e=YU(n.name),t=sA(n.name);return`export interface ${e} extends CstNode { - name: "${n.name}"; - children: ${t}; -}`}function ele(n){return`export type ${sA(n.name)} = { - ${st(n.properties,t=>tle(t)).join(` - `)} -};`}function tle(n){const e=ile(n.type);return`${n.name}${n.optional?"?":""}: ${e}[];`}function nle(n,e){return`export interface ${n} extends ICstVisitor { - ${st(e,t=>rle(t)).join(` - `)} -}`}function rle(n){const e=sA(n.name);return`${n.name}(children: ${e}, param?: IN): OUT;`}function ile(n){if(ln(n)){const e=Ay(st(n,r=>yI(r)));return"("+ds(e,(r,i)=>r+" | "+i)+")"}else return yI(n)}function yI(n){return n.kind==="token"?"IToken":YU(n.name)}function YU(n){return nU(n)+"CstNode"}function sA(n){return nU(n)+"CstChildren"}const sle={includeVisitorInterface:!0,visitorInterfaceName:"ICstNodeVisitor"};function ole(n,e){const t=Object.assign(Object.assign({},sle),e),r=Kce(n);return Zce(r,t)}var ZU={exports:{}},c1={exports:{}},xI;function ale(){return xI||(xI=1,function(n,e){(function(t,r){n.exports=r()})(Eo,function(){function t(v){return!isNaN(parseFloat(v))&&isFinite(v)}function r(v){return v.charAt(0).toUpperCase()+v.substring(1)}function i(v){return function(){return this[v]}}var s=["isConstructor","isEval","isNative","isToplevel"],o=["columnNumber","lineNumber"],a=["fileName","functionName","source"],c=["args"],l=["evalOrigin"],u=s.concat(o,a,c,l);function h(v){if(v)for(var y=0;y-1&&(u=u.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var h=u.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),p=h.match(/ (\(.+\)$)/);h=p?h.replace(p[0],""):h;var m=this.extractLocation(p?p[1]:h),g=p&&h||void 0,v=["eval",""].indexOf(m[0])>-1?void 0:m[0];return new r({functionName:g,fileName:v,lineNumber:m[1],columnNumber:m[2],source:u})},this)},parseFFOrSafari:function(c){var l=c.stack.split(` -`).filter(function(u){return!u.match(o)},this);return l.map(function(u){if(u.indexOf(" > eval")>-1&&(u=u.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),u.indexOf("@")===-1&&u.indexOf(":")===-1)return new r({functionName:u});var h=/((.*".+"[^@]*)?[^@]*)(?:@)/,p=u.match(h),m=p&&p[1]?p[1]:void 0,g=this.extractLocation(u.replace(h,""));return new r({functionName:m,fileName:g[0],lineNumber:g[1],columnNumber:g[2],source:u})},this)},parseOpera:function(c){return!c.stacktrace||c.message.indexOf(` -`)>-1&&c.message.split(` -`).length>c.stacktrace.split(` -`).length?this.parseOpera9(c):c.stack?this.parseOpera11(c):this.parseOpera10(c)},parseOpera9:function(c){for(var l=/Line (\d+).*script (?:in )?(\S+)/i,u=c.message.split(` -`),h=[],p=2,m=u.length;p/,"$2").replace(/\([^)]*\)/g,"")||void 0,v;m.match(/\(([^)]*)\)/)&&(v=m.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var y=v===void 0||v==="[arguments not available]"?void 0:v.split(",");return new r({functionName:g,args:y,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:u})},this)}}})})(ZU);var cle=ZU.exports;const lle=Nc(cle);function $c(n){const e={},t={get(){return[!1,void 0]},set(){return[!1,void 0]},tick(){},everytick(){},...n,getcommand(r){return e[r]},command(r,i){return e[r]=i,t}};return t}function dc(n){return K(n)&&K(n.x)&&K(n.y)}function Yr(n,e){switch(e){case it.NORTH:--n.y;break;case it.SOUTH:++n.y;break;case it.WEST:--n.x;break;case it.EAST:++n.x;break}return n}function Wh(n,e){const t=e.x-n.x,r=e.y-n.y;if(t<0)return it.WEST;if(t>0)return it.EAST;if(r<0)return it.NORTH;if(r>0)return it.SOUTH}const QU={idle:"IDLE",up:"NORTH",down:"SOUTH",left:"WEST",right:"EAST",by:"BY",at:"AT",flow:"FLOW",seek:"SEEK",rndns:"RNDNS",rndne:"RNDNE",rnd:"RND",cw:"CW",ccw:"CCW",opp:"OPP",rndp:"RNDP",i:"IDLE",u:"NORTH",north:"NORTH",n:"NORTH",d:"SOUTH",south:"SOUTH",s:"SOUTH",l:"WEST",west:"WEST",w:"WEST",r:"EAST",east:"EAST",e:"EAST",edit:"EDIT"};function vc(n){return fn(n)&&JU(n[0])}function JU(n){return K(it[n])&&Kt(n)}function ule(n){const e=it[n];return K(e)?e:it.IDLE}function e3(n){if(Kt(n))return QU[$t(n)]}function SI(n){if(vc(n))return n;if(JU(n))return[n];const e=e3(n);if(K(e))return[e]}function EI(n){const e=se.words[n],t=SI(e);if(vc(t))return[t,n+1];const[r,i]=Di(n),s=SI(r);return vc(s)?[s,i]:[void 0,n]}function mw(n){const e=[];let[t,r]=EI(n);for(;vc(t);){if(e.push(...t),(t[0]==="AT"||t[0]==="BY")&&t.length<2){const[o,a,c]=Ve(se.words,r,[Ne.NUMBER,Ne.NUMBER]);e.push(o,a),r=c}const[i,s]=EI(r);t=i,r=s}return e.length?[e,r]:[void 0,n]}function $f(n){return fn(n)&&typeof n[0]=="string"}function wI(n){const e=se.words[n];if($f(e))return[e,n+1];const[t,r]=fv(n),[i,s]=Di(r,!1);return Kt(i)?[[i,t],s]:[void 0,n]}function av(n){if(!$f(n))return;const[e]=n;return e}function t3(n){if(!$f(n))return;const[,e]=n,t=K(e)?efe(e):void 0;return K(t)?t:void 0}function n3(n){if(!$f(n))return;const[,e]=n,t=K(e)?tfe(e):void 0;return K(t)?t:void 0}const li=60,uh=25;var vn=(n=>(n[n.ERROR=0]="ERROR",n[n.LOADER=1]="LOADER",n[n.BOARD=2]="BOARD",n[n.OBJECT=3]="OBJECT",n[n.TERRAIN=4]="TERRAIN",n[n.CHARSET=5]="CHARSET",n[n.PALETTE=6]="PALETTE",n))(vn||{});function r3(n,e){const t=n??Vn.ISWALK,r=e??Vn.ISWALK;switch(t){case Vn.ISWALK:return r!==Vn.ISWALK;case Vn.ISSWIM:return r!==Vn.ISSWIM;case Vn.ISSOLID:return!0;case Vn.ISBULLET:return r!==Vn.ISWALK&&r!==Vn.ISSWIM}}function TI(n,e,t){const r=n==null?void 0:n.objects[t];if(K(r))return r;if(K(e)){const i=bm(n,"player"),s={x:e.x??0,y:e.y??0};s3(s,i)}}function bm(n,e){var r,i;return[...((i=(r=n==null?void 0:n.named)==null?void 0:r[e])==null?void 0:i.values())??[]].map(s=>typeof s=="string"?n==null?void 0:n.objects[s]:n==null?void 0:n.terrain[s]).filter(K)}function i3(n,e){const t=av(e),r=t3(e),i=n3(e);return n.filter(s=>!(K(t)&&dA(s)!==t||K(r)&&Qle(s)!==r||K(i)&&Jle(s)!==i)).filter(K)}function l1(n,e){return K(n)?e.map(t=>{var r;if(typeof t=="string"){const i=n.objects[t];if(K(i))return i;const s=bm(n,$t(t));if(s.length)return s}else if(dc(t)&&t.x>=0&&t.x=0&&t.y=0;r--){const i=n[r];let s=oA[i];s*=t,e+=s,t*=qf}return e}ci.s_to_int=aA;function a3(n){let e=BigInt(0),t=BigInt(1);const r=BigInt(qf);for(let i=n.length-1;i>=0;i--){const s=n[i];let o=BigInt(oA[s]);o*=t,e+=o,t*=r}return e}ci.s_to_big_int=a3;function cA(n){if(n===0)return kc[0];const e=[];for(;n!==0;){const t=n%qf,r=kc[t];e.push(r),n-=t,n/=qf}return e.reverse().join("")}ci.int_to_s=cA;function c3(n){const e=BigInt(0),t=BigInt(qf);if(n===e)return kc[0];const r=[];for(;n!==e;){const i=n%t,s=kc[Number(i)];r.push(s),n/=t}return r.reverse().join("")}ci.big_int_to_s=c3;function l3(n){return n.split("").reverse().join("")}function u3(n){if(n<0)return"-"+u3(-n);let[e,t]=n.toString().split(".");if(!t)return cA(n);let r;t&&([t,r]=t.split("e")),e=u_(e),t=l3(t),t=u_(t);let i=e+"."+t;if(r){switch(i+=".",r[0]){case"+":r=r.slice(1);break;case"-":i+="-",r=r.slice(1);break}r=u_(r),i+=r}return i}ci.num_to_s=u3;function u_(n){const e=+n;return e.toString()===n&&e+1!==e&&e-1!==e?cA(e):":"+c3(BigInt(n))}ci.int_str_to_s=u_;function u1(n){return n[0]===":"?a3(n.substring(1)).toString():aA(n).toString()}function h3(n){if(n[0]==="-")return-h3(n.substr(1));let[e,t,r]=n.split(".");if(!t)return aA(e);e=u1(e),t=u1(t),t=l3(t);let i=e+"."+t;if(r){i+="e";let s=!1;r[0]==="-"&&(s=!0,r=r.slice(1)),r=u1(r),i+=s?-r:+r}return+i}ci.s_to_num=h3;Object.defineProperty(ai,"__esModule",{value:!0});ai.decodeStr=ai.encodeStr=ai.decodeBool=ai.encodeBool=ai.decodeKey=ai.decodeNum=ai.encodeNum=void 0;const lA=ci;function ple(n){return"n|"+(0,lA.num_to_s)(n)}ai.encodeNum=ple;function mle(n){return n=n.replace("n|",""),(0,lA.s_to_num)(n)}ai.decodeNum=mle;function gle(n){return typeof n=="number"?n:(0,lA.s_to_int)(n)}ai.decodeKey=gle;function _le(n){return n?"b|T":"b|F"}ai.encodeBool=_le;function vle(n){switch(n){case"b|T":return!0;case"b|F":return!1}return!!n}ai.decodeBool=vle;function yle(n){switch(n[0]+n[1]){case"b|":case"o|":case"n|":case"a|":case"s|":n="s|"+n}return n}ai.encodeStr=yle;function xle(n){return n[0]+n[1]==="s|"?n.substr(2):n}ai.decodeStr=xle;var Cs={},Am={};Object.defineProperty(Am,"__esModule",{value:!0});Am.config=void 0;Am.config={sort_key:!1,error_on_nan:!1,error_on_infinite:!1};Object.defineProperty(Cs,"__esModule",{value:!0});Cs.addValue=Cs.makeInMemoryMemory=Cs.makeInMemoryCache=Cs.makeInMemoryStore=Cs.memToValues=void 0;const gw=Am,h1=xc,f1=ai,Sle=ci;function Ele(n){return n.store.toArray()}Cs.memToValues=Ele;function f3(){const n=[];return{forEach(e){for(let t=0;t(yw(),this?this.unpack(e,t):Pp.prototype.unpack.call(bI,e,t)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof t=="object"?(Zs=t.end||e.length,ue=t.start||0):(ue=0,Zs=t>-1?t:e.length),fa=0,vl=null,ei=null,We=e;try{en=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw We=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof Pp){if(Ln=this,this.structures)return on=this.structures,A0(t);(!on||on.length>0)&&(on=[])}else Ln=bI,(!on||on.length>0)&&(on=[]);return A0(t)}unpackMultiple(e,t){let r,i=0;try{wl=!0;let s=e.length,o=this?this.unpack(e,s):Ny.unpack(e,s);if(t){if(t(o,i,ue)===!1)return;for(;uer.slice(0)));for(let r=0,i=e.length;r=32&&(s.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in t||[])if(r>=0){let i=e[r],s=t[r];s&&(i&&((e.restoreStructures||(e.restoreStructures=[]))[r]=i),e[r]=s)}return this.structures=e}decode(e,t){return this.unpack(e,t)}}function A0(n){try{if(!Ln.trusted&&!wl){let t=on.sharedLength||0;t=32&&AI?(e=AI(We,ue,Zs,Ln),We=null,!(n&&n.lazy)&&e&&(e=e.toJSON()),ue=Zs):e=mr(),ei&&(ue=ei.postBundlePosition,ei=null),wl&&(on.restoreStructures=null),ue==Zs)on&&on.restoreStructures&&MI(),on=null,We=null,Sc&&(Sc=null);else{if(ue>Zs)throw new Error("Unexpected end of MessagePack data");if(!wl){let t;try{t=JSON.stringify(e,(r,i)=>typeof i=="bigint"?`${i}n`:i).slice(0,100)}catch(r){t="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+t)}}return e}catch(e){throw on&&on.restoreStructures&&MI(),yw(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||ue>Zs)&&(e.incomplete=!0),e}}function MI(){for(let n in on.restoreStructures)on[n]=on.restoreStructures[n];on.restoreStructures=null}function mr(){let n=We[ue++];if(n<160)if(n<128){if(n<64)return n;{let e=on[n&63]||Ln.getStructures&&v3()[n&63];return e?(e.read||(e.read=uA(e,n&63)),e.read()):n}}else if(n<144)if(n-=128,Ln.mapsAsObjects){let e={};for(let t=0;t=ue)return vl.slice(ue-$s,(ue+=e)-$s);if(fa==0&&Zs<140){let t=e<16?hA(e):y3(e);if(t!=null)return t}return vw(e)}else{let e;switch(n){case 192:return null;case 193:return ei?(e=mr(),e>0?ei[1].slice(ei.position1,ei.position1+=e):ei[0].slice(ei.position0,ei.position0-=e)):g3;case 194:return!1;case 195:return!0;case 196:if(e=We[ue++],e===void 0)throw new Error("Unexpected end of buffer");return p1(e);case 197:return e=en.getUint16(ue),ue+=2,p1(e);case 198:return e=en.getUint32(ue),ue+=4,p1(e);case 199:return fu(We[ue++]);case 200:return e=en.getUint16(ue),ue+=2,fu(e);case 201:return e=en.getUint32(ue),ue+=4,fu(e);case 202:if(e=en.getFloat32(ue),Ln.useFloat32>2){let t=fA[(We[ue]&127)<<1|We[ue+1]>>7];return ue+=4,(t*e+(e>0?.5:-.5)>>0)/t}return ue+=4,e;case 203:return e=en.getFloat64(ue),ue+=8,e;case 204:return We[ue++];case 205:return e=en.getUint16(ue),ue+=2,e;case 206:return e=en.getUint32(ue),ue+=4,e;case 207:return Ln.int64AsType==="number"?(e=en.getUint32(ue)*4294967296,e+=en.getUint32(ue+4)):Ln.int64AsType==="string"?e=en.getBigUint64(ue).toString():Ln.int64AsType==="auto"?(e=en.getBigUint64(ue),e<=BigInt(2)<=BigInt(-2)<=ue?vl.slice(ue-$s,(ue+=e)-$s):Ole(e);case 218:return e=en.getUint16(ue),ue+=2,fa>=ue?vl.slice(ue-$s,(ue+=e)-$s):Lle(e);case 219:return e=en.getUint32(ue),ue+=4,fa>=ue?vl.slice(ue-$s,(ue+=e)-$s):Ple(e);case 220:return e=en.getUint16(ue),ue+=2,RI(e);case 221:return e=en.getUint32(ue),ue+=4,RI(e);case 222:return e=en.getUint16(ue),ue+=2,kI(e);case 223:return e=en.getUint32(ue),ue+=4,kI(e);default:if(n>=224)return n-256;if(n===void 0){let t=new Error("Unexpected end of MessagePack data");throw t.incomplete=!0,t}throw new Error("Unknown MessagePack token "+n)}}}const Nle=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function uA(n,e){function t(){if(t.count++>_3){let i=n.read=new Function("r","return function(){return "+(Ln.freezeData?"Object.freeze":"")+"({"+n.map(s=>s==="__proto__"?"__proto_:r()":Nle.test(s)?s+":r()":"["+JSON.stringify(s)+"]:r()").join(",")+"})}")(mr);return n.highByte===0&&(n.read=CI(e,n.read)),i()}let r={};for(let i=0,s=n.length;ifunction(){let t=We[ue++];if(t===0)return e();let r=n<32?-(n+(t<<5)):n+(t<<5),i=on[r]||v3()[r];if(!i)throw new Error("Record id is not defined for "+r);return i.read||(i.read=uA(i,n)),i.read()};function v3(){let n=w3(()=>(We=null,Ln.getStructures()));return on=Ln._mergeStructures(n,on)}var vw=Mm,Ole=Mm,Lle=Mm,Ple=Mm;function Mm(n){let e;if(n<16&&(e=hA(n)))return e;if(n>64&&_w)return _w.decode(We.subarray(ue,ue+=n));const t=ue+n,r=[];for(e="";ue65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c)}else r.push(i);r.length>=4096&&(e+=Qr.apply(String,r),r.length=0)}return r.length>0&&(e+=Qr.apply(String,r)),e}function RI(n){let e=new Array(n);for(let t=0;t0){ue=e;return}t[r]=i}return Qr.apply(String,t)}function hA(n){if(n<4)if(n<2){if(n===0)return"";{let e=We[ue++];if((e&128)>1){ue-=1;return}return Qr(e)}}else{let e=We[ue++],t=We[ue++];if((e&128)>0||(t&128)>0){ue-=2;return}if(n<3)return Qr(e,t);let r=We[ue++];if((r&128)>0){ue-=3;return}return Qr(e,t,r)}else{let e=We[ue++],t=We[ue++],r=We[ue++],i=We[ue++];if((e&128)>0||(t&128)>0||(r&128)>0||(i&128)>0){ue-=4;return}if(n<6){if(n===4)return Qr(e,t,r,i);{let s=We[ue++];if((s&128)>0){ue-=5;return}return Qr(e,t,r,i,s)}}else if(n<8){let s=We[ue++],o=We[ue++];if((s&128)>0||(o&128)>0){ue-=6;return}if(n<7)return Qr(e,t,r,i,s,o);let a=We[ue++];if((a&128)>0){ue-=7;return}return Qr(e,t,r,i,s,o,a)}else{let s=We[ue++],o=We[ue++],a=We[ue++],c=We[ue++];if((s&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){ue-=8;return}if(n<10){if(n===8)return Qr(e,t,r,i,s,o,a,c);{let l=We[ue++];if((l&128)>0){ue-=9;return}return Qr(e,t,r,i,s,o,a,c,l)}}else if(n<12){let l=We[ue++],u=We[ue++];if((l&128)>0||(u&128)>0){ue-=10;return}if(n<11)return Qr(e,t,r,i,s,o,a,c,l,u);let h=We[ue++];if((h&128)>0){ue-=11;return}return Qr(e,t,r,i,s,o,a,c,l,u,h)}else{let l=We[ue++],u=We[ue++],h=We[ue++],p=We[ue++];if((l&128)>0||(u&128)>0||(h&128)>0||(p&128)>0){ue-=12;return}if(n<14){if(n===12)return Qr(e,t,r,i,s,o,a,c,l,u,h,p);{let m=We[ue++];if((m&128)>0){ue-=13;return}return Qr(e,t,r,i,s,o,a,c,l,u,h,p,m)}}else{let m=We[ue++],g=We[ue++];if((m&128)>0||(g&128)>0){ue-=14;return}if(n<15)return Qr(e,t,r,i,s,o,a,c,l,u,h,p,m,g);let v=We[ue++];if((v&128)>0){ue-=15;return}return Qr(e,t,r,i,s,o,a,c,l,u,h,p,m,g,v)}}}}}function II(){let n=We[ue++],e;if(n<192)e=n-160;else switch(n){case 217:e=We[ue++];break;case 218:e=en.getUint16(ue),ue+=2;break;case 219:e=en.getUint32(ue),ue+=4;break;default:throw new Error("Expected string")}return Mm(e)}function p1(n){return Ln.copyBuffers?Uint8Array.prototype.slice.call(We,ue,ue+=n):We.subarray(ue,ue+=n)}function fu(n){let e=We[ue++];if(gs[e]){let t;return gs[e](We.subarray(ue,t=ue+=n),r=>{ue=r;try{return mr()}finally{ue=t}})}else throw new Error("Unknown extension type "+e)}var NI=new Array(4096);function x3(){let n=We[ue++];if(n>=160&&n<192){if(n=n-160,fa>=ue)return vl.slice(ue-$s,(ue+=n)-$s);if(!(fa==0&&Zs<180))return vw(n)}else return ue--,S3(mr());let e=(n<<5^(n>1?en.getUint16(ue):n>0?We[ue]:0))&4095,t=NI[e],r=ue,i=ue+n-3,s,o=0;if(t&&t.bytes==n){for(;r{let t=mr().map(S3),r=n;e!==void 0&&(n=n<32?-((e<<5)+n):(e<<5)+n,t.highByte=e);let i=on[n];return i&&(i.isShared||wl)&&((on.restoreStructures||(on.restoreStructures=[]))[n]=i),on[n]=t,t.read=uA(t,r),t.read()};gs[0]=()=>{};gs[0].noBuffer=!0;gs[66]=n=>{let e=n.length,t=BigInt(n[0]&128?n[0]-256:n[0]);for(let r=1;r{let n=mr();return(Dle[n[0]]||Error)(n[1],{cause:n[2]})};gs[105]=n=>{if(Ln.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=en.getUint32(ue-4);Sc||(Sc=new Map);let t=We[ue],r;t>=144&&t<160||t==220||t==221?r=[]:r={};let i={target:r};Sc.set(e,i);let s=mr();return i.used?Object.assign(r,s):(i.target=s,s)};gs[112]=n=>{if(Ln.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=en.getUint32(ue-4),t=Sc.get(e);return t.used=!0,t.target};gs[115]=()=>new Set(mr());const E3=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(n=>n+"Array");let Ule=typeof globalThis=="object"?globalThis:window;gs[116]=n=>{let e=n[0],t=E3[e];if(!t){if(e===16){let r=new ArrayBuffer(n.length-1);return new Uint8Array(r).set(n.subarray(1)),r}throw new Error("Could not find typed array for code "+e)}return new Ule[t](Uint8Array.prototype.slice.call(n,1).buffer)};gs[120]=()=>{let n=mr();return new RegExp(n[0],n[1])};const Fle=[];gs[98]=n=>{let e=(n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3],t=ue;return ue+=e-n.length,ei=Fle,ei=[II(),II()],ei.position0=0,ei.position1=0,ei.postBundlePosition=ue,ue=t,mr()};gs[255]=n=>n.length==4?new Date((n[0]*16777216+(n[1]<<16)+(n[2]<<8)+n[3])*1e3):n.length==8?new Date(((n[0]<<22)+(n[1]<<14)+(n[2]<<6)+(n[3]>>2))/1e6+((n[3]&3)*4294967296+n[4]*16777216+(n[5]<<16)+(n[6]<<8)+n[7])*1e3):n.length==12?new Date(((n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3])/1e6+((n[4]&128?-281474976710656:0)+n[6]*1099511627776+n[7]*4294967296+n[8]*16777216+(n[9]<<16)+(n[10]<<8)+n[11])*1e3):new Date("invalid");function w3(n){let e=Zs,t=ue,r=$s,i=fa,s=vl,o=Sc,a=ei,c=new Uint8Array(We.slice(0,Zs)),l=on,u=on.slice(0,on.length),h=Ln,p=wl,m=n();return Zs=e,ue=t,$s=r,fa=i,vl=s,Sc=o,ei=a,We=c,wl=p,on=l,on.splice(0,on.length,...u),Ln=h,en=new DataView(We.buffer,We.byteOffset,We.byteLength),m}function yw(){We=null,Sc=null,on=null}const fA=new Array(147);for(let n=0;n<256;n++)fA[n]=+("1e"+Math.floor(45.15-n*.30103));var Ny=new Pp({useRecords:!1});Ny.unpack;Ny.unpackMultiple;Ny.unpack;let Ble=new Float32Array(1);new Uint8Array(Ble.buffer,0,4);let h_;try{h_=new TextEncoder}catch{}let xw,T3;const Oy=typeof Buffer<"u",M0=Oy?function(n){return Buffer.allocUnsafeSlow(n)}:Uint8Array,b3=Oy?Buffer:Uint8Array,LI=Oy?4294967296:2144337920;let ye,Hd,In,pe=0,Ci,Zn=null,zle;const Vle=21760,Hle=/[\u0080-\uFFFF]/,jh=Symbol("record-id");class Gle extends Pp{constructor(e){super(e),this.offset=0;let t,r,i,s,o=b3.prototype.utf8Write?function(P,b){return ye.utf8Write(P,b,ye.byteLength-b)}:h_&&h_.encodeInto?function(P,b){return h_.encodeInto(P,ye.subarray(b)).written}:!1,a=this;e||(e={});let c=e&&e.sequential,l=e.structures||e.saveStructures,u=e.maxSharedStructures;if(u==null&&(u=l?32:0),u>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let h=e.maxOwnStructures;h==null&&(h=l?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let p=u>32||h+u>64,m=u+64,g=u+h+64;if(g>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let v=[],y=0,_=0;this.pack=this.encode=function(P,b){if(ye||(ye=new M0(8192),In=ye.dataView||(ye.dataView=new DataView(ye.buffer,0,8192)),pe=0),Ci=ye.length-10,Ci-pe<2048?(ye=new M0(ye.length),In=ye.dataView||(ye.dataView=new DataView(ye.buffer,0,ye.length)),Ci=ye.length-10,pe=0):pe=pe+7&2147483640,t=pe,b&Kle&&(pe+=b&255),s=a.structuredClone?new Map:null,a.bundleStrings&&typeof P!="string"?(Zn=[],Zn.size=1/0):Zn=null,i=a.structures,i){i.uninitialized&&(i=a._mergeStructures(a.getStructures()));let W=i.sharedLength||0;if(W>u)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let V=0;VX.offset>Y.offset?1:-1),G=V.length,$=-1;for(;W&&G>0;){let X=V[--G].offset+t;XW.position+t?$>=0&&($+=6):($>=0&&(In.setUint32(W.position+t,In.getUint32(W.position+t)+$),$=-1),W=W.previous,G++)}$>=0&&W&&In.setUint32(W.position+t,In.getUint32(W.position+t)+$),pe+=V.length*6,pe>Ci&&M(pe),a.offset=pe;let Z=jle(ye.subarray(t,pe),V);return s=null,Z}return a.offset=pe,b&qle?(ye.start=t,ye.end=pe,ye):ye.subarray(t,pe)}catch(W){throw B=W,W}finally{if(i&&(S(),r&&a.saveStructures)){let W=i.sharedLength||0,V=ye.subarray(t,pe),G=$le(i,a);if(!B)return a.saveStructures(G,G.isCompatible)===!1?a.pack(P,b):(a.lastNamedStructuresLength=W,ye.length>1073741824&&(ye=null),V)}ye.length>1073741824&&(ye=null),b&Xle&&(pe=t)}};const S=()=>{_<10&&_++;let P=i.sharedLength||0;if(i.length>P&&!c&&(i.length=P),y>1e4)i.transitions=null,_=0,y=0,v.length>0&&(v=[]);else if(v.length>0&&!c){for(let b=0,B=v.length;b{var b=P.length;b<16?ye[pe++]=144|b:b<65536?(ye[pe++]=220,ye[pe++]=b>>8,ye[pe++]=b&255):(ye[pe++]=221,In.setUint32(pe,b),pe+=4);for(let B=0;B{pe>Ci&&(ye=M(pe));var b=typeof P,B;if(b==="string"){let W=P.length;if(Zn&&W>=4&&W<4096){if((Zn.size+=W)>Vle){let Z,X=(Zn[0]?Zn[0].length*3+Zn[1].length:0)+10;pe+X>Ci&&(ye=M(pe+X));let Y;Zn.position?(Y=Zn,ye[pe]=200,pe+=3,ye[pe++]=98,Z=pe-t,pe+=4,UI(t,T,0),In.setUint16(Z+t-3,pe-t-Z)):(ye[pe++]=214,ye[pe++]=98,Z=pe-t,pe+=4),Zn=["",""],Zn.previous=Y,Zn.size=0,Zn.position=Z}let $=Hle.test(P);Zn[$?0:1]+=P,ye[pe++]=193,T($?-W:W);return}let V;W<32?V=1:W<256?V=2:W<65536?V=3:V=5;let G=W*3;if(pe+G>Ci&&(ye=M(pe+G)),W<64||!o){let $,Z,X,Y=pe+V;for($=0;$>6|192,ye[Y++]=Z&63|128):(Z&64512)===55296&&((X=P.charCodeAt($+1))&64512)===56320?(Z=65536+((Z&1023)<<10)+(X&1023),$++,ye[Y++]=Z>>18|240,ye[Y++]=Z>>12&63|128,ye[Y++]=Z>>6&63|128,ye[Y++]=Z&63|128):(ye[Y++]=Z>>12|224,ye[Y++]=Z>>6&63|128,ye[Y++]=Z&63|128);B=Y-pe-V}else B=o(P,pe+V);B<32?ye[pe++]=160|B:B<256?(V<2&&ye.copyWithin(pe+2,pe+1,pe+1+B),ye[pe++]=217,ye[pe++]=B):B<65536?(V<3&&ye.copyWithin(pe+3,pe+2,pe+2+B),ye[pe++]=218,ye[pe++]=B>>8,ye[pe++]=B&255):(V<5&&ye.copyWithin(pe+5,pe+3,pe+3+B),ye[pe++]=219,In.setUint32(pe,B),pe+=4),pe+=B}else if(b==="number")if(P>>>0===P)P<32||P<128&&this.useRecords===!1||P<64&&!this.randomAccessStructure?ye[pe++]=P:P<256?(ye[pe++]=204,ye[pe++]=P):P<65536?(ye[pe++]=205,ye[pe++]=P>>8,ye[pe++]=P&255):(ye[pe++]=206,In.setUint32(pe,P),pe+=4);else if(P>>0===P)P>=-32?ye[pe++]=256+P:P>=-128?(ye[pe++]=208,ye[pe++]=P+256):P>=-32768?(ye[pe++]=209,In.setInt16(pe,P),pe+=2):(ye[pe++]=210,In.setInt32(pe,P),pe+=4);else{let W;if((W=this.useFloat32)>0&&P<4294967296&&P>=-2147483648){ye[pe++]=202,In.setFloat32(pe,P);let V;if(W<4||(V=P*fA[(ye[pe]&127)<<1|ye[pe+1]>>7])>>0===V){pe+=4;return}else pe--}ye[pe++]=203,In.setFloat64(pe,P),pe+=8}else if(b==="object"||b==="function")if(!P)ye[pe++]=192;else{if(s){let V=s.get(P);if(V){if(!V.id){let G=s.idsToInsert||(s.idsToInsert=[]);V.id=G.push(V)}ye[pe++]=214,ye[pe++]=112,In.setUint32(pe,V.id),pe+=4;return}else s.set(P,{offset:pe-t})}let W=P.constructor;if(W===Object)O(P);else if(W===Array)w(P);else if(W===Map)if(this.mapAsEmptyObject)ye[pe++]=128;else{B=P.size,B<16?ye[pe++]=128|B:B<65536?(ye[pe++]=222,ye[pe++]=B>>8,ye[pe++]=B&255):(ye[pe++]=223,In.setUint32(pe,B),pe+=4);for(let[V,G]of P)T(V),T(G)}else{for(let V=0,G=xw.length;V(ye=X,X=null,pe+=ie,pe>Ci&&M(pe),{target:ye,targetView:In,position:pe-ie}),T)}finally{X&&(ye=X,In=Y,pe=ve,Ci=ye.length-10)}ne&&(ne.length+pe>Ci&&M(ne.length+pe),pe=Wle(ne,ye,pe,Z.type));return}}if(Array.isArray(P))w(P);else{if(P.toJSON){const V=P.toJSON();if(V!==P)return T(V)}if(b==="function")return T(this.writeFunction&&this.writeFunction(P));O(P)}}}else if(b==="boolean")ye[pe++]=P?195:194;else if(b==="bigint"){if(P=-(BigInt(1)<0)ye[pe++]=207,In.setBigUint64(pe,P);else if(this.largeBigIntToFloat)ye[pe++]=203,In.setFloat64(pe,Number(P));else{if(this.largeBigIntToString)return T(P.toString());if(this.useBigIntExtension&&P-(BigInt(2)**BigInt(1023))){ye[pe++]=199,pe++,ye[pe++]=66;let W=[],V;do{let G=P&BigInt(255);V=(G&BigInt(128))===(P>=BigInt(8)}while(!((P===BigInt(0)||P===BigInt(-1))&&V));ye[pe-2]=W.length;for(let G=W.length;G>0;)ye[pe++]=Number(W[--G]);return}else throw new RangeError(P+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}pe+=8}else if(b==="undefined")this.encodeUndefinedAsNil?ye[pe++]=192:(ye[pe++]=212,ye[pe++]=0,ye[pe++]=0);else throw new Error("Unknown type: "+b)},k=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?P=>{let b;if(this.skipValues){b=[];for(let V in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(V))&&!this.skipValues.includes(P[V])&&b.push(V)}else b=Object.keys(P);let B=b.length;B<16?ye[pe++]=128|B:B<65536?(ye[pe++]=222,ye[pe++]=B>>8,ye[pe++]=B&255):(ye[pe++]=223,In.setUint32(pe,B),pe+=4);let W;if(this.coercibleKeyAsNumber)for(let V=0;V{ye[pe++]=222;let b=pe-t;pe+=2;let B=0;for(let W in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(W))&&(T(W),T(P[W]),B++);if(B>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');ye[b+++t]=B>>8,ye[b+t]=B&255},R=this.useRecords===!1?k:e.progressiveRecords&&!p?P=>{let b,B=i.transitions||(i.transitions=Object.create(null)),W=pe++-t,V;for(let G in P)if(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(G)){if(b=B[G],b)B=b;else{let $=Object.keys(P),Z=B;B=i.transitions;let X=0;for(let Y=0,ve=$.length;Y{let b,B=i.transitions||(i.transitions=Object.create(null)),W=0;for(let G in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(G))&&(b=B[G],b||(b=B[G]=Object.create(null),W++),B=b);let V=B[jh];V?V>=96&&p?(ye[pe++]=((V-=96)&31)+96,ye[pe++]=V>>5):ye[pe++]=V:N(B,B.__keys__||Object.keys(P),W);for(let G in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(G))&&T(P[G])},C=typeof this.useRecords=="function"&&this.useRecords,O=C?P=>{C(P)?R(P):k(P)}:R,M=P=>{let b;if(P>16777216){if(P-t>LI)throw new Error("Packed buffer would be larger than maximum buffer size");b=Math.min(LI,Math.round(Math.max((P-t)*(P>67108864?1.25:2),4194304)/4096)*4096)}else b=(Math.max(P-t<<2,ye.length-1)>>12)+1<<12;let B=new M0(b);return In=B.dataView||(B.dataView=new DataView(B.buffer,0,b)),P=Math.min(P,ye.length),ye.copy?ye.copy(B,0,t,P):B.set(ye.slice(t,P)),pe-=t,t=0,Ci=B.length-10,ye=B},N=(P,b,B)=>{let W=i.nextId;W||(W=64),W=g&&(W=m),i.nextId=W+1);let V=b.highByte=W>=96&&p?W-96>>5:-1;P[jh]=W,P.__keys__=b,i[W-64]=b,W=0?(ye[pe++]=(W&31)+96,ye[pe++]=V):ye[pe++]=W):(V>=0?(ye[pe++]=213,ye[pe++]=114,ye[pe++]=(W&31)+96,ye[pe++]=V):(ye[pe++]=212,ye[pe++]=114,ye[pe++]=W),B&&(y+=_*B),v.length>=h&&(v.shift()[jh]=0),v.push(P),T(b))},U=(P,b,B,W)=>{let V=ye,G=pe,$=Ci,Z=t;ye=Hd,pe=0,t=0,ye||(Hd=ye=new M0(8192)),Ci=ye.length-10,N(P,b,W),Hd=ye;let X=pe;if(ye=V,pe=G,Ci=$,t=Z,X>1){let Y=pe+X-1;Y>Ci&&M(Y);let ve=B+t;ye.copyWithin(ve+X,ve+1,pe),ye.set(Hd.slice(0,X),ve),pe=Y}else ye[B+t]=Hd[0]},L=P=>{let b=zle(P,ye,t,pe,i,M,(B,W,V)=>{if(V)return r=!0;pe=W;let G=ye;return T(B),S(),G!==ye?{position:pe,targetView:In,target:ye}:pe},this);if(b===0)return O(P);pe=b}}useBuffer(e){ye=e,ye.dataView||(ye.dataView=new DataView(ye.buffer,ye.byteOffset,ye.byteLength)),pe=0}set position(e){pe=e}get position(){return pe}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}}T3=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,m3];xw=[{pack(n,e,t){let r=n.getTime()/1e3;if((this.useTimestamp32||n.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:i,targetView:s,position:o}=e(6);i[o++]=214,i[o++]=255,s.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:i,targetView:s,position:o}=e(10);i[o++]=215,i[o++]=255,s.setUint32(o,n.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),s.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),t(this.onInvalidDate());let{target:i,targetView:s,position:o}=e(3);i[o++]=212,i[o++]=255,i[o++]=255}else{let{target:i,targetView:s,position:o}=e(15);i[o++]=199,i[o++]=12,i[o++]=255,s.setUint32(o,n.getMilliseconds()*1e6),s.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(n,e,t){if(this.setAsEmptyObject)return e(0),t({});let r=Array.from(n),{target:i,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(i[s++]=212,i[s++]=115,i[s++]=0),t(r)}},{pack(n,e,t){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),t([n.name,n.message,n.cause])}},{pack(n,e,t){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),t([n.source,n.flags])}},{pack(n,e){this.moreTypes?PI(n,16,e):DI(Oy?Buffer.from(n):new Uint8Array(n),e)}},{pack(n,e){let t=n.constructor;t!==b3&&this.moreTypes?PI(n,E3.indexOf(t.name),e):DI(n,e)}},{pack(n,e){let{target:t,position:r}=e(1);t[r]=193}}];function PI(n,e,t,r){let i=n.byteLength;if(i+1<256){var{target:s,position:o}=t(4+i);s[o++]=199,s[o++]=i+1}else if(i+1<65536){var{target:s,position:o}=t(5+i);s[o++]=200,s[o++]=i+1>>8,s[o++]=i+1&255}else{var{target:s,position:o,targetView:a}=t(7+i);s[o++]=201,a.setUint32(o,i+1),o+=4}s[o++]=116,s[o++]=e,n.buffer||(n=new Uint8Array(n)),s.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength),o)}function DI(n,e){let t=n.byteLength;var r,i;if(t<256){var{target:r,position:i}=e(t+2);r[i++]=196,r[i++]=t}else if(t<65536){var{target:r,position:i}=e(t+3);r[i++]=197,r[i++]=t>>8,r[i++]=t&255}else{var{target:r,position:i,targetView:s}=e(t+5);r[i++]=198,s.setUint32(i,t),i+=4}r.set(n,i)}function Wle(n,e,t,r){let i=n.length;switch(i){case 1:e[t++]=212;break;case 2:e[t++]=213;break;case 4:e[t++]=214;break;case 8:e[t++]=215;break;case 16:e[t++]=216;break;default:i<256?(e[t++]=199,e[t++]=i):i<65536?(e[t++]=200,e[t++]=i>>8,e[t++]=i&255):(e[t++]=201,e[t++]=i>>24,e[t++]=i>>16&255,e[t++]=i>>8&255,e[t++]=i&255)}return e[t++]=r,e.set(n,t),t+=i,t}function jle(n,e){let t,r=e.length*6,i=n.length-r;for(;t=e.pop();){let s=t.offset,o=t.id;n.copyWithin(s+r,s,i),r-=6;let a=s+r;n[a++]=214,n[a++]=105,n[a++]=o>>24,n[a++]=o>>16&255,n[a++]=o>>8&255,n[a++]=o&255,i=s}return n}function UI(n,e,t){if(Zn.length>0){In.setUint32(Zn.position+n,pe+t-Zn.position-n),Zn.stringsPosition=pe-n;let r=Zn;Zn=null,e(r[0]),e(r[1])}}function $le(n,e){return n.isCompatible=t=>{let r=!t||(e.lastNamedStructuresLength||0)===t.length;return r||e._mergeStructures(t),r},n}let A3=new Gle({useRecords:!1});A3.pack;A3.pack;const qle=512,Xle=1024,Kle=2048;function FI(){return{id:fr()}}function Yle(){return new Array(li*uh).map(()=>{})}function Zle(n=$G){const e={terrain:Yle(),objects:{},id:""};return n(e)}function dA(n){var e;return $t((n==null?void 0:n.name)??((e=n==null?void 0:n.kinddata)==null?void 0:e.name)??"object")}function Qle(n){var e;return(n==null?void 0:n.color)??((e=n==null?void 0:n.kinddata)==null?void 0:e.color)??wn.BLACK}function Jle(n){var e;return(n==null?void 0:n.bg)??((e=n==null?void 0:n.kinddata)==null?void 0:e.bg)??wn.BLACK}function cv(n,e){if(!K(n)||!ro(e))return;const{color:t,bg:r}=nfe(e);K(t)&&(n.color=t),K(r)&&(n.bg=r)}function eue(n,e){if(!K(n)||!K(e)||!K(e.x)||!K(e.y)||e.x<0||e.x>=li||e.y<0||e.y>=uh)return;const t={...e},r=e.x+e.y*li;return n.terrain[r]=t,e}function tue(n,e){if(!K(n)||!K(e))return;const t={...e,id:e.id??fr()};return n.objects[t.id]=t,t}function M3(n,e,t){return eue(n,{...e,kind:t})}function C3(n,e,t,r){return tue(n,{...e,id:void 0,kind:t})}function lv(n,e){if(n)return n.objects[e]}function Sw(n,e,t,r,i){if(!K(n)||!K(e))return{x:0,y:0};const s={x:e.x??0,y:e.y??0},o={x:e.lx??s.x,y:e.ly??s.y},a=Wh(o,s),c=li-1,l=uh-1;for(let u=0;u(n[n.CATEGORY=0]="CATEGORY",n[n.COLLISION=1]="COLLISION",n[n.COLOR=2]="COLOR",n[n.KIND=3]="KIND",n[n.DIR=4]="DIR",n[n.NUMBER=5]="NUMBER",n[n.STRING=6]="STRING",n[n.NUMBER_OR_STRING=7]="NUMBER_OR_STRING",n[n.MAYBE_CATEGORY=8]="MAYBE_CATEGORY",n[n.MAYBE_COLLISION=9]="MAYBE_COLLISION",n[n.MAYBE_COLOR=10]="MAYBE_COLOR",n[n.MAYBE_KIND=11]="MAYBE_KIND",n[n.MAYBE_DIR=12]="MAYBE_DIR",n[n.MAYBE_NUMBER=13]="MAYBE_NUMBER",n[n.MAYBE_STRING=14]="MAYBE_STRING",n[n.MAYBE_NUMBER_OR_STRING=15]="MAYBE_NUMBER_OR_STRING",n[n.ANY=16]="ANY",n))(Ne||{});function Zr(n,e){throw new Error(`Invalid arg, expected: ${n} but got ${JSON.stringify(e)}`)}function Ve(n,e,t){var o,a,c,l;const r=se.words;se.words=n;const i=[];let s=e;for(let u=0;u(zI(1,n,e),0)).command("synth",(n,e)=>{for(let t=1;t<=8;++t)na(t,e);return 0}).command("synth1",(n,e)=>(na(1,e),0)).command("synth2",(n,e)=>(na(2,e),0)).command("synth3",(n,e)=>(na(3,e),0)).command("synth4",(n,e)=>(na(4,e),0)).command("synth5",(n,e)=>(na(5,e),0)).command("synth6",(n,e)=>(na(6,e),0)).command("synth7",(n,e)=>(na(7,e),0)).command("synth8",(n,e)=>(na(8,e),0)).command("bgplay",(n,e)=>(zI(-1,n,e),0)).command("bgsynth",(n,e)=>(na(0,e),0)),pA=ly(32,126).map(n=>String.fromCharCode(n));function tn(n){return Ps({...n,name:`token_${n.name}`})}function uo(n,e=!1){return tn(e?{name:n,pattern:new RegExp(n.toLowerCase(),"i"),longer_alt:Gi,group:Br.SKIPPED}:{name:n,pattern:new RegExp(n.toLowerCase(),"i"),longer_alt:Gi})}const Dp=tn({name:"newline",line_breaks:!0,start_chars_hint:[` -`,"\r"],pattern:/\n|\r\n?/}),oue=tn({name:"whitespace",pattern:/ +/,group:Br.SKIPPED}),aue=tn({name:"whitespace",pattern:/\s+/,line_breaks:!0,group:Br.SKIPPED}),mA=tn({name:"stat",pattern:/@.*/,start_chars_hint:["@"]}),Jh=tn({name:"command",pattern:/#/,start_chars_hint:["#"]});let L3=!1;function cue(n,e,t){if(!L3)return null;const[r]=t.slice(-1);if(r&&r.tokenType!==Dp)return null;let i=e;for(;n[i]===" ";)i++;if("@#/?':!".includes(n[i]))return null;let s=e+1;for(;s"@#/?':!".includes(n)===!1)}),D3=tn({name:"comment",pattern:/'.*/,start_chars_hint:["'"]}),U3=tn({name:"label",pattern:/:[^;:\n]*/,start_chars_hint:[":"]}),F3=tn({name:"hyperlink",pattern:/!/,start_chars_hint:["!"]}),B3=tn({name:"hyperlinktext",pattern:/;[^;\n]*/,start_chars_hint:[";"]}),Gi=tn({name:"stringliteral",pattern:/[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/,start_chars_hint:pA}),z3=tn({name:"stringliteraldouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),V3=tn({name:"numberliteral",pattern:/-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?/}),H3=tn({name:"iseq",pattern:/=|is|eq|equal/,longer_alt:Gi}),G3=tn({name:"isnoteq",pattern:/!=|not ?eq|not ?equal/,longer_alt:Gi}),W3=tn({name:"islessthan",pattern:/<|below/,longer_alt:Gi}),j3=tn({name:"isgreaterthan",pattern:/>|above/,longer_alt:Gi}),$3=tn({name:"islessthanorequal",pattern:/<=|below ?or ?eq|below ?or ?equal/,longer_alt:Gi}),q3=tn({name:"isgreaterthanorequal",pattern:/>=|above ?or ?eq|above ?or ?equal/,longer_alt:Gi}),ww=tn({name:"or",pattern:/or/i,longer_alt:Gi}),Tw=tn({name:"not",pattern:/not/i,longer_alt:Gi}),bw=tn({name:"and",pattern:/and/i,longer_alt:Gi}),Aw=tn({name:"plus",pattern:/\+/}),Mw=tn({name:"minus",pattern:/-/}),X3=tn({name:"power",pattern:/\*\*/}),K3=tn({name:"multiply",pattern:/\*/}),Cw=tn({name:"divide",pattern:/\//}),Y3=tn({name:"moddivide",pattern:/%/}),Z3=tn({name:"floordivide",pattern:/%%/}),Q3=tn({name:"query",pattern:/\?/}),J3=tn({name:"lparen",pattern:/\(/,push_mode:"ignore_newlines"}),e4=tn({name:"rparen",pattern:/\)/,pop_mode:!0}),t4=tn({name:"command_play",pattern:/(play|bgplay) .*/,start_chars_hint:pA,longer_alt:Gi}),n4=uo("debugger"),Rw=uo("if"),d_=uo("do"),lue=uo("to",!0),kw=uo("done"),uue=uo("then",!0),Iw=uo("else"),r4=uo("while"),i4=uo("repeat"),s4=uo("waitfor"),o4=tn({name:"foreach",pattern:/foreach|for/,longer_alt:Gi}),a4=uo("break"),c4=uo("continue");function l4(n){return[...n,V3,H3,G3,$3,W3,q3,j3,ww,Tw,bw,Aw,Mw,X3,K3,Cw,Z3,Y3,Q3,J3,e4,z3,Gi]}const u4=l4([P3,mA,t4,Jh,D3,U3,F3,B3,Dp,oue,a4,c4,n4,kw,d_,Iw,o4,Rw,i4,uue,lue,s4,r4]),hue=new Br({defaultMode:"use_newlines",modes:{use_newlines:u4,ignore_newlines:l4([aue])}},{skipValidations:!ba,ensureOptimizations:ba});function h4(n){L3=!0;const e=hue.tokenize(n||` -`),[t]=(fn(e.tokens)?e.tokens:[]).slice(-1);return t&&t.tokenType.name!=="Newline"&&e.tokens.push(wm(Dp,` -`,t.startOffset,t.endOffset??NaN,t.startLine??NaN,t.endLine??NaN,t.startColumn??NaN,t.endColumn??NaN)),e}function f4(n,e=!0){const[t,...r]=n;switch($t(t)){default:return e?{type:dt.OBJECT,values:n}:{type:dt.CONST,values:n};case"loader":return{type:dt.LOADER,values:r};case"board":return{type:dt.BOARD,values:r};case"object":return{type:dt.OBJECT,values:r};case"terrain":return{type:dt.TERRAIN,values:r};case"charset":return{type:dt.CHARSET,values:r};case"palette":return{type:dt.PALETTE,values:r};case"rn":case"range":return{type:dt.RANGE,values:r};case"sl":case"select":return{type:dt.SELECT,values:r};case"nm":case"number":return{type:dt.NUMBER,values:r};case"tx":case"text":return{type:dt.TEXT,values:r};case"ln":case"link":return{type:dt.LINK,values:r};case"hk":case"hotkey":return{type:dt.HOTKEY,values:r};case"scroll":return{type:dt.SCROLL,values:r};case"copyit":return{type:dt.COPYIT,values:r}}}function Ks(n){switch(n){case dt.LOADER:return"loader";case dt.BOARD:return"board";case dt.OBJECT:return"object";case dt.TERRAIN:return"terrain";case dt.CHARSET:return"charset";case dt.PALETTE:return"palette";case dt.CONST:return"const";case dt.RANGE:return"range";case dt.SELECT:return"select";case dt.NUMBER:return"number";case dt.TEXT:return"text";case dt.LINK:return"link";case dt.HOTKEY:return"hotkey";case dt.SCROLL:return"scroll";case dt.COPYIT:return"copyit"}}function fue(n,e){return{id:fr(),code:n,...e}}function due(n){const e={...gA(n)};return Object.keys(e).forEach(t=>{switch(t){case"type":case"name":delete e[t];break}}),e}function gA(n){var r;if(!K(n))return{};if(K((r=n.stats)==null?void 0:r.type))return n.stats;n.stats={};const e=h4(n.code);let t=!0;for(let i=0;ii.id===e||t===pc(i))}function g4(n,e,t){if(!K(n))return;const r=$t(t);return n.pages.find(s=>_A(s)===e&&(s.id===t||r===pc(s)))}function pue(n,e){if(!K(n)||!K(e))return!1;const t=Cm(n,e.id);return K(t)?!1:(n.pages.push(e),!0)}function mue(n,e){const t=Cm(n,e);if(K(n)&&K(t)){const r=$t(e);return n.pages=n.pages.filter(i=>i.id!==e&&r!==pc(i)),t}}function Ic(n,e){if(K(e)&&K(e.kind))return K(e.kinddata)||(e.kinddata=K(e.id)?vA(n,e.kind):_4(n,e.kind)),e.kinddata}function gue(n,e){const t=Ic(n,e);return{char:(e==null?void 0:e.char)??(t==null?void 0:t.char)??1,color:(e==null?void 0:e.color)??(t==null?void 0:t.color)??wn.WHITE,bg:(e==null?void 0:e.bg)??(t==null?void 0:t.bg)??wn.ONBORROW}}function vA(n,e){const t=e??"",r=g4(n,vn.OBJECT,t);if(K(r)){const i=p4(r);return{...uT(i),name:t,code:r.code}}}function _4(n,e){const t=e??"",r=g4(n,vn.TERRAIN,t);if(K(r)){const i=p4(r);return{...uT(i),name:t,code:r.code}}}function _ue(n,e){return n?(n.flags[e]=n.flags[e]??{},n.flags[e]):{}}function vue(n,e){n&&delete n.flags[e]}function yue(n,e,t,r){const i=lv(e,(t==null?void 0:t.id)??"");if(!K(n)||!K(e)||!K(i)||!K(i.x)||!K(i.y)||!K(e.lookup)||r.x<0||r.x>=li||r.y<0||r.y>=uh||i.x-r.x===0&&i.y-r.y===0)return!0;const s=r.x+r.y*li,o=Ic(n,i),a=i.collision??(o==null?void 0:o.collision),c=lv(e,e.lookup[s]??"");if(K(c))return!0;const l=e.terrain[s];if(K(l)){const u=Ic(n,l),h=l.collision??(u==null?void 0:u.collision);if(r3(a,h))return!0}return!1}function xue(n,e,t,r){const i=lv(e,(t==null?void 0:t.id)??"");if(!K(n)||!K(e)||!K(i)||!K(i.x)||!K(i.y)||!K(e.lookup)||r.x<0||r.x>=li||r.y<0||r.y>=uh)return{kind:"edge",collision:Vn.ISSOLID,x:r.x,y:r.y};if(i.x-r.x===0&&i.y-r.y===0)return;const s=i.x+i.y*li,o=r.x+r.y*li,a=Ic(n,i),c=i.collision??(a==null?void 0:a.collision),l=lv(e,e.lookup[o]??"");if(K(l))return{...l};const u=e.terrain[o];if(K(u)){const h=Ic(n,u),p=u.collision??(h==null?void 0:h.collision);if(r3(c,p))return{...u,x:r.x,y:r.y}}i.x=r.x,i.y=r.y,K(i.removed)||(e.lookup[s]=void 0,e.lookup[o]=i.id??"")}function Kf(n,e){const t=Ic(n,e);return K(e==null?void 0:e.id)&&K(e.x)&&K(e.y)?$t(e.name??(t==null?void 0:t.name)??"object"):$t((e==null?void 0:e.name)??(t==null?void 0:t.name)??"terrain")}function Nw(n,e,t,r){if(!K(n)||!K(e)||!K(e.named)||!K(t))return;const i=Kf(n,t);e.named[i]||(e.named[i]=new Set),e.named[i].add((t==null?void 0:t.id)??r??"")}function Sue(n,e,t){if(!(!K(n)||!K(e)||!K(e.lookup)||!K(t==null?void 0:t.id))&&!K(t.removed)){const r=t.x??0,i=t.y??0;e.lookup[r+i*li]=t.id}}function Ow(n,e){if(!K(n)||!K(e)||K(e.lookup)&&K(e.named))return;const t=new Array(li*uh).fill(void 0),r={},i=Object.values(e.objects);for(let a=0;a=li&&(s=0,++o)}e.lookup=t,e.named=r}function yA(n,e,t){return Kf(n,e)!=="player"&&K(e)?(e.removed=t,!0):!1}function Ly(n,e,t){var r;if(K(n)&&K(e)&&K(t==null?void 0:t.id)){if(K(e.lookup)&&K(t.x)&&K(t.y)){const s=t.x+t.y*li;e.lookup[s]===t.id&&e.lookup.splice(s,1)}const i=Kf(n,t);K((r=e.named)==null?void 0:r[i])&&K(t.id)&&e.named[i].delete(t.id)}}function Eue(n,e,t,r){if(K(n)&&K(e)&&K(t)){const[i,s]=t,o=vA(n,i);if(K(o)&&K(o.name)){const a=C3(e,r,i);return cv(a,s),Nw(n,e,a),a}}}function Lw(n,e,t,r){if(K(n)&&K(e)&&K(t)){const[i,s]=t,o=_4(n,i);if(K(o)){const c=M3(e,r,i);cv(c,s);const l=r.x+r.y*li;return Nw(n,e,c,l),c}const a=vA(n,i);if(K(a)&&K(a.name)){const c=C3(e,r,i);return cv(c,s),Sue(n,e,c),Nw(n,e,c),c}}}function R0(n,e,t,r){const i=Kt(e)?e:e.id,s=Kt(e)?void 0:{x:e.x??0,y:e.y??0},o=Kt(t)?t:t.id,a=i??s;K(o)&&K(a)&&n.send(o,r,a)}function wue(n,e,t,r){K(t==null?void 0:t.id)?(t.headless=!0,Ly(n,e,t)):M3(e,r,"empty")}function HI(n,e,t,r,i){const s=xue(e,t,r,i);if(K(s)){R0(n,s,n.id(),"thud"),r.kind===Ar.PLAYER?R0(n,n.id(),s,"touch"):r.collision===Vn.ISBULLET?R0(n,n.id(),s,"shot"):R0(n,n.id(),s,"bump");const o=Ic(e,s);return(s.destructible??(o==null?void 0:o.destructible))&&wue(e,t,s,i),!1}return!0}function GI(n,e,t){if(!dc(se.element))return 0;const[r,i]=Ve(e,0,[Ne.DIR,Ne.MAYBE_KIND]),s=i??["bullet"],o=Eue(se.book,se.board,s,{x:se.element.x,y:se.element.y});if(K(o)){o.arg=t,o.collision=Vn.ISBULLET,o.stepx=r.x-se.element.x,o.stepy=r.y-se.element.y;const a=Ic(se.book,o),c=o.code??(a==null?void 0:a.code)??"";Zhe(se.book,se.board,o,c,1),o.x===se.element.x&&o.y===se.element.y?o.headless=!0:n.bucket(o.id)}return n.yield(),0}const Tue=$c().command("change",(n,e)=>{if(!K(se.book)||!K(se.board))return 0;const[t,r]=Ve(e,0,[Ne.KIND,Ne.KIND]);Ow(se.book,se.board);const i=av(t)??"",s=bm(se.board,i),o=i3(s,t),a=av(r),c=t3(r),l=n3(r);return o.forEach(u=>{if(Kf(se.book,u)===a)K(c)&&(u.color=c),K(l)&&(u.bg=l);else{if(K(u.id)&&(Ly(se.book,se.board,u),!yA(se.book,u,se.timestamp)))return;dc(u)&&Lw(se.book,se.board,r,u)}}),0}).command("put",(n,e)=>{if(!K(se.book)||!K(se.board))return 0;const[t,r]=Ve(e,0,[Ne.DIR,Ne.KIND]);return Ow(se.book,se.board),Lw(se.book,se.board,r,t),0}).command("shootwith",(n,e)=>{const[t,r]=Ve(e,0,[Ne.ANY]);return GI(n,e.slice(r),t)}).command("shoot",GI).command("throwstar",()=>0),bue=$c().command("send",(n,e)=>{const[t,r]=Ve(e,0,[Ne.STRING,Ne.ANY]);switch(t){case"helpmenu":lc("cli","H E L P"),rn("cli","#help controls","zss controls and inputs"),qn("cli","!helpcontrols;read help controls"),qn("cli",""),rn("cli","#help text","text formatting"),qn("cli","!helptext;read help text"),qn("cli",""),rn("cli","#help developer","developer commands"),qn("cli","!helpdeveloper;read help developer"),qn("cli",""),rn("cli","#help player","player settings"),qn("cli","!helpplayer;read help player"),ic("cli","keyboard input"),rn("cli","?","open console"),rn("cli","esc","close console"),rn("cli","tab","move console"),rn("cli","up / down arrow keys","navigate console items"),rn("cli","left / right arrow keys","change console items"),rn("cli","enter","interact with console items"),rn("cli","alt + arrow keys","skip words and console lines"),rn("cli",`${Eee} + up / down arrow keys`,"input history");break;case"helpcontrols":lc("cli","zss controls and inputs"),ic("cli","keyboard input"),rn("cli","arrow keys","move"),rn("cli","shift + arrow keys","shoot"),rn("cli","enter","ok / accept"),rn("cli","escape","cancel / close"),rn("cli","tab","menu / action"),ic("cli","mouse input"),un("cli","todo ???"),ic("cli","controller input"),rn("cli","left stick","move"),rn("cli","right stick","aim"),rn("cli","a","ok / accept"),rn("cli","b","cancel / close"),rn("cli","y","menu / action"),rn("cli","x","shoot"),rn("cli","triggers","shoot");break;case"helptext":lc("cli","text formatting"),ic("cli","typography"),un("cli","plain text"),un("cli","$centering text"),un("cli",'"\\"@quoted strings for special chars\\""'),un("cli","$$0-255 for ascii chars $159$176$240"),un("cli",`use color names like ${ws("red","$$red")} to change foreground color`),un("cli",`use color names like ${tk("ongreen","$$ongreen")} to change background color`),un("cli",`use clear ${tk("onclear","to change background to")} transparent`),ic("cli","hyperlinks"),un("cli",`${ws("white",'"!hotkey"')} message shortcut;${ws("gray","Label")}`),un("cli",`${ws("white",'"!range"')} flag [labelmin] [labelmax];${ws("gray","Input Label")}`),un("cli",`${ws("white",'"!select"')} flag ...list of values;${ws("gray","Input Label")}`),un("cli",`${ws("white",'"!number"')} flag [minvalue] [maxvalue];${ws("gray","Input Label")}`),un("cli",`${ws("white",'"!text"')} flag;${ws("gray","Input Label")}`),un("cli",`${ws("white",'"!copyit"')} flag;${ws("gray","Input Label")}`);break;case"helpdeveloper":lc("cli","developer commands"),rn("cli","#books","list books in memory"),rn("cli","#pages","list pages in opened book"),rn("cli","@[pagetype:]page name","create & edit a new codepage in the currently opened book"),rn("cli","#trash","list books and pages from open book you can delete"),rn("cli","#save","flush state to register");break;case"helpplayer":lc("cli","player settings"),un("cli","todo");break;default:eo("$2",`${t} ${r??""}`);break}return 0}).command("stat",(n,e)=>{let t;const[r,...i]=e.map(ti),s=i.join(" ");switch($t(r)){case Ks(dt.LOADER):t=mu(Ar.CONTENT,s,vn.LOADER);break;default:t=mu(Ar.CONTENT,[r,...i].join(" "),vn.OBJECT);break;case Ks(dt.BOARD):t=mu(Ar.CONTENT,s,vn.BOARD);break;case Ks(dt.OBJECT):t=mu(Ar.CONTENT,s,vn.OBJECT);break;case Ks(dt.TERRAIN):t=mu(Ar.CONTENT,s,vn.TERRAIN);break;case Ks(dt.CHARSET):t=mu(Ar.CONTENT,s,vn.CHARSET);break;case Ks(dt.PALETTE):t=mu(Ar.CONTENT,s,vn.PALETTE);break}return K(t)&&n.command("pageopen",t.id),0}).command("text",(n,e)=>{const t=e.map(ti).join(" ");return eo("$2",t),0}).command("hyperlink",(n,e)=>{const[t,...r]=e,i=ti(t),s=r.map(ti).join(" ");return eo("$2",`!${s};${i}`),0}).command("dev",()=>(Yh("cli"),fW("cli",se.player),0)).command("share",()=>(Yh("cli"),dW("cli",se.player),0)).command("bookcreate",(n,e)=>{const[t]=Ve(e,0,[Ne.MAYBE_STRING]),r=U4(t);return K(r)&&n.command("bookopen",r.id),0}).command("bookopen",(n,e)=>{const[t]=Ve(e,0,[Ne.STRING]),r=Yf(t);return K(r)?(un("cli",`opened [book] ${r.name}`),zw(Ar.MAIN,r.id),n.command("pages")):Pn("cli","bookopen",`book ${t} not found`,se.player),0}).command("booktrash",(n,e)=>{const[t]=Ve(e,0,[Ne.STRING]),r=np(Ar.MAIN),i=Yf(t);return K(i)&&(r===i&&zw(Ar.MAIN,""),Khe(t),un("cli",`trashed [book] ${i.name}`),Yh("cli"),n.command("pages")),0}).command("pageopen",(n,e)=>{const[t]=Ve(e,0,[Ne.STRING]),r=Ec(Ar.MAIN);if(!K(r))return 0;const i=Cm(r,t);if(K(i)){const s=pc(i),o=C0(i);un("cli",`opened [${o}] ${s}`),sD(NO(r.id,i.id),i.code);const a=C0(i);xW("cli",r.id,i.id,a,`${s} - ${r.name}`,se.player)}else Pn("cli","pageopen",`page ${t} not found`,se.player);return 0}).command("pagetrash",(n,e)=>{const[t]=Ve(e,0,[Ne.STRING]),r=Ec(Ar.MAIN),i=mue(r,t);if(K(t)){const s=pc(i),o=C0(i);un("cli",`trashed [${o}] ${s}`),Yh("cli"),n.command("pages")}return 0}).command("nodetrash",()=>(mW("cli"),un("cli","node id changed, refreshing page recommended"),0)).command("help",(n,e)=>{const t=e.map(ti).join(" ")||"menu";return n.command(`help${t}`),0}).command("books",()=>{ic("cli","books");const n=np(Ar.MAIN);rn("cli","main",`${(n==null?void 0:n.name)??"empty"} $GREEN${(n==null?void 0:n.id)??""}`);const e=np(Ar.CONTENT);rn("cli","content",`${(e==null?void 0:e.name)??"empty"} ${(e==null?void 0:e.id)??""}`),Cb("cli",7);const t=Bw();return t.length?t.forEach(r=>{qn("cli",`!bookopen ${r.id};${r.name}`)}):un("cli","no books found"),qn("cli","!bookcreate;create a new book"),0}).command("pages",()=>{ic("cli","pages");const n=Ec(Ar.MAIN);return K(n)&&(rn("cli","main",`${n.name} $GREEN${n.id}`),n.pages.length?n.pages.forEach(e=>{const t=pc(e),r=C0(e);qn("cli",`!pageopen ${e.id};[${r}] ${t}`)}):(qn("cli",""),un("cli","no pages found"),un("cli","use @ to create a page"),un("cli","@board name of board"),un("cli","@object name of object"),un("cli","@terrain name of terrain"),un("cli","You can omit the type and it will default to object"),un("cli","@object name of object"),un("cli","@name of object"))),0}).command("trash",()=>{ic("cli","$REDTRASH"),un("cli","books");const n=Bw();n.length&&(n.forEach(t=>{qn("cli",`!booktrash ${t.id};$REDTRASH ${t.name}`)}),qn("cli",""));const e=np(Ar.MAIN);return K(e)&&(un("cli",`pages in open ${e.name} book`),e.pages.forEach(t=>{const r=pc(t);qn("cli",`!pagetrash ${t.id};$REDTRASH ${r}`)}),qn("cli","")),0}).command("save",()=>(Yh("cli"),0)).command("nuke",()=>(pW("cli"),0));function Aue(n){const e=R3[n];if(K(e))return e;const t=N3[n];if(K(t))return t;const r=Uy[n];if(K(r))return r;const i=QU[n];if(K(i))return i}const Mue=$c({get(n,e){const t=Aue(e);return K(t)?[!0,t]:[!1,void 0]}}),Cue=new Set(["inputmove","inputalt","inputctrl","inputshift","inputok","inputcancel","inputmenu"]),WI=new Set(["player","pushable","collision","destructible","p1","p2","p3","cycle","stepx","stepy","sender","arg"]),Rue=["NORTH","SOUTH","WEST","EAST"];function kue(){const n=Up(se.player);if(fn(n.inputqueue)||(n.inputqueue=[],n.inputcurrent=0),mt(n.inputcurrent)&&n.inputcurrent>0)return;const[e]=n.inputqueue,[t=De.NONE,r=0]=e??[De.NONE,0];switch(n.inputmove=[],n.inputok=0,n.inputcancel=0,n.inputmenu=0,n.inputalt=r&uD?1:0,n.inputctrl=r&hD?1:0,n.inputshift=r&fD?1:0,t){case De.MOVE_UP:case De.MOVE_DOWN:case De.MOVE_LEFT:case De.MOVE_RIGHT:n.inputmove=[Rue[t-De.MOVE_UP]];break;case De.OK_BUTTON:n.inputok=1;break;case De.CANCEL_BUTTON:n.inputcancel=1;break;case De.MENU_BUTTON:n.inputmenu=1;break}n.inputcurrent=t,n.inputqueue=n.inputqueue.filter(i=>{const[s]=i;return s!==De.NONE&&s!==t})}const Iue=$c({get(n,e){var s;se.isplayer&&Cue.has(e)&&kue();const t=(s=se.element)==null?void 0:s[e];if(K(t)||WI.has(e))return[!0,t];const i=Up(se.player)[e];return[K(i),i]},set(n,e,t){var s;const r=(s=se.element)==null?void 0:s[e];if(K(r)||WI.has(e))return K(se.element)&&(se.element[e]=t),[!0,t];const i=Up(se.player);return i[e]=t,[!0,t]},everytick(n){var e,t;K((e=se.element)==null?void 0:e.x)&&K(se.element.y)&&K(se.element.stepx)&&K(se.element.stepy)&&HI(n,se.book,se.board,se.element,{x:se.element.x+se.element.stepx,y:se.element.y+se.element.stepy})===!1&&(se.element.stepx=0,se.element.stepy=0),(t=se.element)!=null&&t.headless&&n.command("die")}}).command("become",(n,e)=>{var i,s;const t={x:((i=se.element)==null?void 0:i.x)??0,y:((s=se.element)==null?void 0:s.y)??0},[r]=Ve(e,0,[Ne.KIND]);return Ow(se.book,se.board),Ly(se.book,se.board,se.element),yA(se.book,se.element,se.timestamp)&&Lw(se.book,se.board,r,t),n.endofprogram(),0}).command("bind",()=>0).command("char",(n,e)=>{const[t]=Ve(e,0,[Ne.NUMBER]);return K(se.element)&&(se.element.char=t),0}).command("color",(n,e)=>{const[t]=Ve(e,0,[Ne.COLOR]);return K(se.element)&&K(t)&&cv(se.element,t),0}).command("go",(n,e)=>{if(K(se.element)){const[t]=Ve(e,0,[Ne.DIR]);if(HI(n,se.book,se.board,se.element,t),n.yield(),se.element.x===t.x&&se.element.y===t.y)return 0}return 1}).command("try",(n,e)=>{const[,t]=Ve(e,0,[Ne.DIR]);return n.command("go",...e)&&t{if(!K(se.element))return 0;const[t]=Ve(e,0,[Ne.DIR]),r=se.element.x??0,i=se.element.y??0;return se.element.stepx=t.x-r,se.element.stepy=t.y-i,0}),Nue=$c().command("clear",(n,e)=>(e.forEach(t=>n.set(ti(t),0)),0)).command("set",(n,e)=>{const[t,r]=Ve(e,0,[Ne.STRING,Ne.ANY]);return n.set(t,r),0}).command("take",(n,e)=>{const[t,r,i]=Ve(e,0,[Ne.STRING,Ne.MAYBE_NUMBER]),s=n.get(t),o=r??1;if(!mt(s))return 1;const a=s-o;return a<0?(i{const[t,r,i]=Ve(e,0,[Ne.STRING,Ne.MAYBE_NUMBER]),s=n.get(t),o=mt(s)?s:0,a=r??1;if(!mt(a))return 0;const c=s===void 0?1:0;return c&&i0&&y<_.lastIndexOf(" ")?c.low.call(g):g})},sentence:function(m,g,v){return m=l.lower(m).replace(a.sentence,function(y,_,S){return _+c.up.call(S)}),g&&g.forEach(function(y){m=m.replace(new RegExp("\\b"+l.lower(y)+"\\b","g"),c.cap)}),v&&v.forEach(function(y){m=m.replace(new RegExp("(\\b"+l.lower(y)+"\\. +)(\\w)"),function(_,S,w){return S+c.low.call(w)})}),m}};u.squish=u.pascal,l.default=l;for(var h in u)l.type(h,u[h]);var p=typeof p=="function"?p:function(){};p(n.exports?n.exports=l:this.Case=l)}).call(Eo)})(v4);var Oue=v4.exports;const Lue=Nc(Oue),ml={};function Pue(n){return{player:n,layers:[],panels:[],reset:!0,focus:"scroll"}}function y4(n){n.text=[],Object.values(ml[n.id]??{}).forEach(e=>e==null?void 0:e()),ml[n.id]={}}function x4(n){const e=n.panels.find(t=>t.name===n.focus);if(!e){const t={id:fr(),name:n.focus,edge:yi.RIGHT,size:20,text:[]};return n.panels.push(t),n.reset=!1,t}return e}const Due=new Set(["hk","hotkey","rn","range","sl","select","nm","number","tx","text"]),Uue=new Set(["rn","range","sl","select","nm","number","tx","text"]),Fue=new Set(["tx","text"]),Bue={rn:1,range:1,sl:0,select:0,nm:0,number:0,tx:"",text:""},jI={};let zue=n=>{let e=jI[n];return K(e)||(jI[n]=e=Pue(n)),e};function Py(n){return zue(n)}function Vue(n,e,t){Object.values(ml).forEach(r=>{if(r[e]!==void 0){const i=ld(n.id(),e);mt(t)&&El(i,t),Kt(t)&&_J(i,t)}})}function Hue(n){let e="";const t=Py(n);return t.panels=t.panels.filter(r=>{if(r.edge===yi.SCROLL){const[i]=r.text;return Kt(i)&&r.text.length===1&&(e=i),r.text.length>1}return!0}),e}function m1(n,e,t,r,i){const s=Py(n),o=r,a=i??Lue.capital(e),c=s.panels.find(l=>l.name===a);if(c)s.reset=!0,s.focus=a,mt(o)&&(c.size=o);else switch(t){case yi.START:break;case yi.LEFT:case yi.RIGHT:case yi.TOP:case yi.BOTTOM:case yi.SCROLL:{const l={id:fr(),name:a,edge:t,size:o??OJ[t],text:[]};s.panels.push(l),s.focus=a;break}}}function Gue(n,e){const t=Py(n),r=x4(t);t.reset&&(t.reset=!1,y4(r)),r.text.push(e)}function Wue(n,e,t,r,i){const s=Py(n),o=x4(s);s.reset&&(s.reset=!1,y4(o));const a=$t(r),c=[e.id(),t,...Due.has(a)?[a]:["hyperlink",r],...i],l=c[2];if(Uue.has(l)){const u=`${c[3]??""}`;ml[o.id]=ml[o.id]??{};const h=e.get(u)??Bue[l];if(ml[o.id][u]===void 0){const p=ld(e.id(),u);mt(h)&&gJ(p,h),Kt(h)&&sD(p,h),Fue.has(l)?ml[o.id][u]=yJ(p,m=>{K(m)&&m!==e.get(u)&&e.set(u,m)}):ml[o.id][u]=vJ(p,m=>{K(m)&&m!==e.get(u)&&e.set(u,m)})}}o.text.push(c)}const jue=$c({get(){return[!1,void 0]},set(n,e,t){return Vue(n,e,t),[!1,void 0]},tick(){var e;const n=((e=se.element)==null?void 0:e.name)??"scroll";m1(se.player,"scroll",yi.SCROLL,void 0,n)},everytick(){const n=Hue(se.player);if(n&&K(se.element)){se.element.tickertext=n,se.element.tickertime=se.timestamp;const e=gue(se.book,se.element);eo(`$${wn[e.color]}$${e.char}`,n)}}}).command("send",(n,e)=>{var u,h;const[t,r]=Ve(e,0,[Ne.STRING,Ne.ANY]),[i,s]=t.split(":"),o=K(s)?i:"self",a=s??i;function c(p){p.forEach(m=>{K(m.id)&&n.send(m.id,a,r)})}const l=$t(o);switch(l){case"all":for(const p of Object.keys(((u=se.board)==null?void 0:u.objects)??{}))n.send(p,a,r);break;case"self":n.message({id:fr(),sender:n.id(),target:a,data:r});break;case"others":for(const p of Object.keys(((h=se.board)==null?void 0:h.objects)??{}))p!==n.id()&&n.send(p,a,r);break;default:{c(l1(se.board,[o]));const p=n.get(l);fn(p)?c(l1(se.board,p)):c(l1(se.board,[p]));break}}return 0}).command("stat",(n,e)=>{const t=f4(e.map(ti));switch(t.type){case dt.OBJECT:K(se.element)&&(se.element.name=t.values.join(" "));break}return 0}).command("text",(n,e)=>{const t=e.map(ti).join("");return Gue(se.player,t),0}).command("hyperlink",(n,e)=>{const[t,r,...i]=e,s=ti(t),o=ti(r);return Wue(se.player,n,s,o,i),0}).command("gadget",(n,e)=>{const[t]=Ve(e,0,[Ne.STRING]),r=NJ[$t(t)];if(r===yi.SCROLL){const[,i,s]=Ve(e,0,[Ne.STRING,Ne.MAYBE_STRING,Ne.MAYBE_NUMBER]);m1(se.player,t,r,s,i)}else{const[,i,s]=Ve(e,0,[Ne.STRING,Ne.MAYBE_NUMBER,Ne.MAYBE_STRING]);m1(se.player,t,r,i,s)}return 0}),$ue=$c().command("idle",n=>(n.yield(),0)).command("end",n=>(n.endofprogram(),0)).command("endwith",(n,e)=>{const[t]=Ve(e,0,[Ne.ANY]);return n.set("arg",t),n.command("end")}).command("lock",n=>(n.lock(n.id()),0)).command("restore",(n,e)=>(n.restore(ti(e[0])),0)).command("unlock",n=>(n.unlock(),0)).command("zap",(n,e)=>(n.zap(ti(e[0])),0)).command("cycle",(n,e)=>{if(K(se.element)){const[t]=Ve(e,0,[Ne.NUMBER]);se.element.cycle=Cn(Math.round(t),1,255)}return 0}).command("die",n=>{var e;return(e=se.element)!=null&&e.headless&&Ly(se.book,se.board,se.element),yA(se.book,se.element,se.timestamp),n.endofprogram(),0}).command("endgame",()=>(bW("element",se.player),0)).command("run",(n,e)=>{const[t]=Ve(e,0,[Ne.STRING]);return hv(t),0}).command("runwith",(n,e)=>{const[t,r]=Ve(e,0,[Ne.ANY,Ne.STRING]);return n.set("arg",t),hv(r),0});function $I(n,e){if(!K(n))return;const t=$t(e),r=t.endsWith("le");switch(t){case"float32":case"float32le":{const i=n.dataview.getFloat32(n.cursor,r);return n.cursor+=4,i}case"float64":case"float64le":{const i=n.dataview.getFloat64(n.cursor,r);return n.cursor+=8,i}case"int8":case"int8le":{const i=n.dataview.getInt8(n.cursor);return n.cursor+=1,i}case"int16":case"int16le":{const i=n.dataview.getInt16(n.cursor,r);return n.cursor+=2,i}case"int32":case"int32le":{const i=n.dataview.getInt32(n.cursor,r);return n.cursor+=4,i}case"int64":case"int64le":{const i=n.dataview.getBigInt64(n.cursor,r);return n.cursor+=8,i}case"uint8":case"uint8le":{const i=n.dataview.getUint8(n.cursor);return n.cursor+=1,i}case"uint16":case"uint16le":{const i=n.dataview.getUint16(n.cursor,r);return n.cursor+=2,i}case"uint32":case"uint32le":{const i=n.dataview.getUint32(n.cursor,r);return n.cursor+=4,i}case"uint64":case"uint64le":{const i=n.dataview.getBigUint64(n.cursor,r);return n.cursor+=8,i}}}const que=(n,e)=>{const t=B4(n.id());if(!K(t))return 0;const[r]=Ve(e,0,[Ne.STRING]),i=$t(r);switch(i){case"seek":{const[s]=Ve(e,1,[Ne.NUMBER]);t.cursor=s;break}case"float32":case"float32le":case"float64":case"float64le":case"int8":case"int8le":case"int16":case"int16le":case"int32":case"int32le":case"int64":case"int64le":case"uint8":case"uint8le":case"uint16":case"uint16le":case"uint32":case"uint32le":case"uint64":case"uint64le":{const[s]=Ve(e,1,[Ne.STRING]);n.set(s,$I(t,i));break}case"text":{const[s,o]=Ve(e,1,[Ne.STRING,Ne.STRING]),a=$I(t,s);if(mt(a)&&Kt(o)){const c=new Uint8Array(t.bytes.buffer,t.cursor,a),u=new TextDecoder("utf-8").decode(c);n.set(o,u),t.cursor+=a}break}}return 0},Xue=$c({get(n,e){const t=B4(n.id());if(K(t))switch($t(e)){case"filename":return[K(t.filename),t.filename];case"cursor":return[K(t.cursor),t.cursor]}return[!1,void 0]}}).command("send",(n,e)=>{const[t,r]=Ve(e,0,[Ne.STRING,Ne.ANY]);return n.message({id:fr(),sender:n.id(),target:t,data:r}),0}).command("stat",()=>0).command("text",(n,e)=>{const t=e.map(ti).join(" ");return eo("$2",t),0}).command("hyperlink",(n,e)=>{const[t,...r]=e,i=ti(t),s=r.map(ti).join(" ");return eo("$2",`!${s};${i}`),0}).command("load",(n,e)=>{const t=e.map(ti).join(" "),r=n.get(t)??t;return Ec(Ar.CONTENT,r),0}).command("reload",(n,e)=>{const t=e.map(ti).join(" "),r=n.get(t)??t,i=Ec(Ar.CONTENT,r);return i.pages=[],0}).command("bin",que);var xA=(n=>(n[n.ERROR=0]="ERROR",n[n.CLI=1]="CLI",n[n.LOADER=2]="LOADER",n[n.CODE_PAGE=3]="CODE_PAGE",n))(xA||{});const Kue={audio:sue,board:Tue,cli:bue,const:Mue,element:Iue,flags:Nue,gadget:jue,lifecycle:$ue,loader:Xue},g1=["const","flags","audio","board","lifecycle","element"],Yue={0:[],1:["cli",...g1],2:["loader",...g1],3:["gadget",...g1]},Zue={0:new Map,1:new Map,2:new Map,3:new Map};function Rm(n){return(Yue[n]??[]).map(t=>Kue[t]).filter(K)}function Que(n,e){const t=Zue[n];if(!t.has(e)){let r;const i=Rm(n);for(let s=0;s>>=T4,i>0&&(r|=ihe),t+=nhe.encode(r);while(i>0);return t};var km={};(function(n){function e(R,C,O){if(C in R)return R[C];if(arguments.length===3)return O;throw new Error('"'+C+'" is a required argument.')}n.getArg=e;const t=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(R){const C=R.match(t);return C?{scheme:C[1],auth:C[2],host:C[3],port:C[4],path:C[5]}:null}n.urlParse=i;function s(R){let C="";return R.scheme&&(C+=R.scheme+":"),C+="//",R.auth&&(C+=R.auth+"@"),R.host&&(C+=R.host),R.port&&(C+=":"+R.port),R.path&&(C+=R.path),C}n.urlGenerate=s;const o=32;function a(R){const C=[];return function(O){for(let N=0;No&&C.pop(),M}}const c=a(function(C){let O=C;const M=i(C);if(M){if(!M.path)return C;O=M.path}const N=n.isAbsolute(O),U=[];let L=0,P=0;for(;;)if(L=P,P=O.indexOf("/",L),P===-1){U.push(O.slice(L));break}else for(U.push(O.slice(L,P));P=0;P--){const B=U[P];B==="."?U.splice(P,1):B===".."?b++:b>0&&(B===""?(U.splice(P+1,b),b=0):(U.splice(P,2),b--))}return O=U.join("/"),O===""&&(O=N?"/":"."),M?(M.path=O,s(M)):O});n.normalize=c;function l(R,C){R===""&&(R="."),C===""&&(C=".");const O=i(C),M=i(R);if(M&&(R=M.path||"/"),O&&!O.scheme)return M&&(O.scheme=M.scheme),s(O);if(O||C.match(r))return C;if(M&&!M.host&&!M.path)return M.host=C,s(M);const N=C.charAt(0)==="/"?C:c(R.replace(/\/+$/,"")+"/"+C);return M?(M.path=N,s(M)):N}n.join=l,n.isAbsolute=function(R){return R.charAt(0)==="/"||t.test(R)};function u(R,C){R===""&&(R="."),R=R.replace(/\/$/,"");let O=0;for(;C.indexOf(R+"/")!==0;){const M=R.lastIndexOf("/");if(M<0||(R=R.slice(0,M),R.match(/^([^\/]+:\/)?\/*$/)))return C;++O}return Array(O+1).join("../")+C.substr(R.length+1)}n.relative=u;const h=function(){return!("__proto__"in Object.create(null))}();function p(R){return R}function m(R){return v(R)?"$"+R:R}n.toSetString=h?p:m;function g(R){return v(R)?R.slice(1):R}n.fromSetString=h?p:g;function v(R){if(!R)return!1;const C=R.length;if(C<9||R.charCodeAt(C-1)!==95||R.charCodeAt(C-2)!==95||R.charCodeAt(C-3)!==111||R.charCodeAt(C-4)!==116||R.charCodeAt(C-5)!==111||R.charCodeAt(C-6)!==114||R.charCodeAt(C-7)!==112||R.charCodeAt(C-8)!==95||R.charCodeAt(C-9)!==95)return!1;for(let O=C-10;O>=0;O--)if(R.charCodeAt(O)!==36)return!1;return!0}function y(R,C,O){let M=S(R.source,C.source);return M!==0||(M=R.originalLine-C.originalLine,M!==0)||(M=R.originalColumn-C.originalColumn,M!==0||O)||(M=R.generatedColumn-C.generatedColumn,M!==0)||(M=R.generatedLine-C.generatedLine,M!==0)?M:S(R.name,C.name)}n.compareByOriginalPositions=y;function _(R,C,O){let M=R.generatedLine-C.generatedLine;return M!==0||(M=R.generatedColumn-C.generatedColumn,M!==0||O)||(M=S(R.source,C.source),M!==0)||(M=R.originalLine-C.originalLine,M!==0)||(M=R.originalColumn-C.originalColumn,M!==0)?M:S(R.name,C.name)}n.compareByGeneratedPositionsDeflated=_;function S(R,C){return R===C?0:R===null?1:C===null?-1:R>C?1:-1}function w(R,C){let O=R.generatedLine-C.generatedLine;return O!==0||(O=R.generatedColumn-C.generatedColumn,O!==0)||(O=S(R.source,C.source),O!==0)||(O=R.originalLine-C.originalLine,O!==0)||(O=R.originalColumn-C.originalColumn,O!==0)?O:S(R.name,C.name)}n.compareByGeneratedPositionsInflated=w;function T(R){return JSON.parse(R.replace(/^\)]}'[^\n]*\n/,""))}n.parseSourceMapInput=T;function k(R,C,O){if(C=C||"",R&&(R[R.length-1]!=="/"&&C[0]!=="/"&&(R+="/"),C=R+C),O){const M=i(O);if(!M)throw new Error("sourceMapURL could not be parsed");if(M.path){const N=M.path.lastIndexOf("/");N>=0&&(M.path=M.path.substring(0,N+1))}C=l(s(M),C)}return c(C)}n.computeSourceURL=k})(km);var SA={};let ohe=class A4{constructor(){this._array=[],this._set=new Map}static fromArray(e,t){const r=new A4;for(let i=0,s=e.length;i=0)return t;throw new Error('"'+e+'" is not in the set.')}at(e){if(e>=0&&et||r==t&&s>=i||C4.compareByGeneratedPositionsInflated(n,e)<=0}let che=class{constructor(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}unsortedForEach(e,t){this._array.forEach(e,t)}add(e){ahe(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))}toArray(){return this._sorted||(this._array.sort(C4.compareByGeneratedPositionsInflated),this._sorted=!0),this._array}};M4.MappingList=che;const Gd=E4,wr=km,k0=SA.ArraySet,lhe=M4.MappingList;let R4=class k4{constructor(e){e||(e={}),this._file=wr.getArg(e,"file",null),this._sourceRoot=wr.getArg(e,"sourceRoot",null),this._skipValidation=wr.getArg(e,"skipValidation",!1),this._sources=new k0,this._names=new k0,this._mappings=new lhe,this._sourcesContents=null}static fromSourceMap(e){const t=e.sourceRoot,r=new k4({file:e.file,sourceRoot:t});return e.eachMapping(function(i){const s={generated:{line:i.generatedLine,column:i.generatedColumn}};i.source!=null&&(s.source=i.source,t!=null&&(s.source=wr.relative(t,s.source)),s.original={line:i.originalLine,column:i.originalColumn},i.name!=null&&(s.name=i.name)),r.addMapping(s)}),e.sources.forEach(function(i){let s=i;t!==null&&(s=wr.relative(t,i)),r._sources.has(s)||r._sources.add(s);const o=e.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r}addMapping(e){const t=wr.getArg(e,"generated"),r=wr.getArg(e,"original",null);let i=wr.getArg(e,"source",null),s=wr.getArg(e,"name",null);this._skipValidation||this._validateMapping(t,r,i,s),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:s})}setSourceContent(e,t){let r=e;this._sourceRoot!=null&&(r=wr.relative(this._sourceRoot,r)),t!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[wr.toSetString(r)]=t):this._sourcesContents&&(delete this._sourcesContents[wr.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))}applySourceMap(e,t,r){let i=t;if(t==null){if(e.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=e.file}const s=this._sourceRoot;s!=null&&(i=wr.relative(s,i));const o=this._mappings.toArray().length>0?new k0:this._sources,a=new k0;this._mappings.unsortedForEach(function(c){if(c.source===i&&c.originalLine!=null){const h=e.originalPositionFor({line:c.originalLine,column:c.originalColumn});h.source!=null&&(c.source=h.source,r!=null&&(c.source=wr.join(r,c.source)),s!=null&&(c.source=wr.relative(s,c.source)),c.originalLine=h.line,c.originalColumn=h.column,h.name!=null&&(c.name=h.name))}const l=c.source;l!=null&&!o.has(l)&&o.add(l);const u=c.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=o,this._names=a,e.sources.forEach(function(c){const l=e.sourceContentFor(c);l!=null&&(r!=null&&(c=wr.join(r,c)),s!=null&&(c=wr.relative(s,c)),this.setSourceContent(c,l))},this)}_validateMapping(e,t,r,i){if(t&&typeof t.line!="number"&&typeof t.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!t&&!r&&!i)){if(!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:t,name:i}))}}_serializeMappings(){let e=0,t=1,r=0,i=0,s=0,o=0,a="",c,l,u,h;const p=this._mappings.toArray();for(let m=0,g=p.length;m0){if(!wr.compareByGeneratedPositionsInflated(l,p[m-1]))continue;c+=","}c+=Gd.encode(l.generatedColumn-e),e=l.generatedColumn,l.source!=null&&(h=this._sources.indexOf(l.source),c+=Gd.encode(h-o),o=h,c+=Gd.encode(l.originalLine-1-i),i=l.originalLine-1,c+=Gd.encode(l.originalColumn-r),r=l.originalColumn,l.name!=null&&(u=this._names.indexOf(l.name),c+=Gd.encode(u-s),s=u)),a+=c}return a}_generateSourcesContent(e,t){return e.map(function(r){if(!this._sourcesContents)return null;t!=null&&(r=wr.relative(t,r));const i=wr.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)}toJSON(){const e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e}toString(){return JSON.stringify(this.toJSON())}};R4.prototype._version=3;S4.SourceMapGenerator=R4;var I4={};(function(n){n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2;function e(t,r,i,s,o,a){const c=Math.floor((r-t)/2)+t,l=o(i,s[c],!0);return l===0?c:l>0?r-c>1?e(c,r,i,s,o,a):a==n.LEAST_UPPER_BOUND?r1?e(t,c,i,s,o,a):a==n.LEAST_UPPER_BOUND?c:t<0?-1:t}n.search=function(r,i,s,o){if(i.length===0)return-1;let a=e(-1,i.length,r,i,s,o||n.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&s(i[a],i[a-1],!0)===0;)--a;return a}})(I4);var Jd={exports:{}};const uhe={},hhe=Object.freeze(Object.defineProperty({__proto__:null,default:uhe},Symbol.toStringTag,{value:"Module"})),KI=$F(hhe),fhe=(function(){return typeof window<"u"&&this===window}).call();if(fhe){let n=null;Jd.exports=function(){if(typeof n=="string")return fetch(n).then(t=>t.arrayBuffer());if(n instanceof ArrayBuffer)return Promise.resolve(n);throw new Error("You must provide the string URL or ArrayBuffer contents of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer")},Jd.exports.initialize=e=>n=e}else{const n=KI,e=KI;Jd.exports=function(){return new Promise((r,i)=>{const s=e.join(__dirname,"mappings.wasm");n.readFile(s,null,(o,a)=>{if(o){i(o);return}r(a.buffer)})})},Jd.exports.initialize=t=>{console.debug("SourceMapConsumer.initialize is a no-op when running in node.js")}}var N4=Jd.exports;const dhe=N4;function phe(){this.generatedLine=0,this.generatedColumn=0,this.lastGeneratedColumn=null,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}let Wd=null;var mhe=function(){if(Wd)return Wd;const e=[];return Wd=dhe().then(t=>WebAssembly.instantiate(t,{env:{mapping_callback(r,i,s,o,a,c,l,u,h,p){const m=new phe;m.generatedLine=r+1,m.generatedColumn=i,s&&(m.lastGeneratedColumn=o-1),a&&(m.source=c,m.originalLine=l+1,m.originalColumn=u,h&&(m.name=p)),e[e.length-1](m)},start_all_generated_locations_for(){console.time("all_generated_locations_for")},end_all_generated_locations_for(){console.timeEnd("all_generated_locations_for")},start_compute_column_spans(){console.time("compute_column_spans")},end_compute_column_spans(){console.timeEnd("compute_column_spans")},start_generated_location_for(){console.time("generated_location_for")},end_generated_location_for(){console.timeEnd("generated_location_for")},start_original_location_for(){console.time("original_location_for")},end_original_location_for(){console.timeEnd("original_location_for")},start_parse_mappings(){console.time("parse_mappings")},end_parse_mappings(){console.timeEnd("parse_mappings")},start_sort_by_generated_location(){console.time("sort_by_generated_location")},end_sort_by_generated_location(){console.timeEnd("sort_by_generated_location")},start_sort_by_original_location(){console.time("sort_by_original_location")},end_sort_by_original_location(){console.timeEnd("sort_by_original_location")}}})).then(t=>({exports:t.instance.exports,withMappingCallback:(r,i)=>{e.push(r);try{i()}finally{e.pop()}}})).then(null,t=>{throw Wd=null,t}),Wd};const _t=km,_1=I4,uv=SA.ArraySet,ghe=N4,_he=mhe,EA=Symbol("smcInternal");class dr{constructor(e,t){return e==EA?Promise.resolve(this):yhe(e,t)}static initialize(e){ghe.initialize(e["lib/mappings.wasm"])}static fromSourceMap(e,t){return xhe(e,t)}static async with(e,t,r){const i=await new dr(e,t);try{return await r(i)}finally{i.destroy()}}_parseMappings(e,t){throw new Error("Subclasses must implement _parseMappings")}eachMapping(e,t,r){throw new Error("Subclasses must implement eachMapping")}allGeneratedPositionsFor(e){throw new Error("Subclasses must implement allGeneratedPositionsFor")}destroy(){throw new Error("Subclasses must implement destroy")}}dr.prototype._version=3;dr.GENERATED_ORDER=1;dr.ORIGINAL_ORDER=2;dr.GREATEST_LOWER_BOUND=1;dr.LEAST_UPPER_BOUND=2;class Im extends dr{constructor(e,t){return super(EA).then(r=>{let i=e;typeof e=="string"&&(i=_t.parseSourceMapInput(e));const s=_t.getArg(i,"version");let o=_t.getArg(i,"sources");const a=_t.getArg(i,"names",[]);let c=_t.getArg(i,"sourceRoot",null);const l=_t.getArg(i,"sourcesContent",null),u=_t.getArg(i,"mappings"),h=_t.getArg(i,"file",null);if(s!=r._version)throw new Error("Unsupported version: "+s);return c&&(c=_t.normalize(c)),o=o.map(String).map(_t.normalize).map(function(p){return c&&_t.isAbsolute(c)&&_t.isAbsolute(p)?_t.relative(c,p):p}),r._names=uv.fromArray(a.map(String),!0),r._sources=uv.fromArray(o,!0),r._absoluteSources=r._sources.toArray().map(function(p){return _t.computeSourceURL(c,p,t)}),r.sourceRoot=c,r.sourcesContent=l,r._mappings=u,r._sourceMapURL=t,r.file=h,r._computedColumnSpans=!1,r._mappingsPtr=0,r._wasm=null,_he().then(p=>(r._wasm=p,r))})}_findSourceIndex(e){let t=e;if(this.sourceRoot!=null&&(t=_t.relative(this.sourceRoot,t)),this._sources.has(t))return this._sources.indexOf(t);for(let r=0;r{a.source!==null&&(a.source=this._sources.at(a.source),a.source=_t.computeSourceURL(o,a.source,this._sourceMapURL),a.name!==null&&(a.name=this._names.at(a.name))),e.call(i,a)},()=>{switch(s){case dr.GENERATED_ORDER:this._wasm.exports.by_generated_location(this._getMappingsPtr());break;case dr.ORIGINAL_ORDER:this._wasm.exports.by_original_location(this._getMappingsPtr());break;default:throw new Error("Unknown order of iteration.")}})}allGeneratedPositionsFor(e){let t=_t.getArg(e,"source");const r=_t.getArg(e,"line"),i=e.column||0;if(t=this._findSourceIndex(t),t<0)return[];if(r<1)throw new Error("Line numbers must be >= 1");if(i<0)throw new Error("Column numbers must be >= 0");const s=[];return this._wasm.withMappingCallback(o=>{let a=o.lastGeneratedColumn;this._computedColumnSpans&&a===null&&(a=1/0),s.push({line:o.generatedLine,column:o.generatedColumn,lastColumn:a})},()=>{this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(),t,r-1,"column"in e,i)}),s}destroy(){this._mappingsPtr!==0&&(this._wasm.exports.free_mappings(this._mappingsPtr),this._mappingsPtr=0)}computeColumnSpans(){this._computedColumnSpans||(this._wasm.exports.compute_column_spans(this._getMappingsPtr()),this._computedColumnSpans=!0)}originalPositionFor(e){const t={generatedLine:_t.getArg(e,"line"),generatedColumn:_t.getArg(e,"column")};if(t.generatedLine<1)throw new Error("Line numbers must be >= 1");if(t.generatedColumn<0)throw new Error("Column numbers must be >= 0");let r=_t.getArg(e,"bias",dr.GREATEST_LOWER_BOUND);r==null&&(r=dr.GREATEST_LOWER_BOUND);let i;if(this._wasm.withMappingCallback(s=>i=s,()=>{this._wasm.exports.original_location_for(this._getMappingsPtr(),t.generatedLine-1,t.generatedColumn,r)}),i&&i.generatedLine===t.generatedLine){let s=_t.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=_t.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));let o=_t.getArg(i,"name",null);return o!==null&&(o=this._names.at(o)),{source:s,line:_t.getArg(i,"originalLine",null),column:_t.getArg(i,"originalColumn",null),name:o}}return{source:null,line:null,column:null,name:null}}hasContentsOfAllSources(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1}sourceContentFor(e,t){if(!this.sourcesContent)return null;const r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];let i=e;this.sourceRoot!=null&&(i=_t.relative(this.sourceRoot,i));let s;if(this.sourceRoot!=null&&(s=_t.urlParse(this.sourceRoot))){const o=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(t)return null;throw new Error('"'+i+'" is not in the SourceMap.')}generatedPositionFor(e){let t=_t.getArg(e,"source");if(t=this._findSourceIndex(t),t<0)return{line:null,column:null,lastColumn:null};const r={source:t,originalLine:_t.getArg(e,"line"),originalColumn:_t.getArg(e,"column")};if(r.originalLine<1)throw new Error("Line numbers must be >= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");let i=_t.getArg(e,"bias",dr.GREATEST_LOWER_BOUND);i==null&&(i=dr.GREATEST_LOWER_BOUND);let s;if(this._wasm.withMappingCallback(o=>s=o,()=>{this._wasm.exports.generated_location_for(this._getMappingsPtr(),r.source,r.originalLine-1,r.originalColumn,i)}),s&&s.source===r.source){let o=s.lastGeneratedColumn;return this._computedColumnSpans&&o===null&&(o=1/0),{line:_t.getArg(s,"generatedLine",null),column:_t.getArg(s,"generatedColumn",null),lastColumn:o}}return{line:null,column:null,lastColumn:null}}}Im.prototype.consumer=dr;class vhe extends dr{constructor(e,t){return super(EA).then(r=>{let i=e;typeof e=="string"&&(i=_t.parseSourceMapInput(e));const s=_t.getArg(i,"version"),o=_t.getArg(i,"sections");if(s!=r._version)throw new Error("Unsupported version: "+s);r._sources=new uv,r._names=new uv,r.__generatedMappings=null,r.__originalMappings=null,r.__generatedMappingsUnsorted=null,r.__originalMappingsUnsorted=null;let a={line:-1,column:0};return Promise.all(o.map(c=>{if(c.url)throw new Error("Support for url field in sections not implemented.");const l=_t.getArg(c,"offset"),u=_t.getArg(l,"line"),h=_t.getArg(l,"column");if(u({generatedOffset:{generatedLine:u+1,generatedColumn:h+1},consumer:m}))})).then(c=>(r._sections=c,r))})}get _generatedMappings(){return this.__generatedMappings||this._sortGeneratedMappings(),this.__generatedMappings}get _originalMappings(){return this.__originalMappings||this._sortOriginalMappings(),this.__originalMappings}get _generatedMappingsUnsorted(){return this.__generatedMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappingsUnsorted}get _originalMappingsUnsorted(){return this.__originalMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappingsUnsorted}_sortGeneratedMappings(){const e=this._generatedMappingsUnsorted;e.sort(_t.compareByGeneratedPositionsDeflated),this.__generatedMappings=e}_sortOriginalMappings(){const e=this._originalMappingsUnsorted;e.sort(_t.compareByOriginalPositions),this.__originalMappings=e}get sources(){const e=[];for(let t=0;ta.push(c));for(let c=0;c= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");const i=[];let s=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",_t.compareByOriginalPositions,_1.LEAST_UPPER_BOUND);if(s>=0){let o=this._originalMappings[s];if(e.column===void 0){const a=o.originalLine;for(;o&&o.originalLine===a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:_t.getArg(o,"generatedLine",null),column:_t.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}else{const a=o.originalColumn;for(;o&&o.originalLine===t&&o.originalColumn==a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:_t.getArg(o,"generatedLine",null),column:_t.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}}return i}destroy(){for(let e=0;e=0;t--)this.prepend(e[t]);else if(e[$h]||typeof e=="string")this.children.unshift(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this}walk(e){let t;for(let r=0,i=this.children.length;r0){for(t=[],r=0;r{this.MANY(()=>this.SUBRULE(this.line))}));vt(this,"line",this.RULED("line",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt)},{ALT:()=>this.CONSUME(Dp)}])}));vt(this,"stmt",this.RULED("stmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.short_commands)),this.MANY(()=>this.SUBRULE(this.commands))}}])}));vt(this,"inline",this.RULED("inline",()=>{this.SUBRULE(this.instmt)}));vt(this,"instmt",this.RULED("instmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}])}));vt(this,"stmt_label",this.RULED("stmt_label",()=>{this.CONSUME(U3)}));vt(this,"stmt_stat",this.RULED("stmt_stat",()=>{this.CONSUME(mA)}));vt(this,"stmt_text",this.RULED("stmt_text",()=>{this.OR([{ALT:()=>this.CONSUME(P3)}])}));vt(this,"stmt_comment",this.RULED("stmt_comment",()=>{this.CONSUME(D3)}));vt(this,"stmt_hyperlink",this.RULED("stmt_hyperlink",()=>{this.CONSUME(F3),this.SUBRULE(this.words),this.CONSUME(B3)}));vt(this,"stmt_command",this.RULED("stmt_command",()=>{this.CONSUME(Jh),this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}));vt(this,"short_commands",this.RULED("short_commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)}])}));vt(this,"commands",this.RULED("commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.words)},{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)},{ALT:()=>this.SUBRULE(this.command_play)},{ALT:()=>this.SUBRULE(this.structured_cmd)}])}));vt(this,"structured_cmd",this.RULED("structured_cmd",()=>{this.OR([{ALT:()=>this.SUBRULE(this.command_debugger)},{ALT:()=>this.SUBRULE(this.command_if)},{ALT:()=>this.SUBRULE(this.command_while)},{ALT:()=>this.SUBRULE(this.command_repeat)},{ALT:()=>this.SUBRULE(this.command_waitfor)},{ALT:()=>this.SUBRULE(this.command_foreach)},{ALT:()=>this.SUBRULE(this.command_break)},{ALT:()=>this.SUBRULE(this.command_continue)}])}));vt(this,"short_go",this.RULED("short_go",()=>{this.CONSUME(Cw),this.SUBRULE(this.words)}));vt(this,"short_try",this.RULED("short_try",()=>{this.CONSUME(Q3),this.SUBRULE(this.words)}));vt(this,"command_debugger",this.RULED("command_debugger",()=>{this.CONSUME(n4)}));vt(this,"command_if",this.RULED("command_if",()=>{this.CONSUME(Rw),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_if_block))}));vt(this,"command_if_block",this.RULED("command_if_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(d_),this.MANY(()=>this.SUBRULE(this.line)),this.MANY2({GATE:this.BACKTRACK(this.command_else_if),DEF:()=>this.SUBRULE(this.command_else_if)}),this.OPTION(()=>this.SUBRULE(this.command_else)),this.MANY3(()=>this.CONSUME3(Dp)),this.CONSUME4(Jh),this.CONSUME4(kw)}}])}));vt(this,"command_block",this.RULED("command_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(d_),this.MANY(()=>this.SUBRULE(this.line)),this.CONSUME(Jh),this.CONSUME(kw)}}])}));vt(this,"command_fork",this.RULED("command_fork",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(d_),this.MANY({GATE:this.BACKTRACK(this.line),DEF:()=>this.SUBRULE(this.line)})}}])}));vt(this,"command_else_if",this.RULED("command_else_if",()=>{this.CONSUME(Jh),this.CONSUME(Iw),this.CONSUME(Rw),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_fork))}));vt(this,"command_else",this.RULED("command_else",()=>{this.CONSUME(Jh),this.CONSUME(Iw),this.OPTION(()=>this.SUBRULE(this.command_fork))}));vt(this,"command_while",this.RULED("command_while",()=>{this.CONSUME(r4),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));vt(this,"command_repeat",this.RULED("command_repeat",()=>{this.CONSUME(i4),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));vt(this,"command_waitfor",this.RULED("command_waitfor",()=>{this.CONSUME(s4),this.SUBRULE(this.words)}));vt(this,"command_foreach",this.RULED("command_foreach",()=>{this.CONSUME(o4),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));vt(this,"command_break",this.RULED("command_break",()=>{this.CONSUME(a4)}));vt(this,"command_continue",this.RULED("command_continue",()=>{this.CONSUME(c4)}));vt(this,"command_play",this.RULED("command_play",()=>{this.CONSUME(t4)}));vt(this,"expr",this.RULED("expr",()=>{this.SUBRULE1(this.and_test),this.MANY(()=>{this.CONSUME(ww),this.SUBRULE2(this.and_test)})}));vt(this,"and_test",this.RULED("and_test",()=>{this.SUBRULE1(this.not_test),this.MANY(()=>{this.CONSUME(bw),this.SUBRULE2(this.not_test)})}));vt(this,"not_test",this.RULED("not_test",()=>{this.OR([{ALT:()=>{this.CONSUME(Tw),this.SUBRULE1(this.not_test)}},{ALT:()=>this.SUBRULE2(this.comparison)}])}));vt(this,"comparison",this.RULED("comparison",()=>{this.SUBRULE1(this.arith_expr),this.MANY(()=>{this.SUBRULE(this.comp_op),this.SUBRULE2(this.arith_expr)})}));vt(this,"comp_op",this.RULED("comp_op",()=>{this.OR([{ALT:()=>this.CONSUME(H3)},{ALT:()=>this.CONSUME(G3)},{ALT:()=>this.CONSUME(W3)},{ALT:()=>this.CONSUME(j3)},{ALT:()=>this.CONSUME($3)},{ALT:()=>this.CONSUME(q3)}])}));vt(this,"expr_value",this.RULED("expr_value",()=>{this.SUBRULE1(this.and_test_value),this.MANY(()=>{this.CONSUME(ww),this.SUBRULE2(this.and_test_value)})}));vt(this,"and_test_value",this.RULED("and_test_value",()=>{this.SUBRULE1(this.not_test_value),this.MANY(()=>{this.CONSUME(bw),this.SUBRULE2(this.not_test_value)})}));vt(this,"not_test_value",this.RULED("not_test_value",()=>{this.OR([{ALT:()=>{this.CONSUME(Tw),this.SUBRULE1(this.not_test_value)}},{ALT:()=>this.SUBRULE2(this.arith_expr)}])}));vt(this,"arith_expr",this.RULED("arith_expr",()=>{this.SUBRULE1(this.term),this.MANY(()=>this.SUBRULE2(this.arith_expr_item))}));vt(this,"arith_expr_item",this.RULED("arith_expr_item",()=>{this.OR([{ALT:()=>this.CONSUME(Aw)},{ALT:()=>this.CONSUME(Mw)}]),this.SUBRULE(this.term)}));vt(this,"term",this.RULED("term",()=>{this.SUBRULE1(this.factor),this.MANY(()=>this.SUBRULE2(this.term_item))}));vt(this,"term_item",this.RULED("term_item",()=>{this.OR([{ALT:()=>this.CONSUME(K3)},{ALT:()=>this.CONSUME(Cw)},{ALT:()=>this.CONSUME(Y3)},{ALT:()=>this.CONSUME(Z3)}]),this.SUBRULE(this.factor)}));vt(this,"factor",this.RULED("factor",()=>{this.OR1([{ALT:()=>{this.OR2([{ALT:()=>this.CONSUME(Aw)},{ALT:()=>this.CONSUME(Mw)}]),this.SUBRULE(this.factor)}},{ALT:()=>this.SUBRULE(this.power)}])}));vt(this,"power",this.RULED("power",()=>{this.SUBRULE(this.token),this.OPTION(()=>{this.CONSUME(X3),this.SUBRULE(this.factor)})}));vt(this,"words",this.RULED("words",()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.expr))}));vt(this,"token",this.RULED("token",()=>{this.OR([{ALT:()=>this.CONSUME(z3)},{ALT:()=>this.CONSUME(Gi)},{ALT:()=>this.CONSUME(V3)},{ALT:()=>{this.CONSUME(J3),this.SUBRULE(this.expr),this.CONSUME(e4)}}])}));this.performSelfAnalysis()}PEEK(t,r,...i){console.info(t,i.map(s=>[s.image,s.tokenType]),r)}RULED(t,r,i){const s=Ahe.some(o=>t.includes(o));return this.RULE(t,()=>{const a=(YI++).toString().padStart(3),c=s?"font-weight: bold;":"";if(ZI&&!this.RECORDING_PHASE){const l=[this.LA(1),this.LA(2),this.LA(3)].map(u=>`[${u.tokenType.name} ${u.image.replaceAll(` -`,"\\n")}]`);console.info(`${a}%c> ${t} ${l.join(" ")}`,c)}r(),ZI&&!this.RECORDING_PHASE&&console.info(`${a}%c< ${t} `,c),YI--},i)}}const lf=new Mhe;if(GK){const n=lf.getGAstProductions(),e=ole(n);console.info(e)}const Che=lf.getBaseCstVisitorConstructor();var Xe=(n=>(n[n.PROGRAM=0]="PROGRAM",n[n.API=1]="API",n[n.LINE=2]="LINE",n[n.MARK=3]="MARK",n[n.GOTO=4]="GOTO",n[n.COUNT=5]="COUNT",n[n.TEXT=6]="TEXT",n[n.LABEL=7]="LABEL",n[n.HYPERLINK=8]="HYPERLINK",n[n.STAT=9]="STAT",n[n.MOVE=10]="MOVE",n[n.COMMAND=11]="COMMAND",n[n.LITERAL=12]="LITERAL",n[n.IF=13]="IF",n[n.IF_CHECK=14]="IF_CHECK",n[n.IF_BLOCK=15]="IF_BLOCK",n[n.ELSE_IF=16]="ELSE_IF",n[n.ELSE=17]="ELSE",n[n.WHILE=18]="WHILE",n[n.BREAK=19]="BREAK",n[n.CONTINUE=20]="CONTINUE",n[n.REPEAT=21]="REPEAT",n[n.WAITFOR=22]="WAITFOR",n[n.FOREACH=23]="FOREACH",n[n.OR=24]="OR",n[n.AND=25]="AND",n[n.NOT=26]="NOT",n[n.COMPARE=27]="COMPARE",n[n.COMPARE_ITEM=28]="COMPARE_ITEM",n[n.OPERATOR=29]="OPERATOR",n[n.OPERATOR_ITEM=30]="OPERATOR_ITEM",n[n.EXPR=31]="EXPR",n))(Xe||{}),vu=(n=>(n[n.IS_EQ=0]="IS_EQ",n[n.IS_NOT_EQ=1]="IS_NOT_EQ",n[n.IS_LESS_THAN=2]="IS_LESS_THAN",n[n.IS_GREATER_THAN=3]="IS_GREATER_THAN",n[n.IS_LESS_THAN_OR_EQ=4]="IS_LESS_THAN_OR_EQ",n[n.IS_GREATER_THAN_OR_EQ=5]="IS_GREATER_THAN_OR_EQ",n))(vu||{}),ra=(n=>(n[n.EMPTY=0]="EMPTY",n[n.PLUS=1]="PLUS",n[n.MINUS=2]="MINUS",n[n.POWER=3]="POWER",n[n.MULTIPLY=4]="MULTIPLY",n[n.DIVIDE=5]="DIVIDE",n[n.MOD_DIVIDE=6]="MOD_DIVIDE",n[n.FLOOR_DIVIDE=7]="FLOOR_DIVIDE",n[n.UNI_PLUS=8]="UNI_PLUS",n[n.UNI_MINUS=9]="UNI_MINUS",n))(ra||{}),p_=(n=>(n[n.NUMBER=0]="NUMBER",n[n.STRING=1]="STRING",n[n.TEMPLATE=2]="TEMPLATE",n))(p_||{});function Rhe(n){return!!(n!=null&&n.tokenType)}function sc(n,e){const[t]=n??[];return((t==null?void 0:t.image)??e).trimStart().replaceAll(/^"|"$/g,"")}class khe extends Che{constructor(){super();vt(this,"unique",0);ba&&this.validateVisitor()}getnodelocation(t){const r=Object.values(t).flat().filter(i=>!!i).map(i=>i&&Rhe(i)?{startLine:i.startLine,startColumn:i.startColumn,startOffset:i.startOffset,endLine:i.endLine,endColumn:i.endColumn,endOffset:i.endOffset}:i!=null&&i.location?{...i.location}:{startLine:0,startColumn:0,startOffset:0,endLine:0,endColumn:0,endOffset:0}).filter(i=>i.startLine!==0&&i.endLine!==0);return{startLine:Math.min(...r.map(i=>i.startLine??1)),startColumn:Math.min(...r.map(i=>i.startColumn??1)),startOffset:Math.min(...r.map(i=>i.startOffset??1)),endLine:Math.max(...r.map(i=>i.endLine??1)),endColumn:Math.max(...r.map(i=>i.endColumn??1)),endOffset:Math.max(...r.map(i=>i.endOffset??1))}}createcodenode(t,r){return[{...r,...this.getnodelocation(t),lineindex:0}]}createstringnode(t,r){return this.createcodenode(t,{type:12,literal:1,value:r})}createmarknode(t,r,i){return this.createlinenode(t,this.createcodenode(t,{type:3,id:r,comment:i}))}creategotonode(t,r,i){return this.createlinenode(t,this.createcodenode(t,{type:4,id:r,comment:i}))}createlinenode(t,r){return this.createcodenode(t,{type:2,stmts:r})}createapinode(t,r,i){return this.createlinenode(t,this.createcodenode(t,{type:1,words:i,method:r}))}createlogicnode(t,r,i,s){return this.createlinenode(t,this.createcodenode(t,{type:14,skip:i,words:s,method:r}))}createcountnode(t){return this.createcodenode(t,{type:5,index:this.unique++})}go(t){return Array.isArray(t)?t.map(r=>this.visit(r)).flat():K(t)?[this.visit(t)].flat():[]}program(t){return this.unique=0,this.createcodenode(t,{type:0,lines:[this.createlinenode(t,this.createcodenode(t,{type:7,active:!0,name:"restart"})),this.go(t.line)].flat()})}line(t){return t.stmt?this.go(t.stmt):[]}stmt(t){return t.stmt_label?this.go(t.stmt_label):t.stmt_stat?this.go(t.stmt_stat):t.stmt_text?this.go(t.stmt_text):t.stmt_comment?this.go(t.stmt_comment):t.stmt_command?this.go(t.stmt_command):t.stmt_hyperlink?this.go(t.stmt_hyperlink):t.short_commands?[this.go(t.short_commands),this.go(t.commands)].flat():[]}inline(t){return this.go(t.instmt)}instmt(t){return t.stmt_label?this.go(t.stmt_label):t.stmt_stat?this.go(t.stmt_stat):t.stmt_text?this.go(t.stmt_text):t.stmt_comment?this.go(t.stmt_comment):t.stmt_command?this.go(t.stmt_command):t.stmt_hyperlink?this.go(t.stmt_hyperlink):t.commands?this.go(t.commands):[]}stmt_label(t){return this.createlinenode(t,this.createcodenode(t,{type:7,active:!0,name:sc(t.token_label,":").slice(1).trim()}))}stmt_stat(t){return this.createlinenode(t,this.createcodenode(t,{type:9,value:sc(t.token_stat,"@").slice(1)}))}stmt_text(t){return this.createlinenode(t,this.createcodenode(t,{type:6,value:sc(t.token_text,"")}))}stmt_comment(t){return this.createlinenode(t,this.createcodenode(t,{type:7,active:!1,name:sc(t.token_comment,"'").slice(1).trim()}))}stmt_hyperlink(t){return this.createlinenode(t,this.createcodenode(t,{type:8,link:this.go(t.words),text:sc(t.token_hyperlinktext,";").slice(1)}))}stmt_command(t){return t.commands?this.go(t.commands):[]}short_commands(t){return t.short_go?this.go(t.short_go):t.short_try?this.go(t.short_try):[]}commands(t){return t.words?this.createlinenode(t,this.createcodenode(t,{type:11,words:this.go(t.words)})):t.short_go?this.go(t.short_go):t.short_try?this.go(t.short_try):t.command_play?this.go(t.command_play):t.structured_cmd?this.go(t.structured_cmd):[]}structured_cmd(t){return t.command_if?this.go(t.command_if):t.command_while?this.go(t.command_while):t.command_repeat?this.go(t.command_repeat):t.command_waitfor?this.go(t.command_waitfor):t.command_foreach?this.go(t.command_foreach):t.command_break?this.go(t.command_break):t.command_continue?this.go(t.command_continue):[]}short_go(t){return t.token_divide?this.createlinenode(t,this.createcodenode(t,{type:10,wait:!0,words:this.go(t.words)})):[]}short_try(t){return t.token_query?this.createlinenode(t,this.createcodenode(t,{type:10,wait:!1,words:this.go(t.words)})):[]}command_if(t){const[r]=this.createlogicnode(t,"if","",this.go(t.words)),[i]=this.go(t.command_if_block)??[];return this.createcodenode(t,{type:13,check:r,block:i})}command_if_block(t){const r=fr(),i=fr();return this.createcodenode(t,{type:15,skip:r,done:i,lines:[this.go(t.inline),this.go(t.line),this.creategotonode(t,i,"end of if"),this.createmarknode(t,r,"alt logic")].flat(),altlines:[this.go(t.command_else_if),this.go(t.command_else),this.createmarknode(t,i,"end of if")].flat()})}command_block(t){return[this.go(t.inline),this.go(t.line)].flat()}command_fork(t){return[this.go(t.inline),this.go(t.line)].flat()}command_else_if(t){const r=fr(),i=fr();return this.createcodenode(t,{type:16,done:i,lines:[this.createlogicnode(t,"if",r,this.go(t.words)),this.go(t.command_fork),this.creategotonode(t,i,"end of if"),this.createmarknode(t,r,"skip")].flat()})}command_else(t){return this.createcodenode(t,{type:17,lines:this.go(t.command_fork)})}command_while(t){const r=fr(),i=fr();return this.createcodenode(t,{type:18,loop:r,done:i,lines:[this.createmarknode(t,r,"start of while"),this.createlogicnode(t,"if",i,this.go(t.words)),this.go(t.command_block),this.creategotonode(t,r,"loop of while"),this.createmarknode(t,i,"end of while")].flat()})}command_repeat(t){const r=fr(),i=fr(),o=[this.createcountnode(t),this.go(t.words)].flat();return this.createcodenode(t,{type:21,loop:r,done:i,lines:[this.createapinode(t,"repeatstart",o),this.createmarknode(t,r,"start of repeat"),this.createlogicnode(t,"repeat",i,o),this.go(t.command_block),this.creategotonode(t,r,"loop of repeat"),this.createmarknode(t,i,"end of repeat")].flat()})}command_foreach(t){const r=fr(),i=fr(),o=[this.createcountnode(t),this.go(t.words)].flat();return this.createcodenode(t,{type:23,loop:r,done:i,lines:[this.createapinode(t,"foreachstart",o),this.createmarknode(t,r,"start of foreach"),this.createlogicnode(t,"foreach",i,o),this.go(t.command_block),this.creategotonode(t,r,"loop of foreach"),this.createmarknode(t,i,"end of foreach")].flat()})}command_waitfor(t){return this.createcodenode(t,{type:22,words:this.go(t.words)})}command_break(t){return this.createcodenode(t,{type:19,goto:0})}command_continue(t){return this.createcodenode(t,{type:20,goto:0})}command_play(t){const r=sc(t.token_command_play,""),i=r.replace("bgplay","").replace("play","").trim(),s=r.includes("bgplay");return this.createlinenode(t,this.createcodenode(t,{type:11,words:[this.createstringnode(t,s?"bgplay":"play"),this.createstringnode(t,i)].flat()}))}expr(t){return t.and_test.length===1?this.go(t.and_test):this.createcodenode(t,{type:24,items:this.go(t.and_test)})}and_test(t){return t.not_test.length===1?this.go(t.not_test):this.createcodenode(t,{type:25,items:this.go(t.not_test)})}not_test(t){return t.comparison?this.go(t.comparison):t.not_test?this.createcodenode(t,{type:26,items:this.go(t.not_test)}):[]}comparison(t){if(t.arith_expr.length===1)return this.go(t.arith_expr);const[r,i]=this.go(t.arith_expr),[s]=this.go(t.comp_op);return this.createcodenode(t,{type:27,lhs:r,compare:s,rhs:i})}comp_op(t){return t.token_iseq?this.createcodenode(t,{type:28,method:0}):t.token_isnoteq?this.createcodenode(t,{type:28,method:1}):t.token_islessthan?this.createcodenode(t,{type:28,method:2}):t.token_isgreaterthan?this.createcodenode(t,{type:28,method:3}):t.token_isgreaterthanorequal?this.createcodenode(t,{type:28,method:4}):t.token_isgreaterthanorequal?this.createcodenode(t,{type:28,method:5}):[]}expr_value(t){return t.and_test_value.length===1?this.go(t.and_test_value):this.createcodenode(t,{type:24,items:this.go(t.and_test_value)})}and_test_value(t){return t.not_test_value.length===1?this.go(t.not_test_value):this.createcodenode(t,{type:25,items:this.go(t.not_test_value)})}not_test_value(t){return t.arith_expr?this.go(t.arith_expr):t.not_test_value?this.createcodenode(t,{type:26,items:this.go(t.not_test_value)}):[]}arith_expr(t){const r=this.go(t.term);return t.arith_expr_item?this.createcodenode(t,{type:29,lhs:r[0],items:this.go(t.arith_expr_item)}):r}arith_expr_item(t){return this.createcodenode(t,{type:30,operator:t.token_plus?1:2,rhs:this.go(t.term)[0]})}term(t){return t.term_item?this.createcodenode(t,{type:29,lhs:this.go(t.factor)[0],items:this.go(t.term_item)}):this.go(t.factor)}term_item(t){let r=0;return t.token_multiply&&(r=4),t.token_divide&&(r=5),t.token_moddivide&&(r=6),t.token_floordivide&&(r=7),this.createcodenode(t,{type:30,operator:r,rhs:this.go(t.factor)[0]})}factor(t){if(t.power)return this.go(t.power);let r=0;return t.token_plus&&(r=8),t.token_minus&&(r=9),this.createcodenode(t,{type:29,lhs:void 0,items:this.createcodenode(t,{type:30,operator:r,rhs:this.go(t.factor)[0]})})}power(t){const r=this.go(t.token);return t.factor?this.createcodenode(t,{type:29,lhs:r[0],items:this.createcodenode(t,{type:30,operator:3,rhs:this.go(t.factor)[0]})}):r}words(t){return this.go(t.expr)}token(t){if(t.token_stringliteraldouble){const r=sc(t.token_stringliteraldouble,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(t,{type:12,literal:2,value:r})}if(t.token_stringliteral){const r=sc(t.token_stringliteral,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(t,{type:12,literal:1,value:r})}if(t.token_numberliteral){const r=parseFloat(sc(t.token_numberliteral,"0"));return this.createcodenode(t,{type:12,literal:0,value:r})}return t.token_lparen?this.createcodenode(t,{type:31,words:this.go(t.expr)}):[]}}const Ihe=new khe,ts={labels:{},internal:0,lineindex:0,linelookup:{},isfirststat:!1},Dy="zss.js";function sn(n,e){return new bhe(n.startLine??1,n.startColumn??1,Dy,e)}function Dw(n){return n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function v1(n){return`'${Dw(n)}'`}function m_(n){if(n.startsWith('"'))return m_(n.replaceAll(/(^"|"$)/g,""));const e=Fy(n);return e.errors.length?n:`['${e.tokens.map(r=>r.tokenType===MA?`', api.get('${Dw(r.image.substring(1))}'), '`:Dw(r.image)).join("")}'].join('')`}function du(n){return n.filter(e=>e!==void 0).map(xn)}function QI(n){return sn(n,"")}function Nhe(n,e){const t=[];return n.forEach(r=>{t.push(r,e)}),t.pop(),t}function Mr(n,e,t){return sn(n,[`api.${e}(`,...Nhe(t,", "),")"])}function Ohe(n){if(n.type===Xe.COMPARE&&n.compare.type===Xe.COMPARE_ITEM)switch(n.compare.method){case vu.IS_EQ:return Mr(n,"isEq",[xn(n.lhs),xn(n.rhs)]);case vu.IS_NOT_EQ:return Mr(n,"isNotEq",[xn(n.lhs),xn(n.rhs)]);case vu.IS_LESS_THAN:return Mr(n,"isLessThan",[xn(n.lhs),xn(n.rhs)]);case vu.IS_GREATER_THAN:return Mr(n,"isGreaterThan",[xn(n.lhs),xn(n.rhs)]);case vu.IS_LESS_THAN_OR_EQ:return Mr(n,"isLessThanOrEq",[xn(n.lhs),xn(n.rhs)]);case vu.IS_GREATER_THAN_OR_EQ:return Mr(n,"isGreaterThanOrEq",[xn(n.lhs),xn(n.rhs)])}return sn(n,"")}function pu(n,e,t){return n.prepend(`api.${e}(`),n.add([", ",xn(t),")"])}function JI(n,e,t){return n.prepend(`api.${e}(`),n.add([xn(t),")"])}function Lhe(n,e){if(n.type===Xe.OPERATOR_ITEM)switch(n.operator){case ra.PLUS:return pu(e,"opPlus",n.rhs);case ra.MINUS:return pu(e,"opMinus",n.rhs);case ra.POWER:return pu(e,"opPower",n.rhs);case ra.MULTIPLY:return pu(e,"opMultiply",n.rhs);case ra.DIVIDE:return pu(e,"opDivide",n.rhs);case ra.MOD_DIVIDE:return pu(e,"opModDivide",n.rhs);case ra.FLOOR_DIVIDE:return pu(e,"opFloorDivide",n.rhs);case ra.UNI_PLUS:return JI(e,"opUniPlus",n.rhs);case ra.UNI_MINUS:return JI(e,"opUniMinus",n.rhs)}return sn(n,"")}function Phe(n){if(n.type===Xe.OPERATOR){const e=n.lhs?xn(n.lhs):sn(n,"");return n.items.forEach(t=>Lhe(t,e)),e}return sn(n,"")}function N0(n,e){return sn(n,[Mr(n,"jump",[`${e}`]),"; continue;"])}function oc(n){return ts.linelookup[n??""]??-1}function Uw(n,e){ts.linelookup[n]=e}function ep(n,e,t){for(let r=0;rr.add(xn(i))),L4(t.altlines,Xe.ELSE_IF,oc(t.done)),t.altlines.forEach(i=>r.add(xn(i))),r}return sn(n,xn(n.check))}case Xe.IF_CHECK:{const t=oc(n.skip);return t===-1?sn(n,[" ",Mr(n,n.method,du(n.words)),`; -`]):sn(n,[" if (!",Mr(n,n.method,du(n.words)),") { ",N0(n,t),` } -`])}case Xe.ELSE_IF:case Xe.ELSE:{const t=sn(n,"");return n.lines.forEach(r=>t.add(xn(r))),t}case Xe.WHILE:{const t=oc(n.loop),r=oc(n.done),i=sn(n,"");return ep(n.lines,Xe.IF_CHECK,n.done),n.lines.forEach(s=>{switch(s.type){case Xe.BREAK:s.goto=r;break;case Xe.CONTINUE:s.goto=t;break}i.add(xn(s))}),i}case Xe.REPEAT:{const t=oc(n.loop),r=oc(n.done),i=sn(n,"");return ep(n.lines,Xe.IF_CHECK,n.done),n.lines.forEach(s=>{switch(s.type){case Xe.BREAK:s.goto=r;break;case Xe.CONTINUE:s.goto=t;break}i.add(xn(s))}),i}case Xe.WAITFOR:{const t=sn(n,"");return t.add([" if (!",Mr(n,"if",du(n.words)),`) { api.i(${n.lineindex-1}); } -`]),t}case Xe.FOREACH:{const t=oc(n.loop),r=oc(n.done),i=sn(n,"");return ep(n.lines,Xe.IF_CHECK,n.done),n.lines.forEach(s=>{switch(s.type){case Xe.BREAK:s.goto=r;break;case Xe.CONTINUE:s.goto=t;break}i.add(xn(s))}),i}case Xe.BREAK:return sn(n,[" ",N0(n,n.goto),` -`]);case Xe.CONTINUE:return sn(n,[" ",N0(n,n.goto),` -`]);case Xe.OR:return Mr(n,"or",n.items.map(xn));case Xe.AND:return Mr(n,"and",n.items.map(xn));case Xe.NOT:return Mr(n,"not",n.items.map(xn));case Xe.COMPARE:return Ohe(n);case Xe.OPERATOR:return Phe(n);case Xe.EXPR:return Mr(n,"expr",n.words.map(xn));default:return console.error("",n.type,n),QI(n)}}function ia(n){if(K(n))switch(n.type===Xe.LINE&&++ts.lineindex,n.lineindex=ts.lineindex,n.type){case Xe.PROGRAM:n.lines.forEach(ia);break;case Xe.LINE:n.stmts.forEach(ia);break;case Xe.MARK:Uw(n.id,n.lineindex);break;case Xe.IF:ia(n.check),ia(n.block);break;case Xe.IF_BLOCK:n.lines.forEach(ia),n.altlines.forEach(ia);break;case Xe.ELSE_IF:n.lines.forEach(ia);break;case Xe.ELSE:case Xe.WHILE:case Xe.REPEAT:case Xe.FOREACH:n.lines.forEach(ia);break;case Xe.MOVE:case Xe.COMMAND:case Xe.WAITFOR:case Xe.IF_CHECK:n.words.forEach(ia);break}}function Dhe(n){return ts.labels={},ts.internal=1,ts.lineindex=0,ts.isfirststat=!0,ia(n),{...xn(n).toStringWithSourceMap({file:`${Dy}.map`}),...ts}}const Uhe={HALT_AT_COUNT:256};function Fhe(n){return fn(n)?n.length>0?1:0:n??0}function ti(n){return`${n??""}`}function Bhe(n){return`${n}_chip`}function zhe(n,e,t){var c,l;const r=Bhe(n),i=Up(r);let s;fn(i.lb)||(i.lb=uT(Object.entries(t.labels??{})),i.lk="",i.mg=void 0,i.ec=1,i.lc=0,i.ys=0,i.ps=0,i.es=(((c=t.errors)==null?void 0:c.length)??0)!==0?1:0);function o(u,h){se.words=h,se.get=a.get;const p=Que(e,u);return K(p)?p(a,h):u!=="send"?o("send",[u,...h]):0}const a={halt(){Xhe(r)},id(){return n},senderid(u=n){return`vm:${u??n}`},set(u,h){const[p,m]=ehe(e,a,u,h);if(p)return m},get(u){const[h,p]=Jue(e,a,u);if(h)return p},bucket(u){const h=a.get("bucket");fn(h)?h.push(u):a.set("bucket",[u])},tick(u){const h=mt(i.ps)?i.ps:0,p=h%u===0;if(i.ps=h+1,p===!1)return!1;if(a.shouldtick()===!1)return qI(e,a),!1;i.lc=0,i.ys=0,the(e,a);try{const m=s==null?void 0:s.next();m!=null&&m.done&&(Pn("chip","crash","generator logic unexpectedly exited"),i.es=1)}catch(m){Pn("chip","crash",m.message),i.es=1}return qI(e,a),!0},isended(){return i.es===1},shouldtick(){return i.es===0||a.hm()!==0},shouldhalt(){return mt(i.lc)?++i.lc>Uhe.HALT_AT_COUNT:!0},hm(){if(fn(i.mg)&&fn(i.lb)){const[,u]=i.mg;if(K(u))for(let h=0;hmt(g)&&g>0)??0}}return 0},yield(){i.ys=1},jump(u){i.ec=u},sy(){return!!i.ys||a.shouldhalt()},emit(u,h,p){Yt.emit(u,a.senderid(),h,p)},send(u,h,p,m){Yt.emit(`${a.senderid(u)}:${h}`,n,p,m)},lock(u){i.lk=u},unlock(){i.lk=""},message(u){i.lk&&u.sender!==i.lk||(i.mg=[u.id,u.target,u.data,u.sender,u.player])},zap(u){if(fn(i.lb))for(let h=0;hv>0);g>=0&&(m[g]*=-1)}}},restore(u){if(fn(i.lb))for(let h=0;hm.fileName===Dy);return{line:(p==null?void 0:p.lineNumber)??0,column:(p==null?void 0:p.columnNumber)??0}},text(u){return o("text",[u])},stat(...u){return o("stat",u)},hyperlink(...u){return o("hyperlink",u)},command(...u){if(u.length===0)return 0;const[h,...p]=u;return o(ti(h),p)},if(...u){const[h,p]=Ve(u,0,[Ne.ANY]),m=Fhe(h);return m&&p0,v=i[p];return g&&fn(v)&&a.command(...v),g?1:0},foreachstart(u,...h){const[p,m,g,v]=Ve(h,0,[Ne.STRING,Ne.NUMBER,Ne.NUMBER,Ne.MAYBE_NUMBER]);let y=Math.min(m,g),_=Math.max(m,g);const S=(v??0)||1;if(S<0){const w=y;y=_,_=w}return a.set(p,y-S),0},foreach(u,...h){const[p,m,g,v,y]=Ve(h,0,[Ne.STRING,Ne.NUMBER,Ne.NUMBER,Ne.MAYBE_NUMBER]);let _=Math.min(m,g),S=Math.max(m,g);const w=(v??0)||1;if(w<0){const R=_;_=S,S=R}let T=a.get(p);!mt(T)||T<_||T>S?T=_:T+=w;const k=T<=S?1:0;return k&&(a.set(p,T),ym?1:0},isLessThanOrEq(u,h){const[p]=Ve([u],0,[Ne.NUMBER]),[m]=Ve([h],0,[Ne.NUMBER]);return p<=m?1:0},isGreaterThanOrEq(u,h){const[p]=Ve([u],0,[Ne.NUMBER]),[m]=Ve([h],0,[Ne.NUMBER]);return p>=m?1:0},opPlus(u,h){const[p]=Ve([u],0,[Ne.ANY]),[m]=Ve([h],0,[Ne.ANY]);return p+m},opMinus(u,h){const[p]=Ve([u],0,[Ne.ANY]),[m]=Ve([h],0,[Ne.ANY]);return p-m},opPower(u,h){const[p]=Ve([u],0,[Ne.NUMBER]),[m]=Ve([h],0,[Ne.NUMBER]);return Math.pow(p,m)},opMultiply(u,h){const[p]=Ve([u],0,[Ne.NUMBER]),[m]=Ve([h],0,[Ne.NUMBER]);return p*m},opDivide(u,h){const[p]=Ve([u],0,[Ne.NUMBER]),[m]=Ve([h],0,[Ne.NUMBER]);return p/m},opModDivide(u,h){const[p]=Ve([u],0,[Ne.NUMBER]),[m]=Ve([h],0,[Ne.NUMBER]);return p%m},opFloorDivide(u,h){const[p]=Ve([u],0,[Ne.NUMBER]),[m]=Ve([h],0,[Ne.NUMBER]);return Math.floor(p/m)},opUniPlus(u){const[h]=Ve([u],0,[Ne.NUMBER]);return+h},opUniMinus(u){const[h]=Ve([u],0,[Ne.NUMBER]);return-h}};return s=(l=t.code)==null?void 0:l.call(t,a),a}function O0(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Vhe={exports:{}};/*! - -JSZip v3.10.1 - A JavaScript class for generating and reading zip files - - -(c) 2009-2016 Stuart Knightley -Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. - -JSZip uses the library pako released under the MIT license : -https://github.com/nodeca/pako/blob/main/LICENSE -*/(function(n,e){(function(t){n.exports=t()})(function(){return function t(r,i,s){function o(l,u){if(!i[l]){if(!r[l]){var h=typeof O0=="function"&&O0;if(!u&&h)return h(l,!0);if(a)return a(l,!0);var p=new Error("Cannot find module '"+l+"'");throw p.code="MODULE_NOT_FOUND",p}var m=i[l]={exports:{}};r[l][0].call(m.exports,function(g){var v=r[l][1][g];return o(v||g)},m,m.exports,t,r,i,s)}return i[l].exports}for(var a=typeof O0=="function"&&O0,c=0;c>2,m=(3&l)<<4|u>>4,g=1>6:64,v=2>4,u=(15&p)<<4|(m=a.indexOf(c.charAt(v++)))>>2,h=(3&m)<<6|(g=a.indexOf(c.charAt(v++))),S[y++]=l,m!==64&&(S[y++]=u),g!==64&&(S[y++]=h);return S}},{"./support":30,"./utils":32}],2:[function(t,r,i){var s=t("./external"),o=t("./stream/DataWorker"),a=t("./stream/Crc32Probe"),c=t("./stream/DataLengthProbe");function l(u,h,p,m,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=p,this.compression=m,this.compressedContent=g}l.prototype={getContentWorker:function(){var u=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},l.createWorkerFrom=function(u,h,p){return u.pipe(new a).pipe(new c("uncompressedSize")).pipe(h.compressWorker(p)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=l},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,r,i){var s=t("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,r,i){var s=t("./utils"),o=function(){for(var a,c=[],l=0;l<256;l++){a=l;for(var u=0;u<8;u++)a=1&a?3988292384^a>>>1:a>>>1;c[l]=a}return c}();r.exports=function(a,c){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(l,u,h,p){var m=o,g=p+h;l^=-1;for(var v=p;v>>8^m[255&(l^u[v])];return-1^l}(0|c,a,a.length,0):function(l,u,h,p){var m=o,g=p+h;l^=-1;for(var v=p;v>>8^m[255&(l^u.charCodeAt(v))];return-1^l}(0|c,a,a.length,0):0}},{"./utils":32}],5:[function(t,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(t,r,i){var s=null;s=typeof Promise<"u"?Promise:t("lie"),r.exports={Promise:s}},{lie:37}],7:[function(t,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=t("pako"),a=t("./utils"),c=t("./stream/GenericWorker"),l=s?"uint8array":"array";function u(h,p){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=p,this.meta={}}i.magic="\b\0",a.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(l,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(p){h.push({data:p,meta:h.meta})}},i.compressWorker=function(h){return new u("Deflate",h)},i.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,r,i){function s(m,g){var v,y="";for(v=0;v>>=8;return y}function o(m,g,v,y,_,S){var w,T,k=m.file,R=m.compression,C=S!==l.utf8encode,O=a.transformTo("string",S(k.name)),M=a.transformTo("string",l.utf8encode(k.name)),N=k.comment,U=a.transformTo("string",S(N)),L=a.transformTo("string",l.utf8encode(N)),P=M.length!==k.name.length,b=L.length!==N.length,B="",W="",V="",G=k.dir,$=k.date,Z={crc32:0,compressedSize:0,uncompressedSize:0};g&&!v||(Z.crc32=m.crc32,Z.compressedSize=m.compressedSize,Z.uncompressedSize=m.uncompressedSize);var X=0;g&&(X|=8),C||!P&&!b||(X|=2048);var Y=0,ve=0;G&&(Y|=16),_==="UNIX"?(ve=798,Y|=function(ie,be){var Ce=ie;return ie||(Ce=be?16893:33204),(65535&Ce)<<16}(k.unixPermissions,G)):(ve=20,Y|=function(ie){return 63&(ie||0)}(k.dosPermissions)),w=$.getUTCHours(),w<<=6,w|=$.getUTCMinutes(),w<<=5,w|=$.getUTCSeconds()/2,T=$.getUTCFullYear()-1980,T<<=4,T|=$.getUTCMonth()+1,T<<=5,T|=$.getUTCDate(),P&&(W=s(1,1)+s(u(O),4)+M,B+="up"+s(W.length,2)+W),b&&(V=s(1,1)+s(u(U),4)+L,B+="uc"+s(V.length,2)+V);var ne="";return ne+=` -\0`,ne+=s(X,2),ne+=R.magic,ne+=s(w,2),ne+=s(T,2),ne+=s(Z.crc32,4),ne+=s(Z.compressedSize,4),ne+=s(Z.uncompressedSize,4),ne+=s(O.length,2),ne+=s(B.length,2),{fileRecord:h.LOCAL_FILE_HEADER+ne+O+B,dirRecord:h.CENTRAL_FILE_HEADER+s(ve,2)+ne+s(U.length,2)+"\0\0\0\0"+s(Y,4)+s(y,4)+O+B+U}}var a=t("../utils"),c=t("../stream/GenericWorker"),l=t("../utf8"),u=t("../crc32"),h=t("../signature");function p(m,g,v,y){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=v,this.encodeFileName=y,this.streamFiles=m,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(p,c),p.prototype.push=function(m){var g=m.meta.percent||0,v=this.entriesCount,y=this._sources.length;this.accumulate?this.contentBuffer.push(m):(this.bytesWritten+=m.data.length,c.prototype.push.call(this,{data:m.data,meta:{currentFile:this.currentFile,percent:v?(g+100*(v-y-1))/v:100}}))},p.prototype.openedSource=function(m){this.currentSourceOffset=this.bytesWritten,this.currentFile=m.file.name;var g=this.streamFiles&&!m.file.dir;if(g){var v=o(m,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:v.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(m){this.accumulate=!1;var g=this.streamFiles&&!m.file.dir,v=o(m,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(v.dirRecord),g)this.push({data:function(y){return h.DATA_DESCRIPTOR+s(y.crc32,4)+s(y.compressedSize,4)+s(y.uncompressedSize,4)}(m),meta:{percent:100}});else for(this.push({data:v.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var m=this.bytesWritten,g=0;g=this.index;c--)l=(l<<8)+this.byteAt(c);return this.index+=a,l},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},r.exports=o},{"../utils":32}],19:[function(t,r,i){var s=t("./Uint8ArrayReader");function o(a){s.call(this,a)}t("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,r,i){var s=t("./DataReader");function o(a){s.call(this,a)}t("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(t,r,i){var s=t("./ArrayReader");function o(a){s.call(this,a)}t("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(t,r,i){var s=t("../utils"),o=t("../support"),a=t("./ArrayReader"),c=t("./StringReader"),l=t("./NodeBufferReader"),u=t("./Uint8ArrayReader");r.exports=function(h){var p=s.getTypeOf(h);return s.checkSupport(p),p!=="string"||o.uint8array?p==="nodebuffer"?new l(h):o.uint8array?new u(s.transformTo("uint8array",h)):new a(s.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(t,r,i){var s=t("./GenericWorker"),o=t("../utils");function a(c){s.call(this,"ConvertWorker to "+c),this.destType=c}o.inherits(a,s),a.prototype.processChunk=function(c){this.push({data:o.transformTo(this.destType,c.data),meta:c.meta})},r.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(t,r,i){var s=t("./GenericWorker"),o=t("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}t("../utils").inherits(a,s),a.prototype.processChunk=function(c){this.streamInfo.crc32=o(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,r,i){var s=t("../utils"),o=t("./GenericWorker");function a(c){o.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}s.inherits(a,o),a.prototype.processChunk=function(c){if(c){var l=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=l+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(t,r,i){var s=t("../utils"),o=t("./GenericWorker");function a(c){o.call(this,"DataWorker");var l=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){l.dataIsReady=!0,l.data=u,l.max=u&&u.length||0,l.type=s.getTypeOf(u),l.isPaused||l._tickAndRepeat()},function(u){l.error(u)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,l=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,l);break;case"uint8array":c=this.data.subarray(this.index,l);break;case"array":case"nodebuffer":c=this.data.slice(this.index,l)}return this.index=l,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(t,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var c=0;c "+o:o}},r.exports=s},{}],29:[function(t,r,i){var s=t("../utils"),o=t("./ConvertWorker"),a=t("./GenericWorker"),c=t("../base64"),l=t("../support"),u=t("../external"),h=null;if(l.nodestream)try{h=t("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(g,v){return new u.Promise(function(y,_){var S=[],w=g._internalType,T=g._outputType,k=g._mimeType;g.on("data",function(R,C){S.push(R),v&&v(C)}).on("error",function(R){S=[],_(R)}).on("end",function(){try{var R=function(C,O,M){switch(C){case"blob":return s.newBlob(s.transformTo("arraybuffer",O),M);case"base64":return c.encode(O);default:return s.transformTo(C,O)}}(T,function(C,O){var M,N=0,U=null,L=0;for(M=0;M"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!t("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(t,r,i){for(var s=t("./utils"),o=t("./support"),a=t("./nodejsUtils"),c=t("./stream/GenericWorker"),l=new Array(256),u=0;u<256;u++)l[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;l[254]=l[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function p(){c.call(this,"utf-8 encode")}i.utf8encode=function(m){return o.nodebuffer?a.newBufferFrom(m,"utf-8"):function(g){var v,y,_,S,w,T=g.length,k=0;for(S=0;S>>6:(y<65536?v[w++]=224|y>>>12:(v[w++]=240|y>>>18,v[w++]=128|y>>>12&63),v[w++]=128|y>>>6&63),v[w++]=128|63&y);return v}(m)},i.utf8decode=function(m){return o.nodebuffer?s.transformTo("nodebuffer",m).toString("utf-8"):function(g){var v,y,_,S,w=g.length,T=new Array(2*w);for(v=y=0;v>10&1023,T[y++]=56320|1023&_)}return T.length!==y&&(T.subarray?T=T.subarray(0,y):T.length=y),s.applyFromCharCode(T)}(m=s.transformTo(o.uint8array?"uint8array":"array",m))},s.inherits(h,c),h.prototype.processChunk=function(m){var g=s.transformTo(o.uint8array?"uint8array":"array",m.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var v=g;(g=new Uint8Array(v.length+this.leftOver.length)).set(this.leftOver,0),g.set(v,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var y=function(S,w){var T;for((w=w||S.length)>S.length&&(w=S.length),T=w-1;0<=T&&(192&S[T])==128;)T--;return T<0||T===0?w:T+l[S[T]]>w?T:w}(g),_=g;y!==g.length&&(o.uint8array?(_=g.subarray(0,y),this.leftOver=g.subarray(y,g.length)):(_=g.slice(0,y),this.leftOver=g.slice(y,g.length))),this.push({data:i.utf8decode(_),meta:m.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=h,s.inherits(p,c),p.prototype.processChunk=function(m){this.push({data:i.utf8encode(m.data),meta:m.meta})},i.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,r,i){var s=t("./support"),o=t("./base64"),a=t("./nodejsUtils"),c=t("./external");function l(v){return v}function u(v,y){for(var _=0;_>8;this.dir=!!(16&this.externalFileAttributes),m==0&&(this.dosPermissions=63&this.externalFileAttributes),m==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var m=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=m.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=m.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=m.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=m.readInt(4))}},readExtraFields:function(m){var g,v,y,_=m.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});m.index+4<_;)g=m.readInt(2),v=m.readInt(2),y=m.readData(v),this.extraFields[g]={id:g,length:v,value:y};m.setIndex(_)},handleUTF8:function(){var m=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=l.utf8decode(this.fileName),this.fileCommentStr=l.utf8decode(this.fileComment);else{var g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var v=o.transformTo(m,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(v)}var y=this.findExtraFieldUnicodeComment();if(y!==null)this.fileCommentStr=y;else{var _=o.transformTo(m,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(_)}}},findExtraFieldUnicodePath:function(){var m=this.extraFields[28789];if(m){var g=s(m.value);return g.readInt(1)!==1||c(this.fileName)!==g.readInt(4)?null:l.utf8decode(g.readData(m.length-5))}return null},findExtraFieldUnicodeComment:function(){var m=this.extraFields[25461];if(m){var g=s(m.value);return g.readInt(1)!==1||c(this.fileComment)!==g.readInt(4)?null:l.utf8decode(g.readData(m.length-5))}return null}},r.exports=p},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(t,r,i){function s(g,v,y){this.name=g,this.dir=y.dir,this.date=y.date,this.comment=y.comment,this.unixPermissions=y.unixPermissions,this.dosPermissions=y.dosPermissions,this._data=v,this._dataBinary=y.binary,this.options={compression:y.compression,compressionOptions:y.compressionOptions}}var o=t("./stream/StreamHelper"),a=t("./stream/DataWorker"),c=t("./utf8"),l=t("./compressedObject"),u=t("./stream/GenericWorker");s.prototype={internalStream:function(g){var v=null,y="string";try{if(!g)throw new Error("No output type specified.");var _=(y=g.toLowerCase())==="string"||y==="text";y!=="binarystring"&&y!=="text"||(y="string"),v=this._decompressWorker();var S=!this._dataBinary;S&&!_&&(v=v.pipe(new c.Utf8EncodeWorker)),!S&&_&&(v=v.pipe(new c.Utf8DecodeWorker))}catch(w){(v=new u("error")).error(w)}return new o(v,y,"")},async:function(g,v){return this.internalStream(g).accumulate(v)},nodeStream:function(g,v){return this.internalStream(g||"nodebuffer").toNodejsStream(v)},_compressWorker:function(g,v){if(this._data instanceof l&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var y=this._decompressWorker();return this._dataBinary||(y=y.pipe(new c.Utf8EncodeWorker)),l.createWorkerFrom(y,g,v)},_decompressWorker:function(){return this._data instanceof l?this._data.getContentWorker():this._data instanceof u?this._data:new a(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],p=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},m=0;m>>6:(m<65536?p[y++]=224|m>>>12:(p[y++]=240|m>>>18,p[y++]=128|m>>>12&63),p[y++]=128|m>>>6&63),p[y++]=128|63&m);return p},i.buf2binstring=function(h){return u(h,h.length)},i.binstring2buf=function(h){for(var p=new s.Buf8(h.length),m=0,g=p.length;m>10&1023,S[g++]=56320|1023&v)}return u(S,g)},i.utf8border=function(h,p){var m;for((p=p||h.length)>h.length&&(p=h.length),m=p-1;0<=m&&(192&h[m])==128;)m--;return m<0||m===0?p:m+c[h[m]]>p?m:p}},{"./common":41}],43:[function(t,r,i){r.exports=function(s,o,a,c){for(var l=65535&s|0,u=s>>>16&65535|0,h=0;a!==0;){for(a-=h=2e3>>1:o>>>1;a[c]=o}return a}();r.exports=function(o,a,c,l){var u=s,h=l+c;o^=-1;for(var p=l;p>>8^u[255&(o^a[p])];return-1^o}},{}],46:[function(t,r,i){var s,o=t("../utils/common"),a=t("./trees"),c=t("./adler32"),l=t("./crc32"),u=t("./messages"),h=0,p=4,m=0,g=-2,v=-1,y=4,_=2,S=8,w=9,T=286,k=30,R=19,C=2*T+1,O=15,M=3,N=258,U=N+M+1,L=42,P=113,b=1,B=2,W=3,V=4;function G(A,J){return A.msg=u[J],J}function $(A){return(A<<1)-(4A.avail_out&&(re=A.avail_out),re!==0&&(o.arraySet(A.output,J.pending_buf,J.pending_out,re,A.next_out),A.next_out+=re,J.pending_out+=re,A.total_out+=re,A.avail_out-=re,J.pending-=re,J.pending===0&&(J.pending_out=0))}function Y(A,J){a._tr_flush_block(A,0<=A.block_start?A.block_start:-1,A.strstart-A.block_start,J),A.block_start=A.strstart,X(A.strm)}function ve(A,J){A.pending_buf[A.pending++]=J}function ne(A,J){A.pending_buf[A.pending++]=J>>>8&255,A.pending_buf[A.pending++]=255&J}function ie(A,J){var re,j,H=A.max_chain_length,te=A.strstart,oe=A.prev_length,z=A.nice_match,D=A.strstart>A.w_size-U?A.strstart-(A.w_size-U):0,ee=A.window,he=A.w_mask,ce=A.prev,ge=A.strstart+N,Be=ee[te+oe-1],Oe=ee[te+oe];A.prev_length>=A.good_match&&(H>>=2),z>A.lookahead&&(z=A.lookahead);do if(ee[(re=J)+oe]===Oe&&ee[re+oe-1]===Be&&ee[re]===ee[te]&&ee[++re]===ee[te+1]){te+=2,re++;do;while(ee[++te]===ee[++re]&&ee[++te]===ee[++re]&&ee[++te]===ee[++re]&&ee[++te]===ee[++re]&&ee[++te]===ee[++re]&&ee[++te]===ee[++re]&&ee[++te]===ee[++re]&&ee[++te]===ee[++re]&&teD&&--H!=0);return oe<=A.lookahead?oe:A.lookahead}function be(A){var J,re,j,H,te,oe,z,D,ee,he,ce=A.w_size;do{if(H=A.window_size-A.lookahead-A.strstart,A.strstart>=ce+(ce-U)){for(o.arraySet(A.window,A.window,ce,ce,0),A.match_start-=ce,A.strstart-=ce,A.block_start-=ce,J=re=A.hash_size;j=A.head[--J],A.head[J]=ce<=j?j-ce:0,--re;);for(J=re=ce;j=A.prev[--J],A.prev[J]=ce<=j?j-ce:0,--re;);H+=ce}if(A.strm.avail_in===0)break;if(oe=A.strm,z=A.window,D=A.strstart+A.lookahead,ee=H,he=void 0,he=oe.avail_in,ee=M)for(te=A.strstart-A.insert,A.ins_h=A.window[te],A.ins_h=(A.ins_h<=M&&(A.ins_h=(A.ins_h<=M)if(j=a._tr_tally(A,A.strstart-A.match_start,A.match_length-M),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=M){for(A.match_length--;A.strstart++,A.ins_h=(A.ins_h<=M&&(A.ins_h=(A.ins_h<=M&&A.match_length<=A.prev_length){for(H=A.strstart+A.lookahead-M,j=a._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-M),A.lookahead-=A.prev_length-1,A.prev_length-=2;++A.strstart<=H&&(A.ins_h=(A.ins_h<A.pending_buf_size-5&&(re=A.pending_buf_size-5);;){if(A.lookahead<=1){if(be(A),A.lookahead===0&&J===h)return b;if(A.lookahead===0)break}A.strstart+=A.lookahead,A.lookahead=0;var j=A.block_start+re;if((A.strstart===0||A.strstart>=j)&&(A.lookahead=A.strstart-j,A.strstart=j,Y(A,!1),A.strm.avail_out===0)||A.strstart-A.block_start>=A.w_size-U&&(Y(A,!1),A.strm.avail_out===0))return b}return A.insert=0,J===p?(Y(A,!0),A.strm.avail_out===0?W:V):(A.strstart>A.block_start&&(Y(A,!1),A.strm.avail_out),b)}),new Le(4,4,8,4,Ce),new Le(4,5,16,8,Ce),new Le(4,6,32,32,Ce),new Le(4,4,16,16,Ee),new Le(8,16,32,32,Ee),new Le(8,16,128,128,Ee),new Le(8,32,128,256,Ee),new Le(32,128,258,1024,Ee),new Le(32,258,258,4096,Ee)],i.deflateInit=function(A,J){return ft(A,J,S,15,8,0)},i.deflateInit2=ft,i.deflateReset=rt,i.deflateResetKeep=Ge,i.deflateSetHeader=function(A,J){return A&&A.state?A.state.wrap!==2?g:(A.state.gzhead=J,m):g},i.deflate=function(A,J){var re,j,H,te;if(!A||!A.state||5>8&255),ve(j,j.gzhead.time>>16&255),ve(j,j.gzhead.time>>24&255),ve(j,j.level===9?2:2<=j.strategy||j.level<2?4:0),ve(j,255&j.gzhead.os),j.gzhead.extra&&j.gzhead.extra.length&&(ve(j,255&j.gzhead.extra.length),ve(j,j.gzhead.extra.length>>8&255)),j.gzhead.hcrc&&(A.adler=l(A.adler,j.pending_buf,j.pending,0)),j.gzindex=0,j.status=69):(ve(j,0),ve(j,0),ve(j,0),ve(j,0),ve(j,0),ve(j,j.level===9?2:2<=j.strategy||j.level<2?4:0),ve(j,3),j.status=P);else{var oe=S+(j.w_bits-8<<4)<<8;oe|=(2<=j.strategy||j.level<2?0:j.level<6?1:j.level===6?2:3)<<6,j.strstart!==0&&(oe|=32),oe+=31-oe%31,j.status=P,ne(j,oe),j.strstart!==0&&(ne(j,A.adler>>>16),ne(j,65535&A.adler)),A.adler=1}if(j.status===69)if(j.gzhead.extra){for(H=j.pending;j.gzindex<(65535&j.gzhead.extra.length)&&(j.pending!==j.pending_buf_size||(j.gzhead.hcrc&&j.pending>H&&(A.adler=l(A.adler,j.pending_buf,j.pending-H,H)),X(A),H=j.pending,j.pending!==j.pending_buf_size));)ve(j,255&j.gzhead.extra[j.gzindex]),j.gzindex++;j.gzhead.hcrc&&j.pending>H&&(A.adler=l(A.adler,j.pending_buf,j.pending-H,H)),j.gzindex===j.gzhead.extra.length&&(j.gzindex=0,j.status=73)}else j.status=73;if(j.status===73)if(j.gzhead.name){H=j.pending;do{if(j.pending===j.pending_buf_size&&(j.gzhead.hcrc&&j.pending>H&&(A.adler=l(A.adler,j.pending_buf,j.pending-H,H)),X(A),H=j.pending,j.pending===j.pending_buf_size)){te=1;break}te=j.gzindexH&&(A.adler=l(A.adler,j.pending_buf,j.pending-H,H)),te===0&&(j.gzindex=0,j.status=91)}else j.status=91;if(j.status===91)if(j.gzhead.comment){H=j.pending;do{if(j.pending===j.pending_buf_size&&(j.gzhead.hcrc&&j.pending>H&&(A.adler=l(A.adler,j.pending_buf,j.pending-H,H)),X(A),H=j.pending,j.pending===j.pending_buf_size)){te=1;break}te=j.gzindexH&&(A.adler=l(A.adler,j.pending_buf,j.pending-H,H)),te===0&&(j.status=103)}else j.status=103;if(j.status===103&&(j.gzhead.hcrc?(j.pending+2>j.pending_buf_size&&X(A),j.pending+2<=j.pending_buf_size&&(ve(j,255&A.adler),ve(j,A.adler>>8&255),A.adler=0,j.status=P)):j.status=P),j.pending!==0){if(X(A),A.avail_out===0)return j.last_flush=-1,m}else if(A.avail_in===0&&$(J)<=$(re)&&J!==p)return G(A,-5);if(j.status===666&&A.avail_in!==0)return G(A,-5);if(A.avail_in!==0||j.lookahead!==0||J!==h&&j.status!==666){var z=j.strategy===2?function(D,ee){for(var he;;){if(D.lookahead===0&&(be(D),D.lookahead===0)){if(ee===h)return b;break}if(D.match_length=0,he=a._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++,he&&(Y(D,!1),D.strm.avail_out===0))return b}return D.insert=0,ee===p?(Y(D,!0),D.strm.avail_out===0?W:V):D.last_lit&&(Y(D,!1),D.strm.avail_out===0)?b:B}(j,J):j.strategy===3?function(D,ee){for(var he,ce,ge,Be,Oe=D.window;;){if(D.lookahead<=N){if(be(D),D.lookahead<=N&&ee===h)return b;if(D.lookahead===0)break}if(D.match_length=0,D.lookahead>=M&&0D.lookahead&&(D.match_length=D.lookahead)}if(D.match_length>=M?(he=a._tr_tally(D,1,D.match_length-M),D.lookahead-=D.match_length,D.strstart+=D.match_length,D.match_length=0):(he=a._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++),he&&(Y(D,!1),D.strm.avail_out===0))return b}return D.insert=0,ee===p?(Y(D,!0),D.strm.avail_out===0?W:V):D.last_lit&&(Y(D,!1),D.strm.avail_out===0)?b:B}(j,J):s[j.level].func(j,J);if(z!==W&&z!==V||(j.status=666),z===b||z===W)return A.avail_out===0&&(j.last_flush=-1),m;if(z===B&&(J===1?a._tr_align(j):J!==5&&(a._tr_stored_block(j,0,0,!1),J===3&&(Z(j.head),j.lookahead===0&&(j.strstart=0,j.block_start=0,j.insert=0))),X(A),A.avail_out===0))return j.last_flush=-1,m}return J!==p?m:j.wrap<=0?1:(j.wrap===2?(ve(j,255&A.adler),ve(j,A.adler>>8&255),ve(j,A.adler>>16&255),ve(j,A.adler>>24&255),ve(j,255&A.total_in),ve(j,A.total_in>>8&255),ve(j,A.total_in>>16&255),ve(j,A.total_in>>24&255)):(ne(j,A.adler>>>16),ne(j,65535&A.adler)),X(A),0=re.w_size&&(te===0&&(Z(re.head),re.strstart=0,re.block_start=0,re.insert=0),ee=new o.Buf8(re.w_size),o.arraySet(ee,J,he-re.w_size,re.w_size,0),J=ee,he=re.w_size),oe=A.avail_in,z=A.next_in,D=A.input,A.avail_in=he,A.next_in=0,A.input=J,be(re);re.lookahead>=M;){for(j=re.strstart,H=re.lookahead-(M-1);re.ins_h=(re.ins_h<>>=M=O>>>24,w-=M,(M=O>>>16&255)===0)B[u++]=65535&O;else{if(!(16&M)){if(!(64&M)){O=T[(65535&O)+(S&(1<>>=M,w-=M),w<15&&(S+=b[c++]<>>=M=O>>>24,w-=M,!(16&(M=O>>>16&255))){if(!(64&M)){O=k[(65535&O)+(S&(1<>>=M,w-=M,(M=u-h)>3,S&=(1<<(w-=N<<3))-1,s.next_in=c,s.next_out=u,s.avail_in=c>>24&255)+(L>>>8&65280)+((65280&L)<<8)+((255&L)<<24)}function S(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function w(L){var P;return L&&L.state?(P=L.state,L.total_in=L.total_out=P.total=0,L.msg="",P.wrap&&(L.adler=1&P.wrap),P.mode=g,P.last=0,P.havedict=0,P.dmax=32768,P.head=null,P.hold=0,P.bits=0,P.lencode=P.lendyn=new s.Buf32(v),P.distcode=P.distdyn=new s.Buf32(y),P.sane=1,P.back=-1,p):m}function T(L){var P;return L&&L.state?((P=L.state).wsize=0,P.whave=0,P.wnext=0,w(L)):m}function k(L,P){var b,B;return L&&L.state?(B=L.state,P<0?(b=0,P=-P):(b=1+(P>>4),P<48&&(P&=15)),P&&(P<8||15=V.wsize?(s.arraySet(V.window,P,b-V.wsize,V.wsize,0),V.wnext=0,V.whave=V.wsize):(B<(W=V.wsize-V.wnext)&&(W=B),s.arraySet(V.window,P,b-B,W,V.wnext),(B-=W)?(s.arraySet(V.window,P,b-B,B,0),V.wnext=B,V.whave=V.wsize):(V.wnext+=W,V.wnext===V.wsize&&(V.wnext=0),V.whave>>8&255,b.check=a(b.check,te,2,0),Y=X=0,b.mode=2;break}if(b.flags=0,b.head&&(b.head.done=!1),!(1&b.wrap)||(((255&X)<<8)+(X>>8))%31){L.msg="incorrect header check",b.mode=30;break}if((15&X)!=8){L.msg="unknown compression method",b.mode=30;break}if(Y-=4,A=8+(15&(X>>>=4)),b.wbits===0)b.wbits=A;else if(A>b.wbits){L.msg="invalid window size",b.mode=30;break}b.dmax=1<>8&1),512&b.flags&&(te[0]=255&X,te[1]=X>>>8&255,b.check=a(b.check,te,2,0)),Y=X=0,b.mode=3;case 3:for(;Y<32;){if($===0)break e;$--,X+=B[V++]<>>8&255,te[2]=X>>>16&255,te[3]=X>>>24&255,b.check=a(b.check,te,4,0)),Y=X=0,b.mode=4;case 4:for(;Y<16;){if($===0)break e;$--,X+=B[V++]<>8),512&b.flags&&(te[0]=255&X,te[1]=X>>>8&255,b.check=a(b.check,te,2,0)),Y=X=0,b.mode=5;case 5:if(1024&b.flags){for(;Y<16;){if($===0)break e;$--,X+=B[V++]<>>8&255,b.check=a(b.check,te,2,0)),Y=X=0}else b.head&&(b.head.extra=null);b.mode=6;case 6:if(1024&b.flags&&($<(ie=b.length)&&(ie=$),ie&&(b.head&&(A=b.head.extra_len-b.length,b.head.extra||(b.head.extra=new Array(b.head.extra_len)),s.arraySet(b.head.extra,B,V,ie,A)),512&b.flags&&(b.check=a(b.check,B,ie,V)),$-=ie,V+=ie,b.length-=ie),b.length))break e;b.length=0,b.mode=7;case 7:if(2048&b.flags){if($===0)break e;for(ie=0;A=B[V+ie++],b.head&&A&&b.length<65536&&(b.head.name+=String.fromCharCode(A)),A&&ie<$;);if(512&b.flags&&(b.check=a(b.check,B,ie,V)),$-=ie,V+=ie,A)break e}else b.head&&(b.head.name=null);b.length=0,b.mode=8;case 8:if(4096&b.flags){if($===0)break e;for(ie=0;A=B[V+ie++],b.head&&A&&b.length<65536&&(b.head.comment+=String.fromCharCode(A)),A&&ie<$;);if(512&b.flags&&(b.check=a(b.check,B,ie,V)),$-=ie,V+=ie,A)break e}else b.head&&(b.head.comment=null);b.mode=9;case 9:if(512&b.flags){for(;Y<16;){if($===0)break e;$--,X+=B[V++]<>9&1,b.head.done=!0),L.adler=b.check=0,b.mode=12;break;case 10:for(;Y<32;){if($===0)break e;$--,X+=B[V++]<>>=7&Y,Y-=7&Y,b.mode=27;break}for(;Y<3;){if($===0)break e;$--,X+=B[V++]<>>=1)){case 0:b.mode=14;break;case 1:if(N(b),b.mode=20,P!==6)break;X>>>=2,Y-=2;break e;case 2:b.mode=17;break;case 3:L.msg="invalid block type",b.mode=30}X>>>=2,Y-=2;break;case 14:for(X>>>=7&Y,Y-=7&Y;Y<32;){if($===0)break e;$--,X+=B[V++]<>>16^65535)){L.msg="invalid stored block lengths",b.mode=30;break}if(b.length=65535&X,Y=X=0,b.mode=15,P===6)break e;case 15:b.mode=16;case 16:if(ie=b.length){if($>>=5,Y-=5,b.ndist=1+(31&X),X>>>=5,Y-=5,b.ncode=4+(15&X),X>>>=4,Y-=4,286>>=3,Y-=3}for(;b.have<19;)b.lens[oe[b.have++]]=0;if(b.lencode=b.lendyn,b.lenbits=7,re={bits:b.lenbits},J=l(0,b.lens,0,19,b.lencode,0,b.work,re),b.lenbits=re.bits,J){L.msg="invalid code lengths set",b.mode=30;break}b.have=0,b.mode=19;case 19:for(;b.have>>16&255,ze=65535&H,!((Ee=H>>>24)<=Y);){if($===0)break e;$--,X+=B[V++]<>>=Ee,Y-=Ee,b.lens[b.have++]=ze;else{if(ze===16){for(j=Ee+2;Y>>=Ee,Y-=Ee,b.have===0){L.msg="invalid bit length repeat",b.mode=30;break}A=b.lens[b.have-1],ie=3+(3&X),X>>>=2,Y-=2}else if(ze===17){for(j=Ee+3;Y>>=Ee)),X>>>=3,Y-=3}else{for(j=Ee+7;Y>>=Ee)),X>>>=7,Y-=7}if(b.have+ie>b.nlen+b.ndist){L.msg="invalid bit length repeat",b.mode=30;break}for(;ie--;)b.lens[b.have++]=A}}if(b.mode===30)break;if(b.lens[256]===0){L.msg="invalid code -- missing end-of-block",b.mode=30;break}if(b.lenbits=9,re={bits:b.lenbits},J=l(u,b.lens,0,b.nlen,b.lencode,0,b.work,re),b.lenbits=re.bits,J){L.msg="invalid literal/lengths set",b.mode=30;break}if(b.distbits=6,b.distcode=b.distdyn,re={bits:b.distbits},J=l(h,b.lens,b.nlen,b.ndist,b.distcode,0,b.work,re),b.distbits=re.bits,J){L.msg="invalid distances set",b.mode=30;break}if(b.mode=20,P===6)break e;case 20:b.mode=21;case 21:if(6<=$&&258<=Z){L.next_out=G,L.avail_out=Z,L.next_in=V,L.avail_in=$,b.hold=X,b.bits=Y,c(L,ne),G=L.next_out,W=L.output,Z=L.avail_out,V=L.next_in,B=L.input,$=L.avail_in,X=b.hold,Y=b.bits,b.mode===12&&(b.back=-1);break}for(b.back=0;Le=(H=b.lencode[X&(1<>>16&255,ze=65535&H,!((Ee=H>>>24)<=Y);){if($===0)break e;$--,X+=B[V++]<>Ge)])>>>16&255,ze=65535&H,!(Ge+(Ee=H>>>24)<=Y);){if($===0)break e;$--,X+=B[V++]<>>=Ge,Y-=Ge,b.back+=Ge}if(X>>>=Ee,Y-=Ee,b.back+=Ee,b.length=ze,Le===0){b.mode=26;break}if(32&Le){b.back=-1,b.mode=12;break}if(64&Le){L.msg="invalid literal/length code",b.mode=30;break}b.extra=15&Le,b.mode=22;case 22:if(b.extra){for(j=b.extra;Y>>=b.extra,Y-=b.extra,b.back+=b.extra}b.was=b.length,b.mode=23;case 23:for(;Le=(H=b.distcode[X&(1<>>16&255,ze=65535&H,!((Ee=H>>>24)<=Y);){if($===0)break e;$--,X+=B[V++]<>Ge)])>>>16&255,ze=65535&H,!(Ge+(Ee=H>>>24)<=Y);){if($===0)break e;$--,X+=B[V++]<>>=Ge,Y-=Ge,b.back+=Ge}if(X>>>=Ee,Y-=Ee,b.back+=Ee,64&Le){L.msg="invalid distance code",b.mode=30;break}b.offset=ze,b.extra=15&Le,b.mode=24;case 24:if(b.extra){for(j=b.extra;Y>>=b.extra,Y-=b.extra,b.back+=b.extra}if(b.offset>b.dmax){L.msg="invalid distance too far back",b.mode=30;break}b.mode=25;case 25:if(Z===0)break e;if(ie=ne-Z,b.offset>ie){if((ie=b.offset-ie)>b.whave&&b.sane){L.msg="invalid distance too far back",b.mode=30;break}be=ie>b.wnext?(ie-=b.wnext,b.wsize-ie):b.wnext-ie,ie>b.length&&(ie=b.length),Ce=b.window}else Ce=W,be=G-b.offset,ie=b.length;for(ZC?(M=be[Ce+y[P]],Y[ve+y[P]]):(M=96,0),S=1<>G)+(w-=S)]=O<<24|M<<16|N|0,w!==0;);for(S=1<>=1;if(S!==0?(X&=S-1,X+=S):X=0,P++,--ne[L]==0){if(L===B)break;L=h[p+y[P]]}if(W>>7)]}function ve(H,te){H.pending_buf[H.pending++]=255&te,H.pending_buf[H.pending++]=te>>>8&255}function ne(H,te,oe){H.bi_valid>_-oe?(H.bi_buf|=te<>_-H.bi_valid,H.bi_valid+=oe-_):(H.bi_buf|=te<>>=1,oe<<=1,0<--te;);return oe>>>1}function Ce(H,te,oe){var z,D,ee=new Array(y+1),he=0;for(z=1;z<=y;z++)ee[z]=he=he+oe[z-1]<<1;for(D=0;D<=te;D++){var ce=H[2*D+1];ce!==0&&(H[2*D]=be(ee[ce]++,ce))}}function Ee(H){var te;for(te=0;te>1;1<=oe;oe--)Ge(H,ee,oe);for(D=ge;oe=H.heap[1],H.heap[1]=H.heap[H.heap_len--],Ge(H,ee,1),z=H.heap[1],H.heap[--H.heap_max]=oe,H.heap[--H.heap_max]=z,ee[2*D]=ee[2*oe]+ee[2*z],H.depth[D]=(H.depth[oe]>=H.depth[z]?H.depth[oe]:H.depth[z])+1,ee[2*oe+1]=ee[2*z+1]=D,H.heap[1]=D++,Ge(H,ee,1),2<=H.heap_len;);H.heap[--H.heap_max]=H.heap[1],function(Oe,He){var Lt,Pe,tt,Je,yt,nt,Ct=He.dyn_tree,Rt=He.max_code,Sn=He.stat_desc.static_tree,le=He.stat_desc.has_stree,je=He.stat_desc.extra_bits,Me=He.stat_desc.extra_base,Ie=He.stat_desc.max_length,$e=0;for(Je=0;Je<=y;Je++)Oe.bl_count[Je]=0;for(Ct[2*Oe.heap[Oe.heap_max]+1]=0,Lt=Oe.heap_max+1;Lt>=7;D>>=1)if(1&Be&&ce.dyn_ltree[2*ge]!==0)return o;if(ce.dyn_ltree[18]!==0||ce.dyn_ltree[20]!==0||ce.dyn_ltree[26]!==0)return a;for(ge=32;ge>>3,(ee=H.static_len+3+7>>>3)<=D&&(D=ee)):D=ee=oe+5,oe+4<=D&&te!==-1?j(H,te,oe,z):H.strategy===4||ee===D?(ne(H,2+(z?1:0),3),rt(H,U,L)):(ne(H,4+(z?1:0),3),function(ce,ge,Be,Oe){var He;for(ne(ce,ge-257,5),ne(ce,Be-1,5),ne(ce,Oe-4,4),He=0;He>>8&255,H.pending_buf[H.d_buf+2*H.last_lit+1]=255&te,H.pending_buf[H.l_buf+H.last_lit]=255&oe,H.last_lit++,te===0?H.dyn_ltree[2*oe]++:(H.matches++,te--,H.dyn_ltree[2*(b[oe]+h+1)]++,H.dyn_dtree[2*Y(te)]++),H.last_lit===H.lit_bufsize-1},i._tr_align=function(H){ne(H,2,3),ie(H,w,U),function(te){te.bi_valid===16?(ve(te,te.bi_buf),te.bi_buf=0,te.bi_valid=0):8<=te.bi_valid&&(te.pending_buf[te.pending++]=255&te.bi_buf,te.bi_buf>>=8,te.bi_valid-=8)}(H)}},{"../utils/common":41}],53:[function(t,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(t,r,i){(function(s){(function(o,a){if(!o.setImmediate){var c,l,u,h,p=1,m={},g=!1,v=o.document,y=Object.getPrototypeOf&&Object.getPrototypeOf(o);y=y&&y.setTimeout?y:o,c={}.toString.call(o.process)==="[object process]"?function(T){process.nextTick(function(){S(T)})}:function(){if(o.postMessage&&!o.importScripts){var T=!0,k=o.onmessage;return o.onmessage=function(){T=!1},o.postMessage("","*"),o.onmessage=k,T}}()?(h="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",w,!1):o.attachEvent("onmessage",w),function(T){o.postMessage(h+T,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(T){S(T.data)},function(T){u.port2.postMessage(T)}):v&&"onreadystatechange"in v.createElement("script")?(l=v.documentElement,function(T){var k=v.createElement("script");k.onreadystatechange=function(){S(T),k.onreadystatechange=null,l.removeChild(k),k=null},l.appendChild(k)}):function(T){setTimeout(S,0,T)},y.setImmediate=function(T){typeof T!="function"&&(T=new Function(""+T));for(var k=new Array(arguments.length-1),R=0;R"u"?s===void 0?this:s:self)}).call(this,typeof Eo<"u"?Eo:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Vhe);const P4={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(P4);var js=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},ef,tp,yu;class Hhe{constructor(...e){ef.set(this,new Map),tp.set(this,new Map),yu.set(this,new Map);for(const t of e)this.define(t)}define(e,t=!1){for(let[r,i]of Object.entries(e)){r=r.toLowerCase(),i=i.map(a=>a.toLowerCase()),js(this,yu,"f").has(r)||js(this,yu,"f").set(r,new Set);const s=js(this,yu,"f").get(r);let o=!0;for(let a of i){const c=a.startsWith("*");if(a=c?a.slice(1):a,s==null||s.add(a),o&&js(this,tp,"f").set(r,a),o=!1,c)continue;const l=js(this,ef,"f").get(a);if(l&&l!=r&&!t)throw new Error(`"${r} -> ${a}" conflicts with "${l} -> ${a}". Pass \`force=true\` to override this definition.`);js(this,ef,"f").set(a,r)}}return this}getType(e){if(typeof e!="string")return null;const t=e.replace(/^.*[/\\]/,"").toLowerCase(),r=t.replace(/^.*\./,"").toLowerCase(),i=t.length{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(const e of js(this,yu,"f").values())Object.freeze(e);return this}_getTestState(){return{types:js(this,ef,"f"),extensions:js(this,tp,"f")}}}ef=new WeakMap,tp=new WeakMap,yu=new WeakMap;new Hhe(P4)._freeze();function Fw(n){if(!n||n.type===void 0)return;const e=[{start:n.startOffset,end:n.endOffset??0}];return Object.keys(n).forEach(t=>{if(t!=="parent"){const r=n[t];fn(r)?r.forEach(i=>{e.push(Fw(i))}):e.push(Fw(r))}}),n.range={start:Math.min(...e.filter(t=>t).map(t=>(t==null?void 0:t.start)??0)),end:Math.max(...e.filter(t=>t).map(t=>(t==null?void 0:t.end)??0))},n.range}function Ghe(n){const e=h4(`${n} -`);if(e.errors.length>0)return e;lf.input=e.tokens;const t=lf.program();if(lf.errors.length>0)return{tokens:e.tokens,errors:lf.errors.map(i=>({offset:i.token.startOffset,line:i.token.startLine,column:i.token.startColumn,length:i.token.image.length,message:i.message}))};const[r]=Ihe.go(t);return r?(Fw(r),{tokens:e.tokens,cst:t,ast:r}):{tokens:e.tokens,cst:t,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]}}const y1=Object.getPrototypeOf(function*(){}).constructor;function Whe(n,e){const t=`compile-${n}`;console.time(t);const r=Ghe(e);if(console.timeEnd(t),r.errors&&r.errors.length>0)return r;if(!r.ast)return{...r,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]};const i=Dhe(r.ast);if(i.code){jK&&console.info(i.code);try{return{...r,...i,source:i.code,code:new y1("api",i.code)}}catch(s){return{errors:[{message:`unexpected error ${s.message}`,offset:0,line:0,column:0,length:0}],source:"",code:new y1("api"," ")}}}return{...r,...i,source:"",code:new y1("api"," ")}}function jhe(){const n={},e={};function t(i,s){const o=n[s];if(o)return o;const a=Whe(i,s);return n[s]=a,a}const r={ids(){return Object.keys(e)},has(i){return K(e[i])},isended(i){const s=e[i];return K(s)?s.isended():!0},halt(i){const s=e[i];return K(s)&&(s.halt(),delete e[i]),!!s},gc(){const i=r.ids();for(let s=0;s[_,S]);g.slice(m-5,m).forEach(([_,S])=>{Pn("os","build",`$grey${S+1} $grey${_}`)});const[v,y]=g[m]??[];if(Kt(v)&&K(y)){const _=(p.column??1)-1,S=_+p.length,w=_{Pn("os","build",_)}),!1}}return!!(l!=null&&l.tick(o))},once(i,s,o,a){const c=r.tick(i,s,1,o,a);return r.halt(i)&&c},message(i){const{target:s,path:o}=kO(i.target),a=e[s];if(K(a)){const c={...i,target:o};a.message(c)}}};return r}const D4=jhe();var Ar=(n=>(n.MAIN="main",n.TITLE="title",n.PLAYER="player",n.CONTENT="content",n.GADGETSTORE="gadgetstore",n.GADGETSYNC="gadgetsync",n))(Ar||{});const za={defaultplayer:oW(),software:{main:"",content:""},books:new Map,chips:new Map,loaders:new Map,chipindex:new Map,codepageindex:new Map,binaryfiles:new Map};function Bw(){return[...za.books.values()]}function $he(){const[n]=za.books.values();return n}function Yf(n){const e=$t(n);return za.books.get(n)??Bw().find(t=>t.name===e)}function zw(n,e){K(Yf(e))&&(za.software[n]=e)}function np(n){return Yf(za.software[n])}function U4(n){const e=m4([]);return Kt(n)&&(e.name=n),F4(e),eo("memory",`created [book] ${e.name}`),e}function qhe(n){let e=Yf(n);return K(e)||(e=m4([]),e.name=n),F4(e),eo("memory",`created [book] ${e.name}`),e}function Ec(n,e){let t=K(e)?qhe(e):np(n);return K(t)||(K(t)||(t=$he()),K(t)||(t=U4(e)),K(t)&&eo("memory",`opened [book] ${t.name} for ${n}`)),zw(n,t.id),t}function mu(n,e,t){const r=Ec(n);let i=Cm(r,e);if(K(i))return i;const s=d4(t);return i=fue(s==="object"?`@${e} -`:`@${s} ${e} -`,{}),pue(r,i),Yhe(i.id,r.id),Yh("memory"),i}function Up(n){const e=Ec("main");return _ue(e,n)}function Xhe(n){const e=Ec("main");return vue(e,n)}function F4(n){return za.books.set(n.id,n),n.id}function Khe(n){const e=Yf(n);e&&za.books.delete(e.id)}function Yhe(n,e){za.codepageindex.set(n,e)}function Zhe(n,e,t,r,i=xJ){if(!K(n)||!K(e)||!K(t))return;const s={...se};se.book=n,se.board=e,se.element=t,se.player=t.player??za.defaultplayer,se.isplayer=aW(t.id??"");const o=Ic(n,t),a=t.cycle??(o==null?void 0:o.cycle)??i,c=t.id??"",l=dA(t);if(D4.tick(c,xA.CODE_PAGE,mt(a)?a:i,l,r),mt(t==null?void 0:t.tickertime)&&se.timestamp-t.tickertime>$_*5&&(t.tickertime=0,t.tickertext=""),se.isplayer){const u=Up(se.player);u.inputcurrent=0}TO(s).forEach(u=>{se[u]=s[u]})}function hv(n){const e=Ec("main"),t=Cm(e,n);if(!K(e)||!K(t)||!K(se.element))return;const r=`${n}_run`,i=dA(se.element),s=(t==null?void 0:t.code)??"";D4.once(r,xA.CODE_PAGE,i,s)}function B4(n){return za.binaryfiles.get(n)}function Di(n,e=!0){var r,i,s,o,a;const t=se.words[n];if(I3(t)){const[c,l]=f_(n);if(K(c))return[c,l]}if(rue(t)){const[c,l]=O3(n);if(K(c))return[c,l]}if(V4(t)){const[c,l]=fv(n);if(K(c))return[c,l]}if(Kt(t)&&$t(t)==="rnd"){const[c,l]=Di(n+1),[u,h]=Di(l);return mt(c)&&mt(u)?[Xd(c,u),h]:mt(c)?[Xd(0,c),l]:[Xd(0,1),n+1]}if(e3(t)){const[c,l]=mw(n);if(K(c))return[c,l]}if(!K(t))return[void 0,n];if(dc(t)||mt(t)||fn(t))return[t,n+1];if(Kt(t)){const c=$t(t);if(e){const l=(r=se.get)==null?void 0:r.call(se,t);if(K(l))return[l,n+1]}switch(c){case"aligned":case"alligned":{const l=TI(se.board,se.element,se.player);return!K(se.element)||!K(l)?[0,n+1]:[se.element.x===l.x||se.element.y===l.y?1:0,n+1]}case"contact":{const l=TI(se.board,se.element,se.player);if(!K(se.element)||!K(l))return[0,n+1];const u=(l.x??0)-(((i=se.element)==null?void 0:i.x)??0),h=(l.y??0)-(((s=se.element)==null?void 0:s.y)??0);return[u===0&&Math.abs(h)<2||h===0&&Math.abs(u)<2?1:0,n+1]}case"blocked":{const[l,u]=Ve(se.words,n+1,[Ne.DIR]);return[yue(se.book,se.board,se.element,l)?1:0,u]}case"any":{const[l,u]=Ve(se.words,n+1,[Ne.KIND]),h=av(l)??"",p=bm(se.board,h);return[i3(p,l).length?1:0,u]}case"rnd":return[Xd(0,1),n+1];case"abs":{const[l,u]=Ve(se.words,n+1,[Ne.NUMBER]);return[Math.abs(l),u]}case"ceil":{const[l,u]=Ve(se.words,n+1,[Ne.NUMBER]);return[Math.ceil(l),u]}case"floor":{const[l,u]=Ve(se.words,n+1,[Ne.NUMBER]);return[Math.floor(l),u]}case"round":{const[l,u]=Ve(se.words,n+1,[Ne.NUMBER]);return[Math.round(l),u]}case"min":{const l=[];for(let u=n+1;uwn.WHITE&&nwn[e]).find(e=>K(e)&&ewn[e]).find(e=>K(e)&&e>=wn.ONBLACK)}function tN(n){if(ro(n))return n;if(z4(n))return[n];const e=V4(n);if(K(e))return[e]}function nN(n){const e=se.words[n],t=tN(e);if(ro(t))return[t,n+1];const[r,i]=Di(n),s=tN(r);return ro(s)?[s,i]:[void 0,n]}function fv(n){const e=[];let t=n;const[r,i]=nN(n);if(ro(r)&&(e.push(...r),t=i),ro(e)&&!eN(e)){const[s,o]=nN(i);eN(s)&&(t=o)}return e.length?[e,t]:[void 0,n]}function nfe(n){const e={};return n.every(t=>{const r=wn[t];K(r)&&(rString.fromCharCode(n)),ife=Ps({name:"Whitespace",pattern:/ +/}),sfe=Ps({name:"WhitespaceSkipped",pattern:/ +/,group:Br.SKIPPED}),wA=Ps({name:"Newline",line_breaks:!0,start_chars_hint:[` -`,"\r"],pattern:/\n|\r\n?/}),TA=Ps({name:"StringLiteral",pattern:/[^ $;\r\n]+/,start_chars_hint:rfe}),bA=Ps({name:"StringLiteralDouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),AA=Ps({name:"EscapedDollar",pattern:"$$"}),MA=Ps({name:"MaybeFlag",pattern:/\$[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/}),CA=Ps({name:"NumberLiteral",pattern:/\$-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?\+?/}),RA=Ps({name:"HyperLinkText",pattern:/;[^;\r\n]*/,start_chars_hint:[";"]});function ofe(n,e=""){return Ps({name:e||n,pattern:new RegExp(n.toLowerCase(),"i")})}const afe=Object.keys(Uy),H4=afe.map(n=>ofe(`\\$(${n})`,n)),cfe=[ife,wA,...H4,bA,TA,CA,AA,RA,MA],lfe=new Br(cfe,{skipValidations:!ba,ensureOptimizations:ba}),ufe=new Br([sfe,wA,...H4,bA,TA,CA,AA,RA,MA],{skipValidations:!ba,ensureOptimizations:ba});function Fy(n,e=!1){return e?ufe.tokenize(n):lfe.tokenize(n)}function Nm(n,e,t,r,i,s,o,a){return{disablewrap:!1,measureonly:!1,measuredwidth:0,writefullwidth:void 0,x:0,y:0,iseven:!0,active:{color:t,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},reset:{color:t,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},width:n,height:e,char:[],color:[],bg:[],changed(){}}}function kA(n){n.active={...n.reset}}function IA(n,e){const t=e.y;function r(){++e.x;const a=e.active.rightedge??e.width-1;!e.disablewrap&&e.x>a&&(e.x=e.active.leftedge??0,++e.y),e.x>e.measuredwidth&&(e.measuredwidth=e.x)}function i(){return e.x>=(e.active.leftedge??0)&&e.x<=(e.active.rightedge??e.width-1)&&e.y>=(e.active.topedge??0)&&e.y<=(e.active.bottomedge??e.height-1)}function s(a){for(let c=0;ce.measuredwidth&&(e.measuredwidth=e.x+1);const o=e.active.leftedge??0;if(K(e.writefullwidth)&&(e.x>o||e.y===t)){const c=(e.active.rightedge??e.width-1)-e.x;if(c>0){kA(e);const l=String.fromCharCode(e.writefullwidth).repeat(c),u=e.x+e.y*e.width;zy(u,u+l.length,e.active.color,e.active.bg,e),By(u,l,e)}}}function Fn(n,e,t){const r=Fy(n);r.tokens&&(IA(r.tokens,e),t&&kA(e))}function NA(n,e,t){const r=Fy(n);if(!r.tokens)return;const i=Nm(e,t,wn.WHITE,wn.BLACK);return i.measureonly=!0,IA(r.tokens,i),i.x>0&&++i.y,i}function By(n,e,t){let r=0;const i=n+e.length;for(let s=n;s({blink:!1}));setInterval(()=>{G4.setState(n=>({blink:!n.blink}))},333);function Ha(){return G4(n=>n.blink)}function W4(){return tb(n=>{function e(){n({render:Math.random()})}return{dither:[],render:0,changed(){setTimeout(e,0)}}})}function ffe(n){n.fill(0)}function x1(n,e,t,r,i,s){if(r<0||r>=e||i<0||i>=t)return-1;n[r+i*e]=s}const j4=ke.createContext(W4());function dfe(n,e,t){const[r]=ke.useState(()=>W4()),i=n*e,s=r.getState();return s.dither.length!==i&&(s.dither=new Array(i).fill(t),s.render=0),r}function $4(){return tb(n=>{function e(){n({render:Math.random()})}return{width:0,height:0,char:[],color:[],bg:[],render:0,changed(){setTimeout(e,0)}}})}function pfe(n,e,t,r){n.char.fill(e),n.color.fill(t),n.bg.fill(r)}function Lr(n,e,t,r,i,s){if(r<0||r>=e||i<0||i>=t)return;const o=r+i*e;TO(s).forEach(a=>{const c=s[a];K(c)&&(n[a][o]=c)})}const OA=ke.createContext($4());function LA(n,e,t,r,i){const[s]=ke.useState(()=>$4()),o=n*e,a=s.getState();return a.char.length!==o&&(a.width=n,a.height=e,a.char=new Array(o).fill(t),a.color=new Array(o).fill(r),a.bg=new Array(o).fill(i),a.render=0),s}function mfe(){return ke.useContext(OA).getState()}function gfe({item:n,context:e}){return Fn(`${n} -`,e,!0),null}const Vy=ke.createContext({sendmessage(){},sendclose(){},didclose(){}}),rN={input:{color:"$white",active:"$yellow"}};function jl(n){return n?rN.input.active:rN.input.color}function io(n,e){return typeof n==typeof e?n:e}function q4(n,e){return`vm:${n}:${e}`}function rp(n,e,t=0,r=""){return`${n.substring(0,e)}${r}${n.substring(e+t)}`}function _fe({chip:n,active:e,label:t,args:r,context:i}){var p;const[s,o,a]=[io(r[0],""),io(r[1],((p=r[1])==null?void 0:p.toString())??""),io(r[2],"")],c=a||` ${o.toUpperCase()} `,l=jl(e);Fn(`${i.iseven?"$black$onltgray":"$black$ondkcyan"}${c}${l}$onclear ${t} -`,i,!0);const u=ke.useContext(Vy),h=ke.useCallback(()=>{u.sendmessage(q4(n,s)),u.sendclose()},[n,u,s]);return _e.jsxs(_e.Fragment,{children:[e&&_e.jsx(us,{OK_BUTTON:h}),_e.jsx(cp,{hotkey:o,children:h})]})}function vfe({chip:n,active:e,label:t,args:r,context:i}){const[s,o]=[io(r[0],""),r[1]],a=jl(e);Fn(` $purple$16 ${a}${t} -`,i,!0);const c=ke.useContext(Vy),l=ke.useCallback(()=>{c.sendmessage(q4(n,s),o),c.sendclose()},[c,n,s,o]);return e&&_e.jsx(us,{OK_BUTTON:l})}function yfe({chip:n,active:e,label:t,args:r,context:i}){const[s,o,a]=[io(r[0],""),io(r[1],-1),io(r[2],-1)];let c,l;o===-1?(c=0,l=31):a===-1?(c=0,l=o):(c=o,l=a);const u=ld(n,s),h=Mb(u),p=h==null?void 0:h.value,m=p??0,g=Ha(),[v,y]=ke.useState(""),[_,S]=ke.useState(0),[w,T]=ke.useState(!1);let k=`${m}`;const R=t.trim(),C=jl(e);w&&(k=g?rp(v,_,1,"$219+"):v),i.writefullwidth=32,Fn(` # ${C}${R} $green${k}`,i,!1),i.writefullwidth=void 0,Fn(` -`,i,!1);const O=ke.useCallback(U=>{const L=U.alt?10:1;El(u,Math.min(l,m+L))},[l,m,u]),M=ke.useCallback(U=>{const L=U.alt?10:1;El(u,Math.max(c,m-L))},[c,m,u]),N=ke.useCallback(()=>{T(U=>{const L=!U;if(L){const P=`${p}`;y(P),S(P.length)}else{const P=parseFloat(v),b=isNaN(P)?0:P;El(s,Math.min(l,Math.max(c,b)))}return L})},[l,c,v,s,p]);return p!==void 0&&_e.jsxs(_e.Fragment,{children:[e&&_e.jsx(us,{MOVE_LEFT:M,MOVE_RIGHT:O,OK_BUTTON:N}),w&&_e.jsxs(mm,{blockhotkeys:!0,children:[_e.jsx(cp,{hotkey:"ctrl+c",children:()=>{console.info("copy")}}),_e.jsx(cp,{hotkey:"ctrl+v",children:()=>{console.info("paste")}}),_e.jsx(cp,{hotkey:"ctrl+a",children:()=>{console.info("select all")}}),_e.jsx(us,{MOVE_LEFT:()=>{S(U=>Math.max(0,U-1))},MOVE_RIGHT:()=>{S(U=>Math.min(v.length,U+1))},CANCEL_BUTTON:N,OK_BUTTON:N,keydown:U=>{switch($t(U.key)){case"delete":v.length>0&&y(L=>rp(L,_,1));break;case"backspace":_>0&&(y(L=>rp(L,_-1,1)),S(L=>Math.max(0,L-1)));break}U.key.length===1&&v.lengthrp(L,_,0,U.key)),S(L=>L+1))}})]})]})}function xfe({chip:n,active:e,label:t,args:r,context:i}){const[s,o,a]=[io(r[0],""),io(r[1],""),io(r[2],"")];let c,l;o===""?(c="L ",l=" H"):a===""?(c="L ",l=` ${o}`):(c=`${o} `,l=` ${a}`);const u=0,h=8,p=ld(n,s),m=Mb(p),g=(m==null?void 0:m.value)??0,v=Ha(),y=t.trim(),_=jl(e);Fn(` $red $29 ${_}${y} `,i,!1);const w=rp("----:----",g,1,`$green${e?v?"$26":"$27":"$4"}${_}`).replaceAll("-","$7").replaceAll(":","$9");Fn(`${_}${c}${w}${l} $green${g+1} -`,i,!1);const T=ke.useCallback(R=>{const C=R.alt?10:1;El(p,Math.min(h,g+C))},[h,g,p]),k=ke.useCallback(R=>{const C=R.alt?10:1;El(p,Math.max(u,g-C))},[u,g,p]);return _e.jsx(_e.Fragment,{children:e&&_e.jsx(us,{MOVE_LEFT:k,MOVE_RIGHT:T})})}function Sfe({chip:n,active:e,label:t,args:r,context:i}){const[s,...o]=[io(r[0],""),...r.slice(1)],a=0,c=o.length-1,l=ld(n,s),u=Mb(l),h=(u==null?void 0:u.value)??0,p=Ha(),m=`${o[h]}`,g=t.trim(),v=jl(e);Fn(` $dkred ? ${v}${g} `,i,!1);const y=e?p?"$26":"$27":"/";Fn(`${h+1}$green${y}${v}${c+1}`,i,!1),i.writefullwidth=32,Fn(` $green${m}`,i,!1),i.writefullwidth=void 0,Fn(` -`,i,!1);const _=ke.useCallback(w=>{const T=w.alt?10:1;El(l,Math.min(c,h+T))},[c,h,l]),S=ke.useCallback(w=>{const T=w.alt?10:1;El(l,Math.max(a,h-T))},[a,h,l]);return _e.jsx(_e.Fragment,{children:e&&_e.jsx(us,{MOVE_LEFT:S,MOVE_RIGHT:_})})}function Efe({chip:n,active:e,label:t,args:r,context:i}){const s=io(r[0],""),o=ld(n,s),a=rD(o),c=a==null?void 0:a.value,l=(c==null?void 0:c.toJSON())??"",u=Ha(),[h,p]=ke.useState(0),[m,g]=ke.useState(!1),[v,y]=ke.useState(void 0),_=`${l} `,S=t.trim(),w=jl(e);Fn(`$green $20 ${w}${S} $green`,i,!1);const T=i.x,R=i.y*i.width;i.writefullwidth=32,Fn(`${_}`,i,!1),i.writefullwidth=void 0,Fn(` -`,i,!1);const C=K(v),O=i.width-T-2,M=C?Math.min(v,h):h;let N=C?Math.max(v,h):h;C&&(N!==M&&N===h&&--N,zy(T+M+R,T+N+R,15,8,i)),m&&u&&By(T+h+R,"Û",i);function U(){K(c)&&(p(M),y(void 0),c.delete(M,N-M+1))}return _e.jsxs(_e.Fragment,{children:[e&&_e.jsx(us,{OK_BUTTON:()=>{c&&(g(!0),p(c.length),y(void 0))}}),m&&_e.jsx(mm,{blockhotkeys:!0,children:_e.jsx(us,{MOVE_LEFT:L=>{L.shift?K(v)||y(Cn(h-1,0,l.length)):y(void 0),p(P=>Cn(P-1,0,l.length))},MOVE_RIGHT:L=>{L.shift?K(v)||y(h):y(void 0),p(P=>Cn(P+1,0,l.length))},CANCEL_BUTTON:()=>{g(!1),p(l.length),y(void 0)},OK_BUTTON:()=>g(!1),keydown:L=>{if(!c)return;const{key:P}=L,b=$t(P),B={alt:L.altKey,ctrl:Vf?L.metaKey:L.ctrlKey,shift:L.shiftKey},W=c.toJSON();switch(b){case"delete":C?U():W.length>0&&c.delete(h,1);break;case"backspace":C?U():h>0&&(c.delete(h-1,1),p(V=>Math.max(0,V-1)));break;default:if(B.ctrl)switch(b){case"a":y(0),p(W.length);break;case"c":K(navigator.clipboard)&&navigator.clipboard.writeText(c.toJSON()).catch(V=>console.error(V));break;case"v":K(navigator.clipboard)&&navigator.clipboard.readText().then(V=>{C&&U(),c.insert(h,V),p(h+V.length)}).catch(V=>console.error(V));break;case"x":K(navigator.clipboard)&&navigator.clipboard.writeText(c.toJSON()).then(()=>U()).catch(V=>console.error(V));break}else B.alt||P.length===1&&W.lengthV+1));break}}})})]})}function wfe({item:n,active:e}){const t=rb(),r=Va();if(r.iseven=r.y%2===0,typeof n=="string")return _e.jsx(gfe,{player:t,item:n,context:r});if(fn(n)){const[i,s,o,...a]=n;if(typeof i!="string"||typeof s!="string"||typeof o!="string")return null;const c={player:t,chip:i,active:e,label:s,args:a,context:r};switch($t(o)){case"hk":case"hotkey":return _e.jsx(_fe,{...c});case"hyperlink":return _e.jsx(vfe,{...c});case"rn":case"range":return _e.jsx(xfe,{...c});case"sl":case"select":return _e.jsx(Sfe,{...c});case"nm":case"number":return _e.jsx(yfe,{...c});case"tx":case"text":return _e.jsx(Efe,{...c})}kA(r)}return null}function PA({store:n,children:e}){return _e.jsx(OA.Provider,{value:n,children:e})}function DA({width:n,height:e}){const t=ke.useContext(OA),[r,i,s]=nb(t,Hl(o=>[o.char,o.color,o.bg,o.render]));return n>0&&e>0&&_e.jsx(ED,{char:r.slice(),color:i.slice(),bg:s.slice(),width:n,height:e})}function X4({margin:n=1,selected:e=-1,width:t,height:r,color:i,bg:s,text:o}){const a=LA(t,r,0,i,s),c=a.getState(),l={...Nm(t,r,i,s,0,n,t-n,r),...a.getState(),x:n};return pfe(c,0,i,s),c.changed(),_e.jsxs(PA,{store:a,children:[_e.jsx(Eu.Provider,{value:l,children:o.map((u,h)=>_e.jsx(wfe,{item:u,active:h===e},h))}),_e.jsx(DA,{width:t,height:r})]})}var Tfe=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.01,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1/(2*Math.PI);return r/Math.atan(1/t)*Math.atan(Math.sin(2*Math.PI*e*i)/t)},bfe=function(e){return 1/(1+e+.48*e*e+.235*e*e*e)};function Afe(n,e,t){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:.25,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:.01,s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1/0,o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:bfe,a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:.001,c="velocity_"+e;if(n.__damp===void 0&&(n.__damp={}),n.__damp[c]===void 0&&(n.__damp[c]=0),Math.abs(n[e]-t)<=a)return n[e]=t,!1;r=Math.max(1e-4,r);var l=2/r,u=o(l*i),h=n[e]-t,p=t,m=s*r;h=Math.min(Math.max(h,-m),m),t=n[e]-h;var g=(n.__damp[c]+l*h)*i;n.__damp[c]=(n.__damp[c]-l*g)*u;var v=t+(h+g)*u;return p-n[e]>0==v>p&&(v=p,n.__damp[c]=(v-p)/i),n[e]=v,!0}const Mfe=2,Cfe=14,K4=Cfe*Mfe;function Rfe(n){return wG(n,K4*.5)}function kfe(n,e,t,r,i=1.235){function s(a){return Tfe(a,r)}Afe(n.userData,e,t,i,r,K4*12,s),n.position[e]=Rfe(n.userData[e]);const o=t-n.position.y;return Math.abs(o)<.1}function iN({x:n,y:e,color:t,on:r=232,off:i=7,alt:s}){const o=Ha(),a=mfe(),c=ke.useRef(0),l=K(s)?c.current%2===0?r:s:r;return Lr(a,a.width,a.height,n,e,{char:o?l:i,color:t}),a.changed(),o&&++c.current,null}function Ife({store:n,children:e}){return _e.jsx(j4.Provider,{value:n,children:e})}function Nfe({width:n,height:e}){const t=ke.useContext(j4),[r]=nb(t,Hl(i=>[i.dither,i.render]));return n>0&&e>0&&_e.jsx(hy,{alphas:r.slice(),width:n,height:e})}function Ofe({name:n,width:e,height:t,color:r,bg:i,text:s,shouldclose:o}){const{viewport:a}=pa(),c=e-3,l=t-3,u=LA(e,t,0,r,i),h=dfe(c,l,0),p=ke.useContext(Vy),m=u.getState();for(let b=1;b2&&b{o&&p.didclose()},[o,p]);ke.useEffect(()=>{if(N.current&&!o){const b=a.height;N.current.position.y=b,N.current.userData.y=b,N.current.userData.vy=0}},[o]),Tv(ke.useCallback((b,B)=>{if(K(N.current)){const W=o?t*2*-zi:0;kfe(N.current,"y",W,B)&&U()}},[o,U,t]));const L=ke.useCallback(b=>{const B=b.alt?10:1;w(W=>Math.max(0,W-B))},[w]),P=ke.useCallback(b=>{const B=b.alt?10:1;w(W=>Math.min(s.length,W+B))},[w,s.length]);return _e.jsx(PA,{store:u,children:_e.jsx(Ife,{store:h,children:_e.jsx("group",{ref:N,"position-y":1e6,children:_e.jsxs(mm,{children:[_e.jsx(us,{MOVE_UP:L,MOVE_DOWN:P,CANCEL_BUTTON:p.sendclose}),_e.jsx(DA,{width:e,height:t}),_e.jsxs("group",{position:[2*ss,2*zi,0],children:[_e.jsx(Nfe,{width:c,height:l}),_e.jsx(X4,{name:n,width:c,height:l,margin:0,color:r,bg:wn.ONCLEAR,text:k,selected:R}),_e.jsx(iN,{x:1,y:1}),_e.jsx(iN,{x:1,y:2+R,on:26,alt:27,off:45,color:12})]})]})})})})}function sN({rect:n,shouldclose:e=!1}){switch(n.type){case 0:return _e.jsx(X4,{name:n.name,width:n.width,height:n.height,color:14,bg:1,text:n.text});case 1:return _e.jsx(Ofe,{name:n.name,width:n.width,height:n.height,color:14,bg:1,text:n.text,shouldclose:e});case 2:return _e.jsx(Uee,{width:n.width,height:n.height})}return null}function Lfe(){const n=pa(g=>g.viewport),{width:e,height:t}=n.getCurrentViewport(),r=Math.floor(e/ss),i=Math.floor(t/zi),s=e-r*ss,o=t-i*zi,[a,c]=ke.useState(),[l,u]=is(RX(g=>[g.gadget.player,g.gadget.panels]));if(r<1||i<1)return null;const h={name:"main",type:2,x:0,y:0,width:r,height:i,text:[]},p=[];let m=!0;return u.forEach(g=>{let v;switch(g.edge){case yi.LEFT:v={name:g.name,type:0,x:h.x,y:h.y,width:g.size,height:h.height,text:g.text},h.x+=g.size,h.width-=g.size,p.push(v);break;default:case yi.RIGHT:v={name:g.name,type:0,x:h.x+h.width-g.size,y:h.y,width:g.size,height:h.height,text:g.text},h.width-=g.size,p.push(v);break;case yi.TOP:v={name:g.name,type:0,x:h.x,y:h.y,width:h.width,height:g.size,text:g.text},h.y+=g.size,h.height-=g.size,p.push(v);break;case yi.BOTTOM:v={name:g.name,type:0,x:h.x,y:h.y+h.height-g.size,width:h.width,height:g.size,text:g.text},h.height-=g.size,p.push(v);break;case yi.SCROLL:v={name:g.name,type:1,x:0,y:0,width:Cn(g.size||50,24,h.width-2),height:Cn(18,8,h.height-8),text:g.text},v.x=h.x+Math.floor((h.width-v.width)*.5),v.y=h.y+Math.floor((h.height-v.height)*.5),m=!1,Rf(a,v)||c(Ui(v))}}),p.unshift(h),_e.jsx(Vy.Provider,{value:{sendmessage(g,v){Yt.emit(g,"gadget",v,l)},sendclose(){hW("gadget",l)},didclose(){c(void 0)}},children:_e.jsxs("group",{position:[s*.5,o*.5,-512],children:[p.map(g=>_e.jsx("group",{position:[g.x*ss,g.y*zi,0],children:_e.jsx(sN,{rect:g})},g.name)),a&&_e.jsxs(bo.Fragment,{children:[_e.jsx("group",{position:[0,0,800],children:_e.jsx(cee,{width:r,height:i,alpha:.14})}),_e.jsx("group",{position:[a.x*ss,a.y*zi,900],children:_e.jsx(sN,{rect:a,shouldclose:m})})]},a.name)]})})}const Pfe=250,Dfe=249,Fp=wn.BLUE,Ufe=wn.WHITE,Ul=wn.DKBLUE,Ffe=wn.DKGRAY,Y4=wn.BLACK,dv=1,S1=ss*dv,E1=zi*dv,Z4=ke.createContext({sendmessage(){}});function wf(n,e,t,r,i){const s=Wo(i);i.iseven=i.y%2===0,i.active.bg=e&&!n?Y4:Ul,i.active.leftedge=s.left,i.active.rightedge=s.right,i.active.topedge=s.top,i.active.bottomedge=s.bottom,i.x=i.active.leftedge+t,i.y=i.active.topedge+r}function uf(n,e,t,r,i,s,o,a){const c=Wo(i);i.iseven=i.y%2===0,i.active.bg=Ul,i.active.leftedge=c.left+s,i.active.rightedge=c.right-s,i.active.topedge=c.top+o,i.active.bottomedge=c.bottom-a,i.x=i.active.leftedge+t,i.y=i.active.topedge+r}function Bfe(n){let e=0;return n.split(/\r?\n/).map(r=>{const i=e,s=`${r} -`;return e+=s.length,{start:i,code:s,end:i+r.length}})}function zfe(n){return n.reduce((e,t)=>{const r=t.code.length;return r>e?r:e},0)}function Vfe(n,e){for(let t=0;t{const e="nativeEvent"in n?n.nativeEvent:n;return{deltaX:e.deltaX||0,deltaY:e.deltaY||0,deltaZ:e.deltaZ||0,timeStamp:e.timeStamp}},jfe=n=>[n.deltaX,n.deltaY,n.deltaZ],L0=n=>{const e=jfe(n).map(Math.abs);return Math.max(...e)};var dl;(function(n){n.ALL_OTHER_CHECKS_FAILED="ALL_OTHER_CHECKS_FAILED",n.NO_PREVIOUS_EVENT_TO_COMPARE="NO_PREVIOUS_EVENT_TO_COMPARE",n.PAST_TIMESTAMP_EVENT="PAST_TIMESTAMP_EVENT",n.ENOUGH_TIME_PASSED="ENOUGH_TIME_PASSED",n.NON_DECREASING_DELTAS_OF_KNOWN_HUMAN="NON_DECREASING_DELTAS_OF_KNOWN_HUMAN",n.DELTA_MODULE_HAS_BEEN_INCREASING="DELTA_MODULE_HAS_BEEN_INCREASING"})(dl||(dl={}));class $fe{constructor({sensitivity:e=2,delay:t=100,increasingDeltasThreshold:r=3}={}){vt(this,"sensitivity");vt(this,"delay");vt(this,"increasingDeltasThreshold");vt(this,"previousEvents");this.sensitivity=Math.max(1,e),this.delay=Math.max(1,t),this.increasingDeltasThreshold=Math.max(2,r),this.previousEvents=[]}check(e){var s;if(!(("nativeEvent"in e?e.nativeEvent:e)instanceof Event))throw new Error(`"${e}" is not a valid event`);const r=Wfe(e);if(L0(r)(((s=this.previousEvents.at(-1))==null?void 0:s.timeStamp)||0)&&this.previousEvents.push(r),i}isHuman(e){const t=this.previousEvents.at(-1);if(!t)return{isHuman:!0,reason:dl.NO_PREVIOUS_EVENT_TO_COMPARE};if(e.timeStampt.timeStamp+this.delay)return{isHuman:!0,reason:dl.ENOUGH_TIME_PASSED};const s=L0(e),o=L0(t);if(s>=o){if(this.previousEvents.length===1)return{isHuman:!0,reason:dl.NON_DECREASING_DELTAS_OF_KNOWN_HUMAN};if(this.increasingDeltasThreshold<=2||this.previousEvents.length>=this.increasingDeltasThreshold&&this.previousEvents.slice(-this.increasingDeltasThreshold).map(L0).every((u,h,p)=>h===0||u>p[h-1]))return{isHuman:!0,reason:dl.DELTA_MODULE_HAS_BEEN_INCREASING}}return{isHuman:!1,reason:dl.ALL_OTHER_CHECKS_FAILED}}}function oN(){}const qfe=bo.forwardRef(function({args:e,children:t,...r},i){const s=bo.useRef(null);return bo.useImperativeHandle(i,()=>s.current),_e.jsxs("mesh",{ref:s,...r,children:[_e.jsx("planeGeometry",{attach:"geometry",args:e}),t]})}),Xfe=bo.forwardRef(function({blocking:e=!1,cursor:t="default",x:r=0,y:i=0,width:s=1,height:o=1,opacity:a=1,visible:c=!0,...l},u){const h=s*.5,p=o*.5,m=[(r+h)*ss,(i+p)*zi,0],g=cy();return _e.jsx(qfe,{ref:u,args:[s*ss,o*zi],userData:{blocking:e,cursor:t,clippingPlanes:g},onClick:e?oN:void 0,onPointerMove:e?oN:void 0,position:m,...l,children:_e.jsx("meshBasicMaterial",{color:"white",opacity:a,visible:c,transparent:a!==1,clippingPlanes:g})})}),Kfe=new $fe({sensitivity:Vf?7:2}),aN=4,Yfe=.75;function Zfe(n){const e=Cn(n,-aN,aN);return Math.round(e*Yfe)}function J4({debug:n=!1,disabled:e=!1,blocking:t=!0,cursor:r="pointer",x:i=0,y:s=0,width:o=30,height:a=10,children:c,onScroll:l,...u}){return _e.jsxs("group",{...u,children:[_e.jsx(Xfe,{blocking:t,cursor:r,visible:n,x:i,y:s,width:o,height:a,onWheel:h=>{e||!Kfe.check(h)||l==null||l(Zfe(h.deltaY))}}),c]})}function Qfe({tapeycursor:n,logrowtotalheight:e}){const t=Ha(),r=Va(),i=Tr(),s=rb(),o=Wo(r),a=i.buffer[i.bufferindex];let c=i.xcursor,l=i.xcursor,u=!1;K(i.xselect)&&K(i.yselect)&&(u=!0,c=Math.min(i.xcursor,i.xselect),l=Math.max(i.xcursor,i.xselect),i.xcursor!==i.xselect&&--l);const h=l-c+1,p=i.ycursor===0,m=u?a.substring(c,l+1):a;function g(O,M,N){i.bufferindex>0&&Tr.setState({bufferindex:0}),i.buffer[0]=Hfe(a,O,M,N),Tr.setState({buffer:i.buffer,xselect:void 0,xcursor:O+(N??"").length})}function v(O){const M=i.buffer.length-1,N=Cn(O,0,M);Tr.setState({bufferindex:N,xcursor:i.buffer[N].length,ycursor:0,xselect:void 0,yselect:void 0})}function y(O){O?K(i.xselect)||Tr.setState({xselect:i.xcursor,yselect:i.ycursor}):Tr.setState({xselect:void 0,yselect:void 0})}function _(){K(i.xselect)&&(Tr.setState({xcursor:c,xselect:void 0,yselect:void 0}),g(c,h))}function S(){Tr.setState({xcursor:a.length,ycursor:0,xselect:void 0,yselect:void 0})}wf(!1,!1,0,0,r);const w="main:0.20.26 - if lost try #help";r.x=o.right-w.length,Fn(`$dkcyan${w}`,r,!0);const T="$196",R="$205".repeat(o.width-6);wf(!1,!1,0,o.height-2,r),Fn(` ${T}${R}${T} `,r,!0);const C=a.padEnd(o.width," ");if(wf(!1,!1,0,o.height-1,r),Fn(C,r,!0),K(i.xselect)&&K(i.yselect)&&i.xcursor!==i.xselect){const O=Math.min(i.xcursor,i.xselect),M=Math.min(i.ycursor,i.yselect),N=Math.max(i.xcursor,i.xselect)-1,U=Math.max(i.ycursor,i.yselect);for(let L=M;L<=U;++L){const P=O+(o.bottom-L)*o.width,b=N+(o.bottom-L)*o.width;zy(P,b,15,8,r)}}if(t){const O=o.left+i.xcursor,M=o.top+n;By(O+M*r.width,"Ý",r)}return ke.useEffect(()=>{let O=i.scroll;n<4&&O++,n>o.bottom-4&&O--,Tr.setState({scroll:Math.round(Cn(O,0,e))})},[i.scroll,n,e,o.bottom]),r.changed(),_e.jsxs(_e.Fragment,{children:[_e.jsx(J4,{blocking:!0,x:o.left,y:o.top,width:o.width,height:o.height,onScroll:O=>{y(!1),Tr.setState({ycursor:Cn(Math.round(i.ycursor-O),0,e)})}}),_e.jsx(us,{keydown:O=>{const{key:M}=O,N=$t(M),U=dy(O);switch(N){case"arrowleft":y(U.shift),U.ctrl?Tr.setState({xcursor:0}):Tr.setState({xcursor:Cn(i.xcursor-(U.alt?10:1),0,o.right)});break;case"arrowright":y(U.shift),U.ctrl?Tr.setState({xcursor:p?a.length:o.right}):Tr.setState({xcursor:Cn(i.xcursor+(U.alt?10:1),0,o.right)});break;case"arrowup":U.ctrl?v(i.bufferindex+1):(y(U.shift),Tr.setState({ycursor:Cn(Math.round(i.ycursor+(U.alt?10:1)),0,e)}));break;case"arrowdown":U.ctrl?v(i.bufferindex-1):(y(U.shift),Tr.setState({ycursor:Cn(Math.round(i.ycursor-(U.alt?10:1)),0,e)}));break;case"enter":{const L=u?m:a;L.length&&(p?(Tr.setState({xcursor:0,bufferindex:0,xselect:void 0,yselect:void 0,buffer:["",L,...i.buffer.slice(1).filter(P=>P!==L)]}),Av("tape",L,s)):S());break}case"esc":case"escape":hT("tape");break;case"tab":IO("tape",!U.shift);break;case"delete":p?u?_():a.length>0&&g(i.xcursor,1):S();break;case"backspace":p?u?_():i.xcursor>0&&g(i.xcursor-1,1):S();break;default:if(U.ctrl)switch(N){case"a":Tr.setState({xselect:0,yselect:0,xcursor:a.length,ycursor:0});break;case"c":p&&K(navigator.clipboard)?navigator.clipboard.writeText(m).catch(L=>console.error(L)):S();break;case"v":p&&K(navigator.clipboard)?navigator.clipboard.readText().then(L=>{const P=L.replaceAll("\r","");u?g(c,h,P):g(i.xcursor,0,P)}).catch(L=>console.error(L)):S();break;case"x":p&&K(navigator.clipboard)?navigator.clipboard.writeText(m).then(()=>_()).catch(L=>console.error(L)):S();break}else U.alt||M.length===1&&(p&&i.xcursor<=a.length?u?(g(c,h,M),Tr.setState({xselect:void 0})):g(i.xcursor,0,M):S());break}}})]})}function Jfe({blink:n,active:e,prefix:t,label:r,words:i,y:s}){const o=Va(),a=ke.useCallback(()=>{if(K(navigator.clipboard)){const[,...l]=i,u=l.join(" ");navigator.clipboard.writeText(u).then(()=>un("copyit","copied!")).catch(h=>console.error(h))}},[i]),c=jl(!!e);return wf(!!n,!!e,0,s,o),Fn(`${t} $purple$16 $yellowCOPYIT ${c}${r}`,o,!0),o.changed(),e&&_e.jsx(us,{OK_BUTTON:a})}function ede({blink:n,active:e,prefix:t,label:r,words:i,y:s}){const o=Va(),a=ke.useContext(Z4),c=ke.useCallback(()=>{const[u,h]=i;a.sendmessage(u,h)},[i,a]),l=jl(!!e);return wf(!!n,!!e,0,s,o),Fn(`${t} $purple$16 ${l}${r}`,o,!0),o.changed(),e&&_e.jsx(us,{OK_BUTTON:c})}function eF({blink:n,active:e,text:t,y:r}){const i=Va(),s=Wo(i),o=t.startsWith("!");if(wf(!!n,!!e,0,r,i),i.active.bottomedge=s.bottom,Fn(o?"":t,i,!0),o){const[a,...c]=t.slice(1).split("!"),l=`${c.join("!")}`;let u="PRESS ME";const h=[];Fy(l,!0).tokens.forEach(y=>{switch(y.tokenType){case RA:u=y.image.slice(1);break;default:h.push(y.image);break}});const[m,...g]=h,v={blink:n,active:e,prefix:a,label:u,words:g,y:r};switch($t(m)){case"hk":case"hotkey":return null;case"rn":case"range":return null;case"sl":case"select":return null;case"nm":case"number":return null;case"tx":case"text":return null;case"copyit":return _e.jsx(Jfe,{...v,words:h});default:case"hyperlink":return _e.jsx(ede,{...v,words:h})}}return null}function tde(n){const e=Ha();return _e.jsx(eF,{active:!0,blink:e,...n})}function w1(){const n=rb(),[e,t]=Ji(Hl(p=>[p.terminal.logs,p.editor.open])),r=Va(),i=Tr(),s=Wo(r),o=e.map(p=>{const[,m,g,...v]=p;let y="$white";switch(m){case"debug":y="$yellow";break;case"error":y="$red";break}const _=v.map(T=>`${T}`).join(" "),S=_.startsWith("!"),w=`$blue[${y}${g}$blue]`;return`${S?"!":""}${w} ${_}`}),a=o.map(p=>{if(p.startsWith("!"))return 1;const m=NA(p,s.width,s.height);return(m==null?void 0:m.y)??1});let c=0,l=s.bottom-1;const u=a.map(p=>(l-=p,c+=p,l));++c;const h=s.bottom-i.ycursor+i.scroll;return _e.jsxs(_e.Fragment,{children:[_e.jsx(UA,{context:r}),_e.jsxs(Z4.Provider,{value:{sendmessage(p,m){const[g,v]=Gfe(p);if(g==="self"){const y=`#${v} ${m??""}`;Av("tape",y,n)}else Yt.emit(`${g}:${v}`,"gadget",m,n)}},children:[o.map((p,m)=>{const g=u[m]+i.scroll,v=a[m],y=g+v;return y<0||g>s.bottom-1?null:!t&&h>=g&&h[m.editor.type,m.editor.title])),o=Ha(),a="$205".repeat(e.width-4);uf(!1,!1,0,1,n,0,0,0),Fn(`$179$${o?"7":"232"}$200${a}$181`,n,!0);const l=` ${`[${i}] `}${s} `,u=NA(l,e.width,e.height),h=(u==null?void 0:u.measuredwidth)??1,p=Math.round(e.width*.5)-Math.round(h*.5);return uf(!1,!1,p,0,n,0,0,0),Fn(l,n,!0),n.changed(),null}function rde({xcursor:n,ycursor:e,xoffset:t,yoffset:r,rows:i,codepage:s}){var P,b;const o=Ha(),a=Va(),c=ke.useRef(),l=hr(),u=Wo(a),h=Ji(B=>B.editor.player),p=Q4(s),m=K(p)?p.toJSON():"",g=i.length-1,v=n+1-t,y=e+2-r;if(K(s)){const B=((P=c.current)==null?void 0:P.x)!==v||((b=c.current)==null?void 0:b.y)!==y;if(o||B){const W=u.left+v,V=u.top+y;V>u.top+1&&Vu.left&&W0&&(p==null||p.delete(B,W)),K(V)&&(p==null||p.insert(B,V)),hr.setState({cursor:B+(V??"").length,select:void 0})}function N(){K(l.select)&&(hr.setState({cursor:w}),M(w,R))}function U(){hr.setState({cursor:_,select:void 0})}const L=ke.useCallback(function(W){const V=Math.round(e+W);if(V<0)hr.setState({cursor:0});else if(V>g)hr.setState({cursor:_});else{const G=i[V];hr.setState({cursor:G.start+Math.min(n,G.code.length-1)})}},[_,i,g,n,e]);return a.changed(),_e.jsxs(_e.Fragment,{children:[_e.jsx(J4,{blocking:!0,x:u.left,y:u.top,width:u.width,height:u.height,onScroll:B=>L(B*.75)}),_e.jsx(us,{keydown:B=>{if(!K(p))return;const{key:W}=B,V=$t(W),G=dy(B);switch(V){case"arrowleft":if(O(G.shift),G.ctrl)hr.setState({cursor:S.start});else{const $=l.cursor-(G.alt?10:1);hr.setState({cursor:Cn($,0,_)})}break;case"arrowright":if(O(G.shift),G.ctrl)hr.setState({cursor:S.end});else{const $=l.cursor+(G.alt?10:1);hr.setState({cursor:Cn($,0,_)})}break;case"arrowup":O(G.shift),G.ctrl?hr.setState({cursor:0}):L(G.alt?-10:-1);break;case"arrowdown":O(G.shift),G.ctrl?hr.setState({cursor:_}):L(G.alt?10:1);break;case"enter":K(p)&&(p.insert(l.cursor,` -`),hr.setState({cursor:l.cursor+1}));break;case"esc":case"escape":G.shift||G.alt||G.ctrl?hT("tape"):SW("editor");break;case"tab":IO("editor",!G.shift);break;case"delete":k?N():M(l.cursor,1);break;case"backspace":k?N():m.length>0&&M(Math.max(l.cursor-1,0),1);break;default:if(G.ctrl)switch(V){case"a":hr.setState({cursor:_,select:0});break;case"c":K(navigator.clipboard)?navigator.clipboard.writeText(C).catch($=>Pn("tape","clipboard",$)):U();break;case"v":K(navigator.clipboard)?navigator.clipboard.readText().then($=>{const Z=$.replaceAll("\r","");k?M(w,R,Z):M(l.cursor,0,Z)}).catch($=>Pn("tape","clipboard",$)):U();break;case"x":K(navigator.clipboard)?navigator.clipboard.writeText(C).then(()=>N()).catch($=>Pn("tape","clipboard",$)):U();break;case"p":Av("editor",C,h),un("editor",`running: ${C}`);break}else if(!G.alt){if(W.length===1)if(k)M(w,R,W);else{const $=l.cursor+W.length;p.insert(l.cursor,W),hr.setState({cursor:$})}}break}}})]})}function ide({ycursor:n,xoffset:e,yoffset:t,rows:r,codepage:i}){const s=Ha(),o=Va(),a=hr(),c=Wo(o);if(!K(i)){const m=(s?"|":"-").repeat(3);return uf(!1,!1,0,0,o,1,2,1),Fn(` ${m} LOADING ${m}`,o,!0),null}let l=a.cursor,u=a.cursor,h=!1;K(a.select)&&(h=!0,l=Math.min(a.cursor,a.select),u=Math.max(a.cursor,a.select),a.cursor!==a.select&&--u);const p=c.left+1;uf(!1,!1,-e,-t,o,1,2,1);for(let m=0;m=l){const _=Math.max(g.start,l)-g.start-e,S=Math.min(g.end,u)-g.start-e,w=c.width-3,T=1+o.y*o.width,k=Math.max(0,_),R=Math.min(w,S);k<=w&&R>=p&&zy(T+k,T+R,Ufe,Ffe,o)}if(++o.y,o.y>=c.bottom)break}return o.disablewrap=!1,null}function T1(){const[n]=Ji(Hl(v=>[v.editor])),e=Va(),t=hr(),r=rD(NO(n.book,n.page)),i=Wo(e);ke.useEffect(()=>(CW("editor",n.book,n.page,n.player),()=>{RW("editor",n.book,n.page,n.player)}),[n.book,n.page,n.player]);const s=Q4(r),o=K(s)?s.toJSON():"",a=Bfe(o),c=Vfe(t.cursor,a),l=t.cursor-a[c].start,u=zfe(a),h={rows:a,xcursor:l,ycursor:c,codepage:r,xoffset:t.xscroll,yoffset:t.yscroll},p=32,m=(Math.round(u/p)+1)*p,g=a.length;return ke.useEffect(()=>{let v=t.xscroll;const y=l-v,_=i.width-3;let S=Math.round(Cn(Math.abs(y)*.5,1,p));S<8&&(S=1),y>_-8&&(v+=S),y<8&&(v-=S);let w=t.yscroll;const T=c-w,k=i.height-4,R=Math.round(k*.5);let C=Math.round(Cn(Math.abs(T)*.25,1,R));C<8&&(C=1),T>k-4&&(w+=C),T<4&&(w-=C),setTimeout(()=>hr.setState({xscroll:Math.round(Cn(v,0,m)),yscroll:Math.round(Cn(w,0,g))}),16)},[l,m,t.xscroll,c,g,t.yscroll,i.width,i.height]),_e.jsxs(_e.Fragment,{children:[_e.jsx(UA,{context:e}),_e.jsx(nde,{}),_e.jsx(ide,{...h}),_e.jsx(rde,{...h})]})}function cN(n,e,t,r,i){return{...i,x:n,y:e,reset:{...i.reset,topedge:e,leftedge:n,rightedge:t,bottomedge:r},active:{...i.reset,topedge:e,leftedge:n,rightedge:t,bottomedge:r}}}function sde({context:n}){const[e,t]=Ji(Hl(l=>[l.layout,l.editor.open])),r=n.width-1,i=n.height-1,s=Wo(n),o=Math.floor(s.height*.5),a=ke.useMemo(()=>cN(0,0,r,o-1,n),[o,r,n]),c=ke.useMemo(()=>cN(0,o,r,i,n),[o,r,i,n]);if(t){let l,u;switch(e){case Oi.SPLIT_Y:case Oi.SPLIT_Y_ALT:l=a,u=c;break}if(K(l)&&K(u))switch(e){case Oi.SPLIT_Y:return _e.jsxs(_e.Fragment,{children:[_e.jsx(Eu.Provider,{value:l,children:_e.jsx(w1,{})}),_e.jsx(Eu.Provider,{value:u,children:_e.jsx(T1,{})})]});case Oi.SPLIT_Y_ALT:return _e.jsxs(_e.Fragment,{children:[_e.jsx(Eu.Provider,{value:l,children:_e.jsx(T1,{})}),_e.jsx(Eu.Provider,{value:u,children:_e.jsx(w1,{})})]})}}return _e.jsx(_e.Fragment,{children:_e.jsx(Eu.Provider,{value:n,children:t?_e.jsx(T1,{}):_e.jsx(w1,{})})})}function ode(){const n=pa(_=>_.viewport),{width:e,height:t}=n.getCurrentViewport(),r=Math.floor(e/ss),i=Math.floor(t/zi),s=Math.floor(e/S1),o=Math.floor(t/E1),a=e-s*S1,c=t-o*E1;let l=0;const u=0,h=s;let p=o;const[m,g]=Ji(Hl(_=>[_.layout,_.terminal.open]));switch(m){case Oi.TOP:p=Math.round(o*.5);break;case Oi.BOTTOM:p=Math.round(o*.5),l=o-p;break;default:case Oi.FULL:break}const v=LA(h,p,0,Fp,Ul),y={...Nm(h,p,Fp,Ul),...v.getState()};return h<1||p<1?null:_e.jsx(PA,{store:v,children:_e.jsxs("group",{position:[0,0,900],children:[g&&_e.jsx(lee,{width:r,height:i,top:l,left:u,right:u+h-1,bottom:l+p-1}),_e.jsx("group",{position:[a*.5+u*S1,c+l*E1,1],scale:[dv,dv,1],children:g?_e.jsxs(mm,{blockhotkeys:!0,children:[_e.jsx(UA,{context:y}),_e.jsx(sde,{context:y}),_e.jsx(DA,{width:h,height:p})]}):_e.jsx(cp,{hotkey:"Shift+?",children:()=>yW("tape")})})]})})}sT({OrthographicCamera:Sv});kJ();function ade(){const n=pa(p=>p.viewport),e=ke.useRef(null),{width:t,height:r}=n.getCurrentViewport(),i=ib(tY);i.minFilter=vr,i.magFilter=vr;const[s]=ke.useState(()=>new HK);ke.useEffect(()=>{if(!WK)return;document.body.appendChild(s.dom),s.showPanel(0),s.dom.style.cssText="position:fixed;bottom:0;left:0;";const p=cG(()=>s.begin()),m=lG(()=>s.end());return()=>{document.body.removeChild(s.dom),p(),m()}},[s]);const[o,a]=ke.useState();ke.useEffect(()=>{zK({benchmarksURL:"/benchmarks-min"}).then(a).catch(p=>Pn("gpu","detect",p))},[]);const c=!$K&&o&&o.tier>2&&!o.isMobile,l=pa(({set:p})=>p),u=pa(({size:p})=>p),h=pa(({camera:p})=>p);return ke.useLayoutEffect(()=>{var p;(p=e.current)==null||p.updateProjectionMatrix()}),ke.useLayoutEffect(()=>{const p=h;return l(()=>({camera:e.current})),()=>l(()=>({camera:p}))},[l,h,e]),_e.jsxs(_e.Fragment,{children:[_e.jsx("orthographicCamera",{ref:e,left:u.width/-2,right:u.width/2,top:u.height/2,bottom:u.height/-2,near:1,far:2e3,position:[0,0,1e3]}),_e.jsx("group",{"scale-x":-1,"rotation-z":Math.PI,children:_e.jsx("group",{position:[t*-.5,r*-.5,0],children:_e.jsxs(mm,{children:[_e.jsx(Lfe,{}),_e.jsx(ode,{})]})})}),c&&_e.jsx(OK,{children:_e.jsx(eY,{splat:i,viewheight:r})})]})}sT({BufferGeometry:Do,Group:qd,Mesh:wo,MeshBasicMaterial:Jw,OrthographicCamera:Sv,PlaneGeometry:Gp,Points:kH});document.addEventListener("keydown",()=>{od()});window.addEventListener("touchstart",()=>{od()});window.addEventListener("click",()=>{od()});window.addEventListener("dragover",n=>{n.preventDefault()});window.addEventListener("contextmenu",n=>{od(),n.preventDefault()});window.addEventListener("paste",n=>{var t;if(!((t=n.clipboardData)!=null&&t.files.length))return;od(),n.preventDefault(),[...n.clipboardData.files].forEach(r=>EE("loadfile",r,F_()))});window.addEventListener("drop",n=>{var e,t;od(),n.preventDefault(),(e=n.dataTransfer)!=null&&e.items?[...n.dataTransfer.items].forEach(i=>{if(i.kind==="file"){const s=i.getAsFile();K(s)&&EE("loadfile",s,F_())}}):[...((t=n.dataTransfer)==null?void 0:t.files)??[]].forEach(i=>EE("loadfile",i,F_()))});function cde(){return _e.jsx(ade,{})}const lN=new xe,uN=new xe,hN=n=>({..._G(n),filter:e=>{const t=e.filter(o=>!(!o.object.visible||(o.object.userData.clippingPlanes??[]).some(c=>(c.projectPoint(o.point,lN),uN.subVectors(o.point,lN).normalize().round(),c.normal.equals(uN)===!1)))),r=t.findIndex(o=>o.object.userData.blocking),i=r===-1?t:t.slice(0,r+1);let s="default";return i.some(o=>o.object.userData.cursor?(s=o.object.userData.cursor,!0):!1),document.querySelectorAll("html, body").forEach(o=>{o.style.cursor=s}),i}}),fN=document.querySelector("canvas");if(K(fN)){const n=pG(fN),e={dpr:1,flat:!0,linear:!0,shadows:!1,gl:{alpha:!1,stencil:!1,antialias:!1,preserveDrawingBuffer:!0}};n.configure({...e,events:hN,onCreated({gl:r}){r.localClippingEnabled=!0}});const t=yG((r,i)=>{n.configure({...e,events:hN,size:{width:r,height:i,top:0,left:0},onCreated({gl:s}){s.localClippingEnabled=!0}})},256);window.addEventListener("resize",()=>{t(OR(window.innerWidth),OR(window.innerHeight))}),n.render(_e.jsx(cde,{}))}});export default lde(); diff --git a/assets/instance-Bxjt_sve.js b/assets/instance-BmWSmEhW.js similarity index 78% rename from assets/instance-Bxjt_sve.js rename to assets/instance-BmWSmEhW.js index e9732b97..861abfc9 100644 --- a/assets/instance-Bxjt_sve.js +++ b/assets/instance-BmWSmEhW.js @@ -1,13 +1,13 @@ -var YM=Object.defineProperty;var QM=(cr,Ue,Bt)=>Ue in cr?YM(cr,Ue,{enumerable:!0,configurable:!0,writable:!0,value:Bt}):cr[Ue]=Bt;var ye=(cr,Ue,Bt)=>QM(cr,typeof Ue!="symbol"?Ue+"":Ue,Bt);(function(){"use strict";const cr=new Set,Ue={emit(e,t,n,r){Ue.invoke(yb(e,t,n,r))},invoke(e){cr.forEach(t=>t.handle(e))},connect(e){cr.add(e)},disconnect(e){cr.delete(e)}};var Bt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Pi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function tb(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var ih={};(function(e){var t=Bt&&Bt.__spreadArray||function(l,u,f){if(f||arguments.length===2)for(var d=0,h=u.length,p;df.length?u:f})}function i(l){return l.reduce(function(u,f){return u.lengthcrypto.getRandomValues(new Uint8Array(e)),sb=(e,t,n)=>{let r=(2<{let o="";for(;;){let a=n(i),c=i;for(;c--;)if(o+=e[a[c]&r]||"",o.length===s)return o}}},sh=(e,t=21)=>sb(e,t,ib),ob=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e));for(;e--;)t+=rb[n[e]&63];return t};var oh="abcdefghijklmnopqrstuvwxyz",ah="ABCDEFGHIJKLMNOPQRSTUVWXYZ",ch="0123456789",ab="346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz",cb="6789BCDFGHJKLMNPQRTWbcdfghjkmnpqrtwz";const lb=ch,ub=oh,fb=ah;var hb=lb+ub+fb,jc={lowercase:oh,uppercase:ah,numbers:ch,nolookalikes:ab,nolookalikesSafe:cb,alphanumeric:hb};function ht(){return`sid_${ob(12).replaceAll("-",".")}`}const db=sh(jc.numbers,4),pb=sh(`${jc.numbers}${jc.lowercase}`,16);function mb(){return`pid_${db()}_${pb()}`}function lh(e){return(e==null?void 0:e.startsWith("pid_"))??!1}function gb(){return nb({capitalize:!1,adjectiveCount:1})}var be=(e=>(e[e.BLACK=0]="BLACK",e[e.DKBLUE=1]="DKBLUE",e[e.DKGREEN=2]="DKGREEN",e[e.DKCYAN=3]="DKCYAN",e[e.DKRED=4]="DKRED",e[e.DKPURPLE=5]="DKPURPLE",e[e.DKYELLOW=6]="DKYELLOW",e[e.LTGRAY=7]="LTGRAY",e[e.DKGRAY=8]="DKGRAY",e[e.BLUE=9]="BLUE",e[e.GREEN=10]="GREEN",e[e.CYAN=11]="CYAN",e[e.RED=12]="RED",e[e.PURPLE=13]="PURPLE",e[e.YELLOW=14]="YELLOW",e[e.WHITE=15]="WHITE",e[e.ONBLACK=16]="ONBLACK",e[e.ONDKBLUE=17]="ONDKBLUE",e[e.ONDKGREEN=18]="ONDKGREEN",e[e.ONDKCYAN=19]="ONDKCYAN",e[e.ONDKRED=20]="ONDKRED",e[e.ONDKPURPLE=21]="ONDKPURPLE",e[e.ONDKYELLOW=22]="ONDKYELLOW",e[e.ONLTGRAY=23]="ONLTGRAY",e[e.ONDKGRAY=24]="ONDKGRAY",e[e.ONBLUE=25]="ONBLUE",e[e.ONGREEN=26]="ONGREEN",e[e.ONCYAN=27]="ONCYAN",e[e.ONRED=28]="ONRED",e[e.ONPURPLE=29]="ONPURPLE",e[e.ONYELLOW=30]="ONYELLOW",e[e.ONWHITE=31]="ONWHITE",e[e.ONCLEAR=32]="ONCLEAR",e[e.ONSHADOW=33]="ONSHADOW",e[e.ONBORROW=34]="ONBORROW",e))(be||{}),Ye=(e=>(e[e.ISWALK=0]="ISWALK",e[e.ISSOLID=1]="ISSOLID",e[e.ISSWIM=2]="ISSWIM",e[e.ISBULLET=3]="ISBULLET",e))(Ye||{}),Uo=(e=>(e[e.ISTERRAIN=0]="ISTERRAIN",e[e.ISOBJECT=1]="ISOBJECT",e))(Uo||{}),ae=(e=>(e[e.IDLE=0]="IDLE",e[e.NORTH=1]="NORTH",e[e.SOUTH=2]="SOUTH",e[e.WEST=3]="WEST",e[e.EAST=4]="EAST",e[e.BY=5]="BY",e[e.AT=6]="AT",e[e.FLOW=7]="FLOW",e[e.SEEK=8]="SEEK",e[e.RNDNS=9]="RNDNS",e[e.RNDNE=10]="RNDNE",e[e.RND=11]="RND",e[e.CW=12]="CW",e[e.CCW=13]="CCW",e[e.OPP=14]="OPP",e[e.RNDP=15]="RNDP",e))(ae||{}),fe=(e=>(e[e.LOADER=0]="LOADER",e[e.BOARD=1]="BOARD",e[e.OBJECT=2]="OBJECT",e[e.TERRAIN=3]="TERRAIN",e[e.CHARSET=4]="CHARSET",e[e.PALETTE=5]="PALETTE",e[e.CONST=6]="CONST",e[e.RANGE=7]="RANGE",e[e.SELECT=8]="SELECT",e[e.NUMBER=9]="NUMBER",e[e.TEXT=10]="TEXT",e[e.LINK=11]="LINK",e[e.HOTKEY=12]="HOTKEY",e[e.SCROLL=13]="SCROLL",e[e.COPYIT=14]="COPYIT",e))(fe||{});function Pe(e){return e.toLowerCase().trim()}function yb(e,t,n,r){return{id:ht(),target:e,sender:t,data:n,player:r}}function uh(e){const[t,...n]=e.split(":");return{target:t,path:n.join(":")}}function Po(e,t,n){const r=ht(),i=Pe(e),s=t.map(Pe),o={id(){return r},name(){return e},topics(){return t},emit(a,c,l){Ue.emit(a,r,c,l)},reply(a,c,l,u){o.emit(`${a.sender}:${c}`,l,u)},handle(a){const{target:c,path:l}=uh(a.target),u=Pe(c);s.findIndex(f=>f==="all"||f===u)!==-1&&n(a),(r===c||u==="all"||i===u)&&n({...a,target:l})}};return Ue.connect(o),o}function _b(e){const t=new Set;function n(r){t.has(r.id)||(t.add(r.id),Ue.invoke(r))}return Po("forward",["all"],r=>{t.has(r.id)||(t.add(r.id),e(r))}),n}function Do(e,t){return new Array(e).fill(t)}function fh(e,t,n,r,i=0){const s=n*r;return{id:`tiles:${e}:${t}`,type:1,width:n,height:r,char:Do(s,0),color:Do(s,0),bg:Do(s,i)}}function bb(e,t,n,r=1,i=15){return{id:`sprites:${e}:${t}:${n}`,x:0,y:0,char:r,color:i,bg:be.ONCLEAR}}function wb(e,t){return{id:`sprites:${e}:${t}`,type:2,sprites:[]}}function vb(e,t,n,r,i=0){const s=n*r;return{id:`dither:${e}:${t}`,type:3,width:n,height:r,alphas:Do(s,i)}}function Eb(e,t){return{id:`control:${e}:${t}`,type:5,focusx:0,focusy:0,focusid:e,viewscale:2}}var fn=(e=>(e[e.START=0]="START",e[e.LEFT=1]="LEFT",e[e.RIGHT=2]="RIGHT",e[e.TOP=3]="TOP",e[e.BOTTOM=4]="BOTTOM",e[e.SCROLL=5]="SCROLL",e))(fn||{});const kb={start:0,left:1,right:2,top:3,bottom:4,scroll:5},Sb={0:1,1:20,2:20,3:1,4:1,5:40};function hh(e,t){return`${e}:${t}`}const Ab=1,Tb=16,xb=256;var Ft=(e=>(e[e.NONE=0]="NONE",e[e.ALT=1]="ALT",e[e.CTRL=2]="CTRL",e[e.SHIFT=3]="SHIFT",e[e.MOVE_UP=4]="MOVE_UP",e[e.MOVE_DOWN=5]="MOVE_DOWN",e[e.MOVE_LEFT=6]="MOVE_LEFT",e[e.MOVE_RIGHT=7]="MOVE_RIGHT",e[e.OK_BUTTON=8]="OK_BUTTON",e[e.CANCEL_BUTTON=9]="CANCEL_BUTTON",e[e.MENU_BUTTON=10]="MENU_BUTTON",e[e.SHOOT_UP=11]="SHOOT_UP",e[e.SHOOT_DOWN=12]="SHOOT_DOWN",e[e.SHOOT_LEFT=13]="SHOOT_LEFT",e[e.SHOOT_RIGHT=14]="SHOOT_RIGHT",e))(Ft||{});function et(e,t,n,r){const i=r??"";return Ue.emit(`error:${t}`,e,n,i),Bb(e,n,i)}function Rb(e,t,n){Ue.emit("gadgetclient:reset",e,t,n)}function Ib(e,t,n){Ue.emit("gadgetclient:patch",e,t,n)}function Ob(e,t,n){Ue.emit("register:flush",e,[t,n])}function Nb(e,t){Ue.emit("register:dev",e,void 0,t)}function Cb(e,t){Ue.emit("register:share",e,void 0,t)}function Lb(e){Ue.emit("register:refresh",e)}function Mb(e){Ue.emit("register:nuke",e)}function Ub(e){Ue.emit("register:nodetrash",e)}function Pb(e,t,n){Ue.emit("synth:play",e,[t,n])}function zc(e,t,n,r){Ue.emit("synth:voice",e,[t,n,r])}function Db(e,t,n,r,i){Ue.emit("synth:voicefx",e,[t,n,r,i])}function yt(e,...t){return Ue.emit("tape:info",e,t),!0}function dh(e,...t){return Ue.emit("tape:debug",e,t),!0}function Bb(e,...t){return Ue.emit("tape:error",e,t),!1}function Fb(e,t,n,r,i,s){Ue.emit("tape:editor:open",e,[t,n,r,i],s)}function $b(e,t){Ue.emit("vm:endgame",e,void 0,t)}function ph(e,t){return`${e}${t}`}function ni(e){Ue.emit("vm:flush",e)}function Wc(e,t){function n(r){console.error(r),et(e,"crash",r.message)}t().catch(n)}/*! +var QM=Object.defineProperty;var eU=(cr,Ue,Bt)=>Ue in cr?QM(cr,Ue,{enumerable:!0,configurable:!0,writable:!0,value:Bt}):cr[Ue]=Bt;var ye=(cr,Ue,Bt)=>eU(cr,typeof Ue!="symbol"?Ue+"":Ue,Bt);(function(){"use strict";const cr=new Set,Ue={emit(e,t,n,r){Ue.invoke(yb(e,t,n,r))},invoke(e){cr.forEach(t=>t.handle(e))},connect(e){cr.add(e)},disconnect(e){cr.delete(e)}};var Bt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Pi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function tb(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var ih={};(function(e){var t=Bt&&Bt.__spreadArray||function(l,u,f){if(f||arguments.length===2)for(var d=0,h=u.length,p;df.length?u:f})}function i(l){return l.reduce(function(u,f){return u.lengthcrypto.getRandomValues(new Uint8Array(e)),sb=(e,t,n)=>{let r=(2<{let o="";for(;;){let a=n(i),c=i;for(;c--;)if(o+=e[a[c]&r]||"",o.length===s)return o}}},sh=(e,t=21)=>sb(e,t,ib),ob=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e));for(;e--;)t+=rb[n[e]&63];return t};var oh="abcdefghijklmnopqrstuvwxyz",ah="ABCDEFGHIJKLMNOPQRSTUVWXYZ",ch="0123456789",ab="346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz",cb="6789BCDFGHJKLMNPQRTWbcdfghjkmnpqrtwz";const lb=ch,ub=oh,fb=ah;var hb=lb+ub+fb,jc={lowercase:oh,uppercase:ah,numbers:ch,nolookalikes:ab,nolookalikesSafe:cb,alphanumeric:hb};function ht(){return`sid_${ob(12).replaceAll("-",".")}`}const db=sh(jc.numbers,4),pb=sh(`${jc.numbers}${jc.lowercase}`,16);function mb(){return`pid_${db()}_${pb()}`}function lh(e){return(e==null?void 0:e.startsWith("pid_"))??!1}function gb(){return nb({capitalize:!1,adjectiveCount:1})}var be=(e=>(e[e.BLACK=0]="BLACK",e[e.DKBLUE=1]="DKBLUE",e[e.DKGREEN=2]="DKGREEN",e[e.DKCYAN=3]="DKCYAN",e[e.DKRED=4]="DKRED",e[e.DKPURPLE=5]="DKPURPLE",e[e.DKYELLOW=6]="DKYELLOW",e[e.LTGRAY=7]="LTGRAY",e[e.DKGRAY=8]="DKGRAY",e[e.BLUE=9]="BLUE",e[e.GREEN=10]="GREEN",e[e.CYAN=11]="CYAN",e[e.RED=12]="RED",e[e.PURPLE=13]="PURPLE",e[e.YELLOW=14]="YELLOW",e[e.WHITE=15]="WHITE",e[e.ONBLACK=16]="ONBLACK",e[e.ONDKBLUE=17]="ONDKBLUE",e[e.ONDKGREEN=18]="ONDKGREEN",e[e.ONDKCYAN=19]="ONDKCYAN",e[e.ONDKRED=20]="ONDKRED",e[e.ONDKPURPLE=21]="ONDKPURPLE",e[e.ONDKYELLOW=22]="ONDKYELLOW",e[e.ONLTGRAY=23]="ONLTGRAY",e[e.ONDKGRAY=24]="ONDKGRAY",e[e.ONBLUE=25]="ONBLUE",e[e.ONGREEN=26]="ONGREEN",e[e.ONCYAN=27]="ONCYAN",e[e.ONRED=28]="ONRED",e[e.ONPURPLE=29]="ONPURPLE",e[e.ONYELLOW=30]="ONYELLOW",e[e.ONWHITE=31]="ONWHITE",e[e.ONCLEAR=32]="ONCLEAR",e[e.ONSHADOW=33]="ONSHADOW",e[e.ONBORROW=34]="ONBORROW",e))(be||{}),Ye=(e=>(e[e.ISWALK=0]="ISWALK",e[e.ISSOLID=1]="ISSOLID",e[e.ISSWIM=2]="ISSWIM",e[e.ISBULLET=3]="ISBULLET",e))(Ye||{}),Uo=(e=>(e[e.ISTERRAIN=0]="ISTERRAIN",e[e.ISOBJECT=1]="ISOBJECT",e))(Uo||{}),ae=(e=>(e[e.IDLE=0]="IDLE",e[e.NORTH=1]="NORTH",e[e.SOUTH=2]="SOUTH",e[e.WEST=3]="WEST",e[e.EAST=4]="EAST",e[e.BY=5]="BY",e[e.AT=6]="AT",e[e.FLOW=7]="FLOW",e[e.SEEK=8]="SEEK",e[e.RNDNS=9]="RNDNS",e[e.RNDNE=10]="RNDNE",e[e.RND=11]="RND",e[e.CW=12]="CW",e[e.CCW=13]="CCW",e[e.OPP=14]="OPP",e[e.RNDP=15]="RNDP",e))(ae||{}),fe=(e=>(e[e.LOADER=0]="LOADER",e[e.BOARD=1]="BOARD",e[e.OBJECT=2]="OBJECT",e[e.TERRAIN=3]="TERRAIN",e[e.CHARSET=4]="CHARSET",e[e.PALETTE=5]="PALETTE",e[e.CONST=6]="CONST",e[e.RANGE=7]="RANGE",e[e.SELECT=8]="SELECT",e[e.NUMBER=9]="NUMBER",e[e.TEXT=10]="TEXT",e[e.LINK=11]="LINK",e[e.HOTKEY=12]="HOTKEY",e[e.SCROLL=13]="SCROLL",e[e.COPYIT=14]="COPYIT",e))(fe||{});function Pe(e){return e.toLowerCase().trim()}function yb(e,t,n,r){return{id:ht(),target:e,sender:t,data:n,player:r}}function uh(e){const[t,...n]=e.split(":");return{target:t,path:n.join(":")}}function Po(e,t,n){const r=ht(),i=Pe(e),s=t.map(Pe),o={id(){return r},name(){return e},topics(){return t},emit(a,c,l){Ue.emit(a,r,c,l)},reply(a,c,l,u){o.emit(`${a.sender}:${c}`,l,u)},handle(a){const{target:c,path:l}=uh(a.target),u=Pe(c);s.findIndex(f=>f==="all"||f===u)!==-1&&n(a),(r===c||u==="all"||i===u)&&n({...a,target:l})}};return Ue.connect(o),o}function _b(e){const t=new Set;function n(r){t.has(r.id)||(t.add(r.id),Ue.invoke(r))}return Po("forward",["all"],r=>{t.has(r.id)||(t.add(r.id),e(r))}),n}function Do(e,t){return new Array(e).fill(t)}function fh(e,t,n,r,i=0){const s=n*r;return{id:`tiles:${e}:${t}`,type:1,width:n,height:r,char:Do(s,0),color:Do(s,0),bg:Do(s,i)}}function bb(e,t,n,r=1,i=15){return{id:`sprites:${e}:${t}:${n}`,x:0,y:0,char:r,color:i,bg:be.ONCLEAR}}function wb(e,t){return{id:`sprites:${e}:${t}`,type:2,sprites:[]}}function vb(e,t,n,r,i=0){const s=n*r;return{id:`dither:${e}:${t}`,type:3,width:n,height:r,alphas:Do(s,i)}}function Eb(e,t){return{id:`control:${e}:${t}`,type:5,focusx:0,focusy:0,focusid:e,viewscale:2}}var fn=(e=>(e[e.START=0]="START",e[e.LEFT=1]="LEFT",e[e.RIGHT=2]="RIGHT",e[e.TOP=3]="TOP",e[e.BOTTOM=4]="BOTTOM",e[e.SCROLL=5]="SCROLL",e))(fn||{});const kb={start:0,left:1,right:2,top:3,bottom:4,scroll:5},Sb={0:1,1:20,2:20,3:1,4:1,5:40};function hh(e,t){return`${e}:${t}`}const Ab=1,Tb=16,xb=256;var Ft=(e=>(e[e.NONE=0]="NONE",e[e.ALT=1]="ALT",e[e.CTRL=2]="CTRL",e[e.SHIFT=3]="SHIFT",e[e.MOVE_UP=4]="MOVE_UP",e[e.MOVE_DOWN=5]="MOVE_DOWN",e[e.MOVE_LEFT=6]="MOVE_LEFT",e[e.MOVE_RIGHT=7]="MOVE_RIGHT",e[e.OK_BUTTON=8]="OK_BUTTON",e[e.CANCEL_BUTTON=9]="CANCEL_BUTTON",e[e.MENU_BUTTON=10]="MENU_BUTTON",e[e.SHOOT_UP=11]="SHOOT_UP",e[e.SHOOT_DOWN=12]="SHOOT_DOWN",e[e.SHOOT_LEFT=13]="SHOOT_LEFT",e[e.SHOOT_RIGHT=14]="SHOOT_RIGHT",e))(Ft||{});function et(e,t,n,r){const i=r??"";return Ue.emit(`error:${t}`,e,n,i),Fb(e,n,i)}function Rb(e,t,n){Ue.emit("gadgetclient:reset",e,t,n)}function Ib(e,t,n){Ue.emit("gadgetclient:patch",e,t,n)}function Ob(e,t,n){Ue.emit("register:flush",e,[t,n])}function Nb(e,t){Ue.emit("register:dev",e,void 0,t)}function Cb(e,t){Ue.emit("register:share",e,void 0,t)}function Lb(e){Ue.emit("register:refresh",e)}function Mb(e){Ue.emit("register:nuke",e)}function Ub(e){Ue.emit("register:nodetrash",e)}function Pb(e,t,n){Ue.emit("synth:tts",e,[t,n])}function Db(e,t,n){Ue.emit("synth:play",e,[t,n])}function zc(e,t,n,r){Ue.emit("synth:voice",e,[t,n,r])}function Bb(e,t,n,r,i){Ue.emit("synth:voicefx",e,[t,n,r,i])}function yt(e,...t){return Ue.emit("tape:info",e,t),!0}function dh(e,...t){return Ue.emit("tape:debug",e,t),!0}function Fb(e,...t){return Ue.emit("tape:error",e,t),!1}function $b(e,t,n,r,i,s){Ue.emit("tape:editor:open",e,[t,n,r,i],s)}function jb(e,t){Ue.emit("vm:endgame",e,void 0,t)}function ph(e,t){return`${e}${t}`}function ni(e){Ue.emit("vm:flush",e)}function Wc(e,t){function n(r){console.error(r),et(e,"crash",r.message)}t().catch(n)}/*! * https://github.com/Starcounter-Jack/JSON-Patch * (c) 2017-2022 Joachim Wester * MIT licensed - */var jb=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),zb=Object.prototype.hasOwnProperty;function Gc(e,t){return zb.call(e,t)}function Hc(e){if(Array.isArray(e)){for(var t=new Array(e.length),n=0;n=48&&r<=57){t++;continue}return!1}return!0}function ri(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function mh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Kc(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(l[h]===void 0?d=c.slice(0,u).join("/"):u==f-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),u++,Array.isArray(l)){if(h==="-")h=l.length;else{if(n&&!Vc(h))throw new it("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,t,e);Vc(h)&&(h=~~h)}if(u>=f){if(n&&t.op==="add"&&h>l.length)throw new it("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);var o=Gb[t.op].call(t,l,h,e);if(o.test===!1)throw new it("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return o}}else if(u>=f){var o=Di[t.op].call(t,l,h,e);if(o.test===!1)throw new it("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return o}if(l=l[h],n&&u0)throw new it('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new it("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new it("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&Kc(e.value))throw new it("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n){if(e.op=="add"){var i=e.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new it("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==r)throw new it("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if(e.op==="move"||e.op==="copy"){var o={op:"_get",path:e.from,value:void 0},a=_h([o],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new it("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new it("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function _h(e,t,n){try{if(!Array.isArray(e))throw new it("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)qc(Kt(t),Kt(e),n||!0);else{n=n||Fo;for(var r=0;r=48&&r<=57){t++;continue}return!1}return!0}function ri(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function mh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Kc(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(l[h]===void 0?d=c.slice(0,u).join("/"):u==f-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),u++,Array.isArray(l)){if(h==="-")h=l.length;else{if(n&&!Vc(h))throw new it("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,t,e);Vc(h)&&(h=~~h)}if(u>=f){if(n&&t.op==="add"&&h>l.length)throw new it("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);var o=Hb[t.op].call(t,l,h,e);if(o.test===!1)throw new it("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return o}}else if(u>=f){var o=Di[t.op].call(t,l,h,e);if(o.test===!1)throw new it("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return o}if(l=l[h],n&&u0)throw new it('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new it("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new it("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&Kc(e.value))throw new it("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n){if(e.op=="add"){var i=e.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new it("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==r)throw new it("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if(e.op==="move"||e.op==="copy"){var o={op:"_get",path:e.from,value:void 0},a=_h([o],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new it("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new it("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function _h(e,t,n){try{if(!Array.isArray(e))throw new it("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)qc(Kt(t),Kt(e),n||!0);else{n=n||Fo;for(var r=0;r0&&(e.patches=[],e.callback&&e.callback(r)),r}function Zc(e,t,n,r,i){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=Hc(t),o=Hc(e),a=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(Gc(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var f=t[l];typeof u=="object"&&u!=null&&typeof f=="object"&&f!=null&&Array.isArray(u)===Array.isArray(f)?Zc(u,f,n,r+"/"+ri(l),i):u!==f&&(i&&n.push({op:"test",path:r+"/"+ri(l),value:Kt(u)}),n.push({op:"replace",path:r+"/"+ri(l),value:Kt(f)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:"test",path:r+"/"+ri(l),value:Kt(u)}),n.push({op:"remove",path:r+"/"+ri(l)}),a=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:t}))}if(!(!a&&s.length==o.length))for(var c=0;c0&&(e.patches=[],e.callback&&e.callback(r)),r}function Zc(e,t,n,r,i){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=Hc(t),o=Hc(e),a=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(Gc(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var f=t[l];typeof u=="object"&&u!=null&&typeof f=="object"&&f!=null&&Array.isArray(u)===Array.isArray(f)?Zc(u,f,n,r+"/"+ri(l),i):u!==f&&(i&&n.push({op:"test",path:r+"/"+ri(l),value:Kt(u)}),n.push({op:"replace",path:r+"/"+ri(l),value:Kt(f)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:"test",path:r+"/"+ri(l),value:Kt(u)}),n.push({op:"remove",path:r+"/"+ri(l)}),a=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:t}))}if(!(!a&&s.length==o.length))for(var c=0;c-1&&(u=u.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var f=u.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),d=f.match(/ (\(.+\)$)/);f=d?f.replace(d[0],""):f;var h=this.extractLocation(d?d[1]:f),p=d&&f||void 0,m=["eval",""].indexOf(h[0])>-1?void 0:h[0];return new r({functionName:p,fileName:m,lineNumber:h[1],columnNumber:h[2],source:u})},this)},parseFFOrSafari:function(c){var l=c.stack.split(` `).filter(function(u){return!u.match(o)},this);return l.map(function(u){if(u.indexOf(" > eval")>-1&&(u=u.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),u.indexOf("@")===-1&&u.indexOf(":")===-1)return new r({functionName:u});var f=/((.*".+"[^@]*)?[^@]*)(?:@)/,d=u.match(f),h=d&&d[1]?d[1]:void 0,p=this.extractLocation(u.replace(f,""));return new r({functionName:h,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:u})},this)},parseOpera:function(c){return!c.stacktrace||c.message.indexOf(` `)>-1&&c.message.split(` @@ -15,16 +15,16 @@ var YM=Object.defineProperty;var QM=(cr,Ue,Bt)=>Ue in cr?YM(cr,Ue,{enumerable:!0 `).length?this.parseOpera9(c):c.stack?this.parseOpera11(c):this.parseOpera10(c)},parseOpera9:function(c){for(var l=/Line (\d+).*script (?:in )?(\S+)/i,u=c.message.split(` `),f=[],d=2,h=u.length;d/,"$2").replace(/\([^)]*\)/g,"")||void 0,m;h.match(/\(([^)]*)\)/)&&(m=h.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var b=m===void 0||m==="[arguments not available]"?void 0:m.split(",");return new r({functionName:p,args:b,fileName:d[0],lineNumber:d[1],columnNumber:d[2],source:u})},this)}}})})(wh);var uw=wh.exports,fw=Pi(uw);function lr(e){const t={},n={get(){return[!1,void 0]},set(){return[!1,void 0]},tick(){},everytick(){},...e,getcommand(r){return t[r]},command(r,i){return t[r]=i,n}};return n}var Eh={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Bt,function(){return n.importState=function(i){var s=new n;return s.importState(i),s},n;function n(){return function(i){var s=0,o=0,a=0,c=1;i.length==0&&(i=[+new Date]);var l=r();s=l(" "),o=l(" "),a=l(" ");for(var u=0;u>>0,c-=i,c*=i,i=c>>>0,c-=i,i+=c*4294967296}return(i>>>0)*23283064365386963e-26};return s.version="Mash 0.9",s}})})(Eh);var hw=Eh.exports,dw=Pi(hw);function si(e,t,n){return Math.max(t,Math.min(n,e))}const pw=dw("089fad0j9awfem09wavefc09uwaef");function mw(){return pw()}function _s(e,t){const n=Math.min(e,t),i=Math.max(e,t)-n+1;return n+Math.floor(mw()*i)}function Qc(e,t,n){typeof e!="number"&&(e=0,t=0,n=1),typeof t!="number"&&(t=e,e=0,n=1),typeof n!="number"&&(n=1);const r=[],i=Math.min(e,t),s=Math.max(e,t);for(let o=i;o<=s;o+=n)r.push(o);return r}function gw(e){return e[_s(0,e.length-1)]}function ur(...e){return gw(e.flat())}function yw(e){return[...new Set(e)].filter(k)}function _w(...e){const t=e.flat().filter(k);return t.reduce((n,r)=>n+r,0)/t.length}function fr(e){return k(e)&&k(e.x)&&k(e.y)}function At(e,t){switch(t){case ae.NORTH:--e.y;break;case ae.SOUTH:++e.y;break;case ae.WEST:--e.x;break;case ae.EAST:++e.x;break}return e}function Bi(e,t){const n=t.x-e.x,r=t.y-e.y;if(n<0)return ae.WEST;if(n>0)return ae.EAST;if(r<0)return ae.NORTH;if(r>0)return ae.SOUTH}const kh={idle:"IDLE",up:"NORTH",down:"SOUTH",left:"WEST",right:"EAST",by:"BY",at:"AT",flow:"FLOW",seek:"SEEK",rndns:"RNDNS",rndne:"RNDNE",rnd:"RND",cw:"CW",ccw:"CCW",opp:"OPP",rndp:"RNDP",i:"IDLE",u:"NORTH",north:"NORTH",n:"NORTH",d:"SOUTH",south:"SOUTH",s:"SOUTH",l:"WEST",west:"WEST",w:"WEST",r:"EAST",east:"EAST",e:"EAST",edit:"EDIT"};function hr(e){return Ge(e)&&Sh(e[0])}function Sh(e){return k(ae[e])&&Ce(e)}function bw(e){const t=ae[e];return k(t)?t:ae.IDLE}function Ah(e){if(Ce(e))return kh[Pe(e)]}function Th(e){if(hr(e))return e;if(Sh(e))return[e];const t=Ah(e);if(k(t))return[t]}function xh(e){const t=C.words[e],n=Th(t);if(hr(n))return[n,e+1];const[r,i]=Gt(e),s=Th(r);return hr(s)?[s,i]:[void 0,e]}function el(e){const t=[];let[n,r]=xh(e);for(;hr(n);){if(t.push(...n),(n[0]==="AT"||n[0]==="BY")&&n.length<2){const[o,a,c]=ne(C.words,r,[q.NUMBER,q.NUMBER]);t.push(o,a),r=c}const[i,s]=xh(r);n=i,r=s}return t.length?[t,r]:[void 0,e]}function Fi(e){return Ge(e)&&typeof e[0]=="string"}function Rh(e){const t=C.words[e];if(Fi(t))return[t,e+1];const[n,r]=Ha(e),[i,s]=Gt(r,!1);return Ce(i)?[[i,n],s]:[void 0,e]}function jo(e){if(!Fi(e))return;const[t]=e;return t}function Ih(e){if(!Fi(e))return;const[,t]=e,n=k(t)?sI(t):void 0;return k(n)?n:void 0}function Oh(e){if(!Fi(e))return;const[,t]=e,n=k(t)?oI(t):void 0;return k(n)?n:void 0}const ze=60,rn=25;var Ae=(e=>(e[e.ERROR=0]="ERROR",e[e.LOADER=1]="LOADER",e[e.BOARD=2]="BOARD",e[e.OBJECT=3]="OBJECT",e[e.TERRAIN=4]="TERRAIN",e[e.CHARSET=5]="CHARSET",e[e.PALETTE=6]="PALETTE",e))(Ae||{});function Nh(e,t){const n=e??Ye.ISWALK,r=t??Ye.ISWALK;switch(n){case Ye.ISWALK:return r!==Ye.ISWALK;case Ye.ISSWIM:return r!==Ye.ISSWIM;case Ye.ISSOLID:return!0;case Ye.ISBULLET:return r!==Ye.ISWALK&&r!==Ye.ISSWIM}}function Ch(e,t,n){const r=e==null?void 0:e.objects[n];if(k(r))return r;if(k(t)){const i=bs(e,"player"),s={x:t.x??0,y:t.y??0};Mh(s,i)}}function bs(e,t){var r,i;return[...((i=(r=e==null?void 0:e.named)==null?void 0:r[t])==null?void 0:i.values())??[]].map(s=>typeof s=="string"?e==null?void 0:e.objects[s]:e==null?void 0:e.terrain[s]).filter(k)}function Lh(e,t){const n=jo(t),r=Ih(t),i=Oh(t);return e.filter(s=>!(k(n)&&Du(s)!==n||k(r)&&hI(s)!==r||k(i)&&dI(s)!==i)).filter(k)}function tl(e,t){return k(e)?t.map(n=>{var r;if(typeof n=="string"){const i=e.objects[n];if(k(i))return i;const s=bs(e,Pe(n));if(s.length)return s}else if(fr(n)&&n.x>=0&&n.x=0&&n.y0){if(++t>=cv)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function hv(e){return function(){return e}}var Ho=function(){try{var e=ai(Object,"defineProperty");return e({},"",{}),e}catch{}}(),dv=Ho?function(e,t){return Ho(e,"toString",{configurable:!0,enumerable:!1,value:hv(t),writable:!0})}:$i,pv=fv(dv);function Vh(e,t){for(var n=-1,r=e==null?0:e.length;++n-1}var yv=9007199254740991,_v=/^(?:0|[1-9]\d*)$/;function Vo(e,t){var n=typeof e;return t=t??yv,!!t&&(n=="number"||n!="symbol"&&_v.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=Ev}function jn(e){return e!=null&&cl(e.length)&&!dr(e)}function Xh(e,t,n){if(!dn(n))return!1;var r=typeof t;return(r=="number"?jn(n)&&Vo(t,n.length):r=="string"&&t in n)?vs(n[t],e):!1}function kv(e){return al(function(t,n){var r=-1,i=n.length,s=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(s=e.length>3&&typeof s=="function"?(i--,s):void 0,o&&Xh(n[0],n[1],o)&&(s=i<3?void 0:s,i=1),t=Object(t);++r-1}function ME(e,t){var n=this.__data__,r=Xo(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function pr(e){var t=-1,n=e==null?0:e.length;for(this.clear();++ti?0:i+t),n=n>i?i:n,n<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var s=Array(i);++r=r?e:gl(e,t,n)}var ZE="\\ud800-\\udfff",YE="\\u0300-\\u036f",QE="\\ufe20-\\ufe2f",ek="\\u20d0-\\u20ff",tk=YE+QE+ek,nk="\\ufe0e\\ufe0f",rk="\\u200d",ik=RegExp("["+rk+ZE+tk+nk+"]");function fd(e){return ik.test(e)}function sk(e){return e.split("")}var hd="\\ud800-\\udfff",ok="\\u0300-\\u036f",ak="\\ufe20-\\ufe2f",ck="\\u20d0-\\u20ff",lk=ok+ak+ck,uk="\\ufe0e\\ufe0f",fk="["+hd+"]",yl="["+lk+"]",_l="\\ud83c[\\udffb-\\udfff]",hk="(?:"+yl+"|"+_l+")",dd="[^"+hd+"]",pd="(?:\\ud83c[\\udde6-\\uddff]){2}",md="[\\ud800-\\udbff][\\udc00-\\udfff]",dk="\\u200d",gd=hk+"?",yd="["+uk+"]?",pk="(?:"+dk+"(?:"+[dd,pd,md].join("|")+")"+yd+gd+")*",mk=yd+gd+pk,gk="(?:"+[dd+yl+"?",yl,pd,md,fk].join("|")+")",yk=RegExp(_l+"(?="+_l+")|"+gk+mk,"g");function _k(e){return e.match(yk)||[]}function bk(e){return fd(e)?_k(e):sk(e)}function wk(e){return function(t){t=cd(t);var n=fd(t)?bk(t):void 0,r=n?n[0]:t.charAt(0),i=n?XE(n,1).join(""):t.slice(1);return r[e]()+i}}var _d=wk("toUpperCase");function vk(e,t,n,r){var i=-1,s=e==null?0:e.length;for(r&&s&&(n=e[++i]);++ia))return!1;var l=s.get(e),u=s.get(t);if(l&&u)return l==t&&u==e;var f=-1,d=!0,h=n&Q1?new zi:void 0;for(s.set(e,t),s.set(t,e);++f2?t[2]:void 0;for(i&&Xh(t[0],t[1],i)&&(r=1);++n=WS&&(s=Sl,o=!1,t=new zi(t));e:for(;++i-1?i[s?t[o]:o]:void 0}}var JS=Math.max;function XS(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var i=n==null?0:Go(n);return i<0&&(i=JS(r+i,0)),Kh(e,Wn(t),i)}var Gi=qS(XS);function In(e){return e&&e.length?e[0]:void 0}function ZS(e,t){var n=-1,r=jn(e)?Array(e.length):[];return li(e,function(i,s,o){r[++n]=t(i,s,o)}),r}function ce(e,t){var n=Le(e)?Wo:ZS;return n(e,Wn(t))}function yn(e,t){return ml(ce(e,t))}var YS=Object.prototype,QS=YS.hasOwnProperty,Xd=jS(function(e,t,n){QS.call(e,n)?e[n].push(t):sl(e,n,[t])}),eA=Object.prototype,tA=eA.hasOwnProperty;function nA(e,t){return e!=null&&tA.call(e,t)}function pe(e,t){return e!=null&&Vd(e,t,nA)}var rA="[object String]";function Jt(e){return typeof e=="string"||!Le(e)&&xn(e)&&Dr(e)==rA}function iA(e,t){return Wo(t,function(n){return e[n]})}function dt(e){return e==null?[]:iA(e,pn(e))}var sA=Math.max;function $t(e,t,n,r){e=jn(e)?e:dt(e),n=n&&!r?Go(n):0;var i=e.length;return n<0&&(n=sA(i+n,0)),Jt(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&il(e,t,n)>-1}function Zd(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var i=0;return il(e,t,i)}var oA="[object Map]",aA="[object Set]",cA=Object.prototype,lA=cA.hasOwnProperty;function Ve(e){if(e==null)return!0;if(jn(e)&&(Le(e)||typeof e=="string"||typeof e.splice=="function"||ks(e)||ul(e)||qo(e)))return!e.length;var t=mn(e);if(t==oA||t==aA)return!e.size;if(Es(e))return!od(e).length;for(var n in e)if(lA.call(e,n))return!1;return!0}var uA="[object RegExp]";function fA(e){return xn(e)&&Dr(e)==uA}var Yd=Br&&Br.isRegExp,gr=Yd?Jo(Yd):fA;function yr(e){return e===void 0}var hA="Expected a function";function dA(e){if(typeof e!="function")throw new TypeError(hA);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}function pA(e,t,n,r){if(!dn(e))return e;t=Yo(t,e);for(var i=-1,s=t.length,o=s-1,a=e;a!=null&&++i=wA){var l=bA(e);if(l)return Al(l);o=!1,i=Sl,c=new zi}else c=a;e:for(;++r{n.accept(t)})}}class Zt extends Gn{constructor(t){super([]),this.idx=1,qt(this,On(t,n=>n!==void 0))}set definition(t){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(t){t.visit(this)}}class Hi extends Gn{constructor(t){super(t.definition),this.orgText="",qt(this,On(t,n=>n!==void 0))}}class Yt extends Gn{constructor(t){super(t.definition),this.ignoreAmbiguities=!1,qt(this,On(t,n=>n!==void 0))}}class Qt extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class Hn extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class Vn extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class bt extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class Nn extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class Cn extends Gn{get definition(){return this._definition}set definition(t){this._definition=t}constructor(t){super(t.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,qt(this,On(t,n=>n!==void 0))}}class tt{constructor(t){this.idx=1,qt(this,On(t,n=>n!==void 0))}accept(t){t.visit(this)}}function SA(e){return ce(e,sa)}function sa(e){function t(n){return ce(n,sa)}if(e instanceof Zt){const n={type:"NonTerminal",name:e.nonTerminalName,idx:e.idx};return Jt(e.label)&&(n.label=e.label),n}else{if(e instanceof Yt)return{type:"Alternative",definition:t(e.definition)};if(e instanceof Qt)return{type:"Option",idx:e.idx,definition:t(e.definition)};if(e instanceof Hn)return{type:"RepetitionMandatory",idx:e.idx,definition:t(e.definition)};if(e instanceof Vn)return{type:"RepetitionMandatoryWithSeparator",idx:e.idx,separator:sa(new tt({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof Nn)return{type:"RepetitionWithSeparator",idx:e.idx,separator:sa(new tt({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof bt)return{type:"Repetition",idx:e.idx,definition:t(e.definition)};if(e instanceof Cn)return{type:"Alternation",idx:e.idx,definition:t(e.definition)};if(e instanceof tt){const n={type:"Terminal",name:e.terminalType.name,label:EA(e.terminalType),idx:e.idx};Jt(e.label)&&(n.terminalLabel=e.label);const r=e.terminalType.PATTERN;return e.terminalType.PATTERN&&(n.pattern=gr(r)?r.source:r),n}else{if(e instanceof Hi)return{type:"Rule",name:e.name,orgText:e.orgText,definition:t(e.definition)};throw Error("non exhaustive match")}}}class ui{visit(t){const n=t;switch(n.constructor){case Zt:return this.visitNonTerminal(n);case Yt:return this.visitAlternative(n);case Qt:return this.visitOption(n);case Hn:return this.visitRepetitionMandatory(n);case Vn:return this.visitRepetitionMandatoryWithSeparator(n);case Nn:return this.visitRepetitionWithSeparator(n);case bt:return this.visitRepetition(n);case Cn:return this.visitAlternation(n);case tt:return this.visitTerminal(n);case Hi:return this.visitRule(n);default:throw Error("non exhaustive match")}}visitNonTerminal(t){}visitAlternative(t){}visitOption(t){}visitRepetition(t){}visitRepetitionMandatory(t){}visitRepetitionMandatoryWithSeparator(t){}visitRepetitionWithSeparator(t){}visitAlternation(t){}visitTerminal(t){}visitRule(t){}}function AA(e){return e instanceof Yt||e instanceof Qt||e instanceof bt||e instanceof Hn||e instanceof Vn||e instanceof Nn||e instanceof tt||e instanceof Hi}function oa(e,t=[]){return e instanceof Qt||e instanceof bt||e instanceof Nn?!0:e instanceof Cn?Il(e.definition,r=>oa(r,t)):e instanceof Zt&&$t(t,e)?!1:e instanceof Gn?(e instanceof Zt&&t.push(e),Rn(e.definition,r=>oa(r,t))):!1}function TA(e){return e instanceof Cn}function Kn(e){if(e instanceof Zt)return"SUBRULE";if(e instanceof Qt)return"OPTION";if(e instanceof Cn)return"OR";if(e instanceof Hn)return"AT_LEAST_ONE";if(e instanceof Vn)return"AT_LEAST_ONE_SEP";if(e instanceof Nn)return"MANY_SEP";if(e instanceof bt)return"MANY";if(e instanceof tt)return"CONSUME";throw Error("non exhaustive match")}class aa{walk(t,n=[]){me(t.definition,(r,i)=>{const s=Lt(t.definition,i+1);if(r instanceof Zt)this.walkProdRef(r,s,n);else if(r instanceof tt)this.walkTerminal(r,s,n);else if(r instanceof Yt)this.walkFlat(r,s,n);else if(r instanceof Qt)this.walkOption(r,s,n);else if(r instanceof Hn)this.walkAtLeastOne(r,s,n);else if(r instanceof Vn)this.walkAtLeastOneSep(r,s,n);else if(r instanceof Nn)this.walkManySep(r,s,n);else if(r instanceof bt)this.walkMany(r,s,n);else if(r instanceof Cn)this.walkOr(r,s,n);else throw Error("non exhaustive match")})}walkTerminal(t,n,r){}walkProdRef(t,n,r){}walkFlat(t,n,r){const i=n.concat(r);this.walk(t,i)}walkOption(t,n,r){const i=n.concat(r);this.walk(t,i)}walkAtLeastOne(t,n,r){const i=[new Qt({definition:t.definition})].concat(n,r);this.walk(t,i)}walkAtLeastOneSep(t,n,r){const i=np(t,n,r);this.walk(t,i)}walkMany(t,n,r){const i=[new Qt({definition:t.definition})].concat(n,r);this.walk(t,i)}walkManySep(t,n,r){const i=np(t,n,r);this.walk(t,i)}walkOr(t,n,r){const i=n.concat(r);me(t.definition,s=>{const o=new Yt({definition:[s]});this.walk(o,i)})}}function np(e,t,n){return[new Qt({definition:[new tt({terminalType:e.separator})].concat(e.definition)})].concat(t,n)}function Os(e){if(e instanceof Zt)return Os(e.referencedRule);if(e instanceof tt)return IA(e);if(AA(e))return xA(e);if(TA(e))return RA(e);throw Error("non exhaustive match")}function xA(e){let t=[];const n=e.definition;let r=0,i=n.length>r,s,o=!0;for(;i&&o;)s=n[r],o=oa(s),t=t.concat(Os(s)),r=r+1,i=n.length>r;return ia(t)}function RA(e){const t=ce(e.definition,n=>Os(n));return ia(sn(t))}function IA(e){return[e.terminalType]}const rp="_~IN~_";class OA extends aa{constructor(t){super(),this.topProd=t,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(t,n,r){}walkProdRef(t,n,r){const i=CA(t.referencedRule,t.idx)+this.topProd.name,s=n.concat(r),o=new Yt({definition:s}),a=Os(o);this.follows[i]=a}}function NA(e){const t={};return me(e,n=>{const r=new OA(n).startWalking();qt(t,r)}),t}function CA(e,t){return e.name+t+rp}function ge(e){return e.charCodeAt(0)}function Nl(e,t){Array.isArray(e)?e.forEach(function(n){t.push(n)}):t.push(e)}function Ns(e,t){if(e[t]===!0)throw"duplicate flag "+t;e[t],e[t]=!0}function Vi(e){if(e===void 0)throw Error("Internal Error - Should never get here!");return!0}function LA(){throw Error("Internal Error - Should never get here!")}function ip(e){return e.type==="Character"}const ca=[];for(let e=ge("0");e<=ge("9");e++)ca.push(e);const la=[ge("_")].concat(ca);for(let e=ge("a");e<=ge("z");e++)la.push(e);for(let e=ge("A");e<=ge("Z");e++)la.push(e);const sp=[ge(" "),ge("\f"),ge(` -`),ge("\r"),ge(" "),ge("\v"),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge("\u2028"),ge("\u2029"),ge(" "),ge(" "),ge(" "),ge("\uFEFF")],MA=/[0-9a-fA-F]/,ua=/[0-9]/,UA=/[1-9]/;class PA{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(t){this.idx=t.idx,this.input=t.input,this.groupIdx=t.groupIdx}pattern(t){this.idx=0,this.input=t,this.groupIdx=0,this.consumeChar("/");const n=this.disjunction();this.consumeChar("/");const r={type:"Flags",loc:{begin:this.idx,end:t.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":Ns(r,"global");break;case"i":Ns(r,"ignoreCase");break;case"m":Ns(r,"multiLine");break;case"u":Ns(r,"unicode");break;case"y":Ns(r,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:n,loc:this.loc(0)}}disjunction(){const t=[],n=this.idx;for(t.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),t.push(this.alternative());return{type:"Disjunction",value:t,loc:this.loc(n)}}alternative(){const t=[],n=this.idx;for(;this.isTerm();)t.push(this.term());return{type:"Alternative",value:t,loc:this.loc(n)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){const t=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(t)};case"$":return{type:"EndAnchor",loc:this.loc(t)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(t)};case"B":return{type:"NonWordBoundary",loc:this.loc(t)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let n;switch(this.popChar()){case"=":n="Lookahead";break;case"!":n="NegativeLookahead";break}Vi(n);const r=this.disjunction();return this.consumeChar(")"),{type:n,value:r,loc:this.loc(t)}}return LA()}quantifier(t=!1){let n;const r=this.idx;switch(this.popChar()){case"*":n={atLeast:0,atMost:1/0};break;case"+":n={atLeast:1,atMost:1/0};break;case"?":n={atLeast:0,atMost:1};break;case"{":const i=this.integerIncludingZero();switch(this.popChar()){case"}":n={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),n={atLeast:i,atMost:s}):n={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(t===!0&&n===void 0)return;Vi(n);break}if(!(t===!0&&n===void 0)&&Vi(n))return this.peekChar(0)==="?"?(this.consumeChar("?"),n.greedy=!1):n.greedy=!0,n.type="Quantifier",n.loc=this.loc(r),n}atom(){let t;const n=this.idx;switch(this.peekChar()){case".":t=this.dotAll();break;case"\\":t=this.atomEscape();break;case"[":t=this.characterClass();break;case"(":t=this.group();break}if(t===void 0&&this.isPatternCharacter()&&(t=this.patternCharacter()),Vi(t))return t.loc=this.loc(n),this.isQuantifier()&&(t.quantifier=this.quantifier()),t}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[ge(` +`).filter(function(u){return!!u.match(i)&&!u.match(/^Error created at/)},this);return l.map(function(u){var f=u.split("@"),d=this.extractLocation(f.pop()),h=f.shift()||"",p=h.replace(//,"$2").replace(/\([^)]*\)/g,"")||void 0,m;h.match(/\(([^)]*)\)/)&&(m=h.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var b=m===void 0||m==="[arguments not available]"?void 0:m.split(",");return new r({functionName:p,args:b,fileName:d[0],lineNumber:d[1],columnNumber:d[2],source:u})},this)}}})})(wh);var fw=wh.exports,hw=Pi(fw);function lr(e){const t={},n={get(){return[!1,void 0]},set(){return[!1,void 0]},tick(){},everytick(){},...e,getcommand(r){return t[r]},command(r,i){return t[r]=i,n}};return n}var Eh={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Bt,function(){return n.importState=function(i){var s=new n;return s.importState(i),s},n;function n(){return function(i){var s=0,o=0,a=0,c=1;i.length==0&&(i=[+new Date]);var l=r();s=l(" "),o=l(" "),a=l(" ");for(var u=0;u>>0,c-=i,c*=i,i=c>>>0,c-=i,i+=c*4294967296}return(i>>>0)*23283064365386963e-26};return s.version="Mash 0.9",s}})})(Eh);var dw=Eh.exports,pw=Pi(dw);function si(e,t,n){return Math.max(t,Math.min(n,e))}const mw=pw("089fad0j9awfem09wavefc09uwaef");function gw(){return mw()}function _s(e,t){const n=Math.min(e,t),i=Math.max(e,t)-n+1;return n+Math.floor(gw()*i)}function Qc(e,t,n){typeof e!="number"&&(e=0,t=0,n=1),typeof t!="number"&&(t=e,e=0,n=1),typeof n!="number"&&(n=1);const r=[],i=Math.min(e,t),s=Math.max(e,t);for(let o=i;o<=s;o+=n)r.push(o);return r}function yw(e){return e[_s(0,e.length-1)]}function ur(...e){return yw(e.flat())}function _w(e){return[...new Set(e)].filter(k)}function bw(...e){const t=e.flat().filter(k);return t.reduce((n,r)=>n+r,0)/t.length}function fr(e){return k(e)&&k(e.x)&&k(e.y)}function At(e,t){switch(t){case ae.NORTH:--e.y;break;case ae.SOUTH:++e.y;break;case ae.WEST:--e.x;break;case ae.EAST:++e.x;break}return e}function Bi(e,t){const n=t.x-e.x,r=t.y-e.y;if(n<0)return ae.WEST;if(n>0)return ae.EAST;if(r<0)return ae.NORTH;if(r>0)return ae.SOUTH}const kh={idle:"IDLE",up:"NORTH",down:"SOUTH",left:"WEST",right:"EAST",by:"BY",at:"AT",flow:"FLOW",seek:"SEEK",rndns:"RNDNS",rndne:"RNDNE",rnd:"RND",cw:"CW",ccw:"CCW",opp:"OPP",rndp:"RNDP",i:"IDLE",u:"NORTH",north:"NORTH",n:"NORTH",d:"SOUTH",south:"SOUTH",s:"SOUTH",l:"WEST",west:"WEST",w:"WEST",r:"EAST",east:"EAST",e:"EAST",edit:"EDIT"};function hr(e){return Ge(e)&&Sh(e[0])}function Sh(e){return k(ae[e])&&Ce(e)}function ww(e){const t=ae[e];return k(t)?t:ae.IDLE}function Ah(e){if(Ce(e))return kh[Pe(e)]}function Th(e){if(hr(e))return e;if(Sh(e))return[e];const t=Ah(e);if(k(t))return[t]}function xh(e){const t=C.words[e],n=Th(t);if(hr(n))return[n,e+1];const[r,i]=Gt(e),s=Th(r);return hr(s)?[s,i]:[void 0,e]}function el(e){const t=[];let[n,r]=xh(e);for(;hr(n);){if(t.push(...n),(n[0]==="AT"||n[0]==="BY")&&n.length<2){const[o,a,c]=ne(C.words,r,[q.NUMBER,q.NUMBER]);t.push(o,a),r=c}const[i,s]=xh(r);n=i,r=s}return t.length?[t,r]:[void 0,e]}function Fi(e){return Ge(e)&&typeof e[0]=="string"}function Rh(e){const t=C.words[e];if(Fi(t))return[t,e+1];const[n,r]=Ha(e),[i,s]=Gt(r,!1);return Ce(i)?[[i,n],s]:[void 0,e]}function jo(e){if(!Fi(e))return;const[t]=e;return t}function Ih(e){if(!Fi(e))return;const[,t]=e,n=k(t)?oI(t):void 0;return k(n)?n:void 0}function Oh(e){if(!Fi(e))return;const[,t]=e,n=k(t)?aI(t):void 0;return k(n)?n:void 0}const ze=60,rn=25;var Ae=(e=>(e[e.ERROR=0]="ERROR",e[e.LOADER=1]="LOADER",e[e.BOARD=2]="BOARD",e[e.OBJECT=3]="OBJECT",e[e.TERRAIN=4]="TERRAIN",e[e.CHARSET=5]="CHARSET",e[e.PALETTE=6]="PALETTE",e))(Ae||{});function Nh(e,t){const n=e??Ye.ISWALK,r=t??Ye.ISWALK;switch(n){case Ye.ISWALK:return r!==Ye.ISWALK;case Ye.ISSWIM:return r!==Ye.ISSWIM;case Ye.ISSOLID:return!0;case Ye.ISBULLET:return r!==Ye.ISWALK&&r!==Ye.ISSWIM}}function Ch(e,t,n){const r=e==null?void 0:e.objects[n];if(k(r))return r;if(k(t)){const i=bs(e,"player"),s={x:t.x??0,y:t.y??0};Mh(s,i)}}function bs(e,t){var r,i;return[...((i=(r=e==null?void 0:e.named)==null?void 0:r[t])==null?void 0:i.values())??[]].map(s=>typeof s=="string"?e==null?void 0:e.objects[s]:e==null?void 0:e.terrain[s]).filter(k)}function Lh(e,t){const n=jo(t),r=Ih(t),i=Oh(t);return e.filter(s=>!(k(n)&&Du(s)!==n||k(r)&&dI(s)!==r||k(i)&&pI(s)!==i)).filter(k)}function tl(e,t){return k(e)?t.map(n=>{var r;if(typeof n=="string"){const i=e.objects[n];if(k(i))return i;const s=bs(e,Pe(n));if(s.length)return s}else if(fr(n)&&n.x>=0&&n.x=0&&n.y0){if(++t>=lv)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function dv(e){return function(){return e}}var Ho=function(){try{var e=ai(Object,"defineProperty");return e({},"",{}),e}catch{}}(),pv=Ho?function(e,t){return Ho(e,"toString",{configurable:!0,enumerable:!1,value:dv(t),writable:!0})}:$i,mv=hv(pv);function Vh(e,t){for(var n=-1,r=e==null?0:e.length;++n-1}var _v=9007199254740991,bv=/^(?:0|[1-9]\d*)$/;function Vo(e,t){var n=typeof e;return t=t??_v,!!t&&(n=="number"||n!="symbol"&&bv.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=kv}function jn(e){return e!=null&&cl(e.length)&&!dr(e)}function Xh(e,t,n){if(!dn(n))return!1;var r=typeof t;return(r=="number"?jn(n)&&Vo(t,n.length):r=="string"&&t in n)?vs(n[t],e):!1}function Sv(e){return al(function(t,n){var r=-1,i=n.length,s=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(s=e.length>3&&typeof s=="function"?(i--,s):void 0,o&&Xh(n[0],n[1],o)&&(s=i<3?void 0:s,i=1),t=Object(t);++r-1}function UE(e,t){var n=this.__data__,r=Xo(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function pr(e){var t=-1,n=e==null?0:e.length;for(this.clear();++ti?0:i+t),n=n>i?i:n,n<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var s=Array(i);++r=r?e:gl(e,t,n)}var YE="\\ud800-\\udfff",QE="\\u0300-\\u036f",ek="\\ufe20-\\ufe2f",tk="\\u20d0-\\u20ff",nk=QE+ek+tk,rk="\\ufe0e\\ufe0f",ik="\\u200d",sk=RegExp("["+ik+YE+nk+rk+"]");function fd(e){return sk.test(e)}function ok(e){return e.split("")}var hd="\\ud800-\\udfff",ak="\\u0300-\\u036f",ck="\\ufe20-\\ufe2f",lk="\\u20d0-\\u20ff",uk=ak+ck+lk,fk="\\ufe0e\\ufe0f",hk="["+hd+"]",yl="["+uk+"]",_l="\\ud83c[\\udffb-\\udfff]",dk="(?:"+yl+"|"+_l+")",dd="[^"+hd+"]",pd="(?:\\ud83c[\\udde6-\\uddff]){2}",md="[\\ud800-\\udbff][\\udc00-\\udfff]",pk="\\u200d",gd=dk+"?",yd="["+fk+"]?",mk="(?:"+pk+"(?:"+[dd,pd,md].join("|")+")"+yd+gd+")*",gk=yd+gd+mk,yk="(?:"+[dd+yl+"?",yl,pd,md,hk].join("|")+")",_k=RegExp(_l+"(?="+_l+")|"+yk+gk,"g");function bk(e){return e.match(_k)||[]}function wk(e){return fd(e)?bk(e):ok(e)}function vk(e){return function(t){t=cd(t);var n=fd(t)?wk(t):void 0,r=n?n[0]:t.charAt(0),i=n?ZE(n,1).join(""):t.slice(1);return r[e]()+i}}var _d=vk("toUpperCase");function Ek(e,t,n,r){var i=-1,s=e==null?0:e.length;for(r&&s&&(n=e[++i]);++ia))return!1;var l=s.get(e),u=s.get(t);if(l&&u)return l==t&&u==e;var f=-1,d=!0,h=n&eS?new zi:void 0;for(s.set(e,t),s.set(t,e);++f2?t[2]:void 0;for(i&&Xh(t[0],t[1],i)&&(r=1);++n=GS&&(s=Sl,o=!1,t=new zi(t));e:for(;++i-1?i[s?t[o]:o]:void 0}}var XS=Math.max;function ZS(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var i=n==null?0:Go(n);return i<0&&(i=XS(r+i,0)),Kh(e,Wn(t),i)}var Gi=JS(ZS);function In(e){return e&&e.length?e[0]:void 0}function YS(e,t){var n=-1,r=jn(e)?Array(e.length):[];return li(e,function(i,s,o){r[++n]=t(i,s,o)}),r}function ce(e,t){var n=Le(e)?Wo:YS;return n(e,Wn(t))}function yn(e,t){return ml(ce(e,t))}var QS=Object.prototype,eA=QS.hasOwnProperty,Xd=zS(function(e,t,n){eA.call(e,n)?e[n].push(t):sl(e,n,[t])}),tA=Object.prototype,nA=tA.hasOwnProperty;function rA(e,t){return e!=null&&nA.call(e,t)}function pe(e,t){return e!=null&&Vd(e,t,rA)}var iA="[object String]";function Jt(e){return typeof e=="string"||!Le(e)&&xn(e)&&Dr(e)==iA}function sA(e,t){return Wo(t,function(n){return e[n]})}function dt(e){return e==null?[]:sA(e,pn(e))}var oA=Math.max;function $t(e,t,n,r){e=jn(e)?e:dt(e),n=n&&!r?Go(n):0;var i=e.length;return n<0&&(n=oA(i+n,0)),Jt(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&il(e,t,n)>-1}function Zd(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var i=0;return il(e,t,i)}var aA="[object Map]",cA="[object Set]",lA=Object.prototype,uA=lA.hasOwnProperty;function Ve(e){if(e==null)return!0;if(jn(e)&&(Le(e)||typeof e=="string"||typeof e.splice=="function"||ks(e)||ul(e)||qo(e)))return!e.length;var t=mn(e);if(t==aA||t==cA)return!e.size;if(Es(e))return!od(e).length;for(var n in e)if(uA.call(e,n))return!1;return!0}var fA="[object RegExp]";function hA(e){return xn(e)&&Dr(e)==fA}var Yd=Br&&Br.isRegExp,gr=Yd?Jo(Yd):hA;function yr(e){return e===void 0}var dA="Expected a function";function pA(e){if(typeof e!="function")throw new TypeError(dA);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}function mA(e,t,n,r){if(!dn(e))return e;t=Yo(t,e);for(var i=-1,s=t.length,o=s-1,a=e;a!=null&&++i=vA){var l=wA(e);if(l)return Al(l);o=!1,i=Sl,c=new zi}else c=a;e:for(;++r{n.accept(t)})}}class Zt extends Gn{constructor(t){super([]),this.idx=1,qt(this,On(t,n=>n!==void 0))}set definition(t){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(t){t.visit(this)}}class Hi extends Gn{constructor(t){super(t.definition),this.orgText="",qt(this,On(t,n=>n!==void 0))}}class Yt extends Gn{constructor(t){super(t.definition),this.ignoreAmbiguities=!1,qt(this,On(t,n=>n!==void 0))}}class Qt extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class Hn extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class Vn extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class bt extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class Nn extends Gn{constructor(t){super(t.definition),this.idx=1,qt(this,On(t,n=>n!==void 0))}}class Cn extends Gn{get definition(){return this._definition}set definition(t){this._definition=t}constructor(t){super(t.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,qt(this,On(t,n=>n!==void 0))}}class tt{constructor(t){this.idx=1,qt(this,On(t,n=>n!==void 0))}accept(t){t.visit(this)}}function AA(e){return ce(e,sa)}function sa(e){function t(n){return ce(n,sa)}if(e instanceof Zt){const n={type:"NonTerminal",name:e.nonTerminalName,idx:e.idx};return Jt(e.label)&&(n.label=e.label),n}else{if(e instanceof Yt)return{type:"Alternative",definition:t(e.definition)};if(e instanceof Qt)return{type:"Option",idx:e.idx,definition:t(e.definition)};if(e instanceof Hn)return{type:"RepetitionMandatory",idx:e.idx,definition:t(e.definition)};if(e instanceof Vn)return{type:"RepetitionMandatoryWithSeparator",idx:e.idx,separator:sa(new tt({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof Nn)return{type:"RepetitionWithSeparator",idx:e.idx,separator:sa(new tt({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof bt)return{type:"Repetition",idx:e.idx,definition:t(e.definition)};if(e instanceof Cn)return{type:"Alternation",idx:e.idx,definition:t(e.definition)};if(e instanceof tt){const n={type:"Terminal",name:e.terminalType.name,label:kA(e.terminalType),idx:e.idx};Jt(e.label)&&(n.terminalLabel=e.label);const r=e.terminalType.PATTERN;return e.terminalType.PATTERN&&(n.pattern=gr(r)?r.source:r),n}else{if(e instanceof Hi)return{type:"Rule",name:e.name,orgText:e.orgText,definition:t(e.definition)};throw Error("non exhaustive match")}}}class ui{visit(t){const n=t;switch(n.constructor){case Zt:return this.visitNonTerminal(n);case Yt:return this.visitAlternative(n);case Qt:return this.visitOption(n);case Hn:return this.visitRepetitionMandatory(n);case Vn:return this.visitRepetitionMandatoryWithSeparator(n);case Nn:return this.visitRepetitionWithSeparator(n);case bt:return this.visitRepetition(n);case Cn:return this.visitAlternation(n);case tt:return this.visitTerminal(n);case Hi:return this.visitRule(n);default:throw Error("non exhaustive match")}}visitNonTerminal(t){}visitAlternative(t){}visitOption(t){}visitRepetition(t){}visitRepetitionMandatory(t){}visitRepetitionMandatoryWithSeparator(t){}visitRepetitionWithSeparator(t){}visitAlternation(t){}visitTerminal(t){}visitRule(t){}}function TA(e){return e instanceof Yt||e instanceof Qt||e instanceof bt||e instanceof Hn||e instanceof Vn||e instanceof Nn||e instanceof tt||e instanceof Hi}function oa(e,t=[]){return e instanceof Qt||e instanceof bt||e instanceof Nn?!0:e instanceof Cn?Il(e.definition,r=>oa(r,t)):e instanceof Zt&&$t(t,e)?!1:e instanceof Gn?(e instanceof Zt&&t.push(e),Rn(e.definition,r=>oa(r,t))):!1}function xA(e){return e instanceof Cn}function Kn(e){if(e instanceof Zt)return"SUBRULE";if(e instanceof Qt)return"OPTION";if(e instanceof Cn)return"OR";if(e instanceof Hn)return"AT_LEAST_ONE";if(e instanceof Vn)return"AT_LEAST_ONE_SEP";if(e instanceof Nn)return"MANY_SEP";if(e instanceof bt)return"MANY";if(e instanceof tt)return"CONSUME";throw Error("non exhaustive match")}class aa{walk(t,n=[]){me(t.definition,(r,i)=>{const s=Lt(t.definition,i+1);if(r instanceof Zt)this.walkProdRef(r,s,n);else if(r instanceof tt)this.walkTerminal(r,s,n);else if(r instanceof Yt)this.walkFlat(r,s,n);else if(r instanceof Qt)this.walkOption(r,s,n);else if(r instanceof Hn)this.walkAtLeastOne(r,s,n);else if(r instanceof Vn)this.walkAtLeastOneSep(r,s,n);else if(r instanceof Nn)this.walkManySep(r,s,n);else if(r instanceof bt)this.walkMany(r,s,n);else if(r instanceof Cn)this.walkOr(r,s,n);else throw Error("non exhaustive match")})}walkTerminal(t,n,r){}walkProdRef(t,n,r){}walkFlat(t,n,r){const i=n.concat(r);this.walk(t,i)}walkOption(t,n,r){const i=n.concat(r);this.walk(t,i)}walkAtLeastOne(t,n,r){const i=[new Qt({definition:t.definition})].concat(n,r);this.walk(t,i)}walkAtLeastOneSep(t,n,r){const i=np(t,n,r);this.walk(t,i)}walkMany(t,n,r){const i=[new Qt({definition:t.definition})].concat(n,r);this.walk(t,i)}walkManySep(t,n,r){const i=np(t,n,r);this.walk(t,i)}walkOr(t,n,r){const i=n.concat(r);me(t.definition,s=>{const o=new Yt({definition:[s]});this.walk(o,i)})}}function np(e,t,n){return[new Qt({definition:[new tt({terminalType:e.separator})].concat(e.definition)})].concat(t,n)}function Os(e){if(e instanceof Zt)return Os(e.referencedRule);if(e instanceof tt)return OA(e);if(TA(e))return RA(e);if(xA(e))return IA(e);throw Error("non exhaustive match")}function RA(e){let t=[];const n=e.definition;let r=0,i=n.length>r,s,o=!0;for(;i&&o;)s=n[r],o=oa(s),t=t.concat(Os(s)),r=r+1,i=n.length>r;return ia(t)}function IA(e){const t=ce(e.definition,n=>Os(n));return ia(sn(t))}function OA(e){return[e.terminalType]}const rp="_~IN~_";class NA extends aa{constructor(t){super(),this.topProd=t,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(t,n,r){}walkProdRef(t,n,r){const i=LA(t.referencedRule,t.idx)+this.topProd.name,s=n.concat(r),o=new Yt({definition:s}),a=Os(o);this.follows[i]=a}}function CA(e){const t={};return me(e,n=>{const r=new NA(n).startWalking();qt(t,r)}),t}function LA(e,t){return e.name+t+rp}function ge(e){return e.charCodeAt(0)}function Nl(e,t){Array.isArray(e)?e.forEach(function(n){t.push(n)}):t.push(e)}function Ns(e,t){if(e[t]===!0)throw"duplicate flag "+t;e[t],e[t]=!0}function Vi(e){if(e===void 0)throw Error("Internal Error - Should never get here!");return!0}function MA(){throw Error("Internal Error - Should never get here!")}function ip(e){return e.type==="Character"}const ca=[];for(let e=ge("0");e<=ge("9");e++)ca.push(e);const la=[ge("_")].concat(ca);for(let e=ge("a");e<=ge("z");e++)la.push(e);for(let e=ge("A");e<=ge("Z");e++)la.push(e);const sp=[ge(" "),ge("\f"),ge(` +`),ge("\r"),ge(" "),ge("\v"),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge("\u2028"),ge("\u2029"),ge(" "),ge(" "),ge(" "),ge("\uFEFF")],UA=/[0-9a-fA-F]/,ua=/[0-9]/,PA=/[1-9]/;class DA{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(t){this.idx=t.idx,this.input=t.input,this.groupIdx=t.groupIdx}pattern(t){this.idx=0,this.input=t,this.groupIdx=0,this.consumeChar("/");const n=this.disjunction();this.consumeChar("/");const r={type:"Flags",loc:{begin:this.idx,end:t.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":Ns(r,"global");break;case"i":Ns(r,"ignoreCase");break;case"m":Ns(r,"multiLine");break;case"u":Ns(r,"unicode");break;case"y":Ns(r,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:n,loc:this.loc(0)}}disjunction(){const t=[],n=this.idx;for(t.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),t.push(this.alternative());return{type:"Disjunction",value:t,loc:this.loc(n)}}alternative(){const t=[],n=this.idx;for(;this.isTerm();)t.push(this.term());return{type:"Alternative",value:t,loc:this.loc(n)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){const t=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(t)};case"$":return{type:"EndAnchor",loc:this.loc(t)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(t)};case"B":return{type:"NonWordBoundary",loc:this.loc(t)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let n;switch(this.popChar()){case"=":n="Lookahead";break;case"!":n="NegativeLookahead";break}Vi(n);const r=this.disjunction();return this.consumeChar(")"),{type:n,value:r,loc:this.loc(t)}}return MA()}quantifier(t=!1){let n;const r=this.idx;switch(this.popChar()){case"*":n={atLeast:0,atMost:1/0};break;case"+":n={atLeast:1,atMost:1/0};break;case"?":n={atLeast:0,atMost:1};break;case"{":const i=this.integerIncludingZero();switch(this.popChar()){case"}":n={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),n={atLeast:i,atMost:s}):n={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(t===!0&&n===void 0)return;Vi(n);break}if(!(t===!0&&n===void 0)&&Vi(n))return this.peekChar(0)==="?"?(this.consumeChar("?"),n.greedy=!1):n.greedy=!0,n.type="Quantifier",n.loc=this.loc(r),n}atom(){let t;const n=this.idx;switch(this.peekChar()){case".":t=this.dotAll();break;case"\\":t=this.atomEscape();break;case"[":t=this.characterClass();break;case"(":t=this.group();break}if(t===void 0&&this.isPatternCharacter()&&(t=this.patternCharacter()),Vi(t))return t.loc=this.loc(n),this.isQuantifier()&&(t.quantifier=this.quantifier()),t}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[ge(` `),ge("\r"),ge("\u2028"),ge("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let t,n=!1;switch(this.popChar()){case"d":t=ca;break;case"D":t=ca,n=!0;break;case"s":t=sp;break;case"S":t=sp,n=!0;break;case"w":t=la;break;case"W":t=la,n=!0;break}if(Vi(t))return{type:"Set",value:t,complement:n}}controlEscapeAtom(){let t;switch(this.popChar()){case"f":t=ge("\f");break;case"n":t=ge(` `);break;case"r":t=ge("\r");break;case"t":t=ge(" ");break;case"v":t=ge("\v");break}if(Vi(t))return{type:"Character",value:t}}controlLetterEscapeAtom(){this.consumeChar("c");const t=this.popChar();if(/[a-zA-Z]/.test(t)===!1)throw Error("Invalid ");return{type:"Character",value:t.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:ge("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){const t=this.popChar();return{type:"Character",value:ge(t)}}classPatternCharacterAtom(){switch(this.peekChar()){case` `:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:const t=this.popChar();return{type:"Character",value:ge(t)}}}characterClass(){const t=[];let n=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),n=!0);this.isClassAtom();){const r=this.classAtom();if(r.type,ip(r)&&this.isRangeDash()){this.consumeChar("-");const i=this.classAtom();if(i.type,ip(i)){if(i.value=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(t){return{begin:t,end:this.idx}}}class Cl{visitChildren(t){for(const n in t){const r=t[n];t.hasOwnProperty(n)&&(r.type!==void 0?this.visit(r):Array.isArray(r)&&r.forEach(i=>{this.visit(i)},this))}}visit(t){switch(t.type){case"Pattern":this.visitPattern(t);break;case"Flags":this.visitFlags(t);break;case"Disjunction":this.visitDisjunction(t);break;case"Alternative":this.visitAlternative(t);break;case"StartAnchor":this.visitStartAnchor(t);break;case"EndAnchor":this.visitEndAnchor(t);break;case"WordBoundary":this.visitWordBoundary(t);break;case"NonWordBoundary":this.visitNonWordBoundary(t);break;case"Lookahead":this.visitLookahead(t);break;case"NegativeLookahead":this.visitNegativeLookahead(t);break;case"Character":this.visitCharacter(t);break;case"Set":this.visitSet(t);break;case"Group":this.visitGroup(t);break;case"GroupBackReference":this.visitGroupBackReference(t);break;case"Quantifier":this.visitQuantifier(t);break}this.visitChildren(t)}visitPattern(t){}visitFlags(t){}visitDisjunction(t){}visitAlternative(t){}visitStartAnchor(t){}visitEndAnchor(t){}visitWordBoundary(t){}visitNonWordBoundary(t){}visitLookahead(t){}visitNegativeLookahead(t){}visitCharacter(t){}visitSet(t){}visitGroup(t){}visitGroupBackReference(t){}visitQuantifier(t){}}let fa={};const DA=new PA;function ha(e){const t=e.toString();if(fa.hasOwnProperty(t))return fa[t];{const n=DA.pattern(t);return fa[t]=n,n}}function BA(){fa={}}const op="Complement Sets are not supported for first char optimization",da=`Unable to use "first char" lexer optimizations: -`;function FA(e,t=!1){try{const n=ha(e);return Ll(n.value,{},n.flags.ignoreCase)}catch(n){if(n.message===op)t&&Qd(`${da} Unable to optimize: < ${e.toString()} > +`:case"\r":case"\u2028":case"\u2029":return!1;default:return!0}}parseHexDigits(t){let n="";for(let i=0;i=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(t){return{begin:t,end:this.idx}}}class Cl{visitChildren(t){for(const n in t){const r=t[n];t.hasOwnProperty(n)&&(r.type!==void 0?this.visit(r):Array.isArray(r)&&r.forEach(i=>{this.visit(i)},this))}}visit(t){switch(t.type){case"Pattern":this.visitPattern(t);break;case"Flags":this.visitFlags(t);break;case"Disjunction":this.visitDisjunction(t);break;case"Alternative":this.visitAlternative(t);break;case"StartAnchor":this.visitStartAnchor(t);break;case"EndAnchor":this.visitEndAnchor(t);break;case"WordBoundary":this.visitWordBoundary(t);break;case"NonWordBoundary":this.visitNonWordBoundary(t);break;case"Lookahead":this.visitLookahead(t);break;case"NegativeLookahead":this.visitNegativeLookahead(t);break;case"Character":this.visitCharacter(t);break;case"Set":this.visitSet(t);break;case"Group":this.visitGroup(t);break;case"GroupBackReference":this.visitGroupBackReference(t);break;case"Quantifier":this.visitQuantifier(t);break}this.visitChildren(t)}visitPattern(t){}visitFlags(t){}visitDisjunction(t){}visitAlternative(t){}visitStartAnchor(t){}visitEndAnchor(t){}visitWordBoundary(t){}visitNonWordBoundary(t){}visitLookahead(t){}visitNegativeLookahead(t){}visitCharacter(t){}visitSet(t){}visitGroup(t){}visitGroupBackReference(t){}visitQuantifier(t){}}let fa={};const BA=new DA;function ha(e){const t=e.toString();if(fa.hasOwnProperty(t))return fa[t];{const n=BA.pattern(t);return fa[t]=n,n}}function FA(){fa={}}const op="Complement Sets are not supported for first char optimization",da=`Unable to use "first char" lexer optimizations: +`;function $A(e,t=!1){try{const n=ha(e);return Ll(n.value,{},n.flags.ignoreCase)}catch(n){if(n.message===op)t&&Qd(`${da} Unable to optimize: < ${e.toString()} > Complement Sets cannot be automatically optimized. This will disable the lexer's first char optimizations. See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let r="";t&&(r=` @@ -32,48 +32,48 @@ var YM=Object.defineProperty;var QM=(cr,Ue,Bt)=>Ue in cr?YM(cr,Ue,{enumerable:!0 See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),Ol(`${da} Failed parsing: < ${e.toString()} > Using the @chevrotain/regexp-to-ast library - Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}function Ll(e,t,n){switch(e.type){case"Disjunction":for(let i=0;i{if(typeof c=="number")pa(c,t,n);else{const l=c;if(n===!0)for(let u=l.from;u<=l.to;u++)pa(u,t,n);else{for(let u=l.from;u<=l.to&&u=Ls){const u=l.from>=Ls?l.from:Ls,f=l.to,d=Fr(u),h=Fr(f);for(let p=d;p<=h;p++)t[p]=p}}}});break;case"Group":Ll(o.value,t,n);break;default:throw Error("Non Exhaustive Match")}const a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&Ml(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return dt(t)}function pa(e,t,n){const r=Fr(e);t[r]=r,n===!0&&$A(e,t)}function $A(e,t){const n=String.fromCharCode(e),r=n.toUpperCase();if(r!==n){const i=Fr(r.charCodeAt(0));t[i]=i}else{const i=n.toLowerCase();if(i!==n){const s=Fr(i.charCodeAt(0));t[s]=s}}}function ap(e,t){return Gi(e.value,n=>{if(typeof n=="number")return $t(t,n);{const r=n;return Gi(t,i=>r.from<=i&&i<=r.to)!==void 0}})}function Ml(e){const t=e.quantifier;return t&&t.atLeast===0?!0:e.value?Le(e.value)?Rn(e.value,Ml):Ml(e.value):!1}class jA extends Cl{constructor(t){super(),this.targetCharCodes=t,this.found=!1}visitChildren(t){if(this.found!==!0){switch(t.type){case"Lookahead":this.visitLookahead(t);return;case"NegativeLookahead":this.visitNegativeLookahead(t);return}super.visitChildren(t)}}visitCharacter(t){$t(this.targetCharCodes,t.value)&&(this.found=!0)}visitSet(t){t.complement?ap(t,this.targetCharCodes)===void 0&&(this.found=!0):ap(t,this.targetCharCodes)!==void 0&&(this.found=!0)}}function Ul(e,t){if(t instanceof RegExp){const n=ha(t),r=new jA(e);return r.visit(n),r.found}else return Gi(t,n=>$t(e,n.charCodeAt(0)))!==void 0}const fi="PATTERN",Cs="defaultMode",ma="modes";let cp=typeof new RegExp("(?:)").sticky=="boolean";function zA(e,t){t=Rl(t,{useSticky:cp,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` -`],tracer:(w,v)=>v()});const n=t.tracer;n("initCharCodeToOptimizedIndexMap",()=>{fT()});let r;n("Reject Lexer.NA",()=>{r=ra(e,w=>w[fi]===wt.NA)});let i=!1,s;n("Transform Patterns",()=>{i=!1,s=ce(r,w=>{const v=w[fi];if(gr(v)){const S=v.source;return S.length===1&&S!=="^"&&S!=="$"&&S!=="."&&!v.ignoreCase?S:S.length===2&&S[0]==="\\"&&!$t(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],S[1])?S[1]:t.useSticky?up(v):lp(v)}else{if(dr(v))return i=!0,{exec:v};if(typeof v=="object")return i=!0,v;if(typeof v=="string"){if(v.length===1)return v;{const S=v.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),L=new RegExp(S);return t.useSticky?up(L):lp(L)}}else throw Error("non exhaustive match")}})});let o,a,c,l,u;n("misc mapping",()=>{o=ce(r,w=>w.tokenTypeIdx),a=ce(r,w=>{const v=w.GROUP;if(v!==wt.SKIPPED){if(Jt(v))return v;if(yr(v))return!1;throw Error("non exhaustive match")}}),c=ce(r,w=>{const v=w.LONGER_ALT;if(v)return Le(v)?ce(v,L=>Zd(r,L)):[Zd(r,v)]}),l=ce(r,w=>w.PUSH_MODE),u=ce(r,w=>pe(w,"POP_MODE"))});let f;n("Line Terminator Handling",()=>{const w=dp(t.lineTerminatorCharacters);f=ce(r,v=>!1),t.positionTracking!=="onlyOffset"&&(f=ce(r,v=>pe(v,"LINE_BREAKS")?!!v.LINE_BREAKS:hp(v,w)===!1&&Ul(w,v.PATTERN)))});let d,h,p,m;n("Misc Mapping #2",()=>{d=ce(r,fp),h=ce(s,cT),p=Xt(r,(w,v)=>{const S=v.GROUP;return Jt(S)&&S!==wt.SKIPPED&&(w[S]=[]),w},{}),m=ce(s,(w,v)=>({pattern:s[v],longerAlt:c[v],canLineTerminator:f[v],isCustom:d[v],short:h[v],group:a[v],push:l[v],pop:u[v],tokenTypeIdx:o[v],tokenType:r[v]}))});let b=!0,_=[];return t.safeMode||n("First Char Optimization",()=>{_=Xt(r,(w,v,S)=>{if(typeof v.PATTERN=="string"){const L=v.PATTERN.charCodeAt(0),I=Fr(L);Pl(w,I,m[S])}else if(Le(v.START_CHARS_HINT)){let L;me(v.START_CHARS_HINT,I=>{const T=typeof I=="string"?I.charCodeAt(0):I,M=Fr(T);L!==M&&(L=M,Pl(w,M,m[S]))})}else if(gr(v.PATTERN))if(v.PATTERN.unicode)b=!1,t.ensureOptimizations&&Ol(`${da} Unable to analyze < ${v.PATTERN.toString()} > pattern. + Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}function Ll(e,t,n){switch(e.type){case"Disjunction":for(let i=0;i{if(typeof c=="number")pa(c,t,n);else{const l=c;if(n===!0)for(let u=l.from;u<=l.to;u++)pa(u,t,n);else{for(let u=l.from;u<=l.to&&u=Ls){const u=l.from>=Ls?l.from:Ls,f=l.to,d=Fr(u),h=Fr(f);for(let p=d;p<=h;p++)t[p]=p}}}});break;case"Group":Ll(o.value,t,n);break;default:throw Error("Non Exhaustive Match")}const a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&Ml(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return dt(t)}function pa(e,t,n){const r=Fr(e);t[r]=r,n===!0&&jA(e,t)}function jA(e,t){const n=String.fromCharCode(e),r=n.toUpperCase();if(r!==n){const i=Fr(r.charCodeAt(0));t[i]=i}else{const i=n.toLowerCase();if(i!==n){const s=Fr(i.charCodeAt(0));t[s]=s}}}function ap(e,t){return Gi(e.value,n=>{if(typeof n=="number")return $t(t,n);{const r=n;return Gi(t,i=>r.from<=i&&i<=r.to)!==void 0}})}function Ml(e){const t=e.quantifier;return t&&t.atLeast===0?!0:e.value?Le(e.value)?Rn(e.value,Ml):Ml(e.value):!1}class zA extends Cl{constructor(t){super(),this.targetCharCodes=t,this.found=!1}visitChildren(t){if(this.found!==!0){switch(t.type){case"Lookahead":this.visitLookahead(t);return;case"NegativeLookahead":this.visitNegativeLookahead(t);return}super.visitChildren(t)}}visitCharacter(t){$t(this.targetCharCodes,t.value)&&(this.found=!0)}visitSet(t){t.complement?ap(t,this.targetCharCodes)===void 0&&(this.found=!0):ap(t,this.targetCharCodes)!==void 0&&(this.found=!0)}}function Ul(e,t){if(t instanceof RegExp){const n=ha(t),r=new zA(e);return r.visit(n),r.found}else return Gi(t,n=>$t(e,n.charCodeAt(0)))!==void 0}const fi="PATTERN",Cs="defaultMode",ma="modes";let cp=typeof new RegExp("(?:)").sticky=="boolean";function WA(e,t){t=Rl(t,{useSticky:cp,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` +`],tracer:(w,v)=>v()});const n=t.tracer;n("initCharCodeToOptimizedIndexMap",()=>{hT()});let r;n("Reject Lexer.NA",()=>{r=ra(e,w=>w[fi]===wt.NA)});let i=!1,s;n("Transform Patterns",()=>{i=!1,s=ce(r,w=>{const v=w[fi];if(gr(v)){const S=v.source;return S.length===1&&S!=="^"&&S!=="$"&&S!=="."&&!v.ignoreCase?S:S.length===2&&S[0]==="\\"&&!$t(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],S[1])?S[1]:t.useSticky?up(v):lp(v)}else{if(dr(v))return i=!0,{exec:v};if(typeof v=="object")return i=!0,v;if(typeof v=="string"){if(v.length===1)return v;{const S=v.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),L=new RegExp(S);return t.useSticky?up(L):lp(L)}}else throw Error("non exhaustive match")}})});let o,a,c,l,u;n("misc mapping",()=>{o=ce(r,w=>w.tokenTypeIdx),a=ce(r,w=>{const v=w.GROUP;if(v!==wt.SKIPPED){if(Jt(v))return v;if(yr(v))return!1;throw Error("non exhaustive match")}}),c=ce(r,w=>{const v=w.LONGER_ALT;if(v)return Le(v)?ce(v,L=>Zd(r,L)):[Zd(r,v)]}),l=ce(r,w=>w.PUSH_MODE),u=ce(r,w=>pe(w,"POP_MODE"))});let f;n("Line Terminator Handling",()=>{const w=dp(t.lineTerminatorCharacters);f=ce(r,v=>!1),t.positionTracking!=="onlyOffset"&&(f=ce(r,v=>pe(v,"LINE_BREAKS")?!!v.LINE_BREAKS:hp(v,w)===!1&&Ul(w,v.PATTERN)))});let d,h,p,m;n("Misc Mapping #2",()=>{d=ce(r,fp),h=ce(s,lT),p=Xt(r,(w,v)=>{const S=v.GROUP;return Jt(S)&&S!==wt.SKIPPED&&(w[S]=[]),w},{}),m=ce(s,(w,v)=>({pattern:s[v],longerAlt:c[v],canLineTerminator:f[v],isCustom:d[v],short:h[v],group:a[v],push:l[v],pop:u[v],tokenTypeIdx:o[v],tokenType:r[v]}))});let b=!0,_=[];return t.safeMode||n("First Char Optimization",()=>{_=Xt(r,(w,v,S)=>{if(typeof v.PATTERN=="string"){const L=v.PATTERN.charCodeAt(0),I=Fr(L);Pl(w,I,m[S])}else if(Le(v.START_CHARS_HINT)){let L;me(v.START_CHARS_HINT,I=>{const T=typeof I=="string"?I.charCodeAt(0):I,M=Fr(T);L!==M&&(L=M,Pl(w,M,m[S]))})}else if(gr(v.PATTERN))if(v.PATTERN.unicode)b=!1,t.ensureOptimizations&&Ol(`${da} Unable to analyze < ${v.PATTERN.toString()} > pattern. The regexp unicode flag is not currently supported by the regexp-to-ast library. This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{const L=FA(v.PATTERN,t.ensureOptimizations);Ve(L)&&(b=!1),me(L,I=>{Pl(w,I,m[S])})}else t.ensureOptimizations&&Ol(`${da} TokenType: <${v.name}> is using a custom token pattern without providing parameter. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{const L=$A(v.PATTERN,t.ensureOptimizations);Ve(L)&&(b=!1),me(L,I=>{Pl(w,I,m[S])})}else t.ensureOptimizations&&Ol(`${da} TokenType: <${v.name}> is using a custom token pattern without providing parameter. This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),b=!1;return w},[])}),{emptyGroups:p,patternIdxToConfig:m,charCodeToPatternIdxToConfig:_,hasCustom:i,canBeOptimized:b}}function WA(e,t){let n=[];const r=HA(e);n=n.concat(r.errors);const i=VA(r.valid),s=i.valid;return n=n.concat(i.errors),n=n.concat(GA(s)),n=n.concat(eT(s)),n=n.concat(tT(s,t)),n=n.concat(nT(s)),n}function GA(e){let t=[];const n=gn(e,r=>gr(r[fi]));return t=t.concat(qA(n)),t=t.concat(ZA(n)),t=t.concat(YA(n)),t=t.concat(QA(n)),t=t.concat(JA(n)),t}function HA(e){const t=gn(e,i=>!pe(i,fi)),n=ce(t,i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:st.MISSING_PATTERN,tokenTypes:[i]})),r=na(e,t);return{errors:n,valid:r}}function VA(e){const t=gn(e,i=>{const s=i[fi];return!gr(s)&&!dr(s)&&!pe(s,"exec")&&!Jt(s)}),n=ce(t,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:st.INVALID_PATTERN,tokenTypes:[i]})),r=na(e,t);return{errors:n,valid:r}}const KA=/[^\\][$]/;function qA(e){class t extends Cl{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}const n=gn(e,i=>{const s=i.PATTERN;try{const o=ha(s),a=new t;return a.visit(o),a.found}catch{return KA.test(s.source)}});return ce(n,i=>({message:`Unexpected RegExp Anchor Error: + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),b=!1;return w},[])}),{emptyGroups:p,patternIdxToConfig:m,charCodeToPatternIdxToConfig:_,hasCustom:i,canBeOptimized:b}}function GA(e,t){let n=[];const r=VA(e);n=n.concat(r.errors);const i=KA(r.valid),s=i.valid;return n=n.concat(i.errors),n=n.concat(HA(s)),n=n.concat(tT(s)),n=n.concat(nT(s,t)),n=n.concat(rT(s)),n}function HA(e){let t=[];const n=gn(e,r=>gr(r[fi]));return t=t.concat(JA(n)),t=t.concat(YA(n)),t=t.concat(QA(n)),t=t.concat(eT(n)),t=t.concat(XA(n)),t}function VA(e){const t=gn(e,i=>!pe(i,fi)),n=ce(t,i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:st.MISSING_PATTERN,tokenTypes:[i]})),r=na(e,t);return{errors:n,valid:r}}function KA(e){const t=gn(e,i=>{const s=i[fi];return!gr(s)&&!dr(s)&&!pe(s,"exec")&&!Jt(s)}),n=ce(t,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:st.INVALID_PATTERN,tokenTypes:[i]})),r=na(e,t);return{errors:n,valid:r}}const qA=/[^\\][$]/;function JA(e){class t extends Cl{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}const n=gn(e,i=>{const s=i.PATTERN;try{const o=ha(s),a=new t;return a.visit(o),a.found}catch{return qA.test(s.source)}});return ce(n,i=>({message:`Unexpected RegExp Anchor Error: Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' - See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:st.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function JA(e){const t=gn(e,r=>r.PATTERN.test(""));return ce(t,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' must not match an empty string",type:st.EMPTY_MATCH_PATTERN,tokenTypes:[r]}))}const XA=/[^\\[][\^]|^\^/;function ZA(e){class t extends Cl{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}const n=gn(e,i=>{const s=i.PATTERN;try{const o=ha(s),a=new t;return a.visit(o),a.found}catch{return XA.test(s.source)}});return ce(n,i=>({message:`Unexpected RegExp Anchor Error: + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:st.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function XA(e){const t=gn(e,r=>r.PATTERN.test(""));return ce(t,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' must not match an empty string",type:st.EMPTY_MATCH_PATTERN,tokenTypes:[r]}))}const ZA=/[^\\[][\^]|^\^/;function YA(e){class t extends Cl{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}const n=gn(e,i=>{const s=i.PATTERN;try{const o=ha(s),a=new t;return a.visit(o),a.found}catch{return ZA.test(s.source)}});return ce(n,i=>({message:`Unexpected RegExp Anchor Error: Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:st.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function YA(e){const t=gn(e,r=>{const i=r[fi];return i instanceof RegExp&&(i.multiline||i.global)});return ce(t,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:st.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[r]}))}function QA(e){const t=[];let n=ce(e,s=>Xt(e,(o,a)=>(s.PATTERN.source===a.PATTERN.source&&!$t(t,a)&&a.PATTERN!==wt.NA&&(t.push(a),o.push(a)),o),[]));n=Rs(n);const r=gn(n,s=>s.length>1);return ce(r,s=>{const o=ce(s,c=>c.name);return{message:`The same RegExp pattern ->${In(s).PATTERN}<-has been used in all of the following Token Types: ${o.join(", ")} <-`,type:st.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function eT(e){const t=gn(e,r=>{if(!pe(r,"GROUP"))return!1;const i=r.GROUP;return i!==wt.SKIPPED&&i!==wt.NA&&!Jt(i)});return ce(t,r=>({message:"Token Type: ->"+r.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:st.INVALID_GROUP_TYPE_FOUND,tokenTypes:[r]}))}function tT(e,t){const n=gn(e,i=>i.PUSH_MODE!==void 0&&!$t(t,i.PUSH_MODE));return ce(n,i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:st.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function nT(e){const t=[],n=Xt(e,(r,i,s)=>{const o=i.PATTERN;return o===wt.NA||(Jt(o)?r.push({str:o,idx:s,tokenType:i}):gr(o)&&iT(o)&&r.push({str:o.source,idx:s,tokenType:i})),r},[]);return me(e,(r,i)=>{me(n,({str:s,idx:o,tokenType:a})=>{if(i${a.name}<- can never be matched. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:st.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function QA(e){const t=gn(e,r=>{const i=r[fi];return i instanceof RegExp&&(i.multiline||i.global)});return ce(t,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:st.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[r]}))}function eT(e){const t=[];let n=ce(e,s=>Xt(e,(o,a)=>(s.PATTERN.source===a.PATTERN.source&&!$t(t,a)&&a.PATTERN!==wt.NA&&(t.push(a),o.push(a)),o),[]));n=Rs(n);const r=gn(n,s=>s.length>1);return ce(r,s=>{const o=ce(s,c=>c.name);return{message:`The same RegExp pattern ->${In(s).PATTERN}<-has been used in all of the following Token Types: ${o.join(", ")} <-`,type:st.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function tT(e){const t=gn(e,r=>{if(!pe(r,"GROUP"))return!1;const i=r.GROUP;return i!==wt.SKIPPED&&i!==wt.NA&&!Jt(i)});return ce(t,r=>({message:"Token Type: ->"+r.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:st.INVALID_GROUP_TYPE_FOUND,tokenTypes:[r]}))}function nT(e,t){const n=gn(e,i=>i.PUSH_MODE!==void 0&&!$t(t,i.PUSH_MODE));return ce(n,i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:st.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function rT(e){const t=[],n=Xt(e,(r,i,s)=>{const o=i.PATTERN;return o===wt.NA||(Jt(o)?r.push({str:o,idx:s,tokenType:i}):gr(o)&&sT(o)&&r.push({str:o.source,idx:s,tokenType:i})),r},[]);return me(e,(r,i)=>{me(n,({str:s,idx:o,tokenType:a})=>{if(i${a.name}<- can never be matched. Because it appears AFTER the Token Type ->${r.name}<-in the lexer's definition. -See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;t.push({message:c,type:st.UNREACHABLE_PATTERN,tokenTypes:[r,a]})}})}),t}function rT(e,t){if(gr(t)){const n=t.exec(e);return n!==null&&n.index===0}else{if(dr(t))return t(e,0,[],{});if(pe(t,"exec"))return t.exec(e,0,[],{});if(typeof t=="string")return t===e;throw Error("non exhaustive match")}}function iT(e){return Gi([".","\\","[","]","|","^","$","(",")","?","*","+","{"],n=>e.source.indexOf(n)!==-1)===void 0}function lp(e){const t=e.ignoreCase?"i":"";return new RegExp(`^(?:${e.source})`,t)}function up(e){const t=e.ignoreCase?"iy":"y";return new RegExp(`${e.source}`,t)}function sT(e,t,n){const r=[];return pe(e,Cs)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+Cs+`> property in its definition +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;t.push({message:c,type:st.UNREACHABLE_PATTERN,tokenTypes:[r,a]})}})}),t}function iT(e,t){if(gr(t)){const n=t.exec(e);return n!==null&&n.index===0}else{if(dr(t))return t(e,0,[],{});if(pe(t,"exec"))return t.exec(e,0,[],{});if(typeof t=="string")return t===e;throw Error("non exhaustive match")}}function sT(e){return Gi([".","\\","[","]","|","^","$","(",")","?","*","+","{"],n=>e.source.indexOf(n)!==-1)===void 0}function lp(e){const t=e.ignoreCase?"i":"";return new RegExp(`^(?:${e.source})`,t)}function up(e){const t=e.ignoreCase?"iy":"y";return new RegExp(`${e.source}`,t)}function oT(e,t,n){const r=[];return pe(e,Cs)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+Cs+`> property in its definition `,type:st.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),pe(e,ma)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+ma+`> property in its definition `,type:st.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),pe(e,ma)&&pe(e,Cs)&&!pe(e.modes,e.defaultMode)&&r.push({message:`A MultiMode Lexer cannot be initialized with a ${Cs}: <${e.defaultMode}>which does not exist `,type:st.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),pe(e,ma)&&me(e.modes,(i,s)=>{me(i,(o,a)=>{if(yr(o))r.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${s}> at index: <${a}> `,type:st.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if(pe(o,"LONGER_ALT")){const c=Le(o.LONGER_ALT)?o.LONGER_ALT:[o.LONGER_ALT];me(c,l=>{!yr(l)&&!$t(i,l)&&r.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${l.name}> on token <${o.name}> outside of mode <${s}> -`,type:st.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),r}function oT(e,t,n){const r=[];let i=!1;const s=Rs(sn(dt(e.modes))),o=ra(s,c=>c[fi]===wt.NA),a=dp(n);return t&&me(o,c=>{const l=hp(c,a);if(l!==!1){const f={message:uT(c,l),type:l.issue,tokenType:c};r.push(f)}else pe(c,"LINE_BREAKS")?c.LINE_BREAKS===!0&&(i=!0):Ul(a,c.PATTERN)&&(i=!0)}),t&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. +`,type:st.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),r}function aT(e,t,n){const r=[];let i=!1;const s=Rs(sn(dt(e.modes))),o=ra(s,c=>c[fi]===wt.NA),a=dp(n);return t&&me(o,c=>{const l=hp(c,a);if(l!==!1){const f={message:fT(c,l),type:l.issue,tokenType:c};r.push(f)}else pe(c,"LINE_BREAKS")?c.LINE_BREAKS===!0&&(i=!0):Ul(a,c.PATTERN)&&(i=!0)}),t&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. This Lexer has been defined to track line and column information, But none of the Token Types can be identified as matching a line terminator. See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS - for details.`,type:st.NO_LINE_BREAKS_FLAGS}),r}function aT(e){const t={},n=pn(e);return me(n,r=>{const i=e[r];if(Le(i))t[r]=[];else throw Error("non exhaustive match")}),t}function fp(e){const t=e.PATTERN;if(gr(t))return!1;if(dr(t))return!0;if(pe(t,"exec"))return!0;if(Jt(t))return!1;throw Error("non exhaustive match")}function cT(e){return Jt(e)&&e.length===1?e.charCodeAt(0):!1}const lT={test:function(e){const t=e.length;for(let n=this.lastIndex;n{const i=e[r];if(Le(i))t[r]=[];else throw Error("non exhaustive match")}),t}function fp(e){const t=e.PATTERN;if(gr(t))return!1;if(dr(t))return!0;if(pe(t,"exec"))return!0;if(Jt(t))return!1;throw Error("non exhaustive match")}function lT(e){return Jt(e)&&e.length===1?e.charCodeAt(0):!1}const uT={test:function(e){const t=e.length;for(let n=this.lastIndex;n Token Type Root cause: ${t.errMsg}. For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(t.issue===st.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. The problem is in the <${e.name}> Token Type - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function dp(e){return ce(e,n=>Jt(n)?n.charCodeAt(0):n)}function Pl(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}const Ls=256;let ga=[];function Fr(e){return e255?255+~~(e/255):e}}function Ms(e,t){const n=e.tokenTypeIdx;return n===t.tokenTypeIdx?!0:t.isParent===!0&&t.categoryMatchesMap[n]===!0}function ya(e,t){return e.tokenTypeIdx===t.tokenTypeIdx}let pp=1;const mp={};function Us(e){const t=hT(e);dT(t),mT(t),pT(t),me(t,n=>{n.isParent=n.categoryMatches.length>0})}function hT(e){let t=Ct(e),n=e,r=!0;for(;r;){n=Rs(sn(ce(n,s=>s.CATEGORIES)));const i=na(n,t);t=t.concat(i),Ve(i)?r=!1:n=i}return t}function dT(e){me(e,t=>{yp(t)||(mp[pp]=t,t.tokenTypeIdx=pp++),_p(t)&&!Le(t.CATEGORIES)&&(t.CATEGORIES=[t.CATEGORIES]),_p(t)||(t.CATEGORIES=[]),gT(t)||(t.categoryMatches=[]),yT(t)||(t.categoryMatchesMap={})})}function pT(e){me(e,t=>{t.categoryMatches=[],me(t.categoryMatchesMap,(n,r)=>{t.categoryMatches.push(mp[r].tokenTypeIdx)})})}function mT(e){me(e,t=>{gp([],t)})}function gp(e,t){me(e,n=>{t.categoryMatchesMap[n.tokenTypeIdx]=!0}),me(t.CATEGORIES,n=>{const r=e.concat(t);$t(r,n)||gp(r,n)})}function yp(e){return pe(e,"tokenTypeIdx")}function _p(e){return pe(e,"CATEGORIES")}function gT(e){return pe(e,"categoryMatches")}function yT(e){return pe(e,"categoryMatchesMap")}function _T(e){return pe(e,"tokenTypeIdx")}const bT={buildUnableToPopLexerModeMessage(e){return`Unable to pop Lexer Mode after encountering Token ->${e.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(e,t,n,r,i){return`unexpected character: ->${e.charAt(t)}<- at offset: ${t}, skipped ${n} characters.`}};var st;(function(e){e[e.MISSING_PATTERN=0]="MISSING_PATTERN",e[e.INVALID_PATTERN=1]="INVALID_PATTERN",e[e.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",e[e.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",e[e.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",e[e.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",e[e.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",e[e.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",e[e.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",e[e.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",e[e.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",e[e.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",e[e.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",e[e.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",e[e.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",e[e.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",e[e.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",e[e.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(st||(st={}));const Ps={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` -`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:bT,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(Ps);class wt{constructor(t,n=Ps){if(this.lexerDefinition=t,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;const o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${i}>`);const{time:a,value:c}=ep(s),l=a>10?console.warn:console.log;return this.traceInitIndent time: ${a}ms`),this.traceInitIndent--,c}else return s()},typeof n=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. -a boolean 2nd argument is no longer supported`);this.config=qt({},Ps,n);const r=this.config.traceInitPerf;r===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof r=="number"&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===Ps.lineTerminatorsPattern)this.config.lineTerminatorsPattern=lT;else if(this.config.lineTerminatorCharacters===Ps.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(n.safeMode&&n.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),Le(t)?i={modes:{defaultMode:Ct(t)},defaultMode:Cs}:(s=!1,i=Ct(t))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(sT(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(oT(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},me(i.modes,(a,c)=>{i.modes[c]=ra(a,l=>yr(l))});const o=pn(i.modes);if(me(i.modes,(a,c)=>{this.TRACE_INIT(`Mode: <${c}> processing`,()=>{if(this.modes.push(c),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(WA(a,o))}),Ve(this.lexerDefinitionErrors)){Us(a);let l;this.TRACE_INIT("analyzeTokenTypes",()=>{l=zA(a,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:n.positionTracking,ensureOptimizations:n.ensureOptimizations,safeMode:n.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[c]=l.patternIdxToConfig,this.charCodeToPatternIdxToConfig[c]=l.charCodeToPatternIdxToConfig,this.emptyGroups=qt({},this.emptyGroups,l.emptyGroups),this.hasCustom=l.hasCustom||this.hasCustom,this.canModeBeOptimized[c]=l.canBeOptimized}})}),this.defaultMode=i.defaultMode,!Ve(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){const c=ce(this.lexerDefinitionErrors,l=>l.message).join(`----------------------- + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function dp(e){return ce(e,n=>Jt(n)?n.charCodeAt(0):n)}function Pl(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}const Ls=256;let ga=[];function Fr(e){return e255?255+~~(e/255):e}}function Ms(e,t){const n=e.tokenTypeIdx;return n===t.tokenTypeIdx?!0:t.isParent===!0&&t.categoryMatchesMap[n]===!0}function ya(e,t){return e.tokenTypeIdx===t.tokenTypeIdx}let pp=1;const mp={};function Us(e){const t=dT(e);pT(t),gT(t),mT(t),me(t,n=>{n.isParent=n.categoryMatches.length>0})}function dT(e){let t=Ct(e),n=e,r=!0;for(;r;){n=Rs(sn(ce(n,s=>s.CATEGORIES)));const i=na(n,t);t=t.concat(i),Ve(i)?r=!1:n=i}return t}function pT(e){me(e,t=>{yp(t)||(mp[pp]=t,t.tokenTypeIdx=pp++),_p(t)&&!Le(t.CATEGORIES)&&(t.CATEGORIES=[t.CATEGORIES]),_p(t)||(t.CATEGORIES=[]),yT(t)||(t.categoryMatches=[]),_T(t)||(t.categoryMatchesMap={})})}function mT(e){me(e,t=>{t.categoryMatches=[],me(t.categoryMatchesMap,(n,r)=>{t.categoryMatches.push(mp[r].tokenTypeIdx)})})}function gT(e){me(e,t=>{gp([],t)})}function gp(e,t){me(e,n=>{t.categoryMatchesMap[n.tokenTypeIdx]=!0}),me(t.CATEGORIES,n=>{const r=e.concat(t);$t(r,n)||gp(r,n)})}function yp(e){return pe(e,"tokenTypeIdx")}function _p(e){return pe(e,"CATEGORIES")}function yT(e){return pe(e,"categoryMatches")}function _T(e){return pe(e,"categoryMatchesMap")}function bT(e){return pe(e,"tokenTypeIdx")}const wT={buildUnableToPopLexerModeMessage(e){return`Unable to pop Lexer Mode after encountering Token ->${e.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(e,t,n,r,i){return`unexpected character: ->${e.charAt(t)}<- at offset: ${t}, skipped ${n} characters.`}};var st;(function(e){e[e.MISSING_PATTERN=0]="MISSING_PATTERN",e[e.INVALID_PATTERN=1]="INVALID_PATTERN",e[e.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",e[e.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",e[e.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",e[e.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",e[e.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",e[e.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",e[e.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",e[e.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",e[e.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",e[e.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",e[e.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",e[e.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",e[e.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",e[e.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",e[e.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",e[e.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(st||(st={}));const Ps={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` +`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:wT,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(Ps);class wt{constructor(t,n=Ps){if(this.lexerDefinition=t,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;const o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${i}>`);const{time:a,value:c}=ep(s),l=a>10?console.warn:console.log;return this.traceInitIndent time: ${a}ms`),this.traceInitIndent--,c}else return s()},typeof n=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`);this.config=qt({},Ps,n);const r=this.config.traceInitPerf;r===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof r=="number"&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===Ps.lineTerminatorsPattern)this.config.lineTerminatorsPattern=uT;else if(this.config.lineTerminatorCharacters===Ps.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(n.safeMode&&n.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),Le(t)?i={modes:{defaultMode:Ct(t)},defaultMode:Cs}:(s=!1,i=Ct(t))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(oT(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(aT(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},me(i.modes,(a,c)=>{i.modes[c]=ra(a,l=>yr(l))});const o=pn(i.modes);if(me(i.modes,(a,c)=>{this.TRACE_INIT(`Mode: <${c}> processing`,()=>{if(this.modes.push(c),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(GA(a,o))}),Ve(this.lexerDefinitionErrors)){Us(a);let l;this.TRACE_INIT("analyzeTokenTypes",()=>{l=WA(a,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:n.positionTracking,ensureOptimizations:n.ensureOptimizations,safeMode:n.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[c]=l.patternIdxToConfig,this.charCodeToPatternIdxToConfig[c]=l.charCodeToPatternIdxToConfig,this.emptyGroups=qt({},this.emptyGroups,l.emptyGroups),this.hasCustom=l.hasCustom||this.hasCustom,this.canModeBeOptimized[c]=l.canBeOptimized}})}),this.defaultMode=i.defaultMode,!Ve(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){const c=ce(this.lexerDefinitionErrors,l=>l.message).join(`----------------------- `);throw new Error(`Errors detected in definition of Lexer: `+c)}me(this.lexerDefinitionWarning,a=>{Qd(a.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(cp?(this.chopInput=$i,this.match=this.matchWithTest):(this.updateLastIndex=_t,this.match=this.matchWithExec),s&&(this.handleModes=_t),this.trackStartLines===!1&&(this.computeNewColumn=$i),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=_t),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{const a=Xt(this.canModeBeOptimized,(c,l,u)=>(l===!1&&c.push(u),c),[]);if(n.ensureOptimizations&&!Ve(a))throw Error(`Lexer Modes: < ${a.join(", ")} > cannot be optimized. Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. - Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{BA()}),this.TRACE_INIT("toFastProperties",()=>{tp(this)})})}tokenize(t,n=this.defaultMode){if(!Ve(this.lexerDefinitionErrors)){const i=ce(this.lexerDefinitionErrors,s=>s.message).join(`----------------------- + Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{FA()}),this.TRACE_INIT("toFastProperties",()=>{tp(this)})})}tokenize(t,n=this.defaultMode){if(!Ve(this.lexerDefinitionErrors)){const i=ce(this.lexerDefinitionErrors,s=>s.message).join(`----------------------- `);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: -`+i)}return this.tokenizeInternal(t,n)}tokenizeInternal(t,n){let r,i,s,o,a,c,l,u,f,d,h,p,m,b,_;const w=t,v=w.length;let S=0,L=0;const I=this.hasCustom?0:Math.floor(t.length/10),T=new Array(I),M=[];let x=this.trackStartLines?1:void 0,V=this.trackStartLines?1:void 0;const oe=aT(this.emptyGroups),O=this.trackStartLines,E=this.config.lineTerminatorsPattern;let g=0,N=[],W=[];const B=[],Z=[];Object.freeze(Z);let H;function Y(){return N}function $(Se){const je=Fr(Se),we=W[je];return we===void 0?Z:we}const F=Se=>{if(B.length===1&&Se.tokenType.PUSH_MODE===void 0){const je=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(Se);M.push({offset:Se.startOffset,line:Se.startLine,column:Se.startColumn,length:Se.image.length,message:je})}else{B.pop();const je=Wi(B);N=this.patternIdxToConfig[je],W=this.charCodeToPatternIdxToConfig[je],g=N.length;const we=this.canModeBeOptimized[je]&&this.config.safeMode===!1;W&&we?H=$:H=Y}};function ue(Se){B.push(Se),W=this.charCodeToPatternIdxToConfig[Se],N=this.patternIdxToConfig[Se],g=N.length,g=N.length;const je=this.canModeBeOptimized[Se]&&this.config.safeMode===!1;W&&je?H=$:H=Y}ue.call(this,n);let Q;const ee=this.config.recoveryEnabled;for(;Sc.length){c=o,l=u,Q=gt;break}}}break}}if(c!==null){if(f=c.length,d=Q.group,d!==void 0&&(h=Q.tokenTypeIdx,p=this.createTokenInstance(c,S,h,Q.tokenType,x,V,f),this.handlePayload(p,l),d===!1?L=this.addToken(T,L,p):oe[d].push(p)),t=this.chopInput(t,f),S=S+f,V=this.computeNewColumn(V,f),O===!0&&Q.canLineTerminator===!0){let _e=0,We,$e;E.lastIndex=0;do We=E.test(c),We===!0&&($e=E.lastIndex-1,_e++);while(We===!0);_e!==0&&(x=x+_e,V=f-$e,this.updateTokenEndLineColumnLocation(p,d,$e,_e,x,V,f))}this.handleModes(Q,F,ue,p)}else{const _e=S,We=x,$e=V;let gt=ee===!1;for(;gt===!1&&S ${Ds(e)} <--`:`token of type --> ${e.name} <--`} but found --> '${t.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:e,ruleName:t}){return"Redundant input, expecting EOF but found: "+e.image},buildNoViableAltMessage({expectedPathsPerAlt:e,actual:t,previous:n,customUserDescription:r,ruleName:i}){const s="Expecting: ",a=` +`+i)}return this.tokenizeInternal(t,n)}tokenizeInternal(t,n){let r,i,s,o,a,c,l,u,f,d,h,p,m,b,_;const w=t,v=w.length;let S=0,L=0;const I=this.hasCustom?0:Math.floor(t.length/10),T=new Array(I),M=[];let x=this.trackStartLines?1:void 0,V=this.trackStartLines?1:void 0;const oe=cT(this.emptyGroups),O=this.trackStartLines,E=this.config.lineTerminatorsPattern;let g=0,N=[],W=[];const B=[],Z=[];Object.freeze(Z);let H;function Y(){return N}function $(Se){const je=Fr(Se),we=W[je];return we===void 0?Z:we}const F=Se=>{if(B.length===1&&Se.tokenType.PUSH_MODE===void 0){const je=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(Se);M.push({offset:Se.startOffset,line:Se.startLine,column:Se.startColumn,length:Se.image.length,message:je})}else{B.pop();const je=Wi(B);N=this.patternIdxToConfig[je],W=this.charCodeToPatternIdxToConfig[je],g=N.length;const we=this.canModeBeOptimized[je]&&this.config.safeMode===!1;W&&we?H=$:H=Y}};function ue(Se){B.push(Se),W=this.charCodeToPatternIdxToConfig[Se],N=this.patternIdxToConfig[Se],g=N.length,g=N.length;const je=this.canModeBeOptimized[Se]&&this.config.safeMode===!1;W&&je?H=$:H=Y}ue.call(this,n);let Q;const ee=this.config.recoveryEnabled;for(;Sc.length){c=o,l=u,Q=gt;break}}}break}}if(c!==null){if(f=c.length,d=Q.group,d!==void 0&&(h=Q.tokenTypeIdx,p=this.createTokenInstance(c,S,h,Q.tokenType,x,V,f),this.handlePayload(p,l),d===!1?L=this.addToken(T,L,p):oe[d].push(p)),t=this.chopInput(t,f),S=S+f,V=this.computeNewColumn(V,f),O===!0&&Q.canLineTerminator===!0){let _e=0,We,$e;E.lastIndex=0;do We=E.test(c),We===!0&&($e=E.lastIndex-1,_e++);while(We===!0);_e!==0&&(x=x+_e,V=f-$e,this.updateTokenEndLineColumnLocation(p,d,$e,_e,x,V,f))}this.handleModes(Q,F,ue,p)}else{const _e=S,We=x,$e=V;let gt=ee===!1;for(;gt===!1&&S ${Ds(e)} <--`:`token of type --> ${e.name} <--`} but found --> '${t.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:e,ruleName:t}){return"Redundant input, expecting EOF but found: "+e.image},buildNoViableAltMessage({expectedPathsPerAlt:e,actual:t,previous:n,customUserDescription:r,ruleName:i}){const s="Expecting: ",a=` but found: '`+In(t).image+"'";if(r)return s+r+a;{const c=Xt(e,(d,h)=>d.concat(h),[]),l=ce(c,d=>`[${ce(d,h=>Ds(h)).join(", ")}]`),f=`one of these possible Token sequences: ${ce(l,(d,h)=>` ${h+1}. ${d}`).join(` `)}`;return s+f+a}},buildEarlyExitMessage({expectedIterationPaths:e,actual:t,customUserDescription:n,ruleName:r}){const i="Expecting: ",o=` but found: '`+In(t).image+"'";if(n)return i+n+o;{const c=`expecting at least one iteration which starts with one of these possible Token sequences:: - <${ce(e,l=>`[${ce(l,u=>Ds(u)).join(",")}]`).join(" ,")}>`;return i+c+o}}};Object.freeze(Rp);const kT={buildRuleNotFoundError(e,t){return"Invalid grammar, reference to a rule which is not defined: ->"+t.nonTerminalName+`<- + <${ce(e,l=>`[${ce(l,u=>Ds(u)).join(",")}]`).join(" ,")}>`;return i+c+o}}};Object.freeze(Rp);const ST={buildRuleNotFoundError(e,t){return"Invalid grammar, reference to a rule which is not defined: ->"+t.nonTerminalName+`<- inside top level rule: ->`+e.name+"<-"}},di={buildDuplicateFoundError(e,t){function n(u){return u instanceof tt?u.terminalType.name:u instanceof Zt?u.nonTerminalName:""}const r=e.name,i=In(t),s=i.idx,o=Kn(i),a=n(i),c=s>0;let l=`->${o}${c?s:""}<- ${a?`with argument: ->${a}<-`:""} appears more than once (${t.length} times) in the top level rule: ->${r}<-. For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES @@ -98,49 +98,49 @@ rule: <${t}> can be invoked from itself (directly or indirectly) without consuming any Tokens. The grammar path that causes this is: ${r} To fix this refactor your grammar to remove the left recursion. -see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(e){return"deprecated"},buildDuplicateRuleNameError(e){let t;return e.topLevelRule instanceof Hi?t=e.topLevelRule.name:t=e.topLevelRule,`Duplicate definition, rule: ->${t}<- is already defined in the grammar: ->${e.grammarName}<-`}};function ST(e,t){const n=new AT(e,t);return n.resolveRefs(),n.errors}class AT extends ui{constructor(t,n){super(),this.nameToTopRule=t,this.errMsgProvider=n,this.errors=[]}resolveRefs(){me(dt(this.nameToTopRule),t=>{this.currTopLevel=t,t.accept(this)})}visitNonTerminal(t){const n=this.nameToTopRule[t.nonTerminalName];if(n)t.referencedRule=n;else{const r=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,t);this.errors.push({message:r,type:jt.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:t.nonTerminalName})}}}class TT extends aa{constructor(t,n){super(),this.topProd=t,this.path=n,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=Ct(this.path.ruleStack).reverse(),this.occurrenceStack=Ct(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(t,n=[]){this.found||super.walk(t,n)}walkProdRef(t,n,r){if(t.referencedRule.name===this.nextProductionName&&t.idx===this.nextProductionOccurrence){const i=n.concat(r);this.updateExpectedNext(),this.walk(t.referencedRule,i)}}updateExpectedNext(){Ve(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}}class xT extends TT{constructor(t,n){super(t,n),this.path=n,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(t,n,r){if(this.isAtEndOfPath&&t.terminalType.name===this.nextTerminalName&&t.idx===this.nextTerminalOccurrence&&!this.found){const i=n.concat(r),s=new Yt({definition:i});this.possibleTokTypes=Os(s),this.found=!0}}}class ba extends aa{constructor(t,n){super(),this.topRule=t,this.occurrence=n,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}}class RT extends ba{walkMany(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkMany(t,n,r)}}class Ip extends ba{walkManySep(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkManySep(t,n,r)}}class IT extends ba{walkAtLeastOne(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOne(t,n,r)}}class Op extends ba{walkAtLeastOneSep(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOneSep(t,n,r)}}function Dl(e,t,n=[]){n=Ct(n);let r=[],i=0;function s(a){return a.concat(Lt(e,i+1))}function o(a){const c=Dl(s(a),t,n);return r.concat(c)}for(;n.length{Ve(c.definition)===!1&&(r=o(c.definition))}),r;if(a instanceof tt)n.push(a.terminalType);else throw Error("non exhaustive match")}i++}return r.push({partialPath:n,suffixDef:Lt(e,i)}),r}function Np(e,t,n,r){const i="EXIT_NONE_TERMINAL",s=[i],o="EXIT_ALTERNATIVE";let a=!1;const c=t.length,l=c-r-1,u=[],f=[];for(f.push({idx:-1,def:e,ruleStack:[],occurrenceStack:[]});!Ve(f);){const d=f.pop();if(d===o){a&&Wi(f).idx<=l&&f.pop();continue}const h=d.def,p=d.idx,m=d.ruleStack,b=d.occurrenceStack;if(Ve(h))continue;const _=h[0];if(_===i){const w={idx:p,def:Lt(h),ruleStack:Is(m),occurrenceStack:Is(b)};f.push(w)}else if(_ instanceof tt)if(p=0;w--){const v=_.definition[w],S={idx:p,def:v.definition.concat(Lt(h)),ruleStack:m,occurrenceStack:b};f.push(S),f.push(o)}else if(_ instanceof Yt)f.push({idx:p,def:_.definition.concat(Lt(h)),ruleStack:m,occurrenceStack:b});else if(_ instanceof Hi)f.push(OT(_,p,m,b));else throw Error("non exhaustive match")}return u}function OT(e,t,n,r){const i=Ct(n);i.push(e.name);const s=Ct(r);return s.push(1),{idx:t,def:e.definition,ruleStack:i,occurrenceStack:s}}var ot;(function(e){e[e.OPTION=0]="OPTION",e[e.REPETITION=1]="REPETITION",e[e.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",e[e.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",e[e.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",e[e.ALTERNATION=5]="ALTERNATION"})(ot||(ot={}));function Cp(e){if(e instanceof Qt||e==="Option")return ot.OPTION;if(e instanceof bt||e==="Repetition")return ot.REPETITION;if(e instanceof Hn||e==="RepetitionMandatory")return ot.REPETITION_MANDATORY;if(e instanceof Vn||e==="RepetitionMandatoryWithSeparator")return ot.REPETITION_MANDATORY_WITH_SEPARATOR;if(e instanceof Nn||e==="RepetitionWithSeparator")return ot.REPETITION_WITH_SEPARATOR;if(e instanceof Cn||e==="Alternation")return ot.ALTERNATION;throw Error("non exhaustive match")}function NT(e,t,n,r,i,s){const o=Fl(e,t,n),a=Pp(o)?ya:Ms;return s(o,r,a,i)}function CT(e,t,n,r,i,s){const o=$l(e,t,i,n),a=Pp(o)?ya:Ms;return s(o[0],a,r)}function LT(e,t,n,r){const i=e.length,s=Rn(e,o=>Rn(o,a=>a.length===1));if(t)return function(o){const a=ce(o,c=>c.GATE);for(let c=0;csn(c)),a=Xt(o,(c,l,u)=>(me(l,f=>{pe(c,f.tokenTypeIdx)||(c[f.tokenTypeIdx]=u),me(f.categoryMatches,d=>{pe(c,d)||(c[d]=u)})}),c),{});return function(){const c=this.LA(1);return a[c.tokenTypeIdx]}}else return function(){for(let o=0;os.length===1),i=e.length;if(r&&!n){const s=sn(e);if(s.length===1&&Ve(s[0].categoryMatches)){const a=s[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===a}}else{const o=Xt(s,(a,c,l)=>(a[c.tokenTypeIdx]=!0,me(c.categoryMatches,u=>{a[u]=!0}),a),[]);return function(){const a=this.LA(1);return o[a.tokenTypeIdx]===!0}}}else return function(){e:for(let s=0;sDl([o],1)),r=Mp(n.length),i=ce(n,o=>{const a={};return me(o,c=>{const l=Bl(c.partialPath);me(l,u=>{a[u]=!0})}),a});let s=n;for(let o=1;o<=t;o++){const a=s;s=Mp(a.length);for(let c=0;c{const _=Bl(b.partialPath);me(_,w=>{i[c][w]=!0})})}}}}return r}function Fl(e,t,n,r){const i=new Lp(e,ot.ALTERNATION,r);return t.accept(i),Up(i.result,n)}function $l(e,t,n,r){const i=new Lp(e,n);t.accept(i);const s=i.result,a=new UT(t,e,n).startWalking(),c=new Yt({definition:s}),l=new Yt({definition:a});return Up([c,l],r)}function jl(e,t){e:for(let n=0;n{const i=t[r];return n===i||i.categoryMatchesMap[n.tokenTypeIdx]})}function Pp(e){return Rn(e,t=>Rn(t,n=>Rn(n,r=>Ve(r.categoryMatches))))}function BT(e){const t=e.lookaheadStrategy.validate({rules:e.rules,tokenTypes:e.tokenTypes,grammarName:e.grammarName});return ce(t,n=>Object.assign({type:jt.CUSTOM_LOOKAHEAD_VALIDATION},n))}function FT(e,t,n,r){const i=yn(e,c=>$T(c,n)),s=YT(e,t,n),o=yn(e,c=>qT(c,n)),a=yn(e,c=>WT(c,e,r,n));return i.concat(s,o,a)}function $T(e,t){const n=new zT;e.accept(n);const r=n.allProductions,i=Xd(r,jT),s=On(i,a=>a.length>1);return ce(dt(s),a=>{const c=In(a),l=t.buildDuplicateFoundError(e,a),u=Kn(c),f={message:l,type:jt.DUPLICATE_PRODUCTIONS,ruleName:e.name,dslName:u,occurrence:c.idx},d=Dp(c);return d&&(f.parameter=d),f})}function jT(e){return`${Kn(e)}_#_${e.idx}_#_${Dp(e)}`}function Dp(e){return e instanceof tt?e.terminalType.name:e instanceof Zt?e.nonTerminalName:""}class zT extends ui{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(t){this.allProductions.push(t)}visitOption(t){this.allProductions.push(t)}visitRepetitionWithSeparator(t){this.allProductions.push(t)}visitRepetitionMandatory(t){this.allProductions.push(t)}visitRepetitionMandatoryWithSeparator(t){this.allProductions.push(t)}visitRepetition(t){this.allProductions.push(t)}visitAlternation(t){this.allProductions.push(t)}visitTerminal(t){this.allProductions.push(t)}}function WT(e,t,n,r){const i=[];if(Xt(t,(o,a)=>a.name===e.name?o+1:o,0)>1){const o=r.buildDuplicateRuleNameError({topLevelRule:e,grammarName:n});i.push({message:o,type:jt.DUPLICATE_RULE_NAME,ruleName:e.name})}return i}function GT(e,t,n){const r=[];let i;return $t(t,e)||(i=`Invalid rule override, rule: ->${e}<- cannot be overridden in the grammar: ->${n}<-as it is not defined in any of the super grammars `,r.push({message:i,type:jt.INVALID_RULE_OVERRIDE,ruleName:e})),r}function Bp(e,t,n,r=[]){const i=[],s=wa(t.definition);if(Ve(s))return[];{const o=e.name;$t(s,e)&&i.push({message:n.buildLeftRecursionError({topLevelRule:e,leftRecursionPath:r}),type:jt.LEFT_RECURSION,ruleName:o});const c=na(s,r.concat([e])),l=yn(c,u=>{const f=Ct(r);return f.push(u),Bp(e,u,n,f)});return i.concat(l)}}function wa(e){let t=[];if(Ve(e))return t;const n=In(e);if(n instanceof Zt)t.push(n.referencedRule);else if(n instanceof Yt||n instanceof Qt||n instanceof Hn||n instanceof Vn||n instanceof Nn||n instanceof bt)t=t.concat(wa(n.definition));else if(n instanceof Cn)t=sn(ce(n.definition,s=>wa(s.definition)));else if(!(n instanceof tt))throw Error("non exhaustive match");const r=oa(n),i=e.length>1;if(r&&i){const s=Lt(e);return t.concat(wa(s))}else return t}class zl extends ui{constructor(){super(...arguments),this.alternations=[]}visitAlternation(t){this.alternations.push(t)}}function HT(e,t){const n=new zl;e.accept(n);const r=n.alternations;return yn(r,s=>{const o=Is(s.definition);return yn(o,(a,c)=>{const l=Np([a],[],Ms,1);return Ve(l)?[{message:t.buildEmptyAlternationError({topLevelRule:e,alternation:s,emptyChoiceIdx:c}),type:jt.NONE_LAST_EMPTY_ALT,ruleName:e.name,occurrence:s.idx,alternative:c+1}]:[]})})}function VT(e,t,n){const r=new zl;e.accept(r);let i=r.alternations;return i=ra(i,o=>o.ignoreAmbiguities===!0),yn(i,o=>{const a=o.idx,c=o.maxLookahead||t,l=Fl(a,e,c,o),u=XT(l,o,e,n),f=ZT(l,o,e,n);return u.concat(f)})}class KT extends ui{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(t){this.allProductions.push(t)}visitRepetitionMandatory(t){this.allProductions.push(t)}visitRepetitionMandatoryWithSeparator(t){this.allProductions.push(t)}visitRepetition(t){this.allProductions.push(t)}}function qT(e,t){const n=new zl;e.accept(n);const r=n.alternations;return yn(r,s=>s.definition.length>255?[{message:t.buildTooManyAlternativesError({topLevelRule:e,alternation:s}),type:jt.TOO_MANY_ALTS,ruleName:e.name,occurrence:s.idx}]:[])}function JT(e,t,n){const r=[];return me(e,i=>{const s=new KT;i.accept(s);const o=s.allProductions;me(o,a=>{const c=Cp(a),l=a.maxLookahead||t,u=a.idx,d=$l(u,i,c,l)[0];if(Ve(sn(d))){const h=n.buildEmptyRepetitionError({topLevelRule:i,repetition:a});r.push({message:h,type:jt.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),r}function XT(e,t,n,r){const i=[],s=Xt(e,(a,c,l)=>(t.definition[l].ignoreAmbiguities===!0||me(c,u=>{const f=[l];me(e,(d,h)=>{l!==h&&jl(d,u)&&t.definition[h].ignoreAmbiguities!==!0&&f.push(h)}),f.length>1&&!jl(i,u)&&(i.push(u),a.push({alts:f,path:u}))}),a),[]);return ce(s,a=>{const c=ce(a.alts,u=>u+1);return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:c,prefixPath:a.path}),type:jt.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:t.idx,alternatives:a.alts}})}function ZT(e,t,n,r){const i=Xt(e,(o,a,c)=>{const l=ce(a,u=>({idx:c,path:u}));return o.concat(l)},[]);return Rs(yn(i,o=>{if(t.definition[o.idx].ignoreAmbiguities===!0)return[];const c=o.idx,l=o.path,u=gn(i,d=>t.definition[d.idx].ignoreAmbiguities!==!0&&d.idx{const h=[d.idx+1,c+1],p=t.idx===0?"":t.idx;return{message:r.buildAlternationPrefixAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:h,prefixPath:d.path}),type:jt.AMBIGUOUS_PREFIX_ALTS,ruleName:n.name,occurrence:p,alternatives:h}})}))}function YT(e,t,n){const r=[],i=ce(t,s=>s.name);return me(e,s=>{const o=s.name;if($t(i,o)){const a=n.buildNamespaceConflictError(s);r.push({message:a,type:jt.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:o})}}),r}function QT(e){const t=Rl(e,{errMsgProvider:kT}),n={};return me(e.rules,r=>{n[r.name]=r}),ST(n,t.errMsgProvider)}function ex(e){return e=Rl(e,{errMsgProvider:di}),FT(e.rules,e.tokenTypes,e.errMsgProvider,e.grammarName)}const Fp="MismatchedTokenException",$p="NoViableAltException",jp="EarlyExitException",zp="NotAllInputParsedException",Wp=[Fp,$p,jp,zp];Object.freeze(Wp);function va(e){return $t(Wp,e.name)}class Ea extends Error{constructor(t,n){super(t),this.token=n,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class Gp extends Ea{constructor(t,n,r){super(t,n),this.previousToken=r,this.name=Fp}}class tx extends Ea{constructor(t,n,r){super(t,n),this.previousToken=r,this.name=$p}}class nx extends Ea{constructor(t,n){super(t,n),this.name=zp}}class rx extends Ea{constructor(t,n,r){super(t,n),this.previousToken=r,this.name=jp}}const Wl={},Hp="InRuleRecoveryException";class ix extends Error{constructor(t){super(t),this.name=Hp}}class sx{initRecoverable(t){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=pe(t,"recoveryEnabled")?t.recoveryEnabled:_r.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=ox)}getTokenToInsert(t){const n=_a(t,"",NaN,NaN,NaN,NaN,NaN,NaN);return n.isInsertedInRecovery=!0,n}canTokenTypeBeInsertedInRecovery(t){return!0}canTokenTypeBeDeletedInRecovery(t){return!0}tryInRepetitionRecovery(t,n,r,i){const s=this.findReSyncTokenType(),o=this.exportLexerState(),a=[];let c=!1;const l=this.LA(1);let u=this.LA(1);const f=()=>{const d=this.LA(0),h=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:l,previous:d,ruleName:this.getCurrRuleFullName()}),p=new Gp(h,l,this.LA(0));p.resyncedTokens=Is(a),this.SAVE_ERROR(p)};for(;!c;)if(this.tokenMatcher(u,i)){f();return}else if(r.call(this)){f(),t.apply(this,n);return}else this.tokenMatcher(u,s)?c=!0:(u=this.SKIP_TOKEN(),this.addToResyncTokens(u,a));this.importLexerState(o)}shouldInRepetitionRecoveryBeTried(t,n,r){return!(r===!1||this.tokenMatcher(this.LA(1),t)||this.isBackTracking()||this.canPerformInRuleRecovery(t,this.getFollowsForInRuleRecovery(t,n)))}getFollowsForInRuleRecovery(t,n){const r=this.getCurrentGrammarPath(t,n);return this.getNextPossibleTokenTypes(r)}tryInRuleRecovery(t,n){if(this.canRecoverWithSingleTokenInsertion(t,n))return this.getTokenToInsert(t);if(this.canRecoverWithSingleTokenDeletion(t)){const r=this.SKIP_TOKEN();return this.consumeToken(),r}throw new ix("sad sad panda")}canPerformInRuleRecovery(t,n){return this.canRecoverWithSingleTokenInsertion(t,n)||this.canRecoverWithSingleTokenDeletion(t)}canRecoverWithSingleTokenInsertion(t,n){if(!this.canTokenTypeBeInsertedInRecovery(t)||Ve(n))return!1;const r=this.LA(1);return Gi(n,s=>this.tokenMatcher(r,s))!==void 0}canRecoverWithSingleTokenDeletion(t){return this.canTokenTypeBeDeletedInRecovery(t)?this.tokenMatcher(this.LA(2),t):!1}isInCurrentRuleReSyncSet(t){const n=this.getCurrFollowKey(),r=this.getFollowSetFromFollowKey(n);return $t(r,t)}findReSyncTokenType(){const t=this.flattenFollowSet();let n=this.LA(1),r=2;for(;;){const i=Gi(t,s=>ET(n,s));if(i!==void 0)return i;n=this.LA(r),r++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return Wl;const t=this.getLastExplicitRuleShortName(),n=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(t),idxInCallingRule:n,inRule:this.shortRuleNameToFullName(r)}}buildFullFollowKeyStack(){const t=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return ce(t,(r,i)=>i===0?Wl:{ruleName:this.shortRuleNameToFullName(r),idxInCallingRule:n[i],inRule:this.shortRuleNameToFullName(t[i-1])})}flattenFollowSet(){const t=ce(this.buildFullFollowKeyStack(),n=>this.getFollowSetFromFollowKey(n));return sn(t)}getFollowSetFromFollowKey(t){if(t===Wl)return[hi];const n=t.ruleName+t.idxInCallingRule+rp+t.inRule;return this.resyncFollows[n]}addToResyncTokens(t,n){return this.tokenMatcher(t,hi)||n.push(t),n}reSyncTo(t){const n=[];let r=this.LA(1);for(;this.tokenMatcher(r,t)===!1;)r=this.SKIP_TOKEN(),this.addToResyncTokens(r,n);return Is(n)}attemptInRepetitionRecovery(t,n,r,i,s,o,a){}getCurrentGrammarPath(t,n){const r=this.getHumanReadableRuleStack(),i=Ct(this.RULE_OCCURRENCE_STACK);return{ruleStack:r,occurrenceStack:i,lastTok:t,lastTokOccurrence:n}}getHumanReadableRuleStack(){return ce(this.RULE_STACK,t=>this.shortRuleNameToFullName(t))}}function ox(e,t,n,r,i,s,o){const a=this.getKeyForAutomaticLookahead(r,i);let c=this.firstAfterRepMap[a];if(c===void 0){const d=this.getCurrRuleFullName(),h=this.getGAstProductions()[d];c=new s(h,i).startWalking(),this.firstAfterRepMap[a]=c}let l=c.token,u=c.occurrence;const f=c.isEndOfRule;this.RULE_STACK.length===1&&f&&l===void 0&&(l=hi,u=1),!(l===void 0||u===void 0)&&this.shouldInRepetitionRecoveryBeTried(l,u,o)&&this.tryInRepetitionRecovery(e,t,n,l)}const ax=4,$r=8,Vp=1<<$r,Kp=2<<$r,Gl=3<<$r,Hl=4<<$r,Vl=5<<$r,ka=6<<$r;function Kl(e,t,n){return n|t|e}class cx{constructor(t){var n;this.maxLookahead=(n=t==null?void 0:t.maxLookahead)!==null&&n!==void 0?n:_r.maxLookahead}validate(t){const n=this.validateNoLeftRecursion(t.rules);if(Ve(n)){const r=this.validateEmptyOrAlternatives(t.rules),i=this.validateAmbiguousAlternationAlternatives(t.rules,this.maxLookahead),s=this.validateSomeNonEmptyLookaheadPath(t.rules,this.maxLookahead);return[...n,...r,...i,...s]}return n}validateNoLeftRecursion(t){return yn(t,n=>Bp(n,n,di))}validateEmptyOrAlternatives(t){return yn(t,n=>HT(n,di))}validateAmbiguousAlternationAlternatives(t,n){return yn(t,r=>VT(r,n,di))}validateSomeNonEmptyLookaheadPath(t,n){return JT(t,n,di)}buildLookaheadForAlternation(t){return NT(t.prodOccurrence,t.rule,t.maxLookahead,t.hasPredicates,t.dynamicTokensEnabled,LT)}buildLookaheadForOptional(t){return CT(t.prodOccurrence,t.rule,t.maxLookahead,t.dynamicTokensEnabled,Cp(t.prodType),MT)}}class lx{initLooksAhead(t){this.dynamicTokensEnabled=pe(t,"dynamicTokensEnabled")?t.dynamicTokensEnabled:_r.dynamicTokensEnabled,this.maxLookahead=pe(t,"maxLookahead")?t.maxLookahead:_r.maxLookahead,this.lookaheadStrategy=pe(t,"lookaheadStrategy")?t.lookaheadStrategy:new cx({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(t){me(t,n=>{this.TRACE_INIT(`${n.name} Rule Lookahead`,()=>{const{alternation:r,repetition:i,option:s,repetitionMandatory:o,repetitionMandatoryWithSeparator:a,repetitionWithSeparator:c}=fx(n);me(r,l=>{const u=l.idx===0?"":l.idx;this.TRACE_INIT(`${Kn(l)}${u}`,()=>{const f=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:l.idx,rule:n,maxLookahead:l.maxLookahead||this.maxLookahead,hasPredicates:l.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),d=Kl(this.fullRuleNameToShort[n.name],Vp,l.idx);this.setLaFuncCache(d,f)})}),me(i,l=>{this.computeLookaheadFunc(n,l.idx,Gl,"Repetition",l.maxLookahead,Kn(l))}),me(s,l=>{this.computeLookaheadFunc(n,l.idx,Kp,"Option",l.maxLookahead,Kn(l))}),me(o,l=>{this.computeLookaheadFunc(n,l.idx,Hl,"RepetitionMandatory",l.maxLookahead,Kn(l))}),me(a,l=>{this.computeLookaheadFunc(n,l.idx,ka,"RepetitionMandatoryWithSeparator",l.maxLookahead,Kn(l))}),me(c,l=>{this.computeLookaheadFunc(n,l.idx,Vl,"RepetitionWithSeparator",l.maxLookahead,Kn(l))})})})}computeLookaheadFunc(t,n,r,i,s,o){this.TRACE_INIT(`${o}${n===0?"":n}`,()=>{const a=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:n,rule:t,maxLookahead:s||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),c=Kl(this.fullRuleNameToShort[t.name],r,n);this.setLaFuncCache(c,a)})}getKeyForAutomaticLookahead(t,n){const r=this.getLastExplicitRuleShortName();return Kl(r,t,n)}getLaFuncFromCache(t){return this.lookAheadFuncsCache.get(t)}setLaFuncCache(t,n){this.lookAheadFuncsCache.set(t,n)}}class ux extends ui{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(t){this.dslMethods.option.push(t)}visitRepetitionWithSeparator(t){this.dslMethods.repetitionWithSeparator.push(t)}visitRepetitionMandatory(t){this.dslMethods.repetitionMandatory.push(t)}visitRepetitionMandatoryWithSeparator(t){this.dslMethods.repetitionMandatoryWithSeparator.push(t)}visitRepetition(t){this.dslMethods.repetition.push(t)}visitAlternation(t){this.dslMethods.alternation.push(t)}}const Sa=new ux;function fx(e){Sa.reset(),e.accept(Sa);const t=Sa.dslMethods;return Sa.reset(),t}function qp(e,t){isNaN(e.startOffset)===!0?(e.startOffset=t.startOffset,e.endOffset=t.endOffset):e.endOffseto.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: +see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(e){return"deprecated"},buildDuplicateRuleNameError(e){let t;return e.topLevelRule instanceof Hi?t=e.topLevelRule.name:t=e.topLevelRule,`Duplicate definition, rule: ->${t}<- is already defined in the grammar: ->${e.grammarName}<-`}};function AT(e,t){const n=new TT(e,t);return n.resolveRefs(),n.errors}class TT extends ui{constructor(t,n){super(),this.nameToTopRule=t,this.errMsgProvider=n,this.errors=[]}resolveRefs(){me(dt(this.nameToTopRule),t=>{this.currTopLevel=t,t.accept(this)})}visitNonTerminal(t){const n=this.nameToTopRule[t.nonTerminalName];if(n)t.referencedRule=n;else{const r=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,t);this.errors.push({message:r,type:jt.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:t.nonTerminalName})}}}class xT extends aa{constructor(t,n){super(),this.topProd=t,this.path=n,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=Ct(this.path.ruleStack).reverse(),this.occurrenceStack=Ct(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(t,n=[]){this.found||super.walk(t,n)}walkProdRef(t,n,r){if(t.referencedRule.name===this.nextProductionName&&t.idx===this.nextProductionOccurrence){const i=n.concat(r);this.updateExpectedNext(),this.walk(t.referencedRule,i)}}updateExpectedNext(){Ve(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}}class RT extends xT{constructor(t,n){super(t,n),this.path=n,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(t,n,r){if(this.isAtEndOfPath&&t.terminalType.name===this.nextTerminalName&&t.idx===this.nextTerminalOccurrence&&!this.found){const i=n.concat(r),s=new Yt({definition:i});this.possibleTokTypes=Os(s),this.found=!0}}}class ba extends aa{constructor(t,n){super(),this.topRule=t,this.occurrence=n,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}}class IT extends ba{walkMany(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkMany(t,n,r)}}class Ip extends ba{walkManySep(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkManySep(t,n,r)}}class OT extends ba{walkAtLeastOne(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOne(t,n,r)}}class Op extends ba{walkAtLeastOneSep(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOneSep(t,n,r)}}function Dl(e,t,n=[]){n=Ct(n);let r=[],i=0;function s(a){return a.concat(Lt(e,i+1))}function o(a){const c=Dl(s(a),t,n);return r.concat(c)}for(;n.length{Ve(c.definition)===!1&&(r=o(c.definition))}),r;if(a instanceof tt)n.push(a.terminalType);else throw Error("non exhaustive match")}i++}return r.push({partialPath:n,suffixDef:Lt(e,i)}),r}function Np(e,t,n,r){const i="EXIT_NONE_TERMINAL",s=[i],o="EXIT_ALTERNATIVE";let a=!1;const c=t.length,l=c-r-1,u=[],f=[];for(f.push({idx:-1,def:e,ruleStack:[],occurrenceStack:[]});!Ve(f);){const d=f.pop();if(d===o){a&&Wi(f).idx<=l&&f.pop();continue}const h=d.def,p=d.idx,m=d.ruleStack,b=d.occurrenceStack;if(Ve(h))continue;const _=h[0];if(_===i){const w={idx:p,def:Lt(h),ruleStack:Is(m),occurrenceStack:Is(b)};f.push(w)}else if(_ instanceof tt)if(p=0;w--){const v=_.definition[w],S={idx:p,def:v.definition.concat(Lt(h)),ruleStack:m,occurrenceStack:b};f.push(S),f.push(o)}else if(_ instanceof Yt)f.push({idx:p,def:_.definition.concat(Lt(h)),ruleStack:m,occurrenceStack:b});else if(_ instanceof Hi)f.push(NT(_,p,m,b));else throw Error("non exhaustive match")}return u}function NT(e,t,n,r){const i=Ct(n);i.push(e.name);const s=Ct(r);return s.push(1),{idx:t,def:e.definition,ruleStack:i,occurrenceStack:s}}var ot;(function(e){e[e.OPTION=0]="OPTION",e[e.REPETITION=1]="REPETITION",e[e.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",e[e.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",e[e.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",e[e.ALTERNATION=5]="ALTERNATION"})(ot||(ot={}));function Cp(e){if(e instanceof Qt||e==="Option")return ot.OPTION;if(e instanceof bt||e==="Repetition")return ot.REPETITION;if(e instanceof Hn||e==="RepetitionMandatory")return ot.REPETITION_MANDATORY;if(e instanceof Vn||e==="RepetitionMandatoryWithSeparator")return ot.REPETITION_MANDATORY_WITH_SEPARATOR;if(e instanceof Nn||e==="RepetitionWithSeparator")return ot.REPETITION_WITH_SEPARATOR;if(e instanceof Cn||e==="Alternation")return ot.ALTERNATION;throw Error("non exhaustive match")}function CT(e,t,n,r,i,s){const o=Fl(e,t,n),a=Pp(o)?ya:Ms;return s(o,r,a,i)}function LT(e,t,n,r,i,s){const o=$l(e,t,i,n),a=Pp(o)?ya:Ms;return s(o[0],a,r)}function MT(e,t,n,r){const i=e.length,s=Rn(e,o=>Rn(o,a=>a.length===1));if(t)return function(o){const a=ce(o,c=>c.GATE);for(let c=0;csn(c)),a=Xt(o,(c,l,u)=>(me(l,f=>{pe(c,f.tokenTypeIdx)||(c[f.tokenTypeIdx]=u),me(f.categoryMatches,d=>{pe(c,d)||(c[d]=u)})}),c),{});return function(){const c=this.LA(1);return a[c.tokenTypeIdx]}}else return function(){for(let o=0;os.length===1),i=e.length;if(r&&!n){const s=sn(e);if(s.length===1&&Ve(s[0].categoryMatches)){const a=s[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===a}}else{const o=Xt(s,(a,c,l)=>(a[c.tokenTypeIdx]=!0,me(c.categoryMatches,u=>{a[u]=!0}),a),[]);return function(){const a=this.LA(1);return o[a.tokenTypeIdx]===!0}}}else return function(){e:for(let s=0;sDl([o],1)),r=Mp(n.length),i=ce(n,o=>{const a={};return me(o,c=>{const l=Bl(c.partialPath);me(l,u=>{a[u]=!0})}),a});let s=n;for(let o=1;o<=t;o++){const a=s;s=Mp(a.length);for(let c=0;c{const _=Bl(b.partialPath);me(_,w=>{i[c][w]=!0})})}}}}return r}function Fl(e,t,n,r){const i=new Lp(e,ot.ALTERNATION,r);return t.accept(i),Up(i.result,n)}function $l(e,t,n,r){const i=new Lp(e,n);t.accept(i);const s=i.result,a=new PT(t,e,n).startWalking(),c=new Yt({definition:s}),l=new Yt({definition:a});return Up([c,l],r)}function jl(e,t){e:for(let n=0;n{const i=t[r];return n===i||i.categoryMatchesMap[n.tokenTypeIdx]})}function Pp(e){return Rn(e,t=>Rn(t,n=>Rn(n,r=>Ve(r.categoryMatches))))}function FT(e){const t=e.lookaheadStrategy.validate({rules:e.rules,tokenTypes:e.tokenTypes,grammarName:e.grammarName});return ce(t,n=>Object.assign({type:jt.CUSTOM_LOOKAHEAD_VALIDATION},n))}function $T(e,t,n,r){const i=yn(e,c=>jT(c,n)),s=QT(e,t,n),o=yn(e,c=>JT(c,n)),a=yn(e,c=>GT(c,e,r,n));return i.concat(s,o,a)}function jT(e,t){const n=new WT;e.accept(n);const r=n.allProductions,i=Xd(r,zT),s=On(i,a=>a.length>1);return ce(dt(s),a=>{const c=In(a),l=t.buildDuplicateFoundError(e,a),u=Kn(c),f={message:l,type:jt.DUPLICATE_PRODUCTIONS,ruleName:e.name,dslName:u,occurrence:c.idx},d=Dp(c);return d&&(f.parameter=d),f})}function zT(e){return`${Kn(e)}_#_${e.idx}_#_${Dp(e)}`}function Dp(e){return e instanceof tt?e.terminalType.name:e instanceof Zt?e.nonTerminalName:""}class WT extends ui{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(t){this.allProductions.push(t)}visitOption(t){this.allProductions.push(t)}visitRepetitionWithSeparator(t){this.allProductions.push(t)}visitRepetitionMandatory(t){this.allProductions.push(t)}visitRepetitionMandatoryWithSeparator(t){this.allProductions.push(t)}visitRepetition(t){this.allProductions.push(t)}visitAlternation(t){this.allProductions.push(t)}visitTerminal(t){this.allProductions.push(t)}}function GT(e,t,n,r){const i=[];if(Xt(t,(o,a)=>a.name===e.name?o+1:o,0)>1){const o=r.buildDuplicateRuleNameError({topLevelRule:e,grammarName:n});i.push({message:o,type:jt.DUPLICATE_RULE_NAME,ruleName:e.name})}return i}function HT(e,t,n){const r=[];let i;return $t(t,e)||(i=`Invalid rule override, rule: ->${e}<- cannot be overridden in the grammar: ->${n}<-as it is not defined in any of the super grammars `,r.push({message:i,type:jt.INVALID_RULE_OVERRIDE,ruleName:e})),r}function Bp(e,t,n,r=[]){const i=[],s=wa(t.definition);if(Ve(s))return[];{const o=e.name;$t(s,e)&&i.push({message:n.buildLeftRecursionError({topLevelRule:e,leftRecursionPath:r}),type:jt.LEFT_RECURSION,ruleName:o});const c=na(s,r.concat([e])),l=yn(c,u=>{const f=Ct(r);return f.push(u),Bp(e,u,n,f)});return i.concat(l)}}function wa(e){let t=[];if(Ve(e))return t;const n=In(e);if(n instanceof Zt)t.push(n.referencedRule);else if(n instanceof Yt||n instanceof Qt||n instanceof Hn||n instanceof Vn||n instanceof Nn||n instanceof bt)t=t.concat(wa(n.definition));else if(n instanceof Cn)t=sn(ce(n.definition,s=>wa(s.definition)));else if(!(n instanceof tt))throw Error("non exhaustive match");const r=oa(n),i=e.length>1;if(r&&i){const s=Lt(e);return t.concat(wa(s))}else return t}class zl extends ui{constructor(){super(...arguments),this.alternations=[]}visitAlternation(t){this.alternations.push(t)}}function VT(e,t){const n=new zl;e.accept(n);const r=n.alternations;return yn(r,s=>{const o=Is(s.definition);return yn(o,(a,c)=>{const l=Np([a],[],Ms,1);return Ve(l)?[{message:t.buildEmptyAlternationError({topLevelRule:e,alternation:s,emptyChoiceIdx:c}),type:jt.NONE_LAST_EMPTY_ALT,ruleName:e.name,occurrence:s.idx,alternative:c+1}]:[]})})}function KT(e,t,n){const r=new zl;e.accept(r);let i=r.alternations;return i=ra(i,o=>o.ignoreAmbiguities===!0),yn(i,o=>{const a=o.idx,c=o.maxLookahead||t,l=Fl(a,e,c,o),u=ZT(l,o,e,n),f=YT(l,o,e,n);return u.concat(f)})}class qT extends ui{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(t){this.allProductions.push(t)}visitRepetitionMandatory(t){this.allProductions.push(t)}visitRepetitionMandatoryWithSeparator(t){this.allProductions.push(t)}visitRepetition(t){this.allProductions.push(t)}}function JT(e,t){const n=new zl;e.accept(n);const r=n.alternations;return yn(r,s=>s.definition.length>255?[{message:t.buildTooManyAlternativesError({topLevelRule:e,alternation:s}),type:jt.TOO_MANY_ALTS,ruleName:e.name,occurrence:s.idx}]:[])}function XT(e,t,n){const r=[];return me(e,i=>{const s=new qT;i.accept(s);const o=s.allProductions;me(o,a=>{const c=Cp(a),l=a.maxLookahead||t,u=a.idx,d=$l(u,i,c,l)[0];if(Ve(sn(d))){const h=n.buildEmptyRepetitionError({topLevelRule:i,repetition:a});r.push({message:h,type:jt.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),r}function ZT(e,t,n,r){const i=[],s=Xt(e,(a,c,l)=>(t.definition[l].ignoreAmbiguities===!0||me(c,u=>{const f=[l];me(e,(d,h)=>{l!==h&&jl(d,u)&&t.definition[h].ignoreAmbiguities!==!0&&f.push(h)}),f.length>1&&!jl(i,u)&&(i.push(u),a.push({alts:f,path:u}))}),a),[]);return ce(s,a=>{const c=ce(a.alts,u=>u+1);return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:c,prefixPath:a.path}),type:jt.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:t.idx,alternatives:a.alts}})}function YT(e,t,n,r){const i=Xt(e,(o,a,c)=>{const l=ce(a,u=>({idx:c,path:u}));return o.concat(l)},[]);return Rs(yn(i,o=>{if(t.definition[o.idx].ignoreAmbiguities===!0)return[];const c=o.idx,l=o.path,u=gn(i,d=>t.definition[d.idx].ignoreAmbiguities!==!0&&d.idx{const h=[d.idx+1,c+1],p=t.idx===0?"":t.idx;return{message:r.buildAlternationPrefixAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:h,prefixPath:d.path}),type:jt.AMBIGUOUS_PREFIX_ALTS,ruleName:n.name,occurrence:p,alternatives:h}})}))}function QT(e,t,n){const r=[],i=ce(t,s=>s.name);return me(e,s=>{const o=s.name;if($t(i,o)){const a=n.buildNamespaceConflictError(s);r.push({message:a,type:jt.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:o})}}),r}function ex(e){const t=Rl(e,{errMsgProvider:ST}),n={};return me(e.rules,r=>{n[r.name]=r}),AT(n,t.errMsgProvider)}function tx(e){return e=Rl(e,{errMsgProvider:di}),$T(e.rules,e.tokenTypes,e.errMsgProvider,e.grammarName)}const Fp="MismatchedTokenException",$p="NoViableAltException",jp="EarlyExitException",zp="NotAllInputParsedException",Wp=[Fp,$p,jp,zp];Object.freeze(Wp);function va(e){return $t(Wp,e.name)}class Ea extends Error{constructor(t,n){super(t),this.token=n,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class Gp extends Ea{constructor(t,n,r){super(t,n),this.previousToken=r,this.name=Fp}}class nx extends Ea{constructor(t,n,r){super(t,n),this.previousToken=r,this.name=$p}}class rx extends Ea{constructor(t,n){super(t,n),this.name=zp}}class ix extends Ea{constructor(t,n,r){super(t,n),this.previousToken=r,this.name=jp}}const Wl={},Hp="InRuleRecoveryException";class sx extends Error{constructor(t){super(t),this.name=Hp}}class ox{initRecoverable(t){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=pe(t,"recoveryEnabled")?t.recoveryEnabled:_r.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=ax)}getTokenToInsert(t){const n=_a(t,"",NaN,NaN,NaN,NaN,NaN,NaN);return n.isInsertedInRecovery=!0,n}canTokenTypeBeInsertedInRecovery(t){return!0}canTokenTypeBeDeletedInRecovery(t){return!0}tryInRepetitionRecovery(t,n,r,i){const s=this.findReSyncTokenType(),o=this.exportLexerState(),a=[];let c=!1;const l=this.LA(1);let u=this.LA(1);const f=()=>{const d=this.LA(0),h=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:l,previous:d,ruleName:this.getCurrRuleFullName()}),p=new Gp(h,l,this.LA(0));p.resyncedTokens=Is(a),this.SAVE_ERROR(p)};for(;!c;)if(this.tokenMatcher(u,i)){f();return}else if(r.call(this)){f(),t.apply(this,n);return}else this.tokenMatcher(u,s)?c=!0:(u=this.SKIP_TOKEN(),this.addToResyncTokens(u,a));this.importLexerState(o)}shouldInRepetitionRecoveryBeTried(t,n,r){return!(r===!1||this.tokenMatcher(this.LA(1),t)||this.isBackTracking()||this.canPerformInRuleRecovery(t,this.getFollowsForInRuleRecovery(t,n)))}getFollowsForInRuleRecovery(t,n){const r=this.getCurrentGrammarPath(t,n);return this.getNextPossibleTokenTypes(r)}tryInRuleRecovery(t,n){if(this.canRecoverWithSingleTokenInsertion(t,n))return this.getTokenToInsert(t);if(this.canRecoverWithSingleTokenDeletion(t)){const r=this.SKIP_TOKEN();return this.consumeToken(),r}throw new sx("sad sad panda")}canPerformInRuleRecovery(t,n){return this.canRecoverWithSingleTokenInsertion(t,n)||this.canRecoverWithSingleTokenDeletion(t)}canRecoverWithSingleTokenInsertion(t,n){if(!this.canTokenTypeBeInsertedInRecovery(t)||Ve(n))return!1;const r=this.LA(1);return Gi(n,s=>this.tokenMatcher(r,s))!==void 0}canRecoverWithSingleTokenDeletion(t){return this.canTokenTypeBeDeletedInRecovery(t)?this.tokenMatcher(this.LA(2),t):!1}isInCurrentRuleReSyncSet(t){const n=this.getCurrFollowKey(),r=this.getFollowSetFromFollowKey(n);return $t(r,t)}findReSyncTokenType(){const t=this.flattenFollowSet();let n=this.LA(1),r=2;for(;;){const i=Gi(t,s=>kT(n,s));if(i!==void 0)return i;n=this.LA(r),r++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return Wl;const t=this.getLastExplicitRuleShortName(),n=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(t),idxInCallingRule:n,inRule:this.shortRuleNameToFullName(r)}}buildFullFollowKeyStack(){const t=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return ce(t,(r,i)=>i===0?Wl:{ruleName:this.shortRuleNameToFullName(r),idxInCallingRule:n[i],inRule:this.shortRuleNameToFullName(t[i-1])})}flattenFollowSet(){const t=ce(this.buildFullFollowKeyStack(),n=>this.getFollowSetFromFollowKey(n));return sn(t)}getFollowSetFromFollowKey(t){if(t===Wl)return[hi];const n=t.ruleName+t.idxInCallingRule+rp+t.inRule;return this.resyncFollows[n]}addToResyncTokens(t,n){return this.tokenMatcher(t,hi)||n.push(t),n}reSyncTo(t){const n=[];let r=this.LA(1);for(;this.tokenMatcher(r,t)===!1;)r=this.SKIP_TOKEN(),this.addToResyncTokens(r,n);return Is(n)}attemptInRepetitionRecovery(t,n,r,i,s,o,a){}getCurrentGrammarPath(t,n){const r=this.getHumanReadableRuleStack(),i=Ct(this.RULE_OCCURRENCE_STACK);return{ruleStack:r,occurrenceStack:i,lastTok:t,lastTokOccurrence:n}}getHumanReadableRuleStack(){return ce(this.RULE_STACK,t=>this.shortRuleNameToFullName(t))}}function ax(e,t,n,r,i,s,o){const a=this.getKeyForAutomaticLookahead(r,i);let c=this.firstAfterRepMap[a];if(c===void 0){const d=this.getCurrRuleFullName(),h=this.getGAstProductions()[d];c=new s(h,i).startWalking(),this.firstAfterRepMap[a]=c}let l=c.token,u=c.occurrence;const f=c.isEndOfRule;this.RULE_STACK.length===1&&f&&l===void 0&&(l=hi,u=1),!(l===void 0||u===void 0)&&this.shouldInRepetitionRecoveryBeTried(l,u,o)&&this.tryInRepetitionRecovery(e,t,n,l)}const cx=4,$r=8,Vp=1<<$r,Kp=2<<$r,Gl=3<<$r,Hl=4<<$r,Vl=5<<$r,ka=6<<$r;function Kl(e,t,n){return n|t|e}class lx{constructor(t){var n;this.maxLookahead=(n=t==null?void 0:t.maxLookahead)!==null&&n!==void 0?n:_r.maxLookahead}validate(t){const n=this.validateNoLeftRecursion(t.rules);if(Ve(n)){const r=this.validateEmptyOrAlternatives(t.rules),i=this.validateAmbiguousAlternationAlternatives(t.rules,this.maxLookahead),s=this.validateSomeNonEmptyLookaheadPath(t.rules,this.maxLookahead);return[...n,...r,...i,...s]}return n}validateNoLeftRecursion(t){return yn(t,n=>Bp(n,n,di))}validateEmptyOrAlternatives(t){return yn(t,n=>VT(n,di))}validateAmbiguousAlternationAlternatives(t,n){return yn(t,r=>KT(r,n,di))}validateSomeNonEmptyLookaheadPath(t,n){return XT(t,n,di)}buildLookaheadForAlternation(t){return CT(t.prodOccurrence,t.rule,t.maxLookahead,t.hasPredicates,t.dynamicTokensEnabled,MT)}buildLookaheadForOptional(t){return LT(t.prodOccurrence,t.rule,t.maxLookahead,t.dynamicTokensEnabled,Cp(t.prodType),UT)}}class ux{initLooksAhead(t){this.dynamicTokensEnabled=pe(t,"dynamicTokensEnabled")?t.dynamicTokensEnabled:_r.dynamicTokensEnabled,this.maxLookahead=pe(t,"maxLookahead")?t.maxLookahead:_r.maxLookahead,this.lookaheadStrategy=pe(t,"lookaheadStrategy")?t.lookaheadStrategy:new lx({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(t){me(t,n=>{this.TRACE_INIT(`${n.name} Rule Lookahead`,()=>{const{alternation:r,repetition:i,option:s,repetitionMandatory:o,repetitionMandatoryWithSeparator:a,repetitionWithSeparator:c}=hx(n);me(r,l=>{const u=l.idx===0?"":l.idx;this.TRACE_INIT(`${Kn(l)}${u}`,()=>{const f=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:l.idx,rule:n,maxLookahead:l.maxLookahead||this.maxLookahead,hasPredicates:l.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),d=Kl(this.fullRuleNameToShort[n.name],Vp,l.idx);this.setLaFuncCache(d,f)})}),me(i,l=>{this.computeLookaheadFunc(n,l.idx,Gl,"Repetition",l.maxLookahead,Kn(l))}),me(s,l=>{this.computeLookaheadFunc(n,l.idx,Kp,"Option",l.maxLookahead,Kn(l))}),me(o,l=>{this.computeLookaheadFunc(n,l.idx,Hl,"RepetitionMandatory",l.maxLookahead,Kn(l))}),me(a,l=>{this.computeLookaheadFunc(n,l.idx,ka,"RepetitionMandatoryWithSeparator",l.maxLookahead,Kn(l))}),me(c,l=>{this.computeLookaheadFunc(n,l.idx,Vl,"RepetitionWithSeparator",l.maxLookahead,Kn(l))})})})}computeLookaheadFunc(t,n,r,i,s,o){this.TRACE_INIT(`${o}${n===0?"":n}`,()=>{const a=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:n,rule:t,maxLookahead:s||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),c=Kl(this.fullRuleNameToShort[t.name],r,n);this.setLaFuncCache(c,a)})}getKeyForAutomaticLookahead(t,n){const r=this.getLastExplicitRuleShortName();return Kl(r,t,n)}getLaFuncFromCache(t){return this.lookAheadFuncsCache.get(t)}setLaFuncCache(t,n){this.lookAheadFuncsCache.set(t,n)}}class fx extends ui{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(t){this.dslMethods.option.push(t)}visitRepetitionWithSeparator(t){this.dslMethods.repetitionWithSeparator.push(t)}visitRepetitionMandatory(t){this.dslMethods.repetitionMandatory.push(t)}visitRepetitionMandatoryWithSeparator(t){this.dslMethods.repetitionMandatoryWithSeparator.push(t)}visitRepetition(t){this.dslMethods.repetition.push(t)}visitAlternation(t){this.dslMethods.alternation.push(t)}}const Sa=new fx;function hx(e){Sa.reset(),e.accept(Sa);const t=Sa.dslMethods;return Sa.reset(),t}function qp(e,t){isNaN(e.startOffset)===!0?(e.startOffset=t.startOffset,e.endOffset=t.endOffset):e.endOffseto.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: ${s.join(` `).replace(/\n/g,` - `)}`)}}};return n.prototype=r,n.prototype.constructor=n,n._RULE_NAMES=t,n}function yx(e,t,n){const r=function(){};Xp(r,e+"BaseSemanticsWithDefaults");const i=Object.create(n.prototype);return me(t,s=>{i[s]=mx}),r.prototype=i,r.prototype.constructor=r,r}var ql;(function(e){e[e.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",e[e.MISSING_METHOD=1]="MISSING_METHOD"})(ql||(ql={}));function _x(e,t){return bx(e,t)}function bx(e,t){const n=gn(t,i=>dr(e[i])===!1),r=ce(n,i=>({msg:`Missing visitor method: <${i}> on ${e.constructor.name} CST Visitor.`,type:ql.MISSING_METHOD,methodName:i}));return Rs(r)}class wx{initTreeBuilder(t){if(this.CST_STACK=[],this.outputCst=t.outputCst,this.nodeLocationTracking=pe(t,"nodeLocationTracking")?t.nodeLocationTracking:_r.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=_t,this.cstFinallyStateUpdate=_t,this.cstPostTerminal=_t,this.cstPostNonTerminal=_t,this.cstPostRule=_t;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Jp,this.setNodeLocationFromNode=Jp,this.cstPostRule=_t,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=_t,this.setNodeLocationFromNode=_t,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=qp,this.setNodeLocationFromNode=qp,this.cstPostRule=_t,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=_t,this.setNodeLocationFromNode=_t,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=_t,this.setNodeLocationFromNode=_t,this.cstPostRule=_t,this.setInitialNodeLocation=_t;else throw Error(`Invalid config option: "${t.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(t){t.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(t){t.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(t){t.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(t){const n=this.LA(1);t.location={startOffset:n.startOffset,startLine:n.startLine,startColumn:n.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(t){const n={name:t,children:Object.create(null)};this.setInitialNodeLocation(n),this.CST_STACK.push(n)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(t){const n=this.LA(0),r=t.location;r.startOffset<=n.startOffset?(r.endOffset=n.endOffset,r.endLine=n.endLine,r.endColumn=n.endColumn):(r.startOffset=NaN,r.startLine=NaN,r.startColumn=NaN)}cstPostRuleOnlyOffset(t){const n=this.LA(0),r=t.location;r.startOffset<=n.startOffset?r.endOffset=n.endOffset:r.startOffset=NaN}cstPostTerminal(t,n){const r=this.CST_STACK[this.CST_STACK.length-1];hx(r,n,t),this.setNodeLocationFromToken(r.location,n)}cstPostNonTerminal(t,n){const r=this.CST_STACK[this.CST_STACK.length-1];dx(r,n,t),this.setNodeLocationFromNode(r.location,t.location)}getBaseCstVisitorConstructor(){if(yr(this.baseCstVisitorConstructor)){const t=gx(this.className,pn(this.gastProductionsCache));return this.baseCstVisitorConstructor=t,t}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(yr(this.baseCstVisitorWithDefaultsConstructor)){const t=yx(this.className,pn(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=t,t}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){const t=this.RULE_STACK;return t[t.length-1]}getPreviousExplicitRuleShortName(){const t=this.RULE_STACK;return t[t.length-2]}getLastExplicitRuleOccurrenceIndex(){const t=this.RULE_OCCURRENCE_STACK;return t[t.length-1]}}class vx{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(t){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=t,this.tokVectorLength=t.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):xa}LA(t){const n=this.currIdx+t;return n<0||this.tokVectorLength<=n?xa:this.tokVector[n]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(t){this.currIdx=t}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}}class Ex{ACTION(t){return t.call(this)}consume(t,n,r){return this.consumeInternal(n,t,r)}subrule(t,n,r){return this.subruleInternal(n,t,r)}option(t,n){return this.optionInternal(n,t)}or(t,n){return this.orInternal(n,t)}many(t,n){return this.manyInternal(t,n)}atLeastOne(t,n){return this.atLeastOneInternal(t,n)}CONSUME(t,n){return this.consumeInternal(t,0,n)}CONSUME1(t,n){return this.consumeInternal(t,1,n)}CONSUME2(t,n){return this.consumeInternal(t,2,n)}CONSUME3(t,n){return this.consumeInternal(t,3,n)}CONSUME4(t,n){return this.consumeInternal(t,4,n)}CONSUME5(t,n){return this.consumeInternal(t,5,n)}CONSUME6(t,n){return this.consumeInternal(t,6,n)}CONSUME7(t,n){return this.consumeInternal(t,7,n)}CONSUME8(t,n){return this.consumeInternal(t,8,n)}CONSUME9(t,n){return this.consumeInternal(t,9,n)}SUBRULE(t,n){return this.subruleInternal(t,0,n)}SUBRULE1(t,n){return this.subruleInternal(t,1,n)}SUBRULE2(t,n){return this.subruleInternal(t,2,n)}SUBRULE3(t,n){return this.subruleInternal(t,3,n)}SUBRULE4(t,n){return this.subruleInternal(t,4,n)}SUBRULE5(t,n){return this.subruleInternal(t,5,n)}SUBRULE6(t,n){return this.subruleInternal(t,6,n)}SUBRULE7(t,n){return this.subruleInternal(t,7,n)}SUBRULE8(t,n){return this.subruleInternal(t,8,n)}SUBRULE9(t,n){return this.subruleInternal(t,9,n)}OPTION(t){return this.optionInternal(t,0)}OPTION1(t){return this.optionInternal(t,1)}OPTION2(t){return this.optionInternal(t,2)}OPTION3(t){return this.optionInternal(t,3)}OPTION4(t){return this.optionInternal(t,4)}OPTION5(t){return this.optionInternal(t,5)}OPTION6(t){return this.optionInternal(t,6)}OPTION7(t){return this.optionInternal(t,7)}OPTION8(t){return this.optionInternal(t,8)}OPTION9(t){return this.optionInternal(t,9)}OR(t){return this.orInternal(t,0)}OR1(t){return this.orInternal(t,1)}OR2(t){return this.orInternal(t,2)}OR3(t){return this.orInternal(t,3)}OR4(t){return this.orInternal(t,4)}OR5(t){return this.orInternal(t,5)}OR6(t){return this.orInternal(t,6)}OR7(t){return this.orInternal(t,7)}OR8(t){return this.orInternal(t,8)}OR9(t){return this.orInternal(t,9)}MANY(t){this.manyInternal(0,t)}MANY1(t){this.manyInternal(1,t)}MANY2(t){this.manyInternal(2,t)}MANY3(t){this.manyInternal(3,t)}MANY4(t){this.manyInternal(4,t)}MANY5(t){this.manyInternal(5,t)}MANY6(t){this.manyInternal(6,t)}MANY7(t){this.manyInternal(7,t)}MANY8(t){this.manyInternal(8,t)}MANY9(t){this.manyInternal(9,t)}MANY_SEP(t){this.manySepFirstInternal(0,t)}MANY_SEP1(t){this.manySepFirstInternal(1,t)}MANY_SEP2(t){this.manySepFirstInternal(2,t)}MANY_SEP3(t){this.manySepFirstInternal(3,t)}MANY_SEP4(t){this.manySepFirstInternal(4,t)}MANY_SEP5(t){this.manySepFirstInternal(5,t)}MANY_SEP6(t){this.manySepFirstInternal(6,t)}MANY_SEP7(t){this.manySepFirstInternal(7,t)}MANY_SEP8(t){this.manySepFirstInternal(8,t)}MANY_SEP9(t){this.manySepFirstInternal(9,t)}AT_LEAST_ONE(t){this.atLeastOneInternal(0,t)}AT_LEAST_ONE1(t){return this.atLeastOneInternal(1,t)}AT_LEAST_ONE2(t){this.atLeastOneInternal(2,t)}AT_LEAST_ONE3(t){this.atLeastOneInternal(3,t)}AT_LEAST_ONE4(t){this.atLeastOneInternal(4,t)}AT_LEAST_ONE5(t){this.atLeastOneInternal(5,t)}AT_LEAST_ONE6(t){this.atLeastOneInternal(6,t)}AT_LEAST_ONE7(t){this.atLeastOneInternal(7,t)}AT_LEAST_ONE8(t){this.atLeastOneInternal(8,t)}AT_LEAST_ONE9(t){this.atLeastOneInternal(9,t)}AT_LEAST_ONE_SEP(t){this.atLeastOneSepFirstInternal(0,t)}AT_LEAST_ONE_SEP1(t){this.atLeastOneSepFirstInternal(1,t)}AT_LEAST_ONE_SEP2(t){this.atLeastOneSepFirstInternal(2,t)}AT_LEAST_ONE_SEP3(t){this.atLeastOneSepFirstInternal(3,t)}AT_LEAST_ONE_SEP4(t){this.atLeastOneSepFirstInternal(4,t)}AT_LEAST_ONE_SEP5(t){this.atLeastOneSepFirstInternal(5,t)}AT_LEAST_ONE_SEP6(t){this.atLeastOneSepFirstInternal(6,t)}AT_LEAST_ONE_SEP7(t){this.atLeastOneSepFirstInternal(7,t)}AT_LEAST_ONE_SEP8(t){this.atLeastOneSepFirstInternal(8,t)}AT_LEAST_ONE_SEP9(t){this.atLeastOneSepFirstInternal(9,t)}RULE(t,n,r=Ra){if($t(this.definedRulesNames,t)){const o={message:di.buildDuplicateRuleNameError({topLevelRule:t,grammarName:this.className}),type:jt.DUPLICATE_RULE_NAME,ruleName:t};this.definitionErrors.push(o)}this.definedRulesNames.push(t);const i=this.defineRule(t,n,r);return this[t]=i,i}OVERRIDE_RULE(t,n,r=Ra){const i=GT(t,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);const s=this.defineRule(t,n,r);return this[t]=s,s}BACKTRACK(t,n){return function(){this.isBackTrackingStack.push(1);const r=this.saveRecogState();try{return t.apply(this,n),!0}catch(i){if(va(i))return!1;throw i}finally{this.reloadRecogState(r),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return SA(dt(this.gastProductionsCache))}}class kx{initRecognizerEngine(t,n){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=ya,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},pe(n,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. + `)}`)}}};return n.prototype=r,n.prototype.constructor=n,n._RULE_NAMES=t,n}function _x(e,t,n){const r=function(){};Xp(r,e+"BaseSemanticsWithDefaults");const i=Object.create(n.prototype);return me(t,s=>{i[s]=gx}),r.prototype=i,r.prototype.constructor=r,r}var ql;(function(e){e[e.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",e[e.MISSING_METHOD=1]="MISSING_METHOD"})(ql||(ql={}));function bx(e,t){return wx(e,t)}function wx(e,t){const n=gn(t,i=>dr(e[i])===!1),r=ce(n,i=>({msg:`Missing visitor method: <${i}> on ${e.constructor.name} CST Visitor.`,type:ql.MISSING_METHOD,methodName:i}));return Rs(r)}class vx{initTreeBuilder(t){if(this.CST_STACK=[],this.outputCst=t.outputCst,this.nodeLocationTracking=pe(t,"nodeLocationTracking")?t.nodeLocationTracking:_r.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=_t,this.cstFinallyStateUpdate=_t,this.cstPostTerminal=_t,this.cstPostNonTerminal=_t,this.cstPostRule=_t;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Jp,this.setNodeLocationFromNode=Jp,this.cstPostRule=_t,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=_t,this.setNodeLocationFromNode=_t,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=qp,this.setNodeLocationFromNode=qp,this.cstPostRule=_t,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=_t,this.setNodeLocationFromNode=_t,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=_t,this.setNodeLocationFromNode=_t,this.cstPostRule=_t,this.setInitialNodeLocation=_t;else throw Error(`Invalid config option: "${t.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(t){t.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(t){t.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(t){t.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(t){const n=this.LA(1);t.location={startOffset:n.startOffset,startLine:n.startLine,startColumn:n.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(t){const n={name:t,children:Object.create(null)};this.setInitialNodeLocation(n),this.CST_STACK.push(n)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(t){const n=this.LA(0),r=t.location;r.startOffset<=n.startOffset?(r.endOffset=n.endOffset,r.endLine=n.endLine,r.endColumn=n.endColumn):(r.startOffset=NaN,r.startLine=NaN,r.startColumn=NaN)}cstPostRuleOnlyOffset(t){const n=this.LA(0),r=t.location;r.startOffset<=n.startOffset?r.endOffset=n.endOffset:r.startOffset=NaN}cstPostTerminal(t,n){const r=this.CST_STACK[this.CST_STACK.length-1];dx(r,n,t),this.setNodeLocationFromToken(r.location,n)}cstPostNonTerminal(t,n){const r=this.CST_STACK[this.CST_STACK.length-1];px(r,n,t),this.setNodeLocationFromNode(r.location,t.location)}getBaseCstVisitorConstructor(){if(yr(this.baseCstVisitorConstructor)){const t=yx(this.className,pn(this.gastProductionsCache));return this.baseCstVisitorConstructor=t,t}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(yr(this.baseCstVisitorWithDefaultsConstructor)){const t=_x(this.className,pn(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=t,t}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){const t=this.RULE_STACK;return t[t.length-1]}getPreviousExplicitRuleShortName(){const t=this.RULE_STACK;return t[t.length-2]}getLastExplicitRuleOccurrenceIndex(){const t=this.RULE_OCCURRENCE_STACK;return t[t.length-1]}}class Ex{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(t){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=t,this.tokVectorLength=t.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):xa}LA(t){const n=this.currIdx+t;return n<0||this.tokVectorLength<=n?xa:this.tokVector[n]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(t){this.currIdx=t}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}}class kx{ACTION(t){return t.call(this)}consume(t,n,r){return this.consumeInternal(n,t,r)}subrule(t,n,r){return this.subruleInternal(n,t,r)}option(t,n){return this.optionInternal(n,t)}or(t,n){return this.orInternal(n,t)}many(t,n){return this.manyInternal(t,n)}atLeastOne(t,n){return this.atLeastOneInternal(t,n)}CONSUME(t,n){return this.consumeInternal(t,0,n)}CONSUME1(t,n){return this.consumeInternal(t,1,n)}CONSUME2(t,n){return this.consumeInternal(t,2,n)}CONSUME3(t,n){return this.consumeInternal(t,3,n)}CONSUME4(t,n){return this.consumeInternal(t,4,n)}CONSUME5(t,n){return this.consumeInternal(t,5,n)}CONSUME6(t,n){return this.consumeInternal(t,6,n)}CONSUME7(t,n){return this.consumeInternal(t,7,n)}CONSUME8(t,n){return this.consumeInternal(t,8,n)}CONSUME9(t,n){return this.consumeInternal(t,9,n)}SUBRULE(t,n){return this.subruleInternal(t,0,n)}SUBRULE1(t,n){return this.subruleInternal(t,1,n)}SUBRULE2(t,n){return this.subruleInternal(t,2,n)}SUBRULE3(t,n){return this.subruleInternal(t,3,n)}SUBRULE4(t,n){return this.subruleInternal(t,4,n)}SUBRULE5(t,n){return this.subruleInternal(t,5,n)}SUBRULE6(t,n){return this.subruleInternal(t,6,n)}SUBRULE7(t,n){return this.subruleInternal(t,7,n)}SUBRULE8(t,n){return this.subruleInternal(t,8,n)}SUBRULE9(t,n){return this.subruleInternal(t,9,n)}OPTION(t){return this.optionInternal(t,0)}OPTION1(t){return this.optionInternal(t,1)}OPTION2(t){return this.optionInternal(t,2)}OPTION3(t){return this.optionInternal(t,3)}OPTION4(t){return this.optionInternal(t,4)}OPTION5(t){return this.optionInternal(t,5)}OPTION6(t){return this.optionInternal(t,6)}OPTION7(t){return this.optionInternal(t,7)}OPTION8(t){return this.optionInternal(t,8)}OPTION9(t){return this.optionInternal(t,9)}OR(t){return this.orInternal(t,0)}OR1(t){return this.orInternal(t,1)}OR2(t){return this.orInternal(t,2)}OR3(t){return this.orInternal(t,3)}OR4(t){return this.orInternal(t,4)}OR5(t){return this.orInternal(t,5)}OR6(t){return this.orInternal(t,6)}OR7(t){return this.orInternal(t,7)}OR8(t){return this.orInternal(t,8)}OR9(t){return this.orInternal(t,9)}MANY(t){this.manyInternal(0,t)}MANY1(t){this.manyInternal(1,t)}MANY2(t){this.manyInternal(2,t)}MANY3(t){this.manyInternal(3,t)}MANY4(t){this.manyInternal(4,t)}MANY5(t){this.manyInternal(5,t)}MANY6(t){this.manyInternal(6,t)}MANY7(t){this.manyInternal(7,t)}MANY8(t){this.manyInternal(8,t)}MANY9(t){this.manyInternal(9,t)}MANY_SEP(t){this.manySepFirstInternal(0,t)}MANY_SEP1(t){this.manySepFirstInternal(1,t)}MANY_SEP2(t){this.manySepFirstInternal(2,t)}MANY_SEP3(t){this.manySepFirstInternal(3,t)}MANY_SEP4(t){this.manySepFirstInternal(4,t)}MANY_SEP5(t){this.manySepFirstInternal(5,t)}MANY_SEP6(t){this.manySepFirstInternal(6,t)}MANY_SEP7(t){this.manySepFirstInternal(7,t)}MANY_SEP8(t){this.manySepFirstInternal(8,t)}MANY_SEP9(t){this.manySepFirstInternal(9,t)}AT_LEAST_ONE(t){this.atLeastOneInternal(0,t)}AT_LEAST_ONE1(t){return this.atLeastOneInternal(1,t)}AT_LEAST_ONE2(t){this.atLeastOneInternal(2,t)}AT_LEAST_ONE3(t){this.atLeastOneInternal(3,t)}AT_LEAST_ONE4(t){this.atLeastOneInternal(4,t)}AT_LEAST_ONE5(t){this.atLeastOneInternal(5,t)}AT_LEAST_ONE6(t){this.atLeastOneInternal(6,t)}AT_LEAST_ONE7(t){this.atLeastOneInternal(7,t)}AT_LEAST_ONE8(t){this.atLeastOneInternal(8,t)}AT_LEAST_ONE9(t){this.atLeastOneInternal(9,t)}AT_LEAST_ONE_SEP(t){this.atLeastOneSepFirstInternal(0,t)}AT_LEAST_ONE_SEP1(t){this.atLeastOneSepFirstInternal(1,t)}AT_LEAST_ONE_SEP2(t){this.atLeastOneSepFirstInternal(2,t)}AT_LEAST_ONE_SEP3(t){this.atLeastOneSepFirstInternal(3,t)}AT_LEAST_ONE_SEP4(t){this.atLeastOneSepFirstInternal(4,t)}AT_LEAST_ONE_SEP5(t){this.atLeastOneSepFirstInternal(5,t)}AT_LEAST_ONE_SEP6(t){this.atLeastOneSepFirstInternal(6,t)}AT_LEAST_ONE_SEP7(t){this.atLeastOneSepFirstInternal(7,t)}AT_LEAST_ONE_SEP8(t){this.atLeastOneSepFirstInternal(8,t)}AT_LEAST_ONE_SEP9(t){this.atLeastOneSepFirstInternal(9,t)}RULE(t,n,r=Ra){if($t(this.definedRulesNames,t)){const o={message:di.buildDuplicateRuleNameError({topLevelRule:t,grammarName:this.className}),type:jt.DUPLICATE_RULE_NAME,ruleName:t};this.definitionErrors.push(o)}this.definedRulesNames.push(t);const i=this.defineRule(t,n,r);return this[t]=i,i}OVERRIDE_RULE(t,n,r=Ra){const i=HT(t,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);const s=this.defineRule(t,n,r);return this[t]=s,s}BACKTRACK(t,n){return function(){this.isBackTrackingStack.push(1);const r=this.saveRecogState();try{return t.apply(this,n),!0}catch(i){if(va(i))return!1;throw i}finally{this.reloadRecogState(r),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return AA(dt(this.gastProductionsCache))}}class Sx{initRecognizerEngine(t,n){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=ya,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},pe(n,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 For Further details.`);if(Le(t)){if(Ve(t))throw Error(`A Token Vocabulary cannot be empty. Note that the first argument for the parser constructor is no longer a Token vector (since v4.0).`);if(typeof t[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 - For Further details.`)}if(Le(t))this.tokensMap=Xt(t,(s,o)=>(s[o.name]=o,s),{});else if(pe(t,"modes")&&Rn(sn(dt(t.modes)),_T)){const s=sn(dt(t.modes)),o=ia(s);this.tokensMap=Xt(o,(a,c)=>(a[c.name]=c,a),{})}else if(dn(t))this.tokensMap=Ct(t);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=hi;const r=pe(t,"modes")?sn(dt(t.modes)):dt(t),i=Rn(r,s=>Ve(s.categoryMatches));this.tokenMatcher=i?ya:Ms,Us(dt(this.tokensMap))}defineRule(t,n,r){if(this.selfAnalysisDone)throw Error(`Grammar rule <${t}> may not be defined after the 'performSelfAnalysis' method has been called' -Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);const i=pe(r,"resyncEnabled")?r.resyncEnabled:Ra.resyncEnabled,s=pe(r,"recoveryValueFunc")?r.recoveryValueFunc:Ra.recoveryValueFunc,o=this.ruleShortNameIdx<o.call(this)&&a.call(this)}}else s=t;if(i.call(this)===!0)return s.call(this)}atLeastOneInternal(t,n){const r=this.getKeyForAutomaticLookahead(Hl,t);return this.atLeastOneInternalLogic(t,n,r)}atLeastOneInternalLogic(t,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const o=n.GATE;if(o!==void 0){const a=i;i=()=>o.call(this)&&a.call(this)}}else s=n;if(i.call(this)===!0){let o=this.doSingleRepetition(s);for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s)}else throw this.raiseEarlyExitException(t,ot.REPETITION_MANDATORY,n.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[t,n],i,Hl,t,IT)}atLeastOneSepFirstInternal(t,n){const r=this.getKeyForAutomaticLookahead(ka,t);this.atLeastOneSepFirstInternalLogic(t,n,r)}atLeastOneSepFirstInternalLogic(t,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,s,a,i,Op],a,ka,t,Op)}else throw this.raiseEarlyExitException(t,ot.REPETITION_MANDATORY_WITH_SEPARATOR,n.ERR_MSG)}manyInternal(t,n){const r=this.getKeyForAutomaticLookahead(Gl,t);return this.manyInternalLogic(t,n,r)}manyInternalLogic(t,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const a=n.GATE;if(a!==void 0){const c=i;i=()=>a.call(this)&&c.call(this)}}else s=n;let o=!0;for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s);this.attemptInRepetitionRecovery(this.manyInternal,[t,n],i,Gl,t,RT,o)}manySepFirstInternal(t,n){const r=this.getKeyForAutomaticLookahead(Vl,t);this.manySepFirstInternalLogic(t,n,r)}manySepFirstInternalLogic(t,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,s,a,i,Ip],a,Vl,t,Ip)}}repetitionSepSecondInternal(t,n,r,i,s){for(;r();)this.CONSUME(n),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,n,r,i,s],r,ka,t,s)}doSingleRepetition(t){const n=this.getLexerPosition();return t.call(this),this.getLexerPosition()>n}orInternal(t,n){const r=this.getKeyForAutomaticLookahead(Vp,n),i=Le(t)?t:t.DEF,o=this.getLaFuncFromCache(r).call(this,i);if(o!==void 0)return i[o].ALT.call(this);this.raiseNoAltException(n,t.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){const t=this.LA(1),n=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:t,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new nx(n,t))}}subruleInternal(t,n,r){let i;try{const s=r!==void 0?r.ARGS:void 0;return this.subruleIdx=n,i=t.apply(this,s),this.cstPostNonTerminal(i,r!==void 0&&r.LABEL!==void 0?r.LABEL:t.ruleName),i}catch(s){throw this.subruleInternalError(s,r,t.ruleName)}}subruleInternalError(t,n,r){throw va(t)&&t.partialCstResult!==void 0&&(this.cstPostNonTerminal(t.partialCstResult,n!==void 0&&n.LABEL!==void 0?n.LABEL:r),delete t.partialCstResult),t}consumeInternal(t,n,r){let i;try{const s=this.LA(1);this.tokenMatcher(s,t)===!0?(this.consumeToken(),i=s):this.consumeInternalError(t,s,r)}catch(s){i=this.consumeInternalRecovery(t,n,s)}return this.cstPostTerminal(r!==void 0&&r.LABEL!==void 0?r.LABEL:t.name,i),i}consumeInternalError(t,n,r){let i;const s=this.LA(0);throw r!==void 0&&r.ERR_MSG?i=r.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:t,actual:n,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new Gp(i,n,s))}consumeInternalRecovery(t,n,r){if(this.recoveryEnabled&&r.name==="MismatchedTokenException"&&!this.isBackTracking()){const i=this.getFollowsForInRuleRecovery(t,n);try{return this.tryInRuleRecovery(t,i)}catch(s){throw s.name===Hp?r:s}}else throw r}saveRecogState(){const t=this.errors,n=Ct(this.RULE_STACK);return{errors:t,lexerState:this.exportLexerState(),RULE_STACK:n,CST_STACK:this.CST_STACK}}reloadRecogState(t){this.errors=t.errors,this.importLexerState(t.lexerState),this.RULE_STACK=t.RULE_STACK}ruleInvocationStateUpdate(t,n,r){this.RULE_OCCURRENCE_STACK.push(r),this.RULE_STACK.push(t),this.cstInvocationStateUpdate(n)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){const t=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[t]}shortRuleNameToFullName(t){return this.shortRuleNameToFull[t]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),hi)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}}class Sx{initErrorHandler(t){this._errors=[],this.errorMessageProvider=pe(t,"errorMessageProvider")?t.errorMessageProvider:_r.errorMessageProvider}SAVE_ERROR(t){if(va(t))return t.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:Ct(this.RULE_OCCURRENCE_STACK)},this._errors.push(t),t;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return Ct(this._errors)}set errors(t){this._errors=t}raiseEarlyExitException(t,n,r){const i=this.getCurrRuleFullName(),s=this.getGAstProductions()[i],a=$l(t,s,n,this.maxLookahead)[0],c=[];for(let u=1;u<=this.maxLookahead;u++)c.push(this.LA(u));const l=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:c,previous:this.LA(0),customUserDescription:r,ruleName:i});throw this.SAVE_ERROR(new rx(l,this.LA(1),this.LA(0)))}raiseNoAltException(t,n){const r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],s=Fl(t,i,this.maxLookahead),o=[];for(let l=1;l<=this.maxLookahead;l++)o.push(this.LA(l));const a=this.LA(0),c=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:o,previous:a,customUserDescription:n,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new tx(c,this.LA(1),a))}}class Ax{initContentAssist(){}computeContentAssist(t,n){const r=this.gastProductionsCache[t];if(yr(r))throw Error(`Rule ->${t}<- does not exist in this grammar.`);return Np([r],n,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(t){const n=In(t.ruleStack),i=this.getGAstProductions()[n];return new xT(i,t).startWalking()}}const Aa={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(Aa);const Zp=!0,Yp=Math.pow(2,$r)-1,Qp=on({name:"RECORDING_PHASE_TOKEN",pattern:wt.NA});Us([Qp]);const em=_a(Qp,`This IToken indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(em);const Tx={name:`This CSTNode indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}};class xx{initGastRecorder(t){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let t=0;t<10;t++){const n=t>0?t:"";this[`CONSUME${n}`]=function(r,i){return this.consumeInternalRecord(r,t,i)},this[`SUBRULE${n}`]=function(r,i){return this.subruleInternalRecord(r,t,i)},this[`OPTION${n}`]=function(r){return this.optionInternalRecord(r,t)},this[`OR${n}`]=function(r){return this.orInternalRecord(r,t)},this[`MANY${n}`]=function(r){this.manyInternalRecord(t,r)},this[`MANY_SEP${n}`]=function(r){this.manySepFirstInternalRecord(t,r)},this[`AT_LEAST_ONE${n}`]=function(r){this.atLeastOneInternalRecord(t,r)},this[`AT_LEAST_ONE_SEP${n}`]=function(r){this.atLeastOneSepFirstInternalRecord(t,r)}}this.consume=function(t,n,r){return this.consumeInternalRecord(n,t,r)},this.subrule=function(t,n,r){return this.subruleInternalRecord(n,t,r)},this.option=function(t,n){return this.optionInternalRecord(n,t)},this.or=function(t,n){return this.orInternalRecord(n,t)},this.many=function(t,n){this.manyInternalRecord(t,n)},this.atLeastOne=function(t,n){this.atLeastOneInternalRecord(t,n)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{const t=this;for(let n=0;n<10;n++){const r=n>0?n:"";delete t[`CONSUME${r}`],delete t[`SUBRULE${r}`],delete t[`OPTION${r}`],delete t[`OR${r}`],delete t[`MANY${r}`],delete t[`MANY_SEP${r}`],delete t[`AT_LEAST_ONE${r}`],delete t[`AT_LEAST_ONE_SEP${r}`]}delete t.consume,delete t.subrule,delete t.option,delete t.or,delete t.many,delete t.atLeastOne,delete t.ACTION,delete t.BACKTRACK,delete t.LA})}ACTION_RECORD(t){}BACKTRACK_RECORD(t,n){return()=>!0}LA_RECORD(t){return xa}topLevelRuleRecord(t,n){try{const r=new Hi({definition:[],name:t});return r.name=t,this.recordingProdStack.push(r),n.call(this),this.recordingProdStack.pop(),r}catch(r){if(r.KNOWN_RECORDER_ERROR!==!0)try{r.message=r.message+` + For Further details.`)}if(Le(t))this.tokensMap=Xt(t,(s,o)=>(s[o.name]=o,s),{});else if(pe(t,"modes")&&Rn(sn(dt(t.modes)),bT)){const s=sn(dt(t.modes)),o=ia(s);this.tokensMap=Xt(o,(a,c)=>(a[c.name]=c,a),{})}else if(dn(t))this.tokensMap=Ct(t);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=hi;const r=pe(t,"modes")?sn(dt(t.modes)):dt(t),i=Rn(r,s=>Ve(s.categoryMatches));this.tokenMatcher=i?ya:Ms,Us(dt(this.tokensMap))}defineRule(t,n,r){if(this.selfAnalysisDone)throw Error(`Grammar rule <${t}> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);const i=pe(r,"resyncEnabled")?r.resyncEnabled:Ra.resyncEnabled,s=pe(r,"recoveryValueFunc")?r.recoveryValueFunc:Ra.recoveryValueFunc,o=this.ruleShortNameIdx<o.call(this)&&a.call(this)}}else s=t;if(i.call(this)===!0)return s.call(this)}atLeastOneInternal(t,n){const r=this.getKeyForAutomaticLookahead(Hl,t);return this.atLeastOneInternalLogic(t,n,r)}atLeastOneInternalLogic(t,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const o=n.GATE;if(o!==void 0){const a=i;i=()=>o.call(this)&&a.call(this)}}else s=n;if(i.call(this)===!0){let o=this.doSingleRepetition(s);for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s)}else throw this.raiseEarlyExitException(t,ot.REPETITION_MANDATORY,n.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[t,n],i,Hl,t,OT)}atLeastOneSepFirstInternal(t,n){const r=this.getKeyForAutomaticLookahead(ka,t);this.atLeastOneSepFirstInternalLogic(t,n,r)}atLeastOneSepFirstInternalLogic(t,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,s,a,i,Op],a,ka,t,Op)}else throw this.raiseEarlyExitException(t,ot.REPETITION_MANDATORY_WITH_SEPARATOR,n.ERR_MSG)}manyInternal(t,n){const r=this.getKeyForAutomaticLookahead(Gl,t);return this.manyInternalLogic(t,n,r)}manyInternalLogic(t,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const a=n.GATE;if(a!==void 0){const c=i;i=()=>a.call(this)&&c.call(this)}}else s=n;let o=!0;for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s);this.attemptInRepetitionRecovery(this.manyInternal,[t,n],i,Gl,t,IT,o)}manySepFirstInternal(t,n){const r=this.getKeyForAutomaticLookahead(Vl,t);this.manySepFirstInternalLogic(t,n,r)}manySepFirstInternalLogic(t,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,s,a,i,Ip],a,Vl,t,Ip)}}repetitionSepSecondInternal(t,n,r,i,s){for(;r();)this.CONSUME(n),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,n,r,i,s],r,ka,t,s)}doSingleRepetition(t){const n=this.getLexerPosition();return t.call(this),this.getLexerPosition()>n}orInternal(t,n){const r=this.getKeyForAutomaticLookahead(Vp,n),i=Le(t)?t:t.DEF,o=this.getLaFuncFromCache(r).call(this,i);if(o!==void 0)return i[o].ALT.call(this);this.raiseNoAltException(n,t.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){const t=this.LA(1),n=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:t,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new rx(n,t))}}subruleInternal(t,n,r){let i;try{const s=r!==void 0?r.ARGS:void 0;return this.subruleIdx=n,i=t.apply(this,s),this.cstPostNonTerminal(i,r!==void 0&&r.LABEL!==void 0?r.LABEL:t.ruleName),i}catch(s){throw this.subruleInternalError(s,r,t.ruleName)}}subruleInternalError(t,n,r){throw va(t)&&t.partialCstResult!==void 0&&(this.cstPostNonTerminal(t.partialCstResult,n!==void 0&&n.LABEL!==void 0?n.LABEL:r),delete t.partialCstResult),t}consumeInternal(t,n,r){let i;try{const s=this.LA(1);this.tokenMatcher(s,t)===!0?(this.consumeToken(),i=s):this.consumeInternalError(t,s,r)}catch(s){i=this.consumeInternalRecovery(t,n,s)}return this.cstPostTerminal(r!==void 0&&r.LABEL!==void 0?r.LABEL:t.name,i),i}consumeInternalError(t,n,r){let i;const s=this.LA(0);throw r!==void 0&&r.ERR_MSG?i=r.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:t,actual:n,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new Gp(i,n,s))}consumeInternalRecovery(t,n,r){if(this.recoveryEnabled&&r.name==="MismatchedTokenException"&&!this.isBackTracking()){const i=this.getFollowsForInRuleRecovery(t,n);try{return this.tryInRuleRecovery(t,i)}catch(s){throw s.name===Hp?r:s}}else throw r}saveRecogState(){const t=this.errors,n=Ct(this.RULE_STACK);return{errors:t,lexerState:this.exportLexerState(),RULE_STACK:n,CST_STACK:this.CST_STACK}}reloadRecogState(t){this.errors=t.errors,this.importLexerState(t.lexerState),this.RULE_STACK=t.RULE_STACK}ruleInvocationStateUpdate(t,n,r){this.RULE_OCCURRENCE_STACK.push(r),this.RULE_STACK.push(t),this.cstInvocationStateUpdate(n)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){const t=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[t]}shortRuleNameToFullName(t){return this.shortRuleNameToFull[t]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),hi)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}}class Ax{initErrorHandler(t){this._errors=[],this.errorMessageProvider=pe(t,"errorMessageProvider")?t.errorMessageProvider:_r.errorMessageProvider}SAVE_ERROR(t){if(va(t))return t.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:Ct(this.RULE_OCCURRENCE_STACK)},this._errors.push(t),t;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return Ct(this._errors)}set errors(t){this._errors=t}raiseEarlyExitException(t,n,r){const i=this.getCurrRuleFullName(),s=this.getGAstProductions()[i],a=$l(t,s,n,this.maxLookahead)[0],c=[];for(let u=1;u<=this.maxLookahead;u++)c.push(this.LA(u));const l=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:c,previous:this.LA(0),customUserDescription:r,ruleName:i});throw this.SAVE_ERROR(new ix(l,this.LA(1),this.LA(0)))}raiseNoAltException(t,n){const r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],s=Fl(t,i,this.maxLookahead),o=[];for(let l=1;l<=this.maxLookahead;l++)o.push(this.LA(l));const a=this.LA(0),c=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:o,previous:a,customUserDescription:n,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new nx(c,this.LA(1),a))}}class Tx{initContentAssist(){}computeContentAssist(t,n){const r=this.gastProductionsCache[t];if(yr(r))throw Error(`Rule ->${t}<- does not exist in this grammar.`);return Np([r],n,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(t){const n=In(t.ruleStack),i=this.getGAstProductions()[n];return new RT(i,t).startWalking()}}const Aa={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(Aa);const Zp=!0,Yp=Math.pow(2,$r)-1,Qp=on({name:"RECORDING_PHASE_TOKEN",pattern:wt.NA});Us([Qp]);const em=_a(Qp,`This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(em);const xx={name:`This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}};class Rx{initGastRecorder(t){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let t=0;t<10;t++){const n=t>0?t:"";this[`CONSUME${n}`]=function(r,i){return this.consumeInternalRecord(r,t,i)},this[`SUBRULE${n}`]=function(r,i){return this.subruleInternalRecord(r,t,i)},this[`OPTION${n}`]=function(r){return this.optionInternalRecord(r,t)},this[`OR${n}`]=function(r){return this.orInternalRecord(r,t)},this[`MANY${n}`]=function(r){this.manyInternalRecord(t,r)},this[`MANY_SEP${n}`]=function(r){this.manySepFirstInternalRecord(t,r)},this[`AT_LEAST_ONE${n}`]=function(r){this.atLeastOneInternalRecord(t,r)},this[`AT_LEAST_ONE_SEP${n}`]=function(r){this.atLeastOneSepFirstInternalRecord(t,r)}}this.consume=function(t,n,r){return this.consumeInternalRecord(n,t,r)},this.subrule=function(t,n,r){return this.subruleInternalRecord(n,t,r)},this.option=function(t,n){return this.optionInternalRecord(n,t)},this.or=function(t,n){return this.orInternalRecord(n,t)},this.many=function(t,n){this.manyInternalRecord(t,n)},this.atLeastOne=function(t,n){this.atLeastOneInternalRecord(t,n)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{const t=this;for(let n=0;n<10;n++){const r=n>0?n:"";delete t[`CONSUME${r}`],delete t[`SUBRULE${r}`],delete t[`OPTION${r}`],delete t[`OR${r}`],delete t[`MANY${r}`],delete t[`MANY_SEP${r}`],delete t[`AT_LEAST_ONE${r}`],delete t[`AT_LEAST_ONE_SEP${r}`]}delete t.consume,delete t.subrule,delete t.option,delete t.or,delete t.many,delete t.atLeastOne,delete t.ACTION,delete t.BACKTRACK,delete t.LA})}ACTION_RECORD(t){}BACKTRACK_RECORD(t,n){return()=>!0}LA_RECORD(t){return xa}topLevelRuleRecord(t,n){try{const r=new Hi({definition:[],name:t});return r.name=t,this.recordingProdStack.push(r),n.call(this),this.recordingProdStack.pop(),r}catch(r){if(r.KNOWN_RECORDER_ERROR!==!0)try{r.message=r.message+` This error was thrown during the "grammar recording phase" For more info see: - https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw r}throw r}}optionInternalRecord(t,n){return Bs.call(this,Qt,t,n)}atLeastOneInternalRecord(t,n){Bs.call(this,Hn,n,t)}atLeastOneSepFirstInternalRecord(t,n){Bs.call(this,Vn,n,t,Zp)}manyInternalRecord(t,n){Bs.call(this,bt,n,t)}manySepFirstInternalRecord(t,n){Bs.call(this,Nn,n,t,Zp)}orInternalRecord(t,n){return Rx.call(this,t,n)}subruleInternalRecord(t,n,r){if(Ta(n),!t||pe(t,"ruleName")===!1){const a=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(t)}> - inside top level rule: <${this.recordingProdStack[0].name}>`);throw a.KNOWN_RECORDER_ERROR=!0,a}const i=Wi(this.recordingProdStack),s=t.ruleName,o=new Zt({idx:n,nonTerminalName:s,label:r==null?void 0:r.LABEL,referencedRule:void 0});return i.definition.push(o),this.outputCst?Tx:Aa}consumeInternalRecord(t,n,r){if(Ta(n),!yp(t)){const o=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(t)}> - inside top level rule: <${this.recordingProdStack[0].name}>`);throw o.KNOWN_RECORDER_ERROR=!0,o}const i=Wi(this.recordingProdStack),s=new tt({idx:n,terminalType:t,label:r==null?void 0:r.LABEL});return i.definition.push(s),em}}function Bs(e,t,n,r=!1){Ta(n);const i=Wi(this.recordingProdStack),s=dr(t)?t:t.DEF,o=new e({definition:[],idx:n});return r&&(o.separator=t.SEP),pe(t,"MAX_LOOKAHEAD")&&(o.maxLookahead=t.MAX_LOOKAHEAD),this.recordingProdStack.push(o),s.call(this),i.definition.push(o),this.recordingProdStack.pop(),Aa}function Rx(e,t){Ta(t);const n=Wi(this.recordingProdStack),r=Le(e)===!1,i=r===!1?e:e.DEF,s=new Cn({definition:[],idx:t,ignoreAmbiguities:r&&e.IGNORE_AMBIGUITIES===!0});pe(e,"MAX_LOOKAHEAD")&&(s.maxLookahead=e.MAX_LOOKAHEAD);const o=Il(i,a=>dr(a.GATE));return s.hasPredicates=o,n.definition.push(s),me(i,a=>{const c=new Yt({definition:[]});s.definition.push(c),pe(a,"IGNORE_AMBIGUITIES")?c.ignoreAmbiguities=a.IGNORE_AMBIGUITIES:pe(a,"GATE")&&(c.ignoreAmbiguities=!0),this.recordingProdStack.push(c),a.ALT.call(this),this.recordingProdStack.pop()}),Aa}function tm(e){return e===0?"":`${e}`}function Ta(e){if(e<0||e>Yp){const t=new Error(`Invalid DSL Method idx value: <${e}> - Idx value must be a none negative value smaller than ${Yp+1}`);throw t.KNOWN_RECORDER_ERROR=!0,t}}class Ix{initPerformanceTracer(t){if(pe(t,"traceInitPerf")){const n=t.traceInitPerf,r=typeof n=="number";this.traceInitMaxIdent=r?n:1/0,this.traceInitPerf=r?n>0:n}else this.traceInitMaxIdent=0,this.traceInitPerf=_r.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(t,n){if(this.traceInitPerf===!0){this.traceInitIndent++;const r=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${t}>`);const{time:i,value:s}=ep(n),o=i>10?console.warn:console.log;return this.traceInitIndent time: ${i}ms`),this.traceInitIndent--,s}else return n()}}function Ox(e,t){t.forEach(n=>{const r=n.prototype;Object.getOwnPropertyNames(r).forEach(i=>{if(i==="constructor")return;const s=Object.getOwnPropertyDescriptor(r,i);s&&(s.get||s.set)?Object.defineProperty(e.prototype,i,s):e.prototype[i]=n.prototype[i]})})}const xa=_a(hi,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(xa);const _r=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:Rp,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),Ra=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0});var jt;(function(e){e[e.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",e[e.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",e[e.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",e[e.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",e[e.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",e[e.LEFT_RECURSION=5]="LEFT_RECURSION",e[e.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",e[e.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",e[e.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",e[e.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",e[e.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",e[e.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",e[e.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",e[e.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(jt||(jt={}));class Fs{static performSelfAnalysis(t){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let t;this.selfAnalysisDone=!0;const n=this.className;this.TRACE_INIT("toFastProps",()=>{tp(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),me(this.definedRulesNames,i=>{const o=this[i].originalGrammarAction;let a;this.TRACE_INIT(`${i} Rule`,()=>{a=this.topLevelRuleRecord(i,o)}),this.gastProductionsCache[i]=a})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT("Grammar Resolving",()=>{r=QT({rules:dt(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT("Grammar Validations",()=>{if(Ve(r)&&this.skipValidations===!1){const i=ex({rules:dt(this.gastProductionsCache),tokenTypes:dt(this.tokensMap),errMsgProvider:di,grammarName:n}),s=BT({lookaheadStrategy:this.lookaheadStrategy,rules:dt(this.gastProductionsCache),tokenTypes:dt(this.tokensMap),grammarName:n});this.definitionErrors=this.definitionErrors.concat(i,s)}}),Ve(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{const i=NA(dt(this.gastProductionsCache));this.resyncFollows=i}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var i,s;(s=(i=this.lookaheadStrategy).initialize)===null||s===void 0||s.call(i,{rules:dt(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(dt(this.gastProductionsCache))})),!Fs.DEFER_DEFINITION_ERRORS_HANDLING&&!Ve(this.definitionErrors))throw t=ce(this.definitionErrors,i=>i.message),new Error(`Parser Definition Errors detected: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw r}throw r}}optionInternalRecord(t,n){return Bs.call(this,Qt,t,n)}atLeastOneInternalRecord(t,n){Bs.call(this,Hn,n,t)}atLeastOneSepFirstInternalRecord(t,n){Bs.call(this,Vn,n,t,Zp)}manyInternalRecord(t,n){Bs.call(this,bt,n,t)}manySepFirstInternalRecord(t,n){Bs.call(this,Nn,n,t,Zp)}orInternalRecord(t,n){return Ix.call(this,t,n)}subruleInternalRecord(t,n,r){if(Ta(n),!t||pe(t,"ruleName")===!1){const a=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(t)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw a.KNOWN_RECORDER_ERROR=!0,a}const i=Wi(this.recordingProdStack),s=t.ruleName,o=new Zt({idx:n,nonTerminalName:s,label:r==null?void 0:r.LABEL,referencedRule:void 0});return i.definition.push(o),this.outputCst?xx:Aa}consumeInternalRecord(t,n,r){if(Ta(n),!yp(t)){const o=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(t)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw o.KNOWN_RECORDER_ERROR=!0,o}const i=Wi(this.recordingProdStack),s=new tt({idx:n,terminalType:t,label:r==null?void 0:r.LABEL});return i.definition.push(s),em}}function Bs(e,t,n,r=!1){Ta(n);const i=Wi(this.recordingProdStack),s=dr(t)?t:t.DEF,o=new e({definition:[],idx:n});return r&&(o.separator=t.SEP),pe(t,"MAX_LOOKAHEAD")&&(o.maxLookahead=t.MAX_LOOKAHEAD),this.recordingProdStack.push(o),s.call(this),i.definition.push(o),this.recordingProdStack.pop(),Aa}function Ix(e,t){Ta(t);const n=Wi(this.recordingProdStack),r=Le(e)===!1,i=r===!1?e:e.DEF,s=new Cn({definition:[],idx:t,ignoreAmbiguities:r&&e.IGNORE_AMBIGUITIES===!0});pe(e,"MAX_LOOKAHEAD")&&(s.maxLookahead=e.MAX_LOOKAHEAD);const o=Il(i,a=>dr(a.GATE));return s.hasPredicates=o,n.definition.push(s),me(i,a=>{const c=new Yt({definition:[]});s.definition.push(c),pe(a,"IGNORE_AMBIGUITIES")?c.ignoreAmbiguities=a.IGNORE_AMBIGUITIES:pe(a,"GATE")&&(c.ignoreAmbiguities=!0),this.recordingProdStack.push(c),a.ALT.call(this),this.recordingProdStack.pop()}),Aa}function tm(e){return e===0?"":`${e}`}function Ta(e){if(e<0||e>Yp){const t=new Error(`Invalid DSL Method idx value: <${e}> + Idx value must be a none negative value smaller than ${Yp+1}`);throw t.KNOWN_RECORDER_ERROR=!0,t}}class Ox{initPerformanceTracer(t){if(pe(t,"traceInitPerf")){const n=t.traceInitPerf,r=typeof n=="number";this.traceInitMaxIdent=r?n:1/0,this.traceInitPerf=r?n>0:n}else this.traceInitMaxIdent=0,this.traceInitPerf=_r.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(t,n){if(this.traceInitPerf===!0){this.traceInitIndent++;const r=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${t}>`);const{time:i,value:s}=ep(n),o=i>10?console.warn:console.log;return this.traceInitIndent time: ${i}ms`),this.traceInitIndent--,s}else return n()}}function Nx(e,t){t.forEach(n=>{const r=n.prototype;Object.getOwnPropertyNames(r).forEach(i=>{if(i==="constructor")return;const s=Object.getOwnPropertyDescriptor(r,i);s&&(s.get||s.set)?Object.defineProperty(e.prototype,i,s):e.prototype[i]=n.prototype[i]})})}const xa=_a(hi,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(xa);const _r=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:Rp,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),Ra=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0});var jt;(function(e){e[e.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",e[e.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",e[e.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",e[e.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",e[e.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",e[e.LEFT_RECURSION=5]="LEFT_RECURSION",e[e.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",e[e.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",e[e.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",e[e.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",e[e.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",e[e.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",e[e.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",e[e.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(jt||(jt={}));class Fs{static performSelfAnalysis(t){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let t;this.selfAnalysisDone=!0;const n=this.className;this.TRACE_INIT("toFastProps",()=>{tp(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),me(this.definedRulesNames,i=>{const o=this[i].originalGrammarAction;let a;this.TRACE_INIT(`${i} Rule`,()=>{a=this.topLevelRuleRecord(i,o)}),this.gastProductionsCache[i]=a})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT("Grammar Resolving",()=>{r=ex({rules:dt(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT("Grammar Validations",()=>{if(Ve(r)&&this.skipValidations===!1){const i=tx({rules:dt(this.gastProductionsCache),tokenTypes:dt(this.tokensMap),errMsgProvider:di,grammarName:n}),s=FT({lookaheadStrategy:this.lookaheadStrategy,rules:dt(this.gastProductionsCache),tokenTypes:dt(this.tokensMap),grammarName:n});this.definitionErrors=this.definitionErrors.concat(i,s)}}),Ve(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{const i=CA(dt(this.gastProductionsCache));this.resyncFollows=i}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var i,s;(s=(i=this.lookaheadStrategy).initialize)===null||s===void 0||s.call(i,{rules:dt(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(dt(this.gastProductionsCache))})),!Fs.DEFER_DEFINITION_ERRORS_HANDLING&&!Ve(this.definitionErrors))throw t=ce(this.definitionErrors,i=>i.message),new Error(`Parser Definition Errors detected: ${t.join(` ------------------------------- `)}`)})}constructor(t,n){this.definitionErrors=[],this.selfAnalysisDone=!1;const r=this;if(r.initErrorHandler(n),r.initLexerAdapter(),r.initLooksAhead(n),r.initRecognizerEngine(t,n),r.initRecoverable(n),r.initTreeBuilder(n),r.initContentAssist(),r.initGastRecorder(n),r.initPerformanceTracer(n),pe(n,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. Please use the flag on the relevant DSL method instead. See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES - For further details.`);this.skipValidations=pe(n,"skipValidations")?n.skipValidations:_r.skipValidations}}Fs.DEFER_DEFINITION_ERRORS_HANDLING=!1,Ox(Fs,[sx,lx,wx,vx,kx,Ex,Sx,Ax,xx,Ix]);class Nx extends Fs{constructor(t,n=_r){const r=Ct(n);r.outputCst=!0,super(t,r)}}function Cx(e){const t=new Lx,n=dt(e);return ce(n,r=>t.visitRule(r))}class Lx extends ui{visitRule(t){const n=this.visitEach(t.definition),r=Xd(n,s=>s.propertyName),i=ce(r,(s,o)=>{const a=!Il(s,l=>!l.canBeNull);let c=s[0].type;return s.length>1&&(c=ce(s,l=>l.type)),{name:o,type:c,optional:a}});return{name:t.name,properties:i}}visitAlternative(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitOption(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitRepetition(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitRepetitionMandatory(t){return this.visitEach(t.definition)}visitRepetitionMandatoryWithSeparator(t){return this.visitEach(t.definition).concat({propertyName:t.separator.name,canBeNull:!0,type:Ia(t.separator)})}visitRepetitionWithSeparator(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0}).concat({propertyName:t.separator.name,canBeNull:!0,type:Ia(t.separator)})}visitAlternation(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitTerminal(t){return[{propertyName:t.label||t.terminalType.name,canBeNull:!1,type:Ia(t)}]}visitNonTerminal(t){return[{propertyName:t.label||t.nonTerminalName,canBeNull:!1,type:Ia(t)}]}visitEachAndOverrideWith(t,n){return ce(this.visitEach(t),r=>qt({},r,n))}visitEach(t){return sn(ce(t,n=>this.visit(n)))}}function Ia(e){return e instanceof Zt?{kind:"rule",name:e.referencedRule.name}:{kind:"token"}}function Mx(e,t){let n=[];return n=n.concat('import type { CstNode, ICstVisitor, IToken } from "chevrotain";'),n=n.concat(sn(ce(e,r=>Ux(r)))),t.includeVisitorInterface&&(n=n.concat(Fx(t.visitorInterfaceName,e))),n.join(` + For further details.`);this.skipValidations=pe(n,"skipValidations")?n.skipValidations:_r.skipValidations}}Fs.DEFER_DEFINITION_ERRORS_HANDLING=!1,Nx(Fs,[ox,ux,vx,Ex,Sx,kx,Ax,Tx,Rx,Ox]);class Cx extends Fs{constructor(t,n=_r){const r=Ct(n);r.outputCst=!0,super(t,r)}}function Lx(e){const t=new Mx,n=dt(e);return ce(n,r=>t.visitRule(r))}class Mx extends ui{visitRule(t){const n=this.visitEach(t.definition),r=Xd(n,s=>s.propertyName),i=ce(r,(s,o)=>{const a=!Il(s,l=>!l.canBeNull);let c=s[0].type;return s.length>1&&(c=ce(s,l=>l.type)),{name:o,type:c,optional:a}});return{name:t.name,properties:i}}visitAlternative(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitOption(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitRepetition(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitRepetitionMandatory(t){return this.visitEach(t.definition)}visitRepetitionMandatoryWithSeparator(t){return this.visitEach(t.definition).concat({propertyName:t.separator.name,canBeNull:!0,type:Ia(t.separator)})}visitRepetitionWithSeparator(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0}).concat({propertyName:t.separator.name,canBeNull:!0,type:Ia(t.separator)})}visitAlternation(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitTerminal(t){return[{propertyName:t.label||t.terminalType.name,canBeNull:!1,type:Ia(t)}]}visitNonTerminal(t){return[{propertyName:t.label||t.nonTerminalName,canBeNull:!1,type:Ia(t)}]}visitEachAndOverrideWith(t,n){return ce(this.visitEach(t),r=>qt({},r,n))}visitEach(t){return sn(ce(t,n=>this.visit(n)))}}function Ia(e){return e instanceof Zt?{kind:"rule",name:e.referencedRule.name}:{kind:"token"}}function Ux(e,t){let n=[];return n=n.concat('import type { CstNode, ICstVisitor, IToken } from "chevrotain";'),n=n.concat(sn(ce(e,r=>Px(r)))),t.includeVisitorInterface&&(n=n.concat($x(t.visitorInterfaceName,e))),n.join(` `)+` -`}function Ux(e){const t=Px(e),n=Dx(e);return[t,n]}function Px(e){const t=rm(e.name),n=Jl(e.name);return`export interface ${t} extends CstNode { +`}function Px(e){const t=Dx(e),n=Bx(e);return[t,n]}function Dx(e){const t=rm(e.name),n=Jl(e.name);return`export interface ${t} extends CstNode { name: "${e.name}"; children: ${n}; -}`}function Dx(e){return`export type ${Jl(e.name)} = { - ${ce(e.properties,n=>Bx(n)).join(` +}`}function Bx(e){return`export type ${Jl(e.name)} = { + ${ce(e.properties,n=>Fx(n)).join(` `)} -};`}function Bx(e){const t=jx(e.type);return`${e.name}${e.optional?"?":""}: ${t}[];`}function Fx(e,t){return`export interface ${e} extends ICstVisitor { - ${ce(t,n=>$x(n)).join(` +};`}function Fx(e){const t=zx(e.type);return`${e.name}${e.optional?"?":""}: ${t}[];`}function $x(e,t){return`export interface ${e} extends ICstVisitor { + ${ce(t,n=>jx(n)).join(` `)} -}`}function $x(e){const t=Jl(e.name);return`${e.name}(children: ${t}, param?: IN): OUT;`}function jx(e){if(Le(e)){const t=ia(ce(e,r=>nm(r)));return"("+Xt(t,(r,i)=>r+" | "+i)+")"}else return nm(e)}function nm(e){return e.kind==="token"?"IToken":rm(e.name)}function rm(e){return _d(e)+"CstNode"}function Jl(e){return _d(e)+"CstChildren"}const zx={includeVisitorInterface:!0,visitorInterfaceName:"ICstNodeVisitor"};function Wx(e,t){const n=Object.assign(Object.assign({},zx),t),r=Cx(e);return Mx(r,n)}const qn=!!JSON.parse("false"),Gx=!!JSON.parse("false");JSON.parse("false");const Hx=!!JSON.parse("false");JSON.parse("false"),JSON.parse("false");const Xl=Qc(32,126).map(e=>String.fromCharCode(e));function Te(e){return on({...e,name:`token_${e.name}`})}function _n(e,t=!1){return Te(t?{name:e,pattern:new RegExp(e.toLowerCase(),"i"),longer_alt:zt,group:wt.SKIPPED}:{name:e,pattern:new RegExp(e.toLowerCase(),"i"),longer_alt:zt})}const $s=Te({name:"newline",line_breaks:!0,start_chars_hint:[` -`,"\r"],pattern:/\n|\r\n?/}),Vx=Te({name:"whitespace",pattern:/ +/,group:wt.SKIPPED}),Kx=Te({name:"whitespace",pattern:/\s+/,line_breaks:!0,group:wt.SKIPPED}),Zl=Te({name:"stat",pattern:/@.*/,start_chars_hint:["@"]}),Ki=Te({name:"command",pattern:/#/,start_chars_hint:["#"]});let im=!1;function qx(e,t,n){if(!im)return null;const[r]=n.slice(-1);if(r&&r.tokenType!==$s)return null;let i=t;for(;e[i]===" ";)i++;if("@#/?':!".includes(e[i]))return null;let s=t+1;for(;s"@#/?':!".includes(e)===!1)}),om=Te({name:"comment",pattern:/'.*/,start_chars_hint:["'"]}),am=Te({name:"label",pattern:/:[^;:\n]*/,start_chars_hint:[":"]}),cm=Te({name:"hyperlink",pattern:/!/,start_chars_hint:["!"]}),lm=Te({name:"hyperlinktext",pattern:/;[^;\n]*/,start_chars_hint:[";"]}),zt=Te({name:"stringliteral",pattern:/[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/,start_chars_hint:Xl}),um=Te({name:"stringliteraldouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),fm=Te({name:"numberliteral",pattern:/-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?/}),hm=Te({name:"iseq",pattern:/=|is|eq|equal/,longer_alt:zt}),dm=Te({name:"isnoteq",pattern:/!=|not ?eq|not ?equal/,longer_alt:zt}),pm=Te({name:"islessthan",pattern:/<|below/,longer_alt:zt}),mm=Te({name:"isgreaterthan",pattern:/>|above/,longer_alt:zt}),gm=Te({name:"islessthanorequal",pattern:/<=|below ?or ?eq|below ?or ?equal/,longer_alt:zt}),ym=Te({name:"isgreaterthanorequal",pattern:/>=|above ?or ?eq|above ?or ?equal/,longer_alt:zt}),Yl=Te({name:"or",pattern:/or/i,longer_alt:zt}),Ql=Te({name:"not",pattern:/not/i,longer_alt:zt}),eu=Te({name:"and",pattern:/and/i,longer_alt:zt}),tu=Te({name:"plus",pattern:/\+/}),nu=Te({name:"minus",pattern:/-/}),_m=Te({name:"power",pattern:/\*\*/}),bm=Te({name:"multiply",pattern:/\*/}),ru=Te({name:"divide",pattern:/\//}),wm=Te({name:"moddivide",pattern:/%/}),vm=Te({name:"floordivide",pattern:/%%/}),Em=Te({name:"query",pattern:/\?/}),km=Te({name:"lparen",pattern:/\(/,push_mode:"ignore_newlines"}),Sm=Te({name:"rparen",pattern:/\)/,pop_mode:!0}),Am=Te({name:"command_play",pattern:/(play|bgplay) .*/,start_chars_hint:Xl,longer_alt:zt}),Tm=_n("debugger"),iu=_n("if"),Oa=_n("do"),Jx=_n("to",!0),su=_n("done"),Xx=_n("then",!0),ou=_n("else"),xm=_n("while"),Rm=_n("repeat"),Im=_n("waitfor"),Om=Te({name:"foreach",pattern:/foreach|for/,longer_alt:zt}),Nm=_n("break"),Cm=_n("continue");function Lm(e){return[...e,fm,hm,dm,gm,pm,ym,mm,Yl,Ql,eu,tu,nu,_m,bm,ru,vm,wm,Em,km,Sm,um,zt]}const Mm=Lm([sm,Zl,Am,Ki,om,am,cm,lm,$s,Vx,Nm,Cm,Tm,su,Oa,ou,Om,iu,Rm,Xx,Jx,Im,xm]),Zx=new wt({defaultMode:"use_newlines",modes:{use_newlines:Mm,ignore_newlines:Lm([Kx])}},{skipValidations:!qn,ensureOptimizations:qn});function Um(e){im=!0;const t=Zx.tokenize(e||` +}`}function jx(e){const t=Jl(e.name);return`${e.name}(children: ${t}, param?: IN): OUT;`}function zx(e){if(Le(e)){const t=ia(ce(e,r=>nm(r)));return"("+Xt(t,(r,i)=>r+" | "+i)+")"}else return nm(e)}function nm(e){return e.kind==="token"?"IToken":rm(e.name)}function rm(e){return _d(e)+"CstNode"}function Jl(e){return _d(e)+"CstChildren"}const Wx={includeVisitorInterface:!0,visitorInterfaceName:"ICstNodeVisitor"};function Gx(e,t){const n=Object.assign(Object.assign({},Wx),t),r=Lx(e);return Ux(r,n)}const qn=!!JSON.parse("false"),Hx=!!JSON.parse("false");JSON.parse("false");const Vx=!!JSON.parse("false");JSON.parse("false"),JSON.parse("false");const Xl=Qc(32,126).map(e=>String.fromCharCode(e));function Te(e){return on({...e,name:`token_${e.name}`})}function _n(e,t=!1){return Te(t?{name:e,pattern:new RegExp(e.toLowerCase(),"i"),longer_alt:zt,group:wt.SKIPPED}:{name:e,pattern:new RegExp(e.toLowerCase(),"i"),longer_alt:zt})}const $s=Te({name:"newline",line_breaks:!0,start_chars_hint:[` +`,"\r"],pattern:/\n|\r\n?/}),Kx=Te({name:"whitespace",pattern:/ +/,group:wt.SKIPPED}),qx=Te({name:"whitespace",pattern:/\s+/,line_breaks:!0,group:wt.SKIPPED}),Zl=Te({name:"stat",pattern:/@.*/,start_chars_hint:["@"]}),Ki=Te({name:"command",pattern:/#/,start_chars_hint:["#"]});let im=!1;function Jx(e,t,n){if(!im)return null;const[r]=n.slice(-1);if(r&&r.tokenType!==$s)return null;let i=t;for(;e[i]===" ";)i++;if("@#/?':!".includes(e[i]))return null;let s=t+1;for(;s"@#/?':!".includes(e)===!1)}),om=Te({name:"comment",pattern:/'.*/,start_chars_hint:["'"]}),am=Te({name:"label",pattern:/:[^;:\n]*/,start_chars_hint:[":"]}),cm=Te({name:"hyperlink",pattern:/!/,start_chars_hint:["!"]}),lm=Te({name:"hyperlinktext",pattern:/;[^;\n]*/,start_chars_hint:[";"]}),zt=Te({name:"stringliteral",pattern:/[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/,start_chars_hint:Xl}),um=Te({name:"stringliteraldouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),fm=Te({name:"numberliteral",pattern:/-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?/}),hm=Te({name:"iseq",pattern:/=|is|eq|equal/,longer_alt:zt}),dm=Te({name:"isnoteq",pattern:/!=|not ?eq|not ?equal/,longer_alt:zt}),pm=Te({name:"islessthan",pattern:/<|below/,longer_alt:zt}),mm=Te({name:"isgreaterthan",pattern:/>|above/,longer_alt:zt}),gm=Te({name:"islessthanorequal",pattern:/<=|below ?or ?eq|below ?or ?equal/,longer_alt:zt}),ym=Te({name:"isgreaterthanorequal",pattern:/>=|above ?or ?eq|above ?or ?equal/,longer_alt:zt}),Yl=Te({name:"or",pattern:/or/i,longer_alt:zt}),Ql=Te({name:"not",pattern:/not/i,longer_alt:zt}),eu=Te({name:"and",pattern:/and/i,longer_alt:zt}),tu=Te({name:"plus",pattern:/\+/}),nu=Te({name:"minus",pattern:/-/}),_m=Te({name:"power",pattern:/\*\*/}),bm=Te({name:"multiply",pattern:/\*/}),ru=Te({name:"divide",pattern:/\//}),wm=Te({name:"moddivide",pattern:/%/}),vm=Te({name:"floordivide",pattern:/%%/}),Em=Te({name:"query",pattern:/\?/}),km=Te({name:"lparen",pattern:/\(/,push_mode:"ignore_newlines"}),Sm=Te({name:"rparen",pattern:/\)/,pop_mode:!0}),Am=Te({name:"command_play",pattern:/(play|bgplay) .*/,start_chars_hint:Xl,longer_alt:zt}),Tm=_n("debugger"),iu=_n("if"),Oa=_n("do"),Xx=_n("to",!0),su=_n("done"),Zx=_n("then",!0),ou=_n("else"),xm=_n("while"),Rm=_n("repeat"),Im=_n("waitfor"),Om=Te({name:"foreach",pattern:/foreach|for/,longer_alt:zt}),Nm=_n("break"),Cm=_n("continue");function Lm(e){return[...e,fm,hm,dm,gm,pm,ym,mm,Yl,Ql,eu,tu,nu,_m,bm,ru,vm,wm,Em,km,Sm,um,zt]}const Mm=Lm([sm,Zl,Am,Ki,om,am,cm,lm,$s,Kx,Nm,Cm,Tm,su,Oa,ou,Om,iu,Rm,Zx,Xx,Im,xm]),Yx=new wt({defaultMode:"use_newlines",modes:{use_newlines:Mm,ignore_newlines:Lm([qx])}},{skipValidations:!qn,ensureOptimizations:qn});function Um(e){im=!0;const t=Yx.tokenize(e||` `),[n]=(Ge(t.tokens)?t.tokens:[]).slice(-1);return n&&n.tokenType.name!=="Newline"&&t.tokens.push(_a($s,` -`,n.startOffset,n.endOffset??NaN,n.startLine??NaN,n.endLine??NaN,n.startColumn??NaN,n.endColumn??NaN)),t}function Pm(e,t=!0){const[n,...r]=e;switch(Pe(n)){default:return t?{type:fe.OBJECT,values:e}:{type:fe.CONST,values:e};case"loader":return{type:fe.LOADER,values:r};case"board":return{type:fe.BOARD,values:r};case"object":return{type:fe.OBJECT,values:r};case"terrain":return{type:fe.TERRAIN,values:r};case"charset":return{type:fe.CHARSET,values:r};case"palette":return{type:fe.PALETTE,values:r};case"rn":case"range":return{type:fe.RANGE,values:r};case"sl":case"select":return{type:fe.SELECT,values:r};case"nm":case"number":return{type:fe.NUMBER,values:r};case"tx":case"text":return{type:fe.TEXT,values:r};case"ln":case"link":return{type:fe.LINK,values:r};case"hk":case"hotkey":return{type:fe.HOTKEY,values:r};case"scroll":return{type:fe.SCROLL,values:r};case"copyit":return{type:fe.COPYIT,values:r}}}function bn(e){switch(e){case fe.LOADER:return"loader";case fe.BOARD:return"board";case fe.OBJECT:return"object";case fe.TERRAIN:return"terrain";case fe.CHARSET:return"charset";case fe.PALETTE:return"palette";case fe.CONST:return"const";case fe.RANGE:return"range";case fe.SELECT:return"select";case fe.NUMBER:return"number";case fe.TEXT:return"text";case fe.LINK:return"link";case fe.HOTKEY:return"hotkey";case fe.SCROLL:return"scroll";case fe.COPYIT:return"copyit"}}var Dm={},br={},wr={};Object.defineProperty(wr,"__esModule",{value:!0}),wr.throwUnsupportedData=wr.throwUnknownDataType=wr.getType=void 0;function Bm(e){return Object.prototype.toString.call(e)}wr.getType=Bm;function Yx(e){throw new TypeError("unsupported data type: "+Bm(e))}wr.throwUnknownDataType=Yx;function Qx(e){throw new TypeError("unsupported data type: "+e)}wr.throwUnsupportedData=Qx;var Mt={},Ut={};Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.s_to_num=Ut.int_str_to_s=Ut.num_to_s=Ut.big_int_to_s=Ut.int_to_s=Ut.s_to_big_int=Ut.s_to_int=void 0;let vr="";for(let e=0;e<10;e++){const t=String.fromCharCode(48+e);vr+=t}for(let e=0;e<26;e++){const t=String.fromCharCode(65+e);vr+=t}for(let e=0;e<26;e++){const t=String.fromCharCode(97+e);vr+=t}const qi=vr.length,au={};for(let e=0;e=0;r--){const i=e[r];let s=au[i];s*=n,t+=s,n*=qi}return t}Ut.s_to_int=cu;function Fm(e){let t=BigInt(0),n=BigInt(1);const r=BigInt(qi);for(let i=e.length-1;i>=0;i--){const s=e[i];let o=BigInt(au[s]);o*=n,t+=o,n*=r}return t}Ut.s_to_big_int=Fm;function lu(e){if(e===0)return vr[0];const t=[];for(;e!==0;){const n=e%qi,r=vr[n];t.push(r),e-=n,e/=qi}return t.reverse().join("")}Ut.int_to_s=lu;function $m(e){const t=BigInt(0),n=BigInt(qi);if(e===t)return vr[0];const r=[];for(;e!==t;){const i=e%n,s=vr[Number(i)];r.push(s),e/=n}return r.reverse().join("")}Ut.big_int_to_s=$m;function jm(e){return e.split("").reverse().join("")}function zm(e){if(e<0)return"-"+zm(-e);let[t,n]=e.toString().split(".");if(!n)return lu(e);let r;n&&([n,r]=n.split("e")),t=Na(t),n=jm(n),n=Na(n);let i=t+"."+n;if(r){switch(i+=".",r[0]){case"+":r=r.slice(1);break;case"-":i+="-",r=r.slice(1);break}r=Na(r),i+=r}return i}Ut.num_to_s=zm;function Na(e){const t=+e;return t.toString()===e&&t+1!==t&&t-1!==t?lu(t):":"+$m(BigInt(e))}Ut.int_str_to_s=Na;function uu(e){return e[0]===":"?Fm(e.substring(1)).toString():cu(e).toString()}function Wm(e){if(e[0]==="-")return-Wm(e.substr(1));let[t,n,r]=e.split(".");if(!n)return cu(t);t=uu(t),n=uu(n),n=jm(n);let i=t+"."+n;if(r){i+="e";let s=!1;r[0]==="-"&&(s=!0,r=r.slice(1)),r=uu(r),i+=s?-r:+r}return+i}Ut.s_to_num=Wm,Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.decodeStr=Mt.encodeStr=Mt.decodeBool=Mt.encodeBool=Mt.decodeKey=Mt.decodeNum=Mt.encodeNum=void 0;const fu=Ut;function eR(e){return"n|"+(0,fu.num_to_s)(e)}Mt.encodeNum=eR;function tR(e){return e=e.replace("n|",""),(0,fu.s_to_num)(e)}Mt.decodeNum=tR;function nR(e){return typeof e=="number"?e:(0,fu.s_to_int)(e)}Mt.decodeKey=nR;function rR(e){return e?"b|T":"b|F"}Mt.encodeBool=rR;function iR(e){switch(e){case"b|T":return!0;case"b|F":return!1}return!!e}Mt.decodeBool=iR;function sR(e){switch(e[0]+e[1]){case"b|":case"o|":case"n|":case"a|":case"s|":e="s|"+e}return e}Mt.encodeStr=sR;function oR(e){return e[0]+e[1]==="s|"?e.substr(2):e}Mt.decodeStr=oR;var an={},js={};Object.defineProperty(js,"__esModule",{value:!0}),js.config=void 0,js.config={sort_key:!1,error_on_nan:!1,error_on_infinite:!1},Object.defineProperty(an,"__esModule",{value:!0}),an.addValue=an.makeInMemoryMemory=an.makeInMemoryCache=an.makeInMemoryStore=an.memToValues=void 0;const hu=js,du=wr,pu=Mt,aR=Ut;function cR(e){return e.store.toArray()}an.memToValues=cR;function Gm(){const e=[];return{forEach(t){for(let n=0;n(vu(),this?this.unpack(t,n):Gs.prototype.unpack.call(Km,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<"u"?Buffer.from(t):new Uint8Array(t)),typeof n=="object"?(wn=n.end||t.length,U=n.start||0):(U=0,wn=n>-1?n:t.length),Jn=0,jr=null,Tt=null,ie=t;try{xe=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(r){throw ie=null,t instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(t&&typeof t=="object"?t.constructor.name:typeof t))}if(this instanceof Gs){if(Ke=this,this.structures)return Ie=this.structures,La(n);(!Ie||Ie.length>0)&&(Ie=[])}else Ke=Km,(!Ie||Ie.length>0)&&(Ie=[]);return La(n)}unpackMultiple(t,n){let r,i=0;try{zr=!0;let s=t.length,o=this?this.unpack(t,s):Ma.unpack(t,s);if(n){if(n(o,i,U)===!1)return;for(;Ur.slice(0)));for(let r=0,i=t.length;r=32&&(s.highByte=r-32>>5))}t.sharedLength=t.length;for(let r in n||[])if(r>=0){let i=t[r],s=n[r];s&&(i&&((t.restoreStructures||(t.restoreStructures=[]))[r]=i),t[r]=s)}return this.structures=t}decode(t,n){return this.unpack(t,n)}}function La(e){try{if(!Ke.trusted&&!zr){let n=Ie.sharedLength||0;n=32&&Zm?(t=Zm(ie,U,wn,Ke),ie=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),U=wn):t=lt(),Tt&&(U=Tt.postBundlePosition,Tt=null),zr&&(Ie.restoreStructures=null),U==wn)Ie&&Ie.restoreStructures&&Ym(),Ie=null,ie=null,Er&&(Er=null);else{if(U>wn)throw new Error("Unexpected end of MessagePack data");if(!zr){let n;try{n=JSON.stringify(t,(r,i)=>typeof i=="bigint"?`${i}n`:i).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return t}catch(t){throw Ie&&Ie.restoreStructures&&Ym(),vu(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer")||U>wn)&&(t.incomplete=!0),t}}function Ym(){for(let e in Ie.restoreStructures)Ie[e]=Ie.restoreStructures[e];Ie.restoreStructures=null}function lt(){let e=ie[U++];if(e<160)if(e<128){if(e<64)return e;{let t=Ie[e&63]||Ke.getStructures&&eg()[e&63];return t?(t.read||(t.read=yu(t,e&63)),t.read()):e}}else if(e<144)if(e-=128,Ke.mapsAsObjects){let t={};for(let n=0;n=U)return jr.slice(U-vn,(U+=t)-vn);if(Jn==0&&wn<140){let n=t<16?bu(t):rg(t);if(n!=null)return n}return _u(t)}else{let t;switch(e){case 192:return null;case 193:return Tt?(t=lt(),t>0?Tt[1].slice(Tt.position1,Tt.position1+=t):Tt[0].slice(Tt.position0,Tt.position0-=t)):Jm;case 194:return!1;case 195:return!0;case 196:if(t=ie[U++],t===void 0)throw new Error("Unexpected end of buffer");return wu(t);case 197:return t=xe.getUint16(U),U+=2,wu(t);case 198:return t=xe.getUint32(U),U+=4,wu(t);case 199:return mi(ie[U++]);case 200:return t=xe.getUint16(U),U+=2,mi(t);case 201:return t=xe.getUint32(U),U+=4,mi(t);case 202:if(t=xe.getFloat32(U),Ke.useFloat32>2){let n=Eu[(ie[U]&127)<<1|ie[U+1]>>7];return U+=4,(n*t+(t>0?.5:-.5)>>0)/n}return U+=4,t;case 203:return t=xe.getFloat64(U),U+=8,t;case 204:return ie[U++];case 205:return t=xe.getUint16(U),U+=2,t;case 206:return t=xe.getUint32(U),U+=4,t;case 207:return Ke.int64AsType==="number"?(t=xe.getUint32(U)*4294967296,t+=xe.getUint32(U+4)):Ke.int64AsType==="string"?t=xe.getBigUint64(U).toString():Ke.int64AsType==="auto"?(t=xe.getBigUint64(U),t<=BigInt(2)<=BigInt(-2)<=U?jr.slice(U-vn,(U+=t)-vn):bR(t);case 218:return t=xe.getUint16(U),U+=2,Jn>=U?jr.slice(U-vn,(U+=t)-vn):wR(t);case 219:return t=xe.getUint32(U),U+=4,Jn>=U?jr.slice(U-vn,(U+=t)-vn):vR(t);case 220:return t=xe.getUint16(U),U+=2,tg(t);case 221:return t=xe.getUint32(U),U+=4,tg(t);case 222:return t=xe.getUint16(U),U+=2,ng(t);case 223:return t=xe.getUint32(U),U+=4,ng(t);default:if(e>=224)return e-256;if(e===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+e)}}}const _R=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function yu(e,t){function n(){if(n.count++>Xm){let i=e.read=new Function("r","return function(){return "+(Ke.freezeData?"Object.freeze":"")+"({"+e.map(s=>s==="__proto__"?"__proto_:r()":_R.test(s)?s+":r()":"["+JSON.stringify(s)+"]:r()").join(",")+"})}")(lt);return e.highByte===0&&(e.read=Qm(t,e.read)),i()}let r={};for(let i=0,s=e.length;ifunction(){let n=ie[U++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=Ie[r]||eg()[r];if(!i)throw new Error("Record id is not defined for "+r);return i.read||(i.read=yu(i,e)),i.read()};function eg(){let e=ug(()=>(ie=null,Ke.getStructures()));return Ie=Ke._mergeStructures(e,Ie)}var _u=Hs,bR=Hs,wR=Hs,vR=Hs;function Hs(e){let t;if(e<16&&(t=bu(e)))return t;if(e>64&&gu)return gu.decode(ie.subarray(U,U+=e));const n=U+e,r=[];for(t="";U65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c)}else r.push(i);r.length>=4096&&(t+=xt.apply(String,r),r.length=0)}return r.length>0&&(t+=xt.apply(String,r)),t}function tg(e){let t=new Array(e);for(let n=0;n0){U=t;return}n[r]=i}return xt.apply(String,n)}function bu(e){if(e<4)if(e<2){if(e===0)return"";{let t=ie[U++];if((t&128)>1){U-=1;return}return xt(t)}}else{let t=ie[U++],n=ie[U++];if((t&128)>0||(n&128)>0){U-=2;return}if(e<3)return xt(t,n);let r=ie[U++];if((r&128)>0){U-=3;return}return xt(t,n,r)}else{let t=ie[U++],n=ie[U++],r=ie[U++],i=ie[U++];if((t&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){U-=4;return}if(e<6){if(e===4)return xt(t,n,r,i);{let s=ie[U++];if((s&128)>0){U-=5;return}return xt(t,n,r,i,s)}}else if(e<8){let s=ie[U++],o=ie[U++];if((s&128)>0||(o&128)>0){U-=6;return}if(e<7)return xt(t,n,r,i,s,o);let a=ie[U++];if((a&128)>0){U-=7;return}return xt(t,n,r,i,s,o,a)}else{let s=ie[U++],o=ie[U++],a=ie[U++],c=ie[U++];if((s&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){U-=8;return}if(e<10){if(e===8)return xt(t,n,r,i,s,o,a,c);{let l=ie[U++];if((l&128)>0){U-=9;return}return xt(t,n,r,i,s,o,a,c,l)}}else if(e<12){let l=ie[U++],u=ie[U++];if((l&128)>0||(u&128)>0){U-=10;return}if(e<11)return xt(t,n,r,i,s,o,a,c,l,u);let f=ie[U++];if((f&128)>0){U-=11;return}return xt(t,n,r,i,s,o,a,c,l,u,f)}else{let l=ie[U++],u=ie[U++],f=ie[U++],d=ie[U++];if((l&128)>0||(u&128)>0||(f&128)>0||(d&128)>0){U-=12;return}if(e<14){if(e===12)return xt(t,n,r,i,s,o,a,c,l,u,f,d);{let h=ie[U++];if((h&128)>0){U-=13;return}return xt(t,n,r,i,s,o,a,c,l,u,f,d,h)}}else{let h=ie[U++],p=ie[U++];if((h&128)>0||(p&128)>0){U-=14;return}if(e<15)return xt(t,n,r,i,s,o,a,c,l,u,f,d,h,p);let m=ie[U++];if((m&128)>0){U-=15;return}return xt(t,n,r,i,s,o,a,c,l,u,f,d,h,p,m)}}}}}function ig(){let e=ie[U++],t;if(e<192)t=e-160;else switch(e){case 217:t=ie[U++];break;case 218:t=xe.getUint16(U),U+=2;break;case 219:t=xe.getUint32(U),U+=4;break;default:throw new Error("Expected string")}return Hs(t)}function wu(e){return Ke.copyBuffers?Uint8Array.prototype.slice.call(ie,U,U+=e):ie.subarray(U,U+=e)}function mi(e){let t=ie[U++];if(en[t]){let n;return en[t](ie.subarray(U,n=U+=e),r=>{U=r;try{return lt()}finally{U=n}})}else throw new Error("Unknown extension type "+t)}var sg=new Array(4096);function og(){let e=ie[U++];if(e>=160&&e<192){if(e=e-160,Jn>=U)return jr.slice(U-vn,(U+=e)-vn);if(!(Jn==0&&wn<180))return _u(e)}else return U--,ag(lt());let t=(e<<5^(e>1?xe.getUint16(U):e>0?ie[U]:0))&4095,n=sg[t],r=U,i=U+e-3,s,o=0;if(n&&n.bytes==e){for(;r{let n=lt().map(ag),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=Ie[e];return i&&(i.isShared||zr)&&((Ie.restoreStructures||(Ie.restoreStructures=[]))[e]=i),Ie[e]=n,n.read=yu(n,r),n.read()};en[0]=()=>{},en[0].noBuffer=!0,en[66]=e=>{let t=e.length,n=BigInt(e[0]&128?e[0]-256:e[0]);for(let r=1;r{let e=lt();return(ER[e[0]]||Error)(e[1],{cause:e[2]})},en[105]=e=>{if(Ke.structuredClone===!1)throw new Error("Structured clone extension is disabled");let t=xe.getUint32(U-4);Er||(Er=new Map);let n=ie[U],r;n>=144&&n<160||n==220||n==221?r=[]:r={};let i={target:r};Er.set(t,i);let s=lt();return i.used?Object.assign(r,s):(i.target=s,s)},en[112]=e=>{if(Ke.structuredClone===!1)throw new Error("Structured clone extension is disabled");let t=xe.getUint32(U-4),n=Er.get(t);return n.used=!0,n.target},en[115]=()=>new Set(lt());const lg=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(e=>e+"Array");let kR=typeof globalThis=="object"?globalThis:window;en[116]=e=>{let t=e[0],n=lg[t];if(!n){if(t===16){let r=new ArrayBuffer(e.length-1);return new Uint8Array(r).set(e.subarray(1)),r}throw new Error("Could not find typed array for code "+t)}return new kR[n](Uint8Array.prototype.slice.call(e,1).buffer)},en[120]=()=>{let e=lt();return new RegExp(e[0],e[1])};const SR=[];en[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=U;return U+=t-e.length,Tt=SR,Tt=[ig(),ig()],Tt.position0=0,Tt.position1=0,Tt.postBundlePosition=U,U=n,lt()},en[255]=e=>e.length==4?new Date((e[0]*16777216+(e[1]<<16)+(e[2]<<8)+e[3])*1e3):e.length==8?new Date(((e[0]<<22)+(e[1]<<14)+(e[2]<<6)+(e[3]>>2))/1e6+((e[3]&3)*4294967296+e[4]*16777216+(e[5]<<16)+(e[6]<<8)+e[7])*1e3):e.length==12?new Date(((e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3])/1e6+((e[4]&128?-281474976710656:0)+e[6]*1099511627776+e[7]*4294967296+e[8]*16777216+(e[9]<<16)+(e[10]<<8)+e[11])*1e3):new Date("invalid");function ug(e){let t=wn,n=U,r=vn,i=Jn,s=jr,o=Er,a=Tt,c=new Uint8Array(ie.slice(0,wn)),l=Ie,u=Ie.slice(0,Ie.length),f=Ke,d=zr,h=e();return wn=t,U=n,vn=r,Jn=i,jr=s,Er=o,Tt=a,ie=c,zr=d,Ie=l,Ie.splice(0,Ie.length,...u),Ke=f,xe=new DataView(ie.buffer,ie.byteOffset,ie.byteLength),h}function vu(){ie=null,Er=null,Ie=null}const Eu=new Array(147);for(let e=0;e<256;e++)Eu[e]=+("1e"+Math.floor(45.15-e*.30103));var Ma=new Gs({useRecords:!1});const AR=Ma.unpack;Ma.unpackMultiple,Ma.unpack;let TR=new Float32Array(1);new Uint8Array(TR.buffer,0,4);let Ua;try{Ua=new TextEncoder}catch{}let ku,fg;const Pa=typeof Buffer<"u",Da=Pa?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,hg=Pa?Buffer:Uint8Array,dg=Pa?4294967296:2144337920;let j,Vs,qe,P=0,Wt,nt=null,xR;const RR=21760,IR=/[\u0080-\uFFFF]/,Xi=Symbol("record-id");class OR extends Gs{constructor(t){super(t),this.offset=0;let n,r,i,s,o=hg.prototype.utf8Write?function(E,g){return j.utf8Write(E,g,j.byteLength-g)}:Ua&&Ua.encodeInto?function(E,g){return Ua.encodeInto(E,j.subarray(g)).written}:!1,a=this;t||(t={});let c=t&&t.sequential,l=t.structures||t.saveStructures,u=t.maxSharedStructures;if(u==null&&(u=l?32:0),u>8160)throw new Error("Maximum maxSharedStructure is 8160");t.structuredClone&&t.moreTypes==null&&(this.moreTypes=!0);let f=t.maxOwnStructures;f==null&&(f=l?32:64),!this.structures&&t.useRecords!=!1&&(this.structures=[]);let d=u>32||f+u>64,h=u+64,p=u+f+64;if(p>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let m=[],b=0,_=0;this.pack=this.encode=function(E,g){if(j||(j=new Da(8192),qe=j.dataView||(j.dataView=new DataView(j.buffer,0,8192)),P=0),Wt=j.length-10,Wt-P<2048?(j=new Da(j.length),qe=j.dataView||(j.dataView=new DataView(j.buffer,0,j.length)),Wt=j.length-10,P=0):P=P+7&2147483640,n=P,g&DR&&(P+=g&255),s=a.structuredClone?new Map:null,a.bundleStrings&&typeof E!="string"?(nt=[],nt.size=1/0):nt=null,i=a.structures,i){i.uninitialized&&(i=a._mergeStructures(a.getStructures()));let W=i.sharedLength||0;if(W>u)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let B=0;B$.offset>F.offset?1:-1),Z=B.length,H=-1;for(;W&&Z>0;){let $=B[--Z].offset+n;$W.position+n?H>=0&&(H+=6):(H>=0&&(qe.setUint32(W.position+n,qe.getUint32(W.position+n)+H),H=-1),W=W.previous,Z++)}H>=0&&W&&qe.setUint32(W.position+n,qe.getUint32(W.position+n)+H),P+=B.length*6,P>Wt&&x(P),a.offset=P;let Y=CR(j.subarray(n,P),B);return s=null,Y}return a.offset=P,g&UR?(j.start=n,j.end=P,j):j.subarray(n,P)}catch(W){throw N=W,W}finally{if(i&&(w(),r&&a.saveStructures)){let W=i.sharedLength||0,B=j.subarray(n,P),Z=LR(i,a);if(!N)return a.saveStructures(Z,Z.isCompatible)===!1?a.pack(E,g):(a.lastNamedStructuresLength=W,j.length>1073741824&&(j=null),B)}j.length>1073741824&&(j=null),g&PR&&(P=n)}};const w=()=>{_<10&&_++;let E=i.sharedLength||0;if(i.length>E&&!c&&(i.length=E),b>1e4)i.transitions=null,_=0,b=0,m.length>0&&(m=[]);else if(m.length>0&&!c){for(let g=0,N=m.length;g{var g=E.length;g<16?j[P++]=144|g:g<65536?(j[P++]=220,j[P++]=g>>8,j[P++]=g&255):(j[P++]=221,qe.setUint32(P,g),P+=4);for(let N=0;N{P>Wt&&(j=x(P));var g=typeof E,N;if(g==="string"){let W=E.length;if(nt&&W>=4&&W<4096){if((nt.size+=W)>RR){let Y,$=(nt[0]?nt[0].length*3+nt[1].length:0)+10;P+$>Wt&&(j=x(P+$));let F;nt.position?(F=nt,j[P]=200,P+=3,j[P++]=98,Y=P-n,P+=4,gg(n,S,0),qe.setUint16(Y+n-3,P-n-Y)):(j[P++]=214,j[P++]=98,Y=P-n,P+=4),nt=["",""],nt.previous=F,nt.size=0,nt.position=Y}let H=IR.test(E);nt[H?0:1]+=E,j[P++]=193,S(H?-W:W);return}let B;W<32?B=1:W<256?B=2:W<65536?B=3:B=5;let Z=W*3;if(P+Z>Wt&&(j=x(P+Z)),W<64||!o){let H,Y,$,F=P+B;for(H=0;H>6|192,j[F++]=Y&63|128):(Y&64512)===55296&&(($=E.charCodeAt(H+1))&64512)===56320?(Y=65536+((Y&1023)<<10)+($&1023),H++,j[F++]=Y>>18|240,j[F++]=Y>>12&63|128,j[F++]=Y>>6&63|128,j[F++]=Y&63|128):(j[F++]=Y>>12|224,j[F++]=Y>>6&63|128,j[F++]=Y&63|128);N=F-P-B}else N=o(E,P+B);N<32?j[P++]=160|N:N<256?(B<2&&j.copyWithin(P+2,P+1,P+1+N),j[P++]=217,j[P++]=N):N<65536?(B<3&&j.copyWithin(P+3,P+2,P+2+N),j[P++]=218,j[P++]=N>>8,j[P++]=N&255):(B<5&&j.copyWithin(P+5,P+3,P+3+N),j[P++]=219,qe.setUint32(P,N),P+=4),P+=N}else if(g==="number")if(E>>>0===E)E<32||E<128&&this.useRecords===!1||E<64&&!this.randomAccessStructure?j[P++]=E:E<256?(j[P++]=204,j[P++]=E):E<65536?(j[P++]=205,j[P++]=E>>8,j[P++]=E&255):(j[P++]=206,qe.setUint32(P,E),P+=4);else if(E>>0===E)E>=-32?j[P++]=256+E:E>=-128?(j[P++]=208,j[P++]=E+256):E>=-32768?(j[P++]=209,qe.setInt16(P,E),P+=2):(j[P++]=210,qe.setInt32(P,E),P+=4);else{let W;if((W=this.useFloat32)>0&&E<4294967296&&E>=-2147483648){j[P++]=202,qe.setFloat32(P,E);let B;if(W<4||(B=E*Eu[(j[P]&127)<<1|j[P+1]>>7])>>0===B){P+=4;return}else P--}j[P++]=203,qe.setFloat64(P,E),P+=8}else if(g==="object"||g==="function")if(!E)j[P++]=192;else{if(s){let B=s.get(E);if(B){if(!B.id){let Z=s.idsToInsert||(s.idsToInsert=[]);B.id=Z.push(B)}j[P++]=214,j[P++]=112,qe.setUint32(P,B.id),P+=4;return}else s.set(E,{offset:P-n})}let W=E.constructor;if(W===Object)M(E);else if(W===Array)v(E);else if(W===Map)if(this.mapAsEmptyObject)j[P++]=128;else{N=E.size,N<16?j[P++]=128|N:N<65536?(j[P++]=222,j[P++]=N>>8,j[P++]=N&255):(j[P++]=223,qe.setUint32(P,N),P+=4);for(let[B,Z]of E)S(B),S(Z)}else{for(let B=0,Z=ku.length;B(j=$,$=null,P+=ee,P>Wt&&x(P),{target:j,targetView:qe,position:P-ee}),S)}finally{$&&(j=$,qe=F,P=ue,Wt=j.length-10)}Q&&(Q.length+P>Wt&&x(Q.length+P),P=NR(Q,j,P,Y.type));return}}if(Array.isArray(E))v(E);else{if(E.toJSON){const B=E.toJSON();if(B!==E)return S(B)}if(g==="function")return S(this.writeFunction&&this.writeFunction(E));M(E)}}}else if(g==="boolean")j[P++]=E?195:194;else if(g==="bigint"){if(E=-(BigInt(1)<0)j[P++]=207,qe.setBigUint64(P,E);else if(this.largeBigIntToFloat)j[P++]=203,qe.setFloat64(P,Number(E));else{if(this.largeBigIntToString)return S(E.toString());if(this.useBigIntExtension&&E-(BigInt(2)**BigInt(1023))){j[P++]=199,P++,j[P++]=66;let W=[],B;do{let Z=E&BigInt(255);B=(Z&BigInt(128))===(E>=BigInt(8)}while(!((E===BigInt(0)||E===BigInt(-1))&&B));j[P-2]=W.length;for(let Z=W.length;Z>0;)j[P++]=Number(W[--Z]);return}else throw new RangeError(E+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}P+=8}else if(g==="undefined")this.encodeUndefinedAsNil?j[P++]=192:(j[P++]=212,j[P++]=0,j[P++]=0);else throw new Error("Unknown type: "+g)},L=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?E=>{let g;if(this.skipValues){g=[];for(let B in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(B))&&!this.skipValues.includes(E[B])&&g.push(B)}else g=Object.keys(E);let N=g.length;N<16?j[P++]=128|N:N<65536?(j[P++]=222,j[P++]=N>>8,j[P++]=N&255):(j[P++]=223,qe.setUint32(P,N),P+=4);let W;if(this.coercibleKeyAsNumber)for(let B=0;B{j[P++]=222;let g=P-n;P+=2;let N=0;for(let W in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(W))&&(S(W),S(E[W]),N++);if(N>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');j[g+++n]=N>>8,j[g+n]=N&255},I=this.useRecords===!1?L:t.progressiveRecords&&!d?E=>{let g,N=i.transitions||(i.transitions=Object.create(null)),W=P++-n,B;for(let Z in E)if(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(Z)){if(g=N[Z],g)N=g;else{let H=Object.keys(E),Y=N;N=i.transitions;let $=0;for(let F=0,ue=H.length;F{let g,N=i.transitions||(i.transitions=Object.create(null)),W=0;for(let Z in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(Z))&&(g=N[Z],g||(g=N[Z]=Object.create(null),W++),N=g);let B=N[Xi];B?B>=96&&d?(j[P++]=((B-=96)&31)+96,j[P++]=B>>5):j[P++]=B:V(N,N.__keys__||Object.keys(E),W);for(let Z in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(Z))&&S(E[Z])},T=typeof this.useRecords=="function"&&this.useRecords,M=T?E=>{T(E)?I(E):L(E)}:I,x=E=>{let g;if(E>16777216){if(E-n>dg)throw new Error("Packed buffer would be larger than maximum buffer size");g=Math.min(dg,Math.round(Math.max((E-n)*(E>67108864?1.25:2),4194304)/4096)*4096)}else g=(Math.max(E-n<<2,j.length-1)>>12)+1<<12;let N=new Da(g);return qe=N.dataView||(N.dataView=new DataView(N.buffer,0,g)),E=Math.min(E,j.length),j.copy?j.copy(N,0,n,E):N.set(j.slice(n,E)),P-=n,n=0,Wt=N.length-10,j=N},V=(E,g,N)=>{let W=i.nextId;W||(W=64),W=p&&(W=h),i.nextId=W+1);let B=g.highByte=W>=96&&d?W-96>>5:-1;E[Xi]=W,E.__keys__=g,i[W-64]=g,W=0?(j[P++]=(W&31)+96,j[P++]=B):j[P++]=W):(B>=0?(j[P++]=213,j[P++]=114,j[P++]=(W&31)+96,j[P++]=B):(j[P++]=212,j[P++]=114,j[P++]=W),N&&(b+=_*N),m.length>=f&&(m.shift()[Xi]=0),m.push(E),S(g))},oe=(E,g,N,W)=>{let B=j,Z=P,H=Wt,Y=n;j=Vs,P=0,n=0,j||(Vs=j=new Da(8192)),Wt=j.length-10,V(E,g,W),Vs=j;let $=P;if(j=B,P=Z,Wt=H,n=Y,$>1){let F=P+$-1;F>Wt&&x(F);let ue=N+n;j.copyWithin(ue+$,ue+1,P),j.set(Vs.slice(0,$),ue),P=F}else j[N+n]=Vs[0]},O=E=>{let g=xR(E,j,n,P,i,x,(N,W,B)=>{if(B)return r=!0;P=W;let Z=j;return S(N),w(),Z!==j?{position:P,targetView:qe,target:j}:P},this);if(g===0)return M(E);P=g}}useBuffer(t){j=t,j.dataView||(j.dataView=new DataView(j.buffer,j.byteOffset,j.byteLength)),P=0}set position(t){P=t}get position(){return P}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}}fg=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,qm],ku=[{pack(e,t,n){let r=e.getTime()/1e3;if((this.useTimestamp32||e.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:i,targetView:s,position:o}=t(6);i[o++]=214,i[o++]=255,s.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:i,targetView:s,position:o}=t(10);i[o++]=215,i[o++]=255,s.setUint32(o,e.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),s.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return t(0),n(this.onInvalidDate());let{target:i,targetView:s,position:o}=t(3);i[o++]=212,i[o++]=255,i[o++]=255}else{let{target:i,targetView:s,position:o}=t(15);i[o++]=199,i[o++]=12,i[o++]=255,s.setUint32(o,e.getMilliseconds()*1e6),s.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(e,t,n){if(this.setAsEmptyObject)return t(0),n({});let r=Array.from(e),{target:i,position:s}=t(this.moreTypes?3:0);this.moreTypes&&(i[s++]=212,i[s++]=115,i[s++]=0),n(r)}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),n([e.name,e.message,e.cause])}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),n([e.source,e.flags])}},{pack(e,t){this.moreTypes?pg(e,16,t):mg(Pa?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==hg&&this.moreTypes?pg(e,lg.indexOf(n.name),t):mg(e,t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function pg(e,t,n,r){let i=e.byteLength;if(i+1<256){var{target:s,position:o}=n(4+i);s[o++]=199,s[o++]=i+1}else if(i+1<65536){var{target:s,position:o}=n(5+i);s[o++]=200,s[o++]=i+1>>8,s[o++]=i+1&255}else{var{target:s,position:o,targetView:a}=n(7+i);s[o++]=201,a.setUint32(o,i+1),o+=4}s[o++]=116,s[o++]=t,e.buffer||(e=new Uint8Array(e)),s.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o)}function mg(e,t){let n=e.byteLength;var r,i;if(n<256){var{target:r,position:i}=t(n+2);r[i++]=196,r[i++]=n}else if(n<65536){var{target:r,position:i}=t(n+3);r[i++]=197,r[i++]=n>>8,r[i++]=n&255}else{var{target:r,position:i,targetView:s}=t(n+5);r[i++]=198,s.setUint32(i,n),i+=4}r.set(e,i)}function NR(e,t,n,r){let i=e.length;switch(i){case 1:t[n++]=212;break;case 2:t[n++]=213;break;case 4:t[n++]=214;break;case 8:t[n++]=215;break;case 16:t[n++]=216;break;default:i<256?(t[n++]=199,t[n++]=i):i<65536?(t[n++]=200,t[n++]=i>>8,t[n++]=i&255):(t[n++]=201,t[n++]=i>>24,t[n++]=i>>16&255,t[n++]=i>>8&255,t[n++]=i&255)}return t[n++]=r,t.set(e,n),n+=i,n}function CR(e,t){let n,r=t.length*6,i=e.length-r;for(;n=t.pop();){let s=n.offset,o=n.id;e.copyWithin(s+r,s,i),r-=6;let a=s+r;e[a++]=214,e[a++]=105,e[a++]=o>>24,e[a++]=o>>16&255,e[a++]=o>>8&255,e[a++]=o&255,i=s}return e}function gg(e,t,n){if(nt.length>0){qe.setUint32(nt.position+e,P+n-nt.position-e),nt.stringsPosition=P-e;let r=nt;nt=null,t(r[0]),t(r[1])}}function LR(e,t){return e.isCompatible=n=>{let r=!n||(t.lastNamedStructuresLength||0)===n.length;return r||t._mergeStructures(n),r},e}let yg=new OR({useRecords:!1});const MR=yg.pack;yg.pack;const UR=512,PR=1024,DR=2048;function gi(){return null}function Ks(e,t,n={}){if(!k(e))return;const r=[],i=Object.keys(e);for(let s=0;s(e[e.kind=0]="kind",e[e.id=1]="id",e[e.x=2]="x",e[e.y=3]="y",e[e.lx=4]="lx",e[e.ly=5]="ly",e[e.code=6]="code",e[e.name=7]="name",e[e.char=8]="char",e[e.color=9]="color",e[e.bg=10]="bg",e[e.player=11]="player",e[e.bucket=12]="bucket",e[e.pushable=13]="pushable",e[e.collision=14]="collision",e[e.destructible=15]="destructible",e[e.tickertext=16]="tickertext",e[e.tickertime=17]="tickertime",e[e.p1=18]="p1",e[e.p2=19]="p2",e[e.p3=20]="p3",e[e.cycle=21]="cycle",e[e.stepx=22]="stepx",e[e.stepy=23]="stepy",e[e.sender=24]="sender",e[e.arg=25]="arg",e[e.headless=26]="headless",e[e.removed=27]="removed",e))(Su||{});function Ba(e){return Ks(e,Su,{category:gi,kinddata:gi})}function Fa(e){return qs(e,Su)}var Au=(e=>(e[e.width=0]="width",e[e.height=1]="height",e[e.bits=2]="bits",e))(Au||{});function bg(e){return Ks(e,Au)}function wg(e){return qs(e,Au)}function vg(e,t){return{id:ht(),code:e,...t}}var Tu=(e=>(e[e.id=0]="id",e[e.code=1]="code",e[e.board=2]="board",e[e.object=3]="object",e[e.terrain=4]="terrain",e[e.charset=5]="charset",e[e.palette=6]="palette",e[e.eighttrack=7]="eighttrack",e))(Tu||{});function $R(e){return Ks(e,Tu,{board:uI,object:Ba,terrain:Ba,charset:bg,palette:bg,stats:gi})}function jR(e){return qs(e,Tu,{board:fI,object:Fa,terrain:Fa,charset:wg,palette:wg})}function zR(e){const t={...Js(e)};return Object.keys(t).forEach(n=>{switch(n){case"type":case"name":delete t[n];break}}),t}function WR(e){return k(e)?(e.stats=void 0,Js(e)):{}}function Js(e){var r;if(!k(e))return{};if(k((r=e.stats)==null?void 0:r.type))return e.stats;e.stats={};const t=Um(e.code);let n=!0;for(let i=0;i(e[e.id=0]="id",e[e.name=1]="name",e[e.timestamp=2]="timestamp",e[e.activelist=3]="activelist",e[e.pages=4]="pages",e[e.flags=5]="flags",e))(Ru||{});function GR(e){return Ks(e,Ru,{pages:t=>t.map($R)})}function HR(e){return qs(e,Ru,{pages:t=>t.map(jR)})}function yi(e,t){if(!k(e))return;const n=Pe(t);return e.pages.find(i=>i.id===t||n===Xn(i))}function Iu(e,t,n){if(!k(e))return;const r=Pe(n);return e.pages.find(s=>Xs(s)===t&&(s.id===n||r===Xn(s)))}function VR(e,t){return k(e)?e.pages.filter(n=>Xs(n)===t):[]}function Ag(e,t){if(!k(e)||!k(t))return!1;const n=yi(e,t.id);return k(n)?!1:(e.pages.push(t),!0)}function KR(e,t){const n=yi(e,t);if(k(e)&&k(n)){const r=Pe(t);return e.pages=e.pages.filter(i=>i.id!==t&&r!==Xn(i)),n}}function Ln(e,t){if(k(t)&&k(t.kind))return k(t.kinddata)||(t.kinddata=k(t.id)?$a(e,t.kind):xg(e,t.kind)),t.kinddata}function Tg(e,t){const n=Ln(e,t);return{char:(t==null?void 0:t.char)??(n==null?void 0:n.char)??1,color:(t==null?void 0:t.color)??(n==null?void 0:n.color)??be.WHITE,bg:(t==null?void 0:t.bg)??(n==null?void 0:n.bg)??be.ONBORROW}}function $a(e,t){const n=t??"",r=Iu(e,Ae.OBJECT,n);if(k(r)){const i=xu(r);return{...ys(i),name:n,code:r.code}}}function xg(e,t){const n=t??"",r=Iu(e,Ae.TERRAIN,n);if(k(r)){const i=xu(r);return{...ys(i),name:n,code:r.code}}}function Zi(e,t){const n=yi(e,t);return xu(n)}function Ys(e,t){return e?(e.flags[t]=e.flags[t]??{},e.flags[t]):{}}function Ou(e,t){e&&delete e.flags[t]}function Rg(e,t,n){const r=Ys(e,t);return r==null?void 0:r[n]}function qR(e,t,n,r){const i=Ys(e,t);return i&&(i[n]=r),r}function ja(e,t){const n=Rg(e,t,"board");return Zi(e,Ce(n)?n:"")}function Nu(e,t,n){if(!k(e))return;qR(e,t,"board",n);const r=Zi(e,n);k(r)?e.activelist.includes(t)||e.activelist.push(t):e.activelist=e.activelist.filter(i=>i!==t)}function JR(e){const n=((e==null?void 0:e.activelist)??[]).map(r=>{const i=Rg(e,r,"board");return Ce(i)?i:""});return yw(n)}function Ig(e){return JR(e).map(n=>Zi(e,n)).filter(k)}function XR(e,t,n,r){const i=Qi(t,(n==null?void 0:n.id)??"");if(!k(e)||!k(t)||!k(i)||!k(i.x)||!k(i.y)||!k(t.lookup)||r.x<0||r.x>=ze||r.y<0||r.y>=rn||i.x-r.x===0&&i.y-r.y===0)return!0;const s=r.x+r.y*ze,o=Ln(e,i),a=i.collision??(o==null?void 0:o.collision),c=Qi(t,t.lookup[s]??"");if(k(c))return!0;const l=t.terrain[s];if(k(l)){const u=Ln(e,l),f=l.collision??(u==null?void 0:u.collision);if(Nh(a,f))return!0}return!1}function ZR(e,t,n,r){const i=Qi(t,(n==null?void 0:n.id)??"");if(!k(e)||!k(t)||!k(i)||!k(i.x)||!k(i.y)||!k(t.lookup)||r.x<0||r.x>=ze||r.y<0||r.y>=rn)return{kind:"edge",collision:Ye.ISSOLID,x:r.x,y:r.y};if(i.x-r.x===0&&i.y-r.y===0)return;const s=i.x+i.y*ze,o=r.x+r.y*ze,a=Ln(e,i),c=i.collision??(a==null?void 0:a.collision),l=Qi(t,t.lookup[o]??"");if(k(l))return{...l};const u=t.terrain[o];if(k(u)){const f=Ln(e,u),d=u.collision??(f==null?void 0:f.collision);if(Nh(c,d))return{...u,x:r.x,y:r.y}}i.x=r.x,i.y=r.y,k(i.removed)||(t.lookup[s]=void 0,t.lookup[o]=i.id??"")}function Yi(e,t){const n=Ln(e,t);return k(t==null?void 0:t.id)&&k(t.x)&&k(t.y)?Pe(t.name??(n==null?void 0:n.name)??"object"):Pe((t==null?void 0:t.name)??(n==null?void 0:n.name)??"terrain")}function Cu(e,t,n,r){if(!k(e)||!k(t)||!k(t.named)||!k(n))return;const i=Yi(e,n);t.named[i]||(t.named[i]=new Set),t.named[i].add((n==null?void 0:n.id)??r??"")}function YR(e,t,n){if(!(!k(e)||!k(t)||!k(t.lookup)||!k(n==null?void 0:n.id))&&!k(n.removed)){const r=n.x??0,i=n.y??0;t.lookup[r+i*ze]=n.id}}function za(e,t){if(!k(e)||!k(t)||k(t.lookup)&&k(t.named))return;const n=new Array(ze*rn).fill(void 0),r={},i=Object.values(t.objects);for(let a=0;a=ze&&(s=0,++o)}t.lookup=n,t.named=r}function Lu(e,t,n){return Yi(e,t)!=="player"&&k(t)?(t.removed=n,!0):!1}function Qs(e,t,n){var r;if(k(e)&&k(t)&&k(n==null?void 0:n.id)){if(k(t.lookup)&&k(n.x)&&k(n.y)){const s=n.x+n.y*ze;t.lookup[s]===n.id&&t.lookup.splice(s,1)}const i=Yi(e,n);k((r=t.named)==null?void 0:r[i])&&k(n.id)&&t.named[i].delete(n.id)}}function QR(e,t,n){const r=[];if(!k(e)||!k(t))return r;const i=Object.values(t.objects);for(let s=0;sUh*5&&(r.push(o.id),zg(t,o.id))}return r}function eI(e,t,n){const r=[];if(!k(e)||!k(t))return r;t.lookup=void 0,za(e,t);const i=Object.values(t.objects);for(let o=0;obe.WHITE&&ebe[t]).find(t=>k(t)&&tbe[t]).find(t=>k(t)&&t>=be.ONBLACK)}function Fg(e){if(En(e))return e;if(Dg(e))return[e];const t=Bg(e);if(k(t))return[t]}function $g(e){const t=C.words[e],n=Fg(t);if(En(n))return[n,e+1];const[r,i]=Gt(e),s=Fg(r);return En(s)?[s,i]:[void 0,e]}function Ha(e){const t=[];let n=e;const[r,i]=$g(e);if(En(r)&&(t.push(...r),n=i),En(t)&&!Pg(t)){const[s,o]=$g(i);Pg(s)&&(n=o)}return t.length?[t,n]:[void 0,e]}function aI(e){const t={};return e.every(n=>{const r=be[n];k(r)&&(r{})}function lI(e=cw){const t={terrain:cI(),objects:{},id:""};return e(t)}var Pu=(e=>(e[e.terrain=0]="terrain",e[e.objects=1]="objects",e[e.isdark=2]="isdark",e[e.over=3]="over",e[e.under=4]="under",e[e.exitnorth=5]="exitnorth",e[e.exitsouth=6]="exitsouth",e[e.exitwest=7]="exitwest",e[e.exiteast=8]="exiteast",e[e.timelimit=9]="timelimit",e[e.restartonzap=10]="restartonzap",e[e.maxplayershots=11]="maxplayershots",e))(Pu||{});function uI(e){return Ks(e,Pu,{terrain:t=>t.map(Ba),objects:t=>Object.values(t).map(Ba),id:gi,named:gi,lookup:gi,codepage:gi})}function fI(e){return qs(e,Pu,{terrain:t=>t.map(Fa),objects:t=>{const n={};for(let r=0;r=ze||t.y<0||t.y>=rn)return;const n={...t},r=t.x+t.y*ze;return e.terrain[r]=n,t}function mI(e,t){if(!k(e)||!k(t))return;const n={...t,id:t.id??ht()};return e.objects[n.id]=n,n}function jg(e,t,n){return pI(e,{...t,kind:n})}function Bu(e,t,n,r){return mI(e,{...t,id:r??void 0,kind:n})}function Qi(e,t){if(e)return e.objects[t]}function Fu(e,t,n,r,i){if(!k(e)||!k(t))return{x:0,y:0};const s={x:t.x??0,y:t.y??0},o={x:t.lx??s.x,y:t.ly??s.y},a=Bi(o,s),c=ze-1,l=rn-1;for(let u=0;u(e[e.CATEGORY=0]="CATEGORY",e[e.COLLISION=1]="COLLISION",e[e.COLOR=2]="COLOR",e[e.KIND=3]="KIND",e[e.DIR=4]="DIR",e[e.NUMBER=5]="NUMBER",e[e.STRING=6]="STRING",e[e.NUMBER_OR_STRING=7]="NUMBER_OR_STRING",e[e.MAYBE_CATEGORY=8]="MAYBE_CATEGORY",e[e.MAYBE_COLLISION=9]="MAYBE_COLLISION",e[e.MAYBE_COLOR=10]="MAYBE_COLOR",e[e.MAYBE_KIND=11]="MAYBE_KIND",e[e.MAYBE_DIR=12]="MAYBE_DIR",e[e.MAYBE_NUMBER=13]="MAYBE_NUMBER",e[e.MAYBE_STRING=14]="MAYBE_STRING",e[e.MAYBE_NUMBER_OR_STRING=15]="MAYBE_NUMBER_OR_STRING",e[e.ANY=16]="ANY",e))(q||{});function Rt(e,t){throw new Error(`Invalid arg, expected: ${e} but got ${JSON.stringify(t)}`)}function ne(e,t,n){var o,a,c,l;const r=C.words;C.words=e;const i=[];let s=t;for(let u=0;u(Wg(1,e,t),0)).command("synth",(e,t)=>{for(let n=1;n<=8;++n)Zn(n,t);return 0}).command("synth1",(e,t)=>(Zn(1,t),0)).command("synth2",(e,t)=>(Zn(2,t),0)).command("synth3",(e,t)=>(Zn(3,t),0)).command("synth4",(e,t)=>(Zn(4,t),0)).command("synth5",(e,t)=>(Zn(5,t),0)).command("synth6",(e,t)=>(Zn(6,t),0)).command("synth7",(e,t)=>(Zn(7,t),0)).command("synth8",(e,t)=>(Zn(8,t),0)).command("bgplay",(e,t)=>(Wg(-1,e,t),0)).command("bgsynth",(e,t)=>(Zn(0,t),0));function Ka(e,t,n,r){const i=Ce(t)?t:t.id,s=Ce(t)?void 0:{x:t.x??0,y:t.y??0},o=Ce(n)?n:n.id,a=i??s;k(o)&&k(a)&&e.send(o,r,a)}function bI(e,t,n,r){k(n==null?void 0:n.id)?(n.headless=!0,Qs(e,t,n)):jg(t,r,"empty")}function Gg(e,t,n,r,i){const s=ZR(t,n,r,i);if(k(s)){Ka(e,s,e.id(),"thud"),r.kind===Xe.PLAYER?Ka(e,e.id(),s,"touch"):r.collision===Ye.ISBULLET?Ka(e,e.id(),s,"shot"):Ka(e,e.id(),s,"bump");const o=Ln(t,s);return(s.destructible??(o==null?void 0:o.destructible))&&bI(t,n,s,i),!1}return!0}function Hg(e,t,n){if(!fr(C.element))return 0;const[r,i]=ne(t,0,[q.DIR,q.MAYBE_KIND]),s=i??["bullet"],o=tI(C.book,C.board,s,{x:C.element.x,y:C.element.y});if(k(o)){o.arg=n,o.collision=Ye.ISBULLET,o.stepx=r.x-C.element.x,o.stepy=r.y-C.element.y;const a=Ln(C.book,o),c=o.code??(a==null?void 0:a.code)??"";G_(C.book,C.board,o,c,1),o.x===C.element.x&&o.y===C.element.y?o.headless=!0:e.bucket(o.id)}return e.yield(),0}const wI=lr().command("change",(e,t)=>{if(!k(C.book)||!k(C.board))return 0;const[n,r]=ne(t,0,[q.KIND,q.KIND]);za(C.book,C.board);const i=jo(n)??"",s=bs(C.board,i),o=Lh(s,n),a=jo(r),c=Ih(r),l=Oh(r);return o.forEach(u=>{if(Yi(C.book,u)===a)k(c)&&(u.color=c),k(l)&&(u.bg=l);else{if(k(u.id)&&(Qs(C.book,C.board,u),!Lu(C.book,u,C.timestamp)))return;fr(u)&&Mu(C.book,C.board,r,u)}}),0}).command("put",(e,t)=>{if(!k(C.book)||!k(C.board))return 0;const[n,r]=ne(t,0,[q.DIR,q.KIND]);return za(C.book,C.board),Mu(C.book,C.board,r,n),0}).command("shootwith",(e,t)=>{const[n,r]=ne(t,0,[q.ANY]);return Hg(e,t.slice(r),n)}).command("shoot",Hg).command("throwstar",()=>0);function eo(){return eo=Object.assign||function(e){for(var t=1;t0}function ju(e){Ja++;try{return e()}finally{Ja--,Ja===0&&AI()}}var zu=!1;function Xg(){return zu}function Zg(e){zu=!0;try{e()}finally{zu=!1}}function SI(e){return function(){return Zg(e)}}var Wu=[];function AI(){var e=[].concat(Wu);Wu=[],Yg(e)}function Yg(e){var t=new Set;e.forEach(function(n){var r;(n.type==="add"||n.type==="delete")&&n.observable[vt].connections.iterate.forEach(function(i){t.add(i)}),(r=n.observable[vt].connections.byKey.get(n.key))==null||r.forEach(function(i){t.add(i)})}),t.forEach(function(n){n.trigger()})}function Xa(e){if(Jg()){Wu.push(e);return}Yg([e])}function Qg(e,t){if(e.type==="iterate")e.observable[vt].connections.iterate.add(t);else{var n=e.observable[vt].connections.byKey.get(e.key);n||(n=new Set,e.observable[vt].connections.byKey.set(e.key,n)),n.add(t)}}function Za(e,t){if(!Xg()){var n=qg();n&&(Qg(e,n),n.registerConnection(e)),t&&(Qg(e,t),t.registerConnection(e))}}var Gu=Symbol("$skipreactive"),vt=Symbol("$reactive"),kn=Symbol("$reactiveproxy");function to(e,t){return!!(e&&e[kn]&&e[kn].implicitObserver===t)}function Hu(e){return e[Gu]=!0,e}function e0(e){return!!(e&&!to(e)&&e[vt])}function Vu(e,t,n){if(n===void 0&&(n=!1),e[Gu]||to(e,t))return e;var r=TI(e,n);if(!t)return r;var i=r[vt].proxiesWithImplicitObserver.get(t);if(!i){var s={implicitObserver:t};Object.setPrototypeOf(s,t0),i=new Proxy(r[vt].raw,s),r[vt].proxiesWithImplicitObserver.set(t,i)}return i}var no=Vu;function TI(e,t){if(t===void 0&&(t=!1),to(e))return e;if(e0(e))return e[vt].proxy;if(e[vt]||e[kn])throw new Error("unexpected");var n={connections:{iterate:new Set,byKey:new Map},proxy:{},raw:e,proxiesWithImplicitObserver:new Map,shallow:t};Object.defineProperty(e,vt,{enumerable:!1,writable:!0,configurable:!0,value:n});var r=new Proxy(e,t0);return n.proxy=r,r}var t0={has:function(t,n){var r=Reflect.has(t,n);return typeof n=="symbol"||Za({observable:t,key:n,type:"has"},this.implicitObserver),r},get:function(t,n,r){if(n===kn)return{implicitObserver:this.implicitObserver};var i=Reflect.get(t,n,r);if(typeof n=="symbol")return n.toString()==="Symbol($reactiveproxy)"&&console.error("warning, Symbol($reactiveproxy) passed, but does not match $reactiveproxy. Multiple Reactive libraries loaded?"),i;if(n==="length"&&Array.isArray(t)?Za({observable:t,type:"iterate"},this.implicitObserver):Za({observable:t,key:n,type:"get"},this.implicitObserver),e0(i))return Vu(i,this.implicitObserver);if(t[vt].shallow)return i;if(typeof i=="object"&&i!==null&&!to(i,this.implicitObserver)&&!Object.isFrozen(i)){var s=Reflect.getOwnPropertyDescriptor(t,n);if((!s||!(s.writable===!1&&s.configurable===!1))&&(Kg()||this.implicitObserver))return Vu(i,this.implicitObserver)}return i},ownKeys:function(t){return Za({observable:t,type:"iterate"},this.implicitObserver),Reflect.ownKeys(t)},set:function(t,n,r,i){return ju(function(){if(typeof n=="symbol")return Reflect.set(t,n,r,i);var s=Object.hasOwnProperty.call(t,n),o=Reflect.get(t,n,i),a=Reflect.set(t,n,r,i);if(!s)Xa({observable:t,key:n,value:r,type:"add"});else if(r!==o)if(n==="length"&&Array.isArray(t)){if(!(onew Map,Ku=e=>{const t=Mn();return e.forEach((n,r)=>{t.set(r,n)}),t},Gr=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},NI=(e,t)=>{const n=[];for(const[r,i]of e)n.push(t(i,r));return n},CI=(e,t)=>{for(const[n,r]of e)if(t(r,n))return!0;return!1},es=()=>new Set,qu=e=>e[e.length-1],LI=(e,t)=>{for(let n=0;n{this.off(t,r),n(...i)};this.on(t,r)}off(t,n){const r=this._observers.get(t);r!==void 0&&(r.delete(n),r.size===0&&this._observers.delete(t))}emit(t,n){return Hr((this._observers.get(t)||Mn()).values()).forEach(r=>r(...n))}destroy(){this._observers=Mn()}}const Vr=Math.floor,Ya=Math.abs,r0=(e,t)=>ee>t?e:t,i0=e=>e!==0?e<0:1/e<0,s0=1,o0=2,Ju=4,Xu=8,ro=32,kr=64,cn=128,Qa=31,Zu=63,vi=127,PI=2147483647,a0=Number.MAX_SAFE_INTEGER,DI=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&Vr(e)===e),BI=e=>e.toLowerCase(),FI=/^\s*/g,$I=e=>e.replace(FI,""),jI=/([A-Z])/g,c0=(e,t)=>$I(e.replace(jI,n=>`${t}${BI(n)}`)),zI=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let i=0;iio.encode(e):zI;let so=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});so&&so.decode(new Uint8Array).length===1&&(so=null);class oo{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Kr=()=>new oo,GI=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(GI(e));let n=0;for(let r=0;r{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Yu=It,ve=(e,t)=>{for(;t>vi;)It(e,cn|vi&t),t=Vr(t/128);It(e,vi&t)},Qu=(e,t)=>{const n=i0(t);for(n&&(t=-t),It(e,(t>Zu?cn:0)|(n?kr:0)|Zu&t),t=Vr(t/64);t>0;)It(e,(t>vi?cn:0)|vi&t),t=Vr(t/128)},ef=new Uint8Array(3e4),VI=ef.length/3,KI=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),r=n.length;ve(e,r);for(let i=0;i{const n=e.cbuf.length,r=e.cpos,i=r0(n-r,t.length),s=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,s>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(wi(n*2,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)},Pt=(e,t)=>{ve(e,t.byteLength),ec(e,t)},tf=(e,t)=>{HI(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},JI=(e,t)=>tf(e,4).setFloat32(0,t,!1),XI=(e,t)=>tf(e,8).setFloat64(0,t,!1),ZI=(e,t)=>tf(e,8).setBigInt64(0,t,!1),l0=new DataView(new ArrayBuffer(4)),YI=e=>(l0.setFloat32(0,e),l0.getFloat32(0)===e),ao=(e,t)=>{switch(typeof t){case"string":It(e,119),ts(e,t);break;case"number":DI(t)&&Ya(t)<=PI?(It(e,125),Qu(e,t)):YI(t)?(It(e,124),JI(e,t)):(It(e,123),XI(e,t));break;case"bigint":It(e,122),ZI(e,t);break;case"object":if(t===null)It(e,126);else if(MI(t)){It(e,117),ve(e,t.length);for(let n=0;n0&&ve(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const f0=e=>{e.count>0&&(Qu(e.encoder,e.count===1?e.s:-e.s),e.count>1&&ve(e.encoder,e.count-2))};class tc{constructor(){this.encoder=new oo,this.s=0,this.count=0}write(t){this.s===t?this.count++:(f0(this),this.count=1,this.s=t)}toUint8Array(){return f0(this),Un(this.encoder)}}const h0=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Qu(e.encoder,t),e.count>1&&ve(e.encoder,e.count-2)}};class nf{constructor(){this.encoder=new oo,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(h0(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return h0(this),Un(this.encoder)}}class QI{constructor(){this.sarr=[],this.s="",this.lensE=new tc}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new oo;return this.sarr.push(this.s),this.s="",ts(t,this.sarr.join("")),ec(t,this.lensE.toUint8Array()),Un(t)}}const qr=e=>new Error(e),Yn=()=>{throw qr("Method unimplemented")},Qn=()=>{throw qr("Unexpected case")},d0=qr("Unexpected end of array"),p0=qr("Integer out of Range");class nc{constructor(t){this.arr=t,this.pos=0}}const Ei=e=>new nc(e),eO=e=>e.pos!==e.arr.length,tO=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Ht=e=>tO(e,Ee(e)),ns=e=>e.arr[e.pos++],Ee=e=>{let t=0,n=1;const r=e.arr.length;for(;e.posa0)throw p0}throw d0},rf=e=>{let t=e.arr[e.pos++],n=t&Zu,r=64;const i=(t&kr)>0?-1:1;if(!(t&cn))return i*n;const s=e.arr.length;for(;e.posa0)throw p0}throw d0},rs=so?e=>so.decode(Ht(e)):e=>{let t=Ee(e);if(t===0)return"";{let n=String.fromCodePoint(ns(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ns(e));else for(;t>0;){const r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},sf=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},nO=[e=>{},e=>null,rf,e=>sf(e,4).getFloat32(0,!1),e=>sf(e,8).getFloat64(0,!1),e=>sf(e,8).getBigInt64(0,!1),e=>!1,e=>!0,rs,e=>{const t=Ee(e),n={};for(let r=0;r{const t=Ee(e),n=[];for(let r=0;rnO[127-ns(e)](e);class m0 extends nc{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),eO(this)?this.count=Ee(this)+1:this.count=-1),this.count--,this.s}}class rc extends nc{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=rf(this);const t=i0(this.s);this.count=1,t&&(this.s=-this.s,this.count=Ee(this)+2)}return this.count--,this.s}}class of extends nc{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=rf(this),n=t&1;this.diff=Vr(t/2),this.count=1,n&&(this.count=Ee(this)+2)}return this.s+=this.diff,this.count--,this.s}}class rO{constructor(t){this.decoder=new rc(t),this.str=rs(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const iO=crypto.getRandomValues.bind(crypto),g0=()=>iO(new Uint32Array(1))[0],sO="10000000-1000-4000-8000"+-1e11,oO=()=>sO.replace(/[018]/g,e=>(e^g0()&15>>e/4).toString(16)),y0=e=>new Promise(e);Promise.all.bind(Promise);const _0=e=>e===void 0?null:e;class aO{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let b0=new aO,cO=!0;try{typeof localStorage<"u"&&localStorage&&(b0=localStorage,cO=!1)}catch{}const lO=b0,uO=Object.assign,fO=Object.keys,hO=(e,t)=>{for(const n in e)t(e[n],n)},w0=e=>fO(e).length,dO=e=>{for(const t in e)return!1;return!0},pO=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},mO=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),gO=(e,t)=>e===t||w0(e)===w0(t)&&pO(e,(n,r)=>(n!==void 0||mO(t,r))&&t[r]===n),yO=Object.freeze,v0=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&v0(e[t])}return yO(e)},af=(e,t,n=0)=>{try{for(;ne,bO=(e,t)=>t.includes(e);var E0={};const lo=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let er;const wO=()=>{if(er===void 0)if(lo){er=Mn();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");er.set(`--${c0(t,"-")}`,n),er.set(`-${c0(t,"-")}`,n)}})):er=Mn();return er},cf=e=>wO().has(e),ic=e=>_0(lo?E0[e.toUpperCase().replaceAll("-","_")]:lO.getItem(e)),k0=e=>cf("--"+e)||ic(e)!==null;k0("production");const vO=lo&&bO(E0.FORCE_COLOR,["true","1","2"])||!cf("--no-colors")&&!k0("no-color")&&(!lo||process.stdout.isTTY)&&(!lo||cf("--color")||ic("COLORTERM")!==null||(ic("TERM")||"").includes("color")),EO=e=>new Uint8Array(e),kO=e=>{const t=EO(e.byteLength);return t.set(e),t};class SO{constructor(t,n){this.left=t,this.right=n}}const Sr=(e,t)=>new SO(e,t);typeof DOMParser<"u"&&new DOMParser;const AO=e=>NI(e,(t,n)=>`${n}:${t};`).join(""),Ar=Symbol,S0=Ar(),A0=Ar(),TO=Ar(),xO=Ar(),RO=Ar(),T0=Ar(),IO=Ar(),lf=Ar(),OO=Ar(),NO=e=>{var i;e.length===1&&((i=e[0])==null?void 0:i.constructor)===Function&&(e=e[0]());const t=[],n=[];let r=0;for(;r0&&n.push(t.join(""));r{var o;e.length===1&&((o=e[0])==null?void 0:o.constructor)===Function&&(e=e[0]());const t=[],n=[],r=Mn();let i=[],s=0;for(;s0||l.length>0?(t.push("%c"+a),n.push(l)):t.push(a)}else break}}for(s>0&&(i=n,i.unshift(t.join("")));s{console.log(...x0(e)),R0.forEach(t=>t.print(e))},MO=(...e)=>{console.warn(...x0(e)),e.unshift(lf),R0.forEach(t=>t.print(e))},R0=es(),I0=e=>({[Symbol.iterator](){return this},next:e}),UO=(e,t)=>I0(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),uf=(e,t)=>I0(()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});class ff{constructor(t,n){this.clock=t,this.len=n}}class uo{constructor(){this.clients=new Map}}const O0=(e,t,n)=>t.clients.forEach((r,i)=>{const s=e.doc.store.clients.get(i);for(let o=0;o{let n=0,r=e.length-1;for(;n<=r;){const i=Vr((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&PO(n,t.clock)!==null},hf=e=>{e.clients.forEach(t=>{t.sort((i,s)=>i.clock-s.clock);let n,r;for(n=1,r=1;n=s.clock?i.len=wi(i.len,s.clock+s.len-i.clock):(r{const t=new uo;for(let n=0;n{if(!t.clients.has(i)){const s=r.slice();for(let o=n+1;o{Gr(e.clients,t,()=>[]).push(new ff(n,r))},BO=()=>new uo,FO=e=>{const t=BO();return e.clients.forEach((n,r)=>{const i=[];for(let s=0;s0&&t.clients.set(r,i)}),t},is=(e,t)=>{ve(e.restEncoder,t.clients.size),Hr(t.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{e.resetDsCurVal(),ve(e.restEncoder,n);const i=r.length;ve(e.restEncoder,i);for(let s=0;s{const t=new uo,n=Ee(e.restDecoder);for(let r=0;r0){const o=Gr(t.clients,i,()=>[]);for(let a=0;a{const r=new uo,i=Ee(e.restDecoder);for(let s=0;s0){const s=new ki;return ve(s.restEncoder,0),is(s,r),s.toUint8Array()}return null},L0=g0;class Tr extends UI{constructor({guid:t=oO(),collectionid:n=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=L0(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new H0,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=y0(l=>{this.on("load",()=>{this.isLoaded=!0,l(this)})});const c=()=>y0(l=>{const u=f=>{(f===void 0||f===!0)&&(this.off("sync",u),l())};this.on("sync",u)});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&Je(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Hr(this.subdocs).map(t=>t.guid))}transact(t,n=null){return Je(this,t,n)}get(t,n=at){const r=Gr(this.share,t,()=>{const s=new n;return s._integrate(this,null),s}),i=r.constructor;if(n!==at&&i!==n)if(i===at){const s=new n;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(t,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return r}getArray(t=""){return this.get(t,tr)}getText(t=""){return this.get(t,Dn)}getMap(t=""){return this.get(t,nr)}getXmlElement(t=""){return this.get(t,xr)}getXmlFragment(t=""){return this.get(t,rr)}toJSON(){const t={};return this.share.forEach((n,r)=>{t[r]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Hr(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new Tr({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Je(t.parent.doc,r=>{const i=n.doc;t.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class M0{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return Ee(this.restDecoder)}readDsLen(){return Ee(this.restDecoder)}}class U0 extends M0{readLeftID(){return Oe(Ee(this.restDecoder),Ee(this.restDecoder))}readRightID(){return Oe(Ee(this.restDecoder),Ee(this.restDecoder))}readClient(){return Ee(this.restDecoder)}readInfo(){return ns(this.restDecoder)}readString(){return rs(this.restDecoder)}readParentInfo(){return Ee(this.restDecoder)===1}readTypeRef(){return Ee(this.restDecoder)}readLen(){return Ee(this.restDecoder)}readAny(){return co(this.restDecoder)}readBuf(){return kO(Ht(this.restDecoder))}readJSON(){return JSON.parse(rs(this.restDecoder))}readKey(){return rs(this.restDecoder)}}class $O{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ee(this.restDecoder),this.dsCurrVal}readDsLen(){const t=Ee(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class ss extends $O{constructor(t){super(t),this.keys=[],Ee(t),this.keyClockDecoder=new of(Ht(t)),this.clientDecoder=new rc(Ht(t)),this.leftClockDecoder=new of(Ht(t)),this.rightClockDecoder=new of(Ht(t)),this.infoDecoder=new m0(Ht(t),ns),this.stringDecoder=new rO(Ht(t)),this.parentInfoDecoder=new m0(Ht(t),ns),this.typeRefDecoder=new rc(Ht(t)),this.lenDecoder=new rc(Ht(t))}readLeftID(){return new os(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new os(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return co(this.restDecoder)}readBuf(){return Ht(this.restDecoder)}readJSON(){return co(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{r=wi(r,t[0].id.clock);const i=Pn(t,r);ve(e.restEncoder,t.length-i),e.writeClient(n),ve(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let o=i+1;o{const r=new Map;n.forEach((i,s)=>{Ot(t,s)>i&&r.set(s,i)}),ac(t).forEach((i,s)=>{n.has(s)||r.set(s,0)}),ve(e.restEncoder,r.size),Hr(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{jO(e,t.clients.get(i),i,s)})},zO=(e,t)=>{const n=Mn(),r=Ee(e.restDecoder);for(let i=0;i{const r=[];let i=Hr(n.keys()).sort((h,p)=>h-p);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let h=n.get(i[i.length-1]);for(;h.refs.length===h.i;)if(i.pop(),i.length>0)h=n.get(i[i.length-1]);else return null;return h};let o=s();if(o===null)return null;const a=new H0,c=new Map,l=(h,p)=>{const m=c.get(h);(m==null||m>p)&&c.set(h,p)};let u=o.refs[o.i++];const f=new Map,d=()=>{for(const h of r){const p=h.id.client,m=n.get(p);m?(m.i--,a.clients.set(p,m.refs.slice(m.i)),n.delete(p),m.i=0,m.refs=[]):a.clients.set(p,[h]),i=i.filter(b=>b!==p)}r.length=0};for(;;){if(u.constructor!==Sn){const p=Gr(f,u.id.client,()=>Ot(t,u.id.client))-u.id.clock;if(p<0)r.push(u),l(u.id.client,u.id.clock-1),d();else{const m=u.getMissing(e,t);if(m!==null){r.push(u);const b=n.get(m)||{refs:[],i:0};if(b.refs.length===b.i)l(m,Ot(t,m)),d();else{u=b.refs[b.i++];continue}}else(p===0||p0)u=r.pop();else if(o!==null&&o.i0){const h=new ki;return pf(h,a,new Map),ve(h.restEncoder,0),{missing:c,update:h.toUint8Array()}}return null},GO=(e,t)=>pf(e,t.doc.store,t.beforeState),HO=(e,t,n,r=new ss(e))=>Je(t,i=>{i.local=!1;let s=!1;const o=i.doc,a=o.store,c=zO(r,o),l=WO(i,a,c),u=a.pendingStructs;if(u){for(const[d,h]of u.missing)if(hh)&&u.missing.set(d,h)}u.update=lc([u.update,l.update])}}else a.pendingStructs=l;const f=C0(r,i,a);if(a.pendingDs){const d=new ss(Ei(a.pendingDs));Ee(d.restDecoder);const h=C0(d,i,a);f&&h?a.pendingDs=lc([f,h]):a.pendingDs=f||h}else a.pendingDs=f;if(s){const d=a.pendingStructs.update;a.pendingStructs=null,B0(i.doc,d)}},n,!1),B0=(e,t,n,r=ss)=>{const i=Ei(t);HO(i,e,n,new r(i))},VO=(e,t,n)=>B0(e,t,n,U0),KO=(e,t,n=new Map)=>{pf(e,t.store,n),is(e,FO(t.store))},qO=(e,t=new Uint8Array([0]),n=new ki)=>{const r=F0(t);KO(n,e,r);const i=[n.toUint8Array()];if(e.store.pendingDs&&i.push(e.store.pendingDs),e.store.pendingStructs&&i.push(lN(e.store.pendingStructs.update,t)),i.length>1){if(n.constructor===fo)return aN(i.map((s,o)=>o===0?s:fN(s)));if(n.constructor===ki)return lc(i)}return i[0]},JO=(e,t)=>qO(e,t,new fo),XO=e=>{const t=new Map,n=Ee(e.restDecoder);for(let r=0;rXO(new M0(Ei(e))),$0=(e,t)=>(ve(e.restEncoder,t.size),Hr(t.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{ve(e.restEncoder,n),ve(e.restEncoder,r)}),e),ZO=(e,t)=>$0(e,ac(t.store)),YO=(e,t=new D0)=>(e instanceof Map?$0(t,e):ZO(t,e),t.toUint8Array()),QO=e=>YO(e,new P0);class eN{constructor(){this.l=[]}}const j0=()=>new eN,z0=(e,t)=>e.l.push(t),W0=(e,t)=>{const n=e.l,r=n.length;e.l=n.filter(i=>t!==i),r===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},G0=(e,t,n)=>af(e.l,[t,n]);class os{constructor(t,n){this.client=t,this.clock=n}}const oc=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,Oe=(e,t)=>new os(e,t),tN=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Qn()},as=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!N0(t.ds,e.id),mf=(e,t)=>{const n=Gr(e.meta,mf,es),r=e.doc.store;n.has(t)||(t.sv.forEach((i,s)=>{i{}),n.add(t))};class H0{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ac=e=>{const t=new Map;return e.clients.forEach((n,r)=>{const i=n[n.length-1];t.set(r,i.id.clock+i.length)}),t},Ot=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const r=n[n.length-1];return r.id.clock+r.length},V0=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const r=n[n.length-1];if(r.id.clock+r.length!==t.id.clock)throw Qn()}n.push(t)},Pn=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=Vr(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t{const n=e.clients.get(t.client);return n[Pn(n,t.clock)]},yf=(e,t,n)=>{const r=Pn(t,n),i=t[r];return i.id.clock{const n=e.doc.store.clients.get(t.client);return n[yf(e,n,t.clock)]},K0=(e,t,n)=>{const r=t.clients.get(n.client),i=Pn(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==ln&&r.splice(i+1,0,_c(e,s,n.clock-s.id.clock+1)),s},nN=(e,t,n)=>{const r=e.clients.get(t.id.client);r[Pn(r,t.id.clock)]=n},q0=(e,t,n,r,i)=>{if(r===0)return;const s=n+r;let o=yf(e,t,n),a;do a=t[o++],st.deleteSet.clients.size===0&&!CI(t.afterState,(n,r)=>t.beforeState.get(r)!==n)?!1:(hf(t.deleteSet),GO(e,t),is(e,t.deleteSet),!0),X0=(e,t,n)=>{const r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Gr(e.changed,t,es).add(n)},cc=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof kt&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}const s=t-i;return s&&e.splice(t+1-s,s),s},iN=(e,t,n)=>{for(const[r,i]of e.clients.entries()){const s=t.clients.get(r);for(let o=i.length-1;o>=0;o--){const a=i[o],c=a.clock+a.len;for(let l=Pn(s,a.clock),u=s[l];l{e.clients.forEach((n,r)=>{const i=t.clients.get(r);for(let s=n.length-1;s>=0;s--){const o=n[s],a=r0(i.length-1,1+Pn(i,o.clock+o.len-1));for(let c=a,l=i[c];c>0&&l.id.clock>=o.clock;l=i[c])c-=1+cc(i,c)}})},Z0=(e,t)=>{if(ta.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(n,c)})),a.push(()=>{n.changedParentTypes.forEach((c,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=l,u._path=null}),c.sort((u,f)=>u.path.length-f.path.length),G0(l._dEH,c,n))})}),a.push(()=>r.emit("afterTransaction",[n,r])),af(a,[]),n._needFormattingCleanup&&AN(n)}finally{r.gc&&iN(s,i,r.gcFilter),sN(s,i),n.afterState.forEach((u,f)=>{const d=n.beforeState.get(f)||0;if(d!==u){const h=i.clients.get(f),p=wi(Pn(h,d),1);for(let m=h.length-1;m>=p;)m-=1+cc(h,m)}});for(let u=o.length-1;u>=0;u--){const{client:f,clock:d}=o[u].id,h=i.clients.get(f),p=Pn(h,d);p+11||p>0&&cc(h,p)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(LO(lf,S0,"[yjs] ",A0,T0,"Changed the client-id because another client seems to be using it."),r.clientID=L0()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const u=new fo;J0(u,n)&&r.emit("update",[u.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const u=new ki;J0(u,n)&&r.emit("updateV2",[u.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=n;(a.size>0||l.size>0||c.size>0)&&(a.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),l.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,n]),l.forEach(u=>u.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):Z0(e,t+1)}}},Je=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;e._transaction===null&&(s=!0,e._transaction=new rN(e,n,r),i.push(e._transaction),i.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const a=e._transaction===i[0];e._transaction=null,a&&Z0(i,0)}}return o};function*oN(e){const t=Ee(e.restDecoder);for(let n=0;nlc(e,U0,fo),cN=(e,t)=>{if(e.constructor===ln){const{client:n,clock:r}=e.id;return new ln(Oe(n,r+t),e.length-t)}else if(e.constructor===Sn){const{client:n,clock:r}=e.id;return new Sn(Oe(n,r+t),e.length-t)}else{const n=e,{client:r,clock:i}=n.id;return new kt(Oe(r,i+t),null,Oe(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},lc=(e,t=ss,n=ki)=>{if(e.length===1)return e[0];const r=e.map(u=>new t(Ei(u)));let i=r.map(u=>new _f(u,!0)),s=null;const o=new n,a=new bf(o);for(;i=i.filter(d=>d.curr!==null),i.sort((d,h)=>{if(d.curr.id.client===h.curr.id.client){const p=d.curr.id.clock-h.curr.id.clock;return p===0?d.curr.constructor===h.curr.constructor?0:d.curr.constructor===Sn?1:-1:p}else return h.curr.id.client-d.curr.id.client}),i.length!==0;){const u=i[0],f=u.curr.id.client;if(s!==null){let d=u.curr,h=!1;for(;d!==null&&d.id.clock+d.length<=s.struct.id.clock+s.struct.length&&d.id.client>=s.struct.id.client;)d=u.next(),h=!0;if(d===null||d.id.client!==f||h&&d.id.clock>s.struct.id.clock+s.struct.length)continue;if(f!==s.struct.id.client)Xr(a,s.struct,s.offset),s={struct:d,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===Sn?s.struct.length-=p:d=cN(d,p)),s.struct.mergeWith(d)||(Xr(a,s.struct,s.offset),s={struct:d,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===f&&d.id.clock===s.struct.id.clock+s.struct.length&&d.constructor!==Sn;d=u.next())Xr(a,s.struct,s.offset),s={struct:d,offset:0}}s!==null&&(Xr(a,s.struct,s.offset),s=null),wf(a);const c=r.map(u=>df(u)),l=DO(c);return is(o,l),o.toUint8Array()},lN=(e,t,n=ss,r=ki)=>{const i=F0(t),s=new r,o=new bf(s),a=new n(Ei(e)),c=new _f(a,!1);for(;c.curr;){const u=c.curr,f=u.id.client,d=i.get(f)||0;if(c.curr.constructor===Sn){c.next();continue}if(u.id.clock+u.length>d)for(Xr(o,u,wi(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===f;)Xr(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===f&&c.curr.id.clock+c.curr.length<=d;)c.next()}wf(o);const l=df(a);return is(s,l),s.toUint8Array()},Y0=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Un(e.encoder.restEncoder)}),e.encoder.restEncoder=Kr(),e.written=0)},Xr=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Y0(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),ve(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},wf=e=>{Y0(e);const t=e.encoder.restEncoder;ve(t,e.clientStructs.length);for(let n=0;n{const i=new n(Ei(e)),s=new _f(i,!1),o=new r,a=new bf(o);for(let l=s.curr;l!==null;l=s.next())Xr(a,t(l),0);wf(a);const c=df(i);return is(o,c),o.toUint8Array()},fN=e=>uN(e,_O,ss,fo),Q0="You must not compute changes after the event-handler fired.";class uc{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=hN(this.currentTarget,this.target))}deletes(t){return N0(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw qr(Q0);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(i=>{if(i!==null){const s=n._map.get(i);let o,a;if(this.adds(s)){let c=s.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(s))if(c!==null&&this.deletes(c))o="delete",a=qu(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",a=qu(c.content.getContent())):(o="add",a=void 0)}else if(this.deletes(s))o="delete",a=qu(s.content.getContent());else return;t.set(i,{action:o,oldValue:a})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw qr(Q0);const n=this.target,r=es(),i=es(),s=[];if(t={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const c=()=>{a&&s.push(a)};for(let l=n._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=l.length,i.add(l)):this.adds(l)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(l.content.getContent()),r.add(l)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=l.length);a!==null&&a.retain===void 0&&c()}this._changes=t}return t}}const hN=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let r=0,i=t._item.parent._start;for(;i!==t._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;n.unshift(r)}t=t._item.parent}return n},Dt=()=>{MO("Invalid access: Add Yjs type to a document before reading data.")},ey=80;let vf=0;class dN{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=vf++}}const pN=e=>{e.timestamp=vf++},ty=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=vf++},mN=(e,t,n)=>{if(e.length>=ey){const r=e.reduce((i,s)=>i.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((s,o)=>Ya(t-s.index)t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&Ya(n.index-i){for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){e.splice(r,1);continue}i.p=s,s.marker=!0}(t0&&t===i.index)&&(i.index=wi(t,i.index+n))}},hc=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;Gr(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;G0(r._eH,n,t)};class at{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=j0(),this._dEH=j0(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw Yn()}clone(){throw Yn()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){z0(this._eH,t)}observeDeep(t){z0(this._dEH,t)}unobserve(t){W0(this._eH,t)}unobserveDeep(t){W0(this._dEH,t)}toJSON(){}}const ny=(e,t,n)=>{e.doc??Dt(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=t)t-=o.length;else{for(let a=t;a0;a++)i.push(o[a]),r--;t=0}}s=s.right}return i},ry=e=>{e.doc??Dt();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let i=0;i{let n=0,r=e._start;for(e.doc??Dt();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const n=[];return po(e,(r,i)=>{n.push(t(r,i,e))}),n},gN=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const i=n[r++];return n.length<=r&&(n=null),{done:!1,value:i}}}},sy=(e,t)=>{e.doc??Dt();const n=fc(e,t);let r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t{let i=n;const s=e.doc,o=s.clientID,a=s.store,c=n===null?t._start:n.right;let l=[];const u=()=>{l.length>0&&(i=new kt(Oe(o,Ot(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Ti(l)),i.integrate(e,0),l=[])};r.forEach(f=>{if(f===null)l.push(f);else switch(f.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(f);break;default:switch(u(),f.constructor){case Uint8Array:case ArrayBuffer:i=new kt(Oe(o,Ot(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new mo(new Uint8Array(f))),i.integrate(e,0);break;case Tr:i=new kt(Oe(o,Ot(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new yo(f)),i.integrate(e,0);break;default:if(f instanceof at)i=new kt(Oe(o,Ot(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Rr(f)),i.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},oy=()=>qr("Length exceeded!"),ay=(e,t,n,r)=>{if(n>t._length)throw oy();if(n===0)return t._searchMarker&&ho(t._searchMarker,n,r.length),dc(e,t,null,r);const i=n,s=fc(t,n);let o=t._start;for(s!==null&&(o=s.p,n-=s.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let i=(t._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:t._start}).p;if(i)for(;i.right;)i=i.right;return dc(e,t,i,n)},cy=(e,t,n,r)=>{if(r===0)return;const i=n,s=r,o=fc(t,n);let a=t._start;for(o!==null&&(a=o.p,n-=o.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n0&&a!==null;)a.deleted||(r0)throw oy();t._searchMarker&&ho(t._searchMarker,i,-s+r)},pc=(e,t,n)=>{const r=t._map.get(n);r!==void 0&&r.delete(e)},Ef=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let a;if(r==null)a=new Ti([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:a=new Ti([r]);break;case Uint8Array:a=new mo(r);break;case Tr:a=new yo(r);break;default:if(r instanceof at)a=new Rr(r);else throw new Error("Unexpected content type")}new kt(Oe(o,Ot(s.store,o)),i,i&&i.lastId,null,null,t,n,a).integrate(e,0)},kf=(e,t)=>{e.doc??Dt();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ly=e=>{const t={};return e.doc??Dt(),e._map.forEach((n,r)=>{n.deleted||(t[r]=n.content.getContent()[n.length-1])}),t},uy=(e,t)=>{e.doc??Dt();const n=e._map.get(t);return n!==void 0&&!n.deleted},_N=(e,t)=>{const n={};return e._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!t.sv.has(s.id.client)||s.id.clock>=(t.sv.get(s.id.client)||0));)s=s.left;s!==null&&as(s,t)&&(n[i]=s.content.getContent()[s.length-1])}),n},mc=e=>(e.doc??Dt(),UO(e._map.entries(),t=>!t[1].deleted));class bN extends uc{}class tr extends at{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new tr;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new tr}clone(){const t=new tr;return t.insert(0,this.toArray().map(n=>n instanceof at?n.clone():n)),t}get length(){return this.doc??Dt(),this._length}_callObserver(t,n){super._callObserver(t,n),hc(this,t,new bN(this,t))}insert(t,n){this.doc!==null?Je(this.doc,r=>{ay(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?Je(this.doc,n=>{yN(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?Je(this.doc,r=>{cy(r,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return sy(this,t)}toArray(){return ry(this)}slice(t=0,n=this.length){return ny(this,t,n)}toJSON(){return this.map(t=>t instanceof at?t.toJSON():t)}map(t){return iy(this,t)}forEach(t){po(this,t)}[Symbol.iterator](){return gN(this)}_write(t){t.writeTypeRef(GN)}}const wN=e=>new tr;class vN extends uc{constructor(t,n,r){super(t,n),this.keysChanged=r}}class nr extends at{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new nr}clone(){const t=new nr;return this.forEach((n,r)=>{t.set(r,n instanceof at?n.clone():n)}),t}_callObserver(t,n){hc(this,t,new vN(this,t,n))}toJSON(){this.doc??Dt();const t={};return this._map.forEach((n,r)=>{if(!n.deleted){const i=n.content.getContent()[n.length-1];t[r]=i instanceof at?i.toJSON():i}}),t}get size(){return[...mc(this)].length}keys(){return uf(mc(this),t=>t[0])}values(){return uf(mc(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return uf(mc(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Dt(),this._map.forEach((n,r)=>{n.deleted||t(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?Je(this.doc,n=>{pc(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?Je(this.doc,r=>{Ef(r,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return kf(this,t)}has(t){return uy(this,t)}clear(){this.doc!==null?Je(this.doc,t=>{this.forEach(function(n,r,i){pc(t,i,r)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(HN)}}const EN=e=>new nr,Zr=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&gO(e,t);class Sf{constructor(t,n,r,i){this.left=t,this.right=n,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Qn(),this.right.content.constructor){case Et:this.right.deleted||cs(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const fy=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case Et:t.right.deleted||cs(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n{const i=new Map,s=r?fc(t,n):null;if(s){const o=new Sf(s.p.left,s.p,s.index,i);return fy(e,o,n-s.index)}else{const o=new Sf(null,t._start,0,i);return fy(e,o,n)}},hy=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Et&&Zr(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach((o,a)=>{const c=n.left,l=n.right,u=new kt(Oe(s,Ot(i.store,s)),c,c&&c.lastId,l,l&&l.id,t,null,new Et(a,o));u.integrate(e,0),n.right=u,n.forward()})},cs=(e,t)=>{const{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},dy=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Et&&Zr(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},py=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)??null;if(!Zr(l,c)){o.set(a,l);const{left:u,right:f}=n;n.right=new kt(Oe(s,Ot(i.store,s)),u,u&&u.lastId,f,f&&f.id,t,null,new Et(a,c)),n.right.integrate(e,0),n.forward()}}return o},Af=(e,t,n,r,i)=>{n.currentAttributes.forEach((d,h)=>{i[h]===void 0&&(i[h]=null)});const s=e.doc,o=s.clientID;dy(n,i);const a=py(e,t,n,i),c=r.constructor===String?new ir(r):r instanceof at?new Rr(r):new Ai(r);let{left:l,right:u,index:f}=n;t._searchMarker&&ho(t._searchMarker,n.index,c.getLength()),u=new kt(Oe(o,Ot(s.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=f,n.forward(),hy(e,t,n,a)},my=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;dy(n,i);const a=py(e,t,n,i);e:for(;n.right!==null&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Et));){if(!n.right.deleted)switch(n.right.content.constructor){case Et:{const{key:c,value:l}=n.right.content,u=i[c];if(u!==void 0){if(Zr(u,l))a.delete(c);else{if(r===0)break e;a.set(c,l)}n.right.delete(e)}else n.currentAttributes.set(c,l);break}default:r0){let c="";for(;r>0;r--)c+=` -`;n.right=new kt(Oe(o,Ot(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new ir(c)),n.right.integrate(e,0),n.forward()}hy(e,t,n,a)},gy=(e,t,n,r,i)=>{let s=t;const o=Mn();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===Et){const l=s.content;o.set(l.key,l)}s=s.right}let a=0,c=!1;for(;t!==s;){if(n===t&&(c=!0),!t.deleted){const l=t.content;switch(l.constructor){case Et:{const{key:u,value:f}=l,d=r.get(u)??null;(o.get(u)!==l||d===f)&&(t.delete(e),a++,!c&&(i.get(u)??null)===f&&d!==f&&(d===null?i.delete(u):i.set(u,d))),!c&&!t.deleted&&cs(i,l);break}}}t=t.right}return a},kN=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Et){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},SN=e=>{let t=0;return Je(e.doc,n=>{let r=e._start,i=e._start,s=Mn();const o=Ku(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Et:cs(o,i.content);break;default:t+=gy(n,r,i,s,o),s=Ku(o),r=i;break}i=i.right}}),t},AN=e=>{const t=new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&q0(e,n.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===Et&&o.constructor!==ln&&t.add(o.parent)})}Je(n,r=>{O0(e,e.deleteSet,i=>{if(i instanceof ln||!i.parent._hasFormatting||t.has(i.parent))return;const s=i.parent;i.content.constructor===Et?t.add(s):kN(r,i)});for(const i of t)SN(i)})},yy=(e,t,n)=>{const r=n,i=Ku(t.currentAttributes),s=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Rr:case Ai:case ir:n{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];Je(t,r=>{const i=new Map,s=new Map;let o=this.target._start,a=null;const c={};let l="",u=0,f=0;const d=()=>{if(a!==null){let h=null;switch(a){case"delete":f>0&&(h={delete:f}),f=0;break;case"insert":(typeof l=="object"||l.length>0)&&(h={insert:l},i.size>0&&(h.attributes={},i.forEach((p,m)=>{p!==null&&(h.attributes[m]=p)}))),l="";break;case"retain":u>0&&(h={retain:u},dO(c)||(h.attributes=uO({},c))),u=0;break}h&&n.push(h),a=null}};for(;o!==null;){switch(o.content.constructor){case Rr:case Ai:this.adds(o)?this.deletes(o)||(d(),a="insert",l=o.content.getContent()[0],d()):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),f+=1):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=1);break;case ir:this.adds(o)?this.deletes(o)||(a!=="insert"&&(d(),a="insert"),l+=o.content.str):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),f+=o.length):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=o.length);break;case Et:{const{key:h,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const m=i.get(h)??null;Zr(m,p)?p!==null&&o.delete(r):(a==="retain"&&d(),Zr(p,s.get(h)??null)?delete c[h]:c[h]=p)}}else if(this.deletes(o)){s.set(h,p);const m=i.get(h)??null;Zr(m,p)||(a==="retain"&&d(),c[h]=m)}else if(!o.deleted){s.set(h,p);const m=c[h];m!==void 0&&(Zr(m,p)?m!==null&&o.delete(r):(a==="retain"&&d(),p===null?delete c[h]:c[h]=p))}o.deleted||(a==="insert"&&d(),cs(i,o.content));break}}o=o.right}for(d();n.length>0;){const h=n[n.length-1];if(h.retain!==void 0&&h.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Dn extends at{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Dt(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new Dn}clone(){const t=new Dn;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const r=new TN(this,t,n);hc(this,t,r),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Dt();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===ir&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?Je(this.doc,r=>{const i=new Sf(null,this._start,0,new Map);for(let s=0;s0)&&Af(r,this,i,a,o.attributes||{})}else o.retain!==void 0?my(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&yy(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,r){this.doc??Dt();const i=[],s=new Map,o=this.doc;let a="",c=this._start;function l(){if(a.length>0){const f={};let d=!1;s.forEach((p,m)=>{d=!0,f[m]=p});const h={insert:a};d&&(h.attributes=f),i.push(h),a=""}}const u=()=>{for(;c!==null;){if(as(c,t)||n!==void 0&&as(c,n))switch(c.content.constructor){case ir:{const f=s.get("ychange");t!==void 0&&!as(c,t)?(f===void 0||f.user!==c.id.client||f.type!=="removed")&&(l(),s.set("ychange",r?r("removed",c.id):{type:"removed"})):n!==void 0&&!as(c,n)?(f===void 0||f.user!==c.id.client||f.type!=="added")&&(l(),s.set("ychange",r?r("added",c.id):{type:"added"})):f!==void 0&&(l(),s.delete("ychange")),a+=c.content.str;break}case Rr:case Ai:{l();const f={insert:c.content.getContent()[0]};if(s.size>0){const d={};f.attributes=d,s.forEach((h,p)=>{d[p]=h})}i.push(f);break}case Et:as(c,t)&&(l(),cs(s,c.content));break}c=c.right}l()};return t||n?Je(o,f=>{t&&mf(f,t),n&&mf(f,n),u()},"cleanup"):u(),i}insert(t,n,r){if(n.length<=0)return;const i=this.doc;i!==null?Je(i,s=>{const o=gc(s,this,t,!r);r||(r={},o.currentAttributes.forEach((a,c)=>{r[c]=a})),Af(s,this,o,n,r)}):this._pending.push(()=>this.insert(t,n,r))}insertEmbed(t,n,r){const i=this.doc;i!==null?Je(i,s=>{const o=gc(s,this,t,!r);Af(s,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(t,n,r||{}))}delete(t,n){if(n===0)return;const r=this.doc;r!==null?Je(r,i=>{yy(i,gc(i,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,r){if(n===0)return;const i=this.doc;i!==null?Je(i,s=>{const o=gc(s,this,t,!1);o.right!==null&&my(s,this,o,n,r)}):this._pending.push(()=>this.format(t,n,r))}removeAttribute(t){this.doc!==null?Je(this.doc,n=>{pc(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?Je(this.doc,r=>{Ef(r,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return kf(this,t)}getAttributes(){return ly(this)}_write(t){t.writeTypeRef(VN)}}const xN=e=>new Dn;class Tf{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Dt()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===xr||n.constructor===rr)&&n._start!==null)t=n._start;else for(;t!==null;)if(t.right!==null){t=t.right;break}else t.parent===this._root?t=null:t=t.parent._item;while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class rr extends at{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new rr}clone(){const t=new rr;return t.insert(0,this.toArray().map(n=>n instanceof at?n.clone():n)),t}get length(){return this.doc??Dt(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Tf(this,t)}querySelector(t){t=t.toUpperCase();const r=new Tf(this,i=>i.nodeName&&i.nodeName.toUpperCase()===t).next();return r.done?null:r.value}querySelectorAll(t){return t=t.toUpperCase(),Hr(new Tf(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){hc(this,t,new ON(this,n,t))}toString(){return iy(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},r){const i=t.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),po(this,s=>{i.insertBefore(s.toDOM(t,n,r),null)}),i}insert(t,n){this.doc!==null?Je(this.doc,r=>{ay(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)Je(this.doc,r=>{const i=t&&t instanceof at?t._item:t;dc(r,this,i,n)});else{const r=this._prelimContent,i=t===null?0:r.findIndex(s=>s===t)+1;if(i===0&&t!==null)throw qr("Reference item not found");r.splice(i,0,...n)}}delete(t,n=1){this.doc!==null?Je(this.doc,r=>{cy(r,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return ry(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return sy(this,t)}slice(t=0,n=this.length){return ny(this,t,n)}forEach(t){po(this,t)}_write(t){t.writeTypeRef(qN)}}const RN=e=>new rr;class xr extends rr{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new xr(this.nodeName)}clone(){const t=new xr(this.nodeName),n=this.getAttributes();return hO(n,(r,i)=>{typeof r=="string"&&t.setAttribute(i,r)}),t.insert(0,this.toArray().map(r=>r instanceof at?r.clone():r)),t}toString(){const t=this.getAttributes(),n=[],r=[];for(const a in t)r.push(a);r.sort();const i=r.length;for(let a=0;a0?" "+n.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?Je(this.doc,n=>{pc(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?Je(this.doc,r=>{Ef(r,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return kf(this,t)}hasAttribute(t){return uy(this,t)}getAttributes(t){return t?_N(this,t):ly(this)}toDOM(t=document,n={},r){const i=t.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const a=s[o];typeof a=="string"&&i.setAttribute(o,a)}return po(this,o=>{i.appendChild(o.toDOM(t,n,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(t){t.writeTypeRef(KN),t.writeKey(this.nodeName)}}const IN=e=>new xr(e.readKey());class ON extends uc{constructor(t,n,r){super(t,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class ls extends nr{constructor(t){super(),this.hookName=t}_copy(){return new ls(this.hookName)}clone(){const t=new ls(this.hookName);return this.forEach((n,r)=>{t.set(r,n)}),t}toDOM(t=document,n={},r){const i=n[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(t){t.writeTypeRef(JN),t.writeKey(this.hookName)}}const NN=e=>new ls(e.readKey());class Si extends Dn{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Si}clone(){const t=new Si;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,r){const i=t.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(t=>{const n=[];for(const i in t.attributes){const s=[];for(const o in t.attributes[i])s.push({key:o,value:t.attributes[i][o]});s.sort((o,a)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(XN)}}const CN=e=>new Si;class xf{constructor(t,n){this.id=t,this.length=n}get deleted(){throw Yn()}mergeWith(t){return!1}write(t,n,r){throw Yn()}integrate(t,n){throw Yn()}}const LN=0;class ln extends xf{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),V0(t.doc.store,this)}write(t,n){t.writeInfo(LN),t.writeLen(this.length-n)}getMissing(t,n){return null}}class mo{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new mo(this.content)}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const MN=e=>new mo(e.readBuf());class go{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new go(this.len)}splice(t){const n=new go(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){sc(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const UN=e=>new go(e.readLen()),_y=(e,t)=>new Tr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class yo{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new yo(_y(this.doc.guid,this.opts))}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const PN=e=>new yo(_y(e.readString(),e.readAny()));class Ai{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Ai(this.embed)}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const DN=e=>new Ai(e.readJSON());class Et{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Et(this.key,this.value)}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){const r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const BN=e=>new Et(e.readKey(),e.readJSON());class yc{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new yc(this.arr)}splice(t){const n=new yc(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const r=this.arr.length;t.writeLen(r-n);for(let i=n;i{const t=e.readLen(),n=[];for(let r=0;r{const t=e.readLen(),n=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const zN=e=>new ir(e.readString()),WN=[wN,EN,xN,IN,RN,NN,CN],GN=0,HN=1,VN=2,KN=3,qN=4,JN=5,XN=6;class Rr{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Rr(this.type._copy())}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(t.beforeState.get(r.id.client)||0)&&t._mergeStructs.push(r):r.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(t,!0),r=r.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const ZN=e=>new Rr(WN[e.readTypeRef()](e)),_c=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new kt(Oe(r,i+n),t,Oe(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),t.redone!==null&&(s.redone=Oe(t.redone.client,t.redone.clock+n)),t.right=s,s.right!==null&&(s.right.left=s),e._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),t.length=n,s};class kt extends xf{constructor(t,n,r,i,s,o,a,c){super(t,c.getLength()),this.origin=r,this.left=n,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?o0:0}set marker(t){(this.info&Xu)>0!==t&&(this.info^=Xu)}get marker(){return(this.info&Xu)>0}get keep(){return(this.info&s0)>0}set keep(t){this.keep!==t&&(this.info^=s0)}get countable(){return(this.info&o0)>0}get deleted(){return(this.info&Ju)>0}set deleted(t){this.deleted!==t&&(this.info^=Ju)}markDeleted(){this.info|=Ju}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Ot(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Ot(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===os&&this.id.client!==this.parent.client&&this.parent.clock>=Ot(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=K0(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Jr(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ln||this.right&&this.right.constructor===ln)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===kt&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===kt&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===os){const r=gf(n,this.parent);r.constructor===ln?this.parent=null:this.parent=r.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=K0(t,t.doc.store,Oe(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),oc(this.origin,i.origin)){if(i.id.client{r.p===t&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),sc(t.deleteSet,this.id.client,this.id.clock,this.length),X0(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw Qn();this.content.gc(t),n?nN(t,this,new ln(this.id,this.length)):this.content=new go(this.length)}write(t,n){const r=n>0?Oe(this.id.client,this.id.clock+n-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&Qa|(r===null?0:cn)|(i===null?0:kr)|(s===null?0:ro);if(t.writeInfo(o),r!==null&&t.writeLeftID(r),i!==null&&t.writeRightID(i),r===null&&i===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const l=tN(a);t.writeParentInfo(!0),t.writeString(l)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else a.constructor===String?(t.writeParentInfo(!0),t.writeString(a)):a.constructor===os?(t.writeParentInfo(!1),t.writeLeftID(a)):Qn();s!==null&&t.writeString(s)}this.content.write(t,n)}}const by=(e,t)=>YN[t&Qa](e),YN=[()=>{Qn()},UN,FN,MN,zN,DN,BN,ZN,jN,PN,()=>{Qn()}],QN=10;class Sn extends xf{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){Qn()}write(t,n){t.writeInfo(QN),ve(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const wy=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},vy="__ $YJS$ __";wy[vy]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438"),wy[vy]=!0;let Rf,If,eC=e=>e();function tC(e,t){if(If)return If(e,t);eC(e)}function xi(e,t,n){if(Rf)return Rf.apply(null,arguments);throw new Error("observable implementation not provided. Call enableReactiveBindings, enableVueBindings or enableMobxBindings.")}function nC(e){Rf=function(t,n,r){const i=e.createAtom(t);return n&&n(),i},If=(t,n)=>e.reaction(t,n,{fireImmediately:!1})}const Ey=new WeakSet;function rC(e){if(Ey.has(e))return e;Ey.add(e);let t;const n=new Map;function r(){if(!t){const f=d=>{(d.changes.added.size||d.changes.deleted.size||d.changes.keys.size||d.changes.delta.length)&&t.reportChanged()};t=xi("map",()=>{e.observe(f)},()=>{e.unobserve(f)})}t.reportObserved(e._implicitObserver)}function i(f){let d=n.get(f);if(!d){const h=p=>{d.reportChanged()};d=xi(f+"",()=>{e.observe(h)},()=>{e.unobserve(h)}),n.set(f,d)}d.reportObserved(e._implicitObserver)}const s=e.get;e.get=function(f){if(typeof f!="number")throw new Error("unexpected");return i(f),Reflect.apply(s,this,arguments)};function o(f){const d=e[f];e[f]=function(){return r(),Reflect.apply(d,this,arguments)}}function a(f){let d=e,h=Object.getOwnPropertyDescriptor(d,f);if(h||(d=Object.getPrototypeOf(d),h=Object.getOwnPropertyDescriptor(d,f)),h||(d=Object.getPrototypeOf(d),h=Object.getOwnPropertyDescriptor(d,f)),!h)throw new Error("property not found");const p=h.get;h.get=function(){return this._disableTracking||r(),Reflect.apply(p,this,arguments)},Object.defineProperty(e,f,h)}function c(f,d){let h=e,p=Object.getOwnPropertyDescriptor(h,f);if(p||(h=Object.getPrototypeOf(h),p=Object.getOwnPropertyDescriptor(h,f)),p||(h=Object.getPrototypeOf(h),p=Object.getOwnPropertyDescriptor(h,f)),!p)throw new Error("property not found");Object.defineProperty(e,d,p)}o("forEach"),o("toJSON"),o("toArray"),o("slice"),o("map"),c("length","lengthUntracked"),a("length");const l=e.push;e.push=function(f){this._disableTracking=!0;const d=l.call(this,f);return this._disableTracking=!1,d};const u=e.slice;return e.slice=function(f,d){this._disableTracking=!0;const h=u.call(this,f,d);return this._disableTracking=!1,h},e}const ky=new WeakSet;function iC(e){if(ky.has(e))return e;ky.add(e);let t;function n(){if(!t){let s=Array.from(e.share.keys());const o=a=>{const c=Array.from(e.share.keys());JSON.stringify(s)!==JSON.stringify(c)&&(s=c,t.reportChanged())};t=xi("map",()=>{e.on("beforeObserverCalls",o)},()=>{e.off("beforeObserverCalls",o)})}t.reportObserved(e._implicitObserver)}const r=e.get;e.get=function(s){if(typeof s!="string")throw new Error("unexpected");const o=Reflect.apply(r,this,arguments);return bc(o),o};function i(s){const o=e[s];let a;e[s]=function(){let c,l=arguments;return n(),a&&a.removeObservers(),a=tC(()=>(c=Reflect.apply(o,e,l),c),()=>t.reportChanged()),c}}return i("toJSON"),Object.defineProperty(e,"keys",{get:()=>(n(),Object.keys(e.share))}),e}const Sy=new WeakSet;function sC(e){if(Sy.has(e))return e;Sy.add(e);let t;const n=new Map;function r(){if(!t){const a=c=>{(c.changes.added.size||c.changes.deleted.size||c.changes.keys.size||c.changes.delta.length)&&t.reportChanged()};t=xi("map",()=>{e.observe(a)},()=>{e.unobserve(a)})}t.reportObserved(e._implicitObserver)}function i(a){let c=n.get(a);if(!c){const l=u=>{u.keysChanged.has(a)&&(u.changes.added.size||u.changes.deleted.size||u.changes.keys.size||u.changes.delta.length)&&c.reportChanged()};c=xi(a,()=>{e.observe(l)},()=>{e.unobserve(l)}),n.set(a,c)}c.reportObserved(e._implicitObserver)}const s=e.get;e.get=function(a){if(typeof a!="string")throw new Error("unexpected");return i(a),Reflect.apply(s,this,arguments)};function o(a){const c=e[a];e[a]=function(){return r(),Reflect.apply(c,this,arguments)}}return o("values"),o("entries"),o("keys"),o("forEach"),o("toJSON"),e}const Ay=new WeakSet;function Ty(e){if(Ay.has(e))return e;Ay.add(e);let t;const n=i=>{t.reportChanged()};t=xi("text",()=>{e.observe(n)},()=>{e.unobserve(n)});function r(i){const s=e[i];e[i]=function(){return t.reportObserved(this._implicitObserver),Reflect.apply(s,this,arguments)}}return r("toString"),r("toJSON"),e}const xy=new WeakSet;function Ry(e){if(xy.has(e))return e;xy.add(e);let t;const n=s=>{(s.changes.added.size||s.changes.deleted.size||s.changes.keys.size||s.changes.delta.length)&&t.reportChanged()};t=xi("xml",()=>{e.observe(n)},()=>{e.unobserve(n)});function r(s){const o=e[s];e[s]=function(){return t.reportObserved(this._implicitObserver),Reflect.apply(o,this,arguments)}}function i(s){let o=e,a=Object.getOwnPropertyDescriptor(o,s);if(a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),!a)throw new Error("property not found");const c=a.get;a.get=function(){return t.reportObserved(this._implicitObserver),Reflect.apply(c,this,arguments)},Object.defineProperty(e,s,a)}return r("toString"),r("toDOM"),r("toArray"),r("getAttribute"),i("firstChild"),e}function bc(e){return e instanceof Si||e instanceof Dn?Ty(e):e instanceof tr?rC(e):e instanceof nr?sC(e):e instanceof Tr||Object.prototype.hasOwnProperty.call(e,"autoLoad")?iC(e):e instanceof rr||e instanceof xr?Ry(e):e}function Iy(e){e.share.forEach(t=>{t.constructor!==at&&bc(t)})}function Oy(e,t){for(let r=e.length-1;r>=t;r--){let i=e[r];if(!i.deleted){var n;if(i instanceof ln)continue;(n=i.content)==null||n.getContent().forEach(s=>{s instanceof at&&bc(s)})}}}const Ny=new WeakSet;function oC(e){Ny.has(e)||(Ny.add(e),bc(e),e.store.clients.forEach(t=>{t&&Oy(t,0)}),Iy(e),e.on("beforeObserverCalls",t=>{Iy(e),t.afterState.forEach((n,r)=>{const i=t.beforeState.get(r)||0;if(i!==n){const s=t.doc.store.clients.get(r);if(!s)return;const o=Pn(s,i);Oy(s,o)}})}))}class _o{constructor(t){this.value=void 0,this.value=t}}function aC(e){return ArrayBuffer.isView(e)?new _o(e):new _o(Object.freeze(e))}function cC(e){const t=function(){var a;let c=(a=this[kn])==null?void 0:a.implicitObserver;return e._implicitObserver=c,e.slice.bind(e).apply(e,arguments).map(u=>{const f=wc(u,c);return c&&typeof f=="object"?no(f,c):f})},n=function(a){return a.map(c=>{const l=Of(c);let u=Ri(l)||l;if(u instanceof _o&&(u=u.value),u instanceof at&&u.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return u})},r=function(){return[].findIndex.apply(t.apply(this),arguments)},i={slice:t,unshift:(...o)=>(e.unshift(n(o)),e.lengthUntracked),push:(...o)=>(e.push(n(o)),e.lengthUntracked),insert:e.insert.bind(e),toJSON:e.toJSON.bind(e),forEach:function(){return[].forEach.apply(t.apply(this),arguments)},every:function(){return[].every.apply(t.apply(this),arguments)},filter:function(){return[].filter.apply(t.apply(this),arguments)},find:function(){return[].find.apply(t.apply(this),arguments)},findIndex:r,some:function(){return[].some.apply(t.apply(this),arguments)},includes:function(){return[].includes.apply(t.apply(this),arguments)},map:function(){return[].map.apply(t.apply(this),arguments)},indexOf:function(){const o=arguments[0];return r.call(this,a=>dC(a,o))},splice:function(){let o=arguments[0]<0?e.length-Math.abs(arguments[0]):arguments[0],a=arguments[1],c=Array.from(Array.from(arguments).slice(2)),l=t.apply(this,[o,Number.isInteger(a)?o+a:void 0]);return e.doc?e.doc.transact(()=>{e.delete(o,a),e.insert(o,n(c))}):(e.delete(o,a),e.insert(o,n(c))),l}},s=[];for(let o in i)s[o]=i[o];return s}function bo(e){if(typeof e=="string"&&e.trim().length){const t=Number(e);if(Number.isInteger(t))return t}return e}function Cy(e,t=new tr){if(t[vt])throw new Error("unexpected");const n=cC(t),r=new Proxy(n,{set:(i,s,o)=>{throw typeof bo(s)!="number"?new Error:new Error("array assignment is not implemented / supported")},get:(i,s,o)=>{const a=bo(s);if(a===vc)return t;if(typeof a=="number"){let u;if(o&&o[kn]){var c;u=(c=o[kn])==null?void 0:c.implicitObserver,t._implicitObserver=u}let f=t.get(a);return f=wc(f,u),f}if(a===Symbol.toStringTag)return"Array";if(a===Symbol.iterator){const u=t.slice();return Reflect.get(u,a)}return a==="length"?t.length:Reflect.get(i,a,o)},deleteProperty:(i,s)=>{const o=bo(s);if(typeof o!="number")throw new Error;return o=0?(t.delete(o),!0):!1},has:(i,s)=>{const o=bo(s);return typeof o!="number"?Reflect.has(i,o):o=0},getOwnPropertyDescriptor(i,s){const o=bo(s);if(o==="length")return{enumerable:!1,configurable:!1,writable:!0};if(typeof o=="number"&&o>=0&&o{const s=[];for(let o=0;o{if(typeof i!="string")throw new Error;const o=Of(s);let a=Ri(o)||o;if(a instanceof _o&&(a=a.value),a instanceof at&&a.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return t.set(i,a),!0},get:(r,i,s)=>{if(i===vc)return t;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[kn]){var a;o=(a=s[kn])==null?void 0:a.implicitObserver,t._implicitObserver=o}let c=t.get(i);return c=wc(c,o),c},deleteProperty:(r,i)=>{if(typeof i!="string")throw new Error;return t.has(i)?(t.delete(i),!0):!1},has:(r,i)=>!!(typeof i=="string"&&t.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&t.has(i))return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(t.keys())});wo.set(t,n);for(let r in e)n[r]=e[r];return n}function lC(e){return e instanceof at}const wo=new WeakMap;function wc(e,t){if(lC(e)){if(e._implicitObserver=t,e instanceof tr||e instanceof nr){if(!wo.has(e)){const n=Of(e);wo.set(e,n)}e=wo.get(e)}else if(e instanceof xr||e instanceof rr||e instanceof Si||e instanceof ls||e instanceof Dn)Hu(e),e.__v_skip=!0;else throw new Error("unknown YType");return e}else{if(e===null)return null;if(typeof e=="object")return aC(e)}return e}function Of(e){if(e==null)return e;if(e=Ri(e)||e,e instanceof tr)return Cy([],e);if(e instanceof nr)return Ly({},e);if(typeof e=="string")return e;if(Array.isArray(e))return Cy(e);if(e instanceof xr||e instanceof rr||e instanceof Si||e instanceof ls)return e;if(e instanceof Dn)return e;if(typeof e=="object")return e instanceof _o?e:Ly(e);if(typeof e=="number"||typeof e=="boolean")return e;throw new Error("invalid")}function uC(e){for(let[t,n]of Object.entries(e))if(Array.isArray(n)){if(n.length!==0)throw new Error("Root Array initializer must always be empty array")}else if(n&&typeof n=="object"){if(Object.keys(n).length!==0||Object.getPrototypeOf(n)!==Object.prototype)throw new Error("Root Object initializer must always be {}")}else if(n!=="xml"&&n!=="text")throw new Error("unknown Root initializer")}function My(e,t,n){let r=t[n];if(!r){n!=="__v_raw"&&n!=="__v_isRef"&&n!=="__v_isReadonly"&&console.warn("property not found on root doc",n);return}return r==="xml"?e.getXmlFragment(n):r==="text"?e.getText(n):Array.isArray(r)?e.getArray(n):e.getMap(n)}function fC(e,t){if(e[vt])throw new Error("unexpected");uC(t);const n=new Proxy({},{set:(r,i,s)=>{throw typeof i!="string"?new Error:new Error("cannot set new elements on root doc")},get:(r,i,s)=>{if(i===vc)return e;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[kn]){var a;o=(a=s[kn])==null?void 0:a.implicitObserver,e._implicitObserver=o}if(i==="toJSON"){for(let u of Object.keys(t))My(e,t,u);return Reflect.get(e,i)}let c=My(e,t,i);return c=wc(c,o),c},deleteProperty:(r,i)=>{throw new Error("deleteProperty not available for doc")},has:(r,i)=>!!(typeof i=="string"&&e.share.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&e.share.has(i)||i==="toJSON")return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(e.share.keys())});return wo.set(e,n),n}nC(OI);const vc=Symbol("INTERNAL_SYMBOL");function Uy(e,t){const n=Ri(e)||e;if(!n)throw new Error("not a valid synced object");return n instanceof Tr?(n.on("update",t),()=>{n.off("update",t)}):(n.observeDeep(t),()=>{n.unobserveDeep(t)})}function hC(e){const t=Ri(e);if(!(t instanceof Tr))throw new Error("store is not a valid syncedStore that maps to a Y.Doc");return t}function Ri(e){if(typeof e!="object"||e===null)return;const t=e[vc];return t&&(Hu(t),t.__v_skip=!0),t}function dC(e,t){if(e===t)return!0;if(typeof e=="object"&&typeof t=="object"){const n=Ri(e),r=Ri(t);return!n||!r?!1:n===r}return!1}function pC(e,t=new Tr){return oC(t),fC(t,e)}var Re={};/** +`,n.startOffset,n.endOffset??NaN,n.startLine??NaN,n.endLine??NaN,n.startColumn??NaN,n.endColumn??NaN)),t}function Pm(e,t=!0){const[n,...r]=e;switch(Pe(n)){default:return t?{type:fe.OBJECT,values:e}:{type:fe.CONST,values:e};case"loader":return{type:fe.LOADER,values:r};case"board":return{type:fe.BOARD,values:r};case"object":return{type:fe.OBJECT,values:r};case"terrain":return{type:fe.TERRAIN,values:r};case"charset":return{type:fe.CHARSET,values:r};case"palette":return{type:fe.PALETTE,values:r};case"rn":case"range":return{type:fe.RANGE,values:r};case"sl":case"select":return{type:fe.SELECT,values:r};case"nm":case"number":return{type:fe.NUMBER,values:r};case"tx":case"text":return{type:fe.TEXT,values:r};case"ln":case"link":return{type:fe.LINK,values:r};case"hk":case"hotkey":return{type:fe.HOTKEY,values:r};case"scroll":return{type:fe.SCROLL,values:r};case"copyit":return{type:fe.COPYIT,values:r}}}function bn(e){switch(e){case fe.LOADER:return"loader";case fe.BOARD:return"board";case fe.OBJECT:return"object";case fe.TERRAIN:return"terrain";case fe.CHARSET:return"charset";case fe.PALETTE:return"palette";case fe.CONST:return"const";case fe.RANGE:return"range";case fe.SELECT:return"select";case fe.NUMBER:return"number";case fe.TEXT:return"text";case fe.LINK:return"link";case fe.HOTKEY:return"hotkey";case fe.SCROLL:return"scroll";case fe.COPYIT:return"copyit"}}var Dm={},br={},wr={};Object.defineProperty(wr,"__esModule",{value:!0}),wr.throwUnsupportedData=wr.throwUnknownDataType=wr.getType=void 0;function Bm(e){return Object.prototype.toString.call(e)}wr.getType=Bm;function Qx(e){throw new TypeError("unsupported data type: "+Bm(e))}wr.throwUnknownDataType=Qx;function eR(e){throw new TypeError("unsupported data type: "+e)}wr.throwUnsupportedData=eR;var Mt={},Ut={};Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.s_to_num=Ut.int_str_to_s=Ut.num_to_s=Ut.big_int_to_s=Ut.int_to_s=Ut.s_to_big_int=Ut.s_to_int=void 0;let vr="";for(let e=0;e<10;e++){const t=String.fromCharCode(48+e);vr+=t}for(let e=0;e<26;e++){const t=String.fromCharCode(65+e);vr+=t}for(let e=0;e<26;e++){const t=String.fromCharCode(97+e);vr+=t}const qi=vr.length,au={};for(let e=0;e=0;r--){const i=e[r];let s=au[i];s*=n,t+=s,n*=qi}return t}Ut.s_to_int=cu;function Fm(e){let t=BigInt(0),n=BigInt(1);const r=BigInt(qi);for(let i=e.length-1;i>=0;i--){const s=e[i];let o=BigInt(au[s]);o*=n,t+=o,n*=r}return t}Ut.s_to_big_int=Fm;function lu(e){if(e===0)return vr[0];const t=[];for(;e!==0;){const n=e%qi,r=vr[n];t.push(r),e-=n,e/=qi}return t.reverse().join("")}Ut.int_to_s=lu;function $m(e){const t=BigInt(0),n=BigInt(qi);if(e===t)return vr[0];const r=[];for(;e!==t;){const i=e%n,s=vr[Number(i)];r.push(s),e/=n}return r.reverse().join("")}Ut.big_int_to_s=$m;function jm(e){return e.split("").reverse().join("")}function zm(e){if(e<0)return"-"+zm(-e);let[t,n]=e.toString().split(".");if(!n)return lu(e);let r;n&&([n,r]=n.split("e")),t=Na(t),n=jm(n),n=Na(n);let i=t+"."+n;if(r){switch(i+=".",r[0]){case"+":r=r.slice(1);break;case"-":i+="-",r=r.slice(1);break}r=Na(r),i+=r}return i}Ut.num_to_s=zm;function Na(e){const t=+e;return t.toString()===e&&t+1!==t&&t-1!==t?lu(t):":"+$m(BigInt(e))}Ut.int_str_to_s=Na;function uu(e){return e[0]===":"?Fm(e.substring(1)).toString():cu(e).toString()}function Wm(e){if(e[0]==="-")return-Wm(e.substr(1));let[t,n,r]=e.split(".");if(!n)return cu(t);t=uu(t),n=uu(n),n=jm(n);let i=t+"."+n;if(r){i+="e";let s=!1;r[0]==="-"&&(s=!0,r=r.slice(1)),r=uu(r),i+=s?-r:+r}return+i}Ut.s_to_num=Wm,Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.decodeStr=Mt.encodeStr=Mt.decodeBool=Mt.encodeBool=Mt.decodeKey=Mt.decodeNum=Mt.encodeNum=void 0;const fu=Ut;function tR(e){return"n|"+(0,fu.num_to_s)(e)}Mt.encodeNum=tR;function nR(e){return e=e.replace("n|",""),(0,fu.s_to_num)(e)}Mt.decodeNum=nR;function rR(e){return typeof e=="number"?e:(0,fu.s_to_int)(e)}Mt.decodeKey=rR;function iR(e){return e?"b|T":"b|F"}Mt.encodeBool=iR;function sR(e){switch(e){case"b|T":return!0;case"b|F":return!1}return!!e}Mt.decodeBool=sR;function oR(e){switch(e[0]+e[1]){case"b|":case"o|":case"n|":case"a|":case"s|":e="s|"+e}return e}Mt.encodeStr=oR;function aR(e){return e[0]+e[1]==="s|"?e.substr(2):e}Mt.decodeStr=aR;var an={},js={};Object.defineProperty(js,"__esModule",{value:!0}),js.config=void 0,js.config={sort_key:!1,error_on_nan:!1,error_on_infinite:!1},Object.defineProperty(an,"__esModule",{value:!0}),an.addValue=an.makeInMemoryMemory=an.makeInMemoryCache=an.makeInMemoryStore=an.memToValues=void 0;const hu=js,du=wr,pu=Mt,cR=Ut;function lR(e){return e.store.toArray()}an.memToValues=lR;function Gm(){const e=[];return{forEach(t){for(let n=0;n(vu(),this?this.unpack(t,n):Gs.prototype.unpack.call(Km,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<"u"?Buffer.from(t):new Uint8Array(t)),typeof n=="object"?(wn=n.end||t.length,U=n.start||0):(U=0,wn=n>-1?n:t.length),Jn=0,jr=null,Tt=null,ie=t;try{xe=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(r){throw ie=null,t instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(t&&typeof t=="object"?t.constructor.name:typeof t))}if(this instanceof Gs){if(Ke=this,this.structures)return Ie=this.structures,La(n);(!Ie||Ie.length>0)&&(Ie=[])}else Ke=Km,(!Ie||Ie.length>0)&&(Ie=[]);return La(n)}unpackMultiple(t,n){let r,i=0;try{zr=!0;let s=t.length,o=this?this.unpack(t,s):Ma.unpack(t,s);if(n){if(n(o,i,U)===!1)return;for(;Ur.slice(0)));for(let r=0,i=t.length;r=32&&(s.highByte=r-32>>5))}t.sharedLength=t.length;for(let r in n||[])if(r>=0){let i=t[r],s=n[r];s&&(i&&((t.restoreStructures||(t.restoreStructures=[]))[r]=i),t[r]=s)}return this.structures=t}decode(t,n){return this.unpack(t,n)}}function La(e){try{if(!Ke.trusted&&!zr){let n=Ie.sharedLength||0;n=32&&Zm?(t=Zm(ie,U,wn,Ke),ie=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),U=wn):t=lt(),Tt&&(U=Tt.postBundlePosition,Tt=null),zr&&(Ie.restoreStructures=null),U==wn)Ie&&Ie.restoreStructures&&Ym(),Ie=null,ie=null,Er&&(Er=null);else{if(U>wn)throw new Error("Unexpected end of MessagePack data");if(!zr){let n;try{n=JSON.stringify(t,(r,i)=>typeof i=="bigint"?`${i}n`:i).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return t}catch(t){throw Ie&&Ie.restoreStructures&&Ym(),vu(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer")||U>wn)&&(t.incomplete=!0),t}}function Ym(){for(let e in Ie.restoreStructures)Ie[e]=Ie.restoreStructures[e];Ie.restoreStructures=null}function lt(){let e=ie[U++];if(e<160)if(e<128){if(e<64)return e;{let t=Ie[e&63]||Ke.getStructures&&eg()[e&63];return t?(t.read||(t.read=yu(t,e&63)),t.read()):e}}else if(e<144)if(e-=128,Ke.mapsAsObjects){let t={};for(let n=0;n=U)return jr.slice(U-vn,(U+=t)-vn);if(Jn==0&&wn<140){let n=t<16?bu(t):rg(t);if(n!=null)return n}return _u(t)}else{let t;switch(e){case 192:return null;case 193:return Tt?(t=lt(),t>0?Tt[1].slice(Tt.position1,Tt.position1+=t):Tt[0].slice(Tt.position0,Tt.position0-=t)):Jm;case 194:return!1;case 195:return!0;case 196:if(t=ie[U++],t===void 0)throw new Error("Unexpected end of buffer");return wu(t);case 197:return t=xe.getUint16(U),U+=2,wu(t);case 198:return t=xe.getUint32(U),U+=4,wu(t);case 199:return mi(ie[U++]);case 200:return t=xe.getUint16(U),U+=2,mi(t);case 201:return t=xe.getUint32(U),U+=4,mi(t);case 202:if(t=xe.getFloat32(U),Ke.useFloat32>2){let n=Eu[(ie[U]&127)<<1|ie[U+1]>>7];return U+=4,(n*t+(t>0?.5:-.5)>>0)/n}return U+=4,t;case 203:return t=xe.getFloat64(U),U+=8,t;case 204:return ie[U++];case 205:return t=xe.getUint16(U),U+=2,t;case 206:return t=xe.getUint32(U),U+=4,t;case 207:return Ke.int64AsType==="number"?(t=xe.getUint32(U)*4294967296,t+=xe.getUint32(U+4)):Ke.int64AsType==="string"?t=xe.getBigUint64(U).toString():Ke.int64AsType==="auto"?(t=xe.getBigUint64(U),t<=BigInt(2)<=BigInt(-2)<=U?jr.slice(U-vn,(U+=t)-vn):wR(t);case 218:return t=xe.getUint16(U),U+=2,Jn>=U?jr.slice(U-vn,(U+=t)-vn):vR(t);case 219:return t=xe.getUint32(U),U+=4,Jn>=U?jr.slice(U-vn,(U+=t)-vn):ER(t);case 220:return t=xe.getUint16(U),U+=2,tg(t);case 221:return t=xe.getUint32(U),U+=4,tg(t);case 222:return t=xe.getUint16(U),U+=2,ng(t);case 223:return t=xe.getUint32(U),U+=4,ng(t);default:if(e>=224)return e-256;if(e===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+e)}}}const bR=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function yu(e,t){function n(){if(n.count++>Xm){let i=e.read=new Function("r","return function(){return "+(Ke.freezeData?"Object.freeze":"")+"({"+e.map(s=>s==="__proto__"?"__proto_:r()":bR.test(s)?s+":r()":"["+JSON.stringify(s)+"]:r()").join(",")+"})}")(lt);return e.highByte===0&&(e.read=Qm(t,e.read)),i()}let r={};for(let i=0,s=e.length;ifunction(){let n=ie[U++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=Ie[r]||eg()[r];if(!i)throw new Error("Record id is not defined for "+r);return i.read||(i.read=yu(i,e)),i.read()};function eg(){let e=ug(()=>(ie=null,Ke.getStructures()));return Ie=Ke._mergeStructures(e,Ie)}var _u=Hs,wR=Hs,vR=Hs,ER=Hs;function Hs(e){let t;if(e<16&&(t=bu(e)))return t;if(e>64&&gu)return gu.decode(ie.subarray(U,U+=e));const n=U+e,r=[];for(t="";U65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c)}else r.push(i);r.length>=4096&&(t+=xt.apply(String,r),r.length=0)}return r.length>0&&(t+=xt.apply(String,r)),t}function tg(e){let t=new Array(e);for(let n=0;n0){U=t;return}n[r]=i}return xt.apply(String,n)}function bu(e){if(e<4)if(e<2){if(e===0)return"";{let t=ie[U++];if((t&128)>1){U-=1;return}return xt(t)}}else{let t=ie[U++],n=ie[U++];if((t&128)>0||(n&128)>0){U-=2;return}if(e<3)return xt(t,n);let r=ie[U++];if((r&128)>0){U-=3;return}return xt(t,n,r)}else{let t=ie[U++],n=ie[U++],r=ie[U++],i=ie[U++];if((t&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){U-=4;return}if(e<6){if(e===4)return xt(t,n,r,i);{let s=ie[U++];if((s&128)>0){U-=5;return}return xt(t,n,r,i,s)}}else if(e<8){let s=ie[U++],o=ie[U++];if((s&128)>0||(o&128)>0){U-=6;return}if(e<7)return xt(t,n,r,i,s,o);let a=ie[U++];if((a&128)>0){U-=7;return}return xt(t,n,r,i,s,o,a)}else{let s=ie[U++],o=ie[U++],a=ie[U++],c=ie[U++];if((s&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){U-=8;return}if(e<10){if(e===8)return xt(t,n,r,i,s,o,a,c);{let l=ie[U++];if((l&128)>0){U-=9;return}return xt(t,n,r,i,s,o,a,c,l)}}else if(e<12){let l=ie[U++],u=ie[U++];if((l&128)>0||(u&128)>0){U-=10;return}if(e<11)return xt(t,n,r,i,s,o,a,c,l,u);let f=ie[U++];if((f&128)>0){U-=11;return}return xt(t,n,r,i,s,o,a,c,l,u,f)}else{let l=ie[U++],u=ie[U++],f=ie[U++],d=ie[U++];if((l&128)>0||(u&128)>0||(f&128)>0||(d&128)>0){U-=12;return}if(e<14){if(e===12)return xt(t,n,r,i,s,o,a,c,l,u,f,d);{let h=ie[U++];if((h&128)>0){U-=13;return}return xt(t,n,r,i,s,o,a,c,l,u,f,d,h)}}else{let h=ie[U++],p=ie[U++];if((h&128)>0||(p&128)>0){U-=14;return}if(e<15)return xt(t,n,r,i,s,o,a,c,l,u,f,d,h,p);let m=ie[U++];if((m&128)>0){U-=15;return}return xt(t,n,r,i,s,o,a,c,l,u,f,d,h,p,m)}}}}}function ig(){let e=ie[U++],t;if(e<192)t=e-160;else switch(e){case 217:t=ie[U++];break;case 218:t=xe.getUint16(U),U+=2;break;case 219:t=xe.getUint32(U),U+=4;break;default:throw new Error("Expected string")}return Hs(t)}function wu(e){return Ke.copyBuffers?Uint8Array.prototype.slice.call(ie,U,U+=e):ie.subarray(U,U+=e)}function mi(e){let t=ie[U++];if(en[t]){let n;return en[t](ie.subarray(U,n=U+=e),r=>{U=r;try{return lt()}finally{U=n}})}else throw new Error("Unknown extension type "+t)}var sg=new Array(4096);function og(){let e=ie[U++];if(e>=160&&e<192){if(e=e-160,Jn>=U)return jr.slice(U-vn,(U+=e)-vn);if(!(Jn==0&&wn<180))return _u(e)}else return U--,ag(lt());let t=(e<<5^(e>1?xe.getUint16(U):e>0?ie[U]:0))&4095,n=sg[t],r=U,i=U+e-3,s,o=0;if(n&&n.bytes==e){for(;r{let n=lt().map(ag),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=Ie[e];return i&&(i.isShared||zr)&&((Ie.restoreStructures||(Ie.restoreStructures=[]))[e]=i),Ie[e]=n,n.read=yu(n,r),n.read()};en[0]=()=>{},en[0].noBuffer=!0,en[66]=e=>{let t=e.length,n=BigInt(e[0]&128?e[0]-256:e[0]);for(let r=1;r{let e=lt();return(kR[e[0]]||Error)(e[1],{cause:e[2]})},en[105]=e=>{if(Ke.structuredClone===!1)throw new Error("Structured clone extension is disabled");let t=xe.getUint32(U-4);Er||(Er=new Map);let n=ie[U],r;n>=144&&n<160||n==220||n==221?r=[]:r={};let i={target:r};Er.set(t,i);let s=lt();return i.used?Object.assign(r,s):(i.target=s,s)},en[112]=e=>{if(Ke.structuredClone===!1)throw new Error("Structured clone extension is disabled");let t=xe.getUint32(U-4),n=Er.get(t);return n.used=!0,n.target},en[115]=()=>new Set(lt());const lg=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(e=>e+"Array");let SR=typeof globalThis=="object"?globalThis:window;en[116]=e=>{let t=e[0],n=lg[t];if(!n){if(t===16){let r=new ArrayBuffer(e.length-1);return new Uint8Array(r).set(e.subarray(1)),r}throw new Error("Could not find typed array for code "+t)}return new SR[n](Uint8Array.prototype.slice.call(e,1).buffer)},en[120]=()=>{let e=lt();return new RegExp(e[0],e[1])};const AR=[];en[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=U;return U+=t-e.length,Tt=AR,Tt=[ig(),ig()],Tt.position0=0,Tt.position1=0,Tt.postBundlePosition=U,U=n,lt()},en[255]=e=>e.length==4?new Date((e[0]*16777216+(e[1]<<16)+(e[2]<<8)+e[3])*1e3):e.length==8?new Date(((e[0]<<22)+(e[1]<<14)+(e[2]<<6)+(e[3]>>2))/1e6+((e[3]&3)*4294967296+e[4]*16777216+(e[5]<<16)+(e[6]<<8)+e[7])*1e3):e.length==12?new Date(((e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3])/1e6+((e[4]&128?-281474976710656:0)+e[6]*1099511627776+e[7]*4294967296+e[8]*16777216+(e[9]<<16)+(e[10]<<8)+e[11])*1e3):new Date("invalid");function ug(e){let t=wn,n=U,r=vn,i=Jn,s=jr,o=Er,a=Tt,c=new Uint8Array(ie.slice(0,wn)),l=Ie,u=Ie.slice(0,Ie.length),f=Ke,d=zr,h=e();return wn=t,U=n,vn=r,Jn=i,jr=s,Er=o,Tt=a,ie=c,zr=d,Ie=l,Ie.splice(0,Ie.length,...u),Ke=f,xe=new DataView(ie.buffer,ie.byteOffset,ie.byteLength),h}function vu(){ie=null,Er=null,Ie=null}const Eu=new Array(147);for(let e=0;e<256;e++)Eu[e]=+("1e"+Math.floor(45.15-e*.30103));var Ma=new Gs({useRecords:!1});const TR=Ma.unpack;Ma.unpackMultiple,Ma.unpack;let xR=new Float32Array(1);new Uint8Array(xR.buffer,0,4);let Ua;try{Ua=new TextEncoder}catch{}let ku,fg;const Pa=typeof Buffer<"u",Da=Pa?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,hg=Pa?Buffer:Uint8Array,dg=Pa?4294967296:2144337920;let j,Vs,qe,P=0,Wt,nt=null,RR;const IR=21760,OR=/[\u0080-\uFFFF]/,Xi=Symbol("record-id");class NR extends Gs{constructor(t){super(t),this.offset=0;let n,r,i,s,o=hg.prototype.utf8Write?function(E,g){return j.utf8Write(E,g,j.byteLength-g)}:Ua&&Ua.encodeInto?function(E,g){return Ua.encodeInto(E,j.subarray(g)).written}:!1,a=this;t||(t={});let c=t&&t.sequential,l=t.structures||t.saveStructures,u=t.maxSharedStructures;if(u==null&&(u=l?32:0),u>8160)throw new Error("Maximum maxSharedStructure is 8160");t.structuredClone&&t.moreTypes==null&&(this.moreTypes=!0);let f=t.maxOwnStructures;f==null&&(f=l?32:64),!this.structures&&t.useRecords!=!1&&(this.structures=[]);let d=u>32||f+u>64,h=u+64,p=u+f+64;if(p>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let m=[],b=0,_=0;this.pack=this.encode=function(E,g){if(j||(j=new Da(8192),qe=j.dataView||(j.dataView=new DataView(j.buffer,0,8192)),P=0),Wt=j.length-10,Wt-P<2048?(j=new Da(j.length),qe=j.dataView||(j.dataView=new DataView(j.buffer,0,j.length)),Wt=j.length-10,P=0):P=P+7&2147483640,n=P,g&BR&&(P+=g&255),s=a.structuredClone?new Map:null,a.bundleStrings&&typeof E!="string"?(nt=[],nt.size=1/0):nt=null,i=a.structures,i){i.uninitialized&&(i=a._mergeStructures(a.getStructures()));let W=i.sharedLength||0;if(W>u)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let B=0;B$.offset>F.offset?1:-1),Z=B.length,H=-1;for(;W&&Z>0;){let $=B[--Z].offset+n;$W.position+n?H>=0&&(H+=6):(H>=0&&(qe.setUint32(W.position+n,qe.getUint32(W.position+n)+H),H=-1),W=W.previous,Z++)}H>=0&&W&&qe.setUint32(W.position+n,qe.getUint32(W.position+n)+H),P+=B.length*6,P>Wt&&x(P),a.offset=P;let Y=LR(j.subarray(n,P),B);return s=null,Y}return a.offset=P,g&PR?(j.start=n,j.end=P,j):j.subarray(n,P)}catch(W){throw N=W,W}finally{if(i&&(w(),r&&a.saveStructures)){let W=i.sharedLength||0,B=j.subarray(n,P),Z=MR(i,a);if(!N)return a.saveStructures(Z,Z.isCompatible)===!1?a.pack(E,g):(a.lastNamedStructuresLength=W,j.length>1073741824&&(j=null),B)}j.length>1073741824&&(j=null),g&DR&&(P=n)}};const w=()=>{_<10&&_++;let E=i.sharedLength||0;if(i.length>E&&!c&&(i.length=E),b>1e4)i.transitions=null,_=0,b=0,m.length>0&&(m=[]);else if(m.length>0&&!c){for(let g=0,N=m.length;g{var g=E.length;g<16?j[P++]=144|g:g<65536?(j[P++]=220,j[P++]=g>>8,j[P++]=g&255):(j[P++]=221,qe.setUint32(P,g),P+=4);for(let N=0;N{P>Wt&&(j=x(P));var g=typeof E,N;if(g==="string"){let W=E.length;if(nt&&W>=4&&W<4096){if((nt.size+=W)>IR){let Y,$=(nt[0]?nt[0].length*3+nt[1].length:0)+10;P+$>Wt&&(j=x(P+$));let F;nt.position?(F=nt,j[P]=200,P+=3,j[P++]=98,Y=P-n,P+=4,gg(n,S,0),qe.setUint16(Y+n-3,P-n-Y)):(j[P++]=214,j[P++]=98,Y=P-n,P+=4),nt=["",""],nt.previous=F,nt.size=0,nt.position=Y}let H=OR.test(E);nt[H?0:1]+=E,j[P++]=193,S(H?-W:W);return}let B;W<32?B=1:W<256?B=2:W<65536?B=3:B=5;let Z=W*3;if(P+Z>Wt&&(j=x(P+Z)),W<64||!o){let H,Y,$,F=P+B;for(H=0;H>6|192,j[F++]=Y&63|128):(Y&64512)===55296&&(($=E.charCodeAt(H+1))&64512)===56320?(Y=65536+((Y&1023)<<10)+($&1023),H++,j[F++]=Y>>18|240,j[F++]=Y>>12&63|128,j[F++]=Y>>6&63|128,j[F++]=Y&63|128):(j[F++]=Y>>12|224,j[F++]=Y>>6&63|128,j[F++]=Y&63|128);N=F-P-B}else N=o(E,P+B);N<32?j[P++]=160|N:N<256?(B<2&&j.copyWithin(P+2,P+1,P+1+N),j[P++]=217,j[P++]=N):N<65536?(B<3&&j.copyWithin(P+3,P+2,P+2+N),j[P++]=218,j[P++]=N>>8,j[P++]=N&255):(B<5&&j.copyWithin(P+5,P+3,P+3+N),j[P++]=219,qe.setUint32(P,N),P+=4),P+=N}else if(g==="number")if(E>>>0===E)E<32||E<128&&this.useRecords===!1||E<64&&!this.randomAccessStructure?j[P++]=E:E<256?(j[P++]=204,j[P++]=E):E<65536?(j[P++]=205,j[P++]=E>>8,j[P++]=E&255):(j[P++]=206,qe.setUint32(P,E),P+=4);else if(E>>0===E)E>=-32?j[P++]=256+E:E>=-128?(j[P++]=208,j[P++]=E+256):E>=-32768?(j[P++]=209,qe.setInt16(P,E),P+=2):(j[P++]=210,qe.setInt32(P,E),P+=4);else{let W;if((W=this.useFloat32)>0&&E<4294967296&&E>=-2147483648){j[P++]=202,qe.setFloat32(P,E);let B;if(W<4||(B=E*Eu[(j[P]&127)<<1|j[P+1]>>7])>>0===B){P+=4;return}else P--}j[P++]=203,qe.setFloat64(P,E),P+=8}else if(g==="object"||g==="function")if(!E)j[P++]=192;else{if(s){let B=s.get(E);if(B){if(!B.id){let Z=s.idsToInsert||(s.idsToInsert=[]);B.id=Z.push(B)}j[P++]=214,j[P++]=112,qe.setUint32(P,B.id),P+=4;return}else s.set(E,{offset:P-n})}let W=E.constructor;if(W===Object)M(E);else if(W===Array)v(E);else if(W===Map)if(this.mapAsEmptyObject)j[P++]=128;else{N=E.size,N<16?j[P++]=128|N:N<65536?(j[P++]=222,j[P++]=N>>8,j[P++]=N&255):(j[P++]=223,qe.setUint32(P,N),P+=4);for(let[B,Z]of E)S(B),S(Z)}else{for(let B=0,Z=ku.length;B(j=$,$=null,P+=ee,P>Wt&&x(P),{target:j,targetView:qe,position:P-ee}),S)}finally{$&&(j=$,qe=F,P=ue,Wt=j.length-10)}Q&&(Q.length+P>Wt&&x(Q.length+P),P=CR(Q,j,P,Y.type));return}}if(Array.isArray(E))v(E);else{if(E.toJSON){const B=E.toJSON();if(B!==E)return S(B)}if(g==="function")return S(this.writeFunction&&this.writeFunction(E));M(E)}}}else if(g==="boolean")j[P++]=E?195:194;else if(g==="bigint"){if(E=-(BigInt(1)<0)j[P++]=207,qe.setBigUint64(P,E);else if(this.largeBigIntToFloat)j[P++]=203,qe.setFloat64(P,Number(E));else{if(this.largeBigIntToString)return S(E.toString());if(this.useBigIntExtension&&E-(BigInt(2)**BigInt(1023))){j[P++]=199,P++,j[P++]=66;let W=[],B;do{let Z=E&BigInt(255);B=(Z&BigInt(128))===(E>=BigInt(8)}while(!((E===BigInt(0)||E===BigInt(-1))&&B));j[P-2]=W.length;for(let Z=W.length;Z>0;)j[P++]=Number(W[--Z]);return}else throw new RangeError(E+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}P+=8}else if(g==="undefined")this.encodeUndefinedAsNil?j[P++]=192:(j[P++]=212,j[P++]=0,j[P++]=0);else throw new Error("Unknown type: "+g)},L=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?E=>{let g;if(this.skipValues){g=[];for(let B in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(B))&&!this.skipValues.includes(E[B])&&g.push(B)}else g=Object.keys(E);let N=g.length;N<16?j[P++]=128|N:N<65536?(j[P++]=222,j[P++]=N>>8,j[P++]=N&255):(j[P++]=223,qe.setUint32(P,N),P+=4);let W;if(this.coercibleKeyAsNumber)for(let B=0;B{j[P++]=222;let g=P-n;P+=2;let N=0;for(let W in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(W))&&(S(W),S(E[W]),N++);if(N>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');j[g+++n]=N>>8,j[g+n]=N&255},I=this.useRecords===!1?L:t.progressiveRecords&&!d?E=>{let g,N=i.transitions||(i.transitions=Object.create(null)),W=P++-n,B;for(let Z in E)if(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(Z)){if(g=N[Z],g)N=g;else{let H=Object.keys(E),Y=N;N=i.transitions;let $=0;for(let F=0,ue=H.length;F{let g,N=i.transitions||(i.transitions=Object.create(null)),W=0;for(let Z in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(Z))&&(g=N[Z],g||(g=N[Z]=Object.create(null),W++),N=g);let B=N[Xi];B?B>=96&&d?(j[P++]=((B-=96)&31)+96,j[P++]=B>>5):j[P++]=B:V(N,N.__keys__||Object.keys(E),W);for(let Z in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(Z))&&S(E[Z])},T=typeof this.useRecords=="function"&&this.useRecords,M=T?E=>{T(E)?I(E):L(E)}:I,x=E=>{let g;if(E>16777216){if(E-n>dg)throw new Error("Packed buffer would be larger than maximum buffer size");g=Math.min(dg,Math.round(Math.max((E-n)*(E>67108864?1.25:2),4194304)/4096)*4096)}else g=(Math.max(E-n<<2,j.length-1)>>12)+1<<12;let N=new Da(g);return qe=N.dataView||(N.dataView=new DataView(N.buffer,0,g)),E=Math.min(E,j.length),j.copy?j.copy(N,0,n,E):N.set(j.slice(n,E)),P-=n,n=0,Wt=N.length-10,j=N},V=(E,g,N)=>{let W=i.nextId;W||(W=64),W=p&&(W=h),i.nextId=W+1);let B=g.highByte=W>=96&&d?W-96>>5:-1;E[Xi]=W,E.__keys__=g,i[W-64]=g,W=0?(j[P++]=(W&31)+96,j[P++]=B):j[P++]=W):(B>=0?(j[P++]=213,j[P++]=114,j[P++]=(W&31)+96,j[P++]=B):(j[P++]=212,j[P++]=114,j[P++]=W),N&&(b+=_*N),m.length>=f&&(m.shift()[Xi]=0),m.push(E),S(g))},oe=(E,g,N,W)=>{let B=j,Z=P,H=Wt,Y=n;j=Vs,P=0,n=0,j||(Vs=j=new Da(8192)),Wt=j.length-10,V(E,g,W),Vs=j;let $=P;if(j=B,P=Z,Wt=H,n=Y,$>1){let F=P+$-1;F>Wt&&x(F);let ue=N+n;j.copyWithin(ue+$,ue+1,P),j.set(Vs.slice(0,$),ue),P=F}else j[N+n]=Vs[0]},O=E=>{let g=RR(E,j,n,P,i,x,(N,W,B)=>{if(B)return r=!0;P=W;let Z=j;return S(N),w(),Z!==j?{position:P,targetView:qe,target:j}:P},this);if(g===0)return M(E);P=g}}useBuffer(t){j=t,j.dataView||(j.dataView=new DataView(j.buffer,j.byteOffset,j.byteLength)),P=0}set position(t){P=t}get position(){return P}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}}fg=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,qm],ku=[{pack(e,t,n){let r=e.getTime()/1e3;if((this.useTimestamp32||e.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:i,targetView:s,position:o}=t(6);i[o++]=214,i[o++]=255,s.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:i,targetView:s,position:o}=t(10);i[o++]=215,i[o++]=255,s.setUint32(o,e.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),s.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return t(0),n(this.onInvalidDate());let{target:i,targetView:s,position:o}=t(3);i[o++]=212,i[o++]=255,i[o++]=255}else{let{target:i,targetView:s,position:o}=t(15);i[o++]=199,i[o++]=12,i[o++]=255,s.setUint32(o,e.getMilliseconds()*1e6),s.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(e,t,n){if(this.setAsEmptyObject)return t(0),n({});let r=Array.from(e),{target:i,position:s}=t(this.moreTypes?3:0);this.moreTypes&&(i[s++]=212,i[s++]=115,i[s++]=0),n(r)}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),n([e.name,e.message,e.cause])}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),n([e.source,e.flags])}},{pack(e,t){this.moreTypes?pg(e,16,t):mg(Pa?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==hg&&this.moreTypes?pg(e,lg.indexOf(n.name),t):mg(e,t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function pg(e,t,n,r){let i=e.byteLength;if(i+1<256){var{target:s,position:o}=n(4+i);s[o++]=199,s[o++]=i+1}else if(i+1<65536){var{target:s,position:o}=n(5+i);s[o++]=200,s[o++]=i+1>>8,s[o++]=i+1&255}else{var{target:s,position:o,targetView:a}=n(7+i);s[o++]=201,a.setUint32(o,i+1),o+=4}s[o++]=116,s[o++]=t,e.buffer||(e=new Uint8Array(e)),s.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o)}function mg(e,t){let n=e.byteLength;var r,i;if(n<256){var{target:r,position:i}=t(n+2);r[i++]=196,r[i++]=n}else if(n<65536){var{target:r,position:i}=t(n+3);r[i++]=197,r[i++]=n>>8,r[i++]=n&255}else{var{target:r,position:i,targetView:s}=t(n+5);r[i++]=198,s.setUint32(i,n),i+=4}r.set(e,i)}function CR(e,t,n,r){let i=e.length;switch(i){case 1:t[n++]=212;break;case 2:t[n++]=213;break;case 4:t[n++]=214;break;case 8:t[n++]=215;break;case 16:t[n++]=216;break;default:i<256?(t[n++]=199,t[n++]=i):i<65536?(t[n++]=200,t[n++]=i>>8,t[n++]=i&255):(t[n++]=201,t[n++]=i>>24,t[n++]=i>>16&255,t[n++]=i>>8&255,t[n++]=i&255)}return t[n++]=r,t.set(e,n),n+=i,n}function LR(e,t){let n,r=t.length*6,i=e.length-r;for(;n=t.pop();){let s=n.offset,o=n.id;e.copyWithin(s+r,s,i),r-=6;let a=s+r;e[a++]=214,e[a++]=105,e[a++]=o>>24,e[a++]=o>>16&255,e[a++]=o>>8&255,e[a++]=o&255,i=s}return e}function gg(e,t,n){if(nt.length>0){qe.setUint32(nt.position+e,P+n-nt.position-e),nt.stringsPosition=P-e;let r=nt;nt=null,t(r[0]),t(r[1])}}function MR(e,t){return e.isCompatible=n=>{let r=!n||(t.lastNamedStructuresLength||0)===n.length;return r||t._mergeStructures(n),r},e}let yg=new NR({useRecords:!1});const UR=yg.pack;yg.pack;const PR=512,DR=1024,BR=2048;function gi(){return null}function Ks(e,t,n={}){if(!k(e))return;const r=[],i=Object.keys(e);for(let s=0;s(e[e.kind=0]="kind",e[e.id=1]="id",e[e.x=2]="x",e[e.y=3]="y",e[e.lx=4]="lx",e[e.ly=5]="ly",e[e.code=6]="code",e[e.name=7]="name",e[e.char=8]="char",e[e.color=9]="color",e[e.bg=10]="bg",e[e.player=11]="player",e[e.bucket=12]="bucket",e[e.pushable=13]="pushable",e[e.collision=14]="collision",e[e.destructible=15]="destructible",e[e.tickertext=16]="tickertext",e[e.tickertime=17]="tickertime",e[e.p1=18]="p1",e[e.p2=19]="p2",e[e.p3=20]="p3",e[e.cycle=21]="cycle",e[e.stepx=22]="stepx",e[e.stepy=23]="stepy",e[e.sender=24]="sender",e[e.arg=25]="arg",e[e.headless=26]="headless",e[e.removed=27]="removed",e))(Su||{});function Ba(e){return Ks(e,Su,{category:gi,kinddata:gi})}function Fa(e){return qs(e,Su)}var Au=(e=>(e[e.width=0]="width",e[e.height=1]="height",e[e.bits=2]="bits",e))(Au||{});function bg(e){return Ks(e,Au)}function wg(e){return qs(e,Au)}function vg(e,t){return{id:ht(),code:e,...t}}var Tu=(e=>(e[e.id=0]="id",e[e.code=1]="code",e[e.board=2]="board",e[e.object=3]="object",e[e.terrain=4]="terrain",e[e.charset=5]="charset",e[e.palette=6]="palette",e[e.eighttrack=7]="eighttrack",e))(Tu||{});function jR(e){return Ks(e,Tu,{board:fI,object:Ba,terrain:Ba,charset:bg,palette:bg,stats:gi})}function zR(e){return qs(e,Tu,{board:hI,object:Fa,terrain:Fa,charset:wg,palette:wg})}function WR(e){const t={...Js(e)};return Object.keys(t).forEach(n=>{switch(n){case"type":case"name":delete t[n];break}}),t}function GR(e){return k(e)?(e.stats=void 0,Js(e)):{}}function Js(e){var r;if(!k(e))return{};if(k((r=e.stats)==null?void 0:r.type))return e.stats;e.stats={};const t=Um(e.code);let n=!0;for(let i=0;i(e[e.id=0]="id",e[e.name=1]="name",e[e.timestamp=2]="timestamp",e[e.activelist=3]="activelist",e[e.pages=4]="pages",e[e.flags=5]="flags",e))(Ru||{});function HR(e){return Ks(e,Ru,{pages:t=>t.map(jR)})}function VR(e){return qs(e,Ru,{pages:t=>t.map(zR)})}function yi(e,t){if(!k(e))return;const n=Pe(t);return e.pages.find(i=>i.id===t||n===Xn(i))}function Iu(e,t,n){if(!k(e))return;const r=Pe(n);return e.pages.find(s=>Xs(s)===t&&(s.id===n||r===Xn(s)))}function KR(e,t){return k(e)?e.pages.filter(n=>Xs(n)===t):[]}function Ag(e,t){if(!k(e)||!k(t))return!1;const n=yi(e,t.id);return k(n)?!1:(e.pages.push(t),!0)}function qR(e,t){const n=yi(e,t);if(k(e)&&k(n)){const r=Pe(t);return e.pages=e.pages.filter(i=>i.id!==t&&r!==Xn(i)),n}}function Ln(e,t){if(k(t)&&k(t.kind))return k(t.kinddata)||(t.kinddata=k(t.id)?$a(e,t.kind):xg(e,t.kind)),t.kinddata}function Tg(e,t){const n=Ln(e,t);return{char:(t==null?void 0:t.char)??(n==null?void 0:n.char)??1,color:(t==null?void 0:t.color)??(n==null?void 0:n.color)??be.WHITE,bg:(t==null?void 0:t.bg)??(n==null?void 0:n.bg)??be.ONBORROW}}function $a(e,t){const n=t??"",r=Iu(e,Ae.OBJECT,n);if(k(r)){const i=xu(r);return{...ys(i),name:n,code:r.code}}}function xg(e,t){const n=t??"",r=Iu(e,Ae.TERRAIN,n);if(k(r)){const i=xu(r);return{...ys(i),name:n,code:r.code}}}function Zi(e,t){const n=yi(e,t);return xu(n)}function Ys(e,t){return e?(e.flags[t]=e.flags[t]??{},e.flags[t]):{}}function Ou(e,t){e&&delete e.flags[t]}function Rg(e,t,n){const r=Ys(e,t);return r==null?void 0:r[n]}function JR(e,t,n,r){const i=Ys(e,t);return i&&(i[n]=r),r}function ja(e,t){const n=Rg(e,t,"board");return Zi(e,Ce(n)?n:"")}function Nu(e,t,n){if(!k(e))return;JR(e,t,"board",n);const r=Zi(e,n);k(r)?e.activelist.includes(t)||e.activelist.push(t):e.activelist=e.activelist.filter(i=>i!==t)}function XR(e){const n=((e==null?void 0:e.activelist)??[]).map(r=>{const i=Rg(e,r,"board");return Ce(i)?i:""});return _w(n)}function Ig(e){return XR(e).map(n=>Zi(e,n)).filter(k)}function ZR(e,t,n,r){const i=Qi(t,(n==null?void 0:n.id)??"");if(!k(e)||!k(t)||!k(i)||!k(i.x)||!k(i.y)||!k(t.lookup)||r.x<0||r.x>=ze||r.y<0||r.y>=rn||i.x-r.x===0&&i.y-r.y===0)return!0;const s=r.x+r.y*ze,o=Ln(e,i),a=i.collision??(o==null?void 0:o.collision),c=Qi(t,t.lookup[s]??"");if(k(c))return!0;const l=t.terrain[s];if(k(l)){const u=Ln(e,l),f=l.collision??(u==null?void 0:u.collision);if(Nh(a,f))return!0}return!1}function YR(e,t,n,r){const i=Qi(t,(n==null?void 0:n.id)??"");if(!k(e)||!k(t)||!k(i)||!k(i.x)||!k(i.y)||!k(t.lookup)||r.x<0||r.x>=ze||r.y<0||r.y>=rn)return{kind:"edge",collision:Ye.ISSOLID,x:r.x,y:r.y};if(i.x-r.x===0&&i.y-r.y===0)return;const s=i.x+i.y*ze,o=r.x+r.y*ze,a=Ln(e,i),c=i.collision??(a==null?void 0:a.collision),l=Qi(t,t.lookup[o]??"");if(k(l))return{...l};const u=t.terrain[o];if(k(u)){const f=Ln(e,u),d=u.collision??(f==null?void 0:f.collision);if(Nh(c,d))return{...u,x:r.x,y:r.y}}i.x=r.x,i.y=r.y,k(i.removed)||(t.lookup[s]=void 0,t.lookup[o]=i.id??"")}function Yi(e,t){const n=Ln(e,t);return k(t==null?void 0:t.id)&&k(t.x)&&k(t.y)?Pe(t.name??(n==null?void 0:n.name)??"object"):Pe((t==null?void 0:t.name)??(n==null?void 0:n.name)??"terrain")}function Cu(e,t,n,r){if(!k(e)||!k(t)||!k(t.named)||!k(n))return;const i=Yi(e,n);t.named[i]||(t.named[i]=new Set),t.named[i].add((n==null?void 0:n.id)??r??"")}function QR(e,t,n){if(!(!k(e)||!k(t)||!k(t.lookup)||!k(n==null?void 0:n.id))&&!k(n.removed)){const r=n.x??0,i=n.y??0;t.lookup[r+i*ze]=n.id}}function za(e,t){if(!k(e)||!k(t)||k(t.lookup)&&k(t.named))return;const n=new Array(ze*rn).fill(void 0),r={},i=Object.values(t.objects);for(let a=0;a=ze&&(s=0,++o)}t.lookup=n,t.named=r}function Lu(e,t,n){return Yi(e,t)!=="player"&&k(t)?(t.removed=n,!0):!1}function Qs(e,t,n){var r;if(k(e)&&k(t)&&k(n==null?void 0:n.id)){if(k(t.lookup)&&k(n.x)&&k(n.y)){const s=n.x+n.y*ze;t.lookup[s]===n.id&&t.lookup.splice(s,1)}const i=Yi(e,n);k((r=t.named)==null?void 0:r[i])&&k(n.id)&&t.named[i].delete(n.id)}}function eI(e,t,n){const r=[];if(!k(e)||!k(t))return r;const i=Object.values(t.objects);for(let s=0;sUh*5&&(r.push(o.id),zg(t,o.id))}return r}function tI(e,t,n){const r=[];if(!k(e)||!k(t))return r;t.lookup=void 0,za(e,t);const i=Object.values(t.objects);for(let o=0;obe.WHITE&&ebe[t]).find(t=>k(t)&&tbe[t]).find(t=>k(t)&&t>=be.ONBLACK)}function Fg(e){if(En(e))return e;if(Dg(e))return[e];const t=Bg(e);if(k(t))return[t]}function $g(e){const t=C.words[e],n=Fg(t);if(En(n))return[n,e+1];const[r,i]=Gt(e),s=Fg(r);return En(s)?[s,i]:[void 0,e]}function Ha(e){const t=[];let n=e;const[r,i]=$g(e);if(En(r)&&(t.push(...r),n=i),En(t)&&!Pg(t)){const[s,o]=$g(i);Pg(s)&&(n=o)}return t.length?[t,n]:[void 0,e]}function cI(e){const t={};return e.every(n=>{const r=be[n];k(r)&&(r{})}function uI(e=lw){const t={terrain:lI(),objects:{},id:""};return e(t)}var Pu=(e=>(e[e.terrain=0]="terrain",e[e.objects=1]="objects",e[e.isdark=2]="isdark",e[e.over=3]="over",e[e.under=4]="under",e[e.exitnorth=5]="exitnorth",e[e.exitsouth=6]="exitsouth",e[e.exitwest=7]="exitwest",e[e.exiteast=8]="exiteast",e[e.timelimit=9]="timelimit",e[e.restartonzap=10]="restartonzap",e[e.maxplayershots=11]="maxplayershots",e))(Pu||{});function fI(e){return Ks(e,Pu,{terrain:t=>t.map(Ba),objects:t=>Object.values(t).map(Ba),id:gi,named:gi,lookup:gi,codepage:gi})}function hI(e){return qs(e,Pu,{terrain:t=>t.map(Fa),objects:t=>{const n={};for(let r=0;r=ze||t.y<0||t.y>=rn)return;const n={...t},r=t.x+t.y*ze;return e.terrain[r]=n,t}function gI(e,t){if(!k(e)||!k(t))return;const n={...t,id:t.id??ht()};return e.objects[n.id]=n,n}function jg(e,t,n){return mI(e,{...t,kind:n})}function Bu(e,t,n,r){return gI(e,{...t,id:r??void 0,kind:n})}function Qi(e,t){if(e)return e.objects[t]}function Fu(e,t,n,r,i){if(!k(e)||!k(t))return{x:0,y:0};const s={x:t.x??0,y:t.y??0},o={x:t.lx??s.x,y:t.ly??s.y},a=Bi(o,s),c=ze-1,l=rn-1;for(let u=0;u(e[e.CATEGORY=0]="CATEGORY",e[e.COLLISION=1]="COLLISION",e[e.COLOR=2]="COLOR",e[e.KIND=3]="KIND",e[e.DIR=4]="DIR",e[e.NUMBER=5]="NUMBER",e[e.STRING=6]="STRING",e[e.NUMBER_OR_STRING=7]="NUMBER_OR_STRING",e[e.MAYBE_CATEGORY=8]="MAYBE_CATEGORY",e[e.MAYBE_COLLISION=9]="MAYBE_COLLISION",e[e.MAYBE_COLOR=10]="MAYBE_COLOR",e[e.MAYBE_KIND=11]="MAYBE_KIND",e[e.MAYBE_DIR=12]="MAYBE_DIR",e[e.MAYBE_NUMBER=13]="MAYBE_NUMBER",e[e.MAYBE_STRING=14]="MAYBE_STRING",e[e.MAYBE_NUMBER_OR_STRING=15]="MAYBE_NUMBER_OR_STRING",e[e.ANY=16]="ANY",e))(q||{});function Rt(e,t){throw new Error(`Invalid arg, expected: ${e} but got ${JSON.stringify(t)}`)}function ne(e,t,n){var o,a,c,l;const r=C.words;C.words=e;const i=[];let s=t;for(let u=0;u(Wg(1,e,t),0)).command("synth",(e,t)=>{for(let n=1;n<=8;++n)Zn(n,t);return 0}).command("synth1",(e,t)=>(Zn(1,t),0)).command("synth2",(e,t)=>(Zn(2,t),0)).command("synth3",(e,t)=>(Zn(3,t),0)).command("synth4",(e,t)=>(Zn(4,t),0)).command("synth5",(e,t)=>(Zn(5,t),0)).command("synth6",(e,t)=>(Zn(6,t),0)).command("synth7",(e,t)=>(Zn(7,t),0)).command("synth8",(e,t)=>(Zn(8,t),0)).command("bgplay",(e,t)=>(Wg(0,e,t),0)).command("bgsynth",(e,t)=>(Zn(0,t),0)).command("tts",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.MAYBE_STRING]);return Pb("audio",r??"",n),0});function Ka(e,t,n,r){const i=Ce(t)?t:t.id,s=Ce(t)?void 0:{x:t.x??0,y:t.y??0},o=Ce(n)?n:n.id,a=i??s;k(o)&&k(a)&&e.send(o,r,a)}function wI(e,t,n,r){k(n==null?void 0:n.id)?(n.headless=!0,Qs(e,t,n)):jg(t,r,"empty")}function Gg(e,t,n,r,i){const s=YR(t,n,r,i);if(k(s)){Ka(e,s,e.id(),"thud"),r.kind===Xe.PLAYER?Ka(e,e.id(),s,"touch"):r.collision===Ye.ISBULLET?Ka(e,e.id(),s,"shot"):Ka(e,e.id(),s,"bump");const o=Ln(t,s);return(s.destructible??(o==null?void 0:o.destructible))&&wI(t,n,s,i),!1}return!0}function Hg(e,t,n){if(!fr(C.element))return 0;const[r,i]=ne(t,0,[q.DIR,q.MAYBE_KIND]),s=i??["bullet"],o=nI(C.book,C.board,s,{x:C.element.x,y:C.element.y});if(k(o)){o.arg=n,o.collision=Ye.ISBULLET,o.stepx=r.x-C.element.x,o.stepy=r.y-C.element.y;const a=Ln(C.book,o),c=o.code??(a==null?void 0:a.code)??"";G_(C.book,C.board,o,c,1),o.x===C.element.x&&o.y===C.element.y?o.headless=!0:e.bucket(o.id)}return e.yield(),0}const vI=lr().command("change",(e,t)=>{if(!k(C.book)||!k(C.board))return 0;const[n,r]=ne(t,0,[q.KIND,q.KIND]);za(C.book,C.board);const i=jo(n)??"",s=bs(C.board,i),o=Lh(s,n),a=jo(r),c=Ih(r),l=Oh(r);return o.forEach(u=>{if(Yi(C.book,u)===a)k(c)&&(u.color=c),k(l)&&(u.bg=l);else{if(k(u.id)&&(Qs(C.book,C.board,u),!Lu(C.book,u,C.timestamp)))return;fr(u)&&Mu(C.book,C.board,r,u)}}),0}).command("put",(e,t)=>{if(!k(C.book)||!k(C.board))return 0;const[n,r]=ne(t,0,[q.DIR,q.KIND]);return za(C.book,C.board),Mu(C.book,C.board,r,n),0}).command("shootwith",(e,t)=>{const[n,r]=ne(t,0,[q.ANY]);return Hg(e,t.slice(r),n)}).command("shoot",Hg).command("throwstar",()=>0);function eo(){return eo=Object.assign||function(e){for(var t=1;t0}function ju(e){Ja++;try{return e()}finally{Ja--,Ja===0&&TI()}}var zu=!1;function Xg(){return zu}function Zg(e){zu=!0;try{e()}finally{zu=!1}}function AI(e){return function(){return Zg(e)}}var Wu=[];function TI(){var e=[].concat(Wu);Wu=[],Yg(e)}function Yg(e){var t=new Set;e.forEach(function(n){var r;(n.type==="add"||n.type==="delete")&&n.observable[vt].connections.iterate.forEach(function(i){t.add(i)}),(r=n.observable[vt].connections.byKey.get(n.key))==null||r.forEach(function(i){t.add(i)})}),t.forEach(function(n){n.trigger()})}function Xa(e){if(Jg()){Wu.push(e);return}Yg([e])}function Qg(e,t){if(e.type==="iterate")e.observable[vt].connections.iterate.add(t);else{var n=e.observable[vt].connections.byKey.get(e.key);n||(n=new Set,e.observable[vt].connections.byKey.set(e.key,n)),n.add(t)}}function Za(e,t){if(!Xg()){var n=qg();n&&(Qg(e,n),n.registerConnection(e)),t&&(Qg(e,t),t.registerConnection(e))}}var Gu=Symbol("$skipreactive"),vt=Symbol("$reactive"),kn=Symbol("$reactiveproxy");function to(e,t){return!!(e&&e[kn]&&e[kn].implicitObserver===t)}function Hu(e){return e[Gu]=!0,e}function e0(e){return!!(e&&!to(e)&&e[vt])}function Vu(e,t,n){if(n===void 0&&(n=!1),e[Gu]||to(e,t))return e;var r=xI(e,n);if(!t)return r;var i=r[vt].proxiesWithImplicitObserver.get(t);if(!i){var s={implicitObserver:t};Object.setPrototypeOf(s,t0),i=new Proxy(r[vt].raw,s),r[vt].proxiesWithImplicitObserver.set(t,i)}return i}var no=Vu;function xI(e,t){if(t===void 0&&(t=!1),to(e))return e;if(e0(e))return e[vt].proxy;if(e[vt]||e[kn])throw new Error("unexpected");var n={connections:{iterate:new Set,byKey:new Map},proxy:{},raw:e,proxiesWithImplicitObserver:new Map,shallow:t};Object.defineProperty(e,vt,{enumerable:!1,writable:!0,configurable:!0,value:n});var r=new Proxy(e,t0);return n.proxy=r,r}var t0={has:function(t,n){var r=Reflect.has(t,n);return typeof n=="symbol"||Za({observable:t,key:n,type:"has"},this.implicitObserver),r},get:function(t,n,r){if(n===kn)return{implicitObserver:this.implicitObserver};var i=Reflect.get(t,n,r);if(typeof n=="symbol")return n.toString()==="Symbol($reactiveproxy)"&&console.error("warning, Symbol($reactiveproxy) passed, but does not match $reactiveproxy. Multiple Reactive libraries loaded?"),i;if(n==="length"&&Array.isArray(t)?Za({observable:t,type:"iterate"},this.implicitObserver):Za({observable:t,key:n,type:"get"},this.implicitObserver),e0(i))return Vu(i,this.implicitObserver);if(t[vt].shallow)return i;if(typeof i=="object"&&i!==null&&!to(i,this.implicitObserver)&&!Object.isFrozen(i)){var s=Reflect.getOwnPropertyDescriptor(t,n);if((!s||!(s.writable===!1&&s.configurable===!1))&&(Kg()||this.implicitObserver))return Vu(i,this.implicitObserver)}return i},ownKeys:function(t){return Za({observable:t,type:"iterate"},this.implicitObserver),Reflect.ownKeys(t)},set:function(t,n,r,i){return ju(function(){if(typeof n=="symbol")return Reflect.set(t,n,r,i);var s=Object.hasOwnProperty.call(t,n),o=Reflect.get(t,n,i),a=Reflect.set(t,n,r,i);if(!s)Xa({observable:t,key:n,value:r,type:"add"});else if(r!==o)if(n==="length"&&Array.isArray(t)){if(!(onew Map,Ku=e=>{const t=Mn();return e.forEach((n,r)=>{t.set(r,n)}),t},Gr=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},CI=(e,t)=>{const n=[];for(const[r,i]of e)n.push(t(i,r));return n},LI=(e,t)=>{for(const[n,r]of e)if(t(r,n))return!0;return!1},es=()=>new Set,qu=e=>e[e.length-1],MI=(e,t)=>{for(let n=0;n{this.off(t,r),n(...i)};this.on(t,r)}off(t,n){const r=this._observers.get(t);r!==void 0&&(r.delete(n),r.size===0&&this._observers.delete(t))}emit(t,n){return Hr((this._observers.get(t)||Mn()).values()).forEach(r=>r(...n))}destroy(){this._observers=Mn()}}const Vr=Math.floor,Ya=Math.abs,r0=(e,t)=>ee>t?e:t,i0=e=>e!==0?e<0:1/e<0,s0=1,o0=2,Ju=4,Xu=8,ro=32,kr=64,cn=128,Qa=31,Zu=63,vi=127,DI=2147483647,a0=Number.MAX_SAFE_INTEGER,BI=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&Vr(e)===e),FI=e=>e.toLowerCase(),$I=/^\s*/g,jI=e=>e.replace($I,""),zI=/([A-Z])/g,c0=(e,t)=>jI(e.replace(zI,n=>`${t}${FI(n)}`)),WI=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let i=0;iio.encode(e):WI;let so=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});so&&so.decode(new Uint8Array).length===1&&(so=null);class oo{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Kr=()=>new oo,HI=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(HI(e));let n=0;for(let r=0;r{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Yu=It,ve=(e,t)=>{for(;t>vi;)It(e,cn|vi&t),t=Vr(t/128);It(e,vi&t)},Qu=(e,t)=>{const n=i0(t);for(n&&(t=-t),It(e,(t>Zu?cn:0)|(n?kr:0)|Zu&t),t=Vr(t/64);t>0;)It(e,(t>vi?cn:0)|vi&t),t=Vr(t/128)},ef=new Uint8Array(3e4),KI=ef.length/3,qI=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),r=n.length;ve(e,r);for(let i=0;i{const n=e.cbuf.length,r=e.cpos,i=r0(n-r,t.length),s=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,s>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(wi(n*2,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)},Pt=(e,t)=>{ve(e,t.byteLength),ec(e,t)},tf=(e,t)=>{VI(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},XI=(e,t)=>tf(e,4).setFloat32(0,t,!1),ZI=(e,t)=>tf(e,8).setFloat64(0,t,!1),YI=(e,t)=>tf(e,8).setBigInt64(0,t,!1),l0=new DataView(new ArrayBuffer(4)),QI=e=>(l0.setFloat32(0,e),l0.getFloat32(0)===e),ao=(e,t)=>{switch(typeof t){case"string":It(e,119),ts(e,t);break;case"number":BI(t)&&Ya(t)<=DI?(It(e,125),Qu(e,t)):QI(t)?(It(e,124),XI(e,t)):(It(e,123),ZI(e,t));break;case"bigint":It(e,122),YI(e,t);break;case"object":if(t===null)It(e,126);else if(UI(t)){It(e,117),ve(e,t.length);for(let n=0;n0&&ve(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const f0=e=>{e.count>0&&(Qu(e.encoder,e.count===1?e.s:-e.s),e.count>1&&ve(e.encoder,e.count-2))};class tc{constructor(){this.encoder=new oo,this.s=0,this.count=0}write(t){this.s===t?this.count++:(f0(this),this.count=1,this.s=t)}toUint8Array(){return f0(this),Un(this.encoder)}}const h0=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Qu(e.encoder,t),e.count>1&&ve(e.encoder,e.count-2)}};class nf{constructor(){this.encoder=new oo,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(h0(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return h0(this),Un(this.encoder)}}class eO{constructor(){this.sarr=[],this.s="",this.lensE=new tc}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new oo;return this.sarr.push(this.s),this.s="",ts(t,this.sarr.join("")),ec(t,this.lensE.toUint8Array()),Un(t)}}const qr=e=>new Error(e),Yn=()=>{throw qr("Method unimplemented")},Qn=()=>{throw qr("Unexpected case")},d0=qr("Unexpected end of array"),p0=qr("Integer out of Range");class nc{constructor(t){this.arr=t,this.pos=0}}const Ei=e=>new nc(e),tO=e=>e.pos!==e.arr.length,nO=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Ht=e=>nO(e,Ee(e)),ns=e=>e.arr[e.pos++],Ee=e=>{let t=0,n=1;const r=e.arr.length;for(;e.posa0)throw p0}throw d0},rf=e=>{let t=e.arr[e.pos++],n=t&Zu,r=64;const i=(t&kr)>0?-1:1;if(!(t&cn))return i*n;const s=e.arr.length;for(;e.posa0)throw p0}throw d0},rs=so?e=>so.decode(Ht(e)):e=>{let t=Ee(e);if(t===0)return"";{let n=String.fromCodePoint(ns(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ns(e));else for(;t>0;){const r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},sf=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},rO=[e=>{},e=>null,rf,e=>sf(e,4).getFloat32(0,!1),e=>sf(e,8).getFloat64(0,!1),e=>sf(e,8).getBigInt64(0,!1),e=>!1,e=>!0,rs,e=>{const t=Ee(e),n={};for(let r=0;r{const t=Ee(e),n=[];for(let r=0;rrO[127-ns(e)](e);class m0 extends nc{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),tO(this)?this.count=Ee(this)+1:this.count=-1),this.count--,this.s}}class rc extends nc{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=rf(this);const t=i0(this.s);this.count=1,t&&(this.s=-this.s,this.count=Ee(this)+2)}return this.count--,this.s}}class of extends nc{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=rf(this),n=t&1;this.diff=Vr(t/2),this.count=1,n&&(this.count=Ee(this)+2)}return this.s+=this.diff,this.count--,this.s}}class iO{constructor(t){this.decoder=new rc(t),this.str=rs(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const sO=crypto.getRandomValues.bind(crypto),g0=()=>sO(new Uint32Array(1))[0],oO="10000000-1000-4000-8000"+-1e11,aO=()=>oO.replace(/[018]/g,e=>(e^g0()&15>>e/4).toString(16)),y0=e=>new Promise(e);Promise.all.bind(Promise);const _0=e=>e===void 0?null:e;class cO{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let b0=new cO,lO=!0;try{typeof localStorage<"u"&&localStorage&&(b0=localStorage,lO=!1)}catch{}const uO=b0,fO=Object.assign,hO=Object.keys,dO=(e,t)=>{for(const n in e)t(e[n],n)},w0=e=>hO(e).length,pO=e=>{for(const t in e)return!1;return!0},mO=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},gO=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),yO=(e,t)=>e===t||w0(e)===w0(t)&&mO(e,(n,r)=>(n!==void 0||gO(t,r))&&t[r]===n),_O=Object.freeze,v0=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&v0(e[t])}return _O(e)},af=(e,t,n=0)=>{try{for(;ne,wO=(e,t)=>t.includes(e);var E0={};const lo=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let er;const vO=()=>{if(er===void 0)if(lo){er=Mn();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");er.set(`--${c0(t,"-")}`,n),er.set(`-${c0(t,"-")}`,n)}})):er=Mn();return er},cf=e=>vO().has(e),ic=e=>_0(lo?E0[e.toUpperCase().replaceAll("-","_")]:uO.getItem(e)),k0=e=>cf("--"+e)||ic(e)!==null;k0("production");const EO=lo&&wO(E0.FORCE_COLOR,["true","1","2"])||!cf("--no-colors")&&!k0("no-color")&&(!lo||process.stdout.isTTY)&&(!lo||cf("--color")||ic("COLORTERM")!==null||(ic("TERM")||"").includes("color")),kO=e=>new Uint8Array(e),SO=e=>{const t=kO(e.byteLength);return t.set(e),t};class AO{constructor(t,n){this.left=t,this.right=n}}const Sr=(e,t)=>new AO(e,t);typeof DOMParser<"u"&&new DOMParser;const TO=e=>CI(e,(t,n)=>`${n}:${t};`).join(""),Ar=Symbol,S0=Ar(),A0=Ar(),xO=Ar(),RO=Ar(),IO=Ar(),T0=Ar(),OO=Ar(),lf=Ar(),NO=Ar(),CO=e=>{var i;e.length===1&&((i=e[0])==null?void 0:i.constructor)===Function&&(e=e[0]());const t=[],n=[];let r=0;for(;r0&&n.push(t.join(""));r{var o;e.length===1&&((o=e[0])==null?void 0:o.constructor)===Function&&(e=e[0]());const t=[],n=[],r=Mn();let i=[],s=0;for(;s0||l.length>0?(t.push("%c"+a),n.push(l)):t.push(a)}else break}}for(s>0&&(i=n,i.unshift(t.join("")));s{console.log(...x0(e)),R0.forEach(t=>t.print(e))},UO=(...e)=>{console.warn(...x0(e)),e.unshift(lf),R0.forEach(t=>t.print(e))},R0=es(),I0=e=>({[Symbol.iterator](){return this},next:e}),PO=(e,t)=>I0(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),uf=(e,t)=>I0(()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});class ff{constructor(t,n){this.clock=t,this.len=n}}class uo{constructor(){this.clients=new Map}}const O0=(e,t,n)=>t.clients.forEach((r,i)=>{const s=e.doc.store.clients.get(i);for(let o=0;o{let n=0,r=e.length-1;for(;n<=r;){const i=Vr((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&DO(n,t.clock)!==null},hf=e=>{e.clients.forEach(t=>{t.sort((i,s)=>i.clock-s.clock);let n,r;for(n=1,r=1;n=s.clock?i.len=wi(i.len,s.clock+s.len-i.clock):(r{const t=new uo;for(let n=0;n{if(!t.clients.has(i)){const s=r.slice();for(let o=n+1;o{Gr(e.clients,t,()=>[]).push(new ff(n,r))},FO=()=>new uo,$O=e=>{const t=FO();return e.clients.forEach((n,r)=>{const i=[];for(let s=0;s0&&t.clients.set(r,i)}),t},is=(e,t)=>{ve(e.restEncoder,t.clients.size),Hr(t.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{e.resetDsCurVal(),ve(e.restEncoder,n);const i=r.length;ve(e.restEncoder,i);for(let s=0;s{const t=new uo,n=Ee(e.restDecoder);for(let r=0;r0){const o=Gr(t.clients,i,()=>[]);for(let a=0;a{const r=new uo,i=Ee(e.restDecoder);for(let s=0;s0){const s=new ki;return ve(s.restEncoder,0),is(s,r),s.toUint8Array()}return null},L0=g0;class Tr extends PI{constructor({guid:t=aO(),collectionid:n=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=L0(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new H0,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=y0(l=>{this.on("load",()=>{this.isLoaded=!0,l(this)})});const c=()=>y0(l=>{const u=f=>{(f===void 0||f===!0)&&(this.off("sync",u),l())};this.on("sync",u)});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&Je(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Hr(this.subdocs).map(t=>t.guid))}transact(t,n=null){return Je(this,t,n)}get(t,n=at){const r=Gr(this.share,t,()=>{const s=new n;return s._integrate(this,null),s}),i=r.constructor;if(n!==at&&i!==n)if(i===at){const s=new n;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(t,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return r}getArray(t=""){return this.get(t,tr)}getText(t=""){return this.get(t,Dn)}getMap(t=""){return this.get(t,nr)}getXmlElement(t=""){return this.get(t,xr)}getXmlFragment(t=""){return this.get(t,rr)}toJSON(){const t={};return this.share.forEach((n,r)=>{t[r]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Hr(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new Tr({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Je(t.parent.doc,r=>{const i=n.doc;t.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class M0{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return Ee(this.restDecoder)}readDsLen(){return Ee(this.restDecoder)}}class U0 extends M0{readLeftID(){return Oe(Ee(this.restDecoder),Ee(this.restDecoder))}readRightID(){return Oe(Ee(this.restDecoder),Ee(this.restDecoder))}readClient(){return Ee(this.restDecoder)}readInfo(){return ns(this.restDecoder)}readString(){return rs(this.restDecoder)}readParentInfo(){return Ee(this.restDecoder)===1}readTypeRef(){return Ee(this.restDecoder)}readLen(){return Ee(this.restDecoder)}readAny(){return co(this.restDecoder)}readBuf(){return SO(Ht(this.restDecoder))}readJSON(){return JSON.parse(rs(this.restDecoder))}readKey(){return rs(this.restDecoder)}}class jO{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ee(this.restDecoder),this.dsCurrVal}readDsLen(){const t=Ee(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class ss extends jO{constructor(t){super(t),this.keys=[],Ee(t),this.keyClockDecoder=new of(Ht(t)),this.clientDecoder=new rc(Ht(t)),this.leftClockDecoder=new of(Ht(t)),this.rightClockDecoder=new of(Ht(t)),this.infoDecoder=new m0(Ht(t),ns),this.stringDecoder=new iO(Ht(t)),this.parentInfoDecoder=new m0(Ht(t),ns),this.typeRefDecoder=new rc(Ht(t)),this.lenDecoder=new rc(Ht(t))}readLeftID(){return new os(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new os(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return co(this.restDecoder)}readBuf(){return Ht(this.restDecoder)}readJSON(){return co(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{r=wi(r,t[0].id.clock);const i=Pn(t,r);ve(e.restEncoder,t.length-i),e.writeClient(n),ve(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let o=i+1;o{const r=new Map;n.forEach((i,s)=>{Ot(t,s)>i&&r.set(s,i)}),ac(t).forEach((i,s)=>{n.has(s)||r.set(s,0)}),ve(e.restEncoder,r.size),Hr(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{zO(e,t.clients.get(i),i,s)})},WO=(e,t)=>{const n=Mn(),r=Ee(e.restDecoder);for(let i=0;i{const r=[];let i=Hr(n.keys()).sort((h,p)=>h-p);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let h=n.get(i[i.length-1]);for(;h.refs.length===h.i;)if(i.pop(),i.length>0)h=n.get(i[i.length-1]);else return null;return h};let o=s();if(o===null)return null;const a=new H0,c=new Map,l=(h,p)=>{const m=c.get(h);(m==null||m>p)&&c.set(h,p)};let u=o.refs[o.i++];const f=new Map,d=()=>{for(const h of r){const p=h.id.client,m=n.get(p);m?(m.i--,a.clients.set(p,m.refs.slice(m.i)),n.delete(p),m.i=0,m.refs=[]):a.clients.set(p,[h]),i=i.filter(b=>b!==p)}r.length=0};for(;;){if(u.constructor!==Sn){const p=Gr(f,u.id.client,()=>Ot(t,u.id.client))-u.id.clock;if(p<0)r.push(u),l(u.id.client,u.id.clock-1),d();else{const m=u.getMissing(e,t);if(m!==null){r.push(u);const b=n.get(m)||{refs:[],i:0};if(b.refs.length===b.i)l(m,Ot(t,m)),d();else{u=b.refs[b.i++];continue}}else(p===0||p0)u=r.pop();else if(o!==null&&o.i0){const h=new ki;return pf(h,a,new Map),ve(h.restEncoder,0),{missing:c,update:h.toUint8Array()}}return null},HO=(e,t)=>pf(e,t.doc.store,t.beforeState),VO=(e,t,n,r=new ss(e))=>Je(t,i=>{i.local=!1;let s=!1;const o=i.doc,a=o.store,c=WO(r,o),l=GO(i,a,c),u=a.pendingStructs;if(u){for(const[d,h]of u.missing)if(hh)&&u.missing.set(d,h)}u.update=lc([u.update,l.update])}}else a.pendingStructs=l;const f=C0(r,i,a);if(a.pendingDs){const d=new ss(Ei(a.pendingDs));Ee(d.restDecoder);const h=C0(d,i,a);f&&h?a.pendingDs=lc([f,h]):a.pendingDs=f||h}else a.pendingDs=f;if(s){const d=a.pendingStructs.update;a.pendingStructs=null,B0(i.doc,d)}},n,!1),B0=(e,t,n,r=ss)=>{const i=Ei(t);VO(i,e,n,new r(i))},KO=(e,t,n)=>B0(e,t,n,U0),qO=(e,t,n=new Map)=>{pf(e,t.store,n),is(e,$O(t.store))},JO=(e,t=new Uint8Array([0]),n=new ki)=>{const r=F0(t);qO(n,e,r);const i=[n.toUint8Array()];if(e.store.pendingDs&&i.push(e.store.pendingDs),e.store.pendingStructs&&i.push(uN(e.store.pendingStructs.update,t)),i.length>1){if(n.constructor===fo)return cN(i.map((s,o)=>o===0?s:hN(s)));if(n.constructor===ki)return lc(i)}return i[0]},XO=(e,t)=>JO(e,t,new fo),ZO=e=>{const t=new Map,n=Ee(e.restDecoder);for(let r=0;rZO(new M0(Ei(e))),$0=(e,t)=>(ve(e.restEncoder,t.size),Hr(t.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{ve(e.restEncoder,n),ve(e.restEncoder,r)}),e),YO=(e,t)=>$0(e,ac(t.store)),QO=(e,t=new D0)=>(e instanceof Map?$0(t,e):YO(t,e),t.toUint8Array()),eN=e=>QO(e,new P0);class tN{constructor(){this.l=[]}}const j0=()=>new tN,z0=(e,t)=>e.l.push(t),W0=(e,t)=>{const n=e.l,r=n.length;e.l=n.filter(i=>t!==i),r===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},G0=(e,t,n)=>af(e.l,[t,n]);class os{constructor(t,n){this.client=t,this.clock=n}}const oc=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,Oe=(e,t)=>new os(e,t),nN=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Qn()},as=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!N0(t.ds,e.id),mf=(e,t)=>{const n=Gr(e.meta,mf,es),r=e.doc.store;n.has(t)||(t.sv.forEach((i,s)=>{i{}),n.add(t))};class H0{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ac=e=>{const t=new Map;return e.clients.forEach((n,r)=>{const i=n[n.length-1];t.set(r,i.id.clock+i.length)}),t},Ot=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const r=n[n.length-1];return r.id.clock+r.length},V0=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const r=n[n.length-1];if(r.id.clock+r.length!==t.id.clock)throw Qn()}n.push(t)},Pn=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=Vr(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t{const n=e.clients.get(t.client);return n[Pn(n,t.clock)]},yf=(e,t,n)=>{const r=Pn(t,n),i=t[r];return i.id.clock{const n=e.doc.store.clients.get(t.client);return n[yf(e,n,t.clock)]},K0=(e,t,n)=>{const r=t.clients.get(n.client),i=Pn(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==ln&&r.splice(i+1,0,_c(e,s,n.clock-s.id.clock+1)),s},rN=(e,t,n)=>{const r=e.clients.get(t.id.client);r[Pn(r,t.id.clock)]=n},q0=(e,t,n,r,i)=>{if(r===0)return;const s=n+r;let o=yf(e,t,n),a;do a=t[o++],st.deleteSet.clients.size===0&&!LI(t.afterState,(n,r)=>t.beforeState.get(r)!==n)?!1:(hf(t.deleteSet),HO(e,t),is(e,t.deleteSet),!0),X0=(e,t,n)=>{const r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Gr(e.changed,t,es).add(n)},cc=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof kt&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}const s=t-i;return s&&e.splice(t+1-s,s),s},sN=(e,t,n)=>{for(const[r,i]of e.clients.entries()){const s=t.clients.get(r);for(let o=i.length-1;o>=0;o--){const a=i[o],c=a.clock+a.len;for(let l=Pn(s,a.clock),u=s[l];l{e.clients.forEach((n,r)=>{const i=t.clients.get(r);for(let s=n.length-1;s>=0;s--){const o=n[s],a=r0(i.length-1,1+Pn(i,o.clock+o.len-1));for(let c=a,l=i[c];c>0&&l.id.clock>=o.clock;l=i[c])c-=1+cc(i,c)}})},Z0=(e,t)=>{if(ta.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(n,c)})),a.push(()=>{n.changedParentTypes.forEach((c,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=l,u._path=null}),c.sort((u,f)=>u.path.length-f.path.length),G0(l._dEH,c,n))})}),a.push(()=>r.emit("afterTransaction",[n,r])),af(a,[]),n._needFormattingCleanup&&TN(n)}finally{r.gc&&sN(s,i,r.gcFilter),oN(s,i),n.afterState.forEach((u,f)=>{const d=n.beforeState.get(f)||0;if(d!==u){const h=i.clients.get(f),p=wi(Pn(h,d),1);for(let m=h.length-1;m>=p;)m-=1+cc(h,m)}});for(let u=o.length-1;u>=0;u--){const{client:f,clock:d}=o[u].id,h=i.clients.get(f),p=Pn(h,d);p+11||p>0&&cc(h,p)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(MO(lf,S0,"[yjs] ",A0,T0,"Changed the client-id because another client seems to be using it."),r.clientID=L0()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const u=new fo;J0(u,n)&&r.emit("update",[u.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const u=new ki;J0(u,n)&&r.emit("updateV2",[u.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=n;(a.size>0||l.size>0||c.size>0)&&(a.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),l.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,n]),l.forEach(u=>u.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):Z0(e,t+1)}}},Je=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;e._transaction===null&&(s=!0,e._transaction=new iN(e,n,r),i.push(e._transaction),i.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const a=e._transaction===i[0];e._transaction=null,a&&Z0(i,0)}}return o};function*aN(e){const t=Ee(e.restDecoder);for(let n=0;nlc(e,U0,fo),lN=(e,t)=>{if(e.constructor===ln){const{client:n,clock:r}=e.id;return new ln(Oe(n,r+t),e.length-t)}else if(e.constructor===Sn){const{client:n,clock:r}=e.id;return new Sn(Oe(n,r+t),e.length-t)}else{const n=e,{client:r,clock:i}=n.id;return new kt(Oe(r,i+t),null,Oe(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},lc=(e,t=ss,n=ki)=>{if(e.length===1)return e[0];const r=e.map(u=>new t(Ei(u)));let i=r.map(u=>new _f(u,!0)),s=null;const o=new n,a=new bf(o);for(;i=i.filter(d=>d.curr!==null),i.sort((d,h)=>{if(d.curr.id.client===h.curr.id.client){const p=d.curr.id.clock-h.curr.id.clock;return p===0?d.curr.constructor===h.curr.constructor?0:d.curr.constructor===Sn?1:-1:p}else return h.curr.id.client-d.curr.id.client}),i.length!==0;){const u=i[0],f=u.curr.id.client;if(s!==null){let d=u.curr,h=!1;for(;d!==null&&d.id.clock+d.length<=s.struct.id.clock+s.struct.length&&d.id.client>=s.struct.id.client;)d=u.next(),h=!0;if(d===null||d.id.client!==f||h&&d.id.clock>s.struct.id.clock+s.struct.length)continue;if(f!==s.struct.id.client)Xr(a,s.struct,s.offset),s={struct:d,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===Sn?s.struct.length-=p:d=lN(d,p)),s.struct.mergeWith(d)||(Xr(a,s.struct,s.offset),s={struct:d,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===f&&d.id.clock===s.struct.id.clock+s.struct.length&&d.constructor!==Sn;d=u.next())Xr(a,s.struct,s.offset),s={struct:d,offset:0}}s!==null&&(Xr(a,s.struct,s.offset),s=null),wf(a);const c=r.map(u=>df(u)),l=BO(c);return is(o,l),o.toUint8Array()},uN=(e,t,n=ss,r=ki)=>{const i=F0(t),s=new r,o=new bf(s),a=new n(Ei(e)),c=new _f(a,!1);for(;c.curr;){const u=c.curr,f=u.id.client,d=i.get(f)||0;if(c.curr.constructor===Sn){c.next();continue}if(u.id.clock+u.length>d)for(Xr(o,u,wi(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===f;)Xr(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===f&&c.curr.id.clock+c.curr.length<=d;)c.next()}wf(o);const l=df(a);return is(s,l),s.toUint8Array()},Y0=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Un(e.encoder.restEncoder)}),e.encoder.restEncoder=Kr(),e.written=0)},Xr=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Y0(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),ve(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},wf=e=>{Y0(e);const t=e.encoder.restEncoder;ve(t,e.clientStructs.length);for(let n=0;n{const i=new n(Ei(e)),s=new _f(i,!1),o=new r,a=new bf(o);for(let l=s.curr;l!==null;l=s.next())Xr(a,t(l),0);wf(a);const c=df(i);return is(o,c),o.toUint8Array()},hN=e=>fN(e,bO,ss,fo),Q0="You must not compute changes after the event-handler fired.";class uc{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=dN(this.currentTarget,this.target))}deletes(t){return N0(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw qr(Q0);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(i=>{if(i!==null){const s=n._map.get(i);let o,a;if(this.adds(s)){let c=s.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(s))if(c!==null&&this.deletes(c))o="delete",a=qu(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",a=qu(c.content.getContent())):(o="add",a=void 0)}else if(this.deletes(s))o="delete",a=qu(s.content.getContent());else return;t.set(i,{action:o,oldValue:a})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw qr(Q0);const n=this.target,r=es(),i=es(),s=[];if(t={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const c=()=>{a&&s.push(a)};for(let l=n._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=l.length,i.add(l)):this.adds(l)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(l.content.getContent()),r.add(l)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=l.length);a!==null&&a.retain===void 0&&c()}this._changes=t}return t}}const dN=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let r=0,i=t._item.parent._start;for(;i!==t._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;n.unshift(r)}t=t._item.parent}return n},Dt=()=>{UO("Invalid access: Add Yjs type to a document before reading data.")},ey=80;let vf=0;class pN{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=vf++}}const mN=e=>{e.timestamp=vf++},ty=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=vf++},gN=(e,t,n)=>{if(e.length>=ey){const r=e.reduce((i,s)=>i.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((s,o)=>Ya(t-s.index)t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&Ya(n.index-i){for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){e.splice(r,1);continue}i.p=s,s.marker=!0}(t0&&t===i.index)&&(i.index=wi(t,i.index+n))}},hc=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;Gr(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;G0(r._eH,n,t)};class at{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=j0(),this._dEH=j0(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw Yn()}clone(){throw Yn()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){z0(this._eH,t)}observeDeep(t){z0(this._dEH,t)}unobserve(t){W0(this._eH,t)}unobserveDeep(t){W0(this._dEH,t)}toJSON(){}}const ny=(e,t,n)=>{e.doc??Dt(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=t)t-=o.length;else{for(let a=t;a0;a++)i.push(o[a]),r--;t=0}}s=s.right}return i},ry=e=>{e.doc??Dt();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let i=0;i{let n=0,r=e._start;for(e.doc??Dt();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const n=[];return po(e,(r,i)=>{n.push(t(r,i,e))}),n},yN=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const i=n[r++];return n.length<=r&&(n=null),{done:!1,value:i}}}},sy=(e,t)=>{e.doc??Dt();const n=fc(e,t);let r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t{let i=n;const s=e.doc,o=s.clientID,a=s.store,c=n===null?t._start:n.right;let l=[];const u=()=>{l.length>0&&(i=new kt(Oe(o,Ot(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Ti(l)),i.integrate(e,0),l=[])};r.forEach(f=>{if(f===null)l.push(f);else switch(f.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(f);break;default:switch(u(),f.constructor){case Uint8Array:case ArrayBuffer:i=new kt(Oe(o,Ot(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new mo(new Uint8Array(f))),i.integrate(e,0);break;case Tr:i=new kt(Oe(o,Ot(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new yo(f)),i.integrate(e,0);break;default:if(f instanceof at)i=new kt(Oe(o,Ot(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Rr(f)),i.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},oy=()=>qr("Length exceeded!"),ay=(e,t,n,r)=>{if(n>t._length)throw oy();if(n===0)return t._searchMarker&&ho(t._searchMarker,n,r.length),dc(e,t,null,r);const i=n,s=fc(t,n);let o=t._start;for(s!==null&&(o=s.p,n-=s.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let i=(t._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:t._start}).p;if(i)for(;i.right;)i=i.right;return dc(e,t,i,n)},cy=(e,t,n,r)=>{if(r===0)return;const i=n,s=r,o=fc(t,n);let a=t._start;for(o!==null&&(a=o.p,n-=o.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n0&&a!==null;)a.deleted||(r0)throw oy();t._searchMarker&&ho(t._searchMarker,i,-s+r)},pc=(e,t,n)=>{const r=t._map.get(n);r!==void 0&&r.delete(e)},Ef=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let a;if(r==null)a=new Ti([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:a=new Ti([r]);break;case Uint8Array:a=new mo(r);break;case Tr:a=new yo(r);break;default:if(r instanceof at)a=new Rr(r);else throw new Error("Unexpected content type")}new kt(Oe(o,Ot(s.store,o)),i,i&&i.lastId,null,null,t,n,a).integrate(e,0)},kf=(e,t)=>{e.doc??Dt();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ly=e=>{const t={};return e.doc??Dt(),e._map.forEach((n,r)=>{n.deleted||(t[r]=n.content.getContent()[n.length-1])}),t},uy=(e,t)=>{e.doc??Dt();const n=e._map.get(t);return n!==void 0&&!n.deleted},bN=(e,t)=>{const n={};return e._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!t.sv.has(s.id.client)||s.id.clock>=(t.sv.get(s.id.client)||0));)s=s.left;s!==null&&as(s,t)&&(n[i]=s.content.getContent()[s.length-1])}),n},mc=e=>(e.doc??Dt(),PO(e._map.entries(),t=>!t[1].deleted));class wN extends uc{}class tr extends at{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new tr;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new tr}clone(){const t=new tr;return t.insert(0,this.toArray().map(n=>n instanceof at?n.clone():n)),t}get length(){return this.doc??Dt(),this._length}_callObserver(t,n){super._callObserver(t,n),hc(this,t,new wN(this,t))}insert(t,n){this.doc!==null?Je(this.doc,r=>{ay(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?Je(this.doc,n=>{_N(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?Je(this.doc,r=>{cy(r,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return sy(this,t)}toArray(){return ry(this)}slice(t=0,n=this.length){return ny(this,t,n)}toJSON(){return this.map(t=>t instanceof at?t.toJSON():t)}map(t){return iy(this,t)}forEach(t){po(this,t)}[Symbol.iterator](){return yN(this)}_write(t){t.writeTypeRef(HN)}}const vN=e=>new tr;class EN extends uc{constructor(t,n,r){super(t,n),this.keysChanged=r}}class nr extends at{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new nr}clone(){const t=new nr;return this.forEach((n,r)=>{t.set(r,n instanceof at?n.clone():n)}),t}_callObserver(t,n){hc(this,t,new EN(this,t,n))}toJSON(){this.doc??Dt();const t={};return this._map.forEach((n,r)=>{if(!n.deleted){const i=n.content.getContent()[n.length-1];t[r]=i instanceof at?i.toJSON():i}}),t}get size(){return[...mc(this)].length}keys(){return uf(mc(this),t=>t[0])}values(){return uf(mc(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return uf(mc(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Dt(),this._map.forEach((n,r)=>{n.deleted||t(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?Je(this.doc,n=>{pc(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?Je(this.doc,r=>{Ef(r,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return kf(this,t)}has(t){return uy(this,t)}clear(){this.doc!==null?Je(this.doc,t=>{this.forEach(function(n,r,i){pc(t,i,r)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(VN)}}const kN=e=>new nr,Zr=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&yO(e,t);class Sf{constructor(t,n,r,i){this.left=t,this.right=n,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Qn(),this.right.content.constructor){case Et:this.right.deleted||cs(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const fy=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case Et:t.right.deleted||cs(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n{const i=new Map,s=r?fc(t,n):null;if(s){const o=new Sf(s.p.left,s.p,s.index,i);return fy(e,o,n-s.index)}else{const o=new Sf(null,t._start,0,i);return fy(e,o,n)}},hy=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Et&&Zr(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach((o,a)=>{const c=n.left,l=n.right,u=new kt(Oe(s,Ot(i.store,s)),c,c&&c.lastId,l,l&&l.id,t,null,new Et(a,o));u.integrate(e,0),n.right=u,n.forward()})},cs=(e,t)=>{const{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},dy=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Et&&Zr(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},py=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)??null;if(!Zr(l,c)){o.set(a,l);const{left:u,right:f}=n;n.right=new kt(Oe(s,Ot(i.store,s)),u,u&&u.lastId,f,f&&f.id,t,null,new Et(a,c)),n.right.integrate(e,0),n.forward()}}return o},Af=(e,t,n,r,i)=>{n.currentAttributes.forEach((d,h)=>{i[h]===void 0&&(i[h]=null)});const s=e.doc,o=s.clientID;dy(n,i);const a=py(e,t,n,i),c=r.constructor===String?new ir(r):r instanceof at?new Rr(r):new Ai(r);let{left:l,right:u,index:f}=n;t._searchMarker&&ho(t._searchMarker,n.index,c.getLength()),u=new kt(Oe(o,Ot(s.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=f,n.forward(),hy(e,t,n,a)},my=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;dy(n,i);const a=py(e,t,n,i);e:for(;n.right!==null&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Et));){if(!n.right.deleted)switch(n.right.content.constructor){case Et:{const{key:c,value:l}=n.right.content,u=i[c];if(u!==void 0){if(Zr(u,l))a.delete(c);else{if(r===0)break e;a.set(c,l)}n.right.delete(e)}else n.currentAttributes.set(c,l);break}default:r0){let c="";for(;r>0;r--)c+=` +`;n.right=new kt(Oe(o,Ot(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new ir(c)),n.right.integrate(e,0),n.forward()}hy(e,t,n,a)},gy=(e,t,n,r,i)=>{let s=t;const o=Mn();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===Et){const l=s.content;o.set(l.key,l)}s=s.right}let a=0,c=!1;for(;t!==s;){if(n===t&&(c=!0),!t.deleted){const l=t.content;switch(l.constructor){case Et:{const{key:u,value:f}=l,d=r.get(u)??null;(o.get(u)!==l||d===f)&&(t.delete(e),a++,!c&&(i.get(u)??null)===f&&d!==f&&(d===null?i.delete(u):i.set(u,d))),!c&&!t.deleted&&cs(i,l);break}}}t=t.right}return a},SN=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Et){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},AN=e=>{let t=0;return Je(e.doc,n=>{let r=e._start,i=e._start,s=Mn();const o=Ku(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Et:cs(o,i.content);break;default:t+=gy(n,r,i,s,o),s=Ku(o),r=i;break}i=i.right}}),t},TN=e=>{const t=new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&q0(e,n.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===Et&&o.constructor!==ln&&t.add(o.parent)})}Je(n,r=>{O0(e,e.deleteSet,i=>{if(i instanceof ln||!i.parent._hasFormatting||t.has(i.parent))return;const s=i.parent;i.content.constructor===Et?t.add(s):SN(r,i)});for(const i of t)AN(i)})},yy=(e,t,n)=>{const r=n,i=Ku(t.currentAttributes),s=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Rr:case Ai:case ir:n{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];Je(t,r=>{const i=new Map,s=new Map;let o=this.target._start,a=null;const c={};let l="",u=0,f=0;const d=()=>{if(a!==null){let h=null;switch(a){case"delete":f>0&&(h={delete:f}),f=0;break;case"insert":(typeof l=="object"||l.length>0)&&(h={insert:l},i.size>0&&(h.attributes={},i.forEach((p,m)=>{p!==null&&(h.attributes[m]=p)}))),l="";break;case"retain":u>0&&(h={retain:u},pO(c)||(h.attributes=fO({},c))),u=0;break}h&&n.push(h),a=null}};for(;o!==null;){switch(o.content.constructor){case Rr:case Ai:this.adds(o)?this.deletes(o)||(d(),a="insert",l=o.content.getContent()[0],d()):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),f+=1):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=1);break;case ir:this.adds(o)?this.deletes(o)||(a!=="insert"&&(d(),a="insert"),l+=o.content.str):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),f+=o.length):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=o.length);break;case Et:{const{key:h,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const m=i.get(h)??null;Zr(m,p)?p!==null&&o.delete(r):(a==="retain"&&d(),Zr(p,s.get(h)??null)?delete c[h]:c[h]=p)}}else if(this.deletes(o)){s.set(h,p);const m=i.get(h)??null;Zr(m,p)||(a==="retain"&&d(),c[h]=m)}else if(!o.deleted){s.set(h,p);const m=c[h];m!==void 0&&(Zr(m,p)?m!==null&&o.delete(r):(a==="retain"&&d(),p===null?delete c[h]:c[h]=p))}o.deleted||(a==="insert"&&d(),cs(i,o.content));break}}o=o.right}for(d();n.length>0;){const h=n[n.length-1];if(h.retain!==void 0&&h.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Dn extends at{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Dt(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new Dn}clone(){const t=new Dn;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const r=new xN(this,t,n);hc(this,t,r),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Dt();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===ir&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?Je(this.doc,r=>{const i=new Sf(null,this._start,0,new Map);for(let s=0;s0)&&Af(r,this,i,a,o.attributes||{})}else o.retain!==void 0?my(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&yy(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,r){this.doc??Dt();const i=[],s=new Map,o=this.doc;let a="",c=this._start;function l(){if(a.length>0){const f={};let d=!1;s.forEach((p,m)=>{d=!0,f[m]=p});const h={insert:a};d&&(h.attributes=f),i.push(h),a=""}}const u=()=>{for(;c!==null;){if(as(c,t)||n!==void 0&&as(c,n))switch(c.content.constructor){case ir:{const f=s.get("ychange");t!==void 0&&!as(c,t)?(f===void 0||f.user!==c.id.client||f.type!=="removed")&&(l(),s.set("ychange",r?r("removed",c.id):{type:"removed"})):n!==void 0&&!as(c,n)?(f===void 0||f.user!==c.id.client||f.type!=="added")&&(l(),s.set("ychange",r?r("added",c.id):{type:"added"})):f!==void 0&&(l(),s.delete("ychange")),a+=c.content.str;break}case Rr:case Ai:{l();const f={insert:c.content.getContent()[0]};if(s.size>0){const d={};f.attributes=d,s.forEach((h,p)=>{d[p]=h})}i.push(f);break}case Et:as(c,t)&&(l(),cs(s,c.content));break}c=c.right}l()};return t||n?Je(o,f=>{t&&mf(f,t),n&&mf(f,n),u()},"cleanup"):u(),i}insert(t,n,r){if(n.length<=0)return;const i=this.doc;i!==null?Je(i,s=>{const o=gc(s,this,t,!r);r||(r={},o.currentAttributes.forEach((a,c)=>{r[c]=a})),Af(s,this,o,n,r)}):this._pending.push(()=>this.insert(t,n,r))}insertEmbed(t,n,r){const i=this.doc;i!==null?Je(i,s=>{const o=gc(s,this,t,!r);Af(s,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(t,n,r||{}))}delete(t,n){if(n===0)return;const r=this.doc;r!==null?Je(r,i=>{yy(i,gc(i,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,r){if(n===0)return;const i=this.doc;i!==null?Je(i,s=>{const o=gc(s,this,t,!1);o.right!==null&&my(s,this,o,n,r)}):this._pending.push(()=>this.format(t,n,r))}removeAttribute(t){this.doc!==null?Je(this.doc,n=>{pc(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?Je(this.doc,r=>{Ef(r,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return kf(this,t)}getAttributes(){return ly(this)}_write(t){t.writeTypeRef(KN)}}const RN=e=>new Dn;class Tf{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Dt()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===xr||n.constructor===rr)&&n._start!==null)t=n._start;else for(;t!==null;)if(t.right!==null){t=t.right;break}else t.parent===this._root?t=null:t=t.parent._item;while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class rr extends at{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new rr}clone(){const t=new rr;return t.insert(0,this.toArray().map(n=>n instanceof at?n.clone():n)),t}get length(){return this.doc??Dt(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Tf(this,t)}querySelector(t){t=t.toUpperCase();const r=new Tf(this,i=>i.nodeName&&i.nodeName.toUpperCase()===t).next();return r.done?null:r.value}querySelectorAll(t){return t=t.toUpperCase(),Hr(new Tf(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){hc(this,t,new NN(this,n,t))}toString(){return iy(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},r){const i=t.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),po(this,s=>{i.insertBefore(s.toDOM(t,n,r),null)}),i}insert(t,n){this.doc!==null?Je(this.doc,r=>{ay(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)Je(this.doc,r=>{const i=t&&t instanceof at?t._item:t;dc(r,this,i,n)});else{const r=this._prelimContent,i=t===null?0:r.findIndex(s=>s===t)+1;if(i===0&&t!==null)throw qr("Reference item not found");r.splice(i,0,...n)}}delete(t,n=1){this.doc!==null?Je(this.doc,r=>{cy(r,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return ry(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return sy(this,t)}slice(t=0,n=this.length){return ny(this,t,n)}forEach(t){po(this,t)}_write(t){t.writeTypeRef(JN)}}const IN=e=>new rr;class xr extends rr{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new xr(this.nodeName)}clone(){const t=new xr(this.nodeName),n=this.getAttributes();return dO(n,(r,i)=>{typeof r=="string"&&t.setAttribute(i,r)}),t.insert(0,this.toArray().map(r=>r instanceof at?r.clone():r)),t}toString(){const t=this.getAttributes(),n=[],r=[];for(const a in t)r.push(a);r.sort();const i=r.length;for(let a=0;a0?" "+n.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?Je(this.doc,n=>{pc(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?Je(this.doc,r=>{Ef(r,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return kf(this,t)}hasAttribute(t){return uy(this,t)}getAttributes(t){return t?bN(this,t):ly(this)}toDOM(t=document,n={},r){const i=t.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const a=s[o];typeof a=="string"&&i.setAttribute(o,a)}return po(this,o=>{i.appendChild(o.toDOM(t,n,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(t){t.writeTypeRef(qN),t.writeKey(this.nodeName)}}const ON=e=>new xr(e.readKey());class NN extends uc{constructor(t,n,r){super(t,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class ls extends nr{constructor(t){super(),this.hookName=t}_copy(){return new ls(this.hookName)}clone(){const t=new ls(this.hookName);return this.forEach((n,r)=>{t.set(r,n)}),t}toDOM(t=document,n={},r){const i=n[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(t){t.writeTypeRef(XN),t.writeKey(this.hookName)}}const CN=e=>new ls(e.readKey());class Si extends Dn{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Si}clone(){const t=new Si;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,r){const i=t.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(t=>{const n=[];for(const i in t.attributes){const s=[];for(const o in t.attributes[i])s.push({key:o,value:t.attributes[i][o]});s.sort((o,a)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(ZN)}}const LN=e=>new Si;class xf{constructor(t,n){this.id=t,this.length=n}get deleted(){throw Yn()}mergeWith(t){return!1}write(t,n,r){throw Yn()}integrate(t,n){throw Yn()}}const MN=0;class ln extends xf{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),V0(t.doc.store,this)}write(t,n){t.writeInfo(MN),t.writeLen(this.length-n)}getMissing(t,n){return null}}class mo{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new mo(this.content)}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const UN=e=>new mo(e.readBuf());class go{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new go(this.len)}splice(t){const n=new go(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){sc(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const PN=e=>new go(e.readLen()),_y=(e,t)=>new Tr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class yo{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new yo(_y(this.doc.guid,this.opts))}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const DN=e=>new yo(_y(e.readString(),e.readAny()));class Ai{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Ai(this.embed)}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const BN=e=>new Ai(e.readJSON());class Et{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Et(this.key,this.value)}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){const r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const FN=e=>new Et(e.readKey(),e.readJSON());class yc{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new yc(this.arr)}splice(t){const n=new yc(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const r=this.arr.length;t.writeLen(r-n);for(let i=n;i{const t=e.readLen(),n=[];for(let r=0;r{const t=e.readLen(),n=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const WN=e=>new ir(e.readString()),GN=[vN,kN,RN,ON,IN,CN,LN],HN=0,VN=1,KN=2,qN=3,JN=4,XN=5,ZN=6;class Rr{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Rr(this.type._copy())}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(t.beforeState.get(r.id.client)||0)&&t._mergeStructs.push(r):r.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(t,!0),r=r.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const YN=e=>new Rr(GN[e.readTypeRef()](e)),_c=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new kt(Oe(r,i+n),t,Oe(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),t.redone!==null&&(s.redone=Oe(t.redone.client,t.redone.clock+n)),t.right=s,s.right!==null&&(s.right.left=s),e._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),t.length=n,s};class kt extends xf{constructor(t,n,r,i,s,o,a,c){super(t,c.getLength()),this.origin=r,this.left=n,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?o0:0}set marker(t){(this.info&Xu)>0!==t&&(this.info^=Xu)}get marker(){return(this.info&Xu)>0}get keep(){return(this.info&s0)>0}set keep(t){this.keep!==t&&(this.info^=s0)}get countable(){return(this.info&o0)>0}get deleted(){return(this.info&Ju)>0}set deleted(t){this.deleted!==t&&(this.info^=Ju)}markDeleted(){this.info|=Ju}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Ot(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Ot(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===os&&this.id.client!==this.parent.client&&this.parent.clock>=Ot(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=K0(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Jr(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ln||this.right&&this.right.constructor===ln)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===kt&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===kt&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===os){const r=gf(n,this.parent);r.constructor===ln?this.parent=null:this.parent=r.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=K0(t,t.doc.store,Oe(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),oc(this.origin,i.origin)){if(i.id.client{r.p===t&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),sc(t.deleteSet,this.id.client,this.id.clock,this.length),X0(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw Qn();this.content.gc(t),n?rN(t,this,new ln(this.id,this.length)):this.content=new go(this.length)}write(t,n){const r=n>0?Oe(this.id.client,this.id.clock+n-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&Qa|(r===null?0:cn)|(i===null?0:kr)|(s===null?0:ro);if(t.writeInfo(o),r!==null&&t.writeLeftID(r),i!==null&&t.writeRightID(i),r===null&&i===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const l=nN(a);t.writeParentInfo(!0),t.writeString(l)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else a.constructor===String?(t.writeParentInfo(!0),t.writeString(a)):a.constructor===os?(t.writeParentInfo(!1),t.writeLeftID(a)):Qn();s!==null&&t.writeString(s)}this.content.write(t,n)}}const by=(e,t)=>QN[t&Qa](e),QN=[()=>{Qn()},PN,$N,UN,WN,BN,FN,YN,zN,DN,()=>{Qn()}],eC=10;class Sn extends xf{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){Qn()}write(t,n){t.writeInfo(eC),ve(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const wy=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},vy="__ $YJS$ __";wy[vy]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438"),wy[vy]=!0;let Rf,If,tC=e=>e();function nC(e,t){if(If)return If(e,t);tC(e)}function xi(e,t,n){if(Rf)return Rf.apply(null,arguments);throw new Error("observable implementation not provided. Call enableReactiveBindings, enableVueBindings or enableMobxBindings.")}function rC(e){Rf=function(t,n,r){const i=e.createAtom(t);return n&&n(),i},If=(t,n)=>e.reaction(t,n,{fireImmediately:!1})}const Ey=new WeakSet;function iC(e){if(Ey.has(e))return e;Ey.add(e);let t;const n=new Map;function r(){if(!t){const f=d=>{(d.changes.added.size||d.changes.deleted.size||d.changes.keys.size||d.changes.delta.length)&&t.reportChanged()};t=xi("map",()=>{e.observe(f)},()=>{e.unobserve(f)})}t.reportObserved(e._implicitObserver)}function i(f){let d=n.get(f);if(!d){const h=p=>{d.reportChanged()};d=xi(f+"",()=>{e.observe(h)},()=>{e.unobserve(h)}),n.set(f,d)}d.reportObserved(e._implicitObserver)}const s=e.get;e.get=function(f){if(typeof f!="number")throw new Error("unexpected");return i(f),Reflect.apply(s,this,arguments)};function o(f){const d=e[f];e[f]=function(){return r(),Reflect.apply(d,this,arguments)}}function a(f){let d=e,h=Object.getOwnPropertyDescriptor(d,f);if(h||(d=Object.getPrototypeOf(d),h=Object.getOwnPropertyDescriptor(d,f)),h||(d=Object.getPrototypeOf(d),h=Object.getOwnPropertyDescriptor(d,f)),!h)throw new Error("property not found");const p=h.get;h.get=function(){return this._disableTracking||r(),Reflect.apply(p,this,arguments)},Object.defineProperty(e,f,h)}function c(f,d){let h=e,p=Object.getOwnPropertyDescriptor(h,f);if(p||(h=Object.getPrototypeOf(h),p=Object.getOwnPropertyDescriptor(h,f)),p||(h=Object.getPrototypeOf(h),p=Object.getOwnPropertyDescriptor(h,f)),!p)throw new Error("property not found");Object.defineProperty(e,d,p)}o("forEach"),o("toJSON"),o("toArray"),o("slice"),o("map"),c("length","lengthUntracked"),a("length");const l=e.push;e.push=function(f){this._disableTracking=!0;const d=l.call(this,f);return this._disableTracking=!1,d};const u=e.slice;return e.slice=function(f,d){this._disableTracking=!0;const h=u.call(this,f,d);return this._disableTracking=!1,h},e}const ky=new WeakSet;function sC(e){if(ky.has(e))return e;ky.add(e);let t;function n(){if(!t){let s=Array.from(e.share.keys());const o=a=>{const c=Array.from(e.share.keys());JSON.stringify(s)!==JSON.stringify(c)&&(s=c,t.reportChanged())};t=xi("map",()=>{e.on("beforeObserverCalls",o)},()=>{e.off("beforeObserverCalls",o)})}t.reportObserved(e._implicitObserver)}const r=e.get;e.get=function(s){if(typeof s!="string")throw new Error("unexpected");const o=Reflect.apply(r,this,arguments);return bc(o),o};function i(s){const o=e[s];let a;e[s]=function(){let c,l=arguments;return n(),a&&a.removeObservers(),a=nC(()=>(c=Reflect.apply(o,e,l),c),()=>t.reportChanged()),c}}return i("toJSON"),Object.defineProperty(e,"keys",{get:()=>(n(),Object.keys(e.share))}),e}const Sy=new WeakSet;function oC(e){if(Sy.has(e))return e;Sy.add(e);let t;const n=new Map;function r(){if(!t){const a=c=>{(c.changes.added.size||c.changes.deleted.size||c.changes.keys.size||c.changes.delta.length)&&t.reportChanged()};t=xi("map",()=>{e.observe(a)},()=>{e.unobserve(a)})}t.reportObserved(e._implicitObserver)}function i(a){let c=n.get(a);if(!c){const l=u=>{u.keysChanged.has(a)&&(u.changes.added.size||u.changes.deleted.size||u.changes.keys.size||u.changes.delta.length)&&c.reportChanged()};c=xi(a,()=>{e.observe(l)},()=>{e.unobserve(l)}),n.set(a,c)}c.reportObserved(e._implicitObserver)}const s=e.get;e.get=function(a){if(typeof a!="string")throw new Error("unexpected");return i(a),Reflect.apply(s,this,arguments)};function o(a){const c=e[a];e[a]=function(){return r(),Reflect.apply(c,this,arguments)}}return o("values"),o("entries"),o("keys"),o("forEach"),o("toJSON"),e}const Ay=new WeakSet;function Ty(e){if(Ay.has(e))return e;Ay.add(e);let t;const n=i=>{t.reportChanged()};t=xi("text",()=>{e.observe(n)},()=>{e.unobserve(n)});function r(i){const s=e[i];e[i]=function(){return t.reportObserved(this._implicitObserver),Reflect.apply(s,this,arguments)}}return r("toString"),r("toJSON"),e}const xy=new WeakSet;function Ry(e){if(xy.has(e))return e;xy.add(e);let t;const n=s=>{(s.changes.added.size||s.changes.deleted.size||s.changes.keys.size||s.changes.delta.length)&&t.reportChanged()};t=xi("xml",()=>{e.observe(n)},()=>{e.unobserve(n)});function r(s){const o=e[s];e[s]=function(){return t.reportObserved(this._implicitObserver),Reflect.apply(o,this,arguments)}}function i(s){let o=e,a=Object.getOwnPropertyDescriptor(o,s);if(a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),!a)throw new Error("property not found");const c=a.get;a.get=function(){return t.reportObserved(this._implicitObserver),Reflect.apply(c,this,arguments)},Object.defineProperty(e,s,a)}return r("toString"),r("toDOM"),r("toArray"),r("getAttribute"),i("firstChild"),e}function bc(e){return e instanceof Si||e instanceof Dn?Ty(e):e instanceof tr?iC(e):e instanceof nr?oC(e):e instanceof Tr||Object.prototype.hasOwnProperty.call(e,"autoLoad")?sC(e):e instanceof rr||e instanceof xr?Ry(e):e}function Iy(e){e.share.forEach(t=>{t.constructor!==at&&bc(t)})}function Oy(e,t){for(let r=e.length-1;r>=t;r--){let i=e[r];if(!i.deleted){var n;if(i instanceof ln)continue;(n=i.content)==null||n.getContent().forEach(s=>{s instanceof at&&bc(s)})}}}const Ny=new WeakSet;function aC(e){Ny.has(e)||(Ny.add(e),bc(e),e.store.clients.forEach(t=>{t&&Oy(t,0)}),Iy(e),e.on("beforeObserverCalls",t=>{Iy(e),t.afterState.forEach((n,r)=>{const i=t.beforeState.get(r)||0;if(i!==n){const s=t.doc.store.clients.get(r);if(!s)return;const o=Pn(s,i);Oy(s,o)}})}))}class _o{constructor(t){this.value=void 0,this.value=t}}function cC(e){return ArrayBuffer.isView(e)?new _o(e):new _o(Object.freeze(e))}function lC(e){const t=function(){var a;let c=(a=this[kn])==null?void 0:a.implicitObserver;return e._implicitObserver=c,e.slice.bind(e).apply(e,arguments).map(u=>{const f=wc(u,c);return c&&typeof f=="object"?no(f,c):f})},n=function(a){return a.map(c=>{const l=Of(c);let u=Ri(l)||l;if(u instanceof _o&&(u=u.value),u instanceof at&&u.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return u})},r=function(){return[].findIndex.apply(t.apply(this),arguments)},i={slice:t,unshift:(...o)=>(e.unshift(n(o)),e.lengthUntracked),push:(...o)=>(e.push(n(o)),e.lengthUntracked),insert:e.insert.bind(e),toJSON:e.toJSON.bind(e),forEach:function(){return[].forEach.apply(t.apply(this),arguments)},every:function(){return[].every.apply(t.apply(this),arguments)},filter:function(){return[].filter.apply(t.apply(this),arguments)},find:function(){return[].find.apply(t.apply(this),arguments)},findIndex:r,some:function(){return[].some.apply(t.apply(this),arguments)},includes:function(){return[].includes.apply(t.apply(this),arguments)},map:function(){return[].map.apply(t.apply(this),arguments)},indexOf:function(){const o=arguments[0];return r.call(this,a=>pC(a,o))},splice:function(){let o=arguments[0]<0?e.length-Math.abs(arguments[0]):arguments[0],a=arguments[1],c=Array.from(Array.from(arguments).slice(2)),l=t.apply(this,[o,Number.isInteger(a)?o+a:void 0]);return e.doc?e.doc.transact(()=>{e.delete(o,a),e.insert(o,n(c))}):(e.delete(o,a),e.insert(o,n(c))),l}},s=[];for(let o in i)s[o]=i[o];return s}function bo(e){if(typeof e=="string"&&e.trim().length){const t=Number(e);if(Number.isInteger(t))return t}return e}function Cy(e,t=new tr){if(t[vt])throw new Error("unexpected");const n=lC(t),r=new Proxy(n,{set:(i,s,o)=>{throw typeof bo(s)!="number"?new Error:new Error("array assignment is not implemented / supported")},get:(i,s,o)=>{const a=bo(s);if(a===vc)return t;if(typeof a=="number"){let u;if(o&&o[kn]){var c;u=(c=o[kn])==null?void 0:c.implicitObserver,t._implicitObserver=u}let f=t.get(a);return f=wc(f,u),f}if(a===Symbol.toStringTag)return"Array";if(a===Symbol.iterator){const u=t.slice();return Reflect.get(u,a)}return a==="length"?t.length:Reflect.get(i,a,o)},deleteProperty:(i,s)=>{const o=bo(s);if(typeof o!="number")throw new Error;return o=0?(t.delete(o),!0):!1},has:(i,s)=>{const o=bo(s);return typeof o!="number"?Reflect.has(i,o):o=0},getOwnPropertyDescriptor(i,s){const o=bo(s);if(o==="length")return{enumerable:!1,configurable:!1,writable:!0};if(typeof o=="number"&&o>=0&&o{const s=[];for(let o=0;o{if(typeof i!="string")throw new Error;const o=Of(s);let a=Ri(o)||o;if(a instanceof _o&&(a=a.value),a instanceof at&&a.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return t.set(i,a),!0},get:(r,i,s)=>{if(i===vc)return t;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[kn]){var a;o=(a=s[kn])==null?void 0:a.implicitObserver,t._implicitObserver=o}let c=t.get(i);return c=wc(c,o),c},deleteProperty:(r,i)=>{if(typeof i!="string")throw new Error;return t.has(i)?(t.delete(i),!0):!1},has:(r,i)=>!!(typeof i=="string"&&t.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&t.has(i))return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(t.keys())});wo.set(t,n);for(let r in e)n[r]=e[r];return n}function uC(e){return e instanceof at}const wo=new WeakMap;function wc(e,t){if(uC(e)){if(e._implicitObserver=t,e instanceof tr||e instanceof nr){if(!wo.has(e)){const n=Of(e);wo.set(e,n)}e=wo.get(e)}else if(e instanceof xr||e instanceof rr||e instanceof Si||e instanceof ls||e instanceof Dn)Hu(e),e.__v_skip=!0;else throw new Error("unknown YType");return e}else{if(e===null)return null;if(typeof e=="object")return cC(e)}return e}function Of(e){if(e==null)return e;if(e=Ri(e)||e,e instanceof tr)return Cy([],e);if(e instanceof nr)return Ly({},e);if(typeof e=="string")return e;if(Array.isArray(e))return Cy(e);if(e instanceof xr||e instanceof rr||e instanceof Si||e instanceof ls)return e;if(e instanceof Dn)return e;if(typeof e=="object")return e instanceof _o?e:Ly(e);if(typeof e=="number"||typeof e=="boolean")return e;throw new Error("invalid")}function fC(e){for(let[t,n]of Object.entries(e))if(Array.isArray(n)){if(n.length!==0)throw new Error("Root Array initializer must always be empty array")}else if(n&&typeof n=="object"){if(Object.keys(n).length!==0||Object.getPrototypeOf(n)!==Object.prototype)throw new Error("Root Object initializer must always be {}")}else if(n!=="xml"&&n!=="text")throw new Error("unknown Root initializer")}function My(e,t,n){let r=t[n];if(!r){n!=="__v_raw"&&n!=="__v_isRef"&&n!=="__v_isReadonly"&&console.warn("property not found on root doc",n);return}return r==="xml"?e.getXmlFragment(n):r==="text"?e.getText(n):Array.isArray(r)?e.getArray(n):e.getMap(n)}function hC(e,t){if(e[vt])throw new Error("unexpected");fC(t);const n=new Proxy({},{set:(r,i,s)=>{throw typeof i!="string"?new Error:new Error("cannot set new elements on root doc")},get:(r,i,s)=>{if(i===vc)return e;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[kn]){var a;o=(a=s[kn])==null?void 0:a.implicitObserver,e._implicitObserver=o}if(i==="toJSON"){for(let u of Object.keys(t))My(e,t,u);return Reflect.get(e,i)}let c=My(e,t,i);return c=wc(c,o),c},deleteProperty:(r,i)=>{throw new Error("deleteProperty not available for doc")},has:(r,i)=>!!(typeof i=="string"&&e.share.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&e.share.has(i)||i==="toJSON")return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(e.share.keys())});return wo.set(e,n),n}rC(NI);const vc=Symbol("INTERNAL_SYMBOL");function Uy(e,t){const n=Ri(e)||e;if(!n)throw new Error("not a valid synced object");return n instanceof Tr?(n.on("update",t),()=>{n.off("update",t)}):(n.observeDeep(t),()=>{n.unobserveDeep(t)})}function dC(e){const t=Ri(e);if(!(t instanceof Tr))throw new Error("store is not a valid syncedStore that maps to a Y.Doc");return t}function Ri(e){if(typeof e!="object"||e===null)return;const t=e[vc];return t&&(Hu(t),t.__v_skip=!0),t}function pC(e,t){if(e===t)return!0;if(typeof e=="object"&&typeof t=="object"){const n=Ri(e),r=Ri(t);return!n||!r?!1:n===r}return!1}function mC(e,t=new Tr){return aC(t),hC(t,e)}var Re={};/** * @license React * react.production.min.js * @@ -148,10 +148,10 @@ Make sure that all grammar rule definitions are done before 'performSelfAnalysis * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var vo=Symbol.for("react.element"),mC=Symbol.for("react.portal"),gC=Symbol.for("react.fragment"),yC=Symbol.for("react.strict_mode"),_C=Symbol.for("react.profiler"),bC=Symbol.for("react.provider"),wC=Symbol.for("react.context"),vC=Symbol.for("react.forward_ref"),EC=Symbol.for("react.suspense"),kC=Symbol.for("react.memo"),SC=Symbol.for("react.lazy"),Py=Symbol.iterator;function AC(e){return e===null||typeof e!="object"?null:(e=Py&&e[Py]||e["@@iterator"],typeof e=="function"?e:null)}var Dy={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},By=Object.assign,Fy={};function us(e,t,n){this.props=e,this.context=t,this.refs=Fy,this.updater=n||Dy}us.prototype.isReactComponent={},us.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},us.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function $y(){}$y.prototype=us.prototype;function Nf(e,t,n){this.props=e,this.context=t,this.refs=Fy,this.updater=n||Dy}var Cf=Nf.prototype=new $y;Cf.constructor=Nf,By(Cf,us.prototype),Cf.isPureReactComponent=!0;var jy=Array.isArray,zy=Object.prototype.hasOwnProperty,Lf={current:null},Wy={key:!0,ref:!0,__self:!0,__source:!0};function Gy(e,t,n){var r,i={},s=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(s=""+t.key),t)zy.call(t,r)&&!Wy.hasOwnProperty(r)&&(i[r]=t[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1{ve(e,Pf);const n=QO(t);Pt(e,n)},Jy=(e,t,n)=>{ve(e,Ky),Pt(e,JO(t,n))},NC=(e,t,n)=>Jy(t,n,Ht(e)),Xy=(e,t,n)=>{try{VO(t,Ht(e),n)}catch(r){console.error("Caught error while handling a Yjs update",r)}},CC=(e,t)=>{ve(e,qy),Pt(e,t)},LC=Xy,MC=(e,t,n,r)=>{const i=Ee(e);switch(i){case Pf:NC(e,t,n);break;case Ky:Xy(e,n,r);break;case qy:LC(e,n,r);break;default:throw new Error("Unknown message type")}return i},Ir=pC({shared:[]});function Ac(e,t,n){return e.find(r=>r.key===t&&r.type===n)}function Zy(e,t,n){const r=Ac(Ir.shared,e,t);k(r)||Ir.shared.push({key:e,type:t,value:n})}function UC(e,t){Zy(e,0,t)}function Yy(e,t){const n=new Dn(t);Zy(e,1,n)}function PC(e,t){const n=Ac(Ir.shared,e,0);if(k(n)){n.value=t;return}Ir.shared.push({key:e,type:0,value:t})}function DC(e,t){const n=new Dn(t),r=Ac(Ir.shared,e,1);if(k(r)){r.value=n;return}Ir.shared.push({key:e,type:1,value:n})}function Qy(e,t,n){let r;function i(){const o=Ac(Ir.shared,e,t);k(o)&&(s(),r=Uy(o,()=>n(o.value)))}const s=Uy(Ir.shared,i);return i(),()=>r==null?void 0:r()}function BC(e,t){return Qy(e,0,t)}function e_(e,t){return Qy(e,1,n=>t(n.toJSON()))}function Tc(e){return Un(e)}let t_=!1;const Yr=hC(Ir),Or=Po("modem",["second"],e=>{switch(e.target){case"second":!t_&&e.data%2===0&&Or.emit("modem:join");break;case"join":if(e.sender!==Or.id()){Or.reply(e,"joinack");const t=Kr();OC(t,Yr),Or.reply(e,"sync",Tc(t));const n=Kr();Jy(n,Yr),Or.reply(e,"sync",Tc(n))}break;case"joinack":t_=!0;break;case"sync":{if(k(e.data)&&e.sender!==Or.id()){const t=Ei(e.data),n=Kr();MC(t,n,Yr,Or)===Pf&&Or.emit("modem:sync",Tc(n))}break}}});function n_(e){const t=Kr();CC(t,e),Or.emit("modem:sync",Tc(t))}Yr.on("update",n_),Yr.on("destroy",()=>{Yr==null||Yr.off("update",n_)});const FC=navigator.userAgent.includes("Mac")?"cmd":"ctrl",Qr="$dkpurple",$C="$196",jC="$205";function un(e,t){return`$${e}${t}$blue`}function r_(e,t){return`$${e}${t}$ondkblue`}function rt(e,t){yt(e,t)}function zC(e,t){const n=$C.repeat(t);rt(e,`${Qr}${n}`)}function Df(e,t){const n=jC.repeat(t);rt(e,`${Qr}${n}`)}function Eo(e,t){rt(e,`${Qr} ${" ".repeat(t.length)} `),zC(e,t.length+2),rt(e,`${Qr} $white${t} `),Df(e,t.length+2)}function Nr(e,t){rt(e,`${Qr} ${" ".repeat(t.length)} `),rt(e,`${Qr} $gray${t} `),Df(e,t.length+2)}function De(e,t,n){rt(e,`${Qr} $white${t} $blue${n}`)}function Be(e,t){rt(e,`${Qr}$blue${t}`)}const WC=lr().command("send",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.ANY]);switch(n){case"helpmenu":Eo("cli","H E L P"),De("cli","#help controls","zss controls and inputs"),rt("cli","!helpcontrols;read help controls"),rt("cli",""),De("cli","#help text","text formatting"),rt("cli","!helptext;read help text"),rt("cli",""),De("cli","#help developer","developer commands"),rt("cli","!helpdeveloper;read help developer"),rt("cli",""),De("cli","#help player","player settings"),rt("cli","!helpplayer;read help player"),Nr("cli","keyboard input"),De("cli","?","open console"),De("cli","esc","close console"),De("cli","tab","move console"),De("cli","up / down arrow keys","navigate console items"),De("cli","left / right arrow keys","change console items"),De("cli","enter","interact with console items"),De("cli","alt + arrow keys","skip words and console lines"),De("cli",`${FC} + up / down arrow keys`,"input history");break;case"helpcontrols":Eo("cli","zss controls and inputs"),Nr("cli","keyboard input"),De("cli","arrow keys","move"),De("cli","shift + arrow keys","shoot"),De("cli","enter","ok / accept"),De("cli","escape","cancel / close"),De("cli","tab","menu / action"),Nr("cli","mouse input"),Be("cli","todo ???"),Nr("cli","controller input"),De("cli","left stick","move"),De("cli","right stick","aim"),De("cli","a","ok / accept"),De("cli","b","cancel / close"),De("cli","y","menu / action"),De("cli","x","shoot"),De("cli","triggers","shoot");break;case"helptext":Eo("cli","text formatting"),Nr("cli","typography"),Be("cli","plain text"),Be("cli","$centering text"),Be("cli",'"\\"@quoted strings for special chars\\""'),Be("cli","$$0-255 for ascii chars $159$176$240"),Be("cli",`use color names like ${un("red","$$red")} to change foreground color`),Be("cli",`use color names like ${r_("ongreen","$$ongreen")} to change background color`),Be("cli",`use clear ${r_("onclear","to change background to")} transparent`),Nr("cli","hyperlinks"),Be("cli",`${un("white",'"!hotkey"')} message shortcut;${un("gray","Label")}`),Be("cli",`${un("white",'"!range"')} flag [labelmin] [labelmax];${un("gray","Input Label")}`),Be("cli",`${un("white",'"!select"')} flag ...list of values;${un("gray","Input Label")}`),Be("cli",`${un("white",'"!number"')} flag [minvalue] [maxvalue];${un("gray","Input Label")}`),Be("cli",`${un("white",'"!text"')} flag;${un("gray","Input Label")}`),Be("cli",`${un("white",'"!copyit"')} flag;${un("gray","Input Label")}`);break;case"helpdeveloper":Eo("cli","developer commands"),De("cli","#books","list books in memory"),De("cli","#pages","list pages in opened book"),De("cli","@[pagetype:]page name","create & edit a new codepage in the currently opened book"),De("cli","#trash","list books and pages from open book you can delete"),De("cli","#save","flush state to register");break;case"helpplayer":Eo("cli","player settings"),Be("cli","todo");break;default:yt("$2",`${n} ${r??""}`);break}return 0}).command("stat",(e,t)=>{let n;const[r,...i]=t.map(Nt),s=i.join(" ");switch(Pe(r)){case bn(fe.LOADER):n=Mi(Xe.CONTENT,s,Ae.LOADER);break;default:n=Mi(Xe.CONTENT,[r,...i].join(" "),Ae.OBJECT);break;case bn(fe.BOARD):n=Mi(Xe.CONTENT,s,Ae.BOARD);break;case bn(fe.OBJECT):n=Mi(Xe.CONTENT,s,Ae.OBJECT);break;case bn(fe.TERRAIN):n=Mi(Xe.CONTENT,s,Ae.TERRAIN);break;case bn(fe.CHARSET):n=Mi(Xe.CONTENT,s,Ae.CHARSET);break;case bn(fe.PALETTE):n=Mi(Xe.CONTENT,s,Ae.PALETTE);break}return k(n)&&e.command("pageopen",n.id),0}).command("text",(e,t)=>{const n=t.map(Nt).join(" ");return yt("$2",n),0}).command("hyperlink",(e,t)=>{const[n,...r]=t,i=Nt(n),s=r.map(Nt).join(" ");return yt("$2",`!${s};${i}`),0}).command("dev",()=>(ni("cli"),Nb("cli",C.player),0)).command("share",()=>(ni("cli"),Cb("cli",C.player),0)).command("bookcreate",(e,t)=>{const[n]=ne(t,0,[q.MAYBE_STRING]),r=$_(n);return k(r)&&e.command("bookopen",r.id),0}).command("bookopen",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=ti(n);return k(r)?(Be("cli",`opened [book] ${r.name}`),Dc(Xe.MAIN,r.id),e.command("pages")):et("cli","bookopen",`book ${n} not found`,C.player),0}).command("booktrash",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=nn(Xe.MAIN),i=ti(n);return k(i)&&(r===i&&Dc(Xe.MAIN,""),IM(n),Be("cli",`trashed [book] ${i.name}`),ni("cli"),e.command("pages")),0}).command("pageopen",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=Bn(Xe.MAIN);if(!k(r))return 0;const i=yi(r,n);if(k(i)){const s=Xn(i),o=Zs(i);Be("cli",`opened [${o}] ${s}`),Yy(ph(r.id,i.id),i.code);const a=Zs(i);Fb("cli",r.id,i.id,a,`${s} - ${r.name}`,C.player)}else et("cli","pageopen",`page ${n} not found`,C.player);return 0}).command("pagetrash",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=Bn(Xe.MAIN),i=KR(r,n);if(k(n)){const s=Xn(i),o=Zs(i);Be("cli",`trashed [${o}] ${s}`),ni("cli"),e.command("pages")}return 0}).command("nodetrash",()=>(Ub("cli"),Be("cli","node id changed, refreshing page recommended"),0)).command("help",(e,t)=>{const n=t.map(Nt).join(" ")||"menu";return e.command(`help${n}`),0}).command("books",()=>{Nr("cli","books");const e=nn(Xe.MAIN);De("cli","main",`${(e==null?void 0:e.name)??"empty"} $GREEN${(e==null?void 0:e.id)??""}`);const t=nn(Xe.CONTENT);De("cli","content",`${(t==null?void 0:t.name)??"empty"} ${(t==null?void 0:t.id)??""}`),Df("cli",7);const n=Pc();return n.length?n.forEach(r=>{rt("cli",`!bookopen ${r.id};${r.name}`)}):Be("cli","no books found"),rt("cli","!bookcreate;create a new book"),0}).command("pages",()=>{Nr("cli","pages");const e=Bn(Xe.MAIN);return k(e)&&(De("cli","main",`${e.name} $GREEN${e.id}`),e.pages.length?e.pages.forEach(t=>{const n=Xn(t),r=Zs(t);rt("cli",`!pageopen ${t.id};[${r}] ${n}`)}):(rt("cli",""),Be("cli","no pages found"),Be("cli","use @ to create a page"),Be("cli","@board name of board"),Be("cli","@object name of object"),Be("cli","@terrain name of terrain"),Be("cli","You can omit the type and it will default to object"),Be("cli","@object name of object"),Be("cli","@name of object"))),0}).command("trash",()=>{Nr("cli","$REDTRASH"),Be("cli","books");const e=Pc();e.length&&(e.forEach(n=>{rt("cli",`!booktrash ${n.id};$REDTRASH ${n.name}`)}),rt("cli",""));const t=nn(Xe.MAIN);return k(t)&&(Be("cli",`pages in open ${t.name} book`),t.pages.forEach(n=>{const r=Xn(n);rt("cli",`!pagetrash ${n.id};$REDTRASH ${r}`)}),rt("cli","")),0}).command("save",()=>(ni("cli"),0)).command("nuke",()=>(Mb("cli"),0));function GC(e){const t=Og[e];if(k(t))return t;const n=Mg[e];if(k(n))return n;const r=Ga[e];if(k(r))return r;const i=kh[e];if(k(i))return i}const HC=lr({get(e,t){const n=GC(t);return k(n)?[!0,n]:[!1,void 0]}}),VC=new Set(["inputmove","inputalt","inputctrl","inputshift","inputok","inputcancel","inputmenu"]),i_=new Set(["player","pushable","collision","destructible","p1","p2","p3","cycle","stepx","stepy","sender","arg"]),KC=["NORTH","SOUTH","WEST","EAST"];function qC(){const e=ps(C.player);if(Ge(e.inputqueue)||(e.inputqueue=[],e.inputcurrent=0),ke(e.inputcurrent)&&e.inputcurrent>0)return;const[t]=e.inputqueue,[n=Ft.NONE,r=0]=t??[Ft.NONE,0];switch(e.inputmove=[],e.inputok=0,e.inputcancel=0,e.inputmenu=0,e.inputalt=r&Ab?1:0,e.inputctrl=r&Tb?1:0,e.inputshift=r&xb?1:0,n){case Ft.MOVE_UP:case Ft.MOVE_DOWN:case Ft.MOVE_LEFT:case Ft.MOVE_RIGHT:e.inputmove=[KC[n-Ft.MOVE_UP]];break;case Ft.OK_BUTTON:e.inputok=1;break;case Ft.CANCEL_BUTTON:e.inputcancel=1;break;case Ft.MENU_BUTTON:e.inputmenu=1;break}e.inputcurrent=n,e.inputqueue=e.inputqueue.filter(i=>{const[s]=i;return s!==Ft.NONE&&s!==n})}const JC=lr({get(e,t){var s;C.isplayer&&VC.has(t)&&qC();const n=(s=C.element)==null?void 0:s[t];if(k(n)||i_.has(t))return[!0,n];const i=ps(C.player)[t];return[k(i),i]},set(e,t,n){var s;const r=(s=C.element)==null?void 0:s[t];if(k(r)||i_.has(t))return k(C.element)&&(C.element[t]=n),[!0,n];const i=ps(C.player);return i[t]=n,[!0,n]},everytick(e){var t,n;k((t=C.element)==null?void 0:t.x)&&k(C.element.y)&&k(C.element.stepx)&&k(C.element.stepy)&&Gg(e,C.book,C.board,C.element,{x:C.element.x+C.element.stepx,y:C.element.y+C.element.stepy})===!1&&(C.element.stepx=0,C.element.stepy=0),(n=C.element)!=null&&n.headless&&e.command("die")}}).command("become",(e,t)=>{var i,s;const n={x:((i=C.element)==null?void 0:i.x)??0,y:((s=C.element)==null?void 0:s.y)??0},[r]=ne(t,0,[q.KIND]);return za(C.book,C.board),Qs(C.book,C.board,C.element),Lu(C.book,C.element,C.timestamp)&&Mu(C.book,C.board,r,n),e.endofprogram(),0}).command("bind",()=>0).command("char",(e,t)=>{const[n]=ne(t,0,[q.NUMBER]);return k(C.element)&&(C.element.char=n),0}).command("color",(e,t)=>{const[n]=ne(t,0,[q.COLOR]);return k(C.element)&&k(n)&&Va(C.element,n),0}).command("go",(e,t)=>{if(k(C.element)){const[n]=ne(t,0,[q.DIR]);if(Gg(e,C.book,C.board,C.element,n),e.yield(),C.element.x===n.x&&C.element.y===n.y)return 0}return 1}).command("try",(e,t)=>{const[,n]=ne(t,0,[q.DIR]);return e.command("go",...t)&&n{if(!k(C.element))return 0;const[n]=ne(t,0,[q.DIR]),r=C.element.x??0,i=C.element.y??0;return C.element.stepx=n.x-r,C.element.stepy=n.y-i,0}),XC=lr().command("clear",(e,t)=>(t.forEach(n=>e.set(Nt(n),0)),0)).command("set",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.ANY]);return e.set(n,r),0}).command("take",(e,t)=>{const[n,r,i]=ne(t,0,[q.STRING,q.MAYBE_NUMBER]),s=e.get(n),o=r??1;if(!ke(s))return 1;const a=s-o;return a<0?(i{const[n,r,i]=ne(t,0,[q.STRING,q.MAYBE_NUMBER]),s=e.get(n),o=ke(s)?s:0,a=r??1;if(!ke(a))return 0;const c=s===void 0?1:0;return c&&i0&&b<_.lastIndexOf(" ")?c.low.call(p):p})},sentence:function(h,p,m){return h=l.lower(h).replace(a.sentence,function(b,_,w){return _+c.up.call(w)}),p&&p.forEach(function(b){h=h.replace(new RegExp("\\b"+l.lower(b)+"\\b","g"),c.cap)}),m&&m.forEach(function(b){h=h.replace(new RegExp("(\\b"+l.lower(b)+"\\. +)(\\w)"),function(_,w,v){return w+c.low.call(v)})}),h}};u.squish=u.pascal,l.default=l;for(var f in u)l.type(f,u[f]);var d=typeof d=="function"?d:function(){};d(e.exports?e.exports=l:this.Case=l)}).call(Bt)})(s_);var ZC=s_.exports,YC=Pi(ZC);const ei={};function Bf(e){return{player:e,layers:[],panels:[],reset:!0,focus:"scroll"}}function o_(e){e.text=[],Object.values(ei[e.id]??{}).forEach(t=>t==null?void 0:t()),ei[e.id]={}}function a_(e){const t=e.panels.find(n=>n.name===e.focus);if(!t){const n={id:ht(),name:e.focus,edge:fn.RIGHT,size:20,text:[]};return e.panels.push(n),e.reset=!1,n}return t}const QC=new Set(["hk","hotkey","rn","range","sl","select","nm","number","tx","text"]),eL=new Set(["rn","range","sl","select","nm","number","tx","text"]),tL=new Set(["tx","text"]),nL={rn:1,range:1,sl:0,select:0,nm:0,number:0,tx:"",text:""},c_={};let l_=e=>{let t=c_[e];return k(t)||(c_[e]=t=Bf(e)),t};function rL(e){l_=e}function Ii(e){return l_(e)}function iL(e){const t=Ii(e);t.panels=t.panels.filter(n=>n.edge!==fn.SCROLL)}function sL(e,t,n){Object.values(ei).forEach(r=>{if(r[t]!==void 0){const i=hh(e.id(),t);ke(n)&&PC(i,n),Ce(n)&&DC(i,n)}})}function oL(e){let t="";const n=Ii(e);return n.panels=n.panels.filter(r=>{if(r.edge===fn.SCROLL){const[i]=r.text;return Ce(i)&&r.text.length===1&&(t=i),r.text.length>1}return!0}),t}function Ff(e,t,n,r,i){const s=Ii(e),o=r,a=i??YC.capital(t),c=s.panels.find(l=>l.name===a);if(c)s.reset=!0,s.focus=a,ke(o)&&(c.size=o);else switch(n){case fn.START:break;case fn.LEFT:case fn.RIGHT:case fn.TOP:case fn.BOTTOM:case fn.SCROLL:{const l={id:ht(),name:a,edge:n,size:o??Sb[n],text:[]};s.panels.push(l),s.focus=a;break}}}function aL(e,t){const n=Ii(e),r=a_(n);n.reset&&(n.reset=!1,o_(r)),r.text.push(t)}function cL(e,t,n,r,i){const s=Ii(e),o=a_(s);s.reset&&(s.reset=!1,o_(o));const a=Pe(r),c=[t.id(),n,...QC.has(a)?[a]:["hyperlink",r],...i],l=c[2];if(eL.has(l)){const u=`${c[3]??""}`;ei[o.id]=ei[o.id]??{};const f=t.get(u)??nL[l];if(ei[o.id][u]===void 0){const d=hh(t.id(),u);ke(f)&&UC(d,f),Ce(f)&&Yy(d,f),tL.has(l)?ei[o.id][u]=e_(d,h=>{k(h)&&h!==t.get(u)&&t.set(u,h)}):ei[o.id][u]=BC(d,h=>{k(h)&&h!==t.get(u)&&t.set(u,h)})}}o.text.push(c)}const lL=lr({get(){return[!1,void 0]},set(e,t,n){return sL(e,t,n),[!1,void 0]},tick(){var t;const e=((t=C.element)==null?void 0:t.name)??"scroll";Ff(C.player,"scroll",fn.SCROLL,void 0,e)},everytick(){const e=oL(C.player);if(e&&k(C.element)){C.element.tickertext=e,C.element.tickertime=C.timestamp;const t=Tg(C.book,C.element);yt(`$${be[t.color]}$${t.char}`,e)}}}).command("send",(e,t)=>{var u,f;const[n,r]=ne(t,0,[q.STRING,q.ANY]),[i,s]=n.split(":"),o=k(s)?i:"self",a=s??i;function c(d){d.forEach(h=>{k(h.id)&&e.send(h.id,a,r)})}const l=Pe(o);switch(l){case"all":for(const d of Object.keys(((u=C.board)==null?void 0:u.objects)??{}))e.send(d,a,r);break;case"self":e.message({id:ht(),sender:e.id(),target:a,data:r});break;case"others":for(const d of Object.keys(((f=C.board)==null?void 0:f.objects)??{}))d!==e.id()&&e.send(d,a,r);break;default:{c(tl(C.board,[o]));const d=e.get(l);Ge(d)?c(tl(C.board,d)):c(tl(C.board,[d]));break}}return 0}).command("stat",(e,t)=>{const n=Pm(t.map(Nt));switch(n.type){case fe.OBJECT:k(C.element)&&(C.element.name=n.values.join(" "));break}return 0}).command("text",(e,t)=>{const n=t.map(Nt).join("");return aL(C.player,n),0}).command("hyperlink",(e,t)=>{const[n,r,...i]=t,s=Nt(n),o=Nt(r);return cL(C.player,e,s,o,i),0}).command("gadget",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=kb[Pe(n)];if(r===fn.SCROLL){const[,i,s]=ne(t,0,[q.STRING,q.MAYBE_STRING,q.MAYBE_NUMBER]);Ff(C.player,n,r,s,i)}else{const[,i,s]=ne(t,0,[q.STRING,q.MAYBE_NUMBER,q.MAYBE_STRING]);Ff(C.player,n,r,i,s)}return 0}),uL=lr().command("idle",e=>(e.yield(),0)).command("end",e=>(e.endofprogram(),0)).command("endwith",(e,t)=>{const[n]=ne(t,0,[q.ANY]);return e.set("arg",n),e.command("end")}).command("lock",e=>(e.lock(e.id()),0)).command("restore",(e,t)=>(e.restore(Nt(t[0])),0)).command("unlock",e=>(e.unlock(),0)).command("zap",(e,t)=>(e.zap(Nt(t[0])),0)).command("cycle",(e,t)=>{if(k(C.element)){const[n]=ne(t,0,[q.NUMBER]);C.element.cycle=si(Math.round(n),1,255)}return 0}).command("die",e=>{var t;return(t=C.element)!=null&&t.headless&&Qs(C.book,C.board,C.element),Lu(C.book,C.element,C.timestamp),e.endofprogram(),0}).command("endgame",()=>($b("element",C.player),0)).command("run",(e,t)=>{const[n]=ne(t,0,[q.STRING]);return Bc(n),0}).command("runwith",(e,t)=>{const[n,r]=ne(t,0,[q.ANY,q.STRING]);return e.set("arg",n),Bc(r),0});function u_(e,t){if(!k(e))return;const n=Pe(t),r=n.endsWith("le");switch(n){case"float32":case"float32le":{const i=e.dataview.getFloat32(e.cursor,r);return e.cursor+=4,i}case"float64":case"float64le":{const i=e.dataview.getFloat64(e.cursor,r);return e.cursor+=8,i}case"int8":case"int8le":{const i=e.dataview.getInt8(e.cursor);return e.cursor+=1,i}case"int16":case"int16le":{const i=e.dataview.getInt16(e.cursor,r);return e.cursor+=2,i}case"int32":case"int32le":{const i=e.dataview.getInt32(e.cursor,r);return e.cursor+=4,i}case"int64":case"int64le":{const i=e.dataview.getBigInt64(e.cursor,r);return e.cursor+=8,i}case"uint8":case"uint8le":{const i=e.dataview.getUint8(e.cursor);return e.cursor+=1,i}case"uint16":case"uint16le":{const i=e.dataview.getUint16(e.cursor,r);return e.cursor+=2,i}case"uint32":case"uint32le":{const i=e.dataview.getUint32(e.cursor,r);return e.cursor+=4,i}case"uint64":case"uint64le":{const i=e.dataview.getBigUint64(e.cursor,r);return e.cursor+=8,i}}}const fL=(e,t)=>{const n=H_(e.id());if(!k(n))return 0;const[r]=ne(t,0,[q.STRING]),i=Pe(r);switch(i){case"seek":{const[s]=ne(t,1,[q.NUMBER]);n.cursor=s;break}case"float32":case"float32le":case"float64":case"float64le":case"int8":case"int8le":case"int16":case"int16le":case"int32":case"int32le":case"int64":case"int64le":case"uint8":case"uint8le":case"uint16":case"uint16le":case"uint32":case"uint32le":case"uint64":case"uint64le":{const[s]=ne(t,1,[q.STRING]);e.set(s,u_(n,i));break}case"text":{const[s,o]=ne(t,1,[q.STRING,q.STRING]),a=u_(n,s);if(ke(a)&&Ce(o)){const c=new Uint8Array(n.bytes.buffer,n.cursor,a),u=new TextDecoder("utf-8").decode(c);e.set(o,u),n.cursor+=a}break}}return 0},hL=lr({get(e,t){const n=H_(e.id());if(k(n))switch(Pe(t)){case"filename":return[k(n.filename),n.filename];case"cursor":return[k(n.cursor),n.cursor]}return[!1,void 0]}}).command("send",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.ANY]);return e.message({id:ht(),sender:e.id(),target:n,data:r}),0}).command("stat",()=>0).command("text",(e,t)=>{const n=t.map(Nt).join(" ");return yt("$2",n),0}).command("hyperlink",(e,t)=>{const[n,...r]=t,i=Nt(n),s=r.map(Nt).join(" ");return yt("$2",`!${s};${i}`),0}).command("load",(e,t)=>{const n=t.map(Nt).join(" "),r=e.get(n)??n;return Bn(Xe.CONTENT,r),0}).command("reload",(e,t)=>{const n=t.map(Nt).join(" "),r=e.get(n)??n,i=Bn(Xe.CONTENT,r);return i.pages=[],0}).command("bin",fL);var ko=(e=>(e[e.ERROR=0]="ERROR",e[e.CLI=1]="CLI",e[e.LOADER=2]="LOADER",e[e.CODE_PAGE=3]="CODE_PAGE",e))(ko||{});const dL={audio:_I,board:wI,cli:WC,const:HC,element:JC,flags:XC,gadget:lL,lifecycle:uL,loader:hL},$f=["const","flags","audio","board","lifecycle","element"],pL={0:[],1:["cli",...$f],2:["loader",...$f],3:["gadget",...$f]},mL={0:new Map,1:new Map,2:new Map,3:new Map};function So(e){return(pL[e]??[]).map(n=>dL[n]).filter(k)}function gL(e,t){const n=mL[e];if(!n.has(t)){let r;const i=So(e);for(let s=0;s>>=g_,i>0&&(r|=EL),n+=wL.encode(r);while(i>0);return n};var Ao={};(function(e){function t(I,T,M){if(T in I)return I[T];if(arguments.length===3)return M;throw new Error('"'+T+'" is a required argument.')}e.getArg=t;const n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(I){const T=I.match(n);return T?{scheme:T[1],auth:T[2],host:T[3],port:T[4],path:T[5]}:null}e.urlParse=i;function s(I){let T="";return I.scheme&&(T+=I.scheme+":"),T+="//",I.auth&&(T+=I.auth+"@"),I.host&&(T+=I.host),I.port&&(T+=":"+I.port),I.path&&(T+=I.path),T}e.urlGenerate=s;const o=32;function a(I){const T=[];return function(M){for(let V=0;Vo&&T.pop(),x}}const c=a(function(T){let M=T;const x=i(T);if(x){if(!x.path)return T;M=x.path}const V=e.isAbsolute(M),oe=[];let O=0,E=0;for(;;)if(O=E,E=M.indexOf("/",O),E===-1){oe.push(M.slice(O));break}else for(oe.push(M.slice(O,E));E=0;E--){const N=oe[E];N==="."?oe.splice(E,1):N===".."?g++:g>0&&(N===""?(oe.splice(E+1,g),g=0):(oe.splice(E,2),g--))}return M=oe.join("/"),M===""&&(M=V?"/":"."),x?(x.path=M,s(x)):M});e.normalize=c;function l(I,T){I===""&&(I="."),T===""&&(T=".");const M=i(T),x=i(I);if(x&&(I=x.path||"/"),M&&!M.scheme)return x&&(M.scheme=x.scheme),s(M);if(M||T.match(r))return T;if(x&&!x.host&&!x.path)return x.host=T,s(x);const V=T.charAt(0)==="/"?T:c(I.replace(/\/+$/,"")+"/"+T);return x?(x.path=V,s(x)):V}e.join=l,e.isAbsolute=function(I){return I.charAt(0)==="/"||n.test(I)};function u(I,T){I===""&&(I="."),I=I.replace(/\/$/,"");let M=0;for(;T.indexOf(I+"/")!==0;){const x=I.lastIndexOf("/");if(x<0||(I=I.slice(0,x),I.match(/^([^\/]+:\/)?\/*$/)))return T;++M}return Array(M+1).join("../")+T.substr(I.length+1)}e.relative=u;const f=function(){return!("__proto__"in Object.create(null))}();function d(I){return I}function h(I){return m(I)?"$"+I:I}e.toSetString=f?d:h;function p(I){return m(I)?I.slice(1):I}e.fromSetString=f?d:p;function m(I){if(!I)return!1;const T=I.length;if(T<9||I.charCodeAt(T-1)!==95||I.charCodeAt(T-2)!==95||I.charCodeAt(T-3)!==111||I.charCodeAt(T-4)!==116||I.charCodeAt(T-5)!==111||I.charCodeAt(T-6)!==114||I.charCodeAt(T-7)!==112||I.charCodeAt(T-8)!==95||I.charCodeAt(T-9)!==95)return!1;for(let M=T-10;M>=0;M--)if(I.charCodeAt(M)!==36)return!1;return!0}function b(I,T,M){let x=w(I.source,T.source);return x!==0||(x=I.originalLine-T.originalLine,x!==0)||(x=I.originalColumn-T.originalColumn,x!==0||M)||(x=I.generatedColumn-T.generatedColumn,x!==0)||(x=I.generatedLine-T.generatedLine,x!==0)?x:w(I.name,T.name)}e.compareByOriginalPositions=b;function _(I,T,M){let x=I.generatedLine-T.generatedLine;return x!==0||(x=I.generatedColumn-T.generatedColumn,x!==0||M)||(x=w(I.source,T.source),x!==0)||(x=I.originalLine-T.originalLine,x!==0)||(x=I.originalColumn-T.originalColumn,x!==0)?x:w(I.name,T.name)}e.compareByGeneratedPositionsDeflated=_;function w(I,T){return I===T?0:I===null?1:T===null?-1:I>T?1:-1}function v(I,T){let M=I.generatedLine-T.generatedLine;return M!==0||(M=I.generatedColumn-T.generatedColumn,M!==0)||(M=w(I.source,T.source),M!==0)||(M=I.originalLine-T.originalLine,M!==0)||(M=I.originalColumn-T.originalColumn,M!==0)?M:w(I.name,T.name)}e.compareByGeneratedPositionsInflated=v;function S(I){return JSON.parse(I.replace(/^\)]}'[^\n]*\n/,""))}e.parseSourceMapInput=S;function L(I,T,M){if(T=T||"",I&&(I[I.length-1]!=="/"&&T[0]!=="/"&&(I+="/"),T=I+T),M){const x=i(M);if(!x)throw new Error("sourceMapURL could not be parsed");if(x.path){const V=x.path.lastIndexOf("/");V>=0&&(x.path=x.path.substring(0,V+1))}T=l(s(x),T)}return c(T)}e.computeSourceURL=L})(Ao);var jf={};let SL=class Q_{constructor(){this._array=[],this._set=new Map}static fromArray(t,n){const r=new Q_;for(let i=0,s=t.length;i=0)return n;throw new Error('"'+t+'" is not in the set.')}at(t){if(t>=0&&tn||r==n&&s>=i||b_.compareByGeneratedPositionsInflated(e,t)<=0}let TL=class{constructor(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}unsortedForEach(t,n){this._array.forEach(t,n)}add(t){AL(this._last,t)?(this._last=t,this._array.push(t)):(this._sorted=!1,this._array.push(t))}toArray(){return this._sorted||(this._array.sort(b_.compareByGeneratedPositionsInflated),this._sorted=!0),this._array}};__.MappingList=TL;const To=d_,pt=Ao,xc=jf.ArraySet,xL=__.MappingList;let w_=class eb{constructor(t){t||(t={}),this._file=pt.getArg(t,"file",null),this._sourceRoot=pt.getArg(t,"sourceRoot",null),this._skipValidation=pt.getArg(t,"skipValidation",!1),this._sources=new xc,this._names=new xc,this._mappings=new xL,this._sourcesContents=null}static fromSourceMap(t){const n=t.sourceRoot,r=new eb({file:t.file,sourceRoot:n});return t.eachMapping(function(i){const s={generated:{line:i.generatedLine,column:i.generatedColumn}};i.source!=null&&(s.source=i.source,n!=null&&(s.source=pt.relative(n,s.source)),s.original={line:i.originalLine,column:i.originalColumn},i.name!=null&&(s.name=i.name)),r.addMapping(s)}),t.sources.forEach(function(i){let s=i;n!==null&&(s=pt.relative(n,i)),r._sources.has(s)||r._sources.add(s);const o=t.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r}addMapping(t){const n=pt.getArg(t,"generated"),r=pt.getArg(t,"original",null);let i=pt.getArg(t,"source",null),s=pt.getArg(t,"name",null);this._skipValidation||this._validateMapping(n,r,i,s),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:s})}setSourceContent(t,n){let r=t;this._sourceRoot!=null&&(r=pt.relative(this._sourceRoot,r)),n!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[pt.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[pt.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))}applySourceMap(t,n,r){let i=n;if(n==null){if(t.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=t.file}const s=this._sourceRoot;s!=null&&(i=pt.relative(s,i));const o=this._mappings.toArray().length>0?new xc:this._sources,a=new xc;this._mappings.unsortedForEach(function(c){if(c.source===i&&c.originalLine!=null){const f=t.originalPositionFor({line:c.originalLine,column:c.originalColumn});f.source!=null&&(c.source=f.source,r!=null&&(c.source=pt.join(r,c.source)),s!=null&&(c.source=pt.relative(s,c.source)),c.originalLine=f.line,c.originalColumn=f.column,f.name!=null&&(c.name=f.name))}const l=c.source;l!=null&&!o.has(l)&&o.add(l);const u=c.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=o,this._names=a,t.sources.forEach(function(c){const l=t.sourceContentFor(c);l!=null&&(r!=null&&(c=pt.join(r,c)),s!=null&&(c=pt.relative(s,c)),this.setSourceContent(c,l))},this)}_validateMapping(t,n,r,i){if(n&&typeof n.line!="number"&&typeof n.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(t&&"line"in t&&"column"in t&&t.line>0&&t.column>=0&&!n&&!r&&!i)){if(!(t&&"line"in t&&"column"in t&&n&&"line"in n&&"column"in n&&t.line>0&&t.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:t,source:r,original:n,name:i}))}}_serializeMappings(){let t=0,n=1,r=0,i=0,s=0,o=0,a="",c,l,u,f;const d=this._mappings.toArray();for(let h=0,p=d.length;h0){if(!pt.compareByGeneratedPositionsInflated(l,d[h-1]))continue;c+=","}c+=To.encode(l.generatedColumn-t),t=l.generatedColumn,l.source!=null&&(f=this._sources.indexOf(l.source),c+=To.encode(f-o),o=f,c+=To.encode(l.originalLine-1-i),i=l.originalLine-1,c+=To.encode(l.originalColumn-r),r=l.originalColumn,l.name!=null&&(u=this._names.indexOf(l.name),c+=To.encode(u-s),s=u)),a+=c}return a}_generateSourcesContent(t,n){return t.map(function(r){if(!this._sourcesContents)return null;n!=null&&(r=pt.relative(n,r));const i=pt.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)}toJSON(){const t={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(t.file=this._file),this._sourceRoot!=null&&(t.sourceRoot=this._sourceRoot),this._sourcesContents&&(t.sourcesContent=this._generateSourcesContent(t.sources,t.sourceRoot)),t}toString(){return JSON.stringify(this.toJSON())}};w_.prototype._version=3,h_.SourceMapGenerator=w_;var v_={};(function(e){e.GREATEST_LOWER_BOUND=1,e.LEAST_UPPER_BOUND=2;function t(n,r,i,s,o,a){const c=Math.floor((r-n)/2)+n,l=o(i,s[c],!0);return l===0?c:l>0?r-c>1?t(c,r,i,s,o,a):a==e.LEAST_UPPER_BOUND?r1?t(n,c,i,s,o,a):a==e.LEAST_UPPER_BOUND?c:n<0?-1:n}e.search=function(r,i,s,o){if(i.length===0)return-1;let a=t(-1,i.length,r,i,s,o||e.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&s(i[a],i[a-1],!0)===0;)--a;return a}})(v_);var xo={exports:{}},RL={},IL=Object.freeze({__proto__:null,default:RL}),E_=tb(IL);if((function(){return typeof window<"u"&&this===window}).call()){let e=null;xo.exports=function(){if(typeof e=="string")return fetch(e).then(n=>n.arrayBuffer());if(e instanceof ArrayBuffer)return Promise.resolve(e);throw new Error("You must provide the string URL or ArrayBuffer contents of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer")},xo.exports.initialize=t=>e=t}else{const e=E_,t=E_;xo.exports=function(){return new Promise((r,i)=>{const s=t.join(__dirname,"mappings.wasm");e.readFile(s,null,(o,a)=>{if(o){i(o);return}r(a.buffer)})})},xo.exports.initialize=n=>{console.debug("SourceMapConsumer.initialize is a no-op when running in node.js")}}var k_=xo.exports;const OL=k_;function NL(){this.generatedLine=0,this.generatedColumn=0,this.lastGeneratedColumn=null,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}let Ro=null;var CL=function(){if(Ro)return Ro;const t=[];return Ro=OL().then(n=>WebAssembly.instantiate(n,{env:{mapping_callback(r,i,s,o,a,c,l,u,f,d){const h=new NL;h.generatedLine=r+1,h.generatedColumn=i,s&&(h.lastGeneratedColumn=o-1),a&&(h.source=c,h.originalLine=l+1,h.originalColumn=u,f&&(h.name=d)),t[t.length-1](h)},start_all_generated_locations_for(){console.time("all_generated_locations_for")},end_all_generated_locations_for(){console.timeEnd("all_generated_locations_for")},start_compute_column_spans(){console.time("compute_column_spans")},end_compute_column_spans(){console.timeEnd("compute_column_spans")},start_generated_location_for(){console.time("generated_location_for")},end_generated_location_for(){console.timeEnd("generated_location_for")},start_original_location_for(){console.time("original_location_for")},end_original_location_for(){console.timeEnd("original_location_for")},start_parse_mappings(){console.time("parse_mappings")},end_parse_mappings(){console.timeEnd("parse_mappings")},start_sort_by_generated_location(){console.time("sort_by_generated_location")},end_sort_by_generated_location(){console.timeEnd("sort_by_generated_location")},start_sort_by_original_location(){console.time("sort_by_original_location")},end_sort_by_original_location(){console.timeEnd("sort_by_original_location")}}})).then(n=>({exports:n.instance.exports,withMappingCallback:(r,i)=>{t.push(r);try{i()}finally{t.pop()}}})).then(null,n=>{throw Ro=null,n}),Ro};const he=Ao,zf=v_,Rc=jf.ArraySet,LL=k_,ML=CL,Wf=Symbol("smcInternal");class ut{constructor(t,n){return t==Wf?Promise.resolve(this):PL(t,n)}static initialize(t){LL.initialize(t["lib/mappings.wasm"])}static fromSourceMap(t,n){return DL(t,n)}static async with(t,n,r){const i=await new ut(t,n);try{return await r(i)}finally{i.destroy()}}_parseMappings(t,n){throw new Error("Subclasses must implement _parseMappings")}eachMapping(t,n,r){throw new Error("Subclasses must implement eachMapping")}allGeneratedPositionsFor(t){throw new Error("Subclasses must implement allGeneratedPositionsFor")}destroy(){throw new Error("Subclasses must implement destroy")}}ut.prototype._version=3,ut.GENERATED_ORDER=1,ut.ORIGINAL_ORDER=2,ut.GREATEST_LOWER_BOUND=1,ut.LEAST_UPPER_BOUND=2;class Io extends ut{constructor(t,n){return super(Wf).then(r=>{let i=t;typeof t=="string"&&(i=he.parseSourceMapInput(t));const s=he.getArg(i,"version");let o=he.getArg(i,"sources");const a=he.getArg(i,"names",[]);let c=he.getArg(i,"sourceRoot",null);const l=he.getArg(i,"sourcesContent",null),u=he.getArg(i,"mappings"),f=he.getArg(i,"file",null);if(s!=r._version)throw new Error("Unsupported version: "+s);return c&&(c=he.normalize(c)),o=o.map(String).map(he.normalize).map(function(d){return c&&he.isAbsolute(c)&&he.isAbsolute(d)?he.relative(c,d):d}),r._names=Rc.fromArray(a.map(String),!0),r._sources=Rc.fromArray(o,!0),r._absoluteSources=r._sources.toArray().map(function(d){return he.computeSourceURL(c,d,n)}),r.sourceRoot=c,r.sourcesContent=l,r._mappings=u,r._sourceMapURL=n,r.file=f,r._computedColumnSpans=!1,r._mappingsPtr=0,r._wasm=null,ML().then(d=>(r._wasm=d,r))})}_findSourceIndex(t){let n=t;if(this.sourceRoot!=null&&(n=he.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);for(let r=0;r{a.source!==null&&(a.source=this._sources.at(a.source),a.source=he.computeSourceURL(o,a.source,this._sourceMapURL),a.name!==null&&(a.name=this._names.at(a.name))),t.call(i,a)},()=>{switch(s){case ut.GENERATED_ORDER:this._wasm.exports.by_generated_location(this._getMappingsPtr());break;case ut.ORIGINAL_ORDER:this._wasm.exports.by_original_location(this._getMappingsPtr());break;default:throw new Error("Unknown order of iteration.")}})}allGeneratedPositionsFor(t){let n=he.getArg(t,"source");const r=he.getArg(t,"line"),i=t.column||0;if(n=this._findSourceIndex(n),n<0)return[];if(r<1)throw new Error("Line numbers must be >= 1");if(i<0)throw new Error("Column numbers must be >= 0");const s=[];return this._wasm.withMappingCallback(o=>{let a=o.lastGeneratedColumn;this._computedColumnSpans&&a===null&&(a=1/0),s.push({line:o.generatedLine,column:o.generatedColumn,lastColumn:a})},()=>{this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(),n,r-1,"column"in t,i)}),s}destroy(){this._mappingsPtr!==0&&(this._wasm.exports.free_mappings(this._mappingsPtr),this._mappingsPtr=0)}computeColumnSpans(){this._computedColumnSpans||(this._wasm.exports.compute_column_spans(this._getMappingsPtr()),this._computedColumnSpans=!0)}originalPositionFor(t){const n={generatedLine:he.getArg(t,"line"),generatedColumn:he.getArg(t,"column")};if(n.generatedLine<1)throw new Error("Line numbers must be >= 1");if(n.generatedColumn<0)throw new Error("Column numbers must be >= 0");let r=he.getArg(t,"bias",ut.GREATEST_LOWER_BOUND);r==null&&(r=ut.GREATEST_LOWER_BOUND);let i;if(this._wasm.withMappingCallback(s=>i=s,()=>{this._wasm.exports.original_location_for(this._getMappingsPtr(),n.generatedLine-1,n.generatedColumn,r)}),i&&i.generatedLine===n.generatedLine){let s=he.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=he.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));let o=he.getArg(i,"name",null);return o!==null&&(o=this._names.at(o)),{source:s,line:he.getArg(i,"originalLine",null),column:he.getArg(i,"originalColumn",null),name:o}}return{source:null,line:null,column:null,name:null}}hasContentsOfAllSources(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(t){return t==null}):!1}sourceContentFor(t,n){if(!this.sourcesContent)return null;const r=this._findSourceIndex(t);if(r>=0)return this.sourcesContent[r];let i=t;this.sourceRoot!=null&&(i=he.relative(this.sourceRoot,i));let s;if(this.sourceRoot!=null&&(s=he.urlParse(this.sourceRoot))){const o=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(n)return null;throw new Error('"'+i+'" is not in the SourceMap.')}generatedPositionFor(t){let n=he.getArg(t,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};const r={source:n,originalLine:he.getArg(t,"line"),originalColumn:he.getArg(t,"column")};if(r.originalLine<1)throw new Error("Line numbers must be >= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");let i=he.getArg(t,"bias",ut.GREATEST_LOWER_BOUND);i==null&&(i=ut.GREATEST_LOWER_BOUND);let s;if(this._wasm.withMappingCallback(o=>s=o,()=>{this._wasm.exports.generated_location_for(this._getMappingsPtr(),r.source,r.originalLine-1,r.originalColumn,i)}),s&&s.source===r.source){let o=s.lastGeneratedColumn;return this._computedColumnSpans&&o===null&&(o=1/0),{line:he.getArg(s,"generatedLine",null),column:he.getArg(s,"generatedColumn",null),lastColumn:o}}return{line:null,column:null,lastColumn:null}}}Io.prototype.consumer=ut;class UL extends ut{constructor(t,n){return super(Wf).then(r=>{let i=t;typeof t=="string"&&(i=he.parseSourceMapInput(t));const s=he.getArg(i,"version"),o=he.getArg(i,"sections");if(s!=r._version)throw new Error("Unsupported version: "+s);r._sources=new Rc,r._names=new Rc,r.__generatedMappings=null,r.__originalMappings=null,r.__generatedMappingsUnsorted=null,r.__originalMappingsUnsorted=null;let a={line:-1,column:0};return Promise.all(o.map(c=>{if(c.url)throw new Error("Support for url field in sections not implemented.");const l=he.getArg(c,"offset"),u=he.getArg(l,"line"),f=he.getArg(l,"column");if(u({generatedOffset:{generatedLine:u+1,generatedColumn:f+1},consumer:h}))})).then(c=>(r._sections=c,r))})}get _generatedMappings(){return this.__generatedMappings||this._sortGeneratedMappings(),this.__generatedMappings}get _originalMappings(){return this.__originalMappings||this._sortOriginalMappings(),this.__originalMappings}get _generatedMappingsUnsorted(){return this.__generatedMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappingsUnsorted}get _originalMappingsUnsorted(){return this.__originalMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappingsUnsorted}_sortGeneratedMappings(){const t=this._generatedMappingsUnsorted;t.sort(he.compareByGeneratedPositionsDeflated),this.__generatedMappings=t}_sortOriginalMappings(){const t=this._originalMappingsUnsorted;t.sort(he.compareByOriginalPositions),this.__originalMappings=t}get sources(){const t=[];for(let n=0;na.push(c));for(let c=0;c= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");const i=[];let s=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",he.compareByOriginalPositions,zf.LEAST_UPPER_BOUND);if(s>=0){let o=this._originalMappings[s];if(t.column===void 0){const a=o.originalLine;for(;o&&o.originalLine===a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:he.getArg(o,"generatedLine",null),column:he.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}else{const a=o.originalColumn;for(;o&&o.originalLine===n&&o.originalColumn==a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:he.getArg(o,"generatedLine",null),column:he.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}}return i}destroy(){for(let t=0;t=0;n--)this.prepend(t[n]);else if(t[fs]||typeof t=="string")this.children.unshift(t);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+t);return this}walk(t){let n;for(let r=0,i=this.children.length;r0){for(n=[],r=0;rString.fromCharCode(e)),GL=on({name:"Whitespace",pattern:/ +/}),HL=on({name:"WhitespaceSkipped",pattern:/ +/,group:wt.SKIPPED}),Gf=on({name:"Newline",line_breaks:!0,start_chars_hint:[` -`,"\r"],pattern:/\n|\r\n?/}),A_=on({name:"StringLiteral",pattern:/[^ $;\r\n]+/,start_chars_hint:WL}),Hf=on({name:"StringLiteralDouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),Vf=on({name:"EscapedDollar",pattern:"$$"}),Kf=on({name:"MaybeFlag",pattern:/\$[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/}),qf=on({name:"NumberLiteral",pattern:/\$-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?\+?/}),T_=on({name:"HyperLinkText",pattern:/;[^;\r\n]*/,start_chars_hint:[";"]});function VL(e,t=""){return on({name:t||e,pattern:new RegExp(e.toLowerCase(),"i")})}const x_=Object.keys(Ga).map(e=>VL(`\\$(${e})`,e)),KL=[GL,Gf,...x_,Hf,A_,qf,Vf,T_,Kf],qL=new wt(KL,{skipValidations:!qn,ensureOptimizations:qn}),JL=new wt([HL,Gf,...x_,Hf,A_,qf,Vf,T_,Kf],{skipValidations:!qn,ensureOptimizations:qn});function Jf(e,t=!1){return t?JL.tokenize(e):qL.tokenize(e)}function R_(e,t,n,r,i,s,o,a){return{disablewrap:!1,measureonly:!1,measuredwidth:0,writefullwidth:void 0,x:0,y:0,iseven:!0,active:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},reset:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},width:e,height:t,char:[],color:[],bg:[],changed(){}}}function I_(e){e.active={...e.reset}}function O_(e,t){const n=t.y;function r(){++t.x;const a=t.active.rightedge??t.width-1;!t.disablewrap&&t.x>a&&(t.x=t.active.leftedge??0,++t.y),t.x>t.measuredwidth&&(t.measuredwidth=t.x)}function i(){return t.x>=(t.active.leftedge??0)&&t.x<=(t.active.rightedge??t.width-1)&&t.y>=(t.active.topedge??0)&&t.y<=(t.active.bottomedge??t.height-1)}function s(a){for(let c=0;ct.measuredwidth&&(t.measuredwidth=t.x+1);const o=t.active.leftedge??0;if(k(t.writefullwidth)&&(t.x>o||t.y===n)){const c=(t.active.rightedge??t.width-1)-t.x;if(c>0){I_(t);const l=String.fromCharCode(t.writefullwidth).repeat(c),u=t.x+t.y*t.width;QL(u,u+l.length,t.active.color,t.active.bg,t),YL(u,l,t)}}}function XL(e,t,n){const r=Jf(e);r.tokens&&(O_(r.tokens,t),I_(t))}function ZL(e,t,n){const r=Jf(e);if(!r.tokens)return;const i=R_(t,n,be.WHITE,be.BLACK);return i.measureonly=!0,O_(r.tokens,i),i.x>0&&++i.y,i}function YL(e,t,n){let r=0;const i=e+t.length;for(let s=e;s{this.MANY(()=>this.SUBRULE(this.line))}));ye(this,"line",this.RULED("line",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt)},{ALT:()=>this.CONSUME($s)}])}));ye(this,"stmt",this.RULED("stmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.short_commands)),this.MANY(()=>this.SUBRULE(this.commands))}}])}));ye(this,"inline",this.RULED("inline",()=>{this.SUBRULE(this.instmt)}));ye(this,"instmt",this.RULED("instmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}])}));ye(this,"stmt_label",this.RULED("stmt_label",()=>{this.CONSUME(am)}));ye(this,"stmt_stat",this.RULED("stmt_stat",()=>{this.CONSUME(Zl)}));ye(this,"stmt_text",this.RULED("stmt_text",()=>{this.OR([{ALT:()=>this.CONSUME(sm)}])}));ye(this,"stmt_comment",this.RULED("stmt_comment",()=>{this.CONSUME(om)}));ye(this,"stmt_hyperlink",this.RULED("stmt_hyperlink",()=>{this.CONSUME(cm),this.SUBRULE(this.words),this.CONSUME(lm)}));ye(this,"stmt_command",this.RULED("stmt_command",()=>{this.CONSUME(Ki),this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}));ye(this,"short_commands",this.RULED("short_commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)}])}));ye(this,"commands",this.RULED("commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.words)},{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)},{ALT:()=>this.SUBRULE(this.command_play)},{ALT:()=>this.SUBRULE(this.structured_cmd)}])}));ye(this,"structured_cmd",this.RULED("structured_cmd",()=>{this.OR([{ALT:()=>this.SUBRULE(this.command_debugger)},{ALT:()=>this.SUBRULE(this.command_if)},{ALT:()=>this.SUBRULE(this.command_while)},{ALT:()=>this.SUBRULE(this.command_repeat)},{ALT:()=>this.SUBRULE(this.command_waitfor)},{ALT:()=>this.SUBRULE(this.command_foreach)},{ALT:()=>this.SUBRULE(this.command_break)},{ALT:()=>this.SUBRULE(this.command_continue)}])}));ye(this,"short_go",this.RULED("short_go",()=>{this.CONSUME(ru),this.SUBRULE(this.words)}));ye(this,"short_try",this.RULED("short_try",()=>{this.CONSUME(Em),this.SUBRULE(this.words)}));ye(this,"command_debugger",this.RULED("command_debugger",()=>{this.CONSUME(Tm)}));ye(this,"command_if",this.RULED("command_if",()=>{this.CONSUME(iu),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_if_block))}));ye(this,"command_if_block",this.RULED("command_if_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(Oa),this.MANY(()=>this.SUBRULE(this.line)),this.MANY2({GATE:this.BACKTRACK(this.command_else_if),DEF:()=>this.SUBRULE(this.command_else_if)}),this.OPTION(()=>this.SUBRULE(this.command_else)),this.MANY3(()=>this.CONSUME3($s)),this.CONSUME4(Ki),this.CONSUME4(su)}}])}));ye(this,"command_block",this.RULED("command_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(Oa),this.MANY(()=>this.SUBRULE(this.line)),this.CONSUME(Ki),this.CONSUME(su)}}])}));ye(this,"command_fork",this.RULED("command_fork",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(Oa),this.MANY({GATE:this.BACKTRACK(this.line),DEF:()=>this.SUBRULE(this.line)})}}])}));ye(this,"command_else_if",this.RULED("command_else_if",()=>{this.CONSUME(Ki),this.CONSUME(ou),this.CONSUME(iu),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_fork))}));ye(this,"command_else",this.RULED("command_else",()=>{this.CONSUME(Ki),this.CONSUME(ou),this.OPTION(()=>this.SUBRULE(this.command_fork))}));ye(this,"command_while",this.RULED("command_while",()=>{this.CONSUME(xm),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_repeat",this.RULED("command_repeat",()=>{this.CONSUME(Rm),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_waitfor",this.RULED("command_waitfor",()=>{this.CONSUME(Im),this.SUBRULE(this.words)}));ye(this,"command_foreach",this.RULED("command_foreach",()=>{this.CONSUME(Om),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_break",this.RULED("command_break",()=>{this.CONSUME(Nm)}));ye(this,"command_continue",this.RULED("command_continue",()=>{this.CONSUME(Cm)}));ye(this,"command_play",this.RULED("command_play",()=>{this.CONSUME(Am)}));ye(this,"expr",this.RULED("expr",()=>{this.SUBRULE1(this.and_test),this.MANY(()=>{this.CONSUME(Yl),this.SUBRULE2(this.and_test)})}));ye(this,"and_test",this.RULED("and_test",()=>{this.SUBRULE1(this.not_test),this.MANY(()=>{this.CONSUME(eu),this.SUBRULE2(this.not_test)})}));ye(this,"not_test",this.RULED("not_test",()=>{this.OR([{ALT:()=>{this.CONSUME(Ql),this.SUBRULE1(this.not_test)}},{ALT:()=>this.SUBRULE2(this.comparison)}])}));ye(this,"comparison",this.RULED("comparison",()=>{this.SUBRULE1(this.arith_expr),this.MANY(()=>{this.SUBRULE(this.comp_op),this.SUBRULE2(this.arith_expr)})}));ye(this,"comp_op",this.RULED("comp_op",()=>{this.OR([{ALT:()=>this.CONSUME(hm)},{ALT:()=>this.CONSUME(dm)},{ALT:()=>this.CONSUME(pm)},{ALT:()=>this.CONSUME(mm)},{ALT:()=>this.CONSUME(gm)},{ALT:()=>this.CONSUME(ym)}])}));ye(this,"expr_value",this.RULED("expr_value",()=>{this.SUBRULE1(this.and_test_value),this.MANY(()=>{this.CONSUME(Yl),this.SUBRULE2(this.and_test_value)})}));ye(this,"and_test_value",this.RULED("and_test_value",()=>{this.SUBRULE1(this.not_test_value),this.MANY(()=>{this.CONSUME(eu),this.SUBRULE2(this.not_test_value)})}));ye(this,"not_test_value",this.RULED("not_test_value",()=>{this.OR([{ALT:()=>{this.CONSUME(Ql),this.SUBRULE1(this.not_test_value)}},{ALT:()=>this.SUBRULE2(this.arith_expr)}])}));ye(this,"arith_expr",this.RULED("arith_expr",()=>{this.SUBRULE1(this.term),this.MANY(()=>this.SUBRULE2(this.arith_expr_item))}));ye(this,"arith_expr_item",this.RULED("arith_expr_item",()=>{this.OR([{ALT:()=>this.CONSUME(tu)},{ALT:()=>this.CONSUME(nu)}]),this.SUBRULE(this.term)}));ye(this,"term",this.RULED("term",()=>{this.SUBRULE1(this.factor),this.MANY(()=>this.SUBRULE2(this.term_item))}));ye(this,"term_item",this.RULED("term_item",()=>{this.OR([{ALT:()=>this.CONSUME(bm)},{ALT:()=>this.CONSUME(ru)},{ALT:()=>this.CONSUME(wm)},{ALT:()=>this.CONSUME(vm)}]),this.SUBRULE(this.factor)}));ye(this,"factor",this.RULED("factor",()=>{this.OR1([{ALT:()=>{this.OR2([{ALT:()=>this.CONSUME(tu)},{ALT:()=>this.CONSUME(nu)}]),this.SUBRULE(this.factor)}},{ALT:()=>this.SUBRULE(this.power)}])}));ye(this,"power",this.RULED("power",()=>{this.SUBRULE(this.token),this.OPTION(()=>{this.CONSUME(_m),this.SUBRULE(this.factor)})}));ye(this,"words",this.RULED("words",()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.expr))}));ye(this,"token",this.RULED("token",()=>{this.OR([{ALT:()=>this.CONSUME(um)},{ALT:()=>this.CONSUME(zt)},{ALT:()=>this.CONSUME(fm)},{ALT:()=>{this.CONSUME(km),this.SUBRULE(this.expr),this.CONSUME(Sm)}}])}));this.performSelfAnalysis()}PEEK(n,r,...i){console.info(n,i.map(s=>[s.image,s.tokenType]),r)}RULED(n,r,i){const s=eM.some(o=>n.includes(o));return this.RULE(n,()=>{const a=(N_++).toString().padStart(3),c=s?"font-weight: bold;":"";if(C_&&!this.RECORDING_PHASE){const l=[this.LA(1),this.LA(2),this.LA(3)].map(u=>`[${u.tokenType.name} ${u.image.replaceAll(` -`,"\\n")}]`);console.info(`${a}%c> ${n} ${l.join(" ")}`,c)}r(),C_&&!this.RECORDING_PHASE&&console.info(`${a}%c< ${n} `,c),N_--},i)}}const hs=new tM;if(Gx){const e=hs.getGAstProductions(),t=Wx(e);console.info(t)}const nM=hs.getBaseCstVisitorConstructor();var se=(e=>(e[e.PROGRAM=0]="PROGRAM",e[e.API=1]="API",e[e.LINE=2]="LINE",e[e.MARK=3]="MARK",e[e.GOTO=4]="GOTO",e[e.COUNT=5]="COUNT",e[e.TEXT=6]="TEXT",e[e.LABEL=7]="LABEL",e[e.HYPERLINK=8]="HYPERLINK",e[e.STAT=9]="STAT",e[e.MOVE=10]="MOVE",e[e.COMMAND=11]="COMMAND",e[e.LITERAL=12]="LITERAL",e[e.IF=13]="IF",e[e.IF_CHECK=14]="IF_CHECK",e[e.IF_BLOCK=15]="IF_BLOCK",e[e.ELSE_IF=16]="ELSE_IF",e[e.ELSE=17]="ELSE",e[e.WHILE=18]="WHILE",e[e.BREAK=19]="BREAK",e[e.CONTINUE=20]="CONTINUE",e[e.REPEAT=21]="REPEAT",e[e.WAITFOR=22]="WAITFOR",e[e.FOREACH=23]="FOREACH",e[e.OR=24]="OR",e[e.AND=25]="AND",e[e.NOT=26]="NOT",e[e.COMPARE=27]="COMPARE",e[e.COMPARE_ITEM=28]="COMPARE_ITEM",e[e.OPERATOR=29]="OPERATOR",e[e.OPERATOR_ITEM=30]="OPERATOR_ITEM",e[e.EXPR=31]="EXPR",e))(se||{}),Oi=(e=>(e[e.IS_EQ=0]="IS_EQ",e[e.IS_NOT_EQ=1]="IS_NOT_EQ",e[e.IS_LESS_THAN=2]="IS_LESS_THAN",e[e.IS_GREATER_THAN=3]="IS_GREATER_THAN",e[e.IS_LESS_THAN_OR_EQ=4]="IS_LESS_THAN_OR_EQ",e[e.IS_GREATER_THAN_OR_EQ=5]="IS_GREATER_THAN_OR_EQ",e))(Oi||{}),sr=(e=>(e[e.EMPTY=0]="EMPTY",e[e.PLUS=1]="PLUS",e[e.MINUS=2]="MINUS",e[e.POWER=3]="POWER",e[e.MULTIPLY=4]="MULTIPLY",e[e.DIVIDE=5]="DIVIDE",e[e.MOD_DIVIDE=6]="MOD_DIVIDE",e[e.FLOOR_DIVIDE=7]="FLOOR_DIVIDE",e[e.UNI_PLUS=8]="UNI_PLUS",e[e.UNI_MINUS=9]="UNI_MINUS",e))(sr||{}),Oc=(e=>(e[e.NUMBER=0]="NUMBER",e[e.STRING=1]="STRING",e[e.TEMPLATE=2]="TEMPLATE",e))(Oc||{});function rM(e){return!!(e!=null&&e.tokenType)}function Cr(e,t){const[n]=e??[];return((n==null?void 0:n.image)??t).trimStart().replaceAll(/^"|"$/g,"")}class iM extends nM{constructor(){super();ye(this,"unique",0);qn&&this.validateVisitor()}getnodelocation(n){const r=Object.values(n).flat().filter(i=>!!i).map(i=>i&&rM(i)?{startLine:i.startLine,startColumn:i.startColumn,startOffset:i.startOffset,endLine:i.endLine,endColumn:i.endColumn,endOffset:i.endOffset}:i!=null&&i.location?{...i.location}:{startLine:0,startColumn:0,startOffset:0,endLine:0,endColumn:0,endOffset:0}).filter(i=>i.startLine!==0&&i.endLine!==0);return{startLine:Math.min(...r.map(i=>i.startLine??1)),startColumn:Math.min(...r.map(i=>i.startColumn??1)),startOffset:Math.min(...r.map(i=>i.startOffset??1)),endLine:Math.max(...r.map(i=>i.endLine??1)),endColumn:Math.max(...r.map(i=>i.endColumn??1)),endOffset:Math.max(...r.map(i=>i.endOffset??1))}}createcodenode(n,r){return[{...r,...this.getnodelocation(n),lineindex:0}]}createstringnode(n,r){return this.createcodenode(n,{type:12,literal:1,value:r})}createmarknode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:3,id:r,comment:i}))}creategotonode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:4,id:r,comment:i}))}createlinenode(n,r){return this.createcodenode(n,{type:2,stmts:r})}createapinode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:1,words:i,method:r}))}createlogicnode(n,r,i,s){return this.createlinenode(n,this.createcodenode(n,{type:14,skip:i,words:s,method:r}))}createcountnode(n){return this.createcodenode(n,{type:5,index:this.unique++})}go(n){return Array.isArray(n)?n.map(r=>this.visit(r)).flat():k(n)?[this.visit(n)].flat():[]}program(n){return this.unique=0,this.createcodenode(n,{type:0,lines:[this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:"restart"})),this.go(n.line)].flat()})}line(n){return n.stmt?this.go(n.stmt):[]}stmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.short_commands?[this.go(n.short_commands),this.go(n.commands)].flat():[]}inline(n){return this.go(n.instmt)}instmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.commands?this.go(n.commands):[]}stmt_label(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:Cr(n.token_label,":").slice(1).trim()}))}stmt_stat(n){return this.createlinenode(n,this.createcodenode(n,{type:9,value:Cr(n.token_stat,"@").slice(1)}))}stmt_text(n){return this.createlinenode(n,this.createcodenode(n,{type:6,value:Cr(n.token_text,"")}))}stmt_comment(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!1,name:Cr(n.token_comment,"'").slice(1).trim()}))}stmt_hyperlink(n){return this.createlinenode(n,this.createcodenode(n,{type:8,link:this.go(n.words),text:Cr(n.token_hyperlinktext,";").slice(1)}))}stmt_command(n){return n.commands?this.go(n.commands):[]}short_commands(n){return n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):[]}commands(n){return n.words?this.createlinenode(n,this.createcodenode(n,{type:11,words:this.go(n.words)})):n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):n.command_play?this.go(n.command_play):n.structured_cmd?this.go(n.structured_cmd):[]}structured_cmd(n){return n.command_if?this.go(n.command_if):n.command_while?this.go(n.command_while):n.command_repeat?this.go(n.command_repeat):n.command_waitfor?this.go(n.command_waitfor):n.command_foreach?this.go(n.command_foreach):n.command_break?this.go(n.command_break):n.command_continue?this.go(n.command_continue):[]}short_go(n){return n.token_divide?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!0,words:this.go(n.words)})):[]}short_try(n){return n.token_query?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!1,words:this.go(n.words)})):[]}command_if(n){const[r]=this.createlogicnode(n,"if","",this.go(n.words)),[i]=this.go(n.command_if_block)??[];return this.createcodenode(n,{type:13,check:r,block:i})}command_if_block(n){const r=ht(),i=ht();return this.createcodenode(n,{type:15,skip:r,done:i,lines:[this.go(n.inline),this.go(n.line),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"alt logic")].flat(),altlines:[this.go(n.command_else_if),this.go(n.command_else),this.createmarknode(n,i,"end of if")].flat()})}command_block(n){return[this.go(n.inline),this.go(n.line)].flat()}command_fork(n){return[this.go(n.inline),this.go(n.line)].flat()}command_else_if(n){const r=ht(),i=ht();return this.createcodenode(n,{type:16,done:i,lines:[this.createlogicnode(n,"if",r,this.go(n.words)),this.go(n.command_fork),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"skip")].flat()})}command_else(n){return this.createcodenode(n,{type:17,lines:this.go(n.command_fork)})}command_while(n){const r=ht(),i=ht();return this.createcodenode(n,{type:18,loop:r,done:i,lines:[this.createmarknode(n,r,"start of while"),this.createlogicnode(n,"if",i,this.go(n.words)),this.go(n.command_block),this.creategotonode(n,r,"loop of while"),this.createmarknode(n,i,"end of while")].flat()})}command_repeat(n){const r=ht(),i=ht(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:21,loop:r,done:i,lines:[this.createapinode(n,"repeatstart",o),this.createmarknode(n,r,"start of repeat"),this.createlogicnode(n,"repeat",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of repeat"),this.createmarknode(n,i,"end of repeat")].flat()})}command_foreach(n){const r=ht(),i=ht(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:23,loop:r,done:i,lines:[this.createapinode(n,"foreachstart",o),this.createmarknode(n,r,"start of foreach"),this.createlogicnode(n,"foreach",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of foreach"),this.createmarknode(n,i,"end of foreach")].flat()})}command_waitfor(n){return this.createcodenode(n,{type:22,words:this.go(n.words)})}command_break(n){return this.createcodenode(n,{type:19,goto:0})}command_continue(n){return this.createcodenode(n,{type:20,goto:0})}command_play(n){const r=Cr(n.token_command_play,""),i=r.replace("bgplay","").replace("play","").trim(),s=r.includes("bgplay");return this.createlinenode(n,this.createcodenode(n,{type:11,words:[this.createstringnode(n,s?"bgplay":"play"),this.createstringnode(n,i)].flat()}))}expr(n){return n.and_test.length===1?this.go(n.and_test):this.createcodenode(n,{type:24,items:this.go(n.and_test)})}and_test(n){return n.not_test.length===1?this.go(n.not_test):this.createcodenode(n,{type:25,items:this.go(n.not_test)})}not_test(n){return n.comparison?this.go(n.comparison):n.not_test?this.createcodenode(n,{type:26,items:this.go(n.not_test)}):[]}comparison(n){if(n.arith_expr.length===1)return this.go(n.arith_expr);const[r,i]=this.go(n.arith_expr),[s]=this.go(n.comp_op);return this.createcodenode(n,{type:27,lhs:r,compare:s,rhs:i})}comp_op(n){return n.token_iseq?this.createcodenode(n,{type:28,method:0}):n.token_isnoteq?this.createcodenode(n,{type:28,method:1}):n.token_islessthan?this.createcodenode(n,{type:28,method:2}):n.token_isgreaterthan?this.createcodenode(n,{type:28,method:3}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:4}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:5}):[]}expr_value(n){return n.and_test_value.length===1?this.go(n.and_test_value):this.createcodenode(n,{type:24,items:this.go(n.and_test_value)})}and_test_value(n){return n.not_test_value.length===1?this.go(n.not_test_value):this.createcodenode(n,{type:25,items:this.go(n.not_test_value)})}not_test_value(n){return n.arith_expr?this.go(n.arith_expr):n.not_test_value?this.createcodenode(n,{type:26,items:this.go(n.not_test_value)}):[]}arith_expr(n){const r=this.go(n.term);return n.arith_expr_item?this.createcodenode(n,{type:29,lhs:r[0],items:this.go(n.arith_expr_item)}):r}arith_expr_item(n){return this.createcodenode(n,{type:30,operator:n.token_plus?1:2,rhs:this.go(n.term)[0]})}term(n){return n.term_item?this.createcodenode(n,{type:29,lhs:this.go(n.factor)[0],items:this.go(n.term_item)}):this.go(n.factor)}term_item(n){let r=0;return n.token_multiply&&(r=4),n.token_divide&&(r=5),n.token_moddivide&&(r=6),n.token_floordivide&&(r=7),this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})}factor(n){if(n.power)return this.go(n.power);let r=0;return n.token_plus&&(r=8),n.token_minus&&(r=9),this.createcodenode(n,{type:29,lhs:void 0,items:this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})})}power(n){const r=this.go(n.token);return n.factor?this.createcodenode(n,{type:29,lhs:r[0],items:this.createcodenode(n,{type:30,operator:3,rhs:this.go(n.factor)[0]})}):r}words(n){return this.go(n.expr)}token(n){if(n.token_stringliteraldouble){const r=Cr(n.token_stringliteraldouble,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:2,value:r})}if(n.token_stringliteral){const r=Cr(n.token_stringliteral,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:1,value:r})}if(n.token_numberliteral){const r=parseFloat(Cr(n.token_numberliteral,"0"));return this.createcodenode(n,{type:12,literal:0,value:r})}return n.token_lparen?this.createcodenode(n,{type:31,words:this.go(n.expr)}):[]}}const sM=new iM,tn={labels:{},internal:0,lineindex:0,linelookup:{},isfirststat:!1},Nc="zss.js";function Ne(e,t){return new zL(e.startLine??1,e.startColumn??1,Nc,t)}function Xf(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Zf(e){return`'${Xf(e)}'`}function Cc(e){if(e.startsWith('"'))return Cc(e.replaceAll(/(^"|"$)/g,""));const t=Jf(e);return t.errors.length?e:`['${t.tokens.map(r=>r.tokenType===Kf?`', api.get('${Xf(r.image.substring(1))}'), '`:Xf(r.image)).join("")}'].join('')`}function Ni(e){return e.filter(t=>t!==void 0).map(Fe)}function L_(e){return Ne(e,"")}function oM(e,t){const n=[];return e.forEach(r=>{n.push(r,t)}),n.pop(),n}function mt(e,t,n){return Ne(e,[`api.${t}(`,...oM(n,", "),")"])}function aM(e){if(e.type===se.COMPARE&&e.compare.type===se.COMPARE_ITEM)switch(e.compare.method){case Oi.IS_EQ:return mt(e,"isEq",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_NOT_EQ:return mt(e,"isNotEq",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_LESS_THAN:return mt(e,"isLessThan",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_GREATER_THAN:return mt(e,"isGreaterThan",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_LESS_THAN_OR_EQ:return mt(e,"isLessThanOrEq",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_GREATER_THAN_OR_EQ:return mt(e,"isGreaterThanOrEq",[Fe(e.lhs),Fe(e.rhs)])}return Ne(e,"")}function Ci(e,t,n){return e.prepend(`api.${t}(`),e.add([", ",Fe(n),")"])}function M_(e,t,n){return e.prepend(`api.${t}(`),e.add([Fe(n),")"])}function cM(e,t){if(e.type===se.OPERATOR_ITEM)switch(e.operator){case sr.PLUS:return Ci(t,"opPlus",e.rhs);case sr.MINUS:return Ci(t,"opMinus",e.rhs);case sr.POWER:return Ci(t,"opPower",e.rhs);case sr.MULTIPLY:return Ci(t,"opMultiply",e.rhs);case sr.DIVIDE:return Ci(t,"opDivide",e.rhs);case sr.MOD_DIVIDE:return Ci(t,"opModDivide",e.rhs);case sr.FLOOR_DIVIDE:return Ci(t,"opFloorDivide",e.rhs);case sr.UNI_PLUS:return M_(t,"opUniPlus",e.rhs);case sr.UNI_MINUS:return M_(t,"opUniMinus",e.rhs)}return Ne(e,"")}function lM(e){if(e.type===se.OPERATOR){const t=e.lhs?Fe(e.lhs):Ne(e,"");return e.items.forEach(n=>cM(n,t)),t}return Ne(e,"")}function Lc(e,t){return Ne(e,[mt(e,"jump",[`${t}`]),"; continue;"])}function Lr(e){return tn.linelookup[e??""]??-1}function Yf(e,t){tn.linelookup[e]=t}function Oo(e,t,n){for(let r=0;r{ve(e,Pf);const n=eN(t);Pt(e,n)},Jy=(e,t,n)=>{ve(e,Ky),Pt(e,XO(t,n))},CC=(e,t,n)=>Jy(t,n,Ht(e)),Xy=(e,t,n)=>{try{KO(t,Ht(e),n)}catch(r){console.error("Caught error while handling a Yjs update",r)}},LC=(e,t)=>{ve(e,qy),Pt(e,t)},MC=Xy,UC=(e,t,n,r)=>{const i=Ee(e);switch(i){case Pf:CC(e,t,n);break;case Ky:Xy(e,n,r);break;case qy:MC(e,n,r);break;default:throw new Error("Unknown message type")}return i},Ir=mC({shared:[]});function Ac(e,t,n){return e.find(r=>r.key===t&&r.type===n)}function Zy(e,t,n){const r=Ac(Ir.shared,e,t);k(r)||Ir.shared.push({key:e,type:t,value:n})}function PC(e,t){Zy(e,0,t)}function Yy(e,t){const n=new Dn(t);Zy(e,1,n)}function DC(e,t){const n=Ac(Ir.shared,e,0);if(k(n)){n.value=t;return}Ir.shared.push({key:e,type:0,value:t})}function BC(e,t){const n=new Dn(t),r=Ac(Ir.shared,e,1);if(k(r)){r.value=n;return}Ir.shared.push({key:e,type:1,value:n})}function Qy(e,t,n){let r;function i(){const o=Ac(Ir.shared,e,t);k(o)&&(s(),r=Uy(o,()=>n(o.value)))}const s=Uy(Ir.shared,i);return i(),()=>r==null?void 0:r()}function FC(e,t){return Qy(e,0,t)}function e_(e,t){return Qy(e,1,n=>t(n.toJSON()))}function Tc(e){return Un(e)}let t_=!1;const Yr=dC(Ir),Or=Po("modem",["second"],e=>{switch(e.target){case"second":!t_&&e.data%2===0&&Or.emit("modem:join");break;case"join":if(e.sender!==Or.id()){Or.reply(e,"joinack");const t=Kr();NC(t,Yr),Or.reply(e,"sync",Tc(t));const n=Kr();Jy(n,Yr),Or.reply(e,"sync",Tc(n))}break;case"joinack":t_=!0;break;case"sync":{if(k(e.data)&&e.sender!==Or.id()){const t=Ei(e.data),n=Kr();UC(t,n,Yr,Or)===Pf&&Or.emit("modem:sync",Tc(n))}break}}});function n_(e){const t=Kr();LC(t,e),Or.emit("modem:sync",Tc(t))}Yr.on("update",n_),Yr.on("destroy",()=>{Yr==null||Yr.off("update",n_)});const $C=navigator.userAgent.includes("Mac")?"cmd":"ctrl",Qr="$dkpurple",jC="$196",zC="$205";function un(e,t){return`$${e}${t}$blue`}function r_(e,t){return`$${e}${t}$ondkblue`}function rt(e,t){yt(e,t)}function WC(e,t){const n=jC.repeat(t);rt(e,`${Qr}${n}`)}function Df(e,t){const n=zC.repeat(t);rt(e,`${Qr}${n}`)}function Eo(e,t){rt(e,`${Qr} ${" ".repeat(t.length)} `),WC(e,t.length+2),rt(e,`${Qr} $white${t} `),Df(e,t.length+2)}function Nr(e,t){rt(e,`${Qr} ${" ".repeat(t.length)} `),rt(e,`${Qr} $gray${t} `),Df(e,t.length+2)}function De(e,t,n){rt(e,`${Qr} $white${t} $blue${n}`)}function Be(e,t){rt(e,`${Qr}$blue${t}`)}const GC=lr().command("send",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.ANY]);switch(n){case"helpmenu":Eo("cli","H E L P"),De("cli","#help controls","zss controls and inputs"),rt("cli","!helpcontrols;read help controls"),rt("cli",""),De("cli","#help text","text formatting"),rt("cli","!helptext;read help text"),rt("cli",""),De("cli","#help developer","developer commands"),rt("cli","!helpdeveloper;read help developer"),rt("cli",""),De("cli","#help player","player settings"),rt("cli","!helpplayer;read help player"),Nr("cli","keyboard input"),De("cli","?","open console"),De("cli","esc","close console"),De("cli","tab","move console"),De("cli","up / down arrow keys","navigate console items"),De("cli","left / right arrow keys","change console items"),De("cli","enter","interact with console items"),De("cli","alt + arrow keys","skip words and console lines"),De("cli",`${$C} + up / down arrow keys`,"input history");break;case"helpcontrols":Eo("cli","zss controls and inputs"),Nr("cli","keyboard input"),De("cli","arrow keys","move"),De("cli","shift + arrow keys","shoot"),De("cli","enter","ok / accept"),De("cli","escape","cancel / close"),De("cli","tab","menu / action"),Nr("cli","mouse input"),Be("cli","todo ???"),Nr("cli","controller input"),De("cli","left stick","move"),De("cli","right stick","aim"),De("cli","a","ok / accept"),De("cli","b","cancel / close"),De("cli","y","menu / action"),De("cli","x","shoot"),De("cli","triggers","shoot");break;case"helptext":Eo("cli","text formatting"),Nr("cli","typography"),Be("cli","plain text"),Be("cli","$centering text"),Be("cli",'"\\"@quoted strings for special chars\\""'),Be("cli","$$0-255 for ascii chars $159$176$240"),Be("cli",`use color names like ${un("red","$$red")} to change foreground color`),Be("cli",`use color names like ${r_("ongreen","$$ongreen")} to change background color`),Be("cli",`use clear ${r_("onclear","to change background to")} transparent`),Nr("cli","hyperlinks"),Be("cli",`${un("white",'"!hotkey"')} message shortcut;${un("gray","Label")}`),Be("cli",`${un("white",'"!range"')} flag [labelmin] [labelmax];${un("gray","Input Label")}`),Be("cli",`${un("white",'"!select"')} flag ...list of values;${un("gray","Input Label")}`),Be("cli",`${un("white",'"!number"')} flag [minvalue] [maxvalue];${un("gray","Input Label")}`),Be("cli",`${un("white",'"!text"')} flag;${un("gray","Input Label")}`),Be("cli",`${un("white",'"!copyit"')} flag;${un("gray","Input Label")}`);break;case"helpdeveloper":Eo("cli","developer commands"),De("cli","#books","list books in memory"),De("cli","#pages","list pages in opened book"),De("cli","@[pagetype:]page name","create & edit a new codepage in the currently opened book"),De("cli","#trash","list books and pages from open book you can delete"),De("cli","#save","flush state to register");break;case"helpplayer":Eo("cli","player settings"),Be("cli","todo");break;default:yt("$2",`${n} ${r??""}`);break}return 0}).command("stat",(e,t)=>{let n;const[r,...i]=t.map(Nt),s=i.join(" ");switch(Pe(r)){case bn(fe.LOADER):n=Mi(Xe.CONTENT,s,Ae.LOADER);break;default:n=Mi(Xe.CONTENT,[r,...i].join(" "),Ae.OBJECT);break;case bn(fe.BOARD):n=Mi(Xe.CONTENT,s,Ae.BOARD);break;case bn(fe.OBJECT):n=Mi(Xe.CONTENT,s,Ae.OBJECT);break;case bn(fe.TERRAIN):n=Mi(Xe.CONTENT,s,Ae.TERRAIN);break;case bn(fe.CHARSET):n=Mi(Xe.CONTENT,s,Ae.CHARSET);break;case bn(fe.PALETTE):n=Mi(Xe.CONTENT,s,Ae.PALETTE);break}return k(n)&&e.command("pageopen",n.id),0}).command("text",(e,t)=>{const n=t.map(Nt).join(" ");return yt("$2",n),0}).command("hyperlink",(e,t)=>{const[n,...r]=t,i=Nt(n),s=r.map(Nt).join(" ");return yt("$2",`!${s};${i}`),0}).command("dev",()=>(ni("cli"),Nb("cli",C.player),0)).command("share",()=>(ni("cli"),Cb("cli",C.player),0)).command("bookcreate",(e,t)=>{const[n]=ne(t,0,[q.MAYBE_STRING]),r=$_(n);return k(r)&&e.command("bookopen",r.id),0}).command("bookopen",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=ti(n);return k(r)?(Be("cli",`opened [book] ${r.name}`),Dc(Xe.MAIN,r.id),e.command("pages")):et("cli","bookopen",`book ${n} not found`,C.player),0}).command("booktrash",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=nn(Xe.MAIN),i=ti(n);return k(i)&&(r===i&&Dc(Xe.MAIN,""),OM(n),Be("cli",`trashed [book] ${i.name}`),ni("cli"),e.command("pages")),0}).command("pageopen",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=Bn(Xe.MAIN);if(!k(r))return 0;const i=yi(r,n);if(k(i)){const s=Xn(i),o=Zs(i);Be("cli",`opened [${o}] ${s}`),Yy(ph(r.id,i.id),i.code);const a=Zs(i);$b("cli",r.id,i.id,a,`${s} - ${r.name}`,C.player)}else et("cli","pageopen",`page ${n} not found`,C.player);return 0}).command("pagetrash",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=Bn(Xe.MAIN),i=qR(r,n);if(k(n)){const s=Xn(i),o=Zs(i);Be("cli",`trashed [${o}] ${s}`),ni("cli"),e.command("pages")}return 0}).command("nodetrash",()=>(Ub("cli"),Be("cli","node id changed, refreshing page recommended"),0)).command("help",(e,t)=>{const n=t.map(Nt).join(" ")||"menu";return e.command(`help${n}`),0}).command("books",()=>{Nr("cli","books");const e=nn(Xe.MAIN);De("cli","main",`${(e==null?void 0:e.name)??"empty"} $GREEN${(e==null?void 0:e.id)??""}`);const t=nn(Xe.CONTENT);De("cli","content",`${(t==null?void 0:t.name)??"empty"} ${(t==null?void 0:t.id)??""}`),Df("cli",7);const n=Pc();return n.length?n.forEach(r=>{rt("cli",`!bookopen ${r.id};${r.name}`)}):Be("cli","no books found"),rt("cli","!bookcreate;create a new book"),0}).command("pages",()=>{Nr("cli","pages");const e=Bn(Xe.MAIN);return k(e)&&(De("cli","main",`${e.name} $GREEN${e.id}`),e.pages.length?e.pages.forEach(t=>{const n=Xn(t),r=Zs(t);rt("cli",`!pageopen ${t.id};[${r}] ${n}`)}):(rt("cli",""),Be("cli","no pages found"),Be("cli","use @ to create a page"),Be("cli","@board name of board"),Be("cli","@object name of object"),Be("cli","@terrain name of terrain"),Be("cli","You can omit the type and it will default to object"),Be("cli","@object name of object"),Be("cli","@name of object"))),0}).command("trash",()=>{Nr("cli","$REDTRASH"),Be("cli","books");const e=Pc();e.length&&(e.forEach(n=>{rt("cli",`!booktrash ${n.id};$REDTRASH ${n.name}`)}),rt("cli",""));const t=nn(Xe.MAIN);return k(t)&&(Be("cli",`pages in open ${t.name} book`),t.pages.forEach(n=>{const r=Xn(n);rt("cli",`!pagetrash ${n.id};$REDTRASH ${r}`)}),rt("cli","")),0}).command("save",()=>(ni("cli"),0)).command("nuke",()=>(Mb("cli"),0));function HC(e){const t=Og[e];if(k(t))return t;const n=Mg[e];if(k(n))return n;const r=Ga[e];if(k(r))return r;const i=kh[e];if(k(i))return i}const VC=lr({get(e,t){const n=HC(t);return k(n)?[!0,n]:[!1,void 0]}}),KC=new Set(["inputmove","inputalt","inputctrl","inputshift","inputok","inputcancel","inputmenu"]),i_=new Set(["player","pushable","collision","destructible","p1","p2","p3","cycle","stepx","stepy","sender","arg"]),qC=["NORTH","SOUTH","WEST","EAST"];function JC(){const e=ps(C.player);if(Ge(e.inputqueue)||(e.inputqueue=[],e.inputcurrent=0),ke(e.inputcurrent)&&e.inputcurrent>0)return;const[t]=e.inputqueue,[n=Ft.NONE,r=0]=t??[Ft.NONE,0];switch(e.inputmove=[],e.inputok=0,e.inputcancel=0,e.inputmenu=0,e.inputalt=r&Ab?1:0,e.inputctrl=r&Tb?1:0,e.inputshift=r&xb?1:0,n){case Ft.MOVE_UP:case Ft.MOVE_DOWN:case Ft.MOVE_LEFT:case Ft.MOVE_RIGHT:e.inputmove=[qC[n-Ft.MOVE_UP]];break;case Ft.OK_BUTTON:e.inputok=1;break;case Ft.CANCEL_BUTTON:e.inputcancel=1;break;case Ft.MENU_BUTTON:e.inputmenu=1;break}e.inputcurrent=n,e.inputqueue=e.inputqueue.filter(i=>{const[s]=i;return s!==Ft.NONE&&s!==n})}const XC=lr({get(e,t){var s;C.isplayer&&KC.has(t)&&JC();const n=(s=C.element)==null?void 0:s[t];if(k(n)||i_.has(t))return[!0,n];const i=ps(C.player)[t];return[k(i),i]},set(e,t,n){var s;const r=(s=C.element)==null?void 0:s[t];if(k(r)||i_.has(t))return k(C.element)&&(C.element[t]=n),[!0,n];const i=ps(C.player);return i[t]=n,[!0,n]},everytick(e){var t,n;k((t=C.element)==null?void 0:t.x)&&k(C.element.y)&&k(C.element.stepx)&&k(C.element.stepy)&&Gg(e,C.book,C.board,C.element,{x:C.element.x+C.element.stepx,y:C.element.y+C.element.stepy})===!1&&(C.element.stepx=0,C.element.stepy=0),(n=C.element)!=null&&n.headless&&e.command("die")}}).command("become",(e,t)=>{var i,s;const n={x:((i=C.element)==null?void 0:i.x)??0,y:((s=C.element)==null?void 0:s.y)??0},[r]=ne(t,0,[q.KIND]);return za(C.book,C.board),Qs(C.book,C.board,C.element),Lu(C.book,C.element,C.timestamp)&&Mu(C.book,C.board,r,n),e.endofprogram(),0}).command("bind",()=>0).command("char",(e,t)=>{const[n]=ne(t,0,[q.NUMBER]);return k(C.element)&&(C.element.char=n),0}).command("color",(e,t)=>{const[n]=ne(t,0,[q.COLOR]);return k(C.element)&&k(n)&&Va(C.element,n),0}).command("go",(e,t)=>{if(k(C.element)){const[n]=ne(t,0,[q.DIR]);if(Gg(e,C.book,C.board,C.element,n),e.yield(),C.element.x===n.x&&C.element.y===n.y)return 0}return 1}).command("try",(e,t)=>{const[,n]=ne(t,0,[q.DIR]);return e.command("go",...t)&&n{if(!k(C.element))return 0;const[n]=ne(t,0,[q.DIR]),r=C.element.x??0,i=C.element.y??0;return C.element.stepx=n.x-r,C.element.stepy=n.y-i,0}),ZC=lr().command("clear",(e,t)=>(t.forEach(n=>e.set(Nt(n),0)),0)).command("set",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.ANY]);return e.set(n,r),0}).command("take",(e,t)=>{const[n,r,i]=ne(t,0,[q.STRING,q.MAYBE_NUMBER]),s=e.get(n),o=r??1;if(!ke(s))return 1;const a=s-o;return a<0?(i{const[n,r,i]=ne(t,0,[q.STRING,q.MAYBE_NUMBER]),s=e.get(n),o=ke(s)?s:0,a=r??1;if(!ke(a))return 0;const c=s===void 0?1:0;return c&&i0&&b<_.lastIndexOf(" ")?c.low.call(p):p})},sentence:function(h,p,m){return h=l.lower(h).replace(a.sentence,function(b,_,w){return _+c.up.call(w)}),p&&p.forEach(function(b){h=h.replace(new RegExp("\\b"+l.lower(b)+"\\b","g"),c.cap)}),m&&m.forEach(function(b){h=h.replace(new RegExp("(\\b"+l.lower(b)+"\\. +)(\\w)"),function(_,w,v){return w+c.low.call(v)})}),h}};u.squish=u.pascal,l.default=l;for(var f in u)l.type(f,u[f]);var d=typeof d=="function"?d:function(){};d(e.exports?e.exports=l:this.Case=l)}).call(Bt)})(s_);var YC=s_.exports,QC=Pi(YC);const ei={};function Bf(e){return{player:e,layers:[],panels:[],reset:!0,focus:"scroll"}}function o_(e){e.text=[],Object.values(ei[e.id]??{}).forEach(t=>t==null?void 0:t()),ei[e.id]={}}function a_(e){const t=e.panels.find(n=>n.name===e.focus);if(!t){const n={id:ht(),name:e.focus,edge:fn.RIGHT,size:20,text:[]};return e.panels.push(n),e.reset=!1,n}return t}const eL=new Set(["hk","hotkey","rn","range","sl","select","nm","number","tx","text"]),tL=new Set(["rn","range","sl","select","nm","number","tx","text"]),nL=new Set(["tx","text"]),rL={rn:1,range:1,sl:0,select:0,nm:0,number:0,tx:"",text:""},c_={};let l_=e=>{let t=c_[e];return k(t)||(c_[e]=t=Bf(e)),t};function iL(e){l_=e}function Ii(e){return l_(e)}function sL(e){const t=Ii(e);t.panels=t.panels.filter(n=>n.edge!==fn.SCROLL)}function oL(e,t,n){Object.values(ei).forEach(r=>{if(r[t]!==void 0){const i=hh(e.id(),t);ke(n)&&DC(i,n),Ce(n)&&BC(i,n)}})}function aL(e){let t="";const n=Ii(e);return n.panels=n.panels.filter(r=>{if(r.edge===fn.SCROLL){const[i]=r.text;return Ce(i)&&r.text.length===1&&(t=i),r.text.length>1}return!0}),t}function Ff(e,t,n,r,i){const s=Ii(e),o=r,a=i??QC.capital(t),c=s.panels.find(l=>l.name===a);if(c)s.reset=!0,s.focus=a,ke(o)&&(c.size=o);else switch(n){case fn.START:break;case fn.LEFT:case fn.RIGHT:case fn.TOP:case fn.BOTTOM:case fn.SCROLL:{const l={id:ht(),name:a,edge:n,size:o??Sb[n],text:[]};s.panels.push(l),s.focus=a;break}}}function cL(e,t){const n=Ii(e),r=a_(n);n.reset&&(n.reset=!1,o_(r)),r.text.push(t)}function lL(e,t,n,r,i){const s=Ii(e),o=a_(s);s.reset&&(s.reset=!1,o_(o));const a=Pe(r),c=[t.id(),n,...eL.has(a)?[a]:["hyperlink",r],...i],l=c[2];if(tL.has(l)){const u=`${c[3]??""}`;ei[o.id]=ei[o.id]??{};const f=t.get(u)??rL[l];if(ei[o.id][u]===void 0){const d=hh(t.id(),u);ke(f)&&PC(d,f),Ce(f)&&Yy(d,f),nL.has(l)?ei[o.id][u]=e_(d,h=>{k(h)&&h!==t.get(u)&&t.set(u,h)}):ei[o.id][u]=FC(d,h=>{k(h)&&h!==t.get(u)&&t.set(u,h)})}}o.text.push(c)}const uL=lr({get(){return[!1,void 0]},set(e,t,n){return oL(e,t,n),[!1,void 0]},tick(){var t;const e=((t=C.element)==null?void 0:t.name)??"scroll";Ff(C.player,"scroll",fn.SCROLL,void 0,e)},everytick(){const e=aL(C.player);if(e&&k(C.element)){C.element.tickertext=e,C.element.tickertime=C.timestamp;const t=Tg(C.book,C.element);yt(`$${be[t.color]}$${t.char}`,e)}}}).command("send",(e,t)=>{var u,f;const[n,r]=ne(t,0,[q.STRING,q.ANY]),[i,s]=n.split(":"),o=k(s)?i:"self",a=s??i;function c(d){d.forEach(h=>{k(h.id)&&e.send(h.id,a,r)})}const l=Pe(o);switch(l){case"all":for(const d of Object.keys(((u=C.board)==null?void 0:u.objects)??{}))e.send(d,a,r);break;case"self":e.message({id:ht(),sender:e.id(),target:a,data:r});break;case"others":for(const d of Object.keys(((f=C.board)==null?void 0:f.objects)??{}))d!==e.id()&&e.send(d,a,r);break;default:{c(tl(C.board,[o]));const d=e.get(l);Ge(d)?c(tl(C.board,d)):c(tl(C.board,[d]));break}}return 0}).command("stat",(e,t)=>{const n=Pm(t.map(Nt));switch(n.type){case fe.OBJECT:k(C.element)&&(C.element.name=n.values.join(" "));break}return 0}).command("text",(e,t)=>{const n=t.map(Nt).join("");return cL(C.player,n),0}).command("hyperlink",(e,t)=>{const[n,r,...i]=t,s=Nt(n),o=Nt(r);return lL(C.player,e,s,o,i),0}).command("gadget",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=kb[Pe(n)];if(r===fn.SCROLL){const[,i,s]=ne(t,0,[q.STRING,q.MAYBE_STRING,q.MAYBE_NUMBER]);Ff(C.player,n,r,s,i)}else{const[,i,s]=ne(t,0,[q.STRING,q.MAYBE_NUMBER,q.MAYBE_STRING]);Ff(C.player,n,r,i,s)}return 0}),fL=lr().command("idle",e=>(e.yield(),0)).command("end",e=>(e.endofprogram(),0)).command("endwith",(e,t)=>{const[n]=ne(t,0,[q.ANY]);return e.set("arg",n),e.command("end")}).command("lock",e=>(e.lock(e.id()),0)).command("restore",(e,t)=>(e.restore(Nt(t[0])),0)).command("unlock",e=>(e.unlock(),0)).command("zap",(e,t)=>(e.zap(Nt(t[0])),0)).command("cycle",(e,t)=>{if(k(C.element)){const[n]=ne(t,0,[q.NUMBER]);C.element.cycle=si(Math.round(n),1,255)}return 0}).command("die",e=>{var t;return(t=C.element)!=null&&t.headless&&Qs(C.book,C.board,C.element),Lu(C.book,C.element,C.timestamp),e.endofprogram(),0}).command("endgame",()=>(jb("element",C.player),0)).command("run",(e,t)=>{const[n]=ne(t,0,[q.STRING]);return Bc(n),0}).command("runwith",(e,t)=>{const[n,r]=ne(t,0,[q.ANY,q.STRING]);return e.set("arg",n),Bc(r),0});function u_(e,t){if(!k(e))return;const n=Pe(t),r=n.endsWith("le");switch(n){case"float32":case"float32le":{const i=e.dataview.getFloat32(e.cursor,r);return e.cursor+=4,i}case"float64":case"float64le":{const i=e.dataview.getFloat64(e.cursor,r);return e.cursor+=8,i}case"int8":case"int8le":{const i=e.dataview.getInt8(e.cursor);return e.cursor+=1,i}case"int16":case"int16le":{const i=e.dataview.getInt16(e.cursor,r);return e.cursor+=2,i}case"int32":case"int32le":{const i=e.dataview.getInt32(e.cursor,r);return e.cursor+=4,i}case"int64":case"int64le":{const i=e.dataview.getBigInt64(e.cursor,r);return e.cursor+=8,i}case"uint8":case"uint8le":{const i=e.dataview.getUint8(e.cursor);return e.cursor+=1,i}case"uint16":case"uint16le":{const i=e.dataview.getUint16(e.cursor,r);return e.cursor+=2,i}case"uint32":case"uint32le":{const i=e.dataview.getUint32(e.cursor,r);return e.cursor+=4,i}case"uint64":case"uint64le":{const i=e.dataview.getBigUint64(e.cursor,r);return e.cursor+=8,i}}}const hL=(e,t)=>{const n=H_(e.id());if(!k(n))return 0;const[r]=ne(t,0,[q.STRING]),i=Pe(r);switch(i){case"seek":{const[s]=ne(t,1,[q.NUMBER]);n.cursor=s;break}case"float32":case"float32le":case"float64":case"float64le":case"int8":case"int8le":case"int16":case"int16le":case"int32":case"int32le":case"int64":case"int64le":case"uint8":case"uint8le":case"uint16":case"uint16le":case"uint32":case"uint32le":case"uint64":case"uint64le":{const[s]=ne(t,1,[q.STRING]);e.set(s,u_(n,i));break}case"text":{const[s,o]=ne(t,1,[q.STRING,q.STRING]),a=u_(n,s);if(ke(a)&&Ce(o)){const c=new Uint8Array(n.bytes.buffer,n.cursor,a),u=new TextDecoder("utf-8").decode(c);e.set(o,u),n.cursor+=a}break}}return 0},dL=lr({get(e,t){const n=H_(e.id());if(k(n))switch(Pe(t)){case"filename":return[k(n.filename),n.filename];case"cursor":return[k(n.cursor),n.cursor]}return[!1,void 0]}}).command("send",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.ANY]);return e.message({id:ht(),sender:e.id(),target:n,data:r}),0}).command("stat",()=>0).command("text",(e,t)=>{const n=t.map(Nt).join(" ");return yt("$2",n),0}).command("hyperlink",(e,t)=>{const[n,...r]=t,i=Nt(n),s=r.map(Nt).join(" ");return yt("$2",`!${s};${i}`),0}).command("load",(e,t)=>{const n=t.map(Nt).join(" "),r=e.get(n)??n;return Bn(Xe.CONTENT,r),0}).command("reload",(e,t)=>{const n=t.map(Nt).join(" "),r=e.get(n)??n,i=Bn(Xe.CONTENT,r);return i.pages=[],0}).command("bin",hL);var ko=(e=>(e[e.ERROR=0]="ERROR",e[e.CLI=1]="CLI",e[e.LOADER=2]="LOADER",e[e.CODE_PAGE=3]="CODE_PAGE",e))(ko||{});const pL={audio:bI,board:vI,cli:GC,const:VC,element:XC,flags:ZC,gadget:uL,lifecycle:fL,loader:dL},$f=["const","flags","audio","board","lifecycle","element"],mL={0:[],1:["cli",...$f],2:["loader",...$f],3:["gadget",...$f]},gL={0:new Map,1:new Map,2:new Map,3:new Map};function So(e){return(mL[e]??[]).map(n=>pL[n]).filter(k)}function yL(e,t){const n=gL[e];if(!n.has(t)){let r;const i=So(e);for(let s=0;s>>=g_,i>0&&(r|=kL),n+=vL.encode(r);while(i>0);return n};var Ao={};(function(e){function t(I,T,M){if(T in I)return I[T];if(arguments.length===3)return M;throw new Error('"'+T+'" is a required argument.')}e.getArg=t;const n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(I){const T=I.match(n);return T?{scheme:T[1],auth:T[2],host:T[3],port:T[4],path:T[5]}:null}e.urlParse=i;function s(I){let T="";return I.scheme&&(T+=I.scheme+":"),T+="//",I.auth&&(T+=I.auth+"@"),I.host&&(T+=I.host),I.port&&(T+=":"+I.port),I.path&&(T+=I.path),T}e.urlGenerate=s;const o=32;function a(I){const T=[];return function(M){for(let V=0;Vo&&T.pop(),x}}const c=a(function(T){let M=T;const x=i(T);if(x){if(!x.path)return T;M=x.path}const V=e.isAbsolute(M),oe=[];let O=0,E=0;for(;;)if(O=E,E=M.indexOf("/",O),E===-1){oe.push(M.slice(O));break}else for(oe.push(M.slice(O,E));E=0;E--){const N=oe[E];N==="."?oe.splice(E,1):N===".."?g++:g>0&&(N===""?(oe.splice(E+1,g),g=0):(oe.splice(E,2),g--))}return M=oe.join("/"),M===""&&(M=V?"/":"."),x?(x.path=M,s(x)):M});e.normalize=c;function l(I,T){I===""&&(I="."),T===""&&(T=".");const M=i(T),x=i(I);if(x&&(I=x.path||"/"),M&&!M.scheme)return x&&(M.scheme=x.scheme),s(M);if(M||T.match(r))return T;if(x&&!x.host&&!x.path)return x.host=T,s(x);const V=T.charAt(0)==="/"?T:c(I.replace(/\/+$/,"")+"/"+T);return x?(x.path=V,s(x)):V}e.join=l,e.isAbsolute=function(I){return I.charAt(0)==="/"||n.test(I)};function u(I,T){I===""&&(I="."),I=I.replace(/\/$/,"");let M=0;for(;T.indexOf(I+"/")!==0;){const x=I.lastIndexOf("/");if(x<0||(I=I.slice(0,x),I.match(/^([^\/]+:\/)?\/*$/)))return T;++M}return Array(M+1).join("../")+T.substr(I.length+1)}e.relative=u;const f=function(){return!("__proto__"in Object.create(null))}();function d(I){return I}function h(I){return m(I)?"$"+I:I}e.toSetString=f?d:h;function p(I){return m(I)?I.slice(1):I}e.fromSetString=f?d:p;function m(I){if(!I)return!1;const T=I.length;if(T<9||I.charCodeAt(T-1)!==95||I.charCodeAt(T-2)!==95||I.charCodeAt(T-3)!==111||I.charCodeAt(T-4)!==116||I.charCodeAt(T-5)!==111||I.charCodeAt(T-6)!==114||I.charCodeAt(T-7)!==112||I.charCodeAt(T-8)!==95||I.charCodeAt(T-9)!==95)return!1;for(let M=T-10;M>=0;M--)if(I.charCodeAt(M)!==36)return!1;return!0}function b(I,T,M){let x=w(I.source,T.source);return x!==0||(x=I.originalLine-T.originalLine,x!==0)||(x=I.originalColumn-T.originalColumn,x!==0||M)||(x=I.generatedColumn-T.generatedColumn,x!==0)||(x=I.generatedLine-T.generatedLine,x!==0)?x:w(I.name,T.name)}e.compareByOriginalPositions=b;function _(I,T,M){let x=I.generatedLine-T.generatedLine;return x!==0||(x=I.generatedColumn-T.generatedColumn,x!==0||M)||(x=w(I.source,T.source),x!==0)||(x=I.originalLine-T.originalLine,x!==0)||(x=I.originalColumn-T.originalColumn,x!==0)?x:w(I.name,T.name)}e.compareByGeneratedPositionsDeflated=_;function w(I,T){return I===T?0:I===null?1:T===null?-1:I>T?1:-1}function v(I,T){let M=I.generatedLine-T.generatedLine;return M!==0||(M=I.generatedColumn-T.generatedColumn,M!==0)||(M=w(I.source,T.source),M!==0)||(M=I.originalLine-T.originalLine,M!==0)||(M=I.originalColumn-T.originalColumn,M!==0)?M:w(I.name,T.name)}e.compareByGeneratedPositionsInflated=v;function S(I){return JSON.parse(I.replace(/^\)]}'[^\n]*\n/,""))}e.parseSourceMapInput=S;function L(I,T,M){if(T=T||"",I&&(I[I.length-1]!=="/"&&T[0]!=="/"&&(I+="/"),T=I+T),M){const x=i(M);if(!x)throw new Error("sourceMapURL could not be parsed");if(x.path){const V=x.path.lastIndexOf("/");V>=0&&(x.path=x.path.substring(0,V+1))}T=l(s(x),T)}return c(T)}e.computeSourceURL=L})(Ao);var jf={};let AL=class Q_{constructor(){this._array=[],this._set=new Map}static fromArray(t,n){const r=new Q_;for(let i=0,s=t.length;i=0)return n;throw new Error('"'+t+'" is not in the set.')}at(t){if(t>=0&&tn||r==n&&s>=i||b_.compareByGeneratedPositionsInflated(e,t)<=0}let xL=class{constructor(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}unsortedForEach(t,n){this._array.forEach(t,n)}add(t){TL(this._last,t)?(this._last=t,this._array.push(t)):(this._sorted=!1,this._array.push(t))}toArray(){return this._sorted||(this._array.sort(b_.compareByGeneratedPositionsInflated),this._sorted=!0),this._array}};__.MappingList=xL;const To=d_,pt=Ao,xc=jf.ArraySet,RL=__.MappingList;let w_=class eb{constructor(t){t||(t={}),this._file=pt.getArg(t,"file",null),this._sourceRoot=pt.getArg(t,"sourceRoot",null),this._skipValidation=pt.getArg(t,"skipValidation",!1),this._sources=new xc,this._names=new xc,this._mappings=new RL,this._sourcesContents=null}static fromSourceMap(t){const n=t.sourceRoot,r=new eb({file:t.file,sourceRoot:n});return t.eachMapping(function(i){const s={generated:{line:i.generatedLine,column:i.generatedColumn}};i.source!=null&&(s.source=i.source,n!=null&&(s.source=pt.relative(n,s.source)),s.original={line:i.originalLine,column:i.originalColumn},i.name!=null&&(s.name=i.name)),r.addMapping(s)}),t.sources.forEach(function(i){let s=i;n!==null&&(s=pt.relative(n,i)),r._sources.has(s)||r._sources.add(s);const o=t.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r}addMapping(t){const n=pt.getArg(t,"generated"),r=pt.getArg(t,"original",null);let i=pt.getArg(t,"source",null),s=pt.getArg(t,"name",null);this._skipValidation||this._validateMapping(n,r,i,s),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:s})}setSourceContent(t,n){let r=t;this._sourceRoot!=null&&(r=pt.relative(this._sourceRoot,r)),n!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[pt.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[pt.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))}applySourceMap(t,n,r){let i=n;if(n==null){if(t.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=t.file}const s=this._sourceRoot;s!=null&&(i=pt.relative(s,i));const o=this._mappings.toArray().length>0?new xc:this._sources,a=new xc;this._mappings.unsortedForEach(function(c){if(c.source===i&&c.originalLine!=null){const f=t.originalPositionFor({line:c.originalLine,column:c.originalColumn});f.source!=null&&(c.source=f.source,r!=null&&(c.source=pt.join(r,c.source)),s!=null&&(c.source=pt.relative(s,c.source)),c.originalLine=f.line,c.originalColumn=f.column,f.name!=null&&(c.name=f.name))}const l=c.source;l!=null&&!o.has(l)&&o.add(l);const u=c.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=o,this._names=a,t.sources.forEach(function(c){const l=t.sourceContentFor(c);l!=null&&(r!=null&&(c=pt.join(r,c)),s!=null&&(c=pt.relative(s,c)),this.setSourceContent(c,l))},this)}_validateMapping(t,n,r,i){if(n&&typeof n.line!="number"&&typeof n.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(t&&"line"in t&&"column"in t&&t.line>0&&t.column>=0&&!n&&!r&&!i)){if(!(t&&"line"in t&&"column"in t&&n&&"line"in n&&"column"in n&&t.line>0&&t.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:t,source:r,original:n,name:i}))}}_serializeMappings(){let t=0,n=1,r=0,i=0,s=0,o=0,a="",c,l,u,f;const d=this._mappings.toArray();for(let h=0,p=d.length;h0){if(!pt.compareByGeneratedPositionsInflated(l,d[h-1]))continue;c+=","}c+=To.encode(l.generatedColumn-t),t=l.generatedColumn,l.source!=null&&(f=this._sources.indexOf(l.source),c+=To.encode(f-o),o=f,c+=To.encode(l.originalLine-1-i),i=l.originalLine-1,c+=To.encode(l.originalColumn-r),r=l.originalColumn,l.name!=null&&(u=this._names.indexOf(l.name),c+=To.encode(u-s),s=u)),a+=c}return a}_generateSourcesContent(t,n){return t.map(function(r){if(!this._sourcesContents)return null;n!=null&&(r=pt.relative(n,r));const i=pt.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)}toJSON(){const t={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(t.file=this._file),this._sourceRoot!=null&&(t.sourceRoot=this._sourceRoot),this._sourcesContents&&(t.sourcesContent=this._generateSourcesContent(t.sources,t.sourceRoot)),t}toString(){return JSON.stringify(this.toJSON())}};w_.prototype._version=3,h_.SourceMapGenerator=w_;var v_={};(function(e){e.GREATEST_LOWER_BOUND=1,e.LEAST_UPPER_BOUND=2;function t(n,r,i,s,o,a){const c=Math.floor((r-n)/2)+n,l=o(i,s[c],!0);return l===0?c:l>0?r-c>1?t(c,r,i,s,o,a):a==e.LEAST_UPPER_BOUND?r1?t(n,c,i,s,o,a):a==e.LEAST_UPPER_BOUND?c:n<0?-1:n}e.search=function(r,i,s,o){if(i.length===0)return-1;let a=t(-1,i.length,r,i,s,o||e.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&s(i[a],i[a-1],!0)===0;)--a;return a}})(v_);var xo={exports:{}},IL={},OL=Object.freeze({__proto__:null,default:IL}),E_=tb(OL);if((function(){return typeof window<"u"&&this===window}).call()){let e=null;xo.exports=function(){if(typeof e=="string")return fetch(e).then(n=>n.arrayBuffer());if(e instanceof ArrayBuffer)return Promise.resolve(e);throw new Error("You must provide the string URL or ArrayBuffer contents of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer")},xo.exports.initialize=t=>e=t}else{const e=E_,t=E_;xo.exports=function(){return new Promise((r,i)=>{const s=t.join(__dirname,"mappings.wasm");e.readFile(s,null,(o,a)=>{if(o){i(o);return}r(a.buffer)})})},xo.exports.initialize=n=>{console.debug("SourceMapConsumer.initialize is a no-op when running in node.js")}}var k_=xo.exports;const NL=k_;function CL(){this.generatedLine=0,this.generatedColumn=0,this.lastGeneratedColumn=null,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}let Ro=null;var LL=function(){if(Ro)return Ro;const t=[];return Ro=NL().then(n=>WebAssembly.instantiate(n,{env:{mapping_callback(r,i,s,o,a,c,l,u,f,d){const h=new CL;h.generatedLine=r+1,h.generatedColumn=i,s&&(h.lastGeneratedColumn=o-1),a&&(h.source=c,h.originalLine=l+1,h.originalColumn=u,f&&(h.name=d)),t[t.length-1](h)},start_all_generated_locations_for(){console.time("all_generated_locations_for")},end_all_generated_locations_for(){console.timeEnd("all_generated_locations_for")},start_compute_column_spans(){console.time("compute_column_spans")},end_compute_column_spans(){console.timeEnd("compute_column_spans")},start_generated_location_for(){console.time("generated_location_for")},end_generated_location_for(){console.timeEnd("generated_location_for")},start_original_location_for(){console.time("original_location_for")},end_original_location_for(){console.timeEnd("original_location_for")},start_parse_mappings(){console.time("parse_mappings")},end_parse_mappings(){console.timeEnd("parse_mappings")},start_sort_by_generated_location(){console.time("sort_by_generated_location")},end_sort_by_generated_location(){console.timeEnd("sort_by_generated_location")},start_sort_by_original_location(){console.time("sort_by_original_location")},end_sort_by_original_location(){console.timeEnd("sort_by_original_location")}}})).then(n=>({exports:n.instance.exports,withMappingCallback:(r,i)=>{t.push(r);try{i()}finally{t.pop()}}})).then(null,n=>{throw Ro=null,n}),Ro};const he=Ao,zf=v_,Rc=jf.ArraySet,ML=k_,UL=LL,Wf=Symbol("smcInternal");class ut{constructor(t,n){return t==Wf?Promise.resolve(this):DL(t,n)}static initialize(t){ML.initialize(t["lib/mappings.wasm"])}static fromSourceMap(t,n){return BL(t,n)}static async with(t,n,r){const i=await new ut(t,n);try{return await r(i)}finally{i.destroy()}}_parseMappings(t,n){throw new Error("Subclasses must implement _parseMappings")}eachMapping(t,n,r){throw new Error("Subclasses must implement eachMapping")}allGeneratedPositionsFor(t){throw new Error("Subclasses must implement allGeneratedPositionsFor")}destroy(){throw new Error("Subclasses must implement destroy")}}ut.prototype._version=3,ut.GENERATED_ORDER=1,ut.ORIGINAL_ORDER=2,ut.GREATEST_LOWER_BOUND=1,ut.LEAST_UPPER_BOUND=2;class Io extends ut{constructor(t,n){return super(Wf).then(r=>{let i=t;typeof t=="string"&&(i=he.parseSourceMapInput(t));const s=he.getArg(i,"version");let o=he.getArg(i,"sources");const a=he.getArg(i,"names",[]);let c=he.getArg(i,"sourceRoot",null);const l=he.getArg(i,"sourcesContent",null),u=he.getArg(i,"mappings"),f=he.getArg(i,"file",null);if(s!=r._version)throw new Error("Unsupported version: "+s);return c&&(c=he.normalize(c)),o=o.map(String).map(he.normalize).map(function(d){return c&&he.isAbsolute(c)&&he.isAbsolute(d)?he.relative(c,d):d}),r._names=Rc.fromArray(a.map(String),!0),r._sources=Rc.fromArray(o,!0),r._absoluteSources=r._sources.toArray().map(function(d){return he.computeSourceURL(c,d,n)}),r.sourceRoot=c,r.sourcesContent=l,r._mappings=u,r._sourceMapURL=n,r.file=f,r._computedColumnSpans=!1,r._mappingsPtr=0,r._wasm=null,UL().then(d=>(r._wasm=d,r))})}_findSourceIndex(t){let n=t;if(this.sourceRoot!=null&&(n=he.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);for(let r=0;r{a.source!==null&&(a.source=this._sources.at(a.source),a.source=he.computeSourceURL(o,a.source,this._sourceMapURL),a.name!==null&&(a.name=this._names.at(a.name))),t.call(i,a)},()=>{switch(s){case ut.GENERATED_ORDER:this._wasm.exports.by_generated_location(this._getMappingsPtr());break;case ut.ORIGINAL_ORDER:this._wasm.exports.by_original_location(this._getMappingsPtr());break;default:throw new Error("Unknown order of iteration.")}})}allGeneratedPositionsFor(t){let n=he.getArg(t,"source");const r=he.getArg(t,"line"),i=t.column||0;if(n=this._findSourceIndex(n),n<0)return[];if(r<1)throw new Error("Line numbers must be >= 1");if(i<0)throw new Error("Column numbers must be >= 0");const s=[];return this._wasm.withMappingCallback(o=>{let a=o.lastGeneratedColumn;this._computedColumnSpans&&a===null&&(a=1/0),s.push({line:o.generatedLine,column:o.generatedColumn,lastColumn:a})},()=>{this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(),n,r-1,"column"in t,i)}),s}destroy(){this._mappingsPtr!==0&&(this._wasm.exports.free_mappings(this._mappingsPtr),this._mappingsPtr=0)}computeColumnSpans(){this._computedColumnSpans||(this._wasm.exports.compute_column_spans(this._getMappingsPtr()),this._computedColumnSpans=!0)}originalPositionFor(t){const n={generatedLine:he.getArg(t,"line"),generatedColumn:he.getArg(t,"column")};if(n.generatedLine<1)throw new Error("Line numbers must be >= 1");if(n.generatedColumn<0)throw new Error("Column numbers must be >= 0");let r=he.getArg(t,"bias",ut.GREATEST_LOWER_BOUND);r==null&&(r=ut.GREATEST_LOWER_BOUND);let i;if(this._wasm.withMappingCallback(s=>i=s,()=>{this._wasm.exports.original_location_for(this._getMappingsPtr(),n.generatedLine-1,n.generatedColumn,r)}),i&&i.generatedLine===n.generatedLine){let s=he.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=he.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));let o=he.getArg(i,"name",null);return o!==null&&(o=this._names.at(o)),{source:s,line:he.getArg(i,"originalLine",null),column:he.getArg(i,"originalColumn",null),name:o}}return{source:null,line:null,column:null,name:null}}hasContentsOfAllSources(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(t){return t==null}):!1}sourceContentFor(t,n){if(!this.sourcesContent)return null;const r=this._findSourceIndex(t);if(r>=0)return this.sourcesContent[r];let i=t;this.sourceRoot!=null&&(i=he.relative(this.sourceRoot,i));let s;if(this.sourceRoot!=null&&(s=he.urlParse(this.sourceRoot))){const o=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(n)return null;throw new Error('"'+i+'" is not in the SourceMap.')}generatedPositionFor(t){let n=he.getArg(t,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};const r={source:n,originalLine:he.getArg(t,"line"),originalColumn:he.getArg(t,"column")};if(r.originalLine<1)throw new Error("Line numbers must be >= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");let i=he.getArg(t,"bias",ut.GREATEST_LOWER_BOUND);i==null&&(i=ut.GREATEST_LOWER_BOUND);let s;if(this._wasm.withMappingCallback(o=>s=o,()=>{this._wasm.exports.generated_location_for(this._getMappingsPtr(),r.source,r.originalLine-1,r.originalColumn,i)}),s&&s.source===r.source){let o=s.lastGeneratedColumn;return this._computedColumnSpans&&o===null&&(o=1/0),{line:he.getArg(s,"generatedLine",null),column:he.getArg(s,"generatedColumn",null),lastColumn:o}}return{line:null,column:null,lastColumn:null}}}Io.prototype.consumer=ut;class PL extends ut{constructor(t,n){return super(Wf).then(r=>{let i=t;typeof t=="string"&&(i=he.parseSourceMapInput(t));const s=he.getArg(i,"version"),o=he.getArg(i,"sections");if(s!=r._version)throw new Error("Unsupported version: "+s);r._sources=new Rc,r._names=new Rc,r.__generatedMappings=null,r.__originalMappings=null,r.__generatedMappingsUnsorted=null,r.__originalMappingsUnsorted=null;let a={line:-1,column:0};return Promise.all(o.map(c=>{if(c.url)throw new Error("Support for url field in sections not implemented.");const l=he.getArg(c,"offset"),u=he.getArg(l,"line"),f=he.getArg(l,"column");if(u({generatedOffset:{generatedLine:u+1,generatedColumn:f+1},consumer:h}))})).then(c=>(r._sections=c,r))})}get _generatedMappings(){return this.__generatedMappings||this._sortGeneratedMappings(),this.__generatedMappings}get _originalMappings(){return this.__originalMappings||this._sortOriginalMappings(),this.__originalMappings}get _generatedMappingsUnsorted(){return this.__generatedMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappingsUnsorted}get _originalMappingsUnsorted(){return this.__originalMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappingsUnsorted}_sortGeneratedMappings(){const t=this._generatedMappingsUnsorted;t.sort(he.compareByGeneratedPositionsDeflated),this.__generatedMappings=t}_sortOriginalMappings(){const t=this._originalMappingsUnsorted;t.sort(he.compareByOriginalPositions),this.__originalMappings=t}get sources(){const t=[];for(let n=0;na.push(c));for(let c=0;c= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");const i=[];let s=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",he.compareByOriginalPositions,zf.LEAST_UPPER_BOUND);if(s>=0){let o=this._originalMappings[s];if(t.column===void 0){const a=o.originalLine;for(;o&&o.originalLine===a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:he.getArg(o,"generatedLine",null),column:he.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}else{const a=o.originalColumn;for(;o&&o.originalLine===n&&o.originalColumn==a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:he.getArg(o,"generatedLine",null),column:he.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}}return i}destroy(){for(let t=0;t=0;n--)this.prepend(t[n]);else if(t[fs]||typeof t=="string")this.children.unshift(t);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+t);return this}walk(t){let n;for(let r=0,i=this.children.length;r0){for(n=[],r=0;rString.fromCharCode(e)),HL=on({name:"Whitespace",pattern:/ +/}),VL=on({name:"WhitespaceSkipped",pattern:/ +/,group:wt.SKIPPED}),Gf=on({name:"Newline",line_breaks:!0,start_chars_hint:[` +`,"\r"],pattern:/\n|\r\n?/}),A_=on({name:"StringLiteral",pattern:/[^ $;\r\n]+/,start_chars_hint:GL}),Hf=on({name:"StringLiteralDouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),Vf=on({name:"EscapedDollar",pattern:"$$"}),Kf=on({name:"MaybeFlag",pattern:/\$[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/}),qf=on({name:"NumberLiteral",pattern:/\$-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?\+?/}),T_=on({name:"HyperLinkText",pattern:/;[^;\r\n]*/,start_chars_hint:[";"]});function KL(e,t=""){return on({name:t||e,pattern:new RegExp(e.toLowerCase(),"i")})}const x_=Object.keys(Ga).map(e=>KL(`\\$(${e})`,e)),qL=[HL,Gf,...x_,Hf,A_,qf,Vf,T_,Kf],JL=new wt(qL,{skipValidations:!qn,ensureOptimizations:qn}),XL=new wt([VL,Gf,...x_,Hf,A_,qf,Vf,T_,Kf],{skipValidations:!qn,ensureOptimizations:qn});function Jf(e,t=!1){return t?XL.tokenize(e):JL.tokenize(e)}function R_(e,t,n,r,i,s,o,a){return{disablewrap:!1,measureonly:!1,measuredwidth:0,writefullwidth:void 0,x:0,y:0,iseven:!0,active:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},reset:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},width:e,height:t,char:[],color:[],bg:[],changed(){}}}function I_(e){e.active={...e.reset}}function O_(e,t){const n=t.y;function r(){++t.x;const a=t.active.rightedge??t.width-1;!t.disablewrap&&t.x>a&&(t.x=t.active.leftedge??0,++t.y),t.x>t.measuredwidth&&(t.measuredwidth=t.x)}function i(){return t.x>=(t.active.leftedge??0)&&t.x<=(t.active.rightedge??t.width-1)&&t.y>=(t.active.topedge??0)&&t.y<=(t.active.bottomedge??t.height-1)}function s(a){for(let c=0;ct.measuredwidth&&(t.measuredwidth=t.x+1);const o=t.active.leftedge??0;if(k(t.writefullwidth)&&(t.x>o||t.y===n)){const c=(t.active.rightedge??t.width-1)-t.x;if(c>0){I_(t);const l=String.fromCharCode(t.writefullwidth).repeat(c),u=t.x+t.y*t.width;eM(u,u+l.length,t.active.color,t.active.bg,t),QL(u,l,t)}}}function ZL(e,t,n){const r=Jf(e);r.tokens&&(O_(r.tokens,t),I_(t))}function YL(e,t,n){const r=Jf(e);if(!r.tokens)return;const i=R_(t,n,be.WHITE,be.BLACK);return i.measureonly=!0,O_(r.tokens,i),i.x>0&&++i.y,i}function QL(e,t,n){let r=0;const i=e+t.length;for(let s=e;s{this.MANY(()=>this.SUBRULE(this.line))}));ye(this,"line",this.RULED("line",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt)},{ALT:()=>this.CONSUME($s)}])}));ye(this,"stmt",this.RULED("stmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.short_commands)),this.MANY(()=>this.SUBRULE(this.commands))}}])}));ye(this,"inline",this.RULED("inline",()=>{this.SUBRULE(this.instmt)}));ye(this,"instmt",this.RULED("instmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}])}));ye(this,"stmt_label",this.RULED("stmt_label",()=>{this.CONSUME(am)}));ye(this,"stmt_stat",this.RULED("stmt_stat",()=>{this.CONSUME(Zl)}));ye(this,"stmt_text",this.RULED("stmt_text",()=>{this.OR([{ALT:()=>this.CONSUME(sm)}])}));ye(this,"stmt_comment",this.RULED("stmt_comment",()=>{this.CONSUME(om)}));ye(this,"stmt_hyperlink",this.RULED("stmt_hyperlink",()=>{this.CONSUME(cm),this.SUBRULE(this.words),this.CONSUME(lm)}));ye(this,"stmt_command",this.RULED("stmt_command",()=>{this.CONSUME(Ki),this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}));ye(this,"short_commands",this.RULED("short_commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)}])}));ye(this,"commands",this.RULED("commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.words)},{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)},{ALT:()=>this.SUBRULE(this.command_play)},{ALT:()=>this.SUBRULE(this.structured_cmd)}])}));ye(this,"structured_cmd",this.RULED("structured_cmd",()=>{this.OR([{ALT:()=>this.SUBRULE(this.command_debugger)},{ALT:()=>this.SUBRULE(this.command_if)},{ALT:()=>this.SUBRULE(this.command_while)},{ALT:()=>this.SUBRULE(this.command_repeat)},{ALT:()=>this.SUBRULE(this.command_waitfor)},{ALT:()=>this.SUBRULE(this.command_foreach)},{ALT:()=>this.SUBRULE(this.command_break)},{ALT:()=>this.SUBRULE(this.command_continue)}])}));ye(this,"short_go",this.RULED("short_go",()=>{this.CONSUME(ru),this.SUBRULE(this.words)}));ye(this,"short_try",this.RULED("short_try",()=>{this.CONSUME(Em),this.SUBRULE(this.words)}));ye(this,"command_debugger",this.RULED("command_debugger",()=>{this.CONSUME(Tm)}));ye(this,"command_if",this.RULED("command_if",()=>{this.CONSUME(iu),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_if_block))}));ye(this,"command_if_block",this.RULED("command_if_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(Oa),this.MANY(()=>this.SUBRULE(this.line)),this.MANY2({GATE:this.BACKTRACK(this.command_else_if),DEF:()=>this.SUBRULE(this.command_else_if)}),this.OPTION(()=>this.SUBRULE(this.command_else)),this.MANY3(()=>this.CONSUME3($s)),this.CONSUME4(Ki),this.CONSUME4(su)}}])}));ye(this,"command_block",this.RULED("command_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(Oa),this.MANY(()=>this.SUBRULE(this.line)),this.CONSUME(Ki),this.CONSUME(su)}}])}));ye(this,"command_fork",this.RULED("command_fork",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(Oa),this.MANY({GATE:this.BACKTRACK(this.line),DEF:()=>this.SUBRULE(this.line)})}}])}));ye(this,"command_else_if",this.RULED("command_else_if",()=>{this.CONSUME(Ki),this.CONSUME(ou),this.CONSUME(iu),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_fork))}));ye(this,"command_else",this.RULED("command_else",()=>{this.CONSUME(Ki),this.CONSUME(ou),this.OPTION(()=>this.SUBRULE(this.command_fork))}));ye(this,"command_while",this.RULED("command_while",()=>{this.CONSUME(xm),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_repeat",this.RULED("command_repeat",()=>{this.CONSUME(Rm),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_waitfor",this.RULED("command_waitfor",()=>{this.CONSUME(Im),this.SUBRULE(this.words)}));ye(this,"command_foreach",this.RULED("command_foreach",()=>{this.CONSUME(Om),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_break",this.RULED("command_break",()=>{this.CONSUME(Nm)}));ye(this,"command_continue",this.RULED("command_continue",()=>{this.CONSUME(Cm)}));ye(this,"command_play",this.RULED("command_play",()=>{this.CONSUME(Am)}));ye(this,"expr",this.RULED("expr",()=>{this.SUBRULE1(this.and_test),this.MANY(()=>{this.CONSUME(Yl),this.SUBRULE2(this.and_test)})}));ye(this,"and_test",this.RULED("and_test",()=>{this.SUBRULE1(this.not_test),this.MANY(()=>{this.CONSUME(eu),this.SUBRULE2(this.not_test)})}));ye(this,"not_test",this.RULED("not_test",()=>{this.OR([{ALT:()=>{this.CONSUME(Ql),this.SUBRULE1(this.not_test)}},{ALT:()=>this.SUBRULE2(this.comparison)}])}));ye(this,"comparison",this.RULED("comparison",()=>{this.SUBRULE1(this.arith_expr),this.MANY(()=>{this.SUBRULE(this.comp_op),this.SUBRULE2(this.arith_expr)})}));ye(this,"comp_op",this.RULED("comp_op",()=>{this.OR([{ALT:()=>this.CONSUME(hm)},{ALT:()=>this.CONSUME(dm)},{ALT:()=>this.CONSUME(pm)},{ALT:()=>this.CONSUME(mm)},{ALT:()=>this.CONSUME(gm)},{ALT:()=>this.CONSUME(ym)}])}));ye(this,"expr_value",this.RULED("expr_value",()=>{this.SUBRULE1(this.and_test_value),this.MANY(()=>{this.CONSUME(Yl),this.SUBRULE2(this.and_test_value)})}));ye(this,"and_test_value",this.RULED("and_test_value",()=>{this.SUBRULE1(this.not_test_value),this.MANY(()=>{this.CONSUME(eu),this.SUBRULE2(this.not_test_value)})}));ye(this,"not_test_value",this.RULED("not_test_value",()=>{this.OR([{ALT:()=>{this.CONSUME(Ql),this.SUBRULE1(this.not_test_value)}},{ALT:()=>this.SUBRULE2(this.arith_expr)}])}));ye(this,"arith_expr",this.RULED("arith_expr",()=>{this.SUBRULE1(this.term),this.MANY(()=>this.SUBRULE2(this.arith_expr_item))}));ye(this,"arith_expr_item",this.RULED("arith_expr_item",()=>{this.OR([{ALT:()=>this.CONSUME(tu)},{ALT:()=>this.CONSUME(nu)}]),this.SUBRULE(this.term)}));ye(this,"term",this.RULED("term",()=>{this.SUBRULE1(this.factor),this.MANY(()=>this.SUBRULE2(this.term_item))}));ye(this,"term_item",this.RULED("term_item",()=>{this.OR([{ALT:()=>this.CONSUME(bm)},{ALT:()=>this.CONSUME(ru)},{ALT:()=>this.CONSUME(wm)},{ALT:()=>this.CONSUME(vm)}]),this.SUBRULE(this.factor)}));ye(this,"factor",this.RULED("factor",()=>{this.OR1([{ALT:()=>{this.OR2([{ALT:()=>this.CONSUME(tu)},{ALT:()=>this.CONSUME(nu)}]),this.SUBRULE(this.factor)}},{ALT:()=>this.SUBRULE(this.power)}])}));ye(this,"power",this.RULED("power",()=>{this.SUBRULE(this.token),this.OPTION(()=>{this.CONSUME(_m),this.SUBRULE(this.factor)})}));ye(this,"words",this.RULED("words",()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.expr))}));ye(this,"token",this.RULED("token",()=>{this.OR([{ALT:()=>this.CONSUME(um)},{ALT:()=>this.CONSUME(zt)},{ALT:()=>this.CONSUME(fm)},{ALT:()=>{this.CONSUME(km),this.SUBRULE(this.expr),this.CONSUME(Sm)}}])}));this.performSelfAnalysis()}PEEK(n,r,...i){console.info(n,i.map(s=>[s.image,s.tokenType]),r)}RULED(n,r,i){const s=tM.some(o=>n.includes(o));return this.RULE(n,()=>{const a=(N_++).toString().padStart(3),c=s?"font-weight: bold;":"";if(C_&&!this.RECORDING_PHASE){const l=[this.LA(1),this.LA(2),this.LA(3)].map(u=>`[${u.tokenType.name} ${u.image.replaceAll(` +`,"\\n")}]`);console.info(`${a}%c> ${n} ${l.join(" ")}`,c)}r(),C_&&!this.RECORDING_PHASE&&console.info(`${a}%c< ${n} `,c),N_--},i)}}const hs=new nM;if(Hx){const e=hs.getGAstProductions(),t=Gx(e);console.info(t)}const rM=hs.getBaseCstVisitorConstructor();var se=(e=>(e[e.PROGRAM=0]="PROGRAM",e[e.API=1]="API",e[e.LINE=2]="LINE",e[e.MARK=3]="MARK",e[e.GOTO=4]="GOTO",e[e.COUNT=5]="COUNT",e[e.TEXT=6]="TEXT",e[e.LABEL=7]="LABEL",e[e.HYPERLINK=8]="HYPERLINK",e[e.STAT=9]="STAT",e[e.MOVE=10]="MOVE",e[e.COMMAND=11]="COMMAND",e[e.LITERAL=12]="LITERAL",e[e.IF=13]="IF",e[e.IF_CHECK=14]="IF_CHECK",e[e.IF_BLOCK=15]="IF_BLOCK",e[e.ELSE_IF=16]="ELSE_IF",e[e.ELSE=17]="ELSE",e[e.WHILE=18]="WHILE",e[e.BREAK=19]="BREAK",e[e.CONTINUE=20]="CONTINUE",e[e.REPEAT=21]="REPEAT",e[e.WAITFOR=22]="WAITFOR",e[e.FOREACH=23]="FOREACH",e[e.OR=24]="OR",e[e.AND=25]="AND",e[e.NOT=26]="NOT",e[e.COMPARE=27]="COMPARE",e[e.COMPARE_ITEM=28]="COMPARE_ITEM",e[e.OPERATOR=29]="OPERATOR",e[e.OPERATOR_ITEM=30]="OPERATOR_ITEM",e[e.EXPR=31]="EXPR",e))(se||{}),Oi=(e=>(e[e.IS_EQ=0]="IS_EQ",e[e.IS_NOT_EQ=1]="IS_NOT_EQ",e[e.IS_LESS_THAN=2]="IS_LESS_THAN",e[e.IS_GREATER_THAN=3]="IS_GREATER_THAN",e[e.IS_LESS_THAN_OR_EQ=4]="IS_LESS_THAN_OR_EQ",e[e.IS_GREATER_THAN_OR_EQ=5]="IS_GREATER_THAN_OR_EQ",e))(Oi||{}),sr=(e=>(e[e.EMPTY=0]="EMPTY",e[e.PLUS=1]="PLUS",e[e.MINUS=2]="MINUS",e[e.POWER=3]="POWER",e[e.MULTIPLY=4]="MULTIPLY",e[e.DIVIDE=5]="DIVIDE",e[e.MOD_DIVIDE=6]="MOD_DIVIDE",e[e.FLOOR_DIVIDE=7]="FLOOR_DIVIDE",e[e.UNI_PLUS=8]="UNI_PLUS",e[e.UNI_MINUS=9]="UNI_MINUS",e))(sr||{}),Oc=(e=>(e[e.NUMBER=0]="NUMBER",e[e.STRING=1]="STRING",e[e.TEMPLATE=2]="TEMPLATE",e))(Oc||{});function iM(e){return!!(e!=null&&e.tokenType)}function Cr(e,t){const[n]=e??[];return((n==null?void 0:n.image)??t).trimStart().replaceAll(/^"|"$/g,"")}class sM extends rM{constructor(){super();ye(this,"unique",0);qn&&this.validateVisitor()}getnodelocation(n){const r=Object.values(n).flat().filter(i=>!!i).map(i=>i&&iM(i)?{startLine:i.startLine,startColumn:i.startColumn,startOffset:i.startOffset,endLine:i.endLine,endColumn:i.endColumn,endOffset:i.endOffset}:i!=null&&i.location?{...i.location}:{startLine:0,startColumn:0,startOffset:0,endLine:0,endColumn:0,endOffset:0}).filter(i=>i.startLine!==0&&i.endLine!==0);return{startLine:Math.min(...r.map(i=>i.startLine??1)),startColumn:Math.min(...r.map(i=>i.startColumn??1)),startOffset:Math.min(...r.map(i=>i.startOffset??1)),endLine:Math.max(...r.map(i=>i.endLine??1)),endColumn:Math.max(...r.map(i=>i.endColumn??1)),endOffset:Math.max(...r.map(i=>i.endOffset??1))}}createcodenode(n,r){return[{...r,...this.getnodelocation(n),lineindex:0}]}createstringnode(n,r){return this.createcodenode(n,{type:12,literal:1,value:r})}createmarknode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:3,id:r,comment:i}))}creategotonode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:4,id:r,comment:i}))}createlinenode(n,r){return this.createcodenode(n,{type:2,stmts:r})}createapinode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:1,words:i,method:r}))}createlogicnode(n,r,i,s){return this.createlinenode(n,this.createcodenode(n,{type:14,skip:i,words:s,method:r}))}createcountnode(n){return this.createcodenode(n,{type:5,index:this.unique++})}go(n){return Array.isArray(n)?n.map(r=>this.visit(r)).flat():k(n)?[this.visit(n)].flat():[]}program(n){return this.unique=0,this.createcodenode(n,{type:0,lines:[this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:"restart"})),this.go(n.line)].flat()})}line(n){return n.stmt?this.go(n.stmt):[]}stmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.short_commands?[this.go(n.short_commands),this.go(n.commands)].flat():[]}inline(n){return this.go(n.instmt)}instmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.commands?this.go(n.commands):[]}stmt_label(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:Cr(n.token_label,":").slice(1).trim()}))}stmt_stat(n){return this.createlinenode(n,this.createcodenode(n,{type:9,value:Cr(n.token_stat,"@").slice(1)}))}stmt_text(n){return this.createlinenode(n,this.createcodenode(n,{type:6,value:Cr(n.token_text,"")}))}stmt_comment(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!1,name:Cr(n.token_comment,"'").slice(1).trim()}))}stmt_hyperlink(n){return this.createlinenode(n,this.createcodenode(n,{type:8,link:this.go(n.words),text:Cr(n.token_hyperlinktext,";").slice(1)}))}stmt_command(n){return n.commands?this.go(n.commands):[]}short_commands(n){return n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):[]}commands(n){return n.words?this.createlinenode(n,this.createcodenode(n,{type:11,words:this.go(n.words)})):n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):n.command_play?this.go(n.command_play):n.structured_cmd?this.go(n.structured_cmd):[]}structured_cmd(n){return n.command_if?this.go(n.command_if):n.command_while?this.go(n.command_while):n.command_repeat?this.go(n.command_repeat):n.command_waitfor?this.go(n.command_waitfor):n.command_foreach?this.go(n.command_foreach):n.command_break?this.go(n.command_break):n.command_continue?this.go(n.command_continue):[]}short_go(n){return n.token_divide?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!0,words:this.go(n.words)})):[]}short_try(n){return n.token_query?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!1,words:this.go(n.words)})):[]}command_if(n){const[r]=this.createlogicnode(n,"if","",this.go(n.words)),[i]=this.go(n.command_if_block)??[];return this.createcodenode(n,{type:13,check:r,block:i})}command_if_block(n){const r=ht(),i=ht();return this.createcodenode(n,{type:15,skip:r,done:i,lines:[this.go(n.inline),this.go(n.line),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"alt logic")].flat(),altlines:[this.go(n.command_else_if),this.go(n.command_else),this.createmarknode(n,i,"end of if")].flat()})}command_block(n){return[this.go(n.inline),this.go(n.line)].flat()}command_fork(n){return[this.go(n.inline),this.go(n.line)].flat()}command_else_if(n){const r=ht(),i=ht();return this.createcodenode(n,{type:16,done:i,lines:[this.createlogicnode(n,"if",r,this.go(n.words)),this.go(n.command_fork),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"skip")].flat()})}command_else(n){return this.createcodenode(n,{type:17,lines:this.go(n.command_fork)})}command_while(n){const r=ht(),i=ht();return this.createcodenode(n,{type:18,loop:r,done:i,lines:[this.createmarknode(n,r,"start of while"),this.createlogicnode(n,"if",i,this.go(n.words)),this.go(n.command_block),this.creategotonode(n,r,"loop of while"),this.createmarknode(n,i,"end of while")].flat()})}command_repeat(n){const r=ht(),i=ht(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:21,loop:r,done:i,lines:[this.createapinode(n,"repeatstart",o),this.createmarknode(n,r,"start of repeat"),this.createlogicnode(n,"repeat",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of repeat"),this.createmarknode(n,i,"end of repeat")].flat()})}command_foreach(n){const r=ht(),i=ht(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:23,loop:r,done:i,lines:[this.createapinode(n,"foreachstart",o),this.createmarknode(n,r,"start of foreach"),this.createlogicnode(n,"foreach",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of foreach"),this.createmarknode(n,i,"end of foreach")].flat()})}command_waitfor(n){return this.createcodenode(n,{type:22,words:this.go(n.words)})}command_break(n){return this.createcodenode(n,{type:19,goto:0})}command_continue(n){return this.createcodenode(n,{type:20,goto:0})}command_play(n){const r=Cr(n.token_command_play,""),i=r.replace("bgplay","").replace("play","").trim(),s=r.includes("bgplay");return this.createlinenode(n,this.createcodenode(n,{type:11,words:[this.createstringnode(n,s?"bgplay":"play"),this.createstringnode(n,i)].flat()}))}expr(n){return n.and_test.length===1?this.go(n.and_test):this.createcodenode(n,{type:24,items:this.go(n.and_test)})}and_test(n){return n.not_test.length===1?this.go(n.not_test):this.createcodenode(n,{type:25,items:this.go(n.not_test)})}not_test(n){return n.comparison?this.go(n.comparison):n.not_test?this.createcodenode(n,{type:26,items:this.go(n.not_test)}):[]}comparison(n){if(n.arith_expr.length===1)return this.go(n.arith_expr);const[r,i]=this.go(n.arith_expr),[s]=this.go(n.comp_op);return this.createcodenode(n,{type:27,lhs:r,compare:s,rhs:i})}comp_op(n){return n.token_iseq?this.createcodenode(n,{type:28,method:0}):n.token_isnoteq?this.createcodenode(n,{type:28,method:1}):n.token_islessthan?this.createcodenode(n,{type:28,method:2}):n.token_isgreaterthan?this.createcodenode(n,{type:28,method:3}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:4}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:5}):[]}expr_value(n){return n.and_test_value.length===1?this.go(n.and_test_value):this.createcodenode(n,{type:24,items:this.go(n.and_test_value)})}and_test_value(n){return n.not_test_value.length===1?this.go(n.not_test_value):this.createcodenode(n,{type:25,items:this.go(n.not_test_value)})}not_test_value(n){return n.arith_expr?this.go(n.arith_expr):n.not_test_value?this.createcodenode(n,{type:26,items:this.go(n.not_test_value)}):[]}arith_expr(n){const r=this.go(n.term);return n.arith_expr_item?this.createcodenode(n,{type:29,lhs:r[0],items:this.go(n.arith_expr_item)}):r}arith_expr_item(n){return this.createcodenode(n,{type:30,operator:n.token_plus?1:2,rhs:this.go(n.term)[0]})}term(n){return n.term_item?this.createcodenode(n,{type:29,lhs:this.go(n.factor)[0],items:this.go(n.term_item)}):this.go(n.factor)}term_item(n){let r=0;return n.token_multiply&&(r=4),n.token_divide&&(r=5),n.token_moddivide&&(r=6),n.token_floordivide&&(r=7),this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})}factor(n){if(n.power)return this.go(n.power);let r=0;return n.token_plus&&(r=8),n.token_minus&&(r=9),this.createcodenode(n,{type:29,lhs:void 0,items:this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})})}power(n){const r=this.go(n.token);return n.factor?this.createcodenode(n,{type:29,lhs:r[0],items:this.createcodenode(n,{type:30,operator:3,rhs:this.go(n.factor)[0]})}):r}words(n){return this.go(n.expr)}token(n){if(n.token_stringliteraldouble){const r=Cr(n.token_stringliteraldouble,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:2,value:r})}if(n.token_stringliteral){const r=Cr(n.token_stringliteral,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:1,value:r})}if(n.token_numberliteral){const r=parseFloat(Cr(n.token_numberliteral,"0"));return this.createcodenode(n,{type:12,literal:0,value:r})}return n.token_lparen?this.createcodenode(n,{type:31,words:this.go(n.expr)}):[]}}const oM=new sM,tn={labels:{},internal:0,lineindex:0,linelookup:{},isfirststat:!1},Nc="zss.js";function Ne(e,t){return new WL(e.startLine??1,e.startColumn??1,Nc,t)}function Xf(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Zf(e){return`'${Xf(e)}'`}function Cc(e){if(e.startsWith('"'))return Cc(e.replaceAll(/(^"|"$)/g,""));const t=Jf(e);return t.errors.length?e:`['${t.tokens.map(r=>r.tokenType===Kf?`', api.get('${Xf(r.image.substring(1))}'), '`:Xf(r.image)).join("")}'].join('')`}function Ni(e){return e.filter(t=>t!==void 0).map(Fe)}function L_(e){return Ne(e,"")}function aM(e,t){const n=[];return e.forEach(r=>{n.push(r,t)}),n.pop(),n}function mt(e,t,n){return Ne(e,[`api.${t}(`,...aM(n,", "),")"])}function cM(e){if(e.type===se.COMPARE&&e.compare.type===se.COMPARE_ITEM)switch(e.compare.method){case Oi.IS_EQ:return mt(e,"isEq",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_NOT_EQ:return mt(e,"isNotEq",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_LESS_THAN:return mt(e,"isLessThan",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_GREATER_THAN:return mt(e,"isGreaterThan",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_LESS_THAN_OR_EQ:return mt(e,"isLessThanOrEq",[Fe(e.lhs),Fe(e.rhs)]);case Oi.IS_GREATER_THAN_OR_EQ:return mt(e,"isGreaterThanOrEq",[Fe(e.lhs),Fe(e.rhs)])}return Ne(e,"")}function Ci(e,t,n){return e.prepend(`api.${t}(`),e.add([", ",Fe(n),")"])}function M_(e,t,n){return e.prepend(`api.${t}(`),e.add([Fe(n),")"])}function lM(e,t){if(e.type===se.OPERATOR_ITEM)switch(e.operator){case sr.PLUS:return Ci(t,"opPlus",e.rhs);case sr.MINUS:return Ci(t,"opMinus",e.rhs);case sr.POWER:return Ci(t,"opPower",e.rhs);case sr.MULTIPLY:return Ci(t,"opMultiply",e.rhs);case sr.DIVIDE:return Ci(t,"opDivide",e.rhs);case sr.MOD_DIVIDE:return Ci(t,"opModDivide",e.rhs);case sr.FLOOR_DIVIDE:return Ci(t,"opFloorDivide",e.rhs);case sr.UNI_PLUS:return M_(t,"opUniPlus",e.rhs);case sr.UNI_MINUS:return M_(t,"opUniMinus",e.rhs)}return Ne(e,"")}function uM(e){if(e.type===se.OPERATOR){const t=e.lhs?Fe(e.lhs):Ne(e,"");return e.items.forEach(n=>lM(n,t)),t}return Ne(e,"")}function Lc(e,t){return Ne(e,[mt(e,"jump",[`${t}`]),"; continue;"])}function Lr(e){return tn.linelookup[e??""]??-1}function Yf(e,t){tn.linelookup[e]=t}function Oo(e,t,n){for(let r=0;rn.add(Fe(r))),n}case se.WHILE:{const n=Lr(e.loop),r=Lr(e.done),i=Ne(e,"");return Oo(e.lines,se.IF_CHECK,e.done),e.lines.forEach(s=>{switch(s.type){case se.BREAK:s.goto=r;break;case se.CONTINUE:s.goto=n;break}i.add(Fe(s))}),i}case se.REPEAT:{const n=Lr(e.loop),r=Lr(e.done),i=Ne(e,"");return Oo(e.lines,se.IF_CHECK,e.done),e.lines.forEach(s=>{switch(s.type){case se.BREAK:s.goto=r;break;case se.CONTINUE:s.goto=n;break}i.add(Fe(s))}),i}case se.WAITFOR:{const n=Ne(e,"");return n.add([" if (!",mt(e,"if",Ni(e.words)),`) { api.i(${e.lineindex-1}); } `]),n}case se.FOREACH:{const n=Lr(e.loop),r=Lr(e.done),i=Ne(e,"");return Oo(e.lines,se.IF_CHECK,e.done),e.lines.forEach(s=>{switch(s.type){case se.BREAK:s.goto=r;break;case se.CONTINUE:s.goto=n;break}i.add(Fe(s))}),i}case se.BREAK:return Ne(e,[" ",Lc(e,e.goto),` `]);case se.CONTINUE:return Ne(e,[" ",Lc(e,e.goto),` -`]);case se.OR:return mt(e,"or",e.items.map(Fe));case se.AND:return mt(e,"and",e.items.map(Fe));case se.NOT:return mt(e,"not",e.items.map(Fe));case se.COMPARE:return aM(e);case se.OPERATOR:return lM(e);case se.EXPR:return mt(e,"expr",e.words.map(Fe));default:return console.error("",e.type,e),L_(e)}}function or(e){if(k(e))switch(e.type===se.LINE&&++tn.lineindex,e.lineindex=tn.lineindex,e.type){case se.PROGRAM:e.lines.forEach(or);break;case se.LINE:e.stmts.forEach(or);break;case se.MARK:Yf(e.id,e.lineindex);break;case se.IF:or(e.check),or(e.block);break;case se.IF_BLOCK:e.lines.forEach(or),e.altlines.forEach(or);break;case se.ELSE_IF:e.lines.forEach(or);break;case se.ELSE:case se.WHILE:case se.REPEAT:case se.FOREACH:e.lines.forEach(or);break;case se.MOVE:case se.COMMAND:case se.WAITFOR:case se.IF_CHECK:e.words.forEach(or);break}}function uM(e){return tn.labels={},tn.internal=1,tn.lineindex=0,tn.isfirststat=!0,or(e),{...Fe(e).toStringWithSourceMap({file:`${Nc}.map`}),...tn}}const Mc={HALT_AT_COUNT:256};function fM(e){return Ge(e)?e.length>0?1:0:e??0}function Nt(e){return`${e??""}`}function P_(e){return`${e}_chip`}function hM(e,t,n){var c,l;const r=P_(e),i=ps(r);let s;Ge(i.lb)||(i.lb=ys(Object.entries(n.labels??{})),i.lk="",i.mg=void 0,i.ec=1,i.lc=0,i.ys=0,i.ps=0,i.es=(((c=n.errors)==null?void 0:c.length)??0)!==0?1:0);function o(u,f){C.words=f,C.get=a.get;const d=gL(t,u);return k(d)?d(a,f):u!=="send"?o("send",[u,...f]):0}const a={halt(){xM(r)},id(){return e},senderid(u=e){return`vm:${u??e}`},set(u,f){const[d,h]=_L(t,a,u,f);if(d)return h},get(u){const[f,d]=yL(t,a,u);if(f)return d},bucket(u){const f=a.get("bucket");Ge(f)?f.push(u):a.set("bucket",[u])},tick(u){const f=ke(i.ps)?i.ps:0,d=f%u===0;if(i.ps=f+1,d===!1)return!1;if(a.shouldtick()===!1)return f_(t,a),!1;i.lc=0,i.ys=0,bL(t,a);try{const h=s==null?void 0:s.next();h!=null&&h.done&&(et("chip","crash","generator logic unexpectedly exited"),i.es=1)}catch(h){et("chip","crash",h.message),i.es=1}return f_(t,a),!0},isended(){return i.es===1},shouldtick(){return i.es===0||a.hm()!==0},shouldhalt(){return ke(i.lc)?++i.lc>Mc.HALT_AT_COUNT:!0},hm(){if(Ge(i.mg)&&Ge(i.lb)){const[,u]=i.mg;if(k(u))for(let f=0;fke(p)&&p>0)??0}}return 0},yield(){i.ys=1},jump(u){i.ec=u},sy(){return!!i.ys||a.shouldhalt()},emit(u,f,d){Ue.emit(u,a.senderid(),f,d)},send(u,f,d,h){Ue.emit(`${a.senderid(u)}:${f}`,e,d,h)},lock(u){i.lk=u},unlock(){i.lk=""},message(u){i.lk&&u.sender!==i.lk||(i.mg=[u.id,u.target,u.data,u.sender,u.player])},zap(u){if(Ge(i.lb))for(let f=0;fm>0);p>=0&&(h[p]*=-1)}}},restore(u){if(Ge(i.lb))for(let f=0;fh.fileName===Nc);return{line:(d==null?void 0:d.lineNumber)??0,column:(d==null?void 0:d.columnNumber)??0}},text(u){return o("text",[u])},stat(...u){return o("stat",u)},hyperlink(...u){return o("hyperlink",u)},command(...u){if(u.length===0)return 0;const[f,...d]=u;return o(Nt(f),d)},if(...u){const[f,d]=ne(u,0,[q.ANY]),h=fM(f);return h&&d0,m=i[d];return p&&Ge(m)&&a.command(...m),p?1:0},foreachstart(u,...f){const[d,h,p,m]=ne(f,0,[q.STRING,q.NUMBER,q.NUMBER,q.MAYBE_NUMBER]);let b=Math.min(h,p),_=Math.max(h,p);const w=(m??0)||1;if(w<0){const v=b;b=_,_=v}return a.set(d,b-w),0},foreach(u,...f){const[d,h,p,m,b]=ne(f,0,[q.STRING,q.NUMBER,q.NUMBER,q.MAYBE_NUMBER]);let _=Math.min(h,p),w=Math.max(h,p);const v=(m??0)||1;if(v<0){const I=_;_=w,w=I}let S=a.get(d);!ke(S)||S<_||S>w?S=_:S+=v;const L=S<=w?1:0;return L&&(a.set(d,S),bh?1:0},isLessThanOrEq(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d<=h?1:0},isGreaterThanOrEq(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d>=h?1:0},opPlus(u,f){const[d]=ne([u],0,[q.ANY]),[h]=ne([f],0,[q.ANY]);return d+h},opMinus(u,f){const[d]=ne([u],0,[q.ANY]),[h]=ne([f],0,[q.ANY]);return d-h},opPower(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return Math.pow(d,h)},opMultiply(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d*h},opDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d/h},opModDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d%h},opFloorDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return Math.floor(d/h)},opUniPlus(u){const[f]=ne([u],0,[q.NUMBER]);return+f},opUniMinus(u){const[f]=ne([u],0,[q.NUMBER]);return-f}};return s=(l=n.code)==null?void 0:l.call(n,a),a}function Uc(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var D_={exports:{}};/*! +`]);case se.OR:return mt(e,"or",e.items.map(Fe));case se.AND:return mt(e,"and",e.items.map(Fe));case se.NOT:return mt(e,"not",e.items.map(Fe));case se.COMPARE:return cM(e);case se.OPERATOR:return uM(e);case se.EXPR:return mt(e,"expr",e.words.map(Fe));default:return console.error("",e.type,e),L_(e)}}function or(e){if(k(e))switch(e.type===se.LINE&&++tn.lineindex,e.lineindex=tn.lineindex,e.type){case se.PROGRAM:e.lines.forEach(or);break;case se.LINE:e.stmts.forEach(or);break;case se.MARK:Yf(e.id,e.lineindex);break;case se.IF:or(e.check),or(e.block);break;case se.IF_BLOCK:e.lines.forEach(or),e.altlines.forEach(or);break;case se.ELSE_IF:e.lines.forEach(or);break;case se.ELSE:case se.WHILE:case se.REPEAT:case se.FOREACH:e.lines.forEach(or);break;case se.MOVE:case se.COMMAND:case se.WAITFOR:case se.IF_CHECK:e.words.forEach(or);break}}function fM(e){return tn.labels={},tn.internal=1,tn.lineindex=0,tn.isfirststat=!0,or(e),{...Fe(e).toStringWithSourceMap({file:`${Nc}.map`}),...tn}}const Mc={HALT_AT_COUNT:256};function hM(e){return Ge(e)?e.length>0?1:0:e??0}function Nt(e){return`${e??""}`}function P_(e){return`${e}_chip`}function dM(e,t,n){var c,l;const r=P_(e),i=ps(r);let s;Ge(i.lb)||(i.lb=ys(Object.entries(n.labels??{})),i.lk="",i.mg=void 0,i.ec=1,i.lc=0,i.ys=0,i.ps=0,i.es=(((c=n.errors)==null?void 0:c.length)??0)!==0?1:0);function o(u,f){C.words=f,C.get=a.get;const d=yL(t,u);return k(d)?d(a,f):u!=="send"?o("send",[u,...f]):0}const a={halt(){RM(r)},id(){return e},senderid(u=e){return`vm:${u??e}`},set(u,f){const[d,h]=bL(t,a,u,f);if(d)return h},get(u){const[f,d]=_L(t,a,u);if(f)return d},bucket(u){const f=a.get("bucket");Ge(f)?f.push(u):a.set("bucket",[u])},tick(u){const f=ke(i.ps)?i.ps:0,d=f%u===0;if(i.ps=f+1,d===!1)return!1;if(a.shouldtick()===!1)return f_(t,a),!1;i.lc=0,i.ys=0,wL(t,a);try{const h=s==null?void 0:s.next();h!=null&&h.done&&(et("chip","crash","generator logic unexpectedly exited"),i.es=1)}catch(h){et("chip","crash",h.message),i.es=1}return f_(t,a),!0},isended(){return i.es===1},shouldtick(){return i.es===0||a.hm()!==0},shouldhalt(){return ke(i.lc)?++i.lc>Mc.HALT_AT_COUNT:!0},hm(){if(Ge(i.mg)&&Ge(i.lb)){const[,u]=i.mg;if(k(u))for(let f=0;fke(p)&&p>0)??0}}return 0},yield(){i.ys=1},jump(u){i.ec=u},sy(){return!!i.ys||a.shouldhalt()},emit(u,f,d){Ue.emit(u,a.senderid(),f,d)},send(u,f,d,h){Ue.emit(`${a.senderid(u)}:${f}`,e,d,h)},lock(u){i.lk=u},unlock(){i.lk=""},message(u){i.lk&&u.sender!==i.lk||(i.mg=[u.id,u.target,u.data,u.sender,u.player])},zap(u){if(Ge(i.lb))for(let f=0;fm>0);p>=0&&(h[p]*=-1)}}},restore(u){if(Ge(i.lb))for(let f=0;fh.fileName===Nc);return{line:(d==null?void 0:d.lineNumber)??0,column:(d==null?void 0:d.columnNumber)??0}},text(u){return o("text",[u])},stat(...u){return o("stat",u)},hyperlink(...u){return o("hyperlink",u)},command(...u){if(u.length===0)return 0;const[f,...d]=u;return o(Nt(f),d)},if(...u){const[f,d]=ne(u,0,[q.ANY]),h=hM(f);return h&&d0,m=i[d];return p&&Ge(m)&&a.command(...m),p?1:0},foreachstart(u,...f){const[d,h,p,m]=ne(f,0,[q.STRING,q.NUMBER,q.NUMBER,q.MAYBE_NUMBER]);let b=Math.min(h,p),_=Math.max(h,p);const w=(m??0)||1;if(w<0){const v=b;b=_,_=v}return a.set(d,b-w),0},foreach(u,...f){const[d,h,p,m,b]=ne(f,0,[q.STRING,q.NUMBER,q.NUMBER,q.MAYBE_NUMBER]);let _=Math.min(h,p),w=Math.max(h,p);const v=(m??0)||1;if(v<0){const I=_;_=w,w=I}let S=a.get(d);!ke(S)||S<_||S>w?S=_:S+=v;const L=S<=w?1:0;return L&&(a.set(d,S),bh?1:0},isLessThanOrEq(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d<=h?1:0},isGreaterThanOrEq(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d>=h?1:0},opPlus(u,f){const[d]=ne([u],0,[q.ANY]),[h]=ne([f],0,[q.ANY]);return d+h},opMinus(u,f){const[d]=ne([u],0,[q.ANY]),[h]=ne([f],0,[q.ANY]);return d-h},opPower(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return Math.pow(d,h)},opMultiply(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d*h},opDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d/h},opModDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d%h},opFloorDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return Math.floor(d/h)},opUniPlus(u){const[f]=ne([u],0,[q.NUMBER]);return+f},opUniMinus(u){const[f]=ne([u],0,[q.NUMBER]);return-f}};return s=(l=n.code)==null?void 0:l.call(n,a),a}function Uc(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var D_={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files @@ -199,10 +199,10 @@ Make sure that all grammar rule definitions are done before 'performSelfAnalysis JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/main/LICENSE */(function(e,t){(function(n){e.exports=n()})(function(){return function n(r,i,s){function o(l,u){if(!i[l]){if(!r[l]){var f=typeof Uc=="function"&&Uc;if(!u&&f)return f(l,!0);if(a)return a(l,!0);var d=new Error("Cannot find module '"+l+"'");throw d.code="MODULE_NOT_FOUND",d}var h=i[l]={exports:{}};r[l][0].call(h.exports,function(p){var m=r[l][1][p];return o(m||p)},h,h.exports,n,r,i,s)}return i[l].exports}for(var a=typeof Uc=="function"&&Uc,c=0;c>2,h=(3&l)<<4|u>>4,p=1>6:64,m=2>4,u=(15&d)<<4|(h=a.indexOf(c.charAt(m++)))>>2,f=(3&h)<<6|(p=a.indexOf(c.charAt(m++))),w[b++]=l,h!==64&&(w[b++]=u),p!==64&&(w[b++]=f);return w}},{"./support":30,"./utils":32}],2:[function(n,r,i){var s=n("./external"),o=n("./stream/DataWorker"),a=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function l(u,f,d,h,p){this.compressedSize=u,this.uncompressedSize=f,this.crc32=d,this.compression=h,this.compressedContent=p}l.prototype={getContentWorker:function(){var u=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),f=this;return u.on("end",function(){if(this.streamInfo.data_length!==f.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},l.createWorkerFrom=function(u,f,d){return u.pipe(new a).pipe(new c("uncompressedSize")).pipe(f.compressWorker(d)).pipe(new c("compressedSize")).withStreamInfo("compression",f)},r.exports=l},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,i){var s=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,i){var s=n("./utils"),o=function(){for(var a,c=[],l=0;l<256;l++){a=l;for(var u=0;u<8;u++)a=1&a?3988292384^a>>>1:a>>>1;c[l]=a}return c}();r.exports=function(a,c){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(l,u,f,d){var h=o,p=d+f;l^=-1;for(var m=d;m>>8^h[255&(l^u[m])];return-1^l}(0|c,a,a.length,0):function(l,u,f,d){var h=o,p=d+f;l^=-1;for(var m=d;m>>8^h[255&(l^u.charCodeAt(m))];return-1^l}(0|c,a,a.length,0):0}},{"./utils":32}],5:[function(n,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,r,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),a=n("./utils"),c=n("./stream/GenericWorker"),l=s?"uint8array":"array";function u(f,d){c.call(this,"FlateWorker/"+f),this._pako=null,this._pakoAction=f,this._pakoOptions=d,this.meta={}}i.magic="\b\0",a.inherits(u,c),u.prototype.processChunk=function(f){this.meta=f.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(l,f.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var f=this;this._pako.onData=function(d){f.push({data:d,meta:f.meta})}},i.compressWorker=function(f){return new u("Deflate",f)},i.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(h,p){var m,b="";for(m=0;m>>=8;return b}function o(h,p,m,b,_,w){var v,S,L=h.file,I=h.compression,T=w!==l.utf8encode,M=a.transformTo("string",w(L.name)),x=a.transformTo("string",l.utf8encode(L.name)),V=L.comment,oe=a.transformTo("string",w(V)),O=a.transformTo("string",l.utf8encode(V)),E=x.length!==L.name.length,g=O.length!==V.length,N="",W="",B="",Z=L.dir,H=L.date,Y={crc32:0,compressedSize:0,uncompressedSize:0};p&&!m||(Y.crc32=h.crc32,Y.compressedSize=h.compressedSize,Y.uncompressedSize=h.uncompressedSize);var $=0;p&&($|=8),T||!E&&!g||($|=2048);var F=0,ue=0;Z&&(F|=16),_==="UNIX"?(ue=798,F|=function(ee,Se){var je=ee;return ee||(je=Se?16893:33204),(65535&je)<<16}(L.unixPermissions,Z)):(ue=20,F|=function(ee){return 63&(ee||0)}(L.dosPermissions)),v=H.getUTCHours(),v<<=6,v|=H.getUTCMinutes(),v<<=5,v|=H.getUTCSeconds()/2,S=H.getUTCFullYear()-1980,S<<=4,S|=H.getUTCMonth()+1,S<<=5,S|=H.getUTCDate(),E&&(W=s(1,1)+s(u(M),4)+x,N+="up"+s(W.length,2)+W),g&&(B=s(1,1)+s(u(oe),4)+O,N+="uc"+s(B.length,2)+B);var Q="";return Q+=` -\0`,Q+=s($,2),Q+=I.magic,Q+=s(v,2),Q+=s(S,2),Q+=s(Y.crc32,4),Q+=s(Y.compressedSize,4),Q+=s(Y.uncompressedSize,4),Q+=s(M.length,2),Q+=s(N.length,2),{fileRecord:f.LOCAL_FILE_HEADER+Q+M+N,dirRecord:f.CENTRAL_FILE_HEADER+s(ue,2)+Q+s(oe.length,2)+"\0\0\0\0"+s(F,4)+s(b,4)+M+N+oe}}var a=n("../utils"),c=n("../stream/GenericWorker"),l=n("../utf8"),u=n("../crc32"),f=n("../signature");function d(h,p,m,b){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=p,this.zipPlatform=m,this.encodeFileName=b,this.streamFiles=h,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(d,c),d.prototype.push=function(h){var p=h.meta.percent||0,m=this.entriesCount,b=this._sources.length;this.accumulate?this.contentBuffer.push(h):(this.bytesWritten+=h.data.length,c.prototype.push.call(this,{data:h.data,meta:{currentFile:this.currentFile,percent:m?(p+100*(m-b-1))/m:100}}))},d.prototype.openedSource=function(h){this.currentSourceOffset=this.bytesWritten,this.currentFile=h.file.name;var p=this.streamFiles&&!h.file.dir;if(p){var m=o(h,p,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:m.fileRecord,meta:{percent:0}})}else this.accumulate=!0},d.prototype.closedSource=function(h){this.accumulate=!1;var p=this.streamFiles&&!h.file.dir,m=o(h,p,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(m.dirRecord),p)this.push({data:function(b){return f.DATA_DESCRIPTOR+s(b.crc32,4)+s(b.compressedSize,4)+s(b.uncompressedSize,4)}(h),meta:{percent:100}});else for(this.push({data:m.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},d.prototype.flush=function(){for(var h=this.bytesWritten,p=0;p=this.index;c--)l=(l<<8)+this.byteAt(c);return this.index+=a,l},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},r.exports=o},{"../utils":32}],19:[function(n,r,i){var s=n("./Uint8ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,i){var s=n("./DataReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,r,i){var s=n("./ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,i){var s=n("../utils"),o=n("../support"),a=n("./ArrayReader"),c=n("./StringReader"),l=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(f){var d=s.getTypeOf(f);return s.checkSupport(d),d!=="string"||o.uint8array?d==="nodebuffer"?new l(f):o.uint8array?new u(s.transformTo("uint8array",f)):new a(s.transformTo("array",f)):new c(f)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,i){var s=n("./GenericWorker"),o=n("../utils");function a(c){s.call(this,"ConvertWorker to "+c),this.destType=c}o.inherits(a,s),a.prototype.processChunk=function(c){this.push({data:o.transformTo(this.destType,c.data),meta:c.meta})},r.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,i){var s=n("./GenericWorker"),o=n("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(a,s),a.prototype.processChunk=function(c){this.streamInfo.crc32=o(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}s.inherits(a,o),a.prototype.processChunk=function(c){if(c){var l=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=l+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataWorker");var l=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){l.dataIsReady=!0,l.data=u,l.max=u&&u.length||0,l.type=s.getTypeOf(u),l.isPaused||l._tickAndRepeat()},function(u){l.error(u)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,l=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,l);break;case"uint8array":c=this.data.subarray(this.index,l);break;case"array":case"nodebuffer":c=this.data.slice(this.index,l)}return this.index=l,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var c=0;c "+o:o}},r.exports=s},{}],29:[function(n,r,i){var s=n("../utils"),o=n("./ConvertWorker"),a=n("./GenericWorker"),c=n("../base64"),l=n("../support"),u=n("../external"),f=null;if(l.nodestream)try{f=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function d(p,m){return new u.Promise(function(b,_){var w=[],v=p._internalType,S=p._outputType,L=p._mimeType;p.on("data",function(I,T){w.push(I),m&&m(T)}).on("error",function(I){w=[],_(I)}).on("end",function(){try{var I=function(T,M,x){switch(T){case"blob":return s.newBlob(s.transformTo("arraybuffer",M),x);case"base64":return c.encode(M);default:return s.transformTo(T,M)}}(S,function(T,M){var x,V=0,oe=null,O=0;for(x=0;x"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,i){for(var s=n("./utils"),o=n("./support"),a=n("./nodejsUtils"),c=n("./stream/GenericWorker"),l=new Array(256),u=0;u<256;u++)l[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;l[254]=l[254]=1;function f(){c.call(this,"utf-8 decode"),this.leftOver=null}function d(){c.call(this,"utf-8 encode")}i.utf8encode=function(h){return o.nodebuffer?a.newBufferFrom(h,"utf-8"):function(p){var m,b,_,w,v,S=p.length,L=0;for(w=0;w>>6:(b<65536?m[v++]=224|b>>>12:(m[v++]=240|b>>>18,m[v++]=128|b>>>12&63),m[v++]=128|b>>>6&63),m[v++]=128|63&b);return m}(h)},i.utf8decode=function(h){return o.nodebuffer?s.transformTo("nodebuffer",h).toString("utf-8"):function(p){var m,b,_,w,v=p.length,S=new Array(2*v);for(m=b=0;m>10&1023,S[b++]=56320|1023&_)}return S.length!==b&&(S.subarray?S=S.subarray(0,b):S.length=b),s.applyFromCharCode(S)}(h=s.transformTo(o.uint8array?"uint8array":"array",h))},s.inherits(f,c),f.prototype.processChunk=function(h){var p=s.transformTo(o.uint8array?"uint8array":"array",h.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var m=p;(p=new Uint8Array(m.length+this.leftOver.length)).set(this.leftOver,0),p.set(m,this.leftOver.length)}else p=this.leftOver.concat(p);this.leftOver=null}var b=function(w,v){var S;for((v=v||w.length)>w.length&&(v=w.length),S=v-1;0<=S&&(192&w[S])==128;)S--;return S<0||S===0?v:S+l[w[S]]>v?S:v}(p),_=p;b!==p.length&&(o.uint8array?(_=p.subarray(0,b),this.leftOver=p.subarray(b,p.length)):(_=p.slice(0,b),this.leftOver=p.slice(b,p.length))),this.push({data:i.utf8decode(_),meta:h.meta})},f.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=f,s.inherits(d,c),d.prototype.processChunk=function(h){this.push({data:i.utf8encode(h.data),meta:h.meta})},i.Utf8EncodeWorker=d},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,i){var s=n("./support"),o=n("./base64"),a=n("./nodejsUtils"),c=n("./external");function l(m){return m}function u(m,b){for(var _=0;_>8;this.dir=!!(16&this.externalFileAttributes),h==0&&(this.dosPermissions=63&this.externalFileAttributes),h==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var h=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=h.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=h.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=h.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=h.readInt(4))}},readExtraFields:function(h){var p,m,b,_=h.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});h.index+4<_;)p=h.readInt(2),m=h.readInt(2),b=h.readData(m),this.extraFields[p]={id:p,length:m,value:b};h.setIndex(_)},handleUTF8:function(){var h=f.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=l.utf8decode(this.fileName),this.fileCommentStr=l.utf8decode(this.fileComment);else{var p=this.findExtraFieldUnicodePath();if(p!==null)this.fileNameStr=p;else{var m=o.transformTo(h,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(m)}var b=this.findExtraFieldUnicodeComment();if(b!==null)this.fileCommentStr=b;else{var _=o.transformTo(h,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(_)}}},findExtraFieldUnicodePath:function(){var h=this.extraFields[28789];if(h){var p=s(h.value);return p.readInt(1)!==1||c(this.fileName)!==p.readInt(4)?null:l.utf8decode(p.readData(h.length-5))}return null},findExtraFieldUnicodeComment:function(){var h=this.extraFields[25461];if(h){var p=s(h.value);return p.readInt(1)!==1||c(this.fileComment)!==p.readInt(4)?null:l.utf8decode(p.readData(h.length-5))}return null}},r.exports=d},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,i){function s(p,m,b){this.name=p,this.dir=b.dir,this.date=b.date,this.comment=b.comment,this.unixPermissions=b.unixPermissions,this.dosPermissions=b.dosPermissions,this._data=m,this._dataBinary=b.binary,this.options={compression:b.compression,compressionOptions:b.compressionOptions}}var o=n("./stream/StreamHelper"),a=n("./stream/DataWorker"),c=n("./utf8"),l=n("./compressedObject"),u=n("./stream/GenericWorker");s.prototype={internalStream:function(p){var m=null,b="string";try{if(!p)throw new Error("No output type specified.");var _=(b=p.toLowerCase())==="string"||b==="text";b!=="binarystring"&&b!=="text"||(b="string"),m=this._decompressWorker();var w=!this._dataBinary;w&&!_&&(m=m.pipe(new c.Utf8EncodeWorker)),!w&&_&&(m=m.pipe(new c.Utf8DecodeWorker))}catch(v){(m=new u("error")).error(v)}return new o(m,b,"")},async:function(p,m){return this.internalStream(p).accumulate(m)},nodeStream:function(p,m){return this.internalStream(p||"nodebuffer").toNodejsStream(m)},_compressWorker:function(p,m){if(this._data instanceof l&&this._data.compression.magic===p.magic)return this._data.getCompressedWorker();var b=this._decompressWorker();return this._dataBinary||(b=b.pipe(new c.Utf8EncodeWorker)),l.createWorkerFrom(b,p,m)},_decompressWorker:function(){return this._data instanceof l?this._data.getContentWorker():this._data instanceof u?this._data:new a(this._data)}};for(var f=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],d=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},h=0;h>>6:(h<65536?d[b++]=224|h>>>12:(d[b++]=240|h>>>18,d[b++]=128|h>>>12&63),d[b++]=128|h>>>6&63),d[b++]=128|63&h);return d},i.buf2binstring=function(f){return u(f,f.length)},i.binstring2buf=function(f){for(var d=new s.Buf8(f.length),h=0,p=d.length;h>10&1023,w[p++]=56320|1023&m)}return u(w,p)},i.utf8border=function(f,d){var h;for((d=d||f.length)>f.length&&(d=f.length),h=d-1;0<=h&&(192&f[h])==128;)h--;return h<0||h===0?d:h+c[f[h]]>d?h:d}},{"./common":41}],43:[function(n,r,i){r.exports=function(s,o,a,c){for(var l=65535&s|0,u=s>>>16&65535|0,f=0;a!==0;){for(a-=f=2e3>>1:o>>>1;a[c]=o}return a}();r.exports=function(o,a,c,l){var u=s,f=l+c;o^=-1;for(var d=l;d>>8^u[255&(o^a[d])];return-1^o}},{}],46:[function(n,r,i){var s,o=n("../utils/common"),a=n("./trees"),c=n("./adler32"),l=n("./crc32"),u=n("./messages"),f=0,d=4,h=0,p=-2,m=-1,b=4,_=2,w=8,v=9,S=286,L=30,I=19,T=2*S+1,M=15,x=3,V=258,oe=V+x+1,O=42,E=113,g=1,N=2,W=3,B=4;function Z(y,K){return y.msg=u[K],K}function H(y){return(y<<1)-(4y.avail_out&&(G=y.avail_out),G!==0&&(o.arraySet(y.output,K.pending_buf,K.pending_out,G,y.next_out),y.next_out+=G,K.pending_out+=G,y.total_out+=G,y.avail_out-=G,K.pending-=G,K.pending===0&&(K.pending_out=0))}function F(y,K){a._tr_flush_block(y,0<=y.block_start?y.block_start:-1,y.strstart-y.block_start,K),y.block_start=y.strstart,$(y.strm)}function ue(y,K){y.pending_buf[y.pending++]=K}function Q(y,K){y.pending_buf[y.pending++]=K>>>8&255,y.pending_buf[y.pending++]=255&K}function ee(y,K){var G,R,A=y.max_chain_length,D=y.strstart,J=y.prev_length,X=y.nice_match,z=y.strstart>y.w_size-oe?y.strstart-(y.w_size-oe):0,te=y.window,le=y.w_mask,re=y.prev,de=y.strstart+V,Ze=te[D+J-1],Me=te[D+J];y.prev_length>=y.good_match&&(A>>=2),X>y.lookahead&&(X=y.lookahead);do if(te[(G=K)+J]===Me&&te[G+J-1]===Ze&&te[G]===te[D]&&te[++G]===te[D+1]){D+=2,G++;do;while(te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&Dz&&--A!=0);return J<=y.lookahead?J:y.lookahead}function Se(y){var K,G,R,A,D,J,X,z,te,le,re=y.w_size;do{if(A=y.window_size-y.lookahead-y.strstart,y.strstart>=re+(re-oe)){for(o.arraySet(y.window,y.window,re,re,0),y.match_start-=re,y.strstart-=re,y.block_start-=re,K=G=y.hash_size;R=y.head[--K],y.head[K]=re<=R?R-re:0,--G;);for(K=G=re;R=y.prev[--K],y.prev[K]=re<=R?R-re:0,--G;);A+=re}if(y.strm.avail_in===0)break;if(J=y.strm,X=y.window,z=y.strstart+y.lookahead,te=A,le=void 0,le=J.avail_in,te=x)for(D=y.strstart-y.insert,y.ins_h=y.window[D],y.ins_h=(y.ins_h<=x&&(y.ins_h=(y.ins_h<=x)if(R=a._tr_tally(y,y.strstart-y.match_start,y.match_length-x),y.lookahead-=y.match_length,y.match_length<=y.max_lazy_match&&y.lookahead>=x){for(y.match_length--;y.strstart++,y.ins_h=(y.ins_h<=x&&(y.ins_h=(y.ins_h<=x&&y.match_length<=y.prev_length){for(A=y.strstart+y.lookahead-x,R=a._tr_tally(y,y.strstart-1-y.prev_match,y.prev_length-x),y.lookahead-=y.prev_length-1,y.prev_length-=2;++y.strstart<=A&&(y.ins_h=(y.ins_h<y.pending_buf_size-5&&(G=y.pending_buf_size-5);;){if(y.lookahead<=1){if(Se(y),y.lookahead===0&&K===f)return g;if(y.lookahead===0)break}y.strstart+=y.lookahead,y.lookahead=0;var R=y.block_start+G;if((y.strstart===0||y.strstart>=R)&&(y.lookahead=y.strstart-R,y.strstart=R,F(y,!1),y.strm.avail_out===0)||y.strstart-y.block_start>=y.w_size-oe&&(F(y,!1),y.strm.avail_out===0))return g}return y.insert=0,K===d?(F(y,!0),y.strm.avail_out===0?W:B):(y.strstart>y.block_start&&(F(y,!1),y.strm.avail_out),g)}),new _e(4,4,8,4,je),new _e(4,5,16,8,je),new _e(4,6,32,32,je),new _e(4,4,16,16,we),new _e(8,16,32,32,we),new _e(8,16,128,128,we),new _e(8,32,128,256,we),new _e(32,128,258,1024,we),new _e(32,258,258,4096,we)],i.deflateInit=function(y,K){return St(y,K,w,15,8,0)},i.deflateInit2=St,i.deflateReset=gt,i.deflateResetKeep=$e,i.deflateSetHeader=function(y,K){return y&&y.state?y.state.wrap!==2?p:(y.state.gzhead=K,h):p},i.deflate=function(y,K){var G,R,A,D;if(!y||!y.state||5>8&255),ue(R,R.gzhead.time>>16&255),ue(R,R.gzhead.time>>24&255),ue(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),ue(R,255&R.gzhead.os),R.gzhead.extra&&R.gzhead.extra.length&&(ue(R,255&R.gzhead.extra.length),ue(R,R.gzhead.extra.length>>8&255)),R.gzhead.hcrc&&(y.adler=l(y.adler,R.pending_buf,R.pending,0)),R.gzindex=0,R.status=69):(ue(R,0),ue(R,0),ue(R,0),ue(R,0),ue(R,0),ue(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),ue(R,3),R.status=E);else{var J=w+(R.w_bits-8<<4)<<8;J|=(2<=R.strategy||R.level<2?0:R.level<6?1:R.level===6?2:3)<<6,R.strstart!==0&&(J|=32),J+=31-J%31,R.status=E,Q(R,J),R.strstart!==0&&(Q(R,y.adler>>>16),Q(R,65535&y.adler)),y.adler=1}if(R.status===69)if(R.gzhead.extra){for(A=R.pending;R.gzindex<(65535&R.gzhead.extra.length)&&(R.pending!==R.pending_buf_size||(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending!==R.pending_buf_size));)ue(R,255&R.gzhead.extra[R.gzindex]),R.gzindex++;R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),R.gzindex===R.gzhead.extra.length&&(R.gzindex=0,R.status=73)}else R.status=73;if(R.status===73)if(R.gzhead.name){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindexA&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),D===0&&(R.gzindex=0,R.status=91)}else R.status=91;if(R.status===91)if(R.gzhead.comment){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindexA&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),D===0&&(R.status=103)}else R.status=103;if(R.status===103&&(R.gzhead.hcrc?(R.pending+2>R.pending_buf_size&&$(y),R.pending+2<=R.pending_buf_size&&(ue(R,255&y.adler),ue(R,y.adler>>8&255),y.adler=0,R.status=E)):R.status=E),R.pending!==0){if($(y),y.avail_out===0)return R.last_flush=-1,h}else if(y.avail_in===0&&H(K)<=H(G)&&K!==d)return Z(y,-5);if(R.status===666&&y.avail_in!==0)return Z(y,-5);if(y.avail_in!==0||R.lookahead!==0||K!==f&&R.status!==666){var X=R.strategy===2?function(z,te){for(var le;;){if(z.lookahead===0&&(Se(z),z.lookahead===0)){if(te===f)return g;break}if(z.match_length=0,le=a._tr_tally(z,0,z.window[z.strstart]),z.lookahead--,z.strstart++,le&&(F(z,!1),z.strm.avail_out===0))return g}return z.insert=0,te===d?(F(z,!0),z.strm.avail_out===0?W:B):z.last_lit&&(F(z,!1),z.strm.avail_out===0)?g:N}(R,K):R.strategy===3?function(z,te){for(var le,re,de,Ze,Me=z.window;;){if(z.lookahead<=V){if(Se(z),z.lookahead<=V&&te===f)return g;if(z.lookahead===0)break}if(z.match_length=0,z.lookahead>=x&&0z.lookahead&&(z.match_length=z.lookahead)}if(z.match_length>=x?(le=a._tr_tally(z,1,z.match_length-x),z.lookahead-=z.match_length,z.strstart+=z.match_length,z.match_length=0):(le=a._tr_tally(z,0,z.window[z.strstart]),z.lookahead--,z.strstart++),le&&(F(z,!1),z.strm.avail_out===0))return g}return z.insert=0,te===d?(F(z,!0),z.strm.avail_out===0?W:B):z.last_lit&&(F(z,!1),z.strm.avail_out===0)?g:N}(R,K):s[R.level].func(R,K);if(X!==W&&X!==B||(R.status=666),X===g||X===W)return y.avail_out===0&&(R.last_flush=-1),h;if(X===N&&(K===1?a._tr_align(R):K!==5&&(a._tr_stored_block(R,0,0,!1),K===3&&(Y(R.head),R.lookahead===0&&(R.strstart=0,R.block_start=0,R.insert=0))),$(y),y.avail_out===0))return R.last_flush=-1,h}return K!==d?h:R.wrap<=0?1:(R.wrap===2?(ue(R,255&y.adler),ue(R,y.adler>>8&255),ue(R,y.adler>>16&255),ue(R,y.adler>>24&255),ue(R,255&y.total_in),ue(R,y.total_in>>8&255),ue(R,y.total_in>>16&255),ue(R,y.total_in>>24&255)):(Q(R,y.adler>>>16),Q(R,65535&y.adler)),$(y),0=G.w_size&&(D===0&&(Y(G.head),G.strstart=0,G.block_start=0,G.insert=0),te=new o.Buf8(G.w_size),o.arraySet(te,K,le-G.w_size,G.w_size,0),K=te,le=G.w_size),J=y.avail_in,X=y.next_in,z=y.input,y.avail_in=le,y.next_in=0,y.input=K,Se(G);G.lookahead>=x;){for(R=G.strstart,A=G.lookahead-(x-1);G.ins_h=(G.ins_h<>>=x=M>>>24,v-=x,(x=M>>>16&255)===0)N[u++]=65535&M;else{if(!(16&x)){if(!(64&x)){M=S[(65535&M)+(w&(1<>>=x,v-=x),v<15&&(w+=g[c++]<>>=x=M>>>24,v-=x,!(16&(x=M>>>16&255))){if(!(64&x)){M=L[(65535&M)+(w&(1<>>=x,v-=x,(x=u-f)>3,w&=(1<<(v-=V<<3))-1,s.next_in=c,s.next_out=u,s.avail_in=c>>24&255)+(O>>>8&65280)+((65280&O)<<8)+((255&O)<<24)}function w(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(O){var E;return O&&O.state?(E=O.state,O.total_in=O.total_out=E.total=0,O.msg="",E.wrap&&(O.adler=1&E.wrap),E.mode=p,E.last=0,E.havedict=0,E.dmax=32768,E.head=null,E.hold=0,E.bits=0,E.lencode=E.lendyn=new s.Buf32(m),E.distcode=E.distdyn=new s.Buf32(b),E.sane=1,E.back=-1,d):h}function S(O){var E;return O&&O.state?((E=O.state).wsize=0,E.whave=0,E.wnext=0,v(O)):h}function L(O,E){var g,N;return O&&O.state?(N=O.state,E<0?(g=0,E=-E):(g=1+(E>>4),E<48&&(E&=15)),E&&(E<8||15=B.wsize?(s.arraySet(B.window,E,g-B.wsize,B.wsize,0),B.wnext=0,B.whave=B.wsize):(N<(W=B.wsize-B.wnext)&&(W=N),s.arraySet(B.window,E,g-N,W,B.wnext),(N-=W)?(s.arraySet(B.window,E,g-N,N,0),B.wnext=N,B.whave=B.wsize):(B.wnext+=W,B.wnext===B.wsize&&(B.wnext=0),B.whave>>8&255,g.check=a(g.check,D,2,0),F=$=0,g.mode=2;break}if(g.flags=0,g.head&&(g.head.done=!1),!(1&g.wrap)||(((255&$)<<8)+($>>8))%31){O.msg="incorrect header check",g.mode=30;break}if((15&$)!=8){O.msg="unknown compression method",g.mode=30;break}if(F-=4,y=8+(15&($>>>=4)),g.wbits===0)g.wbits=y;else if(y>g.wbits){O.msg="invalid window size",g.mode=30;break}g.dmax=1<>8&1),512&g.flags&&(D[0]=255&$,D[1]=$>>>8&255,g.check=a(g.check,D,2,0)),F=$=0,g.mode=3;case 3:for(;F<32;){if(H===0)break e;H--,$+=N[B++]<>>8&255,D[2]=$>>>16&255,D[3]=$>>>24&255,g.check=a(g.check,D,4,0)),F=$=0,g.mode=4;case 4:for(;F<16;){if(H===0)break e;H--,$+=N[B++]<>8),512&g.flags&&(D[0]=255&$,D[1]=$>>>8&255,g.check=a(g.check,D,2,0)),F=$=0,g.mode=5;case 5:if(1024&g.flags){for(;F<16;){if(H===0)break e;H--,$+=N[B++]<>>8&255,g.check=a(g.check,D,2,0)),F=$=0}else g.head&&(g.head.extra=null);g.mode=6;case 6:if(1024&g.flags&&(H<(ee=g.length)&&(ee=H),ee&&(g.head&&(y=g.head.extra_len-g.length,g.head.extra||(g.head.extra=new Array(g.head.extra_len)),s.arraySet(g.head.extra,N,B,ee,y)),512&g.flags&&(g.check=a(g.check,N,ee,B)),H-=ee,B+=ee,g.length-=ee),g.length))break e;g.length=0,g.mode=7;case 7:if(2048&g.flags){if(H===0)break e;for(ee=0;y=N[B+ee++],g.head&&y&&g.length<65536&&(g.head.name+=String.fromCharCode(y)),y&&ee>9&1,g.head.done=!0),O.adler=g.check=0,g.mode=12;break;case 10:for(;F<32;){if(H===0)break e;H--,$+=N[B++]<>>=7&F,F-=7&F,g.mode=27;break}for(;F<3;){if(H===0)break e;H--,$+=N[B++]<>>=1)){case 0:g.mode=14;break;case 1:if(V(g),g.mode=20,E!==6)break;$>>>=2,F-=2;break e;case 2:g.mode=17;break;case 3:O.msg="invalid block type",g.mode=30}$>>>=2,F-=2;break;case 14:for($>>>=7&F,F-=7&F;F<32;){if(H===0)break e;H--,$+=N[B++]<>>16^65535)){O.msg="invalid stored block lengths",g.mode=30;break}if(g.length=65535&$,F=$=0,g.mode=15,E===6)break e;case 15:g.mode=16;case 16:if(ee=g.length){if(H>>=5,F-=5,g.ndist=1+(31&$),$>>>=5,F-=5,g.ncode=4+(15&$),$>>>=4,F-=4,286>>=3,F-=3}for(;g.have<19;)g.lens[J[g.have++]]=0;if(g.lencode=g.lendyn,g.lenbits=7,G={bits:g.lenbits},K=l(0,g.lens,0,19,g.lencode,0,g.work,G),g.lenbits=G.bits,K){O.msg="invalid code lengths set",g.mode=30;break}g.have=0,g.mode=19;case 19:for(;g.have>>16&255,We=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>>=we,F-=we,g.lens[g.have++]=We;else{if(We===16){for(R=we+2;F>>=we,F-=we,g.have===0){O.msg="invalid bit length repeat",g.mode=30;break}y=g.lens[g.have-1],ee=3+(3&$),$>>>=2,F-=2}else if(We===17){for(R=we+3;F>>=we)),$>>>=3,F-=3}else{for(R=we+7;F>>=we)),$>>>=7,F-=7}if(g.have+ee>g.nlen+g.ndist){O.msg="invalid bit length repeat",g.mode=30;break}for(;ee--;)g.lens[g.have++]=y}}if(g.mode===30)break;if(g.lens[256]===0){O.msg="invalid code -- missing end-of-block",g.mode=30;break}if(g.lenbits=9,G={bits:g.lenbits},K=l(u,g.lens,0,g.nlen,g.lencode,0,g.work,G),g.lenbits=G.bits,K){O.msg="invalid literal/lengths set",g.mode=30;break}if(g.distbits=6,g.distcode=g.distdyn,G={bits:g.distbits},K=l(f,g.lens,g.nlen,g.ndist,g.distcode,0,g.work,G),g.distbits=G.bits,K){O.msg="invalid distances set",g.mode=30;break}if(g.mode=20,E===6)break e;case 20:g.mode=21;case 21:if(6<=H&&258<=Y){O.next_out=Z,O.avail_out=Y,O.next_in=B,O.avail_in=H,g.hold=$,g.bits=F,c(O,Q),Z=O.next_out,W=O.output,Y=O.avail_out,B=O.next_in,N=O.input,H=O.avail_in,$=g.hold,F=g.bits,g.mode===12&&(g.back=-1);break}for(g.back=0;_e=(A=g.lencode[$&(1<>>16&255,We=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>$e)])>>>16&255,We=65535&A,!($e+(we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>>=$e,F-=$e,g.back+=$e}if($>>>=we,F-=we,g.back+=we,g.length=We,_e===0){g.mode=26;break}if(32&_e){g.back=-1,g.mode=12;break}if(64&_e){O.msg="invalid literal/length code",g.mode=30;break}g.extra=15&_e,g.mode=22;case 22:if(g.extra){for(R=g.extra;F>>=g.extra,F-=g.extra,g.back+=g.extra}g.was=g.length,g.mode=23;case 23:for(;_e=(A=g.distcode[$&(1<>>16&255,We=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>$e)])>>>16&255,We=65535&A,!($e+(we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>>=$e,F-=$e,g.back+=$e}if($>>>=we,F-=we,g.back+=we,64&_e){O.msg="invalid distance code",g.mode=30;break}g.offset=We,g.extra=15&_e,g.mode=24;case 24:if(g.extra){for(R=g.extra;F>>=g.extra,F-=g.extra,g.back+=g.extra}if(g.offset>g.dmax){O.msg="invalid distance too far back",g.mode=30;break}g.mode=25;case 25:if(Y===0)break e;if(ee=Q-Y,g.offset>ee){if((ee=g.offset-ee)>g.whave&&g.sane){O.msg="invalid distance too far back",g.mode=30;break}Se=ee>g.wnext?(ee-=g.wnext,g.wsize-ee):g.wnext-ee,ee>g.length&&(ee=g.length),je=g.window}else je=W,Se=Z-g.offset,ee=g.length;for(YT?(x=Se[je+b[E]],F[ue+b[E]]):(x=96,0),w=1<>Z)+(v-=w)]=M<<24|x<<16|V|0,v!==0;);for(w=1<>=1;if(w!==0?($&=w-1,$+=w):$=0,E++,--Q[O]==0){if(O===N)break;O=f[d+b[E]]}if(W>>7)]}function ue(A,D){A.pending_buf[A.pending++]=255&D,A.pending_buf[A.pending++]=D>>>8&255}function Q(A,D,J){A.bi_valid>_-J?(A.bi_buf|=D<>_-A.bi_valid,A.bi_valid+=J-_):(A.bi_buf|=D<>>=1,J<<=1,0<--D;);return J>>>1}function je(A,D,J){var X,z,te=new Array(b+1),le=0;for(X=1;X<=b;X++)te[X]=le=le+J[X-1]<<1;for(z=0;z<=D;z++){var re=A[2*z+1];re!==0&&(A[2*z]=Se(te[re]++,re))}}function we(A){var D;for(D=0;D>1;1<=J;J--)$e(A,te,J);for(z=de;J=A.heap[1],A.heap[1]=A.heap[A.heap_len--],$e(A,te,1),X=A.heap[1],A.heap[--A.heap_max]=J,A.heap[--A.heap_max]=X,te[2*z]=te[2*J]+te[2*X],A.depth[z]=(A.depth[J]>=A.depth[X]?A.depth[J]:A.depth[X])+1,te[2*J+1]=te[2*X+1]=z,A.heap[1]=z++,$e(A,te,1),2<=A.heap_len;);A.heap[--A.heap_max]=A.heap[1],function(Me,Tn){var Co,ar,Lo,ft,Fc,nh,Pr=Tn.dyn_tree,Z_=Tn.max_code,JM=Tn.stat_desc.static_tree,XM=Tn.stat_desc.has_stree,ZM=Tn.stat_desc.extra_bits,Y_=Tn.stat_desc.extra_base,Mo=Tn.stat_desc.max_length,$c=0;for(ft=0;ft<=b;ft++)Me.bl_count[ft]=0;for(Pr[2*Me.heap[Me.heap_max]+1]=0,Co=Me.heap_max+1;Co>=7;z>>=1)if(1&Ze&&re.dyn_ltree[2*de]!==0)return o;if(re.dyn_ltree[18]!==0||re.dyn_ltree[20]!==0||re.dyn_ltree[26]!==0)return a;for(de=32;de>>3,(te=A.static_len+3+7>>>3)<=z&&(z=te)):z=te=J+5,J+4<=z&&D!==-1?R(A,D,J,X):A.strategy===4||te===z?(Q(A,2+(X?1:0),3),gt(A,oe,O)):(Q(A,4+(X?1:0),3),function(re,de,Ze,Me){var Tn;for(Q(re,de-257,5),Q(re,Ze-1,5),Q(re,Me-4,4),Tn=0;Tn>>8&255,A.pending_buf[A.d_buf+2*A.last_lit+1]=255&D,A.pending_buf[A.l_buf+A.last_lit]=255&J,A.last_lit++,D===0?A.dyn_ltree[2*J]++:(A.matches++,D--,A.dyn_ltree[2*(g[J]+f+1)]++,A.dyn_dtree[2*F(D)]++),A.last_lit===A.lit_bufsize-1},i._tr_align=function(A){Q(A,2,3),ee(A,v,oe),function(D){D.bi_valid===16?(ue(D,D.bi_buf),D.bi_buf=0,D.bi_valid=0):8<=D.bi_valid&&(D.pending_buf[D.pending++]=255&D.bi_buf,D.bi_buf>>=8,D.bi_valid-=8)}(A)}},{"../utils/common":41}],53:[function(n,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,i){(function(s){(function(o,a){if(!o.setImmediate){var c,l,u,f,d=1,h={},p=!1,m=o.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(o);b=b&&b.setTimeout?b:o,c={}.toString.call(o.process)==="[object process]"?function(S){process.nextTick(function(){w(S)})}:function(){if(o.postMessage&&!o.importScripts){var S=!0,L=o.onmessage;return o.onmessage=function(){S=!1},o.postMessage("","*"),o.onmessage=L,S}}()?(f="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",v,!1):o.attachEvent("onmessage",v),function(S){o.postMessage(f+S,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(S){w(S.data)},function(S){u.port2.postMessage(S)}):m&&"onreadystatechange"in m.createElement("script")?(l=m.documentElement,function(S){var L=m.createElement("script");L.onreadystatechange=function(){w(S),L.onreadystatechange=null,l.removeChild(L),L=null},l.appendChild(L)}):function(S){setTimeout(w,0,S)},b.setImmediate=function(S){typeof S!="function"&&(S=new Function(""+S));for(var L=new Array(arguments.length-1),I=0;I"u"?s===void 0?this:s:self)}).call(this,typeof Bt<"u"?Bt:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(D_);var dM=D_.exports,Qf=Pi(dM);const B_={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(B_);var An=function(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)},ds,No,Li;class pM{constructor(...t){ds.set(this,new Map),No.set(this,new Map),Li.set(this,new Map);for(const n of t)this.define(n)}define(t,n=!1){for(let[r,i]of Object.entries(t)){r=r.toLowerCase(),i=i.map(a=>a.toLowerCase()),An(this,Li,"f").has(r)||An(this,Li,"f").set(r,new Set);const s=An(this,Li,"f").get(r);let o=!0;for(let a of i){const c=a.startsWith("*");if(a=c?a.slice(1):a,s==null||s.add(a),o&&An(this,No,"f").set(r,a),o=!1,c)continue;const l=An(this,ds,"f").get(a);if(l&&l!=r&&!n)throw new Error(`"${r} -> ${a}" conflicts with "${l} -> ${a}". Pass \`force=true\` to override this definition.`);An(this,ds,"f").set(a,r)}}return this}getType(t){if(typeof t!="string")return null;const n=t.replace(/^.*[/\\]/,"").toLowerCase(),r=n.replace(/^.*\./,"").toLowerCase(),i=n.length{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(const t of An(this,Li,"f").values())Object.freeze(t);return this}_getTestState(){return{types:An(this,ds,"f"),extensions:An(this,No,"f")}}}ds=new WeakMap,No=new WeakMap,Li=new WeakMap;var mM=new pM(B_)._freeze();function F_(e,t){switch([...t.slice(0,4)].map(i=>i.toString(16)).join("").toUpperCase()){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"FFD8FFDB":case"FFD8FFE0":case"FFD8FFE1":return"image/jpeg";case"504B0304":return"application/zip"}return mM.getType(e)??"application/octet-stream"}function gM(e){const t=vg(e,{}),n=Xn(t),r=Zs(t),i=Bn(Xe.MAIN);if(!k(i))return;const s=Xs(t),o=Iu(i,s,n);k(o)?yt("memory",`${i.name} already has a [${r}] named ${n}`):(Ag(i,t),z_(t.id,i.id),yt("memory",`created [${r}] ${n} in ${i.name}`))}async function yM(e){const t=await e.text();gM(t)}async function _M(e,t){try{yt("parsezipfile",e.name);const n=await e.arrayBuffer();(await new Qf().loadAsync(n)).forEach((s,o)=>{o.async("uint8array").then(a=>{const c=F_(s,a),l=new File([a],o.name,{type:c});t(l)}).catch(a=>{et("memory","crash",a.message)})})}catch(n){et("memory","crash",n.message)}}async function bM(e,t){try{yt("parsebinaryfile",e.name);const n=await e.arrayBuffer(),r=e.name.split(".").slice(-1)[0]??"";t(Pe(r),new Uint8Array(n))}catch(n){et("memory","crash",n.message)}}function eh(e){if(!e||e.type===void 0)return;const t=[{start:e.startOffset,end:e.endOffset??0}];return Object.keys(e).forEach(n=>{if(n!=="parent"){const r=e[n];Ge(r)?r.forEach(i=>{t.push(eh(i))}):t.push(eh(r))}}),e.range={start:Math.min(...t.filter(n=>n).map(n=>(n==null?void 0:n.start)??0)),end:Math.max(...t.filter(n=>n).map(n=>(n==null?void 0:n.end)??0))},e.range}function wM(e){const t=Um(`${e} -`);if(t.errors.length>0)return t;hs.input=t.tokens;const n=hs.program();if(hs.errors.length>0)return{tokens:t.tokens,errors:hs.errors.map(i=>({offset:i.token.startOffset,line:i.token.startLine,column:i.token.startColumn,length:i.token.image.length,message:i.message}))};const[r]=sM.go(n);return r?(eh(r),{tokens:t.tokens,cst:n,ast:r}):{tokens:t.tokens,cst:n,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]}}const th=Object.getPrototypeOf(function*(){}).constructor;function vM(e,t){const n=`compile-${e}`;console.time(n);const r=wM(t);if(console.timeEnd(n),r.errors&&r.errors.length>0)return r;if(!r.ast)return{...r,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]};const i=uM(r.ast);if(i.code){Hx&&console.info(i.code);try{return{...r,...i,source:i.code,code:new th("api",i.code)}}catch(s){return{errors:[{message:`unexpected error ${s.message}`,offset:0,line:0,column:0,length:0}],source:"",code:new th("api"," ")}}}return{...r,...i,source:"",code:new th("api"," ")}}function EM(){const e={},t={};function n(i,s){const o=e[s];if(o)return o;const a=vM(i,s);return e[s]=a,a}const r={ids(){return Object.keys(t)},has(i){return k(t[i])},isended(i){const s=t[i];return k(s)?s.isended():!0},halt(i){const s=t[i];return k(s)&&(s.halt(),delete t[i]),!!s},gc(){const i=r.ids();for(let s=0;s=this.index;c--)l=(l<<8)+this.byteAt(c);return this.index+=a,l},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},r.exports=o},{"../utils":32}],19:[function(n,r,i){var s=n("./Uint8ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,i){var s=n("./DataReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,r,i){var s=n("./ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,i){var s=n("../utils"),o=n("../support"),a=n("./ArrayReader"),c=n("./StringReader"),l=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(f){var d=s.getTypeOf(f);return s.checkSupport(d),d!=="string"||o.uint8array?d==="nodebuffer"?new l(f):o.uint8array?new u(s.transformTo("uint8array",f)):new a(s.transformTo("array",f)):new c(f)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,i){var s=n("./GenericWorker"),o=n("../utils");function a(c){s.call(this,"ConvertWorker to "+c),this.destType=c}o.inherits(a,s),a.prototype.processChunk=function(c){this.push({data:o.transformTo(this.destType,c.data),meta:c.meta})},r.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,i){var s=n("./GenericWorker"),o=n("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(a,s),a.prototype.processChunk=function(c){this.streamInfo.crc32=o(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}s.inherits(a,o),a.prototype.processChunk=function(c){if(c){var l=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=l+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataWorker");var l=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){l.dataIsReady=!0,l.data=u,l.max=u&&u.length||0,l.type=s.getTypeOf(u),l.isPaused||l._tickAndRepeat()},function(u){l.error(u)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,l=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,l);break;case"uint8array":c=this.data.subarray(this.index,l);break;case"array":case"nodebuffer":c=this.data.slice(this.index,l)}return this.index=l,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var c=0;c "+o:o}},r.exports=s},{}],29:[function(n,r,i){var s=n("../utils"),o=n("./ConvertWorker"),a=n("./GenericWorker"),c=n("../base64"),l=n("../support"),u=n("../external"),f=null;if(l.nodestream)try{f=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function d(p,m){return new u.Promise(function(b,_){var w=[],v=p._internalType,S=p._outputType,L=p._mimeType;p.on("data",function(I,T){w.push(I),m&&m(T)}).on("error",function(I){w=[],_(I)}).on("end",function(){try{var I=function(T,M,x){switch(T){case"blob":return s.newBlob(s.transformTo("arraybuffer",M),x);case"base64":return c.encode(M);default:return s.transformTo(T,M)}}(S,function(T,M){var x,V=0,oe=null,O=0;for(x=0;x"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,i){for(var s=n("./utils"),o=n("./support"),a=n("./nodejsUtils"),c=n("./stream/GenericWorker"),l=new Array(256),u=0;u<256;u++)l[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;l[254]=l[254]=1;function f(){c.call(this,"utf-8 decode"),this.leftOver=null}function d(){c.call(this,"utf-8 encode")}i.utf8encode=function(h){return o.nodebuffer?a.newBufferFrom(h,"utf-8"):function(p){var m,b,_,w,v,S=p.length,L=0;for(w=0;w>>6:(b<65536?m[v++]=224|b>>>12:(m[v++]=240|b>>>18,m[v++]=128|b>>>12&63),m[v++]=128|b>>>6&63),m[v++]=128|63&b);return m}(h)},i.utf8decode=function(h){return o.nodebuffer?s.transformTo("nodebuffer",h).toString("utf-8"):function(p){var m,b,_,w,v=p.length,S=new Array(2*v);for(m=b=0;m>10&1023,S[b++]=56320|1023&_)}return S.length!==b&&(S.subarray?S=S.subarray(0,b):S.length=b),s.applyFromCharCode(S)}(h=s.transformTo(o.uint8array?"uint8array":"array",h))},s.inherits(f,c),f.prototype.processChunk=function(h){var p=s.transformTo(o.uint8array?"uint8array":"array",h.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var m=p;(p=new Uint8Array(m.length+this.leftOver.length)).set(this.leftOver,0),p.set(m,this.leftOver.length)}else p=this.leftOver.concat(p);this.leftOver=null}var b=function(w,v){var S;for((v=v||w.length)>w.length&&(v=w.length),S=v-1;0<=S&&(192&w[S])==128;)S--;return S<0||S===0?v:S+l[w[S]]>v?S:v}(p),_=p;b!==p.length&&(o.uint8array?(_=p.subarray(0,b),this.leftOver=p.subarray(b,p.length)):(_=p.slice(0,b),this.leftOver=p.slice(b,p.length))),this.push({data:i.utf8decode(_),meta:h.meta})},f.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=f,s.inherits(d,c),d.prototype.processChunk=function(h){this.push({data:i.utf8encode(h.data),meta:h.meta})},i.Utf8EncodeWorker=d},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,i){var s=n("./support"),o=n("./base64"),a=n("./nodejsUtils"),c=n("./external");function l(m){return m}function u(m,b){for(var _=0;_>8;this.dir=!!(16&this.externalFileAttributes),h==0&&(this.dosPermissions=63&this.externalFileAttributes),h==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var h=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=h.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=h.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=h.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=h.readInt(4))}},readExtraFields:function(h){var p,m,b,_=h.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});h.index+4<_;)p=h.readInt(2),m=h.readInt(2),b=h.readData(m),this.extraFields[p]={id:p,length:m,value:b};h.setIndex(_)},handleUTF8:function(){var h=f.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=l.utf8decode(this.fileName),this.fileCommentStr=l.utf8decode(this.fileComment);else{var p=this.findExtraFieldUnicodePath();if(p!==null)this.fileNameStr=p;else{var m=o.transformTo(h,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(m)}var b=this.findExtraFieldUnicodeComment();if(b!==null)this.fileCommentStr=b;else{var _=o.transformTo(h,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(_)}}},findExtraFieldUnicodePath:function(){var h=this.extraFields[28789];if(h){var p=s(h.value);return p.readInt(1)!==1||c(this.fileName)!==p.readInt(4)?null:l.utf8decode(p.readData(h.length-5))}return null},findExtraFieldUnicodeComment:function(){var h=this.extraFields[25461];if(h){var p=s(h.value);return p.readInt(1)!==1||c(this.fileComment)!==p.readInt(4)?null:l.utf8decode(p.readData(h.length-5))}return null}},r.exports=d},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,i){function s(p,m,b){this.name=p,this.dir=b.dir,this.date=b.date,this.comment=b.comment,this.unixPermissions=b.unixPermissions,this.dosPermissions=b.dosPermissions,this._data=m,this._dataBinary=b.binary,this.options={compression:b.compression,compressionOptions:b.compressionOptions}}var o=n("./stream/StreamHelper"),a=n("./stream/DataWorker"),c=n("./utf8"),l=n("./compressedObject"),u=n("./stream/GenericWorker");s.prototype={internalStream:function(p){var m=null,b="string";try{if(!p)throw new Error("No output type specified.");var _=(b=p.toLowerCase())==="string"||b==="text";b!=="binarystring"&&b!=="text"||(b="string"),m=this._decompressWorker();var w=!this._dataBinary;w&&!_&&(m=m.pipe(new c.Utf8EncodeWorker)),!w&&_&&(m=m.pipe(new c.Utf8DecodeWorker))}catch(v){(m=new u("error")).error(v)}return new o(m,b,"")},async:function(p,m){return this.internalStream(p).accumulate(m)},nodeStream:function(p,m){return this.internalStream(p||"nodebuffer").toNodejsStream(m)},_compressWorker:function(p,m){if(this._data instanceof l&&this._data.compression.magic===p.magic)return this._data.getCompressedWorker();var b=this._decompressWorker();return this._dataBinary||(b=b.pipe(new c.Utf8EncodeWorker)),l.createWorkerFrom(b,p,m)},_decompressWorker:function(){return this._data instanceof l?this._data.getContentWorker():this._data instanceof u?this._data:new a(this._data)}};for(var f=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],d=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},h=0;h>>6:(h<65536?d[b++]=224|h>>>12:(d[b++]=240|h>>>18,d[b++]=128|h>>>12&63),d[b++]=128|h>>>6&63),d[b++]=128|63&h);return d},i.buf2binstring=function(f){return u(f,f.length)},i.binstring2buf=function(f){for(var d=new s.Buf8(f.length),h=0,p=d.length;h>10&1023,w[p++]=56320|1023&m)}return u(w,p)},i.utf8border=function(f,d){var h;for((d=d||f.length)>f.length&&(d=f.length),h=d-1;0<=h&&(192&f[h])==128;)h--;return h<0||h===0?d:h+c[f[h]]>d?h:d}},{"./common":41}],43:[function(n,r,i){r.exports=function(s,o,a,c){for(var l=65535&s|0,u=s>>>16&65535|0,f=0;a!==0;){for(a-=f=2e3>>1:o>>>1;a[c]=o}return a}();r.exports=function(o,a,c,l){var u=s,f=l+c;o^=-1;for(var d=l;d>>8^u[255&(o^a[d])];return-1^o}},{}],46:[function(n,r,i){var s,o=n("../utils/common"),a=n("./trees"),c=n("./adler32"),l=n("./crc32"),u=n("./messages"),f=0,d=4,h=0,p=-2,m=-1,b=4,_=2,w=8,v=9,S=286,L=30,I=19,T=2*S+1,M=15,x=3,V=258,oe=V+x+1,O=42,E=113,g=1,N=2,W=3,B=4;function Z(y,K){return y.msg=u[K],K}function H(y){return(y<<1)-(4y.avail_out&&(G=y.avail_out),G!==0&&(o.arraySet(y.output,K.pending_buf,K.pending_out,G,y.next_out),y.next_out+=G,K.pending_out+=G,y.total_out+=G,y.avail_out-=G,K.pending-=G,K.pending===0&&(K.pending_out=0))}function F(y,K){a._tr_flush_block(y,0<=y.block_start?y.block_start:-1,y.strstart-y.block_start,K),y.block_start=y.strstart,$(y.strm)}function ue(y,K){y.pending_buf[y.pending++]=K}function Q(y,K){y.pending_buf[y.pending++]=K>>>8&255,y.pending_buf[y.pending++]=255&K}function ee(y,K){var G,R,A=y.max_chain_length,D=y.strstart,J=y.prev_length,X=y.nice_match,z=y.strstart>y.w_size-oe?y.strstart-(y.w_size-oe):0,te=y.window,le=y.w_mask,re=y.prev,de=y.strstart+V,Ze=te[D+J-1],Me=te[D+J];y.prev_length>=y.good_match&&(A>>=2),X>y.lookahead&&(X=y.lookahead);do if(te[(G=K)+J]===Me&&te[G+J-1]===Ze&&te[G]===te[D]&&te[++G]===te[D+1]){D+=2,G++;do;while(te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&Dz&&--A!=0);return J<=y.lookahead?J:y.lookahead}function Se(y){var K,G,R,A,D,J,X,z,te,le,re=y.w_size;do{if(A=y.window_size-y.lookahead-y.strstart,y.strstart>=re+(re-oe)){for(o.arraySet(y.window,y.window,re,re,0),y.match_start-=re,y.strstart-=re,y.block_start-=re,K=G=y.hash_size;R=y.head[--K],y.head[K]=re<=R?R-re:0,--G;);for(K=G=re;R=y.prev[--K],y.prev[K]=re<=R?R-re:0,--G;);A+=re}if(y.strm.avail_in===0)break;if(J=y.strm,X=y.window,z=y.strstart+y.lookahead,te=A,le=void 0,le=J.avail_in,te=x)for(D=y.strstart-y.insert,y.ins_h=y.window[D],y.ins_h=(y.ins_h<=x&&(y.ins_h=(y.ins_h<=x)if(R=a._tr_tally(y,y.strstart-y.match_start,y.match_length-x),y.lookahead-=y.match_length,y.match_length<=y.max_lazy_match&&y.lookahead>=x){for(y.match_length--;y.strstart++,y.ins_h=(y.ins_h<=x&&(y.ins_h=(y.ins_h<=x&&y.match_length<=y.prev_length){for(A=y.strstart+y.lookahead-x,R=a._tr_tally(y,y.strstart-1-y.prev_match,y.prev_length-x),y.lookahead-=y.prev_length-1,y.prev_length-=2;++y.strstart<=A&&(y.ins_h=(y.ins_h<y.pending_buf_size-5&&(G=y.pending_buf_size-5);;){if(y.lookahead<=1){if(Se(y),y.lookahead===0&&K===f)return g;if(y.lookahead===0)break}y.strstart+=y.lookahead,y.lookahead=0;var R=y.block_start+G;if((y.strstart===0||y.strstart>=R)&&(y.lookahead=y.strstart-R,y.strstart=R,F(y,!1),y.strm.avail_out===0)||y.strstart-y.block_start>=y.w_size-oe&&(F(y,!1),y.strm.avail_out===0))return g}return y.insert=0,K===d?(F(y,!0),y.strm.avail_out===0?W:B):(y.strstart>y.block_start&&(F(y,!1),y.strm.avail_out),g)}),new _e(4,4,8,4,je),new _e(4,5,16,8,je),new _e(4,6,32,32,je),new _e(4,4,16,16,we),new _e(8,16,32,32,we),new _e(8,16,128,128,we),new _e(8,32,128,256,we),new _e(32,128,258,1024,we),new _e(32,258,258,4096,we)],i.deflateInit=function(y,K){return St(y,K,w,15,8,0)},i.deflateInit2=St,i.deflateReset=gt,i.deflateResetKeep=$e,i.deflateSetHeader=function(y,K){return y&&y.state?y.state.wrap!==2?p:(y.state.gzhead=K,h):p},i.deflate=function(y,K){var G,R,A,D;if(!y||!y.state||5>8&255),ue(R,R.gzhead.time>>16&255),ue(R,R.gzhead.time>>24&255),ue(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),ue(R,255&R.gzhead.os),R.gzhead.extra&&R.gzhead.extra.length&&(ue(R,255&R.gzhead.extra.length),ue(R,R.gzhead.extra.length>>8&255)),R.gzhead.hcrc&&(y.adler=l(y.adler,R.pending_buf,R.pending,0)),R.gzindex=0,R.status=69):(ue(R,0),ue(R,0),ue(R,0),ue(R,0),ue(R,0),ue(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),ue(R,3),R.status=E);else{var J=w+(R.w_bits-8<<4)<<8;J|=(2<=R.strategy||R.level<2?0:R.level<6?1:R.level===6?2:3)<<6,R.strstart!==0&&(J|=32),J+=31-J%31,R.status=E,Q(R,J),R.strstart!==0&&(Q(R,y.adler>>>16),Q(R,65535&y.adler)),y.adler=1}if(R.status===69)if(R.gzhead.extra){for(A=R.pending;R.gzindex<(65535&R.gzhead.extra.length)&&(R.pending!==R.pending_buf_size||(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending!==R.pending_buf_size));)ue(R,255&R.gzhead.extra[R.gzindex]),R.gzindex++;R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),R.gzindex===R.gzhead.extra.length&&(R.gzindex=0,R.status=73)}else R.status=73;if(R.status===73)if(R.gzhead.name){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindexA&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),D===0&&(R.gzindex=0,R.status=91)}else R.status=91;if(R.status===91)if(R.gzhead.comment){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindexA&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),D===0&&(R.status=103)}else R.status=103;if(R.status===103&&(R.gzhead.hcrc?(R.pending+2>R.pending_buf_size&&$(y),R.pending+2<=R.pending_buf_size&&(ue(R,255&y.adler),ue(R,y.adler>>8&255),y.adler=0,R.status=E)):R.status=E),R.pending!==0){if($(y),y.avail_out===0)return R.last_flush=-1,h}else if(y.avail_in===0&&H(K)<=H(G)&&K!==d)return Z(y,-5);if(R.status===666&&y.avail_in!==0)return Z(y,-5);if(y.avail_in!==0||R.lookahead!==0||K!==f&&R.status!==666){var X=R.strategy===2?function(z,te){for(var le;;){if(z.lookahead===0&&(Se(z),z.lookahead===0)){if(te===f)return g;break}if(z.match_length=0,le=a._tr_tally(z,0,z.window[z.strstart]),z.lookahead--,z.strstart++,le&&(F(z,!1),z.strm.avail_out===0))return g}return z.insert=0,te===d?(F(z,!0),z.strm.avail_out===0?W:B):z.last_lit&&(F(z,!1),z.strm.avail_out===0)?g:N}(R,K):R.strategy===3?function(z,te){for(var le,re,de,Ze,Me=z.window;;){if(z.lookahead<=V){if(Se(z),z.lookahead<=V&&te===f)return g;if(z.lookahead===0)break}if(z.match_length=0,z.lookahead>=x&&0z.lookahead&&(z.match_length=z.lookahead)}if(z.match_length>=x?(le=a._tr_tally(z,1,z.match_length-x),z.lookahead-=z.match_length,z.strstart+=z.match_length,z.match_length=0):(le=a._tr_tally(z,0,z.window[z.strstart]),z.lookahead--,z.strstart++),le&&(F(z,!1),z.strm.avail_out===0))return g}return z.insert=0,te===d?(F(z,!0),z.strm.avail_out===0?W:B):z.last_lit&&(F(z,!1),z.strm.avail_out===0)?g:N}(R,K):s[R.level].func(R,K);if(X!==W&&X!==B||(R.status=666),X===g||X===W)return y.avail_out===0&&(R.last_flush=-1),h;if(X===N&&(K===1?a._tr_align(R):K!==5&&(a._tr_stored_block(R,0,0,!1),K===3&&(Y(R.head),R.lookahead===0&&(R.strstart=0,R.block_start=0,R.insert=0))),$(y),y.avail_out===0))return R.last_flush=-1,h}return K!==d?h:R.wrap<=0?1:(R.wrap===2?(ue(R,255&y.adler),ue(R,y.adler>>8&255),ue(R,y.adler>>16&255),ue(R,y.adler>>24&255),ue(R,255&y.total_in),ue(R,y.total_in>>8&255),ue(R,y.total_in>>16&255),ue(R,y.total_in>>24&255)):(Q(R,y.adler>>>16),Q(R,65535&y.adler)),$(y),0=G.w_size&&(D===0&&(Y(G.head),G.strstart=0,G.block_start=0,G.insert=0),te=new o.Buf8(G.w_size),o.arraySet(te,K,le-G.w_size,G.w_size,0),K=te,le=G.w_size),J=y.avail_in,X=y.next_in,z=y.input,y.avail_in=le,y.next_in=0,y.input=K,Se(G);G.lookahead>=x;){for(R=G.strstart,A=G.lookahead-(x-1);G.ins_h=(G.ins_h<>>=x=M>>>24,v-=x,(x=M>>>16&255)===0)N[u++]=65535&M;else{if(!(16&x)){if(!(64&x)){M=S[(65535&M)+(w&(1<>>=x,v-=x),v<15&&(w+=g[c++]<>>=x=M>>>24,v-=x,!(16&(x=M>>>16&255))){if(!(64&x)){M=L[(65535&M)+(w&(1<>>=x,v-=x,(x=u-f)>3,w&=(1<<(v-=V<<3))-1,s.next_in=c,s.next_out=u,s.avail_in=c>>24&255)+(O>>>8&65280)+((65280&O)<<8)+((255&O)<<24)}function w(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(O){var E;return O&&O.state?(E=O.state,O.total_in=O.total_out=E.total=0,O.msg="",E.wrap&&(O.adler=1&E.wrap),E.mode=p,E.last=0,E.havedict=0,E.dmax=32768,E.head=null,E.hold=0,E.bits=0,E.lencode=E.lendyn=new s.Buf32(m),E.distcode=E.distdyn=new s.Buf32(b),E.sane=1,E.back=-1,d):h}function S(O){var E;return O&&O.state?((E=O.state).wsize=0,E.whave=0,E.wnext=0,v(O)):h}function L(O,E){var g,N;return O&&O.state?(N=O.state,E<0?(g=0,E=-E):(g=1+(E>>4),E<48&&(E&=15)),E&&(E<8||15=B.wsize?(s.arraySet(B.window,E,g-B.wsize,B.wsize,0),B.wnext=0,B.whave=B.wsize):(N<(W=B.wsize-B.wnext)&&(W=N),s.arraySet(B.window,E,g-N,W,B.wnext),(N-=W)?(s.arraySet(B.window,E,g-N,N,0),B.wnext=N,B.whave=B.wsize):(B.wnext+=W,B.wnext===B.wsize&&(B.wnext=0),B.whave>>8&255,g.check=a(g.check,D,2,0),F=$=0,g.mode=2;break}if(g.flags=0,g.head&&(g.head.done=!1),!(1&g.wrap)||(((255&$)<<8)+($>>8))%31){O.msg="incorrect header check",g.mode=30;break}if((15&$)!=8){O.msg="unknown compression method",g.mode=30;break}if(F-=4,y=8+(15&($>>>=4)),g.wbits===0)g.wbits=y;else if(y>g.wbits){O.msg="invalid window size",g.mode=30;break}g.dmax=1<>8&1),512&g.flags&&(D[0]=255&$,D[1]=$>>>8&255,g.check=a(g.check,D,2,0)),F=$=0,g.mode=3;case 3:for(;F<32;){if(H===0)break e;H--,$+=N[B++]<>>8&255,D[2]=$>>>16&255,D[3]=$>>>24&255,g.check=a(g.check,D,4,0)),F=$=0,g.mode=4;case 4:for(;F<16;){if(H===0)break e;H--,$+=N[B++]<>8),512&g.flags&&(D[0]=255&$,D[1]=$>>>8&255,g.check=a(g.check,D,2,0)),F=$=0,g.mode=5;case 5:if(1024&g.flags){for(;F<16;){if(H===0)break e;H--,$+=N[B++]<>>8&255,g.check=a(g.check,D,2,0)),F=$=0}else g.head&&(g.head.extra=null);g.mode=6;case 6:if(1024&g.flags&&(H<(ee=g.length)&&(ee=H),ee&&(g.head&&(y=g.head.extra_len-g.length,g.head.extra||(g.head.extra=new Array(g.head.extra_len)),s.arraySet(g.head.extra,N,B,ee,y)),512&g.flags&&(g.check=a(g.check,N,ee,B)),H-=ee,B+=ee,g.length-=ee),g.length))break e;g.length=0,g.mode=7;case 7:if(2048&g.flags){if(H===0)break e;for(ee=0;y=N[B+ee++],g.head&&y&&g.length<65536&&(g.head.name+=String.fromCharCode(y)),y&&ee>9&1,g.head.done=!0),O.adler=g.check=0,g.mode=12;break;case 10:for(;F<32;){if(H===0)break e;H--,$+=N[B++]<>>=7&F,F-=7&F,g.mode=27;break}for(;F<3;){if(H===0)break e;H--,$+=N[B++]<>>=1)){case 0:g.mode=14;break;case 1:if(V(g),g.mode=20,E!==6)break;$>>>=2,F-=2;break e;case 2:g.mode=17;break;case 3:O.msg="invalid block type",g.mode=30}$>>>=2,F-=2;break;case 14:for($>>>=7&F,F-=7&F;F<32;){if(H===0)break e;H--,$+=N[B++]<>>16^65535)){O.msg="invalid stored block lengths",g.mode=30;break}if(g.length=65535&$,F=$=0,g.mode=15,E===6)break e;case 15:g.mode=16;case 16:if(ee=g.length){if(H>>=5,F-=5,g.ndist=1+(31&$),$>>>=5,F-=5,g.ncode=4+(15&$),$>>>=4,F-=4,286>>=3,F-=3}for(;g.have<19;)g.lens[J[g.have++]]=0;if(g.lencode=g.lendyn,g.lenbits=7,G={bits:g.lenbits},K=l(0,g.lens,0,19,g.lencode,0,g.work,G),g.lenbits=G.bits,K){O.msg="invalid code lengths set",g.mode=30;break}g.have=0,g.mode=19;case 19:for(;g.have>>16&255,We=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>>=we,F-=we,g.lens[g.have++]=We;else{if(We===16){for(R=we+2;F>>=we,F-=we,g.have===0){O.msg="invalid bit length repeat",g.mode=30;break}y=g.lens[g.have-1],ee=3+(3&$),$>>>=2,F-=2}else if(We===17){for(R=we+3;F>>=we)),$>>>=3,F-=3}else{for(R=we+7;F>>=we)),$>>>=7,F-=7}if(g.have+ee>g.nlen+g.ndist){O.msg="invalid bit length repeat",g.mode=30;break}for(;ee--;)g.lens[g.have++]=y}}if(g.mode===30)break;if(g.lens[256]===0){O.msg="invalid code -- missing end-of-block",g.mode=30;break}if(g.lenbits=9,G={bits:g.lenbits},K=l(u,g.lens,0,g.nlen,g.lencode,0,g.work,G),g.lenbits=G.bits,K){O.msg="invalid literal/lengths set",g.mode=30;break}if(g.distbits=6,g.distcode=g.distdyn,G={bits:g.distbits},K=l(f,g.lens,g.nlen,g.ndist,g.distcode,0,g.work,G),g.distbits=G.bits,K){O.msg="invalid distances set",g.mode=30;break}if(g.mode=20,E===6)break e;case 20:g.mode=21;case 21:if(6<=H&&258<=Y){O.next_out=Z,O.avail_out=Y,O.next_in=B,O.avail_in=H,g.hold=$,g.bits=F,c(O,Q),Z=O.next_out,W=O.output,Y=O.avail_out,B=O.next_in,N=O.input,H=O.avail_in,$=g.hold,F=g.bits,g.mode===12&&(g.back=-1);break}for(g.back=0;_e=(A=g.lencode[$&(1<>>16&255,We=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>$e)])>>>16&255,We=65535&A,!($e+(we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>>=$e,F-=$e,g.back+=$e}if($>>>=we,F-=we,g.back+=we,g.length=We,_e===0){g.mode=26;break}if(32&_e){g.back=-1,g.mode=12;break}if(64&_e){O.msg="invalid literal/length code",g.mode=30;break}g.extra=15&_e,g.mode=22;case 22:if(g.extra){for(R=g.extra;F>>=g.extra,F-=g.extra,g.back+=g.extra}g.was=g.length,g.mode=23;case 23:for(;_e=(A=g.distcode[$&(1<>>16&255,We=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>$e)])>>>16&255,We=65535&A,!($e+(we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>>=$e,F-=$e,g.back+=$e}if($>>>=we,F-=we,g.back+=we,64&_e){O.msg="invalid distance code",g.mode=30;break}g.offset=We,g.extra=15&_e,g.mode=24;case 24:if(g.extra){for(R=g.extra;F>>=g.extra,F-=g.extra,g.back+=g.extra}if(g.offset>g.dmax){O.msg="invalid distance too far back",g.mode=30;break}g.mode=25;case 25:if(Y===0)break e;if(ee=Q-Y,g.offset>ee){if((ee=g.offset-ee)>g.whave&&g.sane){O.msg="invalid distance too far back",g.mode=30;break}Se=ee>g.wnext?(ee-=g.wnext,g.wsize-ee):g.wnext-ee,ee>g.length&&(ee=g.length),je=g.window}else je=W,Se=Z-g.offset,ee=g.length;for(YT?(x=Se[je+b[E]],F[ue+b[E]]):(x=96,0),w=1<>Z)+(v-=w)]=M<<24|x<<16|V|0,v!==0;);for(w=1<>=1;if(w!==0?($&=w-1,$+=w):$=0,E++,--Q[O]==0){if(O===N)break;O=f[d+b[E]]}if(W>>7)]}function ue(A,D){A.pending_buf[A.pending++]=255&D,A.pending_buf[A.pending++]=D>>>8&255}function Q(A,D,J){A.bi_valid>_-J?(A.bi_buf|=D<>_-A.bi_valid,A.bi_valid+=J-_):(A.bi_buf|=D<>>=1,J<<=1,0<--D;);return J>>>1}function je(A,D,J){var X,z,te=new Array(b+1),le=0;for(X=1;X<=b;X++)te[X]=le=le+J[X-1]<<1;for(z=0;z<=D;z++){var re=A[2*z+1];re!==0&&(A[2*z]=Se(te[re]++,re))}}function we(A){var D;for(D=0;D>1;1<=J;J--)$e(A,te,J);for(z=de;J=A.heap[1],A.heap[1]=A.heap[A.heap_len--],$e(A,te,1),X=A.heap[1],A.heap[--A.heap_max]=J,A.heap[--A.heap_max]=X,te[2*z]=te[2*J]+te[2*X],A.depth[z]=(A.depth[J]>=A.depth[X]?A.depth[J]:A.depth[X])+1,te[2*J+1]=te[2*X+1]=z,A.heap[1]=z++,$e(A,te,1),2<=A.heap_len;);A.heap[--A.heap_max]=A.heap[1],function(Me,Tn){var Co,ar,Lo,ft,Fc,nh,Pr=Tn.dyn_tree,Z_=Tn.max_code,XM=Tn.stat_desc.static_tree,ZM=Tn.stat_desc.has_stree,YM=Tn.stat_desc.extra_bits,Y_=Tn.stat_desc.extra_base,Mo=Tn.stat_desc.max_length,$c=0;for(ft=0;ft<=b;ft++)Me.bl_count[ft]=0;for(Pr[2*Me.heap[Me.heap_max]+1]=0,Co=Me.heap_max+1;Co>=7;z>>=1)if(1&Ze&&re.dyn_ltree[2*de]!==0)return o;if(re.dyn_ltree[18]!==0||re.dyn_ltree[20]!==0||re.dyn_ltree[26]!==0)return a;for(de=32;de>>3,(te=A.static_len+3+7>>>3)<=z&&(z=te)):z=te=J+5,J+4<=z&&D!==-1?R(A,D,J,X):A.strategy===4||te===z?(Q(A,2+(X?1:0),3),gt(A,oe,O)):(Q(A,4+(X?1:0),3),function(re,de,Ze,Me){var Tn;for(Q(re,de-257,5),Q(re,Ze-1,5),Q(re,Me-4,4),Tn=0;Tn>>8&255,A.pending_buf[A.d_buf+2*A.last_lit+1]=255&D,A.pending_buf[A.l_buf+A.last_lit]=255&J,A.last_lit++,D===0?A.dyn_ltree[2*J]++:(A.matches++,D--,A.dyn_ltree[2*(g[J]+f+1)]++,A.dyn_dtree[2*F(D)]++),A.last_lit===A.lit_bufsize-1},i._tr_align=function(A){Q(A,2,3),ee(A,v,oe),function(D){D.bi_valid===16?(ue(D,D.bi_buf),D.bi_buf=0,D.bi_valid=0):8<=D.bi_valid&&(D.pending_buf[D.pending++]=255&D.bi_buf,D.bi_buf>>=8,D.bi_valid-=8)}(A)}},{"../utils/common":41}],53:[function(n,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,i){(function(s){(function(o,a){if(!o.setImmediate){var c,l,u,f,d=1,h={},p=!1,m=o.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(o);b=b&&b.setTimeout?b:o,c={}.toString.call(o.process)==="[object process]"?function(S){process.nextTick(function(){w(S)})}:function(){if(o.postMessage&&!o.importScripts){var S=!0,L=o.onmessage;return o.onmessage=function(){S=!1},o.postMessage("","*"),o.onmessage=L,S}}()?(f="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",v,!1):o.attachEvent("onmessage",v),function(S){o.postMessage(f+S,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(S){w(S.data)},function(S){u.port2.postMessage(S)}):m&&"onreadystatechange"in m.createElement("script")?(l=m.documentElement,function(S){var L=m.createElement("script");L.onreadystatechange=function(){w(S),L.onreadystatechange=null,l.removeChild(L),L=null},l.appendChild(L)}):function(S){setTimeout(w,0,S)},b.setImmediate=function(S){typeof S!="function"&&(S=new Function(""+S));for(var L=new Array(arguments.length-1),I=0;I"u"?s===void 0?this:s:self)}).call(this,typeof Bt<"u"?Bt:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(D_);var pM=D_.exports,Qf=Pi(pM);const B_={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(B_);var An=function(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)},ds,No,Li;class mM{constructor(...t){ds.set(this,new Map),No.set(this,new Map),Li.set(this,new Map);for(const n of t)this.define(n)}define(t,n=!1){for(let[r,i]of Object.entries(t)){r=r.toLowerCase(),i=i.map(a=>a.toLowerCase()),An(this,Li,"f").has(r)||An(this,Li,"f").set(r,new Set);const s=An(this,Li,"f").get(r);let o=!0;for(let a of i){const c=a.startsWith("*");if(a=c?a.slice(1):a,s==null||s.add(a),o&&An(this,No,"f").set(r,a),o=!1,c)continue;const l=An(this,ds,"f").get(a);if(l&&l!=r&&!n)throw new Error(`"${r} -> ${a}" conflicts with "${l} -> ${a}". Pass \`force=true\` to override this definition.`);An(this,ds,"f").set(a,r)}}return this}getType(t){if(typeof t!="string")return null;const n=t.replace(/^.*[/\\]/,"").toLowerCase(),r=n.replace(/^.*\./,"").toLowerCase(),i=n.length{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(const t of An(this,Li,"f").values())Object.freeze(t);return this}_getTestState(){return{types:An(this,ds,"f"),extensions:An(this,No,"f")}}}ds=new WeakMap,No=new WeakMap,Li=new WeakMap;var gM=new mM(B_)._freeze();function F_(e,t){switch([...t.slice(0,4)].map(i=>i.toString(16)).join("").toUpperCase()){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"FFD8FFDB":case"FFD8FFE0":case"FFD8FFE1":return"image/jpeg";case"504B0304":return"application/zip"}return gM.getType(e)??"application/octet-stream"}function yM(e){const t=vg(e,{}),n=Xn(t),r=Zs(t),i=Bn(Xe.MAIN);if(!k(i))return;const s=Xs(t),o=Iu(i,s,n);k(o)?yt("memory",`${i.name} already has a [${r}] named ${n}`):(Ag(i,t),z_(t.id,i.id),yt("memory",`created [${r}] ${n} in ${i.name}`))}async function _M(e){const t=await e.text();yM(t)}async function bM(e,t){try{yt("parsezipfile",e.name);const n=await e.arrayBuffer();(await new Qf().loadAsync(n)).forEach((s,o)=>{o.async("uint8array").then(a=>{const c=F_(s,a),l=new File([a],o.name,{type:c});t(l)}).catch(a=>{et("memory","crash",a.message)})})}catch(n){et("memory","crash",n.message)}}async function wM(e,t){try{yt("parsebinaryfile",e.name);const n=await e.arrayBuffer(),r=e.name.split(".").slice(-1)[0]??"";t(Pe(r),new Uint8Array(n))}catch(n){et("memory","crash",n.message)}}function eh(e){if(!e||e.type===void 0)return;const t=[{start:e.startOffset,end:e.endOffset??0}];return Object.keys(e).forEach(n=>{if(n!=="parent"){const r=e[n];Ge(r)?r.forEach(i=>{t.push(eh(i))}):t.push(eh(r))}}),e.range={start:Math.min(...t.filter(n=>n).map(n=>(n==null?void 0:n.start)??0)),end:Math.max(...t.filter(n=>n).map(n=>(n==null?void 0:n.end)??0))},e.range}function vM(e){const t=Um(`${e} +`);if(t.errors.length>0)return t;hs.input=t.tokens;const n=hs.program();if(hs.errors.length>0)return{tokens:t.tokens,errors:hs.errors.map(i=>({offset:i.token.startOffset,line:i.token.startLine,column:i.token.startColumn,length:i.token.image.length,message:i.message}))};const[r]=oM.go(n);return r?(eh(r),{tokens:t.tokens,cst:n,ast:r}):{tokens:t.tokens,cst:n,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]}}const th=Object.getPrototypeOf(function*(){}).constructor;function EM(e,t){const n=`compile-${e}`;console.time(n);const r=vM(t);if(console.timeEnd(n),r.errors&&r.errors.length>0)return r;if(!r.ast)return{...r,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]};const i=fM(r.ast);if(i.code){Vx&&console.info(i.code);try{return{...r,...i,source:i.code,code:new th("api",i.code)}}catch(s){return{errors:[{message:`unexpected error ${s.message}`,offset:0,line:0,column:0,length:0}],source:"",code:new th("api"," ")}}}return{...r,...i,source:"",code:new th("api"," ")}}function kM(){const e={},t={};function n(i,s){const o=e[s];if(o)return o;const a=EM(i,s);return e[s]=a,a}const r={ids(){return Object.keys(t)},has(i){return k(t[i])},isended(i){const s=t[i];return k(s)?s.isended():!0},halt(i){const s=t[i];return k(s)&&(s.halt(),delete t[i]),!!s},gc(){const i=r.ids();for(let s=0;s[_,w]);p.slice(h-5,h).forEach(([_,w])=>{et("os","build",`$grey${w+1} $grey${_}`)});const[m,b]=p[h]??[];if(Ce(m)&&k(b)){const _=(d.column??1)-1,w=_+d.length,v=_{et("os","build",_)}),!1}}return!!(l!=null&&l.tick(o))},once(i,s,o,a){const c=r.tick(i,s,1,o,a);return r.halt(i)&&c},message(i){const{target:s,path:o}=uh(i.target),a=t[s];if(k(a)){const c={...i,target:o};a.message(c)}}};return r}const Mr=EM();var Xe=(e=>(e.MAIN="main",e.TITLE="title",e.PLAYER="player",e.CONTENT="content",e.GADGETSTORE="gadgetstore",e.GADGETSYNC="gadgetsync",e))(Xe||{});const ct={defaultplayer:mb(),software:{main:"",content:""},books:new Map,chips:new Map,loaders:new Map,chipindex:new Map,codepageindex:new Map,binaryfiles:new Map};function kM(e){ct.defaultplayer=e}function SM(){return ct.defaultplayer}function Pc(){return[...ct.books.values()]}function AM(){const[e]=ct.books.values();return e}function ti(e){const t=Pe(e);return ct.books.get(e)??Pc().find(n=>n.name===t)}function Dc(e,t){k(ti(t))&&(ct.software[e]=t)}function nn(e){return ti(ct.software[e])}function $_(e){const t=Sg([]);return Ce(e)&&(t.name=e),j_(t),yt("memory",`created [book] ${t.name}`),t}function TM(e){let t=ti(e);return k(t)||(t=Sg([]),t.name=e),j_(t),yt("memory",`created [book] ${t.name}`),t}function Bn(e,t){let n=k(t)?TM(t):nn(e);return k(n)||(k(n)||(n=AM()),k(n)||(n=$_(t)),k(n)&&yt("memory",`opened [book] ${n.name} for ${e}`)),Dc(e,n.id),n}function Mi(e,t,n){const r=Bn(e);let i=yi(r,t);if(k(i))return i;const s=Eg(n);return i=vg(s==="object"?`@${t} +`).forEach(_=>{et("os","build",_)}),!1}}return!!(l!=null&&l.tick(o))},once(i,s,o,a){const c=r.tick(i,s,1,o,a);return r.halt(i)&&c},message(i){const{target:s,path:o}=uh(i.target),a=t[s];if(k(a)){const c={...i,target:o};a.message(c)}}};return r}const Mr=kM();var Xe=(e=>(e.MAIN="main",e.TITLE="title",e.PLAYER="player",e.CONTENT="content",e.GADGETSTORE="gadgetstore",e.GADGETSYNC="gadgetsync",e))(Xe||{});const ct={defaultplayer:mb(),software:{main:"",content:""},books:new Map,chips:new Map,loaders:new Map,chipindex:new Map,codepageindex:new Map,binaryfiles:new Map};function SM(e){ct.defaultplayer=e}function AM(){return ct.defaultplayer}function Pc(){return[...ct.books.values()]}function TM(){const[e]=ct.books.values();return e}function ti(e){const t=Pe(e);return ct.books.get(e)??Pc().find(n=>n.name===t)}function Dc(e,t){k(ti(t))&&(ct.software[e]=t)}function nn(e){return ti(ct.software[e])}function $_(e){const t=Sg([]);return Ce(e)&&(t.name=e),j_(t),yt("memory",`created [book] ${t.name}`),t}function xM(e){let t=ti(e);return k(t)||(t=Sg([]),t.name=e),j_(t),yt("memory",`created [book] ${t.name}`),t}function Bn(e,t){let n=k(t)?xM(t):nn(e);return k(n)||(k(n)||(n=TM()),k(n)||(n=$_(t)),k(n)&&yt("memory",`opened [book] ${n.name} for ${e}`)),Dc(e,n.id),n}function Mi(e,t,n){const r=Bn(e);let i=yi(r,t);if(k(i))return i;const s=Eg(n);return i=vg(s==="object"?`@${t} `:`@${s} ${t} -`,{}),Ag(r,i),z_(i.id,r.id),ni("memory"),i}function ps(e){const t=Bn("main");return Ys(t,e)}function xM(e){const t=Bn("main");return Ou(t,e)}function RM(e,t){ct.books.clear(),e.forEach(r=>{ct.books.set(r.id,r),r.name==="main"&&(ct.software.main=r.id)});const n=ti(t);if(k(n)&&Dc("main",n.id),!ct.software.main){const r=ct.books.values().next();r.value&&(ct.software.main=r.value.id)}}function j_(e){return ct.books.set(e.id,e),e.id}function IM(e){const t=ti(e);t&&ct.books.delete(t.id)}function z_(e,t){ct.codepageindex.set(e,t)}function OM(e){if(!Ce(e)||!e)return et("memory","login",`failed for playerid ==>${e}<==`,e);const t=nn("main");if(!k(t))return et("memory","login:main","login failed to find book 'main'",e);const n=ja(t,e);if(k(n))return!0;const r=Zi(t,"title");if(!k(r))return et("memory","login:title","login failed to find board 'title'",e);const i=$a(t,"player");if(!k(i))return et("memory","login:player","login failed to find object type 'player'",e);const s={x:0,y:0},o=i.name??"player",a=Bu(r,s,o,e);return k(a==null?void 0:a.id)?(Nu(t,e,r.id),!0):!1}function W_(e){const t=nn("main"),n=ja(t,e);Nu(t,e,""),Qs(t,n,Qi(n,e)),zg(n,e),Ou(t,e),Ou(t,P_(e))}function NM(e){const t=nn("main"),n=Ig(t);for(let r=0;rUh*5&&(n.tickertime=0,n.tickertext=""),C.isplayer){const u=ps(C.player);u.inputcurrent=0}aw(s).forEach(u=>{C[u]=s[u]})}function LM(){const e=nn("main");if(!k(e))return;const t=e.timestamp+1,n=Mc.HALT_AT_COUNT;Mc.HALT_AT_COUNT=n*2,ct.loaders.forEach((i,s)=>{Mr.tick(s,ko.LOADER,1,"loader",i),Mr.isended(s)&&(Mr.halt(s),ct.loaders.delete(s))}),Mc.HALT_AT_COUNT=n,e.timestamp=t,C.timestamp=t,Ig(e).forEach(i=>{const s=eI(e,i,t);for(let o=0;o{const c=Js(a);return Object.keys(c).filter(u=>s.includes(Pe(u))).length===s.length});for(let a=0;aet("memory","crash",i.message));break;case"application/zip":_M(t,i=>V_(e,i)).catch(i=>et("memory","crash",i.message));break;case"application/octet-stream":bM(t,(i,s)=>{PM(e,t,i,s)}).catch(i=>et("memory","crash",i.message));break;default:t.arrayBuffer().then(i=>{const s=F_(t.name,new Uint8Array(i));if(s)n(s);else return et("memory","loadfile",`unsupported file ${t.name}`)}).catch(i=>et("memory","crash",i.message));return}}n((t==null?void 0:t.type)??"")}let K_=0;function DM(){switch(K_++){case 0:return be.BLUE;case 1:return be.GREEN;case 2:return be.CYAN;case 3:return be.RED;case 4:return be.PURPLE;case 5:return be.YELLOW;default:return K_=0,be.WHITE}}function BM(e,t,n,r,i,s){const o=[];let a=t;const c=a===0,l=ze,u=rn,f=c?be.BLACK:be.ONCLEAR,d=fh(e,a++,l,u,f);o.push(d);const h=vb(e,a++,l,u);o.push(h);const p=a++,m=wb(e,p);o.push(m);const b=fh(e,a++,l,u,be.ONCLEAR);o.push(b);const _={...R_(ze,rn,DM(),be.ONCLEAR),...b},w=Eb(e,a++);i&&o.push(w),r.terrain.forEach((T,M)=>{if(T){const x=Ln(n,T);d.char[M]=T.char??(x==null?void 0:x.char)??0,d.color[M]=T.color??(x==null?void 0:x.color)??f,d.bg[M]=T.bg??(x==null?void 0:x.bg)??f,d.color[M]!==be.ONCLEAR&&(s[M]=d.color[M])}});const v=r.objects??{};Object.values(v).forEach(T=>{if(k(T.removed)||k(T.headless))return;const M=T.id??"",x=Tg(n,T),V=bb(e,p,M),oe=T.lx??T.x??0,O=T.ly??T.y??0,E=oe+O*ze;if(V.x=T.x??0,V.y=T.y??0,V.char=T.char??(x==null?void 0:x.char)??1,V.color=T.color??(x==null?void 0:x.color)??be.WHITE,V.bg=T.bg??(x==null?void 0:x.bg)??be.ONBORROW,m.sprites.push(V),V.bg===be.ONSHADOW&&(V.bg=be.ONCLEAR,h.alphas[oe+O*l]=.5),V.bg===be.ONBORROW&&(V.bg=s[E]??be.BLACK),V.color!==be.ONCLEAR&&(s[E]=V.color),Ce(T.tickertext)&&ke(T.tickertime)&&T.tickertext.length){const g=ze,N=ZL(T.tickertext,g,rn-1),W=(N==null?void 0:N.measuredwidth)??1,B=T.x??0,Z=T.y??0,H=Zze&&(_.x=ze-W),_.x<0&&(_.x=0),XL(T.tickertext,_)}M===e&&(w.focusx=V.x,w.focusy=V.y,w.focusid=M)});function S(T,M){if(!(T<0||T>=ze||M<0||M>=rn))return h.alphas[T+M*ze]}const L=[[1,1,1,1,1],[1,3,5,3,1],[1,5,12,5,1],[1,3,5,3,1],[1,1,1,1,1]].flat(),I=new Array(h.alphas.length);for(let T=0;Tk(oe)?oe*L[O]:void 0).filter(k);I[T]=si(_w(V),0,1)}return h.alphas=I,o}function FM(e){const t=nn("main"),n=ja(t,e),r=[];if(!k(t)||!k(n))return r;const i=new Array(ze*rn).fill(0),s=Zi(t,n.over??""),o=Zi(t,n.under??""),a=[s,n,o].filter(k);let c=0;for(let l=0;l{const r=new Qf;for(let i=0;i{t(jM(i))}).catch(n)})}async function GM(e){return new Promise((t,n)=>{const r=new Qf;r.loadAsync($M(e),{base64:!0}).then(async()=>{const i=[],s=[];r.forEach((o,a)=>s.push(a));for(let o=0;o{var t;switch(e.target){case"init":k(e.player)&&(kM(e.player),Fn.reply(e,"ackinit",!0,e.player));break;case"books":Wc("vm:books",async()=>{if(Ge(e.data)){const[n,r]=e.data,i=await GM(n),s=i.map(o=>o.name);RM(i,r),yt(Fn.name(),"reset by",e.sender,"with",...s,e.player),Fn.reply(e,"ackbooks",!0,e.player)}});break;case"login":e.player&&OM(e.player)&&(Ui[e.player]=0,yt(Fn.name(),"player login",e.player),Fn.reply(e,"acklogin",!0,e.player));break;case"endgame":Wc("vm:endgame",async()=>{e.player&&(W_(e.player),await J_(),Lb("vm"))});break;case"doot":e.player&&(Ui[e.player]=0,dh(Fn.name(),"active",e.player));break;case"input":if(e.player){const n=ps(e.player),[r=Ft.NONE,i=0]=e.data??[Ft.NONE,0];Ge(n.inputqueue)||(n.inputqueue=[]),r!==Ft.NONE&&n.inputqueue.push([r,i])}break;case"codewatch":if(e.player&&Ge(e.data)){const[n,r]=e.data;if(!k(ms[r])){const i=ph(n,r);ms[r]=e_(i,s=>{const o=ti(n),a=yi(o,r);k(a)&&(a.code=s,WR(a))})}Ur[n]=Ur[n]??{},Ur[n][r]=Ur[n][r]??new Set,Ur[n][r].add(e.player)}break;case"coderelease":if(e.player&&Ge(e.data)){const[n,r]=e.data;k(Ur[n])&&k(Ur[n][r])&&(Ur[n][r].delete(e.player),Ur[n][r].size===0&&((t=ms[r])==null||t.call(ms),ms[r]=void 0))}break;case"tick":e.player!=="locked"&&LM();break;case"second":{NM(Ui);const n=Object.keys(Ui);for(let r=0;r=HM&&(delete Ui[i],W_(i),yt(Fn.name(),"player logout",i),Fn.emit("logout",void 0,i))}++q_>=VM&&(q_=0,ni(Fn.name()));break}case"flush":Wc("vm:flush",J_);break;case"cli":k(e.player)&&UM(e.player,e.data);break;case"loadfile":k(e.player)&&V_(e.player,e.data);break;default:CM(e);break}});function KM(){Fn.emit("ready",void 0,SM())}rL(e=>{const t=nn(Xe.MAIN);if(!k(t))return Bf("");const n=Ys(t,Xe.GADGETSTORE);let r=n[e];return k(r)||(n[e]=r=Bf(e)),r});const X_=Po("gadgetserver",["tock"],e=>{const t=nn(Xe.MAIN),n=(t==null?void 0:t.activelist)??[],r=Ys(t,Xe.GADGETSYNC);switch(e.target){case"tock":for(let i=0;ipostMessage(e));onmessage=function(t){qM(t.data)},setTimeout(KM)})(); +`,{}),Ag(r,i),z_(i.id,r.id),ni("memory"),i}function ps(e){const t=Bn("main");return Ys(t,e)}function RM(e){const t=Bn("main");return Ou(t,e)}function IM(e,t){ct.books.clear(),e.forEach(r=>{ct.books.set(r.id,r),r.name==="main"&&(ct.software.main=r.id)});const n=ti(t);if(k(n)&&Dc("main",n.id),!ct.software.main){const r=ct.books.values().next();r.value&&(ct.software.main=r.value.id)}}function j_(e){return ct.books.set(e.id,e),e.id}function OM(e){const t=ti(e);t&&ct.books.delete(t.id)}function z_(e,t){ct.codepageindex.set(e,t)}function NM(e){if(!Ce(e)||!e)return et("memory","login",`failed for playerid ==>${e}<==`,e);const t=nn("main");if(!k(t))return et("memory","login:main","login failed to find book 'main'",e);const n=ja(t,e);if(k(n))return!0;const r=Zi(t,"title");if(!k(r))return et("memory","login:title","login failed to find board 'title'",e);const i=$a(t,"player");if(!k(i))return et("memory","login:player","login failed to find object type 'player'",e);const s={x:0,y:0},o=i.name??"player",a=Bu(r,s,o,e);return k(a==null?void 0:a.id)?(Nu(t,e,r.id),!0):!1}function W_(e){const t=nn("main"),n=ja(t,e);Nu(t,e,""),Qs(t,n,Qi(n,e)),zg(n,e),Ou(t,e),Ou(t,P_(e))}function CM(e){const t=nn("main"),n=Ig(t);for(let r=0;rUh*5&&(n.tickertime=0,n.tickertext=""),C.isplayer){const u=ps(C.player);u.inputcurrent=0}cw(s).forEach(u=>{C[u]=s[u]})}function MM(){const e=nn("main");if(!k(e))return;const t=e.timestamp+1,n=Mc.HALT_AT_COUNT;Mc.HALT_AT_COUNT=n*2,ct.loaders.forEach((i,s)=>{Mr.tick(s,ko.LOADER,1,"loader",i),Mr.isended(s)&&(Mr.halt(s),ct.loaders.delete(s))}),Mc.HALT_AT_COUNT=n,e.timestamp=t,C.timestamp=t,Ig(e).forEach(i=>{const s=tI(e,i,t);for(let o=0;o{const c=Js(a);return Object.keys(c).filter(u=>s.includes(Pe(u))).length===s.length});for(let a=0;aet("memory","crash",i.message));break;case"application/zip":bM(t,i=>V_(e,i)).catch(i=>et("memory","crash",i.message));break;case"application/octet-stream":wM(t,(i,s)=>{DM(e,t,i,s)}).catch(i=>et("memory","crash",i.message));break;default:t.arrayBuffer().then(i=>{const s=F_(t.name,new Uint8Array(i));if(s)n(s);else return et("memory","loadfile",`unsupported file ${t.name}`)}).catch(i=>et("memory","crash",i.message));return}}n((t==null?void 0:t.type)??"")}let K_=0;function BM(){switch(K_++){case 0:return be.BLUE;case 1:return be.GREEN;case 2:return be.CYAN;case 3:return be.RED;case 4:return be.PURPLE;case 5:return be.YELLOW;default:return K_=0,be.WHITE}}function FM(e,t,n,r,i,s){const o=[];let a=t;const c=a===0,l=ze,u=rn,f=c?be.BLACK:be.ONCLEAR,d=fh(e,a++,l,u,f);o.push(d);const h=vb(e,a++,l,u);o.push(h);const p=a++,m=wb(e,p);o.push(m);const b=fh(e,a++,l,u,be.ONCLEAR);o.push(b);const _={...R_(ze,rn,BM(),be.ONCLEAR),...b},w=Eb(e,a++);i&&o.push(w),r.terrain.forEach((T,M)=>{if(T){const x=Ln(n,T);d.char[M]=T.char??(x==null?void 0:x.char)??0,d.color[M]=T.color??(x==null?void 0:x.color)??f,d.bg[M]=T.bg??(x==null?void 0:x.bg)??f,d.color[M]!==be.ONCLEAR&&(s[M]=d.color[M])}});const v=r.objects??{};Object.values(v).forEach(T=>{if(k(T.removed)||k(T.headless))return;const M=T.id??"",x=Tg(n,T),V=bb(e,p,M),oe=T.lx??T.x??0,O=T.ly??T.y??0,E=oe+O*ze;if(V.x=T.x??0,V.y=T.y??0,V.char=T.char??(x==null?void 0:x.char)??1,V.color=T.color??(x==null?void 0:x.color)??be.WHITE,V.bg=T.bg??(x==null?void 0:x.bg)??be.ONBORROW,m.sprites.push(V),V.bg===be.ONSHADOW&&(V.bg=be.ONCLEAR,h.alphas[oe+O*l]=.5),V.bg===be.ONBORROW&&(V.bg=s[E]??be.BLACK),V.color!==be.ONCLEAR&&(s[E]=V.color),Ce(T.tickertext)&&ke(T.tickertime)&&T.tickertext.length){const g=ze,N=YL(T.tickertext,g,rn-1),W=(N==null?void 0:N.measuredwidth)??1,B=T.x??0,Z=T.y??0,H=Zze&&(_.x=ze-W),_.x<0&&(_.x=0),ZL(T.tickertext,_)}M===e&&(w.focusx=V.x,w.focusy=V.y,w.focusid=M)});function S(T,M){if(!(T<0||T>=ze||M<0||M>=rn))return h.alphas[T+M*ze]}const L=[[1,1,1,1,1],[1,3,5,3,1],[1,5,12,5,1],[1,3,5,3,1],[1,1,1,1,1]].flat(),I=new Array(h.alphas.length);for(let T=0;Tk(oe)?oe*L[O]:void 0).filter(k);I[T]=si(bw(V),0,1)}return h.alphas=I,o}function $M(e){const t=nn("main"),n=ja(t,e),r=[];if(!k(t)||!k(n))return r;const i=new Array(ze*rn).fill(0),s=Zi(t,n.over??""),o=Zi(t,n.under??""),a=[s,n,o].filter(k);let c=0;for(let l=0;l{const r=new Qf;for(let i=0;i{t(zM(i))}).catch(n)})}async function HM(e){return new Promise((t,n)=>{const r=new Qf;r.loadAsync(jM(e),{base64:!0}).then(async()=>{const i=[],s=[];r.forEach((o,a)=>s.push(a));for(let o=0;o{var t;switch(e.target){case"init":k(e.player)&&(SM(e.player),Fn.reply(e,"ackinit",!0,e.player));break;case"books":Wc("vm:books",async()=>{if(Ge(e.data)){const[n,r]=e.data,i=await HM(n),s=i.map(o=>o.name);IM(i,r),yt(Fn.name(),"reset by",e.sender,"with",...s,e.player),Fn.reply(e,"ackbooks",!0,e.player)}});break;case"login":e.player&&NM(e.player)&&(Ui[e.player]=0,yt(Fn.name(),"player login",e.player),Fn.reply(e,"acklogin",!0,e.player));break;case"endgame":Wc("vm:endgame",async()=>{e.player&&(W_(e.player),await J_(),Lb("vm"))});break;case"doot":e.player&&(Ui[e.player]=0,dh(Fn.name(),"active",e.player));break;case"input":if(e.player){const n=ps(e.player),[r=Ft.NONE,i=0]=e.data??[Ft.NONE,0];Ge(n.inputqueue)||(n.inputqueue=[]),r!==Ft.NONE&&n.inputqueue.push([r,i])}break;case"codewatch":if(e.player&&Ge(e.data)){const[n,r]=e.data;if(!k(ms[r])){const i=ph(n,r);ms[r]=e_(i,s=>{const o=ti(n),a=yi(o,r);k(a)&&(a.code=s,GR(a))})}Ur[n]=Ur[n]??{},Ur[n][r]=Ur[n][r]??new Set,Ur[n][r].add(e.player)}break;case"coderelease":if(e.player&&Ge(e.data)){const[n,r]=e.data;k(Ur[n])&&k(Ur[n][r])&&(Ur[n][r].delete(e.player),Ur[n][r].size===0&&((t=ms[r])==null||t.call(ms),ms[r]=void 0))}break;case"tick":e.player!=="locked"&&MM();break;case"second":{CM(Ui);const n=Object.keys(Ui);for(let r=0;r=VM&&(delete Ui[i],W_(i),yt(Fn.name(),"player logout",i),Fn.emit("logout",void 0,i))}++q_>=KM&&(q_=0,ni(Fn.name()));break}case"flush":Wc("vm:flush",J_);break;case"cli":k(e.player)&&PM(e.player,e.data);break;case"loadfile":k(e.player)&&V_(e.player,e.data);break;default:LM(e);break}});function qM(){Fn.emit("ready",void 0,AM())}iL(e=>{const t=nn(Xe.MAIN);if(!k(t))return Bf("");const n=Ys(t,Xe.GADGETSTORE);let r=n[e];return k(r)||(n[e]=r=Bf(e)),r});const X_=Po("gadgetserver",["tock"],e=>{const t=nn(Xe.MAIN),n=(t==null?void 0:t.activelist)??[],r=Ys(t,Xe.GADGETSYNC);switch(e.target){case"tock":for(let i=0;ipostMessage(e));onmessage=function(t){JM(t.data)},setTimeout(qM)})(); diff --git a/index.html b/index.html index c155623b..8640eb66 100644 --- a/index.html +++ b/index.html @@ -4,7 +4,7 @@ - ZSS - main:0.20.26:7bfc950d4e61d7af377857d8ab96111777468f44 + ZSS - main:0.20.27:c55f43dc559c59ad8253a6a04e136235e0210998 @@ -36,7 +36,7 @@ }(window.location)) - +