@idetik/core 0.32.4 → 0.32.6

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.
@@ -4218,7 +4218,7 @@ return ret;
4218
4218
  `,Li=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",ki],{type:"text/javascript;charset=utf-8"});function Ps(Q){let A;try{if(A=Li&&(self.URL||self.webkitURL).createObjectURL(Li),!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(ki),{type:"module",name:Q?.name})}}const Vs=Math.max(1,navigator.hardwareConcurrency-2);let UI=[],Os=0,Ji=0;const Dg=new Map,CQ=new Set;function Yi(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 vs(Q,A){const{id:I,success:g}=Q.data,B=Dg.get(I);if(!B){CQ.has(I)?CQ.delete(I):gA.warn("ZarrWorker",`Received response for unknown message ID ${I}:`,Q.data);return}Dg.delete(I),B.abortListener&&B.abortSignal&&B.abortSignal.removeEventListener("abort",B.abortListener);const C=Yi(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 Ki(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=Yi(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 Dg.entries())C.workerId===g&&(C.reject(new Error(`Worker error: ${Q.message}`)),Dg.delete(B));try{const B=Mi();UI.push({worker:B,pendingCount:0,workerId:Ji++}),gA.debug("ZarrWorker","Replacement worker created successfully")}catch(B){gA.error("ZarrWorker","Failed to create replacement worker",B)}}function Mi(){const Q=new Ps;return Q.addEventListener("message",A=>vs(A,Q)),Q.addEventListener("error",A=>Ki(A,Q)),Q.addEventListener("messageerror",A=>Ki(A,Q)),Q}function Xs(){if(UI.length===0)throw new Error("Worker pool is not initialized");return UI.sort((Q,A)=>Q.pendingCount-A.pendingCount)[0]}async function js(Q,A,I,g){return new Promise((B,C)=>{const E=Xs(),i=Os++,o={resolve:B,reject:C,workerId:E.workerId};if(Dg.set(i,o),g?.signal){const a=()=>{E.worker.postMessage({id:i,type:"cancel"}),Dg.delete(i),CQ.add(i),E.pendingCount--,C(new DOMException("Operation was aborted","AbortError"))};if(g.signal.aborted){a(),CQ.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 zs(){if(!(UI.length>0))try{for(let Q=0;Q<Vs;Q++){const A=Mi();UI.push({worker:A,pendingCount:0,workerId:Ji++})}gA.debug("ZarrWorker",`Initialized worker pool with ${UI.length} workers`)}catch{gA.warn("ZarrWorker","Failed to create workers - clearing pool"),$s();return}}async function _s(Q,A,I,g,B){zs();try{return await js(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(!xD(E.data))throw new Error(`Unsupported chunk data type: ${E.data.constructor.name}`);return bs(E.data,E.shape,E.stride,g)}}function $s(){for(const Q of UI)Q.worker.terminate();UI=[],Dg.clear()}class Ah{metadata_;arrays_;arrayParams_;dimensions_;bytesPerElement_;constructor(A){this.metadata_=A.metadata,this.arrays_=A.arrays,this.arrayParams_=A.arrayParams,this.dimensions_=gh(this.metadata_,this.arrays_),this.bytesPerElement_=Ih(this.arrays_[0].dtype)}getSourceDimensionMap(){return this.dimensions_}getBytesPerElement(){return this.bytesPerElement_}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 _s(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,uD(A,a)}}const di={int8:1,uint8:1,int16:2,uint16:2,int32:4,uint32:4,float32:4};function Ih(Q){const A=di[Q];if(A===void 0)throw new Error(`Unsupported zarr dtype "${Q}". Supported dtypes: ${Object.keys(di).join(", ")}`);return A}function gh(Q,A){const I=Q.axes.map(s=>s.name),g=Q.axes.length,B=Hi(I,"x"),C=Hi(I,"y"),E=(s,y)=>{const w=[];for(let k=0;k<Q.datasets.length;k++){const f=Q.datasets[k],d=A[k],T=f.coordinateTransformations[0].scale,z=f.coordinateTransformations.length===2?f.coordinateTransformations[1].translation:new Array(g).fill(0);w.push({size:d.shape[y],chunkSize:d.chunks[y],scale:T[y],translation:z[y]})}if(Q.axes[y].type==="space"&&Qh(w))for(const k of w)k.translation-=.5*k.scale;return{name:s,index:y,unit:Q.axes[y].unit,lods:w}},i={x:E(I[B],B),y:E(I[C],C),numLods:A.length},o=EQ(I,"z");o!==-1&&(i.z=E(I[o],o));const a=EQ(I,"c");a!==-1&&(i.c=E(I[a],a));const D=EQ(I,"t");return D!==-1&&(i.t=E(I[D],D)),i}function Bh(Q,A){return Q.toLowerCase()===A.toLowerCase()}function Hi(Q,A){const I=EQ(Q,A);if(I===-1)throw new Error(`Could not find "${A}" dimension in [${Q.join(", ")}]`);return I}function EQ(Q,A){return Q.findIndex(I=>Bh(I,A))}function Qh(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 nA;(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})(nA||(nA={}));var qi;(function(Q){Q.mergeShapes=(A,I)=>({...A,...I})})(qi||(qi={}));const $=nA.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),bI=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}},P=nA.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 pI 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 pI))throw new Error(`Not a ZodError: ${A}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,nA.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()}}pI.create=Q=>new pI(Q);const SC=(Q,A)=>{let I;switch(Q.code){case P.invalid_type:Q.received===$.undefined?I="Required":I=`Expected ${Q.expected}, received ${Q.received}`;break;case P.invalid_literal:I=`Invalid literal value, expected ${JSON.stringify(Q.expected,nA.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:I=`Unrecognized key(s) in object: ${nA.joinValues(Q.keys,", ")}`;break;case P.invalid_union:I="Invalid input";break;case P.invalid_union_discriminator:I=`Invalid discriminator value. Expected ${nA.joinValues(Q.options)}`;break;case P.invalid_enum_value:I=`Invalid enum value. Expected ${nA.joinValues(Q.options)}, received '${Q.received}'`;break;case P.invalid_arguments:I="Invalid function arguments";break;case P.invalid_return_type:I="Invalid function return type";break;case P.invalid_date:I="Invalid date";break;case P.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}"`:nA.assertNever(Q.validation):Q.validation!=="regex"?I=`Invalid ${Q.validation}`:I="Invalid";break;case P.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 P.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 P.custom:I="Invalid input";break;case P.invalid_intersection_types:I="Intersection results could not be merged";break;case P.not_multiple_of:I=`Number must be a multiple of ${Q.multipleOf}`;break;case P.not_finite:I="Number must be finite";break;default:I=A.defaultError,nA.assertNever(Q)}return{message:I}};let Ch=SC;function Eh(){return Ch}const ih=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=Eh(),g=ih({issueData:A,data:Q.data,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,I,I===SC?void 0:SC].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"}),SB=Q=>({status:"dirty",value:Q}),nI=Q=>({status:"valid",value:Q}),li=Q=>Q.status==="aborted",fi=Q=>Q.status==="dirty",dg=Q=>Q.status==="valid",iQ=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 ZI{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 pi=(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 pI(Q.common.issues);return this._error=I,this._error}}};function tA(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 bI(A.data)}_getOrReturnCtx(A,I){return I||{common:A.parent.common,data:A.data,parsedType:bI(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:bI(A.data),schemaErrorMap:this._def.errorMap,path:A.path,parent:A.parent}}}_parseSync(A){const I=this._parse(A);if(iQ(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:bI(A)},B=this._parseSync({data:A,path:g.path,parent:g});return pi(g,B)}"~validate"(A){const I={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:bI(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:bI(A)},B=this._parse({data:A,path:g.path,parent:g}),C=await(iQ(B)?B:Promise.resolve(B));return pi(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:P.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 fg({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 OI.create(this,this._def)}nullable(){return pg.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dI.create(this)}promise(){return sQ.create(this,this._def)}or(A){return aQ.create([this,A],this._def)}and(A){return DQ.create(this,A,this._def)}transform(A){return new fg({...tA(this._def),schema:this,typeName:aA.ZodEffects,effect:{type:"transform",transform:A}})}default(A){const I=typeof A=="function"?A:()=>A;return new LC({...tA(this._def),innerType:this,defaultValue:I,typeName:aA.ZodDefault})}brand(){return new Kh({typeName:aA.ZodBranded,type:this,...tA(this._def)})}catch(A){const I=typeof A=="function"?A:()=>A;return new JC({...tA(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 YC.create(this,A)}readonly(){return KC.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const oh=/^c[^\s-]{8,}$/i,ah=/^[0-9a-z]+$/,Dh=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sh=/^[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,hh=/^[a-z0-9_-]{21}$/i,yh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,th=/^[-+]?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)?)??$/,Gh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,eh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let NC;const wh=/^(?:(?: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])$/,Fh=/^(?:(?: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])$/,rh=/^(([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]))$/,nh=/^(([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])$/,Sh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Nh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ui="((\\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])))",Rh=new RegExp(`^${ui}$`);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 ch(Q){return new RegExp(`^${mi(Q)}$`)}function Uh(Q){let A=`${ui}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 kh(Q,A){return!!((A==="v4"||!A)&&wh.test(Q)||(A==="v6"||!A)&&rh.test(Q))}function Lh(Q,A){if(!yh.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 Jh(Q,A){return!!((A==="v4"||!A)&&Fh.test(Q)||(A==="v6"||!A)&&nh.test(Q))}class PI 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:P.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:P.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:P.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:P.too_big,maximum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}):i&&j(B,{code:P.too_small,minimum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}),g.dirty())}else if(C.kind==="email")Gh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"email",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="emoji")NC||(NC=new RegExp(eh,"u")),NC.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"emoji",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="uuid")sh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"uuid",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="nanoid")hh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"nanoid",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="cuid")oh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"cuid",code:P.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:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="ulid")Dh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"ulid",code:P.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:P.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:P.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:P.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:P.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:P.invalid_string,validation:{endsWith:C.value},message:C.message}),g.dirty()):C.kind==="datetime"?Uh(C).test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{code:P.invalid_string,validation:"datetime",message:C.message}),g.dirty()):C.kind==="date"?Rh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{code:P.invalid_string,validation:"date",message:C.message}),g.dirty()):C.kind==="time"?ch(C).test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{code:P.invalid_string,validation:"time",message:C.message}),g.dirty()):C.kind==="duration"?th.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"duration",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="ip"?kh(A.data,C.version)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"ip",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="jwt"?Lh(A.data,C.alg)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"jwt",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="cidr"?Jh(A.data,C.version)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"cidr",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="base64"?Sh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"base64",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="base64url"?Nh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"base64url",code:P.invalid_string,message:C.message}),g.dirty()):nA.assertNever(C);return{status:g.value,value:A.data}}_regex(A,I,g){return this.refinement(B=>A.test(B),{validation:I,code:P.invalid_string,...AA.errToObj(g)})}_addCheck(A){return new PI({...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 PI({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new PI({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new PI({...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}}PI.create=Q=>new PI({checks:[],typeName:aA.ZodString,coerce:Q?.coerce??!1,...tA(Q)});function Yh(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 Hg 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:P.invalid_type,expected:$.number,received:C.parsedType}),oA}let g;const B=new tI;for(const C of this._def.checks)C.kind==="int"?nA.isInteger(A.data)||(g=this._getOrReturnCtx(A,g),j(g,{code:P.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:P.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:P.too_big,maximum:C.value,type:"number",inclusive:C.inclusive,exact:!1,message:C.message}),B.dirty()):C.kind==="multipleOf"?Yh(A.data,C.value)!==0&&(g=this._getOrReturnCtx(A,g),j(g,{code:P.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:P.not_finite,message:C.message}),B.dirty()):nA.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 Hg({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:g,message:AA.toString(B)}]})}_addCheck(A){return new Hg({...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"&&nA.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)}}Hg.create=Q=>new Hg({checks:[],typeName:aA.ZodNumber,coerce:Q?.coerce||!1,...tA(Q)});class NB 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:P.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:P.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:P.not_multiple_of,multipleOf:C.value,message:C.message}),B.dirty()):nA.assertNever(C);return{status:B.value,value:A.data}}_getInvalidInput(A){const I=this._getOrReturnCtx(A);return j(I,{code:P.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 NB({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:g,message:AA.toString(B)}]})}_addCheck(A){return new NB({...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}}NB.create=Q=>new NB({checks:[],typeName:aA.ZodBigInt,coerce:Q?.coerce??!1,...tA(Q)});class RC 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:P.invalid_type,expected:$.boolean,received:g.parsedType}),oA}return nI(A.data)}}RC.create=Q=>new RC({typeName:aA.ZodBoolean,coerce:Q?.coerce||!1,...tA(Q)});class oQ 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:P.invalid_type,expected:$.date,received:C.parsedType}),oA}if(Number.isNaN(A.data.getTime())){const C=this._getOrReturnCtx(A);return j(C,{code:P.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:P.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:P.too_big,message:C.message,inclusive:!0,exact:!1,maximum:C.value,type:"date"}),g.dirty()):nA.assertNever(C);return{status:g.value,value:new Date(A.data.getTime())}}_addCheck(A){return new oQ({...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}}oQ.create=Q=>new oQ({checks:[],coerce:Q?.coerce||!1,typeName:aA.ZodDate,...tA(Q)});class xi extends rA{_parse(A){if(this._getType(A)!==$.symbol){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.symbol,received:g.parsedType}),oA}return nI(A.data)}}xi.create=Q=>new xi({typeName:aA.ZodSymbol,...tA(Q)});class Ti extends rA{_parse(A){if(this._getType(A)!==$.undefined){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.undefined,received:g.parsedType}),oA}return nI(A.data)}}Ti.create=Q=>new Ti({typeName:aA.ZodUndefined,...tA(Q)});class Wi extends rA{_parse(A){if(this._getType(A)!==$.null){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.null,received:g.parsedType}),oA}return nI(A.data)}}Wi.create=Q=>new Wi({typeName:aA.ZodNull,...tA(Q)});class cC extends rA{constructor(){super(...arguments),this._any=!0}_parse(A){return nI(A.data)}}cC.create=Q=>new cC({typeName:aA.ZodAny,...tA(Q)});class bi extends rA{constructor(){super(...arguments),this._unknown=!0}_parse(A){return nI(A.data)}}bi.create=Q=>new bi({typeName:aA.ZodUnknown,...tA(Q)});class VI extends rA{_parse(A){const I=this._getOrReturnCtx(A);return j(I,{code:P.invalid_type,expected:$.never,received:I.parsedType}),oA}}VI.create=Q=>new VI({typeName:aA.ZodNever,...tA(Q)});class Zi extends rA{_parse(A){if(this._getType(A)!==$.undefined){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.void,received:g.parsedType}),oA}return nI(A.data)}}Zi.create=Q=>new Zi({typeName:aA.ZodVoid,...tA(Q)});class dI extends rA{_parse(A){const{ctx:I,status:g}=this._processInputParams(A),B=this._def;if(I.parsedType!==$.array)return j(I,{code:P.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?P.too_big:P.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:P.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:P.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 ZI(I,E,I.path,i)))).then(E=>tI.mergeArray(g,E));const C=[...I.data].map((E,i)=>B.type._parseSync(new ZI(I,E,I.path,i)));return tI.mergeArray(g,C)}get element(){return this._def.type}min(A,I){return new dI({...this._def,minLength:{value:A,message:AA.toString(I)}})}max(A,I){return new dI({...this._def,maxLength:{value:A,message:AA.toString(I)}})}length(A,I){return new dI({...this._def,exactLength:{value:A,message:AA.toString(I)}})}nonempty(A){return this.min(1,A)}}dI.create=(Q,A)=>new dI({type:Q,minLength:null,maxLength:null,exactLength:null,typeName:aA.ZodArray,...tA(A)});function qg(Q){if(Q instanceof bA){const A={};for(const I in Q.shape){const g=Q.shape[I];A[I]=OI.create(qg(g))}return new bA({...Q._def,shape:()=>A})}else return Q instanceof dI?new dI({...Q._def,type:qg(Q.element)}):Q instanceof OI?OI.create(qg(Q.unwrap())):Q instanceof pg?pg.create(qg(Q.unwrap())):Q instanceof sg?sg.create(Q.items.map(A=>qg(A))):Q}class bA 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=nA.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:P.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 ZI(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:P.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 ZI(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 bA({...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 bA({...this._def,unknownKeys:"strip"})}passthrough(){return new bA({...this._def,unknownKeys:"passthrough"})}extend(A){return new bA({...this._def,shape:()=>({...this._def.shape(),...A})})}merge(A){return new bA({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 bA({...this._def,catchall:A})}pick(A){const I={};for(const g of nA.objectKeys(A))A[g]&&this.shape[g]&&(I[g]=this.shape[g]);return new bA({...this._def,shape:()=>I})}omit(A){const I={};for(const g of nA.objectKeys(this.shape))A[g]||(I[g]=this.shape[g]);return new bA({...this._def,shape:()=>I})}deepPartial(){return qg(this)}partial(A){const I={};for(const g of nA.objectKeys(this.shape)){const B=this.shape[g];A&&!A[g]?I[g]=B:I[g]=B.optional()}return new bA({...this._def,shape:()=>I})}required(A){const I={};for(const g of nA.objectKeys(this.shape))if(A&&!A[g])I[g]=this.shape[g];else{let C=this.shape[g];for(;C instanceof OI;)C=C._def.innerType;I[g]=C}return new bA({...this._def,shape:()=>I})}keyof(){return Oi(nA.objectKeys(this.shape))}}bA.create=(Q,A)=>new bA({shape:()=>Q,unknownKeys:"strip",catchall:VI.create(),typeName:aA.ZodObject,...tA(A)}),bA.strictCreate=(Q,A)=>new bA({shape:()=>Q,unknownKeys:"strict",catchall:VI.create(),typeName:aA.ZodObject,...tA(A)}),bA.lazycreate=(Q,A)=>new bA({shape:Q,unknownKeys:"strip",catchall:VI.create(),typeName:aA.ZodObject,...tA(A)});class aQ 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 pI(i.ctx.common.issues));return j(I,{code:P.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 pI(o));return j(I,{code:P.invalid_union,unionErrors:i}),oA}}get options(){return this._def.options}}aQ.create=(Q,A)=>new aQ({options:Q,typeName:aA.ZodUnion,...tA(A)});function UC(Q,A){const I=bI(Q),g=bI(A);if(Q===A)return{valid:!0,data:Q};if(I===$.object&&g===$.object){const B=nA.objectKeys(A),C=nA.objectKeys(Q).filter(i=>B.indexOf(i)!==-1),E={...Q,...A};for(const i of C){const o=UC(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=UC(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 DQ extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A),B=(C,E)=>{if(li(C)||li(E))return oA;const i=UC(C.value,E.value);return i.valid?((fi(C)||fi(E))&&I.dirty(),{status:I.value,value:i.data}):(j(g,{code:P.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}))}}DQ.create=(Q,A,I)=>new DQ({left:Q,right:A,typeName:aA.ZodIntersection,...tA(I)});class sg extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.parsedType!==$.array)return j(g,{code:P.invalid_type,expected:$.array,received:g.parsedType}),oA;if(g.data.length<this._def.items.length)return j(g,{code:P.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:P.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 ZI(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 sg({...this._def,rest:A})}}sg.create=(Q,A)=>{if(!Array.isArray(Q))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new sg({items:Q,typeName:aA.ZodTuple,rest:null,...tA(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:P.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 ZI(g,i,g.path,[a,"key"])),value:C._parse(new ZI(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,...tA(I)});class RB extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.parsedType!==$.set)return j(g,{code:P.invalid_type,expected:$.set,received:g.parsedType}),oA;const B=this._def;B.minSize!==null&&g.data.size<B.minSize.value&&(j(g,{code:P.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:P.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 ZI(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,...tA(A)});class Vi 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})}}Vi.create=(Q,A)=>new Vi({getter:Q,typeName:aA.ZodLazy,...tA(A)});class kC extends rA{_parse(A){if(A.data!==this._def.value){const I=this._getOrReturnCtx(A);return j(I,{received:I.data,code:P.invalid_literal,expected:this._def.value}),oA}return{status:"valid",value:A.data}}get value(){return this._def.value}}kC.create=(Q,A)=>new kC({value:Q,typeName:aA.ZodLiteral,...tA(A)});function Oi(Q,A){return new lg({values:Q,typeName:aA.ZodEnum,...tA(A)})}class lg extends rA{_parse(A){if(typeof A.data!="string"){const I=this._getOrReturnCtx(A),g=this._def.values;return j(I,{expected:nA.joinValues(g),received:I.parsedType,code:P.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:P.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 lg.create(A,{...this._def,...I})}exclude(A,I=this._def){return lg.create(this.options.filter(g=>!A.includes(g)),{...this._def,...I})}}lg.create=Oi;class vi extends rA{_parse(A){const I=nA.getValidEnumValues(this._def.values),g=this._getOrReturnCtx(A);if(g.parsedType!==$.string&&g.parsedType!==$.number){const B=nA.objectValues(I);return j(g,{expected:nA.joinValues(B),received:g.parsedType,code:P.invalid_type}),oA}if(this._cache||(this._cache=new Set(nA.getValidEnumValues(this._def.values))),!this._cache.has(A.data)){const B=nA.objectValues(I);return j(g,{received:g.data,code:P.invalid_enum_value,options:B}),oA}return nI(A.data)}get enum(){return this._def.values}}vi.create=(Q,A)=>new vi({values:Q,typeName:aA.ZodNativeEnum,...tA(A)});class sQ 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:P.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})))}}sQ.create=(Q,A)=>new sQ({type:Q,typeName:aA.ZodPromise,...tA(A)});class fg 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"?SB(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"?SB(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);nA.assertNever(B)}}fg.create=(Q,A,I)=>new fg({schema:Q,typeName:aA.ZodEffects,effect:A,...tA(I)}),fg.createWithPreprocess=(Q,A,I)=>new fg({schema:A,effect:{type:"preprocess",transform:Q},typeName:aA.ZodEffects,...tA(I)});class OI extends rA{_parse(A){return this._getType(A)===$.undefined?nI(void 0):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}OI.create=(Q,A)=>new OI({innerType:Q,typeName:aA.ZodOptional,...tA(A)});class pg extends rA{_parse(A){return this._getType(A)===$.null?nI(null):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}pg.create=(Q,A)=>new pg({innerType:Q,typeName:aA.ZodNullable,...tA(A)});class LC 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}}LC.create=(Q,A)=>new LC({innerType:Q,typeName:aA.ZodDefault,defaultValue:typeof A.default=="function"?A.default:()=>A.default,...tA(A)});class JC 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 iQ(B)?B.then(C=>({status:"valid",value:C.status==="valid"?C.value:this._def.catchValue({get error(){return new pI(g.common.issues)},input:g.data})})):{status:"valid",value:B.status==="valid"?B.value:this._def.catchValue({get error(){return new pI(g.common.issues)},input:g.data})}}removeCatch(){return this._def.innerType}}JC.create=(Q,A)=>new JC({innerType:Q,typeName:aA.ZodCatch,catchValue:typeof A.catch=="function"?A.catch:()=>A.catch,...tA(A)});class Xi extends rA{_parse(A){if(this._getType(A)!==$.nan){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.nan,received:g.parsedType}),oA}return{status:"valid",value:A.data}}}Xi.create=Q=>new Xi({typeName:aA.ZodNaN,...tA(Q)});class Kh 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 YC 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(),SB(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 YC({in:A,out:I,typeName:aA.ZodPipeline})}}class KC extends rA{_parse(A){const I=this._def.innerType._parse(A),g=B=>(dg(B)&&(B.value=Object.freeze(B.value)),B);return iQ(I)?I.then(B=>g(B)):g(I)}unwrap(){return this._def.innerType}}KC.create=(Q,A)=>new KC({innerType:Q,typeName:aA.ZodReadonly,...tA(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=PI.create,GA=Hg.create,ji=RC.create,vI=cC.create;VI.create;const LA=dI.create,QA=bA.create;aQ.create,DQ.create,sg.create;const QI=kC.create,ug=lg.create;sQ.create,OI.create,pg.create;const Mh=QA({multiscales:LA(QA({name:kA().optional(),datasets:LA(QA({path:kA(),coordinateTransformations:LA(vI().superRefine((Q,A)=>{const I=[QA({type:QI("scale"),scale:LA(GA()).min(2)}),QA({type:QI("translation"),translation:LA(GA()).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:QI("0.4").optional(),axes:LA(vI().superRefine((Q,A)=>{const I=[QA({name:kA(),type:ug(["channel","time","space"])}),QA({name:kA(),type:vI().refine(B=>!ug(["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(vI().superRefine((Q,A)=>{const I=[QA({type:QI("scale"),scale:LA(GA()).min(2)}),QA({type:QI("translation"),translation:LA(GA()).min(2)}),QA({type:QI("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:GA(),max:GA(),min:GA(),start:GA()}),label:kA().optional(),family:kA().optional(),color:kA(),active:ji().optional()})),rdefs:QA({defaultT:GA().optional(),defaultZ:GA().optional(),color:ug(["color","greyscale"]).optional(),projection:kA().optional()}).optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),dh=QA({plate:QA({acquisitions:LA(QA({id:GA().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:GA().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:GA().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:GA().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:QI("0.4").describe("The version of the specification").optional(),field_count:GA().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:GA().int().gte(0).describe("The index of the well in the rows list"),columnIndex:GA().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"),Hh=QA({well:QA({images:LA(QA({acquisition:GA().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:QI("0.4").describe("The version of the specification").optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),qh=QA({ome:QA({multiscales:LA(QA({name:kA().optional(),datasets:LA(QA({path:kA(),coordinateTransformations:LA(vI().superRefine((Q,A)=>{const I=[QA({type:QI("scale"),scale:LA(GA()).min(2)}),QA({type:QI("translation"),translation:LA(GA()).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(vI().superRefine((Q,A)=>{const I=[QA({name:kA(),type:ug(["channel","time","space"])}),QA({name:kA(),type:vI().refine(B=>!ug(["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(vI().superRefine((Q,A)=>{const I=[QA({type:QI("scale"),scale:LA(GA()).min(2)}),QA({type:QI("translation"),translation:LA(GA()).min(2)}),QA({type:QI("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:GA(),max:GA(),min:GA(),start:GA()}).optional(),label:kA().optional(),family:kA().optional(),color:kA().optional(),active:ji().optional()})),rdefs:QA({defaultT:GA().optional(),defaultZ:GA().optional(),color:ug(["color","greyscale"]).optional(),projection:kA().optional()}).optional()}).optional(),version:QI("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({plate:QA({acquisitions:LA(QA({id:GA().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:GA().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:GA().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:GA().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:GA().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:GA().int().gte(0).describe("The index of the well in the rows list"),columnIndex:GA().int().gte(0).describe("The index of the well in the columns list")})).min(1).describe("The wells of the plate")}),version:QI("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("The zarr.json attributes key"),fh=QA({ome:QA({well:QA({images:LA(QA({acquisition:GA().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:QI("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("JSON from OME-Zarr zarr.json"),ph=["0.4","0.5"],uh=new Set(ph);function mh(Q){if(!("ome"in Q)||!(Q.ome instanceof Object))return;const A=Q.ome;if("version"in A&&typeof A.version=="string"&&uh.has(A.version))return A.version}function MC(Q){const A=mh(Q);return A===void 0?"0.4":A}function mg(Q){if(Q!==void 0)switch(Q){case"0.4":return"v2";case"0.5":return"v3"}}function zi(Q,A){const I={...Q};return delete I[A],I}async function xh(Q,A){const I=new eB(Q),g=new FI(I),B=mg(A),C=await nB(g,B);try{return Th(C.attrs)}catch{throw Error(`Failed to parse OME-Zarr plate:
4219
4219
  ${JSON.stringify(C.attrs)}`)}}function Th(Q){switch(MC(Q)){case"0.5":return{...lh.parse(Q).ome,originalVersion:"0.5"};case"0.4":return{...Wh(dh.parse(Q)).ome,originalVersion:"0.4"}}}function Wh(Q){if(Q.plate===void 0)throw new Error("Plate metadata is missing in OME-Zarr v0.4 plate");return{ome:{plate:zi(Q.plate,"version"),version:"0.5"}}}function bh(Q){if(Q.well===void 0)throw new Error("Well metadata is missing in OME-Zarr v0.4 well");return{ome:{well:zi(Q.well,"version"),version:"0.5"}}}function Zh(Q){switch(MC(Q)){case"0.5":return{...fh.parse(Q).ome,originalVersion:"0.5"};case"0.4":return{...bh(Hh.parse(Q)).ome,originalVersion:"0.4"}}}async function Ph(Q,A,I){const g=Q+"/"+A,B=new eB(g),C=new FI(B),E=mg(I),i=await nB(C,E);try{return Zh(i.attrs)}catch{throw Error(`Failed to parse OME-Zarr well:
4220
4220
  ${JSON.stringify(i.attrs)}`)}}async function Vh(Q){const A=mg(Q.version),I=await nB(Q.location,A);return dC(I.attrs).omero?.channels??[]}async function Oh(Q){const A=mg(Q.version),I=await nB(Q.location,A);return dC(I.attrs).omero?.rdefs}function vh(Q){return{ome:{multiscales:Q.multiscales,omero:Q.omero,version:"0.5"}}}function Xh(Q){switch(MC(Q)){case"0.5":return{...qh.parse(Q).ome,originalVersion:"0.5"};case"0.4":return{...vh(Mh.parse(Q)).ome,originalVersion:"0.4"}}}function dC(Q){try{return Xh(Q)}catch{throw Error(`Failed to parse OME-Zarr image:
4221
- ${JSON.stringify(Q)}`)}}class xg{location;version;loader_;constructor(A){this.location=A.location,this.version=A.version,this.loader_=A.loader}static async openLoader(A,I){let g=mg(I);const B=await nB(A,g),C=dC(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=mg(C.originalVersion));const o=i.datasets.map(y=>Ws(A,y.path,g)),a=await Promise.all(o.map(y=>Ts(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 Ah({metadata:i,arrays:a,arrayParams:o})}getDimensions(){return this.loader_.getSourceDimensionMap()}getChannelCount(){return this.getDimensions().c?.lods[0].size??1}get loader(){return this.loader_}static async fromHttp(A){const I=new FI(new eB(A.url)),g=await xg.openLoader(I,A.version);return new xg({location:I,version:A.version,loader:g})}static async fromFileSystem(A){const I=new FI(new nC(A.directory),A.path),g=await xg.openLoader(I,A.version);return new xg({location:I,version:A.version,loader:g})}}class cB{objects_=[];state_="initialized";attached_=!1;callbacks_=[];opacity_;blendMode;constructor({opacity:A=1,blendMode:I="none"}={}){this.opacity_=fI(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_=fI(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 jh 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&&cQ(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 zh 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 _h=cA(0,1,0);class $h{dirty_=!0;matrix_=gI();rotation_=kQ();translation_=YA();scale_=cA(1,1,1);addRotation(A){aa(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){sa(this.rotation_,A),this.dirty_=!0}get rotation(){return Da(this.rotation_)}addTranslation(A){gB(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){SQ(this.translation_,A),this.dirty_=!0}get translation(){return HI(this.translation_)}addScale(A){Aa(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){SQ(this.scale_,A),this.dirty_=!0}targetTo(A){cQ(this.translation_,A)&&(A=HI(A),A[2]+=JA);const I=zo(gI(),this.translation_,A,_h),g=bo($C(),I);QE(this.rotation_,g),JQ(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return HI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return lB(gI(),this.matrix)}computeMatrix(){Vo(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Tg extends rQ{wireframeEnabled=!1;wireframeColor=wA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new $h;geometry_=new Ug;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){this.textures_[A]=I}clearTextures(){this.textures_.length=0}markStaleTexture(A){A!==void 0&&this.staleTextures_.push(A)}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new zh(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 _i extends Tg{color_;width_;constructor({geometry:A,color:I,width:g}){super(),this.geometry=A,this.color_=wA.from(I),this.width_=g,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=wA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{u_lineColor:this.color.rgb,u_lineWidth:this.width}}}class Ay extends cB{type="AxesLayer";constructor(A){super();const{length:I,width:g}=A;this.addObject(HC({end:[I,0,0],width:g,color:[1,0,0]})),this.addObject(HC({end:[0,I,0],width:g,color:[0,1,0]})),this.addObject(HC({end:[0,0,I],width:g,color:[0,0,1]})),this.setState("ready")}update(){}}function HC(Q){const{end:A,width:I,color:g}=Q,B=new jh([[0,0,0],A]);return new _i({geometry:B,color:g,width:I})}const $i=32;function UB(Q,{visible:A,color:I,contrastLimits:g,opacity:B}){return A??=!0,I=I===void 0?wA.WHITE:wA.from(I),B=B===void 0?1:fI(B,0,1),Q!==null?g=Iy(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 qC(Q,A){if(A.length>$i)throw new Error(`Maximum number of channels is ${$i}`);return A.map(I=>UB(Q,I))}function Ao(Q,A){if(Q&&Q.length!==A)throw new Error(`channelProps length (${Q.length}) must match source channel count (${A}).`)}function Iy(Q,A){if(Q===void 0)return wa(A);if(Q[1]<=Q[0])throw new Error(`Contrast limits must be strictly increasing: ${Q}.`);return Q}class Io 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 w=0;w<D;++w){const k=w*y;for(let f=0;f<a;++f){const d=f*s,T=f/i,z=w/o,x=[d,k,0],l=[0,0,1],Z=[T,z];C.push(...x,...l,...Z)}}for(let w=0;w<o;++w)for(let k=0;k<i;++k){const f=k+a*w,d=k+a*(w+1),T=k+1+a*(w+1),z=k+1+a*w;E.push(f,d,z),E.push(d,T,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 go extends Tg{channels_;worldToTexCoord=gI();constructor(A,I,g,B=[]){super(),this.geometry=new Io(A,I,1,1),this.setTexture(0,g),this.channels_=qC(g,B),this.programName=gy(g)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=qC(this.textures[0],A)}setChannelProperty(A,I,g){const B=UB(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]??UB(A,{});return{u_imageSampler:0,u_color:I.rgb,u_valueOffset:-g[0],u_valueScale:1/(g[1]-g[0]),Opacity:B,u_worldToTexCoord:this.worldToTexCoord}}}function gy(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 Bo(Q,A,I,g,B=3){switch(Q.type){case"pointerdown":{const C=Q.event;return xA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=Q.event,E=xA(C.clientX,C.clientY);if(ha(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 lC{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 fC extends cB{type="ImageLayer";source_;sliceCoords_;axes_={u:"x",v:"y",w:"z"};onPickValue_;visibleChunks_=new Map;pool_=new lC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new wA(.6,.3,.3),new wA(.3,.6,.4),new wA(.4,.4,.7),new wA(.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(Ao(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_)return;const I=A.camera;if(I.type!=="OrthographicCamera")throw new Error("Image rendering currently supports only orthographic cameras. Update the implementation before using a perspective camera.");this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:I.getWorldViewRect(),bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[g,B]of this.visibleChunks_)this.updateSlicePosition(B,g)}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),g=new Set(I),B=Array.from(this.visibleChunks_.keys()).filter(C=>!g.has(C));this.releaseAndRemoveChunks(B),this.clearObjects();for(const C of I){const E=this.getImageForChunk(C,C.texture);this.visibleChunks_.set(C,E),this.addObject(E)}}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_>fC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Bo(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,XB))}getImageForChunk(A,I){const g=this.visibleChunks_.get(A);if(g)return g;const B=this.pool_.acquire(hQ(A));return B?(B.setTexture(0,I),B.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(B,A),B):this.createImage(A,I)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A,I){const g=new go(A.shape[this.axes_.u],A.shape[this.axes_.v],I,this.getChannelPropsForChunk(A));return this.updateImageChunk(g,A),g}updateSlicePosition(A,I){const{u:g,v:B,w:C}=this.axes_;A.transform.setTranslation([I.offset[g],I.offset[B],this.sliceCoords_[C]??I.offset[C]])}sliceIndexForChunk(A){const I=this.axes_.w,g=this.sliceCoords_[I];if(g===void 0)return 0;const B=(g-A.offset[I])/A.scale[I];return fI(Math.round(B),0,A.shape[I]-1)}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1;const{u:g,v:B}=this.axes_;A.transform.setScale([I.scale[g],I.scale[B],1]),this.updateSlicePosition(A,I),A.worldToTexCoord=$E(I,this.axes_)}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=RQ(YA(),g,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,o=Math.floor(B[0]),a=Math.floor(B[1]);if(o<0||o>=A.shape[C]||a<0||a>=A.shape[E])return null;const D={x:0,y:0,z:0};return D[C]=o,D[E]=a,D[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(D.x,D.y,D.z)??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(hQ(I),g),this.visibleChunks_.delete(I))}}}function hQ(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class By 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,w){const k=E/a,f=i/D,d=E/2,T=i/2,z=o/2*s,x=a+1,l=D+1,Z=y.length/8;for(let v=0;v<l;v++){const EA=-T+v*f;for(let hA=0;hA<x;hA++){const DA=-d+hA*k,yA={x:0,y:0,z:0};yA[A]=DA*B,yA[I]=EA*C,yA[g]=z;const eA={x:0,y:0,z:0};eA[g]=s;const zA=hA/a,uA=1-v/D;y.push(yA.x,yA.y,yA.z,eA.x,eA.y,eA.z,zA,uA)}}for(let v=0;v<D;v++)for(let EA=0;EA<a;EA++){const hA=Z+EA+x*v,DA=Z+EA+x*(v+1),yA=Z+(EA+1)+x*(v+1),eA=Z+(EA+1)+x*v;w.push(hA,DA,eA,DA,yA,eA)}}}class Qo extends Tg{voxelScale=cA(1,1,1);channels_;loadedChannels_=new Set;channelToTextureIndex_=new Map;constructor(){super(),this.geometry=new By(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){if(!A.texture)return;const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A.texture):this.addChannelTexture(I,A.texture),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=this.textures.length;this.setTexture(g,I),this.channelToTextureIndex_.set(A,g);const B=Qy(I.dataType);if(this.programName&&this.programName!==B)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${I.dataType} and program: ${B}`);this.programName=B}updateChannelTexture(A,I){this.setTexture(A,I)}clearLoadedChannels(){this.loadedChannels_=new Set}reset(){this.clearTextures(),this.channelToTextureIndex_.clear(),this.clearLoadedChannels()}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=UB(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[`u_channel${D}Sampler`]=a,o),{u_visible:A,"u_color[0]":I,u_valueOffset:g,u_valueScale:B,u_channelOpacity:C,u_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_=qC(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const B=UB(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=B}}function Qy(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 Cy(Q,A){const I=A.position,g=YA(),B=YA();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=gE(I,g),o=gE(I,B);return i-o}),Q}const Ey=2;class iy extends cB{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new lC;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,XB))}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=Dy(I[0]),C=this.pool_.acquire(B)??new Qo;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_),Ao(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;this.state!=="ready"&&this.setState("ready");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}}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]),gg(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.reset(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!A||!this.chunkStoreView_)return;this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.camera.getViewProjection());const I=A.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?Ey:1,this.updateChunks(),Cy(this.objects,A.camera)}getUniforms(){return{u_debugShowDegenerateRays:Number(this.debugShowDegenerateRays),u_relativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,u_opacityMultiplier:this.opacityMultiplier,u_earlyTerminationAlpha:this.earlyTerminationAlpha}}}function oy(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=oy(I);let B=A.get(g);B||(B=[],A.set(g,B)),B.push(I)}return A}function Dy(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class Co extends MQ{width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=KQ(A),this.data_=A,this.width_=I,this.height_=g}get type(){return"Texture2D"}get width(){return this.width_}get height(){return this.height_}}const Eo=new Set(["byte","short","int"]),sy=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function hy(Q){if(Q.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${Q.dataFormat}`);if(!Eo.has(Q.dataType)&&!sy.has(Q.dataType))throw new Error(`Image data type must be an integer, instead found: ${Q.dataType}`);return Q}function yy(Q){return Eo.has(Q.dataType)?"intLabelImage":"labelImage"}class io extends Tg{outlineSelected_;selectedValue_;worldToTexCoord=gI();constructor(A){super(),this.geometry=new Io(A.width,A.height,1,1),this.setTexture(0,hy(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=yy(A.imageData)}get type(){return"LabelImageRenderable"}getUniforms(){return{u_imageSampler:0,u_colorCycleSampler:1,u_colorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1,u_worldToTexCoord:this.worldToTexCoord}}setColorMap(A){this.markStaleTexture(this.textures[1]),this.markStaleTexture(this.textures[2]),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 Co(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,wA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,wA.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 Co(C,B,2)}}const ty=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Gy(Q){return Q=Q??new Map,new Map(Array.from(Q.entries()).map(([A,I])=>[A,wA.from(I)]))}function ey(Q){return Q=Q??ty,Q.map(wA.from)}class pC{lookupTable;cycle;constructor(A={}){this.lookupTable=Gy(A.lookupTable),this.cycle=ey(A.cycle)}}class uC extends cB{type="LabelLayer";source_;sliceCoords_;axes_={u:"x",v:"y",w:"z"};onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new lC;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 pC(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_)return;const I=A.camera;if(I.type!=="OrthographicCamera")throw new Error("Label rendering currently supports only orthographic cameras. Update the implementation before using a perspective camera.");this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:I.getWorldViewRect(),bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[g,B]of this.visibleChunks_)this.updateSlicePosition(B,g)}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),g=new Set(I),B=Array.from(this.visibleChunks_.keys()).filter(C=>!g.has(C));this.releaseAndRemoveChunks(B),this.clearObjects();for(const C of I){const E=this.getLabelForChunk(C,C.texture);this.visibleChunks_.set(C,E),this.addObject(E)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>uC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Bo(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 pC(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,XB))}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=RQ(YA(),g,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,o=Math.floor(B[0]),a=Math.floor(B[1]);if(o<0||o>=A.shape[C]||a<0||a>=A.shape[E])return null;const D={x:0,y:0,z:0};return D[C]=o,D[E]=a,D[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(D.x,D.y,D.z)??null}getLabelForChunk(A,I){const g=this.visibleChunks_.get(A);if(g)return g;const B=this.pool_.acquire(hQ(A));return B?(B.setTexture(0,I),B.setColorMap(this.colorMap_),B.setSelectedValue(this.selectedValue_),this.updateLabelChunk(B,A),B):this.createLabel(A,I)}createLabel(A,I){const g=new io({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],imageData:I,colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return this.updateLabelChunk(g,A),g}updateSlicePosition(A,I){const{u:g,v:B,w:C}=this.axes_;A.transform.setTranslation([I.offset[g],I.offset[B],this.sliceCoords_[C]??I.offset[C]])}sliceIndexForChunk(A){const I=this.axes_.w,g=this.sliceCoords_[I];if(g===void 0)return 0;const B=(g-A.offset[I])/A.scale[I];return fI(Math.round(B),0,A.shape[I]-1)}updateLabelChunk(A,I){const{u:g,v:B}=this.axes_;A.transform.setScale([I.scale[g],I.scale[B],1]),this.updateSlicePosition(A,I),A.worldToTexCoord=$E(I,this.axes_)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(hQ(I),g),this.visibleChunks_.delete(I))}}}class wy extends MQ{width_;height_;depth_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=KQ(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=A.length/(I*g)}get type(){return"Texture2DArray"}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}}const oo={circle:0,square:1,triangle:2};class Fy extends Tg{constructor(A){super(),this.programName="points";const I=A.flatMap(B=>{const C=wA.from(B.color);return[B.position[0],B.position[1],B.position[2],C.r,C.g,C.b,C.a,B.size,oo[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,ry())}get type(){return"Points"}}let mC;function ry(){return mC||(mC=ny()),mC}function ny(){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,oo[a]*65536);const o=new wy(i,256,256);return o.wrapR="clamp_to_edge",o.wrapS="clamp_to_edge",o.wrapT="clamp_to_edge",o}class ao{radius;phi;theta;constructor(A,I,g){this.radius=A,this.phi=I,this.theta=g}toVec3(){const A=Math.cos(this.theta);return cA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const xC=-1,Do=0,Sy=1,so=.009,Ny=.001,Ry=9e-4,cy=.5,Uy=60;class ky{camera_;orbitVelocity_=new ao(0,0,0);panVelocity_=YA();currPos_;currCenter_=YA();dampingFactor_;currMouseButton_=xC;constructor(A,I){this.camera_=A,this.currPos_=new ao(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&SQ(this.currCenter_,I.target),this.dampingFactor_=fI(I?.dampingFactor??cy,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&&cQ(this.panVelocity_,cA(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=fI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const g=Math.pow(1-this.dampingFactor_,A*Uy);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_==xC)return;const I=A.event,g=I.movementX??0,B=I.movementY??0,C=this.currMouseButton_===Do&&!I.shiftKey,E=this.currMouseButton_===Do&&I.shiftKey||this.currMouseButton_===Sy;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_=xC;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*so,this.orbitVelocity_.theta+=I*so}pan(A,I){const g=this.currPos_.radius*Ny,B=YA();IE(B,B,this.camera_.right,A),IE(B,B,this.camera_.up,I),BB(B,B,g),UQ(this.panVelocity_,this.panVelocity_,B)}zoom(A){this.orbitVelocity_.radius+=A*Ry}updateCamera(){const A=gB(YA(),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),nQ(this.panVelocity_)<JA&&ga(this.panVelocity_)}}class Wg{normal;signedDistance;constructor(A=cA(0,1,0),I=0){this.normal=HI(A),this.signedDistance=I}set(A,I){this.normal=HI(A),this.signedDistance=I}signedDistanceToPoint(A){return BE(this.normal,A)+this.signedDistance}normalize(){const A=nQ(this.normal);if(A>0){const I=1/A;BB(this.normal,this.normal,I),this.signedDistance*=I}}}class Ly{planes_;constructor(A){this.planes_=[new Wg(YA(),0),new Wg(YA(),0),new Wg(YA(),0),new Wg(YA(),0),new Wg(YA(),0),new Wg(YA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=YA();this.planes_[0].set(gg(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(gg(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(gg(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(gg(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(gg(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(gg(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=YA();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 ho extends Tg{projectionMatrix_=gI();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 cA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return cA(A[4],A[5],A[6])}getViewProjection(){return Rg(gI(),this.projectionMatrix,this.viewMatrix)}get frustum(){return new Ly(this.getViewProjection())}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=fB(A[0],A[1],A[2],1),g=lB(gI(),this.projectionMatrix_),B=QB(cg(),I,g);Ea(B,B,1/B[3]);const C=QB(cg(),B,this.transform.matrix);return cA(C[0],C[1],C[2])}}const yo=1.77,to=128,Go=128/yo,Jy=-1e6,Yy=1e6;class Ky extends ho{width_=to;height_=Go;viewportAspectRatio_=yo;viewportSize_=[to,Go];constructor(A,I,g,B,C=Jy,E=Yy){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=fB(-1,-1,0,1),I=fB(1,1,0,1);const g=lB(gI(),this.getViewProjection());return A=QB(cg(),A,g),I=QB(cg(),I,g),new CI(xA(A[0],A[1]),xA(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],jo(this.projectionMatrix_,-B,B,-C,C,this.near_,this.far_)}}const eo=0;class My{camera_;dragActive_=!1;dragStart_=YA();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=HI(A.worldPos),B=I.deltaY<0?1.05:.95;this.camera_.zoom(B);const C=this.camera_.clipToWorld(A.clipPos),E=UQ(YA(),g,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==eo||(this.dragStart_=HI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=UQ(YA(),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 dy=60,Hy=1.77,yQ=.1,TC=180-yQ;class qy extends ho{fov_;aspectRatio_;constructor(A={}){const{fov:I=dy,aspectRatio:g=Hy,near:B=.1,far:C=1e4,position:E=cA(0,0,0)}=A;if(I<yQ||I>TC)throw new Error(`Invalid field of view: ${I}, must be in [${yQ}, ${TC}] 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(yQ,Math.min(TC,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){vo(this.projectionMatrix_,Wo(this.fov),this.aspectRatio_,this.near_,this.far_)}}const wo=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function tQ(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(wo.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 ly(Q={}){return tQ(WC({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},Q))}function fy(Q={}){return tQ(WC({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"]},Q))}function py(Q={}){return tQ(WC({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!==wo.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function WC(Q,A={}){return{profile:A.profile??Q.profile,prefetch:{...Q.prefetch,...A.prefetch??{}},lod:{...Q.lod,...A.lod??{}},priorityOrder:A.priorityOrder??Q.priorityOrder}}var bC=(()=>{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}})(),my=(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"&&yA("no native wasm support detected");var a,D=!1,s,y,w,k,f,d,T,z;function x(){var G=a.buffer;A.HEAP8=s=new Int8Array(G),A.HEAP16=w=new Int16Array(G),A.HEAPU8=y=new Uint8Array(G),A.HEAPU16=k=new Uint16Array(G),A.HEAP32=f=new Int32Array(G),A.HEAPU32=d=new Uint32Array(G),A.HEAPF32=T=new Float32Array(G),A.HEAPF64=z=new Float64Array(G)}var l=[],Z=[],v=[];function EA(){var G=A.preRun.shift();l.unshift(G)}var hA=0,DA=null;function yA(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 eA=G=>G.startsWith("data:application/octet-stream;base64,"),zA=G=>G.startsWith("file://"),uA;if(uA="blosc_codec.wasm",!eA(uA)){var SA=uA;uA=A.locateFile?A.locateFile(SA,""):""+SA}function uI(G){return Promise.resolve().then(()=>{if(G==uA&&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 uI(G).then(H=>WebAssembly.instantiate(H,r)).then(H=>H).then(N,H=>{i(`failed to asynchronously prepare wasm: ${H}`),yA(H)})}function mI(G,r){var N=uA;return o||typeof WebAssembly.instantiateStreaming!="function"||eA(N)||zA(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 XI=G=>{for(;0<G.length;)G.shift()(A)};function jI(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,ZA,dA=G=>{for(var r="";y[G];)r+=ZA[y[G++]];return r},XA={},MA={},mA={},PA,hg=G=>{throw new PA(G)},yg,GI=(G,r)=>{function N(Y){if(Y=r(Y),Y.length!==H.length)throw new yg("Mismatched type converter count");for(var L=0;L<H.length;++L)HA(H[L],Y[L])}var H=[];H.forEach(function(Y){mA[Y]=G});var h=Array(G.length),e=[],S=0;G.forEach((Y,L)=>{MA.hasOwnProperty(Y)?h[L]=MA[Y]:(e.push(Y),XA.hasOwnProperty(Y)||(XA[Y]=[]),XA[Y].push(()=>{h[L]=MA[Y],++S,S===e.length&&N(h)}))}),e.length===0&&N(h)};function DI(G,r,N={}){var H=r.name;if(!G)throw new PA(`type "${H}" must have a positive integer typeid pointer`);if(MA.hasOwnProperty(G)){if(N.P)return;throw new PA(`Cannot register type '${H}' twice`)}MA[G]=r,delete mA[G],XA.hasOwnProperty(G)&&(r=XA[G],delete XA[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,xI=G=>{G>=_A.H&&--_A.get(G).L===0&&_A.J(G)},Og=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 zI(G){return this.fromWireType(f[G>>2])}var tg=(G,r)=>{switch(r){case 4:return function(N){return this.fromWireType(T[N>>2])};case 8:return function(N){return this.fromWireType(z[N>>3])};default:throw new TypeError(`invalid float width (${r}): ${G}`)}},_I=(G,r)=>Object.defineProperty(r,"name",{value:G}),vg=G=>{for(;G.length;){var r=G.pop();G.pop()(r)}};function Xg(G){for(var r=1;r<G.length;++r)if(G[r]!==null&&G[r].G===void 0)return!0;return!1}function kB(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=_I(r.name||"unknownFunctionName",function(){});return N.prototype=r.prototype,N=new N,G=r.apply(N,G),G instanceof Object?G:N}var LB=(G,r)=>{if(A[G].C===void 0){var N=A[G];A[G]=function(){if(!A[G].C.hasOwnProperty(arguments.length))throw new PA(`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}},Gg=(G,r,N)=>{if(A.hasOwnProperty(G)){if(N===void 0||A[G].C!==void 0&&A[G].C[N]!==void 0)throw new PA(`Cannot register public name '${G}' twice`);if(LB(G,G),A.hasOwnProperty(N))throw new PA(`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)},eg=(G,r)=>{for(var N=[],H=0;H<G;H++)N.push(d[r+4*H>>2]);return N},wg,jg=(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=wg.get(r).apply(null,N);return H}},zg=(G,r)=>{G=dA(G);var N=G.includes("j")?jg(G,r):wg.get(r);if(typeof N!="function")throw new PA(`unknown function pointer with signature ${G}: ${r}`);return N},Fg,rg=G=>{G=O(G);var r=dA(G);return u(G),r},JB=(G,r)=>{function N(e){h[e]||MA[e]||(mA[e]?mA[e].forEach(N):(H.push(e),h[e]=!0))}var H=[],h={};throw r.forEach(N),new Fg(`${G}: `+H.map(rg).join([", "]))},YB=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=>w[H>>1]:H=>k[H>>1];case 4:return N?H=>f[H>>2]:H=>d[H>>2];default:throw new TypeError(`invalid integer width (${r}): ${G}`)}};function ng(G){return this.fromWireType(d[G>>2])}for(var $I=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Sg=(G,r,N)=>{var H=r+N;for(N=r;G[N]&&!(N>=H);)++N;if(16<N-r&&G.buffer&&$I)return $I.decode(G.subarray(r,N));for(H="";r<N;){var h=G[r++];if(h&128){var e=G[r++]&63;if((h&224)==192)H+=String.fromCharCode((h&31)<<6|e);else{var S=G[r++]&63;h=(h&240)==224?(h&15)<<12|e<<6|S:(h&7)<<18|e<<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},$g=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,KB=(G,r)=>{for(var N=G>>1,H=N+r/2;!(N>=H)&&k[N];)++N;if(N<<=1,32<N-G&&$g)return $g.decode(y.subarray(G,N));for(N="",H=0;!(H>=r/2);++H){var h=w[G+2*H>>1];if(h==0)break;N+=String.fromCharCode(h)}return N},MB=(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)w[r>>1]=G.charCodeAt(h),r+=2;return w[r>>1]=0,r-H},dB=G=>2*G.length,AB=(G,r)=>{for(var N=0,H="";!(N>=r/4);){var h=f[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},Ag=(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 e=G.charCodeAt(h);if(55296<=e&&57343>=e){var S=G.charCodeAt(++h);e=65536+((e&1023)<<10)|S&1023}if(f[r>>2]=e,r+=4,r+4>N)break}return f[r>>2]=0,r-H},Ng=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,pA=[null,[],[]],JI=Array(256),jA=0;256>jA;++jA)JI[jA]=String.fromCharCode(jA);ZA=JI,PA=A.BindingError=class extends Error{constructor(G){super(G),this.name="BindingError"}},yg=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},Fg=A.UnboundTypeError=((G,r)=>{var N=_I(r,function(H){this.name=r,this.message=H,H=Error(H).stack,H!==void 0&&(this.stack=this.toString()+`
4221
+ ${JSON.stringify(Q)}`)}}class xg{location;version;loader_;constructor(A){this.location=A.location,this.version=A.version,this.loader_=A.loader}static async openLoader(A,I){let g=mg(I);const B=await nB(A,g),C=dC(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=mg(C.originalVersion));const o=i.datasets.map(y=>Ws(A,y.path,g)),a=await Promise.all(o.map(y=>Ts(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 Ah({metadata:i,arrays:a,arrayParams:o})}getDimensions(){return this.loader_.getSourceDimensionMap()}getChannelCount(){return this.getDimensions().c?.lods[0].size??1}get loader(){return this.loader_}static async fromHttp(A){const I=new FI(new eB(A.url)),g=await xg.openLoader(I,A.version);return new xg({location:I,version:A.version,loader:g})}static async fromFileSystem(A){const I=new FI(new nC(A.directory),A.path),g=await xg.openLoader(I,A.version);return new xg({location:I,version:A.version,loader:g})}}class cB{objects_=[];state_="initialized";attached_=!1;callbacks_=[];opacity_;blendMode;constructor({opacity:A=1,blendMode:I="none"}={}){this.opacity_=fI(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_=fI(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 jh 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&&cQ(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 zh 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 _h=cA(0,1,0);class $h{dirty_=!0;matrix_=gI();rotation_=kQ();translation_=YA();scale_=cA(1,1,1);addRotation(A){aa(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){sa(this.rotation_,A),this.dirty_=!0}get rotation(){return Da(this.rotation_)}addTranslation(A){gB(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){SQ(this.translation_,A),this.dirty_=!0}get translation(){return HI(this.translation_)}addScale(A){Aa(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){SQ(this.scale_,A),this.dirty_=!0}targetTo(A){cQ(this.translation_,A)&&(A=HI(A),A[2]+=JA);const I=zo(gI(),this.translation_,A,_h),g=bo($C(),I);QE(this.rotation_,g),JQ(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return HI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return lB(gI(),this.matrix)}computeMatrix(){Vo(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Tg extends rQ{wireframeEnabled=!1;wireframeColor=wA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new $h;geometry_=new Ug;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){this.textures_[A]=I}clearTextures(){this.textures_.length=0}markStaleTexture(A){A!==void 0&&this.staleTextures_.push(A)}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new zh(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 _i extends Tg{color_;width_;constructor({geometry:A,color:I,width:g}){super(),this.geometry=A,this.color_=wA.from(I),this.width_=g,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=wA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{u_lineColor:this.color.rgb,u_lineWidth:this.width}}}class Ay extends cB{type="AxesLayer";constructor(A){super();const{length:I,width:g}=A;this.addObject(HC({end:[I,0,0],width:g,color:[1,0,0]})),this.addObject(HC({end:[0,I,0],width:g,color:[0,1,0]})),this.addObject(HC({end:[0,0,I],width:g,color:[0,0,1]})),this.setState("ready")}update(){}}function HC(Q){const{end:A,width:I,color:g}=Q,B=new jh([[0,0,0],A]);return new _i({geometry:B,color:g,width:I})}const $i=32;function UB(Q,{visible:A,color:I,contrastLimits:g,opacity:B}){return A??=!0,I=I===void 0?wA.WHITE:wA.from(I),B=B===void 0?1:fI(B,0,1),Q!==null?g=Iy(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 qC(Q,A){if(A.length>$i)throw new Error(`Maximum number of channels is ${$i}`);return A.map(I=>UB(Q,I))}function Ao(Q,A){if(Q&&Q.length!==A)throw new Error(`channelProps length (${Q.length}) must match source channel count (${A}).`)}function Iy(Q,A){if(Q===void 0)return wa(A);if(Q[1]<=Q[0])throw new Error(`Contrast limits must be strictly increasing: ${Q}.`);return Q}class Io 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 w=0;w<D;++w){const k=w*y;for(let f=0;f<a;++f){const d=f*s,T=f/i,z=w/o,x=[d,k,0],l=[0,0,1],Z=[T,z];C.push(...x,...l,...Z)}}for(let w=0;w<o;++w)for(let k=0;k<i;++k){const f=k+a*w,d=k+a*(w+1),T=k+1+a*(w+1),z=k+1+a*w;E.push(f,d,z),E.push(d,T,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 go extends Tg{channels_;worldToTexCoord=gI();constructor(A,I,g,B=[]){super(),this.geometry=new Io(A,I,1,1),this.setTexture(0,g),this.channels_=qC(g,B),this.programName=gy(g)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=qC(this.textures[0],A)}setChannelProperty(A,I,g){const B=UB(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]??UB(A,{});return{u_imageSampler:0,u_color:I.rgb,u_valueOffset:-g[0],u_valueScale:1/(g[1]-g[0]),Opacity:B,u_worldToTexCoord:this.worldToTexCoord}}}function gy(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 Bo(Q,A,I,g,B=3){switch(Q.type){case"pointerdown":{const C=Q.event;return xA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=Q.event,E=xA(C.clientX,C.clientY);if(ha(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 lC{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 fC extends cB{type="ImageLayer";source_;sliceCoords_;axes_={u:"x",v:"y",w:"z"};onPickValue_;visibleChunks_=new Map;pool_=new lC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new wA(.6,.3,.3),new wA(.3,.6,.4),new wA(.4,.4,.7),new wA(.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(Ao(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_)return;const I=A.camera;if(I.type!=="OrthographicCamera")throw new Error("Image rendering currently supports only orthographic cameras. Update the implementation before using a perspective camera.");this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:I.getWorldViewRect(),bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[g,B]of this.visibleChunks_)this.updateSlicePosition(B,g)}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),g=new Set(I),B=Array.from(this.visibleChunks_.keys()).filter(C=>!g.has(C));this.releaseAndRemoveChunks(B),this.clearObjects();for(const C of I){const E=this.getImageForChunk(C,C.texture);this.visibleChunks_.set(C,E),this.addObject(E)}}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_>fC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Bo(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,XB))}getImageForChunk(A,I){const g=this.visibleChunks_.get(A);if(g)return g;const B=this.pool_.acquire(hQ(A));return B?(B.setTexture(0,I),B.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(B,A),B):this.createImage(A,I)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A,I){const g=new go(A.shape[this.axes_.u],A.shape[this.axes_.v],I,this.getChannelPropsForChunk(A));return this.updateImageChunk(g,A),g}updateSlicePosition(A,I){const{u:g,v:B,w:C}=this.axes_;A.transform.setTranslation([I.offset[g],I.offset[B],this.sliceCoords_[C]??I.offset[C]])}sliceIndexForChunk(A){const I=this.axes_.w,g=this.sliceCoords_[I];if(g===void 0)return 0;const B=(g-A.offset[I])/A.scale[I];return fI(Math.round(B),0,A.shape[I]-1)}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1;const{u:g,v:B}=this.axes_;A.transform.setScale([I.scale[g],I.scale[B],1]),this.updateSlicePosition(A,I),A.worldToTexCoord=$E(I,this.axes_)}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=RQ(YA(),g,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,o=Math.floor(B[0]),a=Math.floor(B[1]);if(o<0||o>=A.shape[C]||a<0||a>=A.shape[E])return null;const D={x:0,y:0,z:0};return D[C]=o,D[E]=a,D[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(D.x,D.y,D.z)??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(hQ(I),g),this.visibleChunks_.delete(I))}}}function hQ(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class By 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,w){const k=E/a,f=i/D,d=E/2,T=i/2,z=o/2*s,x=a+1,l=D+1,Z=y.length/8;for(let v=0;v<l;v++){const EA=-T+v*f;for(let hA=0;hA<x;hA++){const DA=-d+hA*k,yA={x:0,y:0,z:0};yA[A]=DA*B,yA[I]=EA*C,yA[g]=z;const eA={x:0,y:0,z:0};eA[g]=s;const zA=hA/a,uA=1-v/D;y.push(yA.x,yA.y,yA.z,eA.x,eA.y,eA.z,zA,uA)}}for(let v=0;v<D;v++)for(let EA=0;EA<a;EA++){const hA=Z+EA+x*v,DA=Z+EA+x*(v+1),yA=Z+(EA+1)+x*(v+1),eA=Z+(EA+1)+x*v;w.push(hA,DA,eA,DA,yA,eA)}}}class Qo extends Tg{voxelScale=cA(1,1,1);channels_;loadedChannels_=new Set;channelToTextureIndex_=new Map;constructor(){super(),this.geometry=new By(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){if(!A.texture)return;const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A.texture):this.addChannelTexture(I,A.texture),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=this.textures.length;this.setTexture(g,I),this.channelToTextureIndex_.set(A,g);const B=Qy(I.dataType);if(this.programName&&this.programName!==B)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${I.dataType} and program: ${B}`);this.programName=B}updateChannelTexture(A,I){this.setTexture(A,I)}clearLoadedChannels(){this.loadedChannels_=new Set}reset(){this.clearTextures(),this.channelToTextureIndex_.clear(),this.clearLoadedChannels()}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=UB(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[`u_channel${D}Sampler`]=a,o),{u_visible:A,"u_color[0]":I,u_valueOffset:g,u_valueScale:B,u_channelOpacity:C,u_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_=qC(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const B=UB(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=B}}function Qy(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 Cy(Q,A){const I=A.position,g=YA(),B=YA();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=gE(I,g),o=gE(I,B);return i-o}),Q}const Ey=2;class iy extends cB{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new lC;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,XB))}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=Dy(I[0]),C=this.pool_.acquire(B)??new Qo;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_),Ao(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;this.state!=="ready"&&this.setState("ready");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}}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]),gg(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.reset(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!A||!this.chunkStoreView_)return;this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.camera.getViewProjection());const I=A.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?Ey:1,this.updateChunks(),Cy(this.objects,A.camera)}getUniforms(){return{u_debugShowDegenerateRays:Number(this.debugShowDegenerateRays),u_relativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,u_opacityMultiplier:this.opacityMultiplier,u_earlyTerminationAlpha:this.earlyTerminationAlpha}}}function oy(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=oy(I);let B=A.get(g);B||(B=[],A.set(g,B)),B.push(I)}return A}function Dy(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class Co extends MQ{width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=KQ(A),this.data_=A,this.width_=I,this.height_=g}get type(){return"Texture2D"}get width(){return this.width_}get height(){return this.height_}}const Eo=new Set(["byte","short","int"]),sy=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function hy(Q){if(Q.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${Q.dataFormat}`);if(!Eo.has(Q.dataType)&&!sy.has(Q.dataType))throw new Error(`Image data type must be an integer, instead found: ${Q.dataType}`);return Q}function yy(Q){return Eo.has(Q.dataType)?"intLabelImage":"labelImage"}class io extends Tg{outlineSelected_;selectedValue_;worldToTexCoord=gI();constructor(A){super(),this.geometry=new Io(A.width,A.height,1,1),this.setTexture(0,hy(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=yy(A.imageData)}get type(){return"LabelImageRenderable"}getUniforms(){return{u_imageSampler:0,u_colorCycleSampler:1,u_colorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1,u_worldToTexCoord:this.worldToTexCoord}}setColorMap(A){this.markStaleTexture(this.textures[1]),this.markStaleTexture(this.textures[2]),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 Co(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,wA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,wA.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 Co(C,B,2)}}const ty=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Gy(Q){return Q=Q??new Map,new Map(Array.from(Q.entries()).map(([A,I])=>[A,wA.from(I)]))}function ey(Q){return Q=Q??ty,Q.map(wA.from)}class pC{lookupTable;cycle;constructor(A={}){this.lookupTable=Gy(A.lookupTable),this.cycle=ey(A.cycle)}}class uC extends cB{type="LabelLayer";source_;sliceCoords_;axes_={u:"x",v:"y",w:"z"};onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new lC;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 pC(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_)return;const I=A.camera;if(I.type!=="OrthographicCamera")throw new Error("Label rendering currently supports only orthographic cameras. Update the implementation before using a perspective camera.");this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:I.getWorldViewRect(),bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[g,B]of this.visibleChunks_)this.updateSlicePosition(B,g)}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),g=new Set(I),B=Array.from(this.visibleChunks_.keys()).filter(C=>!g.has(C));this.releaseAndRemoveChunks(B),this.clearObjects();for(const C of I){const E=this.getLabelForChunk(C,C.texture);this.visibleChunks_.set(C,E),this.addObject(E)}}hasMultipleLODs(){return this.chunkStoreView_?this.chunkStoreView_.lodCount>1:!1}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>uC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Bo(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 pC(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,XB))}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=RQ(YA(),g,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,o=Math.floor(B[0]),a=Math.floor(B[1]);if(o<0||o>=A.shape[C]||a<0||a>=A.shape[E])return null;const D={x:0,y:0,z:0};return D[C]=o,D[E]=a,D[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(D.x,D.y,D.z)??null}getLabelForChunk(A,I){const g=this.visibleChunks_.get(A);if(g)return g;const B=this.pool_.acquire(hQ(A));return B?(B.setTexture(0,I),B.setColorMap(this.colorMap_),B.setSelectedValue(this.selectedValue_),this.updateLabelChunk(B,A),B):this.createLabel(A,I)}createLabel(A,I){const g=new io({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],imageData:I,colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return this.updateLabelChunk(g,A),g}updateSlicePosition(A,I){const{u:g,v:B,w:C}=this.axes_;A.transform.setTranslation([I.offset[g],I.offset[B],this.sliceCoords_[C]??I.offset[C]])}sliceIndexForChunk(A){const I=this.axes_.w,g=this.sliceCoords_[I];if(g===void 0)return 0;const B=(g-A.offset[I])/A.scale[I];return fI(Math.round(B),0,A.shape[I]-1)}updateLabelChunk(A,I){const{u:g,v:B}=this.axes_;A.transform.setScale([I.scale[g],I.scale[B],1]),this.updateSlicePosition(A,I),A.worldToTexCoord=$E(I,this.axes_)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(hQ(I),g),this.visibleChunks_.delete(I))}}}class wy extends MQ{width_;height_;depth_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=KQ(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=A.length/(I*g)}get type(){return"Texture2DArray"}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}}const oo={circle:0,square:1,triangle:2};class Fy extends Tg{constructor(A){super(),this.programName="points";const I=A.flatMap(B=>{const C=wA.from(B.color);return[B.position[0],B.position[1],B.position[2],C.r,C.g,C.b,C.a,B.size,oo[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,ry())}get type(){return"Points"}}let mC;function ry(){return mC||(mC=ny()),mC}function ny(){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,oo[a]*65536);const o=new wy(i,256,256);return o.wrapR="clamp_to_edge",o.wrapS="clamp_to_edge",o.wrapT="clamp_to_edge",o}class ao{radius;phi;theta;constructor(A,I,g){this.radius=A,this.phi=I,this.theta=g}toVec3(){const A=Math.cos(this.theta);return cA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const xC=-1,Do=0,Sy=1,so=.009,Ny=.001,Ry=9e-4,cy=.5,Uy=60;class ky{camera_;orbitVelocity_=new ao(0,0,0);panVelocity_=YA();currPos_;currCenter_=YA();dampingFactor_;currMouseButton_=xC;constructor(A,I){this.camera_=A,this.currPos_=new ao(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&SQ(this.currCenter_,I.target),this.dampingFactor_=fI(I?.dampingFactor??cy,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&&cQ(this.panVelocity_,cA(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=fI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const g=Math.pow(1-this.dampingFactor_,A*Uy);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_==xC)return;const I=A.event,g=I.movementX??0,B=I.movementY??0,C=this.currMouseButton_===Do&&!I.shiftKey,E=this.currMouseButton_===Do&&I.shiftKey||this.currMouseButton_===Sy;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_=xC;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*so,this.orbitVelocity_.theta+=I*so}pan(A,I){const g=this.currPos_.radius*Ny,B=YA();IE(B,B,this.camera_.right,A),IE(B,B,this.camera_.up,I),BB(B,B,g),UQ(this.panVelocity_,this.panVelocity_,B)}zoom(A){this.orbitVelocity_.radius+=A*Ry}updateCamera(){const A=gB(YA(),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),nQ(this.panVelocity_)<JA&&ga(this.panVelocity_)}}class Wg{normal;signedDistance;constructor(A=cA(0,1,0),I=0){this.normal=HI(A),this.signedDistance=I}set(A,I){this.normal=HI(A),this.signedDistance=I}signedDistanceToPoint(A){return BE(this.normal,A)+this.signedDistance}normalize(){const A=nQ(this.normal);if(A>0){const I=1/A;BB(this.normal,this.normal,I),this.signedDistance*=I}}}class Ly{planes_;constructor(A){this.planes_=[new Wg(YA(),0),new Wg(YA(),0),new Wg(YA(),0),new Wg(YA(),0),new Wg(YA(),0),new Wg(YA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=YA();this.planes_[0].set(gg(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(gg(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(gg(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(gg(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(gg(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(gg(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=YA();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 ho extends Tg{projectionMatrix_=gI();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 cA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return cA(A[4],A[5],A[6])}getViewProjection(){return Rg(gI(),this.projectionMatrix,this.viewMatrix)}get frustum(){return new Ly(this.getViewProjection())}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=fB(A[0],A[1],A[2],1),g=lB(gI(),this.projectionMatrix_),B=QB(cg(),I,g);Ea(B,B,1/B[3]);const C=QB(cg(),B,this.transform.matrix);return cA(C[0],C[1],C[2])}}const yo=1.77,to=128,Go=128/yo,Jy=-1e6,Yy=1e6;class Ky extends ho{width_=to;height_=Go;viewportAspectRatio_=yo;viewportSize_=[to,Go];constructor(A,I,g,B,C=Jy,E=Yy){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=fB(-1,-1,0,1),I=fB(1,1,0,1);const g=lB(gI(),this.getViewProjection());return A=QB(cg(),A,g),I=QB(cg(),I,g),new CI(xA(A[0],A[1]),xA(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],jo(this.projectionMatrix_,-B,B,-C,C,this.near_,this.far_)}}const eo=0;class My{camera_;dragActive_=!1;dragStart_=YA();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=HI(A.worldPos),B=I.deltaY<0?1.05:.95;this.camera_.zoom(B);const C=this.camera_.clipToWorld(A.clipPos),E=UQ(YA(),g,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==eo||(this.dragStart_=HI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=UQ(YA(),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 dy=60,Hy=1.77,yQ=.1,TC=180-yQ;class qy extends ho{fov_;aspectRatio_;constructor(A={}){const{fov:I=dy,aspectRatio:g=Hy,near:B=.1,far:C=1e4,position:E=cA(0,0,0)}=A;if(I<yQ||I>TC)throw new Error(`Invalid field of view: ${I}, must be in [${yQ}, ${TC}] 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(yQ,Math.min(TC,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){vo(this.projectionMatrix_,Wo(this.fov),this.aspectRatio_,this.near_,this.far_)}}const wo=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function tQ(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(wo.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 ly(Q={}){return tQ(WC({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},Q))}function fy(Q={}){return tQ(WC({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"]},Q))}function py(Q={}){return tQ(WC({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!==wo.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function WC(Q,A={}){return{profile:A.profile??Q.profile,prefetch:{...Q.prefetch,...A.prefetch??{}},lod:{...Q.lod,...A.lod??{}},priorityOrder:A.priorityOrder??Q.priorityOrder}}var bC=(()=>{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}})(),my=(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"&&yA("no native wasm support detected");var a,D=!1,s,y,w,k,f,d,T,z;function x(){var G=a.buffer;A.HEAP8=s=new Int8Array(G),A.HEAP16=w=new Int16Array(G),A.HEAPU8=y=new Uint8Array(G),A.HEAPU16=k=new Uint16Array(G),A.HEAP32=f=new Int32Array(G),A.HEAPU32=d=new Uint32Array(G),A.HEAPF32=T=new Float32Array(G),A.HEAPF64=z=new Float64Array(G)}var l=[],Z=[],v=[];function EA(){var G=A.preRun.shift();l.unshift(G)}var hA=0,DA=null;function yA(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 eA=G=>G.startsWith("data:application/octet-stream;base64,"),zA=G=>G.startsWith("file://"),uA;if(uA="blosc_codec.wasm",!eA(uA)){var SA=uA;uA=A.locateFile?A.locateFile(SA,""):""+SA}function uI(G){return Promise.resolve().then(()=>{if(G==uA&&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 uI(G).then(H=>WebAssembly.instantiate(H,r)).then(H=>H).then(N,H=>{i(`failed to asynchronously prepare wasm: ${H}`),yA(H)})}function mI(G,r){var N=uA;return o||typeof WebAssembly.instantiateStreaming!="function"||eA(N)||zA(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 XI=G=>{for(;0<G.length;)G.shift()(A)};function jI(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,ZA,dA=G=>{for(var r="";y[G];)r+=ZA[y[G++]];return r},XA={},MA={},mA={},PA,hg=G=>{throw new PA(G)},yg,GI=(G,r)=>{function N(Y){if(Y=r(Y),Y.length!==H.length)throw new yg("Mismatched type converter count");for(var L=0;L<H.length;++L)HA(H[L],Y[L])}var H=[];H.forEach(function(Y){mA[Y]=G});var h=Array(G.length),e=[],S=0;G.forEach((Y,L)=>{MA.hasOwnProperty(Y)?h[L]=MA[Y]:(e.push(Y),XA.hasOwnProperty(Y)||(XA[Y]=[]),XA[Y].push(()=>{h[L]=MA[Y],++S,S===e.length&&N(h)}))}),e.length===0&&N(h)};function DI(G,r,N={}){var H=r.name;if(!G)throw new PA(`type "${H}" must have a positive integer typeid pointer`);if(MA.hasOwnProperty(G)){if(N.P)return;throw new PA(`Cannot register type '${H}' twice`)}MA[G]=r,delete mA[G],XA.hasOwnProperty(G)&&(r=XA[G],delete XA[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,xI=G=>{G>=_A.H&&--_A.get(G).L===0&&_A.J(G)},Og=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 zI(G){return this.fromWireType(f[G>>2])}var tg=(G,r)=>{switch(r){case 4:return function(N){return this.fromWireType(T[N>>2])};case 8:return function(N){return this.fromWireType(z[N>>3])};default:throw new TypeError(`invalid float width (${r}): ${G}`)}},_I=(G,r)=>Object.defineProperty(r,"name",{value:G}),vg=G=>{for(;G.length;){var r=G.pop();G.pop()(r)}};function Xg(G){for(var r=1;r<G.length;++r)if(G[r]!==null&&G[r].G===void 0)return!0;return!1}function kB(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=_I(r.name||"unknownFunctionName",function(){});return N.prototype=r.prototype,N=new N,G=r.apply(N,G),G instanceof Object?G:N}var LB=(G,r)=>{if(A[G].C===void 0){var N=A[G];A[G]=function(){if(!A[G].C.hasOwnProperty(arguments.length))throw new PA(`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}},Gg=(G,r,N)=>{if(A.hasOwnProperty(G)){if(N===void 0||A[G].C!==void 0&&A[G].C[N]!==void 0)throw new PA(`Cannot register public name '${G}' twice`);if(LB(G,G),A.hasOwnProperty(N))throw new PA(`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)},eg=(G,r)=>{for(var N=[],H=0;H<G;H++)N.push(d[r+4*H>>2]);return N},wg,jg=(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=wg.get(r).apply(null,N);return H}},zg=(G,r)=>{G=dA(G);var N=G.includes("j")?jg(G,r):wg.get(r);if(typeof N!="function")throw new PA(`unknown function pointer with signature ${G}: ${r}`);return N},Fg,rg=G=>{G=O(G);var r=dA(G);return u(G),r},JB=(G,r)=>{function N(e){h[e]||MA[e]||(mA[e]?mA[e].forEach(N):(H.push(e),h[e]=!0))}var H=[],h={};throw r.forEach(N),new Fg(`${G}: `+H.map(rg).join([", "]))},YB=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=>w[H>>1]:H=>k[H>>1];case 4:return N?H=>f[H>>2]:H=>d[H>>2];default:throw new TypeError(`invalid integer width (${r}): ${G}`)}};function ng(G){return this.fromWireType(d[G>>2])}for(var $I=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Sg=(G,r,N)=>{var H=r+N;for(N=r;G[N]&&!(N>=H);)++N;if(16<N-r&&G.buffer&&$I)return $I.decode(G.subarray(r,N));for(H="";r<N;){var h=G[r++];if(h&128){var e=G[r++]&63;if((h&224)==192)H+=String.fromCharCode((h&31)<<6|e);else{var S=G[r++]&63;h=(h&240)==224?(h&15)<<12|e<<6|S:(h&7)<<18|e<<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},$g=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,KB=(G,r)=>{for(var N=G>>1,H=N+r/2;!(N>=H)&&k[N];)++N;if(N<<=1,32<N-G&&$g)return $g.decode(y.subarray(G,N));for(N="",H=0;!(H>=r/2);++H){var h=w[G+2*H>>1];if(h==0)break;N+=String.fromCharCode(h)}return N},MB=(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)w[r>>1]=G.charCodeAt(h),r+=2;return w[r>>1]=0,r-H},dB=G=>2*G.length,AB=(G,r)=>{for(var N=0,H="";!(N>=r/4);){var h=f[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},Ag=(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 e=G.charCodeAt(h);if(55296<=e&&57343>=e){var S=G.charCodeAt(++h);e=65536+((e&1023)<<10)|S&1023}if(f[r>>2]=e,r+=4,r+4>N)break}return f[r>>2]=0,r-H},Ng=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,pA=[null,[],[]],JI=Array(256),jA=0;256>jA;++jA)JI[jA]=String.fromCharCode(jA);ZA=JI,PA=A.BindingError=class extends Error{constructor(G){super(G),this.name="BindingError"}},yg=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},Fg=A.UnboundTypeError=((G,r)=>{var N=_I(r,function(H){this.name=r,this.message=H,H=Error(H).stack,H!==void 0&&(this.stack=this.toString()+`
4222
4222
  `+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 jI(G).I(r,N),$A=G,$A},o:()=>{},l:(G,r,N,H)=>{r=dA(r),HA(G,{name:r,fromWireType:function(h){return!!h},toWireType:function(h,e){return e?N:H},argPackAdvance:8,readValueFromPointer:function(h){return this.fromWireType(y[h])},G:null})},k:(G,r)=>{r=dA(r),HA(G,{name:r,fromWireType:N=>{if(!N)throw new PA("Cannot use deleted val. handle = "+N);var H=_A.get(N).value;return xI(N),H},toWireType:(N,H)=>Og(H),argPackAdvance:8,readValueFromPointer:zI,G:null})},i:(G,r,N)=>{r=dA(r),HA(G,{name:r,fromWireType:H=>H,toWireType:(H,h)=>h,argPackAdvance:8,readValueFromPointer:tg(r,N),G:null})},d:(G,r,N,H,h,e,S)=>{var Y=eg(r,N);G=dA(G),G=YB(G),h=zg(H,h),Gg(G,function(){JB(`Cannot call ${G} due to unbound types`,Y)},r-1),GI(Y,function(L){var m=G,b=G;L=[L[0],null].concat(L.slice(1));var V=h,W=L.length;if(2>W)throw new PA("argTypes array size mismatch! Must at least get return value and 'this' types!");var BA=L[1]!==null&&!1,iA=Xg(L),AI=L[0].name!=="void";V=[hg,V,e,vg,L[0],L[1]];for(var sA=0;sA<W-2;++sA)V.push(L[sA+2]);if(!iA)for(sA=BA?1:2;sA<L.length;++sA)L[sA].G!==null&&V.push(L[sA].G);iA=Xg(L),sA=L.length;var VA="",SI="";for(W=0;W<sA-2;++W)VA+=(W!==0?", ":"")+"arg"+W,SI+=(W!==0?", ":"")+"arg"+W+"Wired";VA=`
4223
4223
  return function (${VA}) {
4224
4224
  if (arguments.length !== ${sA-2}) {