From b9f511f63668b2e33f8013bf8eb68aef03a025c8 Mon Sep 17 00:00:00 2001 From: Ross Date: Mon, 18 May 2026 16:41:01 +0100 Subject: [PATCH] update dv3d --- rad/static/dv3d/index.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/rad/static/dv3d/index.js b/rad/static/dv3d/index.js index cc9c6a40..8d763956 100644 --- a/rad/static/dv3d/index.js +++ b/rad/static/dv3d/index.js @@ -4189,11 +4189,11 @@ fn main( \r `)),o===-1)throw new Error("invalid response - no multipart mime header");if(!s&&(a=$_e(n,0,o).split(`\r `),s=W_e(a),!s))throw new Error("invalid response - no boundary marker");const l=o+4,f=MT(n,s,l);if(f===-1&&!i)throw new Error("invalid response - terminating boundary not found");return c||(c=z_e(a)),r.tokenIndex=o,r.boundary=s,r.responseHeaders=a,r.multipartContentType=c,r.isPartial=f===-1,{contentType:c,extractDone:!i||f!==-1,tokenIndex:o,responseHeaders:a,boundary:s,multipartContentType:c,pixelData:e.slice(l,f-2)}}function W_e(t){for(let e=0;e{if(typeof i.errorInterceptor=="function"){const u=new Error("request failed");i.errorInterceptor(u)}},l=new j_e("streamRequest");return l.generate(async(f,u)=>{var g,p;const d=(g=i.beforeSend)==null?void 0:g.call(i,null,t,r,{}),h=Object.assign({},r,d);Object.keys(h).forEach(function(v){h[v]===null&&(h[v]=void 0),v==="Accept"&&t.indexOf("accept=")!==-1&&(h[v]=void 0)});try{const v=await fetch(t,{headers:h,signal:void 0});if(v.status!==200)throw new Error(`Couldn't retrieve ${t} got status ${v.status}`);const y=v.body.getReader(),m=v.headers,w=m.get("content-type"),x=Number(m.get("Content-Length"));let C=!1,S=a.encodedData,T=a.lastSize||0;for(a.isPartial=!0;!C;){const{done:_,value:E}=await y.read();if(S=H_e(S,E),!S){if(C)throw new Error(`Done but no image frame available ${e}`);continue}if(C=_||S.byteLength===x,!C&&S.lengthr-i&&(console.log(`Truncated fragment, changing fragment length from ${n.length} to ${r-i}`),n.length=r-i)}return t}function X_e(t){let e=lr.parseDicom(t,{untilTag:"x7fe00010"});e.elements.x7fe00010||console.warn("Pixel data not found!");let r;try{r=lr.parseDicom(t)}catch(n){console.error(n),console.log("pixel data dataset:",n.dataSet),r=n.dataSet}return e.elements.x7fe00010=r.elements.x7fe00010,e=q_e(e),e}async function Fz(t,e,r){const n=X_e(t),{uri:i,imageId:o,fileTotalLength:a}=r;return n.fetchMore=async function(s){const c=Object.assign({uri:i,imageId:o,fetchedLength:t.length,lengthToFetch:a-t.length},s),{fetchedLength:l,lengthToFetch:f}=c,{arrayBuffer:u}=await e(i,o,{byteRange:`${l}-${l+f}`}),d=new Uint8Array(u),h=new Uint8Array(n.byteArray.length+d.length);return h.set(n.byteArray),h.set(d,n.byteArray.length),Fz(h,e,r)},n}function Y_e(t,e){if(!t)return;const{NumberOfFrames:r,PerFrameFunctionalGroupsSequence:n,SharedFunctionalGroupsSequence:i}=Bz(t);if(n||r>1){const{shared:o,perFrame:a}=Uz(n,i,e);return{NumberOfFrames:r,PerFrameFunctionalInformation:a,SharedFunctionalInformation:o}}return{NumberOfFrames:r}}function Uz(t,e,r){const n={};(e?Object.values(e.items[0].dataSet.elements):[]).map(o=>n[o.tag]=o);const i={};return(t?Object.values(t.items[r-1].dataSet.elements):[]).map(o=>i[o.tag]=o),{shared:n,perFrame:i}}function Bz(t){if(!t)return;const{elements:e,...r}=t,{x52009230:n,x52009229:i,...o}=e;return{NumberOfFrames:t.intString("x00280008"),PerFrameFunctionalGroupsSequence:n,SharedFunctionalGroupsSequence:i,otherElements:o,otherAttributtes:r}}function J_e(t,e){if(!e)return;const{NumberOfFrames:r,PerFrameFunctionalGroupsSequence:n,SharedFunctionalGroupsSequence:i,otherElements:o}=Bz(e);if(n||r>1){const{shared:a,perFrame:s}=Uz(n,i,t),c={elements:{...o,...a,...s}},l=Object.create(e);return Object.assign(l,c)}return e}let ki={};const Z_e=()=>{ki={}};function $8(t){if(ki[t])return ki[t]}function Q_e(t){const e=$8(t);return Gz(e)}function Gz(t){if(!t)return!1;const e=t.intString("x00280008");return e&&e>1}function e4e(t){return t.indexOf("&frame=")}function t4e(t){const e=e4e(t),r=e===-1?t:t.slice(0,e),n=parseInt(t.slice(e+7),10)||1;let i;return ki[r]?i=ki[r].dataSet:i=void 0,{dataSet:i,frame:n}}function n4e(t){const e=[],r=$8(t);if(Gz(r)){const n=r.intString("x00280008");for(let i=1;i<=n;i++)e.push(`${t}&frame=${i}`)}else e.push(t);return e}const Wz={_get:$8,generateMultiframeWADOURIs:n4e,retrieveMultiframeDataset:t4e,isMultiframeDataset:Q_e};let Ah=0,$f={};function r4e(t){return ki[t]!==void 0}function i4e(t){let e;if(t.includes("&frame=")){const{frame:r,dataSet:n}=Wz.retrieveMultiframeDataset(t);e=J_e(r,n)}else ki[t]&&(e=ki[t].dataSet);return e}function o4e(t,e){const r=ki[t];if(!r){console.error(`No loaded dataSet for uri ${t}`);return}Ah-=r.dataSet.byteArray.length,r.dataSet=e,Ah+=e.byteArray.length,it(Ze,"datasetscachechanged",{uri:t,action:"updated",cacheInfo:ix()})}function a4e(t,e=rx,r){if(ki[t])return new Promise(o=>{ki[t].cacheCount++,o(ki[t].dataSet)});if($f[t])return $f[t].cacheCount++,$f[t];const n=e(t,r),i=new Promise((o,a)=>{n.then(async function(s){const c={isPartialContent:!1,fileTotalLength:null};if(!(s instanceof ArrayBuffer)){if(!s.arrayBuffer)return a(new Error("If not returning ArrayBuffer, must return object with `arrayBuffer` parameter"));c.isPartialContent=s.flags.isPartialContent,c.fileTotalLength=s.flags.fileTotalLength,s=s.arrayBuffer}const l=new Uint8Array(s);let f;try{c.isPartialContent?f=await Fz(l,e,{uri:t,imageId:r,fileTotalLength:c.fileTotalLength}):f=lr.parseDicom(l)}catch(u){return a(u)}ki[t]={dataSet:f,cacheCount:i.cacheCount},Ah+=f.byteArray.length,o(f),it(Ze,"datasetscachechanged",{uri:t,action:"loaded",cacheInfo:ix()})},a).then(()=>{delete $f[t]},()=>{delete $f[t]})});return i.cacheCount=1,$f[t]=i,i}function s4e(t){ki[t]&&(ki[t].cacheCount--,ki[t].cacheCount===0&&(Ah-=ki[t].dataSet.byteArray.length,delete ki[t],it(Ze,"datasetscachechanged",{uri:t,action:"unloaded",cacheInfo:ix()})))}function ix(){return{cacheSizeInBytes:Ah,numberOfDataSetsCached:Object.keys(ki).length}}function c4e(){Z_e(),$f={},Ah=0}const ch={isLoaded:r4e,load:a4e,unload:s4e,getInfo:ix,purge:c4e,get:i4e,update:o4e};function l4e(t){const e=[];for(let r=0;r<=30;r+=2){let n=`x60${r.toString(16)}`;n.length===4&&(n=`x600${r.toString(16)}`);const i=t.elements[`${n}3000`];if(!i)continue;const o=[];for(let a=0;a>s&1}e.push({rows:t.uint16(`${n}0010`),columns:t.uint16(`${n}0011`),type:t.string(`${n}0040`),x:t.int16(`${n}0050`,1)-1,y:t.int16(`${n}0050`,0)-1,pixelData:o,description:t.string(`${n}0022`),label:t.string(`${n}1500`),roiArea:t.string(`${n}1301`),roiMean:t.string(`${n}1302`),roiStandardDeviation:t.string(`${n}1303`)})}return{overlays:e}}function ug(t){return t==="RECON TOMO"||t==="RECON GATED TOMO"}function j8(t,e){const r=t.string("x00080008");if(r){const n=r.split("\\");if(n.length>e)return n[e]}}function u4e(t){let e;const r=t.string("x00080060");if(r!=null&&r.includes("NM")){const n=j8(t,2);n&&ug(n)&&t.elements.x00540022&&(e=gc(t.elements.x00540022.items[0].dataSet,"x00200037",6))}return e}function f4e(t){let e;const r=t.string("x00080060");if(r!=null&&r.includes("NM")){const n=j8(t,2);n&&ug(n)&&t.elements.x00540022&&(e=gc(t.elements.x00540022.items[0].dataSet,"x00200032",3))}return e}function O7(t){let e=gc(t,"x00200037",6);return!e&&t.elements.x00209116&&(e=gc(t.elements.x00209116.items[0].dataSet,"x00200037",6)),e||(e=u4e(t)),e}function M7(t){let e=gc(t,"x00200032",3);return!e&&t.elements.x00209113&&(e=gc(t.elements.x00209113.items[0].dataSet,"x00200032",3)),e||(e=f4e(t)),e}function P7(t){let e=gc(t,"x00280030",2);return!e&&t.elements.x00289110&&(e=gc(t.elements.x00289110.items[0].dataSet,"x00280030",2)),e}function R7(t){let e;return t.elements.x00180050?e=t.floatString("x00180050"):t.elements.x00289110&&t.elements.x00289110.items.length&&t.elements.x00289110.items[0].dataSet.elements.x00180050&&(e=t.elements.x00289110.items[0].dataSet.floatString("x00180050")),e}function zz(t,e,r){const n={};for(const i of r)try{const o=e(i,t);if(o){const a={};for(const s in o)if(s in o){const c=d4e(s);a[c]=o[s]}Object.assign(n,a)}}catch(o){console.error(`Error retrieving ${i} data:`,o)}return n}const d4e=t=>t.charAt(0).toUpperCase()+t.slice(1),$z=["multiframeModule","generalSeriesModule","patientStudyModule","imagePlaneModule","nmMultiframeGeometryModule","imagePixelModule","modalityLutModule","voiLutModule","sopCommonModule","petIsotopeModule","overlayPlaneModule","transferSyntax","petSeriesModule","petImageModule"];function L7(t){const e=t.elements.x00186011;return!e||!e.items?[]:e.items.map(n=>{const i=n.dataSet.double("x0018602c"),o=n.dataSet.double("x0018602e"),a=n.dataSet.uint16("x00186024"),s=n.dataSet.uint16("x00186026"),c=n.dataSet.uint16("x0018601a"),l=n.dataSet.uint16("x0018601e"),f=n.dataSet.uint16("x00186018"),u=n.dataSet.uint16("x0018601c"),d=n.dataSet.int32("x00186020")||null,h=n.dataSet.int32("x00186022")||null,g=n.dataSet.uint16("x0018602a"),p=n.dataSet.uint16("x00186028"),v=n.dataSet.uint16("x00186012"),y=n.dataSet.uint16("x00186014"),m=n.dataSet.uint16("x00186016"),w=n.dataSet.uint16("x00186030");return{regionLocationMinY0:c,regionLocationMaxY1:l,regionLocationMinX0:f,regionLocationMaxX1:u,referencePixelX0:d,referencePixelY0:h,physicalDeltaX:i,physicalDeltaY:o,physicalUnitsXDirection:a,physicalUnitsYDirection:s,referencePhysicalPixelValueY:g,referencePhysicalPixelValueX:p,regionSpatialFormat:v,regionDataType:y,regionFlags:m,transducerFrequency:w}})}function H8(t,e){const{MetadataModules:r}=Ha;if(Array.isArray(e))return;const n=Pm(e);if(t===r.MULTIFRAME){const a=Wz.retrieveMultiframeDataset(n.url);return a.dataSet?Y_e(a.dataSet,a.frame):void 0}let i=n.url;n.frame&&(i=`${i}&frame=${n.frame}`);const o=ch.get(i);if(o)return jz(t,e,o)}function jz(t,e,r){const{MetadataModules:n}=Ha;if(t===n.GENERAL_STUDY)return{studyDescription:r.string("x00081030"),studyDate:lr.parseDA(r.string("x00080020")),studyTime:lr.parseTM(r.string("x00080030")||""),accessionNumber:r.string("x00080050")};if(t===n.GENERAL_SERIES)return{modality:r.string("x00080060"),seriesInstanceUID:r.string("x0020000e"),seriesDescription:r.string("x0008103e"),seriesNumber:r.intString("x00200011"),studyInstanceUID:r.string("x0020000d"),seriesDate:lr.parseDA(r.string("x00080021")),seriesTime:lr.parseTM(r.string("x00080031")||""),acquisitionDate:lr.parseDA(r.string("x00080022")),acquisitionTime:lr.parseTM(r.string("x00080032")||"")};if(t===n.GENERAL_IMAGE)return{sopInstanceUID:r.string("x00080018"),instanceNumber:r.intString("x00200013"),lossyImageCompression:r.string("x00282110"),lossyImageCompressionRatio:r.floatString("x00282112"),lossyImageCompressionMethod:r.string("x00282114")};if(t===n.PATIENT)return{patientID:r.string("x00100020"),patientName:r.string("x00100010")};if(t===n.PATIENT_STUDY)return{patientAge:r.intString("x00101010"),patientSize:r.floatString("x00101020"),patientSex:r.string("x00100040"),patientWeight:r.floatString("x00101030")};if(t===n.NM_MULTIFRAME_GEOMETRY){const i=r.string("x00080060"),o=j8(r,2);return{modality:i,imageType:r.string("x00080008"),imageSubType:o,imageOrientationPatient:O7(r),imagePositionPatient:M7(r),sliceThickness:R7(r),pixelSpacing:P7(r),numberOfFrames:r.uint16("x00280008"),isNMReconstructable:ug(o)&&i.includes("NM")}}if(t===n.IMAGE_PLANE){const i=O7(r),o=M7(r),a=P7(r),s=R7(r);let c=null,l=null;a&&(l=a[0],c=a[1]);let f=null,u=null;return i&&(f=[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])],u=[parseFloat(i[3]),parseFloat(i[4]),parseFloat(i[5])]),{frameOfReferenceUID:r.string("x00200052"),rows:r.uint16("x00280010"),columns:r.uint16("x00280011"),imageOrientationPatient:i,rowCosines:f,columnCosines:u,imagePositionPatient:o,sliceThickness:s,sliceLocation:r.floatString("x00201041"),pixelSpacing:a,rowPixelSpacing:l,columnPixelSpacing:c}}if(t===n.CINE)return{frameTime:r.floatString("x00181063")};if(t===n.IMAGE_PIXEL)return Lz(r);if(t===n.VOI_LUT){const i=Az(r);return{windowCenter:gc(r,"x00281050",1),windowWidth:gc(r,"x00281051",1),voiLUTSequence:IT(i,r.elements.x00283010),voiLUTFunction:r.string("x00281056")}}if(t===n.MODALITY_LUT)return{rescaleIntercept:r.floatString("x00281052"),rescaleSlope:r.floatString("x00281053"),rescaleType:r.string("x00281054"),modalityLUTSequence:IT(r.uint16("x00280103"),r.elements.x00283000)};if(t===n.SOP_COMMON)return{sopClassUID:r.string("x00080016"),sopInstanceUID:r.string("x00080018")};if(t===n.PET_ISOTOPE){const i=r.elements.x00540016;if(i===void 0)return;const o=i.items[0].dataSet;return{radiopharmaceuticalInfo:{radiopharmaceuticalStartTime:lr.parseTM(o.string("x00181072")||""),radionuclideTotalDose:o.floatString("x00181074"),radionuclideHalfLife:o.floatString("x00181075")}}}if(t===n.OVERLAY_PLANE)return l4e(r);if(t==="transferSyntax"){let i;try{i=r.string("x00020010")}catch{}return{transferSyntaxUID:i}}if(t===n.PET_SERIES)return{correctedImage:r.string("x00280051"),units:r.string("x00541001"),decayCorrection:r.string("x00541102")};if(t===n.PET_IMAGE)return{frameReferenceTime:r.floatString(r.string("x00541300")||""),actualFrameDuration:r.intString(r.string("x00181242"))};if(t===n.ULTRASOUND_ENHANCED_REGION)return L7(r);if(t===n.CALIBRATION&&r.string("x00080060")==="US")return{sequenceOfUltrasoundRegions:L7(r)};if(t==="instance")return zz(e,H8,$z)}let ox=[];function h4e(t){return`dicomfile:${ox.push(t)-1}`}function g4e(t){return ox[t]}function p4e(t){ox[t]=void 0}function m4e(){ox=[]}const Hz={add:h4e,get:g4e,remove:p4e,purge:m4e};function v4e(t){const e=t.intString("x00280008"),r=t.elements.x7fe00010;return e!==r.fragments.length}function Kz(t,e){if(t.elements.x7fe00010&&t.elements.x7fe00010.basicOffsetTable.length)return lr.readEncapsulatedImageFrame(t,t.elements.x7fe00010,e);if(v4e(t)){const l=lr.createJPEGBasicOffsetTable(t,t.elements.x7fe00010);return lr.readEncapsulatedImageFrame(t,t.elements.x7fe00010,e,l)}const r=t.elements.x7fe00010.fragments,n=new lr.ByteStream(t.byteArrayParser,t.byteArray,t.elements.x7fe00010.dataOffset),i=lr.readSequenceItem(n);if(i.tag!=="xfffee000")throw"dicomParser.readEncapsulatedPixelData: missing basic offset table xfffee000";n.seek(i.length);const o=n.position;if(e+1>r.length)throw"dicomParser.readEncapsulatedPixelData: frame exceeds number of fragments";const s=o+r[e].offset+8,c=r[e].length;return new Uint8Array(n.byteArray.buffer.slice(n.byteArray.byteOffset+s,n.byteArray.byteOffset+s+c))}function y4e(t,e){return t&1<=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l))}else if(n===16){if(f=c+e*l*2,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l*2))}else if(n===1){if(f=c+e*l*.125,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return qz(t.byteArray,f,l)}else if(n===32){if(f=c+e*l*4,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l*4))}throw new Error("unsupported pixel format")}function Yz(t){const e=Pm(t),r=parseInt(e.url,10),n=Hz.get(r);return new Promise((i,o)=>{const a=new FileReader;a.onload=s=>{const c=s.target.result;i(c)},a.onerror=o,a.readAsArrayBuffer(n)})}function K8(t,e=0){const r=t.elements.x7fe00010||t.elements.x7fe00008;return r?r.encapsulatedPixelData?Kz(t,e):Xz(t,e):null}function ax(t){let e=t[0],r=t[0],n;const i=t.length;for(let o=1;o{const s=new FileReader;s.readAsBinaryString===void 0?s.readAsArrayBuffer(i):s.readAsBinaryString(i),s.onload=function(){const c=new Image;c.onload=function(){r.height=c.height,r.width=c.width,t.rows=c.height,t.columns=c.width;const l=r.getContext("2d");l.drawImage(this,0,0);const f=l.getImageData(0,0,c.width,c.height),u=new Date().getTime();t.pixelData=new Uint8Array(f.data.buffer),t.imageData=f,t.decodeTimeInMS=u-n;const d=ax(t.pixelData);t.smallestPixelValue=d.min,t.largestPixelValue=d.max,t.pixelDataLength=t.pixelData.length,o(t)},c.onerror=function(l){a(l)},s.readAsBinaryString===void 0?c.src=`data:image/jpeg;base64,${window.btoa(C4e(s.result))}`:c.src=`data:image/jpeg;base64,${window.btoa(s.result)}`},s.onerror=c=>{a(c)}})}function ia(t,e,r,n,i){const o={...n};delete o.loader,delete o.streamingData;const a=fl(),s=o.priority||void 0;return o.transferPixelData&&r.buffer,a.executeTask("dicomImageLoader","decodeTask",{imageFrame:t,transferSyntax:e,pixelData:r,options:o,decodeConfig:i},{priority:s,requestType:o==null?void 0:o.requestType})}function T4e(t,e,r,n,i={},o){switch(e){case"1.2.840.10008.1.2":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.1":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.2":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.1.99":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.5":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.50":return t.bitsAllocated===8&&(t.samplesPerPixel===3||t.samplesPerPixel===4)?Zz(t,r,n):ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.51":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.57":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.70":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.80":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.81":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.90":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.91":return ia(t,e,r,i,o);case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":return ia(t,e,r,i,o)}return Promise.reject(new Error(`No decoder for transfer syntax ${e}`))}function Qz(t){const e=ct("imagePixelModule",t);return{samplesPerPixel:e.samplesPerPixel,photometricInterpretation:e.photometricInterpretation,planarConfiguration:e.planarConfiguration,rows:e.rows,columns:e.columns,bitsAllocated:e.bitsAllocated,bitsStored:e.bitsStored,pixelRepresentation:e.pixelRepresentation,smallestPixelValue:e.smallestPixelValue,largestPixelValue:e.largestPixelValue,redPaletteColorLookupTableDescriptor:e.redPaletteColorLookupTableDescriptor,greenPaletteColorLookupTableDescriptor:e.greenPaletteColorLookupTableDescriptor,bluePaletteColorLookupTableDescriptor:e.bluePaletteColorLookupTableDescriptor,redPaletteColorLookupTableData:e.redPaletteColorLookupTableData,greenPaletteColorLookupTableData:e.greenPaletteColorLookupTableData,bluePaletteColorLookupTableData:e.bluePaletteColorLookupTableData,pixelData:void 0,imageId:t}}function _4e(t,e){const r=t.get("modalityLutModule",e)||{},n=t.get("generalSeriesModule",e)||{},{modality:i}=n,o={rescaleSlope:r.rescaleSlope,rescaleIntercept:r.rescaleIntercept,modality:i},a=t.get("scalingModule",e)||{};return{...o,...i==="PT"&&{suvbw:a.suvbw},...i==="RTDOSE"&&{doseGridScaling:a.DoseGridScaling,doseSummation:a.DoseSummation,doseType:a.DoseType,doseUnit:a.DoseUnit}}}function q8(t){return t==="RGB"||t==="PALETTE COLOR"||t==="YBR_FULL"||t==="YBR_FULL_422"||t==="YBR_PARTIAL_422"||t==="YBR_PARTIAL_420"||t==="YBR_RCT"||t==="YBR_ICT"}function E4e(t,e){const r=t.length/4;let n=0,i=0;for(let o=0;o=0?e<=255?r=Uint8Array:e<=65535?r=Uint16Array:e<=4294967295&&(r=Uint32Array):t>=-128&&e<=127?r=Int8Array:t>=-32768&&e<=32767&&(r=Int16Array)),r||Float32Array}function D4e(t,e,r){return X8(t,e)===r}function I4e(t){const e=t.smallestPixelValue,r=t.largestPixelValue,n=X8(e,r);if(n){const i=new n(t.pixelData);t.pixelData=i}else throw new Error("Could not apply a typed array to the pixel data")}let A7="";function sx(t,e,r,n={}){const i=n.useRGBA;if(n.preScale={enabled:n.preScale&&n.preScale.enabled!==void 0?n.preScale.enabled:!0},!(e!=null&&e.length))return Promise.reject(new Error("The pixel data is missing"));const{MetadataModules:o}=Ha,a=document.createElement("canvas"),s=Qz(t);if(s.decodeLevel=n.decodeLevel,n.allowFloatRendering=dw(),n.preScale.enabled){const u=_4e(A4,t);u&&(n.preScale={...n.preScale,scalingParameters:u})}const{decodeConfig:c}=Rm();Object.keys(s).forEach(u=>{(typeof s[u]=="function"||s[u]instanceof Promise)&&delete s[u]});const l=T4e(s,r,e,a,n,c),f=q8(s.photometricInterpretation);return new Promise((u,d)=>{l.then(function(h){let g=!1;if(n.targetBuffer&&n.targetBuffer.type&&!f){const{arrayBuffer:_,type:E,offset:b=0,length:D}=n.targetBuffer,I=h.pixelDataLength,P=b,O=D??I-P,L={Uint8Array,Uint16Array,Int16Array,Float32Array,Uint32Array};if(O!==h.pixelDataLength)throw new Error(`target array for image does not have the same length (${O}) as the decoded image length (${h.pixelDataLength}).`);const B=L[E],H=_?new B(_,P,O):new B(h.pixelData);if(O!==h.pixelDataLength)throw new Error("target array for image does not have the same length as the decoded image length.");h.pixelData=H,g=!0}g||I4e(h);const p=ct(o.IMAGE_PLANE,t)||{},v=ct(o.VOI_LUT,t)||{},y=ct(o.MODALITY_LUT,t)||{},m=ct(o.SOP_COMMON,t)||{},w=ct(o.CALIBRATION,t)||{},{rows:x,columns:C}=h;if(f){if(x4e(h)){a.height=h.rows,a.width=h.columns;let b=a.getContext("2d").createImageData(h.columns,h.rows);i||(b={...b,data:new Uint8ClampedArray(3*h.columns*h.rows)}),Jz(h,b.data,i),h.imageData=b,h.pixelData=b.data,h.pixelDataLength=b.data.length}else if(!i&&h.pixelDataLength===4*x*C){const E=new Uint8Array(h.pixelData.length/4*3);h.pixelData=E4e(h.pixelData,E),h.pixelDataLength=h.pixelData.length}const _=ax(h.pixelData);h.smallestPixelValue=_.min,h.largestPixelValue=_.max}const S=fc.createImageVoxelManager({scalarData:h.pixelData,width:h.columns,height:h.rows,numberOfComponents:h.samplesPerPixel}),T={imageId:t,dataType:h.pixelData.constructor.name,color:f,calibration:w,columnPixelSpacing:p.columnPixelSpacing,columns:h.columns,height:h.rows,preScale:h.preScale,intercept:y.rescaleIntercept?y.rescaleIntercept:0,slope:y.rescaleSlope?y.rescaleSlope:1,invert:h.photometricInterpretation==="MONOCHROME1",minPixelValue:h.smallestPixelValue,maxPixelValue:h.largestPixelValue,rowPixelSpacing:p.rowPixelSpacing,rows:h.rows,sizeInBytes:h.pixelData.byteLength,width:h.columns,windowCenter:v.windowCenter?v.windowCenter[0]:void 0,windowWidth:v.windowWidth?v.windowWidth[0]:void 0,voiLUTFunction:v.voiLUTFunction?v.voiLUTFunction:void 0,decodeTimeInMS:h.decodeTimeInMS,floatPixelData:void 0,imageFrame:h,voxelManager:S,rgba:f&&i,getPixelData:()=>h.pixelData,getCanvas:void 0,numberOfComponents:h.samplesPerPixel};if(T.color&&(T.getCanvas=function(){if(A7===t)return a;const _=T.columns,E=T.rows;a.height=E,a.width=_;const b=a.getContext("2d"),D=b.createImageData(_,E),I=h.pixelData;if(I.length===_*E*4)for(let P=0;P0&&b4e(m.sopClassUID)&&(T.modalityLUT=y.modalityLUTSequence[0]),v.voiLUTSequence&&v.voiLUTSequence.length>0&&(T.voiLUT=v.voiLUTSequence[0]),T.color&&(T.windowWidth=256,T.windowCenter=128),T.windowCenter===void 0||T.windowWidth===void 0){const _=T.imageFrame.smallestPixelValue,E=T.imageFrame.largestPixelValue;T.windowWidth=E-_,T.windowCenter=(E+_)/2}u(T)},d)})}const{ImageQualityStatus:e$}=Ha;function O4e(t,e){t.decache=function(){const r=Pm(e);ch.unload(r.url)}}function t$(t,e,r=0,n,i,o){const a=new Date().getTime(),s={cancelFn:void 0,promise:void 0};return s.promise=new Promise((c,l)=>{t.then(f=>{const u=K8(f,r),d=f.string("x00020010"),h=new Date().getTime(),g=sx(e,u,d,i);O4e(s,e),g.then(p=>{p=p,p.data=f,p.sharedCacheKey=n;const v=new Date().getTime();p.loadTimeInMS=h-a,p.totalTimeInMS=v-a,p.imageQualityStatus=e$.FULL_RESOLUTION,o!==void 0&&o.imageDoneCallback!==void 0&&o.imageDoneCallback(p),c(p)},function(p){l({error:p,dataSet:f})})},function(f){l({error:f})})}),s}function M4e(t,e,r=0,n,i){const o=new Date().getTime();return{promise:new Promise((s,c)=>{const l=new Date().getTime();let f;try{const u=K8(t,r),d=t.string("x00020010");f=sx(e,u,d,i)}catch(u){c({error:u,dataSet:t});return}f.then(u=>{u=u,u.data=t;const d=new Date().getTime();u.loadTimeInMS=l-o,u.totalTimeInMS=d-o,u.imageQualityStatus=e$.FULL_RESOLUTION,s(u)},c)}),cancelFn:void 0}}function n$(t){if(t==="dicomweb"||t==="wadouri")return rx;if(t==="dicomfile")return Yz}function Bv(t,e={}){const r=Pm(t);e=Object.assign({},e),delete e.loader;const n=n$(r.scheme);if(ch.isLoaded(r.url)){const o=ch.get(r.url,n,t);return M4e(o,t,r.pixelDataFrame,r.url,e)}const i=ch.load(r.url,n,t);return t$(i,t,r.frame,r.url,e)}function r$(){ld("dicomweb",Bv),ld("wadouri",Bv),ld("dicomfile",Bv),zh(H8)}const P4e={getImagePixelModule:Lz,getLUTs:IT,getModalityLUTOutputPixelRepresentation:Az,getNumberValues:gc,metaDataProvider:H8,metadataForDataset:jz},R4e={metaData:P4e,dataSetCacheManager:ch,fileManager:Hz,getEncapsulatedImageFrame:Kz,getUncompressedImageFrame:Xz,loadFileRequest:Yz,loadImageFromPromise:t$,getLoaderForScheme:n$,getPixelData:K8,loadImage:Bv,parseImageId:Pm,unpackBinaryFrame:qz,register:r$};function Ht(t,e,r){return e=e||0,!t||!t.Value||Array.isArray(t.Value)&&t.Value.length<=e?r:t.Value[e]}function L4e(t,e,r){const n=Ht(t,e,r);if(n!==void 0)return parseFloat(String(n))}function Fn(t,e){const r=Ht(t,e);if(r!==void 0)return parseFloat(r)}function So(t,e){if(!t||!t.Value||!Array.isArray(t.Value)||e&&t.Value.length>s&1}e.push({rows:Fn(t[`${n}0010`]),columns:Fn(t[`${n}0011`]),type:Ht(t[`${n}0040`]),x:Fn(t[`${n}0050`],1)-1,y:Fn(t[`${n}0050`],0)-1,pixelData:o,description:Ht(t[`${n}0022`]),label:Ht(t[`${n}1500`]),roiArea:Ht(t[`${n}1301`]),roiMean:Ht(t[`${n}1302`]),roiStandardDeviation:Ht(t[`${n}1303`])})}return{overlays:e}}function cx(t){const e=t.indexOf(":");return t.substring(e+1)}function lh(t,e=!0){return t&&t.Value?t.Value[0]&&e?t.Value[0]:t.Value:t}function i$(t,e,r){const n=(e?Object.values(e[0]):[]).map(o=>{var a;return(a=o.Value)==null?void 0:a[0]}).filter(o=>o!==void 0&&typeof o=="object"),i=(t?Object.values(t[r-1]):[]).map(o=>{var a;return(a=o.Value)==null?void 0:a[0]}).filter(o=>o!==void 0&&typeof o=="object");return{shared:n,perFrame:i}}function o$(t){let{52009230:e,52009229:r,"00280008":n,...i}=t;return e=lh(e,!1),r=lh(r,!1),n=lh(n),{PerFrameFunctionalGroupsSequence:e,SharedFunctionalGroupsSequence:r,NumberOfFrames:n,rest:i}}function N4e(t,e){const{PerFrameFunctionalGroupsSequence:r,SharedFunctionalGroupsSequence:n,NumberOfFrames:i,rest:o}=o$(e);if(r||i>1){const{shared:a,perFrame:s}=i$(r,n,t),c=Object.assign(e,{frameNumber:t});return[...a,...s].forEach(l=>{Object.entries(l).forEach(([f,u])=>{c[f]=u})}),Object.assign(o,{"00280008":i},c)}return e}let Lm=[],L5={};function a$(t){const e=t.indexOf("/frames/")+8,r=t.slice(0,e),n=parseInt(t.slice(e),10);return{metadata:Lm[`${r}1`],frame:n}}function k4e(t){const e=cx(t);return a$(e)}function V4e(t){if(t[52009230]!==void 0||t[52009229]!==void 0)return!0;const e=Ht(t["00280008"]);return e&&e>1}function F4e(t,e){const r=cx(t);Object.defineProperty(e,"isMultiframe",{value:V4e(e),enumerable:!1}),Lm[r]=e}function U4e(t){const e=cx(t),r=Lm[e];if(r&&!(r!=null&&r.isMultiframe))return r;const n=L5[e];if(n)return n;const i=a$(e);if(!i||!i.metadata)return;const{metadata:o,frame:a}=i;if(o){const s=N4e(a,o);return L5[e]=s,s}}function B4e(t){const e=cx(t);Lm[e]=void 0,L5[e]=void 0}function G4e(){Lm=[],L5={}}const Y8={add:F4e,get:U4e,remove:B4e,purge:G4e};function s$(t){return Ht(t["00080060"]).includes("NM")}function J8(t,e){const r=lh(t["00080008"],!1);if(r)return r[e]}function W4e(t){let e;const r=J8(t,2);if(r&&ug(r)){const n=lh(t["00540022"]);n&&(e=So(n["00200037"],6))}return e}function z4e(t){let e;const r=J8(t,2);if(r&&ug(r)){const n=lh(t["00540022"]);n&&(e=So(n["00200032"],3))}return e}function N7(t){let e=So(t["00200037"],6);return!e&&s$(t)&&(e=W4e(t)),e}function k7(t){let e=So(t["00200032"],3);return!e&&s$(t)&&(e=z4e(t)),e}function xo(t,e){const r=So(t[e]);return r?r[0]:null}function $4e(t){var e;return(e=t==null?void 0:t.Value)!=null&&e.length?Array.isArray(t.Value)?t.Value:typeof t.Value=="object"?(console.warn("Warning: Value should be an array, but an object was found. Encapsulating the object in an array."),[t.Value]):[]:[]}function V7(t){const e=$4e(t["00186011"]);return!e||!e.length?null:e.map(n=>{const i=xo(n,"0018602C"),o=xo(n,"0018602E"),a=xo(n,"00186024"),s=xo(n,"00186026"),c=xo(n,"0018601A"),l=xo(n,"0018601E"),f=xo(n,"00186018"),u=xo(n,"0018601C"),d=xo(n,"00186020"),h=xo(n,"00186022"),g=xo(n,"0018602A"),p=xo(n,"00186028"),v=xo(n,"00186012"),y=xo(n,"00186014"),m=xo(n,"00186016"),w=xo(n,"00186030");return{regionLocationMinY0:c,regionLocationMaxY1:l,regionLocationMinX0:f,regionLocationMaxX1:u,referencePixelX0:d,referencePixelY0:h,physicalDeltaX:i,physicalDeltaY:o,physicalUnitsXDirection:a,physicalUnitsYDirection:s,referencePhysicalPixelValueY:g,referencePhysicalPixelValueX:p,regionSpatialFormat:v,regionDataType:y,regionFlags:m,transducerFrequency:w}})}function Z8(t,e){const{MetadataModules:r}=Ha;if(t===r.MULTIFRAME){const{metadata:i,frame:o}=k4e(e);if(!i)return;const{PerFrameFunctionalGroupsSequence:a,SharedFunctionalGroupsSequence:s,NumberOfFrames:c}=o$(i);if(a||c>1){const{shared:l,perFrame:f}=i$(a,s,o);return{NumberOfFrames:c,PerFrameFunctionalInformation:f,SharedFunctionalInformation:l}}return{NumberOfFrames:c}}const n=Y8.get(e);if(n){if(t===r.GENERAL_STUDY)return{studyDescription:Ht(n["00081030"]),studyDate:lr.parseDA(Ht(n["00080020"])),studyTime:lr.parseTM(Ht(n["00080030"],0,"")),accessionNumber:Ht(n["00080050"])};if(t===r.GENERAL_SERIES)return{modality:Ht(n["00080060"]),seriesInstanceUID:Ht(n["0020000E"]),seriesDescription:Ht(n["0008103E"]),seriesNumber:Fn(n["00200011"]),studyInstanceUID:Ht(n["0020000D"]),seriesDate:lr.parseDA(Ht(n["00080021"])),seriesTime:lr.parseTM(Ht(n["00080031"],0,"")),acquisitionDate:lr.parseDA(Ht(n["00080022"])),acquisitionTime:lr.parseTM(Ht(n["00080032"],0,""))};if(t===r.GENERAL_IMAGE)return{sopInstanceUID:Ht(n["00080018"]),instanceNumber:Fn(n["00200013"]),lossyImageCompression:Ht(n["00282110"]),lossyImageCompressionRatio:Fn(n["00282112"]),lossyImageCompressionMethod:Ht(n["00282114"])};if(t===r.PATIENT)return{patientID:Ht(n["00100020"]),patientName:Ht(n["00100010"])};if(t===r.PATIENT_STUDY)return{patientAge:Fn(n["00101010"]),patientSize:Fn(n["00101020"]),patientSex:Ht(n["00100040"]),patientWeight:Fn(n["00101030"])};if(t===r.NM_MULTIFRAME_GEOMETRY){const i=Ht(n["00080060"]),o=J8(n,2);return{modality:i,imageType:Ht(n["00080008"]),imageSubType:o,imageOrientationPatient:N7(n),imagePositionPatient:k7(n),sliceThickness:Fn(n["00180050"]),spacingBetweenSlices:Fn(n["00180088"]),pixelSpacing:So(n["00280030"],2),numberOfFrames:Fn(n["00280008"]),isNMReconstructable:ug(o)&&i.includes("NM")}}if(t===r.IMAGE_PLANE){let i=N7(n),o=k7(n);const a=So(n["00280030"],2);let s=null,c=null,l=null,f=null,u=!1;return a?(c=a[0],s=a[1]):(u=!0,c=1,s=1),i?(l=[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])],f=[parseFloat(i[3]),parseFloat(i[4]),parseFloat(i[5])]):(l=[1,0,0],f=[0,1,0],u=!0,i=[...l,...f]),o||(o=[0,0,0],u=!0),{frameOfReferenceUID:Ht(n["00200052"]),rows:Fn(n["00280010"]),columns:Fn(n["00280011"]),imageOrientationPatient:i,rowCosines:l,columnCosines:f,imagePositionPatient:o,sliceThickness:Fn(n["00180050"]),sliceLocation:Fn(n["00201041"]),pixelSpacing:a,rowPixelSpacing:c,columnPixelSpacing:s,usingDefaultValues:u}}if(t===r.ULTRASOUND_ENHANCED_REGION)return V7(n);if(t===r.CALIBRATION&&Ht(n["00080060"])==="US")return{sequenceOfUltrasoundRegions:V7(n)};if(t===r.IMAGE_URL)return j4e(e,n);if(t===r.CINE)return H4e(e,n);if(t===r.IMAGE_PIXEL)return{samplesPerPixel:Fn(n["00280002"]),photometricInterpretation:Ht(n["00280004"]),rows:Fn(n["00280010"]),columns:Fn(n["00280011"]),bitsAllocated:Fn(n["00280100"]),bitsStored:Fn(n["00280101"]),highBit:Ht(n["00280102"]),pixelRepresentation:Fn(n["00280103"]),planarConfiguration:Fn(n["00280006"]),pixelAspectRatio:Ht(n["00280034"]),smallestPixelValue:Fn(n["00280106"]),largestPixelValue:Fn(n["00280107"]),redPaletteColorLookupTableDescriptor:So(n["00281101"]),greenPaletteColorLookupTableDescriptor:So(n["00281102"]),bluePaletteColorLookupTableDescriptor:So(n["00281103"]),redPaletteColorLookupTableData:So(n["00281201"]),greenPaletteColorLookupTableData:So(n["00281202"]),bluePaletteColorLookupTableData:So(n["00281203"])};if(t===r.VOI_LUT)return{windowCenter:So(n["00281050"],1),windowWidth:So(n["00281051"],1),voiLUTFunction:Ht(n["00281056"])};if(t===r.MODALITY_LUT)return{rescaleIntercept:Fn(n["00281052"]),rescaleSlope:Fn(n["00281053"]),rescaleType:Ht(n["00281054"])};if(t===r.SOP_COMMON)return{sopClassUID:Ht(n["00080016"]),sopInstanceUID:Ht(n["00080018"])};if(t===r.PET_ISOTOPE){const i=Ht(n["00540016"]);return i===void 0?void 0:{radiopharmaceuticalInfo:{radiopharmaceuticalStartTime:lr.parseTM(Ht(i["00181072"],0,"")),radiopharmaceuticalStartDateTime:Ht(i["00181078"],0,""),radionuclideTotalDose:Fn(i["00181074"]),radionuclideHalfLife:Fn(i["00181075"])}}}if(t===r.OVERLAY_PLANE)return A4e(n);if(t==="transferSyntax")return c$(e,n);if(t===r.PET_SERIES)return{correctedImage:Ht(n["00280051"]),units:Ht(n["00541001"]),decayCorrection:Ht(n["00541102"])};if(t===r.PET_IMAGE)return{frameReferenceTime:Fn(n["00541300"]),actualFrameDuration:Fn(n["00181242"])};if(t==="instance")return zz(e,Z8,$z)}}function j4e(t,e){const{transferSyntaxUID:r}=c$(t,e),n=OV(r),i=t.substring(7),o=i.replace("/frames/","/thumbnail/");let a=i.replace("/frames/","/rendered/");return n&&(a=a.replace("/rendered/1","/rendered")),{isVideo:n,rendered:a,thumbnail:o}}function H4e(t,e){return{cineRate:Ht(e["00180040"]),numberOfFrames:Fn(e["00280008"])}}function c$(t,e){return{transferSyntaxUID:Ht(e["00020010"])||Ht(e["00083002"])}}function K4e(t,e,r={},n={}){const i=Rm(),{retrieveOptions:o={},streamingData:a}=n,s=a.chunkSize||X4e(e,o,"chunkSize")||65536,c=f=>{if(typeof i.errorInterceptor=="function"){const u=new Error("request failed");i.errorInterceptor(u)}else console.warn("rangeRequest:Caught",f)};return new Promise(async(f,u)=>{const d=Object.assign({},r);Object.keys(d).forEach(function(h){(d[h]===null||d[h]===void 0)&&delete d[h]});try{a.encodedData||(a.chunkSize=s,a.rangesFetched=0);const h=Y4e(a,o),{encodedData:g,responseHeaders:p}=await q4e(t,d,h,a),v=p.get("content-type"),{totalBytes:y}=a,m=y===g.byteLength,w=W8(v,g,{isPartial:!0}),x=z8(o,m||w.extractDone);f({...w,imageQualityStatus:x,percentComplete:w.extractDone?100:s*100/y})}catch(h){c(h),console.error(h),u(h)}})}async function q4e(t,e,r,n){r&&(e=Object.assign(e,{Range:`bytes=${r[0]}-${r[1]}`}));let{encodedData:i}=n;if(r[1]&&(i==null?void 0:i.byteLength)>r[1])return n;const o=await fetch(t,{headers:e,signal:void 0}),a=await o.arrayBuffer(),s=new Uint8Array(a),{status:c}=o;let l;i?(l=new Uint8Array(i.length+s.length),l.set(i,0),l.set(s,i.length),n.rangesFetched=1):(l=new Uint8Array(s.length),l.set(s,0),n.rangesFetched++),n.encodedData=i=l,n.responseHeaders=o.headers;const f=o.headers.get("Content-Range");return f?n.totalBytes=Number(f.split("/")[1]):c!==206||!r?n.totalBytes=i==null?void 0:i.byteLength:r[1]===""||(i==null?void 0:i.length)r-i?[(n==null?void 0:n.byteLength)||0,""]:[(n==null?void 0:n.byteLength)||0,i*(o+1)-1]}function Q8(t,e,r="application/octet-stream",n){const{streamingData:i,retrieveOptions:o={}}=n||{},a={Accept:r};let s=o.urlArguments?`${t}${t.indexOf("?")===-1?"?":"&"}${o.urlArguments}`:t;if(o.framesPath&&(s=s.replace("/frames/",o.framesPath)),(i==null?void 0:i.url)!==s&&(n.streamingData={url:s}),o.rangeIndex!==void 0)return K4e(s,e,a,n);if(o.streaming)return Vz(s,e,a,n);const c=rx(s,e,a),{xhr:l}=c;return c.then(function(f){const u=l.getResponseHeader("Content-Type")||"application/octet-stream",d=W8(u,new Uint8Array(f));return d.imageQualityStatus=z8(o,!0),d})}const{ProgressiveIterator:F7}=pn,{ImageQualityStatus:U7}=Ha,J4e=new Set(["3.2.840.10008.1.2.4.96","1.2.840.10008.1.2.4.202","1.2.840.10008.1.2.4.203"]);function Z4e(t){const e="1.2.840.10008.1.2";if(!t)return e;const r=t.split(";"),n={};r.forEach(o=>{const a=o.split("=");if(a.length!==2)return;const s=a[1].trim().replace(/"/g,"");n[a[0].trim()]=s});const i={"image/jpeg":"1.2.840.10008.1.2.4.50","image/x-dicom-rle":"1.2.840.10008.1.2.5","image/x-jls":"1.2.840.10008.1.2.4.80","image/jls":"1.2.840.10008.1.2.4.80","image/jll":"1.2.840.10008.1.2.4.70","image/jp2":"1.2.840.10008.1.2.4.90","image/jpx":"1.2.840.10008.1.2.4.92","image/jphc":"3.2.840.10008.1.2.4.96","image/jxl":"1.2.840.10008.1.2.4.140"};return n["transfer-syntax"]?n["transfer-syntax"]:t&&!Object.keys(n).length&&i[t]?i[t]:n.type&&i[n.type]?i[n.type]:i[t]?i[t]:e}function Q4e(){return qh}const eEe="multipart/related; type=application/octet-stream; transfer-syntax=*";function l$(t,e={}){const r=Q4e(),n=new Date().getTime(),i=new F7("decompress");async function o(f,u,d){i.generate(async h=>{var v;const g=F7.as(Q8(f,u,d,e));let p=10;for await(const y of g){const{pixelData:m,imageQualityStatus:w=U7.FULL_RESOLUTION,percentComplete:x,done:C=!0,extractDone:S=!0}=y,T=Z4e(y.contentType);if(!S&&!J4e.has(T))continue;const _=y.decodeLevel??(w===U7.FULL_RESOLUTION?0:tEe(x,(v=e.retrieveOptions)==null?void 0:v.decodeLevel));if(!(!C&&p<=_))try{const E={...e,decodeLevel:_},b=await sx(u,m,T,E),D=new Date().getTime();b.loadTimeInMS=D-n,b.transferSyntaxUID=T,b.imageQualityStatus=w,h.add(b,C),p=_}catch(E){if(S)throw console.warn("Couldn't decode",E),E}}})}const a=e.requestType||Qt.Interaction,s=e.additionalDetails||{imageId:t},c=e.priority===void 0?5:e.priority,l=t.substring(7);return r.addRequest(o.bind(this,l,t,eEe),a,s,c),{promise:i.getDonePromise(),cancelFn:void 0}}function tEe(t,e=4){const r=t/100-.02;return r>1/4?Math.min(e,0):r>1/16?Math.min(e,1):r>1/64?Math.min(e,2):Math.min(e,3)}function u$(){ld("wadors",l$),zh(Z8)}const nEe={getNumberString:L4e,getNumberValue:Fn,getNumberValues:So,getValue:Ht,metaDataProvider:Z8},rEe={metaData:nEe,findIndexOfString:MT,getPixelData:Q8,loadImage:l$,metaDataManager:Y8,register:u$};function iEe(){u$(),r$()}const oEe=()=>new Worker(new URL("/static/dv3d/assets/decodeImageFrameWorker-DhtpjVX0.js",import.meta.url),{type:"module"});function f$(t={}){kz(t),iEe();const e=fl(),r=(t==null?void 0:t.maxWebWorkers)||aEe();e.registerWorker("dicomImageLoader",oEe,{maxWorkerInstances:r})}function aEe(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.max(1,Math.floor(navigator.hardwareConcurrency/2)):1}function sEe(t,e){if(e=e||t.transferSyntax,t.bitsAllocated===8&&e==="1.2.840.10008.1.2.4.50"&&(t.samplesPerPixel===3||t.samplesPerPixel===4))return!0}const cEe={IMPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2",EXPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2.1",DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2.1.99",EXPLICIT_VR_BIG_ENDIAN:"1.2.840.10008.1.2.2",JPEG_BASELINE_PROCESS_1:"1.2.840.10008.1.2.4.50",JPEG_EXTENDED_PROCESS_2_4:"1.2.840.10008.1.2.4.51",JPEG_EXTENDED_PROCESSES_3_5:"1.2.840.10008.1.2.4.52",JPEG_SPECTRAL_SELECTION_NONHIERARCHICAL_PROCESSES_6_8:"1.2.840.10008.1.2.4.53",JPEG_SPECTRAL_SELECTION_NONHIERARCHICAL_PROCESSES_7_9:"1.2.840.10008.1.2.4.54",JPEG_FULL_PROGRESSION_NONHIERARCHICAL_PROCESSES_10_12:"1.2.840.10008.1.2.4.55",JPEG_FULL_PROGRESSION_NONHIERARCHICAL_PROCESSES_11_13:"1.2.840.10008.1.2.4.56",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_14:"1.2.840.10008.1.2.4.57",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_15:"1.2.840.10008.1.2.4.58",JPEG_EXTENDED_HIERARCHICAL_PROCESSES_16_18:"1.2.840.10008.1.2.4.59",JPEG_EXTENDED_HIERARCHICAL_PROCESSES_17_19:"1.2.840.10008.1.2.4.60",JPEG_SPECTRAL_SELECTION_HIERARCHICAL_PROCESSES_20_22:"1.2.840.10008.1.2.4.61",JPEG_SPECTRAL_SELECTION_HIERARCHICAL_PROCESSES_21_23:"1.2.840.10008.1.2.4.62",JPEG_FULL_PROGRESSION_HIERARCHICAL_PROCESSES_24_26:"1.2.840.10008.1.2.4.63",JPEG_FULL_PROGRESSION_HIERARCHICAL_PROCESSES_25_27:"1.2.840.10008.1.2.4.64",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_28:"1.2.840.10008.1.2.4.65",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_29:"1.2.840.10008.1.2.4.66",JPEG_LOSSLESS_NONHIERARCHICAL_FIRST_ORDER_PREDICTION_PROCESS_14:"1.2.840.10008.1.2.4.70",JPEG_LS_LOSSLESS_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.80",JPEG_LS_LOSSY_NEAR_LOSSLESS_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.81",JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY:"1.2.840.10008.1.2.4.90",JPEG_2000_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.91",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY:"1.2.840.10008.1.2.4.92",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.93",JPIP_REFERENCED:"1.2.840.10008.1.2.4.94",JPIP_REFERENCED_DEFLATE:"1.2.840.10008.1.2.4.95",MPEG2_MAIN_PROFILE_MAIN_LEVEL:"1.2.840.10008.1.2.4.100",MPEG4_AVC_H264_HIGH_PROFILE_LEVEL_4_1:"1.2.840.10008.1.2.4.101",MPEG4_AVC_H264_BD_COMPATIBLE_HIGH_PROFILE_LEVEL_4_1:"1.2.840.10008.1.2.4.102",MPEG4_AVC_H264_HIGH_PROFILE_FOR_2D_VIDEO:"1.2.840.10008.1.2.4.103",MPEG4_AVC_H264_HIGH_PROFILE_FOR_3D_VIDEO:"1.2.840.10008.1.2.4.104",JPIP_LOSSLESS:"1.2.840.10008.1.2.4.96",JPIP_PART2_MULTICOMPONENT_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.97",RFC_2557_MIME_ENCAPSULATION:"1.2.840.10008.1.2.6.1",JPEG_XR_IMAGE_COMPRESSION:"1.2.840.10008.1.2.6.2",JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY_RETIRED:"1.2.840.10008.1.2.4.90R",JPEG_2000_IMAGE_COMPRESSION_RETIRED:"1.2.840.10008.1.2.4.91R",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY_RETIRED:"1.2.840.10008.1.2.4.92R",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_RETIRED:"1.2.840.10008.1.2.4.93R"},lEe=Object.freeze(Object.defineProperty({__proto__:null,transferSyntaxes:cEe},Symbol.toStringTag,{value:"Module"}));function uEe(t,e){const{rows:r,columns:n,data:i}=t,{rows:o,columns:a,data:s}=e,c=[],l=[],f=[];for(let u=0;u>8&255}async function hEe(t,e){if(t.bitsAllocated===16){let r=e.buffer,n=e.byteOffset;const i=e.length;n%2&&(r=r.slice(n),n=0),t.pixelRepresentation===0?t.pixelData=new Uint16Array(r,n,i/2):t.pixelData=new Int16Array(r,n,i/2);for(let o=0;o=0&&g<=127)for(let p=0;p=-127){const p=a[u++];for(let v=0;v<-g+1&&c=0&&g<=127)for(let p=0;p=-127){const p=a[u++];for(let v=0;v<-g+1&&c=0&&g<=127)for(let p=0;p=-127){const p=a[d++];for(let v=0;v<-g+1&&f{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(R,V){a=R,s=V});var c=Object.assign({},o),l="./this.program",f=(R,V)=>{throw V},u=typeof window=="object",d=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function p(R){return o.locateFile?o.locateFile(R,g):g+R}var v,y,m;if(h){var w=el,x=el;d?g=x.dirname(g)+"/":g=__dirname+"/",v=(R,V)=>(R=pe(R)?new URL(R):x.normalize(R),w.readFileSync(R,V?void 0:"utf8")),m=R=>{var V=v(R,!0);return V.buffer||(V=new Uint8Array(V)),V},y=(R,V,Y)=>{R=pe(R)?new URL(R):x.normalize(R),w.readFile(R,function(ye,xe){ye?Y(ye):V(xe.buffer)})},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(R){if(!(R instanceof pt))throw R}),process.on("unhandledRejection",function(R){throw R}),f=(R,V)=>{throw process.exitCode=R,V},o.inspect=function(){return"[Emscripten Module object]"}}else(u||d)&&(d?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),n&&(g=n),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",v=R=>{var V=new XMLHttpRequest;return V.open("GET",R,!1),V.send(null),V.responseText},d&&(m=R=>{var V=new XMLHttpRequest;return V.open("GET",R,!1),V.responseType="arraybuffer",V.send(null),new Uint8Array(V.response)}),y=(R,V,Y)=>{var ye=new XMLHttpRequest;ye.open("GET",R,!0),ye.responseType="arraybuffer",ye.onload=()=>{if(ye.status==200||ye.status==0&&ye.response){V(ye.response);return}Y()},ye.onerror=Y,ye.send(null)});var C=o.print||console.log.bind(console),S=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&(l=o.thisProgram),o.quit&&(f=o.quit);var T;o.wasmBinary&&(T=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&se("no native wasm support detected");var _,E=!1;function b(R,V){R||se(V)}var D=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function I(R,V,Y){for(var ye=V+Y,xe=V;R[xe]&&!(xe>=ye);)++xe;if(xe-V>16&&R.buffer&&D)return D.decode(R.subarray(V,xe));for(var Ce="";V>10,56320|qe&1023)}}return Ce}function P(R,V){return R?I(F,R,V):""}function O(R,V,Y,ye){if(!(ye>0))return 0;for(var xe=Y,Ce=Y+ye-1,Te=0;Te=55296&&Me<=57343){var Ae=R.charCodeAt(++Te);Me=65536+((Me&1023)<<10)|Ae&1023}if(Me<=127){if(Y>=Ce)break;V[Y++]=Me}else if(Me<=2047){if(Y+1>=Ce)break;V[Y++]=192|Me>>6,V[Y++]=128|Me&63}else if(Me<=65535){if(Y+2>=Ce)break;V[Y++]=224|Me>>12,V[Y++]=128|Me>>6&63,V[Y++]=128|Me&63}else{if(Y+3>=Ce)break;V[Y++]=240|Me>>18,V[Y++]=128|Me>>12&63,V[Y++]=128|Me>>6&63,V[Y++]=128|Me&63}}return V[Y]=0,Y-xe}function L(R,V,Y){return O(R,F,V,Y)}function B(R){for(var V=0,Y=0;Y=55296&&ye<=57343?(V+=4,++Y):V+=3}return V}var H,A,F,G,X,ee,ce,Se,we;function _e(R){H=R,o.HEAP8=A=new Int8Array(R),o.HEAP16=G=new Int16Array(R),o.HEAP32=ee=new Int32Array(R),o.HEAPU8=F=new Uint8Array(R),o.HEAPU16=X=new Uint16Array(R),o.HEAPU32=ce=new Uint32Array(R),o.HEAPF32=Se=new Float32Array(R),o.HEAPF64=we=new Float64Array(R)}o.INITIAL_MEMORY;var Ve,Ge=[],Ne=[],j=[];function M(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)J(o.preRun.shift());dt(Ge)}function q(){dt(Ne)}function K(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)ie(o.postRun.shift());dt(j)}function J(R){Ge.unshift(R)}function re(R){Ne.unshift(R)}function ie(R){j.unshift(R)}var Re=0,Fe=null;function je(R){Re++,o.monitorRunDependencies&&o.monitorRunDependencies(Re)}function Xe(R){if(Re--,o.monitorRunDependencies&&o.monitorRunDependencies(Re),Re==0&&Fe){var V=Fe;Fe=null,V()}}function se(R){o.onAbort&&o.onAbort(R),R="Aborted("+R+")",S(R),E=!0,R+=". Build with -sASSERTIONS for more info.";var V=new WebAssembly.RuntimeError(R);throw s(V),V}var ue="data:application/octet-stream;base64,";function Pe(R){return R.startsWith(ue)}function pe(R){return R.startsWith("file://")}var Ee;Ee="libjpegturbowasm_decode.wasm",Pe(Ee)||(Ee=p(Ee));function Qe(R){try{if(R==Ee&&T)return new Uint8Array(T);if(m)return m(R);throw"both async and sync fetching of the wasm failed"}catch(V){se(V)}}function fe(){if(!T&&(u||d)){if(typeof fetch=="function"&&!pe(Ee))return fetch(Ee,{credentials:"same-origin"}).then(function(R){if(!R.ok)throw"failed to load wasm binary file at '"+Ee+"'";return R.arrayBuffer()}).catch(function(){return Qe(Ee)});if(y)return new Promise(function(R,V){y(Ee,function(Y){R(new Uint8Array(Y))},V)})}return Promise.resolve().then(function(){return Qe(Ee)})}function ft(){var R={a:de};function V(Te,Me){var Ae=Te.exports;o.asm=Ae,_=o.asm.K,_e(_.buffer),Ve=o.asm.M,re(o.asm.L),Xe()}je();function Y(Te){V(Te.instance)}function ye(Te){return fe().then(function(Me){return WebAssembly.instantiate(Me,R)}).then(function(Me){return Me}).then(Te,function(Me){S("failed to asynchronously prepare wasm: "+Me),se(Me)})}function xe(){return!T&&typeof WebAssembly.instantiateStreaming=="function"&&!Pe(Ee)&&!pe(Ee)&&!h&&typeof fetch=="function"?fetch(Ee,{credentials:"same-origin"}).then(function(Te){var Me=WebAssembly.instantiateStreaming(Te,R);return Me.then(Y,function(Ae){return S("wasm streaming compile failed: "+Ae),S("falling back to ArrayBuffer instantiation"),ye(Y)})}):ye(Y)}if(o.instantiateWasm)try{var Ce=o.instantiateWasm(R,V);return Ce}catch(Te){S("Module.instantiateWasm callback failed with error: "+Te),s(Te)}return xe().catch(s),{}}function pt(R){this.name="ExitStatus",this.message="Program terminated with exit("+R+")",this.status=R}function dt(R){for(;R.length>0;)R.shift()(o)}function Ue(R){this.excPtr=R,this.ptr=R-24,this.set_type=function(V){ce[this.ptr+4>>2]=V},this.get_type=function(){return ce[this.ptr+4>>2]},this.set_destructor=function(V){ce[this.ptr+8>>2]=V},this.get_destructor=function(){return ce[this.ptr+8>>2]},this.set_refcount=function(V){ee[this.ptr>>2]=V},this.set_caught=function(V){V=V?1:0,A[this.ptr+12>>0]=V},this.get_caught=function(){return A[this.ptr+12>>0]!=0},this.set_rethrown=function(V){V=V?1:0,A[this.ptr+13>>0]=V},this.get_rethrown=function(){return A[this.ptr+13>>0]!=0},this.init=function(V,Y){this.set_adjusted_ptr(0),this.set_type(V),this.set_destructor(Y),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var V=ee[this.ptr>>2];ee[this.ptr>>2]=V+1},this.release_ref=function(){var V=ee[this.ptr>>2];return ee[this.ptr>>2]=V-1,V===1},this.set_adjusted_ptr=function(V){ce[this.ptr+16>>2]=V},this.get_adjusted_ptr=function(){return ce[this.ptr+16>>2]},this.get_exception_ptr=function(){var V=te(this.get_type());if(V)return ce[this.excPtr>>2];var Y=this.get_adjusted_ptr();return Y!==0?Y:this.excPtr}}function nt(R,V,Y){var ye=new Ue(R);throw ye.init(V,Y),R}var at={};function ot(R){for(;R.length;){var V=R.pop(),Y=R.pop();Y(V)}}function lt(R){return this.fromWireType(ee[R>>2])}var _t={},vt={},Mt={},Ft=48,wn=57;function Dn(R){if(R===void 0)return"_unknown";R=R.replace(/[^a-zA-Z0-9_]/g,"$");var V=R.charCodeAt(0);return V>=Ft&&V<=wn?"_"+R:R}function Nt(R,V){return R=Dn(R),new Function("body","return function "+R+`() { + See http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.3.html for more information.`));const c=r.dataOffset,l=i*o*a;let f;if(n===8){if(f=c+e*l,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l))}else if(n===16){if(f=c+e*l*2,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l*2))}else if(n===1){if(f=c+e*l*.125,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return qz(t.byteArray,f,l)}else if(n===32){if(f=c+e*l*4,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l*4))}throw new Error("unsupported pixel format")}function Yz(t){const e=Pm(t),r=parseInt(e.url,10),n=Hz.get(r);return new Promise((i,o)=>{const a=new FileReader;a.onload=s=>{const c=s.target.result;i(c)},a.onerror=o,a.readAsArrayBuffer(n)})}function K8(t,e=0){const r=t.elements.x7fe00010||t.elements.x7fe00008;return r?r.encapsulatedPixelData?Kz(t,e):Xz(t,e):null}function ax(t){let e=t[0],r=t[0],n;const i=t.length;for(let o=1;o{const s=new FileReader;s.readAsBinaryString===void 0?s.readAsArrayBuffer(i):s.readAsBinaryString(i),s.onload=function(){const c=new Image;c.onload=function(){r.height=c.height,r.width=c.width,t.rows=c.height,t.columns=c.width;const l=r.getContext("2d");l.drawImage(this,0,0);const f=l.getImageData(0,0,c.width,c.height),u=new Date().getTime();t.pixelData=new Uint8Array(f.data.buffer),t.imageData=f,t.decodeTimeInMS=u-n;const d=ax(t.pixelData);t.smallestPixelValue=d.min,t.largestPixelValue=d.max,t.pixelDataLength=t.pixelData.length,o(t)},c.onerror=function(l){a(l)},s.readAsBinaryString===void 0?c.src=`data:image/jpeg;base64,${window.btoa(C4e(s.result))}`:c.src=`data:image/jpeg;base64,${window.btoa(s.result)}`},s.onerror=c=>{a(c)}})}function ia(t,e,r,n,i){const o={...n};delete o.loader,delete o.streamingData;const a=fl(),s=o.priority||void 0;return o.transferPixelData&&r.buffer,a.executeTask("dicomImageLoader","decodeTask",{imageFrame:t,transferSyntax:e,pixelData:r,options:o,decodeConfig:i},{priority:s,requestType:o==null?void 0:o.requestType})}function T4e(t,e,r,n,i={},o){switch(e){case"1.2.840.10008.1.2":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.1":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.2":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.1.99":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.5":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.50":return t.bitsAllocated===8&&(t.samplesPerPixel===3||t.samplesPerPixel===4)?Zz(t,r,n):ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.51":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.57":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.70":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.80":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.81":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.90":return ia(t,e,r,i,o);case"1.2.840.10008.1.2.4.91":return ia(t,e,r,i,o);case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":return ia(t,e,r,i,o)}return Promise.reject(new Error(`No decoder for transfer syntax ${e}`))}function Qz(t){const e=ct("imagePixelModule",t);return{samplesPerPixel:e.samplesPerPixel,photometricInterpretation:e.photometricInterpretation,planarConfiguration:e.planarConfiguration,rows:e.rows,columns:e.columns,bitsAllocated:e.bitsAllocated,bitsStored:e.bitsStored,pixelRepresentation:e.pixelRepresentation,smallestPixelValue:e.smallestPixelValue,largestPixelValue:e.largestPixelValue,redPaletteColorLookupTableDescriptor:e.redPaletteColorLookupTableDescriptor,greenPaletteColorLookupTableDescriptor:e.greenPaletteColorLookupTableDescriptor,bluePaletteColorLookupTableDescriptor:e.bluePaletteColorLookupTableDescriptor,redPaletteColorLookupTableData:e.redPaletteColorLookupTableData,greenPaletteColorLookupTableData:e.greenPaletteColorLookupTableData,bluePaletteColorLookupTableData:e.bluePaletteColorLookupTableData,pixelData:void 0,imageId:t}}function _4e(t,e){const r=t.get("modalityLutModule",e)||{},n=t.get("generalSeriesModule",e)||{},{modality:i}=n,o={rescaleSlope:r.rescaleSlope,rescaleIntercept:r.rescaleIntercept,modality:i},a=t.get("scalingModule",e)||{};return{...o,...i==="PT"&&{suvbw:a.suvbw},...i==="RTDOSE"&&{doseGridScaling:a.DoseGridScaling,doseSummation:a.DoseSummation,doseType:a.DoseType,doseUnit:a.DoseUnit}}}function q8(t){return t==="RGB"||t==="PALETTE COLOR"||t==="YBR_FULL"||t==="YBR_FULL_422"||t==="YBR_PARTIAL_422"||t==="YBR_PARTIAL_420"||t==="YBR_RCT"||t==="YBR_ICT"}function E4e(t,e){const r=t.length/4;let n=0,i=0;for(let o=0;o=0?e<=255?r=Uint8Array:e<=65535?r=Uint16Array:e<=4294967295&&(r=Uint32Array):t>=-128&&e<=127?r=Int8Array:t>=-32768&&e<=32767&&(r=Int16Array)),r||Float32Array}function D4e(t,e,r){return X8(t,e)===r}function I4e(t){const e=t.smallestPixelValue,r=t.largestPixelValue,n=X8(e,r);if(n){const i=new n(t.pixelData);t.pixelData=i}else throw new Error("Could not apply a typed array to the pixel data")}let A7="";function sx(t,e,r,n={}){const i=n.useRGBA;if(n.preScale={enabled:n.preScale&&n.preScale.enabled!==void 0?n.preScale.enabled:!0},!(e!=null&&e.length))return Promise.reject(new Error("The pixel data is missing"));const{MetadataModules:o}=Ha,a=document.createElement("canvas"),s=Qz(t);if(s.decodeLevel=n.decodeLevel,n.allowFloatRendering=dw(),n.preScale.enabled){const u=_4e(A4,t);u&&(n.preScale={...n.preScale,scalingParameters:u})}const{decodeConfig:c}=Rm();Object.keys(s).forEach(u=>{(typeof s[u]=="function"||s[u]instanceof Promise)&&delete s[u]});const l=T4e(s,r,e,a,n,c),f=q8(s.photometricInterpretation);return new Promise((u,d)=>{l.then(function(h){let g=!1;if(n.targetBuffer&&n.targetBuffer.type&&!f){const{arrayBuffer:_,type:E,offset:b=0,length:D}=n.targetBuffer,I=h.pixelDataLength,P=b,O=D??I-P,L={Uint8Array,Uint16Array,Int16Array,Float32Array,Uint32Array};if(O!==h.pixelDataLength)throw new Error(`target array for image does not have the same length (${O}) as the decoded image length (${h.pixelDataLength}).`);const B=L[E],H=_?new B(_,P,O):new B(h.pixelData);if(O!==h.pixelDataLength)throw new Error("target array for image does not have the same length as the decoded image length.");h.pixelData=H,g=!0}g||I4e(h);const p=ct(o.IMAGE_PLANE,t)||{},v=ct(o.VOI_LUT,t)||{},y=ct(o.MODALITY_LUT,t)||{},m=ct(o.SOP_COMMON,t)||{},w=ct(o.CALIBRATION,t)||{},{rows:x,columns:C}=h;if(f){if(x4e(h)){a.height=h.rows,a.width=h.columns;let b=a.getContext("2d").createImageData(h.columns,h.rows);i||(b={...b,data:new Uint8ClampedArray(3*h.columns*h.rows)}),Jz(h,b.data,i),h.imageData=b,h.pixelData=b.data,h.pixelDataLength=b.data.length}else if(!i&&h.pixelDataLength===4*x*C){const E=new Uint8Array(h.pixelData.length/4*3);h.pixelData=E4e(h.pixelData,E),h.pixelDataLength=h.pixelData.length}const _=ax(h.pixelData);h.smallestPixelValue=_.min,h.largestPixelValue=_.max}const S=fc.createImageVoxelManager({scalarData:h.pixelData,width:h.columns,height:h.rows,numberOfComponents:h.samplesPerPixel}),T={imageId:t,dataType:h.pixelData.constructor.name,color:f,calibration:w,columnPixelSpacing:p.columnPixelSpacing,columns:h.columns,height:h.rows,preScale:h.preScale,intercept:y.rescaleIntercept?y.rescaleIntercept:0,slope:y.rescaleSlope?y.rescaleSlope:1,invert:h.photometricInterpretation==="MONOCHROME1",minPixelValue:h.smallestPixelValue,maxPixelValue:h.largestPixelValue,rowPixelSpacing:p.rowPixelSpacing,rows:h.rows,sizeInBytes:h.pixelData.byteLength,width:h.columns,windowCenter:v.windowCenter?v.windowCenter[0]:void 0,windowWidth:v.windowWidth?v.windowWidth[0]:void 0,voiLUTFunction:v.voiLUTFunction?v.voiLUTFunction:void 0,decodeTimeInMS:h.decodeTimeInMS,floatPixelData:void 0,imageFrame:h,voxelManager:S,rgba:f&&i,getPixelData:()=>h.pixelData,getCanvas:void 0,numberOfComponents:h.samplesPerPixel};if(T.color&&(T.getCanvas=function(){if(A7===t)return a;const _=T.columns,E=T.rows;a.height=E,a.width=_;const b=a.getContext("2d"),D=b.createImageData(_,E),I=h.pixelData;if(I.length===_*E*4)for(let P=0;P0&&b4e(m.sopClassUID)&&(T.modalityLUT=y.modalityLUTSequence[0]),v.voiLUTSequence&&v.voiLUTSequence.length>0&&(T.voiLUT=v.voiLUTSequence[0]),T.color&&(T.windowWidth=256,T.windowCenter=128),T.windowCenter===void 0||T.windowWidth===void 0){const _=T.imageFrame.smallestPixelValue,E=T.imageFrame.largestPixelValue;T.windowWidth=E-_,T.windowCenter=(E+_)/2}u(T)},d)})}const{ImageQualityStatus:e$}=Ha;function O4e(t,e){t.decache=function(){const r=Pm(e);ch.unload(r.url)}}function t$(t,e,r=0,n,i,o){const a=new Date().getTime(),s={cancelFn:void 0,promise:void 0};return s.promise=new Promise((c,l)=>{t.then(f=>{const u=K8(f,r),d=f.string("x00020010"),h=new Date().getTime(),g=sx(e,u,d,i);O4e(s,e),g.then(p=>{p=p,p.data=f,p.sharedCacheKey=n;const v=new Date().getTime();p.loadTimeInMS=h-a,p.totalTimeInMS=v-a,p.imageQualityStatus=e$.FULL_RESOLUTION,o!==void 0&&o.imageDoneCallback!==void 0&&o.imageDoneCallback(p),c(p)},function(p){l({error:p,dataSet:f})})},function(f){l({error:f})})}),s}function M4e(t,e,r=0,n,i){const o=new Date().getTime();return{promise:new Promise((s,c)=>{const l=new Date().getTime();let f;try{const u=K8(t,r),d=t.string("x00020010");f=sx(e,u,d,i)}catch(u){c({error:u,dataSet:t});return}f.then(u=>{u=u,u.data=t;const d=new Date().getTime();u.loadTimeInMS=l-o,u.totalTimeInMS=d-o,u.imageQualityStatus=e$.FULL_RESOLUTION,s(u)},c)}),cancelFn:void 0}}function n$(t){if(t==="dicomweb"||t==="wadouri")return rx;if(t==="dicomfile")return Yz}function Bv(t,e={}){const r=Pm(t);e=Object.assign({},e),delete e.loader;const n=n$(r.scheme);if(ch.isLoaded(r.url)){const o=ch.get(r.url,n,t);return M4e(o,t,r.pixelDataFrame,r.url,e)}const i=ch.load(r.url,n,t);return t$(i,t,r.frame,r.url,e)}function r$(){ld("dicomweb",Bv),ld("wadouri",Bv),ld("dicomfile",Bv),zh(H8)}const P4e={getImagePixelModule:Lz,getLUTs:IT,getModalityLUTOutputPixelRepresentation:Az,getNumberValues:gc,metaDataProvider:H8,metadataForDataset:jz},R4e={metaData:P4e,dataSetCacheManager:ch,fileManager:Hz,getEncapsulatedImageFrame:Kz,getUncompressedImageFrame:Xz,loadFileRequest:Yz,loadImageFromPromise:t$,getLoaderForScheme:n$,getPixelData:K8,loadImage:Bv,parseImageId:Pm,unpackBinaryFrame:qz,register:r$};function Ht(t,e,r){return e=e||0,!t||!t.Value||Array.isArray(t.Value)&&t.Value.length<=e?r:t.Value[e]}function L4e(t,e,r){const n=Ht(t,e,r);if(n!==void 0)return parseFloat(String(n))}function Fn(t,e){const r=Ht(t,e);if(r!==void 0)return parseFloat(r)}function So(t,e){if(!t||!t.Value||!Array.isArray(t.Value)||e&&t.Value.length>s&1}e.push({rows:Fn(t[`${n}0010`]),columns:Fn(t[`${n}0011`]),type:Ht(t[`${n}0040`]),x:Fn(t[`${n}0050`],1)-1,y:Fn(t[`${n}0050`],0)-1,pixelData:o,description:Ht(t[`${n}0022`]),label:Ht(t[`${n}1500`]),roiArea:Ht(t[`${n}1301`]),roiMean:Ht(t[`${n}1302`]),roiStandardDeviation:Ht(t[`${n}1303`])})}return{overlays:e}}function cx(t){const e=t.indexOf(":");return t.substring(e+1)}function lh(t,e=!0){return t&&t.Value?t.Value[0]&&e?t.Value[0]:t.Value:t}function i$(t,e,r){const n=(e?Object.values(e[0]):[]).map(o=>{var a;return(a=o.Value)==null?void 0:a[0]}).filter(o=>o!==void 0&&typeof o=="object"),i=(t?Object.values(t[r-1]):[]).map(o=>{var a;return(a=o.Value)==null?void 0:a[0]}).filter(o=>o!==void 0&&typeof o=="object");return{shared:n,perFrame:i}}function o$(t){let{52009230:e,52009229:r,"00280008":n,...i}=t;return e=lh(e,!1),r=lh(r,!1),n=lh(n),{PerFrameFunctionalGroupsSequence:e,SharedFunctionalGroupsSequence:r,NumberOfFrames:n,rest:i}}function N4e(t,e){const{PerFrameFunctionalGroupsSequence:r,SharedFunctionalGroupsSequence:n,NumberOfFrames:i,rest:o}=o$(e);if(r||i>1){const{shared:a,perFrame:s}=i$(r,n,t),c=Object.assign(e,{frameNumber:t});return[...a,...s].forEach(l=>{Object.entries(l).forEach(([f,u])=>{c[f]=u})}),Object.assign(o,{"00280008":i},c)}return e}let Lm=[],L5={};function a$(t){const e=t.indexOf("/frames/")+8,r=t.slice(0,e),n=parseInt(t.slice(e),10);return{metadata:Lm[`${r}1`],frame:n}}function k4e(t){const e=cx(t);return a$(e)}function V4e(t){if(t[52009230]!==void 0||t[52009229]!==void 0)return!0;const e=Ht(t["00280008"]);return e&&e>1}function F4e(t,e){const r=cx(t);Object.defineProperty(e,"isMultiframe",{value:V4e(e),enumerable:!1}),Lm[r]=e}function U4e(t){const e=cx(t),r=Lm[e];if(r&&!(r!=null&&r.isMultiframe))return r;const n=L5[e];if(n)return n;const i=a$(e);if(!i||!i.metadata)return;const{metadata:o,frame:a}=i;if(o){const s=N4e(a,o);return L5[e]=s,s}}function B4e(t){const e=cx(t);Lm[e]=void 0,L5[e]=void 0}function G4e(){Lm=[],L5={}}const Y8={add:F4e,get:U4e,remove:B4e,purge:G4e};function s$(t){return Ht(t["00080060"]).includes("NM")}function J8(t,e){const r=lh(t["00080008"],!1);if(r)return r[e]}function W4e(t){let e;const r=J8(t,2);if(r&&ug(r)){const n=lh(t["00540022"]);n&&(e=So(n["00200037"],6))}return e}function z4e(t){let e;const r=J8(t,2);if(r&&ug(r)){const n=lh(t["00540022"]);n&&(e=So(n["00200032"],3))}return e}function N7(t){let e=So(t["00200037"],6);return!e&&s$(t)&&(e=W4e(t)),e}function k7(t){let e=So(t["00200032"],3);return!e&&s$(t)&&(e=z4e(t)),e}function xo(t,e){const r=So(t[e]);return r?r[0]:null}function $4e(t){var e;return(e=t==null?void 0:t.Value)!=null&&e.length?Array.isArray(t.Value)?t.Value:typeof t.Value=="object"?(console.warn("Warning: Value should be an array, but an object was found. Encapsulating the object in an array."),[t.Value]):[]:[]}function V7(t){const e=$4e(t["00186011"]);return!e||!e.length?null:e.map(n=>{const i=xo(n,"0018602C"),o=xo(n,"0018602E"),a=xo(n,"00186024"),s=xo(n,"00186026"),c=xo(n,"0018601A"),l=xo(n,"0018601E"),f=xo(n,"00186018"),u=xo(n,"0018601C"),d=xo(n,"00186020"),h=xo(n,"00186022"),g=xo(n,"0018602A"),p=xo(n,"00186028"),v=xo(n,"00186012"),y=xo(n,"00186014"),m=xo(n,"00186016"),w=xo(n,"00186030");return{regionLocationMinY0:c,regionLocationMaxY1:l,regionLocationMinX0:f,regionLocationMaxX1:u,referencePixelX0:d,referencePixelY0:h,physicalDeltaX:i,physicalDeltaY:o,physicalUnitsXDirection:a,physicalUnitsYDirection:s,referencePhysicalPixelValueY:g,referencePhysicalPixelValueX:p,regionSpatialFormat:v,regionDataType:y,regionFlags:m,transducerFrequency:w}})}function Z8(t,e){const{MetadataModules:r}=Ha;if(t===r.MULTIFRAME){const{metadata:i,frame:o}=k4e(e);if(!i)return;const{PerFrameFunctionalGroupsSequence:a,SharedFunctionalGroupsSequence:s,NumberOfFrames:c}=o$(i);if(a||c>1){const{shared:l,perFrame:f}=i$(a,s,o);return{NumberOfFrames:c,PerFrameFunctionalInformation:f,SharedFunctionalInformation:l}}return{NumberOfFrames:c}}const n=Y8.get(e);if(n){if(t===r.GENERAL_STUDY)return{studyDescription:Ht(n["00081030"]),studyDate:lr.parseDA(Ht(n["00080020"])),studyTime:lr.parseTM(Ht(n["00080030"],0,"")),accessionNumber:Ht(n["00080050"])};if(t===r.GENERAL_SERIES)return{modality:Ht(n["00080060"]),seriesInstanceUID:Ht(n["0020000E"]),seriesDescription:Ht(n["0008103E"]),seriesNumber:Fn(n["00200011"]),studyInstanceUID:Ht(n["0020000D"]),seriesDate:lr.parseDA(Ht(n["00080021"])),seriesTime:lr.parseTM(Ht(n["00080031"],0,"")),acquisitionDate:lr.parseDA(Ht(n["00080022"])),acquisitionTime:lr.parseTM(Ht(n["00080032"],0,""))};if(t===r.GENERAL_IMAGE)return{sopInstanceUID:Ht(n["00080018"]),instanceNumber:Fn(n["00200013"]),lossyImageCompression:Ht(n["00282110"]),lossyImageCompressionRatio:Fn(n["00282112"]),lossyImageCompressionMethod:Ht(n["00282114"])};if(t===r.PATIENT)return{patientID:Ht(n["00100020"]),patientName:Ht(n["00100010"])};if(t===r.PATIENT_STUDY)return{patientAge:Fn(n["00101010"]),patientSize:Fn(n["00101020"]),patientSex:Ht(n["00100040"]),patientWeight:Fn(n["00101030"])};if(t===r.NM_MULTIFRAME_GEOMETRY){const i=Ht(n["00080060"]),o=J8(n,2);return{modality:i,imageType:Ht(n["00080008"]),imageSubType:o,imageOrientationPatient:N7(n),imagePositionPatient:k7(n),sliceThickness:Fn(n["00180050"]),spacingBetweenSlices:Fn(n["00180088"]),pixelSpacing:So(n["00280030"],2),numberOfFrames:Fn(n["00280008"]),isNMReconstructable:ug(o)&&i.includes("NM")}}if(t===r.IMAGE_PLANE){let i=N7(n),o=k7(n);const a=So(n["00280030"],2);let s=null,c=null,l=null,f=null,u=!1;return a?(c=a[0],s=a[1]):(u=!0,c=1,s=1),i?(l=[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])],f=[parseFloat(i[3]),parseFloat(i[4]),parseFloat(i[5])]):(l=[1,0,0],f=[0,1,0],u=!0,i=[...l,...f]),o||(o=[0,0,0],u=!0),{frameOfReferenceUID:Ht(n["00200052"]),rows:Fn(n["00280010"]),columns:Fn(n["00280011"]),imageOrientationPatient:i,rowCosines:l,columnCosines:f,imagePositionPatient:o,sliceThickness:Fn(n["00180050"]),sliceLocation:Fn(n["00201041"]),pixelSpacing:a,rowPixelSpacing:c,columnPixelSpacing:s,usingDefaultValues:u}}if(t===r.ULTRASOUND_ENHANCED_REGION)return V7(n);if(t===r.CALIBRATION&&Ht(n["00080060"])==="US")return{sequenceOfUltrasoundRegions:V7(n)};if(t===r.IMAGE_URL)return j4e(e,n);if(t===r.CINE)return H4e(e,n);if(t===r.IMAGE_PIXEL)return{samplesPerPixel:Fn(n["00280002"]),photometricInterpretation:Ht(n["00280004"]),rows:Fn(n["00280010"]),columns:Fn(n["00280011"]),bitsAllocated:Fn(n["00280100"]),bitsStored:Fn(n["00280101"]),highBit:Ht(n["00280102"]),pixelRepresentation:Fn(n["00280103"]),planarConfiguration:Fn(n["00280006"]),pixelAspectRatio:Ht(n["00280034"]),smallestPixelValue:Fn(n["00280106"]),largestPixelValue:Fn(n["00280107"]),redPaletteColorLookupTableDescriptor:So(n["00281101"]),greenPaletteColorLookupTableDescriptor:So(n["00281102"]),bluePaletteColorLookupTableDescriptor:So(n["00281103"]),redPaletteColorLookupTableData:So(n["00281201"]),greenPaletteColorLookupTableData:So(n["00281202"]),bluePaletteColorLookupTableData:So(n["00281203"])};if(t===r.VOI_LUT)return{windowCenter:So(n["00281050"],1),windowWidth:So(n["00281051"],1),voiLUTFunction:Ht(n["00281056"])};if(t===r.MODALITY_LUT)return{rescaleIntercept:Fn(n["00281052"]),rescaleSlope:Fn(n["00281053"]),rescaleType:Ht(n["00281054"])};if(t===r.SOP_COMMON)return{sopClassUID:Ht(n["00080016"]),sopInstanceUID:Ht(n["00080018"])};if(t===r.PET_ISOTOPE){const i=Ht(n["00540016"]);return i===void 0?void 0:{radiopharmaceuticalInfo:{radiopharmaceuticalStartTime:lr.parseTM(Ht(i["00181072"],0,"")),radiopharmaceuticalStartDateTime:Ht(i["00181078"],0,""),radionuclideTotalDose:Fn(i["00181074"]),radionuclideHalfLife:Fn(i["00181075"])}}}if(t===r.OVERLAY_PLANE)return A4e(n);if(t==="transferSyntax")return c$(e,n);if(t===r.PET_SERIES)return{correctedImage:Ht(n["00280051"]),units:Ht(n["00541001"]),decayCorrection:Ht(n["00541102"])};if(t===r.PET_IMAGE)return{frameReferenceTime:Fn(n["00541300"]),actualFrameDuration:Fn(n["00181242"])};if(t==="instance")return zz(e,Z8,$z)}}function j4e(t,e){const{transferSyntaxUID:r}=c$(t,e),n=OV(r),i=t.substring(7),o=i.replace("/frames/","/thumbnail/");let a=i.replace("/frames/","/rendered/");return n&&(a=a.replace("/rendered/1","/rendered")),{isVideo:n,rendered:a,thumbnail:o}}function H4e(t,e){return{cineRate:Ht(e["00180040"]),numberOfFrames:Fn(e["00280008"])}}function c$(t,e){return{transferSyntaxUID:Ht(e["00020010"])||Ht(e["00083002"])}}function K4e(t,e,r={},n={}){const i=Rm(),{retrieveOptions:o={},streamingData:a}=n,s=a.chunkSize||X4e(e,o,"chunkSize")||65536,c=f=>{if(typeof i.errorInterceptor=="function"){const u=new Error("request failed");i.errorInterceptor(u)}else console.warn("rangeRequest:Caught",f)};return new Promise(async(f,u)=>{const d=Object.assign({},r);Object.keys(d).forEach(function(h){(d[h]===null||d[h]===void 0)&&delete d[h]});try{a.encodedData||(a.chunkSize=s,a.rangesFetched=0);const h=Y4e(a,o),{encodedData:g,responseHeaders:p}=await q4e(t,d,h,a),v=p.get("content-type"),{totalBytes:y}=a,m=y===g.byteLength,w=W8(v,g,{isPartial:!0}),x=z8(o,m||w.extractDone);f({...w,imageQualityStatus:x,percentComplete:w.extractDone?100:s*100/y})}catch(h){c(h),console.error(h),u(h)}})}async function q4e(t,e,r,n){r&&(e=Object.assign(e,{Range:`bytes=${r[0]}-${r[1]}`}));let{encodedData:i}=n;if(r[1]&&(i==null?void 0:i.byteLength)>r[1])return n;const o=await fetch(t,{headers:e,signal:void 0}),a=await o.arrayBuffer(),s=new Uint8Array(a),{status:c}=o;let l;i?(l=new Uint8Array(i.length+s.length),l.set(i,0),l.set(s,i.length),n.rangesFetched=1):(l=new Uint8Array(s.length),l.set(s,0),n.rangesFetched++),n.encodedData=i=l,n.responseHeaders=o.headers;const f=o.headers.get("Content-Range");return f?n.totalBytes=Number(f.split("/")[1]):c!==206||!r?n.totalBytes=i==null?void 0:i.byteLength:r[1]===""||(i==null?void 0:i.length)r-i?[(n==null?void 0:n.byteLength)||0,""]:[(n==null?void 0:n.byteLength)||0,i*(o+1)-1]}function Q8(t,e,r="application/octet-stream",n){const{streamingData:i,retrieveOptions:o={}}=n||{},a={Accept:r};let s=o.urlArguments?`${t}${t.indexOf("?")===-1?"?":"&"}${o.urlArguments}`:t;if(o.framesPath&&(s=s.replace("/frames/",o.framesPath)),(i==null?void 0:i.url)!==s&&(n.streamingData={url:s}),o.rangeIndex!==void 0)return K4e(s,e,a,n);if(o.streaming)return Vz(s,e,a,n);const c=rx(s,e,a),{xhr:l}=c;return c.then(function(f){const u=l.getResponseHeader("Content-Type")||"application/octet-stream",d=W8(u,new Uint8Array(f));return d.imageQualityStatus=z8(o,!0),d})}const{ProgressiveIterator:F7}=pn,{ImageQualityStatus:U7}=Ha,J4e=new Set(["3.2.840.10008.1.2.4.96","1.2.840.10008.1.2.4.202","1.2.840.10008.1.2.4.203"]);function Z4e(t){const e="1.2.840.10008.1.2";if(!t)return e;const r=t.split(";"),n={};r.forEach(o=>{const a=o.split("=");if(a.length!==2)return;const s=a[1].trim().replace(/"/g,"");n[a[0].trim()]=s});const i={"image/jpeg":"1.2.840.10008.1.2.4.50","image/x-dicom-rle":"1.2.840.10008.1.2.5","image/x-jls":"1.2.840.10008.1.2.4.80","image/jls":"1.2.840.10008.1.2.4.80","image/jll":"1.2.840.10008.1.2.4.70","image/jp2":"1.2.840.10008.1.2.4.90","image/jpx":"1.2.840.10008.1.2.4.92","image/jphc":"3.2.840.10008.1.2.4.96","image/jxl":"1.2.840.10008.1.2.4.140"};return n["transfer-syntax"]?n["transfer-syntax"]:t&&!Object.keys(n).length&&i[t]?i[t]:n.type&&i[n.type]?i[n.type]:i[t]?i[t]:e}function Q4e(){return qh}const eEe="multipart/related; type=application/octet-stream; transfer-syntax=*";function l$(t,e={}){const r=Q4e(),n=new Date().getTime(),i=new F7("decompress");async function o(f,u,d){i.generate(async h=>{var v;const g=F7.as(Q8(f,u,d,e));let p=10;for await(const y of g){const{pixelData:m,imageQualityStatus:w=U7.FULL_RESOLUTION,percentComplete:x,done:C=!0,extractDone:S=!0}=y,T=Z4e(y.contentType);if(!S&&!J4e.has(T))continue;const _=y.decodeLevel??(w===U7.FULL_RESOLUTION?0:tEe(x,(v=e.retrieveOptions)==null?void 0:v.decodeLevel));if(!(!C&&p<=_))try{const E={...e,decodeLevel:_},b=await sx(u,m,T,E),D=new Date().getTime();b.loadTimeInMS=D-n,b.transferSyntaxUID=T,b.imageQualityStatus=w,h.add(b,C),p=_}catch(E){if(S)throw console.warn("Couldn't decode",E),E}}})}const a=e.requestType||Qt.Interaction,s=e.additionalDetails||{imageId:t},c=e.priority===void 0?5:e.priority,l=t.substring(7);return r.addRequest(o.bind(this,l,t,eEe),a,s,c),{promise:i.getDonePromise(),cancelFn:void 0}}function tEe(t,e=4){const r=t/100-.02;return r>1/4?Math.min(e,0):r>1/16?Math.min(e,1):r>1/64?Math.min(e,2):Math.min(e,3)}function u$(){ld("wadors",l$),zh(Z8)}const nEe={getNumberString:L4e,getNumberValue:Fn,getNumberValues:So,getValue:Ht,metaDataProvider:Z8},rEe={metaData:nEe,findIndexOfString:MT,getPixelData:Q8,loadImage:l$,metaDataManager:Y8,register:u$};function iEe(){u$(),r$()}const oEe=()=>new Worker(new URL("/static/dv3d/assets/decodeImageFrameWorker-DhtpjVX0.js",import.meta.url),{type:"module"});function f$(t={}){kz(t),iEe();const e=fl(),r=(t==null?void 0:t.maxWebWorkers)||aEe();e.registerWorker("dicomImageLoader",oEe,{maxWorkerInstances:r})}function aEe(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.max(1,Math.floor(navigator.hardwareConcurrency/2)):1}function sEe(t,e){if(e=e||t.transferSyntax,t.bitsAllocated===8&&e==="1.2.840.10008.1.2.4.50"&&(t.samplesPerPixel===3||t.samplesPerPixel===4))return!0}const cEe={IMPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2",EXPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2.1",DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2.1.99",EXPLICIT_VR_BIG_ENDIAN:"1.2.840.10008.1.2.2",JPEG_BASELINE_PROCESS_1:"1.2.840.10008.1.2.4.50",JPEG_EXTENDED_PROCESS_2_4:"1.2.840.10008.1.2.4.51",JPEG_EXTENDED_PROCESSES_3_5:"1.2.840.10008.1.2.4.52",JPEG_SPECTRAL_SELECTION_NONHIERARCHICAL_PROCESSES_6_8:"1.2.840.10008.1.2.4.53",JPEG_SPECTRAL_SELECTION_NONHIERARCHICAL_PROCESSES_7_9:"1.2.840.10008.1.2.4.54",JPEG_FULL_PROGRESSION_NONHIERARCHICAL_PROCESSES_10_12:"1.2.840.10008.1.2.4.55",JPEG_FULL_PROGRESSION_NONHIERARCHICAL_PROCESSES_11_13:"1.2.840.10008.1.2.4.56",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_14:"1.2.840.10008.1.2.4.57",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_15:"1.2.840.10008.1.2.4.58",JPEG_EXTENDED_HIERARCHICAL_PROCESSES_16_18:"1.2.840.10008.1.2.4.59",JPEG_EXTENDED_HIERARCHICAL_PROCESSES_17_19:"1.2.840.10008.1.2.4.60",JPEG_SPECTRAL_SELECTION_HIERARCHICAL_PROCESSES_20_22:"1.2.840.10008.1.2.4.61",JPEG_SPECTRAL_SELECTION_HIERARCHICAL_PROCESSES_21_23:"1.2.840.10008.1.2.4.62",JPEG_FULL_PROGRESSION_HIERARCHICAL_PROCESSES_24_26:"1.2.840.10008.1.2.4.63",JPEG_FULL_PROGRESSION_HIERARCHICAL_PROCESSES_25_27:"1.2.840.10008.1.2.4.64",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_28:"1.2.840.10008.1.2.4.65",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_29:"1.2.840.10008.1.2.4.66",JPEG_LOSSLESS_NONHIERARCHICAL_FIRST_ORDER_PREDICTION_PROCESS_14:"1.2.840.10008.1.2.4.70",JPEG_LS_LOSSLESS_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.80",JPEG_LS_LOSSY_NEAR_LOSSLESS_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.81",JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY:"1.2.840.10008.1.2.4.90",JPEG_2000_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.91",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY:"1.2.840.10008.1.2.4.92",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.93",JPIP_REFERENCED:"1.2.840.10008.1.2.4.94",JPIP_REFERENCED_DEFLATE:"1.2.840.10008.1.2.4.95",MPEG2_MAIN_PROFILE_MAIN_LEVEL:"1.2.840.10008.1.2.4.100",MPEG4_AVC_H264_HIGH_PROFILE_LEVEL_4_1:"1.2.840.10008.1.2.4.101",MPEG4_AVC_H264_BD_COMPATIBLE_HIGH_PROFILE_LEVEL_4_1:"1.2.840.10008.1.2.4.102",MPEG4_AVC_H264_HIGH_PROFILE_FOR_2D_VIDEO:"1.2.840.10008.1.2.4.103",MPEG4_AVC_H264_HIGH_PROFILE_FOR_3D_VIDEO:"1.2.840.10008.1.2.4.104",JPIP_LOSSLESS:"1.2.840.10008.1.2.4.96",JPIP_PART2_MULTICOMPONENT_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.97",RFC_2557_MIME_ENCAPSULATION:"1.2.840.10008.1.2.6.1",JPEG_XR_IMAGE_COMPRESSION:"1.2.840.10008.1.2.6.2",JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY_RETIRED:"1.2.840.10008.1.2.4.90R",JPEG_2000_IMAGE_COMPRESSION_RETIRED:"1.2.840.10008.1.2.4.91R",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY_RETIRED:"1.2.840.10008.1.2.4.92R",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_RETIRED:"1.2.840.10008.1.2.4.93R"},lEe=Object.freeze(Object.defineProperty({__proto__:null,transferSyntaxes:cEe},Symbol.toStringTag,{value:"Module"}));function uEe(t,e){const{rows:r,columns:n,data:i}=t,{rows:o,columns:a,data:s}=e,c=[],l=[],f=[];for(let u=0;u>8&255}async function hEe(t,e){if(t.bitsAllocated===16){let r=e.buffer,n=e.byteOffset;const i=e.length;n%2&&(r=r.slice(n),n=0),t.pixelRepresentation===0?t.pixelData=new Uint16Array(r,n,i/2):t.pixelData=new Int16Array(r,n,i/2);for(let o=0;o=0&&g<=127)for(let p=0;p=-127){const p=a[u++];for(let v=0;v<-g+1&&c=0&&g<=127)for(let p=0;p=-127){const p=a[u++];for(let v=0;v<-g+1&&c=0&&g<=127)for(let p=0;p=-127){const p=a[d++];for(let v=0;v<-g+1&&f{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(R,V){a=R,s=V});var c=Object.assign({},o),l="./this.program",f=(R,V)=>{throw V},u=typeof window=="object",d=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function p(R){return o.locateFile?o.locateFile(R,g):g+R}var v,y,m;if(h){var w=el,x=el;d?g=x.dirname(g)+"/":g=__dirname+"/",v=(R,V)=>(R=pe(R)?new URL(R):x.normalize(R),w.readFileSync(R,V?void 0:"utf8")),m=R=>{var V=v(R,!0);return V.buffer||(V=new Uint8Array(V)),V},y=(R,V,Y)=>{R=pe(R)?new URL(R):x.normalize(R),w.readFile(R,function(ye,xe){ye?Y(ye):V(xe.buffer)})},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(R){if(!(R instanceof pt))throw R}),process.on("unhandledRejection",function(R){throw R}),f=(R,V)=>{throw process.exitCode=R,V},o.inspect=function(){return"[Emscripten Module object]"}}else(u||d)&&(d?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),n&&(g=n),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",v=R=>{var V=new XMLHttpRequest;return V.open("GET",R,!1),V.send(null),V.responseText},d&&(m=R=>{var V=new XMLHttpRequest;return V.open("GET",R,!1),V.responseType="arraybuffer",V.send(null),new Uint8Array(V.response)}),y=(R,V,Y)=>{var ye=new XMLHttpRequest;ye.open("GET",R,!0),ye.responseType="arraybuffer",ye.onload=()=>{if(ye.status==200||ye.status==0&&ye.response){V(ye.response);return}Y()},ye.onerror=Y,ye.send(null)});var C=o.print||console.log.bind(console),S=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&(l=o.thisProgram),o.quit&&(f=o.quit);var T;o.wasmBinary&&(T=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&se("no native wasm support detected");var _,E=!1;function b(R,V){R||se(V)}var D=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function I(R,V,Y){for(var ye=V+Y,xe=V;R[xe]&&!(xe>=ye);)++xe;if(xe-V>16&&R.buffer&&D)return D.decode(R.subarray(V,xe));for(var Ce="";V>10,56320|qe&1023)}}return Ce}function P(R,V){return R?I(F,R,V):""}function O(R,V,Y,ye){if(!(ye>0))return 0;for(var xe=Y,Ce=Y+ye-1,Te=0;Te=55296&&Me<=57343){var Ae=R.charCodeAt(++Te);Me=65536+((Me&1023)<<10)|Ae&1023}if(Me<=127){if(Y>=Ce)break;V[Y++]=Me}else if(Me<=2047){if(Y+1>=Ce)break;V[Y++]=192|Me>>6,V[Y++]=128|Me&63}else if(Me<=65535){if(Y+2>=Ce)break;V[Y++]=224|Me>>12,V[Y++]=128|Me>>6&63,V[Y++]=128|Me&63}else{if(Y+3>=Ce)break;V[Y++]=240|Me>>18,V[Y++]=128|Me>>12&63,V[Y++]=128|Me>>6&63,V[Y++]=128|Me&63}}return V[Y]=0,Y-xe}function L(R,V,Y){return O(R,F,V,Y)}function B(R){for(var V=0,Y=0;Y=55296&&ye<=57343?(V+=4,++Y):V+=3}return V}var H,A,F,G,X,ee,ce,Se,we;function _e(R){H=R,o.HEAP8=A=new Int8Array(R),o.HEAP16=G=new Int16Array(R),o.HEAP32=ee=new Int32Array(R),o.HEAPU8=F=new Uint8Array(R),o.HEAPU16=X=new Uint16Array(R),o.HEAPU32=ce=new Uint32Array(R),o.HEAPF32=Se=new Float32Array(R),o.HEAPF64=we=new Float64Array(R)}o.INITIAL_MEMORY;var Ve,Ge=[],Ne=[],j=[];function M(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)J(o.preRun.shift());dt(Ge)}function q(){dt(Ne)}function K(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)ie(o.postRun.shift());dt(j)}function J(R){Ge.unshift(R)}function re(R){Ne.unshift(R)}function ie(R){j.unshift(R)}var Re=0,Fe=null;function je(R){Re++,o.monitorRunDependencies&&o.monitorRunDependencies(Re)}function Xe(R){if(Re--,o.monitorRunDependencies&&o.monitorRunDependencies(Re),Re==0&&Fe){var V=Fe;Fe=null,V()}}function se(R){o.onAbort&&o.onAbort(R),R="Aborted("+R+")",S(R),E=!0,R+=". Build with -sASSERTIONS for more info.";var V=new WebAssembly.RuntimeError(R);throw s(V),V}var ue="data:application/octet-stream;base64,";function Pe(R){return R.startsWith(ue)}function pe(R){return R.startsWith("file://")}var Ee;Ee="libjpegturbowasm_decode.wasm",Pe(Ee)||(Ee=p(Ee));function Qe(R){try{if(R==Ee&&T)return new Uint8Array(T);if(m)return m(R);throw"both async and sync fetching of the wasm failed"}catch(V){se(V)}}function fe(){if(!T&&(u||d)){if(typeof fetch=="function"&&!pe(Ee))return fetch(Ee,{credentials:"same-origin"}).then(function(R){if(!R.ok)throw"failed to load wasm binary file at '"+Ee+"'";return R.arrayBuffer()}).catch(function(){return Qe(Ee)});if(y)return new Promise(function(R,V){y(Ee,function(Y){R(new Uint8Array(Y))},V)})}return Promise.resolve().then(function(){return Qe(Ee)})}function ft(){var R={a:he};function V(Te,Me){var Ae=Te.exports;o.asm=Ae,_=o.asm.K,_e(_.buffer),Ve=o.asm.M,re(o.asm.L),Xe()}je();function Y(Te){V(Te.instance)}function ye(Te){return fe().then(function(Me){return WebAssembly.instantiate(Me,R)}).then(function(Me){return Me}).then(Te,function(Me){S("failed to asynchronously prepare wasm: "+Me),se(Me)})}function xe(){return!T&&typeof WebAssembly.instantiateStreaming=="function"&&!Pe(Ee)&&!pe(Ee)&&!h&&typeof fetch=="function"?fetch(Ee,{credentials:"same-origin"}).then(function(Te){var Me=WebAssembly.instantiateStreaming(Te,R);return Me.then(Y,function(Ae){return S("wasm streaming compile failed: "+Ae),S("falling back to ArrayBuffer instantiation"),ye(Y)})}):ye(Y)}if(o.instantiateWasm)try{var Ce=o.instantiateWasm(R,V);return Ce}catch(Te){S("Module.instantiateWasm callback failed with error: "+Te),s(Te)}return xe().catch(s),{}}function pt(R){this.name="ExitStatus",this.message="Program terminated with exit("+R+")",this.status=R}function dt(R){for(;R.length>0;)R.shift()(o)}function Ue(R){this.excPtr=R,this.ptr=R-24,this.set_type=function(V){ce[this.ptr+4>>2]=V},this.get_type=function(){return ce[this.ptr+4>>2]},this.set_destructor=function(V){ce[this.ptr+8>>2]=V},this.get_destructor=function(){return ce[this.ptr+8>>2]},this.set_refcount=function(V){ee[this.ptr>>2]=V},this.set_caught=function(V){V=V?1:0,A[this.ptr+12>>0]=V},this.get_caught=function(){return A[this.ptr+12>>0]!=0},this.set_rethrown=function(V){V=V?1:0,A[this.ptr+13>>0]=V},this.get_rethrown=function(){return A[this.ptr+13>>0]!=0},this.init=function(V,Y){this.set_adjusted_ptr(0),this.set_type(V),this.set_destructor(Y),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var V=ee[this.ptr>>2];ee[this.ptr>>2]=V+1},this.release_ref=function(){var V=ee[this.ptr>>2];return ee[this.ptr>>2]=V-1,V===1},this.set_adjusted_ptr=function(V){ce[this.ptr+16>>2]=V},this.get_adjusted_ptr=function(){return ce[this.ptr+16>>2]},this.get_exception_ptr=function(){var V=te(this.get_type());if(V)return ce[this.excPtr>>2];var Y=this.get_adjusted_ptr();return Y!==0?Y:this.excPtr}}function nt(R,V,Y){var ye=new Ue(R);throw ye.init(V,Y),R}var at={};function ot(R){for(;R.length;){var V=R.pop(),Y=R.pop();Y(V)}}function lt(R){return this.fromWireType(ee[R>>2])}var _t={},vt={},Mt={},Ft=48,wn=57;function Dn(R){if(R===void 0)return"_unknown";R=R.replace(/[^a-zA-Z0-9_]/g,"$");var V=R.charCodeAt(0);return V>=Ft&&V<=wn?"_"+R:R}function Nt(R,V){return R=Dn(R),new Function("body","return function "+R+`() { "use strict"; return body.apply(this, arguments); }; `)(V)}function xn(R,V){var Y=Nt(V,function(ye){this.name=V,this.message=ye;var xe=new Error(ye).stack;xe!==void 0&&(this.stack=this.toString()+` -`+xe.replace(/^Error(:[^\n]*)?\n/,""))});return Y.prototype=Object.create(R.prototype),Y.prototype.constructor=Y,Y.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},Y}var Ui=void 0;function br(R){throw new Ui(R)}function Ye(R,V,Y){R.forEach(function(Me){Mt[Me]=V});function ye(Me){var Ae=Y(Me);Ae.length!==R.length&&br("Mismatched type converter count");for(var qe=0;qe{vt.hasOwnProperty(Me)?xe[Ae]=vt[Me]:(Ce.push(Me),_t.hasOwnProperty(Me)||(_t[Me]=[]),_t[Me].push(()=>{xe[Ae]=vt[Me],++Te,Te===Ce.length&&ye(xe)}))}),Ce.length===0&&ye(xe)}function ut(R){var V=at[R];delete at[R];var Y=V.rawConstructor,ye=V.rawDestructor,xe=V.fields,Ce=xe.map(Te=>Te.getterReturnType).concat(xe.map(Te=>Te.setterArgumentType));Ye([R],Ce,Te=>{var Me={};return xe.forEach((Ae,qe)=>{var rt=Ae.fieldName,mt=Te[qe],ht=Ae.getter,zt=Ae.getterContext,Ut=Te[qe+xe.length],Gn=Ae.setter,ai=Ae.setterContext;Me[rt]={read:vi=>mt.fromWireType(ht(zt,vi)),write:(vi,bf)=>{var rs=[];Gn(ai,vi,Ut.toWireType(rs,bf)),ot(rs)}}}),[{name:V.name,fromWireType:function(Ae){var qe={};for(var rt in Me)qe[rt]=Me[rt].read(Ae);return ye(Ae),qe},toWireType:function(Ae,qe){for(var rt in Me)if(!(rt in qe))throw new TypeError('Missing field: "'+rt+'"');var mt=Y();for(rt in Me)Me[rt].write(mt,qe[rt]);return Ae!==null&&Ae.push(ye,mt),mt},argPackAdvance:8,readValueFromPointer:lt,destructorFunction:ye}]})}function Rt(R,V,Y,ye,xe){}function mn(R){switch(R){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+R)}}function Fr(){for(var R=new Array(256),V=0;V<256;++V)R[V]=String.fromCharCode(V);Lt=R}var Lt=void 0;function Cn(R){for(var V="",Y=R;F[Y];)V+=Lt[F[Y++]];return V}var Yt=void 0;function jt(R){throw new Yt(R)}function hi(R,V,Y={}){if(!("argPackAdvance"in V))throw new TypeError("registerType registeredInstance requires argPackAdvance");var ye=V.name;if(R||jt('type "'+ye+'" must have a positive integer typeid pointer'),vt.hasOwnProperty(R)){if(Y.ignoreDuplicateRegistrations)return;jt("Cannot register type '"+ye+"' twice")}if(vt[R]=V,delete Mt[R],_t.hasOwnProperty(R)){var xe=_t[R];delete _t[R],xe.forEach(Ce=>Ce())}}function Bi(R,V,Y,ye,xe){var Ce=mn(Y);V=Cn(V),hi(R,{name:V,fromWireType:function(Te){return!!Te},toWireType:function(Te,Me){return Me?ye:xe},argPackAdvance:8,readValueFromPointer:function(Te){var Me;if(Y===1)Me=A;else if(Y===2)Me=G;else if(Y===4)Me=ee;else throw new TypeError("Unknown boolean type size: "+V);return this.fromWireType(Me[Te>>Ce])},destructorFunction:null})}function Ao(R){if(!(this instanceof Di)||!(R instanceof Di))return!1;for(var V=this.$$.ptrType.registeredClass,Y=this.$$.ptr,ye=R.$$.ptrType.registeredClass,xe=R.$$.ptr;V.baseClass;)Y=V.upcast(Y),V=V.baseClass;for(;ye.baseClass;)xe=ye.upcast(xe),ye=ye.baseClass;return V===ye&&Y===xe}function jn(R){return{count:R.count,deleteScheduled:R.deleteScheduled,preservePointerOnDelete:R.preservePointerOnDelete,ptr:R.ptr,ptrType:R.ptrType,smartPtr:R.smartPtr,smartPtrType:R.smartPtrType}}function fo(R){function V(Y){return Y.$$.ptrType.registeredClass.name}jt(V(R)+" instance already deleted")}var Ei=!1;function xa(R){}function Bn(R){R.smartPtr?R.smartPtrType.rawDestructor(R.smartPtr):R.ptrType.registeredClass.rawDestructor(R.ptr)}function Ct(R){R.count.value-=1;var V=R.count.value===0;V&&Bn(R)}function Zt(R,V,Y){if(V===Y)return R;if(Y.baseClass===void 0)return null;var ye=Zt(R,V,Y.baseClass);return ye===null?null:Y.downcast(ye)}var ar={};function Qo(){return Object.keys(Zi).length}function Dr(){var R=[];for(var V in Zi)Zi.hasOwnProperty(V)&&R.push(Zi[V]);return R}var ho=[];function bi(){for(;ho.length;){var R=ho.pop();R.$$.deleteScheduled=!1,R.delete()}}var Ur=void 0;function Cs(R){Ur=R,ho.length&&Ur&&Ur(bi)}function go(){o.getInheritedInstanceCount=Qo,o.getLiveInheritedInstances=Dr,o.flushPendingDeletes=bi,o.setDelayFunction=Cs}var Zi={};function Ca(R,V){for(V===void 0&&jt("ptr should not be undefined");R.baseClass;)V=R.upcast(V),R=R.baseClass;return V}function gi(R,V){return V=Ca(R,V),Zi[V]}function Sa(R,V){(!V.ptrType||!V.ptr)&&br("makeClassHandle requires ptr and ptrType");var Y=!!V.smartPtrType,ye=!!V.smartPtr;return Y!==ye&&br("Both smartPtrType and smartPtr must be specified"),V.count={value:1},Gi(Object.create(R,{$$:{value:V}}))}function ln(R){var V=this.getPointee(R);if(!V)return this.destructor(R),null;var Y=gi(this.registeredClass,V);if(Y!==void 0){if(Y.$$.count.value===0)return Y.$$.ptr=V,Y.$$.smartPtr=R,Y.clone();var ye=Y.clone();return this.destructor(R),ye}function xe(){return this.isSmartPointer?Sa(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:V,smartPtrType:this,smartPtr:R}):Sa(this.registeredClass.instancePrototype,{ptrType:this,ptr:R})}var Ce=this.registeredClass.getActualType(V),Te=ar[Ce];if(!Te)return xe.call(this);var Me;this.isConst?Me=Te.constPointerType:Me=Te.pointerType;var Ae=Zt(V,this.registeredClass,Me.registeredClass);return Ae===null?xe.call(this):this.isSmartPointer?Sa(Me.registeredClass.instancePrototype,{ptrType:Me,ptr:Ae,smartPtrType:this,smartPtr:R}):Sa(Me.registeredClass.instancePrototype,{ptrType:Me,ptr:Ae})}function Gi(R){return typeof FinalizationRegistry>"u"?(Gi=V=>V,R):(Ei=new FinalizationRegistry(V=>{Ct(V.$$)}),Gi=V=>{var Y=V.$$,ye=!!Y.smartPtr;if(ye){var xe={$$:Y};Ei.register(V,xe,V)}return V},xa=V=>Ei.unregister(V),Gi(R))}function Ss(){if(this.$$.ptr||fo(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var R=Gi(Object.create(Object.getPrototypeOf(this),{$$:{value:jn(this.$$)}}));return R.$$.count.value+=1,R.$$.deleteScheduled=!1,R}function ea(){this.$$.ptr||fo(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&jt("Object already scheduled for deletion"),xa(this),Ct(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Qi(){return!this.$$.ptr}function po(){return this.$$.ptr||fo(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&jt("Object already scheduled for deletion"),ho.push(this),ho.length===1&&Ur&&Ur(bi),this.$$.deleteScheduled=!0,this}function Zr(){Di.prototype.isAliasOf=Ao,Di.prototype.clone=Ss,Di.prototype.delete=ea,Di.prototype.isDeleted=Qi,Di.prototype.deleteLater=po}function Di(){}function sn(R,V,Y){if(R[V].overloadTable===void 0){var ye=R[V];R[V]=function(){return R[V].overloadTable.hasOwnProperty(arguments.length)||jt("Function '"+Y+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+R[V].overloadTable+")!"),R[V].overloadTable[arguments.length].apply(this,arguments)},R[V].overloadTable=[],R[V].overloadTable[ye.argCount]=ye}}function pi(R,V,Y){o.hasOwnProperty(R)?(jt("Cannot register public name '"+R+"' twice"),sn(o,R,R),o.hasOwnProperty(Y)&&jt("Cannot register multiple overloads of a function with the same number of arguments ("+Y+")!"),o[R].overloadTable[Y]=V):o[R]=V}function No(R,V,Y,ye,xe,Ce,Te,Me){this.name=R,this.constructor=V,this.instancePrototype=Y,this.rawDestructor=ye,this.baseClass=xe,this.getActualType=Ce,this.upcast=Te,this.downcast=Me,this.pureVirtualFunctions=[]}function Wi(R,V,Y){for(;V!==Y;)V.upcast||jt("Expected null or instance of "+Y.name+", got an instance of "+V.name),R=V.upcast(R),V=V.baseClass;return R}function Ii(R,V){if(V===null)return this.isReference&&jt("null is not a valid "+this.name),0;V.$$||jt('Cannot pass "'+ba(V)+'" as a '+this.name),V.$$.ptr||jt("Cannot pass deleted object as a pointer of type "+this.name);var Y=V.$$.ptrType.registeredClass,ye=Wi(V.$$.ptr,Y,this.registeredClass);return ye}function Ts(R,V){var Y;if(V===null)return this.isReference&&jt("null is not a valid "+this.name),this.isSmartPointer?(Y=this.rawConstructor(),R!==null&&R.push(this.rawDestructor,Y),Y):0;V.$$||jt('Cannot pass "'+ba(V)+'" as a '+this.name),V.$$.ptr||jt("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&V.$$.ptrType.isConst&&jt("Cannot convert argument of type "+(V.$$.smartPtrType?V.$$.smartPtrType.name:V.$$.ptrType.name)+" to parameter type "+this.name);var ye=V.$$.ptrType.registeredClass;if(Y=Wi(V.$$.ptr,ye,this.registeredClass),this.isSmartPointer)switch(V.$$.smartPtr===void 0&&jt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:V.$$.smartPtrType===this?Y=V.$$.smartPtr:jt("Cannot convert argument of type "+(V.$$.smartPtrType?V.$$.smartPtrType.name:V.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:Y=V.$$.smartPtr;break;case 2:if(V.$$.smartPtrType===this)Y=V.$$.smartPtr;else{var xe=V.clone();Y=this.rawShare(Y,ji.toHandle(function(){xe.delete()})),R!==null&&R.push(this.rawDestructor,Y)}break;default:jt("Unsupporting sharing policy")}return Y}function ko(R,V){if(V===null)return this.isReference&&jt("null is not a valid "+this.name),0;V.$$||jt('Cannot pass "'+ba(V)+'" as a '+this.name),V.$$.ptr||jt("Cannot pass deleted object as a pointer of type "+this.name),V.$$.ptrType.isConst&&jt("Cannot convert argument of type "+V.$$.ptrType.name+" to parameter type "+this.name);var Y=V.$$.ptrType.registeredClass,ye=Wi(V.$$.ptr,Y,this.registeredClass);return ye}function _s(R){return this.rawGetPointee&&(R=this.rawGetPointee(R)),R}function eo(R){this.rawDestructor&&this.rawDestructor(R)}function zi(R){R!==null&&R.delete()}function $i(){Ir.prototype.getPointee=_s,Ir.prototype.destructor=eo,Ir.prototype.argPackAdvance=8,Ir.prototype.readValueFromPointer=lt,Ir.prototype.deleteObject=zi,Ir.prototype.fromWireType=ln}function Ir(R,V,Y,ye,xe,Ce,Te,Me,Ae,qe,rt){this.name=R,this.registeredClass=V,this.isReference=Y,this.isConst=ye,this.isSmartPointer=xe,this.pointeeType=Ce,this.sharingPolicy=Te,this.rawGetPointee=Me,this.rawConstructor=Ae,this.rawShare=qe,this.rawDestructor=rt,!xe&&V.baseClass===void 0?ye?(this.toWireType=Ii,this.destructorFunction=null):(this.toWireType=ko,this.destructorFunction=null):this.toWireType=Ts}function yc(R,V,Y){o.hasOwnProperty(R)||br("Replacing nonexistant public symbol"),o[R].overloadTable!==void 0&&Y!==void 0||(o[R]=V,o[R].argCount=Y)}function Vo(R,V,Y){var ye=o["dynCall_"+R];return Y&&Y.length?ye.apply(null,[V].concat(Y)):ye.call(null,V)}var Fo=[];function yr(R){var V=Fo[R];return V||(R>=Fo.length&&(Fo.length=R+1),Fo[R]=V=Ve.get(R)),V}function wc(R,V,Y){if(R.includes("j"))return Vo(R,V,Y);var ye=yr(V).apply(null,Y);return ye}function mi(R,V){var Y=[];return function(){return Y.length=0,Object.assign(Y,arguments),wc(R,V,Y)}}function Or(R,V){R=Cn(R);function Y(){return R.includes("j")?mi(R,V):yr(V)}var ye=Y();return typeof ye!="function"&&jt("unknown function pointer with signature "+R+": "+V),ye}var qa=void 0;function mo(R){var V=he(R),Y=Cn(V);return Q(V),Y}function ii(R,V){var Y=[],ye={};function xe(Ce){if(!ye[Ce]&&!vt[Ce]){if(Mt[Ce]){Mt[Ce].forEach(xe);return}Y.push(Ce),ye[Ce]=!0}}throw V.forEach(xe),new qa(R+": "+Y.map(mo).join([", "]))}function ta(R,V,Y,ye,xe,Ce,Te,Me,Ae,qe,rt,mt,ht){rt=Cn(rt),Ce=Or(xe,Ce),Me&&(Me=Or(Te,Me)),qe&&(qe=Or(Ae,qe)),ht=Or(mt,ht);var zt=Dn(rt);pi(zt,function(){ii("Cannot construct "+rt+" due to unbound types",[ye])}),Ye([R,V,Y],ye?[ye]:[],function(Ut){Ut=Ut[0];var Gn,ai;ye?(Gn=Ut.registeredClass,ai=Gn.instancePrototype):ai=Di.prototype;var vi=Nt(zt,function(){if(Object.getPrototypeOf(this)!==bf)throw new Yt("Use 'new' to construct "+rt);if(rs.constructor_body===void 0)throw new Yt(rt+" has no accessible constructor");var wb=rs.constructor_body[arguments.length];if(wb===void 0)throw new Yt("Tried to invoke ctor of "+rt+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(rs.constructor_body).toString()+") parameters instead!");return wb.apply(this,arguments)}),bf=Object.create(ai,{constructor:{value:vi}});vi.prototype=bf;var rs=new No(rt,vi,bf,ht,Gn,Ce,Me,qe),Am=new Ir(rt,rs,!0,!1,!1),fg=new Ir(rt+"*",rs,!1,!1,!1),yb=new Ir(rt+" const*",rs,!1,!0,!1);return ar[R]={pointerType:fg,constPointerType:yb},yc(zt,vi),[Am,fg,yb]})}function Es(R,V){for(var Y=[],ye=0;ye>2]);return Y}function Xa(R,V){if(!(R instanceof Function))throw new TypeError("new_ called with constructor type "+typeof R+" which is not a function");var Y=Nt(R.name||"unknownFunctionName",function(){});Y.prototype=R.prototype;var ye=new Y,xe=R.apply(ye,V);return xe instanceof Object?xe:ye}function Ta(R,V,Y,ye,xe){var Ce=V.length;Ce<2&&jt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Te=V[1]!==null&&Y!==null,Me=!1,Ae=1;Ae{vt.hasOwnProperty(Me)?xe[Ae]=vt[Me]:(Ce.push(Me),_t.hasOwnProperty(Me)||(_t[Me]=[]),_t[Me].push(()=>{xe[Ae]=vt[Me],++Te,Te===Ce.length&&ye(xe)}))}),Ce.length===0&&ye(xe)}function ut(R){var V=at[R];delete at[R];var Y=V.rawConstructor,ye=V.rawDestructor,xe=V.fields,Ce=xe.map(Te=>Te.getterReturnType).concat(xe.map(Te=>Te.setterArgumentType));Ye([R],Ce,Te=>{var Me={};return xe.forEach((Ae,qe)=>{var rt=Ae.fieldName,mt=Te[qe],ht=Ae.getter,zt=Ae.getterContext,Ut=Te[qe+xe.length],Gn=Ae.setter,ai=Ae.setterContext;Me[rt]={read:vi=>mt.fromWireType(ht(zt,vi)),write:(vi,bf)=>{var rs=[];Gn(ai,vi,Ut.toWireType(rs,bf)),ot(rs)}}}),[{name:V.name,fromWireType:function(Ae){var qe={};for(var rt in Me)qe[rt]=Me[rt].read(Ae);return ye(Ae),qe},toWireType:function(Ae,qe){for(var rt in Me)if(!(rt in qe))throw new TypeError('Missing field: "'+rt+'"');var mt=Y();for(rt in Me)Me[rt].write(mt,qe[rt]);return Ae!==null&&Ae.push(ye,mt),mt},argPackAdvance:8,readValueFromPointer:lt,destructorFunction:ye}]})}function Rt(R,V,Y,ye,xe){}function mn(R){switch(R){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+R)}}function Fr(){for(var R=new Array(256),V=0;V<256;++V)R[V]=String.fromCharCode(V);Lt=R}var Lt=void 0;function Cn(R){for(var V="",Y=R;F[Y];)V+=Lt[F[Y++]];return V}var Yt=void 0;function jt(R){throw new Yt(R)}function hi(R,V,Y={}){if(!("argPackAdvance"in V))throw new TypeError("registerType registeredInstance requires argPackAdvance");var ye=V.name;if(R||jt('type "'+ye+'" must have a positive integer typeid pointer'),vt.hasOwnProperty(R)){if(Y.ignoreDuplicateRegistrations)return;jt("Cannot register type '"+ye+"' twice")}if(vt[R]=V,delete Mt[R],_t.hasOwnProperty(R)){var xe=_t[R];delete _t[R],xe.forEach(Ce=>Ce())}}function Bi(R,V,Y,ye,xe){var Ce=mn(Y);V=Cn(V),hi(R,{name:V,fromWireType:function(Te){return!!Te},toWireType:function(Te,Me){return Me?ye:xe},argPackAdvance:8,readValueFromPointer:function(Te){var Me;if(Y===1)Me=A;else if(Y===2)Me=G;else if(Y===4)Me=ee;else throw new TypeError("Unknown boolean type size: "+V);return this.fromWireType(Me[Te>>Ce])},destructorFunction:null})}function Ao(R){if(!(this instanceof Di)||!(R instanceof Di))return!1;for(var V=this.$$.ptrType.registeredClass,Y=this.$$.ptr,ye=R.$$.ptrType.registeredClass,xe=R.$$.ptr;V.baseClass;)Y=V.upcast(Y),V=V.baseClass;for(;ye.baseClass;)xe=ye.upcast(xe),ye=ye.baseClass;return V===ye&&Y===xe}function jn(R){return{count:R.count,deleteScheduled:R.deleteScheduled,preservePointerOnDelete:R.preservePointerOnDelete,ptr:R.ptr,ptrType:R.ptrType,smartPtr:R.smartPtr,smartPtrType:R.smartPtrType}}function fo(R){function V(Y){return Y.$$.ptrType.registeredClass.name}jt(V(R)+" instance already deleted")}var Ei=!1;function xa(R){}function Bn(R){R.smartPtr?R.smartPtrType.rawDestructor(R.smartPtr):R.ptrType.registeredClass.rawDestructor(R.ptr)}function Ct(R){R.count.value-=1;var V=R.count.value===0;V&&Bn(R)}function Zt(R,V,Y){if(V===Y)return R;if(Y.baseClass===void 0)return null;var ye=Zt(R,V,Y.baseClass);return ye===null?null:Y.downcast(ye)}var ar={};function Qo(){return Object.keys(Zi).length}function Dr(){var R=[];for(var V in Zi)Zi.hasOwnProperty(V)&&R.push(Zi[V]);return R}var ho=[];function bi(){for(;ho.length;){var R=ho.pop();R.$$.deleteScheduled=!1,R.delete()}}var Ur=void 0;function Cs(R){Ur=R,ho.length&&Ur&&Ur(bi)}function go(){o.getInheritedInstanceCount=Qo,o.getLiveInheritedInstances=Dr,o.flushPendingDeletes=bi,o.setDelayFunction=Cs}var Zi={};function Ca(R,V){for(V===void 0&&jt("ptr should not be undefined");R.baseClass;)V=R.upcast(V),R=R.baseClass;return V}function gi(R,V){return V=Ca(R,V),Zi[V]}function Sa(R,V){(!V.ptrType||!V.ptr)&&br("makeClassHandle requires ptr and ptrType");var Y=!!V.smartPtrType,ye=!!V.smartPtr;return Y!==ye&&br("Both smartPtrType and smartPtr must be specified"),V.count={value:1},Gi(Object.create(R,{$$:{value:V}}))}function ln(R){var V=this.getPointee(R);if(!V)return this.destructor(R),null;var Y=gi(this.registeredClass,V);if(Y!==void 0){if(Y.$$.count.value===0)return Y.$$.ptr=V,Y.$$.smartPtr=R,Y.clone();var ye=Y.clone();return this.destructor(R),ye}function xe(){return this.isSmartPointer?Sa(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:V,smartPtrType:this,smartPtr:R}):Sa(this.registeredClass.instancePrototype,{ptrType:this,ptr:R})}var Ce=this.registeredClass.getActualType(V),Te=ar[Ce];if(!Te)return xe.call(this);var Me;this.isConst?Me=Te.constPointerType:Me=Te.pointerType;var Ae=Zt(V,this.registeredClass,Me.registeredClass);return Ae===null?xe.call(this):this.isSmartPointer?Sa(Me.registeredClass.instancePrototype,{ptrType:Me,ptr:Ae,smartPtrType:this,smartPtr:R}):Sa(Me.registeredClass.instancePrototype,{ptrType:Me,ptr:Ae})}function Gi(R){return typeof FinalizationRegistry>"u"?(Gi=V=>V,R):(Ei=new FinalizationRegistry(V=>{Ct(V.$$)}),Gi=V=>{var Y=V.$$,ye=!!Y.smartPtr;if(ye){var xe={$$:Y};Ei.register(V,xe,V)}return V},xa=V=>Ei.unregister(V),Gi(R))}function Ss(){if(this.$$.ptr||fo(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var R=Gi(Object.create(Object.getPrototypeOf(this),{$$:{value:jn(this.$$)}}));return R.$$.count.value+=1,R.$$.deleteScheduled=!1,R}function ea(){this.$$.ptr||fo(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&jt("Object already scheduled for deletion"),xa(this),Ct(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Qi(){return!this.$$.ptr}function po(){return this.$$.ptr||fo(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&jt("Object already scheduled for deletion"),ho.push(this),ho.length===1&&Ur&&Ur(bi),this.$$.deleteScheduled=!0,this}function Zr(){Di.prototype.isAliasOf=Ao,Di.prototype.clone=Ss,Di.prototype.delete=ea,Di.prototype.isDeleted=Qi,Di.prototype.deleteLater=po}function Di(){}function sn(R,V,Y){if(R[V].overloadTable===void 0){var ye=R[V];R[V]=function(){return R[V].overloadTable.hasOwnProperty(arguments.length)||jt("Function '"+Y+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+R[V].overloadTable+")!"),R[V].overloadTable[arguments.length].apply(this,arguments)},R[V].overloadTable=[],R[V].overloadTable[ye.argCount]=ye}}function pi(R,V,Y){o.hasOwnProperty(R)?(jt("Cannot register public name '"+R+"' twice"),sn(o,R,R),o.hasOwnProperty(Y)&&jt("Cannot register multiple overloads of a function with the same number of arguments ("+Y+")!"),o[R].overloadTable[Y]=V):o[R]=V}function No(R,V,Y,ye,xe,Ce,Te,Me){this.name=R,this.constructor=V,this.instancePrototype=Y,this.rawDestructor=ye,this.baseClass=xe,this.getActualType=Ce,this.upcast=Te,this.downcast=Me,this.pureVirtualFunctions=[]}function Wi(R,V,Y){for(;V!==Y;)V.upcast||jt("Expected null or instance of "+Y.name+", got an instance of "+V.name),R=V.upcast(R),V=V.baseClass;return R}function Ii(R,V){if(V===null)return this.isReference&&jt("null is not a valid "+this.name),0;V.$$||jt('Cannot pass "'+ba(V)+'" as a '+this.name),V.$$.ptr||jt("Cannot pass deleted object as a pointer of type "+this.name);var Y=V.$$.ptrType.registeredClass,ye=Wi(V.$$.ptr,Y,this.registeredClass);return ye}function Ts(R,V){var Y;if(V===null)return this.isReference&&jt("null is not a valid "+this.name),this.isSmartPointer?(Y=this.rawConstructor(),R!==null&&R.push(this.rawDestructor,Y),Y):0;V.$$||jt('Cannot pass "'+ba(V)+'" as a '+this.name),V.$$.ptr||jt("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&V.$$.ptrType.isConst&&jt("Cannot convert argument of type "+(V.$$.smartPtrType?V.$$.smartPtrType.name:V.$$.ptrType.name)+" to parameter type "+this.name);var ye=V.$$.ptrType.registeredClass;if(Y=Wi(V.$$.ptr,ye,this.registeredClass),this.isSmartPointer)switch(V.$$.smartPtr===void 0&&jt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:V.$$.smartPtrType===this?Y=V.$$.smartPtr:jt("Cannot convert argument of type "+(V.$$.smartPtrType?V.$$.smartPtrType.name:V.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:Y=V.$$.smartPtr;break;case 2:if(V.$$.smartPtrType===this)Y=V.$$.smartPtr;else{var xe=V.clone();Y=this.rawShare(Y,ji.toHandle(function(){xe.delete()})),R!==null&&R.push(this.rawDestructor,Y)}break;default:jt("Unsupporting sharing policy")}return Y}function ko(R,V){if(V===null)return this.isReference&&jt("null is not a valid "+this.name),0;V.$$||jt('Cannot pass "'+ba(V)+'" as a '+this.name),V.$$.ptr||jt("Cannot pass deleted object as a pointer of type "+this.name),V.$$.ptrType.isConst&&jt("Cannot convert argument of type "+V.$$.ptrType.name+" to parameter type "+this.name);var Y=V.$$.ptrType.registeredClass,ye=Wi(V.$$.ptr,Y,this.registeredClass);return ye}function _s(R){return this.rawGetPointee&&(R=this.rawGetPointee(R)),R}function eo(R){this.rawDestructor&&this.rawDestructor(R)}function zi(R){R!==null&&R.delete()}function $i(){Ir.prototype.getPointee=_s,Ir.prototype.destructor=eo,Ir.prototype.argPackAdvance=8,Ir.prototype.readValueFromPointer=lt,Ir.prototype.deleteObject=zi,Ir.prototype.fromWireType=ln}function Ir(R,V,Y,ye,xe,Ce,Te,Me,Ae,qe,rt){this.name=R,this.registeredClass=V,this.isReference=Y,this.isConst=ye,this.isSmartPointer=xe,this.pointeeType=Ce,this.sharingPolicy=Te,this.rawGetPointee=Me,this.rawConstructor=Ae,this.rawShare=qe,this.rawDestructor=rt,!xe&&V.baseClass===void 0?ye?(this.toWireType=Ii,this.destructorFunction=null):(this.toWireType=ko,this.destructorFunction=null):this.toWireType=Ts}function yc(R,V,Y){o.hasOwnProperty(R)||br("Replacing nonexistant public symbol"),o[R].overloadTable!==void 0&&Y!==void 0||(o[R]=V,o[R].argCount=Y)}function Vo(R,V,Y){var ye=o["dynCall_"+R];return Y&&Y.length?ye.apply(null,[V].concat(Y)):ye.call(null,V)}var Fo=[];function yr(R){var V=Fo[R];return V||(R>=Fo.length&&(Fo.length=R+1),Fo[R]=V=Ve.get(R)),V}function wc(R,V,Y){if(R.includes("j"))return Vo(R,V,Y);var ye=yr(V).apply(null,Y);return ye}function mi(R,V){var Y=[];return function(){return Y.length=0,Object.assign(Y,arguments),wc(R,V,Y)}}function Or(R,V){R=Cn(R);function Y(){return R.includes("j")?mi(R,V):yr(V)}var ye=Y();return typeof ye!="function"&&jt("unknown function pointer with signature "+R+": "+V),ye}var qa=void 0;function mo(R){var V=de(R),Y=Cn(V);return Q(V),Y}function ii(R,V){var Y=[],ye={};function xe(Ce){if(!ye[Ce]&&!vt[Ce]){if(Mt[Ce]){Mt[Ce].forEach(xe);return}Y.push(Ce),ye[Ce]=!0}}throw V.forEach(xe),new qa(R+": "+Y.map(mo).join([", "]))}function ta(R,V,Y,ye,xe,Ce,Te,Me,Ae,qe,rt,mt,ht){rt=Cn(rt),Ce=Or(xe,Ce),Me&&(Me=Or(Te,Me)),qe&&(qe=Or(Ae,qe)),ht=Or(mt,ht);var zt=Dn(rt);pi(zt,function(){ii("Cannot construct "+rt+" due to unbound types",[ye])}),Ye([R,V,Y],ye?[ye]:[],function(Ut){Ut=Ut[0];var Gn,ai;ye?(Gn=Ut.registeredClass,ai=Gn.instancePrototype):ai=Di.prototype;var vi=Nt(zt,function(){if(Object.getPrototypeOf(this)!==bf)throw new Yt("Use 'new' to construct "+rt);if(rs.constructor_body===void 0)throw new Yt(rt+" has no accessible constructor");var wb=rs.constructor_body[arguments.length];if(wb===void 0)throw new Yt("Tried to invoke ctor of "+rt+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(rs.constructor_body).toString()+") parameters instead!");return wb.apply(this,arguments)}),bf=Object.create(ai,{constructor:{value:vi}});vi.prototype=bf;var rs=new No(rt,vi,bf,ht,Gn,Ce,Me,qe),Am=new Ir(rt,rs,!0,!1,!1),fg=new Ir(rt+"*",rs,!1,!1,!1),yb=new Ir(rt+" const*",rs,!1,!0,!1);return ar[R]={pointerType:fg,constPointerType:yb},yc(zt,vi),[Am,fg,yb]})}function Es(R,V){for(var Y=[],ye=0;ye>2]);return Y}function Xa(R,V){if(!(R instanceof Function))throw new TypeError("new_ called with constructor type "+typeof R+" which is not a function");var Y=Nt(R.name||"unknownFunctionName",function(){});Y.prototype=R.prototype;var ye=new Y,xe=R.apply(ye,V);return xe instanceof Object?xe:ye}function Ta(R,V,Y,ye,xe){var Ce=V.length;Ce<2&&jt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Te=V[1]!==null&&Y!==null,Me=!1,Ae=1;Ae>>16),_e(_.buffer),1}catch{}}function es(R){var V=F.length;R=R>>>0;var Y=Ic();if(R>Y)return!1;let ye=(Ae,qe)=>Ae+(qe-Ae%qe)%qe;for(var xe=1;xe<=4;xe*=2){var Ce=V*(1+.2/xe);Ce=Math.min(Ce,R+100663296);var Te=Math.min(Y,ye(Math.max(R,Ce),65536)),Me=Oc(Te);if(Me)return!0}return!1}var ts={};function vo(){return l||"./this.program"}function Bo(){if(!Bo.strings){var R=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",V={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:R,_:vo()};for(var Y in ts)ts[Y]===void 0?delete V[Y]:V[Y]=ts[Y];var ye=[];for(var Y in V)ye.push(Y+"="+V[Y]);Bo.strings=ye}return Bo.strings}function Hi(R,V,Y){for(var ye=0;ye>0]=R.charCodeAt(ye);A[V>>0]=0}function Ns(R,V){var Y=0;return Bo().forEach(function(ye,xe){var Ce=V+Y;ce[R+xe*4>>2]=Ce,Hi(ye,Ce),Y+=ye.length+1}),0}function ks(R,V){var Y=Bo();ce[R>>2]=Y.length;var ye=0;return Y.forEach(function(xe){ye+=xe.length+1}),ce[V>>2]=ye,0}function ns(R){f(R,new pt(R))}function Vs(R,V){ns(R)}var Ia=Vs;function Fs(R){return 52}function oe(R,V,Y,ye,xe){return 70}var ae=[null,[],[]];function De(R,V){var Y=ae[R];V===0||V===10?((R===1?C:S)(I(Y,0)),Y.length=0):Y.push(V)}function He(R,V,Y,ye){for(var xe=0,Ce=0;Ce>2],Me=ce[V+4>>2];V+=8;for(var Ae=0;Ae>2]=xe,0}function tt(R){var V=o["_"+R];return V}function z(R,V){A.set(R,V)}function ne(R,V,Y,ye,xe){var Ce={string:Ut=>{var Gn=0;if(Ut!=null&&Ut!==0){var ai=(Ut.length<<2)+1;Gn=k(ai),L(Ut,Gn,ai)}return Gn},array:Ut=>{var Gn=k(Ut.length);return z(Ut,Gn),Gn}};function Te(Ut){return V==="string"?P(Ut):V==="boolean"?!!Ut:Ut}var Me=tt(R),Ae=[],qe=0;if(ye)for(var rt=0;rt0||(M(),Re>0))return;function V(){W||(W=!0,o.calledRun=!0,!E&&(q(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),K()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),V()},1)):V()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return $(),i.ready}})();t.exports=r})(d$);var yEe=d$.exports;const wEe=ll(yEe),xEe=new URL("/static/dv3d/libjpegturbowasm_decode.wasm",import.meta.url),Gv={codec:void 0,decoder:void 0};function CEe(){if(Gv.codec)return Promise.resolve();const t=wEe({locateFile:e=>e.endsWith(".wasm")?xEe.toString():e});return new Promise((e,r)=>{t.then(n=>{Gv.codec=n,Gv.decoder=new n.JPEGDecoder,e()},r)})}async function SEe(t,e){await CEe();const r=Gv.decoder;r.getEncodedBuffer(t.length).set(t),r.decode();const i=r.getFrameInfo(),o=r.getDecodedBuffer(),a={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:e.signed,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},s=TEe(i,o),c={frameInfo:i};return{...e,pixelData:s,imageInfo:a,encodeOptions:c,...c,...a}}function TEe(t,e){return t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const _Ee="modulepreload",EEe=function(t){return"/static/dv3d/"+t},G7={},h$=function(e,r,n){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),s=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));i=Promise.allSettled(r.map(c=>{if(c=EEe(c),c in G7)return;G7[c]=!0;const l=c.endsWith(".css"),f=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${f}`))return;const u=document.createElement("link");if(u.rel=l?"stylesheet":_Ee,l||(u.as="script"),u.crossOrigin="",u.href=c,s&&u.setAttribute("nonce",s),document.head.appendChild(u),l)return new Promise((d,h)=>{u.addEventListener("load",d),u.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${c}`)))})}))}function o(a){const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=a,window.dispatchEvent(s),!s.defaultPrevented)throw a}return i.then(a=>{for(const s of a||[])s.status==="rejected"&&o(s.reason);return e().catch(o)})},Op={JpegImage:void 0,decodeConfig:{}};function bEe(t){return Op.decodeConfig=t,Op.JpegImage?Promise.resolve():new Promise((e,r)=>{h$(()=>import("./jpeg.js"),[]).then(n=>{Op.JpegImage=n.default,e()}).catch(r)})}async function DEe(t,e){if(await bEe(),typeof Op.JpegImage>"u")throw new Error("No JPEG Baseline decoder loaded");const r=new Op.JpegImage;if(r.parse(e),r.colorTransform=!1,t.bitsAllocated===8)return t.pixelData=r.getData(t.columns,t.rows),t;if(t.bitsAllocated===16)return t.pixelData=r.getData16(t.columns,t.rows),t}const Mp={jpeg:void 0,decodeConfig:{}};function IEe(t){return Mp.decodeConfig=t,Mp.jpeg?Promise.resolve():new Promise((e,r)=>{h$(async()=>{const{Decoder:n}=await import("./lossless.js");return{Decoder:n}},[]).then(({Decoder:n})=>{const i=new n;Mp.jpeg=i,e()},r)})}async function W7(t,e){if(await IEe(),typeof Mp.jpeg>"u")throw new Error("No JPEG Lossless decoder loaded");const r=t.bitsAllocated<=8?1:2,n=e.buffer,i=Mp.jpeg.decode(n,e.byteOffset,e.length,r);return t.pixelRepresentation===0?t.bitsAllocated===16?(t.pixelData=new Uint16Array(i.buffer),t):(t.pixelData=new Uint8Array(i.buffer),t):(t.pixelData=new Int16Array(i.buffer),t)}var g$={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(oe,ae){a=oe,s=ae});var c=Object.assign({},o),l=typeof window=="object",f=typeof importScripts=="function",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",d="";function h(oe){return o.locateFile?o.locateFile(oe,d):d+oe}var g,p,v;if(u){var y=el,m=el;f?d=m.dirname(d)+"/":d=__dirname+"/",g=(oe,ae)=>(oe=se(oe)?new URL(oe):m.normalize(oe),y.readFileSync(oe,ae?void 0:"utf8")),v=oe=>{var ae=g(oe,!0);return ae.buffer||(ae=new Uint8Array(ae)),ae},p=(oe,ae,De)=>{oe=se(oe)?new URL(oe):m.normalize(oe),y.readFile(oe,function(He,tt){He?De(He):ae(tt.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(oe){if(!(oe instanceof Qe))throw oe}),process.on("unhandledRejection",function(oe){throw oe}),o.inspect=function(){return"[Emscripten Module object]"}}else(l||f)&&(f?d=self.location.href:typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),n&&(d=n),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="",g=oe=>{var ae=new XMLHttpRequest;return ae.open("GET",oe,!1),ae.send(null),ae.responseText},f&&(v=oe=>{var ae=new XMLHttpRequest;return ae.open("GET",oe,!1),ae.responseType="arraybuffer",ae.send(null),new Uint8Array(ae.response)}),p=(oe,ae,De)=>{var He=new XMLHttpRequest;He.open("GET",oe,!0),He.responseType="arraybuffer",He.onload=()=>{if(He.status==200||He.status==0&&He.response){ae(He.response);return}De()},He.onerror=De,He.send(null)});o.print||console.log.bind(console);var w=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit;var x;o.wasmBinary&&(x=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&Fe("no native wasm support detected");var C,S=!1;function T(oe,ae){oe||Fe(ae)}var _=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function E(oe,ae,De){for(var He=ae+De,tt=ae;oe[tt]&&!(tt>=He);)++tt;if(tt-ae>16&&oe.buffer&&_)return _.decode(oe.subarray(ae,tt));for(var z="";ae>10,56320|Q&1023)}}return z}function b(oe,ae){return oe?E(B,oe,ae):""}function D(oe,ae,De,He){if(!(He>0))return 0;for(var tt=De,z=De+He-1,ne=0;ne=55296&&de<=57343){var le=oe.charCodeAt(++ne);de=65536+((de&1023)<<10)|le&1023}if(de<=127){if(De>=z)break;ae[De++]=de}else if(de<=2047){if(De+1>=z)break;ae[De++]=192|de>>6,ae[De++]=128|de&63}else if(de<=65535){if(De+2>=z)break;ae[De++]=224|de>>12,ae[De++]=128|de>>6&63,ae[De++]=128|de&63}else{if(De+3>=z)break;ae[De++]=240|de>>18,ae[De++]=128|de>>12&63,ae[De++]=128|de>>6&63,ae[De++]=128|de&63}}return ae[De]=0,De-tt}function I(oe,ae,De){return D(oe,B,ae,De)}function P(oe){for(var ae=0,De=0;De=55296&&He<=57343?(ae+=4,++De):ae+=3}return ae}var O,L,B,H,A,F,G,X,ee;function ce(oe){O=oe,o.HEAP8=L=new Int8Array(oe),o.HEAP16=H=new Int16Array(oe),o.HEAP32=F=new Int32Array(oe),o.HEAPU8=B=new Uint8Array(oe),o.HEAPU16=A=new Uint16Array(oe),o.HEAPU32=G=new Uint32Array(oe),o.HEAPF32=X=new Float32Array(oe),o.HEAPF64=ee=new Float64Array(oe)}o.INITIAL_MEMORY;var Se,we=[],_e=[],Ve=[];function Ge(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)M(o.preRun.shift());fe(we)}function Ne(){fe(_e)}function j(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)K(o.postRun.shift());fe(Ve)}function M(oe){we.unshift(oe)}function q(oe){_e.unshift(oe)}function K(oe){Ve.unshift(oe)}var J=0,re=null;function ie(oe){J++,o.monitorRunDependencies&&o.monitorRunDependencies(J)}function Re(oe){if(J--,o.monitorRunDependencies&&o.monitorRunDependencies(J),J==0&&re){var ae=re;re=null,ae()}}function Fe(oe){o.onAbort&&o.onAbort(oe),oe="Aborted("+oe+")",w(oe),S=!0,oe+=". Build with -sASSERTIONS for more info.";var ae=new WebAssembly.RuntimeError(oe);throw s(ae),ae}var je="data:application/octet-stream;base64,";function Xe(oe){return oe.startsWith(je)}function se(oe){return oe.startsWith("file://")}var ue;ue="charlswasm_decode.wasm",Xe(ue)||(ue=h(ue));function Pe(oe){try{if(oe==ue&&x)return new Uint8Array(x);if(v)return v(oe);throw"both async and sync fetching of the wasm failed"}catch(ae){Fe(ae)}}function pe(){if(!x&&(l||f)){if(typeof fetch=="function"&&!se(ue))return fetch(ue,{credentials:"same-origin"}).then(function(oe){if(!oe.ok)throw"failed to load wasm binary file at '"+ue+"'";return oe.arrayBuffer()}).catch(function(){return Pe(ue)});if(p)return new Promise(function(oe,ae){p(ue,function(De){oe(new Uint8Array(De))},ae)})}return Promise.resolve().then(function(){return Pe(ue)})}function Ee(){var oe={a:ts};function ae(ne,de){var le=ne.exports;o.asm=le,C=o.asm.z,ce(C.buffer),Se=o.asm.C,q(o.asm.A),Re()}ie();function De(ne){ae(ne.instance)}function He(ne){return pe().then(function(de){return WebAssembly.instantiate(de,oe)}).then(function(de){return de}).then(ne,function(de){w("failed to asynchronously prepare wasm: "+de),Fe(de)})}function tt(){return!x&&typeof WebAssembly.instantiateStreaming=="function"&&!Xe(ue)&&!se(ue)&&!u&&typeof fetch=="function"?fetch(ue,{credentials:"same-origin"}).then(function(ne){var de=WebAssembly.instantiateStreaming(ne,oe);return de.then(De,function(le){return w("wasm streaming compile failed: "+le),w("falling back to ArrayBuffer instantiation"),He(De)})}):He(De)}if(o.instantiateWasm)try{var z=o.instantiateWasm(oe,ae);return z}catch(ne){w("Module.instantiateWasm callback failed with error: "+ne),s(ne)}return tt().catch(s),{}}function Qe(oe){this.name="ExitStatus",this.message="Program terminated with exit("+oe+")",this.status=oe}function fe(oe){for(;oe.length>0;)oe.shift()(o)}function ft(oe){this.excPtr=oe,this.ptr=oe-24,this.set_type=function(ae){G[this.ptr+4>>2]=ae},this.get_type=function(){return G[this.ptr+4>>2]},this.set_destructor=function(ae){G[this.ptr+8>>2]=ae},this.get_destructor=function(){return G[this.ptr+8>>2]},this.set_refcount=function(ae){F[this.ptr>>2]=ae},this.set_caught=function(ae){ae=ae?1:0,L[this.ptr+12>>0]=ae},this.get_caught=function(){return L[this.ptr+12>>0]!=0},this.set_rethrown=function(ae){ae=ae?1:0,L[this.ptr+13>>0]=ae},this.get_rethrown=function(){return L[this.ptr+13>>0]!=0},this.init=function(ae,De){this.set_adjusted_ptr(0),this.set_type(ae),this.set_destructor(De),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var ae=F[this.ptr>>2];F[this.ptr>>2]=ae+1},this.release_ref=function(){var ae=F[this.ptr>>2];return F[this.ptr>>2]=ae-1,ae===1},this.set_adjusted_ptr=function(ae){G[this.ptr+16>>2]=ae},this.get_adjusted_ptr=function(){return G[this.ptr+16>>2]},this.get_exception_ptr=function(){var ae=Vs(this.get_type());if(ae)return G[this.excPtr>>2];var De=this.get_adjusted_ptr();return De!==0?De:this.excPtr}}function pt(oe,ae,De){var He=new ft(oe);throw He.init(ae,De),oe}var dt={};function Ue(oe){for(;oe.length;){var ae=oe.pop(),De=oe.pop();De(ae)}}function nt(oe){return this.fromWireType(F[oe>>2])}var at={},ot={},lt={},_t=48,vt=57;function Mt(oe){if(oe===void 0)return"_unknown";oe=oe.replace(/[^a-zA-Z0-9_]/g,"$");var ae=oe.charCodeAt(0);return ae>=_t&&ae<=vt?"_"+oe:oe}function Ft(oe,ae){return oe=Mt(oe),new Function("body","return function "+oe+`() { +`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",xe)(Qa,o,ji.toHandle,ye)}var Ls={};function Ec(R,V,Y,ye){R=ji.toValue(R);var xe=Ls[V];return xe||(xe=_c(V),Ls[V]=xe),xe(R,Y,ye)}function As(R,V){R=Qa(R,"_emval_take_value");var Y=R.readValueFromPointer(V);return ji.toHandle(Y)}function bc(){se("")}function Dc(R,V,Y){F.copyWithin(R,V,V+Y)}function Ic(){return 2147483648}function Oc(R){try{return _.grow(R-H.byteLength+65535>>>16),_e(_.buffer),1}catch{}}function es(R){var V=F.length;R=R>>>0;var Y=Ic();if(R>Y)return!1;let ye=(Ae,qe)=>Ae+(qe-Ae%qe)%qe;for(var xe=1;xe<=4;xe*=2){var Ce=V*(1+.2/xe);Ce=Math.min(Ce,R+100663296);var Te=Math.min(Y,ye(Math.max(R,Ce),65536)),Me=Oc(Te);if(Me)return!0}return!1}var ts={};function vo(){return l||"./this.program"}function Bo(){if(!Bo.strings){var R=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",V={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:R,_:vo()};for(var Y in ts)ts[Y]===void 0?delete V[Y]:V[Y]=ts[Y];var ye=[];for(var Y in V)ye.push(Y+"="+V[Y]);Bo.strings=ye}return Bo.strings}function Hi(R,V,Y){for(var ye=0;ye>0]=R.charCodeAt(ye);A[V>>0]=0}function Ns(R,V){var Y=0;return Bo().forEach(function(ye,xe){var Ce=V+Y;ce[R+xe*4>>2]=Ce,Hi(ye,Ce),Y+=ye.length+1}),0}function ks(R,V){var Y=Bo();ce[R>>2]=Y.length;var ye=0;return Y.forEach(function(xe){ye+=xe.length+1}),ce[V>>2]=ye,0}function ns(R){f(R,new pt(R))}function Vs(R,V){ns(R)}var Ia=Vs;function Fs(R){return 52}function oe(R,V,Y,ye,xe){return 70}var ae=[null,[],[]];function De(R,V){var Y=ae[R];V===0||V===10?((R===1?C:S)(I(Y,0)),Y.length=0):Y.push(V)}function He(R,V,Y,ye){for(var xe=0,Ce=0;Ce>2],Me=ce[V+4>>2];V+=8;for(var Ae=0;Ae>2]=xe,0}function tt(R){var V=o["_"+R];return V}function z(R,V){A.set(R,V)}function ne(R,V,Y,ye,xe){var Ce={string:Ut=>{var Gn=0;if(Ut!=null&&Ut!==0){var ai=(Ut.length<<2)+1;Gn=k(ai),L(Ut,Gn,ai)}return Gn},array:Ut=>{var Gn=k(Ut.length);return z(Ut,Gn),Gn}};function Te(Ut){return V==="string"?P(Ut):V==="boolean"?!!Ut:Ut}var Me=tt(R),Ae=[],qe=0;if(ye)for(var rt=0;rt0||(M(),Re>0))return;function V(){W||(W=!0,o.calledRun=!0,!E&&(q(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),K()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),V()},1)):V()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return $(),i.ready}})();t.exports=r})(d$);var yEe=d$.exports;const wEe=ll(yEe),xEe=new URL("/static/dv3d/libjpegturbowasm_decode.wasm",import.meta.url),Gv={codec:void 0,decoder:void 0};function CEe(){if(Gv.codec)return Promise.resolve();const t=wEe({locateFile:e=>e.endsWith(".wasm")?xEe.toString():e});return new Promise((e,r)=>{t.then(n=>{Gv.codec=n,Gv.decoder=new n.JPEGDecoder,e()},r)})}async function SEe(t,e){await CEe();const r=Gv.decoder;r.getEncodedBuffer(t.length).set(t),r.decode();const i=r.getFrameInfo(),o=r.getDecodedBuffer(),a={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:e.signed,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},s=TEe(i,o),c={frameInfo:i};return{...e,pixelData:s,imageInfo:a,encodeOptions:c,...c,...a}}function TEe(t,e){return t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const _Ee="modulepreload",EEe=function(t){return"/static/dv3d/"+t},G7={},h$=function(e,r,n){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),s=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));i=Promise.allSettled(r.map(c=>{if(c=EEe(c),c in G7)return;G7[c]=!0;const l=c.endsWith(".css"),f=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${f}`))return;const u=document.createElement("link");if(u.rel=l?"stylesheet":_Ee,l||(u.as="script"),u.crossOrigin="",u.href=c,s&&u.setAttribute("nonce",s),document.head.appendChild(u),l)return new Promise((d,h)=>{u.addEventListener("load",d),u.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${c}`)))})}))}function o(a){const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=a,window.dispatchEvent(s),!s.defaultPrevented)throw a}return i.then(a=>{for(const s of a||[])s.status==="rejected"&&o(s.reason);return e().catch(o)})},Op={JpegImage:void 0,decodeConfig:{}};function bEe(t){return Op.decodeConfig=t,Op.JpegImage?Promise.resolve():new Promise((e,r)=>{h$(()=>import("./jpeg.js"),[]).then(n=>{Op.JpegImage=n.default,e()}).catch(r)})}async function DEe(t,e){if(await bEe(),typeof Op.JpegImage>"u")throw new Error("No JPEG Baseline decoder loaded");const r=new Op.JpegImage;if(r.parse(e),r.colorTransform=!1,t.bitsAllocated===8)return t.pixelData=r.getData(t.columns,t.rows),t;if(t.bitsAllocated===16)return t.pixelData=r.getData16(t.columns,t.rows),t}const Mp={jpeg:void 0,decodeConfig:{}};function IEe(t){return Mp.decodeConfig=t,Mp.jpeg?Promise.resolve():new Promise((e,r)=>{h$(async()=>{const{Decoder:n}=await import("./lossless.js");return{Decoder:n}},[]).then(({Decoder:n})=>{const i=new n;Mp.jpeg=i,e()},r)})}async function W7(t,e){if(await IEe(),typeof Mp.jpeg>"u")throw new Error("No JPEG Lossless decoder loaded");const r=t.bitsAllocated<=8?1:2,n=e.buffer,i=Mp.jpeg.decode(n,e.byteOffset,e.length,r);return t.pixelRepresentation===0?t.bitsAllocated===16?(t.pixelData=new Uint16Array(i.buffer),t):(t.pixelData=new Uint8Array(i.buffer),t):(t.pixelData=new Int16Array(i.buffer),t)}var g$={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(oe,ae){a=oe,s=ae});var c=Object.assign({},o),l=typeof window=="object",f=typeof importScripts=="function",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",d="";function h(oe){return o.locateFile?o.locateFile(oe,d):d+oe}var g,p,v;if(u){var y=el,m=el;f?d=m.dirname(d)+"/":d=__dirname+"/",g=(oe,ae)=>(oe=se(oe)?new URL(oe):m.normalize(oe),y.readFileSync(oe,ae?void 0:"utf8")),v=oe=>{var ae=g(oe,!0);return ae.buffer||(ae=new Uint8Array(ae)),ae},p=(oe,ae,De)=>{oe=se(oe)?new URL(oe):m.normalize(oe),y.readFile(oe,function(He,tt){He?De(He):ae(tt.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(oe){if(!(oe instanceof Qe))throw oe}),process.on("unhandledRejection",function(oe){throw oe}),o.inspect=function(){return"[Emscripten Module object]"}}else(l||f)&&(f?d=self.location.href:typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),n&&(d=n),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="",g=oe=>{var ae=new XMLHttpRequest;return ae.open("GET",oe,!1),ae.send(null),ae.responseText},f&&(v=oe=>{var ae=new XMLHttpRequest;return ae.open("GET",oe,!1),ae.responseType="arraybuffer",ae.send(null),new Uint8Array(ae.response)}),p=(oe,ae,De)=>{var He=new XMLHttpRequest;He.open("GET",oe,!0),He.responseType="arraybuffer",He.onload=()=>{if(He.status==200||He.status==0&&He.response){ae(He.response);return}De()},He.onerror=De,He.send(null)});o.print||console.log.bind(console);var w=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit;var x;o.wasmBinary&&(x=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&Fe("no native wasm support detected");var C,S=!1;function T(oe,ae){oe||Fe(ae)}var _=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function E(oe,ae,De){for(var He=ae+De,tt=ae;oe[tt]&&!(tt>=He);)++tt;if(tt-ae>16&&oe.buffer&&_)return _.decode(oe.subarray(ae,tt));for(var z="";ae>10,56320|Q&1023)}}return z}function b(oe,ae){return oe?E(B,oe,ae):""}function D(oe,ae,De,He){if(!(He>0))return 0;for(var tt=De,z=De+He-1,ne=0;ne=55296&&he<=57343){var le=oe.charCodeAt(++ne);he=65536+((he&1023)<<10)|le&1023}if(he<=127){if(De>=z)break;ae[De++]=he}else if(he<=2047){if(De+1>=z)break;ae[De++]=192|he>>6,ae[De++]=128|he&63}else if(he<=65535){if(De+2>=z)break;ae[De++]=224|he>>12,ae[De++]=128|he>>6&63,ae[De++]=128|he&63}else{if(De+3>=z)break;ae[De++]=240|he>>18,ae[De++]=128|he>>12&63,ae[De++]=128|he>>6&63,ae[De++]=128|he&63}}return ae[De]=0,De-tt}function I(oe,ae,De){return D(oe,B,ae,De)}function P(oe){for(var ae=0,De=0;De=55296&&He<=57343?(ae+=4,++De):ae+=3}return ae}var O,L,B,H,A,F,G,X,ee;function ce(oe){O=oe,o.HEAP8=L=new Int8Array(oe),o.HEAP16=H=new Int16Array(oe),o.HEAP32=F=new Int32Array(oe),o.HEAPU8=B=new Uint8Array(oe),o.HEAPU16=A=new Uint16Array(oe),o.HEAPU32=G=new Uint32Array(oe),o.HEAPF32=X=new Float32Array(oe),o.HEAPF64=ee=new Float64Array(oe)}o.INITIAL_MEMORY;var Se,we=[],_e=[],Ve=[];function Ge(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)M(o.preRun.shift());fe(we)}function Ne(){fe(_e)}function j(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)K(o.postRun.shift());fe(Ve)}function M(oe){we.unshift(oe)}function q(oe){_e.unshift(oe)}function K(oe){Ve.unshift(oe)}var J=0,re=null;function ie(oe){J++,o.monitorRunDependencies&&o.monitorRunDependencies(J)}function Re(oe){if(J--,o.monitorRunDependencies&&o.monitorRunDependencies(J),J==0&&re){var ae=re;re=null,ae()}}function Fe(oe){o.onAbort&&o.onAbort(oe),oe="Aborted("+oe+")",w(oe),S=!0,oe+=". Build with -sASSERTIONS for more info.";var ae=new WebAssembly.RuntimeError(oe);throw s(ae),ae}var je="data:application/octet-stream;base64,";function Xe(oe){return oe.startsWith(je)}function se(oe){return oe.startsWith("file://")}var ue;ue="charlswasm_decode.wasm",Xe(ue)||(ue=h(ue));function Pe(oe){try{if(oe==ue&&x)return new Uint8Array(x);if(v)return v(oe);throw"both async and sync fetching of the wasm failed"}catch(ae){Fe(ae)}}function pe(){if(!x&&(l||f)){if(typeof fetch=="function"&&!se(ue))return fetch(ue,{credentials:"same-origin"}).then(function(oe){if(!oe.ok)throw"failed to load wasm binary file at '"+ue+"'";return oe.arrayBuffer()}).catch(function(){return Pe(ue)});if(p)return new Promise(function(oe,ae){p(ue,function(De){oe(new Uint8Array(De))},ae)})}return Promise.resolve().then(function(){return Pe(ue)})}function Ee(){var oe={a:ts};function ae(ne,he){var le=ne.exports;o.asm=le,C=o.asm.z,ce(C.buffer),Se=o.asm.C,q(o.asm.A),Re()}ie();function De(ne){ae(ne.instance)}function He(ne){return pe().then(function(he){return WebAssembly.instantiate(he,oe)}).then(function(he){return he}).then(ne,function(he){w("failed to asynchronously prepare wasm: "+he),Fe(he)})}function tt(){return!x&&typeof WebAssembly.instantiateStreaming=="function"&&!Xe(ue)&&!se(ue)&&!u&&typeof fetch=="function"?fetch(ue,{credentials:"same-origin"}).then(function(ne){var he=WebAssembly.instantiateStreaming(ne,oe);return he.then(De,function(le){return w("wasm streaming compile failed: "+le),w("falling back to ArrayBuffer instantiation"),He(De)})}):He(De)}if(o.instantiateWasm)try{var z=o.instantiateWasm(oe,ae);return z}catch(ne){w("Module.instantiateWasm callback failed with error: "+ne),s(ne)}return tt().catch(s),{}}function Qe(oe){this.name="ExitStatus",this.message="Program terminated with exit("+oe+")",this.status=oe}function fe(oe){for(;oe.length>0;)oe.shift()(o)}function ft(oe){this.excPtr=oe,this.ptr=oe-24,this.set_type=function(ae){G[this.ptr+4>>2]=ae},this.get_type=function(){return G[this.ptr+4>>2]},this.set_destructor=function(ae){G[this.ptr+8>>2]=ae},this.get_destructor=function(){return G[this.ptr+8>>2]},this.set_refcount=function(ae){F[this.ptr>>2]=ae},this.set_caught=function(ae){ae=ae?1:0,L[this.ptr+12>>0]=ae},this.get_caught=function(){return L[this.ptr+12>>0]!=0},this.set_rethrown=function(ae){ae=ae?1:0,L[this.ptr+13>>0]=ae},this.get_rethrown=function(){return L[this.ptr+13>>0]!=0},this.init=function(ae,De){this.set_adjusted_ptr(0),this.set_type(ae),this.set_destructor(De),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var ae=F[this.ptr>>2];F[this.ptr>>2]=ae+1},this.release_ref=function(){var ae=F[this.ptr>>2];return F[this.ptr>>2]=ae-1,ae===1},this.set_adjusted_ptr=function(ae){G[this.ptr+16>>2]=ae},this.get_adjusted_ptr=function(){return G[this.ptr+16>>2]},this.get_exception_ptr=function(){var ae=Vs(this.get_type());if(ae)return G[this.excPtr>>2];var De=this.get_adjusted_ptr();return De!==0?De:this.excPtr}}function pt(oe,ae,De){var He=new ft(oe);throw He.init(ae,De),oe}var dt={};function Ue(oe){for(;oe.length;){var ae=oe.pop(),De=oe.pop();De(ae)}}function nt(oe){return this.fromWireType(F[oe>>2])}var at={},ot={},lt={},_t=48,vt=57;function Mt(oe){if(oe===void 0)return"_unknown";oe=oe.replace(/[^a-zA-Z0-9_]/g,"$");var ae=oe.charCodeAt(0);return ae>=_t&&ae<=vt?"_"+oe:oe}function Ft(oe,ae){return oe=Mt(oe),new Function("body","return function "+oe+`() { "use strict"; return body.apply(this, arguments); }; `)(ae)}function wn(oe,ae){var De=Ft(ae,function(He){this.name=ae,this.message=He;var tt=new Error(He).stack;tt!==void 0&&(this.stack=this.toString()+` -`+tt.replace(/^Error(:[^\n]*)?\n/,""))});return De.prototype=Object.create(oe.prototype),De.prototype.constructor=De,De.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},De}var Dn=void 0;function Nt(oe){throw new Dn(oe)}function xn(oe,ae,De){oe.forEach(function(de){lt[de]=ae});function He(de){var le=De(de);le.length!==oe.length&&Nt("Mismatched type converter count");for(var Q=0;Q{ot.hasOwnProperty(de)?tt[le]=ot[de]:(z.push(de),at.hasOwnProperty(de)||(at[de]=[]),at[de].push(()=>{tt[le]=ot[de],++ne,ne===z.length&&He(tt)}))}),z.length===0&&He(tt)}function Ui(oe){var ae=dt[oe];delete dt[oe];var De=ae.rawConstructor,He=ae.rawDestructor,tt=ae.fields,z=tt.map(ne=>ne.getterReturnType).concat(tt.map(ne=>ne.setterArgumentType));xn([oe],z,ne=>{var de={};return tt.forEach((le,Q)=>{var he=le.fieldName,ge=ne[Q],me=le.getter,N=le.getterContext,k=ne[Q+tt.length],te=le.setter,ve=le.setterContext;de[he]={read:Ie=>ge.fromWireType(me(N,Ie)),write:(Ie,ke)=>{var be=[];te(ve,Ie,k.toWireType(be,ke)),Ue(be)}}}),[{name:ae.name,fromWireType:function(le){var Q={};for(var he in de)Q[he]=de[he].read(le);return He(le),Q},toWireType:function(le,Q){for(var he in de)if(!(he in Q))throw new TypeError('Missing field: "'+he+'"');var ge=De();for(he in de)de[he].write(ge,Q[he]);return le!==null&&le.push(He,ge),ge},argPackAdvance:8,readValueFromPointer:nt,destructorFunction:He}]})}function br(oe,ae,De,He,tt){}function Ye(oe){switch(oe){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+oe)}}function ut(){for(var oe=new Array(256),ae=0;ae<256;++ae)oe[ae]=String.fromCharCode(ae);Rt=oe}var Rt=void 0;function mn(oe){for(var ae="",De=oe;B[De];)ae+=Rt[B[De++]];return ae}var Fr=void 0;function Lt(oe){throw new Fr(oe)}function Cn(oe,ae,De={}){if(!("argPackAdvance"in ae))throw new TypeError("registerType registeredInstance requires argPackAdvance");var He=ae.name;if(oe||Lt('type "'+He+'" must have a positive integer typeid pointer'),ot.hasOwnProperty(oe)){if(De.ignoreDuplicateRegistrations)return;Lt("Cannot register type '"+He+"' twice")}if(ot[oe]=ae,delete lt[oe],at.hasOwnProperty(oe)){var tt=at[oe];delete at[oe],tt.forEach(z=>z())}}function Yt(oe,ae,De,He,tt){var z=Ye(De);ae=mn(ae),Cn(oe,{name:ae,fromWireType:function(ne){return!!ne},toWireType:function(ne,de){return de?He:tt},argPackAdvance:8,readValueFromPointer:function(ne){var de;if(De===1)de=L;else if(De===2)de=H;else if(De===4)de=F;else throw new TypeError("Unknown boolean type size: "+ae);return this.fromWireType(de[ne>>z])},destructorFunction:null})}function jt(oe){if(!(this instanceof Qi)||!(oe instanceof Qi))return!1;for(var ae=this.$$.ptrType.registeredClass,De=this.$$.ptr,He=oe.$$.ptrType.registeredClass,tt=oe.$$.ptr;ae.baseClass;)De=ae.upcast(De),ae=ae.baseClass;for(;He.baseClass;)tt=He.upcast(tt),He=He.baseClass;return ae===He&&De===tt}function hi(oe){return{count:oe.count,deleteScheduled:oe.deleteScheduled,preservePointerOnDelete:oe.preservePointerOnDelete,ptr:oe.ptr,ptrType:oe.ptrType,smartPtr:oe.smartPtr,smartPtrType:oe.smartPtrType}}function Bi(oe){function ae(De){return De.$$.ptrType.registeredClass.name}Lt(ae(oe)+" instance already deleted")}var Ao=!1;function jn(oe){}function fo(oe){oe.smartPtr?oe.smartPtrType.rawDestructor(oe.smartPtr):oe.ptrType.registeredClass.rawDestructor(oe.ptr)}function Ei(oe){oe.count.value-=1;var ae=oe.count.value===0;ae&&fo(oe)}function xa(oe,ae,De){if(ae===De)return oe;if(De.baseClass===void 0)return null;var He=xa(oe,ae,De.baseClass);return He===null?null:De.downcast(He)}var Bn={};function Ct(){return Object.keys(Ur).length}function Zt(){var oe=[];for(var ae in Ur)Ur.hasOwnProperty(ae)&&oe.push(Ur[ae]);return oe}var ar=[];function Qo(){for(;ar.length;){var oe=ar.pop();oe.$$.deleteScheduled=!1,oe.delete()}}var Dr=void 0;function ho(oe){Dr=oe,ar.length&&Dr&&Dr(Qo)}function bi(){o.getInheritedInstanceCount=Ct,o.getLiveInheritedInstances=Zt,o.flushPendingDeletes=Qo,o.setDelayFunction=ho}var Ur={};function Cs(oe,ae){for(ae===void 0&&Lt("ptr should not be undefined");oe.baseClass;)ae=oe.upcast(ae),oe=oe.baseClass;return ae}function go(oe,ae){return ae=Cs(oe,ae),Ur[ae]}function Zi(oe,ae){(!ae.ptrType||!ae.ptr)&&Nt("makeClassHandle requires ptr and ptrType");var De=!!ae.smartPtrType,He=!!ae.smartPtr;return De!==He&&Nt("Both smartPtrType and smartPtr must be specified"),ae.count={value:1},gi(Object.create(oe,{$$:{value:ae}}))}function Ca(oe){var ae=this.getPointee(oe);if(!ae)return this.destructor(oe),null;var De=go(this.registeredClass,ae);if(De!==void 0){if(De.$$.count.value===0)return De.$$.ptr=ae,De.$$.smartPtr=oe,De.clone();var He=De.clone();return this.destructor(oe),He}function tt(){return this.isSmartPointer?Zi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:ae,smartPtrType:this,smartPtr:oe}):Zi(this.registeredClass.instancePrototype,{ptrType:this,ptr:oe})}var z=this.registeredClass.getActualType(ae),ne=Bn[z];if(!ne)return tt.call(this);var de;this.isConst?de=ne.constPointerType:de=ne.pointerType;var le=xa(ae,this.registeredClass,de.registeredClass);return le===null?tt.call(this):this.isSmartPointer?Zi(de.registeredClass.instancePrototype,{ptrType:de,ptr:le,smartPtrType:this,smartPtr:oe}):Zi(de.registeredClass.instancePrototype,{ptrType:de,ptr:le})}function gi(oe){return typeof FinalizationRegistry>"u"?(gi=ae=>ae,oe):(Ao=new FinalizationRegistry(ae=>{Ei(ae.$$)}),gi=ae=>{var De=ae.$$,He=!!De.smartPtr;if(He){var tt={$$:De};Ao.register(ae,tt,ae)}return ae},jn=ae=>Ao.unregister(ae),gi(oe))}function Sa(){if(this.$$.ptr||Bi(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var oe=gi(Object.create(Object.getPrototypeOf(this),{$$:{value:hi(this.$$)}}));return oe.$$.count.value+=1,oe.$$.deleteScheduled=!1,oe}function ln(){this.$$.ptr||Bi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Lt("Object already scheduled for deletion"),jn(this),Ei(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Gi(){return!this.$$.ptr}function Ss(){return this.$$.ptr||Bi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Lt("Object already scheduled for deletion"),ar.push(this),ar.length===1&&Dr&&Dr(Qo),this.$$.deleteScheduled=!0,this}function ea(){Qi.prototype.isAliasOf=jt,Qi.prototype.clone=Sa,Qi.prototype.delete=ln,Qi.prototype.isDeleted=Gi,Qi.prototype.deleteLater=Ss}function Qi(){}function po(oe,ae,De){if(oe[ae].overloadTable===void 0){var He=oe[ae];oe[ae]=function(){return oe[ae].overloadTable.hasOwnProperty(arguments.length)||Lt("Function '"+De+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+oe[ae].overloadTable+")!"),oe[ae].overloadTable[arguments.length].apply(this,arguments)},oe[ae].overloadTable=[],oe[ae].overloadTable[He.argCount]=He}}function Zr(oe,ae,De){o.hasOwnProperty(oe)?((De===void 0||o[oe].overloadTable!==void 0&&o[oe].overloadTable[De]!==void 0)&&Lt("Cannot register public name '"+oe+"' twice"),po(o,oe,oe),o.hasOwnProperty(De)&&Lt("Cannot register multiple overloads of a function with the same number of arguments ("+De+")!"),o[oe].overloadTable[De]=ae):(o[oe]=ae,De!==void 0&&(o[oe].numArguments=De))}function Di(oe,ae,De,He,tt,z,ne,de){this.name=oe,this.constructor=ae,this.instancePrototype=De,this.rawDestructor=He,this.baseClass=tt,this.getActualType=z,this.upcast=ne,this.downcast=de,this.pureVirtualFunctions=[]}function sn(oe,ae,De){for(;ae!==De;)ae.upcast||Lt("Expected null or instance of "+De.name+", got an instance of "+ae.name),oe=ae.upcast(oe),ae=ae.baseClass;return oe}function pi(oe,ae){if(ae===null)return this.isReference&&Lt("null is not a valid "+this.name),0;ae.$$||Lt('Cannot pass "'+Sn(ae)+'" as a '+this.name),ae.$$.ptr||Lt("Cannot pass deleted object as a pointer of type "+this.name);var De=ae.$$.ptrType.registeredClass,He=sn(ae.$$.ptr,De,this.registeredClass);return He}function No(oe,ae){var De;if(ae===null)return this.isReference&&Lt("null is not a valid "+this.name),this.isSmartPointer?(De=this.rawConstructor(),oe!==null&&oe.push(this.rawDestructor,De),De):0;ae.$$||Lt('Cannot pass "'+Sn(ae)+'" as a '+this.name),ae.$$.ptr||Lt("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&ae.$$.ptrType.isConst&&Lt("Cannot convert argument of type "+(ae.$$.smartPtrType?ae.$$.smartPtrType.name:ae.$$.ptrType.name)+" to parameter type "+this.name);var He=ae.$$.ptrType.registeredClass;if(De=sn(ae.$$.ptr,He,this.registeredClass),this.isSmartPointer)switch(ae.$$.smartPtr===void 0&&Lt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:ae.$$.smartPtrType===this?De=ae.$$.smartPtr:Lt("Cannot convert argument of type "+(ae.$$.smartPtrType?ae.$$.smartPtrType.name:ae.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:De=ae.$$.smartPtr;break;case 2:if(ae.$$.smartPtrType===this)De=ae.$$.smartPtr;else{var tt=ae.clone();De=this.rawShare(De,oi.toHandle(function(){tt.delete()})),oe!==null&&oe.push(this.rawDestructor,De)}break;default:Lt("Unsupporting sharing policy")}return De}function Wi(oe,ae){if(ae===null)return this.isReference&&Lt("null is not a valid "+this.name),0;ae.$$||Lt('Cannot pass "'+Sn(ae)+'" as a '+this.name),ae.$$.ptr||Lt("Cannot pass deleted object as a pointer of type "+this.name),ae.$$.ptrType.isConst&&Lt("Cannot convert argument of type "+ae.$$.ptrType.name+" to parameter type "+this.name);var De=ae.$$.ptrType.registeredClass,He=sn(ae.$$.ptr,De,this.registeredClass);return He}function Ii(oe){return this.rawGetPointee&&(oe=this.rawGetPointee(oe)),oe}function Ts(oe){this.rawDestructor&&this.rawDestructor(oe)}function ko(oe){oe!==null&&oe.delete()}function _s(){eo.prototype.getPointee=Ii,eo.prototype.destructor=Ts,eo.prototype.argPackAdvance=8,eo.prototype.readValueFromPointer=nt,eo.prototype.deleteObject=ko,eo.prototype.fromWireType=Ca}function eo(oe,ae,De,He,tt,z,ne,de,le,Q,he){this.name=oe,this.registeredClass=ae,this.isReference=De,this.isConst=He,this.isSmartPointer=tt,this.pointeeType=z,this.sharingPolicy=ne,this.rawGetPointee=de,this.rawConstructor=le,this.rawShare=Q,this.rawDestructor=he,!tt&&ae.baseClass===void 0?He?(this.toWireType=pi,this.destructorFunction=null):(this.toWireType=Wi,this.destructorFunction=null):this.toWireType=No}function zi(oe,ae,De){o.hasOwnProperty(oe)||Nt("Replacing nonexistant public symbol"),o[oe].overloadTable!==void 0&&De!==void 0?o[oe].overloadTable[De]=ae:(o[oe]=ae,o[oe].argCount=De)}function $i(oe,ae,De){var He=o["dynCall_"+oe];return De&&De.length?He.apply(null,[ae].concat(De)):He.call(null,ae)}var Ir=[];function yc(oe){var ae=Ir[oe];return ae||(oe>=Ir.length&&(Ir.length=oe+1),Ir[oe]=ae=Se.get(oe)),ae}function Vo(oe,ae,De){if(oe.includes("j"))return $i(oe,ae,De);var He=yc(ae).apply(null,De);return He}function Fo(oe,ae){var De=[];return function(){return De.length=0,Object.assign(De,arguments),Vo(oe,ae,De)}}function yr(oe,ae){oe=mn(oe);function De(){return oe.includes("j")?Fo(oe,ae):yc(ae)}var He=De();return typeof He!="function"&&Lt("unknown function pointer with signature "+oe+": "+ae),He}var wc=void 0;function mi(oe){var ae=Bo(oe),De=mn(ae);return Hi(ae),De}function Or(oe,ae){var De=[],He={};function tt(z){if(!He[z]&&!ot[z]){if(lt[z]){lt[z].forEach(tt);return}De.push(z),He[z]=!0}}throw ae.forEach(tt),new wc(oe+": "+De.map(mi).join([", "]))}function qa(oe,ae,De,He,tt,z,ne,de,le,Q,he,ge,me){he=mn(he),z=yr(tt,z),de&&(de=yr(ne,de)),Q&&(Q=yr(le,Q)),me=yr(ge,me);var N=Mt(he);Zr(N,function(){Or("Cannot construct "+he+" due to unbound types",[He])}),xn([oe,ae,De],He?[He]:[],function(k){k=k[0];var te,ve;He?(te=k.registeredClass,ve=te.instancePrototype):ve=Qi.prototype;var Ie=Ft(N,function(){if(Object.getPrototypeOf(this)!==ke)throw new Fr("Use 'new' to construct "+he);if(be.constructor_body===void 0)throw new Fr(he+" has no accessible constructor");var R=be.constructor_body[arguments.length];if(R===void 0)throw new Fr("Tried to invoke ctor of "+he+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(be.constructor_body).toString()+") parameters instead!");return R.apply(this,arguments)}),ke=Object.create(ve,{constructor:{value:Ie}});Ie.prototype=ke;var be=new Di(he,Ie,ke,me,te,z,de,Q),Oe=new eo(he,be,!0,!1,!1),W=new eo(he+"*",be,!1,!1,!1),$=new eo(he+" const*",be,!1,!0,!1);return Bn[oe]={pointerType:W,constPointerType:$},zi(N,Ie),[Oe,W,$]})}function mo(oe,ae){for(var De=[],He=0;He>2]);return De}function ii(oe,ae){if(!(oe instanceof Function))throw new TypeError("new_ called with constructor type "+typeof oe+" which is not a function");var De=Ft(oe.name||"unknownFunctionName",function(){});De.prototype=oe.prototype;var He=new De,tt=oe.apply(He,ae);return tt instanceof Object?tt:He}function ta(oe,ae,De,He,tt){var z=ae.length;z<2&&Lt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var ne=ae[1]!==null&&De!==null,de=!1,le=1;le{ot.hasOwnProperty(he)?tt[le]=ot[he]:(z.push(he),at.hasOwnProperty(he)||(at[he]=[]),at[he].push(()=>{tt[le]=ot[he],++ne,ne===z.length&&He(tt)}))}),z.length===0&&He(tt)}function Ui(oe){var ae=dt[oe];delete dt[oe];var De=ae.rawConstructor,He=ae.rawDestructor,tt=ae.fields,z=tt.map(ne=>ne.getterReturnType).concat(tt.map(ne=>ne.setterArgumentType));xn([oe],z,ne=>{var he={};return tt.forEach((le,Q)=>{var de=le.fieldName,ge=ne[Q],me=le.getter,N=le.getterContext,k=ne[Q+tt.length],te=le.setter,ve=le.setterContext;he[de]={read:Ie=>ge.fromWireType(me(N,Ie)),write:(Ie,ke)=>{var be=[];te(ve,Ie,k.toWireType(be,ke)),Ue(be)}}}),[{name:ae.name,fromWireType:function(le){var Q={};for(var de in he)Q[de]=he[de].read(le);return He(le),Q},toWireType:function(le,Q){for(var de in he)if(!(de in Q))throw new TypeError('Missing field: "'+de+'"');var ge=De();for(de in he)he[de].write(ge,Q[de]);return le!==null&&le.push(He,ge),ge},argPackAdvance:8,readValueFromPointer:nt,destructorFunction:He}]})}function br(oe,ae,De,He,tt){}function Ye(oe){switch(oe){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+oe)}}function ut(){for(var oe=new Array(256),ae=0;ae<256;++ae)oe[ae]=String.fromCharCode(ae);Rt=oe}var Rt=void 0;function mn(oe){for(var ae="",De=oe;B[De];)ae+=Rt[B[De++]];return ae}var Fr=void 0;function Lt(oe){throw new Fr(oe)}function Cn(oe,ae,De={}){if(!("argPackAdvance"in ae))throw new TypeError("registerType registeredInstance requires argPackAdvance");var He=ae.name;if(oe||Lt('type "'+He+'" must have a positive integer typeid pointer'),ot.hasOwnProperty(oe)){if(De.ignoreDuplicateRegistrations)return;Lt("Cannot register type '"+He+"' twice")}if(ot[oe]=ae,delete lt[oe],at.hasOwnProperty(oe)){var tt=at[oe];delete at[oe],tt.forEach(z=>z())}}function Yt(oe,ae,De,He,tt){var z=Ye(De);ae=mn(ae),Cn(oe,{name:ae,fromWireType:function(ne){return!!ne},toWireType:function(ne,he){return he?He:tt},argPackAdvance:8,readValueFromPointer:function(ne){var he;if(De===1)he=L;else if(De===2)he=H;else if(De===4)he=F;else throw new TypeError("Unknown boolean type size: "+ae);return this.fromWireType(he[ne>>z])},destructorFunction:null})}function jt(oe){if(!(this instanceof Qi)||!(oe instanceof Qi))return!1;for(var ae=this.$$.ptrType.registeredClass,De=this.$$.ptr,He=oe.$$.ptrType.registeredClass,tt=oe.$$.ptr;ae.baseClass;)De=ae.upcast(De),ae=ae.baseClass;for(;He.baseClass;)tt=He.upcast(tt),He=He.baseClass;return ae===He&&De===tt}function hi(oe){return{count:oe.count,deleteScheduled:oe.deleteScheduled,preservePointerOnDelete:oe.preservePointerOnDelete,ptr:oe.ptr,ptrType:oe.ptrType,smartPtr:oe.smartPtr,smartPtrType:oe.smartPtrType}}function Bi(oe){function ae(De){return De.$$.ptrType.registeredClass.name}Lt(ae(oe)+" instance already deleted")}var Ao=!1;function jn(oe){}function fo(oe){oe.smartPtr?oe.smartPtrType.rawDestructor(oe.smartPtr):oe.ptrType.registeredClass.rawDestructor(oe.ptr)}function Ei(oe){oe.count.value-=1;var ae=oe.count.value===0;ae&&fo(oe)}function xa(oe,ae,De){if(ae===De)return oe;if(De.baseClass===void 0)return null;var He=xa(oe,ae,De.baseClass);return He===null?null:De.downcast(He)}var Bn={};function Ct(){return Object.keys(Ur).length}function Zt(){var oe=[];for(var ae in Ur)Ur.hasOwnProperty(ae)&&oe.push(Ur[ae]);return oe}var ar=[];function Qo(){for(;ar.length;){var oe=ar.pop();oe.$$.deleteScheduled=!1,oe.delete()}}var Dr=void 0;function ho(oe){Dr=oe,ar.length&&Dr&&Dr(Qo)}function bi(){o.getInheritedInstanceCount=Ct,o.getLiveInheritedInstances=Zt,o.flushPendingDeletes=Qo,o.setDelayFunction=ho}var Ur={};function Cs(oe,ae){for(ae===void 0&&Lt("ptr should not be undefined");oe.baseClass;)ae=oe.upcast(ae),oe=oe.baseClass;return ae}function go(oe,ae){return ae=Cs(oe,ae),Ur[ae]}function Zi(oe,ae){(!ae.ptrType||!ae.ptr)&&Nt("makeClassHandle requires ptr and ptrType");var De=!!ae.smartPtrType,He=!!ae.smartPtr;return De!==He&&Nt("Both smartPtrType and smartPtr must be specified"),ae.count={value:1},gi(Object.create(oe,{$$:{value:ae}}))}function Ca(oe){var ae=this.getPointee(oe);if(!ae)return this.destructor(oe),null;var De=go(this.registeredClass,ae);if(De!==void 0){if(De.$$.count.value===0)return De.$$.ptr=ae,De.$$.smartPtr=oe,De.clone();var He=De.clone();return this.destructor(oe),He}function tt(){return this.isSmartPointer?Zi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:ae,smartPtrType:this,smartPtr:oe}):Zi(this.registeredClass.instancePrototype,{ptrType:this,ptr:oe})}var z=this.registeredClass.getActualType(ae),ne=Bn[z];if(!ne)return tt.call(this);var he;this.isConst?he=ne.constPointerType:he=ne.pointerType;var le=xa(ae,this.registeredClass,he.registeredClass);return le===null?tt.call(this):this.isSmartPointer?Zi(he.registeredClass.instancePrototype,{ptrType:he,ptr:le,smartPtrType:this,smartPtr:oe}):Zi(he.registeredClass.instancePrototype,{ptrType:he,ptr:le})}function gi(oe){return typeof FinalizationRegistry>"u"?(gi=ae=>ae,oe):(Ao=new FinalizationRegistry(ae=>{Ei(ae.$$)}),gi=ae=>{var De=ae.$$,He=!!De.smartPtr;if(He){var tt={$$:De};Ao.register(ae,tt,ae)}return ae},jn=ae=>Ao.unregister(ae),gi(oe))}function Sa(){if(this.$$.ptr||Bi(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var oe=gi(Object.create(Object.getPrototypeOf(this),{$$:{value:hi(this.$$)}}));return oe.$$.count.value+=1,oe.$$.deleteScheduled=!1,oe}function ln(){this.$$.ptr||Bi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Lt("Object already scheduled for deletion"),jn(this),Ei(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Gi(){return!this.$$.ptr}function Ss(){return this.$$.ptr||Bi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Lt("Object already scheduled for deletion"),ar.push(this),ar.length===1&&Dr&&Dr(Qo),this.$$.deleteScheduled=!0,this}function ea(){Qi.prototype.isAliasOf=jt,Qi.prototype.clone=Sa,Qi.prototype.delete=ln,Qi.prototype.isDeleted=Gi,Qi.prototype.deleteLater=Ss}function Qi(){}function po(oe,ae,De){if(oe[ae].overloadTable===void 0){var He=oe[ae];oe[ae]=function(){return oe[ae].overloadTable.hasOwnProperty(arguments.length)||Lt("Function '"+De+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+oe[ae].overloadTable+")!"),oe[ae].overloadTable[arguments.length].apply(this,arguments)},oe[ae].overloadTable=[],oe[ae].overloadTable[He.argCount]=He}}function Zr(oe,ae,De){o.hasOwnProperty(oe)?((De===void 0||o[oe].overloadTable!==void 0&&o[oe].overloadTable[De]!==void 0)&&Lt("Cannot register public name '"+oe+"' twice"),po(o,oe,oe),o.hasOwnProperty(De)&&Lt("Cannot register multiple overloads of a function with the same number of arguments ("+De+")!"),o[oe].overloadTable[De]=ae):(o[oe]=ae,De!==void 0&&(o[oe].numArguments=De))}function Di(oe,ae,De,He,tt,z,ne,he){this.name=oe,this.constructor=ae,this.instancePrototype=De,this.rawDestructor=He,this.baseClass=tt,this.getActualType=z,this.upcast=ne,this.downcast=he,this.pureVirtualFunctions=[]}function sn(oe,ae,De){for(;ae!==De;)ae.upcast||Lt("Expected null or instance of "+De.name+", got an instance of "+ae.name),oe=ae.upcast(oe),ae=ae.baseClass;return oe}function pi(oe,ae){if(ae===null)return this.isReference&&Lt("null is not a valid "+this.name),0;ae.$$||Lt('Cannot pass "'+Sn(ae)+'" as a '+this.name),ae.$$.ptr||Lt("Cannot pass deleted object as a pointer of type "+this.name);var De=ae.$$.ptrType.registeredClass,He=sn(ae.$$.ptr,De,this.registeredClass);return He}function No(oe,ae){var De;if(ae===null)return this.isReference&&Lt("null is not a valid "+this.name),this.isSmartPointer?(De=this.rawConstructor(),oe!==null&&oe.push(this.rawDestructor,De),De):0;ae.$$||Lt('Cannot pass "'+Sn(ae)+'" as a '+this.name),ae.$$.ptr||Lt("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&ae.$$.ptrType.isConst&&Lt("Cannot convert argument of type "+(ae.$$.smartPtrType?ae.$$.smartPtrType.name:ae.$$.ptrType.name)+" to parameter type "+this.name);var He=ae.$$.ptrType.registeredClass;if(De=sn(ae.$$.ptr,He,this.registeredClass),this.isSmartPointer)switch(ae.$$.smartPtr===void 0&&Lt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:ae.$$.smartPtrType===this?De=ae.$$.smartPtr:Lt("Cannot convert argument of type "+(ae.$$.smartPtrType?ae.$$.smartPtrType.name:ae.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:De=ae.$$.smartPtr;break;case 2:if(ae.$$.smartPtrType===this)De=ae.$$.smartPtr;else{var tt=ae.clone();De=this.rawShare(De,oi.toHandle(function(){tt.delete()})),oe!==null&&oe.push(this.rawDestructor,De)}break;default:Lt("Unsupporting sharing policy")}return De}function Wi(oe,ae){if(ae===null)return this.isReference&&Lt("null is not a valid "+this.name),0;ae.$$||Lt('Cannot pass "'+Sn(ae)+'" as a '+this.name),ae.$$.ptr||Lt("Cannot pass deleted object as a pointer of type "+this.name),ae.$$.ptrType.isConst&&Lt("Cannot convert argument of type "+ae.$$.ptrType.name+" to parameter type "+this.name);var De=ae.$$.ptrType.registeredClass,He=sn(ae.$$.ptr,De,this.registeredClass);return He}function Ii(oe){return this.rawGetPointee&&(oe=this.rawGetPointee(oe)),oe}function Ts(oe){this.rawDestructor&&this.rawDestructor(oe)}function ko(oe){oe!==null&&oe.delete()}function _s(){eo.prototype.getPointee=Ii,eo.prototype.destructor=Ts,eo.prototype.argPackAdvance=8,eo.prototype.readValueFromPointer=nt,eo.prototype.deleteObject=ko,eo.prototype.fromWireType=Ca}function eo(oe,ae,De,He,tt,z,ne,he,le,Q,de){this.name=oe,this.registeredClass=ae,this.isReference=De,this.isConst=He,this.isSmartPointer=tt,this.pointeeType=z,this.sharingPolicy=ne,this.rawGetPointee=he,this.rawConstructor=le,this.rawShare=Q,this.rawDestructor=de,!tt&&ae.baseClass===void 0?He?(this.toWireType=pi,this.destructorFunction=null):(this.toWireType=Wi,this.destructorFunction=null):this.toWireType=No}function zi(oe,ae,De){o.hasOwnProperty(oe)||Nt("Replacing nonexistant public symbol"),o[oe].overloadTable!==void 0&&De!==void 0?o[oe].overloadTable[De]=ae:(o[oe]=ae,o[oe].argCount=De)}function $i(oe,ae,De){var He=o["dynCall_"+oe];return De&&De.length?He.apply(null,[ae].concat(De)):He.call(null,ae)}var Ir=[];function yc(oe){var ae=Ir[oe];return ae||(oe>=Ir.length&&(Ir.length=oe+1),Ir[oe]=ae=Se.get(oe)),ae}function Vo(oe,ae,De){if(oe.includes("j"))return $i(oe,ae,De);var He=yc(ae).apply(null,De);return He}function Fo(oe,ae){var De=[];return function(){return De.length=0,Object.assign(De,arguments),Vo(oe,ae,De)}}function yr(oe,ae){oe=mn(oe);function De(){return oe.includes("j")?Fo(oe,ae):yc(ae)}var He=De();return typeof He!="function"&&Lt("unknown function pointer with signature "+oe+": "+ae),He}var wc=void 0;function mi(oe){var ae=Bo(oe),De=mn(ae);return Hi(ae),De}function Or(oe,ae){var De=[],He={};function tt(z){if(!He[z]&&!ot[z]){if(lt[z]){lt[z].forEach(tt);return}De.push(z),He[z]=!0}}throw ae.forEach(tt),new wc(oe+": "+De.map(mi).join([", "]))}function qa(oe,ae,De,He,tt,z,ne,he,le,Q,de,ge,me){de=mn(de),z=yr(tt,z),he&&(he=yr(ne,he)),Q&&(Q=yr(le,Q)),me=yr(ge,me);var N=Mt(de);Zr(N,function(){Or("Cannot construct "+de+" due to unbound types",[He])}),xn([oe,ae,De],He?[He]:[],function(k){k=k[0];var te,ve;He?(te=k.registeredClass,ve=te.instancePrototype):ve=Qi.prototype;var Ie=Ft(N,function(){if(Object.getPrototypeOf(this)!==ke)throw new Fr("Use 'new' to construct "+de);if(be.constructor_body===void 0)throw new Fr(de+" has no accessible constructor");var R=be.constructor_body[arguments.length];if(R===void 0)throw new Fr("Tried to invoke ctor of "+de+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(be.constructor_body).toString()+") parameters instead!");return R.apply(this,arguments)}),ke=Object.create(ve,{constructor:{value:Ie}});Ie.prototype=ke;var be=new Di(de,Ie,ke,me,te,z,he,Q),Oe=new eo(de,be,!0,!1,!1),W=new eo(de+"*",be,!1,!1,!1),$=new eo(de+" const*",be,!1,!0,!1);return Bn[oe]={pointerType:W,constPointerType:$},zi(N,Ie),[Oe,W,$]})}function mo(oe,ae){for(var De=[],He=0;He>2]);return De}function ii(oe,ae){if(!(oe instanceof Function))throw new TypeError("new_ called with constructor type "+typeof oe+" which is not a function");var De=Ft(oe.name||"unknownFunctionName",function(){});De.prototype=oe.prototype;var He=new De,tt=oe.apply(He,ae);return tt instanceof Object?tt:He}function ta(oe,ae,De,He,tt){var z=ae.length;z<2&&Lt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var ne=ae[1]!==null&&De!==null,he=!1,le=1;le0?", ":"")+ge),me+=(Q?"var rv = ":"")+"invoker(fn"+(ge.length>0?", ":"")+ge+`); -`,de)me+=`runDestructors(destructors); +`,he)me+=`runDestructors(destructors); `;else for(var le=ne?1:2;le0);var ne=mo(ae,De);tt=yr(He,tt),xn([],[oe],function(de){de=de[0];var le="constructor "+de.name;if(de.registeredClass.constructor_body===void 0&&(de.registeredClass.constructor_body=[]),de.registeredClass.constructor_body[ae-1]!==void 0)throw new Fr("Cannot register multiple constructors with identical number of parameters ("+(ae-1)+") for class '"+de.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return de.registeredClass.constructor_body[ae-1]=()=>{Or("Cannot construct "+de.name+" due to unbound types",ne)},xn([],ne,function(Q){return Q.splice(1,0,null),de.registeredClass.constructor_body[ae-1]=ta(le,Q,null,tt,z),[]}),[]})}function Xa(oe,ae,De,He,tt,z,ne,de){var le=mo(De,He);ae=mn(ae),z=yr(tt,z),xn([],[oe],function(Q){Q=Q[0];var he=Q.name+"."+ae;ae.startsWith("@@")&&(ae=Symbol[ae.substring(2)]),de&&Q.registeredClass.pureVirtualFunctions.push(ae);function ge(){Or("Cannot call "+he+" due to unbound types",le)}var me=Q.registeredClass.instancePrototype,N=me[ae];return N===void 0||N.overloadTable===void 0&&N.className!==Q.name&&N.argCount===De-2?(ge.argCount=De-2,ge.className=Q.name,me[ae]=ge):(po(me,ae,he),me[ae].overloadTable[De-2]=ge),xn([],le,function(k){var te=ta(he,k,Q,z,ne);return me[ae].overloadTable===void 0?(te.argCount=De-2,me[ae]=te):me[ae].overloadTable[De-2]=te,[]}),[]})}var Ta=[],Vn=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function _a(oe){oe>4&&--Vn[oe].refcount===0&&(Vn[oe]=void 0,Ta.push(oe))}function Qr(){for(var oe=0,ae=5;ae(oe||Lt("Cannot use deleted val. handle = "+oe),Vn[oe].value),toHandle:oe=>{switch(oe){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var ae=Ta.length?Ta.pop():Vn.length;return Vn[ae]={refcount:1,value:oe},ae}}}};function Ya(oe,ae){ae=mn(ae),Cn(oe,{name:ae,fromWireType:function(De){var He=oi.toValue(De);return _a(De),He},toWireType:function(De,He){return oi.toHandle(He)},argPackAdvance:8,readValueFromPointer:nt,destructorFunction:null})}function Sn(oe){if(oe===null)return"null";var ae=typeof oe;return ae==="object"||ae==="array"||ae==="function"?oe.toString():""+oe}function ji(oe,ae){switch(ae){case 2:return function(De){return this.fromWireType(X[De>>2])};case 3:return function(De){return this.fromWireType(ee[De>>3])};default:throw new TypeError("Unknown float type: "+oe)}}function Ea(oe,ae,De){var He=Ye(De);ae=mn(ae),Cn(oe,{name:ae,fromWireType:function(tt){return tt},toWireType:function(tt,z){return z},argPackAdvance:8,readValueFromPointer:ji(ae,He),destructorFunction:null})}function ba(oe,ae,De,He,tt,z){var ne=mo(ae,De);oe=mn(oe),tt=yr(He,tt),Zr(oe,function(){Or("Cannot call "+oe+" due to unbound types",ne)},ae-1),xn([],ne,function(de){var le=[de[0],null].concat(de.slice(1));return zi(oe,ta(oe,le,null,tt,z),ae-1),[]})}function Oi(oe,ae,De){switch(ae){case 0:return De?function(tt){return L[tt]}:function(tt){return B[tt]};case 1:return De?function(tt){return H[tt>>1]}:function(tt){return A[tt>>1]};case 2:return De?function(tt){return F[tt>>2]}:function(tt){return G[tt>>2]};default:throw new TypeError("Unknown integer type: "+oe)}}function bs(oe,ae,De,He,tt){ae=mn(ae);var z=Ye(De),ne=ge=>ge;if(He===0){var de=32-8*De;ne=ge=>ge<>>de}var le=ae.includes("unsigned"),Q=(ge,me)=>{},he;le?he=function(ge,me){return Q(me,this.name),me>>>0}:he=function(ge,me){return Q(me,this.name),me},Cn(oe,{name:ae,fromWireType:ne,toWireType:he,argPackAdvance:8,readValueFromPointer:Oi(ae,z,He!==0),destructorFunction:null})}function na(oe,ae,De){var He=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],tt=He[ae];function z(ne){ne=ne>>2;var de=G,le=de[ne],Q=de[ne+1];return new tt(O,Q,le)}De=mn(De),Cn(oe,{name:De,fromWireType:z,argPackAdvance:8,readValueFromPointer:z},{ignoreDuplicateRegistrations:!0})}function Cc(oe,ae){ae=mn(ae);var De=ae==="std::string";Cn(oe,{name:ae,fromWireType:function(He){var tt=G[He>>2],z=He+4,ne;if(De)for(var de=z,le=0;le<=tt;++le){var Q=z+le;if(le==tt||B[Q]==0){var he=Q-de,ge=b(de,he);ne===void 0?ne=ge:(ne+="\0",ne+=ge),de=Q+1}}else{for(var me=new Array(tt),le=0;le>2]=z,De&&ne)I(tt,le,z+1);else if(ne)for(var Q=0;Q255&&(Hi(le),Lt("String has UTF-16 code units that do not fit in 8 bits")),B[le+Q]=he}else for(var Q=0;Q>1,tt=He+ae/2;!(He>=tt)&&A[He];)++He;if(De=He<<1,De-oe>32&&Uo)return Uo.decode(B.subarray(oe,De));for(var z="",ne=0;!(ne>=ae/2);++ne){var de=H[oe+ne*2>>1];if(de==0)break;z+=String.fromCharCode(de)}return z}function Sc(oe,ae,De){if(De===void 0&&(De=2147483647),De<2)return 0;De-=2;for(var He=ae,tt=De>1]=ne,ae+=2}return H[ae>>1]=0,ae-He}function Ja(oe){return oe.length*2}function pl(oe,ae){for(var De=0,He="";!(De>=ae/4);){var tt=F[oe+De*4>>2];if(tt==0)break;if(++De,tt>=65536){var z=tt-65536;He+=String.fromCharCode(55296|z>>10,56320|z&1023)}else He+=String.fromCharCode(tt)}return He}function ml(oe,ae,De){if(De===void 0&&(De=2147483647),De<4)return 0;for(var He=ae,tt=He+De-4,z=0;z=55296&&ne<=57343){var de=oe.charCodeAt(++z);ne=65536+((ne&1023)<<10)|de&1023}if(F[ae>>2]=ne,ae+=4,ae+4>tt)break}return F[ae>>2]=0,ae-He}function vl(oe){for(var ae=0,De=0;De=55296&&He<=57343&&++De,ae+=4}return ae}function yl(oe,ae,De){De=mn(De);var He,tt,z,ne,de;ae===2?(He=Da,tt=Sc,ne=Ja,z=()=>A,de=1):ae===4&&(He=pl,tt=ml,ne=vl,z=()=>G,de=2),Cn(oe,{name:De,fromWireType:function(le){for(var Q=G[le>>2],he=z(),ge,me=le+4,N=0;N<=Q;++N){var k=le+4+N*ae;if(N==Q||he[k>>de]==0){var te=k-me,ve=He(me,te);ge===void 0?ge=ve:(ge+="\0",ge+=ve),me=k+ae}}return Hi(le),ge},toWireType:function(le,Q){typeof Q!="string"&&Lt("Cannot pass non-string to C++ string type "+De);var he=ne(Q),ge=vo(4+he+ae);return G[ge>>2]=he>>de,tt(Q,ge+4,he+ae),le!==null&&le.push(Hi,ge),ge},argPackAdvance:8,readValueFromPointer:nt,destructorFunction:function(le){Hi(le)}})}function wl(oe,ae,De,He,tt,z){dt[oe]={name:mn(ae),rawConstructor:yr(De,He),rawDestructor:yr(tt,z),fields:[]}}function Ds(oe,ae,De,He,tt,z,ne,de,le,Q){dt[oe].fields.push({fieldName:mn(ae),getterReturnType:De,getter:yr(He,tt),getterContext:z,setterArgumentType:ne,setter:yr(de,le),setterContext:Q})}function xl(oe,ae){ae=mn(ae),Cn(oe,{isVoid:!0,name:ae,argPackAdvance:0,fromWireType:function(){},toWireType:function(De,He){}})}var Is={};function Cl(oe){var ae=Is[oe];return ae===void 0?mn(oe):ae}function Os(){return typeof globalThis=="object"?globalThis:function(){return Function}()("return this")()}function Ms(oe){return oe===0?oi.toHandle(Os()):(oe=Cl(oe),oi.toHandle(Os()[oe]))}function Tc(oe){oe>4&&(Vn[oe].refcount+=1)}function Za(oe,ae){var De=ot[oe];return De===void 0&&Lt(ae+" has unknown type "+mi(oe)),De}function Ps(oe){for(var ae="",De=0;DeG,tt="return function emval_allocator_"+oe+`(constructor, argTypes, args) { +`,k.push(me);var Ie=ii(Function,k).apply(null,te);return Ie}function Es(oe,ae,De,He,tt,z){T(ae>0);var ne=mo(ae,De);tt=yr(He,tt),xn([],[oe],function(he){he=he[0];var le="constructor "+he.name;if(he.registeredClass.constructor_body===void 0&&(he.registeredClass.constructor_body=[]),he.registeredClass.constructor_body[ae-1]!==void 0)throw new Fr("Cannot register multiple constructors with identical number of parameters ("+(ae-1)+") for class '"+he.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return he.registeredClass.constructor_body[ae-1]=()=>{Or("Cannot construct "+he.name+" due to unbound types",ne)},xn([],ne,function(Q){return Q.splice(1,0,null),he.registeredClass.constructor_body[ae-1]=ta(le,Q,null,tt,z),[]}),[]})}function Xa(oe,ae,De,He,tt,z,ne,he){var le=mo(De,He);ae=mn(ae),z=yr(tt,z),xn([],[oe],function(Q){Q=Q[0];var de=Q.name+"."+ae;ae.startsWith("@@")&&(ae=Symbol[ae.substring(2)]),he&&Q.registeredClass.pureVirtualFunctions.push(ae);function ge(){Or("Cannot call "+de+" due to unbound types",le)}var me=Q.registeredClass.instancePrototype,N=me[ae];return N===void 0||N.overloadTable===void 0&&N.className!==Q.name&&N.argCount===De-2?(ge.argCount=De-2,ge.className=Q.name,me[ae]=ge):(po(me,ae,de),me[ae].overloadTable[De-2]=ge),xn([],le,function(k){var te=ta(de,k,Q,z,ne);return me[ae].overloadTable===void 0?(te.argCount=De-2,me[ae]=te):me[ae].overloadTable[De-2]=te,[]}),[]})}var Ta=[],Vn=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function _a(oe){oe>4&&--Vn[oe].refcount===0&&(Vn[oe]=void 0,Ta.push(oe))}function Qr(){for(var oe=0,ae=5;ae(oe||Lt("Cannot use deleted val. handle = "+oe),Vn[oe].value),toHandle:oe=>{switch(oe){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var ae=Ta.length?Ta.pop():Vn.length;return Vn[ae]={refcount:1,value:oe},ae}}}};function Ya(oe,ae){ae=mn(ae),Cn(oe,{name:ae,fromWireType:function(De){var He=oi.toValue(De);return _a(De),He},toWireType:function(De,He){return oi.toHandle(He)},argPackAdvance:8,readValueFromPointer:nt,destructorFunction:null})}function Sn(oe){if(oe===null)return"null";var ae=typeof oe;return ae==="object"||ae==="array"||ae==="function"?oe.toString():""+oe}function ji(oe,ae){switch(ae){case 2:return function(De){return this.fromWireType(X[De>>2])};case 3:return function(De){return this.fromWireType(ee[De>>3])};default:throw new TypeError("Unknown float type: "+oe)}}function Ea(oe,ae,De){var He=Ye(De);ae=mn(ae),Cn(oe,{name:ae,fromWireType:function(tt){return tt},toWireType:function(tt,z){return z},argPackAdvance:8,readValueFromPointer:ji(ae,He),destructorFunction:null})}function ba(oe,ae,De,He,tt,z){var ne=mo(ae,De);oe=mn(oe),tt=yr(He,tt),Zr(oe,function(){Or("Cannot call "+oe+" due to unbound types",ne)},ae-1),xn([],ne,function(he){var le=[he[0],null].concat(he.slice(1));return zi(oe,ta(oe,le,null,tt,z),ae-1),[]})}function Oi(oe,ae,De){switch(ae){case 0:return De?function(tt){return L[tt]}:function(tt){return B[tt]};case 1:return De?function(tt){return H[tt>>1]}:function(tt){return A[tt>>1]};case 2:return De?function(tt){return F[tt>>2]}:function(tt){return G[tt>>2]};default:throw new TypeError("Unknown integer type: "+oe)}}function bs(oe,ae,De,He,tt){ae=mn(ae);var z=Ye(De),ne=ge=>ge;if(He===0){var he=32-8*De;ne=ge=>ge<>>he}var le=ae.includes("unsigned"),Q=(ge,me)=>{},de;le?de=function(ge,me){return Q(me,this.name),me>>>0}:de=function(ge,me){return Q(me,this.name),me},Cn(oe,{name:ae,fromWireType:ne,toWireType:de,argPackAdvance:8,readValueFromPointer:Oi(ae,z,He!==0),destructorFunction:null})}function na(oe,ae,De){var He=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],tt=He[ae];function z(ne){ne=ne>>2;var he=G,le=he[ne],Q=he[ne+1];return new tt(O,Q,le)}De=mn(De),Cn(oe,{name:De,fromWireType:z,argPackAdvance:8,readValueFromPointer:z},{ignoreDuplicateRegistrations:!0})}function Cc(oe,ae){ae=mn(ae);var De=ae==="std::string";Cn(oe,{name:ae,fromWireType:function(He){var tt=G[He>>2],z=He+4,ne;if(De)for(var he=z,le=0;le<=tt;++le){var Q=z+le;if(le==tt||B[Q]==0){var de=Q-he,ge=b(he,de);ne===void 0?ne=ge:(ne+="\0",ne+=ge),he=Q+1}}else{for(var me=new Array(tt),le=0;le>2]=z,De&&ne)I(tt,le,z+1);else if(ne)for(var Q=0;Q255&&(Hi(le),Lt("String has UTF-16 code units that do not fit in 8 bits")),B[le+Q]=de}else for(var Q=0;Q>1,tt=He+ae/2;!(He>=tt)&&A[He];)++He;if(De=He<<1,De-oe>32&&Uo)return Uo.decode(B.subarray(oe,De));for(var z="",ne=0;!(ne>=ae/2);++ne){var he=H[oe+ne*2>>1];if(he==0)break;z+=String.fromCharCode(he)}return z}function Sc(oe,ae,De){if(De===void 0&&(De=2147483647),De<2)return 0;De-=2;for(var He=ae,tt=De>1]=ne,ae+=2}return H[ae>>1]=0,ae-He}function Ja(oe){return oe.length*2}function pl(oe,ae){for(var De=0,He="";!(De>=ae/4);){var tt=F[oe+De*4>>2];if(tt==0)break;if(++De,tt>=65536){var z=tt-65536;He+=String.fromCharCode(55296|z>>10,56320|z&1023)}else He+=String.fromCharCode(tt)}return He}function ml(oe,ae,De){if(De===void 0&&(De=2147483647),De<4)return 0;for(var He=ae,tt=He+De-4,z=0;z=55296&&ne<=57343){var he=oe.charCodeAt(++z);ne=65536+((ne&1023)<<10)|he&1023}if(F[ae>>2]=ne,ae+=4,ae+4>tt)break}return F[ae>>2]=0,ae-He}function vl(oe){for(var ae=0,De=0;De=55296&&He<=57343&&++De,ae+=4}return ae}function yl(oe,ae,De){De=mn(De);var He,tt,z,ne,he;ae===2?(He=Da,tt=Sc,ne=Ja,z=()=>A,he=1):ae===4&&(He=pl,tt=ml,ne=vl,z=()=>G,he=2),Cn(oe,{name:De,fromWireType:function(le){for(var Q=G[le>>2],de=z(),ge,me=le+4,N=0;N<=Q;++N){var k=le+4+N*ae;if(N==Q||de[k>>he]==0){var te=k-me,ve=He(me,te);ge===void 0?ge=ve:(ge+="\0",ge+=ve),me=k+ae}}return Hi(le),ge},toWireType:function(le,Q){typeof Q!="string"&&Lt("Cannot pass non-string to C++ string type "+De);var de=ne(Q),ge=vo(4+de+ae);return G[ge>>2]=de>>he,tt(Q,ge+4,de+ae),le!==null&&le.push(Hi,ge),ge},argPackAdvance:8,readValueFromPointer:nt,destructorFunction:function(le){Hi(le)}})}function wl(oe,ae,De,He,tt,z){dt[oe]={name:mn(ae),rawConstructor:yr(De,He),rawDestructor:yr(tt,z),fields:[]}}function Ds(oe,ae,De,He,tt,z,ne,he,le,Q){dt[oe].fields.push({fieldName:mn(ae),getterReturnType:De,getter:yr(He,tt),getterContext:z,setterArgumentType:ne,setter:yr(he,le),setterContext:Q})}function xl(oe,ae){ae=mn(ae),Cn(oe,{isVoid:!0,name:ae,argPackAdvance:0,fromWireType:function(){},toWireType:function(De,He){}})}var Is={};function Cl(oe){var ae=Is[oe];return ae===void 0?mn(oe):ae}function Os(){return typeof globalThis=="object"?globalThis:function(){return Function}()("return this")()}function Ms(oe){return oe===0?oi.toHandle(Os()):(oe=Cl(oe),oi.toHandle(Os()[oe]))}function Tc(oe){oe>4&&(Vn[oe].refcount+=1)}function Za(oe,ae){var De=ot[oe];return De===void 0&&Lt(ae+" has unknown type "+mi(oe)),De}function Ps(oe){for(var ae="",De=0;DeG,tt="return function emval_allocator_"+oe+`(constructor, argTypes, args) { var HEAPU32 = getMemory(); `,De=0;De>2)], 'parameter "+De+`'); var arg`+De+" = argType"+De+`.readValueFromPointer(args); @@ -4241,7 +4241,7 @@ argTypes += 4; `;return tt+="var obj = new constructor("+ae+`); return valueToHandle(obj); } -`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",tt)(Za,o,oi.toHandle,He)}var Rs={};function Qa(oe,ae,De,He){oe=oi.toValue(oe);var tt=Rs[ae];return tt||(tt=Ps(ae),Rs[ae]=tt),tt(oe,De,He)}function _c(oe,ae){oe=Za(oe,"_emval_take_value");var De=oe.readValueFromPointer(ae);return oi.toHandle(De)}function Ls(){Fe("")}function Ec(oe,ae,De){B.copyWithin(oe,ae,ae+De)}function As(){return 2147483648}function bc(oe){try{return C.grow(oe-O.byteLength+65535>>>16),ce(C.buffer),1}catch{}}function Dc(oe){var ae=B.length;oe=oe>>>0;var De=As();if(oe>De)return!1;let He=(le,Q)=>le+(Q-le%Q)%Q;for(var tt=1;tt<=4;tt*=2){var z=ae*(1+.2/tt);z=Math.min(z,oe+100663296);var ne=Math.min(De,He(Math.max(oe,z),65536)),de=bc(ne);if(de)return!0}return!1}function Ic(oe){var ae=o["_"+oe];return ae}function Oc(oe,ae){L.set(oe,ae)}function es(oe,ae,De,He,tt){var z={string:k=>{var te=0;if(k!=null&&k!==0){var ve=(k.length<<2)+1;te=ns(ve),I(k,te,ve)}return te},array:k=>{var te=ns(k.length);return Oc(k,te),te}};function ne(k){return ae==="string"?b(k):ae==="boolean"?!!k:k}var de=Ic(oe),le=[],Q=0;if(He)for(var he=0;he0||(Ge(),J>0))return;function ae(){Ia||(Ia=!0,o.calledRun=!0,!S&&(Ne(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),j()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),ae()},1)):ae()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Fs(),i.ready}})();t.exports=r})(g$);var OEe=g$.exports;const MEe=ll(OEe),PEe=new URL("/static/dv3d/charlswasm_decode.wasm",import.meta.url),M0={codec:void 0,decoder:void 0,decodeConfig:{}};function REe(t){return typeof t=="number"?M0.codec.getExceptionMessage(t):t}function LEe(t){if(M0.decodeConfig=t,M0.codec)return Promise.resolve();const e=MEe({locateFile:r=>r.endsWith(".wasm")?PEe.toString():r});return new Promise((r,n)=>{e.then(i=>{M0.codec=i,M0.decoder=new i.JpegLSDecoder,r()},n)})}async function z7(t,e){try{await LEe();const r=M0.decoder;r.getEncodedBuffer(t.length).set(t),r.decode();const i=r.getFrameInfo(),o=r.getInterleaveMode(),a=r.getNearLossless(),s=r.getDecodedBuffer(),c={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:e.signed,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},l=AEe(i,s,e.signed),f={nearLossless:a,interleaveMode:o,frameInfo:i};return{...e,pixelData:l,imageInfo:c,encodeOptions:f,...f,...c}}catch(r){throw REe(r)}}function AEe(t,e,r){return t.bitsPerSample>8?r?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):r?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var p$={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(N,k){a=N,s=k});var c=Object.assign({},o),l="./this.program",f=typeof window=="object",u=typeof importScripts=="function",d=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",h="";function g(N){return o.locateFile?o.locateFile(N,h):h+N}var p,v,y;if(d){var m=el,w=el;u?h=w.dirname(h)+"/":h=__dirname+"/",p=(N,k)=>(N=Pe(N)?new URL(N):w.normalize(N),m.readFileSync(N,k?void 0:"utf8")),y=N=>{var k=p(N,!0);return k.buffer||(k=new Uint8Array(k)),k},v=(N,k,te)=>{N=Pe(N)?new URL(N):w.normalize(N),m.readFile(N,function(ve,Ie){ve?te(ve):k(Ie.buffer)})},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(N){if(!(N instanceof ft))throw N}),process.on("unhandledRejection",function(N){throw N}),o.inspect=function(){return"[Emscripten Module object]"}}else(f||u)&&(u?h=self.location.href:typeof document<"u"&&document.currentScript&&(h=document.currentScript.src),n&&(h=n),h.indexOf("blob:")!==0?h=h.substr(0,h.replace(/[?#].*/,"").lastIndexOf("/")+1):h="",p=N=>{var k=new XMLHttpRequest;return k.open("GET",N,!1),k.send(null),k.responseText},u&&(y=N=>{var k=new XMLHttpRequest;return k.open("GET",N,!1),k.responseType="arraybuffer",k.send(null),new Uint8Array(k.response)}),v=(N,k,te)=>{var ve=new XMLHttpRequest;ve.open("GET",N,!0),ve.responseType="arraybuffer",ve.onload=()=>{if(ve.status==200||ve.status==0&&ve.response){k(ve.response);return}te()},ve.onerror=te,ve.send(null)});var x=o.print||console.log.bind(console),C=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&(l=o.thisProgram),o.quit&&o.quit;var S;o.wasmBinary&&(S=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&Xe("no native wasm support detected");var T,_=!1;function E(N,k){N||Xe(k)}var b=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function D(N,k,te){for(var ve=k+te,Ie=k;N[Ie]&&!(Ie>=ve);)++Ie;if(Ie-k>16&&N.buffer&&b)return b.decode(N.subarray(k,Ie));for(var ke="";k>10,56320|$&1023)}}return ke}function I(N,k){return N?D(A,N,k):""}function P(N,k,te,ve){if(!(ve>0))return 0;for(var Ie=te,ke=te+ve-1,be=0;be=55296&&Oe<=57343){var W=N.charCodeAt(++be);Oe=65536+((Oe&1023)<<10)|W&1023}if(Oe<=127){if(te>=ke)break;k[te++]=Oe}else if(Oe<=2047){if(te+1>=ke)break;k[te++]=192|Oe>>6,k[te++]=128|Oe&63}else if(Oe<=65535){if(te+2>=ke)break;k[te++]=224|Oe>>12,k[te++]=128|Oe>>6&63,k[te++]=128|Oe&63}else{if(te+3>=ke)break;k[te++]=240|Oe>>18,k[te++]=128|Oe>>12&63,k[te++]=128|Oe>>6&63,k[te++]=128|Oe&63}}return k[te]=0,te-Ie}function O(N,k,te){return P(N,A,k,te)}function L(N){for(var k=0,te=0;te=55296&&ve<=57343?(k+=4,++te):k+=3}return k}var B,H,A,F,G,X,ee,ce,Se;function we(N){B=N,o.HEAP8=H=new Int8Array(N),o.HEAP16=F=new Int16Array(N),o.HEAP32=X=new Int32Array(N),o.HEAPU8=A=new Uint8Array(N),o.HEAPU16=G=new Uint16Array(N),o.HEAPU32=ee=new Uint32Array(N),o.HEAPF32=ce=new Float32Array(N),o.HEAPF64=Se=new Float64Array(N)}o.INITIAL_MEMORY;var _e,Ve=[],Ge=[],Ne=[];function j(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)K(o.preRun.shift());pt(Ve)}function M(){pt(Ge)}function q(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)re(o.postRun.shift());pt(Ne)}function K(N){Ve.unshift(N)}function J(N){Ge.unshift(N)}function re(N){Ne.unshift(N)}var ie=0,Re=null;function Fe(N){ie++,o.monitorRunDependencies&&o.monitorRunDependencies(ie)}function je(N){if(ie--,o.monitorRunDependencies&&o.monitorRunDependencies(ie),ie==0&&Re){var k=Re;Re=null,k()}}function Xe(N){o.onAbort&&o.onAbort(N),N="Aborted("+N+")",C(N),_=!0,N+=". Build with -sASSERTIONS for more info.";var k=new WebAssembly.RuntimeError(N);throw s(k),k}var se="data:application/octet-stream;base64,";function ue(N){return N.startsWith(se)}function Pe(N){return N.startsWith("file://")}var pe;pe="openjpegwasm_decode.wasm",ue(pe)||(pe=g(pe));function Ee(N){try{if(N==pe&&S)return new Uint8Array(S);if(y)return y(N);throw"both async and sync fetching of the wasm failed"}catch(k){Xe(k)}}function Qe(){if(!S&&(f||u)){if(typeof fetch=="function"&&!Pe(pe))return fetch(pe,{credentials:"same-origin"}).then(function(N){if(!N.ok)throw"failed to load wasm binary file at '"+pe+"'";return N.arrayBuffer()}).catch(function(){return Ee(pe)});if(v)return new Promise(function(N,k){v(pe,function(te){N(new Uint8Array(te))},k)})}return Promise.resolve().then(function(){return Ee(pe)})}function fe(){var N={a:He};function k(be,Oe){var W=be.exports;o.asm=W,T=o.asm.E,we(T.buffer),_e=o.asm.G,J(o.asm.F),je()}Fe();function te(be){k(be.instance)}function ve(be){return Qe().then(function(Oe){return WebAssembly.instantiate(Oe,N)}).then(function(Oe){return Oe}).then(be,function(Oe){C("failed to asynchronously prepare wasm: "+Oe),Xe(Oe)})}function Ie(){return!S&&typeof WebAssembly.instantiateStreaming=="function"&&!ue(pe)&&!Pe(pe)&&!d&&typeof fetch=="function"?fetch(pe,{credentials:"same-origin"}).then(function(be){var Oe=WebAssembly.instantiateStreaming(be,N);return Oe.then(te,function(W){return C("wasm streaming compile failed: "+W),C("falling back to ArrayBuffer instantiation"),ve(te)})}):ve(te)}if(o.instantiateWasm)try{var ke=o.instantiateWasm(N,k);return ke}catch(be){C("Module.instantiateWasm callback failed with error: "+be),s(be)}return Ie().catch(s),{}}function ft(N){this.name="ExitStatus",this.message="Program terminated with exit("+N+")",this.status=N}function pt(N){for(;N.length>0;)N.shift()(o)}function dt(N){this.excPtr=N,this.ptr=N-24,this.set_type=function(k){ee[this.ptr+4>>2]=k},this.get_type=function(){return ee[this.ptr+4>>2]},this.set_destructor=function(k){ee[this.ptr+8>>2]=k},this.get_destructor=function(){return ee[this.ptr+8>>2]},this.set_refcount=function(k){X[this.ptr>>2]=k},this.set_caught=function(k){k=k?1:0,H[this.ptr+12>>0]=k},this.get_caught=function(){return H[this.ptr+12>>0]!=0},this.set_rethrown=function(k){k=k?1:0,H[this.ptr+13>>0]=k},this.get_rethrown=function(){return H[this.ptr+13>>0]!=0},this.init=function(k,te){this.set_adjusted_ptr(0),this.set_type(k),this.set_destructor(te),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var k=X[this.ptr>>2];X[this.ptr>>2]=k+1},this.release_ref=function(){var k=X[this.ptr>>2];return X[this.ptr>>2]=k-1,k===1},this.set_adjusted_ptr=function(k){ee[this.ptr+16>>2]=k},this.get_adjusted_ptr=function(){return ee[this.ptr+16>>2]},this.get_exception_ptr=function(){var k=he(this.get_type());if(k)return ee[this.excPtr>>2];var te=this.get_adjusted_ptr();return te!==0?te:this.excPtr}}function Ue(N,k,te){var ve=new dt(N);throw ve.init(k,te),N}var nt={};function at(N){for(;N.length;){var k=N.pop(),te=N.pop();te(k)}}function ot(N){return this.fromWireType(X[N>>2])}var lt={},_t={},vt={},Mt=48,Ft=57;function wn(N){if(N===void 0)return"_unknown";N=N.replace(/[^a-zA-Z0-9_]/g,"$");var k=N.charCodeAt(0);return k>=Mt&&k<=Ft?"_"+N:N}function Dn(N,k){return N=wn(N),new Function("body","return function "+N+`() { +`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",tt)(Za,o,oi.toHandle,He)}var Rs={};function Qa(oe,ae,De,He){oe=oi.toValue(oe);var tt=Rs[ae];return tt||(tt=Ps(ae),Rs[ae]=tt),tt(oe,De,He)}function _c(oe,ae){oe=Za(oe,"_emval_take_value");var De=oe.readValueFromPointer(ae);return oi.toHandle(De)}function Ls(){Fe("")}function Ec(oe,ae,De){B.copyWithin(oe,ae,ae+De)}function As(){return 2147483648}function bc(oe){try{return C.grow(oe-O.byteLength+65535>>>16),ce(C.buffer),1}catch{}}function Dc(oe){var ae=B.length;oe=oe>>>0;var De=As();if(oe>De)return!1;let He=(le,Q)=>le+(Q-le%Q)%Q;for(var tt=1;tt<=4;tt*=2){var z=ae*(1+.2/tt);z=Math.min(z,oe+100663296);var ne=Math.min(De,He(Math.max(oe,z),65536)),he=bc(ne);if(he)return!0}return!1}function Ic(oe){var ae=o["_"+oe];return ae}function Oc(oe,ae){L.set(oe,ae)}function es(oe,ae,De,He,tt){var z={string:k=>{var te=0;if(k!=null&&k!==0){var ve=(k.length<<2)+1;te=ns(ve),I(k,te,ve)}return te},array:k=>{var te=ns(k.length);return Oc(k,te),te}};function ne(k){return ae==="string"?b(k):ae==="boolean"?!!k:k}var he=Ic(oe),le=[],Q=0;if(He)for(var de=0;de0||(Ge(),J>0))return;function ae(){Ia||(Ia=!0,o.calledRun=!0,!S&&(Ne(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),j()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),ae()},1)):ae()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Fs(),i.ready}})();t.exports=r})(g$);var OEe=g$.exports;const MEe=ll(OEe),PEe=new URL("/static/dv3d/charlswasm_decode.wasm",import.meta.url),M0={codec:void 0,decoder:void 0,decodeConfig:{}};function REe(t){return typeof t=="number"?M0.codec.getExceptionMessage(t):t}function LEe(t){if(M0.decodeConfig=t,M0.codec)return Promise.resolve();const e=MEe({locateFile:r=>r.endsWith(".wasm")?PEe.toString():r});return new Promise((r,n)=>{e.then(i=>{M0.codec=i,M0.decoder=new i.JpegLSDecoder,r()},n)})}async function z7(t,e){try{await LEe();const r=M0.decoder;r.getEncodedBuffer(t.length).set(t),r.decode();const i=r.getFrameInfo(),o=r.getInterleaveMode(),a=r.getNearLossless(),s=r.getDecodedBuffer(),c={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:e.signed,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},l=AEe(i,s,e.signed),f={nearLossless:a,interleaveMode:o,frameInfo:i};return{...e,pixelData:l,imageInfo:c,encodeOptions:f,...f,...c}}catch(r){throw REe(r)}}function AEe(t,e,r){return t.bitsPerSample>8?r?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):r?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var p$={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(N,k){a=N,s=k});var c=Object.assign({},o),l="./this.program",f=typeof window=="object",u=typeof importScripts=="function",d=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",h="";function g(N){return o.locateFile?o.locateFile(N,h):h+N}var p,v,y;if(d){var m=el,w=el;u?h=w.dirname(h)+"/":h=__dirname+"/",p=(N,k)=>(N=Pe(N)?new URL(N):w.normalize(N),m.readFileSync(N,k?void 0:"utf8")),y=N=>{var k=p(N,!0);return k.buffer||(k=new Uint8Array(k)),k},v=(N,k,te)=>{N=Pe(N)?new URL(N):w.normalize(N),m.readFile(N,function(ve,Ie){ve?te(ve):k(Ie.buffer)})},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(N){if(!(N instanceof ft))throw N}),process.on("unhandledRejection",function(N){throw N}),o.inspect=function(){return"[Emscripten Module object]"}}else(f||u)&&(u?h=self.location.href:typeof document<"u"&&document.currentScript&&(h=document.currentScript.src),n&&(h=n),h.indexOf("blob:")!==0?h=h.substr(0,h.replace(/[?#].*/,"").lastIndexOf("/")+1):h="",p=N=>{var k=new XMLHttpRequest;return k.open("GET",N,!1),k.send(null),k.responseText},u&&(y=N=>{var k=new XMLHttpRequest;return k.open("GET",N,!1),k.responseType="arraybuffer",k.send(null),new Uint8Array(k.response)}),v=(N,k,te)=>{var ve=new XMLHttpRequest;ve.open("GET",N,!0),ve.responseType="arraybuffer",ve.onload=()=>{if(ve.status==200||ve.status==0&&ve.response){k(ve.response);return}te()},ve.onerror=te,ve.send(null)});var x=o.print||console.log.bind(console),C=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&(l=o.thisProgram),o.quit&&o.quit;var S;o.wasmBinary&&(S=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&Xe("no native wasm support detected");var T,_=!1;function E(N,k){N||Xe(k)}var b=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function D(N,k,te){for(var ve=k+te,Ie=k;N[Ie]&&!(Ie>=ve);)++Ie;if(Ie-k>16&&N.buffer&&b)return b.decode(N.subarray(k,Ie));for(var ke="";k>10,56320|$&1023)}}return ke}function I(N,k){return N?D(A,N,k):""}function P(N,k,te,ve){if(!(ve>0))return 0;for(var Ie=te,ke=te+ve-1,be=0;be=55296&&Oe<=57343){var W=N.charCodeAt(++be);Oe=65536+((Oe&1023)<<10)|W&1023}if(Oe<=127){if(te>=ke)break;k[te++]=Oe}else if(Oe<=2047){if(te+1>=ke)break;k[te++]=192|Oe>>6,k[te++]=128|Oe&63}else if(Oe<=65535){if(te+2>=ke)break;k[te++]=224|Oe>>12,k[te++]=128|Oe>>6&63,k[te++]=128|Oe&63}else{if(te+3>=ke)break;k[te++]=240|Oe>>18,k[te++]=128|Oe>>12&63,k[te++]=128|Oe>>6&63,k[te++]=128|Oe&63}}return k[te]=0,te-Ie}function O(N,k,te){return P(N,A,k,te)}function L(N){for(var k=0,te=0;te=55296&&ve<=57343?(k+=4,++te):k+=3}return k}var B,H,A,F,G,X,ee,ce,Se;function we(N){B=N,o.HEAP8=H=new Int8Array(N),o.HEAP16=F=new Int16Array(N),o.HEAP32=X=new Int32Array(N),o.HEAPU8=A=new Uint8Array(N),o.HEAPU16=G=new Uint16Array(N),o.HEAPU32=ee=new Uint32Array(N),o.HEAPF32=ce=new Float32Array(N),o.HEAPF64=Se=new Float64Array(N)}o.INITIAL_MEMORY;var _e,Ve=[],Ge=[],Ne=[];function j(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)K(o.preRun.shift());pt(Ve)}function M(){pt(Ge)}function q(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)re(o.postRun.shift());pt(Ne)}function K(N){Ve.unshift(N)}function J(N){Ge.unshift(N)}function re(N){Ne.unshift(N)}var ie=0,Re=null;function Fe(N){ie++,o.monitorRunDependencies&&o.monitorRunDependencies(ie)}function je(N){if(ie--,o.monitorRunDependencies&&o.monitorRunDependencies(ie),ie==0&&Re){var k=Re;Re=null,k()}}function Xe(N){o.onAbort&&o.onAbort(N),N="Aborted("+N+")",C(N),_=!0,N+=". Build with -sASSERTIONS for more info.";var k=new WebAssembly.RuntimeError(N);throw s(k),k}var se="data:application/octet-stream;base64,";function ue(N){return N.startsWith(se)}function Pe(N){return N.startsWith("file://")}var pe;pe="openjpegwasm_decode.wasm",ue(pe)||(pe=g(pe));function Ee(N){try{if(N==pe&&S)return new Uint8Array(S);if(y)return y(N);throw"both async and sync fetching of the wasm failed"}catch(k){Xe(k)}}function Qe(){if(!S&&(f||u)){if(typeof fetch=="function"&&!Pe(pe))return fetch(pe,{credentials:"same-origin"}).then(function(N){if(!N.ok)throw"failed to load wasm binary file at '"+pe+"'";return N.arrayBuffer()}).catch(function(){return Ee(pe)});if(v)return new Promise(function(N,k){v(pe,function(te){N(new Uint8Array(te))},k)})}return Promise.resolve().then(function(){return Ee(pe)})}function fe(){var N={a:He};function k(be,Oe){var W=be.exports;o.asm=W,T=o.asm.E,we(T.buffer),_e=o.asm.G,J(o.asm.F),je()}Fe();function te(be){k(be.instance)}function ve(be){return Qe().then(function(Oe){return WebAssembly.instantiate(Oe,N)}).then(function(Oe){return Oe}).then(be,function(Oe){C("failed to asynchronously prepare wasm: "+Oe),Xe(Oe)})}function Ie(){return!S&&typeof WebAssembly.instantiateStreaming=="function"&&!ue(pe)&&!Pe(pe)&&!d&&typeof fetch=="function"?fetch(pe,{credentials:"same-origin"}).then(function(be){var Oe=WebAssembly.instantiateStreaming(be,N);return Oe.then(te,function(W){return C("wasm streaming compile failed: "+W),C("falling back to ArrayBuffer instantiation"),ve(te)})}):ve(te)}if(o.instantiateWasm)try{var ke=o.instantiateWasm(N,k);return ke}catch(be){C("Module.instantiateWasm callback failed with error: "+be),s(be)}return Ie().catch(s),{}}function ft(N){this.name="ExitStatus",this.message="Program terminated with exit("+N+")",this.status=N}function pt(N){for(;N.length>0;)N.shift()(o)}function dt(N){this.excPtr=N,this.ptr=N-24,this.set_type=function(k){ee[this.ptr+4>>2]=k},this.get_type=function(){return ee[this.ptr+4>>2]},this.set_destructor=function(k){ee[this.ptr+8>>2]=k},this.get_destructor=function(){return ee[this.ptr+8>>2]},this.set_refcount=function(k){X[this.ptr>>2]=k},this.set_caught=function(k){k=k?1:0,H[this.ptr+12>>0]=k},this.get_caught=function(){return H[this.ptr+12>>0]!=0},this.set_rethrown=function(k){k=k?1:0,H[this.ptr+13>>0]=k},this.get_rethrown=function(){return H[this.ptr+13>>0]!=0},this.init=function(k,te){this.set_adjusted_ptr(0),this.set_type(k),this.set_destructor(te),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var k=X[this.ptr>>2];X[this.ptr>>2]=k+1},this.release_ref=function(){var k=X[this.ptr>>2];return X[this.ptr>>2]=k-1,k===1},this.set_adjusted_ptr=function(k){ee[this.ptr+16>>2]=k},this.get_adjusted_ptr=function(){return ee[this.ptr+16>>2]},this.get_exception_ptr=function(){var k=de(this.get_type());if(k)return ee[this.excPtr>>2];var te=this.get_adjusted_ptr();return te!==0?te:this.excPtr}}function Ue(N,k,te){var ve=new dt(N);throw ve.init(k,te),N}var nt={};function at(N){for(;N.length;){var k=N.pop(),te=N.pop();te(k)}}function ot(N){return this.fromWireType(X[N>>2])}var lt={},_t={},vt={},Mt=48,Ft=57;function wn(N){if(N===void 0)return"_unknown";N=N.replace(/[^a-zA-Z0-9_]/g,"$");var k=N.charCodeAt(0);return k>=Mt&&k<=Ft?"_"+N:N}function Dn(N,k){return N=wn(N),new Function("body","return function "+N+`() { "use strict"; return body.apply(this, arguments); }; `)(k)}function Nt(N,k){var te=Dn(k,function(ve){this.name=k,this.message=ve;var Ie=new Error(ve).stack;Ie!==void 0&&(this.stack=this.toString()+` @@ -4267,7 +4267,7 @@ argTypes += 4; `;return Ie+="var obj = new constructor("+k+`); return valueToHandle(obj); } -`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",Ie)(Ps,o,Sn.toHandle,ve)}var Qa={};function _c(N,k,te,ve){N=Sn.toValue(N);var Ie=Qa[k];return Ie||(Ie=Rs(k),Qa[k]=Ie),Ie(N,te,ve)}function Ls(N,k){N=Ps(N,"_emval_take_value");var te=N.readValueFromPointer(k);return Sn.toHandle(te)}function Ec(){Xe("")}function As(){return 2147483648}function bc(){return As()}function Dc(N,k,te){A.copyWithin(N,k,k+te)}function Ic(N){try{return T.grow(N-B.byteLength+65535>>>16),we(T.buffer),1}catch{}}function Oc(N){var k=A.length;N=N>>>0;var te=As();if(N>te)return!1;let ve=(W,$)=>W+($-W%$)%$;for(var Ie=1;Ie<=4;Ie*=2){var ke=k*(1+.2/Ie);ke=Math.min(ke,N+100663296);var be=Math.min(te,ve(Math.max(N,ke),65536)),Oe=Ic(be);if(Oe)return!0}return!1}var es={};function ts(){return l||"./this.program"}function vo(){if(!vo.strings){var N=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",k={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:N,_:ts()};for(var te in es)es[te]===void 0?delete k[te]:k[te]=es[te];var ve=[];for(var te in k)ve.push(te+"="+k[te]);vo.strings=ve}return vo.strings}function Bo(N,k,te){for(var ve=0;ve>0]=N.charCodeAt(ve);H[k>>0]=0}function Hi(N,k){var te=0;return vo().forEach(function(ve,Ie){var ke=k+te;ee[N+Ie*4>>2]=ke,Bo(ve,ke),te+=ve.length+1}),0}function Ns(N,k){var te=vo();ee[N>>2]=te.length;var ve=0;return te.forEach(function(Ie){ve+=Ie.length+1}),ee[k>>2]=ve,0}function ks(N){return 52}function ns(N,k,te,ve,Ie){return 70}var Vs=[null,[],[]];function Ia(N,k){var te=Vs[N];k===0||k===10?((N===1?x:C)(D(te,0)),te.length=0):te.push(k)}function Fs(N,k,te,ve){for(var Ie=0,ke=0;ke>2],Oe=ee[k+4>>2];k+=8;for(var W=0;W>2]=Ie,0}function oe(N){var k=o["_"+N];return k}function ae(N,k){H.set(N,k)}function De(N,k,te,ve,Ie){var ke={string:xe=>{var Ce=0;if(xe!=null&&xe!==0){var Te=(xe.length<<2)+1;Ce=Q(Te),O(xe,Ce,Te)}return Ce},array:xe=>{var Ce=Q(xe.length);return ae(xe,Ce),Ce}};function be(xe){return k==="string"?I(xe):k==="boolean"?!!xe:xe}var Oe=oe(N),W=[],$=0;if(ve)for(var R=0;R0||(j(),ie>0))return;function k(){ge||(ge=!0,o.calledRun=!0,!_&&(M(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),q()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),k()},1)):k()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return me(),i.ready}})();t.exports=r})(p$);var NEe=p$.exports;const kEe=ll(NEe),VEe=new URL("/static/dv3d/openjpegwasm_decode.wasm",import.meta.url),ip={codec:void 0,decoder:void 0,decodeConfig:{}};function FEe(t){if(ip.decodeConfig=t,ip.codec)return Promise.resolve();const e=kEe({locateFile:r=>r.endsWith(".wasm")?VEe.toString():r});return new Promise((r,n)=>{e.then(i=>{ip.codec=i,ip.decoder=new i.J2KDecoder,r()},n)})}async function $7(t,e){await FEe();const r=ip.decoder,n=r.getEncodedBuffer(t.length);n.set(t),r.decode();const i=r.getFrameInfo(),o=r.getDecodedBuffer();new Uint8Array(o.length).set(o);const s=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,c=r.getNumDecompositions(),l=r.getNumLayers(),f=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],u=r.getIsReversible(),d=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,h=`${r.getTileSize().width} x ${r.getTileSize().height}`,g=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,p=r.getColorSpace(),v=`${o.length.toLocaleString()} bytes`,y=`${(o.length/n.length).toFixed(2)}:1`,m={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:i.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},w=UEe(i,o),x={imageOffset:s,numDecompositions:c,numLayers:l,progessionOrder:f,reversible:u,blockDimensions:d,tileSize:h,tileOffset:g,colorTransform:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:x,...x,...m}}function UEe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var m$={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(o){o=o||{};var o=typeof o<"u"?o:{},a,s;o.ready=new Promise(function(W,$){a=W,s=$});var c=Object.assign({},o),l=typeof window=="object",f=typeof importScripts=="function",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",d="";function h(W){return o.locateFile?o.locateFile(W,d):d+W}var g,p,v;if(u){var y=el,m=el;f?d=m.dirname(d)+"/":d=__dirname+"/",g=(W,$)=>(W=ue(W)?new URL(W):m.normalize(W),y.readFileSync(W,$?void 0:"utf8")),v=W=>{var $=g(W,!0);return $.buffer||($=new Uint8Array($)),$},p=(W,$,R)=>{W=ue(W)?new URL(W):m.normalize(W),y.readFile(W,function(V,Y){V?R(V):$(Y.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(W){if(!(W instanceof fe))throw W}),process.on("unhandledRejection",function(W){throw W}),o.inspect=function(){return"[Emscripten Module object]"}}else(l||f)&&(f?d=self.location.href:typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),n&&(d=n),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="",g=W=>{var $=new XMLHttpRequest;return $.open("GET",W,!1),$.send(null),$.responseText},f&&(v=W=>{var $=new XMLHttpRequest;return $.open("GET",W,!1),$.responseType="arraybuffer",$.send(null),new Uint8Array($.response)}),p=(W,$,R)=>{var V=new XMLHttpRequest;V.open("GET",W,!0),V.responseType="arraybuffer",V.onload=()=>{if(V.status==200||V.status==0&&V.response){$(V.response);return}R()},V.onerror=R,V.send(null)});var w=o.print||console.log.bind(console),x=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit;var C;o.wasmBinary&&(C=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&je("no native wasm support detected");var S,T=!1;function _(W,$){W||je($)}var E=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function b(W,$,R){for(var V=$+R,Y=$;W[Y]&&!(Y>=V);)++Y;if(Y-$>16&&W.buffer&&E)return E.decode(W.subarray($,Y));for(var ye="";$>10,56320|Me&1023)}}return ye}function D(W,$){return W?b(H,W,$):""}function I(W,$,R,V){if(!(V>0))return 0;for(var Y=R,ye=R+V-1,xe=0;xe=55296&&Ce<=57343){var Te=W.charCodeAt(++xe);Ce=65536+((Ce&1023)<<10)|Te&1023}if(Ce<=127){if(R>=ye)break;$[R++]=Ce}else if(Ce<=2047){if(R+1>=ye)break;$[R++]=192|Ce>>6,$[R++]=128|Ce&63}else if(Ce<=65535){if(R+2>=ye)break;$[R++]=224|Ce>>12,$[R++]=128|Ce>>6&63,$[R++]=128|Ce&63}else{if(R+3>=ye)break;$[R++]=240|Ce>>18,$[R++]=128|Ce>>12&63,$[R++]=128|Ce>>6&63,$[R++]=128|Ce&63}}return $[R]=0,R-Y}function P(W,$,R){return I(W,H,$,R)}function O(W){for(var $=0,R=0;R=55296&&V<=57343?($+=4,++R):$+=3}return $}var L,B,H,A,F,G,X,ee,ce;function Se(W){L=W,o.HEAP8=B=new Int8Array(W),o.HEAP16=A=new Int16Array(W),o.HEAP32=G=new Int32Array(W),o.HEAPU8=H=new Uint8Array(W),o.HEAPU16=F=new Uint16Array(W),o.HEAPU32=X=new Uint32Array(W),o.HEAPF32=ee=new Float32Array(W),o.HEAPF64=ce=new Float64Array(W)}o.INITIAL_MEMORY;var we,_e=[],Ve=[],Ge=[];function Ne(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)q(o.preRun.shift());ft(_e)}function j(){ft(Ve)}function M(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)J(o.postRun.shift());ft(Ge)}function q(W){_e.unshift(W)}function K(W){Ve.unshift(W)}function J(W){Ge.unshift(W)}var re=0,ie=null;function Re(W){re++,o.monitorRunDependencies&&o.monitorRunDependencies(re)}function Fe(W){if(re--,o.monitorRunDependencies&&o.monitorRunDependencies(re),re==0&&ie){var $=ie;ie=null,$()}}function je(W){o.onAbort&&o.onAbort(W),W="Aborted("+W+")",x(W),T=!0,W+=". Build with -sASSERTIONS for more info.";var $=new WebAssembly.RuntimeError(W);throw s($),$}var Xe="data:application/octet-stream;base64,";function se(W){return W.startsWith(Xe)}function ue(W){return W.startsWith("file://")}var Pe;Pe="openjphjs.wasm",se(Pe)||(Pe=h(Pe));function pe(W){try{if(W==Pe&&C)return new Uint8Array(C);if(v)return v(W);throw"both async and sync fetching of the wasm failed"}catch($){je($)}}function Ee(){if(!C&&(l||f)){if(typeof fetch=="function"&&!ue(Pe))return fetch(Pe,{credentials:"same-origin"}).then(function(W){if(!W.ok)throw"failed to load wasm binary file at '"+Pe+"'";return W.arrayBuffer()}).catch(function(){return pe(Pe)});if(p)return new Promise(function(W,$){p(Pe,function(R){W(new Uint8Array(R))},$)})}return Promise.resolve().then(function(){return pe(Pe)})}function Qe(){var W={env:oe,wasi_snapshot_preview1:oe};function $(xe,Ce){var Te=xe.exports;o.asm=Te,S=o.asm.memory,Se(S.buffer),we=o.asm.__indirect_function_table,K(o.asm.__wasm_call_ctors),Fe()}Re();function R(xe){$(xe.instance)}function V(xe){return Ee().then(function(Ce){return WebAssembly.instantiate(Ce,W)}).then(function(Ce){return Ce}).then(xe,function(Ce){x("failed to asynchronously prepare wasm: "+Ce),je(Ce)})}function Y(){return!C&&typeof WebAssembly.instantiateStreaming=="function"&&!se(Pe)&&!ue(Pe)&&!u&&typeof fetch=="function"?fetch(Pe,{credentials:"same-origin"}).then(function(xe){var Ce=WebAssembly.instantiateStreaming(xe,W);return Ce.then(R,function(Te){return x("wasm streaming compile failed: "+Te),x("falling back to ArrayBuffer instantiation"),V(R)})}):V(R)}if(o.instantiateWasm)try{var ye=o.instantiateWasm(W,$);return ye}catch(xe){x("Module.instantiateWasm callback failed with error: "+xe),s(xe)}return Y().catch(s),{}}function fe(W){this.name="ExitStatus",this.message="Program terminated with exit("+W+")",this.status=W}function ft(W){for(;W.length>0;)W.shift()(o)}function pt(W,$,R,V){je("Assertion failed: "+D(W)+", at: "+[$?D($):"unknown filename",R,V?D(V):"unknown function"])}var dt=[];function Ue(W){W.add_ref()}function nt(W){var $=new Mt(W);return $.get_caught()||$.set_caught(!0),$.set_rethrown(!1),dt.push($),Ue($),$.get_exception_ptr()}var at=0,ot=[];function lt(W){var $=ot[W];return $||(W>=ot.length&&(ot.length=W+1),ot[W]=$=we.get(W)),$}function _t(W){if(W.release_ref()&&!W.get_rethrown()){var $=W.get_destructor();$&<($)(W.excPtr),He(W.excPtr)}}function vt(){_setThrew(0);var W=dt.pop();_t(W),at=0}function Mt(W){this.excPtr=W,this.ptr=W-24,this.set_type=function($){X[this.ptr+4>>2]=$},this.get_type=function(){return X[this.ptr+4>>2]},this.set_destructor=function($){X[this.ptr+8>>2]=$},this.get_destructor=function(){return X[this.ptr+8>>2]},this.set_refcount=function($){G[this.ptr>>2]=$},this.set_caught=function($){$=$?1:0,B[this.ptr+12>>0]=$},this.get_caught=function(){return B[this.ptr+12>>0]!=0},this.set_rethrown=function($){$=$?1:0,B[this.ptr+13>>0]=$},this.get_rethrown=function(){return B[this.ptr+13>>0]!=0},this.init=function($,R){this.set_adjusted_ptr(0),this.set_type($),this.set_destructor(R),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var $=G[this.ptr>>2];G[this.ptr>>2]=$+1},this.release_ref=function(){var $=G[this.ptr>>2];return G[this.ptr>>2]=$-1,$===1},this.set_adjusted_ptr=function($){X[this.ptr+16>>2]=$},this.get_adjusted_ptr=function(){return X[this.ptr+16>>2]},this.get_exception_ptr=function(){var $=he(this.get_type());if($)return X[this.excPtr>>2];var R=this.get_adjusted_ptr();return R!==0?R:this.excPtr}}function Ft(W){throw at||(at=W),W}function wn(){var W=at;if(!W)return z(0),0;var $=new Mt(W);$.set_adjusted_ptr(W);var R=$.get_type();if(!R)return z(0),W;for(var V=0;V>2])}var Ye={},ut={},Rt={},mn=48,Fr=57;function Lt(W){if(W===void 0)return"_unknown";W=W.replace(/[^a-zA-Z0-9_]/g,"$");var $=W.charCodeAt(0);return $>=mn&&$<=Fr?"_"+W:W}function Cn(W,$){return W=Lt(W),new Function("body","return function "+W+`() { +`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",Ie)(Ps,o,Sn.toHandle,ve)}var Qa={};function _c(N,k,te,ve){N=Sn.toValue(N);var Ie=Qa[k];return Ie||(Ie=Rs(k),Qa[k]=Ie),Ie(N,te,ve)}function Ls(N,k){N=Ps(N,"_emval_take_value");var te=N.readValueFromPointer(k);return Sn.toHandle(te)}function Ec(){Xe("")}function As(){return 2147483648}function bc(){return As()}function Dc(N,k,te){A.copyWithin(N,k,k+te)}function Ic(N){try{return T.grow(N-B.byteLength+65535>>>16),we(T.buffer),1}catch{}}function Oc(N){var k=A.length;N=N>>>0;var te=As();if(N>te)return!1;let ve=(W,$)=>W+($-W%$)%$;for(var Ie=1;Ie<=4;Ie*=2){var ke=k*(1+.2/Ie);ke=Math.min(ke,N+100663296);var be=Math.min(te,ve(Math.max(N,ke),65536)),Oe=Ic(be);if(Oe)return!0}return!1}var es={};function ts(){return l||"./this.program"}function vo(){if(!vo.strings){var N=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",k={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:N,_:ts()};for(var te in es)es[te]===void 0?delete k[te]:k[te]=es[te];var ve=[];for(var te in k)ve.push(te+"="+k[te]);vo.strings=ve}return vo.strings}function Bo(N,k,te){for(var ve=0;ve>0]=N.charCodeAt(ve);H[k>>0]=0}function Hi(N,k){var te=0;return vo().forEach(function(ve,Ie){var ke=k+te;ee[N+Ie*4>>2]=ke,Bo(ve,ke),te+=ve.length+1}),0}function Ns(N,k){var te=vo();ee[N>>2]=te.length;var ve=0;return te.forEach(function(Ie){ve+=Ie.length+1}),ee[k>>2]=ve,0}function ks(N){return 52}function ns(N,k,te,ve,Ie){return 70}var Vs=[null,[],[]];function Ia(N,k){var te=Vs[N];k===0||k===10?((N===1?x:C)(D(te,0)),te.length=0):te.push(k)}function Fs(N,k,te,ve){for(var Ie=0,ke=0;ke>2],Oe=ee[k+4>>2];k+=8;for(var W=0;W>2]=Ie,0}function oe(N){var k=o["_"+N];return k}function ae(N,k){H.set(N,k)}function De(N,k,te,ve,Ie){var ke={string:xe=>{var Ce=0;if(xe!=null&&xe!==0){var Te=(xe.length<<2)+1;Ce=Q(Te),O(xe,Ce,Te)}return Ce},array:xe=>{var Ce=Q(xe.length);return ae(xe,Ce),Ce}};function be(xe){return k==="string"?I(xe):k==="boolean"?!!xe:xe}var Oe=oe(N),W=[],$=0;if(ve)for(var R=0;R0||(j(),ie>0))return;function k(){ge||(ge=!0,o.calledRun=!0,!_&&(M(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),q()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),k()},1)):k()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return me(),i.ready}})();t.exports=r})(p$);var NEe=p$.exports;const kEe=ll(NEe),VEe=new URL("/static/dv3d/openjpegwasm_decode.wasm",import.meta.url),ip={codec:void 0,decoder:void 0,decodeConfig:{}};function FEe(t){if(ip.decodeConfig=t,ip.codec)return Promise.resolve();const e=kEe({locateFile:r=>r.endsWith(".wasm")?VEe.toString():r});return new Promise((r,n)=>{e.then(i=>{ip.codec=i,ip.decoder=new i.J2KDecoder,r()},n)})}async function $7(t,e){await FEe();const r=ip.decoder,n=r.getEncodedBuffer(t.length);n.set(t),r.decode();const i=r.getFrameInfo(),o=r.getDecodedBuffer();new Uint8Array(o.length).set(o);const s=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,c=r.getNumDecompositions(),l=r.getNumLayers(),f=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],u=r.getIsReversible(),d=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,h=`${r.getTileSize().width} x ${r.getTileSize().height}`,g=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,p=r.getColorSpace(),v=`${o.length.toLocaleString()} bytes`,y=`${(o.length/n.length).toFixed(2)}:1`,m={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:i.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},w=UEe(i,o),x={imageOffset:s,numDecompositions:c,numLayers:l,progessionOrder:f,reversible:u,blockDimensions:d,tileSize:h,tileOffset:g,colorTransform:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:x,...x,...m}}function UEe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var m$={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(o){o=o||{};var o=typeof o<"u"?o:{},a,s;o.ready=new Promise(function(W,$){a=W,s=$});var c=Object.assign({},o),l=typeof window=="object",f=typeof importScripts=="function",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",d="";function h(W){return o.locateFile?o.locateFile(W,d):d+W}var g,p,v;if(u){var y=el,m=el;f?d=m.dirname(d)+"/":d=__dirname+"/",g=(W,$)=>(W=ue(W)?new URL(W):m.normalize(W),y.readFileSync(W,$?void 0:"utf8")),v=W=>{var $=g(W,!0);return $.buffer||($=new Uint8Array($)),$},p=(W,$,R)=>{W=ue(W)?new URL(W):m.normalize(W),y.readFile(W,function(V,Y){V?R(V):$(Y.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(W){if(!(W instanceof fe))throw W}),process.on("unhandledRejection",function(W){throw W}),o.inspect=function(){return"[Emscripten Module object]"}}else(l||f)&&(f?d=self.location.href:typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),n&&(d=n),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="",g=W=>{var $=new XMLHttpRequest;return $.open("GET",W,!1),$.send(null),$.responseText},f&&(v=W=>{var $=new XMLHttpRequest;return $.open("GET",W,!1),$.responseType="arraybuffer",$.send(null),new Uint8Array($.response)}),p=(W,$,R)=>{var V=new XMLHttpRequest;V.open("GET",W,!0),V.responseType="arraybuffer",V.onload=()=>{if(V.status==200||V.status==0&&V.response){$(V.response);return}R()},V.onerror=R,V.send(null)});var w=o.print||console.log.bind(console),x=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit;var C;o.wasmBinary&&(C=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&je("no native wasm support detected");var S,T=!1;function _(W,$){W||je($)}var E=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function b(W,$,R){for(var V=$+R,Y=$;W[Y]&&!(Y>=V);)++Y;if(Y-$>16&&W.buffer&&E)return E.decode(W.subarray($,Y));for(var ye="";$>10,56320|Me&1023)}}return ye}function D(W,$){return W?b(H,W,$):""}function I(W,$,R,V){if(!(V>0))return 0;for(var Y=R,ye=R+V-1,xe=0;xe=55296&&Ce<=57343){var Te=W.charCodeAt(++xe);Ce=65536+((Ce&1023)<<10)|Te&1023}if(Ce<=127){if(R>=ye)break;$[R++]=Ce}else if(Ce<=2047){if(R+1>=ye)break;$[R++]=192|Ce>>6,$[R++]=128|Ce&63}else if(Ce<=65535){if(R+2>=ye)break;$[R++]=224|Ce>>12,$[R++]=128|Ce>>6&63,$[R++]=128|Ce&63}else{if(R+3>=ye)break;$[R++]=240|Ce>>18,$[R++]=128|Ce>>12&63,$[R++]=128|Ce>>6&63,$[R++]=128|Ce&63}}return $[R]=0,R-Y}function P(W,$,R){return I(W,H,$,R)}function O(W){for(var $=0,R=0;R=55296&&V<=57343?($+=4,++R):$+=3}return $}var L,B,H,A,F,G,X,ee,ce;function Se(W){L=W,o.HEAP8=B=new Int8Array(W),o.HEAP16=A=new Int16Array(W),o.HEAP32=G=new Int32Array(W),o.HEAPU8=H=new Uint8Array(W),o.HEAPU16=F=new Uint16Array(W),o.HEAPU32=X=new Uint32Array(W),o.HEAPF32=ee=new Float32Array(W),o.HEAPF64=ce=new Float64Array(W)}o.INITIAL_MEMORY;var we,_e=[],Ve=[],Ge=[];function Ne(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)q(o.preRun.shift());ft(_e)}function j(){ft(Ve)}function M(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)J(o.postRun.shift());ft(Ge)}function q(W){_e.unshift(W)}function K(W){Ve.unshift(W)}function J(W){Ge.unshift(W)}var re=0,ie=null;function Re(W){re++,o.monitorRunDependencies&&o.monitorRunDependencies(re)}function Fe(W){if(re--,o.monitorRunDependencies&&o.monitorRunDependencies(re),re==0&&ie){var $=ie;ie=null,$()}}function je(W){o.onAbort&&o.onAbort(W),W="Aborted("+W+")",x(W),T=!0,W+=". Build with -sASSERTIONS for more info.";var $=new WebAssembly.RuntimeError(W);throw s($),$}var Xe="data:application/octet-stream;base64,";function se(W){return W.startsWith(Xe)}function ue(W){return W.startsWith("file://")}var Pe;Pe="openjphjs.wasm",se(Pe)||(Pe=h(Pe));function pe(W){try{if(W==Pe&&C)return new Uint8Array(C);if(v)return v(W);throw"both async and sync fetching of the wasm failed"}catch($){je($)}}function Ee(){if(!C&&(l||f)){if(typeof fetch=="function"&&!ue(Pe))return fetch(Pe,{credentials:"same-origin"}).then(function(W){if(!W.ok)throw"failed to load wasm binary file at '"+Pe+"'";return W.arrayBuffer()}).catch(function(){return pe(Pe)});if(p)return new Promise(function(W,$){p(Pe,function(R){W(new Uint8Array(R))},$)})}return Promise.resolve().then(function(){return pe(Pe)})}function Qe(){var W={env:oe,wasi_snapshot_preview1:oe};function $(xe,Ce){var Te=xe.exports;o.asm=Te,S=o.asm.memory,Se(S.buffer),we=o.asm.__indirect_function_table,K(o.asm.__wasm_call_ctors),Fe()}Re();function R(xe){$(xe.instance)}function V(xe){return Ee().then(function(Ce){return WebAssembly.instantiate(Ce,W)}).then(function(Ce){return Ce}).then(xe,function(Ce){x("failed to asynchronously prepare wasm: "+Ce),je(Ce)})}function Y(){return!C&&typeof WebAssembly.instantiateStreaming=="function"&&!se(Pe)&&!ue(Pe)&&!u&&typeof fetch=="function"?fetch(Pe,{credentials:"same-origin"}).then(function(xe){var Ce=WebAssembly.instantiateStreaming(xe,W);return Ce.then(R,function(Te){return x("wasm streaming compile failed: "+Te),x("falling back to ArrayBuffer instantiation"),V(R)})}):V(R)}if(o.instantiateWasm)try{var ye=o.instantiateWasm(W,$);return ye}catch(xe){x("Module.instantiateWasm callback failed with error: "+xe),s(xe)}return Y().catch(s),{}}function fe(W){this.name="ExitStatus",this.message="Program terminated with exit("+W+")",this.status=W}function ft(W){for(;W.length>0;)W.shift()(o)}function pt(W,$,R,V){je("Assertion failed: "+D(W)+", at: "+[$?D($):"unknown filename",R,V?D(V):"unknown function"])}var dt=[];function Ue(W){W.add_ref()}function nt(W){var $=new Mt(W);return $.get_caught()||$.set_caught(!0),$.set_rethrown(!1),dt.push($),Ue($),$.get_exception_ptr()}var at=0,ot=[];function lt(W){var $=ot[W];return $||(W>=ot.length&&(ot.length=W+1),ot[W]=$=we.get(W)),$}function _t(W){if(W.release_ref()&&!W.get_rethrown()){var $=W.get_destructor();$&<($)(W.excPtr),He(W.excPtr)}}function vt(){_setThrew(0);var W=dt.pop();_t(W),at=0}function Mt(W){this.excPtr=W,this.ptr=W-24,this.set_type=function($){X[this.ptr+4>>2]=$},this.get_type=function(){return X[this.ptr+4>>2]},this.set_destructor=function($){X[this.ptr+8>>2]=$},this.get_destructor=function(){return X[this.ptr+8>>2]},this.set_refcount=function($){G[this.ptr>>2]=$},this.set_caught=function($){$=$?1:0,B[this.ptr+12>>0]=$},this.get_caught=function(){return B[this.ptr+12>>0]!=0},this.set_rethrown=function($){$=$?1:0,B[this.ptr+13>>0]=$},this.get_rethrown=function(){return B[this.ptr+13>>0]!=0},this.init=function($,R){this.set_adjusted_ptr(0),this.set_type($),this.set_destructor(R),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var $=G[this.ptr>>2];G[this.ptr>>2]=$+1},this.release_ref=function(){var $=G[this.ptr>>2];return G[this.ptr>>2]=$-1,$===1},this.set_adjusted_ptr=function($){X[this.ptr+16>>2]=$},this.get_adjusted_ptr=function(){return X[this.ptr+16>>2]},this.get_exception_ptr=function(){var $=de(this.get_type());if($)return X[this.excPtr>>2];var R=this.get_adjusted_ptr();return R!==0?R:this.excPtr}}function Ft(W){throw at||(at=W),W}function wn(){var W=at;if(!W)return z(0),0;var $=new Mt(W);$.set_adjusted_ptr(W);var R=$.get_type();if(!R)return z(0),W;for(var V=0;V>2])}var Ye={},ut={},Rt={},mn=48,Fr=57;function Lt(W){if(W===void 0)return"_unknown";W=W.replace(/[^a-zA-Z0-9_]/g,"$");var $=W.charCodeAt(0);return $>=mn&&$<=Fr?"_"+W:W}function Cn(W,$){return W=Lt(W),new Function("body","return function "+W+`() { "use strict"; return body.apply(this, arguments); }; `)($)}function Yt(W,$){var R=Cn($,function(V){this.name=$,this.message=V;var Y=new Error(V).stack;Y!==void 0&&(this.stack=this.toString()+` @@ -4284,4 +4284,4 @@ throwBindingError('function `+W+" called with ' + arguments.length + ' arguments `,ht.push(Ut+"_dtor"),zt.push($[Te].destructorFunction))}Me&&(rt+=`var ret = retType.fromWireType(rv); return ret; `),rt+=`} -`,ht.push(rt);var Gn=Ya(Function,ht).apply(null,zt);return Gn}function ji(W,$,R,V,Y,ye){_($>0);var xe=oi($,R);Y=Vn(V,Y),Bi([],[W],function(Ce){Ce=Ce[0];var Te="constructor "+Ce.name;if(Ce.registeredClass.constructor_body===void 0&&(Ce.registeredClass.constructor_body=[]),Ce.registeredClass.constructor_body[$-1]!==void 0)throw new Ct("Cannot register multiple constructors with identical number of parameters ("+($-1)+") for class '"+Ce.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return Ce.registeredClass.constructor_body[$-1]=()=>{Mr("Cannot construct "+Ce.name+" due to unbound types",xe)},Bi([],xe,function(Me){return Me.splice(1,0,null),Ce.registeredClass.constructor_body[$-1]=Sn(Te,Me,null,Y,ye),[]}),[]})}function Ea(W,$,R,V,Y,ye,xe,Ce){var Te=oi(R,V);$=Bn($),ye=Vn(Y,ye),Bi([],[W],function(Me){Me=Me[0];var Ae=Me.name+"."+$;$.startsWith("@@")&&($=Symbol[$.substring(2)]),Ce&&Me.registeredClass.pureVirtualFunctions.push($);function qe(){Mr("Cannot call "+Ae+" due to unbound types",Te)}var rt=Me.registeredClass.instancePrototype,mt=rt[$];return mt===void 0||mt.overloadTable===void 0&&mt.className!==Me.name&&mt.argCount===R-2?(qe.argCount=R-2,qe.className=Me.name,rt[$]=qe):($i(rt,$,Ae),rt[$].overloadTable[R-2]=qe),Bi([],Te,function(ht){var zt=Sn(Ae,ht,Me,ye,xe);return rt[$].overloadTable===void 0?(zt.argCount=R-2,rt[$]=zt):rt[$].overloadTable[R-2]=zt,[]}),[]})}var ba=[],Oi=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function bs(W){W>4&&--Oi[W].refcount===0&&(Oi[W]=void 0,ba.push(W))}function na(){for(var W=0,$=5;$(W||Zt("Cannot use deleted val. handle = "+W),Oi[W].value),toHandle:W=>{switch(W){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var $=ba.length?ba.pop():Oi.length;return Oi[$]={refcount:1,value:W},$}}}};function Sc(W,$){$=Bn($),ar(W,{name:$,fromWireType:function(R){var V=Da.toValue(R);return bs(R),V},toWireType:function(R,V){return Da.toHandle(V)},argPackAdvance:8,readValueFromPointer:br,destructorFunction:null})}function Ja(W){if(W===null)return"null";var $=typeof W;return $==="object"||$==="array"||$==="function"?W.toString():""+W}function pl(W,$){switch($){case 2:return function(R){return this.fromWireType(ee[R>>2])};case 3:return function(R){return this.fromWireType(ce[R>>3])};default:throw new TypeError("Unknown float type: "+W)}}function ml(W,$,R){var V=fo(R);$=Bn($),ar(W,{name:$,fromWireType:function(Y){return Y},toWireType:function(Y,ye){return ye},argPackAdvance:8,readValueFromPointer:pl($,V),destructorFunction:null})}function vl(W,$,R,V,Y,ye){var xe=oi($,R);W=Bn(W),Y=Vn(V,Y),Ir(W,function(){Mr("Cannot call "+W+" due to unbound types",xe)},$-1),Bi([],xe,function(Ce){var Te=[Ce[0],null].concat(Ce.slice(1));return ta(W,Sn(W,Te,null,Y,ye),$-1),[]})}function yl(W,$,R){switch($){case 0:return R?function(Y){return B[Y]}:function(Y){return H[Y]};case 1:return R?function(Y){return A[Y>>1]}:function(Y){return F[Y>>1]};case 2:return R?function(Y){return G[Y>>2]}:function(Y){return X[Y>>2]};default:throw new TypeError("Unknown integer type: "+W)}}function wl(W,$,R,V,Y){$=Bn($);var ye=fo(R),xe=qe=>qe;if(V===0){var Ce=32-8*R;xe=qe=>qe<>>Ce}var Te=$.includes("unsigned"),Me=(qe,rt)=>{},Ae;Te?Ae=function(qe,rt){return Me(rt,this.name),rt>>>0}:Ae=function(qe,rt){return Me(rt,this.name),rt},ar(W,{name:$,fromWireType:xe,toWireType:Ae,argPackAdvance:8,readValueFromPointer:yl($,ye,V!==0),destructorFunction:null})}function Ds(W,$,R){var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Y=V[$];function ye(xe){xe=xe>>2;var Ce=X,Te=Ce[xe],Me=Ce[xe+1];return new Y(L,Me,Te)}R=Bn(R),ar(W,{name:R,fromWireType:ye,argPackAdvance:8,readValueFromPointer:ye},{ignoreDuplicateRegistrations:!0})}function xl(W,$){$=Bn($);var R=$==="std::string";ar(W,{name:$,fromWireType:function(V){var Y=X[V>>2],ye=V+4,xe;if(R)for(var Ce=ye,Te=0;Te<=Y;++Te){var Me=ye+Te;if(Te==Y||H[Me]==0){var Ae=Me-Ce,qe=D(Ce,Ae);xe===void 0?xe=qe:(xe+="\0",xe+=qe),Ce=Me+1}}else{for(var rt=new Array(Y),Te=0;Te>2]=ye,R&&xe)P(Y,Te,ye+1);else if(xe)for(var Me=0;Me255&&(De(Te),Zt("String has UTF-16 code units that do not fit in 8 bits")),H[Te+Me]=Ae}else for(var Me=0;Me>1,Y=V+$/2;!(V>=Y)&&F[V];)++V;if(R=V<<1,R-W>32&&Is)return Is.decode(H.subarray(W,R));for(var ye="",xe=0;!(xe>=$/2);++xe){var Ce=A[W+xe*2>>1];if(Ce==0)break;ye+=String.fromCharCode(Ce)}return ye}function Os(W,$,R){if(R===void 0&&(R=2147483647),R<2)return 0;R-=2;for(var V=$,Y=R>1]=xe,$+=2}return A[$>>1]=0,$-V}function Ms(W){return W.length*2}function Tc(W,$){for(var R=0,V="";!(R>=$/4);){var Y=G[W+R*4>>2];if(Y==0)break;if(++R,Y>=65536){var ye=Y-65536;V+=String.fromCharCode(55296|ye>>10,56320|ye&1023)}else V+=String.fromCharCode(Y)}return V}function Za(W,$,R){if(R===void 0&&(R=2147483647),R<4)return 0;for(var V=$,Y=V+R-4,ye=0;ye=55296&&xe<=57343){var Ce=W.charCodeAt(++ye);xe=65536+((xe&1023)<<10)|Ce&1023}if(G[$>>2]=xe,$+=4,$+4>Y)break}return G[$>>2]=0,$-V}function Ps(W){for(var $=0,R=0;R=55296&&V<=57343&&++R,$+=4}return $}function Rs(W,$,R){R=Bn(R);var V,Y,ye,xe,Ce;$===2?(V=Cl,Y=Os,xe=Ms,ye=()=>F,Ce=1):$===4&&(V=Tc,Y=Za,xe=Ps,ye=()=>X,Ce=2),ar(W,{name:R,fromWireType:function(Te){for(var Me=X[Te>>2],Ae=ye(),qe,rt=Te+4,mt=0;mt<=Me;++mt){var ht=Te+4+mt*$;if(mt==Me||Ae[ht>>Ce]==0){var zt=ht-rt,Ut=V(rt,zt);qe===void 0?qe=Ut:(qe+="\0",qe+=Ut),rt=ht+$}}return De(Te),qe},toWireType:function(Te,Me){typeof Me!="string"&&Zt("Cannot pass non-string to C++ string type "+R);var Ae=xe(Me),qe=ae(4+Ae+$);return X[qe>>2]=Ae>>Ce,Y(Me,qe+4,Ae+$),Te!==null&&Te.push(De,qe),qe},argPackAdvance:8,readValueFromPointer:br,destructorFunction:function(Te){De(Te)}})}function Qa(W,$,R,V,Y,ye){xn[W]={name:Bn($),rawConstructor:Vn(R,V),rawDestructor:Vn(Y,ye),fields:[]}}function _c(W,$,R,V,Y,ye,xe,Ce,Te,Me){xn[W].fields.push({fieldName:Bn($),getterReturnType:R,getter:Vn(V,Y),getterContext:ye,setterArgumentType:xe,setter:Vn(Ce,Te),setterContext:Me})}function Ls(W,$){$=Bn($),ar(W,{isVoid:!0,name:$,argPackAdvance:0,fromWireType:function(){},toWireType:function(R,V){}})}function Ec(W){W>4&&(Oi[W].refcount+=1)}function As(W,$){var R=ut[W];return R===void 0&&Zt($+" has unknown type "+Qr(W)),R}function bc(W,$){W=As(W,"_emval_take_value");var R=W.readValueFromPointer($);return Da.toHandle(R)}function Dc(){je("")}function Ic(W,$,R){H.copyWithin(W,$,$+R)}function Oc(){return 2147483648}function es(W){try{return S.grow(W-L.byteLength+65535>>>16),Se(S.buffer),1}catch{}}function ts(W){var $=H.length;W=W>>>0;var R=Oc();if(W>R)return!1;let V=(Te,Me)=>Te+(Me-Te%Me)%Me;for(var Y=1;Y<=4;Y*=2){var ye=$*(1+.2/Y);ye=Math.min(ye,W+100663296);var xe=Math.min(R,V(Math.max(W,ye),65536)),Ce=es(xe);if(Ce)return!0}return!1}function vo(W){return 52}function Bo(W,$,R,V,Y){return 70}var Hi=[null,[],[]];function Ns(W,$){var R=Hi[W];$===0||$===10?((W===1?w:x)(b(R,0)),R.length=0):R.push($)}function ks(W,$,R,V){for(var Y=0,ye=0;ye>2],Ce=X[$+4>>2];$+=8;for(var Te=0;Te>2]=Y,0}function ns(W){return W}function Vs(W){var $=o["_"+W];return $}function Ia(W,$){B.set(W,$)}function Fs(W,$,R,V,Y){var ye={string:ht=>{var zt=0;if(ht!=null&&ht!==0){var Ut=(ht.length<<2)+1;zt=le(Ut),P(ht,zt,Ut)}return zt},array:ht=>{var zt=le(ht.length);return Ia(ht,zt),zt}};function xe(ht){return $==="string"?D(ht):$==="boolean"?!!ht:ht}var Ce=Vs(W),Te=[],Me=0;if(V)for(var Ae=0;Ae0||(Ne(),re>0))return;function $(){be||(be=!0,o.calledRun=!0,!T&&(j(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),M()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),$()},1)):$()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Oe(),o.ready}})();t.exports=r})(m$);var BEe=m$.exports;const GEe=ll(BEe),WEe=new URL("/static/dv3d/openjphjs.wasm",import.meta.url),op={codec:void 0,decoder:void 0,decodeConfig:{}};function zEe(t,e,r){const n={width:e,height:r};for(;t>0;)n.width=Math.ceil(n.width/2),n.height=Math.ceil(n.height/2),t--;return n}function $Ee(t){if(op.decodeConfig=t,op.codec)return Promise.resolve();const e=GEe({locateFile:r=>r.endsWith(".wasm")?WEe.toString():r});return new Promise((r,n)=>{e.then(i=>{op.codec=i,op.decoder=new i.HTJ2KDecoder,r()},n)})}async function jEe(t,e){await $Ee();const r=new op.codec.HTJ2KDecoder,n=r.getEncodedBuffer(t.length);n.set(t);const i=e.decodeLevel||0;r.decodeSubResolution(i);const o=r.getFrameInfo();if(e.decodeLevel>0){const{width:E,height:b}=zEe(e.decodeLevel,o.width,o.height);o.width=E,o.height=b}const a=r.getDecodedBuffer();new Uint8Array(a.length).set(a);const c=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,l=r.getNumDecompositions(),f=r.getNumLayers(),u=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],d=r.getIsReversible(),h=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,g=`${r.getTileSize().width} x ${r.getTileSize().height}`,p=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,v=`${a.length.toLocaleString()} bytes`,y=`${(a.length/n.length).toFixed(2)}:1`,m={columns:o.width,rows:o.height,bitsPerPixel:o.bitsPerSample,signed:o.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:o.componentCount};let w=HEe(o,a);const{buffer:x,byteOffset:C,byteLength:S}=w,T=x.slice(C,C+S);w=new w.constructor(T);const _={imageOffset:c,numDecompositions:l,numLayers:f,progessionOrder:u,reversible:d,blockDimensions:h,tileSize:g,tileOffset:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:_,..._,...m}}function HEe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function KEe(t,e){const r=t.length,{rescaleSlope:n,rescaleIntercept:i,suvbw:o,doseGridScaling:a}=e;if(e.modality==="PT"&&typeof o=="number"&&!isNaN(o))for(let s=0;s>o;let a=t.pixelData;t.pixelDataLength=t.pixelData.length;const{min:s,max:c}=ax(t.pixelData),l=typeof e.allowFloatRendering<"u"?e.allowFloatRendering:!0;let f=q8(t.photometricInterpretation)&&((m=e.targetBuffer)==null?void 0:m.offset)===void 0;const d=((w=e.preScale)==null?void 0:w.enabled)&&Object.values(e.preScale.scalingParameters).some(C=>typeof C=="number"&&!Number.isInteger(C)),h=!e.preScale.enabled||!l&&d,g=(x=e.targetBuffer)==null?void 0:x.type;if(g&&e.preScale.enabled&&!h){const C=e.preScale.scalingParameters,S=PT(s,c,C);f=!D4e(S.min,S.max,j7[g])}g&&!f?a=JEe(e,t,j7,a):e.preScale.enabled&&!h?a=ZEe(e,s,c,t):a=v$(s,c,t);let p=s,v=c;if(e.preScale.enabled&&!h){const C=e.preScale.scalingParameters;if(y$(C),YEe(C)){KEe(a,C),t.preScale={...e.preScale,scaled:!0};const T=PT(s,c,C);p=T.min,v=T.max}}else h&&(t.preScale={enabled:!0,scaled:!1},p=s,v=c);t.pixelData=a,t.smallestPixelValue=p,t.largestPixelValue=v;const y=new Date().getTime();return t.decodeTimeInMS=y-r,t}function YEe(t){const{rescaleSlope:e,rescaleIntercept:r,modality:n,doseGridScaling:i,suvbw:o}=t;return typeof e=="number"&&typeof r=="number"||n==="RTDOSE"&&typeof i=="number"||n==="PT"&&typeof o=="number"}function JEe(t,e,r,n){const{arrayBuffer:i,type:o,offset:a=0,length:s,rows:c}=t.targetBuffer,l=r[o];if(!l)throw new Error(`target array ${o} is not supported, or doesn't exist.`);c&&c!=e.rows&&e8e(e,t.targetBuffer,l);const f=e.pixelDataLength,u=a,d=s??f-u,h=e.pixelData;if(d!==h.length)throw new Error(`target array for image does not have the same length (${d}) as the decoded image length (${h.length}).`);const g=i?new l(i,u,d):new l(d);return g.set(h,0),n=g,n}function ZEe(t,e,r,n){const i=t.preScale.scalingParameters;y$(i);const o=PT(e,r,i);return v$(o.min,o.max,n)}function v$(t,e,r){const n=X8(t,e),i=new n(r.pixelData.length);return i.set(r.pixelData,0),i}function PT(t,e,r){const{rescaleSlope:n,rescaleIntercept:i,modality:o,doseGridScaling:a,suvbw:s}=r;return o==="PT"&&typeof s=="number"&&!isNaN(s)?{min:s*(t*n+i),max:s*(e*n+i)}:o==="RTDOSE"&&typeof a=="number"&&!isNaN(a)?{min:t*a,max:e*a}:typeof n=="number"&&typeof i=="number"?{min:n*t+i,max:n*e+i}:{min:t,max:e}}function y$(t){if(!t)throw new Error("options.preScale.scalingParameters must be defined if preScale.enabled is true, and scalingParameters cannot be derived from the metadata providers.")}function QEe(t,e,r){const{samplesPerPixel:n}=t,{rows:i,columns:o}=e,a=i*o*n,s=new r(a),c=s.byteLength/a;return{pixelData:s,rows:i,columns:o,frameInfo:{...t.frameInfo,rows:i,columns:o},imageInfo:{...t.imageInfo,rows:i,columns:o,bytesPerPixel:c}}}function e8e(t,e,r){const n=QEe(t,e,r),{scalingType:i="replicate"}=e;return qEe[i](t,n),Object.assign(t,n),t.pixelDataLength=t.pixelData.length,t}async function w$(t,e,r,n,i,o){const a=new Date().getTime();let s=null,c;switch(e){case"1.2.840.10008.1.2":case"1.2.840.10008.1.2.1":s=B7(t,r);break;case"1.2.840.10008.1.2.2":s=hEe(t,r);break;case"1.2.840.10008.1.2.1.99":s=B7(t,r);break;case"1.2.840.10008.1.2.5":s=gEe(t,r);break;case"1.2.840.10008.1.2.4.50":c={...t},s=SEe(r,c);break;case"1.2.840.10008.1.2.4.51":s=DEe(t,r);break;case"1.2.840.10008.1.2.4.57":s=W7(t,r);break;case"1.2.840.10008.1.2.4.70":s=W7(t,r);break;case"1.2.840.10008.1.2.4.80":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=z7(r,c);break;case"1.2.840.10008.1.2.4.81":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=z7(r,c);break;case"1.2.840.10008.1.2.4.90":c={...t},s=$7(r,c);break;case"1.2.840.10008.1.2.4.91":c={...t},s=$7(r,c);break;case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":c={...t},s=jEe(r,c);break;default:throw new Error(`no decoder for transfer syntax ${e}`)}if(!s)throw new Error("decodePromise not defined");const l=await s,f=XEe(l,i,a);return o==null||o(f),f}const t8e={decodeTask({imageFrame:t,transferSyntax:e,decodeConfig:r,options:n,pixelData:i,callbackFn:o}){return w$(t,e,i,r,n,o)}};I4(t8e);const Il={constants:lEe,convertRGBColorByPixel:Iz,convertRGBColorByPlane:Oz,convertYBRFullByPixel:Mz,convertYBRFullByPlane:Pz,convertPALETTECOLOR:Rz,wadouri:R4e,wadors:rEe,init:f$,convertColorSpace:Jz,createImage:sx,decodeJPEGBaseline8BitColor:Zz,getImageFrame:Qz,getPixelData:Q8,getMinMax:ax,isColorImage:q8,isJPEGBaseline8BitColor:sEe,internal:K_e,decodeImageFrame:w$};class Nh extends mf{}xb(Nh,"toolName","NoLabelArrowAnnotate");function H7(t,e){const r=ct("imagePlaneModule",t);if(!r)return;const{rowCosines:n,columnCosines:i,imagePositionPatient:o,rowPixelSpacing:a,columnPixelSpacing:s}=r;if(!n||!i||!o)return;const c=s||1,l=a||1,f=n,u=i,d=o;return[d[0]+e.x*u[0]*c+e.y*f[0]*l,d[1]+e.x*u[1]*c+e.y*f[1]*l,d[2]+e.x*u[2]*c+e.y*f[2]*l]}window.cornerstone3dTools=Dz;window.cornerstone3d=jhe;window.cornerstoneDICOMImageLoader=Il;const{MouseBindings:Fg,KeyboardBindings:K7}=lF,{IMAGE_RENDERED:Ug}=et,n8e=[{name:"Soft Tissue",center:40,width:400},{name:"Lung",center:-600,width:1500},{name:"Bone",center:300,width:1500},{name:"Brain",center:40,width:80},{name:"Abdomen",center:60,width:400}],q7=t=>{const e=(t||"").toUpperCase(),r=[{name:"Reset to default",action:"reset"},{name:"Auto level",action:"autolevel"}];return e!=="CT"?r:[...r,...n8e.map(n=>({name:n.name,action:"preset",center:n.center,width:n.width}))]},l0=[{label:"Window/Level",value:Mh.toolName,icon:"🌓"},{label:"Pan",value:ef.toolName,icon:"✋"},{label:"Zoom",value:Wl.toolName,icon:"🔍"},{label:"Stack Scroll",value:Ld.toolName,icon:"📚"},{label:"Rotate",value:Ph.toolName,icon:"↺"},{label:"Length",value:pf.toolName,icon:"📏"},{label:"Probe",value:su.toolName,icon:"🔎"},{label:"Arrow (No Label)",value:Nh.toolName,icon:"➡️"},{label:"Arrow Annotate",value:mf.toolName,icon:"✈️"},{label:"Rectangle ROI",value:au.toolName,icon:"▭"},{label:"Ellipse ROI",value:Ad.toolName,icon:"◯"},{label:"Freehand ROI",value:gf.toolName,icon:"✏️"},{label:"Freehand Contour Segmentation",value:sl.toolName,icon:"🖊️"},{label:"Sculptor",value:Rh.toolName,icon:"🔧"},{label:"Reference Cursors",value:La.toolName,icon:"⦿"}],r8e=3,i8e=220;function o8e(t){if(!t)return"🔖";const e=l0.find(r=>r.value===t||r.label===t);return(e==null?void 0:e.icon)||"🔖"}function zs(t){return t?t.startsWith("wadouri:")?t.replace(/^wadouri:+/,"").replace(/^:+/,""):t:""}function RT(t){return/([?&])frame=\d+/i.test(t)}function X7(t,e){const r=Math.max(1,Math.floor(e));return RT(t)?t.replace(/([?&])frame=\d+/i,`$1frame=${r}`):`${t}&frame=${r}`}function Y7(t){const e=t.match(/[?&]frame=(\d+)/i);if(!e)return null;const r=Number(e[1]);return Number.isFinite(r)&&r>0?Math.floor(r):null}function J7(t){return t?t.split(/\\|,/).map(e=>Number(e.trim())).filter(e=>Number.isFinite(e)):[]}function a0(t){return t.startsWith("wadouri:")||t.startsWith("external:")?t:`wadouri:${t}`}function e3(t){const e=new Set,r=[];for(const n of t)!n||e.has(n)||(e.add(n),r.push(n));return r}function a8e(t){try{const e=t.getContext("2d",{willReadFrequently:!0});if(!e)return!0;const r=t.width||160,n=t.height||160,o=e.getImageData(0,0,r,n).data;let a=255,s=0,c=0,l=0;for(let d=0;d0&&w>12&&(c+=1),a=Math.min(a,w),s=Math.max(s,w),l+=1}if(l===0)return!0;const f=c/l,u=s-a;return f>.015||u>8}catch{return!0}}const Z7=[{label:"Left",value:"Primary"},{label:"Middle",value:"Auxiliary"},{label:"Right",value:"Secondary"}],ev=[{label:"Left",value:"Primary",mask:1},{label:"Middle",value:"Auxiliary",mask:4},{label:"Right",value:"Secondary",mask:2},{label:"Left + Right",value:"Primary_and_Secondary",mask:3},{label:"Left + Middle",value:"Primary_and_Auxiliary",mask:5},{label:"Right + Middle",value:"Secondary_and_Auxiliary",mask:6},{label:"Left + Right + Middle",value:"Primary_and_Secondary_and_Auxiliary",mask:7},{label:"Fourth Button",value:"Fourth_Button",mask:8},{label:"Fifth Button",value:"Fifth_Button",mask:16},{label:"Mouse Wheel",value:"Wheel",mask:524288},{label:"Mouse Wheel + Left",value:"Wheel_Primary",mask:524289}];function s8e({container_id:t,imageStacks:e,autoCacheStack:r,annotationJson:n,viewerState:i,...o}){var Ms,Tc,Za,Ps,Rs,Qa,_c,Ls,Ec,As,bc,Dc,Ic,Oc,es,ts,vo,Bo,Hi,Ns,ks,ns,Vs,Ia,Fs,oe,ae,De,He,tt;const a=st.useRef(null),s=st.useRef(null),c=st.useRef(!1),l="dv3d_mouseToolBindings",f="dv3d_ctrlMouseToolBindings",[u,d]=st.useState(!1),[h,g]=st.useState(!1),[p,v]=st.useState(320),y=`dv3d_stackPanelWidth_${t||"default"}`,m=st.useRef({resizing:!1,startX:0,startWidth:320}),w=240,x=720,C=220,S=40,T=14,_=st.useRef(null),[E,b]=st.useState(null),[D,I]=st.useState(null),[P,O]=st.useState(!1),L=9,B="renderingEngine_"+t,H="TOOL_GROUP_"+t,A=st.useRef(null),F=st.useRef(!1),[G,X]=st.useState(!0),[ee,ce]=st.useState(!1),[Se,we]=st.useState([]),[_e,Ve]=st.useState(0),[Ge,Ne]=st.useState(null),[j,M]=st.useState(!1),[q,K]=st.useState(null),[J,re]=st.useState(()=>Array(L).fill([])),ie=z=>{typeof z=="function"?re(ne=>{const de=z(ne);return console.log("setViewportImageIds (fn):",de),de}):(console.log("setViewportImageIds:",z),re(z))},[Re,Fe]=st.useState(()=>Array(L).fill(0)),[je,Xe]=st.useState(()=>Array(L).fill(null).map(()=>[])),[se,ue]=st.useState(()=>Array(L).fill(0)),[Pe,pe]=st.useState(()=>Array(L).fill(!1)),[Ee,Qe]=st.useState(()=>Array(L).fill(12)),[fe,ft]=st.useState(()=>Array(L).fill(!1)),pt=st.useRef({}),dt=st.useRef({}),[Ue,nt]=st.useState({}),at=st.useRef({}),ot=st.useRef({}),lt=st.useCallback((z,ne)=>{nt(de=>{const le=de[z];if(le&&le!==ne&&le.startsWith("blob:"))try{URL.revokeObjectURL(le)}catch{}const Q={...de,[z]:ne};return at.current=Q,Q})},[]);st.useEffect(()=>{at.current=Ue},[Ue]),st.useEffect(()=>()=>{Object.values(at.current).forEach(z=>{if(typeof z=="string"&&z.startsWith("blob:"))try{URL.revokeObjectURL(z)}catch{}})},[]),st.useEffect(()=>{try{const z=localStorage.getItem(y);if(z){const ne=Number(z);Number.isNaN(ne)||v(Math.max(w,Math.min(x,Math.round(ne))))}}catch{}},[y]),st.useEffect(()=>{try{localStorage.setItem(y,String(Math.round(p)))}catch{}},[y,p]);function _t(z){if(!z)return null;try{if(z.tagName&&z.tagName.toLowerCase()==="canvas")return z}catch{}try{const ne=z.querySelector&&z.querySelector("canvas");if(ne)return ne}catch{}try{const ne=z.children||[];for(let de=0;deMath.min(rt,Math.max(qe,Ae)),Ie=()=>{ne.style.transform=`translate(${ge}px, ${me}px) scale(${he})`};let ke=!0,be=!0;const Oe=Ae=>{if(!be)return;Ae.preventDefault();const qe=ne.getBoundingClientRect(),rt=Ae.clientX-qe.left,mt=Ae.clientY-qe.top,ht=-Ae.deltaY,zt=1+(ht>0?.1:-.1)*Math.min(4,Math.abs(ht)/100),Ut=ve(he*zt,.1,10);ge=(ge-rt)*(Ut/he)+rt,me=(me-mt)*(Ut/he)+mt,he=Ut,Ie()},W=Ae=>{Ae.button===0&&ke&&(N=!0,k=Ae.clientX,te=Ae.clientY,ne.style.cursor="grabbing",Ae.preventDefault())},$=Ae=>{if(!N)return;const qe=Ae.clientX-k,rt=Ae.clientY-te;ge+=qe,me+=rt,k=Ae.clientX,te=Ae.clientY,Ie()},R=Ae=>{N&&(N=!1,ne.style.cursor="grab")},V=Ae=>{he=1,ge=0,me=0,Ie()};let Y=0;const ye=(Ae,qe)=>Math.hypot(qe.clientX-Ae.clientX,qe.clientY-Ae.clientY),xe=Ae=>{Ae.touches.length===1?ke&&(N=!0,k=Ae.touches[0].clientX,te=Ae.touches[0].clientY):Ae.touches.length===2&&(Y=ye(Ae.touches[0],Ae.touches[1]))},Ce=Ae=>{if(Ae.touches.length===1&&N){const qe=Ae.touches[0].clientX-k,rt=Ae.touches[0].clientY-te;ge+=qe,me+=rt,k=Ae.touches[0].clientX,te=Ae.touches[0].clientY,Ie()}else if(Ae.touches.length===2&&be){const qe=ye(Ae.touches[0],Ae.touches[1]);if(Y>0){const rt=qe/Y,mt=ne.getBoundingClientRect(),ht=(Ae.touches[0].clientX+Ae.touches[1].clientX)/2-mt.left,zt=(Ae.touches[0].clientY+Ae.touches[1].clientY)/2-mt.top,Ut=ve(he*rt,.1,10);ge=(ge-ht)*(Ut/he)+ht,me=(me-zt)*(Ut/he)+zt,he=Ut,Ie()}Y=qe}Ae.preventDefault()},Te=Ae=>{Ae.touches.length===0&&(N=!1,Y=0)};return z.addEventListener("wheel",Oe,{passive:!1}),z.addEventListener("mousedown",W),window.addEventListener("mousemove",$),window.addEventListener("mouseup",R),ne.addEventListener("dblclick",V),z.addEventListener("touchstart",xe,{passive:!1}),z.addEventListener("touchmove",Ce,{passive:!1}),z.addEventListener("touchend",Te),{cleanup:()=>{z.removeEventListener("wheel",Oe),z.removeEventListener("mousedown",W),window.removeEventListener("mousemove",$),window.removeEventListener("mouseup",R),ne.removeEventListener("dblclick",V),z.removeEventListener("touchstart",xe),z.removeEventListener("touchmove",Ce),z.removeEventListener("touchend",Te),ne.style.transform="",ne.style.cursor="",ne.style.willChange=""},setAllowPan:Ae=>{ke=Ae},setAllowZoom:Ae=>{be=Ae}}}const[Ft,wn]=st.useState(!1),[Dn,Nt]=st.useState(null),[xn,Ui]=st.useState(!1),[br,Ye]=st.useState(null);st.useEffect(()=>{const z=de=>{try{const le=de&&de.message?String(de.message):"";(le.includes("releaseGraphicsResources")||le.includes("openGLTexture")||le.includes("getDefaultActor")||le.includes("setColormapGPU")||le.includes(`can't access property "actor"`)||le.toLowerCase().includes("webgl")||le.toLowerCase().includes("colormap"))&&(console.error("Detected graphics/rendering error:",de),Ye(le||null),Ui(!0))}catch{}},ne=de=>{try{const le=de&&de.reason||"",Q=typeof le=="string"?le:le&&le.message?le.message:String(le);(Q.includes("releaseGraphicsResources")||Q.includes("openGLTexture")||Q.includes("getDefaultActor")||Q.includes("setColormapGPU")||Q.includes(`can't access property "actor"`)||Q.toLowerCase().includes("webgl")||Q.toLowerCase().includes("colormap"))&&(console.error("Detected graphics/rendering rejection:",de),Ye(Q||null),Ui(!0))}catch{}};return window.addEventListener("error",z),window.addEventListener("unhandledrejection",ne),()=>{window.removeEventListener("error",z),window.removeEventListener("unhandledrejection",ne)}},[]),st.useEffect(()=>{let z=!1;if(n||i){Nt(n?"annotations":"viewerState");const ne=setTimeout(()=>{if(z)return;const de=t||"default";if(n)try{const le=window[`importAnnotations_${de}`]||window.importAnnotations;typeof le=="function"&&le(n)}catch(le){console.error("Failed to import annotations from prop:",le)}if(i)try{const le=window[`importViewerState_${de}`]||window.importViewerState;typeof le=="function"&&le(i)}catch(le){console.error("Failed to import viewer state from prop:",le)}Nt(null)},2e3);return()=>{z=!0,clearTimeout(ne),Nt(null)}}},[n,i,t]),st.useEffect(()=>{let z=!0;return e().then(async ne=>{var Q,he;if(!z)return;const de=Array.isArray(ne)?ne:[],le=await Promise.all(de.map(async ge=>{if(Array.isArray(ge)){const ve=await Ei(ge),Ie=await Bn(ve);return{imageIds:ve,seriesGroups:Ie}}const me=Array.isArray(ge.imageIds)?ge.imageIds:Array.isArray(ge.i)?ge.i:[],N=await Ei(me);let k;if(Array.isArray(ge.series)){const Ie=(await Promise.all(ge.series.map(async(ke,be)=>{const Oe=Array.isArray(ke==null?void 0:ke.imageIds)?ke.imageIds:Array.isArray(ke==null?void 0:ke.i)?ke.i:[],W=await Ei(Oe),R=(typeof(ke==null?void 0:ke.name)=="string"?ke.name:"").trim()||`Series ${be+1}`;return{key:String((ke==null?void 0:ke.seriesInstanceUID)||(ke==null?void 0:ke.seriesId)||`SERIES_${be}`),label:R,imageIds:W,seriesInstanceUID:ke==null?void 0:ke.seriesInstanceUID,bValue:Number.isFinite(Number(ke==null?void 0:ke.bValue))?Number(ke.bValue):null}}))).filter(ke=>ke.imageIds.length>0);Ie.length>0&&(k=Ie)}(!k||k.length===0)&&(k=await Bn(N));let te=ge.studyInstanceUID;if(!te&&N.length>0)try{const ve=N[0];if(typeof fetch=="function"&&typeof window.dicomParser<"u"&&ve.startsWith("wadouri:")){const Ie=zs(ve),be=await(await fetch(Ie)).arrayBuffer();te=window.dicomParser.parseDicom(new Uint8Array(be)).string("x0020000d")}}catch{}return{imageIds:N,seriesGroups:k,studyInstanceUID:te,studyId:ge.studyId,name:ge.name,caseId:ge.caseId}}));if(we(le),le[0]){const ge=le[0],me=((he=(Q=ge.seriesGroups)==null?void 0:Q[0])==null?void 0:he.imageIds)||ge.imageIds;await jn(me),ie(Array(L).fill(me||[])),Xe(Array(L).fill(null).map(()=>ge.seriesGroups||[])),ue(Array(L).fill(0))}else ie(Array(L).fill([])),Xe(Array(L).fill(null).map(()=>[])),ue(Array(L).fill(0))}).catch(ne=>{console.error("Failed to load imageStacks:",ne),we([]),ie(Array(L).fill([]))}),()=>{z=!1}},[]);const ut=async(z,ne)=>{var ge;const de=Se[ne];if(!de)return;let le=de.seriesGroups;const Q=de.imageIds;await jn(Q,{force:!0}),(!le||le.length===0)&&(le=await Bn(Q),we(me=>{const N=[...me];return N[ne]?(N[ne]={...N[ne],seriesGroups:le},N):me}));const he=((ge=le[0])==null?void 0:ge.imageIds)||Q;Nt("displayset");try{pi(me=>{const N=[...me];return N[z]="stack",N}),ie(me=>{const N=[...me];return N[z]=he,N}),Fe(me=>{const N=[...me];return N[z]=ne,N}),Xe(me=>{const N=[...me];return N[z]=le||[],N}),ue(me=>{const N=[...me];return N[z]=0,N}),await jn(he)}finally{Nt(null)}},[Rt,mn]=st.useState(!1),[Fr,Lt]=st.useState(!0),[Cn,Yt]=st.useState(!1),[jt,hi]=st.useState(!1),Bi=()=>{console.log("Sorting viewport imageIds by slice location"),ie(z=>{const ne=z.map((de,le)=>{if(!de||de.length===0)return de;const ge=[...de.map(me=>{const N=ct("imagePlaneModule",me);let k=null;return N&&(N.sliceLocation!==void 0?k=Number(N.sliceLocation):N.imagePositionPatient&&Array.isArray(N.imagePositionPatient)&&N.imagePositionPatient.length===3&&(k=Number(N.imagePositionPatient[2]))),{imageId:me,sortKey:k}})].sort((me,N)=>me.sortKey!==null&&N.sortKey!==null?me.sortKey-N.sortKey:me.imageId.localeCompare(N.imageId)).map(me=>me.imageId);return JSON.stringify(ge)===JSON.stringify(de)?de:ge});return wn(!0),ne})},Ao=st.useCallback(async(z,ne,de=0)=>{if(!ne||Ue[z]||ot.current[z])return;if(vt(ne)){try{const ge=new Image;ge.crossOrigin="anonymous";const me=ne.replace(/^external:/,"");ge.src=me,await new Promise((ve,Ie)=>{ge.onload=()=>ve(!0),ge.onerror=ke=>Ie(ke)});const N=document.createElement("canvas"),k=160;N.width=k,N.height=k;const te=N.getContext("2d");if(te){const ve=Math.min(k/ge.width,k/ge.height),Ie=ge.width*ve,ke=ge.height*ve,be=(k-Ie)/2,Oe=(k-ke)/2;te.fillStyle="#000",te.fillRect(0,0,k,k),te.drawImage(ge,be,Oe,Ie,ke),lt(z,N.toDataURL("image/png"))}else lt(z,"BROKEN")}catch{lt(z,"BROKEN")}return}const le=A.current;if(!le)return;ot.current[z]=!0;const Q=`THUMB_${t||"main"}_${z}`,he=document.createElement("div");he.style.width="160px",he.style.height="160px",he.style.position="absolute",he.style.left="-9999px",he.style.top="0",document.body.appendChild(he);try{le.enableElement({viewportId:Q,type:ir.STACK,element:he});const ge=le.getViewport(Q);if(!ge)return;try{ge.setStack([ne])}catch{}await new Promise(N=>{let k=!1;const te=setTimeout(()=>{k||(k=!0,N(!1))},2e3),ve=()=>{k||(k=!0,clearTimeout(te),N(!0))};try{if(ge&&ge.element&&ge.element.addEventListener(Ug,ve,{once:!0}),typeof ge.render=="function")try{const Ie=ge.render();Ie&&typeof Ie.then=="function"&&Ie.catch(()=>{})}catch{}}catch{clearTimeout(te),N(!1)}});let me=_t(he)||(ge&&ge.element?_t(ge.element):null);if(me||(await new Promise(N=>setTimeout(N,150)),me=_t(he)||(ge&&ge.element?_t(ge.element):null)),me){if(!a8e(me)&&de{Ao(z,ne,de+1)},k);return}try{if(typeof me.toBlob=="function"){const k=await new Promise(te=>{me.toBlob(ve=>{if(!ve){te(null);return}te(URL.createObjectURL(ve))},"image/png")});k?lt(z,k):lt(z,me.toDataURL("image/png"))}else lt(z,me.toDataURL("image/png"))}catch{lt(z,"BROKEN")}}else lt(z,"BROKEN")}catch{try{lt(z,"BROKEN")}catch{}}finally{try{le.disableElement(Q)}catch{}he&&he.parentNode&&he.parentNode.removeChild(he)}},[t,Ue,lt]);st.useEffect(()=>{!Se||Se.length===0||!A.current||Se.forEach((ne,de)=>{const le=Array.isArray(ne.imageIds)?ne.imageIds:[],Q=Math.floor(le.length/2),he=le[Q]||le[0]||null;!Ue[de]&&!ot.current[de]&&Ao(de,he)})},[Se,Ao,Ue]);const jn=async(z,ne)=>{console.log("Setting loaded imageIds:",z),console.log("autoCacheStack:",r);const de=[];if(!!(r||ne!=null&&ne.force)){for(const Q of z)if(Q.startsWith("wadouri:"))try{const he=zs(Q);if(Il.wadouri.dataSetCacheManager){const ge=Il.wadouri.dataSetCacheManager.load(he);ge&&typeof ge.then=="function"&&de.push(ge)}else console.warn("MetaDataManager not found. Unable to cache metadata.")}catch(he){console.warn(`Failed to cache metadata for ${Q}:`,he)}await Promise.all(de),Ur&&(console.log("Sorting viewport imageIds by slice location"),Bi())}},fo=st.useCallback(async z=>{var ge;if(!z.startsWith("wadouri:")||RT(z))return 1;const ne=a0(z),de=zs(ne),le=`wadouri:${de}`,Q=pt.current[le];if(Q!==void 0)return Q;const he=me=>{if(!me||typeof me.intString!="function")return 1;const N=Number(me.intString("x00280008"));return Number.isFinite(N)&&N>1?Math.floor(N):1};try{const me=ct("multiframeModule",ne),N=Number(me==null?void 0:me.numberOfFrames);if(Number.isFinite(N)&&N>1)return pt.current[le]=Math.floor(N),Math.floor(N)}catch{}try{const me=(ge=Il==null?void 0:Il.wadouri)==null?void 0:ge.dataSetCacheManager;if(me!=null&&me.get){const N=me.get(de),k=he(N);return pt.current[le]=k,k}}catch{}try{const N=await(await fetch(de)).arrayBuffer(),k=lr.parseDicom(new Uint8Array(N)),te=he(k);return pt.current[le]=te,te}catch{return pt.current[le]=1,1}},[]),Ei=st.useCallback(async z=>{const ne=[];for(const de of z||[]){const le=a0(de);if(!le.startsWith("wadouri:")||RT(le)){ne.push(le);continue}const Q=await fo(le);if(Q<=1){ne.push(le);continue}for(let he=1;he<=Q;he++)ne.push(X7(le,he))}return e3(ne)},[fo]),xa=st.useCallback(async z=>{var he;if(!z.startsWith("wadouri:"))return[];const ne=a0(z),de=zs(ne).replace(/[?&]frame=\d+/i,""),le=dt.current[de];if(le)return le;const Q=ge=>{if(!ge||typeof ge.string!="function")return[];const me=J7(ge.string("x00189087"));if(me.length>0)return me;const N=J7(ge.string("x20011003"));return N.length>0?N:[]};try{const ge=(he=Il==null?void 0:Il.wadouri)==null?void 0:he.dataSetCacheManager;if(ge!=null&&ge.get){const me=ge.get(de),N=Q(me);if(N.length>0)return dt.current[de]=N,N}}catch{}try{const me=await(await fetch(de)).arrayBuffer(),N=lr.parseDicom(new Uint8Array(me)),k=Q(N);return dt.current[de]=k,k}catch{return dt.current[de]=[],[]}},[]),Bn=st.useCallback(async z=>{if(!Array.isArray(z)||z.length===0)return[];const ne=new Map;z.forEach(he=>{const ge=zs(a0(he)).replace(/[?&]frame=\d+/i,""),me=ne.get(ge)||[];me.push(he),ne.set(ge,me)}),ne.forEach((he,ge)=>{he.sort((me,N)=>{const k=Y7(me)||1,te=Y7(N)||1;return k-te}),ne.set(ge,he)});const de=new Map;await Promise.all(Array.from(ne.keys()).map(async he=>{const ge=`wadouri:${he}`,me=await xa(ge);de.set(he,me)}));const le=new Map;return z.forEach(he=>{const ge=ct("generalSeriesModule",he)||{},me=ct("generalImageModule",he)||{},N=ct("mrImageModule",he)||{},k=(ge.seriesInstanceUID||"").trim(),te=(ge.seriesDescription||"").trim(),ve=Number(ge.seriesNumber),Ie=Number(me.temporalPositionIdentifier),ke=Number(me.triggerTime);let be=Number(N.diffusionBValue??N.diffusionbValue??N.bValue),Oe=Number.isFinite(be)?be:null;if(Oe===null){const ye=zs(a0(he)).replace(/[?&]frame=\d+/i,""),xe=de.get(ye)||[];if(xe.length>0){const Ce=ne.get(ye)||[he],Te=Math.max(0,Ce.indexOf(he)),Me=Math.max(1,Ce.length);if(xe.length===1)Oe=xe[0];else if(xe.length===Me)Oe=xe[Math.min(xe.length-1,Te)];else if(xe.length===2&&Me%2===0)Oe=Te{const N=[];ge.seriesDescription&&N.push(ge.seriesDescription),ge.seriesNumber!==void 0&&N.push(`#${ge.seriesNumber}`),ge.bValue!==null&&ge.bValue!==void 0&&N.push(`b=${Math.round(ge.bValue)}`);const k=N.length>0?N.join(" • "):`Series ${me+1}`;return{key:he,label:k,imageIds:e3(ge.imageIds),seriesInstanceUID:ge.seriesInstanceUID,bValue:ge.bValue}})},[xa]),[Ct,Zt]=st.useState({rows:1,cols:1}),[ar,Qo]=st.useState(!1),Dr=st.useRef([]),ho=st.useRef({}),bi=st.useRef({}),[Ur,Cs]=st.useState(!1),[go,Zi]=st.useState(!0),Ca=st.useCallback(z=>{const ne=z.currentTarget.getBoundingClientRect(),de=z.clientX-ne.left,le=z.clientY-ne.top,Q=ne.width,he=ne.height,ge=Math.min(Q,he)*.24,me=[{zone:"left",distance:de},{zone:"right",distance:Q-de},{zone:"top",distance:le},{zone:"bottom",distance:he-le}];return me.sort((N,k)=>N.distance-k.distance),me[0].distance<=ge?me[0].zone:"center"},[]),gi=st.useCallback(z=>z==="left"||z==="right"?Ct.cols<3?z:"center":(z==="top"||z==="bottom")&&Ct.rows<3?z:"center",[Ct]),Sa=[];for(let z=1;z<=3;z++)for(let ne=1;ne<=3;ne++)Sa.push({rows:z,cols:ne});const[ln,Gi]=st.useState(()=>Array(Ct.rows*Ct.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:"",modality:"",orientation:"",resolution:"",spacing:"",focalPoint:""})),[Ss,ea]=st.useState(()=>Array(L).fill(null).map(()=>[])),Qi=st.useRef(Array(L).fill("")),po=st.useRef(Array(L).fill(null)),Zr=st.useRef(Array(L).fill(null)),Di=st.useRef(Array(L).fill(null)),[sn,pi]=st.useState(()=>Array(L).fill("stack")),[No,Wi]=st.useState(()=>Array(Ct.rows*Ct.cols).fill(!1)),[Ii,Ts]=st.useState({Primary:Ld.toolName,Auxiliary:ef.toolName,Secondary:Mh.toolName,Primary_and_Secondary:Wl.toolName,Fourth_Button:Ph.toolName,Wheel:Ld.toolName}),[ko,_s]=st.useState({Primary:pf.toolName,Auxiliary:su.toolName,Secondary:Nh.toolName}),[eo,zi]=st.useState(!1);st.useEffect(()=>{const z=de=>{de.ctrlKey&&zi(!0)},ne=de=>{de.ctrlKey||zi(!1)};return window.addEventListener("keydown",z),window.addEventListener("keyup",ne),()=>{window.removeEventListener("keydown",z),window.removeEventListener("keyup",ne)}},[]);const[$i,Ir]=st.useState(!1),[yc,Vo]=st.useState(null),Fo=(z,ne)=>{qo&&qo(ne),Is(de=>{const le=[...de];return le[z]=ne,le})},yr=(z,ne,de)=>{const le=rr.getAllAnnotations()||[];le.forEach(he=>{he.annotationUID===ne&&(he.isSelected=!1)}),rr.removeAnnotation(ne),A.current.render();const Q=de.filter(he=>he.annotationUID!==ne);Is(he=>{const ge=[...he],me=Q.length>0?Q[0].annotationUID:null;return ge[z]=me,le.forEach(N=>{N.isSelected=N.annotationUID===me}),qo(me),A.current.render(),ge})},wc=()=>{const z=J.findIndex(Q=>Q&&Q.length>0);if(z===-1){Vo("No images loaded."),Ir(!0);return}const ne=J[z][0],de=["imagePlaneModule","generalSeriesModule","generalStudyModule","patientModule","imagePixelModule","voiLutModule","modalityLutModule","sopCommonModule","petIsotopeModule","multiframeModule","cineModule","overlayPlaneModule","generalImageModule","stackModule","voiLutModule","modalityLutModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule"],le={};de.forEach(Q=>{const he=ct(Q,ne);he!==void 0&&(le[Q]=he)}),Vo(ze.jsx("pre",{style:{maxHeight:600,overflow:"auto",fontSize:13,color:"#fff"},children:JSON.stringify(le,null,2)})),Ir(!0)};st.useEffect(()=>{try{const z=localStorage.getItem(l),ne=localStorage.getItem(f);z&&Ts(JSON.parse(z)),ne&&_s(JSON.parse(ne))}catch{}},[]),st.useEffect(()=>{try{localStorage.setItem(l,JSON.stringify(Ii))}catch{}},[Ii]),st.useEffect(()=>{try{localStorage.setItem(f,JSON.stringify(ko))}catch{}},[ko]),st.useEffect(()=>(window.loadDicomStackFromFiles=z=>{const ne=Array.from(z);Ya({target:{files:ne}})},()=>{window.loadDicomStackFromFiles=void 0}),[]),st.useEffect(()=>{const z=()=>{M(!1),K(null),Ne(null)};return document.addEventListener("dragend",z),()=>document.removeEventListener("dragend",z)},[]);const[mi,Or]=st.useState(!1),[qa,mo]=st.useState(!1);st.useEffect(()=>{const z=jr(H);z&&["ArrowAnnotate","NoLabelArrowAnnotate","Length","RectangleROI","EllipticalROI","PlanarFreehandROI","PlanarFreehandContourSegmentation"].forEach(ne=>{z.setToolConfiguration(ne,{color:"#00e676",selectedColor:"#ffeb3b"})})},[H]),st.useEffect(()=>{const z=le=>{le.altKey&&Or(!0),le.shiftKey&&mo(!0)},ne=le=>{le.altKey||Or(!1),le.shiftKey||mo(!1)},de=()=>{Or(!1),mo(!1)};return window.addEventListener("keydown",z),window.addEventListener("keyup",ne),window.addEventListener("blur",de),()=>{window.removeEventListener("keydown",z),window.removeEventListener("keyup",ne),window.removeEventListener("blur",de)}},[]),st.useEffect(()=>{const z=jr(H);if(!z)return;if(qa||go&&mi){const de=Ct.rows*Ct.cols;J.slice(0,de).filter((Q,he)=>sn[he]==="stack"&&Array.isArray(Q)&&Q.length>0).forEach(Q=>{jn(Q,{force:!0}).catch(he=>{console.warn("Reference cursor metadata warm-up failed:",he)})}),z.hasTool(La.toolName)||z.addTool(La.toolName),z.setToolEnabled(La.toolName),z.setToolActive(La.toolName)}else z.hasTool(La.toolName)&&z.setToolDisabled(La.toolName)},[mi,qa,go,Ct.rows,Ct.cols,J,sn,jn]);const ii=st.useCallback(()=>{[jr(H)].forEach(ne=>{if(ne){l0.forEach(le=>{ne.setToolPassive(le.value,{removeAllBindings:!0})}),ne.setToolDisabled(La.toolName);const de={};Object.entries(Ii).forEach(([le,Q])=>{de[Q]||(de[Q]=[]);const he=ev.find(ge=>ge.value===le);he?de[Q].push({mouseButton:he.mask}):Fg[le]&&de[Q].push({mouseButton:Fg[le]})}),Object.entries(ko).forEach(([le,Q])=>{if(!Q)return;de[Q]||(de[Q]=[]);const he=ev.find(ge=>ge.value===le);he?de[Q].push({mouseButton:he.mask,modifierKey:K7.Ctrl}):Fg[le]&&de[Q].push({mouseButton:Fg[le],modifierKey:K7.Ctrl})}),Object.entries(de).forEach(([le,Q])=>{ne.setToolActive(le,{bindings:Q})});try{const le=Ii.Primary,Q=Ii.Wheel,he=Ii.Auxiliary,ge=le===ef.toolName||he===ef.toolName,me=le===Wl.toolName||Q===Wl.toolName||Ii.Primary_and_Secondary===Wl.toolName;Dr.current.forEach(N=>{if(!N)return;const k=N._externalPanZoom;k&&(typeof k.setAllowPan=="function"&&k.setAllowPan(!!ge),typeof k.setAllowZoom=="function"&&k.setAllowZoom(!!me))})}catch{}}})},[Ii,ko]),[ta,Es]=st.useState(!1),[Xa,Ta]=st.useState("add"),Vn=st.useRef(null),_a=st.useCallback(z=>{h&&(z.preventDefault(),z.stopPropagation(),m.current={resizing:!0,startX:z.clientX,startWidth:p},document.body.style.cursor="col-resize",document.body.style.userSelect="none")},[h,p]);st.useEffect(()=>{const z=de=>{if(!m.current.resizing)return;const le=m.current.startX-de.clientX,Q=Math.max(w,Math.min(x,m.current.startWidth+le));v(Q)},ne=()=>{m.current.resizing&&(m.current.resizing=!1,document.body.style.cursor="",document.body.style.userSelect="")};return window.addEventListener("mousemove",z),window.addEventListener("mouseup",ne),()=>{window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",ne),document.body.style.cursor="",document.body.style.userSelect=""}},[]);const Qr=ta?C-S/2:-S+T;st.useEffect(()=>{try{Vn.current&&(Vn.current.setAttribute("webkitdirectory","true"),Vn.current.setAttribute("directory",""),Vn.current.setAttribute("mozdirectory",""))}catch{}},[]);async function Mr(z,ne=""){const de=[],le=z.entries?z.entries():z.values();for await(const Q of le)try{let he,ge;if(Array.isArray(Q)&&Q.length>=2?(ge=Q[0],he=Q[1]):(he=Q,ge=he.name),!he)continue;if(he.kind==="file"){const me=await he.getFile();try{Object.defineProperty(me,"webkitRelativePath",{value:ne+(ge||he.name),configurable:!0})}catch{}de.push(me)}else if(he.kind==="directory"){const me=await Mr(he,ne+(ge||he.name)+"/");de.push(...me)}}catch(he){console.debug("collectFilesFromDirectoryHandle: skipping entry due to error",he)}return de}const xc=async()=>{var z;if(window.showDirectoryPicker)try{const ne=await window.showDirectoryPicker(),de=await Mr(ne);de&&de.length>0?await Ya({target:{files:de}}):alert("No files found in selected folder.");return}catch(ne){console.warn("showDirectoryPicker failed or cancelled",ne)}(z=Vn.current)==null||z.click()},oi=st.useRef(null),Ya=async z=>{const ne=z.target.files;if(!ne||ne.length===0)return;Cs(!1);const de=Array.from(ne).sort((ge,me)=>ge.name.localeCompare(me.name)),le=await Promise.all(de.map(async ge=>{const me=ge.type&&ge.type.startsWith("image/");let N,k,te,ve,Ie=1,ke=!1;if(!me)try{const Oe=await ge.arrayBuffer(),W=lr.parseDicom(new Uint8Array(Oe));N=W.string("x0020000d"),k=W.string("x0020000e");const $=W.string("x00200013");$!=null&&$!==""&&(te=parseInt($,10));const R=W.string("x00201041")||W.string("x00201040");R!=null&&R!==""&&(ve=parseFloat(R));const V=W.string("x00280008");if(V!=null&&V!==""){const Y=Number(V);Number.isFinite(Y)&&Y>1&&(Ie=Math.floor(Y))}ke=!0}catch{ke=!1}const be=me?`external:${URL.createObjectURL(ge)}`:`wadouri:${URL.createObjectURL(ge)}`;return{file:ge,imageId:be,studyInstanceUID:N,seriesInstanceUID:k,instanceNumber:te,sliceLocation:ve,numberOfFrames:Ie,isImage:me,parsedSuccessfully:ke}})),Q=new Map;for(const ge of le){if(!ge.isImage&&!ge.parsedSuccessfully){console.debug("Skipping non-DICOM/non-image file:",ge.file.name);continue}const me=ge.seriesInstanceUID||ge.studyInstanceUID||(ge.file.webkitRelativePath?ge.file.webkitRelativePath.split("/")[0]:ge.file.name);Q.has(me)||Q.set(me,{entries:[],studyInstanceUID:ge.studyInstanceUID,seriesInstanceUID:ge.seriesInstanceUID}),Q.get(me).entries.push(ge)}const he=[];for(const[ge,me]of Q.entries()){const N=me.entries;N.sort((ve,Ie)=>Ur&&ve.sliceLocation!==void 0&&Ie.sliceLocation!==void 0?ve.sliceLocation-Ie.sliceLocation:ve.instanceNumber!==void 0&&Ie.instanceNumber!==void 0?ve.instanceNumber-Ie.instanceNumber:(ve.file.webkitRelativePath||ve.file.name).localeCompare(Ie.file.webkitRelativePath||Ie.file.name));const k=N.flatMap(ve=>{if(ve.isImage||!Number.isFinite(ve.numberOfFrames)||ve.numberOfFrames<=1)return[ve.imageId];const Ie=[];for(let ke=1;ke<=ve.numberOfFrames;ke++)Ie.push(X7(ve.imageId,ke));return Ie}),te=await Bn(k);he.push({imageIds:k,studyInstanceUID:me.studyInstanceUID,seriesInstanceUID:me.seriesInstanceUID,seriesGroups:te})}if(he.length!==0)if(Xa==="replace"){try{const ge=A.current;if(ge)for(let me=0;me{var me,N;const ge=Array(L).fill([]);for(let k=0;k{const ge=Array(L).fill(null).map(()=>[]);for(let me=0;me{const me=[...ge,...he];ie(N=>{var ve,Ie;const k=[...N],te=he[he.length-1];return k[0]=((Ie=(ve=te.seriesGroups)==null?void 0:ve[0])==null?void 0:Ie.imageIds)||te.imageIds,k}),Fe(N=>{const k=[...N];return k[0]=me.length-1,k}),Xe(N=>{var te;const k=[...N];return k[0]=((te=he[he.length-1])==null?void 0:te.seriesGroups)||[],k}),ue(N=>{const k=[...N];return k[0]=0,k});for(const N of he)jn(N.imageIds);return me})},Sn=st.useCallback((z,ne)=>{var Ie,ke;if(!ne)return;let de=0,le=0,Q="",he="",ge="",me="",N="",k="",te="",ve="";if(sn[z]==="stack"){de=typeof ne.getCurrentImageIdIndex=="function"?ne.getCurrentImageIdIndex():0;const be=typeof ne.getImageIds=="function"?ne.getImageIds():[];le=be.length;const Oe=be[de];if(Oe){const W=ct("generalSeriesModule",Oe),$=ct("imagePlaneModule",Oe),R=ct("imagePixelModule",Oe);me=(W==null?void 0:W.modality)||"",R!=null&&R.rows&&(R!=null&&R.columns)&&(k=`${R.columns} x ${R.rows}`);const V=[$==null?void 0:$.columnPixelSpacing,$==null?void 0:$.rowPixelSpacing,$==null?void 0:$.sliceThickness].filter(Y=>Y!=null&&Y!=="");V.length>0&&(te=V.join(" x "))}if(typeof ne.getCamera=="function"){const W=ne.getCamera();W!=null&&W.focalPoint&&Array.isArray(W.focalPoint)&&(ve=W.focalPoint.map($=>$.toFixed(1)).join(", "))}if(de>=0&&ea(W=>{const $=[...W],R=new Set($[z]||[]);return R.has(de)?W:(R.add(de),$[z]=Array.from(R).sort((V,Y)=>V-Y),$)}),typeof ne.getProperties=="function"){const W=ne.getProperties();if(W.voiRange){const{lower:$,upper:R}=W.voiRange;Q=((R+$)/2).toFixed(0),he=(R-$).toFixed(0),po.current[z]===null&&(po.current[z]={lower:$,upper:R})}}}else if(sn[z]==="volume"){if(typeof ne.getSliceIndex=="function"&&(de=ne.getSliceIndex()),typeof ne.getNumberOfSlices=="function"&&(le=ne.getNumberOfSlices()),typeof ne.getProperties=="function"){let Oe;if(ne.volumeIds&&ne.volumeIds.size>0){const W=Array.from(ne.volumeIds)[0];Oe=ne.getProperties(W)}else Oe=ne.getProperties();if(Oe&&Oe.voiRange){const{lower:W,upper:$}=Oe.voiRange;Q=(($+W)/2).toFixed(0),he=($-W).toFixed(0),po.current[z]===null&&(po.current[z]={lower:W,upper:$})}}if(typeof ne.getSlicePlaneCoordinates=="function"){const Oe=ne.getSlicePlaneCoordinates();Oe&&typeof Oe.position=="number"&&(ge=Oe.position.toFixed(2)+" mm")}const be=(Ie=J[z])==null?void 0:Ie[0];if(be){const Oe=ct("generalSeriesModule",be),W=ct("imagePlaneModule",be),$=ct("imagePixelModule",be);me=(Oe==null?void 0:Oe.modality)||"",N=String(((ke=ne.viewportProperties)==null?void 0:ke.orientation)||"").toUpperCase(),$!=null&&$.rows&&($!=null&&$.columns)&&(k=`${$.columns} x ${$.rows}`);const R=[W==null?void 0:W.columnPixelSpacing,W==null?void 0:W.rowPixelSpacing,W==null?void 0:W.sliceThickness].filter(V=>V!=null&&V!=="");R.length>0&&(te=R.join(" x "))}if(typeof ne.getCamera=="function"){const Oe=ne.getCamera();Oe!=null&&Oe.focalPoint&&Array.isArray(Oe.focalPoint)&&(ve=Oe.focalPoint.map(W=>W.toFixed(1)).join(", "))}}Gi(be=>{const Oe=[...be];return Oe[z]={index:de+1,total:le,windowCenter:Q,windowWidth:he,slicePosition:ge,modality:me,orientation:N,resolution:k,spacing:te,focalPoint:ve},Oe})},[sn,J]);st.useEffect(()=>{ea(z=>{let ne=!1;const de=[...z];for(let le=0;le{var Ce;const Q=await Ei(ne.map(a0));if(Q.length===0)return;await jn(Q,{force:!0});const he=await Bn(Q),ge=((Ce=he[0])==null?void 0:Ce.imageIds)||Q;let me=0;we(Te=>(me=Te.length,[...Te,{imageIds:Q,name:de,seriesGroups:he}]));const N=gi(le);if(N==="center"){Nt("displayset");try{pi(Te=>{const Me=[...Te];return Me[z]="stack",Me}),ie(Te=>{const Me=[...Te];return Me[z]=ge,Me}),Fe(Te=>{const Me=[...Te];return Me[z]=me,Me}),Xe(Te=>{const Me=[...Te];return Me[z]=he,Me}),ue(Te=>{const Me=[...Te];return Me[z]=0,Me}),Ve(z),await jn(ge)}finally{Nt(null)}return}const k=Ct.rows,te=Ct.cols,ve=Math.floor(z/te),Ie=z%te,ke=N==="top"||N==="bottom"?k+1:k,be=N==="left"||N==="right"?te+1:te;if(ke>3||be>3||ke*be>L){Nt("displayset");try{pi(Te=>{const Me=[...Te];return Me[z]="stack",Me}),ie(Te=>{const Me=[...Te];return Me[z]=Q,Me}),Fe(Te=>{const Me=[...Te];return Me[z]=me,Me}),Ve(z),await jn(Q)}finally{Nt(null)}return}const Oe=N==="top"?ve:N==="bottom"?ve+1:ve,W=N==="left"?Ie:N==="right"?Ie+1:Ie,$=Oe*be+W,R=Array(L).fill([]),V=Array(L).fill("stack"),Y=Array(L).fill(0),ye=Array(L).fill(null).map(()=>[]),xe=Array(L).fill(0);for(let Te=0;TeIe||N==="left"?Ae+1:Ae),(N==="top"||N==="bottom")&&Ae===Ie&&(qe=Meve||N==="top"?Me+1:Me);const mt=qe*be+rt;R[mt]=J[Te]||[],V[mt]=sn[Te]||"stack",Y[mt]=Re[Te]??0,ye[mt]=je[Te]||[],xe[mt]=se[Te]??0}R[$]=ge,V[$]="stack",Y[$]=me,ye[$]=he,xe[$]=0,Nt("displayset");try{ji(),Zt({rows:ke,cols:be}),ie(R),pi(V),Fe(Y),Xe(ye),ue(xe),Ve($),await jn(ge)}finally{Nt(null)}},ba=async(z,ne,de)=>{var xe;const le=Se[ne];if(!le)return;let Q=le.seriesGroups;const he=le.imageIds||[];await jn(he,{force:!0}),(!Q||Q.length===0)&&(Q=await Bn(he),we(Ce=>{const Te=[...Ce];return Te[ne]?(Te[ne]={...Te[ne],seriesGroups:Q},Te):Ce}));const ge=((xe=Q[0])==null?void 0:xe.imageIds)||he,me=gi(de);if(me==="center"){await ut(z,ne),Ve(z);return}const N=Ct.rows,k=Ct.cols,te=Math.floor(z/k),ve=z%k,Ie=me==="top"||me==="bottom"?N+1:N,ke=me==="left"||me==="right"?k+1:k;if(Ie>3||ke>3||Ie*ke>L){await ut(z,ne),Ve(z);return}const be=Array(L).fill([]),Oe=Array(L).fill("stack"),W=Array(L).fill(0),$=Array(L).fill(null).map(()=>[]),R=Array(L).fill(0),V=me==="top"?te:me==="bottom"?te+1:te,Y=me==="left"?ve:me==="right"?ve+1:ve,ye=V*ke+Y;for(let Ce=0;Ceve?qe=Me+1:qe=me==="left"?Me+1:Me),(me==="top"||me==="bottom")&&Me===ve&&(Tete?Ae=Te+1:Ae=me==="top"?Te+1:Te);const rt=Ae*ke+qe;be[rt]=J[Ce]||[],Oe[rt]=sn[Ce]||"stack",W[rt]=Re[Ce]??0,$[rt]=je[Ce]||[],R[rt]=se[Ce]??0}be[ye]=ge,Oe[ye]="stack",W[ye]=ne,$[ye]=Q||[],R[ye]=0,Nt("displayset");try{ji(),Zt({rows:Ie,cols:ke}),ie(be),pi(Oe),Fe(W),Xe($),ue(R),Ve(ye),await jn(ge)}finally{Nt(null)}};st.useEffect(()=>{const z=async()=>{var he;if(console.log("setup"),!c.current){c.current=!0,await WA(),await fG(),f$();try{ld("external",ge=>({promise:(async()=>{const N=ge.replace(/^external:/,""),k=new Image;k.crossOrigin="anonymous",k.src=N,await new Promise((W,$)=>{k.onload=()=>W(!0),k.onerror=R=>$(R)});const te=k.naturalWidth||k.width,ve=k.naturalHeight||k.height,Ie=document.createElement("canvas");Ie.width=te,Ie.height=ve;const ke=Ie.getContext("2d");if(!ke)throw new Error("Unable to create canvas context");ke.drawImage(k,0,0,te,ve);const be=ke.getImageData(0,0,te,ve);return{imageId:ge,minPixelValue:0,maxPixelValue:255,slope:1,intercept:0,rows:ve,columns:te,height:ve,width:te,color:!0,rgba:!0,sizeInBytes:be.data.length,getPixelData:()=>be.data,getImageData:()=>be,getCanvas:()=>Ie}})()}))}catch(ge){console.warn("Failed to register external image loader",ge)}}let de=A.current;if(!de){de=new aE(B),A.current=de;try{Se&&Se.length>0&&Se.forEach((ge,me)=>{const N=Array.isArray(ge.imageIds)?ge.imageIds:[],k=Math.floor(N.length/2),te=N[k]||N[0]||null;te&&!Ue[me]&&!ot.current[me]&&Ao(me,te)})}catch{}}let le=jr(H);le||(le=c8e(H)),sn.slice(0,Ct.rows*Ct.cols).filter(ge=>ge==="volume").length,Ja(le);for(let ge=0;ge{if(k.offsetWidth>0&&k.offsetHeight>0){de.resize();const be=de.getViewport(N);be&&typeof be.resize=="function"&&be.resize(),be&&typeof be.render=="function"&&be.render()}});ke.observe(k),k._resizeObserver=ke}if(sn[ge]==="stack"){if(me&&me.length>0){const ke=me[0];if(vt(ke))try{try{const W=k._externalPanZoom;W&&typeof W.cleanup=="function"&&W.cleanup()}catch{}k.innerHTML="";const be=document.createElement("img");be.style.width="100%",be.style.height="100%",be.style.objectFit="contain",be.style.display="block",be.src=ke.replace(/^external:/,""),be.setAttribute("draggable","false"),k.appendChild(be);const Oe=Mt(k,be);k._externalPanZoom=Oe,le.removeViewports(B,N)}catch(be){console.warn("Failed to render external image in viewport",be)}else try{ve.setStack(me)}catch(be){console.warn("viewport.setStack failed",be)}}Rt?le.removeViewports(B,N):le.addViewport(N,B)}else if(sn[ge]==="volume"){le.addViewport(N,B);const ke=`myVolumeId_${ge}`;(await p1(ke,{imageIds:me})).load(),ve.setVolumes([{volumeId:ke}]),ve.render(),k._overlayListener&&ve.element.removeEventListener(Ug,k._overlayListener);const Oe=()=>Sn(ge,ve);ve.element.addEventListener(Ug,Oe),k._overlayListener=Oe,Sn(ge,ve);continue}if(ve.render(),!F.current){bi.current[ge]!==void 0&&typeof ve.setImageIdIndex=="function"&&oa(ve.element,{imageIndex:bi.current[ge]});const ke=ho.current[ge];if(ke&&typeof ve.setProperties=="function"){const{voiRange:be,invert:Oe,interpolationType:W,VOILUTFunction:$,colormap:R}=ke,V={};be&&be.lower!==void 0&&be.upper!==void 0&&(V.voiRange=be),Oe!==void 0&&(V.invert=Oe),W!==void 0&&(V.interpolationType=W),$&&(V.VOILUTFunction=$),R!=null&&(typeof R=="string"||typeof R=="object"&&!("actor"in R))&&(V.colormap=R),setTimeout(()=>{console.log("Restoring properties (timeout) for viewport",ge,V),ve.setProperties(V),ve.render()},100)}}k._overlayListener&&ve.element.removeEventListener(Ug,k._overlayListener);const Ie=()=>Sn(ge,ve);ve.element.addEventListener(Ug,Ie),k._overlayListener=Ie,Sn(ge,ve)}for(let ge=0;ge=2?(le.hasTool(Uc.toolName)||le.addTool(Uc.toolName),le.setToolEnabled(Uc.toolName),le.setToolConfiguration(Uc.toolName,{}),le.setToolActive(Uc.toolName,{bindings:[{mouseButton:Fg.Primary}]})):le.hasTool(Uc.toolName)&&le.setToolDisabled(Uc.toolName)),ii()},ne=requestAnimationFrame(()=>{z()});return()=>{Dr.current.forEach(de=>{de&&de._resizeObserver&&(de._resizeObserver.disconnect(),delete de._resizeObserver)}),cancelAnimationFrame(ne)}},[s,Sn,Ct,sn,J]);const Oi=st.useCallback(z=>{const ne=`CT_${z}`,le=A.current.getViewport(ne);le&&typeof le.resetCamera=="function"&&(le.resetCamera(),console.log("Restoring viewport properties for viewport",z),le.resetProperties(),le.render())},[]),bs=st.useCallback((z,ne,de)=>{const le=`CT_${z}`;try{const Q=A.current;if(Q){const he=Q.getViewport(le);he&&typeof he.setProperties=="function"&&(console.log(`Applying preset to viewport ${z}: center=${ne}, width=${de}`),he.setProperties({voiRange:{lower:ne-de/2,upper:ne+de/2}}),he.render(),Sn(z,he))}}catch{}},[Sn]),na=st.useCallback((z,ne=!1)=>{const de=`CT_${z}`;try{const le=A.current,Q=le==null?void 0:le.getViewport(de);if(!Q)return!1;const he=typeof Q.getImageIds=="function"?Q.getImageIds():J[z]||[],ge=typeof Q.getCurrentImageIdIndex=="function"?Q.getCurrentImageIdIndex():0,me=he[ge]||he[0],N=po.current[z],k=me?ct("voiLutModule",me)||{}:{},te=me?ct("imagePixelModule",me)||{}:{},ve=me?ct("modalityLutModule",me)||{}:{},Ie=Array.isArray(k.windowCenter)?k.windowCenter[0]:k.windowCenter,ke=Array.isArray(k.windowWidth)?k.windowWidth[0]:k.windowWidth,be=Number(te.smallestPixelValue??te.smallestImagePixelValue),Oe=Number(te.largestPixelValue??te.largestImagePixelValue),W=Number(ve.rescaleSlope??1),$=Number(ve.rescaleIntercept??0);if(N)Q.setProperties({voiRange:N});else if(Number.isFinite(Number(Ie))&&Number.isFinite(Number(ke))&&Number(ke)>0){const R=Number(Ie),V=Number(ke);Q.setProperties({voiRange:{lower:R-V/2,upper:R+V/2}})}else Number.isFinite(be)&&Number.isFinite(Oe)&&Oe>be?Q.setProperties({voiRange:{lower:be*W+$,upper:Oe*W+$}}):typeof Q.resetProperties=="function"&&Q.resetProperties();return ne&&typeof Q.resetCamera=="function"&&Q.resetCamera(),Q.render(),Sn(z,Q),!0}catch(le){return console.warn("Failed to apply default window level",le),!1}},[Sn,J]),Cc=st.useCallback(z=>{const ne=`CT_${z}`;(async()=>{const de=A.current;if(!de)return;const le=de.getViewport(ne);if(!le)return;const Q=typeof le.getImageIds=="function"?le.getImageIds():J[z]||[],he=typeof le.getCurrentImageIdIndex=="function"?le.getCurrentImageIdIndex():0,ge=Q[he]||Q[0];if(!ge){na(z);return}const me=ct("imagePixelModule",ge)||{},N=ct("modalityLutModule",ge)||{},k=ct("voiLutModule",ge)||{},te=po.current[z];let ve=Number(me.smallestPixelValue??me.smallestImagePixelValue),Ie=Number(me.largestPixelValue??me.largestImagePixelValue),ke=Number(N.rescaleSlope??1),be=Number(N.rescaleIntercept??0);if(!Number.isFinite(ve)||!Number.isFinite(Ie)||Ie<=ve)try{const $=await ws(ge);ve=Number($==null?void 0:$.minPixelValue),Ie=Number($==null?void 0:$.maxPixelValue),ke=Number(($==null?void 0:$.slope)??ke),be=Number(($==null?void 0:$.intercept)??be)}catch{const R=Q.filter(V=>!!V).slice(0,6);for(const V of R)try{const Y=await ws(V);if(ve=Number(Y==null?void 0:Y.minPixelValue),Ie=Number(Y==null?void 0:Y.maxPixelValue),ke=Number((Y==null?void 0:Y.slope)??ke),be=Number((Y==null?void 0:Y.intercept)??be),Number.isFinite(ve)&&Number.isFinite(Ie)&&Ie>ve)break}catch{}}const Oe=Array.isArray(k.windowCenter)?k.windowCenter[0]:k.windowCenter,W=Array.isArray(k.windowWidth)?k.windowWidth[0]:k.windowWidth;if(Number.isFinite(ve)&&Number.isFinite(Ie)&&Ie>ve)le.setProperties({voiRange:{lower:ve*ke+be,upper:Ie*ke+be}});else if(Number.isFinite(Number(Oe))&&Number.isFinite(Number(W))&&Number(W)>0){const $=Number(Oe),R=Number(W);le.setProperties({voiRange:{lower:$-R/2,upper:$+R/2}})}else if(te)le.setProperties({voiRange:te});else{na(z);return}le.render(),Sn(z,le)})().catch(()=>{na(z)})},[na,Sn,J]),Uo=st.useCallback((z,ne,de=!0,le=!0)=>{if(de&&(Zr.current[z]=ne),ne.action==="reset"){na(z,le);return}if(ne.action==="autolevel"){Cc(z);return}const Q=ne;bs(z,Q.center,Q.width)},[na,bs,Cc]);st.useEffect(()=>{const z=()=>{const de=A.current;if(!de)return;const le=Ct.rows*Ct.cols;for(let Q=0;Qwindow.clearTimeout(ne)},[Uo,ln,Ct,sn]),st.useEffect(()=>{const z=ne=>{var me,N;const de=ne.target;if(de){const k=(me=de.tagName)==null?void 0:me.toLowerCase(),te=de.getAttribute("contenteditable")==="true";if(k==="input"||k==="textarea"||k==="select"||te)return}if(ne.ctrlKey||ne.altKey||ne.metaKey||_e===null)return;const le=(N=ln[_e])==null?void 0:N.modality,Q=q7(le);if(ne.key==="0"){const k=Q.find(te=>te.action==="reset");k&&(Uo(_e,k),ne.preventDefault());return}if(!/^[1-9]$/.test(ne.key))return;const he=Number(ne.key)-1,ge=Q.filter(k=>k.action==="preset");he>=ge.length||(Uo(_e,ge[he]),ne.preventDefault())};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[_e,Uo,ln]);const Da=st.useCallback((z,ne)=>{const de=je[z]||[];if(de.length<=1)return;const le=Math.max(0,Math.min(de.length-1,ne)),Q=de[le];if(!Q||Q.imageIds.length===0)return;const he=A.current,ge=he==null?void 0:he.getViewport(`CT_${z}`);let me=0;if(ge&&typeof ge.getCurrentImageIdIndex=="function"){const k=(J[z]||[]).length,te=ge.getCurrentImageIdIndex(),ve=k>1?te/(k-1):0;me=Math.max(0,Math.min(Q.imageIds.length-1,Math.round(ve*Math.max(0,Q.imageIds.length-1))))}ue(N=>{const k=[...N];return k[z]=le,k}),ie(N=>{const k=[...N];return k[z]=Q.imageIds,k}),jn(Q.imageIds,{force:!0}),window.setTimeout(()=>{var k;const N=(k=A.current)==null?void 0:k.getViewport(`CT_${z}`);!N||typeof N.setImageIdIndex!="function"||(oa(N.element,{imageIndex:me}),N.render(),Sn(z,N))},25)},[je,jn,Sn,J]);st.useEffect(()=>{const z=[],ne=Ct.rows*Ct.cols;for(let de=0;de{var Ie,ke;const me=(Ie=A.current)==null?void 0:Ie.getViewport(`CT_${de}`);if(!me||typeof me.getCurrentImageIdIndex!="function"||typeof me.setImageIdIndex!="function")return;const k=(((ke=me.getImageIds)==null?void 0:ke.call(me))||le).length;if(k<2)return;const ve=(me.getCurrentImageIdIndex()+1)%k;oa(me.element,{imageIndex:ve}),me.render()},he);z.push(ge)}return()=>{z.forEach(de=>window.clearInterval(de))}},[Ee,Pe,Ct,J,sn]);const Sc=st.useCallback(()=>{const z=a.current;z&&(document.fullscreenElement===z?document.exitFullscreen():z.requestFullscreen?z.requestFullscreen():z.webkitRequestFullscreen?z.webkitRequestFullscreen():z.msRequestFullscreen&&z.msRequestFullscreen())},[]);st.useEffect(()=>{Gi(Array(Ct.rows*Ct.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:"",modality:"",orientation:"",resolution:"",spacing:"",focalPoint:""})),Wi(Array(Ct.rows*Ct.cols).fill(!1)),ft(Array(L).fill(!1))},[Ct]),st.useEffect(()=>{ii()},[Ii,ko,eo,ii]),st.useEffect(()=>{if(!No.some(Boolean))return;const z=ne=>{const de=document.querySelector(".preset-menu");de&&!de.contains(ne.target)&&Wi(le=>le.map(()=>!1))};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[No]),st.useEffect(()=>{if(!ar)return;const z=ne=>{const de=_.current;de&&!de.contains(ne.target)&&(Qo(!1),O(!1))};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[ar]),st.useEffect(()=>{const z=ne=>{if(ne.button===3||ne.button===4)return ne.preventDefault(),!1};return window.addEventListener("mousedown",z,!0),window.addEventListener("mouseup",z,!0),window.addEventListener("auxclick",z,!0),()=>{window.removeEventListener("mousedown",z,!0),window.removeEventListener("mouseup",z,!0),window.removeEventListener("auxclick",z,!0)}},[]),st.useEffect(()=>{const z=a.current;if(!z)return;const ne=de=>{de.preventDefault()};return z.addEventListener("contextmenu",ne),()=>{z.removeEventListener("contextmenu",ne)}},[]),st.useEffect(()=>{if(!Fr)return;const z=jr(H);Ja(z)},[_e,Fr]),st.useEffect(()=>{oi.current&&(oi.current.setAttribute("webkitdirectory","true"),oi.current.setAttribute("directory","true"))},[]),st.useEffect(()=>(window.loadDicomStackFromWadouriList=async z=>{var he;if(!z||z.length===0)return;const ne=await Ei(z);await jn(ne,{force:!0});const de=await Bn(ne),le=((he=de[0])==null?void 0:he.imageIds)||ne;let Q;try{const ge=ne[0];if(ge&&ge.startsWith("wadouri:")){const me=zs(ge),k=await(await fetch(me)).arrayBuffer();Q=lr.parseDicom(new Uint8Array(k)).string("x0020000d")}}catch{}we(ge=>{const me=[...ge,{imageIds:ne,studyInstanceUID:Q,seriesGroups:de}];return ie(N=>{const k=[...N];return k[0]=le,k}),Fe(N=>{const k=[...N];return k[0]=me.length-1,k}),Xe(N=>{const k=[...N];return k[0]=de,k}),ue(N=>{const k=[...N];return k[0]=0,k}),jn(le),me})},()=>{window.loadDicomStackFromWadouriList=void 0}),[Bn,Ei,we,jn,Fe,ie]),st.useEffect(()=>{!Ur||!J.every(ne=>!ne||ne.length===0||ne.every(de=>!!ct("imagePlaneModule",de)))||ie(ne=>{let de=!1;const le=ne.map(Q=>{if(!Q||Q.length===0)return Q;const me=[...Q.map(N=>({imageId:N,sliceLoc:(()=>{const k=ct("imagePlaneModule",N);return k&&k.sliceLocation!==void 0?Number(k.sliceLocation):null})()}))].sort((N,k)=>N.sliceLoc!==null&&k.sliceLoc!==null?N.sliceLoc-k.sliceLoc:N.imageId.localeCompare(k.imageId)).map(N=>N.imageId);return JSON.stringify(me)!==JSON.stringify(Q)?(de=!0,me):Q});return de&&wn(!0),le})},[Ur,Se]);function Ja(z){if(!z)return;const ne=`CT_${_e}`;Fr?(z.setToolEnabled(pd.toolName),z.setToolConfiguration(pd.toolName,{sourceViewportId:ne})):z.setToolDisabled(pd.toolName)}function pl(){var ne,de,le;const z=A.current;if(z)for(let Q=0;Q[])),ue(Array(L).fill(0)),pe(Array(L).fill(!1)),ft(Array(L).fill(!1)),pi(Array(L).fill("stack")),Object.values(at.current).forEach(ne=>{if(typeof ne=="string"&&ne.startsWith("blob:"))try{URL.revokeObjectURL(ne)}catch{}}),at.current={},nt({}),ot.current={},wn(!1),Ve(0)}function vl(z,ne){var ge,me;if(console.log("Truncating stack from",z,"to",ne),console.log(Ft),Ct.rows!==1||Ct.cols!==1||Se.length!==1||!J[0]||J[0].length===0||Ft)return alert("Truncation is only allowed when a single stack is loaded in a single viewport (and the order has not been modified in the viewer)."),!1;const de=Se[0],le=de.imageIds;if(z<0||ne>=le.length||z>=ne)return alert("Invalid truncation bounds."),!1;const Q=le.slice(z,ne+1);we([{...de,imageIds:Q}]),ie([Q]),Fe([0]);const he=A.current;if(he){const N=he.getViewport("CT_0");N&&typeof N.setStack=="function"&&(N.setStack(Q),(ge=N.setImageIdIndex)==null||ge.call(N,0),(me=N.render)==null||me.call(N))}return!0}function yl(z=0){const ne=A.current;if(!ne)return null;const de=ne.getViewport(`CT_${z}`);return!de||typeof de.getCurrentImageIdIndex!="function"?null:de.getCurrentImageIdIndex()}st.useEffect(()=>{const z=t||"default";function ne(le,Q){const he=A.current;if(!he)return;const ge=he.getViewport(`CT_${le}`);if(!ge||typeof ge.getImageIds!="function")return;const N=ge.getImageIds().map(ve=>zs(ve)),k=zs(Q),te=N.indexOf(k);te!==-1&&typeof ge.setImageIdIndex=="function"&&(oa(ge.element,{imageIndex:te}),Sn(le,ge))}window[`getViewport_${z}`]=le=>{const Q=A.current;if(Q)return Q.getViewport(`CT_${le}`)},window[`getAllViewports_${z}`]=()=>{const le=A.current;return le?Array.from({length:L},(Q,he)=>le.getViewport(`CT_${he}`)).filter(Boolean):[]},window[`jumpToSliceByImageId_${z}`]=ne,window[`resetViewer_${z}`]=pl,window[`clearViewer_${z}`]=ml,window[`truncateStack_${z}`]=vl,window[`getCurrentStackPosition_${z}`]=yl,window[`loadAdditionalStack_${z}`]=async(le,Q)=>{var k,te;if(!Array.isArray(le)||le.length===0)return;const he=await Ei(le);await jn(he,{force:!0});const ge=await Bn(he),me=((k=ge[0])==null?void 0:k.imageIds)||he;let N=Q;if(!N&&((te=he[0])!=null&&te.startsWith("wadouri:")))try{const ve=zs(he[0]),ke=await(await fetch(ve)).arrayBuffer();N=lr.parseDicom(new Uint8Array(ke)).string("x0020000d")}catch{}we(ve=>[...ve,{imageIds:he,studyInstanceUID:N,seriesGroups:ge}]),ie(ve=>{const Ie=[...ve],ke=Ie.findIndex(be=>!be||be.length===0);return ke!==-1&&(Ie[ke]=me,Xe(be=>{const Oe=[...be];return Oe[ke]=ge,Oe}),ue(be=>{const Oe=[...be];return Oe[ke]=0,Oe})),Ie}),jn(me)},window[`loadExternalStack_${z}`]=async(le,Q)=>{!Array.isArray(le)||le.length===0||await Ea(_e??0,le,Q||"Series","center")},window[`loadExternalStackNewViewport_${z}`]=async(le,Q)=>{if(!Array.isArray(le)||le.length===0)return;await Ea(_e??0,le,Q||"Series","right")},window[`exportViewerState_${z}`]=()=>{var be;const le=Ct.rows*Ct.cols,Q=sn.slice(0,le),he=Re.slice(0,le),ge=Se.map(Oe=>({i:Oe.imageIds,u:Oe.studyInstanceUID,g:Oe.seriesGroups}));console.log("Exporting viewer state with",le,"active viewports"),console.log("modes",Q);const me=A.current,N=[],k=[],te=[],ve=[],Ie=[];for(let Oe=0;Oe{try{F.current=!0;const Q=typeof le=="string"?JSON.parse(le):le;if(Q.grid&&Zt(Q.grid),Q.modes&&pi(Q.modes),Q.stacks&&we(Q.stacks.map(N=>({imageIds:N.i,studyInstanceUID:N.u,seriesGroups:Array.isArray(N.g)?N.g:void 0}))),Q.stackIdx&&Q.stacks){const N=Q.stackIdx.map(k=>{var te;return((te=Q.stacks[k])==null?void 0:te.i)||[]});ie(N),Fe(Q.stackIdx),Xe(()=>{const k=Array(L).fill(null).map(()=>[]);for(let te=0;temt===qe[ht])){console.warn(`Viewport ${Ce}: importedImageIds do not match viewportImageIds`,{importedImageIds:qe,viewportImageIds:rt}),te=!1;break}}catch{te=!1}}if(!te&&ge{me()},500);return}for(let Ce=0;Ce{try{oa(Te.element,{imageIndex:Q.volumeSliceIndices[Ce]})}catch{}},100)}else{try{Te.setStack&&(Te.setStack(qe),Te.render())}catch(rt){console.warn("Failed to set stack for viewport",Ce,rt)}if(Q.stackPos&&typeof Q.stackPos[Ce]=="number"&&typeof Te.setImageIdIndex=="function")try{pn&&oa?oa(Te.element,{imageIndex:Q.stackPos[Ce]}):Te.setImageIdIndex(Q.stackPos[Ce])}catch{}}}const ve=1500;console.log(`Waiting ${ve}ms before applying properties/camera to viewports`),await new Promise(Ce=>setTimeout(Ce,ve));for(let Ce=0;Ce{me()},100)}catch(Q){F.current=!1,alert("Failed to import viewer state: "+Q)}},window[`exportAnnotations_${z}`]=()=>{try{let le=rr.getAllAnnotations();if(console.log("Exporting annotations:",le),Array.isArray(le)){const Q=[pf.toolName,Nh.toolName,mf.toolName,au.toolName,Ad.toolName,gf.toolName,sl.toolName,su.toolName,Rh.toolName];le=le.filter(he=>Q.includes(he.metadata.toolName))}else return"{}";return JSON.stringify(le,null,2)}catch(le){return alert("Failed to export annotations: "+le),"{}"}},window.__pendingImportAnnotations=window.__pendingImportAnnotations||{};const de=le=>{try{const Q=window.__pendingImportAnnotations&&window.__pendingImportAnnotations[le];if(!Q||!Q.length)return;const he=rr;if(!he||typeof he.addAnnotation!="function")return;for(;(window.__pendingImportAnnotations[le]||[]).length;){const ge=(window.__pendingImportAnnotations[le]||[]).shift();ge&&Array.isArray(ge)&&ge.forEach(me=>{try{he.addAnnotation(me,me.annotationUID)}catch(N){console.error("Failed to add queued annotation",N,me)}})}A.current&&A.current.render()}catch(Q){console.error("Error flushing pending annotations:",Q)}};return window[`importAnnotations_${z}`]=le=>{try{const Q=typeof le=="string"?JSON.parse(le):le,he=rr;if(!he||typeof he.addAnnotation!="function"){window.__pendingImportAnnotations[z]=window.__pendingImportAnnotations[z]||[],window.__pendingImportAnnotations[z].push(Q),console.warn("importAnnotations: annotation state not ready, queued import",z),setTimeout(()=>de(z),500);return}if(he.removeAllAnnotations)try{he.removeAllAnnotations()}catch(ge){console.warn("removeAllAnnotations failed",ge)}Array.isArray(Q)&&Q.forEach(ge=>{try{he.addAnnotation(ge,ge.annotationUID)}catch(me){console.error("Failed to add annotation",me,ge)}}),A.current&&A.current.render()}catch(Q){console.error("Failed to import annotations:",Q,{apiKey:z,cornerstoneTools:!!Dz,renderingEngine:!!A.current});try{alert("Failed to import annotations: "+Q)}catch{}}try{de(z)}catch{}},window[`importLegacyAnnotations_${z}`]=le=>{rr.removeAllAnnotations&&rr.removeAllAnnotations();let Q;try{Q=typeof le=="string"?JSON.parse(le):le}catch{alert("Invalid legacy annotation JSON");return}const he={ArrowAnnotate:"ArrowAnnotate"};Object.entries(Q).forEach(([ge,me])=>{console.log("Importing legacy annotations for imageId:",ge),Object.entries(me).forEach(([N,k])=>{const te=he[N]||N;k.data&&Array.isArray(k.data)&&k.data.forEach(ve=>{const Ie=H7(ge,{x:ve.handles.start.y,y:ve.handles.start.x}),ke=H7(ge,{x:ve.handles.end.y,y:ve.handles.end.x});console.log("Importing legacy annotation:"),console.log(" Image ID:",ge),console.log(" Start World:",Ie),console.log(" End World:",ke);const be=ct("imagePlaneModule",ge);console.log(A4);let Oe=ct("frameOfReferenceUID",ge);!Oe&&be&&be.frameOfReferenceUID&&(Oe=be.frameOfReferenceUID);const W=be!=null&&be.rowCosines&&(be!=null&&be.columnCosines)?[be.rowCosines[1]*be.columnCosines[2]-be.rowCosines[2]*be.columnCosines[1],be.rowCosines[2]*be.columnCosines[0]-be.rowCosines[0]*be.columnCosines[2],be.rowCosines[0]*be.columnCosines[1]-be.rowCosines[1]*be.columnCosines[0]]:void 0;Array.isArray(W)&&W.length,typeof ve.rotation=="number"&&ve.rotation;const $={annotationUID:ve.uuid,metadata:{toolName:te,referencedImageId:ge,FrameOfReferenceUID:Oe,viewPlaneNormal:W},data:{handles:{points:[Ie,ke],textBox:ve.handles.textBox},text:ve.text||""},visibility:ve.visible!==!1,active:ve.active||!1};rr.addAnnotation($,$.annotationUID)})})}),A.current&&A.current.render()},window[`importLegacyViewport_${z}`]=le=>{let Q;try{Q=typeof le=="string"?JSON.parse(le):le}catch{alert("Invalid legacy viewport JSON");return}const he=A.current;if(!he)return;const ge=`CT_${_e??0}`,me=he.getViewport(ge);if(!me)return;const N={};if(Q.voi&&(N.voiRange={lower:Q.voi.windowCenter-Q.voi.windowWidth/2,upper:Q.voi.windowCenter+Q.voi.windowWidth/2}),typeof Q.invert=="boolean"&&(N.invert=Q.invert),typeof Q.pixelReplication=="boolean"&&(N.interpolationType=Q.pixelReplication?0:1),typeof Q.hflip=="boolean"&&(N.hflip=Q.hflip),typeof Q.vflip=="boolean"&&(N.vflip=Q.vflip),typeof me.setProperties=="function"&&me.setProperties(N),Q.translation||Q.scale){const k=me.getCamera?me.getCamera():{};Q.translation&&(k.translation={...k.translation,...Q.translation}),Q.scale&&(k.parallelScale=200/Q.scale),console.log("Applying legacy camera properties:",k),typeof me.setCamera=="function"&&me.setCamera(k)}typeof Q.rotation=="number"&&me.setRotation(Q.rotation),me.render(),Sn(_e??0,me)},()=>{window[`exportViewerState_${z}`]=void 0,window[`importViewerState_${z}`]=void 0,window[`exportAnnotations_${z}`]=void 0,window[`importAnnotations_${z}`]=void 0,window[`importLegacyAnnotations_${z}`]=void 0,window[`importLegacyViewport_${z}`]=void 0,window[`jumpToSliceByImageId_${z}`]=void 0,window[`resetViewer_${z}`]=void 0,window[`clearViewer_${z}`]=void 0,window[`truncateStack_${z}`]=void 0,window[`getCurrentStackPosition_${z}`]=void 0,window[`loadAdditionalStack_${z}`]=void 0,window[`loadExternalStack_${z}`]=void 0,window[`loadExternalStackNewViewport_${z}`]=void 0,window[`getViewport_${z}`]=void 0,window[`getAllViewports_${z}`]=void 0}},[Ct,sn,Re,Se,J,Zt,pi,Fe,we,ie,we,ie,jn]),st.useEffect(()=>{const z=a.current;if(!z)return;function ne(de){if(console.log("Handling arrow key navigation",de.key),console.log("activeViewport",_e),_e===null)return;const le=A.current;if(!le)return;const Q=le.getViewport(`CT_${_e}`);if(Q){if(console.log(Q),sn[_e]==="stack"){if(typeof Q.getCurrentImageIdIndex!="function"||typeof Q.setImageIdIndex!="function")return;const he=J[_e];if(!he||he.length===0)return;de.key==="ArrowUp"||de.key==="ArrowRight"?(oc(Q,{delta:-1}),de.preventDefault()):(de.key==="ArrowDown"||de.key==="ArrowLeft")&&(oc(Q,{delta:1}),de.preventDefault())}sn[_e]==="volume"&&typeof Q.getSliceIndex=="function"&&typeof Q.getNumberOfSlices=="function"&&Q.getNumberOfSlices()>1&&(de.key==="ArrowUp"||de.key==="ArrowRight"?(oc(Q,{delta:-1}),de.preventDefault()):(de.key==="ArrowDown"||de.key==="ArrowLeft")&&(oc(Q,{delta:1}),de.preventDefault()))}}return z.addEventListener("keydown",ne),()=>{z.removeEventListener("keydown",ne)}},[_e,sn,J,Sn]);const wl=_e!==null?Re[_e]:0,Ds=Se[wl];Ds==null||Ds.studyInstanceUID;const[xl,Is]=st.useState(()=>Array(L).fill(null)),Cl=Ct.rows*Ct.cols,Os=[];for(let z=0;zDr.current[z]=Q,style:{flex:1,border:ne?"1px solid #222":"none",background:"#000",minWidth:0,minHeight:0,position:"relative",overflow:"hidden",flexDirection:"column",gridRow:Math.floor(z/Ct.cols)+1,gridColumn:z%Ct.cols+1,height:"100%",boxShadow:_e===z?"0 0 0 4px #1976d2, 0 0 16px 4px #1976d2cc":void 0,zIndex:_e===z?10:1},onClick:()=>{Ve(z),Qo(!1)},onDoubleClick:()=>Oi(z),onDragEnter:Q=>{const he=Q.dataTransfer.types,ge=he.includes("text/stack-idx"),me=he.includes("text/dv3d-imageids");if(!ge&&!me)return;Q.preventDefault(),me&&M(!0);const N=Ca(Q);K({viewportIdx:z,zone:N})},onDragOver:Q=>{const he=Q.dataTransfer.types,ge=he.includes("text/stack-idx"),me=he.includes("text/dv3d-imageids");if(!ge&&!me)return;Q.preventDefault();const N=Ca(Q),k=gi(N);K({viewportIdx:z,zone:N}),Q.dataTransfer.dropEffect=k===N?"copy":"move"},onDragLeave:Q=>{if((q==null?void 0:q.viewportIdx)!==z)return;const he=Q.relatedTarget;he&&Q.currentTarget.contains(he)||K(null)},onDrop:Q=>{Q.preventDefault();const he=Q.dataTransfer.getData("text/dv3d-imageids");if(he){const N=Q.dataTransfer.getData("text/dv3d-stack-name")||"Series";try{const k=JSON.parse(he),te=Ca(Q);Ea(z,k,N,te).catch(ve=>{console.error("Failed to apply external drop:",ve)})}catch(k){console.error("Invalid text/dv3d-imageids payload:",k)}K(null),M(!1);return}const ge=Q.dataTransfer.getData("text/stack-idx"),me=parseInt(ge,10);if(!isNaN(me)){const N=Ca(Q);ba(z,me,N).catch(k=>{console.error("Failed to apply dropped stack:",k)})}K(null),Ne(null),M(!1)},children:[(Ge!==null||j)&&de&&ze.jsx("div",{style:{position:"absolute",inset:0,zIndex:19,pointerEvents:"none",background:"rgba(0,0,0,0.08)"},children:ze.jsx("div",{style:{position:"absolute",left:le==="left"?0:le==="right"?"50%":"20%",top:le==="top"?0:le==="bottom"?"50%":"20%",width:le==="left"||le==="right"?"50%":"60%",height:le==="top"||le==="bottom"?"50%":"60%",border:"2px solid #90caf9",boxShadow:"0 0 0 9999px rgba(17, 29, 45, 0.22)",background:"rgba(25, 118, 210, 0.28)",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:.4},children:le==="center"?"Load Here":`Split ${le}`})}),ze.jsx("button",{style:{position:"absolute",top:8,left:8,zIndex:20,background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"12px",opacity:.85},onClick:()=>{pi(Q=>{const he=[...Q];return he[z]=Q[z]==="stack"?"volume":"stack",he})},children:sn[z]==="stack"?"Volume":"Stack"}),sn[z]==="volume"&&ze.jsxs("div",{style:{position:"absolute",top:8,left:70,zIndex:21,display:"flex",gap:"6px",background:"rgba(34,34,34,0.85)",borderRadius:"4px",padding:"2px 6px",alignItems:"center"},children:[ze.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const Q=A.current,he=Q==null?void 0:Q.getViewport(`CT_${z}`);he&&he.setOrientation&&(he.setOrientation("axial"),he.render())},children:"Axial"}),ze.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const Q=A.current,he=Q==null?void 0:Q.getViewport(`CT_${z}`);he&&he.setOrientation&&(he.setOrientation("sagittal"),he.render())},children:"Sagittal"}),ze.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px"},onClick:()=>{const Q=A.current,he=Q==null?void 0:Q.getViewport(`CT_${z}`);he&&he.setOrientation&&(he.setOrientation("coronal"),he.render())},children:"Coronal"})]}),ze.jsxs("button",{style:{position:"absolute",top:40,left:8,zIndex:20,background:"#111",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"13px",opacity:.85,marginTop:"4px",display:"flex",alignItems:"center",gap:"6px"},title:"Toggle Fullscreen",onClick:Q=>{Q.stopPropagation();const he=Dr.current[z];document.fullscreenElement===he?document.exitFullscreen():he!=null&&he.requestFullscreen?he.requestFullscreen():he!=null&&he.webkitRequestFullscreen?he.webkitRequestFullscreen():he!=null&&he.msRequestFullscreen&&he.msRequestFullscreen()},onMouseEnter:()=>b(z),onMouseLeave:()=>b(null),children:[ze.jsx("span",{style:{fontSize:"18px",lineHeight:1},children:"⛶"}),E===z&&ze.jsx("span",{style:{marginLeft:6},children:document.fullscreenElement===Dr.current[z]?"Exit Fullscreen":"Fullscreen"})]}),sn[z]==="stack"&&G&&(()=>{var ke;const Q=J[z],ge=(rr.getAllAnnotations()||[]).filter(be=>be.metadata&&be.metadata.referencedImageId&&Q.includes(be.metadata.referencedImageId)&&be.metadata.toolName!==La.toolName);if(!ge.length)return null;const me=A.current,N=me==null?void 0:me.getViewport(`CT_${z}`),k=((ke=N==null?void 0:N.getCurrentImageIdIndex)==null?void 0:ke.call(N))??0,te=Q[k],ve=ge.filter(be=>be.metadata.referencedImageId===te),Ie=xl[z];return ze.jsxs("div",{style:{position:"absolute",left:"50%",bottom:60,transform:"translateX(-50%)",zIndex:30,display:"flex",gap:4,pointerEvents:"auto",alignItems:"center"},children:[ze.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Previous Annotation","aria-label":"Previous Annotation",onClick:()=>{const be=A.current,Oe=be==null?void 0:be.getViewport(`CT_${z}`);if(!Oe||typeof Oe.getCurrentImageIdIndex!="function")return;const W=Oe.getCurrentImageIdIndex(),$=Q7(W,Q,ge,-1);if($!==null&&typeof Oe.setImageIdIndex=="function"){oa(Oe.element,{imageIndex:$}),Sn(z,Oe);const R=Q[$],V=ge.filter(Y=>Y.metadata.referencedImageId===R);Fo(z,V.length>0?V[0].annotationUID:null)}},children:ze.jsx("span",{"aria-hidden":"true",children:"◀"})}),ze.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Next Annotation","aria-label":"Next Annotation",onClick:()=>{const be=A.current,Oe=be==null?void 0:be.getViewport(`CT_${z}`);if(!Oe||typeof Oe.getCurrentImageIdIndex!="function")return;const W=Oe.getCurrentImageIdIndex(),$=Q7(W,Q,ge,1);if($!==null&&typeof Oe.setImageIdIndex=="function"){oa(Oe.element,{imageIndex:$}),Sn(z,Oe);const R=Q[$],V=ge.filter(Y=>Y.metadata.referencedImageId===R);Fo(z,V.length>0?V[0].annotationUID:null)}},children:ze.jsx("span",{"aria-hidden":"true",children:"▶"})}),ve.length>0&&ze.jsx("div",{style:{display:"flex",gap:2,alignItems:"center"},children:ve.map(be=>ze.jsxs("div",{style:{display:"flex",alignItems:"center",background:Ie===be.annotationUID?"rgb(4, 225, 0)":"#444",color:Ie===be.annotationUID?"#222":"#fff",borderRadius:"4px",padding:"2px 6px",marginRight:2,cursor:"pointer",border:Ie===be.annotationUID?"2px solid #1976d2":"none",fontWeight:Ie===be.annotationUID?"bold":"normal"},onClick:()=>Fo(z,be.annotationUID),children:[ze.jsxs("span",{style:{marginRight:4},title:be.metadata.toolName||"Annotation",children:[Ie===be.annotationUID?"★ ":"",ze.jsx("span",{style:{fontSize:14,lineHeight:1},children:o8e(be.metadata.toolName)})]}),ze.jsx("button",{style:{background:"transparent",color:"#f44336",border:"1px solid #f44336",borderRadius:3,width:16,height:16,fontSize:10,lineHeight:1,cursor:"pointer",marginLeft:4,display:"flex",alignItems:"center",justifyContent:"center",opacity:.95,padding:0},title:"Delete this annotation","aria-label":"Delete annotation",onClick:Oe=>{Oe.stopPropagation(),yr(z,be.annotationUID,ve)},children:ze.jsx("span",{"aria-hidden":"true",children:"✖"})})]},be.annotationUID))})]})})(),ze.jsx("div",{style:{position:"absolute",left:8,bottom:8,background:"rgba(0,0,0,0.7)",color:"#fff",padding:"6px 12px",borderRadius:"4px",fontSize:"14px",zIndex:10,pointerEvents:"none",minWidth:"120px",userSelect:"none"},children:sn[z]==="stack"?ze.jsxs(ze.Fragment,{children:[ze.jsxs("div",{children:["Image: ",(Ms=ln[z])==null?void 0:Ms.index," / ",(Tc=ln[z])==null?void 0:Tc.total]}),ze.jsxs("div",{children:["WC: ",(Za=ln[z])==null?void 0:Za.windowCenter,"   WW: ",(Ps=ln[z])==null?void 0:Ps.windowWidth]}),ee&&ze.jsxs(ze.Fragment,{children:[ze.jsxs("div",{children:["Ori: ",((Rs=ln[z])==null?void 0:Rs.orientation)||"N/A"]}),((Qa=ln[z])==null?void 0:Qa.resolution)&&ze.jsxs("div",{children:["Res: ",(_c=ln[z])==null?void 0:_c.resolution]}),((Ls=ln[z])==null?void 0:Ls.spacing)&&ze.jsxs("div",{children:["Spacing: ",(Ec=ln[z])==null?void 0:Ec.spacing]}),((As=ln[z])==null?void 0:As.focalPoint)&&ze.jsxs("div",{children:["Pos: ",(bc=ln[z])==null?void 0:bc.focalPoint]})]})]}):ze.jsxs("div",{children:["Slice: ",(Dc=ln[z])==null?void 0:Dc.index," / ",(Ic=ln[z])==null?void 0:Ic.total,((Oc=ln[z])==null?void 0:Oc.slicePosition)&&ze.jsxs("span",{children:["   (",(es=ln[z])==null?void 0:es.slicePosition,")"]}),ze.jsx("br",{}),"WC: ",(ts=ln[z])==null?void 0:ts.windowCenter,"   WW: ",(vo=ln[z])==null?void 0:vo.windowWidth,ee&&ze.jsxs(ze.Fragment,{children:[ze.jsx("br",{}),"Ori: ",((Bo=ln[z])==null?void 0:Bo.orientation)||"N/A",((Hi=ln[z])==null?void 0:Hi.resolution)&&ze.jsxs(ze.Fragment,{children:[ze.jsx("br",{}),"Res: ",(Ns=ln[z])==null?void 0:Ns.resolution]}),((ks=ln[z])==null?void 0:ks.spacing)&&ze.jsxs(ze.Fragment,{children:[ze.jsx("br",{}),"Spacing: ",(ns=ln[z])==null?void 0:ns.spacing]}),((Vs=ln[z])==null?void 0:Vs.focalPoint)&&ze.jsxs(ze.Fragment,{children:[ze.jsx("br",{}),"Pos: ",(Ia=ln[z])==null?void 0:Ia.focalPoint]})]})]})}),ze.jsxs("div",{style:{position:"absolute",right:8,bottom:8,zIndex:110,pointerEvents:"auto",display:"flex",alignItems:"flex-end",gap:6},children:[ze.jsx("button",{style:{background:fe[z]?"rgba(30,120,200,0.95)":"rgba(0,0,0,0.7)",color:"#fff",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"4px",fontSize:"12px",fontWeight:700,padding:"6px 9px",cursor:"pointer",minHeight:30},title:fe[z]?"Hide cine controls":"Show cine controls",onClick:Q=>{Q.stopPropagation(),ft(he=>{const ge=[...he],me=!ge[z];return ge[z]=me,me||pe(N=>{const k=[...N];return k[z]=!1,k}),ge})},children:"Cine"}),ze.jsxs("div",{className:"preset-menu",style:{background:"rgba(0,0,0,0.7)",color:"#fff",borderRadius:"4px",fontSize:"14px",minWidth:"120px",overflow:"hidden",cursor:"pointer",position:"relative",boxShadow:No[z]?"0 2px 8px rgba(0,0,0,0.3)":void 0,pointerEvents:"auto"},onClick:Q=>Q.stopPropagation(),children:[ze.jsxs("div",{style:{padding:"6px 12px",fontWeight:"bold",userSelect:"none"},onClick:Q=>{Q.stopPropagation(),Wi(he=>{const ge=[...he];return ge[z]=!ge[z],ge})},children:["Presets (",((Fs=ln[z])==null?void 0:Fs.modality)||"Unknown",")",ze.jsx("span",{style:{float:"right",fontWeight:"normal"},children:No[z]?"▲":"▼"})]}),No[z]&&ze.jsx("div",{className:"preset-menu-content",style:{background:"rgba(0,0,0,0.95)",borderRadius:"0 0 4px 4px",padding:"6px 0 6px 0",display:"flex",flexDirection:"column",zIndex:111,pointerEvents:"auto"},onClick:Q=>Q.stopPropagation(),children:(()=>{var ge;const Q=q7((ge=ln[z])==null?void 0:ge.modality);let he=0;return Q.map(me=>{let N="";return me.action==="reset"?N="0":me.action==="preset"&&(he+=1,N=String(he)),ze.jsxs("button",{title:N?`Shortcut: ${N}`:void 0,style:{display:"block",width:"100%",margin:"2px 0",background:me.action==="preset"?"#333":"#444",color:"#fff",border:"none",borderRadius:"3px",cursor:"pointer",padding:me.action==="preset"?"4px 0":"6px 0",fontSize:"13px",opacity:.9,fontWeight:me.action==="preset"?"normal":"600"},onClick:k=>{k.stopPropagation(),Uo(z,me),Wi(te=>{const ve=[...te];return ve[z]=!1,ve})},children:[me.name,N?` (${N})`:""]},me.name)})})()})]})]}),sn[z]==="stack"&&(fe[z]||(je[z]||[]).length>1)&&ze.jsxs("div",{style:{position:"absolute",left:"50%",bottom:8,transform:"translateX(-50%)",zIndex:36,background:"rgba(15,15,15,0.82)",border:"1px solid rgba(255,255,255,0.18)",borderRadius:8,padding:"6px 10px",display:"flex",alignItems:"center",gap:8,pointerEvents:"auto",minWidth:200,maxWidth:"72%"},onClick:Q=>Q.stopPropagation(),children:[fe[z]&&((oe=ln[z])==null?void 0:oe.total)>1&&ze.jsxs(ze.Fragment,{children:[ze.jsx("button",{style:{background:Pe[z]?"#d32f2f":"#2e7d32",color:"#fff",border:"none",borderRadius:4,fontSize:12,padding:"4px 8px",cursor:"pointer"},title:Pe[z]?"Pause cine":"Play cine",onClick:()=>{pe(Q=>{const he=[...Q];return he[z]=!he[z],he})},children:Pe[z]?"Pause":"Play"}),ze.jsxs("label",{style:{color:"#ddd",fontSize:11,display:"flex",alignItems:"center",gap:4},children:["FPS",ze.jsx("input",{type:"range",min:1,max:30,step:1,value:Math.max(1,Math.min(30,Math.round(Ee[z]||12))),onChange:Q=>{const he=Number(Q.target.value);Qe(ge=>{const me=[...ge];return me[z]=he,me})}}),ze.jsx("span",{style:{minWidth:22,textAlign:"right"},children:Math.round(Ee[z]||12)})]})]}),(je[z]||[]).length>1&&ze.jsxs(ze.Fragment,{children:[ze.jsx("span",{style:{color:"#fff",fontSize:12,whiteSpace:"nowrap"},children:"Series"}),ze.jsx("input",{type:"range",min:0,max:Math.max(0,(je[z]||[]).length-1),step:1,value:Math.max(0,Math.min((je[z]||[]).length-1,se[z]||0)),onChange:Q=>{Da(z,Number(Q.target.value))},style:{width:140}}),ze.jsx("span",{style:{color:"#e0e0e0",fontSize:11,maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:((De=(ae=je[z])==null?void 0:ae[se[z]||0])==null?void 0:De.label)||"",children:((tt=(He=je[z])==null?void 0:He[se[z]||0])==null?void 0:tt.label)||"Series"})]})]}),sn[z]==="stack"&&J[z]&&ze.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"14px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:35,display:J[z].length>0?"flex":"none",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:(()=>{const Q=J[z]||[],he=Q.length;if(he===0)return null;const ge=A.current,me=ge==null?void 0:ge.getViewport(`CT_${z}`),N=me&&typeof me.getCurrentImageIdIndex=="function"?me.getCurrentImageIdIndex():-1,k=new Set(Ss[z]||[]),te=Q.map(Oe=>Oe.startsWith("external:")?!0:!!ct("imagePlaneModule",Oe)||!!ct("generalSeriesModule",Oe)),ve=te.reduce((Oe,W)=>Oe+(W?1:0),0),Ie=Q.reduce((Oe,W,$)=>Oe+(k.has($)?1:0),0),ke=Math.min(he,180),be=Array.from({length:ke},()=>({loaded:!1,viewed:!1,current:!1}));for(let Oe=0;Oe{var xe;const $=Oe.currentTarget.getBoundingClientRect(),R=Math.min($.height,Math.max(0,Oe.clientY-$.top)),V=$.height>0?R/$.height:0,Y=Math.min(he-1,Math.max(0,Math.round(V*(he-1)))),ye=(xe=A.current)==null?void 0:xe.getViewport(`CT_${z}`);ye&&typeof ye.setImageIdIndex=="function"&&sn[z]==="stack"&&(oa(ye.element,{imageIndex:Y}),Sn(z,ye))},children:[be.map((Oe,W)=>{let $="#3f3f3f";return Oe.loaded&&($="#2e7d32"),Oe.viewed&&($="#1565c0"),Oe.current&&($="#fbc02d"),ze.jsx("div",{style:{width:"100%",height:`${100/ke}%`,minHeight:1,background:$,opacity:Oe.loaded||Oe.viewed||Oe.current?.95:.45,borderBottom:W=0&&he>ke&&ze.jsx("div",{style:{position:"absolute",left:0,right:0,top:`${N/Math.max(1,he-1)*100}%`,height:2,background:"#ffeb3b",boxShadow:"0 0 4px #ffeb3b",transform:"translateY(-1px)",pointerEvents:"none"}})]})})()}),sn[z]==="volume"&&(()=>{const Q=A.current,he=Q==null?void 0:Q.getViewport(`CT_${z}`);let ge=0,me=0;return he&&typeof he.getNumberOfSlices=="function"&&typeof he.getSliceIndex=="function"&&(ge=he.getNumberOfSlices(),me=he.getSliceIndex()),ge>1?ze.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"12px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:30,display:"flex",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:ze.jsx("div",{style:{width:"8px",height:"100%",maxHeight:"100%",minHeight:0,borderRadius:"6px",background:"#222",position:"relative",display:"flex",flexDirection:"column",justifyContent:"flex-start",boxShadow:"0 0 8px #2196f3cc",overflow:"hidden",cursor:"pointer"},onClick:N=>{const te=N.currentTarget.getBoundingClientRect(),ve=N.clientY-te.top,Ie=Math.floor(ve/te.height*ge),ke=A.current,be=ke==null?void 0:ke.getViewport(`CT_${z}`);be&&(oa(be.element,{imageIndex:Ie}),be.render(),Sn(z,be))},children:Array.from({length:ge}).map((N,k)=>{const te=k===me;return ze.jsx("div",{style:{width:"100%",height:`${100/ge}%`,minHeight:te?1:0,background:te?"linear-gradient(to right, #ffeb3b 60%, #ff9800 100%)":"#444",opacity:te?.95:.4,transition:"background 0.3s, opacity 0.3s",borderBottom:k1||!J[z]||J[z].length===0)&&ze.jsx("div",{style:{position:"absolute",left:0,right:0,bottom:sn[z]==="stack"&&(fe[z]||(je[z]||[]).length>1)?56:8,zIndex:20,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",width:"100%",background:"none",borderRadius:"0",padding:0},children:ze.jsxs("div",{style:{position:"relative"},children:[ze.jsxs("button",{onClick:Q=>{Q.stopPropagation(),I(he=>he===z?null:z)},style:{padding:"6px 12px",background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",cursor:"pointer",pointerEvents:"auto",fontSize:13},title:"Choose stack",children:[(()=>{const Q=Array.isArray(Re)?Re[z]:void 0,he=typeof Q=="number"&&Se[Q]?Se[Q]:void 0,ge=he&&Array.isArray(he.imageIds)?he.imageIds:[],me=he?he.name||(he.caseId?`Case: ${he.caseId}`:void 0):void 0;if(me)return me;if(ge.length>0)return`Stack ${typeof Q=="number"?Q+1:"1"}`;const N=J[z]||[];return N.length>0?`Stack (${N.length} images)`:"No stack"})(),ze.jsx("span",{style:{marginLeft:8,opacity:.8},children:D===z?"▲":"▼"})]}),D===z&&ze.jsx("div",{ref:Q=>{Q&&Q.focus()},tabIndex:0,style:{position:"absolute",left:0,bottom:"110%",background:"#222",border:"1px solid #444",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",zIndex:100,minWidth:220,maxHeight:260,overflowY:"auto",overscrollBehavior:"contain",scrollbarWidth:"thin",padding:6},role:"listbox",onMouseDown:Q=>Q.stopPropagation(),onWheel:Q=>{var ge;try{Q.stopPropagation()}catch{}try{Q.preventDefault()}catch{}const he=Q.currentTarget;if(he){const me=Q.deltaY??((ge=Q.nativeEvent)==null?void 0:ge.deltaY)??0;he.scrollTop+=me}},onBlur:Q=>{setTimeout(()=>{Q.currentTarget.contains(document.activeElement)||I(null)},0)},children:(()=>{const Q={};return Se.forEach((he,ge)=>{const me=he.studyId||he.studyInstanceUID||"Unspecified";Q[me]||(Q[me]=[]),Q[me].push({idx:ge,stack:he})}),Object.keys(Q).map(he=>ze.jsxs("div",{style:{marginBottom:6},children:[ze.jsx("div",{style:{fontSize:12,color:"#aaa",padding:"4px 8px",fontWeight:700},children:he==="Unspecified"?"Unspecified study":`Study: ${he}`}),ze.jsx("div",{children:Q[he].map(({idx:ge,stack:me})=>{const N=Array.isArray(me.imageIds)?me.imageIds:[],k=me&&(me.name||me.caseId)?me.name||`Case: ${me.caseId}`:`Stack ${ge+1}`,te=N.length,ve=!Array.isArray(N)||te===0;return ze.jsxs("button",{role:"option","aria-selected":!1,title:ve?"Invalid stack descriptor":`${k} — ${te} image${te===1?"":"s"}${me!=null&&me.caseId?` — case ${me.caseId}`:""}`,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",width:"100%",padding:"8px 12px",background:"transparent",color:"#fff",border:"none",textAlign:"left",cursor:ve?"not-allowed":"pointer"},onClick:Ie=>{if(Ie.stopPropagation(),ve){console.warn(`Attempted to select invalid stack at index ${ge}`,me);return}ut(z,ge).catch(ke=>console.error("Failed to load stack:",ke)),I(null)},children:[ze.jsx("div",{style:{fontWeight:"600",fontSize:13},children:k}),ze.jsxs("div",{style:{fontSize:12,opacity:.7},children:[te," image",te===1?"":"s",me!=null&&me.caseId?` • case ${me.caseId}`:""]})]},ge)})})]},he))})()})]})})]},z))}return ze.jsxs("div",{ref:a,style:{position:"relative",inset:0,width:"100%",height:"100%",boxSizing:"border-box",background:"#222",padding:"12px",overflow:"hidden"},children:[Dn&&ze.jsx("div",{style:{position:"absolute",zIndex:3e3,top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.7)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontSize:28,fontWeight:"bold",letterSpacing:1},children:Dn==="annotations"?"Loading Annotations...":Dn==="displayset"?"Loading Display Set...":"Loading Viewer State..."}),xn&&ze.jsxs("div",{style:{position:"fixed",top:12,left:12,right:12,zIndex:1e4,background:"#fff3cd",color:"#856404",border:"1px solid #ffeeba",padding:"10px 14px",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[ze.jsxs("div",{style:{flex:1,fontSize:14},children:[ze.jsx("strong",{children:"Graphics error:"})," The viewer encountered a WebGL/graphics error and may be unstable. Please reload the page.",br?ze.jsx("div",{style:{marginTop:6,fontSize:12,color:"#6b4f00"},children:br}):null]}),ze.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[ze.jsx("button",{onClick:()=>window.location.reload(),style:{padding:"6px 10px"},children:"Reload"}),ze.jsx("button",{onClick:()=>Ui(!1),style:{padding:"6px 10px"},children:"Dismiss"})]})]}),!h&&ze.jsx("button",{onClick:()=>g(!0),"aria-pressed":!1,title:"Open stacks",style:{position:"absolute",right:8,top:76,zIndex:120,width:24,height:42,background:"#1976d2",color:"#fff",border:"none",borderRadius:5,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",pointerEvents:"auto"},children:"▶"}),ze.jsxs("div",{children:[ze.jsx("button",{style:{position:"absolute",top:"50%",transform:"translateY(-50%)",left:Qr,zIndex:200,width:S,height:S,background:"#222",color:"#fff",border:"none",borderRadius:"50%",fontWeight:"bold",cursor:"pointer",fontSize:"22px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",transition:"left 0.25s cubic-bezier(.4,2,.6,1), background 0.2s"},onClick:()=>Es(z=>!z),"aria-label":"Open menu",children:"☰"}),ta&&ze.jsx("div",{style:{position:"absolute",top:0,left:0,width:C,height:"100%",background:"#222",color:"#fff",zIndex:199,boxShadow:"2px 0 12px rgba(0,0,0,0.3)",flexDirection:"column",padding:"24px 16px 16px 16px",display:"flex",overflow:"hidden"},children:ze.jsxs("div",{style:{flex:1,minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column"},children:[ze.jsxs("div",{style:{fontWeight:"bold",fontSize:18,marginBottom:24},children:["Menu",ze.jsx("button",{style:{float:"right",background:"transparent",color:"#fff",border:"none",fontSize:"22px",cursor:"pointer"},onClick:()=>Es(!1),"aria-label":"Close menu",children:"×"})]}),ze.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[ze.jsxs("label",{style:{fontSize:13},children:[ze.jsx("input",{type:"radio",name:"folderLoadMode",value:"add",checked:Xa==="add",onChange:()=>Ta("add")})," Add (append)"]}),ze.jsxs("label",{style:{fontSize:13},children:[ze.jsx("input",{type:"radio",name:"folderLoadMode",value:"replace",checked:Xa==="replace",onChange:()=>Ta("replace")})," Replace all"]})]}),ze.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:xc,children:"Load DICOM Folder"}),ze.jsx("input",{ref:Vn,type:"file",style:{display:"none"},multiple:!0,onChange:Ya}),ze.jsx("input",{ref:oi,type:"file",style:{display:"none"},multiple:!0,onChange:Ya,accept:".dcm,application/dicom"}),ze.jsxs("div",{style:{marginBottom:"18px",display:"flex",alignItems:"center",gap:"8px"},children:[ze.jsx("input",{type:"checkbox",id:"orderBySliceLocation",checked:Ur,onChange:z=>Cs(z.target.checked),style:{accentColor:"#666"}}),ze.jsx("label",{htmlFor:"orderBySliceLocation",style:{fontSize:"15px",cursor:"pointer"},children:"Order by Slice Location"})]}),ze.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:wc,children:"Show DICOM Metadata"}),ze.jsxs("button",{style:{padding:"10px 18px",background:Rt?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>mn(z=>!z),children:[Rt?"Disable":"Enable"," Cross Reference Lines"]}),ze.jsxs("button",{style:{padding:"10px 18px",background:Fr?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Lt(z=>!z),children:[Fr?"Disable":"Enable"," Reference Lines"]}),ze.jsx("button",{onClick:Bi,style:{margin:8,padding:8},children:"Sort All Viewports by Slice Location"}),ze.jsx("button",{style:{padding:"10px 18px",background:go?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Zi(z=>!z),children:go?"Disable Alt Key for Reference Cursors (Shift always works)":"Enable Alt Key for Reference Cursors (Shift always works)"}),ze.jsxs("button",{style:{padding:"10px 18px",background:G?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>X(z=>!z),children:[G?"Hide":"Show"," Annotation Navigation"]}),ze.jsxs("button",{style:{padding:"10px 18px",background:ee?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>ce(z=>!z),children:[ee?"Disable":"Enable"," Volume Diagnostics"]})]})})]}),ze.jsxs("div",{ref:_,className:"grid-menu-hover-container",style:{position:"absolute",top:ar||P?8:-18,left:"50%",transform:"translateX(-50%)",zIndex:100,display:"flex",flexDirection:"row",alignItems:"flex-start",gap:8,width:"auto",pointerEvents:"auto",transition:"top 180ms ease",paddingTop:28,marginTop:-28,paddingBottom:12},onMouseEnter:()=>O(!0),onMouseLeave:()=>{ar||O(!1)},children:[ze.jsxs("button",{style:{height:40,padding:"6px 12px 6px 10px",background:"#222",color:"#fff",border:"none",borderRadius:"0 0 4px 4px",fontWeight:"bold",cursor:"pointer",fontSize:"14px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",display:"inline-flex",alignItems:"center",gap:8},title:"Toggle viewer fullscreen",onFocus:()=>O(!0),onClick:()=>{O(!0),Sc()},children:[ze.jsx("span",{style:{fontSize:16,lineHeight:1},children:"⛶"}),ze.jsx("span",{children:"Fullscreen"})]}),ze.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"stretch"},children:[ze.jsxs("button",{className:"grid-menu-btn",style:{height:40,padding:"6px 14px 6px 10px",background:"#222",color:"#fff",border:"none",borderRadius:"0 0 4px 4px",fontWeight:"bold",cursor:"pointer",fontSize:"14px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",display:"inline-flex",alignItems:"center",gap:10,justifyContent:"space-between",minWidth:136},onFocus:()=>O(!0),onClick:()=>{O(!0),Qo(z=>!z)},tabIndex:0,children:[ze.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[ze.jsx("span",{style:{display:"grid",gridTemplateColumns:`repeat(${Ct.cols}, 5px)`,gridTemplateRows:`repeat(${Ct.rows}, 5px)`,gap:2,padding:1},children:Array.from({length:Ct.rows*Ct.cols}).map((z,ne)=>ze.jsx("span",{style:{width:5,height:5,borderRadius:1,background:"#90caf9",display:"block"}},ne))}),ze.jsxs("span",{children:[Ct.rows,"x",Ct.cols]})]}),ze.jsx("span",{style:{opacity:.8},children:ar?"▲":"▼"})]}),ar&&ze.jsx("div",{style:{position:"absolute",top:"calc(100% + 8px)",right:0,background:"#222",color:"#fff",borderRadius:"6px",boxShadow:"0 2px 12px rgba(0,0,0,0.4)",padding:"12px",display:"grid",gridTemplateColumns:"repeat(3, minmax(68px, 1fr))",gap:"8px",zIndex:200,pointerEvents:"auto"},onMouseDown:z=>z.stopPropagation(),children:Sa.map(z=>ze.jsxs("button",{style:{minWidth:"68px",height:"54px",background:z.rows===Ct.rows&&z.cols===Ct.cols?"#444":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"13px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6},onClick:()=>{ji(),Zt({rows:z.rows,cols:z.cols}),Qo(!1),O(!1)},children:[ze.jsx("span",{style:{display:"grid",gridTemplateColumns:`repeat(${z.cols}, 6px)`,gridTemplateRows:`repeat(${z.rows}, 6px)`,gap:2},children:Array.from({length:z.rows*z.cols}).map((ne,de)=>ze.jsx("span",{style:{width:6,height:6,borderRadius:1,background:"#90caf9",display:"block"}},de))}),ze.jsxs("span",{children:[z.rows,"x",z.cols]})]},`${z.rows}x${z.cols}`))})]})]}),ze.jsxs("div",{style:{display:"flex",flexDirection:"row",height:"calc(100% - 48px)",gap:8},children:[ze.jsxs("div",{style:{flex:1,display:"grid",margin:3,gridTemplateRows:`repeat(${Ct.rows}, 1fr)`,gridTemplateColumns:`repeat(${Ct.cols}, 1fr)`,gap:"5px",minHeight:0,minWidth:0,zIndex:1,position:"relative"},children:[Os,ze.jsx("button",{style:{position:"absolute",top:8,right:8,zIndex:2600,padding:"6px 12px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer",opacity:.85,userSelect:"none"},onClick:()=>d(!0),children:"Settings"})]}),ze.jsxs("div",{style:{width:h?p:0,transition:"width 220ms ease",display:"flex",flexDirection:"column",pointerEvents:h?"auto":"none",overflow:"hidden",position:"relative"},children:[h&&ze.jsx("div",{onMouseDown:_a,title:"Resize stacks panel",style:{position:"absolute",left:0,top:0,width:8,height:"100%",cursor:"col-resize",zIndex:2800,background:"linear-gradient(to right, rgba(100,181,246,0.25), rgba(100,181,246,0))"}}),ze.jsx("div",{style:{pointerEvents:"auto",width:"100%",height:"100%"},children:ze.jsxs("div",{style:{height:"100%",width:"100%",background:"#1f2428",color:"#fff",boxShadow:"0 2px 14px rgba(0,0,0,0.45)",borderLeft:"1px solid #2f3336",transform:"translateX(0)",transition:"transform 220ms ease",display:"flex",flexDirection:"column",overflow:"hidden"},children:[ze.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid #2b2f31"},children:[ze.jsx("div",{style:{fontWeight:700},children:"Stacks"}),ze.jsxs("div",{style:{fontSize:12,color:"#9bb4c8"},children:["Active VP: ",_e!==null?_e+1:"-"]}),ze.jsx("div",{style:{display:"flex",gap:8,alignItems:"center"},children:ze.jsx("button",{title:"Close",onClick:()=>{g(!1)},style:{background:"transparent",color:"#fff",border:"none",cursor:"pointer",fontSize:16},children:"×"})})]}),ze.jsx("div",{style:{overflowY:"auto",padding:8,flex:1},children:Se.length===0?ze.jsx("div",{style:{color:"#999",padding:12},children:"No stacks available"}):ze.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:Se.map((z,ne)=>{const de=Array.isArray(z.imageIds)?z.imageIds:[],le=z.name||(z.caseId?`Case: ${z.caseId}`:`Stack ${ne+1}`),Q=de.length,he=!Array.isArray(de)||Q===0,ge=Re.includes(ne),me=_e!==null&&Re[_e]===ne,N=Math.floor(de.length/2),k=de[N]||de[0],te=k?zs(k):null;return ze.jsxs("div",{draggable:!he,onDragStart:ve=>{he||(Ne(ne),K(null),ve.dataTransfer.setData("text/stack-idx",String(ne)),ve.dataTransfer.effectAllowed="copy")},onDragEnd:()=>{Ne(null),K(null)},onClick:()=>{if(he)return;ut(_e??0,ne)},style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 10px",background:me?"#0d47a1":ge?"#1976d2":"transparent",color:ge?"#fff":"#ddd",border:me?"1px solid #64b5f6":"1px solid transparent",borderRadius:6,cursor:he?"not-allowed":"pointer"},children:[ze.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(()=>{const ve=Ue[ne],Ie=ve&&ve!=="BROKEN"?ve:null,ke=Ie||te||null;return ke?ze.jsx("img",{"data-thumb-stack":ne,src:ke,alt:le,style:{width:56,height:56,objectFit:"cover",borderRadius:4,background:"#111"},onError:()=>{if(console.warn("Thumbnail failed to load for stack",ne,ke),!!Ie){lt(ne,"BROKEN");return}ot.current[ne]||Ao(ne,k)}}):ze.jsx("div",{style:{width:56,height:56,borderRadius:4,background:"#111",display:"flex",alignItems:"center",justifyContent:"center",color:"#777"},children:"No Img"})})(),ze.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[ze.jsx("div",{style:{fontWeight:600},children:le}),ze.jsxs("div",{style:{fontSize:12,opacity:.7},children:[Q," img",Q===1?"":"s"]})]})]}),ze.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:4},children:[ze.jsx("div",{style:{fontSize:12,opacity:.8},children:z.studyId||""}),me&&ze.jsx("div",{style:{fontSize:11,color:"#bbdefb",fontWeight:700},children:"ACTIVE"})]})]},ne)})})})]})})]})]}),u&&ze.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.4)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>d(!1),children:ze.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",minHeight:"180px",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative"},onClick:z=>z.stopPropagation(),children:[ze.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"Settings"}),ze.jsxs("div",{style:{marginBottom:"24px"},children:[ze.jsx("div",{style:{marginBottom:12,fontWeight:"bold"},children:"Mouse Button Tool Bindings"}),Z7.map(z=>ze.jsxs("div",{style:{marginBottom:10},children:[ze.jsxs("label",{style:{marginRight:8},children:[z.label," Button:"]}),ze.jsx("select",{value:Ii[z.value],onChange:ne=>Ts(de=>({...de,[z.value]:ne.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:l0.map(ne=>ze.jsx("option",{value:ne.value,title:ne.label,children:`${ne.icon?`${ne.icon} `:""}${ne.label}`},ne.value))})]},z.value)),ze.jsxs("div",{style:{margin:"12px 0"},children:[ze.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>Yt(z=>!z),children:[Cn?"Hide":"Show"," Advanced Mouse Bindings"]}),Cn&&ze.jsx("div",{style:{marginTop:8},children:ev.slice(3).map(z=>ze.jsxs("div",{style:{marginBottom:10},children:[ze.jsxs("label",{style:{marginRight:8},children:[z.label,":"]}),ze.jsxs("select",{value:Ii[z.value]||"",onChange:ne=>Ts(de=>({...de,[z.value]:ne.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[ze.jsx("option",{value:"",children:"(None)"}),l0.map(ne=>ze.jsx("option",{value:ne.value,title:ne.label,children:`${ne.icon?`${ne.icon} `:""}${ne.label}`},ne.value))]})]},z.value))})]}),ze.jsx("div",{style:{margin:"18px 0 8px 0",fontWeight:"bold"},children:"Ctrl + Mouse Button Tool Bindings"}),Z7.map(z=>ze.jsxs("div",{style:{marginBottom:10},children:[ze.jsxs("label",{style:{marginRight:8},children:[z.label," + Ctrl:"]}),ze.jsxs("select",{value:ko[z.value]||"",onChange:ne=>_s(de=>({...de,[z.value]:ne.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[ze.jsx("option",{value:"",children:"(None)"}),l0.map(ne=>ze.jsx("option",{value:ne.value,title:ne.label,children:`${ne.icon?`${ne.icon} `:""}${ne.label}`},ne.value))]})]},z.value+"_ctrl")),ze.jsxs("div",{style:{margin:"12px 0"},children:[ze.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>hi(z=>!z),children:[jt?"Hide":"Show"," Advanced Ctrl + Mouse Bindings"]}),jt&&ze.jsx("div",{style:{marginTop:8},children:ev.slice(3).map(z=>ze.jsxs("div",{style:{marginBottom:10},children:[ze.jsxs("label",{style:{marginRight:8},children:[z.label," + Ctrl:"]}),ze.jsxs("select",{value:ko[z.value]||"",onChange:ne=>_s(de=>({...de,[z.value]:ne.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[ze.jsx("option",{value:"",children:"(None)"}),l0.map(ne=>ze.jsx("option",{value:ne.value,title:ne.label,children:`${ne.icon?`${ne.icon} `:""}${ne.label}`},ne.value))]})]},z.value+"_ctrl"))})]})]}),ze.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>d(!1),"aria-label":"Close",children:"×"})]})}),$i&&ze.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"rgba(0,0,0,0.5)",zIndex:2e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>Ir(!1),children:ze.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",maxWidth:"80vw",maxHeight:"80vh",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative",overflow:"auto"},onClick:z=>z.stopPropagation(),children:[ze.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"DICOM Metadata"}),yc,ze.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>Ir(!1),"aria-label":"Close",children:"×"})]})})]})}function c8e(t){console.log("Setting up tools...",t),xi(ef),xi(Mh),xi(Ld),xi(Wl),xi(Ph),xi(pf),xi(su),xi(mf),xi(au),xi(Ad),xi(gf),xi(sl),xi(Rh),xi(La),xi(Uc),xi(pd),xi(Nh);let e=jr(t);return e||(e=xF(t),e.addTool(Mh.toolName),e.addTool(ef.toolName),e.addTool(Wl.toolName),e.addTool(Ld.toolName,{loop:!1}),e.addTool(Ph.toolName),e.addTool(pf.toolName),e.addTool(Nh.toolName,{getTextCallback:()=>""}),e.addTool(mf.toolName),e.addTool(su.toolName,{statsCalculator:()=>null}),e.addTool(au.toolName,{calculateStats:!1,getTextCallback:()=>""}),e.addTool(Ad.toolName,{getTextCallback:()=>""}),e.addTool(gf.toolName,{calculateStats:!1}),e.addTool(sl.toolName,{}),e.addTool(Rh.toolName,{}),e.addTool(pd.toolName),e.addTool(La.toolName)),e}function Q7(t,e,r,n){if(!r.length||!e.length)return null;const i=r.map(o=>e.findIndex(a=>a===o.metadata.referencedImageId)).filter(o=>o!==-1).sort((o,a)=>o-a);if(!i.length)return null;if(n===1){for(let o of i)if(o>t)return o;return i[0]}else{for(let o=i.length-1;o>=0;o--)if(i[o]`wadouri:/test_images/stack2/IMG${r+1}.dcm`),Array.from({length:25},(e,r)=>`wadouri:/test_images/stack5/IMG${r+1}.dcm`),Array.from({length:26},(e,r)=>`wadouri:/test_images/stack3/IMG${r+1}.dcm`)]}const t3=new WeakMap,u8e=t=>{const e=t.trim();return!e||e.startsWith("external:")||e.startsWith("wadors:")?e:e.startsWith("wadouri:")?`wadouri:${e.slice(8).replace(/^:+/,"")}`:`wadouri:${e.replace(/^:+/,"")}`},W1=t=>t.map(u8e),eO=t=>t?{imageIds:W1(t)}:{imageIds:[]},f8e=t=>{if(!t)return[];if(Array.isArray(t)&&t.length>0&&typeof t[0]=="string")return[eO(t)];if(!Array.isArray(t))return[];const e=[];return t.forEach((r,n)=>{if(r&&typeof r=="object"&&Array.isArray(r.stacks)){const i=r.caseId||r.caseUID||r.case||void 0,o=r.studyId||r.studyUID||r.studyInstanceUID||void 0;r.stacks.forEach((a,s)=>{let c=[];if(Array.isArray(a)?c=a:Array.isArray(a.imageIds)?c=a.imageIds:Array.isArray(a.i)&&(c=a.i),!Array.isArray(c)||c.length===0||!c.every(l=>typeof l=="string")){console.warn(`data-named-stacks: skipping invalid nested stack at parsed[${n}].stacks[${s}]`,a);return}e.push({imageIds:W1(c),name:a.name||a.label||void 0,caseId:i,studyId:a.studyId||o})});return}if(r&&typeof r=="object"&&(Array.isArray(r.imageIds)||Array.isArray(r.i))){const i=Array.isArray(r.imageIds)?r.imageIds:r.i;if(!Array.isArray(i)||i.length===0||!i.every(o=>typeof o=="string")){console.warn(`data-named-stacks: skipping invalid stack object at parsed[${n}]`,r);return}e.push({imageIds:W1(i),name:r.name||r.label||void 0,caseId:r.caseId||r.caseUID||void 0,studyId:r.studyId||r.studyUID||r.studyInstanceUID||void 0});return}if(Array.isArray(r)&&r.length>0&&typeof r[0]=="string"){e.push(eO(r));return}console.warn(`data-named-stacks: unknown or invalid entry at parsed[${n}] — skipping`,r)}),e},d8e=t=>JSON.stringify({id:t.id||"",empty:t.getAttribute("data-empty")||"",namedStacks:t.getAttribute("data-named-stacks")||"",images:t.getAttribute("data-images")||"",autoCache:t.getAttribute("data-auto-cache-stack")||"",annotation:t.getAttribute("data-annotationjson")||"",viewerState:t.getAttribute("data-viewerstate")||""}),tO=(t,e)=>!(e!=null&&e.containerIds)||e.containerIds.length===0?!0:e.containerIds.includes(t.id||""),nO=(t,e,r)=>{const n=d8e(t),i=t3.get(t);if(i&&!(r!=null&&r.force)&&i.signature===n)return;i&&(i.root.unmount(),t3.delete(t));const o=pP(t);o.render(ze.jsx(s8e,{container_id:t.id||"",imageStacks:e,autoCacheStack:t.getAttribute("data-auto-cache-stack")==="true"||t.getAttribute("data-auto-cache-stack")==="1",annotationJson:t.getAttribute("data-annotationjson")||void 0,viewerState:t.getAttribute("data-viewerstate")||void 0})),t3.set(t,{root:o,signature:n})};function eb(t){document.querySelectorAll(".dicom-viewer-test-root").forEach(n=>{if(!tO(n,t))return;n.id,nO(n,()=>l8e(),t)}),document.querySelectorAll(".dicom-viewer-root").forEach(n=>{if(!tO(n,t))return;let i;const o=n.getAttribute("data-empty")==="true",a=n.getAttribute("data-named-stacks"),s=n.getAttribute("data-images");if(o)i=()=>Promise.resolve([]);else if(a){let c;try{c=JSON.parse(a)}catch(f){console.error("Invalid data-named-stacks JSON:",f),c=[]}const l=f8e(c);i=()=>Promise.resolve(l)}else if(s){let c;try{c=JSON.parse(s)}catch(l){console.error("Invalid data-images JSON:",l),c=[]}Array.isArray(c)&&c.length>0&&typeof c[0]=="string"?i=()=>Promise.resolve([W1(c)]):Array.isArray(c)?i=()=>Promise.resolve(c.map(l=>Array.isArray(l)?W1(l):[])):i=()=>Promise.resolve([[]])}else i=()=>Promise.resolve([]);nO(n,i,t)})}eb();window.mountDicomViewers=eb;window.remountDicomViewer=t=>{eb({force:!0,containerIds:[t]})}; +`,ht.push(rt);var Gn=Ya(Function,ht).apply(null,zt);return Gn}function ji(W,$,R,V,Y,ye){_($>0);var xe=oi($,R);Y=Vn(V,Y),Bi([],[W],function(Ce){Ce=Ce[0];var Te="constructor "+Ce.name;if(Ce.registeredClass.constructor_body===void 0&&(Ce.registeredClass.constructor_body=[]),Ce.registeredClass.constructor_body[$-1]!==void 0)throw new Ct("Cannot register multiple constructors with identical number of parameters ("+($-1)+") for class '"+Ce.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return Ce.registeredClass.constructor_body[$-1]=()=>{Mr("Cannot construct "+Ce.name+" due to unbound types",xe)},Bi([],xe,function(Me){return Me.splice(1,0,null),Ce.registeredClass.constructor_body[$-1]=Sn(Te,Me,null,Y,ye),[]}),[]})}function Ea(W,$,R,V,Y,ye,xe,Ce){var Te=oi(R,V);$=Bn($),ye=Vn(Y,ye),Bi([],[W],function(Me){Me=Me[0];var Ae=Me.name+"."+$;$.startsWith("@@")&&($=Symbol[$.substring(2)]),Ce&&Me.registeredClass.pureVirtualFunctions.push($);function qe(){Mr("Cannot call "+Ae+" due to unbound types",Te)}var rt=Me.registeredClass.instancePrototype,mt=rt[$];return mt===void 0||mt.overloadTable===void 0&&mt.className!==Me.name&&mt.argCount===R-2?(qe.argCount=R-2,qe.className=Me.name,rt[$]=qe):($i(rt,$,Ae),rt[$].overloadTable[R-2]=qe),Bi([],Te,function(ht){var zt=Sn(Ae,ht,Me,ye,xe);return rt[$].overloadTable===void 0?(zt.argCount=R-2,rt[$]=zt):rt[$].overloadTable[R-2]=zt,[]}),[]})}var ba=[],Oi=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function bs(W){W>4&&--Oi[W].refcount===0&&(Oi[W]=void 0,ba.push(W))}function na(){for(var W=0,$=5;$(W||Zt("Cannot use deleted val. handle = "+W),Oi[W].value),toHandle:W=>{switch(W){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var $=ba.length?ba.pop():Oi.length;return Oi[$]={refcount:1,value:W},$}}}};function Sc(W,$){$=Bn($),ar(W,{name:$,fromWireType:function(R){var V=Da.toValue(R);return bs(R),V},toWireType:function(R,V){return Da.toHandle(V)},argPackAdvance:8,readValueFromPointer:br,destructorFunction:null})}function Ja(W){if(W===null)return"null";var $=typeof W;return $==="object"||$==="array"||$==="function"?W.toString():""+W}function pl(W,$){switch($){case 2:return function(R){return this.fromWireType(ee[R>>2])};case 3:return function(R){return this.fromWireType(ce[R>>3])};default:throw new TypeError("Unknown float type: "+W)}}function ml(W,$,R){var V=fo(R);$=Bn($),ar(W,{name:$,fromWireType:function(Y){return Y},toWireType:function(Y,ye){return ye},argPackAdvance:8,readValueFromPointer:pl($,V),destructorFunction:null})}function vl(W,$,R,V,Y,ye){var xe=oi($,R);W=Bn(W),Y=Vn(V,Y),Ir(W,function(){Mr("Cannot call "+W+" due to unbound types",xe)},$-1),Bi([],xe,function(Ce){var Te=[Ce[0],null].concat(Ce.slice(1));return ta(W,Sn(W,Te,null,Y,ye),$-1),[]})}function yl(W,$,R){switch($){case 0:return R?function(Y){return B[Y]}:function(Y){return H[Y]};case 1:return R?function(Y){return A[Y>>1]}:function(Y){return F[Y>>1]};case 2:return R?function(Y){return G[Y>>2]}:function(Y){return X[Y>>2]};default:throw new TypeError("Unknown integer type: "+W)}}function wl(W,$,R,V,Y){$=Bn($);var ye=fo(R),xe=qe=>qe;if(V===0){var Ce=32-8*R;xe=qe=>qe<>>Ce}var Te=$.includes("unsigned"),Me=(qe,rt)=>{},Ae;Te?Ae=function(qe,rt){return Me(rt,this.name),rt>>>0}:Ae=function(qe,rt){return Me(rt,this.name),rt},ar(W,{name:$,fromWireType:xe,toWireType:Ae,argPackAdvance:8,readValueFromPointer:yl($,ye,V!==0),destructorFunction:null})}function Ds(W,$,R){var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Y=V[$];function ye(xe){xe=xe>>2;var Ce=X,Te=Ce[xe],Me=Ce[xe+1];return new Y(L,Me,Te)}R=Bn(R),ar(W,{name:R,fromWireType:ye,argPackAdvance:8,readValueFromPointer:ye},{ignoreDuplicateRegistrations:!0})}function xl(W,$){$=Bn($);var R=$==="std::string";ar(W,{name:$,fromWireType:function(V){var Y=X[V>>2],ye=V+4,xe;if(R)for(var Ce=ye,Te=0;Te<=Y;++Te){var Me=ye+Te;if(Te==Y||H[Me]==0){var Ae=Me-Ce,qe=D(Ce,Ae);xe===void 0?xe=qe:(xe+="\0",xe+=qe),Ce=Me+1}}else{for(var rt=new Array(Y),Te=0;Te>2]=ye,R&&xe)P(Y,Te,ye+1);else if(xe)for(var Me=0;Me255&&(De(Te),Zt("String has UTF-16 code units that do not fit in 8 bits")),H[Te+Me]=Ae}else for(var Me=0;Me>1,Y=V+$/2;!(V>=Y)&&F[V];)++V;if(R=V<<1,R-W>32&&Is)return Is.decode(H.subarray(W,R));for(var ye="",xe=0;!(xe>=$/2);++xe){var Ce=A[W+xe*2>>1];if(Ce==0)break;ye+=String.fromCharCode(Ce)}return ye}function Os(W,$,R){if(R===void 0&&(R=2147483647),R<2)return 0;R-=2;for(var V=$,Y=R>1]=xe,$+=2}return A[$>>1]=0,$-V}function Ms(W){return W.length*2}function Tc(W,$){for(var R=0,V="";!(R>=$/4);){var Y=G[W+R*4>>2];if(Y==0)break;if(++R,Y>=65536){var ye=Y-65536;V+=String.fromCharCode(55296|ye>>10,56320|ye&1023)}else V+=String.fromCharCode(Y)}return V}function Za(W,$,R){if(R===void 0&&(R=2147483647),R<4)return 0;for(var V=$,Y=V+R-4,ye=0;ye=55296&&xe<=57343){var Ce=W.charCodeAt(++ye);xe=65536+((xe&1023)<<10)|Ce&1023}if(G[$>>2]=xe,$+=4,$+4>Y)break}return G[$>>2]=0,$-V}function Ps(W){for(var $=0,R=0;R=55296&&V<=57343&&++R,$+=4}return $}function Rs(W,$,R){R=Bn(R);var V,Y,ye,xe,Ce;$===2?(V=Cl,Y=Os,xe=Ms,ye=()=>F,Ce=1):$===4&&(V=Tc,Y=Za,xe=Ps,ye=()=>X,Ce=2),ar(W,{name:R,fromWireType:function(Te){for(var Me=X[Te>>2],Ae=ye(),qe,rt=Te+4,mt=0;mt<=Me;++mt){var ht=Te+4+mt*$;if(mt==Me||Ae[ht>>Ce]==0){var zt=ht-rt,Ut=V(rt,zt);qe===void 0?qe=Ut:(qe+="\0",qe+=Ut),rt=ht+$}}return De(Te),qe},toWireType:function(Te,Me){typeof Me!="string"&&Zt("Cannot pass non-string to C++ string type "+R);var Ae=xe(Me),qe=ae(4+Ae+$);return X[qe>>2]=Ae>>Ce,Y(Me,qe+4,Ae+$),Te!==null&&Te.push(De,qe),qe},argPackAdvance:8,readValueFromPointer:br,destructorFunction:function(Te){De(Te)}})}function Qa(W,$,R,V,Y,ye){xn[W]={name:Bn($),rawConstructor:Vn(R,V),rawDestructor:Vn(Y,ye),fields:[]}}function _c(W,$,R,V,Y,ye,xe,Ce,Te,Me){xn[W].fields.push({fieldName:Bn($),getterReturnType:R,getter:Vn(V,Y),getterContext:ye,setterArgumentType:xe,setter:Vn(Ce,Te),setterContext:Me})}function Ls(W,$){$=Bn($),ar(W,{isVoid:!0,name:$,argPackAdvance:0,fromWireType:function(){},toWireType:function(R,V){}})}function Ec(W){W>4&&(Oi[W].refcount+=1)}function As(W,$){var R=ut[W];return R===void 0&&Zt($+" has unknown type "+Qr(W)),R}function bc(W,$){W=As(W,"_emval_take_value");var R=W.readValueFromPointer($);return Da.toHandle(R)}function Dc(){je("")}function Ic(W,$,R){H.copyWithin(W,$,$+R)}function Oc(){return 2147483648}function es(W){try{return S.grow(W-L.byteLength+65535>>>16),Se(S.buffer),1}catch{}}function ts(W){var $=H.length;W=W>>>0;var R=Oc();if(W>R)return!1;let V=(Te,Me)=>Te+(Me-Te%Me)%Me;for(var Y=1;Y<=4;Y*=2){var ye=$*(1+.2/Y);ye=Math.min(ye,W+100663296);var xe=Math.min(R,V(Math.max(W,ye),65536)),Ce=es(xe);if(Ce)return!0}return!1}function vo(W){return 52}function Bo(W,$,R,V,Y){return 70}var Hi=[null,[],[]];function Ns(W,$){var R=Hi[W];$===0||$===10?((W===1?w:x)(b(R,0)),R.length=0):R.push($)}function ks(W,$,R,V){for(var Y=0,ye=0;ye>2],Ce=X[$+4>>2];$+=8;for(var Te=0;Te>2]=Y,0}function ns(W){return W}function Vs(W){var $=o["_"+W];return $}function Ia(W,$){B.set(W,$)}function Fs(W,$,R,V,Y){var ye={string:ht=>{var zt=0;if(ht!=null&&ht!==0){var Ut=(ht.length<<2)+1;zt=le(Ut),P(ht,zt,Ut)}return zt},array:ht=>{var zt=le(ht.length);return Ia(ht,zt),zt}};function xe(ht){return $==="string"?D(ht):$==="boolean"?!!ht:ht}var Ce=Vs(W),Te=[],Me=0;if(V)for(var Ae=0;Ae0||(Ne(),re>0))return;function $(){be||(be=!0,o.calledRun=!0,!T&&(j(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),M()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),$()},1)):$()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Oe(),o.ready}})();t.exports=r})(m$);var BEe=m$.exports;const GEe=ll(BEe),WEe=new URL("/static/dv3d/openjphjs.wasm",import.meta.url),op={codec:void 0,decoder:void 0,decodeConfig:{}};function zEe(t,e,r){const n={width:e,height:r};for(;t>0;)n.width=Math.ceil(n.width/2),n.height=Math.ceil(n.height/2),t--;return n}function $Ee(t){if(op.decodeConfig=t,op.codec)return Promise.resolve();const e=GEe({locateFile:r=>r.endsWith(".wasm")?WEe.toString():r});return new Promise((r,n)=>{e.then(i=>{op.codec=i,op.decoder=new i.HTJ2KDecoder,r()},n)})}async function jEe(t,e){await $Ee();const r=new op.codec.HTJ2KDecoder,n=r.getEncodedBuffer(t.length);n.set(t);const i=e.decodeLevel||0;r.decodeSubResolution(i);const o=r.getFrameInfo();if(e.decodeLevel>0){const{width:E,height:b}=zEe(e.decodeLevel,o.width,o.height);o.width=E,o.height=b}const a=r.getDecodedBuffer();new Uint8Array(a.length).set(a);const c=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,l=r.getNumDecompositions(),f=r.getNumLayers(),u=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],d=r.getIsReversible(),h=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,g=`${r.getTileSize().width} x ${r.getTileSize().height}`,p=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,v=`${a.length.toLocaleString()} bytes`,y=`${(a.length/n.length).toFixed(2)}:1`,m={columns:o.width,rows:o.height,bitsPerPixel:o.bitsPerSample,signed:o.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:o.componentCount};let w=HEe(o,a);const{buffer:x,byteOffset:C,byteLength:S}=w,T=x.slice(C,C+S);w=new w.constructor(T);const _={imageOffset:c,numDecompositions:l,numLayers:f,progessionOrder:u,reversible:d,blockDimensions:h,tileSize:g,tileOffset:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:_,..._,...m}}function HEe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function KEe(t,e){const r=t.length,{rescaleSlope:n,rescaleIntercept:i,suvbw:o,doseGridScaling:a}=e;if(e.modality==="PT"&&typeof o=="number"&&!isNaN(o))for(let s=0;s>o;let a=t.pixelData;t.pixelDataLength=t.pixelData.length;const{min:s,max:c}=ax(t.pixelData),l=typeof e.allowFloatRendering<"u"?e.allowFloatRendering:!0;let f=q8(t.photometricInterpretation)&&((m=e.targetBuffer)==null?void 0:m.offset)===void 0;const d=((w=e.preScale)==null?void 0:w.enabled)&&Object.values(e.preScale.scalingParameters).some(C=>typeof C=="number"&&!Number.isInteger(C)),h=!e.preScale.enabled||!l&&d,g=(x=e.targetBuffer)==null?void 0:x.type;if(g&&e.preScale.enabled&&!h){const C=e.preScale.scalingParameters,S=PT(s,c,C);f=!D4e(S.min,S.max,j7[g])}g&&!f?a=JEe(e,t,j7,a):e.preScale.enabled&&!h?a=ZEe(e,s,c,t):a=v$(s,c,t);let p=s,v=c;if(e.preScale.enabled&&!h){const C=e.preScale.scalingParameters;if(y$(C),YEe(C)){KEe(a,C),t.preScale={...e.preScale,scaled:!0};const T=PT(s,c,C);p=T.min,v=T.max}}else h&&(t.preScale={enabled:!0,scaled:!1},p=s,v=c);t.pixelData=a,t.smallestPixelValue=p,t.largestPixelValue=v;const y=new Date().getTime();return t.decodeTimeInMS=y-r,t}function YEe(t){const{rescaleSlope:e,rescaleIntercept:r,modality:n,doseGridScaling:i,suvbw:o}=t;return typeof e=="number"&&typeof r=="number"||n==="RTDOSE"&&typeof i=="number"||n==="PT"&&typeof o=="number"}function JEe(t,e,r,n){const{arrayBuffer:i,type:o,offset:a=0,length:s,rows:c}=t.targetBuffer,l=r[o];if(!l)throw new Error(`target array ${o} is not supported, or doesn't exist.`);c&&c!=e.rows&&e8e(e,t.targetBuffer,l);const f=e.pixelDataLength,u=a,d=s??f-u,h=e.pixelData;if(d!==h.length)throw new Error(`target array for image does not have the same length (${d}) as the decoded image length (${h.length}).`);const g=i?new l(i,u,d):new l(d);return g.set(h,0),n=g,n}function ZEe(t,e,r,n){const i=t.preScale.scalingParameters;y$(i);const o=PT(e,r,i);return v$(o.min,o.max,n)}function v$(t,e,r){const n=X8(t,e),i=new n(r.pixelData.length);return i.set(r.pixelData,0),i}function PT(t,e,r){const{rescaleSlope:n,rescaleIntercept:i,modality:o,doseGridScaling:a,suvbw:s}=r;return o==="PT"&&typeof s=="number"&&!isNaN(s)?{min:s*(t*n+i),max:s*(e*n+i)}:o==="RTDOSE"&&typeof a=="number"&&!isNaN(a)?{min:t*a,max:e*a}:typeof n=="number"&&typeof i=="number"?{min:n*t+i,max:n*e+i}:{min:t,max:e}}function y$(t){if(!t)throw new Error("options.preScale.scalingParameters must be defined if preScale.enabled is true, and scalingParameters cannot be derived from the metadata providers.")}function QEe(t,e,r){const{samplesPerPixel:n}=t,{rows:i,columns:o}=e,a=i*o*n,s=new r(a),c=s.byteLength/a;return{pixelData:s,rows:i,columns:o,frameInfo:{...t.frameInfo,rows:i,columns:o},imageInfo:{...t.imageInfo,rows:i,columns:o,bytesPerPixel:c}}}function e8e(t,e,r){const n=QEe(t,e,r),{scalingType:i="replicate"}=e;return qEe[i](t,n),Object.assign(t,n),t.pixelDataLength=t.pixelData.length,t}async function w$(t,e,r,n,i,o){const a=new Date().getTime();let s=null,c;switch(e){case"1.2.840.10008.1.2":case"1.2.840.10008.1.2.1":s=B7(t,r);break;case"1.2.840.10008.1.2.2":s=hEe(t,r);break;case"1.2.840.10008.1.2.1.99":s=B7(t,r);break;case"1.2.840.10008.1.2.5":s=gEe(t,r);break;case"1.2.840.10008.1.2.4.50":c={...t},s=SEe(r,c);break;case"1.2.840.10008.1.2.4.51":s=DEe(t,r);break;case"1.2.840.10008.1.2.4.57":s=W7(t,r);break;case"1.2.840.10008.1.2.4.70":s=W7(t,r);break;case"1.2.840.10008.1.2.4.80":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=z7(r,c);break;case"1.2.840.10008.1.2.4.81":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=z7(r,c);break;case"1.2.840.10008.1.2.4.90":c={...t},s=$7(r,c);break;case"1.2.840.10008.1.2.4.91":c={...t},s=$7(r,c);break;case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":c={...t},s=jEe(r,c);break;default:throw new Error(`no decoder for transfer syntax ${e}`)}if(!s)throw new Error("decodePromise not defined");const l=await s,f=XEe(l,i,a);return o==null||o(f),f}const t8e={decodeTask({imageFrame:t,transferSyntax:e,decodeConfig:r,options:n,pixelData:i,callbackFn:o}){return w$(t,e,i,r,n,o)}};I4(t8e);const Il={constants:lEe,convertRGBColorByPixel:Iz,convertRGBColorByPlane:Oz,convertYBRFullByPixel:Mz,convertYBRFullByPlane:Pz,convertPALETTECOLOR:Rz,wadouri:R4e,wadors:rEe,init:f$,convertColorSpace:Jz,createImage:sx,decodeJPEGBaseline8BitColor:Zz,getImageFrame:Qz,getPixelData:Q8,getMinMax:ax,isColorImage:q8,isJPEGBaseline8BitColor:sEe,internal:K_e,decodeImageFrame:w$};class Nh extends mf{}xb(Nh,"toolName","NoLabelArrowAnnotate");function H7(t,e){const r=ct("imagePlaneModule",t);if(!r)return;const{rowCosines:n,columnCosines:i,imagePositionPatient:o,rowPixelSpacing:a,columnPixelSpacing:s}=r;if(!n||!i||!o)return;const c=s||1,l=a||1,f=n,u=i,d=o;return[d[0]+e.x*u[0]*c+e.y*f[0]*l,d[1]+e.x*u[1]*c+e.y*f[1]*l,d[2]+e.x*u[2]*c+e.y*f[2]*l]}window.cornerstone3dTools=Dz;window.cornerstone3d=jhe;window.cornerstoneDICOMImageLoader=Il;const{MouseBindings:Fg,KeyboardBindings:K7}=lF,{IMAGE_RENDERED:Ug}=et,n8e=[{name:"Soft Tissue",center:40,width:400},{name:"Lung",center:-600,width:1500},{name:"Bone",center:300,width:1500},{name:"Brain",center:40,width:80},{name:"Abdomen",center:60,width:400}],q7=t=>{const e=(t||"").toUpperCase(),r=[{name:"Reset to default",action:"reset"},{name:"Auto level",action:"autolevel"}];return e!=="CT"?r:[...r,...n8e.map(n=>({name:n.name,action:"preset",center:n.center,width:n.width}))]},l0=[{label:"Window/Level",value:Mh.toolName,icon:"🌓"},{label:"Pan",value:ef.toolName,icon:"✋"},{label:"Zoom",value:Wl.toolName,icon:"🔍"},{label:"Stack Scroll",value:Ld.toolName,icon:"📚"},{label:"Rotate",value:Ph.toolName,icon:"↺"},{label:"Length",value:pf.toolName,icon:"📏"},{label:"Probe",value:su.toolName,icon:"🔎"},{label:"Arrow (No Label)",value:Nh.toolName,icon:"➡️"},{label:"Arrow Annotate",value:mf.toolName,icon:"✈️"},{label:"Rectangle ROI",value:au.toolName,icon:"▭"},{label:"Ellipse ROI",value:Ad.toolName,icon:"◯"},{label:"Freehand ROI",value:gf.toolName,icon:"✏️"},{label:"Freehand Contour Segmentation",value:sl.toolName,icon:"🖊️"},{label:"Sculptor",value:Rh.toolName,icon:"🔧"},{label:"Reference Cursors",value:La.toolName,icon:"⦿"}],r8e=3,i8e=220;function o8e(t){if(!t)return"🔖";const e=l0.find(r=>r.value===t||r.label===t);return(e==null?void 0:e.icon)||"🔖"}function zs(t){return t?t.startsWith("wadouri:")?t.replace(/^wadouri:+/,"").replace(/^:+/,""):t:""}function RT(t){return/([?&])frame=\d+/i.test(t)}function X7(t,e){const r=Math.max(1,Math.floor(e));return RT(t)?t.replace(/([?&])frame=\d+/i,`$1frame=${r}`):`${t}&frame=${r}`}function Y7(t){const e=t.match(/[?&]frame=(\d+)/i);if(!e)return null;const r=Number(e[1]);return Number.isFinite(r)&&r>0?Math.floor(r):null}function J7(t){return t?t.split(/\\|,/).map(e=>Number(e.trim())).filter(e=>Number.isFinite(e)):[]}function a0(t){return t.startsWith("wadouri:")||t.startsWith("external:")?t:`wadouri:${t}`}function e3(t){const e=new Set,r=[];for(const n of t)!n||e.has(n)||(e.add(n),r.push(n));return r}function a8e(t){try{const e=t.getContext("2d",{willReadFrequently:!0});if(!e)return!0;const r=t.width||160,n=t.height||160,o=e.getImageData(0,0,r,n).data;let a=255,s=0,c=0,l=0;for(let d=0;d0&&w>12&&(c+=1),a=Math.min(a,w),s=Math.max(s,w),l+=1}if(l===0)return!0;const f=c/l,u=s-a;return f>.015||u>8}catch{return!0}}const Z7=[{label:"Left",value:"Primary"},{label:"Middle",value:"Auxiliary"},{label:"Right",value:"Secondary"}],ev=[{label:"Left",value:"Primary",mask:1},{label:"Middle",value:"Auxiliary",mask:4},{label:"Right",value:"Secondary",mask:2},{label:"Left + Right",value:"Primary_and_Secondary",mask:3},{label:"Left + Middle",value:"Primary_and_Auxiliary",mask:5},{label:"Right + Middle",value:"Secondary_and_Auxiliary",mask:6},{label:"Left + Right + Middle",value:"Primary_and_Secondary_and_Auxiliary",mask:7},{label:"Fourth Button",value:"Fourth_Button",mask:8},{label:"Fifth Button",value:"Fifth_Button",mask:16},{label:"Mouse Wheel",value:"Wheel",mask:524288},{label:"Mouse Wheel + Left",value:"Wheel_Primary",mask:524289}];function s8e({container_id:t,imageStacks:e,autoCacheStack:r,annotationJson:n,viewerState:i,...o}){var Ms,Tc,Za,Ps,Rs,Qa,_c,Ls,Ec,As,bc,Dc,Ic,Oc,es,ts,vo,Bo,Hi,Ns,ks,ns,Vs,Ia,Fs,oe,ae,De,He,tt;const a=st.useRef(null),s=st.useRef(null),c=st.useRef(!1),l="dv3d_mouseToolBindings",f="dv3d_ctrlMouseToolBindings",[u,d]=st.useState(!1),[h,g]=st.useState(!1),[p,v]=st.useState(320),y=`dv3d_stackPanelWidth_${t||"default"}`,m=st.useRef({resizing:!1,startX:0,startWidth:320}),w=240,x=720,C=220,S=40,T=14,_=st.useRef(null),[E,b]=st.useState(null),[D,I]=st.useState(null),[P,O]=st.useState(!1),L=9,B="renderingEngine_"+t,H="TOOL_GROUP_"+t,A=st.useRef(null),F=st.useRef(!1),[G,X]=st.useState(!0),[ee,ce]=st.useState(!1),[Se,we]=st.useState([]),[_e,Ve]=st.useState(0),[Ge,Ne]=st.useState(null),[j,M]=st.useState(!1),[q,K]=st.useState(null),[J,re]=st.useState(()=>Array(L).fill([])),ie=z=>{typeof z=="function"?re(ne=>{const he=z(ne);return console.log("setViewportImageIds (fn):",he),he}):(console.log("setViewportImageIds:",z),re(z))},[Re,Fe]=st.useState(()=>Array(L).fill(0)),[je,Xe]=st.useState(()=>Array(L).fill(null).map(()=>[])),[se,ue]=st.useState(()=>Array(L).fill(0)),[Pe,pe]=st.useState(()=>Array(L).fill(!1)),[Ee,Qe]=st.useState(()=>Array(L).fill(12)),[fe,ft]=st.useState(()=>Array(L).fill(!1)),pt=st.useRef({}),dt=st.useRef({}),[Ue,nt]=st.useState({}),at=st.useRef({}),ot=st.useRef({}),lt=st.useCallback((z,ne)=>{nt(he=>{const le=he[z];if(le&&le!==ne&&le.startsWith("blob:"))try{URL.revokeObjectURL(le)}catch{}const Q={...he,[z]:ne};return at.current=Q,Q})},[]);st.useEffect(()=>{at.current=Ue},[Ue]),st.useEffect(()=>()=>{Object.values(at.current).forEach(z=>{if(typeof z=="string"&&z.startsWith("blob:"))try{URL.revokeObjectURL(z)}catch{}})},[]),st.useEffect(()=>{try{const z=localStorage.getItem(y);if(z){const ne=Number(z);Number.isNaN(ne)||v(Math.max(w,Math.min(x,Math.round(ne))))}}catch{}},[y]),st.useEffect(()=>{try{localStorage.setItem(y,String(Math.round(p)))}catch{}},[y,p]);function _t(z){if(!z)return null;try{if(z.tagName&&z.tagName.toLowerCase()==="canvas")return z}catch{}try{const ne=z.querySelector&&z.querySelector("canvas");if(ne)return ne}catch{}try{const ne=z.children||[];for(let he=0;heMath.min(rt,Math.max(qe,Ae)),Ie=()=>{ne.style.transform=`translate(${ge}px, ${me}px) scale(${de})`};let ke=!0,be=!0;const Oe=Ae=>{if(!be)return;Ae.preventDefault();const qe=ne.getBoundingClientRect(),rt=Ae.clientX-qe.left,mt=Ae.clientY-qe.top,ht=-Ae.deltaY,zt=1+(ht>0?.1:-.1)*Math.min(4,Math.abs(ht)/100),Ut=ve(de*zt,.1,10);ge=(ge-rt)*(Ut/de)+rt,me=(me-mt)*(Ut/de)+mt,de=Ut,Ie()},W=Ae=>{Ae.button===0&&ke&&(N=!0,k=Ae.clientX,te=Ae.clientY,ne.style.cursor="grabbing",Ae.preventDefault())},$=Ae=>{if(!N)return;const qe=Ae.clientX-k,rt=Ae.clientY-te;ge+=qe,me+=rt,k=Ae.clientX,te=Ae.clientY,Ie()},R=Ae=>{N&&(N=!1,ne.style.cursor="grab")},V=Ae=>{de=1,ge=0,me=0,Ie()};let Y=0;const ye=(Ae,qe)=>Math.hypot(qe.clientX-Ae.clientX,qe.clientY-Ae.clientY),xe=Ae=>{Ae.touches.length===1?ke&&(N=!0,k=Ae.touches[0].clientX,te=Ae.touches[0].clientY):Ae.touches.length===2&&(Y=ye(Ae.touches[0],Ae.touches[1]))},Ce=Ae=>{if(Ae.touches.length===1&&N){const qe=Ae.touches[0].clientX-k,rt=Ae.touches[0].clientY-te;ge+=qe,me+=rt,k=Ae.touches[0].clientX,te=Ae.touches[0].clientY,Ie()}else if(Ae.touches.length===2&&be){const qe=ye(Ae.touches[0],Ae.touches[1]);if(Y>0){const rt=qe/Y,mt=ne.getBoundingClientRect(),ht=(Ae.touches[0].clientX+Ae.touches[1].clientX)/2-mt.left,zt=(Ae.touches[0].clientY+Ae.touches[1].clientY)/2-mt.top,Ut=ve(de*rt,.1,10);ge=(ge-ht)*(Ut/de)+ht,me=(me-zt)*(Ut/de)+zt,de=Ut,Ie()}Y=qe}Ae.preventDefault()},Te=Ae=>{Ae.touches.length===0&&(N=!1,Y=0)};return z.addEventListener("wheel",Oe,{passive:!1}),z.addEventListener("mousedown",W),window.addEventListener("mousemove",$),window.addEventListener("mouseup",R),ne.addEventListener("dblclick",V),z.addEventListener("touchstart",xe,{passive:!1}),z.addEventListener("touchmove",Ce,{passive:!1}),z.addEventListener("touchend",Te),{cleanup:()=>{z.removeEventListener("wheel",Oe),z.removeEventListener("mousedown",W),window.removeEventListener("mousemove",$),window.removeEventListener("mouseup",R),ne.removeEventListener("dblclick",V),z.removeEventListener("touchstart",xe),z.removeEventListener("touchmove",Ce),z.removeEventListener("touchend",Te),ne.style.transform="",ne.style.cursor="",ne.style.willChange=""},setAllowPan:Ae=>{ke=Ae},setAllowZoom:Ae=>{be=Ae}}}const[Ft,wn]=st.useState(!1),[Dn,Nt]=st.useState(null),[xn,Ui]=st.useState(!1),[br,Ye]=st.useState(null);st.useEffect(()=>{const z=he=>{try{const le=he&&he.message?String(he.message):"";(le.includes("releaseGraphicsResources")||le.includes("openGLTexture")||le.includes("getDefaultActor")||le.includes("setColormapGPU")||le.includes(`can't access property "actor"`)||le.toLowerCase().includes("webgl")||le.toLowerCase().includes("colormap"))&&(console.error("Detected graphics/rendering error:",he),Ye(le||null),Ui(!0))}catch{}},ne=he=>{try{const le=he&&he.reason||"",Q=typeof le=="string"?le:le&&le.message?le.message:String(le);(Q.includes("releaseGraphicsResources")||Q.includes("openGLTexture")||Q.includes("getDefaultActor")||Q.includes("setColormapGPU")||Q.includes(`can't access property "actor"`)||Q.toLowerCase().includes("webgl")||Q.toLowerCase().includes("colormap"))&&(console.error("Detected graphics/rendering rejection:",he),Ye(Q||null),Ui(!0))}catch{}};return window.addEventListener("error",z),window.addEventListener("unhandledrejection",ne),()=>{window.removeEventListener("error",z),window.removeEventListener("unhandledrejection",ne)}},[]),st.useEffect(()=>{let z=!1;if(n||i){Nt(n?"annotations":"viewerState");const ne=setTimeout(()=>{if(z)return;const he=t||"default";if(n)try{const le=window[`importAnnotations_${he}`]||window.importAnnotations;typeof le=="function"&&le(n)}catch(le){console.error("Failed to import annotations from prop:",le)}if(i)try{const le=window[`importViewerState_${he}`]||window.importViewerState;typeof le=="function"&&le(i)}catch(le){console.error("Failed to import viewer state from prop:",le)}Nt(null)},2e3);return()=>{z=!0,clearTimeout(ne),Nt(null)}}},[n,i,t]),st.useEffect(()=>{let z=!0;return e().then(async ne=>{var Q,de;if(!z)return;const he=Array.isArray(ne)?ne:[],le=await Promise.all(he.map(async ge=>{if(Array.isArray(ge)){const ve=await Ei(ge),Ie=await Bn(ve);return{imageIds:ve,seriesGroups:Ie}}const me=Array.isArray(ge.imageIds)?ge.imageIds:Array.isArray(ge.i)?ge.i:[],N=await Ei(me);let k;if(Array.isArray(ge.series)){const Ie=(await Promise.all(ge.series.map(async(ke,be)=>{const Oe=Array.isArray(ke==null?void 0:ke.imageIds)?ke.imageIds:Array.isArray(ke==null?void 0:ke.i)?ke.i:[],W=await Ei(Oe),R=(typeof(ke==null?void 0:ke.name)=="string"?ke.name:"").trim()||`Series ${be+1}`;return{key:String((ke==null?void 0:ke.seriesInstanceUID)||(ke==null?void 0:ke.seriesId)||`SERIES_${be}`),label:R,imageIds:W,seriesInstanceUID:ke==null?void 0:ke.seriesInstanceUID,bValue:Number.isFinite(Number(ke==null?void 0:ke.bValue))?Number(ke.bValue):null}}))).filter(ke=>ke.imageIds.length>0);Ie.length>0&&(k=Ie)}(!k||k.length===0)&&(k=await Bn(N));let te=ge.studyInstanceUID;if(!te&&N.length>0)try{const ve=N[0];if(typeof fetch=="function"&&typeof window.dicomParser<"u"&&ve.startsWith("wadouri:")){const Ie=zs(ve),be=await(await fetch(Ie)).arrayBuffer();te=window.dicomParser.parseDicom(new Uint8Array(be)).string("x0020000d")}}catch{}return{imageIds:N,seriesGroups:k,studyInstanceUID:te,studyId:ge.studyId,name:ge.name,caseId:ge.caseId}}));if(we(le),le[0]){const ge=le[0],me=((de=(Q=ge.seriesGroups)==null?void 0:Q[0])==null?void 0:de.imageIds)||ge.imageIds;await jn(me),ie(Array(L).fill(me||[])),Xe(Array(L).fill(null).map(()=>ge.seriesGroups||[])),ue(Array(L).fill(0))}else ie(Array(L).fill([])),Xe(Array(L).fill(null).map(()=>[])),ue(Array(L).fill(0))}).catch(ne=>{console.error("Failed to load imageStacks:",ne),we([]),ie(Array(L).fill([]))}),()=>{z=!1}},[]);const ut=async(z,ne)=>{var ge;const he=Se[ne];if(!he)return;let le=he.seriesGroups;const Q=he.imageIds;await jn(Q,{force:!0}),(!le||le.length===0)&&(le=await Bn(Q),we(me=>{const N=[...me];return N[ne]?(N[ne]={...N[ne],seriesGroups:le},N):me}));const de=((ge=le[0])==null?void 0:ge.imageIds)||Q;Nt("displayset");try{pi(me=>{const N=[...me];return N[z]="stack",N}),ie(me=>{const N=[...me];return N[z]=de,N}),Fe(me=>{const N=[...me];return N[z]=ne,N}),Xe(me=>{const N=[...me];return N[z]=le||[],N}),ue(me=>{const N=[...me];return N[z]=0,N}),await jn(de)}finally{Nt(null)}},[Rt,mn]=st.useState(!1),[Fr,Lt]=st.useState(!0),[Cn,Yt]=st.useState(!1),[jt,hi]=st.useState(!1),Bi=()=>{console.log("Sorting viewport imageIds by slice location"),ie(z=>{const ne=z.map((he,le)=>{if(!he||he.length===0)return he;const ge=[...he.map(me=>{const N=ct("imagePlaneModule",me);let k=null;return N&&(N.sliceLocation!==void 0?k=Number(N.sliceLocation):N.imagePositionPatient&&Array.isArray(N.imagePositionPatient)&&N.imagePositionPatient.length===3&&(k=Number(N.imagePositionPatient[2]))),{imageId:me,sortKey:k}})].sort((me,N)=>me.sortKey!==null&&N.sortKey!==null?me.sortKey-N.sortKey:me.imageId.localeCompare(N.imageId)).map(me=>me.imageId);return JSON.stringify(ge)===JSON.stringify(he)?he:ge});return wn(!0),ne})},Ao=st.useCallback(async(z,ne,he=0)=>{if(!ne||Ue[z]||ot.current[z])return;if(vt(ne)){try{const ge=new Image;ge.crossOrigin="anonymous";const me=ne.replace(/^external:/,"");ge.src=me,await new Promise((ve,Ie)=>{ge.onload=()=>ve(!0),ge.onerror=ke=>Ie(ke)});const N=document.createElement("canvas"),k=160;N.width=k,N.height=k;const te=N.getContext("2d");if(te){const ve=Math.min(k/ge.width,k/ge.height),Ie=ge.width*ve,ke=ge.height*ve,be=(k-Ie)/2,Oe=(k-ke)/2;te.fillStyle="#000",te.fillRect(0,0,k,k),te.drawImage(ge,be,Oe,Ie,ke),lt(z,N.toDataURL("image/png"))}else lt(z,"BROKEN")}catch{lt(z,"BROKEN")}return}const le=A.current;if(!le)return;ot.current[z]=!0;const Q=`THUMB_${t||"main"}_${z}`,de=document.createElement("div");de.style.width="160px",de.style.height="160px",de.style.position="absolute",de.style.left="-9999px",de.style.top="0",document.body.appendChild(de);try{le.enableElement({viewportId:Q,type:ir.STACK,element:de});const ge=le.getViewport(Q);if(!ge)return;try{ge.setStack([ne])}catch{}await new Promise(N=>{let k=!1;const te=setTimeout(()=>{k||(k=!0,N(!1))},2e3),ve=()=>{k||(k=!0,clearTimeout(te),N(!0))};try{if(ge&&ge.element&&ge.element.addEventListener(Ug,ve,{once:!0}),typeof ge.render=="function")try{const Ie=ge.render();Ie&&typeof Ie.then=="function"&&Ie.catch(()=>{})}catch{}}catch{clearTimeout(te),N(!1)}});let me=_t(de)||(ge&&ge.element?_t(ge.element):null);if(me||(await new Promise(N=>setTimeout(N,150)),me=_t(de)||(ge&&ge.element?_t(ge.element):null)),me){if(!a8e(me)&&he{Ao(z,ne,he+1)},k);return}try{if(typeof me.toBlob=="function"){const k=await new Promise(te=>{me.toBlob(ve=>{if(!ve){te(null);return}te(URL.createObjectURL(ve))},"image/png")});k?lt(z,k):lt(z,me.toDataURL("image/png"))}else lt(z,me.toDataURL("image/png"))}catch{lt(z,"BROKEN")}}else lt(z,"BROKEN")}catch{try{lt(z,"BROKEN")}catch{}}finally{try{le.disableElement(Q)}catch{}de&&de.parentNode&&de.parentNode.removeChild(de)}},[t,Ue,lt]);st.useEffect(()=>{!Se||Se.length===0||!A.current||Se.forEach((ne,he)=>{const le=Array.isArray(ne.imageIds)?ne.imageIds:[],Q=Math.floor(le.length/2),de=le[Q]||le[0]||null;!Ue[he]&&!ot.current[he]&&Ao(he,de)})},[Se,Ao,Ue]);const jn=async(z,ne)=>{console.log("Setting loaded imageIds:",z),console.log("autoCacheStack:",r);const he=[];if(!!(r||ne!=null&&ne.force)){for(const Q of z)if(Q.startsWith("wadouri:"))try{const de=zs(Q);if(Il.wadouri.dataSetCacheManager){const ge=Il.wadouri.dataSetCacheManager.load(de);ge&&typeof ge.then=="function"&&he.push(ge)}else console.warn("MetaDataManager not found. Unable to cache metadata.")}catch(de){console.warn(`Failed to cache metadata for ${Q}:`,de)}await Promise.all(he),Ur&&(console.log("Sorting viewport imageIds by slice location"),Bi())}},fo=st.useCallback(async z=>{var ge;if(!z.startsWith("wadouri:")||RT(z))return 1;const ne=a0(z),he=zs(ne),le=`wadouri:${he}`,Q=pt.current[le];if(Q!==void 0)return Q;const de=me=>{if(!me||typeof me.intString!="function")return 1;const N=Number(me.intString("x00280008"));return Number.isFinite(N)&&N>1?Math.floor(N):1};try{const me=ct("multiframeModule",ne),N=Number(me==null?void 0:me.numberOfFrames);if(Number.isFinite(N)&&N>1)return pt.current[le]=Math.floor(N),Math.floor(N)}catch{}try{const me=(ge=Il==null?void 0:Il.wadouri)==null?void 0:ge.dataSetCacheManager;if(me!=null&&me.get){const N=me.get(he),k=de(N);return pt.current[le]=k,k}}catch{}try{const N=await(await fetch(he)).arrayBuffer(),k=lr.parseDicom(new Uint8Array(N)),te=de(k);return pt.current[le]=te,te}catch{return pt.current[le]=1,1}},[]),Ei=st.useCallback(async z=>{const ne=[];for(const he of z||[]){const le=a0(he);if(!le.startsWith("wadouri:")||RT(le)){ne.push(le);continue}const Q=await fo(le);if(Q<=1){ne.push(le);continue}for(let de=1;de<=Q;de++)ne.push(X7(le,de))}return e3(ne)},[fo]),xa=st.useCallback(async z=>{var de;if(!z.startsWith("wadouri:"))return[];const ne=a0(z),he=zs(ne).replace(/[?&]frame=\d+/i,""),le=dt.current[he];if(le)return le;const Q=ge=>{if(!ge||typeof ge.string!="function")return[];const me=J7(ge.string("x00189087"));if(me.length>0)return me;const N=J7(ge.string("x20011003"));return N.length>0?N:[]};try{const ge=(de=Il==null?void 0:Il.wadouri)==null?void 0:de.dataSetCacheManager;if(ge!=null&&ge.get){const me=ge.get(he),N=Q(me);if(N.length>0)return dt.current[he]=N,N}}catch{}try{const me=await(await fetch(he)).arrayBuffer(),N=lr.parseDicom(new Uint8Array(me)),k=Q(N);return dt.current[he]=k,k}catch{return dt.current[he]=[],[]}},[]),Bn=st.useCallback(async z=>{if(!Array.isArray(z)||z.length===0)return[];const ne=new Map;z.forEach(de=>{const ge=zs(a0(de)).replace(/[?&]frame=\d+/i,""),me=ne.get(ge)||[];me.push(de),ne.set(ge,me)}),ne.forEach((de,ge)=>{de.sort((me,N)=>{const k=Y7(me)||1,te=Y7(N)||1;return k-te}),ne.set(ge,de)});const he=new Map;await Promise.all(Array.from(ne.keys()).map(async de=>{const ge=`wadouri:${de}`,me=await xa(ge);he.set(de,me)}));const le=new Map;return z.forEach(de=>{const ge=ct("generalSeriesModule",de)||{},me=ct("generalImageModule",de)||{},N=ct("mrImageModule",de)||{},k=(ge.seriesInstanceUID||"").trim(),te=(ge.seriesDescription||"").trim(),ve=Number(ge.seriesNumber),Ie=Number(me.temporalPositionIdentifier),ke=Number(me.triggerTime);let be=Number(N.diffusionBValue??N.diffusionbValue??N.bValue),Oe=Number.isFinite(be)?be:null;if(Oe===null){const ye=zs(a0(de)).replace(/[?&]frame=\d+/i,""),xe=he.get(ye)||[];if(xe.length>0){const Ce=ne.get(ye)||[de],Te=Math.max(0,Ce.indexOf(de)),Me=Math.max(1,Ce.length);if(xe.length===1)Oe=xe[0];else if(xe.length===Me)Oe=xe[Math.min(xe.length-1,Te)];else if(xe.length===2&&Me%2===0)Oe=Te{const N=[];ge.seriesDescription&&N.push(ge.seriesDescription),ge.seriesNumber!==void 0&&N.push(`#${ge.seriesNumber}`),ge.bValue!==null&&ge.bValue!==void 0&&N.push(`b=${Math.round(ge.bValue)}`);const k=N.length>0?N.join(" • "):`Series ${me+1}`;return{key:de,label:k,imageIds:e3(ge.imageIds),seriesInstanceUID:ge.seriesInstanceUID,bValue:ge.bValue}})},[xa]),[Ct,Zt]=st.useState({rows:1,cols:1}),[ar,Qo]=st.useState(!1),Dr=st.useRef([]),ho=st.useRef({}),bi=st.useRef({}),[Ur,Cs]=st.useState(!1),[go,Zi]=st.useState(!0),Ca=st.useCallback(z=>{const ne=z.currentTarget.getBoundingClientRect(),he=z.clientX-ne.left,le=z.clientY-ne.top,Q=ne.width,de=ne.height,ge=Math.min(Q,de)*.24,me=[{zone:"left",distance:he},{zone:"right",distance:Q-he},{zone:"top",distance:le},{zone:"bottom",distance:de-le}];return me.sort((N,k)=>N.distance-k.distance),me[0].distance<=ge?me[0].zone:"center"},[]),gi=st.useCallback(z=>z==="left"||z==="right"?Ct.cols<3?z:"center":(z==="top"||z==="bottom")&&Ct.rows<3?z:"center",[Ct]),Sa=[];for(let z=1;z<=3;z++)for(let ne=1;ne<=3;ne++)Sa.push({rows:z,cols:ne});const[ln,Gi]=st.useState(()=>Array(Ct.rows*Ct.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:"",modality:"",orientation:"",resolution:"",spacing:"",focalPoint:""})),[Ss,ea]=st.useState(()=>Array(L).fill(null).map(()=>[])),Qi=st.useRef(Array(L).fill("")),po=st.useRef(Array(L).fill(null)),Zr=st.useRef(Array(L).fill(null)),Di=st.useRef(Array(L).fill(null)),[sn,pi]=st.useState(()=>Array(L).fill("stack")),[No,Wi]=st.useState(()=>Array(Ct.rows*Ct.cols).fill(!1)),[Ii,Ts]=st.useState({Primary:Ld.toolName,Auxiliary:ef.toolName,Secondary:Mh.toolName,Primary_and_Secondary:Wl.toolName,Fourth_Button:Ph.toolName,Wheel:Ld.toolName}),[ko,_s]=st.useState({Primary:pf.toolName,Auxiliary:su.toolName,Secondary:Nh.toolName}),[eo,zi]=st.useState(!1);st.useEffect(()=>{const z=he=>{he.ctrlKey&&zi(!0)},ne=he=>{he.ctrlKey||zi(!1)};return window.addEventListener("keydown",z),window.addEventListener("keyup",ne),()=>{window.removeEventListener("keydown",z),window.removeEventListener("keyup",ne)}},[]);const[$i,Ir]=st.useState(!1),[yc,Vo]=st.useState(null),Fo=(z,ne)=>{qo&&qo(ne),Is(he=>{const le=[...he];return le[z]=ne,le})},yr=(z,ne,he)=>{const le=rr.getAllAnnotations()||[];le.forEach(de=>{de.annotationUID===ne&&(de.isSelected=!1)}),rr.removeAnnotation(ne),A.current.render();const Q=he.filter(de=>de.annotationUID!==ne);Is(de=>{const ge=[...de],me=Q.length>0?Q[0].annotationUID:null;return ge[z]=me,le.forEach(N=>{N.isSelected=N.annotationUID===me}),qo(me),A.current.render(),ge})},wc=()=>{const z=J.findIndex(Q=>Q&&Q.length>0);if(z===-1){Vo("No images loaded."),Ir(!0);return}const ne=J[z][0],he=["imagePlaneModule","generalSeriesModule","generalStudyModule","patientModule","imagePixelModule","voiLutModule","modalityLutModule","sopCommonModule","petIsotopeModule","multiframeModule","cineModule","overlayPlaneModule","generalImageModule","stackModule","voiLutModule","modalityLutModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule"],le={};he.forEach(Q=>{const de=ct(Q,ne);de!==void 0&&(le[Q]=de)}),Vo(ze.jsx("pre",{style:{maxHeight:600,overflow:"auto",fontSize:13,color:"#fff"},children:JSON.stringify(le,null,2)})),Ir(!0)};st.useEffect(()=>{try{const z=localStorage.getItem(l),ne=localStorage.getItem(f);z&&Ts(JSON.parse(z)),ne&&_s(JSON.parse(ne))}catch{}},[]),st.useEffect(()=>{try{localStorage.setItem(l,JSON.stringify(Ii))}catch{}},[Ii]),st.useEffect(()=>{try{localStorage.setItem(f,JSON.stringify(ko))}catch{}},[ko]),st.useEffect(()=>(window.loadDicomStackFromFiles=z=>{const ne=Array.from(z);Ya({target:{files:ne}})},()=>{window.loadDicomStackFromFiles=void 0}),[]),st.useEffect(()=>{const z=()=>{M(!1),K(null),Ne(null)};return document.addEventListener("dragend",z),()=>document.removeEventListener("dragend",z)},[]);const[mi,Or]=st.useState(!1),[qa,mo]=st.useState(!1);st.useEffect(()=>{const z=jr(H);z&&["ArrowAnnotate","NoLabelArrowAnnotate","Length","RectangleROI","EllipticalROI","PlanarFreehandROI","PlanarFreehandContourSegmentation"].forEach(ne=>{z.setToolConfiguration(ne,{color:"#00e676",selectedColor:"#ffeb3b"})})},[H]),st.useEffect(()=>{const z=le=>{le.altKey&&Or(!0),le.shiftKey&&mo(!0)},ne=le=>{le.altKey||Or(!1),le.shiftKey||mo(!1)},he=()=>{Or(!1),mo(!1)};return window.addEventListener("keydown",z),window.addEventListener("keyup",ne),window.addEventListener("blur",he),()=>{window.removeEventListener("keydown",z),window.removeEventListener("keyup",ne),window.removeEventListener("blur",he)}},[]),st.useEffect(()=>{const z=jr(H);if(!z)return;if(qa||go&&mi){const he=Ct.rows*Ct.cols;J.slice(0,he).filter((Q,de)=>sn[de]==="stack"&&Array.isArray(Q)&&Q.length>0).forEach(Q=>{jn(Q,{force:!0}).catch(de=>{console.warn("Reference cursor metadata warm-up failed:",de)})}),z.hasTool(La.toolName)||z.addTool(La.toolName),z.setToolEnabled(La.toolName),z.setToolActive(La.toolName)}else z.hasTool(La.toolName)&&z.setToolDisabled(La.toolName)},[mi,qa,go,Ct.rows,Ct.cols,J,sn,jn]);const ii=st.useCallback(()=>{[jr(H)].forEach(ne=>{if(ne){l0.forEach(le=>{ne.setToolPassive(le.value,{removeAllBindings:!0})}),ne.setToolDisabled(La.toolName);const he={};Object.entries(Ii).forEach(([le,Q])=>{he[Q]||(he[Q]=[]);const de=ev.find(ge=>ge.value===le);de?he[Q].push({mouseButton:de.mask}):Fg[le]&&he[Q].push({mouseButton:Fg[le]})}),Object.entries(ko).forEach(([le,Q])=>{if(!Q)return;he[Q]||(he[Q]=[]);const de=ev.find(ge=>ge.value===le);de?he[Q].push({mouseButton:de.mask,modifierKey:K7.Ctrl}):Fg[le]&&he[Q].push({mouseButton:Fg[le],modifierKey:K7.Ctrl})}),Object.entries(he).forEach(([le,Q])=>{ne.setToolActive(le,{bindings:Q})});try{const le=Ii.Primary,Q=Ii.Wheel,de=Ii.Auxiliary,ge=le===ef.toolName||de===ef.toolName,me=le===Wl.toolName||Q===Wl.toolName||Ii.Primary_and_Secondary===Wl.toolName;Dr.current.forEach(N=>{if(!N)return;const k=N._externalPanZoom;k&&(typeof k.setAllowPan=="function"&&k.setAllowPan(!!ge),typeof k.setAllowZoom=="function"&&k.setAllowZoom(!!me))})}catch{}}})},[Ii,ko]),[ta,Es]=st.useState(!1),[Xa,Ta]=st.useState("add"),Vn=st.useRef(null),_a=st.useCallback(z=>{h&&(z.preventDefault(),z.stopPropagation(),m.current={resizing:!0,startX:z.clientX,startWidth:p},document.body.style.cursor="col-resize",document.body.style.userSelect="none")},[h,p]);st.useEffect(()=>{const z=he=>{if(!m.current.resizing)return;const le=m.current.startX-he.clientX,Q=Math.max(w,Math.min(x,m.current.startWidth+le));v(Q)},ne=()=>{m.current.resizing&&(m.current.resizing=!1,document.body.style.cursor="",document.body.style.userSelect="")};return window.addEventListener("mousemove",z),window.addEventListener("mouseup",ne),()=>{window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",ne),document.body.style.cursor="",document.body.style.userSelect=""}},[]);const Qr=ta?C-S/2:-S+T;st.useEffect(()=>{try{Vn.current&&(Vn.current.setAttribute("webkitdirectory","true"),Vn.current.setAttribute("directory",""),Vn.current.setAttribute("mozdirectory",""))}catch{}},[]);async function Mr(z,ne=""){const he=[],le=z.entries?z.entries():z.values();for await(const Q of le)try{let de,ge;if(Array.isArray(Q)&&Q.length>=2?(ge=Q[0],de=Q[1]):(de=Q,ge=de.name),!de)continue;if(de.kind==="file"){const me=await de.getFile();try{Object.defineProperty(me,"webkitRelativePath",{value:ne+(ge||de.name),configurable:!0})}catch{}he.push(me)}else if(de.kind==="directory"){const me=await Mr(de,ne+(ge||de.name)+"/");he.push(...me)}}catch(de){console.debug("collectFilesFromDirectoryHandle: skipping entry due to error",de)}return he}const xc=async()=>{var z;if(window.showDirectoryPicker)try{const ne=await window.showDirectoryPicker(),he=await Mr(ne);he&&he.length>0?await Ya({target:{files:he}}):alert("No files found in selected folder.");return}catch(ne){console.warn("showDirectoryPicker failed or cancelled",ne)}(z=Vn.current)==null||z.click()},oi=st.useRef(null),Ya=async z=>{const ne=z.target.files;if(!ne||ne.length===0)return;Cs(!1);const he=Array.from(ne).sort((ge,me)=>ge.name.localeCompare(me.name)),le=await Promise.all(he.map(async ge=>{const me=ge.type&&ge.type.startsWith("image/");let N,k,te,ve,Ie=1,ke=!1;if(!me)try{const Oe=await ge.arrayBuffer(),W=lr.parseDicom(new Uint8Array(Oe));N=W.string("x0020000d"),k=W.string("x0020000e");const $=W.string("x00200013");$!=null&&$!==""&&(te=parseInt($,10));const R=W.string("x00201041")||W.string("x00201040");R!=null&&R!==""&&(ve=parseFloat(R));const V=W.string("x00280008");if(V!=null&&V!==""){const Y=Number(V);Number.isFinite(Y)&&Y>1&&(Ie=Math.floor(Y))}ke=!0}catch{ke=!1}const be=me?`external:${URL.createObjectURL(ge)}`:`wadouri:${URL.createObjectURL(ge)}`;return{file:ge,imageId:be,studyInstanceUID:N,seriesInstanceUID:k,instanceNumber:te,sliceLocation:ve,numberOfFrames:Ie,isImage:me,parsedSuccessfully:ke}})),Q=new Map;for(const ge of le){if(!ge.isImage&&!ge.parsedSuccessfully){console.debug("Skipping non-DICOM/non-image file:",ge.file.name);continue}const me=ge.seriesInstanceUID||ge.studyInstanceUID||(ge.file.webkitRelativePath?ge.file.webkitRelativePath.split("/")[0]:ge.file.name);Q.has(me)||Q.set(me,{entries:[],studyInstanceUID:ge.studyInstanceUID,seriesInstanceUID:ge.seriesInstanceUID}),Q.get(me).entries.push(ge)}const de=[];for(const[ge,me]of Q.entries()){const N=me.entries;N.sort((ve,Ie)=>Ur&&ve.sliceLocation!==void 0&&Ie.sliceLocation!==void 0?ve.sliceLocation-Ie.sliceLocation:ve.instanceNumber!==void 0&&Ie.instanceNumber!==void 0?ve.instanceNumber-Ie.instanceNumber:(ve.file.webkitRelativePath||ve.file.name).localeCompare(Ie.file.webkitRelativePath||Ie.file.name));const k=N.flatMap(ve=>{if(ve.isImage||!Number.isFinite(ve.numberOfFrames)||ve.numberOfFrames<=1)return[ve.imageId];const Ie=[];for(let ke=1;ke<=ve.numberOfFrames;ke++)Ie.push(X7(ve.imageId,ke));return Ie}),te=await Bn(k);de.push({imageIds:k,studyInstanceUID:me.studyInstanceUID,seriesInstanceUID:me.seriesInstanceUID,seriesGroups:te})}if(de.length!==0)if(Xa==="replace"){try{const ge=A.current;if(ge)for(let me=0;me{var me,N;const ge=Array(L).fill([]);for(let k=0;k{const ge=Array(L).fill(null).map(()=>[]);for(let me=0;me{const me=[...ge,...de];ie(N=>{var ve,Ie;const k=[...N],te=de[de.length-1];return k[0]=((Ie=(ve=te.seriesGroups)==null?void 0:ve[0])==null?void 0:Ie.imageIds)||te.imageIds,k}),Fe(N=>{const k=[...N];return k[0]=me.length-1,k}),Xe(N=>{var te;const k=[...N];return k[0]=((te=de[de.length-1])==null?void 0:te.seriesGroups)||[],k}),ue(N=>{const k=[...N];return k[0]=0,k});for(const N of de)jn(N.imageIds);return me})},Sn=st.useCallback((z,ne)=>{var Ie,ke;if(!ne)return;let he=0,le=0,Q="",de="",ge="",me="",N="",k="",te="",ve="";if(sn[z]==="stack"){he=typeof ne.getCurrentImageIdIndex=="function"?ne.getCurrentImageIdIndex():0;const be=typeof ne.getImageIds=="function"?ne.getImageIds():[];le=be.length;const Oe=be[he];if(Oe){const W=ct("generalSeriesModule",Oe),$=ct("imagePlaneModule",Oe),R=ct("imagePixelModule",Oe);me=(W==null?void 0:W.modality)||"",R!=null&&R.rows&&(R!=null&&R.columns)&&(k=`${R.columns} x ${R.rows}`);const V=[$==null?void 0:$.columnPixelSpacing,$==null?void 0:$.rowPixelSpacing,$==null?void 0:$.sliceThickness].filter(Y=>Y!=null&&Y!=="");V.length>0&&(te=V.join(" x "))}if(typeof ne.getCamera=="function"){const W=ne.getCamera();W!=null&&W.focalPoint&&Array.isArray(W.focalPoint)&&(ve=W.focalPoint.map($=>$.toFixed(1)).join(", "))}if(he>=0&&ea(W=>{const $=[...W],R=new Set($[z]||[]);return R.has(he)?W:(R.add(he),$[z]=Array.from(R).sort((V,Y)=>V-Y),$)}),typeof ne.getProperties=="function"){const W=ne.getProperties();if(W.voiRange){const{lower:$,upper:R}=W.voiRange;Q=((R+$)/2).toFixed(0),de=(R-$).toFixed(0),po.current[z]===null&&(po.current[z]={lower:$,upper:R})}}}else if(sn[z]==="volume"){if(typeof ne.getSliceIndex=="function"&&(he=ne.getSliceIndex()),typeof ne.getNumberOfSlices=="function"&&(le=ne.getNumberOfSlices()),typeof ne.getProperties=="function"){let Oe;if(ne.volumeIds&&ne.volumeIds.size>0){const W=Array.from(ne.volumeIds)[0];Oe=ne.getProperties(W)}else Oe=ne.getProperties();if(Oe&&Oe.voiRange){const{lower:W,upper:$}=Oe.voiRange;Q=(($+W)/2).toFixed(0),de=($-W).toFixed(0),po.current[z]===null&&(po.current[z]={lower:W,upper:$})}}if(typeof ne.getSlicePlaneCoordinates=="function"){const Oe=ne.getSlicePlaneCoordinates();Oe&&typeof Oe.position=="number"&&(ge=Oe.position.toFixed(2)+" mm")}const be=(Ie=J[z])==null?void 0:Ie[0];if(be){const Oe=ct("generalSeriesModule",be),W=ct("imagePlaneModule",be),$=ct("imagePixelModule",be);me=(Oe==null?void 0:Oe.modality)||"",N=String(((ke=ne.viewportProperties)==null?void 0:ke.orientation)||"").toUpperCase(),$!=null&&$.rows&&($!=null&&$.columns)&&(k=`${$.columns} x ${$.rows}`);const R=[W==null?void 0:W.columnPixelSpacing,W==null?void 0:W.rowPixelSpacing,W==null?void 0:W.sliceThickness].filter(V=>V!=null&&V!=="");R.length>0&&(te=R.join(" x "))}if(typeof ne.getCamera=="function"){const Oe=ne.getCamera();Oe!=null&&Oe.focalPoint&&Array.isArray(Oe.focalPoint)&&(ve=Oe.focalPoint.map(W=>W.toFixed(1)).join(", "))}}Gi(be=>{const Oe=[...be];return Oe[z]={index:he+1,total:le,windowCenter:Q,windowWidth:de,slicePosition:ge,modality:me,orientation:N,resolution:k,spacing:te,focalPoint:ve},Oe})},[sn,J]);st.useEffect(()=>{ea(z=>{let ne=!1;const he=[...z];for(let le=0;le{var Ce;const Q=await Ei(ne.map(a0));if(Q.length===0)return;await jn(Q,{force:!0});const de=await Bn(Q),ge=((Ce=de[0])==null?void 0:Ce.imageIds)||Q;let me=0;we(Te=>(me=Te.length,[...Te,{imageIds:Q,name:he,seriesGroups:de}]));const N=gi(le);if(N==="center"){Nt("displayset");try{pi(Te=>{const Me=[...Te];return Me[z]="stack",Me}),ie(Te=>{const Me=[...Te];return Me[z]=ge,Me}),Fe(Te=>{const Me=[...Te];return Me[z]=me,Me}),Xe(Te=>{const Me=[...Te];return Me[z]=de,Me}),ue(Te=>{const Me=[...Te];return Me[z]=0,Me}),Ve(z),await jn(ge)}finally{Nt(null)}return}const k=Ct.rows,te=Ct.cols,ve=Math.floor(z/te),Ie=z%te,ke=N==="top"||N==="bottom"?k+1:k,be=N==="left"||N==="right"?te+1:te;if(ke>3||be>3||ke*be>L){Nt("displayset");try{pi(Te=>{const Me=[...Te];return Me[z]="stack",Me}),ie(Te=>{const Me=[...Te];return Me[z]=Q,Me}),Fe(Te=>{const Me=[...Te];return Me[z]=me,Me}),Ve(z),await jn(Q)}finally{Nt(null)}return}const Oe=N==="top"?ve:N==="bottom"?ve+1:ve,W=N==="left"?Ie:N==="right"?Ie+1:Ie,$=Oe*be+W,R=Array(L).fill([]),V=Array(L).fill("stack"),Y=Array(L).fill(0),ye=Array(L).fill(null).map(()=>[]),xe=Array(L).fill(0);for(let Te=0;TeIe||N==="left"?Ae+1:Ae),(N==="top"||N==="bottom")&&Ae===Ie&&(qe=Meve||N==="top"?Me+1:Me);const mt=qe*be+rt;R[mt]=J[Te]||[],V[mt]=sn[Te]||"stack",Y[mt]=Re[Te]??0,ye[mt]=je[Te]||[],xe[mt]=se[Te]??0}R[$]=ge,V[$]="stack",Y[$]=me,ye[$]=de,xe[$]=0,Nt("displayset");try{ji(),Zt({rows:ke,cols:be}),ie(R),pi(V),Fe(Y),Xe(ye),ue(xe),Ve($),await jn(ge)}finally{Nt(null)}},ba=async(z,ne,he)=>{var xe;const le=Se[ne];if(!le)return;let Q=le.seriesGroups;const de=le.imageIds||[];await jn(de,{force:!0}),(!Q||Q.length===0)&&(Q=await Bn(de),we(Ce=>{const Te=[...Ce];return Te[ne]?(Te[ne]={...Te[ne],seriesGroups:Q},Te):Ce}));const ge=((xe=Q[0])==null?void 0:xe.imageIds)||de,me=gi(he);if(me==="center"){await ut(z,ne),Ve(z);return}const N=Ct.rows,k=Ct.cols,te=Math.floor(z/k),ve=z%k,Ie=me==="top"||me==="bottom"?N+1:N,ke=me==="left"||me==="right"?k+1:k;if(Ie>3||ke>3||Ie*ke>L){await ut(z,ne),Ve(z);return}const be=Array(L).fill([]),Oe=Array(L).fill("stack"),W=Array(L).fill(0),$=Array(L).fill(null).map(()=>[]),R=Array(L).fill(0),V=me==="top"?te:me==="bottom"?te+1:te,Y=me==="left"?ve:me==="right"?ve+1:ve,ye=V*ke+Y;for(let Ce=0;Ceve?qe=Me+1:qe=me==="left"?Me+1:Me),(me==="top"||me==="bottom")&&Me===ve&&(Tete?Ae=Te+1:Ae=me==="top"?Te+1:Te);const rt=Ae*ke+qe;be[rt]=J[Ce]||[],Oe[rt]=sn[Ce]||"stack",W[rt]=Re[Ce]??0,$[rt]=je[Ce]||[],R[rt]=se[Ce]??0}be[ye]=ge,Oe[ye]="stack",W[ye]=ne,$[ye]=Q||[],R[ye]=0,Nt("displayset");try{ji(),Zt({rows:Ie,cols:ke}),ie(be),pi(Oe),Fe(W),Xe($),ue(R),Ve(ye),await jn(ge)}finally{Nt(null)}};st.useEffect(()=>{const z=async()=>{var de;if(console.log("setup"),!c.current){c.current=!0,await WA(),await fG(),f$();try{ld("external",ge=>({promise:(async()=>{const N=ge.replace(/^external:/,""),k=new Image;k.crossOrigin="anonymous",k.src=N,await new Promise((W,$)=>{k.onload=()=>W(!0),k.onerror=R=>$(R)});const te=k.naturalWidth||k.width,ve=k.naturalHeight||k.height,Ie=document.createElement("canvas");Ie.width=te,Ie.height=ve;const ke=Ie.getContext("2d");if(!ke)throw new Error("Unable to create canvas context");ke.drawImage(k,0,0,te,ve);const be=ke.getImageData(0,0,te,ve);return{imageId:ge,minPixelValue:0,maxPixelValue:255,slope:1,intercept:0,rows:ve,columns:te,height:ve,width:te,color:!0,rgba:!0,sizeInBytes:be.data.length,getPixelData:()=>be.data,getImageData:()=>be,getCanvas:()=>Ie}})()}))}catch(ge){console.warn("Failed to register external image loader",ge)}}let he=A.current;if(!he){he=new aE(B),A.current=he;try{Se&&Se.length>0&&Se.forEach((ge,me)=>{const N=Array.isArray(ge.imageIds)?ge.imageIds:[],k=Math.floor(N.length/2),te=N[k]||N[0]||null;te&&!Ue[me]&&!ot.current[me]&&Ao(me,te)})}catch{}}let le=jr(H);le||(le=c8e(H)),sn.slice(0,Ct.rows*Ct.cols).filter(ge=>ge==="volume").length,Ja(le);for(let ge=0;ge{if(k.offsetWidth>0&&k.offsetHeight>0){he.resize();const be=he.getViewport(N);be&&typeof be.resize=="function"&&be.resize(),be&&typeof be.render=="function"&&be.render()}});ke.observe(k),k._resizeObserver=ke}if(sn[ge]==="stack"){if(me&&me.length>0){const ke=me[0];if(vt(ke))try{try{const W=k._externalPanZoom;W&&typeof W.cleanup=="function"&&W.cleanup()}catch{}k.innerHTML="";const be=document.createElement("img");be.style.width="100%",be.style.height="100%",be.style.objectFit="contain",be.style.display="block",be.src=ke.replace(/^external:/,""),be.setAttribute("draggable","false"),k.appendChild(be);const Oe=Mt(k,be);k._externalPanZoom=Oe,le.removeViewports(B,N)}catch(be){console.warn("Failed to render external image in viewport",be)}else try{ve.setStack(me)}catch(be){console.warn("viewport.setStack failed",be)}}Rt?le.removeViewports(B,N):le.addViewport(N,B)}else if(sn[ge]==="volume"){le.addViewport(N,B);const ke=`myVolumeId_${ge}`;(await p1(ke,{imageIds:me})).load(),ve.setVolumes([{volumeId:ke}]),ve.render(),k._overlayListener&&ve.element.removeEventListener(Ug,k._overlayListener);const Oe=()=>Sn(ge,ve);ve.element.addEventListener(Ug,Oe),k._overlayListener=Oe,Sn(ge,ve);continue}if(ve.render(),!F.current){bi.current[ge]!==void 0&&typeof ve.setImageIdIndex=="function"&&oa(ve.element,{imageIndex:bi.current[ge]});const ke=ho.current[ge];if(ke&&typeof ve.setProperties=="function"){const{voiRange:be,invert:Oe,interpolationType:W,VOILUTFunction:$,colormap:R}=ke,V={};be&&be.lower!==void 0&&be.upper!==void 0&&(V.voiRange=be),Oe!==void 0&&(V.invert=Oe),W!==void 0&&(V.interpolationType=W),$&&(V.VOILUTFunction=$),R!=null&&(typeof R=="string"||typeof R=="object"&&!("actor"in R))&&(V.colormap=R),setTimeout(()=>{console.log("Restoring properties (timeout) for viewport",ge,V),ve.setProperties(V),ve.render()},100)}}k._overlayListener&&ve.element.removeEventListener(Ug,k._overlayListener);const Ie=()=>Sn(ge,ve);ve.element.addEventListener(Ug,Ie),k._overlayListener=Ie,Sn(ge,ve)}for(let ge=0;ge=2?(le.hasTool(Uc.toolName)||le.addTool(Uc.toolName),le.setToolEnabled(Uc.toolName),le.setToolConfiguration(Uc.toolName,{}),le.setToolActive(Uc.toolName,{bindings:[{mouseButton:Fg.Primary}]})):le.hasTool(Uc.toolName)&&le.setToolDisabled(Uc.toolName)),ii()},ne=requestAnimationFrame(()=>{z()});return()=>{Dr.current.forEach(he=>{he&&he._resizeObserver&&(he._resizeObserver.disconnect(),delete he._resizeObserver)}),cancelAnimationFrame(ne)}},[s,Sn,Ct,sn,J]);const Oi=st.useCallback(z=>{const ne=`CT_${z}`,le=A.current.getViewport(ne);le&&typeof le.resetCamera=="function"&&(le.resetCamera(),console.log("Restoring viewport properties for viewport",z),le.resetProperties(),le.render())},[]),bs=st.useCallback((z,ne,he)=>{const le=`CT_${z}`;try{const Q=A.current;if(Q){const de=Q.getViewport(le);de&&typeof de.setProperties=="function"&&(console.log(`Applying preset to viewport ${z}: center=${ne}, width=${he}`),de.setProperties({voiRange:{lower:ne-he/2,upper:ne+he/2}}),de.render(),Sn(z,de))}}catch{}},[Sn]),na=st.useCallback((z,ne=!1)=>{const he=`CT_${z}`;try{const le=A.current,Q=le==null?void 0:le.getViewport(he);if(!Q)return!1;const de=typeof Q.getImageIds=="function"?Q.getImageIds():J[z]||[],ge=typeof Q.getCurrentImageIdIndex=="function"?Q.getCurrentImageIdIndex():0,me=de[ge]||de[0],N=po.current[z],k=me?ct("voiLutModule",me)||{}:{},te=me?ct("imagePixelModule",me)||{}:{},ve=me?ct("modalityLutModule",me)||{}:{},Ie=Array.isArray(k.windowCenter)?k.windowCenter[0]:k.windowCenter,ke=Array.isArray(k.windowWidth)?k.windowWidth[0]:k.windowWidth,be=Number(te.smallestPixelValue??te.smallestImagePixelValue),Oe=Number(te.largestPixelValue??te.largestImagePixelValue),W=Number(ve.rescaleSlope??1),$=Number(ve.rescaleIntercept??0);if(N)Q.setProperties({voiRange:N});else if(Number.isFinite(Number(Ie))&&Number.isFinite(Number(ke))&&Number(ke)>0){const R=Number(Ie),V=Number(ke);Q.setProperties({voiRange:{lower:R-V/2,upper:R+V/2}})}else Number.isFinite(be)&&Number.isFinite(Oe)&&Oe>be?Q.setProperties({voiRange:{lower:be*W+$,upper:Oe*W+$}}):typeof Q.resetProperties=="function"&&Q.resetProperties();return ne&&typeof Q.resetCamera=="function"&&Q.resetCamera(),Q.render(),Sn(z,Q),!0}catch(le){return console.warn("Failed to apply default window level",le),!1}},[Sn,J]),Cc=st.useCallback(z=>{const ne=`CT_${z}`;(async()=>{const he=A.current;if(!he)return;const le=he.getViewport(ne);if(!le)return;const Q=typeof le.getImageIds=="function"?le.getImageIds():J[z]||[],de=typeof le.getCurrentImageIdIndex=="function"?le.getCurrentImageIdIndex():0,ge=Q[de]||Q[0];if(!ge){na(z);return}const me=ct("imagePixelModule",ge)||{},N=ct("modalityLutModule",ge)||{},k=ct("voiLutModule",ge)||{},te=po.current[z];let ve=Number(me.smallestPixelValue??me.smallestImagePixelValue),Ie=Number(me.largestPixelValue??me.largestImagePixelValue),ke=Number(N.rescaleSlope??1),be=Number(N.rescaleIntercept??0);if(!Number.isFinite(ve)||!Number.isFinite(Ie)||Ie<=ve)try{const $=await ws(ge);ve=Number($==null?void 0:$.minPixelValue),Ie=Number($==null?void 0:$.maxPixelValue),ke=Number(($==null?void 0:$.slope)??ke),be=Number(($==null?void 0:$.intercept)??be)}catch{const R=Q.filter(V=>!!V).slice(0,6);for(const V of R)try{const Y=await ws(V);if(ve=Number(Y==null?void 0:Y.minPixelValue),Ie=Number(Y==null?void 0:Y.maxPixelValue),ke=Number((Y==null?void 0:Y.slope)??ke),be=Number((Y==null?void 0:Y.intercept)??be),Number.isFinite(ve)&&Number.isFinite(Ie)&&Ie>ve)break}catch{}}const Oe=Array.isArray(k.windowCenter)?k.windowCenter[0]:k.windowCenter,W=Array.isArray(k.windowWidth)?k.windowWidth[0]:k.windowWidth;if(Number.isFinite(ve)&&Number.isFinite(Ie)&&Ie>ve)le.setProperties({voiRange:{lower:ve*ke+be,upper:Ie*ke+be}});else if(Number.isFinite(Number(Oe))&&Number.isFinite(Number(W))&&Number(W)>0){const $=Number(Oe),R=Number(W);le.setProperties({voiRange:{lower:$-R/2,upper:$+R/2}})}else if(te)le.setProperties({voiRange:te});else{na(z);return}le.render(),Sn(z,le)})().catch(()=>{na(z)})},[na,Sn,J]),Uo=st.useCallback((z,ne,he=!0,le=!0)=>{if(he&&(Zr.current[z]=ne),ne.action==="reset"){na(z,le);return}if(ne.action==="autolevel"){Cc(z);return}const Q=ne;bs(z,Q.center,Q.width)},[na,bs,Cc]);st.useEffect(()=>{const z=()=>{const he=A.current;if(!he)return;const le=Ct.rows*Ct.cols;for(let Q=0;Qwindow.clearTimeout(ne)},[Uo,ln,Ct,sn]),st.useEffect(()=>{const z=ne=>{var me,N;const he=ne.target;if(he){const k=(me=he.tagName)==null?void 0:me.toLowerCase(),te=he.getAttribute("contenteditable")==="true";if(k==="input"||k==="textarea"||k==="select"||te)return}if(ne.ctrlKey||ne.altKey||ne.metaKey||_e===null)return;const le=(N=ln[_e])==null?void 0:N.modality,Q=q7(le);if(ne.key==="0"){const k=Q.find(te=>te.action==="reset");k&&(Uo(_e,k),ne.preventDefault());return}if(!/^[1-9]$/.test(ne.key))return;const de=Number(ne.key)-1,ge=Q.filter(k=>k.action==="preset");de>=ge.length||(Uo(_e,ge[de]),ne.preventDefault())};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[_e,Uo,ln]);const Da=st.useCallback((z,ne)=>{const he=je[z]||[];if(he.length<=1)return;const le=Math.max(0,Math.min(he.length-1,ne)),Q=he[le];if(!Q||Q.imageIds.length===0)return;const de=A.current,ge=de==null?void 0:de.getViewport(`CT_${z}`);let me=0;if(ge&&typeof ge.getCurrentImageIdIndex=="function"){const k=(J[z]||[]).length,te=ge.getCurrentImageIdIndex(),ve=k>1?te/(k-1):0;me=Math.max(0,Math.min(Q.imageIds.length-1,Math.round(ve*Math.max(0,Q.imageIds.length-1))))}ue(N=>{const k=[...N];return k[z]=le,k}),ie(N=>{const k=[...N];return k[z]=Q.imageIds,k}),jn(Q.imageIds,{force:!0}),window.setTimeout(()=>{var k;const N=(k=A.current)==null?void 0:k.getViewport(`CT_${z}`);!N||typeof N.setImageIdIndex!="function"||(oa(N.element,{imageIndex:me}),N.render(),Sn(z,N))},25)},[je,jn,Sn,J]);st.useEffect(()=>{const z=[],ne=Ct.rows*Ct.cols;for(let he=0;he{var Ie,ke;const me=(Ie=A.current)==null?void 0:Ie.getViewport(`CT_${he}`);if(!me||typeof me.getCurrentImageIdIndex!="function"||typeof me.setImageIdIndex!="function")return;const k=(((ke=me.getImageIds)==null?void 0:ke.call(me))||le).length;if(k<2)return;const ve=(me.getCurrentImageIdIndex()+1)%k;oa(me.element,{imageIndex:ve}),me.render()},de);z.push(ge)}return()=>{z.forEach(he=>window.clearInterval(he))}},[Ee,Pe,Ct,J,sn]);const Sc=st.useCallback(()=>{const z=a.current;z&&(document.fullscreenElement===z?document.exitFullscreen():z.requestFullscreen?z.requestFullscreen():z.webkitRequestFullscreen?z.webkitRequestFullscreen():z.msRequestFullscreen&&z.msRequestFullscreen())},[]);st.useEffect(()=>{Gi(Array(Ct.rows*Ct.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:"",modality:"",orientation:"",resolution:"",spacing:"",focalPoint:""})),Wi(Array(Ct.rows*Ct.cols).fill(!1)),ft(Array(L).fill(!1))},[Ct]),st.useEffect(()=>{ii()},[Ii,ko,eo,ii]),st.useEffect(()=>{if(!No.some(Boolean))return;const z=ne=>{const he=document.querySelector(".preset-menu");he&&!he.contains(ne.target)&&Wi(le=>le.map(()=>!1))};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[No]),st.useEffect(()=>{if(!ar)return;const z=ne=>{const he=_.current;he&&!he.contains(ne.target)&&(Qo(!1),O(!1))};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[ar]),st.useEffect(()=>{const z=ne=>{if(ne.button===3||ne.button===4)return ne.preventDefault(),!1};return window.addEventListener("mousedown",z,!0),window.addEventListener("mouseup",z,!0),window.addEventListener("auxclick",z,!0),()=>{window.removeEventListener("mousedown",z,!0),window.removeEventListener("mouseup",z,!0),window.removeEventListener("auxclick",z,!0)}},[]),st.useEffect(()=>{const z=a.current;if(!z)return;const ne=he=>{he.preventDefault()};return z.addEventListener("contextmenu",ne),()=>{z.removeEventListener("contextmenu",ne)}},[]),st.useEffect(()=>{if(!Fr)return;const z=jr(H);Ja(z)},[_e,Fr]),st.useEffect(()=>{oi.current&&(oi.current.setAttribute("webkitdirectory","true"),oi.current.setAttribute("directory","true"))},[]),st.useEffect(()=>(window.loadDicomStackFromWadouriList=async z=>{var de;if(!z||z.length===0)return;const ne=await Ei(z);await jn(ne,{force:!0});const he=await Bn(ne),le=((de=he[0])==null?void 0:de.imageIds)||ne;let Q;try{const ge=ne[0];if(ge&&ge.startsWith("wadouri:")){const me=zs(ge),k=await(await fetch(me)).arrayBuffer();Q=lr.parseDicom(new Uint8Array(k)).string("x0020000d")}}catch{}we(ge=>{const me=[...ge,{imageIds:ne,studyInstanceUID:Q,seriesGroups:he}];return ie(N=>{const k=[...N];return k[0]=le,k}),Fe(N=>{const k=[...N];return k[0]=me.length-1,k}),Xe(N=>{const k=[...N];return k[0]=he,k}),ue(N=>{const k=[...N];return k[0]=0,k}),jn(le),me})},()=>{window.loadDicomStackFromWadouriList=void 0}),[Bn,Ei,we,jn,Fe,ie]),st.useEffect(()=>{!Ur||!J.every(ne=>!ne||ne.length===0||ne.every(he=>!!ct("imagePlaneModule",he)))||ie(ne=>{let he=!1;const le=ne.map(Q=>{if(!Q||Q.length===0)return Q;const me=[...Q.map(N=>({imageId:N,sliceLoc:(()=>{const k=ct("imagePlaneModule",N);return k&&k.sliceLocation!==void 0?Number(k.sliceLocation):null})()}))].sort((N,k)=>N.sliceLoc!==null&&k.sliceLoc!==null?N.sliceLoc-k.sliceLoc:N.imageId.localeCompare(k.imageId)).map(N=>N.imageId);return JSON.stringify(me)!==JSON.stringify(Q)?(he=!0,me):Q});return he&&wn(!0),le})},[Ur,Se]);function Ja(z){if(!z)return;const ne=`CT_${_e}`;Fr?(z.setToolEnabled(pd.toolName),z.setToolConfiguration(pd.toolName,{sourceViewportId:ne})):z.setToolDisabled(pd.toolName)}function pl(){var ne,he,le;const z=A.current;if(z)for(let Q=0;Q[])),ue(Array(L).fill(0)),pe(Array(L).fill(!1)),ft(Array(L).fill(!1)),pi(Array(L).fill("stack")),Object.values(at.current).forEach(ne=>{if(typeof ne=="string"&&ne.startsWith("blob:"))try{URL.revokeObjectURL(ne)}catch{}}),at.current={},nt({}),ot.current={},wn(!1),Ve(0)}function vl(z,ne){var ge,me;if(console.log("Truncating stack from",z,"to",ne),console.log(Ft),Ct.rows!==1||Ct.cols!==1||Se.length!==1||!J[0]||J[0].length===0||Ft)return alert("Truncation is only allowed when a single stack is loaded in a single viewport (and the order has not been modified in the viewer)."),!1;const he=Se[0],le=he.imageIds;if(z<0||ne>=le.length||z>=ne)return alert("Invalid truncation bounds."),!1;const Q=le.slice(z,ne+1);we([{...he,imageIds:Q}]),ie([Q]),Fe([0]);const de=A.current;if(de){const N=de.getViewport("CT_0");N&&typeof N.setStack=="function"&&(N.setStack(Q),(ge=N.setImageIdIndex)==null||ge.call(N,0),(me=N.render)==null||me.call(N))}return!0}function yl(z=0){const ne=A.current;if(!ne)return null;const he=ne.getViewport(`CT_${z}`);return!he||typeof he.getCurrentImageIdIndex!="function"?null:he.getCurrentImageIdIndex()}st.useEffect(()=>{const z=t||"default";function ne(le,Q){const de=A.current;if(!de)return;const ge=de.getViewport(`CT_${le}`);if(!ge||typeof ge.getImageIds!="function")return;const N=ge.getImageIds().map(ve=>zs(ve)),k=zs(Q),te=N.indexOf(k);te!==-1&&typeof ge.setImageIdIndex=="function"&&(oa(ge.element,{imageIndex:te}),Sn(le,ge))}window[`getViewport_${z}`]=le=>{const Q=A.current;if(Q)return Q.getViewport(`CT_${le}`)},window[`getAllViewports_${z}`]=()=>{const le=A.current;return le?Array.from({length:L},(Q,de)=>le.getViewport(`CT_${de}`)).filter(Boolean):[]},window[`jumpToSliceByImageId_${z}`]=ne,window[`resetViewer_${z}`]=pl,window[`clearViewer_${z}`]=ml,window[`truncateStack_${z}`]=vl,window[`getCurrentStackPosition_${z}`]=yl,window[`loadAdditionalStack_${z}`]=async(le,Q)=>{var k,te;if(!Array.isArray(le)||le.length===0)return;const de=await Ei(le);await jn(de,{force:!0});const ge=await Bn(de),me=((k=ge[0])==null?void 0:k.imageIds)||de;let N=Q;if(!N&&((te=de[0])!=null&&te.startsWith("wadouri:")))try{const ve=zs(de[0]),ke=await(await fetch(ve)).arrayBuffer();N=lr.parseDicom(new Uint8Array(ke)).string("x0020000d")}catch{}we(ve=>[...ve,{imageIds:de,studyInstanceUID:N,seriesGroups:ge}]),ie(ve=>{const Ie=[...ve],ke=Ie.findIndex(be=>!be||be.length===0);return ke!==-1&&(Ie[ke]=me,Xe(be=>{const Oe=[...be];return Oe[ke]=ge,Oe}),ue(be=>{const Oe=[...be];return Oe[ke]=0,Oe})),Ie}),jn(me)},window[`loadExternalStack_${z}`]=async(le,Q)=>{!Array.isArray(le)||le.length===0||await Ea(_e??0,le,Q||"Series","center")},window[`loadExternalStackNewViewport_${z}`]=async(le,Q)=>{if(!Array.isArray(le)||le.length===0)return;await Ea(_e??0,le,Q||"Series","right")},window[`exportViewerState_${z}`]=()=>{var be;const le=Ct.rows*Ct.cols,Q=sn.slice(0,le),de=Re.slice(0,le),ge=Se.map(Oe=>({i:Oe.imageIds,u:Oe.studyInstanceUID,g:Oe.seriesGroups}));console.log("Exporting viewer state with",le,"active viewports"),console.log("modes",Q);const me=A.current,N=[],k=[],te=[],ve=[],Ie=[];for(let Oe=0;Oe{try{F.current=!0;const Q=typeof le=="string"?JSON.parse(le):le;if(Q.grid&&Zt(Q.grid),Q.modes&&pi(Q.modes),Q.stacks&&we(Q.stacks.map(N=>({imageIds:N.i,studyInstanceUID:N.u,seriesGroups:Array.isArray(N.g)?N.g:void 0}))),Q.stackIdx&&Q.stacks){const N=Q.stackIdx.map(k=>{var te;return((te=Q.stacks[k])==null?void 0:te.i)||[]});ie(N),Fe(Q.stackIdx),Xe(()=>{const k=Array(L).fill(null).map(()=>[]);for(let te=0;temt===qe[ht])){console.warn(`Viewport ${Ce}: importedImageIds do not match viewportImageIds`,{importedImageIds:qe,viewportImageIds:rt}),te=!1;break}}catch{te=!1}}if(!te&&ge{me()},500);return}for(let Ce=0;Ce{try{oa(Te.element,{imageIndex:Q.volumeSliceIndices[Ce]})}catch{}},100)}else{try{Te.setStack&&(Te.setStack(qe),Te.render())}catch(rt){console.warn("Failed to set stack for viewport",Ce,rt)}if(Q.stackPos&&typeof Q.stackPos[Ce]=="number"&&typeof Te.setImageIdIndex=="function")try{pn&&oa?oa(Te.element,{imageIndex:Q.stackPos[Ce]}):Te.setImageIdIndex(Q.stackPos[Ce])}catch{}}}const ve=1500;console.log(`Waiting ${ve}ms before applying properties/camera to viewports`),await new Promise(Ce=>setTimeout(Ce,ve));for(let Ce=0;Ce{me()},100)}catch(Q){F.current=!1,alert("Failed to import viewer state: "+Q)}},window[`exportAnnotations_${z}`]=()=>{try{let le=rr.getAllAnnotations();if(console.log("Exporting annotations:",le),Array.isArray(le)){const Q=[pf.toolName,Nh.toolName,mf.toolName,au.toolName,Ad.toolName,gf.toolName,sl.toolName,su.toolName,Rh.toolName];le=le.filter(de=>Q.includes(de.metadata.toolName))}else return"{}";return JSON.stringify(le,null,2)}catch(le){return alert("Failed to export annotations: "+le),"{}"}},window.__pendingImportAnnotations=window.__pendingImportAnnotations||{};const he=le=>{try{const Q=window.__pendingImportAnnotations&&window.__pendingImportAnnotations[le];if(!Q||!Q.length)return;const de=rr;if(!de||typeof de.addAnnotation!="function")return;for(;(window.__pendingImportAnnotations[le]||[]).length;){const ge=(window.__pendingImportAnnotations[le]||[]).shift();ge&&Array.isArray(ge)&&ge.forEach(me=>{try{de.addAnnotation(me,me.annotationUID)}catch(N){console.error("Failed to add queued annotation",N,me)}})}A.current&&A.current.render()}catch(Q){console.error("Error flushing pending annotations:",Q)}};return window[`importAnnotations_${z}`]=le=>{try{const Q=typeof le=="string"?JSON.parse(le):le,de=rr;if(!de||typeof de.addAnnotation!="function"){window.__pendingImportAnnotations[z]=window.__pendingImportAnnotations[z]||[],window.__pendingImportAnnotations[z].push(Q),console.warn("importAnnotations: annotation state not ready, queued import",z),setTimeout(()=>he(z),500);return}if(de.removeAllAnnotations)try{de.removeAllAnnotations()}catch(ge){console.warn("removeAllAnnotations failed",ge)}Array.isArray(Q)&&Q.forEach(ge=>{try{de.addAnnotation(ge,ge.annotationUID)}catch(me){console.error("Failed to add annotation",me,ge)}}),A.current&&A.current.render()}catch(Q){console.error("Failed to import annotations:",Q,{apiKey:z,cornerstoneTools:!!Dz,renderingEngine:!!A.current});try{alert("Failed to import annotations: "+Q)}catch{}}try{he(z)}catch{}},window[`importLegacyAnnotations_${z}`]=le=>{rr.removeAllAnnotations&&rr.removeAllAnnotations();let Q;try{Q=typeof le=="string"?JSON.parse(le):le}catch{alert("Invalid legacy annotation JSON");return}const de={ArrowAnnotate:"ArrowAnnotate"};Object.entries(Q).forEach(([ge,me])=>{console.log("Importing legacy annotations for imageId:",ge),Object.entries(me).forEach(([N,k])=>{const te=de[N]||N;k.data&&Array.isArray(k.data)&&k.data.forEach(ve=>{const Ie=H7(ge,{x:ve.handles.start.y,y:ve.handles.start.x}),ke=H7(ge,{x:ve.handles.end.y,y:ve.handles.end.x});console.log("Importing legacy annotation:"),console.log(" Image ID:",ge),console.log(" Start World:",Ie),console.log(" End World:",ke);const be=ct("imagePlaneModule",ge);console.log(A4);let Oe=ct("frameOfReferenceUID",ge);!Oe&&be&&be.frameOfReferenceUID&&(Oe=be.frameOfReferenceUID);const W=be!=null&&be.rowCosines&&(be!=null&&be.columnCosines)?[be.rowCosines[1]*be.columnCosines[2]-be.rowCosines[2]*be.columnCosines[1],be.rowCosines[2]*be.columnCosines[0]-be.rowCosines[0]*be.columnCosines[2],be.rowCosines[0]*be.columnCosines[1]-be.rowCosines[1]*be.columnCosines[0]]:void 0;Array.isArray(W)&&W.length,typeof ve.rotation=="number"&&ve.rotation;const $={annotationUID:ve.uuid,metadata:{toolName:te,referencedImageId:ge,FrameOfReferenceUID:Oe,viewPlaneNormal:W},data:{handles:{points:[Ie,ke],textBox:ve.handles.textBox},text:ve.text||""},visibility:ve.visible!==!1,active:ve.active||!1};rr.addAnnotation($,$.annotationUID)})})}),A.current&&A.current.render()},window[`importLegacyViewport_${z}`]=le=>{let Q;try{Q=typeof le=="string"?JSON.parse(le):le}catch{alert("Invalid legacy viewport JSON");return}const de=A.current;if(!de)return;const ge=`CT_${_e??0}`,me=de.getViewport(ge);if(!me)return;const N={};if(Q.voi&&(N.voiRange={lower:Q.voi.windowCenter-Q.voi.windowWidth/2,upper:Q.voi.windowCenter+Q.voi.windowWidth/2}),typeof Q.invert=="boolean"&&(N.invert=Q.invert),typeof Q.pixelReplication=="boolean"&&(N.interpolationType=Q.pixelReplication?0:1),typeof Q.hflip=="boolean"&&(N.hflip=Q.hflip),typeof Q.vflip=="boolean"&&(N.vflip=Q.vflip),typeof me.setProperties=="function"&&me.setProperties(N),Q.translation||Q.scale){const k=me.getCamera?me.getCamera():{};Q.translation&&(k.translation={...k.translation,...Q.translation}),Q.scale&&(k.parallelScale=200/Q.scale),console.log("Applying legacy camera properties:",k),typeof me.setCamera=="function"&&me.setCamera(k)}typeof Q.rotation=="number"&&me.setRotation(Q.rotation),me.render(),Sn(_e??0,me)},()=>{window[`exportViewerState_${z}`]=void 0,window[`importViewerState_${z}`]=void 0,window[`exportAnnotations_${z}`]=void 0,window[`importAnnotations_${z}`]=void 0,window[`importLegacyAnnotations_${z}`]=void 0,window[`importLegacyViewport_${z}`]=void 0,window[`jumpToSliceByImageId_${z}`]=void 0,window[`resetViewer_${z}`]=void 0,window[`clearViewer_${z}`]=void 0,window[`truncateStack_${z}`]=void 0,window[`getCurrentStackPosition_${z}`]=void 0,window[`loadAdditionalStack_${z}`]=void 0,window[`loadExternalStack_${z}`]=void 0,window[`loadExternalStackNewViewport_${z}`]=void 0,window[`getViewport_${z}`]=void 0,window[`getAllViewports_${z}`]=void 0}},[Ct,sn,Re,Se,J,Zt,pi,Fe,we,ie,we,ie,jn]),st.useEffect(()=>{const z=a.current;if(!z)return;function ne(he){if(console.log("Handling arrow key navigation",he.key),console.log("activeViewport",_e),_e===null)return;const le=A.current;if(!le)return;const Q=le.getViewport(`CT_${_e}`);if(Q){if(console.log(Q),sn[_e]==="stack"){if(typeof Q.getCurrentImageIdIndex!="function"||typeof Q.setImageIdIndex!="function")return;const de=J[_e];if(!de||de.length===0)return;he.key==="ArrowUp"||he.key==="ArrowRight"?(oc(Q,{delta:-1}),he.preventDefault()):(he.key==="ArrowDown"||he.key==="ArrowLeft")&&(oc(Q,{delta:1}),he.preventDefault())}sn[_e]==="volume"&&typeof Q.getSliceIndex=="function"&&typeof Q.getNumberOfSlices=="function"&&Q.getNumberOfSlices()>1&&(he.key==="ArrowUp"||he.key==="ArrowRight"?(oc(Q,{delta:-1}),he.preventDefault()):(he.key==="ArrowDown"||he.key==="ArrowLeft")&&(oc(Q,{delta:1}),he.preventDefault()))}}return z.addEventListener("keydown",ne),()=>{z.removeEventListener("keydown",ne)}},[_e,sn,J,Sn]);const wl=_e!==null?Re[_e]:0,Ds=Se[wl];Ds==null||Ds.studyInstanceUID;const[xl,Is]=st.useState(()=>Array(L).fill(null)),Cl=Ct.rows*Ct.cols,Os=[];for(let z=0;zDr.current[z]=Q,style:{flex:1,border:ne?"1px solid #222":"none",background:"#000",minWidth:0,minHeight:0,position:"relative",overflow:"hidden",flexDirection:"column",gridRow:Math.floor(z/Ct.cols)+1,gridColumn:z%Ct.cols+1,height:"100%",boxShadow:_e===z?"0 0 0 4px #1976d2, 0 0 16px 4px #1976d2cc":void 0,zIndex:_e===z?10:1},onClick:()=>{Ve(z),Qo(!1)},onDoubleClick:()=>Oi(z),onDragEnter:Q=>{const de=Q.dataTransfer.types,ge=de.includes("text/stack-idx"),me=de.includes("text/dv3d-imageids");if(!ge&&!me)return;Q.preventDefault(),me&&M(!0);const N=Ca(Q);K({viewportIdx:z,zone:N})},onDragOver:Q=>{const de=Q.dataTransfer.types,ge=de.includes("text/stack-idx"),me=de.includes("text/dv3d-imageids");if(!ge&&!me)return;Q.preventDefault();const N=Ca(Q),k=gi(N);K({viewportIdx:z,zone:N}),Q.dataTransfer.dropEffect=k===N?"copy":"move"},onDragLeave:Q=>{if((q==null?void 0:q.viewportIdx)!==z)return;const de=Q.relatedTarget;de&&Q.currentTarget.contains(de)||K(null)},onDrop:Q=>{Q.preventDefault();const de=Q.dataTransfer.getData("text/dv3d-imageids");if(de){const N=Q.dataTransfer.getData("text/dv3d-stack-name")||"Series";try{const k=JSON.parse(de),te=Ca(Q);Ea(z,k,N,te).catch(ve=>{console.error("Failed to apply external drop:",ve)})}catch(k){console.error("Invalid text/dv3d-imageids payload:",k)}K(null),M(!1);return}const ge=Q.dataTransfer.getData("text/stack-idx"),me=parseInt(ge,10);if(!isNaN(me)){const N=Ca(Q);ba(z,me,N).catch(k=>{console.error("Failed to apply dropped stack:",k)})}K(null),Ne(null),M(!1)},children:[(Ge!==null||j)&&he&&ze.jsx("div",{style:{position:"absolute",inset:0,zIndex:19,pointerEvents:"none",background:"rgba(0,0,0,0.08)"},children:ze.jsx("div",{style:{position:"absolute",left:le==="left"?0:le==="right"?"50%":"20%",top:le==="top"?0:le==="bottom"?"50%":"20%",width:le==="left"||le==="right"?"50%":"60%",height:le==="top"||le==="bottom"?"50%":"60%",border:"2px solid #90caf9",boxShadow:"0 0 0 9999px rgba(17, 29, 45, 0.22)",background:"rgba(25, 118, 210, 0.28)",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:.4},children:le==="center"?"Load Here":`Split ${le}`})}),ze.jsx("button",{style:{position:"absolute",top:8,left:8,zIndex:20,background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"12px",opacity:.85},onClick:()=>{pi(Q=>{const de=[...Q];return de[z]=Q[z]==="stack"?"volume":"stack",de})},children:sn[z]==="stack"?"Volume":"Stack"}),sn[z]==="volume"&&ze.jsxs("div",{style:{position:"absolute",top:8,left:70,zIndex:21,display:"flex",gap:"6px",background:"rgba(34,34,34,0.85)",borderRadius:"4px",padding:"2px 6px",alignItems:"center"},children:[ze.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const Q=A.current,de=Q==null?void 0:Q.getViewport(`CT_${z}`);de&&de.setOrientation&&(de.setOrientation("axial"),de.render())},children:"Axial"}),ze.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const Q=A.current,de=Q==null?void 0:Q.getViewport(`CT_${z}`);de&&de.setOrientation&&(de.setOrientation("sagittal"),de.render())},children:"Sagittal"}),ze.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px"},onClick:()=>{const Q=A.current,de=Q==null?void 0:Q.getViewport(`CT_${z}`);de&&de.setOrientation&&(de.setOrientation("coronal"),de.render())},children:"Coronal"})]}),ze.jsxs("button",{style:{position:"absolute",top:40,left:8,zIndex:20,background:"#111",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"13px",opacity:.85,marginTop:"4px",display:"flex",alignItems:"center",gap:"6px"},title:"Toggle Fullscreen",onClick:Q=>{Q.stopPropagation();const de=Dr.current[z];document.fullscreenElement===de?document.exitFullscreen():de!=null&&de.requestFullscreen?de.requestFullscreen():de!=null&&de.webkitRequestFullscreen?de.webkitRequestFullscreen():de!=null&&de.msRequestFullscreen&&de.msRequestFullscreen()},onMouseEnter:()=>b(z),onMouseLeave:()=>b(null),children:[ze.jsx("span",{style:{fontSize:"18px",lineHeight:1},children:"⛶"}),E===z&&ze.jsx("span",{style:{marginLeft:6},children:document.fullscreenElement===Dr.current[z]?"Exit Fullscreen":"Fullscreen"})]}),sn[z]==="stack"&&G&&(()=>{var ke;const Q=J[z],ge=(rr.getAllAnnotations()||[]).filter(be=>be.metadata&&be.metadata.referencedImageId&&Q.includes(be.metadata.referencedImageId)&&be.metadata.toolName!==La.toolName);if(!ge.length)return null;const me=A.current,N=me==null?void 0:me.getViewport(`CT_${z}`),k=((ke=N==null?void 0:N.getCurrentImageIdIndex)==null?void 0:ke.call(N))??0,te=Q[k],ve=ge.filter(be=>be.metadata.referencedImageId===te),Ie=xl[z];return ze.jsxs("div",{style:{position:"absolute",left:"50%",bottom:60,transform:"translateX(-50%)",zIndex:30,display:"flex",gap:4,pointerEvents:"auto",alignItems:"center"},children:[ze.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Previous Annotation","aria-label":"Previous Annotation",onClick:()=>{const be=A.current,Oe=be==null?void 0:be.getViewport(`CT_${z}`);if(!Oe||typeof Oe.getCurrentImageIdIndex!="function")return;const W=Oe.getCurrentImageIdIndex(),$=Q7(W,Q,ge,-1);if($!==null&&typeof Oe.setImageIdIndex=="function"){oa(Oe.element,{imageIndex:$}),Sn(z,Oe);const R=Q[$],V=ge.filter(Y=>Y.metadata.referencedImageId===R);Fo(z,V.length>0?V[0].annotationUID:null)}},children:ze.jsx("span",{"aria-hidden":"true",children:"◀"})}),ze.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Next Annotation","aria-label":"Next Annotation",onClick:()=>{const be=A.current,Oe=be==null?void 0:be.getViewport(`CT_${z}`);if(!Oe||typeof Oe.getCurrentImageIdIndex!="function")return;const W=Oe.getCurrentImageIdIndex(),$=Q7(W,Q,ge,1);if($!==null&&typeof Oe.setImageIdIndex=="function"){oa(Oe.element,{imageIndex:$}),Sn(z,Oe);const R=Q[$],V=ge.filter(Y=>Y.metadata.referencedImageId===R);Fo(z,V.length>0?V[0].annotationUID:null)}},children:ze.jsx("span",{"aria-hidden":"true",children:"▶"})}),ve.length>0&&ze.jsx("div",{style:{display:"flex",gap:2,alignItems:"center"},children:ve.map(be=>ze.jsxs("div",{style:{display:"flex",alignItems:"center",background:Ie===be.annotationUID?"rgb(4, 225, 0)":"#444",color:Ie===be.annotationUID?"#222":"#fff",borderRadius:"4px",padding:"2px 6px",marginRight:2,cursor:"pointer",border:Ie===be.annotationUID?"2px solid #1976d2":"none",fontWeight:Ie===be.annotationUID?"bold":"normal"},onClick:()=>Fo(z,be.annotationUID),children:[ze.jsxs("span",{style:{marginRight:4},title:be.metadata.toolName||"Annotation",children:[Ie===be.annotationUID?"★ ":"",ze.jsx("span",{style:{fontSize:14,lineHeight:1},children:o8e(be.metadata.toolName)})]}),ze.jsx("button",{style:{background:"transparent",color:"#f44336",border:"1px solid #f44336",borderRadius:3,width:16,height:16,fontSize:10,lineHeight:1,cursor:"pointer",marginLeft:4,display:"flex",alignItems:"center",justifyContent:"center",opacity:.95,padding:0},title:"Delete this annotation","aria-label":"Delete annotation",onClick:Oe=>{Oe.stopPropagation(),yr(z,be.annotationUID,ve)},children:ze.jsx("span",{"aria-hidden":"true",children:"✖"})})]},be.annotationUID))})]})})(),ze.jsx("div",{style:{position:"absolute",left:8,bottom:8,background:"rgba(0,0,0,0.7)",color:"#fff",padding:"6px 12px",borderRadius:"4px",fontSize:"14px",zIndex:10,pointerEvents:"none",minWidth:"120px",userSelect:"none"},children:sn[z]==="stack"?ze.jsxs(ze.Fragment,{children:[ze.jsxs("div",{children:["Image: ",(Ms=ln[z])==null?void 0:Ms.index," / ",(Tc=ln[z])==null?void 0:Tc.total]}),ze.jsxs("div",{children:["WC: ",(Za=ln[z])==null?void 0:Za.windowCenter,"   WW: ",(Ps=ln[z])==null?void 0:Ps.windowWidth]}),ee&&ze.jsxs(ze.Fragment,{children:[ze.jsxs("div",{children:["Ori: ",((Rs=ln[z])==null?void 0:Rs.orientation)||"N/A"]}),((Qa=ln[z])==null?void 0:Qa.resolution)&&ze.jsxs("div",{children:["Res: ",(_c=ln[z])==null?void 0:_c.resolution]}),((Ls=ln[z])==null?void 0:Ls.spacing)&&ze.jsxs("div",{children:["Spacing: ",(Ec=ln[z])==null?void 0:Ec.spacing]}),((As=ln[z])==null?void 0:As.focalPoint)&&ze.jsxs("div",{children:["Pos: ",(bc=ln[z])==null?void 0:bc.focalPoint]})]})]}):ze.jsxs("div",{children:["Slice: ",(Dc=ln[z])==null?void 0:Dc.index," / ",(Ic=ln[z])==null?void 0:Ic.total,((Oc=ln[z])==null?void 0:Oc.slicePosition)&&ze.jsxs("span",{children:["   (",(es=ln[z])==null?void 0:es.slicePosition,")"]}),ze.jsx("br",{}),"WC: ",(ts=ln[z])==null?void 0:ts.windowCenter,"   WW: ",(vo=ln[z])==null?void 0:vo.windowWidth,ee&&ze.jsxs(ze.Fragment,{children:[ze.jsx("br",{}),"Ori: ",((Bo=ln[z])==null?void 0:Bo.orientation)||"N/A",((Hi=ln[z])==null?void 0:Hi.resolution)&&ze.jsxs(ze.Fragment,{children:[ze.jsx("br",{}),"Res: ",(Ns=ln[z])==null?void 0:Ns.resolution]}),((ks=ln[z])==null?void 0:ks.spacing)&&ze.jsxs(ze.Fragment,{children:[ze.jsx("br",{}),"Spacing: ",(ns=ln[z])==null?void 0:ns.spacing]}),((Vs=ln[z])==null?void 0:Vs.focalPoint)&&ze.jsxs(ze.Fragment,{children:[ze.jsx("br",{}),"Pos: ",(Ia=ln[z])==null?void 0:Ia.focalPoint]})]})]})}),ze.jsxs("div",{style:{position:"absolute",right:8,bottom:8,zIndex:110,pointerEvents:"auto",display:"flex",alignItems:"flex-end",gap:6},children:[ze.jsx("button",{style:{background:fe[z]?"rgba(30,120,200,0.95)":"rgba(0,0,0,0.7)",color:"#fff",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"4px",fontSize:"12px",fontWeight:700,padding:"6px 9px",cursor:"pointer",minHeight:30},title:fe[z]?"Hide cine controls":"Show cine controls",onClick:Q=>{Q.stopPropagation(),ft(de=>{const ge=[...de],me=!ge[z];return ge[z]=me,me||pe(N=>{const k=[...N];return k[z]=!1,k}),ge})},children:"Cine"}),ze.jsxs("div",{className:"preset-menu",style:{background:"rgba(0,0,0,0.7)",color:"#fff",borderRadius:"4px",fontSize:"14px",minWidth:"120px",overflow:"hidden",cursor:"pointer",position:"relative",boxShadow:No[z]?"0 2px 8px rgba(0,0,0,0.3)":void 0,pointerEvents:"auto"},onClick:Q=>Q.stopPropagation(),children:[ze.jsxs("div",{style:{padding:"6px 12px",fontWeight:"bold",userSelect:"none"},onClick:Q=>{Q.stopPropagation(),Wi(de=>{const ge=[...de];return ge[z]=!ge[z],ge})},children:["Presets (",((Fs=ln[z])==null?void 0:Fs.modality)||"Unknown",")",ze.jsx("span",{style:{float:"right",fontWeight:"normal"},children:No[z]?"▲":"▼"})]}),No[z]&&ze.jsx("div",{className:"preset-menu-content",style:{background:"rgba(0,0,0,0.95)",borderRadius:"0 0 4px 4px",padding:"6px 0 6px 0",display:"flex",flexDirection:"column",zIndex:111,pointerEvents:"auto"},onClick:Q=>Q.stopPropagation(),children:(()=>{var ge;const Q=q7((ge=ln[z])==null?void 0:ge.modality);let de=0;return Q.map(me=>{let N="";return me.action==="reset"?N="0":me.action==="preset"&&(de+=1,N=String(de)),ze.jsxs("button",{title:N?`Shortcut: ${N}`:void 0,style:{display:"block",width:"100%",margin:"2px 0",background:me.action==="preset"?"#333":"#444",color:"#fff",border:"none",borderRadius:"3px",cursor:"pointer",padding:me.action==="preset"?"4px 0":"6px 0",fontSize:"13px",opacity:.9,fontWeight:me.action==="preset"?"normal":"600"},onClick:k=>{k.stopPropagation(),Uo(z,me),Wi(te=>{const ve=[...te];return ve[z]=!1,ve})},children:[me.name,N?` (${N})`:""]},me.name)})})()})]})]}),sn[z]==="stack"&&(fe[z]||(je[z]||[]).length>1)&&ze.jsxs("div",{style:{position:"absolute",left:"50%",bottom:8,transform:"translateX(-50%)",zIndex:36,background:"rgba(15,15,15,0.82)",border:"1px solid rgba(255,255,255,0.18)",borderRadius:8,padding:"6px 10px",display:"flex",alignItems:"center",gap:8,pointerEvents:"auto",minWidth:200,maxWidth:"72%"},onClick:Q=>Q.stopPropagation(),children:[fe[z]&&((oe=ln[z])==null?void 0:oe.total)>1&&ze.jsxs(ze.Fragment,{children:[ze.jsx("button",{style:{background:Pe[z]?"#d32f2f":"#2e7d32",color:"#fff",border:"none",borderRadius:4,fontSize:12,padding:"4px 8px",cursor:"pointer"},title:Pe[z]?"Pause cine":"Play cine",onClick:()=>{pe(Q=>{const de=[...Q];return de[z]=!de[z],de})},children:Pe[z]?"Pause":"Play"}),ze.jsxs("label",{style:{color:"#ddd",fontSize:11,display:"flex",alignItems:"center",gap:4},children:["FPS",ze.jsx("input",{type:"range",min:1,max:30,step:1,value:Math.max(1,Math.min(30,Math.round(Ee[z]||12))),onChange:Q=>{const de=Number(Q.target.value);Qe(ge=>{const me=[...ge];return me[z]=de,me})}}),ze.jsx("span",{style:{minWidth:22,textAlign:"right"},children:Math.round(Ee[z]||12)})]})]}),(je[z]||[]).length>1&&ze.jsxs(ze.Fragment,{children:[ze.jsx("span",{style:{color:"#fff",fontSize:12,whiteSpace:"nowrap"},children:"Series"}),ze.jsx("input",{type:"range",min:0,max:Math.max(0,(je[z]||[]).length-1),step:1,value:Math.max(0,Math.min((je[z]||[]).length-1,se[z]||0)),onChange:Q=>{Da(z,Number(Q.target.value))},style:{width:140}}),ze.jsx("span",{style:{color:"#e0e0e0",fontSize:11,maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:((De=(ae=je[z])==null?void 0:ae[se[z]||0])==null?void 0:De.label)||"",children:((tt=(He=je[z])==null?void 0:He[se[z]||0])==null?void 0:tt.label)||"Series"})]})]}),sn[z]==="stack"&&J[z]&&ze.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"14px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:35,display:J[z].length>0?"flex":"none",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:(()=>{const Q=J[z]||[],de=Q.length;if(de===0)return null;const ge=A.current,me=ge==null?void 0:ge.getViewport(`CT_${z}`),N=me&&typeof me.getCurrentImageIdIndex=="function"?me.getCurrentImageIdIndex():-1,k=new Set(Ss[z]||[]),te=Q.map(Oe=>Oe.startsWith("external:")?!0:!!ct("imagePlaneModule",Oe)||!!ct("generalSeriesModule",Oe)),ve=te.reduce((Oe,W)=>Oe+(W?1:0),0),Ie=Q.reduce((Oe,W,$)=>Oe+(k.has($)?1:0),0),ke=Math.min(de,180),be=Array.from({length:ke},()=>({loaded:!1,viewed:!1,current:!1}));for(let Oe=0;Oe{var xe;const $=Oe.currentTarget.getBoundingClientRect(),R=Math.min($.height,Math.max(0,Oe.clientY-$.top)),V=$.height>0?R/$.height:0,Y=Math.min(de-1,Math.max(0,Math.round(V*(de-1)))),ye=(xe=A.current)==null?void 0:xe.getViewport(`CT_${z}`);ye&&typeof ye.setImageIdIndex=="function"&&sn[z]==="stack"&&(oa(ye.element,{imageIndex:Y}),Sn(z,ye))},children:[be.map((Oe,W)=>{let $="#3f3f3f";return Oe.loaded&&($="#2e7d32"),Oe.viewed&&($="#1565c0"),Oe.current&&($="#fbc02d"),ze.jsx("div",{style:{width:"100%",height:`${100/ke}%`,minHeight:1,background:$,opacity:Oe.loaded||Oe.viewed||Oe.current?.95:.45,borderBottom:W=0&&de>ke&&ze.jsx("div",{style:{position:"absolute",left:0,right:0,top:`${N/Math.max(1,de-1)*100}%`,height:2,background:"#ffeb3b",boxShadow:"0 0 4px #ffeb3b",transform:"translateY(-1px)",pointerEvents:"none"}})]})})()}),sn[z]==="volume"&&(()=>{const Q=A.current,de=Q==null?void 0:Q.getViewport(`CT_${z}`);let ge=0,me=0;return de&&typeof de.getNumberOfSlices=="function"&&typeof de.getSliceIndex=="function"&&(ge=de.getNumberOfSlices(),me=de.getSliceIndex()),ge>1?ze.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"12px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:30,display:"flex",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:ze.jsx("div",{style:{width:"8px",height:"100%",maxHeight:"100%",minHeight:0,borderRadius:"6px",background:"#222",position:"relative",display:"flex",flexDirection:"column",justifyContent:"flex-start",boxShadow:"0 0 8px #2196f3cc",overflow:"hidden",cursor:"pointer"},onClick:N=>{const te=N.currentTarget.getBoundingClientRect(),ve=N.clientY-te.top,Ie=Math.floor(ve/te.height*ge),ke=A.current,be=ke==null?void 0:ke.getViewport(`CT_${z}`);be&&(oa(be.element,{imageIndex:Ie}),be.render(),Sn(z,be))},children:Array.from({length:ge}).map((N,k)=>{const te=k===me;return ze.jsx("div",{style:{width:"100%",height:`${100/ge}%`,minHeight:te?1:0,background:te?"linear-gradient(to right, #ffeb3b 60%, #ff9800 100%)":"#444",opacity:te?.95:.4,transition:"background 0.3s, opacity 0.3s",borderBottom:k1||!J[z]||J[z].length===0)&&ze.jsx("div",{style:{position:"absolute",left:0,right:0,bottom:sn[z]==="stack"&&(fe[z]||(je[z]||[]).length>1)?56:8,zIndex:20,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",width:"100%",background:"none",borderRadius:"0",padding:0},children:ze.jsxs("div",{style:{position:"relative"},children:[ze.jsxs("button",{onClick:Q=>{Q.stopPropagation(),I(de=>de===z?null:z)},style:{padding:"6px 12px",background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",cursor:"pointer",pointerEvents:"auto",fontSize:13},title:"Choose stack",children:[(()=>{const Q=Array.isArray(Re)?Re[z]:void 0,de=typeof Q=="number"&&Se[Q]?Se[Q]:void 0,ge=de&&Array.isArray(de.imageIds)?de.imageIds:[],me=de?de.name||(de.caseId?`Case: ${de.caseId}`:void 0):void 0;if(me)return me;if(ge.length>0)return`Stack ${typeof Q=="number"?Q+1:"1"}`;const N=J[z]||[];return N.length>0?`Stack (${N.length} images)`:"No stack"})(),ze.jsx("span",{style:{marginLeft:8,opacity:.8},children:D===z?"▲":"▼"})]}),D===z&&ze.jsx("div",{ref:Q=>{Q&&Q.focus()},tabIndex:0,style:{position:"absolute",left:0,bottom:"110%",background:"#222",border:"1px solid #444",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",zIndex:100,minWidth:220,maxHeight:260,overflowY:"auto",overscrollBehavior:"contain",scrollbarWidth:"thin",padding:6},role:"listbox",onMouseDown:Q=>Q.stopPropagation(),onWheel:Q=>{var ge;try{Q.stopPropagation()}catch{}try{Q.preventDefault()}catch{}const de=Q.currentTarget;if(de){const me=Q.deltaY??((ge=Q.nativeEvent)==null?void 0:ge.deltaY)??0;de.scrollTop+=me}},onBlur:Q=>{const de=Q.currentTarget;setTimeout(()=>{if(!de){I(null);return}de.contains(document.activeElement)||I(null)},0)},children:(()=>{const Q={};return Se.forEach((de,ge)=>{const me=de.studyId||de.studyInstanceUID||"Unspecified";Q[me]||(Q[me]=[]),Q[me].push({idx:ge,stack:de})}),Object.keys(Q).map(de=>ze.jsxs("div",{style:{marginBottom:6},children:[ze.jsx("div",{style:{fontSize:12,color:"#aaa",padding:"4px 8px",fontWeight:700},children:de==="Unspecified"?"Unspecified study":`Study: ${de}`}),ze.jsx("div",{children:Q[de].map(({idx:ge,stack:me})=>{const N=Array.isArray(me.imageIds)?me.imageIds:[],k=me&&(me.name||me.caseId)?me.name||`Case: ${me.caseId}`:`Stack ${ge+1}`,te=N.length,ve=!Array.isArray(N)||te===0;return ze.jsxs("button",{role:"option","aria-selected":!1,title:ve?"Invalid stack descriptor":`${k} — ${te} image${te===1?"":"s"}${me!=null&&me.caseId?` — case ${me.caseId}`:""}`,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",width:"100%",padding:"8px 12px",background:"transparent",color:"#fff",border:"none",textAlign:"left",cursor:ve?"not-allowed":"pointer"},onClick:Ie=>{if(Ie.stopPropagation(),ve){console.warn(`Attempted to select invalid stack at index ${ge}`,me);return}ut(z,ge).catch(ke=>console.error("Failed to load stack:",ke)),I(null)},children:[ze.jsx("div",{style:{fontWeight:"600",fontSize:13},children:k}),ze.jsxs("div",{style:{fontSize:12,opacity:.7},children:[te," image",te===1?"":"s",me!=null&&me.caseId?` • case ${me.caseId}`:""]})]},ge)})})]},de))})()})]})})]},z))}return ze.jsxs("div",{ref:a,style:{position:"relative",inset:0,width:"100%",height:"100%",boxSizing:"border-box",background:"#222",padding:"12px",overflow:"hidden"},children:[Dn&&ze.jsx("div",{style:{position:"absolute",zIndex:3e3,top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.7)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontSize:28,fontWeight:"bold",letterSpacing:1},children:Dn==="annotations"?"Loading Annotations...":Dn==="displayset"?"Loading Display Set...":"Loading Viewer State..."}),xn&&ze.jsxs("div",{style:{position:"fixed",top:12,left:12,right:12,zIndex:1e4,background:"#fff3cd",color:"#856404",border:"1px solid #ffeeba",padding:"10px 14px",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[ze.jsxs("div",{style:{flex:1,fontSize:14},children:[ze.jsx("strong",{children:"Graphics error:"})," The viewer encountered a WebGL/graphics error and may be unstable. Please reload the page.",br?ze.jsx("div",{style:{marginTop:6,fontSize:12,color:"#6b4f00"},children:br}):null]}),ze.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[ze.jsx("button",{onClick:()=>window.location.reload(),style:{padding:"6px 10px"},children:"Reload"}),ze.jsx("button",{onClick:()=>Ui(!1),style:{padding:"6px 10px"},children:"Dismiss"})]})]}),!h&&ze.jsx("button",{onClick:()=>g(!0),"aria-pressed":!1,title:"Open stacks",style:{position:"absolute",right:8,top:76,zIndex:120,width:24,height:42,background:"#1976d2",color:"#fff",border:"none",borderRadius:5,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",pointerEvents:"auto"},children:"▶"}),ze.jsxs("div",{children:[ze.jsx("button",{style:{position:"absolute",top:"50%",transform:"translateY(-50%)",left:Qr,zIndex:200,width:S,height:S,background:"#222",color:"#fff",border:"none",borderRadius:"50%",fontWeight:"bold",cursor:"pointer",fontSize:"22px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",transition:"left 0.25s cubic-bezier(.4,2,.6,1), background 0.2s"},onClick:()=>Es(z=>!z),"aria-label":"Open menu",children:"☰"}),ta&&ze.jsx("div",{style:{position:"absolute",top:0,left:0,width:C,height:"100%",background:"#222",color:"#fff",zIndex:199,boxShadow:"2px 0 12px rgba(0,0,0,0.3)",flexDirection:"column",padding:"24px 16px 16px 16px",display:"flex",overflow:"hidden"},children:ze.jsxs("div",{style:{flex:1,minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column"},children:[ze.jsxs("div",{style:{fontWeight:"bold",fontSize:18,marginBottom:24},children:["Menu",ze.jsx("button",{style:{float:"right",background:"transparent",color:"#fff",border:"none",fontSize:"22px",cursor:"pointer"},onClick:()=>Es(!1),"aria-label":"Close menu",children:"×"})]}),ze.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[ze.jsxs("label",{style:{fontSize:13},children:[ze.jsx("input",{type:"radio",name:"folderLoadMode",value:"add",checked:Xa==="add",onChange:()=>Ta("add")})," Add (append)"]}),ze.jsxs("label",{style:{fontSize:13},children:[ze.jsx("input",{type:"radio",name:"folderLoadMode",value:"replace",checked:Xa==="replace",onChange:()=>Ta("replace")})," Replace all"]})]}),ze.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:xc,children:"Load DICOM Folder"}),ze.jsx("input",{ref:Vn,type:"file",style:{display:"none"},multiple:!0,onChange:Ya}),ze.jsx("input",{ref:oi,type:"file",style:{display:"none"},multiple:!0,onChange:Ya,accept:".dcm,application/dicom"}),ze.jsxs("div",{style:{marginBottom:"18px",display:"flex",alignItems:"center",gap:"8px"},children:[ze.jsx("input",{type:"checkbox",id:"orderBySliceLocation",checked:Ur,onChange:z=>Cs(z.target.checked),style:{accentColor:"#666"}}),ze.jsx("label",{htmlFor:"orderBySliceLocation",style:{fontSize:"15px",cursor:"pointer"},children:"Order by Slice Location"})]}),ze.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:wc,children:"Show DICOM Metadata"}),ze.jsxs("button",{style:{padding:"10px 18px",background:Rt?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>mn(z=>!z),children:[Rt?"Disable":"Enable"," Cross Reference Lines"]}),ze.jsxs("button",{style:{padding:"10px 18px",background:Fr?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Lt(z=>!z),children:[Fr?"Disable":"Enable"," Reference Lines"]}),ze.jsx("button",{onClick:Bi,style:{margin:8,padding:8},children:"Sort All Viewports by Slice Location"}),ze.jsx("button",{style:{padding:"10px 18px",background:go?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Zi(z=>!z),children:go?"Disable Alt Key for Reference Cursors (Shift always works)":"Enable Alt Key for Reference Cursors (Shift always works)"}),ze.jsxs("button",{style:{padding:"10px 18px",background:G?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>X(z=>!z),children:[G?"Hide":"Show"," Annotation Navigation"]}),ze.jsxs("button",{style:{padding:"10px 18px",background:ee?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>ce(z=>!z),children:[ee?"Disable":"Enable"," Volume Diagnostics"]})]})})]}),ze.jsxs("div",{ref:_,className:"grid-menu-hover-container",style:{position:"absolute",top:ar||P?8:-18,left:"50%",transform:"translateX(-50%)",zIndex:100,display:"flex",flexDirection:"row",alignItems:"flex-start",gap:8,width:"auto",pointerEvents:"auto",transition:"top 180ms ease",paddingTop:28,marginTop:-28,paddingBottom:12},onMouseEnter:()=>O(!0),onMouseLeave:()=>{ar||O(!1)},children:[ze.jsxs("button",{style:{height:40,padding:"6px 12px 6px 10px",background:"#222",color:"#fff",border:"none",borderRadius:"0 0 4px 4px",fontWeight:"bold",cursor:"pointer",fontSize:"14px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",display:"inline-flex",alignItems:"center",gap:8},title:"Toggle viewer fullscreen",onFocus:()=>O(!0),onClick:()=>{O(!0),Sc()},children:[ze.jsx("span",{style:{fontSize:16,lineHeight:1},children:"⛶"}),ze.jsx("span",{children:"Fullscreen"})]}),ze.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"stretch"},children:[ze.jsxs("button",{className:"grid-menu-btn",style:{height:40,padding:"6px 14px 6px 10px",background:"#222",color:"#fff",border:"none",borderRadius:"0 0 4px 4px",fontWeight:"bold",cursor:"pointer",fontSize:"14px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",display:"inline-flex",alignItems:"center",gap:10,justifyContent:"space-between",minWidth:136},onFocus:()=>O(!0),onClick:()=>{O(!0),Qo(z=>!z)},tabIndex:0,children:[ze.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[ze.jsx("span",{style:{display:"grid",gridTemplateColumns:`repeat(${Ct.cols}, 5px)`,gridTemplateRows:`repeat(${Ct.rows}, 5px)`,gap:2,padding:1},children:Array.from({length:Ct.rows*Ct.cols}).map((z,ne)=>ze.jsx("span",{style:{width:5,height:5,borderRadius:1,background:"#90caf9",display:"block"}},ne))}),ze.jsxs("span",{children:[Ct.rows,"x",Ct.cols]})]}),ze.jsx("span",{style:{opacity:.8},children:ar?"▲":"▼"})]}),ar&&ze.jsx("div",{style:{position:"absolute",top:"calc(100% + 8px)",right:0,background:"#222",color:"#fff",borderRadius:"6px",boxShadow:"0 2px 12px rgba(0,0,0,0.4)",padding:"12px",display:"grid",gridTemplateColumns:"repeat(3, minmax(68px, 1fr))",gap:"8px",zIndex:200,pointerEvents:"auto"},onMouseDown:z=>z.stopPropagation(),children:Sa.map(z=>ze.jsxs("button",{style:{minWidth:"68px",height:"54px",background:z.rows===Ct.rows&&z.cols===Ct.cols?"#444":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"13px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6},onClick:()=>{ji(),Zt({rows:z.rows,cols:z.cols}),Qo(!1),O(!1)},children:[ze.jsx("span",{style:{display:"grid",gridTemplateColumns:`repeat(${z.cols}, 6px)`,gridTemplateRows:`repeat(${z.rows}, 6px)`,gap:2},children:Array.from({length:z.rows*z.cols}).map((ne,he)=>ze.jsx("span",{style:{width:6,height:6,borderRadius:1,background:"#90caf9",display:"block"}},he))}),ze.jsxs("span",{children:[z.rows,"x",z.cols]})]},`${z.rows}x${z.cols}`))})]})]}),ze.jsxs("div",{style:{display:"flex",flexDirection:"row",height:"calc(100% - 48px)",gap:8},children:[ze.jsxs("div",{style:{flex:1,display:"grid",margin:3,gridTemplateRows:`repeat(${Ct.rows}, 1fr)`,gridTemplateColumns:`repeat(${Ct.cols}, 1fr)`,gap:"5px",minHeight:0,minWidth:0,zIndex:1,position:"relative"},children:[Os,ze.jsx("button",{style:{position:"absolute",top:8,right:8,zIndex:2600,padding:"6px 12px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer",opacity:.85,userSelect:"none"},onClick:()=>d(!0),children:"Settings"})]}),ze.jsxs("div",{style:{width:h?p:0,transition:"width 220ms ease",display:"flex",flexDirection:"column",pointerEvents:h?"auto":"none",overflow:"hidden",position:"relative"},children:[h&&ze.jsx("div",{onMouseDown:_a,title:"Resize stacks panel",style:{position:"absolute",left:0,top:0,width:8,height:"100%",cursor:"col-resize",zIndex:2800,background:"linear-gradient(to right, rgba(100,181,246,0.25), rgba(100,181,246,0))"}}),ze.jsx("div",{style:{pointerEvents:"auto",width:"100%",height:"100%"},children:ze.jsxs("div",{style:{height:"100%",width:"100%",background:"#1f2428",color:"#fff",boxShadow:"0 2px 14px rgba(0,0,0,0.45)",borderLeft:"1px solid #2f3336",transform:"translateX(0)",transition:"transform 220ms ease",display:"flex",flexDirection:"column",overflow:"hidden"},children:[ze.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid #2b2f31"},children:[ze.jsx("div",{style:{fontWeight:700},children:"Stacks"}),ze.jsxs("div",{style:{fontSize:12,color:"#9bb4c8"},children:["Active VP: ",_e!==null?_e+1:"-"]}),ze.jsx("div",{style:{display:"flex",gap:8,alignItems:"center"},children:ze.jsx("button",{title:"Close",onClick:()=>{g(!1)},style:{background:"transparent",color:"#fff",border:"none",cursor:"pointer",fontSize:16},children:"×"})})]}),ze.jsx("div",{style:{overflowY:"auto",padding:8,flex:1},children:Se.length===0?ze.jsx("div",{style:{color:"#999",padding:12},children:"No stacks available"}):ze.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:Se.map((z,ne)=>{const he=Array.isArray(z.imageIds)?z.imageIds:[],le=z.name||(z.caseId?`Case: ${z.caseId}`:`Stack ${ne+1}`),Q=he.length,de=!Array.isArray(he)||Q===0,ge=Re.includes(ne),me=_e!==null&&Re[_e]===ne,N=Math.floor(he.length/2),k=he[N]||he[0],te=k?zs(k):null;return ze.jsxs("div",{draggable:!de,onDragStart:ve=>{de||(Ne(ne),K(null),ve.dataTransfer.setData("text/stack-idx",String(ne)),ve.dataTransfer.effectAllowed="copy")},onDragEnd:()=>{Ne(null),K(null)},onClick:()=>{if(de)return;ut(_e??0,ne)},style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 10px",background:me?"#0d47a1":ge?"#1976d2":"transparent",color:ge?"#fff":"#ddd",border:me?"1px solid #64b5f6":"1px solid transparent",borderRadius:6,cursor:de?"not-allowed":"pointer"},children:[ze.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(()=>{const ve=Ue[ne],Ie=ve&&ve!=="BROKEN"?ve:null,ke=Ie||te||null;return ke?ze.jsx("img",{"data-thumb-stack":ne,src:ke,alt:le,style:{width:56,height:56,objectFit:"cover",borderRadius:4,background:"#111"},onError:()=>{if(console.warn("Thumbnail failed to load for stack",ne,ke),!!Ie){lt(ne,"BROKEN");return}ot.current[ne]||Ao(ne,k)}}):ze.jsx("div",{style:{width:56,height:56,borderRadius:4,background:"#111",display:"flex",alignItems:"center",justifyContent:"center",color:"#777"},children:"No Img"})})(),ze.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[ze.jsx("div",{style:{fontWeight:600},children:le}),ze.jsxs("div",{style:{fontSize:12,opacity:.7},children:[Q," img",Q===1?"":"s"]})]})]}),ze.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:4},children:[ze.jsx("div",{style:{fontSize:12,opacity:.8},children:z.studyId||""}),me&&ze.jsx("div",{style:{fontSize:11,color:"#bbdefb",fontWeight:700},children:"ACTIVE"})]})]},ne)})})})]})})]})]}),u&&ze.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.4)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>d(!1),children:ze.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",minHeight:"180px",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative"},onClick:z=>z.stopPropagation(),children:[ze.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"Settings"}),ze.jsxs("div",{style:{marginBottom:"24px"},children:[ze.jsx("div",{style:{marginBottom:12,fontWeight:"bold"},children:"Mouse Button Tool Bindings"}),Z7.map(z=>ze.jsxs("div",{style:{marginBottom:10},children:[ze.jsxs("label",{style:{marginRight:8},children:[z.label," Button:"]}),ze.jsx("select",{value:Ii[z.value],onChange:ne=>Ts(he=>({...he,[z.value]:ne.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:l0.map(ne=>ze.jsx("option",{value:ne.value,title:ne.label,children:`${ne.icon?`${ne.icon} `:""}${ne.label}`},ne.value))})]},z.value)),ze.jsxs("div",{style:{margin:"12px 0"},children:[ze.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>Yt(z=>!z),children:[Cn?"Hide":"Show"," Advanced Mouse Bindings"]}),Cn&&ze.jsx("div",{style:{marginTop:8},children:ev.slice(3).map(z=>ze.jsxs("div",{style:{marginBottom:10},children:[ze.jsxs("label",{style:{marginRight:8},children:[z.label,":"]}),ze.jsxs("select",{value:Ii[z.value]||"",onChange:ne=>Ts(he=>({...he,[z.value]:ne.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[ze.jsx("option",{value:"",children:"(None)"}),l0.map(ne=>ze.jsx("option",{value:ne.value,title:ne.label,children:`${ne.icon?`${ne.icon} `:""}${ne.label}`},ne.value))]})]},z.value))})]}),ze.jsx("div",{style:{margin:"18px 0 8px 0",fontWeight:"bold"},children:"Ctrl + Mouse Button Tool Bindings"}),Z7.map(z=>ze.jsxs("div",{style:{marginBottom:10},children:[ze.jsxs("label",{style:{marginRight:8},children:[z.label," + Ctrl:"]}),ze.jsxs("select",{value:ko[z.value]||"",onChange:ne=>_s(he=>({...he,[z.value]:ne.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[ze.jsx("option",{value:"",children:"(None)"}),l0.map(ne=>ze.jsx("option",{value:ne.value,title:ne.label,children:`${ne.icon?`${ne.icon} `:""}${ne.label}`},ne.value))]})]},z.value+"_ctrl")),ze.jsxs("div",{style:{margin:"12px 0"},children:[ze.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>hi(z=>!z),children:[jt?"Hide":"Show"," Advanced Ctrl + Mouse Bindings"]}),jt&&ze.jsx("div",{style:{marginTop:8},children:ev.slice(3).map(z=>ze.jsxs("div",{style:{marginBottom:10},children:[ze.jsxs("label",{style:{marginRight:8},children:[z.label," + Ctrl:"]}),ze.jsxs("select",{value:ko[z.value]||"",onChange:ne=>_s(he=>({...he,[z.value]:ne.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[ze.jsx("option",{value:"",children:"(None)"}),l0.map(ne=>ze.jsx("option",{value:ne.value,title:ne.label,children:`${ne.icon?`${ne.icon} `:""}${ne.label}`},ne.value))]})]},z.value+"_ctrl"))})]})]}),ze.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>d(!1),"aria-label":"Close",children:"×"})]})}),$i&&ze.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"rgba(0,0,0,0.5)",zIndex:2e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>Ir(!1),children:ze.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",maxWidth:"80vw",maxHeight:"80vh",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative",overflow:"auto"},onClick:z=>z.stopPropagation(),children:[ze.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"DICOM Metadata"}),yc,ze.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>Ir(!1),"aria-label":"Close",children:"×"})]})})]})}function c8e(t){console.log("Setting up tools...",t),xi(ef),xi(Mh),xi(Ld),xi(Wl),xi(Ph),xi(pf),xi(su),xi(mf),xi(au),xi(Ad),xi(gf),xi(sl),xi(Rh),xi(La),xi(Uc),xi(pd),xi(Nh);let e=jr(t);return e||(e=xF(t),e.addTool(Mh.toolName),e.addTool(ef.toolName),e.addTool(Wl.toolName),e.addTool(Ld.toolName,{loop:!1}),e.addTool(Ph.toolName),e.addTool(pf.toolName),e.addTool(Nh.toolName,{getTextCallback:()=>""}),e.addTool(mf.toolName),e.addTool(su.toolName,{statsCalculator:()=>null}),e.addTool(au.toolName,{calculateStats:!1,getTextCallback:()=>""}),e.addTool(Ad.toolName,{getTextCallback:()=>""}),e.addTool(gf.toolName,{calculateStats:!1}),e.addTool(sl.toolName,{}),e.addTool(Rh.toolName,{}),e.addTool(pd.toolName),e.addTool(La.toolName)),e}function Q7(t,e,r,n){if(!r.length||!e.length)return null;const i=r.map(o=>e.findIndex(a=>a===o.metadata.referencedImageId)).filter(o=>o!==-1).sort((o,a)=>o-a);if(!i.length)return null;if(n===1){for(let o of i)if(o>t)return o;return i[0]}else{for(let o=i.length-1;o>=0;o--)if(i[o]`wadouri:/test_images/stack2/IMG${r+1}.dcm`),Array.from({length:25},(e,r)=>`wadouri:/test_images/stack5/IMG${r+1}.dcm`),Array.from({length:26},(e,r)=>`wadouri:/test_images/stack3/IMG${r+1}.dcm`)]}const t3=new WeakMap,u8e=t=>{const e=t.trim();return!e||e.startsWith("external:")||e.startsWith("wadors:")?e:e.startsWith("wadouri:")?`wadouri:${e.slice(8).replace(/^:+/,"")}`:`wadouri:${e.replace(/^:+/,"")}`},W1=t=>t.map(u8e),eO=t=>t?{imageIds:W1(t)}:{imageIds:[]},f8e=t=>{if(!t)return[];if(Array.isArray(t)&&t.length>0&&typeof t[0]=="string")return[eO(t)];if(!Array.isArray(t))return[];const e=[];return t.forEach((r,n)=>{if(r&&typeof r=="object"&&Array.isArray(r.stacks)){const i=r.caseId||r.caseUID||r.case||void 0,o=r.studyId||r.studyUID||r.studyInstanceUID||void 0;r.stacks.forEach((a,s)=>{let c=[];if(Array.isArray(a)?c=a:Array.isArray(a.imageIds)?c=a.imageIds:Array.isArray(a.i)&&(c=a.i),!Array.isArray(c)||c.length===0||!c.every(l=>typeof l=="string")){console.warn(`data-named-stacks: skipping invalid nested stack at parsed[${n}].stacks[${s}]`,a);return}e.push({imageIds:W1(c),name:a.name||a.label||void 0,caseId:i,studyId:a.studyId||o})});return}if(r&&typeof r=="object"&&(Array.isArray(r.imageIds)||Array.isArray(r.i))){const i=Array.isArray(r.imageIds)?r.imageIds:r.i;if(!Array.isArray(i)||i.length===0||!i.every(o=>typeof o=="string")){console.warn(`data-named-stacks: skipping invalid stack object at parsed[${n}]`,r);return}e.push({imageIds:W1(i),name:r.name||r.label||void 0,caseId:r.caseId||r.caseUID||void 0,studyId:r.studyId||r.studyUID||r.studyInstanceUID||void 0});return}if(Array.isArray(r)&&r.length>0&&typeof r[0]=="string"){e.push(eO(r));return}console.warn(`data-named-stacks: unknown or invalid entry at parsed[${n}] — skipping`,r)}),e},d8e=t=>JSON.stringify({id:t.id||"",empty:t.getAttribute("data-empty")||"",namedStacks:t.getAttribute("data-named-stacks")||"",images:t.getAttribute("data-images")||"",autoCache:t.getAttribute("data-auto-cache-stack")||"",annotation:t.getAttribute("data-annotationjson")||"",viewerState:t.getAttribute("data-viewerstate")||""}),tO=(t,e)=>!(e!=null&&e.containerIds)||e.containerIds.length===0?!0:e.containerIds.includes(t.id||""),nO=(t,e,r)=>{const n=d8e(t),i=t3.get(t);if(i&&!(r!=null&&r.force)&&i.signature===n)return;i&&(i.root.unmount(),t3.delete(t));const o=pP(t);o.render(ze.jsx(s8e,{container_id:t.id||"",imageStacks:e,autoCacheStack:t.getAttribute("data-auto-cache-stack")==="true"||t.getAttribute("data-auto-cache-stack")==="1",annotationJson:t.getAttribute("data-annotationjson")||void 0,viewerState:t.getAttribute("data-viewerstate")||void 0})),t3.set(t,{root:o,signature:n})};function eb(t){document.querySelectorAll(".dicom-viewer-test-root").forEach(n=>{if(!tO(n,t))return;n.id,nO(n,()=>l8e(),t)}),document.querySelectorAll(".dicom-viewer-root").forEach(n=>{if(!tO(n,t))return;let i;const o=n.getAttribute("data-empty")==="true",a=n.getAttribute("data-named-stacks"),s=n.getAttribute("data-images");if(o)i=()=>Promise.resolve([]);else if(a){let c;try{c=JSON.parse(a)}catch(f){console.error("Invalid data-named-stacks JSON:",f),c=[]}const l=f8e(c);i=()=>Promise.resolve(l)}else if(s){let c;try{c=JSON.parse(s)}catch(l){console.error("Invalid data-images JSON:",l),c=[]}Array.isArray(c)&&c.length>0&&typeof c[0]=="string"?i=()=>Promise.resolve([W1(c)]):Array.isArray(c)?i=()=>Promise.resolve(c.map(l=>Array.isArray(l)?W1(l):[])):i=()=>Promise.resolve([[]])}else i=()=>Promise.resolve([]);nO(n,i,t)})}eb();window.mountDicomViewers=eb;window.remountDicomViewer=t=>{eb({force:!0,containerIds:[t]})};