@etu-wiki/sharp-iiif-shims 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var we=Object.create;var ae=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,be=Object.prototype.hasOwnProperty;var xe=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var $e=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ze(e))!be.call(s,r)&&r!==t&&ae(s,r,{get:()=>e[r],enumerable:!(i=ye(e,r))||i.enumerable});return s};var Pe=(s,e,t)=>(t=s!=null?we(ve(s)):{},$e(e||!s||!s.__esModule?ae(t,"default",{value:s,enumerable:!0}):t,s));var ce=xe((Ne,K)=>{"use strict";var J=Object.defineProperty,Ie=Object.getOwnPropertyDescriptor,Be=Object.getOwnPropertyNames,He=Object.prototype.hasOwnProperty,Me=(s,e)=>{for(var t in e)J(s,t,{get:e[t],enumerable:!0})},We=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Be(e))!He.call(s,r)&&r!==t&&J(s,r,{get:()=>e[r],enumerable:!(i=Ie(e,r))||i.enumerable});return s},Se=s=>We(J({},"__esModule",{value:!0}),s),le={};Me(le,{default:()=>he});K.exports=Se(le);var n="[1-9][0-9]*",ne="[0-9]*",j="(?=.*[1-9])\\d+(\\.\\d+)?",G="\\d+(\\.\\d+)?",Y=(s=>(s.jpg="image/jpeg",s.jpeg="image/jpeg",s.png="image/png",s.webp="image/webp",s.tif="image/tiff",s.tiff="image/tiff",s.gif="image/gif",s.jp2="image/jp2",s.pdf="application/pdf",s))(Y||{}),O={version:["1.0","1.1","2.0","2.1","3.0"],level:["0","1","2"],region:["full","square",`${ne},${ne},${n},${n}`,`pct:${G},${G},${j},${j}`],rotation:`!?${G}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:[""]},je={1:["full",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],1.1:["full",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],2:["full",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],2.1:["full","max",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],3:["max",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`,"\\^max",`\\^${n},`,`\\^,${n}`,`\\^pct:${j}`,`\\^${n},${n}`,`\\^!${n},${n}`]},X=/^pct:([\d,]+)/,he=class{constructor(s,e,t,i,r,o,a){this.version=s,this.level=e,this.maxArea=t,this.maxWidth=i,this.maxHeight=r,this.tileWidth=o,this.tileHeight=a,this.validate("version",s),this.validate("level",e),O.size=je[Number(s)]}validator(s){var e=O[s];return e instanceof Array&&(e=e.join("|")),new RegExp("^("+e+")$")}validate(s,e){if(!this.validator(s).test(e))throw Error(`invalid IIIF url ${s}: ${e}`);return!0}normalizeRegionParams(s,e){if(this.validate("region",s),s==="full")return null;if(s==="square")return this._regionSquare(e);if(X.test(s))return this._regionPct(s.match(X)[1],e);{let t=s.split(",").map(i=>Number(i));return this._regionXYWH(t,e)}}_regionSquare(s){let e,t,i=s.width,r=s.height;if(i!==r){let o=Math.min(i,r),a=Math.abs(Math.floor((i-r)/2));return i>r?(e=a,t=0):(e=0,t=a),this._regionXYWH([e,t,o,o],s)}return null}_regionPct(s,e){let t=s.split(",").map((i,r)=>{let o=Number(i)/100;return r===0||r===2?Math.ceil(e.width*o):r===1||r===3?Math.ceil(e.height*o):null});return this._regionXYWH(t,e)}_regionXYWH(s,e){let t=e.width,i=e.height,[r,o,a,h]=s;return r+a>t&&(a=t-r),o+h>i&&(h=i-o),{x:r,y:o,w:a,h}}normalizeSizeParams(s,e){let t=s,i=e.width,r=e.height;if(!e||!i&&!r)throw Error(`invalid region dimensions: ${JSON.stringify(e,null,2)}`);this.validate("size",t);let o=!1;t.charAt(0)==="^"&&(o=!0,t=t.substring(1));let a=null;if(t==="full"||(t==="max"?a=this._sizeMaxScale(e):X.test(t)?a=this._sizePctScale(t.match(X)[1]):t.charAt(0)==="!"&&(t=t.substring(1),a=this._sizeBangScale(t,o,e)),a===1))return null;if(a){let h=Math.ceil(i*a),c=Math.ceil(r*a);return this._sizeWH(`${h},${c}`,o,e)}else return this._sizeWH(t,o,e)}_sizeBangScale(s,e,t){let i=t.width,r=t.height,[o,a]=s.split(",").map(c=>c===""?null:Number(c)),h=Math.min(o/i,a/r);if(o>i&&a>r&&!e)throw Error("should not upscale without ^");return h}_sizeMaxScale(s){let e=s.width,t=s.height,i=1;return this.maxArea&&this.maxArea<e*t&&(i=Math.sqrt(this.maxArea/(e*t))),this.maxWidth&&this.maxWidth<e&&(i=Math.min(i,this.maxWidth/e)),this.maxHeight&&this.maxHeight<t&&(i=Math.min(i,this.maxHeight/t)),i}_sizePctScale(s){return Number(s)/100}_sizeWH(s,e,t){let i=t.width,r=t.height,[o,a]=s.split(",").map(h=>h===""?null:Number(h));if(o?a||(a=Math.ceil(r*o/i),a=a===0?1:a):(o=Math.ceil(i*a/r),o=o===0?1:o),(o>i||a>r)&&!e)throw Error("should not upscale without ^");return{width:o,height:a}}normalizeRotationParams(s){this.validate("rotation",s);let e=!1;if(s==="0")return null;s[0]==="!"&&(e=!0);let t=Number(s.replace(/^!/,""));return{isMirror:e,degree:t}}normalizeQualityParams(s){return this.validate("quality",s),s==="native"||s==="default"?null:s}normalizeFormatParams(s,e){if((this.version==="1.0"||this.version==="1.1"||this.version==="2.0"||this.version==="2.1")&&!s)return"png";this.validate("format",s);let t=Y[s],i=Y[e];return t===i?null:s}getContentType(s){return Y[s]}generateImageInfoTemp(s,e){let t={},i={};t.info=i;let r=this.version;return r==="1.0"?(i.identifier=s,i.width=e.width,i.height=e.height,i.scale_factors=this.factors(e),i.tile_width=this.tileWidth,i.tile_height=this.tileHeight,i.formats=O.format,i.qualities=O.quality,i.profile=this.uriPattern("compliance"),t.contentType="application/json",t.body=JSON.stringify(i)):(r==="1.1"?(i["@context"]=this.uriPattern("context"),i["@id"]=s,i.width=e.width,i.height=e.height,i.scale_factors=this.factors(e),i.tile_width=this.tileWidth,i.tile_height=this.tileHeight,i.formats=O.format,i.qualities=O.quality,i.profile=this.uriPattern("compliance")):r==="2.0"||r==="2.1"?(i["@context"]=this.uriPattern("context"),i["@id"]=s,i.protocol="http://iiif.io/api/image",i.width=e.width,i.height=e.height,this.level==="0"?i.sizes=this.sizes(e):i.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],i.profile=[this.uriPattern("compliance")]):r==="3.0"&&(i["@context"]=[this.uriPattern("context")],i.id=s,i.type="ImageService3",i.protocol="http://iiif.io/api/image",i.width=e.width,i.height=e.height,this.level==="0"?i.sizes=this.sizes(e):i.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],i.profile=this.uriPattern("compliance")),t.contentType="application/ld+json"),t}factors(s){let e=1,t=[];for(;this.tileWidth*e<=s.width||this.tileHeight*e<=s.height;)t.push(e),e*=2;return t.length===0&&t.push(1),t}uriPattern(s){let e="",t="";return this.version==="1.0"?e=`http://library.stanford.edu/iiif/image-api/compliance.html#level${this.level}`:this.version==="1.1"?(e=`http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level${this.level}`,t="http://library.stanford.edu/iiif/image-api/1.1/context.json"):this.version==="2.0"||this.version==="2.1"?(e=`http://iiif.io/api/image/2/level${this.level}.json`,t="http://iiif.io/api/image/2/context.json"):this.version==="3.0"&&(e=`level${this.level}`,t="http://iiif.io/api/image/3/context.json"),s==="compliance"?e:s==="context"?t:""}sizes(s){return[{width:s.width,height:s.height}]}};K.exports=he});var fe=Pe(ce(),1);import v from"sharp";import{addDecoder as Fe,BaseDecoder as Re,fromCustomClient as pe,fromUrl as qe,BaseClient as me,BaseResponse as de}from"geotiff";import{createVerifiedFetch as _e}from"@helia/verified-fetch";var Te=1e8,ge=1e4,ue=1e4,Ae=512,Ce=512,Q=null,V=null;async function Oe(){if(!Q){let s=await _e();Q=s.fetch||s,V=s.helia}return Q}async function Ve(){V&&(await V.stop(),V=null,Q=null)}var Ee={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"]},Z=class extends Re{async decode(e,t){let i=Array.isArray(e.BitsPerSample)?e.BitsPerSample.length:e.SamplesPerPixel||4,r=v(t,{sequentialRead:!0}),a=(await r.metadata()).channels||4;i===4&&a<4&&r.ensureAlpha?r=r.ensureAlpha():i===3&&a>3&&r.removeAlpha&&(r=r.removeAlpha());let{data:h,info:c}=await r.raw().toBuffer({resolveWithObject:!0});if(c.channels!==i){let w=c.width*c.height,z=Buffer.alloc(w*i),M=h;for(let l=0;l<w;l+=1){let u=l*c.channels,p=l*i;for(let g=0;g<i;g+=1)g<c.channels?z[p+g]=M[u+g]:z[p+g]=g===3?255:0}return z.buffer.slice(z.byteOffset,z.byteOffset+z.byteLength)}return h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength)}};Fe(50001,()=>Promise.resolve(Z));var ee=class extends de{constructor(e){super(),this.result=e}get ok(){return this.result.res.status>=200&&this.result.res.status<300}get status(){return this.result.res.status}getHeader(e){return this.result.res.headers[e.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}},te=class extends me{constructor(e,t){super(e),this.objectKey=e,this.ossClient=t}async request({headers:e={}}={}){let t=await this.ossClient.get(this.objectKey,{headers:e,timeout:3e4});return new ee(t)}};async function Le(s,e){let t=new te(s,e);return pe(t)}var ie=class extends de{constructor(e,t){super(),this.response=e,this.arrayBuffer=t}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(e){return this.response.headers.get(e)||""}getData(){return this.arrayBuffer}},se=class extends me{constructor(e){super(e),this.ipfsUrl=e}async request({headers:e={}}={}){let t=new AbortController,i=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),t.abort()},3e4);try{let o=await(await Oe())(this.ipfsUrl,{headers:e,signal:t.signal,session:!1});if(!o.ok)throw new Error(`Failed to fetch from IPFS: ${o.status} ${o.statusText}`);let a=await o.arrayBuffer();return clearTimeout(i),new ie(o,a)}catch(r){throw clearTimeout(i),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 ke(s){let e=new se(s);return await pe(e)}var re=class extends fe.default{constructor(e,t,i=!1,r=Te,o=ge,a=ue,h=Ae,c=Ce){super(e,t,r,o,a,h,c),this.enableHD=i}regionImpl(e,t){e&&(t=t.extract({left:e.x,top:e.y,width:e.w,height:e.h}))}sizeImpl(e,t){e&&(t=t.resize({...e,fit:"fill"}))}rotationImpl(e,t){e&&(e.isMirror&&(t=t.flop()),t=t.rotate(e.degree))}qualityFormatImpl(e,t,i,r,o){e&&(e==="color"?i=i.toColorspace("srgb"):e==="gray"||e==="grey"?i=i.grayscale():e==="bitonal"&&(i=i.threshold())),t&&(i=i.toFormat(t)),r==="png"&&(o.paletteBitDepth===1||o.space==="b-w")&&(i=i.toColorspace("b-w").png({colors:2}))}async generateImageTile(e,t,i){let r=e.split("/"),o=r.pop(),a=o.split(".")[0],h=o.split(".")[1],c=r.pop(),w=r.pop(),z=r.pop(),M=r.pop(),l={width:t.width,height:t.height},u=super.normalizeRegionParams(z,l),p=super.normalizeSizeParams(w,{width:u?u.w:l.width,height:u?u.h:l.height}),{x:g,y:f,w:y,h:B}=u??{x:0,y:0,w:l.width,h:l.height},{width:F,height:H}=p;console.log(`Attempting to fetch from URL: ${i}`);let x;typeof i=="string"?i.startsWith("ipfs://")?(console.log("Detected IPFS protocol URL, using verified-fetch"),x=await ke(i)):(console.log("Using standard HTTP fetch"),x=await qe(i)):x=await Le(M,i);let $=await x.getImage();console.log(`Source dimensions: ${$.getWidth()} x ${$.getHeight()}`),console.log(`Extracting region: x=${g}, y=${f}, w=${y}, h=${B}`),console.log(`Output size: ${F} x ${H}`);let _=await x.getImageCount();console.log(`Total images (including overviews): ${_}`);let k=$.getSamplesPerPixel(),W;k>=3?(W=[0,1,2],k>=4&&W.push(3)):W=[0],console.log("Using automatic overview selection based on resolution...");let D=Math.max(y/F,B/H),d=$,b=1;for(let I=0;I<_;I++){let R=await x.getImage(I),S=$.getWidth()/R.getWidth();S<=D&&S>b&&(b=S,d=R)}console.log(`Selected overview with scale: ${b.toFixed(2)}x`),console.log(`Overview dimensions: ${d.getWidth()} x ${d.getHeight()}`);let E=[Math.floor(g/b),Math.floor(f/b),Math.floor((g+y)/b),Math.floor((f+B)/b)],P;try{P=await d.readRasters({window:E,width:F,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}catch(I){console.log(`Failed to read from overview, falling back to main image: ${I}`);let R=[g,f,g+y,f+B];P=await $.readRasters({window:R,width:F,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}let T=W.length,N=Buffer.from(P.buffer,P.byteOffset,P.byteLength),A=v(N,{raw:{width:F,height:H,channels:T}}),m=super.normalizeRotationParams(c);this.rotationImpl(m,A);let U=super.normalizeQualityParams(a),L=super.normalizeFormatParams(h,t.format);this.qualityFormatImpl(U,L,A,h,t);let C={};return C.body=A,C.contentType=super.getContentType(L),C}iiifTransform(e,t){let i=this.enableHD?v({limitInputPixels:!1,sequentialRead:!0}):v(),r=e.split("/"),o=r.pop(),a=o.split(".")[0],h=o.split(".")[1],c=r.pop(),w=r.pop(),z=r.pop(),M=!1,l=i,u={width:t.width,height:t.height};t&&t.orientation&&(M=!0,l=l.rotate(),t.orientation>=5&&(u={width:t.height,height:t.width}));let p=super.normalizeRegionParams(z,u);this.regionImpl(p,l);let g=super.normalizeSizeParams(w,{width:p?p.w:u.width,height:p?p.h:u.height});this.sizeImpl(g,l);let f=super.normalizeRotationParams(c);this.rotationImpl(f,l);let y=super.normalizeQualityParams(a),B=super.normalizeFormatParams(h,t.format);return this.qualityFormatImpl(y,B,l,h,t),p||g||f||y||B||M?l:(console.log("skip iiif transform"),null)}async generateIiifImage(e,t,i=256){let r=this.enableHD?v(t,{limitInputPixels:!1,sequentialRead:!0}):v(t),o=e.split("/"),a=o.pop(),h=a.split(".")[0],c=a.split(".")[1],w=o.pop(),z=o.pop(),M=o.pop(),l=await r.metadata(),u={width:l.width,height:l.height},p={},g=r,f=super.normalizeRegionParams(M,u);this.regionImpl(f,g);let y=super.normalizeSizeParams(z,{width:f?f.w:u.width,height:f?f.h:u.height});this.sizeImpl(y,g);let{x:B,y:F,w:H,h:x}=f||{x:0,y:0,w:u.width,h:u.height},{width:$,height:_}=y||{width:u.width,height:u.height};try{if(H*x>$*_*i&&$<ge&&_<ue&&l.pages&&l.pages>1){console.log("thumbnail");let d=Math.max($/H,_/x),[b,E,P,T]=[Math.round(B*d),Math.round(F*d),Math.round(H*d),Math.round(x*d)],[N,A]=[Math.round(u.width*d),Math.round(u.height*d)];console.log("rawMeta.pages: "+l.pages);let m=Math.max(0,l.pages-1);console.log("selectedPage1: "+m),m>=l.pages&&(console.log("Warning: Selected page exceeds available pages, using last available page"),m=Math.max(0,l.pages-1));let U=this.enableHD?await v(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).metadata():await v(t,{page:m}).metadata(),L=U.width,C=U.height;for(;m>0&&(C<A||L<N);)C*=2,L*=2,m--;(m<0||m>=l.pages)&&(console.log("Warning: Invalid page index after calculation, using page 0"),m=0),console.log("selectedPage2: "+m);let I={width:N,height:A,fastShrinkOnLoad:!1},R=this.enableHD?await v(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).resize(I).toBuffer():await v(t,{page:m}).resize(I).toBuffer(),S=this.enableHD?v(R,{limitInputPixels:!1,sequentialRead:!0}):v(R),q=await S.metadata();console.log(q),E+T>q.height&&(T=q.height-E,console.log("adjested sh: "+T)),b+P>q.width&&(P=q.width-b,console.log("adjusted sw: "+P));let oe={x:b,y:E,w:P,h:T};this.regionImpl(oe,S),this.sizeImpl(y,S),console.log(q.width,q.height,I.width,I.height,oe,y),g=S}}catch(d){console.trace(d),console.log(d)}let k=super.normalizeRotationParams(w);this.rotationImpl(k,g);let W=super.normalizeQualityParams(h);console.log(c,l.format);let D=super.normalizeFormatParams(c,l.format);return this.qualityFormatImpl(W,D,g,c,l),console.log("pipeline "+g),p.body=g,p.contentType=super.getContentType(D),p}generateImageInfo(e,t,i=""){let r=this.version,o=this.level,a={width:t.width,height:t.height};t&&t.orientation&&t.orientation>=5&&(console.log(t.orientation),a={width:t.height,height:t.width});let h=super.generateImageInfoTemp(e,a),c=h.info;if((r==="2.0"||r==="2.1")&&(c.profile=[super.uriPattern("compliance")],o==="2")){let w={};w.formats=["jpg","png","webp","jp2","pdf","tif"],w.qualities=["color","gray","bitonal","default","native","grey"],w.supports=Ee[Number(r)],c.profile.push(w)}return r==="3.0"&&i&&(c.extraFormats=[i],c.preferredFormats=[i]),i&&(c.formats=[i]),h}};export{Ve as closeVerifiedFetch,re as default};
|
|
1
|
+
var ge=Object.create;var ee=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty;var de=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var we=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fe(e))!me.call(r,s)&&s!==t&&ee(r,s,{get:()=>e[s],enumerable:!(i=ue(e,s))||i.enumerable});return r};var ye=(r,e,t)=>(t=r!=null?ge(pe(r)):{},we(e||!r||!r.__esModule?ee(t,"default",{value:r,enumerable:!0}):t,r));var se=de((Ce,X)=>{"use strict";var U=Object.defineProperty,ze=Object.getOwnPropertyDescriptor,$e=Object.getOwnPropertyNames,ve=Object.prototype.hasOwnProperty,Pe=(r,e)=>{for(var t in e)U(r,t,{get:e[t],enumerable:!0})},be=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $e(e))!ve.call(r,s)&&s!==t&&U(r,s,{get:()=>e[s],enumerable:!(i=ze(e,s))||i.enumerable});return r},xe=r=>be(U({},"__esModule",{value:!0}),r),ie={};Pe(ie,{default:()=>re});X.exports=xe(ie);var a="[1-9][0-9]*",te="[0-9]*",j="(?=.*[1-9])\\d+(\\.\\d+)?",N="\\d+(\\.\\d+)?",E=(r=>(r.jpg="image/jpeg",r.jpeg="image/jpeg",r.png="image/png",r.webp="image/webp",r.tif="image/tiff",r.tiff="image/tiff",r.gif="image/gif",r.jp2="image/jp2",r.pdf="application/pdf",r))(E||{}),F={version:["1.0","1.1","2.0","2.1","3.0"],level:["0","1","2"],region:["full","square",`${te},${te},${a},${a}`,`pct:${N},${N},${j},${j}`],rotation:`!?${N}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:[""]},Ie={1:["full",`${a},`,`,${a}`,`pct:${j}`,`${a},${a}`,`!${a},${a}`],1.1:["full",`${a},`,`,${a}`,`pct:${j}`,`${a},${a}`,`!${a},${a}`],2:["full",`${a},`,`,${a}`,`pct:${j}`,`${a},${a}`,`!${a},${a}`],2.1:["full","max",`${a},`,`,${a}`,`pct:${j}`,`${a},${a}`,`!${a},${a}`],3:["max",`${a},`,`,${a}`,`pct:${j}`,`${a},${a}`,`!${a},${a}`,"\\^max",`\\^${a},`,`\\^,${a}`,`\\^pct:${j}`,`\\^${a},${a}`,`\\^!${a},${a}`]},O=/^pct:([\d,]+)/,re=class{constructor(r,e,t,i,s,o,n){this.version=r,this.level=e,this.maxArea=t,this.maxWidth=i,this.maxHeight=s,this.tileWidth=o,this.tileHeight=n,this.validate("version",r),this.validate("level",e),F.size=Ie[Number(r)]}validator(r){var e=F[r];return e instanceof Array&&(e=e.join("|")),new RegExp("^("+e+")$")}validate(r,e){if(!this.validator(r).test(e))throw Error(`invalid IIIF url ${r}: ${e}`);return!0}normalizeRegionParams(r,e){if(this.validate("region",r),r==="full")return null;if(r==="square")return this._regionSquare(e);if(O.test(r))return this._regionPct(r.match(O)[1],e);{let t=r.split(",").map(i=>Number(i));return this._regionXYWH(t,e)}}_regionSquare(r){let e,t,i=r.width,s=r.height;if(i!==s){let o=Math.min(i,s),n=Math.abs(Math.floor((i-s)/2));return i>s?(e=n,t=0):(e=0,t=n),this._regionXYWH([e,t,o,o],r)}return null}_regionPct(r,e){let t=r.split(",").map((i,s)=>{let o=Number(i)/100;return s===0||s===2?Math.ceil(e.width*o):s===1||s===3?Math.ceil(e.height*o):null});return this._regionXYWH(t,e)}_regionXYWH(r,e){let t=e.width,i=e.height,[s,o,n,l]=r;return s+n>t&&(n=t-s),o+l>i&&(l=i-o),{x:s,y:o,w:n,h:l}}normalizeSizeParams(r,e){let t=r,i=e.width,s=e.height;if(!e||!i&&!s)throw Error(`invalid region dimensions: ${JSON.stringify(e,null,2)}`);this.validate("size",t);let o=!1;t.charAt(0)==="^"&&(o=!0,t=t.substring(1));let n=null;if(t==="full"||(t==="max"?n=this._sizeMaxScale(e):O.test(t)?n=this._sizePctScale(t.match(O)[1]):t.charAt(0)==="!"&&(t=t.substring(1),n=this._sizeBangScale(t,o,e)),n===1))return null;if(n){let l=Math.ceil(i*n),h=Math.ceil(s*n);return this._sizeWH(`${l},${h}`,o,e)}else return this._sizeWH(t,o,e)}_sizeBangScale(r,e,t){let i=t.width,s=t.height,[o,n]=r.split(",").map(h=>h===""?null:Number(h)),l=Math.min(o/i,n/s);if(o>i&&n>s&&!e)throw Error("should not upscale without ^");return l}_sizeMaxScale(r){let e=r.width,t=r.height,i=1;return this.maxArea&&this.maxArea<e*t&&(i=Math.sqrt(this.maxArea/(e*t))),this.maxWidth&&this.maxWidth<e&&(i=Math.min(i,this.maxWidth/e)),this.maxHeight&&this.maxHeight<t&&(i=Math.min(i,this.maxHeight/t)),i}_sizePctScale(r){return Number(r)/100}_sizeWH(r,e,t){let i=t.width,s=t.height,[o,n]=r.split(",").map(l=>l===""?null:Number(l));if(o?n||(n=Math.ceil(s*o/i),n=n===0?1:n):(o=Math.ceil(i*n/s),o=o===0?1:o),(o>i||n>s)&&!e)throw Error("should not upscale without ^");return{width:o,height:n}}normalizeRotationParams(r){this.validate("rotation",r);let e=!1;if(r==="0")return null;r[0]==="!"&&(e=!0);let t=Number(r.replace(/^!/,""));return{isMirror:e,degree:t}}normalizeQualityParams(r){return this.validate("quality",r),r==="native"||r==="default"?null:r}normalizeFormatParams(r,e){if((this.version==="1.0"||this.version==="1.1"||this.version==="2.0"||this.version==="2.1")&&!r)return"png";this.validate("format",r);let t=E[r],i=E[e];return t===i?null:r}getContentType(r){return E[r]}generateImageInfoTemp(r,e){let t={},i={};t.info=i;let s=this.version;return s==="1.0"?(i.identifier=r,i.width=e.width,i.height=e.height,i.scale_factors=this.factors(e),i.tile_width=this.tileWidth,i.tile_height=this.tileHeight,i.formats=F.format,i.qualities=F.quality,i.profile=this.uriPattern("compliance"),t.contentType="application/json",t.body=JSON.stringify(i)):(s==="1.1"?(i["@context"]=this.uriPattern("context"),i["@id"]=r,i.width=e.width,i.height=e.height,i.scale_factors=this.factors(e),i.tile_width=this.tileWidth,i.tile_height=this.tileHeight,i.formats=F.format,i.qualities=F.quality,i.profile=this.uriPattern("compliance")):s==="2.0"||s==="2.1"?(i["@context"]=this.uriPattern("context"),i["@id"]=r,i.protocol="http://iiif.io/api/image",i.width=e.width,i.height=e.height,this.level==="0"?i.sizes=this.sizes(e):i.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],i.profile=[this.uriPattern("compliance")]):s==="3.0"&&(i["@context"]=[this.uriPattern("context")],i.id=r,i.type="ImageService3",i.protocol="http://iiif.io/api/image",i.width=e.width,i.height=e.height,this.level==="0"?i.sizes=this.sizes(e):i.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],i.profile=this.uriPattern("compliance")),t.contentType="application/ld+json"),t}factors(r){let e=1,t=[];for(;this.tileWidth*e<=r.width||this.tileHeight*e<=r.height;)t.push(e),e*=2;return t.length===0&&t.push(1),t}uriPattern(r){let e="",t="";return this.version==="1.0"?e=`http://library.stanford.edu/iiif/image-api/compliance.html#level${this.level}`:this.version==="1.1"?(e=`http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level${this.level}`,t="http://library.stanford.edu/iiif/image-api/1.1/context.json"):this.version==="2.0"||this.version==="2.1"?(e=`http://iiif.io/api/image/2/level${this.level}.json`,t="http://iiif.io/api/image/2/context.json"):this.version==="3.0"&&(e=`level${this.level}`,t="http://iiif.io/api/image/3/context.json"),r==="compliance"?e:r==="context"?t:""}sizes(r){return[{width:r.width,height:r.height}]}};X.exports=re});var oe=ye(se(),1);import x from"sharp";import{addDecoder as Be,BaseDecoder as He,fromCustomClient as ne,fromUrl as We,BaseClient as ae,BaseResponse as le}from"geotiff";var Me=1e8,Se=1e4,je=1e4,qe=512,Re=512,_e={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"]},Y=class extends He{async decode(e,t){let i=Array.isArray(e.BitsPerSample)?e.BitsPerSample.length:e.SamplesPerPixel||4,s=x(t,{sequentialRead:!0}),n=(await s.metadata()).channels||4;i===4&&n<4&&s.ensureAlpha?s=s.ensureAlpha():i===3&&n>3&&s.removeAlpha&&(s=s.removeAlpha());let{data:l,info:h}=await s.raw().toBuffer({resolveWithObject:!0});if(h.channels!==i){let m=h.width*h.height,y=Buffer.alloc(m*i),u=l;for(let c=0;c<m;c+=1){let p=c*h.channels,d=c*i;for(let g=0;g<i;g+=1)g<h.channels?y[d+g]=u[p+g]:y[d+g]=g===3?255:0}return y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength)}return l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength)}};Be(50001,()=>Promise.resolve(Y));var Q=class extends le{constructor(e){super(),this.result=e}get ok(){return this.result.res.status>=200&&this.result.res.status<300}get status(){return this.result.res.status}getHeader(e){return this.result.res.headers[e.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}},G=class extends ae{constructor(e,t){super(e),this.objectKey=e,this.ossClient=t}async request({headers:e={}}={}){let t=await this.ossClient.get(this.objectKey,{headers:e,timeout:3e4});return new Q(t)}};async function Fe(r,e){let t=new G(r,e);return ne(t)}var J=class extends le{constructor(e,t){super(),this.response=e,this.arrayBuffer=t}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(e){return this.response.headers.get(e)||""}getData(){return this.arrayBuffer}},K=class extends ae{constructor(e,t){super(e),this.ipfsUrl=e,this.verifiedFetch=t}async request({headers:e={}}={}){let t=new AbortController,i=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),t.abort()},3e4);try{let s=await this.verifiedFetch(this.ipfsUrl,{headers:e,signal:t.signal,session:!1});if(!s.ok)throw new Error(`Failed to fetch from IPFS: ${s.status} ${s.statusText}`);let o=await s.arrayBuffer();return clearTimeout(i),new J(s,o)}catch(s){throw clearTimeout(i),console.error("[IPFSClient] Error during request:",s),s instanceof Error&&(console.error("[IPFSClient] Error name:",s.name),console.error("[IPFSClient] Error message:",s.message),console.error("[IPFSClient] Error stack:",s.stack)),s&&typeof s=="object"&&"errors"in s&&console.error("[IPFSClient] AggregateError details:",s.errors),s}}};async function Ae(r,e){let t=new K(r,e);return await ne(t)}var V=class extends oe.default{constructor(e,t,i=!1,s=Me,o=Se,n=je,l=qe,h=Re){super(e,t,s,o,n,l,h),this.enableHD=i}regionImpl(e,t){e&&(t=t.extract({left:e.x,top:e.y,width:e.w,height:e.h}))}sizeImpl(e,t){e&&(t=t.resize({...e,fit:"fill"}))}rotationImpl(e,t){e&&(e.isMirror&&(t=t.flop()),t=t.rotate(e.degree))}qualityFormatImpl(e,t,i,s,o){e&&(e==="color"?i=i.toColorspace("srgb"):e==="gray"||e==="grey"?i=i.grayscale():e==="bitonal"&&(i=i.threshold())),t&&(i=i.toFormat(t)),s==="png"&&(o.paletteBitDepth===1||o.space==="b-w")&&(i=i.toColorspace("b-w").png({colors:2}))}async generateImageTile(e,t,i){let s=e.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],h=s.pop(),m=s.pop(),y=s.pop(),u=s.pop(),c={width:t.width,height:t.height},p=super.normalizeRegionParams(y,c),d=super.normalizeSizeParams(m,{width:p?p.w:c.width,height:p?p.h:c.height}),{x:g,y:v,w:I,h:z}=p??{x:0,y:0,w:c.width,h:c.height},{width:B,height:H}=d;console.log(`Attempting to fetch from URL: ${i}`);let P;typeof i=="string"?(console.log("Using standard HTTP fetch"),P=await We(i)):typeof u=="string"&&u.startsWith("bafy")?(console.log("Detected CID id, using fromIPFS"),P=await Ae(`ipfs://${u}`,i)):P=await Fe(u,i);let f=await P.getImage();console.log(`Source dimensions: ${f.getWidth()} x ${f.getHeight()}`),console.log(`Extracting region: x=${g}, y=${v}, w=${I}, h=${z}`),console.log(`Output size: ${B} x ${H}`);let w=await P.getImageCount();console.log(`Total images (including overviews): ${w}`);let R=f.getSamplesPerPixel(),W;R>=3?(W=[0,1,2],R>=4&&W.push(3)):W=[0],console.log("Using automatic overview selection based on resolution...");let L=Math.max(I/B,z/H),_=f,b=1;for(let A=0;A<w;A++){let C=await P.getImage(A),D=f.getWidth()/C.getWidth();D<=L&&D>b&&(b=D,_=C)}console.log(`Selected overview with scale: ${b.toFixed(2)}x`),console.log(`Overview dimensions: ${_.getWidth()} x ${_.getHeight()}`);let T=[Math.floor(g/b),Math.floor(v/b),Math.floor((g+I)/b),Math.floor((v+z)/b)],M;try{M=await _.readRasters({window:T,width:B,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}catch(A){console.log(`Failed to read from overview, falling back to main image: ${A}`);let C=[g,v,g+I,v+z];M=await f.readRasters({window:C,width:B,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}let q=W.length,S=Buffer.from(M.buffer,M.byteOffset,M.byteLength),$=x(S,{raw:{width:B,height:H,channels:q}}),he=super.normalizeRotationParams(h);this.rotationImpl(he,$);let ce=super.normalizeQualityParams(n),Z=super.normalizeFormatParams(l,t.format);this.qualityFormatImpl(ce,Z,$,l,t);let k={};return k.body=$,k.contentType=super.getContentType(Z),k}iiifTransform(e,t){let i=this.enableHD?x({limitInputPixels:!1,sequentialRead:!0}):x(),s=e.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],h=s.pop(),m=s.pop(),y=s.pop(),u=!1,c=i,p={width:t.width,height:t.height};t&&t.orientation&&(u=!0,c=c.rotate(),t.orientation>=5&&(p={width:t.height,height:t.width}));let d=super.normalizeRegionParams(y,p);this.regionImpl(d,c);let g=super.normalizeSizeParams(m,{width:d?d.w:p.width,height:d?d.h:p.height});this.sizeImpl(g,c);let v=super.normalizeRotationParams(h);this.rotationImpl(v,c);let I=super.normalizeQualityParams(n),z=super.normalizeFormatParams(l,t.format);return this.qualityFormatImpl(I,z,c,l,t),d||g||v||I||z||u?c:(console.log("skip iiif transform"),null)}async generateIiifImage(e,t,i){let s=e.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],h=s.pop(),m=s.pop(),y=s.pop(),u=super.normalizeRegionParams(y,i),c=super.normalizeSizeParams(m,{width:u?u.w:i.width,height:u?u.h:i.height}),p=super.normalizeRotationParams(h),d=super.normalizeQualityParams(n),g=super.normalizeFormatParams(l,i.format),{x:v,y:I,w:z,h:B}=u||{x:0,y:0,w:i.width,h:i.height},{width:H,height:P}=c||{width:i.width,height:i.height},f=0,w;if(i.pages&&i.pages>1){let W=H/z,L=P/B,_=Math.max(W,L);f=i.pages-1;let b=this.enableHD?await x(t,{limitInputPixels:!1,page:f,sequentialRead:!0}).metadata():await x(t,{page:f}).metadata(),T=b.width,M=b.height;for(;f>0;){let q=z*(T/i.width),S=B*(M/i.height);if(q>=H&&S>=P)break;f--,T*=2,M*=2}if(console.log(`Pyramid optimization: selected page ${f}/${i.pages-1} (scale: ${_.toFixed(2)}x, target: ${H}x${P})`),w=this.enableHD?x(t,{limitInputPixels:!1,page:f,sequentialRead:!0}):x(t,{page:f}),u&&f>0){let q=await w.metadata(),S=q.width/i.width,$={x:Math.floor(v*S),y:Math.floor(I*S),w:Math.floor(z*S),h:Math.floor(B*S)};$.w=Math.min($.w,q.width-$.x),$.h=Math.min($.h,q.height-$.y),this.regionImpl($,w)}else this.regionImpl(u,w)}else w=this.enableHD?x(t,{limitInputPixels:!1,sequentialRead:!0}):x(t),this.regionImpl(u,w);this.sizeImpl(c,w),this.rotationImpl(p,w),this.qualityFormatImpl(d,g,w,l,i);let R={};return R.body=w,R.contentType=super.getContentType(g),R}generateImageInfo(e,t,i=""){let s=this.version,o=this.level,n={width:t.width,height:t.height};t&&t.orientation&&t.orientation>=5&&(console.log(t.orientation),n={width:t.height,height:t.width});let l=super.generateImageInfoTemp(e,n),h=l.info;if((s==="2.0"||s==="2.1")&&(h.profile=[super.uriPattern("compliance")],o==="2")){let m={};m.formats=["jpg","png","webp","jp2","pdf","tif"],m.qualities=["color","gray","bitonal","default","native","grey"],m.supports=_e[Number(s)],h.profile.push(m)}return s==="3.0"&&i&&(h.extraFormats=[i],h.preferredFormats=[i]),i&&(h.formats=[i]),l}};export{V as default};
|