@keeratita/heic-converter 0.5.2 → 0.6.0

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 CHANGED
@@ -1 +1 @@
1
- import{HeicConverterError as e,Messages as t,validateConvertOptions as n,throwIfAborted as i,DEFAULT_QUALITY as r,validateConcurrency as o,validateBatchOptions as a,runnerCountFor as s,runBoundedBatch as c,clampPercent as d,validateFormat as f,validateCrop as u,validateResize as h}from"./chunk-PTRQ7ZFB.mjs";export{DEFAULT_QUALITY,HeicConverterError,SUPPORTED_FORMATS}from"./chunk-PTRQ7ZFB.mjs";var l=new WeakSet,w=/[\u0000-\u001f\u007f-\u009f]+/g,m=class{options;module=null;decoderInstance=null;initPromise=null;initGeneration=0;constructor(e){this.options=e}async initialize(){if(!this.initPromise){const e=++this.initGeneration,t={};this.options?.moduleOverrides&&Object.assign(t,this.options.moduleOverrides),this.options?.locateFile&&(t.locateFile=this.options.locateFile),this.options?.wasmBinary&&(t.wasmBinary=this.options.wasmBinary);const n=import("./heic-decoder-43VH2M3C.mjs").then(({default:e})=>e(t)).then(t=>{const n=new t.HeicDecoder;return e!==this.initGeneration?(n.delete(),null):(this.module=t,this.decoderInstance=n,t)}).catch(e=>{throw this.initPromise===n&&(this.initPromise=null),e});this.initPromise=n}await this.initPromise}async decode(n,i){if(this.module&&this.decoderInstance||await this.initialize(),!this.module||!this.decoderInstance)throw new e("decode_failed",t.DecoderFreedDuringDecode);let r;const o=i?e=>{try{i(d(e))}catch(e){r=r??e}}:null,a=this.module,s=this.decoderInstance;let c;try{if("function"==typeof s.decodeFromPointer&&"function"==typeof a._malloc&&"function"==typeof a._free&&a.HEAPU8 instanceof Uint8Array&&n.buffer!==a.HEAPU8.buffer){const i=a._malloc(n.byteLength);if(0===i)throw new e("decode_failed",t.DecodeInputAllocFailed(n.byteLength));try{a.HEAPU8.set(n,i),c=s.decodeFromPointer(i,n.byteLength,o)}finally{a._free(i)}}else c=s.decode(n,o)}catch(i){if(i instanceof e)throw i;throw l.add(this),new e("decode_failed",t.DecodeFaulted(n.byteLength),{cause:i})}if("string"==typeof c)throw new e("decode_failed",t.DecodeFailedWithDetail(function(e){const t=e.replace(w," ").trim();return t.length>200?`${t.slice(0,197)}...`:t}(c),n.byteLength));if(!c)throw new e("decode_failed",t.DecodeFailed(n.byteLength));if(void 0!==r)throw new e("progress_callback_failed",t.ProgressCallbackThrew(r instanceof Error?r.message:String(r)),{cause:r});const f=c.width,u=c.height,h=c.orientation,m="number"==typeof h&&Number.isInteger(h)&&h>=1&&h<=8?h:1,g=a.HEAPU8 instanceof Uint8Array?a.HEAPU8.buffer:void 0,p={width:f,height:u,data:void 0!==g&&c.data.buffer!==g?new Uint8ClampedArray(c.data.buffer,c.data.byteOffset,c.data.byteLength):new Uint8ClampedArray(c.data)};m>1&&(p.orientation=m);const y=c.exif;return y instanceof Uint8Array&&y.length>=14&&(p.exif=void 0!==g&&y.buffer!==g?new Uint8Array(y.buffer,y.byteOffset,y.byteLength):new Uint8Array(y)),p}free(){this.initGeneration+=1,this.decoderInstance&&(this.decoderInstance.delete(),this.decoderInstance=null),this.module=null,l.delete(this),this.initPromise=null}},g=16384;function p(){if("undefined"==typeof OffscreenCanvas&&"undefined"==typeof document)throw new e("unsupported_environment",t.CanvasUnsupported)}var y=null;function v(){if(null===y){const e=async function(){let e;try{e=P(1,1)}catch{return}const t=F(e,"image/avif");let n;const i=new Promise(e=>{n=setTimeout(()=>e("timeout"),5e3)});try{const e=await Promise.race([t,i]);return"timeout"===e?void 0:"image/avif"===e.type&&e.size>0}finally{void 0!==n&&clearTimeout(n),B(e)}}().catch(()=>!1);y=e,e.then(t=>{void 0===t&&y===e&&(y=null)})}return y}async function b(n){if(f(n),"avif"===String(n).toLowerCase()&&!1===await v())throw new e("format_unsupported",t.FormatUnsupported("avif"))}function _(n,i){if(!Number.isFinite(n)||!Number.isFinite(i)||n>g||i>g)throw new e("invalid_resize",t.TargetSizeTooLarge(n,i,g))}async function I(n){if("undefined"!=typeof FileReader)return new Promise((i,r)=>{const o=new FileReader;o.onloadend=()=>{"string"==typeof o.result?i(o.result):r(new e("render_encode_failed",t.BlobToBase64Failed))},o.onerror=()=>r(new e("render_encode_failed",t.BlobToBase64FailedWithCause(o.error?.message??"FileReader failed"),{cause:o.error??void 0})),o.readAsDataURL(n)});try{const e=await n.arrayBuffer(),t=new Uint8Array(e);let i="";const r=32768;for(let e=0;e<t.length;e+=r)i+=String.fromCharCode(...t.subarray(e,e+r));const o=btoa(i);return`data:${n.type};base64,${o}`}catch(n){throw new e("render_encode_failed",t.BlobToBase64FailedWithCause(n instanceof Error?n.message:String(n)),{cause:n})}}function F(n,i,r){return"convertToBlob"in n?n.convertToBlob({type:i,quality:r}):new Promise((o,a)=>{n.toBlob(n=>{n?o(n):a(new e("render_encode_failed",t.CanvasToBlobFailed(i)))},i,r)})}function P(n,i){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(n,i);if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=n,e.height=i,e}throw new e("unsupported_environment",t.CanvasUnsupported)}function B(e){const t=e;"function"==typeof t.close?t.close():e.width=0}function U(e,t,n,i){if("undefined"!=typeof ImageData)e.putImageData(new ImageData(t,n,i),0,0);else{const r=e.createImageData(n,i);r.data.set(t),e.putImageData(r,0,0)}}var x=!1;async function A(e,t,n,i,r){const o=t.exif;if(!n||!o||0===o.length)return e;const a=await import("./exif-MBEKII5G.mjs").catch(()=>null);if(!a)return x||(x=!0,console.warn("@keeratita/heic-converter: the EXIF injector chunk could not be loaded — converted without metadata; serve every file in dist/ together, with dist/exif-*.mjs as JavaScript.")),e;const{injectExifIntoJpeg:s,injectExifIntoPng:c,normalizeOrientationTag:d}=a,f=r?d(o):o,u=new Uint8Array(await e.arrayBuffer()),h="jpeg"===i?s(u,f):c(u,f);return h===u?e:new Blob([h.buffer],{type:e.type})}function C(){return import("./worker-FNMN2SJV.mjs").catch(n=>{const i=n instanceof Error?n.message:String(n);throw new e("worker_load_failed",t.WorkerChunkLoadFailed(i),{cause:n})})}function T(e,t){return C().then(n=>n.convertHeicInWorker(e,t))}function E(e,t){return C().then(n=>n.convertManyInWorker(e,t))}function O(){}async function D(o,a){const s=a?.to??"jpeg";n(a),p(),await b(s);const c=a?.signal;i(c);const l=void 0!==a?.maxWidth||void 0!==a?.maxHeight||void 0!==a?.scale?a:void 0,w=await async function(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if("undefined"!=typeof Blob&&n instanceof Blob)return new Uint8Array(await n.arrayBuffer());if(null!==n&&"object"==typeof n&&"function"==typeof n.arrayBuffer){const e=await n.arrayBuffer();if(e instanceof ArrayBuffer)return new Uint8Array(e)}if(ArrayBuffer.isView(n)){const e=n;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}throw new e("invalid_input",t.UnsupportedInputType(Object.prototype.toString.call(n)))}(o);i(c);const g=a?.decoder??new m,y=!a?.decoder;let x=!1;const C=()=>{if(y&&!x){x=!0;try{g.free()}catch{}}};try{try{await g.initialize()}catch(n){throw new e("decoder_init_failed",t.DecoderInitFailed(n instanceof Error?n.message:String(n)),{cause:n})}i(c);const n=function(n){if("function"!=typeof n)return;let i,r=!1;return{report:e=>{if(r)return;const t=d(e);if(!(t>=100))try{n(t)}catch(e){i=i??e}},complete:()=>{if(!r){if(r=!0,void 0!==i)throw new e("progress_callback_failed",t.ProgressCallbackThrew(i instanceof Error?i.message:String(i)),{cause:i});(()=>{try{n(100)}catch(n){throw new e("progress_callback_failed",t.ProgressCallbackThrew(n instanceof Error?n.message:String(n)),{cause:n})}})()}}}}(a?.onProgress),o=await g.decode(w,n?n.report:void 0);C(),i(c);const m=void 0!==a?.quality?a.quality:r;let p;try{p=await async function(n,i,r,o,a=!0,s,c=!1){f(i),u(s);const d=i.toLowerCase();if("avif"===d&&!1===await v())throw new e("format_unsupported",t.FormatUnsupported("avif"));const{width:l,height:w,data:m}=n;if(!Number.isInteger(l)||l<=0||!Number.isInteger(w)||w<=0)throw new e("render_encode_failed",t.InvalidDimensions(l,w));const g=l*w*4;if(m.length!==g)throw new e("render_encode_failed",t.DataLengthMismatch(g,l,w,m.length));const p=function(e,t){return t&&"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=8?e:1}(n.orientation,a),y=!(void 0!==n.orientation&&n.orientation>=2&&n.orientation<=8)||a,b=function(e,t,n){switch(e){case 2:return[-1,0,0,1,t,0];case 3:return[-1,0,0,-1,t,n];case 4:return[1,0,0,-1,0,n];case 5:return[0,1,1,0,0,0];case 6:return[0,1,-1,0,n,0];case 7:return[0,-1,-1,0,n,t];case 8:return[0,-1,1,0,0,t];default:return null}}(p,l,w),x=p>=5,C=x?w:l,T=x?l:w,E=s?.x??0,O=s?.y??0,D=s?s.width:C,M=s?s.height:T;if(s&&(E+D>C||O+M>T))throw new e("invalid_crop",t.CropOutOfBounds(E,O,D,M,C,T));const S=function(e,t,n){if(h(n),!n)return{width:e,height:t};const{maxWidth:i,maxHeight:r,scale:o}=n;if(void 0!==o){const n=Math.max(1,Math.round(e*o)),i=Math.max(1,Math.round(t*o));return _(n,i),{width:n,height:i}}if(void 0===i&&void 0===r)return{width:e,height:t};const a=Math.min(void 0!==i?i/e:Number.POSITIVE_INFINITY,void 0!==r?r/t:Number.POSITIVE_INFINITY);if(a>=1)return{width:e,height:t};const s=Math.min(Math.max(1,Math.round(e*a)),void 0!==i?Math.floor(i):Number.POSITIVE_INFINITY),c=Math.min(Math.max(1,Math.round(t*a)),void 0!==r?Math.floor(r):Number.POSITIVE_INFINITY);return _(s,c),{width:s,height:c}}(D,M,o),N=S.width!==D||S.height!==M,j=null!==b||void 0!==s,k=P(S.width,S.height),L=k.getContext("2d");if(!L)throw new e("render_encode_failed",t.ContextUnavailable);if(j||N){const n=P(l,w),i=n.getContext("2d");if(!i)throw new e("render_encode_failed",t.ContextUnavailable);if(U(i,m,l,w),j){const e=S.width/D,t=S.height/M,i=b?b[0]:1,r=b?b[1]:0,o=b?b[2]:0,a=b?b[3]:1,s=b?b[4]:0,c=b?b[5]:0;L.setTransform(i*e,r*t,o*e,a*t,e*(s-E),t*(c-O)),L.drawImage(n,0,0)}else L.drawImage(n,0,0,S.width,S.height);B(n)}else U(L,m,l,w);if("png"===d){const e=await F(k,"image/png");return B(k),A(e,n,c,"png",y)}if("jpeg"===d||"jpg"===d){const e=await F(k,"image/jpeg",r);return B(k),A(e,n,c,"jpeg",y)}if("webp"===d){const e=await F(k,"image/webp",r);return B(k),e}if("avif"===d){const n=await F(k,"image/avif",r);if(B(k),"image/avif"!==n.type)throw new e("format_unsupported",t.FormatUnsupported("avif"));return n}if("svg"===d){const e=await F(k,"image/png");B(k);const t=await I(e),n=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${S.width} ${S.height}" width="${S.width}" height="${S.height}">\n <image width="${S.width}" height="${S.height}" href="`;return new Blob([n,t,'" />\n</svg>'],{type:"image/svg+xml"})}throw new e("invalid_format",t.UnsupportedFormat(String(i)))}(o,s,m,l,a?.applyOrientation??!0,a?.crop,a?.preserveExif??!1)}catch(n){if(n instanceof e)throw n;throw new e("render_encode_failed",t.RenderEncodeFailed(s,n instanceof Error?n.message:String(n)),{cause:n})}return i(c),n?.complete(),async function(e,t){return"dataUrl"===t?await I(e):"arrayBuffer"===t?await e.arrayBuffer():e}(p,a?.output??"blob")}finally{C()}}var M=class{max;idle=[];waiters=[];leasedCount=0;disposed=!1;constructor(e){this.max=Math.max(1,e)}async acquire(){return this.idle.pop()||(this.leasedCount<this.max?(this.leasedCount+=1,new m):new Promise(e=>this.waiters.push(e)))}release(e){if(this.disposed){try{e.free()}catch{}return}if(function(e){return l.has(e)}(e)){this.leasedCount-=1;try{e.free()}catch{}const t=this.waiters.shift();return void(t&&(this.leasedCount+=1,t(new m)))}const t=this.waiters.shift();t?t(e):this.idle.push(e)}dispose(){this.disposed=!0;for(const e of this.idle)try{e.free()}catch{}this.idle.length=0;for(const e of this.waiters.splice(0))e(new m)}};async function S(i,r){if(!Array.isArray(i))throw new e("invalid_input",t.InputsMustBeArray);const d=r?.concurrency??4;o(d),n(r),a(r),p(),await b(r?.to??"jpeg");const{concurrency:f,onProgress:u,continueOnError:h,reuseDecoders:l,...w}=r??{},m=!0===l&&void 0===r?.decoder?new M(s(d,i.length)):null;try{return await c(i,d,async(e,t)=>{const n=m?await m.acquire():null;try{return await D(e,{...w,...n?{decoder:n}:{},onProgress:void 0!==u?e=>u(t,e):void 0})}finally{n&&m.release(n)}},{continueOnError:!0===r?.continueOnError,signal:r?.signal})}finally{m?.dispose()}}export{m as LibheifDecoder,D as convertHeic,T as convertHeicInWorker,S as convertMany,E as convertManyInWorker,O as freeSharedDecoder};
1
+ import{Messages as e,validateConvertOptions as t,throwIfAborted as n,progressGateFor as i,DEFAULT_QUALITY as r,validateConcurrency as o,validateBatchOptions as a,progressCallbackFor as s,runBoundedBatch as c,clampPercent as d,progressCallbackError as f,validateFormat as u,validateCrop as l,validateResize as h}from"./chunk-BTAX2PFV.mjs";export{DEFAULT_QUALITY,SUPPORTED_FORMATS}from"./chunk-BTAX2PFV.mjs";import{HeicConverterError as w}from"./chunk-AROQBV5T.mjs";export{HeicConverterError}from"./chunk-AROQBV5T.mjs";var m=new WeakSet,p=/[\u0000-\u001f\u007f-\u009f]+/g,g=class{options;module=null;decoderInstance=null;initPromise=null;initGeneration=0;constructor(e){this.options=e}async initialize(){if(!this.initPromise){const t=++this.initGeneration,n={};this.options?.moduleOverrides&&Object.assign(n,this.options.moduleOverrides),this.options?.locateFile&&(n.locateFile=this.options.locateFile),this.options?.wasmBinary&&(n.wasmBinary=this.options.wasmBinary);const i=import("./heic-decoder-43VH2M3C.mjs").then(({default:e})=>e(n)).then(n=>{const i=new n.HeicDecoder;if(t!==this.initGeneration)return i.delete(),null;const r=["function"==typeof i.decodeFromPointer?null:"decodeFromPointer","function"==typeof n._malloc?null:"_malloc","function"==typeof n._free?null:"_free",n.HEAPU8 instanceof Uint8Array?null:"HEAPU8"].filter(e=>null!==e);if(r.length>0)throw i.delete(),new w("decoder_init_failed",e.GlueApiMissing(r.join(", ")));return this.module=n,this.decoderInstance=i,n}).catch(e=>{throw this.initPromise===i&&(this.initPromise=null),e});this.initPromise=i}await this.initPromise}async decode(t,n){if(this.module&&this.decoderInstance||await this.initialize(),!this.module||!this.decoderInstance)throw new w("decode_failed",e.DecoderFreedDuringDecode);let i;const r=n?e=>{try{n(d(e))}catch(e){i=i??e}}:null,o=this.module,a=this.decoderInstance,s=o.HEAPU8.buffer;let c;try{const n=t.buffer===s?new Uint8Array(t):t,i=o._malloc(n.byteLength);if(0===i)throw new w("decode_failed",e.DecodeInputAllocFailed(n.byteLength));try{o.HEAPU8.set(n,i),c=a.decodeFromPointer(i,n.byteLength,r)}finally{o._free(i)}}catch(n){if(n instanceof w)throw n;throw m.add(this),new w("decode_failed",e.DecodeFaulted(t.byteLength),{cause:n})}if("string"==typeof c)throw new w("decode_failed",e.DecodeFailedWithDetail(function(e){const t=e.replace(p," ").trim();return t.length>200?`${t.slice(0,197)}...`:t}(c),t.byteLength));if(!c)throw new w("decode_failed",e.DecodeFailed(t.byteLength));if(void 0!==i)throw f(i);const u=c.width,l=c.height,h=c.orientation,g="number"==typeof h&&Number.isInteger(h)&&h>=1&&h<=8?h:1,y=o.HEAPU8.buffer,v={width:u,height:l,data:c.data.buffer!==y?new Uint8ClampedArray(c.data.buffer,c.data.byteOffset,c.data.byteLength):new Uint8ClampedArray(c.data)};g>1&&(v.orientation=g);const b=c.exif;return b instanceof Uint8Array&&b.length>=14&&(v.exif=b.buffer!==y?new Uint8Array(b.buffer,b.byteOffset,b.byteLength):new Uint8Array(b)),v}free(){this.initGeneration+=1,this.decoderInstance&&(this.decoderInstance.delete(),this.decoderInstance=null),this.module=null,m.delete(this),this.initPromise=null}},y=16384;function v(){if("undefined"==typeof OffscreenCanvas&&"undefined"==typeof document)throw new w("unsupported_environment",e.CanvasUnsupported)}var b=null,I=0;function _(){if(null===b){if(Date.now()<I)return Promise.resolve(void 0);const e=async function(){let e;try{e=P(1,1)}catch{return}const t=F(e,"image/avif");let n;const i=new Promise(e=>{n=setTimeout(()=>e("timeout"),5e3)});try{const e=await Promise.race([t,i]);return"timeout"===e?void 0:"image/avif"===e.type&&e.size>0}finally{void 0!==n&&clearTimeout(n),E(e)}}().catch(()=>{});b=e,e.then(t=>{void 0===t&&b===e&&(b=null,I=Date.now()+1e4)})}return b}async function A(t){if(u(t),"avif"===String(t).toLowerCase()&&!1===await _())throw new w("format_unsupported",e.FormatUnsupported("avif"))}function U(t,n){if(!Number.isFinite(t)||!Number.isFinite(n)||t>y||n>y)throw new w("invalid_resize",e.TargetSizeTooLarge(t,n,y))}async function B(t){try{const e=await t.arrayBuffer(),n=new Uint8Array(e);let i="";const r=32768;for(let e=0;e<n.length;e+=r)i+=String.fromCharCode(...n.subarray(e,e+r));const o=btoa(i);return`data:${t.type};base64,${o}`}catch(t){throw new w("render_encode_failed",e.BlobToBase64FailedWithCause(t instanceof Error?t.message:String(t)),{cause:t})}}function F(t,n,i){return"convertToBlob"in t?t.convertToBlob({type:n,quality:i}):new Promise((r,o)=>{t.toBlob(t=>{t?r(t):o(new w("render_encode_failed",e.CanvasToBlobFailed(n)))},n,i)})}function P(t,n){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(t,n);if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=t,e.height=n,e}throw new w("unsupported_environment",e.CanvasUnsupported)}function E(e){const t=e;"function"==typeof t.close?t.close():e.width=0}function T(e,t,n,i){if("undefined"!=typeof ImageData)e.putImageData(new ImageData(t,n,i),0,0);else{const r=e.createImageData(n,i);r.data.set(t),e.putImageData(r,0,0)}}var x=!1;async function O(t,n,i,r,o){const a=n.exif;if(!i||!a||0===a.length)return t;const s=await import("./exif-MBEKII5G.mjs").catch(()=>null);if(!s)return x||(x=!0,console.warn(e.ExifChunkLoadWarning)),t;const{injectExifIntoJpeg:c,injectExifIntoPng:d,normalizeOrientationTag:f}=s,u=o?f(a):a,l=new Uint8Array(await t.arrayBuffer()),h="jpeg"===r?c(l,u):d(l,u);return h===l?t:new Blob([h.buffer],{type:t.type})}function D(){return import("./worker-VA6WQF25.mjs").catch(t=>{const n=t instanceof Error?t.message:String(t);throw new w("worker_load_failed",e.WorkerChunkLoadFailed(n),{cause:t})})}function C(e,t){return D().then(n=>n.convertHeicInWorker(e,t))}function N(e,t){return D().then(n=>n.convertManyInWorker(e,t))}function j(){}function M(e){return!0===e?.nativeDecode&&!0!==e?.preserveExif&&!1!==e?.applyOrientation}var L=!1;async function S(o,a){const s=a?.to??"jpeg";t(a),v(),await A(s);const c=a?.signal;n(c);const d=a,f=await async function(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if("undefined"!=typeof Blob&&t instanceof Blob)return new Uint8Array(await t.arrayBuffer());if(null!==t&&"object"==typeof t&&"function"==typeof t.arrayBuffer){const e=await t.arrayBuffer();if(e instanceof ArrayBuffer)return new Uint8Array(e)}if(ArrayBuffer.isView(t)){const e=t;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}throw new w("invalid_input",e.UnsupportedInputType(Object.prototype.toString.call(t)))}(o);let m,p;n(c);let y,b=!1;if(a?.decoder)m=a.decoder,p=!1;else if(M(a)){try{y=await(import("./native-IGARV2W7.mjs"))}catch(t){I=t instanceof Error?t.message:String(t),L||(L=!0,console.warn(e.NativeChunkLoadWarning(I)))}void 0===y||y.isNativeHeicRefused()?m=new g:(m=new y.NativeHeicDecoder,b=!0),p=!0}else m=new g,p=!0;var I;let x=!1;const D=()=>{if(p&&!x){x=!0;try{m.free()}catch{}}};try{const t=i(a?.onProgress),o=async i=>{try{await i.initialize()}catch(t){throw new w("decoder_init_failed",e.DecoderInitFailed(t instanceof Error?t.message:String(t)),{cause:t})}return n(c),i.decode(f,t?t.report:void 0)};let p;try{p=await o(m)}catch(e){if(!b)throw e;if(e instanceof w&&"aborted"===e.code)throw e;e instanceof w&&"decoder_init_failed"===e.code&&y.markNativeHeicRefused(),n(c),D(),m=new g,x=!1,b=!1,p=await o(m)}D(),n(c);const v=void 0!==a?.quality?a.quality:r;let I;try{I=await async function(t,n,i,r,o=!0,a,s=!1){u(n),l(a);const c=n.toLowerCase();if("avif"===c&&!1===await _())throw new w("format_unsupported",e.FormatUnsupported("avif"));const{width:d,height:f,data:m}=t;if(!Number.isInteger(d)||d<=0||!Number.isInteger(f)||f<=0)throw new w("render_encode_failed",e.InvalidDimensions(d,f));const p=d*f*4;if(m.length!==p)throw new w("render_encode_failed",e.DataLengthMismatch(p,d,f,m.length));const g=function(e,t){return t&&"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=8?e:1}(t.orientation,o),y=!(void 0!==t.orientation&&t.orientation>=2&&t.orientation<=8)||o,v=function(e,t,n){switch(e){case 2:return[-1,0,0,1,t,0];case 3:return[-1,0,0,-1,t,n];case 4:return[1,0,0,-1,0,n];case 5:return[0,1,1,0,0,0];case 6:return[0,1,-1,0,n,0];case 7:return[0,-1,-1,0,n,t];case 8:return[0,-1,1,0,0,t];default:return null}}(g,d,f),b=g>=5,I=b?f:d,A=b?d:f,x=a?.x??0,D=a?.y??0,C=a?a.width:I,N=a?a.height:A;if(a&&(x+C>I||D+N>A))throw new w("invalid_crop",e.CropOutOfBounds(x,D,C,N,I,A));const j=function(e,t,n){if(h(n),!n)return{width:e,height:t};const{maxWidth:i,maxHeight:r,scale:o}=n;if(void 0!==o){const n=Math.max(1,Math.round(e*o)),i=Math.max(1,Math.round(t*o));return U(n,i),{width:n,height:i}}if(void 0===i&&void 0===r)return{width:e,height:t};const a=Math.min(void 0!==i?i/e:Number.POSITIVE_INFINITY,void 0!==r?r/t:Number.POSITIVE_INFINITY);if(a>=1)return{width:e,height:t};const s=Math.min(Math.max(1,Math.round(e*a)),void 0!==i?Math.floor(i):Number.POSITIVE_INFINITY),c=Math.min(Math.max(1,Math.round(t*a)),void 0!==r?Math.floor(r):Number.POSITIVE_INFINITY);return U(s,c),{width:s,height:c}}(C,N,r),M=j.width!==C||j.height!==N,L=null!==v||void 0!==a,S=P(j.width,j.height),k=S.getContext("2d");if(!k)throw new w("render_encode_failed",e.ContextUnavailable);if(L||M){const t=P(d,f),n=t.getContext("2d");if(!n)throw new w("render_encode_failed",e.ContextUnavailable);if(T(n,m,d,f),L){const e=j.width/C,n=j.height/N,i=v?v[0]:1,r=v?v[1]:0,o=v?v[2]:0,a=v?v[3]:1,s=v?v[4]:0,c=v?v[5]:0;k.setTransform(i*e,r*n,o*e,a*n,e*(s-x),n*(c-D)),k.drawImage(t,0,0)}else k.drawImage(t,0,0,j.width,j.height);E(t)}else T(k,m,d,f);if("png"===c){const e=await F(S,"image/png");return E(S),O(e,t,s,"png",y)}if("jpeg"===c||"jpg"===c){const e=await F(S,"image/jpeg",i);return E(S),O(e,t,s,"jpeg",y)}if("webp"===c){const e=await F(S,"image/webp",i);return E(S),e}if("avif"===c){const t=await F(S,"image/avif",i);if(E(S),"image/avif"!==t.type)throw new w("format_unsupported",e.FormatUnsupported("avif"));return t}if("svg"===c){const e=await F(S,"image/png");E(S);const t=await B(e),n=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${j.width} ${j.height}" width="${j.width}" height="${j.height}">\n <image width="${j.width}" height="${j.height}" href="`;return new Blob([n,t,'" />\n</svg>'],{type:"image/svg+xml"})}throw new w("invalid_format",e.UnsupportedFormat(String(n)))}(p,s,v,d,a?.applyOrientation??!0,a?.crop,a?.preserveExif??!1)}catch(t){if(t instanceof w)throw t;throw new w("render_encode_failed",e.RenderEncodeFailed(s,t instanceof Error?t.message:String(t)),{cause:t})}return n(c),t?.complete(),async function(e,t){return"dataUrl"===t?await B(e):"arrayBuffer"===t?await e.arrayBuffer():e}(I,a?.output??"blob")}finally{D()}}var k=class{idle=[];disposed=!1;acquire(){return this.idle.pop()??new g}release(e){if(this.disposed||function(e){return m.has(e)}(e))try{e.free()}catch{}else this.idle.push(e)}dispose(){this.disposed=!0;for(const e of this.idle)try{e.free()}catch{}this.idle.length=0}};async function H(n,i){if(!Array.isArray(n))throw new w("invalid_input",e.InputsMustBeArray);const r=i?.concurrency??4;o(r),t(i),a(i),v(),await A(i?.to??"jpeg");const{concurrency:d,onProgress:f,continueOnError:u,reuseDecoders:l,...h}=i??{},m=s(f),p=!0!==l||void 0!==i?.decoder||M(i)?null:new k;try{return await c(n,r,async(e,t)=>{const n=p?p.acquire():null;try{return await S(e,{...h,...n?{decoder:n}:{},onProgress:m?e=>m(t,e):void 0})}finally{n&&p.release(n)}},{continueOnError:!0===i?.continueOnError,signal:i?.signal})}finally{p?.dispose()}}export{g as LibheifDecoder,S as convertHeic,C as convertHeicInWorker,H as convertMany,N as convertManyInWorker,j as freeSharedDecoder};
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Centralized error message templates used across the library.
3
+ *
4
+ * Static messages are plain strings; dynamic messages are template
5
+ * functions that produce the final string at the call site. Keep all
6
+ * user-facing error strings here (grouped by the file that throws them)
7
+ * instead of inlining new ones.
8
+ *
9
+ * This module holds the strings the eagerly loaded graph throws — anything
10
+ * `src/index.ts`, `src/validate.ts` or the render path touches. `Messages` is
11
+ * one object literal, so an unused entry cannot be tree-shaken out of it:
12
+ * worker-only strings live in `./worker` (`WorkerMessages`) and stay inside the
13
+ * chunk a caller pays for only when they use those APIs. The rule is which
14
+ * *chunk* throws the text, not which API it mentions — `WorkerChunkLoadFailed`
15
+ * is here because `src/index.ts` throws it before the worker chunk exists.
16
+ */
17
+ export declare const Messages: {
18
+ readonly QualityInvalid: (value: unknown) => string;
19
+ readonly BooleanOptionInvalid: (name: string, value: unknown) => string;
20
+ readonly UnsupportedInputType: (type: string) => string;
21
+ readonly DecoderInitFailed: (message: string) => string;
22
+ readonly WorkerChunkLoadFailed: (message: string) => string;
23
+ readonly NativeChunkLoadWarning: (message: string) => string;
24
+ readonly RenderEncodeFailed: (format: string, message: string) => string;
25
+ readonly ConcurrencyInvalid: (value: unknown, max: number) => string;
26
+ readonly InputsMustBeArray: "Inputs must be an array of HEIC images";
27
+ readonly OutputShapeInvalid: (value: unknown) => string;
28
+ readonly SignalInvalid: (value: unknown) => string;
29
+ readonly Aborted: "Conversion aborted (AbortSignal was aborted)";
30
+ readonly ConvertManyItemFailed: (index: number, total: number, message: string) => string;
31
+ /** The settled-completion tail: an entry the race recorded as ok yet carries no result. */
32
+ readonly BatchItemProducedNoResult: (index: number, total: number) => string;
33
+ /** The unreachable tail: the race settled with nothing to show for it. Names no
34
+ * item, because there is no failing item to name. */
35
+ readonly BatchEndedWithoutSettling: (total: number) => string;
36
+ readonly ConvertManyExtraFailures: (failedCount: number, total: number) => string;
37
+ readonly ConvertManyOtherErrors: (messages: string[]) => string;
38
+ readonly ExifChunkLoadWarning: string;
39
+ readonly ScaleInvalid: (value: unknown) => string;
40
+ readonly MaxWidthInvalid: (value: unknown) => string;
41
+ readonly MaxHeightInvalid: (value: unknown) => string;
42
+ readonly TargetSizeTooLarge: (width: number, height: number, max: number) => string;
43
+ readonly BlobToBase64FailedWithCause: (message: string) => string;
44
+ readonly CanvasToBlobFailed: (type: string) => string;
45
+ readonly CanvasUnsupported: string;
46
+ readonly InvalidDimensions: (width: number, height: number) => string;
47
+ readonly DataLengthMismatch: (expected: number, width: number, height: number, actual: number) => string;
48
+ readonly ContextUnavailable: "Failed to acquire 2D rendering context from canvas";
49
+ readonly UnsupportedFormat: (format: string) => string;
50
+ readonly FormatUnsupported: (format: string) => string;
51
+ readonly CropInvalid: (field: string, value: unknown) => string;
52
+ readonly CropOutOfBounds: (x: number, y: number, width: number, height: number, displayWidth: number, displayHeight: number) => string;
53
+ readonly GlueApiMissing: (missing: string) => string;
54
+ readonly DecoderFreedDuringDecode: "Decoder was freed before decoding completed; call initialize() again.";
55
+ readonly DecodeInputAllocFailed: (bytes: number) => string;
56
+ readonly DecodeFailed: (bytes: number) => string;
57
+ readonly DecodeFailedWithDetail: (detail: string, bytes: number) => string;
58
+ readonly DecodeFaulted: (bytes: number) => string;
59
+ readonly ProgressCallbackThrew: (message: string) => string;
60
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Error strings thrown from `src/worker.ts`, which is the lazily loaded worker
3
+ * chunk. Add a string here when the *chunk* throws it — not when the API is
4
+ * worker-related: text that `src/index.ts` or `src/validate.ts` can reach must
5
+ * go to `./core`, or the eager bundle grows, because an object literal cannot
6
+ * be tree-shaken per property.
7
+ */
8
+ export declare const WorkerMessages: {
9
+ readonly WorkerUnsupported: "Web Worker is not supported in the current environment";
10
+ readonly WorkerCreateFailed: (message: string) => string;
11
+ readonly WorkerPostFailed: (message: string) => string;
12
+ readonly WorkerConversionFailed: "Worker conversion failed";
13
+ readonly WorkerDecoderUnsupported: string;
14
+ readonly WorkerFailed: (workerUrl?: string | URL) => string;
15
+ readonly WorkerTimeout: (timeoutMs: number, stats: {
16
+ progressMessages: number;
17
+ lastPercent?: number;
18
+ unknownType?: string;
19
+ /** Replies ignored for not echoing the request id (duplicates or late replies). */
20
+ staleResults?: number;
21
+ /** Progress messages ignored for not echoing the request id. */
22
+ staleProgress?: number;
23
+ /** The lease came from the pool rather than a fresh boot. */
24
+ adopted?: boolean;
25
+ workerUrl?: string | URL;
26
+ /** Required, not optional: the caller knows whether a slot was granted, and
27
+ * guessing from an omitted field would decide the diagnosis for it. */
28
+ startedAt: number | undefined;
29
+ queueWaitMs?: number;
30
+ }) => string;
31
+ readonly MaxConcurrentWorkersInvalid: (value: unknown, max: number) => string;
32
+ readonly TimeoutInvalid: (value: unknown) => string;
33
+ };
@@ -0,0 +1 @@
1
+ import{HeicConverterError as e}from"./chunk-AROQBV5T.mjs";var i=16384,t=67108864,n=!1,a=!1;function d(){return n}function o(){n=!0,a||(a=!0,console.warn("@keeratita/heic-converter: native HEIC decoding is unavailable in this environment — nativeDecode conversions will use the bundled decoder on this page."))}function r(){n=!1,a=!1}var h=class{async initialize(){if("function"!=typeof createImageBitmap||"undefined"==typeof OffscreenCanvas)throw new e("decoder_init_failed","Native HEIC decoding is unavailable in this environment.")}async decode(n){const a="undefined"!=typeof SharedArrayBuffer&&n.buffer instanceof SharedArrayBuffer?new Uint8Array(n):n,d=await createImageBitmap(new Blob([a],{type:"image/heic"}),{imageOrientation:"from-image"});try{if(d.width>i||d.height>i)throw new e("decode_failed",`Native HEIC decoding is limited to 16384px per side, got ${d.width}x${d.height}.`);if(d.width*d.height>t)throw new e("decode_failed",`Native HEIC decoding is limited to 64MP total, got ${d.width}x${d.height} (${d.width*d.height} pixels).`);const n=new OffscreenCanvas(d.width,d.height).getContext("2d",{willReadFrequently:!0});if(!n)throw new e("decode_failed","Could not acquire a 2D context for native HEIC pixel readback.");n.drawImage(d,0,0);const a=n.getImageData(0,0,d.width,d.height);return{width:a.width,height:a.height,data:a.data}}finally{d.close?.()}}free(){}};export{i as MAX_NATIVE_DECODE_DIMENSION,t as MAX_NATIVE_DECODE_PIXELS,h as NativeHeicDecoder,r as __resetNativeHeicProbe,d as isNativeHeicRefused,o as markNativeHeicRefused};
@@ -0,0 +1 @@
1
+ var e=require("./chunk-N2LCVW2Q.js"),i=16384,t=67108864,r=!1,n=!1;exports.MAX_NATIVE_DECODE_DIMENSION=i,exports.MAX_NATIVE_DECODE_PIXELS=t,exports.NativeHeicDecoder=class{async initialize(){if("function"!=typeof createImageBitmap||"undefined"==typeof OffscreenCanvas)throw new e.HeicConverterError("decoder_init_failed","Native HEIC decoding is unavailable in this environment.")}async decode(r){const n="undefined"!=typeof SharedArrayBuffer&&r.buffer instanceof SharedArrayBuffer?new Uint8Array(r):r,a=await createImageBitmap(new Blob([n],{type:"image/heic"}),{imageOrientation:"from-image"});try{if(a.width>i||a.height>i)throw new e.HeicConverterError("decode_failed",`Native HEIC decoding is limited to 16384px per side, got ${a.width}x${a.height}.`);if(a.width*a.height>t)throw new e.HeicConverterError("decode_failed",`Native HEIC decoding is limited to 64MP total, got ${a.width}x${a.height} (${a.width*a.height} pixels).`);const r=new OffscreenCanvas(a.width,a.height).getContext("2d",{willReadFrequently:!0});if(!r)throw new e.HeicConverterError("decode_failed","Could not acquire a 2D context for native HEIC pixel readback.");r.drawImage(a,0,0);const n=r.getImageData(0,0,a.width,a.height);return{width:n.width,height:n.height,data:n.data}}finally{a.close?.()}}free(){}},exports.__resetNativeHeicProbe=function(){r=!1,n=!1},exports.isNativeHeicRefused=function(){return r},exports.markNativeHeicRefused=function(){r=!0,n||(n=!0,console.warn("@keeratita/heic-converter: native HEIC decoding is unavailable in this environment — nativeDecode conversions will use the bundled decoder on this page."))};
@@ -0,0 +1,39 @@
1
+ import { HeicConverterError } from './errors';
2
+ /**
3
+ * Shared progress-value helpers. The public onProgress contract — "a number
4
+ * clamped to 0-100, the final 100% withheld until success, a throwing host
5
+ * callback surfaced as `progress_callback_failed`" — lives here as one
6
+ * implementation so the in-process path (`convertHeic`) and the worker
7
+ * transport cannot drift: each stage funnels host-visible percentages through
8
+ * `clampPercent`/`createProgressGate` and decides only *when* to surface a
9
+ * recorded host failure (in-process defers it to completion; the worker
10
+ * rejects on the spot and terminates).
11
+ */
12
+ /** Coerce an arbitrary value to the documented 0-100 progress range. */
13
+ export declare function clampPercent(value: unknown): number;
14
+ /** The one construction of the `progress_callback_failed` contract error. */
15
+ export declare function progressCallbackError(error: unknown): HeicConverterError;
16
+ /**
17
+ * The host callback when it is callable, `undefined` when it is effectively
18
+ * absent. Everything non-function — truthy or not — counts as absent, so a
19
+ * malformed `onProgress` is silently ignored rather than TypeErroring later.
20
+ * One decision for all entry points and the worker transport.
21
+ */
22
+ export declare function progressCallbackFor<A extends unknown[]>(value: ((...args: A) => void) | undefined): ((...args: A) => void) | undefined;
23
+ /**
24
+ * Build the gate for a host callback, or return undefined when it is
25
+ * effectively absent. Anything non-function counts as absent — the decision
26
+ * lives here once so the entry points and the worker transport cannot drift
27
+ * on what a malformed `onProgress` means (silently ignored, not TypeErrors
28
+ * surfacing as `progress_callback_failed`).
29
+ */
30
+ export declare function progressGateFor(onProgress: ((percent: number) => void) | undefined): ProgressGate | undefined;
31
+ export interface ProgressGate {
32
+ /** Forward a clamped sub-100 percentage; a host throw is recorded, never rethrown here. */
33
+ report(percent: number): void;
34
+ /** Emit the withheld 100%, or throw the recorded host failure. Idempotent. */
35
+ complete(): void;
36
+ /** The recorded host failure, if the callback has thrown so far. */
37
+ pendingError(): HeicConverterError | undefined;
38
+ }
39
+ export declare function createProgressGate(onProgress: (percent: number) => void): ProgressGate;
@@ -0,0 +1,71 @@
1
+ import type { CropOptions, DecodedImage, ImageFormat, ResizeOptions } from '../types';
2
+ /**
3
+ * Maximum supported canvas dimension per side (browsers cap around this):
4
+ * turns absurd scale factors into a clear error instead of an allocation
5
+ * failure. The WASM wrapper (main.cpp) and the native Strategy apply the same
6
+ * cap before allocating — keep them in sync.
7
+ */
8
+ export declare const MAX_CANVAS_DIMENSION = 16384;
9
+ /**
10
+ * Cheap probe for canvas support, safe to call before an expensive decode.
11
+ * Throws (unwrapped, with an actionable message) in environments with
12
+ * neither OffscreenCanvas nor HTMLCanvasElement — notably plain Node.js,
13
+ * where encoding is unsupported even though decoding works.
14
+ */
15
+ export declare function assertEncodeEnvironment(): void;
16
+ /**
17
+ * Environment probe: some browsers cannot encode AVIF via canvas (e.g.
18
+ * Safari), and per spec `toBlob` silently falls back to PNG — trusting the
19
+ * requested type would emit a PNG under an AVIF label. Probed once. `false`
20
+ * is a definitive refusal (the only verdict that may produce
21
+ * `format_unsupported`); `undefined` is indeterminate (wedged `toBlob`,
22
+ * throwing canvas under memory pressure) — callers proceed and let the
23
+ * encode-time `blob.type` check decide.
24
+ */
25
+ type AvifSupport = boolean | undefined;
26
+ /** How long the probe's toBlob may take before the attempt is deemed indeterminate. Exported so tests control the window. */
27
+ export declare const AVIF_PROBE_TIMEOUT_MS = 5000;
28
+ /**
29
+ * An indeterminate verdict is never cached as truth, but re-probing per call
30
+ * would make a starved host pay the full timeout each time. The latest "don't
31
+ * know" is honoured for this cooldown. Exported so tests advance past it, not
32
+ * around it.
33
+ */
34
+ export declare const AVIF_INDETERMINATE_COOLDOWN_MS = 10000;
35
+ export declare function canEncodeAvif(): Promise<AvifSupport>;
36
+ /**
37
+ * Up-front capability gate for the chosen output format, safe to call before
38
+ * an expensive decode. Only a definitive `false` rejects here; indeterminate
39
+ * defers to the encode-time `blob.type` re-check in `renderAndEncode`.
40
+ */
41
+ export declare function assertEncodeCapability(format: ImageFormat): Promise<void>;
42
+ /** @internal Reset the cached AVIF capability probe (tests only). */
43
+ export declare function __resetAvifProbe(): void;
44
+ /** @internal Re-arm the one-shot EXIF-chunk warning (tests only). */
45
+ export declare function __resetExifChunkWarning(): void;
46
+ /**
47
+ * Computes the target dimensions for the given resize options.
48
+ * `scale` takes precedence over `maxWidth`/`maxHeight`; the latter only
49
+ * downscale (never upscale) while preserving the aspect ratio.
50
+ */
51
+ export declare function computeTargetSize(width: number, height: number, resize?: ResizeOptions): {
52
+ width: number;
53
+ height: number;
54
+ };
55
+ /**
56
+ * Converts a Blob to a base64 data URL (`blob.arrayBuffer()` + `btoa`; both
57
+ * present on every host that reaches the render stage). Encoding failure is a
58
+ * `render_encode_failed`.
59
+ */
60
+ export declare function blobToBase64(blob: Blob): Promise<string>;
61
+ /**
62
+ * Encodes a canvas via the encoder it exposes: `convertToBlob` for an
63
+ * OffscreenCanvas, `toBlob` for an HTMLCanvasElement. A null blob from the
64
+ * latter is a `render_encode_failed`.
65
+ */
66
+ export declare function canvasToBlob(canvas: HTMLCanvasElement | OffscreenCanvas, type: string, quality?: number): Promise<Blob>;
67
+ /**
68
+ * Renders DecodedImage pixel data onto a canvas and encodes it into the target format.
69
+ */
70
+ export declare function renderAndEncode(decoded: DecodedImage, format: ImageFormat, quality: number, resize?: ResizeOptions, applyOrientation?: boolean, crop?: CropOptions, preserveExif?: boolean): Promise<Blob>;
71
+ export {};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Post-encode EXIF re-injection for JPEG (APP1 segment) and PNG (eXIf chunk).
3
+ *
4
+ * Canvas encoding drops all source metadata; when `preserveExif: true` these
5
+ * helpers splice the decoded `DecodedImage.exif` block back into the encoded
6
+ * bytes. Both injectors are fail-safe by design: any surprise while parsing
7
+ * the encoded output (or a malformed EXIF block) returns the original bytes
8
+ * untouched — losing metadata is always preferable to emitting a corrupt
9
+ * image.
10
+ */
11
+ /**
12
+ * Rewrite the TIFF orientation tag (274) in a `"Exif\0\0" + TIFF` block to
13
+ * `1` (normal) and return a modified copy. Needed because the converted
14
+ * raster is already upright — the EXIF/orientation transform was applied at
15
+ * render (or by libheif for `irot`/`imir` files) — so carrying the source
16
+ * tag verbatim would tell EXIF-respecting consumers to rotate the image a
17
+ * second time. Fail-safe: anything malformed returns the block untouched,
18
+ * and the input array is never mutated.
19
+ */
20
+ export declare function normalizeOrientationTag(block: Uint8Array): Uint8Array;
21
+ /**
22
+ * Insert the EXIF block as a JPEG APP1 segment, positioned after SOI and any
23
+ * leading APPn/COM segments (the conventional slot right after the JFIF
24
+ * APP0). Returns the original bytes unchanged when the JPEG does not parse,
25
+ * the block is malformed, or the block exceeds the 16-bit segment length
26
+ * field (EXIF payloads >64 KB are rare in HEIC items and splitting across
27
+ * multiple APP1 segments is out of scope).
28
+ */
29
+ export declare function injectExifIntoJpeg(jpeg: Uint8Array, exifBlock: Uint8Array): Uint8Array;
30
+ /**
31
+ * Insert the EXIF TIFF structure as a PNG `eXIf` chunk (PNG Extensions
32
+ * registry: chunk data is the raw TIFF without the "Exif\0\0" JPEG marker).
33
+ * Positioned after IHDR and before the first IDAT (or IEND when there is no
34
+ * IDAT); an existing eXIf chunk wins untouched. Fail-safe: unparsable PNG
35
+ * input is returned unchanged.
36
+ */
37
+ export declare function injectExifIntoPng(png: Uint8Array, exifBlock: Uint8Array): Uint8Array;
@@ -0,0 +1,257 @@
1
+ export interface DecodedImage {
2
+ width: number;
3
+ height: number;
4
+ /**
5
+ * RGBA pixel data, interleaved, row-major, 4 bytes per pixel.
6
+ *
7
+ * The buffer is always a plain `ArrayBuffer` owned by the returned array
8
+ * (never a view into the WASM heap), so it stays valid after
9
+ * `LibheifDecoder.free()` and can be passed directly to
10
+ * `new ImageData(...)` / `putImageData` — including the `ImageData`
11
+ * overload that requires `Uint8ClampedArray<ArrayBuffer>` under TS >= 5.7.
12
+ */
13
+ data: Uint8ClampedArray;
14
+ /**
15
+ * Raw EXIF block copied from the source file, normalized to the JPEG APP1
16
+ * payload form: `"Exif\0\0"` followed by the TIFF structure. Present when
17
+ * the file carries an Exif item — including files where libheif already
18
+ * applied `irot`/`imir` (the block is reported independently of
19
+ * {@link DecodedImage.orientation}).
20
+ *
21
+ * `convertHeic` re-injects this block into JPEG (APP1) and PNG (`eXIf`)
22
+ * output when `preserveExif: true`; raw-decode consumers can attach it to
23
+ * their own encoder output (e.g. `sharp`'s `.withMetadata({ exif })`).
24
+ * Owned by the returned object; never a WASM-heap view.
25
+ */
26
+ exif?: Uint8Array;
27
+ /**
28
+ * EXIF orientation of the **stored** pixels (1–8, EXIF tag 274 semantics;
29
+ * 1 = upright). Absent or 1 means no rotation is pending.
30
+ *
31
+ * libheif already applies `irot`/`imir` container transforms during
32
+ * decode — for those files this is 1 and the pixels are upright. A value
33
+ * > 1 means the orientation comes only from the Exif item: `convertHeic`
34
+ * applies it automatically (unless `applyOrientation: false`), while raw
35
+ * `decode()` consumers get stored pixels and must apply it themselves.
36
+ * Decoders that do not report orientation may omit this field.
37
+ */
38
+ orientation?: number;
39
+ }
40
+ /**
41
+ * Decoder contract used by {@link ConvertOptions.decoder} /
42
+ * {@link ConvertManyOptions.decoder} and implemented by `LibheifDecoder`.
43
+ *
44
+ * Lifecycle rules followed by the library (implementations may rely on them):
45
+ * - `initialize()` is called before every `decode()`; implementations must
46
+ * make repeated/concurrent calls cheap (e.g. memoize the load promise).
47
+ * - `decode()` is awaited before the library calls `free()`; the returned
48
+ * `DecodedImage` must therefore not reference decoder-owned memory that
49
+ * `free()` releases (copy pixels out, as `LibheifDecoder` does).
50
+ * - `free()` is called at most once per conversion. Decoders **injected** via
51
+ * options are never freed by the library — the caller owns their lifetime.
52
+ *
53
+ * Concurrency: with `convertMany`, a single injected decoder is shared by
54
+ * all concurrent conversions, so `decode()` must be safe to call concurrently
55
+ * on one instance (no shared mutable state across in-flight decodes).
56
+ */
57
+ export interface IHeicDecoder {
58
+ /**
59
+ * Initializes the decoder (e.g., loading WebAssembly module).
60
+ */
61
+ initialize(): Promise<void>;
62
+ /**
63
+ * Decodes HEIC binary data into raw RGBA pixel data.
64
+ * @param data The HEIC file as a Uint8Array.
65
+ * @param onProgress Optional progress callback that receives the progress percentage.
66
+ */
67
+ decode(data: Uint8Array, onProgress?: (percent: number) => void): Promise<DecodedImage>;
68
+ /**
69
+ * Cleans up allocated resources. Idempotent: safe to call multiple times.
70
+ */
71
+ free(): void;
72
+ }
73
+ export type ImageFormat = 'jpeg' | 'jpg' | 'png' | 'svg' | 'webp' | 'avif';
74
+ /**
75
+ * Formats accepted by {@link ConvertOptions.to} (case-insensitive).
76
+ * `'jpg'` is an alias of `'jpeg'`. `'avif'` requires an environment whose
77
+ * canvas can encode AVIF (Chromium/Firefox today); elsewhere it rejects with
78
+ * `format_unsupported`.
79
+ */
80
+ export declare const SUPPORTED_FORMATS: readonly ImageFormat[];
81
+ /** Default JPEG/WebP encoding quality used when `quality` is not provided. */
82
+ export declare const DEFAULT_QUALITY = 0.92;
83
+ /**
84
+ * Accepted input for every convert entry point. `ArrayBufferView` is a
85
+ * declared (tested) surface: DataView and non-Uint8 typed arrays are read as
86
+ * raw bytes (byteOffset/byteLength), including SharedArrayBuffer-backed
87
+ * views. Cross-realm Blob-likes (anything exposing `arrayBuffer()`, e.g. a
88
+ * Blob from another frame) are accepted at runtime even though `instanceof
89
+ * Blob` cannot see them.
90
+ */
91
+ export type HeicInput = Blob | ArrayBuffer | ArrayBufferView;
92
+ /**
93
+ * How {@link convertHeic} returns the converted image.
94
+ * - `'blob'` — a `Blob` (the default; browser-native, works everywhere)
95
+ * - `'dataUrl'` — a `data:image/...;base64,…` string (previews, `<img src>`)
96
+ * - `'arrayBuffer'` — raw bytes (uploads, WebCodecs, Node-friendly transfer)
97
+ */
98
+ export type OutputShape = 'blob' | 'dataUrl' | 'arrayBuffer';
99
+ /** Resolved return type of `convertHeic`/`convertMany` for an output shape. */
100
+ export type ConvertResult<S extends OutputShape> = S extends 'dataUrl' ? string : S extends 'arrayBuffer' ? ArrayBuffer : Blob;
101
+ /** Crop rectangle in **post-orientation display pixels** (top-left origin). */
102
+ export interface CropOptions {
103
+ /** Left edge of the crop box. @default 0 */
104
+ x?: number;
105
+ /** Top edge of the crop box. @default 0 */
106
+ y?: number;
107
+ /** Crop width in pixels. Must be a positive integer and fit inside the image. */
108
+ width: number;
109
+ /** Crop height in pixels. Must be a positive integer and fit inside the image. */
110
+ height: number;
111
+ }
112
+ /** Per-item outcome when `continueOnError: true`. */
113
+ export type ConvertItemResult<T = Blob> = {
114
+ index: number;
115
+ ok: true;
116
+ result: T;
117
+ } | {
118
+ index: number;
119
+ ok: false;
120
+ error: Error;
121
+ };
122
+ export interface ResizeOptions {
123
+ /**
124
+ * Maximum width in pixels. The image is downscaled to fit within this
125
+ * bound while preserving the aspect ratio. Images smaller than the bound
126
+ * are never upscaled.
127
+ */
128
+ maxWidth?: number;
129
+ /**
130
+ * Maximum height in pixels. The image is downscaled to fit within this
131
+ * bound while preserving the aspect ratio. Images smaller than the bound
132
+ * are never upscaled.
133
+ */
134
+ maxHeight?: number;
135
+ /**
136
+ * Uniform scale factor applied to both dimensions (e.g. 0.5 halves the
137
+ * image). Takes precedence over `maxWidth` and `maxHeight` when set.
138
+ */
139
+ scale?: number;
140
+ }
141
+ export interface ConvertOptions extends ResizeOptions {
142
+ /**
143
+ * Target format for the conversion. Must be one of the values in
144
+ * {@link SUPPORTED_FORMATS}; an unknown value is rejected up front,
145
+ * before the input is decoded.
146
+ * @default 'jpeg'
147
+ */
148
+ to?: ImageFormat;
149
+ /**
150
+ * Quality of the converted image, between 0.0 and 1.0 (inclusive).
151
+ * Applicable for 'jpeg', 'jpg', 'webp', and 'avif' formats — but validated
152
+ * for every format: passing an out-of-range value (e.g. `90` from a 0-100
153
+ * scale) throws regardless of `to`.
154
+ * @default 0.92
155
+ */
156
+ quality?: number;
157
+ /**
158
+ * Optional custom decoder implementation to inject.
159
+ * If not provided, a default LibheifDecoder is used.
160
+ * The library never calls `free()` on an injected decoder.
161
+ */
162
+ decoder?: IHeicDecoder;
163
+ /**
164
+ * Optional progress callback that receives the progress percentage during
165
+ * decoding. Values are normalized and clamped to the range 0 to 100; the
166
+ * final 100% is emitted only when the conversion succeeds. A callback that
167
+ * throws rejects the conversion with `progress_callback_failed`.
168
+ */
169
+ onProgress?: (percent: number) => void;
170
+ /**
171
+ * Rotate/flip the output so it matches the source's EXIF orientation
172
+ * (applied as a canvas transform during rendering; `irot`/`imir` container
173
+ * transforms are already applied by the decoder and never stacked on top).
174
+ * Set `false` to keep the exact stored-pixel geometry. A non-boolean value
175
+ * is rejected up front with `invalid_input`.
176
+ * @default true
177
+ */
178
+ applyOrientation?: boolean;
179
+ /**
180
+ * Representation of the converted image. See {@link OutputShape}.
181
+ * @default 'blob'
182
+ */
183
+ output?: OutputShape;
184
+ /**
185
+ * AbortSignal that cancels the conversion. Cancellation is checked at
186
+ * stage boundaries (input read, decoder init, before/after decode,
187
+ * before encode) and aborts `convertHeicInWorker` calls immediately by
188
+ * terminating the worker; the synchronous WASM decode itself cannot be
189
+ * preempted mid-call. An aborted signal rejects with code `aborted`.
190
+ */
191
+ signal?: AbortSignal;
192
+ /**
193
+ * Crop rectangle in post-orientation display pixels (the geometry the
194
+ * image will be displayed in). Applied before resize: `scale`/`maxWidth`/
195
+ * `maxHeight` then downscale the cropped region. Out-of-bounds crops
196
+ * reject with `invalid_crop`.
197
+ */
198
+ crop?: CropOptions;
199
+ /**
200
+ * Copy the source HEIC's EXIF block into JPEG (APP1) and PNG (`eXIf`
201
+ * chunk) output so converted files keep camera metadata (orientation,
202
+ * GPS, timestamps). Note this **preserves private data** like GPS — set
203
+ * deliberately. Ignored for `webp`/`svg` output.
204
+ * @default false
205
+ */
206
+ preserveExif?: boolean;
207
+ /**
208
+ * Decode with the platform's native HEIC stack (`createImageBitmap` on
209
+ * Safari/iOS, Edge, Windows) instead of the bundled libheif WASM decoder,
210
+ * skipping its ~300 KB payload. Hosts without native HEIC support fall
211
+ * back to libheif on the same conversion; the refusal is cached per realm.
212
+ *
213
+ * Ignored (libheif used) with an injected `decoder`, `preserveExif: true`
214
+ * or `applyOrientation: false`. Native output is upright and progress
215
+ * fires only at completion (tile progress is a libheif feature).
216
+ * @default false
217
+ */
218
+ nativeDecode?: boolean;
219
+ }
220
+ export interface ConvertManyOptions extends Omit<ConvertOptions, 'onProgress'> {
221
+ /**
222
+ * Maximum number of conversions running concurrently.
223
+ * @default 4
224
+ */
225
+ concurrency?: number;
226
+ /**
227
+ * Optional progress callback that receives the item index (0-based) and
228
+ * its progress percentage (normalized to 0 to 100) during decoding.
229
+ */
230
+ onProgress?: (index: number, percent: number) => void;
231
+ /**
232
+ * Optional custom decoder implementation to inject. When provided, the
233
+ * same instance is shared by all concurrent conversions, so it must be
234
+ * safe for concurrent `decode()` calls (see {@link IHeicDecoder}). If not
235
+ * provided, a fresh default LibheifDecoder is created per item.
236
+ */
237
+ decoder?: IHeicDecoder;
238
+ /**
239
+ * Resolve with per-item results instead of rejecting the whole batch on
240
+ * the first failure: the promise fulfills with `ConvertItemResult[]` in
241
+ * input order, each item `{ index, ok: true, result }` or
242
+ * `{ index, ok: false, error }`. All items always run to completion.
243
+ * Up-front option validation failures still reject normally (a typo is a
244
+ * caller bug, not an item failure).
245
+ * @default false
246
+ */
247
+ continueOnError?: boolean;
248
+ /**
249
+ * Reuse one library-owned `LibheifDecoder` per concurrent runner across
250
+ * items instead of creating (and WASM-initializing) a fresh instance per
251
+ * item — amortizes the module load in large batches while preserving the
252
+ * exclusive-use invariant (an instance is only ever held by one runner,
253
+ * never decodes concurrently). Ignored when `decoder` is injected.
254
+ * @default false
255
+ */
256
+ reuseDecoders?: boolean;
257
+ }
@@ -0,0 +1,59 @@
1
+ import type { CropOptions, ImageFormat, ResizeOptions } from './types';
2
+ /**
3
+ * Option validators shared by `index.ts` (convertHeic/convertMany) and
4
+ * `worker.ts` (the *InWorker APIs perform the same up-front checks so a
5
+ * typo surfaces its own error code on the main thread instead of coming
6
+ * back stringified as worker_failed). Lives in its own module to keep
7
+ * index ↔ worker import-free; the render layer imports these too for its
8
+ * internal re-checks, so validation lives in exactly one place.
9
+ */
10
+ /**
11
+ * Upper bound for `concurrency` / `maxConcurrentWorkers`. Every unit of
12
+ * concurrency is a full WASM boot (its own instantiated module and grown
13
+ * heap), so a runaway config value — a query param, a queue-size setting —
14
+ * would otherwise boot hundreds of decoders and take the page down. The
15
+ * default paths clamp to 8; explicit values may reach this ceiling.
16
+ */
17
+ export declare const MAX_BATCH_CONCURRENCY = 64;
18
+ /** Validates every per-conversion option shared by all four entry points. */
19
+ export declare function validateConvertOptions(options?: {
20
+ to?: ImageFormat;
21
+ quality?: number;
22
+ applyOrientation?: boolean;
23
+ output?: unknown;
24
+ signal?: AbortSignal;
25
+ crop?: CropOptions;
26
+ preserveExif?: boolean;
27
+ nativeDecode?: boolean;
28
+ maxWidth?: number;
29
+ maxHeight?: number;
30
+ scale?: number;
31
+ }): void;
32
+ /**
33
+ * Validates the batch knobs shared by both batch entry points (convertMany
34
+ * and convertManyInWorker both call this). The worker-only knobs
35
+ * (`maxConcurrentWorkers`, `timeoutMs`) are validated in `src/worker.ts`, so
36
+ * their message text stays in the lazy worker chunk.
37
+ */
38
+ export declare function validateBatchOptions(options?: {
39
+ continueOnError?: boolean;
40
+ reuseDecoders?: boolean;
41
+ }): void;
42
+ /** @throws `invalid_concurrency` for a `concurrency` outside 1..MAX_BATCH_CONCURRENCY. */
43
+ export declare function validateConcurrency(concurrency: number): void;
44
+ /** Boundary check for cooperative cancellation (sync WASM decode cannot be preempted). */
45
+ export declare function throwIfAborted(signal?: AbortSignal): void;
46
+ /**
47
+ * Validates that a requested output format is supported (case-insensitive).
48
+ */
49
+ export declare function validateFormat(format: ImageFormat): void;
50
+ /**
51
+ * Validates resize options. Throws if any value is not a positive finite number.
52
+ */
53
+ export declare function validateResize(resize?: ResizeOptions): void;
54
+ /**
55
+ * Validates the crop rectangle *shape* (integer, positive, non-negative).
56
+ * Range checking against the image size happens in `renderAndEncode`, once
57
+ * the post-orientation display dimensions are known.
58
+ */
59
+ export declare function validateCrop(crop?: CropOptions): void;
@@ -0,0 +1,3 @@
1
+ export declare function markFaulted(decoder: object): void;
2
+ export declare function clearFaulted(decoder: object): void;
3
+ export declare function isDecoderPoisoned(decoder: object): boolean;
@@ -0,0 +1 @@
1
+ export * from './wrapper';