@etu-wiki/sharp-iiif-shims 0.1.3 → 0.1.5
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 me=Object.create;var re=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var be=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var ve=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of we(e))!ze.call(s,r)&&r!==t&&re(s,r,{get:()=>e[r],enumerable:!(i=de(e,r))||i.enumerable});return s};var $e=(s,e,t)=>(t=s!=null?me(ye(s)):{},ve(e||!s||!s.__esModule?re(t,"default",{value:s,enumerable:!0}):t,s));var le=be((Le,J)=>{"use strict";var G=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Pe=Object.getOwnPropertyNames,Ie=Object.prototype.hasOwnProperty,Be=(s,e)=>{for(var t in e)G(s,t,{get:e[t],enumerable:!0})},He=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pe(e))!Ie.call(s,r)&&r!==t&&G(s,r,{get:()=>e[r],enumerable:!(i=xe(e,r))||i.enumerable});return s},Me=s=>He(G({},"__esModule",{value:!0}),s),ae={};Be(ae,{default:()=>ne});J.exports=Me(ae);var n="[1-9][0-9]*",oe="[0-9]*",j="(?=.*[1-9])\\d+(\\.\\d+)?",Q="\\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",`${oe},${oe},${n},${n}`,`pct:${Q},${Q},${j},${j}`],rotation:`!?${Q}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:[""]},We={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,]+)/,ne=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=We[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}]}};J.exports=ne});var ge=$e(le(),1);import b from"sharp";import{addDecoder as Se,BaseDecoder as je,fromCustomClient as ue,fromUrl as Re,BaseClient as fe,BaseResponse as pe}from"geotiff";import{verifiedFetch as qe}from"@helia/verified-fetch";var _e=1e8,he=1e4,ce=1e4,Te=512,Fe=512,Ae={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"]},K=class extends je{async decode(e,t){let i=Array.isArray(e.BitsPerSample)?e.BitsPerSample.length:e.SamplesPerPixel||4,r=b(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)}};Se(50001,()=>Promise.resolve(K));var V=class extends pe{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}},Z=class extends fe{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 V(t)}};async function Ce(s,e){let t=new Z(s,e);return ue(t)}var ee=class extends pe{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}},te=class extends fe{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 r=await qe(this.ipfsUrl,{headers:e});if(!r.ok)throw new Error(`Failed to fetch from IPFS: ${r.status} ${r.statusText}`);let o=await r.arrayBuffer();return clearTimeout(i),new ee(r,o)}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 Oe(s){let e=new te(s);return await ue(e)}var ie=class extends ge.default{constructor(e,t,i=!1,r=_e,o=he,a=ce,h=Te,c=Fe){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:R,height:H}=p;console.log(`Attempting to fetch from URL: ${i}`);let $;typeof i=="string"?i.startsWith("ipfs://")?(console.log("Detected IPFS protocol URL, using verified-fetch"),$=await Oe(i)):(console.log("Using standard HTTP fetch"),$=await Re(i)):$=await Ce(M,i);let x=await $.getImage();console.log(`Source dimensions: ${x.getWidth()} x ${x.getHeight()}`),console.log(`Extracting region: x=${g}, y=${f}, w=${y}, h=${B}`),console.log(`Output size: ${R} x ${H}`);let T=await $.getImageCount();console.log(`Total images (including overviews): ${T}`);let k=x.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/R,B/H),d=x,v=1;for(let I=0;I<T;I++){let q=await $.getImage(I),S=x.getWidth()/q.getWidth();S<=D&&S>v&&(v=S,d=q)}console.log(`Selected overview with scale: ${v.toFixed(2)}x`),console.log(`Overview dimensions: ${d.getWidth()} x ${d.getHeight()}`);let E=[Math.floor(g/v),Math.floor(f/v),Math.floor((g+y)/v),Math.floor((f+B)/v)],P;try{P=await d.readRasters({window:E,width:R,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}catch(I){console.log(`Failed to read from overview, falling back to main image: ${I}`);let q=[g,f,g+y,f+B];P=await x.readRasters({window:q,width:R,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}let F=W.length,N=Buffer.from(P.buffer,P.byteOffset,P.byteLength),A=b(N,{raw:{width:R,height:H,channels:F}}),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?b({limitInputPixels:!1,sequentialRead:!0}):b(),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?b(t,{limitInputPixels:!1,sequentialRead:!0}):b(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:R,w:H,h:$}=f||{x:0,y:0,w:u.width,h:u.height},{width:x,height:T}=y||{width:u.width,height:u.height};try{if(H*$>x*T*i&&x<he&&T<ce&&l.pages&&l.pages>1){console.log("thumbnail");let d=Math.max(x/H,T/$),[v,E,P,F]=[Math.round(B*d),Math.round(R*d),Math.round(H*d),Math.round($*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 b(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).metadata():await b(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},q=this.enableHD?await b(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).resize(I).toBuffer():await b(t,{page:m}).resize(I).toBuffer(),S=this.enableHD?b(q,{limitInputPixels:!1,sequentialRead:!0}):b(q),_=await S.metadata();console.log(_),E+F>_.height&&(F=_.height-E,console.log("adjested sh: "+F)),v+P>_.width&&(P=_.width-v,console.log("adjusted sw: "+P));let se={x:v,y:E,w:P,h:F};this.regionImpl(se,S),this.sizeImpl(y,S),console.log(_.width,_.height,I.width,I.height,se,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=Ae[Number(r)],c.profile.push(w)}return r==="3.0"&&i&&(c.extraFormats=[i],c.preferredFormats=[i]),i&&(c.formats=[i]),h}};export{ie as default};
|
|
1
|
+
var me=Object.create;var re=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var be=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var ve=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of we(e))!ze.call(s,r)&&r!==t&&re(s,r,{get:()=>e[r],enumerable:!(i=de(e,r))||i.enumerable});return s};var $e=(s,e,t)=>(t=s!=null?me(ye(s)):{},ve(e||!s||!s.__esModule?re(t,"default",{value:s,enumerable:!0}):t,s));var le=be((Ee,J)=>{"use strict";var G=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Pe=Object.getOwnPropertyNames,Ie=Object.prototype.hasOwnProperty,Be=(s,e)=>{for(var t in e)G(s,t,{get:e[t],enumerable:!0})},He=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pe(e))!Ie.call(s,r)&&r!==t&&G(s,r,{get:()=>e[r],enumerable:!(i=xe(e,r))||i.enumerable});return s},Me=s=>He(G({},"__esModule",{value:!0}),s),ae={};Be(ae,{default:()=>ne});J.exports=Me(ae);var n="[1-9][0-9]*",oe="[0-9]*",j="(?=.*[1-9])\\d+(\\.\\d+)?",Q="\\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",`${oe},${oe},${n},${n}`,`pct:${Q},${Q},${j},${j}`],rotation:`!?${Q}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:[""]},We={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,]+)/,ne=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=We[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}]}};J.exports=ne});var ge=$e(le(),1);import b from"sharp";import{addDecoder as Se,BaseDecoder as je,fromCustomClient as ue,fromUrl as qe,BaseClient as fe,BaseResponse as pe}from"geotiff";var Re=1e8,he=1e4,ce=1e4,_e=512,Fe=512,Te={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"]},K=class extends je{async decode(e,t){let i=Array.isArray(e.BitsPerSample)?e.BitsPerSample.length:e.SamplesPerPixel||4,r=b(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),v=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]=v[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)}};Se(50001,()=>Promise.resolve(K));var V=class extends pe{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}},Z=class extends fe{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 V(t)}};async function Ae(s,e){let t=new Z(s,e);return ue(t)}var ee=class extends pe{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}},te=class extends fe{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 r=await this.verifiedFetch(this.ipfsUrl,{headers:e,signal:t.signal,session:!1});if(!r.ok)throw new Error(`Failed to fetch from IPFS: ${r.status} ${r.statusText}`);let o=await r.arrayBuffer();return clearTimeout(i),new ee(r,o)}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 Ce(s,e){let t=new te(s,e);return await ue(t)}var ie=class extends ge.default{constructor(e,t,i=!1,r=Re,o=he,a=ce,h=_e,c=Fe){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(),v=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:H}=u??{x:0,y:0,w:l.width,h:l.height},{width:q,height:M}=p;console.log(`Attempting to fetch from URL: ${i}`);let x;typeof i=="string"?(console.log("Using standard HTTP fetch"),x=await qe(i)):typeof v=="string"&&v.startsWith("bafy")?(console.log("Detected CID id, using fromIPFS"),x=await Ce(`ipfs://${v}`,i)):x=await Ae(v,i);let P=await x.getImage();console.log(`Source dimensions: ${P.getWidth()} x ${P.getHeight()}`),console.log(`Extracting region: x=${g}, y=${f}, w=${y}, h=${H}`),console.log(`Output size: ${q} x ${M}`);let F=await x.getImageCount();console.log(`Total images (including overviews): ${F}`);let k=P.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/q,H/M),d=P,$=1;for(let B=0;B<F;B++){let R=await x.getImage(B),S=P.getWidth()/R.getWidth();S<=D&&S>$&&($=S,d=R)}console.log(`Selected overview with scale: ${$.toFixed(2)}x`),console.log(`Overview dimensions: ${d.getWidth()} x ${d.getHeight()}`);let E=[Math.floor(g/$),Math.floor(f/$),Math.floor((g+y)/$),Math.floor((f+H)/$)],I;try{I=await d.readRasters({window:E,width:q,height:M,samples:W,interleave:!0,resampleMethod:"bilinear"})}catch(B){console.log(`Failed to read from overview, falling back to main image: ${B}`);let R=[g,f,g+y,f+H];I=await P.readRasters({window:R,width:q,height:M,samples:W,interleave:!0,resampleMethod:"bilinear"})}let T=W.length,N=Buffer.from(I.buffer,I.byteOffset,I.byteLength),A=b(N,{raw:{width:q,height:M,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?b({limitInputPixels:!1,sequentialRead:!0}):b(),r=e.split("/"),o=r.pop(),a=o.split(".")[0],h=o.split(".")[1],c=r.pop(),w=r.pop(),z=r.pop(),v=!1,l=i,u={width:t.width,height:t.height};t&&t.orientation&&(v=!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),H=super.normalizeFormatParams(h,t.format);return this.qualityFormatImpl(y,H,l,h,t),p||g||f||y||H||v?l:(console.log("skip iiif transform"),null)}async generateIiifImage(e,t,i=256){let r=this.enableHD?b(t,{limitInputPixels:!1,sequentialRead:!0}):b(t),o=e.split("/"),a=o.pop(),h=a.split(".")[0],c=a.split(".")[1],w=o.pop(),z=o.pop(),v=o.pop(),l=await r.metadata(),u={width:l.width,height:l.height},p={},g=r,f=super.normalizeRegionParams(v,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:H,y:q,w:M,h:x}=f||{x:0,y:0,w:u.width,h:u.height},{width:P,height:F}=y||{width:u.width,height:u.height};try{if(M*x>P*F*i&&P<he&&F<ce&&l.pages&&l.pages>1){console.log("thumbnail");let d=Math.max(P/M,F/x),[$,E,I,T]=[Math.round(H*d),Math.round(q*d),Math.round(M*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 b(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).metadata():await b(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 B={width:N,height:A,fastShrinkOnLoad:!1},R=this.enableHD?await b(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).resize(B).toBuffer():await b(t,{page:m}).resize(B).toBuffer(),S=this.enableHD?b(R,{limitInputPixels:!1,sequentialRead:!0}):b(R),_=await S.metadata();console.log(_),E+T>_.height&&(T=_.height-E,console.log("adjested sh: "+T)),$+I>_.width&&(I=_.width-$,console.log("adjusted sw: "+I));let se={x:$,y:E,w:I,h:T};this.regionImpl(se,S),this.sizeImpl(y,S),console.log(_.width,_.height,B.width,B.height,se,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=Te[Number(r)],c.profile.push(w)}return r==="3.0"&&i&&(c.extraFormats=[i],c.preferredFormats=[i]),i&&(c.formats=[i]),h}};export{ie as default};
|