@idetik/core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -343,7 +343,7 @@ void main() {
343
343
  fragColor = vec4(color.rgb, alpha);
344
344
  }`;const pE={projectedLine:{vertex:ME,fragment:HE},points:{vertex:eE,fragment:qE},wireframe:{vertex:dE,fragment:fE},floatScalarImage:{vertex:dI,fragment:qB},floatScalarImageArray:{vertex:dI,fragment:dB},intScalarImage:{vertex:dI,fragment:qB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},intScalarImageArray:{vertex:dI,fragment:dB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:dI,fragment:qB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},uintScalarImageArray:{vertex:dI,fragment:dB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:dI,fragment:lE},floatVolume:{vertex:fB,fragment:lB},intVolume:{vertex:fB,fragment:lB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:fB,fragment:lB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},xQ={debug:10,info:20,warn:30,error:40},WE={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function mE(){const g=typeof process<"u"&&typeof process.env?.NODE_ENV=="string"?process.env.NODE_ENV:void 0;if(g==="production"||g==="development"||g==="test")return g;if(typeof window<"u"){const{NODE_ENV:A}=window;if(A==="production"||A==="development"||A==="test")return A}return"development"}class j{static logLevel_=mE()==="production"?"warn":"debug";static setLogLevel(A){j.logLevel_=A}static debug(A,I,...B){j.log("debug",A,I,...B)}static info(A,I,...B){j.log("info",A,I,...B)}static warn(A,I,...B){j.log("warn",A,I,...B)}static error(A,I,...B){j.log("error",A,I,...B)}static log(A,I,B,...Q){if(xQ[A]<xQ[j.logLevel_])return;const C=new Date().toISOString(),E=WE[A],i=`[${C}][${A.toUpperCase()}][${I}]`,o=[`${E}${i}`,B,...Q];switch(A){case"debug":console.debug(...o);break;case"info":console.info(...o);break;case"warn":console.warn(...o);break;case"error":console.error(...o);break}}}class TE{gl_;program_;uniformInfo_=new Map;constructor(A,I,B){this.gl_=A;const Q=A.createProgram();if(!Q)throw new Error("Failed to create WebGL shader program");this.program_=Q;const C=[];try{C.push(this.addShader(I,A.VERTEX_SHADER)),C.push(this.addShader(B,A.FRAGMENT_SHADER)),this.link(),this.preprocessUniformLocations()}catch(E){throw A.deleteProgram(Q),E}finally{C.forEach(E=>this.gl_.deleteShader(E))}}setUniform(A,I){const[B,Q]=this.uniformInfo_.get(A)??[];if(!B||!Q)throw new Error(`Uniform "${A}" not found in shader program`);const C=Q.type;switch(C){case this.gl_.BOOL:case this.gl_.FLOAT:typeof I=="number"?this.gl_.uniform1f(B,I):this.gl_.uniform1fv(B,I);break;case this.gl_.FLOAT_VEC2:this.gl_.uniform2fv(B,I);break;case this.gl_.FLOAT_VEC3:this.gl_.uniform3fv(B,I);break;case this.gl_.FLOAT_MAT4:this.gl_.uniformMatrix4fv(B,!1,I);break;case this.gl_.SAMPLER_2D:case this.gl_.SAMPLER_CUBE:case this.gl_.SAMPLER_3D:case this.gl_.SAMPLER_2D_ARRAY:case this.gl_.SAMPLER_2D_SHADOW:case this.gl_.SAMPLER_CUBE_SHADOW:case this.gl_.SAMPLER_2D_ARRAY_SHADOW:case this.gl_.INT_SAMPLER_2D:case this.gl_.INT_SAMPLER_3D:case this.gl_.INT_SAMPLER_CUBE:case this.gl_.INT_SAMPLER_2D_ARRAY:case this.gl_.UNSIGNED_INT_SAMPLER_2D:case this.gl_.UNSIGNED_INT_SAMPLER_3D:case this.gl_.UNSIGNED_INT_SAMPLER_CUBE:case this.gl_.UNSIGNED_INT_SAMPLER_2D_ARRAY:this.gl_.uniform1i(B,I);break;default:{const E=C;throw new Error(`Unhandled uniform type: ${E}`)}}}preprocessUniformLocations(){const A=this.gl_.getProgramParameter(this.program_,this.gl_.ACTIVE_UNIFORMS);for(let I=0;I<A;I++){const B=this.gl_.getActiveUniform(this.program_,I);if(B){if(!ZE.has(B.type))throw new Error(`Unsupported uniform type "${B.type}" (GLenum) found in shader program for uniform "${B.name}"`);const Q=this.gl_.getUniformLocation(this.program_,B.name);Q&&(this.uniformInfo_.set(B.name,[Q,B]),j.debug("WebGLShaderProgram","Uniform found:",B.name,B.type,B.size))}}}addShader(A,I){const B=this.gl_.createShader(I);if(!B)throw new Error(`Failed to create a new shader of type ${I}`);if(this.gl_.shaderSource(B,A),this.gl_.compileShader(B),!this.gl_.getShaderParameter(B,this.gl_.COMPILE_STATUS)){const Q=this.gl_.getShaderInfoLog(B);throw this.gl_.deleteShader(B),new Error(`Error compiling shader: ${Q}`)}return this.gl_.attachShader(this.program_,B),B}link(){if(this.gl_.linkProgram(this.program_),!this.getParameter(this.gl_.LINK_STATUS)){const A=this.gl_.getProgramInfoLog(this.program_);throw new Error(`Error linking program: ${A}`)}}use(){this.gl_.useProgram(this.program_)}getParameter(A){return this.gl_.getProgramParameter(this.program_,A)}get uniformNames(){return Array.from(this.uniformInfo_.keys())}}const xE=typeof window<"u"?[WebGL2RenderingContext.BOOL,WebGL2RenderingContext.FLOAT,WebGL2RenderingContext.FLOAT_VEC2,WebGL2RenderingContext.FLOAT_VEC3,WebGL2RenderingContext.FLOAT_MAT4,WebGL2RenderingContext.SAMPLER_2D,WebGL2RenderingContext.SAMPLER_CUBE,WebGL2RenderingContext.SAMPLER_3D,WebGL2RenderingContext.SAMPLER_2D_ARRAY,WebGL2RenderingContext.SAMPLER_2D_SHADOW,WebGL2RenderingContext.SAMPLER_CUBE_SHADOW,WebGL2RenderingContext.SAMPLER_2D_ARRAY_SHADOW,WebGL2RenderingContext.INT_SAMPLER_2D,WebGL2RenderingContext.INT_SAMPLER_3D,WebGL2RenderingContext.INT_SAMPLER_CUBE,WebGL2RenderingContext.INT_SAMPLER_2D_ARRAY,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_3D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_CUBE,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D_ARRAY]:[],ZE=new Set(xE),pB="#pragma inject_defines";class bE{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const B=pE[A],Q=ZQ(B.vertex,B.vertexDefines),C=ZQ(B.fragment,B.fragmentDefines);I=new TE(this.gl_,Q,C),I.use();const E=this.gl_.getError();if(E!==this.gl_.NO_ERROR)throw new Error(`Error using WebGL program: ${E}`);this.programs_.set(A,I)}else I.use();return I}}function ZQ(g,A){if(A===void 0||A.size==0)return g;if(!g.includes(pB))throw new Error(`Shader source does not contain "${pB}" directive`);const I=Array(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
345
345
  `),Q=`#line __LINE__ + ${1-A.size}`,C=`${I}
346
- ${Q}`;return g.replace(pB,C)}const ZA=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];function bQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(ZA[g&255]+ZA[g>>8&255]+ZA[g>>16&255]+ZA[g>>24&255]+"-"+ZA[A&255]+ZA[A>>8&255]+"-"+ZA[A>>16&15|64]+ZA[A>>24&255]+"-"+ZA[I&63|128]+ZA[I>>8&255]+"-"+ZA[I>>16&255]+ZA[I>>24&255]+ZA[B&255]+ZA[B>>8&255]+ZA[B>>16&255]+ZA[B>>24&255]).toLowerCase()}class WB{uuid=bQ()}var fI=1e-6,lA=typeof Float32Array<"u"?Float32Array:Array,uE=Math.PI/180;function PE(g){return g*uE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function uQ(){var g=new lA(9);return lA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[5]=0,g[6]=0,g[7]=0),g[0]=1,g[4]=1,g[8]=1,g}function OE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[4],g[4]=A[5],g[5]=A[6],g[6]=A[8],g[7]=A[9],g[8]=A[10],g}function QI(){var g=new lA(16);return lA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=0,g[12]=0,g[13]=0,g[14]=0),g[0]=1,g[5]=1,g[10]=1,g[15]=1,g}function mB(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],o=A[6],h=A[7],s=A[8],R=A[9],N=A[10],r=A[11],M=A[12],e=A[13],n=A[14],f=A[15],V=I*i-B*E,m=I*o-Q*E,b=I*h-C*E,u=B*o-Q*i,W=B*h-C*i,gA=Q*h-C*o,O=s*e-R*M,x=s*n-N*M,$=s*f-r*M,IA=R*n-N*e,wA=R*f-r*e,kA=N*f-r*n,CA=V*kA-m*wA+b*IA+u*$-W*x+gA*O;return CA?(CA=1/CA,g[0]=(i*kA-o*wA+h*IA)*CA,g[1]=(Q*wA-B*kA-C*IA)*CA,g[2]=(e*gA-n*W+f*u)*CA,g[3]=(N*W-R*gA-r*u)*CA,g[4]=(o*$-E*kA-h*x)*CA,g[5]=(I*kA-Q*$+C*x)*CA,g[6]=(n*b-M*gA-f*m)*CA,g[7]=(s*gA-N*b+r*m)*CA,g[8]=(E*wA-i*$+h*O)*CA,g[9]=(B*$-I*wA-C*O)*CA,g[10]=(M*W-e*b+f*V)*CA,g[11]=(R*b-s*W-r*V)*CA,g[12]=(i*x-E*IA-o*O)*CA,g[13]=(I*IA-B*x+Q*O)*CA,g[14]=(e*m-M*u-n*V)*CA,g[15]=(s*u-R*m+N*V)*CA,g):null}function DB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],o=A[5],h=A[6],s=A[7],R=A[8],N=A[9],r=A[10],M=A[11],e=A[12],n=A[13],f=A[14],V=A[15],m=I[0],b=I[1],u=I[2],W=I[3];return g[0]=m*B+b*i+u*R+W*e,g[1]=m*Q+b*o+u*N+W*n,g[2]=m*C+b*h+u*r+W*f,g[3]=m*E+b*s+u*M+W*V,m=I[4],b=I[5],u=I[6],W=I[7],g[4]=m*B+b*i+u*R+W*e,g[5]=m*Q+b*o+u*N+W*n,g[6]=m*C+b*h+u*r+W*f,g[7]=m*E+b*s+u*M+W*V,m=I[8],b=I[9],u=I[10],W=I[11],g[8]=m*B+b*i+u*R+W*e,g[9]=m*Q+b*o+u*N+W*n,g[10]=m*C+b*h+u*r+W*f,g[11]=m*E+b*s+u*M+W*V,m=I[12],b=I[13],u=I[14],W=I[15],g[12]=m*B+b*i+u*R+W*e,g[13]=m*Q+b*o+u*N+W*n,g[14]=m*C+b*h+u*r+W*f,g[15]=m*E+b*s+u*M+W*V,g}function VE(g,A){return g[0]=A[0],g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=A[1],g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=A[2],g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g}function XE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=Q+Q,h=C+C,s=E+E,R=Q*o,N=Q*h,r=Q*s,M=C*h,e=C*s,n=E*s,f=i*o,V=i*h,m=i*s,b=B[0],u=B[1],W=B[2];return g[0]=(1-(M+n))*b,g[1]=(N+m)*b,g[2]=(r-V)*b,g[3]=0,g[4]=(N-m)*u,g[5]=(1-(R+n))*u,g[6]=(e+f)*u,g[7]=0,g[8]=(r+V)*W,g[9]=(e-f)*W,g[10]=(1-(R+M))*W,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function vE(g,A,I,B,Q){var C=1/Math.tan(A/2),E;return g[0]=C/I,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=C,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=-1,g[12]=0,g[13]=0,g[15]=0,Q!=null&&Q!==1/0?(E=1/(B-Q),g[10]=(Q+B)*E,g[14]=2*Q*B*E):(g[10]=-1,g[14]=-2*B),g}var jE=vE;function zE(g,A,I,B,Q,C,E){var i=1/(A-I),o=1/(B-Q),h=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*o,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*h,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*o,g[14]=(E+C)*h,g[15]=1,g}var _E=zE;function $E(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],o=B[1],h=B[2],s=Q-I[0],R=C-I[1],N=E-I[2],r=s*s+R*R+N*N;r>0&&(r=1/Math.sqrt(r),s*=r,R*=r,N*=r);var M=o*N-h*R,e=h*s-i*N,n=i*R-o*s;return r=M*M+e*e+n*n,r>0&&(r=1/Math.sqrt(r),M*=r,e*=r,n*=r),g[0]=M,g[1]=e,g[2]=n,g[3]=0,g[4]=R*n-N*e,g[5]=N*M-s*n,g[6]=s*e-R*M,g[7]=0,g[8]=s,g[9]=R,g[10]=N,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function rA(){var g=new lA(3);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function CI(g){var A=new lA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function PQ(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function NA(g,A,I){var B=new lA(3);return B[0]=g,B[1]=A,B[2]=I,B}function tg(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function _I(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function OQ(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function Ai(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function Ii(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function VQ(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function XQ(g,A,I,B){return g[0]=A[0]+I[0]*B,g[1]=A[1]+I[1]*B,g[2]=A[2]+I[2]*B,g}function vQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return Math.hypot(I,B,Q)}function gi(g,A){var I=A[0],B=A[1],Q=A[2],C=I*I+B*B+Q*Q;return C>0&&(C=1/Math.sqrt(C)),g[0]=A[0]*C,g[1]=A[1]*C,g[2]=A[2]*C,g}function jQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function TB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return g[0]=Q*o-C*i,g[1]=C*E-B*o,g[2]=B*i-Q*E,g}function Bi(g,A,I,B,Q,C){var E=1-C,i=E*E,o=C*C,h=i*E,s=3*C*i,R=3*o*E,N=o*C;return g[0]=A[0]*h+I[0]*s+B[0]*R+Q[0]*N,g[1]=A[1]*h+I[1]*s+B[1]*R+Q[1]*N,g[2]=A[2]*h+I[2]*s+B[2]*R+Q[2]*N,g}function oB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[3]*B+I[7]*Q+I[11]*C+I[15];return E=E||1,g[0]=(I[0]*B+I[4]*Q+I[8]*C+I[12])/E,g[1]=(I[1]*B+I[5]*Q+I[9]*C+I[13])/E,g[2]=(I[2]*B+I[6]*Q+I[10]*C+I[14])/E,g}function Qi(g,A){var I=g[0],B=g[1],Q=g[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=fI*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=fI*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=fI*Math.max(1,Math.abs(Q),Math.abs(i))}var xB=Ai,Ci=PQ;(function(){var g=rA();return function(A,I,B,Q,C,E){var i,o;for(I||(I=3),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2];return A}})();function cg(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function Ei(g){var A=new lA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function ZB(g,A,I,B){var Q=new lA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function ii(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function Di(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g[3]=A[3]*I,g}function oi(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=I*I+B*B+Q*Q+C*C;return E>0&&(E=1/Math.sqrt(E)),g[0]=I*E,g[1]=B*E,g[2]=Q*E,g[3]=C*E,g}function aB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3];return g[0]=I[0]*B+I[4]*Q+I[8]*C+I[12]*E,g[1]=I[1]*B+I[5]*Q+I[9]*C+I[13]*E,g[2]=I[2]*B+I[6]*Q+I[10]*C+I[14]*E,g[3]=I[3]*B+I[7]*Q+I[11]*C+I[15]*E,g}(function(){var g=cg();return function(A,I,B,Q,C,E){var i,o;for(I||(I=4),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],g[3]=A[i+3],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2],A[i+3]=g[3];return A}})();function bB(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function ai(g,A,I){I=I*.5;var B=Math.sin(I);return g[0]=B*A[0],g[1]=B*A[1],g[2]=B*A[2],g[3]=Math.cos(I),g}function si(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],o=I[1],h=I[2],s=I[3];return g[0]=B*s+E*i+Q*h-C*o,g[1]=Q*s+E*o+C*i-B*h,g[2]=C*s+E*h+B*o-Q*i,g[3]=E*s-B*i-Q*o-C*h,g}function uB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=I[0],h=I[1],s=I[2],R=I[3],N,r,M,e,n;return r=Q*o+C*h+E*s+i*R,r<0&&(r=-r,o=-o,h=-h,s=-s,R=-R),1-r>fI?(N=Math.acos(r),M=Math.sin(N),e=Math.sin((1-B)*N)/M,n=Math.sin(B*N)/M):(e=1-B,n=B),g[0]=e*Q+n*o,g[1]=e*C+n*h,g[2]=e*E+n*s,g[3]=e*i+n*R,g}function zQ(g,A){var I=A[0]+A[4]+A[8],B;if(I>0)B=Math.sqrt(I+1),g[3]=.5*B,B=.5/B,g[0]=(A[5]-A[7])*B,g[1]=(A[6]-A[2])*B,g[2]=(A[1]-A[3])*B;else{var Q=0;A[4]>A[0]&&(Q=1),A[8]>A[Q*3+Q]&&(Q=2);var C=(Q+1)%3,E=(Q+2)%3;B=Math.sqrt(A[Q*3+Q]-A[C*3+C]-A[E*3+E]+1),g[Q]=.5*B,B=.5/B,g[3]=(A[C*3+E]-A[E*3+C])*B,g[C]=(A[C*3+Q]+A[Q*3+C])*B,g[E]=(A[E*3+Q]+A[Q*3+E])*B}return g}var yi=Ei,hi=ii,PB=oi;(function(){var g=rA(),A=NA(1,0,0),I=NA(0,1,0);return function(B,Q,C){var E=jQ(Q,C);return E<-.999999?(TB(g,A,Q),Ci(g)<1e-6&&TB(g,I,Q),gi(g,g),ai(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(TB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,PB(B,B))}})(),function(){var g=bB(),A=bB();return function(I,B,Q,C,E,i){return uB(g,B,E,i),uB(A,Q,C,i),uB(I,g,A,2*i*(1-i)),I}}(),function(){var g=uQ();return function(A,I,B,Q){return g[0]=B[0],g[3]=B[1],g[6]=B[2],g[1]=Q[0],g[4]=Q[1],g[7]=Q[2],g[2]=-I[0],g[5]=-I[1],g[8]=-I[2],PB(A,zQ(A,g))}}();function _Q(){var g=new lA(2);return lA!=Float32Array&&(g[0]=0,g[1]=0),g}function $Q(g){var A=new lA(2);return A[0]=g[0],A[1]=g[1],A}function pA(g,A){var I=new lA(2);return I[0]=g,I[1]=A,I}function Gi(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function Fi(g){var A=g[0],I=g[1];return A*A+I*I}function wi(g,A,I,B){var Q=A[0],C=A[1];return g[0]=Q+B*(I[0]-Q),g[1]=C+B*(I[1]-C),g}function AC(g,A){return g[0]===A[0]&&g[1]===A[1]}function OB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=fI*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=fI*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=_Q();return function(A,I,B,Q,C,E){var i,o;for(I||(I=2),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;i+=I)g[0]=A[i],g[1]=A[i+1],C(g,g,E),A[i]=g[0],A[i+1]=g[1];return A}})();class tI{min;max;constructor(A,I){this.min=A?CI(A):NA(1/0,1/0,1/0),this.max=I?CI(I):NA(-1/0,-1/0,-1/0)}clone(){return new tI(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]||this.max[2]<=this.min[2]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1]||A.max[2]<=I.min[2]||A.min[2]>=I.max[2])}expandWithPoint(A){A[0]<this.min[0]&&(this.min[0]=A[0]),A[1]<this.min[1]&&(this.min[1]=A[1]),A[2]<this.min[2]&&(this.min[2]=A[2]),A[0]>this.max[0]&&(this.max[0]=A[0]),A[1]>this.max[1]&&(this.max[1]=A[1]),A[2]>this.max[2]&&(this.max[2]=A[2])}applyTransform(A){const{min:I,max:B}=this,Q=[NA(I[0],I[1],I[2]),NA(I[0],I[1],B[2]),NA(I[0],B[1],I[2]),NA(I[0],B[1],B[2]),NA(B[0],I[1],I[2]),NA(B[0],I[1],B[2]),NA(B[0],B[1],I[2]),NA(B[0],B[1],B[2])];this.min=NA(1/0,1/0,1/0),this.max=NA(-1/0,-1/0,-1/0);const C=rA();for(const E of Q)oB(C,E,A),this.expandWithPoint(C)}}const Si={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class $I extends WB{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],B="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=B,this.attributes_=[]}addAttribute(A){this.attributes_.push(A),this.boundingBox_=null}get vertexCount(){return this.vertexData_.byteLength/this.strideBytes}get stride(){return this.attributes_.reduce((A,I)=>A+I.itemSize,0)}get strideBytes(){return this.stride*Float32Array.BYTES_PER_ELEMENT}get primitive(){return this.primitive_}get vertexData(){return this.vertexData_}get indexData(){return this.indexData_}get attributes(){return this.attributes_}get boundingBox(){if(this.boundingBox_===null){const A=this.getAttribute("position");if(!A||this.vertexCount===0)throw new Error("Failed to generate bounding box");const I=(A.offset??0)/Float32Array.BYTES_PER_ELEMENT,B=new tI,Q=rA();for(let C=0;C<this.vertexData_.length;C+=this.stride)Q[0]=this.vertexData_[C+I+0],Q[1]=this.vertexData_[C+I+1],Q[2]=this.vertexData_[C+I+2],B.expandWithPoint(Q);this.boundingBox_=B}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class Ri{gl_;buffers_=new Map;currentGeometry_=null;constructor(A){this.gl_=A}bindGeometry(A){if(this.alreadyActive(A))return;this.buffers_.has(A)||this.generateBuffers(A);const I=this.buffers_.get(A);if(!I)throw new Error("Failed to retrieve buffer handles for object");this.gl_.bindVertexArray(I.vao),this.currentGeometry_=A}disposeObject(A){const I=this.buffers_.get(A);I&&(this.gl_.deleteVertexArray(I.vao),this.gl_.deleteBuffer(I.vbo),I.ebo&&this.gl_.deleteBuffer(I.ebo),this.buffers_.delete(A),this.currentGeometry_===A&&(this.currentGeometry_=null))}disposeAll(){for(const A of this.buffers_.keys())this.disposeObject(A)}alreadyActive(A){return this.currentGeometry_===A}generateBuffers(A){const I=this.gl_.createVertexArray();if(!I)throw new Error("Failed to create vertex array object (VAO)");this.gl_.bindVertexArray(I);const{vertexData:B}=A,Q=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(Q,C),this.gl_.bufferData(Q,B,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(s=>{const R=Si[s.type];this.gl_.vertexAttribPointer(R,s.itemSize,this.gl_.FLOAT,!1,i,s.offset),this.gl_.enableVertexAttribArray(R)});const o={vao:I,vbo:C},{indexData:h}=A;if(h.length){const s=this.gl_.ELEMENT_ARRAY_BUFFER,R=this.gl_.createBuffer();if(!R)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(s,R),this.gl_.bufferData(s,h,this.gl_.STATIC_DRAW),o.ebo=R}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class Ni{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}bindTexture(A,I){if(this.alreadyActive(A))return;if(I<0||I>=this.maxTextureUnits_)throw new Error(`Texture index ${I} must be in [0, ${this.maxTextureUnits_-1}]`);this.gl_.activeTexture(this.gl_.TEXTURE0+I);const B=this.getTextureType(A),Q=this.getDataFormatInfo(A.dataFormat,A.dataType);this.textures_.has(A)||this.generateTexture(A,Q,B);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(B,C),A.needsUpdate&&A.data!==null&&(this.configureTextureParameters(A,B),this.uploadTextureData(A,Q,B),A.needsUpdate=!1),this.currentTexture_=A}disposeTexture(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),this.currentTexture_===A&&(this.currentTexture_=null);const B=this.getDataFormatInfo(A.dataFormat,A.dataType),Q=this.computeStorageBytes(A,B);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-Q),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.disposeTexture(A);this.gpuTextureBytes_=0,this.textureCount_=0}get textureInfo(){return{textures:this.textureCount_,totalBytes:this.gpuTextureBytes_}}alreadyActive(A){return this.currentTexture_===A&&!A.needsUpdate}generateTexture(A,I,B){const Q=this.gl_.createTexture();if(!Q)throw new Error("Failed to create texture");if(this.gl_.bindTexture(B,Q),this.isTexture2D(A))this.gl_.texStorage2D(B,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(B,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=this.computeStorageBytes(A,I),this.textureCount_+=1,this.textures_.set(A,Q),this.gl_.bindTexture(B,null)}configureTextureParameters(A,I){const B=this.gl_,Q=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);B.pixelStorei(B.UNPACK_ALIGNMENT,A.unpackAlignment),B.texParameteri(I,B.TEXTURE_MIN_FILTER,Q),B.texParameteri(I,B.TEXTURE_MAG_FILTER,C),B.texParameteri(I,B.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),B.texParameteri(I,B.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),B.texParameteri(I,B.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,B){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(B,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(B,0,C.x,C.y,C.z,A.width,A.height,A.depth,I.format,I.type,A.data);else throw new Error("Attempting to upload data for an unsupported texture type")}getFilter(A,I){const{dataFormat:B,dataType:Q}=I;if(B==="scalar"&&Q!=="float"&&A!=="nearest")return j.warn("WebGLTexture","Integer values are not filterable. Using gl.NEAREST instead."),this.gl_.NEAREST;switch(A){case"nearest":return this.gl_.NEAREST;case"linear":return this.gl_.LINEAR;default:throw new Error(`Unsupported texture filter: ${A}`)}}getTextureType(A){if(this.isTexture2D(A))return this.gl_.TEXTURE_2D;if(this.isTexture2DArray(A))return this.gl_.TEXTURE_2D_ARRAY;if(this.isTexture3D(A))return this.gl_.TEXTURE_3D;throw new Error(`Unknown texture type ${A.type}`)}getWrapMode(A){switch(A){case"repeat":return this.gl_.REPEAT;case"clamp_to_edge":return this.gl_.CLAMP_TO_EDGE;default:throw new Error(`Unsupported wrap mode: ${A}`)}}getDataFormatInfo(A,I){if(A==="rgba"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGBA8,format:this.gl_.RGBA,type:this.gl_.UNSIGNED_BYTE};if(A==="rgb"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGB8,format:this.gl_.RGB,type:this.gl_.UNSIGNED_BYTE};if(A==="scalar")switch(I){case"byte":return{internalFormat:this.gl_.R8I,format:this.gl_.RED_INTEGER,type:this.gl_.BYTE};case"short":return{internalFormat:this.gl_.R16I,format:this.gl_.RED_INTEGER,type:this.gl_.SHORT};case"int":return{internalFormat:this.gl_.R32I,format:this.gl_.RED_INTEGER,type:this.gl_.INT};case"unsigned_byte":return{internalFormat:this.gl_.R8UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_BYTE};case"unsigned_short":return{internalFormat:this.gl_.R16UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_SHORT};case"unsigned_int":return{internalFormat:this.gl_.R32UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_INT};case"float":return{internalFormat:this.gl_.R32F,format:this.gl_.RED,type:this.gl_.FLOAT};default:throw new Error(`Unsupported scalar type: ${I}`)}throw new Error(`Unsupported format/type: ${A}/${I}`)}computeStorageBytes(A,I){const B=this.bytesPerTexel(I),Q=Math.max(1,A.mipmapLevels),C=this.isTextureStorage3D(A)?Math.max(1,A.depth):1;let E=Math.max(1,A.width),i=Math.max(1,A.height),o=0;for(let h=0;h<Q;h++)o+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class jA{min;max;constructor(A,I){this.min=A?$Q(A):pA(1/0,1/0),this.max=I?$Q(I):pA(-1/0,-1/0)}clone(){return new jA(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1])}static equals(A,I){return AC(A.min,I.min)&&AC(A.max,I.max)}floor(){return new jA(pA(Math.floor(this.min[0]),Math.floor(this.min[1])),pA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],B=this.max[0]-this.min[0],Q=this.max[1]-this.min[1];return{x:A,y:I,width:B,height:Q}}}class Ui{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;constructor(A){this.gl_=A}enable(A){this.enabledCapabilities_.get(A)||(this.gl_.enable(A),this.enabledCapabilities_.set(A,!0))}disable(A){this.enabledCapabilities_.get(A)&&(this.gl_.disable(A),this.enabledCapabilities_.set(A,!1))}setBlendFunc(A,I){(this.blendSrcFactor_!==A||this.blendDstFactor_!==I)&&(this.gl_.blendFunc(A,I),this.blendSrcFactor_=A,this.blendDstFactor_=I)}setDepthTesting(A){A?this.enable(this.gl_.DEPTH_TEST):this.disable(this.gl_.DEPTH_TEST)}setBlending(A){A?this.enable(this.gl_.BLEND):this.disable(this.gl_.BLEND)}setDepthMask(A){this.depthMaskEnabled_!==A&&(this.gl_.depthMask(A),this.depthMaskEnabled_=A)}setBlendingMode(A){if(this.currentBlendingMode_!==A){if(A==="none")this.setBlending(!1);else switch(this.setBlending(!0),A){case"additive":this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE);break;case"multiply":this.setBlendFunc(this.gl_.DST_COLOR,this.gl_.ZERO);break;case"subtractive":this.setBlendFunc(this.gl_.ZERO,this.gl_.ONE_MINUS_SRC_COLOR);break;case"normal":default:this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE_MINUS_SRC_ALPHA);break}this.currentBlendingMode_=A}}setViewport(A){const I=A.floor();if(this.currentViewport_&&jA.equals(I,this.currentViewport_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.viewport(B,Q,C,E),this.currentViewport_=I}setScissorTest(A){A?this.enable(this.gl_.SCISSOR_TEST):(this.disable(this.gl_.SCISSOR_TEST),this.currentScissor_=null)}setScissor(A){const I=A.floor();if(this.currentScissor_&&jA.equals(I,this.currentScissor_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.scissor(B,Q,C,E),this.currentScissor_=I}}const ki=VE(QI(),[1,-1,1]);class IC extends KE{gl_=null;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;constructor(A){if(super(A),this.gl_=this.canvas.getContext("webgl2",{depth:!0,antialias:!0}),!this.gl_)throw new Error("Failed to initialize WebGL2 context");j.info("WebGLRenderer",`WebGL version ${this.gl.getParameter(this.gl.VERSION)}`),this.programs_=new bE(this.gl),this.bindings_=new Ri(this.gl),this.textures_=new Ni(this.gl),this.state_=new Ui(this.gl),this.resize(this.canvas.width,this.canvas.height)}render(A){const I=A.getBoxRelativeTo(this.canvas),B=new jA(pA(0,0),pA(this.width,this.height));if(jA.equals(I.floor(),B.floor()))this.state_.setScissorTest(!1);else if(jA.intersects(I,B))this.state_.setScissor(I),this.state_.setScissorTest(!0);else{j.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(I),this.renderedObjectsPerFrame_=0,this.clear();const{opaque:Q,transparent:C}=A.layerManager.partitionLayers();this.state_.setDepthMask(!0);const E=A.camera.frustum;for(const i of Q)i.update(),i.state==="ready"&&this.renderLayer(i,A.camera,E);this.state_.setDepthMask(!1);for(const i of C)i.update(),i.state==="ready"&&this.renderLayer(i,A.camera,E);this.state_.setDepthMask(!0),this.renderedObjects_=this.renderedObjectsPerFrame_}get textureInfo(){return this.textures_.textureInfo}renderLayer(A,I,B){this.state_.setBlendingMode(A.transparent?A.blendMode:"none"),A.objects.forEach((Q,C)=>{B.intersectsWithBox3(Q.boundingBox)&&(this.renderObject(A,C,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];this.bindings_.bindGeometry(Q.geometry),Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),Q.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(Q.programName);if(this.drawGeometry(Q.geometry,Q,A,C,B),Q.wireframeEnabled){this.bindings_.bindGeometry(Q.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",Q.wireframeColor.rgb),this.drawGeometry(Q.wireframeGeometry,Q,A,E,B)}}drawGeometry(A,I,B,Q,C){const E=DB(QI(),C.viewMatrix,I.transform.matrix),i=DB(QI(),ki,C.projectionMatrix),o=[this.canvas.width,this.canvas.height],h=I.getUniforms();for(const N of Q.uniformNames)switch(N){case"ModelView":Q.setUniform(N,E);break;case"Projection":Q.setUniform(N,i);break;case"Resolution":Q.setUniform(N,o);break;case"u_opacity":Q.setUniform(N,B.opacity);break;default:N in h&&Q.setUniform(N,h[N])}const s=this.glGetPrimitive(A.primitive),R=A.indexData;R.length?this.gl.drawElements(s,R.length,this.gl.UNSIGNED_INT,0):this.gl.drawArrays(s,0,A.vertexCount)}glGetPrimitive(A){switch(A){case"points":return this.gl.POINTS;case"triangles":return this.gl.TRIANGLES;case"lines":return this.gl.LINES;default:{const I=A;throw new Error(`Unknown Primitive type: ${I}`)}}}resize(A,I){const B=new jA(pA(0,0),pA(A,I));this.state_.setViewport(B)}clear(){this.gl.clearColor(...this.backgroundColor.rgba),this.gl.clear(this.gl.COLOR_BUFFER_BIT|this.gl.DEPTH_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl.depthFunc(this.gl.LEQUAL)}get gl(){return this.gl_}}const ti=8;class ci{maxConcurrent_;pending_=[];running_=new Map;constructor(A=ti){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(B=>B.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(Q=>Q.chunk===A);if(I>=0){this.pending_.splice(I,1),j.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),j.debug("ChunkQueue","Cancelled fetch request"))}get pendingCount(){return this.pending_.length}get runningCount(){return this.running_.size}pump(){if(!(this.running_.size>=this.maxConcurrent_||this.pending_.length===0))for(this.pending_.sort((A,I)=>{const B=A.chunk.priority??Number.MAX_SAFE_INTEGER,Q=I.chunk.priority??Number.MAX_SAFE_INTEGER;return B===Q?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):B-Q});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:B}=A;I.state="loading";const Q=new AbortController,C=Promise.resolve().then(()=>B(Q.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&j.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const gC=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function BC(g){if(gC.some(I=>g instanceof I))return!0;const A=gC.map(I=>I.name);return j.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function Li(g,A){return Math.round((A-g.translation)/g.scale)}function VB(g,A,I=1e-6){return Math.abs(g-A)<=I}function Lg(g,A,I){return Math.max(A,Math.min(I,g))}const QC=Symbol("INTERNAL_POLICY_KEY");class Ji{chunks_;loader_;lowestResLOD_;sliceCoords_;dimensions_;tIndicesWithQueuedChunks_=new Set;sourceMaxSquareDistance2D_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastZBounds_;lastTCoord_;constructor(A,I,B){this.loader_=A,this.policy_=B,this.dimensions_=this.loader_.getSourceDimensionMap(),this.lowestResLOD_=this.dimensions_.numLods-1,this.currentLOD_=0,this.sliceCoords_=I,j.info("ChunkManagerSource","Using image source policy:",this.policy_.profile),this.validateXYScaleRatios();const{size:Q}=this.getAndValidateTimeDimension(),{size:C}=this.getAndValidateChannelDimension(),E=this.dimensions_.x.lods[0],i=this.dimensions_.y.lods[0];this.sourceMaxSquareDistance2D_=Fi(pA(E.size*E.scale,i.size*i.scale)),this.chunks_=Array.from({length:Q},()=>[]);for(let o=0;o<Q;++o){const h=this.chunks_[o];for(let s=0;s<this.dimensions_.numLods;++s){const R=this.dimensions_.x.lods[s],N=this.dimensions_.y.lods[s],r=this.dimensions_.z?.lods[s],M=R.chunkSize,e=N.chunkSize,n=r?.chunkSize??1,f=Math.ceil(R.size/M),V=Math.ceil(N.size/e),m=Math.ceil((r?.size??1)/n);for(let b=0;b<f;++b){const u=R.translation+b*R.chunkSize*R.scale;for(let W=0;W<V;++W){const gA=N.translation+W*N.chunkSize*N.scale;for(let O=0;O<m;++O){const x=r!==void 0?r.translation+O*n*r.scale:0;for(let $=0;$<C;++$)h.push({state:"unloaded",lod:s,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(M,R.size-b*M),y:Math.min(e,N.size-W*e),z:Math.min(n,(r?.size??1)-O*n),c:1},rowAlignmentBytes:1,chunkIndex:{x:b,y:W,z:O,c:$,t:o},scale:{x:R.scale,y:N.scale,z:r?.scale??1},offset:{x:u,y:gA,z:x}})}}}}}}getChunks(){const A=this.getChunksAtCurrentTime(),I=A.filter(Q=>Q.lod===this.currentLOD_&&Q.visible&&Q.state==="loaded");return this.currentLOD_===this.lowestResLOD_?I:[...A.filter(Q=>Q.lod===this.lowestResLOD_&&Q.visible&&Q.state==="loaded"),...I]}getChunksAtCurrentTime(){return this.chunks_[this.getCurrentTimeIndex()]}getCurrentTimeIndex(){return this.sliceCoords_.t===void 0||this.dimensions_.t===void 0?0:Li(this.dimensions_.t.lods[0],this.sliceCoords_.t)}allVisibleLowestLODLoaded(){return this.getChunksAtCurrentTime().filter(A=>A.visible&&A.lod===this.lowestResLOD_).every(A=>A.state==="loaded")}updateAndCollectChunkChanges(A,I){this.setLOD(A);const B=this.getZBounds(),C=this.policyChanged_||this.viewBounds2DChanged(I)||this.zBoundsChanged(B)||this.lastTCoord_!==this.sliceCoords_.t?this.updateAndCollectChunkChangesForCurrentLod(I):[];return this.policyChanged_=!1,this.lastViewBounds2D_=I.clone(),this.lastZBounds_=B,this.lastTCoord_=this.sliceCoords_.t,C}get lodCount(){return this.lowestResLOD_+1}get dimensions(){return this.dimensions_}get currentLOD(){return this.currentLOD_}setImageSourcePolicy(A,I){if(I!==QC)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,j.info("ChunkManagerSource","Using image source policy:",this.policy_.profile))}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}setLOD(A){const I=this.dimensions_.x.lods[0].scale,Q=this.policy_.lod.bias-Math.log2(I)-A,C=Math.floor(Q),E=Math.max(0,Math.min(this.lowestResLOD_,this.policy_.lod.min)),i=Math.max(E,Math.min(this.lowestResLOD_,this.policy_.lod.max)),o=Lg(C,E,i);o!==this.currentLOD_&&(this.currentLOD_=o)}updateAndCollectChunkChangesForCurrentLod(A){if(this.chunks_.length===0)return j.warn("ChunkManagerSource","updateChunkVisibility called with no chunks initialized"),[];const I=_Q();wi(I,A.min,A.max,.5);const[B,Q]=this.getZBounds(),C=new tI(NA(A.min[0],A.min[1],B),NA(A.max[0],A.max[1],Q)),E=[],i=this.getCurrentTimeIndex();if(this.sliceCoords_.t!==void 0){const h=this.disposeStaleTimeChunks(i);E.push(...h)}const o=this.updateChunksAtTimeIndex(i,C,I);if(E.push(...o),this.sliceCoords_.t!==void 0){const h=this.markTimeChunksForPrefetch(i,C,I);E.push(...h)}return E}disposeStaleTimeChunks(A){const I=[];for(const B of this.tIndicesWithQueuedChunks_){const Q=B-A;if(Q>=0&&Q<=this.policy_.prefetch.t)continue;const C=this.chunks_[B];for(const E of C)this.disposeChunk(E),I.push(E);this.tIndicesWithQueuedChunks_.delete(B)}return I}updateChunksAtTimeIndex(A,I,B){const Q=this.getPaddedBounds(I),C=this.chunks_[A];this.tIndicesWithQueuedChunks_.add(A);for(const E of C){const i=this.isChunkWithinBounds(E,I),o=this.isChunkChannelInSlice(E),h=!i&&o&&this.isChunkWithinBounds(E,Q),s=E.lod===this.currentLOD_,R=E.lod===this.lowestResLOD_,N=E.state==="loaded";E.visible=i,E.prefetch=h&&s&&!N,E.priority=this.computePriority(R,s,i,E.prefetch,o),E.priority!==null&&E.state==="unloaded"?E.state="queued":E.priority===null&&E.state==="queued"&&(E.state="unloaded",E.orderKey=null),E.priority!==null&&(E.orderKey=this.squareDistance2D(E,B)),this.shouldDispose(N,R,s,i,h,o)&&this.disposeChunk(E)}return C}markTimeChunksForPrefetch(A,I,B){const Q=Math.min(this.chunks_.length-1,A+this.policy_.prefetch.t),C=[];for(let E=A+1;E<=Q;++E)for(const i of this.chunks_[E]){if(i.state!=="unloaded"||i.lod!==this.lowestResLOD_||!this.isChunkChannelInSlice(i)||!this.isChunkWithinBounds(i,I))continue;i.prefetch=!0,i.priority=this.policy_.priorityMap.prefetchTime;const o=this.squareDistance2D(i,B),h=Lg(o/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON);i.orderKey=E-A+h,i.state="queued",this.tIndicesWithQueuedChunks_.add(E),C.push(i)}return C}isChunkChannelInSlice(A){return this.sliceCoords_.c===void 0||this.sliceCoords_.c===A.chunkIndex.c}shouldDispose(A,I,B,Q,C,E){return A?E?I?!1:B?!Q&&!C:!0:!0:!1}disposeChunk(A){A.data=void 0,A.state="unloaded",A.priority=null,A.orderKey=null,A.prefetch=!1}computePriority(A,I,B,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&B?E.fallbackVisible:I&&B?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let B=1;B<this.dimensions_.numLods;B++){const Q=A.lods[B].scale/A.lods[B-1].scale,C=I.lods[B].scale/I.lods[B-1].scale;if(!VB(Q,2,.02)||!VB(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${B-1} → ${B}: expected (2× in X and Y), but got (${Q.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[B-1].scale}, ${I.lods[B-1].scale}] → [${A.lods[B].scale}, ${I.lods[B].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;if(I.chunkSize!==1)throw new Error(`ChunkManager only supports a chunk size of 1 in t. Found ${I.chunkSize} at LOD ${A}`);const B=this.dimensions_.t?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkManager does not support downsampling in t. Found ${B.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.chunkSize!==1)throw new Error(`ChunkManager only supports a chunk size of 1 in c. Found ${I.chunkSize} at LOD ${A}`);if(I.scale!==1)throw new Error(`ChunkManager does not support scale in c. Found ${I.scale} at LOD ${A}`);if(I.translation!==0)throw new Error(`ChunkManager does not support translation in c. Found ${I.translation} at LOD ${A}`);const B=this.dimensions_.c?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkManager does not support downsampling in c. Found ${B.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}isChunkWithinBounds(A,I){const B=new tI(NA(A.offset.x,A.offset.y,A.offset.z),NA(A.offset.x+A.shape.x*A.scale.x,A.offset.y+A.shape.y*A.scale.y,A.offset.z+A.shape.z*A.scale.z));return tI.intersects(B,I)}getZBounds(){const A=this.dimensions_.z;if(A===void 0||this.sliceCoords_.z===void 0)return[0,1];const I=A.lods[this.currentLOD_],B=I.size,Q=I.scale,C=I.translation,E=Math.floor((this.sliceCoords_.z-C)/Q),i=I.chunkSize,o=Math.max(0,Math.min(Math.floor(E/i),Math.ceil(B/i)-1));return[C+o*i*Q,C+(o+1)*i*Q]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!OB(this.lastViewBounds2D_.min,A.min)||!OB(this.lastViewBounds2D_.max,A.max)}zBoundsChanged(A){return!this.lastZBounds_||!OB(this.lastZBounds_,A)}getPaddedBounds(A){const I=this.dimensions_.x.lods[this.currentLOD_],B=this.dimensions_.y.lods[this.currentLOD_],Q=this.dimensions_.z?.lods[this.currentLOD_],C=I.chunkSize*I.scale*this.policy_.prefetch.x,E=B.chunkSize*B.scale*this.policy_.prefetch.y;let i=0;return Q&&(i=Q.chunkSize*Q.scale*this.policy_.prefetch.z),new tI(NA(A.min[0]-C,A.min[1]-E,A.min[2]-i),NA(A.max[0]+C,A.max[1]+E,A.max[2]+i))}squareDistance2D(A,I){const B={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},Q=B.x-I[0],C=B.y-I[1];return Q*Q+C*C}}class ri{sources_=new Map;pendingSources_=new Map;queue_=new ci;async addSource(A,I,B){const Q=this.sources_.get(A)??this.pendingSources_.get(A);if(Q)return Q;const E=(async()=>{const i=await A.open(),o=new Ji(i,I,B);return this.sources_.set(A,o),this.pendingSources_.delete(A),o})();return this.pendingSources_.set(A,E),E}update(A,I){if(this.sources_.size===0)return;if(A.type!=="OrthographicCamera")throw new Error("ChunkManager currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const B=A.getWorldViewRect(),C=Math.abs(B.max[0]-B.min[0])/I,E=Math.log2(1/C);for(const[i,o]of this.sources_){const h=o.updateAndCollectChunkChanges(E,B);for(const s of h)s.priority===null?this.queue_.cancel(s):s.state==="queued"&&this.queue_.enqueue(s,R=>o.loadChunkData(s,R))}this.queue_.flush()}}var Jg=function(g=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(R){R.preventDefault(),Q(++A%I.children.length)},!1);function B(R){return I.appendChild(R.dom),R}function Q(R){for(var N=0;N<I.children.length;N++)I.children[N].style.display=N===R?"block":"none";A=R}var C=(performance||Date).now(),E=C,i=0,o=B(new Jg.Panel("FPS","#0ff","#002",g)),h=B(new Jg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var s=B(new Jg.Panel("MB","#f08","#201",g));return Q(0),{REVISION:16,dom:I,addPanel:B,showPanel:Q,begin:function(){C=(performance||Date).now()},end:function(){i++;var R=(performance||Date).now();if(h.update(R-C,200),R>=E+1e3&&(o.update(i*1e3/(R-E),100),E=R,i=0,s)){var N=performance.memory;s.update(N.usedJSHeapSize/1048576,N.jsHeapSizeLimit/1048576)}return R},update:function(){C=this.end()},domElement:I,setMode:Q}};Jg.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*B),h=E(48*i*B),s=E(3*i*B),R=E(2*i*B),N=E(3*i*B),r=E(15*i*B),M=E(74*i*B),e=E(30*i*B),n=document.createElement("canvas");n.width=o,n.height=h,n.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var f=n.getContext("2d");return f.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",f.textBaseline="top",f.fillStyle=I,f.fillRect(0,0,o,h),f.fillStyle=A,f.fillText(g,s,R),f.fillRect(N,r,M,e),f.fillStyle=I,f.globalAlpha=.9,f.fillRect(N,r,M,e),{dom:n,update:function(V,m){Q=Math.min(Q,V),C=Math.max(C,V),f.fillStyle=I,f.globalAlpha=1,f.fillRect(0,0,o,r),f.fillStyle=A,f.fillText(E(V)+" "+g+" ("+E(Q)+"-"+E(C)+")",s,R),f.drawImage(n,N+i,r,M-i,e,N,r,M-i,e),f.fillRect(N+M-i,r,i,e),f.fillStyle=I,f.globalAlpha=.9,f.fillRect(N+M-i,r,i,E((1-V/m)*e))}}};function Yi({scale:g}={scale:1.5}){const A=new Jg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class CC{layers_=[];callbacks_=[];context_;constructor(A){this.context_=A}partitionLayers(){const A=[],I=[];for(const B of this.layers)B.transparent?I.push(B):A.push(B);return{opaque:A,transparent:I}}add(A){this.layers_=[...this.layers_,A],this.context_&&A.onAttached(this.context_),this.notifyLayersChanged()}remove(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.removeByIndex(I)}removeByIndex(A){const I=this.layers_[A];I&&I.onDetached(),this.layers_=this.layers_.filter((B,Q)=>Q!==A),this.notifyLayersChanged()}removeAll(){for(const A of this.layers_)A.onDetached();this.layers_=[],this.notifyLayersChanged()}get layers(){return this.layers_}notifyLayersChanged(){for(const A of this.callbacks_)A()}addLayersChangeCallback(A){return this.callbacks_.push(A),()=>{this.removeLayersChangeCallback(A)}}removeLayersChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove not found: ${A}`);this.callbacks_.splice(I,1)}}const XB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function ni(g){return XB.includes(g)}class Ki{propagationStopped_=!1;type;event;worldPos;clipPos;constructor(A,I){this.type=A,this.event=I}get propagationStopped(){return this.propagationStopped_}stopPropagation(){this.propagationStopped_=!0}}class Mi{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){j.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,XB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){j.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,XB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!ni(A.type)){j.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new Ki(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class EC{id;element;camera;layerManager;events;cameraControls;constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.layerManager=A.layerManager,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new Mi(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=pA(B,Q);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const B of this.layerManager.layers)if(B.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.layerManager.add(I)}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),B=A.getBoundingClientRect(),Q=window.devicePixelRatio||1,C=B.left*Q,E=B.top*Q,i=B.height*Q,o=I.x-C,h=I.y-E,s=Math.floor(o),R=Math.floor(i-h-I.height),N=Math.floor(I.width),r=Math.floor(I.height);return new jA(pA(s,R),pA(s+N,R+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return NA(2*(B-C.x)/C.width-1,2*(Q-C.y)/C.height-1,I)}clientToWorld(A,I=0){const B=this.clientToClip(A,I);return this.camera.clipToWorld(B)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,B=A.left*I,Q=A.top*I,C=A.width*I,E=A.height*I;return new jA(pA(B,Q),pA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){j.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const B=A/I;this.camera.setAspectRatio(B)}}function Hi(g){const A=new Map,I=new Set;for(const B of g){if(I.has(B.id))throw new Error(`Duplicate viewport ID "${B.id}". Each viewport must have a unique ID.`);if(I.add(B.id),A.has(B.element)){const Q=A.get(B.element),C=B.element.tagName.toLowerCase()+(B.element.id?`#${B.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${Q}" and "${B.id}" both use ${C}`)}A.set(B.element,B.id)}}function iC(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??bQ(),layerManager:new CC(I)}});return Hi(B),B.map(Q=>new EC(Q))}class ei{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;changed_=!1;constructor(A=[]){this.elements_=A}connect(){if(this.resizeObserver_){j.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.changed_=!0});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}getAndResetChanged(){const A=this.changed_;return this.changed_=!1,A}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.changed_=!0,this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){j.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}}class qi{lastAnimationId_;chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;constructor(A){if(this.canvas=A.canvas,A.viewports.length===0)throw new Error("At least one viewport config must be specified.");this.renderer_=new IC(this.canvas),this.chunkManager_=new ri,this.context_={chunkManager:this.chunkManager_},this.viewports_=iC(A.viewports,this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=Yi());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new ei(I)}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get textureInfo(){return this.renderer_.textureInfo}get viewports(){return this.viewports_}getViewport(A){return this.viewports_.find(I=>I.id===A)}start(){if(j.info("Idetik","Idetik runtime starting"),this.lastAnimationId_===void 0){for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.animate()}else j.warn("Idetik","Idetik runtime already started");return this}animate(A){this.stats_&&this.stats_.begin(),this.sizeObserver_.getAndResetChanged()&&this.updateSize();for(const I of this.viewports_)I.camera.type==="OrthographicCamera"&&this.chunkManager_.update(I.camera,I.getBoxRelativeTo(this.canvas).toRect().width),this.renderer_.render(I);for(const I of this.overlays)I.update(this,A);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(I=>this.animate(I))}stop(){if(j.info("Idetik","Idetik runtime stopping"),this.lastAnimationId_===void 0)j.warn("Idetik","Idetik runtime not started");else{this.sizeObserver_.disconnect();for(const A of this.viewports_)A.events.disconnect();cancelAnimationFrame(this.lastAnimationId_),this.lastAnimationId_=void 0}}updateSize(){this.renderer_.updateSize();for(const A of this.viewports_)A.updateSize()}}class di extends $I{constructor(A){if(super(),A.primitive!="triangles"){j.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){j.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,B=[],Q=(E,i)=>{const o=Math.min(E,i),h=Math.max(E,i);I.has({i0:o,i1:h})||(I.add({i0:o,i1:h}),B.push(o,h))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],h=C[E+2];Q(i,o),Q(o,h),Q(h,i)}this.indexData_=new Uint32Array(B)}}const fi=NA(0,1,0);class li{dirty_=!0;matrix_=QI();rotation_=bB();translation_=rA();scale_=NA(1,1,1);addRotation(A){si(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){hi(this.rotation_,A),this.dirty_=!0}get rotation(){return yi(this.rotation_)}addTranslation(A){OQ(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){tg(this.translation_,A),this.dirty_=!0}get translation(){return CI(this.translation_)}addScale(A){Ii(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){tg(this.scale_,A),this.dirty_=!0}targetTo(A){Qi(this.translation_,A)&&(A=CI(A),A[2]+=fI);const I=$E(QI(),this.translation_,A,fi),B=OE(uQ(),I);zQ(this.rotation_,B),PB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return CI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return mB(QI(),this.matrix)}computeMatrix(){XE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Ag extends WB{wireframeEnabled=!1;wireframeColor=hA.WHITE;textures_=[];staleTextures_=[];transform_=new li;geometry_=new $I;wireframeGeometry_=null;programName_=null;setTexture(A,I){const B=this.textures_[A];B!==void 0&&this.staleTextures_.push(B),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new di(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){if(this.programName_===null)throw new Error("Program name not set");return this.programName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}getUniforms(){return{}}}class lI{normal;signedDistance;constructor(A=NA(0,1,0),I=0){this.normal=CI(A),this.signedDistance=I}set(A,I){this.normal=CI(A),this.signedDistance=I}signedDistanceToPoint(A){return jQ(this.normal,A)+this.signedDistance}normalize(){const A=PQ(this.normal);if(A>0){const I=1/A;VQ(this.normal,this.normal,I),this.signedDistance*=I}}}class DC{planes_;constructor(A){this.planes_=[new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=rA();this.planes_[0].set(_I(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(_I(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(_I(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(_I(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(_I(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(_I(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const B of this.planes_)B.normalize()}intersectsWithBox3(A){const I=rA();for(const B of this.planes_){const Q=B.normal;if(I[0]=Q[0]>0?A.max[0]:A.min[0],I[1]=Q[1]>0?A.max[1]:A.min[1],I[2]=Q[2]>0?A.max[2]:A.min[2],B.signedDistanceToPoint(I)<0)return!1}return!0}}class oC extends Ag{projectionMatrix_=QI();near_=0;far_=0;update(){this.updateProjectionMatrix()}get projectionMatrix(){return this.projectionMatrix_}get viewMatrix(){return this.transform.inverse}get right(){const A=this.transform.matrix;return NA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return NA(A[4],A[5],A[6])}get frustum(){return new DC(DB(QI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=ZB(A[0],A[1],A[2],1),B=mB(QI(),this.projectionMatrix_),Q=aB(cg(),I,B);Di(Q,Q,1/Q[3]);const C=aB(cg(),Q,this.transform.matrix);return NA(C[0],C[1],C[2])}}const aC=1.77,sC=128,yC=128/aC;class pi extends oC{width_=sC;height_=yC;viewportAspectRatio_=aC;viewportSize_=[sC,yC];constructor(A,I,B,Q,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,Q,B),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,B,Q){this.width_=Math.abs(I-A),this.height_=Math.abs(Q-B),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(B+Q);this.transform.setTranslation([C,E,0]),this.transform.setScale([1,1,1]),this.transform.setRotation([0,0,0,1])}get type(){return"OrthographicCamera"}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=ZB(-1,-1,0,1),I=ZB(1,1,0,1);const B=DB(QI(),this.projectionMatrix,this.viewMatrix),Q=mB(QI(),B);return A=aB(cg(),A,Q),I=aB(cg(),I,Q),new jA(pA(A[0],A[1]),pA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,B=A/I;let Q=.5*A,C=.5*I;this.viewportAspectRatio_>B?Q*=this.viewportAspectRatio_/B:C*=B/this.viewportAspectRatio_,this.viewportSize_=[2*Q,2*C],_E(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const Wi=60,mi=1.77,sB=.1,vB=180-sB;class Ti extends oC{fov_;aspectRatio_;constructor(A={}){const{fov:I=Wi,aspectRatio:B=mi,near:Q=.1,far:C=1e4,position:E=NA(0,0,0)}=A;if(I<sB||I>vB)throw new Error(`Invalid field of view: ${I}, must be in [${sB}, ${vB}] degrees`);super(),this.fov_=I,this.aspectRatio_=B,this.near_=Q,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(sB,Math.min(vB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){jE(this.projectionMatrix_,PE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const hC=0;class xi{camera_;dragActive_=!1;dragStart_=rA();constructor(A){this.camera_=A}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const B=CI(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=xB(rA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==hC||(this.dragStart_=CI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=xB(rA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==hC||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class SI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&j.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=Lg(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&j.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=Lg(A,0,1)}onEvent(A){}async onAttached(A){}onDetached(){}get objects(){return this.objects_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(B=>B(A,I))}addObject(A){this.objects_.push(A)}removeObject(A){const I=this.objects_.indexOf(A);I!==-1&&this.objects_.splice(I,1)}clearObjects(){this.objects_=[]}}class yB extends $I{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"path_proportion",itemSize:1,offset:10*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*11);let B=0,Q=0;const C=A.reduce((E,i,o)=>E+vQ(i,A[o+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const o=A[E];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const h=A[E-1]??A[E];I[B++]=h[0],I[B++]=h[1],I[B++]=h[2];const s=A[E+1]??A[E];I[B++]=s[0],I[B++]=s[1],I[B++]=s[2],I[B++]=i,I[B++]=Q}Q+=vQ(A[E],A[E+1]??A[E])/C}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let B=0;for(let Q=0;Q<2*A;Q+=2)I[B++]=Q+0,I[B++]=Q+1,I[B++]=Q+2,I[B++]=Q+2,I[B++]=Q+1,I[B++]=Q+3;return I}}class jB extends Ag{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=hA.from(I),this.width_=B,this.taperOffset_=Q??this.taperOffset_,this.taperPower_=C??this.taperPower_,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=hA.from(A)}get width(){return this.width_}set width(A){this.width_=A}get taperOffset(){return this.taperOffset_}set taperOffset(A){this.taperOffset_=A}get taperPower(){return this.taperPower_}set taperPower(A){this.taperPower_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width,TaperOffset:this.taperOffset,TaperPower:this.taperPower}}}class Zi extends SI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(zB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(zB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(zB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function zB(g){const{end:A,width:I,color:B}=g,Q=new yB([[0,0,0],A]);return new jB({geometry:Q,color:B,width:I})}class bi extends SI{type="ProjectedLineLayer";paths_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){const{path:I,color:B,width:Q}=A;this.paths_.push(I);const C=new yB(I);this.addObject(new jB({geometry:C,color:B,width:Q}))}update(){}get extent(){return ui(this.paths_.flat())}}function ui(g){function A(o){const h=g.map(s=>s[o]);return[Math.min(...h),Math.max(...h)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}class Pi extends SI{type="TracksLayer";tracks_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){this.tracks_.push(A);let I;if(A.interpolation){const i=Vi({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new yB(i)}else I=new yB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new jB({geometry:I,color:B,width:Q,taperOffset:C,taperPower:E}))}setTimeIndex(A){for(const[I,B]of this.tracks_.entries()){if(!B.time)continue;let Q=.5;A<B.time[0]?Q=-1.5:A>B.time[B.time.length-1]&&(Q=1.5);const C=B.time.findIndex(i=>i===A);B.time&&C!==-1&&(Q=C/(B.time.length-1));const E=this.objects[I];E.taperOffset=Q}}update(){}get extent(){const A=this.tracks_.map(I=>I.path);return Oi(A.flat())}}function Oi(g){function A(o){const h=g.map(s=>s[o]);return[Math.min(...h),Math.max(...h)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}function Vi({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=Xi(g),Q=Array((g.length-1)*A);for(let C=0;C<g.length-1;C++){const E=g[C],i=g[C+1],o=CI(B[C]);XQ(o,E,o,I);const h=CI(B[C+1]);XQ(h,i,h,-I);for(let s=0;s<A;s++){const R=s/A,N=Q[C*A+s]=rA();Bi(N,E,o,h,i,R)}}return Q}function Xi(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=rA(),B=rA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=rA(),Q!==0&&tg(I,B),Q!==g.length-1&&xB(B,E,C),Q===0?tg(A[Q],B):Q==g.length-1?tg(A[Q],I):(OQ(A[Q],I,B),VQ(A[Q],A[Q],.5))}return A}class GC extends $I{constructor(A,I,B,Q){super();const C=[],E=[],i=B,o=Q,h=i+1,s=o+1,R=A/i,N=I/o;for(let r=0;r<s;++r){const M=r*N;for(let e=0;e<h;++e){const n=e*R,f=e/i,V=r/o,m=[n,M,0],b=[0,0,1],u=[f,V];C.push(...m,...b,...u)}}for(let r=0;r<o;++r)for(let M=0;M<i;++M){const e=M+h*r,n=M+h*(r+1),f=M+1+h*(r+1),V=M+1+h*r;E.push(e,n,V),E.push(n,f,V)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}function FC(g){return g===1||g===2||g===4||g===8}function Ig(g){if(g instanceof Int8Array)return"byte";if(g instanceof Int16Array)return"short";if(g instanceof Int32Array)return"int";if(g instanceof Uint8Array)return"unsigned_byte";if(g instanceof Uint16Array)return"unsigned_short";if(g instanceof Uint32Array)return"unsigned_int";if(g instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function vi(g){if(g.dataFormat==="rgb"||g.dataFormat==="rgba")return[0,1];switch(g.dataType){case"byte":return[-128,127];case"short":return[-32768,32767];case"int":return[-2147483648,2147483647];case"unsigned_byte":return[0,255];case"unsigned_short":return[0,65535];case"unsigned_int":return[0,4294967295];case"float":return[0,1]}}class _B extends WB{dataFormat="rgba";dataType="unsigned_byte";maxFilter="nearest";minFilter="nearest";mipmapLevels=1;unpackAlignment=4;wrapR="clamp_to_edge";wrapS="clamp_to_edge";wrapT="clamp_to_edge";needsUpdate=!0;get type(){return"Texture"}}const wC=32;function $B(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=hA.WHITE:I=hA.from(I),g!==null?B=ji(B,g):B===void 0&&(j.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function SC(g,A){if(A.length>wC)throw new Error(`Maximum number of channels is ${wC}`);if(g?.type==="Texture2DArray"){const I=g.depth;if(A.length!==I)throw new Error(`Number of channels (${A.length}) must match depth of texture (${I}).`)}return A.map(I=>$B(g,I))}function ji(g,A){if(g===void 0)return vi(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class AQ extends Ag{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new GC(A,I,1,1),this.setTexture(0,B),this.channels_=SC(B,Q),this.programName=zi(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=SC(this.textures[0],A)}setChannelProperty(A,I,B){const Q=$B(this.textures[0],{...this.channels_[A],[I]:B});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");if(A.type==="Texture2D"){const{color:I,contrastLimits:B}=this.channels_[0]??$B(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-B[0],ValueScale:1/(B[1]-B[0])}}else{const I=[],B=[],Q=[],C=[];return this.channels_.forEach(E=>{I.push(E.visible),B.push(...E.color.rgb),Q.push(-E.contrastLimits[0]),C.push(1/(E.contrastLimits[1]-E.contrastLimits[0]))}),{ImageSampler:0,"Visible[0]":I,"Color[0]":B,"ValueOffset[0]":Q,"ValueScale[0]":C}}}}function zi(g){if(g.type==="Texture2D")return _i(g.dataType);if(g.type==="Texture2DArray")return $i(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function _i(g){switch(g){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function $i(g){switch(g){case"byte":case"int":case"short":return"intScalarImageArray";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImageArray";case"float":return"floatScalarImageArray"}}class gg extends _B{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=A.length/(I*B)}get type(){return"Texture2DArray"}set data(A){this.data_=A,this.needsUpdate=!0}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===B)return;const Q=A.shape.x,C=A.shape.y,E=B.length/(Q*C);if(this.width!=Q||this.height!=C||this.depth_!=E||this.dataType!=Ig(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new gg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function IQ(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return pA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=pA(C.clientX,C.clientY);if(Gi(A,E)<Q){if(!B)return null;const o=g.worldPos;if(o){const h=I(o);h!==null&&B({world:o,value:h})}return null}return A}case"pointercancel":return null;default:return A}}class AD{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&j.debug("RenderablePool","Renderable object acquired"),B}release(A,I){let B=this.bins_.get(A);B||(B=[],this.bins_.set(A,B)),B.push(I),j.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class gQ extends SI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new AD;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkManagerSource_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new hA(.6,.3,.3),new hA(.3,.6,.4),new hA(.4,.4,.7),new hA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:B,channelProps:Q,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=B,this.sliceCoords_=I,this.channelProps_=Q,this.initialChannelProps_=Q,this.onPickValue_=C}async onAttached(A){if(this.chunkManagerSource_)throw new Error("ChunkedImageLayer is already attached. A layer cannot be attached to multiple LayerManagers simultaneously.");this.chunkManagerSource_=await A.chunkManager.addSource(this.source_,this.sliceCoords_,this.policy_)}onDetached(){this.chunkManagerSource_=void 0,this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects()}update(){this.updateChunks(),this.resliceIfZChanged()}updateChunks(){if(!this.chunkManagerSource_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkManagerSource_.allVisibleLowestLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkManagerSource_.getChunks(),I=new Set(A),B=Array.from(this.visibleChunks_.keys()).filter(Q=>!I.has(Q));this.releaseAndRemoveChunks(B),this.clearObjects();for(const Q of A){if(Q.state!=="loaded")continue;const C=this.getImageForChunk(Q);this.visibleChunks_.set(Q,C),this.addObject(C)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>gQ.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,B]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const Q=this.slicePlane(I,A);Q&&B.textures[0].updateWithChunk(I,Q)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=IQ(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get chunkManagerSource(){return this.chunkManagerSource_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkManagerSource_&&this.chunkManagerSource_.setImageSourcePolicy(A,QC))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=Lg(Q,0,A.shape.z-1);VB(B,C,1+1e-6)||j.error("ImageLayer","slicePlane zValue outside extent");const E=A.shape.x*A.shape.y,i=E*C;return A.data.slice(i,i+E)}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const B=this.pool_.acquire(RC(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(B,A),this.channelProps_&&B.setChannelProps(this.channelProps_),B):this.createImage(A)}createImage(A){const I=new AQ(A.shape.x,A.shape.y,gg.createWithChunk(A,this.getDataForImage(A)),this.channelProps_??[{}]);return this.updateImageChunk(I,A),I}getDataForImage(A){const I=this.sliceCoords_?.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data;if(!I){j.warn("ChunkedImageLayer","No data for image");return}return I}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1,A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}getValueAtWorld(A){const I=this.chunkManagerSource_?.currentLOD??0;for(const[B,Q]of this.visibleChunks_){if(B.lod!==I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}for(const[B,Q]of this.visibleChunks_){if(B.lod===I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}return null}getValueFromChunk(A,I,B){if(!A.data)return null;const Q=oB(rA(),B,I.transform.inverse),C=Math.floor(Q[0]),E=Math.floor(Q[1]);if(C>=0&&C<A.shape.x&&E>=0&&E<A.shape.y){const i=this.sliceCoords_.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data,o=E*A.shape.x+C;return i[o]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,B)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[B.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach(I=>{I.setChannelProps(A)}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(RC(I),B),this.visibleChunks_.delete(I))}}}function RC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class hB extends _B{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=Ig(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=Q}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture3D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==I){if(this.width!=A.shape.x||this.height!=A.shape.y||this.depth!=A.shape.z||this.dataType!=Ig(I))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=I}}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new hB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class ID extends $I{constructor(A,I,B,Q,C,E){super();const i=[],o=[],h=Math.floor(Q),s=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,R,s,1,i,o),this.buildFace("z","y","x",1,-1,B,I,A,R,s,-1,i,o),this.buildFace("x","z","y",1,1,A,B,I,h,R,1,i,o),this.buildFace("x","z","y",1,-1,A,B,I,h,R,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,B,h,s,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,B,h,s,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,B,Q,C,E,i,o,h,s,R,N,r){const M=E/h,e=i/s,n=E/2,f=i/2,V=o/2*R,m=h+1,b=s+1,u=N.length/8;for(let W=0;W<b;W++){const gA=-f+W*e;for(let O=0;O<m;O++){const x=-n+O*M,$={x:0,y:0,z:0};$[A]=x*Q,$[I]=gA*C,$[B]=V;const IA={x:0,y:0,z:0};IA[B]=R;const wA=O/h,kA=1-W/s;N.push($.x,$.y,$.z,IA.x,IA.y,IA.z,wA,kA)}}for(let W=0;W<s;W++)for(let gA=0;gA<h;gA++){const O=u+gA+m*W,x=u+gA+m*(W+1),$=u+(gA+1)+m*(W+1),IA=u+(gA+1)+m*W;R===1?r.push(O,x,IA,x,$,IA):r.push(O,IA,x,x,IA,$)}}}class gD extends Ag{constructor(A,I,B,Q){super(),this.geometry=new ID(A,I,B,1,1,1),this.setTexture(0,Q),this.programName=BD(Q.dataType)}get type(){return"VolumeRenderable"}}function BD(g){switch(g){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}class QD extends SI{type="VolumeLayer";constructor(){super();const A=new Int8Array([127,0,0,127,127,0,0,127]),I=new hB(A,2,2,2);I.unpackAlignment=1;const B=new gD(1,1,1,I);B.wireframeEnabled=!0,this.addObject(B),this.setState("ready")}update(){}}class CD extends SI{type="ImageLayer";source_;region_;lod_;onPickValue_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;image_;chunk_;extent_;pointerDownPos_=null;constructor({source:A,region:I,channelProps:B,onPickValue:Q,lod:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.region_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=Q,this.lod_=C}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}onEvent(A){this.pointerDownPos_=IQ(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=I.getAttributes(),Q=this.lod_??B.length-1,C=await I.loadRegion(A,Q);this.extent_={x:C.shape.x*C.scale.x,y:C.shape.y*C.scale.y},this.image_=this.createImage(C),this.chunk_=C,this.addObject(this.image_),this.setState("ready")}get extent(){return this.extent_}createImage(A){const I=new AQ(A.shape.x,A.shape.y,gg.createWithChunk(A),this.channelProps);return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.chunk_?.data)return null;const I=oB(rA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B>=0&&B<this.chunk_.shape.x&&Q>=0&&Q<this.chunk_.shape.y){const C=Q*this.chunk_.shape.x+B;return this.chunk_.data[C]}return null}}class rg extends _B{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(A),this.data_=A,this.width_=I,this.height_=B}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture2D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==B){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=Ig(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new rg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const ED=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function iD(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,hA.from(I)]))}function DD(g){return g=g??ED,g.map(hA.from)}class NC{lookupTable;cycle;constructor(A={}){this.lookupTable=iD(A.lookupTable),this.cycle=DD(A.cycle)}}const oD=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function aD(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!oD.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class sD extends Ag{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new GC(A.width,A.height,1,1),this.setTexture(0,aD(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const B=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,B),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{ImageSampler:0,ColorCycleSampler:1,ColorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new rg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,hA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,hA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new rg(C,Q,2)}}class yD extends SI{type="LabelImageLayer";source_;region_;lod_;colorMap_;onPickValue_;outlineSelected_;image_;imageChunk_;pointerDownPos_=null;selectedValue_=null;constructor({source:A,region:I,colorMap:B={},onPickValue:Q,lod:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.region_=I,this.colorMap_=new NC(B),this.onPickValue_=Q,this.lod_=C,this.outlineSelected_=E}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new NC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=IQ(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=I.getAttributes(),Q=this.lod_??B.length-1,C=await I.loadRegion(A,Q);this.image_=this.createImage(C),this.addObject(this.image_),this.setState("ready")}createImage(A){this.imageChunk_=A;const I=new sD({width:A.shape.x,height:A.shape.y,imageData:rg.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.imageChunk_?.data)return null;const I=oB(rA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B<0||B>=this.imageChunk_.shape.x||Q<0||Q>=this.imageChunk_.shape.y)return null;const C=Q*this.imageChunk_.shape.x+B;return this.imageChunk_.data[C]}}class GB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,GB.prototype)}}class hD{maxConcurrent_;pending_=[];abortController_=new AbortController;numRunning_=0;constructor(A){if(A<=0)throw Error(`maxConcurrent (${A}) must be positive`);this.maxConcurrent_=A}async submit(A){return this.abortController_.signal.throwIfAborted(),new Promise((I,B)=>{const Q=async()=>{try{this.abortController_.signal.throwIfAborted();const C=await A();I(C)}catch(C){B(C)}finally{this.numRunning_--,this.maybeRunNext()}};this.pending_.push(Q),this.maybeRunNext()})}maybeRunNext(){if(this.numRunning_>=this.maxConcurrent_)return;const A=this.pending_.shift();A!==void 0&&(this.numRunning_++,A())}get abortSignal(){return this.abortController_.signal}shutdown(){this.abortController_.abort(new GB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class GD{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new hD(16);lod_;loader_=null;seriesAttributes_;loadingToken_=null;dataChunks_=[];constructor(A){this.source_=A.source,this.region_=A.region,this.lod_=A.lod,this.seriesDimensionName_=A.seriesDimensionName;const I=A.region.find(B=>B.dimension==A.seriesDimensionName);if(I===void 0)throw new Error(`Series dimension '${A.seriesDimensionName}' not in region ${JSON.stringify(A.region)}`);if(I.index.type==="point")throw new Error("Series dimension index in region must be an interval or 'full', not a point value");this.seriesIndex_=I.index}async setPosition(A){const I=await this.loadSeriesAttributes(),B=Math.round((A-I.start)/I.scale);return await this.setIndex(B)}async setIndex(A){const I=this.loadingToken_;if(I){if(I.index===A&&!I.canceled)return j.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};j.debug("ImageSeriesLoader",`Cancelling setIndex request for index ${I.index}, new requested index is ${A}`),I.canceled=!0}let B=this.dataChunks_[A];if(B===void 0){const Q={canceled:!1,index:A};if(this.loadingToken_=Q,B=await this.loadChunkAtIndex(A,Q),Q.canceled)return{success:!1,reason:"canceled"}}return{success:!0,chunk:B}}shutdown(){this.scheduler_.shutdown()}async loadSeriesAttributes(){if(this.seriesAttributes_)return this.seriesAttributes_;const I=(await this.getLoader()).getAttributes(),B=I[this.lod_??I.length-1],Q=B.dimensionNames.findIndex(R=>R===this.seriesDimensionName_);if(Q===-1)throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${B.dimensionNames}`);const C=B.scale[Q],E=B.shape[Q]*C,i=this.seriesIndex_.type==="full",o=i?0:this.seriesIndex_.start,h=i?E:this.seriesIndex_.stop,s=Math.round((h-o)/C);return this.dataChunks_=new Array(s),this.seriesAttributes_={start:o,stop:h,scale:C,length:s},this.seriesAttributes_}async loadChunkAtIndex(A,I){const B=await this.loadSeriesAttributes();if(A<0||A>=B.length)throw new Error(`Requested index ${A} is out of bounds [0, ${B.length-1}]`);const Q=B.start+A*B.scale,C=this.region_.filter(s=>s.dimension!==this.seriesDimensionName_);C.push({dimension:this.seriesDimensionName_,index:{type:"point",value:Q}});const E=await this.getLoader(),i=E.getAttributes(),o=this.lod_??i.length-1,h=await E.loadRegion(C,o,this.scheduler_);return this.dataChunks_[A]=h,I&&I.canceled&&(this.loadingToken_=null),h}async preloadAllChunks(){const{length:A}=await this.loadSeriesAttributes(),I=[];for(let Q=0;Q<A;Q++)I.push(this.loadChunkAtIndex(Q));const B=await Promise.allSettled(I);for(const Q of B)if(Q.status==="rejected"){if(Q.reason instanceof GB)return Promise.reject(Q.reason);j.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class FD extends SI{type="ImageSeriesLayer";seriesLoader_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;texture_=null;image_;extent_;constructor({source:A,region:I,seriesDimensionName:B,channelProps:Q,lod:C,...E}){super(E),this.setState("initialized"),this.channelProps_=Q,this.initialChannelProps_=Q,this.seriesLoader_=new GD({source:A,region:I,seriesDimensionName:B,lod:C})}update(){this.state==="initialized"&&(this.setState("loading"),this.seriesLoader_.loadSeriesAttributes())}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async setPosition(A){const I=await this.seriesLoader_.setPosition(A);return this.processIndexResult(I)}async setIndex(A){const I=await this.seriesLoader_.setIndex(A);return this.processIndexResult(I)}close(){this.seriesLoader_.shutdown()}async preloadSeries(){return this.seriesLoader_.preloadAllChunks()}get extent(){return this.extent_}processIndexResult(A){return A.chunk&&(this.setData(A.chunk),this.setState("ready")),A}setData(A){!this.texture_||!this.image_?(this.texture_=gg.createWithChunk(A),this.image_=this.createImage(A,this.texture_,this.channelProps_),this.addObject(this.image_),this.extent_={x:A.shape.x*A.scale.x,y:A.shape.y*A.scale.y}):A.data&&this.texture_.updateWithChunk(A)}createImage(A,I,B){const Q=new AQ(A.shape.x,A.shape.y,I,B);return Q.transform.setScale([A.scale.x,A.scale.y,1]),Q.transform.setTranslation([A.offset.x,A.offset.y,0]),Q}}class Yg extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class BQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}class QQ{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new Error("keepbits must be zero or positive")}static fromConfig(A,I){return new QQ(A,I)}encode(A){throw new Error("`BitroundCodec.encode` is not implemented. Please open an issue at https://github.com/manzt/zarrita.js/issues.")}decode(A){return A}}class UC{#A;constructor(A,I,B){typeof A=="number"?this.#A=new Uint8Array(A):A instanceof ArrayBuffer?this.#A=new Uint8Array(A,I,B):this.#A=new Uint8Array(Array.from(A,Q=>Q?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#A.byteOffset}get byteLength(){return this.#A.byteLength}get buffer(){return this.#A.buffer}get length(){return this.#A.length}get(A){let I=this.#A[A];return typeof I=="number"?I!==0:I}set(A,I){this.#A[A]=I?1:0}fill(A){this.#A.fill(A?1:0)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class CQ{_data;chars;#A;constructor(A,I,B,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q=Q*A),this._data=new Uint8Array(I,B,Q);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const B=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);B.fill(0),B.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let B=0;B<this.length;B++)this._data.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class ng{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new ng(A,1);this.#A=new Int32Array(function*(){for(let i of C)E.set(0,i),yield*E.#A}())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let B="";for(let Q=0;Q<this.chars;Q++)B+=String.fromCodePoint(this.#A[I+Q]);return B.replace(/\u0000/g,"")}set(A,I){const B=this.chars*A,Q=this.#A.subarray(B,B+this.chars);Q.fill(0);for(let C=0;C<this.chars;C++)Q[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let B=1;B<this.length;B++)this.#A.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function Kg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function kC(g,A){const I=A/2,B=A-1;let Q=0;for(let C=0;C<g.length;C+=A)for(let E=0;E<I;E+=1)Q=g[C+E],g[C+E]=g[C+B-E],g[C+B-E]=Q}const wD={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float32:Float32Array,float64:Float64Array,bool:UC},SD=/v2:([US])(\d+)/;function tC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(SD);if(A){let[,B,Q]=A;return(B==="U"?ng:CQ).bind(null,Number(Q))}let I=wD[g];if(!I)throw new Error(`Unknown or unsupported data_type: ${g}`);return I}function pI(g,A){return(A==="C"?RD:ND)(g)}function RD(g){const A=g.length,I=globalThis.Array(A);for(let B=A-1,Q=1;B>=0;B--)I[B]=Q,Q*=g[B];return I}function ND(g){const A=g.length,I=globalThis.Array(A);for(let B=0,Q=1;B<A;B++)I[B]=Q,Q*=g[B];return I}function UD({name:g,configuration:A}){if(g==="default"){const I=A?.separator??"/";return B=>["c",...B].join(I)}if(g==="v2"){const I=A?.separator??".";return B=>B.join(I)||"0"}throw new Error(`Unknown chunk key encoding: ${g}`)}function EQ(g){return g.find(I=>I.name==="transpose")?.configuration?.order==="F"?"F":"C"}const kD=/^([<|>])(.*)$/;function tD(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(kD);if(!A)throw new Error(`Invalid dtype: ${g}`);let[,I,B]=A,Q={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f4:"float32",f8:"float64"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);if(!Q)throw new Error(`Unsupported or unknown dtype: ${g}`);return I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function cD(g,A={}){let I=[],B=tD(g.dtype);g.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}}),"endian"in B&&B.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}});for(let{id:Q,...C}of g.filters??[])I.push({name:Q,configuration:C});if(g.compressor){let{id:Q,...C}=g.compressor;I.push({name:Q,configuration:C})}return{zarr_format:3,node_type:"array",shape:g.shape,data_type:B.data_type,chunk_grid:{name:"regular",configuration:{chunk_shape:g.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:g.dimension_separator??"."}},codecs:I,fill_value:g.fill_value,attributes:A}}function LD(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function JD(g,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return g===A;let I=g==="bool";if(A==="boolean")return I;let B=g.startsWith("v2:U")||g.startsWith("v2:S");if(A==="string")return B;let Q=g==="int64"||g==="uint64";if(A==="bigint")return Q;let C=g==="v2:object";return A==="object"?C:!B&&!Q&&!I&&!C}function rD(g){return g?.name==="sharding_indexed"}function cC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}const LC=YD();function YD(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function JC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class FB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=tC(I.data_type),this.#Q=I.shape,this.#A=pI(I.shape,EQ(I.codecs));const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new FB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return LC&&this.#B==="big"&&kC(I,JC(this.#I)),I}decode(A){return LC&&this.#B==="big"&&kC(A,JC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class iQ{kind="bytes_to_bytes";static fromConfig(){return new iQ}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}function nD(g,A){if(Number.isNaN(A))throw new Error("JsonCodec allow_nan is false but NaN was encountered during encoding.");if(A===Number.POSITIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but Infinity was encountered during encoding.");if(A===Number.NEGATIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but -Infinity was encountered during encoding.");return A}function KD(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class DQ{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:B=!1,ensure_ascii:Q=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:h=!0}=A;let s=A.separators;s||(o?s=[", ",": "]:s=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:o,separators:s,sort_keys:i},this.#I={strict:h}}static fromConfig(A){return new DQ(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;if(B!=="utf-8")throw new Error("JsonCodec does not yet support non-utf-8 encoding.");const o=[];if(!C)throw new Error("JsonCodec does not yet support skipping the check for circular references during encoding.");E||o.push(nD),i&&o.push(KD);const h=Array.from(A.data);h.push("|O"),h.push(A.shape);let s;o.length&&(s=(N,r)=>{let M=r;for(let e of o)M=e(N,M);return M});let R=JSON.stringify(h,s,I);return Q&&(R=R.replace(/[\u007F-\uFFFF]/g,N=>{const r=`0000${N.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(R)}decode(A){const{strict:I}=this.#I;if(!I)throw new Error("JsonCodec does not yet support non-strict decoding.");const B=Kg(A),Q=B.pop();if(B.pop(),!Q)throw new Error("0D not implemented for JsonCodec.");const C=pI(Q,"C");return{data:B,shape:Q,stride:C}}}function rC(g){return g instanceof UC||g instanceof CQ||g instanceof ng?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function MD(g,A){let I;return g.data instanceof CQ||g.data instanceof ng?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:pI(g.shape,A)}}function HD(g,A){let I=MD(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=rC(g.data),i=rC(I.data);for(let o=0;o<Q;o++){let h=0;for(let s=0;s<B;s++)h+=C[s]*I.stride[s];i[h]=E[o],C[0]+=1;for(let s=0;s<B;s++)if(C[s]===g.shape[s]){if(s+1===B)break;C[s]=0,C[s+1]+=1}}return I}function eD(g){if(!g.stride)return"C";let A=pI(g.shape,"C");return g.stride.every((I,B)=>I===A[B])?"C":"F"}class oQ{configuration;kind="array_to_array";constructor(A){this.configuration=A}static fromConfig(A){return new oQ(A)}encode(A){return eD(A)===this.configuration?.order?A:HD(A,this.configuration?.order??"C")}decode(A){return A}}class aQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=pI(A,"C")}static fromConfig(A,I){return new aQ(I.shape)}encode(A){throw new Error("Method not implemented.")}decode(A){let I=new TextDecoder,B=new DataView(A.buffer),Q=Array(B.getUint32(0,!0)),C=4;for(let E=0;E<Q.length;E++){let i=B.getUint32(C,!0);C+=4,Q[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:Q,shape:this.#A,stride:this.#I}}}function qD(){return new Map().set("blosc",()=>Promise.resolve().then(()=>os).then(g=>g.default)).set("gzip",()=>Promise.resolve().then(()=>ds).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>Ts).then(g=>g.default)).set("zlib",()=>Promise.resolve().then(()=>bs).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>vs).then(g=>g.default)).set("transpose",()=>oQ).set("bytes",()=>FB).set("crc32c",()=>iQ).set("vlen-utf8",()=>aQ).set("json2",()=>DQ).set("bitround",()=>QQ)}const dD=qD();function sQ(g){let A;return{async encode(I){A||(A=await YC(g));for(const Q of A.array_to_array)I=await Q.encode(I);let B=await A.array_to_bytes.encode(I);for(const Q of A.bytes_to_bytes)B=await Q.encode(B);return B},async decode(I){A||(A=await YC(g));for(let Q=A.bytes_to_bytes.length-1;Q>=0;Q--)I=await A.bytes_to_bytes[Q].decode(I);let B=await A.array_to_bytes.decode(I);for(let Q=A.array_to_array.length-1;Q>=0;Q--)B=await A.array_to_array[Q].decode(B);return B}}}async function YC(g){let A=g.codecs.map(async C=>{let E=await dD.get(C.name)?.();if(!E)throw new Error(`Unknown codec: ${C.name}`);return{Codec:E,meta:C}}),I=[],B,Q=[];for await(let{Codec:C,meta:E}of A){let i=C.fromConfig(E.configuration,g);switch(i.kind){case"array_to_array":I.push(i);break;case"array_to_bytes":B=i;break;default:Q.push(i)}}if(!B){if(!fD(g))throw new Error(`Cannot encode ${g.data_type} to bytes without a codec`);B=FB.fromConfig({endian:"little"},g)}return{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function fD(g){return g.data_type!=="v2:object"}const nC=18446744073709551615n;function lD(g,A,I,B){if(g.store.getRange===void 0)throw new Error("Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((o,h)=>o/B.chunk_shape[h]),E=sQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async o=>{let h=o.map((V,m)=>Math.floor(V/C[m])),s=g.resolve(I(h)).path,R;if(s in i)R=i[s];else{let V=4,m=16*C.reduce((u,W)=>u*W,1),b=await Q(s,{suffixLength:m+V});R=i[s]=b?await E.decode(b):null}if(R===null)return;let{data:N,shape:r,stride:M}=R,e=o.map((V,m)=>V%r[m]).reduce((V,m,b)=>V+m*M[b],0),n=N[e],f=N[e+1];if(!(n===nC&&f===nC))return Q(s,{offset:Number(n),length:Number(f)})}}class II{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new II(this.store,new URL(A,I).pathname)}}class yQ extends II{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}const Mg=Symbol("zarrita.context");function pD(g){return g[Mg]}function WD(g,A){let{configuration:I}=A.codecs.find(rD)??{},B={encode_chunk_key:UD(A.chunk_key_encoding),TypedArray:tC(A.data_type),fill_value:A.fill_value};if(I){let C=EQ(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:sQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E,i){return pI(E,i??C)},get_chunk_bytes:lD(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=EQ(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:sQ({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C,E){return pI(C,E??Q)},async get_chunk_bytes(C,E){let i=B.encode_chunk_key(C),o=g.resolve(i).path;return g.store.get(o,E)}}}let wB=class extends II{kind="array";#A;[Mg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:cC(B)},this[Mg]=WD(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[Mg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[Mg],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,o)=>i*o,1),E=new B.TypedArray(C);return E.fill(B.fill_value),{data:E,shape:B.chunk_shape,stride:B.get_strides(B.chunk_shape)}}return B.codec.decode(Q)}is(A){return JD(this.dtype,A)}},SB=mD();function mD(){let g=new WeakMap;function A(I){let B=g.get(I)??{v2:0,v3:0};return g.set(I,B),B}return{increment(I,B){A(I)[B]+=1},version_max(I){let B=A(I);return B.v3>B.v2?"v3":"v2"}}}async function TD(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Kg(A):{}}async function xD(g,A={}){let I="store"in g?g:new II(g),B={};return(A.attrs??!0)&&(B=await TD(I)),A.kind==="array"?KC(I,B):A.kind==="group"?MC(I,B):KC(I,B).catch(Q=>{if(Q instanceof Yg)return MC(I,B);throw Q})}async function KC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new Yg("v2 array",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new wB(g.store,g.path,cD(Kg(B),A))}async function MC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new Yg("v2 group",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new yQ(g.store,g.path,LD(Kg(B),A))}async function ZD(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new Yg("v3 array or group",{cause:new BQ(I)});let Q=Kg(B);return Q.node_type==="array"&&(Q.fill_value=cC(Q)),Q.node_type==="array"?new wB(A,g.path,Q):new yQ(A,g.path,Q)}async function bD(g,A={}){let I="store"in g?g:new II(g),B=await ZD(I);if(SB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof wB||A.kind==="group"&&B instanceof yQ)return B;let Q=B instanceof wB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function gI(g,A={}){let I="store"in g?g.store:g,B=SB.version_max(I),Q=B==="v2"?gI.v2:gI.v3,C=B==="v2"?gI.v3:gI.v2;return Q(g,A).catch(E=>{if(E instanceof Yg)return C(g,A);throw E})}gI.v2=xD,gI.v3=bD;function HC(g,A,I,B={}){return A!==void 0&&I!==void 0&&(B={...B,headers:{...B.headers,Range:`bytes=${A}-${A+I-1}`}}),fetch(g,B)}function uD(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function eC(g,A){const I=typeof g=="string"?new URL(g):g;I.pathname.endsWith("/")||(I.pathname+="/");const B=new URL(A.slice(1),I);return B.search=I.search,B}async function qC(g){if(g.status!==404){if(g.status===200||g.status===206)return new Uint8Array(await g.arrayBuffer());throw new Error(`Unexpected response status ${g.status} ${g.statusText}`)}}async function PD(g,A,I,B){if(B)return fetch(g,{...I,headers:{...I.headers,Range:`bytes=-${A}`}});let Q=await fetch(g,{...I,method:"HEAD"});if(!Q.ok)return Q;let C=Q.headers.get("Content-Length"),E=Number(C);return HC(g,E-A,E,I)}class Hg{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return uD(this.#A,A)}async get(A,I={}){let B=eC(this.url,A).href,Q=await fetch(B,this.#g(I));return qC(Q)}async getRange(A,I,B={}){let Q=eC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await PD(Q,I.suffixLength,C,this.#I):E=await HC(Q,I.offset,I.length,C),qC(E)}}function*OD(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*VD(...g){if(g.length===0)return;const A=g.map(B=>B[Symbol.iterator]()),I=A.map(B=>B.next());if(I.some(B=>B.done))throw new Error("Input contains an empty iterator.");for(let B=0;;){if(I[B].done){if(A[B]=g[B][Symbol.iterator](),I[B]=A[B].next(),++B>=A.length)return}else yield I.map(({value:Q})=>Q),B=0;I[B]=A[B].next()}}function XD({start:g,stop:A,step:I},B){if(I===0)throw new Error("slice step cannot be zero");I=I??1;const Q=I<0,[C,E]=Q?[-1,B-1]:[0,B];return g===null?g=Q?E:C:g<0?(g+=B,g<C&&(g=C)):g>E&&(g=E),A===null?A=Q?C:E:A<0?(A+=B,A<C&&(A=C)):A>E&&(A=E),[g,A,I]}function RB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function vD(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class hQ extends Error{constructor(A){super(A),this.name="IndexError"}}function jD(g,A){throw new hQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function zD(g){throw new hQ(`index out of bounds for dimension with length ${g}`)}function _D(){throw new hQ("only slices with step >= 1 are supported")}function $D(g,A){g.length>A.length&&jD(g,A)}function Ao(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&zD(A),g}class Io{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=Ao(A,I),this.dim_sel=A,this.dim_len=I,this.dim_chunk_len=B,this.nitems=1}*[Symbol.iterator](){const A=Math.floor(this.dim_sel/this.dim_chunk_len),I=A*this.dim_chunk_len,B=this.dim_sel-I;yield{dim_chunk_ix:A,dim_chunk_sel:B}}}class dC{start;stop;step;dim_len;dim_chunk_len;nitems;nchunks;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){const[Q,C,E]=XD(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&_D(),this.dim_len=I,this.dim_chunk_len=B,this.nitems=Math.max(0,Math.ceil((this.stop-this.start)/this.step)),this.nchunks=Math.ceil(this.dim_len/this.dim_chunk_len)}*[Symbol.iterator](){const A=Math.floor(this.start/this.dim_chunk_len),I=Math.ceil(this.stop/this.dim_chunk_len);for(const B of OD(A,I)){const Q=B*this.dim_chunk_len,C=Math.min(this.dim_len,(B+1)*this.dim_chunk_len),E=C-Q;let i=0,o=0;if(this.start<Q){const r=(Q-this.start)%this.step;r&&(o+=this.step-r),i=Math.ceil((Q-this.start)/this.step)}else o=this.start-Q;const h=this.stop>C?E:this.stop-Q,s=[o,h,this.step],R=Math.ceil((h-o)/this.step),N=[i,i+R,1];yield{dim_chunk_ix:B,dim_chunk_sel:s,dim_out_sel:N}}}}function go(g,A){let I=[];return g===null?I=A.map(B=>RB(null)):Array.isArray(g)&&(I=g.map(B=>B??RB(null))),$D(I,A),I}class Bo{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=go(A,I).map((Q,C)=>new(typeof Q=="number"?Io:dC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof dC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of VD(...this.dim_indexers)){const I=A.map(Q=>Q.dim_chunk_ix),B=A.map(Q=>"dim_out_sel"in Q?{from:Q.dim_chunk_sel,to:Q.dim_out_sel}:{from:Q.dim_chunk_sel,to:null});yield{chunk_coords:I,mapping:B}}}}function Qo(g,A){return"get"in g?g.get(A):g[A]}async function Co(g,A,I,B){let Q=pD(g),C=new Bo({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((o,h)=>o*h,1)),C.shape,Q.get_strides(C.shape,I.order)),i=I.create_queue?.()??vD();for(const{chunk_coords:o,mapping:h}of C)i.add(async()=>{let{data:s,shape:R,stride:N}=await g.getChunk(o,I.opts),r=B.prepare(s,R,N);B.set_from_chunk(E,r,h)});return await i.onIdle(),C.shape.length===0?Qo(E.data,0):E}function GQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return GQ(g,A+Q,C-Q)},set(Q,C=0){for(let E=0;E<Q.length;E++)g[A+C+E]=Q.get(E)},get(Q){return g[A+Q]}}}function FQ(g){return globalThis.Array.isArray(g.data)?{data:GQ(g.data),stride:g.stride,bytes_per_element:1}:{data:new Uint8Array(g.data.buffer,g.data.byteOffset,g.data.byteLength),stride:g.stride,bytes_per_element:g.data.BYTES_PER_ELEMENT}}function Eo(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function io(g,A){if(globalThis.Array.isArray(g.data))return GQ([A]);let I=Eo(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const Do={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=FQ(g);wQ(B,A,io(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=FQ(g);NB(B,FQ(A),B.bytes_per_element,I)}};async function oo(g,A=null,I={}){return Co(g,A,I,Do)}function fC(g,A,I){return I<0&&A<g?Math.floor((g-A-1)/-I)+1:g<A?Math.floor((A-g-1)/I)+1:0}function wQ(g,A,I,B){if(A.length===0){g.data.set(I,0);return}const[Q,...C]=A,[E,...i]=g.stride;if(typeof Q=="number"){const N=g.data.subarray(E*Q*B);wQ({data:N,stride:i},C,I,B);return}const[o,h,s]=Q,R=fC(o,h,s);if(C.length===0){for(let N=0;N<R;N++)g.data.set(I,E*(o+s*N)*B);return}for(let N=0;N<R;N++){const r=g.data.subarray(E*(o+s*N)*B);wQ({data:r,stride:i},C,I,B)}}function NB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[o,...h]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}NB({data:g.data.subarray(E*Q.to*I),stride:i},A,I,C);return}if(Q.to===null){if(C.length===0){let f=Q.from*I;g.data.set(A.data.subarray(f,f+I),0);return}NB(g,{data:A.data.subarray(o*Q.from*I),stride:h},I,C);return}const[s,R,N]=Q.to,[r,M,e]=Q.from,n=fC(s,R,N);if(C.length===0){if(N===1&&e===1&&E===1&&o===1){let f=r*I,V=n*I;g.data.set(A.data.subarray(f,f+V),s*I);return}for(let f=0;f<n;f++){let V=o*(r+e*f)*I;g.data.set(A.data.subarray(V,V+I),E*(s+N*f)*I)}return}for(let f=0;f<n;f++)NB({data:g.data.subarray(E*(s+f*N)*I),stride:i},{data:A.data.subarray(o*(r+f*e)*I),stride:h},I,C)}async function ao(g,A){const I=A.split("/"),B=I.pop();if(!B)throw new Error("Invalid path");for(const Q of I)g=await g.getDirectoryHandle(Q);return g.getFileHandle(B)}class SQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await ao(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}async function eg(g,A){if(A==="v2")try{return gI.v2(g,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${g}`)}if(A==="v3")try{return gI.v3(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${g}`)}try{return gI(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${g}`)}}async function so(g,A){if(A==="v2")try{return gI.v2(g,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${g}`)}if(A==="v3")try{return gI.v3(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${g}`)}try{return gI(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${g}`)}}async function yo(g){let A;switch(g.type){case"fetch":{A=new II(new Hg(g.url,g.fetchOptions));break}case"filesystem":{A=new II(new SQ(g.directoryHandle),g.path);break}default:{const B=g;throw new Error(`Unsupported store type: ${B}`)}}const I=g.arrayPath?A.resolve(g.arrayPath):A;return so(I,g.zarrVersion)}function ho(g,A,I,B){if(g.store instanceof Hg)return{type:"fetch",arrayPath:A,zarrVersion:I,url:g.store.url.toString(),fetchOptions:B};if(g.store instanceof SQ)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:g.store.directoryHandle,path:g.path};throw new Error(`Unsupported store type: ${g.store.constructor.name}`)}const lC=`class HI extends Error {
346
+ ${Q}`;return g.replace(pB,C)}const ZA=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];function bQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(ZA[g&255]+ZA[g>>8&255]+ZA[g>>16&255]+ZA[g>>24&255]+"-"+ZA[A&255]+ZA[A>>8&255]+"-"+ZA[A>>16&15|64]+ZA[A>>24&255]+"-"+ZA[I&63|128]+ZA[I>>8&255]+"-"+ZA[I>>16&255]+ZA[I>>24&255]+ZA[B&255]+ZA[B>>8&255]+ZA[B>>16&255]+ZA[B>>24&255]).toLowerCase()}class WB{uuid=bQ()}var fI=1e-6,lA=typeof Float32Array<"u"?Float32Array:Array,uE=Math.PI/180;function PE(g){return g*uE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function uQ(){var g=new lA(9);return lA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[5]=0,g[6]=0,g[7]=0),g[0]=1,g[4]=1,g[8]=1,g}function OE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[4],g[4]=A[5],g[5]=A[6],g[6]=A[8],g[7]=A[9],g[8]=A[10],g}function QI(){var g=new lA(16);return lA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=0,g[12]=0,g[13]=0,g[14]=0),g[0]=1,g[5]=1,g[10]=1,g[15]=1,g}function mB(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],o=A[6],h=A[7],s=A[8],R=A[9],N=A[10],r=A[11],M=A[12],e=A[13],n=A[14],f=A[15],V=I*i-B*E,m=I*o-Q*E,b=I*h-C*E,u=B*o-Q*i,W=B*h-C*i,gA=Q*h-C*o,O=s*e-R*M,x=s*n-N*M,$=s*f-r*M,IA=R*n-N*e,wA=R*f-r*e,kA=N*f-r*n,CA=V*kA-m*wA+b*IA+u*$-W*x+gA*O;return CA?(CA=1/CA,g[0]=(i*kA-o*wA+h*IA)*CA,g[1]=(Q*wA-B*kA-C*IA)*CA,g[2]=(e*gA-n*W+f*u)*CA,g[3]=(N*W-R*gA-r*u)*CA,g[4]=(o*$-E*kA-h*x)*CA,g[5]=(I*kA-Q*$+C*x)*CA,g[6]=(n*b-M*gA-f*m)*CA,g[7]=(s*gA-N*b+r*m)*CA,g[8]=(E*wA-i*$+h*O)*CA,g[9]=(B*$-I*wA-C*O)*CA,g[10]=(M*W-e*b+f*V)*CA,g[11]=(R*b-s*W-r*V)*CA,g[12]=(i*x-E*IA-o*O)*CA,g[13]=(I*IA-B*x+Q*O)*CA,g[14]=(e*m-M*u-n*V)*CA,g[15]=(s*u-R*m+N*V)*CA,g):null}function DB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],o=A[5],h=A[6],s=A[7],R=A[8],N=A[9],r=A[10],M=A[11],e=A[12],n=A[13],f=A[14],V=A[15],m=I[0],b=I[1],u=I[2],W=I[3];return g[0]=m*B+b*i+u*R+W*e,g[1]=m*Q+b*o+u*N+W*n,g[2]=m*C+b*h+u*r+W*f,g[3]=m*E+b*s+u*M+W*V,m=I[4],b=I[5],u=I[6],W=I[7],g[4]=m*B+b*i+u*R+W*e,g[5]=m*Q+b*o+u*N+W*n,g[6]=m*C+b*h+u*r+W*f,g[7]=m*E+b*s+u*M+W*V,m=I[8],b=I[9],u=I[10],W=I[11],g[8]=m*B+b*i+u*R+W*e,g[9]=m*Q+b*o+u*N+W*n,g[10]=m*C+b*h+u*r+W*f,g[11]=m*E+b*s+u*M+W*V,m=I[12],b=I[13],u=I[14],W=I[15],g[12]=m*B+b*i+u*R+W*e,g[13]=m*Q+b*o+u*N+W*n,g[14]=m*C+b*h+u*r+W*f,g[15]=m*E+b*s+u*M+W*V,g}function VE(g,A){return g[0]=A[0],g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=A[1],g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=A[2],g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g}function XE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=Q+Q,h=C+C,s=E+E,R=Q*o,N=Q*h,r=Q*s,M=C*h,e=C*s,n=E*s,f=i*o,V=i*h,m=i*s,b=B[0],u=B[1],W=B[2];return g[0]=(1-(M+n))*b,g[1]=(N+m)*b,g[2]=(r-V)*b,g[3]=0,g[4]=(N-m)*u,g[5]=(1-(R+n))*u,g[6]=(e+f)*u,g[7]=0,g[8]=(r+V)*W,g[9]=(e-f)*W,g[10]=(1-(R+M))*W,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function vE(g,A,I,B,Q){var C=1/Math.tan(A/2),E;return g[0]=C/I,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=C,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=-1,g[12]=0,g[13]=0,g[15]=0,Q!=null&&Q!==1/0?(E=1/(B-Q),g[10]=(Q+B)*E,g[14]=2*Q*B*E):(g[10]=-1,g[14]=-2*B),g}var jE=vE;function zE(g,A,I,B,Q,C,E){var i=1/(A-I),o=1/(B-Q),h=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*o,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*h,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*o,g[14]=(E+C)*h,g[15]=1,g}var _E=zE;function $E(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],o=B[1],h=B[2],s=Q-I[0],R=C-I[1],N=E-I[2],r=s*s+R*R+N*N;r>0&&(r=1/Math.sqrt(r),s*=r,R*=r,N*=r);var M=o*N-h*R,e=h*s-i*N,n=i*R-o*s;return r=M*M+e*e+n*n,r>0&&(r=1/Math.sqrt(r),M*=r,e*=r,n*=r),g[0]=M,g[1]=e,g[2]=n,g[3]=0,g[4]=R*n-N*e,g[5]=N*M-s*n,g[6]=s*e-R*M,g[7]=0,g[8]=s,g[9]=R,g[10]=N,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function rA(){var g=new lA(3);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function CI(g){var A=new lA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function PQ(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function NA(g,A,I){var B=new lA(3);return B[0]=g,B[1]=A,B[2]=I,B}function tg(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function _I(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function OQ(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function Ai(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function Ii(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function VQ(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function XQ(g,A,I,B){return g[0]=A[0]+I[0]*B,g[1]=A[1]+I[1]*B,g[2]=A[2]+I[2]*B,g}function vQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return Math.hypot(I,B,Q)}function gi(g,A){var I=A[0],B=A[1],Q=A[2],C=I*I+B*B+Q*Q;return C>0&&(C=1/Math.sqrt(C)),g[0]=A[0]*C,g[1]=A[1]*C,g[2]=A[2]*C,g}function jQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function TB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return g[0]=Q*o-C*i,g[1]=C*E-B*o,g[2]=B*i-Q*E,g}function Bi(g,A,I,B,Q,C){var E=1-C,i=E*E,o=C*C,h=i*E,s=3*C*i,R=3*o*E,N=o*C;return g[0]=A[0]*h+I[0]*s+B[0]*R+Q[0]*N,g[1]=A[1]*h+I[1]*s+B[1]*R+Q[1]*N,g[2]=A[2]*h+I[2]*s+B[2]*R+Q[2]*N,g}function oB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[3]*B+I[7]*Q+I[11]*C+I[15];return E=E||1,g[0]=(I[0]*B+I[4]*Q+I[8]*C+I[12])/E,g[1]=(I[1]*B+I[5]*Q+I[9]*C+I[13])/E,g[2]=(I[2]*B+I[6]*Q+I[10]*C+I[14])/E,g}function Qi(g,A){var I=g[0],B=g[1],Q=g[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=fI*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=fI*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=fI*Math.max(1,Math.abs(Q),Math.abs(i))}var xB=Ai,Ci=PQ;(function(){var g=rA();return function(A,I,B,Q,C,E){var i,o;for(I||(I=3),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2];return A}})();function cg(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function Ei(g){var A=new lA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function ZB(g,A,I,B){var Q=new lA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function ii(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function Di(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g[3]=A[3]*I,g}function oi(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=I*I+B*B+Q*Q+C*C;return E>0&&(E=1/Math.sqrt(E)),g[0]=I*E,g[1]=B*E,g[2]=Q*E,g[3]=C*E,g}function aB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3];return g[0]=I[0]*B+I[4]*Q+I[8]*C+I[12]*E,g[1]=I[1]*B+I[5]*Q+I[9]*C+I[13]*E,g[2]=I[2]*B+I[6]*Q+I[10]*C+I[14]*E,g[3]=I[3]*B+I[7]*Q+I[11]*C+I[15]*E,g}(function(){var g=cg();return function(A,I,B,Q,C,E){var i,o;for(I||(I=4),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],g[3]=A[i+3],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2],A[i+3]=g[3];return A}})();function bB(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function ai(g,A,I){I=I*.5;var B=Math.sin(I);return g[0]=B*A[0],g[1]=B*A[1],g[2]=B*A[2],g[3]=Math.cos(I),g}function si(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],o=I[1],h=I[2],s=I[3];return g[0]=B*s+E*i+Q*h-C*o,g[1]=Q*s+E*o+C*i-B*h,g[2]=C*s+E*h+B*o-Q*i,g[3]=E*s-B*i-Q*o-C*h,g}function uB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=I[0],h=I[1],s=I[2],R=I[3],N,r,M,e,n;return r=Q*o+C*h+E*s+i*R,r<0&&(r=-r,o=-o,h=-h,s=-s,R=-R),1-r>fI?(N=Math.acos(r),M=Math.sin(N),e=Math.sin((1-B)*N)/M,n=Math.sin(B*N)/M):(e=1-B,n=B),g[0]=e*Q+n*o,g[1]=e*C+n*h,g[2]=e*E+n*s,g[3]=e*i+n*R,g}function zQ(g,A){var I=A[0]+A[4]+A[8],B;if(I>0)B=Math.sqrt(I+1),g[3]=.5*B,B=.5/B,g[0]=(A[5]-A[7])*B,g[1]=(A[6]-A[2])*B,g[2]=(A[1]-A[3])*B;else{var Q=0;A[4]>A[0]&&(Q=1),A[8]>A[Q*3+Q]&&(Q=2);var C=(Q+1)%3,E=(Q+2)%3;B=Math.sqrt(A[Q*3+Q]-A[C*3+C]-A[E*3+E]+1),g[Q]=.5*B,B=.5/B,g[3]=(A[C*3+E]-A[E*3+C])*B,g[C]=(A[C*3+Q]+A[Q*3+C])*B,g[E]=(A[E*3+Q]+A[Q*3+E])*B}return g}var yi=Ei,hi=ii,PB=oi;(function(){var g=rA(),A=NA(1,0,0),I=NA(0,1,0);return function(B,Q,C){var E=jQ(Q,C);return E<-.999999?(TB(g,A,Q),Ci(g)<1e-6&&TB(g,I,Q),gi(g,g),ai(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(TB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,PB(B,B))}})(),function(){var g=bB(),A=bB();return function(I,B,Q,C,E,i){return uB(g,B,E,i),uB(A,Q,C,i),uB(I,g,A,2*i*(1-i)),I}}(),function(){var g=uQ();return function(A,I,B,Q){return g[0]=B[0],g[3]=B[1],g[6]=B[2],g[1]=Q[0],g[4]=Q[1],g[7]=Q[2],g[2]=-I[0],g[5]=-I[1],g[8]=-I[2],PB(A,zQ(A,g))}}();function _Q(){var g=new lA(2);return lA!=Float32Array&&(g[0]=0,g[1]=0),g}function $Q(g){var A=new lA(2);return A[0]=g[0],A[1]=g[1],A}function pA(g,A){var I=new lA(2);return I[0]=g,I[1]=A,I}function Gi(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function Fi(g){var A=g[0],I=g[1];return A*A+I*I}function wi(g,A,I,B){var Q=A[0],C=A[1];return g[0]=Q+B*(I[0]-Q),g[1]=C+B*(I[1]-C),g}function AC(g,A){return g[0]===A[0]&&g[1]===A[1]}function OB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=fI*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=fI*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=_Q();return function(A,I,B,Q,C,E){var i,o;for(I||(I=2),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;i+=I)g[0]=A[i],g[1]=A[i+1],C(g,g,E),A[i]=g[0],A[i+1]=g[1];return A}})();class tI{min;max;constructor(A,I){this.min=A?CI(A):NA(1/0,1/0,1/0),this.max=I?CI(I):NA(-1/0,-1/0,-1/0)}clone(){return new tI(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]||this.max[2]<=this.min[2]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1]||A.max[2]<=I.min[2]||A.min[2]>=I.max[2])}expandWithPoint(A){A[0]<this.min[0]&&(this.min[0]=A[0]),A[1]<this.min[1]&&(this.min[1]=A[1]),A[2]<this.min[2]&&(this.min[2]=A[2]),A[0]>this.max[0]&&(this.max[0]=A[0]),A[1]>this.max[1]&&(this.max[1]=A[1]),A[2]>this.max[2]&&(this.max[2]=A[2])}applyTransform(A){const{min:I,max:B}=this,Q=[NA(I[0],I[1],I[2]),NA(I[0],I[1],B[2]),NA(I[0],B[1],I[2]),NA(I[0],B[1],B[2]),NA(B[0],I[1],I[2]),NA(B[0],I[1],B[2]),NA(B[0],B[1],I[2]),NA(B[0],B[1],B[2])];this.min=NA(1/0,1/0,1/0),this.max=NA(-1/0,-1/0,-1/0);const C=rA();for(const E of Q)oB(C,E,A),this.expandWithPoint(C)}}const Si={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class $I extends WB{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],B="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=B,this.attributes_=[]}addAttribute(A){this.attributes_.push(A),this.boundingBox_=null}get vertexCount(){return this.vertexData_.byteLength/this.strideBytes}get stride(){return this.attributes_.reduce((A,I)=>A+I.itemSize,0)}get strideBytes(){return this.stride*Float32Array.BYTES_PER_ELEMENT}get primitive(){return this.primitive_}get vertexData(){return this.vertexData_}get indexData(){return this.indexData_}get attributes(){return this.attributes_}get boundingBox(){if(this.boundingBox_===null){const A=this.getAttribute("position");if(!A||this.vertexCount===0)throw new Error("Failed to generate bounding box");const I=(A.offset??0)/Float32Array.BYTES_PER_ELEMENT,B=new tI,Q=rA();for(let C=0;C<this.vertexData_.length;C+=this.stride)Q[0]=this.vertexData_[C+I+0],Q[1]=this.vertexData_[C+I+1],Q[2]=this.vertexData_[C+I+2],B.expandWithPoint(Q);this.boundingBox_=B}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class Ri{gl_;buffers_=new Map;currentGeometry_=null;constructor(A){this.gl_=A}bindGeometry(A){if(this.alreadyActive(A))return;this.buffers_.has(A)||this.generateBuffers(A);const I=this.buffers_.get(A);if(!I)throw new Error("Failed to retrieve buffer handles for object");this.gl_.bindVertexArray(I.vao),this.currentGeometry_=A}disposeObject(A){const I=this.buffers_.get(A);I&&(this.gl_.deleteVertexArray(I.vao),this.gl_.deleteBuffer(I.vbo),I.ebo&&this.gl_.deleteBuffer(I.ebo),this.buffers_.delete(A),this.currentGeometry_===A&&(this.currentGeometry_=null))}disposeAll(){for(const A of this.buffers_.keys())this.disposeObject(A)}alreadyActive(A){return this.currentGeometry_===A}generateBuffers(A){const I=this.gl_.createVertexArray();if(!I)throw new Error("Failed to create vertex array object (VAO)");this.gl_.bindVertexArray(I);const{vertexData:B}=A,Q=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(Q,C),this.gl_.bufferData(Q,B,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(s=>{const R=Si[s.type];this.gl_.vertexAttribPointer(R,s.itemSize,this.gl_.FLOAT,!1,i,s.offset),this.gl_.enableVertexAttribArray(R)});const o={vao:I,vbo:C},{indexData:h}=A;if(h.length){const s=this.gl_.ELEMENT_ARRAY_BUFFER,R=this.gl_.createBuffer();if(!R)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(s,R),this.gl_.bufferData(s,h,this.gl_.STATIC_DRAW),o.ebo=R}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class Ni{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}bindTexture(A,I){if(this.alreadyActive(A))return;if(I<0||I>=this.maxTextureUnits_)throw new Error(`Texture index ${I} must be in [0, ${this.maxTextureUnits_-1}]`);this.gl_.activeTexture(this.gl_.TEXTURE0+I);const B=this.getTextureType(A),Q=this.getDataFormatInfo(A.dataFormat,A.dataType);this.textures_.has(A)||this.generateTexture(A,Q,B);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(B,C),A.needsUpdate&&A.data!==null&&(this.configureTextureParameters(A,B),this.uploadTextureData(A,Q,B),A.needsUpdate=!1),this.currentTexture_=A}disposeTexture(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),this.currentTexture_===A&&(this.currentTexture_=null);const B=this.getDataFormatInfo(A.dataFormat,A.dataType),Q=this.computeStorageBytes(A,B);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-Q),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.disposeTexture(A);this.gpuTextureBytes_=0,this.textureCount_=0}get textureInfo(){return{textures:this.textureCount_,totalBytes:this.gpuTextureBytes_}}alreadyActive(A){return this.currentTexture_===A&&!A.needsUpdate}generateTexture(A,I,B){const Q=this.gl_.createTexture();if(!Q)throw new Error("Failed to create texture");if(this.gl_.bindTexture(B,Q),this.isTexture2D(A))this.gl_.texStorage2D(B,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(B,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=this.computeStorageBytes(A,I),this.textureCount_+=1,this.textures_.set(A,Q),this.gl_.bindTexture(B,null)}configureTextureParameters(A,I){const B=this.gl_,Q=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);B.pixelStorei(B.UNPACK_ALIGNMENT,A.unpackAlignment),B.texParameteri(I,B.TEXTURE_MIN_FILTER,Q),B.texParameteri(I,B.TEXTURE_MAG_FILTER,C),B.texParameteri(I,B.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),B.texParameteri(I,B.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),B.texParameteri(I,B.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,B){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(B,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(B,0,C.x,C.y,C.z,A.width,A.height,A.depth,I.format,I.type,A.data);else throw new Error("Attempting to upload data for an unsupported texture type")}getFilter(A,I){const{dataFormat:B,dataType:Q}=I;if(B==="scalar"&&Q!=="float"&&A!=="nearest")return j.warn("WebGLTexture","Integer values are not filterable. Using gl.NEAREST instead."),this.gl_.NEAREST;switch(A){case"nearest":return this.gl_.NEAREST;case"linear":return this.gl_.LINEAR;default:throw new Error(`Unsupported texture filter: ${A}`)}}getTextureType(A){if(this.isTexture2D(A))return this.gl_.TEXTURE_2D;if(this.isTexture2DArray(A))return this.gl_.TEXTURE_2D_ARRAY;if(this.isTexture3D(A))return this.gl_.TEXTURE_3D;throw new Error(`Unknown texture type ${A.type}`)}getWrapMode(A){switch(A){case"repeat":return this.gl_.REPEAT;case"clamp_to_edge":return this.gl_.CLAMP_TO_EDGE;default:throw new Error(`Unsupported wrap mode: ${A}`)}}getDataFormatInfo(A,I){if(A==="rgba"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGBA8,format:this.gl_.RGBA,type:this.gl_.UNSIGNED_BYTE};if(A==="rgb"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGB8,format:this.gl_.RGB,type:this.gl_.UNSIGNED_BYTE};if(A==="scalar")switch(I){case"byte":return{internalFormat:this.gl_.R8I,format:this.gl_.RED_INTEGER,type:this.gl_.BYTE};case"short":return{internalFormat:this.gl_.R16I,format:this.gl_.RED_INTEGER,type:this.gl_.SHORT};case"int":return{internalFormat:this.gl_.R32I,format:this.gl_.RED_INTEGER,type:this.gl_.INT};case"unsigned_byte":return{internalFormat:this.gl_.R8UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_BYTE};case"unsigned_short":return{internalFormat:this.gl_.R16UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_SHORT};case"unsigned_int":return{internalFormat:this.gl_.R32UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_INT};case"float":return{internalFormat:this.gl_.R32F,format:this.gl_.RED,type:this.gl_.FLOAT};default:throw new Error(`Unsupported scalar type: ${I}`)}throw new Error(`Unsupported format/type: ${A}/${I}`)}computeStorageBytes(A,I){const B=this.bytesPerTexel(I),Q=Math.max(1,A.mipmapLevels),C=this.isTextureStorage3D(A)?Math.max(1,A.depth):1;let E=Math.max(1,A.width),i=Math.max(1,A.height),o=0;for(let h=0;h<Q;h++)o+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class jA{min;max;constructor(A,I){this.min=A?$Q(A):pA(1/0,1/0),this.max=I?$Q(I):pA(-1/0,-1/0)}clone(){return new jA(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1])}static equals(A,I){return AC(A.min,I.min)&&AC(A.max,I.max)}floor(){return new jA(pA(Math.floor(this.min[0]),Math.floor(this.min[1])),pA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],B=this.max[0]-this.min[0],Q=this.max[1]-this.min[1];return{x:A,y:I,width:B,height:Q}}}class Ui{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;constructor(A){this.gl_=A}enable(A){this.enabledCapabilities_.get(A)||(this.gl_.enable(A),this.enabledCapabilities_.set(A,!0))}disable(A){this.enabledCapabilities_.get(A)&&(this.gl_.disable(A),this.enabledCapabilities_.set(A,!1))}setBlendFunc(A,I){(this.blendSrcFactor_!==A||this.blendDstFactor_!==I)&&(this.gl_.blendFunc(A,I),this.blendSrcFactor_=A,this.blendDstFactor_=I)}setDepthTesting(A){A?this.enable(this.gl_.DEPTH_TEST):this.disable(this.gl_.DEPTH_TEST)}setBlending(A){A?this.enable(this.gl_.BLEND):this.disable(this.gl_.BLEND)}setDepthMask(A){this.depthMaskEnabled_!==A&&(this.gl_.depthMask(A),this.depthMaskEnabled_=A)}setBlendingMode(A){if(this.currentBlendingMode_!==A){if(A==="none")this.setBlending(!1);else switch(this.setBlending(!0),A){case"additive":this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE);break;case"multiply":this.setBlendFunc(this.gl_.DST_COLOR,this.gl_.ZERO);break;case"subtractive":this.setBlendFunc(this.gl_.ZERO,this.gl_.ONE_MINUS_SRC_COLOR);break;case"normal":default:this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE_MINUS_SRC_ALPHA);break}this.currentBlendingMode_=A}}setViewport(A){const I=A.floor();if(this.currentViewport_&&jA.equals(I,this.currentViewport_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.viewport(B,Q,C,E),this.currentViewport_=I}setScissorTest(A){A?this.enable(this.gl_.SCISSOR_TEST):(this.disable(this.gl_.SCISSOR_TEST),this.currentScissor_=null)}setScissor(A){const I=A.floor();if(this.currentScissor_&&jA.equals(I,this.currentScissor_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.scissor(B,Q,C,E),this.currentScissor_=I}setCullFace(A){A?this.enable(this.gl_.CULL_FACE):this.disable(this.gl_.CULL_FACE)}setCullFaceMode(A){if(this.currentCullingMode_!==A){if(A==="none")this.setCullFace(!1);else switch(this.setCullFace(!0),A){case"front":this.gl_.cullFace(this.gl_.FRONT);break;case"back":this.gl_.cullFace(this.gl_.BACK);break;case"both":this.gl_.cullFace(this.gl_.FRONT_AND_BACK);break}this.currentCullingMode_=A}}}const ki=VE(QI(),[1,-1,1]);class IC extends KE{gl_=null;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;constructor(A){if(super(A),this.gl_=this.canvas.getContext("webgl2",{depth:!0,antialias:!0}),!this.gl_)throw new Error("Failed to initialize WebGL2 context");j.info("WebGLRenderer",`WebGL version ${this.gl.getParameter(this.gl.VERSION)}`),this.programs_=new bE(this.gl),this.bindings_=new Ri(this.gl),this.textures_=new Ni(this.gl),this.state_=new Ui(this.gl),this.resize(this.canvas.width,this.canvas.height)}render(A){const I=A.getBoxRelativeTo(this.canvas),B=new jA(pA(0,0),pA(this.width,this.height));if(jA.equals(I.floor(),B.floor()))this.state_.setScissorTest(!1);else if(jA.intersects(I,B))this.state_.setScissor(I),this.state_.setScissorTest(!0);else{j.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(I),this.renderedObjectsPerFrame_=0,this.clear();const{opaque:Q,transparent:C}=A.layerManager.partitionLayers();this.state_.setDepthMask(!0);const E=A.camera.frustum;for(const i of Q)i.update(),i.state==="ready"&&this.renderLayer(i,A.camera,E);this.state_.setDepthMask(!1);for(const i of C)i.update(),i.state==="ready"&&this.renderLayer(i,A.camera,E);this.state_.setDepthMask(!0),this.renderedObjects_=this.renderedObjectsPerFrame_}get textureInfo(){return this.textures_.textureInfo}renderLayer(A,I,B){this.state_.setBlendingMode(A.transparent?A.blendMode:"none"),A.objects.forEach((Q,C)=>{B.intersectsWithBox3(Q.boundingBox)&&(this.renderObject(A,C,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];this.state_.setCullFaceMode(Q.cullFaceMode),this.bindings_.bindGeometry(Q.geometry),Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),Q.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(Q.programName);if(this.drawGeometry(Q.geometry,Q,A,C,B),Q.wireframeEnabled){this.bindings_.bindGeometry(Q.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",Q.wireframeColor.rgb),this.drawGeometry(Q.wireframeGeometry,Q,A,E,B)}}drawGeometry(A,I,B,Q,C){const E=DB(QI(),C.viewMatrix,I.transform.matrix),i=DB(QI(),ki,C.projectionMatrix),o=[this.canvas.width,this.canvas.height],h=I.getUniforms();for(const N of Q.uniformNames)switch(N){case"ModelView":Q.setUniform(N,E);break;case"Projection":Q.setUniform(N,i);break;case"Resolution":Q.setUniform(N,o);break;case"u_opacity":Q.setUniform(N,B.opacity);break;default:N in h&&Q.setUniform(N,h[N])}const s=this.glGetPrimitive(A.primitive),R=A.indexData;R.length?this.gl.drawElements(s,R.length,this.gl.UNSIGNED_INT,0):this.gl.drawArrays(s,0,A.vertexCount)}glGetPrimitive(A){switch(A){case"points":return this.gl.POINTS;case"triangles":return this.gl.TRIANGLES;case"lines":return this.gl.LINES;default:{const I=A;throw new Error(`Unknown Primitive type: ${I}`)}}}resize(A,I){const B=new jA(pA(0,0),pA(A,I));this.state_.setViewport(B)}clear(){this.gl.clearColor(...this.backgroundColor.rgba),this.gl.clear(this.gl.COLOR_BUFFER_BIT|this.gl.DEPTH_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl.depthFunc(this.gl.LEQUAL)}get gl(){return this.gl_}}const ti=8;class ci{maxConcurrent_;pending_=[];running_=new Map;constructor(A=ti){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(B=>B.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(Q=>Q.chunk===A);if(I>=0){this.pending_.splice(I,1),j.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),j.debug("ChunkQueue","Cancelled fetch request"))}get pendingCount(){return this.pending_.length}get runningCount(){return this.running_.size}pump(){if(!(this.running_.size>=this.maxConcurrent_||this.pending_.length===0))for(this.pending_.sort((A,I)=>{const B=A.chunk.priority??Number.MAX_SAFE_INTEGER,Q=I.chunk.priority??Number.MAX_SAFE_INTEGER;return B===Q?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):B-Q});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:B}=A;I.state="loading";const Q=new AbortController,C=Promise.resolve().then(()=>B(Q.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&j.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const gC=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function BC(g){if(gC.some(I=>g instanceof I))return!0;const A=gC.map(I=>I.name);return j.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function Li(g,A){return Math.round((A-g.translation)/g.scale)}function VB(g,A,I=1e-6){return Math.abs(g-A)<=I}function Lg(g,A,I){return Math.max(A,Math.min(I,g))}const QC=Symbol("INTERNAL_POLICY_KEY");class Ji{chunks_;loader_;lowestResLOD_;sliceCoords_;dimensions_;tIndicesWithQueuedChunks_=new Set;sourceMaxSquareDistance2D_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastZBounds_;lastTCoord_;constructor(A,I,B){this.loader_=A,this.policy_=B,this.dimensions_=this.loader_.getSourceDimensionMap(),this.lowestResLOD_=this.dimensions_.numLods-1,this.currentLOD_=0,this.sliceCoords_=I,j.info("ChunkManagerSource","Using image source policy:",this.policy_.profile),this.validateXYScaleRatios();const{size:Q}=this.getAndValidateTimeDimension(),{size:C}=this.getAndValidateChannelDimension(),E=this.dimensions_.x.lods[0],i=this.dimensions_.y.lods[0];this.sourceMaxSquareDistance2D_=Fi(pA(E.size*E.scale,i.size*i.scale)),this.chunks_=Array.from({length:Q},()=>[]);for(let o=0;o<Q;++o){const h=this.chunks_[o];for(let s=0;s<this.dimensions_.numLods;++s){const R=this.dimensions_.x.lods[s],N=this.dimensions_.y.lods[s],r=this.dimensions_.z?.lods[s],M=R.chunkSize,e=N.chunkSize,n=r?.chunkSize??1,f=Math.ceil(R.size/M),V=Math.ceil(N.size/e),m=Math.ceil((r?.size??1)/n);for(let b=0;b<f;++b){const u=R.translation+b*R.chunkSize*R.scale;for(let W=0;W<V;++W){const gA=N.translation+W*N.chunkSize*N.scale;for(let O=0;O<m;++O){const x=r!==void 0?r.translation+O*n*r.scale:0;for(let $=0;$<C;++$)h.push({state:"unloaded",lod:s,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(M,R.size-b*M),y:Math.min(e,N.size-W*e),z:Math.min(n,(r?.size??1)-O*n),c:1},rowAlignmentBytes:1,chunkIndex:{x:b,y:W,z:O,c:$,t:o},scale:{x:R.scale,y:N.scale,z:r?.scale??1},offset:{x:u,y:gA,z:x}})}}}}}}getChunks(){const A=this.getChunksAtCurrentTime(),I=A.filter(Q=>Q.lod===this.currentLOD_&&Q.visible&&Q.state==="loaded");return this.currentLOD_===this.lowestResLOD_?I:[...A.filter(Q=>Q.lod===this.lowestResLOD_&&Q.visible&&Q.state==="loaded"),...I]}getChunksAtCurrentTime(){return this.chunks_[this.getCurrentTimeIndex()]}getCurrentTimeIndex(){return this.sliceCoords_.t===void 0||this.dimensions_.t===void 0?0:Li(this.dimensions_.t.lods[0],this.sliceCoords_.t)}allVisibleLowestLODLoaded(){return this.getChunksAtCurrentTime().filter(A=>A.visible&&A.lod===this.lowestResLOD_).every(A=>A.state==="loaded")}updateAndCollectChunkChanges(A,I){this.setLOD(A);const B=this.getZBounds(),C=this.policyChanged_||this.viewBounds2DChanged(I)||this.zBoundsChanged(B)||this.lastTCoord_!==this.sliceCoords_.t?this.updateAndCollectChunkChangesForCurrentLod(I):[];return this.policyChanged_=!1,this.lastViewBounds2D_=I.clone(),this.lastZBounds_=B,this.lastTCoord_=this.sliceCoords_.t,C}get lodCount(){return this.lowestResLOD_+1}get dimensions(){return this.dimensions_}get currentLOD(){return this.currentLOD_}setImageSourcePolicy(A,I){if(I!==QC)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,j.info("ChunkManagerSource","Using image source policy:",this.policy_.profile))}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}setLOD(A){const I=this.dimensions_.x.lods[0].scale,Q=this.policy_.lod.bias-Math.log2(I)-A,C=Math.floor(Q),E=Math.max(0,Math.min(this.lowestResLOD_,this.policy_.lod.min)),i=Math.max(E,Math.min(this.lowestResLOD_,this.policy_.lod.max)),o=Lg(C,E,i);o!==this.currentLOD_&&(this.currentLOD_=o)}updateAndCollectChunkChangesForCurrentLod(A){if(this.chunks_.length===0)return j.warn("ChunkManagerSource","updateChunkVisibility called with no chunks initialized"),[];const I=_Q();wi(I,A.min,A.max,.5);const[B,Q]=this.getZBounds(),C=new tI(NA(A.min[0],A.min[1],B),NA(A.max[0],A.max[1],Q)),E=[],i=this.getCurrentTimeIndex();if(this.sliceCoords_.t!==void 0){const h=this.disposeStaleTimeChunks(i);E.push(...h)}const o=this.updateChunksAtTimeIndex(i,C,I);if(E.push(...o),this.sliceCoords_.t!==void 0){const h=this.markTimeChunksForPrefetch(i,C,I);E.push(...h)}return E}disposeStaleTimeChunks(A){const I=[];for(const B of this.tIndicesWithQueuedChunks_){const Q=B-A;if(Q>=0&&Q<=this.policy_.prefetch.t)continue;const C=this.chunks_[B];for(const E of C)this.disposeChunk(E),I.push(E);this.tIndicesWithQueuedChunks_.delete(B)}return I}updateChunksAtTimeIndex(A,I,B){const Q=this.getPaddedBounds(I),C=this.chunks_[A];this.tIndicesWithQueuedChunks_.add(A);for(const E of C){const i=this.isChunkWithinBounds(E,I),o=this.isChunkChannelInSlice(E),h=!i&&o&&this.isChunkWithinBounds(E,Q),s=E.lod===this.currentLOD_,R=E.lod===this.lowestResLOD_,N=E.state==="loaded";E.visible=i,E.prefetch=h&&s&&!N,E.priority=this.computePriority(R,s,i,E.prefetch,o),E.priority!==null&&E.state==="unloaded"?E.state="queued":E.priority===null&&E.state==="queued"&&(E.state="unloaded",E.orderKey=null),E.priority!==null&&(E.orderKey=this.squareDistance2D(E,B)),this.shouldDispose(N,R,s,i,h,o)&&this.disposeChunk(E)}return C}markTimeChunksForPrefetch(A,I,B){const Q=Math.min(this.chunks_.length-1,A+this.policy_.prefetch.t),C=[];for(let E=A+1;E<=Q;++E)for(const i of this.chunks_[E]){if(i.state!=="unloaded"||i.lod!==this.lowestResLOD_||!this.isChunkChannelInSlice(i)||!this.isChunkWithinBounds(i,I))continue;i.prefetch=!0,i.priority=this.policy_.priorityMap.prefetchTime;const o=this.squareDistance2D(i,B),h=Lg(o/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON);i.orderKey=E-A+h,i.state="queued",this.tIndicesWithQueuedChunks_.add(E),C.push(i)}return C}isChunkChannelInSlice(A){return this.sliceCoords_.c===void 0||this.sliceCoords_.c===A.chunkIndex.c}shouldDispose(A,I,B,Q,C,E){return A?E?I?!1:B?!Q&&!C:!0:!0:!1}disposeChunk(A){A.data=void 0,A.state="unloaded",A.priority=null,A.orderKey=null,A.prefetch=!1}computePriority(A,I,B,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&B?E.fallbackVisible:I&&B?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let B=1;B<this.dimensions_.numLods;B++){const Q=A.lods[B].scale/A.lods[B-1].scale,C=I.lods[B].scale/I.lods[B-1].scale;if(!VB(Q,2,.02)||!VB(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${B-1} → ${B}: expected (2× in X and Y), but got (${Q.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[B-1].scale}, ${I.lods[B-1].scale}] → [${A.lods[B].scale}, ${I.lods[B].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;if(I.chunkSize!==1)throw new Error(`ChunkManager only supports a chunk size of 1 in t. Found ${I.chunkSize} at LOD ${A}`);const B=this.dimensions_.t?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkManager does not support downsampling in t. Found ${B.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.chunkSize!==1)throw new Error(`ChunkManager only supports a chunk size of 1 in c. Found ${I.chunkSize} at LOD ${A}`);if(I.scale!==1)throw new Error(`ChunkManager does not support scale in c. Found ${I.scale} at LOD ${A}`);if(I.translation!==0)throw new Error(`ChunkManager does not support translation in c. Found ${I.translation} at LOD ${A}`);const B=this.dimensions_.c?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkManager does not support downsampling in c. Found ${B.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}isChunkWithinBounds(A,I){const B=new tI(NA(A.offset.x,A.offset.y,A.offset.z),NA(A.offset.x+A.shape.x*A.scale.x,A.offset.y+A.shape.y*A.scale.y,A.offset.z+A.shape.z*A.scale.z));return tI.intersects(B,I)}getZBounds(){const A=this.dimensions_.z;if(A===void 0||this.sliceCoords_.z===void 0)return[0,1];const I=A.lods[this.currentLOD_],B=I.size,Q=I.scale,C=I.translation,E=Math.floor((this.sliceCoords_.z-C)/Q),i=I.chunkSize,o=Math.max(0,Math.min(Math.floor(E/i),Math.ceil(B/i)-1));return[C+o*i*Q,C+(o+1)*i*Q]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!OB(this.lastViewBounds2D_.min,A.min)||!OB(this.lastViewBounds2D_.max,A.max)}zBoundsChanged(A){return!this.lastZBounds_||!OB(this.lastZBounds_,A)}getPaddedBounds(A){const I=this.dimensions_.x.lods[this.currentLOD_],B=this.dimensions_.y.lods[this.currentLOD_],Q=this.dimensions_.z?.lods[this.currentLOD_],C=I.chunkSize*I.scale*this.policy_.prefetch.x,E=B.chunkSize*B.scale*this.policy_.prefetch.y;let i=0;return Q&&(i=Q.chunkSize*Q.scale*this.policy_.prefetch.z),new tI(NA(A.min[0]-C,A.min[1]-E,A.min[2]-i),NA(A.max[0]+C,A.max[1]+E,A.max[2]+i))}squareDistance2D(A,I){const B={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},Q=B.x-I[0],C=B.y-I[1];return Q*Q+C*C}}class ri{sources_=new Map;pendingSources_=new Map;queue_=new ci;async addSource(A,I,B){const Q=this.sources_.get(A)??this.pendingSources_.get(A);if(Q)return Q;const E=(async()=>{const i=await A.open(),o=new Ji(i,I,B);return this.sources_.set(A,o),this.pendingSources_.delete(A),o})();return this.pendingSources_.set(A,E),E}update(A,I){if(this.sources_.size===0)return;if(A.type!=="OrthographicCamera")throw new Error("ChunkManager currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const B=A.getWorldViewRect(),C=Math.abs(B.max[0]-B.min[0])/I,E=Math.log2(1/C);for(const[i,o]of this.sources_){const h=o.updateAndCollectChunkChanges(E,B);for(const s of h)s.priority===null?this.queue_.cancel(s):s.state==="queued"&&this.queue_.enqueue(s,R=>o.loadChunkData(s,R))}this.queue_.flush()}}var Jg=function(g=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(R){R.preventDefault(),Q(++A%I.children.length)},!1);function B(R){return I.appendChild(R.dom),R}function Q(R){for(var N=0;N<I.children.length;N++)I.children[N].style.display=N===R?"block":"none";A=R}var C=(performance||Date).now(),E=C,i=0,o=B(new Jg.Panel("FPS","#0ff","#002",g)),h=B(new Jg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var s=B(new Jg.Panel("MB","#f08","#201",g));return Q(0),{REVISION:16,dom:I,addPanel:B,showPanel:Q,begin:function(){C=(performance||Date).now()},end:function(){i++;var R=(performance||Date).now();if(h.update(R-C,200),R>=E+1e3&&(o.update(i*1e3/(R-E),100),E=R,i=0,s)){var N=performance.memory;s.update(N.usedJSHeapSize/1048576,N.jsHeapSizeLimit/1048576)}return R},update:function(){C=this.end()},domElement:I,setMode:Q}};Jg.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*B),h=E(48*i*B),s=E(3*i*B),R=E(2*i*B),N=E(3*i*B),r=E(15*i*B),M=E(74*i*B),e=E(30*i*B),n=document.createElement("canvas");n.width=o,n.height=h,n.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var f=n.getContext("2d");return f.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",f.textBaseline="top",f.fillStyle=I,f.fillRect(0,0,o,h),f.fillStyle=A,f.fillText(g,s,R),f.fillRect(N,r,M,e),f.fillStyle=I,f.globalAlpha=.9,f.fillRect(N,r,M,e),{dom:n,update:function(V,m){Q=Math.min(Q,V),C=Math.max(C,V),f.fillStyle=I,f.globalAlpha=1,f.fillRect(0,0,o,r),f.fillStyle=A,f.fillText(E(V)+" "+g+" ("+E(Q)+"-"+E(C)+")",s,R),f.drawImage(n,N+i,r,M-i,e,N,r,M-i,e),f.fillRect(N+M-i,r,i,e),f.fillStyle=I,f.globalAlpha=.9,f.fillRect(N+M-i,r,i,E((1-V/m)*e))}}};function Yi({scale:g}={scale:1.5}){const A=new Jg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class CC{layers_=[];callbacks_=[];context_;constructor(A){this.context_=A}partitionLayers(){const A=[],I=[];for(const B of this.layers)B.transparent?I.push(B):A.push(B);return{opaque:A,transparent:I}}add(A){this.layers_=[...this.layers_,A],this.context_&&A.onAttached(this.context_),this.notifyLayersChanged()}remove(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.removeByIndex(I)}removeByIndex(A){const I=this.layers_[A];I&&I.onDetached(),this.layers_=this.layers_.filter((B,Q)=>Q!==A),this.notifyLayersChanged()}removeAll(){for(const A of this.layers_)A.onDetached();this.layers_=[],this.notifyLayersChanged()}get layers(){return this.layers_}notifyLayersChanged(){for(const A of this.callbacks_)A()}addLayersChangeCallback(A){return this.callbacks_.push(A),()=>{this.removeLayersChangeCallback(A)}}removeLayersChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove not found: ${A}`);this.callbacks_.splice(I,1)}}const XB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function ni(g){return XB.includes(g)}class Ki{propagationStopped_=!1;type;event;worldPos;clipPos;constructor(A,I){this.type=A,this.event=I}get propagationStopped(){return this.propagationStopped_}stopPropagation(){this.propagationStopped_=!0}}class Mi{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){j.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,XB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){j.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,XB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!ni(A.type)){j.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new Ki(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class EC{id;element;camera;layerManager;events;cameraControls;constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.layerManager=A.layerManager,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new Mi(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=pA(B,Q);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const B of this.layerManager.layers)if(B.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.layerManager.add(I)}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),B=A.getBoundingClientRect(),Q=window.devicePixelRatio||1,C=B.left*Q,E=B.top*Q,i=B.height*Q,o=I.x-C,h=I.y-E,s=Math.floor(o),R=Math.floor(i-h-I.height),N=Math.floor(I.width),r=Math.floor(I.height);return new jA(pA(s,R),pA(s+N,R+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return NA(2*(B-C.x)/C.width-1,2*(Q-C.y)/C.height-1,I)}clientToWorld(A,I=0){const B=this.clientToClip(A,I);return this.camera.clipToWorld(B)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,B=A.left*I,Q=A.top*I,C=A.width*I,E=A.height*I;return new jA(pA(B,Q),pA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){j.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const B=A/I;this.camera.setAspectRatio(B)}}function Hi(g){const A=new Map,I=new Set;for(const B of g){if(I.has(B.id))throw new Error(`Duplicate viewport ID "${B.id}". Each viewport must have a unique ID.`);if(I.add(B.id),A.has(B.element)){const Q=A.get(B.element),C=B.element.tagName.toLowerCase()+(B.element.id?`#${B.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${Q}" and "${B.id}" both use ${C}`)}A.set(B.element,B.id)}}function iC(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??bQ(),layerManager:new CC(I)}});return Hi(B),B.map(Q=>new EC(Q))}class ei{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;changed_=!1;constructor(A=[]){this.elements_=A}connect(){if(this.resizeObserver_){j.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.changed_=!0});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}getAndResetChanged(){const A=this.changed_;return this.changed_=!1,A}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.changed_=!0,this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){j.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}}class qi{lastAnimationId_;chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;constructor(A){if(this.canvas=A.canvas,A.viewports.length===0)throw new Error("At least one viewport config must be specified.");this.renderer_=new IC(this.canvas),this.chunkManager_=new ri,this.context_={chunkManager:this.chunkManager_},this.viewports_=iC(A.viewports,this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=Yi());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new ei(I)}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get textureInfo(){return this.renderer_.textureInfo}get viewports(){return this.viewports_}getViewport(A){return this.viewports_.find(I=>I.id===A)}start(){if(j.info("Idetik","Idetik runtime starting"),this.lastAnimationId_===void 0){for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.animate()}else j.warn("Idetik","Idetik runtime already started");return this}animate(A){this.stats_&&this.stats_.begin(),this.sizeObserver_.getAndResetChanged()&&this.updateSize();for(const I of this.viewports_)I.camera.type==="OrthographicCamera"&&this.chunkManager_.update(I.camera,I.getBoxRelativeTo(this.canvas).toRect().width),this.renderer_.render(I);for(const I of this.overlays)I.update(this,A);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(I=>this.animate(I))}stop(){if(j.info("Idetik","Idetik runtime stopping"),this.lastAnimationId_===void 0)j.warn("Idetik","Idetik runtime not started");else{this.sizeObserver_.disconnect();for(const A of this.viewports_)A.events.disconnect();cancelAnimationFrame(this.lastAnimationId_),this.lastAnimationId_=void 0}}updateSize(){this.renderer_.updateSize();for(const A of this.viewports_)A.updateSize()}}class di extends $I{constructor(A){if(super(),A.primitive!="triangles"){j.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){j.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,B=[],Q=(E,i)=>{const o=Math.min(E,i),h=Math.max(E,i);I.has({i0:o,i1:h})||(I.add({i0:o,i1:h}),B.push(o,h))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],h=C[E+2];Q(i,o),Q(o,h),Q(h,i)}this.indexData_=new Uint32Array(B)}}const fi=NA(0,1,0);class li{dirty_=!0;matrix_=QI();rotation_=bB();translation_=rA();scale_=NA(1,1,1);addRotation(A){si(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){hi(this.rotation_,A),this.dirty_=!0}get rotation(){return yi(this.rotation_)}addTranslation(A){OQ(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){tg(this.translation_,A),this.dirty_=!0}get translation(){return CI(this.translation_)}addScale(A){Ii(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){tg(this.scale_,A),this.dirty_=!0}targetTo(A){Qi(this.translation_,A)&&(A=CI(A),A[2]+=fI);const I=$E(QI(),this.translation_,A,fi),B=OE(uQ(),I);zQ(this.rotation_,B),PB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return CI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return mB(QI(),this.matrix)}computeMatrix(){XE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Ag extends WB{wireframeEnabled=!1;wireframeColor=hA.WHITE;textures_=[];staleTextures_=[];transform_=new li;geometry_=new $I;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const B=this.textures_[A];B!==void 0&&this.staleTextures_.push(B),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new di(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){if(this.programName_===null)throw new Error("Program name not set");return this.programName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class lI{normal;signedDistance;constructor(A=NA(0,1,0),I=0){this.normal=CI(A),this.signedDistance=I}set(A,I){this.normal=CI(A),this.signedDistance=I}signedDistanceToPoint(A){return jQ(this.normal,A)+this.signedDistance}normalize(){const A=PQ(this.normal);if(A>0){const I=1/A;VQ(this.normal,this.normal,I),this.signedDistance*=I}}}class DC{planes_;constructor(A){this.planes_=[new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=rA();this.planes_[0].set(_I(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(_I(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(_I(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(_I(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(_I(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(_I(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const B of this.planes_)B.normalize()}intersectsWithBox3(A){const I=rA();for(const B of this.planes_){const Q=B.normal;if(I[0]=Q[0]>0?A.max[0]:A.min[0],I[1]=Q[1]>0?A.max[1]:A.min[1],I[2]=Q[2]>0?A.max[2]:A.min[2],B.signedDistanceToPoint(I)<0)return!1}return!0}}class oC extends Ag{projectionMatrix_=QI();near_=0;far_=0;update(){this.updateProjectionMatrix()}get projectionMatrix(){return this.projectionMatrix_}get viewMatrix(){return this.transform.inverse}get right(){const A=this.transform.matrix;return NA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return NA(A[4],A[5],A[6])}get frustum(){return new DC(DB(QI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=ZB(A[0],A[1],A[2],1),B=mB(QI(),this.projectionMatrix_),Q=aB(cg(),I,B);Di(Q,Q,1/Q[3]);const C=aB(cg(),Q,this.transform.matrix);return NA(C[0],C[1],C[2])}}const aC=1.77,sC=128,yC=128/aC;class pi extends oC{width_=sC;height_=yC;viewportAspectRatio_=aC;viewportSize_=[sC,yC];constructor(A,I,B,Q,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,Q,B),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,B,Q){this.width_=Math.abs(I-A),this.height_=Math.abs(Q-B),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(B+Q);this.transform.setTranslation([C,E,0]),this.transform.setScale([1,1,1]),this.transform.setRotation([0,0,0,1])}get type(){return"OrthographicCamera"}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=ZB(-1,-1,0,1),I=ZB(1,1,0,1);const B=DB(QI(),this.projectionMatrix,this.viewMatrix),Q=mB(QI(),B);return A=aB(cg(),A,Q),I=aB(cg(),I,Q),new jA(pA(A[0],A[1]),pA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,B=A/I;let Q=.5*A,C=.5*I;this.viewportAspectRatio_>B?Q*=this.viewportAspectRatio_/B:C*=B/this.viewportAspectRatio_,this.viewportSize_=[2*Q,2*C],_E(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const Wi=60,mi=1.77,sB=.1,vB=180-sB;class Ti extends oC{fov_;aspectRatio_;constructor(A={}){const{fov:I=Wi,aspectRatio:B=mi,near:Q=.1,far:C=1e4,position:E=NA(0,0,0)}=A;if(I<sB||I>vB)throw new Error(`Invalid field of view: ${I}, must be in [${sB}, ${vB}] degrees`);super(),this.fov_=I,this.aspectRatio_=B,this.near_=Q,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(sB,Math.min(vB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){jE(this.projectionMatrix_,PE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const hC=0;class xi{camera_;dragActive_=!1;dragStart_=rA();constructor(A){this.camera_=A}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const B=CI(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=xB(rA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==hC||(this.dragStart_=CI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=xB(rA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==hC||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class SI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&j.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=Lg(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&j.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=Lg(A,0,1)}onEvent(A){}async onAttached(A){}onDetached(){}get objects(){return this.objects_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(B=>B(A,I))}addObject(A){this.objects_.push(A)}removeObject(A){const I=this.objects_.indexOf(A);I!==-1&&this.objects_.splice(I,1)}clearObjects(){this.objects_=[]}}class yB extends $I{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"path_proportion",itemSize:1,offset:10*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*11);let B=0,Q=0;const C=A.reduce((E,i,o)=>E+vQ(i,A[o+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const o=A[E];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const h=A[E-1]??A[E];I[B++]=h[0],I[B++]=h[1],I[B++]=h[2];const s=A[E+1]??A[E];I[B++]=s[0],I[B++]=s[1],I[B++]=s[2],I[B++]=i,I[B++]=Q}Q+=vQ(A[E],A[E+1]??A[E])/C}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let B=0;for(let Q=0;Q<2*A;Q+=2)I[B++]=Q+0,I[B++]=Q+1,I[B++]=Q+2,I[B++]=Q+2,I[B++]=Q+1,I[B++]=Q+3;return I}}class jB extends Ag{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=hA.from(I),this.width_=B,this.taperOffset_=Q??this.taperOffset_,this.taperPower_=C??this.taperPower_,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=hA.from(A)}get width(){return this.width_}set width(A){this.width_=A}get taperOffset(){return this.taperOffset_}set taperOffset(A){this.taperOffset_=A}get taperPower(){return this.taperPower_}set taperPower(A){this.taperPower_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width,TaperOffset:this.taperOffset,TaperPower:this.taperPower}}}class Zi extends SI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(zB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(zB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(zB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function zB(g){const{end:A,width:I,color:B}=g,Q=new yB([[0,0,0],A]);return new jB({geometry:Q,color:B,width:I})}class bi extends SI{type="ProjectedLineLayer";paths_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){const{path:I,color:B,width:Q}=A;this.paths_.push(I);const C=new yB(I);this.addObject(new jB({geometry:C,color:B,width:Q}))}update(){}get extent(){return ui(this.paths_.flat())}}function ui(g){function A(o){const h=g.map(s=>s[o]);return[Math.min(...h),Math.max(...h)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}class Pi extends SI{type="TracksLayer";tracks_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){this.tracks_.push(A);let I;if(A.interpolation){const i=Vi({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new yB(i)}else I=new yB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new jB({geometry:I,color:B,width:Q,taperOffset:C,taperPower:E}))}setTimeIndex(A){for(const[I,B]of this.tracks_.entries()){if(!B.time)continue;let Q=.5;A<B.time[0]?Q=-1.5:A>B.time[B.time.length-1]&&(Q=1.5);const C=B.time.findIndex(i=>i===A);B.time&&C!==-1&&(Q=C/(B.time.length-1));const E=this.objects[I];E.taperOffset=Q}}update(){}get extent(){const A=this.tracks_.map(I=>I.path);return Oi(A.flat())}}function Oi(g){function A(o){const h=g.map(s=>s[o]);return[Math.min(...h),Math.max(...h)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}function Vi({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=Xi(g),Q=Array((g.length-1)*A);for(let C=0;C<g.length-1;C++){const E=g[C],i=g[C+1],o=CI(B[C]);XQ(o,E,o,I);const h=CI(B[C+1]);XQ(h,i,h,-I);for(let s=0;s<A;s++){const R=s/A,N=Q[C*A+s]=rA();Bi(N,E,o,h,i,R)}}return Q}function Xi(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=rA(),B=rA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=rA(),Q!==0&&tg(I,B),Q!==g.length-1&&xB(B,E,C),Q===0?tg(A[Q],B):Q==g.length-1?tg(A[Q],I):(OQ(A[Q],I,B),VQ(A[Q],A[Q],.5))}return A}class GC extends $I{constructor(A,I,B,Q){super();const C=[],E=[],i=B,o=Q,h=i+1,s=o+1,R=A/i,N=I/o;for(let r=0;r<s;++r){const M=r*N;for(let e=0;e<h;++e){const n=e*R,f=e/i,V=r/o,m=[n,M,0],b=[0,0,1],u=[f,V];C.push(...m,...b,...u)}}for(let r=0;r<o;++r)for(let M=0;M<i;++M){const e=M+h*r,n=M+h*(r+1),f=M+1+h*(r+1),V=M+1+h*r;E.push(e,n,V),E.push(n,f,V)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}function FC(g){return g===1||g===2||g===4||g===8}function Ig(g){if(g instanceof Int8Array)return"byte";if(g instanceof Int16Array)return"short";if(g instanceof Int32Array)return"int";if(g instanceof Uint8Array)return"unsigned_byte";if(g instanceof Uint16Array)return"unsigned_short";if(g instanceof Uint32Array)return"unsigned_int";if(g instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function vi(g){if(g.dataFormat==="rgb"||g.dataFormat==="rgba")return[0,1];switch(g.dataType){case"byte":return[-128,127];case"short":return[-32768,32767];case"int":return[-2147483648,2147483647];case"unsigned_byte":return[0,255];case"unsigned_short":return[0,65535];case"unsigned_int":return[0,4294967295];case"float":return[0,1]}}class _B extends WB{dataFormat="rgba";dataType="unsigned_byte";maxFilter="nearest";minFilter="nearest";mipmapLevels=1;unpackAlignment=4;wrapR="clamp_to_edge";wrapS="clamp_to_edge";wrapT="clamp_to_edge";needsUpdate=!0;get type(){return"Texture"}}const wC=32;function $B(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=hA.WHITE:I=hA.from(I),g!==null?B=ji(B,g):B===void 0&&(j.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function SC(g,A){if(A.length>wC)throw new Error(`Maximum number of channels is ${wC}`);if(g?.type==="Texture2DArray"){const I=g.depth;if(A.length!==I)throw new Error(`Number of channels (${A.length}) must match depth of texture (${I}).`)}return A.map(I=>$B(g,I))}function ji(g,A){if(g===void 0)return vi(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class AQ extends Ag{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new GC(A,I,1,1),this.setTexture(0,B),this.channels_=SC(B,Q),this.programName=zi(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=SC(this.textures[0],A)}setChannelProperty(A,I,B){const Q=$B(this.textures[0],{...this.channels_[A],[I]:B});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");if(A.type==="Texture2D"){const{color:I,contrastLimits:B}=this.channels_[0]??$B(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-B[0],ValueScale:1/(B[1]-B[0])}}else{const I=[],B=[],Q=[],C=[];return this.channels_.forEach(E=>{I.push(E.visible),B.push(...E.color.rgb),Q.push(-E.contrastLimits[0]),C.push(1/(E.contrastLimits[1]-E.contrastLimits[0]))}),{ImageSampler:0,"Visible[0]":I,"Color[0]":B,"ValueOffset[0]":Q,"ValueScale[0]":C}}}}function zi(g){if(g.type==="Texture2D")return _i(g.dataType);if(g.type==="Texture2DArray")return $i(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function _i(g){switch(g){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function $i(g){switch(g){case"byte":case"int":case"short":return"intScalarImageArray";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImageArray";case"float":return"floatScalarImageArray"}}class gg extends _B{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=A.length/(I*B)}get type(){return"Texture2DArray"}set data(A){this.data_=A,this.needsUpdate=!0}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===B)return;const Q=A.shape.x,C=A.shape.y,E=B.length/(Q*C);if(this.width!=Q||this.height!=C||this.depth_!=E||this.dataType!=Ig(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new gg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function IQ(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return pA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=pA(C.clientX,C.clientY);if(Gi(A,E)<Q){if(!B)return null;const o=g.worldPos;if(o){const h=I(o);h!==null&&B({world:o,value:h})}return null}return A}case"pointercancel":return null;default:return A}}class AD{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&j.debug("RenderablePool","Renderable object acquired"),B}release(A,I){let B=this.bins_.get(A);B||(B=[],this.bins_.set(A,B)),B.push(I),j.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class gQ extends SI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new AD;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkManagerSource_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new hA(.6,.3,.3),new hA(.3,.6,.4),new hA(.4,.4,.7),new hA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:B,channelProps:Q,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=B,this.sliceCoords_=I,this.channelProps_=Q,this.initialChannelProps_=Q,this.onPickValue_=C}async onAttached(A){if(this.chunkManagerSource_)throw new Error("ChunkedImageLayer is already attached. A layer cannot be attached to multiple LayerManagers simultaneously.");this.chunkManagerSource_=await A.chunkManager.addSource(this.source_,this.sliceCoords_,this.policy_)}onDetached(){this.chunkManagerSource_=void 0,this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects()}update(){this.updateChunks(),this.resliceIfZChanged()}updateChunks(){if(!this.chunkManagerSource_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkManagerSource_.allVisibleLowestLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkManagerSource_.getChunks(),I=new Set(A),B=Array.from(this.visibleChunks_.keys()).filter(Q=>!I.has(Q));this.releaseAndRemoveChunks(B),this.clearObjects();for(const Q of A){if(Q.state!=="loaded")continue;const C=this.getImageForChunk(Q);this.visibleChunks_.set(Q,C),this.addObject(C)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>gQ.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,B]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const Q=this.slicePlane(I,A);Q&&B.textures[0].updateWithChunk(I,Q)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=IQ(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get chunkManagerSource(){return this.chunkManagerSource_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkManagerSource_&&this.chunkManagerSource_.setImageSourcePolicy(A,QC))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=Lg(Q,0,A.shape.z-1);VB(B,C,1+1e-6)||j.error("ImageLayer","slicePlane zValue outside extent");const E=A.shape.x*A.shape.y,i=E*C;return A.data.slice(i,i+E)}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const B=this.pool_.acquire(RC(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(B,A),this.channelProps_&&B.setChannelProps(this.channelProps_),B):this.createImage(A)}createImage(A){const I=new AQ(A.shape.x,A.shape.y,gg.createWithChunk(A,this.getDataForImage(A)),this.channelProps_??[{}]);return this.updateImageChunk(I,A),I}getDataForImage(A){const I=this.sliceCoords_?.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data;if(!I){j.warn("ChunkedImageLayer","No data for image");return}return I}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1,A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}getValueAtWorld(A){const I=this.chunkManagerSource_?.currentLOD??0;for(const[B,Q]of this.visibleChunks_){if(B.lod!==I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}for(const[B,Q]of this.visibleChunks_){if(B.lod===I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}return null}getValueFromChunk(A,I,B){if(!A.data)return null;const Q=oB(rA(),B,I.transform.inverse),C=Math.floor(Q[0]),E=Math.floor(Q[1]);if(C>=0&&C<A.shape.x&&E>=0&&E<A.shape.y){const i=this.sliceCoords_.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data,o=E*A.shape.x+C;return i[o]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,B)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[B.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach(I=>{I.setChannelProps(A)}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(RC(I),B),this.visibleChunks_.delete(I))}}}function RC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class hB extends _B{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=Ig(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=Q}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture3D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==I){if(this.width!=A.shape.x||this.height!=A.shape.y||this.depth!=A.shape.z||this.dataType!=Ig(I))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=I}}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new hB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class ID extends $I{constructor(A,I,B,Q,C,E){super();const i=[],o=[],h=Math.floor(Q),s=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,R,s,1,i,o),this.buildFace("z","y","x",1,-1,B,I,A,R,s,-1,i,o),this.buildFace("x","z","y",1,1,A,B,I,h,R,1,i,o),this.buildFace("x","z","y",1,-1,A,B,I,h,R,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,B,h,s,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,B,h,s,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,B,Q,C,E,i,o,h,s,R,N,r){const M=E/h,e=i/s,n=E/2,f=i/2,V=o/2*R,m=h+1,b=s+1,u=N.length/8;for(let W=0;W<b;W++){const gA=-f+W*e;for(let O=0;O<m;O++){const x=-n+O*M,$={x:0,y:0,z:0};$[A]=x*Q,$[I]=gA*C,$[B]=V;const IA={x:0,y:0,z:0};IA[B]=R;const wA=O/h,kA=1-W/s;N.push($.x,$.y,$.z,IA.x,IA.y,IA.z,wA,kA)}}for(let W=0;W<s;W++)for(let gA=0;gA<h;gA++){const O=u+gA+m*W,x=u+gA+m*(W+1),$=u+(gA+1)+m*(W+1),IA=u+(gA+1)+m*W;R===1?r.push(O,x,IA,x,$,IA):r.push(O,IA,x,x,IA,$)}}}class gD extends Ag{constructor(A,I,B,Q){super(),this.geometry=new ID(A,I,B,1,1,1),this.cullFaceMode="back",this.setTexture(0,Q),this.programName=BD(Q.dataType)}get type(){return"VolumeRenderable"}}function BD(g){switch(g){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}class QD extends SI{type="VolumeLayer";constructor(){super();const A=new Int8Array([127,0,0,127,127,0,0,127]),I=new hB(A,2,2,2);I.unpackAlignment=1;const B=new gD(1,1,1,I);B.wireframeEnabled=!0,this.addObject(B),this.setState("ready")}update(){}}class CD extends SI{type="ImageLayer";source_;region_;lod_;onPickValue_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;image_;chunk_;extent_;pointerDownPos_=null;constructor({source:A,region:I,channelProps:B,onPickValue:Q,lod:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.region_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=Q,this.lod_=C}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}onEvent(A){this.pointerDownPos_=IQ(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=I.getAttributes(),Q=this.lod_??B.length-1,C=await I.loadRegion(A,Q);this.extent_={x:C.shape.x*C.scale.x,y:C.shape.y*C.scale.y},this.image_=this.createImage(C),this.chunk_=C,this.addObject(this.image_),this.setState("ready")}get extent(){return this.extent_}createImage(A){const I=new AQ(A.shape.x,A.shape.y,gg.createWithChunk(A),this.channelProps);return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.chunk_?.data)return null;const I=oB(rA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B>=0&&B<this.chunk_.shape.x&&Q>=0&&Q<this.chunk_.shape.y){const C=Q*this.chunk_.shape.x+B;return this.chunk_.data[C]}return null}}class rg extends _B{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(A),this.data_=A,this.width_=I,this.height_=B}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture2D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==B){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=Ig(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new rg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const ED=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function iD(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,hA.from(I)]))}function DD(g){return g=g??ED,g.map(hA.from)}class NC{lookupTable;cycle;constructor(A={}){this.lookupTable=iD(A.lookupTable),this.cycle=DD(A.cycle)}}const oD=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function aD(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!oD.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class sD extends Ag{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new GC(A.width,A.height,1,1),this.setTexture(0,aD(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const B=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,B),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{ImageSampler:0,ColorCycleSampler:1,ColorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new rg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,hA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,hA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new rg(C,Q,2)}}class yD extends SI{type="LabelImageLayer";source_;region_;lod_;colorMap_;onPickValue_;outlineSelected_;image_;imageChunk_;pointerDownPos_=null;selectedValue_=null;constructor({source:A,region:I,colorMap:B={},onPickValue:Q,lod:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.region_=I,this.colorMap_=new NC(B),this.onPickValue_=Q,this.lod_=C,this.outlineSelected_=E}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new NC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=IQ(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=I.getAttributes(),Q=this.lod_??B.length-1,C=await I.loadRegion(A,Q);this.image_=this.createImage(C),this.addObject(this.image_),this.setState("ready")}createImage(A){this.imageChunk_=A;const I=new sD({width:A.shape.x,height:A.shape.y,imageData:rg.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.imageChunk_?.data)return null;const I=oB(rA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B<0||B>=this.imageChunk_.shape.x||Q<0||Q>=this.imageChunk_.shape.y)return null;const C=Q*this.imageChunk_.shape.x+B;return this.imageChunk_.data[C]}}class GB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,GB.prototype)}}class hD{maxConcurrent_;pending_=[];abortController_=new AbortController;numRunning_=0;constructor(A){if(A<=0)throw Error(`maxConcurrent (${A}) must be positive`);this.maxConcurrent_=A}async submit(A){return this.abortController_.signal.throwIfAborted(),new Promise((I,B)=>{const Q=async()=>{try{this.abortController_.signal.throwIfAborted();const C=await A();I(C)}catch(C){B(C)}finally{this.numRunning_--,this.maybeRunNext()}};this.pending_.push(Q),this.maybeRunNext()})}maybeRunNext(){if(this.numRunning_>=this.maxConcurrent_)return;const A=this.pending_.shift();A!==void 0&&(this.numRunning_++,A())}get abortSignal(){return this.abortController_.signal}shutdown(){this.abortController_.abort(new GB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class GD{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new hD(16);lod_;loader_=null;seriesAttributes_;loadingToken_=null;dataChunks_=[];constructor(A){this.source_=A.source,this.region_=A.region,this.lod_=A.lod,this.seriesDimensionName_=A.seriesDimensionName;const I=A.region.find(B=>B.dimension==A.seriesDimensionName);if(I===void 0)throw new Error(`Series dimension '${A.seriesDimensionName}' not in region ${JSON.stringify(A.region)}`);if(I.index.type==="point")throw new Error("Series dimension index in region must be an interval or 'full', not a point value");this.seriesIndex_=I.index}async setPosition(A){const I=await this.loadSeriesAttributes(),B=Math.round((A-I.start)/I.scale);return await this.setIndex(B)}async setIndex(A){const I=this.loadingToken_;if(I){if(I.index===A&&!I.canceled)return j.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};j.debug("ImageSeriesLoader",`Cancelling setIndex request for index ${I.index}, new requested index is ${A}`),I.canceled=!0}let B=this.dataChunks_[A];if(B===void 0){const Q={canceled:!1,index:A};if(this.loadingToken_=Q,B=await this.loadChunkAtIndex(A,Q),Q.canceled)return{success:!1,reason:"canceled"}}return{success:!0,chunk:B}}shutdown(){this.scheduler_.shutdown()}async loadSeriesAttributes(){if(this.seriesAttributes_)return this.seriesAttributes_;const I=(await this.getLoader()).getAttributes(),B=I[this.lod_??I.length-1],Q=B.dimensionNames.findIndex(R=>R===this.seriesDimensionName_);if(Q===-1)throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${B.dimensionNames}`);const C=B.scale[Q],E=B.shape[Q]*C,i=this.seriesIndex_.type==="full",o=i?0:this.seriesIndex_.start,h=i?E:this.seriesIndex_.stop,s=Math.round((h-o)/C);return this.dataChunks_=new Array(s),this.seriesAttributes_={start:o,stop:h,scale:C,length:s},this.seriesAttributes_}async loadChunkAtIndex(A,I){const B=await this.loadSeriesAttributes();if(A<0||A>=B.length)throw new Error(`Requested index ${A} is out of bounds [0, ${B.length-1}]`);const Q=B.start+A*B.scale,C=this.region_.filter(s=>s.dimension!==this.seriesDimensionName_);C.push({dimension:this.seriesDimensionName_,index:{type:"point",value:Q}});const E=await this.getLoader(),i=E.getAttributes(),o=this.lod_??i.length-1,h=await E.loadRegion(C,o,this.scheduler_);return this.dataChunks_[A]=h,I&&I.canceled&&(this.loadingToken_=null),h}async preloadAllChunks(){const{length:A}=await this.loadSeriesAttributes(),I=[];for(let Q=0;Q<A;Q++)I.push(this.loadChunkAtIndex(Q));const B=await Promise.allSettled(I);for(const Q of B)if(Q.status==="rejected"){if(Q.reason instanceof GB)return Promise.reject(Q.reason);j.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class FD extends SI{type="ImageSeriesLayer";seriesLoader_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;texture_=null;image_;extent_;constructor({source:A,region:I,seriesDimensionName:B,channelProps:Q,lod:C,...E}){super(E),this.setState("initialized"),this.channelProps_=Q,this.initialChannelProps_=Q,this.seriesLoader_=new GD({source:A,region:I,seriesDimensionName:B,lod:C})}update(){this.state==="initialized"&&(this.setState("loading"),this.seriesLoader_.loadSeriesAttributes())}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async setPosition(A){const I=await this.seriesLoader_.setPosition(A);return this.processIndexResult(I)}async setIndex(A){const I=await this.seriesLoader_.setIndex(A);return this.processIndexResult(I)}close(){this.seriesLoader_.shutdown()}async preloadSeries(){return this.seriesLoader_.preloadAllChunks()}get extent(){return this.extent_}processIndexResult(A){return A.chunk&&(this.setData(A.chunk),this.setState("ready")),A}setData(A){!this.texture_||!this.image_?(this.texture_=gg.createWithChunk(A),this.image_=this.createImage(A,this.texture_,this.channelProps_),this.addObject(this.image_),this.extent_={x:A.shape.x*A.scale.x,y:A.shape.y*A.scale.y}):A.data&&this.texture_.updateWithChunk(A)}createImage(A,I,B){const Q=new AQ(A.shape.x,A.shape.y,I,B);return Q.transform.setScale([A.scale.x,A.scale.y,1]),Q.transform.setTranslation([A.offset.x,A.offset.y,0]),Q}}class Yg extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class BQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}class QQ{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new Error("keepbits must be zero or positive")}static fromConfig(A,I){return new QQ(A,I)}encode(A){throw new Error("`BitroundCodec.encode` is not implemented. Please open an issue at https://github.com/manzt/zarrita.js/issues.")}decode(A){return A}}class UC{#A;constructor(A,I,B){typeof A=="number"?this.#A=new Uint8Array(A):A instanceof ArrayBuffer?this.#A=new Uint8Array(A,I,B):this.#A=new Uint8Array(Array.from(A,Q=>Q?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#A.byteOffset}get byteLength(){return this.#A.byteLength}get buffer(){return this.#A.buffer}get length(){return this.#A.length}get(A){let I=this.#A[A];return typeof I=="number"?I!==0:I}set(A,I){this.#A[A]=I?1:0}fill(A){this.#A.fill(A?1:0)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class CQ{_data;chars;#A;constructor(A,I,B,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q=Q*A),this._data=new Uint8Array(I,B,Q);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const B=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);B.fill(0),B.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let B=0;B<this.length;B++)this._data.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class ng{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new ng(A,1);this.#A=new Int32Array(function*(){for(let i of C)E.set(0,i),yield*E.#A}())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let B="";for(let Q=0;Q<this.chars;Q++)B+=String.fromCodePoint(this.#A[I+Q]);return B.replace(/\u0000/g,"")}set(A,I){const B=this.chars*A,Q=this.#A.subarray(B,B+this.chars);Q.fill(0);for(let C=0;C<this.chars;C++)Q[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let B=1;B<this.length;B++)this.#A.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function Kg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function kC(g,A){const I=A/2,B=A-1;let Q=0;for(let C=0;C<g.length;C+=A)for(let E=0;E<I;E+=1)Q=g[C+E],g[C+E]=g[C+B-E],g[C+B-E]=Q}const wD={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float32:Float32Array,float64:Float64Array,bool:UC},SD=/v2:([US])(\d+)/;function tC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(SD);if(A){let[,B,Q]=A;return(B==="U"?ng:CQ).bind(null,Number(Q))}let I=wD[g];if(!I)throw new Error(`Unknown or unsupported data_type: ${g}`);return I}function pI(g,A){return(A==="C"?RD:ND)(g)}function RD(g){const A=g.length,I=globalThis.Array(A);for(let B=A-1,Q=1;B>=0;B--)I[B]=Q,Q*=g[B];return I}function ND(g){const A=g.length,I=globalThis.Array(A);for(let B=0,Q=1;B<A;B++)I[B]=Q,Q*=g[B];return I}function UD({name:g,configuration:A}){if(g==="default"){const I=A?.separator??"/";return B=>["c",...B].join(I)}if(g==="v2"){const I=A?.separator??".";return B=>B.join(I)||"0"}throw new Error(`Unknown chunk key encoding: ${g}`)}function EQ(g){return g.find(I=>I.name==="transpose")?.configuration?.order==="F"?"F":"C"}const kD=/^([<|>])(.*)$/;function tD(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(kD);if(!A)throw new Error(`Invalid dtype: ${g}`);let[,I,B]=A,Q={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f4:"float32",f8:"float64"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);if(!Q)throw new Error(`Unsupported or unknown dtype: ${g}`);return I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function cD(g,A={}){let I=[],B=tD(g.dtype);g.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}}),"endian"in B&&B.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}});for(let{id:Q,...C}of g.filters??[])I.push({name:Q,configuration:C});if(g.compressor){let{id:Q,...C}=g.compressor;I.push({name:Q,configuration:C})}return{zarr_format:3,node_type:"array",shape:g.shape,data_type:B.data_type,chunk_grid:{name:"regular",configuration:{chunk_shape:g.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:g.dimension_separator??"."}},codecs:I,fill_value:g.fill_value,attributes:A}}function LD(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function JD(g,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return g===A;let I=g==="bool";if(A==="boolean")return I;let B=g.startsWith("v2:U")||g.startsWith("v2:S");if(A==="string")return B;let Q=g==="int64"||g==="uint64";if(A==="bigint")return Q;let C=g==="v2:object";return A==="object"?C:!B&&!Q&&!I&&!C}function rD(g){return g?.name==="sharding_indexed"}function cC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}const LC=YD();function YD(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function JC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class FB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=tC(I.data_type),this.#Q=I.shape,this.#A=pI(I.shape,EQ(I.codecs));const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new FB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return LC&&this.#B==="big"&&kC(I,JC(this.#I)),I}decode(A){return LC&&this.#B==="big"&&kC(A,JC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class iQ{kind="bytes_to_bytes";static fromConfig(){return new iQ}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}function nD(g,A){if(Number.isNaN(A))throw new Error("JsonCodec allow_nan is false but NaN was encountered during encoding.");if(A===Number.POSITIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but Infinity was encountered during encoding.");if(A===Number.NEGATIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but -Infinity was encountered during encoding.");return A}function KD(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class DQ{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:B=!1,ensure_ascii:Q=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:h=!0}=A;let s=A.separators;s||(o?s=[", ",": "]:s=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:o,separators:s,sort_keys:i},this.#I={strict:h}}static fromConfig(A){return new DQ(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;if(B!=="utf-8")throw new Error("JsonCodec does not yet support non-utf-8 encoding.");const o=[];if(!C)throw new Error("JsonCodec does not yet support skipping the check for circular references during encoding.");E||o.push(nD),i&&o.push(KD);const h=Array.from(A.data);h.push("|O"),h.push(A.shape);let s;o.length&&(s=(N,r)=>{let M=r;for(let e of o)M=e(N,M);return M});let R=JSON.stringify(h,s,I);return Q&&(R=R.replace(/[\u007F-\uFFFF]/g,N=>{const r=`0000${N.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(R)}decode(A){const{strict:I}=this.#I;if(!I)throw new Error("JsonCodec does not yet support non-strict decoding.");const B=Kg(A),Q=B.pop();if(B.pop(),!Q)throw new Error("0D not implemented for JsonCodec.");const C=pI(Q,"C");return{data:B,shape:Q,stride:C}}}function rC(g){return g instanceof UC||g instanceof CQ||g instanceof ng?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function MD(g,A){let I;return g.data instanceof CQ||g.data instanceof ng?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:pI(g.shape,A)}}function HD(g,A){let I=MD(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=rC(g.data),i=rC(I.data);for(let o=0;o<Q;o++){let h=0;for(let s=0;s<B;s++)h+=C[s]*I.stride[s];i[h]=E[o],C[0]+=1;for(let s=0;s<B;s++)if(C[s]===g.shape[s]){if(s+1===B)break;C[s]=0,C[s+1]+=1}}return I}function eD(g){if(!g.stride)return"C";let A=pI(g.shape,"C");return g.stride.every((I,B)=>I===A[B])?"C":"F"}class oQ{configuration;kind="array_to_array";constructor(A){this.configuration=A}static fromConfig(A){return new oQ(A)}encode(A){return eD(A)===this.configuration?.order?A:HD(A,this.configuration?.order??"C")}decode(A){return A}}class aQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=pI(A,"C")}static fromConfig(A,I){return new aQ(I.shape)}encode(A){throw new Error("Method not implemented.")}decode(A){let I=new TextDecoder,B=new DataView(A.buffer),Q=Array(B.getUint32(0,!0)),C=4;for(let E=0;E<Q.length;E++){let i=B.getUint32(C,!0);C+=4,Q[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:Q,shape:this.#A,stride:this.#I}}}function qD(){return new Map().set("blosc",()=>Promise.resolve().then(()=>os).then(g=>g.default)).set("gzip",()=>Promise.resolve().then(()=>ds).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>Ts).then(g=>g.default)).set("zlib",()=>Promise.resolve().then(()=>bs).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>vs).then(g=>g.default)).set("transpose",()=>oQ).set("bytes",()=>FB).set("crc32c",()=>iQ).set("vlen-utf8",()=>aQ).set("json2",()=>DQ).set("bitround",()=>QQ)}const dD=qD();function sQ(g){let A;return{async encode(I){A||(A=await YC(g));for(const Q of A.array_to_array)I=await Q.encode(I);let B=await A.array_to_bytes.encode(I);for(const Q of A.bytes_to_bytes)B=await Q.encode(B);return B},async decode(I){A||(A=await YC(g));for(let Q=A.bytes_to_bytes.length-1;Q>=0;Q--)I=await A.bytes_to_bytes[Q].decode(I);let B=await A.array_to_bytes.decode(I);for(let Q=A.array_to_array.length-1;Q>=0;Q--)B=await A.array_to_array[Q].decode(B);return B}}}async function YC(g){let A=g.codecs.map(async C=>{let E=await dD.get(C.name)?.();if(!E)throw new Error(`Unknown codec: ${C.name}`);return{Codec:E,meta:C}}),I=[],B,Q=[];for await(let{Codec:C,meta:E}of A){let i=C.fromConfig(E.configuration,g);switch(i.kind){case"array_to_array":I.push(i);break;case"array_to_bytes":B=i;break;default:Q.push(i)}}if(!B){if(!fD(g))throw new Error(`Cannot encode ${g.data_type} to bytes without a codec`);B=FB.fromConfig({endian:"little"},g)}return{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function fD(g){return g.data_type!=="v2:object"}const nC=18446744073709551615n;function lD(g,A,I,B){if(g.store.getRange===void 0)throw new Error("Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((o,h)=>o/B.chunk_shape[h]),E=sQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async o=>{let h=o.map((V,m)=>Math.floor(V/C[m])),s=g.resolve(I(h)).path,R;if(s in i)R=i[s];else{let V=4,m=16*C.reduce((u,W)=>u*W,1),b=await Q(s,{suffixLength:m+V});R=i[s]=b?await E.decode(b):null}if(R===null)return;let{data:N,shape:r,stride:M}=R,e=o.map((V,m)=>V%r[m]).reduce((V,m,b)=>V+m*M[b],0),n=N[e],f=N[e+1];if(!(n===nC&&f===nC))return Q(s,{offset:Number(n),length:Number(f)})}}class II{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new II(this.store,new URL(A,I).pathname)}}class yQ extends II{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}const Mg=Symbol("zarrita.context");function pD(g){return g[Mg]}function WD(g,A){let{configuration:I}=A.codecs.find(rD)??{},B={encode_chunk_key:UD(A.chunk_key_encoding),TypedArray:tC(A.data_type),fill_value:A.fill_value};if(I){let C=EQ(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:sQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E,i){return pI(E,i??C)},get_chunk_bytes:lD(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=EQ(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:sQ({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C,E){return pI(C,E??Q)},async get_chunk_bytes(C,E){let i=B.encode_chunk_key(C),o=g.resolve(i).path;return g.store.get(o,E)}}}let wB=class extends II{kind="array";#A;[Mg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:cC(B)},this[Mg]=WD(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[Mg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[Mg],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,o)=>i*o,1),E=new B.TypedArray(C);return E.fill(B.fill_value),{data:E,shape:B.chunk_shape,stride:B.get_strides(B.chunk_shape)}}return B.codec.decode(Q)}is(A){return JD(this.dtype,A)}},SB=mD();function mD(){let g=new WeakMap;function A(I){let B=g.get(I)??{v2:0,v3:0};return g.set(I,B),B}return{increment(I,B){A(I)[B]+=1},version_max(I){let B=A(I);return B.v3>B.v2?"v3":"v2"}}}async function TD(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Kg(A):{}}async function xD(g,A={}){let I="store"in g?g:new II(g),B={};return(A.attrs??!0)&&(B=await TD(I)),A.kind==="array"?KC(I,B):A.kind==="group"?MC(I,B):KC(I,B).catch(Q=>{if(Q instanceof Yg)return MC(I,B);throw Q})}async function KC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new Yg("v2 array",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new wB(g.store,g.path,cD(Kg(B),A))}async function MC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new Yg("v2 group",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new yQ(g.store,g.path,LD(Kg(B),A))}async function ZD(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new Yg("v3 array or group",{cause:new BQ(I)});let Q=Kg(B);return Q.node_type==="array"&&(Q.fill_value=cC(Q)),Q.node_type==="array"?new wB(A,g.path,Q):new yQ(A,g.path,Q)}async function bD(g,A={}){let I="store"in g?g:new II(g),B=await ZD(I);if(SB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof wB||A.kind==="group"&&B instanceof yQ)return B;let Q=B instanceof wB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function gI(g,A={}){let I="store"in g?g.store:g,B=SB.version_max(I),Q=B==="v2"?gI.v2:gI.v3,C=B==="v2"?gI.v3:gI.v2;return Q(g,A).catch(E=>{if(E instanceof Yg)return C(g,A);throw E})}gI.v2=xD,gI.v3=bD;function HC(g,A,I,B={}){return A!==void 0&&I!==void 0&&(B={...B,headers:{...B.headers,Range:`bytes=${A}-${A+I-1}`}}),fetch(g,B)}function uD(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function eC(g,A){const I=typeof g=="string"?new URL(g):g;I.pathname.endsWith("/")||(I.pathname+="/");const B=new URL(A.slice(1),I);return B.search=I.search,B}async function qC(g){if(g.status!==404){if(g.status===200||g.status===206)return new Uint8Array(await g.arrayBuffer());throw new Error(`Unexpected response status ${g.status} ${g.statusText}`)}}async function PD(g,A,I,B){if(B)return fetch(g,{...I,headers:{...I.headers,Range:`bytes=-${A}`}});let Q=await fetch(g,{...I,method:"HEAD"});if(!Q.ok)return Q;let C=Q.headers.get("Content-Length"),E=Number(C);return HC(g,E-A,E,I)}class Hg{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return uD(this.#A,A)}async get(A,I={}){let B=eC(this.url,A).href,Q=await fetch(B,this.#g(I));return qC(Q)}async getRange(A,I,B={}){let Q=eC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await PD(Q,I.suffixLength,C,this.#I):E=await HC(Q,I.offset,I.length,C),qC(E)}}function*OD(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*VD(...g){if(g.length===0)return;const A=g.map(B=>B[Symbol.iterator]()),I=A.map(B=>B.next());if(I.some(B=>B.done))throw new Error("Input contains an empty iterator.");for(let B=0;;){if(I[B].done){if(A[B]=g[B][Symbol.iterator](),I[B]=A[B].next(),++B>=A.length)return}else yield I.map(({value:Q})=>Q),B=0;I[B]=A[B].next()}}function XD({start:g,stop:A,step:I},B){if(I===0)throw new Error("slice step cannot be zero");I=I??1;const Q=I<0,[C,E]=Q?[-1,B-1]:[0,B];return g===null?g=Q?E:C:g<0?(g+=B,g<C&&(g=C)):g>E&&(g=E),A===null?A=Q?C:E:A<0?(A+=B,A<C&&(A=C)):A>E&&(A=E),[g,A,I]}function RB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function vD(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class hQ extends Error{constructor(A){super(A),this.name="IndexError"}}function jD(g,A){throw new hQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function zD(g){throw new hQ(`index out of bounds for dimension with length ${g}`)}function _D(){throw new hQ("only slices with step >= 1 are supported")}function $D(g,A){g.length>A.length&&jD(g,A)}function Ao(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&zD(A),g}class Io{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=Ao(A,I),this.dim_sel=A,this.dim_len=I,this.dim_chunk_len=B,this.nitems=1}*[Symbol.iterator](){const A=Math.floor(this.dim_sel/this.dim_chunk_len),I=A*this.dim_chunk_len,B=this.dim_sel-I;yield{dim_chunk_ix:A,dim_chunk_sel:B}}}class dC{start;stop;step;dim_len;dim_chunk_len;nitems;nchunks;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){const[Q,C,E]=XD(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&_D(),this.dim_len=I,this.dim_chunk_len=B,this.nitems=Math.max(0,Math.ceil((this.stop-this.start)/this.step)),this.nchunks=Math.ceil(this.dim_len/this.dim_chunk_len)}*[Symbol.iterator](){const A=Math.floor(this.start/this.dim_chunk_len),I=Math.ceil(this.stop/this.dim_chunk_len);for(const B of OD(A,I)){const Q=B*this.dim_chunk_len,C=Math.min(this.dim_len,(B+1)*this.dim_chunk_len),E=C-Q;let i=0,o=0;if(this.start<Q){const r=(Q-this.start)%this.step;r&&(o+=this.step-r),i=Math.ceil((Q-this.start)/this.step)}else o=this.start-Q;const h=this.stop>C?E:this.stop-Q,s=[o,h,this.step],R=Math.ceil((h-o)/this.step),N=[i,i+R,1];yield{dim_chunk_ix:B,dim_chunk_sel:s,dim_out_sel:N}}}}function go(g,A){let I=[];return g===null?I=A.map(B=>RB(null)):Array.isArray(g)&&(I=g.map(B=>B??RB(null))),$D(I,A),I}class Bo{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=go(A,I).map((Q,C)=>new(typeof Q=="number"?Io:dC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof dC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of VD(...this.dim_indexers)){const I=A.map(Q=>Q.dim_chunk_ix),B=A.map(Q=>"dim_out_sel"in Q?{from:Q.dim_chunk_sel,to:Q.dim_out_sel}:{from:Q.dim_chunk_sel,to:null});yield{chunk_coords:I,mapping:B}}}}function Qo(g,A){return"get"in g?g.get(A):g[A]}async function Co(g,A,I,B){let Q=pD(g),C=new Bo({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((o,h)=>o*h,1)),C.shape,Q.get_strides(C.shape,I.order)),i=I.create_queue?.()??vD();for(const{chunk_coords:o,mapping:h}of C)i.add(async()=>{let{data:s,shape:R,stride:N}=await g.getChunk(o,I.opts),r=B.prepare(s,R,N);B.set_from_chunk(E,r,h)});return await i.onIdle(),C.shape.length===0?Qo(E.data,0):E}function GQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return GQ(g,A+Q,C-Q)},set(Q,C=0){for(let E=0;E<Q.length;E++)g[A+C+E]=Q.get(E)},get(Q){return g[A+Q]}}}function FQ(g){return globalThis.Array.isArray(g.data)?{data:GQ(g.data),stride:g.stride,bytes_per_element:1}:{data:new Uint8Array(g.data.buffer,g.data.byteOffset,g.data.byteLength),stride:g.stride,bytes_per_element:g.data.BYTES_PER_ELEMENT}}function Eo(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function io(g,A){if(globalThis.Array.isArray(g.data))return GQ([A]);let I=Eo(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const Do={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=FQ(g);wQ(B,A,io(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=FQ(g);NB(B,FQ(A),B.bytes_per_element,I)}};async function oo(g,A=null,I={}){return Co(g,A,I,Do)}function fC(g,A,I){return I<0&&A<g?Math.floor((g-A-1)/-I)+1:g<A?Math.floor((A-g-1)/I)+1:0}function wQ(g,A,I,B){if(A.length===0){g.data.set(I,0);return}const[Q,...C]=A,[E,...i]=g.stride;if(typeof Q=="number"){const N=g.data.subarray(E*Q*B);wQ({data:N,stride:i},C,I,B);return}const[o,h,s]=Q,R=fC(o,h,s);if(C.length===0){for(let N=0;N<R;N++)g.data.set(I,E*(o+s*N)*B);return}for(let N=0;N<R;N++){const r=g.data.subarray(E*(o+s*N)*B);wQ({data:r,stride:i},C,I,B)}}function NB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[o,...h]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}NB({data:g.data.subarray(E*Q.to*I),stride:i},A,I,C);return}if(Q.to===null){if(C.length===0){let f=Q.from*I;g.data.set(A.data.subarray(f,f+I),0);return}NB(g,{data:A.data.subarray(o*Q.from*I),stride:h},I,C);return}const[s,R,N]=Q.to,[r,M,e]=Q.from,n=fC(s,R,N);if(C.length===0){if(N===1&&e===1&&E===1&&o===1){let f=r*I,V=n*I;g.data.set(A.data.subarray(f,f+V),s*I);return}for(let f=0;f<n;f++){let V=o*(r+e*f)*I;g.data.set(A.data.subarray(V,V+I),E*(s+N*f)*I)}return}for(let f=0;f<n;f++)NB({data:g.data.subarray(E*(s+f*N)*I),stride:i},{data:A.data.subarray(o*(r+f*e)*I),stride:h},I,C)}async function ao(g,A){const I=A.split("/"),B=I.pop();if(!B)throw new Error("Invalid path");for(const Q of I)g=await g.getDirectoryHandle(Q);return g.getFileHandle(B)}class SQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await ao(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}async function eg(g,A){if(A==="v2")try{return gI.v2(g,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${g}`)}if(A==="v3")try{return gI.v3(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${g}`)}try{return gI(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${g}`)}}async function so(g,A){if(A==="v2")try{return gI.v2(g,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${g}`)}if(A==="v3")try{return gI.v3(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${g}`)}try{return gI(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${g}`)}}async function yo(g){let A;switch(g.type){case"fetch":{A=new II(new Hg(g.url,g.fetchOptions));break}case"filesystem":{A=new II(new SQ(g.directoryHandle),g.path);break}default:{const B=g;throw new Error(`Unsupported store type: ${B}`)}}const I=g.arrayPath?A.resolve(g.arrayPath):A;return so(I,g.zarrVersion)}function ho(g,A,I){if(g.store instanceof Hg)return{type:"fetch",arrayPath:A,zarrVersion:I,url:g.store.url.toString()};if(g.store instanceof SQ)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:g.store.directoryHandle,path:g.path};throw new Error(`Unsupported store type: ${g.store.constructor.name}`)}const lC=`class HI extends Error {
347
347
  constructor(A, I = {}) {
348
348
  super(\`Node not found: \${A}\`, I), this.name = "NodeNotFoundError";
349
349
  }
@@ -3890,7 +3890,7 @@ return ret;
3890
3890
  `,pC=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",lC],{type:"text/javascript;charset=utf-8"});function Go(g){let A;try{if(A=pC&&(self.URL||self.webkitURL).createObjectURL(pC),!A)throw"";const I=new Worker(A,{type:"module",name:g?.name});return I.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(A)}),I}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(lC),{type:"module",name:g?.name})}}const Fo=Math.min(navigator.hardwareConcurrency,8);let EI=[],wo=0,WC=0;const WI=new Map,UB=new Set;function mC(g){const A=EI.find(I=>I.worker===g);return A||j.error("ZarrWorker","Worker not found in pool - this should not happen"),A}function So(g,A){const{id:I,success:B}=g.data,Q=WI.get(I);if(!Q){UB.has(I)?UB.delete(I):j.warn("ZarrWorker",`Received response for unknown message ID ${I}:`,g.data);return}WI.delete(I),Q.abortListener&&Q.abortSignal&&Q.abortSignal.removeEventListener("abort",Q.abortListener);const C=mC(A);C&&C.pendingCount>0?C.pendingCount--:C&&j.error("ZarrWorker","Received message but no pending tasks - this should not happen"),B&&g.data.type==="getChunk"?Q.resolve(g.data.chunk):B||Q.reject(new Error(g.data.error||"Unknown worker error"))}function TC(g,A){if(g instanceof MessageEvent){j.error("ZarrWorker","Message serialization error occurred - worker remains active");return}j.error("ZarrWorker","Worker failed - replacing worker and canceling its in-flight messages",g.message);const I=mC(A);if(I){const Q=EI.indexOf(I);EI.splice(Q,1)}const B=I?.workerId;if(B!==void 0)for(const[Q,C]of WI.entries())C.workerId===B&&(C.reject(new Error(`Worker error: ${g.message}`)),WI.delete(Q));try{const Q=xC();EI.push({worker:Q,pendingCount:0,workerId:WC++}),j.debug("ZarrWorker","Replacement worker created successfully")}catch(Q){j.error("ZarrWorker","Failed to create replacement worker",Q)}}function xC(){const g=new Go;return g.addEventListener("message",A=>So(A,g)),g.addEventListener("error",A=>TC(A,g)),g.addEventListener("messageerror",A=>TC(A,g)),g}function Ro(){if(EI.length===0)throw new Error("Worker pool is not initialized");return EI.sort((g,A)=>g.pendingCount-A.pendingCount)[0]}async function No(g,A,I){return new Promise((B,Q)=>{const C=Ro(),E=wo++,i={resolve:B,reject:Q,workerId:C.workerId};if(WI.set(E,i),I?.signal){const o=()=>{C.worker.postMessage({id:E,type:"cancel"}),WI.delete(E),UB.add(E),C.pendingCount--,Q(new DOMException("Operation was aborted","AbortError"))};if(I.signal.aborted){o(),UB.delete(E);return}I.signal.addEventListener("abort",o,{once:!0}),i.abortListener=o,i.abortSignal=I.signal}C.pendingCount++,C.worker.postMessage({id:E,type:"getChunk",arrayParams:g,index:A})})}function Uo(){if(!(EI.length>0))try{for(let g=0;g<Fo;g++){const A=xC();EI.push({worker:A,pendingCount:0,workerId:WC++})}j.debug("ZarrWorker",`Initialized worker pool with ${EI.length} workers`)}catch{j.warn("ZarrWorker","Failed to create workers - clearing pool"),to();return}}async function ko(g,A,I,B){Uo();try{return await No(A,I,B)}catch(Q){if(Q instanceof DOMException&&Q.name==="AbortError")throw Q;return j.warn("ZarrWorker","Falling back to main thread",Q),await g.getChunk(I,B)}}function to(){for(const g of EI)g.worker.terminate();EI=[],WI.clear()}class co{promises_=[];scheduler_;constructor(A){this.scheduler_=A}add(A){this.promises_.push(A)}onIdle(){return Promise.all(this.promises_.map(A=>this.scheduler_.submit(A)))}}class Lo{metadata_;arrays_;arrayParams_;loaderAttributes_;dimensions_;constructor(A){this.metadata_=A.metadata,this.arrays_=A.arrays,this.arrayParams_=A.arrayParams,this.loaderAttributes_=Jo(this.metadata_,this.arrays_),this.dimensions_=ro(this.loaderAttributes_)}getSourceDimensionMap(){return this.dimensions_}async loadChunkData(A,I){const B=[];B[this.dimensions_.x.index]=A.chunkIndex.x,B[this.dimensions_.y.index]=A.chunkIndex.y,this.dimensions_.z&&(B[this.dimensions_.z.index]=A.chunkIndex.z),this.dimensions_.c&&(B[this.dimensions_.c.index]=A.chunkIndex.c),this.dimensions_.t&&(B[this.dimensions_.t.index]=A.chunkIndex.t);const Q=this.arrays_[A.lod],C=this.arrayParams_[A.lod],E=await ko(Q,C,B,{signal:I});if(!BC(E.data))throw new Error(`Received chunk has an unsupported data type, data=${E.data.constructor.name}`);bC(E);const i={x:E.shape[this.dimensions_.x.index],y:E.shape[this.dimensions_.y.index],z:this.dimensions_.z?E.shape[this.dimensions_.z.index]:A.shape.z};if(i.x<A.shape.x||i.y<A.shape.y||i.z<A.shape.z)throw new Error(`Received incompatible shape for chunkIndex ${JSON.stringify(A.chunkIndex)} at LOD ${A.lod}: expected shape: ${JSON.stringify(A.shape)}, received shape: ${JSON.stringify(i)} (too small)`);i.x>A.shape.x||i.y>A.shape.y||i.z>A.shape.z?A.data=this.trimChunkPadding(A,E.data,E.stride):A.data=E.data;const s=A.data.BYTES_PER_ELEMENT;if(!FC(s))throw new Error("Invalid row alignment value. Possible values are 1, 2, 4, or 8");A.rowAlignmentBytes=s}trimChunkPadding(A,I,B){const Q=A.shape.x*A.shape.y*A.shape.z,C=new I.constructor(Q);let E=0;const i=this.dimensions_.z?B[this.dimensions_.z.index]:0,o=B[this.dimensions_.y.index];for(let h=0;h<A.shape.z;h++){const s=h*i;for(let R=0;R<A.shape.y;R++){const N=s+R*o,r=N+A.shape.x;C.set(I.subarray(N,r),E),E+=A.shape.x}}return C}async loadRegion(A,I,B){if(I>=this.arrays_.length)throw new Error(`Invalid LOD index: ${I}. Only ${this.arrays_.length} lod(s) available`);const Q=this.loaderAttributes_[I],C=this.regionToIndices(A,Q),{scale:E,translation:i}=Q,o=this.arrays_[I];let h={};B!==void 0&&(h={create_queue:()=>new co(B),opts:{signal:B.abortSignal}});const s=await oo(o,C,h);if(!BC(s.data))throw new Error(`Subarray has an unsupported data type, data=${s.data.constructor.name}`);if(bC(s),s.shape.length!==2&&s.shape.length!==3)throw new Error(`Expected to receive a 2D or 3D subarray. Instead chunk has shape ${s.shape}`);const R=s.data.BYTES_PER_ELEMENT;if(!FC(R))throw new Error("Invalid row alignment value. Possible values are 1, 2, 4, or 8");const N=n=>{const f=C[n];return typeof f=="number"?f*E[n]+i[n]:f.start===null?i[n]:f.start*E[n]+i[n]},r=N(C.length-1),M=N(C.length-2);return{state:"loaded",lod:I,visible:!0,prefetch:!1,priority:null,orderKey:null,data:s.data,shape:{x:s.shape[s.shape.length-1],y:s.shape[s.shape.length-2],z:1,c:s.shape.length===3?s.shape[0]:1},chunkIndex:{x:0,y:0,z:0,c:0,t:0},rowAlignmentBytes:R,scale:{x:E[C.length-1],y:E[C.length-2],z:1},offset:{x:r,y:M,z:0}}}getAttributes(){return this.loaderAttributes_}regionToIndices(A,I){const{dimensionNames:B,scale:Q,translation:C}=I,E=[];for(const[i,o]of B.entries()){const h=A.find(N=>N.dimension==o);if(!h)throw new Error(`Region does not contain a slice for ${o}`);let s;const R=h.index;R.type==="full"?s=RB(null):R.type==="point"?s=Math.round((R.value-C[i])/Q[i]):s=RB(Math.floor((R.start-C[i])/Q[i]),Math.ceil((R.stop-C[i])/Q[i])),E.push(s)}return E}}function Jo(g,A){const I=[],B=g.axes.length;for(let Q=0;Q<g.datasets.length;Q++){const C=g.datasets[Q],E=A[Q],i=C.coordinateTransformations[0].scale,o=C.coordinateTransformations.length===2?C.coordinateTransformations[1].translation:new Array(B).fill(0);I.push({dimensionNames:g.axes.map(h=>h.name),dimensionUnits:g.axes.map(h=>h.unit),chunks:E.chunks,shape:E.shape,scale:i,translation:o})}return I}function ro(g){const A=g[0].dimensionNames,I=ZC(A,"x"),B=ZC(A,"y"),Q={x:qg(A[I],I,g),y:qg(A[B],B,g),numLods:g.length},C=kB(A,"z");C!==-1&&(Q.z=qg(A[C],C,g));const E=kB(A,"c");E!==-1&&(Q.c=qg(A[E],E,g));const i=kB(A,"t");return i!==-1&&(Q.t=qg(A[i],i,g)),Q}function qg(g,A,I){return{name:g,index:A,lods:I.map(B=>({size:B.shape[A],chunkSize:B.chunks[A],scale:B.scale[A],translation:B.translation[A]}))}}function Yo(g,A){return g.toLowerCase()===A.toLowerCase()}function ZC(g,A){const I=kB(g,A);if(I===-1)throw new Error(`Could not find "${A}" dimension in [${g.join(", ")}]`);return I}function kB(g,A){return g.findIndex(I=>Yo(I,A))}function bC(g){let A=1;for(let I=g.shape.length-1;I>=0;I--){if(g.stride[I]!==A)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(g.stride)}, shape=${JSON.stringify(g.shape)}`);A*=g.shape[I]}}var yA;(function(g){g.assertEqual=Q=>Q;function A(Q){}g.assertIs=A;function I(Q){throw new Error}g.assertNever=I,g.arrayToEnum=Q=>{const C={};for(const E of Q)C[E]=E;return C},g.getValidEnumValues=Q=>{const C=g.objectKeys(Q).filter(i=>typeof Q[Q[i]]!="number"),E={};for(const i of C)E[i]=Q[i];return g.objectValues(E)},g.objectValues=Q=>g.objectKeys(Q).map(function(C){return Q[C]}),g.objectKeys=typeof Object.keys=="function"?Q=>Object.keys(Q):Q=>{const C=[];for(const E in Q)Object.prototype.hasOwnProperty.call(Q,E)&&C.push(E);return C},g.find=(Q,C)=>{for(const E of Q)if(C(E))return E},g.isInteger=typeof Number.isInteger=="function"?Q=>Number.isInteger(Q):Q=>typeof Q=="number"&&isFinite(Q)&&Math.floor(Q)===Q;function B(Q,C=" | "){return Q.map(E=>typeof E=="string"?`'${E}'`:E).join(C)}g.joinValues=B,g.jsonStringifyReplacer=(Q,C)=>typeof C=="bigint"?C.toString():C})(yA||(yA={}));var RQ;(function(g){g.mergeShapes=(A,I)=>({...A,...I})})(RQ||(RQ={}));const Z=yA.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),RI=g=>{switch(typeof g){case"undefined":return Z.undefined;case"string":return Z.string;case"number":return isNaN(g)?Z.nan:Z.number;case"boolean":return Z.boolean;case"function":return Z.function;case"bigint":return Z.bigint;case"symbol":return Z.symbol;case"object":return Array.isArray(g)?Z.array:g===null?Z.null:g.then&&typeof g.then=="function"&&g.catch&&typeof g.catch=="function"?Z.promise:typeof Map<"u"&&g instanceof Map?Z.map:typeof Set<"u"&&g instanceof Set?Z.set:typeof Date<"u"&&g instanceof Date?Z.date:Z.object;default:return Z.unknown}},q=yA.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),no=g=>JSON.stringify(g,null,2).replace(/"([^"]+)":/g,"$1:");class zA extends Error{get errors(){return this.issues}constructor(A){super(),this.issues=[],this.addIssue=B=>{this.issues=[...this.issues,B]},this.addIssues=(B=[])=>{this.issues=[...this.issues,...B]};const I=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,I):this.__proto__=I,this.name="ZodError",this.issues=A}format(A){const I=A||function(C){return C.message},B={_errors:[]},Q=C=>{for(const E of C.issues)if(E.code==="invalid_union")E.unionErrors.map(Q);else if(E.code==="invalid_return_type")Q(E.returnTypeError);else if(E.code==="invalid_arguments")Q(E.argumentsError);else if(E.path.length===0)B._errors.push(I(E));else{let i=B,o=0;for(;o<E.path.length;){const h=E.path[o];o===E.path.length-1?(i[h]=i[h]||{_errors:[]},i[h]._errors.push(I(E))):i[h]=i[h]||{_errors:[]},i=i[h],o++}}};return Q(this),B}static assert(A){if(!(A instanceof zA))throw new Error(`Not a ZodError: ${A}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,yA.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(A=I=>I.message){const I={},B=[];for(const Q of this.issues)Q.path.length>0?(I[Q.path[0]]=I[Q.path[0]]||[],I[Q.path[0]].push(A(Q))):B.push(A(Q));return{formErrors:B,fieldErrors:I}}get formErrors(){return this.flatten()}}zA.create=g=>new zA(g);const Bg=(g,A)=>{let I;switch(g.code){case q.invalid_type:g.received===Z.undefined?I="Required":I=`Expected ${g.expected}, received ${g.received}`;break;case q.invalid_literal:I=`Invalid literal value, expected ${JSON.stringify(g.expected,yA.jsonStringifyReplacer)}`;break;case q.unrecognized_keys:I=`Unrecognized key(s) in object: ${yA.joinValues(g.keys,", ")}`;break;case q.invalid_union:I="Invalid input";break;case q.invalid_union_discriminator:I=`Invalid discriminator value. Expected ${yA.joinValues(g.options)}`;break;case q.invalid_enum_value:I=`Invalid enum value. Expected ${yA.joinValues(g.options)}, received '${g.received}'`;break;case q.invalid_arguments:I="Invalid function arguments";break;case q.invalid_return_type:I="Invalid function return type";break;case q.invalid_date:I="Invalid date";break;case q.invalid_string:typeof g.validation=="object"?"includes"in g.validation?(I=`Invalid input: must include "${g.validation.includes}"`,typeof g.validation.position=="number"&&(I=`${I} at one or more positions greater than or equal to ${g.validation.position}`)):"startsWith"in g.validation?I=`Invalid input: must start with "${g.validation.startsWith}"`:"endsWith"in g.validation?I=`Invalid input: must end with "${g.validation.endsWith}"`:yA.assertNever(g.validation):g.validation!=="regex"?I=`Invalid ${g.validation}`:I="Invalid";break;case q.too_small:g.type==="array"?I=`Array must contain ${g.exact?"exactly":g.inclusive?"at least":"more than"} ${g.minimum} element(s)`:g.type==="string"?I=`String must contain ${g.exact?"exactly":g.inclusive?"at least":"over"} ${g.minimum} character(s)`:g.type==="number"?I=`Number must be ${g.exact?"exactly equal to ":g.inclusive?"greater than or equal to ":"greater than "}${g.minimum}`:g.type==="date"?I=`Date must be ${g.exact?"exactly equal to ":g.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(g.minimum))}`:I="Invalid input";break;case q.too_big:g.type==="array"?I=`Array must contain ${g.exact?"exactly":g.inclusive?"at most":"less than"} ${g.maximum} element(s)`:g.type==="string"?I=`String must contain ${g.exact?"exactly":g.inclusive?"at most":"under"} ${g.maximum} character(s)`:g.type==="number"?I=`Number must be ${g.exact?"exactly":g.inclusive?"less than or equal to":"less than"} ${g.maximum}`:g.type==="bigint"?I=`BigInt must be ${g.exact?"exactly":g.inclusive?"less than or equal to":"less than"} ${g.maximum}`:g.type==="date"?I=`Date must be ${g.exact?"exactly":g.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(g.maximum))}`:I="Invalid input";break;case q.custom:I="Invalid input";break;case q.invalid_intersection_types:I="Intersection results could not be merged";break;case q.not_multiple_of:I=`Number must be a multiple of ${g.multipleOf}`;break;case q.not_finite:I="Number must be finite";break;default:I=A.defaultError,yA.assertNever(g)}return{message:I}};let uC=Bg;function Ko(g){uC=g}function tB(){return uC}const cB=g=>{const{data:A,path:I,errorMaps:B,issueData:Q}=g,C=[...I,...Q.path||[]],E={...Q,path:C};if(Q.message!==void 0)return{...Q,path:C,message:Q.message};let i="";const o=B.filter(h=>!!h).slice().reverse();for(const h of o)i=h(E,{data:A,defaultError:i}).message;return{...Q,path:C,message:i}},Mo=[];function T(g,A){const I=tB(),B=cB({issueData:A,data:g.data,path:g.path,errorMaps:[g.common.contextualErrorMap,g.schemaErrorMap,I,I===Bg?void 0:Bg].filter(Q=>!!Q)});g.common.issues.push(B)}class bA{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(A,I){const B=[];for(const Q of I){if(Q.status==="aborted")return AA;Q.status==="dirty"&&A.dirty(),B.push(Q.value)}return{status:A.value,value:B}}static async mergeObjectAsync(A,I){const B=[];for(const Q of I){const C=await Q.key,E=await Q.value;B.push({key:C,value:E})}return bA.mergeObjectSync(A,B)}static mergeObjectSync(A,I){const B={};for(const Q of I){const{key:C,value:E}=Q;if(C.status==="aborted"||E.status==="aborted")return AA;C.status==="dirty"&&A.dirty(),E.status==="dirty"&&A.dirty(),C.value!=="__proto__"&&(typeof E.value<"u"||Q.alwaysSet)&&(B[C.value]=E.value)}return{status:A.value,value:B}}}const AA=Object.freeze({status:"aborted"}),Qg=g=>({status:"dirty",value:g}),uA=g=>({status:"valid",value:g}),NQ=g=>g.status==="aborted",UQ=g=>g.status==="dirty",mI=g=>g.status==="valid",dg=g=>typeof Promise<"u"&&g instanceof Promise;function LB(g,A,I,B){if(typeof A=="function"?g!==A||!0:!A.has(g))throw new TypeError("Cannot read private member from an object whose class did not declare it");return A.get(g)}function PC(g,A,I,B,Q){if(typeof A=="function"?g!==A||!0:!A.has(g))throw new TypeError("Cannot write private member to an object whose class did not declare it");return A.set(g,I),I}typeof SuppressedError=="function"&&SuppressedError;var X;(function(g){g.errToObj=A=>typeof A=="string"?{message:A}:A||{},g.toString=A=>typeof A=="string"?A:A?.message})(X||(X={}));var fg,lg;class hI{constructor(A,I,B,Q){this._cachedPath=[],this.parent=A,this.data=I,this._path=B,this._key=Q}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const OC=(g,A)=>{if(mI(A))return{success:!0,data:A.value};if(!g.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const I=new zA(g.common.issues);return this._error=I,this._error}}};function EA(g){if(!g)return{};const{errorMap:A,invalid_type_error:I,required_error:B,description:Q}=g;if(A&&(I||B))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return A?{errorMap:A,description:Q}:{errorMap:(E,i)=>{var o,h;const{message:s}=g;return E.code==="invalid_enum_value"?{message:s??i.defaultError}:typeof i.data>"u"?{message:(o=s??B)!==null&&o!==void 0?o:i.defaultError}:E.code!=="invalid_type"?{message:i.defaultError}:{message:(h=s??I)!==null&&h!==void 0?h:i.defaultError}},description:Q}}class oA{get description(){return this._def.description}_getType(A){return RI(A.data)}_getOrReturnCtx(A,I){return I||{common:A.parent.common,data:A.data,parsedType:RI(A.data),schemaErrorMap:this._def.errorMap,path:A.path,parent:A.parent}}_processInputParams(A){return{status:new bA,ctx:{common:A.parent.common,data:A.data,parsedType:RI(A.data),schemaErrorMap:this._def.errorMap,path:A.path,parent:A.parent}}}_parseSync(A){const I=this._parse(A);if(dg(I))throw new Error("Synchronous parse encountered promise.");return I}_parseAsync(A){const I=this._parse(A);return Promise.resolve(I)}parse(A,I){const B=this.safeParse(A,I);if(B.success)return B.data;throw B.error}safeParse(A,I){var B;const Q={common:{issues:[],async:(B=I?.async)!==null&&B!==void 0?B:!1,contextualErrorMap:I?.errorMap},path:I?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:RI(A)},C=this._parseSync({data:A,path:Q.path,parent:Q});return OC(Q,C)}"~validate"(A){var I,B;const Q={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:RI(A)};if(!this["~standard"].async)try{const C=this._parseSync({data:A,path:[],parent:Q});return mI(C)?{value:C.value}:{issues:Q.common.issues}}catch(C){!((B=(I=C?.message)===null||I===void 0?void 0:I.toLowerCase())===null||B===void 0)&&B.includes("encountered")&&(this["~standard"].async=!0),Q.common={issues:[],async:!0}}return this._parseAsync({data:A,path:[],parent:Q}).then(C=>mI(C)?{value:C.value}:{issues:Q.common.issues})}async parseAsync(A,I){const B=await this.safeParseAsync(A,I);if(B.success)return B.data;throw B.error}async safeParseAsync(A,I){const B={common:{issues:[],contextualErrorMap:I?.errorMap,async:!0},path:I?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:RI(A)},Q=this._parse({data:A,path:B.path,parent:B}),C=await(dg(Q)?Q:Promise.resolve(Q));return OC(B,C)}refine(A,I){const B=Q=>typeof I=="string"||typeof I>"u"?{message:I}:typeof I=="function"?I(Q):I;return this._refinement((Q,C)=>{const E=A(Q),i=()=>C.addIssue({code:q.custom,...B(Q)});return typeof Promise<"u"&&E instanceof Promise?E.then(o=>o?!0:(i(),!1)):E?!0:(i(),!1)})}refinement(A,I){return this._refinement((B,Q)=>A(B)?!0:(Q.addIssue(typeof I=="function"?I(B,Q):I),!1))}_refinement(A){return new oI({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:A}})}superRefine(A){return this._refinement(A)}constructor(A){this.spa=this.safeParseAsync,this._def=A,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:I=>this["~validate"](I)}}optional(){return FI.create(this,this._def)}nullable(){return rI.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return DI.create(this)}promise(){return Dg.create(this,this._def)}or(A){return Tg.create([this,A],this._def)}and(A){return xg.create(this,A,this._def)}transform(A){return new oI({...EA(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:A}})}default(A){const I=typeof A=="function"?A:()=>A;return new Og({...EA(this._def),innerType:this,defaultValue:I,typeName:_.ZodDefault})}brand(){return new cQ({typeName:_.ZodBranded,type:this,...EA(this._def)})}catch(A){const I=typeof A=="function"?A:()=>A;return new Vg({...EA(this._def),innerType:this,catchValue:I,typeName:_.ZodCatch})}describe(A){const I=this.constructor;return new I({...this._def,description:A})}pipe(A){return Xg.create(this,A)}readonly(){return vg.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ho=/^c[^\s-]{8,}$/i,eo=/^[0-9a-z]+$/,qo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fo=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,lo=/^[a-z0-9_-]{21}$/i,po=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Wo=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,mo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,To="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let kQ;const xo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Zo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,bo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,uo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Po=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Oo=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,VC="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Vo=new RegExp(`^${VC}$`);function XC(g){let A="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return g.precision?A=`${A}\\.\\d{${g.precision}}`:g.precision==null&&(A=`${A}(\\.\\d+)?`),A}function Xo(g){return new RegExp(`^${XC(g)}$`)}function vC(g){let A=`${VC}T${XC(g)}`;const I=[];return I.push(g.local?"Z?":"Z"),g.offset&&I.push("([+-]\\d{2}:?\\d{2})"),A=`${A}(${I.join("|")})`,new RegExp(`^${A}$`)}function vo(g,A){return!!((A==="v4"||!A)&&xo.test(g)||(A==="v6"||!A)&&bo.test(g))}function jo(g,A){if(!po.test(g))return!1;try{const[I]=g.split("."),B=I.replace(/-/g,"+").replace(/_/g,"/").padEnd(I.length+(4-I.length%4)%4,"="),Q=JSON.parse(atob(B));return!(typeof Q!="object"||Q===null||!Q.typ||!Q.alg||A&&Q.alg!==A)}catch{return!1}}function zo(g,A){return!!((A==="v4"||!A)&&Zo.test(g)||(A==="v6"||!A)&&uo.test(g))}class iI extends oA{_parse(A){if(this._def.coerce&&(A.data=String(A.data)),this._getType(A)!==Z.string){const C=this._getOrReturnCtx(A);return T(C,{code:q.invalid_type,expected:Z.string,received:C.parsedType}),AA}const B=new bA;let Q;for(const C of this._def.checks)if(C.kind==="min")A.data.length<C.value&&(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.too_small,minimum:C.value,type:"string",inclusive:!0,exact:!1,message:C.message}),B.dirty());else if(C.kind==="max")A.data.length>C.value&&(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.too_big,maximum:C.value,type:"string",inclusive:!0,exact:!1,message:C.message}),B.dirty());else if(C.kind==="length"){const E=A.data.length>C.value,i=A.data.length<C.value;(E||i)&&(Q=this._getOrReturnCtx(A,Q),E?T(Q,{code:q.too_big,maximum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}):i&&T(Q,{code:q.too_small,minimum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}),B.dirty())}else if(C.kind==="email")mo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"email",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="emoji")kQ||(kQ=new RegExp(To,"u")),kQ.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"emoji",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="uuid")fo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"uuid",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="nanoid")lo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"nanoid",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="cuid")Ho.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"cuid",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="cuid2")eo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"cuid2",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="ulid")qo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"ulid",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="url")try{new URL(A.data)}catch{Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"url",code:q.invalid_string,message:C.message}),B.dirty()}else C.kind==="regex"?(C.regex.lastIndex=0,C.regex.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"regex",code:q.invalid_string,message:C.message}),B.dirty())):C.kind==="trim"?A.data=A.data.trim():C.kind==="includes"?A.data.includes(C.value,C.position)||(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.invalid_string,validation:{includes:C.value,position:C.position},message:C.message}),B.dirty()):C.kind==="toLowerCase"?A.data=A.data.toLowerCase():C.kind==="toUpperCase"?A.data=A.data.toUpperCase():C.kind==="startsWith"?A.data.startsWith(C.value)||(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.invalid_string,validation:{startsWith:C.value},message:C.message}),B.dirty()):C.kind==="endsWith"?A.data.endsWith(C.value)||(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.invalid_string,validation:{endsWith:C.value},message:C.message}),B.dirty()):C.kind==="datetime"?vC(C).test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.invalid_string,validation:"datetime",message:C.message}),B.dirty()):C.kind==="date"?Vo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.invalid_string,validation:"date",message:C.message}),B.dirty()):C.kind==="time"?Xo(C).test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.invalid_string,validation:"time",message:C.message}),B.dirty()):C.kind==="duration"?Wo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"duration",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="ip"?vo(A.data,C.version)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"ip",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="jwt"?jo(A.data,C.alg)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"jwt",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="cidr"?zo(A.data,C.version)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"cidr",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="base64"?Po.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"base64",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="base64url"?Oo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),T(Q,{validation:"base64url",code:q.invalid_string,message:C.message}),B.dirty()):yA.assertNever(C);return{status:B.value,value:A.data}}_regex(A,I,B){return this.refinement(Q=>A.test(Q),{validation:I,code:q.invalid_string,...X.errToObj(B)})}_addCheck(A){return new iI({...this._def,checks:[...this._def.checks,A]})}email(A){return this._addCheck({kind:"email",...X.errToObj(A)})}url(A){return this._addCheck({kind:"url",...X.errToObj(A)})}emoji(A){return this._addCheck({kind:"emoji",...X.errToObj(A)})}uuid(A){return this._addCheck({kind:"uuid",...X.errToObj(A)})}nanoid(A){return this._addCheck({kind:"nanoid",...X.errToObj(A)})}cuid(A){return this._addCheck({kind:"cuid",...X.errToObj(A)})}cuid2(A){return this._addCheck({kind:"cuid2",...X.errToObj(A)})}ulid(A){return this._addCheck({kind:"ulid",...X.errToObj(A)})}base64(A){return this._addCheck({kind:"base64",...X.errToObj(A)})}base64url(A){return this._addCheck({kind:"base64url",...X.errToObj(A)})}jwt(A){return this._addCheck({kind:"jwt",...X.errToObj(A)})}ip(A){return this._addCheck({kind:"ip",...X.errToObj(A)})}cidr(A){return this._addCheck({kind:"cidr",...X.errToObj(A)})}datetime(A){var I,B;return typeof A=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:A}):this._addCheck({kind:"datetime",precision:typeof A?.precision>"u"?null:A?.precision,offset:(I=A?.offset)!==null&&I!==void 0?I:!1,local:(B=A?.local)!==null&&B!==void 0?B:!1,...X.errToObj(A?.message)})}date(A){return this._addCheck({kind:"date",message:A})}time(A){return typeof A=="string"?this._addCheck({kind:"time",precision:null,message:A}):this._addCheck({kind:"time",precision:typeof A?.precision>"u"?null:A?.precision,...X.errToObj(A?.message)})}duration(A){return this._addCheck({kind:"duration",...X.errToObj(A)})}regex(A,I){return this._addCheck({kind:"regex",regex:A,...X.errToObj(I)})}includes(A,I){return this._addCheck({kind:"includes",value:A,position:I?.position,...X.errToObj(I?.message)})}startsWith(A,I){return this._addCheck({kind:"startsWith",value:A,...X.errToObj(I)})}endsWith(A,I){return this._addCheck({kind:"endsWith",value:A,...X.errToObj(I)})}min(A,I){return this._addCheck({kind:"min",value:A,...X.errToObj(I)})}max(A,I){return this._addCheck({kind:"max",value:A,...X.errToObj(I)})}length(A,I){return this._addCheck({kind:"length",value:A,...X.errToObj(I)})}nonempty(A){return this.min(1,X.errToObj(A))}trim(){return new iI({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new iI({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new iI({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(A=>A.kind==="datetime")}get isDate(){return!!this._def.checks.find(A=>A.kind==="date")}get isTime(){return!!this._def.checks.find(A=>A.kind==="time")}get isDuration(){return!!this._def.checks.find(A=>A.kind==="duration")}get isEmail(){return!!this._def.checks.find(A=>A.kind==="email")}get isURL(){return!!this._def.checks.find(A=>A.kind==="url")}get isEmoji(){return!!this._def.checks.find(A=>A.kind==="emoji")}get isUUID(){return!!this._def.checks.find(A=>A.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(A=>A.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(A=>A.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(A=>A.kind==="cuid2")}get isULID(){return!!this._def.checks.find(A=>A.kind==="ulid")}get isIP(){return!!this._def.checks.find(A=>A.kind==="ip")}get isCIDR(){return!!this._def.checks.find(A=>A.kind==="cidr")}get isBase64(){return!!this._def.checks.find(A=>A.kind==="base64")}get isBase64url(){return!!this._def.checks.find(A=>A.kind==="base64url")}get minLength(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A}get maxLength(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A}}iI.create=g=>{var A;return new iI({checks:[],typeName:_.ZodString,coerce:(A=g?.coerce)!==null&&A!==void 0?A:!1,...EA(g)})};function _o(g,A){const I=(g.toString().split(".")[1]||"").length,B=(A.toString().split(".")[1]||"").length,Q=I>B?I:B,C=parseInt(g.toFixed(Q).replace(".","")),E=parseInt(A.toFixed(Q).replace(".",""));return C%E/Math.pow(10,Q)}class cI extends oA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(A){if(this._def.coerce&&(A.data=Number(A.data)),this._getType(A)!==Z.number){const C=this._getOrReturnCtx(A);return T(C,{code:q.invalid_type,expected:Z.number,received:C.parsedType}),AA}let B;const Q=new bA;for(const C of this._def.checks)C.kind==="int"?yA.isInteger(A.data)||(B=this._getOrReturnCtx(A,B),T(B,{code:q.invalid_type,expected:"integer",received:"float",message:C.message}),Q.dirty()):C.kind==="min"?(C.inclusive?A.data<C.value:A.data<=C.value)&&(B=this._getOrReturnCtx(A,B),T(B,{code:q.too_small,minimum:C.value,type:"number",inclusive:C.inclusive,exact:!1,message:C.message}),Q.dirty()):C.kind==="max"?(C.inclusive?A.data>C.value:A.data>=C.value)&&(B=this._getOrReturnCtx(A,B),T(B,{code:q.too_big,maximum:C.value,type:"number",inclusive:C.inclusive,exact:!1,message:C.message}),Q.dirty()):C.kind==="multipleOf"?_o(A.data,C.value)!==0&&(B=this._getOrReturnCtx(A,B),T(B,{code:q.not_multiple_of,multipleOf:C.value,message:C.message}),Q.dirty()):C.kind==="finite"?Number.isFinite(A.data)||(B=this._getOrReturnCtx(A,B),T(B,{code:q.not_finite,message:C.message}),Q.dirty()):yA.assertNever(C);return{status:Q.value,value:A.data}}gte(A,I){return this.setLimit("min",A,!0,X.toString(I))}gt(A,I){return this.setLimit("min",A,!1,X.toString(I))}lte(A,I){return this.setLimit("max",A,!0,X.toString(I))}lt(A,I){return this.setLimit("max",A,!1,X.toString(I))}setLimit(A,I,B,Q){return new cI({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:B,message:X.toString(Q)}]})}_addCheck(A){return new cI({...this._def,checks:[...this._def.checks,A]})}int(A){return this._addCheck({kind:"int",message:X.toString(A)})}positive(A){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(A)})}negative(A){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(A)})}nonpositive(A){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(A)})}nonnegative(A){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(A)})}multipleOf(A,I){return this._addCheck({kind:"multipleOf",value:A,message:X.toString(I)})}finite(A){return this._addCheck({kind:"finite",message:X.toString(A)})}safe(A){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(A)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.toString(A)})}get minValue(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A}get maxValue(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A}get isInt(){return!!this._def.checks.find(A=>A.kind==="int"||A.kind==="multipleOf"&&yA.isInteger(A.value))}get isFinite(){let A=null,I=null;for(const B of this._def.checks){if(B.kind==="finite"||B.kind==="int"||B.kind==="multipleOf")return!0;B.kind==="min"?(I===null||B.value>I)&&(I=B.value):B.kind==="max"&&(A===null||B.value<A)&&(A=B.value)}return Number.isFinite(I)&&Number.isFinite(A)}}cI.create=g=>new cI({checks:[],typeName:_.ZodNumber,coerce:g?.coerce||!1,...EA(g)});class LI extends oA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(A){if(this._def.coerce)try{A.data=BigInt(A.data)}catch{return this._getInvalidInput(A)}if(this._getType(A)!==Z.bigint)return this._getInvalidInput(A);let B;const Q=new bA;for(const C of this._def.checks)C.kind==="min"?(C.inclusive?A.data<C.value:A.data<=C.value)&&(B=this._getOrReturnCtx(A,B),T(B,{code:q.too_small,type:"bigint",minimum:C.value,inclusive:C.inclusive,message:C.message}),Q.dirty()):C.kind==="max"?(C.inclusive?A.data>C.value:A.data>=C.value)&&(B=this._getOrReturnCtx(A,B),T(B,{code:q.too_big,type:"bigint",maximum:C.value,inclusive:C.inclusive,message:C.message}),Q.dirty()):C.kind==="multipleOf"?A.data%C.value!==BigInt(0)&&(B=this._getOrReturnCtx(A,B),T(B,{code:q.not_multiple_of,multipleOf:C.value,message:C.message}),Q.dirty()):yA.assertNever(C);return{status:Q.value,value:A.data}}_getInvalidInput(A){const I=this._getOrReturnCtx(A);return T(I,{code:q.invalid_type,expected:Z.bigint,received:I.parsedType}),AA}gte(A,I){return this.setLimit("min",A,!0,X.toString(I))}gt(A,I){return this.setLimit("min",A,!1,X.toString(I))}lte(A,I){return this.setLimit("max",A,!0,X.toString(I))}lt(A,I){return this.setLimit("max",A,!1,X.toString(I))}setLimit(A,I,B,Q){return new LI({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:B,message:X.toString(Q)}]})}_addCheck(A){return new LI({...this._def,checks:[...this._def.checks,A]})}positive(A){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X.toString(A)})}negative(A){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(A)})}nonpositive(A){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(A)})}nonnegative(A){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(A)})}multipleOf(A,I){return this._addCheck({kind:"multipleOf",value:A,message:X.toString(I)})}get minValue(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A}get maxValue(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A}}LI.create=g=>{var A;return new LI({checks:[],typeName:_.ZodBigInt,coerce:(A=g?.coerce)!==null&&A!==void 0?A:!1,...EA(g)})};class pg extends oA{_parse(A){if(this._def.coerce&&(A.data=!!A.data),this._getType(A)!==Z.boolean){const B=this._getOrReturnCtx(A);return T(B,{code:q.invalid_type,expected:Z.boolean,received:B.parsedType}),AA}return uA(A.data)}}pg.create=g=>new pg({typeName:_.ZodBoolean,coerce:g?.coerce||!1,...EA(g)});class TI extends oA{_parse(A){if(this._def.coerce&&(A.data=new Date(A.data)),this._getType(A)!==Z.date){const C=this._getOrReturnCtx(A);return T(C,{code:q.invalid_type,expected:Z.date,received:C.parsedType}),AA}if(isNaN(A.data.getTime())){const C=this._getOrReturnCtx(A);return T(C,{code:q.invalid_date}),AA}const B=new bA;let Q;for(const C of this._def.checks)C.kind==="min"?A.data.getTime()<C.value&&(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.too_small,message:C.message,inclusive:!0,exact:!1,minimum:C.value,type:"date"}),B.dirty()):C.kind==="max"?A.data.getTime()>C.value&&(Q=this._getOrReturnCtx(A,Q),T(Q,{code:q.too_big,message:C.message,inclusive:!0,exact:!1,maximum:C.value,type:"date"}),B.dirty()):yA.assertNever(C);return{status:B.value,value:new Date(A.data.getTime())}}_addCheck(A){return new TI({...this._def,checks:[...this._def.checks,A]})}min(A,I){return this._addCheck({kind:"min",value:A.getTime(),message:X.toString(I)})}max(A,I){return this._addCheck({kind:"max",value:A.getTime(),message:X.toString(I)})}get minDate(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A!=null?new Date(A):null}get maxDate(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A!=null?new Date(A):null}}TI.create=g=>new TI({checks:[],coerce:g?.coerce||!1,typeName:_.ZodDate,...EA(g)});class JB extends oA{_parse(A){if(this._getType(A)!==Z.symbol){const B=this._getOrReturnCtx(A);return T(B,{code:q.invalid_type,expected:Z.symbol,received:B.parsedType}),AA}return uA(A.data)}}JB.create=g=>new JB({typeName:_.ZodSymbol,...EA(g)});class Wg extends oA{_parse(A){if(this._getType(A)!==Z.undefined){const B=this._getOrReturnCtx(A);return T(B,{code:q.invalid_type,expected:Z.undefined,received:B.parsedType}),AA}return uA(A.data)}}Wg.create=g=>new Wg({typeName:_.ZodUndefined,...EA(g)});class mg extends oA{_parse(A){if(this._getType(A)!==Z.null){const B=this._getOrReturnCtx(A);return T(B,{code:q.invalid_type,expected:Z.null,received:B.parsedType}),AA}return uA(A.data)}}mg.create=g=>new mg({typeName:_.ZodNull,...EA(g)});class Cg extends oA{constructor(){super(...arguments),this._any=!0}_parse(A){return uA(A.data)}}Cg.create=g=>new Cg({typeName:_.ZodAny,...EA(g)});class xI extends oA{constructor(){super(...arguments),this._unknown=!0}_parse(A){return uA(A.data)}}xI.create=g=>new xI({typeName:_.ZodUnknown,...EA(g)});class NI extends oA{_parse(A){const I=this._getOrReturnCtx(A);return T(I,{code:q.invalid_type,expected:Z.never,received:I.parsedType}),AA}}NI.create=g=>new NI({typeName:_.ZodNever,...EA(g)});class rB extends oA{_parse(A){if(this._getType(A)!==Z.undefined){const B=this._getOrReturnCtx(A);return T(B,{code:q.invalid_type,expected:Z.void,received:B.parsedType}),AA}return uA(A.data)}}rB.create=g=>new rB({typeName:_.ZodVoid,...EA(g)});class DI extends oA{_parse(A){const{ctx:I,status:B}=this._processInputParams(A),Q=this._def;if(I.parsedType!==Z.array)return T(I,{code:q.invalid_type,expected:Z.array,received:I.parsedType}),AA;if(Q.exactLength!==null){const E=I.data.length>Q.exactLength.value,i=I.data.length<Q.exactLength.value;(E||i)&&(T(I,{code:E?q.too_big:q.too_small,minimum:i?Q.exactLength.value:void 0,maximum:E?Q.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Q.exactLength.message}),B.dirty())}if(Q.minLength!==null&&I.data.length<Q.minLength.value&&(T(I,{code:q.too_small,minimum:Q.minLength.value,type:"array",inclusive:!0,exact:!1,message:Q.minLength.message}),B.dirty()),Q.maxLength!==null&&I.data.length>Q.maxLength.value&&(T(I,{code:q.too_big,maximum:Q.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Q.maxLength.message}),B.dirty()),I.common.async)return Promise.all([...I.data].map((E,i)=>Q.type._parseAsync(new hI(I,E,I.path,i)))).then(E=>bA.mergeArray(B,E));const C=[...I.data].map((E,i)=>Q.type._parseSync(new hI(I,E,I.path,i)));return bA.mergeArray(B,C)}get element(){return this._def.type}min(A,I){return new DI({...this._def,minLength:{value:A,message:X.toString(I)}})}max(A,I){return new DI({...this._def,maxLength:{value:A,message:X.toString(I)}})}length(A,I){return new DI({...this._def,exactLength:{value:A,message:X.toString(I)}})}nonempty(A){return this.min(1,A)}}DI.create=(g,A)=>new DI({type:g,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...EA(A)});function Eg(g){if(g instanceof YA){const A={};for(const I in g.shape){const B=g.shape[I];A[I]=FI.create(Eg(B))}return new YA({...g._def,shape:()=>A})}else return g instanceof DI?new DI({...g._def,type:Eg(g.element)}):g instanceof FI?FI.create(Eg(g.unwrap())):g instanceof rI?rI.create(Eg(g.unwrap())):g instanceof GI?GI.create(g.items.map(A=>Eg(A))):g}class YA extends oA{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const A=this._def.shape(),I=yA.objectKeys(A);return this._cached={shape:A,keys:I}}_parse(A){if(this._getType(A)!==Z.object){const h=this._getOrReturnCtx(A);return T(h,{code:q.invalid_type,expected:Z.object,received:h.parsedType}),AA}const{status:B,ctx:Q}=this._processInputParams(A),{shape:C,keys:E}=this._getCached(),i=[];if(!(this._def.catchall instanceof NI&&this._def.unknownKeys==="strip"))for(const h in Q.data)E.includes(h)||i.push(h);const o=[];for(const h of E){const s=C[h],R=Q.data[h];o.push({key:{status:"valid",value:h},value:s._parse(new hI(Q,R,Q.path,h)),alwaysSet:h in Q.data})}if(this._def.catchall instanceof NI){const h=this._def.unknownKeys;if(h==="passthrough")for(const s of i)o.push({key:{status:"valid",value:s},value:{status:"valid",value:Q.data[s]}});else if(h==="strict")i.length>0&&(T(Q,{code:q.unrecognized_keys,keys:i}),B.dirty());else if(h!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const h=this._def.catchall;for(const s of i){const R=Q.data[s];o.push({key:{status:"valid",value:s},value:h._parse(new hI(Q,R,Q.path,s)),alwaysSet:s in Q.data})}}return Q.common.async?Promise.resolve().then(async()=>{const h=[];for(const s of o){const R=await s.key,N=await s.value;h.push({key:R,value:N,alwaysSet:s.alwaysSet})}return h}).then(h=>bA.mergeObjectSync(B,h)):bA.mergeObjectSync(B,o)}get shape(){return this._def.shape()}strict(A){return X.errToObj,new YA({...this._def,unknownKeys:"strict",...A!==void 0?{errorMap:(I,B)=>{var Q,C,E,i;const o=(E=(C=(Q=this._def).errorMap)===null||C===void 0?void 0:C.call(Q,I,B).message)!==null&&E!==void 0?E:B.defaultError;return I.code==="unrecognized_keys"?{message:(i=X.errToObj(A).message)!==null&&i!==void 0?i:o}:{message:o}}}:{}})}strip(){return new YA({...this._def,unknownKeys:"strip"})}passthrough(){return new YA({...this._def,unknownKeys:"passthrough"})}extend(A){return new YA({...this._def,shape:()=>({...this._def.shape(),...A})})}merge(A){return new YA({unknownKeys:A._def.unknownKeys,catchall:A._def.catchall,shape:()=>({...this._def.shape(),...A._def.shape()}),typeName:_.ZodObject})}setKey(A,I){return this.augment({[A]:I})}catchall(A){return new YA({...this._def,catchall:A})}pick(A){const I={};return yA.objectKeys(A).forEach(B=>{A[B]&&this.shape[B]&&(I[B]=this.shape[B])}),new YA({...this._def,shape:()=>I})}omit(A){const I={};return yA.objectKeys(this.shape).forEach(B=>{A[B]||(I[B]=this.shape[B])}),new YA({...this._def,shape:()=>I})}deepPartial(){return Eg(this)}partial(A){const I={};return yA.objectKeys(this.shape).forEach(B=>{const Q=this.shape[B];A&&!A[B]?I[B]=Q:I[B]=Q.optional()}),new YA({...this._def,shape:()=>I})}required(A){const I={};return yA.objectKeys(this.shape).forEach(B=>{if(A&&!A[B])I[B]=this.shape[B];else{let C=this.shape[B];for(;C instanceof FI;)C=C._def.innerType;I[B]=C}}),new YA({...this._def,shape:()=>I})}keyof(){return jC(yA.objectKeys(this.shape))}}YA.create=(g,A)=>new YA({shape:()=>g,unknownKeys:"strip",catchall:NI.create(),typeName:_.ZodObject,...EA(A)}),YA.strictCreate=(g,A)=>new YA({shape:()=>g,unknownKeys:"strict",catchall:NI.create(),typeName:_.ZodObject,...EA(A)}),YA.lazycreate=(g,A)=>new YA({shape:g,unknownKeys:"strip",catchall:NI.create(),typeName:_.ZodObject,...EA(A)});class Tg extends oA{_parse(A){const{ctx:I}=this._processInputParams(A),B=this._def.options;function Q(C){for(const i of C)if(i.result.status==="valid")return i.result;for(const i of C)if(i.result.status==="dirty")return I.common.issues.push(...i.ctx.common.issues),i.result;const E=C.map(i=>new zA(i.ctx.common.issues));return T(I,{code:q.invalid_union,unionErrors:E}),AA}if(I.common.async)return Promise.all(B.map(async C=>{const E={...I,common:{...I.common,issues:[]},parent:null};return{result:await C._parseAsync({data:I.data,path:I.path,parent:E}),ctx:E}})).then(Q);{let C;const E=[];for(const o of B){const h={...I,common:{...I.common,issues:[]},parent:null},s=o._parseSync({data:I.data,path:I.path,parent:h});if(s.status==="valid")return s;s.status==="dirty"&&!C&&(C={result:s,ctx:h}),h.common.issues.length&&E.push(h.common.issues)}if(C)return I.common.issues.push(...C.ctx.common.issues),C.result;const i=E.map(o=>new zA(o));return T(I,{code:q.invalid_union,unionErrors:i}),AA}}get options(){return this._def.options}}Tg.create=(g,A)=>new Tg({options:g,typeName:_.ZodUnion,...EA(A)});const UI=g=>g instanceof bg?UI(g.schema):g instanceof oI?UI(g.innerType()):g instanceof ug?[g.value]:g instanceof JI?g.options:g instanceof Pg?yA.objectValues(g.enum):g instanceof Og?UI(g._def.innerType):g instanceof Wg?[void 0]:g instanceof mg?[null]:g instanceof FI?[void 0,...UI(g.unwrap())]:g instanceof rI?[null,...UI(g.unwrap())]:g instanceof cQ||g instanceof vg?UI(g.unwrap()):g instanceof Vg?UI(g._def.innerType):[];class YB extends oA{_parse(A){const{ctx:I}=this._processInputParams(A);if(I.parsedType!==Z.object)return T(I,{code:q.invalid_type,expected:Z.object,received:I.parsedType}),AA;const B=this.discriminator,Q=I.data[B],C=this.optionsMap.get(Q);return C?I.common.async?C._parseAsync({data:I.data,path:I.path,parent:I}):C._parseSync({data:I.data,path:I.path,parent:I}):(T(I,{code:q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[B]}),AA)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(A,I,B){const Q=new Map;for(const C of I){const E=UI(C.shape[A]);if(!E.length)throw new Error(`A discriminator value for key \`${A}\` could not be extracted from all schema options`);for(const i of E){if(Q.has(i))throw new Error(`Discriminator property ${String(A)} has duplicate value ${String(i)}`);Q.set(i,C)}}return new YB({typeName:_.ZodDiscriminatedUnion,discriminator:A,options:I,optionsMap:Q,...EA(B)})}}function tQ(g,A){const I=RI(g),B=RI(A);if(g===A)return{valid:!0,data:g};if(I===Z.object&&B===Z.object){const Q=yA.objectKeys(A),C=yA.objectKeys(g).filter(i=>Q.indexOf(i)!==-1),E={...g,...A};for(const i of C){const o=tQ(g[i],A[i]);if(!o.valid)return{valid:!1};E[i]=o.data}return{valid:!0,data:E}}else if(I===Z.array&&B===Z.array){if(g.length!==A.length)return{valid:!1};const Q=[];for(let C=0;C<g.length;C++){const E=g[C],i=A[C],o=tQ(E,i);if(!o.valid)return{valid:!1};Q.push(o.data)}return{valid:!0,data:Q}}else return I===Z.date&&B===Z.date&&+g==+A?{valid:!0,data:g}:{valid:!1}}class xg extends oA{_parse(A){const{status:I,ctx:B}=this._processInputParams(A),Q=(C,E)=>{if(NQ(C)||NQ(E))return AA;const i=tQ(C.value,E.value);return i.valid?((UQ(C)||UQ(E))&&I.dirty(),{status:I.value,value:i.data}):(T(B,{code:q.invalid_intersection_types}),AA)};return B.common.async?Promise.all([this._def.left._parseAsync({data:B.data,path:B.path,parent:B}),this._def.right._parseAsync({data:B.data,path:B.path,parent:B})]).then(([C,E])=>Q(C,E)):Q(this._def.left._parseSync({data:B.data,path:B.path,parent:B}),this._def.right._parseSync({data:B.data,path:B.path,parent:B}))}}xg.create=(g,A,I)=>new xg({left:g,right:A,typeName:_.ZodIntersection,...EA(I)});class GI extends oA{_parse(A){const{status:I,ctx:B}=this._processInputParams(A);if(B.parsedType!==Z.array)return T(B,{code:q.invalid_type,expected:Z.array,received:B.parsedType}),AA;if(B.data.length<this._def.items.length)return T(B,{code:q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),AA;!this._def.rest&&B.data.length>this._def.items.length&&(T(B,{code:q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I.dirty());const C=[...B.data].map((E,i)=>{const o=this._def.items[i]||this._def.rest;return o?o._parse(new hI(B,E,B.path,i)):null}).filter(E=>!!E);return B.common.async?Promise.all(C).then(E=>bA.mergeArray(I,E)):bA.mergeArray(I,C)}get items(){return this._def.items}rest(A){return new GI({...this._def,rest:A})}}GI.create=(g,A)=>{if(!Array.isArray(g))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new GI({items:g,typeName:_.ZodTuple,rest:null,...EA(A)})};class Zg extends oA{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(A){const{status:I,ctx:B}=this._processInputParams(A);if(B.parsedType!==Z.object)return T(B,{code:q.invalid_type,expected:Z.object,received:B.parsedType}),AA;const Q=[],C=this._def.keyType,E=this._def.valueType;for(const i in B.data)Q.push({key:C._parse(new hI(B,i,B.path,i)),value:E._parse(new hI(B,B.data[i],B.path,i)),alwaysSet:i in B.data});return B.common.async?bA.mergeObjectAsync(I,Q):bA.mergeObjectSync(I,Q)}get element(){return this._def.valueType}static create(A,I,B){return I instanceof oA?new Zg({keyType:A,valueType:I,typeName:_.ZodRecord,...EA(B)}):new Zg({keyType:iI.create(),valueType:A,typeName:_.ZodRecord,...EA(I)})}}class nB extends oA{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(A){const{status:I,ctx:B}=this._processInputParams(A);if(B.parsedType!==Z.map)return T(B,{code:q.invalid_type,expected:Z.map,received:B.parsedType}),AA;const Q=this._def.keyType,C=this._def.valueType,E=[...B.data.entries()].map(([i,o],h)=>({key:Q._parse(new hI(B,i,B.path,[h,"key"])),value:C._parse(new hI(B,o,B.path,[h,"value"]))}));if(B.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const o of E){const h=await o.key,s=await o.value;if(h.status==="aborted"||s.status==="aborted")return AA;(h.status==="dirty"||s.status==="dirty")&&I.dirty(),i.set(h.value,s.value)}return{status:I.value,value:i}})}else{const i=new Map;for(const o of E){const h=o.key,s=o.value;if(h.status==="aborted"||s.status==="aborted")return AA;(h.status==="dirty"||s.status==="dirty")&&I.dirty(),i.set(h.value,s.value)}return{status:I.value,value:i}}}}nB.create=(g,A,I)=>new nB({valueType:A,keyType:g,typeName:_.ZodMap,...EA(I)});class ZI extends oA{_parse(A){const{status:I,ctx:B}=this._processInputParams(A);if(B.parsedType!==Z.set)return T(B,{code:q.invalid_type,expected:Z.set,received:B.parsedType}),AA;const Q=this._def;Q.minSize!==null&&B.data.size<Q.minSize.value&&(T(B,{code:q.too_small,minimum:Q.minSize.value,type:"set",inclusive:!0,exact:!1,message:Q.minSize.message}),I.dirty()),Q.maxSize!==null&&B.data.size>Q.maxSize.value&&(T(B,{code:q.too_big,maximum:Q.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Q.maxSize.message}),I.dirty());const C=this._def.valueType;function E(o){const h=new Set;for(const s of o){if(s.status==="aborted")return AA;s.status==="dirty"&&I.dirty(),h.add(s.value)}return{status:I.value,value:h}}const i=[...B.data.values()].map((o,h)=>C._parse(new hI(B,o,B.path,h)));return B.common.async?Promise.all(i).then(o=>E(o)):E(i)}min(A,I){return new ZI({...this._def,minSize:{value:A,message:X.toString(I)}})}max(A,I){return new ZI({...this._def,maxSize:{value:A,message:X.toString(I)}})}size(A,I){return this.min(A,I).max(A,I)}nonempty(A){return this.min(1,A)}}ZI.create=(g,A)=>new ZI({valueType:g,minSize:null,maxSize:null,typeName:_.ZodSet,...EA(A)});class ig extends oA{constructor(){super(...arguments),this.validate=this.implement}_parse(A){const{ctx:I}=this._processInputParams(A);if(I.parsedType!==Z.function)return T(I,{code:q.invalid_type,expected:Z.function,received:I.parsedType}),AA;function B(i,o){return cB({data:i,path:I.path,errorMaps:[I.common.contextualErrorMap,I.schemaErrorMap,tB(),Bg].filter(h=>!!h),issueData:{code:q.invalid_arguments,argumentsError:o}})}function Q(i,o){return cB({data:i,path:I.path,errorMaps:[I.common.contextualErrorMap,I.schemaErrorMap,tB(),Bg].filter(h=>!!h),issueData:{code:q.invalid_return_type,returnTypeError:o}})}const C={errorMap:I.common.contextualErrorMap},E=I.data;if(this._def.returns instanceof Dg){const i=this;return uA(async function(...o){const h=new zA([]),s=await i._def.args.parseAsync(o,C).catch(r=>{throw h.addIssue(B(o,r)),h}),R=await Reflect.apply(E,this,s);return await i._def.returns._def.type.parseAsync(R,C).catch(r=>{throw h.addIssue(Q(R,r)),h})})}else{const i=this;return uA(function(...o){const h=i._def.args.safeParse(o,C);if(!h.success)throw new zA([B(o,h.error)]);const s=Reflect.apply(E,this,h.data),R=i._def.returns.safeParse(s,C);if(!R.success)throw new zA([Q(s,R.error)]);return R.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...A){return new ig({...this._def,args:GI.create(A).rest(xI.create())})}returns(A){return new ig({...this._def,returns:A})}implement(A){return this.parse(A)}strictImplement(A){return this.parse(A)}static create(A,I,B){return new ig({args:A||GI.create([]).rest(xI.create()),returns:I||xI.create(),typeName:_.ZodFunction,...EA(B)})}}class bg extends oA{get schema(){return this._def.getter()}_parse(A){const{ctx:I}=this._processInputParams(A);return this._def.getter()._parse({data:I.data,path:I.path,parent:I})}}bg.create=(g,A)=>new bg({getter:g,typeName:_.ZodLazy,...EA(A)});class ug extends oA{_parse(A){if(A.data!==this._def.value){const I=this._getOrReturnCtx(A);return T(I,{received:I.data,code:q.invalid_literal,expected:this._def.value}),AA}return{status:"valid",value:A.data}}get value(){return this._def.value}}ug.create=(g,A)=>new ug({value:g,typeName:_.ZodLiteral,...EA(A)});function jC(g,A){return new JI({values:g,typeName:_.ZodEnum,...EA(A)})}class JI extends oA{constructor(){super(...arguments),fg.set(this,void 0)}_parse(A){if(typeof A.data!="string"){const I=this._getOrReturnCtx(A),B=this._def.values;return T(I,{expected:yA.joinValues(B),received:I.parsedType,code:q.invalid_type}),AA}if(LB(this,fg)||PC(this,fg,new Set(this._def.values)),!LB(this,fg).has(A.data)){const I=this._getOrReturnCtx(A),B=this._def.values;return T(I,{received:I.data,code:q.invalid_enum_value,options:B}),AA}return uA(A.data)}get options(){return this._def.values}get enum(){const A={};for(const I of this._def.values)A[I]=I;return A}get Values(){const A={};for(const I of this._def.values)A[I]=I;return A}get Enum(){const A={};for(const I of this._def.values)A[I]=I;return A}extract(A,I=this._def){return JI.create(A,{...this._def,...I})}exclude(A,I=this._def){return JI.create(this.options.filter(B=>!A.includes(B)),{...this._def,...I})}}fg=new WeakMap,JI.create=jC;class Pg extends oA{constructor(){super(...arguments),lg.set(this,void 0)}_parse(A){const I=yA.getValidEnumValues(this._def.values),B=this._getOrReturnCtx(A);if(B.parsedType!==Z.string&&B.parsedType!==Z.number){const Q=yA.objectValues(I);return T(B,{expected:yA.joinValues(Q),received:B.parsedType,code:q.invalid_type}),AA}if(LB(this,lg)||PC(this,lg,new Set(yA.getValidEnumValues(this._def.values))),!LB(this,lg).has(A.data)){const Q=yA.objectValues(I);return T(B,{received:B.data,code:q.invalid_enum_value,options:Q}),AA}return uA(A.data)}get enum(){return this._def.values}}lg=new WeakMap,Pg.create=(g,A)=>new Pg({values:g,typeName:_.ZodNativeEnum,...EA(A)});class Dg extends oA{unwrap(){return this._def.type}_parse(A){const{ctx:I}=this._processInputParams(A);if(I.parsedType!==Z.promise&&I.common.async===!1)return T(I,{code:q.invalid_type,expected:Z.promise,received:I.parsedType}),AA;const B=I.parsedType===Z.promise?I.data:Promise.resolve(I.data);return uA(B.then(Q=>this._def.type.parseAsync(Q,{path:I.path,errorMap:I.common.contextualErrorMap})))}}Dg.create=(g,A)=>new Dg({type:g,typeName:_.ZodPromise,...EA(A)});class oI extends oA{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(A){const{status:I,ctx:B}=this._processInputParams(A),Q=this._def.effect||null,C={addIssue:E=>{T(B,E),E.fatal?I.abort():I.dirty()},get path(){return B.path}};if(C.addIssue=C.addIssue.bind(C),Q.type==="preprocess"){const E=Q.transform(B.data,C);if(B.common.async)return Promise.resolve(E).then(async i=>{if(I.value==="aborted")return AA;const o=await this._def.schema._parseAsync({data:i,path:B.path,parent:B});return o.status==="aborted"?AA:o.status==="dirty"||I.value==="dirty"?Qg(o.value):o});{if(I.value==="aborted")return AA;const i=this._def.schema._parseSync({data:E,path:B.path,parent:B});return i.status==="aborted"?AA:i.status==="dirty"||I.value==="dirty"?Qg(i.value):i}}if(Q.type==="refinement"){const E=i=>{const o=Q.refinement(i,C);if(B.common.async)return Promise.resolve(o);if(o instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(B.common.async===!1){const i=this._def.schema._parseSync({data:B.data,path:B.path,parent:B});return i.status==="aborted"?AA:(i.status==="dirty"&&I.dirty(),E(i.value),{status:I.value,value:i.value})}else return this._def.schema._parseAsync({data:B.data,path:B.path,parent:B}).then(i=>i.status==="aborted"?AA:(i.status==="dirty"&&I.dirty(),E(i.value).then(()=>({status:I.value,value:i.value}))))}if(Q.type==="transform")if(B.common.async===!1){const E=this._def.schema._parseSync({data:B.data,path:B.path,parent:B});if(!mI(E))return E;const i=Q.transform(E.value,C);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:I.value,value:i}}else return this._def.schema._parseAsync({data:B.data,path:B.path,parent:B}).then(E=>mI(E)?Promise.resolve(Q.transform(E.value,C)).then(i=>({status:I.value,value:i})):E);yA.assertNever(Q)}}oI.create=(g,A,I)=>new oI({schema:g,typeName:_.ZodEffects,effect:A,...EA(I)}),oI.createWithPreprocess=(g,A,I)=>new oI({schema:A,effect:{type:"preprocess",transform:g},typeName:_.ZodEffects,...EA(I)});class FI extends oA{_parse(A){return this._getType(A)===Z.undefined?uA(void 0):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}FI.create=(g,A)=>new FI({innerType:g,typeName:_.ZodOptional,...EA(A)});class rI extends oA{_parse(A){return this._getType(A)===Z.null?uA(null):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}rI.create=(g,A)=>new rI({innerType:g,typeName:_.ZodNullable,...EA(A)});class Og extends oA{_parse(A){const{ctx:I}=this._processInputParams(A);let B=I.data;return I.parsedType===Z.undefined&&(B=this._def.defaultValue()),this._def.innerType._parse({data:B,path:I.path,parent:I})}removeDefault(){return this._def.innerType}}Og.create=(g,A)=>new Og({innerType:g,typeName:_.ZodDefault,defaultValue:typeof A.default=="function"?A.default:()=>A.default,...EA(A)});class Vg extends oA{_parse(A){const{ctx:I}=this._processInputParams(A),B={...I,common:{...I.common,issues:[]}},Q=this._def.innerType._parse({data:B.data,path:B.path,parent:{...B}});return dg(Q)?Q.then(C=>({status:"valid",value:C.status==="valid"?C.value:this._def.catchValue({get error(){return new zA(B.common.issues)},input:B.data})})):{status:"valid",value:Q.status==="valid"?Q.value:this._def.catchValue({get error(){return new zA(B.common.issues)},input:B.data})}}removeCatch(){return this._def.innerType}}Vg.create=(g,A)=>new Vg({innerType:g,typeName:_.ZodCatch,catchValue:typeof A.catch=="function"?A.catch:()=>A.catch,...EA(A)});class KB extends oA{_parse(A){if(this._getType(A)!==Z.nan){const B=this._getOrReturnCtx(A);return T(B,{code:q.invalid_type,expected:Z.nan,received:B.parsedType}),AA}return{status:"valid",value:A.data}}}KB.create=g=>new KB({typeName:_.ZodNaN,...EA(g)});const $o=Symbol("zod_brand");class cQ extends oA{_parse(A){const{ctx:I}=this._processInputParams(A),B=I.data;return this._def.type._parse({data:B,path:I.path,parent:I})}unwrap(){return this._def.type}}class Xg extends oA{_parse(A){const{status:I,ctx:B}=this._processInputParams(A);if(B.common.async)return(async()=>{const C=await this._def.in._parseAsync({data:B.data,path:B.path,parent:B});return C.status==="aborted"?AA:C.status==="dirty"?(I.dirty(),Qg(C.value)):this._def.out._parseAsync({data:C.value,path:B.path,parent:B})})();{const Q=this._def.in._parseSync({data:B.data,path:B.path,parent:B});return Q.status==="aborted"?AA:Q.status==="dirty"?(I.dirty(),{status:"dirty",value:Q.value}):this._def.out._parseSync({data:Q.value,path:B.path,parent:B})}}static create(A,I){return new Xg({in:A,out:I,typeName:_.ZodPipeline})}}class vg extends oA{_parse(A){const I=this._def.innerType._parse(A),B=Q=>(mI(Q)&&(Q.value=Object.freeze(Q.value)),Q);return dg(I)?I.then(Q=>B(Q)):B(I)}unwrap(){return this._def.innerType}}vg.create=(g,A)=>new vg({innerType:g,typeName:_.ZodReadonly,...EA(A)});function zC(g,A){const I=typeof g=="function"?g(A):typeof g=="string"?{message:g}:g;return typeof I=="string"?{message:I}:I}function _C(g,A={},I){return g?Cg.create().superRefine((B,Q)=>{var C,E;const i=g(B);if(i instanceof Promise)return i.then(o=>{var h,s;if(!o){const R=zC(A,B),N=(s=(h=R.fatal)!==null&&h!==void 0?h:I)!==null&&s!==void 0?s:!0;Q.addIssue({code:"custom",...R,fatal:N})}});if(!i){const o=zC(A,B),h=(E=(C=o.fatal)!==null&&C!==void 0?C:I)!==null&&E!==void 0?E:!0;Q.addIssue({code:"custom",...o,fatal:h})}}):Cg.create()}const Aa={object:YA.lazycreate};var _;(function(g){g.ZodString="ZodString",g.ZodNumber="ZodNumber",g.ZodNaN="ZodNaN",g.ZodBigInt="ZodBigInt",g.ZodBoolean="ZodBoolean",g.ZodDate="ZodDate",g.ZodSymbol="ZodSymbol",g.ZodUndefined="ZodUndefined",g.ZodNull="ZodNull",g.ZodAny="ZodAny",g.ZodUnknown="ZodUnknown",g.ZodNever="ZodNever",g.ZodVoid="ZodVoid",g.ZodArray="ZodArray",g.ZodObject="ZodObject",g.ZodUnion="ZodUnion",g.ZodDiscriminatedUnion="ZodDiscriminatedUnion",g.ZodIntersection="ZodIntersection",g.ZodTuple="ZodTuple",g.ZodRecord="ZodRecord",g.ZodMap="ZodMap",g.ZodSet="ZodSet",g.ZodFunction="ZodFunction",g.ZodLazy="ZodLazy",g.ZodLiteral="ZodLiteral",g.ZodEnum="ZodEnum",g.ZodEffects="ZodEffects",g.ZodNativeEnum="ZodNativeEnum",g.ZodOptional="ZodOptional",g.ZodNullable="ZodNullable",g.ZodDefault="ZodDefault",g.ZodCatch="ZodCatch",g.ZodPromise="ZodPromise",g.ZodBranded="ZodBranded",g.ZodPipeline="ZodPipeline",g.ZodReadonly="ZodReadonly"})(_||(_={}));const Ia=(g,A={message:`Input not instance of ${g.name}`})=>_C(I=>I instanceof g,A),$C=iI.create,AE=cI.create,ga=KB.create,Ba=LI.create,IE=pg.create,Qa=TI.create,Ca=JB.create,Ea=Wg.create,ia=mg.create,Da=Cg.create,oa=xI.create,aa=NI.create,sa=rB.create,ya=DI.create,ha=YA.create,Ga=YA.strictCreate,Fa=Tg.create,wa=YB.create,Sa=xg.create,Ra=GI.create,Na=Zg.create,Ua=nB.create,ka=ZI.create,ta=ig.create,ca=bg.create,La=ug.create,Ja=JI.create,ra=Pg.create,Ya=Dg.create,gE=oI.create,na=FI.create,Ka=rI.create,Ma=oI.createWithPreprocess,Ha=Xg.create;var k=Object.freeze({__proto__:null,defaultErrorMap:Bg,setErrorMap:Ko,getErrorMap:tB,makeIssue:cB,EMPTY_PATH:Mo,addIssueToContext:T,ParseStatus:bA,INVALID:AA,DIRTY:Qg,OK:uA,isAborted:NQ,isDirty:UQ,isValid:mI,isAsync:dg,get util(){return yA},get objectUtil(){return RQ},ZodParsedType:Z,getParsedType:RI,ZodType:oA,datetimeRegex:vC,ZodString:iI,ZodNumber:cI,ZodBigInt:LI,ZodBoolean:pg,ZodDate:TI,ZodSymbol:JB,ZodUndefined:Wg,ZodNull:mg,ZodAny:Cg,ZodUnknown:xI,ZodNever:NI,ZodVoid:rB,ZodArray:DI,ZodObject:YA,ZodUnion:Tg,ZodDiscriminatedUnion:YB,ZodIntersection:xg,ZodTuple:GI,ZodRecord:Zg,ZodMap:nB,ZodSet:ZI,ZodFunction:ig,ZodLazy:bg,ZodLiteral:ug,ZodEnum:JI,ZodNativeEnum:Pg,ZodPromise:Dg,ZodEffects:oI,ZodTransformer:oI,ZodOptional:FI,ZodNullable:rI,ZodDefault:Og,ZodCatch:Vg,ZodNaN:KB,BRAND:$o,ZodBranded:cQ,ZodPipeline:Xg,ZodReadonly:vg,custom:_C,Schema:oA,ZodSchema:oA,late:Aa,get ZodFirstPartyTypeKind(){return _},coerce:{string:g=>iI.create({...g,coerce:!0}),number:g=>cI.create({...g,coerce:!0}),boolean:g=>pg.create({...g,coerce:!0}),bigint:g=>LI.create({...g,coerce:!0}),date:g=>TI.create({...g,coerce:!0})},any:Da,array:ya,bigint:Ba,boolean:IE,date:Qa,discriminatedUnion:wa,effect:gE,enum:Ja,function:ta,instanceof:Ia,intersection:Sa,lazy:ca,literal:La,map:Ua,nan:ga,nativeEnum:ra,never:aa,null:ia,nullable:Ka,number:AE,object:ha,oboolean:()=>IE().optional(),onumber:()=>AE().optional(),optional:na,ostring:()=>$C().optional(),pipeline:Ha,preprocess:Ma,promise:Ya,record:Na,set:ka,strictObject:Ga,string:$C,symbol:Ca,transformer:gE,tuple:Ra,undefined:Ea,union:Fa,unknown:oa,void:sa,NEVER:AA,ZodIssueCode:q,quotelessJson:no,ZodError:zA});const ea=k.object({multiscales:k.array(k.object({name:k.string().optional(),datasets:k.array(k.object({path:k.string(),coordinateTransformations:k.array(k.any().superRefine((g,A)=>{const I=[k.object({type:k.literal("scale"),scale:k.array(k.number()).min(2)}),k.object({type:k.literal("translation"),translation:k.array(k.number()).min(2)})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(1)})).min(1),version:k.literal("0.4").optional(),axes:k.array(k.any().superRefine((g,A)=>{const I=[k.object({name:k.string(),type:k.enum(["channel","time","space"])}),k.object({name:k.string(),type:k.any().refine(Q=>!k.enum(["space","time","channel"]).safeParse(Q).success,"Invalid input: Should NOT be valid against schema").optional()})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(2).max(5),coordinateTransformations:k.array(k.any().superRefine((g,A)=>{const I=[k.object({type:k.literal("scale"),scale:k.array(k.number()).min(2)}),k.object({type:k.literal("translation"),translation:k.array(k.number()).min(2)}),k.object({type:k.literal("identity")})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(1).optional()})).min(1).describe("The multiscale datasets for this image"),omero:k.object({channels:k.array(k.object({window:k.object({end:k.number(),max:k.number(),min:k.number(),start:k.number()}),label:k.string().optional(),family:k.string().optional(),color:k.string(),active:k.boolean().optional()})),rdefs:k.object({defaultT:k.number().optional(),defaultZ:k.number().optional(),color:k.enum(["color","greyscale"]).optional(),projection:k.string().optional()}).optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),qa=k.object({plate:k.object({acquisitions:k.array(k.object({id:k.number().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:k.number().int().gt(0).describe("The maximum number of fields of view for the acquisition").optional(),name:k.string().describe("The name of the acquisition").optional(),description:k.string().describe("The description of the acquisition").optional(),starttime:k.number().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:k.number().int().gte(0).describe("The end timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional()})).describe("The acquisitions for this plate").optional(),version:k.literal("0.4").describe("The version of the specification").optional(),field_count:k.number().int().gt(0).describe("The maximum number of fields per view across all wells").optional(),name:k.string().describe("The name of the plate").optional(),columns:k.array(k.object({name:k.string().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The column name")})).min(1).describe("The columns of the plate"),rows:k.array(k.object({name:k.string().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The row name")})).min(1).describe("The rows of the plate"),wells:k.array(k.object({path:k.string().regex(new RegExp("^[A-Za-z0-9]+/[A-Za-z0-9]+$")).describe("The path to the well subgroup"),rowIndex:k.number().int().gte(0).describe("The index of the well in the rows list"),columnIndex:k.number().int().gte(0).describe("The index of the well in the columns list")})).min(1).describe("The wells of the plate")}).optional()}).describe("JSON from OME-NGFF .zattrs"),da=k.object({well:k.object({images:k.array(k.object({acquisition:k.number().int().describe("A unique identifier within the context of the plate").optional(),path:k.string().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The path for this field of view subgroup")})).min(1).describe("The fields of view for this well"),version:k.literal("0.4").describe("The version of the specification").optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),fa=k.object({ome:k.object({multiscales:k.array(k.object({name:k.string().optional(),datasets:k.array(k.object({path:k.string(),coordinateTransformations:k.array(k.any().superRefine((g,A)=>{const I=[k.object({type:k.literal("scale"),scale:k.array(k.number()).min(2)}),k.object({type:k.literal("translation"),translation:k.array(k.number()).min(2)})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(1)})).min(1),axes:k.array(k.any().superRefine((g,A)=>{const I=[k.object({name:k.string(),type:k.enum(["channel","time","space"])}),k.object({name:k.string(),type:k.any().refine(Q=>!k.enum(["space","time","channel"]).safeParse(Q).success,"Invalid input: Should NOT be valid against schema").optional()})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(2).max(5),coordinateTransformations:k.array(k.any().superRefine((g,A)=>{const I=[k.object({type:k.literal("scale"),scale:k.array(k.number()).min(2)}),k.object({type:k.literal("translation"),translation:k.array(k.number()).min(2)}),k.object({type:k.literal("identity")})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(1).optional()})).min(1).describe("The multiscale datasets for this image"),omero:k.object({channels:k.array(k.object({window:k.object({end:k.number(),max:k.number(),min:k.number(),start:k.number()}).optional(),label:k.string().optional(),family:k.string().optional(),color:k.string().optional(),active:k.boolean().optional()})),rdefs:k.object({defaultT:k.number().optional(),defaultZ:k.number().optional(),color:k.enum(["color","greyscale"]).optional(),projection:k.string().optional()}).optional()}).optional(),version:k.literal("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("The zarr.json attributes key"),la=k.object({ome:k.object({plate:k.object({acquisitions:k.array(k.object({id:k.number().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:k.number().int().gt(0).describe("The maximum number of fields of view for the acquisition").optional(),name:k.string().describe("The name of the acquisition").optional(),description:k.string().describe("The description of the acquisition").optional(),starttime:k.number().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:k.number().int().gte(0).describe("The end timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional()})).describe("The acquisitions for this plate").optional(),field_count:k.number().int().gt(0).describe("The maximum number of fields per view across all wells").optional(),name:k.string().describe("The name of the plate").optional(),columns:k.array(k.object({name:k.string().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The column name")})).min(1).describe("The columns of the plate"),rows:k.array(k.object({name:k.string().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The row name")})).min(1).describe("The rows of the plate"),wells:k.array(k.object({path:k.string().regex(new RegExp("^[A-Za-z0-9]+/[A-Za-z0-9]+$")).describe("The path to the well subgroup"),rowIndex:k.number().int().gte(0).describe("The index of the well in the rows list"),columnIndex:k.number().int().gte(0).describe("The index of the well in the columns list")})).min(1).describe("The wells of the plate")}),version:k.literal("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("The zarr.json attributes key"),pa=k.object({ome:k.object({well:k.object({images:k.array(k.object({acquisition:k.number().int().describe("A unique identifier within the context of the plate").optional(),path:k.string().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The path for this field of view subgroup")})).min(1).describe("The fields of view for this well")}),version:k.literal("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("JSON from OME-Zarr zarr.json"),Wa=["0.4","0.5"],ma=new Set(Wa);function Ta(g){if(!("ome"in g)||!(g.ome instanceof Object))return;const A=g.ome;if("version"in A&&typeof A.version=="string"&&ma.has(A.version))return A.version}function LQ(g){const A=Ta(g);return A===void 0?"0.4":A}function og(g){if(g!==void 0)switch(g){case"0.4":return"v2";case"0.5":return"v3"}}function BE(g,A){const I={...g};return delete I[A],I}async function xa(g,A){const I=new II(new Hg(g)),B=og(A),Q=await eg(I,B);try{return Za(Q.attrs)}catch{throw Error(`Failed to parse OME-Zarr plate:
3891
3891
  ${JSON.stringify(Q.attrs)}`)}}function Za(g){switch(LQ(g)){case"0.5":return{...la.parse(g).ome,originalVersion:"0.5"};case"0.4":return{...ba(qa.parse(g)).ome,originalVersion:"0.4"}}}function ba(g){if(g.plate===void 0)throw new Error("Plate metadata is missing in OME-Zarr v0.4 plate");return{ome:{plate:BE(g.plate,"version"),version:"0.5"}}}function ua(g){if(g.well===void 0)throw new Error("Well metadata is missing in OME-Zarr v0.4 well");return{ome:{well:BE(g.well,"version"),version:"0.5"}}}function Pa(g){switch(LQ(g)){case"0.5":return{...pa.parse(g).ome,originalVersion:"0.5"};case"0.4":return{...ua(da.parse(g)).ome,originalVersion:"0.4"}}}async function Oa(g,A,I){const B=new II(new Hg(g+"/"+A)),Q=og(I),C=await eg(B,Q);try{return Pa(C.attrs)}catch{throw Error(`Failed to parse OME-Zarr well:
3892
3892
  ${JSON.stringify(C.attrs)}`)}}async function Va(g){const A=og(g.version),I=await eg(g.location,A);return JQ(I.attrs).omero?.channels??[]}async function Xa(g){const A=og(g.version),I=await eg(g.location,A);return JQ(I.attrs).omero?.rdefs}function va(g){return{ome:{multiscales:g.multiscales,omero:g.omero,version:"0.5"}}}function ja(g){switch(LQ(g)){case"0.5":return{...fa.parse(g).ome,originalVersion:"0.5"};case"0.4":return{...va(ea.parse(g)).ome,originalVersion:"0.4"}}}function JQ(g){try{return ja(g)}catch{throw Error(`Failed to parse OME-Zarr image:
3893
- ${JSON.stringify(g)}`)}}class za{location;version;fetchOptions;constructor(A,I,B){if(typeof A=="string"){const Q=typeof I=="string"?I:void 0,C=typeof I=="object"?I:B;this.location=new II(new Hg(A,C)),this.version=Q,this.fetchOptions=C}else{const Q=typeof I=="string"?I:void 0,C=typeof B=="string"?B:void 0;this.location=new II(new SQ(A),C),this.version=Q,this.fetchOptions=void 0}}async open(){let A=og(this.version);const I=await eg(this.location,A),B=JQ(I.attrs),Q=B.multiscales;if(Q.length!==1)throw new Error(`Exactly one multiscale image is supported. Found ${Q.length} images.`);const C=Q[0];if(C.datasets.length===0)throw new Error("No datasets found in the multiscale image.");A||(A=og(B.originalVersion));const E=C.datasets.map(s=>ho(this.location,s.path,A,this.fetchOptions)),i=await Promise.all(E.map(s=>yo(s))),o=i[0].shape,h=C.axes;if(h.length!==o.length)throw new Error(`Mismatch between number of axes (${h.length}) and array shape (${o.length})`);return new Lo({metadata:C,arrays:i,arrayParams:E})}}const QE=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function MB(g){Is(g);const A={x:g.prefetch.x,y:g.prefetch.y,z:g.prefetch.z??0,t:g.prefetch.t??0},I=Object.freeze(QE.reduce((C,E)=>{const i=g.priorityOrder.indexOf(E);return C[E]=i,C},{})),B={min:g.lod?.min??0,max:g.lod?.max??Number.MAX_SAFE_INTEGER,bias:g.lod?.bias??.5},Q={profile:g.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...g.priorityOrder]),priorityMap:I,lod:B};return Object.freeze(Q)}function _a(g={}){return MB(rQ({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},g))}function $a(g={}){return MB(rQ({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"]},g))}function As(g={}){return MB(rQ({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},g))}function Is(g){for(const[B,Q]of Object.entries(g.prefetch))if(Q!==void 0&&Q<0)throw new Error(`prefetch.${B} must be a non-negative number`);const A=g.lod;if(A?.min!==void 0&&A?.max!==void 0&&A.min>A.max)throw new Error("lod.min must be <= lod.max");const I=g.priorityOrder;if(I.length!==QE.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function rQ(g,A={}){return{profile:A.profile??g.profile,prefetch:{...g.prefetch,...A.prefetch??{}},lod:{...g.lod,...A.lod??{}},priorityOrder:A.priorityOrder??g.priorityOrder}}class gs{radius;phi;theta;constructor(A,I,B){this.radius=A,this.phi=I,this.theta=B}toVec3(){const A=Math.cos(this.theta);return NA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}class Bs extends Ag{atlas_;constructor(A,I){super(),this.programName="points",this.atlas_=I,A.forEach(C=>{const E=C.markerIndex;if(E<0||E>=this.atlas_.depth)throw new Error(`Markers must be in the range [0, ${this.atlas_.depth-1}] (number of markers in atlas)`)});const B=A.flatMap(C=>[C.position[0],C.position[1],C.position[2],C.color.r,C.color.g,C.color.b,C.color.a,C.size,C.markerIndex]),Q=new $I(B,[],"points");Q.addAttribute({type:"position",itemSize:3,offset:0}),Q.addAttribute({type:"color",itemSize:4,offset:Q.strideBytes}),Q.addAttribute({type:"size",itemSize:1,offset:Q.strideBytes}),Q.addAttribute({type:"marker",itemSize:1,offset:Q.strideBytes}),this.geometry=Q,this.setTexture(0,this.atlas_)}get type(){return"Points"}}var YQ=(()=>{for(var g=new Uint8Array(128),A=0;A<64;A++)g[A<26?A+65:A<52?A+71:A<62?A-4:A*4-205]=A;return I=>{for(var B=I.length,Q=new Uint8Array((B-(I[B-1]=="=")-(I[B-2]=="="))*3/4|0),C=0,E=0;C<B;){var i=g[I.charCodeAt(C++)],o=g[I.charCodeAt(C++)],h=g[I.charCodeAt(C++)],s=g[I.charCodeAt(C++)];Q[E++]=i<<2|o>>4,Q[E++]=o<<4|h>>2,Q[E++]=h<<6|s}return Q}})(),Qs=(typeof document<"u"&&document.currentScript&&document.currentScript.src,function(g={}){var A=g,I,B;A.ready=new Promise((a,G)=>{I=a,B=G});var Q=Object.assign({},A),C="./this.program",E=A.print||console.log.bind(console),i=A.printErr||console.error.bind(console);Object.assign(A,Q),Q=null,A.thisProgram&&(C=A.thisProgram);var o;A.wasmBinary&&(o=A.wasmBinary),typeof WebAssembly!="object"&&$("no native wasm support detected");var h,s=!1,R,N,r,M,e,n,f,V;function m(){var a=h.buffer;A.HEAP8=R=new Int8Array(a),A.HEAP16=r=new Int16Array(a),A.HEAPU8=N=new Uint8Array(a),A.HEAPU16=M=new Uint16Array(a),A.HEAP32=e=new Int32Array(a),A.HEAPU32=n=new Uint32Array(a),A.HEAPF32=f=new Float32Array(a),A.HEAPF64=V=new Float64Array(a)}var b=[],u=[],W=[];function gA(){var a=A.preRun.shift();b.unshift(a)}var O=0,x=null;function $(a){throw A.onAbort?.(a),a="Aborted("+a+")",i(a),s=!0,a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info."),B(a),a}var IA=a=>a.startsWith("data:application/octet-stream;base64,"),wA=a=>a.startsWith("file://"),kA;if(kA="blosc_codec.wasm",!IA(kA)){var CA=kA;kA=A.locateFile?A.locateFile(CA,""):""+CA}function HA(a){return Promise.resolve().then(()=>{if(a==kA&&o)var G=new Uint8Array(o);else throw"both async and sync fetching of the wasm failed";return G})}function tA(a,G,S){return HA(a).then(L=>WebAssembly.instantiate(L,G)).then(L=>L).then(S,L=>{i(`failed to asynchronously prepare wasm: ${L}`),$(L)})}function UA(a,G){var S=kA;return o||typeof WebAssembly.instantiateStreaming!="function"||IA(S)||wA(S)||typeof fetch!="function"?tA(S,a,G):fetch(S,{credentials:"same-origin"}).then(L=>WebAssembly.instantiateStreaming(L,a).then(G,function(D){return i(`wasm streaming compile failed: ${D}`),i("falling back to ArrayBuffer instantiation"),tA(S,a,G)}))}var nA=a=>{for(;0<a.length;)a.shift()(A)};function cA(a){this.H=a-24,this.N=function(G){n[this.H+4>>2]=G},this.M=function(G){n[this.H+8>>2]=G},this.I=function(G,S){this.J(),this.N(G),this.M(S)},this.J=function(){n[this.H+16>>2]=0}}var KA=0,GA,sA=a=>{for(var G="";N[a];)G+=GA[N[a++]];return G},FA={},iA={},QA={},RA,VA=a=>{throw new RA(a)},XA,WA=(a,G)=>{function S(t){if(t=G(t),t.length!==L.length)throw new XA("Mismatched type converter count");for(var U=0;U<L.length;++U)SA(L[U],t[U])}var L=[];L.forEach(function(t){QA[t]=a});var D=Array(a.length),y=[],w=0;a.forEach((t,U)=>{iA.hasOwnProperty(t)?D[U]=iA[t]:(y.push(t),FA.hasOwnProperty(t)||(FA[t]=[]),FA[t].push(()=>{D[U]=iA[t],++w,w===y.length&&S(D)}))}),y.length===0&&S(D)};function dA(a,G,S={}){var L=G.name;if(!a)throw new RA(`type "${L}" must have a positive integer typeid pointer`);if(iA.hasOwnProperty(a)){if(S.P)return;throw new RA(`Cannot register type '${L}' twice`)}iA[a]=G,delete QA[a],FA.hasOwnProperty(a)&&(G=FA[a],delete FA[a],G.forEach(D=>D()))}function SA(a,G,S={}){if(!("argPackAdvance"in G))throw new TypeError("registerType registeredInstance requires argPackAdvance");dA(a,G,S)}function eA(){this.F=[void 0],this.K=[]}var JA=new eA,AI=a=>{a>=JA.H&&--JA.get(a).L===0&&JA.J(a)},Gg=a=>{switch(a){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return JA.I({L:1,value:a})}};function KI(a){return this.fromWireType(e[a>>2])}var bI=(a,G)=>{switch(G){case 4:return function(S){return this.fromWireType(f[S>>2])};case 8:return function(S){return this.fromWireType(V[S>>3])};default:throw new TypeError(`invalid float width (${G}): ${a}`)}},MI=(a,G)=>Object.defineProperty(G,"name",{value:a}),Fg=a=>{for(;a.length;){var G=a.pop();a.pop()(G)}};function wg(a){for(var G=1;G<a.length;++G)if(a[G]!==null&&a[G].G===void 0)return!0;return!1}function AB(a){var G=Function;if(!(G instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof G} which is not a function`);var S=MI(G.name||"unknownFunctionName",function(){});return S.prototype=G.prototype,S=new S,a=G.apply(S,a),a instanceof Object?a:S}var IB=(a,G)=>{if(A[a].C===void 0){var S=A[a];A[a]=function(){if(!A[a].C.hasOwnProperty(arguments.length))throw new RA(`Function '${G}' called with an invalid number of arguments (${arguments.length}) - expects one of (${A[a].C})!`);return A[a].C[arguments.length].apply(this,arguments)},A[a].C=[],A[a].C[S.O]=S}},uI=(a,G,S)=>{if(A.hasOwnProperty(a)){if(S===void 0||A[a].C!==void 0&&A[a].C[S]!==void 0)throw new RA(`Cannot register public name '${a}' twice`);if(IB(a,a),A.hasOwnProperty(S))throw new RA(`Cannot register multiple overloads of a function with the same number of arguments (${S})!`);A[a].C[S]=G}else A[a]=G,S!==void 0&&(A[a].S=S)},PI=(a,G)=>{for(var S=[],L=0;L<a;L++)S.push(n[G+4*L>>2]);return S},OI,Sg=(a,G)=>{var S=[];return function(){if(S.length=0,Object.assign(S,arguments),a.includes("j")){var L=A["dynCall_"+a];L=S&&S.length?L.apply(null,[G].concat(S)):L.call(null,G)}else L=OI.get(G).apply(null,S);return L}},Rg=(a,G)=>{a=sA(a);var S=a.includes("j")?Sg(a,G):OI.get(G);if(typeof S!="function")throw new RA(`unknown function pointer with signature ${a}: ${G}`);return S},VI,XI=a=>{a=p(a);var G=sA(a);return Y(a),G},gB=(a,G)=>{function S(y){D[y]||iA[y]||(QA[y]?QA[y].forEach(S):(L.push(y),D[y]=!0))}var L=[],D={};throw G.forEach(S),new VI(`${a}: `+L.map(XI).join([", "]))},BB=a=>{a=a.trim();const G=a.indexOf("(");return G!==-1?a.substr(0,G):a},Ng=(a,G,S)=>{switch(G){case 1:return S?L=>R[L>>0]:L=>N[L>>0];case 2:return S?L=>r[L>>1]:L=>M[L>>1];case 4:return S?L=>e[L>>2]:L=>n[L>>2];default:throw new TypeError(`invalid integer width (${G}): ${a}`)}};function vI(a){return this.fromWireType(n[a>>2])}for(var HI=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,jI=(a,G,S)=>{var L=G+S;for(S=G;a[S]&&!(S>=L);)++S;if(16<S-G&&a.buffer&&HI)return HI.decode(a.subarray(G,S));for(L="";G<S;){var D=a[G++];if(D&128){var y=a[G++]&63;if((D&224)==192)L+=String.fromCharCode((D&31)<<6|y);else{var w=a[G++]&63;D=(D&240)==224?(D&15)<<12|y<<6|w:(D&7)<<18|y<<12|w<<6|a[G++]&63,65536>D?L+=String.fromCharCode(D):(D-=65536,L+=String.fromCharCode(55296|D>>10,56320|D&1023))}}else L+=String.fromCharCode(D)}return L},Ug=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,QB=(a,G)=>{for(var S=a>>1,L=S+G/2;!(S>=L)&&M[S];)++S;if(S<<=1,32<S-a&&Ug)return Ug.decode(N.subarray(a,S));for(S="",L=0;!(L>=G/2);++L){var D=r[a+2*L>>1];if(D==0)break;S+=String.fromCharCode(D)}return S},CB=(a,G,S)=>{if(S??=2147483647,2>S)return 0;S-=2;var L=G;S=S<2*a.length?S/2:a.length;for(var D=0;D<S;++D)r[G>>1]=a.charCodeAt(D),G+=2;return r[G>>1]=0,G-L},EB=a=>2*a.length,kg=(a,G)=>{for(var S=0,L="";!(S>=G/4);){var D=e[a+4*S>>2];if(D==0)break;++S,65536<=D?(D-=65536,L+=String.fromCharCode(55296|D>>10,56320|D&1023)):L+=String.fromCharCode(D)}return L},eI=(a,G,S)=>{if(S??=2147483647,4>S)return 0;var L=G;S=L+S-4;for(var D=0;D<a.length;++D){var y=a.charCodeAt(D);if(55296<=y&&57343>=y){var w=a.charCodeAt(++D);y=65536+((y&1023)<<10)|w&1023}if(e[G>>2]=y,G+=4,G+4>S)break}return e[G>>2]=0,G-L},zI=a=>{for(var G=0,S=0;S<a.length;++S){var L=a.charCodeAt(S);55296<=L&&57343>=L&&++S,G+=4}return G},PA={},sI=()=>{if(!OA){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"},G;for(G in PA)PA[G]===void 0?delete a[G]:a[G]=PA[G];var S=[];for(G in a)S.push(`${G}=${a[G]}`);OA=S}return OA},OA,MA=[null,[],[]],yI=Array(256),fA=0;256>fA;++fA)yI[fA]=String.fromCharCode(fA);GA=yI,RA=A.BindingError=class extends Error{constructor(a){super(a),this.name="BindingError"}},XA=A.InternalError=class extends Error{constructor(a){super(a),this.name="InternalError"}},Object.assign(eA.prototype,{get(a){return this.F[a]},has(a){return this.F[a]!==void 0},I(a){var G=this.K.pop()||this.F.length;return this.F[G]=a,G},J(a){this.F[a]=void 0,this.K.push(a)}}),JA.F.push({value:void 0},{value:null},{value:!0},{value:!1}),JA.H=JA.F.length,A.count_emval_handles=()=>{for(var a=0,G=JA.H;G<JA.F.length;++G)JA.F[G]!==void 0&&++a;return a},VI=A.UnboundTypeError=((a,G)=>{var S=MI(G,function(L){this.name=G,this.message=L,L=Error(L).stack,L!==void 0&&(this.stack=this.toString()+`
3893
+ ${JSON.stringify(g)}`)}}class za{location;version;constructor(A,I,B){this.location=typeof A=="string"?new II(new Hg(A)):new II(new SQ(A),B),this.version=I}async open(){let A=og(this.version);const I=await eg(this.location,A),B=JQ(I.attrs),Q=B.multiscales;if(Q.length!==1)throw new Error(`Exactly one multiscale image is supported. Found ${Q.length} images.`);const C=Q[0];if(C.datasets.length===0)throw new Error("No datasets found in the multiscale image.");A||(A=og(B.originalVersion));const E=C.datasets.map(s=>ho(this.location,s.path,A)),i=await Promise.all(E.map(s=>yo(s))),o=i[0].shape,h=C.axes;if(h.length!==o.length)throw new Error(`Mismatch between number of axes (${h.length}) and array shape (${o.length})`);return new Lo({metadata:C,arrays:i,arrayParams:E})}}const QE=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function MB(g){Is(g);const A={x:g.prefetch.x,y:g.prefetch.y,z:g.prefetch.z??0,t:g.prefetch.t??0},I=Object.freeze(QE.reduce((C,E)=>{const i=g.priorityOrder.indexOf(E);return C[E]=i,C},{})),B={min:g.lod?.min??0,max:g.lod?.max??Number.MAX_SAFE_INTEGER,bias:g.lod?.bias??.5},Q={profile:g.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...g.priorityOrder]),priorityMap:I,lod:B};return Object.freeze(Q)}function _a(g={}){return MB(rQ({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},g))}function $a(g={}){return MB(rQ({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"]},g))}function As(g={}){return MB(rQ({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},g))}function Is(g){for(const[B,Q]of Object.entries(g.prefetch))if(Q!==void 0&&Q<0)throw new Error(`prefetch.${B} must be a non-negative number`);const A=g.lod;if(A?.min!==void 0&&A?.max!==void 0&&A.min>A.max)throw new Error("lod.min must be <= lod.max");const I=g.priorityOrder;if(I.length!==QE.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function rQ(g,A={}){return{profile:A.profile??g.profile,prefetch:{...g.prefetch,...A.prefetch??{}},lod:{...g.lod,...A.lod??{}},priorityOrder:A.priorityOrder??g.priorityOrder}}class gs{radius;phi;theta;constructor(A,I,B){this.radius=A,this.phi=I,this.theta=B}toVec3(){const A=Math.cos(this.theta);return NA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}class Bs extends Ag{atlas_;constructor(A,I){super(),this.programName="points",this.atlas_=I,A.forEach(C=>{const E=C.markerIndex;if(E<0||E>=this.atlas_.depth)throw new Error(`Markers must be in the range [0, ${this.atlas_.depth-1}] (number of markers in atlas)`)});const B=A.flatMap(C=>[C.position[0],C.position[1],C.position[2],C.color.r,C.color.g,C.color.b,C.color.a,C.size,C.markerIndex]),Q=new $I(B,[],"points");Q.addAttribute({type:"position",itemSize:3,offset:0}),Q.addAttribute({type:"color",itemSize:4,offset:Q.strideBytes}),Q.addAttribute({type:"size",itemSize:1,offset:Q.strideBytes}),Q.addAttribute({type:"marker",itemSize:1,offset:Q.strideBytes}),this.geometry=Q,this.setTexture(0,this.atlas_)}get type(){return"Points"}}var YQ=(()=>{for(var g=new Uint8Array(128),A=0;A<64;A++)g[A<26?A+65:A<52?A+71:A<62?A-4:A*4-205]=A;return I=>{for(var B=I.length,Q=new Uint8Array((B-(I[B-1]=="=")-(I[B-2]=="="))*3/4|0),C=0,E=0;C<B;){var i=g[I.charCodeAt(C++)],o=g[I.charCodeAt(C++)],h=g[I.charCodeAt(C++)],s=g[I.charCodeAt(C++)];Q[E++]=i<<2|o>>4,Q[E++]=o<<4|h>>2,Q[E++]=h<<6|s}return Q}})(),Qs=(typeof document<"u"&&document.currentScript&&document.currentScript.src,function(g={}){var A=g,I,B;A.ready=new Promise((a,G)=>{I=a,B=G});var Q=Object.assign({},A),C="./this.program",E=A.print||console.log.bind(console),i=A.printErr||console.error.bind(console);Object.assign(A,Q),Q=null,A.thisProgram&&(C=A.thisProgram);var o;A.wasmBinary&&(o=A.wasmBinary),typeof WebAssembly!="object"&&$("no native wasm support detected");var h,s=!1,R,N,r,M,e,n,f,V;function m(){var a=h.buffer;A.HEAP8=R=new Int8Array(a),A.HEAP16=r=new Int16Array(a),A.HEAPU8=N=new Uint8Array(a),A.HEAPU16=M=new Uint16Array(a),A.HEAP32=e=new Int32Array(a),A.HEAPU32=n=new Uint32Array(a),A.HEAPF32=f=new Float32Array(a),A.HEAPF64=V=new Float64Array(a)}var b=[],u=[],W=[];function gA(){var a=A.preRun.shift();b.unshift(a)}var O=0,x=null;function $(a){throw A.onAbort?.(a),a="Aborted("+a+")",i(a),s=!0,a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info."),B(a),a}var IA=a=>a.startsWith("data:application/octet-stream;base64,"),wA=a=>a.startsWith("file://"),kA;if(kA="blosc_codec.wasm",!IA(kA)){var CA=kA;kA=A.locateFile?A.locateFile(CA,""):""+CA}function HA(a){return Promise.resolve().then(()=>{if(a==kA&&o)var G=new Uint8Array(o);else throw"both async and sync fetching of the wasm failed";return G})}function tA(a,G,S){return HA(a).then(L=>WebAssembly.instantiate(L,G)).then(L=>L).then(S,L=>{i(`failed to asynchronously prepare wasm: ${L}`),$(L)})}function UA(a,G){var S=kA;return o||typeof WebAssembly.instantiateStreaming!="function"||IA(S)||wA(S)||typeof fetch!="function"?tA(S,a,G):fetch(S,{credentials:"same-origin"}).then(L=>WebAssembly.instantiateStreaming(L,a).then(G,function(D){return i(`wasm streaming compile failed: ${D}`),i("falling back to ArrayBuffer instantiation"),tA(S,a,G)}))}var nA=a=>{for(;0<a.length;)a.shift()(A)};function cA(a){this.H=a-24,this.N=function(G){n[this.H+4>>2]=G},this.M=function(G){n[this.H+8>>2]=G},this.I=function(G,S){this.J(),this.N(G),this.M(S)},this.J=function(){n[this.H+16>>2]=0}}var KA=0,GA,sA=a=>{for(var G="";N[a];)G+=GA[N[a++]];return G},FA={},iA={},QA={},RA,VA=a=>{throw new RA(a)},XA,WA=(a,G)=>{function S(t){if(t=G(t),t.length!==L.length)throw new XA("Mismatched type converter count");for(var U=0;U<L.length;++U)SA(L[U],t[U])}var L=[];L.forEach(function(t){QA[t]=a});var D=Array(a.length),y=[],w=0;a.forEach((t,U)=>{iA.hasOwnProperty(t)?D[U]=iA[t]:(y.push(t),FA.hasOwnProperty(t)||(FA[t]=[]),FA[t].push(()=>{D[U]=iA[t],++w,w===y.length&&S(D)}))}),y.length===0&&S(D)};function dA(a,G,S={}){var L=G.name;if(!a)throw new RA(`type "${L}" must have a positive integer typeid pointer`);if(iA.hasOwnProperty(a)){if(S.P)return;throw new RA(`Cannot register type '${L}' twice`)}iA[a]=G,delete QA[a],FA.hasOwnProperty(a)&&(G=FA[a],delete FA[a],G.forEach(D=>D()))}function SA(a,G,S={}){if(!("argPackAdvance"in G))throw new TypeError("registerType registeredInstance requires argPackAdvance");dA(a,G,S)}function eA(){this.F=[void 0],this.K=[]}var JA=new eA,AI=a=>{a>=JA.H&&--JA.get(a).L===0&&JA.J(a)},Gg=a=>{switch(a){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return JA.I({L:1,value:a})}};function KI(a){return this.fromWireType(e[a>>2])}var bI=(a,G)=>{switch(G){case 4:return function(S){return this.fromWireType(f[S>>2])};case 8:return function(S){return this.fromWireType(V[S>>3])};default:throw new TypeError(`invalid float width (${G}): ${a}`)}},MI=(a,G)=>Object.defineProperty(G,"name",{value:a}),Fg=a=>{for(;a.length;){var G=a.pop();a.pop()(G)}};function wg(a){for(var G=1;G<a.length;++G)if(a[G]!==null&&a[G].G===void 0)return!0;return!1}function AB(a){var G=Function;if(!(G instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof G} which is not a function`);var S=MI(G.name||"unknownFunctionName",function(){});return S.prototype=G.prototype,S=new S,a=G.apply(S,a),a instanceof Object?a:S}var IB=(a,G)=>{if(A[a].C===void 0){var S=A[a];A[a]=function(){if(!A[a].C.hasOwnProperty(arguments.length))throw new RA(`Function '${G}' called with an invalid number of arguments (${arguments.length}) - expects one of (${A[a].C})!`);return A[a].C[arguments.length].apply(this,arguments)},A[a].C=[],A[a].C[S.O]=S}},uI=(a,G,S)=>{if(A.hasOwnProperty(a)){if(S===void 0||A[a].C!==void 0&&A[a].C[S]!==void 0)throw new RA(`Cannot register public name '${a}' twice`);if(IB(a,a),A.hasOwnProperty(S))throw new RA(`Cannot register multiple overloads of a function with the same number of arguments (${S})!`);A[a].C[S]=G}else A[a]=G,S!==void 0&&(A[a].S=S)},PI=(a,G)=>{for(var S=[],L=0;L<a;L++)S.push(n[G+4*L>>2]);return S},OI,Sg=(a,G)=>{var S=[];return function(){if(S.length=0,Object.assign(S,arguments),a.includes("j")){var L=A["dynCall_"+a];L=S&&S.length?L.apply(null,[G].concat(S)):L.call(null,G)}else L=OI.get(G).apply(null,S);return L}},Rg=(a,G)=>{a=sA(a);var S=a.includes("j")?Sg(a,G):OI.get(G);if(typeof S!="function")throw new RA(`unknown function pointer with signature ${a}: ${G}`);return S},VI,XI=a=>{a=p(a);var G=sA(a);return Y(a),G},gB=(a,G)=>{function S(y){D[y]||iA[y]||(QA[y]?QA[y].forEach(S):(L.push(y),D[y]=!0))}var L=[],D={};throw G.forEach(S),new VI(`${a}: `+L.map(XI).join([", "]))},BB=a=>{a=a.trim();const G=a.indexOf("(");return G!==-1?a.substr(0,G):a},Ng=(a,G,S)=>{switch(G){case 1:return S?L=>R[L>>0]:L=>N[L>>0];case 2:return S?L=>r[L>>1]:L=>M[L>>1];case 4:return S?L=>e[L>>2]:L=>n[L>>2];default:throw new TypeError(`invalid integer width (${G}): ${a}`)}};function vI(a){return this.fromWireType(n[a>>2])}for(var HI=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,jI=(a,G,S)=>{var L=G+S;for(S=G;a[S]&&!(S>=L);)++S;if(16<S-G&&a.buffer&&HI)return HI.decode(a.subarray(G,S));for(L="";G<S;){var D=a[G++];if(D&128){var y=a[G++]&63;if((D&224)==192)L+=String.fromCharCode((D&31)<<6|y);else{var w=a[G++]&63;D=(D&240)==224?(D&15)<<12|y<<6|w:(D&7)<<18|y<<12|w<<6|a[G++]&63,65536>D?L+=String.fromCharCode(D):(D-=65536,L+=String.fromCharCode(55296|D>>10,56320|D&1023))}}else L+=String.fromCharCode(D)}return L},Ug=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,QB=(a,G)=>{for(var S=a>>1,L=S+G/2;!(S>=L)&&M[S];)++S;if(S<<=1,32<S-a&&Ug)return Ug.decode(N.subarray(a,S));for(S="",L=0;!(L>=G/2);++L){var D=r[a+2*L>>1];if(D==0)break;S+=String.fromCharCode(D)}return S},CB=(a,G,S)=>{if(S??=2147483647,2>S)return 0;S-=2;var L=G;S=S<2*a.length?S/2:a.length;for(var D=0;D<S;++D)r[G>>1]=a.charCodeAt(D),G+=2;return r[G>>1]=0,G-L},EB=a=>2*a.length,kg=(a,G)=>{for(var S=0,L="";!(S>=G/4);){var D=e[a+4*S>>2];if(D==0)break;++S,65536<=D?(D-=65536,L+=String.fromCharCode(55296|D>>10,56320|D&1023)):L+=String.fromCharCode(D)}return L},eI=(a,G,S)=>{if(S??=2147483647,4>S)return 0;var L=G;S=L+S-4;for(var D=0;D<a.length;++D){var y=a.charCodeAt(D);if(55296<=y&&57343>=y){var w=a.charCodeAt(++D);y=65536+((y&1023)<<10)|w&1023}if(e[G>>2]=y,G+=4,G+4>S)break}return e[G>>2]=0,G-L},zI=a=>{for(var G=0,S=0;S<a.length;++S){var L=a.charCodeAt(S);55296<=L&&57343>=L&&++S,G+=4}return G},PA={},sI=()=>{if(!OA){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"},G;for(G in PA)PA[G]===void 0?delete a[G]:a[G]=PA[G];var S=[];for(G in a)S.push(`${G}=${a[G]}`);OA=S}return OA},OA,MA=[null,[],[]],yI=Array(256),fA=0;256>fA;++fA)yI[fA]=String.fromCharCode(fA);GA=yI,RA=A.BindingError=class extends Error{constructor(a){super(a),this.name="BindingError"}},XA=A.InternalError=class extends Error{constructor(a){super(a),this.name="InternalError"}},Object.assign(eA.prototype,{get(a){return this.F[a]},has(a){return this.F[a]!==void 0},I(a){var G=this.K.pop()||this.F.length;return this.F[G]=a,G},J(a){this.F[a]=void 0,this.K.push(a)}}),JA.F.push({value:void 0},{value:null},{value:!0},{value:!1}),JA.H=JA.F.length,A.count_emval_handles=()=>{for(var a=0,G=JA.H;G<JA.F.length;++G)JA.F[G]!==void 0&&++a;return a},VI=A.UnboundTypeError=((a,G)=>{var S=MI(G,function(L){this.name=G,this.message=L,L=Error(L).stack,L!==void 0&&(this.stack=this.toString()+`
3894
3894
  `+L.replace(/^Error(:[^\n]*)?\n/,""))});return S.prototype=Object.create(a.prototype),S.prototype.constructor=S,S.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},S})(Error,"UnboundTypeError");var F={p:(a,G,S)=>{throw new cA(a).I(G,S),KA=a,KA},o:()=>{},l:(a,G,S,L)=>{G=sA(G),SA(a,{name:G,fromWireType:function(D){return!!D},toWireType:function(D,y){return y?S:L},argPackAdvance:8,readValueFromPointer:function(D){return this.fromWireType(N[D])},G:null})},k:(a,G)=>{G=sA(G),SA(a,{name:G,fromWireType:S=>{if(!S)throw new RA("Cannot use deleted val. handle = "+S);var L=JA.get(S).value;return AI(S),L},toWireType:(S,L)=>Gg(L),argPackAdvance:8,readValueFromPointer:KI,G:null})},i:(a,G,S)=>{G=sA(G),SA(a,{name:G,fromWireType:L=>L,toWireType:(L,D)=>D,argPackAdvance:8,readValueFromPointer:bI(G,S),G:null})},d:(a,G,S,L,D,y,w)=>{var t=PI(G,S);a=sA(a),a=BB(a),D=Rg(L,D),uI(a,function(){gB(`Cannot call ${a} due to unbound types`,t)},G-1),WA(t,function(U){var K=a,d=a;U=[U[0],null].concat(U.slice(1));var l=D,H=U.length;if(2>H)throw new RA("argTypes array size mismatch! Must at least get return value and 'this' types!");var z=U[1]!==null&&!1,BA=wg(U),TA=U[0].name!=="void";l=[VA,l,y,Fg,U[0],U[1]];for(var aA=0;aA<H-2;++aA)l.push(U[aA+2]);if(!BA)for(aA=z?1:2;aA<U.length;++aA)U[aA].G!==null&&l.push(U[aA].G);BA=wg(U),aA=U.length;var qA="",BI="";for(H=0;H<aA-2;++H)qA+=(H!==0?", ":"")+"arg"+H,BI+=(H!==0?", ":"")+"arg"+H+"Wired";qA=`
3895
3895
  return function (${qA}) {
3896
3896
  if (arguments.length !== ${aA-2}) {