@etu-wiki/sharp-iiif-shims 0.1.6 → 0.1.8
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 -2
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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};
|
|
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,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fe(e))!me.call(r,s)&&s!==i&&ee(r,s,{get:()=>e[s],enumerable:!(t=ue(e,s))||t.enumerable});return r};var ye=(r,e,i)=>(i=r!=null?ge(pe(r)):{},we(e||!r||!r.__esModule?ee(i,"default",{value:r,enumerable:!0}):i,r));var se=de((Oe,X)=>{"use strict";var U=Object.defineProperty,ze=Object.getOwnPropertyDescriptor,$e=Object.getOwnPropertyNames,ve=Object.prototype.hasOwnProperty,Pe=(r,e)=>{for(var i in e)U(r,i,{get:e[i],enumerable:!0})},be=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $e(e))!ve.call(r,s)&&s!==i&&U(r,s,{get:()=>e[s],enumerable:!(t=ze(e,s))||t.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]*",S="(?=.*[1-9])\\d+(\\.\\d+)?",N="\\d+(\\.\\d+)?",C=(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))(C||{}),R={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},${S},${S}`],rotation:`!?${N}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:[""]},Ie={1:["full",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`],1.1:["full",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`],2:["full",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`],2.1:["full","max",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`],3:["max",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`,"\\^max",`\\^${a},`,`\\^,${a}`,`\\^pct:${S}`,`\\^${a},${a}`,`\\^!${a},${a}`]},O=/^pct:([\d,]+)/,re=class{constructor(r,e,i,t,s,o,n){this.version=r,this.level=e,this.maxArea=i,this.maxWidth=t,this.maxHeight=s,this.tileWidth=o,this.tileHeight=n,this.validate("version",r),this.validate("level",e),R.size=Ie[Number(r)]}validator(r){var e=R[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 i=r.split(",").map(t=>Number(t));return this._regionXYWH(i,e)}}_regionSquare(r){let e,i,t=r.width,s=r.height;if(t!==s){let o=Math.min(t,s),n=Math.abs(Math.floor((t-s)/2));return t>s?(e=n,i=0):(e=0,i=n),this._regionXYWH([e,i,o,o],r)}return null}_regionPct(r,e){let i=r.split(",").map((t,s)=>{let o=Number(t)/100;return s===0||s===2?Math.ceil(e.width*o):s===1||s===3?Math.ceil(e.height*o):null});return this._regionXYWH(i,e)}_regionXYWH(r,e){let i=e.width,t=e.height,[s,o,n,l]=r;return s+n>i&&(n=i-s),o+l>t&&(l=t-o),{x:s,y:o,w:n,h:l}}normalizeSizeParams(r,e){let i=r,t=e.width,s=e.height;if(!e||!t&&!s)throw Error(`invalid region dimensions: ${JSON.stringify(e,null,2)}`);this.validate("size",i);let o=!1;i.charAt(0)==="^"&&(o=!0,i=i.substring(1));let n=null;if(i==="full"||(i==="max"?n=this._sizeMaxScale(e):O.test(i)?n=this._sizePctScale(i.match(O)[1]):i.charAt(0)==="!"&&(i=i.substring(1),n=this._sizeBangScale(i,o,e)),n===1))return null;if(n){let l=Math.ceil(t*n),h=Math.ceil(s*n);return this._sizeWH(`${l},${h}`,o,e)}else return this._sizeWH(i,o,e)}_sizeBangScale(r,e,i){let t=i.width,s=i.height,[o,n]=r.split(",").map(h=>h===""?null:Number(h)),l=Math.min(o/t,n/s);if(o>t&&n>s&&!e)throw Error("should not upscale without ^");return l}_sizeMaxScale(r){let e=r.width,i=r.height,t=1;return this.maxArea&&this.maxArea<e*i&&(t=Math.sqrt(this.maxArea/(e*i))),this.maxWidth&&this.maxWidth<e&&(t=Math.min(t,this.maxWidth/e)),this.maxHeight&&this.maxHeight<i&&(t=Math.min(t,this.maxHeight/i)),t}_sizePctScale(r){return Number(r)/100}_sizeWH(r,e,i){let t=i.width,s=i.height,[o,n]=r.split(",").map(l=>l===""?null:Number(l));if(o?n||(n=Math.ceil(s*o/t),n=n===0?1:n):(o=Math.ceil(t*n/s),o=o===0?1:o),(o>t||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 i=Number(r.replace(/^!/,""));return{isMirror:e,degree:i}}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 i=C[r],t=C[e];return i===t?null:r}getContentType(r){return C[r]}generateImageInfoTemp(r,e){let i={},t={};i.info=t;let s=this.version;return s==="1.0"?(t.identifier=r,t.width=e.width,t.height=e.height,t.scale_factors=this.factors(e),t.tile_width=this.tileWidth,t.tile_height=this.tileHeight,t.formats=R.format,t.qualities=R.quality,t.profile=this.uriPattern("compliance"),i.contentType="application/json",i.body=JSON.stringify(t)):(s==="1.1"?(t["@context"]=this.uriPattern("context"),t["@id"]=r,t.width=e.width,t.height=e.height,t.scale_factors=this.factors(e),t.tile_width=this.tileWidth,t.tile_height=this.tileHeight,t.formats=R.format,t.qualities=R.quality,t.profile=this.uriPattern("compliance")):s==="2.0"||s==="2.1"?(t["@context"]=this.uriPattern("context"),t["@id"]=r,t.protocol="http://iiif.io/api/image",t.width=e.width,t.height=e.height,this.level==="0"?t.sizes=this.sizes(e):t.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],t.profile=[this.uriPattern("compliance")]):s==="3.0"&&(t["@context"]=[this.uriPattern("context")],t.id=r,t.type="ImageService3",t.protocol="http://iiif.io/api/image",t.width=e.width,t.height=e.height,this.level==="0"?t.sizes=this.sizes(e):t.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],t.profile=this.uriPattern("compliance")),i.contentType="application/ld+json"),i}factors(r){let e=1,i=[];for(;this.tileWidth*e<=r.width||this.tileHeight*e<=r.height;)i.push(e),e*=2;return i.length===0&&i.push(1),i}uriPattern(r){let e="",i="";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}`,i="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`,i="http://iiif.io/api/image/2/context.json"):this.version==="3.0"&&(e=`level${this.level}`,i="http://iiif.io/api/image/3/context.json"),r==="compliance"?e:r==="context"?i:""}sizes(r){return[{width:r.width,height:r.height}]}};X.exports=re});var oe=ye(se(),1);import _ 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,i){let t=Array.isArray(e.BitsPerSample)?e.BitsPerSample.length:e.SamplesPerPixel||4,s=_(i,{sequentialRead:!0}),n=(await s.metadata()).channels||4;t===4&&n<4&&s.ensureAlpha?s=s.ensureAlpha():t===3&&n>3&&s.removeAlpha&&(s=s.removeAlpha());let{data:l,info:h}=await s.raw().toBuffer({resolveWithObject:!0});if(h.channels!==t){let m=h.width*h.height,z=Buffer.alloc(m*t),u=l;for(let c=0;c<m;c+=1){let p=c*h.channels,d=c*t;for(let g=0;g<t;g+=1)g<h.channels?z[d+g]=u[p+g]:z[d+g]=g===3?255:0}return z.buffer.slice(z.byteOffset,z.byteOffset+z.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,i){super(e),this.objectKey=e,this.ossClient=i}async request({headers:e={}}={}){let i=await this.ossClient.get(this.objectKey,{headers:e,timeout:3e4});return new Q(i)}};async function Fe(r,e){let i=new G(r,e);return ne(i)}var J=class extends le{constructor(e,i){super(),this.response=e,this.arrayBuffer=i}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,i){super(e),this.ipfsUrl=e,this.verifiedFetch=i}async request({headers:e={}}={}){let i=new AbortController,t=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),i.abort()},3e4);try{let s=await this.verifiedFetch(this.ipfsUrl,{headers:e,signal:i.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(t),new J(s,o)}catch(s){throw clearTimeout(t),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 i=new K(r,e);return await ne(i)}var V=class extends oe.default{constructor(e,i,t=!1,s=Me,o=Se,n=je,l=qe,h=Re){super(e,i,s,o,n,l,h),this.enableHD=t}regionImpl(e,i){e&&(i=i.extract({left:e.x,top:e.y,width:e.w,height:e.h}))}sizeImpl(e,i){e&&(i=i.resize({...e,fit:"fill"}))}rotationImpl(e,i){e&&(e.isMirror&&(i=i.flop()),i=i.rotate(e.degree))}qualityFormatImpl(e,i,t,s,o){e&&(e==="color"?t=t.toColorspace("srgb"):e==="gray"||e==="grey"?t=t.grayscale():e==="bitonal"&&(t=t.threshold())),i&&(t=t.toFormat(i)),s==="png"&&(o.paletteBitDepth===1||o.space==="b-w")&&(t=t.toColorspace("b-w").png({colors:2}))}async generateImageTile(e,i,t){let s=e.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],h=s.pop(),m=s.pop(),z=s.pop(),u=s.pop(),c={width:i.width,height:i.height},p=super.normalizeRegionParams(z,c),d=super.normalizeSizeParams(m,{width:p?p.w:c.width,height:p?p.h:c.height}),{x:g,y:P,w:I,h:v}=p??{x:0,y:0,w:c.width,h:c.height},{width:B,height:H}=d;console.log(`Attempting to fetch from URL: ${t}`);let b;typeof t=="string"?(console.log("Using standard HTTP fetch"),b=await We(t)):typeof u=="string"&&u.startsWith("bafy")?(console.log("Detected CID id, using fromIPFS"),b=await Ae(`ipfs://${u}`,t)):b=await Fe(u,t);let f=await b.getImage();console.log(`Source dimensions: ${f.getWidth()} x ${f.getHeight()}`),console.log(`Extracting region: x=${g}, y=${P}, w=${I}, h=${v}`),console.log(`Output size: ${B} x ${H}`);let w=await b.getImageCount();console.log(`Total images (including overviews): ${w}`);let q=f.getSamplesPerPixel(),x;q>=3?(x=[0,1,2],q>=4&&x.push(3)):x=[0],console.log("Using automatic overview selection based on resolution...");let E=Math.max(I/B,v/H),j=f,W=1;for(let A=0;A<w;A++){let T=await b.getImage(A),D=f.getWidth()/T.getWidth();D<=E&&D>W&&(W=D,j=T)}console.log(`Selected overview with scale: ${W.toFixed(2)}x`),console.log(`Overview dimensions: ${j.getWidth()} x ${j.getHeight()}`);let M=[Math.floor(g/W),Math.floor(P/W),Math.floor((g+I)/W),Math.floor((P+v)/W)],y;try{y=await j.readRasters({window:M,width:B,height:H,samples:x,interleave:!0,resampleMethod:"bilinear"})}catch(A){console.log(`Failed to read from overview, falling back to main image: ${A}`);let T=[g,P,g+I,P+v];y=await f.readRasters({window:T,width:B,height:H,samples:x,interleave:!0,resampleMethod:"bilinear"})}let $=x.length,L=Buffer.from(y.buffer,y.byteOffset,y.byteLength),F=_(L,{raw:{width:B,height:H,channels:$}}),he=super.normalizeRotationParams(h);this.rotationImpl(he,F);let ce=super.normalizeQualityParams(n),Z=super.normalizeFormatParams(l,i.format);this.qualityFormatImpl(ce,Z,F,l,i);let k={};return k.body=F,k.contentType=super.getContentType(Z),k}iiifTransform(e,i){let t=this.enableHD?_({limitInputPixels:!1,sequentialRead:!0}):_(),s=e.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],h=s.pop(),m=s.pop(),z=s.pop(),u=!1,c=t,p={width:i.width,height:i.height};i&&i.orientation&&(u=!0,c=c.rotate(),i.orientation>=5&&(p={width:i.height,height:i.width}));let d=super.normalizeRegionParams(z,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 P=super.normalizeRotationParams(h);this.rotationImpl(P,c);let I=super.normalizeQualityParams(n),v=super.normalizeFormatParams(l,i.format);return this.qualityFormatImpl(I,v,c,l,i),d||g||P||I||v||u?c:(console.log("skip iiif transform"),null)}async generateIiifImage(e,i,t){let s=e.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],h=s.pop(),m=s.pop(),z=s.pop(),u=super.normalizeRegionParams(z,t),c=super.normalizeSizeParams(m,{width:u?u.w:t.width,height:u?u.h:t.height}),p=super.normalizeRotationParams(h),d=super.normalizeQualityParams(n),g=super.normalizeFormatParams(l,t.format),{x:P,y:I,w:v,h:B}=u||{x:0,y:0,w:t.width,h:t.height},{width:H,height:b}=c||{width:t.width,height:t.height},f=0,w;if(t.pages&&t.pages>1){let x=H/v,E=b/B,j=Math.max(x,E);if(j>=.95)console.log("Pyramid optimization: using full resolution page (scale \u2248 1.0)"),f=0;else{f=t.pages-1;let M=Math.pow(2,t.pages-1),y=t.width/M,$=t.height/M;for(;f>0;){let L=v*(y/t.width),F=B*($/t.height);if(L>=H*1.1&&F>=b*1.1)break;f--,y*=2,$*=2}console.log(`Pyramid optimization: selected page ${f}/${t.pages-1} (scale: ${j.toFixed(2)}x, target: ${H}x${b})`)}let W=this.enableHD?{limitInputPixels:!1,page:f,sequentialRead:!0,failOn:"none"}:{page:f,sequentialRead:!0,failOn:"none"};if(w=_(i,W),u&&f>0){let M=await w.metadata(),y=M.width/t.width,$={x:Math.floor(P*y),y:Math.floor(I*y),w:Math.floor(v*y),h:Math.floor(B*y)};$.w=Math.min($.w,M.width-$.x),$.h=Math.min($.h,M.height-$.y),this.regionImpl($,w)}else this.regionImpl(u,w)}else{let x=this.enableHD?{limitInputPixels:!1,sequentialRead:!0,failOn:"none"}:{sequentialRead:!0,failOn:"none"};w=_(i,x),this.regionImpl(u,w)}this.sizeImpl(c,w),this.rotationImpl(p,w),this.qualityFormatImpl(d,g,w,l,t);let q={};return q.body=w,q.contentType=super.getContentType(g),q}generateImageInfo(e,i,t=""){let s=this.version,o=this.level,n={width:i.width,height:i.height};i&&i.orientation&&i.orientation>=5&&(console.log(i.orientation),n={width:i.height,height:i.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"&&t&&(h.extraFormats=[t],h.preferredFormats=[t]),t&&(h.formats=[t]),l}};export{V as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@etu-wiki/sharp-iiif-shims",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -31,7 +31,6 @@
|
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"@etu-wiki/iiif-image-shims": "^0.0.26",
|
|
34
|
-
"@helia/verified-fetch": "^3.2.3",
|
|
35
34
|
"geotiff": "^2.1.3"
|
|
36
35
|
},
|
|
37
36
|
"peerDependencies": {
|