@idetik/core 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +11 -8
- package/dist/index.js +23 -26
- package/dist/index.js.map +1 -1
- package/dist/index.umd.cjs +2 -2
- package/dist/index.umd.cjs.map +1 -1
- package/dist/types/src/core/layer.d.ts +5 -2
- package/dist/types/src/core/layer.d.ts.map +1 -1
- package/dist/types/src/layers/image_layer.d.ts +2 -2
- package/dist/types/src/layers/image_layer.d.ts.map +1 -1
- package/dist/types/src/layers/label_layer.d.ts +2 -2
- package/dist/types/src/layers/label_layer.d.ts.map +1 -1
- package/dist/types/src/layers/volume_layer.d.ts +2 -2
- package/dist/types/src/layers/volume_layer.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -553,7 +553,7 @@ fn vert(@location(0) aPos: vec3f) -> @builtin(position) vec4f {
|
|
|
553
553
|
@fragment
|
|
554
554
|
fn frag() -> @location(0) vec4f {
|
|
555
555
|
return vec4f(uniforms.color, uniforms.opacity);
|
|
556
|
-
}`;class nD{colorFormat_;depthFormat_;device_;pipelines_;shaderModules_;constructor(A,I,g){this.colorFormat_=I,this.depthFormat_=g,this.device_=A,this.pipelines_=[],this.shaderModules_=[]}async compileShader(A){if(this.shaderModules_.some(a=>a.name===A))return;const I=cD(A),g=this.device_.createShaderModule({code:I});await SD(A,g);const B=yD(I),C=oD(B,{vertex:{entryPoint:"vert"},fragment:{entryPoint:"frag"}}),E=C[B.uniforms.uniforms.group];ND(E);const i=B.textures?.texture;let o;if(i){const a=C[i.group];A==="image_scalar_f32"&&RD(a),o=this.device_.createBindGroupLayout(a)}this.shaderModules_.push({name:A,module:g,defs:B,layouts:{uniforms:this.device_.createBindGroupLayout(E),textures:o}})}get(A,I){const g=this.getCachedPipeline(A);if(g)return g;const B=this.shaderModules_.find(e=>e.name===A.shaderName);if(!B)throw new Error("Shader module not found");const C=A.depthTest?"less-equal":"always",E=A.stencil?{compare:"equal",passOp:"increment-clamp"}:{},i={vertex:{module:B.module,entryPoint:"vert",buffers:[{attributes:I.attributes,arrayStride:I.geometry.strideBytes,stepMode:"vertex"}]},fragment:{module:B.module,entryPoint:"frag",targets:[{format:this.colorFormat_,blend:UD(A.blendMode)}]},primitive:{topology:A.topology,frontFace:"ccw",cullMode:A.cullMode},depthStencil:{format:this.depthFormat_,depthWriteEnabled:A.depthWrite,depthCompare:C,stencilFront:E,stencilBack:E,stencilReadMask:255,stencilWriteMask:255},multisample:{count:4}},o=[B.layouts.uniforms];B.layouts.textures&&o.push(B.layouts.textures);const a=this.device_.createPipelineLayout({bindGroupLayouts:o}),D=this.device_.createRenderPipeline({layout:a,...i}),s=Ha(B.defs.uniforms.uniforms),y={key:A,pipeline:D,uniformsView:s,uniformsData:new Float32Array(s.arrayBuffer),shaderModule:B};return this.pipelines_.push(y),y}getCachedPipeline(A){return this.pipelines_.find(I=>I.key.blendMode===A.blendMode&&I.key.cullMode===A.cullMode&&I.key.depthTest===A.depthTest&&I.key.depthWrite===A.depthWrite&&I.key.shaderName===A.shaderName&&I.key.stencil===A.stencil&&I.key.topology===A.topology&&I.key.vertexAttributesStr===A.vertexAttributesStr)}}async function SD(Q,A){const I=await A.getCompilationInfo();if(I.messages.some(g=>g.type==="error")){for(const g of I.messages)gA.error("WebGPUPipelines",`${g.type}: ${g.message}`);throw new Error(`Failed to compile WGSL shader ${Q}.wgsl`)}}function ND(Q){for(const A of Q.entries)A.buffer&&(A.buffer={...A.buffer,hasDynamicOffset:!0})}function RD(Q){for(const A of Q.entries)A.texture&&(A.texture={...A.texture,sampleType:"unfilterable-float"})}function cD(Q){switch(Q){case"image_scalar_u32":return wD;case"image_scalar_i32":return FD;case"image_scalar_f32":return eD;case"wireframe":return rD}}function UD(Q){let A,I;switch(Q){case"none":return;case"additive":A="src-alpha",I="one";break;case"multiply":A="dst",I="zero";break;case"subtractive":A="zero",I="one-minus-src";break;case"premultiplied":A="one-minus-dst-alpha",I="one";break;case"normal":A="src-alpha",I="one-minus-src-alpha";break}const g={srcFactor:A,dstFactor:I,operation:"add"};return{color:g,alpha:g}}const kD=lo(1,0,0,0,0,-1,0,0,0,0,.5,0,0,0,.5,1);async function LD(Q){if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser");const A=await navigator.gpu.requestAdapter();if(!A)throw new Error("Failed to obtain a WebGPU Adapter");const I=new JD(Q,await A.requestDevice());return await I.compileShaders(),I}class JD extends OC{bindings_;geometryBuffers_;pipelines_;texturePool_;colorFormat_;context_;depthFormat_;device_;currentProjection_=QI();currentModelView_=QI();colorMSAATexture_=null;depthStencilTexture_=null;passEncoder_=null;renderedObjectsPerFrame_=0;needsClear_=!0;currentDepthWrite_=!0;currentStencil_=!1;currentBlendMode_="none";currentLayerOpacity_=1;constructor(A,I){super(A),this.colorFormat_=navigator.gpu.getPreferredCanvasFormat(),this.depthFormat_="depth24plus-stencil8",this.device_=I;const g=A.getContext("webgpu");if(!g)throw new Error("Failed to initialize WebGPU context");g.configure({device:this.device_,format:this.colorFormat_,alphaMode:"premultiplied"}),this.context_=g,this.bindings_=new ta(I),this.geometryBuffers_=new Ga(I),this.texturePool_=new Na(I),this.pipelines_=new nD(I,this.colorFormat_,this.depthFormat_),gA.info("WebGPURenderer","WebGPU Initialized"),this.resize(this.width,this.height)}async compileShaders(){await Promise.all([this.pipelines_.compileShader("image_scalar_u32"),this.pipelines_.compileShader("image_scalar_i32"),this.pipelines_.compileShader("image_scalar_f32"),this.pipelines_.compileShader("wireframe")])}beginFrame(){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.needsClear_=!0}render(A){const I=[],g=[];for(const o of A.layers)(o.blendMode==="none"?I:g).push(o);for(const o of[...I,...g])o.update({viewport:A});if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new CI(TA(0,0),TA(this.width,this.height));if(!CI.intersects(B,C)){gA.warn("WebGPURenderer",`Viewport ${A.id} is entirely outside canvas bounds`);return}const E=A.camera.frustum,i=!CI.equals(B.floor(),C.floor());this.bindings_.clearUniformBindings(),this.updateProjection(A.camera.projectionMatrix),this.currentDepthWrite_=!0;for(const o of I)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.currentDepthWrite_=!1;for(const o of g)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.renderedObjects_=this.renderedObjectsPerFrame_}renderLayer(A,I,g,B,C){if(A.type!=="ImageLayer")throw new Error("Experimental WebGPU renderer only supports image layers");if(A.objects.length===0)return;const E=this.device_.createCommandEncoder();this.passEncoder_=this.beginRenderPass(E);const{x:i,y:o,width:a,height:D}=B.floor().toRect();this.passEncoder_.setViewport(i,o,a,D,0,1),C&&this.passEncoder_.setScissorRect(i,o,a,D),this.currentStencil_=A.hasMultipleLODs(),this.currentStencil_&&this.passEncoder_.setStencilReference(0),this.currentBlendMode_=A.blendMode,this.currentLayerOpacity_=A.opacity,A.objects.forEach((s,y)=>{g.intersectsWithBox3(s.boundingBox)&&(this.renderObject(A,y,I),this.renderedObjectsPerFrame_+=1)}),this.passEncoder_.end(),this.device_.queue.submit([E.finish()]),this.passEncoder_=null}renderObject(A,I,g){const B=A.objects[I];if(B.type!=="ImageRenderable")throw new Error("Experimental WebGPU renderer only supports image renderables");if(B.popStaleTextures().forEach(o=>{this.texturePool_.dispose(o)}),!B.programName)return;const C=this.passEncoder_,E=this.geometryBuffers_.get(B.geometry),i=this.pipelines_.get({shaderName:YD(B.textures[0]),depthWrite:this.currentDepthWrite_,depthTest:B.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"back",topology:"triangle-list",vertexAttributesStr:E.attributesKey},E);C.setPipeline(i.pipeline),this.setUniformsForObject(B,i,g),this.setTexturesForObject(B,i),C.setVertexBuffer(0,E.vertexBuffer),E.indexBuffer?(C.setIndexBuffer(E.indexBuffer,"uint32"),C.drawIndexed(B.geometry.indexData.length)):C.draw(B.geometry.vertexCount),B.wireframeEnabled&&this.renderWireframe(B,g)}renderWireframe(A,I){const g=A.wireframeGeometry;if(g.indexData.length===0)return;const B=this.passEncoder_,C=this.geometryBuffers_.get(g),E=this.pipelines_.get({shaderName:"wireframe",depthWrite:this.currentDepthWrite_,depthTest:A.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"none",topology:"line-list",vertexAttributesStr:C.attributesKey},C);B.setPipeline(E.pipeline),WI(this.currentModelView_,I.viewMatrix,A.transform.matrix),E.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:A.wireframeColor.rgb,opacity:this.currentLayerOpacity_}),this.bindings_.setUniforms(B,E),B.setVertexBuffer(0,C.vertexBuffer),C.indexBuffer&&(B.setIndexBuffer(C.indexBuffer,"uint32"),B.drawIndexed(g.indexData.length))}resize(A,I){this.colorMSAATexture_&&this.colorMSAATexture_.destroy(),this.colorMSAATexture_=this.device_.createTexture({size:{width:A,height:I},format:this.colorFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.depthStencilTexture_&&this.depthStencilTexture_.destroy(),this.depthStencilTexture_=this.device_.createTexture({size:{width:A,height:I},format:this.depthFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT})}beginRenderPass(A){const I=this.needsClear_?"clear":"load";return this.needsClear_=!1,A.beginRenderPass({colorAttachments:[{view:this.colorMSAATexture_.createView(),resolveTarget:this.context_.getCurrentTexture().createView(),loadOp:I,storeOp:"store",clearValue:{r:this.backgroundColor.r,g:this.backgroundColor.g,b:this.backgroundColor.b,a:this.backgroundColor.a}}],depthStencilAttachment:{view:this.depthStencilTexture_.createView(),depthLoadOp:I,depthStoreOp:"store",depthClearValue:1,stencilLoadOp:"clear",stencilStoreOp:"store",stencilClearValue:0}})}clear(){}setUniformsForObject(A,I,g){WI(this.currentModelView_,g.viewMatrix,A.transform.matrix);const B=A.getUniforms(),C=B.Opacity??1;I.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:B.Color,valueOffset:B.ValueOffset,valueScale:B.ValueScale,opacity:this.currentLayerOpacity_*C,zTexCoord:B.ZTexCoord}),this.bindings_.setUniforms(this.passEncoder_,I)}setTexturesForObject(A,I){if(A.textures.length>1)throw new Error("Experimental WebGPU renderer only supports single textures");this.bindings_.setTexture(this.passEncoder_,I,this.texturePool_.get(A.textures[0]))}updateProjection(A){WI(this.currentProjection_,kD,A)}get gpuTextureBytes(){return 0}get gpuTextureCount(){return 0}}function YD(Q){switch(Q.dataType){case"byte":case"unsigned_byte":case"float":return"image_scalar_f32";case"short":case"int":return"image_scalar_i32";case"unsigned_short":case"unsigned_int":return"image_scalar_u32"}}const KD=8;class MD{maxConcurrent_;pending_=[];running_=new Map;constructor(A=KD){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(B=>B.chunk===A);if(I>=0){this.pending_.splice(I,1),gA.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),gA.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 g=A.chunk.priority??Number.MAX_SAFE_INTEGER,B=I.chunk.priority??Number.MAX_SAFE_INTEGER;return g===B?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):g-B});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const B=new AbortController,C=Promise.resolve().then(()=>g(B.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&gA.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:B,promise:C})}}let ZB=0,PB=0;function HD(Q,A){Q.data&&(ZB-=Q.data.byteLength,PB-=1),Q.data=A,ZB+=A.byteLength,PB+=1}function dD(Q){Q.data&&(ZB-=Q.data.byteLength,PB-=1),Q.data=void 0}function qD(){return{cpuChunkBytes:ZB,cpuChunkCount:PB}}function PE(Q,A,I=1e-6){return Math.abs(Q-A)<=I}const VE=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function lD(Q){if(VE.some(I=>Q instanceof I))return!0;const A=VE.map(I=>I.name);return gA.debug("Chunk",`Unsupported chunk data type: ${Q}. Supported data types: ${A}`),!1}function fD(Q,A){return Math.round((A-Q.translation)/Q.scale)}function pI(Q,A,I){return Math.max(A,Math.min(I,Q))}const VB=Symbol("INTERNAL_POLICY_KEY");class pD{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const g=this.store_.dimensions,B=g.x.lods[0],C=g.y.lods[0];this.sourceMaxSquareDistance2D_=Qa(TA(B.size*B.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,g=[],B=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||(C.lod===I?g.push(C):C.lod===A&&I!==A&&B.push(C));return[...g,...B]}updateChunksForImage(A,I){const g=I.camera;if(g.type!=="OrthographicCamera")throw new Error("ChunkStoreView currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const C=g.getWorldViewRect(),E=Math.abs(C.max[0]-C.min[0]),i=I.element,o=I.getBoxRelativeTo(i).toRect().width,a=E/o,D=Math.log2(1/a);this.setLOD(D);const s=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(s)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const e=this.timeIndex(A);if(!this.store_.hasChunksAtTime(e)){gA.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const J=gE();Ca(J,C.min,C.max,.5);const[u,d]=this.getZBounds(A),W=new Cg(nA(C.min[0],C.min[1],u),nA(C.max[0],C.max[1],d));this.chunkViewStates_.forEach(jQ);const z=this.channelsOfInterest(A),m=this.fallbackLOD(),l=this.getPaddedBounds(W),P=this.currentLOD_===m?[this.currentLOD_]:[this.currentLOD_,m];for(const v of P){const EA=v===this.currentLOD_,sA=v===m;this.iterateChunksInBox(e,v,z,l,(DA,hA)=>{const yA=Cg.intersects(hA,W),mA=EA&&!yA,fA=this.computePriority(sA,EA,yA,mA,!0);fA!==null&&this.chunkViewStates_.set(DA,{visible:yA,prefetch:mA,priority:fA,orderKey:this.squareDistance2D(DA,J)})})}this.markTimeChunksForPrefetchImage(e,A,W,J),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=s,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){const g=WI(QI(),I.camera.projectionMatrix,I.camera.viewMatrix);if(!(this.policyChanged_||this.hasViewProjectionChanged(g)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const C=this.timeIndex(A);if(!this.store_.hasChunksAtTime(C)){gA.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(jQ);const E=this.channelsOfInterest(A),i=this.fallbackLOD(),o=a=>{const D=a.lod===i,s=a.lod===this.currentLOD_,y=this.computePriority(D,s,!0,!1,!0);y!==null&&this.chunkViewStates_.set(a,{visible:!0,prefetch:!1,priority:y,orderKey:0})};this.iterateAllChunksAtLod(C,this.currentLOD_,E,o),this.currentLOD_!==i&&this.iterateAllChunksAtLod(C,i,E,o),this.markTimeChunksForPrefetchVolume(C,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=g}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[g,B]of this.chunkViewStates_)if(!(!B.visible||g.lod!==A)&&(I=!0,g.state!=="loaded"))return!1;return I}get currentLOD(){return this.currentLOD_}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.chunkViewStates_.forEach(jQ)}setImageSourcePolicy(A,I){if(I!==VB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const g=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(g)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),a=Math.max(o,Math.min(i,this.policy_.lod.max)),D=pI(E,o,a);D!==this.currentLOD_&&(this.currentLOD_=D)}markTimeChunksForPrefetchImage(A,I,g,B){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),o=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let D=A+1;D<=E;++D)this.iterateChunksInBox(D,i,a,g,s=>{const y=this.squareDistance2D(s,B),e=pI(y/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),J=D-A+e;this.chunkViewStates_.set(s,{visible:!1,prefetch:!0,priority:o,orderKey:J})})}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,B=Math.min(g-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let o=A+1;o<=B;++o)this.iterateAllChunksAtLod(o,C,i,a=>{const D=o-A;this.chunkViewStates_.set(a,{visible:!1,prefetch:!0,priority:E,orderKey:D})})}computePriority(A,I,g,B,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&B?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,B=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(B.size/B.chunkSize),o=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,D=B.chunkSize*B.scale,s=C.chunkSize*C.scale,y=E?E.chunkSize*E.scale:1,e=B.translation,J=C.translation,u=E?.translation??0,d=Math.max(0,Math.floor((A.min[0]-e)/D)),W=Math.min(i,Math.ceil((A.max[0]-e)/D)),z=Math.max(0,Math.floor((A.min[1]-J)/s)),m=Math.min(o,Math.ceil((A.max[1]-J)/s)),l=E?Math.max(0,Math.floor((A.min[2]-u)/y)):0,P=E?Math.min(a,Math.ceil((A.max[2]-u)/y)):1;return d>=W||z>=m||l>=P?null:{xMin:d,xMax:W,yMin:z,yMax:m,zMin:l,zMax:P}}iterateChunksInBox(A,I,g,B,C){const E=this.chunkIndexRange(B,I);if(E)for(const i of g){const o=this.store_.getChunkGrid(I,A,i);if(o)for(let a=E.zMin;a<E.zMax;++a){const D=o[a];for(let s=E.yMin;s<E.yMax;++s){const y=D[s];for(let e=E.xMin;e<E.xMax;++e){const J=y[e];C(J,this.getChunkAabb(J))}}}}}iterateAllChunksAtLod(A,I,g,B){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const o of i)for(const a of o)B(a,this.getChunkAabb(a))}}getChunkAabb(A){return new Cg(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))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:fD(I.lods[0],A.t)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const D=I.lods[this.currentLOD_];return[D.translation,D.translation+D.size*D.scale]}const g=I.lods[this.currentLOD_],B=g.size,C=g.scale,E=g.translation,i=Math.floor((A.z-E)/C),o=g.chunkSize,a=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(B/o)-1));return[E+a*o*C,E+(a+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!LQ(this.lastViewBounds2D_.min,A.min)||!LQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!bo(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!LQ(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const I=this.store_.dimensions,g=I.x.lods[this.currentLOD_],B=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=g.chunkSize*g.scale*this.policy_.prefetch.x,i=B.chunkSize*B.scale*this.policy_.prefetch.y;let o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new Cg(nA(A.min[0]-E,A.min[1]-i,A.min[2]-o),nA(A.max[0]+E,A.max[1]+i,A.max[2]+o))}squareDistance2D(A,I){const g={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},B=g.x-I[0],C=g.y-I[1];return B*B+C*C}}function jQ(Q){Q.visible=!1,Q.prefetch=!1,Q.priority=null,Q.orderKey=null}class uD{chunks_;loader_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.loader_=A,this.dimensions_=this.loader_.getSourceDimensionMap(),this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),B=this.dimensions_.numLods;this.chunks_=new Array(B);for(let C=0;C<B;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],o=this.dimensions_.z?.lods[C],a=E.chunkSize,D=i.chunkSize,s=o?.chunkSize??1,y=Math.ceil(E.size/a),e=Math.ceil(i.size/D),J=o?Math.ceil(o.size/s):1,u=new Array(I);this.chunks_[C]=u;for(let d=0;d<I;++d){const W=new Array(g);u[d]=W;for(let z=0;z<g;++z){const m=new Array(J);W[z]=m;for(let l=0;l<J;++l){const P=o!==void 0?o.translation+l*s*o.scale:0,v=new Array(e);m[l]=v;for(let EA=0;EA<e;++EA){const sA=i.translation+EA*D*i.scale,DA=new Array(y);v[EA]=DA;for(let hA=0;hA<y;++hA){const yA=E.translation+hA*a*E.scale;DA[hA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-hA*a),y:Math.min(D,i.size-EA*D),z:Math.min(s,(o?.size??1)-l*s),c:1},rowAlignmentBytes:1,chunkIndex:{x:hA,y:EA,z:l,c:z,t:d},scale:{x:E.scale,y:i.scale,z:o?.scale??1},offset:{x:yA,y:sA,z:P}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}addView(A){const I=new pD(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,B]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,B=null,C=null;for(const a of this.views_){const D=a.chunkViewStates.get(A);D&&(D.visible&&(I=!0),D.prefetch&&(g=!0),D.priority!==null&&(B===null||D.priority<B)&&(B=D.priority,C=D.orderKey),!D.visible&&!D.prefetch&&D.priority===null&&a.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=B,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}if(A.state==="loaded"&&A.priority===null){if(A.visible||A.prefetch)throw new Error(`Chunk state inconsistency detected: priority is null but visible=${A.visible} or prefetch=${A.prefetch} for chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`);dD(A),A.state="unloaded",A.orderKey=null,gA.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const B=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!PE(B,2,.02)||!PE(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${B.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.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.scale!==1&&gA.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class mD{stores_=new Map;queue_=new MD;get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}get memoryStats(){return qD()}addView(A,I){let g=this.stores_.get(A);return g||(g=new uD(A.getLoader()),this.stores_.set(A,g)),g.addView(I)}update(){for(const[A,I]of this.stores_){const g=I.updateAndCollectChunkChanges();for(const B of g)B.priority===null?this.queue_.cancel(B):B.state==="queued"&&this.queue_.enqueue(B,C=>I.loadChunkData(B,C))}this.queue_.flush();for(const[A,I]of this.stores_)I.canDispose()&&this.stores_.delete(A)}}var sB=function(Q=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(s){s.preventDefault(),B(++A%I.children.length)},!1);function g(s){return I.appendChild(s.dom),s}function B(s){for(var y=0;y<I.children.length;y++)I.children[y].style.display=y===s?"block":"none";A=s}var C=(performance||Date).now(),E=C,i=0,o=g(new sB.Panel("FPS","#0ff","#002",Q)),a=g(new sB.Panel("MS","#0f0","#020",Q));if(self.performance&&self.performance.memory)var D=g(new sB.Panel("MB","#f08","#201",Q));return B(0),{REVISION:16,dom:I,addPanel:g,showPanel:B,begin:function(){C=(performance||Date).now()},end:function(){i++;var s=(performance||Date).now();if(a.update(s-C,200),s>=E+1e3&&(o.update(i*1e3/(s-E),100),E=s,i=0,D)){var y=performance.memory;D.update(y.usedJSHeapSize/1048576,y.jsHeapSizeLimit/1048576)}return s},update:function(){C=this.end()},domElement:I,setMode:B}};sB.Panel=function(Q,A,I,g){var B=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*g),a=E(48*i*g),D=E(3*i*g),s=E(2*i*g),y=E(3*i*g),e=E(15*i*g),J=E(74*i*g),u=E(30*i*g),d=document.createElement("canvas");d.width=o,d.height=a,d.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var W=d.getContext("2d");return W.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",W.textBaseline="top",W.fillStyle=I,W.fillRect(0,0,o,a),W.fillStyle=A,W.fillText(Q,D,s),W.fillRect(y,e,J,u),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y,e,J,u),{dom:d,update:function(z,m){B=Math.min(B,z),C=Math.max(C,z),W.fillStyle=I,W.globalAlpha=1,W.fillRect(0,0,o,e),W.fillStyle=A,W.fillText(E(z)+" "+Q+" ("+E(B)+"-"+E(C)+")",D,s),W.drawImage(d,y+i,e,J-i,u,y,e,J-i,u),W.fillRect(y+J-i,e,i,u),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y+J-i,e,i,E((1-z/m)*u))}}};function xD({scale:Q}={scale:1.5}){const A=new sB(Q);return A.showPanel(0),document.body.appendChild(A.dom),A}const zQ=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function TD(Q){return zQ.includes(Q)}class WD{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 bD{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){gA.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,zQ.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){gA.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,zQ.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!TD(A.type)){gA.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new WD(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}class ZD{id;element;camera;events;cameraControls;context_;layers_=[];constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.context_=A.context,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new bD(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:B}=I.event,C=TA(g,B);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const g of this.layers_)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.addLayer(I)}get layers(){return this.layers_}addLayer(A){this.layers_.push(A),A.onAttached(this.context_)}removeLayer(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.layers_.splice(I,1),A.onDetached(this.context_)}removeAllLayers(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[]}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),B=window.devicePixelRatio||1,C=g.left*B,E=g.top*B,i=g.height*B,o=I.x-C,a=I.y-E,D=Math.floor(o),s=Math.floor(i-a-I.height),y=Math.floor(I.width),e=Math.floor(I.height);return new CI(TA(D,s),TA(D+y,s+e))}clientToClip(A,I=0){const[g,B]=A,C=this.element.getBoundingClientRect();return nA(2*(g-C.x)/C.width-1,2*(B-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,B=A.top*I,C=A.width*I,E=A.height*I;return new CI(TA(g,B),TA(g+C,B+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){gA.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function OE(Q,A){for(const I of A){if(I.id===Q.id)throw new Error(`Duplicate viewport ID "${Q.id}". Each viewport must have a unique ID.`);if(I.element===Q.element){const g=Q.element.tagName.toLowerCase()+(Q.element.id?`#${Q.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${Q.id}" both use ${g}`)}}}function PD(Q){for(let A=0;A<Q.length;A++)OE(Q[A],Q.slice(0,A))}function vE(Q,A,I){const g=Q.map(B=>{const C=B.element??A;return{...B,element:C,id:B.id??C.id??jC("viewport"),context:I}});return PD(g),g.map(B=>new ZD(B))}class VD{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){gA.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.onChange_()});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.onChange_(),this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){gA.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){gA.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){gA.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class _Q{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;static async create(A){const I=A.renderer==="webgpu-experimental"?await LD(A.canvas):new EE(A.canvas);return new _Q(A,I)}constructor(A,I){this.canvas=A.canvas,this.renderer_=I??new EE(this.canvas),this.chunkManager_=new mD,this.context_={chunkManager:this.chunkManager_},this.viewports_=vE(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=xD());const g=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&g.push(B.element);this.sizeObserver_=new VD(g,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get memoryStats(){const A=performance.memory;return{...this.chunkManager_.memoryStats,gpuTextureBytes:this.renderer_.gpuTextureBytes,gpuTextureCount:this.renderer_.gpuTextureCount,jsHeapUsedBytes:A?.usedJSHeapSize,jsHeapLimitBytes:A?.jsHeapSizeLimit}}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=vE([A],this.canvas,this.context_);return OE(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),gA.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(gA.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),gA.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(gA.info("Idetik","Idetik runtime starting"),this.running)gA.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(gA.info("Idetik","Idetik runtime stopping"),!this.running)gA.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}}}function OD(Q,A){return{...Q,...A,headers:{...Q.headers,...A.headers}}}function XE(Q,A){const I=typeof Q=="string"?new URL(Q):Q;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function jE(Q){if(Q.status!==404){if(Q.status===200||Q.status===206)return new Uint8Array(await Q.arrayBuffer());throw new Error(`Unexpected response status ${Q.status} ${Q.statusText}`)}}class hB{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,OD(this.#I,I))}async get(A,I={}){let g=XE(this.url,A).href,B=this.#B(g,I),C=await this.#A(B);return jE(C)}async getRange(A,I,g={}){let B=XE(this.url,A),C;if("suffixLength"in I)C=await this.#Q(B,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(B,E);C=await this.#A(i)}return jE(C)}async#Q(A,I,g){if(this.#g){let D={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,D))}let B=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(B);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),o=i-I,a={...g,headers:{...g.headers,Range:`bytes=${o}-${i-1}`}};return this.#A(this.#B(A,a))}}class yB extends Error{}class Mg extends yB{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class bA extends yB{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class vD extends yB{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class XD extends yB{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class $Q extends yB{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function ag(Q){return()=>{throw new $Q(`${Q} encode`)}}class OB{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new bA("keepbits must be zero or positive")}static fromConfig(A,I){return new OB(A,I)}encode=ag("bitround");decode(A){return A}}function AC(Q){return Q instanceof ArrayBuffer||Q instanceof SharedArrayBuffer}class zE{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):AC(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,B=>B?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 IC{_data;chars;#A;constructor(A,I,g,B){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(AC(I))B&&(B=B*A),this._data=new Uint8Array(I,g,B);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 g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class tB{#A;chars;constructor(A,I,g,B){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(AC(I))B&&(B*=A),this.#A=new Int32Array(I,g,B);else{const C=I,E=new tB(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 g="";for(let B=0;B<this.chars;B++)g+=String.fromCodePoint(this.#A[I+B]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,B=this.#A.subarray(g,g+this.chars);B.fill(0);for(let C=0;C<this.chars;C++)B[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function jD(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function zD(Q,A){return new SharedArrayBuffer(Q)}function GB(Q){const A=new TextDecoder().decode(Q);try{return JSON.parse(A)}catch(I){throw new bA("Failed to decode JSON",{cause:I})}}function _E(Q,A){const I=A/2,g=A-1;let B=0;for(let C=0;C<Q.length;C+=A)for(let E=0;E<I;E+=1)B=Q[C+E],Q[C+E]=Q[C+g-E],Q[C+g-E]=B}function Hg(Q){if(Q==="v2:object")return globalThis.Array;let A=Q.match(/v2:([US])(\d+)/);if(A){let[,g,B]=A;return(g==="U"?tB:IC).bind(null,Number(B))}if(Q==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:zE}[Q];if(!I)throw new bA(`Unknown or unsupported dataType: ${Q}`);return I}function Dg(Q,A){const I=Q.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),yI(I===A.length,"Order length must match the number of dimensions.");let g=1,B=new Array(I);for(let C=A.length-1;C>=0;C--)B[A[C]]=g,g*=Q[A[C]];return B}function _D({name:Q,configuration:A}){if(Q==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(Q==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new bA(`Unknown chunk key encoding: ${Q}`)}function $E(Q){if(Q==="|O")return{dataType:"v2:object"};let A=Q.match(/^([<|>])(.*)$/);if(!A)throw new bA(`Invalid dtype: ${Q}`);let[,I,g]=A,B={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!B)throw new bA(`Unsupported or unknown dtype: ${Q}`);return I==="|"?{dataType:B}:{dataType:B,endian:I==="<"?"little":"big"}}function $D(Q){return(Q.id==="fixedscaleoffset"||Q.id==="numcodecs.fixedscaleoffset")&&typeof Q.scale=="number"&&typeof Q.offset=="number"&&(Q.astype===void 0||typeof Q.astype=="string")&&(Q.dtype===void 0||typeof Q.dtype=="string")}function As(Q,A={}){let I=[],g=$E(Q.dtype);Q.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of Q.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!$D(C))throw new bA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let o=C.astype??C.dtype;if(o!==void 0&&o!==Q.dtype){let a=$E(o).dataType;if(!gC(a,"number")&&!gC(a,"bigint"))throw new bA(`fixedscaleoffset astype must be a numeric data type, got ${o}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),Q.compressor){let{id:C,...E}=Q.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let B;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(B=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:Q.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:Q.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:Q.dimension_separator??"."}},codecs:I,fill_value:Q.fill_value,dimension_names:B,attributes:A}}function Is(Q,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function gC(Q,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return Q===A;let I=Q==="bool";if(A==="boolean")return I;let g=Q.startsWith("v2:U")||Q.startsWith("v2:S")||Q==="string";if(A==="string")return g;let B=Q==="int64"||Q==="uint64";if(A==="bigint")return B;let C=Q==="v2:object";return A==="object"?C:!g&&!B&&!I&&!C}function gs(Q){return Q?.name==="sharding_indexed"}function Ai(Q){if((Q.data_type==="uint64"||Q.data_type==="int64")&&Q.fill_value!=null)return BigInt(Q.fill_value);let A=Q.data_type==="float16"||Q.data_type==="float32"||Q.data_type==="float64";if(typeof Q.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(Q.fill_value in I)return I[Q.fill_value]}return Q.fill_value}function Ii(Q,...A){if(!A.some(I=>Q instanceof I))throw Q}function yI(Q,A=""){if(!Q)throw new Error(A)}async function gi(Q,{format:A,signal:I}){let g;if(Q instanceof ArrayBuffer)g=new Response(Q);else{let B=new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength);g=new Response(B.slice().buffer)}yI(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const Bi=Bs();function Bs(){const Q=new Uint32Array([305419896]);return new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)[0]!==18}function Qi(Q){return"BYTES_PER_ELEMENT"in Q?Q.BYTES_PER_ELEMENT:4}class vB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=Hg(I.dataType),this.#B=I.shape,this.#A=Dg(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new vB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return Bi&&this.#Q==="big"&&_E(I,Qi(this.#I)),I}computeEncodedSize(A){return A}decode(A){return Bi&&this.#Q==="big"&&_E(A,Qi(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const Ci={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},Ei={float16:2,float32:4,float64:8};function XB(Q){return Q in Ei}function BC(Q){return Q==="int64"||Q==="uint64"}function Qs(Q,A){const I=BigInt(Q),g=new ArrayBuffer(A),B=new DataView(g);if(A===2){if(typeof B.getFloat16!="function")throw new $Q("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return B.setUint16(0,Number(I)),B.getFloat16(0)}return A===4?(B.setUint32(0,Number(I)),B.getFloat32(0)):(B.setBigUint64(0,I),B.getFloat64(0))}function jB(Q,A){if(BC(Q)){if(typeof A!="number"||!Number.isInteger(A))throw new bA(`Expected an integer value for data type "${Q}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!XB(Q)&&!Number.isInteger(A))throw new bA(`Expected an integer value for data type "${Q}", got ${A}`);return A}if(!XB(Q))throw new bA(`String-encoded scalar "${A}" is not valid for non-float data type "${Q}"`);return A in Ci?Ci[A]:Qs(A,Ei[Q])}const ii=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),QC={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},CC={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function oi(Q,A,I){return Q.map(([g,B])=>({src:jB(A,g),tgt:jB(I,B)}))}function Cs(Q,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof Q=="number"&&Number.isNaN(Q))return I.tgt}else if(Q===I.src)return I.tgt}function Es(Q){if(!Number.isFinite(Q))return Q;if(Math.abs(Q-Math.trunc(Q))===.5){const A=Math.floor(Q),I=Math.ceil(Q);return A%2===0?A:I}return Math.round(Q)}function is(Q){return Math.sign(Q)*Math.floor(Math.abs(Q)+.5)}function ai(Q){switch(Q){case"nearest-even":return Es;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return is}}function EC(Q,A,I){const g=A-Q+1;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function iC(Q,A,I){const g=A-Q+1n;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class oC{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,B,C,E){this.#A=I,this.#I=Hg(A),this.#g=Di(I,A,g,B,C),this.#B=Di(A,I,g,B,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,B=A.data_type;if(!ii.has(g))throw new bA(`cast_value codec does not support array data type: ${g}`);if(!ii.has(B))throw new bA(`cast_value codec does not support encoded data type: ${B}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?oi(A.scalar_map.decode,B,g):[],i=A.scalar_map?.encode?oi(A.scalar_map.encode,g,B):[];return new oC(g,B,C,A.out_of_range,E,i)}encode=ag("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let B=0;B<I.length;B++)g[B]=this.#g(I[B]);return{data:g,shape:A.shape,stride:A.stride}}}function Di(Q,A,I,g,B){const C=XB(Q),E=BC(Q),i=XB(A),o=BC(A);let a;if(C&&i){if(I!=="nearest-even")throw new bA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=s=>s}else if(C&&!i&&!o){const s=ai(I),y=EC(...QC[A],g);a=e=>{if(!Number.isFinite(e))throw new Error(`Cannot cast ${e} to integer type without scalar_map`);return y(s(e))}}else if(C&&o){const s=ai(I),y=iC(...CC[A],g);a=e=>{if(!Number.isFinite(e))throw new Error(`Cannot cast ${e} to integer type without scalar_map`);return y(BigInt(s(e)))}}else if(!C&&!E&&i)a=s=>s;else if(E&&i)a=s=>Number(s);else if(!C&&!E&&!i&&!o)a=EC(...QC[A],g);else if(!C&&!E&&o){const s=iC(...CC[A],g);a=y=>s(BigInt(y))}else if(E&&!i&&!o){const s=EC(...QC[A],g);a=y=>s(Number(y))}else if(E&&o)a=iC(...CC[A],g);else throw new Error(`Unhandled type combination: ${Q} -> ${A}`);return B.length===0?a:s=>{const y=Cs(s,B);return y!==void 0?y:a(s)}}class aC{kind="bytes_to_bytes";static fromConfig(){return new aC}encode=ag("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const os=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function si(Q,A){const I=Q.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*Q[C+1];if(g)return;let B=I===0||A[0]===1;for(let C=1;C<I&&B;C++)B=A[C]===A[C-1]*Q[C-1];if(!B)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(Q)} stride=${JSON.stringify(A)}`)}class DC{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!os.has(I.dataType))throw new bA(`Delta codec does not support data type: ${I.dataType}`);return new DC(Hg(I.dataType))}encode(A){si(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=I[B]-I[B-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){si(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=g[B-1]+I[B];return{data:g,shape:A.shape,stride:A.stride}}}class sC{kind="bytes_to_bytes";static fromConfig(A){return new sC}encode=ag("gzip");async decode(A){const I=await gi(A,{format:"gzip"});return new Uint8Array(I)}}function as(Q,A){return yI(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),yI(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),yI(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function Ds(Q,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class zB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:B=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:a=!0}=A;let D=A.separators;D||(o?D=[", ",": "]:D=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:B,check_circular:C,allow_nan:E,indent:o,separators:D,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new zB(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:B,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;yI(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];yI(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(as),i&&o.push(Ds);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let D;o.length&&(D=(y,e)=>{let J=e;for(let u of o)J=u(y,J);return J});let s=JSON.stringify(a,D,I);return B&&(s=s.replace(/[\u007F-\uFFFF]/g,y=>{const e=`0000${y.charCodeAt(0).toString(16)}`;return`\\u${e.substring(e.length-4)}`})),new TextEncoder().encode(s)}decode(A){const{strict:I}=this.#I;yI(I,"JsonCodec does not yet support non-strict decoding.");const g=GB(A),B=g.pop();g.pop(),yI(B,"0D not implemented for JsonCodec.");const C=Dg(B,"C");return{data:g,shape:B,stride:C}}}const ss=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class hC{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!ss.has(I.dataType))throw new bA(`scale_offset codec does not support data type: ${I.dataType}`);return new hC(jB(I.dataType,A.scale??1),jB(I.dataType,A.offset??0),Hg(I.dataType))}encode=ag("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let B=0;B<I.length;B++)g[B]=I[B]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class yC{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(Hg(I.dataType))(0);yI("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new yC(A,I)}encode(A){return hs(A,this.#A)}decode(A){return ys(A,this.#A)}}function hs(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[C*g+E]=Q[E*A+C];return B}function ys(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[E*A+C]=Q[C*g+E];return B}function hi(Q){return Q instanceof zE||Q instanceof IC||Q instanceof tB?new Proxy(Q,{get(I,g){return I.get(Number(g))},set(I,g,B){return I.set(Number(g),B),!0}}):Q}function ts(Q,A){let I;return Q.data instanceof IC||Q.data instanceof tB?I=new Q.constructor(Q.data.length,Q.data.chars):I=new Q.constructor(Q.data.length),{data:I,shape:Q.shape,stride:Dg(Q.shape,A)}}function Gs(Q,A){let I=ts(Q,A),g=Q.shape.length,B=Q.data.length,C=Array(g).fill(0),E=hi(Q.data),i=hi(I.data);for(let o=0;o<B;o++){let a=0;for(let D=0;D<g;D++)a+=C[D]*I.stride[D];i[a]=E[o],C[0]+=1;for(let D=0;D<g;D++)if(C[D]===Q.shape[D]){if(D+1===g)break;C[D]=0,C[D+1]+=1}}return I}function ws(Q){let A=Q.shape.length;return yI(A===Q.stride.length,"Shape and stride must have the same length."),Q.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function Fs(Q,A){let I=ws(Q);return yI(I.length===A.length,"Orders must match"),I.every((g,B)=>g===A[B])}class tC{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",B=I.shape.length,C=new Array(B),E=new Array(B);if(g==="C")for(let i=0;i<B;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<B;++i)C[i]=B-i-1,E[i]=B-i-1;else C=g,C.forEach((i,o)=>{yI(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new tC(A,I)}encode(A){return Fs(A,this.#I)?A:Gs(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:Dg(A.shape,this.#A)}}}class _B{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=Dg(A,"C")}static fromConfig(A,I){return new _B(I.shape)}encode=ag("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),B=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<B.length;E++){let i=g.getUint32(C,!0);C+=4,B[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:B,shape:this.#A,stride:this.#I}}}class GC{kind="bytes_to_bytes";static fromConfig(A){return new GC}encode=ag("zlib");async decode(A){const I=await gi(A,{format:"deflate"});return new Uint8Array(I)}}function es(){let Q=()=>Promise.resolve().then(()=>My).then(C=>C.default),A=()=>Promise.resolve().then(()=>py).then(C=>C.default),I=()=>Promise.resolve().then(()=>by).then(C=>C.default),g=()=>sC,B=()=>GC;return new Map().set("blosc",Q).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",B).set("transpose",()=>tC).set("bytes",()=>vB).set("crc32c",()=>aC).set("vlen-utf8",()=>_B).set("json2",()=>zB).set("bitround",()=>OB).set("cast_value",()=>oC).set("scale_offset",()=>hC).set("numcodecs.blosc",Q).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",B).set("numcodecs.vlen-utf8",()=>_B).set("numcodecs.shuffle",()=>yC).set("numcodecs.delta",()=>DC).set("numcodecs.bitround",()=>OB).set("numcodecs.json2",()=>zB)}const rs=es();function wC(Q){let A;function I(){return A||(A=ns(Q)),A}async function g(B,C,E){try{return await E()}catch(i){throw new XD({direction:B,codec:C,cause:i})}}return{async encode(B){let C=await I();for(const{name:i,codec:o}of C.arrayToArray)B=await g("encode",i,()=>o.encode(B));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(B));for(const{name:i,codec:o}of C.bytesToBytes)E=await g("encode",i,()=>o.encode(E));return E},async decode(B){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:o,codec:a}=C.bytesToBytes[i];B=await g("decode",o,()=>a.decode(B))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(B));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:o,codec:a}=C.arrayToArray[i];E=await g("decode",o,()=>a.decode(E))}return E},async computeEncodedSize(B){let C=await I(),E=yi(C.arrayToBytes.name,C.arrayToBytes.codec,B);for(const{name:i,codec:o}of C.bytesToBytes)E=yi(i,o,E);return E}}}function yi(Q,A,I){if(!A.computeEncodedSize)throw new bA(`Codec "${Q}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return A.computeEncodedSize(I)}async function ns(Q){let A=Q.codecs.map(async E=>{let i=await rs.get(E.name)?.();if(!i)throw new vD(E.name);return{Codec:i,meta:E}}),I=[],g,B=[],C={...Q};for await(let{Codec:E,meta:i}of A){let o=E.fromConfig(i.configuration,C);switch(o.kind){case"array_to_array":I.push({name:i.name,codec:o}),o.getEncodedMeta&&(C=o.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:o};break;default:B.push({name:i.name,codec:o})}}if(!g){if(!Ss(C))throw new bA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:vB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:B}}function Ss(Q){return Q.dataType!=="v2:object"&&Q.dataType!=="string"}const ti=18446744073709551615n;function Ns(Q,A,I,g){if(!Q.store.getRange)throw new $Q("sharding requires a store with getRange");let B=Q.store.getRange.bind(Q.store),C=A.map((a,D)=>a/g.chunk_shape[D]),E=wC({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=16*C.reduce((a,D)=>a*D,1),o={};return async(a,D)=>{let s=a.map((l,P)=>Math.floor(l/C[P])),y=Q.resolve(I(s)).path;y in o||(o[y]=(async()=>{let l=await E.computeEncodedSize(i),P=await B(y,{suffixLength:l},D);return P?await E.decode(P):null})().catch(l=>{throw delete o[y],l}));let e=await o[y];if(e===null)return;let{data:J,shape:u,stride:d}=e,W=a.map((l,P)=>l%u[P]).reduce((l,P,v)=>l+P*d[v],0),z=J[W],m=J[W+1];if(!(z===ti&&m===ti))return B(y,{offset:Number(z),length:Number(m)},D)}}class eI{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 eI(this.store,decodeURIComponent(new URL(A,I).pathname))}}class FC extends eI{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function Gi(Q){return Q.find(I=>I.name==="transpose")?.configuration?.order??"C"}const $B=Symbol("zarrita.context");function Rs(Q,A){let{configuration:I}=A.codecs.find(gs)??{},g={encodeChunkKey:_D(A.chunk_key_encoding),TypedArray:Hg(A.data_type),fillValue:A.fill_value};if(I){let C=Gi(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:wC({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return Dg(E,C)},getChunkBytes:Ns(Q,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let B=Gi(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:wC({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return Dg(C,B)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),o=Q.resolve(i).path;return Q.store.get(o,E)}}}let AQ=class extends eI{kind="array";#A;[$B];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:Ai(g)},this[$B]=Rs(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[$B].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&jD();let B=this[$B],C=await B.getChunkBytes(A,I);if(!C){let E=B.chunkShape.reduce((o,a)=>o*a,1),i;if(g?.useSharedArrayBuffer){let o=new B.TypedArray(0);if(!("BYTES_PER_ELEMENT"in o))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new B.TypedArray(E);else{let a=zD(E*o.BYTES_PER_ELEMENT);i=new B.TypedArray(a,0,E)}}else i=new B.TypedArray(E);return i.fill(B.fillValue),{data:i,shape:B.chunkShape,stride:B.getStrides(B.chunkShape)}}return B.codec.decode(C)}is(A){return gC(this.dtype,A)}};function cs(Q,A){let I=Q;for(let g of A)I instanceof Promise?I=I.then(B=>g(B)):I=g(I);return I}function Us(Q,...A){return cs(Q,A)}async function wi(Q){let A=Q.store.arrayExtensions;return A?.length?await Us(Q,...A):Q}let IQ=ks();function ks(){let Q=new WeakMap;function A(I){let g=Q.get(I)??{v2:0,v3:0};return Q.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function Ls(Q,A){let I=await Q.store.get(Q.resolve(".zattrs").path,{signal:A});return I?GB(I):{}}async function Js(Q,A={}){let I="store"in Q?Q:new eI(Q),{signal:g}=A,B={};return(A.attrs??!0)&&(B=await Ls(I,g)),g?.throwIfAborted(),A.kind==="array"?Fi(I,B,g):A.kind==="group"?ei(I,B,g):Fi(I,B,g).catch(C=>(Ii(C,Mg,bA),ei(I,B,g)))}async function Fi(Q,A,I){let{path:g}=Q.resolve(".zarray"),B=await Q.store.get(g,{signal:I});if(!B)throw new Mg("v2 array",{path:g});return IQ.increment(Q.store,"v2"),wi(new AQ(Q.store,Q.path,As(GB(B),A)))}async function ei(Q,A,I){let{path:g}=Q.resolve(".zgroup"),B=await Q.store.get(g,{signal:I});if(!B)throw new Mg("v2 group",{path:g});return IQ.increment(Q.store,"v2"),new FC(Q.store,Q.path,Is(GB(B),A))}async function Ys(Q,A){let{store:I,path:g}=Q.resolve("zarr.json"),B=await Q.store.get(g,{signal:A});if(!B)throw new Mg("v3 array or group",{path:g});let C=GB(B);return C.node_type==="array"&&(C.fill_value=Ai(C)),C.node_type==="array"?wi(new AQ(I,Q.path,C)):new FC(I,Q.path,C)}async function Ks(Q,A={}){let I="store"in Q?Q:new eI(Q),g=await Ys(I,A.signal);if(IQ.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof AQ||A.kind==="group"&&g instanceof FC)return g;let B=g instanceof AQ?"array":"group";throw new Mg(`${A.kind} at ${I.path}`,{path:I.path,found:B})}async function rI(Q,A={}){let I="store"in Q?Q.store:Q,g=IQ.versionMax(I),B=g==="v2"?rI.v2:rI.v3,C=g==="v2"?rI.v3:rI.v2;return B(Q,A).catch(E=>(Ii(E,Mg,bA),C(Q,A)))}rI.v2=Js,rI.v3=Ks;async function Ms(Q,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const B of I)Q=await Q.getDirectoryHandle(B);return Q.getFileHandle(g)}class eC{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await Ms(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const B=await(await I.getFile()).arrayBuffer();return new Uint8Array(B)}}async function wB(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${Q}`)}try{return rI(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${Q}`)}}async function Hs(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${Q}`)}try{return rI(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${Q}`)}}async function ds(Q){let A;switch(Q.type){case"fetch":{const g=new hB(Q.url);A=new eI(g);break}case"filesystem":{A=new eI(new eC(Q.directoryHandle),Q.path);break}default:{const g=Q;throw new Error(`Unsupported store type: ${g}`)}}const I=Q.arrayPath?A.resolve(Q.arrayPath):A;return Hs(I,Q.zarrVersion)}function qs(Q,A,I){if(Q.store instanceof hB)return{type:"fetch",arrayPath:A,zarrVersion:I,url:Q.store.url.toString()};if(Q.store instanceof eC)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:Q.store.directoryHandle,path:Q.path};throw new Error(`Unsupported store type: ${Q.store.constructor.name}`)}function ls(Q,A,I,g){return fs(Q,A,I,g)}function fs(Q,A,I,g){const{targetShape:B,chunkIndex:C,dimIndices:E}=g;let i=1;for(let P=A.length-1;P>=0;P--){if(I[P]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[P]}const o={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:B.z};if(o.x<B.x||o.y<B.y||o.z<B.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(B)}, got ${JSON.stringify(o)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,D=g.tChunkSize?C.t%g.tChunkSize:0,s=B.x*B.y*B.z,y=E.c!==void 0?I[E.c]:0,e=E.t!==void 0?I[E.t]:0,J=D*e+a*y,u=o.x===B.x&&o.y===B.y&&o.z===B.z;if(J===0&&Q.length===s&&u)return Q;const W=new Q.constructor(s),z=E.z!==void 0?I[E.z]:0,m=I[E.y];let l=0;for(let P=0;P<B.z;P++){const v=J+P*z;for(let EA=0;EA<B.y;EA++){const sA=v+EA*m,DA=sA+B.x;W.set(Q.subarray(sA,DA),l),l+=B.x}}return W}const ri=`function xg(B, A) {
|
|
556
|
+
}`;class nD{colorFormat_;depthFormat_;device_;pipelines_;shaderModules_;constructor(A,I,g){this.colorFormat_=I,this.depthFormat_=g,this.device_=A,this.pipelines_=[],this.shaderModules_=[]}async compileShader(A){if(this.shaderModules_.some(a=>a.name===A))return;const I=cD(A),g=this.device_.createShaderModule({code:I});await SD(A,g);const B=yD(I),C=oD(B,{vertex:{entryPoint:"vert"},fragment:{entryPoint:"frag"}}),E=C[B.uniforms.uniforms.group];ND(E);const i=B.textures?.texture;let o;if(i){const a=C[i.group];A==="image_scalar_f32"&&RD(a),o=this.device_.createBindGroupLayout(a)}this.shaderModules_.push({name:A,module:g,defs:B,layouts:{uniforms:this.device_.createBindGroupLayout(E),textures:o}})}get(A,I){const g=this.getCachedPipeline(A);if(g)return g;const B=this.shaderModules_.find(e=>e.name===A.shaderName);if(!B)throw new Error("Shader module not found");const C=A.depthTest?"less-equal":"always",E=A.stencil?{compare:"equal",passOp:"increment-clamp"}:{},i={vertex:{module:B.module,entryPoint:"vert",buffers:[{attributes:I.attributes,arrayStride:I.geometry.strideBytes,stepMode:"vertex"}]},fragment:{module:B.module,entryPoint:"frag",targets:[{format:this.colorFormat_,blend:UD(A.blendMode)}]},primitive:{topology:A.topology,frontFace:"ccw",cullMode:A.cullMode},depthStencil:{format:this.depthFormat_,depthWriteEnabled:A.depthWrite,depthCompare:C,stencilFront:E,stencilBack:E,stencilReadMask:255,stencilWriteMask:255},multisample:{count:4}},o=[B.layouts.uniforms];B.layouts.textures&&o.push(B.layouts.textures);const a=this.device_.createPipelineLayout({bindGroupLayouts:o}),D=this.device_.createRenderPipeline({layout:a,...i}),s=Ha(B.defs.uniforms.uniforms),y={key:A,pipeline:D,uniformsView:s,uniformsData:new Float32Array(s.arrayBuffer),shaderModule:B};return this.pipelines_.push(y),y}getCachedPipeline(A){return this.pipelines_.find(I=>I.key.blendMode===A.blendMode&&I.key.cullMode===A.cullMode&&I.key.depthTest===A.depthTest&&I.key.depthWrite===A.depthWrite&&I.key.shaderName===A.shaderName&&I.key.stencil===A.stencil&&I.key.topology===A.topology&&I.key.vertexAttributesStr===A.vertexAttributesStr)}}async function SD(Q,A){const I=await A.getCompilationInfo();if(I.messages.some(g=>g.type==="error")){for(const g of I.messages)gA.error("WebGPUPipelines",`${g.type}: ${g.message}`);throw new Error(`Failed to compile WGSL shader ${Q}.wgsl`)}}function ND(Q){for(const A of Q.entries)A.buffer&&(A.buffer={...A.buffer,hasDynamicOffset:!0})}function RD(Q){for(const A of Q.entries)A.texture&&(A.texture={...A.texture,sampleType:"unfilterable-float"})}function cD(Q){switch(Q){case"image_scalar_u32":return wD;case"image_scalar_i32":return FD;case"image_scalar_f32":return eD;case"wireframe":return rD}}function UD(Q){let A,I;switch(Q){case"none":return;case"additive":A="src-alpha",I="one";break;case"multiply":A="dst",I="zero";break;case"subtractive":A="zero",I="one-minus-src";break;case"premultiplied":A="one-minus-dst-alpha",I="one";break;case"normal":A="src-alpha",I="one-minus-src-alpha";break}const g={srcFactor:A,dstFactor:I,operation:"add"};return{color:g,alpha:g}}const kD=lo(1,0,0,0,0,-1,0,0,0,0,.5,0,0,0,.5,1);async function LD(Q){if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser");const A=await navigator.gpu.requestAdapter();if(!A)throw new Error("Failed to obtain a WebGPU Adapter");const I=new JD(Q,await A.requestDevice());return await I.compileShaders(),I}class JD extends OC{bindings_;geometryBuffers_;pipelines_;texturePool_;colorFormat_;context_;depthFormat_;device_;currentProjection_=QI();currentModelView_=QI();colorMSAATexture_=null;depthStencilTexture_=null;passEncoder_=null;renderedObjectsPerFrame_=0;needsClear_=!0;currentDepthWrite_=!0;currentStencil_=!1;currentBlendMode_="none";currentLayerOpacity_=1;constructor(A,I){super(A),this.colorFormat_=navigator.gpu.getPreferredCanvasFormat(),this.depthFormat_="depth24plus-stencil8",this.device_=I;const g=A.getContext("webgpu");if(!g)throw new Error("Failed to initialize WebGPU context");g.configure({device:this.device_,format:this.colorFormat_,alphaMode:"premultiplied"}),this.context_=g,this.bindings_=new ta(I),this.geometryBuffers_=new Ga(I),this.texturePool_=new Na(I),this.pipelines_=new nD(I,this.colorFormat_,this.depthFormat_),gA.info("WebGPURenderer","WebGPU Initialized"),this.resize(this.width,this.height)}async compileShaders(){await Promise.all([this.pipelines_.compileShader("image_scalar_u32"),this.pipelines_.compileShader("image_scalar_i32"),this.pipelines_.compileShader("image_scalar_f32"),this.pipelines_.compileShader("wireframe")])}beginFrame(){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.needsClear_=!0}render(A){const I=[],g=[];for(const o of A.layers)(o.blendMode==="none"?I:g).push(o);for(const o of[...I,...g])o.update({viewport:A});if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new CI(TA(0,0),TA(this.width,this.height));if(!CI.intersects(B,C)){gA.warn("WebGPURenderer",`Viewport ${A.id} is entirely outside canvas bounds`);return}const E=A.camera.frustum,i=!CI.equals(B.floor(),C.floor());this.bindings_.clearUniformBindings(),this.updateProjection(A.camera.projectionMatrix),this.currentDepthWrite_=!0;for(const o of I)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.currentDepthWrite_=!1;for(const o of g)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.renderedObjects_=this.renderedObjectsPerFrame_}renderLayer(A,I,g,B,C){if(A.type!=="ImageLayer")throw new Error("Experimental WebGPU renderer only supports image layers");if(A.objects.length===0)return;const E=this.device_.createCommandEncoder();this.passEncoder_=this.beginRenderPass(E);const{x:i,y:o,width:a,height:D}=B.floor().toRect();this.passEncoder_.setViewport(i,o,a,D,0,1),C&&this.passEncoder_.setScissorRect(i,o,a,D),this.currentStencil_=A.hasMultipleLODs(),this.currentStencil_&&this.passEncoder_.setStencilReference(0),this.currentBlendMode_=A.blendMode,this.currentLayerOpacity_=A.opacity,A.objects.forEach((s,y)=>{g.intersectsWithBox3(s.boundingBox)&&(this.renderObject(A,y,I),this.renderedObjectsPerFrame_+=1)}),this.passEncoder_.end(),this.device_.queue.submit([E.finish()]),this.passEncoder_=null}renderObject(A,I,g){const B=A.objects[I];if(B.type!=="ImageRenderable")throw new Error("Experimental WebGPU renderer only supports image renderables");if(B.popStaleTextures().forEach(o=>{this.texturePool_.dispose(o)}),!B.programName)return;const C=this.passEncoder_,E=this.geometryBuffers_.get(B.geometry),i=this.pipelines_.get({shaderName:YD(B.textures[0]),depthWrite:this.currentDepthWrite_,depthTest:B.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"back",topology:"triangle-list",vertexAttributesStr:E.attributesKey},E);C.setPipeline(i.pipeline),this.setUniformsForObject(B,i,g),this.setTexturesForObject(B,i),C.setVertexBuffer(0,E.vertexBuffer),E.indexBuffer?(C.setIndexBuffer(E.indexBuffer,"uint32"),C.drawIndexed(B.geometry.indexData.length)):C.draw(B.geometry.vertexCount),B.wireframeEnabled&&this.renderWireframe(B,g)}renderWireframe(A,I){const g=A.wireframeGeometry;if(g.indexData.length===0)return;const B=this.passEncoder_,C=this.geometryBuffers_.get(g),E=this.pipelines_.get({shaderName:"wireframe",depthWrite:this.currentDepthWrite_,depthTest:A.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"none",topology:"line-list",vertexAttributesStr:C.attributesKey},C);B.setPipeline(E.pipeline),WI(this.currentModelView_,I.viewMatrix,A.transform.matrix),E.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:A.wireframeColor.rgb,opacity:this.currentLayerOpacity_}),this.bindings_.setUniforms(B,E),B.setVertexBuffer(0,C.vertexBuffer),C.indexBuffer&&(B.setIndexBuffer(C.indexBuffer,"uint32"),B.drawIndexed(g.indexData.length))}resize(A,I){this.colorMSAATexture_&&this.colorMSAATexture_.destroy(),this.colorMSAATexture_=this.device_.createTexture({size:{width:A,height:I},format:this.colorFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.depthStencilTexture_&&this.depthStencilTexture_.destroy(),this.depthStencilTexture_=this.device_.createTexture({size:{width:A,height:I},format:this.depthFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT})}beginRenderPass(A){const I=this.needsClear_?"clear":"load";return this.needsClear_=!1,A.beginRenderPass({colorAttachments:[{view:this.colorMSAATexture_.createView(),resolveTarget:this.context_.getCurrentTexture().createView(),loadOp:I,storeOp:"store",clearValue:{r:this.backgroundColor.r,g:this.backgroundColor.g,b:this.backgroundColor.b,a:this.backgroundColor.a}}],depthStencilAttachment:{view:this.depthStencilTexture_.createView(),depthLoadOp:I,depthStoreOp:"store",depthClearValue:1,stencilLoadOp:"clear",stencilStoreOp:"store",stencilClearValue:0}})}clear(){}setUniformsForObject(A,I,g){WI(this.currentModelView_,g.viewMatrix,A.transform.matrix);const B=A.getUniforms(),C=B.Opacity??1;I.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:B.Color,valueOffset:B.ValueOffset,valueScale:B.ValueScale,opacity:this.currentLayerOpacity_*C,zTexCoord:B.ZTexCoord}),this.bindings_.setUniforms(this.passEncoder_,I)}setTexturesForObject(A,I){if(A.textures.length>1)throw new Error("Experimental WebGPU renderer only supports single textures");this.bindings_.setTexture(this.passEncoder_,I,this.texturePool_.get(A.textures[0]))}updateProjection(A){WI(this.currentProjection_,kD,A)}get gpuTextureBytes(){return 0}get gpuTextureCount(){return 0}}function YD(Q){switch(Q.dataType){case"byte":case"unsigned_byte":case"float":return"image_scalar_f32";case"short":case"int":return"image_scalar_i32";case"unsigned_short":case"unsigned_int":return"image_scalar_u32"}}const KD=8;class MD{maxConcurrent_;pending_=[];running_=new Map;constructor(A=KD){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(B=>B.chunk===A);if(I>=0){this.pending_.splice(I,1),gA.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),gA.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 g=A.chunk.priority??Number.MAX_SAFE_INTEGER,B=I.chunk.priority??Number.MAX_SAFE_INTEGER;return g===B?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):g-B});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const B=new AbortController,C=Promise.resolve().then(()=>g(B.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&gA.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:B,promise:C})}}let ZB=0,PB=0;function HD(Q,A){Q.data&&(ZB-=Q.data.byteLength,PB-=1),Q.data=A,ZB+=A.byteLength,PB+=1}function dD(Q){Q.data&&(ZB-=Q.data.byteLength,PB-=1),Q.data=void 0}function qD(){return{cpuChunkBytes:ZB,cpuChunkCount:PB}}function PE(Q,A,I=1e-6){return Math.abs(Q-A)<=I}const VE=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function lD(Q){if(VE.some(I=>Q instanceof I))return!0;const A=VE.map(I=>I.name);return gA.debug("Chunk",`Unsupported chunk data type: ${Q}. Supported data types: ${A}`),!1}function fD(Q,A){return Math.round((A-Q.translation)/Q.scale)}function pI(Q,A,I){return Math.max(A,Math.min(I,Q))}const VB=Symbol("INTERNAL_POLICY_KEY");class pD{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const g=this.store_.dimensions,B=g.x.lods[0],C=g.y.lods[0];this.sourceMaxSquareDistance2D_=Qa(TA(B.size*B.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,g=[],B=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||(C.lod===I?g.push(C):C.lod===A&&I!==A&&B.push(C));return[...g,...B]}updateChunksForImage(A,I){const g=I.camera;if(g.type!=="OrthographicCamera")throw new Error("ChunkStoreView currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const C=g.getWorldViewRect(),E=Math.abs(C.max[0]-C.min[0]),i=I.element,o=I.getBoxRelativeTo(i).toRect().width,a=E/o,D=Math.log2(1/a);this.setLOD(D);const s=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(s)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const e=this.timeIndex(A);if(!this.store_.hasChunksAtTime(e)){gA.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const J=gE();Ca(J,C.min,C.max,.5);const[u,d]=this.getZBounds(A),W=new Cg(nA(C.min[0],C.min[1],u),nA(C.max[0],C.max[1],d));this.chunkViewStates_.forEach(jQ);const z=this.channelsOfInterest(A),m=this.fallbackLOD(),l=this.getPaddedBounds(W),P=this.currentLOD_===m?[this.currentLOD_]:[this.currentLOD_,m];for(const v of P){const EA=v===this.currentLOD_,sA=v===m;this.iterateChunksInBox(e,v,z,l,(DA,hA)=>{const yA=Cg.intersects(hA,W),mA=EA&&!yA,fA=this.computePriority(sA,EA,yA,mA,!0);fA!==null&&this.chunkViewStates_.set(DA,{visible:yA,prefetch:mA,priority:fA,orderKey:this.squareDistance2D(DA,J)})})}this.markTimeChunksForPrefetchImage(e,A,W,J),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=s,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){const g=WI(QI(),I.camera.projectionMatrix,I.camera.viewMatrix);if(!(this.policyChanged_||this.hasViewProjectionChanged(g)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const C=this.timeIndex(A);if(!this.store_.hasChunksAtTime(C)){gA.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(jQ);const E=this.channelsOfInterest(A),i=this.fallbackLOD(),o=a=>{const D=a.lod===i,s=a.lod===this.currentLOD_,y=this.computePriority(D,s,!0,!1,!0);y!==null&&this.chunkViewStates_.set(a,{visible:!0,prefetch:!1,priority:y,orderKey:0})};this.iterateAllChunksAtLod(C,this.currentLOD_,E,o),this.currentLOD_!==i&&this.iterateAllChunksAtLod(C,i,E,o),this.markTimeChunksForPrefetchVolume(C,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=g}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[g,B]of this.chunkViewStates_)if(!(!B.visible||g.lod!==A)&&(I=!0,g.state!=="loaded"))return!1;return I}get currentLOD(){return this.currentLOD_}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.chunkViewStates_.forEach(jQ)}setImageSourcePolicy(A,I){if(I!==VB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const g=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(g)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),a=Math.max(o,Math.min(i,this.policy_.lod.max)),D=pI(E,o,a);D!==this.currentLOD_&&(this.currentLOD_=D)}markTimeChunksForPrefetchImage(A,I,g,B){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),o=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let D=A+1;D<=E;++D)this.iterateChunksInBox(D,i,a,g,s=>{const y=this.squareDistance2D(s,B),e=pI(y/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),J=D-A+e;this.chunkViewStates_.set(s,{visible:!1,prefetch:!0,priority:o,orderKey:J})})}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,B=Math.min(g-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let o=A+1;o<=B;++o)this.iterateAllChunksAtLod(o,C,i,a=>{const D=o-A;this.chunkViewStates_.set(a,{visible:!1,prefetch:!0,priority:E,orderKey:D})})}computePriority(A,I,g,B,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&B?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,B=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(B.size/B.chunkSize),o=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,D=B.chunkSize*B.scale,s=C.chunkSize*C.scale,y=E?E.chunkSize*E.scale:1,e=B.translation,J=C.translation,u=E?.translation??0,d=Math.max(0,Math.floor((A.min[0]-e)/D)),W=Math.min(i,Math.ceil((A.max[0]-e)/D)),z=Math.max(0,Math.floor((A.min[1]-J)/s)),m=Math.min(o,Math.ceil((A.max[1]-J)/s)),l=E?Math.max(0,Math.floor((A.min[2]-u)/y)):0,P=E?Math.min(a,Math.ceil((A.max[2]-u)/y)):1;return d>=W||z>=m||l>=P?null:{xMin:d,xMax:W,yMin:z,yMax:m,zMin:l,zMax:P}}iterateChunksInBox(A,I,g,B,C){const E=this.chunkIndexRange(B,I);if(E)for(const i of g){const o=this.store_.getChunkGrid(I,A,i);if(o)for(let a=E.zMin;a<E.zMax;++a){const D=o[a];for(let s=E.yMin;s<E.yMax;++s){const y=D[s];for(let e=E.xMin;e<E.xMax;++e){const J=y[e];C(J,this.getChunkAabb(J))}}}}}iterateAllChunksAtLod(A,I,g,B){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const o of i)for(const a of o)B(a,this.getChunkAabb(a))}}getChunkAabb(A){return new Cg(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))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:fD(I.lods[0],A.t)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const D=I.lods[this.currentLOD_];return[D.translation,D.translation+D.size*D.scale]}const g=I.lods[this.currentLOD_],B=g.size,C=g.scale,E=g.translation,i=Math.floor((A.z-E)/C),o=g.chunkSize,a=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(B/o)-1));return[E+a*o*C,E+(a+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!LQ(this.lastViewBounds2D_.min,A.min)||!LQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!bo(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!LQ(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const I=this.store_.dimensions,g=I.x.lods[this.currentLOD_],B=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=g.chunkSize*g.scale*this.policy_.prefetch.x,i=B.chunkSize*B.scale*this.policy_.prefetch.y;let o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new Cg(nA(A.min[0]-E,A.min[1]-i,A.min[2]-o),nA(A.max[0]+E,A.max[1]+i,A.max[2]+o))}squareDistance2D(A,I){const g={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},B=g.x-I[0],C=g.y-I[1];return B*B+C*C}}function jQ(Q){Q.visible=!1,Q.prefetch=!1,Q.priority=null,Q.orderKey=null}class uD{chunks_;loader_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.loader_=A,this.dimensions_=this.loader_.getSourceDimensionMap(),this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),B=this.dimensions_.numLods;this.chunks_=new Array(B);for(let C=0;C<B;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],o=this.dimensions_.z?.lods[C],a=E.chunkSize,D=i.chunkSize,s=o?.chunkSize??1,y=Math.ceil(E.size/a),e=Math.ceil(i.size/D),J=o?Math.ceil(o.size/s):1,u=new Array(I);this.chunks_[C]=u;for(let d=0;d<I;++d){const W=new Array(g);u[d]=W;for(let z=0;z<g;++z){const m=new Array(J);W[z]=m;for(let l=0;l<J;++l){const P=o!==void 0?o.translation+l*s*o.scale:0,v=new Array(e);m[l]=v;for(let EA=0;EA<e;++EA){const sA=i.translation+EA*D*i.scale,DA=new Array(y);v[EA]=DA;for(let hA=0;hA<y;++hA){const yA=E.translation+hA*a*E.scale;DA[hA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-hA*a),y:Math.min(D,i.size-EA*D),z:Math.min(s,(o?.size??1)-l*s),c:1},rowAlignmentBytes:1,chunkIndex:{x:hA,y:EA,z:l,c:z,t:d},scale:{x:E.scale,y:i.scale,z:o?.scale??1},offset:{x:yA,y:sA,z:P}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}addView(A){const I=new pD(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,B]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,B=null,C=null;for(const a of this.views_){const D=a.chunkViewStates.get(A);D&&(D.visible&&(I=!0),D.prefetch&&(g=!0),D.priority!==null&&(B===null||D.priority<B)&&(B=D.priority,C=D.orderKey),!D.visible&&!D.prefetch&&D.priority===null&&a.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=B,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}if(A.state==="loaded"&&A.priority===null){if(A.visible||A.prefetch)throw new Error(`Chunk state inconsistency detected: priority is null but visible=${A.visible} or prefetch=${A.prefetch} for chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`);dD(A),A.state="unloaded",A.orderKey=null,gA.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const B=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!PE(B,2,.02)||!PE(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${B.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.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.scale!==1&&gA.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class mD{stores_=new Map;queue_=new MD;get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}get memoryStats(){return qD()}addView(A,I){let g=this.stores_.get(A);return g||(g=new uD(A.getLoader()),this.stores_.set(A,g)),g.addView(I)}update(){for(const[A,I]of this.stores_){const g=I.updateAndCollectChunkChanges();for(const B of g)B.priority===null?this.queue_.cancel(B):B.state==="queued"&&this.queue_.enqueue(B,C=>I.loadChunkData(B,C))}this.queue_.flush();for(const[A,I]of this.stores_)I.canDispose()&&this.stores_.delete(A)}}var sB=function(Q=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(s){s.preventDefault(),B(++A%I.children.length)},!1);function g(s){return I.appendChild(s.dom),s}function B(s){for(var y=0;y<I.children.length;y++)I.children[y].style.display=y===s?"block":"none";A=s}var C=(performance||Date).now(),E=C,i=0,o=g(new sB.Panel("FPS","#0ff","#002",Q)),a=g(new sB.Panel("MS","#0f0","#020",Q));if(self.performance&&self.performance.memory)var D=g(new sB.Panel("MB","#f08","#201",Q));return B(0),{REVISION:16,dom:I,addPanel:g,showPanel:B,begin:function(){C=(performance||Date).now()},end:function(){i++;var s=(performance||Date).now();if(a.update(s-C,200),s>=E+1e3&&(o.update(i*1e3/(s-E),100),E=s,i=0,D)){var y=performance.memory;D.update(y.usedJSHeapSize/1048576,y.jsHeapSizeLimit/1048576)}return s},update:function(){C=this.end()},domElement:I,setMode:B}};sB.Panel=function(Q,A,I,g){var B=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*g),a=E(48*i*g),D=E(3*i*g),s=E(2*i*g),y=E(3*i*g),e=E(15*i*g),J=E(74*i*g),u=E(30*i*g),d=document.createElement("canvas");d.width=o,d.height=a,d.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var W=d.getContext("2d");return W.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",W.textBaseline="top",W.fillStyle=I,W.fillRect(0,0,o,a),W.fillStyle=A,W.fillText(Q,D,s),W.fillRect(y,e,J,u),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y,e,J,u),{dom:d,update:function(z,m){B=Math.min(B,z),C=Math.max(C,z),W.fillStyle=I,W.globalAlpha=1,W.fillRect(0,0,o,e),W.fillStyle=A,W.fillText(E(z)+" "+Q+" ("+E(B)+"-"+E(C)+")",D,s),W.drawImage(d,y+i,e,J-i,u,y,e,J-i,u),W.fillRect(y+J-i,e,i,u),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y+J-i,e,i,E((1-z/m)*u))}}};function xD({scale:Q}={scale:1.5}){const A=new sB(Q);return A.showPanel(0),document.body.appendChild(A.dom),A}const zQ=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function TD(Q){return zQ.includes(Q)}class WD{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 bD{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){gA.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,zQ.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){gA.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,zQ.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!TD(A.type)){gA.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new WD(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}class ZD{id;element;camera;events;cameraControls;context_;layers_=[];constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.context_=A.context,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new bD(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:B}=I.event,C=TA(g,B);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const g of this.layers_)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.addLayer(I)}get layers(){return this.layers_}addLayer(A){A.onAttached(this.context_),this.layers_.push(A)}removeLayer(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.layers_.splice(I,1),A.onDetached(this.context_)}removeAllLayers(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[]}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),B=window.devicePixelRatio||1,C=g.left*B,E=g.top*B,i=g.height*B,o=I.x-C,a=I.y-E,D=Math.floor(o),s=Math.floor(i-a-I.height),y=Math.floor(I.width),e=Math.floor(I.height);return new CI(TA(D,s),TA(D+y,s+e))}clientToClip(A,I=0){const[g,B]=A,C=this.element.getBoundingClientRect();return nA(2*(g-C.x)/C.width-1,2*(B-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,B=A.top*I,C=A.width*I,E=A.height*I;return new CI(TA(g,B),TA(g+C,B+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){gA.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function OE(Q,A){for(const I of A){if(I.id===Q.id)throw new Error(`Duplicate viewport ID "${Q.id}". Each viewport must have a unique ID.`);if(I.element===Q.element){const g=Q.element.tagName.toLowerCase()+(Q.element.id?`#${Q.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${Q.id}" both use ${g}`)}}}function PD(Q){for(let A=0;A<Q.length;A++)OE(Q[A],Q.slice(0,A))}function vE(Q,A,I){const g=Q.map(B=>{const C=B.element??A;return{...B,element:C,id:B.id??C.id??jC("viewport"),context:I}});return PD(g),g.map(B=>new ZD(B))}class VD{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){gA.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.onChange_()});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.onChange_(),this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){gA.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){gA.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){gA.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class _Q{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;static async create(A){const I=A.renderer==="webgpu-experimental"?await LD(A.canvas):new EE(A.canvas);return new _Q(A,I)}constructor(A,I){this.canvas=A.canvas,this.renderer_=I??new EE(this.canvas),this.chunkManager_=new mD,this.context_={chunkManager:this.chunkManager_},this.viewports_=vE(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=xD());const g=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&g.push(B.element);this.sizeObserver_=new VD(g,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get memoryStats(){const A=performance.memory;return{...this.chunkManager_.memoryStats,gpuTextureBytes:this.renderer_.gpuTextureBytes,gpuTextureCount:this.renderer_.gpuTextureCount,jsHeapUsedBytes:A?.usedJSHeapSize,jsHeapLimitBytes:A?.jsHeapSizeLimit}}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=vE([A],this.canvas,this.context_);return OE(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),gA.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(gA.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),gA.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(gA.info("Idetik","Idetik runtime starting"),this.running)gA.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(gA.info("Idetik","Idetik runtime stopping"),!this.running)gA.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}}}function OD(Q,A){return{...Q,...A,headers:{...Q.headers,...A.headers}}}function XE(Q,A){const I=typeof Q=="string"?new URL(Q):Q;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function jE(Q){if(Q.status!==404){if(Q.status===200||Q.status===206)return new Uint8Array(await Q.arrayBuffer());throw new Error(`Unexpected response status ${Q.status} ${Q.statusText}`)}}class hB{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,OD(this.#I,I))}async get(A,I={}){let g=XE(this.url,A).href,B=this.#B(g,I),C=await this.#A(B);return jE(C)}async getRange(A,I,g={}){let B=XE(this.url,A),C;if("suffixLength"in I)C=await this.#Q(B,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(B,E);C=await this.#A(i)}return jE(C)}async#Q(A,I,g){if(this.#g){let D={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,D))}let B=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(B);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),o=i-I,a={...g,headers:{...g.headers,Range:`bytes=${o}-${i-1}`}};return this.#A(this.#B(A,a))}}class yB extends Error{}class Mg extends yB{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class bA extends yB{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class vD extends yB{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class XD extends yB{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class $Q extends yB{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function ag(Q){return()=>{throw new $Q(`${Q} encode`)}}class OB{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new bA("keepbits must be zero or positive")}static fromConfig(A,I){return new OB(A,I)}encode=ag("bitround");decode(A){return A}}function AC(Q){return Q instanceof ArrayBuffer||Q instanceof SharedArrayBuffer}class zE{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):AC(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,B=>B?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 IC{_data;chars;#A;constructor(A,I,g,B){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(AC(I))B&&(B=B*A),this._data=new Uint8Array(I,g,B);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 g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class tB{#A;chars;constructor(A,I,g,B){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(AC(I))B&&(B*=A),this.#A=new Int32Array(I,g,B);else{const C=I,E=new tB(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 g="";for(let B=0;B<this.chars;B++)g+=String.fromCodePoint(this.#A[I+B]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,B=this.#A.subarray(g,g+this.chars);B.fill(0);for(let C=0;C<this.chars;C++)B[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function jD(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function zD(Q,A){return new SharedArrayBuffer(Q)}function GB(Q){const A=new TextDecoder().decode(Q);try{return JSON.parse(A)}catch(I){throw new bA("Failed to decode JSON",{cause:I})}}function _E(Q,A){const I=A/2,g=A-1;let B=0;for(let C=0;C<Q.length;C+=A)for(let E=0;E<I;E+=1)B=Q[C+E],Q[C+E]=Q[C+g-E],Q[C+g-E]=B}function Hg(Q){if(Q==="v2:object")return globalThis.Array;let A=Q.match(/v2:([US])(\d+)/);if(A){let[,g,B]=A;return(g==="U"?tB:IC).bind(null,Number(B))}if(Q==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:zE}[Q];if(!I)throw new bA(`Unknown or unsupported dataType: ${Q}`);return I}function Dg(Q,A){const I=Q.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),yI(I===A.length,"Order length must match the number of dimensions.");let g=1,B=new Array(I);for(let C=A.length-1;C>=0;C--)B[A[C]]=g,g*=Q[A[C]];return B}function _D({name:Q,configuration:A}){if(Q==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(Q==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new bA(`Unknown chunk key encoding: ${Q}`)}function $E(Q){if(Q==="|O")return{dataType:"v2:object"};let A=Q.match(/^([<|>])(.*)$/);if(!A)throw new bA(`Invalid dtype: ${Q}`);let[,I,g]=A,B={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!B)throw new bA(`Unsupported or unknown dtype: ${Q}`);return I==="|"?{dataType:B}:{dataType:B,endian:I==="<"?"little":"big"}}function $D(Q){return(Q.id==="fixedscaleoffset"||Q.id==="numcodecs.fixedscaleoffset")&&typeof Q.scale=="number"&&typeof Q.offset=="number"&&(Q.astype===void 0||typeof Q.astype=="string")&&(Q.dtype===void 0||typeof Q.dtype=="string")}function As(Q,A={}){let I=[],g=$E(Q.dtype);Q.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of Q.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!$D(C))throw new bA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let o=C.astype??C.dtype;if(o!==void 0&&o!==Q.dtype){let a=$E(o).dataType;if(!gC(a,"number")&&!gC(a,"bigint"))throw new bA(`fixedscaleoffset astype must be a numeric data type, got ${o}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),Q.compressor){let{id:C,...E}=Q.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let B;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(B=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:Q.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:Q.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:Q.dimension_separator??"."}},codecs:I,fill_value:Q.fill_value,dimension_names:B,attributes:A}}function Is(Q,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function gC(Q,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return Q===A;let I=Q==="bool";if(A==="boolean")return I;let g=Q.startsWith("v2:U")||Q.startsWith("v2:S")||Q==="string";if(A==="string")return g;let B=Q==="int64"||Q==="uint64";if(A==="bigint")return B;let C=Q==="v2:object";return A==="object"?C:!g&&!B&&!I&&!C}function gs(Q){return Q?.name==="sharding_indexed"}function Ai(Q){if((Q.data_type==="uint64"||Q.data_type==="int64")&&Q.fill_value!=null)return BigInt(Q.fill_value);let A=Q.data_type==="float16"||Q.data_type==="float32"||Q.data_type==="float64";if(typeof Q.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(Q.fill_value in I)return I[Q.fill_value]}return Q.fill_value}function Ii(Q,...A){if(!A.some(I=>Q instanceof I))throw Q}function yI(Q,A=""){if(!Q)throw new Error(A)}async function gi(Q,{format:A,signal:I}){let g;if(Q instanceof ArrayBuffer)g=new Response(Q);else{let B=new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength);g=new Response(B.slice().buffer)}yI(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const Bi=Bs();function Bs(){const Q=new Uint32Array([305419896]);return new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)[0]!==18}function Qi(Q){return"BYTES_PER_ELEMENT"in Q?Q.BYTES_PER_ELEMENT:4}class vB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=Hg(I.dataType),this.#B=I.shape,this.#A=Dg(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new vB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return Bi&&this.#Q==="big"&&_E(I,Qi(this.#I)),I}computeEncodedSize(A){return A}decode(A){return Bi&&this.#Q==="big"&&_E(A,Qi(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const Ci={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},Ei={float16:2,float32:4,float64:8};function XB(Q){return Q in Ei}function BC(Q){return Q==="int64"||Q==="uint64"}function Qs(Q,A){const I=BigInt(Q),g=new ArrayBuffer(A),B=new DataView(g);if(A===2){if(typeof B.getFloat16!="function")throw new $Q("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return B.setUint16(0,Number(I)),B.getFloat16(0)}return A===4?(B.setUint32(0,Number(I)),B.getFloat32(0)):(B.setBigUint64(0,I),B.getFloat64(0))}function jB(Q,A){if(BC(Q)){if(typeof A!="number"||!Number.isInteger(A))throw new bA(`Expected an integer value for data type "${Q}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!XB(Q)&&!Number.isInteger(A))throw new bA(`Expected an integer value for data type "${Q}", got ${A}`);return A}if(!XB(Q))throw new bA(`String-encoded scalar "${A}" is not valid for non-float data type "${Q}"`);return A in Ci?Ci[A]:Qs(A,Ei[Q])}const ii=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),QC={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},CC={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function oi(Q,A,I){return Q.map(([g,B])=>({src:jB(A,g),tgt:jB(I,B)}))}function Cs(Q,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof Q=="number"&&Number.isNaN(Q))return I.tgt}else if(Q===I.src)return I.tgt}function Es(Q){if(!Number.isFinite(Q))return Q;if(Math.abs(Q-Math.trunc(Q))===.5){const A=Math.floor(Q),I=Math.ceil(Q);return A%2===0?A:I}return Math.round(Q)}function is(Q){return Math.sign(Q)*Math.floor(Math.abs(Q)+.5)}function ai(Q){switch(Q){case"nearest-even":return Es;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return is}}function EC(Q,A,I){const g=A-Q+1;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function iC(Q,A,I){const g=A-Q+1n;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class oC{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,B,C,E){this.#A=I,this.#I=Hg(A),this.#g=Di(I,A,g,B,C),this.#B=Di(A,I,g,B,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,B=A.data_type;if(!ii.has(g))throw new bA(`cast_value codec does not support array data type: ${g}`);if(!ii.has(B))throw new bA(`cast_value codec does not support encoded data type: ${B}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?oi(A.scalar_map.decode,B,g):[],i=A.scalar_map?.encode?oi(A.scalar_map.encode,g,B):[];return new oC(g,B,C,A.out_of_range,E,i)}encode=ag("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let B=0;B<I.length;B++)g[B]=this.#g(I[B]);return{data:g,shape:A.shape,stride:A.stride}}}function Di(Q,A,I,g,B){const C=XB(Q),E=BC(Q),i=XB(A),o=BC(A);let a;if(C&&i){if(I!=="nearest-even")throw new bA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=s=>s}else if(C&&!i&&!o){const s=ai(I),y=EC(...QC[A],g);a=e=>{if(!Number.isFinite(e))throw new Error(`Cannot cast ${e} to integer type without scalar_map`);return y(s(e))}}else if(C&&o){const s=ai(I),y=iC(...CC[A],g);a=e=>{if(!Number.isFinite(e))throw new Error(`Cannot cast ${e} to integer type without scalar_map`);return y(BigInt(s(e)))}}else if(!C&&!E&&i)a=s=>s;else if(E&&i)a=s=>Number(s);else if(!C&&!E&&!i&&!o)a=EC(...QC[A],g);else if(!C&&!E&&o){const s=iC(...CC[A],g);a=y=>s(BigInt(y))}else if(E&&!i&&!o){const s=EC(...QC[A],g);a=y=>s(Number(y))}else if(E&&o)a=iC(...CC[A],g);else throw new Error(`Unhandled type combination: ${Q} -> ${A}`);return B.length===0?a:s=>{const y=Cs(s,B);return y!==void 0?y:a(s)}}class aC{kind="bytes_to_bytes";static fromConfig(){return new aC}encode=ag("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const os=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function si(Q,A){const I=Q.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*Q[C+1];if(g)return;let B=I===0||A[0]===1;for(let C=1;C<I&&B;C++)B=A[C]===A[C-1]*Q[C-1];if(!B)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(Q)} stride=${JSON.stringify(A)}`)}class DC{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!os.has(I.dataType))throw new bA(`Delta codec does not support data type: ${I.dataType}`);return new DC(Hg(I.dataType))}encode(A){si(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=I[B]-I[B-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){si(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=g[B-1]+I[B];return{data:g,shape:A.shape,stride:A.stride}}}class sC{kind="bytes_to_bytes";static fromConfig(A){return new sC}encode=ag("gzip");async decode(A){const I=await gi(A,{format:"gzip"});return new Uint8Array(I)}}function as(Q,A){return yI(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),yI(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),yI(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function Ds(Q,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class zB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:B=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:a=!0}=A;let D=A.separators;D||(o?D=[", ",": "]:D=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:B,check_circular:C,allow_nan:E,indent:o,separators:D,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new zB(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:B,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;yI(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];yI(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(as),i&&o.push(Ds);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let D;o.length&&(D=(y,e)=>{let J=e;for(let u of o)J=u(y,J);return J});let s=JSON.stringify(a,D,I);return B&&(s=s.replace(/[\u007F-\uFFFF]/g,y=>{const e=`0000${y.charCodeAt(0).toString(16)}`;return`\\u${e.substring(e.length-4)}`})),new TextEncoder().encode(s)}decode(A){const{strict:I}=this.#I;yI(I,"JsonCodec does not yet support non-strict decoding.");const g=GB(A),B=g.pop();g.pop(),yI(B,"0D not implemented for JsonCodec.");const C=Dg(B,"C");return{data:g,shape:B,stride:C}}}const ss=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class hC{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!ss.has(I.dataType))throw new bA(`scale_offset codec does not support data type: ${I.dataType}`);return new hC(jB(I.dataType,A.scale??1),jB(I.dataType,A.offset??0),Hg(I.dataType))}encode=ag("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let B=0;B<I.length;B++)g[B]=I[B]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class yC{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(Hg(I.dataType))(0);yI("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new yC(A,I)}encode(A){return hs(A,this.#A)}decode(A){return ys(A,this.#A)}}function hs(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[C*g+E]=Q[E*A+C];return B}function ys(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[E*A+C]=Q[C*g+E];return B}function hi(Q){return Q instanceof zE||Q instanceof IC||Q instanceof tB?new Proxy(Q,{get(I,g){return I.get(Number(g))},set(I,g,B){return I.set(Number(g),B),!0}}):Q}function ts(Q,A){let I;return Q.data instanceof IC||Q.data instanceof tB?I=new Q.constructor(Q.data.length,Q.data.chars):I=new Q.constructor(Q.data.length),{data:I,shape:Q.shape,stride:Dg(Q.shape,A)}}function Gs(Q,A){let I=ts(Q,A),g=Q.shape.length,B=Q.data.length,C=Array(g).fill(0),E=hi(Q.data),i=hi(I.data);for(let o=0;o<B;o++){let a=0;for(let D=0;D<g;D++)a+=C[D]*I.stride[D];i[a]=E[o],C[0]+=1;for(let D=0;D<g;D++)if(C[D]===Q.shape[D]){if(D+1===g)break;C[D]=0,C[D+1]+=1}}return I}function ws(Q){let A=Q.shape.length;return yI(A===Q.stride.length,"Shape and stride must have the same length."),Q.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function Fs(Q,A){let I=ws(Q);return yI(I.length===A.length,"Orders must match"),I.every((g,B)=>g===A[B])}class tC{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",B=I.shape.length,C=new Array(B),E=new Array(B);if(g==="C")for(let i=0;i<B;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<B;++i)C[i]=B-i-1,E[i]=B-i-1;else C=g,C.forEach((i,o)=>{yI(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new tC(A,I)}encode(A){return Fs(A,this.#I)?A:Gs(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:Dg(A.shape,this.#A)}}}class _B{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=Dg(A,"C")}static fromConfig(A,I){return new _B(I.shape)}encode=ag("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),B=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<B.length;E++){let i=g.getUint32(C,!0);C+=4,B[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:B,shape:this.#A,stride:this.#I}}}class GC{kind="bytes_to_bytes";static fromConfig(A){return new GC}encode=ag("zlib");async decode(A){const I=await gi(A,{format:"deflate"});return new Uint8Array(I)}}function es(){let Q=()=>Promise.resolve().then(()=>My).then(C=>C.default),A=()=>Promise.resolve().then(()=>py).then(C=>C.default),I=()=>Promise.resolve().then(()=>by).then(C=>C.default),g=()=>sC,B=()=>GC;return new Map().set("blosc",Q).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",B).set("transpose",()=>tC).set("bytes",()=>vB).set("crc32c",()=>aC).set("vlen-utf8",()=>_B).set("json2",()=>zB).set("bitround",()=>OB).set("cast_value",()=>oC).set("scale_offset",()=>hC).set("numcodecs.blosc",Q).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",B).set("numcodecs.vlen-utf8",()=>_B).set("numcodecs.shuffle",()=>yC).set("numcodecs.delta",()=>DC).set("numcodecs.bitround",()=>OB).set("numcodecs.json2",()=>zB)}const rs=es();function wC(Q){let A;function I(){return A||(A=ns(Q)),A}async function g(B,C,E){try{return await E()}catch(i){throw new XD({direction:B,codec:C,cause:i})}}return{async encode(B){let C=await I();for(const{name:i,codec:o}of C.arrayToArray)B=await g("encode",i,()=>o.encode(B));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(B));for(const{name:i,codec:o}of C.bytesToBytes)E=await g("encode",i,()=>o.encode(E));return E},async decode(B){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:o,codec:a}=C.bytesToBytes[i];B=await g("decode",o,()=>a.decode(B))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(B));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:o,codec:a}=C.arrayToArray[i];E=await g("decode",o,()=>a.decode(E))}return E},async computeEncodedSize(B){let C=await I(),E=yi(C.arrayToBytes.name,C.arrayToBytes.codec,B);for(const{name:i,codec:o}of C.bytesToBytes)E=yi(i,o,E);return E}}}function yi(Q,A,I){if(!A.computeEncodedSize)throw new bA(`Codec "${Q}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return A.computeEncodedSize(I)}async function ns(Q){let A=Q.codecs.map(async E=>{let i=await rs.get(E.name)?.();if(!i)throw new vD(E.name);return{Codec:i,meta:E}}),I=[],g,B=[],C={...Q};for await(let{Codec:E,meta:i}of A){let o=E.fromConfig(i.configuration,C);switch(o.kind){case"array_to_array":I.push({name:i.name,codec:o}),o.getEncodedMeta&&(C=o.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:o};break;default:B.push({name:i.name,codec:o})}}if(!g){if(!Ss(C))throw new bA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:vB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:B}}function Ss(Q){return Q.dataType!=="v2:object"&&Q.dataType!=="string"}const ti=18446744073709551615n;function Ns(Q,A,I,g){if(!Q.store.getRange)throw new $Q("sharding requires a store with getRange");let B=Q.store.getRange.bind(Q.store),C=A.map((a,D)=>a/g.chunk_shape[D]),E=wC({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=16*C.reduce((a,D)=>a*D,1),o={};return async(a,D)=>{let s=a.map((l,P)=>Math.floor(l/C[P])),y=Q.resolve(I(s)).path;y in o||(o[y]=(async()=>{let l=await E.computeEncodedSize(i),P=await B(y,{suffixLength:l},D);return P?await E.decode(P):null})().catch(l=>{throw delete o[y],l}));let e=await o[y];if(e===null)return;let{data:J,shape:u,stride:d}=e,W=a.map((l,P)=>l%u[P]).reduce((l,P,v)=>l+P*d[v],0),z=J[W],m=J[W+1];if(!(z===ti&&m===ti))return B(y,{offset:Number(z),length:Number(m)},D)}}class eI{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 eI(this.store,decodeURIComponent(new URL(A,I).pathname))}}class FC extends eI{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function Gi(Q){return Q.find(I=>I.name==="transpose")?.configuration?.order??"C"}const $B=Symbol("zarrita.context");function Rs(Q,A){let{configuration:I}=A.codecs.find(gs)??{},g={encodeChunkKey:_D(A.chunk_key_encoding),TypedArray:Hg(A.data_type),fillValue:A.fill_value};if(I){let C=Gi(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:wC({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return Dg(E,C)},getChunkBytes:Ns(Q,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let B=Gi(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:wC({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return Dg(C,B)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),o=Q.resolve(i).path;return Q.store.get(o,E)}}}let AQ=class extends eI{kind="array";#A;[$B];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:Ai(g)},this[$B]=Rs(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[$B].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&jD();let B=this[$B],C=await B.getChunkBytes(A,I);if(!C){let E=B.chunkShape.reduce((o,a)=>o*a,1),i;if(g?.useSharedArrayBuffer){let o=new B.TypedArray(0);if(!("BYTES_PER_ELEMENT"in o))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new B.TypedArray(E);else{let a=zD(E*o.BYTES_PER_ELEMENT);i=new B.TypedArray(a,0,E)}}else i=new B.TypedArray(E);return i.fill(B.fillValue),{data:i,shape:B.chunkShape,stride:B.getStrides(B.chunkShape)}}return B.codec.decode(C)}is(A){return gC(this.dtype,A)}};function cs(Q,A){let I=Q;for(let g of A)I instanceof Promise?I=I.then(B=>g(B)):I=g(I);return I}function Us(Q,...A){return cs(Q,A)}async function wi(Q){let A=Q.store.arrayExtensions;return A?.length?await Us(Q,...A):Q}let IQ=ks();function ks(){let Q=new WeakMap;function A(I){let g=Q.get(I)??{v2:0,v3:0};return Q.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function Ls(Q,A){let I=await Q.store.get(Q.resolve(".zattrs").path,{signal:A});return I?GB(I):{}}async function Js(Q,A={}){let I="store"in Q?Q:new eI(Q),{signal:g}=A,B={};return(A.attrs??!0)&&(B=await Ls(I,g)),g?.throwIfAborted(),A.kind==="array"?Fi(I,B,g):A.kind==="group"?ei(I,B,g):Fi(I,B,g).catch(C=>(Ii(C,Mg,bA),ei(I,B,g)))}async function Fi(Q,A,I){let{path:g}=Q.resolve(".zarray"),B=await Q.store.get(g,{signal:I});if(!B)throw new Mg("v2 array",{path:g});return IQ.increment(Q.store,"v2"),wi(new AQ(Q.store,Q.path,As(GB(B),A)))}async function ei(Q,A,I){let{path:g}=Q.resolve(".zgroup"),B=await Q.store.get(g,{signal:I});if(!B)throw new Mg("v2 group",{path:g});return IQ.increment(Q.store,"v2"),new FC(Q.store,Q.path,Is(GB(B),A))}async function Ys(Q,A){let{store:I,path:g}=Q.resolve("zarr.json"),B=await Q.store.get(g,{signal:A});if(!B)throw new Mg("v3 array or group",{path:g});let C=GB(B);return C.node_type==="array"&&(C.fill_value=Ai(C)),C.node_type==="array"?wi(new AQ(I,Q.path,C)):new FC(I,Q.path,C)}async function Ks(Q,A={}){let I="store"in Q?Q:new eI(Q),g=await Ys(I,A.signal);if(IQ.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof AQ||A.kind==="group"&&g instanceof FC)return g;let B=g instanceof AQ?"array":"group";throw new Mg(`${A.kind} at ${I.path}`,{path:I.path,found:B})}async function rI(Q,A={}){let I="store"in Q?Q.store:Q,g=IQ.versionMax(I),B=g==="v2"?rI.v2:rI.v3,C=g==="v2"?rI.v3:rI.v2;return B(Q,A).catch(E=>(Ii(E,Mg,bA),C(Q,A)))}rI.v2=Js,rI.v3=Ks;async function Ms(Q,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const B of I)Q=await Q.getDirectoryHandle(B);return Q.getFileHandle(g)}class eC{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await Ms(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const B=await(await I.getFile()).arrayBuffer();return new Uint8Array(B)}}async function wB(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${Q}`)}try{return rI(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${Q}`)}}async function Hs(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${Q}`)}try{return rI(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${Q}`)}}async function ds(Q){let A;switch(Q.type){case"fetch":{const g=new hB(Q.url);A=new eI(g);break}case"filesystem":{A=new eI(new eC(Q.directoryHandle),Q.path);break}default:{const g=Q;throw new Error(`Unsupported store type: ${g}`)}}const I=Q.arrayPath?A.resolve(Q.arrayPath):A;return Hs(I,Q.zarrVersion)}function qs(Q,A,I){if(Q.store instanceof hB)return{type:"fetch",arrayPath:A,zarrVersion:I,url:Q.store.url.toString()};if(Q.store instanceof eC)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:Q.store.directoryHandle,path:Q.path};throw new Error(`Unsupported store type: ${Q.store.constructor.name}`)}function ls(Q,A,I,g){return fs(Q,A,I,g)}function fs(Q,A,I,g){const{targetShape:B,chunkIndex:C,dimIndices:E}=g;let i=1;for(let P=A.length-1;P>=0;P--){if(I[P]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[P]}const o={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:B.z};if(o.x<B.x||o.y<B.y||o.z<B.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(B)}, got ${JSON.stringify(o)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,D=g.tChunkSize?C.t%g.tChunkSize:0,s=B.x*B.y*B.z,y=E.c!==void 0?I[E.c]:0,e=E.t!==void 0?I[E.t]:0,J=D*e+a*y,u=o.x===B.x&&o.y===B.y&&o.z===B.z;if(J===0&&Q.length===s&&u)return Q;const W=new Q.constructor(s),z=E.z!==void 0?I[E.z]:0,m=I[E.y];let l=0;for(let P=0;P<B.z;P++){const v=J+P*z;for(let EA=0;EA<B.y;EA++){const sA=v+EA*m,DA=sA+B.x;W.set(Q.subarray(sA,DA),l),l+=B.x}}return W}const ri=`function xg(B, A) {
|
|
557
557
|
return {
|
|
558
558
|
...B,
|
|
559
559
|
...A,
|
|
@@ -4210,7 +4210,7 @@ return ret;
|
|
|
4210
4210
|
`,ni=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",ri],{type:"text/javascript;charset=utf-8"});function ps(Q){let A;try{if(A=ni&&(self.URL||self.webkitURL).createObjectURL(ni),!A)throw"";const I=new Worker(A,{type:"module",name:Q?.name});return I.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(A)}),I}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(ri),{type:"module",name:Q?.name})}}const us=Math.max(1,navigator.hardwareConcurrency-2);let UI=[],ms=0,Si=0;const sg=new Map,gQ=new Set;function Ni(Q){const A=UI.find(I=>I.worker===Q);return A||gA.error("ZarrWorker","Worker not found in pool - this should not happen"),A}function xs(Q,A){const{id:I,success:g}=Q.data,B=sg.get(I);if(!B){gQ.has(I)?gQ.delete(I):gA.warn("ZarrWorker",`Received response for unknown message ID ${I}:`,Q.data);return}sg.delete(I),B.abortListener&&B.abortSignal&&B.abortSignal.removeEventListener("abort",B.abortListener);const C=Ni(A);C&&C.pendingCount>0?C.pendingCount--:C&&gA.error("ZarrWorker","Received message but no pending tasks - this should not happen"),g&&Q.data.type==="getChunk"?B.resolve(Q.data.data):g||B.reject(new Error(Q.data.error||"Unknown worker error"))}function Ri(Q,A){if(Q instanceof MessageEvent){gA.error("ZarrWorker","Message serialization error occurred - worker remains active");return}gA.error("ZarrWorker","Worker failed - replacing worker and canceling its in-flight messages",Q.message);const I=Ni(A);if(I){const B=UI.indexOf(I);UI.splice(B,1)}const g=I?.workerId;if(g!==void 0)for(const[B,C]of sg.entries())C.workerId===g&&(C.reject(new Error(`Worker error: ${Q.message}`)),sg.delete(B));try{const B=ci();UI.push({worker:B,pendingCount:0,workerId:Si++}),gA.debug("ZarrWorker","Replacement worker created successfully")}catch(B){gA.error("ZarrWorker","Failed to create replacement worker",B)}}function ci(){const Q=new ps;return Q.addEventListener("message",A=>xs(A,Q)),Q.addEventListener("error",A=>Ri(A,Q)),Q.addEventListener("messageerror",A=>Ri(A,Q)),Q}function Ts(){if(UI.length===0)throw new Error("Worker pool is not initialized");return UI.sort((Q,A)=>Q.pendingCount-A.pendingCount)[0]}async function Ws(Q,A,I,g){return new Promise((B,C)=>{const E=Ts(),i=ms++,o={resolve:B,reject:C,workerId:E.workerId};if(sg.set(i,o),g?.signal){const a=()=>{E.worker.postMessage({id:i,type:"cancel"}),sg.delete(i),gQ.add(i),E.pendingCount--,C(new DOMException("Operation was aborted","AbortError"))};if(g.signal.aborted){a(),gQ.delete(i);return}g.signal.addEventListener("abort",a,{once:!0}),o.abortListener=a,o.abortSignal=g.signal}E.pendingCount++,E.worker.postMessage({id:i,type:"getChunk",arrayParams:Q,index:A,sliceSpec:I})})}function bs(){if(!(UI.length>0))try{for(let Q=0;Q<us;Q++){const A=ci();UI.push({worker:A,pendingCount:0,workerId:Si++})}gA.debug("ZarrWorker",`Initialized worker pool with ${UI.length} workers`)}catch{gA.warn("ZarrWorker","Failed to create workers - clearing pool"),Ps();return}}async function Zs(Q,A,I,g,B){bs();try{return await Ws(A,I,g,B)}catch(C){if(C instanceof DOMException&&C.name==="AbortError")throw C;gA.warn("ZarrWorker","Falling back to main thread",C);const E=await Q.getChunk(I,B);if(!lD(E.data))throw new Error(`Unsupported chunk data type: ${E.data.constructor.name}`);return ls(E.data,E.shape,E.stride,g)}}function Ps(){for(const Q of UI)Q.worker.terminate();UI=[],sg.clear()}class Vs{metadata_;arrays_;arrayParams_;dimensions_;constructor(A){this.metadata_=A.metadata,this.arrays_=A.arrays,this.arrayParams_=A.arrayParams,this.dimensions_=Os(this.metadata_,this.arrays_)}getSourceDimensionMap(){return this.dimensions_}async loadChunkData(A,I){const g=[];if(g[this.dimensions_.x.index]=A.chunkIndex.x,g[this.dimensions_.y.index]=A.chunkIndex.y,this.dimensions_.z&&(g[this.dimensions_.z.index]=A.chunkIndex.z),this.dimensions_.c){const s=this.dimensions_.c.lods[A.lod];g[this.dimensions_.c.index]=Math.floor(A.chunkIndex.c/s.chunkSize)}if(this.dimensions_.t){const s=this.dimensions_.t.lods[A.lod];g[this.dimensions_.t.index]=Math.floor(A.chunkIndex.t/s.chunkSize)}const B=this.arrays_[A.lod],C=this.arrayParams_[A.lod],E=this.dimensions_.c?.lods[A.lod],i=this.dimensions_.t?.lods[A.lod],o={targetShape:A.shape,chunkIndex:{c:A.chunkIndex.c,t:A.chunkIndex.t},dimIndices:{x:this.dimensions_.x.index,y:this.dimensions_.y.index,z:this.dimensions_.z?.index,c:this.dimensions_.c?.index,t:this.dimensions_.t?.index},cChunkSize:E?.chunkSize,tChunkSize:i?.chunkSize},a=await Zs(B,C,g,o,{signal:I}),D=a.BYTES_PER_ELEMENT;if(!ea(D))throw new Error("Invalid row alignment value. Possible values are 1, 2, 4, or 8");A.rowAlignmentBytes=D,HD(A,a)}}function Os(Q,A){const I=Q.axes.map(s=>s.name),g=Q.axes.length,B=Ui(I,"x"),C=Ui(I,"y"),E=(s,y)=>{const e=[];for(let J=0;J<Q.datasets.length;J++){const u=Q.datasets[J],d=A[J],W=u.coordinateTransformations[0].scale,z=u.coordinateTransformations.length===2?u.coordinateTransformations[1].translation:new Array(g).fill(0);e.push({size:d.shape[y],chunkSize:d.chunks[y],scale:W[y],translation:z[y]})}if(Q.axes[y].type==="space"&&Xs(e))for(const J of e)J.translation-=.5*J.scale;return{name:s,index:y,unit:Q.axes[y].unit,lods:e}},i={x:E(I[B],B),y:E(I[C],C),numLods:A.length},o=BQ(I,"z");o!==-1&&(i.z=E(I[o],o));const a=BQ(I,"c");a!==-1&&(i.c=E(I[a],a));const D=BQ(I,"t");return D!==-1&&(i.t=E(I[D],D)),i}function vs(Q,A){return Q.toLowerCase()===A.toLowerCase()}function Ui(Q,A){const I=BQ(Q,A);if(I===-1)throw new Error(`Could not find "${A}" dimension in [${Q.join(", ")}]`);return I}function BQ(Q,A){return Q.findIndex(I=>vs(I,A))}function Xs(Q){if(Q.length<=1)return!1;for(let A=1;A<Q.length;A++){const I=.5*(Q[A].scale-Q[A-1].scale),g=Q[A].translation-Q[A-1].translation;if(Math.abs(g-I)>1e-6)return!1}return!0}var SA;(function(Q){Q.assertEqual=B=>{};function A(B){}Q.assertIs=A;function I(B){throw new Error}Q.assertNever=I,Q.arrayToEnum=B=>{const C={};for(const E of B)C[E]=E;return C},Q.getValidEnumValues=B=>{const C=Q.objectKeys(B).filter(i=>typeof B[B[i]]!="number"),E={};for(const i of C)E[i]=B[i];return Q.objectValues(E)},Q.objectValues=B=>Q.objectKeys(B).map(function(C){return B[C]}),Q.objectKeys=typeof Object.keys=="function"?B=>Object.keys(B):B=>{const C=[];for(const E in B)Object.prototype.hasOwnProperty.call(B,E)&&C.push(E);return C},Q.find=(B,C)=>{for(const E of B)if(C(E))return E},Q.isInteger=typeof Number.isInteger=="function"?B=>Number.isInteger(B):B=>typeof B=="number"&&Number.isFinite(B)&&Math.floor(B)===B;function g(B,C=" | "){return B.map(E=>typeof E=="string"?`'${E}'`:E).join(C)}Q.joinValues=g,Q.jsonStringifyReplacer=(B,C)=>typeof C=="bigint"?C.toString():C})(SA||(SA={}));var ki;(function(Q){Q.mergeShapes=(A,I)=>({...A,...I})})(ki||(ki={}));const $=SA.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),PI=Q=>{switch(typeof Q){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(Q)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(Q)?$.array:Q===null?$.null:Q.then&&typeof Q.then=="function"&&Q.catch&&typeof Q.catch=="function"?$.promise:typeof Map<"u"&&Q instanceof Map?$.map:typeof Set<"u"&&Q instanceof Set?$.set:typeof Date<"u"&&Q instanceof Date?$.date:$.object;default:return $.unknown}},Z=SA.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"]);class uI extends Error{get errors(){return this.issues}constructor(A){super(),this.issues=[],this.addIssue=g=>{this.issues=[...this.issues,g]},this.addIssues=(g=[])=>{this.issues=[...this.issues,...g]};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},g={_errors:[]},B=C=>{for(const E of C.issues)if(E.code==="invalid_union")E.unionErrors.map(B);else if(E.code==="invalid_return_type")B(E.returnTypeError);else if(E.code==="invalid_arguments")B(E.argumentsError);else if(E.path.length===0)g._errors.push(I(E));else{let i=g,o=0;for(;o<E.path.length;){const a=E.path[o];o===E.path.length-1?(i[a]=i[a]||{_errors:[]},i[a]._errors.push(I(E))):i[a]=i[a]||{_errors:[]},i=i[a],o++}}};return B(this),g}static assert(A){if(!(A instanceof uI))throw new Error(`Not a ZodError: ${A}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,SA.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(A=I=>I.message){const I={},g=[];for(const B of this.issues)if(B.path.length>0){const C=B.path[0];I[C]=I[C]||[],I[C].push(A(B))}else g.push(A(B));return{formErrors:g,fieldErrors:I}}get formErrors(){return this.flatten()}}uI.create=Q=>new uI(Q);const rC=(Q,A)=>{let I;switch(Q.code){case Z.invalid_type:Q.received===$.undefined?I="Required":I=`Expected ${Q.expected}, received ${Q.received}`;break;case Z.invalid_literal:I=`Invalid literal value, expected ${JSON.stringify(Q.expected,SA.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:I=`Unrecognized key(s) in object: ${SA.joinValues(Q.keys,", ")}`;break;case Z.invalid_union:I="Invalid input";break;case Z.invalid_union_discriminator:I=`Invalid discriminator value. Expected ${SA.joinValues(Q.options)}`;break;case Z.invalid_enum_value:I=`Invalid enum value. Expected ${SA.joinValues(Q.options)}, received '${Q.received}'`;break;case Z.invalid_arguments:I="Invalid function arguments";break;case Z.invalid_return_type:I="Invalid function return type";break;case Z.invalid_date:I="Invalid date";break;case Z.invalid_string:typeof Q.validation=="object"?"includes"in Q.validation?(I=`Invalid input: must include "${Q.validation.includes}"`,typeof Q.validation.position=="number"&&(I=`${I} at one or more positions greater than or equal to ${Q.validation.position}`)):"startsWith"in Q.validation?I=`Invalid input: must start with "${Q.validation.startsWith}"`:"endsWith"in Q.validation?I=`Invalid input: must end with "${Q.validation.endsWith}"`:SA.assertNever(Q.validation):Q.validation!=="regex"?I=`Invalid ${Q.validation}`:I="Invalid";break;case Z.too_small:Q.type==="array"?I=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at least":"more than"} ${Q.minimum} element(s)`:Q.type==="string"?I=`String must contain ${Q.exact?"exactly":Q.inclusive?"at least":"over"} ${Q.minimum} character(s)`:Q.type==="number"?I=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`:Q.type==="bigint"?I=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`:Q.type==="date"?I=`Date must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Q.minimum))}`:I="Invalid input";break;case Z.too_big:Q.type==="array"?I=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at most":"less than"} ${Q.maximum} element(s)`:Q.type==="string"?I=`String must contain ${Q.exact?"exactly":Q.inclusive?"at most":"under"} ${Q.maximum} character(s)`:Q.type==="number"?I=`Number must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`:Q.type==="bigint"?I=`BigInt must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`:Q.type==="date"?I=`Date must be ${Q.exact?"exactly":Q.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Q.maximum))}`:I="Invalid input";break;case Z.custom:I="Invalid input";break;case Z.invalid_intersection_types:I="Intersection results could not be merged";break;case Z.not_multiple_of:I=`Number must be a multiple of ${Q.multipleOf}`;break;case Z.not_finite:I="Number must be finite";break;default:I=A.defaultError,SA.assertNever(Q)}return{message:I}};let js=rC;function zs(){return js}const _s=Q=>{const{data:A,path:I,errorMaps:g,issueData:B}=Q,C=[...I,...B.path||[]],E={...B,path:C};if(B.message!==void 0)return{...B,path:C,message:B.message};let i="";const o=g.filter(a=>!!a).slice().reverse();for(const a of o)i=a(E,{data:A,defaultError:i}).message;return{...B,path:C,message:i}};function j(Q,A){const I=zs(),g=_s({issueData:A,data:Q.data,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,I,I===rC?void 0:rC].filter(B=>!!B)});Q.common.issues.push(g)}class tI{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(A,I){const g=[];for(const B of I){if(B.status==="aborted")return oA;B.status==="dirty"&&A.dirty(),g.push(B.value)}return{status:A.value,value:g}}static async mergeObjectAsync(A,I){const g=[];for(const B of I){const C=await B.key,E=await B.value;g.push({key:C,value:E})}return tI.mergeObjectSync(A,g)}static mergeObjectSync(A,I){const g={};for(const B of I){const{key:C,value:E}=B;if(C.status==="aborted"||E.status==="aborted")return oA;C.status==="dirty"&&A.dirty(),E.status==="dirty"&&A.dirty(),C.value!=="__proto__"&&(typeof E.value<"u"||B.alwaysSet)&&(g[C.value]=E.value)}return{status:A.value,value:g}}}const oA=Object.freeze({status:"aborted"}),FB=Q=>({status:"dirty",value:Q}),nI=Q=>({status:"valid",value:Q}),Li=Q=>Q.status==="aborted",Ji=Q=>Q.status==="dirty",dg=Q=>Q.status==="valid",QQ=Q=>typeof Promise<"u"&&Q instanceof Promise;var AA;(function(Q){Q.errToObj=A=>typeof A=="string"?{message:A}:A||{},Q.toString=A=>typeof A=="string"?A:A?.message})(AA||(AA={}));class VI{constructor(A,I,g,B){this._cachedPath=[],this.parent=A,this.data=I,this._path=g,this._key=B}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Yi=(Q,A)=>{if(dg(A))return{success:!0,data:A.value};if(!Q.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 uI(Q.common.issues);return this._error=I,this._error}}};function GA(Q){if(!Q)return{};const{errorMap:A,invalid_type_error:I,required_error:g,description:B}=Q;if(A&&(I||g))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return A?{errorMap:A,description:B}:{errorMap:(E,i)=>{const{message:o}=Q;return E.code==="invalid_enum_value"?{message:o??i.defaultError}:typeof i.data>"u"?{message:o??g??i.defaultError}:E.code!=="invalid_type"?{message:i.defaultError}:{message:o??I??i.defaultError}},description:B}}class rA{get description(){return this._def.description}_getType(A){return PI(A.data)}_getOrReturnCtx(A,I){return I||{common:A.parent.common,data:A.data,parsedType:PI(A.data),schemaErrorMap:this._def.errorMap,path:A.path,parent:A.parent}}_processInputParams(A){return{status:new tI,ctx:{common:A.parent.common,data:A.data,parsedType:PI(A.data),schemaErrorMap:this._def.errorMap,path:A.path,parent:A.parent}}}_parseSync(A){const I=this._parse(A);if(QQ(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 g=this.safeParse(A,I);if(g.success)return g.data;throw g.error}safeParse(A,I){const g={common:{issues:[],async:I?.async??!1,contextualErrorMap:I?.errorMap},path:I?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:PI(A)},B=this._parseSync({data:A,path:g.path,parent:g});return Yi(g,B)}"~validate"(A){const I={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:PI(A)};if(!this["~standard"].async)try{const g=this._parseSync({data:A,path:[],parent:I});return dg(g)?{value:g.value}:{issues:I.common.issues}}catch(g){g?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),I.common={issues:[],async:!0}}return this._parseAsync({data:A,path:[],parent:I}).then(g=>dg(g)?{value:g.value}:{issues:I.common.issues})}async parseAsync(A,I){const g=await this.safeParseAsync(A,I);if(g.success)return g.data;throw g.error}async safeParseAsync(A,I){const g={common:{issues:[],contextualErrorMap:I?.errorMap,async:!0},path:I?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:PI(A)},B=this._parse({data:A,path:g.path,parent:g}),C=await(QQ(B)?B:Promise.resolve(B));return Yi(g,C)}refine(A,I){const g=B=>typeof I=="string"||typeof I>"u"?{message:I}:typeof I=="function"?I(B):I;return this._refinement((B,C)=>{const E=A(B),i=()=>C.addIssue({code:Z.custom,...g(B)});return typeof Promise<"u"&&E instanceof Promise?E.then(o=>o?!0:(i(),!1)):E?!0:(i(),!1)})}refinement(A,I){return this._refinement((g,B)=>A(g)?!0:(B.addIssue(typeof I=="function"?I(g,B):I),!1))}_refinement(A){return new pg({schema:this,typeName:aA.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 XI.create(this,this._def)}nullable(){return ug.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return HI.create(this)}promise(){return oQ.create(this,this._def)}or(A){return EQ.create([this,A],this._def)}and(A){return iQ.create(this,A,this._def)}transform(A){return new pg({...GA(this._def),schema:this,typeName:aA.ZodEffects,effect:{type:"transform",transform:A}})}default(A){const I=typeof A=="function"?A:()=>A;return new UC({...GA(this._def),innerType:this,defaultValue:I,typeName:aA.ZodDefault})}brand(){return new Sh({typeName:aA.ZodBranded,type:this,...GA(this._def)})}catch(A){const I=typeof A=="function"?A:()=>A;return new kC({...GA(this._def),innerType:this,catchValue:I,typeName:aA.ZodCatch})}describe(A){const I=this.constructor;return new I({...this._def,description:A})}pipe(A){return LC.create(this,A)}readonly(){return JC.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const $s=/^c[^\s-]{8,}$/i,Ah=/^[0-9a-z]+$/,Ih=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gh=/^[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,Bh=/^[a-z0-9_-]{21}$/i,Qh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ch=/^[-+]?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)?)??$/,Eh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ih="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let nC;const oh=/^(?:(?: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])$/,ah=/^(?:(?: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])$/,Dh=/^(([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]))$/,sh=/^(([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])$/,hh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ki="((\\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])))",th=new RegExp(`^${Ki}$`);function Mi(Q){let A="[0-5]\\d";Q.precision?A=`${A}\\.\\d{${Q.precision}}`:Q.precision==null&&(A=`${A}(\\.\\d+)?`);const I=Q.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${A})${I}`}function Gh(Q){return new RegExp(`^${Mi(Q)}$`)}function wh(Q){let A=`${Ki}T${Mi(Q)}`;const I=[];return I.push(Q.local?"Z?":"Z"),Q.offset&&I.push("([+-]\\d{2}:?\\d{2})"),A=`${A}(${I.join("|")})`,new RegExp(`^${A}$`)}function Fh(Q,A){return!!((A==="v4"||!A)&&oh.test(Q)||(A==="v6"||!A)&&Dh.test(Q))}function eh(Q,A){if(!Qh.test(Q))return!1;try{const[I]=Q.split(".");if(!I)return!1;const g=I.replace(/-/g,"+").replace(/_/g,"/").padEnd(I.length+(4-I.length%4)%4,"="),B=JSON.parse(atob(g));return!(typeof B!="object"||B===null||"typ"in B&&B?.typ!=="JWT"||!B.alg||A&&B.alg!==A)}catch{return!1}}function rh(Q,A){return!!((A==="v4"||!A)&&ah.test(Q)||(A==="v6"||!A)&&sh.test(Q))}class OI extends rA{_parse(A){if(this._def.coerce&&(A.data=String(A.data)),this._getType(A)!==$.string){const C=this._getOrReturnCtx(A);return j(C,{code:Z.invalid_type,expected:$.string,received:C.parsedType}),oA}const g=new tI;let B;for(const C of this._def.checks)if(C.kind==="min")A.data.length<C.value&&(B=this._getOrReturnCtx(A,B),j(B,{code:Z.too_small,minimum:C.value,type:"string",inclusive:!0,exact:!1,message:C.message}),g.dirty());else if(C.kind==="max")A.data.length>C.value&&(B=this._getOrReturnCtx(A,B),j(B,{code:Z.too_big,maximum:C.value,type:"string",inclusive:!0,exact:!1,message:C.message}),g.dirty());else if(C.kind==="length"){const E=A.data.length>C.value,i=A.data.length<C.value;(E||i)&&(B=this._getOrReturnCtx(A,B),E?j(B,{code:Z.too_big,maximum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}):i&&j(B,{code:Z.too_small,minimum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}),g.dirty())}else if(C.kind==="email")Eh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"email",code:Z.invalid_string,message:C.message}),g.dirty());else if(C.kind==="emoji")nC||(nC=new RegExp(ih,"u")),nC.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"emoji",code:Z.invalid_string,message:C.message}),g.dirty());else if(C.kind==="uuid")gh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"uuid",code:Z.invalid_string,message:C.message}),g.dirty());else if(C.kind==="nanoid")Bh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"nanoid",code:Z.invalid_string,message:C.message}),g.dirty());else if(C.kind==="cuid")$s.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"cuid",code:Z.invalid_string,message:C.message}),g.dirty());else if(C.kind==="cuid2")Ah.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"cuid2",code:Z.invalid_string,message:C.message}),g.dirty());else if(C.kind==="ulid")Ih.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"ulid",code:Z.invalid_string,message:C.message}),g.dirty());else if(C.kind==="url")try{new URL(A.data)}catch{B=this._getOrReturnCtx(A,B),j(B,{validation:"url",code:Z.invalid_string,message:C.message}),g.dirty()}else C.kind==="regex"?(C.regex.lastIndex=0,C.regex.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"regex",code:Z.invalid_string,message:C.message}),g.dirty())):C.kind==="trim"?A.data=A.data.trim():C.kind==="includes"?A.data.includes(C.value,C.position)||(B=this._getOrReturnCtx(A,B),j(B,{code:Z.invalid_string,validation:{includes:C.value,position:C.position},message:C.message}),g.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)||(B=this._getOrReturnCtx(A,B),j(B,{code:Z.invalid_string,validation:{startsWith:C.value},message:C.message}),g.dirty()):C.kind==="endsWith"?A.data.endsWith(C.value)||(B=this._getOrReturnCtx(A,B),j(B,{code:Z.invalid_string,validation:{endsWith:C.value},message:C.message}),g.dirty()):C.kind==="datetime"?wh(C).test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{code:Z.invalid_string,validation:"datetime",message:C.message}),g.dirty()):C.kind==="date"?th.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{code:Z.invalid_string,validation:"date",message:C.message}),g.dirty()):C.kind==="time"?Gh(C).test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{code:Z.invalid_string,validation:"time",message:C.message}),g.dirty()):C.kind==="duration"?Ch.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"duration",code:Z.invalid_string,message:C.message}),g.dirty()):C.kind==="ip"?Fh(A.data,C.version)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"ip",code:Z.invalid_string,message:C.message}),g.dirty()):C.kind==="jwt"?eh(A.data,C.alg)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"jwt",code:Z.invalid_string,message:C.message}),g.dirty()):C.kind==="cidr"?rh(A.data,C.version)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"cidr",code:Z.invalid_string,message:C.message}),g.dirty()):C.kind==="base64"?hh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"base64",code:Z.invalid_string,message:C.message}),g.dirty()):C.kind==="base64url"?yh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"base64url",code:Z.invalid_string,message:C.message}),g.dirty()):SA.assertNever(C);return{status:g.value,value:A.data}}_regex(A,I,g){return this.refinement(B=>A.test(B),{validation:I,code:Z.invalid_string,...AA.errToObj(g)})}_addCheck(A){return new OI({...this._def,checks:[...this._def.checks,A]})}email(A){return this._addCheck({kind:"email",...AA.errToObj(A)})}url(A){return this._addCheck({kind:"url",...AA.errToObj(A)})}emoji(A){return this._addCheck({kind:"emoji",...AA.errToObj(A)})}uuid(A){return this._addCheck({kind:"uuid",...AA.errToObj(A)})}nanoid(A){return this._addCheck({kind:"nanoid",...AA.errToObj(A)})}cuid(A){return this._addCheck({kind:"cuid",...AA.errToObj(A)})}cuid2(A){return this._addCheck({kind:"cuid2",...AA.errToObj(A)})}ulid(A){return this._addCheck({kind:"ulid",...AA.errToObj(A)})}base64(A){return this._addCheck({kind:"base64",...AA.errToObj(A)})}base64url(A){return this._addCheck({kind:"base64url",...AA.errToObj(A)})}jwt(A){return this._addCheck({kind:"jwt",...AA.errToObj(A)})}ip(A){return this._addCheck({kind:"ip",...AA.errToObj(A)})}cidr(A){return this._addCheck({kind:"cidr",...AA.errToObj(A)})}datetime(A){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:A?.offset??!1,local:A?.local??!1,...AA.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,...AA.errToObj(A?.message)})}duration(A){return this._addCheck({kind:"duration",...AA.errToObj(A)})}regex(A,I){return this._addCheck({kind:"regex",regex:A,...AA.errToObj(I)})}includes(A,I){return this._addCheck({kind:"includes",value:A,position:I?.position,...AA.errToObj(I?.message)})}startsWith(A,I){return this._addCheck({kind:"startsWith",value:A,...AA.errToObj(I)})}endsWith(A,I){return this._addCheck({kind:"endsWith",value:A,...AA.errToObj(I)})}min(A,I){return this._addCheck({kind:"min",value:A,...AA.errToObj(I)})}max(A,I){return this._addCheck({kind:"max",value:A,...AA.errToObj(I)})}length(A,I){return this._addCheck({kind:"length",value:A,...AA.errToObj(I)})}nonempty(A){return this.min(1,AA.errToObj(A))}trim(){return new OI({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new OI({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new OI({...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}}OI.create=Q=>new OI({checks:[],typeName:aA.ZodString,coerce:Q?.coerce??!1,...GA(Q)});function nh(Q,A){const I=(Q.toString().split(".")[1]||"").length,g=(A.toString().split(".")[1]||"").length,B=I>g?I:g,C=Number.parseInt(Q.toFixed(B).replace(".","")),E=Number.parseInt(A.toFixed(B).replace(".",""));return C%E/10**B}class qg extends rA{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)!==$.number){const C=this._getOrReturnCtx(A);return j(C,{code:Z.invalid_type,expected:$.number,received:C.parsedType}),oA}let g;const B=new tI;for(const C of this._def.checks)C.kind==="int"?SA.isInteger(A.data)||(g=this._getOrReturnCtx(A,g),j(g,{code:Z.invalid_type,expected:"integer",received:"float",message:C.message}),B.dirty()):C.kind==="min"?(C.inclusive?A.data<C.value:A.data<=C.value)&&(g=this._getOrReturnCtx(A,g),j(g,{code:Z.too_small,minimum:C.value,type:"number",inclusive:C.inclusive,exact:!1,message:C.message}),B.dirty()):C.kind==="max"?(C.inclusive?A.data>C.value:A.data>=C.value)&&(g=this._getOrReturnCtx(A,g),j(g,{code:Z.too_big,maximum:C.value,type:"number",inclusive:C.inclusive,exact:!1,message:C.message}),B.dirty()):C.kind==="multipleOf"?nh(A.data,C.value)!==0&&(g=this._getOrReturnCtx(A,g),j(g,{code:Z.not_multiple_of,multipleOf:C.value,message:C.message}),B.dirty()):C.kind==="finite"?Number.isFinite(A.data)||(g=this._getOrReturnCtx(A,g),j(g,{code:Z.not_finite,message:C.message}),B.dirty()):SA.assertNever(C);return{status:B.value,value:A.data}}gte(A,I){return this.setLimit("min",A,!0,AA.toString(I))}gt(A,I){return this.setLimit("min",A,!1,AA.toString(I))}lte(A,I){return this.setLimit("max",A,!0,AA.toString(I))}lt(A,I){return this.setLimit("max",A,!1,AA.toString(I))}setLimit(A,I,g,B){return new qg({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:g,message:AA.toString(B)}]})}_addCheck(A){return new qg({...this._def,checks:[...this._def.checks,A]})}int(A){return this._addCheck({kind:"int",message:AA.toString(A)})}positive(A){return this._addCheck({kind:"min",value:0,inclusive:!1,message:AA.toString(A)})}negative(A){return this._addCheck({kind:"max",value:0,inclusive:!1,message:AA.toString(A)})}nonpositive(A){return this._addCheck({kind:"max",value:0,inclusive:!0,message:AA.toString(A)})}nonnegative(A){return this._addCheck({kind:"min",value:0,inclusive:!0,message:AA.toString(A)})}multipleOf(A,I){return this._addCheck({kind:"multipleOf",value:A,message:AA.toString(I)})}finite(A){return this._addCheck({kind:"finite",message:AA.toString(A)})}safe(A){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:AA.toString(A)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:AA.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"&&SA.isInteger(A.value))}get isFinite(){let A=null,I=null;for(const g of this._def.checks){if(g.kind==="finite"||g.kind==="int"||g.kind==="multipleOf")return!0;g.kind==="min"?(I===null||g.value>I)&&(I=g.value):g.kind==="max"&&(A===null||g.value<A)&&(A=g.value)}return Number.isFinite(I)&&Number.isFinite(A)}}qg.create=Q=>new qg({checks:[],typeName:aA.ZodNumber,coerce:Q?.coerce||!1,...GA(Q)});class eB extends rA{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)!==$.bigint)return this._getInvalidInput(A);let g;const B=new tI;for(const C of this._def.checks)C.kind==="min"?(C.inclusive?A.data<C.value:A.data<=C.value)&&(g=this._getOrReturnCtx(A,g),j(g,{code:Z.too_small,type:"bigint",minimum:C.value,inclusive:C.inclusive,message:C.message}),B.dirty()):C.kind==="max"?(C.inclusive?A.data>C.value:A.data>=C.value)&&(g=this._getOrReturnCtx(A,g),j(g,{code:Z.too_big,type:"bigint",maximum:C.value,inclusive:C.inclusive,message:C.message}),B.dirty()):C.kind==="multipleOf"?A.data%C.value!==BigInt(0)&&(g=this._getOrReturnCtx(A,g),j(g,{code:Z.not_multiple_of,multipleOf:C.value,message:C.message}),B.dirty()):SA.assertNever(C);return{status:B.value,value:A.data}}_getInvalidInput(A){const I=this._getOrReturnCtx(A);return j(I,{code:Z.invalid_type,expected:$.bigint,received:I.parsedType}),oA}gte(A,I){return this.setLimit("min",A,!0,AA.toString(I))}gt(A,I){return this.setLimit("min",A,!1,AA.toString(I))}lte(A,I){return this.setLimit("max",A,!0,AA.toString(I))}lt(A,I){return this.setLimit("max",A,!1,AA.toString(I))}setLimit(A,I,g,B){return new eB({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:g,message:AA.toString(B)}]})}_addCheck(A){return new eB({...this._def,checks:[...this._def.checks,A]})}positive(A){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:AA.toString(A)})}negative(A){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:AA.toString(A)})}nonpositive(A){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:AA.toString(A)})}nonnegative(A){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:AA.toString(A)})}multipleOf(A,I){return this._addCheck({kind:"multipleOf",value:A,message:AA.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}}eB.create=Q=>new eB({checks:[],typeName:aA.ZodBigInt,coerce:Q?.coerce??!1,...GA(Q)});class SC extends rA{_parse(A){if(this._def.coerce&&(A.data=!!A.data),this._getType(A)!==$.boolean){const g=this._getOrReturnCtx(A);return j(g,{code:Z.invalid_type,expected:$.boolean,received:g.parsedType}),oA}return nI(A.data)}}SC.create=Q=>new SC({typeName:aA.ZodBoolean,coerce:Q?.coerce||!1,...GA(Q)});class CQ extends rA{_parse(A){if(this._def.coerce&&(A.data=new Date(A.data)),this._getType(A)!==$.date){const C=this._getOrReturnCtx(A);return j(C,{code:Z.invalid_type,expected:$.date,received:C.parsedType}),oA}if(Number.isNaN(A.data.getTime())){const C=this._getOrReturnCtx(A);return j(C,{code:Z.invalid_date}),oA}const g=new tI;let B;for(const C of this._def.checks)C.kind==="min"?A.data.getTime()<C.value&&(B=this._getOrReturnCtx(A,B),j(B,{code:Z.too_small,message:C.message,inclusive:!0,exact:!1,minimum:C.value,type:"date"}),g.dirty()):C.kind==="max"?A.data.getTime()>C.value&&(B=this._getOrReturnCtx(A,B),j(B,{code:Z.too_big,message:C.message,inclusive:!0,exact:!1,maximum:C.value,type:"date"}),g.dirty()):SA.assertNever(C);return{status:g.value,value:new Date(A.data.getTime())}}_addCheck(A){return new CQ({...this._def,checks:[...this._def.checks,A]})}min(A,I){return this._addCheck({kind:"min",value:A.getTime(),message:AA.toString(I)})}max(A,I){return this._addCheck({kind:"max",value:A.getTime(),message:AA.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}}CQ.create=Q=>new CQ({checks:[],coerce:Q?.coerce||!1,typeName:aA.ZodDate,...GA(Q)});class Hi extends rA{_parse(A){if(this._getType(A)!==$.symbol){const g=this._getOrReturnCtx(A);return j(g,{code:Z.invalid_type,expected:$.symbol,received:g.parsedType}),oA}return nI(A.data)}}Hi.create=Q=>new Hi({typeName:aA.ZodSymbol,...GA(Q)});class di extends rA{_parse(A){if(this._getType(A)!==$.undefined){const g=this._getOrReturnCtx(A);return j(g,{code:Z.invalid_type,expected:$.undefined,received:g.parsedType}),oA}return nI(A.data)}}di.create=Q=>new di({typeName:aA.ZodUndefined,...GA(Q)});class qi extends rA{_parse(A){if(this._getType(A)!==$.null){const g=this._getOrReturnCtx(A);return j(g,{code:Z.invalid_type,expected:$.null,received:g.parsedType}),oA}return nI(A.data)}}qi.create=Q=>new qi({typeName:aA.ZodNull,...GA(Q)});class NC extends rA{constructor(){super(...arguments),this._any=!0}_parse(A){return nI(A.data)}}NC.create=Q=>new NC({typeName:aA.ZodAny,...GA(Q)});class li extends rA{constructor(){super(...arguments),this._unknown=!0}_parse(A){return nI(A.data)}}li.create=Q=>new li({typeName:aA.ZodUnknown,...GA(Q)});class vI extends rA{_parse(A){const I=this._getOrReturnCtx(A);return j(I,{code:Z.invalid_type,expected:$.never,received:I.parsedType}),oA}}vI.create=Q=>new vI({typeName:aA.ZodNever,...GA(Q)});class fi extends rA{_parse(A){if(this._getType(A)!==$.undefined){const g=this._getOrReturnCtx(A);return j(g,{code:Z.invalid_type,expected:$.void,received:g.parsedType}),oA}return nI(A.data)}}fi.create=Q=>new fi({typeName:aA.ZodVoid,...GA(Q)});class HI extends rA{_parse(A){const{ctx:I,status:g}=this._processInputParams(A),B=this._def;if(I.parsedType!==$.array)return j(I,{code:Z.invalid_type,expected:$.array,received:I.parsedType}),oA;if(B.exactLength!==null){const E=I.data.length>B.exactLength.value,i=I.data.length<B.exactLength.value;(E||i)&&(j(I,{code:E?Z.too_big:Z.too_small,minimum:i?B.exactLength.value:void 0,maximum:E?B.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:B.exactLength.message}),g.dirty())}if(B.minLength!==null&&I.data.length<B.minLength.value&&(j(I,{code:Z.too_small,minimum:B.minLength.value,type:"array",inclusive:!0,exact:!1,message:B.minLength.message}),g.dirty()),B.maxLength!==null&&I.data.length>B.maxLength.value&&(j(I,{code:Z.too_big,maximum:B.maxLength.value,type:"array",inclusive:!0,exact:!1,message:B.maxLength.message}),g.dirty()),I.common.async)return Promise.all([...I.data].map((E,i)=>B.type._parseAsync(new VI(I,E,I.path,i)))).then(E=>tI.mergeArray(g,E));const C=[...I.data].map((E,i)=>B.type._parseSync(new VI(I,E,I.path,i)));return tI.mergeArray(g,C)}get element(){return this._def.type}min(A,I){return new HI({...this._def,minLength:{value:A,message:AA.toString(I)}})}max(A,I){return new HI({...this._def,maxLength:{value:A,message:AA.toString(I)}})}length(A,I){return new HI({...this._def,exactLength:{value:A,message:AA.toString(I)}})}nonempty(A){return this.min(1,A)}}HI.create=(Q,A)=>new HI({type:Q,minLength:null,maxLength:null,exactLength:null,typeName:aA.ZodArray,...GA(A)});function lg(Q){if(Q instanceof ZA){const A={};for(const I in Q.shape){const g=Q.shape[I];A[I]=XI.create(lg(g))}return new ZA({...Q._def,shape:()=>A})}else return Q instanceof HI?new HI({...Q._def,type:lg(Q.element)}):Q instanceof XI?XI.create(lg(Q.unwrap())):Q instanceof ug?ug.create(lg(Q.unwrap())):Q instanceof hg?hg.create(Q.items.map(A=>lg(A))):Q}class ZA extends rA{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=SA.objectKeys(A);return this._cached={shape:A,keys:I},this._cached}_parse(A){if(this._getType(A)!==$.object){const a=this._getOrReturnCtx(A);return j(a,{code:Z.invalid_type,expected:$.object,received:a.parsedType}),oA}const{status:g,ctx:B}=this._processInputParams(A),{shape:C,keys:E}=this._getCached(),i=[];if(!(this._def.catchall instanceof vI&&this._def.unknownKeys==="strip"))for(const a in B.data)E.includes(a)||i.push(a);const o=[];for(const a of E){const D=C[a],s=B.data[a];o.push({key:{status:"valid",value:a},value:D._parse(new VI(B,s,B.path,a)),alwaysSet:a in B.data})}if(this._def.catchall instanceof vI){const a=this._def.unknownKeys;if(a==="passthrough")for(const D of i)o.push({key:{status:"valid",value:D},value:{status:"valid",value:B.data[D]}});else if(a==="strict")i.length>0&&(j(B,{code:Z.unrecognized_keys,keys:i}),g.dirty());else if(a!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const a=this._def.catchall;for(const D of i){const s=B.data[D];o.push({key:{status:"valid",value:D},value:a._parse(new VI(B,s,B.path,D)),alwaysSet:D in B.data})}}return B.common.async?Promise.resolve().then(async()=>{const a=[];for(const D of o){const s=await D.key,y=await D.value;a.push({key:s,value:y,alwaysSet:D.alwaysSet})}return a}).then(a=>tI.mergeObjectSync(g,a)):tI.mergeObjectSync(g,o)}get shape(){return this._def.shape()}strict(A){return AA.errToObj,new ZA({...this._def,unknownKeys:"strict",...A!==void 0?{errorMap:(I,g)=>{const B=this._def.errorMap?.(I,g).message??g.defaultError;return I.code==="unrecognized_keys"?{message:AA.errToObj(A).message??B}:{message:B}}}:{}})}strip(){return new ZA({...this._def,unknownKeys:"strip"})}passthrough(){return new ZA({...this._def,unknownKeys:"passthrough"})}extend(A){return new ZA({...this._def,shape:()=>({...this._def.shape(),...A})})}merge(A){return new ZA({unknownKeys:A._def.unknownKeys,catchall:A._def.catchall,shape:()=>({...this._def.shape(),...A._def.shape()}),typeName:aA.ZodObject})}setKey(A,I){return this.augment({[A]:I})}catchall(A){return new ZA({...this._def,catchall:A})}pick(A){const I={};for(const g of SA.objectKeys(A))A[g]&&this.shape[g]&&(I[g]=this.shape[g]);return new ZA({...this._def,shape:()=>I})}omit(A){const I={};for(const g of SA.objectKeys(this.shape))A[g]||(I[g]=this.shape[g]);return new ZA({...this._def,shape:()=>I})}deepPartial(){return lg(this)}partial(A){const I={};for(const g of SA.objectKeys(this.shape)){const B=this.shape[g];A&&!A[g]?I[g]=B:I[g]=B.optional()}return new ZA({...this._def,shape:()=>I})}required(A){const I={};for(const g of SA.objectKeys(this.shape))if(A&&!A[g])I[g]=this.shape[g];else{let C=this.shape[g];for(;C instanceof XI;)C=C._def.innerType;I[g]=C}return new ZA({...this._def,shape:()=>I})}keyof(){return mi(SA.objectKeys(this.shape))}}ZA.create=(Q,A)=>new ZA({shape:()=>Q,unknownKeys:"strip",catchall:vI.create(),typeName:aA.ZodObject,...GA(A)}),ZA.strictCreate=(Q,A)=>new ZA({shape:()=>Q,unknownKeys:"strict",catchall:vI.create(),typeName:aA.ZodObject,...GA(A)}),ZA.lazycreate=(Q,A)=>new ZA({shape:Q,unknownKeys:"strip",catchall:vI.create(),typeName:aA.ZodObject,...GA(A)});class EQ extends rA{_parse(A){const{ctx:I}=this._processInputParams(A),g=this._def.options;function B(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 uI(i.ctx.common.issues));return j(I,{code:Z.invalid_union,unionErrors:E}),oA}if(I.common.async)return Promise.all(g.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(B);{let C;const E=[];for(const o of g){const a={...I,common:{...I.common,issues:[]},parent:null},D=o._parseSync({data:I.data,path:I.path,parent:a});if(D.status==="valid")return D;D.status==="dirty"&&!C&&(C={result:D,ctx:a}),a.common.issues.length&&E.push(a.common.issues)}if(C)return I.common.issues.push(...C.ctx.common.issues),C.result;const i=E.map(o=>new uI(o));return j(I,{code:Z.invalid_union,unionErrors:i}),oA}}get options(){return this._def.options}}EQ.create=(Q,A)=>new EQ({options:Q,typeName:aA.ZodUnion,...GA(A)});function RC(Q,A){const I=PI(Q),g=PI(A);if(Q===A)return{valid:!0,data:Q};if(I===$.object&&g===$.object){const B=SA.objectKeys(A),C=SA.objectKeys(Q).filter(i=>B.indexOf(i)!==-1),E={...Q,...A};for(const i of C){const o=RC(Q[i],A[i]);if(!o.valid)return{valid:!1};E[i]=o.data}return{valid:!0,data:E}}else if(I===$.array&&g===$.array){if(Q.length!==A.length)return{valid:!1};const B=[];for(let C=0;C<Q.length;C++){const E=Q[C],i=A[C],o=RC(E,i);if(!o.valid)return{valid:!1};B.push(o.data)}return{valid:!0,data:B}}else return I===$.date&&g===$.date&&+Q==+A?{valid:!0,data:Q}:{valid:!1}}class iQ extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A),B=(C,E)=>{if(Li(C)||Li(E))return oA;const i=RC(C.value,E.value);return i.valid?((Ji(C)||Ji(E))&&I.dirty(),{status:I.value,value:i.data}):(j(g,{code:Z.invalid_intersection_types}),oA)};return g.common.async?Promise.all([this._def.left._parseAsync({data:g.data,path:g.path,parent:g}),this._def.right._parseAsync({data:g.data,path:g.path,parent:g})]).then(([C,E])=>B(C,E)):B(this._def.left._parseSync({data:g.data,path:g.path,parent:g}),this._def.right._parseSync({data:g.data,path:g.path,parent:g}))}}iQ.create=(Q,A,I)=>new iQ({left:Q,right:A,typeName:aA.ZodIntersection,...GA(I)});class hg extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.parsedType!==$.array)return j(g,{code:Z.invalid_type,expected:$.array,received:g.parsedType}),oA;if(g.data.length<this._def.items.length)return j(g,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oA;!this._def.rest&&g.data.length>this._def.items.length&&(j(g,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I.dirty());const C=[...g.data].map((E,i)=>{const o=this._def.items[i]||this._def.rest;return o?o._parse(new VI(g,E,g.path,i)):null}).filter(E=>!!E);return g.common.async?Promise.all(C).then(E=>tI.mergeArray(I,E)):tI.mergeArray(I,C)}get items(){return this._def.items}rest(A){return new hg({...this._def,rest:A})}}hg.create=(Q,A)=>{if(!Array.isArray(Q))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new hg({items:Q,typeName:aA.ZodTuple,rest:null,...GA(A)})};class pi extends rA{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.parsedType!==$.map)return j(g,{code:Z.invalid_type,expected:$.map,received:g.parsedType}),oA;const B=this._def.keyType,C=this._def.valueType,E=[...g.data.entries()].map(([i,o],a)=>({key:B._parse(new VI(g,i,g.path,[a,"key"])),value:C._parse(new VI(g,o,g.path,[a,"value"]))}));if(g.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const o of E){const a=await o.key,D=await o.value;if(a.status==="aborted"||D.status==="aborted")return oA;(a.status==="dirty"||D.status==="dirty")&&I.dirty(),i.set(a.value,D.value)}return{status:I.value,value:i}})}else{const i=new Map;for(const o of E){const a=o.key,D=o.value;if(a.status==="aborted"||D.status==="aborted")return oA;(a.status==="dirty"||D.status==="dirty")&&I.dirty(),i.set(a.value,D.value)}return{status:I.value,value:i}}}}pi.create=(Q,A,I)=>new pi({valueType:A,keyType:Q,typeName:aA.ZodMap,...GA(I)});class rB extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.parsedType!==$.set)return j(g,{code:Z.invalid_type,expected:$.set,received:g.parsedType}),oA;const B=this._def;B.minSize!==null&&g.data.size<B.minSize.value&&(j(g,{code:Z.too_small,minimum:B.minSize.value,type:"set",inclusive:!0,exact:!1,message:B.minSize.message}),I.dirty()),B.maxSize!==null&&g.data.size>B.maxSize.value&&(j(g,{code:Z.too_big,maximum:B.maxSize.value,type:"set",inclusive:!0,exact:!1,message:B.maxSize.message}),I.dirty());const C=this._def.valueType;function E(o){const a=new Set;for(const D of o){if(D.status==="aborted")return oA;D.status==="dirty"&&I.dirty(),a.add(D.value)}return{status:I.value,value:a}}const i=[...g.data.values()].map((o,a)=>C._parse(new VI(g,o,g.path,a)));return g.common.async?Promise.all(i).then(o=>E(o)):E(i)}min(A,I){return new rB({...this._def,minSize:{value:A,message:AA.toString(I)}})}max(A,I){return new rB({...this._def,maxSize:{value:A,message:AA.toString(I)}})}size(A,I){return this.min(A,I).max(A,I)}nonempty(A){return this.min(1,A)}}rB.create=(Q,A)=>new rB({valueType:Q,minSize:null,maxSize:null,typeName:aA.ZodSet,...GA(A)});class ui extends rA{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})}}ui.create=(Q,A)=>new ui({getter:Q,typeName:aA.ZodLazy,...GA(A)});class cC extends rA{_parse(A){if(A.data!==this._def.value){const I=this._getOrReturnCtx(A);return j(I,{received:I.data,code:Z.invalid_literal,expected:this._def.value}),oA}return{status:"valid",value:A.data}}get value(){return this._def.value}}cC.create=(Q,A)=>new cC({value:Q,typeName:aA.ZodLiteral,...GA(A)});function mi(Q,A){return new fg({values:Q,typeName:aA.ZodEnum,...GA(A)})}class fg extends rA{_parse(A){if(typeof A.data!="string"){const I=this._getOrReturnCtx(A),g=this._def.values;return j(I,{expected:SA.joinValues(g),received:I.parsedType,code:Z.invalid_type}),oA}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(A.data)){const I=this._getOrReturnCtx(A),g=this._def.values;return j(I,{received:I.data,code:Z.invalid_enum_value,options:g}),oA}return nI(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 fg.create(A,{...this._def,...I})}exclude(A,I=this._def){return fg.create(this.options.filter(g=>!A.includes(g)),{...this._def,...I})}}fg.create=mi;class xi extends rA{_parse(A){const I=SA.getValidEnumValues(this._def.values),g=this._getOrReturnCtx(A);if(g.parsedType!==$.string&&g.parsedType!==$.number){const B=SA.objectValues(I);return j(g,{expected:SA.joinValues(B),received:g.parsedType,code:Z.invalid_type}),oA}if(this._cache||(this._cache=new Set(SA.getValidEnumValues(this._def.values))),!this._cache.has(A.data)){const B=SA.objectValues(I);return j(g,{received:g.data,code:Z.invalid_enum_value,options:B}),oA}return nI(A.data)}get enum(){return this._def.values}}xi.create=(Q,A)=>new xi({values:Q,typeName:aA.ZodNativeEnum,...GA(A)});class oQ extends rA{unwrap(){return this._def.type}_parse(A){const{ctx:I}=this._processInputParams(A);if(I.parsedType!==$.promise&&I.common.async===!1)return j(I,{code:Z.invalid_type,expected:$.promise,received:I.parsedType}),oA;const g=I.parsedType===$.promise?I.data:Promise.resolve(I.data);return nI(g.then(B=>this._def.type.parseAsync(B,{path:I.path,errorMap:I.common.contextualErrorMap})))}}oQ.create=(Q,A)=>new oQ({type:Q,typeName:aA.ZodPromise,...GA(A)});class pg extends rA{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===aA.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(A){const{status:I,ctx:g}=this._processInputParams(A),B=this._def.effect||null,C={addIssue:E=>{j(g,E),E.fatal?I.abort():I.dirty()},get path(){return g.path}};if(C.addIssue=C.addIssue.bind(C),B.type==="preprocess"){const E=B.transform(g.data,C);if(g.common.async)return Promise.resolve(E).then(async i=>{if(I.value==="aborted")return oA;const o=await this._def.schema._parseAsync({data:i,path:g.path,parent:g});return o.status==="aborted"?oA:o.status==="dirty"||I.value==="dirty"?FB(o.value):o});{if(I.value==="aborted")return oA;const i=this._def.schema._parseSync({data:E,path:g.path,parent:g});return i.status==="aborted"?oA:i.status==="dirty"||I.value==="dirty"?FB(i.value):i}}if(B.type==="refinement"){const E=i=>{const o=B.refinement(i,C);if(g.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(g.common.async===!1){const i=this._def.schema._parseSync({data:g.data,path:g.path,parent:g});return i.status==="aborted"?oA:(i.status==="dirty"&&I.dirty(),E(i.value),{status:I.value,value:i.value})}else return this._def.schema._parseAsync({data:g.data,path:g.path,parent:g}).then(i=>i.status==="aborted"?oA:(i.status==="dirty"&&I.dirty(),E(i.value).then(()=>({status:I.value,value:i.value}))))}if(B.type==="transform")if(g.common.async===!1){const E=this._def.schema._parseSync({data:g.data,path:g.path,parent:g});if(!dg(E))return oA;const i=B.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:g.data,path:g.path,parent:g}).then(E=>dg(E)?Promise.resolve(B.transform(E.value,C)).then(i=>({status:I.value,value:i})):oA);SA.assertNever(B)}}pg.create=(Q,A,I)=>new pg({schema:Q,typeName:aA.ZodEffects,effect:A,...GA(I)}),pg.createWithPreprocess=(Q,A,I)=>new pg({schema:A,effect:{type:"preprocess",transform:Q},typeName:aA.ZodEffects,...GA(I)});class XI extends rA{_parse(A){return this._getType(A)===$.undefined?nI(void 0):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}XI.create=(Q,A)=>new XI({innerType:Q,typeName:aA.ZodOptional,...GA(A)});class ug extends rA{_parse(A){return this._getType(A)===$.null?nI(null):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}ug.create=(Q,A)=>new ug({innerType:Q,typeName:aA.ZodNullable,...GA(A)});class UC extends rA{_parse(A){const{ctx:I}=this._processInputParams(A);let g=I.data;return I.parsedType===$.undefined&&(g=this._def.defaultValue()),this._def.innerType._parse({data:g,path:I.path,parent:I})}removeDefault(){return this._def.innerType}}UC.create=(Q,A)=>new UC({innerType:Q,typeName:aA.ZodDefault,defaultValue:typeof A.default=="function"?A.default:()=>A.default,...GA(A)});class kC extends rA{_parse(A){const{ctx:I}=this._processInputParams(A),g={...I,common:{...I.common,issues:[]}},B=this._def.innerType._parse({data:g.data,path:g.path,parent:{...g}});return QQ(B)?B.then(C=>({status:"valid",value:C.status==="valid"?C.value:this._def.catchValue({get error(){return new uI(g.common.issues)},input:g.data})})):{status:"valid",value:B.status==="valid"?B.value:this._def.catchValue({get error(){return new uI(g.common.issues)},input:g.data})}}removeCatch(){return this._def.innerType}}kC.create=(Q,A)=>new kC({innerType:Q,typeName:aA.ZodCatch,catchValue:typeof A.catch=="function"?A.catch:()=>A.catch,...GA(A)});class Ti extends rA{_parse(A){if(this._getType(A)!==$.nan){const g=this._getOrReturnCtx(A);return j(g,{code:Z.invalid_type,expected:$.nan,received:g.parsedType}),oA}return{status:"valid",value:A.data}}}Ti.create=Q=>new Ti({typeName:aA.ZodNaN,...GA(Q)});class Sh extends rA{_parse(A){const{ctx:I}=this._processInputParams(A),g=I.data;return this._def.type._parse({data:g,path:I.path,parent:I})}unwrap(){return this._def.type}}class LC extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.common.async)return(async()=>{const C=await this._def.in._parseAsync({data:g.data,path:g.path,parent:g});return C.status==="aborted"?oA:C.status==="dirty"?(I.dirty(),FB(C.value)):this._def.out._parseAsync({data:C.value,path:g.path,parent:g})})();{const B=this._def.in._parseSync({data:g.data,path:g.path,parent:g});return B.status==="aborted"?oA:B.status==="dirty"?(I.dirty(),{status:"dirty",value:B.value}):this._def.out._parseSync({data:B.value,path:g.path,parent:g})}}static create(A,I){return new LC({in:A,out:I,typeName:aA.ZodPipeline})}}class JC extends rA{_parse(A){const I=this._def.innerType._parse(A),g=B=>(dg(B)&&(B.value=Object.freeze(B.value)),B);return QQ(I)?I.then(B=>g(B)):g(I)}unwrap(){return this._def.innerType}}JC.create=(Q,A)=>new JC({innerType:Q,typeName:aA.ZodReadonly,...GA(A)});var aA;(function(Q){Q.ZodString="ZodString",Q.ZodNumber="ZodNumber",Q.ZodNaN="ZodNaN",Q.ZodBigInt="ZodBigInt",Q.ZodBoolean="ZodBoolean",Q.ZodDate="ZodDate",Q.ZodSymbol="ZodSymbol",Q.ZodUndefined="ZodUndefined",Q.ZodNull="ZodNull",Q.ZodAny="ZodAny",Q.ZodUnknown="ZodUnknown",Q.ZodNever="ZodNever",Q.ZodVoid="ZodVoid",Q.ZodArray="ZodArray",Q.ZodObject="ZodObject",Q.ZodUnion="ZodUnion",Q.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Q.ZodIntersection="ZodIntersection",Q.ZodTuple="ZodTuple",Q.ZodRecord="ZodRecord",Q.ZodMap="ZodMap",Q.ZodSet="ZodSet",Q.ZodFunction="ZodFunction",Q.ZodLazy="ZodLazy",Q.ZodLiteral="ZodLiteral",Q.ZodEnum="ZodEnum",Q.ZodEffects="ZodEffects",Q.ZodNativeEnum="ZodNativeEnum",Q.ZodOptional="ZodOptional",Q.ZodNullable="ZodNullable",Q.ZodDefault="ZodDefault",Q.ZodCatch="ZodCatch",Q.ZodPromise="ZodPromise",Q.ZodBranded="ZodBranded",Q.ZodPipeline="ZodPipeline",Q.ZodReadonly="ZodReadonly"})(aA||(aA={}));const kA=OI.create,wA=qg.create,Wi=SC.create,jI=NC.create;vI.create;const LA=HI.create,QA=ZA.create;EQ.create,iQ.create,hg.create;const BI=cC.create,mg=fg.create;oQ.create,XI.create,ug.create;const Nh=QA({multiscales:LA(QA({name:kA().optional(),datasets:LA(QA({path:kA(),coordinateTransformations:LA(jI().superRefine((Q,A)=>{const I=[QA({type:BI("scale"),scale:LA(wA()).min(2)}),QA({type:BI("translation"),translation:LA(wA()).min(2)})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(1)})).min(1),version:BI("0.4").optional(),axes:LA(jI().superRefine((Q,A)=>{const I=[QA({name:kA(),type:mg(["channel","time","space"])}),QA({name:kA(),type:jI().refine(B=>!mg(["space","time","channel"]).safeParse(B).success,"Invalid input: Should NOT be valid against schema").optional()})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(2).max(5),coordinateTransformations:LA(jI().superRefine((Q,A)=>{const I=[QA({type:BI("scale"),scale:LA(wA()).min(2)}),QA({type:BI("translation"),translation:LA(wA()).min(2)}),QA({type:BI("identity")})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(1).optional()})).min(1).describe("The multiscale datasets for this image"),omero:QA({channels:LA(QA({window:QA({end:wA(),max:wA(),min:wA(),start:wA()}),label:kA().optional(),family:kA().optional(),color:kA(),active:Wi().optional()})),rdefs:QA({defaultT:wA().optional(),defaultZ:wA().optional(),color:mg(["color","greyscale"]).optional(),projection:kA().optional()}).optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),Rh=QA({plate:QA({acquisitions:LA(QA({id:wA().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:wA().int().gt(0).describe("The maximum number of fields of view for the acquisition").optional(),name:kA().describe("The name of the acquisition").optional(),description:kA().describe("The description of the acquisition").optional(),starttime:wA().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:wA().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:BI("0.4").describe("The version of the specification").optional(),field_count:wA().int().gt(0).describe("The maximum number of fields per view across all wells").optional(),name:kA().describe("The name of the plate").optional(),columns:LA(QA({name:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The column name")})).min(1).describe("The columns of the plate"),rows:LA(QA({name:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The row name")})).min(1).describe("The rows of the plate"),wells:LA(QA({path:kA().regex(new RegExp("^[A-Za-z0-9]+/[A-Za-z0-9]+$")).describe("The path to the well subgroup"),rowIndex:wA().int().gte(0).describe("The index of the well in the rows list"),columnIndex:wA().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"),ch=QA({well:QA({images:LA(QA({acquisition:wA().int().describe("A unique identifier within the context of the plate").optional(),path:kA().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:BI("0.4").describe("The version of the specification").optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),Uh=QA({ome:QA({multiscales:LA(QA({name:kA().optional(),datasets:LA(QA({path:kA(),coordinateTransformations:LA(jI().superRefine((Q,A)=>{const I=[QA({type:BI("scale"),scale:LA(wA()).min(2)}),QA({type:BI("translation"),translation:LA(wA()).min(2)})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(1)})).min(1),axes:LA(jI().superRefine((Q,A)=>{const I=[QA({name:kA(),type:mg(["channel","time","space"])}),QA({name:kA(),type:jI().refine(B=>!mg(["space","time","channel"]).safeParse(B).success,"Invalid input: Should NOT be valid against schema").optional()})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(2).max(5),coordinateTransformations:LA(jI().superRefine((Q,A)=>{const I=[QA({type:BI("scale"),scale:LA(wA()).min(2)}),QA({type:BI("translation"),translation:LA(wA()).min(2)}),QA({type:BI("identity")})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(1).optional()})).min(1).describe("The multiscale datasets for this image"),omero:QA({channels:LA(QA({window:QA({end:wA(),max:wA(),min:wA(),start:wA()}).optional(),label:kA().optional(),family:kA().optional(),color:kA().optional(),active:Wi().optional()})),rdefs:QA({defaultT:wA().optional(),defaultZ:wA().optional(),color:mg(["color","greyscale"]).optional(),projection:kA().optional()}).optional()}).optional(),version:BI("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("The zarr.json attributes key"),kh=QA({ome:QA({plate:QA({acquisitions:LA(QA({id:wA().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:wA().int().gt(0).describe("The maximum number of fields of view for the acquisition").optional(),name:kA().describe("The name of the acquisition").optional(),description:kA().describe("The description of the acquisition").optional(),starttime:wA().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:wA().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:wA().int().gt(0).describe("The maximum number of fields per view across all wells").optional(),name:kA().describe("The name of the plate").optional(),columns:LA(QA({name:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The column name")})).min(1).describe("The columns of the plate"),rows:LA(QA({name:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The row name")})).min(1).describe("The rows of the plate"),wells:LA(QA({path:kA().regex(new RegExp("^[A-Za-z0-9]+/[A-Za-z0-9]+$")).describe("The path to the well subgroup"),rowIndex:wA().int().gte(0).describe("The index of the well in the rows list"),columnIndex:wA().int().gte(0).describe("The index of the well in the columns list")})).min(1).describe("The wells of the plate")}),version:BI("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("The zarr.json attributes key"),Lh=QA({ome:QA({well:QA({images:LA(QA({acquisition:wA().int().describe("A unique identifier within the context of the plate").optional(),path:kA().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:BI("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("JSON from OME-Zarr zarr.json"),Jh=["0.4","0.5"],Yh=new Set(Jh);function Kh(Q){if(!("ome"in Q)||!(Q.ome instanceof Object))return;const A=Q.ome;if("version"in A&&typeof A.version=="string"&&Yh.has(A.version))return A.version}function YC(Q){const A=Kh(Q);return A===void 0?"0.4":A}function xg(Q){if(Q!==void 0)switch(Q){case"0.4":return"v2";case"0.5":return"v3"}}function bi(Q,A){const I={...Q};return delete I[A],I}async function Mh(Q,A){const I=new hB(Q),g=new eI(I),B=xg(A),C=await wB(g,B);try{return Hh(C.attrs)}catch{throw Error(`Failed to parse OME-Zarr plate:
|
|
4211
4211
|
${JSON.stringify(C.attrs)}`)}}function Hh(Q){switch(YC(Q)){case"0.5":return{...kh.parse(Q).ome,originalVersion:"0.5"};case"0.4":return{...dh(Rh.parse(Q)).ome,originalVersion:"0.4"}}}function dh(Q){if(Q.plate===void 0)throw new Error("Plate metadata is missing in OME-Zarr v0.4 plate");return{ome:{plate:bi(Q.plate,"version"),version:"0.5"}}}function qh(Q){if(Q.well===void 0)throw new Error("Well metadata is missing in OME-Zarr v0.4 well");return{ome:{well:bi(Q.well,"version"),version:"0.5"}}}function lh(Q){switch(YC(Q)){case"0.5":return{...Lh.parse(Q).ome,originalVersion:"0.5"};case"0.4":return{...qh(ch.parse(Q)).ome,originalVersion:"0.4"}}}async function fh(Q,A,I){const g=Q+"/"+A,B=new hB(g),C=new eI(B),E=xg(I),i=await wB(C,E);try{return lh(i.attrs)}catch{throw Error(`Failed to parse OME-Zarr well:
|
|
4212
4212
|
${JSON.stringify(i.attrs)}`)}}async function ph(Q){const A=xg(Q.version),I=await wB(Q.location,A);return KC(I.attrs).omero?.channels??[]}async function uh(Q){const A=xg(Q.version),I=await wB(Q.location,A);return KC(I.attrs).omero?.rdefs}function mh(Q){return{ome:{multiscales:Q.multiscales,omero:Q.omero,version:"0.5"}}}function xh(Q){switch(YC(Q)){case"0.5":return{...Uh.parse(Q).ome,originalVersion:"0.5"};case"0.4":return{...mh(Nh.parse(Q)).ome,originalVersion:"0.4"}}}function KC(Q){try{return xh(Q)}catch{throw Error(`Failed to parse OME-Zarr image:
|
|
4213
|
-
${JSON.stringify(Q)}`)}}class Tg{location;version;loader_;constructor(A){this.location=A.location,this.version=A.version,this.loader_=A.loader}static async openLoader(A,I){let g=xg(I);const B=await wB(A,g),C=KC(B.attrs),E=C.multiscales;if(E.length!==1)throw new Error(`Exactly one multiscale image is supported. Found ${E.length} images.`);const i=E[0];if(i.datasets.length===0)throw new Error("No datasets found in the multiscale image.");g||(g=xg(C.originalVersion));const o=i.datasets.map(y=>qs(A,y.path,g)),a=await Promise.all(o.map(y=>ds(y))),D=a[0].shape,s=i.axes;if(s.length!==D.length)throw new Error(`Mismatch between number of axes (${s.length}) and array shape (${D.length})`);return new Vs({metadata:i,arrays:a,arrayParams:o})}getDimensions(){return this.loader_.getSourceDimensionMap()}getChannelCount(){return this.getDimensions().c?.lods[0].size??1}getLoader(){return this.loader_}static async fromHttp(A){const I=new eI(new hB(A.url)),g=await Tg.openLoader(I,A.version);return new Tg({location:I,version:A.version,loader:g})}static async fromFileSystem(A){const I=new eI(new eC(A.directory),A.path),g=await Tg.openLoader(I,A.version);return new Tg({location:I,version:A.version,loader:g})}}class nB{objects_=[];state_="initialized";callbacks_=[];opacity_;blendMode;constructor({opacity:A=1,blendMode:I="none"}={}){this.opacity_=pI(A,0,1),this.blendMode=I}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&gA.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=pI(A,0,1)}onEvent(A){}onAttached(A){}onDetached(A){}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)}hasMultipleLODs(){return!1}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(g=>g(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_=[]}getUniforms(){return{}}}class Th extends Ug{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})}createVertices(A){const I=new Float32Array(2*A.length*10),g=A.length>=3&&NQ(A[0],A[A.length-1]);let B=0;for(const C of[...Array(A.length).keys()])for(const E of[-1,1]){const i=A[C];I[B++]=i[0],I[B++]=i[1],I[B++]=i[2];const o=C===0?g?A[A.length-2]:A[C]:A[C-1];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const a=C===A.length-1?g?A[1]:A[C]:A[C+1];I[B++]=a[0],I[B++]=a[1],I[B++]=a[2],I[B++]=E}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let g=0;for(let B=0;B<2*A;B+=2)I[g++]=B+0,I[g++]=B+1,I[g++]=B+2,I[g++]=B+2,I[g++]=B+1,I[g++]=B+3;return I}}class Wh extends Ug{constructor(A){if(super(),A.primitive!="triangles"){gA.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){gA.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,g=[],B=(E,i)=>{const o=Math.min(E,i),a=Math.max(E,i);I.has({i0:o,i1:a})||(I.add({i0:o,i1:a}),g.push(o,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],a=C[E+2];B(i,o),B(o,a),B(a,i)}this.indexData_=new Uint32Array(g)}}const bh=nA(0,1,0);class Zh{dirty_=!0;matrix_=QI();rotation_=cQ();translation_=dA();scale_=nA(1,1,1);addRotation(A){Aa(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){ga(this.rotation_,A),this.dirty_=!0}get rotation(){return Ia(this.rotation_)}addTranslation(A){gB(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){rQ(this.translation_,A),this.dirty_=!0}get translation(){return dI(this.translation_)}addScale(A){Po(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){rQ(this.scale_,A),this.dirty_=!0}targetTo(A){NQ(this.translation_,A)&&(A=dI(A),A[2]+=JA);const I=Wo(QI(),this.translation_,A,bh),g=qo(zC(),I);IE(this.rotation_,g),kQ(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return dI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return HB(QI(),this.matrix)}computeMatrix(){po(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Wg extends FQ{wireframeEnabled=!1;wireframeColor=FA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new Zh;geometry_=new Ug;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const g=this.textures_[A];g!==void 0&&this.staleTextures_.push(g),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new Wh(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(){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 Zi extends Wg{color_;width_;constructor({geometry:A,color:I,width:g}){super(),this.geometry=A,this.color_=FA.from(I),this.width_=g,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=FA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width}}}class Ph extends nB{type="AxesLayer";constructor(A){super();const{length:I,width:g}=A;this.addObject(MC({end:[I,0,0],width:g,color:[1,0,0]})),this.addObject(MC({end:[0,I,0],width:g,color:[0,1,0]})),this.addObject(MC({end:[0,0,I],width:g,color:[0,0,1]})),this.setState("ready")}update(){}}function MC(Q){const{end:A,width:I,color:g}=Q,B=new Th([[0,0,0],A]);return new Zi({geometry:B,color:g,width:I})}const Pi=32;function SB(Q,{visible:A,color:I,contrastLimits:g,opacity:B}){return A??=!0,I=I===void 0?FA.WHITE:FA.from(I),B=B===void 0?1:pI(B,0,1),Q!==null?g=Vh(g,Q):g===void 0&&(gA.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),g=[0,1]),{visible:A,color:I,contrastLimits:g,opacity:B}}function HC(Q,A){if(A.length>Pi)throw new Error(`Maximum number of channels is ${Pi}`);return A.map(I=>SB(Q,I))}function Vi(Q,A){if(Q&&Q.length!==A)throw new Error(`channelProps length (${Q.length}) must match source channel count (${A}).`)}function Vh(Q,A){if(Q===void 0)return Sa(A);if(Q[1]<=Q[0])throw new Error(`Contrast limits must be strictly increasing: ${Q}.`);return Q}class Oi extends Ug{constructor(A,I,g,B){super();const C=[],E=[],i=g,o=B,a=i+1,D=o+1,s=A/i,y=I/o;for(let e=0;e<D;++e){const J=e*y;for(let u=0;u<a;++u){const d=u*s,W=u/i,z=e/o,m=[d,J,0],l=[0,0,1],P=[W,z];C.push(...m,...l,...P)}}for(let e=0;e<o;++e)for(let J=0;J<i;++J){const u=J+a*e,d=J+a*(e+1),W=J+1+a*(e+1),z=J+1+a*e;E.push(u,d,z),E.push(d,W,z)}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})}}class vi extends Wg{channels_;zTexCoord=.5;constructor(A,I,g,B=[]){super(),this.geometry=new Oi(A,I,1,1),this.setTexture(0,g),this.channels_=HC(g,B),this.programName=Oh(g)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=HC(this.textures[0],A)}setChannelProperty(A,I,g){const B=SB(this.textures[0],{...this.channels_[A],[I]:g});this.channels_[A]=B}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:g,opacity:B}=this.channels_[0]??SB(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-g[0],ValueScale:1/(g[1]-g[0]),Opacity:B,ZTexCoord:this.zTexCoord}}}function Oh(Q){switch(Q.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function Xi(Q,A,I,g,B=3){switch(Q.type){case"pointerdown":{const C=Q.event;return TA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=Q.event,E=TA(C.clientX,C.clientY);if(Ba(A,E)<B){if(!g)return null;const o=Q.worldPos;return o&&I(o).then(a=>{a!==null&&g({world:o,value:a})}).catch(a=>{gA.error("PointPicking",`Failed to read value: ${a}`)}),null}return A}case"pointercancel":return null;default:return A}}class dC{bins_=new Map;acquire(A){const g=this.bins_.get(A)?.pop();return g&&gA.debug("RenderablePool","Renderable object acquired"),g}release(A,I){let g=this.bins_.get(A);g||(g=[],this.bins_.set(A,g)),g.push(I),gA.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class qC extends nB{type="ImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new dC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new FA(.6,.3,.3),new FA(.3,.6,.4),new FA(.4,.4,.7),new FA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:g,channelProps:B,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=C}onAttached(A){if(this.chunkStoreView_)throw new Error("ImageLayer cannot be attached to multiple viewports simultaneously.");this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_);const I=this.chunkStoreView_.channelCount;if(Vi(this.channelProps_,I),I>1&&this.sliceCoords_.c!==void 0&&this.sliceCoords_.c.length>1)throw new Error(`ImageLayer requires exactly one channel in sliceCoords.c for multi-channel sources (found ${I} channels). Use one layer per channel.`)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){if(!(!A||!this.chunkStoreView_)){this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks();for(const[I,g]of this.visibleChunks_)g.zTexCoord=this.zTexCoordForChunk(I)}}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getImageForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}hasMultipleLODs(){return this.chunkStoreView_?this.chunkStoreView_.lodCount>1:!1}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>qC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Xi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(aQ(A));return g?(g.textures[0].updateWithChunk(A),g.zTexCoord=this.zTexCoordForChunk(A),g.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(g,A),g):this.createImage(A)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A){const I=new vi(A.shape.x,A.shape.y,qI.createWithChunk(A),this.getChannelPropsForChunk(A));return I.zTexCoord=this.zTexCoordForChunk(A),this.updateImageChunk(I,A),I}zSliceIndex(A){const I=this.sliceCoords_.z;if(I===void 0)return 0;const g=(I-A.offset.z)/A.scale.z;return pI(Math.round(g),0,A.shape.z-1)}zTexCoordForChunk(A){return(this.zSliceIndex(A)+.5)/A.shape.z}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])}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[B,C]of this.visibleChunks_){if(B.lod===I!==g)continue;const E=await this.readValueFromChunk(B,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const B=SQ(dA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C<0||C>=A.shape.x||E<0||E>=A.shape.y)return null;const i=this.zSliceIndex(A);return await I.textures[0].readTexel?.(C,E,i)??null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,g)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[g.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,g)=>{I.setChannelProps(this.getChannelPropsForChunk(g))}),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 g=this.visibleChunks_.get(I);g&&(this.pool_.release(aQ(I),g),this.visibleChunks_.delete(I))}}}function aQ(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class vh extends Ug{constructor(A,I,g,B,C,E){super();const i=[],o=[],a=Math.floor(B),D=Math.floor(C),s=Math.floor(E);this.buildFace("z","y","x",-1,-1,g,I,A,s,D,1,i,o),this.buildFace("z","y","x",1,-1,g,I,A,s,D,-1,i,o),this.buildFace("x","z","y",1,1,A,g,I,a,s,1,i,o),this.buildFace("x","z","y",1,-1,A,g,I,a,s,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,g,a,D,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,g,a,D,-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,g,B,C,E,i,o,a,D,s,y,e){const J=E/a,u=i/D,d=E/2,W=i/2,z=o/2*s,m=a+1,l=D+1,P=y.length/8;for(let v=0;v<l;v++){const EA=-W+v*u;for(let sA=0;sA<m;sA++){const DA=-d+sA*J,hA={x:0,y:0,z:0};hA[A]=DA*B,hA[I]=EA*C,hA[g]=z;const yA={x:0,y:0,z:0};yA[g]=s;const mA=sA/a,fA=1-v/D;y.push(hA.x,hA.y,hA.z,yA.x,yA.y,yA.z,mA,fA)}}for(let v=0;v<D;v++)for(let EA=0;EA<a;EA++){const sA=P+EA+m*v,DA=P+EA+m*(v+1),hA=P+(EA+1)+m*(v+1),yA=P+(EA+1)+m*v;e.push(sA,DA,yA,DA,hA,yA)}}}class ji extends Wg{voxelScale=nA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new vh(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=qI.createWithChunk(I),B=this.textures.length;this.setTexture(B,g),this.channelToTextureIndex_.set(A,B);const C=Xh(g.dataType);if(this.programName&&this.programName!==C)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${g.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const g=this.textures[A];if(!(g instanceof qI)){const B=qI.createWithChunk(I);this.setTexture(A,B);return}g.updateWithChunk(I)}clearLoadedChannels(){this.loadedChannels_=new Set}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],g=[0,0,0,0],B=[1,1,1,1],C=[1,1,1,1],E=[],i=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let o=0;o<i&&E.length<4;o++){const a=this.channelToTextureIndex_.get(o);if(a===void 0||!this.loadedChannels_.has(o))continue;const D=this.textures[a],s=SB(D,this.channels_[o]||{});if(!s.visible)continue;const y=E.length;I[y*3]=s.color.rgb[0],I[y*3+1]=s.color.rgb[1],I[y*3+2]=s.color.rgb[2],E.push(a),g[y]=-s.contrastLimits[0],B[y]=1/(s.contrastLimits[1]-s.contrastLimits[0]),A[y]=1,C[y]=s.opacity}return E.reduce((o,a,D)=>(o[`Channel${D}Sampler`]=a,o),{Visible:A,"Color[0]":I,ValueOffset:g,ValueScale:B,ChannelOpacity:C,VoxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const g=this.channelToTextureIndex_.get(A);if(g!==void 0)return this.textures[g]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=HC(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const B=SB(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=B}}function Xh(Q){switch(Q){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function jh(Q,A){const I=A.position,g=dA(),B=dA();return Q.sort((C,E)=>{gB(g,C.boundingBox.max,C.boundingBox.min),BB(g,g,.5),gB(B,E.boundingBox.max,E.boundingBox.min),BB(B,B,.5);const i=$C(I,g),o=$C(I,B);return i-o}),Q}const zh=2;class _h extends nB{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new dC;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}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)}constructor({source:A,sliceCoords:I,policy:g,channelProps:B}){super({blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=g,this.initialChannelProps_=B,this.channelProps_=B,this.setState("initialized")}getOrCreateVolume(A,I){const g=this.currentVolumes_.get(A);if(g){for(const E of I)g.updateVolumeWithChunk(E);return g}const B=Iy(I[0]),C=this.pool_.acquire(B)??new ji;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,B);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}onAttached(A){if(this.chunkStoreView_)throw new Error("VolumeLayer cannot be attached to multiple viewports simultaneously.");this.chunkStoreView_=A.chunkManager.addView(this.source_,this.sourcePolicy_),Vi(this.channelProps_,this.chunkStoreView_.channelCount)}onDetached(A){if(this.chunkStoreView_){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0}}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,g=Ay(A);if(this.lastLoadedTime_!==I||g.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)g.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));this.clearObjects();for(const[C,E]of g){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i),this.addObject(i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length,this.state!=="ready"&&this.setState("ready")}}updateVolumeTransform(A,I){const g={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([g.x,g.y,g.z]),Qg(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const B={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+B.x,I.offset.y+B.y,I.offset.z+B.z])}releaseAndRemoveVolume(A){A.clearLoadedChannels(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!this.chunkStoreView_)return;if(A===void 0)throw new Error("RenderContext is required for the VolumeLayer update as camera information is used to reorder the chunks.");this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.viewport);const I=A.viewport.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?zh:1,this.updateChunks(),jh(this.objects,A.viewport.camera)}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),RelativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,OpacityMultiplier:this.opacityMultiplier,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function $h(Q){const{x:A,y:I,z:g,t:B}=Q.chunkIndex;return`${A}:${I}:${g}:${B}`}function Ay(Q){const A=new Map;for(const I of Q){const g=$h(I);let B=A.get(g);B||(B=[],A.set(g,B)),B.push(I)}return A}function Iy(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class DQ extends JQ{data_;width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g}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 g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==g){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new DQ(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}const gy=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function By(Q){if(Q.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${Q.dataFormat}`);if(!gy.has(Q.dataType))throw new Error(`Image data type must be unsigned, instead found: ${Q.dataType}`);return Q}class zi extends Wg{outlineSelected_;selectedValue_;zTexCoord=.5;constructor(A){super(),this.geometry=new Oi(A.width,A.height,1,1),this.setTexture(0,By(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const g=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,g),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,ZTexCoord:this.zTexCoord}}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(B=>B.rgba).map(B=>Math.round(B*255))),g=new DQ(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,FA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,FA.TRANSPARENT],...A]));const I=Array.from(A.keys()),g=Array.from(A.values()).map(E=>E.packed),B=A.size,C=new Uint32Array(B*2);return C.set(I,0),C.set(g,B),new DQ(C,B,2)}}const Qy=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Cy(Q){return Q=Q??new Map,new Map(Array.from(Q.entries()).map(([A,I])=>[A,FA.from(I)]))}function Ey(Q){return Q=Q??Qy,Q.map(FA.from)}class lC{lookupTable;cycle;constructor(A={}){this.lookupTable=Cy(A.lookupTable),this.cycle=Ey(A.cycle)}}class fC extends nB{type="LabelLayer";source_;sliceCoords_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new dC;colorMap_;selectedValue_=null;policy_;chunkStoreView_;pointerDownPos_=null;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:g,colorMap:B={},onPickValue:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.colorMap_=new lC(B),this.onPickValue_=C,this.outlineSelected_=E}onAttached(A){if(this.chunkStoreView_)throw new Error("LabelLayer cannot be attached to multiple viewports simultaneously.");if(this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){if(!(!A||!this.chunkStoreView_)){this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks();for(const[I,g]of this.visibleChunks_)g.zTexCoord=this.zTexCoordForChunk(I)}}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getLabelForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>fC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Xi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new lC(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[B,C]of this.visibleChunks_){if(B.lod===I!==g)continue;const E=await this.readValueFromChunk(B,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const B=SQ(dA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C<0||C>=A.shape.x||E<0||E>=A.shape.y)return null;const i=this.zSliceIndex(A);return await I.textures[0].readTexel?.(C,E,i)??null}getLabelForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(aQ(A));return g?(g.textures[0].updateWithChunk(A),g.zTexCoord=this.zTexCoordForChunk(A),g.setColorMap(this.colorMap_),g.setSelectedValue(this.selectedValue_),this.updateLabelChunk(g,A),g):this.createLabel(A)}createLabel(A){const I=new zi({width:A.shape.x,height:A.shape.y,imageData:qI.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.zTexCoord=this.zTexCoordForChunk(A),this.updateLabelChunk(I,A),I}zSliceIndex(A){const I=this.sliceCoords_.z;if(I===void 0)return 0;const g=(I-A.offset.z)/A.scale.z;return pI(Math.round(g),0,A.shape.z-1)}zTexCoordForChunk(A){return(this.zSliceIndex(A)+.5)/A.shape.z}updateLabelChunk(A,I){A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(aQ(I),g),this.visibleChunks_.delete(I))}}}class pC extends JQ{data_;width_;height_;depth_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=A.length/(I*g)}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 g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===g)return;const B=A.shape.x,C=A.shape.y,E=g.length/(B*C);if(this.width!=B||this.height!=C||this.depth_!=E||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new pC(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}const _i={circle:0,square:1,triangle:2};class iy extends Wg{constructor(A){super(),this.programName="points";const I=A.flatMap(B=>{const C=FA.from(B.color);return[B.position[0],B.position[1],B.position[2],C.r,C.g,C.b,C.a,B.size,_i[B.marker]]}),g=new Ug(I,[],"points");g.addAttribute({type:"position",itemSize:3,offset:0}),g.addAttribute({type:"color",itemSize:4,offset:g.strideBytes}),g.addAttribute({type:"size",itemSize:1,offset:g.strideBytes}),g.addAttribute({type:"marker",itemSize:1,offset:g.strideBytes}),this.geometry=g,this.setTexture(0,oy())}get type(){return"Points"}}let uC;function oy(){return uC||(uC=ay()),uC}function ay(){const Q=a=>{const D=new Float32Array(a*a);return D.fill(1),D},A=a=>{const D=new Float32Array(a*a);for(let s=0;s<a;s++)for(let y=0;y<a;y++)(s-a/2)**2+(y-a/2)**2<(a/2)**2&&(D[s*a+y]=1);return D},I=a=>{const D=new Float32Array(a*a);for(let s=0;s<a;s++)for(let y=0;y<a;y++)y>=(a-s)/2&&y<=(a+s)/2&&(D[s*a+y]=1);return D},C={circle:A(256),square:Q(256),triangle:I(256)},E=Object.keys(C).length,i=new Float32Array(E*65536);for(const[a,D]of Object.entries(C))i.set(D,_i[a]*65536);const o=new pC(i,256,256);return o.wrapR="clamp_to_edge",o.wrapS="clamp_to_edge",o.wrapT="clamp_to_edge",o}class $i{radius;phi;theta;constructor(A,I,g){this.radius=A,this.phi=I,this.theta=g}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)}}const mC=-1,Ao=0,Dy=1,Io=.009,sy=.001,hy=9e-4,yy=.5,ty=60;class Gy{camera_;orbitVelocity_=new $i(0,0,0);panVelocity_=dA();currPos_;currCenter_=dA();dampingFactor_;currMouseButton_=mC;constructor(A,I){this.camera_=A,this.currPos_=new $i(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&rQ(this.currCenter_,I.target),this.dampingFactor_=pI(I?.dampingFactor??yy,0,1),this.updateCamera()}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&NQ(this.panVelocity_,nA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,gB(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-JA;this.currPos_.theta=pI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const g=Math.pow(1-this.dampingFactor_,A*ty);this.orbitVelocity_.phi*=g,this.orbitVelocity_.theta*=g,this.orbitVelocity_.radius*=g,BB(this.panVelocity_,this.panVelocity_,g),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==mC)return;const I=A.event,g=I.movementX??0,B=I.movementY??0,C=this.currMouseButton_===Ao&&!I.shiftKey,E=this.currMouseButton_===Ao&&I.shiftKey||this.currMouseButton_===Dy;C&&this.orbit(g,B),E&&this.pan(g,B)}onWheel(A){const I=A.event;I.preventDefault();const g=I.deltaY??0;this.zoom(g)}onPointerEnd(A){this.currMouseButton_=mC;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*Io,this.orbitVelocity_.theta+=I*Io}pan(A,I){const g=this.currPos_.radius*sy,B=dA();_C(B,B,this.camera_.right,A),_C(B,B,this.camera_.up,I),BB(B,B,g),RQ(this.panVelocity_,this.panVelocity_,B)}zoom(A){this.orbitVelocity_.radius+=A*hy}updateCamera(){const A=gB(dA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<JA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<JA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<JA&&(this.orbitVelocity_.radius=0),eQ(this.panVelocity_)<JA&&Oo(this.panVelocity_)}}class bg{normal;signedDistance;constructor(A=nA(0,1,0),I=0){this.normal=dI(A),this.signedDistance=I}set(A,I){this.normal=dI(A),this.signedDistance=I}signedDistanceToPoint(A){return AE(this.normal,A)+this.signedDistance}normalize(){const A=eQ(this.normal);if(A>0){const I=1/A;BB(this.normal,this.normal,I),this.signedDistance*=I}}}class wy{planes_;constructor(A){this.planes_=[new bg(dA(),0),new bg(dA(),0),new bg(dA(),0),new bg(dA(),0),new bg(dA(),0),new bg(dA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=dA();this.planes_[0].set(Qg(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(Qg(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(Qg(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(Qg(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(Qg(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(Qg(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const g of this.planes_)g.normalize()}intersectsWithBox3(A){const I=dA();for(const g of this.planes_){const B=g.normal;if(I[0]=B[0]>0?A.max[0]:A.min[0],I[1]=B[1]>0?A.max[1]:A.min[1],I[2]=B[2]>0?A.max[2]:A.min[2],g.signedDistanceToPoint(I)<0)return!1}return!0}}class go extends Wg{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 wy(WI(QI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=dB(A[0],A[1],A[2],1),g=HB(QI(),this.projectionMatrix_),B=QB(cg(),I,g);zo(B,B,1/B[3]);const C=QB(cg(),B,this.transform.matrix);return nA(C[0],C[1],C[2])}}const Bo=1.77,Qo=128,Co=128/Bo;class Fy extends go{width_=Qo;height_=Co;viewportAspectRatio_=Bo;viewportSize_=[Qo,Co];constructor(A,I,g,B,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,B,g),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,g,B){this.width_=Math.abs(I-A),this.height_=Math.abs(B-g),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(g+B);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=dB(-1,-1,0,1),I=dB(1,1,0,1);const g=WI(QI(),this.projectionMatrix,this.viewMatrix),B=HB(QI(),g);return A=QB(cg(),A,B),I=QB(cg(),I,B),new CI(TA(A[0],A[1]),TA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,g=A/I;let B=.5*A,C=.5*I;this.viewportAspectRatio_>g?B*=this.viewportAspectRatio_/g:C*=g/this.viewportAspectRatio_,this.viewportSize_=[2*B,2*C],To(this.projectionMatrix_,-B,B,-C,C,this.near_,this.far_)}}const Eo=0;class ey{camera_;dragActive_=!1;dragStart_=dA();constructor(A){this.camera_=A}get isMoving(){return this.dragActive_}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}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const g=dI(A.worldPos),B=I.deltaY<0?1.05:.95;this.camera_.zoom(B);const C=this.camera_.clipToWorld(A.clipPos),E=RQ(dA(),g,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==Eo||(this.dragStart_=dI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=RQ(dA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==Eo||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}const ry=60,ny=1.77,sQ=.1,xC=180-sQ;class Sy extends go{fov_;aspectRatio_;constructor(A={}){const{fov:I=ry,aspectRatio:g=ny,near:B=.1,far:C=1e4,position:E=nA(0,0,0)}=A;if(I<sQ||I>xC)throw new Error(`Invalid field of view: ${I}, must be in [${sQ}, ${xC}] degrees`);super(),this.fov_=I,this.aspectRatio_=g,this.near_=B,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(sQ,Math.min(xC,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){mo(this.projectionMatrix_,Ho(this.fov),this.aspectRatio_,this.near_,this.far_)}}const io=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function hQ(Q){Uy(Q);const A={x:Q.prefetch.x,y:Q.prefetch.y,z:Q.prefetch.z??0,t:Q.prefetch.t??0},I=Object.freeze(io.reduce((C,E)=>{const i=Q.priorityOrder.indexOf(E);return C[E]=i,C},{})),g={min:Q.lod?.min??0,max:Q.lod?.max??Number.MAX_SAFE_INTEGER,bias:Q.lod?.bias??.5},B={profile:Q.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...Q.priorityOrder]),priorityMap:I,lod:g};return Object.freeze(B)}function Ny(Q={}){return hQ(TC({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},Q))}function Ry(Q={}){return hQ(TC({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"]},Q))}function cy(Q={}){return hQ(TC({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},Q))}function Uy(Q){for(const[g,B]of Object.entries(Q.prefetch))if(B!==void 0&&B<0)throw new Error(`prefetch.${g} must be a non-negative number`);const A=Q.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=Q.priorityOrder;if(I.length!==io.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function TC(Q,A={}){return{profile:A.profile??Q.profile,prefetch:{...Q.prefetch,...A.prefetch??{}},lod:{...Q.lod,...A.lod??{}},priorityOrder:A.priorityOrder??Q.priorityOrder}}var WC=(()=>{for(var Q=new Uint8Array(128),A=0;A<64;A++)Q[A<26?A+65:A<52?A+71:A<62?A-4:A*4-205]=A;return I=>{for(var g=I.length,B=new Uint8Array((g-(I[g-1]=="=")-(I[g-2]=="="))*3/4|0),C=0,E=0;C<g;){var i=Q[I.charCodeAt(C++)],o=Q[I.charCodeAt(C++)],a=Q[I.charCodeAt(C++)],D=Q[I.charCodeAt(C++)];B[E++]=i<<2|o>>4,B[E++]=o<<4|a>>2,B[E++]=a<<6|D}return B}})(),ky=(typeof document<"u"&&document.currentScript&&document.currentScript.src,function(Q={}){var A=Q,I,g;A.ready=new Promise((G,r)=>{I=G,g=r});var B=Object.assign({},A),C="./this.program",E=A.print||console.log.bind(console),i=A.printErr||console.error.bind(console);Object.assign(A,B),B=null,A.thisProgram&&(C=A.thisProgram);var o;A.wasmBinary&&(o=A.wasmBinary),typeof WebAssembly!="object"&&hA("no native wasm support detected");var a,D=!1,s,y,e,J,u,d,W,z;function m(){var G=a.buffer;A.HEAP8=s=new Int8Array(G),A.HEAP16=e=new Int16Array(G),A.HEAPU8=y=new Uint8Array(G),A.HEAPU16=J=new Uint16Array(G),A.HEAP32=u=new Int32Array(G),A.HEAPU32=d=new Uint32Array(G),A.HEAPF32=W=new Float32Array(G),A.HEAPF64=z=new Float64Array(G)}var l=[],P=[],v=[];function EA(){var G=A.preRun.shift();l.unshift(G)}var sA=0,DA=null;function hA(G){throw A.onAbort?.(G),G="Aborted("+G+")",i(G),D=!0,G=new WebAssembly.RuntimeError(G+". Build with -sASSERTIONS for more info."),g(G),G}var yA=G=>G.startsWith("data:application/octet-stream;base64,"),mA=G=>G.startsWith("file://"),fA;if(fA="blosc_codec.wasm",!yA(fA)){var NA=fA;fA=A.locateFile?A.locateFile(NA,""):""+NA}function mI(G){return Promise.resolve().then(()=>{if(G==fA&&o)var r=new Uint8Array(o);else throw"both async and sync fetching of the wasm failed";return r})}function kI(G,r,N){return mI(G).then(H=>WebAssembly.instantiate(H,r)).then(H=>H).then(N,H=>{i(`failed to asynchronously prepare wasm: ${H}`),hA(H)})}function xI(G,r){var N=fA;return o||typeof WebAssembly.instantiateStreaming!="function"||yA(N)||mA(N)||typeof fetch!="function"?kI(N,G,r):fetch(N,{credentials:"same-origin"}).then(H=>WebAssembly.instantiateStreaming(H,G).then(r,function(h){return i(`wasm streaming compile failed: ${h}`),i("falling back to ArrayBuffer instantiation"),kI(N,G,r)}))}var zI=G=>{for(;0<G.length;)G.shift()(A)};function _I(G){this.H=G-24,this.N=function(r){d[this.H+4>>2]=r},this.M=function(r){d[this.H+8>>2]=r},this.I=function(r,N){this.J(),this.N(r),this.M(N)},this.J=function(){d[this.H+16>>2]=0}}var $A=0,PA,MA=G=>{for(var r="";y[G];)r+=PA[y[G++]];return r},jA={},KA={},xA={},VA,yg=G=>{throw new VA(G)},tg,GI=(G,r)=>{function N(Y){if(Y=r(Y),Y.length!==H.length)throw new tg("Mismatched type converter count");for(var k=0;k<H.length;++k)HA(H[k],Y[k])}var H=[];H.forEach(function(Y){xA[Y]=G});var h=Array(G.length),w=[],S=0;G.forEach((Y,k)=>{KA.hasOwnProperty(Y)?h[k]=KA[Y]:(w.push(Y),jA.hasOwnProperty(Y)||(jA[Y]=[]),jA[Y].push(()=>{h[k]=KA[Y],++S,S===w.length&&N(h)}))}),w.length===0&&N(h)};function DI(G,r,N={}){var H=r.name;if(!G)throw new VA(`type "${H}" must have a positive integer typeid pointer`);if(KA.hasOwnProperty(G)){if(N.P)return;throw new VA(`Cannot register type '${H}' twice`)}KA[G]=r,delete xA[G],jA.hasOwnProperty(G)&&(r=jA[G],delete jA[G],r.forEach(h=>h()))}function HA(G,r,N={}){if(!("argPackAdvance"in r))throw new TypeError("registerType registeredInstance requires argPackAdvance");DI(G,r,N)}function sI(){this.F=[void 0],this.K=[]}var _A=new sI,TI=G=>{G>=_A.H&&--_A.get(G).L===0&&_A.J(G)},vg=G=>{switch(G){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return _A.I({L:1,value:G})}};function $I(G){return this.fromWireType(u[G>>2])}var Gg=(G,r)=>{switch(r){case 4:return function(N){return this.fromWireType(W[N>>2])};case 8:return function(N){return this.fromWireType(z[N>>3])};default:throw new TypeError(`invalid float width (${r}): ${G}`)}},Ag=(G,r)=>Object.defineProperty(r,"name",{value:G}),Xg=G=>{for(;G.length;){var r=G.pop();G.pop()(r)}};function jg(G){for(var r=1;r<G.length;++r)if(G[r]!==null&&G[r].G===void 0)return!0;return!1}function NB(G){var r=Function;if(!(r instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof r} which is not a function`);var N=Ag(r.name||"unknownFunctionName",function(){});return N.prototype=r.prototype,N=new N,G=r.apply(N,G),G instanceof Object?G:N}var RB=(G,r)=>{if(A[G].C===void 0){var N=A[G];A[G]=function(){if(!A[G].C.hasOwnProperty(arguments.length))throw new VA(`Function '${r}' called with an invalid number of arguments (${arguments.length}) - expects one of (${A[G].C})!`);return A[G].C[arguments.length].apply(this,arguments)},A[G].C=[],A[G].C[N.O]=N}},wg=(G,r,N)=>{if(A.hasOwnProperty(G)){if(N===void 0||A[G].C!==void 0&&A[G].C[N]!==void 0)throw new VA(`Cannot register public name '${G}' twice`);if(RB(G,G),A.hasOwnProperty(N))throw new VA(`Cannot register multiple overloads of a function with the same number of arguments (${N})!`);A[G].C[N]=r}else A[G]=r,N!==void 0&&(A[G].S=N)},Fg=(G,r)=>{for(var N=[],H=0;H<G;H++)N.push(d[r+4*H>>2]);return N},eg,zg=(G,r)=>{var N=[];return function(){if(N.length=0,Object.assign(N,arguments),G.includes("j")){var H=A["dynCall_"+G];H=N&&N.length?H.apply(null,[r].concat(N)):H.call(null,r)}else H=eg.get(r).apply(null,N);return H}},_g=(G,r)=>{G=MA(G);var N=G.includes("j")?zg(G,r):eg.get(r);if(typeof N!="function")throw new VA(`unknown function pointer with signature ${G}: ${r}`);return N},rg,ng=G=>{G=O(G);var r=MA(G);return p(G),r},cB=(G,r)=>{function N(w){h[w]||KA[w]||(xA[w]?xA[w].forEach(N):(H.push(w),h[w]=!0))}var H=[],h={};throw r.forEach(N),new rg(`${G}: `+H.map(ng).join([", "]))},UB=G=>{G=G.trim();const r=G.indexOf("(");return r!==-1?G.substr(0,r):G},$g=(G,r,N)=>{switch(r){case 1:return N?H=>s[H>>0]:H=>y[H>>0];case 2:return N?H=>e[H>>1]:H=>J[H>>1];case 4:return N?H=>u[H>>2]:H=>d[H>>2];default:throw new TypeError(`invalid integer width (${r}): ${G}`)}};function Sg(G){return this.fromWireType(d[G>>2])}for(var Ig=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ng=(G,r,N)=>{var H=r+N;for(N=r;G[N]&&!(N>=H);)++N;if(16<N-r&&G.buffer&&Ig)return Ig.decode(G.subarray(r,N));for(H="";r<N;){var h=G[r++];if(h&128){var w=G[r++]&63;if((h&224)==192)H+=String.fromCharCode((h&31)<<6|w);else{var S=G[r++]&63;h=(h&240)==224?(h&15)<<12|w<<6|S:(h&7)<<18|w<<12|S<<6|G[r++]&63,65536>h?H+=String.fromCharCode(h):(h-=65536,H+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else H+=String.fromCharCode(h)}return H},AB=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,kB=(G,r)=>{for(var N=G>>1,H=N+r/2;!(N>=H)&&J[N];)++N;if(N<<=1,32<N-G&&AB)return AB.decode(y.subarray(G,N));for(N="",H=0;!(H>=r/2);++H){var h=e[G+2*H>>1];if(h==0)break;N+=String.fromCharCode(h)}return N},LB=(G,r,N)=>{if(N??=2147483647,2>N)return 0;N-=2;var H=r;N=N<2*G.length?N/2:G.length;for(var h=0;h<N;++h)e[r>>1]=G.charCodeAt(h),r+=2;return e[r>>1]=0,r-H},JB=G=>2*G.length,IB=(G,r)=>{for(var N=0,H="";!(N>=r/4);){var h=u[G+4*N>>2];if(h==0)break;++N,65536<=h?(h-=65536,H+=String.fromCharCode(55296|h>>10,56320|h&1023)):H+=String.fromCharCode(h)}return H},gg=(G,r,N)=>{if(N??=2147483647,4>N)return 0;var H=r;N=H+N-4;for(var h=0;h<G.length;++h){var w=G.charCodeAt(h);if(55296<=w&&57343>=w){var S=G.charCodeAt(++h);w=65536+((w&1023)<<10)|S&1023}if(u[r>>2]=w,r+=4,r+4>N)break}return u[r>>2]=0,r-H},Rg=G=>{for(var r=0,N=0;N<G.length;++N){var H=G.charCodeAt(N);55296<=H&&57343>=H&&++N,r+=4}return r},oI={},LI=()=>{if(!aI){var G={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"},r;for(r in oI)oI[r]===void 0?delete G[r]:G[r]=oI[r];var N=[];for(r in G)N.push(`${r}=${G[r]}`);aI=N}return aI},aI,uA=[null,[],[]],JI=Array(256),zA=0;256>zA;++zA)JI[zA]=String.fromCharCode(zA);PA=JI,VA=A.BindingError=class extends Error{constructor(G){super(G),this.name="BindingError"}},tg=A.InternalError=class extends Error{constructor(G){super(G),this.name="InternalError"}},Object.assign(sI.prototype,{get(G){return this.F[G]},has(G){return this.F[G]!==void 0},I(G){var r=this.K.pop()||this.F.length;return this.F[r]=G,r},J(G){this.F[G]=void 0,this.K.push(G)}}),_A.F.push({value:void 0},{value:null},{value:!0},{value:!1}),_A.H=_A.F.length,A.count_emval_handles=()=>{for(var G=0,r=_A.H;r<_A.F.length;++r)_A.F[r]!==void 0&&++G;return G},rg=A.UnboundTypeError=((G,r)=>{var N=Ag(r,function(H){this.name=r,this.message=H,H=Error(H).stack,H!==void 0&&(this.stack=this.toString()+`
|
|
4213
|
+
${JSON.stringify(Q)}`)}}class Tg{location;version;loader_;constructor(A){this.location=A.location,this.version=A.version,this.loader_=A.loader}static async openLoader(A,I){let g=xg(I);const B=await wB(A,g),C=KC(B.attrs),E=C.multiscales;if(E.length!==1)throw new Error(`Exactly one multiscale image is supported. Found ${E.length} images.`);const i=E[0];if(i.datasets.length===0)throw new Error("No datasets found in the multiscale image.");g||(g=xg(C.originalVersion));const o=i.datasets.map(y=>qs(A,y.path,g)),a=await Promise.all(o.map(y=>ds(y))),D=a[0].shape,s=i.axes;if(s.length!==D.length)throw new Error(`Mismatch between number of axes (${s.length}) and array shape (${D.length})`);return new Vs({metadata:i,arrays:a,arrayParams:o})}getDimensions(){return this.loader_.getSourceDimensionMap()}getChannelCount(){return this.getDimensions().c?.lods[0].size??1}getLoader(){return this.loader_}static async fromHttp(A){const I=new eI(new hB(A.url)),g=await Tg.openLoader(I,A.version);return new Tg({location:I,version:A.version,loader:g})}static async fromFileSystem(A){const I=new eI(new eC(A.directory),A.path),g=await Tg.openLoader(I,A.version);return new Tg({location:I,version:A.version,loader:g})}}class nB{objects_=[];state_="initialized";attached_=!1;callbacks_=[];opacity_;blendMode;constructor({opacity:A=1,blendMode:I="none"}={}){this.opacity_=pI(A,0,1),this.blendMode=I}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&gA.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=pI(A,0,1)}onEvent(A){}onAttached(A){if(this.attached_)throw new Error(`${this.type} cannot be attached to multiple viewports simultaneously.`);this.attach(A),this.attached_=!0}onDetached(A){this.attached_&&(this.detach(A),this.attached_=!1)}attach(A){}detach(A){}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)}hasMultipleLODs(){return!1}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(g=>g(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_=[]}getUniforms(){return{}}}class Th extends Ug{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})}createVertices(A){const I=new Float32Array(2*A.length*10),g=A.length>=3&&NQ(A[0],A[A.length-1]);let B=0;for(const C of[...Array(A.length).keys()])for(const E of[-1,1]){const i=A[C];I[B++]=i[0],I[B++]=i[1],I[B++]=i[2];const o=C===0?g?A[A.length-2]:A[C]:A[C-1];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const a=C===A.length-1?g?A[1]:A[C]:A[C+1];I[B++]=a[0],I[B++]=a[1],I[B++]=a[2],I[B++]=E}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let g=0;for(let B=0;B<2*A;B+=2)I[g++]=B+0,I[g++]=B+1,I[g++]=B+2,I[g++]=B+2,I[g++]=B+1,I[g++]=B+3;return I}}class Wh extends Ug{constructor(A){if(super(),A.primitive!="triangles"){gA.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){gA.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,g=[],B=(E,i)=>{const o=Math.min(E,i),a=Math.max(E,i);I.has({i0:o,i1:a})||(I.add({i0:o,i1:a}),g.push(o,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],a=C[E+2];B(i,o),B(o,a),B(a,i)}this.indexData_=new Uint32Array(g)}}const bh=nA(0,1,0);class Zh{dirty_=!0;matrix_=QI();rotation_=cQ();translation_=dA();scale_=nA(1,1,1);addRotation(A){Aa(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){ga(this.rotation_,A),this.dirty_=!0}get rotation(){return Ia(this.rotation_)}addTranslation(A){gB(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){rQ(this.translation_,A),this.dirty_=!0}get translation(){return dI(this.translation_)}addScale(A){Po(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){rQ(this.scale_,A),this.dirty_=!0}targetTo(A){NQ(this.translation_,A)&&(A=dI(A),A[2]+=JA);const I=Wo(QI(),this.translation_,A,bh),g=qo(zC(),I);IE(this.rotation_,g),kQ(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return dI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return HB(QI(),this.matrix)}computeMatrix(){po(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Wg extends FQ{wireframeEnabled=!1;wireframeColor=FA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new Zh;geometry_=new Ug;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const g=this.textures_[A];g!==void 0&&this.staleTextures_.push(g),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new Wh(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(){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 Zi extends Wg{color_;width_;constructor({geometry:A,color:I,width:g}){super(),this.geometry=A,this.color_=FA.from(I),this.width_=g,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=FA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width}}}class Ph extends nB{type="AxesLayer";constructor(A){super();const{length:I,width:g}=A;this.addObject(MC({end:[I,0,0],width:g,color:[1,0,0]})),this.addObject(MC({end:[0,I,0],width:g,color:[0,1,0]})),this.addObject(MC({end:[0,0,I],width:g,color:[0,0,1]})),this.setState("ready")}update(){}}function MC(Q){const{end:A,width:I,color:g}=Q,B=new Th([[0,0,0],A]);return new Zi({geometry:B,color:g,width:I})}const Pi=32;function SB(Q,{visible:A,color:I,contrastLimits:g,opacity:B}){return A??=!0,I=I===void 0?FA.WHITE:FA.from(I),B=B===void 0?1:pI(B,0,1),Q!==null?g=Vh(g,Q):g===void 0&&(gA.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),g=[0,1]),{visible:A,color:I,contrastLimits:g,opacity:B}}function HC(Q,A){if(A.length>Pi)throw new Error(`Maximum number of channels is ${Pi}`);return A.map(I=>SB(Q,I))}function Vi(Q,A){if(Q&&Q.length!==A)throw new Error(`channelProps length (${Q.length}) must match source channel count (${A}).`)}function Vh(Q,A){if(Q===void 0)return Sa(A);if(Q[1]<=Q[0])throw new Error(`Contrast limits must be strictly increasing: ${Q}.`);return Q}class Oi extends Ug{constructor(A,I,g,B){super();const C=[],E=[],i=g,o=B,a=i+1,D=o+1,s=A/i,y=I/o;for(let e=0;e<D;++e){const J=e*y;for(let u=0;u<a;++u){const d=u*s,W=u/i,z=e/o,m=[d,J,0],l=[0,0,1],P=[W,z];C.push(...m,...l,...P)}}for(let e=0;e<o;++e)for(let J=0;J<i;++J){const u=J+a*e,d=J+a*(e+1),W=J+1+a*(e+1),z=J+1+a*e;E.push(u,d,z),E.push(d,W,z)}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})}}class vi extends Wg{channels_;zTexCoord=.5;constructor(A,I,g,B=[]){super(),this.geometry=new Oi(A,I,1,1),this.setTexture(0,g),this.channels_=HC(g,B),this.programName=Oh(g)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=HC(this.textures[0],A)}setChannelProperty(A,I,g){const B=SB(this.textures[0],{...this.channels_[A],[I]:g});this.channels_[A]=B}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:g,opacity:B}=this.channels_[0]??SB(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-g[0],ValueScale:1/(g[1]-g[0]),Opacity:B,ZTexCoord:this.zTexCoord}}}function Oh(Q){switch(Q.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function Xi(Q,A,I,g,B=3){switch(Q.type){case"pointerdown":{const C=Q.event;return TA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=Q.event,E=TA(C.clientX,C.clientY);if(Ba(A,E)<B){if(!g)return null;const o=Q.worldPos;return o&&I(o).then(a=>{a!==null&&g({world:o,value:a})}).catch(a=>{gA.error("PointPicking",`Failed to read value: ${a}`)}),null}return A}case"pointercancel":return null;default:return A}}class dC{bins_=new Map;acquire(A){const g=this.bins_.get(A)?.pop();return g&&gA.debug("RenderablePool","Renderable object acquired"),g}release(A,I){let g=this.bins_.get(A);g||(g=[],this.bins_.set(A,g)),g.push(I),gA.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class qC extends nB{type="ImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new dC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new FA(.6,.3,.3),new FA(.3,.6,.4),new FA(.4,.4,.7),new FA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:g,channelProps:B,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_);const I=this.chunkStoreView_.channelCount;if(Vi(this.channelProps_,I),I>1&&this.sliceCoords_.c!==void 0&&this.sliceCoords_.c.length>1)throw new Error(`ImageLayer requires exactly one channel in sliceCoords.c for multi-channel sources (found ${I} channels). Use one layer per channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}update(A){if(!(!A||!this.chunkStoreView_)){this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks();for(const[I,g]of this.visibleChunks_)g.zTexCoord=this.zTexCoordForChunk(I)}}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getImageForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}hasMultipleLODs(){return this.chunkStoreView_?this.chunkStoreView_.lodCount>1:!1}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>qC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Xi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(aQ(A));return g?(g.textures[0].updateWithChunk(A),g.zTexCoord=this.zTexCoordForChunk(A),g.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(g,A),g):this.createImage(A)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A){const I=new vi(A.shape.x,A.shape.y,qI.createWithChunk(A),this.getChannelPropsForChunk(A));return I.zTexCoord=this.zTexCoordForChunk(A),this.updateImageChunk(I,A),I}zSliceIndex(A){const I=this.sliceCoords_.z;if(I===void 0)return 0;const g=(I-A.offset.z)/A.scale.z;return pI(Math.round(g),0,A.shape.z-1)}zTexCoordForChunk(A){return(this.zSliceIndex(A)+.5)/A.shape.z}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])}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[B,C]of this.visibleChunks_){if(B.lod===I!==g)continue;const E=await this.readValueFromChunk(B,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const B=SQ(dA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C<0||C>=A.shape.x||E<0||E>=A.shape.y)return null;const i=this.zSliceIndex(A);return await I.textures[0].readTexel?.(C,E,i)??null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,g)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[g.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,g)=>{I.setChannelProps(this.getChannelPropsForChunk(g))}),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 g=this.visibleChunks_.get(I);g&&(this.pool_.release(aQ(I),g),this.visibleChunks_.delete(I))}}}function aQ(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class vh extends Ug{constructor(A,I,g,B,C,E){super();const i=[],o=[],a=Math.floor(B),D=Math.floor(C),s=Math.floor(E);this.buildFace("z","y","x",-1,-1,g,I,A,s,D,1,i,o),this.buildFace("z","y","x",1,-1,g,I,A,s,D,-1,i,o),this.buildFace("x","z","y",1,1,A,g,I,a,s,1,i,o),this.buildFace("x","z","y",1,-1,A,g,I,a,s,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,g,a,D,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,g,a,D,-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,g,B,C,E,i,o,a,D,s,y,e){const J=E/a,u=i/D,d=E/2,W=i/2,z=o/2*s,m=a+1,l=D+1,P=y.length/8;for(let v=0;v<l;v++){const EA=-W+v*u;for(let sA=0;sA<m;sA++){const DA=-d+sA*J,hA={x:0,y:0,z:0};hA[A]=DA*B,hA[I]=EA*C,hA[g]=z;const yA={x:0,y:0,z:0};yA[g]=s;const mA=sA/a,fA=1-v/D;y.push(hA.x,hA.y,hA.z,yA.x,yA.y,yA.z,mA,fA)}}for(let v=0;v<D;v++)for(let EA=0;EA<a;EA++){const sA=P+EA+m*v,DA=P+EA+m*(v+1),hA=P+(EA+1)+m*(v+1),yA=P+(EA+1)+m*v;e.push(sA,DA,yA,DA,hA,yA)}}}class ji extends Wg{voxelScale=nA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new vh(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=qI.createWithChunk(I),B=this.textures.length;this.setTexture(B,g),this.channelToTextureIndex_.set(A,B);const C=Xh(g.dataType);if(this.programName&&this.programName!==C)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${g.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const g=this.textures[A];if(!(g instanceof qI)){const B=qI.createWithChunk(I);this.setTexture(A,B);return}g.updateWithChunk(I)}clearLoadedChannels(){this.loadedChannels_=new Set}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],g=[0,0,0,0],B=[1,1,1,1],C=[1,1,1,1],E=[],i=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let o=0;o<i&&E.length<4;o++){const a=this.channelToTextureIndex_.get(o);if(a===void 0||!this.loadedChannels_.has(o))continue;const D=this.textures[a],s=SB(D,this.channels_[o]||{});if(!s.visible)continue;const y=E.length;I[y*3]=s.color.rgb[0],I[y*3+1]=s.color.rgb[1],I[y*3+2]=s.color.rgb[2],E.push(a),g[y]=-s.contrastLimits[0],B[y]=1/(s.contrastLimits[1]-s.contrastLimits[0]),A[y]=1,C[y]=s.opacity}return E.reduce((o,a,D)=>(o[`Channel${D}Sampler`]=a,o),{Visible:A,"Color[0]":I,ValueOffset:g,ValueScale:B,ChannelOpacity:C,VoxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const g=this.channelToTextureIndex_.get(A);if(g!==void 0)return this.textures[g]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=HC(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const B=SB(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=B}}function Xh(Q){switch(Q){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function jh(Q,A){const I=A.position,g=dA(),B=dA();return Q.sort((C,E)=>{gB(g,C.boundingBox.max,C.boundingBox.min),BB(g,g,.5),gB(B,E.boundingBox.max,E.boundingBox.min),BB(B,B,.5);const i=$C(I,g),o=$C(I,B);return i-o}),Q}const zh=2;class _h extends nB{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new dC;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}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)}constructor({source:A,sliceCoords:I,policy:g,channelProps:B}){super({blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=g,this.initialChannelProps_=B,this.channelProps_=B,this.setState("initialized")}getOrCreateVolume(A,I){const g=this.currentVolumes_.get(A);if(g){for(const E of I)g.updateVolumeWithChunk(E);return g}const B=Iy(I[0]),C=this.pool_.acquire(B)??new ji;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,B);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.sourcePolicy_),Vi(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,g=Ay(A);if(this.lastLoadedTime_!==I||g.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)g.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));this.clearObjects();for(const[C,E]of g){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i),this.addObject(i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length,this.state!=="ready"&&this.setState("ready")}}updateVolumeTransform(A,I){const g={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([g.x,g.y,g.z]),Qg(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const B={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+B.x,I.offset.y+B.y,I.offset.z+B.z])}releaseAndRemoveVolume(A){A.clearLoadedChannels(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!this.chunkStoreView_)return;if(A===void 0)throw new Error("RenderContext is required for the VolumeLayer update as camera information is used to reorder the chunks.");this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.viewport);const I=A.viewport.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?zh:1,this.updateChunks(),jh(this.objects,A.viewport.camera)}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),RelativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,OpacityMultiplier:this.opacityMultiplier,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function $h(Q){const{x:A,y:I,z:g,t:B}=Q.chunkIndex;return`${A}:${I}:${g}:${B}`}function Ay(Q){const A=new Map;for(const I of Q){const g=$h(I);let B=A.get(g);B||(B=[],A.set(g,B)),B.push(I)}return A}function Iy(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class DQ extends JQ{data_;width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g}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 g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==g){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new DQ(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}const gy=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function By(Q){if(Q.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${Q.dataFormat}`);if(!gy.has(Q.dataType))throw new Error(`Image data type must be unsigned, instead found: ${Q.dataType}`);return Q}class zi extends Wg{outlineSelected_;selectedValue_;zTexCoord=.5;constructor(A){super(),this.geometry=new Oi(A.width,A.height,1,1),this.setTexture(0,By(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const g=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,g),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,ZTexCoord:this.zTexCoord}}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(B=>B.rgba).map(B=>Math.round(B*255))),g=new DQ(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,FA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,FA.TRANSPARENT],...A]));const I=Array.from(A.keys()),g=Array.from(A.values()).map(E=>E.packed),B=A.size,C=new Uint32Array(B*2);return C.set(I,0),C.set(g,B),new DQ(C,B,2)}}const Qy=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Cy(Q){return Q=Q??new Map,new Map(Array.from(Q.entries()).map(([A,I])=>[A,FA.from(I)]))}function Ey(Q){return Q=Q??Qy,Q.map(FA.from)}class lC{lookupTable;cycle;constructor(A={}){this.lookupTable=Cy(A.lookupTable),this.cycle=Ey(A.cycle)}}class fC extends nB{type="LabelLayer";source_;sliceCoords_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new dC;colorMap_;selectedValue_=null;policy_;chunkStoreView_;pointerDownPos_=null;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:g,colorMap:B={},onPickValue:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.colorMap_=new lC(B),this.onPickValue_=C,this.outlineSelected_=E}attach(A){if(this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}update(A){if(!(!A||!this.chunkStoreView_)){this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks();for(const[I,g]of this.visibleChunks_)g.zTexCoord=this.zTexCoordForChunk(I)}}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getLabelForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>fC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Xi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new lC(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[B,C]of this.visibleChunks_){if(B.lod===I!==g)continue;const E=await this.readValueFromChunk(B,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const B=SQ(dA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C<0||C>=A.shape.x||E<0||E>=A.shape.y)return null;const i=this.zSliceIndex(A);return await I.textures[0].readTexel?.(C,E,i)??null}getLabelForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(aQ(A));return g?(g.textures[0].updateWithChunk(A),g.zTexCoord=this.zTexCoordForChunk(A),g.setColorMap(this.colorMap_),g.setSelectedValue(this.selectedValue_),this.updateLabelChunk(g,A),g):this.createLabel(A)}createLabel(A){const I=new zi({width:A.shape.x,height:A.shape.y,imageData:qI.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.zTexCoord=this.zTexCoordForChunk(A),this.updateLabelChunk(I,A),I}zSliceIndex(A){const I=this.sliceCoords_.z;if(I===void 0)return 0;const g=(I-A.offset.z)/A.scale.z;return pI(Math.round(g),0,A.shape.z-1)}zTexCoordForChunk(A){return(this.zSliceIndex(A)+.5)/A.shape.z}updateLabelChunk(A,I){A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(aQ(I),g),this.visibleChunks_.delete(I))}}}class pC extends JQ{data_;width_;height_;depth_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=A.length/(I*g)}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 g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===g)return;const B=A.shape.x,C=A.shape.y,E=g.length/(B*C);if(this.width!=B||this.height!=C||this.depth_!=E||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new pC(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}const _i={circle:0,square:1,triangle:2};class iy extends Wg{constructor(A){super(),this.programName="points";const I=A.flatMap(B=>{const C=FA.from(B.color);return[B.position[0],B.position[1],B.position[2],C.r,C.g,C.b,C.a,B.size,_i[B.marker]]}),g=new Ug(I,[],"points");g.addAttribute({type:"position",itemSize:3,offset:0}),g.addAttribute({type:"color",itemSize:4,offset:g.strideBytes}),g.addAttribute({type:"size",itemSize:1,offset:g.strideBytes}),g.addAttribute({type:"marker",itemSize:1,offset:g.strideBytes}),this.geometry=g,this.setTexture(0,oy())}get type(){return"Points"}}let uC;function oy(){return uC||(uC=ay()),uC}function ay(){const Q=a=>{const D=new Float32Array(a*a);return D.fill(1),D},A=a=>{const D=new Float32Array(a*a);for(let s=0;s<a;s++)for(let y=0;y<a;y++)(s-a/2)**2+(y-a/2)**2<(a/2)**2&&(D[s*a+y]=1);return D},I=a=>{const D=new Float32Array(a*a);for(let s=0;s<a;s++)for(let y=0;y<a;y++)y>=(a-s)/2&&y<=(a+s)/2&&(D[s*a+y]=1);return D},C={circle:A(256),square:Q(256),triangle:I(256)},E=Object.keys(C).length,i=new Float32Array(E*65536);for(const[a,D]of Object.entries(C))i.set(D,_i[a]*65536);const o=new pC(i,256,256);return o.wrapR="clamp_to_edge",o.wrapS="clamp_to_edge",o.wrapT="clamp_to_edge",o}class $i{radius;phi;theta;constructor(A,I,g){this.radius=A,this.phi=I,this.theta=g}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)}}const mC=-1,Ao=0,Dy=1,Io=.009,sy=.001,hy=9e-4,yy=.5,ty=60;class Gy{camera_;orbitVelocity_=new $i(0,0,0);panVelocity_=dA();currPos_;currCenter_=dA();dampingFactor_;currMouseButton_=mC;constructor(A,I){this.camera_=A,this.currPos_=new $i(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&rQ(this.currCenter_,I.target),this.dampingFactor_=pI(I?.dampingFactor??yy,0,1),this.updateCamera()}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&NQ(this.panVelocity_,nA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,gB(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-JA;this.currPos_.theta=pI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const g=Math.pow(1-this.dampingFactor_,A*ty);this.orbitVelocity_.phi*=g,this.orbitVelocity_.theta*=g,this.orbitVelocity_.radius*=g,BB(this.panVelocity_,this.panVelocity_,g),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==mC)return;const I=A.event,g=I.movementX??0,B=I.movementY??0,C=this.currMouseButton_===Ao&&!I.shiftKey,E=this.currMouseButton_===Ao&&I.shiftKey||this.currMouseButton_===Dy;C&&this.orbit(g,B),E&&this.pan(g,B)}onWheel(A){const I=A.event;I.preventDefault();const g=I.deltaY??0;this.zoom(g)}onPointerEnd(A){this.currMouseButton_=mC;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*Io,this.orbitVelocity_.theta+=I*Io}pan(A,I){const g=this.currPos_.radius*sy,B=dA();_C(B,B,this.camera_.right,A),_C(B,B,this.camera_.up,I),BB(B,B,g),RQ(this.panVelocity_,this.panVelocity_,B)}zoom(A){this.orbitVelocity_.radius+=A*hy}updateCamera(){const A=gB(dA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<JA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<JA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<JA&&(this.orbitVelocity_.radius=0),eQ(this.panVelocity_)<JA&&Oo(this.panVelocity_)}}class bg{normal;signedDistance;constructor(A=nA(0,1,0),I=0){this.normal=dI(A),this.signedDistance=I}set(A,I){this.normal=dI(A),this.signedDistance=I}signedDistanceToPoint(A){return AE(this.normal,A)+this.signedDistance}normalize(){const A=eQ(this.normal);if(A>0){const I=1/A;BB(this.normal,this.normal,I),this.signedDistance*=I}}}class wy{planes_;constructor(A){this.planes_=[new bg(dA(),0),new bg(dA(),0),new bg(dA(),0),new bg(dA(),0),new bg(dA(),0),new bg(dA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=dA();this.planes_[0].set(Qg(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(Qg(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(Qg(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(Qg(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(Qg(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(Qg(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const g of this.planes_)g.normalize()}intersectsWithBox3(A){const I=dA();for(const g of this.planes_){const B=g.normal;if(I[0]=B[0]>0?A.max[0]:A.min[0],I[1]=B[1]>0?A.max[1]:A.min[1],I[2]=B[2]>0?A.max[2]:A.min[2],g.signedDistanceToPoint(I)<0)return!1}return!0}}class go extends Wg{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 wy(WI(QI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=dB(A[0],A[1],A[2],1),g=HB(QI(),this.projectionMatrix_),B=QB(cg(),I,g);zo(B,B,1/B[3]);const C=QB(cg(),B,this.transform.matrix);return nA(C[0],C[1],C[2])}}const Bo=1.77,Qo=128,Co=128/Bo;class Fy extends go{width_=Qo;height_=Co;viewportAspectRatio_=Bo;viewportSize_=[Qo,Co];constructor(A,I,g,B,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,B,g),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,g,B){this.width_=Math.abs(I-A),this.height_=Math.abs(B-g),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(g+B);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=dB(-1,-1,0,1),I=dB(1,1,0,1);const g=WI(QI(),this.projectionMatrix,this.viewMatrix),B=HB(QI(),g);return A=QB(cg(),A,B),I=QB(cg(),I,B),new CI(TA(A[0],A[1]),TA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,g=A/I;let B=.5*A,C=.5*I;this.viewportAspectRatio_>g?B*=this.viewportAspectRatio_/g:C*=g/this.viewportAspectRatio_,this.viewportSize_=[2*B,2*C],To(this.projectionMatrix_,-B,B,-C,C,this.near_,this.far_)}}const Eo=0;class ey{camera_;dragActive_=!1;dragStart_=dA();constructor(A){this.camera_=A}get isMoving(){return this.dragActive_}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}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const g=dI(A.worldPos),B=I.deltaY<0?1.05:.95;this.camera_.zoom(B);const C=this.camera_.clipToWorld(A.clipPos),E=RQ(dA(),g,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==Eo||(this.dragStart_=dI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=RQ(dA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==Eo||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}const ry=60,ny=1.77,sQ=.1,xC=180-sQ;class Sy extends go{fov_;aspectRatio_;constructor(A={}){const{fov:I=ry,aspectRatio:g=ny,near:B=.1,far:C=1e4,position:E=nA(0,0,0)}=A;if(I<sQ||I>xC)throw new Error(`Invalid field of view: ${I}, must be in [${sQ}, ${xC}] degrees`);super(),this.fov_=I,this.aspectRatio_=g,this.near_=B,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(sQ,Math.min(xC,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){mo(this.projectionMatrix_,Ho(this.fov),this.aspectRatio_,this.near_,this.far_)}}const io=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function hQ(Q){Uy(Q);const A={x:Q.prefetch.x,y:Q.prefetch.y,z:Q.prefetch.z??0,t:Q.prefetch.t??0},I=Object.freeze(io.reduce((C,E)=>{const i=Q.priorityOrder.indexOf(E);return C[E]=i,C},{})),g={min:Q.lod?.min??0,max:Q.lod?.max??Number.MAX_SAFE_INTEGER,bias:Q.lod?.bias??.5},B={profile:Q.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...Q.priorityOrder]),priorityMap:I,lod:g};return Object.freeze(B)}function Ny(Q={}){return hQ(TC({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},Q))}function Ry(Q={}){return hQ(TC({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"]},Q))}function cy(Q={}){return hQ(TC({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},Q))}function Uy(Q){for(const[g,B]of Object.entries(Q.prefetch))if(B!==void 0&&B<0)throw new Error(`prefetch.${g} must be a non-negative number`);const A=Q.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=Q.priorityOrder;if(I.length!==io.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function TC(Q,A={}){return{profile:A.profile??Q.profile,prefetch:{...Q.prefetch,...A.prefetch??{}},lod:{...Q.lod,...A.lod??{}},priorityOrder:A.priorityOrder??Q.priorityOrder}}var WC=(()=>{for(var Q=new Uint8Array(128),A=0;A<64;A++)Q[A<26?A+65:A<52?A+71:A<62?A-4:A*4-205]=A;return I=>{for(var g=I.length,B=new Uint8Array((g-(I[g-1]=="=")-(I[g-2]=="="))*3/4|0),C=0,E=0;C<g;){var i=Q[I.charCodeAt(C++)],o=Q[I.charCodeAt(C++)],a=Q[I.charCodeAt(C++)],D=Q[I.charCodeAt(C++)];B[E++]=i<<2|o>>4,B[E++]=o<<4|a>>2,B[E++]=a<<6|D}return B}})(),ky=(typeof document<"u"&&document.currentScript&&document.currentScript.src,function(Q={}){var A=Q,I,g;A.ready=new Promise((G,r)=>{I=G,g=r});var B=Object.assign({},A),C="./this.program",E=A.print||console.log.bind(console),i=A.printErr||console.error.bind(console);Object.assign(A,B),B=null,A.thisProgram&&(C=A.thisProgram);var o;A.wasmBinary&&(o=A.wasmBinary),typeof WebAssembly!="object"&&hA("no native wasm support detected");var a,D=!1,s,y,e,J,u,d,W,z;function m(){var G=a.buffer;A.HEAP8=s=new Int8Array(G),A.HEAP16=e=new Int16Array(G),A.HEAPU8=y=new Uint8Array(G),A.HEAPU16=J=new Uint16Array(G),A.HEAP32=u=new Int32Array(G),A.HEAPU32=d=new Uint32Array(G),A.HEAPF32=W=new Float32Array(G),A.HEAPF64=z=new Float64Array(G)}var l=[],P=[],v=[];function EA(){var G=A.preRun.shift();l.unshift(G)}var sA=0,DA=null;function hA(G){throw A.onAbort?.(G),G="Aborted("+G+")",i(G),D=!0,G=new WebAssembly.RuntimeError(G+". Build with -sASSERTIONS for more info."),g(G),G}var yA=G=>G.startsWith("data:application/octet-stream;base64,"),mA=G=>G.startsWith("file://"),fA;if(fA="blosc_codec.wasm",!yA(fA)){var NA=fA;fA=A.locateFile?A.locateFile(NA,""):""+NA}function mI(G){return Promise.resolve().then(()=>{if(G==fA&&o)var r=new Uint8Array(o);else throw"both async and sync fetching of the wasm failed";return r})}function kI(G,r,N){return mI(G).then(H=>WebAssembly.instantiate(H,r)).then(H=>H).then(N,H=>{i(`failed to asynchronously prepare wasm: ${H}`),hA(H)})}function xI(G,r){var N=fA;return o||typeof WebAssembly.instantiateStreaming!="function"||yA(N)||mA(N)||typeof fetch!="function"?kI(N,G,r):fetch(N,{credentials:"same-origin"}).then(H=>WebAssembly.instantiateStreaming(H,G).then(r,function(h){return i(`wasm streaming compile failed: ${h}`),i("falling back to ArrayBuffer instantiation"),kI(N,G,r)}))}var zI=G=>{for(;0<G.length;)G.shift()(A)};function _I(G){this.H=G-24,this.N=function(r){d[this.H+4>>2]=r},this.M=function(r){d[this.H+8>>2]=r},this.I=function(r,N){this.J(),this.N(r),this.M(N)},this.J=function(){d[this.H+16>>2]=0}}var $A=0,PA,MA=G=>{for(var r="";y[G];)r+=PA[y[G++]];return r},jA={},KA={},xA={},VA,yg=G=>{throw new VA(G)},tg,GI=(G,r)=>{function N(Y){if(Y=r(Y),Y.length!==H.length)throw new tg("Mismatched type converter count");for(var k=0;k<H.length;++k)HA(H[k],Y[k])}var H=[];H.forEach(function(Y){xA[Y]=G});var h=Array(G.length),w=[],S=0;G.forEach((Y,k)=>{KA.hasOwnProperty(Y)?h[k]=KA[Y]:(w.push(Y),jA.hasOwnProperty(Y)||(jA[Y]=[]),jA[Y].push(()=>{h[k]=KA[Y],++S,S===w.length&&N(h)}))}),w.length===0&&N(h)};function DI(G,r,N={}){var H=r.name;if(!G)throw new VA(`type "${H}" must have a positive integer typeid pointer`);if(KA.hasOwnProperty(G)){if(N.P)return;throw new VA(`Cannot register type '${H}' twice`)}KA[G]=r,delete xA[G],jA.hasOwnProperty(G)&&(r=jA[G],delete jA[G],r.forEach(h=>h()))}function HA(G,r,N={}){if(!("argPackAdvance"in r))throw new TypeError("registerType registeredInstance requires argPackAdvance");DI(G,r,N)}function sI(){this.F=[void 0],this.K=[]}var _A=new sI,TI=G=>{G>=_A.H&&--_A.get(G).L===0&&_A.J(G)},vg=G=>{switch(G){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return _A.I({L:1,value:G})}};function $I(G){return this.fromWireType(u[G>>2])}var Gg=(G,r)=>{switch(r){case 4:return function(N){return this.fromWireType(W[N>>2])};case 8:return function(N){return this.fromWireType(z[N>>3])};default:throw new TypeError(`invalid float width (${r}): ${G}`)}},Ag=(G,r)=>Object.defineProperty(r,"name",{value:G}),Xg=G=>{for(;G.length;){var r=G.pop();G.pop()(r)}};function jg(G){for(var r=1;r<G.length;++r)if(G[r]!==null&&G[r].G===void 0)return!0;return!1}function NB(G){var r=Function;if(!(r instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof r} which is not a function`);var N=Ag(r.name||"unknownFunctionName",function(){});return N.prototype=r.prototype,N=new N,G=r.apply(N,G),G instanceof Object?G:N}var RB=(G,r)=>{if(A[G].C===void 0){var N=A[G];A[G]=function(){if(!A[G].C.hasOwnProperty(arguments.length))throw new VA(`Function '${r}' called with an invalid number of arguments (${arguments.length}) - expects one of (${A[G].C})!`);return A[G].C[arguments.length].apply(this,arguments)},A[G].C=[],A[G].C[N.O]=N}},wg=(G,r,N)=>{if(A.hasOwnProperty(G)){if(N===void 0||A[G].C!==void 0&&A[G].C[N]!==void 0)throw new VA(`Cannot register public name '${G}' twice`);if(RB(G,G),A.hasOwnProperty(N))throw new VA(`Cannot register multiple overloads of a function with the same number of arguments (${N})!`);A[G].C[N]=r}else A[G]=r,N!==void 0&&(A[G].S=N)},Fg=(G,r)=>{for(var N=[],H=0;H<G;H++)N.push(d[r+4*H>>2]);return N},eg,zg=(G,r)=>{var N=[];return function(){if(N.length=0,Object.assign(N,arguments),G.includes("j")){var H=A["dynCall_"+G];H=N&&N.length?H.apply(null,[r].concat(N)):H.call(null,r)}else H=eg.get(r).apply(null,N);return H}},_g=(G,r)=>{G=MA(G);var N=G.includes("j")?zg(G,r):eg.get(r);if(typeof N!="function")throw new VA(`unknown function pointer with signature ${G}: ${r}`);return N},rg,ng=G=>{G=O(G);var r=MA(G);return p(G),r},cB=(G,r)=>{function N(w){h[w]||KA[w]||(xA[w]?xA[w].forEach(N):(H.push(w),h[w]=!0))}var H=[],h={};throw r.forEach(N),new rg(`${G}: `+H.map(ng).join([", "]))},UB=G=>{G=G.trim();const r=G.indexOf("(");return r!==-1?G.substr(0,r):G},$g=(G,r,N)=>{switch(r){case 1:return N?H=>s[H>>0]:H=>y[H>>0];case 2:return N?H=>e[H>>1]:H=>J[H>>1];case 4:return N?H=>u[H>>2]:H=>d[H>>2];default:throw new TypeError(`invalid integer width (${r}): ${G}`)}};function Sg(G){return this.fromWireType(d[G>>2])}for(var Ig=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ng=(G,r,N)=>{var H=r+N;for(N=r;G[N]&&!(N>=H);)++N;if(16<N-r&&G.buffer&&Ig)return Ig.decode(G.subarray(r,N));for(H="";r<N;){var h=G[r++];if(h&128){var w=G[r++]&63;if((h&224)==192)H+=String.fromCharCode((h&31)<<6|w);else{var S=G[r++]&63;h=(h&240)==224?(h&15)<<12|w<<6|S:(h&7)<<18|w<<12|S<<6|G[r++]&63,65536>h?H+=String.fromCharCode(h):(h-=65536,H+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else H+=String.fromCharCode(h)}return H},AB=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,kB=(G,r)=>{for(var N=G>>1,H=N+r/2;!(N>=H)&&J[N];)++N;if(N<<=1,32<N-G&&AB)return AB.decode(y.subarray(G,N));for(N="",H=0;!(H>=r/2);++H){var h=e[G+2*H>>1];if(h==0)break;N+=String.fromCharCode(h)}return N},LB=(G,r,N)=>{if(N??=2147483647,2>N)return 0;N-=2;var H=r;N=N<2*G.length?N/2:G.length;for(var h=0;h<N;++h)e[r>>1]=G.charCodeAt(h),r+=2;return e[r>>1]=0,r-H},JB=G=>2*G.length,IB=(G,r)=>{for(var N=0,H="";!(N>=r/4);){var h=u[G+4*N>>2];if(h==0)break;++N,65536<=h?(h-=65536,H+=String.fromCharCode(55296|h>>10,56320|h&1023)):H+=String.fromCharCode(h)}return H},gg=(G,r,N)=>{if(N??=2147483647,4>N)return 0;var H=r;N=H+N-4;for(var h=0;h<G.length;++h){var w=G.charCodeAt(h);if(55296<=w&&57343>=w){var S=G.charCodeAt(++h);w=65536+((w&1023)<<10)|S&1023}if(u[r>>2]=w,r+=4,r+4>N)break}return u[r>>2]=0,r-H},Rg=G=>{for(var r=0,N=0;N<G.length;++N){var H=G.charCodeAt(N);55296<=H&&57343>=H&&++N,r+=4}return r},oI={},LI=()=>{if(!aI){var G={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"},r;for(r in oI)oI[r]===void 0?delete G[r]:G[r]=oI[r];var N=[];for(r in G)N.push(`${r}=${G[r]}`);aI=N}return aI},aI,uA=[null,[],[]],JI=Array(256),zA=0;256>zA;++zA)JI[zA]=String.fromCharCode(zA);PA=JI,VA=A.BindingError=class extends Error{constructor(G){super(G),this.name="BindingError"}},tg=A.InternalError=class extends Error{constructor(G){super(G),this.name="InternalError"}},Object.assign(sI.prototype,{get(G){return this.F[G]},has(G){return this.F[G]!==void 0},I(G){var r=this.K.pop()||this.F.length;return this.F[r]=G,r},J(G){this.F[G]=void 0,this.K.push(G)}}),_A.F.push({value:void 0},{value:null},{value:!0},{value:!1}),_A.H=_A.F.length,A.count_emval_handles=()=>{for(var G=0,r=_A.H;r<_A.F.length;++r)_A.F[r]!==void 0&&++G;return G},rg=A.UnboundTypeError=((G,r)=>{var N=Ag(r,function(H){this.name=r,this.message=H,H=Error(H).stack,H!==void 0&&(this.stack=this.toString()+`
|
|
4214
4214
|
`+H.replace(/^Error(:[^\n]*)?\n/,""))});return N.prototype=Object.create(G.prototype),N.prototype.constructor=N,N.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},N})(Error,"UnboundTypeError");var n={p:(G,r,N)=>{throw new _I(G).I(r,N),$A=G,$A},o:()=>{},l:(G,r,N,H)=>{r=MA(r),HA(G,{name:r,fromWireType:function(h){return!!h},toWireType:function(h,w){return w?N:H},argPackAdvance:8,readValueFromPointer:function(h){return this.fromWireType(y[h])},G:null})},k:(G,r)=>{r=MA(r),HA(G,{name:r,fromWireType:N=>{if(!N)throw new VA("Cannot use deleted val. handle = "+N);var H=_A.get(N).value;return TI(N),H},toWireType:(N,H)=>vg(H),argPackAdvance:8,readValueFromPointer:$I,G:null})},i:(G,r,N)=>{r=MA(r),HA(G,{name:r,fromWireType:H=>H,toWireType:(H,h)=>h,argPackAdvance:8,readValueFromPointer:Gg(r,N),G:null})},d:(G,r,N,H,h,w,S)=>{var Y=Fg(r,N);G=MA(G),G=UB(G),h=_g(H,h),wg(G,function(){cB(`Cannot call ${G} due to unbound types`,Y)},r-1),GI(Y,function(k){var x=G,b=G;k=[k[0],null].concat(k.slice(1));var V=h,T=k.length;if(2>T)throw new VA("argTypes array size mismatch! Must at least get return value and 'this' types!");var BA=k[1]!==null&&!1,iA=jg(k),AI=k[0].name!=="void";V=[yg,V,w,Xg,k[0],k[1]];for(var tA=0;tA<T-2;++tA)V.push(k[tA+2]);if(!iA)for(tA=BA?1:2;tA<k.length;++tA)k[tA].G!==null&&V.push(k[tA].G);iA=jg(k),tA=k.length;var OA="",SI="";for(T=0;T<tA-2;++T)OA+=(T!==0?", ":"")+"arg"+T,SI+=(T!==0?", ":"")+"arg"+T+"Wired";OA=`
|
|
4215
4215
|
return function (${OA}) {
|
|
4216
4216
|
if (arguments.length !== ${tA-2}) {
|