@etu-wiki/sharp-iiif-shims 0.1.31 → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -5,7 +5,7 @@ var ua=Object.create;var Je=Object.defineProperty;var Ca=Object.getOwnPropertyDe
|
|
|
5
5
|
`;function Aa(e){if(typeof Object.fromEntries<"u")return Object.fromEntries(e);let t={};for(let[A,i]of e)t[A.toLowerCase()]=i;return t}function Lg(e){let t=e.split(`\r
|
|
6
6
|
`).map(A=>{let i=A.split(":").map(n=>n.trim());return i[0]=i[0].toLowerCase(),i});return Aa(t)}function ea(e){let[t,...A]=e.split(";").map(n=>n.trim()),i=A.map(n=>n.split("="));return{type:t,params:Aa(i)}}function Mt(e){let t,A,i;return e&&([,t,A,i]=e.match(/bytes (\d+)-(\d+)\/(\d+)/),t=parseInt(t,10),A=parseInt(A,10),i=parseInt(i,10)),{start:t,end:A,total:i}}function ta(e,t){let A=null,i=new TextDecoder("ascii"),n=[],r=`--${t}`,g=`${r}--`;for(let o=0;o<10;++o)i.decode(new Uint8Array(e,o,r.length))===r&&(A=o);if(A===null)throw new Error("Could not find initial boundary");for(;A<e.byteLength;){let o=i.decode(new Uint8Array(e,A,Math.min(r.length+1024,e.byteLength-A)));if(o.length===0||o.startsWith(g))break;if(!o.startsWith(r))throw new Error("Part does not start with boundary");let l=o.substr(r.length+2);if(l.length===0)break;let a=l.indexOf($o),s=Lg(l.substr(0,a)),{start:I,end:c,total:f}=Mt(s["content-range"]),h=A+r.length+a+$o.length,B=parseInt(c,10)+1-parseInt(I,10);n.push({headers:s,data:e.slice(h,h+B),offset:I,length:B,fileSize:f}),A=h+B+4}return n}var Ie=class{async fetch(t,A=void 0){return Promise.all(t.map(i=>this.fetchSlice(i,A)))}async fetchSlice(t){throw new Error(`fetching of slice ${t} not possible, not implemented`)}get fileSize(){return null}async close(){}};var Ye=class extends Map{constructor(t={}){if(super(),!(t.maxSize&&t.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof t.maxAge=="number"&&t.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.maxSize=t.maxSize,this.maxAge=t.maxAge||Number.POSITIVE_INFINITY,this.onEviction=t.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_emitEvictions(t){if(typeof this.onEviction=="function")for(let[A,i]of t)this.onEviction(A,i.value)}_deleteIfExpired(t,A){return typeof A.expiry=="number"&&A.expiry<=Date.now()?(typeof this.onEviction=="function"&&this.onEviction(t,A.value),this.delete(t)):!1}_getOrDeleteIfExpired(t,A){if(this._deleteIfExpired(t,A)===!1)return A.value}_getItemValue(t,A){return A.expiry?this._getOrDeleteIfExpired(t,A):A.value}_peek(t,A){let i=A.get(t);return this._getItemValue(t,i)}_set(t,A){this.cache.set(t,A),this._size++,this._size>=this.maxSize&&(this._size=0,this._emitEvictions(this.oldCache),this.oldCache=this.cache,this.cache=new Map)}_moveToRecent(t,A){this.oldCache.delete(t),this._set(t,A)}*_entriesAscending(){for(let t of this.oldCache){let[A,i]=t;this.cache.has(A)||this._deleteIfExpired(A,i)===!1&&(yield t)}for(let t of this.cache){let[A,i]=t;this._deleteIfExpired(A,i)===!1&&(yield t)}}get(t){if(this.cache.has(t)){let A=this.cache.get(t);return this._getItemValue(t,A)}if(this.oldCache.has(t)){let A=this.oldCache.get(t);if(this._deleteIfExpired(t,A)===!1)return this._moveToRecent(t,A),A.value}}set(t,A,{maxAge:i=this.maxAge}={}){let n=typeof i=="number"&&i!==Number.POSITIVE_INFINITY?Date.now()+i:void 0;return this.cache.has(t)?this.cache.set(t,{value:A,expiry:n}):this._set(t,{value:A,expiry:n}),this}has(t){return this.cache.has(t)?!this._deleteIfExpired(t,this.cache.get(t)):this.oldCache.has(t)?!this._deleteIfExpired(t,this.oldCache.get(t)):!1}peek(t){if(this.cache.has(t))return this._peek(t,this.cache);if(this.oldCache.has(t))return this._peek(t,this.oldCache)}delete(t){let A=this.cache.delete(t);return A&&this._size--,this.oldCache.delete(t)||A}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}resize(t){if(!(t&&t>0))throw new TypeError("`maxSize` must be a number greater than 0");let A=[...this._entriesAscending()],i=A.length-t;i<0?(this.cache=new Map(A),this.oldCache=new Map,this._size=A.length):(i>0&&this._emitEvictions(A.slice(0,i)),this.oldCache=new Map(A.slice(i)),this.cache=new Map,this._size=0),this.maxSize=t}*keys(){for(let[t]of this)yield t}*values(){for(let[,t]of this)yield t}*[Symbol.iterator](){for(let t of this.cache){let[A,i]=t;this._deleteIfExpired(A,i)===!1&&(yield[A,i.value])}for(let t of this.oldCache){let[A,i]=t;this.cache.has(A)||this._deleteIfExpired(A,i)===!1&&(yield[A,i.value])}}*entriesDescending(){let t=[...this.cache];for(let A=t.length-1;A>=0;--A){let i=t[A],[n,r]=i;this._deleteIfExpired(n,r)===!1&&(yield[n,r.value])}t=[...this.oldCache];for(let A=t.length-1;A>=0;--A){let i=t[A],[n,r]=i;this.cache.has(n)||this._deleteIfExpired(n,r)===!1&&(yield[n,r.value])}}*entriesAscending(){for(let[t,A]of this._entriesAscending())yield[t,A.value]}get size(){if(!this._size)return this.oldCache.size;let t=0;for(let A of this.oldCache.keys())this.cache.has(A)||t++;return Math.min(this._size+t,this.maxSize)}entries(){return this.entriesAscending()}forEach(t,A=this){for(let[i,n]of this.entriesAscending())t.call(A,n,i,this)}get[Symbol.toStringTag](){return JSON.stringify([...this.entriesAscending()])}};async function ia(e){return new Promise(t=>setTimeout(t,e))}function na(e,t){let A=Array.isArray(e)?e:Array.from(e),i=Array.isArray(t)?t:Array.from(t);return A.map((n,r)=>[n,i[r]])}var RA=class e extends Error{constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.name="AbortError"}},Zi=class extends Error{constructor(t,A){super(A),this.errors=t,this.message=A,this.name="AggregateError"}},ra=Zi;var Xi=class{constructor(t,A,i=null){this.offset=t,this.length=A,this.data=i}get top(){return this.offset+this.length}},Lt=class{constructor(t,A,i){this.offset=t,this.length=A,this.blockIds=i}},Nt=class extends Ie{constructor(t,{blockSize:A=65536,cacheSize:i=100}={}){super(),this.source=t,this.blockSize=A,this.blockCache=new Ye({maxSize:i,onEviction:(n,r)=>{this.evictedBlocks.set(n,r)}}),this.evictedBlocks=new Map,this.blockRequests=new Map,this.blockIdsToFetch=new Set,this.abortedBlockIds=new Set}get fileSize(){return this.source.fileSize}async fetch(t,A){let i=[],n=[],r=[];this.evictedBlocks.clear();for(let{offset:c,length:f}of t){let h=c+f,{fileSize:B}=this;B!==null&&(h=Math.min(h,B));let u=Math.floor(c/this.blockSize)*this.blockSize;for(let d=u;d<h;d+=this.blockSize){let E=Math.floor(d/this.blockSize);!this.blockCache.has(E)&&!this.blockRequests.has(E)&&(this.blockIdsToFetch.add(E),n.push(E)),this.blockRequests.has(E)&&i.push(this.blockRequests.get(E)),r.push(E)}}await ia(),this.fetchBlocks(A);let g=[];for(let c of n)this.blockRequests.has(c)&&g.push(this.blockRequests.get(c));await Promise.allSettled(i),await Promise.allSettled(g);let o=[],l=r.filter(c=>this.abortedBlockIds.has(c)||!this.blockCache.has(c));if(l.forEach(c=>this.blockIdsToFetch.add(c)),l.length>0&&A&&!A.aborted){this.fetchBlocks(null);for(let c of l){let f=this.blockRequests.get(c);if(!f)throw new Error(`Block ${c} is not in the block requests`);o.push(f)}await Promise.allSettled(o)}if(A&&A.aborted)throw new RA("Request was aborted");let a=r.map(c=>this.blockCache.get(c)||this.evictedBlocks.get(c)),s=a.filter(c=>!c);if(s.length)throw new ra(s,"Request failed");let I=new Map(na(r,a));return this.readSliceData(t,I)}fetchBlocks(t){if(this.blockIdsToFetch.size>0){let A=this.groupBlocks(this.blockIdsToFetch),i=this.source.fetch(A,t);for(let n=0;n<A.length;++n){let r=A[n];for(let g of r.blockIds)this.blockRequests.set(g,(async()=>{try{let o=(await i)[n],l=g*this.blockSize,a=l-o.offset,s=Math.min(a+this.blockSize,o.data.byteLength),I=o.data.slice(a,s),c=new Xi(l,I.byteLength,I,g);this.blockCache.set(g,c),this.abortedBlockIds.delete(g)}catch(o){if(o.name==="AbortError")o.signal=t,this.blockCache.delete(g),this.abortedBlockIds.add(g);else throw o}finally{this.blockRequests.delete(g)}})())}this.blockIdsToFetch.clear()}}groupBlocks(t){let A=Array.from(t).sort((g,o)=>g-o);if(A.length===0)return[];let i=[],n=null,r=[];for(let g of A)n===null||n+1===g?(i.push(g),n=g):(r.push(new Lt(i[0]*this.blockSize,i.length*this.blockSize,i)),i=[g],n=g);return r.push(new Lt(i[0]*this.blockSize,i.length*this.blockSize,i)),r}readSliceData(t,A){return t.map(i=>{let n=i.offset+i.length;this.fileSize!==null&&(n=Math.min(this.fileSize,n));let r=Math.floor(i.offset/this.blockSize),g=Math.floor(n/this.blockSize),o=new ArrayBuffer(i.length),l=new Uint8Array(o);for(let a=r;a<=g;++a){let s=A.get(a),I=s.offset-i.offset,c=s.top-n,f=0,h=0,B;I<0?f=-I:I>0&&(h=I),c<0?B=s.length-f:B=n-s.offset-f;let u=new Uint8Array(s.data,f,B);l.set(u,h)}return o})}};var BA=class{get ok(){return this.status>=200&&this.status<=299}get status(){throw new Error("not implemented")}getHeader(t){throw new Error("not implemented")}async getData(){throw new Error("not implemented")}},uA=class{constructor(t){this.url=t}async request({headers:t,signal:A}={}){throw new Error("request is not implemented")}};var ji=class extends BA{constructor(t){super(),this.response=t}get status(){return this.response.status}getHeader(t){return this.response.headers.get(t)}async getData(){return this.response.arrayBuffer?await this.response.arrayBuffer():(await this.response.buffer()).buffer}},Tt=class extends uA{constructor(t,A){super(t),this.credentials=A}async request({headers:t,signal:A}={}){let i=await fetch(this.url,{headers:t,credentials:this.credentials,signal:A});return new ji(i)}};var Wi=class extends BA{constructor(t,A){super(),this.xhr=t,this.data=A}get status(){return this.xhr.status}getHeader(t){return this.xhr.getResponseHeader(t)}async getData(){return this.data}},Ot=class extends uA{constructRequest(t,A){return new Promise((i,n)=>{let r=new XMLHttpRequest;r.open("GET",this.url),r.responseType="arraybuffer";for(let[g,o]of Object.entries(t))r.setRequestHeader(g,o);r.onload=()=>{let g=r.response;i(new Wi(r,g))},r.onerror=n,r.onabort=()=>n(new RA("Request aborted")),r.send(),A&&(A.aborted&&r.abort(),A.addEventListener("abort",()=>r.abort()))})}async request({headers:t,signal:A}={}){return await this.constructRequest(t,A)}};var la=HA(oa(),1),ga=HA(aa(),1),fa=HA(sa(),1);var $i=class extends BA{constructor(t,A){super(),this.response=t,this.dataPromise=A}get status(){return this.response.statusCode}getHeader(t){return this.response.headers[t]}async getData(){return await this.dataPromise}},qt=class extends uA{constructor(t){super(t),this.parsedUrl=fa.default.parse(this.url),this.httpApi=this.parsedUrl.protocol==="http:"?la.default:ga.default}constructRequest(t,A){return new Promise((i,n)=>{let r=this.httpApi.get({...this.parsedUrl,headers:t},g=>{let o=new Promise(l=>{let a=[];g.on("data",s=>{a.push(s)}),g.on("end",()=>{let s=Buffer.concat(a).buffer;l(s)}),g.on("error",n)});i(new $i(g,o))});r.on("error",n),A&&(A.aborted&&r.destroy(new RA("Request aborted")),A.addEventListener("abort",()=>r.destroy(new RA("Request aborted"))))})}async request({headers:t,signal:A}={}){return await this.constructRequest(t,A)}};var he=class extends Ie{constructor(t,A,i,n){super(),this.client=t,this.headers=A,this.maxRanges=i,this.allowFullFile=n,this._fileSize=null}async fetch(t,A){return this.maxRanges>=t.length?this.fetchSlices(t,A):(this.maxRanges>0&&t.length>1,Promise.all(t.map(i=>this.fetchSlice(i,A))))}async fetchSlices(t,A){let i=await this.client.request({headers:{...this.headers,Range:`bytes=${t.map(({offset:n,length:r})=>`${n}-${n+r}`).join(",")}`},signal:A});if(i.ok)if(i.status===206){let{type:n,params:r}=ea(i.getHeader("content-type"));if(n==="multipart/byteranges"){let I=ta(await i.getData(),r.boundary);return this._fileSize=I[0].fileSize||null,I}let g=await i.getData(),{start:o,end:l,total:a}=Mt(i.getHeader("content-range"));this._fileSize=a||null;let s=[{data:g,offset:o,length:l-o}];if(t.length>1){let I=await Promise.all(t.slice(1).map(c=>this.fetchSlice(c,A)));return s.concat(I)}return s}else{if(!this.allowFullFile)throw new Error("Server responded with full file");let n=await i.getData();return this._fileSize=n.byteLength,[{data:n,offset:0,length:n.byteLength}]}else throw new Error("Error fetching data.")}async fetchSlice(t,A){let{offset:i,length:n}=t,r=await this.client.request({headers:{...this.headers,Range:`bytes=${i}-${i+n}`},signal:A});if(r.ok)if(r.status===206){let g=await r.getData(),{total:o}=Mt(r.getHeader("content-range"));return this._fileSize=o||null,{data:g,offset:i,length:n}}else{if(!this.allowFullFile)throw new Error("Server responded with full file");let g=await r.getData();return this._fileSize=g.byteLength,{data:g,offset:0,length:g.byteLength}}else throw new Error("Error fetching data.")}get fileSize(){return this._fileSize}};function Ht(e,{blockSize:t,cacheSize:A}){return t===null?e:new Nt(e,{blockSize:t,cacheSize:A})}function Ng(e,{headers:t={},credentials:A,maxRanges:i=0,allowFullFile:n=!1,...r}={}){let g=new Tt(e,A),o=new he(g,t,i,n);return Ht(o,r)}function Tg(e,{headers:t={},maxRanges:A=0,allowFullFile:i=!1,...n}={}){let r=new Ot(e),g=new he(r,t,A,i);return Ht(g,n)}function Og(e,{headers:t={},maxRanges:A=0,allowFullFile:i=!1,...n}={}){let r=new qt(e),g=new he(r,t,A,i);return Ht(g,n)}function ca(e,{headers:t={},maxRanges:A=0,allowFullFile:i=!1,...n}={}){let r=new he(e,t,A,i);return Ht(r,n)}function Ia(e,{forceXHR:t=!1,...A}={}){return typeof fetch=="function"&&!t?Ng(e,A):typeof XMLHttpRequest<"u"?Tg(e,A):Og(e,A)}nt();DA();function An(e){switch(e){case q.BYTE:case q.ASCII:case q.SBYTE:case q.UNDEFINED:return 1;case q.SHORT:case q.SSHORT:return 2;case q.LONG:case q.SLONG:case q.FLOAT:case q.IFD:return 4;case q.RATIONAL:case q.SRATIONAL:case q.DOUBLE:case q.LONG8:case q.SLONG8:case q.IFD8:return 8;default:throw new RangeError(`Invalid field type: ${e}`)}}function qg(e){let t=e.GeoKeyDirectory;if(!t)return null;let A={};for(let i=4;i<=t[3]*4;i+=4){let n=de[t[i]],r=t[i+1]?ee[t[i+1]]:null,g=t[i+2],o=t[i+3],l=null;if(!r)l=o;else{if(l=e[r],typeof l>"u"||l===null)throw new Error(`Could not get value of geoKey '${n}'.`);typeof l=="string"?l=l.substring(o,o+g-1):l.subarray&&(l=l.subarray(o,o+g),g===1&&(l=l[0]))}A[n]=l}return A}function Be(e,t,A,i){let n=null,r=null,g=An(t);switch(t){case q.BYTE:case q.ASCII:case q.UNDEFINED:n=new Uint8Array(A),r=e.readUint8;break;case q.SBYTE:n=new Int8Array(A),r=e.readInt8;break;case q.SHORT:n=new Uint16Array(A),r=e.readUint16;break;case q.SSHORT:n=new Int16Array(A),r=e.readInt16;break;case q.LONG:case q.IFD:n=new Uint32Array(A),r=e.readUint32;break;case q.SLONG:n=new Int32Array(A),r=e.readInt32;break;case q.LONG8:case q.IFD8:n=new Array(A),r=e.readUint64;break;case q.SLONG8:n=new Array(A),r=e.readInt64;break;case q.RATIONAL:n=new Uint32Array(A*2),r=e.readUint32;break;case q.SRATIONAL:n=new Int32Array(A*2),r=e.readInt32;break;case q.FLOAT:n=new Float32Array(A),r=e.readFloat32;break;case q.DOUBLE:n=new Float64Array(A),r=e.readFloat64;break;default:throw new RangeError(`Invalid field type: ${t}`)}if(t===q.RATIONAL||t===q.SRATIONAL)for(let o=0;o<A;o+=2)n[o]=r.call(e,i+o*g),n[o+1]=r.call(e,i+(o*g+4));else for(let o=0;o<A;++o)n[o]=r.call(e,i+o*g);return t===q.ASCII?new TextDecoder("utf-8").decode(n):n}var en=class{constructor(t,A,i){this.fileDirectory=t,this.geoKeyDirectory=A,this.nextIFDByteOffset=i}},ue=class extends Error{constructor(t){super(`No image at index ${t}`),this.index=t}},tn=class{async readRasters(t={}){let{window:A,width:i,height:n}=t,{resX:r,resY:g,bbox:o}=t,l=await this.getImage(),a=l,s=await this.getImageCount(),I=l.getBoundingBox();if(A&&o)throw new Error('Both "bbox" and "window" passed.');if(i||n){if(A){let[h,B]=l.getOrigin(),[u,d]=l.getResolution();o=[h+A[0]*u,B+A[1]*d,h+A[2]*u,B+A[3]*d]}let f=o||I;if(i){if(r)throw new Error("Both width and resX passed");r=(f[2]-f[0])/i}if(n){if(g)throw new Error("Both width and resY passed");g=(f[3]-f[1])/n}}if(r||g){let f=[];for(let h=0;h<s;++h){let B=await this.getImage(h),{SubfileType:u,NewSubfileType:d}=B.fileDirectory;(h===0||u===2||d&1)&&f.push(B)}f.sort((h,B)=>h.getWidth()-B.getWidth());for(let h=0;h<f.length;++h){let B=f[h],u=(I[2]-I[0])/B.getWidth(),d=(I[3]-I[1])/B.getHeight();if(a=B,r&&r>u||g&&g>d)break}}let c=A;if(o){let[f,h]=l.getOrigin(),[B,u]=a.getResolution(l);c=[Math.round((o[0]-f)/B),Math.round((o[1]-h)/u),Math.round((o[2]-f)/B),Math.round((o[3]-h)/u)],c=[Math.min(c[0],c[2]),Math.min(c[1],c[3]),Math.max(c[0],c[2]),Math.max(c[1],c[3])]}return a.readRasters({...t,window:c})}},Yt=class e extends tn{constructor(t,A,i,n,r={}){super(),this.source=t,this.littleEndian=A,this.bigTiff=i,this.firstIFDOffset=n,this.cache=r.cache||!1,this.ifdRequests=[],this.ghostValues=null}async getSlice(t,A){let i=this.bigTiff?4048:1024;return new He((await this.source.fetch([{offset:t,length:typeof A<"u"?A:i}]))[0],t,this.littleEndian,this.bigTiff)}async parseFileDirectoryAt(t){let A=this.bigTiff?20:12,i=this.bigTiff?8:2,n=await this.getSlice(t),r=this.bigTiff?n.readUint64(t):n.readUint16(t),g=r*A+(this.bigTiff?16:6);n.covers(t,g)||(n=await this.getSlice(t,g));let o={},l=t+(this.bigTiff?8:2);for(let I=0;I<r;l+=A,++I){let c=n.readUint16(l),f=n.readUint16(l+2),h=this.bigTiff?n.readUint64(l+4):n.readUint32(l+4),B,u,d=An(f),E=l+(this.bigTiff?12:8);if(d*h<=(this.bigTiff?8:4))B=Be(n,f,h,E);else{let x=n.readOffset(E),w=An(f)*h;if(n.covers(x,w))B=Be(n,f,h,x);else{let Q=await this.getSlice(x,w);B=Be(Q,f,h,x)}}h===1&&Xn.indexOf(c)===-1&&!(f===q.RATIONAL||f===q.SRATIONAL)?u=B[0]:u=B,o[ee[c]]=u}let a=qg(o),s=n.readOffset(t+i+A*r);return new en(o,a,s)}async requestIFD(t){if(this.ifdRequests[t])return this.ifdRequests[t];if(t===0)return this.ifdRequests[t]=this.parseFileDirectoryAt(this.firstIFDOffset),this.ifdRequests[t];if(!this.ifdRequests[t-1])try{this.ifdRequests[t-1]=this.requestIFD(t-1)}catch(A){throw A instanceof ue?new ue(t):A}return this.ifdRequests[t]=(async()=>{let A=await this.ifdRequests[t-1];if(A.nextIFDByteOffset===0)throw new ue(t);return this.parseFileDirectoryAt(A.nextIFDByteOffset)})(),this.ifdRequests[t]}async getImage(t=0){let A=await this.requestIFD(t);return new Wo(A.fileDirectory,A.geoKeyDirectory,this.dataView,this.littleEndian,this.cache,this.source)}async getImageCount(){let t=0,A=!0;for(;A;)try{await this.requestIFD(t),++t}catch(i){if(i instanceof ue)A=!1;else throw i}return t}async getGhostValues(){let t=this.bigTiff?16:8;if(this.ghostValues)return this.ghostValues;let A="GDAL_STRUCTURAL_METADATA_SIZE=",i=A.length+100,n=await this.getSlice(t,i);if(A===Be(n,q.ASCII,A.length,t)){let g=Be(n,q.ASCII,i,t).split(`
|
|
7
7
|
`)[0],o=Number(g.split("=")[1].split(" ")[0])+g.length;o>i&&(n=await this.getSlice(t,o));let l=Be(n,q.ASCII,o,t);this.ghostValues={},l.split(`
|
|
8
|
-
`).filter(a=>a.length>0).map(a=>a.split("=")).forEach(([a,s])=>{this.ghostValues[a]=s})}return this.ghostValues}static async fromSource(t,A,i){let n=(await t.fetch([{offset:0,length:1024}],i))[0],r=new qe(n),g=r.getUint16(0,0),o;if(g===18761)o=!0;else if(g===19789)o=!1;else throw new TypeError("Invalid byte order value.");let l=r.getUint16(2,o),a;if(l===42)a=!1;else if(l===43){if(a=!0,r.getUint16(4,o)!==8)throw new Error("Unsupported offset byte-size.")}else throw new TypeError("Invalid magic number.");let s=a?r.getUint64(8,o):r.getUint32(4,o);return new e(t,o,a,s,A)}close(){return typeof this.source.close=="function"?this.source.close():!1}};async function ha(e,t={},A){return Yt.fromSource(Ia(e,t),A)}async function nn(e,t={},A){return Yt.fromSource(ca(e,t),A)}var Hg=1e8,Yg=1e4,Jg=1e4,Kg={2:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByWhListed","sizeByForcedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"],2.1:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByConfinedWh","sizeByDistortedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeByWhListed","sizeByForcedWh"],3:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeUpscaling"]},rn=class extends ${async decode(t,A){let i=Array.isArray(t.BitsPerSample)?t.BitsPerSample.length:t.SamplesPerPixel||4,n=(0,XA.default)(A,{sequentialRead:!0}),g=(await n.metadata()).channels||4;i===4&&g<4&&n.ensureAlpha?n=n.ensureAlpha():i===3&&g>3&&n.removeAlpha&&(n=n.removeAlpha());let{data:o,info:l}=await n.raw().toBuffer({resolveWithObject:!0});if(l.channels!==i){let a=l.width*l.height,s=Buffer.alloc(a*i),I=o;for(let c=0;c<a;c+=1){let f=c*l.channels,h=c*i;for(let B=0;B<i;B+=1)B<l.channels?s[h+B]=I[f+B]:s[h+B]=B===3?255:0}return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}return o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)}};CA(50001,()=>Promise.resolve(rn));var on=class extends BA{constructor(t){super(),this.result=t}get ok(){return this.result.res.status>=200&&this.result.res.status<300}get status(){return this.result.res.status}getHeader(t){return this.result.res.headers[t.toLowerCase()]}getData(){return Buffer.isBuffer(this.result.content)?this.result.content.buffer.slice(this.result.content.byteOffset,this.result.content.byteOffset+this.result.content.byteLength):this.result.content}},an=class extends uA{constructor(t,A){super(t),this.objectKey=t,this.ossClient=A}async request({headers:t={}}={}){let A={timeout:3e4};if(t&&t.Range){let n=t.Range.match(/bytes=(\d+)-(\d+)/);if(n){let r=parseInt(n[1],10),g=parseInt(n[2],10);A.range=`${r}-${g}`,A.headers={Range:`bytes=${r}-${g}`,"x-oss-range-behavior":"standard"}}}A.headers||(A.headers={});for(let[n,r]of Object.entries(t))n!=="Range"&&(A.headers[n.toLowerCase()]=r);let i=await this.ossClient.get(this.objectKey,A);return new on(i)}};async function zg(e,t){let A=new an(e,t);return nn(A)}var Jt=new Map,sn=class extends BA{constructor(t,A){super(),this.response=t,this.arrayBuffer=A}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(t){return this.response.headers.get(t)||""}getData(){return this.arrayBuffer}},ln=class extends uA{constructor(t,A){super(t),this.ipfsUrl=t,this.verifiedFetch=A}extractCID(t){let A=t.match(/(?:ipfs:\/\/|\/ipfs\/)([a-zA-Z0-9]+)/);return A?A[1]:null}async request({headers:t={}}={}){console.log(t);let A=6e4,i=new AbortController,n=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),i.abort()},A);try{let r={headers:t,signal:i.signal,session:!1},g=await this.verifiedFetch(this.ipfsUrl,r);if(!g.ok)throw new Error(`Failed to fetch from IPFS: ${g.status} ${g.statusText}`);let o=await g.arrayBuffer();return clearTimeout(n),new sn(g,o)}catch(r){throw clearTimeout(n),console.error("[IPFSClient] Error during request:",r),r instanceof Error&&(console.error("[IPFSClient] Error name:",r.name),console.error("[IPFSClient] Error message:",r.message),console.error("[IPFSClient] Error stack:",r.stack)),r&&typeof r=="object"&&"errors"in r&&console.error("[IPFSClient] AggregateError details:",r.errors),r}}};async function Pg(e,t){let A=Jt.get(e);if(A)return A instanceof Promise?(console.log(`[fromIPFS] Waiting for in-flight GeoTIFF creation for ${e}`),await A):(console.log(`[fromIPFS] Using cached GeoTIFF client for ${e}`),A);console.log(`[fromIPFS] Creating new GeoTIFF client for ${e}`);let i=(async()=>{let n=new ln(e,t),r=await nn(n);return Jt.set(e,r),r})();Jt.set(e,i);try{return await i}catch(n){throw Jt.delete(e),n}}var gn=class extends Ee{constructor(t=Hg,A=Yg,i=Jg){super(t,A,i)}regionImpl(t,A){t&&(A=A.extract({left:t.x,top:t.y,width:t.w,height:t.h}))}sizeImpl(t,A){t&&(A=A.resize({...t,fit:"fill"}))}rotationImpl(t,A){t&&(t.isMirror&&(A=A.flop()),A=A.rotate(t.degree))}qualityFormatImpl(t,A,i,n,r){t&&(t==="color"?i=i.toColorspace("srgb"):t==="gray"||t==="grey"?i=i.grayscale():t==="bitonal"&&(i=i.threshold())),A&&(i=i.toFormat(A)),n==="png"&&(r.paletteBitDepth===1||r.space==="b-w")&&(i=i.toColorspace("b-w").png({colors:2}))}async generateTileRemote(t,A,i){let n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=n.pop(),c={width:A.width,height:A.height},f=super.normalizeRegionParams(s,c),h=super.normalizeSizeParams(a,{width:f?f.w:c.width,height:f?f.h:c.height}),{x:B,y:u,w:d,h:E}=f??{x:0,y:0,w:c.width,h:c.height},{width:x,height:w}=h;console.log(`Attempting to fetch from URL: ${i}`);let Q;if(typeof i=="string")console.log("Using standard HTTP fetch"),Q=await ha(i);else if(typeof I=="string"&&I.startsWith("bafy")){console.log("Detected CID id, using fromIPFS");let K=`ipfs://${I}`;Q=await Pg(K,i)}else Q=await zg(I,i);let C=await Q.getImage(0);console.log(`Source dimensions: ${C.getWidth()} x ${C.getHeight()}`),console.log(`Extracting region: x=${B}, y=${u}, w=${d}, h=${E}`),console.log(`Output size: ${x} x ${w}`);let y=await Q.getImageCount();console.log(`Total images (including overviews): ${y}`);let p=C.getSamplesPerPixel(),b;p>=3?(b=[0,1,2],p>=4&&b.push(3)):b=[0],console.log("Using automatic overview selection based on resolution...");let m=Math.max(d/x,E/w),k=C,S=1;for(let K=0;K<y;K++){let L=await Q.getImage(K),U=C.getWidth()/L.getWidth();U<=m&&U>S&&(S=U,k=L)}console.log(`Selected overview with scale: ${S.toFixed(2)}x`),console.log(`Overview dimensions: ${k.getWidth()} x ${k.getHeight()}`);let T=[Math.floor(B/S),Math.floor(u/S),Math.floor((B+d)/S),Math.floor((u+E)/S)],D;try{D=await k.readRasters({window:T,width:x,height:w,samples:b,interleave:!0,resampleMethod:"bilinear"})}catch(K){console.log(`Failed to read from overview: ${K.message}`);try{console.log("Attempting to read from main image...");let L=[B,u,B+d,u+E];D=await C.readRasters({window:L,width:x,height:w,samples:b,interleave:!0,resampleMethod:"bilinear"})}catch(L){console.log(`Failed to read from main image: ${L.message}`),console.log("Note: Range requests worked, but tile decoding failed. Falling back to full download.");let U=await i.get(I);return await this.generateTileLocal(t,A,U.content)}}let _=b.length,v=Buffer.from(D.buffer,D.byteOffset,D.byteLength),O={sequentialRead:!0,failOn:"none",raw:{width:x,height:w,channels:_}};(x>5e3||w>5e3)&&(O.limitInputPixels=!1);let F=(0,XA.default)(v,O),M=super.normalizeRotationParams(l);this.rotationImpl(M,F);let G=super.normalizeQualityParams(g),H=super.normalizeFormatParams(o,A.format);this.qualityFormatImpl(G,H,F,o,A);let J={};return J.body=F,J.contentType=super.getContentType(H),J}async generateTileLocal(t,A,i){let n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=super.normalizeRegionParams(s,A),c=super.normalizeSizeParams(a,{width:I?I.w:A.width,height:I?I.h:A.height}),f=super.normalizeRotationParams(l),h=super.normalizeQualityParams(g),B=super.normalizeFormatParams(o,A.format),{x:u,y:d,w:E,h:x}=I||{x:0,y:0,w:A.width,h:A.height},{width:w,height:Q}=c||{width:A.width,height:A.height},C=0,y;if(A.pages&&A.pages>1){let b=w/E,m=Q/x,k=Math.max(b,m);if(k>=.95)console.log("Pyramid optimization: using full resolution page (scale \u2248 1.0)"),C=0;else{C=A.pages-1;let T=Math.pow(2,A.pages-1),D=A.width/T,_=A.height/T;for(;C>0;){let v=E*(D/A.width),O=x*(_/A.height);if(v>=w*1.1&&O>=Q*1.1)break;C--,D*=2,_*=2}console.log(`Pyramid optimization: selected page ${C}/${A.pages-1} (scale: ${k.toFixed(2)}x, target: ${w}x${Q})`)}let S=A.is_hd||A.isHDImage?{limitInputPixels:!1,page:C,sequentialRead:!0,failOn:"none"}:{page:C,sequentialRead:!0,failOn:"none"};if(y=(0,XA.default)(i,S),I&&C>0){let T=await y.metadata(),D=T.width/A.width,_={x:Math.floor(u*D),y:Math.floor(d*D),w:Math.floor(E*D),h:Math.floor(x*D)};_.w=Math.min(_.w,T.width-_.x),_.h=Math.min(_.h,T.height-_.y),this.regionImpl(_,y)}else this.regionImpl(I,y)}else{let b=A.is_hd||A.isHDImage?{limitInputPixels:!1,sequentialRead:!0,failOn:"none"}:{sequentialRead:!0,failOn:"none"};y=(0,XA.default)(i,b),this.regionImpl(I,y)}this.sizeImpl(c,y),this.rotationImpl(f,y),this.qualityFormatImpl(h,B,y,o,A);let p={};return p.body=y,p.contentType=super.getContentType(B),p}generateImageInfo(t,A,i,n="2",r=512,g=512,o=""){let l=super.generateImageInfoTemp(t,A,i,n,r,g),a=l.info;if((i==="2.0"||i==="2.1")&&(a.profile=[super.uriPattern("compliance",i,n)],n==="2")){let s={};s.formats=["jpg","png","webp","jp2","pdf","tif"],s.qualities=["color","gray","bitonal","default","native","grey"],s.supports=Kg[Number(i)],a.profile.push(s)}return i==="3.0"&&o&&(a.extraFormats=[o],a.preferredFormats=[o]),o&&(a.formats=[o]),l.body=a,l}generateTilePipeline(t,A){let i=A.is_hd||A.isHDImage?(0,XA.default)({limitInputPixels:!1,sequentialRead:!0}):(0,XA.default)({sequentialRead:!0}),n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=!1,c=i,f={width:A.width,height:A.height};A&&A.orientation&&(I=!0,c=c.rotate(),A.orientation>=5&&(f={width:A.height,height:A.width}));let h=super.normalizeRegionParams(s,f);this.regionImpl(h,c);let B=super.normalizeSizeParams(a,{width:h?h.w:f.width,height:h?h.h:f.height});this.sizeImpl(B,c);let u=super.normalizeRotationParams(l);this.rotationImpl(u,c);let d=super.normalizeQualityParams(g),E=super.normalizeFormatParams(o,A.format);return this.qualityFormatImpl(d,E,c,o,A),h||B||u||d||E||I?c:(console.log("skip iiif transform"),null)}};
|
|
8
|
+
`).filter(a=>a.length>0).map(a=>a.split("=")).forEach(([a,s])=>{this.ghostValues[a]=s})}return this.ghostValues}static async fromSource(t,A,i){let n=(await t.fetch([{offset:0,length:1024}],i))[0],r=new qe(n),g=r.getUint16(0,0),o;if(g===18761)o=!0;else if(g===19789)o=!1;else throw new TypeError("Invalid byte order value.");let l=r.getUint16(2,o),a;if(l===42)a=!1;else if(l===43){if(a=!0,r.getUint16(4,o)!==8)throw new Error("Unsupported offset byte-size.")}else throw new TypeError("Invalid magic number.");let s=a?r.getUint64(8,o):r.getUint32(4,o);return new e(t,o,a,s,A)}close(){return typeof this.source.close=="function"?this.source.close():!1}};async function ha(e,t={},A){return Yt.fromSource(Ia(e,t),A)}async function nn(e,t={},A){return Yt.fromSource(ca(e,t),A)}var Hg=1e8,Yg=1e4,Jg=1e4,Kg={2:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByWhListed","sizeByForcedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"],2.1:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByConfinedWh","sizeByDistortedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeByWhListed","sizeByForcedWh"],3:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeUpscaling"]},rn=class extends ${async decode(t,A){let i=Array.isArray(t.BitsPerSample)?t.BitsPerSample.length:t.SamplesPerPixel||4,n=(0,XA.default)(A,{sequentialRead:!0}),g=(await n.metadata()).channels||4;i===4&&g<4&&n.ensureAlpha?n=n.ensureAlpha():i===3&&g>3&&n.removeAlpha&&(n=n.removeAlpha());let{data:o,info:l}=await n.raw().toBuffer({resolveWithObject:!0});if(l.channels!==i){let a=l.width*l.height,s=Buffer.alloc(a*i),I=o;for(let c=0;c<a;c+=1){let f=c*l.channels,h=c*i;for(let B=0;B<i;B+=1)B<l.channels?s[h+B]=I[f+B]:s[h+B]=B===3?255:0}return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}return o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)}};CA(50001,()=>Promise.resolve(rn));var on=class extends BA{constructor(t){super(),this.result=t}get ok(){return this.result.res.status>=200&&this.result.res.status<300}get status(){return this.result.res.status}getHeader(t){return this.result.res.headers[t.toLowerCase()]}getData(){return Buffer.isBuffer(this.result.content)?this.result.content.buffer.slice(this.result.content.byteOffset,this.result.content.byteOffset+this.result.content.byteLength):this.result.content}},an=class extends uA{constructor(t,A){super(t),this.objectKey=t,this.ossClient=A}async request({headers:t={}}={}){let A={timeout:3e4};if(t&&t.Range){let n=t.Range.match(/bytes=(\d+)-(\d+)/);if(n){let r=parseInt(n[1],10),g=parseInt(n[2],10);A.range=`${r}-${g}`,A.headers={Range:`bytes=${r}-${g}`,"x-oss-range-behavior":"standard"}}}A.headers||(A.headers={});for(let[n,r]of Object.entries(t))n!=="Range"&&(A.headers[n.toLowerCase()]=r);let i=await this.ossClient.get(this.objectKey,A);return new on(i)}};async function zg(e,t){let A=new an(e,t);return nn(A)}var Jt=new Map,sn=class extends BA{constructor(t,A){super(),this.response=t,this.arrayBuffer=A}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(t){return this.response.headers.get(t)||""}getData(){return this.arrayBuffer}},ln=class extends uA{constructor(t,A){super(t),this.ipfsUrl=t,this.verifiedFetch=A}extractCID(t){let A=t.match(/(?:ipfs:\/\/|\/ipfs\/)([a-zA-Z0-9]+)/);return A?A[1]:null}async request({headers:t={}}={}){console.log(t);let A=6e4,i=new AbortController,n=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),i.abort()},A);try{let r={headers:t,signal:i.signal,session:!1},g=await this.verifiedFetch(this.ipfsUrl,r);if(!g.ok)throw new Error(`Failed to fetch from IPFS: ${g.status} ${g.statusText}`);let o=await g.arrayBuffer();return clearTimeout(n),new sn(g,o)}catch(r){throw clearTimeout(n),console.error("[IPFSClient] Error during request:",r),r instanceof Error&&(console.error("[IPFSClient] Error name:",r.name),console.error("[IPFSClient] Error message:",r.message),console.error("[IPFSClient] Error stack:",r.stack)),r&&typeof r=="object"&&"errors"in r&&console.error("[IPFSClient] AggregateError details:",r.errors),r}}};async function Pg(e,t){let A=Jt.get(e);if(A)return A instanceof Promise?(console.log(`[fromIPFS] Waiting for in-flight GeoTIFF creation for ${e}`),await A):(console.log(`[fromIPFS] Using cached GeoTIFF client for ${e}`),A);console.log(`[fromIPFS] Creating new GeoTIFF client for ${e}`);let i=(async()=>{let n=new ln(e,t),r=await nn(n);return Jt.set(e,r),r})();Jt.set(e,i);try{return await i}catch(n){throw Jt.delete(e),n}}var gn=class extends Ee{constructor(t=Hg,A=Yg,i=Jg){super(t,A,i)}regionImpl(t,A){t&&(A=A.extract({left:t.x,top:t.y,width:t.w,height:t.h}))}sizeImpl(t,A){t&&(A=A.resize({...t,fit:"fill"}))}rotationImpl(t,A){t&&(t.isMirror&&(A=A.flop()),A=A.rotate(t.degree))}qualityFormatImpl(t,A,i,n,r){t&&(t==="color"?i=i.toColorspace("srgb"):t==="gray"||t==="grey"?i=i.grayscale():t==="bitonal"&&(i=i.threshold())),A&&(i=i.toFormat(n)),n==="png"&&(r.paletteBitDepth===1||r.space==="b-w")&&(i=i.toColorspace("b-w").png({colors:2}))}async generateTileRemote(t,A,i){let n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=n.pop(),c={width:A.width,height:A.height},f=super.normalizeRegionParams(s,c),h=super.normalizeSizeParams(a,{width:f?f.w:c.width,height:f?f.h:c.height}),{x:B,y:u,w:d,h:E}=f??{x:0,y:0,w:c.width,h:c.height},{width:x,height:w}=h;console.log(`Attempting to fetch from URL: ${i}`);let Q;if(typeof i=="string")console.log("Using standard HTTP fetch"),Q=await ha(i);else if(typeof I=="string"&&I.startsWith("bafy")){console.log("Detected CID id, using fromIPFS");let K=`ipfs://${I}`;Q=await Pg(K,i)}else Q=await zg(I,i);let C=await Q.getImage(0);console.log(`Source dimensions: ${C.getWidth()} x ${C.getHeight()}`),console.log(`Extracting region: x=${B}, y=${u}, w=${d}, h=${E}`),console.log(`Output size: ${x} x ${w}`);let y=await Q.getImageCount();console.log(`Total images (including overviews): ${y}`);let p=C.getSamplesPerPixel(),b;p>=3?(b=[0,1,2],p>=4&&b.push(3)):b=[0],console.log("Using automatic overview selection based on resolution...");let m=Math.max(d/x,E/w),k=C,S=1;for(let K=0;K<y;K++){let L=await Q.getImage(K),U=C.getWidth()/L.getWidth();U<=m&&U>S&&(S=U,k=L)}console.log(`Selected overview with scale: ${S.toFixed(2)}x`),console.log(`Overview dimensions: ${k.getWidth()} x ${k.getHeight()}`);let T=[Math.floor(B/S),Math.floor(u/S),Math.floor((B+d)/S),Math.floor((u+E)/S)],D;try{D=await k.readRasters({window:T,width:x,height:w,samples:b,interleave:!0,resampleMethod:"bilinear"})}catch(K){console.log(`Failed to read from overview: ${K.message}`);try{console.log("Attempting to read from main image...");let L=[B,u,B+d,u+E];D=await C.readRasters({window:L,width:x,height:w,samples:b,interleave:!0,resampleMethod:"bilinear"})}catch(L){console.log(`Failed to read from main image: ${L.message}`),console.log("Note: Range requests worked, but tile decoding failed. Falling back to full download.");let U=await i.get(I);return await this.generateTileLocal(t,A,U.content)}}let _=b.length,v=Buffer.from(D.buffer,D.byteOffset,D.byteLength),O={sequentialRead:!0,failOn:"none",raw:{width:x,height:w,channels:_}};(x>5e3||w>5e3)&&(O.limitInputPixels=!1);let F=(0,XA.default)(v,O),M=super.normalizeRotationParams(l);this.rotationImpl(M,F);let G=super.normalizeQualityParams(g),H=super.normalizeFormatParams(o,A.format);this.qualityFormatImpl(G,H,F,o,A);let J={};return J.body=F,J.contentType=super.getContentType(o),J}async generateTileLocal(t,A,i){let n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=super.normalizeRegionParams(s,A),c=super.normalizeSizeParams(a,{width:I?I.w:A.width,height:I?I.h:A.height}),f=super.normalizeRotationParams(l),h=super.normalizeQualityParams(g),B=super.normalizeFormatParams(o,A.format),{x:u,y:d,w:E,h:x}=I||{x:0,y:0,w:A.width,h:A.height},{width:w,height:Q}=c||{width:A.width,height:A.height},C=0,y;if(A.pages&&A.pages>1){let b=w/E,m=Q/x,k=Math.max(b,m);if(k>=.95)console.log("Pyramid optimization: using full resolution page (scale \u2248 1.0)"),C=0;else{C=A.pages-1;let T=Math.pow(2,A.pages-1),D=A.width/T,_=A.height/T;for(;C>0;){let v=E*(D/A.width),O=x*(_/A.height);if(v>=w*1.1&&O>=Q*1.1)break;C--,D*=2,_*=2}console.log(`Pyramid optimization: selected page ${C}/${A.pages-1} (scale: ${k.toFixed(2)}x, target: ${w}x${Q})`)}let S=A.is_hd||A.isHDImage?{limitInputPixels:!1,page:C,sequentialRead:!0,failOn:"none"}:{page:C,sequentialRead:!0,failOn:"none"};if(y=(0,XA.default)(i,S),I&&C>0){let T=await y.metadata(),D=T.width/A.width,_={x:Math.floor(u*D),y:Math.floor(d*D),w:Math.floor(E*D),h:Math.floor(x*D)};_.w=Math.min(_.w,T.width-_.x),_.h=Math.min(_.h,T.height-_.y),this.regionImpl(_,y)}else this.regionImpl(I,y)}else{let b=A.is_hd||A.isHDImage?{limitInputPixels:!1,sequentialRead:!0,failOn:"none"}:{sequentialRead:!0,failOn:"none"};y=(0,XA.default)(i,b),this.regionImpl(I,y)}this.sizeImpl(c,y),this.rotationImpl(f,y),this.qualityFormatImpl(h,B,y,o,A);let p={};return p.body=y,p.contentType=super.getContentType(o),p}generateImageInfo(t,A,i,n="2",r=512,g=512,o=""){let l=super.generateImageInfoTemp(t,A,i,n,r,g),a=l.info;if((i==="2.0"||i==="2.1")&&(a.profile=[super.uriPattern("compliance",i,n)],n==="2")){let s={};s.formats=["jpg","png","webp","jp2","pdf","tif"],s.qualities=["color","gray","bitonal","default","native","grey"],s.supports=Kg[Number(i)],a.profile.push(s)}return i==="3.0"&&o&&(a.extraFormats=[o],a.preferredFormats=[o]),o&&(a.formats=[o]),l.body=a,l}generateTilePipeline(t,A){let i=A.is_hd||A.isHDImage?(0,XA.default)({limitInputPixels:!1,sequentialRead:!0}):(0,XA.default)({sequentialRead:!0}),n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=!1,c=i,f={width:A.width,height:A.height};A&&A.orientation&&(I=!0,c=c.rotate(),A.orientation>=5&&(f={width:A.height,height:A.width}));let h=super.normalizeRegionParams(s,f);this.regionImpl(h,c);let B=super.normalizeSizeParams(a,{width:h?h.w:f.width,height:h?h.h:f.height});this.sizeImpl(B,c);let u=super.normalizeRotationParams(l);this.rotationImpl(u,c);let d=super.normalizeQualityParams(g),E=super.normalizeFormatParams(o,A.format);return this.qualityFormatImpl(d,E,c,o,A),h||B||u||d||E||I?c:(console.log("skip iiif transform"),null)}};
|
|
9
9
|
/*! Bundled license information:
|
|
10
10
|
|
|
11
11
|
pako/dist/pako.esm.mjs:
|
package/dist/index.mjs
CHANGED
|
@@ -5,7 +5,7 @@ var Ba=Object.create;var Kt=Object.defineProperty;var ua=Object.getOwnPropertyDe
|
|
|
5
5
|
`;function Wo(e){if(typeof Object.fromEntries<"u")return Object.fromEntries(e);let t={};for(let[A,i]of e)t[A.toLowerCase()]=i;return t}function Mg(e){let t=e.split(`\r
|
|
6
6
|
`).map(A=>{let i=A.split(":").map(n=>n.trim());return i[0]=i[0].toLowerCase(),i});return Wo(t)}function $o(e){let[t,...A]=e.split(";").map(n=>n.trim()),i=A.map(n=>n.split("="));return{type:t,params:Wo(i)}}function Gt(e){let t,A,i;return e&&([,t,A,i]=e.match(/bytes (\d+)-(\d+)\/(\d+)/),t=parseInt(t,10),A=parseInt(A,10),i=parseInt(i,10)),{start:t,end:A,total:i}}function Aa(e,t){let A=null,i=new TextDecoder("ascii"),n=[],r=`--${t}`,g=`${r}--`;for(let o=0;o<10;++o)i.decode(new Uint8Array(e,o,r.length))===r&&(A=o);if(A===null)throw new Error("Could not find initial boundary");for(;A<e.byteLength;){let o=i.decode(new Uint8Array(e,A,Math.min(r.length+1024,e.byteLength-A)));if(o.length===0||o.startsWith(g))break;if(!o.startsWith(r))throw new Error("Part does not start with boundary");let l=o.substr(r.length+2);if(l.length===0)break;let a=l.indexOf(jo),s=Mg(l.substr(0,a)),{start:I,end:c,total:f}=Gt(s["content-range"]),h=A+r.length+a+jo.length,B=parseInt(c,10)+1-parseInt(I,10);n.push({headers:s,data:e.slice(h,h+B),offset:I,length:B,fileSize:f}),A=h+B+4}return n}var ce=class{async fetch(t,A=void 0){return Promise.all(t.map(i=>this.fetchSlice(i,A)))}async fetchSlice(t){throw new Error(`fetching of slice ${t} not possible, not implemented`)}get fileSize(){return null}async close(){}};var Ye=class extends Map{constructor(t={}){if(super(),!(t.maxSize&&t.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof t.maxAge=="number"&&t.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.maxSize=t.maxSize,this.maxAge=t.maxAge||Number.POSITIVE_INFINITY,this.onEviction=t.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_emitEvictions(t){if(typeof this.onEviction=="function")for(let[A,i]of t)this.onEviction(A,i.value)}_deleteIfExpired(t,A){return typeof A.expiry=="number"&&A.expiry<=Date.now()?(typeof this.onEviction=="function"&&this.onEviction(t,A.value),this.delete(t)):!1}_getOrDeleteIfExpired(t,A){if(this._deleteIfExpired(t,A)===!1)return A.value}_getItemValue(t,A){return A.expiry?this._getOrDeleteIfExpired(t,A):A.value}_peek(t,A){let i=A.get(t);return this._getItemValue(t,i)}_set(t,A){this.cache.set(t,A),this._size++,this._size>=this.maxSize&&(this._size=0,this._emitEvictions(this.oldCache),this.oldCache=this.cache,this.cache=new Map)}_moveToRecent(t,A){this.oldCache.delete(t),this._set(t,A)}*_entriesAscending(){for(let t of this.oldCache){let[A,i]=t;this.cache.has(A)||this._deleteIfExpired(A,i)===!1&&(yield t)}for(let t of this.cache){let[A,i]=t;this._deleteIfExpired(A,i)===!1&&(yield t)}}get(t){if(this.cache.has(t)){let A=this.cache.get(t);return this._getItemValue(t,A)}if(this.oldCache.has(t)){let A=this.oldCache.get(t);if(this._deleteIfExpired(t,A)===!1)return this._moveToRecent(t,A),A.value}}set(t,A,{maxAge:i=this.maxAge}={}){let n=typeof i=="number"&&i!==Number.POSITIVE_INFINITY?Date.now()+i:void 0;return this.cache.has(t)?this.cache.set(t,{value:A,expiry:n}):this._set(t,{value:A,expiry:n}),this}has(t){return this.cache.has(t)?!this._deleteIfExpired(t,this.cache.get(t)):this.oldCache.has(t)?!this._deleteIfExpired(t,this.oldCache.get(t)):!1}peek(t){if(this.cache.has(t))return this._peek(t,this.cache);if(this.oldCache.has(t))return this._peek(t,this.oldCache)}delete(t){let A=this.cache.delete(t);return A&&this._size--,this.oldCache.delete(t)||A}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}resize(t){if(!(t&&t>0))throw new TypeError("`maxSize` must be a number greater than 0");let A=[...this._entriesAscending()],i=A.length-t;i<0?(this.cache=new Map(A),this.oldCache=new Map,this._size=A.length):(i>0&&this._emitEvictions(A.slice(0,i)),this.oldCache=new Map(A.slice(i)),this.cache=new Map,this._size=0),this.maxSize=t}*keys(){for(let[t]of this)yield t}*values(){for(let[,t]of this)yield t}*[Symbol.iterator](){for(let t of this.cache){let[A,i]=t;this._deleteIfExpired(A,i)===!1&&(yield[A,i.value])}for(let t of this.oldCache){let[A,i]=t;this.cache.has(A)||this._deleteIfExpired(A,i)===!1&&(yield[A,i.value])}}*entriesDescending(){let t=[...this.cache];for(let A=t.length-1;A>=0;--A){let i=t[A],[n,r]=i;this._deleteIfExpired(n,r)===!1&&(yield[n,r.value])}t=[...this.oldCache];for(let A=t.length-1;A>=0;--A){let i=t[A],[n,r]=i;this.cache.has(n)||this._deleteIfExpired(n,r)===!1&&(yield[n,r.value])}}*entriesAscending(){for(let[t,A]of this._entriesAscending())yield[t,A.value]}get size(){if(!this._size)return this.oldCache.size;let t=0;for(let A of this.oldCache.keys())this.cache.has(A)||t++;return Math.min(this._size+t,this.maxSize)}entries(){return this.entriesAscending()}forEach(t,A=this){for(let[i,n]of this.entriesAscending())t.call(A,n,i,this)}get[Symbol.toStringTag](){return JSON.stringify([...this.entriesAscending()])}};async function ea(e){return new Promise(t=>setTimeout(t,e))}function ta(e,t){let A=Array.isArray(e)?e:Array.from(e),i=Array.isArray(t)?t:Array.from(t);return A.map((n,r)=>[n,i[r]])}var RA=class e extends Error{constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.name="AbortError"}},Zi=class extends Error{constructor(t,A){super(A),this.errors=t,this.message=A,this.name="AggregateError"}},ia=Zi;var Xi=class{constructor(t,A,i=null){this.offset=t,this.length=A,this.data=i}get top(){return this.offset+this.length}},Mt=class{constructor(t,A,i){this.offset=t,this.length=A,this.blockIds=i}},Lt=class extends ce{constructor(t,{blockSize:A=65536,cacheSize:i=100}={}){super(),this.source=t,this.blockSize=A,this.blockCache=new Ye({maxSize:i,onEviction:(n,r)=>{this.evictedBlocks.set(n,r)}}),this.evictedBlocks=new Map,this.blockRequests=new Map,this.blockIdsToFetch=new Set,this.abortedBlockIds=new Set}get fileSize(){return this.source.fileSize}async fetch(t,A){let i=[],n=[],r=[];this.evictedBlocks.clear();for(let{offset:c,length:f}of t){let h=c+f,{fileSize:B}=this;B!==null&&(h=Math.min(h,B));let u=Math.floor(c/this.blockSize)*this.blockSize;for(let d=u;d<h;d+=this.blockSize){let E=Math.floor(d/this.blockSize);!this.blockCache.has(E)&&!this.blockRequests.has(E)&&(this.blockIdsToFetch.add(E),n.push(E)),this.blockRequests.has(E)&&i.push(this.blockRequests.get(E)),r.push(E)}}await ea(),this.fetchBlocks(A);let g=[];for(let c of n)this.blockRequests.has(c)&&g.push(this.blockRequests.get(c));await Promise.allSettled(i),await Promise.allSettled(g);let o=[],l=r.filter(c=>this.abortedBlockIds.has(c)||!this.blockCache.has(c));if(l.forEach(c=>this.blockIdsToFetch.add(c)),l.length>0&&A&&!A.aborted){this.fetchBlocks(null);for(let c of l){let f=this.blockRequests.get(c);if(!f)throw new Error(`Block ${c} is not in the block requests`);o.push(f)}await Promise.allSettled(o)}if(A&&A.aborted)throw new RA("Request was aborted");let a=r.map(c=>this.blockCache.get(c)||this.evictedBlocks.get(c)),s=a.filter(c=>!c);if(s.length)throw new ia(s,"Request failed");let I=new Map(ta(r,a));return this.readSliceData(t,I)}fetchBlocks(t){if(this.blockIdsToFetch.size>0){let A=this.groupBlocks(this.blockIdsToFetch),i=this.source.fetch(A,t);for(let n=0;n<A.length;++n){let r=A[n];for(let g of r.blockIds)this.blockRequests.set(g,(async()=>{try{let o=(await i)[n],l=g*this.blockSize,a=l-o.offset,s=Math.min(a+this.blockSize,o.data.byteLength),I=o.data.slice(a,s),c=new Xi(l,I.byteLength,I,g);this.blockCache.set(g,c),this.abortedBlockIds.delete(g)}catch(o){if(o.name==="AbortError")o.signal=t,this.blockCache.delete(g),this.abortedBlockIds.add(g);else throw o}finally{this.blockRequests.delete(g)}})())}this.blockIdsToFetch.clear()}}groupBlocks(t){let A=Array.from(t).sort((g,o)=>g-o);if(A.length===0)return[];let i=[],n=null,r=[];for(let g of A)n===null||n+1===g?(i.push(g),n=g):(r.push(new Mt(i[0]*this.blockSize,i.length*this.blockSize,i)),i=[g],n=g);return r.push(new Mt(i[0]*this.blockSize,i.length*this.blockSize,i)),r}readSliceData(t,A){return t.map(i=>{let n=i.offset+i.length;this.fileSize!==null&&(n=Math.min(this.fileSize,n));let r=Math.floor(i.offset/this.blockSize),g=Math.floor(n/this.blockSize),o=new ArrayBuffer(i.length),l=new Uint8Array(o);for(let a=r;a<=g;++a){let s=A.get(a),I=s.offset-i.offset,c=s.top-n,f=0,h=0,B;I<0?f=-I:I>0&&(h=I),c<0?B=s.length-f:B=n-s.offset-f;let u=new Uint8Array(s.data,f,B);l.set(u,h)}return o})}};var BA=class{get ok(){return this.status>=200&&this.status<=299}get status(){throw new Error("not implemented")}getHeader(t){throw new Error("not implemented")}async getData(){throw new Error("not implemented")}},uA=class{constructor(t){this.url=t}async request({headers:t,signal:A}={}){throw new Error("request is not implemented")}};var ji=class extends BA{constructor(t){super(),this.response=t}get status(){return this.response.status}getHeader(t){return this.response.headers.get(t)}async getData(){return this.response.arrayBuffer?await this.response.arrayBuffer():(await this.response.buffer()).buffer}},Nt=class extends uA{constructor(t,A){super(t),this.credentials=A}async request({headers:t,signal:A}={}){let i=await fetch(this.url,{headers:t,credentials:this.credentials,signal:A});return new ji(i)}};var Wi=class extends BA{constructor(t,A){super(),this.xhr=t,this.data=A}get status(){return this.xhr.status}getHeader(t){return this.xhr.getResponseHeader(t)}async getData(){return this.data}},Tt=class extends uA{constructRequest(t,A){return new Promise((i,n)=>{let r=new XMLHttpRequest;r.open("GET",this.url),r.responseType="arraybuffer";for(let[g,o]of Object.entries(t))r.setRequestHeader(g,o);r.onload=()=>{let g=r.response;i(new Wi(r,g))},r.onerror=n,r.onabort=()=>n(new RA("Request aborted")),r.send(),A&&(A.aborted&&r.abort(),A.addEventListener("abort",()=>r.abort()))})}async request({headers:t,signal:A}={}){return await this.constructRequest(t,A)}};var aa=ZA(na(),1),sa=ZA(ra(),1),la=ZA(oa(),1);var $i=class extends BA{constructor(t,A){super(),this.response=t,this.dataPromise=A}get status(){return this.response.statusCode}getHeader(t){return this.response.headers[t]}async getData(){return await this.dataPromise}},Ot=class extends uA{constructor(t){super(t),this.parsedUrl=la.default.parse(this.url),this.httpApi=this.parsedUrl.protocol==="http:"?aa.default:sa.default}constructRequest(t,A){return new Promise((i,n)=>{let r=this.httpApi.get({...this.parsedUrl,headers:t},g=>{let o=new Promise(l=>{let a=[];g.on("data",s=>{a.push(s)}),g.on("end",()=>{let s=Buffer.concat(a).buffer;l(s)}),g.on("error",n)});i(new $i(g,o))});r.on("error",n),A&&(A.aborted&&r.destroy(new RA("Request aborted")),A.addEventListener("abort",()=>r.destroy(new RA("Request aborted"))))})}async request({headers:t,signal:A}={}){return await this.constructRequest(t,A)}};var Ie=class extends ce{constructor(t,A,i,n){super(),this.client=t,this.headers=A,this.maxRanges=i,this.allowFullFile=n,this._fileSize=null}async fetch(t,A){return this.maxRanges>=t.length?this.fetchSlices(t,A):(this.maxRanges>0&&t.length>1,Promise.all(t.map(i=>this.fetchSlice(i,A))))}async fetchSlices(t,A){let i=await this.client.request({headers:{...this.headers,Range:`bytes=${t.map(({offset:n,length:r})=>`${n}-${n+r}`).join(",")}`},signal:A});if(i.ok)if(i.status===206){let{type:n,params:r}=$o(i.getHeader("content-type"));if(n==="multipart/byteranges"){let I=Aa(await i.getData(),r.boundary);return this._fileSize=I[0].fileSize||null,I}let g=await i.getData(),{start:o,end:l,total:a}=Gt(i.getHeader("content-range"));this._fileSize=a||null;let s=[{data:g,offset:o,length:l-o}];if(t.length>1){let I=await Promise.all(t.slice(1).map(c=>this.fetchSlice(c,A)));return s.concat(I)}return s}else{if(!this.allowFullFile)throw new Error("Server responded with full file");let n=await i.getData();return this._fileSize=n.byteLength,[{data:n,offset:0,length:n.byteLength}]}else throw new Error("Error fetching data.")}async fetchSlice(t,A){let{offset:i,length:n}=t,r=await this.client.request({headers:{...this.headers,Range:`bytes=${i}-${i+n}`},signal:A});if(r.ok)if(r.status===206){let g=await r.getData(),{total:o}=Gt(r.getHeader("content-range"));return this._fileSize=o||null,{data:g,offset:i,length:n}}else{if(!this.allowFullFile)throw new Error("Server responded with full file");let g=await r.getData();return this._fileSize=g.byteLength,{data:g,offset:0,length:g.byteLength}}else throw new Error("Error fetching data.")}get fileSize(){return this._fileSize}};function qt(e,{blockSize:t,cacheSize:A}){return t===null?e:new Lt(e,{blockSize:t,cacheSize:A})}function Lg(e,{headers:t={},credentials:A,maxRanges:i=0,allowFullFile:n=!1,...r}={}){let g=new Nt(e,A),o=new Ie(g,t,i,n);return qt(o,r)}function Ng(e,{headers:t={},maxRanges:A=0,allowFullFile:i=!1,...n}={}){let r=new Tt(e),g=new Ie(r,t,A,i);return qt(g,n)}function Tg(e,{headers:t={},maxRanges:A=0,allowFullFile:i=!1,...n}={}){let r=new Ot(e),g=new Ie(r,t,A,i);return qt(g,n)}function ga(e,{headers:t={},maxRanges:A=0,allowFullFile:i=!1,...n}={}){let r=new Ie(e,t,A,i);return qt(r,n)}function fa(e,{forceXHR:t=!1,...A}={}){return typeof fetch=="function"&&!t?Lg(e,A):typeof XMLHttpRequest<"u"?Ng(e,A):Tg(e,A)}it();DA();function An(e){switch(e){case q.BYTE:case q.ASCII:case q.SBYTE:case q.UNDEFINED:return 1;case q.SHORT:case q.SSHORT:return 2;case q.LONG:case q.SLONG:case q.FLOAT:case q.IFD:return 4;case q.RATIONAL:case q.SRATIONAL:case q.DOUBLE:case q.LONG8:case q.SLONG8:case q.IFD8:return 8;default:throw new RangeError(`Invalid field type: ${e}`)}}function Og(e){let t=e.GeoKeyDirectory;if(!t)return null;let A={};for(let i=4;i<=t[3]*4;i+=4){let n=de[t[i]],r=t[i+1]?Ae[t[i+1]]:null,g=t[i+2],o=t[i+3],l=null;if(!r)l=o;else{if(l=e[r],typeof l>"u"||l===null)throw new Error(`Could not get value of geoKey '${n}'.`);typeof l=="string"?l=l.substring(o,o+g-1):l.subarray&&(l=l.subarray(o,o+g),g===1&&(l=l[0]))}A[n]=l}return A}function he(e,t,A,i){let n=null,r=null,g=An(t);switch(t){case q.BYTE:case q.ASCII:case q.UNDEFINED:n=new Uint8Array(A),r=e.readUint8;break;case q.SBYTE:n=new Int8Array(A),r=e.readInt8;break;case q.SHORT:n=new Uint16Array(A),r=e.readUint16;break;case q.SSHORT:n=new Int16Array(A),r=e.readInt16;break;case q.LONG:case q.IFD:n=new Uint32Array(A),r=e.readUint32;break;case q.SLONG:n=new Int32Array(A),r=e.readInt32;break;case q.LONG8:case q.IFD8:n=new Array(A),r=e.readUint64;break;case q.SLONG8:n=new Array(A),r=e.readInt64;break;case q.RATIONAL:n=new Uint32Array(A*2),r=e.readUint32;break;case q.SRATIONAL:n=new Int32Array(A*2),r=e.readInt32;break;case q.FLOAT:n=new Float32Array(A),r=e.readFloat32;break;case q.DOUBLE:n=new Float64Array(A),r=e.readFloat64;break;default:throw new RangeError(`Invalid field type: ${t}`)}if(t===q.RATIONAL||t===q.SRATIONAL)for(let o=0;o<A;o+=2)n[o]=r.call(e,i+o*g),n[o+1]=r.call(e,i+(o*g+4));else for(let o=0;o<A;++o)n[o]=r.call(e,i+o*g);return t===q.ASCII?new TextDecoder("utf-8").decode(n):n}var en=class{constructor(t,A,i){this.fileDirectory=t,this.geoKeyDirectory=A,this.nextIFDByteOffset=i}},Be=class extends Error{constructor(t){super(`No image at index ${t}`),this.index=t}},tn=class{async readRasters(t={}){let{window:A,width:i,height:n}=t,{resX:r,resY:g,bbox:o}=t,l=await this.getImage(),a=l,s=await this.getImageCount(),I=l.getBoundingBox();if(A&&o)throw new Error('Both "bbox" and "window" passed.');if(i||n){if(A){let[h,B]=l.getOrigin(),[u,d]=l.getResolution();o=[h+A[0]*u,B+A[1]*d,h+A[2]*u,B+A[3]*d]}let f=o||I;if(i){if(r)throw new Error("Both width and resX passed");r=(f[2]-f[0])/i}if(n){if(g)throw new Error("Both width and resY passed");g=(f[3]-f[1])/n}}if(r||g){let f=[];for(let h=0;h<s;++h){let B=await this.getImage(h),{SubfileType:u,NewSubfileType:d}=B.fileDirectory;(h===0||u===2||d&1)&&f.push(B)}f.sort((h,B)=>h.getWidth()-B.getWidth());for(let h=0;h<f.length;++h){let B=f[h],u=(I[2]-I[0])/B.getWidth(),d=(I[3]-I[1])/B.getHeight();if(a=B,r&&r>u||g&&g>d)break}}let c=A;if(o){let[f,h]=l.getOrigin(),[B,u]=a.getResolution(l);c=[Math.round((o[0]-f)/B),Math.round((o[1]-h)/u),Math.round((o[2]-f)/B),Math.round((o[3]-h)/u)],c=[Math.min(c[0],c[2]),Math.min(c[1],c[3]),Math.max(c[0],c[2]),Math.max(c[1],c[3])]}return a.readRasters({...t,window:c})}},Ht=class e extends tn{constructor(t,A,i,n,r={}){super(),this.source=t,this.littleEndian=A,this.bigTiff=i,this.firstIFDOffset=n,this.cache=r.cache||!1,this.ifdRequests=[],this.ghostValues=null}async getSlice(t,A){let i=this.bigTiff?4048:1024;return new He((await this.source.fetch([{offset:t,length:typeof A<"u"?A:i}]))[0],t,this.littleEndian,this.bigTiff)}async parseFileDirectoryAt(t){let A=this.bigTiff?20:12,i=this.bigTiff?8:2,n=await this.getSlice(t),r=this.bigTiff?n.readUint64(t):n.readUint16(t),g=r*A+(this.bigTiff?16:6);n.covers(t,g)||(n=await this.getSlice(t,g));let o={},l=t+(this.bigTiff?8:2);for(let I=0;I<r;l+=A,++I){let c=n.readUint16(l),f=n.readUint16(l+2),h=this.bigTiff?n.readUint64(l+4):n.readUint32(l+4),B,u,d=An(f),E=l+(this.bigTiff?12:8);if(d*h<=(this.bigTiff?8:4))B=he(n,f,h,E);else{let x=n.readOffset(E),w=An(f)*h;if(n.covers(x,w))B=he(n,f,h,x);else{let Q=await this.getSlice(x,w);B=he(Q,f,h,x)}}h===1&&Vn.indexOf(c)===-1&&!(f===q.RATIONAL||f===q.SRATIONAL)?u=B[0]:u=B,o[Ae[c]]=u}let a=Og(o),s=n.readOffset(t+i+A*r);return new en(o,a,s)}async requestIFD(t){if(this.ifdRequests[t])return this.ifdRequests[t];if(t===0)return this.ifdRequests[t]=this.parseFileDirectoryAt(this.firstIFDOffset),this.ifdRequests[t];if(!this.ifdRequests[t-1])try{this.ifdRequests[t-1]=this.requestIFD(t-1)}catch(A){throw A instanceof Be?new Be(t):A}return this.ifdRequests[t]=(async()=>{let A=await this.ifdRequests[t-1];if(A.nextIFDByteOffset===0)throw new Be(t);return this.parseFileDirectoryAt(A.nextIFDByteOffset)})(),this.ifdRequests[t]}async getImage(t=0){let A=await this.requestIFD(t);return new Xo(A.fileDirectory,A.geoKeyDirectory,this.dataView,this.littleEndian,this.cache,this.source)}async getImageCount(){let t=0,A=!0;for(;A;)try{await this.requestIFD(t),++t}catch(i){if(i instanceof Be)A=!1;else throw i}return t}async getGhostValues(){let t=this.bigTiff?16:8;if(this.ghostValues)return this.ghostValues;let A="GDAL_STRUCTURAL_METADATA_SIZE=",i=A.length+100,n=await this.getSlice(t,i);if(A===he(n,q.ASCII,A.length,t)){let g=he(n,q.ASCII,i,t).split(`
|
|
7
7
|
`)[0],o=Number(g.split("=")[1].split(" ")[0])+g.length;o>i&&(n=await this.getSlice(t,o));let l=he(n,q.ASCII,o,t);this.ghostValues={},l.split(`
|
|
8
|
-
`).filter(a=>a.length>0).map(a=>a.split("=")).forEach(([a,s])=>{this.ghostValues[a]=s})}return this.ghostValues}static async fromSource(t,A,i){let n=(await t.fetch([{offset:0,length:1024}],i))[0],r=new qe(n),g=r.getUint16(0,0),o;if(g===18761)o=!0;else if(g===19789)o=!1;else throw new TypeError("Invalid byte order value.");let l=r.getUint16(2,o),a;if(l===42)a=!1;else if(l===43){if(a=!0,r.getUint16(4,o)!==8)throw new Error("Unsupported offset byte-size.")}else throw new TypeError("Invalid magic number.");let s=a?r.getUint64(8,o):r.getUint32(4,o);return new e(t,o,a,s,A)}close(){return typeof this.source.close=="function"?this.source.close():!1}};async function ca(e,t={},A){return Ht.fromSource(fa(e,t),A)}async function nn(e,t={},A){return Ht.fromSource(ga(e,t),A)}var qg=1e8,Hg=1e4,Yg=1e4,Jg={2:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByWhListed","sizeByForcedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"],2.1:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByConfinedWh","sizeByDistortedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeByWhListed","sizeByForcedWh"],3:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeUpscaling"]},rn=class extends ${async decode(t,A){let i=Array.isArray(t.BitsPerSample)?t.BitsPerSample.length:t.SamplesPerPixel||4,n=ue(A,{sequentialRead:!0}),g=(await n.metadata()).channels||4;i===4&&g<4&&n.ensureAlpha?n=n.ensureAlpha():i===3&&g>3&&n.removeAlpha&&(n=n.removeAlpha());let{data:o,info:l}=await n.raw().toBuffer({resolveWithObject:!0});if(l.channels!==i){let a=l.width*l.height,s=Buffer.alloc(a*i),I=o;for(let c=0;c<a;c+=1){let f=c*l.channels,h=c*i;for(let B=0;B<i;B+=1)B<l.channels?s[h+B]=I[f+B]:s[h+B]=B===3?255:0}return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}return o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)}};CA(50001,()=>Promise.resolve(rn));var on=class extends BA{constructor(t){super(),this.result=t}get ok(){return this.result.res.status>=200&&this.result.res.status<300}get status(){return this.result.res.status}getHeader(t){return this.result.res.headers[t.toLowerCase()]}getData(){return Buffer.isBuffer(this.result.content)?this.result.content.buffer.slice(this.result.content.byteOffset,this.result.content.byteOffset+this.result.content.byteLength):this.result.content}},an=class extends uA{constructor(t,A){super(t),this.objectKey=t,this.ossClient=A}async request({headers:t={}}={}){let A={timeout:3e4};if(t&&t.Range){let n=t.Range.match(/bytes=(\d+)-(\d+)/);if(n){let r=parseInt(n[1],10),g=parseInt(n[2],10);A.range=`${r}-${g}`,A.headers={Range:`bytes=${r}-${g}`,"x-oss-range-behavior":"standard"}}}A.headers||(A.headers={});for(let[n,r]of Object.entries(t))n!=="Range"&&(A.headers[n.toLowerCase()]=r);let i=await this.ossClient.get(this.objectKey,A);return new on(i)}};async function Kg(e,t){let A=new an(e,t);return nn(A)}var Yt=new Map,sn=class extends BA{constructor(t,A){super(),this.response=t,this.arrayBuffer=A}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(t){return this.response.headers.get(t)||""}getData(){return this.arrayBuffer}},ln=class extends uA{constructor(t,A){super(t),this.ipfsUrl=t,this.verifiedFetch=A}extractCID(t){let A=t.match(/(?:ipfs:\/\/|\/ipfs\/)([a-zA-Z0-9]+)/);return A?A[1]:null}async request({headers:t={}}={}){console.log(t);let A=6e4,i=new AbortController,n=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),i.abort()},A);try{let r={headers:t,signal:i.signal,session:!1},g=await this.verifiedFetch(this.ipfsUrl,r);if(!g.ok)throw new Error(`Failed to fetch from IPFS: ${g.status} ${g.statusText}`);let o=await g.arrayBuffer();return clearTimeout(n),new sn(g,o)}catch(r){throw clearTimeout(n),console.error("[IPFSClient] Error during request:",r),r instanceof Error&&(console.error("[IPFSClient] Error name:",r.name),console.error("[IPFSClient] Error message:",r.message),console.error("[IPFSClient] Error stack:",r.stack)),r&&typeof r=="object"&&"errors"in r&&console.error("[IPFSClient] AggregateError details:",r.errors),r}}};async function zg(e,t){let A=Yt.get(e);if(A)return A instanceof Promise?(console.log(`[fromIPFS] Waiting for in-flight GeoTIFF creation for ${e}`),await A):(console.log(`[fromIPFS] Using cached GeoTIFF client for ${e}`),A);console.log(`[fromIPFS] Creating new GeoTIFF client for ${e}`);let i=(async()=>{let n=new ln(e,t),r=await nn(n);return Yt.set(e,r),r})();Yt.set(e,i);try{return await i}catch(n){throw Yt.delete(e),n}}var Ia=class extends Ee{constructor(t=qg,A=Hg,i=Yg){super(t,A,i)}regionImpl(t,A){t&&(A=A.extract({left:t.x,top:t.y,width:t.w,height:t.h}))}sizeImpl(t,A){t&&(A=A.resize({...t,fit:"fill"}))}rotationImpl(t,A){t&&(t.isMirror&&(A=A.flop()),A=A.rotate(t.degree))}qualityFormatImpl(t,A,i,n,r){t&&(t==="color"?i=i.toColorspace("srgb"):t==="gray"||t==="grey"?i=i.grayscale():t==="bitonal"&&(i=i.threshold())),A&&(i=i.toFormat(A)),n==="png"&&(r.paletteBitDepth===1||r.space==="b-w")&&(i=i.toColorspace("b-w").png({colors:2}))}async generateTileRemote(t,A,i){let n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=n.pop(),c={width:A.width,height:A.height},f=super.normalizeRegionParams(s,c),h=super.normalizeSizeParams(a,{width:f?f.w:c.width,height:f?f.h:c.height}),{x:B,y:u,w:d,h:E}=f??{x:0,y:0,w:c.width,h:c.height},{width:x,height:w}=h;console.log(`Attempting to fetch from URL: ${i}`);let Q;if(typeof i=="string")console.log("Using standard HTTP fetch"),Q=await ca(i);else if(typeof I=="string"&&I.startsWith("bafy")){console.log("Detected CID id, using fromIPFS");let K=`ipfs://${I}`;Q=await zg(K,i)}else Q=await Kg(I,i);let C=await Q.getImage(0);console.log(`Source dimensions: ${C.getWidth()} x ${C.getHeight()}`),console.log(`Extracting region: x=${B}, y=${u}, w=${d}, h=${E}`),console.log(`Output size: ${x} x ${w}`);let y=await Q.getImageCount();console.log(`Total images (including overviews): ${y}`);let p=C.getSamplesPerPixel(),b;p>=3?(b=[0,1,2],p>=4&&b.push(3)):b=[0],console.log("Using automatic overview selection based on resolution...");let m=Math.max(d/x,E/w),k=C,S=1;for(let K=0;K<y;K++){let L=await Q.getImage(K),U=C.getWidth()/L.getWidth();U<=m&&U>S&&(S=U,k=L)}console.log(`Selected overview with scale: ${S.toFixed(2)}x`),console.log(`Overview dimensions: ${k.getWidth()} x ${k.getHeight()}`);let T=[Math.floor(B/S),Math.floor(u/S),Math.floor((B+d)/S),Math.floor((u+E)/S)],D;try{D=await k.readRasters({window:T,width:x,height:w,samples:b,interleave:!0,resampleMethod:"bilinear"})}catch(K){console.log(`Failed to read from overview: ${K.message}`);try{console.log("Attempting to read from main image...");let L=[B,u,B+d,u+E];D=await C.readRasters({window:L,width:x,height:w,samples:b,interleave:!0,resampleMethod:"bilinear"})}catch(L){console.log(`Failed to read from main image: ${L.message}`),console.log("Note: Range requests worked, but tile decoding failed. Falling back to full download.");let U=await i.get(I);return await this.generateTileLocal(t,A,U.content)}}let _=b.length,v=Buffer.from(D.buffer,D.byteOffset,D.byteLength),O={sequentialRead:!0,failOn:"none",raw:{width:x,height:w,channels:_}};(x>5e3||w>5e3)&&(O.limitInputPixels=!1);let F=ue(v,O),M=super.normalizeRotationParams(l);this.rotationImpl(M,F);let G=super.normalizeQualityParams(g),H=super.normalizeFormatParams(o,A.format);this.qualityFormatImpl(G,H,F,o,A);let J={};return J.body=F,J.contentType=super.getContentType(H),J}async generateTileLocal(t,A,i){let n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=super.normalizeRegionParams(s,A),c=super.normalizeSizeParams(a,{width:I?I.w:A.width,height:I?I.h:A.height}),f=super.normalizeRotationParams(l),h=super.normalizeQualityParams(g),B=super.normalizeFormatParams(o,A.format),{x:u,y:d,w:E,h:x}=I||{x:0,y:0,w:A.width,h:A.height},{width:w,height:Q}=c||{width:A.width,height:A.height},C=0,y;if(A.pages&&A.pages>1){let b=w/E,m=Q/x,k=Math.max(b,m);if(k>=.95)console.log("Pyramid optimization: using full resolution page (scale \u2248 1.0)"),C=0;else{C=A.pages-1;let T=Math.pow(2,A.pages-1),D=A.width/T,_=A.height/T;for(;C>0;){let v=E*(D/A.width),O=x*(_/A.height);if(v>=w*1.1&&O>=Q*1.1)break;C--,D*=2,_*=2}console.log(`Pyramid optimization: selected page ${C}/${A.pages-1} (scale: ${k.toFixed(2)}x, target: ${w}x${Q})`)}let S=A.is_hd||A.isHDImage?{limitInputPixels:!1,page:C,sequentialRead:!0,failOn:"none"}:{page:C,sequentialRead:!0,failOn:"none"};if(y=ue(i,S),I&&C>0){let T=await y.metadata(),D=T.width/A.width,_={x:Math.floor(u*D),y:Math.floor(d*D),w:Math.floor(E*D),h:Math.floor(x*D)};_.w=Math.min(_.w,T.width-_.x),_.h=Math.min(_.h,T.height-_.y),this.regionImpl(_,y)}else this.regionImpl(I,y)}else{let b=A.is_hd||A.isHDImage?{limitInputPixels:!1,sequentialRead:!0,failOn:"none"}:{sequentialRead:!0,failOn:"none"};y=ue(i,b),this.regionImpl(I,y)}this.sizeImpl(c,y),this.rotationImpl(f,y),this.qualityFormatImpl(h,B,y,o,A);let p={};return p.body=y,p.contentType=super.getContentType(B),p}generateImageInfo(t,A,i,n="2",r=512,g=512,o=""){let l=super.generateImageInfoTemp(t,A,i,n,r,g),a=l.info;if((i==="2.0"||i==="2.1")&&(a.profile=[super.uriPattern("compliance",i,n)],n==="2")){let s={};s.formats=["jpg","png","webp","jp2","pdf","tif"],s.qualities=["color","gray","bitonal","default","native","grey"],s.supports=Jg[Number(i)],a.profile.push(s)}return i==="3.0"&&o&&(a.extraFormats=[o],a.preferredFormats=[o]),o&&(a.formats=[o]),l.body=a,l}generateTilePipeline(t,A){let i=A.is_hd||A.isHDImage?ue({limitInputPixels:!1,sequentialRead:!0}):ue({sequentialRead:!0}),n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=!1,c=i,f={width:A.width,height:A.height};A&&A.orientation&&(I=!0,c=c.rotate(),A.orientation>=5&&(f={width:A.height,height:A.width}));let h=super.normalizeRegionParams(s,f);this.regionImpl(h,c);let B=super.normalizeSizeParams(a,{width:h?h.w:f.width,height:h?h.h:f.height});this.sizeImpl(B,c);let u=super.normalizeRotationParams(l);this.rotationImpl(u,c);let d=super.normalizeQualityParams(g),E=super.normalizeFormatParams(o,A.format);return this.qualityFormatImpl(d,E,c,o,A),h||B||u||d||E||I?c:(console.log("skip iiif transform"),null)}};export{Ia as SharpIiifShims};
|
|
8
|
+
`).filter(a=>a.length>0).map(a=>a.split("=")).forEach(([a,s])=>{this.ghostValues[a]=s})}return this.ghostValues}static async fromSource(t,A,i){let n=(await t.fetch([{offset:0,length:1024}],i))[0],r=new qe(n),g=r.getUint16(0,0),o;if(g===18761)o=!0;else if(g===19789)o=!1;else throw new TypeError("Invalid byte order value.");let l=r.getUint16(2,o),a;if(l===42)a=!1;else if(l===43){if(a=!0,r.getUint16(4,o)!==8)throw new Error("Unsupported offset byte-size.")}else throw new TypeError("Invalid magic number.");let s=a?r.getUint64(8,o):r.getUint32(4,o);return new e(t,o,a,s,A)}close(){return typeof this.source.close=="function"?this.source.close():!1}};async function ca(e,t={},A){return Ht.fromSource(fa(e,t),A)}async function nn(e,t={},A){return Ht.fromSource(ga(e,t),A)}var qg=1e8,Hg=1e4,Yg=1e4,Jg={2:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByWhListed","sizeByForcedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"],2.1:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByConfinedWh","sizeByDistortedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeByWhListed","sizeByForcedWh"],3:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeUpscaling"]},rn=class extends ${async decode(t,A){let i=Array.isArray(t.BitsPerSample)?t.BitsPerSample.length:t.SamplesPerPixel||4,n=ue(A,{sequentialRead:!0}),g=(await n.metadata()).channels||4;i===4&&g<4&&n.ensureAlpha?n=n.ensureAlpha():i===3&&g>3&&n.removeAlpha&&(n=n.removeAlpha());let{data:o,info:l}=await n.raw().toBuffer({resolveWithObject:!0});if(l.channels!==i){let a=l.width*l.height,s=Buffer.alloc(a*i),I=o;for(let c=0;c<a;c+=1){let f=c*l.channels,h=c*i;for(let B=0;B<i;B+=1)B<l.channels?s[h+B]=I[f+B]:s[h+B]=B===3?255:0}return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}return o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)}};CA(50001,()=>Promise.resolve(rn));var on=class extends BA{constructor(t){super(),this.result=t}get ok(){return this.result.res.status>=200&&this.result.res.status<300}get status(){return this.result.res.status}getHeader(t){return this.result.res.headers[t.toLowerCase()]}getData(){return Buffer.isBuffer(this.result.content)?this.result.content.buffer.slice(this.result.content.byteOffset,this.result.content.byteOffset+this.result.content.byteLength):this.result.content}},an=class extends uA{constructor(t,A){super(t),this.objectKey=t,this.ossClient=A}async request({headers:t={}}={}){let A={timeout:3e4};if(t&&t.Range){let n=t.Range.match(/bytes=(\d+)-(\d+)/);if(n){let r=parseInt(n[1],10),g=parseInt(n[2],10);A.range=`${r}-${g}`,A.headers={Range:`bytes=${r}-${g}`,"x-oss-range-behavior":"standard"}}}A.headers||(A.headers={});for(let[n,r]of Object.entries(t))n!=="Range"&&(A.headers[n.toLowerCase()]=r);let i=await this.ossClient.get(this.objectKey,A);return new on(i)}};async function Kg(e,t){let A=new an(e,t);return nn(A)}var Yt=new Map,sn=class extends BA{constructor(t,A){super(),this.response=t,this.arrayBuffer=A}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(t){return this.response.headers.get(t)||""}getData(){return this.arrayBuffer}},ln=class extends uA{constructor(t,A){super(t),this.ipfsUrl=t,this.verifiedFetch=A}extractCID(t){let A=t.match(/(?:ipfs:\/\/|\/ipfs\/)([a-zA-Z0-9]+)/);return A?A[1]:null}async request({headers:t={}}={}){console.log(t);let A=6e4,i=new AbortController,n=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),i.abort()},A);try{let r={headers:t,signal:i.signal,session:!1},g=await this.verifiedFetch(this.ipfsUrl,r);if(!g.ok)throw new Error(`Failed to fetch from IPFS: ${g.status} ${g.statusText}`);let o=await g.arrayBuffer();return clearTimeout(n),new sn(g,o)}catch(r){throw clearTimeout(n),console.error("[IPFSClient] Error during request:",r),r instanceof Error&&(console.error("[IPFSClient] Error name:",r.name),console.error("[IPFSClient] Error message:",r.message),console.error("[IPFSClient] Error stack:",r.stack)),r&&typeof r=="object"&&"errors"in r&&console.error("[IPFSClient] AggregateError details:",r.errors),r}}};async function zg(e,t){let A=Yt.get(e);if(A)return A instanceof Promise?(console.log(`[fromIPFS] Waiting for in-flight GeoTIFF creation for ${e}`),await A):(console.log(`[fromIPFS] Using cached GeoTIFF client for ${e}`),A);console.log(`[fromIPFS] Creating new GeoTIFF client for ${e}`);let i=(async()=>{let n=new ln(e,t),r=await nn(n);return Yt.set(e,r),r})();Yt.set(e,i);try{return await i}catch(n){throw Yt.delete(e),n}}var Ia=class extends Ee{constructor(t=qg,A=Hg,i=Yg){super(t,A,i)}regionImpl(t,A){t&&(A=A.extract({left:t.x,top:t.y,width:t.w,height:t.h}))}sizeImpl(t,A){t&&(A=A.resize({...t,fit:"fill"}))}rotationImpl(t,A){t&&(t.isMirror&&(A=A.flop()),A=A.rotate(t.degree))}qualityFormatImpl(t,A,i,n,r){t&&(t==="color"?i=i.toColorspace("srgb"):t==="gray"||t==="grey"?i=i.grayscale():t==="bitonal"&&(i=i.threshold())),A&&(i=i.toFormat(n)),n==="png"&&(r.paletteBitDepth===1||r.space==="b-w")&&(i=i.toColorspace("b-w").png({colors:2}))}async generateTileRemote(t,A,i){let n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=n.pop(),c={width:A.width,height:A.height},f=super.normalizeRegionParams(s,c),h=super.normalizeSizeParams(a,{width:f?f.w:c.width,height:f?f.h:c.height}),{x:B,y:u,w:d,h:E}=f??{x:0,y:0,w:c.width,h:c.height},{width:x,height:w}=h;console.log(`Attempting to fetch from URL: ${i}`);let Q;if(typeof i=="string")console.log("Using standard HTTP fetch"),Q=await ca(i);else if(typeof I=="string"&&I.startsWith("bafy")){console.log("Detected CID id, using fromIPFS");let K=`ipfs://${I}`;Q=await zg(K,i)}else Q=await Kg(I,i);let C=await Q.getImage(0);console.log(`Source dimensions: ${C.getWidth()} x ${C.getHeight()}`),console.log(`Extracting region: x=${B}, y=${u}, w=${d}, h=${E}`),console.log(`Output size: ${x} x ${w}`);let y=await Q.getImageCount();console.log(`Total images (including overviews): ${y}`);let p=C.getSamplesPerPixel(),b;p>=3?(b=[0,1,2],p>=4&&b.push(3)):b=[0],console.log("Using automatic overview selection based on resolution...");let m=Math.max(d/x,E/w),k=C,S=1;for(let K=0;K<y;K++){let L=await Q.getImage(K),U=C.getWidth()/L.getWidth();U<=m&&U>S&&(S=U,k=L)}console.log(`Selected overview with scale: ${S.toFixed(2)}x`),console.log(`Overview dimensions: ${k.getWidth()} x ${k.getHeight()}`);let T=[Math.floor(B/S),Math.floor(u/S),Math.floor((B+d)/S),Math.floor((u+E)/S)],D;try{D=await k.readRasters({window:T,width:x,height:w,samples:b,interleave:!0,resampleMethod:"bilinear"})}catch(K){console.log(`Failed to read from overview: ${K.message}`);try{console.log("Attempting to read from main image...");let L=[B,u,B+d,u+E];D=await C.readRasters({window:L,width:x,height:w,samples:b,interleave:!0,resampleMethod:"bilinear"})}catch(L){console.log(`Failed to read from main image: ${L.message}`),console.log("Note: Range requests worked, but tile decoding failed. Falling back to full download.");let U=await i.get(I);return await this.generateTileLocal(t,A,U.content)}}let _=b.length,v=Buffer.from(D.buffer,D.byteOffset,D.byteLength),O={sequentialRead:!0,failOn:"none",raw:{width:x,height:w,channels:_}};(x>5e3||w>5e3)&&(O.limitInputPixels=!1);let F=ue(v,O),M=super.normalizeRotationParams(l);this.rotationImpl(M,F);let G=super.normalizeQualityParams(g),H=super.normalizeFormatParams(o,A.format);this.qualityFormatImpl(G,H,F,o,A);let J={};return J.body=F,J.contentType=super.getContentType(o),J}async generateTileLocal(t,A,i){let n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=super.normalizeRegionParams(s,A),c=super.normalizeSizeParams(a,{width:I?I.w:A.width,height:I?I.h:A.height}),f=super.normalizeRotationParams(l),h=super.normalizeQualityParams(g),B=super.normalizeFormatParams(o,A.format),{x:u,y:d,w:E,h:x}=I||{x:0,y:0,w:A.width,h:A.height},{width:w,height:Q}=c||{width:A.width,height:A.height},C=0,y;if(A.pages&&A.pages>1){let b=w/E,m=Q/x,k=Math.max(b,m);if(k>=.95)console.log("Pyramid optimization: using full resolution page (scale \u2248 1.0)"),C=0;else{C=A.pages-1;let T=Math.pow(2,A.pages-1),D=A.width/T,_=A.height/T;for(;C>0;){let v=E*(D/A.width),O=x*(_/A.height);if(v>=w*1.1&&O>=Q*1.1)break;C--,D*=2,_*=2}console.log(`Pyramid optimization: selected page ${C}/${A.pages-1} (scale: ${k.toFixed(2)}x, target: ${w}x${Q})`)}let S=A.is_hd||A.isHDImage?{limitInputPixels:!1,page:C,sequentialRead:!0,failOn:"none"}:{page:C,sequentialRead:!0,failOn:"none"};if(y=ue(i,S),I&&C>0){let T=await y.metadata(),D=T.width/A.width,_={x:Math.floor(u*D),y:Math.floor(d*D),w:Math.floor(E*D),h:Math.floor(x*D)};_.w=Math.min(_.w,T.width-_.x),_.h=Math.min(_.h,T.height-_.y),this.regionImpl(_,y)}else this.regionImpl(I,y)}else{let b=A.is_hd||A.isHDImage?{limitInputPixels:!1,sequentialRead:!0,failOn:"none"}:{sequentialRead:!0,failOn:"none"};y=ue(i,b),this.regionImpl(I,y)}this.sizeImpl(c,y),this.rotationImpl(f,y),this.qualityFormatImpl(h,B,y,o,A);let p={};return p.body=y,p.contentType=super.getContentType(o),p}generateImageInfo(t,A,i,n="2",r=512,g=512,o=""){let l=super.generateImageInfoTemp(t,A,i,n,r,g),a=l.info;if((i==="2.0"||i==="2.1")&&(a.profile=[super.uriPattern("compliance",i,n)],n==="2")){let s={};s.formats=["jpg","png","webp","jp2","pdf","tif"],s.qualities=["color","gray","bitonal","default","native","grey"],s.supports=Jg[Number(i)],a.profile.push(s)}return i==="3.0"&&o&&(a.extraFormats=[o],a.preferredFormats=[o]),o&&(a.formats=[o]),l.body=a,l}generateTilePipeline(t,A){let i=A.is_hd||A.isHDImage?ue({limitInputPixels:!1,sequentialRead:!0}):ue({sequentialRead:!0}),n=t.split("/"),r=n.pop(),g=r.split(".")[0],o=r.split(".")[1],l=n.pop(),a=n.pop(),s=n.pop(),I=!1,c=i,f={width:A.width,height:A.height};A&&A.orientation&&(I=!0,c=c.rotate(),A.orientation>=5&&(f={width:A.height,height:A.width}));let h=super.normalizeRegionParams(s,f);this.regionImpl(h,c);let B=super.normalizeSizeParams(a,{width:h?h.w:f.width,height:h?h.h:f.height});this.sizeImpl(B,c);let u=super.normalizeRotationParams(l);this.rotationImpl(u,c);let d=super.normalizeQualityParams(g),E=super.normalizeFormatParams(o,A.format);return this.qualityFormatImpl(d,E,c,o,A),h||B||u||d||E||I?c:(console.log("skip iiif transform"),null)}};export{Ia as SharpIiifShims};
|
|
9
9
|
/*! Bundled license information:
|
|
10
10
|
|
|
11
11
|
pako/dist/pako.esm.mjs:
|