@embedpdf/engines 1.0.21 → 1.0.23

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.
Files changed (34) hide show
  1. package/dist/{engine-D0zKoYug.js → engine-DSdvr8ah.js} +233 -166
  2. package/dist/engine-DSdvr8ah.js.map +1 -0
  3. package/dist/engine-RdqkJxAO.cjs +2 -0
  4. package/dist/engine-RdqkJxAO.cjs.map +1 -0
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.js +3 -2
  8. package/dist/lib/converters/index.cjs +1 -1
  9. package/dist/lib/converters/index.cjs.map +1 -1
  10. package/dist/lib/converters/index.d.ts +4 -14
  11. package/dist/lib/converters/index.js +16 -19
  12. package/dist/lib/converters/index.js.map +1 -1
  13. package/dist/lib/converters/types.d.ts +9 -0
  14. package/dist/lib/pdfium/engine.d.ts +8 -21
  15. package/dist/lib/pdfium/index.cjs +1 -1
  16. package/dist/lib/pdfium/index.js +3 -2
  17. package/dist/lib/pdfium/web/direct-engine.cjs +1 -1
  18. package/dist/lib/pdfium/web/direct-engine.js +1 -1
  19. package/dist/lib/pdfium/web/worker-engine.cjs +1 -1
  20. package/dist/lib/pdfium/web/worker-engine.js +1 -1
  21. package/dist/preact/index.cjs +1 -1
  22. package/dist/preact/index.js +1 -1
  23. package/dist/react/index.cjs +1 -1
  24. package/dist/react/index.js +1 -1
  25. package/dist/{runner-CGyvdr9V.js → runner-CjYO-wR5.js} +2 -2
  26. package/dist/{runner-CGyvdr9V.js.map → runner-CjYO-wR5.js.map} +1 -1
  27. package/dist/{runner-CHOggH0O.cjs → runner-DoKDIKUP.cjs} +2 -2
  28. package/dist/{runner-CHOggH0O.cjs.map → runner-DoKDIKUP.cjs.map} +1 -1
  29. package/dist/vue/index.cjs +1 -1
  30. package/dist/vue/index.js +1 -1
  31. package/package.json +3 -3
  32. package/dist/engine-D0zKoYug.js.map +0 -1
  33. package/dist/engine-Dcn6oo4j.cjs +0 -2
  34. package/dist/engine-Dcn6oo4j.cjs.map +0 -1
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("@embedpdf/models");function t(e,t,o,i=100){let n=e.wasmExports.malloc(i);for(let d=0;d<i;d++)e.HEAP8[n+d]=0;const r=t(n,i);let s;if(r>i){e.wasmExports.free(n),n=e.wasmExports.malloc(r);for(let t=0;t<r;t++)e.HEAP8[n+t]=0;t(n,r),s=o(n)}else s=o(n);return e.wasmExports.free(n),s}function o(e,t){const o=t(0,0),i=e.wasmExports.malloc(o);t(i,o);const n=new ArrayBuffer(o),r=new DataView(n);for(let s=0;s<o;s++)r.setInt8(s,e.getValue(i+s,"i8"));return e.wasmExports.free(i),n}class i{constructor(e){this.pdfium=e,this.docs=new Map}setDocument(e,t,o){let i=this.docs.get(e);i||(i=new n(t,o,this.pdfium),this.docs.set(e,i))}getContext(e){return this.docs.get(e)}closeDocument(e){const t=this.docs.get(e);return!!t&&(t.dispose(),this.docs.delete(e),!0)}}class n{constructor(e,t,o){this.filePtr=e,this.docPtr=t,this.pageCache=new r(o,t)}acquirePage(e){return this.pageCache.acquire(e)}borrowPage(e,t){return this.pageCache.borrowPage(e,t)}dispose(){this.pageCache.forceReleaseAll(),this.pageCache.pdf.FPDF_CloseDocument(this.docPtr),this.pageCache.pdf.pdfium.wasmExports.free(this.filePtr)}}class r{constructor(e,t){this.pdf=e,this.docPtr=t,this.cache=new Map}acquire(e){let t=this.cache.get(e);if(!t){const o=this.pdf.FPDF_LoadPage(this.docPtr,e);t=new s(this.pdf,this.docPtr,e,o,(()=>{this.cache.delete(e)})),this.cache.set(e,t)}return t.clearExpiryTimer(),t.bumpRefCount(),t}borrowPage(e,t){const o=this.cache.has(e),i=this.acquire(e);try{return t(i)}finally{o?i.release():i.disposeImmediate()}}forceReleaseAll(){for(const e of this.cache.values())e.disposeImmediate();this.cache.clear()}}class s{constructor(e,t,o,i,n){this.pdf=e,this.docPtr=t,this.pageIdx=o,this.pagePtr=i,this.onFinalDispose=n,this.refCount=0,this.disposed=!1}bumpRefCount(){if(this.disposed)throw new Error("Context already disposed");this.refCount++}clearExpiryTimer(){this.expiryTimer&&(clearTimeout(this.expiryTimer),this.expiryTimer=void 0)}release(){this.disposed||(this.refCount--,0===this.refCount&&(this.expiryTimer=setTimeout((()=>this.disposeImmediate()),5e3)))}disposeImmediate(){this.disposed||(this.disposed=!0,void 0!==this.textPagePtr&&this.pdf.FPDFText_ClosePage(this.textPagePtr),void 0!==this.formHandle&&(this.pdf.FORM_OnBeforeClosePage(this.pagePtr,this.formHandle),this.pdf.PDFiumExt_ExitFormFillEnvironment(this.formHandle)),void 0!==this.formInfoPtr&&this.pdf.PDFiumExt_CloseFormFillInfo(this.formInfoPtr),this.pdf.FPDF_ClosePage(this.pagePtr),this.onFinalDispose())}getTextPage(){return this.ensureAlive(),void 0===this.textPagePtr&&(this.textPagePtr=this.pdf.FPDFText_LoadPage(this.pagePtr)),this.textPagePtr}getFormHandle(){return this.ensureAlive(),void 0===this.formHandle&&(this.formInfoPtr=this.pdf.PDFiumExt_OpenFormFillInfo(),this.formHandle=this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr,this.formInfoPtr),this.pdf.FORM_OnAfterLoadPage(this.pagePtr,this.formHandle)),this.formHandle}withAnnotation(e,t){this.ensureAlive();const o=this.pdf.FPDFPage_GetAnnot(this.pagePtr,e);try{return t(o)}finally{this.pdf.FPDFPage_CloseAnnot(o)}}ensureAlive(){if(this.disposed)throw new Error("PageContext already disposed")}}var d=(e=>(e[e.Bitmap_Gray=1]="Bitmap_Gray",e[e.Bitmap_BGR=2]="Bitmap_BGR",e[e.Bitmap_BGRx=3]="Bitmap_BGRx",e[e.Bitmap_BGRA=4]="Bitmap_BGRA",e))(d||{}),a=(e=>(e[e.ANNOT=1]="ANNOT",e[e.LCD_TEXT=2]="LCD_TEXT",e[e.NO_NATIVETEXT=4]="NO_NATIVETEXT",e[e.GRAYSCALE=8]="GRAYSCALE",e[e.DEBUG_INFO=128]="DEBUG_INFO",e[e.NO_CATCH=256]="NO_CATCH",e[e.RENDER_LIMITEDIMAGECACHE=512]="RENDER_LIMITEDIMAGECACHE",e[e.RENDER_FORCEHALFTONE=1024]="RENDER_FORCEHALFTONE",e[e.PRINTING=2048]="PRINTING",e[e.REVERSE_BYTE_ORDER=16]="REVERSE_BYTE_ORDER",e))(a||{});const u="PDFiumEngine",l="Engine";var h=(e=>(e[e.Success=0]="Success",e[e.Unknown=1]="Unknown",e[e.File=2]="File",e[e.Format=3]="Format",e[e.Password=4]="Password",e[e.Security=5]="Security",e[e.Page=6]="Page",e[e.XFALoad=7]="XFALoad",e[e.XFALayout=8]="XFALayout",e))(h||{});const f=(e,t="image/webp")=>{if("undefined"==typeof OffscreenCanvas)throw new Error("OffscreenCanvas is not available in this environment. This converter is intended for browser use only. Please use createNodeImageDataToBlobConverter() or createNodeCanvasImageDataToBlobConverter() for Node.js.");const o=new Uint8ClampedArray(e.data),i=new ImageData(o,e.width,e.height),n=new OffscreenCanvas(i.width,i.height);return n.getContext("2d").putImageData(i,0,0),n.convertToBlob({type:t})};exports.BitmapFormat=d,exports.PdfiumEngine=class{constructor(t,o={}){this.pdfiumModule=t;const{logger:n=new e.NoopLogger,imageDataConverter:r=f}=o;this.cache=new i(this.pdfiumModule),this.logger=n,this.imageDataConverter=r}initialize(){return this.logger.debug(u,l,"initialize"),this.logger.perf(u,l,"Initialize","Begin","General"),this.pdfiumModule.PDFiumExt_Init(),this.logger.perf(u,l,"Initialize","End","General"),e.PdfTaskHelper.resolve(!0)}destroy(){return this.logger.debug(u,l,"destroy"),this.logger.perf(u,l,"Destroy","Begin","General"),this.pdfiumModule.FPDF_DestroyLibrary(),this.logger.perf(u,l,"Destroy","End","General"),e.PdfTaskHelper.resolve(!0)}openDocumentUrl(t,o){const i=(null==o?void 0:o.mode)??"auto",n=(null==o?void 0:o.password)??"";this.logger.debug(u,l,"openDocumentUrl called",t.url,i);const r=e.PdfTaskHelper.create();return(async()=>{try{(await this.fetchFullAndOpen(t,n)).wait((e=>r.resolve(e)),(e=>r.reject(e.reason)))}catch(o){this.logger.error(u,l,"openDocumentUrl error",o),r.reject({code:e.PdfErrorCode.Unknown,message:String(o)})}})(),r}async checkRangeSupport(e){try{this.logger.debug(u,l,"checkRangeSupport",e);const t=await fetch(e,{method:"HEAD"}),o=t.headers.get("Content-Length");if("bytes"===t.headers.get("Accept-Ranges"))return{supportsRanges:!0,fileLength:parseInt(o??"0"),content:null};const i=await fetch(e,{headers:{Range:"bytes=0-1"}});if(200===i.status){const e=await i.arrayBuffer();return{supportsRanges:!1,fileLength:parseInt(o??"0"),content:e}}return{supportsRanges:206===i.status,fileLength:parseInt(o??"0"),content:null}}catch(t){throw this.logger.error(u,l,"checkRangeSupport failed",t),new Error("Failed to check range support: "+t)}}async fetchFullAndOpen(e,t){this.logger.debug(u,l,"fetchFullAndOpen",e.url);const o=await fetch(e.url);if(!o.ok)throw new Error(`Could not fetch PDF: ${o.statusText}`);const i=await o.arrayBuffer(),n={id:e.id,name:e.name,content:i};return this.openDocumentBuffer(n,{password:t})}async openDocumentWithRangeRequest(e,t,o){this.logger.debug(u,l,"openDocumentWithRangeRequest",e.url);const i=o??(await this.retrieveFileLength(e.url)).fileLength;return this.openDocumentFromLoader({id:e.id,fileLength:i,callback:(t,o)=>{const i=new XMLHttpRequest;if(i.open("GET",e.url,!1),i.overrideMimeType("text/plain; charset=x-user-defined"),i.setRequestHeader("Range",`bytes=${t}-${t+o-1}`),i.send(null),206===i.status||200===i.status)return this.convertResponseToUint8Array(i.responseText);throw new Error(`Range request failed with status ${i.status}`)}},t)}async retrieveFileLength(e){this.logger.debug(u,l,"retrieveFileLength",e);const t=await fetch(e,{method:"HEAD"});if(!t.ok)throw new Error(`Failed HEAD request for file length: ${t.statusText}`);const o=t.headers.get("Content-Length")||"0",i=parseInt(o,10)||0;if(!i)throw new Error("Content-Length not found or zero.");return{fileLength:i}}convertResponseToUint8Array(e){const t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=255&e.charCodeAt(o);return t}openDocumentBuffer(t,o){this.logger.debug(u,l,"openDocumentBuffer",t,o),this.logger.perf(u,l,"OpenDocumentBuffer","Begin",t.id);const i=new Uint8Array(t.content),n=i.length,r=this.malloc(n);this.pdfiumModule.pdfium.HEAPU8.set(i,r);const s=this.pdfiumModule.FPDF_LoadMemDocument(r,n,(null==o?void 0:o.password)??"");if(!s){const o=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(u,l,`FPDF_LoadMemDocument failed with ${o}`),this.free(r),this.logger.perf(u,l,"OpenDocumentBuffer","End",t.id),e.PdfTaskHelper.reject({code:o,message:"FPDF_LoadMemDocument failed"})}const d=this.pdfiumModule.FPDF_GetPageCount(s),a=[],h=this.malloc(8);for(let g=0;g<d;g++){if(!this.pdfiumModule.FPDF_GetPageSizeByIndexF(s,g,h)){const o=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(u,l,`FPDF_GetPageSizeByIndexF failed with ${o}`),this.free(h),this.pdfiumModule.FPDF_CloseDocument(s),this.free(r),this.logger.perf(u,l,"OpenDocumentBuffer","End",t.id),e.PdfTaskHelper.reject({code:o,message:"FPDF_GetPageSizeByIndexF failed"})}const o={index:g,size:{width:this.pdfiumModule.pdfium.getValue(h,"float"),height:this.pdfiumModule.pdfium.getValue(h+4,"float")}};a.push(o)}this.free(h);const f={id:t.id,name:t.name,pageCount:d,pages:a};return this.cache.setDocument(t.id,r,s),this.logger.perf(u,l,"OpenDocumentBuffer","End",t.id),e.PdfTaskHelper.resolve(f)}openDocumentFromLoader(t,o=""){const{fileLength:i,callback:n,...r}=t;this.logger.debug(u,l,"openDocumentFromLoader",r,o),this.logger.perf(u,l,"OpenDocumentFromLoader","Begin",r.id);const s=this.pdfiumModule.pdfium.addFunction(((e,t,o,r)=>{try{if(this.logger.debug(u,l,"readBlock",t,r,o),t<0||t>=i)return this.logger.error(u,l,"Offset out of bounds:",t),0;const e=n(t,r);return new Uint8Array(this.pdfiumModule.pdfium.HEAPU8.buffer,o,e.length).set(e),e.length}catch(s){return this.logger.error(u,l,"ReadBlock error:",s),0}}),"iiiii"),d=this.malloc(12);this.pdfiumModule.pdfium.setValue(d,i,"i32"),this.pdfiumModule.pdfium.setValue(d+4,s,"i32"),this.pdfiumModule.pdfium.setValue(d+8,0,"i32");const a=this.pdfiumModule.FPDF_LoadCustomDocument(d,o);if(!a){const t=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(u,l,`FPDF_LoadCustomDocument failed with ${t}`),this.free(d),this.logger.perf(u,l,"OpenDocumentFromLoader","End",r.id),e.PdfTaskHelper.reject({code:t,message:"FPDF_LoadCustomDocument failed"})}const h=this.pdfiumModule.FPDF_GetPageCount(a),f=[],g=this.malloc(8);for(let p=0;p<h;p++){if(!this.pdfiumModule.FPDF_GetPageSizeByIndexF(a,p,g)){const t=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(u,l,`FPDF_GetPageSizeByIndexF failed with ${t}`),this.free(g),this.pdfiumModule.FPDF_CloseDocument(a),this.free(d),this.logger.perf(u,l,"OpenDocumentFromLoader","End",r.id),e.PdfTaskHelper.reject({code:t,message:"FPDF_GetPageSizeByIndexF failed"})}const t={index:p,size:{width:this.pdfiumModule.pdfium.getValue(g,"float"),height:this.pdfiumModule.pdfium.getValue(g+4,"float")}};f.push(t)}this.free(g);const c={id:r.id,name:r.name,pageCount:h,pages:f};return this.cache.setDocument(r.id,d,a),this.logger.perf(u,l,"OpenDocumentFromLoader","End",r.id),e.PdfTaskHelper.resolve(c)}getMetadata(t){this.logger.debug(u,l,"getMetadata",t),this.logger.perf(u,l,"GetMetadata","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(u,l,"GetMetadata","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.readMetaText(o.docPtr,"CreationDate"),n=this.readMetaText(o.docPtr,"ModDate"),r={title:this.readMetaText(o.docPtr,"Title"),author:this.readMetaText(o.docPtr,"Author"),subject:this.readMetaText(o.docPtr,"Subject"),keywords:this.readMetaText(o.docPtr,"Keywords"),producer:this.readMetaText(o.docPtr,"Producer"),creator:this.readMetaText(o.docPtr,"Creator"),creationDate:i?e.pdfDateToDate(i)??null:null,modificationDate:n?e.pdfDateToDate(n)??null:null};return this.logger.perf(u,l,"GetMetadata","End",t.id),e.PdfTaskHelper.resolve(r)}setMetadata(t,o){this.logger.debug(u,l,"setMetadata",t,o),this.logger.perf(u,l,"SetMetadata","Begin",t.id);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(u,l,"SetMetadata","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=[["title","Title"],["author","Author"],["subject","Subject"],["keywords","Keywords"],["producer","Producer"],["creator","Creator"]];let r=!0;for(const[e,d]of n){const t=o[e];if(void 0===t)continue;const n=null===t?null:t;this.setMetaText(i.docPtr,d,n)||(r=!1)}const s=(t,n)=>{const s=o[t];if(void 0===s)return;if(null===s)return void(this.setMetaText(i.docPtr,n,null)||(r=!1));const d=s,a=e.dateToPdfDate(d);this.setMetaText(i.docPtr,n,a)||(r=!1)};return s("creationDate","CreationDate"),s("modificationDate","ModDate"),this.logger.perf(u,l,"SetMetadata","End",t.id),r?e.PdfTaskHelper.resolve(!0):e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:"one or more metadata fields could not be written"})}getDocPermissions(t){this.logger.debug(u,l,"getDocPermissions",t),this.logger.perf(u,l,"getDocPermissions","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(u,l,"getDocPermissions","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.FPDF_GetDocPermissions(o.docPtr);return e.PdfTaskHelper.resolve(i)}getDocUserPermissions(t){this.logger.debug(u,l,"getDocUserPermissions",t),this.logger.perf(u,l,"getDocUserPermissions","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(u,l,"getDocUserPermissions","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.FPDF_GetDocUserPermissions(o.docPtr);return e.PdfTaskHelper.resolve(i)}getSignatures(i){this.logger.debug(u,l,"getSignatures",i),this.logger.perf(u,l,"GetSignatures","Begin",i.id);const n=this.cache.getContext(i.id);if(!n)return this.logger.perf(u,l,"GetSignatures","End",i.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=[],s=this.pdfiumModule.FPDF_GetSignatureCount(n.docPtr);for(let e=0;e<s;e++){const i=this.pdfiumModule.FPDF_GetSignatureObject(n.docPtr,e),s=o(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFSignatureObj_GetContents(i,e,t))),d=o(this.pdfiumModule.pdfium,((e,t)=>4*this.pdfiumModule.FPDFSignatureObj_GetByteRange(i,e,t))),a=o(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFSignatureObj_GetSubFilter(i,e,t))),u=t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFSignatureObj_GetReason(i,e,t)),this.pdfiumModule.pdfium.UTF16ToString),l=t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFSignatureObj_GetTime(i,e,t)),this.pdfiumModule.pdfium.UTF8ToString),h=this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(i);r.push({contents:s,byteRange:d,subFilter:a,reason:u,time:l,docMDP:h})}return this.logger.perf(u,l,"GetSignatures","End",i.id),e.PdfTaskHelper.resolve(r)}getBookmarks(t){this.logger.debug(u,l,"getBookmarks",t),this.logger.perf(u,l,"GetBookmarks","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(u,l,"getBookmarks","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.readPdfBookmarks(o.docPtr,0);return this.logger.perf(u,l,"GetBookmarks","End",t.id),e.PdfTaskHelper.resolve({bookmarks:i})}renderPage(t,o,i){const{imageType:n="image/webp"}=i??{},r=new e.Task;this.logger.debug(u,l,"renderPage",t,o,i),this.logger.perf(u,l,"RenderPage","Begin",`${t.id}-${o.index}`);const s=this.cache.getContext(t.id);if(!s)return this.logger.perf(u,l,"RenderPage","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const d=this.renderPageRectToImageData(s,o,{origin:{x:0,y:0},size:o.size},i);return this.logger.perf(u,l,"RenderPage","End",`${t.id}-${o.index}`),this.imageDataConverter(d,n).then((e=>r.resolve(e))),r}renderPageRect(t,o,i,n){const{imageType:r="image/webp"}=n??{},s=new e.Task;this.logger.debug(u,l,"renderPageRect",t,o,i,n),this.logger.perf(u,l,"RenderPageRect","Begin",`${t.id}-${o.index}`);const d=this.cache.getContext(t.id);if(!d)return this.logger.perf(u,l,"RenderPageRect","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=this.renderPageRectToImageData(d,o,i,n);return this.logger.perf(u,l,"RenderPageRect","End",`${t.id}-${o.index}`),this.imageDataConverter(a,r).then((e=>s.resolve(e))),s}getAllAnnotations(t){this.logger.debug(u,l,"getAllAnnotations-with-progress",t),this.logger.perf(u,l,"GetAllAnnotations","Begin",t.id);const o=e.PdfTaskHelper.create();let i=!1;o.wait(e.ignore,(e=>{"abort"===e.type&&(i=!0)}));const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(u,l,"GetAllAnnotations","End",t.id),o.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"}),o;const r={},s=e=>{if(i)return;const d=Math.min(e+100,t.pageCount);for(let s=e;s<d&&!i;++s){this.logger.debug(u,l,"GetAllAnnotations","Begin",t.id,s);const e=this.readPageAnnotationsRaw(n,t.pages[s]);r[s]=e,this.logger.debug(u,l,"GetAllAnnotations","End",t.id,s),o.progress({page:s,annotations:e})}return i?void 0:d>=t.pageCount?(this.logger.perf(u,l,"GetAllAnnotations","End",t.id),void o.resolve(r)):void setTimeout((()=>s(d)),0)};return s(0),o}readAllAnnotations(e,t){const o={};for(let i=0;i<e.pageCount;i++){const n=this.readPageAnnotations(t,e.pages[i]);o[i]=n}return o}getPageAnnotations(t,o){this.logger.debug(u,l,"getPageAnnotations",t,o),this.logger.perf(u,l,"GetPageAnnotations","Begin",`${t.id}-${o.index}`);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(u,l,"GetPageAnnotations","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.readPageAnnotations(i,o);return this.logger.perf(u,l,"GetPageAnnotations","End",`${t.id}-${o.index}`),this.logger.debug(u,l,"GetPageAnnotations",`${t.id}-${o.index}`,n),e.PdfTaskHelper.resolve(n)}createPageAnnotation(t,o,i,n){this.logger.debug(u,l,"createPageAnnotation",t,o,i),this.logger.perf(u,l,"CreatePageAnnotation","Begin",`${t.id}-${o.index}`);const r=this.cache.getContext(t.id);if(!r)return this.logger.perf(u,l,"CreatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const s=r.acquirePage(o.index),d=this.pdfiumModule.EPDFPage_CreateAnnot(s.pagePtr,i.type);if(!d)return this.logger.perf(u,l,"CreatePageAnnotation","End",`${t.id}-${o.index}`),s.release(),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateAnnot,message:"can not create annotation with specified type"});if(e.isUuidV4(i.id)||(i.id=e.uuidV4()),!this.setAnnotString(d,"NM",i.id))return this.pdfiumModule.FPDFPage_CloseAnnot(d),s.release(),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotString,message:"can not set the name of the annotation"});if(!this.setPageAnnoRect(o,s.pagePtr,d,i.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(d),s.release(),this.logger.perf(u,l,"CreatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotRect,message:"can not set the rect of the annotation"});let a=!1;switch(i.type){case e.PdfAnnotationSubtype.INK:a=this.addInkStroke(o,s.pagePtr,d,i);break;case e.PdfAnnotationSubtype.STAMP:a=this.addStampContent(r.docPtr,o,s.pagePtr,d,i,null==n?void 0:n.imageData);break;case e.PdfAnnotationSubtype.TEXT:a=this.addTextContent(o,s.pagePtr,d,i);break;case e.PdfAnnotationSubtype.FREETEXT:a=this.addFreeTextContent(o,s.pagePtr,d,i);break;case e.PdfAnnotationSubtype.LINE:a=this.addLineContent(o,s.pagePtr,d,i);break;case e.PdfAnnotationSubtype.POLYLINE:case e.PdfAnnotationSubtype.POLYGON:a=this.addPolyContent(o,s.pagePtr,d,i);break;case e.PdfAnnotationSubtype.CIRCLE:case e.PdfAnnotationSubtype.SQUARE:a=this.addShapeContent(o,s.pagePtr,d,i);break;case e.PdfAnnotationSubtype.UNDERLINE:case e.PdfAnnotationSubtype.STRIKEOUT:case e.PdfAnnotationSubtype.SQUIGGLY:case e.PdfAnnotationSubtype.HIGHLIGHT:a=this.addTextMarkupContent(o,s.pagePtr,d,i)}return a?(void 0!==i.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(d,i.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(d),this.pdfiumModule.FPDFPage_GenerateContent(s.pagePtr),this.pdfiumModule.FPDFPage_CloseAnnot(d),s.release(),this.logger.perf(u,l,"CreatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(i.id)):(this.pdfiumModule.FPDFPage_RemoveAnnot(s.pagePtr,d),s.release(),this.logger.perf(u,l,"CreatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotContent,message:"can not add content of the annotation"}))}updatePageAnnotation(t,o,i){this.logger.debug(u,l,"updatePageAnnotation",t,o,i),this.logger.perf(u,l,"UpdatePageAnnotation","Begin",`${t.id}-${o.index}`);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(u,l,"UpdatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=n.acquirePage(o.index),s=this.getAnnotationByName(r.pagePtr,i.id);if(!s)return r.release(),this.logger.perf(u,l,"UpdatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.NotFound,message:"annotation not found"});if(!this.setPageAnnoRect(o,r.pagePtr,s,i.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(s),r.release(),this.logger.perf(u,l,"UpdatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotRect,message:"failed to move annotation"});let d=!1;switch(i.type){case e.PdfAnnotationSubtype.INK:if(!this.pdfiumModule.FPDFAnnot_RemoveInkList(s))break;d=this.addInkStroke(o,r.pagePtr,s,i);break;case e.PdfAnnotationSubtype.STAMP:d=this.addStampContent(n.docPtr,o,r.pagePtr,s,i);break;case e.PdfAnnotationSubtype.TEXT:d=this.addTextContent(o,r.pagePtr,s,i);break;case e.PdfAnnotationSubtype.FREETEXT:d=this.addFreeTextContent(o,r.pagePtr,s,i);break;case e.PdfAnnotationSubtype.CIRCLE:case e.PdfAnnotationSubtype.SQUARE:d=this.addShapeContent(o,r.pagePtr,s,i);break;case e.PdfAnnotationSubtype.LINE:d=this.addLineContent(o,r.pagePtr,s,i);break;case e.PdfAnnotationSubtype.POLYGON:case e.PdfAnnotationSubtype.POLYLINE:d=this.addPolyContent(o,r.pagePtr,s,i);break;case e.PdfAnnotationSubtype.HIGHLIGHT:case e.PdfAnnotationSubtype.UNDERLINE:case e.PdfAnnotationSubtype.STRIKEOUT:case e.PdfAnnotationSubtype.SQUIGGLY:d=this.addTextMarkupContent(o,r.pagePtr,s,i);break;default:d=!1}return d&&(void 0!==i.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(s,i.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(s),this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr)),this.pdfiumModule.FPDFPage_CloseAnnot(s),r.release(),this.logger.perf(u,l,"UpdatePageAnnotation","End",`${t.id}-${o.index}`),d?e.PdfTaskHelper.resolve(!0):e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotContent,message:"failed to update annotation"})}removePageAnnotation(t,o,i){this.logger.debug(u,l,"removePageAnnotation",t,o,i),this.logger.perf(u,l,"RemovePageAnnotation","Begin",`${t.id}-${o.index}`);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(u,l,"RemovePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=n.acquirePage(o.index);let s=!1;return s=this.removeAnnotationByName(r.pagePtr,i.id),s?(s=this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr),s||this.logger.error(u,l,"FPDFPage_GenerateContent Failed",`${t.id}-${o.index}`)):this.logger.error(u,l,"FPDFPage_RemoveAnnot Failed",`${t.id}-${o.index}`),r.release(),this.logger.perf(u,l,"RemovePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(s)}getPageTextRects(t,o){this.logger.debug(u,l,"getPageTextRects",t,o),this.logger.perf(u,l,"GetPageTextRects","Begin",`${t.id}-${o.index}`);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(u,l,"GetPageTextRects","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=i.acquirePage(o.index),r=this.pdfiumModule.FPDFText_LoadPage(n.pagePtr),s=this.readPageTextRects(o,n.docPtr,n.pagePtr,r);return this.pdfiumModule.FPDFText_ClosePage(r),n.release(),this.logger.perf(u,l,"GetPageTextRects","End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(s)}renderThumbnail(t,o,i){const{scaleFactor:n=1,rotation:r=e.Rotation.Degree0,dpr:s=1}=i??{};this.logger.debug(u,l,"renderThumbnail",t,o,i),this.logger.perf(u,l,"RenderThumbnail","Begin",`${t.id}-${o.index}`);if(!this.cache.getContext(t.id))return this.logger.perf(u,l,"RenderThumbnail","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const d=this.renderPage(t,o,{scaleFactor:Math.max(n,.5),rotation:r,dpr:s,withAnnotations:!0});return this.logger.perf(u,l,"RenderThumbnail","End",`${t.id}-${o.index}`),d}getAttachments(t){this.logger.debug(u,l,"getAttachments",t),this.logger.perf(u,l,"GetAttachments","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(u,l,"GetAttachments","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=[],n=this.pdfiumModule.FPDFDoc_GetAttachmentCount(o.docPtr);for(let e=0;e<n;e++){const t=this.readPdfAttachment(o.docPtr,e);i.push(t)}return this.logger.perf(u,l,"GetAttachments","End",t.id),e.PdfTaskHelper.resolve(i)}readAttachmentContent(t,o){this.logger.debug(u,l,"readAttachmentContent",t,o),this.logger.perf(u,l,"ReadAttachmentContent","Begin",t.id);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(u,l,"ReadAttachmentContent","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.FPDFDoc_GetAttachment(i.docPtr,o.index),r=this.malloc(4);if(!this.pdfiumModule.FPDFAttachment_GetFile(n,0,0,r))return this.free(r),this.logger.perf(u,l,"ReadAttachmentContent","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantReadAttachmentSize,message:"can not read attachment size"});const s=this.pdfiumModule.pdfium.getValue(r,"i32")>>>0,d=this.malloc(s);if(!this.pdfiumModule.FPDFAttachment_GetFile(n,d,s,r))return this.free(r),this.free(d),this.logger.perf(u,l,"ReadAttachmentContent","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantReadAttachmentContent,message:"can not read attachment content"});const a=new ArrayBuffer(s),h=new DataView(a);for(let e=0;e<s;e++)h.setInt8(e,this.pdfiumModule.pdfium.getValue(d+e,"i8"));return this.free(r),this.free(d),this.logger.perf(u,l,"ReadAttachmentContent","End",t.id),e.PdfTaskHelper.resolve(a)}setFormFieldValue(t,o,i,n){this.logger.debug(u,l,"SetFormFieldValue",t,i,n),this.logger.perf(u,l,"SetFormFieldValue","Begin",`${t.id}-${i.id}`);const r=this.cache.getContext(t.id);if(!r)return this.logger.debug(u,l,"SetFormFieldValue","document is not opened"),this.logger.perf(u,l,"SetFormFieldValue","End",`${t.id}-${i.id}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const s=this.pdfiumModule.PDFiumExt_OpenFormFillInfo(),d=this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(r.docPtr,s),a=r.acquirePage(o.index);this.pdfiumModule.FORM_OnAfterLoadPage(a.pagePtr,d);const h=this.getAnnotationByName(a.pagePtr,i.id);if(!h)return a.release(),this.logger.perf(u,l,"SetFormFieldValue","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.NotFound,message:"annotation not found"});if(!this.pdfiumModule.FORM_SetFocusedAnnot(d,h))return this.logger.debug(u,l,"SetFormFieldValue","failed to set focused annotation"),this.logger.perf(u,l,"SetFormFieldValue","End",`${t.id}-${i.id}`),this.pdfiumModule.FPDFPage_CloseAnnot(h),this.pdfiumModule.FORM_OnBeforeClosePage(a.pagePtr,d),a.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(d),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(s),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantFocusAnnot,message:"failed to set focused annotation"});switch(n.kind){case"text":{if(!this.pdfiumModule.FORM_SelectAllText(d,a.pagePtr))return this.logger.debug(u,l,"SetFormFieldValue","failed to select all text"),this.logger.perf(u,l,"SetFormFieldValue","End",`${t.id}-${i.id}`),this.pdfiumModule.FORM_ForceToKillFocus(d),this.pdfiumModule.FPDFPage_CloseAnnot(h),this.pdfiumModule.FORM_OnBeforeClosePage(a.pagePtr,d),a.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(d),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(s),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSelectText,message:"failed to select all text"});const o=2*(n.text.length+1),r=this.malloc(o);this.pdfiumModule.pdfium.stringToUTF16(n.text,r,o),this.pdfiumModule.FORM_ReplaceSelection(d,a.pagePtr,r),this.free(r)}break;case"selection":if(!this.pdfiumModule.FORM_SetIndexSelected(d,a.pagePtr,n.index,n.isSelected))return this.logger.debug(u,l,"SetFormFieldValue","failed to set index selected"),this.logger.perf(u,l,"SetFormFieldValue","End",`${t.id}-${i.id}`),this.pdfiumModule.FORM_ForceToKillFocus(d),this.pdfiumModule.FPDFPage_CloseAnnot(h),this.pdfiumModule.FORM_OnBeforeClosePage(a.pagePtr,d),a.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(d),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(s),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSelectOption,message:"failed to set index selected"});break;case"checked":{const o=13;if(!this.pdfiumModule.FORM_OnChar(d,a.pagePtr,o,0))return this.logger.debug(u,l,"SetFormFieldValue","failed to set field checked"),this.logger.perf(u,l,"SetFormFieldValue","End",`${t.id}-${i.id}`),this.pdfiumModule.FORM_ForceToKillFocus(d),this.pdfiumModule.FPDFPage_CloseAnnot(h),this.pdfiumModule.FORM_OnBeforeClosePage(a.pagePtr,d),a.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(d),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(s),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCheckField,message:"failed to set field checked"})}}return this.pdfiumModule.FORM_ForceToKillFocus(d),this.pdfiumModule.FPDFPage_CloseAnnot(h),this.pdfiumModule.FORM_OnBeforeClosePage(a.pagePtr,d),a.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(d),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(s),e.PdfTaskHelper.resolve(!0)}flattenPage(t,o,i){const{flag:n=e.PdfPageFlattenFlag.Display}=i??{};this.logger.debug(u,l,"flattenPage",t,o,n),this.logger.perf(u,l,"flattenPage","Begin",t.id);const r=this.cache.getContext(t.id);if(!r)return this.logger.perf(u,l,"flattenPage","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const s=r.acquirePage(o.index),d=this.pdfiumModule.FPDFPage_Flatten(s.pagePtr,n);return s.release(),this.logger.perf(u,l,"flattenPage","End",t.id),e.PdfTaskHelper.resolve(d)}extractPages(t,o){this.logger.debug(u,l,"extractPages",t,o),this.logger.perf(u,l,"ExtractPages","Begin",t.id);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(u,l,"ExtractPages","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.FPDF_CreateNewDocument();if(!n)return this.logger.perf(u,l,"ExtractPages","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateNewDoc,message:"can not create new document"});const r=this.malloc(4*o.length);for(let e=0;e<o.length;e++)this.pdfiumModule.pdfium.setValue(r+4*e,o[e],"i32");if(!this.pdfiumModule.FPDF_ImportPagesByIndex(n,i.docPtr,r,o.length,0))return this.pdfiumModule.FPDF_CloseDocument(n),this.logger.perf(u,l,"ExtractPages","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantImportPages,message:"can not import pages to new document"});const s=this.saveDocument(n);return this.pdfiumModule.FPDF_CloseDocument(n),this.logger.perf(u,l,"ExtractPages","End",t.id),e.PdfTaskHelper.resolve(s)}extractText(t,o){this.logger.debug(u,l,"extractText",t,o),this.logger.perf(u,l,"ExtractText","Begin",t.id);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(u,l,"ExtractText","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=[];for(let e=0;e<o.length;e++){const t=i.acquirePage(o[e]),r=this.pdfiumModule.FPDFText_LoadPage(t.pagePtr),s=this.pdfiumModule.FPDFText_CountChars(r),d=this.malloc(2*(s+1));this.pdfiumModule.FPDFText_GetText(r,0,s,d);const a=this.pdfiumModule.pdfium.UTF16ToString(d);this.free(d),n.push(a),this.pdfiumModule.FPDFText_ClosePage(r),t.release()}const r=n.join("\n\n");return this.logger.perf(u,l,"ExtractText","End",t.id),e.PdfTaskHelper.resolve(r)}getTextSlices(t,o){if(this.logger.debug(u,l,"getTextSlices",t,o),this.logger.perf(u,l,"GetTextSlices","Begin",t.id),0===o.length)return this.logger.perf(u,l,"GetTextSlices","End",t.id),e.PdfTaskHelper.resolve([]);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(u,l,"GetTextSlices","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});try{const n=new Array(o.length),r=new Map;o.forEach(((e,t)=>{(r.get(e.pageIndex)??r.set(e.pageIndex,[]).get(e.pageIndex)).push({slice:e,pos:t})}));for(const[t,o]of r){const r=i.acquirePage(t),s=r.getTextPage();for(const{slice:t,pos:i}of o){const o=this.malloc(2*(t.charCount+1));this.pdfiumModule.FPDFText_GetText(s,t.charIndex,t.charCount,o),n[i]=e.stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(o)),this.free(o)}r.release()}return this.logger.perf(u,l,"GetTextSlices","End",t.id),e.PdfTaskHelper.resolve(n)}catch(n){return this.logger.error(u,l,"getTextSlices error",n),this.logger.perf(u,l,"GetTextSlices","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:String(n)})}}merge(t){this.logger.debug(u,l,"merge",t);const o=t.map((e=>e.id)).join(".");this.logger.perf(u,l,"Merge","Begin",o);const i=this.pdfiumModule.FPDF_CreateNewDocument();if(!i)return this.logger.perf(u,l,"Merge","End",o),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateNewDoc,message:"can not create new document"});const n=[];for(const d of t.reverse()){const t=new Uint8Array(d.content),r=t.length,s=this.malloc(r);this.pdfiumModule.pdfium.HEAPU8.set(t,s);const a=this.pdfiumModule.FPDF_LoadMemDocument(s,r,"");if(!a){const t=this.pdfiumModule.FPDF_GetLastError();this.logger.error(u,l,`FPDF_LoadMemDocument failed with ${t}`),this.free(s);for(const e of n)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.free(e.filePtr);return this.logger.perf(u,l,"Merge","End",o),e.PdfTaskHelper.reject({code:t,message:"FPDF_LoadMemDocument failed"})}if(n.push({filePtr:s,docPtr:a}),!this.pdfiumModule.FPDF_ImportPages(i,a,"",0)){this.pdfiumModule.FPDF_CloseDocument(i);for(const e of n)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.free(e.filePtr);return this.logger.perf(u,l,"Merge","End",o),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantImportPages,message:"can not import pages to new document"})}}const r=this.saveDocument(i);this.pdfiumModule.FPDF_CloseDocument(i);for(const e of n)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.free(e.filePtr);const s={id:`${Math.random()}`,content:r};return this.logger.perf(u,l,"Merge","End",o),e.PdfTaskHelper.resolve(s)}mergePages(t){const o=t.map((e=>`${e.docId}:${e.pageIndices.join(",")}`)).join("|");this.logger.debug(u,l,"mergePages",t),this.logger.perf(u,l,"MergePages","Begin",o);const i=this.pdfiumModule.FPDF_CreateNewDocument();if(!i)return this.logger.perf(u,l,"MergePages","End",o),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateNewDoc,message:"Cannot create new document"});try{for(const e of[...t].reverse()){const t=this.cache.getContext(e.docId);if(!t){this.logger.warn(u,l,`Document ${e.docId} is not open, skipping`);continue}const o=this.pdfiumModule.FPDF_GetPageCount(t.docPtr),n=e.pageIndices.filter((e=>e>=0&&e<o));if(0===n.length)continue;const r=n.map((e=>e+1)).join(",");try{if(!this.pdfiumModule.FPDF_ImportPages(i,t.docPtr,r,0))throw new Error(`Failed to import pages ${r} from document ${e.docId}`)}finally{}}const n=this.saveDocument(i),r={id:`${Math.random()}`,content:n};return this.logger.perf(u,l,"MergePages","End",o),e.PdfTaskHelper.resolve(r)}catch(n){return this.logger.error(u,l,"mergePages failed",n),this.logger.perf(u,l,"MergePages","End",o),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantImportPages,message:n instanceof Error?n.message:"Failed to merge pages"})}finally{i&&this.pdfiumModule.FPDF_CloseDocument(i)}}saveAsCopy(t){this.logger.debug(u,l,"saveAsCopy",t),this.logger.perf(u,l,"SaveAsCopy","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(u,l,"SaveAsCopy","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.saveDocument(o.docPtr);return this.logger.perf(u,l,"SaveAsCopy","End",t.id),e.PdfTaskHelper.resolve(i)}closeDocument(t){this.logger.debug(u,l,"closeDocument",t),this.logger.perf(u,l,"CloseDocument","Begin",t.id);const o=this.cache.getContext(t.id);return o?(o.dispose(),this.logger.perf(u,l,"CloseDocument","End",t.id),e.PdfTaskHelper.resolve(!0)):(this.logger.perf(u,l,"CloseDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"}))}malloc(e){const t=this.pdfiumModule.pdfium.wasmExports.malloc(e);for(let o=0;o<e;o++)this.pdfiumModule.pdfium.HEAP8[t+o]=0;return t}free(e){this.pdfiumModule.pdfium.wasmExports.free(e)}addTextContent(t,o,i,n){return!!this.setPageAnnoRect(t,o,i,n.rect)&&(!!this.setAnnotString(i,"Contents",n.contents??"")&&(!!this.setAnnotString(i,"T",n.author||"")&&(!(n.modified&&!this.setAnnotationDate(i,"M",n.modified))&&(!(n.created&&!this.setAnnotationDate(i,"CreationDate",n.created))&&(!(n.inReplyToId&&!this.setInReplyToId(o,i,n.inReplyToId))&&(!!this.setAnnotationIcon(i,n.icon||e.PdfAnnotationIcon.Comment)&&(!!this.setAnnotationFlags(i,n.flags||["print","noZoom","noRotate"])&&(!(n.state&&!this.setAnnotString(i,"State",n.state))&&!(n.stateModel&&!this.setAnnotString(i,"StateModel",n.stateModel))))))))))}addFreeTextContent(t,o,i,n){if(n.created&&!this.setAnnotationDate(i,"CreationDate",n.created))return!1;if(n.flags&&!this.setAnnotationFlags(i,n.flags))return!1;if(n.modified&&!this.setAnnotationDate(i,"M",n.modified))return!1;if(!this.setBorderStyle(i,e.PdfAnnotationBorderStyle.SOLID,0))return!1;if(!this.setAnnotString(i,"Contents",n.contents??""))return!1;if(!this.setPageAnnoRect(t,o,i,n.rect))return!1;if(!this.setAnnotString(i,"T",n.author||""))return!1;if(!this.setAnnotationOpacity(i,n.opacity??1))return!1;if(!this.setAnnotationTextAlignment(i,n.textAlign))return!1;if(!this.setAnnotationVerticalAlignment(i,n.verticalAlign))return!1;if(!this.setAnnotationDefaultAppearance(i,n.fontFamily,n.fontSize,n.fontColor))return!1;if(n.intent&&!this.setAnnotIntent(i,n.intent))return!1;if(n.backgroundColor&&"transparent"!==n.backgroundColor){if(!this.setAnnotationColor(i,n.backgroundColor??"#FFFFFF",e.PdfAnnotationColorType.Color))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,e.PdfAnnotationColorType.Color))return!1;return!0}addInkStroke(t,o,i,n){return!(n.created&&!this.setAnnotationDate(i,"CreationDate",n.created))&&(!(n.flags&&!this.setAnnotationFlags(i,n.flags))&&(!(n.modified&&!this.setAnnotationDate(i,"M",n.modified))&&(!!this.setAnnotString(i,"Contents",n.contents??"")&&(!!this.setBorderStyle(i,e.PdfAnnotationBorderStyle.SOLID,n.strokeWidth)&&(!!this.setPageAnnoRect(t,o,i,n.rect)&&(!!this.setInkList(t,i,n.inkList)&&(!!this.setAnnotString(i,"T",n.author||"")&&(!!this.setAnnotationOpacity(i,n.opacity??1)&&!!this.setAnnotationColor(i,n.color??"#FFFF00",e.PdfAnnotationColorType.Color)))))))))}addLineContent(t,o,i,n){var r,s;if(n.created&&!this.setAnnotationDate(i,"CreationDate",n.created))return!1;if(n.flags&&!this.setAnnotationFlags(i,n.flags))return!1;if(n.modified&&!this.setAnnotationDate(i,"M",n.modified))return!1;if(!this.setPageAnnoRect(t,o,i,n.rect))return!1;if(!this.setLinePoints(t,i,n.linePoints.start,n.linePoints.end))return!1;if(!this.setLineEndings(i,(null==(r=n.lineEndings)?void 0:r.start)??e.PdfAnnotationLineEnding.None,(null==(s=n.lineEndings)?void 0:s.end)??e.PdfAnnotationLineEnding.None))return!1;if(!this.setAnnotString(i,"Contents",n.contents??""))return!1;if(!this.setAnnotString(i,"T",n.author||""))return!1;if(!this.setBorderStyle(i,n.strokeStyle,n.strokeWidth))return!1;if(!this.setBorderDashPattern(i,n.strokeDashArray??[]))return!1;if(n.intent&&!this.setAnnotIntent(i,n.intent))return!1;if(n.color&&"transparent"!==n.color){if(!this.setAnnotationColor(i,n.color??"#FFFF00",e.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,e.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(i,n.opacity??1)&&!!this.setAnnotationColor(i,n.strokeColor??"#FFFF00",e.PdfAnnotationColorType.Color)}addPolyContent(t,o,i,n){var r,s;if(n.created&&!this.setAnnotationDate(i,"CreationDate",n.created))return!1;if(n.modified&&!this.setAnnotationDate(i,"M",n.modified))return!1;if(n.flags&&!this.setAnnotationFlags(i,n.flags))return!1;if(!this.setPageAnnoRect(t,o,i,n.rect))return!1;if(n.type===e.PdfAnnotationSubtype.POLYLINE&&!this.setLineEndings(i,(null==(r=n.lineEndings)?void 0:r.start)??e.PdfAnnotationLineEnding.None,(null==(s=n.lineEndings)?void 0:s.end)??e.PdfAnnotationLineEnding.None))return!1;if(!this.setPdfAnnoVertices(t,i,n.vertices))return!1;if(!this.setAnnotString(i,"Contents",n.contents??""))return!1;if(!this.setAnnotString(i,"T",n.author||""))return!1;if(!this.setBorderStyle(i,n.strokeStyle,n.strokeWidth))return!1;if(!this.setBorderDashPattern(i,n.strokeDashArray??[]))return!1;if(n.intent&&!this.setAnnotIntent(i,n.intent))return!1;if(n.color&&"transparent"!==n.color){if(!this.setAnnotationColor(i,n.color??"#FFFF00",e.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,e.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(i,n.opacity??1)&&!!this.setAnnotationColor(i,n.strokeColor??"#FFFF00",e.PdfAnnotationColorType.Color)}addShapeContent(t,o,i,n){if(n.created&&!this.setAnnotationDate(i,"CreationDate",n.created))return!1;if(n.modified&&!this.setAnnotationDate(i,"M",n.modified))return!1;if(!this.setPageAnnoRect(t,o,i,n.rect))return!1;if(!this.setAnnotString(i,"Contents",n.contents??""))return!1;if(!this.setAnnotString(i,"T",n.author||""))return!1;if(!this.setBorderStyle(i,n.strokeStyle,n.strokeWidth))return!1;if(!this.setBorderDashPattern(i,n.strokeDashArray??[]))return!1;if(!this.setAnnotationFlags(i,n.flags))return!1;if(n.color&&"transparent"!==n.color){if(!this.setAnnotationColor(i,n.color??"#FFFF00",e.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,e.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(i,n.opacity??1)&&!!this.setAnnotationColor(i,n.strokeColor??"#FFFF00",e.PdfAnnotationColorType.Color)}addTextMarkupContent(t,o,i,n){return!(n.created&&!this.setAnnotationDate(i,"CreationDate",n.created))&&(!(n.flags&&!this.setAnnotationFlags(i,n.flags))&&(!(n.modified&&!this.setAnnotationDate(i,"M",n.modified))&&(!!this.setPageAnnoRect(t,o,i,n.rect)&&(!!this.syncQuadPointsAnno(t,i,n.segmentRects)&&(!!this.setAnnotString(i,"Contents",n.contents??"")&&(!!this.setAnnotString(i,"T",n.author||"")&&(!!this.setAnnotationOpacity(i,n.opacity??1)&&!!this.setAnnotationColor(i,n.color??"#FFFF00",e.PdfAnnotationColorType.Color))))))))}addStampContent(e,t,o,i,n,r){if(n.created&&!this.setAnnotationDate(i,"CreationDate",n.created))return!1;if(n.flags&&!this.setAnnotationFlags(i,n.flags))return!1;if(n.modified&&!this.setAnnotationDate(i,"M",n.modified))return!1;if(!this.setAnnotString(i,"Contents",n.contents??""))return!1;if(r){for(let e=this.pdfiumModule.FPDFAnnot_GetObjectCount(i)-1;e>=0;e--)this.pdfiumModule.FPDFAnnot_RemoveObject(i,e);return this.addImageObject(e,t,o,i,n.rect.origin,r)}return!0}addImageObject(e,t,o,i,n,r){const s=r.width*r.height,d=this.malloc(4*s);if(!d)return!1;for(let f=0;f<s;f++){const e=r.data[4*f],t=r.data[4*f+1],o=r.data[4*f+2],i=r.data[4*f+3];this.pdfiumModule.pdfium.setValue(d+4*f,o,"i8"),this.pdfiumModule.pdfium.setValue(d+4*f+1,t,"i8"),this.pdfiumModule.pdfium.setValue(d+4*f+2,e,"i8"),this.pdfiumModule.pdfium.setValue(d+4*f+3,i,"i8")}const a=this.pdfiumModule.FPDFBitmap_CreateEx(r.width,r.height,4,d,0);if(!a)return this.free(d),!1;const u=this.pdfiumModule.FPDFPageObj_NewImageObj(e);if(!u)return this.pdfiumModule.FPDFBitmap_Destroy(a),this.free(d),!1;if(!this.pdfiumModule.FPDFImageObj_SetBitmap(o,0,u,a))return this.pdfiumModule.FPDFBitmap_Destroy(a),this.pdfiumModule.FPDFPageObj_Destroy(u),this.free(d),!1;const l=this.malloc(24);if(this.pdfiumModule.pdfium.setValue(l,r.width,"float"),this.pdfiumModule.pdfium.setValue(l+4,0,"float"),this.pdfiumModule.pdfium.setValue(l+8,0,"float"),this.pdfiumModule.pdfium.setValue(l+12,r.height,"float"),this.pdfiumModule.pdfium.setValue(l+16,0,"float"),this.pdfiumModule.pdfium.setValue(l+20,0,"float"),!this.pdfiumModule.FPDFPageObj_SetMatrix(u,l))return this.free(l),this.pdfiumModule.FPDFBitmap_Destroy(a),this.pdfiumModule.FPDFPageObj_Destroy(u),this.free(d),!1;this.free(l);const h=this.convertDevicePointToPagePoint(t,{x:n.x,y:n.y+r.height});return this.pdfiumModule.FPDFPageObj_Transform(u,1,0,0,1,h.x,h.y),this.pdfiumModule.FPDFAnnot_AppendObject(i,u)?(this.pdfiumModule.FPDFBitmap_Destroy(a),this.free(d),!0):(this.pdfiumModule.FPDFBitmap_Destroy(a),this.pdfiumModule.FPDFPageObj_Destroy(u),this.free(d),!1)}saveDocument(e){const t=this.pdfiumModule.PDFiumExt_OpenFileWriter();this.pdfiumModule.PDFiumExt_SaveAsCopy(e,t);const o=this.pdfiumModule.PDFiumExt_GetFileWriterSize(t),i=this.malloc(o);this.pdfiumModule.PDFiumExt_GetFileWriterData(t,i,o);const n=new ArrayBuffer(o),r=new DataView(n);for(let s=0;s<o;s++)r.setInt8(s,this.pdfiumModule.pdfium.getValue(i+s,"i8"));return this.free(i),this.pdfiumModule.PDFiumExt_CloseFileWriter(t),n}readMetaText(e,o){if(!!!this.pdfiumModule.EPDF_HasMetaText(e,o))return null;const i=this.pdfiumModule.FPDF_GetMetaText(e,o,0,0);return 2===i?"":t(this.pdfiumModule.pdfium,((t,i)=>this.pdfiumModule.FPDF_GetMetaText(e,o,t,i)),this.pdfiumModule.pdfium.UTF16ToString,i)}setMetaText(e,t,o){if(null==o||0===o.length){return!!this.pdfiumModule.EPDF_SetMetaText(e,t,0)}const i=2*(o.length+1),n=this.malloc(i);try{this.pdfiumModule.pdfium.stringToUTF16(o,n,i);return!!this.pdfiumModule.EPDF_SetMetaText(e,t,n)}finally{this.free(n)}}readPdfBookmarks(e,t=0){let o=this.pdfiumModule.FPDFBookmark_GetFirstChild(e,t);const i=[];for(;o;){const t=this.readPdfBookmark(e,o);i.push(t);o=this.pdfiumModule.FPDFBookmark_GetNextSibling(e,o)}return i}readPdfBookmark(e,o){const i=t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFBookmark_GetTitle(o,e,t)),this.pdfiumModule.pdfium.UTF16ToString),n=this.readPdfBookmarks(e,o);return{title:i,target:this.readPdfBookmarkTarget(e,(()=>this.pdfiumModule.FPDFBookmark_GetAction(o)),(()=>this.pdfiumModule.FPDFBookmark_GetDest(e,o))),children:n}}readPageTextRects(e,t,o,i){const n=this.pdfiumModule.FPDFText_CountRects(i,0,-1),r=[];for(let s=0;s<n;s++){const t=this.malloc(8),n=this.malloc(8),d=this.malloc(8),a=this.malloc(8);if(!this.pdfiumModule.FPDFText_GetRect(i,s,n,t,d,a)){this.free(n),this.free(t),this.free(d),this.free(a);continue}const u=this.pdfiumModule.pdfium.getValue(n,"double"),l=this.pdfiumModule.pdfium.getValue(t,"double"),h=this.pdfiumModule.pdfium.getValue(d,"double"),f=this.pdfiumModule.pdfium.getValue(a,"double");this.free(n),this.free(t),this.free(d),this.free(a);const g=this.malloc(4),c=this.malloc(4);this.pdfiumModule.FPDF_PageToDevice(o,0,0,e.size.width,e.size.height,0,u,l,g,c);const p=this.pdfiumModule.pdfium.getValue(g,"i32"),m=this.pdfiumModule.pdfium.getValue(c,"i32");this.free(g),this.free(c);const P={origin:{x:p,y:m},size:{width:Math.ceil(Math.abs(h-u)),height:Math.ceil(Math.abs(l-f))}},F=this.pdfiumModule.FPDFText_GetBoundedText(i,u,l,h,f,0,0),A=2*(F+1),D=this.malloc(A);this.pdfiumModule.FPDFText_GetBoundedText(i,u,l,h,f,D,F);const M=this.pdfiumModule.pdfium.UTF16ToString(D);this.free(D);const C=this.pdfiumModule.FPDFText_GetCharIndexAtPos(i,u,l,2,2);let T="",E=P.size.height;if(C>=0){E=this.pdfiumModule.FPDFText_GetFontSize(i,C);const e=this.pdfiumModule.FPDFText_GetFontInfo(i,C,0,0,0)+1,t=this.malloc(e),o=this.malloc(4);this.pdfiumModule.FPDFText_GetFontInfo(i,C,t,e,o),T=this.pdfiumModule.pdfium.UTF8ToString(t),this.free(t),this.free(o)}const y={content:M,rect:P,font:{family:T,size:E}};r.push(y)}return r}getPageGeometry(t,o){const i="getPageGeometry";this.logger.perf(u,l,i,"Begin",t.id);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(u,l,i,"End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=n.acquirePage(o.index),s=r.getTextPage(),d=this.pdfiumModule.FPDFText_CountChars(s),a=[];for(let e=0;e<d;e++){const t=this.readGlyphInfo(o,r.pagePtr,s,e);a.push(t)}const h=this.buildRunsFromGlyphs(a,s);return r.release(),this.logger.perf(u,l,i,"End",t.id),e.PdfTaskHelper.resolve({runs:h})}buildRunsFromGlyphs(e,t){const o=[];let i=null,n=null,r=null;for(let s=0;s<e.length;s++){const d=e[s],a=this.pdfiumModule.FPDFText_GetTextObject(t,s);if(a!==n&&(n=a,i={rect:{x:d.origin.x,y:d.origin.y,width:d.size.width,height:d.size.height},charStart:s,glyphs:[]},r={minX:d.origin.x,minY:d.origin.y,maxX:d.origin.x+d.size.width,maxY:d.origin.y+d.size.height},o.push(i)),i.glyphs.push({x:d.origin.x,y:d.origin.y,width:d.size.width,height:d.size.height,flags:d.isEmpty?2:d.isSpace?1:0}),d.isEmpty)continue;const u=d.origin.x+d.size.width,l=d.origin.y+d.size.height;r.minX=Math.min(r.minX,d.origin.x),r.minY=Math.min(r.minY,d.origin.y),r.maxX=Math.max(r.maxX,u),r.maxY=Math.max(r.maxY,l),i.rect.x=r.minX,i.rect.y=r.minY,i.rect.width=r.maxX-r.minX,i.rect.height=r.maxY-r.minY}return o}readGlyphInfo(e,t,o,i){const n=this.malloc(4),r=this.malloc(4),s=this.malloc(4),d=this.malloc(4),a=this.malloc(16);let u=0,l=0,h=0,f=0,g=!1;if(this.pdfiumModule.FPDFText_GetLooseCharBox(o,i,a)){const c=this.pdfiumModule.pdfium.getValue(a,"float"),p=this.pdfiumModule.pdfium.getValue(a+4,"float"),m=this.pdfiumModule.pdfium.getValue(a+8,"float"),P=this.pdfiumModule.pdfium.getValue(a+12,"float");if(c===m||p===P)return{origin:{x:0,y:0},size:{width:0,height:0},isEmpty:!0};this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,c,p,n,r),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,m,P,s,d);const F=this.pdfiumModule.pdfium.getValue(n,"i32"),A=this.pdfiumModule.pdfium.getValue(r,"i32"),D=this.pdfiumModule.pdfium.getValue(s,"i32"),M=this.pdfiumModule.pdfium.getValue(d,"i32");u=Math.min(F,D),l=Math.min(A,M),h=Math.max(1,Math.abs(D-F)),f=Math.max(1,Math.abs(M-A));g=32===this.pdfiumModule.FPDFText_GetUnicode(o,i)}return[a,n,r,s,d].forEach((e=>this.free(e))),{origin:{x:u,y:l},size:{width:h,height:f},...g&&{isSpace:g}}}getPageGlyphs(t,o){this.logger.debug(u,l,"getPageGlyphs",t,o),this.logger.perf(u,l,"getPageGlyphs","Begin",t.id);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(u,l,"getPageGlyphs","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=i.acquirePage(o.index),r=n.getTextPage(),s=this.pdfiumModule.FPDFText_CountChars(r),d=new Array(s);for(let e=0;e<s;e++){const t=this.readGlyphInfo(o,n.pagePtr,r,e);t.isEmpty||(d[e]={...t})}return n.release(),this.logger.perf(u,l,"getPageGlyphs","End",t.id),e.PdfTaskHelper.resolve(d)}readCharBox(e,t,o,i){const n=this.malloc(8),r=this.malloc(8),s=this.malloc(8),d=this.malloc(8);let a=0,u=0,l=0,h=0;if(this.pdfiumModule.FPDFText_GetCharBox(o,i,r,d,s,n)){const o=this.pdfiumModule.pdfium.getValue(n,"double"),i=this.pdfiumModule.pdfium.getValue(r,"double"),f=this.pdfiumModule.pdfium.getValue(s,"double"),g=this.pdfiumModule.pdfium.getValue(d,"double"),c=this.malloc(4),p=this.malloc(4);this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,i,o,c,p),a=this.pdfiumModule.pdfium.getValue(c,"i32"),u=this.pdfiumModule.pdfium.getValue(p,"i32"),this.free(c),this.free(p),l=Math.ceil(Math.abs(g-i)),h=Math.ceil(Math.abs(o-f))}return this.free(n),this.free(r),this.free(s),this.free(d),{origin:{x:a,y:u},size:{width:l,height:h}}}readPageAnnotations(e,t){return e.borrowPage(t.index,(o=>{const i=this.pdfiumModule.FPDFPage_GetAnnotCount(o.pagePtr),n=[];for(let r=0;r<i;r++)o.withAnnotation(r,(i=>{const r=this.readPageAnnotation(e.docPtr,t,i,o);r&&n.push(r)}));return n}))}readPageAnnotationsRaw(e,t){const o=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(e.docPtr,t.index);if(o<=0)return[];const i=[];for(let n=0;n<o;++n){const o=this.pdfiumModule.EPDFPage_GetAnnotRaw(e.docPtr,t.index,n);if(o)try{const n=this.readPageAnnotation(e.docPtr,t,o);n&&i.push(n)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(o)}}return i}readPageAnnotation(t,o,i,n){let r=this.getAnnotString(i,"NM");r&&e.isUuidV4(r)||(r=e.uuidV4(),this.setAnnotString(i,"NM",r));const s=this.pdfiumModule.FPDFAnnot_GetSubtype(i);let d;switch(s){case e.PdfAnnotationSubtype.TEXT:d=this.readPdfTextAnno(o,i,r);break;case e.PdfAnnotationSubtype.FREETEXT:d=this.readPdfFreeTextAnno(o,i,r);break;case e.PdfAnnotationSubtype.LINK:d=this.readPdfLinkAnno(o,t,i,r);break;case e.PdfAnnotationSubtype.WIDGET:if(n)return this.readPdfWidgetAnno(o,i,n.getFormHandle(),r);case e.PdfAnnotationSubtype.FILEATTACHMENT:d=this.readPdfFileAttachmentAnno(o,i,r);break;case e.PdfAnnotationSubtype.INK:d=this.readPdfInkAnno(o,i,r);break;case e.PdfAnnotationSubtype.POLYGON:d=this.readPdfPolygonAnno(o,i,r);break;case e.PdfAnnotationSubtype.POLYLINE:d=this.readPdfPolylineAnno(o,i,r);break;case e.PdfAnnotationSubtype.LINE:d=this.readPdfLineAnno(o,i,r);break;case e.PdfAnnotationSubtype.HIGHLIGHT:d=this.readPdfHighlightAnno(o,i,r);break;case e.PdfAnnotationSubtype.STAMP:d=this.readPdfStampAnno(o,i,r);break;case e.PdfAnnotationSubtype.SQUARE:d=this.readPdfSquareAnno(o,i,r);break;case e.PdfAnnotationSubtype.CIRCLE:d=this.readPdfCircleAnno(o,i,r);break;case e.PdfAnnotationSubtype.UNDERLINE:d=this.readPdfUnderlineAnno(o,i,r);break;case e.PdfAnnotationSubtype.SQUIGGLY:d=this.readPdfSquigglyAnno(o,i,r);break;case e.PdfAnnotationSubtype.STRIKEOUT:d=this.readPdfStrikeOutAnno(o,i,r);break;case e.PdfAnnotationSubtype.CARET:d=this.readPdfCaretAnno(o,i,r);break;default:d=this.readPdfAnno(o,s,i,r)}return d}readAnnotationColor(t,o=e.PdfAnnotationColorType.Color){const i=this.malloc(4),n=this.malloc(4),r=this.malloc(4);let s;return this.pdfiumModule.EPDFAnnot_GetColor(t,o,i,n,r)&&(s={red:255&this.pdfiumModule.pdfium.getValue(i,"i32"),green:255&this.pdfiumModule.pdfium.getValue(n,"i32"),blue:255&this.pdfiumModule.pdfium.getValue(r,"i32")}),this.free(i),this.free(n),this.free(r),s}getAnnotationColor(t,o=e.PdfAnnotationColorType.Color){const i=this.readAnnotationColor(t,o);return i?e.pdfColorToWebColor(i):void 0}setAnnotationColor(t,o,i=e.PdfAnnotationColorType.Color){const n=e.webColorToPdfColor(o);return this.pdfiumModule.EPDFAnnot_SetColor(t,i,255&n.red,255&n.green,255&n.blue)}getAnnotationOpacity(t){const o=this.malloc(4),i=this.pdfiumModule.EPDFAnnot_GetOpacity(t,o)?this.pdfiumModule.pdfium.getValue(o,"i32"):255;return this.free(o),e.pdfAlphaToWebOpacity(i)}setAnnotationOpacity(t,o){const i=e.webOpacityToPdfAlpha(o);return this.pdfiumModule.EPDFAnnot_SetOpacity(t,255&i)}getAnnotationTextAlignment(e){return this.pdfiumModule.EPDFAnnot_GetTextAlignment(e)}setAnnotationTextAlignment(e,t){return!!this.pdfiumModule.EPDFAnnot_SetTextAlignment(e,t)}getAnnotationVerticalAlignment(e){return this.pdfiumModule.EPDFAnnot_GetVerticalAlignment(e)}setAnnotationVerticalAlignment(e,t){return!!this.pdfiumModule.EPDFAnnot_SetVerticalAlignment(e,t)}getAnnotationDefaultAppearance(t){const o=this.malloc(4),i=this.malloc(4),n=this.malloc(4),r=this.malloc(4),s=this.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(t,o,i,n,r,s))return void[o,i,n,r,s].forEach((e=>this.free(e)));const d=this.pdfiumModule.pdfium,a=d.getValue(o,"i32"),u=d.getValue(i,"float"),l=255&d.getValue(n,"i32"),h=255&d.getValue(r,"i32"),f=255&d.getValue(s,"i32");return[o,i,n,r,s].forEach((e=>this.free(e))),{fontFamily:a,fontSize:u,fontColor:e.pdfColorToWebColor({red:l,green:h,blue:f})}}setAnnotationDefaultAppearance(t,o,i,n){const{red:r,green:s,blue:d}=e.webColorToPdfColor(n);return!!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(t,o,i,255&r,255&s,255&d)}getBorderStyle(t){const o=this.malloc(4);let i=0,n=e.PdfAnnotationBorderStyle.UNKNOWN,r=!1;return n=this.pdfiumModule.EPDFAnnot_GetBorderStyle(t,o),i=this.pdfiumModule.pdfium.getValue(o,"float"),r=n!==e.PdfAnnotationBorderStyle.UNKNOWN,this.free(o),{ok:r,style:n,width:i}}setBorderStyle(e,t,o){return this.pdfiumModule.EPDFAnnot_SetBorderStyle(e,t,o)}getAnnotationIcon(e){return this.pdfiumModule.EPDFAnnot_GetIcon(e)}setAnnotationIcon(e,t){return this.pdfiumModule.EPDFAnnot_SetIcon(e,t)}getBorderEffect(e){const t=this.malloc(4),o=!!this.pdfiumModule.EPDFAnnot_GetBorderEffect(e,t),i=o?this.pdfiumModule.pdfium.getValue(t,"float"):0;return this.free(t),{ok:o,intensity:i}}getRectangleDifferences(e){const t=this.malloc(4),o=this.malloc(4),i=this.malloc(4),n=this.malloc(4),r=!!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(e,t,o,i,n),s=this.pdfiumModule.pdfium,d=s.getValue(t,"float"),a=s.getValue(o,"float"),u=s.getValue(i,"float"),l=s.getValue(n,"float");return this.free(t),this.free(o),this.free(i),this.free(n),{ok:r,left:d,top:a,right:u,bottom:l}}getAnnotationDate(t,o){const i=this.getAnnotString(t,o);return i?e.pdfDateToDate(i):void 0}setAnnotationDate(t,o,i){const n=e.dateToPdfDate(i);return this.setAnnotString(t,o,n)}getBorderDashPattern(e){const t=this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(e);if(0===t)return{ok:!1,pattern:[]};const o=this.malloc(4*t),i=!!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(e,o,t),n=[];if(i){const e=this.pdfiumModule.pdfium;for(let i=0;i<t;i++)n.push(e.getValue(o+4*i,"float"))}return this.free(o),{ok:i,pattern:n}}setBorderDashPattern(e,t){if(!t||0===t.length)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);const o=t.map((e=>Number.isFinite(e)&&e>0?e:0)).filter((e=>e>0));if(0===o.length)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);const i=4*o.length,n=this.malloc(i);for(let s=0;s<o.length;s++)this.pdfiumModule.pdfium.setValue(n+4*s,o[s],"float");const r=!!this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,n,o.length);return this.free(n),r}getLineEndings(e){const t=this.malloc(4),o=this.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetLineEndings(e,t,o))return this.free(t),void this.free(o);const i=this.pdfiumModule.pdfium.getValue(t,"i32"),n=this.pdfiumModule.pdfium.getValue(o,"i32");return this.free(t),this.free(o),{start:i,end:n}}setLineEndings(e,t,o){return!!this.pdfiumModule.EPDFAnnot_SetLineEndings(e,t,o)}getLinePoints(e,t){const o=this.malloc(8),i=this.malloc(8);this.pdfiumModule.FPDFAnnot_GetLine(e,o,i);const n=this.pdfiumModule.pdfium.getValue(o,"float"),r=this.pdfiumModule.pdfium.getValue(o+4,"float"),s=this.convertPagePointToDevicePoint(t,{x:n,y:r}),d=this.pdfiumModule.pdfium.getValue(i,"float"),a=this.pdfiumModule.pdfium.getValue(i+4,"float"),u=this.convertPagePointToDevicePoint(t,{x:d,y:a});return this.free(o),this.free(i),{start:s,end:u}}setLinePoints(e,t,o,i){const n=this.malloc(16),r=this.convertDevicePointToPagePoint(e,o),s=this.convertDevicePointToPagePoint(e,i);this.pdfiumModule.pdfium.setValue(n+0,r.x,"float"),this.pdfiumModule.pdfium.setValue(n+4,r.y,"float"),this.pdfiumModule.pdfium.setValue(n+8,s.x,"float"),this.pdfiumModule.pdfium.setValue(n+12,s.y,"float");const d=this.pdfiumModule.EPDFAnnot_SetLine(t,n,n+8);return this.free(n),d}getQuadPointsAnno(t,o){const i=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(o);if(0===i)return[];const n=[];for(let e=0;e<i;e++){const i=this.malloc(32);if(this.pdfiumModule.FPDFAnnot_GetAttachmentPoints(o,e,i)){const e=[],o=[];for(let t=0;t<4;t++){const n=i+8*t;e.push(this.pdfiumModule.pdfium.getValue(n,"float")),o.push(this.pdfiumModule.pdfium.getValue(n+4,"float"))}const r=this.convertPagePointToDevicePoint(t,{x:e[0],y:o[0]}),s=this.convertPagePointToDevicePoint(t,{x:e[1],y:o[1]}),d=this.convertPagePointToDevicePoint(t,{x:e[2],y:o[2]}),a=this.convertPagePointToDevicePoint(t,{x:e[3],y:o[3]});n.push({p1:r,p2:s,p3:d,p4:a})}this.free(i)}return n.map(e.quadToRect)}syncQuadPointsAnno(t,o,i){const n=this.pdfiumModule.pdfium,r=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(o),s=this.malloc(32),d=o=>{const i=e.rectToQuad(o),r=this.convertDevicePointToPagePoint(t,i.p1),d=this.convertDevicePointToPagePoint(t,i.p2),a=this.convertDevicePointToPagePoint(t,i.p3),u=this.convertDevicePointToPagePoint(t,i.p4);n.setValue(s+0,r.x,"float"),n.setValue(s+4,r.y,"float"),n.setValue(s+8,d.x,"float"),n.setValue(s+12,d.y,"float"),n.setValue(s+16,u.x,"float"),n.setValue(s+20,u.y,"float"),n.setValue(s+24,a.x,"float"),n.setValue(s+28,a.y,"float")},a=Math.min(r,i.length);for(let e=0;e<a;e++)if(d(i[e]),!this.pdfiumModule.FPDFAnnot_SetAttachmentPoints(o,e,s))return this.free(s),!1;for(let e=r;e<i.length;e++)if(d(i[e]),!this.pdfiumModule.FPDFAnnot_AppendAttachmentPoints(o,s))return this.free(s),!1;return this.free(s),!0}redactTextInRects(t,o,i,n){const{recurseForms:r=!0,drawBlackBoxes:s=!1}=n??{};this.logger.debug("PDFiumEngine","Engine","redactTextInQuads",t.id,o.index,i.length);const d="RedactTextInQuads";this.logger.perf("PDFiumEngine","Engine",d,"Begin",`${t.id}-${o.index}`);const a=this.cache.getContext(t.id);if(!a)return this.logger.perf("PDFiumEngine","Engine",d,"End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const u=(i??[]).filter((e=>{var t,o,i,n;return e&&Number.isFinite(null==(t=e.origin)?void 0:t.x)&&Number.isFinite(null==(o=e.origin)?void 0:o.y)&&Number.isFinite(null==(i=e.size)?void 0:i.width)&&Number.isFinite(null==(n=e.size)?void 0:n.height)&&e.size.width>0&&e.size.height>0}));if(0===u.length)return this.logger.perf("PDFiumEngine","Engine",d,"End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(!1);const l=a.acquirePage(o.index),{ptr:h,count:f}=this.allocFSQuadsBufferFromRects(o,u);let g=!1;try{g=!!this.pdfiumModule.EPDFText_RedactInQuads(l.pagePtr,h,f,!!r,!!s)}finally{this.free(h)}return g&&(g=!!this.pdfiumModule.FPDFPage_GenerateContent(l.pagePtr)),l.disposeImmediate(),this.logger.perf("PDFiumEngine","Engine",d,"End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(!!g)}allocFSQuadsBufferFromRects(t,o){const i=o.length,n=this.malloc(32*i),r=this.pdfiumModule.pdfium;for(let s=0;s<i;s++){const i=o[s],d=e.rectToQuad(i),a=this.convertDevicePointToPagePoint(t,d.p1),u=this.convertDevicePointToPagePoint(t,d.p2),l=this.convertDevicePointToPagePoint(t,d.p3),h=this.convertDevicePointToPagePoint(t,d.p4),f=n+32*s;r.setValue(f+0,a.x,"float"),r.setValue(f+4,a.y,"float"),r.setValue(f+8,u.x,"float"),r.setValue(f+12,u.y,"float"),r.setValue(f+16,h.x,"float"),r.setValue(f+20,h.y,"float"),r.setValue(f+24,l.x,"float"),r.setValue(f+28,l.y,"float")}return{ptr:n,count:i}}getInkList(e,t){const o=[],i=this.pdfiumModule.FPDFAnnot_GetInkListCount(t);for(let n=0;n<i;n++){const i=[],r=this.pdfiumModule.FPDFAnnot_GetInkListPath(t,n,0,0);if(r>0){const o=8,s=this.malloc(r*o);this.pdfiumModule.FPDFAnnot_GetInkListPath(t,n,s,r);for(let t=0;t<r;t++){const o=this.pdfiumModule.pdfium.getValue(s+8*t,"float"),n=this.pdfiumModule.pdfium.getValue(s+8*t+4,"float"),{x:r,y:d}=this.convertPagePointToDevicePoint(e,{x:o,y:n});i.push({x:r,y:d})}this.free(s)}o.push({points:i})}return o}setInkList(e,t,o){for(const i of o){const o=i.points.length,n=this.malloc(8*o);for(let t=0;t<o;t++){const o=i.points[t],{x:r,y:s}=this.convertDevicePointToPagePoint(e,o);this.pdfiumModule.pdfium.setValue(n+8*t,r,"float"),this.pdfiumModule.pdfium.setValue(n+8*t+4,s,"float")}if(-1===this.pdfiumModule.FPDFAnnot_AddInkStroke(t,n,o))return this.free(n),!1;this.free(n)}return!0}readPdfTextAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getAnnotString(o,"Contents")||"",h=this.getAnnotString(o,"State"),f=this.getAnnotString(o,"StateModel"),g=this.getAnnotationColor(o),c=this.getAnnotationOpacity(o),p=this.getInReplyToId(o),m=this.getAnnotationFlags(o),P=this.getAnnotationIcon(o);return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.TEXT,flags:m,contents:l,color:g??"#FFFF00",opacity:c,rect:s,inReplyToId:p,author:d,modified:a,created:u,state:h,stateModel:f,icon:P}}readPdfFreeTextAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"Contents")||"",a=this.getAnnotString(o,"T"),u=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),h=this.getAnnotString(o,"DS"),f=this.getAnnotationDefaultAppearance(o),g=this.getAnnotationColor(o),c=this.getAnnotationTextAlignment(o),p=this.getAnnotationVerticalAlignment(o),m=this.getAnnotationOpacity(o),P=this.getAnnotRichContent(o),F=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.FREETEXT,fontFamily:(null==f?void 0:f.fontFamily)??e.PdfStandardFont.Unknown,fontSize:(null==f?void 0:f.fontSize)??12,fontColor:(null==f?void 0:f.fontColor)??"#000000",verticalAlign:p,backgroundColor:g,flags:F,opacity:m,textAlign:c,defaultStyle:h,richContent:P,contents:d,author:a,modified:u,created:l,rect:s}}readPdfLinkAnno(t,o,i,n){const r=this.getAnnotCustom(i),s=this.pdfiumModule.FPDFAnnot_GetLink(i);if(!s)return;const d=this.readPageAnnoRect(i),a=this.convertPageRectToDeviceRect(t,d),u=this.getAnnotString(i,"T"),l=this.getAnnotationDate(i,"M"),h=this.getAnnotationDate(i,"CreationDate"),f=this.getAnnotationFlags(i),g=this.readPdfLinkAnnoTarget(o,(()=>this.pdfiumModule.FPDFLink_GetAction(s)),(()=>this.pdfiumModule.FPDFLink_GetDest(o,s)));return{pageIndex:t.index,custom:r,id:n,type:e.PdfAnnotationSubtype.LINK,flags:f,target:g,rect:a,author:u,modified:l,created:h}}readPdfWidgetAnno(t,o,i,n){const r=this.getAnnotCustom(o),s=this.readPageAnnoRect(o),d=this.convertPageRectToDeviceRect(t,s),a=this.getAnnotString(o,"T"),u=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),h=this.getAnnotationFlags(o),f=this.readPdfWidgetAnnoField(i,o);return{pageIndex:t.index,custom:r,id:n,type:e.PdfAnnotationSubtype.WIDGET,flags:h,rect:d,field:f,author:a,modified:u,created:l}}readPdfFileAttachmentAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.FILEATTACHMENT,flags:l,rect:s,author:d,modified:a,created:u}}readPdfInkAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getAnnotationColor(o),h=this.getAnnotationOpacity(o),{width:f}=this.getBorderStyle(o),g=this.getInkList(t,o),c=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),p=this.getAnnotIntent(o),m=this.getAnnotationFlags(o),P=this.getAnnotString(o,"Contents")||"";return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.INK,...p&&{intent:p},contents:P,blendMode:c,flags:m,color:l??"#FF0000",opacity:h,strokeWidth:0===f?1:f,rect:s,inkList:g,author:d,modified:a,created:u}}readPdfPolygonAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.readPdfAnnoVertices(t,o),h=this.getAnnotString(o,"Contents")||"",f=this.getAnnotationFlags(o),g=this.getAnnotationColor(o),c=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),p=this.getAnnotationOpacity(o);let m,{style:P,width:F}=this.getBorderStyle(o);if(P===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(m=t)}if(l.length>1){const e=l[0],t=l[l.length-1];e.x===t.x&&e.y===t.y&&l.pop()}return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.POLYGON,contents:h,flags:f,strokeColor:g??"#FF0000",color:c??"transparent",opacity:p,strokeWidth:0===F?1:F,strokeStyle:P,strokeDashArray:m,rect:s,vertices:l,author:d,modified:a,created:u}}readPdfPolylineAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.readPdfAnnoVertices(t,o),h=this.getAnnotString(o,"Contents")||"",f=this.getAnnotationColor(o),g=this.getAnnotationFlags(o),c=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),p=this.getAnnotationOpacity(o);let m,{style:P,width:F}=this.getBorderStyle(o);if(P===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(m=t)}const A=this.getLineEndings(o);return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.POLYLINE,contents:h,flags:g,strokeColor:f??"#FF0000",color:c??"transparent",opacity:p,strokeWidth:0===F?1:F,strokeStyle:P,strokeDashArray:m,lineEndings:A,rect:s,vertices:l,author:d,modified:a,created:u}}readPdfLineAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getLinePoints(o,t),h=this.getLineEndings(o),f=this.getAnnotString(o,"Contents")||"",g=this.getAnnotationColor(o),c=this.getAnnotationFlags(o),p=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),m=this.getAnnotationOpacity(o);let P,{style:F,width:A}=this.getBorderStyle(o);if(F===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(P=t)}return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.LINE,flags:c,rect:s,contents:f,strokeWidth:0===A?1:A,strokeStyle:F,strokeDashArray:P,strokeColor:g??"#FF0000",color:p??"transparent",opacity:m,linePoints:l||{start:{x:0,y:0},end:{x:0,y:0}},lineEndings:h||{start:e.PdfAnnotationLineEnding.None,end:e.PdfAnnotationLineEnding.None},author:d,modified:a,created:u}}readPdfHighlightAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getQuadPointsAnno(t,o),a=this.getAnnotationColor(o),u=this.getAnnotationOpacity(o),l=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),h=this.getAnnotString(o,"T"),f=this.getAnnotationDate(o,"M"),g=this.getAnnotationDate(o,"CreationDate"),c=this.getAnnotString(o,"Contents")||"",p=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:n,id:i,blendMode:l,type:e.PdfAnnotationSubtype.HIGHLIGHT,rect:s,flags:p,contents:c,segmentRects:d,color:a??"#FFFF00",opacity:u,author:h,modified:f,created:g}}readPdfUnderlineAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getQuadPointsAnno(t,o),h=this.getAnnotString(o,"Contents")||"",f=this.getAnnotationColor(o),g=this.getAnnotationOpacity(o),c=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),p=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:n,id:i,blendMode:c,type:e.PdfAnnotationSubtype.UNDERLINE,rect:s,flags:p,contents:h,segmentRects:l,color:f??"#FF0000",opacity:g,author:d,modified:a,created:u}}readPdfStrikeOutAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getQuadPointsAnno(t,o),h=this.getAnnotString(o,"Contents")||"",f=this.getAnnotationColor(o),g=this.getAnnotationOpacity(o),c=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),p=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:n,id:i,blendMode:c,type:e.PdfAnnotationSubtype.STRIKEOUT,flags:p,rect:s,contents:h,segmentRects:l,color:f??"#FF0000",opacity:g,author:d,modified:a,created:u}}readPdfSquigglyAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getQuadPointsAnno(t,o),h=this.getAnnotString(o,"Contents")||"",f=this.getAnnotationColor(o),g=this.getAnnotationOpacity(o),c=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),p=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:n,id:i,blendMode:c,type:e.PdfAnnotationSubtype.SQUIGGLY,rect:s,flags:p,contents:h,segmentRects:l,color:f??"#FF0000",opacity:g,author:d,modified:a,created:u}}readPdfCaretAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.CARET,rect:s,flags:l,author:d,modified:a,created:u}}readPdfStampAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getAnnotationFlags(o),h=this.getAnnotString(o,"Contents")||"";return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.STAMP,contents:h,rect:s,author:d,modified:a,created:u,flags:l}}readPdfPageObject(t){switch(this.pdfiumModule.FPDFPageObj_GetType(t)){case e.PdfPageObjectType.PATH:return this.readPathObject(t);case e.PdfPageObjectType.IMAGE:return this.readImageObject(t);case e.PdfPageObjectType.FORM:return this.readFormObject(t)}}readPathObject(t){const o=this.pdfiumModule.FPDFPath_CountSegments(t),i=this.malloc(4),n=this.malloc(4),r=this.malloc(4),s=this.malloc(4);this.pdfiumModule.FPDFPageObj_GetBounds(t,i,n,r,s);const d={left:this.pdfiumModule.pdfium.getValue(i,"float"),bottom:this.pdfiumModule.pdfium.getValue(n,"float"),right:this.pdfiumModule.pdfium.getValue(r,"float"),top:this.pdfiumModule.pdfium.getValue(s,"float")};this.free(i),this.free(n),this.free(r),this.free(s);const a=[];for(let e=0;e<o;e++){const o=this.readPdfSegment(t,e);a.push(o)}const u=this.readPdfPageObjectTransformMatrix(t);return{type:e.PdfPageObjectType.PATH,bounds:d,segments:a,matrix:u}}readPdfSegment(e,t){const o=this.pdfiumModule.FPDFPath_GetPathSegment(e,t),i=this.pdfiumModule.FPDFPathSegment_GetType(o),n=this.pdfiumModule.FPDFPathSegment_GetClose(o),r=this.malloc(4),s=this.malloc(4);this.pdfiumModule.FPDFPathSegment_GetPoint(o,r,s);const d=this.pdfiumModule.pdfium.getValue(r,"float"),a=this.pdfiumModule.pdfium.getValue(s,"float");return this.free(r),this.free(s),{type:i,point:{x:d,y:a},isClosed:n}}readImageObject(t){const o=this.pdfiumModule.FPDFImageObj_GetBitmap(t),i=this.pdfiumModule.FPDFBitmap_GetBuffer(o),n=this.pdfiumModule.FPDFBitmap_GetWidth(o),r=this.pdfiumModule.FPDFBitmap_GetHeight(o),s=this.pdfiumModule.FPDFBitmap_GetFormat(o),d=n*r,a=new Uint8ClampedArray(4*d);for(let e=0;e<d;e++)if(2===s){const t=this.pdfiumModule.pdfium.getValue(i+3*e,"i8"),o=this.pdfiumModule.pdfium.getValue(i+3*e+1,"i8"),n=this.pdfiumModule.pdfium.getValue(i+3*e+2,"i8");a[4*e]=n,a[4*e+1]=o,a[4*e+2]=t,a[4*e+3]=100}const u=new ImageData(a,n,r),l=this.readPdfPageObjectTransformMatrix(t);return{type:e.PdfPageObjectType.IMAGE,imageData:u,matrix:l}}readFormObject(t){const o=this.pdfiumModule.FPDFFormObj_CountObjects(t),i=[];for(let e=0;e<o;e++){const o=this.pdfiumModule.FPDFFormObj_GetObject(t,e),n=this.readPdfPageObject(o);n&&i.push(n)}const n=this.readPdfPageObjectTransformMatrix(t);return{type:e.PdfPageObjectType.FORM,objects:i,matrix:n}}readPdfPageObjectTransformMatrix(e){const t=this.malloc(24);if(this.pdfiumModule.FPDFPageObj_GetMatrix(e,t)){const e=this.pdfiumModule.pdfium.getValue(t,"float"),o=this.pdfiumModule.pdfium.getValue(t+4,"float"),i=this.pdfiumModule.pdfium.getValue(t+8,"float"),n=this.pdfiumModule.pdfium.getValue(t+12,"float"),r=this.pdfiumModule.pdfium.getValue(t+16,"float"),s=this.pdfiumModule.pdfium.getValue(t+20,"float");return this.free(t),{a:e,b:o,c:i,d:n,e:r,f:s}}return this.free(t),{a:1,b:0,c:0,d:1,e:0,f:0}}readStampAnnotationContents(e){const t=[],o=this.pdfiumModule.FPDFAnnot_GetObjectCount(e);for(let i=0;i<o;i++){const o=this.pdfiumModule.FPDFAnnot_GetObject(e,i),n=this.readPdfPageObject(o);n&&t.push(n)}return t}getStrokeWidth(e){const t=this.malloc(4),o=this.malloc(4),i=this.malloc(4),n=this.pdfiumModule.FPDFAnnot_GetBorder(e,t,o,i)?this.pdfiumModule.pdfium.getValue(i,"float"):1;return this.free(t),this.free(o),this.free(i),n}getAnnotationFlags(t){const o=this.pdfiumModule.FPDFAnnot_GetFlags(t);return e.flagsToNames(o)}setAnnotationFlags(t,o){const i=e.namesToFlags(o);return this.pdfiumModule.FPDFAnnot_SetFlags(t,i)}readPdfCircleAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.getAnnotationFlags(o),s=this.readPageAnnoRect(o),d=this.convertPageRectToDeviceRect(t,s),a=this.getAnnotString(o,"T"),u=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),h=this.getAnnotString(o,"Contents")||"",f=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),g=this.getAnnotationColor(o),c=this.getAnnotationOpacity(o);let p,{style:m,width:P}=this.getBorderStyle(o);if(m===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(p=t)}return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.CIRCLE,flags:r,color:f??"transparent",opacity:c,contents:h,strokeWidth:P,strokeColor:g??"#FF0000",strokeStyle:m,rect:d,author:a,modified:u,created:l,...void 0!==p&&{strokeDashArray:p}}}readPdfSquareAnno(t,o,i){const n=this.getAnnotCustom(o),r=this.getAnnotationFlags(o),s=this.readPageAnnoRect(o),d=this.convertPageRectToDeviceRect(t,s),a=this.getAnnotString(o,"T"),u=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),h=this.getAnnotString(o,"Contents")||"",f=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),g=this.getAnnotationColor(o),c=this.getAnnotationOpacity(o);let p,{style:m,width:P}=this.getBorderStyle(o);if(m===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(p=t)}return{pageIndex:t.index,custom:n,id:i,type:e.PdfAnnotationSubtype.SQUARE,flags:r,color:f??"transparent",opacity:c,contents:h,strokeColor:g??"#FF0000",strokeWidth:P,strokeStyle:m,rect:d,author:a,modified:u,created:l,...void 0!==p&&{strokeDashArray:p}}}readPdfAnno(e,t,o,i){const n=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(e,r),d=this.getAnnotString(o,"T"),a=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),l=this.getAnnotationFlags(o);return{pageIndex:e.index,custom:n,id:i,flags:l,type:t,rect:s,author:d,modified:a,created:u}}getInReplyToId(e){const t=this.pdfiumModule.FPDFAnnot_GetLinkedAnnot(e,"IRT");if(t)return this.getAnnotString(t,"NM")}setInReplyToId(e,t,o){const i=this.getAnnotationByName(e,o);return!!i&&this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(t,"IRT",i)}getAnnotString(e,t){const o=this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,0,0);if(0===o)return;const i=2*(o+1),n=this.malloc(i);this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,n,i);const r=this.pdfiumModule.pdfium.UTF16ToString(n);return this.free(n),r||void 0}getAnnotCustom(e){const t=this.getAnnotString(e,"EPDFCustom");if(t)try{return JSON.parse(t)}catch(o){return console.warn("Failed to parse annotation custom data as JSON:",o),void console.warn("Invalid JSON string:",t)}}setAnnotCustom(e,t){if(null==t)return this.setAnnotString(e,"EPDFCustom","");try{const o=JSON.stringify(t);return this.setAnnotString(e,"EPDFCustom",o)}catch(o){return console.warn("Failed to stringify annotation custom data as JSON:",o),console.warn("Invalid data object:",t),!1}}getAnnotIntent(e){const t=this.pdfiumModule.EPDFAnnot_GetIntent(e,0,0);if(0===t)return;const o=2*(t+1),i=this.malloc(o);this.pdfiumModule.EPDFAnnot_GetIntent(e,i,o);const n=this.pdfiumModule.pdfium.UTF16ToString(i);return this.free(i),n&&"undefined"!==n?n:void 0}setAnnotIntent(e,t){return this.pdfiumModule.EPDFAnnot_SetIntent(e,t)}getAnnotRichContent(e){const t=this.pdfiumModule.EPDFAnnot_GetRichContent(e,0,0);if(0===t)return;const o=2*(t+1),i=this.malloc(o);this.pdfiumModule.EPDFAnnot_GetRichContent(e,i,o);const n=this.pdfiumModule.pdfium.UTF16ToString(i);return this.free(i),n||void 0}getAnnotationByName(e,t){const o=2*(t.length+1),i=this.malloc(o);this.pdfiumModule.pdfium.stringToUTF16(t,i,o);const n=this.pdfiumModule.EPDFPage_GetAnnotByName(e,i);return this.free(i),n}removeAnnotationByName(e,t){const o=2*(t.length+1),i=this.malloc(o);this.pdfiumModule.pdfium.stringToUTF16(t,i,o);const n=this.pdfiumModule.EPDFPage_RemoveAnnotByName(e,i);return this.free(i),n}setAnnotString(e,t,o){const i=2*(o.length+1),n=this.malloc(i);this.pdfiumModule.pdfium.stringToUTF16(o,n,i);const r=this.pdfiumModule.FPDFAnnot_SetStringValue(e,t,n);return this.free(n),r}readPdfAnnoVertices(e,t){const o=[],i=this.pdfiumModule.FPDFAnnot_GetVertices(t,0,0),n=this.malloc(8*i);this.pdfiumModule.FPDFAnnot_GetVertices(t,n,i);for(let r=0;r<i;r++){const t=this.pdfiumModule.pdfium.getValue(n+8*r,"float"),i=this.pdfiumModule.pdfium.getValue(n+8*r+4,"float"),{x:s,y:d}=this.convertPagePointToDevicePoint(e,{x:t,y:i}),a=o[o.length-1];a&&a.x===s&&a.y===d||o.push({x:s,y:d})}return this.free(n),o}setPdfAnnoVertices(e,t,o){const i=this.pdfiumModule.pdfium,n=this.malloc(8*o.length);o.forEach(((t,o)=>{const r=this.convertDevicePointToPagePoint(e,t);i.setValue(n+8*o+0,r.x,"float"),i.setValue(n+8*o+4,r.y,"float")}));const r=this.pdfiumModule.EPDFAnnot_SetVertices(t,n,o.length);return this.free(n),r}readPdfBookmarkTarget(e,t,o){const i=t();if(i){return{type:"action",action:this.readPdfAction(e,i)}}{const t=o();if(t){return{type:"destination",destination:this.readPdfDestination(e,t)}}}}readPdfWidgetAnnoField(o,i){const n=this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(o,i),r=this.pdfiumModule.FPDFAnnot_GetFormFieldType(o,i),s=t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFAnnot_GetFormFieldName(o,i,e,t)),this.pdfiumModule.pdfium.UTF16ToString),d=t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(o,i,e,t)),this.pdfiumModule.pdfium.UTF16ToString),a=t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFAnnot_GetFormFieldValue(o,i,e,t)),this.pdfiumModule.pdfium.UTF16ToString),u=[];if(r===e.PDF_FORM_FIELD_TYPE.COMBOBOX||r===e.PDF_FORM_FIELD_TYPE.LISTBOX){const e=this.pdfiumModule.FPDFAnnot_GetOptionCount(o,i);for(let n=0;n<e;n++){const e=t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFAnnot_GetOptionLabel(o,i,n,e,t)),this.pdfiumModule.pdfium.UTF16ToString),r=this.pdfiumModule.FPDFAnnot_IsOptionSelected(o,i,n);u.push({label:e,isSelected:r})}}let l=!1;return r!==e.PDF_FORM_FIELD_TYPE.CHECKBOX&&r!==e.PDF_FORM_FIELD_TYPE.RADIOBUTTON||(l=this.pdfiumModule.FPDFAnnot_IsChecked(o,i)),{flag:n,type:r,name:s,alternateName:d,value:a,isChecked:l,options:u}}renderPageAnnotation(t,o,i,n){const{scaleFactor:r=1,rotation:s=e.Rotation.Degree0,dpr:d=1,mode:a=e.AppearanceMode.Normal,imageType:h="image/webp"}=n??{};this.logger.debug(u,l,"renderPageAnnotation",t,o,i,n),this.logger.perf(u,l,"RenderPageAnnotation","Begin",`${t.id}-${o.index}-${i.id}`);const f=new e.Task,g=this.cache.getContext(t.id);if(!g)return this.logger.perf(u,l,"RenderPageAnnotation","End",`${t.id}-${o.index}-${i.id}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const c=g.acquirePage(o.index),p=this.getAnnotationByName(c.pagePtr,i.id);if(!p)return c.release(),this.logger.perf(u,l,"RenderPageAnnotation","End",`${t.id}-${o.index}-${i.id}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.NotFound,message:"annotation not found"});const m=r*d,P=i.rect,F=e.toIntRect(e.transformRect(o.size,P,s,m)),A=F.size.width*F.size.height*4,D=this.malloc(A),M=this.pdfiumModule.FPDFBitmap_CreateEx(F.size.width,F.size.height,4,D,4*F.size.width);this.pdfiumModule.FPDFBitmap_FillRect(M,0,0,F.size.width,F.size.height,0);const C=e.makeMatrix(i.rect,s,m),T=this.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,T,6).set([C.a,C.b,C.c,C.d,C.e,C.f]);const E=!!this.pdfiumModule.EPDF_RenderAnnotBitmap(M,c.pagePtr,p,a,T,16);if(this.free(T),this.pdfiumModule.FPDFBitmap_Destroy(M),this.pdfiumModule.FPDFPage_CloseAnnot(p),c.release(),!E)return this.free(D),this.logger.perf(u,l,"RenderPageAnnotation","End",`${t.id}-${o.index}-${i.id}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:"EPDF_RenderAnnotBitmap failed"});const y=this.pdfiumModule.pdfium.HEAPU8.subarray(D,D+A),x={data:new Uint8ClampedArray(y),width:F.size.width,height:F.size.height};return this.free(D),this.logger.perf(u,l,"RenderPageAnnotation","End",`${t.id}-${o.index}-${i.id}`),this.imageDataConverter(x,h).then((e=>f.resolve(e))).catch((t=>f.reject({code:e.PdfErrorCode.Unknown,message:String(t)}))),f}renderPageRectToImageData(t,o,i,n){const{scaleFactor:r=1,rotation:s=e.Rotation.Degree0,dpr:d=1}=n??{},a=e.toIntRect(e.transformRect(o.size,i,s,r*d)),u=e.toIntSize(e.transformSize(o.size,s,r*d)),l=a.size.width*a.size.height*4,h=this.malloc(l),f=this.pdfiumModule.FPDFBitmap_CreateEx(a.size.width,a.size.height,4,h,4*a.size.width);this.pdfiumModule.FPDFBitmap_FillRect(f,0,0,a.size.width,a.size.height,4294967295);let g=16;(null==n?void 0:n.withAnnotations)&&(g|=1);const c=t.acquirePage(o.index);this.pdfiumModule.FPDF_RenderPageBitmap(f,c.pagePtr,-a.origin.x,-a.origin.y,u.width,u.height,s,g),this.pdfiumModule.FPDFBitmap_Destroy(f),c.release();const p=this.pdfiumModule.pdfium.HEAPU8.subarray(h,h+l),m={data:new Uint8ClampedArray(p),width:a.size.width,height:a.size.height};return this.free(h),m}readPdfLinkAnnoTarget(e,t,o){const i=o();if(i){return{type:"destination",destination:this.readPdfDestination(e,i)}}{const o=t();if(o){return{type:"action",action:this.readPdfAction(e,o)}}}}readPdfAction(o,i){let n;switch(this.pdfiumModule.FPDFAction_GetType(i)){case e.PdfActionType.Unsupported:n={type:e.PdfActionType.Unsupported};break;case e.PdfActionType.Goto:{const t=this.pdfiumModule.FPDFAction_GetDest(o,i);if(t){const i=this.readPdfDestination(o,t);n={type:e.PdfActionType.Goto,destination:i}}else n={type:e.PdfActionType.Unsupported}}break;case e.PdfActionType.RemoteGoto:n={type:e.PdfActionType.Unsupported};break;case e.PdfActionType.URI:{const r=t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFAction_GetURIPath(o,i,e,t)),this.pdfiumModule.pdfium.UTF8ToString);n={type:e.PdfActionType.URI,uri:r}}break;case e.PdfActionType.LaunchAppOrOpenFile:{const o=t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFAction_GetFilePath(i,e,t)),this.pdfiumModule.pdfium.UTF8ToString);n={type:e.PdfActionType.LaunchAppOrOpenFile,path:o}}}return n}readPdfDestination(t,o){const i=this.pdfiumModule.FPDFDest_GetDestPageIndex(t,o),n=this.malloc(4),r=this.malloc(16),s=this.pdfiumModule.FPDFDest_GetView(o,n,r),d=this.pdfiumModule.pdfium.getValue(n,"i32"),a=[];for(let e=0;e<d;e++){const t=r+4*e;a.push(this.pdfiumModule.pdfium.getValue(t,"float"))}if(this.free(n),this.free(r),s===e.PdfZoomMode.XYZ){const e=this.malloc(1),t=this.malloc(1),n=this.malloc(1),r=this.malloc(4),d=this.malloc(4),u=this.malloc(4);if(this.pdfiumModule.FPDFDest_GetLocationInPage(o,e,t,n,r,d,u)){const o=this.pdfiumModule.pdfium.getValue(e,"i8"),l=this.pdfiumModule.pdfium.getValue(t,"i8"),h=this.pdfiumModule.pdfium.getValue(n,"i8"),f=o?this.pdfiumModule.pdfium.getValue(r,"float"):0,g=l?this.pdfiumModule.pdfium.getValue(d,"float"):0,c=h?this.pdfiumModule.pdfium.getValue(u,"float"):0;return this.free(e),this.free(t),this.free(n),this.free(r),this.free(d),this.free(u),{pageIndex:i,zoom:{mode:s,params:{x:f,y:g,zoom:c}},view:a}}return this.free(e),this.free(t),this.free(n),this.free(r),this.free(d),this.free(u),{pageIndex:i,zoom:{mode:s,params:{x:0,y:0,zoom:0}},view:a}}return{pageIndex:i,zoom:{mode:s},view:a}}readPdfAttachment(e,o){const i=this.pdfiumModule.FPDFDoc_GetAttachment(e,o);return{index:o,name:t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFAttachment_GetName(i,e,t)),this.pdfiumModule.pdfium.UTF16ToString),creationDate:t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFAttachment_GetStringValue(i,"CreationDate",e,t)),this.pdfiumModule.pdfium.UTF16ToString),checksum:t(this.pdfiumModule.pdfium,((e,t)=>this.pdfiumModule.FPDFAttachment_GetStringValue(i,"Checksum",e,t)),this.pdfiumModule.pdfium.UTF16ToString)}}convertDevicePointToPagePoint(e,t){return{x:t.x,y:e.size.height-t.y}}convertPagePointToDevicePoint(e,t){return{x:t.x,y:e.size.height-t.y}}convertPageRectToDeviceRect(e,t){const{x:o,y:i}=this.convertPagePointToDevicePoint(e,{x:t.left,y:t.top});return{origin:{x:o,y:i},size:{width:Math.abs(t.right-t.left),height:Math.abs(t.top-t.bottom)}}}readPageAnnoAppearanceStreams(t){return{normal:this.readPageAnnoAppearanceStream(t,e.AppearanceMode.Normal),rollover:this.readPageAnnoAppearanceStream(t,e.AppearanceMode.Rollover),down:this.readPageAnnoAppearanceStream(t,e.AppearanceMode.Down)}}readPageAnnoAppearanceStream(t,o=e.AppearanceMode.Normal){const i=2*(this.pdfiumModule.FPDFAnnot_GetAP(t,o,0,0)+1),n=this.malloc(i);this.pdfiumModule.FPDFAnnot_GetAP(t,o,n,i);const r=this.pdfiumModule.pdfium.UTF16ToString(n);return this.free(n),r}setPageAnnoRect(e,t,o,i){const n=this.malloc(8),r=this.malloc(8);if(!this.pdfiumModule.FPDF_DeviceToPage(t,0,0,e.size.width,e.size.height,0,i.origin.x,i.origin.y,n,r))return this.free(n),this.free(r),!1;const s=this.pdfiumModule.pdfium.getValue(n,"double"),d=this.pdfiumModule.pdfium.getValue(r,"double");this.free(n),this.free(r);const a=this.malloc(16);return this.pdfiumModule.pdfium.setValue(a,s,"float"),this.pdfiumModule.pdfium.setValue(a+4,d,"float"),this.pdfiumModule.pdfium.setValue(a+8,s+i.size.width,"float"),this.pdfiumModule.pdfium.setValue(a+12,d-i.size.height,"float"),this.pdfiumModule.FPDFAnnot_SetRect(o,a)?(this.free(a),!0):(this.free(a),!1)}readPageAnnoRect(e){const t=this.malloc(16),o={left:0,top:0,right:0,bottom:0};return this.pdfiumModule.FPDFAnnot_GetRect(e,t)&&(o.left=this.pdfiumModule.pdfium.getValue(t,"float"),o.top=this.pdfiumModule.pdfium.getValue(t+4,"float"),o.right=this.pdfiumModule.pdfium.getValue(t+8,"float"),o.bottom=this.pdfiumModule.pdfium.getValue(t+12,"float")),this.free(t),o}getHighlightRects(e,t,o,i,n){const r=this.pdfiumModule.FPDFText_CountRects(o,i,n),s=[];for(let d=0;d<r;d++){const i=this.malloc(8),n=this.malloc(8),r=this.malloc(8),a=this.malloc(8);if(!this.pdfiumModule.FPDFText_GetRect(o,d,n,i,r,a)){this.free(n),this.free(i),this.free(r),this.free(a);continue}const u=this.pdfiumModule.pdfium.getValue(n,"double"),l=this.pdfiumModule.pdfium.getValue(i,"double"),h=this.pdfiumModule.pdfium.getValue(r,"double"),f=this.pdfiumModule.pdfium.getValue(a,"double");this.free(n),this.free(i),this.free(r),this.free(a);const g=this.malloc(4),c=this.malloc(4);this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,u,l,g,c);const p=this.pdfiumModule.pdfium.getValue(g,"i32"),m=this.pdfiumModule.pdfium.getValue(c,"i32");this.free(g),this.free(c);const P=Math.ceil(Math.abs(h-u)),F=Math.ceil(Math.abs(l-f));s.push({origin:{x:p,y:m},size:{width:P,height:F}})}return s}searchAllPages(t,o,i){var n;this.logger.debug(u,l,"searchAllPages",t,o,i),this.logger.perf(u,l,"SearchAllPages","Begin",t.id);const r=this.cache.getContext(t.id);if(!r)return this.logger.perf(u,l,"SearchAllPages","End",t.id),e.PdfTaskHelper.resolve({results:[],total:0});const s=2*(o.length+1),d=this.malloc(s);this.pdfiumModule.pdfium.stringToUTF16(o,d,s);const a=(null==(n=null==i?void 0:i.flags)?void 0:n.reduce(((e,t)=>e|t),e.MatchFlag.None))??e.MatchFlag.None,h=e.PdfTaskHelper.create();let f=!1;h.wait((()=>{}),(e=>{"abort"===e.type&&(f=!0)}));const g=[],c=o=>{if(f)return;const i=Math.min(o+100,t.pageCount);try{for(let e=o;e<i&&!f;e++){const o=this.searchAllInPage(r,t.pages[e],d,a);g.push(...o),h.progress({page:e,results:o})}}catch(n){return void(f||(this.free(d),this.logger.perf(u,l,"SearchAllPages","End",t.id),h.reject({code:e.PdfErrorCode.Unknown,message:`Error searching document: ${n}`})))}return f?void 0:i>=t.pageCount?(this.free(d),this.logger.perf(u,l,"SearchAllPages","End",t.id),void h.resolve({results:g,total:g.length})):void setTimeout((()=>c(i)),0)};return setTimeout((()=>c(0)),0),h.wait((()=>{}),(e=>{if("abort"===e.type)try{this.free(d)}catch{}})),h}buildContext(e,t,o,i=30){const n=/[\s\u00A0.,;:!?()\[\]{}<>/\\\-"'`"”\u2013\u2014]/;let r=t;for(;r>0&&n.test(e[r-1]);)r--;let s=0;for(;r>0&&s<i;)r--,n.test(e[r])||s++;r=(t=>{for(;t>0&&!n.test(e[t-1]);)t--;return t})(r);let d=t+o;for(;d<e.length&&n.test(e[d]);)d++;for(s=0;d<e.length&&s<i;)n.test(e[d])||s++,d++;d=(t=>{for(;t<e.length&&!n.test(e[t]);)t++;return t})(d);const a=e.slice(r,t).replace(/\s+/g," ").trimStart(),u=e.slice(t,t+o),l=e.slice(t+o,d).replace(/\s+/g," ").trimEnd();return{before:this.tidy(a),match:this.tidy(u),after:this.tidy(l),truncatedLeft:r>0,truncatedRight:d<e.length}}tidy(e){return e.replace(/-\uFFFE\s*/g,"").replace(/[\uFFFE\u00AD\u200B\u2060\uFEFF]/g,"").replace(/\s+/g," ")}searchAllInPage(e,t,o,i){return e.borrowPage(t.index,(e=>{const n=e.getTextPage(),r=this.pdfiumModule.FPDFText_CountChars(n),s=this.malloc(2*(r+1));this.pdfiumModule.FPDFText_GetText(n,0,r,s);const d=this.pdfiumModule.pdfium.UTF16ToString(s);this.free(s);const a=[],u=this.pdfiumModule.FPDFText_FindStart(n,o,i,0);for(;this.pdfiumModule.FPDFText_FindNext(u);){const o=this.pdfiumModule.FPDFText_GetSchResultIndex(u),i=this.pdfiumModule.FPDFText_GetSchCount(u),r=this.getHighlightRects(t,e.pagePtr,n,o,i),s=this.buildContext(d,o,i);a.push({pageIndex:t.index,charIndex:o,charCount:i,rects:r,context:s})}return this.pdfiumModule.FPDFText_FindClose(u),a}))}preparePrintDocument(t,o){const{includeAnnotations:i=!0,pageRange:n=null}=o??{};this.logger.debug(u,l,"preparePrintDocument",t,o),this.logger.perf(u,l,"PreparePrintDocument","Begin",t.id);const r=this.cache.getContext(t.id);if(!r)return this.logger.perf(u,l,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"Document is not open"});const s=this.pdfiumModule.FPDF_CreateNewDocument();if(!s)return this.logger.perf(u,l,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateNewDoc,message:"Cannot create print document"});try{const o=this.sanitizePageRange(n,t.pageCount);if(!this.pdfiumModule.FPDF_ImportPages(s,r.docPtr,o??"",0))return this.pdfiumModule.FPDF_CloseDocument(s),this.logger.error(u,l,"Failed to import pages for printing"),this.logger.perf(u,l,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantImportPages,message:"Failed to import pages for printing"});if(!i){const o=this.removeAnnotationsFromPrintDocument(s);if(!o.success)return this.pdfiumModule.FPDF_CloseDocument(s),this.logger.error(u,l,`Failed to remove annotations: ${o.error}`),this.logger.perf(u,l,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:`Failed to prepare print document: ${o.error}`});this.logger.debug(u,l,`Removed ${o.annotationsRemoved} annotations from ${o.pagesProcessed} pages`)}const d=this.saveDocument(s);return this.pdfiumModule.FPDF_CloseDocument(s),this.logger.perf(u,l,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.resolve(d)}catch(d){return s&&this.pdfiumModule.FPDF_CloseDocument(s),this.logger.error(u,l,"preparePrintDocument failed",d),this.logger.perf(u,l,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:d instanceof Error?d.message:"Failed to prepare print document"})}}removeAnnotationsFromPrintDocument(e){let t=0,o=0;try{const i=this.pdfiumModule.FPDF_GetPageCount(e);for(let n=0;n<i;n++){const i=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(e,n);if(i<=0){o++;continue}let r=0;for(let o=i-1;o>=0;o--){this.pdfiumModule.EPDFPage_RemoveAnnotRaw(e,n,o)?(r++,t++):this.logger.warn(u,l,`Failed to remove annotation ${o} from page ${n}`)}if(r>0){const t=this.pdfiumModule.FPDF_LoadPage(e,n);t&&(this.pdfiumModule.FPDFPage_GenerateContent(t),this.pdfiumModule.FPDF_ClosePage(t))}o++}return{success:!0,annotationsRemoved:t,pagesProcessed:o}}catch(i){return{success:!1,annotationsRemoved:t,pagesProcessed:o,error:i instanceof Error?i.message:"Unknown error during annotation removal"}}}sanitizePageRange(e,t){if(!e||""===e.trim())return null;try{const o=[],i=e.split(",");for(const e of i){const i=e.trim();if(i.includes("-")){const[e,n]=i.split("-").map((e=>e.trim())),r=parseInt(e,10),s=parseInt(n,10);if(isNaN(r)||isNaN(s)){this.logger.warn(u,l,`Invalid range: ${i}`);continue}const d=Math.max(1,Math.min(r,t)),a=Math.max(1,Math.min(s,t));for(let t=d;t<=a;t++)o.includes(t)||o.push(t)}else{const e=parseInt(i,10);if(isNaN(e)){this.logger.warn(u,l,`Invalid page number: ${i}`);continue}const n=Math.max(1,Math.min(e,t));o.includes(n)||o.push(n)}}if(0===o.length)return this.logger.warn(u,l,"No valid pages in range, using all pages"),null;o.sort(((e,t)=>e-t));const n=[];let r=o[0],s=o[0];for(let e=1;e<o.length;e++)o[e]===s+1||(r===s?n.push(r.toString()):s-r==1?(n.push(r.toString()),n.push(s.toString())):n.push(`${r}-${s}`),r=o[e]),s=o[e];r===s?n.push(r.toString()):s-r==1?(n.push(r.toString()),n.push(s.toString())):n.push(`${r}-${s}`);const d=n.join(",");return this.logger.debug(u,l,`Sanitized page range: "${e}" -> "${d}"`),d}catch(o){return this.logger.error(u,l,`Error sanitizing page range: ${o}`),null}}},exports.PdfiumErrorCode=h,exports.RenderFlag=a,exports.browserImageDataToBlobConverter=f,exports.readArrayBuffer=o,exports.readString=t;
2
- //# sourceMappingURL=engine-Dcn6oo4j.cjs.map