@copio/sdk 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +154 -151
- package/dist/adapters/image/canvas2d-adapter.js +1 -1
- package/dist/adapters/image/index.js +1 -1
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/indexeddb-adapter.js +1 -1
- package/dist/adapters/pdf/index.js +1 -1
- package/dist/adapters/pdf/pdfkit-adapter.js +1 -1
- package/dist/adapters/storage/index.js +1 -1
- package/dist/adapters/storage/indexeddb-adapter.js +1 -1
- package/dist/cdn.js +42 -1119
- package/dist/{chunk-534NMCRQ.js → chunk-G5EUMLYT.js} +2 -2
- package/dist/{chunk-4YYY7PHH.js → chunk-GGERQ3CJ.js} +11 -11
- package/dist/chunk-K4NR6OAC.js +2 -0
- package/dist/chunk-L4OVZN23.js +2 -0
- package/dist/chunk-NQW6FFN7.js +50 -0
- package/dist/{chunk-DOKG4LX2.js → chunk-O7IV7A6O.js} +2 -2
- package/dist/chunk-Q7XPZMZA.js +1395 -0
- package/dist/core.js +1 -1
- package/dist/custom-elements.json +260 -1770
- package/dist/index.js +2 -2
- package/dist/scanner.js +16 -1120
- package/dist/sync.js +1 -1
- package/dist/types/sdk/elements.d.ts +0 -12
- package/dist/types/sdk/index.d.ts +0 -6
- package/dist/types/sdk/scanner.d.ts +2 -7
- package/dist/types/sdk/version.d.ts +1 -1
- package/package.json +2 -2
- package/sdk/index.js +0 -6
- package/sdk/scanner.js +5 -12
- package/sdk/version.js +1 -1
- package/dist/chunk-4XWSVHFW.js +0 -2472
- package/dist/chunk-5KUKBKWL.js +0 -33
- package/dist/chunk-DY5ZSP4Q.js +0 -2
- package/dist/chunk-IH2AI54D.js +0 -2
- package/dist/chunk-RDCHJL6F.js +0 -2
- package/dist/chunk-XEN5VKAV.js +0 -19
- package/dist/types/js/components/copio-header.d.ts +0 -23
- package/dist/types/js/components/copio-loader.d.ts +0 -6
- package/dist/types/js/core/store.d.ts +0 -2
- package/dist/types/js/routes/add-edit/copio-add-edit-dialog.d.ts +0 -9
- package/dist/types/js/routes/doc/copio-carousel.d.ts +0 -42
- package/dist/types/js/routes/doc/copio-images.d.ts +0 -33
- package/dist/types/js/routes/home/copio-row.d.ts +0 -49
- package/dist/types/js/styles/cropper-styles.d.ts +0 -5
package/dist/cdn.js
CHANGED
|
@@ -1,1095 +1,12 @@
|
|
|
1
|
-
var cd=Object.defineProperty;var ti=(s,t,e)=>()=>{if(e)throw e[0];try{return s&&(t=s(s=0)),t}catch(i){throw e=[i],i}};var ei=(s,t)=>{for(var e in t)cd(s,e,{get:t[e],enumerable:!0})};function lo(){return ja}function us(s){typeof s=="string"&&(ja=s.replace(/\/+$/,"")||".")}function li(s){if(!s)return"";if(/^(https?:|\/\/|data:|blob:)/i.test(s))return s;let t=s.replace(/^\/+/,""),e=ja;return!e||e==="."?t:`${e}/${t}`}function Di(s,t){let e=t();if(e)return Promise.resolve(e);if(ao.has(s))return ao.get(s);let i=new Promise((n,o)=>{if(typeof document>"u"){o(new Error(`Cannot load script "${s}" in an environment without DOM document.`));return}let c=li(s),l=document.querySelector(`script[src="${c}"], script[src="${s}"]`);if(l){if(t()){n(t());return}l.addEventListener("load",()=>n(t()),{once:!0}),l.addEventListener("error",()=>o(new Error(`Failed to load "${s}": Network error`)),{once:!0});return}let h=document.createElement("script");h.src=c,h.async=!0,h.onload=()=>{let m=t();n(m)},h.onerror=()=>{ao.delete(s),h.remove(),o(new Error(`Failed to load script "${s}": Network error`))},document.head.appendChild(h)});return ao.set(s,i),i}async function co(){return Di("js/lib/cropper.js",()=>window.Cropper)}async function ho(){return Di("js/lib/pdfkit.js",()=>window.PDFDocument)}async function uo(){return Di("js/lib/jszip.min.js",()=>window.JSZip)}async function po(){return Di("js/lib/peerjs.min.js",()=>window.Peer)}async function fo(){return Di("js/lib/qrcode.js",()=>window.qrcode)}async function go(){return Di("js/lib/tesseract.min.js",()=>window.Tesseract)}var ja,ao,ci=ti(()=>{ja=".";ao=new Map});var fl={};ei(fl,{Path2D:()=>Vu,createCanvas:()=>ju,default:()=>zu});var zu,ju,Vu,gl=ti(()=>{zu={},ju=()=>null,Vu=globalThis.Path2D||class{}});var Ph={};ei(Ph,{Path2D:()=>qu,createCanvas:()=>Gu,default:()=>Wu});var Wu,Gu,qu,kh=ti(()=>{Wu={},Gu=()=>null,qu=globalThis.Path2D||class{}});var Dh={};ei(Dh,{Path2D:()=>Yu,createCanvas:()=>Ku,default:()=>Xu});var Xu,Ku,Yu,Rh=ti(()=>{Xu={},Ku=()=>null,Yu=globalThis.Path2D||class{}});var Mh={};ei(Mh,{Path2D:()=>Zu,createCanvas:()=>Qu,default:()=>Ju});var Ju,Qu,Zu,Ih=ti(()=>{Ju={},Qu=()=>null,Zu=globalThis.Path2D||class{}});var Lh={};ei(Lh,{Path2D:()=>ip,createCanvas:()=>ep,default:()=>tp});var tp,ep,ip,Fh=ti(()=>{tp={},ep=()=>null,ip=globalThis.Path2D||class{}});var Oh={};ei(Oh,{Path2D:()=>rp,createCanvas:()=>np,default:()=>sp});var sp,np,rp,Nh=ti(()=>{sp={},np=()=>null,rp=globalThis.Path2D||class{}});function Oi(s){jh=s||null}function Ni(){return jh||(typeof document<"u"?document.body:null)}function ml(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function zh(s,t={}){let e={};if(typeof s=="string"||s instanceof HTMLElement?e={message:s,...t}:s&&typeof s=="object"&&(e={...s,...t}),typeof customElements<"u"&&!customElements.get("sl-alert")&&await Promise.race([customElements.whenDefined("sl-alert"),new Promise(a=>setTimeout(a,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return null;let i=customElements.get("sl-alert"),n=e.variant||"info",o=Hh[n]||Hh.info,c=e.container||Ni();if(i?.toastStack&&c){let a=i.toastStack;a.parentElement!==c&&c.appendChild(a),c!==document.body?(a.style.position="absolute",a.style.width="auto",a.style.maxWidth="calc(100% - 24px)",a.style.left="12px",a.style.right="12px",a.style.insetInlineStart="12px",a.style.insetInlineEnd="12px",e.position==="top"?(a.style.top="12px",a.style.bottom="auto"):(a.style.top="auto",a.style.bottom="16px"),a.style.maxHeight="100%",a.style.overflow="auto"):(a.style.position="",a.style.width="",a.style.left="",a.style.right="",a.style.top="",a.style.bottom="",a.style.insetInlineStart="",a.style.insetInlineEnd="",a.style.maxHeight="",a.style.maxWidth="",a.style.overflow="")}let l=document.createElement("sl-alert");l.variant=o.slVariant,l.closable=e.closable!==!1,l.duration=e.duration!==void 0?e.duration:o.defaultDuration;let h=e.icon!==void 0?e.icon:o.defaultIcon;if(h){let a=document.createElement("sl-icon");a.slot="icon",a.name=h,l.appendChild(a)}let m=document.createElement("span");if(e.message instanceof HTMLElement?m.appendChild(e.message):e.html?m.innerHTML=e.message||"":m.textContent=e.message||"",e.action){let a=document.createElement("div");a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="space-between",a.style.gap="0.75rem",a.style.width="100%",m.style.flex="1",a.appendChild(m);let f=document.createElement("sl-button");f.size="small",f.variant=e.action.variant||"text",f.textContent=e.action.text||"Action",f.style.color="inherit",f.style.fontWeight="600",f.style.padding="0",f.addEventListener("click",w=>{w.preventDefault(),w.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(w,l),e.action.autoClose!==!1&&l.hide()}),a.appendChild(f),l.appendChild(a)}else l.appendChild(m);let u=l.toast();return l.toastPromise=u,l}function lp(s,t={}){return Mt.show({message:s,variant:"success",...t})}function cp(s,t={}){return Mt.show({message:s,variant:"error",...t})}function hp(s,t={}){return Mt.show({message:s,variant:"warning",...t})}function dp(s,t={}){return Mt.show({message:s,variant:"info",...t})}function up(s,t,e={}){return Mt.show({message:s,variant:e?.variant||"primary",icon:e?.icon!==void 0?e.icon:"arrow-counterclockwise",duration:e?.duration!==void 0?e.duration:5e3,closable:e?.closable!==!1,action:{text:e?.actionText||"Undo",onClick:(i,n)=>{typeof t=="function"&&t(i,n)},autoClose:!0},...e})}async function pp(s,t={}){let e={};if(typeof s=="string"?e={message:s,...t}:s&&typeof s=="object"&&(e={...s,...t}),typeof customElements<"u"&&(!customElements.get("sl-alert")||!customElements.get("sl-progress-bar"))&&await Promise.race([Promise.all([customElements.whenDefined("sl-alert"),customElements.whenDefined("sl-progress-bar")]),new Promise(p=>setTimeout(p,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||Ni(),n=document.createElement("sl-alert");n.variant=e.variant||"primary",n.closable=e.closable===!0,n.duration=1/0;let o=e.icon!==void 0?e.icon:"arrow-down-circle";if(o){let p=document.createElement("sl-icon");p.slot="icon",p.name=o,n.appendChild(p)}let c=document.createElement("div");c.className="notify-progress-wrapper",c.style.display="flex",c.style.flexDirection="column",c.style.gap="0.35rem",c.style.minWidth="220px";let l=document.createElement("div");l.style.display="flex",l.style.justifyContent="space-between",l.style.alignItems="center",l.style.gap="0.5rem";let h=document.createElement("span");h.className="notify-progress-message",h.style.fontWeight="500",h.style.fontSize="0.9rem",h.textContent=e.message||"Processing...",l.appendChild(h);let m=document.createElement("span");m.className="notify-progress-status",m.style.fontSize="0.78rem",m.style.color="#64748b",m.style.fontWeight="600";let u=e.done!==void 0?e.done:0,a=e.total!==void 0?e.total:0;a>0?m.textContent=`${u} / ${a}`:e.value!==void 0&&(m.textContent=`${e.value}%`),l.appendChild(m),c.appendChild(l);let f=document.createElement("sl-progress-bar");a>0?f.value=Math.round(u/a*100):e.value!==void 0?f.value=e.value:f.indeterminate=!0,c.appendChild(f),n.appendChild(c);let w=customElements.get("sl-alert");if(w?.toastStack&&i){let p=w.toastStack;p.parentElement!==i&&i.appendChild(p)}return n.toast(),{alert:n,progressBar:f,update({done:p,total:y,value:r,message:d}={}){if(d!==void 0&&(h.textContent=d),y!==void 0&&p!==void 0){f.indeterminate=!1;let b=Math.min(100,Math.max(0,Math.round(p/Math.max(y,1)*100)));f.value=b,m.textContent=`${p} / ${y}`}else r!==void 0&&(f.indeterminate=!1,f.value=Math.min(100,Math.max(0,r)),m.textContent=`${Math.round(f.value)}%`)},close(){typeof n.hide=="function"&&n.hide()}}}var jh,Hh,Mt,Bi=ti(()=>{jh=null,Hh={success:{slVariant:"success",defaultIcon:"check-circle",defaultDuration:3e3},error:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},danger:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},warning:{slVariant:"warning",defaultIcon:"exclamation-triangle",defaultDuration:4e3},info:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},primary:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},neutral:{slVariant:"neutral",defaultIcon:"info-circle",defaultDuration:4e3}};Mt=Object.assign(function(s,t){return zh(s,t)},{show:zh,success:lp,error:cp,warning:hp,info:dp,undo:up,progress:pp,clear:ml,setContainer:Oi,getContainer:Ni})});var od={};ei(od,{SUPPORTED_LANGUAGES:()=>ar,getOcrWorker:()=>hn,recognizeDocumentPages:()=>Ss,recognizeImageText:()=>dn,terminateOcrWorker:()=>ji});function Rp(s){return s==="eng"?li("assets/tessdata"):"https://tessdata.projectnaptha.com/4.0.0_fast"}function Mp(s,t=0){let e=Math.round((t||0)*100);switch(s){case"loading tesseract core":return`Downloading OCR engine... ${e>0?e+"%":""}`.trim();case"initializing tesseract":return"Initializing OCR engine...";case"loading language traineddata":case"loaded language traineddata":return`Loading language data... ${e>0?e+"%":""}`.trim();case"initializing api":return"Preparing text recognition...";case"recognizing text":return`Recognizing text... ${e}%`;default:return s&&s.includes("recognizing")?`Recognizing text... ${e}%`:s?`${s.charAt(0).toUpperCase()+s.slice(1)}...`:"Processing..."}}async function hn(s="eng",t=null){if(zi=t,Qe&&Ho===s)return Qe;if(Qe){try{await Qe.terminate()}catch(c){console.warn("Error terminating old OCR worker:",c)}Qe=null,Ho=null}let e=null;if(typeof window<"u"&&!window.Tesseract){zi&&typeof zi=="function"&&zi({status:"downloading-engine",progress:.05,message:"Downloading OCR engine..."});try{e=await Mt.progress({message:"Downloading OCR engine...",total:100,done:0})}catch{}}let n,o;try{n=await go();let c=Rp(s);o=await n.createWorker(s,1,{workerPath:li("js/lib/tesseract-worker.min.js"),corePath:li("js/lib/tesseract-core"),langPath:c,logger:l=>{if(e&&l.status==="loading tesseract core"){let h=Math.round((l.progress||0)*100);e.update(h,100,`Downloading OCR engine... ${h>0?h+"%":""}`.trim())}if(zi&&typeof zi=="function"){let h=Mp(l.status,l.progress);zi({status:l.status,progress:typeof l.progress=="number"?l.progress:0,message:h,raw:l})}}})}finally{e?.close()}return Qe=o,Ho=s,Qe}async function dn(s,t={}){let{lang:e="eng",onProgress:i=null,abortSignal:n=null}=t;if(n?.aborted){let h=new Error("OCR operation cancelled by user");throw h.name="AbortError",h}i&&i({status:"starting",progress:.05,message:"Starting OCR engine..."});let o=await hn(e,i);if(n?.aborted){let h=new Error("OCR operation cancelled by user");throw h.name="AbortError",h}i&&i({status:"recognizing text",progress:.2,message:"Recognizing text..."});let c=null,l=new Promise((h,m)=>{n&&(c=()=>{ji();let u=new Error("OCR operation cancelled by user");u.name="AbortError",m(u)},n.addEventListener("abort",c,{once:!0}))});try{let m=(await Promise.race([o.recognize(s),l]))?.data||{},u=(m.text||"").trim(),a=Math.round(m.confidence||0);i&&i({status:"done",progress:1,message:"Text recognition complete!"});let f=(m.words||[]).map(w=>({text:(w.text||"").trim(),confidence:Math.round(w.confidence||0),bbox:{x0:w.bbox?.x0??0,y0:w.bbox?.y0??0,x1:w.bbox?.x1??0,y1:w.bbox?.y1??0},baseline:w.baseline?{x0:w.baseline.x0??0,y0:w.baseline.y0??0,x1:w.baseline.x1??0,y1:w.baseline.y1??0}:null})).filter(w=>w.text.length>0);return{text:u,confidence:a,words:f,lines:m.lines||[],paragraphs:m.paragraphs||[],hocr:m.hocr||""}}finally{n&&c&&n.removeEventListener("abort",c)}}async function Ss(s,t={}){let{lang:e="eng",onPageProgress:i=null,abortSignal:n=null}=t,o=(s||[]).filter(u=>u.blob||u.src);if(o.length===0)return{pagesResults:[],combinedText:"",averageConfidence:0,empty:!0};let c=[],l=0;for(let u=0;u<o.length;u++){if(n?.aborted){let p=new Error("OCR operation cancelled by user");throw p.name="AbortError",p}let a=o[u],f=u+1,w=o.length,E=await dn(a.blob||a.src,{lang:e,abortSignal:n,onProgress:p=>{if(i){let y=(u+(p.progress||0))/w;i({pageIndex:u,pageNumber:f,totalPages:w,pageProgress:p.progress||0,overallProgress:y,message:`Page ${f} of ${w}: ${p.message}`})}}});c.push({pageId:a.id,pageIndex:u,pageNumber:f,...E}),l+=E.confidence}let h=c.map(u=>c.length>1?`## Page ${u.pageNumber}
|
|
1
|
+
var il=Object.defineProperty;var ke=(n,t,e)=>()=>{if(e)throw e[0];try{return n&&(t=n(n=0)),t}catch(i){throw e=[i],i}};var Re=(n,t)=>{for(var e in t)il(n,e,{get:t[e],enumerable:!0})};function ir(){return va}function Ii(n){typeof n=="string"&&(va=n.replace(/\/+$/,"")||".")}function Ne(n){if(!n)return"";if(/^(https?:|\/\/|data:|blob:)/i.test(n))return n;let t=n.replace(/^\/+/,""),e=va;return!e||e==="."?t:`${e}/${t}`}function ei(n,t){let e=t();if(e)return Promise.resolve(e);if(er.has(n))return er.get(n);let i=new Promise((r,o)=>{if(typeof document>"u"){o(new Error(`Cannot load script "${n}" in an environment without DOM document.`));return}let g=Ne(n),d=document.querySelector(`script[src="${g}"], script[src="${n}"]`);if(d){if(t()){r(t());return}d.addEventListener("load",()=>r(t()),{once:!0}),d.addEventListener("error",()=>o(new Error(`Failed to load "${n}": Network error`)),{once:!0});return}let m=document.createElement("script");m.src=g,m.async=!0,m.onload=()=>{let v=t();r(v)},m.onerror=()=>{er.delete(n),m.remove(),o(new Error(`Failed to load script "${n}": Network error`))},document.head.appendChild(m)});return er.set(n,i),i}async function yc(){return ei("js/lib/cropper.js",()=>window.Cropper)}async function sr(){return ei("js/lib/pdfkit.js",()=>window.PDFDocument)}async function nr(){return ei("js/lib/jszip.min.js",()=>window.JSZip)}async function rr(){return ei("js/lib/peerjs.min.js",()=>window.Peer)}async function ar(){return ei("js/lib/qrcode.js",()=>window.qrcode)}async function or(){return ei("js/lib/tesseract.min.js",()=>window.Tesseract)}var va,er,ii=ke(()=>{va=".";er=new Map});function ri(n){Sc=n||null}function ai(){return Sc||(typeof document<"u"?document.body:null)}function Pa(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function Ac(n,t={}){let e={};if(typeof n=="string"||n instanceof HTMLElement?e={message:n,...t}:n&&typeof n=="object"&&(e={...n,...t}),typeof customElements<"u"&&!customElements.get("sl-alert")&&await Promise.race([customElements.whenDefined("sl-alert"),new Promise(a=>setTimeout(a,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return null;let i=customElements.get("sl-alert"),r=e.variant||"info",o=xc[r]||xc.info,g=e.container||ai();if(i?.toastStack&&g){let a=i.toastStack;a.parentElement!==g&&g.appendChild(a),g!==document.body?(a.style.position="absolute",a.style.width="auto",a.style.maxWidth="calc(100% - 24px)",a.style.left="12px",a.style.right="12px",a.style.insetInlineStart="12px",a.style.insetInlineEnd="12px",e.position==="top"?(a.style.top="12px",a.style.bottom="auto"):(a.style.top="auto",a.style.bottom="16px"),a.style.maxHeight="100%",a.style.overflow="auto"):(a.style.position="",a.style.width="",a.style.left="",a.style.right="",a.style.top="",a.style.bottom="",a.style.insetInlineStart="",a.style.insetInlineEnd="",a.style.maxHeight="",a.style.maxWidth="",a.style.overflow="")}let d=document.createElement("sl-alert");d.variant=o.slVariant,d.closable=e.closable!==!1,d.duration=e.duration!==void 0?e.duration:o.defaultDuration;let m=e.icon!==void 0?e.icon:o.defaultIcon;if(m){let a=document.createElement("sl-icon");a.slot="icon",a.name=m,d.appendChild(a)}let v=document.createElement("span");if(e.message instanceof HTMLElement?v.appendChild(e.message):e.html?v.innerHTML=e.message||"":v.textContent=e.message||"",e.action){let a=document.createElement("div");a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="space-between",a.style.gap="0.75rem",a.style.width="100%",v.style.flex="1",a.appendChild(v);let p=document.createElement("sl-button");p.size="small",p.variant=e.action.variant||"text",p.textContent=e.action.text||"Action",p.style.color="inherit",p.style.fontWeight="600",p.style.padding="0",p.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(x,d),e.action.autoClose!==!1&&d.hide()}),a.appendChild(p),d.appendChild(a)}else d.appendChild(v);let u=d.toast();return d.toastPromise=u,d}function dh(n,t={}){return Dt.show({message:n,variant:"success",...t})}function uh(n,t={}){return Dt.show({message:n,variant:"error",...t})}function ph(n,t={}){return Dt.show({message:n,variant:"warning",...t})}function fh(n,t={}){return Dt.show({message:n,variant:"info",...t})}function gh(n,t,e={}){return Dt.show({message:n,variant:e?.variant||"primary",icon:e?.icon!==void 0?e.icon:"arrow-counterclockwise",duration:e?.duration!==void 0?e.duration:5e3,closable:e?.closable!==!1,action:{text:e?.actionText||"Undo",onClick:(i,r)=>{typeof t=="function"&&t(i,r)},autoClose:!0},...e})}async function mh(n,t={}){let e={};if(typeof n=="string"?e={message:n,...t}:n&&typeof n=="object"&&(e={...n,...t}),typeof customElements<"u"&&(!customElements.get("sl-alert")||!customElements.get("sl-progress-bar"))&&await Promise.race([Promise.all([customElements.whenDefined("sl-alert"),customElements.whenDefined("sl-progress-bar")]),new Promise(l=>setTimeout(l,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||ai(),r=document.createElement("sl-alert");r.variant=e.variant||"primary",r.closable=e.closable===!0,r.duration=1/0;let o=e.icon!==void 0?e.icon:"arrow-down-circle";if(o){let l=document.createElement("sl-icon");l.slot="icon",l.name=o,r.appendChild(l)}let g=document.createElement("div");g.className="notify-progress-wrapper",g.style.display="flex",g.style.flexDirection="column",g.style.gap="0.35rem",g.style.minWidth="220px";let d=document.createElement("div");d.style.display="flex",d.style.justifyContent="space-between",d.style.alignItems="center",d.style.gap="0.5rem";let m=document.createElement("span");m.className="notify-progress-message",m.style.fontWeight="500",m.style.fontSize="0.9rem",m.textContent=e.message||"Processing...",d.appendChild(m);let v=document.createElement("span");v.className="notify-progress-status",v.style.fontSize="0.78rem",v.style.color="#64748b",v.style.fontWeight="600";let u=e.done!==void 0?e.done:0,a=e.total!==void 0?e.total:0;a>0?v.textContent=`${u} / ${a}`:e.value!==void 0&&(v.textContent=`${e.value}%`),d.appendChild(v),g.appendChild(d);let p=document.createElement("sl-progress-bar");a>0?p.value=Math.round(u/a*100):e.value!==void 0?p.value=e.value:p.indeterminate=!0,g.appendChild(p),r.appendChild(g);let x=customElements.get("sl-alert");if(x?.toastStack&&i){let l=x.toastStack;l.parentElement!==i&&i.appendChild(l)}return r.toast(),{alert:r,progressBar:p,update({done:l,total:y,value:s,message:c}={}){if(c!==void 0&&(m.textContent=c),y!==void 0&&l!==void 0){p.indeterminate=!1;let f=Math.min(100,Math.max(0,Math.round(l/Math.max(y,1)*100)));p.value=f,v.textContent=`${l} / ${y}`}else s!==void 0&&(p.indeterminate=!1,p.value=Math.min(100,Math.max(0,s)),v.textContent=`${Math.round(p.value)}%`)},close(){typeof r.hide=="function"&&r.hide()}}}var Sc,xc,Dt,Ni=ke(()=>{Sc=null,xc={success:{slVariant:"success",defaultIcon:"check-circle",defaultDuration:3e3},error:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},danger:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},warning:{slVariant:"warning",defaultIcon:"exclamation-triangle",defaultDuration:4e3},info:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},primary:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},neutral:{slVariant:"neutral",defaultIcon:"info-circle",defaultDuration:4e3}};Dt=Object.assign(function(n,t){return Ac(n,t)},{show:Ac,success:dh,error:uh,warning:ph,info:fh,undo:gh,progress:mh,clear:Pa,setContainer:ri,getContainer:ai})});var $c={};Re($c,{SUPPORTED_LANGUAGES:()=>Ys,getOcrWorker:()=>ms,recognizeDocumentPages:()=>Hi,recognizeImageText:()=>bs,terminateOcrWorker:()=>hi});function Lh(n){return n==="eng"?Ne("assets/tessdata"):"https://tessdata.projectnaptha.com/4.0.0_fast"}function Fh(n,t=0){let e=Math.round((t||0)*100);switch(n){case"loading tesseract core":return`Downloading OCR engine... ${e>0?e+"%":""}`.trim();case"initializing tesseract":return"Initializing OCR engine...";case"loading language traineddata":case"loaded language traineddata":return`Loading language data... ${e>0?e+"%":""}`.trim();case"initializing api":return"Preparing text recognition...";case"recognizing text":return`Recognizing text... ${e}%`;default:return n&&n.includes("recognizing")?`Recognizing text... ${e}%`:n?`${n.charAt(0).toUpperCase()+n.slice(1)}...`:"Processing..."}}async function ms(n="eng",t=null){if(li=t,Pe&&mr===n)return Pe;if(Pe){try{await Pe.terminate()}catch(g){console.warn("Error terminating old OCR worker:",g)}Pe=null,mr=null}let e=null;if(typeof window<"u"&&!window.Tesseract){li&&typeof li=="function"&&li({status:"downloading-engine",progress:.05,message:"Downloading OCR engine..."});try{e=await Dt.progress({message:"Downloading OCR engine...",total:100,done:0})}catch{}}let r,o;try{r=await or();let g=Lh(n);o=await r.createWorker(n,1,{workerPath:Ne("js/lib/tesseract-worker.min.js"),corePath:Ne("js/lib/tesseract-core"),langPath:g,logger:d=>{if(e&&d.status==="loading tesseract core"){let m=Math.round((d.progress||0)*100);e.update(m,100,`Downloading OCR engine... ${m>0?m+"%":""}`.trim())}if(li&&typeof li=="function"){let m=Fh(d.status,d.progress);li({status:d.status,progress:typeof d.progress=="number"?d.progress:0,message:m,raw:d})}}})}finally{e?.close()}return Pe=o,mr=n,Pe}async function bs(n,t={}){let{lang:e="eng",onProgress:i=null,abortSignal:r=null}=t;if(r?.aborted){let m=new Error("OCR operation cancelled by user");throw m.name="AbortError",m}i&&i({status:"starting",progress:.05,message:"Starting OCR engine..."});let o=await ms(e,i);if(r?.aborted){let m=new Error("OCR operation cancelled by user");throw m.name="AbortError",m}i&&i({status:"recognizing text",progress:.2,message:"Recognizing text..."});let g=null,d=new Promise((m,v)=>{r&&(g=()=>{hi();let u=new Error("OCR operation cancelled by user");u.name="AbortError",v(u)},r.addEventListener("abort",g,{once:!0}))});try{let v=(await Promise.race([o.recognize(n),d]))?.data||{},u=(v.text||"").trim(),a=Math.round(v.confidence||0);i&&i({status:"done",progress:1,message:"Text recognition complete!"});let p=(v.words||[]).map(x=>({text:(x.text||"").trim(),confidence:Math.round(x.confidence||0),bbox:{x0:x.bbox?.x0??0,y0:x.bbox?.y0??0,x1:x.bbox?.x1??0,y1:x.bbox?.y1??0},baseline:x.baseline?{x0:x.baseline.x0??0,y0:x.baseline.y0??0,x1:x.baseline.x1??0,y1:x.baseline.y1??0}:null})).filter(x=>x.text.length>0);return{text:u,confidence:a,words:p,lines:v.lines||[],paragraphs:v.paragraphs||[],hocr:v.hocr||""}}finally{r&&g&&r.removeEventListener("abort",g)}}async function Hi(n,t={}){let{lang:e="eng",onPageProgress:i=null,abortSignal:r=null}=t,o=(n||[]).filter(u=>u.blob||u.src);if(o.length===0)return{pagesResults:[],combinedText:"",averageConfidence:0,empty:!0};let g=[],d=0;for(let u=0;u<o.length;u++){if(r?.aborted){let l=new Error("OCR operation cancelled by user");throw l.name="AbortError",l}let a=o[u],p=u+1,x=o.length,T=await bs(a.blob||a.src,{lang:e,abortSignal:r,onProgress:l=>{if(i){let y=(u+(l.progress||0))/x;i({pageIndex:u,pageNumber:p,totalPages:x,pageProgress:l.progress||0,overallProgress:y,message:`Page ${p} of ${x}: ${l.message}`})}}});g.push({pageId:a.id,pageIndex:u,pageNumber:p,...T}),d+=T.confidence}let m=g.map(u=>g.length>1?`## Page ${u.pageNumber}
|
|
2
2
|
|
|
3
3
|
${u.text}`:u.text).join(`
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
`),m=Math.round(l/c.length);return{pagesResults:c,combinedText:h,averageConfidence:m}}async function ji(){if(Qe){try{await Qe.terminate()}catch(s){console.warn("Error during OCR worker termination:",s)}Qe=null,Ho=null,zi=null}}var ar,Qe,Ho,zi,lr=ti(()=>{ci();Bi();ar=[{code:"eng",label:"English",flag:"\u{1F1EC}\u{1F1E7}"},{code:"spa",label:"Spanish (Espa\xF1ol)",flag:"\u{1F1EA}\u{1F1F8}"},{code:"fra",label:"French (Fran\xE7ais)",flag:"\u{1F1EB}\u{1F1F7}"},{code:"deu",label:"German (Deutsch)",flag:"\u{1F1E9}\u{1F1EA}"},{code:"ita",label:"Italian (Italiano)",flag:"\u{1F1EE}\u{1F1F9}"},{code:"por",label:"Portuguese (Portugu\xEAs)",flag:"\u{1F1F5}\u{1F1F9}"},{code:"nld",label:"Dutch (Nederlands)",flag:"\u{1F1F3}\u{1F1F1}"},{code:"pol",label:"Polish (Polski)",flag:"\u{1F1F5}\u{1F1F1}"},{code:"rus",label:"Russian (\u0420\u0443\u0441\u0441\u043A\u0438\u0439)",flag:"\u{1F1F7}\u{1F1FA}"},{code:"chi_sim",label:"Chinese Simplified (\u7B80\u4F53\u4E2D\u6587)",flag:"\u{1F1E8}\u{1F1F3}"},{code:"chi_tra",label:"Chinese Traditional (\u7E41\u9AD4\u4E2D\u6587)",flag:"\u{1F1F9}\u{1F1FC}"},{code:"jpn",label:"Japanese (\u65E5\u672C\u8A9E)",flag:"\u{1F1EF}\u{1F1F5}"},{code:"kor",label:"Korean (\uD55C\uAD6D\uC5B4)",flag:"\u{1F1F0}\u{1F1F7}"},{code:"ara",label:"Arabic (\u0627\u0644\u0639\u0631\u0628\u064A\u0629)",flag:"\u{1F1F8}\u{1F1E6}"},{code:"hin",label:"Hindi (\u0939\u093F\u0928\u094D\u0926\u0940)",flag:"\u{1F1EE}\u{1F1F3}"},{code:"tur",label:"Turkish (T\xFCrk\xE7e)",flag:"\u{1F1F9}\u{1F1F7}"},{code:"vie",label:"Vietnamese (Ti\u1EBFng Vi\u1EC7t)",flag:"\u{1F1FB}\u{1F1F3}"}],Qe=null,Ho=null,zi=null});var jo={};ei(jo,{BUILD_DATE:()=>ih,COPIO_EVENTS:()=>te,Canvas2DAdapter:()=>ui,CopioAddEditDialog:()=>tr,CopioCarousel:()=>Zn,CopioDocOcrDialog:()=>cr,CopioEngine:()=>gs,CopioHeader:()=>ir,CopioImages:()=>Gn,CopioLoader:()=>sr,CopioRow:()=>er,CopioScanner:()=>or,CopioSyncDialog:()=>hr,DocRepository:()=>ki,Document:()=>Mn,ImageProcessorPort:()=>Ke,IndexedDbStorageAdapter:()=>Ge,LicenseManager:()=>zo,MemoryStorageAdapter:()=>Ai,NullImageProcessorAdapter:()=>ps,NullOcrAdapter:()=>Re,NullPdfAdapter:()=>Xe,NullSyncAdapter:()=>pr,OcrPort:()=>hi,OpfsStorageAdapter:()=>ss,Page:()=>fs,PdfKitAdapter:()=>Cs,PdfPort:()=>di,PeerJsAdapter:()=>ur,SUPPORTED_LANGUAGES:()=>ar,ScanSession:()=>In,StoragePort:()=>ke,SyncManager:()=>Vi,SyncPort:()=>mi,TesseractWasmAdapter:()=>Es,VERSION:()=>sh,adoptScannerStyles:()=>Uo,clearNotifications:()=>ml,createDefaultAdapter:()=>Us,dispatchCopioEvent:()=>bo,docRepository:()=>Ys,exportDocumentAsImages:()=>Dl,exportDocumentAsPdf:()=>dr,extractExif:()=>qs,fileToBase64:()=>Xs,getAssetBase:()=>lo,getContainer:()=>Ni,getCroppedSrc:()=>Ha,getOcrWorker:()=>hn,getRegisteredService:()=>Ri,getScannerStyleSheet:()=>$o,hasActiveEdits:()=>mo,loadCropper:()=>co,loadJsZip:()=>uo,loadPdfKit:()=>ho,loadPeerJs:()=>po,loadQrCode:()=>fo,loadScript:()=>Di,loadTesseract:()=>go,normalizeEditStack:()=>Js,notify:()=>Mt,probeOpfs:()=>Kr,randomId:()=>De,recognizeDocumentPages:()=>Ss,recognizeImageText:()=>dn,registerService:()=>Mi,renderPdfPagesToDataUrls:()=>on,resolveAssetUrl:()=>li,rotateSrc:()=>Ua,scannerCss:()=>rr,setAssetBase:()=>us,setContainer:()=>Oi,terminateOcrWorker:()=>ji,thresholdSrc:()=>$a});var ke=class{async init(){throw new Error("StoragePort.init() must be implemented by adapter")}async listDocs(){throw new Error("StoragePort.listDocs() must be implemented by adapter")}async getDoc(t){throw new Error("StoragePort.getDoc() must be implemented by adapter")}async saveDoc(t,e){throw new Error("StoragePort.saveDoc() must be implemented by adapter")}async renameDoc(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t){throw new Error("StoragePort.deleteDoc() must be implemented by adapter")}async savePage(t,e,i){throw new Error("StoragePort.savePage() must be implemented by adapter")}async getPage(t,e){throw new Error("StoragePort.getPage() must be implemented by adapter")}async deletePage(t,e){throw new Error("StoragePort.deletePage() must be implemented by adapter")}subscribe(t){return()=>{}}};var Ai=class extends ke{#t=new Map;#e=new Map;#i=new Set;constructor(){super()}async init(){return{kind:"memory",persistent:!1}}listDocsSync(){return Array.from(this.#t.values()).map(t=>({id:t.id,name:t.name,pages:Array.isArray(t.pages)?[...t.pages]:[]}))}async listDocs(){return this.listDocsSync()}getDocSync(t){let e=this.#t.get(t);return e?{id:e.id,name:e.name,pages:Array.isArray(e.pages)?[...e.pages]:[]}:null}async getDoc(t){return this.getDocSync(t)}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=[];if(Array.isArray(e.pages))i=[...e.pages];else if(typeof e.pages=="string")try{i=JSON.parse(e.pages)}catch{i=[]}this.#t.set(t,{id:t,name:e.name||"",pages:i}),this.#n()}async deleteDoc(t){this.#t.delete(t);let e=`${t}/`;for(let i of this.#e.keys())i.startsWith(e)&&this.#e.delete(i);this.#n()}async renameDoc(t,e){let i=this.#t.get(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,this.#n()}async savePage(t,e,i){this.#e.set(`${t}/${e}`,i);let n=this.#t.get(t);if(n){let o=n.pages.findIndex(c=>c.id===e);if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?n.pages[o]={...n.pages[o],...i}:n.pages[o]={...n.pages[o],src:i};else{let c=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};n.pages.push(c)}}this.#n()}async getPage(t,e){if(this.#e.has(`${t}/${e}`))return this.#e.get(`${t}/${e}`);let i=this.#t.get(t);if(i){let n=i.pages.find(o=>o.id===e);if(n)return n.src??n}return null}async deletePage(t,e){this.#e.delete(`${t}/${e}`);let i=this.#t.get(t);i&&(i.pages=i.pages.filter(n=>n.id!==e)),this.#n()}subscribe(t){return this.#i.add(t),()=>{this.#i.delete(t)}}clear(){this.#t.clear(),this.#e.clear(),this.#n()}#n(){for(let t of this.#i)try{t()}catch(e){console.error("Error in MemoryStorageAdapter subscriber:",e)}}};var _i=s=>typeof s;var nc=_i(""),hd=_i(!0),rc=_i(0),dd=_i(_i),Pr="type",Gi="default",ia="Listener",Yl="Result",sa="add",qi="Has",yn="Ids",Ci="Table",Jl=Ci+"s",ud=Ci+yn,Is="Row",oc=Is+"Count",ac=Is+yn,pd="Sorted"+Is+yn,gn="Cell",Mr=gn+yn,Ir="Value",Ql=Ir+"s",fd=Ir+yn,Bt=s=>""+s;var gd=(s,t="",e)=>s.split(t,e),na=globalThis,Br=Math,Yo=Br.max,Jo=Br.min,md=Br.floor,lc=isFinite,St=s=>s==null,$t=(s,t,e)=>St(s)?e?.():t(s),cc=s=>s==nc||s==hd,bd=s=>_i(s)==nc,ze=s=>_i(s)==dd,Ls=s=>Array.isArray(s),ra=(s,t,e)=>s.slice(t,e),Ce=s=>s.length,hc=()=>{};var Qo=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},oa=(s,t)=>s.includes(t),Lr=(s,t)=>s.every(t),dc=(s,t)=>Ce(s)===Ce(t)&&Lr(s,((e,i)=>t[i]===e)),Zl=(s,t)=>Lr(s,((e,i)=>i==0||t(s[i-1],e)<=0)),aa=(s,t)=>s.sort(t),we=(s,t)=>s.forEach(t),Yi=(s,t)=>s.map(t),tc=s=>uc(s,((t,e)=>t+e),0),mn=s=>Ce(s)==0,uc=(s,t,e)=>s.reduce(t,e),ve=(s,...t)=>s.push(...t),ec=s=>s.pop(),pc=s=>s.shift(),Rs=s=>{let t=_i(s);return cc(t)||t==rc&&lc(s)?t:void 0};var Fr=(s,t,e,i,n)=>St(n)?s.delCell(t,e,i,!0):s.setCell(t,e,i,n),la=(s,t,e)=>St(e)?s.delValue(t):s.setValue(t,e),ua=s=>t=>uc(Fs(t),((e,i)=>e+s(i)),0),Os=s=>s?.size??0,Ji=ua(Os),si=ua(Ji),Zo=ua(si),zt=(s,t)=>s?.has(t)??!1,vt=s=>St(s)||Os(s)==0,Fs=s=>[...s?.values()??[]],Ms=s=>s.clear(),yt=(s,t)=>s?.forEach(t),Ve=(s,t)=>s?.delete(t),Ti=Object,ic=s=>Ti.getPrototypeOf(s),yd=Ti.isFrozen,fc=Ti.entries,Or=s=>!St(s)&&$t(ic(s),(t=>t==Ti.prototype||St(ic(t))),(()=>!0)),vd=Ti.keys,Ns=Ti.freeze,wd=(s=[])=>Ti.fromEntries(s),fn=(s,t)=>t in s,gc=(s,t)=>(delete s[t],s),xd=(s,t)=>we(fc(s),(([e,i])=>t(i,e))),ii=(s,t)=>wd(((e,i)=>Yi(fc(e),(([n,o])=>i(o,n))))(s,((e,i)=>[i,t(e,i)]))),je=s=>Or(s)&&(t=>Ce(vd(t)))(s)==0;var Si=(s,t,e,i=0)=>St(s)||!Or(s)||!i&&je(s)||yd(s)?(e?.(),!1):(xd(s,((n,o)=>{t(n,o)||gc(s,o)})),!!i||!je(s)),ft=s=>new Map(s),Ki=s=>[...s?.keys()??[]],ht=(s,t)=>s?.get(t),Yt=(s,t)=>yt(s,((e,i)=>t(i,e))),bt=(s,t,e)=>St(e)?(Ve(s,t),s):s?.set(t,e),Ht=(s,t,e,i)=>(zt(s,t)?i?.(ht(s,t)):bt(s,t,e()),ht(s,t)),Xi=(s,t,e,i=bt)=>(ii(t,((n,o)=>e(s,o,n))),Yt(s,(n=>fn(t,n)?0:i(s,n))),s),ye=(s,t,e,i)=>{let n={};return yt(s,((o,c)=>{if(!e?.(o,c)){let l=t?t(o,c):o;i?.(l)||(n[c]=l)}})),n},ca=(s,t,e)=>ye(s,(i=>ye(i,t,e)),vt,je),kr=(s,t,e)=>ye(s,(i=>ca(i,t,e)),vt,je),Ei=(s,t)=>{let e=ft();return yt(s,((i,n)=>e.set(n,t?.(i)??i))),e},ha=s=>Ei(s,Ei),ta=s=>Ei(s,ha),bn=(s,t,e,i,n=0)=>$t((e?Ht:ht)(s,t[n],n>Ce(t)-2?e:ft),(o=>{if(n>Ce(t)-2)return i?.(o)&&bt(s,t[n]),o;let c=bn(o,t,e,i,n+1);return vt(o)&&bt(s,t[n]),c})),Jt=s=>new Set(Ls(s)||St(s)?s:[s]),Vt=(s,t)=>s?.add(t),$r=(s,t,e,i,n)=>{let o=s.hasRow,c=ft(),l=ft(),h=ft(),m=ft(),u=ft(),a=ft(),f=(y,r,...d)=>{let b=Ht(a,y,Jt);return we(d,(x=>Vt(b,x)&&r&&s.callListener(x))),d},w=(y,...r)=>$t(ht(a,y),(d=>{we(mn(r)?Fs(d):r,(b=>{s.delListener(b),Ve(d,b)})),vt(d)&&bt(a,y)})),E=(y,r)=>{bt(c,y,r),zt(l,y)||(bt(l,y,t()),bt(m,y,ft()),bt(u,y,ft()),n(h))},p=y=>{bt(c,y),bt(l,y),bt(m,y),bt(u,y),w(y),n(h)};return[()=>s,()=>Ki(c),y=>Yt(l,y),y=>zt(l,y),y=>ht(c,y),y=>ht(l,y),(y,r)=>bt(l,y,r),E,(y,r,d,b,x)=>{E(y,r);let _=ft(),S=ft(),R=ht(m,y),N=ht(u,y),H=K=>{let it=j=>s.getCell(r,K,j),at=ht(R,K),X=o(r,K)?e(b(it,K)):void 0;if(at===X||Ls(at)&&Ls(X)&&dc(at,X)||bt(_,K,[at,X]),!St(x)){let j=ht(N,K),W=o(r,K)?x(it,K):void 0;j!=W&&bt(S,K,W)}},z=K=>{d((()=>{yt(_,(([,it],at)=>bt(R,at,it))),yt(S,((it,at)=>bt(N,at,it)))}),_,S,R,N,K),Ms(_),Ms(S)};Yt(R,H),s.hasTable(r)&&we(s.getRowIds(r),(K=>{zt(R,K)||H(K)})),z(!0),w(y),f(y,0,s.addRowListener(r,null,((K,it,at)=>H(at))),s.addTableListener(r,(()=>z())))},p,y=>i(y,h),()=>Yt(a,p),f,w]},Nr=(s,t)=>bd(s)?e=>e(s):s??(()=>t??""),vn=(s,t)=>{let e=new WeakMap;return i=>{e.has(i)||e.set(i,s(i));let n=e.get(i);return t?.(n),n}},Ad=/^\d+$/,mc=()=>{let s=[],t=0;return[e=>(e?pc(s):null)??""+t++,e=>{Ad.test(e)&&Ce(s)<1e3&&ve(s,e)}]},wn=s=>{let t,[e,i]=mc(),n=ft();return[(o,c,l,h=[],m=()=>[])=>{t??=s();let u=e(1);return bt(n,u,[o,c,l,h,m]),Vt(bn(c,l??[""],Jt),u),u},(o,c,...l)=>we(((h,m=[""])=>{let u=[],a=(f,w)=>w==Ce(m)?ve(u,f):m[w]===null?yt(f,(E=>a(E,w+1))):we([m[w],null],(E=>a(ht(f,E),w+1)));return a(h,0),u})(o,c),(h=>yt(h,(m=>ht(n,m)[0](t,...c??[],...l))))),o=>$t(ht(n,o),(([,c,l])=>(bn(c,l??[""],void 0,(h=>(Ve(h,o),vt(h)?1:0))),bt(n,o),i(o),l))),o=>$t(ht(n,o),(([c,,l=[],h,m])=>{let u=(...a)=>{let f=Ce(a);f==Ce(l)?c(t,...a,...m(a)):St(l[f])?we(h[f]?.(...a)??[],(w=>u(...a,w))):u(...a,l[f])};u()}))]},Hp=vn((s=>{let t,e,i,n=100,o=ft(),c=ft(),l=1,h=ft(),m=ft(),[u,a,f]=wn((()=>W)),w=ft(),E=ft(),p=[],y=[],r=(Y,tt)=>{l=0,s.transaction((()=>{let[st,lt]=ht(w,tt);yt(st,((nt,G)=>yt(nt,((A,T)=>yt(A,((I,g)=>Fr(s,G,T,g,I[Y]))))))),yt(lt,((nt,G)=>la(s,G,nt[Y])))})),l=1},d=Y=>{bt(w,Y),bt(E,Y),a(m,[Y])},b=(Y,tt)=>we(((st,lt)=>st.splice(0,lt))(Y,tt??Ce(Y)),d),x=()=>b(p,Ce(p)-n),_=()=>$t(t,(()=>{ve(p,t),x(),b(y),t=void 0,i=1})),S=()=>{t=ec(p),i=1},R,N,H=(Y="")=>(St(t)&&(t=""+e++,bt(w,t,[o,c]),X(t,Y),o=ft(),c=ft(),i=1),t),z=()=>{mn(p)||(((Y,...tt)=>{Y.unshift(...tt)})(y,H()),r(0,t),t=ec(p),i=1)},K=()=>{mn(y)||(ve(p,t),t=pc(y),r(1,t),i=1)},it=()=>{i&&(a(h),i=0)},at=Y=>{let tt=H(Y);return it(),tt},X=(Y,tt)=>(j(Y)&&ht(E,Y)!==tt&&(bt(E,Y,tt),a(m,[Y])),W),j=Y=>zt(w,Y),W={setSize:Y=>(n=Y,x(),W),addCheckpoint:at,setCheckpoint:X,getStore:()=>s,getCheckpointIds:()=>[[...p],t,[...y]],forEachCheckpoint:Y=>Yt(E,Y),hasCheckpoint:j,getCheckpoint:Y=>ht(E,Y),goBackward:()=>(z(),it(),W),goForward:()=>(K(),it(),W),goTo:Y=>{let tt=oa(p,Y)?z:oa(y,Y)?K:null;for(;!St(tt)&&Y!=t;)tt();return it(),W},addCheckpointIdsListener:Y=>u(Y,h),addCheckpointListener:(Y,tt)=>u(tt,m,[Y]),delListener:Y=>(f(Y),W),clear:()=>(b(p),b(y),St(t)||d(t),t=void 0,e=0,at(),W),clearForward:()=>(mn(y)||(b(y),a(h)),W),destroy:()=>{s.delListener(R),s.delListener(N)},getListenerStats:()=>({checkpointIds:Ji(h),checkpoint:Ji(m)}),_registerListeners:()=>{R=s.addCellListener(null,null,null,((Y,tt,st,lt,nt,G)=>{if(l){_();let A=Ht(o,tt,ft),T=Ht(A,st,ft),I=Ht(T,lt,(()=>[G,void 0]));I[1]=nt,I[0]===nt&&vt(bt(T,lt))&&vt(bt(A,st))&&vt(bt(o,tt))&&S(),it()}})),N=s.addValueListener(null,((Y,tt,st,lt)=>{if(l){_();let nt=Ht(c,tt,(()=>[lt,void 0]));nt[1]=st,nt[0]===st&&vt(bt(c,tt))&&S(),it()}}))}};return Ns(W.clear())}),(s=>s._registerListeners())),Sd=gd("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),zp=ft(Yi(Sd,((s,t)=>[s,t])));var jp=na.crypto?s=>na.crypto.getRandomValues(s):s=>Yi(s,(()=>md(256*Br.random())));var Ed=JSON.stringify,ea=JSON.parse,Ds=s=>Ed(s,((t,e)=>{return i=Map,e instanceof i?Ti.fromEntries([...e]):e;var i})),Vp=new na.TextEncoder;var Wp=2**36,Gp=2**30,qp=2**24,Xp=2**18;var bc=(s,t)=>(s??0)<(t??0)?-1:1,Kp=vn((s=>{let t=ft(),e=ft(),[i,n,o]=wn((()=>d)),[c,l,h,m,u,a,f,,w,E,p,y]=$r(s,ft,(b=>St(b)?"":Ls(b)?Yi(b,Bt):Bt(b)),i,n),r=(b,x,_)=>{let S=u(b);yt(_,((R,N)=>x(N,(H=>yt(R,(z=>H(z,(K=>s.forEachCell(S,z,K)))))))))},d={setIndexDefinition:(b,x,_,S,R,N=bc)=>{let H=St(R)?void 0:([z],[K])=>R(z,K);return w(b,x,((z,K,it,at,X,j)=>{let W=0,Y=Jt(),tt=Jt(),st=a(b);if(yt(K,(([lt,nt],G)=>{let A=Jt(lt),T=Jt(nt);yt(A,(I=>Ve(T,I)?Ve(A,I):0)),yt(A,(I=>{Vt(Y,I),$t(ht(st,I),(g=>{Ve(g,G),vt(g)&&(bt(st,I),W=1)}))})),yt(T,(I=>{Vt(Y,I),zt(st,I)||(bt(st,I,Jt()),W=1),Vt(ht(st,I),G),St(S)||Vt(tt,I)}))})),z(),vt(X)||(j?Yt(st,(lt=>Vt(tt,lt))):Yt(it,(lt=>$t(ht(at,lt),(nt=>we(Ls(nt)?nt:[nt],(G=>Vt(tt,G))))))),yt(tt,(lt=>{let nt=(A,T)=>N(ht(X,A),ht(X,T),lt),G=[...ht(st,lt)];Zl(G,nt)||(bt(st,lt,Jt(aa(G,nt))),Vt(Y,lt))}))),(W||j)&&!St(H)){let lt=[...st];Zl(lt,H)||(f(b,ft(aa(lt,H))),W=1)}W&&n(t,[b]),yt(Y,(lt=>n(e,[b,lt])))}),Nr(_),$t(S,Nr)),d},delIndexDefinition:b=>(E(b),d),getStore:c,getIndexIds:l,forEachIndex:b=>h(((x,_)=>b(x,(S=>r(x,S,_))))),forEachSlice:(b,x)=>r(b,x,a(b)),hasIndex:m,hasSlice:(b,x)=>zt(a(b),x),getTableId:u,getSliceIds:b=>Ki(a(b)),getSliceRowIds:(b,x)=>Fs(ht(a(b),x)),addIndexIdsListener:p,addSliceIdsListener:(b,x)=>i(x,t,[b]),addSliceRowIdsListener:(b,x,_)=>i(_,e,[b,x]),delListener:b=>(o(b),d),destroy:y,getListenerStats:()=>({sliceIds:Ji(t),sliceRowIds:si(e)})};return Ns(d)}));var Dr=s=>[s,s],qt=(s,t=Ji)=>t(s[0])+t(s[1]),Xt=()=>[ft(),ft()],sc=s=>[...s],Rr=([s,t])=>s===t,pn=(s,t,e)=>bt(s,t,ht(s,t)==-e?void 0:e),Qi=()=>{let s,t,e=!1,i=!1,n=0,o=[],c=ft(),l=ft(),h=ft(),m=ft(),u=ft(),a=ft(),f=ft(),w=ft(),E=ft(),p=ft(),y=ft(),r=ft(),d=ft(),b=ft(),x=Jt(),_=ft(),S=ft(),R=ft(),N=ft(),H=Xt(),z=Xt(),K=Xt(),it=Xt(),at=Xt(),X=Xt(),j=Xt(),W=Xt(),Y=Xt(),tt=Xt(),st=Xt(),lt=Xt(),nt=Xt(),G=Xt(),A=Xt(),T=Xt(),I=Xt(),g=Xt(),v=Xt(),P=Xt(),k=Xt(),O=Xt(),M=ft(),C=Xt(),[L,$,B,D]=wn((()=>de)),F=U=>{if(!Si(U,((J,ot)=>oa([Pr,Gi],ot))))return!1;let q=U[Pr];return!(!cc(q)&&q!=rc)&&(Rs(U[Gi])!=q&&gc(U,Gi),!0)},V=Ls,Q=(U,q)=>(!s||zt(y,q)||Ue(q))&&Si(U,((J,ot)=>Z(q,ot,J)),(()=>Ue(q))),Z=(U,q,J,ot)=>Si(ot?J:dt(J,U,q),((ut,mt)=>$t(et(U,q,mt,ut),(At=>(J[mt]=At,!0)),(()=>!1))),(()=>Ue(U,q))),et=(U,q,J,ot)=>s?$t(ht(ht(y,U),J),(ut=>Rs(ot)!=ut[Pr]?Ue(U,q,J,ot,ut[Gi]):ot),(()=>Ue(U,q,J,ot))):St(Rs(ot))?Ue(U,q,J,ot):ot,rt=(U,q)=>Si(q?U:ct(U),((J,ot)=>$t(pt(ot,J),(ut=>(U[ot]=ut,!0)),(()=>!1))),(()=>Wi())),pt=(U,q)=>t?$t(ht(d,U),(J=>Rs(q)!=J[Pr]?Wi(U,q,J[Gi]):q),(()=>Wi(U,q))):St(Rs(q))?Wi(U,q):q,dt=(U,q,J)=>($t(ht(r,q),(([ot,ut])=>{yt(ot,((mt,At)=>{fn(U,At)||(U[At]=mt)})),yt(ut,(mt=>{fn(U,mt)||Ue(q,J,mt)}))})),U),ct=U=>(t&&(yt(b,((q,J)=>{fn(U,J)||(U[J]=q)})),yt(x,(q=>{fn(U,q)||Wi(q)}))),U),wt=U=>Xi(y,U,((q,J,ot)=>{let ut=ft(),mt=Jt();Xi(Ht(y,J,ft),ot,((At,kt,It)=>{bt(At,kt,It),$t(It[Gi],(Ze=>bt(ut,kt,Ze)),(()=>Vt(mt,kt)))})),bt(r,J,[ut,mt])}),((q,J)=>{bt(y,J),bt(r,J)})),Pt=U=>Xi(d,U,((q,J,ot)=>{bt(d,J,ot),$t(ot[Gi],(ut=>bt(b,J,ut)),(()=>Vt(x,J)))}),((q,J)=>{bt(d,J),bt(b,J),Ve(x,J)})),xt=U=>je(U)?Er():Ar(U),Dt=U=>Xi(R,U,((q,J,ot)=>Lt(J,ot)),((q,J)=>bi(J))),Lt=(U,q)=>Xi(Ht(R,U,(()=>(vi(U,1),bt(_,U,mc()),bt(S,U,ft()),ft()))),q,((J,ot,ut)=>Ut(U,J,ot,ut)),((J,ot)=>yi(U,J,ot))),Ut=(U,q,J,ot,ut)=>Xi(Ht(q,J,(()=>(_s(U,J,1),ft()))),ot,((mt,At,kt)=>jt(U,J,mt,At,kt)),((mt,At)=>le(U,q,J,mt,At,ut))),jt=(U,q,J,ot,ut)=>{zt(J,ot)||Le(U,q,ot,1);let mt=ht(J,ot);ut!==mt&&(ne(U,q,ot,mt,ut),bt(J,ot,ut))},he=(U,q,J,ot,ut)=>$t(ht(q,J),(mt=>jt(U,J,mt,ot,ut)),(()=>Ut(U,q,J,dt({[ot]:ut},U,J)))),Se=U=>je(U)?Cr():Sr(U),$e=U=>Xi(N,U,((q,J,ot)=>Pe(J,ot)),((q,J)=>oe(J))),Pe=(U,q)=>{zt(N,U)||fr(U,1);let J=ht(N,U);q!==J&&(Ts(U,J,q),bt(N,U,q))},Ie=U=>ht(R,U)??Lt(U,{}),bi=U=>Lt(U,{}),yi=(U,q,J)=>{let[,ot]=ht(_,U);ot(J),Ut(U,q,J,{},!0)},le=(U,q,J,ot,ut,mt)=>{let At=ht(ht(r,U)?.[0],ut);if(!St(At)&&!mt)return jt(U,J,ot,ut,At);let kt=It=>{ne(U,J,It,ht(ot,It)),Le(U,J,It,-1),bt(ot,It)};St(At)?kt(ut):Yt(ot,kt),vt(ot)&&(_s(U,J,-1),vt(bt(q,J))&&(vi(U,-1),bt(R,U),bt(_,U),bt(S,U)))},oe=U=>{let q=ht(b,U);if(!St(q))return Pe(U,q);Ts(U,ht(N,U)),fr(U,-1),bt(N,U)},vi=(U,q)=>pn(c,U,q),_s=(U,q,J)=>pn(Ht(m,U,ft),q,J)&&bt(h,U,Ht(h,U,(()=>0))+J),Le=(U,q,J,ot)=>{let ut=ht(S,U),mt=ht(ut,J)??0;(mt==0&&ot==1||mt==1&&ot==-1)&&pn(Ht(l,U,ft),J,ot),bt(ut,J,mt!=-ot?mt+ot:null),pn(Ht(Ht(u,U,ft),q,ft),J,ot)},ne=(U,q,J,ot,ut)=>{Ht(Ht(Ht(a,U,ft),q,ft),J,(()=>[ot,0]))[1]=ut,o[3]?.(U,q,J,ut)},fr=(U,q)=>pn(f,U,q),Ts=(U,q,J)=>{Ht(w,U,(()=>[q,0]))[1]=J,o[4]?.(U,J)},Ue=(U,q,J,ot,ut)=>(ve(Ht(Ht(Ht(E,U,ft),q,ft),J,(()=>[])),ot),ut),Wi=(U,q,J)=>(ve(Ht(p,U,(()=>[])),q),J),He=(U,q,J)=>$t(ht(ht(ht(a,U),q),J),(([ot,ut])=>[!0,ot,ut]),(()=>[!1,...Dr(yr(U,q,J))])),gr=U=>$t(ht(w,U),(([q,J])=>[!0,q,J]),(()=>[!1,...Dr(vr(U))])),Ps=U=>vt(E)||vt(T[U])?0:yt(U?ta(E):E,((q,J)=>yt(q,((ot,ut)=>yt(ot,((mt,At)=>$(T[U],[J,ut,At],mt))))))),wi=U=>vt(p)||vt(I[U])?0:yt(U?Ei(p):p,((q,J)=>$(I[U],[J],q))),fe=(U,q,J,ot)=>{if(!vt(U))return $(q,ot,(()=>ye(U))),Yt(U,((ut,mt)=>$(J,[...ot??[],ut],mt==1))),1},mr=U=>{let q=wr();q!=e&&$(H[U],void 0,q);let J=vt(tt[U]),ot=vt(nt[U])&&vt(G[U])&&vt(Y[U])&&vt(st[U])&&vt(X[U])&&vt(j[U])&&vt(W[U])&&J&&vt(K[U])&&vt(it[U]),ut=vt(A[U])&&vt(lt[U])&&vt(at[U])&&vt(z[U]);if(!ot||!ut){let mt=U?[Ei(c),ha(l),Ei(h),ha(m),ta(u),ta(a)]:[c,l,h,m,u,a];if(!ot){fe(mt[0],K[U],it[U]),yt(mt[1],((kt,It)=>fe(kt,X[U],j[U],[It]))),yt(mt[2],((kt,It)=>{kt!=0&&$(W[U],[It],Fl(It))}));let At=Jt();yt(mt[3],((kt,It)=>{fe(kt,Y[U],st[U],[It])&&!J&&($(tt[U],[It,null]),Vt(At,It))})),J||yt(mt[5],((kt,It)=>{if(!zt(At,It)){let Ze=Jt();yt(kt,(xi=>yt(xi,(([_r,Tr],un)=>Tr!==_r?Vt(Ze,un):Ve(xi,un))))),yt(Ze,(xi=>$(tt[U],[It,xi])))}})),yt(mt[4],((kt,It)=>yt(kt,((Ze,xi)=>fe(Ze,nt[U],G[U],[It,xi])))))}if(!ut){let At;yt(mt[5],((kt,It)=>{let Ze;yt(kt,((xi,_r)=>{let Tr;yt(xi,(([un,Kl],ld)=>{Kl!==un&&($(A[U],[It,_r,ld],Kl,un,He),At=Ze=Tr=1)})),Tr&&$(lt[U],[It,_r],He)})),Ze&&$(at[U],[It],He)})),At&&$(z[U],void 0,He)}}},Ml=U=>{let q=xr();q!=i&&$(g[U],void 0,q);let J=vt(P[U])&&vt(k[U]),ot=vt(O[U])&&vt(v[U]);if(!J||!ot){let ut=U?[Ei(f),Ei(w)]:[f,w];if(J||fe(ut[0],P[U],k[U]),!ot){let mt;yt(ut[1],(([At,kt],It)=>{kt!==At&&($(O[U],[It],kt,At,gr),mt=1)})),mt&&$(v[U],void 0,gr)}}},Gt=(U,...q)=>(Ko((()=>U(...Yi(q,Bt)))),de),Il=(U,q,J,ot,ut)=>{let mt=br(U,q,...J);return L((()=>{let At=br(U,q,...J);dc(At,mt)||(mt=At,ot(de,U,q,...J,mt))}),tt[ut?1:0],[U,q],[Ee])},Vo=()=>kr(R),Ee=()=>Ki(R),Ll=U=>Ki(ht(S,Bt(U))),Fl=U=>Os(ht(R,Bt(U))),ks=U=>Ki(ht(R,Bt(U))),br=(U,q,J,ot=0,ut)=>{return Or(U)?br(U.tableId,U.cellId,U.descending,U.offset,U.limit):Yi(ra(aa((mt=ht(R,Bt(U)),At=(kt,It)=>[St(q)?It:ht(kt,Bt(q)),It],Yi([...mt?.entries()??[]],(([kt,It])=>At(It,kt)))),(([kt],[It])=>bc(kt,It)*(J?-1:1))),ot,St(ut)?ut:ot+ut),(([,kt])=>kt));var mt,At},Wo=(U,q)=>Ki(ht(ht(R,Bt(U)),Bt(q))),yr=(U,q,J)=>ht(ht(ht(R,Bt(U)),Bt(q)),Bt(J)),Go=()=>ye(N),qo=()=>Ki(N),vr=U=>ht(N,Bt(U)),wr=()=>!vt(R),Ol=U=>zt(R,Bt(U)),Nl=(U,q)=>zt(ht(S,Bt(U)),Bt(q)),Bl=(U,q)=>zt(ht(R,Bt(U)),Bt(q)),$l=(U,q,J)=>zt(ht(ht(R,Bt(U)),Bt(q)),Bt(J)),xr=()=>!vt(N),Ul=U=>zt(N,Bt(U)),Ar=U=>Gt((()=>(q=>Si(q,Q,Ue))(U)?Dt(U):0)),Sr=U=>Gt((()=>rt(U)?$e(U):0)),Hl=U=>(Qo((()=>xt(ea(U)))),de),zl=U=>Gt((()=>{if((s=Si(U,(q=>Si(q,F))))&&(wt(U),!vt(R))){let q=Vo();Er(),Ar(q)}})),jl=U=>Gt((()=>{if(t=(q=>Si(q,F))(U)){let q=Go();Xo(),Cr(),t=!0,Pt(U),Sr(q)}})),Er=()=>Gt((()=>Dt({}))),Vl=U=>Gt((q=>zt(R,q)?bi(q):0),U),Wl=(U,q)=>Gt(((J,ot)=>$t(ht(R,J),(ut=>zt(ut,ot)?yi(J,ut,ot):0))),U,q),Cr=()=>Gt((()=>$e({}))),Gl=()=>Gt((()=>{wt({}),s=!1})),Xo=()=>Gt((()=>{Pt({}),t=!1})),Ko=(U,q)=>{if(n!=-1){ql();let J=U();return Xl(q),J}},ql=()=>(n!=-1&&n++,n==1&&(o[0]?.(),$(M)),de),Xl=U=>(n>0&&(n--,n==0&&(n=1,Ps(1),vt(a)||mr(1),wi(1),vt(w)||Ml(1),U?.(de)&&(yt(a,((q,J)=>yt(q,((ot,ut)=>yt(ot,(([mt],At)=>Fr(de,J,ut,At,mt))))))),Ms(a),yt(w,(([q],J)=>la(de,J,q))),Ms(w)),$(C[0],void 0),n=-1,Ps(0),vt(a)||mr(0),wi(0),vt(w)||Ml(0),o[1]?.(),$(C[1],void 0),o[2]?.(),n=0,e=wr(),i=xr(),we([c,l,h,m,u,a,E,f,w,p],Ms))),de),de={getContent:()=>[Vo(),Go()],getTables:Vo,getTableIds:Ee,getTable:U=>ca(ht(R,Bt(U))),getTableCellIds:Ll,getRowCount:Fl,getRowIds:ks,getSortedRowIds:br,getRow:(U,q)=>ye(ht(ht(R,Bt(U)),Bt(q))),getCellIds:Wo,getCell:yr,getValues:Go,getValueIds:qo,getValue:vr,hasTables:wr,hasTable:Ol,hasTableCell:Nl,hasRow:Bl,hasCell:$l,hasValues:xr,hasValue:Ul,getTablesJson:()=>Ds(R),getValuesJson:()=>Ds(N),getJson:()=>Ds([R,N]),getTablesSchemaJson:()=>Ds(y),getValuesSchemaJson:()=>Ds(d),getSchemaJson:()=>Ds([y,d]),hasTablesSchema:()=>s,hasValuesSchema:()=>t,setContent:U=>Gt((()=>{let q=ze(U)?U():U;V(q)&&(([J,ot])=>{(je(J)?Er:Ar)(J),(je(ot)?Cr:Sr)(ot)})(q)})),setTables:Ar,setTable:(U,q)=>Gt((J=>Q(q,J)?Lt(J,q):0),U),setRow:(U,q,J)=>Gt(((ot,ut)=>Z(ot,ut,J)?Ut(ot,Ie(ot),ut,J):0),U,q),addRow:(U,q,J=!0)=>Ko((()=>{let ot;return Z(U,ot,q)&&(U=Bt(U),Ut(U,Ie(U),ot=((ut,mt)=>{let[At]=ht(_,ut),kt;do kt=At(mt);while(zt(ht(R,ut),kt));return kt})(U,J?1:0),q)),ot})),setPartialRow:(U,q,J)=>Gt(((ot,ut)=>{if(Z(ot,ut,J,1)){let mt=Ie(ot);ii(J,((At,kt)=>he(ot,mt,ut,kt,At)))}}),U,q),setCell:(U,q,J,ot)=>Gt(((ut,mt,At)=>$t(et(ut,mt,At,ze(ot)?ot(yr(ut,mt,At)):ot),(kt=>he(ut,Ie(ut),mt,At,kt)))),U,q,J),setValues:Sr,setPartialValues:U=>Gt((()=>rt(U,1)?ii(U,((q,J)=>Pe(J,q))):0)),setValue:(U,q)=>Gt((J=>$t(pt(J,ze(q)?q(vr(J)):q),(ot=>Pe(J,ot)))),U),applyChanges:U=>Gt((()=>{ii(U[0],((q,J)=>St(q)?Vl(J):ii(q,((ot,ut)=>St(ot)?Wl(J,ut):ii(ot,((mt,At)=>Fr(de,J,ut,At,mt))))))),ii(U[1],((q,J)=>la(de,J,q)))})),setTablesJson:Hl,setValuesJson:U=>(Qo((()=>Se(ea(U)))),de),setJson:U=>Gt((()=>Qo((()=>{let[q,J]=ea(U);xt(q),Se(J)}),(()=>Hl(U))))),setTablesSchema:zl,setValuesSchema:jl,setSchema:(U,q)=>Gt((()=>{zl(U),jl(q)})),delTables:Er,delTable:Vl,delRow:Wl,delCell:(U,q,J,ot)=>Gt(((ut,mt,At)=>$t(ht(R,ut),(kt=>$t(ht(kt,mt),(It=>zt(It,At)?le(ut,kt,mt,It,At,ot):0))))),U,q,J),delValues:Cr,delValue:U=>Gt((q=>zt(N,q)?oe(q):0),U),delTablesSchema:Gl,delValuesSchema:Xo,delSchema:()=>Gt((()=>{Gl(),Xo()})),transaction:Ko,startTransaction:ql,getTransactionChanges:()=>[ye(a,((U,q)=>ht(c,q)===-1?void 0:ye(U,((J,ot)=>ht(ht(m,q),ot)===-1?void 0:ye(J,(([,ut])=>ut),(ut=>Rr(ut)))),vt,je)),vt,je),ye(w,(([,U])=>U),(U=>Rr(U))),1],getTransactionLog:()=>[!vt(a),!vt(w),kr(a,sc,Rr),kr(E),ye(w,sc,Rr),ye(p),ye(c),ca(m),kr(u),ye(f)],finishTransaction:Xl,forEachTable:U=>yt(R,((q,J)=>U(J,(ot=>yt(q,((ut,mt)=>ot(mt,(At=>Yt(ut,At))))))))),forEachTableCell:(U,q)=>Yt(ht(S,Bt(U)),q),forEachRow:(U,q)=>yt(ht(R,Bt(U)),((J,ot)=>q(ot,(ut=>Yt(J,ut))))),forEachCell:(U,q,J)=>Yt(ht(ht(R,Bt(U)),Bt(q)),J),forEachValue:U=>Yt(N,U),addSortedRowIdsListener:(U,q,J,ot,ut,mt,At)=>Or(U)?Il(U.tableId,U.cellId,[U.descending??!1,U.offset??0,U.limit],q,J):Il(U,q,[J,ot,ut],mt,At),addStartTransactionListener:U=>L(U,M),addWillFinishTransactionListener:U=>L(U,C[0]),addDidFinishTransactionListener:U=>L(U,C[1]),callListener:U=>(D(U),de),delListener:U=>(B(U),de),getListenerStats:()=>({hasTables:qt(H),tables:qt(z),tableIds:qt(K),hasTable:qt(it),table:qt(at),tableCellIds:qt(X),hasTableCell:qt(j,si),rowCount:qt(W),rowIds:qt(Y),sortedRowIds:qt(tt),hasRow:qt(st,si),row:qt(lt,si),cellIds:qt(nt,si),hasCell:qt(G,Zo),cell:qt(A,Zo),invalidCell:qt(T,Zo),hasValues:qt(g),values:qt(v),valueIds:qt(P),hasValue:qt(k),value:qt(O),invalidValue:qt(I),transaction:Ji(M)+qt(C)}),isMergeable:()=>!1,createStore:Qi,addListener:L,callListeners:$,setInternalListeners:(U,q,J,ot,ut)=>o=[U,q,J,ot,ut]};return ii({[qi+Jl]:[0,H,[],()=>[wr()]],[Jl]:[0,z],[ud]:[0,K],[qi+Ci]:[1,it,[Ee],U=>[Ol(...U)]],[Ci]:[1,at,[Ee]],[Ci+Mr]:[1,X,[Ee]],[qi+Ci+gn]:[2,j,[Ee,Ll],U=>[Nl(...U)]],[oc]:[1,W,[Ee]],[ac]:[1,Y,[Ee]],[qi+Is]:[2,st,[Ee,ks],U=>[Bl(...U)]],[Is]:[2,lt,[Ee,ks]],[Mr]:[2,nt,[Ee,ks]],[qi+gn]:[3,G,[Ee,ks,Wo],U=>[$l(...U)]],[gn]:[3,A,[Ee,ks,Wo],U=>Dr(yr(...U))],InvalidCell:[3,T],[qi+Ql]:[0,g,[],()=>[xr()]],[Ql]:[0,v],[fd]:[0,P],[qi+Ir]:[1,k,[qo],U=>[Ul(...U)]],[Ir]:[1,O,[qo],U=>Dr(vr(U[0]))],InvalidValue:[1,I]},(([U,q,J,ot],ut)=>{de[sa+ut+ia]=(...mt)=>L(mt[U],q[mt[U+1]?1:0],U>0?ra(mt,0,U):void 0,J,ot)})),Ns(de)};var da=ft([["avg",[(s,t)=>tc(s)/t,(s,t,e)=>s+(t-s)/(e+1),(s,t,e)=>s+(s-t)/(e-1),(s,t,e,i)=>s+(t-e)/i]],["max",[s=>Yo(...s),(s,t)=>Yo(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:Yo(t,s)]],["min",[s=>Jo(...s),(s,t)=>Jo(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:Jo(t,s)]],["sum",[s=>tc(s),(s,t)=>s+t,(s,t)=>s-t,(s,t,e)=>s-e+t]]]),yc=(s,t,e,i,n,o=!1)=>{if(vt(e))return;let[c,l,h,m]=n;return o||=St(s),yt(i,(([u,a])=>{o||(s=St(u)?l?.(s,a,t++):St(a)?h?.(s,u,t--):m?.(s,a,u,t),o||=St(s))})),o?c(Fs(e),Os(e)):s},Yp=vn((s=>{let t=ft(),[e,i,n]=wn((()=>y)),[o,c,l,h,m,u,a,,f,w,E,p]=$r(s,hc,(r=>isNaN(r)||St(r)||r===!0||r===!1||r===""?void 0:1*r),e,i),y={setMetricDefinition:(r,d,b,x,_,S,R)=>{let N=ze(b)?[b,_,S,R]:ht(da,b)??ht(da,"sum");return f(r,d,((H,z,K,it,at,X)=>{let j=u(r),W=Os(it);X||=St(j),H();let Y=yc(j,W,it,z,N,X);lc(Y)||(Y=void 0),Y!=j&&(a(r,Y),i(t,[r],Y,j))}),Nr(x,1)),y},delMetricDefinition:r=>(w(r),y),getStore:o,getMetricIds:c,forEachMetric:l,hasMetric:h,getTableId:m,getMetric:u,addMetricIdsListener:E,addMetricListener:(r,d)=>e(d,t,[r]),delListener:r=>(n(r),y),destroy:p,getListenerStats:()=>({metric:Ji(t)})};return Ns(y)})),Jp=vn((s=>{let t=s.createStore,e=t(),i=t(),n=ft(),{addListener:o,callListeners:c,delListener:l}=i,[h,m,u,a,f,,,w,,E,p,y,r,d]=$r(s,(()=>!0),hc,o,c),b=(R,N,...H)=>we(H,(z=>Vt(Ht(Ht(n,N,ft),R,Jt),z))),x=R=>{$t(ht(n,R),(N=>{Yt(N,((H,z)=>yt(z,(K=>H.delListener(K))))),Ms(N)})),we([i,e],(N=>N.delTable(R)))},_=(R,N,H)=>b(N,R,N.addStartTransactionListener(H.startTransaction),N.addDidFinishTransactionListener((()=>H.finishTransaction()))),S={setQueryDefinition:(R,N,H)=>{w(R,N),x(R);let z=[],K=[[null,[N,null,null,[],ft()]]],it=[],at=[],X=[];H({select:(nt,G)=>{let A=ze(nt)?[Ce(z)+"",nt]:[St(G)?nt:G,T=>T(nt,G)];return ve(z,A),{as:T=>A[0]=T}},join:(nt,G,A)=>{let T=St(A)||ze(G)?null:G,I=St(T)?G:A,g=[nt,[nt,T,ze(I)?I:v=>v(I),[],ft()]];return ve(K,g),{as:v=>g[0]=v}},where:(nt,G,A)=>ve(it,ze(nt)?nt:St(A)?T=>T(nt)===G:T=>T(nt,G)===A),group:(nt,G,A,T,I)=>{let g=[nt,[nt,ze(G)?[G,A,T,I]:ht(da,G)??[(v,P)=>P]]];return ve(at,g),{as:v=>g[0]=v}},having:(nt,G)=>ve(X,ze(nt)?nt:A=>A(nt)===G)});let j=ft(z);if(vt(j))return S;let W=ft(K);Yt(W,((nt,[,G])=>$t(ht(W,G),(({3:A})=>St(nt)?0:ve(A,nt)))));let Y=ft(at),tt=e;if(vt(Y)&&mn(X))tt=i;else{_(R,tt,i);let nt=ft();Yt(Y,((I,[g,v])=>Vt(Ht(nt,g,Jt),[I,v])));let G=Jt();Yt(j,(I=>zt(nt,I)?0:Vt(G,I)));let A=ft(),T=(I,g,v,P)=>$t(I,(([k,O,M,C])=>{Yt(g,((L,[$])=>{let B=Ht(k,L,ft),D=ht(B,v),F=P?void 0:$;if(D!==F){let V=Jt([[D,F]]),Q=Os(B);bt(B,v,F),yt(ht(nt,L),(([Z,et])=>{let rt=yc(C[Z],Q,B,V,et);C[Z]=St(Rs(rt))?null:rt}))}})),vt(O)||!Lr(X,(L=>L(($=>C[$]))))?i.delRow(R,M):St(M)?I[2]=i.addRow(R,C):i.setRow(R,M,C)}));b(tt,R,tt.addRowListener(R,null,((I,g,v,P)=>{let k=[],O=[],M=ft(),C=tt.hasRow(R,v),L=!C;yt(G,($=>{let[B,D,F]=P(R,v,$);ve(k,D),ve(O,F),L||=B})),Yt(nt,($=>{let[B,,D]=P(R,v,$);(L||B)&&bt(M,$,[D])})),L&&T(bn(A,k,void 0,(([,$])=>(Ve($,v),vt($)))),M,v,1),C&&T(bn(A,O,(()=>{let $={};return yt(G,(B=>$[B]=tt.getCell(R,v,B))),[ft(),Jt(),void 0,$]}),(([,$])=>{Vt($,v)})),M,v)})))}_(R,s,tt);let st=(nt,G,A,T)=>{let I=g=>s.getCell(G,A,g);we(T,(g=>{let[v,,P,k,O]=ht(W,g),M=P?.(I,nt),[C,L]=ht(O,nt)??[];M!=C&&(St(L)||d(R,L),bt(O,nt,St(M)?null:[M,...r(R,1,s.addRowListener(v,M,(()=>st(nt,v,M,k))))]))})),(g=>{let v=(P,k)=>s.getCell(...St(k)?[N,g,P]:P===N?[N,g,k]:[ht(W,P)?.[0],ht(ht(W,P)?.[4],g)?.[0],k]);tt.transaction((()=>Lr(it,(P=>P(v)))?Yt(j,((P,k)=>Fr(tt,R,g,P,k(v,g)))):tt.delRow(R,g)))})(nt)},{3:lt}=ht(W,null);return tt.transaction((()=>r(R,1,s.addRowListener(N,null,((nt,G,A)=>{s.hasRow(N,A)?st(A,N,A,lt):(tt.delRow(R,A),yt(W,(({4:T})=>$t(ht(T,A),(([,I])=>{d(R,I),bt(T,A)})))))}))))),S},delQueryDefinition:R=>(x(R),E(R),S),getStore:h,getQueryIds:m,forEachQuery:u,hasQuery:a,getTableId:f,addQueryIdsListener:R=>p((()=>R(S))),delListener:R=>(l(R),S),destroy:y,getListenerStats:()=>{let{tables:R,tableIds:N,transaction:H,...z}=i.getListenerStats();return z}};return ii({[Ci]:[1,1],[Ci+Mr]:[0,1],[oc]:[0,1],[ac]:[0,1],[pd]:[0,5],[Is]:[1,2],[Mr]:[0,2],[gn]:[1,3]},(([R,N],H)=>{we(R?["get","has","forEach"]:["get"],(z=>S[z+Yl+H]=(...K)=>i[z+H](...K))),S[sa+Yl+H+ia]=(...z)=>i[sa+H+ia](...ra(z,0,N),((K,...it)=>z[N](S,...it)),!0)})),Ns(S)})),Qp=vn((s=>{let t=ft(),e=ft(),i=ft(),n=ft(),[o,c,l]=wn((()=>_)),[h,m,u,a,f,w,,,E,p,y,r]=$r(s,(()=>[ft(),ft(),ft(),ft()]),(S=>St(S)?void 0:S+""),o,c),d=(S,R,N)=>$t(w(S),(([H,,z])=>{if(!zt(z,R)){let K=Jt();if(f(S)!=x(S))Vt(K,R);else{let it=R;for(;!St(it)&&!zt(K,it);)Vt(K,it),it=ht(H,it)}if(N)return K;bt(z,R,K)}return ht(z,R)})),b=(S,R)=>$t(w(S),(([,,N])=>bt(N,R))),x=S=>ht(t,S),_={setRelationshipDefinition:(S,R,N,H)=>(bt(t,S,N),E(S,R,((z,K)=>{let it=Jt(),at=Jt(),X=Jt(),[j,W]=w(S);yt(K,(([Y,tt],st)=>{St(Y)||(Vt(at,Y),$t(ht(W,Y),(lt=>{Ve(lt,st),vt(lt)&&bt(W,Y)}))),St(tt)||(Vt(at,tt),zt(W,tt)||bt(W,tt,Jt()),Vt(ht(W,tt),st)),Vt(it,st),bt(j,st,tt),Yt(ht(n,S),(lt=>{zt(d(S,lt),st)&&Vt(X,lt)}))})),z(),yt(it,(Y=>c(e,[S,Y]))),yt(at,(Y=>c(i,[S,Y]))),yt(X,(Y=>{b(S,Y),c(n,[S,Y])}))}),Nr(H)),_),delRelationshipDefinition:S=>(bt(t,S),p(S),_),getStore:h,getRelationshipIds:m,forEachRelationship:S=>u((R=>S(R,(N=>s.forEachRow(f(R),N))))),hasRelationship:a,getLocalTableId:f,getRemoteTableId:x,getRemoteRowId:(S,R)=>ht(w(S)?.[0],R),getLocalRowIds:(S,R)=>Fs(ht(w(S)?.[1],R)),getLinkedRowIds:(S,R)=>St(w(S))?[R]:Fs(d(S,R,!0)),addRelationshipIdsListener:y,addRemoteRowIdListener:(S,R,N)=>o(N,e,[S,R]),addLocalRowIdsListener:(S,R,N)=>o(N,i,[S,R]),addLinkedRowIdsListener:(S,R,N)=>(d(S,R),o(N,n,[S,R])),delListener:S=>(b(...l(S)??[]),_),destroy:r,getListenerStats:()=>({remoteRowId:si(e),localRowIds:si(i),linkedRowIds:si(n)})};return Ns(_)}));var xc=Promise,Cd=globalThis,vc=Cd.window,_d=1e3,Td=(s,t,e)=>setInterval(s,t*_d),Pd=clearInterval,We=s=>s==null,Vr=(s,t,e)=>We(s)?e?.():t(s),fa=s=>Array.isArray(s),ts=s=>s.length,kd=(s,t)=>s.test(t),Ac=s=>new xc(s),Sc=async s=>xc.all(s),Ec=s=>{throw new Error(s)},Zi=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},ga=(s,t)=>s.forEach(t),xn=(s,t)=>s.map(t),Dd=(s,t)=>s.splice(0,t),Wr=(s,...t)=>s.push(...t),Cc=s=>s.shift(),Bs=Object,wc=s=>Bs.getPrototypeOf(s),Rd=Bs.entries,Md=s=>!We(s)&&Vr(wc(s),t=>t==Bs.prototype||We(wc(t)),()=>!0),Id=Bs.keys,Ld=Bs.freeze,Fd=(s=[])=>Bs.fromEntries(s),Od=(s,t)=>t in s,Nd=(s,t)=>xn(Rd(s),([e,i])=>t(i,e)),Bd=s=>ts(Id(s)),Ur=s=>Md(s)&&Bd(s)==0,$d=s=>s?.size??0,Ud=(s,t)=>s?.has(t)??!1,_c=s=>We(s)||$d(s)==0,Tc=(s,t)=>s?.forEach(t),Pc=(s,t)=>s?.delete(t),An=s=>new Map(s),Fe=(s,t)=>s?.get(t),es=(s,t,e)=>We(e)?(Pc(s,t),s):s?.set(t,e),ma=(s,t,e,i)=>(Ud(s,t)?i?.(Fe(s,t)):es(s,t,e()),Fe(s,t)),ba=(s,t,e,i,n=0)=>Vr((e?ma:Fe)(s,t[n],n>ts(t)-2?e:An),o=>{if(n>ts(t)-2)return i?.(o)&&es(s,t[n]),o;let c=ba(o,t,e,i,n+1);return _c(o)&&es(s,t[n]),c}),Hd=/^\d+$/,zd=()=>{let s=[],t=0;return[e=>(e?Cc(s):null)??""+t++,e=>{kd(Hd,e)&&ts(s)<1e3&&Wr(s,e)}]},jd=s=>new Set(fa(s)||We(s)?s:[s]),Vd=(s,t)=>s?.add(t),Wd=(s,t=[""])=>{let e=[],i=(n,o)=>o==ts(t)?Wr(e,n):t[o]===null?Tc(n,c=>i(c,o+1)):ga([t[o],null],c=>i(Fe(n,c),o+1));return i(s,0),e},Gd=s=>{let t,[e,i]=zd(),n=An();return[(o,c,l,h=[],m=()=>[])=>{t??=s();let u=e(1);return es(n,u,[o,c,l,h,m]),Vd(ba(c,l??[""],jd),u),u},(o,c,...l)=>ga(Wd(o,c),h=>Tc(h,m=>Fe(n,m)[0](t,...c??[],...l))),o=>Vr(Fe(n,o),([,c,l])=>(ba(c,l??[""],void 0,h=>(Pc(h,o),_c(h)?1:0)),es(n,o),i(o),l)),o=>Vr(Fe(n,o),([c,,l=[],h,m])=>{let u=(...a)=>{let f=ts(a);f==ts(l)?c(t,...a,...m(a)):We(l[f])?ga(h[f]?.(...a)??[],w=>u(...a,w)):u(...a,l[f])};u()})]},Hr=An(),zr=An(),qd=(s=1,t,e)=>s!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[n]])=>!Ur(i)||!Ur(n),t.setDefaultContent]:s!=2?[0,t.getContent,t.getTransactionChanges,([i,n])=>!Ur(i)||!Ur(n),t.setContent]:Ec("Store type not supported by this Persister"),Xd=(s,t,e,i,n,o,c,l={},h=0,m=[])=>{let u=0,a=0,f=0,w,E,p;ma(Hr,m,()=>0),ma(zr,m,()=>[]);let y=An(),[r,d,b,x,_]=qd(c,s,h),[S,R,N]=Gd(()=>g),H=v=>{v!=u&&(u=v,R(y,void 0,u))},z=async()=>{if(!Fe(Hr,m)){for(es(Hr,m,1);!We(w=Cc(Fe(zr,m)));)await Zi(w,o);es(Hr,m,0)}},K=v=>{(r&&fa(v?.[0])?v?.[2]===1?s.applyMergeableChanges:s.setMergeableContent:v?.[2]===1?s.applyChanges:s.setContent)(v)},it=async v=>(u!=2&&(H(1),a++,await I(async()=>{await Zi(async()=>{let P=await t();fa(P)?K(P):v?_(v):Ec(`Content is not an array: ${P}`)},()=>{v&&_(v)}),H(0)})),g),at=async v=>(X(),await it(v),await Zi(async()=>E=await i(async(P,k)=>{k||P?u!=2&&(H(1),a++,K(k??P),H(0)):await it()}),o),g),X=async()=>(E&&(await Zi(()=>n(E),o),E=void 0),g),j=()=>!We(E),W=async v=>(u!=1&&(H(2),f++,await I(async()=>{await Zi(()=>e(d,v),o),H(0)})),g),Y=async()=>(tt(),await W(),p=s.addDidFinishTransactionListener(()=>{let v=b();x(v)&&W(v)}),g),tt=async()=>(p&&(s.delListener(p),p=void 0),g),st=()=>!We(p),lt=async(v,P=!1)=>{let[k,O]=P?[Y,at]:[at,Y];return await k(v),await O(v),g},nt=async(v=!1)=>{let[P,k]=v?[tt,X]:[X,tt];return await P(),await k(),g},G=()=>u,A=v=>S(v,y),T=v=>(N(v),s),I=async(...v)=>(Wr(Fe(zr,m),...v),await z(),g),g={load:it,startAutoLoad:at,stopAutoLoad:X,isAutoLoading:j,save:W,startAutoSave:Y,stopAutoSave:tt,isAutoSaving:st,startAutoPersisting:lt,stopAutoPersisting:nt,getStatus:G,addStatusListener:A,delListener:T,schedule:I,getStore:()=>s,destroy:()=>(Dd(Fe(zr,m)),nt()),getStats:()=>({loads:a,saves:f}),...l};return Ld(g)},pa=["t","v"],Kd={keyPath:"k"},Yd=async(s,t)=>{let e=Nd(t,(i,n)=>jr(s,"put",{k:n,v:i}));xn(await jr(s,"getAllKeys"),i=>Od(t,i)?0:Wr(e,jr(s,"delete",i))),await Sc(e)},jr=async(s,t,e)=>Ac((i,n)=>{let o=s[t](e);o.onsuccess=()=>i(o.result),o.onerror=()=>n(`objectStore.${t} error`)}),Gr=(s,t,e=1,i)=>{let n=async(o,c=[],l=0)=>Ac((h,m)=>{let u=(vc?vc.indexedDB:indexedDB).open(t,l?2:void 0);u.onupgradeneeded=()=>l&&xn(pa,a=>Zi(()=>u.result.createObjectStore(a,Kd))),u.onsuccess=()=>Zi(async()=>{let a=u.result.transaction(pa,"readwrite"),f=await Sc(xn(pa,(w,E)=>o(a.objectStore(w),c[E])));u.result.close(),h(f)},a=>{u.result.close(),m(a)}),u.onerror=()=>m("indexedDB.open error")});return Xd(s,async()=>await n(async o=>Fd(xn(await jr(o,"getAll"),({k:c,v:l})=>[c,l]))),o=>n((c,l)=>Yd(c,l),o(),1),o=>Td(o,e),o=>Pd(o),i,1,{getDbName:()=>t})};var $s=Qi();$s.setTable("docs",{});var qr=Gr($s,"copio-db");qr.startAutoLoad();qr.startAutoSave();var Xr=class{#t;#e="blobs";#i=null;constructor(t="copio-blobs"){this.#t=t}async#n(){return this.#i?this.#i:(this.#i=new Promise((t,e)=>{if(typeof indexedDB>"u"){e(new Error("IndexedDB is not available"));return}let i=indexedDB.open(this.#t,1);i.onupgradeneeded=()=>{let n=i.result;n.objectStoreNames.contains(this.#e)||n.createObjectStore(this.#e)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error||new Error("Failed to open blob db"))}),this.#i)}async put(t,e){let i=await this.#n();return new Promise((n,o)=>{let h=i.transaction(this.#e,"readwrite").objectStore(this.#e).put(e,t);h.onsuccess=()=>n(),h.onerror=()=>o(h.error)})}async get(t){let e=await this.#n();return new Promise((i,n)=>{let l=e.transaction(this.#e,"readonly").objectStore(this.#e).get(t);l.onsuccess=()=>i(l.result||null),l.onerror=()=>n(l.error)})}async delete(t){let e=await this.#n();return new Promise((i,n)=>{let l=e.transaction(this.#e,"readwrite").objectStore(this.#e).delete(t);l.onsuccess=()=>i(),l.onerror=()=>n(l.error)})}async deleteByPrefix(t){let e=await this.#n();return new Promise((i,n)=>{let c=e.transaction(this.#e,"readwrite").objectStore(this.#e),l=c.openKeyCursor();l.onsuccess=h=>{let m=h.target.result;m?(typeof m.key=="string"&&m.key.startsWith(t)&&c.delete(m.key),m.continue()):i()},l.onerror=()=>n(l.error)})}async sweepOrphans(t){let e=new Set(t),i=await this.#n(),n=0;return new Promise((o,c)=>{let h=i.transaction(this.#e,"readwrite").objectStore(this.#e),m=h.openKeyCursor();m.onsuccess=u=>{let a=u.target.result;if(a){if(typeof a.key=="string"){let f=a.key.split(":")[0];e.has(f)||(h.delete(a.key),n++)}a.continue()}else o(n)},m.onerror=()=>c(m.error)})}async close(){if(this.#i){try{(await this.#i).close()}catch{}this.#i=null}}};function is(s,t="image/jpeg"){if(s instanceof Blob)return s;if(typeof s!="string"||!s.startsWith("data:"))return null;let e=s.match(/^data:([^;]+);base64,(.*)$/),i=e?e[1]:t,n=e?e[2]:s.split(",")[1],o=atob(n),c=new Uint8Array(o.length);for(let l=0;l<o.length;l++)c[l]=o.charCodeAt(l);return new Blob([c],{type:i})}async function ya(s){return new Promise((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=e,i.readAsDataURL(s)})}var Ge=class extends ke{#t=null;#e=null;#i=null;#n="copio-db";#r=!1;#s=new Set;#a=new Map;#l=new Map;#o=new Map;#h=new Map;#u=null;constructor(t={}){super(),t.dbName&&t.dbName!=="copio-db"?(this.#n=t.dbName,this.#t=t.store||Qi(),this.#t.setTable("docs",{}),this.#e=t.persister||Gr(this.#t,this.#n),this.#r=!0):(this.#t=t.store||$s,this.#e=t.persister||qr,this.#n="copio-db"),this.#i=new Xr(`${this.#n}-blobs`)}get store(){return this.#t}get persister(){return this.#e}get blobStore(){return this.#i}#d(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#s.add(e),this.#a.has(t)||this.#a.set(t,[]),this.#a.get(t).push(e)),e}revokeDocUrls(t){let e=this.#a.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#s.delete(i)}this.#a.delete(t)}for(let[i,n]of this.#l.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(n)}catch{}this.#l.delete(i)}for(let[i,n]of this.#o.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(n)}catch{}this.#o.delete(i)}this.#h.delete(t)}revokeAllUrls(){for(let t of this.#s)try{URL.revokeObjectURL(t)}catch{}this.#s.clear(),this.#a.clear(),this.#l.clear(),this.#o.clear(),this.#h.clear()}async init(){return this.#u?this.#u:(this.#u=(async()=>{this.#r?(await this.#e.load(),this.#e.startAutoLoad(),this.#e.startAutoSave()):await this.#e.load(),await this.sweepOrphans();let t=!0;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{t=await navigator.storage.persisted()}catch{}return{kind:"indexeddb",persistent:t}})(),this.#u)}async sweepOrphans(){let t=Object.keys(this.#t.getTable("docs")||{});return this.#i.sweepOrphans(t)}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#c(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(this.#h.has(t))return this.#h.get(t);if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#c(e.pages)}}async getDoc(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t),i=this.#c(e.pages),n=await Promise.all(i.map(async c=>{if(!c)return c;let l={...c},h=`${t}:${c.id}`,m=await this.#i.get(`${t}:${c.id}`);m&&(l.blob=m,this.#l.has(h)?l.src=this.#l.get(h):(l.src=this.#d(t,URL.createObjectURL(m)),this.#l.set(h,l.src)));let u=`${t}:${c.id}:orig`,a=await this.#i.get(`${t}:${c.id}:original`);return a?(l.originalBlob=a,this.#o.has(u)?l.originalSrc=this.#o.get(u):(l.originalSrc=this.#d(t,URL.createObjectURL(a)),this.#o.set(u,l.originalSrc))):l.blob&&(l.originalBlob=l.blob,l.originalSrc=l.src),l})),o={id:t,name:e.name||"",pages:n};return this.#h.set(t,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#c(e.pages),n=[],o=[],c=[];for(let l of i){if(!l)continue;let h=is(l.src)||(l.src instanceof Blob?l.src:null)||(l.blob instanceof Blob?l.blob:null),m=h?.type||"image/jpeg",u={id:l.id,name:l.name||"",type:l.type||"image",hasBlob:!0,mimeType:m,edits:l.edits,exif:l.exif,content:l.content,ocrText:l.ocrText??null,ocrConfidence:l.ocrConfidence??null,ocrWords:Array.isArray(l.ocrWords)?l.ocrWords:null,ocrWidth:l.ocrWidth??null,ocrHeight:l.ocrHeight??null};n.push(u);let a=`${t}:${l.id}`,f=`${t}:${l.id}:orig`,w={...l},E=this.#l.get(a),p=typeof l.src=="string"&&l.src.startsWith("data:")||l.src instanceof Blob||l.src&&E&&l.src!==E;if(h)if(w.blob=h,p||!E){if(E){try{URL.revokeObjectURL(E)}catch{}this.#s.delete(E)}let x=this.#d(t,URL.createObjectURL(h));this.#l.set(a,x),w.src=x}else w.src=E;let y=is(l.originalSrc)||(l.originalSrc instanceof Blob?l.originalSrc:null)||(l.originalBlob instanceof Blob?l.originalBlob:null),r=this.#o.get(f),d=!r&&!y&&(!l.originalSrc||l.originalSrc===l.src);d&&h&&(y=h);let b=typeof l.originalSrc=="string"&&l.originalSrc.startsWith("data:")||l.originalSrc instanceof Blob||d&&!!y;if(y)if(w.originalBlob=y,b||!r){if(r&&b){try{URL.revokeObjectURL(r)}catch{}this.#s.delete(r)}let x=this.#d(t,URL.createObjectURL(y));this.#o.set(f,x),w.originalSrc=x}else w.originalSrc=r;else r?w.originalSrc=r:l.originalSrc?w.originalSrc=l.originalSrc:(w.originalSrc=w.src,w.blob&&(w.originalBlob=w.blob));o.push(w),c.push({pageId:l.id,page:l,srcBlob:h,origBlob:y})}this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(n)}),this.#h.set(t,{id:t,name:e.name||"",pages:o});for(let l of c){let{pageId:h,page:m,srcBlob:u,origBlob:a}=l;if(!u&&typeof m.src=="string"&&m.src.startsWith("blob:"))try{u=await(await fetch(m.src)).blob()}catch{}if(u&&await this.#i.put(`${t}:${h}`,u),!a&&typeof m.originalSrc=="string"&&m.originalSrc.startsWith("blob:"))try{a=await(await fetch(m.originalSrc)).blob()}catch{}a&&await this.#i.put(`${t}:${h}:original`,a)}}async deleteDoc(t){this.#t.delRow("docs",t),await this.#i.deleteByPrefix(`${t}:`),this.revokeDocUrls(t),this.#h.delete(t)}async renameDoc(t,e){if(!this.#t.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#t.setCell("docs",t,"name",e),this.#h.has(t)&&(this.#h.get(t).name=e)}async savePage(t,e,i){let n=await this.getDoc(t);if(!n)throw new Error(`Document ${t} not found`);let o=n.pages.findIndex(h=>h.id===e),c;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?n.pages[o]={...n.pages[o],...i}:n.pages[o]={...n.pages[o],src:i,blob:i instanceof Blob?i:void 0},c=n.pages[o];else{let h=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};n.pages.push(h),c=h}let l=is(c.src)||(c.src instanceof Blob?c.src:null)||(c.blob instanceof Blob?c.blob:null);if(!l&&typeof c.src=="string"&&c.src.startsWith("blob:"))try{l=await(await fetch(c.src)).blob()}catch{}l&&await this.#i.put(`${t}:${e}`,l),await this.saveDoc(t,n)}async getPage(t,e){let i=await this.#i.get(`${t}:${e}`);if(i)return i;let n=this.getDocSync(t);if(!n)return null;let o=n.pages.find(c=>c.id===e);return o?o.content??o.src??o:null}async deletePage(t,e){let i=this.getDocSync(t);if(!i)return;i.pages=i.pages.filter(c=>c.id!==e),this.#t.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),await this.#i.delete(`${t}:${e}`),await this.#i.delete(`${t}:${e}:original`);let n=`${t}:${e}`;if(this.#l.has(n)){try{URL.revokeObjectURL(this.#l.get(n))}catch{}this.#l.delete(n)}let o=`${t}:${e}:orig`;if(this.#o.has(o)){try{URL.revokeObjectURL(this.#o.get(o))}catch{}this.#o.delete(o)}this.#h.delete(t)}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#c(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};async function Kr(){if(typeof location<"u"&&location.search&&(new URLSearchParams(location.search).has("no-opfs")||new URLSearchParams(location.search).get("storage")==="indexeddb")||typeof navigator>"u"||!navigator.storage||typeof navigator.storage.getDirectory!="function")return!1;try{let s=await navigator.storage.getDirectory();if(!s)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,e=await s.getFileHandle(t,{create:!0}),i=await e.createWritable();if(await i.write(new Uint8Array([1,2,3,4])),await i.close(),(await e.getFile()).size!==4)throw new Error("OPFS probe size mismatch");return await s.removeEntry(t),!0}catch{return!1}}function Jd(s,t,e="store.json"){let i=0,n=null,o=Promise.resolve(),c=0,l=()=>typeof t=="function"?t():t,h=async()=>{await o;let f=l();if(f){i=1;try{let p=await(await(await f.getFileHandle(e)).getFile()).text();p&&p.trim().length>0&&s.setJson(p)}catch{}finally{i=0}}},m=()=>{let f=l();return f?(c++,i=2,o=o.catch(()=>{}).then(async()=>{try{let w=s.getJson(),p=await(await f.getFileHandle(e,{create:!0})).createWritable();await p.write(w),await p.close()}catch(w){console.warn("[OpfsPersister] Failed to save store.json:",w)}finally{c--,c<=0&&(c=0,i=0)}}),o):Promise.resolve()};return{load:h,save:m,startAutoSave:()=>{n||(n=s.addDidFinishTransactionListener(()=>{m()}))},stopAutoSave:()=>{n&&(s.delListener(n),n=null)},getStatus:()=>i,getStore:()=>s}}async function kc(s){let t=[];try{if(typeof s.entries=="function")for await(let e of s.entries())t.push(e);else if(typeof s.values=="function")for await(let e of s.values())t.push([e.name,e])}catch(e){console.warn("[OpfsAdapter] Error reading directory entries:",e)}return t}var ss=class extends ke{#t;#e="copio";#i=null;#n=null;#r=null;#s=null;#a=null;#l=!1;#o=null;#h=new Set;#u=new Map;#d=new Map;#c=new Map;#f=new Map;#g=null;constructor(t={}){super(),this.#t=t,this.#e=t.dirName||"copio",t.store?this.#s=t.store:t.dirName&&t.dirName!=="copio"?(this.#s=Qi(),this.#s.setTable("docs",{})):this.#s=$s,this.#a=t.persister||Jd(this.#s,()=>this.#n,"store.json")}get store(){return this.#l?this.#o?.store:this.#s}get persister(){return this.#l?this.#o?.persister:this.#a}get isFallback(){return this.#l}get fallbackAdapter(){return this.#o}async#p(){if(this.#l)return!1;if(this.#r&&this.#n)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#i=await navigator.storage.getDirectory(),this.#n=await this.#i.getDirectoryHandle(this.#e,{create:!0}),this.#r=await this.#n.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#m(),!1}else return await this.#m(),!1}#y(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#h.add(e),this.#u.has(t)||this.#u.set(t,[]),this.#u.get(t).push(e)),e}revokeDocUrls(t){if(this.#l){this.#o?.revokeDocUrls(t);return}let e=this.#u.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#h.delete(i)}this.#u.delete(t)}for(let[i,n]of this.#d.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(n)}catch{}this.#d.delete(i)}for(let[i,n]of this.#c.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(n)}catch{}this.#c.delete(i)}this.#f.delete(t)}revokeAllUrls(){if(this.#l){this.#o?.revokeAllUrls();return}for(let t of this.#h)try{URL.revokeObjectURL(t)}catch{}this.#h.clear(),this.#u.clear(),this.#d.clear(),this.#c.clear(),this.#f.clear()}async init(){return this.#g?this.#g:(this.#g=(async()=>{if(this.#t.forceFallback)return this.#m();if(!await Kr())return this.#m();try{await this.#p(),await this.#a.load(),this.#a.startAutoSave(),await this.sweepOrphans();let e=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:e}}catch(e){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",e),this.#m()}})(),this.#g)}async#m(){return this.#l=!0,this.#o=new Ge(this.#t),{kind:"indexeddb",persistent:(await this.#o.init()).persistent}}async sweepOrphans(){if(this.#l)return this.#o?.sweepOrphans();if(await this.#p(),!this.#r)return 0;let t=0,e=this.#s.getTable("docs")||{},i=new Set(Object.keys(e)),n=new Map;for(let[c,l]of Object.entries(e)){let h=this.#b(l.pages);n.set(c,new Set(h.map(m=>m.id)))}let o=await kc(this.#r);for(let[c,l]of o)if(l.kind==="directory")if(i.has(c)){let h=n.get(c)||new Set,m=l,u=await kc(m);for(let[a]of u){let f=a.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!h.has(f))try{await m.removeEntry(a),t++}catch{}}}else try{await this.#r.removeEntry(c,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#l)return this.#o?.listDocsSync();let t=this.#s.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#b(i.pages)}))}async listDocs(){return this.#l?this.#o?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#l)return this.#o?.getDocSync(t);if(this.#f.has(t))return this.#f.get(t);if(!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#b(e.pages)}}async getDoc(t){if(this.#l)return this.#o?.getDoc(t);if(await this.#p(),!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t),i=this.#b(e.pages),n=null;if(this.#r)try{n=await this.#r.getDirectoryHandle(t)}catch{}let o=await Promise.all(i.map(async l=>{if(!l||!n)return l;let h={...l},m=`${t}:${l.id}`;try{let f=await(await n.getFileHandle(`${l.id}.bin`)).getFile();h.blob=f,this.#d.has(m)?h.src=this.#d.get(m):(h.src=this.#y(t,URL.createObjectURL(f)),this.#d.set(m,h.src))}catch{}let u=`${t}:${l.id}:orig`;try{let f=await(await n.getFileHandle(`${l.id}-original.bin`)).getFile();h.originalBlob=f,this.#c.has(u)?h.originalSrc=this.#c.get(u):(h.originalSrc=this.#y(t,URL.createObjectURL(f)),this.#c.set(u,h.originalSrc))}catch{h.blob&&(h.originalBlob=h.blob,h.originalSrc=h.src)}return h})),c={id:t,name:e.name||"",pages:o};return this.#f.set(t,c),c}async saveDoc(t,e){if(this.#l)return this.#o?.saveDoc(t,e);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#b(e.pages),n=[],o=[],c=[];for(let h of i){if(!h)continue;let m=is(h.src)||(h.src instanceof Blob?h.src:null)||(h.blob instanceof Blob?h.blob:null),u=m?.type||"image/jpeg",a={id:h.id,name:h.name||"",type:h.type||"image",hasBlob:!0,mimeType:u,edits:h.edits,exif:h.exif,content:h.content,ocrText:h.ocrText??null,ocrConfidence:h.ocrConfidence??null,ocrWords:Array.isArray(h.ocrWords)?h.ocrWords:null,ocrWidth:h.ocrWidth??null,ocrHeight:h.ocrHeight??null};n.push(a);let f=`${t}:${h.id}`,w=`${t}:${h.id}:orig`,E={...h},p=this.#d.get(f),y=typeof h.src=="string"&&h.src.startsWith("data:")||h.src instanceof Blob||h.src&&p&&h.src!==p;if(m)if(E.blob=m,y||!p){if(p){try{URL.revokeObjectURL(p)}catch{}this.#h.delete(p)}let _=this.#y(t,URL.createObjectURL(m));this.#d.set(f,_),E.src=_}else E.src=p;let r=is(h.originalSrc)||(h.originalSrc instanceof Blob?h.originalSrc:null)||(h.originalBlob instanceof Blob?h.originalBlob:null),d=this.#c.get(w),b=!d&&!r&&(!h.originalSrc||h.originalSrc===h.src);b&&m&&(r=m);let x=typeof h.originalSrc=="string"&&h.originalSrc.startsWith("data:")||h.originalSrc instanceof Blob||b&&!!r;if(r)if(E.originalBlob=r,x||!d){if(d&&x){try{URL.revokeObjectURL(d)}catch{}this.#h.delete(d)}let _=this.#y(t,URL.createObjectURL(r));this.#c.set(w,_),E.originalSrc=_}else E.originalSrc=d;else d?E.originalSrc=d:h.originalSrc?E.originalSrc=h.originalSrc:(E.originalSrc=E.src,E.blob&&(E.originalBlob=E.blob));o.push(E),c.push({pageId:h.id,page:h,srcBlob:m,origBlob:r})}if(this.#s.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(n)}),this.#f.set(t,{id:t,name:e.name||"",pages:o}),await this.#p(),this.#l)return this.#o?.saveDoc(t,e);let l=null;if(this.#r)try{l=await this.#r.getDirectoryHandle(t,{create:!0})}catch(h){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,h)}if(l)for(let h of c){let{pageId:m,page:u,srcBlob:a,origBlob:f}=h;if(!a&&typeof u.src=="string"&&u.src.startsWith("blob:"))try{a=await(await fetch(u.src)).blob()}catch{}if(a)try{let E=await(await l.getFileHandle(`${m}.bin`,{create:!0})).createWritable();await E.write(a),await E.close()}catch(w){console.warn(`[OpfsAdapter] Failed writing page file "${m}.bin":`,w)}if(!f&&typeof u.originalSrc=="string"&&u.originalSrc.startsWith("blob:"))try{f=await(await fetch(u.originalSrc)).blob()}catch{}if(f)try{let E=await(await l.getFileHandle(`${m}-original.bin`,{create:!0})).createWritable();await E.write(f),await E.close()}catch{}}}async deleteDoc(t){if(this.#l)return this.#o?.deleteDoc(t);if(this.#s.delRow("docs",t),this.#f.delete(t),this.revokeDocUrls(t),await this.#p(),this.#r)try{await this.#r.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,e){if(this.#l)return this.#o?.renameDoc(t,e);if(!this.#s.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#s.setCell("docs",t,"name",e),this.#f.has(t)&&(this.#f.get(t).name=e)}async savePage(t,e,i){if(this.#l)return this.#o?.savePage(t,e,i);await this.#p();let n=await this.getDoc(t);if(!n)throw new Error(`Document ${t} not found`);let o=n.pages.findIndex(h=>h.id===e),c;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?n.pages[o]={...n.pages[o],...i}:n.pages[o]={...n.pages[o],src:i,blob:i instanceof Blob?i:void 0},c=n.pages[o];else{let h=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};n.pages.push(h),c=h}let l=is(c.src)||(c.src instanceof Blob?c.src:null)||(c.blob instanceof Blob?c.blob:null);if(!l&&typeof c.src=="string"&&c.src.startsWith("blob:"))try{l=await(await fetch(c.src)).blob()}catch{}if(l&&this.#r)try{let u=await(await(await this.#r.getDirectoryHandle(t,{create:!0})).getFileHandle(`${e}.bin`,{create:!0})).createWritable();await u.write(l),await u.close()}catch(h){console.warn(`[OpfsAdapter] Failed writing page file "${e}.bin":`,h)}await this.saveDoc(t,n)}async getPage(t,e){if(this.#l)return this.#o?.getPage(t,e);if(await this.#p(),this.#r)try{return await(await(await this.#r.getDirectoryHandle(t)).getFileHandle(`${e}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let n=i.pages.find(o=>o.id===e);return n?n.content??n.src??n:null}async deletePage(t,e){if(this.#l)return this.#o?.deletePage(t,e);await this.#p();let i=this.getDocSync(t);if(!i)return;if(i.pages=i.pages.filter(c=>c.id!==e),this.#s.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),this.#r){try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}.bin`)}catch{}try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}-original.bin`)}catch{}}let n=`${t}:${e}`;if(this.#d.has(n)){try{URL.revokeObjectURL(this.#d.get(n))}catch{}this.#d.delete(n)}let o=`${t}:${e}:orig`;if(this.#c.has(o)){try{URL.revokeObjectURL(this.#c.get(o))}catch{}this.#c.delete(o)}this.#f.delete(t)}subscribe(t){if(this.#l)return this.#o?.subscribe(t);let e=this.#s.addTableListener("docs",t);return()=>{this.#s.delListener(e)}}#b(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function Us(s={}){return s.forceMemory?new Ai:s.forceIndexedDb?new Ge(s):s.forceOpfs?new ss(s):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new ss(s):typeof indexedDB<"u"?new Ge(s):new Ai}function Nt(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}var Ma=typeof self<"u"?self:global,Tn=typeof navigator<"u",Qd=Tn&&typeof HTMLImageElement>"u",Dc=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),Ia=Ma.Buffer,Yr=Ma.BigInt,La=!!Ia,Jr=s=>zc(s)?void 0:s,Zd=s=>s!==void 0;function zc(s){return s===void 0||(s instanceof Map?s.size===0:Object.values(s).filter(Zd).length===0)}function re(s){let t=new Error(s);throw delete t.stack,t}function jc(s){return(s=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(s).trim())===""?void 0:s}function Rc(s){let t=(function(e){let i=0;return e.ifd0.enabled&&(i+=1024),e.exif.enabled&&(i+=2048),e.makerNote&&(i+=2048),e.userComment&&(i+=1024),e.gps.enabled&&(i+=512),e.interop.enabled&&(i+=100),e.ifd1.enabled&&(i+=1024),i+2048})(s);return s.jfif.enabled&&(t+=50),s.xmp.enabled&&(t+=2e4),s.iptc.enabled&&(t+=14e3),s.icc.enabled&&(t+=6e3),t}var Aa=s=>String.fromCharCode.apply(null,s),Mc=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function Vc(s){return Mc?Mc.decode(s):La?Buffer.from(s).toString("utf8"):decodeURIComponent(escape(Aa(s)))}var oi=class s{static from(t,e){return t instanceof this&&t.le===e?t:new s(t,void 0,void 0,e)}constructor(t,e=0,i,n){if(typeof n=="boolean"&&(this.le=n),Array.isArray(t)&&(t=new Uint8Array(t)),t===0)this.byteOffset=0,this.byteLength=0;else if(t instanceof ArrayBuffer){i===void 0&&(i=t.byteLength-e);let o=new DataView(t,e,i);this._swapDataView(o)}else if(t instanceof Uint8Array||t instanceof DataView||t instanceof s){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&re("Creating view outside of available memory in ArrayBuffer");let o=new DataView(t.buffer,e,i);this._swapDataView(o)}else if(typeof t=="number"){let o=new DataView(new ArrayBuffer(t));this._swapDataView(o)}else re("Invalid input argument for BufferView: "+t)}_swapArrayBuffer(t){this._swapDataView(new DataView(t))}_swapBuffer(t){this._swapDataView(new DataView(t.buffer,t.byteOffset,t.byteLength))}_swapDataView(t){this.dataView=t,this.buffer=t.buffer,this.byteOffset=t.byteOffset,this.byteLength=t.byteLength}_lengthToEnd(t){return this.byteLength-t}set(t,e,i=s){return t instanceof DataView||t instanceof s?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||re("BufferView.set(): Invalid data argument."),this.toUint8().set(t,e),new i(this,e,t.byteLength)}subarray(t,e){return e=e||this._lengthToEnd(t),new s(this,t,e)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(t,e){return new Uint8Array(this.buffer,this.byteOffset+t,e)}getString(t=0,e=this.byteLength){return Vc(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return Aa(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let n=0;n<e&&t+n<this.byteLength;n+=2)i.push(this.getUint16(t+n));return Aa(i)}getInt8(t){return this.dataView.getInt8(t)}getUint8(t){return this.dataView.getUint8(t)}getInt16(t,e=this.le){return this.dataView.getInt16(t,e)}getInt32(t,e=this.le){return this.dataView.getInt32(t,e)}getUint16(t,e=this.le){return this.dataView.getUint16(t,e)}getUint32(t,e=this.le){return this.dataView.getUint32(t,e)}getFloat32(t,e=this.le){return this.dataView.getFloat32(t,e)}getFloat64(t,e=this.le){return this.dataView.getFloat64(t,e)}getFloat(t,e=this.le){return this.dataView.getFloat32(t,e)}getDouble(t,e=this.le){return this.dataView.getFloat64(t,e)}getUintBytes(t,e,i){switch(e){case 1:return this.getUint8(t,i);case 2:return this.getUint16(t,i);case 4:return this.getUint32(t,i);case 8:return this.getUint64&&this.getUint64(t,i)}}getUint(t,e,i){switch(e){case 8:return this.getUint8(t,i);case 16:return this.getUint16(t,i);case 32:return this.getUint32(t,i);case 64:return this.getUint64&&this.getUint64(t,i)}}toString(t){return this.dataView.toString(t,this.constructor.name)}ensureChunk(){}};function Sa(s,t){re(`${s} '${t}' was not loaded, try using full build of exifr.`)}var Pn=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||Sa(this.kind,t),e&&(t in e||(function(i,n){re(`Unknown ${i} '${n}'.`)})(this.kind,t),e[t].enabled||Sa(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},hs=new Pn("file parser"),me=new Pn("segment parser"),ds=new Pn("file reader"),Wc=Ma.fetch;function Ic(s,t){return(e=s).startsWith("data:")||e.length>1e4?Ca(s,t,"base64"):Dc&&s.includes("://")?Ea(s,t,"url",js):Dc?Ca(s,t,"fs"):Tn?Ea(s,t,"url",js):void re("Invalid input argument");var e}async function Ea(s,t,e,i){return ds.has(e)?Ca(s,t,e):i?(async function(n,o){let c=await o(n);return new oi(c)})(s,i):void re(`Parser ${e} is not loaded`)}async function Ca(s,t,e){let i=new(ds.get(e))(s,t);return await i.read(),i}var js=s=>Wc(s).then((t=>t.arrayBuffer())),Vs=s=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(s)})),_a=class extends Map{get tagKeys(){return this.allKeys||(this.allKeys=Array.from(this.keys())),this.allKeys}get tagValues(){return this.allValues||(this.allValues=Array.from(this.values())),this.allValues}};function Oe(s,t,e){let i=new _a;for(let[n,o]of e)i.set(n,o);if(Array.isArray(t))for(let n of t)s.set(n,i);else s.set(t,i);return i}function Fa(s,t,e){let i,n=s.get(t);for(i of e)n.set(i[0],i[1])}var ri=new Map,Gs=new Map,cs=new Map,rs=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],kn=["jfif","xmp","icc","iptc","ihdr"],Ws=["tiff",...kn],Zt=["ifd0","ifd1","exif","gps","interop"],os=[...Ws,...Zt],as=["makerNote","userComment"],Dn=["translateKeys","translateValues","reviveValues","multiSegment"],ls=[...Dn,"sanitize","mergeOutput","silentErrors"],Qr=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},ns=class extends Qr{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,n){if(super(),Nt(this,"enabled",!1),Nt(this,"skip",new Set),Nt(this,"pick",new Set),Nt(this,"deps",new Set),Nt(this,"translateKeys",!1),Nt(this,"translateValues",!1),Nt(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(n),this.canBeFiltered=Zt.includes(t),this.canBeFiltered&&(this.dict=ri.get(t)),i!==void 0)if(Array.isArray(i))this.parse=this.enabled=!0,this.canBeFiltered&&i.length>0&&this.translateTagSet(i,this.pick);else if(typeof i=="object"){if(this.enabled=!0,this.parse=i.parse!==!1,this.canBeFiltered){let{pick:o,skip:c}=i;o&&o.length>0&&this.translateTagSet(o,this.pick),c&&c.length>0&&this.translateTagSet(c,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:re(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of Dn)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,n,{tagKeys:o,tagValues:c}=this.dict;for(i of t)typeof i=="string"?(n=c.indexOf(i),n===-1&&(n=o.indexOf(Number(i))),n!==-1&&e.add(Number(o[n]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,Zr(this.pick,this.deps)):this.enabled&&this.pick.size>0&&Zr(this.pick,this.deps)}},ge={jfif:!1,tiff:!0,xmp:!1,icc:!1,iptc:!1,ifd0:!0,ifd1:!1,exif:!0,gps:!0,interop:!1,ihdr:void 0,makerNote:!1,userComment:!1,multiSegment:!1,skip:[],pick:[],translateKeys:!0,translateValues:!0,reviveValues:!0,sanitize:!0,mergeOutput:!0,silentErrors:!0,chunked:!0,firstChunkSize:void 0,firstChunkSizeNode:512,firstChunkSizeBrowser:65536,chunkSize:65536,chunkLimit:5},Lc=new Map,Pi=class extends Qr{static useCached(t){let e=Lc.get(t);return e!==void 0||(e=new this(t),Lc.set(t,e)),e}constructor(t){super(),t===!0?this.setupFromTrue():t===void 0?this.setupFromUndefined():Array.isArray(t)?this.setupFromArray(t):typeof t=="object"?this.setupFromObject(t):re(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=Tn?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of rs)this[t]=ge[t];for(t of ls)this[t]=ge[t];for(t of as)this[t]=ge[t];for(t of os)this[t]=new ns(t,ge[t],void 0,this)}setupFromTrue(){let t;for(t of rs)this[t]=ge[t];for(t of ls)this[t]=ge[t];for(t of as)this[t]=!0;for(t of os)this[t]=new ns(t,!0,void 0,this)}setupFromArray(t){let e;for(e of rs)this[e]=ge[e];for(e of ls)this[e]=ge[e];for(e of as)this[e]=ge[e];for(e of os)this[e]=new ns(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,Zt)}setupFromObject(t){let e;for(e of(Zt.ifd0=Zt.ifd0||Zt.image,Zt.ifd1=Zt.ifd1||Zt.thumbnail,Object.assign(this,t),rs))this[e]=va(t[e],ge[e]);for(e of ls)this[e]=va(t[e],ge[e]);for(e of as)this[e]=va(t[e],ge[e]);for(e of Ws)this[e]=new ns(e,ge[e],t[e],this);for(e of Zt)this[e]=new ns(e,ge[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,Zt,os),t.tiff===!0?this.batchEnableWithBool(Zt,!0):t.tiff===!1?this.batchEnableWithUserValue(Zt,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,Zt):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,Zt)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let n=e[i];this[i].enabled=n!==!1&&n!==void 0}}setupGlobalFilters(t,e,i,n=i){if(t&&t.length){for(let c of n)this[c].enabled=!1;let o=Fc(t,i);for(let[c,l]of o)Zr(this[c].pick,l),this[c].enabled=!0}else if(e&&e.length){let o=Fc(e,i);for(let[c,l]of o)Zr(this[c].skip,l)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:n,icc:o}=this;this.makerNote?e.deps.add(37500):e.skip.add(37500),this.userComment?e.deps.add(37510):e.skip.add(37510),i.enabled||t.skip.add(700),n.enabled||t.skip.add(33723),o.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:n}=this;n.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=Zt.some((o=>this[o].enabled===!0))||this.makerNote||this.userComment;for(let o of Zt)this[o].finalizeFilters()}get onlyTiff(){return!kn.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of Ws)this[t].enabled&&!me.has(t)&&Sa("segment parser",t)}};function Fc(s,t){let e,i,n,o,c=[];for(n of t){for(o of(e=ri.get(n),i=[],e))(s.includes(o[0])||s.includes(o[1]))&&i.push(o[0]);i.length&&c.push([n,i])}return c}function va(s,t){return s!==void 0?s:t!==void 0?t:void 0}function Zr(s,t){for(let e of t)s.add(e)}Nt(Pi,"default",ge);var ai=class{constructor(t){Nt(this,"parsers",{}),Nt(this,"output",{}),Nt(this,"errors",[]),Nt(this,"pushToErrors",(e=>this.errors.push(e))),this.options=Pi.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?Ic(e,i):Tn&&!Qd&&e instanceof HTMLImageElement?Ic(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new oi(e):Tn&&e instanceof Blob?Ea(e,i,"blob",Vs):void re("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,n]of hs)if(n.canHandle(t,e))return this.fileParser=new n(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),re("Unknown file format")}async parse(){let{output:t,errors:e}=this;return this.setup(),this.options.silentErrors?(await this.executeParsers().catch(this.pushToErrors),e.push(...this.fileParser.errors)):await this.executeParsers(),this.file.close&&this.file.close(),this.options.silentErrors&&e.length>0&&(t.errors=e),Jr(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let n=await i.parse();i.assignToOutput(t,n)}));this.options.silentErrors&&(e=e.map((i=>i.catch(this.pushToErrors)))),await Promise.all(e)}async extractThumbnail(){this.setup();let{options:t,file:e}=this,i=me.get("tiff",t);var n;if(e.tiff?n={start:0,type:"tiff"}:e.jpeg&&(n=await this.fileParser.getOrFindSegment("tiff")),n===void 0)return;let o=await this.fileParser.ensureSegmentChunk(n),c=this.parsers.tiff=new i(o,t,e),l=await c.extractThumbnail();return e.close&&e.close(),l}};async function Oa(s,t){let e=new ai(t);return await e.read(s),e.parse()}var tu=Object.freeze({__proto__:null,parse:Oa,Exifr:ai,fileParsers:hs,segmentParsers:me,fileReaders:ds,tagKeys:ri,tagValues:Gs,tagRevivers:cs,createDictionary:Oe,extendDictionary:Fa,fetchUrlAsArrayBuffer:js,readBlobAsArrayBuffer:Vs,chunkedProps:rs,otherSegments:kn,segments:Ws,tiffBlocks:Zt,segmentsAndBlocks:os,tiffExtractables:as,inheritables:Dn,allFormatters:ls,Options:Pi}),to=class{constructor(t,e,i){Nt(this,"errors",[]),Nt(this,"ensureSegmentChunk",(async n=>{let o=n.start,c=n.size||65536;if(this.file.chunked)if(this.file.available(o,c))n.chunk=this.file.subarray(o,c);else try{n.chunk=await this.file.readChunk(o,c)}catch(l){re(`Couldn't read segment: ${JSON.stringify(n)}. ${l.message}`)}else this.file.byteLength>o+c?n.chunk=this.file.subarray(o,c):n.size===void 0?n.chunk=this.file.subarray(o):re("Segment unreachable: "+JSON.stringify(n));return n.chunk})),this.extendOptions&&this.extendOptions(t),this.options=t,this.file=e,this.parsers=i}injectSegment(t,e){this.options[t].enabled&&this.createParser(t,e)}createParser(t,e){let i=new(me.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:n}=e,o=this.options[i];if(o&&o.enabled){let c=this.parsers[i];c&&c.append||c||this.createParser(i,n)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},ni=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,n=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,o=e+n,c=i-n;return{offset:e,length:i,headerLength:n,start:o,size:c,end:o+c}}static parse(t,e={}){return new this(t,new Pi({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof oi?t:new oi(t)}constructor(t,e={},i){Nt(this,"errors",[]),Nt(this,"raw",new Map),Nt(this,"handleError",(n=>{if(!this.options.silentErrors)throw n;this.errors.push(n.message)})),this.chunk=this.normalizeInput(t),this.file=i,this.type=this.constructor.type,this.globalOptions=this.options=e,this.localOptions=e[this.type],this.canTranslate=this.localOptions&&this.localOptions.translate}translate(){this.canTranslate&&(this.translated=this.translateBlock(this.raw,this.type))}get output(){return this.translated?this.translated:this.raw?Object.fromEntries(this.raw):void 0}translateBlock(t,e){let i=cs.get(e),n=Gs.get(e),o=ri.get(e),c=this.options[e],l=c.reviveValues&&!!i,h=c.translateValues&&!!n,m=c.translateKeys&&!!o,u={};for(let[a,f]of t)l&&i.has(a)?f=i.get(a)(f):h&&n.has(a)&&(f=this.translateValue(f,n.get(a))),m&&o.has(a)&&(a=o.get(a)||a),u[a]=f;return u}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};Nt(ni,"headerLength",4),Nt(ni,"type",void 0),Nt(ni,"multiSegment",!1),Nt(ni,"canHandle",(()=>!1));function eu(s){return s===192||s===194||s===196||s===219||s===221||s===218||s===254}function iu(s){return s>=224&&s<=239}function su(s,t,e){for(let[i,n]of me)if(n.canHandle(s,t,e))return i}var eo=class extends to{constructor(...t){super(...t),Nt(this,"appSegments",[]),Nt(this,"jpegSegments",[]),Nt(this,"unknownSegments",[])}static canHandle(t,e){return e===65496}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(t){t===!0?(this.findAll=!0,this.wanted=new Set(me.keyList())):(t=t===void 0?me.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&me.has(e))),this.findAll=!1,this.remaining=new Set(t),this.wanted=new Set(t)),this.unfinishedMultiSegment=!1}async findAppSegments(t=0,e){this.setupSegmentFinderArgs(e);let{file:i,findAll:n,wanted:o,remaining:c}=this;if(!n&&this.file.chunked&&(n=Array.from(o).some((l=>{let h=me.get(l),m=this.options[l];return h.multiSegment&&m.multiSegment})),n&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let l=!1;for(;c.size>0&&!l&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:h}=i,m=this.appSegments.some((u=>!this.file.available(u.offset||u.start,u.length||u.size)));if(l=t>h&&!m?!await i.readNextChunk(t):!await i.readNextChunk(h),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,n,o,c,l,h,{file:m,findAll:u,wanted:a,remaining:f,options:w}=this;for(;t<e;t++)if(m.getUint8(t)===255){if(i=m.getUint8(t+1),iu(i)){if(n=m.getUint16(t+2),o=su(m,t,n),o&&a.has(o)&&(c=me.get(o),l=c.findPosition(m,t),h=w[o],l.type=o,this.appSegments.push(l),!u&&(c.multiSegment&&h.multiSegment?(this.unfinishedMultiSegment=l.chunkNumber<l.chunkCount,this.unfinishedMultiSegment||f.delete(o)):f.delete(o),f.size===0)))break;w.recordUnknownSegments&&(l=ni.findPosition(m,t),l.marker=i,this.unknownSegments.push(l)),t+=n+1}else if(eu(i)){if(n=m.getUint16(t+2),i===218&&w.stopAfterSos!==!1)return;w.recordJpegSegments&&this.jpegSegments.push({offset:t,length:n,marker:i}),t+=n+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let n,o,c,l=new Map;for(let h=0;h<e.length;h++)n=e[h],o=n[i],l.has(o)?c=l.get(o):l.set(o,c=[]),c.push(n);return Array.from(l)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let n=me.get(e,this.options);return n.handleMultiSegments?{type:e,chunk:n.handleMultiSegments(i)}:i[0]}))}getSegment(t){return this.appSegments.find((e=>e.type===t))}async getOrFindSegment(t){let e=this.getSegment(t);return e===void 0&&(await this.findAppSegments(0,[t]),e=this.getSegment(t)),e}};Nt(eo,"type","jpeg"),hs.set("jpeg",eo);var nu=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],Ta=class extends ni{parseHeader(){var t=this.chunk.getUint16();t===18761?this.le=!0:t===19789&&(this.le=!1),this.chunk.le=this.le,this.headerParsed=!0}parseTags(t,e,i=new Map){let{pick:n,skip:o}=this.options[e];n=new Set(n);let c=n.size>0,l=o.size===0,h=this.chunk.getUint16(t);t+=2;for(let m=0;m<h;m++){let u=this.chunk.getUint16(t);if(c){if(n.has(u)&&(i.set(u,this.parseTag(t,u,e)),n.delete(u),n.size===0))break}else!l&&o.has(u)||i.set(u,this.parseTag(t,u,e));t+=12}return i}parseTag(t,e,i){let{chunk:n}=this,o=n.getUint16(t+2),c=n.getUint32(t+4),l=nu[o];if(l*c<=4?t+=8:t=n.getUint32(t+8),(o<1||o>13)&&re(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t}`),t>n.byteLength&&re(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t} is outside of chunk size ${n.byteLength}`),o===1)return n.getUint8Array(t,c);if(o===2)return jc(n.getString(t,c));if(o===7)return n.getUint8Array(t,c);if(c===1)return this.parseTagValue(o,t);{let h=new((function(u){switch(u){case 1:return Uint8Array;case 3:return Uint16Array;case 4:return Uint32Array;case 5:return Array;case 6:return Int8Array;case 8:return Int16Array;case 9:return Int32Array;case 10:return Array;case 11:return Float32Array;case 12:return Float64Array;default:return Array}})(o))(c),m=l;for(let u=0;u<c;u++)h[u]=this.parseTagValue(o,t),t+=m;return h}}parseTagValue(t,e){let{chunk:i}=this;switch(t){case 1:return i.getUint8(e);case 3:return i.getUint16(e);case 4:return i.getUint32(e);case 5:return i.getUint32(e)/i.getUint32(e+4);case 6:return i.getInt8(e);case 8:return i.getInt16(e);case 9:return i.getInt32(e);case 10:return i.getInt32(e)/i.getInt32(e+4);case 11:return i.getFloat(e);case 12:return i.getDouble(e);case 13:return i.getUint32(e);default:re(`Invalid tiff type ${t}`)}}},En=class extends Ta{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1165519206&&t.getUint16(e+8)===0}async parse(){this.parseHeader();let{options:t}=this;return t.ifd0.enabled&&await this.parseIfd0Block(),t.exif.enabled&&await this.safeParse("parseExifBlock"),t.gps.enabled&&await this.safeParse("parseGpsBlock"),t.interop.enabled&&await this.safeParse("parseInteropBlock"),t.ifd1.enabled&&await this.safeParse("parseThumbnailBlock"),this.createOutput()}safeParse(t){let e=this[t]();return e.catch!==void 0&&(e=e.catch(this.handleError)),e}findIfd0Offset(){this.ifd0Offset===void 0&&(this.ifd0Offset=this.chunk.getUint32(4))}findIfd1Offset(){if(this.ifd1Offset===void 0){this.findIfd0Offset();let t=this.chunk.getUint16(this.ifd0Offset),e=this.ifd0Offset+2+12*t;this.ifd1Offset=this.chunk.getUint32(e)}}parseBlock(t,e){let i=new Map;return this[e]=i,this.parseTags(t,e,i),i}async parseIfd0Block(){if(this.ifd0)return;let{file:t}=this;this.findIfd0Offset(),this.ifd0Offset<8&&re("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&re(`IFD0 offset points to outside of file.
|
|
8
|
-
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,Rc(this.options));let e=this.parseBlock(this.ifd0Offset,"ifd0");return e.size!==0?(this.exifOffset=e.get(34665),this.interopOffset=e.get(40965),this.gpsOffset=e.get(34853),this.xmp=e.get(700),this.iptc=e.get(33723),this.icc=e.get(34675),this.options.sanitize&&(e.delete(34665),e.delete(40965),e.delete(34853),e.delete(700),e.delete(33723),e.delete(34675)),e):void 0}async parseExifBlock(){if(this.exif||(this.ifd0||await this.parseIfd0Block(),this.exifOffset===void 0))return;this.file.tiff&&await this.file.ensureChunk(this.exifOffset,Rc(this.options));let t=this.parseBlock(this.exifOffset,"exif");return this.interopOffset||(this.interopOffset=t.get(40965)),this.makerNote=t.get(37500),this.userComment=t.get(37510),this.options.sanitize&&(t.delete(40965),t.delete(37500),t.delete(37510)),this.unpack(t,41728),this.unpack(t,41729),t}unpack(t,e){let i=t.get(e);i&&i.length===1&&t.set(e,i[0])}async parseGpsBlock(){if(this.gps||(this.ifd0||await this.parseIfd0Block(),this.gpsOffset===void 0))return;let t=this.parseBlock(this.gpsOffset,"gps");return t&&t.has(2)&&t.has(4)&&(t.set("latitude",Oc(...t.get(2),t.get(1))),t.set("longitude",Oc(...t.get(4),t.get(3)))),t}async parseInteropBlock(){if(!this.interop&&(this.ifd0||await this.parseIfd0Block(),this.interopOffset!==void 0||this.exif||await this.parseExifBlock(),this.interopOffset!==void 0))return this.parseBlock(this.interopOffset,"interop")}async parseThumbnailBlock(t=!1){if(!this.ifd1&&!this.ifd1Parsed&&(!this.options.mergeOutput||t))return this.findIfd1Offset(),this.ifd1Offset>0&&(this.parseBlock(this.ifd1Offset,"ifd1"),this.ifd1Parsed=!0),this.ifd1}async extractThumbnail(){if(this.headerParsed||this.parseHeader(),this.ifd1Parsed||await this.parseThumbnailBlock(!0),this.ifd1===void 0)return;let t=this.ifd1.get(513),e=this.ifd1.get(514);return this.chunk.getUint8Array(t,e)}get image(){return this.ifd0}get thumbnail(){return this.ifd1}createOutput(){let t,e,i,n={};for(e of Zt)if(t=this[e],!zc(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(n,i)}else n[e]=i;return this.makerNote&&(n.makerNote=this.makerNote),this.userComment&&(n.userComment=this.userComment),n}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,n]of Object.entries(e))this.assignObjectToOutput(t,i,n)}};function Oc(s,t,e,i){var n=s+t/60+e/3600;return i!=="S"&&i!=="W"||(n*=-1),n}Nt(En,"type","tiff"),Nt(En,"headerLength",10),me.set("tiff",En);var ru=Object.freeze({__proto__:null,default:tu,Exifr:ai,fileParsers:hs,segmentParsers:me,fileReaders:ds,tagKeys:ri,tagValues:Gs,tagRevivers:cs,createDictionary:Oe,extendDictionary:Fa,fetchUrlAsArrayBuffer:js,readBlobAsArrayBuffer:Vs,chunkedProps:rs,otherSegments:kn,segments:Ws,tiffBlocks:Zt,segmentsAndBlocks:os,tiffExtractables:as,inheritables:Dn,allFormatters:ls,Options:Pi,parse:Oa}),Na={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},Gc=Object.assign({},Na,{firstChunkSize:4e4,gps:[1,2,3,4]});async function ou(s){let t=new ai(Gc);await t.read(s);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:n}=e.gps;return{latitude:i,longitude:n}}}var qc=Object.assign({},Na,{tiff:!1,ifd1:!0,mergeOutput:!1});async function au(s){let t=new ai(qc);await t.read(s);let e=await t.extractThumbnail();return e&&La?Ia.from(e):e}async function lu(s){let t=await this.thumbnail(s);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var Xc=Object.assign({},Na,{firstChunkSize:4e4,ifd0:[274]});async function Kc(s){let t=new ai(Xc);await t.read(s);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var Yc=Object.freeze({1:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:0,rad:0},2:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:0,rad:0},3:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:180,rad:180*Math.PI/180},4:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:180,rad:180*Math.PI/180},5:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:90,rad:90*Math.PI/180},6:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:90,rad:90*Math.PI/180},7:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:270,rad:270*Math.PI/180},8:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:270,rad:270*Math.PI/180}}),Hs=!0,zs=!0;if(typeof navigator=="object"){let s=navigator.userAgent;if(s.includes("iPad")||s.includes("iPhone")){let t=s.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;Hs=Number(e)+.1*Number(i)<13.4,zs=!1}}else if(s.includes("OS X 10")){let[,t]=s.match(/OS X 10[_.](\d+)/);Hs=zs=Number(t)<15}if(s.includes("Chrome/")){let[,t]=s.match(/Chrome\/(\d+)/);Hs=zs=Number(t)<81}else if(s.includes("Firefox/")){let[,t]=s.match(/Firefox\/(\d+)/);Hs=zs=Number(t)<77}}async function cu(s){let t=await Kc(s);return Object.assign({canvas:Hs,css:zs},Yc[t])}var Pa=class extends oi{constructor(...t){super(...t),Nt(this,"ranges",new ka),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let n=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(n)}else{let n=t+e;if(n>this.byteLength){let{dataView:o}=this._extend(n);this._swapDataView(o)}}}_extend(t){let e;e=La?Ia.allocUnsafe(t):new Uint8Array(t);let i=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:e,dataView:i}}subarray(t,e,i=!1){return e=e||this._lengthToEnd(t),i&&this._tryExtend(t,e),this.ranges.add(t,e),super.subarray(t,e)}set(t,e,i=!1){i&&this._tryExtend(e,t.byteLength,t);let n=super.set(t,e);return this.ranges.add(e,n.byteLength),n}async ensureChunk(t,e){this.chunked&&(this.ranges.available(t,e)||await this.readChunk(t,e))}available(t,e){return this.ranges.available(t,e)}},ka=class{constructor(){Nt(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let n=t+e,o=this.list.filter((c=>Nc(t,c.offset,n)||Nc(t,c.end,n)));if(o.length>0){t=Math.min(t,...o.map((l=>l.offset))),n=Math.max(n,...o.map((l=>l.end))),e=n-t;let c=o.shift();c.offset=t,c.length=e,c.end=n,this.list=this.list.filter((l=>!o.includes(l)))}else this.list.push({offset:t,length:e,end:n})}available(t,e){let i=t+e;return this.list.some((n=>n.offset<=t&&i<=n.end))}};function Nc(s,t,e){return s<=t&&t<=e}var io=class extends Pa{constructor(t,e){super(0),Nt(this,"chunksRead",0),this.input=t,this.options=e}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(t=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let e=this.options.chunkSize,i=await this.readChunk(t,e);return!!i&&i.byteLength===e}async readChunk(t,e){if(this.chunksRead++,(e=this.safeWrapAddress(t,e))!==0)return this._readChunk(t,e)}safeWrapAddress(t,e){return this.size!==void 0&&t+e>this.size?Math.max(0,this.size-t):e}get nextChunkOffset(){if(this.ranges.list.length!==0)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return this.size!==void 0&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}};ds.set("blob",class extends io{async readWhole(){this.chunked=!1;let s=await Vs(this.input);this._swapArrayBuffer(s)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(s,t){let e=t?s+t:void 0,i=this.input.slice(s,e),n=await Vs(i);return this.set(n,s,!0)}});var hu=Object.freeze({__proto__:null,default:ru,Exifr:ai,fileParsers:hs,segmentParsers:me,fileReaders:ds,tagKeys:ri,tagValues:Gs,tagRevivers:cs,createDictionary:Oe,extendDictionary:Fa,fetchUrlAsArrayBuffer:js,readBlobAsArrayBuffer:Vs,chunkedProps:rs,otherSegments:kn,segments:Ws,tiffBlocks:Zt,segmentsAndBlocks:os,tiffExtractables:as,inheritables:Dn,allFormatters:ls,Options:Pi,parse:Oa,gpsOnlyOptions:Gc,gps:ou,thumbnailOnlyOptions:qc,thumbnail:au,thumbnailUrl:lu,orientationOnlyOptions:Xc,orientation:Kc,rotations:Yc,get rotateCanvas(){return Hs},get rotateCss(){return zs},rotation:cu});ds.set("url",class extends io{async readWhole(){this.chunked=!1;let s=await js(this.input);s instanceof ArrayBuffer?this._swapArrayBuffer(s):s instanceof Uint8Array&&this._swapBuffer(s)}async _readChunk(s,t){let e=t?s+t-1:void 0,i=this.options.httpHeaders||{};(s||e)&&(i.range=`bytes=${[s,e].join("-")}`);let n=await Wc(this.input,{headers:i}),o=await n.arrayBuffer(),c=o.byteLength;if(n.status!==416)return c!==t&&(this.size=s+c),this.set(o,s,!0)}});oi.prototype.getUint64=function(s){let t=this.getUint32(s),e=this.getUint32(s+4);return t<1048575?t<<32|e:typeof Yr!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),Yr(t)<<Yr(32)|Yr(e)):void re("Trying to read 64b value but JS can only handle 53b numbers.")};var Da=class extends to{parseBoxes(t=0){let e=[];for(;t<this.file.byteLength-4;){let i=this.parseBoxHead(t);if(e.push(i),i.length===0)break;t+=i.length}return e}parseSubBoxes(t){t.boxes=this.parseBoxes(t.start)}findBox(t,e){return t.boxes===void 0&&this.parseSubBoxes(t),t.boxes.find((i=>i.kind===e))}parseBoxHead(t){let e=this.file.getUint32(t),i=this.file.getString(t+4,4),n=t+8;return e===1&&(e=this.file.getUint64(t+8),n+=8),{offset:t,length:e,kind:i,start:n}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},so=class extends Da{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let n=16,o=[];for(;n<i;)o.push(t.getString(n,4)),n+=4;return o.includes(this.type)}async parse(){let t=this.file.getUint32(0),e=this.parseBoxHead(t);for(;e.kind!=="meta";)t+=e.length,await this.file.ensureChunk(t,16),e=this.parseBoxHead(t);await this.file.ensureChunk(e.offset,e.length),this.parseBoxFullHead(e),this.parseSubBoxes(e),this.options.icc.enabled&&await this.findIcc(e),this.options.tiff.enabled&&await this.findExif(e)}async registerSegment(t,e,i){await this.file.ensureChunk(e,i);let n=this.file.subarray(e,i);this.createParser(t,n)}async findIcc(t){let e=this.findBox(t,"iprp");if(e===void 0)return;let i=this.findBox(e,"ipco");if(i===void 0)return;let n=this.findBox(i,"colr");n!==void 0&&await this.registerSegment("icc",n.offset+12,n.length)}async findExif(t){let e=this.findBox(t,"iinf");if(e===void 0)return;let i=this.findBox(t,"iloc");if(i===void 0)return;let n=this.findExifLocIdInIinf(e),o=this.findExtentInIloc(i,n);if(o===void 0)return;let[c,l]=o;await this.file.ensureChunk(c,l);let h=4+this.file.getUint32(c);c+=h,l-=h,await this.registerSegment("tiff",c,l)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,n,o,c=t.start,l=this.file.getUint16(c);for(c+=2;l--;){if(e=this.parseBoxHead(c),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(n=e.version===3?4:2,o=this.file.getString(i+n+2,4),o==="Exif"))return this.file.getUintBytes(i,n);c+=e.length}}get8bits(t){let e=this.file.getUint8(t);return[e>>4,15&e]}findExtentInIloc(t,e){this.parseBoxFullHead(t);let i=t.start,[n,o]=this.get8bits(i++),[c,l]=this.get8bits(i++),h=t.version===2?4:2,m=t.version===1||t.version===2?2:0,u=l+n+o,a=t.version===2?4:2,f=this.file.getUintBytes(i,a);for(i+=a;f--;){let w=this.file.getUintBytes(i,h);i+=h+m+2+c;let E=this.file.getUint16(i);if(i+=2,w===e)return E>1&&console.warn(`ILOC box has more than one extent but we're only processing one
|
|
9
|
-
Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+l,n),this.file.getUintBytes(i+l+n,o)];i+=E*u}}},no=class extends so{};Nt(no,"type","heic");var ro=class extends so{};Nt(ro,"type","avif"),hs.set("heic",no),hs.set("avif",ro),Oe(ri,["ifd0","ifd1"],[[256,"ImageWidth"],[257,"ImageHeight"],[258,"BitsPerSample"],[259,"Compression"],[262,"PhotometricInterpretation"],[270,"ImageDescription"],[271,"Make"],[272,"Model"],[273,"StripOffsets"],[274,"Orientation"],[277,"SamplesPerPixel"],[278,"RowsPerStrip"],[279,"StripByteCounts"],[282,"XResolution"],[283,"YResolution"],[284,"PlanarConfiguration"],[296,"ResolutionUnit"],[301,"TransferFunction"],[305,"Software"],[306,"ModifyDate"],[315,"Artist"],[316,"HostComputer"],[317,"Predictor"],[318,"WhitePoint"],[319,"PrimaryChromaticities"],[513,"ThumbnailOffset"],[514,"ThumbnailLength"],[529,"YCbCrCoefficients"],[530,"YCbCrSubSampling"],[531,"YCbCrPositioning"],[532,"ReferenceBlackWhite"],[700,"ApplicationNotes"],[33432,"Copyright"],[33723,"IPTC"],[34665,"ExifIFD"],[34675,"ICC"],[34853,"GpsIFD"],[330,"SubIFD"],[40965,"InteropIFD"],[40091,"XPTitle"],[40092,"XPComment"],[40093,"XPAuthor"],[40094,"XPKeywords"],[40095,"XPSubject"]]),Oe(ri,"exif",[[33434,"ExposureTime"],[33437,"FNumber"],[34850,"ExposureProgram"],[34852,"SpectralSensitivity"],[34855,"ISO"],[34858,"TimeZoneOffset"],[34859,"SelfTimerMode"],[34864,"SensitivityType"],[34865,"StandardOutputSensitivity"],[34866,"RecommendedExposureIndex"],[34867,"ISOSpeed"],[34868,"ISOSpeedLatitudeyyy"],[34869,"ISOSpeedLatitudezzz"],[36864,"ExifVersion"],[36867,"DateTimeOriginal"],[36868,"CreateDate"],[36873,"GooglePlusUploadCode"],[36880,"OffsetTime"],[36881,"OffsetTimeOriginal"],[36882,"OffsetTimeDigitized"],[37121,"ComponentsConfiguration"],[37122,"CompressedBitsPerPixel"],[37377,"ShutterSpeedValue"],[37378,"ApertureValue"],[37379,"BrightnessValue"],[37380,"ExposureCompensation"],[37381,"MaxApertureValue"],[37382,"SubjectDistance"],[37383,"MeteringMode"],[37384,"LightSource"],[37385,"Flash"],[37386,"FocalLength"],[37393,"ImageNumber"],[37394,"SecurityClassification"],[37395,"ImageHistory"],[37396,"SubjectArea"],[37500,"MakerNote"],[37510,"UserComment"],[37520,"SubSecTime"],[37521,"SubSecTimeOriginal"],[37522,"SubSecTimeDigitized"],[37888,"AmbientTemperature"],[37889,"Humidity"],[37890,"Pressure"],[37891,"WaterDepth"],[37892,"Acceleration"],[37893,"CameraElevationAngle"],[40960,"FlashpixVersion"],[40961,"ColorSpace"],[40962,"ExifImageWidth"],[40963,"ExifImageHeight"],[40964,"RelatedSoundFile"],[41483,"FlashEnergy"],[41486,"FocalPlaneXResolution"],[41487,"FocalPlaneYResolution"],[41488,"FocalPlaneResolutionUnit"],[41492,"SubjectLocation"],[41493,"ExposureIndex"],[41495,"SensingMethod"],[41728,"FileSource"],[41729,"SceneType"],[41730,"CFAPattern"],[41985,"CustomRendered"],[41986,"ExposureMode"],[41987,"WhiteBalance"],[41988,"DigitalZoomRatio"],[41989,"FocalLengthIn35mmFormat"],[41990,"SceneCaptureType"],[41991,"GainControl"],[41992,"Contrast"],[41993,"Saturation"],[41994,"Sharpness"],[41996,"SubjectDistanceRange"],[42016,"ImageUniqueID"],[42032,"OwnerName"],[42033,"SerialNumber"],[42034,"LensInfo"],[42035,"LensMake"],[42036,"LensModel"],[42037,"LensSerialNumber"],[42080,"CompositeImage"],[42081,"CompositeImageCount"],[42082,"CompositeImageExposureTimes"],[42240,"Gamma"],[59932,"Padding"],[59933,"OffsetSchema"],[65e3,"OwnerName"],[65001,"SerialNumber"],[65002,"Lens"],[65100,"RawFile"],[65101,"Converter"],[65102,"WhiteBalance"],[65105,"Exposure"],[65106,"Shadows"],[65107,"Brightness"],[65108,"Contrast"],[65109,"Saturation"],[65110,"Sharpness"],[65111,"Smoothness"],[65112,"MoireFilter"],[40965,"InteropIFD"]]),Oe(ri,"gps",[[0,"GPSVersionID"],[1,"GPSLatitudeRef"],[2,"GPSLatitude"],[3,"GPSLongitudeRef"],[4,"GPSLongitude"],[5,"GPSAltitudeRef"],[6,"GPSAltitude"],[7,"GPSTimeStamp"],[8,"GPSSatellites"],[9,"GPSStatus"],[10,"GPSMeasureMode"],[11,"GPSDOP"],[12,"GPSSpeedRef"],[13,"GPSSpeed"],[14,"GPSTrackRef"],[15,"GPSTrack"],[16,"GPSImgDirectionRef"],[17,"GPSImgDirection"],[18,"GPSMapDatum"],[19,"GPSDestLatitudeRef"],[20,"GPSDestLatitude"],[21,"GPSDestLongitudeRef"],[22,"GPSDestLongitude"],[23,"GPSDestBearingRef"],[24,"GPSDestBearing"],[25,"GPSDestDistanceRef"],[26,"GPSDestDistance"],[27,"GPSProcessingMethod"],[28,"GPSAreaInformation"],[29,"GPSDateStamp"],[30,"GPSDifferential"],[31,"GPSHPositioningError"]]),Oe(Gs,["ifd0","ifd1"],[[274,{1:"Horizontal (normal)",2:"Mirror horizontal",3:"Rotate 180",4:"Mirror vertical",5:"Mirror horizontal and rotate 270 CW",6:"Rotate 90 CW",7:"Mirror horizontal and rotate 90 CW",8:"Rotate 270 CW"}],[296,{1:"None",2:"inches",3:"cm"}]]);var Cn=Oe(Gs,"exif",[[34850,{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"}],[37121,{0:"-",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}],[37383,{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"}],[37384,{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"}],[37385,{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"}],[41495,{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"}],[41728,{1:"Film Scanner",2:"Reflection Print Scanner",3:"Digital Camera"}],[41729,{1:"Directly photographed"}],[41985,{0:"Normal",1:"Custom",2:"HDR (no original saved)",3:"HDR (original saved)",4:"Original (for HDR)",6:"Panorama",7:"Portrait HDR",8:"Portrait"}],[41986,{0:"Auto",1:"Manual",2:"Auto bracket"}],[41987,{0:"Auto",1:"Manual"}],[41990,{0:"Standard",1:"Landscape",2:"Portrait",3:"Night",4:"Other"}],[41991,{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"}],[41996,{0:"Unknown",1:"Macro",2:"Close",3:"Distant"}],[42080,{0:"Unknown",1:"Not a Composite Image",2:"General Composite Image",3:"Composite Image Captured While Shooting"}]]),Bc={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};Cn.set(37392,Bc),Cn.set(41488,Bc);var wa={0:"Normal",1:"Low",2:"High"};function $c(s){return typeof s=="object"&&s.length!==void 0?s[0]:s}function Uc(s){let t=Array.from(s).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function xa(s){if(typeof s=="string"){var[t,e,i,n,o,c]=s.trim().split(/[-: ]/g).map(Number),l=new Date(t,e-1,i);return Number.isNaN(n)||Number.isNaN(o)||Number.isNaN(c)||(l.setHours(n),l.setMinutes(o),l.setSeconds(c)),Number.isNaN(+l)?s:l}}function Sn(s){if(typeof s=="string")return s;let t=[];if(s[1]===0&&s[s.length-1]===0)for(let e=0;e<s.length;e+=2)t.push(Hc(s[e+1],s[e]));else for(let e=0;e<s.length;e+=2)t.push(Hc(s[e],s[e+1]));return jc(String.fromCodePoint(...t))}function Hc(s,t){return s<<8|t}Cn.set(41992,wa),Cn.set(41993,wa),Cn.set(41994,wa),Oe(cs,["ifd0","ifd1"],[[50827,function(s){return typeof s!="string"?Vc(s):s}],[306,xa],[40091,Sn],[40092,Sn],[40093,Sn],[40094,Sn],[40095,Sn]]),Oe(cs,"exif",[[40960,Uc],[36864,Uc],[36867,xa],[36868,xa],[40962,$c],[40963,$c]]),Oe(cs,"gps",[[0,s=>Array.from(s).join(".")],[7,s=>Array.from(s).join(":")]]);var _n=class extends ni{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1752462448&&t.getString(e+4,20)==="http://ns.adobe.com/"}static headerLength(t,e){return t.getString(e+4,34)==="http://ns.adobe.com/xmp/extension/"?79:33}static findPosition(t,e){let i=super.findPosition(t,e);return i.multiSegment=i.extended=i.headerLength===79,i.multiSegment?(i.chunkCount=t.getUint8(e+72),i.chunkNumber=t.getUint8(e+76),t.getUint8(e+77)!==0&&i.chunkNumber++):(i.chunkCount=1/0,i.chunkNumber=-1),i}static handleMultiSegments(t){return t.map((e=>e.chunk.getString())).join("")}normalizeInput(t){return typeof t=="string"?t:oi.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let c={},l={};for(let h of th)c[h]=[],l[h]=0;return o.replace(fu,((h,m,u)=>{if(m==="<"){let a=++l[u];return c[u].push(a),`${h}#${a}`}return`${h}#${c[u].pop()}`}))})(t);let e=oo.findAll(t,"rdf","Description");e.length===0&&e.push(new oo("rdf","Description",void 0,t));let i,n={};for(let o of e)for(let c of o.properties)i=pu(c.ns,n),Jc(c,i);return(function(o){let c;for(let l in o)c=o[l]=Jr(o[l]),c===void 0&&delete o[l];return Jr(o)})(n)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,n]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",n);break;case"exif":this.assignObjectToOutput(t,"exif",n);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,n)}else t.xmp=e}};Nt(_n,"type","xmp"),Nt(_n,"multiSegment",!0),me.set("xmp",_n);var Ra=class s{static findAll(t){return Qc(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],n=t[3].slice(1,-1);return n=Zc(n),new s(e,i,n)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},oo=class s{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var n=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else n=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return Qc(t,n).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],n=t[4],o=t[8];return new s(e,i,n,o)}constructor(t,e,i,n){this.ns=t,this.name=e,this.attrString=i,this.innerXml=n,this.attrs=Ra.findAll(i),this.children=s.findAll(n),this.value=this.children.length===0?Zc(n):void 0,this.properties=[...this.attrs,...this.children]}get isPrimitive(){return this.value!==void 0&&this.attrs.length===0&&this.children.length===0}get isListContainer(){return this.children.length===1&&this.children[0].isList}get isList(){let{ns:t,name:e}=this;return t==="rdf"&&(e==="Seq"||e==="Bag"||e==="Alt")}get isListItem(){return this.ns==="rdf"&&this.name==="li"}serialize(){if(this.properties.length===0&&this.value===void 0)return;if(this.isPrimitive)return this.value;if(this.isListContainer)return this.children[0].serialize();if(this.isList)return uu(this.children.map(du));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)Jc(e,t);return this.value!==void 0&&(t.value=this.value),Jr(t)}};function Jc(s,t){let e=s.serialize();e!==void 0&&(t[s.name]=e)}var du=s=>s.serialize(),uu=s=>s.length===1?s[0]:s,pu=(s,t)=>t[s]?t[s]:t[s]={};function Qc(s,t){let e,i=[];if(!s)return i;for(;(e=t.exec(s))!==null;)i.push(e);return i}function Zc(s){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(s))return;let t=Number(s);if(!Number.isNaN(t))return t;let e=s.toLowerCase();return e==="true"||e!=="false"&&s.trim()}var th=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],fu=new RegExp(`(<|\\/)(${th.join("|")})`,"g"),eh=hu;async function qs(s){try{return await eh.parse(s)||null}catch{return null}}function De(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),s=>s.toString(16).padStart(2,"0")).join("")}async function Xs(s){if(typeof createImageBitmap>"u"||typeof document>"u"){if(s&&typeof s.arrayBuffer=="function"){let l=await s.arrayBuffer(),h=globalThis.Buffer,m=typeof h<"u"?h.from(l).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(l)));return`data:${s.type||"image/png"};base64,${m}`}if(typeof s=="string")return s}let t=await createImageBitmap(s),n=Math.min(1,1654/t.width,2339/t.height);if(n===1&&(s.type==="image/jpeg"||s.type==="image/jpg"||s.type==="image/png"||s.type==="image/webp"))return t.close(),new Promise((l,h)=>{let m=new FileReader;m.onload=()=>l(m.result),m.onerror=h,m.readAsDataURL(s)});let o=document.createElement("canvas");o.width=Math.round(t.width*n),o.height=Math.round(t.height*n),o.getContext("2d").drawImage(t,0,0,o.width,o.height),t.close();let c=s.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(c,c==="image/png"?void 0:.82)}function Ba(s,t=21,e=.2,i=128){let{data:n,width:o,height:c}=s,l=o+1,h=new Float64Array((o+1)*(c+1)),m=new Float64Array((o+1)*(c+1)),u=new Uint8Array(o*c);for(let f=0;f<c;f++){let w=0,E=0,p=f*o,y=(f+1)*l,r=f*l;for(let d=0;d<o;d++){let b=(p+d)*4,x=n[b]*77+n[b+1]*150+n[b+2]*29>>8;u[p+d]=x,w+=x,E+=x*x,h[y+d+1]=h[r+d+1]+w,m[y+d+1]=m[r+d+1]+E}}let a=Math.floor(t/2);for(let f=0;f<c;f++){let w=Math.max(0,f-a),E=Math.min(c-1,f+a),p=w*l,y=(E+1)*l;for(let r=0;r<o;r++){let d=Math.max(0,r-a),b=Math.min(o-1,r+a),x=(b-d+1)*(E-w+1),_=h[y+b+1]-h[p+b+1]-h[y+d]+h[p+d],S=m[y+b+1]-m[p+b+1]-m[y+d]+m[p+d],R=_/x,N=Math.max(0,S/x-R*R),H=Math.sqrt(N),z=R*(1+e*(H/i-1)),K=f*o+r,it=u[K]<z?0:255,at=K*4;n[at]=it,n[at+1]=it,n[at+2]=it}}return s}function $a(s,t=21,e=.2,i=128){return new Promise(n=>{let o=new Image;o.onload=()=>{let c=document.createElement("canvas");c.width=o.width,c.height=o.height;let l=c.getContext("2d");l.drawImage(o,0,0);let h=l.getImageData(0,0,c.width,c.height);Ba(h,t,e,i),l.putImageData(h,0,0);let m=s.startsWith("data:image/png"),u=m?"image/png":"image/jpeg";n(c.toDataURL(u,m?void 0:.82))},o.src=s})}function Ua(s){return new Promise(t=>{let e=new Image;e.onload=()=>{let i=document.createElement("canvas");i.width=e.height,i.height=e.width;let n=i.getContext("2d");n.translate(i.width/2,i.height/2),n.rotate(Math.PI/2),n.drawImage(e,-e.width/2,-e.height/2);let o=s.startsWith("data:image/png"),c=o?"image/png":"image/jpeg";t(i.toDataURL(c,o?void 0:.82))},e.src=s})}function Ha(s,t=""){if(!s)return"";let e=s.getCroppedCanvas(),i=t.startsWith("data:image/png"),n=i?"image/png":"image/jpeg";return e.toDataURL(n,i?void 0:.82)}function qe(s){if(!s||typeof s!="object")return{crop:null,rotation:0,filter:"none"};let t=null;s.crop&&typeof s.crop=="object"&&(s.crop.width>0&&s.crop.height>0?t={x:Math.round(s.crop.x||0),y:Math.round(s.crop.y||0),width:Math.round(s.crop.width),height:Math.round(s.crop.height)}:s.crop.w>0&&s.crop.h>0&&(t={x:Number(s.crop.x)||0,y:Number(s.crop.y)||0,w:Number(s.crop.w)||1,h:Number(s.crop.h)||1}));let e=s.rotation!==void 0?s.rotation:s.rotate,i=(Math.round(Number(e)||0)%360+360)%360,n=s.filter==="bw"?"bw":"none";return{crop:t,rotation:i,filter:n}}function za(s){if(!s)return!1;let t=qe(s);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function Ks(s,t){let e=qe(t),i=s.naturalWidth||s.width||0,n=s.naturalHeight||s.height||0,o=document.createElement("canvas"),c=i,l=n,h=0,m=0;if(e.crop){let f=e.crop;"w"in f&&!("width"in f)?(h=Math.max(0,Math.min(Math.round(f.x*i),i)),m=Math.max(0,Math.min(Math.round(f.y*n),n)),c=Math.max(1,Math.min(Math.round(f.w*i),i-h)),l=Math.max(1,Math.min(Math.round(f.h*n),n-m))):(h=Math.max(0,Math.min(f.x,i)),m=Math.max(0,Math.min(f.y,n)),c=Math.max(1,Math.min(f.width,i-h)),l=Math.max(1,Math.min(f.height,n-m)))}o.width=c,o.height=l,o.getContext("2d").drawImage(s,h,m,c,l,0,0,c,l);let a=o;if(e.rotation!==0){let f=e.rotation,w=document.createElement("canvas");f===90||f===270?(w.width=a.height,w.height=a.width):(w.width=a.width,w.height=a.height);let E=w.getContext("2d");E.translate(w.width/2,w.height/2),E.rotate(f*Math.PI/180),E.drawImage(a,-a.width/2,-a.height/2),a=w}if(e.filter==="bw"){let f=a.getContext("2d"),w=f.getImageData(0,0,a.width,a.height);Ba(w),f.putImageData(w,0,0)}return a}function Rn(s,t){if(!s)return Promise.resolve("");let e=qe(t);return za(e)?new Promise((i,n)=>{let o=new Image;o.onload=()=>{try{let c=s.startsWith("data:image/png"),l=c?"image/png":"image/jpeg",h=Ks(o,e);i(h.toDataURL(l,c?void 0:.82))}catch(c){n(c)}},o.onerror=n,o.src=s}):Promise.resolve(s)}var ki=class{#t=null;#e=new Map;#i=new Map;constructor(t=Us()){this.#t=t}get adapter(){return this.#t}get store(){return this.#t?.store??null}async init(){return this.#t.init()}listDocsSync(){return typeof this.#t.listDocsSync=="function"?this.#t.listDocsSync().map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}}):[]}async listDocs(){return(await this.#t.listDocs()).map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}})}getDocSync(t){if(!t)return null;if(typeof this.#t.getDocSync=="function"){let n=this.#t.getDocSync(t);return n?{id:n.id,name:n.name||"",pages:this.#s(n.pages)}:null}let i=this.listDocsSync().find(n=>n.id===t);return i?{id:i.id,name:i.name,pages:i.pages||[]}:null}async getDoc(t){if(!t)return null;if(typeof this.#t.getDoc=="function"){let e=await this.#t.getDoc(t);return e?{id:e.id,name:e.name||"",pages:this.#s(e.pages)}:null}return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=De(),n=this.#s(e),o={id:i,name:t||"Untitled Document",pages:n};return await this.#t.saveDoc(i,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=this.#s(e.pages);await this.#t.saveDoc(t,{id:t,name:e.name||"",pages:i})}async renameDoc(t,e){if(typeof this.#t.renameDoc=="function")return this.#t.renameDoc(t,e);let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t,{soft:e=!0,timeoutMs:i=5e3}={}){if(!t)return;let n=this.getDocSync(t);if(n){if(this.#n(t),await this.#t.deleteDoc(t),e&&i>0){let o=setTimeout(async()=>{this.#e.delete(t)},i);this.#e.set(t,{doc:n,timerId:o})}return{id:t,name:n.name,undo:()=>this.undoDeleteDoc(t)}}}#n(t){if(this.#e.has(t)){let e=this.#e.get(t);clearTimeout(e.timerId),this.#e.delete(t)}}async undoDeleteDoc(t){let e=this.#e.get(t);return e?(clearTimeout(e.timerId),this.#e.delete(t),await this.#t.saveDoc(t,e.doc),e.doc):null}isSoftDeletedDoc(t){return this.#e.has(t)}async addPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let n=Array.isArray(e)?e:[e];i.pages.push(...n),await this.saveDoc(t,i)}async updatePage(t,e,i){let n=await this.getDoc(t);if(!n)throw new Error(`Document "${t}" not found`);let o=n.pages.findIndex(c=>c.id===e);if(o===-1)throw new Error(`Page "${e}" not found in document "${t}"`);n.pages[o]={...n.pages[o],...i},await this.saveDoc(t,n)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let n=new Map(i.pages.map(c=>[c.id,c])),o=[];for(let c of e)n.has(c)&&(o.push(n.get(c)),n.delete(c));for(let c of n.values())o.push(c);i.pages=o,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:n=5e3}={}){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let c=o.pages.findIndex(u=>u.id===e);if(c===-1)return;let[l]=o.pages.splice(c,1);await this.saveDoc(t,o);let h=`${t}:${e}`;if(this.#r(h),!i||n<=0){if(typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}return}let m=setTimeout(async()=>{if(this.#i.delete(h),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}},n);return this.#i.set(h,{docId:t,pageId:e,page:l,index:c,timerId:m}),{docId:t,pageId:e,undo:()=>this.undoDeletePage(t,e)}}#r(t){if(this.#i.has(t)){let e=this.#i.get(t);clearTimeout(e.timerId),this.#i.delete(t)}}async undoDeletePage(t,e){let i=`${t}:${e}`,n=this.#i.get(i);if(!n)return null;clearTimeout(n.timerId),this.#i.delete(i);let o=await this.getDoc(t);if(!o)return null;let c=Math.min(n.index,o.pages.length);return o.pages.splice(c,0,n.page),await this.saveDoc(t,o),n.page}isSoftDeletedPage(t,e){return this.#i.has(`${t}:${e}`)}subscribe(t){return this.#t.subscribe(t)}async getAllDocs(){let t=await this.listDocs(),e={};for(let i of t)e[i.id]=i;return e}async exportAll(){let t=await this.listDocs(),e={};for(let i of t){let n=await this.getDoc(i.id),o=[];for(let c of n?.pages||[]){if(!c){o.push(c);continue}let l={...c},h=l.blob instanceof Blob?l.blob:null;if(!h&&typeof l.src=="string"&&l.src.startsWith("blob:"))try{h=await(await fetch(l.src)).blob()}catch{}h&&(l.src=await ya(h));let m=l.originalBlob instanceof Blob?l.originalBlob:null;if(!m&&typeof l.originalSrc=="string"&&l.originalSrc.startsWith("blob:"))try{m=await(await fetch(l.originalSrc)).blob()}catch{}m&&(l.originalSrc=await ya(m)),delete l.blob,delete l.originalBlob,o.push(l)}e[i.id]={name:i.name,pages:JSON.stringify(o)}}return e}async importDocs(t){let e=0;for(let[i,n]of Object.entries(t||{})){await this.getDoc(i)||e++;let c=this.#s(n.pages);await this.saveDoc(i,{name:n.name||"",pages:c})}return e}#s(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},Ys=new ki;ci();var ih="2026-11-06T11:31:52.811Z",sh="0.1.3";var hi=class{async recognizeImageText(t,e={}){throw new Error("OcrPort.recognizeImageText() must be implemented by adapter")}async recognizeDocumentPages(t,e={}){throw new Error("OcrPort.recognizeDocumentPages() must be implemented by adapter")}async getOcrWorker(t="eng",e=null){throw new Error("OcrPort.getOcrWorker() must be implemented by adapter")}async terminateOcrWorker(){throw new Error("OcrPort.terminateOcrWorker() must be implemented by adapter")}};var Re=class extends hi{async recognizeImageText(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async recognizeDocumentPages(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async getOcrWorker(){return null}async terminateOcrWorker(){}};var di=class{async exportDocumentAsPdf(t,e,i={}){throw new Error("PdfPort.exportDocumentAsPdf() must be implemented by adapter")}async renderPdfPagesToDataUrls(t){throw new Error("PdfPort.renderPdfPagesToDataUrls() must be implemented by adapter")}};var Xe=class extends di{async exportDocumentAsPdf(t,e,i={}){let n=new Error('Feature "pdf" is disabled or PDF module not opted in');throw n.code="FEATURE_DISABLED",n}async renderPdfPagesToDataUrls(t){return[]}};var Ke=class{async renderEdits(t,e){throw new Error("ImageProcessorPort.renderEdits() must be implemented by adapter")}async crop(t,e){throw new Error("ImageProcessorPort.crop() must be implemented by adapter")}async rotate(t,e){throw new Error("ImageProcessorPort.rotate() must be implemented by adapter")}async applyFilter(t,e){throw new Error("ImageProcessorPort.applyFilter() must be implemented by adapter")}};function gu(s){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=s})}var ui=class extends Ke{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await gu(t),n={...e};return e?.crop&&"w"in e.crop&&(n.crop={x:Math.round((e.crop.x||0)*i.naturalWidth),y:Math.round((e.crop.y||0)*i.naturalHeight),width:Math.round((e.crop.w||1)*i.naturalWidth),height:Math.round((e.crop.h||1)*i.naturalHeight)}),e?.rotate!==void 0&&(n.rotation=e.rotate),Ks(i,n).toDataURL("image/jpeg",.92)}catch{return t}}async crop(t,e){return this.renderEdits(t,{crop:e})}async rotate(t,e){return this.renderEdits(t,{rotate:e})}async applyFilter(t,e){return this.renderEdits(t,{filter:e})}};var ps=class extends Ke{async renderEdits(t,e){return t}async crop(t,e){return t}async rotate(t,e){return t}async applyFilter(t,e){return t}};function Js(s={}){let t=s&&s.crop&&typeof s.crop=="object"?{x:Math.max(0,Math.min(1,Number(s.crop.x)||0)),y:Math.max(0,Math.min(1,Number(s.crop.y)||0)),w:Math.max(0,Math.min(1,Number(s.crop.w)||1)),h:Math.max(0,Math.min(1,Number(s.crop.h)||1))}:null,e=0,i=s?.rotate!==void 0?s.rotate:s?.rotation;if(i!==void 0){let o=(Math.round(Number(i)/90)*90%360+360)%360;(o===90||o===180||o===270)&&(e=o)}let n=s&&s.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:n}}function mo(s){if(!s)return!1;let t=s.rotate!==void 0?s.rotate:s.rotation;return!!(s.crop||t&&t!==0||s.filter&&s.filter!=="none")}var ue=s=>Math.round(s*1e6)/1e6;function Va(s,t=0){if(!s)return null;let e=(Math.round(Number(t)/90)*90%360+360)%360,{x:i,y:n,w:o,h:c}=s;return e===90?{x:ue(Math.max(0,Math.min(1,1-n-c))),y:ue(Math.max(0,Math.min(1,i))),w:ue(Math.max(.01,Math.min(1,c))),h:ue(Math.max(.01,Math.min(1,o)))}:e===180?{x:ue(Math.max(0,Math.min(1,1-i-o))),y:ue(Math.max(0,Math.min(1,1-n-c))),w:ue(Math.max(.01,Math.min(1,o))),h:ue(Math.max(.01,Math.min(1,c)))}:e===270?{x:ue(Math.max(0,Math.min(1,n))),y:ue(Math.max(0,Math.min(1,1-i-o))),w:ue(Math.max(.01,Math.min(1,c))),h:ue(Math.max(.01,Math.min(1,o)))}:{x:ue(Math.max(0,Math.min(1,i))),y:ue(Math.max(0,Math.min(1,n))),w:ue(Math.max(.01,Math.min(1,o))),h:ue(Math.max(.01,Math.min(1,c)))}}function Wa(s,t=0){return Va(s,t)}function Ga(s,t=0){return Va(s,-t)}var fs=class{constructor(t){this.id=t.id,this.src=t.src,this.originalSrc=t.originalSrc||t.src,this.edits=Js(t.edits),this.name=t.name||"Page",this.type=t.type||"image",this.orientation=t.orientation||1,this.ocrText=t.ocrText||null,this.ocrConfidence=t.ocrConfidence??null,this.ocrWords=Array.isArray(t.ocrWords)?t.ocrWords:null,this.ocrWidth=typeof t.ocrWidth=="number"?t.ocrWidth:null,this.ocrHeight=typeof t.ocrHeight=="number"?t.ocrHeight:null}get isModified(){return mo(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},Mn=class{constructor(t){this.id=t.id,this.name=t.name||"Untitled Document",this.pages=Array.isArray(t.pages)?t.pages.map(e=>e instanceof fs?e:new fs(e)):[],this.createdAt=t.createdAt||Date.now(),this.updatedAt=t.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(t=>t.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},In=class{constructor(t={}){this.mode=t.mode==="single"?"single":"batch",this.aspect=t.aspect||"auto",this.docId=t.docId||null,this.maxPages=Math.max(0,Number(t.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(t){this.history.push(t),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let t=this.history.pop();return this.future.push(t),t}redo(){if(this.future.length===0)return null;let t=this.future.pop();return this.history.push(t),t}};var te={PAGE_ADDED:"copio:page-added",PAGE_REMOVED:"copio:page-removed",PAGES_CHANGED:"copio:pages-changed",SCAN_COMPLETE:"copio:scan-complete",EXPORT_PROGRESS:"copio:export-progress",EXPORT_COMPLETE:"copio:export-complete",OCR_COMPLETE:"copio:ocr-complete",SYNC_CONNECTED:"copio:sync-connected",ERROR:"copio:error"};function bo(s,t,e={}){let i=new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:!0,detail:e});return s&&typeof s.dispatchEvent=="function"&&s.dispatchEvent(i),i}var Ka=["crop","rotate","filter","ocr","export","sync"],qa=["pdf","zip","png","jpg"],Xa=["eng"],Ya={};function Mi(s,t){!s||!t||(Ya[s]=t,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[s]=t))}function Ri(s){return Ya[s]?Ya[s]:typeof globalThis<"u"&&globalThis.__copio_services__?.[s]?globalThis.__copio_services__[s]:null}function mu(s){return s?s instanceof Set?new Set(s):Array.isArray(s)?new Set(s.map(t=>String(t).trim().toLowerCase()).filter(Boolean)):typeof s=="string"?new Set(s.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set(Ka):new Set(Ka)}function yo(s,t){return s?Array.isArray(s)?s.map(e=>String(e).trim().toLowerCase()).filter(Boolean):typeof s=="string"?s.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean):[...t]:[...t]}var gs=class{#t=new Set(Ka);#e=[...qa];#i=[...Xa];#n=0;#r="";#s=null;#a=null;#l={};#o=!0;#h=!0;#u=null;#d=new Map;#c=new Map;constructor(t={}){this.#s=t.storage||Us(t),this.#a=t.repository||new ki(this.#s),t.services&&(this.#l={...t.services}),t.imageProcessor?(this.#u=t.imageProcessor,this.#l.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#u=this.getService("imageProcessor"):typeof document<"u"?this.#u=new ui:this.#u=new ps,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#e=yo(t.exportFormats,qa)),t.ocrLanguages!==void 0&&(this.#i=yo(t.ocrLanguages,Xa)),t.maxPages!==void 0&&(this.#n=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&us(t.assetBase),t.licenseKey!==void 0&&(this.#r=String(t.licenseKey||"")),t.ocr!==void 0?this.ocr=!!t.ocr:t.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),t.pdf!==void 0?this.pdf=!!t.pdf:t.exportFormats!==void 0&&!this.#e.includes("pdf")&&(this.pdf=!1)}async init(){return this.#s.init()}setService(t,e){this.#l[t]=e}getService(t){return this.#l[t]||Ri(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=mu(t),this.hasFeature("ocr")?(this.#o=!0,this.getService("ocr")instanceof Re&&this.setService("ocr",Ri("ocr"))):(this.#o=!1,this.setService("ocr",new Re))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#o=!0,this.getService("ocr")instanceof Re&&this.setService("ocr",Ri("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#o=!1,this.setService("ocr",new Re))}}get ocr(){return this.#o&&this.hasFeature("ocr")}set ocr(t){this.#o=!!t,this.#o?(this.enableFeature("ocr"),this.getService("ocr")instanceof Re&&this.setService("ocr",Ri("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new Re))}get pdf(){return this.#h&&this.#e.includes("pdf")}set pdf(t){this.#h=!!t,this.#h?(this.#e.includes("pdf")||this.#e.push("pdf"),this.getService("pdf")instanceof Xe&&this.setService("pdf",Ri("pdf"))):(this.#e=this.#e.filter(e=>e!=="pdf"),this.setService("pdf",new Xe))}get exportFormats(){return[...this.#e]}set exportFormats(t){this.#e=yo(t,qa),this.#e.includes("pdf")?(this.#h=!0,this.getService("pdf")instanceof Xe&&this.setService("pdf",Ri("pdf"))):(this.#h=!1,this.setService("pdf",new Xe))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(t){this.#i=yo(t,Xa)}get maxPages(){return this.#n}set maxPages(t){this.#n=Math.max(0,Number(t)||0)}get assetBase(){return lo()}set assetBase(t){us(t)}get licenseKey(){return this.#r}set licenseKey(t){this.#r=String(t||"")}get storage(){return this.#s}setStorage(t){t&&(this.#s=t,this.#a=new ki(this.#s))}#f(t,e){this.#d.has(t)||this.#d.set(t,[]);let i=this.#d.get(t);i.push(e),i.length>50&&i.shift(),this.#c.has(t)&&(this.#c.get(t).length=0)}get imageProcessor(){return this.#u}setImageProcessor(t){t&&(this.#u=t,this.setService("imageProcessor",t))}async renderEdits(t,e){if(!t)return"";let i=Js(e);return this.#u?this.#u.renderEdits(t,i):Rn(t,i)}get docs(){return this.#a}async listDocuments(){return this.#a.listDocs()}async getDocument(t){return this.#a.getDoc(t)}async createDocument(t,e){return this.#a.createDoc(t,e)}async deleteDocument(t,e={}){return this.#a.deleteDoc(t,e)}async undoDeleteDocument(t){return this.#a.undoDeleteDoc(t)}async renameDocument(t,e){return this.#a.renameDoc(t,e)}async addPages(t,e){return this.#a.addPages(t,e)}async deletePage(t,e,i={}){return this.#f(t,{type:"delete",pageId:e}),this.#a.deletePage(t,e,i)}async undoDeletePage(t,e){return this.#a.undoDeletePage(t,e)}async updatePage(t,e,i){return this.#a.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),n=i?.pages?i.pages.map(o=>o.id):[];return this.#f(t,{type:"reorder",priorOrder:n,newOrder:[...e]}),this.#a.reorderPages(t,e)}async#g(t){if(t)return t;let e=await this.listDocuments();return e.length>0?e[0].id:null}async applyEdit(t,e,i){let n=await this.#g(t),o=n?await this.getDocument(n):null;if(!o||!o.pages)throw new Error(`Document with ID "${n||t}" not found`);let c=o.pages.find(f=>f.id===e);if(!c)throw new Error(`Page with ID "${e}" not found in document "${n}"`);let l={...c.edits||{crop:null,rotate:0,filter:"none"}},h=c.src,m=Js({...l,...i}),u=c.originalSrc||c.src,a=u;return this.#u&&(a=await this.#u.renderEdits(u,m)),await this.updatePage(n,e,{originalSrc:u,src:a,edits:m}),this.#f(n,{type:"edit",pageId:e,priorEdits:l,priorSrc:h,newEdits:m,newSrc:a}),{...c,originalSrc:u,src:a,edits:m}}async undo(t){let e=await this.#g(t),i=e?this.#d.get(e):null;if(!i||i.length===0)return null;let n=i.pop();return this.#c.has(e)||this.#c.set(e,[]),this.#c.get(e).push(n),n.type==="edit"?(await this.updatePage(e,n.pageId,{edits:n.priorEdits,src:n.priorSrc}),{type:"edit",pageId:n.pageId,restoredEdits:n.priorEdits}):n.type==="delete"?(await this.undoDeletePage(e,n.pageId),{type:"delete",pageId:n.pageId}):n.type==="reorder"?(await this.#a.reorderPages(e,n.priorOrder),{type:"reorder",priorOrder:n.priorOrder}):n}async redo(t){let e=await this.#g(t),i=e?this.#c.get(e):null;if(!i||i.length===0)return null;let n=i.pop();return this.#d.has(e)||this.#d.set(e,[]),this.#d.get(e).push(n),n.type==="edit"?(await this.updatePage(e,n.pageId,{edits:n.newEdits,src:n.newSrc}),{type:"edit",pageId:n.pageId,appliedEdits:n.newEdits}):n.type==="delete"?(await this.deletePage(e,n.pageId),{type:"delete",pageId:n.pageId}):n.type==="reorder"?(await this.reorderPages(e,n.newOrder),{type:"reorder",newOrder:n.newOrder}):n}subscribe(t){return this.#a.subscribe(t)}async addFiles(t,e=null){if(!t||t.length===0)return[];let i=Array.from(t),n=[];for(let c of i)if(c.type==="application/pdf"){let l=this.getService("pdf");if(l&&typeof l.renderPdfPagesToDataUrls=="function"){let h=await l.renderPdfPagesToDataUrls(c);for(let m of h)n.push({id:De(),src:m,originalSrc:m,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:c.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(c.type&&c.type.startsWith("image/")){let l=await Xs(c),h=null;try{h=await qs(c)}catch{}n.push({id:De(),src:l,originalSrc:l,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:c.name||"Captured Image",orientation:h})}if(n.length===0)return[];await this.init();let o=e;if(o)await this.getDocument(o)||await this.#a.saveDoc(o,{name:"Scanned Document",pages:[]});else{let c=await this.listDocuments();c.length>0?o=c[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let c=(await this.getDocument(o))?.pages||[],l=Math.max(0,this.#n-c.length);if(l<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);n.splice(l)}return await this.addPages(o,n),n}async getPages(t=null){let e=t;if(!e){let n=await this.listDocuments();if(n.length===0)return[];e=n[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let n=await this.listDocuments();if(n.length===0)return;e=n[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let n of i.pages)await this.deletePage(e,n.id)}async#p(t){if(Array.isArray(t))return{docName:"document",pages:t,docId:null};if(typeof t=="string"){let i=await this.getDocument(t);return{docName:i?.name||"document",pages:i?.pages||[],docId:t}}let e=await this.listDocuments();if(e.length>0){let i=await this.getDocument(e[0].id);return{docName:i?.name||"document",pages:i?.pages||[],docId:e[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(t,e={}){if(!this.hasFeature("export")){let c=new Error('Feature "export" is disabled');throw Object.assign(c,{code:"FEATURE_DISABLED"}),c}if(!this.#h||!this.#e.includes("pdf")){let c=new Error('Feature "pdf" is disabled');throw Object.assign(c,{code:"FEATURE_DISABLED"}),c}let{docName:i,pages:n}=await this.#p(t),o=this.getService("pdf")||this.getService("export");if(!o||typeof o.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsPdf(i,n,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof t=="string"){let c=await this.#s.getDoc(t);c&&(c.pages=n,await this.#s.saveDoc(t,c))}},...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let c=new Error('Feature "export" is disabled');throw Object.assign(c,{code:"FEATURE_DISABLED"}),c}let{docName:i,pages:n}=await this.#p(t),o=this.getService("export");if(!o||typeof o.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsImages(i,n,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#o||!this.hasFeature("ocr")){let m=new Error('Feature "ocr" is disabled');throw Object.assign(m,{code:"FEATURE_DISABLED"}),m}let{pages:n}=await this.#p(t),o=n;e&&(o=n.filter(m=>m.id===e));let c=this.getService("ocr");if(!c||typeof c.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let l=i.lang||this.#i[0]||"eng",h=await c.recognizeDocumentPages(o,{lang:l,...i});if(Array.isArray(h.pagesResults)){for(let m of h.pagesResults){let u=o.find(a=>a.id===m.pageId)||o[m.pageIndex];u&&(u.ocrText=m.text,u.ocrConfidence=m.confidence,u.ocrWords=m.words)}if(typeof t=="string"){let m=await this.#s.getDoc(t);if(m&&Array.isArray(m.pages)){for(let u of h.pagesResults){let a=m.pages.find(f=>f.id===u.pageId)||m.pages[u.pageIndex];a&&(a.ocrText=u.text,a.ocrConfidence=u.confidence,a.ocrWords=u.words)}await this.#s.saveDoc(t,m)}}}return{text:h.combinedText,...h}}async sync(t={}){if(!this.hasFeature("sync")){let i=new Error('Feature "sync" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let e=this.getService("sync");if(!e)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new e(this.#a,t.onStateChange)}};function nh(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);t&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),e.push.apply(e,i)}return e}function Je(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?nh(Object(e),!0).forEach(function(i){bu(s,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):nh(Object(e)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(e,i))})}return s}function So(s){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?So=function(t){return typeof t}:So=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},So(s)}function bu(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function fi(){return fi=Object.assign||function(s){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=e[i])}return s},fi.apply(this,arguments)}function yu(s,t){if(s==null)return{};var e={},i=Object.keys(s),n,o;for(o=0;o<i.length;o++)n=i[o],!(t.indexOf(n)>=0)&&(e[n]=s[n]);return e}function vu(s,t){if(s==null)return{};var e=yu(s,t),i,n;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(s);for(n=0;n<o.length;n++)i=o[n],!(t.indexOf(i)>=0)&&Object.prototype.propertyIsEnumerable.call(s,i)&&(e[i]=s[i])}return e}var wu="1.15.6";function pi(s){if(typeof window<"u"&&window.navigator)return!!navigator.userAgent.match(s)}var gi=pi(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),zn=pi(/Edge/i),rh=pi(/firefox/i),Nn=pi(/safari/i)&&!pi(/chrome/i)&&!pi(/android/i),hl=pi(/iP(ad|od|hone)/i),ph=pi(/chrome/i)&&pi(/android/i),fh={capture:!1,passive:!1};function Ot(s,t,e){s.addEventListener(t,e,!gi&&fh)}function Ft(s,t,e){s.removeEventListener(t,e,!gi&&fh)}function Po(s,t){if(t){if(t[0]===">"&&(t=t.substring(1)),s)try{if(s.matches)return s.matches(t);if(s.msMatchesSelector)return s.msMatchesSelector(t);if(s.webkitMatchesSelector)return s.webkitMatchesSelector(t)}catch{return!1}return!1}}function gh(s){return s.host&&s!==document&&s.host.nodeType?s.host:s.parentNode}function Be(s,t,e,i){if(s){e=e||document;do{if(t!=null&&(t[0]===">"?s.parentNode===e&&Po(s,t):Po(s,t))||i&&s===e)return s;if(s===e)break}while(s=gh(s))}return null}var oh=/\s+/g;function _e(s,t,e){if(s&&t)if(s.classList)s.classList[e?"add":"remove"](t);else{var i=(" "+s.className+" ").replace(oh," ").replace(" "+t+" "," ");s.className=(i+(e?" "+t:"")).replace(oh," ")}}function Et(s,t,e){var i=s&&s.style;if(i){if(e===void 0)return document.defaultView&&document.defaultView.getComputedStyle?e=document.defaultView.getComputedStyle(s,""):s.currentStyle&&(e=s.currentStyle),t===void 0?e:e[t];!(t in i)&&t.indexOf("webkit")===-1&&(t="-webkit-"+t),i[t]=e+(typeof e=="string"?"":"px")}}function sn(s,t){var e="";if(typeof s=="string")e=s;else do{var i=Et(s,"transform");i&&i!=="none"&&(e=i+" "+e)}while(!t&&(s=s.parentNode));var n=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return n&&new n(e)}function mh(s,t,e){if(s){var i=s.getElementsByTagName(t),n=0,o=i.length;if(e)for(;n<o;n++)e(i[n],n);return i}return[]}function Ye(){var s=document.scrollingElement;return s||document.documentElement}function ie(s,t,e,i,n){if(!(!s.getBoundingClientRect&&s!==window)){var o,c,l,h,m,u,a;if(s!==window&&s.parentNode&&s!==Ye()?(o=s.getBoundingClientRect(),c=o.top,l=o.left,h=o.bottom,m=o.right,u=o.height,a=o.width):(c=0,l=0,h=window.innerHeight,m=window.innerWidth,u=window.innerHeight,a=window.innerWidth),(t||e)&&s!==window&&(n=n||s.parentNode,!gi))do if(n&&n.getBoundingClientRect&&(Et(n,"transform")!=="none"||e&&Et(n,"position")!=="static")){var f=n.getBoundingClientRect();c-=f.top+parseInt(Et(n,"border-top-width")),l-=f.left+parseInt(Et(n,"border-left-width")),h=c+o.height,m=l+o.width;break}while(n=n.parentNode);if(i&&s!==window){var w=sn(n||s),E=w&&w.a,p=w&&w.d;w&&(c/=p,l/=E,a/=E,u/=p,h=c+u,m=l+a)}return{top:c,left:l,bottom:h,right:m,width:a,height:u}}}function ah(s,t,e){for(var i=Fi(s,!0),n=ie(s)[t];i;){var o=ie(i)[e],c=void 0;if(e==="top"||e==="left"?c=n>=o:c=n<=o,!c)return i;if(i===Ye())break;i=Fi(i,!1)}return!1}function nn(s,t,e,i){for(var n=0,o=0,c=s.children;o<c.length;){if(c[o].style.display!=="none"&&c[o]!==Ct.ghost&&(i||c[o]!==Ct.dragged)&&Be(c[o],e.draggable,s,!1)){if(n===t)return c[o];n++}o++}return null}function dl(s,t){for(var e=s.lastElementChild;e&&(e===Ct.ghost||Et(e,"display")==="none"||t&&!Po(e,t));)e=e.previousElementSibling;return e||null}function Me(s,t){var e=0;if(!s||!s.parentNode)return-1;for(;s=s.previousElementSibling;)s.nodeName.toUpperCase()!=="TEMPLATE"&&s!==Ct.clone&&(!t||Po(s,t))&&e++;return e}function lh(s){var t=0,e=0,i=Ye();if(s)do{var n=sn(s),o=n.a,c=n.d;t+=s.scrollLeft*o,e+=s.scrollTop*c}while(s!==i&&(s=s.parentNode));return[t,e]}function xu(s,t){for(var e in s)if(s.hasOwnProperty(e)){for(var i in t)if(t.hasOwnProperty(i)&&t[i]===s[e][i])return Number(e)}return-1}function Fi(s,t){if(!s||!s.getBoundingClientRect)return Ye();var e=s,i=!1;do if(e.clientWidth<e.scrollWidth||e.clientHeight<e.scrollHeight){var n=Et(e);if(e.clientWidth<e.scrollWidth&&(n.overflowX=="auto"||n.overflowX=="scroll")||e.clientHeight<e.scrollHeight&&(n.overflowY=="auto"||n.overflowY=="scroll")){if(!e.getBoundingClientRect||e===document.body)return Ye();if(i||t)return e;i=!0}}while(e=e.parentNode);return Ye()}function Au(s,t){if(s&&t)for(var e in t)t.hasOwnProperty(e)&&(s[e]=t[e]);return s}function Ja(s,t){return Math.round(s.top)===Math.round(t.top)&&Math.round(s.left)===Math.round(t.left)&&Math.round(s.height)===Math.round(t.height)&&Math.round(s.width)===Math.round(t.width)}var Bn;function bh(s,t){return function(){if(!Bn){var e=arguments,i=this;e.length===1?s.call(i,e[0]):s.apply(i,e),Bn=setTimeout(function(){Bn=void 0},t)}}}function Su(){clearTimeout(Bn),Bn=void 0}function yh(s,t,e){s.scrollLeft+=t,s.scrollTop+=e}function vh(s){var t=window.Polymer,e=window.jQuery||window.Zepto;return t&&t.dom?t.dom(s).cloneNode(!0):e?e(s).clone(!0)[0]:s.cloneNode(!0)}function wh(s,t,e){var i={};return Array.from(s.children).forEach(function(n){var o,c,l,h;if(!(!Be(n,t.draggable,s,!1)||n.animated||n===e)){var m=ie(n);i.left=Math.min((o=i.left)!==null&&o!==void 0?o:1/0,m.left),i.top=Math.min((c=i.top)!==null&&c!==void 0?c:1/0,m.top),i.right=Math.max((l=i.right)!==null&&l!==void 0?l:-1/0,m.right),i.bottom=Math.max((h=i.bottom)!==null&&h!==void 0?h:-1/0,m.bottom)}}),i.width=i.right-i.left,i.height=i.bottom-i.top,i.x=i.left,i.y=i.top,i}var Ae="Sortable"+new Date().getTime();function Eu(){var s=[],t;return{captureAnimationState:function(){if(s=[],!!this.options.animation){var i=[].slice.call(this.el.children);i.forEach(function(n){if(!(Et(n,"display")==="none"||n===Ct.ghost)){s.push({target:n,rect:ie(n)});var o=Je({},s[s.length-1].rect);if(n.thisAnimationDuration){var c=sn(n,!0);c&&(o.top-=c.f,o.left-=c.e)}n.fromRect=o}})}},addAnimationState:function(i){s.push(i)},removeAnimationState:function(i){s.splice(xu(s,{target:i}),1)},animateAll:function(i){var n=this;if(!this.options.animation){clearTimeout(t),typeof i=="function"&&i();return}var o=!1,c=0;s.forEach(function(l){var h=0,m=l.target,u=m.fromRect,a=ie(m),f=m.prevFromRect,w=m.prevToRect,E=l.rect,p=sn(m,!0);p&&(a.top-=p.f,a.left-=p.e),m.toRect=a,m.thisAnimationDuration&&Ja(f,a)&&!Ja(u,a)&&(E.top-a.top)/(E.left-a.left)===(u.top-a.top)/(u.left-a.left)&&(h=_u(E,f,w,n.options)),Ja(a,u)||(m.prevFromRect=u,m.prevToRect=a,h||(h=n.options.animation),n.animate(m,E,a,h)),h&&(o=!0,c=Math.max(c,h),clearTimeout(m.animationResetTimer),m.animationResetTimer=setTimeout(function(){m.animationTime=0,m.prevFromRect=null,m.fromRect=null,m.prevToRect=null,m.thisAnimationDuration=null},h),m.thisAnimationDuration=h)}),clearTimeout(t),o?t=setTimeout(function(){typeof i=="function"&&i()},c):typeof i=="function"&&i(),s=[]},animate:function(i,n,o,c){if(c){Et(i,"transition",""),Et(i,"transform","");var l=sn(this.el),h=l&&l.a,m=l&&l.d,u=(n.left-o.left)/(h||1),a=(n.top-o.top)/(m||1);i.animatingX=!!u,i.animatingY=!!a,Et(i,"transform","translate3d("+u+"px,"+a+"px,0)"),this.forRepaintDummy=Cu(i),Et(i,"transition","transform "+c+"ms"+(this.options.easing?" "+this.options.easing:"")),Et(i,"transform","translate3d(0,0,0)"),typeof i.animated=="number"&&clearTimeout(i.animated),i.animated=setTimeout(function(){Et(i,"transition",""),Et(i,"transform",""),i.animated=!1,i.animatingX=!1,i.animatingY=!1},c)}}}}function Cu(s){return s.offsetWidth}function _u(s,t,e,i){return Math.sqrt(Math.pow(t.top-s.top,2)+Math.pow(t.left-s.left,2))/Math.sqrt(Math.pow(t.top-e.top,2)+Math.pow(t.left-e.left,2))*i.animation}var Qs=[],Qa={initializeByDefault:!0},jn={mount:function(t){for(var e in Qa)Qa.hasOwnProperty(e)&&!(e in t)&&(t[e]=Qa[e]);Qs.forEach(function(i){if(i.pluginName===t.pluginName)throw"Sortable: Cannot mount plugin ".concat(t.pluginName," more than once")}),Qs.push(t)},pluginEvent:function(t,e,i){var n=this;this.eventCanceled=!1,i.cancel=function(){n.eventCanceled=!0};var o=t+"Global";Qs.forEach(function(c){e[c.pluginName]&&(e[c.pluginName][o]&&e[c.pluginName][o](Je({sortable:e},i)),e.options[c.pluginName]&&e[c.pluginName][t]&&e[c.pluginName][t](Je({sortable:e},i)))})},initializePlugins:function(t,e,i,n){Qs.forEach(function(l){var h=l.pluginName;if(!(!t.options[h]&&!l.initializeByDefault)){var m=new l(t,e,t.options);m.sortable=t,m.options=t.options,t[h]=m,fi(i,m.defaults)}});for(var o in t.options)if(t.options.hasOwnProperty(o)){var c=this.modifyOption(t,o,t.options[o]);typeof c<"u"&&(t.options[o]=c)}},getEventProperties:function(t,e){var i={};return Qs.forEach(function(n){typeof n.eventProperties=="function"&&fi(i,n.eventProperties.call(e[n.pluginName],t))}),i},modifyOption:function(t,e,i){var n;return Qs.forEach(function(o){t[o.pluginName]&&o.optionListeners&&typeof o.optionListeners[e]=="function"&&(n=o.optionListeners[e].call(t[o.pluginName],i))}),n}};function Tu(s){var t=s.sortable,e=s.rootEl,i=s.name,n=s.targetEl,o=s.cloneEl,c=s.toEl,l=s.fromEl,h=s.oldIndex,m=s.newIndex,u=s.oldDraggableIndex,a=s.newDraggableIndex,f=s.originalEvent,w=s.putSortable,E=s.extraEventProperties;if(t=t||e&&e[Ae],!!t){var p,y=t.options,r="on"+i.charAt(0).toUpperCase()+i.substr(1);window.CustomEvent&&!gi&&!zn?p=new CustomEvent(i,{bubbles:!0,cancelable:!0}):(p=document.createEvent("Event"),p.initEvent(i,!0,!0)),p.to=c||e,p.from=l||e,p.item=n||e,p.clone=o,p.oldIndex=h,p.newIndex=m,p.oldDraggableIndex=u,p.newDraggableIndex=a,p.originalEvent=f,p.pullMode=w?w.lastPutMode:void 0;var d=Je(Je({},E),jn.getEventProperties(i,t));for(var b in d)p[b]=d[b];e&&e.dispatchEvent(p),y[r]&&y[r].call(t,p)}}var Pu=["evt"],xe=function(t,e){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},n=i.evt,o=vu(i,Pu);jn.pluginEvent.bind(Ct)(t,e,Je({dragEl:gt,parentEl:Qt,ghostEl:Tt,rootEl:Wt,nextEl:ys,lastDownEl:Eo,cloneEl:Kt,cloneHidden:Li,dragStarted:Ln,putSortable:ce,activeSortable:Ct.active,originalEvent:n,oldIndex:en,oldDraggableIndex:$n,newIndex:Te,newDraggableIndex:Ii,hideGhostForTarget:Eh,unhideGhostForTarget:Ch,cloneNowHidden:function(){Li=!0},cloneNowShown:function(){Li=!1},dispatchSortableEvent:function(l){be({sortable:e,name:l,originalEvent:n})}},o))};function be(s){Tu(Je({putSortable:ce,cloneEl:Kt,targetEl:gt,rootEl:Wt,oldIndex:en,oldDraggableIndex:$n,newIndex:Te,newDraggableIndex:Ii},s))}var gt,Qt,Tt,Wt,ys,Eo,Kt,Li,en,Te,$n,Ii,vo,ce,tn=!1,ko=!1,Do=[],ms,Ne,Za,tl,ch,hh,Ln,Zs,Un,Hn=!1,wo=!1,Co,pe,el=[],ol=!1,Ro=[],Io=typeof document<"u",xo=hl,dh=zn||gi?"cssFloat":"float",ku=Io&&!ph&&!hl&&"draggable"in document.createElement("div"),xh=(function(){if(Io){if(gi)return!1;var s=document.createElement("x");return s.style.cssText="pointer-events:auto",s.style.pointerEvents==="auto"}})(),Ah=function(t,e){var i=Et(t),n=parseInt(i.width)-parseInt(i.paddingLeft)-parseInt(i.paddingRight)-parseInt(i.borderLeftWidth)-parseInt(i.borderRightWidth),o=nn(t,0,e),c=nn(t,1,e),l=o&&Et(o),h=c&&Et(c),m=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+ie(o).width,u=h&&parseInt(h.marginLeft)+parseInt(h.marginRight)+ie(c).width;if(i.display==="flex")return i.flexDirection==="column"||i.flexDirection==="column-reverse"?"vertical":"horizontal";if(i.display==="grid")return i.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(o&&l.float&&l.float!=="none"){var a=l.float==="left"?"left":"right";return c&&(h.clear==="both"||h.clear===a)?"vertical":"horizontal"}return o&&(l.display==="block"||l.display==="flex"||l.display==="table"||l.display==="grid"||m>=n&&i[dh]==="none"||c&&i[dh]==="none"&&m+u>n)?"vertical":"horizontal"},Du=function(t,e,i){var n=i?t.left:t.top,o=i?t.right:t.bottom,c=i?t.width:t.height,l=i?e.left:e.top,h=i?e.right:e.bottom,m=i?e.width:e.height;return n===l||o===h||n+c/2===l+m/2},Ru=function(t,e){var i;return Do.some(function(n){var o=n[Ae].options.emptyInsertThreshold;if(!(!o||dl(n))){var c=ie(n),l=t>=c.left-o&&t<=c.right+o,h=e>=c.top-o&&e<=c.bottom+o;if(l&&h)return i=n}}),i},Sh=function(t){function e(o,c){return function(l,h,m,u){var a=l.options.group.name&&h.options.group.name&&l.options.group.name===h.options.group.name;if(o==null&&(c||a))return!0;if(o==null||o===!1)return!1;if(c&&o==="clone")return o;if(typeof o=="function")return e(o(l,h,m,u),c)(l,h,m,u);var f=(c?l:h).options.group.name;return o===!0||typeof o=="string"&&o===f||o.join&&o.indexOf(f)>-1}}var i={},n=t.group;(!n||So(n)!="object")&&(n={name:n}),i.name=n.name,i.checkPull=e(n.pull,!0),i.checkPut=e(n.put),i.revertClone=n.revertClone,t.group=i},Eh=function(){!xh&&Tt&&Et(Tt,"display","none")},Ch=function(){!xh&&Tt&&Et(Tt,"display","")};Io&&!ph&&document.addEventListener("click",function(s){if(ko)return s.preventDefault(),s.stopPropagation&&s.stopPropagation(),s.stopImmediatePropagation&&s.stopImmediatePropagation(),ko=!1,!1},!0);var bs=function(t){if(gt){t=t.touches?t.touches[0]:t;var e=Ru(t.clientX,t.clientY);if(e){var i={};for(var n in t)t.hasOwnProperty(n)&&(i[n]=t[n]);i.target=i.rootEl=e,i.preventDefault=void 0,i.stopPropagation=void 0,e[Ae]._onDragOver(i)}}},Mu=function(t){gt&>.parentNode[Ae]._isOutsideThisEl(t.target)};function Ct(s,t){if(!(s&&s.nodeType&&s.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(s));this.el=s,this.options=t=fi({},t),s[Ae]=this;var e={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(s.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Ah(s,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(c,l){c.setData("Text",l.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:Ct.supportPointer!==!1&&"PointerEvent"in window&&(!Nn||hl),emptyInsertThreshold:5};jn.initializePlugins(this,s,e);for(var i in e)!(i in t)&&(t[i]=e[i]);Sh(t);for(var n in this)n.charAt(0)==="_"&&typeof this[n]=="function"&&(this[n]=this[n].bind(this));this.nativeDraggable=t.forceFallback?!1:ku,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?Ot(s,"pointerdown",this._onTapStart):(Ot(s,"mousedown",this._onTapStart),Ot(s,"touchstart",this._onTapStart)),this.nativeDraggable&&(Ot(s,"dragover",this),Ot(s,"dragenter",this)),Do.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),fi(this,Eu())}Ct.prototype={constructor:Ct,_isOutsideThisEl:function(t){!this.el.contains(t)&&t!==this.el&&(Zs=null)},_getDirection:function(t,e){return typeof this.options.direction=="function"?this.options.direction.call(this,t,e,gt):this.options.direction},_onTapStart:function(t){if(t.cancelable){var e=this,i=this.el,n=this.options,o=n.preventOnFilter,c=t.type,l=t.touches&&t.touches[0]||t.pointerType&&t.pointerType==="touch"&&t,h=(l||t).target,m=t.target.shadowRoot&&(t.path&&t.path[0]||t.composedPath&&t.composedPath()[0])||h,u=n.filter;if(Uu(i),!gt&&!(/mousedown|pointerdown/.test(c)&&t.button!==0||n.disabled)&&!m.isContentEditable&&!(!this.nativeDraggable&&Nn&&h&&h.tagName.toUpperCase()==="SELECT")&&(h=Be(h,n.draggable,i,!1),!(h&&h.animated)&&Eo!==h)){if(en=Me(h),$n=Me(h,n.draggable),typeof u=="function"){if(u.call(this,t,h,this)){be({sortable:e,rootEl:m,name:"filter",targetEl:h,toEl:i,fromEl:i}),xe("filter",e,{evt:t}),o&&t.preventDefault();return}}else if(u&&(u=u.split(",").some(function(a){if(a=Be(m,a.trim(),i,!1),a)return be({sortable:e,rootEl:a,name:"filter",targetEl:h,fromEl:i,toEl:i}),xe("filter",e,{evt:t}),!0}),u)){o&&t.preventDefault();return}n.handle&&!Be(m,n.handle,i,!1)||this._prepareDragStart(t,l,h)}}},_prepareDragStart:function(t,e,i){var n=this,o=n.el,c=n.options,l=o.ownerDocument,h;if(i&&!gt&&i.parentNode===o){var m=ie(i);if(Wt=o,gt=i,Qt=gt.parentNode,ys=gt.nextSibling,Eo=i,vo=c.group,Ct.dragged=gt,ms={target:gt,clientX:(e||t).clientX,clientY:(e||t).clientY},ch=ms.clientX-m.left,hh=ms.clientY-m.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,gt.style["will-change"]="all",h=function(){if(xe("delayEnded",n,{evt:t}),Ct.eventCanceled){n._onDrop();return}n._disableDelayedDragEvents(),!rh&&n.nativeDraggable&&(gt.draggable=!0),n._triggerDragStart(t,e),be({sortable:n,name:"choose",originalEvent:t}),_e(gt,c.chosenClass,!0)},c.ignore.split(",").forEach(function(u){mh(gt,u.trim(),il)}),Ot(l,"dragover",bs),Ot(l,"mousemove",bs),Ot(l,"touchmove",bs),c.supportPointer?(Ot(l,"pointerup",n._onDrop),!this.nativeDraggable&&Ot(l,"pointercancel",n._onDrop)):(Ot(l,"mouseup",n._onDrop),Ot(l,"touchend",n._onDrop),Ot(l,"touchcancel",n._onDrop)),rh&&this.nativeDraggable&&(this.options.touchStartThreshold=4,gt.draggable=!0),xe("delayStart",this,{evt:t}),c.delay&&(!c.delayOnTouchOnly||e)&&(!this.nativeDraggable||!(zn||gi))){if(Ct.eventCanceled){this._onDrop();return}c.supportPointer?(Ot(l,"pointerup",n._disableDelayedDrag),Ot(l,"pointercancel",n._disableDelayedDrag)):(Ot(l,"mouseup",n._disableDelayedDrag),Ot(l,"touchend",n._disableDelayedDrag),Ot(l,"touchcancel",n._disableDelayedDrag)),Ot(l,"mousemove",n._delayedDragTouchMoveHandler),Ot(l,"touchmove",n._delayedDragTouchMoveHandler),c.supportPointer&&Ot(l,"pointermove",n._delayedDragTouchMoveHandler),n._dragStartTimer=setTimeout(h,c.delay)}else h()}},_delayedDragTouchMoveHandler:function(t){var e=t.touches?t.touches[0]:t;Math.max(Math.abs(e.clientX-this._lastX),Math.abs(e.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){gt&&il(gt),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;Ft(t,"mouseup",this._disableDelayedDrag),Ft(t,"touchend",this._disableDelayedDrag),Ft(t,"touchcancel",this._disableDelayedDrag),Ft(t,"pointerup",this._disableDelayedDrag),Ft(t,"pointercancel",this._disableDelayedDrag),Ft(t,"mousemove",this._delayedDragTouchMoveHandler),Ft(t,"touchmove",this._delayedDragTouchMoveHandler),Ft(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||t.pointerType=="touch"&&t,!this.nativeDraggable||e?this.options.supportPointer?Ot(document,"pointermove",this._onTouchMove):e?Ot(document,"touchmove",this._onTouchMove):Ot(document,"mousemove",this._onTouchMove):(Ot(gt,"dragend",this),Ot(Wt,"dragstart",this._onDragStart));try{document.selection?_o(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(t,e){if(tn=!1,Wt&>){xe("dragStarted",this,{evt:e}),this.nativeDraggable&&Ot(document,"dragover",Mu);var i=this.options;!t&&_e(gt,i.dragClass,!1),_e(gt,i.ghostClass,!0),Ct.active=this,t&&this._appendGhost(),be({sortable:this,name:"start",originalEvent:e})}else this._nulling()},_emulateDragOver:function(){if(Ne){this._lastX=Ne.clientX,this._lastY=Ne.clientY,Eh();for(var t=document.elementFromPoint(Ne.clientX,Ne.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(Ne.clientX,Ne.clientY),t!==e);)e=t;if(gt.parentNode[Ae]._isOutsideThisEl(t),e)do{if(e[Ae]){var i=void 0;if(i=e[Ae]._onDragOver({clientX:Ne.clientX,clientY:Ne.clientY,target:t,rootEl:e}),i&&!this.options.dragoverBubble)break}t=e}while(e=gh(e));Ch()}},_onTouchMove:function(t){if(ms){var e=this.options,i=e.fallbackTolerance,n=e.fallbackOffset,o=t.touches?t.touches[0]:t,c=Tt&&sn(Tt,!0),l=Tt&&c&&c.a,h=Tt&&c&&c.d,m=xo&&pe&&lh(pe),u=(o.clientX-ms.clientX+n.x)/(l||1)+(m?m[0]-el[0]:0)/(l||1),a=(o.clientY-ms.clientY+n.y)/(h||1)+(m?m[1]-el[1]:0)/(h||1);if(!Ct.active&&!tn){if(i&&Math.max(Math.abs(o.clientX-this._lastX),Math.abs(o.clientY-this._lastY))<i)return;this._onDragStart(t,!0)}if(Tt){c?(c.e+=u-(Za||0),c.f+=a-(tl||0)):c={a:1,b:0,c:0,d:1,e:u,f:a};var f="matrix(".concat(c.a,",").concat(c.b,",").concat(c.c,",").concat(c.d,",").concat(c.e,",").concat(c.f,")");Et(Tt,"webkitTransform",f),Et(Tt,"mozTransform",f),Et(Tt,"msTransform",f),Et(Tt,"transform",f),Za=u,tl=a,Ne=o}t.cancelable&&t.preventDefault()}},_appendGhost:function(){if(!Tt){var t=this.options.fallbackOnBody?document.body:Wt,e=ie(gt,!0,xo,!0,t),i=this.options;if(xo){for(pe=t;Et(pe,"position")==="static"&&Et(pe,"transform")==="none"&&pe!==document;)pe=pe.parentNode;pe!==document.body&&pe!==document.documentElement?(pe===document&&(pe=Ye()),e.top+=pe.scrollTop,e.left+=pe.scrollLeft):pe=Ye(),el=lh(pe)}Tt=gt.cloneNode(!0),_e(Tt,i.ghostClass,!1),_e(Tt,i.fallbackClass,!0),_e(Tt,i.dragClass,!0),Et(Tt,"transition",""),Et(Tt,"transform",""),Et(Tt,"box-sizing","border-box"),Et(Tt,"margin",0),Et(Tt,"top",e.top),Et(Tt,"left",e.left),Et(Tt,"width",e.width),Et(Tt,"height",e.height),Et(Tt,"opacity","0.8"),Et(Tt,"position",xo?"absolute":"fixed"),Et(Tt,"zIndex","100000"),Et(Tt,"pointerEvents","none"),Ct.ghost=Tt,t.appendChild(Tt),Et(Tt,"transform-origin",ch/parseInt(Tt.style.width)*100+"% "+hh/parseInt(Tt.style.height)*100+"%")}},_onDragStart:function(t,e){var i=this,n=t.dataTransfer,o=i.options;if(xe("dragStart",this,{evt:t}),Ct.eventCanceled){this._onDrop();return}xe("setupClone",this),Ct.eventCanceled||(Kt=vh(gt),Kt.removeAttribute("id"),Kt.draggable=!1,Kt.style["will-change"]="",this._hideClone(),_e(Kt,this.options.chosenClass,!1),Ct.clone=Kt),i.cloneId=_o(function(){xe("clone",i),!Ct.eventCanceled&&(i.options.removeCloneOnHide||Wt.insertBefore(Kt,gt),i._hideClone(),be({sortable:i,name:"clone"}))}),!e&&_e(gt,o.dragClass,!0),e?(ko=!0,i._loopId=setInterval(i._emulateDragOver,50)):(Ft(document,"mouseup",i._onDrop),Ft(document,"touchend",i._onDrop),Ft(document,"touchcancel",i._onDrop),n&&(n.effectAllowed="move",o.setData&&o.setData.call(i,n,gt)),Ot(document,"drop",i),Et(gt,"transform","translateZ(0)")),tn=!0,i._dragStartId=_o(i._dragStarted.bind(i,e,t)),Ot(document,"selectstart",i),Ln=!0,window.getSelection().removeAllRanges(),Nn&&Et(document.body,"user-select","none")},_onDragOver:function(t){var e=this.el,i=t.target,n,o,c,l=this.options,h=l.group,m=Ct.active,u=vo===h,a=l.sort,f=ce||m,w,E=this,p=!1;if(ol)return;function y(tt,st){xe(tt,E,Je({evt:t,isOwner:u,axis:w?"vertical":"horizontal",revert:c,dragRect:n,targetRect:o,canSort:a,fromSortable:f,target:i,completed:d,onMove:function(nt,G){return Ao(Wt,e,gt,n,nt,ie(nt),t,G)},changed:b},st))}function r(){y("dragOverAnimationCapture"),E.captureAnimationState(),E!==f&&f.captureAnimationState()}function d(tt){return y("dragOverCompleted",{insertion:tt}),tt&&(u?m._hideClone():m._showClone(E),E!==f&&(_e(gt,ce?ce.options.ghostClass:m.options.ghostClass,!1),_e(gt,l.ghostClass,!0)),ce!==E&&E!==Ct.active?ce=E:E===Ct.active&&ce&&(ce=null),f===E&&(E._ignoreWhileAnimating=i),E.animateAll(function(){y("dragOverAnimationComplete"),E._ignoreWhileAnimating=null}),E!==f&&(f.animateAll(),f._ignoreWhileAnimating=null)),(i===gt&&!gt.animated||i===e&&!i.animated)&&(Zs=null),!l.dragoverBubble&&!t.rootEl&&i!==document&&(gt.parentNode[Ae]._isOutsideThisEl(t.target),!tt&&bs(t)),!l.dragoverBubble&&t.stopPropagation&&t.stopPropagation(),p=!0}function b(){Te=Me(gt),Ii=Me(gt,l.draggable),be({sortable:E,name:"change",toEl:e,newIndex:Te,newDraggableIndex:Ii,originalEvent:t})}if(t.preventDefault!==void 0&&t.cancelable&&t.preventDefault(),i=Be(i,l.draggable,e,!0),y("dragOver"),Ct.eventCanceled)return p;if(gt.contains(t.target)||i.animated&&i.animatingX&&i.animatingY||E._ignoreWhileAnimating===i)return d(!1);if(ko=!1,m&&!l.disabled&&(u?a||(c=Qt!==Wt):ce===this||(this.lastPutMode=vo.checkPull(this,m,gt,t))&&h.checkPut(this,m,gt,t))){if(w=this._getDirection(t,i)==="vertical",n=ie(gt),y("dragOverValid"),Ct.eventCanceled)return p;if(c)return Qt=Wt,r(),this._hideClone(),y("revert"),Ct.eventCanceled||(ys?Wt.insertBefore(gt,ys):Wt.appendChild(gt)),d(!0);var x=dl(e,l.draggable);if(!x||Ou(t,w,this)&&!x.animated){if(x===gt)return d(!1);if(x&&e===t.target&&(i=x),i&&(o=ie(i)),Ao(Wt,e,gt,n,i,o,t,!!i)!==!1)return r(),x&&x.nextSibling?e.insertBefore(gt,x.nextSibling):e.appendChild(gt),Qt=e,b(),d(!0)}else if(x&&Fu(t,w,this)){var _=nn(e,0,l,!0);if(_===gt)return d(!1);if(i=_,o=ie(i),Ao(Wt,e,gt,n,i,o,t,!1)!==!1)return r(),e.insertBefore(gt,_),Qt=e,b(),d(!0)}else if(i.parentNode===e){o=ie(i);var S=0,R,N=gt.parentNode!==e,H=!Du(gt.animated&>.toRect||n,i.animated&&i.toRect||o,w),z=w?"top":"left",K=ah(i,"top","top")||ah(gt,"top","top"),it=K?K.scrollTop:void 0;Zs!==i&&(R=o[z],Hn=!1,wo=!H&&l.invertSwap||N),S=Nu(t,i,o,w,H?1:l.swapThreshold,l.invertedSwapThreshold==null?l.swapThreshold:l.invertedSwapThreshold,wo,Zs===i);var at;if(S!==0){var X=Me(gt);do X-=S,at=Qt.children[X];while(at&&(Et(at,"display")==="none"||at===Tt))}if(S===0||at===i)return d(!1);Zs=i,Un=S;var j=i.nextElementSibling,W=!1;W=S===1;var Y=Ao(Wt,e,gt,n,i,o,t,W);if(Y!==!1)return(Y===1||Y===-1)&&(W=Y===1),ol=!0,setTimeout(Lu,30),r(),W&&!j?e.appendChild(gt):i.parentNode.insertBefore(gt,W?j:i),K&&yh(K,0,it-K.scrollTop),Qt=gt.parentNode,R!==void 0&&!wo&&(Co=Math.abs(R-ie(i)[z])),b(),d(!0)}if(e.contains(gt))return d(!1)}return!1},_ignoreWhileAnimating:null,_offMoveEvents:function(){Ft(document,"mousemove",this._onTouchMove),Ft(document,"touchmove",this._onTouchMove),Ft(document,"pointermove",this._onTouchMove),Ft(document,"dragover",bs),Ft(document,"mousemove",bs),Ft(document,"touchmove",bs)},_offUpEvents:function(){var t=this.el.ownerDocument;Ft(t,"mouseup",this._onDrop),Ft(t,"touchend",this._onDrop),Ft(t,"pointerup",this._onDrop),Ft(t,"pointercancel",this._onDrop),Ft(t,"touchcancel",this._onDrop),Ft(document,"selectstart",this)},_onDrop:function(t){var e=this.el,i=this.options;if(Te=Me(gt),Ii=Me(gt,i.draggable),xe("drop",this,{evt:t}),Qt=gt&>.parentNode,Te=Me(gt),Ii=Me(gt,i.draggable),Ct.eventCanceled){this._nulling();return}tn=!1,wo=!1,Hn=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),al(this.cloneId),al(this._dragStartId),this.nativeDraggable&&(Ft(document,"drop",this),Ft(e,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),Nn&&Et(document.body,"user-select",""),Et(gt,"transform",""),t&&(Ln&&(t.cancelable&&t.preventDefault(),!i.dropBubble&&t.stopPropagation()),Tt&&Tt.parentNode&&Tt.parentNode.removeChild(Tt),(Wt===Qt||ce&&ce.lastPutMode!=="clone")&&Kt&&Kt.parentNode&&Kt.parentNode.removeChild(Kt),gt&&(this.nativeDraggable&&Ft(gt,"dragend",this),il(gt),gt.style["will-change"]="",Ln&&!tn&&_e(gt,ce?ce.options.ghostClass:this.options.ghostClass,!1),_e(gt,this.options.chosenClass,!1),be({sortable:this,name:"unchoose",toEl:Qt,newIndex:null,newDraggableIndex:null,originalEvent:t}),Wt!==Qt?(Te>=0&&(be({rootEl:Qt,name:"add",toEl:Qt,fromEl:Wt,originalEvent:t}),be({sortable:this,name:"remove",toEl:Qt,originalEvent:t}),be({rootEl:Qt,name:"sort",toEl:Qt,fromEl:Wt,originalEvent:t}),be({sortable:this,name:"sort",toEl:Qt,originalEvent:t})),ce&&ce.save()):Te!==en&&Te>=0&&(be({sortable:this,name:"update",toEl:Qt,originalEvent:t}),be({sortable:this,name:"sort",toEl:Qt,originalEvent:t})),Ct.active&&((Te==null||Te===-1)&&(Te=en,Ii=$n),be({sortable:this,name:"end",toEl:Qt,originalEvent:t}),this.save()))),this._nulling()},_nulling:function(){xe("nulling",this),Wt=gt=Qt=Tt=ys=Kt=Eo=Li=ms=Ne=Ln=Te=Ii=en=$n=Zs=Un=ce=vo=Ct.dragged=Ct.ghost=Ct.clone=Ct.active=null,Ro.forEach(function(t){t.checked=!0}),Ro.length=Za=tl=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":gt&&(this._onDragOver(t),Iu(t));break;case"selectstart":t.preventDefault();break}},toArray:function(){for(var t=[],e,i=this.el.children,n=0,o=i.length,c=this.options;n<o;n++)e=i[n],Be(e,c.draggable,this.el,!1)&&t.push(e.getAttribute(c.dataIdAttr)||$u(e));return t},sort:function(t,e){var i={},n=this.el;this.toArray().forEach(function(o,c){var l=n.children[c];Be(l,this.options.draggable,n,!1)&&(i[o]=l)},this),e&&this.captureAnimationState(),t.forEach(function(o){i[o]&&(n.removeChild(i[o]),n.appendChild(i[o]))}),e&&this.animateAll()},save:function(){var t=this.options.store;t&&t.set&&t.set(this)},closest:function(t,e){return Be(t,e||this.options.draggable,this.el,!1)},option:function(t,e){var i=this.options;if(e===void 0)return i[t];var n=jn.modifyOption(this,t,e);typeof n<"u"?i[t]=n:i[t]=e,t==="group"&&Sh(i)},destroy:function(){xe("destroy",this);var t=this.el;t[Ae]=null,Ft(t,"mousedown",this._onTapStart),Ft(t,"touchstart",this._onTapStart),Ft(t,"pointerdown",this._onTapStart),this.nativeDraggable&&(Ft(t,"dragover",this),Ft(t,"dragenter",this)),Array.prototype.forEach.call(t.querySelectorAll("[draggable]"),function(e){e.removeAttribute("draggable")}),this._onDrop(),this._disableDelayedDragEvents(),Do.splice(Do.indexOf(this.el),1),this.el=t=null},_hideClone:function(){if(!Li){if(xe("hideClone",this),Ct.eventCanceled)return;Et(Kt,"display","none"),this.options.removeCloneOnHide&&Kt.parentNode&&Kt.parentNode.removeChild(Kt),Li=!0}},_showClone:function(t){if(t.lastPutMode!=="clone"){this._hideClone();return}if(Li){if(xe("showClone",this),Ct.eventCanceled)return;gt.parentNode==Wt&&!this.options.group.revertClone?Wt.insertBefore(Kt,gt):ys?Wt.insertBefore(Kt,ys):Wt.appendChild(Kt),this.options.group.revertClone&&this.animate(gt,Kt),Et(Kt,"display",""),Li=!1}}};function Iu(s){s.dataTransfer&&(s.dataTransfer.dropEffect="move"),s.cancelable&&s.preventDefault()}function Ao(s,t,e,i,n,o,c,l){var h,m=s[Ae],u=m.options.onMove,a;return window.CustomEvent&&!gi&&!zn?h=new CustomEvent("move",{bubbles:!0,cancelable:!0}):(h=document.createEvent("Event"),h.initEvent("move",!0,!0)),h.to=t,h.from=s,h.dragged=e,h.draggedRect=i,h.related=n||t,h.relatedRect=o||ie(t),h.willInsertAfter=l,h.originalEvent=c,s.dispatchEvent(h),u&&(a=u.call(m,h,c)),a}function il(s){s.draggable=!1}function Lu(){ol=!1}function Fu(s,t,e){var i=ie(nn(e.el,0,e.options,!0)),n=wh(e.el,e.options,Tt),o=10;return t?s.clientX<n.left-o||s.clientY<i.top&&s.clientX<i.right:s.clientY<n.top-o||s.clientY<i.bottom&&s.clientX<i.left}function Ou(s,t,e){var i=ie(dl(e.el,e.options.draggable)),n=wh(e.el,e.options,Tt),o=10;return t?s.clientX>n.right+o||s.clientY>i.bottom&&s.clientX>i.left:s.clientY>n.bottom+o||s.clientX>i.right&&s.clientY>i.top}function Nu(s,t,e,i,n,o,c,l){var h=i?s.clientY:s.clientX,m=i?e.height:e.width,u=i?e.top:e.left,a=i?e.bottom:e.right,f=!1;if(!c){if(l&&Co<m*n){if(!Hn&&(Un===1?h>u+m*o/2:h<a-m*o/2)&&(Hn=!0),Hn)f=!0;else if(Un===1?h<u+Co:h>a-Co)return-Un}else if(h>u+m*(1-n)/2&&h<a-m*(1-n)/2)return Bu(t)}return f=f||c,f&&(h<u+m*o/2||h>a-m*o/2)?h>u+m/2?1:-1:0}function Bu(s){return Me(gt)<Me(s)?1:-1}function $u(s){for(var t=s.tagName+s.className+s.src+s.href+s.textContent,e=t.length,i=0;e--;)i+=t.charCodeAt(e);return i.toString(36)}function Uu(s){Ro.length=0;for(var t=s.getElementsByTagName("input"),e=t.length;e--;){var i=t[e];i.checked&&Ro.push(i)}}function _o(s){return setTimeout(s,0)}function al(s){return clearTimeout(s)}Io&&Ot(document,"touchmove",function(s){(Ct.active||tn)&&s.cancelable&&s.preventDefault()});Ct.utils={on:Ot,off:Ft,css:Et,find:mh,is:function(t,e){return!!Be(t,e,t,!1)},extend:Au,throttle:bh,closest:Be,toggleClass:_e,clone:vh,index:Me,nextTick:_o,cancelNextTick:al,detectDirection:Ah,getChild:nn,expando:Ae};Ct.get=function(s){return s[Ae]};Ct.mount=function(){for(var s=arguments.length,t=new Array(s),e=0;e<s;e++)t[e]=arguments[e];t[0].constructor===Array&&(t=t[0]),t.forEach(function(i){if(!i.prototype||!i.prototype.constructor)throw"Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(i));i.utils&&(Ct.utils=Je(Je({},Ct.utils),i.utils)),jn.mount(i)})};Ct.create=function(s,t){return new Ct(s,t)};Ct.version=wu;var ee=[],Fn,ll,cl=!1,sl,nl,Mo,On;function Hu(){function s(){this.defaults={scroll:!0,forceAutoScrollFallback:!1,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0};for(var t in this)t.charAt(0)==="_"&&typeof this[t]=="function"&&(this[t]=this[t].bind(this))}return s.prototype={dragStarted:function(e){var i=e.originalEvent;this.sortable.nativeDraggable?Ot(document,"dragover",this._handleAutoScroll):this.options.supportPointer?Ot(document,"pointermove",this._handleFallbackAutoScroll):i.touches?Ot(document,"touchmove",this._handleFallbackAutoScroll):Ot(document,"mousemove",this._handleFallbackAutoScroll)},dragOverCompleted:function(e){var i=e.originalEvent;!this.options.dragOverBubble&&!i.rootEl&&this._handleAutoScroll(i)},drop:function(){this.sortable.nativeDraggable?Ft(document,"dragover",this._handleAutoScroll):(Ft(document,"pointermove",this._handleFallbackAutoScroll),Ft(document,"touchmove",this._handleFallbackAutoScroll),Ft(document,"mousemove",this._handleFallbackAutoScroll)),uh(),To(),Su()},nulling:function(){Mo=ll=Fn=cl=On=sl=nl=null,ee.length=0},_handleFallbackAutoScroll:function(e){this._handleAutoScroll(e,!0)},_handleAutoScroll:function(e,i){var n=this,o=(e.touches?e.touches[0]:e).clientX,c=(e.touches?e.touches[0]:e).clientY,l=document.elementFromPoint(o,c);if(Mo=e,i||this.options.forceAutoScrollFallback||zn||gi||Nn){rl(e,this.options,l,i);var h=Fi(l,!0);cl&&(!On||o!==sl||c!==nl)&&(On&&uh(),On=setInterval(function(){var m=Fi(document.elementFromPoint(o,c),!0);m!==h&&(h=m,To()),rl(e,n.options,m,i)},10),sl=o,nl=c)}else{if(!this.options.bubbleScroll||Fi(l,!0)===Ye()){To();return}rl(e,this.options,Fi(l,!1),!1)}}},fi(s,{pluginName:"scroll",initializeByDefault:!0})}function To(){ee.forEach(function(s){clearInterval(s.pid)}),ee=[]}function uh(){clearInterval(On)}var rl=bh(function(s,t,e,i){if(t.scroll){var n=(s.touches?s.touches[0]:s).clientX,o=(s.touches?s.touches[0]:s).clientY,c=t.scrollSensitivity,l=t.scrollSpeed,h=Ye(),m=!1,u;ll!==e&&(ll=e,To(),Fn=t.scroll,u=t.scrollFn,Fn===!0&&(Fn=Fi(e,!0)));var a=0,f=Fn;do{var w=f,E=ie(w),p=E.top,y=E.bottom,r=E.left,d=E.right,b=E.width,x=E.height,_=void 0,S=void 0,R=w.scrollWidth,N=w.scrollHeight,H=Et(w),z=w.scrollLeft,K=w.scrollTop;w===h?(_=b<R&&(H.overflowX==="auto"||H.overflowX==="scroll"||H.overflowX==="visible"),S=x<N&&(H.overflowY==="auto"||H.overflowY==="scroll"||H.overflowY==="visible")):(_=b<R&&(H.overflowX==="auto"||H.overflowX==="scroll"),S=x<N&&(H.overflowY==="auto"||H.overflowY==="scroll"));var it=_&&(Math.abs(d-n)<=c&&z+b<R)-(Math.abs(r-n)<=c&&!!z),at=S&&(Math.abs(y-o)<=c&&K+x<N)-(Math.abs(p-o)<=c&&!!K);if(!ee[a])for(var X=0;X<=a;X++)ee[X]||(ee[X]={});(ee[a].vx!=it||ee[a].vy!=at||ee[a].el!==w)&&(ee[a].el=w,ee[a].vx=it,ee[a].vy=at,clearInterval(ee[a].pid),(it!=0||at!=0)&&(m=!0,ee[a].pid=setInterval(function(){i&&this.layer===0&&Ct.active._onTouchMove(Mo);var j=ee[this.layer].vy?ee[this.layer].vy*l:0,W=ee[this.layer].vx?ee[this.layer].vx*l:0;typeof u=="function"&&u.call(Ct.dragged.parentNode[Ae],W,j,s,Mo,ee[this.layer].el)!=="continue"||yh(ee[this.layer].el,W,j)}.bind({layer:a}),24))),a++}while(t.bubbleScroll&&f!==h&&(f=Fi(f,!1)));cl=m}},30),_h=function(t){var e=t.originalEvent,i=t.putSortable,n=t.dragEl,o=t.activeSortable,c=t.dispatchSortableEvent,l=t.hideGhostForTarget,h=t.unhideGhostForTarget;if(e){var m=i||o;l();var u=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:e,a=document.elementFromPoint(u.clientX,u.clientY);h(),m&&!m.el.contains(a)&&(c("spill"),this.onSpill({dragEl:n,putSortable:i}))}};function ul(){}ul.prototype={startIndex:null,dragStart:function(t){var e=t.oldDraggableIndex;this.startIndex=e},onSpill:function(t){var e=t.dragEl,i=t.putSortable;this.sortable.captureAnimationState(),i&&i.captureAnimationState();var n=nn(this.sortable.el,this.startIndex,this.options);n?this.sortable.el.insertBefore(e,n):this.sortable.el.appendChild(e),this.sortable.animateAll(),i&&i.animateAll()},drop:_h};fi(ul,{pluginName:"revertOnSpill"});function pl(){}pl.prototype={onSpill:function(t){var e=t.dragEl,i=t.putSortable,n=i||this.sortable;n.captureAnimationState(),e.parentNode&&e.parentNode.removeChild(e),n.animateAll()},drop:_h};fi(pl,{pluginName:"removeOnSpill"});Ct.mount(new Hu);Ct.mount(pl,ul);var Th=Ct;var rn,Vn,Wn,Lo,op={976:(s,t,e)=>{e.d(t,{AnnotationLayer:()=>T,FreeTextAnnotationElement:()=>z,InkAnnotationElement:()=>Y,StampAnnotationElement:()=>G});var i=e(292),n=e(419),o=e(792);function c(I){return Math.floor(255*Math.max(0,Math.min(1,I))).toString(16).padStart(2,"0")}function l(I){return Math.max(0,Math.min(255,255*I))}class h{static CMYK_G([g,v,P,k]){return["G",1-Math.min(1,.3*g+.59*P+.11*v+k)]}static G_CMYK([g]){return["CMYK",0,0,0,1-g]}static G_RGB([g]){return["RGB",g,g,g]}static G_rgb([g]){return[g=l(g),g,g]}static G_HTML([g]){let v=c(g);return`#${v}${v}${v}`}static RGB_G([g,v,P]){return["G",.3*g+.59*v+.11*P]}static RGB_rgb(g){return g.map(l)}static RGB_HTML(g){return`#${g.map(c).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([g,v,P,k]){return["RGB",1-Math.min(1,g+k),1-Math.min(1,P+k),1-Math.min(1,v+k)]}static CMYK_rgb([g,v,P,k]){return[l(1-Math.min(1,g+k)),l(1-Math.min(1,P+k)),l(1-Math.min(1,v+k))]}static CMYK_HTML(g){let v=this.CMYK_RGB(g).slice(1);return this.RGB_HTML(v)}static RGB_CMYK([g,v,P]){let k=1-g,O=1-v,M=1-P;return["CMYK",k,O,M,Math.min(k,O,M)]}}var m=e(284);let u=1e3,a=new WeakSet;function f(I){return{width:I[2]-I[0],height:I[3]-I[1]}}class w{static create(g){switch(g.data.annotationType){case i.AnnotationType.LINK:return new p(g);case i.AnnotationType.TEXT:return new y(g);case i.AnnotationType.WIDGET:switch(g.data.fieldType){case"Tx":return new d(g);case"Btn":return g.data.radioButton?new _(g):g.data.checkBox?new x(g):new S(g);case"Ch":return new R(g);case"Sig":return new b(g)}return new r(g);case i.AnnotationType.POPUP:return new N(g);case i.AnnotationType.FREETEXT:return new z(g);case i.AnnotationType.LINE:return new K(g);case i.AnnotationType.SQUARE:return new it(g);case i.AnnotationType.CIRCLE:return new at(g);case i.AnnotationType.POLYLINE:return new X(g);case i.AnnotationType.CARET:return new W(g);case i.AnnotationType.INK:return new Y(g);case i.AnnotationType.POLYGON:return new j(g);case i.AnnotationType.HIGHLIGHT:return new tt(g);case i.AnnotationType.UNDERLINE:return new st(g);case i.AnnotationType.SQUIGGLY:return new lt(g);case i.AnnotationType.STRIKEOUT:return new nt(g);case i.AnnotationType.STAMP:return new G(g);case i.AnnotationType.FILEATTACHMENT:return new A(g);default:return new E(g)}}}class E{#t=!1;constructor(g,{isRenderable:v=!1,ignoreBorder:P=!1,createQuadrilaterals:k=!1}={}){this.isRenderable=v,this.data=g.data,this.layer=g.layer,this.linkService=g.linkService,this.downloadManager=g.downloadManager,this.imageResourcesPath=g.imageResourcesPath,this.renderForms=g.renderForms,this.svgFactory=g.svgFactory,this.annotationStorage=g.annotationStorage,this.enableScripting=g.enableScripting,this.hasJSActions=g.hasJSActions,this._fieldObjects=g.fieldObjects,this.parent=g.parent,v&&(this.container=this._createContainer(P)),k&&this._createQuadrilaterals()}static _hasPopupData({titleObj:g,contentsObj:v,richText:P}){return!!(g?.str||v?.str||P?.str)}get hasPopupData(){return E._hasPopupData(this.data)}_createContainer(g){let{data:v,parent:{page:P,viewport:k}}=this,O=document.createElement("section");O.setAttribute("data-annotation-id",v.id),this instanceof r||(O.tabIndex=u),O.style.zIndex=this.parent.zIndex++,v.popupRef&&O.setAttribute("aria-haspopup","dialog"),v.alternativeText&&(O.title=v.alternativeText),v.noRotate&&O.classList.add("norotate");let{pageWidth:M,pageHeight:C,pageX:L,pageY:$}=k.rawDims;if(!v.rect||this instanceof N){let{rotation:Q}=v;return v.hasOwnCanvas||Q===0||this.setRotation(Q,O),O}let{width:B,height:D}=f(v.rect),F=i.Util.normalizeRect([v.rect[0],P.view[3]-v.rect[1]+P.view[1],v.rect[2],P.view[3]-v.rect[3]+P.view[1]]);if(!g&&v.borderStyle.width>0){O.style.borderWidth=`${v.borderStyle.width}px`;let Q=v.borderStyle.horizontalCornerRadius,Z=v.borderStyle.verticalCornerRadius;if(Q>0||Z>0){let rt=`calc(${Q}px * var(--scale-factor)) / calc(${Z}px * var(--scale-factor))`;O.style.borderRadius=rt}else if(this instanceof _){let rt=`calc(${B}px * var(--scale-factor)) / calc(${D}px * var(--scale-factor))`;O.style.borderRadius=rt}switch(v.borderStyle.style){case i.AnnotationBorderStyleType.SOLID:O.style.borderStyle="solid";break;case i.AnnotationBorderStyleType.DASHED:O.style.borderStyle="dashed";break;case i.AnnotationBorderStyleType.BEVELED:(0,i.warn)("Unimplemented border style: beveled");break;case i.AnnotationBorderStyleType.INSET:(0,i.warn)("Unimplemented border style: inset");break;case i.AnnotationBorderStyleType.UNDERLINE:O.style.borderBottomStyle="solid"}let et=v.borderColor||null;et?(this.#t=!0,O.style.borderColor=i.Util.makeHexColor(0|et[0],0|et[1],0|et[2])):O.style.borderWidth=0}O.style.left=100*(F[0]-L)/M+"%",O.style.top=100*(F[1]-$)/C+"%";let{rotation:V}=v;return v.hasOwnCanvas||V===0?(O.style.width=100*B/M+"%",O.style.height=100*D/C+"%"):this.setRotation(V,O),O}setRotation(g,v=this.container){if(!this.data.rect)return;let{pageWidth:P,pageHeight:k}=this.parent.viewport.rawDims,{width:O,height:M}=f(this.data.rect),C,L;g%180==0?(C=100*O/P,L=100*M/k):(C=100*M/P,L=100*O/k),v.style.width=`${C}%`,v.style.height=`${L}%`,v.setAttribute("data-main-rotation",(360-g)%360)}get _commonActions(){let g=(v,P,k)=>{let O=k.detail[v],M=O[0],C=O.slice(1);k.target.style[P]=h[`${M}_HTML`](C),this.annotationStorage.setValue(this.data.id,{[P]:h[`${M}_rgb`](C)})};return(0,i.shadow)(this,"_commonActions",{display:v=>{let{display:P}=v.detail,k=P%2==1;this.container.style.visibility=k?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:k,noPrint:P===1||P===2})},print:v=>{this.annotationStorage.setValue(this.data.id,{noPrint:!v.detail.print})},hidden:v=>{let{hidden:P}=v.detail;this.container.style.visibility=P?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:P,noView:P})},focus:v=>{setTimeout((()=>v.target.focus({preventScroll:!1})),0)},userName:v=>{v.target.title=v.detail.userName},readonly:v=>{v.target.disabled=v.detail.readonly},required:v=>{this._setRequired(v.target,v.detail.required)},bgColor:v=>{g("bgColor","backgroundColor",v)},fillColor:v=>{g("fillColor","backgroundColor",v)},fgColor:v=>{g("fgColor","color",v)},textColor:v=>{g("textColor","color",v)},borderColor:v=>{g("borderColor","borderColor",v)},strokeColor:v=>{g("strokeColor","borderColor",v)},rotation:v=>{let P=v.detail.rotation;this.setRotation(P),this.annotationStorage.setValue(this.data.id,{rotation:P})}})}_dispatchEventFromSandbox(g,v){let P=this._commonActions;for(let k of Object.keys(v.detail))(g[k]||P[k])?.(v)}_setDefaultPropertiesFromJS(g){if(!this.enableScripting)return;let v=this.annotationStorage.getRawValue(this.data.id);if(!v)return;let P=this._commonActions;for(let[k,O]of Object.entries(v)){let M=P[k];M&&(M({detail:{[k]:O},target:g}),delete v[k])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:g}=this.data;if(!g)return;let[v,P,k,O]=this.data.rect;if(g.length===1){let[,{x:Z,y:et},{x:rt,y:pt}]=g[0];if(k===Z&&O===et&&v===rt&&P===pt)return}let{style:M}=this.container,C;if(this.#t){let{borderColor:Z,borderWidth:et}=M;M.borderWidth=0,C=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${Z}" stroke-width="${et}">`],this.container.classList.add("hasBorder")}let L=k-v,$=O-P,{svgFactory:B}=this,D=B.createElement("svg");D.classList.add("quadrilateralsContainer"),D.setAttribute("width",0),D.setAttribute("height",0);let F=B.createElement("defs");D.append(F);let V=B.createElement("clipPath"),Q=`clippath_${this.data.id}`;V.setAttribute("id",Q),V.setAttribute("clipPathUnits","objectBoundingBox"),F.append(V);for(let[,{x:Z,y:et},{x:rt,y:pt}]of g){let dt=B.createElement("rect"),ct=(rt-v)/L,wt=(O-et)/$,Pt=(Z-rt)/L,xt=(et-pt)/$;dt.setAttribute("x",ct),dt.setAttribute("y",wt),dt.setAttribute("width",Pt),dt.setAttribute("height",xt),V.append(dt),C?.push(`<rect vector-effect="non-scaling-stroke" x="${ct}" y="${wt}" width="${Pt}" height="${xt}"/>`)}this.#t&&(C.push("</g></svg>')"),M.backgroundImage=C.join("")),this.container.append(D),this.container.style.clipPath=`url(#${Q})`}_createPopup(){let{container:g,data:v}=this;g.setAttribute("aria-haspopup","dialog");let P=new N({data:{color:v.color,titleObj:v.titleObj,modificationDate:v.modificationDate,contentsObj:v.contentsObj,richText:v.richText,parentRect:v.rect,borderStyle:0,id:`popup_${v.id}`,rotation:v.rotation},parent:this.parent,elements:[this]});this.parent.div.append(P.render())}render(){(0,i.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(g,v=null){let P=[];if(this._fieldObjects){let k=this._fieldObjects[g];if(k)for(let{page:O,id:M,exportValues:C}of k){if(O===-1||M===v)continue;let L=typeof C=="string"?C:null,$=document.querySelector(`[data-element-id="${M}"]`);!$||a.has($)?P.push({id:M,exportValue:L,domElement:$}):(0,i.warn)(`_getElementsByName - element not allowed: ${M}`)}return P}for(let k of document.getElementsByName(g)){let{exportValue:O}=k,M=k.getAttribute("data-element-id");M!==v&&a.has(k)&&P.push({id:M,exportValue:O,domElement:k})}return P}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let g=this.getElementsToTriggerPopup();if(Array.isArray(g))for(let v of g)v.classList.add("highlightArea");else g.classList.add("highlightArea")}get _isEditable(){return!1}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:g,data:{id:v}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:g,editId:v})}))}}class p extends E{constructor(g,v=null){super(g,{isRenderable:!0,ignoreBorder:!!v?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=g.data.isTooltipOnly}render(){let{data:g,linkService:v}=this,P=document.createElement("a");P.setAttribute("data-element-id",g.id);let k=!1;return g.url?(v.addLinkAttributes(P,g.url,g.newWindow),k=!0):g.action?(this._bindNamedAction(P,g.action),k=!0):g.attachment?(this.#e(P,g.attachment,g.attachmentDest),k=!0):g.setOCGState?(this.#i(P,g.setOCGState),k=!0):g.dest?(this._bindLink(P,g.dest),k=!0):(g.actions&&(g.actions.Action||g.actions["Mouse Up"]||g.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(P,g),k=!0),g.resetForm?(this._bindResetFormAction(P,g.resetForm),k=!0):this.isTooltipOnly&&!k&&(this._bindLink(P,""),k=!0)),this.container.classList.add("linkAnnotation"),k&&this.container.append(P),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(g,v){g.href=this.linkService.getDestinationHash(v),g.onclick=()=>(v&&this.linkService.goToDestination(v),!1),(v||v==="")&&this.#t()}_bindNamedAction(g,v){g.href=this.linkService.getAnchorUrl(""),g.onclick=()=>(this.linkService.executeNamedAction(v),!1),this.#t()}#e(g,v,P=null){g.href=this.linkService.getAnchorUrl(""),g.onclick=()=>(this.downloadManager?.openOrDownloadData(v.content,v.filename,P),!1),this.#t()}#i(g,v){g.href=this.linkService.getAnchorUrl(""),g.onclick=()=>(this.linkService.executeSetOCGState(v),!1),this.#t()}_bindJSAction(g,v){g.href=this.linkService.getAnchorUrl("");let P=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let k of Object.keys(v.actions)){let O=P.get(k);O&&(g[O]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v.id,name:k}}),!1))}g.onclick||(g.onclick=()=>!1),this.#t()}_bindResetFormAction(g,v){let P=g.onclick;P||(g.href=this.linkService.getAnchorUrl("")),this.#t(),this._fieldObjects?g.onclick=()=>{P?.();let{fields:k,refs:O,include:M}=v,C=[];if(k.length!==0||O.length!==0){let B=new Set(O);for(let D of k){let F=this._fieldObjects[D]||[];for(let{id:V}of F)B.add(V)}for(let D of Object.values(this._fieldObjects))for(let F of D)B.has(F.id)===M&&C.push(F)}else for(let B of Object.values(this._fieldObjects))C.push(...B);let L=this.annotationStorage,$=[];for(let B of C){let{id:D}=B;switch($.push(D),B.type){case"text":{let V=B.defaultValue||"";L.setValue(D,{value:V});break}case"checkbox":case"radiobutton":{let V=B.defaultValue===B.exportValues;L.setValue(D,{value:V});break}case"combobox":case"listbox":{let V=B.defaultValue||"";L.setValue(D,{value:V});break}default:continue}let F=document.querySelector(`[data-element-id="${D}"]`);F&&(a.has(F)?F.dispatchEvent(new Event("resetform")):(0,i.warn)(`_bindResetFormAction - element not allowed: ${D}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:$,name:"ResetForm"}}),!1}:((0,i.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),P||(g.onclick=()=>!1))}}class y extends E{constructor(g){super(g,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let g=document.createElement("img");return g.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",g.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),g.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(g),this.container}}class r extends E{render(){return this.container}showElementAndHideCanvas(g){this.data.hasOwnCanvas&&(g.previousSibling?.nodeName==="CANVAS"&&(g.previousSibling.hidden=!0),g.hidden=!1)}_getKeyModifier(g){return i.FeatureTest.platform.isMac?g.metaKey:g.ctrlKey}_setEventListener(g,v,P,k,O){P.includes("mouse")?g.addEventListener(P,(M=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:k,value:O(M),shift:M.shiftKey,modifier:this._getKeyModifier(M)}})})):g.addEventListener(P,(M=>{if(P==="blur"){if(!v.focused||!M.relatedTarget)return;v.focused=!1}else if(P==="focus"){if(v.focused)return;v.focused=!0}O&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:k,value:O(M)}})}))}_setEventListeners(g,v,P,k){for(let[O,M]of P)(M==="Action"||this.data.actions?.[M])&&(M!=="Focus"&&M!=="Blur"||(v||={focused:!1}),this._setEventListener(g,v,O,M,k),M!=="Focus"||this.data.actions?.Blur?M!=="Blur"||this.data.actions?.Focus||this._setEventListener(g,v,"focus","Focus",null):this._setEventListener(g,v,"blur","Blur",null))}_setBackgroundColor(g){let v=this.data.backgroundColor||null;g.style.backgroundColor=v===null?"transparent":i.Util.makeHexColor(v[0],v[1],v[2])}_setTextStyle(g){let v=["left","center","right"],{fontColor:P}=this.data.defaultAppearanceData,k=this.data.defaultAppearanceData.fontSize||9,O=g.style,M,C=L=>Math.round(10*L)/10;if(this.data.multiLine){let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2),$=L/(Math.round(L/(i.LINE_FACTOR*k))||1);M=Math.min(k,C($/i.LINE_FACTOR))}else{let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2);M=Math.min(k,C(L/i.LINE_FACTOR))}O.fontSize=`calc(${M}px * var(--scale-factor))`,O.color=i.Util.makeHexColor(P[0],P[1],P[2]),this.data.textAlignment!==null&&(O.textAlign=v[this.data.textAlignment])}_setRequired(g,v){v?g.setAttribute("required",!0):g.removeAttribute("required"),g.setAttribute("aria-required",v)}}class d extends r{constructor(g){super(g,{isRenderable:g.renderForms||g.data.hasOwnCanvas||!g.data.hasAppearance&&!!g.data.fieldValue})}setPropertyOnSiblings(g,v,P,k){let O=this.annotationStorage;for(let M of this._getElementsByName(g.name,g.id))M.domElement&&(M.domElement[v]=P),O.setValue(M.id,{[k]:P})}render(){let g=this.annotationStorage,v=this.data.id;this.container.classList.add("textWidgetAnnotation");let P=null;if(this.renderForms){let k=g.getValue(v,{value:this.data.fieldValue}),O=k.value||"",M=g.getValue(v,{charLimit:this.data.maxLen}).charLimit;M&&O.length>M&&(O=O.slice(0,M));let C=k.formattedValue||this.data.textContent?.join(`
|
|
10
|
-
`)||null;C&&this.data.comb&&(C=C.replaceAll(/\s+/g,""));let L={userValue:O,formattedValue:C,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(P=document.createElement("textarea"),P.textContent=C??O,this.data.doNotScroll&&(P.style.overflowY="hidden")):(P=document.createElement("input"),P.type="text",P.setAttribute("value",C??O),this.data.doNotScroll&&(P.style.overflowX="hidden")),this.data.hasOwnCanvas&&(P.hidden=!0),a.add(P),P.setAttribute("data-element-id",v),P.disabled=this.data.readOnly,P.name=this.data.fieldName,P.tabIndex=u,this._setRequired(P,this.data.required),M&&(P.maxLength=M),P.addEventListener("input",(B=>{g.setValue(v,{value:B.target.value}),this.setPropertyOnSiblings(P,"value",B.target.value,"value"),L.formattedValue=null})),P.addEventListener("resetform",(B=>{let D=this.data.defaultFieldValue??"";P.value=L.userValue=D,L.formattedValue=null}));let $=B=>{let{formattedValue:D}=L;D!=null&&(B.target.value=D),B.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){P.addEventListener("focus",(D=>{if(L.focused)return;let{target:F}=D;L.userValue&&(F.value=L.userValue),L.lastCommittedValue=F.value,L.commitKey=1,this.data.actions?.Focus||(L.focused=!0)})),P.addEventListener("updatefromsandbox",(D=>{this.showElementAndHideCanvas(D.target);let F={value(V){L.userValue=V.detail.value??"",g.setValue(v,{value:L.userValue.toString()}),V.target.value=L.userValue},formattedValue(V){let{formattedValue:Q}=V.detail;L.formattedValue=Q,Q!=null&&V.target!==document.activeElement&&(V.target.value=Q),g.setValue(v,{formattedValue:Q})},selRange(V){V.target.setSelectionRange(...V.detail.selRange)},charLimit:V=>{let{charLimit:Q}=V.detail,{target:Z}=V;if(Q===0){Z.removeAttribute("maxLength");return}Z.setAttribute("maxLength",Q);let et=L.userValue;et&&!(et.length<=Q)&&(et=et.slice(0,Q),Z.value=L.userValue=et,g.setValue(v,{value:et}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:et,willCommit:!0,commitKey:1,selStart:Z.selectionStart,selEnd:Z.selectionEnd}}))}};this._dispatchEventFromSandbox(F,D)})),P.addEventListener("keydown",(D=>{L.commitKey=1;let F=-1;if(D.key==="Escape"?F=0:D.key!=="Enter"||this.data.multiLine?D.key==="Tab"&&(L.commitKey=3):F=2,F===-1)return;let{value:V}=D.target;L.lastCommittedValue!==V&&(L.lastCommittedValue=V,L.userValue=V,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:V,willCommit:!0,commitKey:F,selStart:D.target.selectionStart,selEnd:D.target.selectionEnd}}))}));let B=$;$=null,P.addEventListener("blur",(D=>{if(!L.focused||!D.relatedTarget)return;this.data.actions?.Blur||(L.focused=!1);let{value:F}=D.target;L.userValue=F,L.lastCommittedValue!==F&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:F,willCommit:!0,commitKey:L.commitKey,selStart:D.target.selectionStart,selEnd:D.target.selectionEnd}}),B(D)})),this.data.actions?.Keystroke&&P.addEventListener("beforeinput",(D=>{L.lastCommittedValue=null;let{data:F,target:V}=D,{value:Q,selectionStart:Z,selectionEnd:et}=V,rt=Z,pt=et;switch(D.inputType){case"deleteWordBackward":{let dt=Q.substring(0,Z).match(/\w*[^\w]*$/);dt&&(rt-=dt[0].length);break}case"deleteWordForward":{let dt=Q.substring(Z).match(/^[^\w]*\w*/);dt&&(pt+=dt[0].length);break}case"deleteContentBackward":Z===et&&(rt-=1);break;case"deleteContentForward":Z===et&&(pt+=1)}D.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:Q,change:F||"",willCommit:!1,selStart:rt,selEnd:pt}})})),this._setEventListeners(P,L,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(D=>D.target.value))}if($&&P.addEventListener("blur",$),this.data.comb){let B=(this.data.rect[2]-this.data.rect[0])/M;P.classList.add("comb"),P.style.letterSpacing=`calc(${B}px * var(--scale-factor) - 1ch)`}}else P=document.createElement("div"),P.textContent=this.data.fieldValue,P.style.verticalAlign="middle",P.style.display="table-cell",this.data.hasOwnCanvas&&(P.hidden=!0);return this._setTextStyle(P),this._setBackgroundColor(P),this._setDefaultPropertiesFromJS(P),this.container.append(P),this.container}}class b extends r{constructor(g){super(g,{isRenderable:!!g.data.hasOwnCanvas})}}class x extends r{constructor(g){super(g,{isRenderable:g.renderForms})}render(){let g=this.annotationStorage,v=this.data,P=v.id,k=g.getValue(P,{value:v.exportValue===v.fieldValue}).value;typeof k=="string"&&(k=k!=="Off",g.setValue(P,{value:k})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let O=document.createElement("input");return a.add(O),O.setAttribute("data-element-id",P),O.disabled=v.readOnly,this._setRequired(O,this.data.required),O.type="checkbox",O.name=v.fieldName,k&&O.setAttribute("checked",!0),O.setAttribute("exportValue",v.exportValue),O.tabIndex=u,O.addEventListener("change",(M=>{let{name:C,checked:L}=M.target;for(let $ of this._getElementsByName(C,P)){let B=L&&$.exportValue===v.exportValue;$.domElement&&($.domElement.checked=B),g.setValue($.id,{value:B})}g.setValue(P,{value:L})})),O.addEventListener("resetform",(M=>{let C=v.defaultFieldValue||"Off";M.target.checked=C===v.exportValue})),this.enableScripting&&this.hasJSActions&&(O.addEventListener("updatefromsandbox",(M=>{let C={value(L){L.target.checked=L.detail.value!=="Off",g.setValue(P,{value:L.target.checked})}};this._dispatchEventFromSandbox(C,M)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(M=>M.target.checked))),this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class _ extends r{constructor(g){super(g,{isRenderable:g.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let g=this.annotationStorage,v=this.data,P=v.id,k=g.getValue(P,{value:v.fieldValue===v.buttonValue}).value;if(typeof k=="string"&&(k=k!==v.buttonValue,g.setValue(P,{value:k})),k)for(let M of this._getElementsByName(v.fieldName,P))g.setValue(M.id,{value:!1});let O=document.createElement("input");if(a.add(O),O.setAttribute("data-element-id",P),O.disabled=v.readOnly,this._setRequired(O,this.data.required),O.type="radio",O.name=v.fieldName,k&&O.setAttribute("checked",!0),O.tabIndex=u,O.addEventListener("change",(M=>{let{name:C,checked:L}=M.target;for(let $ of this._getElementsByName(C,P))g.setValue($.id,{value:!1});g.setValue(P,{value:L})})),O.addEventListener("resetform",(M=>{let C=v.defaultFieldValue;M.target.checked=C!=null&&C===v.buttonValue})),this.enableScripting&&this.hasJSActions){let M=v.buttonValue;O.addEventListener("updatefromsandbox",(C=>{let L={value:$=>{let B=M===$.detail.value;for(let D of this._getElementsByName($.target.name)){let F=B&&D.id===P;D.domElement&&(D.domElement.checked=F),g.setValue(D.id,{value:F})}}};this._dispatchEventFromSandbox(L,C)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(C=>C.target.checked))}return this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class S extends p{constructor(g){super(g,{ignoreBorder:g.data.hasAppearance})}render(){let g=super.render();g.classList.add("buttonWidgetAnnotation","pushButton");let v=g.lastChild;return this.enableScripting&&this.hasJSActions&&v&&(this._setDefaultPropertiesFromJS(v),v.addEventListener("updatefromsandbox",(P=>{this._dispatchEventFromSandbox({},P)}))),g}}class R extends r{constructor(g){super(g,{isRenderable:g.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let g=this.annotationStorage,v=this.data.id,P=g.getValue(v,{value:this.data.fieldValue}),k=document.createElement("select");a.add(k),k.setAttribute("data-element-id",v),k.disabled=this.data.readOnly,this._setRequired(k,this.data.required),k.name=this.data.fieldName,k.tabIndex=u;let O=this.data.combo&&this.data.options.length>0;this.data.combo||(k.size=this.data.options.length,this.data.multiSelect&&(k.multiple=!0)),k.addEventListener("resetform",(B=>{let D=this.data.defaultFieldValue;for(let F of k.options)F.selected=F.value===D}));for(let B of this.data.options){let D=document.createElement("option");D.textContent=B.displayValue,D.value=B.exportValue,P.value.includes(B.exportValue)&&(D.setAttribute("selected",!0),O=!1),k.append(D)}let M=null;if(O){let B=document.createElement("option");B.value=" ",B.setAttribute("hidden",!0),B.setAttribute("selected",!0),k.prepend(B),M=()=>{B.remove(),k.removeEventListener("input",M),M=null},k.addEventListener("input",M)}let C=B=>{let D=B?"value":"textContent",{options:F,multiple:V}=k;return V?Array.prototype.filter.call(F,(Q=>Q.selected)).map((Q=>Q[D])):F.selectedIndex===-1?null:F[F.selectedIndex][D]},L=C(!1),$=B=>{let D=B.target.options;return Array.prototype.map.call(D,(F=>({displayValue:F.textContent,exportValue:F.value})))};return this.enableScripting&&this.hasJSActions?(k.addEventListener("updatefromsandbox",(B=>{let D={value(F){M?.();let V=F.detail.value,Q=new Set(Array.isArray(V)?V:[V]);for(let Z of k.options)Z.selected=Q.has(Z.value);g.setValue(v,{value:C(!0)}),L=C(!1)},multipleSelection(F){k.multiple=!0},remove(F){let V=k.options,Q=F.detail.remove;V[Q].selected=!1,k.remove(Q),V.length>0&&Array.prototype.findIndex.call(V,(Z=>Z.selected))===-1&&(V[0].selected=!0),g.setValue(v,{value:C(!0),items:$(F)}),L=C(!1)},clear(F){for(;k.length!==0;)k.remove(0);g.setValue(v,{value:null,items:[]}),L=C(!1)},insert(F){let{index:V,displayValue:Q,exportValue:Z}=F.detail.insert,et=k.children[V],rt=document.createElement("option");rt.textContent=Q,rt.value=Z,et?et.before(rt):k.append(rt),g.setValue(v,{value:C(!0),items:$(F)}),L=C(!1)},items(F){let{items:V}=F.detail;for(;k.length!==0;)k.remove(0);for(let Q of V){let{displayValue:Z,exportValue:et}=Q,rt=document.createElement("option");rt.textContent=Z,rt.value=et,k.append(rt)}k.options.length>0&&(k.options[0].selected=!0),g.setValue(v,{value:C(!0),items:$(F)}),L=C(!1)},indices(F){let V=new Set(F.detail.indices);for(let Q of F.target.options)Q.selected=V.has(Q.index);g.setValue(v,{value:C(!0)}),L=C(!1)},editable(F){F.target.disabled=!F.detail.editable}};this._dispatchEventFromSandbox(D,B)})),k.addEventListener("input",(B=>{let D=C(!0);g.setValue(v,{value:D}),B.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:L,changeEx:D,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(k,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(B=>B.target.value))):k.addEventListener("input",(function(B){g.setValue(v,{value:C(!0)})})),this.data.combo&&this._setTextStyle(k),this._setBackgroundColor(k),this._setDefaultPropertiesFromJS(k),this.container.append(k),this.container}}class N extends E{constructor(g){let{data:v,elements:P}=g;super(g,{isRenderable:E._hasPopupData(v)}),this.elements=P}render(){this.container.classList.add("popupAnnotation");let g=new H({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),v=[];for(let P of this.elements)P.popup=g,v.push(P.data.id),P.addHighlightArea();return this.container.setAttribute("aria-controls",v.map((P=>`${i.AnnotationPrefix}${P}`)).join(",")),this.container}}class H{#t=this.#m.bind(this);#e=this.#C.bind(this);#i=this.#S.bind(this);#n=this.#b.bind(this);#r=null;#s=null;#a=null;#l=null;#o=null;#h=null;#u=null;#d=!1;#c=null;#f=null;#g=null;#p=null;#y=!1;constructor({container:g,color:v,elements:P,titleObj:k,modificationDate:O,contentsObj:M,richText:C,parent:L,rect:$,parentRect:B,open:D}){this.#s=g,this.#p=k,this.#a=M,this.#g=C,this.#h=L,this.#r=v,this.#f=$,this.#u=B,this.#o=P,this.#l=n.PDFDateString.toDateObject(O),this.trigger=P.flatMap((F=>F.getElementsToTriggerPopup()));for(let F of this.trigger)F.addEventListener("click",this.#n),F.addEventListener("mouseenter",this.#i),F.addEventListener("mouseleave",this.#e),F.classList.add("popupTriggerArea");for(let F of P)F.container?.addEventListener("keydown",this.#t);this.#s.hidden=!0,D&&this.#b()}render(){if(this.#c)return;let{page:{view:g},viewport:{rawDims:{pageWidth:v,pageHeight:P,pageX:k,pageY:O}}}=this.#h,M=this.#c=document.createElement("div");if(M.className="popup",this.#r){let pt=M.style.outlineColor=i.Util.makeHexColor(...this.#r);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?M.style.backgroundColor=`color-mix(in srgb, ${pt} 30%, white)`:M.style.backgroundColor=i.Util.makeHexColor(...this.#r.map((ct=>Math.floor(.7*(255-ct)+ct))))}let C=document.createElement("span");C.className="header";let L=document.createElement("h1");if(C.append(L),{dir:L.dir,str:L.textContent}=this.#p,M.append(C),this.#l){let pt=document.createElement("span");pt.classList.add("popupDate"),pt.setAttribute("data-l10n-id","pdfjs-annotation-date-string"),pt.setAttribute("data-l10n-args",JSON.stringify({date:this.#l.toLocaleDateString(),time:this.#l.toLocaleTimeString()})),C.append(pt)}let $=this.#a,B=this.#g;if(!B?.str||$?.str&&$.str!==B.str){let pt=this._formatContents($);M.append(pt)}else m.XfaLayer.render({xfaHtml:B.html,intent:"richText",div:M}),M.lastChild.classList.add("richText","popupContent");let D=!!this.#u,F=D?this.#u:this.#f;for(let pt of this.#o)if(!F||i.Util.intersect(pt.data.rect,F)!==null){F=pt.data.rect,D=!0;break}let V=i.Util.normalizeRect([F[0],g[3]-F[1]+g[1],F[2],g[3]-F[3]+g[1]]),Q=D?F[2]-F[0]+5:0,Z=V[0]+Q,et=V[1],{style:rt}=this.#s;rt.left=100*(Z-k)/v+"%",rt.top=100*(et-O)/P+"%",this.#s.append(M)}_formatContents({str:g,dir:v}){let P=document.createElement("p");P.classList.add("popupContent"),P.dir=v;let k=g.split(/(?:\r\n?|\n)/);for(let O=0,M=k.length;O<M;++O){let C=k[O];P.append(document.createTextNode(C)),O<M-1&&P.append(document.createElement("br"))}return P}#m(g){g.altKey||g.shiftKey||g.ctrlKey||g.metaKey||(g.key==="Enter"||g.key==="Escape"&&this.#d)&&this.#b()}#b(){this.#d=!this.#d,this.#d?(this.#S(),this.#s.addEventListener("click",this.#n),this.#s.addEventListener("keydown",this.#t)):(this.#C(),this.#s.removeEventListener("click",this.#n),this.#s.removeEventListener("keydown",this.#t))}#S(){this.#c||this.render(),this.isVisible?this.#d&&this.#s.classList.add("focused"):(this.#s.hidden=!1,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)+1e3)}#C(){this.#s.classList.remove("focused"),!this.#d&&this.isVisible&&(this.#s.hidden=!0,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)-1e3)}forceHide(){this.#y=this.isVisible,this.#y&&(this.#s.hidden=!0)}maybeShow(){this.#y&&(this.#y=!1,this.#s.hidden=!1)}get isVisible(){return this.#s.hidden===!1}}class z extends E{constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0}),this.textContent=g.data.textContent,this.textPosition=g.data.textPosition,this.annotationEditorType=i.AnnotationEditorType.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){let g=document.createElement("div");g.classList.add("annotationTextContent"),g.setAttribute("role","comment");for(let v of this.textContent){let P=document.createElement("span");P.textContent=v,g.append(P)}this.container.append(g)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}get _isEditable(){return this.data.hasOwnCanvas}}class K extends E{#t=null;constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let g=this.data,{width:v,height:P}=f(g.rect),k=this.svgFactory.create(v,P,!0),O=this.#t=this.svgFactory.createElement("svg:line");return O.setAttribute("x1",g.rect[2]-g.lineCoordinates[0]),O.setAttribute("y1",g.rect[3]-g.lineCoordinates[1]),O.setAttribute("x2",g.rect[2]-g.lineCoordinates[2]),O.setAttribute("y2",g.rect[3]-g.lineCoordinates[3]),O.setAttribute("stroke-width",g.borderStyle.width||1),O.setAttribute("stroke","transparent"),O.setAttribute("fill","transparent"),k.append(O),this.container.append(k),!g.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class it extends E{#t=null;constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let g=this.data,{width:v,height:P}=f(g.rect),k=this.svgFactory.create(v,P,!0),O=g.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:rect");return M.setAttribute("x",O/2),M.setAttribute("y",O/2),M.setAttribute("width",v-O),M.setAttribute("height",P-O),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),k.append(M),this.container.append(k),!g.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class at extends E{#t=null;constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let g=this.data,{width:v,height:P}=f(g.rect),k=this.svgFactory.create(v,P,!0),O=g.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:ellipse");return M.setAttribute("cx",v/2),M.setAttribute("cy",P/2),M.setAttribute("rx",v/2-O/2),M.setAttribute("ry",P/2-O/2),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),k.append(M),this.container.append(k),!g.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class X extends E{#t=null;constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);let g=this.data,{width:v,height:P}=f(g.rect),k=this.svgFactory.create(v,P,!0),O=[];for(let C of g.vertices){let L=C.x-g.rect[0],$=g.rect[3]-C.y;O.push(L+","+$)}O=O.join(" ");let M=this.#t=this.svgFactory.createElement(this.svgElementName);return M.setAttribute("points",O),M.setAttribute("stroke-width",g.borderStyle.width||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),k.append(M),this.container.append(k),!g.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class j extends X{constructor(g){super(g),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class W extends E{constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class Y extends E{#t=[];constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=i.AnnotationEditorType.INK}render(){this.container.classList.add(this.containerClassName);let g=this.data,{width:v,height:P}=f(g.rect),k=this.svgFactory.create(v,P,!0);for(let O of g.inkLists){let M=[];for(let L of O){let $=L.x-g.rect[0],B=g.rect[3]-L.y;M.push(`${$},${B}`)}M=M.join(" ");let C=this.svgFactory.createElement(this.svgElementName);this.#t.push(C),C.setAttribute("points",M),C.setAttribute("stroke-width",g.borderStyle.width||1),C.setAttribute("stroke","transparent"),C.setAttribute("fill","transparent"),!g.popupRef&&this.hasPopupData&&this._createPopup(),k.append(C)}return this.container.append(k),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class tt extends E{constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this.container}}class st extends E{constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class lt extends E{constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class nt extends E{constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class G extends E{constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class A extends E{#t=null;constructor(g){super(g,{isRenderable:!0});let{filename:v,content:P}=this.data.file;this.filename=(0,n.getFilenameFromUrl)(v,!0),this.content=P,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,filename:v,content:P})}render(){this.container.classList.add("fileAttachmentAnnotation");let{container:g,data:v}=this,P;v.hasAppearance||v.fillAlpha===0?P=document.createElement("div"):(P=document.createElement("img"),P.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(v.name)?"paperclip":"pushpin"}.svg`,v.fillAlpha&&v.fillAlpha<1&&(P.style=`filter: opacity(${Math.round(100*v.fillAlpha)}%);`)),P.addEventListener("dblclick",this.#e.bind(this)),this.#t=P;let{isMac:k}=i.FeatureTest.platform;return g.addEventListener("keydown",(O=>{O.key==="Enter"&&(k?O.metaKey:O.ctrlKey)&&this.#e()})),!v.popupRef&&this.hasPopupData?this._createPopup():P.classList.add("popupTriggerArea"),g.append(P),g}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class T{#t=null;#e=null;#i=new Map;constructor({div:g,accessibilityManager:v,annotationCanvasMap:P,page:k,viewport:O}){this.div=g,this.#t=v,this.#e=P,this.page=k,this.viewport=O,this.zIndex=0}#n(g,v){let P=g.firstChild||g;P.id=`${i.AnnotationPrefix}${v}`,this.div.append(g),this.#t?.moveElementInDOM(this.div,g,P,!1)}async render(g){let{annotations:v}=g,P=this.div;(0,n.setLayerDimensions)(P,this.viewport);let k=new Map,O={data:null,layer:P,linkService:g.linkService,downloadManager:g.downloadManager,imageResourcesPath:g.imageResourcesPath||"",renderForms:g.renderForms!==!1,svgFactory:new n.DOMSVGFactory,annotationStorage:g.annotationStorage||new o.AnnotationStorage,enableScripting:g.enableScripting===!0,hasJSActions:g.hasJSActions,fieldObjects:g.fieldObjects,parent:this,elements:null};for(let M of v){if(M.noHTML)continue;let C=M.annotationType===i.AnnotationType.POPUP;if(C){let B=k.get(M.id);if(!B)continue;O.elements=B}else{let{width:B,height:D}=f(M.rect);if(B<=0||D<=0)continue}O.data=M;let L=w.create(O);if(!L.isRenderable)continue;if(!C&&M.popupRef){let B=k.get(M.popupRef);B?B.push(L):k.set(M.popupRef,[L])}L.annotationEditorType>0&&this.#i.set(L.data.id,L);let $=L.render();M.hidden&&($.style.visibility="hidden"),this.#n($,M.id)}this.#r()}update({viewport:g}){let v=this.div;this.viewport=g,(0,n.setLayerDimensions)(v,{rotation:g.rotation}),this.#r(),v.hidden=!1}#r(){if(!this.#e)return;let g=this.div;for(let[v,P]of this.#e){let k=g.querySelector(`[data-annotation-id="${v}"]`);if(!k)continue;let{firstChild:O}=k;O?O.nodeName==="CANVAS"?O.replaceWith(P):O.before(P):k.append(P)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#i.values())}getEditableAnnotation(g){return this.#i.get(g)}}},792:(s,t,e)=>{e.d(t,{AnnotationStorage:()=>l,PrintAnnotationStorage:()=>h,SerializableEmpty:()=>c});var i=e(292),n=e(310),o=e(651);let c=Object.freeze({map:null,hash:"",transfer:void 0});class l{#t=!1;#e=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(u,a){let f=this.#e.get(u);return f===void 0?a:Object.assign(a,f)}getRawValue(u){return this.#e.get(u)}remove(u){if(this.#e.delete(u),this.#e.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(let a of this.#e.values())if(a instanceof n.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(u,a){let f=this.#e.get(u),w=!1;if(f!==void 0)for(let[E,p]of Object.entries(a))f[E]!==p&&(w=!0,f[E]=p);else w=!0,this.#e.set(u,a);w&&this.#i(),a instanceof n.AnnotationEditor&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(a.constructor._type)}has(u){return this.#e.has(u)}getAll(){return this.#e.size>0?(0,i.objectFromMap)(this.#e):null}setAll(u){for(let[a,f]of Object.entries(u))this.setValue(a,f)}get size(){return this.#e.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new h(this)}get serializable(){if(this.#e.size===0)return c;let u=new Map,a=new o.MurmurHash3_64,f=[],w=Object.create(null),E=!1;for(let[p,y]of this.#e){let r=y instanceof n.AnnotationEditor?y.serialize(!1,w):y;r&&(u.set(p,r),a.update(`${p}:${JSON.stringify(r)}`),E||=!!r.bitmap)}if(E)for(let p of u.values())p.bitmap&&f.push(p.bitmap);return u.size>0?{map:u,hash:a.hexdigest(),transfer:f}:c}get editorStats(){let u=null,a=new Map;for(let f of this.#e.values()){if(!(f instanceof n.AnnotationEditor))continue;let w=f.telemetryFinalData;if(!w)continue;let{type:E}=w;a.has(E)||a.set(E,Object.getPrototypeOf(f).constructor),u||=Object.create(null);let p=u[E]||=new Map;for(let[y,r]of Object.entries(w)){if(y==="type")continue;let d=p.get(y);d||(d=new Map,p.set(y,d));let b=d.get(r)??0;d.set(r,b+1)}}for(let[f,w]of a)u[f]=w.computeTelemetryFinalData(u[f]);return u}}class h extends l{#t;constructor(u){super();let{map:a,hash:f,transfer:w}=u.serializable,E=structuredClone(a,w?{transfer:w}:null);this.#t={map:E,hash:f,transfer:w}}get print(){(0,i.unreachable)("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}}},831:(s,t,e)=>{e.a(s,(async(i,n)=>{try{let at=function(M){if(typeof M=="string"||M instanceof URL?M={url:M}:(M instanceof ArrayBuffer||ArrayBuffer.isView(M))&&(M={data:M}),typeof M!="object")throw new Error("Invalid parameter in getDocument, need parameter object.");if(!M.url&&!M.data&&!M.range)throw new Error("Invalid parameter object: need either .data, .range or .url");let C=new Y,{docId:L}=C,$=M.url?j(M.url):null,B=M.data?W(M.data):null,D=M.httpHeaders||null,F=M.withCredentials===!0,V=M.password??null,Q=M.range instanceof tt?M.range:null,Z=Number.isInteger(M.rangeChunkSize)&&M.rangeChunkSize>0?M.rangeChunkSize:S,et=M.worker instanceof A?M.worker:null,rt=M.verbosity,pt=typeof M.docBaseUrl!="string"||(0,l.isDataScheme)(M.docBaseUrl)?null:M.docBaseUrl,dt=typeof M.cMapUrl=="string"?M.cMapUrl:null,ct=M.cMapPacked!==!1,wt=M.CMapReaderFactory||z,Pt=typeof M.standardFontDataUrl=="string"?M.standardFontDataUrl:null,xt=M.StandardFontDataFactory||it,Dt=M.stopAtErrors!==!0,Lt=Number.isInteger(M.maxImageSize)&&M.maxImageSize>-1?M.maxImageSize:-1,Ut=M.isEvalSupported!==!1,jt=typeof M.isOffscreenCanvasSupported=="boolean"?M.isOffscreenCanvasSupported:!o.isNodeJS,he=Number.isInteger(M.canvasMaxAreaInBytes)?M.canvasMaxAreaInBytes:-1,Se=typeof M.disableFontFace=="boolean"?M.disableFontFace:o.isNodeJS,$e=M.fontExtraProperties===!0,Pe=M.enableXfa===!0,Ie=M.ownerDocument||globalThis.document,bi=M.disableRange===!0,yi=M.disableStream===!0,le=M.disableAutoFetch===!0,oe=M.pdfBug===!0,vi=Q?Q.length:M.length??NaN,_s=typeof M.useSystemFonts=="boolean"?M.useSystemFonts:!o.isNodeJS&&!Se,Le=typeof M.useWorkerFetch=="boolean"?M.useWorkerFetch:wt===l.DOMCMapReaderFactory&&xt===l.DOMStandardFontDataFactory&&dt&&Pt&&(0,l.isValidFetchUrl)(dt,document.baseURI)&&(0,l.isValidFetchUrl)(Pt,document.baseURI),ne=M.canvasFactory||new H({ownerDocument:Ie}),fr=M.filterFactory||new K({docId:L,ownerDocument:Ie});(0,o.setVerbosityLevel)(rt);let Ts={canvasFactory:ne,filterFactory:fr};if(Le||(Ts.cMapReaderFactory=new wt({baseUrl:dt,isCompressed:ct}),Ts.standardFontDataFactory=new xt({baseUrl:Pt})),!et){let He={verbosity:rt,port:f.GlobalWorkerOptions.workerPort};et=He.port?A.fromPort(He):new A(He),C._worker=et}let Ue={docId:L,apiVersion:"4.1.392",data:B,password:V,disableAutoFetch:le,rangeChunkSize:Z,length:vi,docBaseUrl:pt,enableXfa:Pe,evaluatorOptions:{maxImageSize:Lt,disableFontFace:Se,ignoreErrors:Dt,isEvalSupported:Ut,isOffscreenCanvasSupported:jt,canvasMaxAreaInBytes:he,fontExtraProperties:$e,useSystemFonts:_s,cMapUrl:Le?dt:null,standardFontDataUrl:Le?Pt:null}},Wi={ignoreErrors:Dt,isEvalSupported:Ut,disableFontFace:Se,fontExtraProperties:$e,enableXfa:Pe,ownerDocument:Ie,disableAutoFetch:le,pdfBug:oe,styleElement:null};return et.promise.then((function(){if(C.destroyed)throw new Error("Loading aborted");let He=X(et,Ue),gr=new Promise((function(Ps){let wi;Q?wi=new y.PDFDataTransportStream(Q,{disableRange:bi,disableStream:yi}):B||(wi=(fe=>o.isNodeJS?(function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype})()&&(0,l.isValidFetchUrl)(fe.url)?new r.PDFFetchStream(fe):new b.PDFNodeStream(fe):(0,l.isValidFetchUrl)(fe.url)?new r.PDFFetchStream(fe):new d.PDFNetworkStream(fe))({url:$,length:vi,httpHeaders:D,withCredentials:F,rangeChunkSize:Z,disableRange:bi,disableStream:yi})),Ps(wi)}));return Promise.all([He,gr]).then((function([Ps,wi]){if(C.destroyed)throw new Error("Loading aborted");let fe=new w.MessageHandler(L,Ps,et.port),mr=new T(fe,C,wi,Wi,Ts);C._transport=mr,fe.send("Ready",null)}))})).catch(C._capability.reject),C},j=function(M){if(M instanceof URL)return M.href;try{return new URL(M,window.location).href}catch{if(o.isNodeJS&&typeof M=="string")return M}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")},W=function(M){if(o.isNodeJS&&typeof Buffer<"u"&&M instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(M instanceof Uint8Array&&M.byteLength===M.buffer.byteLength)return M;if(typeof M=="string")return(0,o.stringToBytes)(M);if(M instanceof ArrayBuffer||ArrayBuffer.isView(M)||typeof M=="object"&&!isNaN(M?.length))return new Uint8Array(M);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")};e.d(t,{PDFDataRangeTransport:()=>tt,PDFWorker:()=>A,build:()=>O,getDocument:()=>at,version:()=>k});var o=e(292),c=e(792),l=e(419),h=e(10),m=e(573),u=e(923),a=e(814),f=e(164),w=e(178),E=e(62),p=e(626),y=e(585),r=e(94),d=e(457),b=e(786),x=e(50),_=i([m,b]);[m,b]=_.then?(await _)():_;let S=65536,R=100,N=5e3,H=o.isNodeJS?m.NodeCanvasFactory:l.DOMCanvasFactory,z=o.isNodeJS?m.NodeCMapReaderFactory:l.DOMCMapReaderFactory,K=o.isNodeJS?m.NodeFilterFactory:l.DOMFilterFactory,it=o.isNodeJS?m.NodeStandardFontDataFactory:l.DOMStandardFontDataFactory;async function X(M,C){if(M.destroyed)throw new Error("Worker was destroyed");let L=await M.messageHandler.sendWithPromise("GetDocRequest",C,C.data?[C.data.buffer]:null);if(M.destroyed)throw new Error("Worker was destroyed");return L}class Y{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+Y.#t++,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(C){throw this._worker?.port&&delete this._worker._pendingDestroy,C}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class tt{constructor(C,L,$=!1,B=null){this.length=C,this.initialData=L,this.progressiveDone=$,this.contentDispositionFilename=B,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(C){this._rangeListeners.push(C)}addProgressListener(C){this._progressListeners.push(C)}addProgressiveReadListener(C){this._progressiveReadListeners.push(C)}addProgressiveDoneListener(C){this._progressiveDoneListeners.push(C)}onDataRange(C,L){for(let $ of this._rangeListeners)$(C,L)}onDataProgress(C,L){this._readyCapability.promise.then((()=>{for(let $ of this._progressListeners)$(C,L)}))}onDataProgressiveRead(C){this._readyCapability.promise.then((()=>{for(let L of this._progressiveReadListeners)L(C)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(let C of this._progressiveDoneListeners)C()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(C,L){(0,o.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class st{constructor(C,L){this._pdfInfo=C,this._transport=L}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return(0,o.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(C){return this._transport.getPage(C)}getPageIndex(C){return this._transport.getPageIndex(C)}getDestinations(){return this._transport.getDestinations()}getDestination(C){return this._transport.getDestination(C)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:C="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(C);return this._transport.getOptionalContentConfig(L)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(C=!1){return this._transport.startCleanup(C||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class lt{#t=null;#e=!1;constructor(C,L,$,B=!1){this._pageIndex=C,this._pageInfo=L,this._transport=$,this._stats=B?new l.StatTimer:null,this._pdfBug=B,this.commonObjs=$.commonObjs,this.objs=new g,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:C,rotation:L=this.rotate,offsetX:$=0,offsetY:B=0,dontFlip:D=!1}={}){return new l.PageViewport({viewBox:this.view,scale:C,rotation:L,offsetX:$,offsetY:B,dontFlip:D})}getAnnotations({intent:C="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(C);return this._transport.getAnnotations(this._pageIndex,L)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return(0,o.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:C,viewport:L,intent:$="display",annotationMode:B=o.AnnotationMode.ENABLE,transform:D=null,background:F=null,optionalContentConfigPromise:V=null,annotationCanvasMap:Q=null,pageColors:Z=null,printAnnotationStorage:et=null}){this._stats?.time("Overall");let rt=this._transport.getRenderingIntent($,B,et),{renderingIntent:pt,cacheKey:dt}=rt;this.#e=!1,this.#n(),V||=this._transport.getOptionalContentConfig(pt);let ct=this._intentStates.get(dt);ct||(ct=Object.create(null),this._intentStates.set(dt,ct)),ct.streamReaderCancelTimeout&&(clearTimeout(ct.streamReaderCancelTimeout),ct.streamReaderCancelTimeout=null);let wt=!!(pt&o.RenderingIntentFlag.PRINT);ct.displayReadyCapability||(ct.displayReadyCapability=Promise.withResolvers(),ct.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(rt));let Pt=Lt=>{ct.renderTasks.delete(xt),(this._maybeCleanupAfterRender||wt)&&(this.#e=!0),this.#i(!wt),Lt?(xt.capability.reject(Lt),this._abortOperatorList({intentState:ct,reason:Lt instanceof Error?Lt:new Error(Lt)})):xt.capability.resolve(),this._stats?.timeEnd("Rendering"),this._stats?.timeEnd("Overall")},xt=new P({callback:Pt,params:{canvasContext:C,viewport:L,transform:D,background:F},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:Q,operatorList:ct.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!wt,pdfBug:this._pdfBug,pageColors:Z});(ct.renderTasks||=new Set).add(xt);let Dt=xt.task;return Promise.all([ct.displayReadyCapability.promise,V]).then((([Lt,Ut])=>{if(this.destroyed)Pt();else{if(this._stats?.time("Rendering"),!(Ut.renderingIntent&pt))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");xt.initializeGraphics({transparency:Lt,optionalContentConfig:Ut}),xt.operatorListChanged()}})).catch(Pt),Dt}getOperatorList({intent:C="display",annotationMode:L=o.AnnotationMode.ENABLE,printAnnotationStorage:$=null}={}){let B=this._transport.getRenderingIntent(C,L,$,!0),D,F=this._intentStates.get(B.cacheKey);return F||(F=Object.create(null),this._intentStates.set(B.cacheKey,F)),F.opListReadCapability||(D=Object.create(null),D.operatorListChanged=function(){F.operatorList.lastChunk&&(F.opListReadCapability.resolve(F.operatorList),F.renderTasks.delete(D))},F.opListReadCapability=Promise.withResolvers(),(F.renderTasks||=new Set).add(D),F.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(B)),F.opListReadCapability.promise}streamTextContent({includeMarkedContent:C=!1,disableNormalization:L=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:C===!0,disableNormalization:L===!0},{highWaterMark:100,size:$=>$.items.length})}getTextContent(C={}){if(this._transport._htmlForXfa)return this.getXfa().then(($=>x.XfaText.textContent($)));let L=this.streamTextContent(C);return new Promise((function($,B){let D=L.getReader(),F={items:[],styles:Object.create(null)};(function V(){D.read().then((function({value:Q,done:Z}){Z?$(F):(Object.assign(F.styles,Q.styles),F.items.push(...Q.items),V())}),B)})()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let C=[];for(let L of this._intentStates.values())if(this._abortOperatorList({intentState:L,reason:new Error("Page was destroyed."),force:!0}),!L.opListReadCapability)for(let $ of L.renderTasks)C.push($.completed),$.cancel();return this.objs.clear(),this.#e=!1,this.#n(),Promise.all(C)}cleanup(C=!1){this.#e=!0;let L=this.#i(!1);return C&&L&&(this._stats&&=new l.StatTimer),L}#i(C=!1){if(this.#n(),!this.#e||this.destroyed)return!1;if(C)return this.#t=setTimeout((()=>{this.#t=null,this.#i(!1)}),N),!1;for(let{renderTasks:L,operatorList:$}of this._intentStates.values())if(L.size>0||!$.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#n(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(C,L){let $=this._intentStates.get(L);$&&(this._stats?.timeEnd("Page Request"),$.displayReadyCapability?.resolve(C))}_renderPageChunk(C,L){for(let $=0,B=C.length;$<B;$++)L.operatorList.fnArray.push(C.fnArray[$]),L.operatorList.argsArray.push(C.argsArray[$]);L.operatorList.lastChunk=C.lastChunk,L.operatorList.separateAnnots=C.separateAnnots;for(let $ of L.renderTasks)$.operatorListChanged();C.lastChunk&&this.#i(!0)}_pumpOperatorList({renderingIntent:C,cacheKey:L,annotationStorageSerializable:$}){let{map:B,transfer:D}=$,F=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:C,cacheKey:L,annotationStorage:B},D).getReader(),V=this._intentStates.get(L);V.streamReader=F;let Q=()=>{F.read().then((({value:Z,done:et})=>{et?V.streamReader=null:this._transport.destroyed||(this._renderPageChunk(Z,V),Q())}),(Z=>{if(V.streamReader=null,!this._transport.destroyed){if(V.operatorList){V.operatorList.lastChunk=!0;for(let et of V.renderTasks)et.operatorListChanged();this.#i(!0)}if(V.displayReadyCapability)V.displayReadyCapability.reject(Z);else{if(!V.opListReadCapability)throw Z;V.opListReadCapability.reject(Z)}}}))};Q()}_abortOperatorList({intentState:C,reason:L,force:$=!1}){if(C.streamReader){if(C.streamReaderCancelTimeout&&(clearTimeout(C.streamReaderCancelTimeout),C.streamReaderCancelTimeout=null),!$){if(C.renderTasks.size>0)return;if(L instanceof l.RenderingCancelledException){let B=R;L.extraDelay>0&&L.extraDelay<1e3&&(B+=L.extraDelay),C.streamReaderCancelTimeout=setTimeout((()=>{C.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:C,reason:L,force:!0})}),B);return}}if(C.streamReader.cancel(new o.AbortException(L.message)).catch((()=>{})),C.streamReader=null,!this._transport.destroyed){for(let[B,D]of this._intentStates)if(D===C){this._intentStates.delete(B);break}this.cleanup()}}}get stats(){return this._stats}}class nt{#t=new Set;#e=Promise.resolve();postMessage(C,L){let $={data:structuredClone(C,L?{transfer:L}:null)};this.#e.then((()=>{for(let B of this.#t)B.call(this,$)}))}addEventListener(C,L){this.#t.add(L)}removeEventListener(C,L){this.#t.delete(L)}terminate(){this.#t.clear()}}let G={isWorkerDisabled:!1,fakeWorkerId:0};o.isNodeJS&&(G.isWorkerDisabled=!0,f.GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"),G.isSameOrigin=function(M,C){let L;try{if(L=new URL(M),!L.origin||L.origin==="null")return!1}catch{return!1}let $=new URL(C,L);return L.origin===$.origin},G.createCDNWrapper=function(M){let C=`await import("${M}");`;return URL.createObjectURL(new Blob([C],{type:"text/javascript"}))};class A{static#t;constructor({name:C=null,port:L=null,verbosity:$=(0,o.getVerbosityLevel)()}={}){if(this.name=C,this.destroyed=!1,this.verbosity=$,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,L){if(A.#t?.has(L))throw new Error("Cannot use more than one PDFWorker per port.");(A.#t||=new WeakMap).set(L,this),this._initializeFromPort(L)}else this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(C){this._port=C,this._messageHandler=new w.MessageHandler("main","worker",C),this._messageHandler.on("ready",(function(){})),this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!G.isWorkerDisabled&&!A.#e){let{workerSrc:C}=A;try{G.isSameOrigin(window.location.href,C)||(C=G.createCDNWrapper(new URL(C,window.location).href));let L=new Worker(C,{type:"module"}),$=new w.MessageHandler("main","worker",L),B=()=>{L.removeEventListener("error",D),$.destroy(),L.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},D=()=>{this._webWorker||B()};L.addEventListener("error",D),$.on("test",(V=>{L.removeEventListener("error",D),this.destroyed?B():V?(this._messageHandler=$,this._port=L,this._webWorker=L,this._readyCapability.resolve(),$.send("configure",{verbosity:this.verbosity})):(this._setupFakeWorker(),$.destroy(),L.terminate())})),$.on("ready",(V=>{if(L.removeEventListener("error",D),this.destroyed)B();else try{F()}catch{this._setupFakeWorker()}}));let F=()=>{let V=new Uint8Array;$.send("test",V,[V.buffer])};F();return}catch{(0,o.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){G.isWorkerDisabled||((0,o.warn)("Setting up fake worker."),G.isWorkerDisabled=!0),A._setupFakeWorkerGlobal.then((C=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}let L=new nt;this._port=L;let $="fake"+G.fakeWorkerId++,B=new w.MessageHandler($+"_worker",$,L);C.setup(B,L);let D=new w.MessageHandler($,$+"_worker",L);this._messageHandler=D,this._readyCapability.resolve(),D.send("configure",{verbosity:this.verbosity})})).catch((C=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${C.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),A.#t?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(C){if(!C?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");let L=this.#t?.get(C.port);if(L){if(L._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return L}return new A(C)}static get workerSrc(){if(f.GlobalWorkerOptions.workerSrc)return f.GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#e(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return(0,o.shadow)(this,"_setupFakeWorkerGlobal",(async()=>this.#e?this.#e:(await import(this.workerSrc)).WorkerMessageHandler)())}}class T{#t=new Map;#e=new Map;#i=new Map;#n=null;constructor(C,L,$,B,D){this.messageHandler=C,this.loadingTask=L,this.commonObjs=new g,this.fontLoader=new h.FontLoader({ownerDocument:B.ownerDocument,styleElement:B.styleElement}),this._params=B,this.canvasFactory=D.canvasFactory,this.filterFactory=D.filterFactory,this.cMapReaderFactory=D.cMapReaderFactory,this.standardFontDataFactory=D.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=$,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#r(C,L=null){let $=this.#t.get(C);if($)return $;let B=this.messageHandler.sendWithPromise(C,L);return this.#t.set(C,B),B}get annotationStorage(){return(0,o.shadow)(this,"annotationStorage",new c.AnnotationStorage)}getRenderingIntent(C,L=o.AnnotationMode.ENABLE,$=null,B=!1){let D=o.RenderingIntentFlag.DISPLAY,F=c.SerializableEmpty;switch(C){case"any":D=o.RenderingIntentFlag.ANY;break;case"display":break;case"print":D=o.RenderingIntentFlag.PRINT;break;default:(0,o.warn)(`getRenderingIntent - invalid intent: ${C}`)}switch(L){case o.AnnotationMode.DISABLE:D+=o.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case o.AnnotationMode.ENABLE:break;case o.AnnotationMode.ENABLE_FORMS:D+=o.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case o.AnnotationMode.ENABLE_STORAGE:D+=o.RenderingIntentFlag.ANNOTATIONS_STORAGE,F=(D&o.RenderingIntentFlag.PRINT&&$ instanceof c.PrintAnnotationStorage?$:this.annotationStorage).serializable;break;default:(0,o.warn)(`getRenderingIntent - invalid annotationMode: ${L}`)}return B&&(D+=o.RenderingIntentFlag.OPLIST),{renderingIntent:D,cacheKey:`${D}_${F.hash}`,annotationStorageSerializable:F}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#n?.reject(new Error("Worker was destroyed during onPassword callback"));let C=[];for(let $ of this.#e.values())C.push($._destroy());this.#e.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let L=this.messageHandler.sendWithPromise("Terminate",null);return C.push(L),Promise.all(C).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),(0,a.cleanupTextLayer)(),this._networkStream?.cancelAllRequests(new o.AbortException("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:C,loadingTask:L}=this;C.on("GetReader",(($,B)=>{(0,o.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=D=>{this._lastProgress={loaded:D.loaded,total:D.total}},B.onPull=()=>{this._fullReader.read().then((function({value:D,done:F}){F?B.close():((0,o.assert)(D instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),B.enqueue(new Uint8Array(D),1,[D]))})).catch((D=>{B.error(D)}))},B.onCancel=D=>{this._fullReader.cancel(D),B.ready.catch((F=>{if(!this.destroyed)throw F}))}})),C.on("ReaderHeadersReady",($=>{let B=Promise.withResolvers(),D=this._fullReader;return D.headersReady.then((()=>{(!D.isStreamingSupported||!D.isRangeSupported)&&(this._lastProgress&&L.onProgress?.(this._lastProgress),D.onProgress=F=>{L.onProgress?.({loaded:F.loaded,total:F.total})}),B.resolve({isStreamingSupported:D.isStreamingSupported,isRangeSupported:D.isRangeSupported,contentLength:D.contentLength})}),B.reject),B.promise})),C.on("GetRangeReader",(($,B)=>{(0,o.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let D=this._networkStream.getRangeReader($.begin,$.end);D?(B.onPull=()=>{D.read().then((function({value:F,done:V}){V?B.close():((0,o.assert)(F instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),B.enqueue(new Uint8Array(F),1,[F]))})).catch((F=>{B.error(F)}))},B.onCancel=F=>{D.cancel(F),B.ready.catch((V=>{if(!this.destroyed)throw V}))}):B.close()})),C.on("GetDoc",(({pdfInfo:$})=>{this._numPages=$.numPages,this._htmlForXfa=$.htmlForXfa,delete $.htmlForXfa,L._capability.resolve(new st($,this))})),C.on("DocException",(function($){let B;switch($.name){case"PasswordException":B=new o.PasswordException($.message,$.code);break;case"InvalidPDFException":B=new o.InvalidPDFException($.message);break;case"MissingPDFException":B=new o.MissingPDFException($.message);break;case"UnexpectedResponseException":B=new o.UnexpectedResponseException($.message,$.status);break;case"UnknownErrorException":B=new o.UnknownErrorException($.message,$.details);break;default:(0,o.unreachable)("DocException - expected a valid Error.")}L._capability.reject(B)})),C.on("PasswordRequest",($=>{if(this.#n=Promise.withResolvers(),L.onPassword){let B=D=>{D instanceof Error?this.#n.reject(D):this.#n.resolve({password:D})};try{L.onPassword(B,$.code)}catch(D){this.#n.reject(D)}}else this.#n.reject(new o.PasswordException($.message,$.code));return this.#n.promise})),C.on("DataLoaded",($=>{L.onProgress?.({loaded:$.length,total:$.length}),this.downloadInfoCapability.resolve($)})),C.on("StartRenderPage",($=>{this.destroyed||this.#e.get($.pageIndex)._startRenderPage($.transparency,$.cacheKey)})),C.on("commonobj",(([$,B,D])=>{if(this.destroyed||this.commonObjs.has($))return null;switch(B){case"Font":let F=this._params;if("error"in D){let et=D.error;(0,o.warn)(`Error during font loading: ${et}`),this.commonObjs.resolve($,et);break}let V=F.pdfBug&&globalThis.FontInspector?.enabled?(et,rt)=>globalThis.FontInspector.fontAdded(et,rt):null,Q=new h.FontFaceObject(D,{isEvalSupported:F.isEvalSupported,disableFontFace:F.disableFontFace,ignoreErrors:F.ignoreErrors,inspectFont:V});this.fontLoader.bind(Q).catch((()=>C.sendWithPromise("FontFallback",{id:$}))).finally((()=>{!F.fontExtraProperties&&Q.data&&(Q.data=null),this.commonObjs.resolve($,Q)}));break;case"CopyLocalImage":let{imageRef:Z}=D;(0,o.assert)(Z,"The imageRef must be defined.");for(let et of this.#e.values())for(let[,rt]of et.objs)if(rt.ref===Z)return rt.dataLen?(this.commonObjs.resolve($,structuredClone(rt)),rt.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve($,D);break;default:throw new Error(`Got unknown common object type ${B}`)}return null})),C.on("obj",(([$,B,D,F])=>{if(this.destroyed)return;let V=this.#e.get(B);if(!V.objs.has($))if(V._intentStates.size!==0)switch(D){case"Image":V.objs.resolve($,F),F?.dataLen>o.MAX_IMAGE_SIZE_TO_CACHE&&(V._maybeCleanupAfterRender=!0);break;case"Pattern":V.objs.resolve($,F);break;default:throw new Error(`Got unknown object type ${D}`)}else F?.bitmap?.close()})),C.on("DocProgress",($=>{this.destroyed||L.onProgress?.({loaded:$.loaded,total:$.total})})),C.on("FetchBuiltInCMap",($=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch($):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")))),C.on("FetchStandardFontData",($=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch($):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&(0,o.warn)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:C,transfer:L}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:C,filename:this._fullReader?.filename??null},L).finally((()=>{this.annotationStorage.resetModified()}))}getPage(C){if(!Number.isInteger(C)||C<=0||C>this._numPages)return Promise.reject(new Error("Invalid page request."));let L=C-1,$=this.#i.get(L);if($)return $;let B=this.messageHandler.sendWithPromise("GetPage",{pageIndex:L}).then((D=>{if(this.destroyed)throw new Error("Transport destroyed");let F=new lt(L,D,this,this._params.pdfBug);return this.#e.set(L,F),F}));return this.#i.set(L,B),B}getPageIndex(C){return typeof C!="object"||C===null||!Number.isInteger(C.num)||C.num<0||!Number.isInteger(C.gen)||C.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:C.num,gen:C.gen})}getAnnotations(C,L){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:C,intent:L})}getFieldObjects(){return this.#r("GetFieldObjects")}hasJSActions(){return this.#r("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(C){return typeof C!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:C})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#r("GetDocJSActions")}getPageJSActions(C){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:C})}getStructTree(C){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:C})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(C){return this.#r("GetOptionalContentConfig").then((L=>new p.OptionalContentConfig(L,C)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let C="GetMetadata",L=this.#t.get(C);if(L)return L;let $=this.messageHandler.sendWithPromise(C,null).then((B=>({info:B[0],metadata:B[1]?new E.Metadata(B[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#t.set(C,$),$}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(C=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(let L of this.#e.values())if(!L.cleanup())throw new Error(`startCleanup: Page ${L.pageNumber} is currently rendering.`);this.commonObjs.clear(),C||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),(0,a.cleanupTextLayer)()}}get loadingParams(){let{disableAutoFetch:C,enableXfa:L}=this._params;return(0,o.shadow)(this,"loadingParams",{disableAutoFetch:C,enableXfa:L})}}let I=Symbol("INITIAL_DATA");class g{#t=Object.create(null);#e(C){return this.#t[C]||={...Promise.withResolvers(),data:I}}get(C,L=null){if(L){let B=this.#e(C);return B.promise.then((()=>L(B.data))),null}let $=this.#t[C];if(!$||$.data===I)throw new Error(`Requesting object that isn't resolved yet ${C}.`);return $.data}has(C){let L=this.#t[C];return!!L&&L.data!==I}resolve(C,L=null){let $=this.#e(C);$.data=L,$.resolve()}clear(){for(let C in this.#t){let{data:L}=this.#t[C];L?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(let C in this.#t){let{data:L}=this.#t[C];L!==I&&(yield[C,L])}}}class v{#t=null;constructor(C){this.#t=C,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(C=0){this.#t.cancel(null,C)}get separateAnnots(){let{separateAnnots:C}=this.#t.operatorList;if(!C)return!1;let{annotationCanvasMap:L}=this.#t;return C.form||C.canvas&&L?.size>0}}class P{static#t=new WeakSet;constructor({callback:C,params:L,objs:$,commonObjs:B,annotationCanvasMap:D,operatorList:F,pageIndex:V,canvasFactory:Q,filterFactory:Z,useRequestAnimationFrame:et=!1,pdfBug:rt=!1,pageColors:pt=null}){this.callback=C,this.params=L,this.objs=$,this.commonObjs=B,this.annotationCanvasMap=D,this.operatorListIdx=null,this.operatorList=F,this._pageIndex=V,this.canvasFactory=Q,this.filterFactory=Z,this._pdfBug=rt,this.pageColors=pt,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=et===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new v(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=L.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:C=!1,optionalContentConfig:L}){if(this.cancelled)return;if(this._canvas){if(P.#t.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");P.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:$,viewport:B,transform:D,background:F}=this.params;this.gfx=new u.CanvasGraphics($,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:L},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:D,viewport:B,transparency:C,background:F}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(C=null,L=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),P.#t.delete(this._canvas),this.callback(C||new l.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,L))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?window.requestAnimationFrame((()=>{this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),P.#t.delete(this._canvas),this.callback())))}}let k="4.1.392",O="fcb76a78d";n()}catch(S){n(S)}}))},583:(s,t,e)=>{e.d(t,{BaseCMapReaderFactory:()=>c,BaseCanvasFactory:()=>o,BaseFilterFactory:()=>n,BaseSVGFactory:()=>h,BaseStandardFontDataFactory:()=>l});var i=e(292);class n{constructor(){this.constructor===n&&(0,i.unreachable)("Cannot initialize BaseFilterFactory.")}addFilter(u){return"none"}addHCMFilter(u,a){return"none"}addHighlightHCMFilter(u,a,f,w,E){return"none"}destroy(u=!1){}}class o{constructor(){this.constructor===o&&(0,i.unreachable)("Cannot initialize BaseCanvasFactory.")}create(u,a){if(u<=0||a<=0)throw new Error("Invalid canvas size");let f=this._createCanvas(u,a);return{canvas:f,context:f.getContext("2d")}}reset(u,a,f){if(!u.canvas)throw new Error("Canvas is not specified");if(a<=0||f<=0)throw new Error("Invalid canvas size");u.canvas.width=a,u.canvas.height=f}destroy(u){if(!u.canvas)throw new Error("Canvas is not specified");u.canvas.width=0,u.canvas.height=0,u.canvas=null,u.context=null}_createCanvas(u,a){(0,i.unreachable)("Abstract method `_createCanvas` called.")}}class c{constructor({baseUrl:u=null,isCompressed:a=!0}){this.constructor===c&&(0,i.unreachable)("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=u,this.isCompressed=a}async fetch({name:u}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!u)throw new Error("CMap name must be specified.");let a=this.baseUrl+u+(this.isCompressed?".bcmap":""),f=this.isCompressed?i.CMapCompressionType.BINARY:i.CMapCompressionType.NONE;return this._fetchData(a,f).catch((w=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${a}`)}))}_fetchData(u,a){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class l{constructor({baseUrl:u=null}){this.constructor===l&&(0,i.unreachable)("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=u}async fetch({filename:u}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!u)throw new Error("Font filename must be specified.");let a=`${this.baseUrl}${u}`;return this._fetchData(a).catch((f=>{throw new Error(`Unable to load font data at: ${a}`)}))}_fetchData(u){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class h{constructor(){this.constructor===h&&(0,i.unreachable)("Cannot initialize BaseSVGFactory.")}create(u,a,f=!1){if(u<=0||a<=0)throw new Error("Invalid SVG dimensions");let w=this._createSVG("svg:svg");return w.setAttribute("version","1.1"),f||(w.setAttribute("width",`${u}px`),w.setAttribute("height",`${a}px`)),w.setAttribute("preserveAspectRatio","none"),w.setAttribute("viewBox",`0 0 ${u} ${a}`),w}createElement(u){if(typeof u!="string")throw new Error("Invalid SVG element type");return this._createSVG(u)}_createSVG(u){(0,i.unreachable)("Abstract method `_createSVG` called.")}}},923:(s,t,e)=>{e.d(t,{CanvasGraphics:()=>nt});var i=e(292),n=e(419);let o="Fill",c="Stroke",l="Shading";function h(G,A){if(!A)return;let T=A[2]-A[0],I=A[3]-A[1],g=new Path2D;g.rect(A[0],A[1],T,I),G.clip(g)}class m{constructor(){this.constructor===m&&(0,i.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,i.unreachable)("Abstract method `getPattern` called.")}}class u extends m{constructor(A){super(),this._type=A[1],this._bbox=A[2],this._colorStops=A[3],this._p0=A[4],this._p1=A[5],this._r0=A[6],this._r1=A[7],this.matrix=null}_createGradient(A){let T;this._type==="axial"?T=A.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(T=A.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let I of this._colorStops)T.addColorStop(I[0],I[1]);return T}getPattern(A,T,I,g){let v;if(g===c||g===o){let P=T.current.getClippedPathBoundingBox(g,(0,n.getCurrentTransform)(A))||[0,0,0,0],k=Math.ceil(P[2]-P[0])||1,O=Math.ceil(P[3]-P[1])||1,M=T.cachedCanvases.getCanvas("pattern",k,O,!0),C=M.context;C.clearRect(0,0,C.canvas.width,C.canvas.height),C.beginPath(),C.rect(0,0,C.canvas.width,C.canvas.height),C.translate(-P[0],-P[1]),I=i.Util.transform(I,[1,0,0,1,P[0],P[1]]),C.transform(...T.baseTransform),this.matrix&&C.transform(...this.matrix),h(C,this._bbox),C.fillStyle=this._createGradient(C),C.fill(),v=A.createPattern(M.canvas,"no-repeat");let L=new DOMMatrix(I);v.setTransform(L)}else h(A,this._bbox),v=this._createGradient(A);return v}}function a(G,A,T,I,g,v,P,k){let O=A.coords,M=A.colors,C=G.data,L=4*G.width,$;O[T+1]>O[I+1]&&($=T,T=I,I=$,$=v,v=P,P=$),O[I+1]>O[g+1]&&($=I,I=g,g=$,$=P,P=k,k=$),O[T+1]>O[I+1]&&($=T,T=I,I=$,$=v,v=P,P=$);let B=(O[T]+A.offsetX)*A.scaleX,D=(O[T+1]+A.offsetY)*A.scaleY,F=(O[I]+A.offsetX)*A.scaleX,V=(O[I+1]+A.offsetY)*A.scaleY,Q=(O[g]+A.offsetX)*A.scaleX,Z=(O[g+1]+A.offsetY)*A.scaleY;if(D>=Z)return;let et=M[v],rt=M[v+1],pt=M[v+2],dt=M[P],ct=M[P+1],wt=M[P+2],Pt=M[k],xt=M[k+1],Dt=M[k+2],Lt=Math.round(D),Ut=Math.round(Z),jt,he,Se,$e,Pe,Ie,bi,yi;for(let le=Lt;le<=Ut;le++){if(le<V){let ne=le<D?0:(D-le)/(D-V);jt=B-(B-F)*ne,he=et-(et-dt)*ne,Se=rt-(rt-ct)*ne,$e=pt-(pt-wt)*ne}else{let ne;ne=le>Z?1:V===Z?0:(V-le)/(V-Z),jt=F-(F-Q)*ne,he=dt-(dt-Pt)*ne,Se=ct-(ct-xt)*ne,$e=wt-(wt-Dt)*ne}let oe;oe=le<D?0:le>Z?1:(D-le)/(D-Z),Pe=B-(B-Q)*oe,Ie=et-(et-Pt)*oe,bi=rt-(rt-xt)*oe,yi=pt-(pt-Dt)*oe;let vi=Math.round(Math.min(jt,Pe)),_s=Math.round(Math.max(jt,Pe)),Le=L*le+4*vi;for(let ne=vi;ne<=_s;ne++)oe=(jt-ne)/(jt-Pe),oe<0?oe=0:oe>1&&(oe=1),C[Le++]=he-(he-Ie)*oe|0,C[Le++]=Se-(Se-bi)*oe|0,C[Le++]=$e-($e-yi)*oe|0,C[Le++]=255}}function f(G,A,T){let I=A.coords,g=A.colors,v,P;switch(A.type){case"lattice":let k=A.verticesPerRow,O=Math.floor(I.length/k)-1,M=k-1;for(v=0;v<O;v++){let C=v*k;for(let L=0;L<M;L++,C++)a(G,T,I[C],I[C+1],I[C+k],g[C],g[C+1],g[C+k]),a(G,T,I[C+k+1],I[C+1],I[C+k],g[C+k+1],g[C+1],g[C+k])}break;case"triangles":for(v=0,P=I.length;v<P;v+=3)a(G,T,I[v],I[v+1],I[v+2],g[v],g[v+1],g[v+2]);break;default:throw new Error("illegal figure")}}class w extends m{constructor(A){super(),this._coords=A[2],this._colors=A[3],this._figures=A[4],this._bounds=A[5],this._bbox=A[7],this._background=A[8],this.matrix=null}_createMeshCanvas(A,T,I){let g=Math.floor(this._bounds[0]),v=Math.floor(this._bounds[1]),P=Math.ceil(this._bounds[2])-g,k=Math.ceil(this._bounds[3])-v,O=Math.min(Math.ceil(Math.abs(P*A[0]*1.1)),3e3),M=Math.min(Math.ceil(Math.abs(k*A[1]*1.1)),3e3),C=P/O,L=k/M,$={coords:this._coords,colors:this._colors,offsetX:-g,offsetY:-v,scaleX:1/C,scaleY:1/L},B=O+4,D=M+4,F=I.getCanvas("mesh",B,D,!1),V=F.context,Q=V.createImageData(O,M);if(T){let Z=Q.data;for(let et=0,rt=Z.length;et<rt;et+=4)Z[et]=T[0],Z[et+1]=T[1],Z[et+2]=T[2],Z[et+3]=255}for(let Z of this._figures)f(Q,Z,$);return V.putImageData(Q,2,2),{canvas:F.canvas,offsetX:g-2*C,offsetY:v-2*L,scaleX:C,scaleY:L}}getPattern(A,T,I,g){h(A,this._bbox);let v;if(g===l)v=i.Util.singularValueDecompose2dScale((0,n.getCurrentTransform)(A));else if(v=i.Util.singularValueDecompose2dScale(T.baseTransform),this.matrix){let k=i.Util.singularValueDecompose2dScale(this.matrix);v=[v[0]*k[0],v[1]*k[1]]}let P=this._createMeshCanvas(v,g===l?null:this._background,T.cachedCanvases);return g!==l&&(A.setTransform(...T.baseTransform),this.matrix&&A.transform(...this.matrix)),A.translate(P.offsetX,P.offsetY),A.scale(P.scaleX,P.scaleY),A.createPattern(P.canvas,"no-repeat")}}class E extends m{getPattern(){return"hotpink"}}let p=1,y=2;class r{static MAX_PATTERN_SIZE=3e3;constructor(A,T,I,g,v){this.operatorList=A[2],this.matrix=A[3]||[1,0,0,1,0,0],this.bbox=A[4],this.xstep=A[5],this.ystep=A[6],this.paintType=A[7],this.tilingType=A[8],this.color=T,this.ctx=I,this.canvasGraphicsFactory=g,this.baseTransform=v}createPatternCanvas(A){let T=this.operatorList,I=this.bbox,g=this.xstep,v=this.ystep,P=this.paintType,k=this.tilingType,O=this.color,M=this.canvasGraphicsFactory;(0,i.info)("TilingType: "+k);let C=I[0],L=I[1],$=I[2],B=I[3],D=i.Util.singularValueDecompose2dScale(this.matrix),F=i.Util.singularValueDecompose2dScale(this.baseTransform),V=[D[0]*F[0],D[1]*F[1]],Q=this.getSizeAndScale(g,this.ctx.canvas.width,V[0]),Z=this.getSizeAndScale(v,this.ctx.canvas.height,V[1]),et=A.cachedCanvases.getCanvas("pattern",Q.size,Z.size,!0),rt=et.context,pt=M.createCanvasGraphics(rt);pt.groupLevel=A.groupLevel,this.setFillAndStrokeStyleToContext(pt,P,O);let dt=C,ct=L,wt=$,Pt=B;return C<0&&(dt=0,wt+=Math.abs(C)),L<0&&(ct=0,Pt+=Math.abs(L)),rt.translate(-Q.scale*dt,-Z.scale*ct),pt.transform(Q.scale,0,0,Z.scale,0,0),rt.save(),this.clipBbox(pt,dt,ct,wt,Pt),pt.baseTransform=(0,n.getCurrentTransform)(pt.ctx),pt.executeOperatorList(T),pt.endDrawing(),{canvas:et.canvas,scaleX:Q.scale,scaleY:Z.scale,offsetX:dt,offsetY:ct}}getSizeAndScale(A,T,I){A=Math.abs(A);let g=Math.max(r.MAX_PATTERN_SIZE,T),v=Math.ceil(A*I);return v>=g?v=g:I=v/A,{scale:I,size:v}}clipBbox(A,T,I,g,v){let P=g-T,k=v-I;A.ctx.rect(T,I,P,k),A.current.updateRectMinMax((0,n.getCurrentTransform)(A.ctx),[T,I,g,v]),A.clip(),A.endPath()}setFillAndStrokeStyleToContext(A,T,I){let g=A.ctx,v=A.current;switch(T){case p:let P=this.ctx;g.fillStyle=P.fillStyle,g.strokeStyle=P.strokeStyle,v.fillColor=P.fillStyle,v.strokeColor=P.strokeStyle;break;case y:let k=i.Util.makeHexColor(I[0],I[1],I[2]);g.fillStyle=k,g.strokeStyle=k,v.fillColor=k,v.strokeColor=k;break;default:throw new i.FormatError(`Unsupported paint type: ${T}`)}}getPattern(A,T,I,g){let v=I;g!==l&&(v=i.Util.transform(v,T.baseTransform),this.matrix&&(v=i.Util.transform(v,this.matrix)));let P=this.createPatternCanvas(T),k=new DOMMatrix(v);k=k.translate(P.offsetX,P.offsetY),k=k.scale(1/P.scaleX,1/P.scaleY);let O=A.createPattern(P.canvas,"repeat");return O.setTransform(k),O}}function d({src:G,srcPos:A=0,dest:T,width:I,height:g,nonBlackColor:v=4294967295,inverseDecode:P=!1}){let k=i.FeatureTest.isLittleEndian?4278190080:255,[O,M]=P?[v,k]:[k,v],C=I>>3,L=7&I,$=G.length;T=new Uint32Array(T.buffer);let B=0;for(let D=0;D<g;D++){for(let V=A+C;A<V;A++){let Q=A<$?G[A]:255;T[B++]=128&Q?M:O,T[B++]=64&Q?M:O,T[B++]=32&Q?M:O,T[B++]=16&Q?M:O,T[B++]=8&Q?M:O,T[B++]=4&Q?M:O,T[B++]=2&Q?M:O,T[B++]=1&Q?M:O}if(L===0)continue;let F=A<$?G[A++]:255;for(let V=0;V<L;V++)T[B++]=F&1<<7-V?M:O}return{srcPos:A,destPos:B}}let b=4096,x=16;class _{constructor(A){this.canvasFactory=A,this.cache=Object.create(null)}getCanvas(A,T,I){let g;return this.cache[A]!==void 0?(g=this.cache[A],this.canvasFactory.reset(g,T,I)):(g=this.canvasFactory.create(T,I),this.cache[A]=g),g}delete(A){delete this.cache[A]}clear(){for(let A in this.cache){let T=this.cache[A];this.canvasFactory.destroy(T),delete this.cache[A]}}}function S(G,A,T,I,g,v,P,k,O,M){let[C,L,$,B,D,F]=(0,n.getCurrentTransform)(G);if(L===0&&$===0){let V=P*C+D,Q=Math.round(V),Z=k*B+F,et=Math.round(Z),rt=(P+O)*C+D,pt=Math.abs(Math.round(rt)-Q)||1,dt=(k+M)*B+F,ct=Math.abs(Math.round(dt)-et)||1;return G.setTransform(Math.sign(C),0,0,Math.sign(B),Q,et),G.drawImage(A,T,I,g,v,0,0,pt,ct),G.setTransform(C,L,$,B,D,F),[pt,ct]}if(C===0&&B===0){let V=k*$+D,Q=Math.round(V),Z=P*L+F,et=Math.round(Z),rt=(k+M)*$+D,pt=Math.abs(Math.round(rt)-Q)||1,dt=(P+O)*L+F,ct=Math.abs(Math.round(dt)-et)||1;return G.setTransform(0,Math.sign(L),Math.sign($),0,Q,et),G.drawImage(A,T,I,g,v,0,0,ct,pt),G.setTransform(C,L,$,B,D,F),[ct,pt]}return G.drawImage(A,T,I,g,v,P,k,O,M),[Math.hypot(C,L)*O,Math.hypot($,B)*M]}class R{constructor(A,T){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=i.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=i.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=i.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,A,T])}clone(){let A=Object.create(this);return A.clipBox=this.clipBox.slice(),A}setCurrentPoint(A,T){this.x=A,this.y=T}updatePathMinMax(A,T,I){[T,I]=i.Util.applyTransform([T,I],A),this.minX=Math.min(this.minX,T),this.minY=Math.min(this.minY,I),this.maxX=Math.max(this.maxX,T),this.maxY=Math.max(this.maxY,I)}updateRectMinMax(A,T){let I=i.Util.applyTransform(T,A),g=i.Util.applyTransform(T.slice(2),A),v=i.Util.applyTransform([T[0],T[3]],A),P=i.Util.applyTransform([T[2],T[1]],A);this.minX=Math.min(this.minX,I[0],g[0],v[0],P[0]),this.minY=Math.min(this.minY,I[1],g[1],v[1],P[1]),this.maxX=Math.max(this.maxX,I[0],g[0],v[0],P[0]),this.maxY=Math.max(this.maxY,I[1],g[1],v[1],P[1])}updateScalingPathMinMax(A,T){i.Util.scaleMinMax(A,T),this.minX=Math.min(this.minX,T[0]),this.minY=Math.min(this.minY,T[1]),this.maxX=Math.max(this.maxX,T[2]),this.maxY=Math.max(this.maxY,T[3])}updateCurvePathMinMax(A,T,I,g,v,P,k,O,M,C){let L=i.Util.bezierBoundingBox(T,I,g,v,P,k,O,M,C);C||this.updateRectMinMax(A,L)}getPathBoundingBox(A=o,T=null){let I=[this.minX,this.minY,this.maxX,this.maxY];if(A===c){T||(0,i.unreachable)("Stroke bounding box must include transform.");let g=i.Util.singularValueDecompose2dScale(T),v=g[0]*this.lineWidth/2,P=g[1]*this.lineWidth/2;I[0]-=v,I[1]-=P,I[2]+=v,I[3]+=P}return I}updateClipFromPath(){let A=i.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(A||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(A){this.clipBox=A,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(A=o,T=null){return i.Util.intersect(this.clipBox,this.getPathBoundingBox(A,T))}}function N(G,A){if(typeof ImageData<"u"&&A instanceof ImageData){G.putImageData(A,0,0);return}let T=A.height,I=A.width,g=T%x,v=(T-g)/x,P=g===0?v:v+1,k=G.createImageData(I,x),O,M=0,C=A.data,L=k.data,$,B,D,F;if(A.kind===i.ImageKind.GRAYSCALE_1BPP){let V=C.byteLength,Q=new Uint32Array(L.buffer,0,L.byteLength>>2),Z=Q.length,et=I+7>>3,rt=4294967295,pt=i.FeatureTest.isLittleEndian?4278190080:255;for($=0;$<P;$++){for(D=$<v?x:g,O=0,B=0;B<D;B++){let dt=V-M,ct=0,wt=dt>et?I:8*dt-7,Pt=-8&wt,xt=0,Dt=0;for(;ct<Pt;ct+=8)Dt=C[M++],Q[O++]=128&Dt?rt:pt,Q[O++]=64&Dt?rt:pt,Q[O++]=32&Dt?rt:pt,Q[O++]=16&Dt?rt:pt,Q[O++]=8&Dt?rt:pt,Q[O++]=4&Dt?rt:pt,Q[O++]=2&Dt?rt:pt,Q[O++]=1&Dt?rt:pt;for(;ct<wt;ct++)xt===0&&(Dt=C[M++],xt=128),Q[O++]=Dt&xt?rt:pt,xt>>=1}for(;O<Z;)Q[O++]=0;G.putImageData(k,0,$*x)}}else if(A.kind===i.ImageKind.RGBA_32BPP){for(B=0,F=I*x*4,$=0;$<v;$++)L.set(C.subarray(M,M+F)),M+=F,G.putImageData(k,0,B),B+=x;$<P&&(F=I*g*4,L.set(C.subarray(M,M+F)),G.putImageData(k,0,B))}else{if(A.kind!==i.ImageKind.RGB_24BPP)throw new Error(`bad image kind: ${A.kind}`);for(D=x,F=I*D,$=0;$<P;$++){for($>=v&&(D=g,F=I*D),O=0,B=F;B--;)L[O++]=C[M++],L[O++]=C[M++],L[O++]=C[M++],L[O++]=255;G.putImageData(k,0,$*x)}}}function H(G,A){if(A.bitmap){G.drawImage(A.bitmap,0,0);return}let T=A.height,I=A.width,g=T%x,v=(T-g)/x,P=g===0?v:v+1,k=G.createImageData(I,x),O=0,M=A.data,C=k.data;for(let L=0;L<P;L++){let $=L<v?x:g;({srcPos:O}=d({src:M,srcPos:O,dest:C,width:I,height:$,nonBlackColor:0})),G.putImageData(k,0,L*x)}}function z(G,A){let T=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let I of T)G[I]!==void 0&&(A[I]=G[I]);G.setLineDash!==void 0&&(A.setLineDash(G.getLineDash()),A.lineDashOffset=G.lineDashOffset)}function K(G){if(G.strokeStyle=G.fillStyle="#000000",G.fillRule="nonzero",G.globalAlpha=1,G.lineWidth=1,G.lineCap="butt",G.lineJoin="miter",G.miterLimit=10,G.globalCompositeOperation="source-over",G.font="10px sans-serif",G.setLineDash!==void 0&&(G.setLineDash([]),G.lineDashOffset=0),!i.isNodeJS){let{filter:A}=G;A!=="none"&&A!==""&&(G.filter="none")}}function it(G,A,T,I){let g=G.length;for(let v=3;v<g;v+=4){let P=G[v];if(P===0)G[v-3]=A,G[v-2]=T,G[v-1]=I;else if(P<255){let k=255-P;G[v-3]=G[v-3]*P+A*k>>8,G[v-2]=G[v-2]*P+T*k>>8,G[v-1]=G[v-1]*P+I*k>>8}}}function at(G,A,T){let I=G.length;for(let g=3;g<I;g+=4){let v=T?T[G[g]]:G[g];A[g]=A[g]*v*.00392156862745098|0}}function X(G,A,T){let I=G.length;for(let g=3;g<I;g+=4){let v=77*G[g-3]+152*G[g-2]+28*G[g-1];A[g]=T?A[g]*T[v>>8]>>8:A[g]*v>>16}}function j(G,A,T,I){let g=I[0],v=I[1],P=I[2]-g,k=I[3]-v;P!==0&&k!==0&&((function(M,C,L,$,B,D,F,V,Q,Z,et){let rt=!!D,pt=rt?D[0]:0,dt=rt?D[1]:0,ct=rt?D[2]:0,wt=B==="Luminosity"?X:at,Pt=Math.min($,Math.ceil(1048576/L));for(let xt=0;xt<$;xt+=Pt){let Dt=Math.min(Pt,$-xt),Lt=M.getImageData(V-Z,xt+(Q-et),L,Dt),Ut=C.getImageData(V,xt+Q,L,Dt);rt&&it(Lt.data,pt,dt,ct),wt(Lt.data,Ut.data,F),C.putImageData(Ut,V,xt+Q)}})(A.context,T,P,k,A.subtype,A.backdrop,A.transferMap,g,v,A.offsetX,A.offsetY),G.save(),G.globalAlpha=1,G.globalCompositeOperation="source-over",G.setTransform(1,0,0,1,0,0),G.drawImage(T.canvas,0,0),G.restore())}function W(G,A){let T=i.Util.singularValueDecompose2dScale(G);T[0]=Math.fround(T[0]),T[1]=Math.fround(T[1]);let I=Math.fround((globalThis.devicePixelRatio||1)*n.PixelsPerInch.PDF_TO_CSS_UNITS);return A!==void 0?A:T[0]<=I||T[1]<=I}let Y=["butt","round","square"],tt=["miter","round","bevel"],st={},lt={};class nt{constructor(A,T,I,g,v,{optionalContentConfig:P,markedContentStack:k=null},O,M){this.ctx=A,this.current=new R(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=T,this.objs=I,this.canvasFactory=g,this.filterFactory=v,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=k||[],this.optionalContentConfig=P,this.cachedCanvases=new _(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=O,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=M,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(A,T=null){return typeof A=="string"?A.startsWith("g_")?this.commonObjs.get(A):this.objs.get(A):T}beginDrawing({transform:A,viewport:T,transparency:I=!1,background:g=null}){let v=this.ctx.canvas.width,P=this.ctx.canvas.height,k=this.ctx.fillStyle;if(this.ctx.fillStyle=g||"#ffffff",this.ctx.fillRect(0,0,v,P),this.ctx.fillStyle=k,I){let O=this.cachedCanvases.getCanvas("transparent",v,P);this.compositeCtx=this.ctx,this.transparentCanvas=O.canvas,this.ctx=O.context,this.ctx.save(),this.ctx.transform(...(0,n.getCurrentTransform)(this.compositeCtx))}this.ctx.save(),K(this.ctx),A&&(this.ctx.transform(...A),this.outputScaleX=A[0],this.outputScaleY=A[0]),this.ctx.transform(...T.transform),this.viewportScale=T.scale,this.baseTransform=(0,n.getCurrentTransform)(this.ctx)}executeOperatorList(A,T,I,g){let v=A.argsArray,P=A.fnArray,k=T||0,O=v.length;if(O===k)return k;let M=O-k>10&&typeof I=="function",C=M?Date.now()+15:0,L=0,$=this.commonObjs,B=this.objs,D;for(;;){if(g!==void 0&&k===g.nextBreakPoint)return g.breakIt(k,I),k;if(D=P[k],D!==i.OPS.dependency)this[D].apply(this,v[k]);else for(let F of v[k]){let V=F.startsWith("g_")?$:B;if(!V.has(F))return V.get(F,I),k}if(k++,k===O)return k;if(M&&++L>10){if(Date.now()>C)return I(),k;L=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let A of this._cachedBitmapsMap.values()){for(let T of A.values())typeof HTMLCanvasElement<"u"&&T instanceof HTMLCanvasElement&&(T.width=T.height=0);A.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){let A=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(A!=="none"){let T=this.ctx.filter;this.ctx.filter=A,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=T}}}_scaleImage(A,T){let I=A.width,g=A.height,v,P,k=Math.max(Math.hypot(T[0],T[1]),1),O=Math.max(Math.hypot(T[2],T[3]),1),M=I,C=g,L="prescale1";for(;k>2&&M>1||O>2&&C>1;){let $=M,B=C;k>2&&M>1&&($=M>=16384?Math.floor(M/2)-1||1:Math.ceil(M/2),k/=M/$),O>2&&C>1&&(B=C>=16384?Math.floor(C/2)-1||1:Math.ceil(C)/2,O/=C/B),v=this.cachedCanvases.getCanvas(L,$,B),P=v.context,P.clearRect(0,0,$,B),P.drawImage(A,0,0,M,C,0,0,$,B),A=v.canvas,M=$,C=B,L=L==="prescale1"?"prescale2":"prescale1"}return{img:A,paintWidth:M,paintHeight:C}}_createMaskCanvas(A){let T=this.ctx,{width:I,height:g}=A,v=this.current.fillColor,P=this.current.patternFill,k=(0,n.getCurrentTransform)(T),O,M,C,L;if((A.bitmap||A.data)&&A.count>1){let wt=A.bitmap||A.data.buffer;M=JSON.stringify(P?k:[k.slice(0,4),v]),O=this._cachedBitmapsMap.get(wt),O||(O=new Map,this._cachedBitmapsMap.set(wt,O));let Pt=O.get(M);if(Pt&&!P)return{canvas:Pt,offsetX:Math.round(Math.min(k[0],k[2])+k[4]),offsetY:Math.round(Math.min(k[1],k[3])+k[5])};C=Pt}C||(L=this.cachedCanvases.getCanvas("maskCanvas",I,g),H(L.context,A));let $=i.Util.transform(k,[1/I,0,0,-1/g,0,0]);$=i.Util.transform($,[1,0,0,1,0,-g]);let[B,D,F,V]=i.Util.getAxialAlignedBoundingBox([0,0,I,g],$),Q=Math.round(F-B)||1,Z=Math.round(V-D)||1,et=this.cachedCanvases.getCanvas("fillCanvas",Q,Z),rt=et.context,pt=B,dt=D;rt.translate(-pt,-dt),rt.transform(...$),C||(C=this._scaleImage(L.canvas,(0,n.getCurrentTransformInverse)(rt)),C=C.img,O&&P&&O.set(M,C)),rt.imageSmoothingEnabled=W((0,n.getCurrentTransform)(rt),A.interpolate),S(rt,C,0,0,C.width,C.height,0,0,I,g),rt.globalCompositeOperation="source-in";let ct=i.Util.transform((0,n.getCurrentTransformInverse)(rt),[1,0,0,1,-pt,-dt]);return rt.fillStyle=P?v.getPattern(T,this,ct,o):v,rt.fillRect(0,0,I,g),O&&!P&&(this.cachedCanvases.delete("fillCanvas"),O.set(M,et.canvas)),{canvas:et.canvas,offsetX:Math.round(pt),offsetY:Math.round(dt)}}setLineWidth(A){A!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=A,this.ctx.lineWidth=A}setLineCap(A){this.ctx.lineCap=Y[A]}setLineJoin(A){this.ctx.lineJoin=tt[A]}setMiterLimit(A){this.ctx.miterLimit=A}setDash(A,T){let I=this.ctx;I.setLineDash!==void 0&&(I.setLineDash(A),I.lineDashOffset=T)}setRenderingIntent(A){}setFlatness(A){}setGState(A){for(let[T,I]of A)switch(T){case"LW":this.setLineWidth(I);break;case"LC":this.setLineCap(I);break;case"LJ":this.setLineJoin(I);break;case"ML":this.setMiterLimit(I);break;case"D":this.setDash(I[0],I[1]);break;case"RI":this.setRenderingIntent(I);break;case"FL":this.setFlatness(I);break;case"Font":this.setFont(I[0],I[1]);break;case"CA":this.current.strokeAlpha=I;break;case"ca":this.current.fillAlpha=I,this.ctx.globalAlpha=I;break;case"BM":this.ctx.globalCompositeOperation=I;break;case"SMask":this.current.activeSMask=I?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(I)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let A=this.inSMaskMode;this.current.activeSMask&&!A?this.beginSMaskMode():!this.current.activeSMask&&A&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let A=this.ctx.canvas.width,T=this.ctx.canvas.height,I="smaskGroupAt"+this.groupLevel,g=this.cachedCanvases.getCanvas(I,A,T);this.suspendedCtx=this.ctx,this.ctx=g.context;let v=this.ctx;v.setTransform(...(0,n.getCurrentTransform)(this.suspendedCtx)),z(this.suspendedCtx,v),(function(k,O){if(k._removeMirroring)throw new Error("Context is already forwarding operations.");k.__originalSave=k.save,k.__originalRestore=k.restore,k.__originalRotate=k.rotate,k.__originalScale=k.scale,k.__originalTranslate=k.translate,k.__originalTransform=k.transform,k.__originalSetTransform=k.setTransform,k.__originalResetTransform=k.resetTransform,k.__originalClip=k.clip,k.__originalMoveTo=k.moveTo,k.__originalLineTo=k.lineTo,k.__originalBezierCurveTo=k.bezierCurveTo,k.__originalRect=k.rect,k.__originalClosePath=k.closePath,k.__originalBeginPath=k.beginPath,k._removeMirroring=()=>{k.save=k.__originalSave,k.restore=k.__originalRestore,k.rotate=k.__originalRotate,k.scale=k.__originalScale,k.translate=k.__originalTranslate,k.transform=k.__originalTransform,k.setTransform=k.__originalSetTransform,k.resetTransform=k.__originalResetTransform,k.clip=k.__originalClip,k.moveTo=k.__originalMoveTo,k.lineTo=k.__originalLineTo,k.bezierCurveTo=k.__originalBezierCurveTo,k.rect=k.__originalRect,k.closePath=k.__originalClosePath,k.beginPath=k.__originalBeginPath,delete k._removeMirroring},k.save=function(){O.save(),this.__originalSave()},k.restore=function(){O.restore(),this.__originalRestore()},k.translate=function(C,L){O.translate(C,L),this.__originalTranslate(C,L)},k.scale=function(C,L){O.scale(C,L),this.__originalScale(C,L)},k.transform=function(C,L,$,B,D,F){O.transform(C,L,$,B,D,F),this.__originalTransform(C,L,$,B,D,F)},k.setTransform=function(C,L,$,B,D,F){O.setTransform(C,L,$,B,D,F),this.__originalSetTransform(C,L,$,B,D,F)},k.resetTransform=function(){O.resetTransform(),this.__originalResetTransform()},k.rotate=function(C){O.rotate(C),this.__originalRotate(C)},k.clip=function(C){O.clip(C),this.__originalClip(C)},k.moveTo=function(M,C){O.moveTo(M,C),this.__originalMoveTo(M,C)},k.lineTo=function(M,C){O.lineTo(M,C),this.__originalLineTo(M,C)},k.bezierCurveTo=function(M,C,L,$,B,D){O.bezierCurveTo(M,C,L,$,B,D),this.__originalBezierCurveTo(M,C,L,$,B,D)},k.rect=function(M,C,L,$){O.rect(M,C,L,$),this.__originalRect(M,C,L,$)},k.closePath=function(){O.closePath(),this.__originalClosePath()},k.beginPath=function(){O.beginPath(),this.__originalBeginPath()}})(v,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),z(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(A){if(!this.current.activeSMask)return;A?(A[0]=Math.floor(A[0]),A[1]=Math.floor(A[1]),A[2]=Math.ceil(A[2]),A[3]=Math.ceil(A[3])):A=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let T=this.current.activeSMask;j(this.suspendedCtx,T,this.ctx,A),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}save(){this.inSMaskMode?(z(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let A=this.current;this.stateStack.push(A),this.current=A.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),z(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(A,T,I,g,v,P){this.ctx.transform(A,T,I,g,v,P),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(A,T,I){let g=this.ctx,v=this.current,P,k,O=v.x,M=v.y,C=(0,n.getCurrentTransform)(g),L=C[0]===0&&C[3]===0||C[1]===0&&C[2]===0,$=L?I.slice(0):null;for(let B=0,D=0,F=A.length;B<F;B++)switch(0|A[B]){case i.OPS.rectangle:O=T[D++],M=T[D++];let V=T[D++],Q=T[D++],Z=O+V,et=M+Q;g.moveTo(O,M),V===0||Q===0?g.lineTo(Z,et):(g.lineTo(Z,M),g.lineTo(Z,et),g.lineTo(O,et)),L||v.updateRectMinMax(C,[O,M,Z,et]),g.closePath();break;case i.OPS.moveTo:O=T[D++],M=T[D++],g.moveTo(O,M),L||v.updatePathMinMax(C,O,M);break;case i.OPS.lineTo:O=T[D++],M=T[D++],g.lineTo(O,M),L||v.updatePathMinMax(C,O,M);break;case i.OPS.curveTo:P=O,k=M,O=T[D+4],M=T[D+5],g.bezierCurveTo(T[D],T[D+1],T[D+2],T[D+3],O,M),v.updateCurvePathMinMax(C,P,k,T[D],T[D+1],T[D+2],T[D+3],O,M,$),D+=6;break;case i.OPS.curveTo2:P=O,k=M,g.bezierCurveTo(O,M,T[D],T[D+1],T[D+2],T[D+3]),v.updateCurvePathMinMax(C,P,k,O,M,T[D],T[D+1],T[D+2],T[D+3],$),O=T[D+2],M=T[D+3],D+=4;break;case i.OPS.curveTo3:P=O,k=M,O=T[D+2],M=T[D+3],g.bezierCurveTo(T[D],T[D+1],O,M,O,M),v.updateCurvePathMinMax(C,P,k,T[D],T[D+1],O,M,O,M,$),D+=4;break;case i.OPS.closePath:g.closePath()}L&&v.updateScalingPathMinMax(C,$),v.setCurrentPoint(O,M)}closePath(){this.ctx.closePath()}stroke(A=!0){let T=this.ctx,I=this.current.strokeColor;T.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof I=="object"&&I?.getPattern?(T.save(),T.strokeStyle=I.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),c),this.rescaleAndStroke(!1),T.restore()):this.rescaleAndStroke(!0)),A&&this.consumePath(this.current.getClippedPathBoundingBox()),T.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(A=!0){let T=this.ctx,I=this.current.fillColor,g=!1;this.current.patternFill&&(T.save(),T.fillStyle=I.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),o),g=!0);let v=this.current.getClippedPathBoundingBox();this.contentVisible&&v!==null&&(this.pendingEOFill?(T.fill("evenodd"),this.pendingEOFill=!1):T.fill()),g&&T.restore(),A&&this.consumePath(v)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=st}eoClip(){this.pendingClip=lt}beginText(){this.current.textMatrix=i.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){let A=this.pendingTextPaths,T=this.ctx;if(A!==void 0){T.save(),T.beginPath();for(let I of A)T.setTransform(...I.transform),T.translate(I.x,I.y),I.addToPath(T,I.fontSize);T.restore(),T.clip(),T.beginPath(),delete this.pendingTextPaths}else T.beginPath()}setCharSpacing(A){this.current.charSpacing=A}setWordSpacing(A){this.current.wordSpacing=A}setHScale(A){this.current.textHScale=A/100}setLeading(A){this.current.leading=-A}setFont(A,T){let I=this.commonObjs.get(A),g=this.current;if(!I)throw new Error(`Can't find font for ${A}`);if(g.fontMatrix=I.fontMatrix||i.FONT_IDENTITY_MATRIX,g.fontMatrix[0]!==0&&g.fontMatrix[3]!==0||(0,i.warn)("Invalid font matrix for font "+A),T<0?(T=-T,g.fontDirection=-1):g.fontDirection=1,this.current.font=I,this.current.fontSize=T,I.isType3Font)return;let v=I.loadedName||"sans-serif",P=I.systemFontInfo?.css||`"${v}", ${I.fallbackName}`,k="normal";I.black?k="900":I.bold&&(k="bold");let O=I.italic?"italic":"normal",M=T;T<16?M=16:T>100&&(M=100),this.current.fontSizeScale=T/M,this.ctx.font=`${O} ${k} ${M}px ${P}`}setTextRenderingMode(A){this.current.textRenderingMode=A}setTextRise(A){this.current.textRise=A}moveText(A,T){this.current.x=this.current.lineX+=A,this.current.y=this.current.lineY+=T}setLeadingMoveText(A,T){this.setLeading(-T),this.moveText(A,T)}setTextMatrix(A,T,I,g,v,P){this.current.textMatrix=[A,T,I,g,v,P],this.current.textMatrixScale=Math.hypot(A,T),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(A,T,I,g){let v=this.ctx,P=this.current,k=P.font,O=P.textRenderingMode,M=P.fontSize/P.fontSizeScale,C=O&i.TextRenderingMode.FILL_STROKE_MASK,L=!!(O&i.TextRenderingMode.ADD_TO_PATH_FLAG),$=P.patternFill&&!k.missingFile,B;(k.disableFontFace||L||$)&&(B=k.getPathGenerator(this.commonObjs,A)),k.disableFontFace||$?(v.save(),v.translate(T,I),v.beginPath(),B(v,M),g&&v.setTransform(...g),C!==i.TextRenderingMode.FILL&&C!==i.TextRenderingMode.FILL_STROKE||v.fill(),C!==i.TextRenderingMode.STROKE&&C!==i.TextRenderingMode.FILL_STROKE||v.stroke(),v.restore()):(C!==i.TextRenderingMode.FILL&&C!==i.TextRenderingMode.FILL_STROKE||v.fillText(A,T,I),C!==i.TextRenderingMode.STROKE&&C!==i.TextRenderingMode.FILL_STROKE||v.strokeText(A,T,I)),L&&(this.pendingTextPaths||=[]).push({transform:(0,n.getCurrentTransform)(v),x:T,y:I,fontSize:M,addToPath:B})}get isFontSubpixelAAEnabled(){let{context:A}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);A.scale(1.5,1),A.fillText("I",0,10);let T=A.getImageData(0,0,10,10).data,I=!1;for(let g=3;g<T.length;g+=4)if(T[g]>0&&T[g]<255){I=!0;break}return(0,i.shadow)(this,"isFontSubpixelAAEnabled",I)}showText(A){let T=this.current,I=T.font;if(I.isType3Font)return this.showType3Text(A);let g=T.fontSize;if(g===0)return;let v=this.ctx,P=T.fontSizeScale,k=T.charSpacing,O=T.wordSpacing,M=T.fontDirection,C=T.textHScale*M,L=A.length,$=I.vertical,B=$?1:-1,D=I.defaultVMetrics,F=g*T.fontMatrix[0],V=T.textRenderingMode===i.TextRenderingMode.FILL&&!I.disableFontFace&&!T.patternFill;v.save(),v.transform(...T.textMatrix),v.translate(T.x,T.y+T.textRise),M>0?v.scale(C,-1):v.scale(C,1);let Q;if(T.patternFill){v.save();let dt=T.fillColor.getPattern(v,this,(0,n.getCurrentTransformInverse)(v),o);Q=(0,n.getCurrentTransform)(v),v.restore(),v.fillStyle=dt}let Z=T.lineWidth,et=T.textMatrixScale;if(et===0||Z===0){let dt=T.textRenderingMode&i.TextRenderingMode.FILL_STROKE_MASK;dt!==i.TextRenderingMode.STROKE&&dt!==i.TextRenderingMode.FILL_STROKE||(Z=this.getSinglePixelWidth())}else Z/=et;if(P!==1&&(v.scale(P,P),Z/=P),v.lineWidth=Z,I.isInvalidPDFjsFont){let dt=[],ct=0;for(let wt of A)dt.push(wt.unicode),ct+=wt.width;v.fillText(dt.join(""),0,0),T.x+=ct*F*C,v.restore(),this.compose();return}let rt,pt=0;for(rt=0;rt<L;++rt){let dt=A[rt];if(typeof dt=="number"){pt+=B*dt*g/1e3;continue}let ct=!1,wt=(dt.isSpace?O:0)+k,Pt=dt.fontChar,xt=dt.accent,Dt,Lt,Ut=dt.width;if($){let jt=dt.vmetric||D,he=-(dt.vmetric?jt[1]:.5*Ut)*F,Se=jt[2]*F;Ut=jt?-jt[0]:Ut,Dt=he/P,Lt=(pt+Se)/P}else Dt=pt/P,Lt=0;if(I.remeasure&&Ut>0){let jt=1e3*v.measureText(Pt).width/g*P;if(Ut<jt&&this.isFontSubpixelAAEnabled){let he=Ut/jt;ct=!0,v.save(),v.scale(he,1),Dt/=he}else Ut!==jt&&(Dt+=(Ut-jt)/2e3*g/P)}if(this.contentVisible&&(dt.isInFont||I.missingFile)){if(V&&!xt)v.fillText(Pt,Dt,Lt);else if(this.paintChar(Pt,Dt,Lt,Q),xt){let jt=Dt+g*xt.offset.x/P,he=Lt-g*xt.offset.y/P;this.paintChar(xt.fontChar,jt,he,Q)}}pt+=$?Ut*F-wt*M:Ut*F+wt*M,ct&&v.restore()}$?T.y-=pt:T.x+=pt*C,v.restore(),this.compose()}showType3Text(A){let T=this.ctx,I=this.current,g=I.font,v=I.fontSize,P=I.fontDirection,k=g.vertical?1:-1,O=I.charSpacing,M=I.wordSpacing,C=I.textHScale*P,L=I.fontMatrix||i.FONT_IDENTITY_MATRIX,$=A.length,B,D,F,V;if(I.textRenderingMode!==i.TextRenderingMode.INVISIBLE&&v!==0){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,T.save(),T.transform(...I.textMatrix),T.translate(I.x,I.y),T.scale(C,P),B=0;B<$;++B){if(D=A[B],typeof D=="number"){V=k*D*v/1e3,this.ctx.translate(V,0),I.x+=V*C;continue}let Q=(D.isSpace?M:0)+O,Z=g.charProcOperatorList[D.operatorListId];if(!Z){(0,i.warn)(`Type3 character "${D.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=D,this.save(),T.scale(v,v),T.transform(...L),this.executeOperatorList(Z),this.restore()),F=i.Util.applyTransform([D.width,0],L)[0]*v+Q,T.translate(F,0),I.x+=F*C}T.restore(),this.processingType3=null}}setCharWidth(A,T){}setCharWidthAndBounds(A,T,I,g,v,P){this.ctx.rect(I,g,v-I,P-g),this.ctx.clip(),this.endPath()}getColorN_Pattern(A){let T;if(A[0]==="TilingPattern"){let I=A[1],g=this.baseTransform||(0,n.getCurrentTransform)(this.ctx),v={createCanvasGraphics:P=>new nt(P,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};T=new r(A,I,this.ctx,v,g)}else T=this._getPattern(A[1],A[2]);return T}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(A,T,I){let g=i.Util.makeHexColor(A,T,I);this.ctx.strokeStyle=g,this.current.strokeColor=g}setFillRGBColor(A,T,I){let g=i.Util.makeHexColor(A,T,I);this.ctx.fillStyle=g,this.current.fillColor=g,this.current.patternFill=!1}_getPattern(A,T=null){let I;return this.cachedPatterns.has(A)?I=this.cachedPatterns.get(A):(I=(function(v){switch(v[0]){case"RadialAxial":return new u(v);case"Mesh":return new w(v);case"Dummy":return new E}throw new Error(`Unknown IR type: ${v[0]}`)})(this.getObject(A)),this.cachedPatterns.set(A,I)),T&&(I.matrix=T),I}shadingFill(A){if(!this.contentVisible)return;let T=this.ctx;this.save();let I=this._getPattern(A);T.fillStyle=I.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),l);let g=(0,n.getCurrentTransformInverse)(T);if(g){let{width:v,height:P}=T.canvas,[k,O,M,C]=i.Util.getAxialAlignedBoundingBox([0,0,v,P],g);this.ctx.fillRect(k,O,M-k,C-O)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){(0,i.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,i.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(A,T){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),Array.isArray(A)&&A.length===6&&this.transform(...A),this.baseTransform=(0,n.getCurrentTransform)(this.ctx),T)){let I=T[2]-T[0],g=T[3]-T[1];this.ctx.rect(T[0],T[1],I,g),this.current.updateRectMinMax((0,n.getCurrentTransform)(this.ctx),T),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(A){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let T=this.ctx;A.isolated||(0,i.info)("TODO: Support non-isolated groups."),A.knockout&&(0,i.warn)("Knockout groups not supported.");let I=(0,n.getCurrentTransform)(T);if(A.matrix&&T.transform(...A.matrix),!A.bbox)throw new Error("Bounding box is required.");let g=i.Util.getAxialAlignedBoundingBox(A.bbox,(0,n.getCurrentTransform)(T)),v=[0,0,T.canvas.width,T.canvas.height];g=i.Util.intersect(g,v)||[0,0,0,0];let P=Math.floor(g[0]),k=Math.floor(g[1]),O=Math.max(Math.ceil(g[2])-P,1),M=Math.max(Math.ceil(g[3])-k,1),C=1,L=1;O>b&&(C=O/b,O=b),M>b&&(L=M/b,M=b),this.current.startNewPathAndClipBox([0,0,O,M]);let $="groupAt"+this.groupLevel;A.smask&&($+="_smask_"+this.smaskCounter++%2);let B=this.cachedCanvases.getCanvas($,O,M),D=B.context;D.scale(1/C,1/L),D.translate(-P,-k),D.transform(...I),A.smask?this.smaskStack.push({canvas:B.canvas,context:D,offsetX:P,offsetY:k,scaleX:C,scaleY:L,subtype:A.smask.subtype,backdrop:A.smask.backdrop,transferMap:A.smask.transferMap||null,startTransformInverse:null}):(T.setTransform(1,0,0,1,0,0),T.translate(P,k),T.scale(C,L),T.save()),z(T,D),this.ctx=D,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(T),this.groupLevel++}endGroup(A){if(!this.contentVisible)return;this.groupLevel--;let T=this.ctx,I=this.groupStack.pop();if(this.ctx=I,this.ctx.imageSmoothingEnabled=!1,A.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let g=(0,n.getCurrentTransform)(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...g);let v=i.Util.getAxialAlignedBoundingBox([0,0,T.canvas.width,T.canvas.height],g);this.ctx.drawImage(T.canvas,0,0),this.ctx.restore(),this.compose(v)}}beginAnnotation(A,T,I,g,v){if(this.#t(),K(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),Array.isArray(T)&&T.length===4){let P=T[2]-T[0],k=T[3]-T[1];if(v&&this.annotationCanvasMap){(I=I.slice())[4]-=T[0],I[5]-=T[1],(T=T.slice())[0]=T[1]=0,T[2]=P,T[3]=k;let[O,M]=i.Util.singularValueDecompose2dScale((0,n.getCurrentTransform)(this.ctx)),{viewportScale:C}=this,L=Math.ceil(P*this.outputScaleX*C),$=Math.ceil(k*this.outputScaleY*C);this.annotationCanvas=this.canvasFactory.create(L,$);let{canvas:B,context:D}=this.annotationCanvas;this.annotationCanvasMap.set(A,B),this.annotationCanvas.savedCtx=this.ctx,this.ctx=D,this.ctx.save(),this.ctx.setTransform(O,0,0,-M,0,k*M),K(this.ctx)}else K(this.ctx),this.ctx.rect(T[0],T[1],P,k),this.ctx.clip(),this.endPath()}this.current=new R(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...I),this.transform(...g)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(A){if(!this.contentVisible)return;let T=A.count;(A=this.getObject(A.data,A)).count=T;let I=this.ctx,g=this.processingType3;if(g&&(g.compiled===void 0&&(g.compiled=(function(O){let{width:M,height:C}=O;if(M>1e3||C>1e3)return null;let L=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),$=M+1,B,D,F,V=new Uint8Array($*(C+1)),Q=M+7&-8,Z=new Uint8Array(Q*C),et=0;for(let ct of O.data){let wt=128;for(;wt>0;)Z[et++]=ct&wt?0:255,wt>>=1}let rt=0;for(et=0,Z[et]!==0&&(V[0]=1,++rt),D=1;D<M;D++)Z[et]!==Z[et+1]&&(V[D]=Z[et]?2:1,++rt),et++;for(Z[et]!==0&&(V[D]=2,++rt),B=1;B<C;B++){et=B*Q,F=B*$,Z[et-Q]!==Z[et]&&(V[F]=Z[et]?1:8,++rt);let ct=(Z[et]?4:0)+(Z[et-Q]?8:0);for(D=1;D<M;D++)ct=(ct>>2)+(Z[et+1]?4:0)+(Z[et-Q+1]?8:0),L[ct]&&(V[F+D]=L[ct],++rt),et++;if(Z[et-Q]!==Z[et]&&(V[F+D]=Z[et]?2:4,++rt),rt>1e3)return null}for(et=Q*(C-1),F=B*$,Z[et]!==0&&(V[F]=8,++rt),D=1;D<M;D++)Z[et]!==Z[et+1]&&(V[F+D]=Z[et]?4:8,++rt),et++;if(Z[et]!==0&&(V[F+D]=4,++rt),rt>1e3)return null;let pt=new Int32Array([0,$,-1,0,-$,0,0,0,1]),dt=new Path2D;for(B=0;rt&&B<=C;B++){let ct=B*$,wt=ct+M;for(;ct<wt&&!V[ct];)ct++;if(ct===wt)continue;dt.moveTo(ct%$,B);let Pt=ct,xt=V[ct];do{let Dt=pt[xt];do ct+=Dt;while(!V[ct]);let Lt=V[ct];Lt!==5&&Lt!==10?(xt=Lt,V[ct]=0):(xt=Lt&51*xt>>4,V[ct]&=xt>>2|xt<<2),dt.lineTo(ct%$,ct/$|0),V[ct]||--rt}while(Pt!==ct);--B}return Z=null,V=null,function(ct){ct.save(),ct.scale(1/M,-1/C),ct.translate(0,-C),ct.fill(dt),ct.beginPath(),ct.restore()}})(A)),g.compiled)){g.compiled(I);return}let v=this._createMaskCanvas(A),P=v.canvas;I.save(),I.setTransform(1,0,0,1,0,0),I.drawImage(P,v.offsetX,v.offsetY),I.restore(),this.compose()}paintImageMaskXObjectRepeat(A,T,I=0,g=0,v,P){if(!this.contentVisible)return;A=this.getObject(A.data,A);let k=this.ctx;k.save();let O=(0,n.getCurrentTransform)(k);k.transform(T,I,g,v,0,0);let M=this._createMaskCanvas(A);k.setTransform(1,0,0,1,M.offsetX-O[4],M.offsetY-O[5]);for(let C=0,L=P.length;C<L;C+=2){let $=i.Util.transform(O,[T,I,g,v,P[C],P[C+1]]),[B,D]=i.Util.applyTransform([0,0],$);k.drawImage(M.canvas,B,D)}k.restore(),this.compose()}paintImageMaskXObjectGroup(A){if(!this.contentVisible)return;let T=this.ctx,I=this.current.fillColor,g=this.current.patternFill;for(let v of A){let{data:P,width:k,height:O,transform:M}=v,C=this.cachedCanvases.getCanvas("maskCanvas",k,O),L=C.context;L.save(),H(L,this.getObject(P,v)),L.globalCompositeOperation="source-in",L.fillStyle=g?I.getPattern(L,this,(0,n.getCurrentTransformInverse)(T),o):I,L.fillRect(0,0,k,O),L.restore(),T.save(),T.transform(...M),T.scale(1,-1),S(T,C.canvas,0,0,k,O,0,-1,1,1),T.restore()}this.compose()}paintImageXObject(A){if(!this.contentVisible)return;let T=this.getObject(A);T?this.paintInlineImageXObject(T):(0,i.warn)("Dependent image isn't ready yet")}paintImageXObjectRepeat(A,T,I,g){if(!this.contentVisible)return;let v=this.getObject(A);if(!v){(0,i.warn)("Dependent image isn't ready yet");return}let P=v.width,k=v.height,O=[];for(let M=0,C=g.length;M<C;M+=2)O.push({transform:[T,0,0,I,g[M],g[M+1]],x:0,y:0,w:P,h:k});this.paintInlineImageXObjectGroup(v,O)}applyTransferMapsToCanvas(A){return this.current.transferMaps!=="none"&&(A.filter=this.current.transferMaps,A.drawImage(A.canvas,0,0),A.filter="none"),A.canvas}applyTransferMapsToBitmap(A){if(this.current.transferMaps==="none")return A.bitmap;let{bitmap:T,width:I,height:g}=A,v=this.cachedCanvases.getCanvas("inlineImage",I,g),P=v.context;return P.filter=this.current.transferMaps,P.drawImage(T,0,0),P.filter="none",v.canvas}paintInlineImageXObject(A){if(!this.contentVisible)return;let T=A.width,I=A.height,g=this.ctx;if(this.save(),!i.isNodeJS){let{filter:k}=g;k!=="none"&&k!==""&&(g.filter="none")}g.scale(1/T,-1/I);let v;if(A.bitmap)v=this.applyTransferMapsToBitmap(A);else if(typeof HTMLElement=="function"&&A instanceof HTMLElement||!A.data)v=A;else{let k=this.cachedCanvases.getCanvas("inlineImage",T,I).context;N(k,A),v=this.applyTransferMapsToCanvas(k)}let P=this._scaleImage(v,(0,n.getCurrentTransformInverse)(g));g.imageSmoothingEnabled=W((0,n.getCurrentTransform)(g),A.interpolate),S(g,P.img,0,0,P.paintWidth,P.paintHeight,0,-I,T,I),this.compose(),this.restore()}paintInlineImageXObjectGroup(A,T){if(!this.contentVisible)return;let I=this.ctx,g;if(A.bitmap)g=A.bitmap;else{let v=A.width,P=A.height,k=this.cachedCanvases.getCanvas("inlineImage",v,P).context;N(k,A),g=this.applyTransferMapsToCanvas(k)}for(let v of T)I.save(),I.transform(...v.transform),I.scale(1,-1),S(I,g,v.x,v.y,v.w,v.h,0,-1,1,1),I.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(A){}markPointProps(A,T){}beginMarkedContent(A){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(A,T){A==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(T)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(A){let T=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(A);let I=this.ctx;this.pendingClip&&(T||(this.pendingClip===lt?I.clip("evenodd"):I.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),I.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let A=(0,n.getCurrentTransform)(this.ctx);if(A[1]===0&&A[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(A[0]),Math.abs(A[3]));else{let T=Math.abs(A[0]*A[3]-A[2]*A[1]),I=Math.hypot(A[0],A[2]),g=Math.hypot(A[1],A[3]);this._cachedGetSinglePixelWidth=Math.max(I,g)/T}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:A}=this.current,{a:T,b:I,c:g,d:v}=this.ctx.getTransform(),P,k;if(I===0&&g===0){let O=Math.abs(T),M=Math.abs(v);if(O===M)if(A===0)P=k=1/O;else{let C=O*A;P=k=C<1?1/C:1}else if(A===0)P=1/O,k=1/M;else{let C=O*A,L=M*A;P=C<1?1/C:1,k=L<1?1/L:1}}else{let O=Math.abs(T*v-I*g),M=Math.hypot(T,I),C=Math.hypot(g,v);if(A===0)P=C/O,k=M/O;else{let L=A*O;P=C>L?C/L:1,k=M>L?M/L:1}}this._cachedScaleForStroking[0]=P,this._cachedScaleForStroking[1]=k}return this._cachedScaleForStroking}rescaleAndStroke(A){let{ctx:T}=this,{lineWidth:I}=this.current,[g,v]=this.getScaleForStroking();if(T.lineWidth=I||1,g===1&&v===1){T.stroke();return}let P=T.getLineDash();if(A&&T.save(),T.scale(g,v),P.length>0){let k=Math.max(g,v);T.setLineDash(P.map((O=>O/k))),T.lineDashOffset/=k}T.stroke(),A&&T.restore()}isContentVisible(){for(let A=this.markedContentStack.length-1;A>=0;A--)if(!this.markedContentStack[A].visible)return!1;return!0}}for(let G in i.OPS)nt.prototype[G]!==void 0&&(nt.prototype[i.OPS[G]]=nt.prototype[G])},419:(s,t,e)=>{e.d(t,{DOMCMapReaderFactory:()=>u,DOMCanvasFactory:()=>h,DOMFilterFactory:()=>l,DOMSVGFactory:()=>f,DOMStandardFontDataFactory:()=>a,PDFDateString:()=>R,PageViewport:()=>w,PixelsPerInch:()=>c,RenderingCancelledException:()=>E,StatTimer:()=>b,fetchData:()=>m,getColorValues:()=>z,getCurrentTransform:()=>K,getCurrentTransformInverse:()=>it,getFilenameFromUrl:()=>r,getPdfFilenameFromUrl:()=>d,getRGB:()=>H,getXfaPageViewport:()=>N,isDataScheme:()=>p,isPdfFile:()=>y,isValidFetchUrl:()=>x,noContextMenu:()=>_,setLayerDimensions:()=>at});var i=e(583),n=e(292);let o="http://www.w3.org/2000/svg";class c{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}class l extends i.BaseFilterFactory{#t;#e;#i;#n;#r;#s=0;constructor({docId:j,ownerDocument:W=globalThis.document}={}){super(),this.#i=j,this.#n=W}get#a(){return this.#t||=new Map}get#l(){return this.#r||=new Map}get#o(){if(!this.#e){let j=this.#n.createElement("div"),{style:W}=j;W.visibility="hidden",W.contain="strict",W.width=W.height=0,W.position="absolute",W.top=W.left=0,W.zIndex=-1;let Y=this.#n.createElementNS(o,"svg");Y.setAttribute("width",0),Y.setAttribute("height",0),this.#e=this.#n.createElementNS(o,"defs"),j.append(Y),Y.append(this.#e),this.#n.body.append(j)}return this.#e}addFilter(j){if(!j)return"none";let W,Y,tt,st,lt=this.#a.get(j);if(lt)return lt;if(j.length===1){let T=j[0],I=new Array(256);for(let g=0;g<256;g++)I[g]=T[g]/255;st=W=Y=tt=I.join(",")}else{let[T,I,g]=j,v=new Array(256),P=new Array(256),k=new Array(256);for(let O=0;O<256;O++)v[O]=T[O]/255,P[O]=I[O]/255,k[O]=g[O]/255;W=v.join(","),Y=P.join(","),tt=k.join(","),st=`${W}${Y}${tt}`}if(lt=this.#a.get(st),lt)return this.#a.set(j,lt),lt;let nt=`g_${this.#i}_transfer_map_${this.#s++}`,G=`url(#${nt})`;this.#a.set(j,G),this.#a.set(st,G);let A=this.#u(nt);return this.#c(W,Y,tt,A),G}addHCMFilter(j,W){let Y=`${j}-${W}`,tt="base",st=this.#l.get(tt);if(st?.key===Y||(st?(st.filter?.remove(),st.key=Y,st.url="none",st.filter=null):(st={key:Y,url:"none",filter:null},this.#l.set(tt,st)),!j||!W))return st.url;let lt=this.#f(j);j=n.Util.makeHexColor(...lt);let nt=this.#f(W);if(W=n.Util.makeHexColor(...nt),this.#o.style.color="",j==="#000000"&&W==="#ffffff"||j===W)return st.url;let G=new Array(256);for(let v=0;v<=255;v++){let P=v/255;G[v]=P<=.03928?P/12.92:((P+.055)/1.055)**2.4}let A=G.join(","),T=`g_${this.#i}_hcm_filter`,I=st.filter=this.#u(T);this.#c(A,A,A,I),this.#h(I);let g=(v,P)=>{let k=lt[v]/255,O=nt[v]/255,M=new Array(P+1);for(let C=0;C<=P;C++)M[C]=k+C/P*(O-k);return M.join(",")};return this.#c(g(0,5),g(1,5),g(2,5),I),st.url=`url(#${T})`,st.url}addHighlightHCMFilter(j,W,Y,tt,st){let lt=`${W}-${Y}-${tt}-${st}`,nt=this.#l.get(j);if(nt?.key===lt||(nt?(nt.filter?.remove(),nt.key=lt,nt.url="none",nt.filter=null):(nt={key:lt,url:"none",filter:null},this.#l.set(j,nt)),!W||!Y))return nt.url;let[G,A]=[W,Y].map(this.#f.bind(this)),T=Math.round(.2126*G[0]+.7152*G[1]+.0722*G[2]),I=Math.round(.2126*A[0]+.7152*A[1]+.0722*A[2]),[g,v]=[tt,st].map(this.#f.bind(this));I<T&&([T,I,g,v]=[I,T,v,g]),this.#o.style.color="";let P=(M,C,L)=>{let $=new Array(256),B=(I-T)/L,D=M/255,F=(C-M)/(255*L),V=0;for(let Q=0;Q<=L;Q++){let Z=Math.round(T+Q*B),et=D+Q*F;for(let rt=V;rt<=Z;rt++)$[rt]=et;V=Z+1}for(let Q=V;Q<256;Q++)$[Q]=$[V-1];return $.join(",")},k=`g_${this.#i}_hcm_${j}_filter`,O=nt.filter=this.#u(k);return this.#h(O),this.#c(P(g[0],v[0],5),P(g[1],v[1],5),P(g[2],v[2],5),O),nt.url=`url(#${k})`,nt.url}destroy(j=!1){(!j||this.#l.size===0)&&(this.#e&&(this.#e.parentNode.parentNode.remove(),this.#e=null),this.#t&&(this.#t.clear(),this.#t=null),this.#s=0)}#h(j){let W=this.#n.createElementNS(o,"feColorMatrix");W.setAttribute("type","matrix"),W.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),j.append(W)}#u(j){let W=this.#n.createElementNS(o,"filter");return W.setAttribute("color-interpolation-filters","sRGB"),W.setAttribute("id",j),this.#o.append(W),W}#d(j,W,Y){let tt=this.#n.createElementNS(o,W);tt.setAttribute("type","discrete"),tt.setAttribute("tableValues",Y),j.append(tt)}#c(j,W,Y,tt){let st=this.#n.createElementNS(o,"feComponentTransfer");tt.append(st),this.#d(st,"feFuncR",j),this.#d(st,"feFuncG",W),this.#d(st,"feFuncB",Y)}#f(j){return this.#o.style.color=j,H(getComputedStyle(this.#o).getPropertyValue("color"))}}class h extends i.BaseCanvasFactory{constructor({ownerDocument:j=globalThis.document}={}){super(),this._document=j}_createCanvas(j,W){let Y=this._document.createElement("canvas");return Y.width=j,Y.height=W,Y}}async function m(X,j="text"){if(x(X,document.baseURI)){let W=await fetch(X);if(!W.ok)throw new Error(W.statusText);switch(j){case"arraybuffer":return W.arrayBuffer();case"blob":return W.blob();case"json":return W.json()}return W.text()}return new Promise(((W,Y)=>{let tt=new XMLHttpRequest;tt.open("GET",X,!0),tt.responseType=j,tt.onreadystatechange=()=>{if(tt.readyState===XMLHttpRequest.DONE)if(tt.status!==200&&tt.status!==0)Y(new Error(tt.statusText));else{switch(j){case"arraybuffer":case"blob":case"json":W(tt.response);return}W(tt.responseText)}},tt.send(null)}))}class u extends i.BaseCMapReaderFactory{_fetchData(j,W){return m(j,this.isCompressed?"arraybuffer":"text").then((Y=>({cMapData:Y instanceof ArrayBuffer?new Uint8Array(Y):(0,n.stringToBytes)(Y),compressionType:W})))}}class a extends i.BaseStandardFontDataFactory{_fetchData(j){return m(j,"arraybuffer").then((W=>new Uint8Array(W)))}}class f extends i.BaseSVGFactory{_createSVG(j){return document.createElementNS(o,j)}}class w{constructor({viewBox:j,scale:W,rotation:Y,offsetX:tt=0,offsetY:st=0,dontFlip:lt=!1}){this.viewBox=j,this.scale=W,this.rotation=Y,this.offsetX=tt,this.offsetY=st;let nt=(j[2]+j[0])/2,G=(j[3]+j[1])/2,A,T,I,g,v,P,k,O;switch((Y%=360)<0&&(Y+=360),Y){case 180:A=-1,T=0,I=0,g=1;break;case 90:A=0,T=1,I=1,g=0;break;case 270:A=0,T=-1,I=-1,g=0;break;case 0:A=1,T=0,I=0,g=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}lt&&(I=-I,g=-g),A===0?(v=Math.abs(G-j[1])*W+tt,P=Math.abs(nt-j[0])*W+st,k=(j[3]-j[1])*W,O=(j[2]-j[0])*W):(v=Math.abs(nt-j[0])*W+tt,P=Math.abs(G-j[1])*W+st,k=(j[2]-j[0])*W,O=(j[3]-j[1])*W),this.transform=[A*W,T*W,I*W,g*W,v-A*W*nt-I*W*G,P-T*W*nt-g*W*G],this.width=k,this.height=O}get rawDims(){let{viewBox:j}=this;return(0,n.shadow)(this,"rawDims",{pageWidth:j[2]-j[0],pageHeight:j[3]-j[1],pageX:j[0],pageY:j[1]})}clone({scale:j=this.scale,rotation:W=this.rotation,offsetX:Y=this.offsetX,offsetY:tt=this.offsetY,dontFlip:st=!1}={}){return new w({viewBox:this.viewBox.slice(),scale:j,rotation:W,offsetX:Y,offsetY:tt,dontFlip:st})}convertToViewportPoint(j,W){return n.Util.applyTransform([j,W],this.transform)}convertToViewportRectangle(j){let W=n.Util.applyTransform([j[0],j[1]],this.transform),Y=n.Util.applyTransform([j[2],j[3]],this.transform);return[W[0],W[1],Y[0],Y[1]]}convertToPdfPoint(j,W){return n.Util.applyInverseTransform([j,W],this.transform)}}class E extends n.BaseException{constructor(j,W=0){super(j,"RenderingCancelledException"),this.extraDelay=W}}function p(X){let j=X.length,W=0;for(;W<j&&X[W].trim()==="";)W++;return X.substring(W,W+5).toLowerCase()==="data:"}function y(X){return typeof X=="string"&&/\.pdf$/i.test(X)}function r(X,j=!1){return j||([X]=X.split(/[#?]/,1)),X.substring(X.lastIndexOf("/")+1)}function d(X,j="document.pdf"){if(typeof X!="string")return j;if(p(X))return(0,n.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),j;let W=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,Y=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(X),tt=W.exec(Y[1])||W.exec(Y[2])||W.exec(Y[3]);if(tt&&(tt=tt[0],tt.includes("%")))try{tt=W.exec(decodeURIComponent(tt))[0]}catch{}return tt||j}class b{started=Object.create(null);times=[];time(j){j in this.started&&(0,n.warn)(`Timer is already running for ${j}`),this.started[j]=Date.now()}timeEnd(j){j in this.started||(0,n.warn)(`Timer has not been started for ${j}`),this.times.push({name:j,start:this.started[j],end:Date.now()}),delete this.started[j]}toString(){let j=[],W=0;for(let{name:Y}of this.times)W=Math.max(Y.length,W);for(let{name:Y,start:tt,end:st}of this.times)j.push(`${Y.padEnd(W)} ${st-tt}ms
|
|
11
|
-
`);return j.join("")}}function x(X,j){try{let{protocol:W}=j?new URL(X,j):new URL(X);return W==="http:"||W==="https:"}catch{return!1}}function _(X){X.preventDefault()}let S;class R{static toDateObject(j){if(!j||typeof j!="string")return null;S||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");let W=S.exec(j);if(!W)return null;let Y=parseInt(W[1],10),tt=parseInt(W[2],10);tt=tt>=1&&tt<=12?tt-1:0;let st=parseInt(W[3],10);st=st>=1&&st<=31?st:1;let lt=parseInt(W[4],10);lt=lt>=0&<<=23?lt:0;let nt=parseInt(W[5],10);nt=nt>=0&&nt<=59?nt:0;let G=parseInt(W[6],10);G=G>=0&&G<=59?G:0;let A=W[7]||"Z",T=parseInt(W[8],10);T=T>=0&&T<=23?T:0;let I=parseInt(W[9],10)||0;return I=I>=0&&I<=59?I:0,A==="-"?(lt+=T,nt+=I):A==="+"&&(lt-=T,nt-=I),new Date(Date.UTC(Y,tt,st,lt,nt,G))}}function N(X,{scale:j=1,rotation:W=0}){let{width:Y,height:tt}=X.attributes.style,st=[0,0,parseInt(Y),parseInt(tt)];return new w({viewBox:st,scale:j,rotation:W})}function H(X){if(X.startsWith("#")){let j=parseInt(X.slice(1),16);return[(16711680&j)>>16,(65280&j)>>8,255&j]}return X.startsWith("rgb(")?X.slice(4,-1).split(",").map((j=>parseInt(j))):X.startsWith("rgba(")?X.slice(5,-1).split(",").map((j=>parseInt(j))).slice(0,3):((0,n.warn)(`Not a valid color format: "${X}"`),[0,0,0])}function z(X){let j=document.createElement("span");j.style.visibility="hidden",document.body.append(j);for(let W of X.keys()){j.style.color=W;let Y=window.getComputedStyle(j).color;X.set(W,H(Y))}j.remove()}function K(X){let{a:j,b:W,c:Y,d:tt,e:st,f:lt}=X.getTransform();return[j,W,Y,tt,st,lt]}function it(X){let{a:j,b:W,c:Y,d:tt,e:st,f:lt}=X.getTransform().invertSelf();return[j,W,Y,tt,st,lt]}function at(X,j,W=!1,Y=!0){if(j instanceof w){let{pageWidth:tt,pageHeight:st}=j.rawDims,{style:lt}=X,nt=n.FeatureTest.isCSSRoundSupported,G=`var(--scale-factor) * ${tt}px`,A=`var(--scale-factor) * ${st}px`,T=nt?`round(${G}, 1px)`:`calc(${G})`,I=nt?`round(${A}, 1px)`:`calc(${A})`;W&&j.rotation%180!=0?(lt.width=I,lt.height=T):(lt.width=T,lt.height=I)}Y&&X.setAttribute("data-main-rotation",j.rotation)}},47:(s,t,e)=>{e.d(t,{DrawLayer:()=>o});var i=e(419),n=e(292);class o{#t=null;#e=0;#i=new Map;#n=new Map;constructor({pageIndex:l}){this.pageIndex=l}setParent(l){if(this.#t){if(this.#t!==l){if(this.#i.size>0)for(let h of this.#i.values())h.remove(),l.append(h);this.#t=l}}else this.#t=l}static get _svgFactory(){return(0,n.shadow)(this,"_svgFactory",new i.DOMSVGFactory)}static#r(l,{x:h=0,y:m=0,width:u=1,height:a=1}={}){let{style:f}=l;f.top=100*m+"%",f.left=100*h+"%",f.width=100*u+"%",f.height=100*a+"%"}#s(l){let h=o._svgFactory.create(1,1,!0);return this.#t.append(h),h.setAttribute("aria-hidden",!0),o.#r(h,l),h}#a(l,h){let m=o._svgFactory.createElement("clipPath");l.append(m);let u=`clip_${h}`;m.setAttribute("id",u),m.setAttribute("clipPathUnits","objectBoundingBox");let a=o._svgFactory.createElement("use");return m.append(a),a.setAttribute("href",`#${h}`),a.classList.add("clip"),u}highlight(l,h,m,u=!1){let a=this.#e++,f=this.#s(l.box);f.classList.add("highlight"),l.free&&f.classList.add("free");let w=o._svgFactory.createElement("defs");f.append(w);let E=o._svgFactory.createElement("path");w.append(E);let p=`path_p${this.pageIndex}_${a}`;E.setAttribute("id",p),E.setAttribute("d",l.toSVGPath()),u&&this.#n.set(a,E);let y=this.#a(w,p),r=o._svgFactory.createElement("use");return f.append(r),f.setAttribute("fill",h),f.setAttribute("fill-opacity",m),r.setAttribute("href",`#${p}`),this.#i.set(a,f),{id:a,clipPathId:`url(#${y})`}}highlightOutline(l){let h=this.#e++,m=this.#s(l.box);m.classList.add("highlightOutline");let u=o._svgFactory.createElement("defs");m.append(u);let a=o._svgFactory.createElement("path");u.append(a);let f=`path_p${this.pageIndex}_${h}`;a.setAttribute("id",f),a.setAttribute("d",l.toSVGPath()),a.setAttribute("vector-effect","non-scaling-stroke");let w;if(l.free){m.classList.add("free");let y=o._svgFactory.createElement("mask");u.append(y),w=`mask_p${this.pageIndex}_${h}`,y.setAttribute("id",w),y.setAttribute("maskUnits","objectBoundingBox");let r=o._svgFactory.createElement("rect");y.append(r),r.setAttribute("width","1"),r.setAttribute("height","1"),r.setAttribute("fill","white");let d=o._svgFactory.createElement("use");y.append(d),d.setAttribute("href",`#${f}`),d.setAttribute("stroke","none"),d.setAttribute("fill","black"),d.setAttribute("fill-rule","nonzero"),d.classList.add("mask")}let E=o._svgFactory.createElement("use");m.append(E),E.setAttribute("href",`#${f}`),w&&E.setAttribute("mask",`url(#${w})`);let p=E.cloneNode();return m.append(p),E.classList.add("mainOutline"),p.classList.add("secondaryOutline"),this.#i.set(h,m),h}finalizeLine(l,h){let m=this.#n.get(l);this.#n.delete(l),this.updateBox(l,h.box),m.setAttribute("d",h.toSVGPath())}updateLine(l,h){this.#i.get(l).firstChild.firstChild.setAttribute("d",h.toSVGPath())}removeFreeHighlight(l){this.remove(l),this.#n.delete(l)}updatePath(l,h){this.#n.get(l).setAttribute("d",h.toSVGPath())}updateBox(l,h){o.#r(this.#i.get(l),h)}show(l,h){this.#i.get(l).classList.toggle("hidden",!h)}rotate(l,h){this.#i.get(l).setAttribute("data-main-rotation",h)}changeColor(l,h){this.#i.get(l).setAttribute("fill",h)}changeOpacity(l,h){this.#i.get(l).setAttribute("fill-opacity",h)}addClass(l,h){this.#i.get(l).classList.add(h)}removeClass(l,h){this.#i.get(l).classList.remove(h)}remove(l){this.#t!==null&&(this.#i.get(l).remove(),this.#i.delete(l))}destroy(){this.#t=null;for(let l of this.#i.values())l.remove();this.#i.clear()}}},731:(s,t,e)=>{e.d(t,{AnnotationEditorLayer:()=>p});var i=e(292),n=e(310),o=e(830),c=e(976);let l=/\r\n?|\n/g;class h extends n.AnnotationEditor{#t=this.editorDivBlur.bind(this);#e=this.editorDivFocus.bind(this);#i=this.editorDivInput.bind(this);#n=this.editorDivKeydown.bind(this);#r=this.editorDivPaste.bind(this);#s;#a="";#l=`${this.id}-editor`;#o;#h=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let r=h.prototype,d=_=>_.isEmpty(),b=o.AnnotationEditorUIManager.TRANSLATE_SMALL,x=o.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new o.KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],r.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],r.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],r._translateEmpty,{args:[-b,0],checker:d}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],r._translateEmpty,{args:[-x,0],checker:d}],[["ArrowRight","mac+ArrowRight"],r._translateEmpty,{args:[b,0],checker:d}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],r._translateEmpty,{args:[x,0],checker:d}],[["ArrowUp","mac+ArrowUp"],r._translateEmpty,{args:[0,-b],checker:d}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],r._translateEmpty,{args:[0,-x],checker:d}],[["ArrowDown","mac+ArrowDown"],r._translateEmpty,{args:[0,b],checker:d}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],r._translateEmpty,{args:[0,x],checker:d}]]))}static _type="freetext";static _editorType=i.AnnotationEditorType.FREETEXT;constructor(r){super({...r,name:"freeTextEditor"}),this.#s=r.color||h._defaultColor||n.AnnotationEditor._defaultLineColor,this.#o=r.fontSize||h._defaultFontSize}static initialize(r,d){n.AnnotationEditor.initialize(r,d,{strings:["pdfjs-free-text-default-content"]});let b=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(b.getPropertyValue("--freetext-padding"))}static updateDefaultParams(r,d){switch(r){case i.AnnotationEditorParamsType.FREETEXT_SIZE:h._defaultFontSize=d;break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:h._defaultColor=d}}updateParams(r,d){switch(r){case i.AnnotationEditorParamsType.FREETEXT_SIZE:this.#u(d);break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:this.#d(d)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,h._defaultFontSize],[i.AnnotationEditorParamsType.FREETEXT_COLOR,h._defaultColor||n.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,this.#o],[i.AnnotationEditorParamsType.FREETEXT_COLOR,this.#s]]}#u(r){let d=x=>{this.editorDiv.style.fontSize=`calc(${x}px * var(--scale-factor))`,this.translate(0,-(x-this.#o)*this.parentScale),this.#o=x,this.#f()},b=this.#o;this.addCommands({cmd:d.bind(this,r),undo:d.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#d(r){let d=x=>{this.#s=this.editorDiv.style.color=x},b=this.#s;this.addCommands({cmd:d.bind(this,r),undo:d.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(r,d){this._uiManager.translateSelectedEditors(r,d,!0)}getInitialTranslation(){let r=this.parentScale;return[-h._internalPadding*r,-(h._internalPadding+this.#o)*r]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){this.isInEditMode()||(this.parent.setEditingState(!1),this.parent.updateToolbar(i.AnnotationEditorType.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.editorDiv.addEventListener("keydown",this.#n),this.editorDiv.addEventListener("focus",this.#e),this.editorDiv.addEventListener("blur",this.#t),this.editorDiv.addEventListener("input",this.#i),this.editorDiv.addEventListener("paste",this.#r))}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#l),this._isDraggable=!0,this.editorDiv.removeEventListener("keydown",this.#n),this.editorDiv.removeEventListener("focus",this.#e),this.editorDiv.removeEventListener("blur",this.#t),this.editorDiv.removeEventListener("input",this.#i),this.editorDiv.removeEventListener("paste",this.#r),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(r){this._focusEventsAllowed&&(super.focusin(r),r.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#c(){let r=[];this.editorDiv.normalize();for(let d of this.editorDiv.childNodes)r.push(h.#g(d));return r.join(`
|
|
12
|
-
`)}#f(){let[r,d]=this.parentDimensions,b;if(this.isAttachedToDOM)b=this.div.getBoundingClientRect();else{let{currentLayer:x,div:_}=this,S=_.style.display;_.style.display="hidden",x.div.append(this.div),b=_.getBoundingClientRect(),_.remove(),_.style.display=S}this.rotation%180==this.parentRotation%180?(this.width=b.width/r,this.height=b.height/d):(this.width=b.height/r,this.height=b.width/d),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let r=this.#a,d=this.#a=this.#c().trimEnd();if(r===d)return;let b=x=>{this.#a=x,x?(this.#p(),this._uiManager.rebuild(this),this.#f()):this.remove()};this.addCommands({cmd:()=>{b(d)},undo:()=>{b(r)},mustExec:!1}),this.#f()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(r){this.enterInEditMode()}keydown(r){r.target===this.div&&r.key==="Enter"&&(this.enterInEditMode(),r.preventDefault())}editorDivKeydown(r){h._keyboardManager.exec(this,r)}editorDivFocus(r){this.isEditing=!0}editorDivBlur(r){this.isEditing=!1}editorDivInput(r){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let r,d;this.width&&(r=this.x,d=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#l),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),n.AnnotationEditor._l10nPromise.get("pdfjs-free-text-default-content").then((x=>this.editorDiv?.setAttribute("default-content",x))),this.editorDiv.contentEditable=!0;let{style:b}=this.editorDiv;if(b.fontSize=`calc(${this.#o}px * var(--scale-factor))`,b.color=this.#s,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),(0,o.bindEvents)(this,this.div,["dblclick","keydown"]),this.width){let[x,_]=this.parentDimensions;if(this.annotationElementId){let{position:S}=this.#h,[R,N]=this.getInitialTranslation();[R,N]=this.pageTranslationToScreen(R,N);let[H,z]=this.pageDimensions,[K,it]=this.pageTranslation,at,X;switch(this.rotation){case 0:at=r+(S[0]-K)/H,X=d+this.height-(S[1]-it)/z;break;case 90:at=r+(S[0]-K)/H,X=d-(S[1]-it)/z,[R,N]=[N,-R];break;case 180:at=r-this.width+(S[0]-K)/H,X=d-(S[1]-it)/z,[R,N]=[-R,-N];break;case 270:at=r+(S[0]-K-this.height*z)/H,X=d+(S[1]-it-this.width*H)/z,[R,N]=[-N,R]}this.setAt(at*x,X*_,R,N)}else this.setAt(r*x,d*_,this.width*x,this.height*_);this.#p(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#g(r){return(r.nodeType===Node.TEXT_NODE?r.nodeValue:r.innerText).replaceAll(l,"")}editorDivPaste(r){let d=r.clipboardData||window.clipboardData,{types:b}=d;if(b.length===1&&b[0]==="text/plain")return;r.preventDefault();let x=h.#m(d.getData("text")||"").replaceAll(l,`
|
|
13
|
-
`);if(!x)return;let _=window.getSelection();if(!_.rangeCount)return;this.editorDiv.normalize(),_.deleteFromDocument();let S=_.getRangeAt(0);if(!x.includes(`
|
|
14
|
-
`)){S.insertNode(document.createTextNode(x)),this.editorDiv.normalize(),_.collapseToStart();return}let{startContainer:R,startOffset:N}=S,H=[],z=[];if(R.nodeType===Node.TEXT_NODE){let at=R.parentElement;if(z.push(R.nodeValue.slice(N).replaceAll(l,"")),at!==this.editorDiv){let X=H;for(let j of this.editorDiv.childNodes)j!==at?X.push(h.#g(j)):X=z}H.push(R.nodeValue.slice(0,N).replaceAll(l,""))}else if(R===this.editorDiv){let at=H,X=0;for(let j of this.editorDiv.childNodes)X++===N&&(at=z),at.push(h.#g(j))}this.#a=`${H.join(`
|
|
15
|
-
`)}${x}${z.join(`
|
|
16
|
-
`)}`,this.#p();let K=new Range,it=H.reduce(((at,X)=>at+X.length),0);for(let{firstChild:at}of this.editorDiv.childNodes)if(at.nodeType===Node.TEXT_NODE){let X=at.nodeValue.length;if(it<=X){K.setStart(at,it),K.setEnd(at,it);break}it-=X}_.removeAllRanges(),_.addRange(K)}#p(){if(this.editorDiv.replaceChildren(),this.#a)for(let r of this.#a.split(`
|
|
17
|
-
`)){let d=document.createElement("div");d.append(r?document.createTextNode(r):document.createElement("br")),this.editorDiv.append(d)}}#y(){return this.#a.replaceAll("\xA0"," ")}static#m(r){return r.replaceAll(" ","\xA0")}get contentDiv(){return this.editorDiv}static deserialize(r,d,b){let x=null;if(r instanceof c.FreeTextAnnotationElement){let{data:{defaultAppearanceData:{fontSize:S,fontColor:R},rect:N,rotation:H,id:z},textContent:K,textPosition:it,parent:{page:{pageNumber:at}}}=r;if(!K||K.length===0)return null;x=r={annotationType:i.AnnotationEditorType.FREETEXT,color:Array.from(R),fontSize:S,value:K.join(`
|
|
18
|
-
`),position:it,pageIndex:at-1,rect:N,rotation:H,id:z,deleted:!1}}let _=super.deserialize(r,d,b);return _.#o=r.fontSize,_.#s=i.Util.makeHexColor(...r.color),_.#a=h.#m(r.value),_.annotationElementId=r.id||null,_.#h=x,_}serialize(r=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};let d=h._internalPadding*this.parentScale,b=this.getRect(d,d),x=n.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#s),_={annotationType:i.AnnotationEditorType.FREETEXT,color:x,fontSize:this.#o,value:this.#y(),pageIndex:this.pageIndex,rect:b,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return r?_:this.annotationElementId&&!this.#b(_)?null:(_.id=this.annotationElementId,_)}#b(r){let{value:d,fontSize:b,color:x,pageIndex:_}=this.#h;return this._hasBeenMoved||r.value!==d||r.fontSize!==b||r.color.some(((S,R)=>S!==x[R]))||r.pageIndex!==_}}var m=e(61),u=e(259),a=e(419);class f extends n.AnnotationEditor{#t=null;#e=0;#i;#n=null;#r=null;#s=null;#a=null;#l=0;#o=null;#h=null;#u=null;#d=!1;#c=this.#_.bind(this);#f=null;#g;#p=null;#y="";#m;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _l10nPromise;static _type="highlight";static _editorType=i.AnnotationEditorType.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){let r=f.prototype;return(0,i.shadow)(this,"_keyboardManager",new o.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],r._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],r._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],r._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],r._moveCaret,{args:[3]}]]))}constructor(r){super({...r,name:"highlightEditor"}),this.color=r.color||f._defaultColor,this.#m=r.thickness||f._defaultThickness,this.#g=r.opacity||f._defaultOpacity,this.#i=r.boxes||null,this.#b=r.methodOfCreation||"",this.#y=r.text||"",this._isDraggable=!1,r.highlightId>-1?(this.#d=!0,this.#C(r),this.#E()):(this.#t=r.anchorNode,this.#e=r.anchorOffset,this.#a=r.focusNode,this.#l=r.focusOffset,this.#S(),this.#E(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#d?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#m,methodOfCreation:this.#b}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(r){return{numberOfColors:r.get("color").size}}#S(){let r=new m.Outliner(this.#i,.001);this.#h=r.getOutlines(),{x:this.x,y:this.y,width:this.width,height:this.height}=this.#h.box;let d=new m.Outliner(this.#i,.0025,.001,this._uiManager.direction==="ltr");this.#s=d.getOutlines();let{lastPoint:b}=this.#s.box;this.#f=[(b[0]-this.x)/this.width,(b[1]-this.y)/this.height]}#C({highlightOutlines:r,highlightId:d,clipPathId:b}){if(this.#h=r,this.#s=r.getNewOutline(this.#m/2+1.5,.0025),d>=0)this.#u=d,this.#n=b,this.parent.drawLayer.finalizeLine(d,r),this.#p=this.parent.drawLayer.highlightOutline(this.#s);else if(this.parent){let H=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#u,r),this.parent.drawLayer.updateBox(this.#u,f.#A(this.#h.box,(H-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#p,this.#s),this.parent.drawLayer.updateBox(this.#p,f.#A(this.#s.box,H))}let{x,y:_,width:S,height:R}=r.box;switch(this.rotation){case 0:this.x=x,this.y=_,this.width=S,this.height=R;break;case 90:{let[H,z]=this.parentDimensions;this.x=_,this.y=1-x,this.width=S*z/H,this.height=R*H/z;break}case 180:this.x=1-x,this.y=1-_,this.width=S,this.height=R;break;case 270:{let[H,z]=this.parentDimensions;this.x=1-_,this.y=x,this.width=S*z/H,this.height=R*H/z;break}}let{lastPoint:N}=this.#s.box;this.#f=[(N[0]-x)/S,(N[1]-_)/R]}static initialize(r,d){n.AnnotationEditor.initialize(r,d),f._defaultColor||=d.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(r,d){switch(r){case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:f._defaultColor=d;break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:f._defaultThickness=d}}translateInPage(r,d){}get toolbarPosition(){return this.#f}updateParams(r,d){switch(r){case i.AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#R(d);break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#w(d)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR,f._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,f._defaultThickness]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.color||f._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,this.#m||f._defaultThickness],[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,this.#d]]}#R(r){let d=x=>{this.color=x,this.parent?.drawLayer.changeColor(this.#u,x),this.#r?.updateColor(x)},b=this.color;this.addCommands({cmd:d.bind(this,r),undo:d.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(r)},!0)}#w(r){let d=this.#m,b=x=>{this.#m=x,this.#x(x)};this.addCommands({cmd:b.bind(this,r),undo:b.bind(this,d),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:r},!0)}async addEditToolbar(){let r=await super.addEditToolbar();return r?(this._uiManager.highlightColors&&(this.#r=new u.ColorPicker({editor:this}),r.addColorPicker(this.#r)),r):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#T())}getBaseTranslation(){return[0,0]}getRect(r,d){return super.getRect(r,d,this.#T())}onceAdded(){this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#v(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#E(),this.isAttachedToDOM||this.parent.add(this)))}setParent(r){let d=!1;this.parent&&!r?this.#v():r&&(this.#E(r),d=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(r),this.show(this._isVisible),d&&this.select()}#x(r){if(!this.#d)return;this.#C({highlightOutlines:this.#h.getNewOutline(r/2)}),this.fixAndSetPosition();let[d,b]=this.parentDimensions;this.setDims(this.width*d,this.height*b)}#v(){this.#u!==null&&this.parent&&(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#p),this.#p=null)}#E(r=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#n}=r.drawLayer.highlight(this.#h,this.color,this.#g),this.#p=r.drawLayer.highlightOutline(this.#s),this.#o&&(this.#o.style.clipPath=this.#n))}static#A({x:r,y:d,width:b,height:x},_){switch(_){case 90:return{x:1-d-x,y:r,width:x,height:b};case 180:return{x:1-r-b,y:1-d-x,width:b,height:x};case 270:return{x:d,y:1-r-b,width:x,height:b}}return{x:r,y:d,width:b,height:x}}rotate(r){let{drawLayer:d}=this.parent,b;this.#d?(r=(r-this.rotation+360)%360,b=f.#A(this.#h.box,r)):b=f.#A(this,r),d.rotate(this.#u,r),d.rotate(this.#p,r),d.updateBox(this.#u,b),d.updateBox(this.#p,f.#A(this.#s.box,r))}render(){if(this.div)return this.div;let r=super.render();this.#y&&(r.setAttribute("aria-label",this.#y),r.setAttribute("role","mark")),this.#d?r.classList.add("free"):this.div.addEventListener("keydown",this.#c);let d=this.#o=document.createElement("div");r.append(d),d.setAttribute("aria-hidden","true"),d.className="internal",d.style.clipPath=this.#n;let[b,x]=this.parentDimensions;return this.setDims(this.width*b,this.height*x),(0,o.bindEvents)(this,this.#o,["pointerover","pointerleave"]),this.enableEditing(),r}pointerover(){this.parent.drawLayer.addClass(this.#p,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#p,"hovered")}#_(r){f._keyboardManager.exec(this,r)}_moveCaret(r){switch(this.parent.unselect(this),r){case 0:case 2:this.#P(!0);break;case 1:case 3:this.#P(!1)}}#P(r){if(!this.#t)return;let d=window.getSelection();r?d.setPosition(this.#t,this.#e):d.setPosition(this.#a,this.#l)}select(){super.select(),this.#p&&(this.parent?.drawLayer.removeClass(this.#p,"hovered"),this.parent?.drawLayer.addClass(this.#p,"selected"))}unselect(){super.unselect(),this.#p&&(this.parent?.drawLayer.removeClass(this.#p,"selected"),this.#d||this.#P(!1))}get _mustFixPosition(){return!this.#d}show(r=this._isVisible){super.show(r),this.parent&&(this.parent.drawLayer.show(this.#u,r),this.parent.drawLayer.show(this.#p,r))}#T(){return this.#d?this.rotation:0}#M(){if(this.#d)return null;let[r,d]=this.pageDimensions,b=this.#i,x=new Array(8*b.length),_=0;for(let{x:S,y:R,width:N,height:H}of b){let z=S*r,K=(1-R-H)*d;x[_]=x[_+4]=z,x[_+1]=x[_+3]=K,x[_+2]=x[_+6]=z+N*r,x[_+5]=x[_+7]=K+H*d,_+=8}return x}#k(r){return this.#h.serialize(r,this.#T())}static startHighlighting(r,d,{target:b,x,y:_}){let{x:S,y:R,width:N,height:H}=b.getBoundingClientRect(),z=X=>{this.#L(r,X)},K={capture:!0,passive:!1},it=X=>{X.preventDefault(),X.stopPropagation()},at=X=>{b.removeEventListener("pointermove",z),window.removeEventListener("blur",at),window.removeEventListener("pointerup",at),window.removeEventListener("pointerdown",it,K),window.removeEventListener("contextmenu",a.noContextMenu),this.#I(r,X)};window.addEventListener("blur",at),window.addEventListener("pointerup",at),window.addEventListener("pointerdown",it,K),window.addEventListener("contextmenu",a.noContextMenu),b.addEventListener("pointermove",z),this._freeHighlight=new m.FreeOutliner({x,y:_},[S,R,N,H],r.scale,this._defaultThickness/2,d,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=r.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static#L(r,d){this._freeHighlight.add(d)&&r.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#I(r,d){this._freeHighlight.isEmpty()?r.drawLayer.removeFreeHighlight(this._freeHighlightId):r.createAndAddNewEditor(d,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static deserialize(r,d,b){let x=super.deserialize(r,d,b),{rect:[_,S,R,N],color:H,quadPoints:z}=r;x.color=i.Util.makeHexColor(...H),x.#g=r.opacity;let[K,it]=x.pageDimensions;x.width=(R-_)/K,x.height=(N-S)/it;let at=x.#i=[];for(let X=0;X<z.length;X+=8)at.push({x:(z[4]-R)/K,y:(N-(1-z[X+5]))/it,width:(z[X+2]-z[X])/K,height:(z[X+5]-z[X+1])/it});return x.#S(),x}serialize(r=!1){if(this.isEmpty()||r)return null;let d=this.getRect(0,0),b=n.AnnotationEditor._colorManager.convert(this.color);return{annotationType:i.AnnotationEditorType.HIGHLIGHT,color:b,opacity:this.#g,thickness:this.#m,quadPoints:this.#M(),outlines:this.#k(d),pageIndex:this.pageIndex,rect:d,rotation:this.#T(),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}}class w extends n.AnnotationEditor{#t=0;#e=0;#i=this.canvasPointermove.bind(this);#n=this.canvasPointerleave.bind(this);#r=this.canvasPointerup.bind(this);#s=this.canvasPointerdown.bind(this);#a=null;#l=new Path2D;#o=!1;#h=!1;#u=!1;#d=null;#c=0;#f=0;#g=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=i.AnnotationEditorType.INK;constructor(r){super({...r,name:"inkEditor"}),this.color=r.color||null,this.thickness=r.thickness||null,this.opacity=r.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(r,d){n.AnnotationEditor.initialize(r,d)}static updateDefaultParams(r,d){switch(r){case i.AnnotationEditorParamsType.INK_THICKNESS:w._defaultThickness=d;break;case i.AnnotationEditorParamsType.INK_COLOR:w._defaultColor=d;break;case i.AnnotationEditorParamsType.INK_OPACITY:w._defaultOpacity=d/100}}updateParams(r,d){switch(r){case i.AnnotationEditorParamsType.INK_THICKNESS:this.#p(d);break;case i.AnnotationEditorParamsType.INK_COLOR:this.#y(d);break;case i.AnnotationEditorParamsType.INK_OPACITY:this.#m(d)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,w._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,w._defaultColor||n.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*w._defaultOpacity)]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,this.thickness||w._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,this.color||w._defaultColor||n.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*(this.opacity??w._defaultOpacity))]]}#p(r){let d=x=>{this.thickness=x,this.#N()},b=this.thickness;this.addCommands({cmd:d.bind(this,r),undo:d.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#y(r){let d=x=>{this.color=x,this.#_()},b=this.color;this.addCommands({cmd:d.bind(this,r),undo:d.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#m(r){let d=x=>{this.opacity=x,this.#_()};r/=100;let b=this.opacity;this.addCommands({cmd:d.bind(this,r),undo:d.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(this.#T(),this.#M()),this.isAttachedToDOM||(this.parent.add(this),this.#k()),this.#N()))}remove(){this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#a&&(clearTimeout(this.#a),this.#a=null),this.#d.disconnect(),this.#d=null,super.remove())}setParent(r){!this.parent&&r?this._uiManager.removeShouldRescale(this):this.parent&&r===null&&this._uiManager.addShouldRescale(this),super.setParent(r)}onScaleChanging(){let[r,d]=this.parentDimensions,b=this.width*r,x=this.height*d;this.setDimensions(b,x)}enableEditMode(){!this.#o&&this.canvas!==null&&(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",this.#s))}disableEditMode(){this.isInEditMode()&&this.canvas!==null&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",this.#s))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}#b(){let{parentRotation:r,parentDimensions:[d,b]}=this;switch(r){case 90:return[0,b,b,d];case 180:return[d,b,d,b];case 270:return[d,0,b,d];default:return[0,0,d,b]}}#S(){let{ctx:r,color:d,opacity:b,thickness:x,parentScale:_,scaleFactor:S}=this;r.lineWidth=x*_/S,r.lineCap="round",r.lineJoin="round",r.miterLimit=10,r.strokeStyle=`${d}${(0,o.opacityToHex)(b)}`}#C(r,d){this.canvas.addEventListener("contextmenu",a.noContextMenu),this.canvas.addEventListener("pointerleave",this.#n),this.canvas.addEventListener("pointermove",this.#i),this.canvas.addEventListener("pointerup",this.#r),this.canvas.removeEventListener("pointerdown",this.#s),this.isEditing=!0,this.#u||(this.#u=!0,this.#k(),this.thickness||=w._defaultThickness,this.color||=w._defaultColor||n.AnnotationEditor._defaultLineColor,this.opacity??=w._defaultOpacity),this.currentPath.push([r,d]),this.#h=!1,this.#S(),this.#g=()=>{this.#v(),this.#g&&window.requestAnimationFrame(this.#g)},window.requestAnimationFrame(this.#g)}#R(r,d){let[b,x]=this.currentPath.at(-1);if(this.currentPath.length>1&&r===b&&d===x)return;let _=this.currentPath,S=this.#l;_.push([r,d]),this.#h=!0,_.length<=2?(S.moveTo(..._[0]),S.lineTo(r,d)):(_.length===3&&(this.#l=S=new Path2D,S.moveTo(..._[0])),this.#E(S,..._.at(-3),..._.at(-2),r,d))}#w(){if(this.currentPath.length===0)return;let r=this.currentPath.at(-1);this.#l.lineTo(...r)}#x(r,d){this.#g=null,r=Math.min(Math.max(r,0),this.canvas.width),d=Math.min(Math.max(d,0),this.canvas.height),this.#R(r,d),this.#w();let b;if(this.currentPath.length!==1)b=this.#A();else{let S=[r,d];b=[[S,S.slice(),S.slice(),S]]}let x=this.#l,_=this.currentPath;this.currentPath=[],this.#l=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(_),this.paths.push(b),this.bezierPath2D.push(x),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(this.#T(),this.#M()),this.#N())},mustExec:!0})}#v(){if(!this.#h)return;this.#h=!1;let r=Math.ceil(this.thickness*this.parentScale),d=this.currentPath.slice(-3),b=d.map((S=>S[0])),x=d.map((S=>S[1])),{ctx:_}=(Math.min(...b),Math.max(...b),Math.min(...x),Math.max(...x),this);_.save(),_.clearRect(0,0,this.canvas.width,this.canvas.height);for(let S of this.bezierPath2D)_.stroke(S);_.stroke(this.#l),_.restore()}#E(r,d,b,x,_,S,R){let N=(d+x)/2,H=(b+_)/2,z=(x+S)/2,K=(_+R)/2;r.bezierCurveTo(N+2*(x-N)/3,H+2*(_-H)/3,z+2*(x-z)/3,K+2*(_-K)/3,z,K)}#A(){let r=this.currentPath;if(r.length<=2)return[[r[0],r[0],r.at(-1),r.at(-1)]];let d=[],b,[x,_]=r[0];for(b=1;b<r.length-2;b++){let[it,at]=r[b],[X,j]=r[b+1],W=(it+X)/2,Y=(at+j)/2,tt=[x+2*(it-x)/3,_+2*(at-_)/3],st=[W+2*(it-W)/3,Y+2*(at-Y)/3];d.push([[x,_],tt,st,[W,Y]]),[x,_]=[W,Y]}let[S,R]=r[b],[N,H]=r[b+1],z=[x+2*(S-x)/3,_+2*(R-_)/3],K=[N+2*(S-N)/3,H+2*(R-H)/3];return d.push([[x,_],z,K,[N,H]]),d}#_(){if(this.isEmpty()){this.#I();return}this.#S();let{canvas:r,ctx:d}=this;d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,r.width,r.height),this.#I();for(let b of this.bezierPath2D)d.stroke(b)}commit(){this.#o||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),this.#o=!0,this.div.classList.add("disabled"),this.#N(!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(r){this._focusEventsAllowed&&(super.focusin(r),this.enableEditMode())}canvasPointerdown(r){r.button===0&&this.isInEditMode()&&!this.#o&&(this.setInForeground(),r.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),this.#C(r.offsetX,r.offsetY))}canvasPointermove(r){r.preventDefault(),this.#R(r.offsetX,r.offsetY)}canvasPointerup(r){r.preventDefault(),this.#P(r)}canvasPointerleave(r){this.#P(r)}#P(r){this.canvas.removeEventListener("pointerleave",this.#n),this.canvas.removeEventListener("pointermove",this.#i),this.canvas.removeEventListener("pointerup",this.#r),this.canvas.addEventListener("pointerdown",this.#s),this.#a&&clearTimeout(this.#a),this.#a=setTimeout((()=>{this.#a=null,this.canvas.removeEventListener("contextmenu",a.noContextMenu)}),10),this.#x(r.offsetX,r.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#T(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#M(){this.#d=new ResizeObserver((r=>{let d=r[0].contentRect;d.width&&d.height&&this.setDimensions(d.width,d.height)})),this.#d.observe(this.div)}get isResizable(){return!this.isEmpty()&&this.#o}render(){if(this.div)return this.div;let r,d;this.width&&(r=this.x,d=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");let[b,x,_,S]=this.#b();if(this.setAt(b,x,0,0),this.setDims(_,S),this.#T(),this.width){let[R,N]=this.parentDimensions;this.setAspectRatio(this.width*R,this.height*N),this.setAt(r*R,d*N,this.width*R,this.height*N),this.#u=!0,this.#k(),this.setDims(this.width*R,this.height*N),this.#_(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#M(),this.div}#k(){if(!this.#u)return;let[r,d]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*r),this.canvas.height=Math.ceil(this.height*d),this.#I()}setDimensions(r,d){let b=Math.round(r),x=Math.round(d);if(this.#c===b&&this.#f===x)return;this.#c=b,this.#f=x,this.canvas.style.visibility="hidden";let[_,S]=this.parentDimensions;this.width=r/_,this.height=d/S,this.fixAndSetPosition(),this.#o&&this.#L(r,d),this.#k(),this.#_(),this.canvas.style.visibility="visible",this.fixDims()}#L(r,d){let b=this.#U(),x=(r-b)/this.#e,_=(d-b)/this.#t;this.scaleFactor=Math.min(x,_)}#I(){let r=this.#U()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+r,this.translationY*this.scaleFactor+r)}static#F(r){let d=new Path2D;for(let b=0,x=r.length;b<x;b++){let[_,S,R,N]=r[b];b===0&&d.moveTo(..._),d.bezierCurveTo(S[0],S[1],R[0],R[1],N[0],N[1])}return d}static#O(r,d,b){let[x,_,S,R]=d;switch(b){case 0:for(let N=0,H=r.length;N<H;N+=2)r[N]+=x,r[N+1]=R-r[N+1];break;case 90:for(let N=0,H=r.length;N<H;N+=2){let z=r[N];r[N]=r[N+1]+x,r[N+1]=z+_}break;case 180:for(let N=0,H=r.length;N<H;N+=2)r[N]=S-r[N],r[N+1]+=_;break;case 270:for(let N=0,H=r.length;N<H;N+=2){let z=r[N];r[N]=S-r[N+1],r[N+1]=R-z}break;default:throw new Error("Invalid rotation")}return r}static#V(r,d,b){let[x,_,S,R]=d;switch(b){case 0:for(let N=0,H=r.length;N<H;N+=2)r[N]-=x,r[N+1]=R-r[N+1];break;case 90:for(let N=0,H=r.length;N<H;N+=2){let z=r[N];r[N]=r[N+1]-_,r[N+1]=z-x}break;case 180:for(let N=0,H=r.length;N<H;N+=2)r[N]=S-r[N],r[N+1]-=_;break;case 270:for(let N=0,H=r.length;N<H;N+=2){let z=r[N];r[N]=R-r[N+1],r[N+1]=S-z}break;default:throw new Error("Invalid rotation")}return r}#W(r,d,b,x){let _=[],S=this.thickness/2,R=r*d+S,N=r*b+S;for(let H of this.paths){let z=[],K=[];for(let it=0,at=H.length;it<at;it++){let[X,j,W,Y]=H[it];if(X[0]===Y[0]&&X[1]===Y[1]&&at===1){let g=r*X[0]+R,v=r*X[1]+N;z.push(g,v),K.push(g,v);break}let tt=r*X[0]+R,st=r*X[1]+N,lt=r*j[0]+R,nt=r*j[1]+N,G=r*W[0]+R,A=r*W[1]+N,T=r*Y[0]+R,I=r*Y[1]+N;it===0&&(z.push(tt,st),K.push(tt,st)),z.push(lt,nt,G,A,T,I),K.push(lt,nt),it===at-1&&K.push(T,I)}_.push({bezier:w.#O(z,x,this.rotation),points:w.#O(K,x,this.rotation)})}return _}#z(){let r=1/0,d=-1/0,b=1/0,x=-1/0;for(let _ of this.paths)for(let[S,R,N,H]of _){let z=i.Util.bezierBoundingBox(...S,...R,...N,...H);r=Math.min(r,z[0]),b=Math.min(b,z[1]),d=Math.max(d,z[2]),x=Math.max(x,z[3])}return[r,b,d,x]}#U(){return this.#o?Math.ceil(this.thickness*this.parentScale):0}#N(r=!1){if(this.isEmpty())return;if(!this.#o){this.#_();return}let d=this.#z(),b=this.#U();this.#e=Math.max(n.AnnotationEditor.MIN_SIZE,d[2]-d[0]),this.#t=Math.max(n.AnnotationEditor.MIN_SIZE,d[3]-d[1]);let x=Math.ceil(b+this.#e*this.scaleFactor),_=Math.ceil(b+this.#t*this.scaleFactor),[S,R]=this.parentDimensions;this.width=x/S,this.height=_/R,this.setAspectRatio(x,_);let N=this.translationX,H=this.translationY;this.translationX=-d[0],this.translationY=-d[1],this.#k(),this.#_(),this.#c=x,this.#f=_,this.setDims(x,_);let z=r?b/this.scaleFactor/2:0;this.translate(N-this.translationX-z,H-this.translationY-z)}static deserialize(r,d,b){if(r instanceof c.InkAnnotationElement)return null;let x=super.deserialize(r,d,b);x.thickness=r.thickness,x.color=i.Util.makeHexColor(...r.color),x.opacity=r.opacity;let[_,S]=x.pageDimensions,R=x.width*_,N=x.height*S,H=x.parentScale,z=r.thickness/2;x.#o=!0,x.#c=Math.round(R),x.#f=Math.round(N);let{paths:K,rect:it,rotation:at}=r;for(let{bezier:j}of K){j=w.#V(j,it,at);let W=[];x.paths.push(W);let Y=H*(j[0]-z),tt=H*(j[1]-z);for(let lt=2,nt=j.length;lt<nt;lt+=6){let G=H*(j[lt]-z),A=H*(j[lt+1]-z),T=H*(j[lt+2]-z),I=H*(j[lt+3]-z),g=H*(j[lt+4]-z),v=H*(j[lt+5]-z);W.push([[Y,tt],[G,A],[T,I],[g,v]]),Y=g,tt=v}let st=this.#F(W);x.bezierPath2D.push(st)}let X=x.#z();return x.#e=Math.max(n.AnnotationEditor.MIN_SIZE,X[2]-X[0]),x.#t=Math.max(n.AnnotationEditor.MIN_SIZE,X[3]-X[1]),x.#L(R,N),x}serialize(){if(this.isEmpty())return null;let r=this.getRect(0,0),d=n.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);return{annotationType:i.AnnotationEditorType.INK,color:d,thickness:this.thickness,opacity:this.opacity,paths:this.#W(this.scaleFactor/this.parentScale,this.translationX,this.translationY,r),pageIndex:this.pageIndex,rect:r,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}}class E extends n.AnnotationEditor{#t=null;#e=null;#i=null;#n=null;#r=null;#s="";#a=null;#l=null;#o=null;#h=!1;#u=!1;static _type="stamp";static _editorType=i.AnnotationEditorType.STAMP;constructor(r){super({...r,name:"stampEditor"}),this.#n=r.bitmapUrl,this.#r=r.bitmapFile}static initialize(r,d){n.AnnotationEditor.initialize(r,d)}static get supportedTypes(){return(0,i.shadow)(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((r=>`image/${r}`)))}static get supportedTypesStr(){return(0,i.shadow)(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(r){return this.supportedTypes.includes(r)}static paste(r,d){d.pasteEditor(i.AnnotationEditorType.STAMP,{bitmapFile:r.getAsFile()})}#d(r,d=!1){r?(this.#t=r.bitmap,d||(this.#e=r.id,this.#h=r.isSvg),r.file&&(this.#s=r.file.name),this.#g()):this.remove()}#c(){this.#i=null,this._uiManager.enableWaiting(!1),this.#a&&this.div.focus()}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then((d=>this.#d(d,!0))).finally((()=>this.#c()));return}if(this.#n){let d=this.#n;this.#n=null,this._uiManager.enableWaiting(!0),this.#i=this._uiManager.imageManager.getFromUrl(d).then((b=>this.#d(b))).finally((()=>this.#c()));return}if(this.#r){let d=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#i=this._uiManager.imageManager.getFromFile(d).then((b=>this.#d(b))).finally((()=>this.#c()));return}let r=document.createElement("input");r.type="file",r.accept=E.supportedTypesStr,this.#i=new Promise((d=>{r.addEventListener("change",(async()=>{if(r.files&&r.files.length!==0){this._uiManager.enableWaiting(!0);let b=await this._uiManager.imageManager.getFromFile(r.files[0]);this.#d(b)}else this.remove();d()})),r.addEventListener("cancel",(()=>{this.remove(),d()}))})).finally((()=>this.#c())),r.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#a?.remove(),this.#a=null,this.#l?.disconnect(),this.#l=null,this.#o&&(clearTimeout(this.#o),this.#o=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),this.div!==null&&(this.#e&&this.#a===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))):this.#e&&this.#f()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#i||this.#t||this.#n||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let r,d;if(this.width&&(r=this.x,d=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#t?this.#g():this.#f(),this.width){let[b,x]=this.parentDimensions;this.setAt(r*b,d*x,this.width*b,this.height*x)}return this.div}#g(){let{div:r}=this,{width:d,height:b}=this.#t,[x,_]=this.pageDimensions,S=.75;if(this.width)d=this.width*x,b=this.height*_;else if(d>S*x||b>S*_){let z=Math.min(S*x/d,S*_/b);d*=z,b*=z}let[R,N]=this.parentDimensions;this.setDims(d*R/x,b*N/_),this._uiManager.enableWaiting(!1);let H=this.#a=document.createElement("canvas");r.append(H),r.hidden=!1,this.#m(d,b),this.#S(),this.#u||(this.parent.addUndoableEditor(this),this.#u=!0),this._reportTelemetry({action:"inserted_image"}),this.#s&&H.setAttribute("aria-label",this.#s)}#p(r,d){let[b,x]=this.parentDimensions;this.width=r/b,this.height=d/x,this.setDims(r,d),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this.#o!==null&&clearTimeout(this.#o),this.#o=setTimeout((()=>{this.#o=null,this.#m(r,d)}),200)}#y(r,d){let{width:b,height:x}=this.#t,_=b,S=x,R=this.#t;for(;_>2*r||S>2*d;){let N=_,H=S;_>2*r&&(_=_>=16384?Math.floor(_/2)-1:Math.ceil(_/2)),S>2*d&&(S=S>=16384?Math.floor(S/2)-1:Math.ceil(S/2));let z=new OffscreenCanvas(_,S);z.getContext("2d").drawImage(R,0,0,N,H,0,0,_,S),R=z.transferToImageBitmap()}return R}#m(r,d){r=Math.ceil(r),d=Math.ceil(d);let b=this.#a;if(!b||b.width===r&&b.height===d)return;b.width=r,b.height=d;let x=this.#h?this.#t:this.#y(r,d);if(this._uiManager.hasMLManager&&!this.hasAltText()){let S=new OffscreenCanvas(r,d);S.getContext("2d").drawImage(x,0,0,x.width,x.height,0,0,r,d),S.convertToBlob().then((R=>{let N=new FileReader;N.onload=()=>{let H=N.result;this._uiManager.mlGuess({service:"image-to-text",request:{imageData:H}}).then((z=>{let K=z?.output||"";this.parent&&K&&!this.hasAltText()&&(this.altTextData={altText:K,decorative:!1})}))},N.readAsDataURL(R)}))}let _=b.getContext("2d");_.filter=this._uiManager.hcmFilter,_.drawImage(x,0,0,x.width,x.height,0,0,r,d)}getImageForAltText(){return this.#a}#b(r){if(r){if(this.#h){let b=this._uiManager.imageManager.getSvgUrl(this.#e);if(b)return b}let d=document.createElement("canvas");return{width:d.width,height:d.height}=this.#t,d.getContext("2d").drawImage(this.#t,0,0),d.toDataURL()}if(this.#h){let[d,b]=this.pageDimensions,x=Math.round(this.width*d*a.PixelsPerInch.PDF_TO_CSS_UNITS),_=Math.round(this.height*b*a.PixelsPerInch.PDF_TO_CSS_UNITS),S=new OffscreenCanvas(x,_);return S.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,x,_),S.transferToImageBitmap()}return structuredClone(this.#t)}#S(){this.#l=new ResizeObserver((r=>{let d=r[0].contentRect;d.width&&d.height&&this.#p(d.width,d.height)})),this.#l.observe(this.div)}static deserialize(r,d,b){if(r instanceof c.StampAnnotationElement)return null;let x=super.deserialize(r,d,b),{rect:_,bitmapUrl:S,bitmapId:R,isSvg:N,accessibilityData:H}=r;R&&b.imageManager.isValidId(R)?x.#e=R:x.#n=S,x.#h=N;let[z,K]=x.pageDimensions;return x.width=(_[2]-_[0])/z,x.height=(_[3]-_[1])/K,H&&(x.altTextData=H),x}serialize(r=!1,d=null){if(this.isEmpty())return null;let b={annotationType:i.AnnotationEditorType.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#h,structTreeParentId:this._structTreeParentId};if(r)return b.bitmapUrl=this.#b(!0),b.accessibilityData=this.altTextData,b;let{decorative:x,altText:_}=this.altTextData;if(!x&&_&&(b.accessibilityData={type:"Figure",alt:_}),d===null)return b;d.stamps||=new Map;let S=this.#h?(b.rect[2]-b.rect[0])*(b.rect[3]-b.rect[1]):null;if(d.stamps.has(this.#e)){if(this.#h){let R=d.stamps.get(this.#e);S>R.area&&(R.area=S,R.serialized.bitmap.close(),R.serialized.bitmap=this.#b(!1))}}else d.stamps.set(this.#e,{area:S,serialized:b}),b.bitmap=this.#b(!1);return b}}class p{#t;#e=!1;#i=null;#n=null;#r=null;#s=null;#a=null;#l=new Map;#o=!1;#h=!1;#u=!1;#d=null;#c;static _initialized=!1;static#f=new Map([h,w,E,f].map((r=>[r._editorType,r])));constructor({uiManager:r,pageIndex:d,div:b,accessibilityManager:x,annotationLayer:_,drawLayer:S,textLayer:R,viewport:N,l10n:H}){let z=[...p.#f.values()];if(!p._initialized){p._initialized=!0;for(let K of z)K.initialize(H,r)}r.registerEditorTypes(z),this.#c=r,this.pageIndex=d,this.div=b,this.#t=x,this.#i=_,this.viewport=N,this.#d=R,this.drawLayer=S,this.#c.addLayer(this)}get isEmpty(){return this.#l.size===0}get isInvisible(){return this.isEmpty&&this.#c.getMode()===i.AnnotationEditorType.NONE}updateToolbar(r){this.#c.updateToolbar(r)}updateMode(r=this.#c.getMode()){switch(this.#b(),r){case i.AnnotationEditorType.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case i.AnnotationEditorType.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case i.AnnotationEditorType.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:d}=this.div;for(let b of p.#f.values())d.toggle(`${b._type}Editing`,r===b._editorType);this.div.hidden=!1}hasTextLayer(r){return r===this.#d?.div}addInkEditorIfNeeded(r){if(this.#c.getMode()===i.AnnotationEditorType.INK){if(!r){for(let d of this.#l.values())if(d.isEmpty()){d.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(r){this.#c.setEditingState(r)}addCommands(r){this.#c.addCommands(r)}togglePointerEvents(r=!1){this.div.classList.toggle("disabled",!r)}toggleAnnotationLayerPointerEvents(r=!1){this.#i?.div.classList.toggle("disabled",!r)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);let r=new Set;for(let b of this.#l.values())b.enableEditing(),b.annotationElementId&&r.add(b.annotationElementId);if(!this.#i)return;let d=this.#i.getEditableAnnotations();for(let b of d){if(b.hide(),this.#c.isDeletedAnnotationElement(b.data.id)||r.has(b.data.id))continue;let x=this.deserialize(b);x&&(this.addOrRebuild(x),x.enableEditing())}}disable(){this.#u=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let r=new Set;for(let b of this.#l.values())b.disableEditing(),b.annotationElementId&&b.serialize()===null?(this.getEditableAnnotation(b.annotationElementId)?.show(),b.remove()):r.add(b.annotationElementId);if(this.#i){let b=this.#i.getEditableAnnotations();for(let x of b){let{id:_}=x.data;r.has(_)||this.#c.isDeletedAnnotationElement(_)||x.show()}}this.#b(),this.isEmpty&&(this.div.hidden=!0);let{classList:d}=this.div;for(let b of p.#f.values())d.remove(`${b._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#u=!1}getEditableAnnotation(r){return this.#i?.getEditableAnnotation(r)||null}setActiveEditor(r){this.#c.getActive()!==r&&this.#c.setActiveEditor(r)}enableTextSelection(){this.div.tabIndex=-1,this.#d?.div&&!this.#s&&(this.#s=this.#g.bind(this),this.#d.div.addEventListener("pointerdown",this.#s),this.#d.div.classList.add("highlighting"))}disableTextSelection(){this.div.tabIndex=0,this.#d?.div&&this.#s&&(this.#d.div.removeEventListener("pointerdown",this.#s),this.#s=null,this.#d.div.classList.remove("highlighting"))}#g(r){if(this.#c.unselectAll(),r.target===this.#d.div){let{isMac:d}=i.FeatureTest.platform;if(r.button!==0||r.ctrlKey&&d)return;this.#c.showAllEditors("highlight",!0,!0),this.#d.div.classList.add("free"),f.startHighlighting(this,this.#c.direction==="ltr",r),this.#d.div.addEventListener("pointerup",(()=>{this.#d.div.classList.remove("free")}),{once:!0}),r.preventDefault()}}enableClick(){this.#r||(this.#r=this.pointerdown.bind(this),this.#n=this.pointerup.bind(this),this.div.addEventListener("pointerdown",this.#r),this.div.addEventListener("pointerup",this.#n))}disableClick(){this.#r&&(this.div.removeEventListener("pointerdown",this.#r),this.div.removeEventListener("pointerup",this.#n),this.#r=null,this.#n=null)}attach(r){this.#l.set(r.id,r);let{annotationElementId:d}=r;d&&this.#c.isDeletedAnnotationElement(d)&&this.#c.removeDeletedAnnotationElement(r)}detach(r){this.#l.delete(r.id),this.#t?.removePointerInTextLayer(r.contentDiv),!this.#u&&r.annotationElementId&&this.#c.addDeletedAnnotationElement(r)}remove(r){this.detach(r),this.#c.removeEditor(r),r.div.remove(),r.isAttachedToDOM=!1,this.#h||this.addInkEditorIfNeeded(!1)}changeParent(r){r.parent!==this&&(r.annotationElementId&&(this.#c.addDeletedAnnotationElement(r.annotationElementId),n.AnnotationEditor.deleteAnnotationElement(r),r.annotationElementId=null),this.attach(r),r.parent?.detach(r),r.setParent(this),r.div&&r.isAttachedToDOM&&(r.div.remove(),this.div.append(r.div)))}add(r){if(r.parent!==this||!r.isAttachedToDOM){if(this.changeParent(r),this.#c.addEditor(r),this.attach(r),!r.isAttachedToDOM){let d=r.render();this.div.append(d),r.isAttachedToDOM=!0}r.fixAndSetPosition(),r.onceAdded(),this.#c.addToAnnotationStorage(r),r._reportTelemetry(r.telemetryInitialData)}}moveEditorInDOM(r){if(!r.isAttachedToDOM)return;let{activeElement:d}=document;r.div.contains(d)&&!this.#a&&(r._focusEventsAllowed=!1,this.#a=setTimeout((()=>{this.#a=null,r.div.contains(document.activeElement)?r._focusEventsAllowed=!0:(r.div.addEventListener("focusin",(()=>{r._focusEventsAllowed=!0}),{once:!0}),d.focus())}),0)),r._structTreeParentId=this.#t?.moveElementInDOM(this.div,r.div,r.contentDiv,!0)}addOrRebuild(r){r.needsToBeRebuilt()?(r.parent||=this,r.rebuild(),r.show()):this.add(r)}addUndoableEditor(r){this.addCommands({cmd:()=>r._uiManager.rebuild(r),undo:()=>{r.remove()},mustExec:!1})}getNextId(){return this.#c.getId()}get#p(){return p.#f.get(this.#c.getMode())}#y(r){let d=this.#p;return d?new d.prototype.constructor(r):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(r,d){this.#c.updateToolbar(r),this.#c.updateMode(r);let{offsetX:b,offsetY:x}=this.#m(),_=this.getNextId(),S=this.#y({parent:this,id:_,x:b,y:x,uiManager:this.#c,isCentered:!0,...d});S&&this.add(S)}deserialize(r){return p.#f.get(r.annotationType??r.annotationEditorType)?.deserialize(r,this,this.#c)||null}createAndAddNewEditor(r,d,b={}){let x=this.getNextId(),_=this.#y({parent:this,id:x,x:r.offsetX,y:r.offsetY,uiManager:this.#c,isCentered:d,...b});return _&&this.add(_),_}#m(){let{x:r,y:d,width:b,height:x}=this.div.getBoundingClientRect(),_=Math.max(0,r),S=Math.max(0,d),R=(_+Math.min(window.innerWidth,r+b))/2-r,N=(S+Math.min(window.innerHeight,d+x))/2-d,[H,z]=this.viewport.rotation%180==0?[R,N]:[N,R];return{offsetX:H,offsetY:z}}addNewEditor(){this.createAndAddNewEditor(this.#m(),!0)}setSelected(r){this.#c.setSelected(r)}toggleSelected(r){this.#c.toggleSelected(r)}isSelected(r){return this.#c.isSelected(r)}unselect(r){this.#c.unselect(r)}pointerup(r){let{isMac:d}=i.FeatureTest.platform;!(r.button!==0||r.ctrlKey&&d)&&r.target===this.div&&this.#o&&(this.#o=!1,this.#e?this.#c.getMode()!==i.AnnotationEditorType.STAMP?this.createAndAddNewEditor(r,!1):this.#c.unselectAll():this.#e=!0)}pointerdown(r){if(this.#c.getMode()===i.AnnotationEditorType.HIGHLIGHT&&this.enableTextSelection(),this.#o){this.#o=!1;return}let{isMac:d}=i.FeatureTest.platform;if(r.button!==0||r.ctrlKey&&d||r.target!==this.div)return;this.#o=!0;let b=this.#c.getActive();this.#e=!b||b.isEmpty()}findNewParent(r,d,b){let x=this.#c.findParent(d,b);return x===null||x===this?!1:(x.changeParent(r),!0)}destroy(){this.#c.getActive()?.parent===this&&(this.#c.commitOrRemove(),this.#c.setActiveEditor(null)),this.#a&&(clearTimeout(this.#a),this.#a=null);for(let r of this.#l.values())this.#t?.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,this.#l.clear(),this.#c.removeLayer(this)}#b(){this.#h=!0;for(let r of this.#l.values())r.isEmpty()&&r.remove();this.#h=!1}render({viewport:r}){this.viewport=r,(0,a.setLayerDimensions)(this.div,r);for(let d of this.#c.getEditors(this.pageIndex))this.add(d),d.rebuild();this.updateMode()}update({viewport:r}){this.#c.commitOrRemove(),this.#b();let d=this.viewport.rotation,b=r.rotation;if(this.viewport=r,(0,a.setLayerDimensions)(this.div,{rotation:b}),d!==b)for(let x of this.#l.values())x.rotate(b);this.addInkEditorIfNeeded(!1)}get pageDimensions(){let{pageWidth:r,pageHeight:d}=this.viewport.rawDims;return[r,d]}get scale(){return this.#c.viewParameters.realScale}}},259:(s,t,e)=>{e.d(t,{ColorPicker:()=>c});var i=e(292),n=e(830),o=e(419);class c{#t=this.#g.bind(this);#e=this.#y.bind(this);#i=null;#n=null;#r;#s=null;#a=!1;#l=!1;#o=null;#h;#u=null;#d;static get _keyboardManager(){return(0,i.shadow)(this,"_keyboardManager",new n.KeyboardManager([[["Escape","mac+Escape"],c.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],c.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],c.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],c.prototype._moveToPrevious],[["Home","mac+Home"],c.prototype._moveToBeginning],[["End","mac+End"],c.prototype._moveToEnd]]))}constructor({editor:h=null,uiManager:m=null}){h?(this.#l=!1,this.#d=i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.#o=h):(this.#l=!0,this.#d=i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR),this.#u=h?._uiManager||m,this.#h=this.#u._eventBus,this.#r=h?.color||this.#u?.highlightColors.values().next().value||"#FFFF98"}renderButton(){let h=this.#i=document.createElement("button");h.className="colorPicker",h.tabIndex="0",h.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),h.setAttribute("aria-haspopup",!0),h.addEventListener("click",this.#p.bind(this)),h.addEventListener("keydown",this.#t);let m=this.#n=document.createElement("span");return m.className="swatch",m.setAttribute("aria-hidden",!0),m.style.backgroundColor=this.#r,h.append(m),h}renderMainDropdown(){let h=this.#s=this.#c();return h.setAttribute("aria-orientation","horizontal"),h.setAttribute("aria-labelledby","highlightColorPickerLabel"),h}#c(){let h=document.createElement("div");h.addEventListener("contextmenu",o.noContextMenu),h.className="dropdown",h.role="listbox",h.setAttribute("aria-multiselectable",!1),h.setAttribute("aria-orientation","vertical"),h.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(let[m,u]of this.#u.highlightColors){let a=document.createElement("button");a.tabIndex="0",a.role="option",a.setAttribute("data-color",u),a.title=m,a.setAttribute("data-l10n-id",`pdfjs-editor-colorpicker-${m}`);let f=document.createElement("span");a.append(f),f.className="swatch",f.style.backgroundColor=u,a.setAttribute("aria-selected",u===this.#r),a.addEventListener("click",this.#f.bind(this,u)),h.append(a)}return h.addEventListener("keydown",this.#t),h}#f(h,m){m.stopPropagation(),this.#h.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:h})}_colorSelectFromKeyboard(h){if(h.target===this.#i){this.#p(h);return}let m=h.target.getAttribute("data-color");m&&this.#f(m,h)}_moveToNext(h){this.#m?h.target!==this.#i?h.target.nextSibling?.focus():this.#s.firstChild?.focus():this.#p(h)}_moveToPrevious(h){h.target!==this.#s?.firstChild&&h.target!==this.#i?(this.#m||this.#p(h),h.target.previousSibling?.focus()):this.#m&&this._hideDropdownFromKeyboard()}_moveToBeginning(h){this.#m?this.#s.firstChild?.focus():this.#p(h)}_moveToEnd(h){this.#m?this.#s.lastChild?.focus():this.#p(h)}#g(h){c._keyboardManager.exec(this,h)}#p(h){if(this.#m){this.hideDropdown();return}if(this.#a=h.detail===0,window.addEventListener("pointerdown",this.#e),this.#s){this.#s.classList.remove("hidden");return}let m=this.#s=this.#c();this.#i.append(m)}#y(h){this.#s?.contains(h.target)||this.hideDropdown()}hideDropdown(){this.#s?.classList.add("hidden"),window.removeEventListener("pointerdown",this.#e)}get#m(){return this.#s&&!this.#s.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#l||(this.#m?(this.hideDropdown(),this.#i.focus({preventScroll:!0,focusVisible:this.#a})):this.#o?.unselect())}updateColor(h){if(this.#n&&(this.#n.style.backgroundColor=h),!this.#s)return;let m=this.#u.highlightColors.values();for(let u of this.#s.children)u.setAttribute("aria-selected",m.next().value===h)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null,this.#s?.remove(),this.#s=null}}},310:(s,t,e)=>{e.d(t,{AnnotationEditor:()=>h});var i=e(830),n=e(292),o=e(419);class c{#t="";#e=!1;#i=null;#n=null;#r=null;#s=!1;#a=null;static _l10nPromise=null;constructor(a){this.#a=a}static initialize(a){c._l10nPromise||=a}async render(){let a=this.#i=document.createElement("button");a.className="altText";let f=await c._l10nPromise.get("pdfjs-editor-alt-text-button-label");a.textContent=f,a.setAttribute("aria-label",f),a.tabIndex="0",a.addEventListener("contextmenu",o.noContextMenu),a.addEventListener("pointerdown",(E=>E.stopPropagation()));let w=E=>{E.preventDefault(),this.#a._uiManager.editAltText(this.#a)};return a.addEventListener("click",w,{capture:!0}),a.addEventListener("keydown",(E=>{E.target===a&&E.key==="Enter"&&(this.#s=!0,w(E))})),await this.#l(),a}finish(){this.#i&&(this.#i.focus({focusVisible:this.#s}),this.#s=!1)}isEmpty(){return!this.#t&&!this.#e}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:a,decorative:f}){(this.#t!==a||this.#e!==f)&&(this.#t=a,this.#e=f,this.#l())}toggle(a=!1){this.#i&&(!a&&this.#r&&(clearTimeout(this.#r),this.#r=null),this.#i.disabled=!a)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null}async#l(){let a=this.#i;if(!a)return;if(!this.#t&&!this.#e){a.classList.remove("done"),this.#n?.remove();return}a.classList.add("done"),c._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((E=>{a.setAttribute("aria-label",E)}));let f=this.#n;if(!f){this.#n=f=document.createElement("span"),f.className="tooltip",f.setAttribute("role","tooltip");let E=f.id=`alt-text-tooltip-${this.#a.id}`;a.setAttribute("aria-describedby",E);let p=100;a.addEventListener("mouseenter",(()=>{this.#r=setTimeout((()=>{this.#r=null,this.#n.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})}),p)})),a.addEventListener("mouseleave",(()=>{this.#r&&(clearTimeout(this.#r),this.#r=null),this.#n?.classList.remove("show")}))}f.innerText=this.#e?await c._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#t,f.parentNode||a.append(f),this.#a.getImageForAltText()?.setAttribute("aria-describedby",f.id)}}var l=e(362);class h{#t=null;#e=null;#i=!1;#n=!1;#r=null;#s=null;#a=this.focusin.bind(this);#l=this.focusout.bind(this);#o=null;#h="";#u=!1;#d=null;#c=!1;#f=!1;#g=!1;#p=null;#y=0;#m=0;#b=null;_initialOptions=Object.create(null);_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#S=!1;#C=h._zIndex++;static _borderLineWidth=-1;static _colorManager=new i.ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let a=h.prototype._resizeWithKeyboard,f=i.AnnotationEditorUIManager.TRANSLATE_SMALL,w=i.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,n.shadow)(this,"_resizerKeyboardManager",new i.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],a,{args:[-f,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],a,{args:[-w,0]}],[["ArrowRight","mac+ArrowRight"],a,{args:[f,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],a,{args:[w,0]}],[["ArrowUp","mac+ArrowUp"],a,{args:[0,-f]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],a,{args:[0,-w]}],[["ArrowDown","mac+ArrowDown"],a,{args:[0,f]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],a,{args:[0,w]}],[["Escape","mac+Escape"],h.prototype._stopResizingWithKeyboard]]))}constructor(a){this.constructor===h&&(0,n.unreachable)("Cannot initialize AnnotationEditor."),this.parent=a.parent,this.id=a.id,this.width=this.height=null,this.pageIndex=a.parent.pageIndex,this.name=a.name,this.div=null,this._uiManager=a.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=a.isCentered,this._structTreeParentId=null;let{rotation:f,rawDims:{pageWidth:w,pageHeight:E,pageX:p,pageY:y}}=this.parent.viewport;this.rotation=f,this.pageRotation=(360+f-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[w,E],this.pageTranslation=[p,y];let[r,d]=this.parentDimensions;this.x=a.x/r,this.y=a.y/d,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return(0,n.shadow)(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(a){let f=new m({id:a.parent.getNextId(),parent:a.parent,uiManager:a._uiManager});f.annotationElementId=a.annotationElementId,f.deleted=!0,f._uiManager.addToAnnotationStorage(f)}static initialize(a,f,w){if(h._l10nPromise||=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map((p=>[p,a.get(p.replaceAll(/([A-Z])/g,(y=>`-${y.toLowerCase()}`)))]))),w?.strings)for(let p of w.strings)h._l10nPromise.set(p,a.get(p));if(h._borderLineWidth!==-1)return;let E=getComputedStyle(document.documentElement);h._borderLineWidth=parseFloat(E.getPropertyValue("--outline-width"))||0}static updateDefaultParams(a,f){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(a){return!1}static paste(a,f){(0,n.unreachable)("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#S}set _isDraggable(a){this.#S=a,this.div?.classList.toggle("draggable",a)}get isEnterHandled(){return!0}center(){let[a,f]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*f/(2*a),this.y+=this.width*a/(2*f);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*f/(2*a),this.y-=this.width*a/(2*f);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(a){this._uiManager.addCommands(a)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#C}setParent(a){a!==null?(this.pageIndex=a.pageIndex,this.pageDimensions=a.pageDimensions):this.#F(),this.parent=a}focusin(a){this._focusEventsAllowed&&(this.#u?this.#u=!1:this.parent.setSelected(this))}focusout(a){if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;a.relatedTarget?.closest(`#${this.id}`)||(a.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(a,f,w,E){let[p,y]=this.parentDimensions;[w,E]=this.screenToPageTranslation(w,E),this.x=(a+w)/p,this.y=(f+E)/y,this.fixAndSetPosition()}#R([a,f],w,E){[w,E]=this.screenToPageTranslation(w,E),this.x+=w/a,this.y+=E/f,this.fixAndSetPosition()}translate(a,f){this.#R(this.parentDimensions,a,f)}translateInPage(a,f){this.#d||=[this.x,this.y],this.#R(this.pageDimensions,a,f),this.div.scrollIntoView({block:"nearest"})}drag(a,f){this.#d||=[this.x,this.y];let[w,E]=this.parentDimensions;if(this.x+=a/w,this.y+=f/E,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:b,y:x}=this.div.getBoundingClientRect();this.parent.findNewParent(this,b,x)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:p,y}=this,[r,d]=this.getBaseTranslation();p+=r,y+=d,this.div.style.left=`${(100*p).toFixed(2)}%`,this.div.style.top=`${(100*y).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#d&&(this.#d[0]!==this.x||this.#d[1]!==this.y)}getBaseTranslation(){let[a,f]=this.parentDimensions,{_borderLineWidth:w}=h,E=w/a,p=w/f;switch(this.rotation){case 90:return[-E,p];case 180:return[E,p];case 270:return[E,-p];default:return[-E,-p]}}get _mustFixPosition(){return!0}fixAndSetPosition(a=this.rotation){let[f,w]=this.pageDimensions,{x:E,y:p,width:y,height:r}=this;if(y*=f,r*=w,E*=f,p*=w,this._mustFixPosition)switch(a){case 0:E=Math.max(0,Math.min(f-y,E)),p=Math.max(0,Math.min(w-r,p));break;case 90:E=Math.max(0,Math.min(f-r,E)),p=Math.min(w,Math.max(y,p));break;case 180:E=Math.min(f,Math.max(y,E)),p=Math.min(w,Math.max(r,p));break;case 270:E=Math.min(f,Math.max(r,E)),p=Math.max(0,Math.min(w-y,p))}this.x=E/=f,this.y=p/=w;let[d,b]=this.getBaseTranslation();E+=d,p+=b;let{style:x}=this.div;x.left=`${(100*E).toFixed(2)}%`,x.top=`${(100*p).toFixed(2)}%`,this.moveInDOM()}static#w(a,f,w){switch(w){case 90:return[f,-a];case 180:return[-a,-f];case 270:return[-f,a];default:return[a,f]}}screenToPageTranslation(a,f){return h.#w(a,f,this.parentRotation)}pageTranslationToScreen(a,f){return h.#w(a,f,360-this.parentRotation)}#x(a){switch(a){case 90:{let[f,w]=this.pageDimensions;return[0,-f/w,w/f,0]}case 180:return[-1,0,0,-1];case 270:{let[f,w]=this.pageDimensions;return[0,f/w,-w/f,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:a,pageDimensions:[f,w]}=this,E=f*a,p=w*a;return n.FeatureTest.isCSSRoundSupported?[Math.round(E),Math.round(p)]:[E,p]}setDims(a,f){let[w,E]=this.parentDimensions;this.div.style.width=`${(100*a/w).toFixed(2)}%`,this.#n||(this.div.style.height=`${(100*f/E).toFixed(2)}%`)}fixDims(){let{style:a}=this.div,{height:f,width:w}=a,E=w.endsWith("%"),p=!this.#n&&f.endsWith("%");if(E&&p)return;let[y,r]=this.parentDimensions;E||(a.width=`${(100*parseFloat(w)/y).toFixed(2)}%`),this.#n||p||(a.height=`${(100*parseFloat(f)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#v(){if(this.#r)return;this.#r=document.createElement("div"),this.#r.classList.add("resizers");let a=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"];for(let f of a){let w=document.createElement("div");this.#r.append(w),w.classList.add("resizer",f),w.setAttribute("data-resizer-name",f),w.addEventListener("pointerdown",this.#E.bind(this,f)),w.addEventListener("contextmenu",o.noContextMenu),w.tabIndex=-1}this.div.prepend(this.#r)}#E(a,f){f.preventDefault();let{isMac:w}=n.FeatureTest.platform;if(f.button!==0||f.ctrlKey&&w)return;this.#e?.toggle(!1);let E=this.#_.bind(this,a),p=this._isDraggable;this._isDraggable=!1;let y={passive:!0,capture:!0};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",E,y);let r=this.x,d=this.y,b=this.width,x=this.height,_=this.parent.div.style.cursor,S=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(f.target).cursor;let R=()=>{this.parent.togglePointerEvents(!0),this.#e?.toggle(!0),this._isDraggable=p,window.removeEventListener("pointerup",R),window.removeEventListener("blur",R),window.removeEventListener("pointermove",E,y),this.parent.div.style.cursor=_,this.div.style.cursor=S,this.#A(r,d,b,x)};window.addEventListener("pointerup",R),window.addEventListener("blur",R)}#A(a,f,w,E){let p=this.x,y=this.y,r=this.width,d=this.height;p===a&&y===f&&r===w&&d===E||this.addCommands({cmd:()=>{this.width=r,this.height=d,this.x=p,this.y=y;let[b,x]=this.parentDimensions;this.setDims(b*r,x*d),this.fixAndSetPosition()},undo:()=>{this.width=w,this.height=E,this.x=a,this.y=f;let[b,x]=this.parentDimensions;this.setDims(b*w,x*E),this.fixAndSetPosition()},mustExec:!0})}#_(a,f){let[w,E]=this.parentDimensions,p=this.x,y=this.y,r=this.width,d=this.height,b=h.MIN_SIZE/w,x=h.MIN_SIZE/E,_=P=>Math.round(1e4*P)/1e4,S=this.#x(this.rotation),R=(P,k)=>[S[0]*P+S[2]*k,S[1]*P+S[3]*k],N=this.#x(360-this.rotation),H,z,K=!1,it=!1;switch(a){case"topLeft":K=!0,H=(P,k)=>[0,0],z=(P,k)=>[P,k];break;case"topMiddle":H=(P,k)=>[P/2,0],z=(P,k)=>[P/2,k];break;case"topRight":K=!0,H=(P,k)=>[P,0],z=(P,k)=>[0,k];break;case"middleRight":it=!0,H=(P,k)=>[P,k/2],z=(P,k)=>[0,k/2];break;case"bottomRight":K=!0,H=(P,k)=>[P,k],z=(P,k)=>[0,0];break;case"bottomMiddle":H=(P,k)=>[P/2,k],z=(P,k)=>[P/2,0];break;case"bottomLeft":K=!0,H=(P,k)=>[0,k],z=(P,k)=>[P,0];break;case"middleLeft":it=!0,H=(P,k)=>[0,k/2],z=(P,k)=>[P,k/2]}let at=H(r,d),X=z(r,d),j=R(...X),W=_(p+j[0]),Y=_(y+j[1]),tt=1,st=1,[lt,nt]=this.screenToPageTranslation(f.movementX,f.movementY);[lt,nt]=(G=lt/w,A=nt/E,[N[0]*G+N[2]*A,N[1]*G+N[3]*A]);var G,A;if(K){let P=Math.hypot(r,d);tt=st=Math.max(Math.min(Math.hypot(X[0]-at[0]-lt,X[1]-at[1]-nt)/P,1/r,1/d),b/r,x/d)}else it?tt=Math.max(b,Math.min(1,Math.abs(X[0]-at[0]-lt)))/r:st=Math.max(x,Math.min(1,Math.abs(X[1]-at[1]-nt)))/d;let T=_(r*tt),I=_(d*st);j=R(...z(T,I));let g=W-j[0],v=Y-j[1];this.width=T,this.height=I,this.x=g,this.y=v,this.setDims(w*T,E*I),this.fixAndSetPosition()}altTextFinish(){this.#e?.finish()}async addEditToolbar(){return this.#o||this.#f?this.#o:(this.#o=new l.EditorToolbar(this),this.div.append(this.#o.render()),this.#e&&this.#o.addAltTextButton(await this.#e.render()),this.#o)}removeEditToolbar(){this.#o&&(this.#o.remove(),this.#o=null,this.#e?.destroy())}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#e||(c.initialize(h._l10nPromise),this.#e=new c(this),await this.addEditToolbar())}get altTextData(){return this.#e?.data}set altTextData(a){this.#e&&(this.#e.data=a)}hasAltText(){return!this.#e?.isEmpty()}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#i?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.div.addEventListener("focusin",this.#a),this.div.addEventListener("focusout",this.#l);let[a,f]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*f/a).toFixed(2)}%`,this.div.style.maxHeight=`${(100*a/f).toFixed(2)}%`);let[w,E]=this.getInitialTranslation();return this.translate(w,E),(0,i.bindEvents)(this,this.div,["pointerdown"]),this.div}pointerdown(a){let{isMac:f}=n.FeatureTest.platform;a.button!==0||a.ctrlKey&&f?a.preventDefault():(this.#u=!0,this._isDraggable?this.#T(a):this.#P(a))}#P(a){let{isMac:f}=n.FeatureTest.platform;a.ctrlKey&&!f||a.shiftKey||a.metaKey&&f?this.parent.toggleSelected(this):this.parent.setSelected(this)}#T(a){let f=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let w,E;f&&(this.div.classList.add("moving"),w={passive:!0,capture:!0},this.#y=a.clientX,this.#m=a.clientY,E=y=>{let{clientX:r,clientY:d}=y,[b,x]=this.screenToPageTranslation(r-this.#y,d-this.#m);this.#y=r,this.#m=d,this._uiManager.dragSelectedEditors(b,x)},window.addEventListener("pointermove",E,w));let p=()=>{window.removeEventListener("pointerup",p),window.removeEventListener("blur",p),f&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",E,w)),this.#u=!1,this._uiManager.endDragSession()||this.#P(a)};window.addEventListener("pointerup",p),window.addEventListener("blur",p)}moveInDOM(){this.#p&&clearTimeout(this.#p),this.#p=setTimeout((()=>{this.#p=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(a,f,w){a.changeParent(this),this.x=f,this.y=w,this.fixAndSetPosition()}getRect(a,f,w=this.rotation){let E=this.parentScale,[p,y]=this.pageDimensions,[r,d]=this.pageTranslation,b=a/E,x=f/E,_=this.x*p,S=this.y*y,R=this.width*p,N=this.height*y;switch(w){case 0:return[_+b+r,y-S-x-N+d,_+b+R+r,y-S-x+d];case 90:return[_+x+r,y-S+b+d,_+x+N+r,y-S+b+R+d];case 180:return[_-b-R+r,y-S+x+d,_-b+r,y-S+x+N+d];case 270:return[_-x-N+r,y-S-b-R+d,_-x+r,y-S-b+d];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(a,f){let[w,E,p,y]=a,r=p-w,d=y-E;switch(this.rotation){case 0:return[w,f-y,r,d];case 90:return[w,f-E,d,r];case 180:return[p,f-E,r,d];case 270:return[p,f-y,d,r];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#f=!0}disableEditMode(){this.#f=!1}isInEditMode(){return this.#f}shouldGetKeyboardEvents(){return this.#g}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){this.div?.addEventListener("focusin",this.#a),this.div?.addEventListener("focusout",this.#l)}rotate(a){}serialize(a=!1,f=null){(0,n.unreachable)("An editor must be serializable")}static deserialize(a,f,w){let E=new this.prototype.constructor({parent:f,id:f.getNextId(),uiManager:w});E.rotation=a.rotation;let[p,y]=E.pageDimensions,[r,d,b,x]=E.getRectInCurrentCoords(a.rect,y);return E.x=r/p,E.y=d/y,E.width=b/p,E.height=x/y,E}remove(){if(this.div.removeEventListener("focusin",this.#a),this.div.removeEventListener("focusout",this.#l),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#p&&(clearTimeout(this.#p),this.#p=null),this.#F(),this.removeEditToolbar(),this.#b){for(let a of this.#b.values())clearTimeout(a);this.#b=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#v(),this.#r.classList.remove("hidden"),(0,i.bindEvents)(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(a){if(!this.isResizable||a.target!==this.div||a.key!=="Enter")return;this._uiManager.setSelected(this),this.#s={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let f=this.#r.children;if(!this.#t){this.#t=Array.from(f);let y=this.#M.bind(this),r=this.#k.bind(this);for(let d of this.#t){let b=d.getAttribute("data-resizer-name");d.setAttribute("role","spinbutton"),d.addEventListener("keydown",y),d.addEventListener("blur",r),d.addEventListener("focus",this.#L.bind(this,b)),h._l10nPromise.get(`pdfjs-editor-resizer-label-${b}`).then((x=>d.setAttribute("aria-label",x)))}}let w=this.#t[0],E=0;for(let y of f){if(y===w)break;E++}let p=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(p!==E){if(p<E)for(let r=0;r<E-p;r++)this.#r.append(this.#r.firstChild);else if(p>E)for(let r=0;r<p-E;r++)this.#r.firstChild.before(this.#r.lastChild);let y=0;for(let r of f){let d=this.#t[y++].getAttribute("data-resizer-name");h._l10nPromise.get(`pdfjs-editor-resizer-label-${d}`).then((b=>r.setAttribute("aria-label",b)))}}this.#I(0),this.#g=!0,this.#r.firstChild.focus({focusVisible:!0}),a.preventDefault(),a.stopImmediatePropagation()}#M(a){h._resizerKeyboardManager.exec(this,a)}#k(a){this.#g&&a.relatedTarget?.parentNode!==this.#r&&this.#F()}#L(a){this.#h=this.#g?a:""}#I(a){if(this.#t)for(let f of this.#t)f.tabIndex=a}_resizeWithKeyboard(a,f){this.#g&&this.#_(this.#h,{movementX:a,movementY:f})}#F(){if(this.#g=!1,this.#I(-1),this.#s){let{savedX:a,savedY:f,savedWidth:w,savedHeight:E}=this.#s;this.#A(a,f,w,E),this.#s=null}}_stopResizingWithKeyboard(){this.#F(),this.div.focus()}select(){this.makeResizable(),this.div?.classList.add("selectedEditor"),this.#o?this.#o?.show():this.addEditToolbar().then((()=>{this.div?.classList.contains("selectedEditor")&&this.#o?.show()}))}unselect(){this.#r?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this.#o?.hide()}updateParams(a,f){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#c}set isEditing(a){this.#c=a,this.parent&&(a?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(a,f){this.#n=!0;let w=a/f,{style:E}=this.div;E.aspectRatio=w,E.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(a,f=!1){if(f){this.#b||=new Map;let{action:w}=a,E=this.#b.get(w);E&&clearTimeout(E),E=setTimeout((()=>{this._reportTelemetry(a),this.#b.delete(w),this.#b.size===0&&(this.#b=null)}),h._telemetryTimeout),this.#b.set(w,E)}else a.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:a}})}show(a=this._isVisible){this.div.classList.toggle("hidden",!a),this._isVisible=a}enable(){this.div&&(this.div.tabIndex=0),this.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}}class m extends h{constructor(a){super(a),this.annotationElementId=a.annotationElementId,this.deleted=!0}serialize(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex}}}},61:(s,t,e)=>{e.d(t,{FreeOutliner:()=>l,Outliner:()=>n});var i=e(292);class n{#t;#e=[];#i=[];constructor(u,a=0,f=0,w=!0){let E=1/0,p=-1/0,y=1/0,r=-1/0,d=10**-4;for(let{x:H,y:z,width:K,height:it}of u){let at=Math.floor((H-a)/d)*d,X=Math.ceil((H+K+a)/d)*d,j=Math.floor((z-a)/d)*d,W=Math.ceil((z+it+a)/d)*d,Y=[at,j,W,!0],tt=[X,j,W,!1];this.#e.push(Y,tt),E=Math.min(E,at),p=Math.max(p,X),y=Math.min(y,j),r=Math.max(r,W)}let b=p-E+2*f,x=r-y+2*f,_=E-f,S=y-f,R=this.#e.at(w?-1:-2),N=[R[0],R[2]];for(let H of this.#e){let[z,K,it]=H;H[0]=(z-_)/b,H[1]=(K-S)/x,H[2]=(it-S)/x}this.#t={x:_,y:S,width:b,height:x,lastPoint:N}}getOutlines(){this.#e.sort(((a,f)=>a[0]-f[0]||a[1]-f[1]||a[2]-f[2]));let u=[];for(let a of this.#e)a[3]?(u.push(...this.#l(a)),this.#s(a)):(this.#a(a),u.push(...this.#l(a)));return this.#n(u)}#n(u){let a=[],f=new Set;for(let p of u){let[y,r,d]=p;a.push([y,r,p],[y,d,p])}a.sort(((p,y)=>p[1]-y[1]||p[0]-y[0]));for(let p=0,y=a.length;p<y;p+=2){let r=a[p][2],d=a[p+1][2];r.push(d),d.push(r),f.add(r),f.add(d)}let w=[],E;for(;f.size>0;){let p=f.values().next().value,[y,r,d,b,x]=p;f.delete(p);let _=y,S=r;for(E=[y,d],w.push(E);;){let R;if(f.has(b))R=b;else{if(!f.has(x))break;R=x}f.delete(R),[y,r,d,b,x]=R,_!==y&&(E.push(_,S,y,S===r?r:d),_=y),S=S===r?d:r}E.push(_,S)}return new c(w,this.#t)}#r(u){let a=this.#i,f=0,w=a.length-1;for(;f<=w;){let E=f+w>>1,p=a[E][0];if(p===u)return E;p<u?f=E+1:w=E-1}return w+1}#s([,u,a]){let f=this.#r(u);this.#i.splice(f,0,[u,a])}#a([,u,a]){let f=this.#r(u);for(let w=f;w<this.#i.length;w++){let[E,p]=this.#i[w];if(E!==u)break;if(E===u&&p===a){this.#i.splice(w,1);return}}for(let w=f-1;w>=0;w--){let[E,p]=this.#i[w];if(E!==u)break;if(E===u&&p===a){this.#i.splice(w,1);return}}}#l(u){let[a,f,w]=u,E=[[a,f,w]],p=this.#r(w);for(let y=0;y<p;y++){let[r,d]=this.#i[y];for(let b=0,x=E.length;b<x;b++){let[,_,S]=E[b];if(!(d<=_||S<=r))if(_>=r)if(S>d)E[b][1]=d;else{if(x===1)return[];E.splice(b,1),b--,x--}else E[b][2]=r,S>d&&E.push([a,d,S])}}return E}}class o{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(u,a){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof h}}class c extends o{#t;#e;constructor(u,a){super(),this.#e=u,this.#t=a}toSVGPath(){let u=[];for(let a of this.#e){let[f,w]=a;u.push(`M${f} ${w}`);for(let E=2;E<a.length;E+=2){let p=a[E],y=a[E+1];p===f?(u.push(`V${y}`),w=y):y===w&&(u.push(`H${p}`),f=p)}u.push("Z")}return u.join(" ")}serialize([u,a,f,w],E){let p=[],y=f-u,r=w-a;for(let d of this.#e){let b=new Array(d.length);for(let x=0;x<d.length;x+=2)b[x]=u+d[x]*y,b[x+1]=w-d[x+1]*r;p.push(b)}return p}get box(){return this.#t}}class l{#t;#e=[];#i;#n;#r=[];#s=new Float64Array(18);#a;#l;#o;#h;#u;#d;#c=[];static#f=8;static#g=2;static#p=l.#f+l.#g;constructor({x:u,y:a},f,w,E,p,y=0){this.#t=f,this.#d=E*w,this.#n=p,this.#s.set([NaN,NaN,NaN,NaN,u,a],6),this.#i=y,this.#h=l.#f*w,this.#o=l.#p*w,this.#u=w,this.#c.push(u,a)}get free(){return!0}isEmpty(){return isNaN(this.#s[8])}#y(){let u=this.#s.subarray(4,6),a=this.#s.subarray(16,18),[f,w,E,p]=this.#t;return[(this.#a+(u[0]-a[0])/2-f)/E,(this.#l+(u[1]-a[1])/2-w)/p,(this.#a+(a[0]-u[0])/2-f)/E,(this.#l+(a[1]-u[1])/2-w)/p]}add({x:u,y:a}){this.#a=u,this.#l=a;let[f,w,E,p]=this.#t,[y,r,d,b]=this.#s.subarray(8,12),x=u-d,_=a-b,S=Math.hypot(x,_);if(S<this.#o)return!1;let R=S-this.#h,N=R/S,H=N*x,z=N*_,K=y,it=r;y=d,r=b,d+=H,b+=z,this.#c?.push(u,a);let at=H/R,X=-z/R*this.#d,j=at*this.#d;return this.#s.set(this.#s.subarray(2,8),0),this.#s.set([d+X,b+j],4),this.#s.set(this.#s.subarray(14,18),12),this.#s.set([d-X,b-j],16),isNaN(this.#s[6])?(this.#r.length===0&&(this.#s.set([y+X,r+j],2),this.#r.push(NaN,NaN,NaN,NaN,(y+X-f)/E,(r+j-w)/p),this.#s.set([y-X,r-j],14),this.#e.push(NaN,NaN,NaN,NaN,(y-X-f)/E,(r-j-w)/p)),this.#s.set([K,it,y,r,d,b],6),!this.isEmpty()):(this.#s.set([K,it,y,r,d,b],6),Math.abs(Math.atan2(it-r,K-y)-Math.atan2(z,H))<Math.PI/2?([y,r,d,b]=this.#s.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((y+d)/2-f)/E,((r+b)/2-w)/p),[y,r,K,it]=this.#s.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((K+y)/2-f)/E,((it+r)/2-w)/p),!0):([K,it,y,r,d,b]=this.#s.subarray(0,6),this.#r.push(((K+5*y)/6-f)/E,((it+5*r)/6-w)/p,((5*y+d)/6-f)/E,((5*r+b)/6-w)/p,((y+d)/2-f)/E,((r+b)/2-w)/p),[d,b,y,r,K,it]=this.#s.subarray(12,18),this.#e.push(((K+5*y)/6-f)/E,((it+5*r)/6-w)/p,((5*y+d)/6-f)/E,((5*r+b)/6-w)/p,((y+d)/2-f)/E,((r+b)/2-w)/p),!0))}toSVGPath(){if(this.isEmpty())return"";let u=this.#r,a=this.#e,f=this.#s.subarray(4,6),w=this.#s.subarray(16,18),[E,p,y,r]=this.#t,[d,b,x,_]=this.#y();if(isNaN(this.#s[6])&&!this.isEmpty())return`M${(this.#s[2]-E)/y} ${(this.#s[3]-p)/r} L${(this.#s[4]-E)/y} ${(this.#s[5]-p)/r} L${d} ${b} L${x} ${_} L${(this.#s[16]-E)/y} ${(this.#s[17]-p)/r} L${(this.#s[14]-E)/y} ${(this.#s[15]-p)/r} Z`;let S=[];S.push(`M${u[4]} ${u[5]}`);for(let R=6;R<u.length;R+=6)isNaN(u[R])?S.push(`L${u[R+4]} ${u[R+5]}`):S.push(`C${u[R]} ${u[R+1]} ${u[R+2]} ${u[R+3]} ${u[R+4]} ${u[R+5]}`);S.push(`L${(f[0]-E)/y} ${(f[1]-p)/r} L${d} ${b} L${x} ${_} L${(w[0]-E)/y} ${(w[1]-p)/r}`);for(let R=a.length-6;R>=6;R-=6)isNaN(a[R])?S.push(`L${a[R+4]} ${a[R+5]}`):S.push(`C${a[R]} ${a[R+1]} ${a[R+2]} ${a[R+3]} ${a[R+4]} ${a[R+5]}`);return S.push(`L${a[4]} ${a[5]} Z`),S.join(" ")}getOutlines(){let u=this.#r,a=this.#e,f=this.#s,w=f.subarray(4,6),E=f.subarray(16,18),[p,y,r,d]=this.#t,b=new Float64Array((this.#c?.length??0)+2);for(let z=0,K=b.length-2;z<K;z+=2)b[z]=(this.#c[z]-p)/r,b[z+1]=(this.#c[z+1]-y)/d;b[b.length-2]=(this.#a-p)/r,b[b.length-1]=(this.#l-y)/d;let[x,_,S,R]=this.#y();if(isNaN(f[6])&&!this.isEmpty()){let z=new Float64Array(36);return z.set([NaN,NaN,NaN,NaN,(f[2]-p)/r,(f[3]-y)/d,NaN,NaN,NaN,NaN,(f[4]-p)/r,(f[5]-y)/d,NaN,NaN,NaN,NaN,x,_,NaN,NaN,NaN,NaN,S,R,NaN,NaN,NaN,NaN,(f[16]-p)/r,(f[17]-y)/d,NaN,NaN,NaN,NaN,(f[14]-p)/r,(f[15]-y)/d],0),new h(z,b,this.#t,this.#u,this.#i,this.#n)}let N=new Float64Array(this.#r.length+24+this.#e.length),H=u.length;for(let z=0;z<H;z+=2)isNaN(u[z])?N[z]=N[z+1]=NaN:(N[z]=u[z],N[z+1]=u[z+1]);N.set([NaN,NaN,NaN,NaN,(w[0]-p)/r,(w[1]-y)/d,NaN,NaN,NaN,NaN,x,_,NaN,NaN,NaN,NaN,S,R,NaN,NaN,NaN,NaN,(E[0]-p)/r,(E[1]-y)/d],H),H+=24;for(let z=a.length-6;z>=6;z-=6)for(let K=0;K<6;K+=2)isNaN(a[z+K])?(N[H]=N[H+1]=NaN,H+=2):(N[H]=a[z+K],N[H+1]=a[z+K+1],H+=2);return N.set([NaN,NaN,NaN,NaN,a[4],a[5]],H),new h(N,b,this.#t,this.#u,this.#i,this.#n)}}class h extends o{#t;#e=null;#i;#n;#r;#s;#a;constructor(u,a,f,w,E,p){super(),this.#a=u,this.#r=a,this.#t=f,this.#s=w,this.#i=E,this.#n=p,this.#h(p);let{x:y,y:r,width:d,height:b}=this.#e;for(let x=0,_=u.length;x<_;x+=2)u[x]=(u[x]-y)/d,u[x+1]=(u[x+1]-r)/b;for(let x=0,_=a.length;x<_;x+=2)a[x]=(a[x]-y)/d,a[x+1]=(a[x+1]-r)/b}toSVGPath(){let u=[`M${this.#a[4]} ${this.#a[5]}`];for(let a=6,f=this.#a.length;a<f;a+=6)isNaN(this.#a[a])?u.push(`L${this.#a[a+4]} ${this.#a[a+5]}`):u.push(`C${this.#a[a]} ${this.#a[a+1]} ${this.#a[a+2]} ${this.#a[a+3]} ${this.#a[a+4]} ${this.#a[a+5]}`);return u.push("Z"),u.join(" ")}serialize([u,a,f,w],E){let p=f-u,y=w-a,r,d;switch(E){case 0:r=this.#l(this.#a,u,w,p,-y),d=this.#l(this.#r,u,w,p,-y);break;case 90:r=this.#o(this.#a,u,a,p,y),d=this.#o(this.#r,u,a,p,y);break;case 180:r=this.#l(this.#a,f,a,-p,y),d=this.#l(this.#r,f,a,-p,y);break;case 270:r=this.#o(this.#a,f,w,-p,-y),d=this.#o(this.#r,f,w,-p,-y)}return{outline:Array.from(r),points:[Array.from(d)]}}#l(u,a,f,w,E){let p=new Float64Array(u.length);for(let y=0,r=u.length;y<r;y+=2)p[y]=a+u[y]*w,p[y+1]=f+u[y+1]*E;return p}#o(u,a,f,w,E){let p=new Float64Array(u.length);for(let y=0,r=u.length;y<r;y+=2)p[y]=a+u[y+1]*w,p[y+1]=f+u[y]*E;return p}#h(u){let a=this.#a,f=a[4],w=a[5],E=f,p=w,y=f,r=w,d=f,b=w,x=u?Math.max:Math.min;for(let H=6,z=a.length;H<z;H+=6){if(isNaN(a[H]))E=Math.min(E,a[H+4]),p=Math.min(p,a[H+5]),y=Math.max(y,a[H+4]),r=Math.max(r,a[H+5]),b<a[H+5]?(d=a[H+4],b=a[H+5]):b===a[H+5]&&(d=x(d,a[H+4]));else{let K=i.Util.bezierBoundingBox(f,w,...a.slice(H,H+6));E=Math.min(E,K[0]),p=Math.min(p,K[1]),y=Math.max(y,K[2]),r=Math.max(r,K[3]),b<K[3]?(d=K[2],b=K[3]):b===K[3]&&(d=x(d,K[2]))}f=a[H+4],w=a[H+5]}let _=E-this.#i,S=p-this.#i,R=y-E+2*this.#i,N=r-p+2*this.#i;this.#e={x:_,y:S,width:R,height:N,lastPoint:[d,b]}}get box(){return this.#e}getNewOutline(u,a){let{x:f,y:w,width:E,height:p}=this.#e,[y,r,d,b]=this.#t,x=E*d,_=p*b,S=f*d+y,R=w*b+r,N=new l({x:this.#r[0]*x+S,y:this.#r[1]*_+R},this.#t,this.#s,u,this.#n,a??this.#i);for(let H=2;H<this.#r.length;H+=2)N.add({x:this.#r[H]*x+S,y:this.#r[H+1]*_+R});return N.getOutlines()}}},362:(s,t,e)=>{e.d(t,{EditorToolbar:()=>n,HighlightToolbar:()=>o});var i=e(419);class n{#t=null;#e=null;#i;#n=null;constructor(l){this.#i=l}render(){let l=this.#t=document.createElement("div");l.className="editToolbar",l.setAttribute("role","toolbar"),l.addEventListener("contextmenu",i.noContextMenu),l.addEventListener("pointerdown",n.#r);let h=this.#n=document.createElement("div");h.className="buttons",l.append(h);let m=this.#i.toolbarPosition;if(m){let{style:u}=l,a=this.#i._uiManager.direction==="ltr"?1-m[0]:m[0];u.insetInlineEnd=100*a+"%",u.top=`calc(${100*m[1]}% + var(--editor-toolbar-vert-offset))`}return this.#o(),l}static#r(l){l.stopPropagation()}#s(l){this.#i._focusEventsAllowed=!1,l.preventDefault(),l.stopPropagation()}#a(l){this.#i._focusEventsAllowed=!0,l.preventDefault(),l.stopPropagation()}#l(l){l.addEventListener("focusin",this.#s.bind(this),{capture:!0}),l.addEventListener("focusout",this.#a.bind(this),{capture:!0}),l.addEventListener("contextmenu",i.noContextMenu)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden")}#o(){let l=document.createElement("button");l.className="delete",l.tabIndex=0,l.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#i.editorType}-button`),this.#l(l),l.addEventListener("click",(h=>{this.#i._uiManager.delete()})),this.#n.append(l)}get#h(){let l=document.createElement("div");return l.className="divider",l}addAltTextButton(l){this.#l(l),this.#n.prepend(l,this.#h)}addColorPicker(l){this.#e=l;let h=l.renderButton();this.#l(h),this.#n.prepend(h,this.#h)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class o{#t=null;#e=null;#i;constructor(l){this.#i=l}#n(){let l=this.#e=document.createElement("div");l.className="editToolbar",l.setAttribute("role","toolbar"),l.addEventListener("contextmenu",i.noContextMenu);let h=this.#t=document.createElement("div");return h.className="buttons",l.append(h),this.#s(),l}#r(l,h){let m=0,u=0;for(let a of l){let f=a.y+a.height;if(f<m)continue;let w=a.x+(h?a.width:0);f>m?(u=w,m=f):h?w>u&&(u=w):w<u&&(u=w)}return[h?1-u:u,m]}show(l,h,m){let[u,a]=this.#r(h,m),{style:f}=this.#e||=this.#n();l.append(this.#e),f.insetInlineEnd=100*u+"%",f.top=`calc(${100*a}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#s(){let l=document.createElement("button");l.className="highlightButton",l.tabIndex=0,l.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");let h=document.createElement("span");l.append(h),h.className="visuallyHidden",h.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label"),l.addEventListener("contextmenu",i.noContextMenu),l.addEventListener("click",(()=>{this.#i.highlightSelection("floating_button")})),this.#t.append(l)}}},830:(s,t,e)=>{e.d(t,{AnnotationEditorUIManager:()=>w,ColorManager:()=>f,KeyboardManager:()=>a,bindEvents:()=>c,opacityToHex:()=>l});var i=e(292),n=e(419),o=e(362);function c(E,p,y){for(let r of y)p.addEventListener(r,E[r].bind(E))}function l(E){return Math.round(Math.min(255,Math.max(1,255*E))).toString(16).padStart(2,"0")}class h{#t=0;constructor(){}get id(){return`${i.AnnotationEditorPrefix}${this.#t++}`}}class m{#t=(0,i.getUuid)();#e=0;#i=null;static get _isSVGFittingCanvas(){let p=new OffscreenCanvas(1,3).getContext("2d"),y=new Image;y.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';let r=y.decode().then((()=>(p.drawImage(y,0,0,1,1,0,0,1,3),new Uint32Array(p.getImageData(0,0,1,1).data.buffer)[0]===0)));return(0,i.shadow)(this,"_isSVGFittingCanvas",r)}async#n(p,y){this.#i||=new Map;let r=this.#i.get(p);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let d;if(typeof y=="string"?(r.url=y,d=await(0,n.fetchData)(y,"blob")):d=r.file=y,d.type==="image/svg+xml"){let b=m._isSVGFittingCanvas,x=new FileReader,_=new Image,S=new Promise(((R,N)=>{_.onload=()=>{r.bitmap=_,r.isSvg=!0,R()},x.onload=async()=>{let H=r.svgUrl=x.result;_.src=await b?`${H}#svgView(preserveAspectRatio(none))`:H},_.onerror=x.onerror=N}));x.readAsDataURL(d),await S}else r.bitmap=await createImageBitmap(d);r.refCounter=1}catch(d){console.error(d),r=null}return this.#i.set(p,r),r&&this.#i.set(r.id,r),r}async getFromFile(p){let{lastModified:y,name:r,size:d,type:b}=p;return this.#n(`${y}_${r}_${d}_${b}`,p)}async getFromUrl(p){return this.#n(p,p)}async getFromId(p){this.#i||=new Map;let y=this.#i.get(p);return y?y.bitmap?(y.refCounter+=1,y):y.file?this.getFromFile(y.file):this.getFromUrl(y.url):null}getSvgUrl(p){let y=this.#i.get(p);return y?.isSvg?y.svgUrl:null}deleteId(p){this.#i||=new Map;let y=this.#i.get(p);y&&(y.refCounter-=1,y.refCounter===0&&(y.bitmap=null))}isValidId(p){return p.startsWith(`image_${this.#t}_`)}}class u{#t=[];#e=!1;#i;#n=-1;constructor(p=128){this.#i=p}add({cmd:p,undo:y,post:r,mustExec:d,type:b=NaN,overwriteIfSameType:x=!1,keepUndo:_=!1}){if(d&&p(),this.#e)return;let S={cmd:p,undo:y,post:r,type:b};if(this.#n===-1){this.#t.length>0&&(this.#t.length=0),this.#n=0,this.#t.push(S);return}if(x&&this.#t[this.#n].type===b){_&&(S.undo=this.#t[this.#n].undo),this.#t[this.#n]=S;return}let R=this.#n+1;R===this.#i?this.#t.splice(0,1):(this.#n=R,R<this.#t.length&&this.#t.splice(R)),this.#t.push(S)}undo(){if(this.#n===-1)return;this.#e=!0;let{undo:p,post:y}=this.#t[this.#n];p(),y?.(),this.#e=!1,this.#n-=1}redo(){if(this.#n<this.#t.length-1){this.#n+=1,this.#e=!0;let{cmd:p,post:y}=this.#t[this.#n];p(),y?.(),this.#e=!1}}hasSomethingToUndo(){return this.#n!==-1}hasSomethingToRedo(){return this.#n<this.#t.length-1}destroy(){this.#t=null}}class a{constructor(p){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:y}=i.FeatureTest.platform;for(let[r,d,b={}]of p)for(let x of r){let _=x.startsWith("mac+");y&&_?(this.callbacks.set(x.slice(4),{callback:d,options:b}),this.allKeys.add(x.split("+").at(-1))):!y&&!_&&(this.callbacks.set(x,{callback:d,options:b}),this.allKeys.add(x.split("+").at(-1)))}}#t(p){p.altKey&&this.buffer.push("alt"),p.ctrlKey&&this.buffer.push("ctrl"),p.metaKey&&this.buffer.push("meta"),p.shiftKey&&this.buffer.push("shift"),this.buffer.push(p.key);let y=this.buffer.join("+");return this.buffer.length=0,y}exec(p,y){if(!this.allKeys.has(y.key))return;let r=this.callbacks.get(this.#t(y));if(!r)return;let{callback:d,options:{bubbles:b=!1,args:x=[],checker:_=null}}=r;(!_||_(p,y))&&(d.bind(p,...x,y)(),b||(y.stopPropagation(),y.preventDefault()))}}class f{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let p=new Map([["CanvasText",null],["Canvas",null]]);return(0,n.getColorValues)(p),(0,i.shadow)(this,"_colors",p)}convert(p){let y=(0,n.getRGB)(p);if(!window.matchMedia("(forced-colors: active)").matches)return y;for(let[r,d]of this._colors)if(d.every(((b,x)=>b===y[x])))return f._colorsMapping.get(r);return y}getHexCode(p){let y=this._colors.get(p);return y?i.Util.makeHexColor(...y):p}}class w{#t=null;#e=new Map;#i=new Map;#n=null;#r=null;#s=new u;#a=0;#l=new Set;#o=null;#h=null;#u=new Set;#d=!1;#c=null;#f=null;#g=null;#p=!1;#y=null;#m=new h;#b=!1;#S=!1;#C=null;#R=null;#w=null;#x=i.AnnotationEditorType.NONE;#v=new Set;#E=null;#A=null;#_=null;#P=this.blur.bind(this);#T=this.focus.bind(this);#M=this.copy.bind(this);#k=this.cut.bind(this);#L=this.paste.bind(this);#I=this.keydown.bind(this);#F=this.keyup.bind(this);#O=this.onEditingAction.bind(this);#V=this.onPageChanging.bind(this);#W=this.onScaleChanging.bind(this);#z=this.#nt.bind(this);#U=this.onRotationChanging.bind(this);#N={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#j=[0,0];#B=null;#H=null;#K=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let p=w.prototype,y=x=>x.#H.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&x.hasSomethingToControl(),r=(x,{target:_})=>{if(_ instanceof HTMLInputElement){let{type:S}=_;return S!=="text"&&S!=="number"}return!0},d=this.TRANSLATE_SMALL,b=this.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new a([[["ctrl+a","mac+meta+a"],p.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],p.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],p.redo,{checker:r}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],p.delete,{checker:r}],[["Enter","mac+Enter"],p.addNewEditorFromKeyboard,{checker:(x,{target:_})=>!(_ instanceof HTMLButtonElement)&&x.#H.contains(_)&&!x.isEnterHandled}],[[" ","mac+ "],p.addNewEditorFromKeyboard,{checker:(x,{target:_})=>!(_ instanceof HTMLButtonElement)&&x.#H.contains(document.activeElement)}],[["Escape","mac+Escape"],p.unselectAll],[["ArrowLeft","mac+ArrowLeft"],p.translateSelectedEditors,{args:[-d,0],checker:y}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],p.translateSelectedEditors,{args:[-b,0],checker:y}],[["ArrowRight","mac+ArrowRight"],p.translateSelectedEditors,{args:[d,0],checker:y}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],p.translateSelectedEditors,{args:[b,0],checker:y}],[["ArrowUp","mac+ArrowUp"],p.translateSelectedEditors,{args:[0,-d],checker:y}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],p.translateSelectedEditors,{args:[0,-b],checker:y}],[["ArrowDown","mac+ArrowDown"],p.translateSelectedEditors,{args:[0,d],checker:y}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],p.translateSelectedEditors,{args:[0,b],checker:y}]]))}constructor(p,y,r,d,b,x,_,S,R){this.#H=p,this.#K=y,this.#n=r,this._eventBus=d,this._eventBus._on("editingaction",this.#O),this._eventBus._on("pagechanging",this.#V),this._eventBus._on("scalechanging",this.#W),this._eventBus._on("rotationchanging",this.#U),this.#rt(),this.#J(),this.#r=b.annotationStorage,this.#c=b.filterFactory,this.#A=x,this.#g=_||null,this.#d=S,this.#w=R||null,this.viewParameters={realScale:n.PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#Q(),this.#Y(),this._eventBus._off("editingaction",this.#O),this._eventBus._off("pagechanging",this.#V),this._eventBus._off("scalechanging",this.#W),this._eventBus._off("rotationchanging",this.#U);for(let p of this.#i.values())p.destroy();this.#i.clear(),this.#e.clear(),this.#u.clear(),this.#t=null,this.#v.clear(),this.#s.destroy(),this.#n?.destroy(),this.#y?.hide(),this.#y=null,this.#f&&(clearTimeout(this.#f),this.#f=null),this.#B&&(clearTimeout(this.#B),this.#B=null),this.#ot()}async mlGuess(p){return this.#w?.guess(p)||null}get hasMLManager(){return!!this.#w}get hcmFilter(){return(0,i.shadow)(this,"hcmFilter",this.#A?this.#c.addHCMFilter(this.#A.foreground,this.#A.background):"none")}get direction(){return(0,i.shadow)(this,"direction",getComputedStyle(this.#H).direction)}get highlightColors(){return(0,i.shadow)(this,"highlightColors",this.#g?new Map(this.#g.split(",").map((p=>p.split("=").map((y=>y.trim()))))):null)}get highlightColorNames(){return(0,i.shadow)(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(p=>p.reverse()))):null)}setMainHighlightColorPicker(p){this.#R=p}editAltText(p){this.#n?.editAltText(this,p)}onPageChanging({pageNumber:p}){this.#a=p-1}focusMainContainer(){this.#H.focus()}findParent(p,y){for(let r of this.#i.values()){let{x:d,y:b,width:x,height:_}=r.div.getBoundingClientRect();if(p>=d&&p<=d+x&&y>=b&&y<=b+_)return r}return null}disableUserSelect(p=!1){this.#K.classList.toggle("noUserSelect",p)}addShouldRescale(p){this.#u.add(p)}removeShouldRescale(p){this.#u.delete(p)}onScaleChanging({scale:p}){this.commitOrRemove(),this.viewParameters.realScale=p*n.PixelsPerInch.PDF_TO_CSS_UNITS;for(let y of this.#u)y.onScaleChanging()}onRotationChanging({pagesRotation:p}){this.commitOrRemove(),this.viewParameters.rotation=p}#q({anchorNode:p}){return p.nodeType===Node.TEXT_NODE?p.parentElement:p}highlightSelection(p=""){let y=document.getSelection();if(!y||y.isCollapsed)return;let{anchorNode:r,anchorOffset:d,focusNode:b,focusOffset:x}=y,_=y.toString(),S=this.#q(y).closest(".textLayer"),R=this.getSelectionBoxes(S);if(R){y.empty(),this.#x===i.AnnotationEditorType.NONE&&(this._eventBus.dispatch("showannotationeditorui",{source:this,mode:i.AnnotationEditorType.HIGHLIGHT}),this.showAllEditors("highlight",!0,!0));for(let N of this.#i.values())if(N.hasTextLayer(S)){N.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:p,boxes:R,anchorNode:r,anchorOffset:d,focusNode:b,focusOffset:x,text:_});break}}}#st(){let p=document.getSelection();if(!p||p.isCollapsed)return;let y=this.#q(p).closest(".textLayer"),r=this.getSelectionBoxes(y);r&&(this.#y||=new o.HighlightToolbar(this),this.#y.show(y,r,this.direction==="ltr"))}addToAnnotationStorage(p){p.isEmpty()||!this.#r||this.#r.has(p.id)||this.#r.setValue(p.id,p)}#nt(){let p=document.getSelection();if(!p||p.isCollapsed){this.#E&&(this.#y?.hide(),this.#E=null,this.#D({hasSelectedText:!1}));return}let{anchorNode:y}=p;if(y!==this.#E)if(this.#q(p).closest(".textLayer")){if(this.#y?.hide(),this.#E=y,this.#D({hasSelectedText:!0}),(this.#x===i.AnnotationEditorType.HIGHLIGHT||this.#x===i.AnnotationEditorType.NONE)&&(this.#x===i.AnnotationEditorType.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#p=this.isShiftKeyDown,!this.isShiftKeyDown)){let r=d=>{(d.type!=="pointerup"||d.button===0)&&(window.removeEventListener("pointerup",r),window.removeEventListener("blur",r),d.type==="pointerup"&&this.#X("main_toolbar"))};window.addEventListener("pointerup",r),window.addEventListener("blur",r)}}else this.#E&&(this.#y?.hide(),this.#E=null,this.#D({hasSelectedText:!1}))}#X(p=""){this.#x===i.AnnotationEditorType.HIGHLIGHT?this.highlightSelection(p):this.#d&&this.#st()}#rt(){document.addEventListener("selectionchange",this.#z)}#ot(){document.removeEventListener("selectionchange",this.#z)}#at(){window.addEventListener("focus",this.#T),window.addEventListener("blur",this.#P)}#Y(){window.removeEventListener("focus",this.#T),window.removeEventListener("blur",this.#P)}blur(){if(this.isShiftKeyDown=!1,this.#p&&(this.#p=!1,this.#X("main_toolbar")),!this.hasSelection)return;let{activeElement:p}=document;for(let y of this.#v)if(y.div.contains(p)){this.#C=[y,p],y._focusEventsAllowed=!1;break}}focus(){if(!this.#C)return;let[p,y]=this.#C;this.#C=null,y.addEventListener("focusin",(()=>{p._focusEventsAllowed=!0}),{once:!0}),y.focus()}#J(){window.addEventListener("keydown",this.#I),window.addEventListener("keyup",this.#F)}#Q(){window.removeEventListener("keydown",this.#I),window.removeEventListener("keyup",this.#F)}#Z(){document.addEventListener("copy",this.#M),document.addEventListener("cut",this.#k),document.addEventListener("paste",this.#L)}#tt(){document.removeEventListener("copy",this.#M),document.removeEventListener("cut",this.#k),document.removeEventListener("paste",this.#L)}addEditListeners(){this.#J(),this.#Z()}removeEditListeners(){this.#Q(),this.#tt()}copy(p){if(p.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let y=[];for(let r of this.#v){let d=r.serialize(!0);d&&y.push(d)}y.length!==0&&p.clipboardData.setData("application/pdfjs",JSON.stringify(y))}cut(p){this.copy(p),this.delete()}paste(p){p.preventDefault();let{clipboardData:y}=p;for(let b of y.items)for(let x of this.#h)if(x.isHandlingMimeForPasting(b.type)){x.paste(b,this.currentLayer);return}let r=y.getData("application/pdfjs");if(!r)return;try{r=JSON.parse(r)}catch(b){(0,i.warn)(`paste: "${b.message}".`);return}if(!Array.isArray(r))return;this.unselectAll();let d=this.currentLayer;try{let b=[];for(let S of r){let R=d.deserialize(S);if(!R)return;b.push(R)}let x=()=>{for(let S of b)this.#et(S);this.#it(b)},_=()=>{for(let S of b)S.remove()};this.addCommands({cmd:x,undo:_,mustExec:!0})}catch(b){(0,i.warn)(`paste: "${b.message}".`)}}keydown(p){this.isShiftKeyDown||p.key!=="Shift"||(this.isShiftKeyDown=!0),this.#x===i.AnnotationEditorType.NONE||this.isEditorHandlingKeyboard||w._keyboardManager.exec(this,p)}keyup(p){this.isShiftKeyDown&&p.key==="Shift"&&(this.isShiftKeyDown=!1,this.#p&&(this.#p=!1,this.#X("main_toolbar")))}onEditingAction({name:p}){switch(p){case"undo":case"redo":case"delete":case"selectAll":this[p]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#D(p){Object.entries(p).some((([y,r])=>this.#N[y]!==r))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#N,p)}),this.#x===i.AnnotationEditorType.HIGHLIGHT&&p.hasSelectedEditor===!1&&this.#$([[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]]))}#$(p){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:p})}setEditingState(p){p?(this.#at(),this.#Z(),this.#D({isEditing:this.#x!==i.AnnotationEditorType.NONE,isEmpty:this.#G(),hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:this.#s.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Y(),this.#tt(),this.#D({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(p){if(!this.#h){this.#h=p;for(let y of this.#h)this.#$(y.defaultPropertiesToUpdate)}}getId(){return this.#m.id}get currentLayer(){return this.#i.get(this.#a)}getLayer(p){return this.#i.get(p)}get currentPageIndex(){return this.#a}addLayer(p){this.#i.set(p.pageIndex,p),this.#b?p.enable():p.disable()}removeLayer(p){this.#i.delete(p.pageIndex)}updateMode(p,y=null,r=!1){if(this.#x!==p)if(this.#x=p,p!==i.AnnotationEditorType.NONE){this.setEditingState(!0),this.#lt(),this.unselectAll();for(let d of this.#i.values())d.updateMode(p);if(y||!r){if(y){for(let d of this.#e.values())if(d.annotationElementId===y){this.setSelected(d),d.enterInEditMode();break}}}else this.addNewEditorFromKeyboard()}else this.setEditingState(!1),this.#ct()}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(p){p!==this.#x&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:p})}updateParams(p,y){if(this.#h){switch(p){case i.AnnotationEditorParamsType.CREATE:this.currentLayer.addNewEditor();return;case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:this.#R?.updateColor(y);break;case i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#_||=new Map).set(p,y),this.showAllEditors("highlight",y)}for(let r of this.#v)r.updateParams(p,y);for(let r of this.#h)r.updateDefaultParams(p,y)}}showAllEditors(p,y,r=!1){for(let d of this.#e.values())d.editorType===p&&d.show(y);(this.#_?.get(i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==y&&this.#$([[i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,y]])}enableWaiting(p=!1){if(this.#S!==p){this.#S=p;for(let y of this.#i.values())p?y.disableClick():y.enableClick(),y.div.classList.toggle("waiting",p)}}#lt(){if(!this.#b){this.#b=!0;for(let p of this.#i.values())p.enable();for(let p of this.#e.values())p.enable()}}#ct(){if(this.unselectAll(),this.#b){this.#b=!1;for(let p of this.#i.values())p.disable();for(let p of this.#e.values())p.disable()}}getEditors(p){let y=[];for(let r of this.#e.values())r.pageIndex===p&&y.push(r);return y}getEditor(p){return this.#e.get(p)}addEditor(p){this.#e.set(p.id,p)}removeEditor(p){p.div.contains(document.activeElement)&&(this.#f&&clearTimeout(this.#f),this.#f=setTimeout((()=>{this.focusMainContainer(),this.#f=null}),0)),this.#e.delete(p.id),this.unselect(p),p.annotationElementId&&this.#l.has(p.annotationElementId)||this.#r?.remove(p.id)}addDeletedAnnotationElement(p){this.#l.add(p.annotationElementId),p.deleted=!0}isDeletedAnnotationElement(p){return this.#l.has(p)}removeDeletedAnnotationElement(p){this.#l.delete(p.annotationElementId),p.deleted=!1}#et(p){let y=this.#i.get(p.pageIndex);y?y.addOrRebuild(p):(this.addEditor(p),this.addToAnnotationStorage(p))}setActiveEditor(p){this.#t!==p&&(this.#t=p,p&&this.#$(p.propertiesToUpdate))}get#ht(){let p=null;for(p of this.#v);return p}updateUI(p){this.#ht===p&&this.#$(p.propertiesToUpdate)}toggleSelected(p){this.#v.has(p)?(this.#v.delete(p),p.unselect(),this.#D({hasSelectedEditor:this.hasSelection})):(this.#v.add(p),p.select(),this.#$(p.propertiesToUpdate),this.#D({hasSelectedEditor:!0}))}setSelected(p){for(let y of this.#v)y!==p&&y.unselect();this.#v.clear(),this.#v.add(p),p.select(),this.#$(p.propertiesToUpdate),this.#D({hasSelectedEditor:!0})}isSelected(p){return this.#v.has(p)}get firstSelectedEditor(){return this.#v.values().next().value}unselect(p){p.unselect(),this.#v.delete(p),this.#D({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#v.size!==0}get isEnterHandled(){return this.#v.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#s.undo(),this.#D({hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#G()})}redo(){this.#s.redo(),this.#D({hasSomethingToUndo:!0,hasSomethingToRedo:this.#s.hasSomethingToRedo(),isEmpty:this.#G()})}addCommands(p){this.#s.add(p),this.#D({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#G()})}#G(){if(this.#e.size===0)return!0;if(this.#e.size===1)for(let p of this.#e.values())return p.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;let p=[...this.#v];this.addCommands({cmd:()=>{for(let y of p)y.remove()},undo:()=>{for(let y of p)this.#et(y)},mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#it(p){for(let y of this.#v)y.unselect();this.#v.clear();for(let y of p)y.isEmpty()||(this.#v.add(y),y.select());this.#D({hasSelectedEditor:this.hasSelection})}selectAll(){for(let p of this.#v)p.commit();this.#it(this.#e.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#x!==i.AnnotationEditorType.NONE))&&this.hasSelection){for(let p of this.#v)p.unselect();this.#v.clear(),this.#D({hasSelectedEditor:!1})}}translateSelectedEditors(p,y,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;this.#j[0]+=p,this.#j[1]+=y;let[d,b]=this.#j,x=[...this.#v];this.#B&&clearTimeout(this.#B),this.#B=setTimeout((()=>{this.#B=null,this.#j[0]=this.#j[1]=0,this.addCommands({cmd:()=>{for(let _ of x)this.#e.has(_.id)&&_.translateInPage(d,b)},undo:()=>{for(let _ of x)this.#e.has(_.id)&&_.translateInPage(-d,-b)},mustExec:!1})}),1e3);for(let _ of x)_.translateInPage(p,y)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#o=new Map;for(let p of this.#v)this.#o.set(p,{savedX:p.x,savedY:p.y,savedPageIndex:p.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#o)return!1;this.disableUserSelect(!1);let p=this.#o;this.#o=null;let y=!1;for(let[{x:d,y:b,pageIndex:x},_]of p)_.newX=d,_.newY=b,_.newPageIndex=x,y||=d!==_.savedX||b!==_.savedY||x!==_.savedPageIndex;if(!y)return!1;let r=(d,b,x,_)=>{if(this.#e.has(d.id)){let S=this.#i.get(_);S?d._setParentAndPosition(S,b,x):(d.pageIndex=_,d.x=b,d.y=x)}};return this.addCommands({cmd:()=>{for(let[d,{newX:b,newY:x,newPageIndex:_}]of p)r(d,b,x,_)},undo:()=>{for(let[d,{savedX:b,savedY:x,savedPageIndex:_}]of p)r(d,b,x,_)},mustExec:!0}),!0}dragSelectedEditors(p,y){if(this.#o)for(let r of this.#o.keys())r.drag(p,y)}rebuild(p){if(p.parent===null){let y=this.getLayer(p.pageIndex);y?(y.changeParent(p),y.addOrRebuild(p)):(this.addEditor(p),this.addToAnnotationStorage(p),p.rebuild())}else p.parent.addOrRebuild(p)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#v.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(p){return this.#t===p}getActive(){return this.#t}getMode(){return this.#x}get imageManager(){return(0,i.shadow)(this,"imageManager",new m)}getSelectionBoxes(p){if(!p)return null;let y=document.getSelection();for(let R=0,N=y.rangeCount;R<N;R++)if(!p.contains(y.getRangeAt(R).commonAncestorContainer))return null;let{x:r,y:d,width:b,height:x}=p.getBoundingClientRect(),_;switch(p.getAttribute("data-main-rotation")){case"90":_=(R,N,H,z)=>({x:(N-d)/x,y:1-(R+H-r)/b,width:z/x,height:H/b});break;case"180":_=(R,N,H,z)=>({x:1-(R+H-r)/b,y:1-(N+z-d)/x,width:H/b,height:z/x});break;case"270":_=(R,N,H,z)=>({x:1-(N+z-d)/x,y:(R-r)/b,width:z/x,height:H/b});break;default:_=(R,N,H,z)=>({x:(R-r)/b,y:(N-d)/x,width:H/b,height:z/x})}let S=[];for(let R=0,N=y.rangeCount;R<N;R++){let H=y.getRangeAt(R);if(!H.collapsed)for(let{x:z,y:K,width:it,height:at}of H.getClientRects())it!==0&&at!==0&&S.push(_(z,K,it,at))}return S.length===0?null:S}}},94:(s,t,e)=>{e.d(t,{PDFFetchStream:()=>h});var i=e(292),n=e(490);function o(a,f,w){return{method:"GET",headers:a,signal:w.signal,mode:"cors",credentials:f?"include":"same-origin",redirect:"follow"}}function c(a){let f=new Headers;for(let w in a){let E=a[w];E!==void 0&&f.append(w,E)}return f}function l(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:((0,i.warn)(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class h{constructor(f){this.source=f,this.isHttp=/^https?:/i.test(f.url),this.httpHeaders=this.isHttp&&f.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new m(this),this._fullRequestReader}getRangeReader(f,w){if(w<=this._progressiveDataLength)return null;let E=new u(this,f,w);return this._rangeRequestReaders.push(E),E}cancelAllRequests(f){this._fullRequestReader?.cancel(f);for(let w of this._rangeRequestReaders.slice(0))w.cancel(f)}}class m{constructor(f){this._stream=f,this._reader=null,this._loaded=0,this._filename=null;let w=f.source;this._withCredentials=w.withCredentials||!1,this._contentLength=w.length,this._headersCapability=Promise.withResolvers(),this._disableRange=w.disableRange||!1,this._rangeChunkSize=w.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!w.disableStream,this._isRangeSupported=!w.disableRange,this._headers=c(this._stream.httpHeaders);let E=w.url;fetch(E,o(this._headers,this._withCredentials,this._abortController)).then((p=>{if(!(0,n.validateResponseStatus)(p.status))throw(0,n.createResponseStatusError)(p.status,E);this._reader=p.body.getReader(),this._headersCapability.resolve();let y=b=>p.headers.get(b),{allowRangeRequests:r,suggestedLength:d}=(0,n.validateRangeRequestCapabilities)({getResponseHeader:y,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=d||this._contentLength,this._filename=(0,n.extractFilenameFromHeader)(y),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new i.AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:f,done:w}=await this._reader.read();return w?{value:f,done:w}:(this._loaded+=f.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:l(f),done:!1})}cancel(f){this._reader?.cancel(f),this._abortController.abort()}}class u{constructor(f,w,E){this._stream=f,this._reader=null,this._loaded=0;let p=f.source;this._withCredentials=p.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!p.disableStream,this._abortController=new AbortController,this._headers=c(this._stream.httpHeaders),this._headers.append("Range",`bytes=${w}-${E-1}`);let y=p.url;fetch(y,o(this._headers,this._withCredentials,this._abortController)).then((r=>{if(!(0,n.validateResponseStatus)(r.status))throw(0,n.createResponseStatusError)(r.status,y);this._readCapability.resolve(),this._reader=r.body.getReader()})).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:f,done:w}=await this._reader.read();return w?{value:f,done:w}:(this._loaded+=f.byteLength,this.onProgress?.({loaded:this._loaded}),{value:l(f),done:!1})}cancel(f){this._reader?.cancel(f),this._abortController.abort()}}},10:(s,t,e)=>{e.d(t,{FontFaceObject:()=>o,FontLoader:()=>n});var i=e(292);class n{#t=new Set;constructor({ownerDocument:l=globalThis.document,styleElement:h=null}){this._document=l,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(l){this.nativeFontFaces.add(l),this._document.fonts.add(l)}removeNativeFontFace(l){this.nativeFontFaces.delete(l),this._document.fonts.delete(l)}insertRule(l){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));let h=this.styleElement.sheet;h.insertRule(l,h.cssRules.length)}clear(){for(let l of this.nativeFontFaces)this._document.fonts.delete(l);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:l,_inspectFont:h}){if(l&&!this.#t.has(l.loadedName))if((0,i.assert)(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:m,src:u,style:a}=l,f=new FontFace(m,u,a);this.addNativeFontFace(f);try{await f.load(),this.#t.add(m),h?.(l)}catch{(0,i.warn)(`Cannot load system font: ${l.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(f)}}else(0,i.unreachable)("Not implemented: loadSystemFont without the Font Loading API.")}async bind(l){if(l.attached||l.missingFile&&!l.systemFontInfo)return;if(l.attached=!0,l.systemFontInfo){await this.loadSystemFont(l);return}if(this.isFontLoadingAPISupported){let m=l.createNativeFontFace();if(m){this.addNativeFontFace(m);try{await m.loaded}catch(u){throw(0,i.warn)(`Failed to load font '${m.family}': '${u}'.`),l.disableFontFace=!0,u}}return}let h=l.createFontFaceRule();if(h){if(this.insertRule(h),this.isSyncFontLoadingSupported)return;await new Promise((m=>{let u=this._queueLoadingCallback(m);this._prepareFontLoadEvent(l,u)}))}}get isFontLoadingAPISupported(){let l=!!this._document?.fonts;return(0,i.shadow)(this,"isFontLoadingAPISupported",l)}get isSyncFontLoadingSupported(){let l=!1;return(i.isNodeJS||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(l=!0),(0,i.shadow)(this,"isSyncFontLoadingSupported",l)}_queueLoadingCallback(l){let{loadingRequests:h}=this,m={done:!1,complete:function(){for((0,i.assert)(!m.done,"completeRequest() cannot be called twice."),m.done=!0;h.length>0&&h[0].done;){let a=h.shift();setTimeout(a.callback,0)}},callback:l};return h.push(m),m}get _loadTestFont(){let l=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return(0,i.shadow)(this,"_loadTestFont",l)}_prepareFontLoadEvent(l,h){function m(S,R){return S.charCodeAt(R)<<24|S.charCodeAt(R+1)<<16|S.charCodeAt(R+2)<<8|255&S.charCodeAt(R+3)}function u(S,R,N,H){return S.substring(0,R)+H+S.substring(R+N)}let a,f,w=this._document.createElement("canvas");w.width=1,w.height=1;let E=w.getContext("2d"),p=0,y=`lt${Date.now()}${this.loadTestFontId++}`,r=this._loadTestFont;r=u(r,976,y.length,y);let d=1482184792,b=m(r,16);for(a=0,f=y.length-3;a<f;a+=4)b=b-d+m(y,a)|0;a<y.length&&(b=b-d+m(y+"XXX",a)|0),r=u(r,16,4,(0,i.string32)(b));let x=`@font-face {font-family:"${y}";src:${`url(data:font/opentype;base64,${btoa(r)});`}}`;this.insertRule(x);let _=this._document.createElement("div");_.style.visibility="hidden",_.style.width=_.style.height="10px",_.style.position="absolute",_.style.top=_.style.left="0px";for(let S of[l.loadedName,y]){let R=this._document.createElement("span");R.textContent="Hi",R.style.fontFamily=S,_.append(R)}this._document.body.append(_),(function S(R,N){if(++p>30){(0,i.warn)("Load test font never loaded."),N();return}E.font="30px "+R,E.fillText(".",0,20),E.getImageData(0,0,1,1).data[3]>0?N():setTimeout(S.bind(null,R,N))})(y,(()=>{_.remove(),h.complete()}))}}class o{constructor(l,{isEvalSupported:h=!0,disableFontFace:m=!1,ignoreErrors:u=!1,inspectFont:a=null}){this.compiledGlyphs=Object.create(null);for(let f in l)this[f]=l[f];this.isEvalSupported=h!==!1,this.disableFontFace=m===!0,this.ignoreErrors=u===!0,this._inspectFont=a}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let l;if(this.cssFontInfo){let h={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(h.style=`oblique ${this.cssFontInfo.italicAngle}deg`),l=new FontFace(this.cssFontInfo.fontFamily,this.data,h)}else l=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),l}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let l=(0,i.bytesToString)(this.data),h=`url(data:${this.mimetype};base64,${btoa(l)});`,m;if(this.cssFontInfo){let u=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(u+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),m=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${u}src:${h}}`}else m=`@font-face {font-family:"${this.loadedName}";src:${h}}`;return this._inspectFont?.(this,h),m}getPathGenerator(l,h){if(this.compiledGlyphs[h]!==void 0)return this.compiledGlyphs[h];let m;try{m=l.get(this.loadedName+"_path_"+h)}catch(u){if(!this.ignoreErrors)throw u;return(0,i.warn)(`getPathGenerator - ignoring character: "${u}".`),this.compiledGlyphs[h]=function(a,f){}}if(this.isEvalSupported&&i.FeatureTest.isEvalSupported){let u=[];for(let a of m){let f=a.args!==void 0?a.args.join(","):"";u.push("c.",a.cmd,"(",f,`);
|
|
19
|
-
`)}return this.compiledGlyphs[h]=new Function("c","size",u.join(""))}return this.compiledGlyphs[h]=function(u,a){for(let f of m)f.cmd==="scale"&&(f.args=[a,-a]),u[f.cmd].apply(u,f.args)}}}},62:(s,t,e)=>{e.d(t,{Metadata:()=>n});var i=e(292);class n{#t;#e;constructor({parsedData:c,rawData:l}){this.#t=c,this.#e=l}getRaw(){return this.#e}get(c){return this.#t.get(c)??null}getAll(){return(0,i.objectFromMap)(this.#t)}has(c){return this.#t.has(c)}}},457:(s,t,e)=>{e.d(t,{PDFNetworkStream:()=>c});var i=e(292),n=e(490);class o{constructor(u,a={}){this.url=u,this.isHttp=/^https?:/i.test(u),this.httpHeaders=this.isHttp&&a.httpHeaders||Object.create(null),this.withCredentials=a.withCredentials||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(u,a,f){let w={begin:u,end:a};for(let E in f)w[E]=f[E];return this.request(w)}requestFull(u){return this.request(u)}request(u){let a=new XMLHttpRequest,f=this.currXhrId++,w=this.pendingRequests[f]={xhr:a};a.open("GET",this.url),a.withCredentials=this.withCredentials;for(let E in this.httpHeaders){let p=this.httpHeaders[E];p!==void 0&&a.setRequestHeader(E,p)}return this.isHttp&&"begin"in u&&"end"in u?(a.setRequestHeader("Range",`bytes=${u.begin}-${u.end-1}`),w.expectedStatus=206):w.expectedStatus=200,a.responseType="arraybuffer",u.onError&&(a.onerror=function(E){u.onError(a.status)}),a.onreadystatechange=this.onStateChange.bind(this,f),a.onprogress=this.onProgress.bind(this,f),w.onHeadersReceived=u.onHeadersReceived,w.onDone=u.onDone,w.onError=u.onError,w.onProgress=u.onProgress,a.send(null),f}onProgress(u,a){let f=this.pendingRequests[u];f&&f.onProgress?.(a)}onStateChange(u,a){let f=this.pendingRequests[u];if(!f)return;let w=f.xhr;if(w.readyState>=2&&f.onHeadersReceived&&(f.onHeadersReceived(),delete f.onHeadersReceived),w.readyState!==4||!(u in this.pendingRequests))return;if(delete this.pendingRequests[u],w.status===0&&this.isHttp){f.onError?.(w.status);return}let E=w.status||200;if(!(E===200&&f.expectedStatus===206)&&E!==f.expectedStatus){f.onError?.(w.status);return}let p=(function(r){let d=r.response;return typeof d!="string"?d:(0,i.stringToBytes)(d).buffer})(w);if(E===206){let y=w.getResponseHeader("Content-Range"),r=/bytes (\d+)-(\d+)\/(\d+)/.exec(y);f.onDone({begin:parseInt(r[1],10),chunk:p})}else p?f.onDone({begin:0,chunk:p}):f.onError?.(w.status)}getRequestXhr(u){return this.pendingRequests[u].xhr}isPendingRequest(u){return u in this.pendingRequests}abortRequest(u){let a=this.pendingRequests[u].xhr;delete this.pendingRequests[u],a.abort()}}class c{constructor(u){this._source=u,this._manager=new o(u.url,{httpHeaders:u.httpHeaders,withCredentials:u.withCredentials}),this._rangeChunkSize=u.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(u){let a=this._rangeRequestReaders.indexOf(u);a>=0&&this._rangeRequestReaders.splice(a,1)}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new l(this._manager,this._source),this._fullRequestReader}getRangeReader(u,a){let f=new h(this._manager,u,a);return f.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(f),f}cancelAllRequests(u){this._fullRequestReader?.cancel(u);for(let a of this._rangeRequestReaders.slice(0))a.cancel(u)}}class l{constructor(u,a){this._manager=u;let f={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=a.url,this._fullRequestId=u.requestFull(f),this._headersReceivedCapability=Promise.withResolvers(),this._disableRange=a.disableRange||!1,this._contentLength=a.length,this._rangeChunkSize=a.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let u=this._fullRequestId,a=this._manager.getRequestXhr(u),f=p=>a.getResponseHeader(p),{allowRangeRequests:w,suggestedLength:E}=(0,n.validateRangeRequestCapabilities)({getResponseHeader:f,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});w&&(this._isRangeSupported=!0),this._contentLength=E||this._contentLength,this._filename=(0,n.extractFilenameFromHeader)(f),this._isRangeSupported&&this._manager.abortRequest(u),this._headersReceivedCapability.resolve()}_onDone(u){if(u&&(this._requests.length>0?this._requests.shift().resolve({value:u.chunk,done:!1}):this._cachedChunks.push(u.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(u){this._storedError=(0,n.createResponseStatusError)(u,this._url),this._headersReceivedCapability.reject(this._storedError);for(let a of this._requests)a.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(u){this.onProgress?.({loaded:u.loaded,total:u.lengthComputable?u.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let u=Promise.withResolvers();return this._requests.push(u),u.promise}cancel(u){this._done=!0,this._headersReceivedCapability.reject(u);for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class h{constructor(u,a,f){this._manager=u;let w={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=u.url,this._requestId=u.requestRange(a,f,w),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(u){let a=u.chunk;this._requests.length>0?this._requests.shift().resolve({value:a,done:!1}):this._queuedChunk=a,this._done=!0;for(let f of this._requests)f.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(u){this._storedError=(0,n.createResponseStatusError)(u,this._url);for(let a of this._requests)a.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(u){this.isStreamingSupported||this.onProgress?.({loaded:u.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let a=this._queuedChunk;return this._queuedChunk=null,{value:a,done:!1}}if(this._done)return{value:void 0,done:!0};let u=Promise.withResolvers();return this._requests.push(u),u.promise}cancel(u){this._done=!0;for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}},490:(s,t,e)=>{e.d(t,{createResponseStatusError:()=>l,extractFilenameFromHeader:()=>c,validateRangeRequestCapabilities:()=>o,validateResponseStatus:()=>h});var i=e(292),n=e(419);function o({getResponseHeader:m,isHttp:u,rangeChunkSize:a,disableRange:f}){let w={allowRangeRequests:!1,suggestedLength:void 0},E=parseInt(m("Content-Length"),10);return!Number.isInteger(E)||(w.suggestedLength=E,E<=2*a)||f||!u||m("Accept-Ranges")!=="bytes"||(m("Content-Encoding")||"identity")!=="identity"||(w.allowRangeRequests=!0),w}function c(m){let u=m("Content-Disposition");if(u){let a=(function(w){let E=!0,p=y("filename\\*","i").exec(w);if(p){p=p[1];let S=b(p);return S=unescape(S),S=x(S),S=_(S),d(S)}if(p=(function(R){let N=[],H,z=y("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(H=z.exec(R))!==null;){let[,it,at,X]=H;if(it=parseInt(it,10),it in N){if(it===0)break}else N[it]=[at,X]}let K=[];for(let it=0;it<N.length&&it in N;++it){let[at,X]=N[it];X=b(X),at&&(X=unescape(X),it===0&&(X=x(X))),K.push(X)}return K.join("")})(w),p)return d(_(p));if(p=y("filename","i").exec(w),p){p=p[1];let S=b(p);return S=_(S),d(S)}function y(S,R){return new RegExp("(?:^|;)\\s*"+S+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',R)}function r(S,R){if(S){if(!/^[\x00-\xFF]+$/.test(R))return R;try{let N=new TextDecoder(S,{fatal:!0}),H=(0,i.stringToBytes)(R);R=N.decode(H),E=!1}catch{}}return R}function d(S){return E&&/[\x80-\xff]/.test(S)&&(S=r("utf-8",S),E&&(S=r("iso-8859-1",S))),S}function b(S){if(S.startsWith('"')){let R=S.slice(1).split('\\"');for(let N=0;N<R.length;++N){let H=R[N].indexOf('"');H!==-1&&(R[N]=R[N].slice(0,H),R.length=N+1),R[N]=R[N].replaceAll(/\\(.)/g,"$1")}S=R.join('"')}return S}function x(S){let R=S.indexOf("'");return R===-1?S:r(S.slice(0,R),S.slice(R+1).replace(/^[^']*'/,""))}function _(S){return!S.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(S)?S:S.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(R,N,H,z){if(H==="q"||H==="Q")return r(N,z=(z=z.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(K,it){return String.fromCharCode(parseInt(it,16))})));try{z=atob(z)}catch{}return r(N,z)}))}return""})(u);if(a.includes("%"))try{a=decodeURIComponent(a)}catch{}if((0,n.isPdfFile)(a))return a}return null}function l(m,u){return m===404||m===0&&u.startsWith("file:")?new i.MissingPDFException('Missing PDF "'+u+'".'):new i.UnexpectedResponseException(`Unexpected server response (${m}) while retrieving PDF "${u}".`,m)}function h(m){return m===200||m===206}},786:(s,t,e)=>{e.a(s,(async(i,n)=>{try{let f=function(_){let S=u.parse(_);return S.protocol==="file:"||S.host?S:/^[a-z]:[/\\]/i.test(_)?u.parse(`file:///${_}`):(S.host||(S.protocol="file:"),S)},y=function(_,S){return{protocol:_.protocol,auth:_.auth,host:_.hostname,port:_.port,path:_.path,method:"GET",headers:S}};e.d(t,{PDFNodeStream:()=>w});var o=e(292),c=e(490);let l,h,m,u;o.isNodeJS&&(l=await Promise.resolve().then(()=>(gl(),fl)),h=await Promise.resolve().then(()=>(kh(),Ph)),m=await Promise.resolve().then(()=>(Rh(),Dh)),u=await Promise.resolve().then(()=>(Ih(),Mh)));let a=/^file:\/\/\/[a-zA-Z]:\//;class w{constructor(S){this.source=S,this.url=f(S.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&S.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,o.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new b(this):new r(this),this._fullRequestReader}getRangeReader(S,R){if(R<=this._progressiveDataLength)return null;let N=this.isFsUrl?new x(this,S,R):new d(this,S,R);return this._rangeRequestReaders.push(N),N}cancelAllRequests(S){this._fullRequestReader?.cancel(S);for(let R of this._rangeRequestReaders.slice(0))R.cancel(S)}}class E{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null;let R=S.source;this._contentLength=R.length,this._loaded=0,this._filename=null,this._disableRange=R.disableRange||!1,this._rangeChunkSize=R.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!R.disableStream,this._isRangeSupported=!R.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){this._readableStream?this._readableStream.destroy(S):this._error(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",(()=>{this._readCapability.resolve()})),S.on("end",(()=>{S.destroy(),this._done=!0,this._readCapability.resolve()})),S.on("error",(R=>{this._error(R)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new o.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class p{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let R=S.source;this._isStreamingSupported=!R.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){this._readableStream?this._readableStream.destroy(S):this._error(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",(()=>{this._readCapability.resolve()})),S.on("end",(()=>{S.destroy(),this._done=!0,this._readCapability.resolve()})),S.on("error",(R=>{this._error(R)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class r extends E{constructor(S){super(S);let R=N=>{if(N.statusCode===404){let it=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=it,this._headersCapability.reject(it);return}this._headersCapability.resolve(),this._setReadableStream(N);let H=it=>this._readableStream.headers[it.toLowerCase()],{allowRangeRequests:z,suggestedLength:K}=(0,c.validateRangeRequestCapabilities)({getResponseHeader:H,isHttp:S.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=z,this._contentLength=K||this._contentLength,this._filename=(0,c.extractFilenameFromHeader)(H)};this._request=null,this._url.protocol==="http:"?this._request=h.request(y(this._url,S.httpHeaders),R):this._request=m.request(y(this._url,S.httpHeaders),R),this._request.on("error",(N=>{this._storedError=N,this._headersCapability.reject(N)})),this._request.end()}}class d extends p{constructor(S,R,N){super(S),this._httpHeaders={};for(let z in S.httpHeaders){let K=S.httpHeaders[z];K!==void 0&&(this._httpHeaders[z]=K)}this._httpHeaders.Range=`bytes=${R}-${N-1}`;let H=z=>{if(z.statusCode!==404)this._setReadableStream(z);else{let K=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=K}};this._request=null,this._url.protocol==="http:"?this._request=h.request(y(this._url,this._httpHeaders),H):this._request=m.request(y(this._url,this._httpHeaders),H),this._request.on("error",(z=>{this._storedError=z})),this._request.end()}}class b extends E{constructor(S){super(S);let R=decodeURIComponent(this._url.path);a.test(this._url.href)&&(R=R.replace(/^\//,"")),l.promises.lstat(R).then((N=>{this._contentLength=N.size,this._setReadableStream(l.createReadStream(R)),this._headersCapability.resolve()}),(N=>{N.code==="ENOENT"&&(N=new o.MissingPDFException(`Missing PDF "${R}".`)),this._storedError=N,this._headersCapability.reject(N)}))}}class x extends p{constructor(S,R,N){super(S);let H=decodeURIComponent(this._url.path);a.test(this._url.href)&&(H=H.replace(/^\//,"")),this._setReadableStream(l.createReadStream(H,{start:R,end:N-1}))}}n()}catch(l){n(l)}}),1)},573:(s,t,e)=>{e.a(s,(async(i,n)=>{try{e.d(t,{NodeCMapReaderFactory:()=>f,NodeCanvasFactory:()=>a,NodeFilterFactory:()=>u,NodeStandardFontDataFactory:()=>w});var o=e(583);let c,l,h;if(e(292).isNodeJS){c=await Promise.resolve().then(()=>(gl(),fl));try{l=await Promise.resolve().then(()=>(Fh(),Lh))}catch{}try{h=await Promise.resolve().then(()=>(Nh(),Oh))}catch{}}let m=function(E){return c.promises.readFile(E).then((p=>new Uint8Array(p)))};class u extends o.BaseFilterFactory{}class a extends o.BaseCanvasFactory{_createCanvas(p,y){return l.createCanvas(p,y)}}class f extends o.BaseCMapReaderFactory{_fetchData(p,y){return m(p).then((r=>({cMapData:r,compressionType:y})))}}class w extends o.BaseStandardFontDataFactory{_fetchData(p){return m(p)}}n()}catch(c){n(c)}}),1)},626:(s,t,e)=>{e.d(t,{OptionalContentConfig:()=>l});var i=e(292),n=e(651);let o=Symbol("INTERNAL");class c{#t=!1;#e=!1;#i=!1;#n=!0;constructor(m,{name:u,intent:a,usage:f}){this.#t=!!(m&i.RenderingIntentFlag.DISPLAY),this.#e=!!(m&i.RenderingIntentFlag.PRINT),this.name=u,this.intent=a,this.usage=f}get visible(){if(this.#i)return this.#n;if(!this.#n)return!1;let{print:m,view:u}=this.usage;return this.#t?u?.viewState!=="OFF":!this.#e||m?.printState!=="OFF"}_setVisible(m,u,a=!1){m!==o&&(0,i.unreachable)("Internal method `_setVisible` called."),this.#i=a,this.#n=u}}class l{#t=null;#e=new Map;#i=null;#n=null;constructor(m,u=i.RenderingIntentFlag.DISPLAY){if(this.renderingIntent=u,this.name=null,this.creator=null,m!==null){this.name=m.name,this.creator=m.creator,this.#n=m.order;for(let a of m.groups)this.#e.set(a.id,new c(u,a));if(m.baseState==="OFF")for(let a of this.#e.values())a._setVisible(o,!1);for(let a of m.on)this.#e.get(a)._setVisible(o,!0);for(let a of m.off)this.#e.get(a)._setVisible(o,!1);this.#i=this.getHash()}}#r(m){let u=m.length;if(u<2)return!0;let a=m[0];for(let f=1;f<u;f++){let w=m[f],E;if(Array.isArray(w))E=this.#r(w);else{if(!this.#e.has(w))return(0,i.warn)(`Optional content group not found: ${w}`),!0;E=this.#e.get(w).visible}switch(a){case"And":if(!E)return!1;break;case"Or":if(E)return!0;break;case"Not":return!E;default:return!0}}return a==="And"}isVisible(m){if(this.#e.size===0)return!0;if(!m)return(0,i.info)("Optional content group not defined."),!0;if(m.type==="OCG")return this.#e.has(m.id)?this.#e.get(m.id).visible:((0,i.warn)(`Optional content group not found: ${m.id}`),!0);if(m.type==="OCMD"){if(m.expression)return this.#r(m.expression);if(!m.policy||m.policy==="AnyOn"){for(let u of m.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(this.#e.get(u).visible)return!0}return!1}if(m.policy==="AllOn"){for(let u of m.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(!this.#e.get(u).visible)return!1}return!0}if(m.policy==="AnyOff"){for(let u of m.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(!this.#e.get(u).visible)return!0}return!1}if(m.policy==="AllOff"){for(let u of m.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(this.#e.get(u).visible)return!1}return!0}return(0,i.warn)(`Unknown optional content policy ${m.policy}.`),!0}return(0,i.warn)(`Unknown group type ${m.type}.`),!0}setVisibility(m,u=!0){let a=this.#e.get(m);a?(a._setVisible(o,!!u,!0),this.#t=null):(0,i.warn)(`Optional content group not found: ${m}`)}setOCGState({state:m,preserveRB:u}){let a;for(let f of m){switch(f){case"ON":case"OFF":case"Toggle":a=f;continue}let w=this.#e.get(f);if(w)switch(a){case"ON":w._setVisible(o,!0);break;case"OFF":w._setVisible(o,!1);break;case"Toggle":w._setVisible(o,!w.visible)}}this.#t=null}get hasInitialVisibility(){return this.#i===null||this.getHash()===this.#i}getOrder(){return this.#e.size?this.#n?this.#n.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?(0,i.objectFromMap)(this.#e):null}getGroup(m){return this.#e.get(m)||null}getHash(){if(this.#t!==null)return this.#t;let m=new n.MurmurHash3_64;for(let[u,a]of this.#e)m.update(`${u}:${a.visible}`);return this.#t=m.hexdigest()}}},814:(s,t,e)=>{e.d(t,{cleanupTextLayer:()=>u,renderTextLayer:()=>E,updateTextLayer:()=>p});var i=e(292),n=e(419);let o=30,c=.8,l=new Map,h=null;function m(){if(!h){let y=document.createElement("canvas");y.className="hiddenCanvasElement",document.body.append(y),h=y.getContext("2d",{alpha:!1})}return h}function u(){h?.canvas.remove(),h=null}function a(y,r,d){let b=document.createElement("span"),x={angle:0,canvasWidth:0,hasText:r.str!=="",hasEOL:r.hasEOL,fontSize:0};y._textDivs.push(b);let _=i.Util.transform(y._transform,r.transform),S=Math.atan2(_[1],_[0]),R=d[r.fontName];R.vertical&&(S+=Math.PI/2);let N=y._fontInspectorEnabled&&R.fontSubstitution||R.fontFamily,H=Math.hypot(_[2],_[3]),z=H*(function(Y){let tt=l.get(Y);if(tt)return tt;let st=m(),lt=st.font;st.canvas.width=st.canvas.height=o,st.font=`${o}px ${Y}`;let nt=st.measureText(""),G=nt.fontBoundingBoxAscent,A=Math.abs(nt.fontBoundingBoxDescent);if(G){let I=G/(G+A);return l.set(Y,I),st.canvas.width=st.canvas.height=0,st.font=lt,I}st.strokeStyle="red",st.clearRect(0,0,o,o),st.strokeText("g",0,0);let T=st.getImageData(0,0,o,o).data;A=0;for(let I=T.length-1-3;I>=0;I-=4)if(T[I]>0){A=Math.ceil(I/4/o);break}st.clearRect(0,0,o,o),st.strokeText("A",0,o),T=st.getImageData(0,0,o,o).data,G=0;for(let I=0,g=T.length;I<g;I+=4)if(T[I]>0){G=o-Math.floor(I/4/o);break}if(st.canvas.width=st.canvas.height=0,st.font=lt,G){let I=G/(G+A);return l.set(Y,I),I}return l.set(Y,c),c})(N),K,it;S===0?(K=_[4],it=_[5]-z):(K=_[4]+z*Math.sin(S),it=_[5]-z*Math.cos(S));let at="calc(var(--scale-factor)*",X=b.style;y._container===y._rootContainer?(X.left=`${(100*K/y._pageWidth).toFixed(2)}%`,X.top=`${(100*it/y._pageHeight).toFixed(2)}%`):(X.left=`${at}${K.toFixed(2)}px)`,X.top=`${at}${it.toFixed(2)}px)`),X.fontSize=`${at}${H.toFixed(2)}px)`,X.fontFamily=N,x.fontSize=H,b.setAttribute("role","presentation"),b.textContent=r.str,b.dir=r.dir,y._fontInspectorEnabled&&(b.dataset.fontName=R.fontSubstitutionLoadedName||r.fontName),S!==0&&(x.angle=S*(180/Math.PI));let j=!1;if(r.str.length>1)j=!0;else if(r.str!==" "&&r.transform[0]!==r.transform[3]){let W=Math.abs(r.transform[0]),Y=Math.abs(r.transform[3]);W!==Y&&Math.max(W,Y)/Math.min(W,Y)>1.5&&(j=!0)}j&&(x.canvasWidth=R.vertical?r.height:r.width),y._textDivProperties.set(b,x),y._isReadableStream&&y._layoutText(b)}function f(y){let{div:r,scale:d,properties:b,ctx:x,prevFontSize:_,prevFontFamily:S}=y,{style:R}=r,N="";if(b.canvasWidth!==0&&b.hasText){let{fontFamily:H}=R,{canvasWidth:z,fontSize:K}=b;(_!==K||S!==H)&&(x.font=`${K*d}px ${H}`,y.prevFontSize=K,y.prevFontFamily=H);let{width:it}=x.measureText(r.textContent);it>0&&(N=`scaleX(${z*d/it})`)}b.angle!==0&&(N=`rotate(${b.angle}deg) ${N}`),N.length>0&&(R.transform=N)}class w{constructor({textContentSource:r,container:d,viewport:b,textDivs:x,textDivProperties:_,textContentItemsStr:S}){this._textContentSource=r,this._isReadableStream=r instanceof ReadableStream,this._container=this._rootContainer=d,this._textDivs=x||[],this._textContentItemsStr=S||[],this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled,this._reader=null,this._textDivProperties=_||new WeakMap,this._canceled=!1,this._capability=Promise.withResolvers(),this._layoutTextParams={prevFontSize:null,prevFontFamily:null,div:null,scale:b.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:m()};let{pageWidth:R,pageHeight:N,pageX:H,pageY:z}=b.rawDims;this._transform=[1,0,0,-1,-H,z+N],this._pageWidth=R,this._pageHeight=N,(0,n.setLayerDimensions)(d,b),this._capability.promise.finally((()=>{this._layoutTextParams=null})).catch((()=>{}))}get promise(){return this._capability.promise}cancel(){this._canceled=!0,this._reader&&(this._reader.cancel(new i.AbortException("TextLayer task cancelled.")).catch((()=>{})),this._reader=null),this._capability.reject(new i.AbortException("TextLayer task cancelled."))}_processItems(r,d){for(let b of r)if(b.str!==void 0)this._textContentItemsStr.push(b.str),a(this,b,d);else if(b.type==="beginMarkedContentProps"||b.type==="beginMarkedContent"){let x=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),b.id!==null&&this._container.setAttribute("id",`${b.id}`),x.append(this._container)}else b.type==="endMarkedContent"&&(this._container=this._container.parentNode)}_layoutText(r){let d=this._layoutTextParams.properties=this._textDivProperties.get(r);if(this._layoutTextParams.div=r,f(this._layoutTextParams),d.hasText&&this._container.append(r),d.hasEOL){let b=document.createElement("br");b.setAttribute("role","presentation"),this._container.append(b)}}_render(){let{promise:r,resolve:d,reject:b}=Promise.withResolvers(),x=Object.create(null);if(this._isReadableStream){let _=()=>{this._reader.read().then((({value:S,done:R})=>{R?d():(Object.assign(x,S.styles),this._processItems(S.items,x),_())}),b)};this._reader=this._textContentSource.getReader(),_()}else{if(!this._textContentSource)throw new Error('No "textContentSource" parameter specified.');{let{items:_,styles:S}=this._textContentSource;this._processItems(_,S),d()}}r.then((()=>{x=null,(function(S){if(S._canceled)return;let R=S._textDivs,N=S._capability;if(R.length>1e5)N.resolve();else{if(!S._isReadableStream)for(let H of R)S._layoutText(H);N.resolve()}})(this)}),this._capability.reject)}}function E(y){let r=new w(y);return r._render(),r}function p({container:y,viewport:r,textDivs:d,textDivProperties:b,mustRotate:x=!0,mustRescale:_=!0}){if(x&&(0,n.setLayerDimensions)(y,{rotation:r.rotation}),_){let S=m(),R={prevFontSize:null,prevFontFamily:null,div:null,scale:r.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:S};for(let N of d)R.properties=b.get(N),R.div=N,f(R)}}},585:(s,t,e)=>{e.d(t,{PDFDataTransportStream:()=>o});var i=e(292),n=e(419);class o{constructor(m,{disableRange:u=!1,disableStream:a=!1}){(0,i.assert)(m,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');let{length:f,initialData:w,progressiveDone:E,contentDispositionFilename:p}=m;if(this._queuedChunks=[],this._progressiveDone=E,this._contentDispositionFilename=p,w?.length>0){let y=w instanceof Uint8Array&&w.byteLength===w.buffer.byteLength?w.buffer:new Uint8Array(w).buffer;this._queuedChunks.push(y)}this._pdfDataRangeTransport=m,this._isStreamingSupported=!a,this._isRangeSupported=!u,this._contentLength=f,this._fullRequestReader=null,this._rangeReaders=[],m.addRangeListener(((y,r)=>{this._onReceiveData({begin:y,chunk:r})})),m.addProgressListener(((y,r)=>{this._onProgress({loaded:y,total:r})})),m.addProgressiveReadListener((y=>{this._onReceiveData({chunk:y})})),m.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),m.transportReady()}_onReceiveData({begin:m,chunk:u}){let a=u instanceof Uint8Array&&u.byteLength===u.buffer.byteLength?u.buffer:new Uint8Array(u).buffer;if(m===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(a):this._queuedChunks.push(a);else{let f=this._rangeReaders.some((function(w){return w._begin!==m?!1:(w._enqueue(a),!0)}));(0,i.assert)(f,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(m){m.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:m.loaded}):this._fullRequestReader?.onProgress?.({loaded:m.loaded,total:m.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(m){let u=this._rangeReaders.indexOf(m);u>=0&&this._rangeReaders.splice(u,1)}getFullReader(){(0,i.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let m=this._queuedChunks;return this._queuedChunks=null,new c(this,m,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(m,u){if(u<=this._progressiveDataLength)return null;let a=new l(this,m,u);return this._pdfDataRangeTransport.requestDataRange(m,u),this._rangeReaders.push(a),a}cancelAllRequests(m){this._fullRequestReader?.cancel(m);for(let u of this._rangeReaders.slice(0))u.cancel(m);this._pdfDataRangeTransport.abort()}}class c{constructor(m,u,a=!1,f=null){this._stream=m,this._done=a||!1,this._filename=(0,n.isPdfFile)(f)?f:null,this._queuedChunks=u||[],this._loaded=0;for(let w of this._queuedChunks)this._loaded+=w.byteLength;this._requests=[],this._headersReady=Promise.resolve(),m._fullRequestReader=this,this.onProgress=null}_enqueue(m){this._done||(this._requests.length>0?this._requests.shift().resolve({value:m,done:!1}):this._queuedChunks.push(m),this._loaded+=m.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let m=Promise.withResolvers();return this._requests.push(m),m.promise}cancel(m){this._done=!0;for(let u of this._requests)u.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class l{constructor(m,u,a){this._stream=m,this._begin=u,this._end=a,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(m){if(!this._done){if(this._requests.length===0)this._queuedChunk=m;else{this._requests.shift().resolve({value:m,done:!1});for(let u of this._requests)u.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){let u=this._queuedChunk;return this._queuedChunk=null,{value:u,done:!1}}if(this._done)return{value:void 0,done:!0};let m=Promise.withResolvers();return this._requests.push(m),m.promise}cancel(m){this._done=!0;for(let u of this._requests)u.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}},164:(s,t,e)=>{e.d(t,{GlobalWorkerOptions:()=>i});class i{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(o){if(!(typeof Worker<"u"&&o instanceof Worker)&&o!==null)throw new Error("Invalid `workerPort` type.");this.#t=o}static get workerSrc(){return this.#e}static set workerSrc(o){if(typeof o!="string")throw new Error("Invalid `workerSrc` type.");this.#e=o}}},284:(s,t,e)=>{e.d(t,{XfaLayer:()=>n});var i=e(50);class n{static setupStorage(c,l,h,m,u){let a=m.getValue(l,{value:null});switch(h.name){case"textarea":if(a.value!==null&&(c.textContent=a.value),u==="print")break;c.addEventListener("input",(f=>{m.setValue(l,{value:f.target.value})}));break;case"input":if(h.attributes.type==="radio"||h.attributes.type==="checkbox"){if(a.value===h.attributes.xfaOn?c.setAttribute("checked",!0):a.value===h.attributes.xfaOff&&c.removeAttribute("checked"),u==="print")break;c.addEventListener("change",(f=>{m.setValue(l,{value:f.target.checked?f.target.getAttribute("xfaOn"):f.target.getAttribute("xfaOff")})}))}else{if(a.value!==null&&c.setAttribute("value",a.value),u==="print")break;c.addEventListener("input",(f=>{m.setValue(l,{value:f.target.value})}))}break;case"select":if(a.value!==null){c.setAttribute("value",a.value);for(let f of h.children)f.attributes.value===a.value?f.attributes.selected=!0:f.attributes.hasOwnProperty("selected")&&delete f.attributes.selected}c.addEventListener("input",(f=>{let w=f.target.options,E=w.selectedIndex===-1?"":w[w.selectedIndex].value;m.setValue(l,{value:E})}))}}static setAttributes({html:c,element:l,storage:h=null,intent:m,linkService:u}){let{attributes:a}=l,f=c instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${m}`);for(let[w,E]of Object.entries(a))if(E!=null)switch(w){case"class":E.length&&c.setAttribute(w,E.join(" "));break;case"dataId":break;case"id":c.setAttribute("data-element-id",E);break;case"style":Object.assign(c.style,E);break;case"textContent":c.textContent=E;break;default:(!f||w!=="href"&&w!=="newWindow")&&c.setAttribute(w,E)}f&&u.addLinkAttributes(c,a.href,a.newWindow),h&&a.dataId&&this.setupStorage(c,a.dataId,l,h)}static render(c){let l=c.annotationStorage,h=c.linkService,m=c.xfaHtml,u=c.intent||"display",a=document.createElement(m.name);m.attributes&&this.setAttributes({html:a,element:m,intent:u,linkService:h});let f=u!=="richText",w=c.div;if(w.append(a),c.viewport){let y=`matrix(${c.viewport.transform.join(",")})`;w.style.transform=y}f&&w.setAttribute("class","xfaLayer xfaFont");let E=[];if(m.children.length===0){if(m.value){let y=document.createTextNode(m.value);a.append(y),f&&i.XfaText.shouldBuildText(m.name)&&E.push(y)}return{textDivs:E}}let p=[[m,-1,a]];for(;p.length>0;){let[y,r,d]=p.at(-1);if(r+1===y.children.length){p.pop();continue}let b=y.children[++p.at(-1)[1]];if(b===null)continue;let{name:x}=b;if(x==="#text"){let S=document.createTextNode(b.value);E.push(S),d.append(S);continue}let _=b?.attributes?.xmlns?document.createElementNS(b.attributes.xmlns,x):document.createElement(x);if(d.append(_),b.attributes&&this.setAttributes({html:_,element:b,storage:l,intent:u,linkService:h}),b.children?.length>0)p.push([b,-1,_]);else if(b.value){let S=document.createTextNode(b.value);f&&i.XfaText.shouldBuildText(x)&&E.push(S),_.append(S)}}for(let y of w.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))y.setAttribute("readOnly",!0);return{textDivs:E}}static update(c){let l=`matrix(${c.viewport.transform.join(",")})`;c.div.style.transform=l,c.div.hidden=!1}}},50:(s,t,e)=>{e.d(t,{XfaText:()=>i});class i{static textContent(o){let c=[],l={items:c,styles:Object.create(null)};return(function h(m){if(!m)return;let u=null,a=m.name;if(a==="#text")u=m.value;else{if(!i.shouldBuildText(a))return;m?.attributes?.textContent?u=m.attributes.textContent:m.value&&(u=m.value)}if(u!==null&&c.push({str:u}),m.children)for(let f of m.children)h(f)})(o),l}static shouldBuildText(o){return!(o==="textarea"||o==="input"||o==="option"||o==="select")}}},228:(s,t,e)=>{e.a(s,(async(i,n)=>{try{e.d(t,{AbortException:()=>o.AbortException,AnnotationEditorLayer:()=>m.AnnotationEditorLayer,AnnotationEditorParamsType:()=>o.AnnotationEditorParamsType,AnnotationEditorType:()=>o.AnnotationEditorType,AnnotationEditorUIManager:()=>u.AnnotationEditorUIManager,AnnotationLayer:()=>a.AnnotationLayer,AnnotationMode:()=>o.AnnotationMode,CMapCompressionType:()=>o.CMapCompressionType,ColorPicker:()=>f.ColorPicker,DOMSVGFactory:()=>l.DOMSVGFactory,DrawLayer:()=>w.DrawLayer,FeatureTest:()=>o.FeatureTest,GlobalWorkerOptions:()=>E.GlobalWorkerOptions,ImageKind:()=>o.ImageKind,InvalidPDFException:()=>o.InvalidPDFException,MissingPDFException:()=>o.MissingPDFException,OPS:()=>o.OPS,Outliner:()=>p.Outliner,PDFDataRangeTransport:()=>c.PDFDataRangeTransport,PDFDateString:()=>l.PDFDateString,PDFWorker:()=>c.PDFWorker,PasswordResponses:()=>o.PasswordResponses,PermissionFlag:()=>o.PermissionFlag,PixelsPerInch:()=>l.PixelsPerInch,RenderingCancelledException:()=>l.RenderingCancelledException,UnexpectedResponseException:()=>o.UnexpectedResponseException,Util:()=>o.Util,VerbosityLevel:()=>o.VerbosityLevel,XfaLayer:()=>y.XfaLayer,build:()=>c.build,createValidAbsoluteUrl:()=>o.createValidAbsoluteUrl,fetchData:()=>l.fetchData,getDocument:()=>c.getDocument,getFilenameFromUrl:()=>l.getFilenameFromUrl,getPdfFilenameFromUrl:()=>l.getPdfFilenameFromUrl,getXfaPageViewport:()=>l.getXfaPageViewport,isDataScheme:()=>l.isDataScheme,isPdfFile:()=>l.isPdfFile,noContextMenu:()=>l.noContextMenu,normalizeUnicode:()=>o.normalizeUnicode,renderTextLayer:()=>h.renderTextLayer,setLayerDimensions:()=>l.setLayerDimensions,shadow:()=>o.shadow,updateTextLayer:()=>h.updateTextLayer,version:()=>c.version});var o=e(292),c=e(831),l=e(419),h=e(814),m=e(731),u=e(830),a=e(976),f=e(259),w=e(47),E=e(164),p=e(61),y=e(284),r=i([c]);c=(r.then?(await r)():r)[0],n()}catch(d){n(d)}}))},178:(s,t,e)=>{e.d(t,{MessageHandler:()=>p});var i=e(292);let n=1,o=2,c=1,l=2,h=3,m=4,u=5,a=6,f=7,w=8;function E(y){switch(y instanceof Error||typeof y=="object"&&y!==null||(0,i.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),y.name){case"AbortException":return new i.AbortException(y.message);case"MissingPDFException":return new i.MissingPDFException(y.message);case"PasswordException":return new i.PasswordException(y.message,y.code);case"UnexpectedResponseException":return new i.UnexpectedResponseException(y.message,y.status);case"UnknownErrorException":return new i.UnknownErrorException(y.message,y.details);default:return new i.UnknownErrorException(y.message,y.toString())}}class p{constructor(r,d,b){this.sourceName=r,this.targetName=d,this.comObj=b,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=x=>{let _=x.data;if(_.targetName!==this.sourceName)return;if(_.stream){this.#e(_);return}if(_.callback){let R=_.callbackId,N=this.callbackCapabilities[R];if(!N)throw new Error(`Cannot resolve callback ${R}`);if(delete this.callbackCapabilities[R],_.callback===n)N.resolve(_.data);else{if(_.callback!==o)throw new Error("Unexpected callback case");N.reject(E(_.reason))}return}let S=this.actionHandler[_.action];if(!S)throw new Error(`Unknown action from worker: ${_.action}`);if(_.callbackId){let R=this.sourceName,N=_.sourceName;new Promise((function(H){H(S(_.data))})).then((function(H){b.postMessage({sourceName:R,targetName:N,callback:n,callbackId:_.callbackId,data:H})}),(function(H){b.postMessage({sourceName:R,targetName:N,callback:o,callbackId:_.callbackId,reason:E(H)})}))}else _.streamId?this.#t(_):S(_.data)},b.addEventListener("message",this._onComObjOnMessage)}on(r,d){let b=this.actionHandler;if(b[r])throw new Error(`There is already an actionName called "${r}"`);b[r]=d}send(r,d,b){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:r,data:d},b)}sendWithPromise(r,d,b){let x=this.callbackId++,_=Promise.withResolvers();this.callbackCapabilities[x]=_;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:r,callbackId:x,data:d},b)}catch(S){_.reject(S)}return _.promise}sendWithStream(r,d,b,x){let _=this.streamId++,S=this.sourceName,R=this.targetName,N=this.comObj;return new ReadableStream({start:H=>{let z=Promise.withResolvers();return this.streamControllers[_]={controller:H,startCall:z,pullCall:null,cancelCall:null,isClosed:!1},N.postMessage({sourceName:S,targetName:R,action:r,streamId:_,data:d,desiredSize:H.desiredSize},x),z.promise},pull:H=>{let z=Promise.withResolvers();return this.streamControllers[_].pullCall=z,N.postMessage({sourceName:S,targetName:R,stream:a,streamId:_,desiredSize:H.desiredSize}),z.promise},cancel:H=>{(0,i.assert)(H instanceof Error,"cancel must have a valid reason");let z=Promise.withResolvers();return this.streamControllers[_].cancelCall=z,this.streamControllers[_].isClosed=!0,N.postMessage({sourceName:S,targetName:R,stream:c,streamId:_,reason:E(H)}),z.promise}},b)}#t(r){let d=r.streamId,b=this.sourceName,x=r.sourceName,_=this.comObj,S=this,R=this.actionHandler[r.action],N={enqueue(H,z=1,K){if(this.isCancelled)return;let it=this.desiredSize;this.desiredSize-=z,it>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),_.postMessage({sourceName:b,targetName:x,stream:m,streamId:d,chunk:H},K)},close(){this.isCancelled||(this.isCancelled=!0,_.postMessage({sourceName:b,targetName:x,stream:h,streamId:d}),delete S.streamSinks[d])},error(H){(0,i.assert)(H instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,_.postMessage({sourceName:b,targetName:x,stream:u,streamId:d,reason:E(H)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:r.desiredSize,ready:null};N.sinkCapability.resolve(),N.ready=N.sinkCapability.promise,this.streamSinks[d]=N,new Promise((function(H){H(R(r.data,N))})).then((function(){_.postMessage({sourceName:b,targetName:x,stream:w,streamId:d,success:!0})}),(function(H){_.postMessage({sourceName:b,targetName:x,stream:w,streamId:d,reason:E(H)})}))}#e(r){let d=r.streamId,b=this.sourceName,x=r.sourceName,_=this.comObj,S=this.streamControllers[d],R=this.streamSinks[d];switch(r.stream){case w:r.success?S.startCall.resolve():S.startCall.reject(E(r.reason));break;case f:r.success?S.pullCall.resolve():S.pullCall.reject(E(r.reason));break;case a:if(!R){_.postMessage({sourceName:b,targetName:x,stream:f,streamId:d,success:!0});break}R.desiredSize<=0&&r.desiredSize>0&&R.sinkCapability.resolve(),R.desiredSize=r.desiredSize,new Promise((function(N){N(R.onPull?.())})).then((function(){_.postMessage({sourceName:b,targetName:x,stream:f,streamId:d,success:!0})}),(function(N){_.postMessage({sourceName:b,targetName:x,stream:f,streamId:d,reason:E(N)})}));break;case m:if((0,i.assert)(S,"enqueue should have stream controller"),S.isClosed)break;S.controller.enqueue(r.chunk);break;case h:if((0,i.assert)(S,"close should have stream controller"),S.isClosed)break;S.isClosed=!0,S.controller.close(),this.#i(S,d);break;case u:(0,i.assert)(S,"error should have stream controller"),S.controller.error(E(r.reason)),this.#i(S,d);break;case l:r.success?S.cancelCall.resolve():S.cancelCall.reject(E(r.reason)),this.#i(S,d);break;case c:if(!R)break;new Promise((function(N){N(R.onCancel?.(E(r.reason)))})).then((function(){_.postMessage({sourceName:b,targetName:x,stream:l,streamId:d,success:!0})}),(function(N){_.postMessage({sourceName:b,targetName:x,stream:l,streamId:d,reason:E(N)})})),R.sinkCapability.reject(E(r.reason)),R.isCancelled=!0,delete this.streamSinks[d];break;default:throw new Error("Unexpected stream case")}}async#i(r,d){await Promise.allSettled([r.startCall?.promise,r.pullCall?.promise,r.cancelCall?.promise]),delete this.streamControllers[d]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},651:(s,t,e)=>{e.d(t,{MurmurHash3_64:()=>c});let i=3285377520,n=4294901760,o=65535;class c{constructor(h){this.h1=h?4294967295&h:i,this.h2=h?4294967295&h:i}update(h){let m,u;if(typeof h=="string"){m=new Uint8Array(2*h.length),u=0;for(let S=0,R=h.length;S<R;S++){let N=h.charCodeAt(S);N<=255?m[u++]=N:(m[u++]=N>>>8,m[u++]=255&N)}}else{if(!ArrayBuffer.isView(h))throw new Error("Invalid data format, must be a string or TypedArray.");m=h.slice(),u=m.byteLength}let a=u>>2,f=u-4*a,w=new Uint32Array(m.buffer,0,a),E=0,p=0,y=this.h1,r=this.h2,d=3432918353,b=461845907,x=11601,_=13715;for(let S=0;S<a;S++)1&S?(E=w[S],E=E*d&n|E*x&o,E=E<<15|E>>>17,E=E*b&n|E*_&o,y^=E,y=y<<13|y>>>19,y=5*y+3864292196):(p=w[S],p=p*d&n|p*x&o,p=p<<15|p>>>17,p=p*b&n|p*_&o,r^=p,r=r<<13|r>>>19,r=5*r+3864292196);switch(E=0,f){case 3:E^=m[4*a+2]<<16;case 2:E^=m[4*a+1]<<8;case 1:E^=m[4*a],E=E*d&n|E*x&o,E=E<<15|E>>>17,E=E*b&n|E*_&o,1&a?y^=E:r^=E}this.h1=y,this.h2=r}hexdigest(){let h=this.h1,m=this.h2;return h^=m>>>1,h=3981806797*h&n|36045*h&o,m=4283543511*m&n|(2950163797*(m<<16|h>>>16)&n)>>>16,h^=m>>>1,h=444984403*h&n|60499*h&o,m=3301882366*m&n|(3120437893*(m<<16|h>>>16)&n)>>>16,h^=m>>>1,(h>>>0).toString(16).padStart(8,"0")+(m>>>0).toString(16).padStart(8,"0")}}},292:(s,t,e)=>{e.d(t,{AbortException:()=>G,AnnotationBorderStyleType:()=>r,AnnotationEditorParamsType:()=>f,AnnotationEditorPrefix:()=>u,AnnotationEditorType:()=>a,AnnotationMode:()=>m,AnnotationPrefix:()=>$,AnnotationType:()=>y,BaseException:()=>j,CMapCompressionType:()=>b,FONT_IDENTITY_MATRIX:()=>o,FeatureTest:()=>v,FormatError:()=>nt,IDENTITY_MATRIX:()=>n,ImageKind:()=>p,InvalidPDFException:()=>tt,LINE_FACTOR:()=>l,MAX_IMAGE_SIZE_TO_CACHE:()=>c,MissingPDFException:()=>st,OPS:()=>x,PasswordException:()=>W,PasswordResponses:()=>_,PermissionFlag:()=>w,RenderingIntentFlag:()=>h,TextRenderingMode:()=>E,UnexpectedResponseException:()=>lt,UnknownErrorException:()=>Y,Util:()=>k,VerbosityLevel:()=>d,assert:()=>it,bytesToString:()=>A,createValidAbsoluteUrl:()=>at,getUuid:()=>L,getVerbosityLevel:()=>N,info:()=>H,isNodeJS:()=>i,normalizeUnicode:()=>C,objectFromMap:()=>g,setVerbosityLevel:()=>R,shadow:()=>X,string32:()=>I,stringToBytes:()=>T,unreachable:()=>K,warn:()=>z});let i=!(typeof process!="object"||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&process.type!=="browser"),n=[1,0,0,1,0,0],o=[.001,0,0,.001,0,0],c=1e7,l=1.35,h={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,OPLIST:256},m={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},u="pdfjs_internal_editor_",a={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},f={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},w={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},E={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},p={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},y={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},r={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},d={ERRORS:0,WARNINGS:1,INFOS:5},b={NONE:0,BINARY:1},x={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},_={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},S=d.WARNINGS;function R(B){Number.isInteger(B)&&(S=B)}function N(){return S}function H(B){S>=d.INFOS&&console.log(`Info: ${B}`)}function z(B){S>=d.WARNINGS&&console.log(`Warning: ${B}`)}function K(B){throw new Error(B)}function it(B,D){B||K(D)}function at(B,D=null,F=null){if(!B)return null;try{if(F&&typeof B=="string"&&(F.addDefaultProtocol&&B.startsWith("www.")&&B.match(/\./g)?.length>=2&&(B=`http://${B}`),F.tryConvertEncoding))try{B=(function(Z){return decodeURIComponent(escape(Z))})(B)}catch{}let V=D?new URL(B,D):new URL(B);if((function(Z){switch(Z?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}})(V))return V}catch{}return null}function X(B,D,F,V=!1){return Object.defineProperty(B,D,{value:F,enumerable:!V,configurable:!0,writable:!1}),F}let j=(function(){function D(F,V){this.constructor===D&&K("Cannot initialize BaseException."),this.message=F,this.name=V}return D.prototype=new Error,D.constructor=D,D})();class W extends j{constructor(D,F){super(D,"PasswordException"),this.code=F}}class Y extends j{constructor(D,F){super(D,"UnknownErrorException"),this.details=F}}class tt extends j{constructor(D){super(D,"InvalidPDFException")}}class st extends j{constructor(D){super(D,"MissingPDFException")}}class lt extends j{constructor(D,F){super(D,"UnexpectedResponseException"),this.status=F}}class nt extends j{constructor(D){super(D,"FormatError")}}class G extends j{constructor(D){super(D,"AbortException")}}function A(B){typeof B=="object"&&B?.length!==void 0||K("Invalid argument for bytesToString");let D=B.length,F=8192;if(D<F)return String.fromCharCode.apply(null,B);let V=[];for(let Q=0;Q<D;Q+=F){let Z=Math.min(Q+F,D),et=B.subarray(Q,Z);V.push(String.fromCharCode.apply(null,et))}return V.join("")}function T(B){typeof B!="string"&&K("Invalid argument for stringToBytes");let D=B.length,F=new Uint8Array(D);for(let V=0;V<D;++V)F[V]=255&B.charCodeAt(V);return F}function I(B){return String.fromCharCode(B>>24&255,B>>16&255,B>>8&255,255&B)}function g(B){let D=Object.create(null);for(let[F,V]of B)D[F]=V;return D}class v{static get isLittleEndian(){return X(this,"isLittleEndian",(function(){let F=new Uint8Array(4);return F[0]=1,new Uint32Array(F.buffer,0,1)[0]===1})())}static get isEvalSupported(){return X(this,"isEvalSupported",(function(){try{return new Function(""),!0}catch{return!1}})())}static get isOffscreenCanvasSupported(){return X(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?X(this,"platform",{isMac:navigator.platform.includes("Mac")}):X(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return X(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}let P=Array.from(Array(256).keys(),(B=>B.toString(16).padStart(2,"0")));class k{static makeHexColor(D,F,V){return`#${P[D]}${P[F]}${P[V]}`}static scaleMinMax(D,F){let V;D[0]?(D[0]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=D[0],F[2]*=D[0],D[3]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=D[3],F[3]*=D[3]):(V=F[0],F[0]=F[1],F[1]=V,V=F[2],F[2]=F[3],F[3]=V,D[1]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=D[1],F[3]*=D[1],D[2]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=D[2],F[2]*=D[2]),F[0]+=D[4],F[1]+=D[5],F[2]+=D[4],F[3]+=D[5]}static transform(D,F){return[D[0]*F[0]+D[2]*F[1],D[1]*F[0]+D[3]*F[1],D[0]*F[2]+D[2]*F[3],D[1]*F[2]+D[3]*F[3],D[0]*F[4]+D[2]*F[5]+D[4],D[1]*F[4]+D[3]*F[5]+D[5]]}static applyTransform(D,F){return[D[0]*F[0]+D[1]*F[2]+F[4],D[0]*F[1]+D[1]*F[3]+F[5]]}static applyInverseTransform(D,F){let V=F[0]*F[3]-F[1]*F[2];return[(D[0]*F[3]-D[1]*F[2]+F[2]*F[5]-F[4]*F[3])/V,(-D[0]*F[1]+D[1]*F[0]+F[4]*F[1]-F[5]*F[0])/V]}static getAxialAlignedBoundingBox(D,F){let V=this.applyTransform(D,F),Q=this.applyTransform(D.slice(2,4),F),Z=this.applyTransform([D[0],D[3]],F),et=this.applyTransform([D[2],D[1]],F);return[Math.min(V[0],Q[0],Z[0],et[0]),Math.min(V[1],Q[1],Z[1],et[1]),Math.max(V[0],Q[0],Z[0],et[0]),Math.max(V[1],Q[1],Z[1],et[1])]}static inverseTransform(D){let F=D[0]*D[3]-D[1]*D[2];return[D[3]/F,-D[1]/F,-D[2]/F,D[0]/F,(D[2]*D[5]-D[4]*D[3])/F,(D[4]*D[1]-D[5]*D[0])/F]}static singularValueDecompose2dScale(D){let F=[D[0],D[2],D[1],D[3]],V=D[0]*F[0]+D[1]*F[2],Q=D[0]*F[1]+D[1]*F[3],Z=D[2]*F[0]+D[3]*F[2],et=D[2]*F[1]+D[3]*F[3],rt=(V+et)/2,pt=Math.sqrt((V+et)**2-4*(V*et-Z*Q))/2,dt=rt+pt||1,ct=rt-pt||1;return[Math.sqrt(dt),Math.sqrt(ct)]}static normalizeRect(D){let F=D.slice(0);return D[0]>D[2]&&(F[0]=D[2],F[2]=D[0]),D[1]>D[3]&&(F[1]=D[3],F[3]=D[1]),F}static intersect(D,F){let V=Math.max(Math.min(D[0],D[2]),Math.min(F[0],F[2])),Q=Math.min(Math.max(D[0],D[2]),Math.max(F[0],F[2]));if(V>Q)return null;let Z=Math.max(Math.min(D[1],D[3]),Math.min(F[1],F[3])),et=Math.min(Math.max(D[1],D[3]),Math.max(F[1],F[3]));return Z>et?null:[V,Z,Q,et]}static#t(D,F,V,Q,Z,et,rt,pt,dt,ct){if(dt<=0||dt>=1)return;let wt=1-dt,Pt=dt*dt,xt=Pt*dt,Dt=wt*(wt*(wt*D+3*dt*F)+3*Pt*V)+xt*Q,Lt=wt*(wt*(wt*Z+3*dt*et)+3*Pt*rt)+xt*pt;ct[0]=Math.min(ct[0],Dt),ct[1]=Math.min(ct[1],Lt),ct[2]=Math.max(ct[2],Dt),ct[3]=Math.max(ct[3],Lt)}static#e(D,F,V,Q,Z,et,rt,pt,dt,ct,wt,Pt){if(Math.abs(dt)<1e-12){Math.abs(ct)>=1e-12&&this.#t(D,F,V,Q,Z,et,rt,pt,-wt/ct,Pt);return}let xt=ct**2-4*wt*dt;if(xt<0)return;let Dt=Math.sqrt(xt),Lt=2*dt;this.#t(D,F,V,Q,Z,et,rt,pt,(-ct+Dt)/Lt,Pt),this.#t(D,F,V,Q,Z,et,rt,pt,(-ct-Dt)/Lt,Pt)}static bezierBoundingBox(D,F,V,Q,Z,et,rt,pt,dt){return dt?(dt[0]=Math.min(dt[0],D,rt),dt[1]=Math.min(dt[1],F,pt),dt[2]=Math.max(dt[2],D,rt),dt[3]=Math.max(dt[3],F,pt)):dt=[Math.min(D,rt),Math.min(F,pt),Math.max(D,rt),Math.max(F,pt)],this.#e(D,V,Z,rt,F,Q,et,pt,3*(3*(V-Z)-D+rt),6*(D-2*V+Z),3*(V-D),dt),this.#e(D,V,Z,rt,F,Q,et,pt,3*(3*(Q-et)-F+pt),6*(F-2*Q+et),3*(Q-F),dt),dt}}let O=null,M=null;function C(B){return O||(O=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,M=new Map([["\uFB05","\u017Ft"]])),B.replaceAll(O,((D,F,V)=>F?F.normalize("NFKC"):M.get(V)))}function L(){if(typeof crypto<"u"&&typeof crypto?.randomUUID=="function")return crypto.randomUUID();let B=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto?.getRandomValues=="function")crypto.getRandomValues(B);else for(let D=0;D<32;D++)B[D]=Math.floor(255*Math.random());return A(B)}let $="pdfjs_internal_id_"}},Bh={};function vs(s){var t=Bh[s];if(t!==void 0)return t.exports;var e=Bh[s]={exports:{}};return op[s](e,e.exports,vs),e.exports}rn=typeof Symbol=="function"?Symbol("webpack queues"):"__webpack_queues__",Vn=typeof Symbol=="function"?Symbol("webpack exports"):"__webpack_exports__",Wn=typeof Symbol=="function"?Symbol("webpack error"):"__webpack_error__",Lo=s=>{s&&s.d<1&&(s.d=1,s.forEach((t=>t.r--)),s.forEach((t=>t.r--?t.r++:t())))},vs.a=(s,t,e)=>{var i;e&&((i=[]).d=-1);var n,o,c,l=new Set,h=s.exports,m=new Promise(((u,a)=>{c=a,o=u}));m[Vn]=h,m[rn]=u=>(i&&u(i),l.forEach(u),m.catch((a=>{}))),s.exports=m,t((u=>{n=(E=>E.map((p=>{if(p!==null&&typeof p=="object"){if(p[rn])return p;if(p.then){var y=[];y.d=0,p.then((b=>{r[Vn]=b,Lo(y)}),(b=>{r[Wn]=b,Lo(y)}));var r={};return r[rn]=b=>b(y),r}}var d={};return d[rn]=b=>{},d[Vn]=p,d})))(u);var a,f=()=>n.map((E=>{if(E[Wn])throw E[Wn];return E[Vn]})),w=new Promise((E=>{(a=()=>E(f)).r=0;var p=y=>y!==i&&!l.has(y)&&(l.add(y),y&&!y.d&&(a.r++,y.push(a)));n.map((y=>y[rn](p)))}));return a.r?w:f()}),(u=>(u?c(m[Wn]=u):o(h),Lo(i)))),i&&i.d<0&&(i.d=0)};vs.d=(s,t)=>{for(var e in t)vs.o(t,e)&&!vs.o(s,e)&&Object.defineProperty(s,e,{enumerable:!0,get:t[e]})};vs.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var _t=vs(228),pg=(_t=globalThis.pdfjsLib=await(globalThis.pdfjsLibPromise=_t)).AbortException,fg=_t.AnnotationEditorLayer,gg=_t.AnnotationEditorParamsType,mg=_t.AnnotationEditorType,bg=_t.AnnotationEditorUIManager,yg=_t.AnnotationLayer,vg=_t.AnnotationMode,wg=_t.CMapCompressionType,xg=_t.ColorPicker,Ag=_t.DOMSVGFactory,Sg=_t.DrawLayer,Eg=_t.FeatureTest,$h=_t.GlobalWorkerOptions,Cg=_t.ImageKind,_g=_t.InvalidPDFException,Tg=_t.MissingPDFException,Pg=_t.OPS,kg=_t.Outliner,Dg=_t.PDFDataRangeTransport,Rg=_t.PDFDateString,Mg=_t.PDFWorker,Ig=_t.PasswordResponses,Lg=_t.PermissionFlag,Fg=_t.PixelsPerInch,Og=_t.RenderingCancelledException,Ng=_t.UnexpectedResponseException,Bg=_t.Util,$g=_t.VerbosityLevel,Ug=_t.XfaLayer,Hg=_t.build,zg=_t.createValidAbsoluteUrl,jg=_t.fetchData,Uh=_t.getDocument,Vg=_t.getFilenameFromUrl,Wg=_t.getPdfFilenameFromUrl,Gg=_t.getXfaPageViewport,qg=_t.isDataScheme,Xg=_t.isPdfFile,Kg=_t.noContextMenu,Yg=_t.normalizeUnicode,Jg=_t.renderTextLayer,Qg=_t.setLayerDimensions,Zg=_t.shadow,tm=_t.updateTextLayer,em=_t.version;ci();$h.workerSrc=li("js/lib/pdf.worker.min.mjs");async function on(s,t=2){let e=await Uh({data:s}).promise,i=[];for(let n=1;n<=e.numPages;n++){let o=await e.getPage(n),c=o.getViewport({scale:t}),l=document.createElement("canvas"),h=l.getContext("2d");l.width=c.width,l.height=c.height,await o.render({canvasContext:h,viewport:c}).promise,i.push(l.toDataURL("image/jpeg",.82))}return i}Bi();ci();var Vh=`
|
|
20
|
-
.cropper-container {
|
|
21
|
-
direction: ltr;
|
|
22
|
-
font-size: 0;
|
|
23
|
-
line-height: 0;
|
|
24
|
-
position: relative;
|
|
25
|
-
-ms-touch-action: none;
|
|
26
|
-
touch-action: none;
|
|
27
|
-
-webkit-user-select: none;
|
|
28
|
-
-moz-user-select: none;
|
|
29
|
-
-ms-user-select: none;
|
|
30
|
-
user-select: none;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
.cropper-container img {
|
|
34
|
-
display: block;
|
|
35
|
-
height: 100%;
|
|
36
|
-
image-orientation: 0deg;
|
|
37
|
-
max-height: none !important;
|
|
38
|
-
max-width: none !important;
|
|
39
|
-
min-height: 0 !important;
|
|
40
|
-
min-width: 0 !important;
|
|
41
|
-
width: 100%;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
.cropper-wrap-box,
|
|
45
|
-
.cropper-canvas,
|
|
46
|
-
.cropper-drag-box,
|
|
47
|
-
.cropper-crop-box,
|
|
48
|
-
.cropper-modal {
|
|
49
|
-
bottom: 0;
|
|
50
|
-
left: 0;
|
|
51
|
-
position: absolute;
|
|
52
|
-
right: 0;
|
|
53
|
-
top: 0;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
.cropper-wrap-box,
|
|
57
|
-
.cropper-canvas {
|
|
58
|
-
overflow: hidden;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
.cropper-drag-box {
|
|
62
|
-
background-color: #fff;
|
|
63
|
-
opacity: 0;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
.cropper-modal {
|
|
67
|
-
background-color: #000;
|
|
68
|
-
opacity: 0.5;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
.cropper-view-box {
|
|
72
|
-
display: block;
|
|
73
|
-
height: 100%;
|
|
74
|
-
outline-color: rgba(51, 153, 255, 0.75);
|
|
75
|
-
outline: 1px solid #39f;
|
|
76
|
-
overflow: hidden;
|
|
77
|
-
width: 100%;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
.cropper-dashed {
|
|
81
|
-
border: 0 dashed #eee;
|
|
82
|
-
display: block;
|
|
83
|
-
opacity: 0.5;
|
|
84
|
-
position: absolute;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
.cropper-dashed.dashed-h {
|
|
88
|
-
border-bottom-width: 1px;
|
|
89
|
-
border-top-width: 1px;
|
|
90
|
-
height: 33.33333%;
|
|
91
|
-
left: 0;
|
|
92
|
-
top: 33.33333%;
|
|
93
|
-
width: 100%;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
.cropper-dashed.dashed-v {
|
|
97
|
-
border-left-width: 1px;
|
|
98
|
-
border-right-width: 1px;
|
|
99
|
-
height: 100%;
|
|
100
|
-
left: 33.33333%;
|
|
101
|
-
top: 0;
|
|
102
|
-
width: 33.33333%;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
.cropper-center {
|
|
106
|
-
display: block;
|
|
107
|
-
height: 0;
|
|
108
|
-
left: 50%;
|
|
109
|
-
opacity: 0.75;
|
|
110
|
-
position: absolute;
|
|
111
|
-
top: 50%;
|
|
112
|
-
width: 0;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
.cropper-center:before,
|
|
116
|
-
.cropper-center:after {
|
|
117
|
-
background-color: #eee;
|
|
118
|
-
content: ' ';
|
|
119
|
-
display: block;
|
|
120
|
-
position: absolute;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
.cropper-center:before {
|
|
124
|
-
height: 1px;
|
|
125
|
-
left: -3px;
|
|
126
|
-
top: 0;
|
|
127
|
-
width: 7px;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
.cropper-center:after {
|
|
131
|
-
height: 7px;
|
|
132
|
-
left: 0;
|
|
133
|
-
top: -3px;
|
|
134
|
-
width: 1px;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
.cropper-face,
|
|
138
|
-
.cropper-line,
|
|
139
|
-
.cropper-point {
|
|
140
|
-
display: block;
|
|
141
|
-
height: 100%;
|
|
142
|
-
opacity: 0.1;
|
|
143
|
-
position: absolute;
|
|
144
|
-
width: 100%;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
.cropper-face {
|
|
148
|
-
background-color: #fff;
|
|
149
|
-
left: 0;
|
|
150
|
-
top: 0;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
.cropper-line {
|
|
154
|
-
background-color: #39f;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
.cropper-line.line-e {
|
|
158
|
-
cursor: ew-resize;
|
|
159
|
-
right: -3px;
|
|
160
|
-
top: 0;
|
|
161
|
-
width: 5px;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
.cropper-line.line-n {
|
|
165
|
-
cursor: ns-resize;
|
|
166
|
-
height: 5px;
|
|
167
|
-
left: 0;
|
|
168
|
-
top: -3px;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
.cropper-line.line-w {
|
|
172
|
-
cursor: ew-resize;
|
|
173
|
-
left: -3px;
|
|
174
|
-
top: 0;
|
|
175
|
-
width: 5px;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
.cropper-line.line-s {
|
|
179
|
-
bottom: -3px;
|
|
180
|
-
cursor: ns-resize;
|
|
181
|
-
height: 5px;
|
|
182
|
-
left: 0;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
.cropper-point {
|
|
186
|
-
width: var(--copio-crop-handle-hit, 48px);
|
|
187
|
-
height: var(--copio-crop-handle-hit, 48px);
|
|
188
|
-
min-width: 44px;
|
|
189
|
-
min-height: 44px;
|
|
190
|
-
background-color: transparent;
|
|
191
|
-
opacity: 1;
|
|
192
|
-
display: flex;
|
|
193
|
-
align-items: center;
|
|
194
|
-
justify-content: center;
|
|
195
|
-
box-sizing: border-box;
|
|
196
|
-
touch-action: none;
|
|
197
|
-
z-index: 10;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
.cropper-point::after {
|
|
201
|
-
content: '';
|
|
202
|
-
display: block;
|
|
203
|
-
width: var(--copio-crop-handle-visual, 16px);
|
|
204
|
-
height: var(--copio-crop-handle-visual, 16px);
|
|
205
|
-
border-radius: 50%;
|
|
206
|
-
background-color: var(--copio-color-primary, #38bdf8);
|
|
207
|
-
border: 2.5px solid #ffffff;
|
|
208
|
-
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);
|
|
209
|
-
transition: transform 120ms ease;
|
|
210
|
-
box-sizing: border-box;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
.cropper-point:hover::after,
|
|
214
|
-
.cropper-point:active::after {
|
|
215
|
-
transform: scale(1.25);
|
|
216
|
-
background-color: var(--copio-color-success, #22c55e);
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
.cropper-point.point-e {
|
|
220
|
-
cursor: ew-resize;
|
|
221
|
-
margin-top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
222
|
-
right: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
223
|
-
top: 50%;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
.cropper-point.point-n {
|
|
227
|
-
cursor: ns-resize;
|
|
228
|
-
left: 50%;
|
|
229
|
-
margin-left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
230
|
-
top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
.cropper-point.point-w {
|
|
234
|
-
cursor: ew-resize;
|
|
235
|
-
left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
236
|
-
margin-top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
237
|
-
top: 50%;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
.cropper-point.point-s {
|
|
241
|
-
bottom: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
242
|
-
cursor: s-resize;
|
|
243
|
-
left: 50%;
|
|
244
|
-
margin-left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
.cropper-point.point-ne {
|
|
248
|
-
cursor: nesw-resize;
|
|
249
|
-
right: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
250
|
-
top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
.cropper-point.point-nw {
|
|
254
|
-
cursor: nwse-resize;
|
|
255
|
-
left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
256
|
-
top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
.cropper-point.point-sw {
|
|
260
|
-
bottom: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
261
|
-
cursor: nesw-resize;
|
|
262
|
-
left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
.cropper-point.point-se {
|
|
266
|
-
bottom: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
267
|
-
cursor: nwse-resize;
|
|
268
|
-
right: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
.cropper-invisible {
|
|
272
|
-
opacity: 0;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
.cropper-bg {
|
|
276
|
-
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC');
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
.cropper-hide {
|
|
280
|
-
display: block;
|
|
281
|
-
height: 0;
|
|
282
|
-
position: absolute;
|
|
283
|
-
width: 0;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
.cropper-hidden {
|
|
287
|
-
display: none !important;
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
.cropper-move {
|
|
291
|
-
cursor: move;
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
.cropper-crop {
|
|
295
|
-
cursor: crosshair;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
.cropper-disabled .cropper-drag-box,
|
|
299
|
-
.cropper-disabled .cropper-face,
|
|
300
|
-
.cropper-disabled .cropper-line,
|
|
301
|
-
.cropper-disabled .cropper-point {
|
|
302
|
-
cursor: not-allowed;
|
|
303
|
-
}
|
|
304
|
-
`;var Gn=class extends HTMLElement{#t=[];#e=null;#i=null;#n=null;#r=!1;#s=null;#a=new Set;#l=null;#o=!0;#h=!0;constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.#r||(this.#f(),this.#r=!0),this.#g()}disconnectedCallback(){if(this.#i){try{this.#i.destroy()}catch(i){console.warn("Error destroying Sortable:",i)}this.#i=null}if(this.#e){try{this.#e.destroy()}catch(i){console.warn("Error destroying Cropper:",i)}this.#e=null}this.#n=null,this.stopCamera(),this.#c(),this.#s&&(this.#s.abort(),this.#s=null);let t=this.shadowRoot.querySelector(".file-input"),e=this.shadowRoot.querySelector(".camera-input");t&&(t.onchange=null),e&&(e.onchange=null),this.#r=!1}setCameraStream(t){this.stopCamera(),this.#l=t||null}stopCamera(){if(this.#l){try{(typeof this.#l.getTracks=="function"?this.#l.getTracks():[]).forEach(e=>{typeof e.stop=="function"&&e.stop()})}catch(t){console.warn("Error stopping camera tracks:",t)}this.#l=null}}#u(t){return t&&typeof t=="string"&&t.startsWith("blob:")&&this.#a.add(t),t}#d(t){if(this.#a.has(t)){try{URL.revokeObjectURL(t)}catch{}this.#a.delete(t)}}#c(){for(let t of this.#a)try{URL.revokeObjectURL(t)}catch{}this.#a.clear()}#f(){let t=`
|
|
305
|
-
<style>
|
|
306
|
-
${Vh}
|
|
307
|
-
</style>
|
|
308
|
-
<style>
|
|
309
|
-
.container {
|
|
310
|
-
display: grid;
|
|
311
|
-
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
|
|
312
|
-
gap: 0.75rem;
|
|
313
|
-
max-width: 100%;
|
|
314
|
-
min-height: 140px;
|
|
315
|
-
padding: 0.5rem;
|
|
316
|
-
border-radius: 8px;
|
|
317
|
-
border: 2px dashed transparent;
|
|
318
|
-
box-sizing: border-box;
|
|
319
|
-
transition: border-color 0.2s, background-color 0.2s;
|
|
320
|
-
}
|
|
321
|
-
.container.drag-over {
|
|
322
|
-
border-color: #3b82f6;
|
|
323
|
-
background-color: rgba(59, 130, 246, 0.08);
|
|
324
|
-
box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.2);
|
|
325
|
-
}
|
|
326
|
-
@container copio-scanner (max-width: 400px) {
|
|
327
|
-
.container {
|
|
328
|
-
grid-template-columns: repeat(2, 1fr);
|
|
329
|
-
gap: 0.5rem;
|
|
330
|
-
padding: 0.25rem;
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
@container copio-scanner (min-width: 401px) and (max-width: 767px) {
|
|
334
|
-
.container {
|
|
335
|
-
grid-template-columns: repeat(3, 1fr);
|
|
336
|
-
gap: 0.75rem;
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
@container copio-scanner (min-width: 768px) {
|
|
340
|
-
.container {
|
|
341
|
-
grid-template-columns: repeat(4, 1fr);
|
|
342
|
-
gap: 1rem;
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
/* Fallbacks if container queries are unsupported or outside named container */
|
|
346
|
-
@supports not (container-type: size) {
|
|
347
|
-
@media (min-width: 640px) {
|
|
348
|
-
.container {
|
|
349
|
-
grid-template-columns: repeat(3, 1fr);
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
@media (min-width: 1024px) {
|
|
353
|
-
.container {
|
|
354
|
-
grid-template-columns: repeat(4, 1fr);
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
.image-wrapper {
|
|
359
|
-
cursor: grab;
|
|
360
|
-
position: relative;
|
|
361
|
-
user-select: none;
|
|
362
|
-
-webkit-user-select: none;
|
|
363
|
-
width: 100%;
|
|
364
|
-
aspect-ratio: 1;
|
|
365
|
-
}
|
|
366
|
-
.image-wrapper:active {
|
|
367
|
-
cursor: grabbing;
|
|
368
|
-
}
|
|
369
|
-
.image-wrapper.dragging {
|
|
370
|
-
opacity: 0.4;
|
|
371
|
-
cursor: grabbing;
|
|
372
|
-
}
|
|
373
|
-
.image-wrapper.sortable-ghost {
|
|
374
|
-
opacity: 0.2;
|
|
375
|
-
}
|
|
376
|
-
.image-menu {
|
|
377
|
-
position: absolute;
|
|
378
|
-
top: 4px;
|
|
379
|
-
right: 4px;
|
|
380
|
-
}
|
|
381
|
-
img {
|
|
382
|
-
width: 100%;
|
|
383
|
-
height: 100%;
|
|
384
|
-
object-fit: cover;
|
|
385
|
-
border: 1px solid #ccc;
|
|
386
|
-
border-radius: 4px;
|
|
387
|
-
display: block;
|
|
388
|
-
}
|
|
389
|
-
#crop-image {
|
|
390
|
-
max-width: 100%;
|
|
391
|
-
max-height: 100%;
|
|
392
|
-
display: block;
|
|
393
|
-
}
|
|
394
|
-
.crop-wrapper {
|
|
395
|
-
width: 100%;
|
|
396
|
-
height: 360px;
|
|
397
|
-
max-height: min(50vh, 380px);
|
|
398
|
-
min-height: 200px;
|
|
399
|
-
position: relative;
|
|
400
|
-
display: flex;
|
|
401
|
-
align-items: center;
|
|
402
|
-
justify-content: center;
|
|
403
|
-
overflow: visible;
|
|
404
|
-
box-sizing: border-box;
|
|
405
|
-
margin-bottom: 0.5rem;
|
|
406
|
-
}
|
|
407
|
-
sl-dialog::part(base) {
|
|
408
|
-
position: absolute;
|
|
409
|
-
}
|
|
410
|
-
sl-dialog::part(overlay) {
|
|
411
|
-
position: absolute;
|
|
412
|
-
}
|
|
413
|
-
sl-dialog::part(panel) {
|
|
414
|
-
max-width: calc(100% - 20px);
|
|
415
|
-
max-height: calc(100% - 20px);
|
|
416
|
-
}
|
|
417
|
-
.crop-dialog::part(panel) {
|
|
418
|
-
max-width: min(94%, 560px);
|
|
419
|
-
max-height: calc(100% - 16px);
|
|
420
|
-
display: flex;
|
|
421
|
-
flex-direction: column;
|
|
422
|
-
}
|
|
423
|
-
.crop-dialog::part(body) {
|
|
424
|
-
padding: 24px;
|
|
425
|
-
overflow: hidden;
|
|
426
|
-
display: flex;
|
|
427
|
-
align-items: center;
|
|
428
|
-
justify-content: center;
|
|
429
|
-
flex: 1 1 auto;
|
|
430
|
-
min-height: 0;
|
|
431
|
-
}
|
|
432
|
-
@container copio-scanner (max-width: 400px) {
|
|
433
|
-
.crop-wrapper {
|
|
434
|
-
height: 240px;
|
|
435
|
-
max-height: 42cqh;
|
|
436
|
-
min-height: 160px;
|
|
437
|
-
}
|
|
438
|
-
.crop-dialog::part(panel) {
|
|
439
|
-
max-width: calc(100% - 12px);
|
|
440
|
-
max-height: calc(100% - 12px);
|
|
441
|
-
}
|
|
442
|
-
.crop-dialog::part(body) {
|
|
443
|
-
padding: 16px;
|
|
444
|
-
}
|
|
445
|
-
.crop-dialog::part(header) {
|
|
446
|
-
padding: 0.5rem 0.75rem;
|
|
447
|
-
}
|
|
448
|
-
.crop-dialog::part(footer) {
|
|
449
|
-
padding: 0.5rem 0.75rem;
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
button.add-btn {
|
|
453
|
-
width: 100%;
|
|
454
|
-
aspect-ratio: 1;
|
|
455
|
-
font-size: 1.6rem;
|
|
456
|
-
border: 2px dashed #888;
|
|
457
|
-
border-radius: 4px;
|
|
458
|
-
background: none;
|
|
459
|
-
cursor: pointer;
|
|
460
|
-
display: flex;
|
|
461
|
-
align-items: center;
|
|
462
|
-
justify-content: center;
|
|
463
|
-
color: #64748b;
|
|
464
|
-
transition: border-color 0.15s, color 0.15s, background-color 0.15s;
|
|
465
|
-
}
|
|
466
|
-
button.add-btn:hover {
|
|
467
|
-
border-color: #3b82f6;
|
|
468
|
-
color: #3b82f6;
|
|
469
|
-
background-color: rgba(59, 130, 246, 0.04);
|
|
470
|
-
}
|
|
471
|
-
dialog {
|
|
472
|
-
border: none;
|
|
473
|
-
border-radius: 6px;
|
|
474
|
-
padding: 1rem;
|
|
475
|
-
}
|
|
476
|
-
dialog::backdrop {
|
|
477
|
-
background: rgba(0, 0, 0, 0.3);
|
|
478
|
-
}
|
|
479
|
-
</style>
|
|
480
|
-
`;this.shadowRoot.innerHTML=`
|
|
481
|
-
${t}
|
|
482
|
-
<div class="container"></div>
|
|
483
|
-
|
|
484
|
-
<input type="file" class="file-input" accept="image/*,application/pdf" multiple style="display: none">
|
|
485
|
-
<input type="file" class="camera-input" accept="image/*" capture="environment" style="display: none">
|
|
486
|
-
|
|
487
|
-
<sl-dialog label="Image Data" class="data-dialog">
|
|
488
|
-
<div class="exif-data" style="font-size: 0.85rem; line-height: 1.6;"></div>
|
|
489
|
-
<sl-button slot="footer" variant="primary" class="close-data">Close</sl-button>
|
|
490
|
-
</sl-dialog>
|
|
491
|
-
|
|
492
|
-
<sl-dialog label="Crop Image" class="crop-dialog" style="--width: min(94%, 560px)">
|
|
493
|
-
<div class="crop-wrapper">
|
|
494
|
-
<img id="crop-image" />
|
|
495
|
-
</div>
|
|
496
|
-
<sl-button slot="footer" variant="default" class="cancel-crop">Cancel</sl-button>
|
|
497
|
-
<sl-button slot="footer" variant="primary" class="apply-crop">Apply</sl-button>
|
|
498
|
-
</sl-dialog>
|
|
499
|
-
`,this.#s&&this.#s.abort(),this.#s=new AbortController;let{signal:e}=this.#s,i=this.shadowRoot.querySelector(".close-data");i&&i.addEventListener("click",()=>{this.shadowRoot.querySelector(".data-dialog")?.hide()},{signal:e});let n=this.shadowRoot.querySelector(".file-input"),o=this.shadowRoot.querySelector(".camera-input"),c=!1,l=async d=>{if(c)return;let b=Array.from(d.target?.files||[]);if(b.length!==0){c=!0;try{await this.addFiles(b)}finally{d.target&&(d.target.value=""),c=!1}}};n&&(n.onchange=l,n.addEventListener("change",l,{signal:e})),o&&(o.onchange=l,o.addEventListener("change",l,{signal:e}));let h=0,m=d=>{let b=d.dataTransfer;if(!b)return!1;if(!b.types||b.types.length===0)return!0;let x=Array.from(b.types);return x.includes("Files")||x.some(_=>_.startsWith("image/")||_.startsWith("public.")||_.includes("pdf")||_.includes("file")||_==="text/uri-list")},u=d=>{m(d)&&(d.preventDefault(),h++,E.classList.add("drag-over"))},a=d=>{m(d)&&(d.preventDefault(),d.stopPropagation(),d.dataTransfer&&(d.dataTransfer.dropEffect="copy"),E.classList.add("drag-over"))},f=()=>{h--,h<=0&&(h=0,E.classList.remove("drag-over"))},w=async d=>{h=0,E.classList.remove("drag-over"),d.preventDefault(),d.stopPropagation();let b=[];if(d.dataTransfer?.files?.length>0)b=Array.from(d.dataTransfer.files);else if(d.dataTransfer?.items?.length>0){for(let x of d.dataTransfer.items)if(x.kind==="file"){let _=x.getAsFile();_&&b.push(_)}}else d.detail?.files&&(b=Array.from(d.detail.files));b.length>0&&await this.addFiles(b)},E=this.shadowRoot.querySelector(".container");E&&(E.addEventListener("dragenter",u,{signal:e}),E.addEventListener("dragover",a,{signal:e}),E.addEventListener("dragleave",f,{signal:e}),E.addEventListener("drop",w,{signal:e}),E.addEventListener("dragend",()=>{h=0,E.classList.remove("drag-over")},{signal:e}),E.addEventListener("click",d=>{d.target===E&&n?.click()},{signal:e}));let p=this.shadowRoot.querySelector(".cancel-crop"),y=this.shadowRoot.querySelector(".apply-crop");p&&p.addEventListener("click",()=>this.closeCropDialog(),{signal:e}),y&&y.addEventListener("click",()=>this.applyCrop(),{signal:e});let r=this.shadowRoot.querySelector(".crop-dialog");r&&r.addEventListener("sl-hide",()=>{this.#e&&(this.#e.destroy(),this.#e=null),this.#n=null},{signal:e})}#g(){let t=this.shadowRoot.querySelector(".container");if(!t)return;let e=this.#t.map((o,c)=>{let l=za(o.edits),h=o.edits?.filter==="bw";return`
|
|
500
|
-
<div class="image-wrapper" data-index="${c}">
|
|
501
|
-
<img src="${o.src}" draggable="false">
|
|
502
|
-
<sl-dropdown class="image-menu" data-index="${c}">
|
|
503
|
-
<sl-button slot="trigger" variant="default" size="small" circle>
|
|
504
|
-
<sl-icon name="three-dots-vertical"></sl-icon>
|
|
505
|
-
</sl-button>
|
|
506
|
-
<sl-menu>
|
|
507
|
-
${this.ocr!==!1?`
|
|
508
|
-
<sl-menu-item value="ocr">
|
|
509
|
-
<sl-icon slot="prefix" name="card-text"></sl-icon> Extract Text
|
|
510
|
-
</sl-menu-item>
|
|
511
|
-
<sl-divider></sl-divider>
|
|
512
|
-
`:""}
|
|
513
|
-
<sl-menu-item value="crop">Crop</sl-menu-item>
|
|
514
|
-
<sl-menu-item value="rotate">Rotate</sl-menu-item>
|
|
515
|
-
<sl-menu-item value="threshold">
|
|
516
|
-
<sl-icon slot="prefix" name="${h?"check-lg":"circle"}"></sl-icon>
|
|
517
|
-
${h?"Remove Black & White":"Black & White"}
|
|
518
|
-
</sl-menu-item>
|
|
519
|
-
<sl-menu-item value="reset" ?disabled=${!l}>
|
|
520
|
-
<sl-icon slot="prefix" name="arrow-counterclockwise"></sl-icon>
|
|
521
|
-
Reset to Original
|
|
522
|
-
</sl-menu-item>
|
|
523
|
-
<sl-menu-item value="showdata">Show Data</sl-menu-item>
|
|
524
|
-
<sl-menu-item value="download">Download Image</sl-menu-item>
|
|
525
|
-
<sl-divider></sl-divider>
|
|
526
|
-
<sl-menu-item value="delete">Delete</sl-menu-item>
|
|
527
|
-
</sl-menu>
|
|
528
|
-
</sl-dropdown>
|
|
529
|
-
</div>
|
|
530
|
-
`}).join("");t.innerHTML=`
|
|
531
|
-
${e}
|
|
532
|
-
<button class="add-btn add-image-btn" title="Add image or PDF" aria-label="Add image or PDF">
|
|
533
|
-
<sl-icon name="plus-lg"></sl-icon>
|
|
534
|
-
</button>
|
|
535
|
-
<button class="add-btn add-camera-btn" title="Capture from camera" aria-label="Capture from camera">
|
|
536
|
-
<sl-icon name="camera"></sl-icon>
|
|
537
|
-
</button>
|
|
538
|
-
`;let i=t.querySelector(".add-image-btn");i&&(i.onclick=()=>{this.shadowRoot.querySelector(".file-input").click()});let n=t.querySelector(".add-camera-btn");n&&(n.onclick=()=>{this.shadowRoot.querySelector(".camera-input").click()}),t.querySelectorAll(".image-menu").forEach(o=>{o.querySelector("sl-menu").addEventListener("sl-select",l=>{l.stopPropagation();let h=parseInt(o.dataset.index),m=l.detail.item.value;if(m==="ocr")o.hide(),this.dispatchEvent(new CustomEvent("copio:ocr-page",{bubbles:!0,composed:!0,detail:{page:this.#t[h],pageIndex:h}}));else if(m==="crop")o.hide(),this.openCropDialog(h);else if(m==="rotate")this.rotateImage(h);else if(m==="threshold")this.thresholdImage(h);else if(m==="reset")o.hide(),this.resetImage(h);else if(m==="showdata")o.hide(),this.showImageData(h);else if(m==="download")this.downloadImage(h);else if(m==="delete"){let[u]=this.#t.splice(h,1);this.#g();let a=u.name||`Page ${h+1}`;Mt.undo(`Deleted ${a}`,()=>{this.#t.splice(h,0,u),this.#g(),Mt.success(`Restored ${a}`)},{duration:5e3})}})}),this.#p(t)}#p(t){if(this.#i){try{this.#i.destroy()}catch(e){console.warn("Error destroying Sortable:",e)}this.#i=null}this.#i=Th.create(t,{animation:150,draggable:".image-wrapper",chosenClass:"dragging",ghostClass:"sortable-ghost",filter:"sl-dropdown",preventOnFilter:!1,delay:150,delayOnTouchOnly:!0,touchStartThreshold:5,onEnd:e=>{if(e.to!==t)return;let i=e.oldDraggableIndex,n=e.newDraggableIndex;if(i===n)return;let o=this.#t[i];this.#t.splice(i,1),this.#t.splice(n,0,o),this.#g()}})}async openCropDialog(t){this.#n=t;let e=this.#t[t];if(!e)return;let i=this.shadowRoot.querySelector(".crop-dialog"),n=this.shadowRoot.querySelector("#crop-image");e.originalSrc=e.originalSrc||e.src,e.edits=qe(e.edits),n.src=e.originalSrc,i.show();let o=await co(),c=e.edits?.crop,l=()=>{this.#e&&this.#e.destroy(),this.#e=new o(n,{viewMode:1,autoCropArea:.88,responsive:!0,ready:()=>{if(c)try{if(c.width>0&&c.height>0)this.#e.setData({x:c.x,y:c.y,width:c.width,height:c.height});else if(c.normalized&&c.normalized.w>0){let h=this.#e.getImageData();this.#e.setData({x:Math.round(c.normalized.x*h.naturalWidth),y:Math.round(c.normalized.y*h.naturalHeight),width:Math.round(c.normalized.w*h.naturalWidth),height:Math.round(c.normalized.h*h.naturalHeight)})}else if(typeof c.w=="number"&&c.w>0){let h=this.#e.getImageData();this.#e.setData({x:Math.round(c.x*h.naturalWidth),y:Math.round(c.y*h.naturalHeight),width:Math.round(c.w*h.naturalWidth),height:Math.round(c.h*h.naturalHeight)})}}catch(h){console.warn("Failed restoring prior crop box:",h)}}})};n.onload=l,n.complete&&n.naturalWidth>0&&!this.#e&&l()}closeCropDialog(){let t=this.shadowRoot.querySelector(".crop-dialog"),e=this.shadowRoot.querySelector("#crop-image");if(e&&(e.onload=null),this.#e){try{this.#e.destroy()}catch(i){console.warn("Error destroying Cropper:",i)}this.#e=null}this.#n=null,t?.hide()}applyCrop(){if(this.#e&&this.#n!==null){let t=this.#t[this.#n];if(!t)return;t.originalSrc=t.originalSrc||t.src||"";let e=this.#e.getData(!0),i=this.#e.getImageData(),n=i?.naturalWidth||1,o=i?.naturalHeight||1,c=Math.max(0,Math.min(1,e.x/n)),l=Math.max(0,Math.min(1,e.y/o)),h=Math.max(0,Math.min(1,e.width/n)),m=Math.max(0,Math.min(1,e.height/o));t.edits={...qe(t.edits),crop:{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height),normalized:{x:Number(c.toFixed(4)),y:Number(l.toFixed(4)),w:Number(h.toFixed(4)),h:Number(m.toFixed(4))}}};let u=this.#e.getCroppedCanvas();if(u){let a=Ks(u,{crop:null,rotation:t.edits.rotation,filter:t.edits.filter}),f=typeof t.originalSrc=="string"&&t.originalSrc.startsWith("data:image/png")||t.originalBlob?.type==="image/png"||t.mimeType==="image/png",w=f?"image/png":"image/jpeg";t.src=a.toDataURL(w,f?void 0:.82)}this.#g(),this.closeCropDialog()}}async rotateImage(t){let e=this.#t[t];e&&(e.originalSrc=e.originalSrc||e.src,e.edits={...qe(e.edits),rotation:((e.edits?.rotation||0)+90)%360},e.src=await Rn(e.originalSrc,e.edits),this.#g())}async thresholdImage(t){let e=this.#t[t];if(!e)return;e.originalSrc=e.originalSrc||e.src;let i=e.edits?.filter==="bw";e.edits={...qe(e.edits),filter:i?"none":"bw"},e.src=await Rn(e.originalSrc,e.edits),this.#g(),i?Mt.info("Restored color (removed B&W filter)"):Mt.success("Applied B&W threshold filter")}resetImage(t){let e=this.#t[t];e&&(e.edits={crop:null,rotation:0,filter:"none"},e.src=e.originalSrc||e.src,this.#g(),Mt.success("Reset page to original"))}downloadImage(t){let e=this.#t[t];if(!e)return;let i="jpg",n=e.src,o=!1;if(e.blob instanceof Blob)e.blob.type&&e.blob.type.includes("png")&&(i="png"),n=this.#u(URL.createObjectURL(e.blob)),o=!0;else if(e.src){if(e.src.startsWith("data:")){let h=e.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);h&&h[1].includes("png")&&(i="png")}}else return;let c=document.createElement("a"),l=`image-${t+1}.${i}`;c.href=n,c.download=l,c.click(),o&&this.#d(n),Mt.success(`Downloaded "${l}"`)}showImageData(t){let{src:e,exif:i}=this.#t[t],n=this.shadowRoot.querySelector(`img[src="${e}"]`),o=[];if(o.push(`<strong>Dimensions:</strong> ${n?`${n.naturalWidth} \xD7 ${n.naturalHeight}`:"unknown"}`),i){let c=new Set(["MakerNote","UserComment","FlashPixVersion","ExifVersion","ComponentsConfiguration","SceneType","thumbnail"]);for(let[l,h]of Object.entries(i)){if(c.has(l)||h===void 0||h===null)continue;let m=h instanceof Array?h.join(", "):String(h);m.length>200||o.push(`<strong>${l}:</strong> ${m}`)}}else o.push("<em>No EXIF data available</em>");this.shadowRoot.querySelector(".exif-data").innerHTML=o.join("<br>"),this.shadowRoot.querySelector(".data-dialog").show()}async pdfToImages(t){let e=await t.arrayBuffer();return(await on(e)).map(n=>({id:De(),src:n,originalSrc:n,edits:{crop:null,rotation:0,filter:"none"}}))}async addFiles(t){if(!t||t.length===0)return;let e=[];try{for(let n of t)if(n.type==="application/pdf"){let o=await this.pdfToImages(n);e.push(...o)}else{let[o,c]=await Promise.all([Xs(n),qs(n)]);e.push({id:De(),src:o,originalSrc:o,edits:{crop:null,rotation:0,filter:"none"},exif:c})}this.#t.push(...e),this.#g();let i=e.length;Mt.success(`Imported ${i} page${i!==1?"s":""}`)}catch(i){console.error("Failed to import files:",i),Mt.error("Failed to import files")}}get ocr(){return this.#o!==!1}set ocr(t){this.#o=!!t,this.#r&&this.#g()}get pdf(){return this.#h!==!1}set pdf(t){this.#h=!!t,this.#r&&this.#g()}get images(){return this.#t}set images(t){let e=Array.isArray(t)?t:[];this.#t=e.map(i=>i&&{...i,originalSrc:i.originalSrc||i.src||"",edits:qe(i.edits)}),this.#r&&this.#g()}};customElements.define("copio-images",Gn);var Fo=globalThis,El=Fo.ShadowRoot&&(Fo.ShadyCSS===void 0||Fo.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Cl=Symbol(),Wh=new WeakMap,Oo=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Cl)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.i,e=this.t;if(El&&t===void 0){let i=e!==void 0&&e.length===1;i&&(t=Wh.get(e)),t===void 0&&((this.i=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Wh.set(e,t))}return t}toString(){return this.cssText}},fp=s=>new Oo(typeof s=="string"?s:s+"",void 0,Cl),Hi=(s,...t)=>{let e=s.length===1?s[0]:t.reduce(((i,n,o)=>i+(c=>{if(c._$cssResult$===!0)return c.cssText;if(typeof c=="number")return c;throw Error("Value passed to 'css' function must be a 'css' function result: "+c+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+s[o+1]),s[0]);return new Oo(e,s,Cl)},gp=(s,t)=>{if(El)s.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let i=document.createElement("style"),n=Fo.litNonce;n!==void 0&&i.setAttribute("nonce",n),i.textContent=e.cssText,s.appendChild(i)}},Gh=El?s=>s:s=>s instanceof CSSStyleSheet?(t=>{let e="";for(let i of t.cssRules)e+=i.cssText;return fp(e)})(s):s,{is:mp,defineProperty:bp,getOwnPropertyDescriptor:yp,getOwnPropertyNames:vp,getOwnPropertySymbols:wp,getPrototypeOf:xp}=Object,Bo=globalThis,qh=Bo.trustedTypes,Ap=qh?qh.emptyScript:"",Sp=Bo.reactiveElementPolyfillSupport,Xn=(s,t)=>s,yl={toAttribute(s,t){switch(t){case Boolean:s=s?Ap:null;break;case Object:case Array:s=s==null?s:JSON.stringify(s)}return s},fromAttribute(s,t){let e=s;switch(t){case Boolean:e=s!==null;break;case Number:e=s===null?null:Number(s);break;case Object:case Array:try{e=JSON.parse(s)}catch{e=null}}return e}},ed=(s,t)=>!mp(s,t),Xh={attribute:!0,type:String,converter:yl,reflect:!1,useDefault:!1,hasChanged:ed};Symbol.metadata??=Symbol("metadata"),Bo.litPropertyMetadata??=new WeakMap;var $i=class extends HTMLElement{static addInitializer(t){this.o(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this.u&&[...this.u.keys()]}static createProperty(t,e=Xh){if(e.state&&(e.attribute=!1),this.o(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let i=Symbol(),n=this.getPropertyDescriptor(t,i,e);n!==void 0&&bp(this.prototype,t,n)}}static getPropertyDescriptor(t,e,i){let{get:n,set:o}=yp(this.prototype,t)??{get(){return this[e]},set(c){this[e]=c}};return{get:n,set(c){let l=n?.call(this);o?.call(this,c),this.requestUpdate(t,l,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Xh}static o(){if(this.hasOwnProperty(Xn("elementProperties")))return;let t=xp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Xn("finalized")))return;if(this.finalized=!0,this.o(),this.hasOwnProperty(Xn("properties"))){let e=this.properties,i=[...vp(e),...wp(e)];for(let n of i)this.createProperty(n,e[n])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[i,n]of e)this.elementProperties.set(i,n)}this.u=new Map;for(let[e,i]of this.elementProperties){let n=this.p(e,i);n!==void 0&&this.u.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let n of i)e.unshift(Gh(n))}else t!==void 0&&e.push(Gh(t));return e}static p(t,e){let i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this.v=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this.m=null,this._()}_(){this.S=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this.$(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this.P??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this.P?.delete(t)}$(){let t=new Map,e=this.constructor.elementProperties;for(let i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this.v=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return gp(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this.P?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this.P?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,i){this._$AK(t,i)}C(t,e){let i=this.constructor.elementProperties.get(t),n=this.constructor.p(t,i);if(n!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:yl).toAttribute(e,i.type);this.m=t,o==null?this.removeAttribute(n):this.setAttribute(n,o),this.m=null}}_$AK(t,e){let i=this.constructor,n=i.u.get(t);if(n!==void 0&&this.m!==n){let o=i.getPropertyOptions(n),c=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:yl;this.m=n;let l=c.fromAttribute(e,o.type);this[n]=l??this.T?.get(n)??l,this.m=null}}requestUpdate(t,e,i){if(t!==void 0){let n=this.constructor,o=this[t];if(i??=n.getPropertyOptions(t),!((i.hasChanged??ed)(o,e)||i.useDefault&&i.reflect&&o===this.T?.get(t)&&!this.hasAttribute(n.p(t,i))))return;this.M(t,e,i)}this.isUpdatePending===!1&&(this.S=this.k())}M(t,e,{useDefault:i,reflect:n,wrapped:o},c){i&&!(this.T??=new Map).has(t)&&(this.T.set(t,c??e??this[t]),o!==!0||c!==void 0)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),n===!0&&this.m!==t&&(this.A??=new Set).add(t))}async k(){this.isUpdatePending=!0;try{await this.S}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this.v){for(let[n,o]of this.v)this[n]=o;this.v=void 0}let i=this.constructor.elementProperties;if(i.size>0)for(let[n,o]of i){let{wrapped:c}=o,l=this[n];c!==!0||this._$AL.has(n)||l===void 0||this.M(n,void 0,o,l)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this.P?.forEach((i=>i.hostUpdate?.())),this.update(e)):this.U()}catch(i){throw t=!1,this.U(),i}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this.P?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}U(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this.S}shouldUpdate(t){return!0}update(t){this.A&&=this.A.forEach((e=>this.C(e,this[e]))),this.U()}updated(t){}firstUpdated(t){}};$i.elementStyles=[],$i.shadowRootOptions={mode:"open"},$i[Xn("elementProperties")]=new Map,$i[Xn("finalized")]=new Map,Sp?.({ReactiveElement:$i}),(Bo.reactiveElementVersions??=[]).push("2.1.1");var _l=globalThis,No=_l.trustedTypes,Kh=No?No.createPolicy("lit-html",{createHTML:s=>s}):void 0,id="$lit$",Ui=`lit$${Math.random().toFixed(9).slice(2)}$`,sd="?"+Ui,Ep=`<${sd}>`,As=document,Kn=()=>As.createComment(""),Yn=s=>s===null||typeof s!="object"&&typeof s!="function",Tl=Array.isArray,Cp=s=>Tl(s)||typeof s?.[Symbol.iterator]=="function",bl=`[
|
|
539
|
-
\f\r]`,qn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Yh=/-->/g,Jh=/>/g,ws=RegExp(`>|${bl}(?:([^\\s"'>=/]+)(${bl}*=${bl}*(?:[^
|
|
540
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),Qh=/'/g,Zh=/"/g,nd=/^(?:script|style|textarea|title)$/i,Pl=s=>(t,...e)=>({_$litType$:s,strings:t,values:e}),Rt=Pl(1),pm=Pl(2),fm=Pl(3),an=Symbol.for("lit-noChange"),ae=Symbol.for("lit-nothing"),td=new WeakMap,xs=As.createTreeWalker(As,129);function rd(s,t){if(!Tl(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return Kh!==void 0?Kh.createHTML(t):t}var _p=(s,t)=>{let e=s.length-1,i=[],n,o=t===2?"<svg>":t===3?"<math>":"",c=qn;for(let l=0;l<e;l++){let h=s[l],m,u,a=-1,f=0;for(;f<h.length&&(c.lastIndex=f,u=c.exec(h),u!==null);)f=c.lastIndex,c===qn?u[1]==="!--"?c=Yh:u[1]!==void 0?c=Jh:u[2]!==void 0?(nd.test(u[2])&&(n=RegExp("</"+u[2],"g")),c=ws):u[3]!==void 0&&(c=ws):c===ws?u[0]===">"?(c=n??qn,a=-1):u[1]===void 0?a=-2:(a=c.lastIndex-u[2].length,m=u[1],c=u[3]===void 0?ws:u[3]==='"'?Zh:Qh):c===Zh||c===Qh?c=ws:c===Yh||c===Jh?c=qn:(c=ws,n=void 0);let w=c===ws&&s[l+1].startsWith("/>")?" ":"";o+=c===qn?h+Ep:a>=0?(i.push(m),h.slice(0,a)+id+h.slice(a)+Ui+w):h+Ui+(a===-2?l:w)}return[rd(s,o+(s[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},Jn=class s{constructor({strings:t,_$litType$:e},i){let n;this.parts=[];let o=0,c=0,l=t.length-1,h=this.parts,[m,u]=_p(t,e);if(this.el=s.createElement(m,i),xs.currentNode=this.el.content,e===2||e===3){let a=this.el.content.firstChild;a.replaceWith(...a.childNodes)}for(;(n=xs.nextNode())!==null&&h.length<l;){if(n.nodeType===1){if(n.hasAttributes())for(let a of n.getAttributeNames())if(a.endsWith(id)){let f=u[c++],w=n.getAttribute(a).split(Ui),E=/([.?@])?(.*)/.exec(f);h.push({type:1,index:o,name:E[2],strings:w,ctor:E[1]==="."?wl:E[1]==="?"?xl:E[1]==="@"?Al:cn}),n.removeAttribute(a)}else a.startsWith(Ui)&&(h.push({type:6,index:o}),n.removeAttribute(a));if(nd.test(n.tagName)){let a=n.textContent.split(Ui),f=a.length-1;if(f>0){n.textContent=No?No.emptyScript:"";for(let w=0;w<f;w++)n.append(a[w],Kn()),xs.nextNode(),h.push({type:2,index:++o});n.append(a[f],Kn())}}}else if(n.nodeType===8)if(n.data===sd)h.push({type:2,index:o});else{let a=-1;for(;(a=n.data.indexOf(Ui,a+1))!==-1;)h.push({type:7,index:o}),a+=Ui.length-1}o++}}static createElement(t,e){let i=As.createElement("template");return i.innerHTML=t,i}};function ln(s,t,e=s,i){if(t===an)return t;let n=i!==void 0?e.N?.[i]:e.O,o=Yn(t)?void 0:t._$litDirective$;return n?.constructor!==o&&(n?._$AO?.(!1),o===void 0?n=void 0:(n=new o(s),n._$AT(s,e,i)),i!==void 0?(e.N??=[])[i]=n:e.O=n),n!==void 0&&(t=ln(s,n._$AS(s,t.values),n,i)),t}var vl=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}R(t){let{el:{content:e},parts:i}=this._$AD,n=(t?.creationScope??As).importNode(e,!0);xs.currentNode=n;let o=xs.nextNode(),c=0,l=0,h=i[0];for(;h!==void 0;){if(c===h.index){let m;h.type===2?m=new Qn(o,o.nextSibling,this,t):h.type===1?m=new h.ctor(o,h.name,h.strings,this,t):h.type===6&&(m=new Sl(o,this,t)),this._$AV.push(m),h=i[++l]}c!==h?.index&&(o=xs.nextNode(),c++)}return xs.currentNode=As,n}V(t){let e=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}},Qn=class s{get _$AU(){return this._$AM?._$AU??this.D}constructor(t,e,i,n){this.type=2,this._$AH=ae,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=n,this.D=n?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=ln(this,t,e),Yn(t)?t===ae||t==null||t===""?(this._$AH!==ae&&this._$AR(),this._$AH=ae):t!==this._$AH&&t!==an&&this.L(t):t._$litType$!==void 0?this.j(t):t.nodeType!==void 0?this.I(t):Cp(t)?this.H(t):this.L(t)}B(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}I(t){this._$AH!==t&&(this._$AR(),this._$AH=this.B(t))}L(t){this._$AH!==ae&&Yn(this._$AH)?this._$AA.nextSibling.data=t:this.I(As.createTextNode(t)),this._$AH=t}j(t){let{values:e,_$litType$:i}=t,n=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=Jn.createElement(rd(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.V(e);else{let o=new vl(n,this),c=o.R(this.options);o.V(e),this.I(c),this._$AH=o}}_$AC(t){let e=td.get(t.strings);return e===void 0&&td.set(t.strings,e=new Jn(t)),e}H(t){Tl(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,i,n=0;for(let o of t)n===e.length?e.push(i=new s(this.B(Kn()),this.B(Kn()),this,this.options)):i=e[n],i._$AI(o),n++;n<e.length&&(this._$AR(i&&i._$AB.nextSibling,n),e.length=n)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t!==this._$AB;){let i=t.nextSibling;t.remove(),t=i}}setConnected(t){this._$AM===void 0&&(this.D=t,this._$AP?.(t))}},cn=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,i,n,o){this.type=1,this._$AH=ae,this._$AN=void 0,this.element=t,this.name=e,this._$AM=n,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=ae}_$AI(t,e=this,i,n){let o=this.strings,c=!1;if(o===void 0)t=ln(this,t,e,0),c=!Yn(t)||t!==this._$AH&&t!==an,c&&(this._$AH=t);else{let l=t,h,m;for(t=o[0],h=0;h<o.length-1;h++)m=ln(this,l[i+h],e,h),m===an&&(m=this._$AH[h]),c||=!Yn(m)||m!==this._$AH[h],m===ae?t=ae:t!==ae&&(t+=(m??"")+o[h+1]),this._$AH[h]=m}c&&!n&&this.W(t)}W(t){t===ae?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},wl=class extends cn{constructor(){super(...arguments),this.type=3}W(t){this.element[this.name]=t===ae?void 0:t}},xl=class extends cn{constructor(){super(...arguments),this.type=4}W(t){this.element.toggleAttribute(this.name,!!t&&t!==ae)}},Al=class extends cn{constructor(t,e,i,n,o){super(t,e,i,n,o),this.type=5}_$AI(t,e=this){if((t=ln(this,t,e,0)??ae)===an)return;let i=this._$AH,n=t===ae&&i!==ae||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==ae&&(i===ae||n);n&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Sl=class{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){ln(this,t)}};var Tp=_l.litHtmlPolyfillSupport;Tp?.(Jn,Qn),(_l.litHtmlVersions??=[]).push("3.3.1");var Pp=(s,t,e)=>{let i=e?.renderBefore??t,n=i._$litPart$;if(n===void 0){let o=e?.renderBefore??null;i._$litPart$=n=new Qn(t.insertBefore(Kn(),o),o,void 0,e??{})}return n._$AI(s),n},kl=globalThis;var se=class extends $i{constructor(){super(...arguments),this.renderOptions={host:this},this.rt=void 0}createRenderRoot(){let t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this.rt=Pp(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this.rt?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this.rt?.setConnected(!1)}render(){return an}};se._$litElement$=!0,se.finalized=!0,kl.litElementHydrateSupport?.({LitElement:se});var kp=kl.litElementPolyfillSupport;kp?.({LitElement:se});(kl.litElementVersions??=[]).push("4.2.1");var Zn=class extends se{disconnectedCallback(){super.disconnectedCallback(),this.activeSlideIndex=0}static properties={docId:{type:String},docName:{type:String},images:{type:Array},activeSlideIndex:{type:Number,state:!0},ocr:{type:Boolean},pdf:{type:Boolean}};get visibleImages(){return this.images||[]}get hasImages(){return(this.images||[]).some(t=>!!t.src)}get pageCount(){return this.visibleImages.length}static styles=Hi`
|
|
541
|
-
:host {
|
|
542
|
-
display: block;
|
|
543
|
-
position: absolute;
|
|
544
|
-
top: 0;
|
|
545
|
-
left: 0;
|
|
546
|
-
right: 0;
|
|
547
|
-
bottom: 0;
|
|
548
|
-
width: 100%;
|
|
549
|
-
height: 100%;
|
|
550
|
-
z-index: 10;
|
|
551
|
-
overflow: hidden;
|
|
552
|
-
background: #000;
|
|
553
|
-
box-sizing: border-box;
|
|
554
|
-
}
|
|
555
|
-
sl-carousel {
|
|
556
|
-
position: absolute;
|
|
557
|
-
top: 0;
|
|
558
|
-
padding-top: 16px;
|
|
559
|
-
background: white;
|
|
560
|
-
z-index: 4;
|
|
561
|
-
height: 100%;
|
|
562
|
-
width: 100%;
|
|
563
|
-
}
|
|
564
|
-
sl-carousel-item {
|
|
565
|
-
height: 100%;
|
|
566
|
-
}
|
|
567
|
-
.item {
|
|
568
|
-
width: 100%;
|
|
569
|
-
height: 100%;
|
|
570
|
-
background-repeat: no-repeat;
|
|
571
|
-
background-size: contain;
|
|
572
|
-
background-position: center;
|
|
573
|
-
}
|
|
574
|
-
.top-bar {
|
|
575
|
-
position: absolute;
|
|
576
|
-
top: 0;
|
|
577
|
-
left: 0;
|
|
578
|
-
right: 0;
|
|
579
|
-
height: 56px;
|
|
580
|
-
z-index: 10;
|
|
581
|
-
display: flex;
|
|
582
|
-
align-items: center;
|
|
583
|
-
justify-content: space-between;
|
|
584
|
-
padding: 0 16px;
|
|
585
|
-
background: linear-gradient(to bottom, rgba(15, 23, 42, 0.85) 0%, rgba(15, 23, 42, 0.3) 80%, transparent 100%);
|
|
586
|
-
pointer-events: none;
|
|
587
|
-
box-sizing: border-box;
|
|
588
|
-
}
|
|
589
|
-
.top-bar > * {
|
|
590
|
-
pointer-events: auto;
|
|
591
|
-
}
|
|
592
|
-
.top-bar-left {
|
|
593
|
-
display: flex;
|
|
594
|
-
align-items: center;
|
|
595
|
-
gap: 10px;
|
|
596
|
-
min-width: 0;
|
|
597
|
-
}
|
|
598
|
-
.top-bar-right {
|
|
599
|
-
display: flex;
|
|
600
|
-
align-items: center;
|
|
601
|
-
gap: 8px;
|
|
602
|
-
}
|
|
603
|
-
.back {
|
|
604
|
-
font-size: 26px;
|
|
605
|
-
cursor: pointer;
|
|
606
|
-
appearance: none;
|
|
607
|
-
background: rgba(15, 23, 42, 0.6);
|
|
608
|
-
border: 1px solid rgba(255, 255, 255, 0.2);
|
|
609
|
-
border-radius: 8px;
|
|
610
|
-
color: white;
|
|
611
|
-
width: 36px;
|
|
612
|
-
height: 36px;
|
|
613
|
-
display: flex;
|
|
614
|
-
align-items: center;
|
|
615
|
-
justify-content: center;
|
|
616
|
-
transition: background 0.15s;
|
|
617
|
-
}
|
|
618
|
-
.back:hover {
|
|
619
|
-
background: rgba(15, 23, 42, 0.9);
|
|
620
|
-
}
|
|
621
|
-
.doc-heading {
|
|
622
|
-
color: #f8fafc;
|
|
623
|
-
font-size: 1.05rem;
|
|
624
|
-
font-weight: 600;
|
|
625
|
-
white-space: nowrap;
|
|
626
|
-
overflow: hidden;
|
|
627
|
-
text-overflow: ellipsis;
|
|
628
|
-
max-width: 240px;
|
|
629
|
-
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
|
|
630
|
-
}
|
|
631
|
-
.ocr-btn, .export-btn {
|
|
632
|
-
background: rgba(15, 23, 42, 0.75);
|
|
633
|
-
backdrop-filter: blur(8px);
|
|
634
|
-
color: white;
|
|
635
|
-
border: 1px solid rgba(255, 255, 255, 0.2);
|
|
636
|
-
border-radius: 8px;
|
|
637
|
-
padding: 6px 12px;
|
|
638
|
-
height: 36px;
|
|
639
|
-
font-size: 13px;
|
|
640
|
-
display: flex;
|
|
641
|
-
align-items: center;
|
|
642
|
-
gap: 6px;
|
|
643
|
-
cursor: pointer;
|
|
644
|
-
transition: background 0.15s, border-color 0.15s;
|
|
645
|
-
box-sizing: border-box;
|
|
646
|
-
}
|
|
647
|
-
.ocr-btn:hover, .export-btn:hover {
|
|
648
|
-
background: rgba(15, 23, 42, 0.95);
|
|
649
|
-
border-color: rgba(255, 255, 255, 0.4);
|
|
650
|
-
}
|
|
651
|
-
`;constructor(){super(),this.docId="",this.docName="",this.images=[],this.activeSlideIndex=0,this.ocr=!0,this.pdf=!0}handleBackClick(){this.dispatchEvent(new CustomEvent("dialog:close",{bubbles:!0,composed:!1}))}handleOcrClick(){let t=this.images[this.activeSlideIndex];!t||!t.src||this.dispatchEvent(new CustomEvent("copio:ocr-page",{bubbles:!0,composed:!0,detail:{page:t,pageIndex:this.activeSlideIndex}}))}handleExportSelect(t){if(t.detail?.item?.disabled)return;let e=t.detail?.item?.value,i={docId:this.docId,docName:this.docName,pages:this.images};e==="pdf"?this.dispatchEvent(new CustomEvent("doc:download-pdf",{bubbles:!0,composed:!1,detail:{...i,searchable:!1}})):e==="searchable-pdf"?this.dispatchEvent(new CustomEvent("doc:download-pdf",{bubbles:!0,composed:!1,detail:{...i,searchable:!0}})):e==="images"&&this.dispatchEvent(new CustomEvent("doc:download-images",{bubbles:!0,composed:!1,detail:i}))}handleSlideChange(t){this.activeSlideIndex=t.detail?.index||0}renderItem(t){return Rt`
|
|
652
|
-
<sl-carousel-item data-id="${t.id}">
|
|
653
|
-
<div class="item" style="background-image: url('${t.src}')"></div>
|
|
654
|
-
</sl-carousel-item>
|
|
655
|
-
`}render(){let t=this.visibleImages[this.activeSlideIndex],e=this.ocr!==!1&&t&&!!t.src;return Rt`
|
|
656
|
-
<div class="top-bar">
|
|
657
|
-
<div class="top-bar-left">
|
|
658
|
-
<button class="back" @click=${this.handleBackClick} aria-label="Back">←</button>
|
|
659
|
-
<span class="doc-heading">${this.docName||"Document"}</span>
|
|
660
|
-
</div>
|
|
661
|
-
|
|
662
|
-
<div class="top-bar-right">
|
|
663
|
-
${e?Rt`
|
|
664
|
-
<button class="ocr-btn" @click=${this.handleOcrClick} aria-label="Extract text">
|
|
665
|
-
<sl-icon name="card-text"></sl-icon>
|
|
666
|
-
<span>Extract Text</span>
|
|
667
|
-
</button>
|
|
668
|
-
`:""}
|
|
669
|
-
|
|
670
|
-
<sl-dropdown>
|
|
671
|
-
<button slot="trigger" class="export-btn" aria-label="Export document">
|
|
672
|
-
<sl-icon name="box-arrow-up"></sl-icon>
|
|
673
|
-
<span>Export</span>
|
|
674
|
-
<sl-icon name="chevron-down" style="font-size: 0.75rem;"></sl-icon>
|
|
675
|
-
</button>
|
|
676
|
-
<sl-menu @sl-select=${this.handleExportSelect}>
|
|
677
|
-
${this.pdf!==!1?Rt`
|
|
678
|
-
<sl-menu-item value="pdf" ?disabled=${this.pageCount===0}>
|
|
679
|
-
<sl-icon slot="prefix" name="file-earmark-pdf"></sl-icon>
|
|
680
|
-
Download as PDF
|
|
681
|
-
</sl-menu-item>
|
|
682
|
-
${this.ocr!==!1?Rt`
|
|
683
|
-
<sl-menu-item value="searchable-pdf" ?disabled=${this.pageCount===0}>
|
|
684
|
-
<sl-icon slot="prefix" name="file-earmark-text"></sl-icon>
|
|
685
|
-
Download Searchable PDF
|
|
686
|
-
</sl-menu-item>
|
|
687
|
-
`:""}
|
|
688
|
-
`:""}
|
|
689
|
-
<sl-menu-item value="images" ?disabled=${this.pageCount===0}>
|
|
690
|
-
<sl-icon slot="prefix" name="images"></sl-icon>
|
|
691
|
-
Download as Images (ZIP)
|
|
692
|
-
</sl-menu-item>
|
|
693
|
-
</sl-menu>
|
|
694
|
-
</sl-dropdown>
|
|
695
|
-
</div>
|
|
696
|
-
</div>
|
|
697
|
-
|
|
698
|
-
<sl-carousel
|
|
699
|
-
class="sl-carousel"
|
|
700
|
-
orientation="vertical"
|
|
701
|
-
@sl-slide-change=${this.handleSlideChange}
|
|
702
|
-
>
|
|
703
|
-
${this.visibleImages.map(i=>this.renderItem(i))}
|
|
704
|
-
</sl-carousel>
|
|
705
|
-
`}};customElements.define("copio-carousel",Zn);var tr=class extends se{createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.#t()}#t=()=>{let t=this.querySelector(".dialog-add-edit-input-name"),e=this.querySelector(".dialog-name-error");if(e&&(e.style.display="none"),t&&(t.classList.remove("input-invalid"),t.style.removeProperty("--sl-input-border-color"),t.style.removeProperty("--sl-input-border-color-focus"),typeof t.setCustomValidity=="function"))try{t.setCustomValidity("")}catch{}};#e=t=>{t.target?.value?.trim()&&this.#t()};#i=t=>{if(t.target!==t.currentTarget)return;this.#t();let e=this.querySelector(".dialog-add-edit-input-id"),i=this.querySelector(".dialog-add-edit-input-name"),n=this.querySelector("copio-images");e&&(e.value=""),i&&(i.value=""),n&&(n.images=[]),this.dispatchEvent(new CustomEvent("dialog:close",{bubbles:!0,composed:!1}))};#n=t=>{if(t.key!=="Enter"||this.querySelector("sl-dialog[open]"))return;if(t.target?.classList?.contains("dialog-add-edit-input-name")){t.preventDefault(),this.#r();return}let e=t.target?.tagName;e==="TEXTAREA"||e==="SL-TEXTAREA"||e==="INPUT"||e==="SL-INPUT"||t.target?.tagName==="SL-BUTTON"||t.target?.tagName==="BUTTON"||(t.preventDefault(),this.#r())};async open(){await this.updateComplete,this.#t();let t=this.querySelector(".dialog-add-edit");t&&(await t.show(),this.querySelector(".dialog-add-edit-input-name")?.focus())}async openEdit(t,e,i){await this.updateComplete,this.#t();let n=this.querySelector(".dialog-add-edit");if(!n)return;let o=this.querySelector(".dialog-add-edit-input-id"),c=this.querySelector(".dialog-add-edit-input-name"),l=this.querySelector("copio-images");o.value=t,c.value=e,await customElements.whenDefined("copio-images"),l.images=i.map(({id:h,src:m,originalSrc:u,edits:a,exif:f})=>({id:h,src:m,originalSrc:u||m,edits:a||{crop:null,rotation:0,filter:"none"},exif:f})),n.open||(await n.show(),c.focus())}#r=()=>{let t=this.querySelector(".dialog-add-edit-input-id"),e=this.querySelector(".dialog-add-edit-input-name"),i=this.querySelector(".dialog-name-error"),n=this.querySelector("copio-images"),o=e?.value?.trim();if(!o){i&&(i.style.display="block"),e&&(e.classList.add("input-invalid"),e.style.setProperty("--sl-input-border-color","#ef4444"),e.style.setProperty("--sl-input-border-color-focus","#ef4444"),typeof e.setCustomValidity=="function"&&(e.setCustomValidity("Please enter a document name"),e.reportValidity?.()),e.focus());return}let c=(n?.images||[]).map(({id:h,src:m,originalSrc:u,edits:a,exif:f,type:w,name:E,content:p})=>({id:h,src:m,originalSrc:u||m,edits:a||{crop:null,rotation:0,filter:"none"},exif:f,type:w,name:E,content:p})),l=t?.value||De();this.dispatchEvent(new CustomEvent("dialog:save",{bubbles:!0,composed:!1,detail:{id:l,name:o,pages:c}})),this.querySelector(".dialog-add-edit")?.hide()};render(){return Rt`
|
|
706
|
-
<sl-dialog
|
|
707
|
-
label="Add / Edit"
|
|
708
|
-
class="dialog-add-edit"
|
|
709
|
-
style="--width: min(94%, 640px)"
|
|
710
|
-
@sl-after-hide=${this.#i}
|
|
711
|
-
@keydown=${this.#n}
|
|
712
|
-
>
|
|
713
|
-
<div style="min-height: min(65cqh, 420px); min-height: 350px;">
|
|
714
|
-
<sl-input
|
|
715
|
-
disabled
|
|
716
|
-
class="dialog-add-edit-input-id"
|
|
717
|
-
placeholder="id"
|
|
718
|
-
style="display: none"
|
|
719
|
-
></sl-input>
|
|
720
|
-
<div class="dialog-name-field" style="max-width: 300px">
|
|
721
|
-
<sl-input
|
|
722
|
-
class="dialog-add-edit-input-name"
|
|
723
|
-
placeholder="Enter name of document or image"
|
|
724
|
-
@sl-input=${this.#e}
|
|
725
|
-
></sl-input>
|
|
726
|
-
<div
|
|
727
|
-
class="dialog-name-error"
|
|
728
|
-
style="color: #ef4444; font-size: 0.8rem; margin-top: 4px; display: none;"
|
|
729
|
-
>
|
|
730
|
-
Please enter a document name
|
|
731
|
-
</div>
|
|
732
|
-
</div>
|
|
733
|
-
|
|
734
|
-
<copio-images
|
|
735
|
-
style="display: block; margin-top: 1.5rem"
|
|
736
|
-
></copio-images>
|
|
737
|
-
|
|
738
|
-
<br />
|
|
739
|
-
|
|
740
|
-
<sl-button
|
|
741
|
-
class="dialog-add-edit-savebtn"
|
|
742
|
-
style="width: 100%; margin-top: auto;"
|
|
743
|
-
slot="footer"
|
|
744
|
-
variant="primary"
|
|
745
|
-
@click=${this.#r}
|
|
746
|
-
>Save</sl-button
|
|
747
|
-
>
|
|
748
|
-
</div>
|
|
749
|
-
</sl-dialog>
|
|
750
|
-
`}};customElements.define("copio-add-edit-dialog",tr);var er=class extends se{static properties={name:{type:String},pages:{type:Array},isRenaming:{type:Boolean,state:!0},renameValue:{type:String,state:!0},ocr:{type:Boolean},pdf:{type:Boolean}};constructor(){super(),this.name="",this.pages=[],this.isRenaming=!1,this.renameValue="",this.ocr=!0,this.pdf=!0}get hasImages(){return(this.pages||[]).some(t=>!!t.src)}get visiblePages(){return this.pages||[]}get pageCount(){return this.visiblePages.length}static styles=Hi`
|
|
751
|
-
.wrapper {
|
|
752
|
-
margin-left: auto;
|
|
753
|
-
margin-right: auto;
|
|
754
|
-
display: flex;
|
|
755
|
-
justify-content: space-between;
|
|
756
|
-
align-items: center;
|
|
757
|
-
max-width: 768px;
|
|
758
|
-
padding: 10px 12px;
|
|
759
|
-
border-bottom: 1px solid #e2e8f0;
|
|
760
|
-
cursor: pointer;
|
|
761
|
-
user-select: none;
|
|
762
|
-
}
|
|
763
|
-
.inner {
|
|
764
|
-
display: flex;
|
|
765
|
-
align-items: center;
|
|
766
|
-
flex: 1;
|
|
767
|
-
min-width: 0;
|
|
768
|
-
}
|
|
769
|
-
.titles {
|
|
770
|
-
display: flex;
|
|
771
|
-
flex-direction: column;
|
|
772
|
-
margin-left: 12px;
|
|
773
|
-
padding: 2px 0;
|
|
774
|
-
flex: 1;
|
|
775
|
-
min-width: 0;
|
|
776
|
-
}
|
|
777
|
-
.doc-title {
|
|
778
|
-
font-weight: 600;
|
|
779
|
-
font-size: 0.95rem;
|
|
780
|
-
color: #151f2a;
|
|
781
|
-
white-space: nowrap;
|
|
782
|
-
overflow: hidden;
|
|
783
|
-
text-overflow: ellipsis;
|
|
784
|
-
line-height: 1.3;
|
|
785
|
-
}
|
|
786
|
-
.doc-page-count {
|
|
787
|
-
font-size: 0.8rem;
|
|
788
|
-
color: #64748b;
|
|
789
|
-
margin-top: 2px;
|
|
790
|
-
}
|
|
791
|
-
.rename-container {
|
|
792
|
-
display: flex;
|
|
793
|
-
align-items: center;
|
|
794
|
-
gap: 6px;
|
|
795
|
-
width: 100%;
|
|
796
|
-
max-width: 320px;
|
|
797
|
-
}
|
|
798
|
-
.rename-container sl-input {
|
|
799
|
-
flex: 1;
|
|
800
|
-
}
|
|
801
|
-
button {
|
|
802
|
-
appearance: none;
|
|
803
|
-
border: none;
|
|
804
|
-
color: black;
|
|
805
|
-
padding: 3px 4px 3px 7px;
|
|
806
|
-
background: white;
|
|
807
|
-
cursor: pointer;
|
|
808
|
-
}
|
|
809
|
-
`;#t(t){this.isRenaming||t.target.closest("sl-dropdown")||t.target.closest(".rename-container")||this.handleView()}#e(t){if(t.detail?.item?.disabled)return;let e=t.detail?.item?.value;e==="delete"&&this.handleDelete(),e==="rename"&&this.startRename(),e==="edit"&&this.handleEdit(),e==="extract-ocr"&&this.handleExtractOcr(),e==="download"&&this.handleDownload(),e==="download-searchable-pdf"&&this.handleDownloadSearchablePdf(),e==="download-images"&&this.handleDownloadImages()}startRename(t){t&&(t.preventDefault(),t.stopPropagation()),this.renameValue=this.name||"",this.isRenaming=!0,this.updateComplete.then(()=>{let e=this.shadowRoot.querySelector(".rename-input");e&&(e.focus(),typeof e.select=="function"&&e.select())})}cancelRename(t){t&&(t.preventDefault(),t.stopPropagation()),this.isRenaming=!1,this.renameValue=this.name||""}commitRename(t){t&&(t.preventDefault(),t.stopPropagation());let e=(this.renameValue||"").trim();if(!e){this.cancelRename();return}if(e!==this.name){let i={id:this.getAttribute("id"),name:e};this.dispatchEvent(new CustomEvent("doc:rename",{bubbles:!0,composed:!1,detail:i})),this.name=e}this.isRenaming=!1}handleRenameKeyDown(t){t.key==="Enter"?(t.preventDefault(),this.commitRename()):t.key==="Escape"&&(t.preventDefault(),this.cancelRename())}handleExtractOcr(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:extract-ocr",{bubbles:!0,composed:!1,detail:t}))}handleView(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:view",{bubbles:!0,composed:!1,detail:t}))}handleDelete(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:delete",{bubbles:!0,composed:!1,detail:t}))}handleEdit(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:edit",{bubbles:!0,composed:!1,detail:t}))}handleDownload(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:download",{bubbles:!0,composed:!1,detail:t}))}handleDownloadSearchablePdf(){let t={id:this.getAttribute("id"),searchable:!0};this.dispatchEvent(new CustomEvent("doc:download",{bubbles:!0,composed:!1,detail:t}))}handleDownloadImages(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:download-images",{bubbles:!0,composed:!1,detail:t}))}render(){return Rt`
|
|
810
|
-
<div class="wrapper" @click=${this.#t}>
|
|
811
|
-
<div class="inner">
|
|
812
|
-
<sl-avatar label="Document icon">
|
|
813
|
-
<sl-icon slot="icon" name="file-earmark-text"></sl-icon>
|
|
814
|
-
</sl-avatar>
|
|
815
|
-
|
|
816
|
-
<div class="titles">
|
|
817
|
-
${this.isRenaming?Rt`
|
|
818
|
-
<div class="rename-container" @click=${t=>t.stopPropagation()}>
|
|
819
|
-
<sl-input
|
|
820
|
-
class="rename-input"
|
|
821
|
-
size="small"
|
|
822
|
-
.value=${this.renameValue}
|
|
823
|
-
@sl-input=${t=>this.renameValue=t.target.value}
|
|
824
|
-
@keydown=${this.handleRenameKeyDown}
|
|
825
|
-
></sl-input>
|
|
826
|
-
<sl-icon-button
|
|
827
|
-
name="check-lg"
|
|
828
|
-
label="Save rename"
|
|
829
|
-
@click=${this.commitRename}
|
|
830
|
-
></sl-icon-button>
|
|
831
|
-
<sl-icon-button
|
|
832
|
-
name="x-lg"
|
|
833
|
-
label="Cancel rename"
|
|
834
|
-
@click=${this.cancelRename}
|
|
835
|
-
></sl-icon-button>
|
|
836
|
-
</div>
|
|
837
|
-
`:Rt`
|
|
838
|
-
<div class="doc-title">${this.name||"Untitled Document"}</div>
|
|
839
|
-
<div class="doc-page-count">
|
|
840
|
-
${this.pageCount} ${this.pageCount===1?"page":"pages"}
|
|
841
|
-
</div>
|
|
842
|
-
`}
|
|
843
|
-
</div>
|
|
844
|
-
</div>
|
|
845
|
-
|
|
846
|
-
<sl-dropdown>
|
|
847
|
-
<sl-button slot="trigger" variant="default" size="small" circle>
|
|
848
|
-
<sl-icon name="three-dots-vertical"></sl-icon>
|
|
849
|
-
</sl-button>
|
|
850
|
-
<sl-menu @sl-select=${this.#e}>
|
|
851
|
-
<sl-menu-item value="edit">
|
|
852
|
-
<sl-icon slot="prefix" name="sliders"></sl-icon>
|
|
853
|
-
Edit
|
|
854
|
-
</sl-menu-item>
|
|
855
|
-
<sl-menu-item value="rename">
|
|
856
|
-
<sl-icon slot="prefix" name="pencil"></sl-icon>
|
|
857
|
-
Rename
|
|
858
|
-
</sl-menu-item>
|
|
859
|
-
${this.ocr!==!1?Rt`
|
|
860
|
-
<sl-menu-item
|
|
861
|
-
value="extract-ocr"
|
|
862
|
-
?disabled=${!this.hasImages}
|
|
863
|
-
title=${this.hasImages?"Extract text with OCR":"No image pages in document"}
|
|
864
|
-
>
|
|
865
|
-
<sl-icon slot="prefix" name="card-text"></sl-icon>
|
|
866
|
-
Extract All Text (OCR)
|
|
867
|
-
</sl-menu-item>
|
|
868
|
-
`:""}
|
|
869
|
-
<sl-divider></sl-divider>
|
|
870
|
-
${this.pdf!==!1?Rt`
|
|
871
|
-
<sl-menu-item
|
|
872
|
-
value="download"
|
|
873
|
-
?disabled=${this.pageCount===0}
|
|
874
|
-
title=${this.pageCount===0?"Document is empty":"Download as PDF"}
|
|
875
|
-
>
|
|
876
|
-
<sl-icon slot="prefix" name="file-earmark-pdf"></sl-icon>
|
|
877
|
-
Download as PDF
|
|
878
|
-
</sl-menu-item>
|
|
879
|
-
${this.ocr!==!1?Rt`
|
|
880
|
-
<sl-menu-item
|
|
881
|
-
value="download-searchable-pdf"
|
|
882
|
-
?disabled=${this.pageCount===0||!this.hasImages}
|
|
883
|
-
title=${this.pageCount===0?"Document is empty":"Download as Searchable PDF (with OCR text layer)"}
|
|
884
|
-
>
|
|
885
|
-
<sl-icon slot="prefix" name="file-earmark-text"></sl-icon>
|
|
886
|
-
Download Searchable PDF
|
|
887
|
-
</sl-menu-item>
|
|
888
|
-
`:""}
|
|
889
|
-
`:""}
|
|
890
|
-
<sl-menu-item
|
|
891
|
-
value="download-images"
|
|
892
|
-
?disabled=${this.pageCount===0}
|
|
893
|
-
title=${this.pageCount===0?"Document is empty":"Download as Images"}
|
|
894
|
-
>
|
|
895
|
-
<sl-icon slot="prefix" name="images"></sl-icon>
|
|
896
|
-
Download as Images
|
|
897
|
-
</sl-menu-item>
|
|
898
|
-
<sl-divider></sl-divider>
|
|
899
|
-
<sl-menu-item value="delete">
|
|
900
|
-
<sl-icon slot="prefix" name="trash"></sl-icon>
|
|
901
|
-
Delete
|
|
902
|
-
</sl-menu-item>
|
|
903
|
-
</sl-menu>
|
|
904
|
-
</sl-dropdown>
|
|
905
|
-
</div>
|
|
906
|
-
`}};customElements.define("copio-row",er);var ir=class extends se{static styles=Hi`
|
|
907
|
-
header {
|
|
908
|
-
background-color: #151f2a;
|
|
909
|
-
color: white;
|
|
910
|
-
display: flex;
|
|
911
|
-
align-items: center;
|
|
912
|
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
913
|
-
padding: 8px;
|
|
914
|
-
}
|
|
915
|
-
.header-left,
|
|
916
|
-
.header-right {
|
|
917
|
-
flex: 1;
|
|
918
|
-
display: flex;
|
|
919
|
-
align-items: center;
|
|
920
|
-
}
|
|
921
|
-
.header-right {
|
|
922
|
-
justify-content: flex-end;
|
|
923
|
-
}
|
|
924
|
-
h1 {
|
|
925
|
-
font-size: 24px;
|
|
926
|
-
margin: 0;
|
|
927
|
-
}
|
|
928
|
-
sl-icon-button::part(base) {
|
|
929
|
-
min-width: 44px;
|
|
930
|
-
min-height: 44px;
|
|
931
|
-
display: inline-flex;
|
|
932
|
-
align-items: center;
|
|
933
|
-
justify-content: center;
|
|
934
|
-
}
|
|
935
|
-
`;static properties={_storageEstimate:{state:!0},_isPersisted:{state:!0},storageKind:{type:String}};constructor(){super()}async connectedCallback(){super.connectedCallback(),await this.#t()}disconnectedCallback(){super.disconnectedCallback()}async#t(){navigator.storage&&(navigator.storage.persisted&&(this._isPersisted=await navigator.storage.persisted()),navigator.storage.estimate&&(this._storageEstimate=await navigator.storage.estimate()))}_formatBytes(t){if(t==null)return"Unknown";if(t===0)return"0 B";let e=1024,i=["B","KB","MB","GB"],n=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,n)).toFixed(1))+" "+i[n]}#e(t){if(t.detail?.item?.value==="link-device"){this.dispatchEvent(new CustomEvent("header:link-device",{bubbles:!0,composed:!1}));return}if(t.detail?.item?.value==="clear-cache"){this.dispatchEvent(new CustomEvent("header:clear-cache",{bubbles:!0,composed:!1}));return}}render(){return Rt`
|
|
936
|
-
<header>
|
|
937
|
-
<div class="header-left">
|
|
938
|
-
<sl-dropdown @sl-show=${this.#t}>
|
|
939
|
-
<sl-icon-button
|
|
940
|
-
slot="trigger"
|
|
941
|
-
name="list"
|
|
942
|
-
label="Menu"
|
|
943
|
-
style="font-size: 1.5rem; color: white;"
|
|
944
|
-
></sl-icon-button>
|
|
945
|
-
<sl-menu @sl-select=${this.#e}>
|
|
946
|
-
<sl-menu-item value="link-device">Link another device</sl-menu-item>
|
|
947
|
-
<sl-menu-item value="clear-cache">Clear cache & update</sl-menu-item>
|
|
948
|
-
<sl-divider></sl-divider>
|
|
949
|
-
<sl-menu-item disabled>
|
|
950
|
-
Storage: ${this._formatBytes(this._storageEstimate?.usage)} / ${this._formatBytes(this._storageEstimate?.quota)}
|
|
951
|
-
</sl-menu-item>
|
|
952
|
-
<sl-menu-item disabled>
|
|
953
|
-
Backend: ${(this.storageKind||"opfs").toUpperCase()} (${this._isPersisted?"Persisted":"Volatile"})
|
|
954
|
-
</sl-menu-item>
|
|
955
|
-
</sl-menu>
|
|
956
|
-
</sl-dropdown>
|
|
957
|
-
</div>
|
|
958
|
-
<h1>COPIO</h1>
|
|
959
|
-
<div class="header-right"></div>
|
|
960
|
-
</header>
|
|
961
|
-
`}};customElements.define("copio-header",ir);var sr=class extends se{disconnectedCallback(){super.disconnectedCallback()}static styles=Hi`
|
|
962
|
-
.lds-roller {
|
|
963
|
-
display: inline-block;
|
|
964
|
-
position: relative;
|
|
965
|
-
width: 80px;
|
|
966
|
-
height: 80px;
|
|
967
|
-
}
|
|
968
|
-
.lds-roller div {
|
|
969
|
-
animation: lds-roller 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
|
|
970
|
-
transform-origin: 40px 40px;
|
|
971
|
-
}
|
|
972
|
-
.lds-roller div:after {
|
|
973
|
-
content: ' ';
|
|
974
|
-
display: block;
|
|
975
|
-
position: absolute;
|
|
976
|
-
width: 7px;
|
|
977
|
-
height: 7px;
|
|
978
|
-
border-radius: 50%;
|
|
979
|
-
background: #fff;
|
|
980
|
-
margin: -4px 0 0 -4px;
|
|
981
|
-
}
|
|
982
|
-
.lds-roller div:nth-child(1) {
|
|
983
|
-
animation-delay: -0.036s;
|
|
984
|
-
}
|
|
985
|
-
.lds-roller div:nth-child(1):after {
|
|
986
|
-
top: 63px;
|
|
987
|
-
left: 63px;
|
|
988
|
-
}
|
|
989
|
-
.lds-roller div:nth-child(2) {
|
|
990
|
-
animation-delay: -0.072s;
|
|
991
|
-
}
|
|
992
|
-
.lds-roller div:nth-child(2):after {
|
|
993
|
-
top: 68px;
|
|
994
|
-
left: 56px;
|
|
995
|
-
}
|
|
996
|
-
.lds-roller div:nth-child(3) {
|
|
997
|
-
animation-delay: -0.108s;
|
|
998
|
-
}
|
|
999
|
-
.lds-roller div:nth-child(3):after {
|
|
1000
|
-
top: 71px;
|
|
1001
|
-
left: 48px;
|
|
1002
|
-
}
|
|
1003
|
-
.lds-roller div:nth-child(4) {
|
|
1004
|
-
animation-delay: -0.144s;
|
|
1005
|
-
}
|
|
1006
|
-
.lds-roller div:nth-child(4):after {
|
|
1007
|
-
top: 72px;
|
|
1008
|
-
left: 40px;
|
|
1009
|
-
}
|
|
1010
|
-
.lds-roller div:nth-child(5) {
|
|
1011
|
-
animation-delay: -0.18s;
|
|
1012
|
-
}
|
|
1013
|
-
.lds-roller div:nth-child(5):after {
|
|
1014
|
-
top: 71px;
|
|
1015
|
-
left: 32px;
|
|
1016
|
-
}
|
|
1017
|
-
.lds-roller div:nth-child(6) {
|
|
1018
|
-
animation-delay: -0.216s;
|
|
1019
|
-
}
|
|
1020
|
-
.lds-roller div:nth-child(6):after {
|
|
1021
|
-
top: 68px;
|
|
1022
|
-
left: 24px;
|
|
1023
|
-
}
|
|
1024
|
-
.lds-roller div:nth-child(7) {
|
|
1025
|
-
animation-delay: -0.252s;
|
|
1026
|
-
}
|
|
1027
|
-
.lds-roller div:nth-child(7):after {
|
|
1028
|
-
top: 63px;
|
|
1029
|
-
left: 17px;
|
|
1030
|
-
}
|
|
1031
|
-
.lds-roller div:nth-child(8) {
|
|
1032
|
-
animation-delay: -0.288s;
|
|
1033
|
-
}
|
|
1034
|
-
.lds-roller div:nth-child(8):after {
|
|
1035
|
-
top: 56px;
|
|
1036
|
-
left: 12px;
|
|
1037
|
-
}
|
|
1038
|
-
@keyframes lds-roller {
|
|
1039
|
-
0% {
|
|
1040
|
-
transform: rotate(0deg);
|
|
1041
|
-
}
|
|
1042
|
-
100% {
|
|
1043
|
-
transform: rotate(360deg);
|
|
1044
|
-
}
|
|
1045
|
-
}
|
|
1046
|
-
`;render(){return Rt`
|
|
1047
|
-
<div
|
|
1048
|
-
style="
|
|
1049
|
-
background: #151f2a;
|
|
1050
|
-
width: 100%;
|
|
1051
|
-
position: absolute;
|
|
1052
|
-
z-index: 5;
|
|
1053
|
-
height: 100%;
|
|
1054
|
-
margin: 0;
|
|
1055
|
-
padding: 0;
|
|
1056
|
-
top: 0;
|
|
1057
|
-
left: 0;
|
|
1058
|
-
"
|
|
1059
|
-
>
|
|
1060
|
-
<img
|
|
1061
|
-
src="copio.svg"
|
|
1062
|
-
style="
|
|
1063
|
-
position: absolute;
|
|
1064
|
-
top: 50%;
|
|
1065
|
-
left: 50%;
|
|
1066
|
-
transform: translate(-50%, -50%);
|
|
1067
|
-
opacity: 0.3;
|
|
1068
|
-
z-index: 1;
|
|
1069
|
-
max-width: 320px;
|
|
1070
|
-
"
|
|
1071
|
-
/>
|
|
1072
|
-
<div
|
|
1073
|
-
class="lds-roller"
|
|
1074
|
-
style="
|
|
1075
|
-
position: absolute;
|
|
1076
|
-
top: calc(50% + -50px);
|
|
1077
|
-
left: 50%;
|
|
1078
|
-
transform: translate(-50%) scale(1);
|
|
1079
|
-
opacity: 0.5;
|
|
1080
|
-
"
|
|
1081
|
-
>
|
|
1082
|
-
<div></div>
|
|
1083
|
-
<div></div>
|
|
1084
|
-
<div></div>
|
|
1085
|
-
<div></div>
|
|
1086
|
-
<div></div>
|
|
1087
|
-
<div></div>
|
|
1088
|
-
<div></div>
|
|
1089
|
-
<div></div>
|
|
1090
|
-
</div>
|
|
1091
|
-
</div>
|
|
1092
|
-
`}};customElements.define("copio-loader",sr);ci();Bi();var rr=`
|
|
7
|
+
`),v=Math.round(d/g.length);return{pagesResults:g,combinedText:m,averageConfidence:v}}async function hi(){if(Pe){try{await Pe.terminate()}catch(n){console.warn("Error during OCR worker termination:",n)}Pe=null,mr=null,li=null}}var Ys,Pe,mr,li,Js=ke(()=>{ii();Ni();Ys=[{code:"eng",label:"English",flag:"\u{1F1EC}\u{1F1E7}"},{code:"spa",label:"Spanish (Espa\xF1ol)",flag:"\u{1F1EA}\u{1F1F8}"},{code:"fra",label:"French (Fran\xE7ais)",flag:"\u{1F1EB}\u{1F1F7}"},{code:"deu",label:"German (Deutsch)",flag:"\u{1F1E9}\u{1F1EA}"},{code:"ita",label:"Italian (Italiano)",flag:"\u{1F1EE}\u{1F1F9}"},{code:"por",label:"Portuguese (Portugu\xEAs)",flag:"\u{1F1F5}\u{1F1F9}"},{code:"nld",label:"Dutch (Nederlands)",flag:"\u{1F1F3}\u{1F1F1}"},{code:"pol",label:"Polish (Polski)",flag:"\u{1F1F5}\u{1F1F1}"},{code:"rus",label:"Russian (\u0420\u0443\u0441\u0441\u043A\u0438\u0439)",flag:"\u{1F1F7}\u{1F1FA}"},{code:"chi_sim",label:"Chinese Simplified (\u7B80\u4F53\u4E2D\u6587)",flag:"\u{1F1E8}\u{1F1F3}"},{code:"chi_tra",label:"Chinese Traditional (\u7E41\u9AD4\u4E2D\u6587)",flag:"\u{1F1F9}\u{1F1FC}"},{code:"jpn",label:"Japanese (\u65E5\u672C\u8A9E)",flag:"\u{1F1EF}\u{1F1F5}"},{code:"kor",label:"Korean (\uD55C\uAD6D\uC5B4)",flag:"\u{1F1F0}\u{1F1F7}"},{code:"ara",label:"Arabic (\u0627\u0644\u0639\u0631\u0628\u064A\u0629)",flag:"\u{1F1F8}\u{1F1E6}"},{code:"hin",label:"Hindi (\u0939\u093F\u0928\u094D\u0926\u0940)",flag:"\u{1F1EE}\u{1F1F3}"},{code:"tur",label:"Turkish (T\xFCrk\xE7e)",flag:"\u{1F1F9}\u{1F1F7}"},{code:"vie",label:"Vietnamese (Ti\u1EBFng Vi\u1EC7t)",flag:"\u{1F1FB}\u{1F1F3}"}],Pe=null,mr=null,li=null});var za={};Re(za,{Path2D:()=>jh,createCanvas:()=>Hh,default:()=>$h});var $h,Hh,jh,Va=ke(()=>{$h={},Hh=()=>null,jh=globalThis.Path2D||class{}});var jc={};Re(jc,{Path2D:()=>Wh,createCanvas:()=>Vh,default:()=>zh});var zh,Vh,Wh,zc=ke(()=>{zh={},Vh=()=>null,Wh=globalThis.Path2D||class{}});var Vc={};Re(Vc,{Path2D:()=>Xh,createCanvas:()=>qh,default:()=>Gh});var Gh,qh,Xh,Wc=ke(()=>{Gh={},qh=()=>null,Xh=globalThis.Path2D||class{}});var Gc={};Re(Gc,{Path2D:()=>Jh,createCanvas:()=>Yh,default:()=>Kh});var Kh,Yh,Jh,qc=ke(()=>{Kh={},Yh=()=>null,Jh=globalThis.Path2D||class{}});var Xc={};Re(Xc,{Path2D:()=>td,createCanvas:()=>Zh,default:()=>Qh});var Qh,Zh,td,Kc=ke(()=>{Qh={},Zh=()=>null,td=globalThis.Path2D||class{}});var Yc={};Re(Yc,{Path2D:()=>sd,createCanvas:()=>id,default:()=>ed});var ed,id,sd,Jc=ke(()=>{ed={},id=()=>null,sd=globalThis.Path2D||class{}});var wr={};Re(wr,{BUILD_DATE:()=>vc,COPIO_EVENTS:()=>Vt,Canvas2DAdapter:()=>$e,CopioDocOcrDialog:()=>Qs,CopioEngine:()=>Oi,CopioScanner:()=>zs,CopioSyncDialog:()=>Zs,DocRepository:()=>ti,Document:()=>Us,ImageProcessorPort:()=>_e,IndexedDbStorageAdapter:()=>Se,LicenseManager:()=>br,MemoryStorageAdapter:()=>qe,NullImageProcessorAdapter:()=>Li,NullOcrAdapter:()=>de,NullPdfAdapter:()=>Ee,NullSyncAdapter:()=>rn,OcrPort:()=>Be,OpfsStorageAdapter:()=>Si,Page:()=>Fi,PdfKitAdapter:()=>Vi,PdfPort:()=>Ue,PeerJsAdapter:()=>nn,SUPPORTED_LANGUAGES:()=>Ys,ScanSession:()=>$s,StoragePort:()=>he,SyncManager:()=>di,SyncPort:()=>He,TesseractWasmAdapter:()=>zi,VERSION:()=>wc,adoptScannerStyles:()=>ur,clearNotifications:()=>Pa,createDefaultAdapter:()=>ns,dispatchCopioEvent:()=>lr,docRepository:()=>ds,exportDocumentAsImages:()=>Ha,exportDocumentAsPdf:()=>tn,extractExif:()=>Jn,fileToBase64:()=>Qn,getAssetBase:()=>ir,getContainer:()=>ai,getCroppedSrc:()=>ya,getOcrWorker:()=>ms,getRegisteredService:()=>si,getScannerStyleSheet:()=>dr,hasActiveEdits:()=>cr,loadCropper:()=>yc,loadJsZip:()=>nr,loadPdfKit:()=>sr,loadPeerJs:()=>rr,loadQrCode:()=>ar,loadScript:()=>ei,loadTesseract:()=>or,normalizeEditStack:()=>us,notify:()=>Dt,probeOpfs:()=>Un,randomId:()=>Di,recognizeDocumentPages:()=>Hi,recognizeImageText:()=>bs,registerService:()=>ni,renderPdfPagesToDataUrls:()=>vr,resolveAssetUrl:()=>Ne,rotateSrc:()=>ba,scannerCss:()=>js,setAssetBase:()=>Ii,setContainer:()=>ri,terminateOcrWorker:()=>hi,thresholdSrc:()=>ma});var he=class{async init(){throw new Error("StoragePort.init() must be implemented by adapter")}async listDocs(){throw new Error("StoragePort.listDocs() must be implemented by adapter")}async getDoc(t){throw new Error("StoragePort.getDoc() must be implemented by adapter")}async saveDoc(t,e){throw new Error("StoragePort.saveDoc() must be implemented by adapter")}async renameDoc(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t){throw new Error("StoragePort.deleteDoc() must be implemented by adapter")}async savePage(t,e,i){throw new Error("StoragePort.savePage() must be implemented by adapter")}async getPage(t,e){throw new Error("StoragePort.getPage() must be implemented by adapter")}async deletePage(t,e){throw new Error("StoragePort.deletePage() must be implemented by adapter")}subscribe(t){return()=>{}}};var qe=class extends he{#t=new Map;#e=new Map;#i=new Set;constructor(){super()}async init(){return{kind:"memory",persistent:!1}}listDocsSync(){return Array.from(this.#t.values()).map(t=>({id:t.id,name:t.name,pages:Array.isArray(t.pages)?[...t.pages]:[]}))}async listDocs(){return this.listDocsSync()}getDocSync(t){let e=this.#t.get(t);return e?{id:e.id,name:e.name,pages:Array.isArray(e.pages)?[...e.pages]:[]}:null}async getDoc(t){return this.getDocSync(t)}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=[];if(Array.isArray(e.pages))i=[...e.pages];else if(typeof e.pages=="string")try{i=JSON.parse(e.pages)}catch{i=[]}this.#t.set(t,{id:t,name:e.name||"",pages:i}),this.#n()}async deleteDoc(t){this.#t.delete(t);let e=`${t}/`;for(let i of this.#e.keys())i.startsWith(e)&&this.#e.delete(i);this.#n()}async renameDoc(t,e){let i=this.#t.get(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,this.#n()}async savePage(t,e,i){this.#e.set(`${t}/${e}`,i);let r=this.#t.get(t);if(r){let o=r.pages.findIndex(g=>g.id===e);if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i};else{let g=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};r.pages.push(g)}}this.#n()}async getPage(t,e){if(this.#e.has(`${t}/${e}`))return this.#e.get(`${t}/${e}`);let i=this.#t.get(t);if(i){let r=i.pages.find(o=>o.id===e);if(r)return r.src??r}return null}async deletePage(t,e){this.#e.delete(`${t}/${e}`);let i=this.#t.get(t);i&&(i.pages=i.pages.filter(r=>r.id!==e)),this.#n()}subscribe(t){return this.#i.add(t),()=>{this.#i.delete(t)}}clear(){this.#t.clear(),this.#e.clear(),this.#n()}#n(){for(let t of this.#i)try{t()}catch(e){console.error("Error in MemoryStorageAdapter subscriber:",e)}}};var Je=n=>typeof n;var yo=Je(""),sl=Je(!0),vo=Je(0),nl=Je(Je),wn="type",pi="default",Ir="Listener",lo="Result",Lr="add",fi="Has",_s="Ids",Ye="Table",ho=Ye+"s",rl=Ye+_s,Qi="Row",wo=Qi+"Count",xo=Qi+_s,al="Sorted"+Qi+_s,As="Cell",En=As+_s,_n="Value",uo=_n+"s",ol=_n+_s,Rt=n=>""+n;var cl=(n,t="",e)=>n.split(t,e),Fr=globalThis,Rn=Math,Pr=Rn.max,Tr=Rn.min,ll=Rn.floor,Ao=isFinite,At=n=>n==null,Mt=(n,t,e)=>At(n)?e?.():t(n),So=n=>n==yo||n==sl,hl=n=>Je(n)==yo,ve=n=>Je(n)==nl,Zi=n=>Array.isArray(n),Or=(n,t,e)=>n.slice(t,e),ce=n=>n.length,Eo=()=>{};var kr=async(n,t,e)=>{try{return await n()}catch(i){t?.(i)}},Nr=(n,t)=>n.includes(t),Cn=(n,t)=>n.every(t),_o=(n,t)=>ce(n)===ce(t)&&Cn(n,((e,i)=>t[i]===e)),po=(n,t)=>Cn(n,((e,i)=>i==0||t(n[i-1],e)<=0)),Br=(n,t)=>n.sort(t),re=(n,t)=>n.forEach(t),bi=(n,t)=>n.map(t),fo=n=>Co(n,((t,e)=>t+e),0),Ss=n=>ce(n)==0,Co=(n,t,e)=>n.reduce(t,e),ne=(n,...t)=>n.push(...t),go=n=>n.pop(),Po=n=>n.shift(),Yi=n=>{let t=Je(n);return So(t)||t==vo&&Ao(n)?t:void 0};var Pn=(n,t,e,i,r)=>At(r)?n.delCell(t,e,i,!0):n.setCell(t,e,i,r),Ur=(n,t,e)=>At(e)?n.delValue(t):n.setValue(t,e),zr=n=>t=>Co(ts(t),((e,i)=>e+n(i)),0),es=n=>n?.size??0,yi=zr(es),De=zr(yi),Rr=zr(De),Ft=(n,t)=>n?.has(t)??!1,yt=n=>At(n)||es(n)==0,ts=n=>[...n?.values()??[]],Ji=n=>n.clear(),bt=(n,t)=>n?.forEach(t),xe=(n,t)=>n?.delete(t),Qe=Object,mo=n=>Qe.getPrototypeOf(n),dl=Qe.isFrozen,To=Qe.entries,Tn=n=>!At(n)&&Mt(mo(n),(t=>t==Qe.prototype||At(mo(t))),(()=>!0)),ul=Qe.keys,is=Qe.freeze,pl=(n=[])=>Qe.fromEntries(n),xs=(n,t)=>t in n,ko=(n,t)=>(delete n[t],n),fl=(n,t)=>re(To(n),(([e,i])=>t(i,e))),Me=(n,t)=>pl(((e,i)=>bi(To(e),(([r,o])=>i(o,r))))(n,((e,i)=>[i,t(e,i)]))),we=n=>Tn(n)&&(t=>ce(ul(t)))(n)==0;var Xe=(n,t,e,i=0)=>At(n)||!Tn(n)||!i&&we(n)||dl(n)?(e?.(),!1):(fl(n,((r,o)=>{t(r,o)||ko(n,o)})),!!i||!we(n)),ft=n=>new Map(n),mi=n=>[...n?.keys()??[]],ht=(n,t)=>n?.get(t),Ht=(n,t)=>bt(n,((e,i)=>t(i,e))),mt=(n,t,e)=>At(e)?(xe(n,t),n):n?.set(t,e),Lt=(n,t,e,i)=>(Ft(n,t)?i?.(ht(n,t)):mt(n,t,e()),ht(n,t)),gi=(n,t,e,i=mt)=>(Me(t,((r,o)=>e(n,o,r))),Ht(n,(r=>xs(t,r)?0:i(n,r))),n),se=(n,t,e,i)=>{let r={};return bt(n,((o,g)=>{if(!e?.(o,g)){let d=t?t(o,g):o;i?.(d)||(r[g]=d)}})),r},$r=(n,t,e)=>se(n,(i=>se(i,t,e)),yt,we),xn=(n,t,e)=>se(n,(i=>$r(i,t,e)),yt,we),Ke=(n,t)=>{let e=ft();return bt(n,((i,r)=>e.set(r,t?.(i)??i))),e},Hr=n=>Ke(n,Ke),Mr=n=>Ke(n,Hr),Es=(n,t,e,i,r=0)=>Mt((e?Lt:ht)(n,t[r],r>ce(t)-2?e:ft),(o=>{if(r>ce(t)-2)return i?.(o)&&mt(n,t[r]),o;let g=Es(o,t,e,i,r+1);return yt(o)&&mt(n,t[r]),g})),jt=n=>new Set(Zi(n)||At(n)?n:[n]),Nt=(n,t)=>n?.add(t),Mn=(n,t,e,i,r)=>{let o=n.hasRow,g=ft(),d=ft(),m=ft(),v=ft(),u=ft(),a=ft(),p=(y,s,...c)=>{let f=Lt(a,y,jt);return re(c,(w=>Nt(f,w)&&s&&n.callListener(w))),c},x=(y,...s)=>Mt(ht(a,y),(c=>{re(Ss(s)?ts(c):s,(f=>{n.delListener(f),xe(c,f)})),yt(c)&&mt(a,y)})),T=(y,s)=>{mt(g,y,s),Ft(d,y)||(mt(d,y,t()),mt(v,y,ft()),mt(u,y,ft()),r(m))},l=y=>{mt(g,y),mt(d,y),mt(v,y),mt(u,y),x(y),r(m)};return[()=>n,()=>mi(g),y=>Ht(d,y),y=>Ft(d,y),y=>ht(g,y),y=>ht(d,y),(y,s)=>mt(d,y,s),T,(y,s,c,f,w)=>{T(y,s);let R=ft(),S=ft(),D=ht(v,y),N=ht(u,y),H=Y=>{let it=z=>n.getCell(s,Y,z),ot=ht(D,Y),K=o(s,Y)?e(f(it,Y)):void 0;if(ot===K||Zi(ot)&&Zi(K)&&_o(ot,K)||mt(R,Y,[ot,K]),!At(w)){let z=ht(N,Y),W=o(s,Y)?w(it,Y):void 0;z!=W&&mt(S,Y,W)}},j=Y=>{c((()=>{bt(R,(([,it],ot)=>mt(D,ot,it))),bt(S,((it,ot)=>mt(N,ot,it)))}),R,S,D,N,Y),Ji(R),Ji(S)};Ht(D,H),n.hasTable(s)&&re(n.getRowIds(s),(Y=>{Ft(D,Y)||H(Y)})),j(!0),x(y),p(y,0,n.addRowListener(s,null,((Y,it,ot)=>H(ot))),n.addTableListener(s,(()=>j())))},l,y=>i(y,m),()=>Ht(a,l),p,x]},kn=(n,t)=>hl(n)?e=>e(n):n??(()=>t??""),Cs=(n,t)=>{let e=new WeakMap;return i=>{e.has(i)||e.set(i,n(i));let r=e.get(i);return t?.(r),r}},gl=/^\d+$/,Ro=()=>{let n=[],t=0;return[e=>(e?Po(n):null)??""+t++,e=>{gl.test(e)&&ce(n)<1e3&&ne(n,e)}]},Ps=n=>{let t,[e,i]=Ro(),r=ft();return[(o,g,d,m=[],v=()=>[])=>{t??=n();let u=e(1);return mt(r,u,[o,g,d,m,v]),Nt(Es(g,d??[""],jt),u),u},(o,g,...d)=>re(((m,v=[""])=>{let u=[],a=(p,x)=>x==ce(v)?ne(u,p):v[x]===null?bt(p,(T=>a(T,x+1))):re([v[x],null],(T=>a(ht(p,T),x+1)));return a(m,0),u})(o,g),(m=>bt(m,(v=>ht(r,v)[0](t,...g??[],...d))))),o=>Mt(ht(r,o),(([,g,d])=>(Es(g,d??[""],void 0,(m=>(xe(m,o),yt(m)?1:0))),mt(r,o),i(o),d))),o=>Mt(ht(r,o),(([g,,d=[],m,v])=>{let u=(...a)=>{let p=ce(a);p==ce(d)?g(t,...a,...v(a)):At(d[p])?re(m[p]?.(...a)??[],(x=>u(...a,x))):u(...a,d[p])};u()}))]},hd=Cs((n=>{let t,e,i,r=100,o=ft(),g=ft(),d=1,m=ft(),v=ft(),[u,a,p]=Ps((()=>W)),x=ft(),T=ft(),l=[],y=[],s=(X,et)=>{d=0,n.transaction((()=>{let[st,ct]=ht(x,et);bt(st,((nt,G)=>bt(nt,((A,_)=>bt(A,((I,h)=>Pn(n,G,_,h,I[X]))))))),bt(ct,((nt,G)=>Ur(n,G,nt[X])))})),d=1},c=X=>{mt(x,X),mt(T,X),a(v,[X])},f=(X,et)=>re(((st,ct)=>st.splice(0,ct))(X,et??ce(X)),c),w=()=>f(l,ce(l)-r),R=()=>Mt(t,(()=>{ne(l,t),w(),f(y),t=void 0,i=1})),S=()=>{t=go(l),i=1},D,N,H=(X="")=>(At(t)&&(t=""+e++,mt(x,t,[o,g]),K(t,X),o=ft(),g=ft(),i=1),t),j=()=>{Ss(l)||(((X,...et)=>{X.unshift(...et)})(y,H()),s(0,t),t=go(l),i=1)},Y=()=>{Ss(y)||(ne(l,t),t=Po(y),s(1,t),i=1)},it=()=>{i&&(a(m),i=0)},ot=X=>{let et=H(X);return it(),et},K=(X,et)=>(z(X)&&ht(T,X)!==et&&(mt(T,X,et),a(v,[X])),W),z=X=>Ft(x,X),W={setSize:X=>(r=X,w(),W),addCheckpoint:ot,setCheckpoint:K,getStore:()=>n,getCheckpointIds:()=>[[...l],t,[...y]],forEachCheckpoint:X=>Ht(T,X),hasCheckpoint:z,getCheckpoint:X=>ht(T,X),goBackward:()=>(j(),it(),W),goForward:()=>(Y(),it(),W),goTo:X=>{let et=Nr(l,X)?j:Nr(y,X)?Y:null;for(;!At(et)&&X!=t;)et();return it(),W},addCheckpointIdsListener:X=>u(X,m),addCheckpointListener:(X,et)=>u(et,v,[X]),delListener:X=>(p(X),W),clear:()=>(f(l),f(y),At(t)||c(t),t=void 0,e=0,ot(),W),clearForward:()=>(Ss(y)||(f(y),a(m)),W),destroy:()=>{n.delListener(D),n.delListener(N)},getListenerStats:()=>({checkpointIds:yi(m),checkpoint:yi(v)}),_registerListeners:()=>{D=n.addCellListener(null,null,null,((X,et,st,ct,nt,G)=>{if(d){R();let A=Lt(o,et,ft),_=Lt(A,st,ft),I=Lt(_,ct,(()=>[G,void 0]));I[1]=nt,I[0]===nt&&yt(mt(_,ct))&&yt(mt(A,st))&&yt(mt(o,et))&&S(),it()}})),N=n.addValueListener(null,((X,et,st,ct)=>{if(d){R();let nt=Lt(g,et,(()=>[ct,void 0]));nt[1]=st,nt[0]===st&&yt(mt(g,et))&&S(),it()}}))}};return is(W.clear())}),(n=>n._registerListeners())),ml=cl("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),dd=ft(bi(ml,((n,t)=>[n,t])));var ud=Fr.crypto?n=>Fr.crypto.getRandomValues(n):n=>bi(n,(()=>ll(256*Rn.random())));var bl=JSON.stringify,Dr=JSON.parse,Ki=n=>bl(n,((t,e)=>{return i=Map,e instanceof i?Qe.fromEntries([...e]):e;var i})),pd=new Fr.TextEncoder;var fd=2**36,gd=2**30,md=2**24,bd=2**18;var Mo=(n,t)=>(n??0)<(t??0)?-1:1,yd=Cs((n=>{let t=ft(),e=ft(),[i,r,o]=Ps((()=>c)),[g,d,m,v,u,a,p,,x,T,l,y]=Mn(n,ft,(f=>At(f)?"":Zi(f)?bi(f,Rt):Rt(f)),i,r),s=(f,w,R)=>{let S=u(f);bt(R,((D,N)=>w(N,(H=>bt(D,(j=>H(j,(Y=>n.forEachCell(S,j,Y)))))))))},c={setIndexDefinition:(f,w,R,S,D,N=Mo)=>{let H=At(D)?void 0:([j],[Y])=>D(j,Y);return x(f,w,((j,Y,it,ot,K,z)=>{let W=0,X=jt(),et=jt(),st=a(f);if(bt(Y,(([ct,nt],G)=>{let A=jt(ct),_=jt(nt);bt(A,(I=>xe(_,I)?xe(A,I):0)),bt(A,(I=>{Nt(X,I),Mt(ht(st,I),(h=>{xe(h,G),yt(h)&&(mt(st,I),W=1)}))})),bt(_,(I=>{Nt(X,I),Ft(st,I)||(mt(st,I,jt()),W=1),Nt(ht(st,I),G),At(S)||Nt(et,I)}))})),j(),yt(K)||(z?Ht(st,(ct=>Nt(et,ct))):Ht(it,(ct=>Mt(ht(ot,ct),(nt=>re(Zi(nt)?nt:[nt],(G=>Nt(et,G))))))),bt(et,(ct=>{let nt=(A,_)=>N(ht(K,A),ht(K,_),ct),G=[...ht(st,ct)];po(G,nt)||(mt(st,ct,jt(Br(G,nt))),Nt(X,ct))}))),(W||z)&&!At(H)){let ct=[...st];po(ct,H)||(p(f,ft(Br(ct,H))),W=1)}W&&r(t,[f]),bt(X,(ct=>r(e,[f,ct])))}),kn(R),Mt(S,kn)),c},delIndexDefinition:f=>(T(f),c),getStore:g,getIndexIds:d,forEachIndex:f=>m(((w,R)=>f(w,(S=>s(w,S,R))))),forEachSlice:(f,w)=>s(f,w,a(f)),hasIndex:v,hasSlice:(f,w)=>Ft(a(f),w),getTableId:u,getSliceIds:f=>mi(a(f)),getSliceRowIds:(f,w)=>ts(ht(a(f),w)),addIndexIdsListener:l,addSliceIdsListener:(f,w)=>i(w,t,[f]),addSliceRowIdsListener:(f,w,R)=>i(R,e,[f,w]),delListener:f=>(o(f),c),destroy:y,getListenerStats:()=>({sliceIds:yi(t),sliceRowIds:De(e)})};return is(c)}));var An=n=>[n,n],Ut=(n,t=yi)=>t(n[0])+t(n[1]),$t=()=>[ft(),ft()],bo=n=>[...n],Sn=([n,t])=>n===t,ws=(n,t,e)=>mt(n,t,ht(n,t)==-e?void 0:e),Ts=()=>{let n,t,e=!1,i=!1,r=0,o=[],g=ft(),d=ft(),m=ft(),v=ft(),u=ft(),a=ft(),p=ft(),x=ft(),T=ft(),l=ft(),y=ft(),s=ft(),c=ft(),f=ft(),w=jt(),R=ft(),S=ft(),D=ft(),N=ft(),H=$t(),j=$t(),Y=$t(),it=$t(),ot=$t(),K=$t(),z=$t(),W=$t(),X=$t(),et=$t(),st=$t(),ct=$t(),nt=$t(),G=$t(),A=$t(),_=$t(),I=$t(),h=$t(),b=$t(),C=$t(),P=$t(),O=$t(),M=ft(),E=$t(),[L,U,B,k]=Ps((()=>Qt)),F=$=>{if(!Xe($,((J,at)=>Nr([wn,pi],at))))return!1;let q=$[wn];return!(!So(q)&&q!=vo)&&(Yi($[pi])!=q&&ko($,pi),!0)},V=Zi,Q=($,q)=>(!n||Ft(y,q)||be(q))&&Xe($,((J,at)=>Z(q,at,J)),(()=>be(q))),Z=($,q,J,at)=>Xe(at?J:dt(J,$,q),((ut,gt)=>Mt(tt($,q,gt,ut),(xt=>(J[gt]=xt,!0)),(()=>!1))),(()=>be($,q))),tt=($,q,J,at)=>n?Mt(ht(ht(y,$),J),(ut=>Yi(at)!=ut[wn]?be($,q,J,at,ut[pi]):at),(()=>be($,q,J,at))):At(Yi(at))?be($,q,J,at):at,rt=($,q)=>Xe(q?$:lt($),((J,at)=>Mt(pt(at,J),(ut=>($[at]=ut,!0)),(()=>!1))),(()=>ui())),pt=($,q)=>t?Mt(ht(c,$),(J=>Yi(q)!=J[wn]?ui($,q,J[pi]):q),(()=>ui($,q))):At(Yi(q))?ui($,q):q,dt=($,q,J)=>(Mt(ht(s,q),(([at,ut])=>{bt(at,((gt,xt)=>{xs($,xt)||($[xt]=gt)})),bt(ut,(gt=>{xs($,gt)||be(q,J,gt)}))})),$),lt=$=>(t&&(bt(f,((q,J)=>{xs($,J)||($[J]=q)})),bt(w,(q=>{xs($,q)||ui(q)}))),$),vt=$=>gi(y,$,((q,J,at)=>{let ut=ft(),gt=jt();gi(Lt(y,J,ft),at,((xt,_t,Pt)=>{mt(xt,_t,Pt),Mt(Pt[pi],(Te=>mt(ut,_t,Te)),(()=>Nt(gt,_t)))})),mt(s,J,[ut,gt])}),((q,J)=>{mt(y,J),mt(s,J)})),Et=$=>gi(c,$,((q,J,at)=>{mt(c,J,at),Mt(at[pi],(ut=>mt(f,J,ut)),(()=>Nt(w,J)))}),((q,J)=>{mt(c,J),mt(f,J),xe(w,J)})),wt=$=>we($)?mn():fn($),Ct=$=>gi(D,$,((q,J,at)=>Tt(J,at)),((q,J)=>je(J))),Tt=($,q)=>gi(Lt(D,$,(()=>(Ve($,1),mt(R,$,Ro()),mt(S,$,ft()),ft()))),q,((J,at,ut)=>It($,J,at,ut)),((J,at)=>ze($,J,at))),It=($,q,J,at,ut)=>gi(Lt(q,J,(()=>(Wi($,J,1),ft()))),at,((gt,xt,_t)=>Ot($,J,gt,xt,_t)),((gt,xt)=>Yt($,q,J,gt,xt,ut))),Ot=($,q,J,at,ut)=>{Ft(J,at)||pe($,q,at,1);let gt=ht(J,at);ut!==gt&&(Gt($,q,at,gt,ut),mt(J,at,ut))},Jt=($,q,J,at,ut)=>Mt(ht(q,J),(gt=>Ot($,J,gt,at,ut)),(()=>It($,q,J,dt({[at]:ut},$,J)))),ae=$=>we($)?bn():gn($),me=$=>gi(N,$,((q,J,at)=>le(J,at)),((q,J)=>Xt(J))),le=($,q)=>{Ft(N,$)||an($,1);let J=ht(N,$);q!==J&&(Gi($,J,q),mt(N,$,q))},ue=$=>ht(D,$)??Tt($,{}),je=$=>Tt($,{}),ze=($,q,J)=>{let[,at]=ht(R,$);at(J),It($,q,J,{},!0)},Yt=($,q,J,at,ut,gt)=>{let xt=ht(ht(s,$)?.[0],ut);if(!At(xt)&&!gt)return Ot($,J,at,ut,xt);let _t=Pt=>{Gt($,J,Pt,ht(at,Pt)),pe($,J,Pt,-1),mt(at,Pt)};At(xt)?_t(ut):Ht(at,_t),yt(at)&&(Wi($,J,-1),yt(mt(q,J))&&(Ve($,-1),mt(D,$),mt(R,$),mt(S,$)))},Xt=$=>{let q=ht(f,$);if(!At(q))return le($,q);Gi($,ht(N,$)),an($,-1),mt(N,$)},Ve=($,q)=>ws(g,$,q),Wi=($,q,J)=>ws(Lt(v,$,ft),q,J)&&mt(m,$,Lt(m,$,(()=>0))+J),pe=($,q,J,at)=>{let ut=ht(S,$),gt=ht(ut,J)??0;(gt==0&&at==1||gt==1&&at==-1)&&ws(Lt(d,$,ft),J,at),mt(ut,J,gt!=-at?gt+at:null),ws(Lt(Lt(u,$,ft),q,ft),J,at)},Gt=($,q,J,at,ut)=>{Lt(Lt(Lt(a,$,ft),q,ft),J,(()=>[at,0]))[1]=ut,o[3]?.($,q,J,ut)},an=($,q)=>ws(p,$,q),Gi=($,q,J)=>{Lt(x,$,(()=>[q,0]))[1]=J,o[4]?.($,J)},be=($,q,J,at,ut)=>(ne(Lt(Lt(Lt(T,$,ft),q,ft),J,(()=>[])),at),ut),ui=($,q,J)=>(ne(Lt(l,$,(()=>[])),q),J),ye=($,q,J)=>Mt(ht(ht(ht(a,$),q),J),(([at,ut])=>[!0,at,ut]),(()=>[!1,...An(hn($,q,J))])),on=$=>Mt(ht(x,$),(([q,J])=>[!0,q,J]),(()=>[!1,...An(dn($))])),qi=$=>yt(T)||yt(_[$])?0:bt($?Mr(T):T,((q,J)=>bt(q,((at,ut)=>bt(at,((gt,xt)=>U(_[$],[J,ut,xt],gt))))))),We=$=>yt(l)||yt(I[$])?0:bt($?Ke(l):l,((q,J)=>U(I[$],[J],q))),te=($,q,J,at)=>{if(!yt($))return U(q,at,(()=>se($))),Ht($,((ut,gt)=>U(J,[...at??[],ut],gt==1))),1},cn=$=>{let q=un();q!=e&&U(H[$],void 0,q);let J=yt(et[$]),at=yt(nt[$])&&yt(G[$])&&yt(X[$])&&yt(st[$])&&yt(K[$])&&yt(z[$])&&yt(W[$])&&J&&yt(Y[$])&&yt(it[$]),ut=yt(A[$])&&yt(ct[$])&&yt(ot[$])&&yt(j[$]);if(!at||!ut){let gt=$?[Ke(g),Hr(d),Ke(m),Hr(v),Mr(u),Mr(a)]:[g,d,m,v,u,a];if(!at){te(gt[0],Y[$],it[$]),bt(gt[1],((_t,Pt)=>te(_t,K[$],z[$],[Pt]))),bt(gt[2],((_t,Pt)=>{_t!=0&&U(W[$],[Pt],Xa(Pt))}));let xt=jt();bt(gt[3],((_t,Pt)=>{te(_t,X[$],st[$],[Pt])&&!J&&(U(et[$],[Pt,null]),Nt(xt,Pt))})),J||bt(gt[5],((_t,Pt)=>{if(!Ft(xt,Pt)){let Te=jt();bt(_t,(Ge=>bt(Ge,(([yn,vn],vs)=>vn!==yn?Nt(Te,vs):xe(Ge,vs))))),bt(Te,(Ge=>U(et[$],[Pt,Ge])))}})),bt(gt[4],((_t,Pt)=>bt(_t,((Te,Ge)=>te(Te,nt[$],G[$],[Pt,Ge])))))}if(!ut){let xt;bt(gt[5],((_t,Pt)=>{let Te;bt(_t,((Ge,yn)=>{let vn;bt(Ge,(([vs,co],el)=>{co!==vs&&(U(A[$],[Pt,yn,el],co,vs,ye),xt=Te=vn=1)})),vn&&U(ct[$],[Pt,yn],ye)})),Te&&U(ot[$],[Pt],ye)})),xt&&U(j[$],void 0,ye)}}},Wa=$=>{let q=pn();q!=i&&U(h[$],void 0,q);let J=yt(C[$])&&yt(P[$]),at=yt(O[$])&&yt(b[$]);if(!J||!at){let ut=$?[Ke(p),Ke(x)]:[p,x];if(J||te(ut[0],C[$],P[$]),!at){let gt;bt(ut[1],(([xt,_t],Pt)=>{_t!==xt&&(U(O[$],[Pt],_t,xt,on),gt=1)})),gt&&U(b[$],void 0,on)}}},Bt=($,...q)=>(Cr((()=>$(...bi(q,Rt)))),Qt),Ga=($,q,J,at,ut)=>{let gt=ln($,q,...J);return L((()=>{let xt=ln($,q,...J);_o(xt,gt)||(gt=xt,at(Qt,$,q,...J,gt))}),et[ut?1:0],[$,q],[oe])},xr=()=>xn(D),oe=()=>mi(D),qa=$=>mi(ht(S,Rt($))),Xa=$=>es(ht(D,Rt($))),Xi=$=>mi(ht(D,Rt($))),ln=($,q,J,at=0,ut)=>{return Tn($)?ln($.tableId,$.cellId,$.descending,$.offset,$.limit):bi(Or(Br((gt=ht(D,Rt($)),xt=(_t,Pt)=>[At(q)?Pt:ht(_t,Rt(q)),Pt],bi([...gt?.entries()??[]],(([_t,Pt])=>xt(Pt,_t)))),(([_t],[Pt])=>Mo(_t,Pt)*(J?-1:1))),at,At(ut)?ut:at+ut),(([,_t])=>_t));var gt,xt},Ar=($,q)=>mi(ht(ht(D,Rt($)),Rt(q))),hn=($,q,J)=>ht(ht(ht(D,Rt($)),Rt(q)),Rt(J)),Sr=()=>se(N),Er=()=>mi(N),dn=$=>ht(N,Rt($)),un=()=>!yt(D),Ka=$=>Ft(D,Rt($)),Ya=($,q)=>Ft(ht(S,Rt($)),Rt(q)),Ja=($,q)=>Ft(ht(D,Rt($)),Rt(q)),Qa=($,q,J)=>Ft(ht(ht(D,Rt($)),Rt(q)),Rt(J)),pn=()=>!yt(N),Za=$=>Ft(N,Rt($)),fn=$=>Bt((()=>(q=>Xe(q,Q,be))($)?Ct($):0)),gn=$=>Bt((()=>rt($)?me($):0)),to=$=>(kr((()=>wt(Dr($)))),Qt),eo=$=>Bt((()=>{if((n=Xe($,(q=>Xe(q,F))))&&(vt($),!yt(D))){let q=xr();mn(),fn(q)}})),io=$=>Bt((()=>{if(t=(q=>Xe(q,F))($)){let q=Sr();_r(),bn(),t=!0,Et($),gn(q)}})),mn=()=>Bt((()=>Ct({}))),so=$=>Bt((q=>Ft(D,q)?je(q):0),$),no=($,q)=>Bt(((J,at)=>Mt(ht(D,J),(ut=>Ft(ut,at)?ze(J,ut,at):0))),$,q),bn=()=>Bt((()=>me({}))),ro=()=>Bt((()=>{vt({}),n=!1})),_r=()=>Bt((()=>{Et({}),t=!1})),Cr=($,q)=>{if(r!=-1){ao();let J=$();return oo(q),J}},ao=()=>(r!=-1&&r++,r==1&&(o[0]?.(),U(M)),Qt),oo=$=>(r>0&&(r--,r==0&&(r=1,qi(1),yt(a)||cn(1),We(1),yt(x)||Wa(1),$?.(Qt)&&(bt(a,((q,J)=>bt(q,((at,ut)=>bt(at,(([gt],xt)=>Pn(Qt,J,ut,xt,gt))))))),Ji(a),bt(x,(([q],J)=>Ur(Qt,J,q))),Ji(x)),U(E[0],void 0),r=-1,qi(0),yt(a)||cn(0),We(0),yt(x)||Wa(0),o[1]?.(),U(E[1],void 0),o[2]?.(),r=0,e=un(),i=pn(),re([g,d,m,v,u,a,T,p,x,l],Ji))),Qt),Qt={getContent:()=>[xr(),Sr()],getTables:xr,getTableIds:oe,getTable:$=>$r(ht(D,Rt($))),getTableCellIds:qa,getRowCount:Xa,getRowIds:Xi,getSortedRowIds:ln,getRow:($,q)=>se(ht(ht(D,Rt($)),Rt(q))),getCellIds:Ar,getCell:hn,getValues:Sr,getValueIds:Er,getValue:dn,hasTables:un,hasTable:Ka,hasTableCell:Ya,hasRow:Ja,hasCell:Qa,hasValues:pn,hasValue:Za,getTablesJson:()=>Ki(D),getValuesJson:()=>Ki(N),getJson:()=>Ki([D,N]),getTablesSchemaJson:()=>Ki(y),getValuesSchemaJson:()=>Ki(c),getSchemaJson:()=>Ki([y,c]),hasTablesSchema:()=>n,hasValuesSchema:()=>t,setContent:$=>Bt((()=>{let q=ve($)?$():$;V(q)&&(([J,at])=>{(we(J)?mn:fn)(J),(we(at)?bn:gn)(at)})(q)})),setTables:fn,setTable:($,q)=>Bt((J=>Q(q,J)?Tt(J,q):0),$),setRow:($,q,J)=>Bt(((at,ut)=>Z(at,ut,J)?It(at,ue(at),ut,J):0),$,q),addRow:($,q,J=!0)=>Cr((()=>{let at;return Z($,at,q)&&($=Rt($),It($,ue($),at=((ut,gt)=>{let[xt]=ht(R,ut),_t;do _t=xt(gt);while(Ft(ht(D,ut),_t));return _t})($,J?1:0),q)),at})),setPartialRow:($,q,J)=>Bt(((at,ut)=>{if(Z(at,ut,J,1)){let gt=ue(at);Me(J,((xt,_t)=>Jt(at,gt,ut,_t,xt)))}}),$,q),setCell:($,q,J,at)=>Bt(((ut,gt,xt)=>Mt(tt(ut,gt,xt,ve(at)?at(hn(ut,gt,xt)):at),(_t=>Jt(ut,ue(ut),gt,xt,_t)))),$,q,J),setValues:gn,setPartialValues:$=>Bt((()=>rt($,1)?Me($,((q,J)=>le(J,q))):0)),setValue:($,q)=>Bt((J=>Mt(pt(J,ve(q)?q(dn(J)):q),(at=>le(J,at)))),$),applyChanges:$=>Bt((()=>{Me($[0],((q,J)=>At(q)?so(J):Me(q,((at,ut)=>At(at)?no(J,ut):Me(at,((gt,xt)=>Pn(Qt,J,ut,xt,gt))))))),Me($[1],((q,J)=>Ur(Qt,J,q)))})),setTablesJson:to,setValuesJson:$=>(kr((()=>ae(Dr($)))),Qt),setJson:$=>Bt((()=>kr((()=>{let[q,J]=Dr($);wt(q),ae(J)}),(()=>to($))))),setTablesSchema:eo,setValuesSchema:io,setSchema:($,q)=>Bt((()=>{eo($),io(q)})),delTables:mn,delTable:so,delRow:no,delCell:($,q,J,at)=>Bt(((ut,gt,xt)=>Mt(ht(D,ut),(_t=>Mt(ht(_t,gt),(Pt=>Ft(Pt,xt)?Yt(ut,_t,gt,Pt,xt,at):0))))),$,q,J),delValues:bn,delValue:$=>Bt((q=>Ft(N,q)?Xt(q):0),$),delTablesSchema:ro,delValuesSchema:_r,delSchema:()=>Bt((()=>{ro(),_r()})),transaction:Cr,startTransaction:ao,getTransactionChanges:()=>[se(a,(($,q)=>ht(g,q)===-1?void 0:se($,((J,at)=>ht(ht(v,q),at)===-1?void 0:se(J,(([,ut])=>ut),(ut=>Sn(ut)))),yt,we)),yt,we),se(x,(([,$])=>$),($=>Sn($))),1],getTransactionLog:()=>[!yt(a),!yt(x),xn(a,bo,Sn),xn(T),se(x,bo,Sn),se(l),se(g),$r(v),xn(u),se(p)],finishTransaction:oo,forEachTable:$=>bt(D,((q,J)=>$(J,(at=>bt(q,((ut,gt)=>at(gt,(xt=>Ht(ut,xt))))))))),forEachTableCell:($,q)=>Ht(ht(S,Rt($)),q),forEachRow:($,q)=>bt(ht(D,Rt($)),((J,at)=>q(at,(ut=>Ht(J,ut))))),forEachCell:($,q,J)=>Ht(ht(ht(D,Rt($)),Rt(q)),J),forEachValue:$=>Ht(N,$),addSortedRowIdsListener:($,q,J,at,ut,gt,xt)=>Tn($)?Ga($.tableId,$.cellId,[$.descending??!1,$.offset??0,$.limit],q,J):Ga($,q,[J,at,ut],gt,xt),addStartTransactionListener:$=>L($,M),addWillFinishTransactionListener:$=>L($,E[0]),addDidFinishTransactionListener:$=>L($,E[1]),callListener:$=>(k($),Qt),delListener:$=>(B($),Qt),getListenerStats:()=>({hasTables:Ut(H),tables:Ut(j),tableIds:Ut(Y),hasTable:Ut(it),table:Ut(ot),tableCellIds:Ut(K),hasTableCell:Ut(z,De),rowCount:Ut(W),rowIds:Ut(X),sortedRowIds:Ut(et),hasRow:Ut(st,De),row:Ut(ct,De),cellIds:Ut(nt,De),hasCell:Ut(G,Rr),cell:Ut(A,Rr),invalidCell:Ut(_,Rr),hasValues:Ut(h),values:Ut(b),valueIds:Ut(C),hasValue:Ut(P),value:Ut(O),invalidValue:Ut(I),transaction:yi(M)+Ut(E)}),isMergeable:()=>!1,createStore:Ts,addListener:L,callListeners:U,setInternalListeners:($,q,J,at,ut)=>o=[$,q,J,at,ut]};return Me({[fi+ho]:[0,H,[],()=>[un()]],[ho]:[0,j],[rl]:[0,Y],[fi+Ye]:[1,it,[oe],$=>[Ka(...$)]],[Ye]:[1,ot,[oe]],[Ye+En]:[1,K,[oe]],[fi+Ye+As]:[2,z,[oe,qa],$=>[Ya(...$)]],[wo]:[1,W,[oe]],[xo]:[1,X,[oe]],[fi+Qi]:[2,st,[oe,Xi],$=>[Ja(...$)]],[Qi]:[2,ct,[oe,Xi]],[En]:[2,nt,[oe,Xi]],[fi+As]:[3,G,[oe,Xi,Ar],$=>[Qa(...$)]],[As]:[3,A,[oe,Xi,Ar],$=>An(hn(...$))],InvalidCell:[3,_],[fi+uo]:[0,h,[],()=>[pn()]],[uo]:[0,b],[ol]:[0,C],[fi+_n]:[1,P,[Er],$=>[Za(...$)]],[_n]:[1,O,[Er],$=>An(dn($[0]))],InvalidValue:[1,I]},(([$,q,J,at],ut)=>{Qt[Lr+ut+Ir]=(...gt)=>L(gt[$],q[gt[$+1]?1:0],$>0?Or(gt,0,$):void 0,J,at)})),is(Qt)};var jr=ft([["avg",[(n,t)=>fo(n)/t,(n,t,e)=>n+(t-n)/(e+1),(n,t,e)=>n+(n-t)/(e-1),(n,t,e,i)=>n+(t-e)/i]],["max",[n=>Pr(...n),(n,t)=>Pr(t,n),(n,t)=>t==n?void 0:n,(n,t,e)=>e==n?void 0:Pr(t,n)]],["min",[n=>Tr(...n),(n,t)=>Tr(t,n),(n,t)=>t==n?void 0:n,(n,t,e)=>e==n?void 0:Tr(t,n)]],["sum",[n=>fo(n),(n,t)=>n+t,(n,t)=>n-t,(n,t,e)=>n-e+t]]]),Do=(n,t,e,i,r,o=!1)=>{if(yt(e))return;let[g,d,m,v]=r;return o||=At(n),bt(i,(([u,a])=>{o||(n=At(u)?d?.(n,a,t++):At(a)?m?.(n,u,t--):v?.(n,a,u,t),o||=At(n))})),o?g(ts(e),es(e)):n},vd=Cs((n=>{let t=ft(),[e,i,r]=Ps((()=>y)),[o,g,d,m,v,u,a,,p,x,T,l]=Mn(n,Eo,(s=>isNaN(s)||At(s)||s===!0||s===!1||s===""?void 0:1*s),e,i),y={setMetricDefinition:(s,c,f,w,R,S,D)=>{let N=ve(f)?[f,R,S,D]:ht(jr,f)??ht(jr,"sum");return p(s,c,((H,j,Y,it,ot,K)=>{let z=u(s),W=es(it);K||=At(z),H();let X=Do(z,W,it,j,N,K);Ao(X)||(X=void 0),X!=z&&(a(s,X),i(t,[s],X,z))}),kn(w,1)),y},delMetricDefinition:s=>(x(s),y),getStore:o,getMetricIds:g,forEachMetric:d,hasMetric:m,getTableId:v,getMetric:u,addMetricIdsListener:T,addMetricListener:(s,c)=>e(c,t,[s]),delListener:s=>(r(s),y),destroy:l,getListenerStats:()=>({metric:yi(t)})};return is(y)})),wd=Cs((n=>{let t=n.createStore,e=t(),i=t(),r=ft(),{addListener:o,callListeners:g,delListener:d}=i,[m,v,u,a,p,,,x,,T,l,y,s,c]=Mn(n,(()=>!0),Eo,o,g),f=(D,N,...H)=>re(H,(j=>Nt(Lt(Lt(r,N,ft),D,jt),j))),w=D=>{Mt(ht(r,D),(N=>{Ht(N,((H,j)=>bt(j,(Y=>H.delListener(Y))))),Ji(N)})),re([i,e],(N=>N.delTable(D)))},R=(D,N,H)=>f(N,D,N.addStartTransactionListener(H.startTransaction),N.addDidFinishTransactionListener((()=>H.finishTransaction()))),S={setQueryDefinition:(D,N,H)=>{x(D,N),w(D);let j=[],Y=[[null,[N,null,null,[],ft()]]],it=[],ot=[],K=[];H({select:(nt,G)=>{let A=ve(nt)?[ce(j)+"",nt]:[At(G)?nt:G,_=>_(nt,G)];return ne(j,A),{as:_=>A[0]=_}},join:(nt,G,A)=>{let _=At(A)||ve(G)?null:G,I=At(_)?G:A,h=[nt,[nt,_,ve(I)?I:b=>b(I),[],ft()]];return ne(Y,h),{as:b=>h[0]=b}},where:(nt,G,A)=>ne(it,ve(nt)?nt:At(A)?_=>_(nt)===G:_=>_(nt,G)===A),group:(nt,G,A,_,I)=>{let h=[nt,[nt,ve(G)?[G,A,_,I]:ht(jr,G)??[(b,C)=>C]]];return ne(ot,h),{as:b=>h[0]=b}},having:(nt,G)=>ne(K,ve(nt)?nt:A=>A(nt)===G)});let z=ft(j);if(yt(z))return S;let W=ft(Y);Ht(W,((nt,[,G])=>Mt(ht(W,G),(({3:A})=>At(nt)?0:ne(A,nt)))));let X=ft(ot),et=e;if(yt(X)&&Ss(K))et=i;else{R(D,et,i);let nt=ft();Ht(X,((I,[h,b])=>Nt(Lt(nt,h,jt),[I,b])));let G=jt();Ht(z,(I=>Ft(nt,I)?0:Nt(G,I)));let A=ft(),_=(I,h,b,C)=>Mt(I,(([P,O,M,E])=>{Ht(h,((L,[U])=>{let B=Lt(P,L,ft),k=ht(B,b),F=C?void 0:U;if(k!==F){let V=jt([[k,F]]),Q=es(B);mt(B,b,F),bt(ht(nt,L),(([Z,tt])=>{let rt=Do(E[Z],Q,B,V,tt);E[Z]=At(Yi(rt))?null:rt}))}})),yt(O)||!Cn(K,(L=>L((U=>E[U]))))?i.delRow(D,M):At(M)?I[2]=i.addRow(D,E):i.setRow(D,M,E)}));f(et,D,et.addRowListener(D,null,((I,h,b,C)=>{let P=[],O=[],M=ft(),E=et.hasRow(D,b),L=!E;bt(G,(U=>{let[B,k,F]=C(D,b,U);ne(P,k),ne(O,F),L||=B})),Ht(nt,(U=>{let[B,,k]=C(D,b,U);(L||B)&&mt(M,U,[k])})),L&&_(Es(A,P,void 0,(([,U])=>(xe(U,b),yt(U)))),M,b,1),E&&_(Es(A,O,(()=>{let U={};return bt(G,(B=>U[B]=et.getCell(D,b,B))),[ft(),jt(),void 0,U]}),(([,U])=>{Nt(U,b)})),M,b)})))}R(D,n,et);let st=(nt,G,A,_)=>{let I=h=>n.getCell(G,A,h);re(_,(h=>{let[b,,C,P,O]=ht(W,h),M=C?.(I,nt),[E,L]=ht(O,nt)??[];M!=E&&(At(L)||c(D,L),mt(O,nt,At(M)?null:[M,...s(D,1,n.addRowListener(b,M,(()=>st(nt,b,M,P))))]))})),(h=>{let b=(C,P)=>n.getCell(...At(P)?[N,h,C]:C===N?[N,h,P]:[ht(W,C)?.[0],ht(ht(W,C)?.[4],h)?.[0],P]);et.transaction((()=>Cn(it,(C=>C(b)))?Ht(z,((C,P)=>Pn(et,D,h,C,P(b,h)))):et.delRow(D,h)))})(nt)},{3:ct}=ht(W,null);return et.transaction((()=>s(D,1,n.addRowListener(N,null,((nt,G,A)=>{n.hasRow(N,A)?st(A,N,A,ct):(et.delRow(D,A),bt(W,(({4:_})=>Mt(ht(_,A),(([,I])=>{c(D,I),mt(_,A)})))))}))))),S},delQueryDefinition:D=>(w(D),T(D),S),getStore:m,getQueryIds:v,forEachQuery:u,hasQuery:a,getTableId:p,addQueryIdsListener:D=>l((()=>D(S))),delListener:D=>(d(D),S),destroy:y,getListenerStats:()=>{let{tables:D,tableIds:N,transaction:H,...j}=i.getListenerStats();return j}};return Me({[Ye]:[1,1],[Ye+En]:[0,1],[wo]:[0,1],[xo]:[0,1],[al]:[0,5],[Qi]:[1,2],[En]:[0,2],[As]:[1,3]},(([D,N],H)=>{re(D?["get","has","forEach"]:["get"],(j=>S[j+lo+H]=(...Y)=>i[j+H](...Y))),S[Lr+lo+H+Ir]=(...j)=>i[Lr+H+Ir](...Or(j,0,N),((Y,...it)=>j[N](S,...it)),!0)})),is(S)})),xd=Cs((n=>{let t=ft(),e=ft(),i=ft(),r=ft(),[o,g,d]=Ps((()=>R)),[m,v,u,a,p,x,,,T,l,y,s]=Mn(n,(()=>[ft(),ft(),ft(),ft()]),(S=>At(S)?void 0:S+""),o,g),c=(S,D,N)=>Mt(x(S),(([H,,j])=>{if(!Ft(j,D)){let Y=jt();if(p(S)!=w(S))Nt(Y,D);else{let it=D;for(;!At(it)&&!Ft(Y,it);)Nt(Y,it),it=ht(H,it)}if(N)return Y;mt(j,D,Y)}return ht(j,D)})),f=(S,D)=>Mt(x(S),(([,,N])=>mt(N,D))),w=S=>ht(t,S),R={setRelationshipDefinition:(S,D,N,H)=>(mt(t,S,N),T(S,D,((j,Y)=>{let it=jt(),ot=jt(),K=jt(),[z,W]=x(S);bt(Y,(([X,et],st)=>{At(X)||(Nt(ot,X),Mt(ht(W,X),(ct=>{xe(ct,st),yt(ct)&&mt(W,X)}))),At(et)||(Nt(ot,et),Ft(W,et)||mt(W,et,jt()),Nt(ht(W,et),st)),Nt(it,st),mt(z,st,et),Ht(ht(r,S),(ct=>{Ft(c(S,ct),st)&&Nt(K,ct)}))})),j(),bt(it,(X=>g(e,[S,X]))),bt(ot,(X=>g(i,[S,X]))),bt(K,(X=>{f(S,X),g(r,[S,X])}))}),kn(H)),R),delRelationshipDefinition:S=>(mt(t,S),l(S),R),getStore:m,getRelationshipIds:v,forEachRelationship:S=>u((D=>S(D,(N=>n.forEachRow(p(D),N))))),hasRelationship:a,getLocalTableId:p,getRemoteTableId:w,getRemoteRowId:(S,D)=>ht(x(S)?.[0],D),getLocalRowIds:(S,D)=>ts(ht(x(S)?.[1],D)),getLinkedRowIds:(S,D)=>At(x(S))?[D]:ts(c(S,D,!0)),addRelationshipIdsListener:y,addRemoteRowIdListener:(S,D,N)=>o(N,e,[S,D]),addLocalRowIdsListener:(S,D,N)=>o(N,i,[S,D]),addLinkedRowIdsListener:(S,D,N)=>(c(S,D),o(N,r,[S,D])),delListener:S=>(f(...d(S)??[]),R),destroy:s,getListenerStats:()=>({remoteRowId:De(e),localRowIds:De(i),linkedRowIds:De(r)})};return is(R)}));var Fo=Promise,yl=globalThis,Io=yl.window,vl=1e3,wl=(n,t,e)=>setInterval(n,t*vl),xl=clearInterval,Ae=n=>n==null,On=(n,t,e)=>Ae(n)?e?.():t(n),Wr=n=>Array.isArray(n),wi=n=>n.length,Al=(n,t)=>n.test(t),Oo=n=>new Fo(n),No=async n=>Fo.all(n),Bo=n=>{throw new Error(n)},vi=async(n,t,e)=>{try{return await n()}catch(i){t?.(i)}},Gr=(n,t)=>n.forEach(t),ks=(n,t)=>n.map(t),Sl=(n,t)=>n.splice(0,t),Nn=(n,...t)=>n.push(...t),Uo=n=>n.shift(),ss=Object,Lo=n=>ss.getPrototypeOf(n),El=ss.entries,_l=n=>!Ae(n)&&On(Lo(n),t=>t==ss.prototype||Ae(Lo(t)),()=>!0),Cl=ss.keys,Pl=ss.freeze,Tl=(n=[])=>ss.fromEntries(n),kl=(n,t)=>t in n,Rl=(n,t)=>ks(El(n),([e,i])=>t(i,e)),Ml=n=>wi(Cl(n)),Dn=n=>_l(n)&&Ml(n)==0,Dl=n=>n?.size??0,Il=(n,t)=>n?.has(t)??!1,$o=n=>Ae(n)||Dl(n)==0,Ho=(n,t)=>n?.forEach(t),jo=(n,t)=>n?.delete(t),Rs=n=>new Map(n),fe=(n,t)=>n?.get(t),xi=(n,t,e)=>Ae(e)?(jo(n,t),n):n?.set(t,e),qr=(n,t,e,i)=>(Il(n,t)?i?.(fe(n,t)):xi(n,t,e()),fe(n,t)),Xr=(n,t,e,i,r=0)=>On((e?qr:fe)(n,t[r],r>wi(t)-2?e:Rs),o=>{if(r>wi(t)-2)return i?.(o)&&xi(n,t[r]),o;let g=Xr(o,t,e,i,r+1);return $o(o)&&xi(n,t[r]),g}),Ll=/^\d+$/,Fl=()=>{let n=[],t=0;return[e=>(e?Uo(n):null)??""+t++,e=>{Al(Ll,e)&&wi(n)<1e3&&Nn(n,e)}]},Ol=n=>new Set(Wr(n)||Ae(n)?n:[n]),Nl=(n,t)=>n?.add(t),Bl=(n,t=[""])=>{let e=[],i=(r,o)=>o==wi(t)?Nn(e,r):t[o]===null?Ho(r,g=>i(g,o+1)):Gr([t[o],null],g=>i(fe(r,g),o+1));return i(n,0),e},Ul=n=>{let t,[e,i]=Fl(),r=Rs();return[(o,g,d,m=[],v=()=>[])=>{t??=n();let u=e(1);return xi(r,u,[o,g,d,m,v]),Nl(Xr(g,d??[""],Ol),u),u},(o,g,...d)=>Gr(Bl(o,g),m=>Ho(m,v=>fe(r,v)[0](t,...g??[],...d))),o=>On(fe(r,o),([,g,d])=>(Xr(g,d??[""],void 0,m=>(jo(m,o),$o(m)?1:0)),xi(r,o),i(o),d)),o=>On(fe(r,o),([g,,d=[],m,v])=>{let u=(...a)=>{let p=wi(a);p==wi(d)?g(t,...a,...v(a)):Ae(d[p])?Gr(m[p]?.(...a)??[],x=>u(...a,x)):u(...a,d[p])};u()})]},In=Rs(),Ln=Rs(),$l=(n=1,t,e)=>n!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[r]])=>!Dn(i)||!Dn(r),t.setDefaultContent]:n!=2?[0,t.getContent,t.getTransactionChanges,([i,r])=>!Dn(i)||!Dn(r),t.setContent]:Bo("Store type not supported by this Persister"),Hl=(n,t,e,i,r,o,g,d={},m=0,v=[])=>{let u=0,a=0,p=0,x,T,l;qr(In,v,()=>0),qr(Ln,v,()=>[]);let y=Rs(),[s,c,f,w,R]=$l(g,n,m),[S,D,N]=Ul(()=>h),H=b=>{b!=u&&(u=b,D(y,void 0,u))},j=async()=>{if(!fe(In,v)){for(xi(In,v,1);!Ae(x=Uo(fe(Ln,v)));)await vi(x,o);xi(In,v,0)}},Y=b=>{(s&&Wr(b?.[0])?b?.[2]===1?n.applyMergeableChanges:n.setMergeableContent:b?.[2]===1?n.applyChanges:n.setContent)(b)},it=async b=>(u!=2&&(H(1),a++,await I(async()=>{await vi(async()=>{let C=await t();Wr(C)?Y(C):b?R(b):Bo(`Content is not an array: ${C}`)},()=>{b&&R(b)}),H(0)})),h),ot=async b=>(K(),await it(b),await vi(async()=>T=await i(async(C,P)=>{P||C?u!=2&&(H(1),a++,Y(P??C),H(0)):await it()}),o),h),K=async()=>(T&&(await vi(()=>r(T),o),T=void 0),h),z=()=>!Ae(T),W=async b=>(u!=1&&(H(2),p++,await I(async()=>{await vi(()=>e(c,b),o),H(0)})),h),X=async()=>(et(),await W(),l=n.addDidFinishTransactionListener(()=>{let b=f();w(b)&&W(b)}),h),et=async()=>(l&&(n.delListener(l),l=void 0),h),st=()=>!Ae(l),ct=async(b,C=!1)=>{let[P,O]=C?[X,ot]:[ot,X];return await P(b),await O(b),h},nt=async(b=!1)=>{let[C,P]=b?[et,K]:[K,et];return await C(),await P(),h},G=()=>u,A=b=>S(b,y),_=b=>(N(b),n),I=async(...b)=>(Nn(fe(Ln,v),...b),await j(),h),h={load:it,startAutoLoad:ot,stopAutoLoad:K,isAutoLoading:z,save:W,startAutoSave:X,stopAutoSave:et,isAutoSaving:st,startAutoPersisting:ct,stopAutoPersisting:nt,getStatus:G,addStatusListener:A,delListener:_,schedule:I,getStore:()=>n,destroy:()=>(Sl(fe(Ln,v)),nt()),getStats:()=>({loads:a,saves:p}),...d};return Pl(h)},Vr=["t","v"],jl={keyPath:"k"},zl=async(n,t)=>{let e=Rl(t,(i,r)=>Fn(n,"put",{k:r,v:i}));ks(await Fn(n,"getAllKeys"),i=>kl(t,i)?0:Nn(e,Fn(n,"delete",i))),await No(e)},Fn=async(n,t,e)=>Oo((i,r)=>{let o=n[t](e);o.onsuccess=()=>i(o.result),o.onerror=()=>r(`objectStore.${t} error`)}),zo=(n,t,e=1,i)=>{let r=async(o,g=[],d=0)=>Oo((m,v)=>{let u=(Io?Io.indexedDB:indexedDB).open(t,d?2:void 0);u.onupgradeneeded=()=>d&&ks(Vr,a=>vi(()=>u.result.createObjectStore(a,jl))),u.onsuccess=()=>vi(async()=>{let a=u.result.transaction(Vr,"readwrite"),p=await No(ks(Vr,(x,T)=>o(a.objectStore(x),g[T])));u.result.close(),m(p)},a=>{u.result.close(),v(a)}),u.onerror=()=>v("indexedDB.open error")});return Hl(n,async()=>await r(async o=>Tl(ks(await Fn(o,"getAll"),({k:g,v:d})=>[g,d]))),o=>r((g,d)=>zl(g,d),o(),1),o=>wl(o,e),o=>xl(o),i,1,{getDbName:()=>t})};var Bn=class{#t;#e="blobs";#i=null;constructor(t="copio-blobs"){this.#t=t}async#n(){return this.#i?this.#i:(this.#i=new Promise((t,e)=>{if(typeof indexedDB>"u"){e(new Error("IndexedDB is not available"));return}let i=indexedDB.open(this.#t,1);i.onupgradeneeded=()=>{let r=i.result;r.objectStoreNames.contains(this.#e)||r.createObjectStore(this.#e)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error||new Error("Failed to open blob db"))}),this.#i)}async put(t,e){let i=await this.#n();return new Promise((r,o)=>{let m=i.transaction(this.#e,"readwrite").objectStore(this.#e).put(e,t);m.onsuccess=()=>r(),m.onerror=()=>o(m.error)})}async get(t){let e=await this.#n();return new Promise((i,r)=>{let d=e.transaction(this.#e,"readonly").objectStore(this.#e).get(t);d.onsuccess=()=>i(d.result||null),d.onerror=()=>r(d.error)})}async delete(t){let e=await this.#n();return new Promise((i,r)=>{let d=e.transaction(this.#e,"readwrite").objectStore(this.#e).delete(t);d.onsuccess=()=>i(),d.onerror=()=>r(d.error)})}async deleteByPrefix(t){let e=await this.#n();return new Promise((i,r)=>{let g=e.transaction(this.#e,"readwrite").objectStore(this.#e),d=g.openKeyCursor();d.onsuccess=m=>{let v=m.target.result;v?(typeof v.key=="string"&&v.key.startsWith(t)&&g.delete(v.key),v.continue()):i()},d.onerror=()=>r(d.error)})}async sweepOrphans(t){let e=new Set(t),i=await this.#n(),r=0;return new Promise((o,g)=>{let m=i.transaction(this.#e,"readwrite").objectStore(this.#e),v=m.openKeyCursor();v.onsuccess=u=>{let a=u.target.result;if(a){if(typeof a.key=="string"){let p=a.key.split(":")[0];e.has(p)||(m.delete(a.key),r++)}a.continue()}else o(r)},v.onerror=()=>g(v.error)})}async close(){if(this.#i){try{(await this.#i).close()}catch{}this.#i=null}}};function Ai(n,t="image/jpeg"){if(n instanceof Blob)return n;if(typeof n!="string"||!n.startsWith("data:"))return null;let e=n.match(/^data:([^;]+);base64,(.*)$/),i=e?e[1]:t,r=e?e[2]:n.split(",")[1],o=atob(r),g=new Uint8Array(o.length);for(let d=0;d<o.length;d++)g[d]=o.charCodeAt(d);return new Blob([g],{type:i})}async function Kr(n){return new Promise((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=e,i.readAsDataURL(n)})}var Se=class extends he{#t=null;#e=null;#i=null;#n="copio-db";#r=!1;#s=new Set;#o=new Map;#c=new Map;#a=new Map;#h=new Map;#u=null;constructor(t={}){super(),this.#n=t.dbName||"copio-db",t.dbName&&t.dbName!=="copio-db"&&(this.#r=!0),this.#t=t.store||Ts(),this.#t.hasTable("docs")||this.#t.setTable("docs",{}),this.#e=t.persister||zo(this.#t,this.#n),this.#i=new Bn(`${this.#n}-blobs`)}get store(){return this.#t}get persister(){return this.#e}get blobStore(){return this.#i}#d(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#s.add(e),this.#o.has(t)||this.#o.set(t,[]),this.#o.get(t).push(e)),e}revokeDocUrls(t){let e=this.#o.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#s.delete(i)}this.#o.delete(t)}for(let[i,r]of this.#c.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#c.delete(i)}for(let[i,r]of this.#a.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#a.delete(i)}this.#h.delete(t)}revokeAllUrls(){for(let t of this.#s)try{URL.revokeObjectURL(t)}catch{}this.#s.clear(),this.#o.clear(),this.#c.clear(),this.#a.clear(),this.#h.clear()}async init(){return this.#u?this.#u:(this.#u=(async()=>{this.#r?(await this.#e.load(),this.#e.startAutoLoad(),this.#e.startAutoSave()):await this.#e.load(),await this.sweepOrphans();let t=!0;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{t=await navigator.storage.persisted()}catch{}return{kind:"indexeddb",persistent:t}})(),this.#u)}async sweepOrphans(){let t=Object.keys(this.#t.getTable("docs")||{});return this.#i.sweepOrphans(t)}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#l(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(this.#h.has(t))return this.#h.get(t);if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#l(e.pages)}}async getDoc(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t),i=this.#l(e.pages),r=await Promise.all(i.map(async g=>{if(!g)return g;let d={...g},m=`${t}:${g.id}`,v=await this.#i.get(`${t}:${g.id}`);v&&(d.blob=v,this.#c.has(m)?d.src=this.#c.get(m):(d.src=this.#d(t,URL.createObjectURL(v)),this.#c.set(m,d.src)));let u=`${t}:${g.id}:orig`,a=await this.#i.get(`${t}:${g.id}:original`);return a?(d.originalBlob=a,this.#a.has(u)?d.originalSrc=this.#a.get(u):(d.originalSrc=this.#d(t,URL.createObjectURL(a)),this.#a.set(u,d.originalSrc))):d.blob&&(d.originalBlob=d.blob,d.originalSrc=d.src),d})),o={id:t,name:e.name||"",pages:r};return this.#h.set(t,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#l(e.pages),r=[],o=[],g=[];for(let d of i){if(!d)continue;let m=Ai(d.src)||(d.src instanceof Blob?d.src:null)||(d.blob instanceof Blob?d.blob:null),v=m?.type||"image/jpeg",u={id:d.id,name:d.name||"",type:d.type||"image",hasBlob:!0,mimeType:v,edits:d.edits,exif:d.exif,content:d.content,ocrText:d.ocrText??null,ocrConfidence:d.ocrConfidence??null,ocrWords:Array.isArray(d.ocrWords)?d.ocrWords:null,ocrWidth:d.ocrWidth??null,ocrHeight:d.ocrHeight??null};r.push(u);let a=`${t}:${d.id}`,p=`${t}:${d.id}:orig`,x={...d},T=this.#c.get(a),l=typeof d.src=="string"&&d.src.startsWith("data:")||d.src instanceof Blob||d.src&&T&&d.src!==T;if(m)if(x.blob=m,l||!T){if(T){try{URL.revokeObjectURL(T)}catch{}this.#s.delete(T)}let w=this.#d(t,URL.createObjectURL(m));this.#c.set(a,w),x.src=w}else x.src=T;let y=Ai(d.originalSrc)||(d.originalSrc instanceof Blob?d.originalSrc:null)||(d.originalBlob instanceof Blob?d.originalBlob:null),s=this.#a.get(p),c=!s&&!y&&(!d.originalSrc||d.originalSrc===d.src);c&&m&&(y=m);let f=typeof d.originalSrc=="string"&&d.originalSrc.startsWith("data:")||d.originalSrc instanceof Blob||c&&!!y;if(y)if(x.originalBlob=y,f||!s){if(s&&f){try{URL.revokeObjectURL(s)}catch{}this.#s.delete(s)}let w=this.#d(t,URL.createObjectURL(y));this.#a.set(p,w),x.originalSrc=w}else x.originalSrc=s;else s?x.originalSrc=s:d.originalSrc?x.originalSrc=d.originalSrc:(x.originalSrc=x.src,x.blob&&(x.originalBlob=x.blob));o.push(x),g.push({pageId:d.id,page:d,srcBlob:m,origBlob:y})}this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(r)}),this.#h.set(t,{id:t,name:e.name||"",pages:o});for(let d of g){let{pageId:m,page:v,srcBlob:u,origBlob:a}=d;if(!u&&typeof v.src=="string"&&v.src.startsWith("blob:"))try{u=await(await fetch(v.src)).blob()}catch{}if(u&&await this.#i.put(`${t}:${m}`,u),!a&&typeof v.originalSrc=="string"&&v.originalSrc.startsWith("blob:"))try{a=await(await fetch(v.originalSrc)).blob()}catch{}a&&await this.#i.put(`${t}:${m}:original`,a)}}async deleteDoc(t){this.#t.delRow("docs",t),await this.#i.deleteByPrefix(`${t}:`),this.revokeDocUrls(t),this.#h.delete(t)}async renameDoc(t,e){if(!this.#t.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#t.setCell("docs",t,"name",e),this.#h.has(t)&&(this.#h.get(t).name=e)}async savePage(t,e,i){let r=await this.getDoc(t);if(!r)throw new Error(`Document ${t} not found`);let o=r.pages.findIndex(m=>m.id===e),g;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i,blob:i instanceof Blob?i:void 0},g=r.pages[o];else{let m=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};r.pages.push(m),g=m}let d=Ai(g.src)||(g.src instanceof Blob?g.src:null)||(g.blob instanceof Blob?g.blob:null);if(!d&&typeof g.src=="string"&&g.src.startsWith("blob:"))try{d=await(await fetch(g.src)).blob()}catch{}d&&await this.#i.put(`${t}:${e}`,d),await this.saveDoc(t,r)}async getPage(t,e){let i=await this.#i.get(`${t}:${e}`);if(i)return i;let r=this.getDocSync(t);if(!r)return null;let o=r.pages.find(g=>g.id===e);return o?o.content??o.src??o:null}async deletePage(t,e){let i=this.getDocSync(t);if(!i)return;i.pages=i.pages.filter(g=>g.id!==e),this.#t.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),await this.#i.delete(`${t}:${e}`),await this.#i.delete(`${t}:${e}:original`);let r=`${t}:${e}`;if(this.#c.has(r)){try{URL.revokeObjectURL(this.#c.get(r))}catch{}this.#c.delete(r)}let o=`${t}:${e}:orig`;if(this.#a.has(o)){try{URL.revokeObjectURL(this.#a.get(o))}catch{}this.#a.delete(o)}this.#h.delete(t)}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#l(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};async function Un(){if(typeof location<"u"&&location.search&&(new URLSearchParams(location.search).has("no-opfs")||new URLSearchParams(location.search).get("storage")==="indexeddb")||typeof navigator>"u"||!navigator.storage||typeof navigator.storage.getDirectory!="function")return!1;try{let n=await navigator.storage.getDirectory();if(!n)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,e=await n.getFileHandle(t,{create:!0}),i=await e.createWritable();if(await i.write(new Uint8Array([1,2,3,4])),await i.close(),(await e.getFile()).size!==4)throw new Error("OPFS probe size mismatch");return await n.removeEntry(t),!0}catch{return!1}}function Vl(n,t,e="store.json"){let i=0,r=null,o=Promise.resolve(),g=0,d=()=>typeof t=="function"?t():t,m=async()=>{await o;let p=d();if(p){i=1;try{let l=await(await(await p.getFileHandle(e)).getFile()).text();l&&l.trim().length>0&&n.setJson(l)}catch{}finally{i=0}}},v=()=>{let p=d();return p?(g++,i=2,o=o.catch(()=>{}).then(async()=>{try{let x=n.getJson(),l=await(await p.getFileHandle(e,{create:!0})).createWritable();await l.write(x),await l.close()}catch(x){console.warn("[OpfsPersister] Failed to save store.json:",x)}finally{g--,g<=0&&(g=0,i=0)}}),o):Promise.resolve()};return{load:m,save:v,startAutoSave:()=>{r||(r=n.addDidFinishTransactionListener(()=>{v()}))},stopAutoSave:()=>{r&&(n.delListener(r),r=null)},getStatus:()=>i,getStore:()=>n}}async function Vo(n){let t=[];try{if(typeof n.entries=="function")for await(let e of n.entries())t.push(e);else if(typeof n.values=="function")for await(let e of n.values())t.push([e.name,e])}catch(e){console.warn("[OpfsAdapter] Error reading directory entries:",e)}return t}var Si=class extends he{#t;#e="copio";#i=null;#n=null;#r=null;#s=null;#o=null;#c=!1;#a=null;#h=new Set;#u=new Map;#d=new Map;#l=new Map;#f=new Map;#g=null;constructor(t={}){super(),this.#t=t,this.#e=t.dirName||"copio",t.store?this.#s=t.store:(this.#s=Ts(),this.#s.setTable("docs",{})),this.#o=t.persister||Vl(this.#s,()=>this.#n,"store.json")}get store(){return this.#c?this.#a?.store:this.#s}get persister(){return this.#c?this.#a?.persister:this.#o}get isFallback(){return this.#c}get fallbackAdapter(){return this.#a}async#p(){if(this.#c)return!1;if(this.#r&&this.#n)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#i=await navigator.storage.getDirectory(),this.#n=await this.#i.getDirectoryHandle(this.#e,{create:!0}),this.#r=await this.#n.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#m(),!1}else return await this.#m(),!1}#y(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#h.add(e),this.#u.has(t)||this.#u.set(t,[]),this.#u.get(t).push(e)),e}revokeDocUrls(t){if(this.#c){this.#a?.revokeDocUrls(t);return}let e=this.#u.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#h.delete(i)}this.#u.delete(t)}for(let[i,r]of this.#d.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#d.delete(i)}for(let[i,r]of this.#l.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#l.delete(i)}this.#f.delete(t)}revokeAllUrls(){if(this.#c){this.#a?.revokeAllUrls();return}for(let t of this.#h)try{URL.revokeObjectURL(t)}catch{}this.#h.clear(),this.#u.clear(),this.#d.clear(),this.#l.clear(),this.#f.clear()}async init(){return this.#g?this.#g:(this.#g=(async()=>{if(this.#t.forceFallback)return this.#m();if(!await Un())return this.#m();try{await this.#p(),await this.#o.load(),this.#o.startAutoSave(),await this.sweepOrphans();let e=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:e}}catch(e){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",e),this.#m()}})(),this.#g)}async#m(){return this.#c=!0,this.#a=new Se(this.#t),{kind:"indexeddb",persistent:(await this.#a.init()).persistent}}async sweepOrphans(){if(this.#c)return this.#a?.sweepOrphans();if(await this.#p(),!this.#r)return 0;let t=0,e=this.#s.getTable("docs")||{},i=new Set(Object.keys(e)),r=new Map;for(let[g,d]of Object.entries(e)){let m=this.#b(d.pages);r.set(g,new Set(m.map(v=>v.id)))}let o=await Vo(this.#r);for(let[g,d]of o)if(d.kind==="directory")if(i.has(g)){let m=r.get(g)||new Set,v=d,u=await Vo(v);for(let[a]of u){let p=a.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!m.has(p))try{await v.removeEntry(a),t++}catch{}}}else try{await this.#r.removeEntry(g,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#c)return this.#a?.listDocsSync();let t=this.#s.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#b(i.pages)}))}async listDocs(){return this.#c?this.#a?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#c)return this.#a?.getDocSync(t);if(this.#f.has(t))return this.#f.get(t);if(!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#b(e.pages)}}async getDoc(t){if(this.#c)return this.#a?.getDoc(t);if(await this.#p(),!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t),i=this.#b(e.pages),r=null;if(this.#r)try{r=await this.#r.getDirectoryHandle(t)}catch{}let o=await Promise.all(i.map(async d=>{if(!d||!r)return d;let m={...d},v=`${t}:${d.id}`;try{let p=await(await r.getFileHandle(`${d.id}.bin`)).getFile();m.blob=p,this.#d.has(v)?m.src=this.#d.get(v):(m.src=this.#y(t,URL.createObjectURL(p)),this.#d.set(v,m.src))}catch{}let u=`${t}:${d.id}:orig`;try{let p=await(await r.getFileHandle(`${d.id}-original.bin`)).getFile();m.originalBlob=p,this.#l.has(u)?m.originalSrc=this.#l.get(u):(m.originalSrc=this.#y(t,URL.createObjectURL(p)),this.#l.set(u,m.originalSrc))}catch{m.blob&&(m.originalBlob=m.blob,m.originalSrc=m.src)}return m})),g={id:t,name:e.name||"",pages:o};return this.#f.set(t,g),g}async saveDoc(t,e){if(this.#c)return this.#a?.saveDoc(t,e);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#b(e.pages),r=[],o=[],g=[];for(let m of i){if(!m)continue;let v=Ai(m.src)||(m.src instanceof Blob?m.src:null)||(m.blob instanceof Blob?m.blob:null),u=v?.type||"image/jpeg",a={id:m.id,name:m.name||"",type:m.type||"image",hasBlob:!0,mimeType:u,edits:m.edits,exif:m.exif,content:m.content,ocrText:m.ocrText??null,ocrConfidence:m.ocrConfidence??null,ocrWords:Array.isArray(m.ocrWords)?m.ocrWords:null,ocrWidth:m.ocrWidth??null,ocrHeight:m.ocrHeight??null};r.push(a);let p=`${t}:${m.id}`,x=`${t}:${m.id}:orig`,T={...m},l=this.#d.get(p),y=typeof m.src=="string"&&m.src.startsWith("data:")||m.src instanceof Blob||m.src&&l&&m.src!==l;if(v)if(T.blob=v,y||!l){if(l){try{URL.revokeObjectURL(l)}catch{}this.#h.delete(l)}let R=this.#y(t,URL.createObjectURL(v));this.#d.set(p,R),T.src=R}else T.src=l;let s=Ai(m.originalSrc)||(m.originalSrc instanceof Blob?m.originalSrc:null)||(m.originalBlob instanceof Blob?m.originalBlob:null),c=this.#l.get(x),f=!c&&!s&&(!m.originalSrc||m.originalSrc===m.src);f&&v&&(s=v);let w=typeof m.originalSrc=="string"&&m.originalSrc.startsWith("data:")||m.originalSrc instanceof Blob||f&&!!s;if(s)if(T.originalBlob=s,w||!c){if(c&&w){try{URL.revokeObjectURL(c)}catch{}this.#h.delete(c)}let R=this.#y(t,URL.createObjectURL(s));this.#l.set(x,R),T.originalSrc=R}else T.originalSrc=c;else c?T.originalSrc=c:m.originalSrc?T.originalSrc=m.originalSrc:(T.originalSrc=T.src,T.blob&&(T.originalBlob=T.blob));o.push(T),g.push({pageId:m.id,page:m,srcBlob:v,origBlob:s})}if(this.#s.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(r)}),this.#f.set(t,{id:t,name:e.name||"",pages:o}),await this.#p(),this.#c)return this.#a?.saveDoc(t,e);let d=null;if(this.#r)try{d=await this.#r.getDirectoryHandle(t,{create:!0})}catch(m){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,m)}if(d)for(let m of g){let{pageId:v,page:u,srcBlob:a,origBlob:p}=m;if(!a&&typeof u.src=="string"&&u.src.startsWith("blob:"))try{a=await(await fetch(u.src)).blob()}catch{}if(a)try{let T=await(await d.getFileHandle(`${v}.bin`,{create:!0})).createWritable();await T.write(a),await T.close()}catch(x){console.warn(`[OpfsAdapter] Failed writing page file "${v}.bin":`,x)}if(!p&&typeof u.originalSrc=="string"&&u.originalSrc.startsWith("blob:"))try{p=await(await fetch(u.originalSrc)).blob()}catch{}if(p)try{let T=await(await d.getFileHandle(`${v}-original.bin`,{create:!0})).createWritable();await T.write(p),await T.close()}catch{}}}async deleteDoc(t){if(this.#c)return this.#a?.deleteDoc(t);if(this.#s.delRow("docs",t),this.#f.delete(t),this.revokeDocUrls(t),await this.#p(),this.#r)try{await this.#r.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,e){if(this.#c)return this.#a?.renameDoc(t,e);if(!this.#s.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#s.setCell("docs",t,"name",e),this.#f.has(t)&&(this.#f.get(t).name=e)}async savePage(t,e,i){if(this.#c)return this.#a?.savePage(t,e,i);await this.#p();let r=await this.getDoc(t);if(!r)throw new Error(`Document ${t} not found`);let o=r.pages.findIndex(m=>m.id===e),g;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i,blob:i instanceof Blob?i:void 0},g=r.pages[o];else{let m=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};r.pages.push(m),g=m}let d=Ai(g.src)||(g.src instanceof Blob?g.src:null)||(g.blob instanceof Blob?g.blob:null);if(!d&&typeof g.src=="string"&&g.src.startsWith("blob:"))try{d=await(await fetch(g.src)).blob()}catch{}if(d&&this.#r)try{let u=await(await(await this.#r.getDirectoryHandle(t,{create:!0})).getFileHandle(`${e}.bin`,{create:!0})).createWritable();await u.write(d),await u.close()}catch(m){console.warn(`[OpfsAdapter] Failed writing page file "${e}.bin":`,m)}await this.saveDoc(t,r)}async getPage(t,e){if(this.#c)return this.#a?.getPage(t,e);if(await this.#p(),this.#r)try{return await(await(await this.#r.getDirectoryHandle(t)).getFileHandle(`${e}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let r=i.pages.find(o=>o.id===e);return r?r.content??r.src??r:null}async deletePage(t,e){if(this.#c)return this.#a?.deletePage(t,e);await this.#p();let i=this.getDocSync(t);if(!i)return;if(i.pages=i.pages.filter(g=>g.id!==e),this.#s.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),this.#r){try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}.bin`)}catch{}try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}-original.bin`)}catch{}}let r=`${t}:${e}`;if(this.#d.has(r)){try{URL.revokeObjectURL(this.#d.get(r))}catch{}this.#d.delete(r)}let o=`${t}:${e}:orig`;if(this.#l.has(o)){try{URL.revokeObjectURL(this.#l.get(o))}catch{}this.#l.delete(o)}this.#f.delete(t)}subscribe(t){if(this.#c)return this.#a?.subscribe(t);let e=this.#s.addTableListener("docs",t);return()=>{this.#s.delListener(e)}}#b(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function ns(n={}){return n.forceMemory?new qe:n.forceIndexedDb?new Se(n):n.forceOpfs?new Si(n):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new Si(n):typeof indexedDB<"u"?new Se(n):new qe}function kt(n,t,e){return t in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}var la=typeof self<"u"?self:global,Fs=typeof navigator<"u",Wl=Fs&&typeof HTMLImageElement>"u",Wo=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),ha=la.Buffer,$n=la.BigInt,da=!!ha,Hn=n=>sc(n)?void 0:n,Gl=n=>n!==void 0;function sc(n){return n===void 0||(n instanceof Map?n.size===0:Object.values(n).filter(Gl).length===0)}function qt(n){let t=new Error(n);throw delete t.stack,t}function nc(n){return(n=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(n).trim())===""?void 0:n}function Go(n){let t=(function(e){let i=0;return e.ifd0.enabled&&(i+=1024),e.exif.enabled&&(i+=2048),e.makerNote&&(i+=2048),e.userComment&&(i+=1024),e.gps.enabled&&(i+=512),e.interop.enabled&&(i+=100),e.ifd1.enabled&&(i+=1024),i+2048})(n);return n.jfif.enabled&&(t+=50),n.xmp.enabled&&(t+=2e4),n.iptc.enabled&&(t+=14e3),n.icc.enabled&&(t+=6e3),t}var Zr=n=>String.fromCharCode.apply(null,n),qo=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function rc(n){return qo?qo.decode(n):da?Buffer.from(n).toString("utf8"):decodeURIComponent(escape(Zr(n)))}var Fe=class n{static from(t,e){return t instanceof this&&t.le===e?t:new n(t,void 0,void 0,e)}constructor(t,e=0,i,r){if(typeof r=="boolean"&&(this.le=r),Array.isArray(t)&&(t=new Uint8Array(t)),t===0)this.byteOffset=0,this.byteLength=0;else if(t instanceof ArrayBuffer){i===void 0&&(i=t.byteLength-e);let o=new DataView(t,e,i);this._swapDataView(o)}else if(t instanceof Uint8Array||t instanceof DataView||t instanceof n){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&qt("Creating view outside of available memory in ArrayBuffer");let o=new DataView(t.buffer,e,i);this._swapDataView(o)}else if(typeof t=="number"){let o=new DataView(new ArrayBuffer(t));this._swapDataView(o)}else qt("Invalid input argument for BufferView: "+t)}_swapArrayBuffer(t){this._swapDataView(new DataView(t))}_swapBuffer(t){this._swapDataView(new DataView(t.buffer,t.byteOffset,t.byteLength))}_swapDataView(t){this.dataView=t,this.buffer=t.buffer,this.byteOffset=t.byteOffset,this.byteLength=t.byteLength}_lengthToEnd(t){return this.byteLength-t}set(t,e,i=n){return t instanceof DataView||t instanceof n?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||qt("BufferView.set(): Invalid data argument."),this.toUint8().set(t,e),new i(this,e,t.byteLength)}subarray(t,e){return e=e||this._lengthToEnd(t),new n(this,t,e)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(t,e){return new Uint8Array(this.buffer,this.byteOffset+t,e)}getString(t=0,e=this.byteLength){return rc(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return Zr(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let r=0;r<e&&t+r<this.byteLength;r+=2)i.push(this.getUint16(t+r));return Zr(i)}getInt8(t){return this.dataView.getInt8(t)}getUint8(t){return this.dataView.getUint8(t)}getInt16(t,e=this.le){return this.dataView.getInt16(t,e)}getInt32(t,e=this.le){return this.dataView.getInt32(t,e)}getUint16(t,e=this.le){return this.dataView.getUint16(t,e)}getUint32(t,e=this.le){return this.dataView.getUint32(t,e)}getFloat32(t,e=this.le){return this.dataView.getFloat32(t,e)}getFloat64(t,e=this.le){return this.dataView.getFloat64(t,e)}getFloat(t,e=this.le){return this.dataView.getFloat32(t,e)}getDouble(t,e=this.le){return this.dataView.getFloat64(t,e)}getUintBytes(t,e,i){switch(e){case 1:return this.getUint8(t,i);case 2:return this.getUint16(t,i);case 4:return this.getUint32(t,i);case 8:return this.getUint64&&this.getUint64(t,i)}}getUint(t,e,i){switch(e){case 8:return this.getUint8(t,i);case 16:return this.getUint16(t,i);case 32:return this.getUint32(t,i);case 64:return this.getUint64&&this.getUint64(t,i)}}toString(t){return this.dataView.toString(t,this.constructor.name)}ensureChunk(){}};function ta(n,t){qt(`${n} '${t}' was not loaded, try using full build of exifr.`)}var Os=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||ta(this.kind,t),e&&(t in e||(function(i,r){qt(`Unknown ${i} '${r}'.`)})(this.kind,t),e[t].enabled||ta(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},Ri=new Os("file parser"),ie=new Os("segment parser"),Mi=new Os("file reader"),ac=la.fetch;function Xo(n,t){return(e=n).startsWith("data:")||e.length>1e4?ia(n,t,"base64"):Wo&&n.includes("://")?ea(n,t,"url",os):Wo?ia(n,t,"fs"):Fs?ea(n,t,"url",os):void qt("Invalid input argument");var e}async function ea(n,t,e,i){return Mi.has(e)?ia(n,t,e):i?(async function(r,o){let g=await o(r);return new Fe(g)})(n,i):void qt(`Parser ${e} is not loaded`)}async function ia(n,t,e){let i=new(Mi.get(e))(n,t);return await i.read(),i}var os=n=>ac(n).then((t=>t.arrayBuffer())),cs=n=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(n)})),sa=class extends Map{get tagKeys(){return this.allKeys||(this.allKeys=Array.from(this.keys())),this.allKeys}get tagValues(){return this.allValues||(this.allValues=Array.from(this.values())),this.allValues}};function ge(n,t,e){let i=new sa;for(let[r,o]of e)i.set(r,o);if(Array.isArray(t))for(let r of t)n.set(r,i);else n.set(t,i);return i}function ua(n,t,e){let i,r=n.get(t);for(i of e)r.set(i[0],i[1])}var Le=new Map,hs=new Map,ki=new Map,_i=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],Ns=["jfif","xmp","icc","iptc","ihdr"],ls=["tiff",...Ns],zt=["ifd0","ifd1","exif","gps","interop"],Ci=[...ls,...zt],Pi=["makerNote","userComment"],Bs=["translateKeys","translateValues","reviveValues","multiSegment"],Ti=[...Bs,"sanitize","mergeOutput","silentErrors"],jn=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},Ei=class extends jn{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,r){if(super(),kt(this,"enabled",!1),kt(this,"skip",new Set),kt(this,"pick",new Set),kt(this,"deps",new Set),kt(this,"translateKeys",!1),kt(this,"translateValues",!1),kt(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(r),this.canBeFiltered=zt.includes(t),this.canBeFiltered&&(this.dict=Le.get(t)),i!==void 0)if(Array.isArray(i))this.parse=this.enabled=!0,this.canBeFiltered&&i.length>0&&this.translateTagSet(i,this.pick);else if(typeof i=="object"){if(this.enabled=!0,this.parse=i.parse!==!1,this.canBeFiltered){let{pick:o,skip:g}=i;o&&o.length>0&&this.translateTagSet(o,this.pick),g&&g.length>0&&this.translateTagSet(g,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:qt(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of Bs)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,r,{tagKeys:o,tagValues:g}=this.dict;for(i of t)typeof i=="string"?(r=g.indexOf(i),r===-1&&(r=o.indexOf(Number(i))),r!==-1&&e.add(Number(o[r]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,zn(this.pick,this.deps)):this.enabled&&this.pick.size>0&&zn(this.pick,this.deps)}},ee={jfif:!1,tiff:!0,xmp:!1,icc:!1,iptc:!1,ifd0:!0,ifd1:!1,exif:!0,gps:!0,interop:!1,ihdr:void 0,makerNote:!1,userComment:!1,multiSegment:!1,skip:[],pick:[],translateKeys:!0,translateValues:!0,reviveValues:!0,sanitize:!0,mergeOutput:!0,silentErrors:!0,chunked:!0,firstChunkSize:void 0,firstChunkSizeNode:512,firstChunkSizeBrowser:65536,chunkSize:65536,chunkLimit:5},Ko=new Map,Ze=class extends jn{static useCached(t){let e=Ko.get(t);return e!==void 0||(e=new this(t),Ko.set(t,e)),e}constructor(t){super(),t===!0?this.setupFromTrue():t===void 0?this.setupFromUndefined():Array.isArray(t)?this.setupFromArray(t):typeof t=="object"?this.setupFromObject(t):qt(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=Fs?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of _i)this[t]=ee[t];for(t of Ti)this[t]=ee[t];for(t of Pi)this[t]=ee[t];for(t of Ci)this[t]=new Ei(t,ee[t],void 0,this)}setupFromTrue(){let t;for(t of _i)this[t]=ee[t];for(t of Ti)this[t]=ee[t];for(t of Pi)this[t]=!0;for(t of Ci)this[t]=new Ei(t,!0,void 0,this)}setupFromArray(t){let e;for(e of _i)this[e]=ee[e];for(e of Ti)this[e]=ee[e];for(e of Pi)this[e]=ee[e];for(e of Ci)this[e]=new Ei(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,zt)}setupFromObject(t){let e;for(e of(zt.ifd0=zt.ifd0||zt.image,zt.ifd1=zt.ifd1||zt.thumbnail,Object.assign(this,t),_i))this[e]=Yr(t[e],ee[e]);for(e of Ti)this[e]=Yr(t[e],ee[e]);for(e of Pi)this[e]=Yr(t[e],ee[e]);for(e of ls)this[e]=new Ei(e,ee[e],t[e],this);for(e of zt)this[e]=new Ei(e,ee[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,zt,Ci),t.tiff===!0?this.batchEnableWithBool(zt,!0):t.tiff===!1?this.batchEnableWithUserValue(zt,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,zt):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,zt)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let r=e[i];this[i].enabled=r!==!1&&r!==void 0}}setupGlobalFilters(t,e,i,r=i){if(t&&t.length){for(let g of r)this[g].enabled=!1;let o=Yo(t,i);for(let[g,d]of o)zn(this[g].pick,d),this[g].enabled=!0}else if(e&&e.length){let o=Yo(e,i);for(let[g,d]of o)zn(this[g].skip,d)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:r,icc:o}=this;this.makerNote?e.deps.add(37500):e.skip.add(37500),this.userComment?e.deps.add(37510):e.skip.add(37510),i.enabled||t.skip.add(700),r.enabled||t.skip.add(33723),o.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:r}=this;r.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=zt.some((o=>this[o].enabled===!0))||this.makerNote||this.userComment;for(let o of zt)this[o].finalizeFilters()}get onlyTiff(){return!Ns.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of ls)this[t].enabled&&!ie.has(t)&&ta("segment parser",t)}};function Yo(n,t){let e,i,r,o,g=[];for(r of t){for(o of(e=Le.get(r),i=[],e))(n.includes(o[0])||n.includes(o[1]))&&i.push(o[0]);i.length&&g.push([r,i])}return g}function Yr(n,t){return n!==void 0?n:t!==void 0?t:void 0}function zn(n,t){for(let e of t)n.add(e)}kt(Ze,"default",ee);var Oe=class{constructor(t){kt(this,"parsers",{}),kt(this,"output",{}),kt(this,"errors",[]),kt(this,"pushToErrors",(e=>this.errors.push(e))),this.options=Ze.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?Xo(e,i):Fs&&!Wl&&e instanceof HTMLImageElement?Xo(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new Fe(e):Fs&&e instanceof Blob?ea(e,i,"blob",cs):void qt("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,r]of Ri)if(r.canHandle(t,e))return this.fileParser=new r(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),qt("Unknown file format")}async parse(){let{output:t,errors:e}=this;return this.setup(),this.options.silentErrors?(await this.executeParsers().catch(this.pushToErrors),e.push(...this.fileParser.errors)):await this.executeParsers(),this.file.close&&this.file.close(),this.options.silentErrors&&e.length>0&&(t.errors=e),Hn(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let r=await i.parse();i.assignToOutput(t,r)}));this.options.silentErrors&&(e=e.map((i=>i.catch(this.pushToErrors)))),await Promise.all(e)}async extractThumbnail(){this.setup();let{options:t,file:e}=this,i=ie.get("tiff",t);var r;if(e.tiff?r={start:0,type:"tiff"}:e.jpeg&&(r=await this.fileParser.getOrFindSegment("tiff")),r===void 0)return;let o=await this.fileParser.ensureSegmentChunk(r),g=this.parsers.tiff=new i(o,t,e),d=await g.extractThumbnail();return e.close&&e.close(),d}};async function pa(n,t){let e=new Oe(t);return await e.read(n),e.parse()}var ql=Object.freeze({__proto__:null,parse:pa,Exifr:Oe,fileParsers:Ri,segmentParsers:ie,fileReaders:Mi,tagKeys:Le,tagValues:hs,tagRevivers:ki,createDictionary:ge,extendDictionary:ua,fetchUrlAsArrayBuffer:os,readBlobAsArrayBuffer:cs,chunkedProps:_i,otherSegments:Ns,segments:ls,tiffBlocks:zt,segmentsAndBlocks:Ci,tiffExtractables:Pi,inheritables:Bs,allFormatters:Ti,Options:Ze}),Vn=class{constructor(t,e,i){kt(this,"errors",[]),kt(this,"ensureSegmentChunk",(async r=>{let o=r.start,g=r.size||65536;if(this.file.chunked)if(this.file.available(o,g))r.chunk=this.file.subarray(o,g);else try{r.chunk=await this.file.readChunk(o,g)}catch(d){qt(`Couldn't read segment: ${JSON.stringify(r)}. ${d.message}`)}else this.file.byteLength>o+g?r.chunk=this.file.subarray(o,g):r.size===void 0?r.chunk=this.file.subarray(o):qt("Segment unreachable: "+JSON.stringify(r));return r.chunk})),this.extendOptions&&this.extendOptions(t),this.options=t,this.file=e,this.parsers=i}injectSegment(t,e){this.options[t].enabled&&this.createParser(t,e)}createParser(t,e){let i=new(ie.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:r}=e,o=this.options[i];if(o&&o.enabled){let g=this.parsers[i];g&&g.append||g||this.createParser(i,r)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},Ie=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,r=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,o=e+r,g=i-r;return{offset:e,length:i,headerLength:r,start:o,size:g,end:o+g}}static parse(t,e={}){return new this(t,new Ze({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof Fe?t:new Fe(t)}constructor(t,e={},i){kt(this,"errors",[]),kt(this,"raw",new Map),kt(this,"handleError",(r=>{if(!this.options.silentErrors)throw r;this.errors.push(r.message)})),this.chunk=this.normalizeInput(t),this.file=i,this.type=this.constructor.type,this.globalOptions=this.options=e,this.localOptions=e[this.type],this.canTranslate=this.localOptions&&this.localOptions.translate}translate(){this.canTranslate&&(this.translated=this.translateBlock(this.raw,this.type))}get output(){return this.translated?this.translated:this.raw?Object.fromEntries(this.raw):void 0}translateBlock(t,e){let i=ki.get(e),r=hs.get(e),o=Le.get(e),g=this.options[e],d=g.reviveValues&&!!i,m=g.translateValues&&!!r,v=g.translateKeys&&!!o,u={};for(let[a,p]of t)d&&i.has(a)?p=i.get(a)(p):m&&r.has(a)&&(p=this.translateValue(p,r.get(a))),v&&o.has(a)&&(a=o.get(a)||a),u[a]=p;return u}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};kt(Ie,"headerLength",4),kt(Ie,"type",void 0),kt(Ie,"multiSegment",!1),kt(Ie,"canHandle",(()=>!1));function Xl(n){return n===192||n===194||n===196||n===219||n===221||n===218||n===254}function Kl(n){return n>=224&&n<=239}function Yl(n,t,e){for(let[i,r]of ie)if(r.canHandle(n,t,e))return i}var Wn=class extends Vn{constructor(...t){super(...t),kt(this,"appSegments",[]),kt(this,"jpegSegments",[]),kt(this,"unknownSegments",[])}static canHandle(t,e){return e===65496}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(t){t===!0?(this.findAll=!0,this.wanted=new Set(ie.keyList())):(t=t===void 0?ie.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&ie.has(e))),this.findAll=!1,this.remaining=new Set(t),this.wanted=new Set(t)),this.unfinishedMultiSegment=!1}async findAppSegments(t=0,e){this.setupSegmentFinderArgs(e);let{file:i,findAll:r,wanted:o,remaining:g}=this;if(!r&&this.file.chunked&&(r=Array.from(o).some((d=>{let m=ie.get(d),v=this.options[d];return m.multiSegment&&v.multiSegment})),r&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let d=!1;for(;g.size>0&&!d&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:m}=i,v=this.appSegments.some((u=>!this.file.available(u.offset||u.start,u.length||u.size)));if(d=t>m&&!v?!await i.readNextChunk(t):!await i.readNextChunk(m),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,r,o,g,d,m,{file:v,findAll:u,wanted:a,remaining:p,options:x}=this;for(;t<e;t++)if(v.getUint8(t)===255){if(i=v.getUint8(t+1),Kl(i)){if(r=v.getUint16(t+2),o=Yl(v,t,r),o&&a.has(o)&&(g=ie.get(o),d=g.findPosition(v,t),m=x[o],d.type=o,this.appSegments.push(d),!u&&(g.multiSegment&&m.multiSegment?(this.unfinishedMultiSegment=d.chunkNumber<d.chunkCount,this.unfinishedMultiSegment||p.delete(o)):p.delete(o),p.size===0)))break;x.recordUnknownSegments&&(d=Ie.findPosition(v,t),d.marker=i,this.unknownSegments.push(d)),t+=r+1}else if(Xl(i)){if(r=v.getUint16(t+2),i===218&&x.stopAfterSos!==!1)return;x.recordJpegSegments&&this.jpegSegments.push({offset:t,length:r,marker:i}),t+=r+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let r,o,g,d=new Map;for(let m=0;m<e.length;m++)r=e[m],o=r[i],d.has(o)?g=d.get(o):d.set(o,g=[]),g.push(r);return Array.from(d)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let r=ie.get(e,this.options);return r.handleMultiSegments?{type:e,chunk:r.handleMultiSegments(i)}:i[0]}))}getSegment(t){return this.appSegments.find((e=>e.type===t))}async getOrFindSegment(t){let e=this.getSegment(t);return e===void 0&&(await this.findAppSegments(0,[t]),e=this.getSegment(t)),e}};kt(Wn,"type","jpeg"),Ri.set("jpeg",Wn);var Jl=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],na=class extends Ie{parseHeader(){var t=this.chunk.getUint16();t===18761?this.le=!0:t===19789&&(this.le=!1),this.chunk.le=this.le,this.headerParsed=!0}parseTags(t,e,i=new Map){let{pick:r,skip:o}=this.options[e];r=new Set(r);let g=r.size>0,d=o.size===0,m=this.chunk.getUint16(t);t+=2;for(let v=0;v<m;v++){let u=this.chunk.getUint16(t);if(g){if(r.has(u)&&(i.set(u,this.parseTag(t,u,e)),r.delete(u),r.size===0))break}else!d&&o.has(u)||i.set(u,this.parseTag(t,u,e));t+=12}return i}parseTag(t,e,i){let{chunk:r}=this,o=r.getUint16(t+2),g=r.getUint32(t+4),d=Jl[o];if(d*g<=4?t+=8:t=r.getUint32(t+8),(o<1||o>13)&&qt(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t}`),t>r.byteLength&&qt(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t} is outside of chunk size ${r.byteLength}`),o===1)return r.getUint8Array(t,g);if(o===2)return nc(r.getString(t,g));if(o===7)return r.getUint8Array(t,g);if(g===1)return this.parseTagValue(o,t);{let m=new((function(u){switch(u){case 1:return Uint8Array;case 3:return Uint16Array;case 4:return Uint32Array;case 5:return Array;case 6:return Int8Array;case 8:return Int16Array;case 9:return Int32Array;case 10:return Array;case 11:return Float32Array;case 12:return Float64Array;default:return Array}})(o))(g),v=d;for(let u=0;u<g;u++)m[u]=this.parseTagValue(o,t),t+=v;return m}}parseTagValue(t,e){let{chunk:i}=this;switch(t){case 1:return i.getUint8(e);case 3:return i.getUint16(e);case 4:return i.getUint32(e);case 5:return i.getUint32(e)/i.getUint32(e+4);case 6:return i.getInt8(e);case 8:return i.getInt16(e);case 9:return i.getInt32(e);case 10:return i.getInt32(e)/i.getInt32(e+4);case 11:return i.getFloat(e);case 12:return i.getDouble(e);case 13:return i.getUint32(e);default:qt(`Invalid tiff type ${t}`)}}},Ds=class extends na{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1165519206&&t.getUint16(e+8)===0}async parse(){this.parseHeader();let{options:t}=this;return t.ifd0.enabled&&await this.parseIfd0Block(),t.exif.enabled&&await this.safeParse("parseExifBlock"),t.gps.enabled&&await this.safeParse("parseGpsBlock"),t.interop.enabled&&await this.safeParse("parseInteropBlock"),t.ifd1.enabled&&await this.safeParse("parseThumbnailBlock"),this.createOutput()}safeParse(t){let e=this[t]();return e.catch!==void 0&&(e=e.catch(this.handleError)),e}findIfd0Offset(){this.ifd0Offset===void 0&&(this.ifd0Offset=this.chunk.getUint32(4))}findIfd1Offset(){if(this.ifd1Offset===void 0){this.findIfd0Offset();let t=this.chunk.getUint16(this.ifd0Offset),e=this.ifd0Offset+2+12*t;this.ifd1Offset=this.chunk.getUint32(e)}}parseBlock(t,e){let i=new Map;return this[e]=i,this.parseTags(t,e,i),i}async parseIfd0Block(){if(this.ifd0)return;let{file:t}=this;this.findIfd0Offset(),this.ifd0Offset<8&&qt("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&qt(`IFD0 offset points to outside of file.
|
|
8
|
+
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,Go(this.options));let e=this.parseBlock(this.ifd0Offset,"ifd0");return e.size!==0?(this.exifOffset=e.get(34665),this.interopOffset=e.get(40965),this.gpsOffset=e.get(34853),this.xmp=e.get(700),this.iptc=e.get(33723),this.icc=e.get(34675),this.options.sanitize&&(e.delete(34665),e.delete(40965),e.delete(34853),e.delete(700),e.delete(33723),e.delete(34675)),e):void 0}async parseExifBlock(){if(this.exif||(this.ifd0||await this.parseIfd0Block(),this.exifOffset===void 0))return;this.file.tiff&&await this.file.ensureChunk(this.exifOffset,Go(this.options));let t=this.parseBlock(this.exifOffset,"exif");return this.interopOffset||(this.interopOffset=t.get(40965)),this.makerNote=t.get(37500),this.userComment=t.get(37510),this.options.sanitize&&(t.delete(40965),t.delete(37500),t.delete(37510)),this.unpack(t,41728),this.unpack(t,41729),t}unpack(t,e){let i=t.get(e);i&&i.length===1&&t.set(e,i[0])}async parseGpsBlock(){if(this.gps||(this.ifd0||await this.parseIfd0Block(),this.gpsOffset===void 0))return;let t=this.parseBlock(this.gpsOffset,"gps");return t&&t.has(2)&&t.has(4)&&(t.set("latitude",Jo(...t.get(2),t.get(1))),t.set("longitude",Jo(...t.get(4),t.get(3)))),t}async parseInteropBlock(){if(!this.interop&&(this.ifd0||await this.parseIfd0Block(),this.interopOffset!==void 0||this.exif||await this.parseExifBlock(),this.interopOffset!==void 0))return this.parseBlock(this.interopOffset,"interop")}async parseThumbnailBlock(t=!1){if(!this.ifd1&&!this.ifd1Parsed&&(!this.options.mergeOutput||t))return this.findIfd1Offset(),this.ifd1Offset>0&&(this.parseBlock(this.ifd1Offset,"ifd1"),this.ifd1Parsed=!0),this.ifd1}async extractThumbnail(){if(this.headerParsed||this.parseHeader(),this.ifd1Parsed||await this.parseThumbnailBlock(!0),this.ifd1===void 0)return;let t=this.ifd1.get(513),e=this.ifd1.get(514);return this.chunk.getUint8Array(t,e)}get image(){return this.ifd0}get thumbnail(){return this.ifd1}createOutput(){let t,e,i,r={};for(e of zt)if(t=this[e],!sc(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(r,i)}else r[e]=i;return this.makerNote&&(r.makerNote=this.makerNote),this.userComment&&(r.userComment=this.userComment),r}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,r]of Object.entries(e))this.assignObjectToOutput(t,i,r)}};function Jo(n,t,e,i){var r=n+t/60+e/3600;return i!=="S"&&i!=="W"||(r*=-1),r}kt(Ds,"type","tiff"),kt(Ds,"headerLength",10),ie.set("tiff",Ds);var Ql=Object.freeze({__proto__:null,default:ql,Exifr:Oe,fileParsers:Ri,segmentParsers:ie,fileReaders:Mi,tagKeys:Le,tagValues:hs,tagRevivers:ki,createDictionary:ge,extendDictionary:ua,fetchUrlAsArrayBuffer:os,readBlobAsArrayBuffer:cs,chunkedProps:_i,otherSegments:Ns,segments:ls,tiffBlocks:zt,segmentsAndBlocks:Ci,tiffExtractables:Pi,inheritables:Bs,allFormatters:Ti,Options:Ze,parse:pa}),fa={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},oc=Object.assign({},fa,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Zl(n){let t=new Oe(oc);await t.read(n);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:r}=e.gps;return{latitude:i,longitude:r}}}var cc=Object.assign({},fa,{tiff:!1,ifd1:!0,mergeOutput:!1});async function th(n){let t=new Oe(cc);await t.read(n);let e=await t.extractThumbnail();return e&&da?ha.from(e):e}async function eh(n){let t=await this.thumbnail(n);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var lc=Object.assign({},fa,{firstChunkSize:4e4,ifd0:[274]});async function hc(n){let t=new Oe(lc);await t.read(n);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var dc=Object.freeze({1:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:0,rad:0},2:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:0,rad:0},3:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:180,rad:180*Math.PI/180},4:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:180,rad:180*Math.PI/180},5:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:90,rad:90*Math.PI/180},6:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:90,rad:90*Math.PI/180},7:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:270,rad:270*Math.PI/180},8:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:270,rad:270*Math.PI/180}}),rs=!0,as=!0;if(typeof navigator=="object"){let n=navigator.userAgent;if(n.includes("iPad")||n.includes("iPhone")){let t=n.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;rs=Number(e)+.1*Number(i)<13.4,as=!1}}else if(n.includes("OS X 10")){let[,t]=n.match(/OS X 10[_.](\d+)/);rs=as=Number(t)<15}if(n.includes("Chrome/")){let[,t]=n.match(/Chrome\/(\d+)/);rs=as=Number(t)<81}else if(n.includes("Firefox/")){let[,t]=n.match(/Firefox\/(\d+)/);rs=as=Number(t)<77}}async function ih(n){let t=await hc(n);return Object.assign({canvas:rs,css:as},dc[t])}var ra=class extends Fe{constructor(...t){super(...t),kt(this,"ranges",new aa),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let r=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(r)}else{let r=t+e;if(r>this.byteLength){let{dataView:o}=this._extend(r);this._swapDataView(o)}}}_extend(t){let e;e=da?ha.allocUnsafe(t):new Uint8Array(t);let i=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:e,dataView:i}}subarray(t,e,i=!1){return e=e||this._lengthToEnd(t),i&&this._tryExtend(t,e),this.ranges.add(t,e),super.subarray(t,e)}set(t,e,i=!1){i&&this._tryExtend(e,t.byteLength,t);let r=super.set(t,e);return this.ranges.add(e,r.byteLength),r}async ensureChunk(t,e){this.chunked&&(this.ranges.available(t,e)||await this.readChunk(t,e))}available(t,e){return this.ranges.available(t,e)}},aa=class{constructor(){kt(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let r=t+e,o=this.list.filter((g=>Qo(t,g.offset,r)||Qo(t,g.end,r)));if(o.length>0){t=Math.min(t,...o.map((d=>d.offset))),r=Math.max(r,...o.map((d=>d.end))),e=r-t;let g=o.shift();g.offset=t,g.length=e,g.end=r,this.list=this.list.filter((d=>!o.includes(d)))}else this.list.push({offset:t,length:e,end:r})}available(t,e){let i=t+e;return this.list.some((r=>r.offset<=t&&i<=r.end))}};function Qo(n,t,e){return n<=t&&t<=e}var Gn=class extends ra{constructor(t,e){super(0),kt(this,"chunksRead",0),this.input=t,this.options=e}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(t=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let e=this.options.chunkSize,i=await this.readChunk(t,e);return!!i&&i.byteLength===e}async readChunk(t,e){if(this.chunksRead++,(e=this.safeWrapAddress(t,e))!==0)return this._readChunk(t,e)}safeWrapAddress(t,e){return this.size!==void 0&&t+e>this.size?Math.max(0,this.size-t):e}get nextChunkOffset(){if(this.ranges.list.length!==0)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return this.size!==void 0&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}};Mi.set("blob",class extends Gn{async readWhole(){this.chunked=!1;let n=await cs(this.input);this._swapArrayBuffer(n)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(n,t){let e=t?n+t:void 0,i=this.input.slice(n,e),r=await cs(i);return this.set(r,n,!0)}});var sh=Object.freeze({__proto__:null,default:Ql,Exifr:Oe,fileParsers:Ri,segmentParsers:ie,fileReaders:Mi,tagKeys:Le,tagValues:hs,tagRevivers:ki,createDictionary:ge,extendDictionary:ua,fetchUrlAsArrayBuffer:os,readBlobAsArrayBuffer:cs,chunkedProps:_i,otherSegments:Ns,segments:ls,tiffBlocks:zt,segmentsAndBlocks:Ci,tiffExtractables:Pi,inheritables:Bs,allFormatters:Ti,Options:Ze,parse:pa,gpsOnlyOptions:oc,gps:Zl,thumbnailOnlyOptions:cc,thumbnail:th,thumbnailUrl:eh,orientationOnlyOptions:lc,orientation:hc,rotations:dc,get rotateCanvas(){return rs},get rotateCss(){return as},rotation:ih});Mi.set("url",class extends Gn{async readWhole(){this.chunked=!1;let n=await os(this.input);n instanceof ArrayBuffer?this._swapArrayBuffer(n):n instanceof Uint8Array&&this._swapBuffer(n)}async _readChunk(n,t){let e=t?n+t-1:void 0,i=this.options.httpHeaders||{};(n||e)&&(i.range=`bytes=${[n,e].join("-")}`);let r=await ac(this.input,{headers:i}),o=await r.arrayBuffer(),g=o.byteLength;if(r.status!==416)return g!==t&&(this.size=n+g),this.set(o,n,!0)}});Fe.prototype.getUint64=function(n){let t=this.getUint32(n),e=this.getUint32(n+4);return t<1048575?t<<32|e:typeof $n!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),$n(t)<<$n(32)|$n(e)):void qt("Trying to read 64b value but JS can only handle 53b numbers.")};var oa=class extends Vn{parseBoxes(t=0){let e=[];for(;t<this.file.byteLength-4;){let i=this.parseBoxHead(t);if(e.push(i),i.length===0)break;t+=i.length}return e}parseSubBoxes(t){t.boxes=this.parseBoxes(t.start)}findBox(t,e){return t.boxes===void 0&&this.parseSubBoxes(t),t.boxes.find((i=>i.kind===e))}parseBoxHead(t){let e=this.file.getUint32(t),i=this.file.getString(t+4,4),r=t+8;return e===1&&(e=this.file.getUint64(t+8),r+=8),{offset:t,length:e,kind:i,start:r}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},qn=class extends oa{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let r=16,o=[];for(;r<i;)o.push(t.getString(r,4)),r+=4;return o.includes(this.type)}async parse(){let t=this.file.getUint32(0),e=this.parseBoxHead(t);for(;e.kind!=="meta";)t+=e.length,await this.file.ensureChunk(t,16),e=this.parseBoxHead(t);await this.file.ensureChunk(e.offset,e.length),this.parseBoxFullHead(e),this.parseSubBoxes(e),this.options.icc.enabled&&await this.findIcc(e),this.options.tiff.enabled&&await this.findExif(e)}async registerSegment(t,e,i){await this.file.ensureChunk(e,i);let r=this.file.subarray(e,i);this.createParser(t,r)}async findIcc(t){let e=this.findBox(t,"iprp");if(e===void 0)return;let i=this.findBox(e,"ipco");if(i===void 0)return;let r=this.findBox(i,"colr");r!==void 0&&await this.registerSegment("icc",r.offset+12,r.length)}async findExif(t){let e=this.findBox(t,"iinf");if(e===void 0)return;let i=this.findBox(t,"iloc");if(i===void 0)return;let r=this.findExifLocIdInIinf(e),o=this.findExtentInIloc(i,r);if(o===void 0)return;let[g,d]=o;await this.file.ensureChunk(g,d);let m=4+this.file.getUint32(g);g+=m,d-=m,await this.registerSegment("tiff",g,d)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,r,o,g=t.start,d=this.file.getUint16(g);for(g+=2;d--;){if(e=this.parseBoxHead(g),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(r=e.version===3?4:2,o=this.file.getString(i+r+2,4),o==="Exif"))return this.file.getUintBytes(i,r);g+=e.length}}get8bits(t){let e=this.file.getUint8(t);return[e>>4,15&e]}findExtentInIloc(t,e){this.parseBoxFullHead(t);let i=t.start,[r,o]=this.get8bits(i++),[g,d]=this.get8bits(i++),m=t.version===2?4:2,v=t.version===1||t.version===2?2:0,u=d+r+o,a=t.version===2?4:2,p=this.file.getUintBytes(i,a);for(i+=a;p--;){let x=this.file.getUintBytes(i,m);i+=m+v+2+g;let T=this.file.getUint16(i);if(i+=2,x===e)return T>1&&console.warn(`ILOC box has more than one extent but we're only processing one
|
|
9
|
+
Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+d,r),this.file.getUintBytes(i+d+r,o)];i+=T*u}}},Xn=class extends qn{};kt(Xn,"type","heic");var Kn=class extends qn{};kt(Kn,"type","avif"),Ri.set("heic",Xn),Ri.set("avif",Kn),ge(Le,["ifd0","ifd1"],[[256,"ImageWidth"],[257,"ImageHeight"],[258,"BitsPerSample"],[259,"Compression"],[262,"PhotometricInterpretation"],[270,"ImageDescription"],[271,"Make"],[272,"Model"],[273,"StripOffsets"],[274,"Orientation"],[277,"SamplesPerPixel"],[278,"RowsPerStrip"],[279,"StripByteCounts"],[282,"XResolution"],[283,"YResolution"],[284,"PlanarConfiguration"],[296,"ResolutionUnit"],[301,"TransferFunction"],[305,"Software"],[306,"ModifyDate"],[315,"Artist"],[316,"HostComputer"],[317,"Predictor"],[318,"WhitePoint"],[319,"PrimaryChromaticities"],[513,"ThumbnailOffset"],[514,"ThumbnailLength"],[529,"YCbCrCoefficients"],[530,"YCbCrSubSampling"],[531,"YCbCrPositioning"],[532,"ReferenceBlackWhite"],[700,"ApplicationNotes"],[33432,"Copyright"],[33723,"IPTC"],[34665,"ExifIFD"],[34675,"ICC"],[34853,"GpsIFD"],[330,"SubIFD"],[40965,"InteropIFD"],[40091,"XPTitle"],[40092,"XPComment"],[40093,"XPAuthor"],[40094,"XPKeywords"],[40095,"XPSubject"]]),ge(Le,"exif",[[33434,"ExposureTime"],[33437,"FNumber"],[34850,"ExposureProgram"],[34852,"SpectralSensitivity"],[34855,"ISO"],[34858,"TimeZoneOffset"],[34859,"SelfTimerMode"],[34864,"SensitivityType"],[34865,"StandardOutputSensitivity"],[34866,"RecommendedExposureIndex"],[34867,"ISOSpeed"],[34868,"ISOSpeedLatitudeyyy"],[34869,"ISOSpeedLatitudezzz"],[36864,"ExifVersion"],[36867,"DateTimeOriginal"],[36868,"CreateDate"],[36873,"GooglePlusUploadCode"],[36880,"OffsetTime"],[36881,"OffsetTimeOriginal"],[36882,"OffsetTimeDigitized"],[37121,"ComponentsConfiguration"],[37122,"CompressedBitsPerPixel"],[37377,"ShutterSpeedValue"],[37378,"ApertureValue"],[37379,"BrightnessValue"],[37380,"ExposureCompensation"],[37381,"MaxApertureValue"],[37382,"SubjectDistance"],[37383,"MeteringMode"],[37384,"LightSource"],[37385,"Flash"],[37386,"FocalLength"],[37393,"ImageNumber"],[37394,"SecurityClassification"],[37395,"ImageHistory"],[37396,"SubjectArea"],[37500,"MakerNote"],[37510,"UserComment"],[37520,"SubSecTime"],[37521,"SubSecTimeOriginal"],[37522,"SubSecTimeDigitized"],[37888,"AmbientTemperature"],[37889,"Humidity"],[37890,"Pressure"],[37891,"WaterDepth"],[37892,"Acceleration"],[37893,"CameraElevationAngle"],[40960,"FlashpixVersion"],[40961,"ColorSpace"],[40962,"ExifImageWidth"],[40963,"ExifImageHeight"],[40964,"RelatedSoundFile"],[41483,"FlashEnergy"],[41486,"FocalPlaneXResolution"],[41487,"FocalPlaneYResolution"],[41488,"FocalPlaneResolutionUnit"],[41492,"SubjectLocation"],[41493,"ExposureIndex"],[41495,"SensingMethod"],[41728,"FileSource"],[41729,"SceneType"],[41730,"CFAPattern"],[41985,"CustomRendered"],[41986,"ExposureMode"],[41987,"WhiteBalance"],[41988,"DigitalZoomRatio"],[41989,"FocalLengthIn35mmFormat"],[41990,"SceneCaptureType"],[41991,"GainControl"],[41992,"Contrast"],[41993,"Saturation"],[41994,"Sharpness"],[41996,"SubjectDistanceRange"],[42016,"ImageUniqueID"],[42032,"OwnerName"],[42033,"SerialNumber"],[42034,"LensInfo"],[42035,"LensMake"],[42036,"LensModel"],[42037,"LensSerialNumber"],[42080,"CompositeImage"],[42081,"CompositeImageCount"],[42082,"CompositeImageExposureTimes"],[42240,"Gamma"],[59932,"Padding"],[59933,"OffsetSchema"],[65e3,"OwnerName"],[65001,"SerialNumber"],[65002,"Lens"],[65100,"RawFile"],[65101,"Converter"],[65102,"WhiteBalance"],[65105,"Exposure"],[65106,"Shadows"],[65107,"Brightness"],[65108,"Contrast"],[65109,"Saturation"],[65110,"Sharpness"],[65111,"Smoothness"],[65112,"MoireFilter"],[40965,"InteropIFD"]]),ge(Le,"gps",[[0,"GPSVersionID"],[1,"GPSLatitudeRef"],[2,"GPSLatitude"],[3,"GPSLongitudeRef"],[4,"GPSLongitude"],[5,"GPSAltitudeRef"],[6,"GPSAltitude"],[7,"GPSTimeStamp"],[8,"GPSSatellites"],[9,"GPSStatus"],[10,"GPSMeasureMode"],[11,"GPSDOP"],[12,"GPSSpeedRef"],[13,"GPSSpeed"],[14,"GPSTrackRef"],[15,"GPSTrack"],[16,"GPSImgDirectionRef"],[17,"GPSImgDirection"],[18,"GPSMapDatum"],[19,"GPSDestLatitudeRef"],[20,"GPSDestLatitude"],[21,"GPSDestLongitudeRef"],[22,"GPSDestLongitude"],[23,"GPSDestBearingRef"],[24,"GPSDestBearing"],[25,"GPSDestDistanceRef"],[26,"GPSDestDistance"],[27,"GPSProcessingMethod"],[28,"GPSAreaInformation"],[29,"GPSDateStamp"],[30,"GPSDifferential"],[31,"GPSHPositioningError"]]),ge(hs,["ifd0","ifd1"],[[274,{1:"Horizontal (normal)",2:"Mirror horizontal",3:"Rotate 180",4:"Mirror vertical",5:"Mirror horizontal and rotate 270 CW",6:"Rotate 90 CW",7:"Mirror horizontal and rotate 90 CW",8:"Rotate 270 CW"}],[296,{1:"None",2:"inches",3:"cm"}]]);var Is=ge(hs,"exif",[[34850,{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"}],[37121,{0:"-",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}],[37383,{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"}],[37384,{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"}],[37385,{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"}],[41495,{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"}],[41728,{1:"Film Scanner",2:"Reflection Print Scanner",3:"Digital Camera"}],[41729,{1:"Directly photographed"}],[41985,{0:"Normal",1:"Custom",2:"HDR (no original saved)",3:"HDR (original saved)",4:"Original (for HDR)",6:"Panorama",7:"Portrait HDR",8:"Portrait"}],[41986,{0:"Auto",1:"Manual",2:"Auto bracket"}],[41987,{0:"Auto",1:"Manual"}],[41990,{0:"Standard",1:"Landscape",2:"Portrait",3:"Night",4:"Other"}],[41991,{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"}],[41996,{0:"Unknown",1:"Macro",2:"Close",3:"Distant"}],[42080,{0:"Unknown",1:"Not a Composite Image",2:"General Composite Image",3:"Composite Image Captured While Shooting"}]]),Zo={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};Is.set(37392,Zo),Is.set(41488,Zo);var Jr={0:"Normal",1:"Low",2:"High"};function tc(n){return typeof n=="object"&&n.length!==void 0?n[0]:n}function ec(n){let t=Array.from(n).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function Qr(n){if(typeof n=="string"){var[t,e,i,r,o,g]=n.trim().split(/[-: ]/g).map(Number),d=new Date(t,e-1,i);return Number.isNaN(r)||Number.isNaN(o)||Number.isNaN(g)||(d.setHours(r),d.setMinutes(o),d.setSeconds(g)),Number.isNaN(+d)?n:d}}function Ms(n){if(typeof n=="string")return n;let t=[];if(n[1]===0&&n[n.length-1]===0)for(let e=0;e<n.length;e+=2)t.push(ic(n[e+1],n[e]));else for(let e=0;e<n.length;e+=2)t.push(ic(n[e],n[e+1]));return nc(String.fromCodePoint(...t))}function ic(n,t){return n<<8|t}Is.set(41992,Jr),Is.set(41993,Jr),Is.set(41994,Jr),ge(ki,["ifd0","ifd1"],[[50827,function(n){return typeof n!="string"?rc(n):n}],[306,Qr],[40091,Ms],[40092,Ms],[40093,Ms],[40094,Ms],[40095,Ms]]),ge(ki,"exif",[[40960,ec],[36864,ec],[36867,Qr],[36868,Qr],[40962,tc],[40963,tc]]),ge(ki,"gps",[[0,n=>Array.from(n).join(".")],[7,n=>Array.from(n).join(":")]]);var Ls=class extends Ie{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1752462448&&t.getString(e+4,20)==="http://ns.adobe.com/"}static headerLength(t,e){return t.getString(e+4,34)==="http://ns.adobe.com/xmp/extension/"?79:33}static findPosition(t,e){let i=super.findPosition(t,e);return i.multiSegment=i.extended=i.headerLength===79,i.multiSegment?(i.chunkCount=t.getUint8(e+72),i.chunkNumber=t.getUint8(e+76),t.getUint8(e+77)!==0&&i.chunkNumber++):(i.chunkCount=1/0,i.chunkNumber=-1),i}static handleMultiSegments(t){return t.map((e=>e.chunk.getString())).join("")}normalizeInput(t){return typeof t=="string"?t:Fe.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let g={},d={};for(let m of gc)g[m]=[],d[m]=0;return o.replace(oh,((m,v,u)=>{if(v==="<"){let a=++d[u];return g[u].push(a),`${m}#${a}`}return`${m}#${g[u].pop()}`}))})(t);let e=Yn.findAll(t,"rdf","Description");e.length===0&&e.push(new Yn("rdf","Description",void 0,t));let i,r={};for(let o of e)for(let g of o.properties)i=ah(g.ns,r),uc(g,i);return(function(o){let g;for(let d in o)g=o[d]=Hn(o[d]),g===void 0&&delete o[d];return Hn(o)})(r)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,r]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",r);break;case"exif":this.assignObjectToOutput(t,"exif",r);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,r)}else t.xmp=e}};kt(Ls,"type","xmp"),kt(Ls,"multiSegment",!0),ie.set("xmp",Ls);var ca=class n{static findAll(t){return pc(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(n.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[3].slice(1,-1);return r=fc(r),new n(e,i,r)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},Yn=class n{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var r=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else r=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return pc(t,r).map(n.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[4],o=t[8];return new n(e,i,r,o)}constructor(t,e,i,r){this.ns=t,this.name=e,this.attrString=i,this.innerXml=r,this.attrs=ca.findAll(i),this.children=n.findAll(r),this.value=this.children.length===0?fc(r):void 0,this.properties=[...this.attrs,...this.children]}get isPrimitive(){return this.value!==void 0&&this.attrs.length===0&&this.children.length===0}get isListContainer(){return this.children.length===1&&this.children[0].isList}get isList(){let{ns:t,name:e}=this;return t==="rdf"&&(e==="Seq"||e==="Bag"||e==="Alt")}get isListItem(){return this.ns==="rdf"&&this.name==="li"}serialize(){if(this.properties.length===0&&this.value===void 0)return;if(this.isPrimitive)return this.value;if(this.isListContainer)return this.children[0].serialize();if(this.isList)return rh(this.children.map(nh));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)uc(e,t);return this.value!==void 0&&(t.value=this.value),Hn(t)}};function uc(n,t){let e=n.serialize();e!==void 0&&(t[n.name]=e)}var nh=n=>n.serialize(),rh=n=>n.length===1?n[0]:n,ah=(n,t)=>t[n]?t[n]:t[n]={};function pc(n,t){let e,i=[];if(!n)return i;for(;(e=t.exec(n))!==null;)i.push(e);return i}function fc(n){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(n))return;let t=Number(n);if(!Number.isNaN(t))return t;let e=n.toLowerCase();return e==="true"||e!=="false"&&n.trim()}var gc=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],oh=new RegExp(`(<|\\/)(${gc.join("|")})`,"g"),mc=sh;async function Jn(n){try{return await mc.parse(n)||null}catch{return null}}function Di(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),n=>n.toString(16).padStart(2,"0")).join("")}async function Qn(n){if(typeof createImageBitmap>"u"||typeof document>"u"){if(n&&typeof n.arrayBuffer=="function"){let d=await n.arrayBuffer(),m=globalThis.Buffer,v=typeof m<"u"?m.from(d).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(d)));return`data:${n.type||"image/png"};base64,${v}`}if(typeof n=="string")return n}let t=await createImageBitmap(n),r=Math.min(1,1654/t.width,2339/t.height);if(r===1&&(n.type==="image/jpeg"||n.type==="image/jpg"||n.type==="image/png"||n.type==="image/webp"))return t.close(),new Promise((d,m)=>{let v=new FileReader;v.onload=()=>d(v.result),v.onerror=m,v.readAsDataURL(n)});let o=document.createElement("canvas");o.width=Math.round(t.width*r),o.height=Math.round(t.height*r),o.getContext("2d").drawImage(t,0,0,o.width,o.height),t.close();let g=n.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(g,g==="image/png"?void 0:.82)}function ga(n,t=21,e=.2,i=128){let{data:r,width:o,height:g}=n,d=o+1,m=new Float64Array((o+1)*(g+1)),v=new Float64Array((o+1)*(g+1)),u=new Uint8Array(o*g);for(let p=0;p<g;p++){let x=0,T=0,l=p*o,y=(p+1)*d,s=p*d;for(let c=0;c<o;c++){let f=(l+c)*4,w=r[f]*77+r[f+1]*150+r[f+2]*29>>8;u[l+c]=w,x+=w,T+=w*w,m[y+c+1]=m[s+c+1]+x,v[y+c+1]=v[s+c+1]+T}}let a=Math.floor(t/2);for(let p=0;p<g;p++){let x=Math.max(0,p-a),T=Math.min(g-1,p+a),l=x*d,y=(T+1)*d;for(let s=0;s<o;s++){let c=Math.max(0,s-a),f=Math.min(o-1,s+a),w=(f-c+1)*(T-x+1),R=m[y+f+1]-m[l+f+1]-m[y+c]+m[l+c],S=v[y+f+1]-v[l+f+1]-v[y+c]+v[l+c],D=R/w,N=Math.max(0,S/w-D*D),H=Math.sqrt(N),j=D*(1+e*(H/i-1)),Y=p*o+s,it=u[Y]<j?0:255,ot=Y*4;r[ot]=it,r[ot+1]=it,r[ot+2]=it}}return n}function ma(n,t=21,e=.2,i=128){return new Promise(r=>{let o=new Image;o.onload=()=>{let g=document.createElement("canvas");g.width=o.width,g.height=o.height;let d=g.getContext("2d");d.drawImage(o,0,0);let m=d.getImageData(0,0,g.width,g.height);ga(m,t,e,i),d.putImageData(m,0,0);let v=n.startsWith("data:image/png"),u=v?"image/png":"image/jpeg";r(g.toDataURL(u,v?void 0:.82))},o.src=n})}function ba(n){return new Promise(t=>{let e=new Image;e.onload=()=>{let i=document.createElement("canvas");i.width=e.height,i.height=e.width;let r=i.getContext("2d");r.translate(i.width/2,i.height/2),r.rotate(Math.PI/2),r.drawImage(e,-e.width/2,-e.height/2);let o=n.startsWith("data:image/png"),g=o?"image/png":"image/jpeg";t(i.toDataURL(g,o?void 0:.82))},e.src=n})}function ya(n,t=""){if(!n)return"";let e=n.getCroppedCanvas(),i=t.startsWith("data:image/png"),r=i?"image/png":"image/jpeg";return e.toDataURL(r,i?void 0:.82)}function Zn(n){if(!n||typeof n!="object")return{crop:null,rotation:0,filter:"none"};let t=null;n.crop&&typeof n.crop=="object"&&(n.crop.width>0&&n.crop.height>0?t={x:Math.round(n.crop.x||0),y:Math.round(n.crop.y||0),width:Math.round(n.crop.width),height:Math.round(n.crop.height)}:n.crop.w>0&&n.crop.h>0&&(t={x:Number(n.crop.x)||0,y:Number(n.crop.y)||0,w:Number(n.crop.w)||1,h:Number(n.crop.h)||1}));let e=n.rotation!==void 0?n.rotation:n.rotate,i=(Math.round(Number(e)||0)%360+360)%360,r=n.filter==="bw"?"bw":"none";return{crop:t,rotation:i,filter:r}}function ch(n){if(!n)return!1;let t=Zn(n);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function tr(n,t){let e=Zn(t),i=n.naturalWidth||n.width||0,r=n.naturalHeight||n.height||0,o=document.createElement("canvas"),g=i,d=r,m=0,v=0;if(e.crop){let p=e.crop;"w"in p&&!("width"in p)?(m=Math.max(0,Math.min(Math.round(p.x*i),i)),v=Math.max(0,Math.min(Math.round(p.y*r),r)),g=Math.max(1,Math.min(Math.round(p.w*i),i-m)),d=Math.max(1,Math.min(Math.round(p.h*r),r-v))):(m=Math.max(0,Math.min(p.x,i)),v=Math.max(0,Math.min(p.y,r)),g=Math.max(1,Math.min(p.width,i-m)),d=Math.max(1,Math.min(p.height,r-v)))}o.width=g,o.height=d,o.getContext("2d").drawImage(n,m,v,g,d,0,0,g,d);let a=o;if(e.rotation!==0){let p=e.rotation,x=document.createElement("canvas");p===90||p===270?(x.width=a.height,x.height=a.width):(x.width=a.width,x.height=a.height);let T=x.getContext("2d");T.translate(x.width/2,x.height/2),T.rotate(p*Math.PI/180),T.drawImage(a,-a.width/2,-a.height/2),a=x}if(e.filter==="bw"){let p=a.getContext("2d"),x=p.getImageData(0,0,a.width,a.height);ga(x),p.putImageData(x,0,0)}return a}function bc(n,t){if(!n)return Promise.resolve("");let e=Zn(t);return ch(e)?new Promise((i,r)=>{let o=new Image;o.onload=()=>{try{let g=n.startsWith("data:image/png"),d=g?"image/png":"image/jpeg",m=tr(o,e);i(m.toDataURL(d,g?void 0:.82))}catch(g){r(g)}},o.onerror=r,o.src=n}):Promise.resolve(n)}var ti=class{#t=null;#e=new Map;#i=new Map;constructor(t=ns()){this.#t=t}get adapter(){return this.#t}get store(){return this.#t?.store??null}async init(){return this.#t.init()}listDocsSync(){return typeof this.#t.listDocsSync=="function"?this.#t.listDocsSync().map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}}):[]}async listDocs(){return(await this.#t.listDocs()).map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}})}getDocSync(t){if(!t)return null;if(typeof this.#t.getDocSync=="function"){let r=this.#t.getDocSync(t);return r?{id:r.id,name:r.name||"",pages:this.#s(r.pages)}:null}let i=this.listDocsSync().find(r=>r.id===t);return i?{id:i.id,name:i.name,pages:i.pages||[]}:null}async getDoc(t){if(!t)return null;if(typeof this.#t.getDoc=="function"){let e=await this.#t.getDoc(t);return e?{id:e.id,name:e.name||"",pages:this.#s(e.pages)}:null}return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=Di(),r=this.#s(e),o={id:i,name:t||"Untitled Document",pages:r};return await this.#t.saveDoc(i,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=this.#s(e.pages);await this.#t.saveDoc(t,{id:t,name:e.name||"",pages:i})}async renameDoc(t,e){if(typeof this.#t.renameDoc=="function")return this.#t.renameDoc(t,e);let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t,{soft:e=!0,timeoutMs:i=5e3}={}){if(!t)return;let r=this.getDocSync(t);if(r){if(this.#n(t),await this.#t.deleteDoc(t),e&&i>0){let o=setTimeout(async()=>{this.#e.delete(t)},i);this.#e.set(t,{doc:r,timerId:o})}return{id:t,name:r.name,undo:()=>this.undoDeleteDoc(t)}}}#n(t){if(this.#e.has(t)){let e=this.#e.get(t);clearTimeout(e.timerId),this.#e.delete(t)}}async undoDeleteDoc(t){let e=this.#e.get(t);return e?(clearTimeout(e.timerId),this.#e.delete(t),await this.#t.saveDoc(t,e.doc),e.doc):null}isSoftDeletedDoc(t){return this.#e.has(t)}async addPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=Array.isArray(e)?e:[e];i.pages.push(...r),await this.saveDoc(t,i)}async updatePage(t,e,i){let r=await this.getDoc(t);if(!r)throw new Error(`Document "${t}" not found`);let o=r.pages.findIndex(g=>g.id===e);if(o===-1)throw new Error(`Page "${e}" not found in document "${t}"`);r.pages[o]={...r.pages[o],...i},await this.saveDoc(t,r)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=new Map(i.pages.map(g=>[g.id,g])),o=[];for(let g of e)r.has(g)&&(o.push(r.get(g)),r.delete(g));for(let g of r.values())o.push(g);i.pages=o,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:r=5e3}={}){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let g=o.pages.findIndex(u=>u.id===e);if(g===-1)return;let[d]=o.pages.splice(g,1);await this.saveDoc(t,o);let m=`${t}:${e}`;if(this.#r(m),!i||r<=0){if(typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}return}let v=setTimeout(async()=>{if(this.#i.delete(m),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}},r);return this.#i.set(m,{docId:t,pageId:e,page:d,index:g,timerId:v}),{docId:t,pageId:e,undo:()=>this.undoDeletePage(t,e)}}#r(t){if(this.#i.has(t)){let e=this.#i.get(t);clearTimeout(e.timerId),this.#i.delete(t)}}async undoDeletePage(t,e){let i=`${t}:${e}`,r=this.#i.get(i);if(!r)return null;clearTimeout(r.timerId),this.#i.delete(i);let o=await this.getDoc(t);if(!o)return null;let g=Math.min(r.index,o.pages.length);return o.pages.splice(g,0,r.page),await this.saveDoc(t,o),r.page}isSoftDeletedPage(t,e){return this.#i.has(`${t}:${e}`)}subscribe(t){return this.#t.subscribe(t)}async getAllDocs(){let t=await this.listDocs(),e={};for(let i of t)e[i.id]=i;return e}async exportAll(){let t=await this.listDocs(),e={};for(let i of t){let r=await this.getDoc(i.id),o=[];for(let g of r?.pages||[]){if(!g){o.push(g);continue}let d={...g},m=d.blob instanceof Blob?d.blob:null;if(!m&&typeof d.src=="string"&&d.src.startsWith("blob:"))try{m=await(await fetch(d.src)).blob()}catch{}m&&(d.src=await Kr(m));let v=d.originalBlob instanceof Blob?d.originalBlob:null;if(!v&&typeof d.originalSrc=="string"&&d.originalSrc.startsWith("blob:"))try{v=await(await fetch(d.originalSrc)).blob()}catch{}v&&(d.originalSrc=await Kr(v)),delete d.blob,delete d.originalBlob,o.push(d)}e[i.id]={name:i.name,pages:JSON.stringify(o)}}return e}async importDocs(t){let e=0;for(let[i,r]of Object.entries(t||{})){await this.getDoc(i)||e++;let g=this.#s(r.pages);await this.saveDoc(i,{name:r.name||"",pages:g})}return e}#s(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},ds=new ti;ii();var vc="2026-11-06T14:33:27.433Z",wc="0.1.5";var Be=class{async recognizeImageText(t,e={}){throw new Error("OcrPort.recognizeImageText() must be implemented by adapter")}async recognizeDocumentPages(t,e={}){throw new Error("OcrPort.recognizeDocumentPages() must be implemented by adapter")}async getOcrWorker(t="eng",e=null){throw new Error("OcrPort.getOcrWorker() must be implemented by adapter")}async terminateOcrWorker(){throw new Error("OcrPort.terminateOcrWorker() must be implemented by adapter")}};var de=class extends Be{async recognizeImageText(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async recognizeDocumentPages(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async getOcrWorker(){return null}async terminateOcrWorker(){}};var Ue=class{async exportDocumentAsPdf(t,e,i={}){throw new Error("PdfPort.exportDocumentAsPdf() must be implemented by adapter")}async renderPdfPagesToDataUrls(t){throw new Error("PdfPort.renderPdfPagesToDataUrls() must be implemented by adapter")}};var Ee=class extends Ue{async exportDocumentAsPdf(t,e,i={}){let r=new Error('Feature "pdf" is disabled or PDF module not opted in');throw r.code="FEATURE_DISABLED",r}async renderPdfPagesToDataUrls(t){return[]}};var _e=class{async renderEdits(t,e){throw new Error("ImageProcessorPort.renderEdits() must be implemented by adapter")}async crop(t,e){throw new Error("ImageProcessorPort.crop() must be implemented by adapter")}async rotate(t,e){throw new Error("ImageProcessorPort.rotate() must be implemented by adapter")}async applyFilter(t,e){throw new Error("ImageProcessorPort.applyFilter() must be implemented by adapter")}};function lh(n){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=n})}var $e=class extends _e{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await lh(t),r={...e};return e?.crop&&"w"in e.crop&&(r.crop={x:Math.round((e.crop.x||0)*i.naturalWidth),y:Math.round((e.crop.y||0)*i.naturalHeight),width:Math.round((e.crop.w||1)*i.naturalWidth),height:Math.round((e.crop.h||1)*i.naturalHeight)}),e?.rotate!==void 0&&(r.rotation=e.rotate),tr(i,r).toDataURL("image/jpeg",.92)}catch{return t}}async crop(t,e){return this.renderEdits(t,{crop:e})}async rotate(t,e){return this.renderEdits(t,{rotate:e})}async applyFilter(t,e){return this.renderEdits(t,{filter:e})}};var Li=class extends _e{async renderEdits(t,e){return t}async crop(t,e){return t}async rotate(t,e){return t}async applyFilter(t,e){return t}};function us(n={}){let t=n&&n.crop&&typeof n.crop=="object"?{x:Math.max(0,Math.min(1,Number(n.crop.x)||0)),y:Math.max(0,Math.min(1,Number(n.crop.y)||0)),w:Math.max(0,Math.min(1,Number(n.crop.w)||1)),h:Math.max(0,Math.min(1,Number(n.crop.h)||1))}:null,e=0,i=n?.rotate!==void 0?n.rotate:n?.rotation;if(i!==void 0){let o=(Math.round(Number(i)/90)*90%360+360)%360;(o===90||o===180||o===270)&&(e=o)}let r=n&&n.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:r}}function cr(n){if(!n)return!1;let t=n.rotate!==void 0?n.rotate:n.rotation;return!!(n.crop||t&&t!==0||n.filter&&n.filter!=="none")}var Zt=n=>Math.round(n*1e6)/1e6;function wa(n,t=0){if(!n)return null;let e=(Math.round(Number(t)/90)*90%360+360)%360,{x:i,y:r,w:o,h:g}=n;return e===90?{x:Zt(Math.max(0,Math.min(1,1-r-g))),y:Zt(Math.max(0,Math.min(1,i))),w:Zt(Math.max(.01,Math.min(1,g))),h:Zt(Math.max(.01,Math.min(1,o)))}:e===180?{x:Zt(Math.max(0,Math.min(1,1-i-o))),y:Zt(Math.max(0,Math.min(1,1-r-g))),w:Zt(Math.max(.01,Math.min(1,o))),h:Zt(Math.max(.01,Math.min(1,g)))}:e===270?{x:Zt(Math.max(0,Math.min(1,r))),y:Zt(Math.max(0,Math.min(1,1-i-o))),w:Zt(Math.max(.01,Math.min(1,g))),h:Zt(Math.max(.01,Math.min(1,o)))}:{x:Zt(Math.max(0,Math.min(1,i))),y:Zt(Math.max(0,Math.min(1,r))),w:Zt(Math.max(.01,Math.min(1,o))),h:Zt(Math.max(.01,Math.min(1,g)))}}function xa(n,t=0){return wa(n,t)}function Aa(n,t=0){return wa(n,-t)}var Fi=class{constructor(t){this.id=t.id,this.src=t.src,this.originalSrc=t.originalSrc||t.src,this.edits=us(t.edits),this.name=t.name||"Page",this.type=t.type||"image",this.orientation=t.orientation||1,this.ocrText=t.ocrText||null,this.ocrConfidence=t.ocrConfidence??null,this.ocrWords=Array.isArray(t.ocrWords)?t.ocrWords:null,this.ocrWidth=typeof t.ocrWidth=="number"?t.ocrWidth:null,this.ocrHeight=typeof t.ocrHeight=="number"?t.ocrHeight:null}get isModified(){return cr(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},Us=class{constructor(t){this.id=t.id,this.name=t.name||"Untitled Document",this.pages=Array.isArray(t.pages)?t.pages.map(e=>e instanceof Fi?e:new Fi(e)):[],this.createdAt=t.createdAt||Date.now(),this.updatedAt=t.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(t=>t.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},$s=class{constructor(t={}){this.mode=t.mode==="single"?"single":"batch",this.aspect=t.aspect||"auto",this.docId=t.docId||null,this.maxPages=Math.max(0,Number(t.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(t){this.history.push(t),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let t=this.history.pop();return this.future.push(t),t}redo(){if(this.future.length===0)return null;let t=this.future.pop();return this.history.push(t),t}};var Vt={PAGE_ADDED:"copio:page-added",PAGE_REMOVED:"copio:page-removed",PAGES_CHANGED:"copio:pages-changed",SCAN_COMPLETE:"copio:scan-complete",EXPORT_PROGRESS:"copio:export-progress",EXPORT_COMPLETE:"copio:export-complete",OCR_COMPLETE:"copio:ocr-complete",SYNC_CONNECTED:"copio:sync-connected",ERROR:"copio:error"};function lr(n,t,e={}){let i=new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:!0,detail:e});return n&&typeof n.dispatchEvent=="function"&&n.dispatchEvent(i),i}var _a=["crop","rotate","filter","ocr","export","sync"],Sa=["pdf","zip","png","jpg"],Ea=["eng"],Ca={};function ni(n,t){!n||!t||(Ca[n]=t,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[n]=t))}function si(n){return Ca[n]?Ca[n]:typeof globalThis<"u"&&globalThis.__copio_services__?.[n]?globalThis.__copio_services__[n]:null}function hh(n){return n?n instanceof Set?new Set(n):Array.isArray(n)?new Set(n.map(t=>String(t).trim().toLowerCase()).filter(Boolean)):typeof n=="string"?new Set(n.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set(_a):new Set(_a)}function hr(n,t){return n?Array.isArray(n)?n.map(e=>String(e).trim().toLowerCase()).filter(Boolean):typeof n=="string"?n.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean):[...t]:[...t]}var Oi=class{#t=new Set(_a);#e=[...Sa];#i=[...Ea];#n=0;#r="";#s=null;#o=null;#c={};#a=!0;#h=!0;#u=null;#d=new Map;#l=new Map;constructor(t={}){this.#s=t.storage||ns(t),this.#o=t.repository||new ti(this.#s),t.services&&(this.#c={...t.services}),t.imageProcessor?(this.#u=t.imageProcessor,this.#c.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#u=this.getService("imageProcessor"):typeof document<"u"?this.#u=new $e:this.#u=new Li,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#e=hr(t.exportFormats,Sa)),t.ocrLanguages!==void 0&&(this.#i=hr(t.ocrLanguages,Ea)),t.maxPages!==void 0&&(this.#n=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&Ii(t.assetBase),t.licenseKey!==void 0&&(this.#r=String(t.licenseKey||"")),t.ocr!==void 0?this.ocr=!!t.ocr:t.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),t.pdf!==void 0?this.pdf=!!t.pdf:t.exportFormats!==void 0&&!this.#e.includes("pdf")&&(this.pdf=!1)}async init(){return this.#s.init()}setService(t,e){this.#c[t]=e}getService(t){return this.#c[t]||si(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=hh(t),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr"))):(this.#a=!1,this.setService("ocr",new de))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#a=!1,this.setService("ocr",new de))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(t){this.#a=!!t,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new de))}get pdf(){return this.#h&&this.#e.includes("pdf")}set pdf(t){this.#h=!!t,this.#h?(this.#e.includes("pdf")||this.#e.push("pdf"),this.getService("pdf")instanceof Ee&&this.setService("pdf",si("pdf"))):(this.#e=this.#e.filter(e=>e!=="pdf"),this.setService("pdf",new Ee))}get exportFormats(){return[...this.#e]}set exportFormats(t){this.#e=hr(t,Sa),this.#e.includes("pdf")?(this.#h=!0,this.getService("pdf")instanceof Ee&&this.setService("pdf",si("pdf"))):(this.#h=!1,this.setService("pdf",new Ee))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(t){this.#i=hr(t,Ea)}get maxPages(){return this.#n}set maxPages(t){this.#n=Math.max(0,Number(t)||0)}get assetBase(){return ir()}set assetBase(t){Ii(t)}get licenseKey(){return this.#r}set licenseKey(t){this.#r=String(t||"")}get storage(){return this.#s}setStorage(t){t&&(this.#s=t,this.#o=new ti(this.#s))}#f(t,e){this.#d.has(t)||this.#d.set(t,[]);let i=this.#d.get(t);i.push(e),i.length>50&&i.shift(),this.#l.has(t)&&(this.#l.get(t).length=0)}get imageProcessor(){return this.#u}setImageProcessor(t){t&&(this.#u=t,this.setService("imageProcessor",t))}async renderEdits(t,e){if(!t)return"";let i=us(e);return this.#u?this.#u.renderEdits(t,i):bc(t,i)}get docs(){return this.#o}async listDocuments(){return this.#o.listDocs()}async getDocument(t){return this.#o.getDoc(t)}async createDocument(t,e){return this.#o.createDoc(t,e)}async deleteDocument(t,e={}){return this.#o.deleteDoc(t,e)}async undoDeleteDocument(t){return this.#o.undoDeleteDoc(t)}async renameDocument(t,e){return this.#o.renameDoc(t,e)}async addPages(t,e){return this.#o.addPages(t,e)}async deletePage(t,e,i={}){return this.#f(t,{type:"delete",pageId:e}),this.#o.deletePage(t,e,i)}async undoDeletePage(t,e){return this.#o.undoDeletePage(t,e)}async updatePage(t,e,i){return this.#o.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),r=i?.pages?i.pages.map(o=>o.id):[];return this.#f(t,{type:"reorder",priorOrder:r,newOrder:[...e]}),this.#o.reorderPages(t,e)}async#g(t){if(t)return t;let e=await this.listDocuments();return e.length>0?e[0].id:null}async applyEdit(t,e,i){let r=await this.#g(t),o=r?await this.getDocument(r):null;if(!o||!o.pages)throw new Error(`Document with ID "${r||t}" not found`);let g=o.pages.find(p=>p.id===e);if(!g)throw new Error(`Page with ID "${e}" not found in document "${r}"`);let d={...g.edits||{crop:null,rotate:0,filter:"none"}},m=g.src,v=us({...d,...i}),u=g.originalSrc||g.src,a=u;return this.#u&&(a=await this.#u.renderEdits(u,v)),await this.updatePage(r,e,{originalSrc:u,src:a,edits:v}),this.#f(r,{type:"edit",pageId:e,priorEdits:d,priorSrc:m,newEdits:v,newSrc:a}),{...g,originalSrc:u,src:a,edits:v}}async undo(t){let e=await this.#g(t),i=e?this.#d.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#l.has(e)||this.#l.set(e,[]),this.#l.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.priorEdits,src:r.priorSrc}),{type:"edit",pageId:r.pageId,restoredEdits:r.priorEdits}):r.type==="delete"?(await this.undoDeletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.#o.reorderPages(e,r.priorOrder),{type:"reorder",priorOrder:r.priorOrder}):r}async redo(t){let e=await this.#g(t),i=e?this.#l.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#d.has(e)||this.#d.set(e,[]),this.#d.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.newEdits,src:r.newSrc}),{type:"edit",pageId:r.pageId,appliedEdits:r.newEdits}):r.type==="delete"?(await this.deletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.reorderPages(e,r.newOrder),{type:"reorder",newOrder:r.newOrder}):r}subscribe(t){return this.#o.subscribe(t)}async addFiles(t,e=null){if(!t||t.length===0)return[];let i=Array.from(t),r=[];for(let g of i)if(g.type==="application/pdf"){let d=this.getService("pdf");if(d&&typeof d.renderPdfPagesToDataUrls=="function"){let m=await d.renderPdfPagesToDataUrls(g);for(let v of m)r.push({id:Di(),src:v,originalSrc:v,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:g.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(g.type&&g.type.startsWith("image/")){let d=await Qn(g),m=null;try{m=await Jn(g)}catch{}r.push({id:Di(),src:d,originalSrc:d,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:g.name||"Captured Image",orientation:m})}if(r.length===0)return[];await this.init();let o=e;if(o)await this.getDocument(o)||await this.#o.saveDoc(o,{name:"Scanned Document",pages:[]});else{let g=await this.listDocuments();g.length>0?o=g[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let g=(await this.getDocument(o))?.pages||[],d=Math.max(0,this.#n-g.length);if(d<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);r.splice(d)}return await this.addPages(o,r),r}async getPages(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return[];e=r[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return;e=r[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let r of i.pages)await this.deletePage(e,r.id)}async#p(t){if(Array.isArray(t))return{docName:"document",pages:t,docId:null};if(typeof t=="string"){let i=await this.getDocument(t);return{docName:i?.name||"document",pages:i?.pages||[],docId:t}}let e=await this.listDocuments();if(e.length>0){let i=await this.getDocument(e[0].id);return{docName:i?.name||"document",pages:i?.pages||[],docId:e[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(t,e={}){if(!this.hasFeature("export")){let g=new Error('Feature "export" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}if(!this.#h||!this.#e.includes("pdf")){let g=new Error('Feature "pdf" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}let{docName:i,pages:r}=await this.#p(t),o=this.getService("pdf")||this.getService("export");if(!o||typeof o.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsPdf(i,r,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof t=="string"){let g=await this.#s.getDoc(t);g&&(g.pages=r,await this.#s.saveDoc(t,g))}},...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let g=new Error('Feature "export" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}let{docName:i,pages:r}=await this.#p(t),o=this.getService("export");if(!o||typeof o.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsImages(i,r,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#a||!this.hasFeature("ocr")){let v=new Error('Feature "ocr" is disabled');throw Object.assign(v,{code:"FEATURE_DISABLED"}),v}let{pages:r}=await this.#p(t),o=r;e&&(o=r.filter(v=>v.id===e));let g=this.getService("ocr");if(!g||typeof g.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let d=i.lang||this.#i[0]||"eng",m=await g.recognizeDocumentPages(o,{lang:d,...i});if(Array.isArray(m.pagesResults)){for(let v of m.pagesResults){let u=o.find(a=>a.id===v.pageId)||o[v.pageIndex];u&&(u.ocrText=v.text,u.ocrConfidence=v.confidence,u.ocrWords=v.words)}if(typeof t=="string"){let v=await this.#s.getDoc(t);if(v&&Array.isArray(v.pages)){for(let u of m.pagesResults){let a=v.pages.find(p=>p.id===u.pageId)||v.pages[u.pageIndex];a&&(a.ocrText=u.text,a.ocrConfidence=u.confidence,a.ocrWords=u.words)}await this.#s.saveDoc(t,v)}}}return{text:m.combinedText,...m}}async sync(t={}){if(!this.hasFeature("sync")){let i=new Error('Feature "sync" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let e=this.getService("sync");if(!e)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new e(this.#o,t.onStateChange)}};ii();Ni();var js=`
|
|
1093
10
|
:host {
|
|
1094
11
|
all: initial;
|
|
1095
12
|
display: block;
|
|
@@ -2268,7 +1185,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2268
1185
|
min-width: 200px;
|
|
2269
1186
|
}
|
|
2270
1187
|
}
|
|
2271
|
-
`,
|
|
1188
|
+
`,Hs=null;function dr(){if(Hs)return Hs;if(typeof CSSStyleSheet<"u"&&typeof Document<"u"&&"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype)try{return Hs=new CSSStyleSheet,Hs.replaceSync(js),Hs}catch{return null}return null}function ur(n){if(!n)return;let t=dr();if(t&&"adoptedStyleSheets"in n){let e=n.adoptedStyleSheets||[];e.includes(t)||(n.adoptedStyleSheets=[...e,t])}else if(!n.querySelector("style[data-copio-encapsulated-styles]")){let e=document.createElement("style");e.setAttribute("data-copio-encapsulated-styles",""),e.textContent=js,n.appendChild(e)}}var bh=typeof HTMLElement<"u"?HTMLElement:class{},zs=class extends bh{#t=null;#e=null;#i=null;#n=!1;#r="viewfinder";#s=0;#o=0;#c=!1;#a=!1;#h=null;#u=null;#d=0;#l=null;#f=null;#g=null;onShutter=null;get#p(){return this.docId?this.docId:(this.#f||(this.#f=`doc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`),this.#f)}static get observedAttributes(){return["mode","aspect","stage","doc-id","features","export-formats","ocr-languages","max-pages","asset-base","license-key","theme","ocr","pdf"]}constructor(){super(),typeof this.attachShadow=="function"&&this.attachShadow({mode:"open"}),this.#y()}#y(){let t={storage:this.#e};typeof this.getAttribute=="function"&&(this.hasAttribute("features")&&(t.features=this.getAttribute("features")),this.hasAttribute("export-formats")&&(t.exportFormats=this.getAttribute("export-formats")),this.hasAttribute("ocr-languages")&&(t.ocrLanguages=this.getAttribute("ocr-languages")),this.hasAttribute("max-pages")&&(t.maxPages=this.getAttribute("max-pages")),this.hasAttribute("asset-base")&&(t.assetBase=this.getAttribute("asset-base")),this.hasAttribute("license-key")&&(t.licenseKey=this.getAttribute("license-key")),this.hasAttribute("ocr")&&(t.ocr=this.getAttribute("ocr")!=="false"),this.hasAttribute("pdf")&&(t.pdf=this.getAttribute("pdf")!=="false")),this.#t=new Oi(t)}connectedCallback(){this.shadowRoot&&(ur(this.shadowRoot),this.#b()),typeof ri=="function"&&typeof document<"u"&&ai()===document.body&&ri(this.shadowRoot?.querySelector(".copio-scanner-container")||this),this.#t&&(this.#i=this.#t.subscribe(async()=>{let t=await this.getPages();this.dispatch(Vt.PAGES_CHANGED,{pages:t,docId:this.docId}),this.#w()})),this.hasAttribute&&this.hasAttribute("asset-base")&&Ii(this.getAttribute("asset-base")),this.#m(),this.#w()}disconnectedCallback(){if(this.#A(),typeof this.#i=="function"&&(this.#i(),this.#i=null),this.#u&&(clearInterval(this.#u),this.#u=null),typeof ri=="function"&&typeof document<"u"){let t=this.shadowRoot?.querySelector(".copio-scanner-container")||this;ai()===t&&ri(null)}}attributeChangedCallback(t,e,i){if(!(e===i||!this.#t))switch(t){case"features":this.#t.setFeatures(i),this.#m();break;case"export-formats":this.#t.exportFormats=i,this.#m();break;case"ocr-languages":this.#t.ocrLanguages=i;break;case"asset-base":this.#t.assetBase=i;break;case"license-key":this.#t.licenseKey=i;break;case"ocr":this.#t.ocr=i!=="false",this.#m();break;case"pdf":this.#t.pdf=i!=="false",this.#m();break;case"stage":if(i==="viewfinder"||i==="workbench"){this.#r=i;let r=this.shadowRoot;if(r){let o=r.getElementById("viewfinder-section"),g=r.getElementById("workbench-section");o&&g&&(o.style.display=i==="viewfinder"?"flex":"none",g.style.display=i==="workbench"?"flex":"none")}this.#w()}break;case"max-pages":this.#t.maxPages=i,this.#w();break;case"mode":case"aspect":case"theme":this.#w();break}}#m(){if(typeof this.querySelectorAll!="function")return;let t=[];this.shadowRoot&&t.push(this.shadowRoot),t.push(this);for(let e of t){let i=e.querySelectorAll("copio-carousel, copio-row, copio-images");for(let r of i)"ocr"in r&&(r.ocr=this.ocrEnabled),"pdf"in r&&(r.pdf=this.pdf)}}#b(){if(!this.shadowRoot||this.shadowRoot.innerHTML)return;let t="Align Document Inside Frame";this.aspect==="card"?t="Step 1 of 2: Capture Front of ID Card":this.mode==="batch"&&(t="Batch Capture \xB7 Page 1"),this.shadowRoot.innerHTML=`
|
|
2272
1189
|
<div class="copio-scanner-container copio-scanner-host" part="scanner-root">
|
|
2273
1190
|
<header class="copio-header" part="header">
|
|
2274
1191
|
<div class="copio-header-left">
|
|
@@ -2445,7 +1362,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2445
1362
|
<input type="file" id="internal-file-input" accept="image/*" style="display: none;" />
|
|
2446
1363
|
<slot></slot>
|
|
2447
1364
|
</div>
|
|
2448
|
-
`,this.#S()}#S(){let t=this.shadowRoot;if(!t)return;t.getElementById("tab-viewfinder")?.addEventListener("click",()=>{this.stage="viewfinder"}),t.getElementById("tab-workbench")?.addEventListener("click",()=>{this.stage="workbench"});let e=t.getElementById("internal-file-input");t.getElementById("btn-import-file")?.addEventListener("click",()=>{e?.click()}),e?.addEventListener("change",async i=>{let
|
|
1365
|
+
`,this.#S()}#S(){let t=this.shadowRoot;if(!t)return;t.getElementById("tab-viewfinder")?.addEventListener("click",()=>{this.stage="viewfinder"}),t.getElementById("tab-workbench")?.addEventListener("click",()=>{this.stage="workbench"});let e=t.getElementById("internal-file-input");t.getElementById("btn-import-file")?.addEventListener("click",()=>{e?.click()}),e?.addEventListener("change",async i=>{let r=i.target;r.files&&r.files.length>0&&(await this.addFiles(r.files),r.value="")}),t.getElementById("btn-shutter")?.addEventListener("click",async()=>{await this.#C()}),t.getElementById("btn-review")?.addEventListener("click",()=>{this.stage="workbench"}),t.getElementById("btn-retake")?.addEventListener("click",()=>{this.#c=!0,this.#a=!1,this.stage="viewfinder"}),t.getElementById("btn-rotate")?.addEventListener("click",async()=>{await this.#T()}),t.getElementById("btn-filter-bw")?.addEventListener("click",async()=>{await this.#P()}),t.getElementById("btn-crop")?.addEventListener("click",async()=>{await this.#D()}),t.getElementById("btn-delete")?.addEventListener("click",async()=>{await this.#k()}),t.getElementById("btn-ocr")?.addEventListener("click",async()=>{await this.#I()}),t.getElementById("btn-close-ocr")?.addEventListener("click",()=>{this.#F()}),t.getElementById("btn-primary-complete")?.addEventListener("click",async()=>{await this.#O()}),t.getElementById("btn-card-front")?.addEventListener("click",()=>{this.#a=!1,this.#s=0,this.#w()}),t.getElementById("btn-card-back")?.addEventListener("click",()=>{this.#a=!1,this.#s=1,this.#w()}),this.#_()}#_(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("crop-box"),i=t.querySelectorAll(".copio-crop-handle");if(!e||i.length===0)return;let r=null,o=!1,g=0,d=0,m=null,v=p=>{let x=p.target.closest(".copio-crop-handle");if(x)r=x.getAttribute("data-handle"),o=!1;else if(p.target===e||p.target.classList.contains("copio-crop-grid"))r=null,o=!0;else return;p.preventDefault(),p.stopPropagation(),g=p.clientX,d=p.clientY,m=this.#h?{...this.#h}:{x:.05,y:.05,w:.9,h:.9},window.addEventListener("pointermove",u),window.addEventListener("pointerup",a)},u=p=>{if(!r&&!o||!m)return;let T=(t.getElementById("canvas-wrapper")||t.getElementById("canvas-viewport"))?.getBoundingClientRect()||{width:300,height:400},l=(p.clientX-g)/Math.max(T.width,1),y=(p.clientY-d)/Math.max(T.height,1),{x:s,y:c,w:f,h:w}=m;if(o)s=Math.min(Math.max(0,s+l),1-f),c=Math.min(Math.max(0,c+y),1-w);else if(r){if(r.includes("w")){let R=Math.min(Math.max(0,s+l),s+f-.1);f+=s-R,s=R}if(r.includes("e")&&(f=Math.min(Math.max(.1,f+l),1-s)),r.includes("n")){let R=Math.min(Math.max(0,c+y),c+w-.1);w+=c-R,c=R}r.includes("s")&&(w=Math.min(Math.max(.1,w+y),1-c))}this.#h={x:s,y:c,w:f,h:w},this.#M()},a=()=>{r=null,o=!1,m=null,window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",a)};e.addEventListener("pointerdown",v),i.forEach(p=>{p.addEventListener("pointerdown",v)})}#M(){let t=this.shadowRoot;if(!t||!this.#h)return;let e=t.getElementById("crop-box");e&&(e.style.left=`${(this.#h.x*100).toFixed(1)}%`,e.style.top=`${(this.#h.y*100).toFixed(1)}%`,e.style.width=`${(this.#h.w*100).toFixed(1)}%`,e.style.height=`${(this.#h.h*100).toFixed(1)}%`)}async#w(){if(this.shadowRoot)return this.#l?this.#l:(this.#l=(async()=>{try{await Promise.resolve(),await this.#x()}finally{this.#l=null}})(),this.#l)}async#x(){if(this.shadowRoot)try{let t=await this.getPages();this.#o=t.length;let e=this.shadowRoot,i=e.getElementById("mode-badge");i&&(i.textContent=(this.mode||"single").toUpperCase());let r=e.getElementById("tab-viewfinder"),o=e.getElementById("tab-workbench");r&&r.setAttribute("aria-selected",String(this.#r==="viewfinder")),o&&o.setAttribute("aria-selected",String(this.#r==="workbench"));let g=e.getElementById("viewfinder-section"),d=e.getElementById("workbench-section");g&&d&&(this.#r==="viewfinder"?(g.style.display="flex",d.style.display="none"):(g.style.display="none",d.style.display="flex"));let m=e.getElementById("framing-guide");m&&m.setAttribute("data-aspect",this.aspect||"auto");let v=e.getElementById("step-pill-text");v&&(this.#g?v.textContent="Camera Active \xB7 Tap Shutter to Snap":this.aspect==="card"&&this.maxPages===2?v.textContent=t.length===0?"Step 1 of 2: Capture Front of ID Card":"Step 2 of 2: Capture Back of ID Card":this.aspect==="card"?v.textContent="Align Card Inside Frame":this.mode==="batch"?v.textContent=`Batch Capture \xB7 Page ${t.length+1}`:v.textContent="Align Document Inside Frame");let u=e.getElementById("btn-ocr");u&&(u.style.display=this.ocrEnabled&&this.hasFeature("ocr")?"":"none");let a=e.getElementById("btn-review"),p=e.getElementById("review-pill-text");if(a&&p&&(t.length>0?(a.style.display="inline-flex",p.textContent=`Review (${t.length}) \u2192`):a.style.display="none"),t.length===0){this.#r==="workbench"&&(this.stage="viewfinder");return}this.#s>=t.length&&(this.#s=Math.max(0,t.length-1));let x=t[this.#s],T=e.getElementById("card-side-switcher");if(T){let w=this.aspect==="card"&&this.maxPages===2;T.style.display=w?"flex":"none";let R=e.getElementById("btn-card-front"),S=e.getElementById("btn-card-back");R&&(R.classList.toggle("active",this.#s===0),R.setAttribute("aria-selected",String(this.#s===0))),S&&(S.classList.toggle("active",this.#s===1),S.setAttribute("aria-selected",String(this.#s===1)))}let l=e.getElementById("canvas-viewport");l&&l.classList.toggle("is-cropping",this.#a);let y=e.getElementById("stage-img");if(y)if(this.#a){let w=x.edits?.rotate||0,R=x.edits?.filter||"none",S=x.originalSrc||x.src||"";if(w!==0||R!=="none"){let D=this.#t?await this.#t.renderEdits(S,{rotate:w,filter:R}):S;y.src=D||S}else y.src=S}else y.src=x.src||x.originalSrc||"";let s=e.getElementById("crop-layer");if(this.#a){if(!s){let S=e.getElementById("canvas-wrapper");s=document.createElement("div"),s.className="copio-crop-layer",s.id="crop-layer",s.innerHTML=`
|
|
2449
1366
|
<div class="copio-crop-box" id="crop-box">
|
|
2450
1367
|
<div class="copio-crop-grid"></div>
|
|
2451
1368
|
<span class="copio-crop-handle nw" data-handle="nw"></span>
|
|
@@ -2457,9 +1374,9 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2457
1374
|
<span class="copio-crop-handle s edge-s" data-handle="s"></span>
|
|
2458
1375
|
<span class="copio-crop-handle w edge-w" data-handle="w"></span>
|
|
2459
1376
|
</div>
|
|
2460
|
-
`,S?.appendChild(
|
|
1377
|
+
`,S?.appendChild(s),this.#_()}s.style.display="block";let w=x.edits?.rotate||0,R=x.edits?.crop;this.#h=R?xa(R,w):{x:.05,y:.05,w:.9,h:.9},this.#M()}else s&&s.remove();let c=e.getElementById("crop-btn-label");c&&(c.textContent=this.#a?"Apply":"Crop");let f=e.getElementById("btn-primary-complete");f&&(this.aspect==="card"&&this.maxPages===2&&t.length===1?f.textContent="Next: Capture Back (Step 2/2) \u2192":this.aspect==="card"&&t.length>=2?f.textContent="\u2713 Complete ID Scan (2 Sides)":this.mode==="batch"?f.textContent=`\u2713 Complete Scan (${t.length} Pages)`:f.textContent="\u2713 Use Photo"),this.#v(t)}catch{}}#v(t){let e=this.shadowRoot;if(!e)return;let i=e.getElementById("filmstrip-scroll");i&&(i.innerHTML="",t.forEach((r,o)=>{let g=document.createElement("div");g.className=`copio-filmstrip-item ${o===this.#s?"is-active":""}`,g.setAttribute("data-index",String(o)),g.innerHTML=`
|
|
2461
1378
|
<div class="copio-thumb-container">
|
|
2462
|
-
<img src="${
|
|
1379
|
+
<img src="${r.src||r.originalSrc}" alt="Page ${o+1}" class="copio-thumb-img" />
|
|
2463
1380
|
<span class="copio-thumb-num">${o+1}</span>
|
|
2464
1381
|
</div>
|
|
2465
1382
|
${this.mode==="batch"?`
|
|
@@ -2468,21 +1385,23 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2468
1385
|
<button type="button" class="copio-reorder-btn move-right" title="Move Right" ${o===t.length-1?"disabled":""}>\u25B6</button>
|
|
2469
1386
|
</div>
|
|
2470
1387
|
`:""}
|
|
2471
|
-
`,
|
|
1388
|
+
`,g.querySelector(".copio-thumb-container")?.addEventListener("click",()=>{this.#s=o,this.#a=!1,this.#w()}),this.mode==="batch"&&(g.querySelector(".move-left")?.addEventListener("click",async d=>{d.stopPropagation(),await this.#E(o,o-1)}),g.querySelector(".move-right")?.addEventListener("click",async d=>{d.stopPropagation(),await this.#E(o,o+1)})),i.appendChild(g)}))}async#E(t,e){let i=await this.getPages();if(e<0||e>=i.length||t===e)return;let r=i.map(g=>g.id),[o]=r.splice(t,1);r.splice(e,0,o),await this.#t.reorderPages(this.#p,r),this.#s=e,this.#w()}#A(){this.#g&&(this.#g.getTracks().forEach(r=>r.stop()),this.#g=null);let t=this.shadowRoot,e=t?.getElementById("camera-video");e&&(e.srcObject=null,e.style.display="none");let i=t?.querySelector(".copio-camera-placeholder");i&&(i.style.display="")}async#C(){if(typeof this.onShutter=="function"&&await this.onShutter()!==!1)return;let t=this.shadowRoot,e=t?.getElementById("camera-video");if(this.#g&&e&&e.readyState>=2){let o=document.createElement("canvas");o.width=e.videoWidth||1280,o.height=e.videoHeight||720;let g=o.getContext("2d");if(g){g.drawImage(e,0,0,o.width,o.height);let d=await new Promise(m=>o.toBlob(m,"image/jpeg",.92));if(d){this.#A();let m=new File([d],`capture_${Date.now()}.jpg`,{type:"image/jpeg"});await this.addFiles([m]);return}}}if(!(typeof navigator<"u"&&navigator.webdriver===!0)&&typeof navigator<"u"&&navigator.mediaDevices?.getUserMedia&&e)try{this.#g=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080}},audio:!1}),e.srcObject=this.#g,e.style.display="block",await e.play();let o=t?.querySelector(".copio-camera-placeholder");o&&(o.style.display="none");let g=t?.getElementById("step-pill-text");g&&(g.textContent="Camera Active \xB7 Tap Shutter to Snap");return}catch{}let r=t?.getElementById("internal-file-input");r&&typeof r.click=="function"&&r.click()}async#T(){let e=(await this.getPages())[this.#s];if(!e)return;this.#a&&(this.#a=!1,this.#h=null);let r=((e.edits?.rotate||0)+90)%360;await this.#t.applyEdit(this.#p,e.id,{rotate:r}),await this.#w()}async#P(){let e=(await this.getPages())[this.#s];if(!e)return;this.#a&&(this.#a=!1,this.#h=null);let r=(e.edits?.filter||"none")==="bw"?"none":"bw";await this.#t.applyEdit(this.#p,e.id,{filter:r}),await this.#w()}async#D(){let e=(await this.getPages())[this.#s];if(e){if(this.#a){this.#a=!1;let i=this.#h;if(this.#h=null,i){let r=e.edits?.rotate||0,o=Aa(i,r);await this.#t.applyEdit(this.#p,e.id,{crop:o})}}else this.#a=!0;await this.#w()}}async#k(){let t=await this.getPages(),e=t[this.#s];if(!e)return;let i=e.id;await this.#t.deletePage(this.#p,i),this.dispatch(Vt.PAGE_REMOVED,{pageId:i,docId:this.docId}),this.#s>=t.length-1&&(this.#s=Math.max(0,t.length-2)),this.#L(),await this.#w()}#L(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("toast-region");if(!e)return;this.#u&&clearInterval(this.#u),this.#d=5;let i=()=>{e.innerHTML=`
|
|
2472
1389
|
<div class="copio-toast copio-toast-undo">
|
|
2473
1390
|
<span>Page deleted</span>
|
|
2474
1391
|
<button type="button" class="copio-btn-toast-undo" id="btn-toast-undo">
|
|
2475
1392
|
Undo (${this.#d}s)
|
|
2476
1393
|
</button>
|
|
2477
1394
|
</div>
|
|
2478
|
-
`,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#u),this.#u=null,e.innerHTML="",await this.#t.undo(this.#p),await this.#w()})};i(),this.#u=setInterval(()=>{this.#d-=1,this.#d<=0?(clearInterval(this.#u),this.#u=null,e.innerHTML=""):i()},1e3)}async#I(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet"),i=t.getElementById("ocr-body");if(!(!e||!i)){e.style.display="block",i.innerHTML='<p class="copio-ocr-loading">Recognizing text...</p>';try{let o=(await this.getPages())[this.#s],
|
|
1395
|
+
`,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#u),this.#u=null,e.innerHTML="",await this.#t.undo(this.#p),await this.#w()})};i(),this.#u=setInterval(()=>{this.#d-=1,this.#d<=0?(clearInterval(this.#u),this.#u=null,e.innerHTML=""):i()},1e3)}async#I(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet"),i=t.getElementById("ocr-body");if(!(!e||!i)){e.style.display="block",i.innerHTML='<p class="copio-ocr-loading">Recognizing text...</p>';try{let o=(await this.getPages())[this.#s],g=await this.ocr(o?.id||null),d=g.averageConfidence||0,m=d<=1&&d>0?Math.round(d*100):Math.round(d);i.innerHTML=`
|
|
2479
1396
|
<div class="copio-ocr-content">
|
|
2480
|
-
<pre class="copio-ocr-text">${
|
|
1397
|
+
<pre class="copio-ocr-text">${g.text||"No text detected."}</pre>
|
|
2481
1398
|
<div class="copio-ocr-meta">
|
|
2482
|
-
<span>Confidence: ${
|
|
1399
|
+
<span>Confidence: ${m}%</span>
|
|
2483
1400
|
</div>
|
|
2484
1401
|
</div>
|
|
2485
|
-
`}catch(n){i.innerHTML=`<p class="copio-ocr-error">OCR recognition failed: ${n.message}</p>`}}}#F(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet");e&&(e.style.display="none")}async#O(){if(this.aspect==="card"&&this.maxPages===2&&this.#a===1){this.stage="viewfinder";return}let t=await this.getPages();if(this.aspect==="card"&&this.maxPages===2&&t.length===1){this.stage="viewfinder";return}let e=t.map((n,o)=>({id:n.id,pageNumber:o+1,label:n.label||`Page ${o+1}`,originalSrc:n.originalSrc,src:n.src,originalPreserved:!0,dimensions:{width:n.width||0,height:n.height||0},edits:n.edits||{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:n.ocrText||null,blob:n.blob||null})),i={mode:this.mode,aspect:this.aspect,docId:this.docId,pageCount:e.length,pages:e};this.mode==="single"&&(i.page=e[0]||null,this.maxPages>1&&(i.maxPages=this.maxPages)),this.dispatch(te.SCAN_COMPLETE,i)}get theme(){return typeof this.getAttribute=="function"&&this.getAttribute("theme")||"dark"}set theme(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("theme",t):this.removeAttribute("theme"))}get mode(){return typeof this.getAttribute=="function"&&this.getAttribute("mode")||"document"}set mode(t){typeof this.setAttribute=="function"&&this.setAttribute("mode",t)}get aspect(){return typeof this.getAttribute=="function"&&this.getAttribute("aspect")||"auto"}set aspect(t){typeof this.setAttribute=="function"&&this.setAttribute("aspect",t)}get stage(){return this.#r}set stage(t){if(t==="viewfinder"||t==="workbench"){this.#r=t,typeof this.setAttribute=="function"&&this.getAttribute("stage")!==t&&this.setAttribute("stage",t);let e=this.shadowRoot;if(e){let i=e.getElementById("viewfinder-section"),n=e.getElementById("workbench-section");i&&n&&(i.style.display=t==="viewfinder"?"flex":"none",n.style.display=t==="workbench"?"flex":"none")}this.#w()}}get docId(){return typeof this.getAttribute=="function"?this.getAttribute("doc-id"):null}set docId(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("doc-id",t):this.removeAttribute("doc-id"))}async rotateActivePage(){return this.#P()}async toggleActivePageBw(){return this.#T()}async toggleCropMode(){return this.#M()}async deleteActivePageWithUndo(){return this.#k()}get features(){return this.#t?this.#t.features:[]}set features(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(" "):String(t||"");this.setAttribute("features",e)}this.#t&&this.#t.setFeatures(t)}hasFeature(t){return this.#t?this.#t.hasFeature(t):!1}get ocrEnabled(){return this.#t?this.#t.ocr:!0}set ocrEnabled(t){let e=!!t;typeof this.setAttribute=="function"&&this.setAttribute("ocr",e?"true":"false"),this.#t&&(this.#t.ocr=e),this.#m()}get pdf(){return this.#t?this.#t.pdf:!0}set pdf(t){let e=!!t;typeof this.setAttribute=="function"&&this.setAttribute("pdf",e?"true":"false"),this.#t&&(this.#t.pdf=e),this.#m()}get exportFormats(){return this.#t?this.#t.exportFormats:[]}set exportFormats(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(","):String(t||"");this.setAttribute("export-formats",e)}this.#t&&(this.#t.exportFormats=t)}get ocrLanguages(){return this.#t?this.#t.ocrLanguages:[]}set ocrLanguages(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(","):String(t||"");this.setAttribute("ocr-languages",e)}this.#t&&(this.#t.ocrLanguages=t)}get maxPages(){return this.#t?this.#t.maxPages:0}set maxPages(t){typeof this.setAttribute=="function"&&this.setAttribute("max-pages",String(t)),this.#t&&(this.#t.maxPages=t)}get assetBase(){return this.#t?this.#t.assetBase:""}set assetBase(t){typeof this.setAttribute=="function"&&this.setAttribute("asset-base",String(t||"")),this.#t&&(this.#t.assetBase=t)}get licenseKey(){return this.#t?this.#t.licenseKey:""}set licenseKey(t){typeof this.setAttribute=="function"&&this.setAttribute("license-key",String(t||"")),this.#t&&(this.#t.licenseKey=t)}get storage(){return this.#e}set storage(t){this.#e=t,this.#t&&this.#t.setStorage(t)}get engine(){return this.#t}set engine(t){t instanceof gs&&(this.#t=t)}dispatch(t,e={}){return bo(this,t,e)}async open(){this.#n=!0,typeof this.focus=="function"&&this.focus()}async close(){this.#n=!1,this.#A()}get isOpen(){return this.#n}async capture(){return new Promise(t=>{let e=document.createElement("input");e.type="file",e.accept="image/*",e.capture="environment",e.style.display="none",e.onchange=async()=>{try{if(e.files&&e.files.length>0){let i=await this.addFiles([e.files[0]]);t(i[0]||null)}else t(null)}catch(i){this.dispatch(te.ERROR,{code:"CAPTURE_FAILED",message:i.message,error:i}),t(null)}finally{e.remove()}},e.onerror=()=>{e.remove(),t(null)},document.body.appendChild(e),e.click()})}async addFiles(t){try{let e=await this.getPages(),i=null;if(e.length>0){if(this.mode==="single"&&this.maxPages<=1)await this.#t.clear(this.#p);else if(this.#l||this.maxPages>0&&e.length>=this.maxPages){let c=Math.min(this.#s,e.length-1),l=e[c];l&&(i=c,await this.#t.deletePage(this.#p,l.id))}}this.#l=!1;let n=await this.#t.addFiles(t,this.#p);for(let c=0;c<n.length;c++)this.dispatch(te.PAGE_ADDED,{page:n[c],pageNumber:c+1,docId:this.docId,source:"file"});let o=await this.getPages();if(i!==null&&n.length===1&&i<o.length-1){let c=o.map(h=>h.id),l=c.pop();l&&(c.splice(i,0,l),await this.#t.reorderPages(this.#p,c),o=await this.getPages())}return this.#a=o.length,n.length>0&&(this.#s=i!==null?Math.min(i,Math.max(0,o.length-1)):Math.max(0,o.length-1),this.mode==="single"&&(this.#r="workbench",typeof this.setAttribute=="function"&&this.getAttribute("stage")!=="workbench"&&this.setAttribute("stage","workbench"))),this.dispatch(te.PAGES_CHANGED,{pages:o,docId:this.docId}),this.mode==="single"&&n.length>0&&this.maxPages<=1&&this.dispatch(te.SCAN_COMPLETE,{mode:this.mode,aspect:this.aspect,docId:this.docId,pages:o,page:o[o.length-1]||null,pageCount:o.length}),await this.#w(),n}catch(e){throw this.dispatch(te.ERROR,{code:e.code||"ADD_FILES_FAILED",message:e.message,error:e}),e}}async getPages(){return this.#t.getPages(this.#p)}async clear(){this.#A(),this.#s=0,this.#a=0,this.#l=!1,this.#o=!1,await this.#t.clear(this.#p),this.dispatch(te.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#w()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#p,t);return this.dispatch(te.EXPORT_COMPLETE,{type:"pdf",format:"pdf",blob:e,searchable:!!t.searchable,docId:this.docId}),e}catch(e){throw this.dispatch(te.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async exportZip(t={}){try{let e=await this.#t.exportZip(this.#p,t);return this.dispatch(te.EXPORT_COMPLETE,{type:"zip",format:"zip",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(te.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async ocr(t=null,e={}){try{let i=await this.#t.runOcr(this.#p,t,e);return this.dispatch(te.OCR_COMPLETE,{text:i.text,pages:i.pagesResults,averageConfidence:i.averageConfidence,docId:this.docId,pageId:t}),i}catch(i){throw this.dispatch(te.ERROR,{code:i.code||"OCR_FAILED",message:i.message,error:i}),i}}async runOcr(t=null,e={}){return this.ocr(t,e)}async sync(t={}){try{return await this.#t.sync({onStateChange:i=>{i&&(i.step==="connected"||i.step==="syncing")&&this.dispatch(te.SYNC_CONNECTED,{peerId:i.peerId,mode:i.mode}),t.onStateChange&&t.onStateChange(i)}})}catch(e){throw this.dispatch(te.ERROR,{code:e.code||"SYNC_FAILED",message:e.message,error:e}),e}}};typeof customElements<"u"&&!customElements.get("copio-scanner")&&customElements.define("copio-scanner",or);lr();Bi();var cr=class extends se{#t=null;static properties={isOpen:{type:Boolean,state:!0},docId:{type:String,state:!0},docName:{type:String,state:!0},pages:{type:Array,state:!0},lang:{type:String,state:!0},step:{type:String,state:!0},progress:{type:Number,state:!0},statusMessage:{type:String,state:!0},resultText:{type:String,state:!0},confidence:{type:Number,state:!0},copied:{type:Boolean,state:!0}};createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.#t&&(this.#t.abort(),this.#t=null),ji(),this.isOpen=!1}constructor(){super(),this.isOpen=!1,this.docId="",this.docName="",this.pages=[],this.lang="eng",this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine...",this.resultText="",this.confidence=0,this.copied=!1,this._pageIndex=null,this.#t=null}open(t,e,i,n="eng"){this._pageIndex=null,this._openInternal(t,e,i,n)}openPage(t,e,i,n,o="eng"){this._pageIndex=n,this._openInternal(t,e,[i],o)}_openInternal(t,e,i,n){if(this.#t&&(this.#t.abort(),this.#t=null),this.docId=t,this.docName=e||"Document",this.pages=i||[],this.lang=n,this.progress=0,this.resultText="",this.confidence=0,this.copied=!1,(this.pages||[]).filter(c=>c.src).length===0){this.step="empty",this.statusMessage="This document does not contain any image pages for text recognition.",this.isOpen=!0;return}this.step="processing",this.statusMessage=typeof window<"u"&&!window.Tesseract?"Downloading OCR engine...":"Starting OCR engine...",this.isOpen=!0,this.startOcr(n)}cancel=()=>{this.#t&&(this.#t.abort(),this.#t=null),this.close()};close=()=>{this.#t&&(this.#t.abort(),this.#t=null),this.isOpen=!1};async startOcr(t="eng"){this.#t&&(this.#t.abort(),this.#t=null),this.#t=new AbortController;let{signal:e}=this.#t;try{let i=await Ss(this.pages,{lang:t,abortSignal:e,onPageProgress:({overallProgress:n,message:o})=>{this.isOpen&&!e.aborted&&(this.progress=Math.round((n||0)*100),this.statusMessage=o)}});if(this.isOpen&&!e.aborted&&(this.step="done",this.resultText=i.combinedText||"",this.confidence=i.averageConfidence||0,Mt.success("Text recognition complete"),this.docId&&Array.isArray(i.pagesResults)))try{let n=await Ys.getDoc(this.docId);if(n&&Array.isArray(n.pages)){for(let o of i.pagesResults){let c=n.pages.find(l=>l.id===o.pageId)||n.pages[o.pageIndex];c&&(c.ocrText=o.text,c.ocrConfidence=o.confidence,c.ocrWords=o.words)}await Ys.saveDoc(this.docId,n)}}catch(n){console.warn("Could not persist OCR results to document:",n)}}catch(i){if(i.name==="AbortError"||e.aborted)return;console.error("Document OCR Error:",i),this.isOpen&&(this.step="error",this.statusMessage=i.message||"Text recognition failed",Mt.error(i.message||"Text recognition failed"))}finally{this.#t?.signal===e&&(this.#t=null)}}handleLangChange=t=>{let e=t.target.value;this.lang=e,this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine with new language...",this.startOcr(e)};handleTextInput=t=>{this.resultText=t.target.value};copyText=async()=>{if(this.resultText)try{await navigator.clipboard.writeText(this.resultText),this.copied=!0,Mt.success("Copied text to clipboard"),setTimeout(()=>{this.copied=!1},2e3)}catch(t){console.error("Failed to copy text:",t),Mt.error("Failed to copy text to clipboard")}};downloadText=()=>{if(!this.resultText)return;let t=(this.docName||"document").replace(/[/\\?%*:|"<>]/g,"_"),e=new Blob([this.resultText],{type:"text/plain;charset=utf-8"}),i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=`${t}-ocr.txt`,n.click(),URL.revokeObjectURL(i),Mt.success(`Exported OCR text (${t}-ocr.txt)`)};get _isSinglePage(){return this._pageIndex!==null}get _dialogLabel(){return this._isSinglePage?`Extract Text \u2014 ${this.docName} (Page ${this._pageIndex+1})`:`Extract All Text \u2014 ${this.docName}`}render(){return this.isOpen?Rt`
|
|
1402
|
+
`}catch(r){i.innerHTML=`<p class="copio-ocr-error">OCR recognition failed: ${r.message}</p>`}}}#F(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet");e&&(e.style.display="none")}async#O(){if(this.aspect==="card"&&this.maxPages===2&&this.#o===1){this.stage="viewfinder";return}let t=await this.getPages();if(this.aspect==="card"&&this.maxPages===2&&t.length===1){this.stage="viewfinder";return}let e=t.map((r,o)=>({id:r.id,pageNumber:o+1,label:r.label||`Page ${o+1}`,originalSrc:r.originalSrc,src:r.src,originalPreserved:!0,dimensions:{width:r.width||0,height:r.height||0},edits:r.edits||{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:r.ocrText||null,blob:r.blob||null})),i={mode:this.mode,aspect:this.aspect,docId:this.docId,pageCount:e.length,pages:e};this.mode==="single"&&(i.page=e[0]||null,this.maxPages>1&&(i.maxPages=this.maxPages)),this.dispatch(Vt.SCAN_COMPLETE,i)}get theme(){return typeof this.getAttribute=="function"&&this.getAttribute("theme")||"dark"}set theme(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("theme",t):this.removeAttribute("theme"))}get mode(){return typeof this.getAttribute=="function"&&this.getAttribute("mode")||"document"}set mode(t){typeof this.setAttribute=="function"&&this.setAttribute("mode",t)}get aspect(){return typeof this.getAttribute=="function"&&this.getAttribute("aspect")||"auto"}set aspect(t){typeof this.setAttribute=="function"&&this.setAttribute("aspect",t)}get stage(){return this.#r}set stage(t){if(t==="viewfinder"||t==="workbench"){this.#r=t,typeof this.setAttribute=="function"&&this.getAttribute("stage")!==t&&this.setAttribute("stage",t);let e=this.shadowRoot;if(e){let i=e.getElementById("viewfinder-section"),r=e.getElementById("workbench-section");i&&r&&(i.style.display=t==="viewfinder"?"flex":"none",r.style.display=t==="workbench"?"flex":"none")}this.#w()}}get docId(){return typeof this.getAttribute=="function"?this.getAttribute("doc-id"):null}set docId(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("doc-id",t):this.removeAttribute("doc-id"))}async rotateActivePage(){return this.#T()}async toggleActivePageBw(){return this.#P()}async toggleCropMode(){return this.#D()}async deleteActivePageWithUndo(){return this.#k()}setCameraStream(t){this.#A(),this.#g=t}get features(){return this.#t?this.#t.features:[]}set features(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(" "):String(t||"");this.setAttribute("features",e)}this.#t&&this.#t.setFeatures(t)}hasFeature(t){return this.#t?this.#t.hasFeature(t):!1}get ocrEnabled(){return this.#t?this.#t.ocr:!0}set ocrEnabled(t){let e=!!t;typeof this.setAttribute=="function"&&this.setAttribute("ocr",e?"true":"false"),this.#t&&(this.#t.ocr=e),this.#m()}get pdf(){return this.#t?this.#t.pdf:!0}set pdf(t){let e=!!t;typeof this.setAttribute=="function"&&this.setAttribute("pdf",e?"true":"false"),this.#t&&(this.#t.pdf=e),this.#m()}get exportFormats(){return this.#t?this.#t.exportFormats:[]}set exportFormats(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(","):String(t||"");this.setAttribute("export-formats",e)}this.#t&&(this.#t.exportFormats=t)}get ocrLanguages(){return this.#t?this.#t.ocrLanguages:[]}set ocrLanguages(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(","):String(t||"");this.setAttribute("ocr-languages",e)}this.#t&&(this.#t.ocrLanguages=t)}get maxPages(){return this.#t?this.#t.maxPages:0}set maxPages(t){typeof this.setAttribute=="function"&&this.setAttribute("max-pages",String(t)),this.#t&&(this.#t.maxPages=t)}get assetBase(){return this.#t?this.#t.assetBase:""}set assetBase(t){typeof this.setAttribute=="function"&&this.setAttribute("asset-base",String(t||"")),this.#t&&(this.#t.assetBase=t)}get licenseKey(){return this.#t?this.#t.licenseKey:""}set licenseKey(t){typeof this.setAttribute=="function"&&this.setAttribute("license-key",String(t||"")),this.#t&&(this.#t.licenseKey=t)}get storage(){return this.#e}set storage(t){this.#e=t,this.#t&&this.#t.setStorage(t)}get engine(){return this.#t}set engine(t){t instanceof Oi&&(this.#t=t)}dispatch(t,e={}){return lr(this,t,e)}async open(){this.#n=!0,typeof this.focus=="function"&&this.focus()}async close(){this.#n=!1,this.#A()}get isOpen(){return this.#n}async capture(){return new Promise(t=>{let e=document.createElement("input");e.type="file",e.accept="image/*",e.capture="environment",e.style.display="none",e.onchange=async()=>{try{if(e.files&&e.files.length>0){let i=await this.addFiles([e.files[0]]);t(i[0]||null)}else t(null)}catch(i){this.dispatch(Vt.ERROR,{code:"CAPTURE_FAILED",message:i.message,error:i}),t(null)}finally{e.remove()}},e.onerror=()=>{e.remove(),t(null)},document.body.appendChild(e),e.click()})}async addFiles(t){try{let e=await this.getPages(),i=null;if(e.length>0){if(this.mode==="single"&&this.maxPages<=1)await this.#t.clear(this.#p);else if(this.#c||this.maxPages>0&&e.length>=this.maxPages){let g=Math.min(this.#s,e.length-1),d=e[g];d&&(i=g,await this.#t.deletePage(this.#p,d.id))}}this.#c=!1;let r=await this.#t.addFiles(t,this.#p);for(let g=0;g<r.length;g++)this.dispatch(Vt.PAGE_ADDED,{page:r[g],pageNumber:g+1,docId:this.docId,source:"file"});let o=await this.getPages();if(i!==null&&r.length===1&&i<o.length-1){let g=o.map(m=>m.id),d=g.pop();d&&(g.splice(i,0,d),await this.#t.reorderPages(this.#p,g),o=await this.getPages())}return this.#o=o.length,r.length>0&&(this.#s=i!==null?Math.min(i,Math.max(0,o.length-1)):Math.max(0,o.length-1),this.mode==="single"&&(this.#r="workbench",typeof this.setAttribute=="function"&&this.getAttribute("stage")!=="workbench"&&this.setAttribute("stage","workbench"))),this.dispatch(Vt.PAGES_CHANGED,{pages:o,docId:this.docId}),this.mode==="single"&&r.length>0&&this.maxPages<=1&&this.dispatch(Vt.SCAN_COMPLETE,{mode:this.mode,aspect:this.aspect,docId:this.docId,pages:o,page:o[o.length-1]||null,pageCount:o.length}),await this.#w(),r}catch(e){throw this.dispatch(Vt.ERROR,{code:e.code||"ADD_FILES_FAILED",message:e.message,error:e}),e}}async getPages(){return this.#t.getPages(this.#p)}async clear(){this.#A(),this.#s=0,this.#o=0,this.#c=!1,this.#a=!1,await this.#t.clear(this.#p),this.dispatch(Vt.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#w()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#p,t);return this.dispatch(Vt.EXPORT_COMPLETE,{type:"pdf",format:"pdf",blob:e,searchable:!!t.searchable,docId:this.docId}),e}catch(e){throw this.dispatch(Vt.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async exportZip(t={}){try{let e=await this.#t.exportZip(this.#p,t);return this.dispatch(Vt.EXPORT_COMPLETE,{type:"zip",format:"zip",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(Vt.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async ocr(t=null,e={}){try{let i=await this.#t.runOcr(this.#p,t,e);return this.dispatch(Vt.OCR_COMPLETE,{text:i.text,pages:i.pagesResults,averageConfidence:i.averageConfidence,docId:this.docId,pageId:t}),i}catch(i){throw this.dispatch(Vt.ERROR,{code:i.code||"OCR_FAILED",message:i.message,error:i}),i}}async runOcr(t=null,e={}){return this.ocr(t,e)}async sync(t={}){try{return await this.#t.sync({onStateChange:i=>{i&&(i.step==="connected"||i.step==="syncing")&&this.dispatch(Vt.SYNC_CONNECTED,{peerId:i.peerId,mode:i.mode}),t.onStateChange&&t.onStateChange(i)}})}catch(e){throw this.dispatch(Vt.ERROR,{code:e.code||"SYNC_FAILED",message:e.message,error:e}),e}}};typeof customElements<"u"&&!customElements.get("copio-scanner")&&customElements.define("copio-scanner",zs);var pr=globalThis,Oa=pr.ShadowRoot&&(pr.ShadyCSS===void 0||pr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Lc=Symbol(),Ec=new WeakMap,ka=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Lc)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.i,e=this.t;if(Oa&&t===void 0){let i=e!==void 0&&e.length===1;i&&(t=Ec.get(e)),t===void 0&&((this.i=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Ec.set(e,t))}return t}toString(){return this.cssText}},yh=n=>new ka(typeof n=="string"?n:n+"",void 0,Lc);var vh=(n,t)=>{if(Oa)n.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let i=document.createElement("style"),r=pr.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=e.cssText,n.appendChild(i)}},_c=Oa?n=>n:n=>n instanceof CSSStyleSheet?(t=>{let e="";for(let i of t.cssRules)e+=i.cssText;return yh(e)})(n):n,{is:wh,defineProperty:xh,getOwnPropertyDescriptor:Ah,getOwnPropertyNames:Sh,getOwnPropertySymbols:Eh,getPrototypeOf:_h}=Object,gr=globalThis,Cc=gr.trustedTypes,Ch=Cc?Cc.emptyScript:"",Ph=gr.reactiveElementPolyfillSupport,Ws=(n,t)=>n,Ra={toAttribute(n,t){switch(t){case Boolean:n=n?Ch:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,t){let e=n;switch(t){case Boolean:e=n!==null;break;case Number:e=n===null?null:Number(n);break;case Object:case Array:try{e=JSON.parse(n)}catch{e=null}}return e}},Fc=(n,t)=>!wh(n,t),Pc={attribute:!0,type:String,converter:Ra,reflect:!1,useDefault:!1,hasChanged:Fc};Symbol.metadata??=Symbol("metadata"),gr.litPropertyMetadata??=new WeakMap;var oi=class extends HTMLElement{static addInitializer(t){this.o(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this.u&&[...this.u.keys()]}static createProperty(t,e=Pc){if(e.state&&(e.attribute=!1),this.o(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let i=Symbol(),r=this.getPropertyDescriptor(t,i,e);r!==void 0&&xh(this.prototype,t,r)}}static getPropertyDescriptor(t,e,i){let{get:r,set:o}=Ah(this.prototype,t)??{get(){return this[e]},set(g){this[e]=g}};return{get:r,set(g){let d=r?.call(this);o?.call(this,g),this.requestUpdate(t,d,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Pc}static o(){if(this.hasOwnProperty(Ws("elementProperties")))return;let t=_h(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Ws("finalized")))return;if(this.finalized=!0,this.o(),this.hasOwnProperty(Ws("properties"))){let e=this.properties,i=[...Sh(e),...Eh(e)];for(let r of i)this.createProperty(r,e[r])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[i,r]of e)this.elementProperties.set(i,r)}this.u=new Map;for(let[e,i]of this.elementProperties){let r=this.p(e,i);r!==void 0&&this.u.set(r,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let r of i)e.unshift(_c(r))}else t!==void 0&&e.push(_c(t));return e}static p(t,e){let i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this.v=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this.m=null,this._()}_(){this.S=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this.$(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this.P??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this.P?.delete(t)}$(){let t=new Map,e=this.constructor.elementProperties;for(let i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this.v=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return vh(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this.P?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this.P?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,i){this._$AK(t,i)}C(t,e){let i=this.constructor.elementProperties.get(t),r=this.constructor.p(t,i);if(r!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:Ra).toAttribute(e,i.type);this.m=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this.m=null}}_$AK(t,e){let i=this.constructor,r=i.u.get(t);if(r!==void 0&&this.m!==r){let o=i.getPropertyOptions(r),g=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:Ra;this.m=r;let d=g.fromAttribute(e,o.type);this[r]=d??this.T?.get(r)??d,this.m=null}}requestUpdate(t,e,i){if(t!==void 0){let r=this.constructor,o=this[t];if(i??=r.getPropertyOptions(t),!((i.hasChanged??Fc)(o,e)||i.useDefault&&i.reflect&&o===this.T?.get(t)&&!this.hasAttribute(r.p(t,i))))return;this.M(t,e,i)}this.isUpdatePending===!1&&(this.S=this.k())}M(t,e,{useDefault:i,reflect:r,wrapped:o},g){i&&!(this.T??=new Map).has(t)&&(this.T.set(t,g??e??this[t]),o!==!0||g!==void 0)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),r===!0&&this.m!==t&&(this.A??=new Set).add(t))}async k(){this.isUpdatePending=!0;try{await this.S}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this.v){for(let[r,o]of this.v)this[r]=o;this.v=void 0}let i=this.constructor.elementProperties;if(i.size>0)for(let[r,o]of i){let{wrapped:g}=o,d=this[r];g!==!0||this._$AL.has(r)||d===void 0||this.M(r,void 0,o,d)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this.P?.forEach((i=>i.hostUpdate?.())),this.update(e)):this.U()}catch(i){throw t=!1,this.U(),i}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this.P?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}U(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this.S}shouldUpdate(t){return!0}update(t){this.A&&=this.A.forEach((e=>this.C(e,this[e]))),this.U()}updated(t){}firstUpdated(t){}};oi.elementStyles=[],oi.shadowRootOptions={mode:"open"},oi[Ws("elementProperties")]=new Map,oi[Ws("finalized")]=new Map,Ph?.({ReactiveElement:oi}),(gr.reactiveElementVersions??=[]).push("2.1.1");var Na=globalThis,fr=Na.trustedTypes,Tc=fr?fr.createPolicy("lit-html",{createHTML:n=>n}):void 0,Oc="$lit$",ci=`lit$${Math.random().toFixed(9).slice(2)}$`,Nc="?"+ci,Th=`<${Nc}>`,$i=document,Gs=()=>$i.createComment(""),qs=n=>n===null||typeof n!="object"&&typeof n!="function",Ba=Array.isArray,kh=n=>Ba(n)||typeof n?.[Symbol.iterator]=="function",Ta=`[
|
|
1403
|
+
\f\r]`,Vs=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,kc=/-->/g,Rc=/>/g,Bi=RegExp(`>|${Ta}(?:([^\\s"'>=/]+)(${Ta}*=${Ta}*(?:[^
|
|
1404
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Mc=/'/g,Dc=/"/g,Bc=/^(?:script|style|textarea|title)$/i,Ua=n=>(t,...e)=>({_$litType$:n,strings:t,values:e}),Wt=Ua(1),Du=Ua(2),Iu=Ua(3),ps=Symbol.for("lit-noChange"),Kt=Symbol.for("lit-nothing"),Ic=new WeakMap,Ui=$i.createTreeWalker($i,129);function Uc(n,t){if(!Ba(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return Tc!==void 0?Tc.createHTML(t):t}var Rh=(n,t)=>{let e=n.length-1,i=[],r,o=t===2?"<svg>":t===3?"<math>":"",g=Vs;for(let d=0;d<e;d++){let m=n[d],v,u,a=-1,p=0;for(;p<m.length&&(g.lastIndex=p,u=g.exec(m),u!==null);)p=g.lastIndex,g===Vs?u[1]==="!--"?g=kc:u[1]!==void 0?g=Rc:u[2]!==void 0?(Bc.test(u[2])&&(r=RegExp("</"+u[2],"g")),g=Bi):u[3]!==void 0&&(g=Bi):g===Bi?u[0]===">"?(g=r??Vs,a=-1):u[1]===void 0?a=-2:(a=g.lastIndex-u[2].length,v=u[1],g=u[3]===void 0?Bi:u[3]==='"'?Dc:Mc):g===Dc||g===Mc?g=Bi:g===kc||g===Rc?g=Vs:(g=Bi,r=void 0);let x=g===Bi&&n[d+1].startsWith("/>")?" ":"";o+=g===Vs?m+Th:a>=0?(i.push(v),m.slice(0,a)+Oc+m.slice(a)+ci+x):m+ci+(a===-2?d:x)}return[Uc(n,o+(n[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},Xs=class n{constructor({strings:t,_$litType$:e},i){let r;this.parts=[];let o=0,g=0,d=t.length-1,m=this.parts,[v,u]=Rh(t,e);if(this.el=n.createElement(v,i),Ui.currentNode=this.el.content,e===2||e===3){let a=this.el.content.firstChild;a.replaceWith(...a.childNodes)}for(;(r=Ui.nextNode())!==null&&m.length<d;){if(r.nodeType===1){if(r.hasAttributes())for(let a of r.getAttributeNames())if(a.endsWith(Oc)){let p=u[g++],x=r.getAttribute(a).split(ci),T=/([.?@])?(.*)/.exec(p);m.push({type:1,index:o,name:T[2],strings:x,ctor:T[1]==="."?Da:T[1]==="?"?Ia:T[1]==="@"?La:gs}),r.removeAttribute(a)}else a.startsWith(ci)&&(m.push({type:6,index:o}),r.removeAttribute(a));if(Bc.test(r.tagName)){let a=r.textContent.split(ci),p=a.length-1;if(p>0){r.textContent=fr?fr.emptyScript:"";for(let x=0;x<p;x++)r.append(a[x],Gs()),Ui.nextNode(),m.push({type:2,index:++o});r.append(a[p],Gs())}}}else if(r.nodeType===8)if(r.data===Nc)m.push({type:2,index:o});else{let a=-1;for(;(a=r.data.indexOf(ci,a+1))!==-1;)m.push({type:7,index:o}),a+=ci.length-1}o++}}static createElement(t,e){let i=$i.createElement("template");return i.innerHTML=t,i}};function fs(n,t,e=n,i){if(t===ps)return t;let r=i!==void 0?e.N?.[i]:e.O,o=qs(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(n),r._$AT(n,e,i)),i!==void 0?(e.N??=[])[i]=r:e.O=r),r!==void 0&&(t=fs(n,r._$AS(n,t.values),r,i)),t}var Ma=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}R(t){let{el:{content:e},parts:i}=this._$AD,r=(t?.creationScope??$i).importNode(e,!0);Ui.currentNode=r;let o=Ui.nextNode(),g=0,d=0,m=i[0];for(;m!==void 0;){if(g===m.index){let v;m.type===2?v=new Ks(o,o.nextSibling,this,t):m.type===1?v=new m.ctor(o,m.name,m.strings,this,t):m.type===6&&(v=new Fa(o,this,t)),this._$AV.push(v),m=i[++d]}g!==m?.index&&(o=Ui.nextNode(),g++)}return Ui.currentNode=$i,r}V(t){let e=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}},Ks=class n{get _$AU(){return this._$AM?._$AU??this.D}constructor(t,e,i,r){this.type=2,this._$AH=Kt,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=r,this.D=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=fs(this,t,e),qs(t)?t===Kt||t==null||t===""?(this._$AH!==Kt&&this._$AR(),this._$AH=Kt):t!==this._$AH&&t!==ps&&this.L(t):t._$litType$!==void 0?this.j(t):t.nodeType!==void 0?this.I(t):kh(t)?this.H(t):this.L(t)}B(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}I(t){this._$AH!==t&&(this._$AR(),this._$AH=this.B(t))}L(t){this._$AH!==Kt&&qs(this._$AH)?this._$AA.nextSibling.data=t:this.I($i.createTextNode(t)),this._$AH=t}j(t){let{values:e,_$litType$:i}=t,r=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=Xs.createElement(Uc(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.V(e);else{let o=new Ma(r,this),g=o.R(this.options);o.V(e),this.I(g),this._$AH=o}}_$AC(t){let e=Ic.get(t.strings);return e===void 0&&Ic.set(t.strings,e=new Xs(t)),e}H(t){Ba(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,i,r=0;for(let o of t)r===e.length?e.push(i=new n(this.B(Gs()),this.B(Gs()),this,this.options)):i=e[r],i._$AI(o),r++;r<e.length&&(this._$AR(i&&i._$AB.nextSibling,r),e.length=r)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t!==this._$AB;){let i=t.nextSibling;t.remove(),t=i}}setConnected(t){this._$AM===void 0&&(this.D=t,this._$AP?.(t))}},gs=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,i,r,o){this.type=1,this._$AH=Kt,this._$AN=void 0,this.element=t,this.name=e,this._$AM=r,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Kt}_$AI(t,e=this,i,r){let o=this.strings,g=!1;if(o===void 0)t=fs(this,t,e,0),g=!qs(t)||t!==this._$AH&&t!==ps,g&&(this._$AH=t);else{let d=t,m,v;for(t=o[0],m=0;m<o.length-1;m++)v=fs(this,d[i+m],e,m),v===ps&&(v=this._$AH[m]),g||=!qs(v)||v!==this._$AH[m],v===Kt?t=Kt:t!==Kt&&(t+=(v??"")+o[m+1]),this._$AH[m]=v}g&&!r&&this.W(t)}W(t){t===Kt?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Da=class extends gs{constructor(){super(...arguments),this.type=3}W(t){this.element[this.name]=t===Kt?void 0:t}},Ia=class extends gs{constructor(){super(...arguments),this.type=4}W(t){this.element.toggleAttribute(this.name,!!t&&t!==Kt)}},La=class extends gs{constructor(t,e,i,r,o){super(t,e,i,r,o),this.type=5}_$AI(t,e=this){if((t=fs(this,t,e,0)??Kt)===ps)return;let i=this._$AH,r=t===Kt&&i!==Kt||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==Kt&&(i===Kt||r);r&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Fa=class{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){fs(this,t)}};var Mh=Na.litHtmlPolyfillSupport;Mh?.(Xs,Ks),(Na.litHtmlVersions??=[]).push("3.3.1");var Dh=(n,t,e)=>{let i=e?.renderBefore??t,r=i._$litPart$;if(r===void 0){let o=e?.renderBefore??null;i._$litPart$=r=new Ks(t.insertBefore(Gs(),o),o,void 0,e??{})}return r._$AI(n),r},$a=globalThis;var Ce=class extends oi{constructor(){super(...arguments),this.renderOptions={host:this},this.rt=void 0}createRenderRoot(){let t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this.rt=Dh(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this.rt?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this.rt?.setConnected(!1)}render(){return ps}};Ce._$litElement$=!0,Ce.finalized=!0,$a.litElementHydrateSupport?.({LitElement:Ce});var Ih=$a.litElementPolyfillSupport;Ih?.({LitElement:Ce});($a.litElementVersions??=[]).push("4.2.1");Js();Ni();var Qs=class extends Ce{#t=null;static properties={isOpen:{type:Boolean,state:!0},docId:{type:String,state:!0},docName:{type:String,state:!0},pages:{type:Array,state:!0},lang:{type:String,state:!0},step:{type:String,state:!0},progress:{type:Number,state:!0},statusMessage:{type:String,state:!0},resultText:{type:String,state:!0},confidence:{type:Number,state:!0},copied:{type:Boolean,state:!0}};createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.#t&&(this.#t.abort(),this.#t=null),hi(),this.isOpen=!1}constructor(){super(),this.isOpen=!1,this.docId="",this.docName="",this.pages=[],this.lang="eng",this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine...",this.resultText="",this.confidence=0,this.copied=!1,this._pageIndex=null,this.#t=null}open(t,e,i,r="eng"){this._pageIndex=null,this._openInternal(t,e,i,r)}openPage(t,e,i,r,o="eng"){this._pageIndex=r,this._openInternal(t,e,[i],o)}_openInternal(t,e,i,r){if(this.#t&&(this.#t.abort(),this.#t=null),this.docId=t,this.docName=e||"Document",this.pages=i||[],this.lang=r,this.progress=0,this.resultText="",this.confidence=0,this.copied=!1,(this.pages||[]).filter(g=>g.src).length===0){this.step="empty",this.statusMessage="This document does not contain any image pages for text recognition.",this.isOpen=!0;return}this.step="processing",this.statusMessage=typeof window<"u"&&!window.Tesseract?"Downloading OCR engine...":"Starting OCR engine...",this.isOpen=!0,this.startOcr(r)}cancel=()=>{this.#t&&(this.#t.abort(),this.#t=null),this.close()};close=()=>{this.#t&&(this.#t.abort(),this.#t=null),this.isOpen=!1};async startOcr(t="eng"){this.#t&&(this.#t.abort(),this.#t=null),this.#t=new AbortController;let{signal:e}=this.#t;try{let i=await Hi(this.pages,{lang:t,abortSignal:e,onPageProgress:({overallProgress:r,message:o})=>{this.isOpen&&!e.aborted&&(this.progress=Math.round((r||0)*100),this.statusMessage=o)}});if(this.isOpen&&!e.aborted&&(this.step="done",this.resultText=i.combinedText||"",this.confidence=i.averageConfidence||0,Dt.success("Text recognition complete"),this.docId&&Array.isArray(i.pagesResults)))try{let r=await ds.getDoc(this.docId);if(r&&Array.isArray(r.pages)){for(let o of i.pagesResults){let g=r.pages.find(d=>d.id===o.pageId)||r.pages[o.pageIndex];g&&(g.ocrText=o.text,g.ocrConfidence=o.confidence,g.ocrWords=o.words)}await ds.saveDoc(this.docId,r)}}catch(r){console.warn("Could not persist OCR results to document:",r)}}catch(i){if(i.name==="AbortError"||e.aborted)return;console.error("Document OCR Error:",i),this.isOpen&&(this.step="error",this.statusMessage=i.message||"Text recognition failed",Dt.error(i.message||"Text recognition failed"))}finally{this.#t?.signal===e&&(this.#t=null)}}handleLangChange=t=>{let e=t.target.value;this.lang=e,this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine with new language...",this.startOcr(e)};handleTextInput=t=>{this.resultText=t.target.value};copyText=async()=>{if(this.resultText)try{await navigator.clipboard.writeText(this.resultText),this.copied=!0,Dt.success("Copied text to clipboard"),setTimeout(()=>{this.copied=!1},2e3)}catch(t){console.error("Failed to copy text:",t),Dt.error("Failed to copy text to clipboard")}};downloadText=()=>{if(!this.resultText)return;let t=(this.docName||"document").replace(/[/\\?%*:|"<>]/g,"_"),e=new Blob([this.resultText],{type:"text/plain;charset=utf-8"}),i=URL.createObjectURL(e),r=document.createElement("a");r.href=i,r.download=`${t}-ocr.txt`,r.click(),URL.revokeObjectURL(i),Dt.success(`Exported OCR text (${t}-ocr.txt)`)};get _isSinglePage(){return this._pageIndex!==null}get _dialogLabel(){return this._isSinglePage?`Extract Text \u2014 ${this.docName} (Page ${this._pageIndex+1})`:`Extract All Text \u2014 ${this.docName}`}render(){return this.isOpen?Wt`
|
|
2486
1405
|
<sl-dialog
|
|
2487
1406
|
label="${this._dialogLabel}"
|
|
2488
1407
|
open
|
|
@@ -2496,10 +1415,10 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2496
1415
|
@sl-change=${this.handleLangChange}
|
|
2497
1416
|
style="min-width: 180px;"
|
|
2498
1417
|
>
|
|
2499
|
-
${
|
|
1418
|
+
${Ys.map(t=>Wt`<sl-option value=${t.code}>${t.flag} ${t.label}</sl-option>`)}
|
|
2500
1419
|
</sl-select>
|
|
2501
1420
|
|
|
2502
|
-
${this.step==="done"?
|
|
1421
|
+
${this.step==="done"?Wt`
|
|
2503
1422
|
<sl-badge
|
|
2504
1423
|
variant=${this.confidence>=75?"success":this.confidence>=50?"warning":"danger"}
|
|
2505
1424
|
>
|
|
@@ -2508,7 +1427,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2508
1427
|
`:""}
|
|
2509
1428
|
</div>
|
|
2510
1429
|
|
|
2511
|
-
${this.step==="empty"?
|
|
1430
|
+
${this.step==="empty"?Wt`
|
|
2512
1431
|
<div style="padding: 2.5rem 1rem; text-align: center; color: #64748b;">
|
|
2513
1432
|
<sl-icon name="file-earmark-x" style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #94a3b8;"></sl-icon>
|
|
2514
1433
|
<p style="margin: 0; font-size: 1rem; color: #334155; font-weight: 500;">${this.statusMessage}</p>
|
|
@@ -2516,7 +1435,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2516
1435
|
</div>
|
|
2517
1436
|
`:""}
|
|
2518
1437
|
|
|
2519
|
-
${this.step==="processing"?
|
|
1438
|
+
${this.step==="processing"?Wt`
|
|
2520
1439
|
<div style="padding: 2.5rem 1rem; text-align: center;">
|
|
2521
1440
|
<div style="font-size: 1.1rem; color: #0284c7; font-weight: 600; margin-bottom: 1rem;">
|
|
2522
1441
|
${this.statusMessage}
|
|
@@ -2528,14 +1447,14 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2528
1447
|
</div>
|
|
2529
1448
|
`:""}
|
|
2530
1449
|
|
|
2531
|
-
${this.step==="error"?
|
|
1450
|
+
${this.step==="error"?Wt`
|
|
2532
1451
|
<div style="padding: 2rem; text-align: center; color: #ef4444;">
|
|
2533
1452
|
<sl-icon name="x-circle-fill" style="font-size: 2rem;"></sl-icon>
|
|
2534
1453
|
<p style="margin-top: 0.5rem;">${this.statusMessage}</p>
|
|
2535
1454
|
</div>
|
|
2536
1455
|
`:""}
|
|
2537
1456
|
|
|
2538
|
-
${this.step==="done"?
|
|
1457
|
+
${this.step==="done"?Wt`
|
|
2539
1458
|
<div>
|
|
2540
1459
|
<sl-textarea
|
|
2541
1460
|
rows="14"
|
|
@@ -2546,18 +1465,18 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2546
1465
|
</div>
|
|
2547
1466
|
`:""}
|
|
2548
1467
|
|
|
2549
|
-
${this.step==="processing"?
|
|
1468
|
+
${this.step==="processing"?Wt`
|
|
2550
1469
|
<sl-button slot="footer" variant="default" @click=${this.cancel}>
|
|
2551
1470
|
<sl-icon slot="prefix" name="x-lg"></sl-icon>
|
|
2552
1471
|
Cancel
|
|
2553
1472
|
</sl-button>
|
|
2554
1473
|
`:""}
|
|
2555
|
-
${this.step==="empty"||this.step==="error"?
|
|
1474
|
+
${this.step==="empty"||this.step==="error"?Wt`
|
|
2556
1475
|
<sl-button slot="footer" variant="default" @click=${this.close}>
|
|
2557
1476
|
Close
|
|
2558
1477
|
</sl-button>
|
|
2559
1478
|
`:""}
|
|
2560
|
-
${this.step==="done"?
|
|
1479
|
+
${this.step==="done"?Wt`
|
|
2561
1480
|
<sl-button slot="footer" variant="default" @click=${this.close}>
|
|
2562
1481
|
Close
|
|
2563
1482
|
</sl-button>
|
|
@@ -2571,9 +1490,9 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2571
1490
|
</sl-button>
|
|
2572
1491
|
`:""}
|
|
2573
1492
|
</sl-dialog>
|
|
2574
|
-
`:""}};customElements.define("copio-doc-ocr-dialog",
|
|
1493
|
+
`:""}};customElements.define("copio-doc-ocr-dialog",Qs);var Zs=class extends Ce{static properties={syncState:{type:Object}};createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.closeSyncDialog()}handleCloseClick=()=>{let t=this.querySelector("sl-dialog");t&&typeof t.hide=="function"?t.hide():this.closeSyncDialog()};closeSyncDialog=()=>{this.dispatchEvent(new CustomEvent("dialog:close",{bubbles:!0,composed:!1}))};render(){if(!this.syncState)return"";let{step:t,qrSvg:e,url:i,added:r,message:o}=this.syncState,g;return t==="init"?g=Wt`<sl-spinner></sl-spinner> Setting up…`:t==="waiting"?g=Wt`
|
|
2575
1494
|
<div .innerHTML=${e}></div>
|
|
2576
|
-
${i?
|
|
1495
|
+
${i?Wt`
|
|
2577
1496
|
<div style="margin: 0.75rem 0; word-break: break-all;">
|
|
2578
1497
|
<a
|
|
2579
1498
|
class="sync-link"
|
|
@@ -2587,28 +1506,32 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2587
1506
|
</div>
|
|
2588
1507
|
`:""}
|
|
2589
1508
|
<p style="margin-top: 0.5rem; color: #6b7280; font-size: 0.9rem;">Waiting for other device…</p>
|
|
2590
|
-
`:t==="connecting"?
|
|
2591
|
-
Sync complete — ${
|
|
2592
|
-
</p>`:t==="error"&&(
|
|
1509
|
+
`:t==="connecting"?g=Wt`<sl-spinner></sl-spinner> Connecting…`:t==="syncing"?g=Wt`<sl-spinner></sl-spinner> Syncing…`:t==="done"?g=Wt`<p>
|
|
1510
|
+
Sync complete — ${r} doc${r!==1?"s":""} added.
|
|
1511
|
+
</p>`:t==="error"&&(g=Wt`<p style="color:var(--sl-color-danger-600)">
|
|
2593
1512
|
Error: ${o}
|
|
2594
|
-
</p>`),
|
|
1513
|
+
</p>`),Wt`
|
|
2595
1514
|
<sl-dialog
|
|
2596
1515
|
label="Link Device"
|
|
2597
1516
|
open
|
|
2598
1517
|
@sl-after-hide=${this.closeSyncDialog}
|
|
2599
1518
|
>
|
|
2600
|
-
<div style="text-align:center;padding:1rem">${
|
|
1519
|
+
<div style="text-align:center;padding:1rem">${g}</div>
|
|
2601
1520
|
<sl-button slot="footer" class="sync-close-btn" @click=${this.handleCloseClick}
|
|
2602
1521
|
>Close</sl-button
|
|
2603
1522
|
>
|
|
2604
1523
|
</sl-dialog>
|
|
2605
|
-
`}};customElements.define("copio-sync-dialog",hr);var zo=class{constructor(t=null){this.key=t}setKey(t){this.key=t}getKey(){return this.key}isValid(){return!!this.key}getTier(){return this.key?this.key.startsWith("pro_")?"pro":this.key.startsWith("ent_")?"enterprise":"commercial":"community"}};lr();Bi();var Ip="https://copio.metered.live/api/v1/turn/credentials?apiKey=d90f0b0b6bdf180ea68238f5c2185074ce37",Lp=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.relay.metered.ca:80"}],Fp=5e3;async function ad(){let s=new AbortController,t=setTimeout(()=>s.abort(),Fp);try{let e=await fetch(Ip,{signal:s.signal,cache:"no-store"});if(!e.ok)throw new Error(`HTTP ${e.status}`);let i=await e.json();if(!Array.isArray(i)||i.length===0)throw new Error("Empty ICE server list");return[{urls:"stun:stun.l.google.com:19302"},...i]}catch(e){return console.warn("[Sync] Failed to fetch TURN credentials, using STUN only:",e),Lp}finally{clearTimeout(t)}}ci();var Op=3e4,Vi=class{#t=null;#e=null;#i=null;#n=null;#r=0;#s=null;constructor(t,e){this.#e=t,this.#i=e}get state(){return this.#n}#a(t){this.#n=t,this.#i&&this.#i(this.#n)}#l(t){clearTimeout(this.#s),this.#n&&this.#a({...this.#n,step:"error",message:t})}async#o(){let t=++this.#r,[e,i]=await Promise.all([ad(),po()]);return t!==this.#r?null:new i({config:{iceServers:e}})}#h(t){t.on("error",i=>this.#l(i.message));let e=t.peerConnection;e&&e.addEventListener("iceconnectionstatechange",()=>{console.log("[Sync] ICE state:",e.iceConnectionState),e.iceConnectionState==="failed"&&this.#l("Could not connect to the other device. Check both are online and try again.")})}#u(){clearTimeout(this.#s),this.#s=setTimeout(()=>{let t=this.#n?.step;t&&t!=="done"&&t!=="error"&&this.#l("Connection timed out. Try again.")},Op)}#d(t){let e=()=>{clearTimeout(this.#s),this.#a({...this.#n,step:"syncing"}),this.#g(t)};t.open?e():t.on("open",e)}startHost(){if(this.#n?.mode!=="host"){if(!navigator.onLine){Mt.warning("An internet connection is needed to link devices.",{icon:"wifi-off",duration:4e3});return}this.#a({mode:"host",step:"init"}),this.#c().catch(t=>{this.#a({mode:"host",step:"error",message:t.message})})}}async#c(){let t=await this.#o();t&&(this.#t=t,t.on("error",e=>this.#l(e.message)),t.on("open",async e=>{let i=`${location.origin}${location.pathname}?peer=${e}`,o=(await fo())(0,"M");o.addData(i),o.make(),this.#a({mode:"host",step:"waiting",qrSvg:o.createSvgTag(4,8),url:i,peerId:e})}),t.on("connection",e=>{this.#u(),this.#h(e),this.#d(e)}))}startJoiner(t){this.#n?.mode!=="joiner"&&(this.#a({mode:"joiner",step:"connecting"}),this.#u(),this.#f(t).catch(e=>{this.#a({mode:"joiner",step:"error",message:e.message})}))}async#f(t){let e=await this.#o();e&&(this.#t=e,e.on("error",i=>this.#l(i.message)),e.on("open",()=>{let i=e.connect(t);this.#h(i),this.#d(i)}))}#g(t){t.on("data",async e=>{let i;try{i=typeof e=="string"?JSON.parse(e):e}catch(o){console.error("Failed to parse sync data:",o);return}let n=0;typeof this.#e?.importDocs=="function"?n=await this.#e.importDocs(i):typeof this.#e?.transaction=="function"&&this.#e.transaction(()=>{for(let[o,c]of Object.entries(i||{}))this.#e.hasRow("docs",o)||n++,this.#e.setRow("docs",o,c)}),this.#a({...this.#n,step:"done",added:n}),Mt.success(`Sync complete \u2014 ${n} doc${n!==1?"s":""} added`)}),(async()=>{try{let e;typeof this.#e?.exportAll=="function"?e=await this.#e.exportAll():typeof this.#e?.getTable=="function"?e=this.#e.getTable("docs"):e={},t.send(JSON.stringify(e))}catch(e){console.error("Failed to send sync data:",e),this.#l(e.message)}})()}close(){this.#r++,clearTimeout(this.#s),this.#t?.destroy(),this.#t=null,this.#a(null)}};var Rl={};ei(Rl,{exportDocumentAsImages:()=>Dl,exportDocumentAsPdf:()=>dr});Bi();ci();async function dr(s,t,e={}){let{onProgress:i,showProgress:n=!0,download:o=!0,searchable:c=!1,lang:l="eng",onOcrComplete:h=null}=e;if(!t||t.length===0){Mt.warning("No images to export");return}let m=null,u=t.length;try{n&&u>1&&(m=await Mt.progress({message:`Exporting "${s||"document"}.pdf"...`,total:u,done:0}));let a=null;if(typeof window<"u"&&!window.PDFDocument){typeof i=="function"&&i(0,u,"Downloading PDF engine...");try{a=await Mt.progress({message:"Downloading PDF engine...",total:100,done:0})}catch{}}let w;try{w=await ho()}finally{a?.close()}let E=595.28,p=841.89,y=new w({autoFirstPage:!1}),r=[];y.on("data",b=>r.push(b));let d=new Promise((b,x)=>{y.on("end",()=>{try{let _=new Blob(r,{type:"application/pdf"});if(o!==!1){let S=URL.createObjectURL(_),R=document.createElement("a");R.href=S,R.download=`${s||"document"}.pdf`,R.click(),URL.revokeObjectURL(S),Mt.success(`Exported "${s||"document"}.pdf"`)}m?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"pdf",format:"pdf",blob:_,docName:s||"document",searchable:!!c}})),b(_)}catch(_){x(_)}}),y.on("error",x)});for(let b=0;b<t.length;b++){let x=t[b],_=b+1;if(x.src||x.blob){let S=new Image,R=null,N=x.src;if(x.blob instanceof Blob&&(!N||N instanceof Blob)?(N=URL.createObjectURL(x.blob),R=N):x.src instanceof Blob&&(N=URL.createObjectURL(x.src),R=N),await new Promise(H=>{S.onload=H,S.onerror=z=>{console.warn("Page image failed to load for PDF:",z),H(void 0)},S.src=N}),S.width&&S.height){y.addPage({size:"A4"});let H=E/S.width,z=p/S.height,K=Math.min(H,z),it=S.width*K,at=S.height*K,X=(E-it)/2,j=(p-at)/2,W=null;if(x.blob instanceof Blob)W=await x.blob.arrayBuffer();else if(x.src instanceof Blob)W=await x.src.arrayBuffer();else if(typeof x.src=="string"&&x.src.startsWith("blob:"))try{W=await(await(await fetch(x.src)).blob()).arrayBuffer()}catch{}if(W?y.image(W,X,j,{width:it,height:at}):y.image(N,X,j,{width:it,height:at}),c){let Y=Array.isArray(x.ocrWords)&&x.ocrWords.length>0?x.ocrWords:null;if(!Y&&(x.src||x.blob)){typeof i=="function"&&i(_,u,`Recognizing text for page ${_} of ${u}...`),m&&m.update({done:_,total:u,message:`Recognizing text for page ${_} of ${u}...`});try{let st=await(e.recognizeImageText||(await Promise.resolve().then(()=>(lr(),od))).recognizeImageText)(x.blob||x.src,{lang:l});Y=st?.words||[],x.ocrText=st?.text||"",x.ocrConfidence=st?.confidence??0,x.ocrWords=Y,x.ocrWidth=S.width,x.ocrHeight=S.height}catch(tt){console.warn(`On-demand OCR failed for page ${_}:`,tt)}}if(Y&&Y.length>0){y.save(),y.font("Helvetica");let tt=x.ocrWidth||S.width,st=x.ocrHeight||S.height,lt=it/tt,nt=at/st;for(let G of Y){let A=(G.text||"").trim();if(!A)continue;let T=G.bbox||{},I=T.x0??0,g=T.y0??0,v=Math.max(1,(T.x1??0)-I),P=Math.max(1,(T.y1??0)-g),k=X+I*lt,O=j+g*nt,M=v*lt,C=P*nt,L=Math.max(1,C);y.fontSize(L);let $=y.widthOfString(A),B=0;$>0&&A.length>1&&(B=(M-$)/(A.length-1)),y.text(A,k,O,{renderingMode:3,lineBreak:!1,characterSpacing:B})}y.restore()}}}if(R)try{URL.revokeObjectURL(R)}catch{}}typeof i=="function"&&i(_,u),m&&m.update({done:_,total:u,message:`Exporting PDF: page ${_} of ${u}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"pdf",done:_,total:u,docName:s||"document"}})),await new Promise(S=>setTimeout(S,0))}if(c&&typeof h=="function")try{await h(t)}catch(b){console.warn("onOcrComplete error:",b)}return y.end(),await d}catch(a){m?.close(),console.error("Error generating PDF:",a),Mt.error("Failed to generate PDF")}}async function Dl(s,t,e={}){let{onProgress:i,showProgress:n=!0,download:o=!0}=e;if(!t||t.length===0){Mt.warning("No images to export");return}let c=null;try{let l=(s||"document").trim(),m=(p=>p.replace(/[/\\?%*:|"<>]/g,"_"))(l)||"document";if(t.length===1){let p=t[0],y="jpg",r="",d=!1,b=null;if(p.blob instanceof Blob)b=p.blob,b.type&&b.type.includes("png")&&(y="png"),r=URL.createObjectURL(b),d=!0;else if(p.src instanceof Blob)b=p.src,b.type&&b.type.includes("png")&&(y="png"),r=URL.createObjectURL(b),d=!0;else if(typeof p.src=="string")if(r=p.src,p.src.startsWith("data:")){let x=p.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);x&&x[1].includes("png")&&(y="png");try{b=await(await fetch(p.src)).blob()}catch{b=new Blob([p.src],{type:`image/${y}`})}}else if(p.src.startsWith("blob:"))try{b=await(await fetch(p.src)).blob(),b.type&&b.type.includes("png")&&(y="png")}catch{}else try{b=await(await fetch(p.src)).blob(),r=URL.createObjectURL(b),d=!0}catch{}if(typeof i=="function"&&i(1,1),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"image",done:1,total:1,docName:m}})),o!==!1){let x=document.createElement("a");x.href=r,x.download=`${m}.${y}`,x.click(),Mt.success(`Exported "${m}.${y}"`)}return d&&URL.revokeObjectURL(r),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"image",format:y,blob:b,docName:m}})),b}let u=t.length;n&&u>1&&(c=await Mt.progress({message:`Exporting "${m}.zip"...`,total:u,done:0}));let a=await uo(),f=new a,w=0;for(let p=0;p<t.length;p++){let y=t[p],r=[y.blob||y.src],d=Math.max(2,String(t.length*r.length).length);for(let x=0;x<r.length;x++){let _=r[x],S="jpg",R=null;if(_ instanceof Blob)_.type&&_.type.includes("png")&&(S="png"),R=await _.arrayBuffer();else if(typeof _=="string"&&_.startsWith("data:")){let N=_.match(/^data:(image\/[a-zA-Z+]+);base64,(.*)$/),H="";N?(N[1].includes("png")&&(S="png"),H=N[2]):H=_.replace(/^data:[^;]+;base64,/,"");let z=String(w+1).padStart(d,"0"),K=`${m}-${z}.${S}`;f.file(K,H,{base64:!0}),w++;continue}else if(typeof _=="string")try{let H=await(await fetch(_)).blob();H.type&&H.type.includes("png")&&(S="png"),R=await H.arrayBuffer()}catch{}if(R){let N=String(w+1).padStart(d,"0"),H=`${m}-${N}.${S}`;f.file(H,R),w++}}let b=p+1;typeof i=="function"&&i(b,u),c&&c.update({done:b,total:u,message:`Exporting ZIP: page ${b} of ${u}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"zip",done:b,total:u,docName:m}})),await new Promise(x=>setTimeout(x,0))}c&&c.update({message:"Compressing archive..."});let E=await f.generateAsync({type:"blob"},p=>{c&&p.percent&&c.update({value:Math.round(p.percent),message:`Compressing ZIP: ${Math.round(p.percent)}%...`})});if(o!==!1){let p=URL.createObjectURL(E),y=document.createElement("a");y.href=p,y.download=`${m}.zip`,y.click(),URL.revokeObjectURL(p),Mt.success(`Exported "${m}.zip"`)}return c?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"zip",format:"zip",blob:E,docName:m}})),E}catch(l){c?.close(),console.error("Error downloading images:",l),Mt.error("Failed to download images")}}Bi();ci();lr();var Es=class extends hi{async recognizeImageText(t,e={}){return dn(t,e)}async recognizeDocumentPages(t,e={}){return Ss(t,e)}async getOcrWorker(t="eng",e=null){return hn(t,e)}async terminateOcrWorker(){return ji()}};var Cs=class extends di{async exportDocumentAsPdf(t,e,i={}){return dr(t,e,i)}async renderPdfPagesToDataUrls(t){let e=t instanceof ArrayBuffer?t:await t.arrayBuffer();return on(e)}};var mi=class{async connect(t={}){throw new Error("SyncPort.connect() must be implemented by adapter")}async disconnect(){throw new Error("SyncPort.disconnect() must be implemented by adapter")}};var ur=class extends mi{#t=null;#e=null;#i=null;constructor(t=null,e=null){super(),this.#e=t,this.#i=e}async connect(t={}){let e=t.repo||this.#e,i=t.onStateChange||this.#i;return this.#t=new Vi(e,i),this.#t}async disconnect(){this.#t&&typeof this.#t.destroy=="function"&&(this.#t.destroy(),this.#t=null)}};var pr=class extends mi{async connect(){return{step:"disconnected",peerId:null,destroy:()=>{}}}async disconnect(){}};Mi("export",Rl);Mi("ocr",new Es);Mi("sync",Vi);Mi("pdf",new Cs);Mi("imageProcessor",new ui);typeof window<"u"&&(window.Copio=jo);var iy=jo;export{ih as BUILD_DATE,te as COPIO_EVENTS,ui as Canvas2DAdapter,tr as CopioAddEditDialog,Zn as CopioCarousel,cr as CopioDocOcrDialog,gs as CopioEngine,ir as CopioHeader,Gn as CopioImages,sr as CopioLoader,er as CopioRow,or as CopioScanner,hr as CopioSyncDialog,ki as DocRepository,Mn as Document,Ke as ImageProcessorPort,Ge as IndexedDbStorageAdapter,zo as LicenseManager,Ai as MemoryStorageAdapter,ps as NullImageProcessorAdapter,Re as NullOcrAdapter,Xe as NullPdfAdapter,pr as NullSyncAdapter,hi as OcrPort,ss as OpfsStorageAdapter,fs as Page,Cs as PdfKitAdapter,di as PdfPort,ur as PeerJsAdapter,ar as SUPPORTED_LANGUAGES,In as ScanSession,ke as StoragePort,Vi as SyncManager,mi as SyncPort,Es as TesseractWasmAdapter,sh as VERSION,Uo as adoptScannerStyles,ml as clearNotifications,Us as createDefaultAdapter,iy as default,bo as dispatchCopioEvent,Ys as docRepository,Dl as exportDocumentAsImages,dr as exportDocumentAsPdf,qs as extractExif,Xs as fileToBase64,lo as getAssetBase,Ni as getContainer,Ha as getCroppedSrc,hn as getOcrWorker,Ri as getRegisteredService,$o as getScannerStyleSheet,mo as hasActiveEdits,co as loadCropper,uo as loadJsZip,ho as loadPdfKit,po as loadPeerJs,fo as loadQrCode,Di as loadScript,go as loadTesseract,Js as normalizeEditStack,Mt as notify,Kr as probeOpfs,De as randomId,Ss as recognizeDocumentPages,dn as recognizeImageText,Mi as registerService,on as renderPdfPagesToDataUrls,li as resolveAssetUrl,Ua as rotateSrc,rr as scannerCss,us as setAssetBase,Oi as setContainer,ji as terminateOcrWorker,$a as thresholdSrc};
|
|
2606
|
-
/**!
|
|
2607
|
-
* Sortable 1.15.6
|
|
2608
|
-
*
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
1524
|
+
`}};customElements.define("copio-sync-dialog",Zs);var br=class{constructor(t=null){this.key=t}setKey(t){this.key=t}getKey(){return this.key}isValid(){return!!this.key}getTier(){return this.key?this.key.startsWith("pro_")?"pro":this.key.startsWith("ent_")?"enterprise":"commercial":"community"}};Js();Ni();var Oh="https://copio.metered.live/api/v1/turn/credentials?apiKey=d90f0b0b6bdf180ea68238f5c2185074ce37",Nh=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.relay.metered.ca:80"}],Bh=5e3;async function Hc(){let n=new AbortController,t=setTimeout(()=>n.abort(),Bh);try{let e=await fetch(Oh,{signal:n.signal,cache:"no-store"});if(!e.ok)throw new Error(`HTTP ${e.status}`);let i=await e.json();if(!Array.isArray(i)||i.length===0)throw new Error("Empty ICE server list");return[{urls:"stun:stun.l.google.com:19302"},...i]}catch(e){return console.warn("[Sync] Failed to fetch TURN credentials, using STUN only:",e),Nh}finally{clearTimeout(t)}}ii();var Uh=3e4,di=class{#t=null;#e=null;#i=null;#n=null;#r=0;#s=null;constructor(t,e){this.#e=t,this.#i=e}get state(){return this.#n}#o(t){this.#n=t,this.#i&&this.#i(this.#n)}#c(t){clearTimeout(this.#s),this.#n&&this.#o({...this.#n,step:"error",message:t})}async#a(){let t=++this.#r,[e,i]=await Promise.all([Hc(),rr()]);return t!==this.#r?null:new i({config:{iceServers:e}})}#h(t){t.on("error",i=>this.#c(i.message));let e=t.peerConnection;e&&e.addEventListener("iceconnectionstatechange",()=>{console.log("[Sync] ICE state:",e.iceConnectionState),e.iceConnectionState==="failed"&&this.#c("Could not connect to the other device. Check both are online and try again.")})}#u(){clearTimeout(this.#s),this.#s=setTimeout(()=>{let t=this.#n?.step;t&&t!=="done"&&t!=="error"&&this.#c("Connection timed out. Try again.")},Uh)}#d(t){let e=()=>{clearTimeout(this.#s),this.#o({...this.#n,step:"syncing"}),this.#g(t)};t.open?e():t.on("open",e)}startHost(){if(this.#n?.mode!=="host"){if(!navigator.onLine){Dt.warning("An internet connection is needed to link devices.",{icon:"wifi-off",duration:4e3});return}this.#o({mode:"host",step:"init"}),this.#l().catch(t=>{this.#o({mode:"host",step:"error",message:t.message})})}}async#l(){let t=await this.#a();t&&(this.#t=t,t.on("error",e=>this.#c(e.message)),t.on("open",async e=>{let i=`${location.origin}${location.pathname}?peer=${e}`,o=(await ar())(0,"M");o.addData(i),o.make(),this.#o({mode:"host",step:"waiting",qrSvg:o.createSvgTag(4,8),url:i,peerId:e})}),t.on("connection",e=>{this.#u(),this.#h(e),this.#d(e)}))}startJoiner(t){this.#n?.mode!=="joiner"&&(this.#o({mode:"joiner",step:"connecting"}),this.#u(),this.#f(t).catch(e=>{this.#o({mode:"joiner",step:"error",message:e.message})}))}async#f(t){let e=await this.#a();e&&(this.#t=e,e.on("error",i=>this.#c(i.message)),e.on("open",()=>{let i=e.connect(t);this.#h(i),this.#d(i)}))}#g(t){t.on("data",async e=>{let i;try{i=typeof e=="string"?JSON.parse(e):e}catch(o){console.error("Failed to parse sync data:",o);return}let r=0;typeof this.#e?.importDocs=="function"?r=await this.#e.importDocs(i):typeof this.#e?.transaction=="function"&&this.#e.transaction(()=>{for(let[o,g]of Object.entries(i||{}))this.#e.hasRow("docs",o)||r++,this.#e.setRow("docs",o,g)}),this.#o({...this.#n,step:"done",added:r}),Dt.success(`Sync complete \u2014 ${r} doc${r!==1?"s":""} added`)}),(async()=>{try{let e;typeof this.#e?.exportAll=="function"?e=await this.#e.exportAll():typeof this.#e?.getTable=="function"?e=this.#e.getTable("docs"):e={},t.send(JSON.stringify(e))}catch(e){console.error("Failed to send sync data:",e),this.#c(e.message)}})()}close(){this.#r++,clearTimeout(this.#s),this.#t?.destroy(),this.#t=null,this.#o(null)}};var ja={};Re(ja,{exportDocumentAsImages:()=>Ha,exportDocumentAsPdf:()=>tn});Ni();ii();async function tn(n,t,e={}){let{onProgress:i,showProgress:r=!0,download:o=!0,searchable:g=!1,lang:d="eng",onOcrComplete:m=null}=e;if(!t||t.length===0){Dt.warning("No images to export");return}let v=null,u=t.length;try{r&&u>1&&(v=await Dt.progress({message:`Exporting "${n||"document"}.pdf"...`,total:u,done:0}));let a=null;if(typeof window<"u"&&!window.PDFDocument){typeof i=="function"&&i(0,u,"Downloading PDF engine...");try{a=await Dt.progress({message:"Downloading PDF engine...",total:100,done:0})}catch{}}let x;try{x=await sr()}finally{a?.close()}let T=595.28,l=841.89,y=new x({autoFirstPage:!1}),s=[];y.on("data",f=>s.push(f));let c=new Promise((f,w)=>{y.on("end",()=>{try{let R=new Blob(s,{type:"application/pdf"});if(o!==!1){let S=URL.createObjectURL(R),D=document.createElement("a");D.href=S,D.download=`${n||"document"}.pdf`,D.click(),URL.revokeObjectURL(S),Dt.success(`Exported "${n||"document"}.pdf"`)}v?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"pdf",format:"pdf",blob:R,docName:n||"document",searchable:!!g}})),f(R)}catch(R){w(R)}}),y.on("error",w)});for(let f=0;f<t.length;f++){let w=t[f],R=f+1;if(w.src||w.blob){let S=new Image,D=null,N=w.src;if(w.blob instanceof Blob&&(!N||N instanceof Blob)?(N=URL.createObjectURL(w.blob),D=N):w.src instanceof Blob&&(N=URL.createObjectURL(w.src),D=N),await new Promise(H=>{S.onload=H,S.onerror=j=>{console.warn("Page image failed to load for PDF:",j),H(void 0)},S.src=N}),S.width&&S.height){y.addPage({size:"A4"});let H=T/S.width,j=l/S.height,Y=Math.min(H,j),it=S.width*Y,ot=S.height*Y,K=(T-it)/2,z=(l-ot)/2,W=null;if(w.blob instanceof Blob)W=await w.blob.arrayBuffer();else if(w.src instanceof Blob)W=await w.src.arrayBuffer();else if(typeof w.src=="string"&&w.src.startsWith("blob:"))try{W=await(await(await fetch(w.src)).blob()).arrayBuffer()}catch{}if(W?y.image(W,K,z,{width:it,height:ot}):y.image(N,K,z,{width:it,height:ot}),g){let X=Array.isArray(w.ocrWords)&&w.ocrWords.length>0?w.ocrWords:null;if(!X&&(w.src||w.blob)){typeof i=="function"&&i(R,u,`Recognizing text for page ${R} of ${u}...`),v&&v.update({done:R,total:u,message:`Recognizing text for page ${R} of ${u}...`});try{let st=await(e.recognizeImageText||(await Promise.resolve().then(()=>(Js(),$c))).recognizeImageText)(w.blob||w.src,{lang:d});X=st?.words||[],w.ocrText=st?.text||"",w.ocrConfidence=st?.confidence??0,w.ocrWords=X,w.ocrWidth=S.width,w.ocrHeight=S.height}catch(et){console.warn(`On-demand OCR failed for page ${R}:`,et)}}if(X&&X.length>0){y.save(),y.font("Helvetica");let et=w.ocrWidth||S.width,st=w.ocrHeight||S.height,ct=it/et,nt=ot/st;for(let G of X){let A=(G.text||"").trim();if(!A)continue;let _=G.bbox||{},I=_.x0??0,h=_.y0??0,b=Math.max(1,(_.x1??0)-I),C=Math.max(1,(_.y1??0)-h),P=K+I*ct,O=z+h*nt,M=b*ct,E=C*nt,L=Math.max(1,E);y.fontSize(L);let U=y.widthOfString(A),B=0;U>0&&A.length>1&&(B=(M-U)/(A.length-1)),y.text(A,P,O,{renderingMode:3,lineBreak:!1,characterSpacing:B})}y.restore()}}}if(D)try{URL.revokeObjectURL(D)}catch{}}typeof i=="function"&&i(R,u),v&&v.update({done:R,total:u,message:`Exporting PDF: page ${R} of ${u}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"pdf",done:R,total:u,docName:n||"document"}})),await new Promise(S=>setTimeout(S,0))}if(g&&typeof m=="function")try{await m(t)}catch(f){console.warn("onOcrComplete error:",f)}return y.end(),await c}catch(a){v?.close(),console.error("Error generating PDF:",a),Dt.error("Failed to generate PDF")}}async function Ha(n,t,e={}){let{onProgress:i,showProgress:r=!0,download:o=!0}=e;if(!t||t.length===0){Dt.warning("No images to export");return}let g=null;try{let d=(n||"document").trim(),v=(l=>l.replace(/[/\\?%*:|"<>]/g,"_"))(d)||"document";if(t.length===1){let l=t[0],y="jpg",s="",c=!1,f=null;if(l.blob instanceof Blob)f=l.blob,f.type&&f.type.includes("png")&&(y="png"),s=URL.createObjectURL(f),c=!0;else if(l.src instanceof Blob)f=l.src,f.type&&f.type.includes("png")&&(y="png"),s=URL.createObjectURL(f),c=!0;else if(typeof l.src=="string")if(s=l.src,l.src.startsWith("data:")){let w=l.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);w&&w[1].includes("png")&&(y="png");try{f=await(await fetch(l.src)).blob()}catch{f=new Blob([l.src],{type:`image/${y}`})}}else if(l.src.startsWith("blob:"))try{f=await(await fetch(l.src)).blob(),f.type&&f.type.includes("png")&&(y="png")}catch{}else try{f=await(await fetch(l.src)).blob(),s=URL.createObjectURL(f),c=!0}catch{}if(typeof i=="function"&&i(1,1),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"image",done:1,total:1,docName:v}})),o!==!1){let w=document.createElement("a");w.href=s,w.download=`${v}.${y}`,w.click(),Dt.success(`Exported "${v}.${y}"`)}return c&&URL.revokeObjectURL(s),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"image",format:y,blob:f,docName:v}})),f}let u=t.length;r&&u>1&&(g=await Dt.progress({message:`Exporting "${v}.zip"...`,total:u,done:0}));let a=await nr(),p=new a,x=0;for(let l=0;l<t.length;l++){let y=t[l],s=[y.blob||y.src],c=Math.max(2,String(t.length*s.length).length);for(let w=0;w<s.length;w++){let R=s[w],S="jpg",D=null;if(R instanceof Blob)R.type&&R.type.includes("png")&&(S="png"),D=await R.arrayBuffer();else if(typeof R=="string"&&R.startsWith("data:")){let N=R.match(/^data:(image\/[a-zA-Z+]+);base64,(.*)$/),H="";N?(N[1].includes("png")&&(S="png"),H=N[2]):H=R.replace(/^data:[^;]+;base64,/,"");let j=String(x+1).padStart(c,"0"),Y=`${v}-${j}.${S}`;p.file(Y,H,{base64:!0}),x++;continue}else if(typeof R=="string")try{let H=await(await fetch(R)).blob();H.type&&H.type.includes("png")&&(S="png"),D=await H.arrayBuffer()}catch{}if(D){let N=String(x+1).padStart(c,"0"),H=`${v}-${N}.${S}`;p.file(H,D),x++}}let f=l+1;typeof i=="function"&&i(f,u),g&&g.update({done:f,total:u,message:`Exporting ZIP: page ${f} of ${u}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"zip",done:f,total:u,docName:v}})),await new Promise(w=>setTimeout(w,0))}g&&g.update({message:"Compressing archive..."});let T=await p.generateAsync({type:"blob"},l=>{g&&l.percent&&g.update({value:Math.round(l.percent),message:`Compressing ZIP: ${Math.round(l.percent)}%...`})});if(o!==!1){let l=URL.createObjectURL(T),y=document.createElement("a");y.href=l,y.download=`${v}.zip`,y.click(),URL.revokeObjectURL(l),Dt.success(`Exported "${v}.zip"`)}return g?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"zip",format:"zip",blob:T,docName:v}})),T}catch(d){g?.close(),console.error("Error downloading images:",d),Dt.error("Failed to download images")}}Ni();var ys,en,sn,yr,nd={976:(n,t,e)=>{e.d(t,{AnnotationLayer:()=>_,FreeTextAnnotationElement:()=>j,InkAnnotationElement:()=>X,StampAnnotationElement:()=>G});var i=e(292),r=e(419),o=e(792);function g(I){return Math.floor(255*Math.max(0,Math.min(1,I))).toString(16).padStart(2,"0")}function d(I){return Math.max(0,Math.min(255,255*I))}class m{static CMYK_G([h,b,C,P]){return["G",1-Math.min(1,.3*h+.59*C+.11*b+P)]}static G_CMYK([h]){return["CMYK",0,0,0,1-h]}static G_RGB([h]){return["RGB",h,h,h]}static G_rgb([h]){return[h=d(h),h,h]}static G_HTML([h]){let b=g(h);return`#${b}${b}${b}`}static RGB_G([h,b,C]){return["G",.3*h+.59*b+.11*C]}static RGB_rgb(h){return h.map(d)}static RGB_HTML(h){return`#${h.map(g).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([h,b,C,P]){return["RGB",1-Math.min(1,h+P),1-Math.min(1,C+P),1-Math.min(1,b+P)]}static CMYK_rgb([h,b,C,P]){return[d(1-Math.min(1,h+P)),d(1-Math.min(1,C+P)),d(1-Math.min(1,b+P))]}static CMYK_HTML(h){let b=this.CMYK_RGB(h).slice(1);return this.RGB_HTML(b)}static RGB_CMYK([h,b,C]){let P=1-h,O=1-b,M=1-C;return["CMYK",P,O,M,Math.min(P,O,M)]}}var v=e(284);let u=1e3,a=new WeakSet;function p(I){return{width:I[2]-I[0],height:I[3]-I[1]}}class x{static create(h){switch(h.data.annotationType){case i.AnnotationType.LINK:return new l(h);case i.AnnotationType.TEXT:return new y(h);case i.AnnotationType.WIDGET:switch(h.data.fieldType){case"Tx":return new c(h);case"Btn":return h.data.radioButton?new R(h):h.data.checkBox?new w(h):new S(h);case"Ch":return new D(h);case"Sig":return new f(h)}return new s(h);case i.AnnotationType.POPUP:return new N(h);case i.AnnotationType.FREETEXT:return new j(h);case i.AnnotationType.LINE:return new Y(h);case i.AnnotationType.SQUARE:return new it(h);case i.AnnotationType.CIRCLE:return new ot(h);case i.AnnotationType.POLYLINE:return new K(h);case i.AnnotationType.CARET:return new W(h);case i.AnnotationType.INK:return new X(h);case i.AnnotationType.POLYGON:return new z(h);case i.AnnotationType.HIGHLIGHT:return new et(h);case i.AnnotationType.UNDERLINE:return new st(h);case i.AnnotationType.SQUIGGLY:return new ct(h);case i.AnnotationType.STRIKEOUT:return new nt(h);case i.AnnotationType.STAMP:return new G(h);case i.AnnotationType.FILEATTACHMENT:return new A(h);default:return new T(h)}}}class T{#t=!1;constructor(h,{isRenderable:b=!1,ignoreBorder:C=!1,createQuadrilaterals:P=!1}={}){this.isRenderable=b,this.data=h.data,this.layer=h.layer,this.linkService=h.linkService,this.downloadManager=h.downloadManager,this.imageResourcesPath=h.imageResourcesPath,this.renderForms=h.renderForms,this.svgFactory=h.svgFactory,this.annotationStorage=h.annotationStorage,this.enableScripting=h.enableScripting,this.hasJSActions=h.hasJSActions,this._fieldObjects=h.fieldObjects,this.parent=h.parent,b&&(this.container=this._createContainer(C)),P&&this._createQuadrilaterals()}static _hasPopupData({titleObj:h,contentsObj:b,richText:C}){return!!(h?.str||b?.str||C?.str)}get hasPopupData(){return T._hasPopupData(this.data)}_createContainer(h){let{data:b,parent:{page:C,viewport:P}}=this,O=document.createElement("section");O.setAttribute("data-annotation-id",b.id),this instanceof s||(O.tabIndex=u),O.style.zIndex=this.parent.zIndex++,b.popupRef&&O.setAttribute("aria-haspopup","dialog"),b.alternativeText&&(O.title=b.alternativeText),b.noRotate&&O.classList.add("norotate");let{pageWidth:M,pageHeight:E,pageX:L,pageY:U}=P.rawDims;if(!b.rect||this instanceof N){let{rotation:Q}=b;return b.hasOwnCanvas||Q===0||this.setRotation(Q,O),O}let{width:B,height:k}=p(b.rect),F=i.Util.normalizeRect([b.rect[0],C.view[3]-b.rect[1]+C.view[1],b.rect[2],C.view[3]-b.rect[3]+C.view[1]]);if(!h&&b.borderStyle.width>0){O.style.borderWidth=`${b.borderStyle.width}px`;let Q=b.borderStyle.horizontalCornerRadius,Z=b.borderStyle.verticalCornerRadius;if(Q>0||Z>0){let rt=`calc(${Q}px * var(--scale-factor)) / calc(${Z}px * var(--scale-factor))`;O.style.borderRadius=rt}else if(this instanceof R){let rt=`calc(${B}px * var(--scale-factor)) / calc(${k}px * var(--scale-factor))`;O.style.borderRadius=rt}switch(b.borderStyle.style){case i.AnnotationBorderStyleType.SOLID:O.style.borderStyle="solid";break;case i.AnnotationBorderStyleType.DASHED:O.style.borderStyle="dashed";break;case i.AnnotationBorderStyleType.BEVELED:(0,i.warn)("Unimplemented border style: beveled");break;case i.AnnotationBorderStyleType.INSET:(0,i.warn)("Unimplemented border style: inset");break;case i.AnnotationBorderStyleType.UNDERLINE:O.style.borderBottomStyle="solid"}let tt=b.borderColor||null;tt?(this.#t=!0,O.style.borderColor=i.Util.makeHexColor(0|tt[0],0|tt[1],0|tt[2])):O.style.borderWidth=0}O.style.left=100*(F[0]-L)/M+"%",O.style.top=100*(F[1]-U)/E+"%";let{rotation:V}=b;return b.hasOwnCanvas||V===0?(O.style.width=100*B/M+"%",O.style.height=100*k/E+"%"):this.setRotation(V,O),O}setRotation(h,b=this.container){if(!this.data.rect)return;let{pageWidth:C,pageHeight:P}=this.parent.viewport.rawDims,{width:O,height:M}=p(this.data.rect),E,L;h%180==0?(E=100*O/C,L=100*M/P):(E=100*M/C,L=100*O/P),b.style.width=`${E}%`,b.style.height=`${L}%`,b.setAttribute("data-main-rotation",(360-h)%360)}get _commonActions(){let h=(b,C,P)=>{let O=P.detail[b],M=O[0],E=O.slice(1);P.target.style[C]=m[`${M}_HTML`](E),this.annotationStorage.setValue(this.data.id,{[C]:m[`${M}_rgb`](E)})};return(0,i.shadow)(this,"_commonActions",{display:b=>{let{display:C}=b.detail,P=C%2==1;this.container.style.visibility=P?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:P,noPrint:C===1||C===2})},print:b=>{this.annotationStorage.setValue(this.data.id,{noPrint:!b.detail.print})},hidden:b=>{let{hidden:C}=b.detail;this.container.style.visibility=C?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:C,noView:C})},focus:b=>{setTimeout((()=>b.target.focus({preventScroll:!1})),0)},userName:b=>{b.target.title=b.detail.userName},readonly:b=>{b.target.disabled=b.detail.readonly},required:b=>{this._setRequired(b.target,b.detail.required)},bgColor:b=>{h("bgColor","backgroundColor",b)},fillColor:b=>{h("fillColor","backgroundColor",b)},fgColor:b=>{h("fgColor","color",b)},textColor:b=>{h("textColor","color",b)},borderColor:b=>{h("borderColor","borderColor",b)},strokeColor:b=>{h("strokeColor","borderColor",b)},rotation:b=>{let C=b.detail.rotation;this.setRotation(C),this.annotationStorage.setValue(this.data.id,{rotation:C})}})}_dispatchEventFromSandbox(h,b){let C=this._commonActions;for(let P of Object.keys(b.detail))(h[P]||C[P])?.(b)}_setDefaultPropertiesFromJS(h){if(!this.enableScripting)return;let b=this.annotationStorage.getRawValue(this.data.id);if(!b)return;let C=this._commonActions;for(let[P,O]of Object.entries(b)){let M=C[P];M&&(M({detail:{[P]:O},target:h}),delete b[P])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:h}=this.data;if(!h)return;let[b,C,P,O]=this.data.rect;if(h.length===1){let[,{x:Z,y:tt},{x:rt,y:pt}]=h[0];if(P===Z&&O===tt&&b===rt&&C===pt)return}let{style:M}=this.container,E;if(this.#t){let{borderColor:Z,borderWidth:tt}=M;M.borderWidth=0,E=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${Z}" stroke-width="${tt}">`],this.container.classList.add("hasBorder")}let L=P-b,U=O-C,{svgFactory:B}=this,k=B.createElement("svg");k.classList.add("quadrilateralsContainer"),k.setAttribute("width",0),k.setAttribute("height",0);let F=B.createElement("defs");k.append(F);let V=B.createElement("clipPath"),Q=`clippath_${this.data.id}`;V.setAttribute("id",Q),V.setAttribute("clipPathUnits","objectBoundingBox"),F.append(V);for(let[,{x:Z,y:tt},{x:rt,y:pt}]of h){let dt=B.createElement("rect"),lt=(rt-b)/L,vt=(O-tt)/U,Et=(Z-rt)/L,wt=(tt-pt)/U;dt.setAttribute("x",lt),dt.setAttribute("y",vt),dt.setAttribute("width",Et),dt.setAttribute("height",wt),V.append(dt),E?.push(`<rect vector-effect="non-scaling-stroke" x="${lt}" y="${vt}" width="${Et}" height="${wt}"/>`)}this.#t&&(E.push("</g></svg>')"),M.backgroundImage=E.join("")),this.container.append(k),this.container.style.clipPath=`url(#${Q})`}_createPopup(){let{container:h,data:b}=this;h.setAttribute("aria-haspopup","dialog");let C=new N({data:{color:b.color,titleObj:b.titleObj,modificationDate:b.modificationDate,contentsObj:b.contentsObj,richText:b.richText,parentRect:b.rect,borderStyle:0,id:`popup_${b.id}`,rotation:b.rotation},parent:this.parent,elements:[this]});this.parent.div.append(C.render())}render(){(0,i.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(h,b=null){let C=[];if(this._fieldObjects){let P=this._fieldObjects[h];if(P)for(let{page:O,id:M,exportValues:E}of P){if(O===-1||M===b)continue;let L=typeof E=="string"?E:null,U=document.querySelector(`[data-element-id="${M}"]`);!U||a.has(U)?C.push({id:M,exportValue:L,domElement:U}):(0,i.warn)(`_getElementsByName - element not allowed: ${M}`)}return C}for(let P of document.getElementsByName(h)){let{exportValue:O}=P,M=P.getAttribute("data-element-id");M!==b&&a.has(P)&&C.push({id:M,exportValue:O,domElement:P})}return C}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let h=this.getElementsToTriggerPopup();if(Array.isArray(h))for(let b of h)b.classList.add("highlightArea");else h.classList.add("highlightArea")}get _isEditable(){return!1}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:h,data:{id:b}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:h,editId:b})}))}}class l extends T{constructor(h,b=null){super(h,{isRenderable:!0,ignoreBorder:!!b?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=h.data.isTooltipOnly}render(){let{data:h,linkService:b}=this,C=document.createElement("a");C.setAttribute("data-element-id",h.id);let P=!1;return h.url?(b.addLinkAttributes(C,h.url,h.newWindow),P=!0):h.action?(this._bindNamedAction(C,h.action),P=!0):h.attachment?(this.#e(C,h.attachment,h.attachmentDest),P=!0):h.setOCGState?(this.#i(C,h.setOCGState),P=!0):h.dest?(this._bindLink(C,h.dest),P=!0):(h.actions&&(h.actions.Action||h.actions["Mouse Up"]||h.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(C,h),P=!0),h.resetForm?(this._bindResetFormAction(C,h.resetForm),P=!0):this.isTooltipOnly&&!P&&(this._bindLink(C,""),P=!0)),this.container.classList.add("linkAnnotation"),P&&this.container.append(C),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(h,b){h.href=this.linkService.getDestinationHash(b),h.onclick=()=>(b&&this.linkService.goToDestination(b),!1),(b||b==="")&&this.#t()}_bindNamedAction(h,b){h.href=this.linkService.getAnchorUrl(""),h.onclick=()=>(this.linkService.executeNamedAction(b),!1),this.#t()}#e(h,b,C=null){h.href=this.linkService.getAnchorUrl(""),h.onclick=()=>(this.downloadManager?.openOrDownloadData(b.content,b.filename,C),!1),this.#t()}#i(h,b){h.href=this.linkService.getAnchorUrl(""),h.onclick=()=>(this.linkService.executeSetOCGState(b),!1),this.#t()}_bindJSAction(h,b){h.href=this.linkService.getAnchorUrl("");let C=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let P of Object.keys(b.actions)){let O=C.get(P);O&&(h[O]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b.id,name:P}}),!1))}h.onclick||(h.onclick=()=>!1),this.#t()}_bindResetFormAction(h,b){let C=h.onclick;C||(h.href=this.linkService.getAnchorUrl("")),this.#t(),this._fieldObjects?h.onclick=()=>{C?.();let{fields:P,refs:O,include:M}=b,E=[];if(P.length!==0||O.length!==0){let B=new Set(O);for(let k of P){let F=this._fieldObjects[k]||[];for(let{id:V}of F)B.add(V)}for(let k of Object.values(this._fieldObjects))for(let F of k)B.has(F.id)===M&&E.push(F)}else for(let B of Object.values(this._fieldObjects))E.push(...B);let L=this.annotationStorage,U=[];for(let B of E){let{id:k}=B;switch(U.push(k),B.type){case"text":{let V=B.defaultValue||"";L.setValue(k,{value:V});break}case"checkbox":case"radiobutton":{let V=B.defaultValue===B.exportValues;L.setValue(k,{value:V});break}case"combobox":case"listbox":{let V=B.defaultValue||"";L.setValue(k,{value:V});break}default:continue}let F=document.querySelector(`[data-element-id="${k}"]`);F&&(a.has(F)?F.dispatchEvent(new Event("resetform")):(0,i.warn)(`_bindResetFormAction - element not allowed: ${k}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:U,name:"ResetForm"}}),!1}:((0,i.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),C||(h.onclick=()=>!1))}}class y extends T{constructor(h){super(h,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let h=document.createElement("img");return h.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",h.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),h.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(h),this.container}}class s extends T{render(){return this.container}showElementAndHideCanvas(h){this.data.hasOwnCanvas&&(h.previousSibling?.nodeName==="CANVAS"&&(h.previousSibling.hidden=!0),h.hidden=!1)}_getKeyModifier(h){return i.FeatureTest.platform.isMac?h.metaKey:h.ctrlKey}_setEventListener(h,b,C,P,O){C.includes("mouse")?h.addEventListener(C,(M=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:P,value:O(M),shift:M.shiftKey,modifier:this._getKeyModifier(M)}})})):h.addEventListener(C,(M=>{if(C==="blur"){if(!b.focused||!M.relatedTarget)return;b.focused=!1}else if(C==="focus"){if(b.focused)return;b.focused=!0}O&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:P,value:O(M)}})}))}_setEventListeners(h,b,C,P){for(let[O,M]of C)(M==="Action"||this.data.actions?.[M])&&(M!=="Focus"&&M!=="Blur"||(b||={focused:!1}),this._setEventListener(h,b,O,M,P),M!=="Focus"||this.data.actions?.Blur?M!=="Blur"||this.data.actions?.Focus||this._setEventListener(h,b,"focus","Focus",null):this._setEventListener(h,b,"blur","Blur",null))}_setBackgroundColor(h){let b=this.data.backgroundColor||null;h.style.backgroundColor=b===null?"transparent":i.Util.makeHexColor(b[0],b[1],b[2])}_setTextStyle(h){let b=["left","center","right"],{fontColor:C}=this.data.defaultAppearanceData,P=this.data.defaultAppearanceData.fontSize||9,O=h.style,M,E=L=>Math.round(10*L)/10;if(this.data.multiLine){let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2),U=L/(Math.round(L/(i.LINE_FACTOR*P))||1);M=Math.min(P,E(U/i.LINE_FACTOR))}else{let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2);M=Math.min(P,E(L/i.LINE_FACTOR))}O.fontSize=`calc(${M}px * var(--scale-factor))`,O.color=i.Util.makeHexColor(C[0],C[1],C[2]),this.data.textAlignment!==null&&(O.textAlign=b[this.data.textAlignment])}_setRequired(h,b){b?h.setAttribute("required",!0):h.removeAttribute("required"),h.setAttribute("aria-required",b)}}class c extends s{constructor(h){super(h,{isRenderable:h.renderForms||h.data.hasOwnCanvas||!h.data.hasAppearance&&!!h.data.fieldValue})}setPropertyOnSiblings(h,b,C,P){let O=this.annotationStorage;for(let M of this._getElementsByName(h.name,h.id))M.domElement&&(M.domElement[b]=C),O.setValue(M.id,{[P]:C})}render(){let h=this.annotationStorage,b=this.data.id;this.container.classList.add("textWidgetAnnotation");let C=null;if(this.renderForms){let P=h.getValue(b,{value:this.data.fieldValue}),O=P.value||"",M=h.getValue(b,{charLimit:this.data.maxLen}).charLimit;M&&O.length>M&&(O=O.slice(0,M));let E=P.formattedValue||this.data.textContent?.join(`
|
|
1525
|
+
`)||null;E&&this.data.comb&&(E=E.replaceAll(/\s+/g,""));let L={userValue:O,formattedValue:E,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(C=document.createElement("textarea"),C.textContent=E??O,this.data.doNotScroll&&(C.style.overflowY="hidden")):(C=document.createElement("input"),C.type="text",C.setAttribute("value",E??O),this.data.doNotScroll&&(C.style.overflowX="hidden")),this.data.hasOwnCanvas&&(C.hidden=!0),a.add(C),C.setAttribute("data-element-id",b),C.disabled=this.data.readOnly,C.name=this.data.fieldName,C.tabIndex=u,this._setRequired(C,this.data.required),M&&(C.maxLength=M),C.addEventListener("input",(B=>{h.setValue(b,{value:B.target.value}),this.setPropertyOnSiblings(C,"value",B.target.value,"value"),L.formattedValue=null})),C.addEventListener("resetform",(B=>{let k=this.data.defaultFieldValue??"";C.value=L.userValue=k,L.formattedValue=null}));let U=B=>{let{formattedValue:k}=L;k!=null&&(B.target.value=k),B.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){C.addEventListener("focus",(k=>{if(L.focused)return;let{target:F}=k;L.userValue&&(F.value=L.userValue),L.lastCommittedValue=F.value,L.commitKey=1,this.data.actions?.Focus||(L.focused=!0)})),C.addEventListener("updatefromsandbox",(k=>{this.showElementAndHideCanvas(k.target);let F={value(V){L.userValue=V.detail.value??"",h.setValue(b,{value:L.userValue.toString()}),V.target.value=L.userValue},formattedValue(V){let{formattedValue:Q}=V.detail;L.formattedValue=Q,Q!=null&&V.target!==document.activeElement&&(V.target.value=Q),h.setValue(b,{formattedValue:Q})},selRange(V){V.target.setSelectionRange(...V.detail.selRange)},charLimit:V=>{let{charLimit:Q}=V.detail,{target:Z}=V;if(Q===0){Z.removeAttribute("maxLength");return}Z.setAttribute("maxLength",Q);let tt=L.userValue;tt&&!(tt.length<=Q)&&(tt=tt.slice(0,Q),Z.value=L.userValue=tt,h.setValue(b,{value:tt}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:tt,willCommit:!0,commitKey:1,selStart:Z.selectionStart,selEnd:Z.selectionEnd}}))}};this._dispatchEventFromSandbox(F,k)})),C.addEventListener("keydown",(k=>{L.commitKey=1;let F=-1;if(k.key==="Escape"?F=0:k.key!=="Enter"||this.data.multiLine?k.key==="Tab"&&(L.commitKey=3):F=2,F===-1)return;let{value:V}=k.target;L.lastCommittedValue!==V&&(L.lastCommittedValue=V,L.userValue=V,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:V,willCommit:!0,commitKey:F,selStart:k.target.selectionStart,selEnd:k.target.selectionEnd}}))}));let B=U;U=null,C.addEventListener("blur",(k=>{if(!L.focused||!k.relatedTarget)return;this.data.actions?.Blur||(L.focused=!1);let{value:F}=k.target;L.userValue=F,L.lastCommittedValue!==F&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:F,willCommit:!0,commitKey:L.commitKey,selStart:k.target.selectionStart,selEnd:k.target.selectionEnd}}),B(k)})),this.data.actions?.Keystroke&&C.addEventListener("beforeinput",(k=>{L.lastCommittedValue=null;let{data:F,target:V}=k,{value:Q,selectionStart:Z,selectionEnd:tt}=V,rt=Z,pt=tt;switch(k.inputType){case"deleteWordBackward":{let dt=Q.substring(0,Z).match(/\w*[^\w]*$/);dt&&(rt-=dt[0].length);break}case"deleteWordForward":{let dt=Q.substring(Z).match(/^[^\w]*\w*/);dt&&(pt+=dt[0].length);break}case"deleteContentBackward":Z===tt&&(rt-=1);break;case"deleteContentForward":Z===tt&&(pt+=1)}k.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:Q,change:F||"",willCommit:!1,selStart:rt,selEnd:pt}})})),this._setEventListeners(C,L,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(k=>k.target.value))}if(U&&C.addEventListener("blur",U),this.data.comb){let B=(this.data.rect[2]-this.data.rect[0])/M;C.classList.add("comb"),C.style.letterSpacing=`calc(${B}px * var(--scale-factor) - 1ch)`}}else C=document.createElement("div"),C.textContent=this.data.fieldValue,C.style.verticalAlign="middle",C.style.display="table-cell",this.data.hasOwnCanvas&&(C.hidden=!0);return this._setTextStyle(C),this._setBackgroundColor(C),this._setDefaultPropertiesFromJS(C),this.container.append(C),this.container}}class f extends s{constructor(h){super(h,{isRenderable:!!h.data.hasOwnCanvas})}}class w extends s{constructor(h){super(h,{isRenderable:h.renderForms})}render(){let h=this.annotationStorage,b=this.data,C=b.id,P=h.getValue(C,{value:b.exportValue===b.fieldValue}).value;typeof P=="string"&&(P=P!=="Off",h.setValue(C,{value:P})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let O=document.createElement("input");return a.add(O),O.setAttribute("data-element-id",C),O.disabled=b.readOnly,this._setRequired(O,this.data.required),O.type="checkbox",O.name=b.fieldName,P&&O.setAttribute("checked",!0),O.setAttribute("exportValue",b.exportValue),O.tabIndex=u,O.addEventListener("change",(M=>{let{name:E,checked:L}=M.target;for(let U of this._getElementsByName(E,C)){let B=L&&U.exportValue===b.exportValue;U.domElement&&(U.domElement.checked=B),h.setValue(U.id,{value:B})}h.setValue(C,{value:L})})),O.addEventListener("resetform",(M=>{let E=b.defaultFieldValue||"Off";M.target.checked=E===b.exportValue})),this.enableScripting&&this.hasJSActions&&(O.addEventListener("updatefromsandbox",(M=>{let E={value(L){L.target.checked=L.detail.value!=="Off",h.setValue(C,{value:L.target.checked})}};this._dispatchEventFromSandbox(E,M)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(M=>M.target.checked))),this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class R extends s{constructor(h){super(h,{isRenderable:h.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let h=this.annotationStorage,b=this.data,C=b.id,P=h.getValue(C,{value:b.fieldValue===b.buttonValue}).value;if(typeof P=="string"&&(P=P!==b.buttonValue,h.setValue(C,{value:P})),P)for(let M of this._getElementsByName(b.fieldName,C))h.setValue(M.id,{value:!1});let O=document.createElement("input");if(a.add(O),O.setAttribute("data-element-id",C),O.disabled=b.readOnly,this._setRequired(O,this.data.required),O.type="radio",O.name=b.fieldName,P&&O.setAttribute("checked",!0),O.tabIndex=u,O.addEventListener("change",(M=>{let{name:E,checked:L}=M.target;for(let U of this._getElementsByName(E,C))h.setValue(U.id,{value:!1});h.setValue(C,{value:L})})),O.addEventListener("resetform",(M=>{let E=b.defaultFieldValue;M.target.checked=E!=null&&E===b.buttonValue})),this.enableScripting&&this.hasJSActions){let M=b.buttonValue;O.addEventListener("updatefromsandbox",(E=>{let L={value:U=>{let B=M===U.detail.value;for(let k of this._getElementsByName(U.target.name)){let F=B&&k.id===C;k.domElement&&(k.domElement.checked=F),h.setValue(k.id,{value:F})}}};this._dispatchEventFromSandbox(L,E)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(E=>E.target.checked))}return this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class S extends l{constructor(h){super(h,{ignoreBorder:h.data.hasAppearance})}render(){let h=super.render();h.classList.add("buttonWidgetAnnotation","pushButton");let b=h.lastChild;return this.enableScripting&&this.hasJSActions&&b&&(this._setDefaultPropertiesFromJS(b),b.addEventListener("updatefromsandbox",(C=>{this._dispatchEventFromSandbox({},C)}))),h}}class D extends s{constructor(h){super(h,{isRenderable:h.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let h=this.annotationStorage,b=this.data.id,C=h.getValue(b,{value:this.data.fieldValue}),P=document.createElement("select");a.add(P),P.setAttribute("data-element-id",b),P.disabled=this.data.readOnly,this._setRequired(P,this.data.required),P.name=this.data.fieldName,P.tabIndex=u;let O=this.data.combo&&this.data.options.length>0;this.data.combo||(P.size=this.data.options.length,this.data.multiSelect&&(P.multiple=!0)),P.addEventListener("resetform",(B=>{let k=this.data.defaultFieldValue;for(let F of P.options)F.selected=F.value===k}));for(let B of this.data.options){let k=document.createElement("option");k.textContent=B.displayValue,k.value=B.exportValue,C.value.includes(B.exportValue)&&(k.setAttribute("selected",!0),O=!1),P.append(k)}let M=null;if(O){let B=document.createElement("option");B.value=" ",B.setAttribute("hidden",!0),B.setAttribute("selected",!0),P.prepend(B),M=()=>{B.remove(),P.removeEventListener("input",M),M=null},P.addEventListener("input",M)}let E=B=>{let k=B?"value":"textContent",{options:F,multiple:V}=P;return V?Array.prototype.filter.call(F,(Q=>Q.selected)).map((Q=>Q[k])):F.selectedIndex===-1?null:F[F.selectedIndex][k]},L=E(!1),U=B=>{let k=B.target.options;return Array.prototype.map.call(k,(F=>({displayValue:F.textContent,exportValue:F.value})))};return this.enableScripting&&this.hasJSActions?(P.addEventListener("updatefromsandbox",(B=>{let k={value(F){M?.();let V=F.detail.value,Q=new Set(Array.isArray(V)?V:[V]);for(let Z of P.options)Z.selected=Q.has(Z.value);h.setValue(b,{value:E(!0)}),L=E(!1)},multipleSelection(F){P.multiple=!0},remove(F){let V=P.options,Q=F.detail.remove;V[Q].selected=!1,P.remove(Q),V.length>0&&Array.prototype.findIndex.call(V,(Z=>Z.selected))===-1&&(V[0].selected=!0),h.setValue(b,{value:E(!0),items:U(F)}),L=E(!1)},clear(F){for(;P.length!==0;)P.remove(0);h.setValue(b,{value:null,items:[]}),L=E(!1)},insert(F){let{index:V,displayValue:Q,exportValue:Z}=F.detail.insert,tt=P.children[V],rt=document.createElement("option");rt.textContent=Q,rt.value=Z,tt?tt.before(rt):P.append(rt),h.setValue(b,{value:E(!0),items:U(F)}),L=E(!1)},items(F){let{items:V}=F.detail;for(;P.length!==0;)P.remove(0);for(let Q of V){let{displayValue:Z,exportValue:tt}=Q,rt=document.createElement("option");rt.textContent=Z,rt.value=tt,P.append(rt)}P.options.length>0&&(P.options[0].selected=!0),h.setValue(b,{value:E(!0),items:U(F)}),L=E(!1)},indices(F){let V=new Set(F.detail.indices);for(let Q of F.target.options)Q.selected=V.has(Q.index);h.setValue(b,{value:E(!0)}),L=E(!1)},editable(F){F.target.disabled=!F.detail.editable}};this._dispatchEventFromSandbox(k,B)})),P.addEventListener("input",(B=>{let k=E(!0);h.setValue(b,{value:k}),B.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:L,changeEx:k,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(P,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(B=>B.target.value))):P.addEventListener("input",(function(B){h.setValue(b,{value:E(!0)})})),this.data.combo&&this._setTextStyle(P),this._setBackgroundColor(P),this._setDefaultPropertiesFromJS(P),this.container.append(P),this.container}}class N extends T{constructor(h){let{data:b,elements:C}=h;super(h,{isRenderable:T._hasPopupData(b)}),this.elements=C}render(){this.container.classList.add("popupAnnotation");let h=new H({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),b=[];for(let C of this.elements)C.popup=h,b.push(C.data.id),C.addHighlightArea();return this.container.setAttribute("aria-controls",b.map((C=>`${i.AnnotationPrefix}${C}`)).join(",")),this.container}}class H{#t=this.#m.bind(this);#e=this.#_.bind(this);#i=this.#S.bind(this);#n=this.#b.bind(this);#r=null;#s=null;#o=null;#c=null;#a=null;#h=null;#u=null;#d=!1;#l=null;#f=null;#g=null;#p=null;#y=!1;constructor({container:h,color:b,elements:C,titleObj:P,modificationDate:O,contentsObj:M,richText:E,parent:L,rect:U,parentRect:B,open:k}){this.#s=h,this.#p=P,this.#o=M,this.#g=E,this.#h=L,this.#r=b,this.#f=U,this.#u=B,this.#a=C,this.#c=r.PDFDateString.toDateObject(O),this.trigger=C.flatMap((F=>F.getElementsToTriggerPopup()));for(let F of this.trigger)F.addEventListener("click",this.#n),F.addEventListener("mouseenter",this.#i),F.addEventListener("mouseleave",this.#e),F.classList.add("popupTriggerArea");for(let F of C)F.container?.addEventListener("keydown",this.#t);this.#s.hidden=!0,k&&this.#b()}render(){if(this.#l)return;let{page:{view:h},viewport:{rawDims:{pageWidth:b,pageHeight:C,pageX:P,pageY:O}}}=this.#h,M=this.#l=document.createElement("div");if(M.className="popup",this.#r){let pt=M.style.outlineColor=i.Util.makeHexColor(...this.#r);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?M.style.backgroundColor=`color-mix(in srgb, ${pt} 30%, white)`:M.style.backgroundColor=i.Util.makeHexColor(...this.#r.map((lt=>Math.floor(.7*(255-lt)+lt))))}let E=document.createElement("span");E.className="header";let L=document.createElement("h1");if(E.append(L),{dir:L.dir,str:L.textContent}=this.#p,M.append(E),this.#c){let pt=document.createElement("span");pt.classList.add("popupDate"),pt.setAttribute("data-l10n-id","pdfjs-annotation-date-string"),pt.setAttribute("data-l10n-args",JSON.stringify({date:this.#c.toLocaleDateString(),time:this.#c.toLocaleTimeString()})),E.append(pt)}let U=this.#o,B=this.#g;if(!B?.str||U?.str&&U.str!==B.str){let pt=this._formatContents(U);M.append(pt)}else v.XfaLayer.render({xfaHtml:B.html,intent:"richText",div:M}),M.lastChild.classList.add("richText","popupContent");let k=!!this.#u,F=k?this.#u:this.#f;for(let pt of this.#a)if(!F||i.Util.intersect(pt.data.rect,F)!==null){F=pt.data.rect,k=!0;break}let V=i.Util.normalizeRect([F[0],h[3]-F[1]+h[1],F[2],h[3]-F[3]+h[1]]),Q=k?F[2]-F[0]+5:0,Z=V[0]+Q,tt=V[1],{style:rt}=this.#s;rt.left=100*(Z-P)/b+"%",rt.top=100*(tt-O)/C+"%",this.#s.append(M)}_formatContents({str:h,dir:b}){let C=document.createElement("p");C.classList.add("popupContent"),C.dir=b;let P=h.split(/(?:\r\n?|\n)/);for(let O=0,M=P.length;O<M;++O){let E=P[O];C.append(document.createTextNode(E)),O<M-1&&C.append(document.createElement("br"))}return C}#m(h){h.altKey||h.shiftKey||h.ctrlKey||h.metaKey||(h.key==="Enter"||h.key==="Escape"&&this.#d)&&this.#b()}#b(){this.#d=!this.#d,this.#d?(this.#S(),this.#s.addEventListener("click",this.#n),this.#s.addEventListener("keydown",this.#t)):(this.#_(),this.#s.removeEventListener("click",this.#n),this.#s.removeEventListener("keydown",this.#t))}#S(){this.#l||this.render(),this.isVisible?this.#d&&this.#s.classList.add("focused"):(this.#s.hidden=!1,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)+1e3)}#_(){this.#s.classList.remove("focused"),!this.#d&&this.isVisible&&(this.#s.hidden=!0,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)-1e3)}forceHide(){this.#y=this.isVisible,this.#y&&(this.#s.hidden=!0)}maybeShow(){this.#y&&(this.#y=!1,this.#s.hidden=!1)}get isVisible(){return this.#s.hidden===!1}}class j extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0}),this.textContent=h.data.textContent,this.textPosition=h.data.textPosition,this.annotationEditorType=i.AnnotationEditorType.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){let h=document.createElement("div");h.classList.add("annotationTextContent"),h.setAttribute("role","comment");for(let b of this.textContent){let C=document.createElement("span");C.textContent=b,h.append(C)}this.container.append(h)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}get _isEditable(){return this.data.hasOwnCanvas}}class Y extends T{#t=null;constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0),O=this.#t=this.svgFactory.createElement("svg:line");return O.setAttribute("x1",h.rect[2]-h.lineCoordinates[0]),O.setAttribute("y1",h.rect[3]-h.lineCoordinates[1]),O.setAttribute("x2",h.rect[2]-h.lineCoordinates[2]),O.setAttribute("y2",h.rect[3]-h.lineCoordinates[3]),O.setAttribute("stroke-width",h.borderStyle.width||1),O.setAttribute("stroke","transparent"),O.setAttribute("fill","transparent"),P.append(O),this.container.append(P),!h.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class it extends T{#t=null;constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0),O=h.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:rect");return M.setAttribute("x",O/2),M.setAttribute("y",O/2),M.setAttribute("width",b-O),M.setAttribute("height",C-O),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),P.append(M),this.container.append(P),!h.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class ot extends T{#t=null;constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0),O=h.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:ellipse");return M.setAttribute("cx",b/2),M.setAttribute("cy",C/2),M.setAttribute("rx",b/2-O/2),M.setAttribute("ry",C/2-O/2),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),P.append(M),this.container.append(P),!h.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class K extends T{#t=null;constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0),O=[];for(let E of h.vertices){let L=E.x-h.rect[0],U=h.rect[3]-E.y;O.push(L+","+U)}O=O.join(" ");let M=this.#t=this.svgFactory.createElement(this.svgElementName);return M.setAttribute("points",O),M.setAttribute("stroke-width",h.borderStyle.width||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),P.append(M),this.container.append(P),!h.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class z extends K{constructor(h){super(h),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class W extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class X extends T{#t=[];constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=i.AnnotationEditorType.INK}render(){this.container.classList.add(this.containerClassName);let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0);for(let O of h.inkLists){let M=[];for(let L of O){let U=L.x-h.rect[0],B=h.rect[3]-L.y;M.push(`${U},${B}`)}M=M.join(" ");let E=this.svgFactory.createElement(this.svgElementName);this.#t.push(E),E.setAttribute("points",M),E.setAttribute("stroke-width",h.borderStyle.width||1),E.setAttribute("stroke","transparent"),E.setAttribute("fill","transparent"),!h.popupRef&&this.hasPopupData&&this._createPopup(),P.append(E)}return this.container.append(P),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class et extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this.container}}class st extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class ct extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class nt extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class G extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class A extends T{#t=null;constructor(h){super(h,{isRenderable:!0});let{filename:b,content:C}=this.data.file;this.filename=(0,r.getFilenameFromUrl)(b,!0),this.content=C,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,filename:b,content:C})}render(){this.container.classList.add("fileAttachmentAnnotation");let{container:h,data:b}=this,C;b.hasAppearance||b.fillAlpha===0?C=document.createElement("div"):(C=document.createElement("img"),C.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(b.name)?"paperclip":"pushpin"}.svg`,b.fillAlpha&&b.fillAlpha<1&&(C.style=`filter: opacity(${Math.round(100*b.fillAlpha)}%);`)),C.addEventListener("dblclick",this.#e.bind(this)),this.#t=C;let{isMac:P}=i.FeatureTest.platform;return h.addEventListener("keydown",(O=>{O.key==="Enter"&&(P?O.metaKey:O.ctrlKey)&&this.#e()})),!b.popupRef&&this.hasPopupData?this._createPopup():C.classList.add("popupTriggerArea"),h.append(C),h}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class _{#t=null;#e=null;#i=new Map;constructor({div:h,accessibilityManager:b,annotationCanvasMap:C,page:P,viewport:O}){this.div=h,this.#t=b,this.#e=C,this.page=P,this.viewport=O,this.zIndex=0}#n(h,b){let C=h.firstChild||h;C.id=`${i.AnnotationPrefix}${b}`,this.div.append(h),this.#t?.moveElementInDOM(this.div,h,C,!1)}async render(h){let{annotations:b}=h,C=this.div;(0,r.setLayerDimensions)(C,this.viewport);let P=new Map,O={data:null,layer:C,linkService:h.linkService,downloadManager:h.downloadManager,imageResourcesPath:h.imageResourcesPath||"",renderForms:h.renderForms!==!1,svgFactory:new r.DOMSVGFactory,annotationStorage:h.annotationStorage||new o.AnnotationStorage,enableScripting:h.enableScripting===!0,hasJSActions:h.hasJSActions,fieldObjects:h.fieldObjects,parent:this,elements:null};for(let M of b){if(M.noHTML)continue;let E=M.annotationType===i.AnnotationType.POPUP;if(E){let B=P.get(M.id);if(!B)continue;O.elements=B}else{let{width:B,height:k}=p(M.rect);if(B<=0||k<=0)continue}O.data=M;let L=x.create(O);if(!L.isRenderable)continue;if(!E&&M.popupRef){let B=P.get(M.popupRef);B?B.push(L):P.set(M.popupRef,[L])}L.annotationEditorType>0&&this.#i.set(L.data.id,L);let U=L.render();M.hidden&&(U.style.visibility="hidden"),this.#n(U,M.id)}this.#r()}update({viewport:h}){let b=this.div;this.viewport=h,(0,r.setLayerDimensions)(b,{rotation:h.rotation}),this.#r(),b.hidden=!1}#r(){if(!this.#e)return;let h=this.div;for(let[b,C]of this.#e){let P=h.querySelector(`[data-annotation-id="${b}"]`);if(!P)continue;let{firstChild:O}=P;O?O.nodeName==="CANVAS"?O.replaceWith(C):O.before(C):P.append(C)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#i.values())}getEditableAnnotation(h){return this.#i.get(h)}}},792:(n,t,e)=>{e.d(t,{AnnotationStorage:()=>d,PrintAnnotationStorage:()=>m,SerializableEmpty:()=>g});var i=e(292),r=e(310),o=e(651);let g=Object.freeze({map:null,hash:"",transfer:void 0});class d{#t=!1;#e=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(u,a){let p=this.#e.get(u);return p===void 0?a:Object.assign(a,p)}getRawValue(u){return this.#e.get(u)}remove(u){if(this.#e.delete(u),this.#e.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(let a of this.#e.values())if(a instanceof r.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(u,a){let p=this.#e.get(u),x=!1;if(p!==void 0)for(let[T,l]of Object.entries(a))p[T]!==l&&(x=!0,p[T]=l);else x=!0,this.#e.set(u,a);x&&this.#i(),a instanceof r.AnnotationEditor&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(a.constructor._type)}has(u){return this.#e.has(u)}getAll(){return this.#e.size>0?(0,i.objectFromMap)(this.#e):null}setAll(u){for(let[a,p]of Object.entries(u))this.setValue(a,p)}get size(){return this.#e.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new m(this)}get serializable(){if(this.#e.size===0)return g;let u=new Map,a=new o.MurmurHash3_64,p=[],x=Object.create(null),T=!1;for(let[l,y]of this.#e){let s=y instanceof r.AnnotationEditor?y.serialize(!1,x):y;s&&(u.set(l,s),a.update(`${l}:${JSON.stringify(s)}`),T||=!!s.bitmap)}if(T)for(let l of u.values())l.bitmap&&p.push(l.bitmap);return u.size>0?{map:u,hash:a.hexdigest(),transfer:p}:g}get editorStats(){let u=null,a=new Map;for(let p of this.#e.values()){if(!(p instanceof r.AnnotationEditor))continue;let x=p.telemetryFinalData;if(!x)continue;let{type:T}=x;a.has(T)||a.set(T,Object.getPrototypeOf(p).constructor),u||=Object.create(null);let l=u[T]||=new Map;for(let[y,s]of Object.entries(x)){if(y==="type")continue;let c=l.get(y);c||(c=new Map,l.set(y,c));let f=c.get(s)??0;c.set(s,f+1)}}for(let[p,x]of a)u[p]=x.computeTelemetryFinalData(u[p]);return u}}class m extends d{#t;constructor(u){super();let{map:a,hash:p,transfer:x}=u.serializable,T=structuredClone(a,x?{transfer:x}:null);this.#t={map:T,hash:p,transfer:x}}get print(){(0,i.unreachable)("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}}},831:(n,t,e)=>{e.a(n,(async(i,r)=>{try{let ot=function(M){if(typeof M=="string"||M instanceof URL?M={url:M}:(M instanceof ArrayBuffer||ArrayBuffer.isView(M))&&(M={data:M}),typeof M!="object")throw new Error("Invalid parameter in getDocument, need parameter object.");if(!M.url&&!M.data&&!M.range)throw new Error("Invalid parameter object: need either .data, .range or .url");let E=new X,{docId:L}=E,U=M.url?z(M.url):null,B=M.data?W(M.data):null,k=M.httpHeaders||null,F=M.withCredentials===!0,V=M.password??null,Q=M.range instanceof et?M.range:null,Z=Number.isInteger(M.rangeChunkSize)&&M.rangeChunkSize>0?M.rangeChunkSize:S,tt=M.worker instanceof A?M.worker:null,rt=M.verbosity,pt=typeof M.docBaseUrl!="string"||(0,d.isDataScheme)(M.docBaseUrl)?null:M.docBaseUrl,dt=typeof M.cMapUrl=="string"?M.cMapUrl:null,lt=M.cMapPacked!==!1,vt=M.CMapReaderFactory||j,Et=typeof M.standardFontDataUrl=="string"?M.standardFontDataUrl:null,wt=M.StandardFontDataFactory||it,Ct=M.stopAtErrors!==!0,Tt=Number.isInteger(M.maxImageSize)&&M.maxImageSize>-1?M.maxImageSize:-1,It=M.isEvalSupported!==!1,Ot=typeof M.isOffscreenCanvasSupported=="boolean"?M.isOffscreenCanvasSupported:!o.isNodeJS,Jt=Number.isInteger(M.canvasMaxAreaInBytes)?M.canvasMaxAreaInBytes:-1,ae=typeof M.disableFontFace=="boolean"?M.disableFontFace:o.isNodeJS,me=M.fontExtraProperties===!0,le=M.enableXfa===!0,ue=M.ownerDocument||globalThis.document,je=M.disableRange===!0,ze=M.disableStream===!0,Yt=M.disableAutoFetch===!0,Xt=M.pdfBug===!0,Ve=Q?Q.length:M.length??NaN,Wi=typeof M.useSystemFonts=="boolean"?M.useSystemFonts:!o.isNodeJS&&!ae,pe=typeof M.useWorkerFetch=="boolean"?M.useWorkerFetch:vt===d.DOMCMapReaderFactory&&wt===d.DOMStandardFontDataFactory&&dt&&Et&&(0,d.isValidFetchUrl)(dt,document.baseURI)&&(0,d.isValidFetchUrl)(Et,document.baseURI),Gt=M.canvasFactory||new H({ownerDocument:ue}),an=M.filterFactory||new Y({docId:L,ownerDocument:ue});(0,o.setVerbosityLevel)(rt);let Gi={canvasFactory:Gt,filterFactory:an};if(pe||(Gi.cMapReaderFactory=new vt({baseUrl:dt,isCompressed:lt}),Gi.standardFontDataFactory=new wt({baseUrl:Et})),!tt){let ye={verbosity:rt,port:p.GlobalWorkerOptions.workerPort};tt=ye.port?A.fromPort(ye):new A(ye),E._worker=tt}let be={docId:L,apiVersion:"4.1.392",data:B,password:V,disableAutoFetch:Yt,rangeChunkSize:Z,length:Ve,docBaseUrl:pt,enableXfa:le,evaluatorOptions:{maxImageSize:Tt,disableFontFace:ae,ignoreErrors:Ct,isEvalSupported:It,isOffscreenCanvasSupported:Ot,canvasMaxAreaInBytes:Jt,fontExtraProperties:me,useSystemFonts:Wi,cMapUrl:pe?dt:null,standardFontDataUrl:pe?Et:null}},ui={ignoreErrors:Ct,isEvalSupported:It,disableFontFace:ae,fontExtraProperties:me,enableXfa:le,ownerDocument:ue,disableAutoFetch:Yt,pdfBug:Xt,styleElement:null};return tt.promise.then((function(){if(E.destroyed)throw new Error("Loading aborted");let ye=K(tt,be),on=new Promise((function(qi){let We;Q?We=new y.PDFDataTransportStream(Q,{disableRange:je,disableStream:ze}):B||(We=(te=>o.isNodeJS?(function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype})()&&(0,d.isValidFetchUrl)(te.url)?new s.PDFFetchStream(te):new f.PDFNodeStream(te):(0,d.isValidFetchUrl)(te.url)?new s.PDFFetchStream(te):new c.PDFNetworkStream(te))({url:U,length:Ve,httpHeaders:k,withCredentials:F,rangeChunkSize:Z,disableRange:je,disableStream:ze})),qi(We)}));return Promise.all([ye,on]).then((function([qi,We]){if(E.destroyed)throw new Error("Loading aborted");let te=new x.MessageHandler(L,qi,tt.port),cn=new _(te,E,We,ui,Gi);E._transport=cn,te.send("Ready",null)}))})).catch(E._capability.reject),E},z=function(M){if(M instanceof URL)return M.href;try{return new URL(M,window.location).href}catch{if(o.isNodeJS&&typeof M=="string")return M}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")},W=function(M){if(o.isNodeJS&&typeof Buffer<"u"&&M instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(M instanceof Uint8Array&&M.byteLength===M.buffer.byteLength)return M;if(typeof M=="string")return(0,o.stringToBytes)(M);if(M instanceof ArrayBuffer||ArrayBuffer.isView(M)||typeof M=="object"&&!isNaN(M?.length))return new Uint8Array(M);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")};e.d(t,{PDFDataRangeTransport:()=>et,PDFWorker:()=>A,build:()=>O,getDocument:()=>ot,version:()=>P});var o=e(292),g=e(792),d=e(419),m=e(10),v=e(573),u=e(923),a=e(814),p=e(164),x=e(178),T=e(62),l=e(626),y=e(585),s=e(94),c=e(457),f=e(786),w=e(50),R=i([v,f]);[v,f]=R.then?(await R)():R;let S=65536,D=100,N=5e3,H=o.isNodeJS?v.NodeCanvasFactory:d.DOMCanvasFactory,j=o.isNodeJS?v.NodeCMapReaderFactory:d.DOMCMapReaderFactory,Y=o.isNodeJS?v.NodeFilterFactory:d.DOMFilterFactory,it=o.isNodeJS?v.NodeStandardFontDataFactory:d.DOMStandardFontDataFactory;async function K(M,E){if(M.destroyed)throw new Error("Worker was destroyed");let L=await M.messageHandler.sendWithPromise("GetDocRequest",E,E.data?[E.data.buffer]:null);if(M.destroyed)throw new Error("Worker was destroyed");return L}class X{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+X.#t++,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(E){throw this._worker?.port&&delete this._worker._pendingDestroy,E}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class et{constructor(E,L,U=!1,B=null){this.length=E,this.initialData=L,this.progressiveDone=U,this.contentDispositionFilename=B,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(E){this._rangeListeners.push(E)}addProgressListener(E){this._progressListeners.push(E)}addProgressiveReadListener(E){this._progressiveReadListeners.push(E)}addProgressiveDoneListener(E){this._progressiveDoneListeners.push(E)}onDataRange(E,L){for(let U of this._rangeListeners)U(E,L)}onDataProgress(E,L){this._readyCapability.promise.then((()=>{for(let U of this._progressListeners)U(E,L)}))}onDataProgressiveRead(E){this._readyCapability.promise.then((()=>{for(let L of this._progressiveReadListeners)L(E)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(let E of this._progressiveDoneListeners)E()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(E,L){(0,o.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class st{constructor(E,L){this._pdfInfo=E,this._transport=L}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return(0,o.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(E){return this._transport.getPage(E)}getPageIndex(E){return this._transport.getPageIndex(E)}getDestinations(){return this._transport.getDestinations()}getDestination(E){return this._transport.getDestination(E)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:E="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(E);return this._transport.getOptionalContentConfig(L)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(E=!1){return this._transport.startCleanup(E||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class ct{#t=null;#e=!1;constructor(E,L,U,B=!1){this._pageIndex=E,this._pageInfo=L,this._transport=U,this._stats=B?new d.StatTimer:null,this._pdfBug=B,this.commonObjs=U.commonObjs,this.objs=new h,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:E,rotation:L=this.rotate,offsetX:U=0,offsetY:B=0,dontFlip:k=!1}={}){return new d.PageViewport({viewBox:this.view,scale:E,rotation:L,offsetX:U,offsetY:B,dontFlip:k})}getAnnotations({intent:E="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(E);return this._transport.getAnnotations(this._pageIndex,L)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return(0,o.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:E,viewport:L,intent:U="display",annotationMode:B=o.AnnotationMode.ENABLE,transform:k=null,background:F=null,optionalContentConfigPromise:V=null,annotationCanvasMap:Q=null,pageColors:Z=null,printAnnotationStorage:tt=null}){this._stats?.time("Overall");let rt=this._transport.getRenderingIntent(U,B,tt),{renderingIntent:pt,cacheKey:dt}=rt;this.#e=!1,this.#n(),V||=this._transport.getOptionalContentConfig(pt);let lt=this._intentStates.get(dt);lt||(lt=Object.create(null),this._intentStates.set(dt,lt)),lt.streamReaderCancelTimeout&&(clearTimeout(lt.streamReaderCancelTimeout),lt.streamReaderCancelTimeout=null);let vt=!!(pt&o.RenderingIntentFlag.PRINT);lt.displayReadyCapability||(lt.displayReadyCapability=Promise.withResolvers(),lt.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(rt));let Et=Tt=>{lt.renderTasks.delete(wt),(this._maybeCleanupAfterRender||vt)&&(this.#e=!0),this.#i(!vt),Tt?(wt.capability.reject(Tt),this._abortOperatorList({intentState:lt,reason:Tt instanceof Error?Tt:new Error(Tt)})):wt.capability.resolve(),this._stats?.timeEnd("Rendering"),this._stats?.timeEnd("Overall")},wt=new C({callback:Et,params:{canvasContext:E,viewport:L,transform:k,background:F},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:Q,operatorList:lt.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!vt,pdfBug:this._pdfBug,pageColors:Z});(lt.renderTasks||=new Set).add(wt);let Ct=wt.task;return Promise.all([lt.displayReadyCapability.promise,V]).then((([Tt,It])=>{if(this.destroyed)Et();else{if(this._stats?.time("Rendering"),!(It.renderingIntent&pt))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");wt.initializeGraphics({transparency:Tt,optionalContentConfig:It}),wt.operatorListChanged()}})).catch(Et),Ct}getOperatorList({intent:E="display",annotationMode:L=o.AnnotationMode.ENABLE,printAnnotationStorage:U=null}={}){let B=this._transport.getRenderingIntent(E,L,U,!0),k,F=this._intentStates.get(B.cacheKey);return F||(F=Object.create(null),this._intentStates.set(B.cacheKey,F)),F.opListReadCapability||(k=Object.create(null),k.operatorListChanged=function(){F.operatorList.lastChunk&&(F.opListReadCapability.resolve(F.operatorList),F.renderTasks.delete(k))},F.opListReadCapability=Promise.withResolvers(),(F.renderTasks||=new Set).add(k),F.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(B)),F.opListReadCapability.promise}streamTextContent({includeMarkedContent:E=!1,disableNormalization:L=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:E===!0,disableNormalization:L===!0},{highWaterMark:100,size:U=>U.items.length})}getTextContent(E={}){if(this._transport._htmlForXfa)return this.getXfa().then((U=>w.XfaText.textContent(U)));let L=this.streamTextContent(E);return new Promise((function(U,B){let k=L.getReader(),F={items:[],styles:Object.create(null)};(function V(){k.read().then((function({value:Q,done:Z}){Z?U(F):(Object.assign(F.styles,Q.styles),F.items.push(...Q.items),V())}),B)})()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let E=[];for(let L of this._intentStates.values())if(this._abortOperatorList({intentState:L,reason:new Error("Page was destroyed."),force:!0}),!L.opListReadCapability)for(let U of L.renderTasks)E.push(U.completed),U.cancel();return this.objs.clear(),this.#e=!1,this.#n(),Promise.all(E)}cleanup(E=!1){this.#e=!0;let L=this.#i(!1);return E&&L&&(this._stats&&=new d.StatTimer),L}#i(E=!1){if(this.#n(),!this.#e||this.destroyed)return!1;if(E)return this.#t=setTimeout((()=>{this.#t=null,this.#i(!1)}),N),!1;for(let{renderTasks:L,operatorList:U}of this._intentStates.values())if(L.size>0||!U.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#n(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(E,L){let U=this._intentStates.get(L);U&&(this._stats?.timeEnd("Page Request"),U.displayReadyCapability?.resolve(E))}_renderPageChunk(E,L){for(let U=0,B=E.length;U<B;U++)L.operatorList.fnArray.push(E.fnArray[U]),L.operatorList.argsArray.push(E.argsArray[U]);L.operatorList.lastChunk=E.lastChunk,L.operatorList.separateAnnots=E.separateAnnots;for(let U of L.renderTasks)U.operatorListChanged();E.lastChunk&&this.#i(!0)}_pumpOperatorList({renderingIntent:E,cacheKey:L,annotationStorageSerializable:U}){let{map:B,transfer:k}=U,F=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:E,cacheKey:L,annotationStorage:B},k).getReader(),V=this._intentStates.get(L);V.streamReader=F;let Q=()=>{F.read().then((({value:Z,done:tt})=>{tt?V.streamReader=null:this._transport.destroyed||(this._renderPageChunk(Z,V),Q())}),(Z=>{if(V.streamReader=null,!this._transport.destroyed){if(V.operatorList){V.operatorList.lastChunk=!0;for(let tt of V.renderTasks)tt.operatorListChanged();this.#i(!0)}if(V.displayReadyCapability)V.displayReadyCapability.reject(Z);else{if(!V.opListReadCapability)throw Z;V.opListReadCapability.reject(Z)}}}))};Q()}_abortOperatorList({intentState:E,reason:L,force:U=!1}){if(E.streamReader){if(E.streamReaderCancelTimeout&&(clearTimeout(E.streamReaderCancelTimeout),E.streamReaderCancelTimeout=null),!U){if(E.renderTasks.size>0)return;if(L instanceof d.RenderingCancelledException){let B=D;L.extraDelay>0&&L.extraDelay<1e3&&(B+=L.extraDelay),E.streamReaderCancelTimeout=setTimeout((()=>{E.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:E,reason:L,force:!0})}),B);return}}if(E.streamReader.cancel(new o.AbortException(L.message)).catch((()=>{})),E.streamReader=null,!this._transport.destroyed){for(let[B,k]of this._intentStates)if(k===E){this._intentStates.delete(B);break}this.cleanup()}}}get stats(){return this._stats}}class nt{#t=new Set;#e=Promise.resolve();postMessage(E,L){let U={data:structuredClone(E,L?{transfer:L}:null)};this.#e.then((()=>{for(let B of this.#t)B.call(this,U)}))}addEventListener(E,L){this.#t.add(L)}removeEventListener(E,L){this.#t.delete(L)}terminate(){this.#t.clear()}}let G={isWorkerDisabled:!1,fakeWorkerId:0};o.isNodeJS&&(G.isWorkerDisabled=!0,p.GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"),G.isSameOrigin=function(M,E){let L;try{if(L=new URL(M),!L.origin||L.origin==="null")return!1}catch{return!1}let U=new URL(E,L);return L.origin===U.origin},G.createCDNWrapper=function(M){let E=`await import("${M}");`;return URL.createObjectURL(new Blob([E],{type:"text/javascript"}))};class A{static#t;constructor({name:E=null,port:L=null,verbosity:U=(0,o.getVerbosityLevel)()}={}){if(this.name=E,this.destroyed=!1,this.verbosity=U,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,L){if(A.#t?.has(L))throw new Error("Cannot use more than one PDFWorker per port.");(A.#t||=new WeakMap).set(L,this),this._initializeFromPort(L)}else this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(E){this._port=E,this._messageHandler=new x.MessageHandler("main","worker",E),this._messageHandler.on("ready",(function(){})),this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!G.isWorkerDisabled&&!A.#e){let{workerSrc:E}=A;try{G.isSameOrigin(window.location.href,E)||(E=G.createCDNWrapper(new URL(E,window.location).href));let L=new Worker(E,{type:"module"}),U=new x.MessageHandler("main","worker",L),B=()=>{L.removeEventListener("error",k),U.destroy(),L.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},k=()=>{this._webWorker||B()};L.addEventListener("error",k),U.on("test",(V=>{L.removeEventListener("error",k),this.destroyed?B():V?(this._messageHandler=U,this._port=L,this._webWorker=L,this._readyCapability.resolve(),U.send("configure",{verbosity:this.verbosity})):(this._setupFakeWorker(),U.destroy(),L.terminate())})),U.on("ready",(V=>{if(L.removeEventListener("error",k),this.destroyed)B();else try{F()}catch{this._setupFakeWorker()}}));let F=()=>{let V=new Uint8Array;U.send("test",V,[V.buffer])};F();return}catch{(0,o.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){G.isWorkerDisabled||((0,o.warn)("Setting up fake worker."),G.isWorkerDisabled=!0),A._setupFakeWorkerGlobal.then((E=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}let L=new nt;this._port=L;let U="fake"+G.fakeWorkerId++,B=new x.MessageHandler(U+"_worker",U,L);E.setup(B,L);let k=new x.MessageHandler(U,U+"_worker",L);this._messageHandler=k,this._readyCapability.resolve(),k.send("configure",{verbosity:this.verbosity})})).catch((E=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${E.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),A.#t?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(E){if(!E?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");let L=this.#t?.get(E.port);if(L){if(L._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return L}return new A(E)}static get workerSrc(){if(p.GlobalWorkerOptions.workerSrc)return p.GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#e(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return(0,o.shadow)(this,"_setupFakeWorkerGlobal",(async()=>this.#e?this.#e:(await import(this.workerSrc)).WorkerMessageHandler)())}}class _{#t=new Map;#e=new Map;#i=new Map;#n=null;constructor(E,L,U,B,k){this.messageHandler=E,this.loadingTask=L,this.commonObjs=new h,this.fontLoader=new m.FontLoader({ownerDocument:B.ownerDocument,styleElement:B.styleElement}),this._params=B,this.canvasFactory=k.canvasFactory,this.filterFactory=k.filterFactory,this.cMapReaderFactory=k.cMapReaderFactory,this.standardFontDataFactory=k.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=U,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#r(E,L=null){let U=this.#t.get(E);if(U)return U;let B=this.messageHandler.sendWithPromise(E,L);return this.#t.set(E,B),B}get annotationStorage(){return(0,o.shadow)(this,"annotationStorage",new g.AnnotationStorage)}getRenderingIntent(E,L=o.AnnotationMode.ENABLE,U=null,B=!1){let k=o.RenderingIntentFlag.DISPLAY,F=g.SerializableEmpty;switch(E){case"any":k=o.RenderingIntentFlag.ANY;break;case"display":break;case"print":k=o.RenderingIntentFlag.PRINT;break;default:(0,o.warn)(`getRenderingIntent - invalid intent: ${E}`)}switch(L){case o.AnnotationMode.DISABLE:k+=o.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case o.AnnotationMode.ENABLE:break;case o.AnnotationMode.ENABLE_FORMS:k+=o.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case o.AnnotationMode.ENABLE_STORAGE:k+=o.RenderingIntentFlag.ANNOTATIONS_STORAGE,F=(k&o.RenderingIntentFlag.PRINT&&U instanceof g.PrintAnnotationStorage?U:this.annotationStorage).serializable;break;default:(0,o.warn)(`getRenderingIntent - invalid annotationMode: ${L}`)}return B&&(k+=o.RenderingIntentFlag.OPLIST),{renderingIntent:k,cacheKey:`${k}_${F.hash}`,annotationStorageSerializable:F}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#n?.reject(new Error("Worker was destroyed during onPassword callback"));let E=[];for(let U of this.#e.values())E.push(U._destroy());this.#e.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let L=this.messageHandler.sendWithPromise("Terminate",null);return E.push(L),Promise.all(E).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),(0,a.cleanupTextLayer)(),this._networkStream?.cancelAllRequests(new o.AbortException("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:E,loadingTask:L}=this;E.on("GetReader",((U,B)=>{(0,o.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=k=>{this._lastProgress={loaded:k.loaded,total:k.total}},B.onPull=()=>{this._fullReader.read().then((function({value:k,done:F}){F?B.close():((0,o.assert)(k instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),B.enqueue(new Uint8Array(k),1,[k]))})).catch((k=>{B.error(k)}))},B.onCancel=k=>{this._fullReader.cancel(k),B.ready.catch((F=>{if(!this.destroyed)throw F}))}})),E.on("ReaderHeadersReady",(U=>{let B=Promise.withResolvers(),k=this._fullReader;return k.headersReady.then((()=>{(!k.isStreamingSupported||!k.isRangeSupported)&&(this._lastProgress&&L.onProgress?.(this._lastProgress),k.onProgress=F=>{L.onProgress?.({loaded:F.loaded,total:F.total})}),B.resolve({isStreamingSupported:k.isStreamingSupported,isRangeSupported:k.isRangeSupported,contentLength:k.contentLength})}),B.reject),B.promise})),E.on("GetRangeReader",((U,B)=>{(0,o.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let k=this._networkStream.getRangeReader(U.begin,U.end);k?(B.onPull=()=>{k.read().then((function({value:F,done:V}){V?B.close():((0,o.assert)(F instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),B.enqueue(new Uint8Array(F),1,[F]))})).catch((F=>{B.error(F)}))},B.onCancel=F=>{k.cancel(F),B.ready.catch((V=>{if(!this.destroyed)throw V}))}):B.close()})),E.on("GetDoc",(({pdfInfo:U})=>{this._numPages=U.numPages,this._htmlForXfa=U.htmlForXfa,delete U.htmlForXfa,L._capability.resolve(new st(U,this))})),E.on("DocException",(function(U){let B;switch(U.name){case"PasswordException":B=new o.PasswordException(U.message,U.code);break;case"InvalidPDFException":B=new o.InvalidPDFException(U.message);break;case"MissingPDFException":B=new o.MissingPDFException(U.message);break;case"UnexpectedResponseException":B=new o.UnexpectedResponseException(U.message,U.status);break;case"UnknownErrorException":B=new o.UnknownErrorException(U.message,U.details);break;default:(0,o.unreachable)("DocException - expected a valid Error.")}L._capability.reject(B)})),E.on("PasswordRequest",(U=>{if(this.#n=Promise.withResolvers(),L.onPassword){let B=k=>{k instanceof Error?this.#n.reject(k):this.#n.resolve({password:k})};try{L.onPassword(B,U.code)}catch(k){this.#n.reject(k)}}else this.#n.reject(new o.PasswordException(U.message,U.code));return this.#n.promise})),E.on("DataLoaded",(U=>{L.onProgress?.({loaded:U.length,total:U.length}),this.downloadInfoCapability.resolve(U)})),E.on("StartRenderPage",(U=>{this.destroyed||this.#e.get(U.pageIndex)._startRenderPage(U.transparency,U.cacheKey)})),E.on("commonobj",(([U,B,k])=>{if(this.destroyed||this.commonObjs.has(U))return null;switch(B){case"Font":let F=this._params;if("error"in k){let tt=k.error;(0,o.warn)(`Error during font loading: ${tt}`),this.commonObjs.resolve(U,tt);break}let V=F.pdfBug&&globalThis.FontInspector?.enabled?(tt,rt)=>globalThis.FontInspector.fontAdded(tt,rt):null,Q=new m.FontFaceObject(k,{isEvalSupported:F.isEvalSupported,disableFontFace:F.disableFontFace,ignoreErrors:F.ignoreErrors,inspectFont:V});this.fontLoader.bind(Q).catch((()=>E.sendWithPromise("FontFallback",{id:U}))).finally((()=>{!F.fontExtraProperties&&Q.data&&(Q.data=null),this.commonObjs.resolve(U,Q)}));break;case"CopyLocalImage":let{imageRef:Z}=k;(0,o.assert)(Z,"The imageRef must be defined.");for(let tt of this.#e.values())for(let[,rt]of tt.objs)if(rt.ref===Z)return rt.dataLen?(this.commonObjs.resolve(U,structuredClone(rt)),rt.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(U,k);break;default:throw new Error(`Got unknown common object type ${B}`)}return null})),E.on("obj",(([U,B,k,F])=>{if(this.destroyed)return;let V=this.#e.get(B);if(!V.objs.has(U))if(V._intentStates.size!==0)switch(k){case"Image":V.objs.resolve(U,F),F?.dataLen>o.MAX_IMAGE_SIZE_TO_CACHE&&(V._maybeCleanupAfterRender=!0);break;case"Pattern":V.objs.resolve(U,F);break;default:throw new Error(`Got unknown object type ${k}`)}else F?.bitmap?.close()})),E.on("DocProgress",(U=>{this.destroyed||L.onProgress?.({loaded:U.loaded,total:U.total})})),E.on("FetchBuiltInCMap",(U=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(U):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")))),E.on("FetchStandardFontData",(U=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(U):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&(0,o.warn)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:E,transfer:L}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:E,filename:this._fullReader?.filename??null},L).finally((()=>{this.annotationStorage.resetModified()}))}getPage(E){if(!Number.isInteger(E)||E<=0||E>this._numPages)return Promise.reject(new Error("Invalid page request."));let L=E-1,U=this.#i.get(L);if(U)return U;let B=this.messageHandler.sendWithPromise("GetPage",{pageIndex:L}).then((k=>{if(this.destroyed)throw new Error("Transport destroyed");let F=new ct(L,k,this,this._params.pdfBug);return this.#e.set(L,F),F}));return this.#i.set(L,B),B}getPageIndex(E){return typeof E!="object"||E===null||!Number.isInteger(E.num)||E.num<0||!Number.isInteger(E.gen)||E.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:E.num,gen:E.gen})}getAnnotations(E,L){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:E,intent:L})}getFieldObjects(){return this.#r("GetFieldObjects")}hasJSActions(){return this.#r("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(E){return typeof E!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:E})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#r("GetDocJSActions")}getPageJSActions(E){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:E})}getStructTree(E){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:E})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(E){return this.#r("GetOptionalContentConfig").then((L=>new l.OptionalContentConfig(L,E)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let E="GetMetadata",L=this.#t.get(E);if(L)return L;let U=this.messageHandler.sendWithPromise(E,null).then((B=>({info:B[0],metadata:B[1]?new T.Metadata(B[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#t.set(E,U),U}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(E=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(let L of this.#e.values())if(!L.cleanup())throw new Error(`startCleanup: Page ${L.pageNumber} is currently rendering.`);this.commonObjs.clear(),E||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),(0,a.cleanupTextLayer)()}}get loadingParams(){let{disableAutoFetch:E,enableXfa:L}=this._params;return(0,o.shadow)(this,"loadingParams",{disableAutoFetch:E,enableXfa:L})}}let I=Symbol("INITIAL_DATA");class h{#t=Object.create(null);#e(E){return this.#t[E]||={...Promise.withResolvers(),data:I}}get(E,L=null){if(L){let B=this.#e(E);return B.promise.then((()=>L(B.data))),null}let U=this.#t[E];if(!U||U.data===I)throw new Error(`Requesting object that isn't resolved yet ${E}.`);return U.data}has(E){let L=this.#t[E];return!!L&&L.data!==I}resolve(E,L=null){let U=this.#e(E);U.data=L,U.resolve()}clear(){for(let E in this.#t){let{data:L}=this.#t[E];L?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(let E in this.#t){let{data:L}=this.#t[E];L!==I&&(yield[E,L])}}}class b{#t=null;constructor(E){this.#t=E,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(E=0){this.#t.cancel(null,E)}get separateAnnots(){let{separateAnnots:E}=this.#t.operatorList;if(!E)return!1;let{annotationCanvasMap:L}=this.#t;return E.form||E.canvas&&L?.size>0}}class C{static#t=new WeakSet;constructor({callback:E,params:L,objs:U,commonObjs:B,annotationCanvasMap:k,operatorList:F,pageIndex:V,canvasFactory:Q,filterFactory:Z,useRequestAnimationFrame:tt=!1,pdfBug:rt=!1,pageColors:pt=null}){this.callback=E,this.params=L,this.objs=U,this.commonObjs=B,this.annotationCanvasMap=k,this.operatorListIdx=null,this.operatorList=F,this._pageIndex=V,this.canvasFactory=Q,this.filterFactory=Z,this._pdfBug=rt,this.pageColors=pt,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=tt===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new b(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=L.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:E=!1,optionalContentConfig:L}){if(this.cancelled)return;if(this._canvas){if(C.#t.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");C.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:U,viewport:B,transform:k,background:F}=this.params;this.gfx=new u.CanvasGraphics(U,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:L},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:k,viewport:B,transparency:E,background:F}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(E=null,L=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),C.#t.delete(this._canvas),this.callback(E||new d.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,L))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?window.requestAnimationFrame((()=>{this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),C.#t.delete(this._canvas),this.callback())))}}let P="4.1.392",O="fcb76a78d";r()}catch(S){r(S)}}))},583:(n,t,e)=>{e.d(t,{BaseCMapReaderFactory:()=>g,BaseCanvasFactory:()=>o,BaseFilterFactory:()=>r,BaseSVGFactory:()=>m,BaseStandardFontDataFactory:()=>d});var i=e(292);class r{constructor(){this.constructor===r&&(0,i.unreachable)("Cannot initialize BaseFilterFactory.")}addFilter(u){return"none"}addHCMFilter(u,a){return"none"}addHighlightHCMFilter(u,a,p,x,T){return"none"}destroy(u=!1){}}class o{constructor(){this.constructor===o&&(0,i.unreachable)("Cannot initialize BaseCanvasFactory.")}create(u,a){if(u<=0||a<=0)throw new Error("Invalid canvas size");let p=this._createCanvas(u,a);return{canvas:p,context:p.getContext("2d")}}reset(u,a,p){if(!u.canvas)throw new Error("Canvas is not specified");if(a<=0||p<=0)throw new Error("Invalid canvas size");u.canvas.width=a,u.canvas.height=p}destroy(u){if(!u.canvas)throw new Error("Canvas is not specified");u.canvas.width=0,u.canvas.height=0,u.canvas=null,u.context=null}_createCanvas(u,a){(0,i.unreachable)("Abstract method `_createCanvas` called.")}}class g{constructor({baseUrl:u=null,isCompressed:a=!0}){this.constructor===g&&(0,i.unreachable)("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=u,this.isCompressed=a}async fetch({name:u}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!u)throw new Error("CMap name must be specified.");let a=this.baseUrl+u+(this.isCompressed?".bcmap":""),p=this.isCompressed?i.CMapCompressionType.BINARY:i.CMapCompressionType.NONE;return this._fetchData(a,p).catch((x=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${a}`)}))}_fetchData(u,a){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class d{constructor({baseUrl:u=null}){this.constructor===d&&(0,i.unreachable)("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=u}async fetch({filename:u}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!u)throw new Error("Font filename must be specified.");let a=`${this.baseUrl}${u}`;return this._fetchData(a).catch((p=>{throw new Error(`Unable to load font data at: ${a}`)}))}_fetchData(u){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class m{constructor(){this.constructor===m&&(0,i.unreachable)("Cannot initialize BaseSVGFactory.")}create(u,a,p=!1){if(u<=0||a<=0)throw new Error("Invalid SVG dimensions");let x=this._createSVG("svg:svg");return x.setAttribute("version","1.1"),p||(x.setAttribute("width",`${u}px`),x.setAttribute("height",`${a}px`)),x.setAttribute("preserveAspectRatio","none"),x.setAttribute("viewBox",`0 0 ${u} ${a}`),x}createElement(u){if(typeof u!="string")throw new Error("Invalid SVG element type");return this._createSVG(u)}_createSVG(u){(0,i.unreachable)("Abstract method `_createSVG` called.")}}},923:(n,t,e)=>{e.d(t,{CanvasGraphics:()=>nt});var i=e(292),r=e(419);let o="Fill",g="Stroke",d="Shading";function m(G,A){if(!A)return;let _=A[2]-A[0],I=A[3]-A[1],h=new Path2D;h.rect(A[0],A[1],_,I),G.clip(h)}class v{constructor(){this.constructor===v&&(0,i.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,i.unreachable)("Abstract method `getPattern` called.")}}class u extends v{constructor(A){super(),this._type=A[1],this._bbox=A[2],this._colorStops=A[3],this._p0=A[4],this._p1=A[5],this._r0=A[6],this._r1=A[7],this.matrix=null}_createGradient(A){let _;this._type==="axial"?_=A.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(_=A.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let I of this._colorStops)_.addColorStop(I[0],I[1]);return _}getPattern(A,_,I,h){let b;if(h===g||h===o){let C=_.current.getClippedPathBoundingBox(h,(0,r.getCurrentTransform)(A))||[0,0,0,0],P=Math.ceil(C[2]-C[0])||1,O=Math.ceil(C[3]-C[1])||1,M=_.cachedCanvases.getCanvas("pattern",P,O,!0),E=M.context;E.clearRect(0,0,E.canvas.width,E.canvas.height),E.beginPath(),E.rect(0,0,E.canvas.width,E.canvas.height),E.translate(-C[0],-C[1]),I=i.Util.transform(I,[1,0,0,1,C[0],C[1]]),E.transform(..._.baseTransform),this.matrix&&E.transform(...this.matrix),m(E,this._bbox),E.fillStyle=this._createGradient(E),E.fill(),b=A.createPattern(M.canvas,"no-repeat");let L=new DOMMatrix(I);b.setTransform(L)}else m(A,this._bbox),b=this._createGradient(A);return b}}function a(G,A,_,I,h,b,C,P){let O=A.coords,M=A.colors,E=G.data,L=4*G.width,U;O[_+1]>O[I+1]&&(U=_,_=I,I=U,U=b,b=C,C=U),O[I+1]>O[h+1]&&(U=I,I=h,h=U,U=C,C=P,P=U),O[_+1]>O[I+1]&&(U=_,_=I,I=U,U=b,b=C,C=U);let B=(O[_]+A.offsetX)*A.scaleX,k=(O[_+1]+A.offsetY)*A.scaleY,F=(O[I]+A.offsetX)*A.scaleX,V=(O[I+1]+A.offsetY)*A.scaleY,Q=(O[h]+A.offsetX)*A.scaleX,Z=(O[h+1]+A.offsetY)*A.scaleY;if(k>=Z)return;let tt=M[b],rt=M[b+1],pt=M[b+2],dt=M[C],lt=M[C+1],vt=M[C+2],Et=M[P],wt=M[P+1],Ct=M[P+2],Tt=Math.round(k),It=Math.round(Z),Ot,Jt,ae,me,le,ue,je,ze;for(let Yt=Tt;Yt<=It;Yt++){if(Yt<V){let Gt=Yt<k?0:(k-Yt)/(k-V);Ot=B-(B-F)*Gt,Jt=tt-(tt-dt)*Gt,ae=rt-(rt-lt)*Gt,me=pt-(pt-vt)*Gt}else{let Gt;Gt=Yt>Z?1:V===Z?0:(V-Yt)/(V-Z),Ot=F-(F-Q)*Gt,Jt=dt-(dt-Et)*Gt,ae=lt-(lt-wt)*Gt,me=vt-(vt-Ct)*Gt}let Xt;Xt=Yt<k?0:Yt>Z?1:(k-Yt)/(k-Z),le=B-(B-Q)*Xt,ue=tt-(tt-Et)*Xt,je=rt-(rt-wt)*Xt,ze=pt-(pt-Ct)*Xt;let Ve=Math.round(Math.min(Ot,le)),Wi=Math.round(Math.max(Ot,le)),pe=L*Yt+4*Ve;for(let Gt=Ve;Gt<=Wi;Gt++)Xt=(Ot-Gt)/(Ot-le),Xt<0?Xt=0:Xt>1&&(Xt=1),E[pe++]=Jt-(Jt-ue)*Xt|0,E[pe++]=ae-(ae-je)*Xt|0,E[pe++]=me-(me-ze)*Xt|0,E[pe++]=255}}function p(G,A,_){let I=A.coords,h=A.colors,b,C;switch(A.type){case"lattice":let P=A.verticesPerRow,O=Math.floor(I.length/P)-1,M=P-1;for(b=0;b<O;b++){let E=b*P;for(let L=0;L<M;L++,E++)a(G,_,I[E],I[E+1],I[E+P],h[E],h[E+1],h[E+P]),a(G,_,I[E+P+1],I[E+1],I[E+P],h[E+P+1],h[E+1],h[E+P])}break;case"triangles":for(b=0,C=I.length;b<C;b+=3)a(G,_,I[b],I[b+1],I[b+2],h[b],h[b+1],h[b+2]);break;default:throw new Error("illegal figure")}}class x extends v{constructor(A){super(),this._coords=A[2],this._colors=A[3],this._figures=A[4],this._bounds=A[5],this._bbox=A[7],this._background=A[8],this.matrix=null}_createMeshCanvas(A,_,I){let h=Math.floor(this._bounds[0]),b=Math.floor(this._bounds[1]),C=Math.ceil(this._bounds[2])-h,P=Math.ceil(this._bounds[3])-b,O=Math.min(Math.ceil(Math.abs(C*A[0]*1.1)),3e3),M=Math.min(Math.ceil(Math.abs(P*A[1]*1.1)),3e3),E=C/O,L=P/M,U={coords:this._coords,colors:this._colors,offsetX:-h,offsetY:-b,scaleX:1/E,scaleY:1/L},B=O+4,k=M+4,F=I.getCanvas("mesh",B,k,!1),V=F.context,Q=V.createImageData(O,M);if(_){let Z=Q.data;for(let tt=0,rt=Z.length;tt<rt;tt+=4)Z[tt]=_[0],Z[tt+1]=_[1],Z[tt+2]=_[2],Z[tt+3]=255}for(let Z of this._figures)p(Q,Z,U);return V.putImageData(Q,2,2),{canvas:F.canvas,offsetX:h-2*E,offsetY:b-2*L,scaleX:E,scaleY:L}}getPattern(A,_,I,h){m(A,this._bbox);let b;if(h===d)b=i.Util.singularValueDecompose2dScale((0,r.getCurrentTransform)(A));else if(b=i.Util.singularValueDecompose2dScale(_.baseTransform),this.matrix){let P=i.Util.singularValueDecompose2dScale(this.matrix);b=[b[0]*P[0],b[1]*P[1]]}let C=this._createMeshCanvas(b,h===d?null:this._background,_.cachedCanvases);return h!==d&&(A.setTransform(..._.baseTransform),this.matrix&&A.transform(...this.matrix)),A.translate(C.offsetX,C.offsetY),A.scale(C.scaleX,C.scaleY),A.createPattern(C.canvas,"no-repeat")}}class T extends v{getPattern(){return"hotpink"}}let l=1,y=2;class s{static MAX_PATTERN_SIZE=3e3;constructor(A,_,I,h,b){this.operatorList=A[2],this.matrix=A[3]||[1,0,0,1,0,0],this.bbox=A[4],this.xstep=A[5],this.ystep=A[6],this.paintType=A[7],this.tilingType=A[8],this.color=_,this.ctx=I,this.canvasGraphicsFactory=h,this.baseTransform=b}createPatternCanvas(A){let _=this.operatorList,I=this.bbox,h=this.xstep,b=this.ystep,C=this.paintType,P=this.tilingType,O=this.color,M=this.canvasGraphicsFactory;(0,i.info)("TilingType: "+P);let E=I[0],L=I[1],U=I[2],B=I[3],k=i.Util.singularValueDecompose2dScale(this.matrix),F=i.Util.singularValueDecompose2dScale(this.baseTransform),V=[k[0]*F[0],k[1]*F[1]],Q=this.getSizeAndScale(h,this.ctx.canvas.width,V[0]),Z=this.getSizeAndScale(b,this.ctx.canvas.height,V[1]),tt=A.cachedCanvases.getCanvas("pattern",Q.size,Z.size,!0),rt=tt.context,pt=M.createCanvasGraphics(rt);pt.groupLevel=A.groupLevel,this.setFillAndStrokeStyleToContext(pt,C,O);let dt=E,lt=L,vt=U,Et=B;return E<0&&(dt=0,vt+=Math.abs(E)),L<0&&(lt=0,Et+=Math.abs(L)),rt.translate(-Q.scale*dt,-Z.scale*lt),pt.transform(Q.scale,0,0,Z.scale,0,0),rt.save(),this.clipBbox(pt,dt,lt,vt,Et),pt.baseTransform=(0,r.getCurrentTransform)(pt.ctx),pt.executeOperatorList(_),pt.endDrawing(),{canvas:tt.canvas,scaleX:Q.scale,scaleY:Z.scale,offsetX:dt,offsetY:lt}}getSizeAndScale(A,_,I){A=Math.abs(A);let h=Math.max(s.MAX_PATTERN_SIZE,_),b=Math.ceil(A*I);return b>=h?b=h:I=b/A,{scale:I,size:b}}clipBbox(A,_,I,h,b){let C=h-_,P=b-I;A.ctx.rect(_,I,C,P),A.current.updateRectMinMax((0,r.getCurrentTransform)(A.ctx),[_,I,h,b]),A.clip(),A.endPath()}setFillAndStrokeStyleToContext(A,_,I){let h=A.ctx,b=A.current;switch(_){case l:let C=this.ctx;h.fillStyle=C.fillStyle,h.strokeStyle=C.strokeStyle,b.fillColor=C.fillStyle,b.strokeColor=C.strokeStyle;break;case y:let P=i.Util.makeHexColor(I[0],I[1],I[2]);h.fillStyle=P,h.strokeStyle=P,b.fillColor=P,b.strokeColor=P;break;default:throw new i.FormatError(`Unsupported paint type: ${_}`)}}getPattern(A,_,I,h){let b=I;h!==d&&(b=i.Util.transform(b,_.baseTransform),this.matrix&&(b=i.Util.transform(b,this.matrix)));let C=this.createPatternCanvas(_),P=new DOMMatrix(b);P=P.translate(C.offsetX,C.offsetY),P=P.scale(1/C.scaleX,1/C.scaleY);let O=A.createPattern(C.canvas,"repeat");return O.setTransform(P),O}}function c({src:G,srcPos:A=0,dest:_,width:I,height:h,nonBlackColor:b=4294967295,inverseDecode:C=!1}){let P=i.FeatureTest.isLittleEndian?4278190080:255,[O,M]=C?[b,P]:[P,b],E=I>>3,L=7&I,U=G.length;_=new Uint32Array(_.buffer);let B=0;for(let k=0;k<h;k++){for(let V=A+E;A<V;A++){let Q=A<U?G[A]:255;_[B++]=128&Q?M:O,_[B++]=64&Q?M:O,_[B++]=32&Q?M:O,_[B++]=16&Q?M:O,_[B++]=8&Q?M:O,_[B++]=4&Q?M:O,_[B++]=2&Q?M:O,_[B++]=1&Q?M:O}if(L===0)continue;let F=A<U?G[A++]:255;for(let V=0;V<L;V++)_[B++]=F&1<<7-V?M:O}return{srcPos:A,destPos:B}}let f=4096,w=16;class R{constructor(A){this.canvasFactory=A,this.cache=Object.create(null)}getCanvas(A,_,I){let h;return this.cache[A]!==void 0?(h=this.cache[A],this.canvasFactory.reset(h,_,I)):(h=this.canvasFactory.create(_,I),this.cache[A]=h),h}delete(A){delete this.cache[A]}clear(){for(let A in this.cache){let _=this.cache[A];this.canvasFactory.destroy(_),delete this.cache[A]}}}function S(G,A,_,I,h,b,C,P,O,M){let[E,L,U,B,k,F]=(0,r.getCurrentTransform)(G);if(L===0&&U===0){let V=C*E+k,Q=Math.round(V),Z=P*B+F,tt=Math.round(Z),rt=(C+O)*E+k,pt=Math.abs(Math.round(rt)-Q)||1,dt=(P+M)*B+F,lt=Math.abs(Math.round(dt)-tt)||1;return G.setTransform(Math.sign(E),0,0,Math.sign(B),Q,tt),G.drawImage(A,_,I,h,b,0,0,pt,lt),G.setTransform(E,L,U,B,k,F),[pt,lt]}if(E===0&&B===0){let V=P*U+k,Q=Math.round(V),Z=C*L+F,tt=Math.round(Z),rt=(P+M)*U+k,pt=Math.abs(Math.round(rt)-Q)||1,dt=(C+O)*L+F,lt=Math.abs(Math.round(dt)-tt)||1;return G.setTransform(0,Math.sign(L),Math.sign(U),0,Q,tt),G.drawImage(A,_,I,h,b,0,0,lt,pt),G.setTransform(E,L,U,B,k,F),[lt,pt]}return G.drawImage(A,_,I,h,b,C,P,O,M),[Math.hypot(E,L)*O,Math.hypot(U,B)*M]}class D{constructor(A,_){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=i.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=i.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=i.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,A,_])}clone(){let A=Object.create(this);return A.clipBox=this.clipBox.slice(),A}setCurrentPoint(A,_){this.x=A,this.y=_}updatePathMinMax(A,_,I){[_,I]=i.Util.applyTransform([_,I],A),this.minX=Math.min(this.minX,_),this.minY=Math.min(this.minY,I),this.maxX=Math.max(this.maxX,_),this.maxY=Math.max(this.maxY,I)}updateRectMinMax(A,_){let I=i.Util.applyTransform(_,A),h=i.Util.applyTransform(_.slice(2),A),b=i.Util.applyTransform([_[0],_[3]],A),C=i.Util.applyTransform([_[2],_[1]],A);this.minX=Math.min(this.minX,I[0],h[0],b[0],C[0]),this.minY=Math.min(this.minY,I[1],h[1],b[1],C[1]),this.maxX=Math.max(this.maxX,I[0],h[0],b[0],C[0]),this.maxY=Math.max(this.maxY,I[1],h[1],b[1],C[1])}updateScalingPathMinMax(A,_){i.Util.scaleMinMax(A,_),this.minX=Math.min(this.minX,_[0]),this.minY=Math.min(this.minY,_[1]),this.maxX=Math.max(this.maxX,_[2]),this.maxY=Math.max(this.maxY,_[3])}updateCurvePathMinMax(A,_,I,h,b,C,P,O,M,E){let L=i.Util.bezierBoundingBox(_,I,h,b,C,P,O,M,E);E||this.updateRectMinMax(A,L)}getPathBoundingBox(A=o,_=null){let I=[this.minX,this.minY,this.maxX,this.maxY];if(A===g){_||(0,i.unreachable)("Stroke bounding box must include transform.");let h=i.Util.singularValueDecompose2dScale(_),b=h[0]*this.lineWidth/2,C=h[1]*this.lineWidth/2;I[0]-=b,I[1]-=C,I[2]+=b,I[3]+=C}return I}updateClipFromPath(){let A=i.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(A||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(A){this.clipBox=A,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(A=o,_=null){return i.Util.intersect(this.clipBox,this.getPathBoundingBox(A,_))}}function N(G,A){if(typeof ImageData<"u"&&A instanceof ImageData){G.putImageData(A,0,0);return}let _=A.height,I=A.width,h=_%w,b=(_-h)/w,C=h===0?b:b+1,P=G.createImageData(I,w),O,M=0,E=A.data,L=P.data,U,B,k,F;if(A.kind===i.ImageKind.GRAYSCALE_1BPP){let V=E.byteLength,Q=new Uint32Array(L.buffer,0,L.byteLength>>2),Z=Q.length,tt=I+7>>3,rt=4294967295,pt=i.FeatureTest.isLittleEndian?4278190080:255;for(U=0;U<C;U++){for(k=U<b?w:h,O=0,B=0;B<k;B++){let dt=V-M,lt=0,vt=dt>tt?I:8*dt-7,Et=-8&vt,wt=0,Ct=0;for(;lt<Et;lt+=8)Ct=E[M++],Q[O++]=128&Ct?rt:pt,Q[O++]=64&Ct?rt:pt,Q[O++]=32&Ct?rt:pt,Q[O++]=16&Ct?rt:pt,Q[O++]=8&Ct?rt:pt,Q[O++]=4&Ct?rt:pt,Q[O++]=2&Ct?rt:pt,Q[O++]=1&Ct?rt:pt;for(;lt<vt;lt++)wt===0&&(Ct=E[M++],wt=128),Q[O++]=Ct&wt?rt:pt,wt>>=1}for(;O<Z;)Q[O++]=0;G.putImageData(P,0,U*w)}}else if(A.kind===i.ImageKind.RGBA_32BPP){for(B=0,F=I*w*4,U=0;U<b;U++)L.set(E.subarray(M,M+F)),M+=F,G.putImageData(P,0,B),B+=w;U<C&&(F=I*h*4,L.set(E.subarray(M,M+F)),G.putImageData(P,0,B))}else{if(A.kind!==i.ImageKind.RGB_24BPP)throw new Error(`bad image kind: ${A.kind}`);for(k=w,F=I*k,U=0;U<C;U++){for(U>=b&&(k=h,F=I*k),O=0,B=F;B--;)L[O++]=E[M++],L[O++]=E[M++],L[O++]=E[M++],L[O++]=255;G.putImageData(P,0,U*w)}}}function H(G,A){if(A.bitmap){G.drawImage(A.bitmap,0,0);return}let _=A.height,I=A.width,h=_%w,b=(_-h)/w,C=h===0?b:b+1,P=G.createImageData(I,w),O=0,M=A.data,E=P.data;for(let L=0;L<C;L++){let U=L<b?w:h;({srcPos:O}=c({src:M,srcPos:O,dest:E,width:I,height:U,nonBlackColor:0})),G.putImageData(P,0,L*w)}}function j(G,A){let _=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let I of _)G[I]!==void 0&&(A[I]=G[I]);G.setLineDash!==void 0&&(A.setLineDash(G.getLineDash()),A.lineDashOffset=G.lineDashOffset)}function Y(G){if(G.strokeStyle=G.fillStyle="#000000",G.fillRule="nonzero",G.globalAlpha=1,G.lineWidth=1,G.lineCap="butt",G.lineJoin="miter",G.miterLimit=10,G.globalCompositeOperation="source-over",G.font="10px sans-serif",G.setLineDash!==void 0&&(G.setLineDash([]),G.lineDashOffset=0),!i.isNodeJS){let{filter:A}=G;A!=="none"&&A!==""&&(G.filter="none")}}function it(G,A,_,I){let h=G.length;for(let b=3;b<h;b+=4){let C=G[b];if(C===0)G[b-3]=A,G[b-2]=_,G[b-1]=I;else if(C<255){let P=255-C;G[b-3]=G[b-3]*C+A*P>>8,G[b-2]=G[b-2]*C+_*P>>8,G[b-1]=G[b-1]*C+I*P>>8}}}function ot(G,A,_){let I=G.length;for(let h=3;h<I;h+=4){let b=_?_[G[h]]:G[h];A[h]=A[h]*b*.00392156862745098|0}}function K(G,A,_){let I=G.length;for(let h=3;h<I;h+=4){let b=77*G[h-3]+152*G[h-2]+28*G[h-1];A[h]=_?A[h]*_[b>>8]>>8:A[h]*b>>16}}function z(G,A,_,I){let h=I[0],b=I[1],C=I[2]-h,P=I[3]-b;C!==0&&P!==0&&((function(M,E,L,U,B,k,F,V,Q,Z,tt){let rt=!!k,pt=rt?k[0]:0,dt=rt?k[1]:0,lt=rt?k[2]:0,vt=B==="Luminosity"?K:ot,Et=Math.min(U,Math.ceil(1048576/L));for(let wt=0;wt<U;wt+=Et){let Ct=Math.min(Et,U-wt),Tt=M.getImageData(V-Z,wt+(Q-tt),L,Ct),It=E.getImageData(V,wt+Q,L,Ct);rt&&it(Tt.data,pt,dt,lt),vt(Tt.data,It.data,F),E.putImageData(It,V,wt+Q)}})(A.context,_,C,P,A.subtype,A.backdrop,A.transferMap,h,b,A.offsetX,A.offsetY),G.save(),G.globalAlpha=1,G.globalCompositeOperation="source-over",G.setTransform(1,0,0,1,0,0),G.drawImage(_.canvas,0,0),G.restore())}function W(G,A){let _=i.Util.singularValueDecompose2dScale(G);_[0]=Math.fround(_[0]),_[1]=Math.fround(_[1]);let I=Math.fround((globalThis.devicePixelRatio||1)*r.PixelsPerInch.PDF_TO_CSS_UNITS);return A!==void 0?A:_[0]<=I||_[1]<=I}let X=["butt","round","square"],et=["miter","round","bevel"],st={},ct={};class nt{constructor(A,_,I,h,b,{optionalContentConfig:C,markedContentStack:P=null},O,M){this.ctx=A,this.current=new D(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=_,this.objs=I,this.canvasFactory=h,this.filterFactory=b,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=P||[],this.optionalContentConfig=C,this.cachedCanvases=new R(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=O,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=M,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(A,_=null){return typeof A=="string"?A.startsWith("g_")?this.commonObjs.get(A):this.objs.get(A):_}beginDrawing({transform:A,viewport:_,transparency:I=!1,background:h=null}){let b=this.ctx.canvas.width,C=this.ctx.canvas.height,P=this.ctx.fillStyle;if(this.ctx.fillStyle=h||"#ffffff",this.ctx.fillRect(0,0,b,C),this.ctx.fillStyle=P,I){let O=this.cachedCanvases.getCanvas("transparent",b,C);this.compositeCtx=this.ctx,this.transparentCanvas=O.canvas,this.ctx=O.context,this.ctx.save(),this.ctx.transform(...(0,r.getCurrentTransform)(this.compositeCtx))}this.ctx.save(),Y(this.ctx),A&&(this.ctx.transform(...A),this.outputScaleX=A[0],this.outputScaleY=A[0]),this.ctx.transform(..._.transform),this.viewportScale=_.scale,this.baseTransform=(0,r.getCurrentTransform)(this.ctx)}executeOperatorList(A,_,I,h){let b=A.argsArray,C=A.fnArray,P=_||0,O=b.length;if(O===P)return P;let M=O-P>10&&typeof I=="function",E=M?Date.now()+15:0,L=0,U=this.commonObjs,B=this.objs,k;for(;;){if(h!==void 0&&P===h.nextBreakPoint)return h.breakIt(P,I),P;if(k=C[P],k!==i.OPS.dependency)this[k].apply(this,b[P]);else for(let F of b[P]){let V=F.startsWith("g_")?U:B;if(!V.has(F))return V.get(F,I),P}if(P++,P===O)return P;if(M&&++L>10){if(Date.now()>E)return I(),P;L=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let A of this._cachedBitmapsMap.values()){for(let _ of A.values())typeof HTMLCanvasElement<"u"&&_ instanceof HTMLCanvasElement&&(_.width=_.height=0);A.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){let A=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(A!=="none"){let _=this.ctx.filter;this.ctx.filter=A,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=_}}}_scaleImage(A,_){let I=A.width,h=A.height,b,C,P=Math.max(Math.hypot(_[0],_[1]),1),O=Math.max(Math.hypot(_[2],_[3]),1),M=I,E=h,L="prescale1";for(;P>2&&M>1||O>2&&E>1;){let U=M,B=E;P>2&&M>1&&(U=M>=16384?Math.floor(M/2)-1||1:Math.ceil(M/2),P/=M/U),O>2&&E>1&&(B=E>=16384?Math.floor(E/2)-1||1:Math.ceil(E)/2,O/=E/B),b=this.cachedCanvases.getCanvas(L,U,B),C=b.context,C.clearRect(0,0,U,B),C.drawImage(A,0,0,M,E,0,0,U,B),A=b.canvas,M=U,E=B,L=L==="prescale1"?"prescale2":"prescale1"}return{img:A,paintWidth:M,paintHeight:E}}_createMaskCanvas(A){let _=this.ctx,{width:I,height:h}=A,b=this.current.fillColor,C=this.current.patternFill,P=(0,r.getCurrentTransform)(_),O,M,E,L;if((A.bitmap||A.data)&&A.count>1){let vt=A.bitmap||A.data.buffer;M=JSON.stringify(C?P:[P.slice(0,4),b]),O=this._cachedBitmapsMap.get(vt),O||(O=new Map,this._cachedBitmapsMap.set(vt,O));let Et=O.get(M);if(Et&&!C)return{canvas:Et,offsetX:Math.round(Math.min(P[0],P[2])+P[4]),offsetY:Math.round(Math.min(P[1],P[3])+P[5])};E=Et}E||(L=this.cachedCanvases.getCanvas("maskCanvas",I,h),H(L.context,A));let U=i.Util.transform(P,[1/I,0,0,-1/h,0,0]);U=i.Util.transform(U,[1,0,0,1,0,-h]);let[B,k,F,V]=i.Util.getAxialAlignedBoundingBox([0,0,I,h],U),Q=Math.round(F-B)||1,Z=Math.round(V-k)||1,tt=this.cachedCanvases.getCanvas("fillCanvas",Q,Z),rt=tt.context,pt=B,dt=k;rt.translate(-pt,-dt),rt.transform(...U),E||(E=this._scaleImage(L.canvas,(0,r.getCurrentTransformInverse)(rt)),E=E.img,O&&C&&O.set(M,E)),rt.imageSmoothingEnabled=W((0,r.getCurrentTransform)(rt),A.interpolate),S(rt,E,0,0,E.width,E.height,0,0,I,h),rt.globalCompositeOperation="source-in";let lt=i.Util.transform((0,r.getCurrentTransformInverse)(rt),[1,0,0,1,-pt,-dt]);return rt.fillStyle=C?b.getPattern(_,this,lt,o):b,rt.fillRect(0,0,I,h),O&&!C&&(this.cachedCanvases.delete("fillCanvas"),O.set(M,tt.canvas)),{canvas:tt.canvas,offsetX:Math.round(pt),offsetY:Math.round(dt)}}setLineWidth(A){A!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=A,this.ctx.lineWidth=A}setLineCap(A){this.ctx.lineCap=X[A]}setLineJoin(A){this.ctx.lineJoin=et[A]}setMiterLimit(A){this.ctx.miterLimit=A}setDash(A,_){let I=this.ctx;I.setLineDash!==void 0&&(I.setLineDash(A),I.lineDashOffset=_)}setRenderingIntent(A){}setFlatness(A){}setGState(A){for(let[_,I]of A)switch(_){case"LW":this.setLineWidth(I);break;case"LC":this.setLineCap(I);break;case"LJ":this.setLineJoin(I);break;case"ML":this.setMiterLimit(I);break;case"D":this.setDash(I[0],I[1]);break;case"RI":this.setRenderingIntent(I);break;case"FL":this.setFlatness(I);break;case"Font":this.setFont(I[0],I[1]);break;case"CA":this.current.strokeAlpha=I;break;case"ca":this.current.fillAlpha=I,this.ctx.globalAlpha=I;break;case"BM":this.ctx.globalCompositeOperation=I;break;case"SMask":this.current.activeSMask=I?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(I)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let A=this.inSMaskMode;this.current.activeSMask&&!A?this.beginSMaskMode():!this.current.activeSMask&&A&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let A=this.ctx.canvas.width,_=this.ctx.canvas.height,I="smaskGroupAt"+this.groupLevel,h=this.cachedCanvases.getCanvas(I,A,_);this.suspendedCtx=this.ctx,this.ctx=h.context;let b=this.ctx;b.setTransform(...(0,r.getCurrentTransform)(this.suspendedCtx)),j(this.suspendedCtx,b),(function(P,O){if(P._removeMirroring)throw new Error("Context is already forwarding operations.");P.__originalSave=P.save,P.__originalRestore=P.restore,P.__originalRotate=P.rotate,P.__originalScale=P.scale,P.__originalTranslate=P.translate,P.__originalTransform=P.transform,P.__originalSetTransform=P.setTransform,P.__originalResetTransform=P.resetTransform,P.__originalClip=P.clip,P.__originalMoveTo=P.moveTo,P.__originalLineTo=P.lineTo,P.__originalBezierCurveTo=P.bezierCurveTo,P.__originalRect=P.rect,P.__originalClosePath=P.closePath,P.__originalBeginPath=P.beginPath,P._removeMirroring=()=>{P.save=P.__originalSave,P.restore=P.__originalRestore,P.rotate=P.__originalRotate,P.scale=P.__originalScale,P.translate=P.__originalTranslate,P.transform=P.__originalTransform,P.setTransform=P.__originalSetTransform,P.resetTransform=P.__originalResetTransform,P.clip=P.__originalClip,P.moveTo=P.__originalMoveTo,P.lineTo=P.__originalLineTo,P.bezierCurveTo=P.__originalBezierCurveTo,P.rect=P.__originalRect,P.closePath=P.__originalClosePath,P.beginPath=P.__originalBeginPath,delete P._removeMirroring},P.save=function(){O.save(),this.__originalSave()},P.restore=function(){O.restore(),this.__originalRestore()},P.translate=function(E,L){O.translate(E,L),this.__originalTranslate(E,L)},P.scale=function(E,L){O.scale(E,L),this.__originalScale(E,L)},P.transform=function(E,L,U,B,k,F){O.transform(E,L,U,B,k,F),this.__originalTransform(E,L,U,B,k,F)},P.setTransform=function(E,L,U,B,k,F){O.setTransform(E,L,U,B,k,F),this.__originalSetTransform(E,L,U,B,k,F)},P.resetTransform=function(){O.resetTransform(),this.__originalResetTransform()},P.rotate=function(E){O.rotate(E),this.__originalRotate(E)},P.clip=function(E){O.clip(E),this.__originalClip(E)},P.moveTo=function(M,E){O.moveTo(M,E),this.__originalMoveTo(M,E)},P.lineTo=function(M,E){O.lineTo(M,E),this.__originalLineTo(M,E)},P.bezierCurveTo=function(M,E,L,U,B,k){O.bezierCurveTo(M,E,L,U,B,k),this.__originalBezierCurveTo(M,E,L,U,B,k)},P.rect=function(M,E,L,U){O.rect(M,E,L,U),this.__originalRect(M,E,L,U)},P.closePath=function(){O.closePath(),this.__originalClosePath()},P.beginPath=function(){O.beginPath(),this.__originalBeginPath()}})(b,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),j(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(A){if(!this.current.activeSMask)return;A?(A[0]=Math.floor(A[0]),A[1]=Math.floor(A[1]),A[2]=Math.ceil(A[2]),A[3]=Math.ceil(A[3])):A=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let _=this.current.activeSMask;z(this.suspendedCtx,_,this.ctx,A),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}save(){this.inSMaskMode?(j(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let A=this.current;this.stateStack.push(A),this.current=A.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),j(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(A,_,I,h,b,C){this.ctx.transform(A,_,I,h,b,C),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(A,_,I){let h=this.ctx,b=this.current,C,P,O=b.x,M=b.y,E=(0,r.getCurrentTransform)(h),L=E[0]===0&&E[3]===0||E[1]===0&&E[2]===0,U=L?I.slice(0):null;for(let B=0,k=0,F=A.length;B<F;B++)switch(0|A[B]){case i.OPS.rectangle:O=_[k++],M=_[k++];let V=_[k++],Q=_[k++],Z=O+V,tt=M+Q;h.moveTo(O,M),V===0||Q===0?h.lineTo(Z,tt):(h.lineTo(Z,M),h.lineTo(Z,tt),h.lineTo(O,tt)),L||b.updateRectMinMax(E,[O,M,Z,tt]),h.closePath();break;case i.OPS.moveTo:O=_[k++],M=_[k++],h.moveTo(O,M),L||b.updatePathMinMax(E,O,M);break;case i.OPS.lineTo:O=_[k++],M=_[k++],h.lineTo(O,M),L||b.updatePathMinMax(E,O,M);break;case i.OPS.curveTo:C=O,P=M,O=_[k+4],M=_[k+5],h.bezierCurveTo(_[k],_[k+1],_[k+2],_[k+3],O,M),b.updateCurvePathMinMax(E,C,P,_[k],_[k+1],_[k+2],_[k+3],O,M,U),k+=6;break;case i.OPS.curveTo2:C=O,P=M,h.bezierCurveTo(O,M,_[k],_[k+1],_[k+2],_[k+3]),b.updateCurvePathMinMax(E,C,P,O,M,_[k],_[k+1],_[k+2],_[k+3],U),O=_[k+2],M=_[k+3],k+=4;break;case i.OPS.curveTo3:C=O,P=M,O=_[k+2],M=_[k+3],h.bezierCurveTo(_[k],_[k+1],O,M,O,M),b.updateCurvePathMinMax(E,C,P,_[k],_[k+1],O,M,O,M,U),k+=4;break;case i.OPS.closePath:h.closePath()}L&&b.updateScalingPathMinMax(E,U),b.setCurrentPoint(O,M)}closePath(){this.ctx.closePath()}stroke(A=!0){let _=this.ctx,I=this.current.strokeColor;_.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof I=="object"&&I?.getPattern?(_.save(),_.strokeStyle=I.getPattern(_,this,(0,r.getCurrentTransformInverse)(_),g),this.rescaleAndStroke(!1),_.restore()):this.rescaleAndStroke(!0)),A&&this.consumePath(this.current.getClippedPathBoundingBox()),_.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(A=!0){let _=this.ctx,I=this.current.fillColor,h=!1;this.current.patternFill&&(_.save(),_.fillStyle=I.getPattern(_,this,(0,r.getCurrentTransformInverse)(_),o),h=!0);let b=this.current.getClippedPathBoundingBox();this.contentVisible&&b!==null&&(this.pendingEOFill?(_.fill("evenodd"),this.pendingEOFill=!1):_.fill()),h&&_.restore(),A&&this.consumePath(b)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=st}eoClip(){this.pendingClip=ct}beginText(){this.current.textMatrix=i.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){let A=this.pendingTextPaths,_=this.ctx;if(A!==void 0){_.save(),_.beginPath();for(let I of A)_.setTransform(...I.transform),_.translate(I.x,I.y),I.addToPath(_,I.fontSize);_.restore(),_.clip(),_.beginPath(),delete this.pendingTextPaths}else _.beginPath()}setCharSpacing(A){this.current.charSpacing=A}setWordSpacing(A){this.current.wordSpacing=A}setHScale(A){this.current.textHScale=A/100}setLeading(A){this.current.leading=-A}setFont(A,_){let I=this.commonObjs.get(A),h=this.current;if(!I)throw new Error(`Can't find font for ${A}`);if(h.fontMatrix=I.fontMatrix||i.FONT_IDENTITY_MATRIX,h.fontMatrix[0]!==0&&h.fontMatrix[3]!==0||(0,i.warn)("Invalid font matrix for font "+A),_<0?(_=-_,h.fontDirection=-1):h.fontDirection=1,this.current.font=I,this.current.fontSize=_,I.isType3Font)return;let b=I.loadedName||"sans-serif",C=I.systemFontInfo?.css||`"${b}", ${I.fallbackName}`,P="normal";I.black?P="900":I.bold&&(P="bold");let O=I.italic?"italic":"normal",M=_;_<16?M=16:_>100&&(M=100),this.current.fontSizeScale=_/M,this.ctx.font=`${O} ${P} ${M}px ${C}`}setTextRenderingMode(A){this.current.textRenderingMode=A}setTextRise(A){this.current.textRise=A}moveText(A,_){this.current.x=this.current.lineX+=A,this.current.y=this.current.lineY+=_}setLeadingMoveText(A,_){this.setLeading(-_),this.moveText(A,_)}setTextMatrix(A,_,I,h,b,C){this.current.textMatrix=[A,_,I,h,b,C],this.current.textMatrixScale=Math.hypot(A,_),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(A,_,I,h){let b=this.ctx,C=this.current,P=C.font,O=C.textRenderingMode,M=C.fontSize/C.fontSizeScale,E=O&i.TextRenderingMode.FILL_STROKE_MASK,L=!!(O&i.TextRenderingMode.ADD_TO_PATH_FLAG),U=C.patternFill&&!P.missingFile,B;(P.disableFontFace||L||U)&&(B=P.getPathGenerator(this.commonObjs,A)),P.disableFontFace||U?(b.save(),b.translate(_,I),b.beginPath(),B(b,M),h&&b.setTransform(...h),E!==i.TextRenderingMode.FILL&&E!==i.TextRenderingMode.FILL_STROKE||b.fill(),E!==i.TextRenderingMode.STROKE&&E!==i.TextRenderingMode.FILL_STROKE||b.stroke(),b.restore()):(E!==i.TextRenderingMode.FILL&&E!==i.TextRenderingMode.FILL_STROKE||b.fillText(A,_,I),E!==i.TextRenderingMode.STROKE&&E!==i.TextRenderingMode.FILL_STROKE||b.strokeText(A,_,I)),L&&(this.pendingTextPaths||=[]).push({transform:(0,r.getCurrentTransform)(b),x:_,y:I,fontSize:M,addToPath:B})}get isFontSubpixelAAEnabled(){let{context:A}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);A.scale(1.5,1),A.fillText("I",0,10);let _=A.getImageData(0,0,10,10).data,I=!1;for(let h=3;h<_.length;h+=4)if(_[h]>0&&_[h]<255){I=!0;break}return(0,i.shadow)(this,"isFontSubpixelAAEnabled",I)}showText(A){let _=this.current,I=_.font;if(I.isType3Font)return this.showType3Text(A);let h=_.fontSize;if(h===0)return;let b=this.ctx,C=_.fontSizeScale,P=_.charSpacing,O=_.wordSpacing,M=_.fontDirection,E=_.textHScale*M,L=A.length,U=I.vertical,B=U?1:-1,k=I.defaultVMetrics,F=h*_.fontMatrix[0],V=_.textRenderingMode===i.TextRenderingMode.FILL&&!I.disableFontFace&&!_.patternFill;b.save(),b.transform(..._.textMatrix),b.translate(_.x,_.y+_.textRise),M>0?b.scale(E,-1):b.scale(E,1);let Q;if(_.patternFill){b.save();let dt=_.fillColor.getPattern(b,this,(0,r.getCurrentTransformInverse)(b),o);Q=(0,r.getCurrentTransform)(b),b.restore(),b.fillStyle=dt}let Z=_.lineWidth,tt=_.textMatrixScale;if(tt===0||Z===0){let dt=_.textRenderingMode&i.TextRenderingMode.FILL_STROKE_MASK;dt!==i.TextRenderingMode.STROKE&&dt!==i.TextRenderingMode.FILL_STROKE||(Z=this.getSinglePixelWidth())}else Z/=tt;if(C!==1&&(b.scale(C,C),Z/=C),b.lineWidth=Z,I.isInvalidPDFjsFont){let dt=[],lt=0;for(let vt of A)dt.push(vt.unicode),lt+=vt.width;b.fillText(dt.join(""),0,0),_.x+=lt*F*E,b.restore(),this.compose();return}let rt,pt=0;for(rt=0;rt<L;++rt){let dt=A[rt];if(typeof dt=="number"){pt+=B*dt*h/1e3;continue}let lt=!1,vt=(dt.isSpace?O:0)+P,Et=dt.fontChar,wt=dt.accent,Ct,Tt,It=dt.width;if(U){let Ot=dt.vmetric||k,Jt=-(dt.vmetric?Ot[1]:.5*It)*F,ae=Ot[2]*F;It=Ot?-Ot[0]:It,Ct=Jt/C,Tt=(pt+ae)/C}else Ct=pt/C,Tt=0;if(I.remeasure&&It>0){let Ot=1e3*b.measureText(Et).width/h*C;if(It<Ot&&this.isFontSubpixelAAEnabled){let Jt=It/Ot;lt=!0,b.save(),b.scale(Jt,1),Ct/=Jt}else It!==Ot&&(Ct+=(It-Ot)/2e3*h/C)}if(this.contentVisible&&(dt.isInFont||I.missingFile)){if(V&&!wt)b.fillText(Et,Ct,Tt);else if(this.paintChar(Et,Ct,Tt,Q),wt){let Ot=Ct+h*wt.offset.x/C,Jt=Tt-h*wt.offset.y/C;this.paintChar(wt.fontChar,Ot,Jt,Q)}}pt+=U?It*F-vt*M:It*F+vt*M,lt&&b.restore()}U?_.y-=pt:_.x+=pt*E,b.restore(),this.compose()}showType3Text(A){let _=this.ctx,I=this.current,h=I.font,b=I.fontSize,C=I.fontDirection,P=h.vertical?1:-1,O=I.charSpacing,M=I.wordSpacing,E=I.textHScale*C,L=I.fontMatrix||i.FONT_IDENTITY_MATRIX,U=A.length,B,k,F,V;if(I.textRenderingMode!==i.TextRenderingMode.INVISIBLE&&b!==0){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,_.save(),_.transform(...I.textMatrix),_.translate(I.x,I.y),_.scale(E,C),B=0;B<U;++B){if(k=A[B],typeof k=="number"){V=P*k*b/1e3,this.ctx.translate(V,0),I.x+=V*E;continue}let Q=(k.isSpace?M:0)+O,Z=h.charProcOperatorList[k.operatorListId];if(!Z){(0,i.warn)(`Type3 character "${k.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=k,this.save(),_.scale(b,b),_.transform(...L),this.executeOperatorList(Z),this.restore()),F=i.Util.applyTransform([k.width,0],L)[0]*b+Q,_.translate(F,0),I.x+=F*E}_.restore(),this.processingType3=null}}setCharWidth(A,_){}setCharWidthAndBounds(A,_,I,h,b,C){this.ctx.rect(I,h,b-I,C-h),this.ctx.clip(),this.endPath()}getColorN_Pattern(A){let _;if(A[0]==="TilingPattern"){let I=A[1],h=this.baseTransform||(0,r.getCurrentTransform)(this.ctx),b={createCanvasGraphics:C=>new nt(C,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};_=new s(A,I,this.ctx,b,h)}else _=this._getPattern(A[1],A[2]);return _}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(A,_,I){let h=i.Util.makeHexColor(A,_,I);this.ctx.strokeStyle=h,this.current.strokeColor=h}setFillRGBColor(A,_,I){let h=i.Util.makeHexColor(A,_,I);this.ctx.fillStyle=h,this.current.fillColor=h,this.current.patternFill=!1}_getPattern(A,_=null){let I;return this.cachedPatterns.has(A)?I=this.cachedPatterns.get(A):(I=(function(b){switch(b[0]){case"RadialAxial":return new u(b);case"Mesh":return new x(b);case"Dummy":return new T}throw new Error(`Unknown IR type: ${b[0]}`)})(this.getObject(A)),this.cachedPatterns.set(A,I)),_&&(I.matrix=_),I}shadingFill(A){if(!this.contentVisible)return;let _=this.ctx;this.save();let I=this._getPattern(A);_.fillStyle=I.getPattern(_,this,(0,r.getCurrentTransformInverse)(_),d);let h=(0,r.getCurrentTransformInverse)(_);if(h){let{width:b,height:C}=_.canvas,[P,O,M,E]=i.Util.getAxialAlignedBoundingBox([0,0,b,C],h);this.ctx.fillRect(P,O,M-P,E-O)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){(0,i.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,i.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(A,_){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),Array.isArray(A)&&A.length===6&&this.transform(...A),this.baseTransform=(0,r.getCurrentTransform)(this.ctx),_)){let I=_[2]-_[0],h=_[3]-_[1];this.ctx.rect(_[0],_[1],I,h),this.current.updateRectMinMax((0,r.getCurrentTransform)(this.ctx),_),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(A){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let _=this.ctx;A.isolated||(0,i.info)("TODO: Support non-isolated groups."),A.knockout&&(0,i.warn)("Knockout groups not supported.");let I=(0,r.getCurrentTransform)(_);if(A.matrix&&_.transform(...A.matrix),!A.bbox)throw new Error("Bounding box is required.");let h=i.Util.getAxialAlignedBoundingBox(A.bbox,(0,r.getCurrentTransform)(_)),b=[0,0,_.canvas.width,_.canvas.height];h=i.Util.intersect(h,b)||[0,0,0,0];let C=Math.floor(h[0]),P=Math.floor(h[1]),O=Math.max(Math.ceil(h[2])-C,1),M=Math.max(Math.ceil(h[3])-P,1),E=1,L=1;O>f&&(E=O/f,O=f),M>f&&(L=M/f,M=f),this.current.startNewPathAndClipBox([0,0,O,M]);let U="groupAt"+this.groupLevel;A.smask&&(U+="_smask_"+this.smaskCounter++%2);let B=this.cachedCanvases.getCanvas(U,O,M),k=B.context;k.scale(1/E,1/L),k.translate(-C,-P),k.transform(...I),A.smask?this.smaskStack.push({canvas:B.canvas,context:k,offsetX:C,offsetY:P,scaleX:E,scaleY:L,subtype:A.smask.subtype,backdrop:A.smask.backdrop,transferMap:A.smask.transferMap||null,startTransformInverse:null}):(_.setTransform(1,0,0,1,0,0),_.translate(C,P),_.scale(E,L),_.save()),j(_,k),this.ctx=k,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(_),this.groupLevel++}endGroup(A){if(!this.contentVisible)return;this.groupLevel--;let _=this.ctx,I=this.groupStack.pop();if(this.ctx=I,this.ctx.imageSmoothingEnabled=!1,A.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let h=(0,r.getCurrentTransform)(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...h);let b=i.Util.getAxialAlignedBoundingBox([0,0,_.canvas.width,_.canvas.height],h);this.ctx.drawImage(_.canvas,0,0),this.ctx.restore(),this.compose(b)}}beginAnnotation(A,_,I,h,b){if(this.#t(),Y(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),Array.isArray(_)&&_.length===4){let C=_[2]-_[0],P=_[3]-_[1];if(b&&this.annotationCanvasMap){(I=I.slice())[4]-=_[0],I[5]-=_[1],(_=_.slice())[0]=_[1]=0,_[2]=C,_[3]=P;let[O,M]=i.Util.singularValueDecompose2dScale((0,r.getCurrentTransform)(this.ctx)),{viewportScale:E}=this,L=Math.ceil(C*this.outputScaleX*E),U=Math.ceil(P*this.outputScaleY*E);this.annotationCanvas=this.canvasFactory.create(L,U);let{canvas:B,context:k}=this.annotationCanvas;this.annotationCanvasMap.set(A,B),this.annotationCanvas.savedCtx=this.ctx,this.ctx=k,this.ctx.save(),this.ctx.setTransform(O,0,0,-M,0,P*M),Y(this.ctx)}else Y(this.ctx),this.ctx.rect(_[0],_[1],C,P),this.ctx.clip(),this.endPath()}this.current=new D(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...I),this.transform(...h)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(A){if(!this.contentVisible)return;let _=A.count;(A=this.getObject(A.data,A)).count=_;let I=this.ctx,h=this.processingType3;if(h&&(h.compiled===void 0&&(h.compiled=(function(O){let{width:M,height:E}=O;if(M>1e3||E>1e3)return null;let L=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),U=M+1,B,k,F,V=new Uint8Array(U*(E+1)),Q=M+7&-8,Z=new Uint8Array(Q*E),tt=0;for(let lt of O.data){let vt=128;for(;vt>0;)Z[tt++]=lt&vt?0:255,vt>>=1}let rt=0;for(tt=0,Z[tt]!==0&&(V[0]=1,++rt),k=1;k<M;k++)Z[tt]!==Z[tt+1]&&(V[k]=Z[tt]?2:1,++rt),tt++;for(Z[tt]!==0&&(V[k]=2,++rt),B=1;B<E;B++){tt=B*Q,F=B*U,Z[tt-Q]!==Z[tt]&&(V[F]=Z[tt]?1:8,++rt);let lt=(Z[tt]?4:0)+(Z[tt-Q]?8:0);for(k=1;k<M;k++)lt=(lt>>2)+(Z[tt+1]?4:0)+(Z[tt-Q+1]?8:0),L[lt]&&(V[F+k]=L[lt],++rt),tt++;if(Z[tt-Q]!==Z[tt]&&(V[F+k]=Z[tt]?2:4,++rt),rt>1e3)return null}for(tt=Q*(E-1),F=B*U,Z[tt]!==0&&(V[F]=8,++rt),k=1;k<M;k++)Z[tt]!==Z[tt+1]&&(V[F+k]=Z[tt]?4:8,++rt),tt++;if(Z[tt]!==0&&(V[F+k]=4,++rt),rt>1e3)return null;let pt=new Int32Array([0,U,-1,0,-U,0,0,0,1]),dt=new Path2D;for(B=0;rt&&B<=E;B++){let lt=B*U,vt=lt+M;for(;lt<vt&&!V[lt];)lt++;if(lt===vt)continue;dt.moveTo(lt%U,B);let Et=lt,wt=V[lt];do{let Ct=pt[wt];do lt+=Ct;while(!V[lt]);let Tt=V[lt];Tt!==5&&Tt!==10?(wt=Tt,V[lt]=0):(wt=Tt&51*wt>>4,V[lt]&=wt>>2|wt<<2),dt.lineTo(lt%U,lt/U|0),V[lt]||--rt}while(Et!==lt);--B}return Z=null,V=null,function(lt){lt.save(),lt.scale(1/M,-1/E),lt.translate(0,-E),lt.fill(dt),lt.beginPath(),lt.restore()}})(A)),h.compiled)){h.compiled(I);return}let b=this._createMaskCanvas(A),C=b.canvas;I.save(),I.setTransform(1,0,0,1,0,0),I.drawImage(C,b.offsetX,b.offsetY),I.restore(),this.compose()}paintImageMaskXObjectRepeat(A,_,I=0,h=0,b,C){if(!this.contentVisible)return;A=this.getObject(A.data,A);let P=this.ctx;P.save();let O=(0,r.getCurrentTransform)(P);P.transform(_,I,h,b,0,0);let M=this._createMaskCanvas(A);P.setTransform(1,0,0,1,M.offsetX-O[4],M.offsetY-O[5]);for(let E=0,L=C.length;E<L;E+=2){let U=i.Util.transform(O,[_,I,h,b,C[E],C[E+1]]),[B,k]=i.Util.applyTransform([0,0],U);P.drawImage(M.canvas,B,k)}P.restore(),this.compose()}paintImageMaskXObjectGroup(A){if(!this.contentVisible)return;let _=this.ctx,I=this.current.fillColor,h=this.current.patternFill;for(let b of A){let{data:C,width:P,height:O,transform:M}=b,E=this.cachedCanvases.getCanvas("maskCanvas",P,O),L=E.context;L.save(),H(L,this.getObject(C,b)),L.globalCompositeOperation="source-in",L.fillStyle=h?I.getPattern(L,this,(0,r.getCurrentTransformInverse)(_),o):I,L.fillRect(0,0,P,O),L.restore(),_.save(),_.transform(...M),_.scale(1,-1),S(_,E.canvas,0,0,P,O,0,-1,1,1),_.restore()}this.compose()}paintImageXObject(A){if(!this.contentVisible)return;let _=this.getObject(A);_?this.paintInlineImageXObject(_):(0,i.warn)("Dependent image isn't ready yet")}paintImageXObjectRepeat(A,_,I,h){if(!this.contentVisible)return;let b=this.getObject(A);if(!b){(0,i.warn)("Dependent image isn't ready yet");return}let C=b.width,P=b.height,O=[];for(let M=0,E=h.length;M<E;M+=2)O.push({transform:[_,0,0,I,h[M],h[M+1]],x:0,y:0,w:C,h:P});this.paintInlineImageXObjectGroup(b,O)}applyTransferMapsToCanvas(A){return this.current.transferMaps!=="none"&&(A.filter=this.current.transferMaps,A.drawImage(A.canvas,0,0),A.filter="none"),A.canvas}applyTransferMapsToBitmap(A){if(this.current.transferMaps==="none")return A.bitmap;let{bitmap:_,width:I,height:h}=A,b=this.cachedCanvases.getCanvas("inlineImage",I,h),C=b.context;return C.filter=this.current.transferMaps,C.drawImage(_,0,0),C.filter="none",b.canvas}paintInlineImageXObject(A){if(!this.contentVisible)return;let _=A.width,I=A.height,h=this.ctx;if(this.save(),!i.isNodeJS){let{filter:P}=h;P!=="none"&&P!==""&&(h.filter="none")}h.scale(1/_,-1/I);let b;if(A.bitmap)b=this.applyTransferMapsToBitmap(A);else if(typeof HTMLElement=="function"&&A instanceof HTMLElement||!A.data)b=A;else{let P=this.cachedCanvases.getCanvas("inlineImage",_,I).context;N(P,A),b=this.applyTransferMapsToCanvas(P)}let C=this._scaleImage(b,(0,r.getCurrentTransformInverse)(h));h.imageSmoothingEnabled=W((0,r.getCurrentTransform)(h),A.interpolate),S(h,C.img,0,0,C.paintWidth,C.paintHeight,0,-I,_,I),this.compose(),this.restore()}paintInlineImageXObjectGroup(A,_){if(!this.contentVisible)return;let I=this.ctx,h;if(A.bitmap)h=A.bitmap;else{let b=A.width,C=A.height,P=this.cachedCanvases.getCanvas("inlineImage",b,C).context;N(P,A),h=this.applyTransferMapsToCanvas(P)}for(let b of _)I.save(),I.transform(...b.transform),I.scale(1,-1),S(I,h,b.x,b.y,b.w,b.h,0,-1,1,1),I.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(A){}markPointProps(A,_){}beginMarkedContent(A){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(A,_){A==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(_)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(A){let _=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(A);let I=this.ctx;this.pendingClip&&(_||(this.pendingClip===ct?I.clip("evenodd"):I.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),I.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let A=(0,r.getCurrentTransform)(this.ctx);if(A[1]===0&&A[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(A[0]),Math.abs(A[3]));else{let _=Math.abs(A[0]*A[3]-A[2]*A[1]),I=Math.hypot(A[0],A[2]),h=Math.hypot(A[1],A[3]);this._cachedGetSinglePixelWidth=Math.max(I,h)/_}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:A}=this.current,{a:_,b:I,c:h,d:b}=this.ctx.getTransform(),C,P;if(I===0&&h===0){let O=Math.abs(_),M=Math.abs(b);if(O===M)if(A===0)C=P=1/O;else{let E=O*A;C=P=E<1?1/E:1}else if(A===0)C=1/O,P=1/M;else{let E=O*A,L=M*A;C=E<1?1/E:1,P=L<1?1/L:1}}else{let O=Math.abs(_*b-I*h),M=Math.hypot(_,I),E=Math.hypot(h,b);if(A===0)C=E/O,P=M/O;else{let L=A*O;C=E>L?E/L:1,P=M>L?M/L:1}}this._cachedScaleForStroking[0]=C,this._cachedScaleForStroking[1]=P}return this._cachedScaleForStroking}rescaleAndStroke(A){let{ctx:_}=this,{lineWidth:I}=this.current,[h,b]=this.getScaleForStroking();if(_.lineWidth=I||1,h===1&&b===1){_.stroke();return}let C=_.getLineDash();if(A&&_.save(),_.scale(h,b),C.length>0){let P=Math.max(h,b);_.setLineDash(C.map((O=>O/P))),_.lineDashOffset/=P}_.stroke(),A&&_.restore()}isContentVisible(){for(let A=this.markedContentStack.length-1;A>=0;A--)if(!this.markedContentStack[A].visible)return!1;return!0}}for(let G in i.OPS)nt.prototype[G]!==void 0&&(nt.prototype[i.OPS[G]]=nt.prototype[G])},419:(n,t,e)=>{e.d(t,{DOMCMapReaderFactory:()=>u,DOMCanvasFactory:()=>m,DOMFilterFactory:()=>d,DOMSVGFactory:()=>p,DOMStandardFontDataFactory:()=>a,PDFDateString:()=>D,PageViewport:()=>x,PixelsPerInch:()=>g,RenderingCancelledException:()=>T,StatTimer:()=>f,fetchData:()=>v,getColorValues:()=>j,getCurrentTransform:()=>Y,getCurrentTransformInverse:()=>it,getFilenameFromUrl:()=>s,getPdfFilenameFromUrl:()=>c,getRGB:()=>H,getXfaPageViewport:()=>N,isDataScheme:()=>l,isPdfFile:()=>y,isValidFetchUrl:()=>w,noContextMenu:()=>R,setLayerDimensions:()=>ot});var i=e(583),r=e(292);let o="http://www.w3.org/2000/svg";class g{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}class d extends i.BaseFilterFactory{#t;#e;#i;#n;#r;#s=0;constructor({docId:z,ownerDocument:W=globalThis.document}={}){super(),this.#i=z,this.#n=W}get#o(){return this.#t||=new Map}get#c(){return this.#r||=new Map}get#a(){if(!this.#e){let z=this.#n.createElement("div"),{style:W}=z;W.visibility="hidden",W.contain="strict",W.width=W.height=0,W.position="absolute",W.top=W.left=0,W.zIndex=-1;let X=this.#n.createElementNS(o,"svg");X.setAttribute("width",0),X.setAttribute("height",0),this.#e=this.#n.createElementNS(o,"defs"),z.append(X),X.append(this.#e),this.#n.body.append(z)}return this.#e}addFilter(z){if(!z)return"none";let W,X,et,st,ct=this.#o.get(z);if(ct)return ct;if(z.length===1){let _=z[0],I=new Array(256);for(let h=0;h<256;h++)I[h]=_[h]/255;st=W=X=et=I.join(",")}else{let[_,I,h]=z,b=new Array(256),C=new Array(256),P=new Array(256);for(let O=0;O<256;O++)b[O]=_[O]/255,C[O]=I[O]/255,P[O]=h[O]/255;W=b.join(","),X=C.join(","),et=P.join(","),st=`${W}${X}${et}`}if(ct=this.#o.get(st),ct)return this.#o.set(z,ct),ct;let nt=`g_${this.#i}_transfer_map_${this.#s++}`,G=`url(#${nt})`;this.#o.set(z,G),this.#o.set(st,G);let A=this.#u(nt);return this.#l(W,X,et,A),G}addHCMFilter(z,W){let X=`${z}-${W}`,et="base",st=this.#c.get(et);if(st?.key===X||(st?(st.filter?.remove(),st.key=X,st.url="none",st.filter=null):(st={key:X,url:"none",filter:null},this.#c.set(et,st)),!z||!W))return st.url;let ct=this.#f(z);z=r.Util.makeHexColor(...ct);let nt=this.#f(W);if(W=r.Util.makeHexColor(...nt),this.#a.style.color="",z==="#000000"&&W==="#ffffff"||z===W)return st.url;let G=new Array(256);for(let b=0;b<=255;b++){let C=b/255;G[b]=C<=.03928?C/12.92:((C+.055)/1.055)**2.4}let A=G.join(","),_=`g_${this.#i}_hcm_filter`,I=st.filter=this.#u(_);this.#l(A,A,A,I),this.#h(I);let h=(b,C)=>{let P=ct[b]/255,O=nt[b]/255,M=new Array(C+1);for(let E=0;E<=C;E++)M[E]=P+E/C*(O-P);return M.join(",")};return this.#l(h(0,5),h(1,5),h(2,5),I),st.url=`url(#${_})`,st.url}addHighlightHCMFilter(z,W,X,et,st){let ct=`${W}-${X}-${et}-${st}`,nt=this.#c.get(z);if(nt?.key===ct||(nt?(nt.filter?.remove(),nt.key=ct,nt.url="none",nt.filter=null):(nt={key:ct,url:"none",filter:null},this.#c.set(z,nt)),!W||!X))return nt.url;let[G,A]=[W,X].map(this.#f.bind(this)),_=Math.round(.2126*G[0]+.7152*G[1]+.0722*G[2]),I=Math.round(.2126*A[0]+.7152*A[1]+.0722*A[2]),[h,b]=[et,st].map(this.#f.bind(this));I<_&&([_,I,h,b]=[I,_,b,h]),this.#a.style.color="";let C=(M,E,L)=>{let U=new Array(256),B=(I-_)/L,k=M/255,F=(E-M)/(255*L),V=0;for(let Q=0;Q<=L;Q++){let Z=Math.round(_+Q*B),tt=k+Q*F;for(let rt=V;rt<=Z;rt++)U[rt]=tt;V=Z+1}for(let Q=V;Q<256;Q++)U[Q]=U[V-1];return U.join(",")},P=`g_${this.#i}_hcm_${z}_filter`,O=nt.filter=this.#u(P);return this.#h(O),this.#l(C(h[0],b[0],5),C(h[1],b[1],5),C(h[2],b[2],5),O),nt.url=`url(#${P})`,nt.url}destroy(z=!1){(!z||this.#c.size===0)&&(this.#e&&(this.#e.parentNode.parentNode.remove(),this.#e=null),this.#t&&(this.#t.clear(),this.#t=null),this.#s=0)}#h(z){let W=this.#n.createElementNS(o,"feColorMatrix");W.setAttribute("type","matrix"),W.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),z.append(W)}#u(z){let W=this.#n.createElementNS(o,"filter");return W.setAttribute("color-interpolation-filters","sRGB"),W.setAttribute("id",z),this.#a.append(W),W}#d(z,W,X){let et=this.#n.createElementNS(o,W);et.setAttribute("type","discrete"),et.setAttribute("tableValues",X),z.append(et)}#l(z,W,X,et){let st=this.#n.createElementNS(o,"feComponentTransfer");et.append(st),this.#d(st,"feFuncR",z),this.#d(st,"feFuncG",W),this.#d(st,"feFuncB",X)}#f(z){return this.#a.style.color=z,H(getComputedStyle(this.#a).getPropertyValue("color"))}}class m extends i.BaseCanvasFactory{constructor({ownerDocument:z=globalThis.document}={}){super(),this._document=z}_createCanvas(z,W){let X=this._document.createElement("canvas");return X.width=z,X.height=W,X}}async function v(K,z="text"){if(w(K,document.baseURI)){let W=await fetch(K);if(!W.ok)throw new Error(W.statusText);switch(z){case"arraybuffer":return W.arrayBuffer();case"blob":return W.blob();case"json":return W.json()}return W.text()}return new Promise(((W,X)=>{let et=new XMLHttpRequest;et.open("GET",K,!0),et.responseType=z,et.onreadystatechange=()=>{if(et.readyState===XMLHttpRequest.DONE)if(et.status!==200&&et.status!==0)X(new Error(et.statusText));else{switch(z){case"arraybuffer":case"blob":case"json":W(et.response);return}W(et.responseText)}},et.send(null)}))}class u extends i.BaseCMapReaderFactory{_fetchData(z,W){return v(z,this.isCompressed?"arraybuffer":"text").then((X=>({cMapData:X instanceof ArrayBuffer?new Uint8Array(X):(0,r.stringToBytes)(X),compressionType:W})))}}class a extends i.BaseStandardFontDataFactory{_fetchData(z){return v(z,"arraybuffer").then((W=>new Uint8Array(W)))}}class p extends i.BaseSVGFactory{_createSVG(z){return document.createElementNS(o,z)}}class x{constructor({viewBox:z,scale:W,rotation:X,offsetX:et=0,offsetY:st=0,dontFlip:ct=!1}){this.viewBox=z,this.scale=W,this.rotation=X,this.offsetX=et,this.offsetY=st;let nt=(z[2]+z[0])/2,G=(z[3]+z[1])/2,A,_,I,h,b,C,P,O;switch((X%=360)<0&&(X+=360),X){case 180:A=-1,_=0,I=0,h=1;break;case 90:A=0,_=1,I=1,h=0;break;case 270:A=0,_=-1,I=-1,h=0;break;case 0:A=1,_=0,I=0,h=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}ct&&(I=-I,h=-h),A===0?(b=Math.abs(G-z[1])*W+et,C=Math.abs(nt-z[0])*W+st,P=(z[3]-z[1])*W,O=(z[2]-z[0])*W):(b=Math.abs(nt-z[0])*W+et,C=Math.abs(G-z[1])*W+st,P=(z[2]-z[0])*W,O=(z[3]-z[1])*W),this.transform=[A*W,_*W,I*W,h*W,b-A*W*nt-I*W*G,C-_*W*nt-h*W*G],this.width=P,this.height=O}get rawDims(){let{viewBox:z}=this;return(0,r.shadow)(this,"rawDims",{pageWidth:z[2]-z[0],pageHeight:z[3]-z[1],pageX:z[0],pageY:z[1]})}clone({scale:z=this.scale,rotation:W=this.rotation,offsetX:X=this.offsetX,offsetY:et=this.offsetY,dontFlip:st=!1}={}){return new x({viewBox:this.viewBox.slice(),scale:z,rotation:W,offsetX:X,offsetY:et,dontFlip:st})}convertToViewportPoint(z,W){return r.Util.applyTransform([z,W],this.transform)}convertToViewportRectangle(z){let W=r.Util.applyTransform([z[0],z[1]],this.transform),X=r.Util.applyTransform([z[2],z[3]],this.transform);return[W[0],W[1],X[0],X[1]]}convertToPdfPoint(z,W){return r.Util.applyInverseTransform([z,W],this.transform)}}class T extends r.BaseException{constructor(z,W=0){super(z,"RenderingCancelledException"),this.extraDelay=W}}function l(K){let z=K.length,W=0;for(;W<z&&K[W].trim()==="";)W++;return K.substring(W,W+5).toLowerCase()==="data:"}function y(K){return typeof K=="string"&&/\.pdf$/i.test(K)}function s(K,z=!1){return z||([K]=K.split(/[#?]/,1)),K.substring(K.lastIndexOf("/")+1)}function c(K,z="document.pdf"){if(typeof K!="string")return z;if(l(K))return(0,r.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),z;let W=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,X=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(K),et=W.exec(X[1])||W.exec(X[2])||W.exec(X[3]);if(et&&(et=et[0],et.includes("%")))try{et=W.exec(decodeURIComponent(et))[0]}catch{}return et||z}class f{started=Object.create(null);times=[];time(z){z in this.started&&(0,r.warn)(`Timer is already running for ${z}`),this.started[z]=Date.now()}timeEnd(z){z in this.started||(0,r.warn)(`Timer has not been started for ${z}`),this.times.push({name:z,start:this.started[z],end:Date.now()}),delete this.started[z]}toString(){let z=[],W=0;for(let{name:X}of this.times)W=Math.max(X.length,W);for(let{name:X,start:et,end:st}of this.times)z.push(`${X.padEnd(W)} ${st-et}ms
|
|
1526
|
+
`);return z.join("")}}function w(K,z){try{let{protocol:W}=z?new URL(K,z):new URL(K);return W==="http:"||W==="https:"}catch{return!1}}function R(K){K.preventDefault()}let S;class D{static toDateObject(z){if(!z||typeof z!="string")return null;S||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");let W=S.exec(z);if(!W)return null;let X=parseInt(W[1],10),et=parseInt(W[2],10);et=et>=1&&et<=12?et-1:0;let st=parseInt(W[3],10);st=st>=1&&st<=31?st:1;let ct=parseInt(W[4],10);ct=ct>=0&&ct<=23?ct:0;let nt=parseInt(W[5],10);nt=nt>=0&&nt<=59?nt:0;let G=parseInt(W[6],10);G=G>=0&&G<=59?G:0;let A=W[7]||"Z",_=parseInt(W[8],10);_=_>=0&&_<=23?_:0;let I=parseInt(W[9],10)||0;return I=I>=0&&I<=59?I:0,A==="-"?(ct+=_,nt+=I):A==="+"&&(ct-=_,nt-=I),new Date(Date.UTC(X,et,st,ct,nt,G))}}function N(K,{scale:z=1,rotation:W=0}){let{width:X,height:et}=K.attributes.style,st=[0,0,parseInt(X),parseInt(et)];return new x({viewBox:st,scale:z,rotation:W})}function H(K){if(K.startsWith("#")){let z=parseInt(K.slice(1),16);return[(16711680&z)>>16,(65280&z)>>8,255&z]}return K.startsWith("rgb(")?K.slice(4,-1).split(",").map((z=>parseInt(z))):K.startsWith("rgba(")?K.slice(5,-1).split(",").map((z=>parseInt(z))).slice(0,3):((0,r.warn)(`Not a valid color format: "${K}"`),[0,0,0])}function j(K){let z=document.createElement("span");z.style.visibility="hidden",document.body.append(z);for(let W of K.keys()){z.style.color=W;let X=window.getComputedStyle(z).color;K.set(W,H(X))}z.remove()}function Y(K){let{a:z,b:W,c:X,d:et,e:st,f:ct}=K.getTransform();return[z,W,X,et,st,ct]}function it(K){let{a:z,b:W,c:X,d:et,e:st,f:ct}=K.getTransform().invertSelf();return[z,W,X,et,st,ct]}function ot(K,z,W=!1,X=!0){if(z instanceof x){let{pageWidth:et,pageHeight:st}=z.rawDims,{style:ct}=K,nt=r.FeatureTest.isCSSRoundSupported,G=`var(--scale-factor) * ${et}px`,A=`var(--scale-factor) * ${st}px`,_=nt?`round(${G}, 1px)`:`calc(${G})`,I=nt?`round(${A}, 1px)`:`calc(${A})`;W&&z.rotation%180!=0?(ct.width=I,ct.height=_):(ct.width=_,ct.height=I)}X&&K.setAttribute("data-main-rotation",z.rotation)}},47:(n,t,e)=>{e.d(t,{DrawLayer:()=>o});var i=e(419),r=e(292);class o{#t=null;#e=0;#i=new Map;#n=new Map;constructor({pageIndex:d}){this.pageIndex=d}setParent(d){if(this.#t){if(this.#t!==d){if(this.#i.size>0)for(let m of this.#i.values())m.remove(),d.append(m);this.#t=d}}else this.#t=d}static get _svgFactory(){return(0,r.shadow)(this,"_svgFactory",new i.DOMSVGFactory)}static#r(d,{x:m=0,y:v=0,width:u=1,height:a=1}={}){let{style:p}=d;p.top=100*v+"%",p.left=100*m+"%",p.width=100*u+"%",p.height=100*a+"%"}#s(d){let m=o._svgFactory.create(1,1,!0);return this.#t.append(m),m.setAttribute("aria-hidden",!0),o.#r(m,d),m}#o(d,m){let v=o._svgFactory.createElement("clipPath");d.append(v);let u=`clip_${m}`;v.setAttribute("id",u),v.setAttribute("clipPathUnits","objectBoundingBox");let a=o._svgFactory.createElement("use");return v.append(a),a.setAttribute("href",`#${m}`),a.classList.add("clip"),u}highlight(d,m,v,u=!1){let a=this.#e++,p=this.#s(d.box);p.classList.add("highlight"),d.free&&p.classList.add("free");let x=o._svgFactory.createElement("defs");p.append(x);let T=o._svgFactory.createElement("path");x.append(T);let l=`path_p${this.pageIndex}_${a}`;T.setAttribute("id",l),T.setAttribute("d",d.toSVGPath()),u&&this.#n.set(a,T);let y=this.#o(x,l),s=o._svgFactory.createElement("use");return p.append(s),p.setAttribute("fill",m),p.setAttribute("fill-opacity",v),s.setAttribute("href",`#${l}`),this.#i.set(a,p),{id:a,clipPathId:`url(#${y})`}}highlightOutline(d){let m=this.#e++,v=this.#s(d.box);v.classList.add("highlightOutline");let u=o._svgFactory.createElement("defs");v.append(u);let a=o._svgFactory.createElement("path");u.append(a);let p=`path_p${this.pageIndex}_${m}`;a.setAttribute("id",p),a.setAttribute("d",d.toSVGPath()),a.setAttribute("vector-effect","non-scaling-stroke");let x;if(d.free){v.classList.add("free");let y=o._svgFactory.createElement("mask");u.append(y),x=`mask_p${this.pageIndex}_${m}`,y.setAttribute("id",x),y.setAttribute("maskUnits","objectBoundingBox");let s=o._svgFactory.createElement("rect");y.append(s),s.setAttribute("width","1"),s.setAttribute("height","1"),s.setAttribute("fill","white");let c=o._svgFactory.createElement("use");y.append(c),c.setAttribute("href",`#${p}`),c.setAttribute("stroke","none"),c.setAttribute("fill","black"),c.setAttribute("fill-rule","nonzero"),c.classList.add("mask")}let T=o._svgFactory.createElement("use");v.append(T),T.setAttribute("href",`#${p}`),x&&T.setAttribute("mask",`url(#${x})`);let l=T.cloneNode();return v.append(l),T.classList.add("mainOutline"),l.classList.add("secondaryOutline"),this.#i.set(m,v),m}finalizeLine(d,m){let v=this.#n.get(d);this.#n.delete(d),this.updateBox(d,m.box),v.setAttribute("d",m.toSVGPath())}updateLine(d,m){this.#i.get(d).firstChild.firstChild.setAttribute("d",m.toSVGPath())}removeFreeHighlight(d){this.remove(d),this.#n.delete(d)}updatePath(d,m){this.#n.get(d).setAttribute("d",m.toSVGPath())}updateBox(d,m){o.#r(this.#i.get(d),m)}show(d,m){this.#i.get(d).classList.toggle("hidden",!m)}rotate(d,m){this.#i.get(d).setAttribute("data-main-rotation",m)}changeColor(d,m){this.#i.get(d).setAttribute("fill",m)}changeOpacity(d,m){this.#i.get(d).setAttribute("fill-opacity",m)}addClass(d,m){this.#i.get(d).classList.add(m)}removeClass(d,m){this.#i.get(d).classList.remove(m)}remove(d){this.#t!==null&&(this.#i.get(d).remove(),this.#i.delete(d))}destroy(){this.#t=null;for(let d of this.#i.values())d.remove();this.#i.clear()}}},731:(n,t,e)=>{e.d(t,{AnnotationEditorLayer:()=>l});var i=e(292),r=e(310),o=e(830),g=e(976);let d=/\r\n?|\n/g;class m extends r.AnnotationEditor{#t=this.editorDivBlur.bind(this);#e=this.editorDivFocus.bind(this);#i=this.editorDivInput.bind(this);#n=this.editorDivKeydown.bind(this);#r=this.editorDivPaste.bind(this);#s;#o="";#c=`${this.id}-editor`;#a;#h=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let s=m.prototype,c=R=>R.isEmpty(),f=o.AnnotationEditorUIManager.TRANSLATE_SMALL,w=o.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new o.KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],s.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],s.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],s._translateEmpty,{args:[-f,0],checker:c}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],s._translateEmpty,{args:[-w,0],checker:c}],[["ArrowRight","mac+ArrowRight"],s._translateEmpty,{args:[f,0],checker:c}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],s._translateEmpty,{args:[w,0],checker:c}],[["ArrowUp","mac+ArrowUp"],s._translateEmpty,{args:[0,-f],checker:c}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],s._translateEmpty,{args:[0,-w],checker:c}],[["ArrowDown","mac+ArrowDown"],s._translateEmpty,{args:[0,f],checker:c}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],s._translateEmpty,{args:[0,w],checker:c}]]))}static _type="freetext";static _editorType=i.AnnotationEditorType.FREETEXT;constructor(s){super({...s,name:"freeTextEditor"}),this.#s=s.color||m._defaultColor||r.AnnotationEditor._defaultLineColor,this.#a=s.fontSize||m._defaultFontSize}static initialize(s,c){r.AnnotationEditor.initialize(s,c,{strings:["pdfjs-free-text-default-content"]});let f=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(f.getPropertyValue("--freetext-padding"))}static updateDefaultParams(s,c){switch(s){case i.AnnotationEditorParamsType.FREETEXT_SIZE:m._defaultFontSize=c;break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:m._defaultColor=c}}updateParams(s,c){switch(s){case i.AnnotationEditorParamsType.FREETEXT_SIZE:this.#u(c);break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:this.#d(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,m._defaultFontSize],[i.AnnotationEditorParamsType.FREETEXT_COLOR,m._defaultColor||r.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,this.#a],[i.AnnotationEditorParamsType.FREETEXT_COLOR,this.#s]]}#u(s){let c=w=>{this.editorDiv.style.fontSize=`calc(${w}px * var(--scale-factor))`,this.translate(0,-(w-this.#a)*this.parentScale),this.#a=w,this.#f()},f=this.#a;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#d(s){let c=w=>{this.#s=this.editorDiv.style.color=w},f=this.#s;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(s,c){this._uiManager.translateSelectedEditors(s,c,!0)}getInitialTranslation(){let s=this.parentScale;return[-m._internalPadding*s,-(m._internalPadding+this.#a)*s]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){this.isInEditMode()||(this.parent.setEditingState(!1),this.parent.updateToolbar(i.AnnotationEditorType.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.editorDiv.addEventListener("keydown",this.#n),this.editorDiv.addEventListener("focus",this.#e),this.editorDiv.addEventListener("blur",this.#t),this.editorDiv.addEventListener("input",this.#i),this.editorDiv.addEventListener("paste",this.#r))}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#c),this._isDraggable=!0,this.editorDiv.removeEventListener("keydown",this.#n),this.editorDiv.removeEventListener("focus",this.#e),this.editorDiv.removeEventListener("blur",this.#t),this.editorDiv.removeEventListener("input",this.#i),this.editorDiv.removeEventListener("paste",this.#r),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(s){this._focusEventsAllowed&&(super.focusin(s),s.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#l(){let s=[];this.editorDiv.normalize();for(let c of this.editorDiv.childNodes)s.push(m.#g(c));return s.join(`
|
|
1527
|
+
`)}#f(){let[s,c]=this.parentDimensions,f;if(this.isAttachedToDOM)f=this.div.getBoundingClientRect();else{let{currentLayer:w,div:R}=this,S=R.style.display;R.style.display="hidden",w.div.append(this.div),f=R.getBoundingClientRect(),R.remove(),R.style.display=S}this.rotation%180==this.parentRotation%180?(this.width=f.width/s,this.height=f.height/c):(this.width=f.height/s,this.height=f.width/c),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let s=this.#o,c=this.#o=this.#l().trimEnd();if(s===c)return;let f=w=>{this.#o=w,w?(this.#p(),this._uiManager.rebuild(this),this.#f()):this.remove()};this.addCommands({cmd:()=>{f(c)},undo:()=>{f(s)},mustExec:!1}),this.#f()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(s){this.enterInEditMode()}keydown(s){s.target===this.div&&s.key==="Enter"&&(this.enterInEditMode(),s.preventDefault())}editorDivKeydown(s){m._keyboardManager.exec(this,s)}editorDivFocus(s){this.isEditing=!0}editorDivBlur(s){this.isEditing=!1}editorDivInput(s){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let s,c;this.width&&(s=this.x,c=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#c),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),r.AnnotationEditor._l10nPromise.get("pdfjs-free-text-default-content").then((w=>this.editorDiv?.setAttribute("default-content",w))),this.editorDiv.contentEditable=!0;let{style:f}=this.editorDiv;if(f.fontSize=`calc(${this.#a}px * var(--scale-factor))`,f.color=this.#s,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),(0,o.bindEvents)(this,this.div,["dblclick","keydown"]),this.width){let[w,R]=this.parentDimensions;if(this.annotationElementId){let{position:S}=this.#h,[D,N]=this.getInitialTranslation();[D,N]=this.pageTranslationToScreen(D,N);let[H,j]=this.pageDimensions,[Y,it]=this.pageTranslation,ot,K;switch(this.rotation){case 0:ot=s+(S[0]-Y)/H,K=c+this.height-(S[1]-it)/j;break;case 90:ot=s+(S[0]-Y)/H,K=c-(S[1]-it)/j,[D,N]=[N,-D];break;case 180:ot=s-this.width+(S[0]-Y)/H,K=c-(S[1]-it)/j,[D,N]=[-D,-N];break;case 270:ot=s+(S[0]-Y-this.height*j)/H,K=c+(S[1]-it-this.width*H)/j,[D,N]=[-N,D]}this.setAt(ot*w,K*R,D,N)}else this.setAt(s*w,c*R,this.width*w,this.height*R);this.#p(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#g(s){return(s.nodeType===Node.TEXT_NODE?s.nodeValue:s.innerText).replaceAll(d,"")}editorDivPaste(s){let c=s.clipboardData||window.clipboardData,{types:f}=c;if(f.length===1&&f[0]==="text/plain")return;s.preventDefault();let w=m.#m(c.getData("text")||"").replaceAll(d,`
|
|
1528
|
+
`);if(!w)return;let R=window.getSelection();if(!R.rangeCount)return;this.editorDiv.normalize(),R.deleteFromDocument();let S=R.getRangeAt(0);if(!w.includes(`
|
|
1529
|
+
`)){S.insertNode(document.createTextNode(w)),this.editorDiv.normalize(),R.collapseToStart();return}let{startContainer:D,startOffset:N}=S,H=[],j=[];if(D.nodeType===Node.TEXT_NODE){let ot=D.parentElement;if(j.push(D.nodeValue.slice(N).replaceAll(d,"")),ot!==this.editorDiv){let K=H;for(let z of this.editorDiv.childNodes)z!==ot?K.push(m.#g(z)):K=j}H.push(D.nodeValue.slice(0,N).replaceAll(d,""))}else if(D===this.editorDiv){let ot=H,K=0;for(let z of this.editorDiv.childNodes)K++===N&&(ot=j),ot.push(m.#g(z))}this.#o=`${H.join(`
|
|
1530
|
+
`)}${w}${j.join(`
|
|
1531
|
+
`)}`,this.#p();let Y=new Range,it=H.reduce(((ot,K)=>ot+K.length),0);for(let{firstChild:ot}of this.editorDiv.childNodes)if(ot.nodeType===Node.TEXT_NODE){let K=ot.nodeValue.length;if(it<=K){Y.setStart(ot,it),Y.setEnd(ot,it);break}it-=K}R.removeAllRanges(),R.addRange(Y)}#p(){if(this.editorDiv.replaceChildren(),this.#o)for(let s of this.#o.split(`
|
|
1532
|
+
`)){let c=document.createElement("div");c.append(s?document.createTextNode(s):document.createElement("br")),this.editorDiv.append(c)}}#y(){return this.#o.replaceAll("\xA0"," ")}static#m(s){return s.replaceAll(" ","\xA0")}get contentDiv(){return this.editorDiv}static deserialize(s,c,f){let w=null;if(s instanceof g.FreeTextAnnotationElement){let{data:{defaultAppearanceData:{fontSize:S,fontColor:D},rect:N,rotation:H,id:j},textContent:Y,textPosition:it,parent:{page:{pageNumber:ot}}}=s;if(!Y||Y.length===0)return null;w=s={annotationType:i.AnnotationEditorType.FREETEXT,color:Array.from(D),fontSize:S,value:Y.join(`
|
|
1533
|
+
`),position:it,pageIndex:ot-1,rect:N,rotation:H,id:j,deleted:!1}}let R=super.deserialize(s,c,f);return R.#a=s.fontSize,R.#s=i.Util.makeHexColor(...s.color),R.#o=m.#m(s.value),R.annotationElementId=s.id||null,R.#h=w,R}serialize(s=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};let c=m._internalPadding*this.parentScale,f=this.getRect(c,c),w=r.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#s),R={annotationType:i.AnnotationEditorType.FREETEXT,color:w,fontSize:this.#a,value:this.#y(),pageIndex:this.pageIndex,rect:f,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return s?R:this.annotationElementId&&!this.#b(R)?null:(R.id=this.annotationElementId,R)}#b(s){let{value:c,fontSize:f,color:w,pageIndex:R}=this.#h;return this._hasBeenMoved||s.value!==c||s.fontSize!==f||s.color.some(((S,D)=>S!==w[D]))||s.pageIndex!==R}}var v=e(61),u=e(259),a=e(419);class p extends r.AnnotationEditor{#t=null;#e=0;#i;#n=null;#r=null;#s=null;#o=null;#c=0;#a=null;#h=null;#u=null;#d=!1;#l=this.#C.bind(this);#f=null;#g;#p=null;#y="";#m;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _l10nPromise;static _type="highlight";static _editorType=i.AnnotationEditorType.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){let s=p.prototype;return(0,i.shadow)(this,"_keyboardManager",new o.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],s._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],s._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],s._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],s._moveCaret,{args:[3]}]]))}constructor(s){super({...s,name:"highlightEditor"}),this.color=s.color||p._defaultColor,this.#m=s.thickness||p._defaultThickness,this.#g=s.opacity||p._defaultOpacity,this.#i=s.boxes||null,this.#b=s.methodOfCreation||"",this.#y=s.text||"",this._isDraggable=!1,s.highlightId>-1?(this.#d=!0,this.#_(s),this.#E()):(this.#t=s.anchorNode,this.#e=s.anchorOffset,this.#o=s.focusNode,this.#c=s.focusOffset,this.#S(),this.#E(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#d?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#m,methodOfCreation:this.#b}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(s){return{numberOfColors:s.get("color").size}}#S(){let s=new v.Outliner(this.#i,.001);this.#h=s.getOutlines(),{x:this.x,y:this.y,width:this.width,height:this.height}=this.#h.box;let c=new v.Outliner(this.#i,.0025,.001,this._uiManager.direction==="ltr");this.#s=c.getOutlines();let{lastPoint:f}=this.#s.box;this.#f=[(f[0]-this.x)/this.width,(f[1]-this.y)/this.height]}#_({highlightOutlines:s,highlightId:c,clipPathId:f}){if(this.#h=s,this.#s=s.getNewOutline(this.#m/2+1.5,.0025),c>=0)this.#u=c,this.#n=f,this.parent.drawLayer.finalizeLine(c,s),this.#p=this.parent.drawLayer.highlightOutline(this.#s);else if(this.parent){let H=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#u,s),this.parent.drawLayer.updateBox(this.#u,p.#A(this.#h.box,(H-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#p,this.#s),this.parent.drawLayer.updateBox(this.#p,p.#A(this.#s.box,H))}let{x:w,y:R,width:S,height:D}=s.box;switch(this.rotation){case 0:this.x=w,this.y=R,this.width=S,this.height=D;break;case 90:{let[H,j]=this.parentDimensions;this.x=R,this.y=1-w,this.width=S*j/H,this.height=D*H/j;break}case 180:this.x=1-w,this.y=1-R,this.width=S,this.height=D;break;case 270:{let[H,j]=this.parentDimensions;this.x=1-R,this.y=w,this.width=S*j/H,this.height=D*H/j;break}}let{lastPoint:N}=this.#s.box;this.#f=[(N[0]-w)/S,(N[1]-R)/D]}static initialize(s,c){r.AnnotationEditor.initialize(s,c),p._defaultColor||=c.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(s,c){switch(s){case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:p._defaultColor=c;break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:p._defaultThickness=c}}translateInPage(s,c){}get toolbarPosition(){return this.#f}updateParams(s,c){switch(s){case i.AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#M(c);break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#w(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR,p._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,p._defaultThickness]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.color||p._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,this.#m||p._defaultThickness],[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,this.#d]]}#M(s){let c=w=>{this.color=w,this.parent?.drawLayer.changeColor(this.#u,w),this.#r?.updateColor(w)},f=this.color;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(s)},!0)}#w(s){let c=this.#m,f=w=>{this.#m=w,this.#x(w)};this.addCommands({cmd:f.bind(this,s),undo:f.bind(this,c),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:s},!0)}async addEditToolbar(){let s=await super.addEditToolbar();return s?(this._uiManager.highlightColors&&(this.#r=new u.ColorPicker({editor:this}),s.addColorPicker(this.#r)),s):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#P())}getBaseTranslation(){return[0,0]}getRect(s,c){return super.getRect(s,c,this.#P())}onceAdded(){this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#v(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#E(),this.isAttachedToDOM||this.parent.add(this)))}setParent(s){let c=!1;this.parent&&!s?this.#v():s&&(this.#E(s),c=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(s),this.show(this._isVisible),c&&this.select()}#x(s){if(!this.#d)return;this.#_({highlightOutlines:this.#h.getNewOutline(s/2)}),this.fixAndSetPosition();let[c,f]=this.parentDimensions;this.setDims(this.width*c,this.height*f)}#v(){this.#u!==null&&this.parent&&(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#p),this.#p=null)}#E(s=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#n}=s.drawLayer.highlight(this.#h,this.color,this.#g),this.#p=s.drawLayer.highlightOutline(this.#s),this.#a&&(this.#a.style.clipPath=this.#n))}static#A({x:s,y:c,width:f,height:w},R){switch(R){case 90:return{x:1-c-w,y:s,width:w,height:f};case 180:return{x:1-s-f,y:1-c-w,width:f,height:w};case 270:return{x:c,y:1-s-f,width:w,height:f}}return{x:s,y:c,width:f,height:w}}rotate(s){let{drawLayer:c}=this.parent,f;this.#d?(s=(s-this.rotation+360)%360,f=p.#A(this.#h.box,s)):f=p.#A(this,s),c.rotate(this.#u,s),c.rotate(this.#p,s),c.updateBox(this.#u,f),c.updateBox(this.#p,p.#A(this.#s.box,s))}render(){if(this.div)return this.div;let s=super.render();this.#y&&(s.setAttribute("aria-label",this.#y),s.setAttribute("role","mark")),this.#d?s.classList.add("free"):this.div.addEventListener("keydown",this.#l);let c=this.#a=document.createElement("div");s.append(c),c.setAttribute("aria-hidden","true"),c.className="internal",c.style.clipPath=this.#n;let[f,w]=this.parentDimensions;return this.setDims(this.width*f,this.height*w),(0,o.bindEvents)(this,this.#a,["pointerover","pointerleave"]),this.enableEditing(),s}pointerover(){this.parent.drawLayer.addClass(this.#p,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#p,"hovered")}#C(s){p._keyboardManager.exec(this,s)}_moveCaret(s){switch(this.parent.unselect(this),s){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1)}}#T(s){if(!this.#t)return;let c=window.getSelection();s?c.setPosition(this.#t,this.#e):c.setPosition(this.#o,this.#c)}select(){super.select(),this.#p&&(this.parent?.drawLayer.removeClass(this.#p,"hovered"),this.parent?.drawLayer.addClass(this.#p,"selected"))}unselect(){super.unselect(),this.#p&&(this.parent?.drawLayer.removeClass(this.#p,"selected"),this.#d||this.#T(!1))}get _mustFixPosition(){return!this.#d}show(s=this._isVisible){super.show(s),this.parent&&(this.parent.drawLayer.show(this.#u,s),this.parent.drawLayer.show(this.#p,s))}#P(){return this.#d?this.rotation:0}#D(){if(this.#d)return null;let[s,c]=this.pageDimensions,f=this.#i,w=new Array(8*f.length),R=0;for(let{x:S,y:D,width:N,height:H}of f){let j=S*s,Y=(1-D-H)*c;w[R]=w[R+4]=j,w[R+1]=w[R+3]=Y,w[R+2]=w[R+6]=j+N*s,w[R+5]=w[R+7]=Y+H*c,R+=8}return w}#k(s){return this.#h.serialize(s,this.#P())}static startHighlighting(s,c,{target:f,x:w,y:R}){let{x:S,y:D,width:N,height:H}=f.getBoundingClientRect(),j=K=>{this.#L(s,K)},Y={capture:!0,passive:!1},it=K=>{K.preventDefault(),K.stopPropagation()},ot=K=>{f.removeEventListener("pointermove",j),window.removeEventListener("blur",ot),window.removeEventListener("pointerup",ot),window.removeEventListener("pointerdown",it,Y),window.removeEventListener("contextmenu",a.noContextMenu),this.#I(s,K)};window.addEventListener("blur",ot),window.addEventListener("pointerup",ot),window.addEventListener("pointerdown",it,Y),window.addEventListener("contextmenu",a.noContextMenu),f.addEventListener("pointermove",j),this._freeHighlight=new v.FreeOutliner({x:w,y:R},[S,D,N,H],s.scale,this._defaultThickness/2,c,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=s.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static#L(s,c){this._freeHighlight.add(c)&&s.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#I(s,c){this._freeHighlight.isEmpty()?s.drawLayer.removeFreeHighlight(this._freeHighlightId):s.createAndAddNewEditor(c,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static deserialize(s,c,f){let w=super.deserialize(s,c,f),{rect:[R,S,D,N],color:H,quadPoints:j}=s;w.color=i.Util.makeHexColor(...H),w.#g=s.opacity;let[Y,it]=w.pageDimensions;w.width=(D-R)/Y,w.height=(N-S)/it;let ot=w.#i=[];for(let K=0;K<j.length;K+=8)ot.push({x:(j[4]-D)/Y,y:(N-(1-j[K+5]))/it,width:(j[K+2]-j[K])/Y,height:(j[K+5]-j[K+1])/it});return w.#S(),w}serialize(s=!1){if(this.isEmpty()||s)return null;let c=this.getRect(0,0),f=r.AnnotationEditor._colorManager.convert(this.color);return{annotationType:i.AnnotationEditorType.HIGHLIGHT,color:f,opacity:this.#g,thickness:this.#m,quadPoints:this.#D(),outlines:this.#k(c),pageIndex:this.pageIndex,rect:c,rotation:this.#P(),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}}class x extends r.AnnotationEditor{#t=0;#e=0;#i=this.canvasPointermove.bind(this);#n=this.canvasPointerleave.bind(this);#r=this.canvasPointerup.bind(this);#s=this.canvasPointerdown.bind(this);#o=null;#c=new Path2D;#a=!1;#h=!1;#u=!1;#d=null;#l=0;#f=0;#g=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=i.AnnotationEditorType.INK;constructor(s){super({...s,name:"inkEditor"}),this.color=s.color||null,this.thickness=s.thickness||null,this.opacity=s.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(s,c){r.AnnotationEditor.initialize(s,c)}static updateDefaultParams(s,c){switch(s){case i.AnnotationEditorParamsType.INK_THICKNESS:x._defaultThickness=c;break;case i.AnnotationEditorParamsType.INK_COLOR:x._defaultColor=c;break;case i.AnnotationEditorParamsType.INK_OPACITY:x._defaultOpacity=c/100}}updateParams(s,c){switch(s){case i.AnnotationEditorParamsType.INK_THICKNESS:this.#p(c);break;case i.AnnotationEditorParamsType.INK_COLOR:this.#y(c);break;case i.AnnotationEditorParamsType.INK_OPACITY:this.#m(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,x._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,x._defaultColor||r.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*x._defaultOpacity)]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,this.thickness||x._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,this.color||x._defaultColor||r.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*(this.opacity??x._defaultOpacity))]]}#p(s){let c=w=>{this.thickness=w,this.#N()},f=this.thickness;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#y(s){let c=w=>{this.color=w,this.#C()},f=this.color;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#m(s){let c=w=>{this.opacity=w,this.#C()};s/=100;let f=this.opacity;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(this.#P(),this.#D()),this.isAttachedToDOM||(this.parent.add(this),this.#k()),this.#N()))}remove(){this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#o&&(clearTimeout(this.#o),this.#o=null),this.#d.disconnect(),this.#d=null,super.remove())}setParent(s){!this.parent&&s?this._uiManager.removeShouldRescale(this):this.parent&&s===null&&this._uiManager.addShouldRescale(this),super.setParent(s)}onScaleChanging(){let[s,c]=this.parentDimensions,f=this.width*s,w=this.height*c;this.setDimensions(f,w)}enableEditMode(){!this.#a&&this.canvas!==null&&(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",this.#s))}disableEditMode(){this.isInEditMode()&&this.canvas!==null&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",this.#s))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}#b(){let{parentRotation:s,parentDimensions:[c,f]}=this;switch(s){case 90:return[0,f,f,c];case 180:return[c,f,c,f];case 270:return[c,0,f,c];default:return[0,0,c,f]}}#S(){let{ctx:s,color:c,opacity:f,thickness:w,parentScale:R,scaleFactor:S}=this;s.lineWidth=w*R/S,s.lineCap="round",s.lineJoin="round",s.miterLimit=10,s.strokeStyle=`${c}${(0,o.opacityToHex)(f)}`}#_(s,c){this.canvas.addEventListener("contextmenu",a.noContextMenu),this.canvas.addEventListener("pointerleave",this.#n),this.canvas.addEventListener("pointermove",this.#i),this.canvas.addEventListener("pointerup",this.#r),this.canvas.removeEventListener("pointerdown",this.#s),this.isEditing=!0,this.#u||(this.#u=!0,this.#k(),this.thickness||=x._defaultThickness,this.color||=x._defaultColor||r.AnnotationEditor._defaultLineColor,this.opacity??=x._defaultOpacity),this.currentPath.push([s,c]),this.#h=!1,this.#S(),this.#g=()=>{this.#v(),this.#g&&window.requestAnimationFrame(this.#g)},window.requestAnimationFrame(this.#g)}#M(s,c){let[f,w]=this.currentPath.at(-1);if(this.currentPath.length>1&&s===f&&c===w)return;let R=this.currentPath,S=this.#c;R.push([s,c]),this.#h=!0,R.length<=2?(S.moveTo(...R[0]),S.lineTo(s,c)):(R.length===3&&(this.#c=S=new Path2D,S.moveTo(...R[0])),this.#E(S,...R.at(-3),...R.at(-2),s,c))}#w(){if(this.currentPath.length===0)return;let s=this.currentPath.at(-1);this.#c.lineTo(...s)}#x(s,c){this.#g=null,s=Math.min(Math.max(s,0),this.canvas.width),c=Math.min(Math.max(c,0),this.canvas.height),this.#M(s,c),this.#w();let f;if(this.currentPath.length!==1)f=this.#A();else{let S=[s,c];f=[[S,S.slice(),S.slice(),S]]}let w=this.#c,R=this.currentPath;this.currentPath=[],this.#c=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(R),this.paths.push(f),this.bezierPath2D.push(w),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(this.#P(),this.#D()),this.#N())},mustExec:!0})}#v(){if(!this.#h)return;this.#h=!1;let s=Math.ceil(this.thickness*this.parentScale),c=this.currentPath.slice(-3),f=c.map((S=>S[0])),w=c.map((S=>S[1])),{ctx:R}=(Math.min(...f),Math.max(...f),Math.min(...w),Math.max(...w),this);R.save(),R.clearRect(0,0,this.canvas.width,this.canvas.height);for(let S of this.bezierPath2D)R.stroke(S);R.stroke(this.#c),R.restore()}#E(s,c,f,w,R,S,D){let N=(c+w)/2,H=(f+R)/2,j=(w+S)/2,Y=(R+D)/2;s.bezierCurveTo(N+2*(w-N)/3,H+2*(R-H)/3,j+2*(w-j)/3,Y+2*(R-Y)/3,j,Y)}#A(){let s=this.currentPath;if(s.length<=2)return[[s[0],s[0],s.at(-1),s.at(-1)]];let c=[],f,[w,R]=s[0];for(f=1;f<s.length-2;f++){let[it,ot]=s[f],[K,z]=s[f+1],W=(it+K)/2,X=(ot+z)/2,et=[w+2*(it-w)/3,R+2*(ot-R)/3],st=[W+2*(it-W)/3,X+2*(ot-X)/3];c.push([[w,R],et,st,[W,X]]),[w,R]=[W,X]}let[S,D]=s[f],[N,H]=s[f+1],j=[w+2*(S-w)/3,R+2*(D-R)/3],Y=[N+2*(S-N)/3,H+2*(D-H)/3];return c.push([[w,R],j,Y,[N,H]]),c}#C(){if(this.isEmpty()){this.#I();return}this.#S();let{canvas:s,ctx:c}=this;c.setTransform(1,0,0,1,0,0),c.clearRect(0,0,s.width,s.height),this.#I();for(let f of this.bezierPath2D)c.stroke(f)}commit(){this.#a||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),this.#a=!0,this.div.classList.add("disabled"),this.#N(!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(s){this._focusEventsAllowed&&(super.focusin(s),this.enableEditMode())}canvasPointerdown(s){s.button===0&&this.isInEditMode()&&!this.#a&&(this.setInForeground(),s.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),this.#_(s.offsetX,s.offsetY))}canvasPointermove(s){s.preventDefault(),this.#M(s.offsetX,s.offsetY)}canvasPointerup(s){s.preventDefault(),this.#T(s)}canvasPointerleave(s){this.#T(s)}#T(s){this.canvas.removeEventListener("pointerleave",this.#n),this.canvas.removeEventListener("pointermove",this.#i),this.canvas.removeEventListener("pointerup",this.#r),this.canvas.addEventListener("pointerdown",this.#s),this.#o&&clearTimeout(this.#o),this.#o=setTimeout((()=>{this.#o=null,this.canvas.removeEventListener("contextmenu",a.noContextMenu)}),10),this.#x(s.offsetX,s.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#P(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#D(){this.#d=new ResizeObserver((s=>{let c=s[0].contentRect;c.width&&c.height&&this.setDimensions(c.width,c.height)})),this.#d.observe(this.div)}get isResizable(){return!this.isEmpty()&&this.#a}render(){if(this.div)return this.div;let s,c;this.width&&(s=this.x,c=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");let[f,w,R,S]=this.#b();if(this.setAt(f,w,0,0),this.setDims(R,S),this.#P(),this.width){let[D,N]=this.parentDimensions;this.setAspectRatio(this.width*D,this.height*N),this.setAt(s*D,c*N,this.width*D,this.height*N),this.#u=!0,this.#k(),this.setDims(this.width*D,this.height*N),this.#C(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#D(),this.div}#k(){if(!this.#u)return;let[s,c]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*s),this.canvas.height=Math.ceil(this.height*c),this.#I()}setDimensions(s,c){let f=Math.round(s),w=Math.round(c);if(this.#l===f&&this.#f===w)return;this.#l=f,this.#f=w,this.canvas.style.visibility="hidden";let[R,S]=this.parentDimensions;this.width=s/R,this.height=c/S,this.fixAndSetPosition(),this.#a&&this.#L(s,c),this.#k(),this.#C(),this.canvas.style.visibility="visible",this.fixDims()}#L(s,c){let f=this.#$(),w=(s-f)/this.#e,R=(c-f)/this.#t;this.scaleFactor=Math.min(w,R)}#I(){let s=this.#$()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+s,this.translationY*this.scaleFactor+s)}static#F(s){let c=new Path2D;for(let f=0,w=s.length;f<w;f++){let[R,S,D,N]=s[f];f===0&&c.moveTo(...R),c.bezierCurveTo(S[0],S[1],D[0],D[1],N[0],N[1])}return c}static#O(s,c,f){let[w,R,S,D]=c;switch(f){case 0:for(let N=0,H=s.length;N<H;N+=2)s[N]+=w,s[N+1]=D-s[N+1];break;case 90:for(let N=0,H=s.length;N<H;N+=2){let j=s[N];s[N]=s[N+1]+w,s[N+1]=j+R}break;case 180:for(let N=0,H=s.length;N<H;N+=2)s[N]=S-s[N],s[N+1]+=R;break;case 270:for(let N=0,H=s.length;N<H;N+=2){let j=s[N];s[N]=S-s[N+1],s[N+1]=D-j}break;default:throw new Error("Invalid rotation")}return s}static#V(s,c,f){let[w,R,S,D]=c;switch(f){case 0:for(let N=0,H=s.length;N<H;N+=2)s[N]-=w,s[N+1]=D-s[N+1];break;case 90:for(let N=0,H=s.length;N<H;N+=2){let j=s[N];s[N]=s[N+1]-R,s[N+1]=j-w}break;case 180:for(let N=0,H=s.length;N<H;N+=2)s[N]=S-s[N],s[N+1]-=R;break;case 270:for(let N=0,H=s.length;N<H;N+=2){let j=s[N];s[N]=D-s[N+1],s[N+1]=S-j}break;default:throw new Error("Invalid rotation")}return s}#W(s,c,f,w){let R=[],S=this.thickness/2,D=s*c+S,N=s*f+S;for(let H of this.paths){let j=[],Y=[];for(let it=0,ot=H.length;it<ot;it++){let[K,z,W,X]=H[it];if(K[0]===X[0]&&K[1]===X[1]&&ot===1){let h=s*K[0]+D,b=s*K[1]+N;j.push(h,b),Y.push(h,b);break}let et=s*K[0]+D,st=s*K[1]+N,ct=s*z[0]+D,nt=s*z[1]+N,G=s*W[0]+D,A=s*W[1]+N,_=s*X[0]+D,I=s*X[1]+N;it===0&&(j.push(et,st),Y.push(et,st)),j.push(ct,nt,G,A,_,I),Y.push(ct,nt),it===ot-1&&Y.push(_,I)}R.push({bezier:x.#O(j,w,this.rotation),points:x.#O(Y,w,this.rotation)})}return R}#j(){let s=1/0,c=-1/0,f=1/0,w=-1/0;for(let R of this.paths)for(let[S,D,N,H]of R){let j=i.Util.bezierBoundingBox(...S,...D,...N,...H);s=Math.min(s,j[0]),f=Math.min(f,j[1]),c=Math.max(c,j[2]),w=Math.max(w,j[3])}return[s,f,c,w]}#$(){return this.#a?Math.ceil(this.thickness*this.parentScale):0}#N(s=!1){if(this.isEmpty())return;if(!this.#a){this.#C();return}let c=this.#j(),f=this.#$();this.#e=Math.max(r.AnnotationEditor.MIN_SIZE,c[2]-c[0]),this.#t=Math.max(r.AnnotationEditor.MIN_SIZE,c[3]-c[1]);let w=Math.ceil(f+this.#e*this.scaleFactor),R=Math.ceil(f+this.#t*this.scaleFactor),[S,D]=this.parentDimensions;this.width=w/S,this.height=R/D,this.setAspectRatio(w,R);let N=this.translationX,H=this.translationY;this.translationX=-c[0],this.translationY=-c[1],this.#k(),this.#C(),this.#l=w,this.#f=R,this.setDims(w,R);let j=s?f/this.scaleFactor/2:0;this.translate(N-this.translationX-j,H-this.translationY-j)}static deserialize(s,c,f){if(s instanceof g.InkAnnotationElement)return null;let w=super.deserialize(s,c,f);w.thickness=s.thickness,w.color=i.Util.makeHexColor(...s.color),w.opacity=s.opacity;let[R,S]=w.pageDimensions,D=w.width*R,N=w.height*S,H=w.parentScale,j=s.thickness/2;w.#a=!0,w.#l=Math.round(D),w.#f=Math.round(N);let{paths:Y,rect:it,rotation:ot}=s;for(let{bezier:z}of Y){z=x.#V(z,it,ot);let W=[];w.paths.push(W);let X=H*(z[0]-j),et=H*(z[1]-j);for(let ct=2,nt=z.length;ct<nt;ct+=6){let G=H*(z[ct]-j),A=H*(z[ct+1]-j),_=H*(z[ct+2]-j),I=H*(z[ct+3]-j),h=H*(z[ct+4]-j),b=H*(z[ct+5]-j);W.push([[X,et],[G,A],[_,I],[h,b]]),X=h,et=b}let st=this.#F(W);w.bezierPath2D.push(st)}let K=w.#j();return w.#e=Math.max(r.AnnotationEditor.MIN_SIZE,K[2]-K[0]),w.#t=Math.max(r.AnnotationEditor.MIN_SIZE,K[3]-K[1]),w.#L(D,N),w}serialize(){if(this.isEmpty())return null;let s=this.getRect(0,0),c=r.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);return{annotationType:i.AnnotationEditorType.INK,color:c,thickness:this.thickness,opacity:this.opacity,paths:this.#W(this.scaleFactor/this.parentScale,this.translationX,this.translationY,s),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}}class T extends r.AnnotationEditor{#t=null;#e=null;#i=null;#n=null;#r=null;#s="";#o=null;#c=null;#a=null;#h=!1;#u=!1;static _type="stamp";static _editorType=i.AnnotationEditorType.STAMP;constructor(s){super({...s,name:"stampEditor"}),this.#n=s.bitmapUrl,this.#r=s.bitmapFile}static initialize(s,c){r.AnnotationEditor.initialize(s,c)}static get supportedTypes(){return(0,i.shadow)(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((s=>`image/${s}`)))}static get supportedTypesStr(){return(0,i.shadow)(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(s){return this.supportedTypes.includes(s)}static paste(s,c){c.pasteEditor(i.AnnotationEditorType.STAMP,{bitmapFile:s.getAsFile()})}#d(s,c=!1){s?(this.#t=s.bitmap,c||(this.#e=s.id,this.#h=s.isSvg),s.file&&(this.#s=s.file.name),this.#g()):this.remove()}#l(){this.#i=null,this._uiManager.enableWaiting(!1),this.#o&&this.div.focus()}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then((c=>this.#d(c,!0))).finally((()=>this.#l()));return}if(this.#n){let c=this.#n;this.#n=null,this._uiManager.enableWaiting(!0),this.#i=this._uiManager.imageManager.getFromUrl(c).then((f=>this.#d(f))).finally((()=>this.#l()));return}if(this.#r){let c=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#i=this._uiManager.imageManager.getFromFile(c).then((f=>this.#d(f))).finally((()=>this.#l()));return}let s=document.createElement("input");s.type="file",s.accept=T.supportedTypesStr,this.#i=new Promise((c=>{s.addEventListener("change",(async()=>{if(s.files&&s.files.length!==0){this._uiManager.enableWaiting(!0);let f=await this._uiManager.imageManager.getFromFile(s.files[0]);this.#d(f)}else this.remove();c()})),s.addEventListener("cancel",(()=>{this.remove(),c()}))})).finally((()=>this.#l())),s.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#o?.remove(),this.#o=null,this.#c?.disconnect(),this.#c=null,this.#a&&(clearTimeout(this.#a),this.#a=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),this.div!==null&&(this.#e&&this.#o===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))):this.#e&&this.#f()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#i||this.#t||this.#n||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let s,c;if(this.width&&(s=this.x,c=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#t?this.#g():this.#f(),this.width){let[f,w]=this.parentDimensions;this.setAt(s*f,c*w,this.width*f,this.height*w)}return this.div}#g(){let{div:s}=this,{width:c,height:f}=this.#t,[w,R]=this.pageDimensions,S=.75;if(this.width)c=this.width*w,f=this.height*R;else if(c>S*w||f>S*R){let j=Math.min(S*w/c,S*R/f);c*=j,f*=j}let[D,N]=this.parentDimensions;this.setDims(c*D/w,f*N/R),this._uiManager.enableWaiting(!1);let H=this.#o=document.createElement("canvas");s.append(H),s.hidden=!1,this.#m(c,f),this.#S(),this.#u||(this.parent.addUndoableEditor(this),this.#u=!0),this._reportTelemetry({action:"inserted_image"}),this.#s&&H.setAttribute("aria-label",this.#s)}#p(s,c){let[f,w]=this.parentDimensions;this.width=s/f,this.height=c/w,this.setDims(s,c),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this.#a!==null&&clearTimeout(this.#a),this.#a=setTimeout((()=>{this.#a=null,this.#m(s,c)}),200)}#y(s,c){let{width:f,height:w}=this.#t,R=f,S=w,D=this.#t;for(;R>2*s||S>2*c;){let N=R,H=S;R>2*s&&(R=R>=16384?Math.floor(R/2)-1:Math.ceil(R/2)),S>2*c&&(S=S>=16384?Math.floor(S/2)-1:Math.ceil(S/2));let j=new OffscreenCanvas(R,S);j.getContext("2d").drawImage(D,0,0,N,H,0,0,R,S),D=j.transferToImageBitmap()}return D}#m(s,c){s=Math.ceil(s),c=Math.ceil(c);let f=this.#o;if(!f||f.width===s&&f.height===c)return;f.width=s,f.height=c;let w=this.#h?this.#t:this.#y(s,c);if(this._uiManager.hasMLManager&&!this.hasAltText()){let S=new OffscreenCanvas(s,c);S.getContext("2d").drawImage(w,0,0,w.width,w.height,0,0,s,c),S.convertToBlob().then((D=>{let N=new FileReader;N.onload=()=>{let H=N.result;this._uiManager.mlGuess({service:"image-to-text",request:{imageData:H}}).then((j=>{let Y=j?.output||"";this.parent&&Y&&!this.hasAltText()&&(this.altTextData={altText:Y,decorative:!1})}))},N.readAsDataURL(D)}))}let R=f.getContext("2d");R.filter=this._uiManager.hcmFilter,R.drawImage(w,0,0,w.width,w.height,0,0,s,c)}getImageForAltText(){return this.#o}#b(s){if(s){if(this.#h){let f=this._uiManager.imageManager.getSvgUrl(this.#e);if(f)return f}let c=document.createElement("canvas");return{width:c.width,height:c.height}=this.#t,c.getContext("2d").drawImage(this.#t,0,0),c.toDataURL()}if(this.#h){let[c,f]=this.pageDimensions,w=Math.round(this.width*c*a.PixelsPerInch.PDF_TO_CSS_UNITS),R=Math.round(this.height*f*a.PixelsPerInch.PDF_TO_CSS_UNITS),S=new OffscreenCanvas(w,R);return S.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,w,R),S.transferToImageBitmap()}return structuredClone(this.#t)}#S(){this.#c=new ResizeObserver((s=>{let c=s[0].contentRect;c.width&&c.height&&this.#p(c.width,c.height)})),this.#c.observe(this.div)}static deserialize(s,c,f){if(s instanceof g.StampAnnotationElement)return null;let w=super.deserialize(s,c,f),{rect:R,bitmapUrl:S,bitmapId:D,isSvg:N,accessibilityData:H}=s;D&&f.imageManager.isValidId(D)?w.#e=D:w.#n=S,w.#h=N;let[j,Y]=w.pageDimensions;return w.width=(R[2]-R[0])/j,w.height=(R[3]-R[1])/Y,H&&(w.altTextData=H),w}serialize(s=!1,c=null){if(this.isEmpty())return null;let f={annotationType:i.AnnotationEditorType.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#h,structTreeParentId:this._structTreeParentId};if(s)return f.bitmapUrl=this.#b(!0),f.accessibilityData=this.altTextData,f;let{decorative:w,altText:R}=this.altTextData;if(!w&&R&&(f.accessibilityData={type:"Figure",alt:R}),c===null)return f;c.stamps||=new Map;let S=this.#h?(f.rect[2]-f.rect[0])*(f.rect[3]-f.rect[1]):null;if(c.stamps.has(this.#e)){if(this.#h){let D=c.stamps.get(this.#e);S>D.area&&(D.area=S,D.serialized.bitmap.close(),D.serialized.bitmap=this.#b(!1))}}else c.stamps.set(this.#e,{area:S,serialized:f}),f.bitmap=this.#b(!1);return f}}class l{#t;#e=!1;#i=null;#n=null;#r=null;#s=null;#o=null;#c=new Map;#a=!1;#h=!1;#u=!1;#d=null;#l;static _initialized=!1;static#f=new Map([m,x,T,p].map((s=>[s._editorType,s])));constructor({uiManager:s,pageIndex:c,div:f,accessibilityManager:w,annotationLayer:R,drawLayer:S,textLayer:D,viewport:N,l10n:H}){let j=[...l.#f.values()];if(!l._initialized){l._initialized=!0;for(let Y of j)Y.initialize(H,s)}s.registerEditorTypes(j),this.#l=s,this.pageIndex=c,this.div=f,this.#t=w,this.#i=R,this.viewport=N,this.#d=D,this.drawLayer=S,this.#l.addLayer(this)}get isEmpty(){return this.#c.size===0}get isInvisible(){return this.isEmpty&&this.#l.getMode()===i.AnnotationEditorType.NONE}updateToolbar(s){this.#l.updateToolbar(s)}updateMode(s=this.#l.getMode()){switch(this.#b(),s){case i.AnnotationEditorType.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case i.AnnotationEditorType.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case i.AnnotationEditorType.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:c}=this.div;for(let f of l.#f.values())c.toggle(`${f._type}Editing`,s===f._editorType);this.div.hidden=!1}hasTextLayer(s){return s===this.#d?.div}addInkEditorIfNeeded(s){if(this.#l.getMode()===i.AnnotationEditorType.INK){if(!s){for(let c of this.#c.values())if(c.isEmpty()){c.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(s){this.#l.setEditingState(s)}addCommands(s){this.#l.addCommands(s)}togglePointerEvents(s=!1){this.div.classList.toggle("disabled",!s)}toggleAnnotationLayerPointerEvents(s=!1){this.#i?.div.classList.toggle("disabled",!s)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);let s=new Set;for(let f of this.#c.values())f.enableEditing(),f.annotationElementId&&s.add(f.annotationElementId);if(!this.#i)return;let c=this.#i.getEditableAnnotations();for(let f of c){if(f.hide(),this.#l.isDeletedAnnotationElement(f.data.id)||s.has(f.data.id))continue;let w=this.deserialize(f);w&&(this.addOrRebuild(w),w.enableEditing())}}disable(){this.#u=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let s=new Set;for(let f of this.#c.values())f.disableEditing(),f.annotationElementId&&f.serialize()===null?(this.getEditableAnnotation(f.annotationElementId)?.show(),f.remove()):s.add(f.annotationElementId);if(this.#i){let f=this.#i.getEditableAnnotations();for(let w of f){let{id:R}=w.data;s.has(R)||this.#l.isDeletedAnnotationElement(R)||w.show()}}this.#b(),this.isEmpty&&(this.div.hidden=!0);let{classList:c}=this.div;for(let f of l.#f.values())c.remove(`${f._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#u=!1}getEditableAnnotation(s){return this.#i?.getEditableAnnotation(s)||null}setActiveEditor(s){this.#l.getActive()!==s&&this.#l.setActiveEditor(s)}enableTextSelection(){this.div.tabIndex=-1,this.#d?.div&&!this.#s&&(this.#s=this.#g.bind(this),this.#d.div.addEventListener("pointerdown",this.#s),this.#d.div.classList.add("highlighting"))}disableTextSelection(){this.div.tabIndex=0,this.#d?.div&&this.#s&&(this.#d.div.removeEventListener("pointerdown",this.#s),this.#s=null,this.#d.div.classList.remove("highlighting"))}#g(s){if(this.#l.unselectAll(),s.target===this.#d.div){let{isMac:c}=i.FeatureTest.platform;if(s.button!==0||s.ctrlKey&&c)return;this.#l.showAllEditors("highlight",!0,!0),this.#d.div.classList.add("free"),p.startHighlighting(this,this.#l.direction==="ltr",s),this.#d.div.addEventListener("pointerup",(()=>{this.#d.div.classList.remove("free")}),{once:!0}),s.preventDefault()}}enableClick(){this.#r||(this.#r=this.pointerdown.bind(this),this.#n=this.pointerup.bind(this),this.div.addEventListener("pointerdown",this.#r),this.div.addEventListener("pointerup",this.#n))}disableClick(){this.#r&&(this.div.removeEventListener("pointerdown",this.#r),this.div.removeEventListener("pointerup",this.#n),this.#r=null,this.#n=null)}attach(s){this.#c.set(s.id,s);let{annotationElementId:c}=s;c&&this.#l.isDeletedAnnotationElement(c)&&this.#l.removeDeletedAnnotationElement(s)}detach(s){this.#c.delete(s.id),this.#t?.removePointerInTextLayer(s.contentDiv),!this.#u&&s.annotationElementId&&this.#l.addDeletedAnnotationElement(s)}remove(s){this.detach(s),this.#l.removeEditor(s),s.div.remove(),s.isAttachedToDOM=!1,this.#h||this.addInkEditorIfNeeded(!1)}changeParent(s){s.parent!==this&&(s.annotationElementId&&(this.#l.addDeletedAnnotationElement(s.annotationElementId),r.AnnotationEditor.deleteAnnotationElement(s),s.annotationElementId=null),this.attach(s),s.parent?.detach(s),s.setParent(this),s.div&&s.isAttachedToDOM&&(s.div.remove(),this.div.append(s.div)))}add(s){if(s.parent!==this||!s.isAttachedToDOM){if(this.changeParent(s),this.#l.addEditor(s),this.attach(s),!s.isAttachedToDOM){let c=s.render();this.div.append(c),s.isAttachedToDOM=!0}s.fixAndSetPosition(),s.onceAdded(),this.#l.addToAnnotationStorage(s),s._reportTelemetry(s.telemetryInitialData)}}moveEditorInDOM(s){if(!s.isAttachedToDOM)return;let{activeElement:c}=document;s.div.contains(c)&&!this.#o&&(s._focusEventsAllowed=!1,this.#o=setTimeout((()=>{this.#o=null,s.div.contains(document.activeElement)?s._focusEventsAllowed=!0:(s.div.addEventListener("focusin",(()=>{s._focusEventsAllowed=!0}),{once:!0}),c.focus())}),0)),s._structTreeParentId=this.#t?.moveElementInDOM(this.div,s.div,s.contentDiv,!0)}addOrRebuild(s){s.needsToBeRebuilt()?(s.parent||=this,s.rebuild(),s.show()):this.add(s)}addUndoableEditor(s){this.addCommands({cmd:()=>s._uiManager.rebuild(s),undo:()=>{s.remove()},mustExec:!1})}getNextId(){return this.#l.getId()}get#p(){return l.#f.get(this.#l.getMode())}#y(s){let c=this.#p;return c?new c.prototype.constructor(s):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(s,c){this.#l.updateToolbar(s),this.#l.updateMode(s);let{offsetX:f,offsetY:w}=this.#m(),R=this.getNextId(),S=this.#y({parent:this,id:R,x:f,y:w,uiManager:this.#l,isCentered:!0,...c});S&&this.add(S)}deserialize(s){return l.#f.get(s.annotationType??s.annotationEditorType)?.deserialize(s,this,this.#l)||null}createAndAddNewEditor(s,c,f={}){let w=this.getNextId(),R=this.#y({parent:this,id:w,x:s.offsetX,y:s.offsetY,uiManager:this.#l,isCentered:c,...f});return R&&this.add(R),R}#m(){let{x:s,y:c,width:f,height:w}=this.div.getBoundingClientRect(),R=Math.max(0,s),S=Math.max(0,c),D=(R+Math.min(window.innerWidth,s+f))/2-s,N=(S+Math.min(window.innerHeight,c+w))/2-c,[H,j]=this.viewport.rotation%180==0?[D,N]:[N,D];return{offsetX:H,offsetY:j}}addNewEditor(){this.createAndAddNewEditor(this.#m(),!0)}setSelected(s){this.#l.setSelected(s)}toggleSelected(s){this.#l.toggleSelected(s)}isSelected(s){return this.#l.isSelected(s)}unselect(s){this.#l.unselect(s)}pointerup(s){let{isMac:c}=i.FeatureTest.platform;!(s.button!==0||s.ctrlKey&&c)&&s.target===this.div&&this.#a&&(this.#a=!1,this.#e?this.#l.getMode()!==i.AnnotationEditorType.STAMP?this.createAndAddNewEditor(s,!1):this.#l.unselectAll():this.#e=!0)}pointerdown(s){if(this.#l.getMode()===i.AnnotationEditorType.HIGHLIGHT&&this.enableTextSelection(),this.#a){this.#a=!1;return}let{isMac:c}=i.FeatureTest.platform;if(s.button!==0||s.ctrlKey&&c||s.target!==this.div)return;this.#a=!0;let f=this.#l.getActive();this.#e=!f||f.isEmpty()}findNewParent(s,c,f){let w=this.#l.findParent(c,f);return w===null||w===this?!1:(w.changeParent(s),!0)}destroy(){this.#l.getActive()?.parent===this&&(this.#l.commitOrRemove(),this.#l.setActiveEditor(null)),this.#o&&(clearTimeout(this.#o),this.#o=null);for(let s of this.#c.values())this.#t?.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,this.#c.clear(),this.#l.removeLayer(this)}#b(){this.#h=!0;for(let s of this.#c.values())s.isEmpty()&&s.remove();this.#h=!1}render({viewport:s}){this.viewport=s,(0,a.setLayerDimensions)(this.div,s);for(let c of this.#l.getEditors(this.pageIndex))this.add(c),c.rebuild();this.updateMode()}update({viewport:s}){this.#l.commitOrRemove(),this.#b();let c=this.viewport.rotation,f=s.rotation;if(this.viewport=s,(0,a.setLayerDimensions)(this.div,{rotation:f}),c!==f)for(let w of this.#c.values())w.rotate(f);this.addInkEditorIfNeeded(!1)}get pageDimensions(){let{pageWidth:s,pageHeight:c}=this.viewport.rawDims;return[s,c]}get scale(){return this.#l.viewParameters.realScale}}},259:(n,t,e)=>{e.d(t,{ColorPicker:()=>g});var i=e(292),r=e(830),o=e(419);class g{#t=this.#g.bind(this);#e=this.#y.bind(this);#i=null;#n=null;#r;#s=null;#o=!1;#c=!1;#a=null;#h;#u=null;#d;static get _keyboardManager(){return(0,i.shadow)(this,"_keyboardManager",new r.KeyboardManager([[["Escape","mac+Escape"],g.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],g.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],g.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],g.prototype._moveToPrevious],[["Home","mac+Home"],g.prototype._moveToBeginning],[["End","mac+End"],g.prototype._moveToEnd]]))}constructor({editor:m=null,uiManager:v=null}){m?(this.#c=!1,this.#d=i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.#a=m):(this.#c=!0,this.#d=i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR),this.#u=m?._uiManager||v,this.#h=this.#u._eventBus,this.#r=m?.color||this.#u?.highlightColors.values().next().value||"#FFFF98"}renderButton(){let m=this.#i=document.createElement("button");m.className="colorPicker",m.tabIndex="0",m.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),m.setAttribute("aria-haspopup",!0),m.addEventListener("click",this.#p.bind(this)),m.addEventListener("keydown",this.#t);let v=this.#n=document.createElement("span");return v.className="swatch",v.setAttribute("aria-hidden",!0),v.style.backgroundColor=this.#r,m.append(v),m}renderMainDropdown(){let m=this.#s=this.#l();return m.setAttribute("aria-orientation","horizontal"),m.setAttribute("aria-labelledby","highlightColorPickerLabel"),m}#l(){let m=document.createElement("div");m.addEventListener("contextmenu",o.noContextMenu),m.className="dropdown",m.role="listbox",m.setAttribute("aria-multiselectable",!1),m.setAttribute("aria-orientation","vertical"),m.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(let[v,u]of this.#u.highlightColors){let a=document.createElement("button");a.tabIndex="0",a.role="option",a.setAttribute("data-color",u),a.title=v,a.setAttribute("data-l10n-id",`pdfjs-editor-colorpicker-${v}`);let p=document.createElement("span");a.append(p),p.className="swatch",p.style.backgroundColor=u,a.setAttribute("aria-selected",u===this.#r),a.addEventListener("click",this.#f.bind(this,u)),m.append(a)}return m.addEventListener("keydown",this.#t),m}#f(m,v){v.stopPropagation(),this.#h.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:m})}_colorSelectFromKeyboard(m){if(m.target===this.#i){this.#p(m);return}let v=m.target.getAttribute("data-color");v&&this.#f(v,m)}_moveToNext(m){this.#m?m.target!==this.#i?m.target.nextSibling?.focus():this.#s.firstChild?.focus():this.#p(m)}_moveToPrevious(m){m.target!==this.#s?.firstChild&&m.target!==this.#i?(this.#m||this.#p(m),m.target.previousSibling?.focus()):this.#m&&this._hideDropdownFromKeyboard()}_moveToBeginning(m){this.#m?this.#s.firstChild?.focus():this.#p(m)}_moveToEnd(m){this.#m?this.#s.lastChild?.focus():this.#p(m)}#g(m){g._keyboardManager.exec(this,m)}#p(m){if(this.#m){this.hideDropdown();return}if(this.#o=m.detail===0,window.addEventListener("pointerdown",this.#e),this.#s){this.#s.classList.remove("hidden");return}let v=this.#s=this.#l();this.#i.append(v)}#y(m){this.#s?.contains(m.target)||this.hideDropdown()}hideDropdown(){this.#s?.classList.add("hidden"),window.removeEventListener("pointerdown",this.#e)}get#m(){return this.#s&&!this.#s.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#c||(this.#m?(this.hideDropdown(),this.#i.focus({preventScroll:!0,focusVisible:this.#o})):this.#a?.unselect())}updateColor(m){if(this.#n&&(this.#n.style.backgroundColor=m),!this.#s)return;let v=this.#u.highlightColors.values();for(let u of this.#s.children)u.setAttribute("aria-selected",v.next().value===m)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null,this.#s?.remove(),this.#s=null}}},310:(n,t,e)=>{e.d(t,{AnnotationEditor:()=>m});var i=e(830),r=e(292),o=e(419);class g{#t="";#e=!1;#i=null;#n=null;#r=null;#s=!1;#o=null;static _l10nPromise=null;constructor(a){this.#o=a}static initialize(a){g._l10nPromise||=a}async render(){let a=this.#i=document.createElement("button");a.className="altText";let p=await g._l10nPromise.get("pdfjs-editor-alt-text-button-label");a.textContent=p,a.setAttribute("aria-label",p),a.tabIndex="0",a.addEventListener("contextmenu",o.noContextMenu),a.addEventListener("pointerdown",(T=>T.stopPropagation()));let x=T=>{T.preventDefault(),this.#o._uiManager.editAltText(this.#o)};return a.addEventListener("click",x,{capture:!0}),a.addEventListener("keydown",(T=>{T.target===a&&T.key==="Enter"&&(this.#s=!0,x(T))})),await this.#c(),a}finish(){this.#i&&(this.#i.focus({focusVisible:this.#s}),this.#s=!1)}isEmpty(){return!this.#t&&!this.#e}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:a,decorative:p}){(this.#t!==a||this.#e!==p)&&(this.#t=a,this.#e=p,this.#c())}toggle(a=!1){this.#i&&(!a&&this.#r&&(clearTimeout(this.#r),this.#r=null),this.#i.disabled=!a)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null}async#c(){let a=this.#i;if(!a)return;if(!this.#t&&!this.#e){a.classList.remove("done"),this.#n?.remove();return}a.classList.add("done"),g._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((T=>{a.setAttribute("aria-label",T)}));let p=this.#n;if(!p){this.#n=p=document.createElement("span"),p.className="tooltip",p.setAttribute("role","tooltip");let T=p.id=`alt-text-tooltip-${this.#o.id}`;a.setAttribute("aria-describedby",T);let l=100;a.addEventListener("mouseenter",(()=>{this.#r=setTimeout((()=>{this.#r=null,this.#n.classList.add("show"),this.#o._reportTelemetry({action:"alt_text_tooltip"})}),l)})),a.addEventListener("mouseleave",(()=>{this.#r&&(clearTimeout(this.#r),this.#r=null),this.#n?.classList.remove("show")}))}p.innerText=this.#e?await g._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#t,p.parentNode||a.append(p),this.#o.getImageForAltText()?.setAttribute("aria-describedby",p.id)}}var d=e(362);class m{#t=null;#e=null;#i=!1;#n=!1;#r=null;#s=null;#o=this.focusin.bind(this);#c=this.focusout.bind(this);#a=null;#h="";#u=!1;#d=null;#l=!1;#f=!1;#g=!1;#p=null;#y=0;#m=0;#b=null;_initialOptions=Object.create(null);_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#S=!1;#_=m._zIndex++;static _borderLineWidth=-1;static _colorManager=new i.ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let a=m.prototype._resizeWithKeyboard,p=i.AnnotationEditorUIManager.TRANSLATE_SMALL,x=i.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,r.shadow)(this,"_resizerKeyboardManager",new i.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],a,{args:[-p,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],a,{args:[-x,0]}],[["ArrowRight","mac+ArrowRight"],a,{args:[p,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],a,{args:[x,0]}],[["ArrowUp","mac+ArrowUp"],a,{args:[0,-p]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],a,{args:[0,-x]}],[["ArrowDown","mac+ArrowDown"],a,{args:[0,p]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],a,{args:[0,x]}],[["Escape","mac+Escape"],m.prototype._stopResizingWithKeyboard]]))}constructor(a){this.constructor===m&&(0,r.unreachable)("Cannot initialize AnnotationEditor."),this.parent=a.parent,this.id=a.id,this.width=this.height=null,this.pageIndex=a.parent.pageIndex,this.name=a.name,this.div=null,this._uiManager=a.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=a.isCentered,this._structTreeParentId=null;let{rotation:p,rawDims:{pageWidth:x,pageHeight:T,pageX:l,pageY:y}}=this.parent.viewport;this.rotation=p,this.pageRotation=(360+p-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[x,T],this.pageTranslation=[l,y];let[s,c]=this.parentDimensions;this.x=a.x/s,this.y=a.y/c,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return(0,r.shadow)(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(a){let p=new v({id:a.parent.getNextId(),parent:a.parent,uiManager:a._uiManager});p.annotationElementId=a.annotationElementId,p.deleted=!0,p._uiManager.addToAnnotationStorage(p)}static initialize(a,p,x){if(m._l10nPromise||=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map((l=>[l,a.get(l.replaceAll(/([A-Z])/g,(y=>`-${y.toLowerCase()}`)))]))),x?.strings)for(let l of x.strings)m._l10nPromise.set(l,a.get(l));if(m._borderLineWidth!==-1)return;let T=getComputedStyle(document.documentElement);m._borderLineWidth=parseFloat(T.getPropertyValue("--outline-width"))||0}static updateDefaultParams(a,p){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(a){return!1}static paste(a,p){(0,r.unreachable)("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#S}set _isDraggable(a){this.#S=a,this.div?.classList.toggle("draggable",a)}get isEnterHandled(){return!0}center(){let[a,p]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*p/(2*a),this.y+=this.width*a/(2*p);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*p/(2*a),this.y-=this.width*a/(2*p);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(a){this._uiManager.addCommands(a)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#_}setParent(a){a!==null?(this.pageIndex=a.pageIndex,this.pageDimensions=a.pageDimensions):this.#F(),this.parent=a}focusin(a){this._focusEventsAllowed&&(this.#u?this.#u=!1:this.parent.setSelected(this))}focusout(a){if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;a.relatedTarget?.closest(`#${this.id}`)||(a.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(a,p,x,T){let[l,y]=this.parentDimensions;[x,T]=this.screenToPageTranslation(x,T),this.x=(a+x)/l,this.y=(p+T)/y,this.fixAndSetPosition()}#M([a,p],x,T){[x,T]=this.screenToPageTranslation(x,T),this.x+=x/a,this.y+=T/p,this.fixAndSetPosition()}translate(a,p){this.#M(this.parentDimensions,a,p)}translateInPage(a,p){this.#d||=[this.x,this.y],this.#M(this.pageDimensions,a,p),this.div.scrollIntoView({block:"nearest"})}drag(a,p){this.#d||=[this.x,this.y];let[x,T]=this.parentDimensions;if(this.x+=a/x,this.y+=p/T,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:f,y:w}=this.div.getBoundingClientRect();this.parent.findNewParent(this,f,w)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:l,y}=this,[s,c]=this.getBaseTranslation();l+=s,y+=c,this.div.style.left=`${(100*l).toFixed(2)}%`,this.div.style.top=`${(100*y).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#d&&(this.#d[0]!==this.x||this.#d[1]!==this.y)}getBaseTranslation(){let[a,p]=this.parentDimensions,{_borderLineWidth:x}=m,T=x/a,l=x/p;switch(this.rotation){case 90:return[-T,l];case 180:return[T,l];case 270:return[T,-l];default:return[-T,-l]}}get _mustFixPosition(){return!0}fixAndSetPosition(a=this.rotation){let[p,x]=this.pageDimensions,{x:T,y:l,width:y,height:s}=this;if(y*=p,s*=x,T*=p,l*=x,this._mustFixPosition)switch(a){case 0:T=Math.max(0,Math.min(p-y,T)),l=Math.max(0,Math.min(x-s,l));break;case 90:T=Math.max(0,Math.min(p-s,T)),l=Math.min(x,Math.max(y,l));break;case 180:T=Math.min(p,Math.max(y,T)),l=Math.min(x,Math.max(s,l));break;case 270:T=Math.min(p,Math.max(s,T)),l=Math.max(0,Math.min(x-y,l))}this.x=T/=p,this.y=l/=x;let[c,f]=this.getBaseTranslation();T+=c,l+=f;let{style:w}=this.div;w.left=`${(100*T).toFixed(2)}%`,w.top=`${(100*l).toFixed(2)}%`,this.moveInDOM()}static#w(a,p,x){switch(x){case 90:return[p,-a];case 180:return[-a,-p];case 270:return[-p,a];default:return[a,p]}}screenToPageTranslation(a,p){return m.#w(a,p,this.parentRotation)}pageTranslationToScreen(a,p){return m.#w(a,p,360-this.parentRotation)}#x(a){switch(a){case 90:{let[p,x]=this.pageDimensions;return[0,-p/x,x/p,0]}case 180:return[-1,0,0,-1];case 270:{let[p,x]=this.pageDimensions;return[0,p/x,-x/p,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:a,pageDimensions:[p,x]}=this,T=p*a,l=x*a;return r.FeatureTest.isCSSRoundSupported?[Math.round(T),Math.round(l)]:[T,l]}setDims(a,p){let[x,T]=this.parentDimensions;this.div.style.width=`${(100*a/x).toFixed(2)}%`,this.#n||(this.div.style.height=`${(100*p/T).toFixed(2)}%`)}fixDims(){let{style:a}=this.div,{height:p,width:x}=a,T=x.endsWith("%"),l=!this.#n&&p.endsWith("%");if(T&&l)return;let[y,s]=this.parentDimensions;T||(a.width=`${(100*parseFloat(x)/y).toFixed(2)}%`),this.#n||l||(a.height=`${(100*parseFloat(p)/s).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#v(){if(this.#r)return;this.#r=document.createElement("div"),this.#r.classList.add("resizers");let a=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"];for(let p of a){let x=document.createElement("div");this.#r.append(x),x.classList.add("resizer",p),x.setAttribute("data-resizer-name",p),x.addEventListener("pointerdown",this.#E.bind(this,p)),x.addEventListener("contextmenu",o.noContextMenu),x.tabIndex=-1}this.div.prepend(this.#r)}#E(a,p){p.preventDefault();let{isMac:x}=r.FeatureTest.platform;if(p.button!==0||p.ctrlKey&&x)return;this.#e?.toggle(!1);let T=this.#C.bind(this,a),l=this._isDraggable;this._isDraggable=!1;let y={passive:!0,capture:!0};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",T,y);let s=this.x,c=this.y,f=this.width,w=this.height,R=this.parent.div.style.cursor,S=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(p.target).cursor;let D=()=>{this.parent.togglePointerEvents(!0),this.#e?.toggle(!0),this._isDraggable=l,window.removeEventListener("pointerup",D),window.removeEventListener("blur",D),window.removeEventListener("pointermove",T,y),this.parent.div.style.cursor=R,this.div.style.cursor=S,this.#A(s,c,f,w)};window.addEventListener("pointerup",D),window.addEventListener("blur",D)}#A(a,p,x,T){let l=this.x,y=this.y,s=this.width,c=this.height;l===a&&y===p&&s===x&&c===T||this.addCommands({cmd:()=>{this.width=s,this.height=c,this.x=l,this.y=y;let[f,w]=this.parentDimensions;this.setDims(f*s,w*c),this.fixAndSetPosition()},undo:()=>{this.width=x,this.height=T,this.x=a,this.y=p;let[f,w]=this.parentDimensions;this.setDims(f*x,w*T),this.fixAndSetPosition()},mustExec:!0})}#C(a,p){let[x,T]=this.parentDimensions,l=this.x,y=this.y,s=this.width,c=this.height,f=m.MIN_SIZE/x,w=m.MIN_SIZE/T,R=C=>Math.round(1e4*C)/1e4,S=this.#x(this.rotation),D=(C,P)=>[S[0]*C+S[2]*P,S[1]*C+S[3]*P],N=this.#x(360-this.rotation),H,j,Y=!1,it=!1;switch(a){case"topLeft":Y=!0,H=(C,P)=>[0,0],j=(C,P)=>[C,P];break;case"topMiddle":H=(C,P)=>[C/2,0],j=(C,P)=>[C/2,P];break;case"topRight":Y=!0,H=(C,P)=>[C,0],j=(C,P)=>[0,P];break;case"middleRight":it=!0,H=(C,P)=>[C,P/2],j=(C,P)=>[0,P/2];break;case"bottomRight":Y=!0,H=(C,P)=>[C,P],j=(C,P)=>[0,0];break;case"bottomMiddle":H=(C,P)=>[C/2,P],j=(C,P)=>[C/2,0];break;case"bottomLeft":Y=!0,H=(C,P)=>[0,P],j=(C,P)=>[C,0];break;case"middleLeft":it=!0,H=(C,P)=>[0,P/2],j=(C,P)=>[C,P/2]}let ot=H(s,c),K=j(s,c),z=D(...K),W=R(l+z[0]),X=R(y+z[1]),et=1,st=1,[ct,nt]=this.screenToPageTranslation(p.movementX,p.movementY);[ct,nt]=(G=ct/x,A=nt/T,[N[0]*G+N[2]*A,N[1]*G+N[3]*A]);var G,A;if(Y){let C=Math.hypot(s,c);et=st=Math.max(Math.min(Math.hypot(K[0]-ot[0]-ct,K[1]-ot[1]-nt)/C,1/s,1/c),f/s,w/c)}else it?et=Math.max(f,Math.min(1,Math.abs(K[0]-ot[0]-ct)))/s:st=Math.max(w,Math.min(1,Math.abs(K[1]-ot[1]-nt)))/c;let _=R(s*et),I=R(c*st);z=D(...j(_,I));let h=W-z[0],b=X-z[1];this.width=_,this.height=I,this.x=h,this.y=b,this.setDims(x*_,T*I),this.fixAndSetPosition()}altTextFinish(){this.#e?.finish()}async addEditToolbar(){return this.#a||this.#f?this.#a:(this.#a=new d.EditorToolbar(this),this.div.append(this.#a.render()),this.#e&&this.#a.addAltTextButton(await this.#e.render()),this.#a)}removeEditToolbar(){this.#a&&(this.#a.remove(),this.#a=null,this.#e?.destroy())}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#e||(g.initialize(m._l10nPromise),this.#e=new g(this),await this.addEditToolbar())}get altTextData(){return this.#e?.data}set altTextData(a){this.#e&&(this.#e.data=a)}hasAltText(){return!this.#e?.isEmpty()}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#i?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.div.addEventListener("focusin",this.#o),this.div.addEventListener("focusout",this.#c);let[a,p]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*p/a).toFixed(2)}%`,this.div.style.maxHeight=`${(100*a/p).toFixed(2)}%`);let[x,T]=this.getInitialTranslation();return this.translate(x,T),(0,i.bindEvents)(this,this.div,["pointerdown"]),this.div}pointerdown(a){let{isMac:p}=r.FeatureTest.platform;a.button!==0||a.ctrlKey&&p?a.preventDefault():(this.#u=!0,this._isDraggable?this.#P(a):this.#T(a))}#T(a){let{isMac:p}=r.FeatureTest.platform;a.ctrlKey&&!p||a.shiftKey||a.metaKey&&p?this.parent.toggleSelected(this):this.parent.setSelected(this)}#P(a){let p=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let x,T;p&&(this.div.classList.add("moving"),x={passive:!0,capture:!0},this.#y=a.clientX,this.#m=a.clientY,T=y=>{let{clientX:s,clientY:c}=y,[f,w]=this.screenToPageTranslation(s-this.#y,c-this.#m);this.#y=s,this.#m=c,this._uiManager.dragSelectedEditors(f,w)},window.addEventListener("pointermove",T,x));let l=()=>{window.removeEventListener("pointerup",l),window.removeEventListener("blur",l),p&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",T,x)),this.#u=!1,this._uiManager.endDragSession()||this.#T(a)};window.addEventListener("pointerup",l),window.addEventListener("blur",l)}moveInDOM(){this.#p&&clearTimeout(this.#p),this.#p=setTimeout((()=>{this.#p=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(a,p,x){a.changeParent(this),this.x=p,this.y=x,this.fixAndSetPosition()}getRect(a,p,x=this.rotation){let T=this.parentScale,[l,y]=this.pageDimensions,[s,c]=this.pageTranslation,f=a/T,w=p/T,R=this.x*l,S=this.y*y,D=this.width*l,N=this.height*y;switch(x){case 0:return[R+f+s,y-S-w-N+c,R+f+D+s,y-S-w+c];case 90:return[R+w+s,y-S+f+c,R+w+N+s,y-S+f+D+c];case 180:return[R-f-D+s,y-S+w+c,R-f+s,y-S+w+N+c];case 270:return[R-w-N+s,y-S-f-D+c,R-w+s,y-S-f+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(a,p){let[x,T,l,y]=a,s=l-x,c=y-T;switch(this.rotation){case 0:return[x,p-y,s,c];case 90:return[x,p-T,c,s];case 180:return[l,p-T,s,c];case 270:return[l,p-y,c,s];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#f=!0}disableEditMode(){this.#f=!1}isInEditMode(){return this.#f}shouldGetKeyboardEvents(){return this.#g}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){this.div?.addEventListener("focusin",this.#o),this.div?.addEventListener("focusout",this.#c)}rotate(a){}serialize(a=!1,p=null){(0,r.unreachable)("An editor must be serializable")}static deserialize(a,p,x){let T=new this.prototype.constructor({parent:p,id:p.getNextId(),uiManager:x});T.rotation=a.rotation;let[l,y]=T.pageDimensions,[s,c,f,w]=T.getRectInCurrentCoords(a.rect,y);return T.x=s/l,T.y=c/y,T.width=f/l,T.height=w/y,T}remove(){if(this.div.removeEventListener("focusin",this.#o),this.div.removeEventListener("focusout",this.#c),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#p&&(clearTimeout(this.#p),this.#p=null),this.#F(),this.removeEditToolbar(),this.#b){for(let a of this.#b.values())clearTimeout(a);this.#b=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#v(),this.#r.classList.remove("hidden"),(0,i.bindEvents)(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(a){if(!this.isResizable||a.target!==this.div||a.key!=="Enter")return;this._uiManager.setSelected(this),this.#s={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let p=this.#r.children;if(!this.#t){this.#t=Array.from(p);let y=this.#D.bind(this),s=this.#k.bind(this);for(let c of this.#t){let f=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",y),c.addEventListener("blur",s),c.addEventListener("focus",this.#L.bind(this,f)),m._l10nPromise.get(`pdfjs-editor-resizer-label-${f}`).then((w=>c.setAttribute("aria-label",w)))}}let x=this.#t[0],T=0;for(let y of p){if(y===x)break;T++}let l=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(l!==T){if(l<T)for(let s=0;s<T-l;s++)this.#r.append(this.#r.firstChild);else if(l>T)for(let s=0;s<l-T;s++)this.#r.firstChild.before(this.#r.lastChild);let y=0;for(let s of p){let c=this.#t[y++].getAttribute("data-resizer-name");m._l10nPromise.get(`pdfjs-editor-resizer-label-${c}`).then((f=>s.setAttribute("aria-label",f)))}}this.#I(0),this.#g=!0,this.#r.firstChild.focus({focusVisible:!0}),a.preventDefault(),a.stopImmediatePropagation()}#D(a){m._resizerKeyboardManager.exec(this,a)}#k(a){this.#g&&a.relatedTarget?.parentNode!==this.#r&&this.#F()}#L(a){this.#h=this.#g?a:""}#I(a){if(this.#t)for(let p of this.#t)p.tabIndex=a}_resizeWithKeyboard(a,p){this.#g&&this.#C(this.#h,{movementX:a,movementY:p})}#F(){if(this.#g=!1,this.#I(-1),this.#s){let{savedX:a,savedY:p,savedWidth:x,savedHeight:T}=this.#s;this.#A(a,p,x,T),this.#s=null}}_stopResizingWithKeyboard(){this.#F(),this.div.focus()}select(){this.makeResizable(),this.div?.classList.add("selectedEditor"),this.#a?this.#a?.show():this.addEditToolbar().then((()=>{this.div?.classList.contains("selectedEditor")&&this.#a?.show()}))}unselect(){this.#r?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this.#a?.hide()}updateParams(a,p){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#l}set isEditing(a){this.#l=a,this.parent&&(a?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(a,p){this.#n=!0;let x=a/p,{style:T}=this.div;T.aspectRatio=x,T.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(a,p=!1){if(p){this.#b||=new Map;let{action:x}=a,T=this.#b.get(x);T&&clearTimeout(T),T=setTimeout((()=>{this._reportTelemetry(a),this.#b.delete(x),this.#b.size===0&&(this.#b=null)}),m._telemetryTimeout),this.#b.set(x,T)}else a.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:a}})}show(a=this._isVisible){this.div.classList.toggle("hidden",!a),this._isVisible=a}enable(){this.div&&(this.div.tabIndex=0),this.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}}class v extends m{constructor(a){super(a),this.annotationElementId=a.annotationElementId,this.deleted=!0}serialize(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex}}}},61:(n,t,e)=>{e.d(t,{FreeOutliner:()=>d,Outliner:()=>r});var i=e(292);class r{#t;#e=[];#i=[];constructor(u,a=0,p=0,x=!0){let T=1/0,l=-1/0,y=1/0,s=-1/0,c=10**-4;for(let{x:H,y:j,width:Y,height:it}of u){let ot=Math.floor((H-a)/c)*c,K=Math.ceil((H+Y+a)/c)*c,z=Math.floor((j-a)/c)*c,W=Math.ceil((j+it+a)/c)*c,X=[ot,z,W,!0],et=[K,z,W,!1];this.#e.push(X,et),T=Math.min(T,ot),l=Math.max(l,K),y=Math.min(y,z),s=Math.max(s,W)}let f=l-T+2*p,w=s-y+2*p,R=T-p,S=y-p,D=this.#e.at(x?-1:-2),N=[D[0],D[2]];for(let H of this.#e){let[j,Y,it]=H;H[0]=(j-R)/f,H[1]=(Y-S)/w,H[2]=(it-S)/w}this.#t={x:R,y:S,width:f,height:w,lastPoint:N}}getOutlines(){this.#e.sort(((a,p)=>a[0]-p[0]||a[1]-p[1]||a[2]-p[2]));let u=[];for(let a of this.#e)a[3]?(u.push(...this.#c(a)),this.#s(a)):(this.#o(a),u.push(...this.#c(a)));return this.#n(u)}#n(u){let a=[],p=new Set;for(let l of u){let[y,s,c]=l;a.push([y,s,l],[y,c,l])}a.sort(((l,y)=>l[1]-y[1]||l[0]-y[0]));for(let l=0,y=a.length;l<y;l+=2){let s=a[l][2],c=a[l+1][2];s.push(c),c.push(s),p.add(s),p.add(c)}let x=[],T;for(;p.size>0;){let l=p.values().next().value,[y,s,c,f,w]=l;p.delete(l);let R=y,S=s;for(T=[y,c],x.push(T);;){let D;if(p.has(f))D=f;else{if(!p.has(w))break;D=w}p.delete(D),[y,s,c,f,w]=D,R!==y&&(T.push(R,S,y,S===s?s:c),R=y),S=S===s?c:s}T.push(R,S)}return new g(x,this.#t)}#r(u){let a=this.#i,p=0,x=a.length-1;for(;p<=x;){let T=p+x>>1,l=a[T][0];if(l===u)return T;l<u?p=T+1:x=T-1}return x+1}#s([,u,a]){let p=this.#r(u);this.#i.splice(p,0,[u,a])}#o([,u,a]){let p=this.#r(u);for(let x=p;x<this.#i.length;x++){let[T,l]=this.#i[x];if(T!==u)break;if(T===u&&l===a){this.#i.splice(x,1);return}}for(let x=p-1;x>=0;x--){let[T,l]=this.#i[x];if(T!==u)break;if(T===u&&l===a){this.#i.splice(x,1);return}}}#c(u){let[a,p,x]=u,T=[[a,p,x]],l=this.#r(x);for(let y=0;y<l;y++){let[s,c]=this.#i[y];for(let f=0,w=T.length;f<w;f++){let[,R,S]=T[f];if(!(c<=R||S<=s))if(R>=s)if(S>c)T[f][1]=c;else{if(w===1)return[];T.splice(f,1),f--,w--}else T[f][2]=s,S>c&&T.push([a,c,S])}}return T}}class o{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(u,a){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof m}}class g extends o{#t;#e;constructor(u,a){super(),this.#e=u,this.#t=a}toSVGPath(){let u=[];for(let a of this.#e){let[p,x]=a;u.push(`M${p} ${x}`);for(let T=2;T<a.length;T+=2){let l=a[T],y=a[T+1];l===p?(u.push(`V${y}`),x=y):y===x&&(u.push(`H${l}`),p=l)}u.push("Z")}return u.join(" ")}serialize([u,a,p,x],T){let l=[],y=p-u,s=x-a;for(let c of this.#e){let f=new Array(c.length);for(let w=0;w<c.length;w+=2)f[w]=u+c[w]*y,f[w+1]=x-c[w+1]*s;l.push(f)}return l}get box(){return this.#t}}class d{#t;#e=[];#i;#n;#r=[];#s=new Float64Array(18);#o;#c;#a;#h;#u;#d;#l=[];static#f=8;static#g=2;static#p=d.#f+d.#g;constructor({x:u,y:a},p,x,T,l,y=0){this.#t=p,this.#d=T*x,this.#n=l,this.#s.set([NaN,NaN,NaN,NaN,u,a],6),this.#i=y,this.#h=d.#f*x,this.#a=d.#p*x,this.#u=x,this.#l.push(u,a)}get free(){return!0}isEmpty(){return isNaN(this.#s[8])}#y(){let u=this.#s.subarray(4,6),a=this.#s.subarray(16,18),[p,x,T,l]=this.#t;return[(this.#o+(u[0]-a[0])/2-p)/T,(this.#c+(u[1]-a[1])/2-x)/l,(this.#o+(a[0]-u[0])/2-p)/T,(this.#c+(a[1]-u[1])/2-x)/l]}add({x:u,y:a}){this.#o=u,this.#c=a;let[p,x,T,l]=this.#t,[y,s,c,f]=this.#s.subarray(8,12),w=u-c,R=a-f,S=Math.hypot(w,R);if(S<this.#a)return!1;let D=S-this.#h,N=D/S,H=N*w,j=N*R,Y=y,it=s;y=c,s=f,c+=H,f+=j,this.#l?.push(u,a);let ot=H/D,K=-j/D*this.#d,z=ot*this.#d;return this.#s.set(this.#s.subarray(2,8),0),this.#s.set([c+K,f+z],4),this.#s.set(this.#s.subarray(14,18),12),this.#s.set([c-K,f-z],16),isNaN(this.#s[6])?(this.#r.length===0&&(this.#s.set([y+K,s+z],2),this.#r.push(NaN,NaN,NaN,NaN,(y+K-p)/T,(s+z-x)/l),this.#s.set([y-K,s-z],14),this.#e.push(NaN,NaN,NaN,NaN,(y-K-p)/T,(s-z-x)/l)),this.#s.set([Y,it,y,s,c,f],6),!this.isEmpty()):(this.#s.set([Y,it,y,s,c,f],6),Math.abs(Math.atan2(it-s,Y-y)-Math.atan2(j,H))<Math.PI/2?([y,s,c,f]=this.#s.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((y+c)/2-p)/T,((s+f)/2-x)/l),[y,s,Y,it]=this.#s.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((Y+y)/2-p)/T,((it+s)/2-x)/l),!0):([Y,it,y,s,c,f]=this.#s.subarray(0,6),this.#r.push(((Y+5*y)/6-p)/T,((it+5*s)/6-x)/l,((5*y+c)/6-p)/T,((5*s+f)/6-x)/l,((y+c)/2-p)/T,((s+f)/2-x)/l),[c,f,y,s,Y,it]=this.#s.subarray(12,18),this.#e.push(((Y+5*y)/6-p)/T,((it+5*s)/6-x)/l,((5*y+c)/6-p)/T,((5*s+f)/6-x)/l,((y+c)/2-p)/T,((s+f)/2-x)/l),!0))}toSVGPath(){if(this.isEmpty())return"";let u=this.#r,a=this.#e,p=this.#s.subarray(4,6),x=this.#s.subarray(16,18),[T,l,y,s]=this.#t,[c,f,w,R]=this.#y();if(isNaN(this.#s[6])&&!this.isEmpty())return`M${(this.#s[2]-T)/y} ${(this.#s[3]-l)/s} L${(this.#s[4]-T)/y} ${(this.#s[5]-l)/s} L${c} ${f} L${w} ${R} L${(this.#s[16]-T)/y} ${(this.#s[17]-l)/s} L${(this.#s[14]-T)/y} ${(this.#s[15]-l)/s} Z`;let S=[];S.push(`M${u[4]} ${u[5]}`);for(let D=6;D<u.length;D+=6)isNaN(u[D])?S.push(`L${u[D+4]} ${u[D+5]}`):S.push(`C${u[D]} ${u[D+1]} ${u[D+2]} ${u[D+3]} ${u[D+4]} ${u[D+5]}`);S.push(`L${(p[0]-T)/y} ${(p[1]-l)/s} L${c} ${f} L${w} ${R} L${(x[0]-T)/y} ${(x[1]-l)/s}`);for(let D=a.length-6;D>=6;D-=6)isNaN(a[D])?S.push(`L${a[D+4]} ${a[D+5]}`):S.push(`C${a[D]} ${a[D+1]} ${a[D+2]} ${a[D+3]} ${a[D+4]} ${a[D+5]}`);return S.push(`L${a[4]} ${a[5]} Z`),S.join(" ")}getOutlines(){let u=this.#r,a=this.#e,p=this.#s,x=p.subarray(4,6),T=p.subarray(16,18),[l,y,s,c]=this.#t,f=new Float64Array((this.#l?.length??0)+2);for(let j=0,Y=f.length-2;j<Y;j+=2)f[j]=(this.#l[j]-l)/s,f[j+1]=(this.#l[j+1]-y)/c;f[f.length-2]=(this.#o-l)/s,f[f.length-1]=(this.#c-y)/c;let[w,R,S,D]=this.#y();if(isNaN(p[6])&&!this.isEmpty()){let j=new Float64Array(36);return j.set([NaN,NaN,NaN,NaN,(p[2]-l)/s,(p[3]-y)/c,NaN,NaN,NaN,NaN,(p[4]-l)/s,(p[5]-y)/c,NaN,NaN,NaN,NaN,w,R,NaN,NaN,NaN,NaN,S,D,NaN,NaN,NaN,NaN,(p[16]-l)/s,(p[17]-y)/c,NaN,NaN,NaN,NaN,(p[14]-l)/s,(p[15]-y)/c],0),new m(j,f,this.#t,this.#u,this.#i,this.#n)}let N=new Float64Array(this.#r.length+24+this.#e.length),H=u.length;for(let j=0;j<H;j+=2)isNaN(u[j])?N[j]=N[j+1]=NaN:(N[j]=u[j],N[j+1]=u[j+1]);N.set([NaN,NaN,NaN,NaN,(x[0]-l)/s,(x[1]-y)/c,NaN,NaN,NaN,NaN,w,R,NaN,NaN,NaN,NaN,S,D,NaN,NaN,NaN,NaN,(T[0]-l)/s,(T[1]-y)/c],H),H+=24;for(let j=a.length-6;j>=6;j-=6)for(let Y=0;Y<6;Y+=2)isNaN(a[j+Y])?(N[H]=N[H+1]=NaN,H+=2):(N[H]=a[j+Y],N[H+1]=a[j+Y+1],H+=2);return N.set([NaN,NaN,NaN,NaN,a[4],a[5]],H),new m(N,f,this.#t,this.#u,this.#i,this.#n)}}class m extends o{#t;#e=null;#i;#n;#r;#s;#o;constructor(u,a,p,x,T,l){super(),this.#o=u,this.#r=a,this.#t=p,this.#s=x,this.#i=T,this.#n=l,this.#h(l);let{x:y,y:s,width:c,height:f}=this.#e;for(let w=0,R=u.length;w<R;w+=2)u[w]=(u[w]-y)/c,u[w+1]=(u[w+1]-s)/f;for(let w=0,R=a.length;w<R;w+=2)a[w]=(a[w]-y)/c,a[w+1]=(a[w+1]-s)/f}toSVGPath(){let u=[`M${this.#o[4]} ${this.#o[5]}`];for(let a=6,p=this.#o.length;a<p;a+=6)isNaN(this.#o[a])?u.push(`L${this.#o[a+4]} ${this.#o[a+5]}`):u.push(`C${this.#o[a]} ${this.#o[a+1]} ${this.#o[a+2]} ${this.#o[a+3]} ${this.#o[a+4]} ${this.#o[a+5]}`);return u.push("Z"),u.join(" ")}serialize([u,a,p,x],T){let l=p-u,y=x-a,s,c;switch(T){case 0:s=this.#c(this.#o,u,x,l,-y),c=this.#c(this.#r,u,x,l,-y);break;case 90:s=this.#a(this.#o,u,a,l,y),c=this.#a(this.#r,u,a,l,y);break;case 180:s=this.#c(this.#o,p,a,-l,y),c=this.#c(this.#r,p,a,-l,y);break;case 270:s=this.#a(this.#o,p,x,-l,-y),c=this.#a(this.#r,p,x,-l,-y)}return{outline:Array.from(s),points:[Array.from(c)]}}#c(u,a,p,x,T){let l=new Float64Array(u.length);for(let y=0,s=u.length;y<s;y+=2)l[y]=a+u[y]*x,l[y+1]=p+u[y+1]*T;return l}#a(u,a,p,x,T){let l=new Float64Array(u.length);for(let y=0,s=u.length;y<s;y+=2)l[y]=a+u[y+1]*x,l[y+1]=p+u[y]*T;return l}#h(u){let a=this.#o,p=a[4],x=a[5],T=p,l=x,y=p,s=x,c=p,f=x,w=u?Math.max:Math.min;for(let H=6,j=a.length;H<j;H+=6){if(isNaN(a[H]))T=Math.min(T,a[H+4]),l=Math.min(l,a[H+5]),y=Math.max(y,a[H+4]),s=Math.max(s,a[H+5]),f<a[H+5]?(c=a[H+4],f=a[H+5]):f===a[H+5]&&(c=w(c,a[H+4]));else{let Y=i.Util.bezierBoundingBox(p,x,...a.slice(H,H+6));T=Math.min(T,Y[0]),l=Math.min(l,Y[1]),y=Math.max(y,Y[2]),s=Math.max(s,Y[3]),f<Y[3]?(c=Y[2],f=Y[3]):f===Y[3]&&(c=w(c,Y[2]))}p=a[H+4],x=a[H+5]}let R=T-this.#i,S=l-this.#i,D=y-T+2*this.#i,N=s-l+2*this.#i;this.#e={x:R,y:S,width:D,height:N,lastPoint:[c,f]}}get box(){return this.#e}getNewOutline(u,a){let{x:p,y:x,width:T,height:l}=this.#e,[y,s,c,f]=this.#t,w=T*c,R=l*f,S=p*c+y,D=x*f+s,N=new d({x:this.#r[0]*w+S,y:this.#r[1]*R+D},this.#t,this.#s,u,this.#n,a??this.#i);for(let H=2;H<this.#r.length;H+=2)N.add({x:this.#r[H]*w+S,y:this.#r[H+1]*R+D});return N.getOutlines()}}},362:(n,t,e)=>{e.d(t,{EditorToolbar:()=>r,HighlightToolbar:()=>o});var i=e(419);class r{#t=null;#e=null;#i;#n=null;constructor(d){this.#i=d}render(){let d=this.#t=document.createElement("div");d.className="editToolbar",d.setAttribute("role","toolbar"),d.addEventListener("contextmenu",i.noContextMenu),d.addEventListener("pointerdown",r.#r);let m=this.#n=document.createElement("div");m.className="buttons",d.append(m);let v=this.#i.toolbarPosition;if(v){let{style:u}=d,a=this.#i._uiManager.direction==="ltr"?1-v[0]:v[0];u.insetInlineEnd=100*a+"%",u.top=`calc(${100*v[1]}% + var(--editor-toolbar-vert-offset))`}return this.#a(),d}static#r(d){d.stopPropagation()}#s(d){this.#i._focusEventsAllowed=!1,d.preventDefault(),d.stopPropagation()}#o(d){this.#i._focusEventsAllowed=!0,d.preventDefault(),d.stopPropagation()}#c(d){d.addEventListener("focusin",this.#s.bind(this),{capture:!0}),d.addEventListener("focusout",this.#o.bind(this),{capture:!0}),d.addEventListener("contextmenu",i.noContextMenu)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden")}#a(){let d=document.createElement("button");d.className="delete",d.tabIndex=0,d.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#i.editorType}-button`),this.#c(d),d.addEventListener("click",(m=>{this.#i._uiManager.delete()})),this.#n.append(d)}get#h(){let d=document.createElement("div");return d.className="divider",d}addAltTextButton(d){this.#c(d),this.#n.prepend(d,this.#h)}addColorPicker(d){this.#e=d;let m=d.renderButton();this.#c(m),this.#n.prepend(m,this.#h)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class o{#t=null;#e=null;#i;constructor(d){this.#i=d}#n(){let d=this.#e=document.createElement("div");d.className="editToolbar",d.setAttribute("role","toolbar"),d.addEventListener("contextmenu",i.noContextMenu);let m=this.#t=document.createElement("div");return m.className="buttons",d.append(m),this.#s(),d}#r(d,m){let v=0,u=0;for(let a of d){let p=a.y+a.height;if(p<v)continue;let x=a.x+(m?a.width:0);p>v?(u=x,v=p):m?x>u&&(u=x):x<u&&(u=x)}return[m?1-u:u,v]}show(d,m,v){let[u,a]=this.#r(m,v),{style:p}=this.#e||=this.#n();d.append(this.#e),p.insetInlineEnd=100*u+"%",p.top=`calc(${100*a}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#s(){let d=document.createElement("button");d.className="highlightButton",d.tabIndex=0,d.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");let m=document.createElement("span");d.append(m),m.className="visuallyHidden",m.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label"),d.addEventListener("contextmenu",i.noContextMenu),d.addEventListener("click",(()=>{this.#i.highlightSelection("floating_button")})),this.#t.append(d)}}},830:(n,t,e)=>{e.d(t,{AnnotationEditorUIManager:()=>x,ColorManager:()=>p,KeyboardManager:()=>a,bindEvents:()=>g,opacityToHex:()=>d});var i=e(292),r=e(419),o=e(362);function g(T,l,y){for(let s of y)l.addEventListener(s,T[s].bind(T))}function d(T){return Math.round(Math.min(255,Math.max(1,255*T))).toString(16).padStart(2,"0")}class m{#t=0;constructor(){}get id(){return`${i.AnnotationEditorPrefix}${this.#t++}`}}class v{#t=(0,i.getUuid)();#e=0;#i=null;static get _isSVGFittingCanvas(){let l=new OffscreenCanvas(1,3).getContext("2d"),y=new Image;y.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';let s=y.decode().then((()=>(l.drawImage(y,0,0,1,1,0,0,1,3),new Uint32Array(l.getImageData(0,0,1,1).data.buffer)[0]===0)));return(0,i.shadow)(this,"_isSVGFittingCanvas",s)}async#n(l,y){this.#i||=new Map;let s=this.#i.get(l);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let c;if(typeof y=="string"?(s.url=y,c=await(0,r.fetchData)(y,"blob")):c=s.file=y,c.type==="image/svg+xml"){let f=v._isSVGFittingCanvas,w=new FileReader,R=new Image,S=new Promise(((D,N)=>{R.onload=()=>{s.bitmap=R,s.isSvg=!0,D()},w.onload=async()=>{let H=s.svgUrl=w.result;R.src=await f?`${H}#svgView(preserveAspectRatio(none))`:H},R.onerror=w.onerror=N}));w.readAsDataURL(c),await S}else s.bitmap=await createImageBitmap(c);s.refCounter=1}catch(c){console.error(c),s=null}return this.#i.set(l,s),s&&this.#i.set(s.id,s),s}async getFromFile(l){let{lastModified:y,name:s,size:c,type:f}=l;return this.#n(`${y}_${s}_${c}_${f}`,l)}async getFromUrl(l){return this.#n(l,l)}async getFromId(l){this.#i||=new Map;let y=this.#i.get(l);return y?y.bitmap?(y.refCounter+=1,y):y.file?this.getFromFile(y.file):this.getFromUrl(y.url):null}getSvgUrl(l){let y=this.#i.get(l);return y?.isSvg?y.svgUrl:null}deleteId(l){this.#i||=new Map;let y=this.#i.get(l);y&&(y.refCounter-=1,y.refCounter===0&&(y.bitmap=null))}isValidId(l){return l.startsWith(`image_${this.#t}_`)}}class u{#t=[];#e=!1;#i;#n=-1;constructor(l=128){this.#i=l}add({cmd:l,undo:y,post:s,mustExec:c,type:f=NaN,overwriteIfSameType:w=!1,keepUndo:R=!1}){if(c&&l(),this.#e)return;let S={cmd:l,undo:y,post:s,type:f};if(this.#n===-1){this.#t.length>0&&(this.#t.length=0),this.#n=0,this.#t.push(S);return}if(w&&this.#t[this.#n].type===f){R&&(S.undo=this.#t[this.#n].undo),this.#t[this.#n]=S;return}let D=this.#n+1;D===this.#i?this.#t.splice(0,1):(this.#n=D,D<this.#t.length&&this.#t.splice(D)),this.#t.push(S)}undo(){if(this.#n===-1)return;this.#e=!0;let{undo:l,post:y}=this.#t[this.#n];l(),y?.(),this.#e=!1,this.#n-=1}redo(){if(this.#n<this.#t.length-1){this.#n+=1,this.#e=!0;let{cmd:l,post:y}=this.#t[this.#n];l(),y?.(),this.#e=!1}}hasSomethingToUndo(){return this.#n!==-1}hasSomethingToRedo(){return this.#n<this.#t.length-1}destroy(){this.#t=null}}class a{constructor(l){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:y}=i.FeatureTest.platform;for(let[s,c,f={}]of l)for(let w of s){let R=w.startsWith("mac+");y&&R?(this.callbacks.set(w.slice(4),{callback:c,options:f}),this.allKeys.add(w.split("+").at(-1))):!y&&!R&&(this.callbacks.set(w,{callback:c,options:f}),this.allKeys.add(w.split("+").at(-1)))}}#t(l){l.altKey&&this.buffer.push("alt"),l.ctrlKey&&this.buffer.push("ctrl"),l.metaKey&&this.buffer.push("meta"),l.shiftKey&&this.buffer.push("shift"),this.buffer.push(l.key);let y=this.buffer.join("+");return this.buffer.length=0,y}exec(l,y){if(!this.allKeys.has(y.key))return;let s=this.callbacks.get(this.#t(y));if(!s)return;let{callback:c,options:{bubbles:f=!1,args:w=[],checker:R=null}}=s;(!R||R(l,y))&&(c.bind(l,...w,y)(),f||(y.stopPropagation(),y.preventDefault()))}}class p{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let l=new Map([["CanvasText",null],["Canvas",null]]);return(0,r.getColorValues)(l),(0,i.shadow)(this,"_colors",l)}convert(l){let y=(0,r.getRGB)(l);if(!window.matchMedia("(forced-colors: active)").matches)return y;for(let[s,c]of this._colors)if(c.every(((f,w)=>f===y[w])))return p._colorsMapping.get(s);return y}getHexCode(l){let y=this._colors.get(l);return y?i.Util.makeHexColor(...y):l}}class x{#t=null;#e=new Map;#i=new Map;#n=null;#r=null;#s=new u;#o=0;#c=new Set;#a=null;#h=null;#u=new Set;#d=!1;#l=null;#f=null;#g=null;#p=!1;#y=null;#m=new m;#b=!1;#S=!1;#_=null;#M=null;#w=null;#x=i.AnnotationEditorType.NONE;#v=new Set;#E=null;#A=null;#C=null;#T=this.blur.bind(this);#P=this.focus.bind(this);#D=this.copy.bind(this);#k=this.cut.bind(this);#L=this.paste.bind(this);#I=this.keydown.bind(this);#F=this.keyup.bind(this);#O=this.onEditingAction.bind(this);#V=this.onPageChanging.bind(this);#W=this.onScaleChanging.bind(this);#j=this.#nt.bind(this);#$=this.onRotationChanging.bind(this);#N={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#z=[0,0];#B=null;#H=null;#K=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let l=x.prototype,y=w=>w.#H.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&w.hasSomethingToControl(),s=(w,{target:R})=>{if(R instanceof HTMLInputElement){let{type:S}=R;return S!=="text"&&S!=="number"}return!0},c=this.TRANSLATE_SMALL,f=this.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new a([[["ctrl+a","mac+meta+a"],l.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],l.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],l.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],l.delete,{checker:s}],[["Enter","mac+Enter"],l.addNewEditorFromKeyboard,{checker:(w,{target:R})=>!(R instanceof HTMLButtonElement)&&w.#H.contains(R)&&!w.isEnterHandled}],[[" ","mac+ "],l.addNewEditorFromKeyboard,{checker:(w,{target:R})=>!(R instanceof HTMLButtonElement)&&w.#H.contains(document.activeElement)}],[["Escape","mac+Escape"],l.unselectAll],[["ArrowLeft","mac+ArrowLeft"],l.translateSelectedEditors,{args:[-c,0],checker:y}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],l.translateSelectedEditors,{args:[-f,0],checker:y}],[["ArrowRight","mac+ArrowRight"],l.translateSelectedEditors,{args:[c,0],checker:y}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],l.translateSelectedEditors,{args:[f,0],checker:y}],[["ArrowUp","mac+ArrowUp"],l.translateSelectedEditors,{args:[0,-c],checker:y}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],l.translateSelectedEditors,{args:[0,-f],checker:y}],[["ArrowDown","mac+ArrowDown"],l.translateSelectedEditors,{args:[0,c],checker:y}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],l.translateSelectedEditors,{args:[0,f],checker:y}]]))}constructor(l,y,s,c,f,w,R,S,D){this.#H=l,this.#K=y,this.#n=s,this._eventBus=c,this._eventBus._on("editingaction",this.#O),this._eventBus._on("pagechanging",this.#V),this._eventBus._on("scalechanging",this.#W),this._eventBus._on("rotationchanging",this.#$),this.#rt(),this.#J(),this.#r=f.annotationStorage,this.#l=f.filterFactory,this.#A=w,this.#g=R||null,this.#d=S,this.#w=D||null,this.viewParameters={realScale:r.PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#Q(),this.#Y(),this._eventBus._off("editingaction",this.#O),this._eventBus._off("pagechanging",this.#V),this._eventBus._off("scalechanging",this.#W),this._eventBus._off("rotationchanging",this.#$);for(let l of this.#i.values())l.destroy();this.#i.clear(),this.#e.clear(),this.#u.clear(),this.#t=null,this.#v.clear(),this.#s.destroy(),this.#n?.destroy(),this.#y?.hide(),this.#y=null,this.#f&&(clearTimeout(this.#f),this.#f=null),this.#B&&(clearTimeout(this.#B),this.#B=null),this.#at()}async mlGuess(l){return this.#w?.guess(l)||null}get hasMLManager(){return!!this.#w}get hcmFilter(){return(0,i.shadow)(this,"hcmFilter",this.#A?this.#l.addHCMFilter(this.#A.foreground,this.#A.background):"none")}get direction(){return(0,i.shadow)(this,"direction",getComputedStyle(this.#H).direction)}get highlightColors(){return(0,i.shadow)(this,"highlightColors",this.#g?new Map(this.#g.split(",").map((l=>l.split("=").map((y=>y.trim()))))):null)}get highlightColorNames(){return(0,i.shadow)(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(l=>l.reverse()))):null)}setMainHighlightColorPicker(l){this.#M=l}editAltText(l){this.#n?.editAltText(this,l)}onPageChanging({pageNumber:l}){this.#o=l-1}focusMainContainer(){this.#H.focus()}findParent(l,y){for(let s of this.#i.values()){let{x:c,y:f,width:w,height:R}=s.div.getBoundingClientRect();if(l>=c&&l<=c+w&&y>=f&&y<=f+R)return s}return null}disableUserSelect(l=!1){this.#K.classList.toggle("noUserSelect",l)}addShouldRescale(l){this.#u.add(l)}removeShouldRescale(l){this.#u.delete(l)}onScaleChanging({scale:l}){this.commitOrRemove(),this.viewParameters.realScale=l*r.PixelsPerInch.PDF_TO_CSS_UNITS;for(let y of this.#u)y.onScaleChanging()}onRotationChanging({pagesRotation:l}){this.commitOrRemove(),this.viewParameters.rotation=l}#q({anchorNode:l}){return l.nodeType===Node.TEXT_NODE?l.parentElement:l}highlightSelection(l=""){let y=document.getSelection();if(!y||y.isCollapsed)return;let{anchorNode:s,anchorOffset:c,focusNode:f,focusOffset:w}=y,R=y.toString(),S=this.#q(y).closest(".textLayer"),D=this.getSelectionBoxes(S);if(D){y.empty(),this.#x===i.AnnotationEditorType.NONE&&(this._eventBus.dispatch("showannotationeditorui",{source:this,mode:i.AnnotationEditorType.HIGHLIGHT}),this.showAllEditors("highlight",!0,!0));for(let N of this.#i.values())if(N.hasTextLayer(S)){N.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:l,boxes:D,anchorNode:s,anchorOffset:c,focusNode:f,focusOffset:w,text:R});break}}}#st(){let l=document.getSelection();if(!l||l.isCollapsed)return;let y=this.#q(l).closest(".textLayer"),s=this.getSelectionBoxes(y);s&&(this.#y||=new o.HighlightToolbar(this),this.#y.show(y,s,this.direction==="ltr"))}addToAnnotationStorage(l){l.isEmpty()||!this.#r||this.#r.has(l.id)||this.#r.setValue(l.id,l)}#nt(){let l=document.getSelection();if(!l||l.isCollapsed){this.#E&&(this.#y?.hide(),this.#E=null,this.#R({hasSelectedText:!1}));return}let{anchorNode:y}=l;if(y!==this.#E)if(this.#q(l).closest(".textLayer")){if(this.#y?.hide(),this.#E=y,this.#R({hasSelectedText:!0}),(this.#x===i.AnnotationEditorType.HIGHLIGHT||this.#x===i.AnnotationEditorType.NONE)&&(this.#x===i.AnnotationEditorType.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#p=this.isShiftKeyDown,!this.isShiftKeyDown)){let s=c=>{(c.type!=="pointerup"||c.button===0)&&(window.removeEventListener("pointerup",s),window.removeEventListener("blur",s),c.type==="pointerup"&&this.#X("main_toolbar"))};window.addEventListener("pointerup",s),window.addEventListener("blur",s)}}else this.#E&&(this.#y?.hide(),this.#E=null,this.#R({hasSelectedText:!1}))}#X(l=""){this.#x===i.AnnotationEditorType.HIGHLIGHT?this.highlightSelection(l):this.#d&&this.#st()}#rt(){document.addEventListener("selectionchange",this.#j)}#at(){document.removeEventListener("selectionchange",this.#j)}#ot(){window.addEventListener("focus",this.#P),window.addEventListener("blur",this.#T)}#Y(){window.removeEventListener("focus",this.#P),window.removeEventListener("blur",this.#T)}blur(){if(this.isShiftKeyDown=!1,this.#p&&(this.#p=!1,this.#X("main_toolbar")),!this.hasSelection)return;let{activeElement:l}=document;for(let y of this.#v)if(y.div.contains(l)){this.#_=[y,l],y._focusEventsAllowed=!1;break}}focus(){if(!this.#_)return;let[l,y]=this.#_;this.#_=null,y.addEventListener("focusin",(()=>{l._focusEventsAllowed=!0}),{once:!0}),y.focus()}#J(){window.addEventListener("keydown",this.#I),window.addEventListener("keyup",this.#F)}#Q(){window.removeEventListener("keydown",this.#I),window.removeEventListener("keyup",this.#F)}#Z(){document.addEventListener("copy",this.#D),document.addEventListener("cut",this.#k),document.addEventListener("paste",this.#L)}#tt(){document.removeEventListener("copy",this.#D),document.removeEventListener("cut",this.#k),document.removeEventListener("paste",this.#L)}addEditListeners(){this.#J(),this.#Z()}removeEditListeners(){this.#Q(),this.#tt()}copy(l){if(l.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let y=[];for(let s of this.#v){let c=s.serialize(!0);c&&y.push(c)}y.length!==0&&l.clipboardData.setData("application/pdfjs",JSON.stringify(y))}cut(l){this.copy(l),this.delete()}paste(l){l.preventDefault();let{clipboardData:y}=l;for(let f of y.items)for(let w of this.#h)if(w.isHandlingMimeForPasting(f.type)){w.paste(f,this.currentLayer);return}let s=y.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(f){(0,i.warn)(`paste: "${f.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();let c=this.currentLayer;try{let f=[];for(let S of s){let D=c.deserialize(S);if(!D)return;f.push(D)}let w=()=>{for(let S of f)this.#et(S);this.#it(f)},R=()=>{for(let S of f)S.remove()};this.addCommands({cmd:w,undo:R,mustExec:!0})}catch(f){(0,i.warn)(`paste: "${f.message}".`)}}keydown(l){this.isShiftKeyDown||l.key!=="Shift"||(this.isShiftKeyDown=!0),this.#x===i.AnnotationEditorType.NONE||this.isEditorHandlingKeyboard||x._keyboardManager.exec(this,l)}keyup(l){this.isShiftKeyDown&&l.key==="Shift"&&(this.isShiftKeyDown=!1,this.#p&&(this.#p=!1,this.#X("main_toolbar")))}onEditingAction({name:l}){switch(l){case"undo":case"redo":case"delete":case"selectAll":this[l]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#R(l){Object.entries(l).some((([y,s])=>this.#N[y]!==s))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#N,l)}),this.#x===i.AnnotationEditorType.HIGHLIGHT&&l.hasSelectedEditor===!1&&this.#U([[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]]))}#U(l){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:l})}setEditingState(l){l?(this.#ot(),this.#Z(),this.#R({isEditing:this.#x!==i.AnnotationEditorType.NONE,isEmpty:this.#G(),hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:this.#s.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Y(),this.#tt(),this.#R({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(l){if(!this.#h){this.#h=l;for(let y of this.#h)this.#U(y.defaultPropertiesToUpdate)}}getId(){return this.#m.id}get currentLayer(){return this.#i.get(this.#o)}getLayer(l){return this.#i.get(l)}get currentPageIndex(){return this.#o}addLayer(l){this.#i.set(l.pageIndex,l),this.#b?l.enable():l.disable()}removeLayer(l){this.#i.delete(l.pageIndex)}updateMode(l,y=null,s=!1){if(this.#x!==l)if(this.#x=l,l!==i.AnnotationEditorType.NONE){this.setEditingState(!0),this.#ct(),this.unselectAll();for(let c of this.#i.values())c.updateMode(l);if(y||!s){if(y){for(let c of this.#e.values())if(c.annotationElementId===y){this.setSelected(c),c.enterInEditMode();break}}}else this.addNewEditorFromKeyboard()}else this.setEditingState(!1),this.#lt()}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(l){l!==this.#x&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:l})}updateParams(l,y){if(this.#h){switch(l){case i.AnnotationEditorParamsType.CREATE:this.currentLayer.addNewEditor();return;case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:this.#M?.updateColor(y);break;case i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#C||=new Map).set(l,y),this.showAllEditors("highlight",y)}for(let s of this.#v)s.updateParams(l,y);for(let s of this.#h)s.updateDefaultParams(l,y)}}showAllEditors(l,y,s=!1){for(let c of this.#e.values())c.editorType===l&&c.show(y);(this.#C?.get(i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==y&&this.#U([[i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,y]])}enableWaiting(l=!1){if(this.#S!==l){this.#S=l;for(let y of this.#i.values())l?y.disableClick():y.enableClick(),y.div.classList.toggle("waiting",l)}}#ct(){if(!this.#b){this.#b=!0;for(let l of this.#i.values())l.enable();for(let l of this.#e.values())l.enable()}}#lt(){if(this.unselectAll(),this.#b){this.#b=!1;for(let l of this.#i.values())l.disable();for(let l of this.#e.values())l.disable()}}getEditors(l){let y=[];for(let s of this.#e.values())s.pageIndex===l&&y.push(s);return y}getEditor(l){return this.#e.get(l)}addEditor(l){this.#e.set(l.id,l)}removeEditor(l){l.div.contains(document.activeElement)&&(this.#f&&clearTimeout(this.#f),this.#f=setTimeout((()=>{this.focusMainContainer(),this.#f=null}),0)),this.#e.delete(l.id),this.unselect(l),l.annotationElementId&&this.#c.has(l.annotationElementId)||this.#r?.remove(l.id)}addDeletedAnnotationElement(l){this.#c.add(l.annotationElementId),l.deleted=!0}isDeletedAnnotationElement(l){return this.#c.has(l)}removeDeletedAnnotationElement(l){this.#c.delete(l.annotationElementId),l.deleted=!1}#et(l){let y=this.#i.get(l.pageIndex);y?y.addOrRebuild(l):(this.addEditor(l),this.addToAnnotationStorage(l))}setActiveEditor(l){this.#t!==l&&(this.#t=l,l&&this.#U(l.propertiesToUpdate))}get#ht(){let l=null;for(l of this.#v);return l}updateUI(l){this.#ht===l&&this.#U(l.propertiesToUpdate)}toggleSelected(l){this.#v.has(l)?(this.#v.delete(l),l.unselect(),this.#R({hasSelectedEditor:this.hasSelection})):(this.#v.add(l),l.select(),this.#U(l.propertiesToUpdate),this.#R({hasSelectedEditor:!0}))}setSelected(l){for(let y of this.#v)y!==l&&y.unselect();this.#v.clear(),this.#v.add(l),l.select(),this.#U(l.propertiesToUpdate),this.#R({hasSelectedEditor:!0})}isSelected(l){return this.#v.has(l)}get firstSelectedEditor(){return this.#v.values().next().value}unselect(l){l.unselect(),this.#v.delete(l),this.#R({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#v.size!==0}get isEnterHandled(){return this.#v.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#s.undo(),this.#R({hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#G()})}redo(){this.#s.redo(),this.#R({hasSomethingToUndo:!0,hasSomethingToRedo:this.#s.hasSomethingToRedo(),isEmpty:this.#G()})}addCommands(l){this.#s.add(l),this.#R({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#G()})}#G(){if(this.#e.size===0)return!0;if(this.#e.size===1)for(let l of this.#e.values())return l.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;let l=[...this.#v];this.addCommands({cmd:()=>{for(let y of l)y.remove()},undo:()=>{for(let y of l)this.#et(y)},mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#it(l){for(let y of this.#v)y.unselect();this.#v.clear();for(let y of l)y.isEmpty()||(this.#v.add(y),y.select());this.#R({hasSelectedEditor:this.hasSelection})}selectAll(){for(let l of this.#v)l.commit();this.#it(this.#e.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#x!==i.AnnotationEditorType.NONE))&&this.hasSelection){for(let l of this.#v)l.unselect();this.#v.clear(),this.#R({hasSelectedEditor:!1})}}translateSelectedEditors(l,y,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#z[0]+=l,this.#z[1]+=y;let[c,f]=this.#z,w=[...this.#v];this.#B&&clearTimeout(this.#B),this.#B=setTimeout((()=>{this.#B=null,this.#z[0]=this.#z[1]=0,this.addCommands({cmd:()=>{for(let R of w)this.#e.has(R.id)&&R.translateInPage(c,f)},undo:()=>{for(let R of w)this.#e.has(R.id)&&R.translateInPage(-c,-f)},mustExec:!1})}),1e3);for(let R of w)R.translateInPage(l,y)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#a=new Map;for(let l of this.#v)this.#a.set(l,{savedX:l.x,savedY:l.y,savedPageIndex:l.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#a)return!1;this.disableUserSelect(!1);let l=this.#a;this.#a=null;let y=!1;for(let[{x:c,y:f,pageIndex:w},R]of l)R.newX=c,R.newY=f,R.newPageIndex=w,y||=c!==R.savedX||f!==R.savedY||w!==R.savedPageIndex;if(!y)return!1;let s=(c,f,w,R)=>{if(this.#e.has(c.id)){let S=this.#i.get(R);S?c._setParentAndPosition(S,f,w):(c.pageIndex=R,c.x=f,c.y=w)}};return this.addCommands({cmd:()=>{for(let[c,{newX:f,newY:w,newPageIndex:R}]of l)s(c,f,w,R)},undo:()=>{for(let[c,{savedX:f,savedY:w,savedPageIndex:R}]of l)s(c,f,w,R)},mustExec:!0}),!0}dragSelectedEditors(l,y){if(this.#a)for(let s of this.#a.keys())s.drag(l,y)}rebuild(l){if(l.parent===null){let y=this.getLayer(l.pageIndex);y?(y.changeParent(l),y.addOrRebuild(l)):(this.addEditor(l),this.addToAnnotationStorage(l),l.rebuild())}else l.parent.addOrRebuild(l)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#v.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(l){return this.#t===l}getActive(){return this.#t}getMode(){return this.#x}get imageManager(){return(0,i.shadow)(this,"imageManager",new v)}getSelectionBoxes(l){if(!l)return null;let y=document.getSelection();for(let D=0,N=y.rangeCount;D<N;D++)if(!l.contains(y.getRangeAt(D).commonAncestorContainer))return null;let{x:s,y:c,width:f,height:w}=l.getBoundingClientRect(),R;switch(l.getAttribute("data-main-rotation")){case"90":R=(D,N,H,j)=>({x:(N-c)/w,y:1-(D+H-s)/f,width:j/w,height:H/f});break;case"180":R=(D,N,H,j)=>({x:1-(D+H-s)/f,y:1-(N+j-c)/w,width:H/f,height:j/w});break;case"270":R=(D,N,H,j)=>({x:1-(N+j-c)/w,y:(D-s)/f,width:j/w,height:H/f});break;default:R=(D,N,H,j)=>({x:(D-s)/f,y:(N-c)/w,width:H/f,height:j/w})}let S=[];for(let D=0,N=y.rangeCount;D<N;D++){let H=y.getRangeAt(D);if(!H.collapsed)for(let{x:j,y:Y,width:it,height:ot}of H.getClientRects())it!==0&&ot!==0&&S.push(R(j,Y,it,ot))}return S.length===0?null:S}}},94:(n,t,e)=>{e.d(t,{PDFFetchStream:()=>m});var i=e(292),r=e(490);function o(a,p,x){return{method:"GET",headers:a,signal:x.signal,mode:"cors",credentials:p?"include":"same-origin",redirect:"follow"}}function g(a){let p=new Headers;for(let x in a){let T=a[x];T!==void 0&&p.append(x,T)}return p}function d(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:((0,i.warn)(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class m{constructor(p){this.source=p,this.isHttp=/^https?:/i.test(p.url),this.httpHeaders=this.isHttp&&p.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new v(this),this._fullRequestReader}getRangeReader(p,x){if(x<=this._progressiveDataLength)return null;let T=new u(this,p,x);return this._rangeRequestReaders.push(T),T}cancelAllRequests(p){this._fullRequestReader?.cancel(p);for(let x of this._rangeRequestReaders.slice(0))x.cancel(p)}}class v{constructor(p){this._stream=p,this._reader=null,this._loaded=0,this._filename=null;let x=p.source;this._withCredentials=x.withCredentials||!1,this._contentLength=x.length,this._headersCapability=Promise.withResolvers(),this._disableRange=x.disableRange||!1,this._rangeChunkSize=x.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!x.disableStream,this._isRangeSupported=!x.disableRange,this._headers=g(this._stream.httpHeaders);let T=x.url;fetch(T,o(this._headers,this._withCredentials,this._abortController)).then((l=>{if(!(0,r.validateResponseStatus)(l.status))throw(0,r.createResponseStatusError)(l.status,T);this._reader=l.body.getReader(),this._headersCapability.resolve();let y=f=>l.headers.get(f),{allowRangeRequests:s,suggestedLength:c}=(0,r.validateRangeRequestCapabilities)({getResponseHeader:y,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=c||this._contentLength,this._filename=(0,r.extractFilenameFromHeader)(y),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new i.AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:p,done:x}=await this._reader.read();return x?{value:p,done:x}:(this._loaded+=p.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:d(p),done:!1})}cancel(p){this._reader?.cancel(p),this._abortController.abort()}}class u{constructor(p,x,T){this._stream=p,this._reader=null,this._loaded=0;let l=p.source;this._withCredentials=l.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!l.disableStream,this._abortController=new AbortController,this._headers=g(this._stream.httpHeaders),this._headers.append("Range",`bytes=${x}-${T-1}`);let y=l.url;fetch(y,o(this._headers,this._withCredentials,this._abortController)).then((s=>{if(!(0,r.validateResponseStatus)(s.status))throw(0,r.createResponseStatusError)(s.status,y);this._readCapability.resolve(),this._reader=s.body.getReader()})).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:p,done:x}=await this._reader.read();return x?{value:p,done:x}:(this._loaded+=p.byteLength,this.onProgress?.({loaded:this._loaded}),{value:d(p),done:!1})}cancel(p){this._reader?.cancel(p),this._abortController.abort()}}},10:(n,t,e)=>{e.d(t,{FontFaceObject:()=>o,FontLoader:()=>r});var i=e(292);class r{#t=new Set;constructor({ownerDocument:d=globalThis.document,styleElement:m=null}){this._document=d,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(d){this.nativeFontFaces.add(d),this._document.fonts.add(d)}removeNativeFontFace(d){this.nativeFontFaces.delete(d),this._document.fonts.delete(d)}insertRule(d){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));let m=this.styleElement.sheet;m.insertRule(d,m.cssRules.length)}clear(){for(let d of this.nativeFontFaces)this._document.fonts.delete(d);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:d,_inspectFont:m}){if(d&&!this.#t.has(d.loadedName))if((0,i.assert)(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:v,src:u,style:a}=d,p=new FontFace(v,u,a);this.addNativeFontFace(p);try{await p.load(),this.#t.add(v),m?.(d)}catch{(0,i.warn)(`Cannot load system font: ${d.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(p)}}else(0,i.unreachable)("Not implemented: loadSystemFont without the Font Loading API.")}async bind(d){if(d.attached||d.missingFile&&!d.systemFontInfo)return;if(d.attached=!0,d.systemFontInfo){await this.loadSystemFont(d);return}if(this.isFontLoadingAPISupported){let v=d.createNativeFontFace();if(v){this.addNativeFontFace(v);try{await v.loaded}catch(u){throw(0,i.warn)(`Failed to load font '${v.family}': '${u}'.`),d.disableFontFace=!0,u}}return}let m=d.createFontFaceRule();if(m){if(this.insertRule(m),this.isSyncFontLoadingSupported)return;await new Promise((v=>{let u=this._queueLoadingCallback(v);this._prepareFontLoadEvent(d,u)}))}}get isFontLoadingAPISupported(){let d=!!this._document?.fonts;return(0,i.shadow)(this,"isFontLoadingAPISupported",d)}get isSyncFontLoadingSupported(){let d=!1;return(i.isNodeJS||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(d=!0),(0,i.shadow)(this,"isSyncFontLoadingSupported",d)}_queueLoadingCallback(d){let{loadingRequests:m}=this,v={done:!1,complete:function(){for((0,i.assert)(!v.done,"completeRequest() cannot be called twice."),v.done=!0;m.length>0&&m[0].done;){let a=m.shift();setTimeout(a.callback,0)}},callback:d};return m.push(v),v}get _loadTestFont(){let d=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return(0,i.shadow)(this,"_loadTestFont",d)}_prepareFontLoadEvent(d,m){function v(S,D){return S.charCodeAt(D)<<24|S.charCodeAt(D+1)<<16|S.charCodeAt(D+2)<<8|255&S.charCodeAt(D+3)}function u(S,D,N,H){return S.substring(0,D)+H+S.substring(D+N)}let a,p,x=this._document.createElement("canvas");x.width=1,x.height=1;let T=x.getContext("2d"),l=0,y=`lt${Date.now()}${this.loadTestFontId++}`,s=this._loadTestFont;s=u(s,976,y.length,y);let c=1482184792,f=v(s,16);for(a=0,p=y.length-3;a<p;a+=4)f=f-c+v(y,a)|0;a<y.length&&(f=f-c+v(y+"XXX",a)|0),s=u(s,16,4,(0,i.string32)(f));let w=`@font-face {font-family:"${y}";src:${`url(data:font/opentype;base64,${btoa(s)});`}}`;this.insertRule(w);let R=this._document.createElement("div");R.style.visibility="hidden",R.style.width=R.style.height="10px",R.style.position="absolute",R.style.top=R.style.left="0px";for(let S of[d.loadedName,y]){let D=this._document.createElement("span");D.textContent="Hi",D.style.fontFamily=S,R.append(D)}this._document.body.append(R),(function S(D,N){if(++l>30){(0,i.warn)("Load test font never loaded."),N();return}T.font="30px "+D,T.fillText(".",0,20),T.getImageData(0,0,1,1).data[3]>0?N():setTimeout(S.bind(null,D,N))})(y,(()=>{R.remove(),m.complete()}))}}class o{constructor(d,{isEvalSupported:m=!0,disableFontFace:v=!1,ignoreErrors:u=!1,inspectFont:a=null}){this.compiledGlyphs=Object.create(null);for(let p in d)this[p]=d[p];this.isEvalSupported=m!==!1,this.disableFontFace=v===!0,this.ignoreErrors=u===!0,this._inspectFont=a}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let d;if(this.cssFontInfo){let m={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(m.style=`oblique ${this.cssFontInfo.italicAngle}deg`),d=new FontFace(this.cssFontInfo.fontFamily,this.data,m)}else d=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),d}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let d=(0,i.bytesToString)(this.data),m=`url(data:${this.mimetype};base64,${btoa(d)});`,v;if(this.cssFontInfo){let u=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(u+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),v=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${u}src:${m}}`}else v=`@font-face {font-family:"${this.loadedName}";src:${m}}`;return this._inspectFont?.(this,m),v}getPathGenerator(d,m){if(this.compiledGlyphs[m]!==void 0)return this.compiledGlyphs[m];let v;try{v=d.get(this.loadedName+"_path_"+m)}catch(u){if(!this.ignoreErrors)throw u;return(0,i.warn)(`getPathGenerator - ignoring character: "${u}".`),this.compiledGlyphs[m]=function(a,p){}}if(this.isEvalSupported&&i.FeatureTest.isEvalSupported){let u=[];for(let a of v){let p=a.args!==void 0?a.args.join(","):"";u.push("c.",a.cmd,"(",p,`);
|
|
1534
|
+
`)}return this.compiledGlyphs[m]=new Function("c","size",u.join(""))}return this.compiledGlyphs[m]=function(u,a){for(let p of v)p.cmd==="scale"&&(p.args=[a,-a]),u[p.cmd].apply(u,p.args)}}}},62:(n,t,e)=>{e.d(t,{Metadata:()=>r});var i=e(292);class r{#t;#e;constructor({parsedData:g,rawData:d}){this.#t=g,this.#e=d}getRaw(){return this.#e}get(g){return this.#t.get(g)??null}getAll(){return(0,i.objectFromMap)(this.#t)}has(g){return this.#t.has(g)}}},457:(n,t,e)=>{e.d(t,{PDFNetworkStream:()=>g});var i=e(292),r=e(490);class o{constructor(u,a={}){this.url=u,this.isHttp=/^https?:/i.test(u),this.httpHeaders=this.isHttp&&a.httpHeaders||Object.create(null),this.withCredentials=a.withCredentials||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(u,a,p){let x={begin:u,end:a};for(let T in p)x[T]=p[T];return this.request(x)}requestFull(u){return this.request(u)}request(u){let a=new XMLHttpRequest,p=this.currXhrId++,x=this.pendingRequests[p]={xhr:a};a.open("GET",this.url),a.withCredentials=this.withCredentials;for(let T in this.httpHeaders){let l=this.httpHeaders[T];l!==void 0&&a.setRequestHeader(T,l)}return this.isHttp&&"begin"in u&&"end"in u?(a.setRequestHeader("Range",`bytes=${u.begin}-${u.end-1}`),x.expectedStatus=206):x.expectedStatus=200,a.responseType="arraybuffer",u.onError&&(a.onerror=function(T){u.onError(a.status)}),a.onreadystatechange=this.onStateChange.bind(this,p),a.onprogress=this.onProgress.bind(this,p),x.onHeadersReceived=u.onHeadersReceived,x.onDone=u.onDone,x.onError=u.onError,x.onProgress=u.onProgress,a.send(null),p}onProgress(u,a){let p=this.pendingRequests[u];p&&p.onProgress?.(a)}onStateChange(u,a){let p=this.pendingRequests[u];if(!p)return;let x=p.xhr;if(x.readyState>=2&&p.onHeadersReceived&&(p.onHeadersReceived(),delete p.onHeadersReceived),x.readyState!==4||!(u in this.pendingRequests))return;if(delete this.pendingRequests[u],x.status===0&&this.isHttp){p.onError?.(x.status);return}let T=x.status||200;if(!(T===200&&p.expectedStatus===206)&&T!==p.expectedStatus){p.onError?.(x.status);return}let l=(function(s){let c=s.response;return typeof c!="string"?c:(0,i.stringToBytes)(c).buffer})(x);if(T===206){let y=x.getResponseHeader("Content-Range"),s=/bytes (\d+)-(\d+)\/(\d+)/.exec(y);p.onDone({begin:parseInt(s[1],10),chunk:l})}else l?p.onDone({begin:0,chunk:l}):p.onError?.(x.status)}getRequestXhr(u){return this.pendingRequests[u].xhr}isPendingRequest(u){return u in this.pendingRequests}abortRequest(u){let a=this.pendingRequests[u].xhr;delete this.pendingRequests[u],a.abort()}}class g{constructor(u){this._source=u,this._manager=new o(u.url,{httpHeaders:u.httpHeaders,withCredentials:u.withCredentials}),this._rangeChunkSize=u.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(u){let a=this._rangeRequestReaders.indexOf(u);a>=0&&this._rangeRequestReaders.splice(a,1)}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new d(this._manager,this._source),this._fullRequestReader}getRangeReader(u,a){let p=new m(this._manager,u,a);return p.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(p),p}cancelAllRequests(u){this._fullRequestReader?.cancel(u);for(let a of this._rangeRequestReaders.slice(0))a.cancel(u)}}class d{constructor(u,a){this._manager=u;let p={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=a.url,this._fullRequestId=u.requestFull(p),this._headersReceivedCapability=Promise.withResolvers(),this._disableRange=a.disableRange||!1,this._contentLength=a.length,this._rangeChunkSize=a.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let u=this._fullRequestId,a=this._manager.getRequestXhr(u),p=l=>a.getResponseHeader(l),{allowRangeRequests:x,suggestedLength:T}=(0,r.validateRangeRequestCapabilities)({getResponseHeader:p,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});x&&(this._isRangeSupported=!0),this._contentLength=T||this._contentLength,this._filename=(0,r.extractFilenameFromHeader)(p),this._isRangeSupported&&this._manager.abortRequest(u),this._headersReceivedCapability.resolve()}_onDone(u){if(u&&(this._requests.length>0?this._requests.shift().resolve({value:u.chunk,done:!1}):this._cachedChunks.push(u.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(u){this._storedError=(0,r.createResponseStatusError)(u,this._url),this._headersReceivedCapability.reject(this._storedError);for(let a of this._requests)a.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(u){this.onProgress?.({loaded:u.loaded,total:u.lengthComputable?u.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let u=Promise.withResolvers();return this._requests.push(u),u.promise}cancel(u){this._done=!0,this._headersReceivedCapability.reject(u);for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class m{constructor(u,a,p){this._manager=u;let x={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=u.url,this._requestId=u.requestRange(a,p,x),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(u){let a=u.chunk;this._requests.length>0?this._requests.shift().resolve({value:a,done:!1}):this._queuedChunk=a,this._done=!0;for(let p of this._requests)p.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(u){this._storedError=(0,r.createResponseStatusError)(u,this._url);for(let a of this._requests)a.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(u){this.isStreamingSupported||this.onProgress?.({loaded:u.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let a=this._queuedChunk;return this._queuedChunk=null,{value:a,done:!1}}if(this._done)return{value:void 0,done:!0};let u=Promise.withResolvers();return this._requests.push(u),u.promise}cancel(u){this._done=!0;for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}},490:(n,t,e)=>{e.d(t,{createResponseStatusError:()=>d,extractFilenameFromHeader:()=>g,validateRangeRequestCapabilities:()=>o,validateResponseStatus:()=>m});var i=e(292),r=e(419);function o({getResponseHeader:v,isHttp:u,rangeChunkSize:a,disableRange:p}){let x={allowRangeRequests:!1,suggestedLength:void 0},T=parseInt(v("Content-Length"),10);return!Number.isInteger(T)||(x.suggestedLength=T,T<=2*a)||p||!u||v("Accept-Ranges")!=="bytes"||(v("Content-Encoding")||"identity")!=="identity"||(x.allowRangeRequests=!0),x}function g(v){let u=v("Content-Disposition");if(u){let a=(function(x){let T=!0,l=y("filename\\*","i").exec(x);if(l){l=l[1];let S=f(l);return S=unescape(S),S=w(S),S=R(S),c(S)}if(l=(function(D){let N=[],H,j=y("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(H=j.exec(D))!==null;){let[,it,ot,K]=H;if(it=parseInt(it,10),it in N){if(it===0)break}else N[it]=[ot,K]}let Y=[];for(let it=0;it<N.length&&it in N;++it){let[ot,K]=N[it];K=f(K),ot&&(K=unescape(K),it===0&&(K=w(K))),Y.push(K)}return Y.join("")})(x),l)return c(R(l));if(l=y("filename","i").exec(x),l){l=l[1];let S=f(l);return S=R(S),c(S)}function y(S,D){return new RegExp("(?:^|;)\\s*"+S+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',D)}function s(S,D){if(S){if(!/^[\x00-\xFF]+$/.test(D))return D;try{let N=new TextDecoder(S,{fatal:!0}),H=(0,i.stringToBytes)(D);D=N.decode(H),T=!1}catch{}}return D}function c(S){return T&&/[\x80-\xff]/.test(S)&&(S=s("utf-8",S),T&&(S=s("iso-8859-1",S))),S}function f(S){if(S.startsWith('"')){let D=S.slice(1).split('\\"');for(let N=0;N<D.length;++N){let H=D[N].indexOf('"');H!==-1&&(D[N]=D[N].slice(0,H),D.length=N+1),D[N]=D[N].replaceAll(/\\(.)/g,"$1")}S=D.join('"')}return S}function w(S){let D=S.indexOf("'");return D===-1?S:s(S.slice(0,D),S.slice(D+1).replace(/^[^']*'/,""))}function R(S){return!S.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(S)?S:S.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(D,N,H,j){if(H==="q"||H==="Q")return s(N,j=(j=j.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(Y,it){return String.fromCharCode(parseInt(it,16))})));try{j=atob(j)}catch{}return s(N,j)}))}return""})(u);if(a.includes("%"))try{a=decodeURIComponent(a)}catch{}if((0,r.isPdfFile)(a))return a}return null}function d(v,u){return v===404||v===0&&u.startsWith("file:")?new i.MissingPDFException('Missing PDF "'+u+'".'):new i.UnexpectedResponseException(`Unexpected server response (${v}) while retrieving PDF "${u}".`,v)}function m(v){return v===200||v===206}},786:(n,t,e)=>{e.a(n,(async(i,r)=>{try{let p=function(R){let S=u.parse(R);return S.protocol==="file:"||S.host?S:/^[a-z]:[/\\]/i.test(R)?u.parse(`file:///${R}`):(S.host||(S.protocol="file:"),S)},y=function(R,S){return{protocol:R.protocol,auth:R.auth,host:R.hostname,port:R.port,path:R.path,method:"GET",headers:S}};e.d(t,{PDFNodeStream:()=>x});var o=e(292),g=e(490);let d,m,v,u;o.isNodeJS&&(d=await Promise.resolve().then(()=>(Va(),za)),m=await Promise.resolve().then(()=>(zc(),jc)),v=await Promise.resolve().then(()=>(Wc(),Vc)),u=await Promise.resolve().then(()=>(qc(),Gc)));let a=/^file:\/\/\/[a-zA-Z]:\//;class x{constructor(S){this.source=S,this.url=p(S.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&S.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,o.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new f(this):new s(this),this._fullRequestReader}getRangeReader(S,D){if(D<=this._progressiveDataLength)return null;let N=this.isFsUrl?new w(this,S,D):new c(this,S,D);return this._rangeRequestReaders.push(N),N}cancelAllRequests(S){this._fullRequestReader?.cancel(S);for(let D of this._rangeRequestReaders.slice(0))D.cancel(S)}}class T{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null;let D=S.source;this._contentLength=D.length,this._loaded=0,this._filename=null,this._disableRange=D.disableRange||!1,this._rangeChunkSize=D.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!D.disableStream,this._isRangeSupported=!D.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){this._readableStream?this._readableStream.destroy(S):this._error(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",(()=>{this._readCapability.resolve()})),S.on("end",(()=>{S.destroy(),this._done=!0,this._readCapability.resolve()})),S.on("error",(D=>{this._error(D)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new o.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class l{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let D=S.source;this._isStreamingSupported=!D.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){this._readableStream?this._readableStream.destroy(S):this._error(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",(()=>{this._readCapability.resolve()})),S.on("end",(()=>{S.destroy(),this._done=!0,this._readCapability.resolve()})),S.on("error",(D=>{this._error(D)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class s extends T{constructor(S){super(S);let D=N=>{if(N.statusCode===404){let it=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=it,this._headersCapability.reject(it);return}this._headersCapability.resolve(),this._setReadableStream(N);let H=it=>this._readableStream.headers[it.toLowerCase()],{allowRangeRequests:j,suggestedLength:Y}=(0,g.validateRangeRequestCapabilities)({getResponseHeader:H,isHttp:S.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=j,this._contentLength=Y||this._contentLength,this._filename=(0,g.extractFilenameFromHeader)(H)};this._request=null,this._url.protocol==="http:"?this._request=m.request(y(this._url,S.httpHeaders),D):this._request=v.request(y(this._url,S.httpHeaders),D),this._request.on("error",(N=>{this._storedError=N,this._headersCapability.reject(N)})),this._request.end()}}class c extends l{constructor(S,D,N){super(S),this._httpHeaders={};for(let j in S.httpHeaders){let Y=S.httpHeaders[j];Y!==void 0&&(this._httpHeaders[j]=Y)}this._httpHeaders.Range=`bytes=${D}-${N-1}`;let H=j=>{if(j.statusCode!==404)this._setReadableStream(j);else{let Y=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=Y}};this._request=null,this._url.protocol==="http:"?this._request=m.request(y(this._url,this._httpHeaders),H):this._request=v.request(y(this._url,this._httpHeaders),H),this._request.on("error",(j=>{this._storedError=j})),this._request.end()}}class f extends T{constructor(S){super(S);let D=decodeURIComponent(this._url.path);a.test(this._url.href)&&(D=D.replace(/^\//,"")),d.promises.lstat(D).then((N=>{this._contentLength=N.size,this._setReadableStream(d.createReadStream(D)),this._headersCapability.resolve()}),(N=>{N.code==="ENOENT"&&(N=new o.MissingPDFException(`Missing PDF "${D}".`)),this._storedError=N,this._headersCapability.reject(N)}))}}class w extends l{constructor(S,D,N){super(S);let H=decodeURIComponent(this._url.path);a.test(this._url.href)&&(H=H.replace(/^\//,"")),this._setReadableStream(d.createReadStream(H,{start:D,end:N-1}))}}r()}catch(d){r(d)}}),1)},573:(n,t,e)=>{e.a(n,(async(i,r)=>{try{e.d(t,{NodeCMapReaderFactory:()=>p,NodeCanvasFactory:()=>a,NodeFilterFactory:()=>u,NodeStandardFontDataFactory:()=>x});var o=e(583);let g,d,m;if(e(292).isNodeJS){g=await Promise.resolve().then(()=>(Va(),za));try{d=await Promise.resolve().then(()=>(Kc(),Xc))}catch{}try{m=await Promise.resolve().then(()=>(Jc(),Yc))}catch{}}let v=function(T){return g.promises.readFile(T).then((l=>new Uint8Array(l)))};class u extends o.BaseFilterFactory{}class a extends o.BaseCanvasFactory{_createCanvas(l,y){return d.createCanvas(l,y)}}class p extends o.BaseCMapReaderFactory{_fetchData(l,y){return v(l).then((s=>({cMapData:s,compressionType:y})))}}class x extends o.BaseStandardFontDataFactory{_fetchData(l){return v(l)}}r()}catch(g){r(g)}}),1)},626:(n,t,e)=>{e.d(t,{OptionalContentConfig:()=>d});var i=e(292),r=e(651);let o=Symbol("INTERNAL");class g{#t=!1;#e=!1;#i=!1;#n=!0;constructor(v,{name:u,intent:a,usage:p}){this.#t=!!(v&i.RenderingIntentFlag.DISPLAY),this.#e=!!(v&i.RenderingIntentFlag.PRINT),this.name=u,this.intent=a,this.usage=p}get visible(){if(this.#i)return this.#n;if(!this.#n)return!1;let{print:v,view:u}=this.usage;return this.#t?u?.viewState!=="OFF":!this.#e||v?.printState!=="OFF"}_setVisible(v,u,a=!1){v!==o&&(0,i.unreachable)("Internal method `_setVisible` called."),this.#i=a,this.#n=u}}class d{#t=null;#e=new Map;#i=null;#n=null;constructor(v,u=i.RenderingIntentFlag.DISPLAY){if(this.renderingIntent=u,this.name=null,this.creator=null,v!==null){this.name=v.name,this.creator=v.creator,this.#n=v.order;for(let a of v.groups)this.#e.set(a.id,new g(u,a));if(v.baseState==="OFF")for(let a of this.#e.values())a._setVisible(o,!1);for(let a of v.on)this.#e.get(a)._setVisible(o,!0);for(let a of v.off)this.#e.get(a)._setVisible(o,!1);this.#i=this.getHash()}}#r(v){let u=v.length;if(u<2)return!0;let a=v[0];for(let p=1;p<u;p++){let x=v[p],T;if(Array.isArray(x))T=this.#r(x);else{if(!this.#e.has(x))return(0,i.warn)(`Optional content group not found: ${x}`),!0;T=this.#e.get(x).visible}switch(a){case"And":if(!T)return!1;break;case"Or":if(T)return!0;break;case"Not":return!T;default:return!0}}return a==="And"}isVisible(v){if(this.#e.size===0)return!0;if(!v)return(0,i.info)("Optional content group not defined."),!0;if(v.type==="OCG")return this.#e.has(v.id)?this.#e.get(v.id).visible:((0,i.warn)(`Optional content group not found: ${v.id}`),!0);if(v.type==="OCMD"){if(v.expression)return this.#r(v.expression);if(!v.policy||v.policy==="AnyOn"){for(let u of v.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(this.#e.get(u).visible)return!0}return!1}if(v.policy==="AllOn"){for(let u of v.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(!this.#e.get(u).visible)return!1}return!0}if(v.policy==="AnyOff"){for(let u of v.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(!this.#e.get(u).visible)return!0}return!1}if(v.policy==="AllOff"){for(let u of v.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(this.#e.get(u).visible)return!1}return!0}return(0,i.warn)(`Unknown optional content policy ${v.policy}.`),!0}return(0,i.warn)(`Unknown group type ${v.type}.`),!0}setVisibility(v,u=!0){let a=this.#e.get(v);a?(a._setVisible(o,!!u,!0),this.#t=null):(0,i.warn)(`Optional content group not found: ${v}`)}setOCGState({state:v,preserveRB:u}){let a;for(let p of v){switch(p){case"ON":case"OFF":case"Toggle":a=p;continue}let x=this.#e.get(p);if(x)switch(a){case"ON":x._setVisible(o,!0);break;case"OFF":x._setVisible(o,!1);break;case"Toggle":x._setVisible(o,!x.visible)}}this.#t=null}get hasInitialVisibility(){return this.#i===null||this.getHash()===this.#i}getOrder(){return this.#e.size?this.#n?this.#n.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?(0,i.objectFromMap)(this.#e):null}getGroup(v){return this.#e.get(v)||null}getHash(){if(this.#t!==null)return this.#t;let v=new r.MurmurHash3_64;for(let[u,a]of this.#e)v.update(`${u}:${a.visible}`);return this.#t=v.hexdigest()}}},814:(n,t,e)=>{e.d(t,{cleanupTextLayer:()=>u,renderTextLayer:()=>T,updateTextLayer:()=>l});var i=e(292),r=e(419);let o=30,g=.8,d=new Map,m=null;function v(){if(!m){let y=document.createElement("canvas");y.className="hiddenCanvasElement",document.body.append(y),m=y.getContext("2d",{alpha:!1})}return m}function u(){m?.canvas.remove(),m=null}function a(y,s,c){let f=document.createElement("span"),w={angle:0,canvasWidth:0,hasText:s.str!=="",hasEOL:s.hasEOL,fontSize:0};y._textDivs.push(f);let R=i.Util.transform(y._transform,s.transform),S=Math.atan2(R[1],R[0]),D=c[s.fontName];D.vertical&&(S+=Math.PI/2);let N=y._fontInspectorEnabled&&D.fontSubstitution||D.fontFamily,H=Math.hypot(R[2],R[3]),j=H*(function(X){let et=d.get(X);if(et)return et;let st=v(),ct=st.font;st.canvas.width=st.canvas.height=o,st.font=`${o}px ${X}`;let nt=st.measureText(""),G=nt.fontBoundingBoxAscent,A=Math.abs(nt.fontBoundingBoxDescent);if(G){let I=G/(G+A);return d.set(X,I),st.canvas.width=st.canvas.height=0,st.font=ct,I}st.strokeStyle="red",st.clearRect(0,0,o,o),st.strokeText("g",0,0);let _=st.getImageData(0,0,o,o).data;A=0;for(let I=_.length-1-3;I>=0;I-=4)if(_[I]>0){A=Math.ceil(I/4/o);break}st.clearRect(0,0,o,o),st.strokeText("A",0,o),_=st.getImageData(0,0,o,o).data,G=0;for(let I=0,h=_.length;I<h;I+=4)if(_[I]>0){G=o-Math.floor(I/4/o);break}if(st.canvas.width=st.canvas.height=0,st.font=ct,G){let I=G/(G+A);return d.set(X,I),I}return d.set(X,g),g})(N),Y,it;S===0?(Y=R[4],it=R[5]-j):(Y=R[4]+j*Math.sin(S),it=R[5]-j*Math.cos(S));let ot="calc(var(--scale-factor)*",K=f.style;y._container===y._rootContainer?(K.left=`${(100*Y/y._pageWidth).toFixed(2)}%`,K.top=`${(100*it/y._pageHeight).toFixed(2)}%`):(K.left=`${ot}${Y.toFixed(2)}px)`,K.top=`${ot}${it.toFixed(2)}px)`),K.fontSize=`${ot}${H.toFixed(2)}px)`,K.fontFamily=N,w.fontSize=H,f.setAttribute("role","presentation"),f.textContent=s.str,f.dir=s.dir,y._fontInspectorEnabled&&(f.dataset.fontName=D.fontSubstitutionLoadedName||s.fontName),S!==0&&(w.angle=S*(180/Math.PI));let z=!1;if(s.str.length>1)z=!0;else if(s.str!==" "&&s.transform[0]!==s.transform[3]){let W=Math.abs(s.transform[0]),X=Math.abs(s.transform[3]);W!==X&&Math.max(W,X)/Math.min(W,X)>1.5&&(z=!0)}z&&(w.canvasWidth=D.vertical?s.height:s.width),y._textDivProperties.set(f,w),y._isReadableStream&&y._layoutText(f)}function p(y){let{div:s,scale:c,properties:f,ctx:w,prevFontSize:R,prevFontFamily:S}=y,{style:D}=s,N="";if(f.canvasWidth!==0&&f.hasText){let{fontFamily:H}=D,{canvasWidth:j,fontSize:Y}=f;(R!==Y||S!==H)&&(w.font=`${Y*c}px ${H}`,y.prevFontSize=Y,y.prevFontFamily=H);let{width:it}=w.measureText(s.textContent);it>0&&(N=`scaleX(${j*c/it})`)}f.angle!==0&&(N=`rotate(${f.angle}deg) ${N}`),N.length>0&&(D.transform=N)}class x{constructor({textContentSource:s,container:c,viewport:f,textDivs:w,textDivProperties:R,textContentItemsStr:S}){this._textContentSource=s,this._isReadableStream=s instanceof ReadableStream,this._container=this._rootContainer=c,this._textDivs=w||[],this._textContentItemsStr=S||[],this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled,this._reader=null,this._textDivProperties=R||new WeakMap,this._canceled=!1,this._capability=Promise.withResolvers(),this._layoutTextParams={prevFontSize:null,prevFontFamily:null,div:null,scale:f.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:v()};let{pageWidth:D,pageHeight:N,pageX:H,pageY:j}=f.rawDims;this._transform=[1,0,0,-1,-H,j+N],this._pageWidth=D,this._pageHeight=N,(0,r.setLayerDimensions)(c,f),this._capability.promise.finally((()=>{this._layoutTextParams=null})).catch((()=>{}))}get promise(){return this._capability.promise}cancel(){this._canceled=!0,this._reader&&(this._reader.cancel(new i.AbortException("TextLayer task cancelled.")).catch((()=>{})),this._reader=null),this._capability.reject(new i.AbortException("TextLayer task cancelled."))}_processItems(s,c){for(let f of s)if(f.str!==void 0)this._textContentItemsStr.push(f.str),a(this,f,c);else if(f.type==="beginMarkedContentProps"||f.type==="beginMarkedContent"){let w=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),f.id!==null&&this._container.setAttribute("id",`${f.id}`),w.append(this._container)}else f.type==="endMarkedContent"&&(this._container=this._container.parentNode)}_layoutText(s){let c=this._layoutTextParams.properties=this._textDivProperties.get(s);if(this._layoutTextParams.div=s,p(this._layoutTextParams),c.hasText&&this._container.append(s),c.hasEOL){let f=document.createElement("br");f.setAttribute("role","presentation"),this._container.append(f)}}_render(){let{promise:s,resolve:c,reject:f}=Promise.withResolvers(),w=Object.create(null);if(this._isReadableStream){let R=()=>{this._reader.read().then((({value:S,done:D})=>{D?c():(Object.assign(w,S.styles),this._processItems(S.items,w),R())}),f)};this._reader=this._textContentSource.getReader(),R()}else{if(!this._textContentSource)throw new Error('No "textContentSource" parameter specified.');{let{items:R,styles:S}=this._textContentSource;this._processItems(R,S),c()}}s.then((()=>{w=null,(function(S){if(S._canceled)return;let D=S._textDivs,N=S._capability;if(D.length>1e5)N.resolve();else{if(!S._isReadableStream)for(let H of D)S._layoutText(H);N.resolve()}})(this)}),this._capability.reject)}}function T(y){let s=new x(y);return s._render(),s}function l({container:y,viewport:s,textDivs:c,textDivProperties:f,mustRotate:w=!0,mustRescale:R=!0}){if(w&&(0,r.setLayerDimensions)(y,{rotation:s.rotation}),R){let S=v(),D={prevFontSize:null,prevFontFamily:null,div:null,scale:s.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:S};for(let N of c)D.properties=f.get(N),D.div=N,p(D)}}},585:(n,t,e)=>{e.d(t,{PDFDataTransportStream:()=>o});var i=e(292),r=e(419);class o{constructor(v,{disableRange:u=!1,disableStream:a=!1}){(0,i.assert)(v,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');let{length:p,initialData:x,progressiveDone:T,contentDispositionFilename:l}=v;if(this._queuedChunks=[],this._progressiveDone=T,this._contentDispositionFilename=l,x?.length>0){let y=x instanceof Uint8Array&&x.byteLength===x.buffer.byteLength?x.buffer:new Uint8Array(x).buffer;this._queuedChunks.push(y)}this._pdfDataRangeTransport=v,this._isStreamingSupported=!a,this._isRangeSupported=!u,this._contentLength=p,this._fullRequestReader=null,this._rangeReaders=[],v.addRangeListener(((y,s)=>{this._onReceiveData({begin:y,chunk:s})})),v.addProgressListener(((y,s)=>{this._onProgress({loaded:y,total:s})})),v.addProgressiveReadListener((y=>{this._onReceiveData({chunk:y})})),v.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),v.transportReady()}_onReceiveData({begin:v,chunk:u}){let a=u instanceof Uint8Array&&u.byteLength===u.buffer.byteLength?u.buffer:new Uint8Array(u).buffer;if(v===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(a):this._queuedChunks.push(a);else{let p=this._rangeReaders.some((function(x){return x._begin!==v?!1:(x._enqueue(a),!0)}));(0,i.assert)(p,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(v){v.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:v.loaded}):this._fullRequestReader?.onProgress?.({loaded:v.loaded,total:v.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(v){let u=this._rangeReaders.indexOf(v);u>=0&&this._rangeReaders.splice(u,1)}getFullReader(){(0,i.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let v=this._queuedChunks;return this._queuedChunks=null,new g(this,v,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(v,u){if(u<=this._progressiveDataLength)return null;let a=new d(this,v,u);return this._pdfDataRangeTransport.requestDataRange(v,u),this._rangeReaders.push(a),a}cancelAllRequests(v){this._fullRequestReader?.cancel(v);for(let u of this._rangeReaders.slice(0))u.cancel(v);this._pdfDataRangeTransport.abort()}}class g{constructor(v,u,a=!1,p=null){this._stream=v,this._done=a||!1,this._filename=(0,r.isPdfFile)(p)?p:null,this._queuedChunks=u||[],this._loaded=0;for(let x of this._queuedChunks)this._loaded+=x.byteLength;this._requests=[],this._headersReady=Promise.resolve(),v._fullRequestReader=this,this.onProgress=null}_enqueue(v){this._done||(this._requests.length>0?this._requests.shift().resolve({value:v,done:!1}):this._queuedChunks.push(v),this._loaded+=v.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let v=Promise.withResolvers();return this._requests.push(v),v.promise}cancel(v){this._done=!0;for(let u of this._requests)u.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class d{constructor(v,u,a){this._stream=v,this._begin=u,this._end=a,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(v){if(!this._done){if(this._requests.length===0)this._queuedChunk=v;else{this._requests.shift().resolve({value:v,done:!1});for(let u of this._requests)u.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){let u=this._queuedChunk;return this._queuedChunk=null,{value:u,done:!1}}if(this._done)return{value:void 0,done:!0};let v=Promise.withResolvers();return this._requests.push(v),v.promise}cancel(v){this._done=!0;for(let u of this._requests)u.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}},164:(n,t,e)=>{e.d(t,{GlobalWorkerOptions:()=>i});class i{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(o){if(!(typeof Worker<"u"&&o instanceof Worker)&&o!==null)throw new Error("Invalid `workerPort` type.");this.#t=o}static get workerSrc(){return this.#e}static set workerSrc(o){if(typeof o!="string")throw new Error("Invalid `workerSrc` type.");this.#e=o}}},284:(n,t,e)=>{e.d(t,{XfaLayer:()=>r});var i=e(50);class r{static setupStorage(g,d,m,v,u){let a=v.getValue(d,{value:null});switch(m.name){case"textarea":if(a.value!==null&&(g.textContent=a.value),u==="print")break;g.addEventListener("input",(p=>{v.setValue(d,{value:p.target.value})}));break;case"input":if(m.attributes.type==="radio"||m.attributes.type==="checkbox"){if(a.value===m.attributes.xfaOn?g.setAttribute("checked",!0):a.value===m.attributes.xfaOff&&g.removeAttribute("checked"),u==="print")break;g.addEventListener("change",(p=>{v.setValue(d,{value:p.target.checked?p.target.getAttribute("xfaOn"):p.target.getAttribute("xfaOff")})}))}else{if(a.value!==null&&g.setAttribute("value",a.value),u==="print")break;g.addEventListener("input",(p=>{v.setValue(d,{value:p.target.value})}))}break;case"select":if(a.value!==null){g.setAttribute("value",a.value);for(let p of m.children)p.attributes.value===a.value?p.attributes.selected=!0:p.attributes.hasOwnProperty("selected")&&delete p.attributes.selected}g.addEventListener("input",(p=>{let x=p.target.options,T=x.selectedIndex===-1?"":x[x.selectedIndex].value;v.setValue(d,{value:T})}))}}static setAttributes({html:g,element:d,storage:m=null,intent:v,linkService:u}){let{attributes:a}=d,p=g instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${v}`);for(let[x,T]of Object.entries(a))if(T!=null)switch(x){case"class":T.length&&g.setAttribute(x,T.join(" "));break;case"dataId":break;case"id":g.setAttribute("data-element-id",T);break;case"style":Object.assign(g.style,T);break;case"textContent":g.textContent=T;break;default:(!p||x!=="href"&&x!=="newWindow")&&g.setAttribute(x,T)}p&&u.addLinkAttributes(g,a.href,a.newWindow),m&&a.dataId&&this.setupStorage(g,a.dataId,d,m)}static render(g){let d=g.annotationStorage,m=g.linkService,v=g.xfaHtml,u=g.intent||"display",a=document.createElement(v.name);v.attributes&&this.setAttributes({html:a,element:v,intent:u,linkService:m});let p=u!=="richText",x=g.div;if(x.append(a),g.viewport){let y=`matrix(${g.viewport.transform.join(",")})`;x.style.transform=y}p&&x.setAttribute("class","xfaLayer xfaFont");let T=[];if(v.children.length===0){if(v.value){let y=document.createTextNode(v.value);a.append(y),p&&i.XfaText.shouldBuildText(v.name)&&T.push(y)}return{textDivs:T}}let l=[[v,-1,a]];for(;l.length>0;){let[y,s,c]=l.at(-1);if(s+1===y.children.length){l.pop();continue}let f=y.children[++l.at(-1)[1]];if(f===null)continue;let{name:w}=f;if(w==="#text"){let S=document.createTextNode(f.value);T.push(S),c.append(S);continue}let R=f?.attributes?.xmlns?document.createElementNS(f.attributes.xmlns,w):document.createElement(w);if(c.append(R),f.attributes&&this.setAttributes({html:R,element:f,storage:d,intent:u,linkService:m}),f.children?.length>0)l.push([f,-1,R]);else if(f.value){let S=document.createTextNode(f.value);p&&i.XfaText.shouldBuildText(w)&&T.push(S),R.append(S)}}for(let y of x.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))y.setAttribute("readOnly",!0);return{textDivs:T}}static update(g){let d=`matrix(${g.viewport.transform.join(",")})`;g.div.style.transform=d,g.div.hidden=!1}}},50:(n,t,e)=>{e.d(t,{XfaText:()=>i});class i{static textContent(o){let g=[],d={items:g,styles:Object.create(null)};return(function m(v){if(!v)return;let u=null,a=v.name;if(a==="#text")u=v.value;else{if(!i.shouldBuildText(a))return;v?.attributes?.textContent?u=v.attributes.textContent:v.value&&(u=v.value)}if(u!==null&&g.push({str:u}),v.children)for(let p of v.children)m(p)})(o),d}static shouldBuildText(o){return!(o==="textarea"||o==="input"||o==="option"||o==="select")}}},228:(n,t,e)=>{e.a(n,(async(i,r)=>{try{e.d(t,{AbortException:()=>o.AbortException,AnnotationEditorLayer:()=>v.AnnotationEditorLayer,AnnotationEditorParamsType:()=>o.AnnotationEditorParamsType,AnnotationEditorType:()=>o.AnnotationEditorType,AnnotationEditorUIManager:()=>u.AnnotationEditorUIManager,AnnotationLayer:()=>a.AnnotationLayer,AnnotationMode:()=>o.AnnotationMode,CMapCompressionType:()=>o.CMapCompressionType,ColorPicker:()=>p.ColorPicker,DOMSVGFactory:()=>d.DOMSVGFactory,DrawLayer:()=>x.DrawLayer,FeatureTest:()=>o.FeatureTest,GlobalWorkerOptions:()=>T.GlobalWorkerOptions,ImageKind:()=>o.ImageKind,InvalidPDFException:()=>o.InvalidPDFException,MissingPDFException:()=>o.MissingPDFException,OPS:()=>o.OPS,Outliner:()=>l.Outliner,PDFDataRangeTransport:()=>g.PDFDataRangeTransport,PDFDateString:()=>d.PDFDateString,PDFWorker:()=>g.PDFWorker,PasswordResponses:()=>o.PasswordResponses,PermissionFlag:()=>o.PermissionFlag,PixelsPerInch:()=>d.PixelsPerInch,RenderingCancelledException:()=>d.RenderingCancelledException,UnexpectedResponseException:()=>o.UnexpectedResponseException,Util:()=>o.Util,VerbosityLevel:()=>o.VerbosityLevel,XfaLayer:()=>y.XfaLayer,build:()=>g.build,createValidAbsoluteUrl:()=>o.createValidAbsoluteUrl,fetchData:()=>d.fetchData,getDocument:()=>g.getDocument,getFilenameFromUrl:()=>d.getFilenameFromUrl,getPdfFilenameFromUrl:()=>d.getPdfFilenameFromUrl,getXfaPageViewport:()=>d.getXfaPageViewport,isDataScheme:()=>d.isDataScheme,isPdfFile:()=>d.isPdfFile,noContextMenu:()=>d.noContextMenu,normalizeUnicode:()=>o.normalizeUnicode,renderTextLayer:()=>m.renderTextLayer,setLayerDimensions:()=>d.setLayerDimensions,shadow:()=>o.shadow,updateTextLayer:()=>m.updateTextLayer,version:()=>g.version});var o=e(292),g=e(831),d=e(419),m=e(814),v=e(731),u=e(830),a=e(976),p=e(259),x=e(47),T=e(164),l=e(61),y=e(284),s=i([g]);g=(s.then?(await s)():s)[0],r()}catch(c){r(c)}}))},178:(n,t,e)=>{e.d(t,{MessageHandler:()=>l});var i=e(292);let r=1,o=2,g=1,d=2,m=3,v=4,u=5,a=6,p=7,x=8;function T(y){switch(y instanceof Error||typeof y=="object"&&y!==null||(0,i.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),y.name){case"AbortException":return new i.AbortException(y.message);case"MissingPDFException":return new i.MissingPDFException(y.message);case"PasswordException":return new i.PasswordException(y.message,y.code);case"UnexpectedResponseException":return new i.UnexpectedResponseException(y.message,y.status);case"UnknownErrorException":return new i.UnknownErrorException(y.message,y.details);default:return new i.UnknownErrorException(y.message,y.toString())}}class l{constructor(s,c,f){this.sourceName=s,this.targetName=c,this.comObj=f,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=w=>{let R=w.data;if(R.targetName!==this.sourceName)return;if(R.stream){this.#e(R);return}if(R.callback){let D=R.callbackId,N=this.callbackCapabilities[D];if(!N)throw new Error(`Cannot resolve callback ${D}`);if(delete this.callbackCapabilities[D],R.callback===r)N.resolve(R.data);else{if(R.callback!==o)throw new Error("Unexpected callback case");N.reject(T(R.reason))}return}let S=this.actionHandler[R.action];if(!S)throw new Error(`Unknown action from worker: ${R.action}`);if(R.callbackId){let D=this.sourceName,N=R.sourceName;new Promise((function(H){H(S(R.data))})).then((function(H){f.postMessage({sourceName:D,targetName:N,callback:r,callbackId:R.callbackId,data:H})}),(function(H){f.postMessage({sourceName:D,targetName:N,callback:o,callbackId:R.callbackId,reason:T(H)})}))}else R.streamId?this.#t(R):S(R.data)},f.addEventListener("message",this._onComObjOnMessage)}on(s,c){let f=this.actionHandler;if(f[s])throw new Error(`There is already an actionName called "${s}"`);f[s]=c}send(s,c,f){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:s,data:c},f)}sendWithPromise(s,c,f){let w=this.callbackId++,R=Promise.withResolvers();this.callbackCapabilities[w]=R;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:s,callbackId:w,data:c},f)}catch(S){R.reject(S)}return R.promise}sendWithStream(s,c,f,w){let R=this.streamId++,S=this.sourceName,D=this.targetName,N=this.comObj;return new ReadableStream({start:H=>{let j=Promise.withResolvers();return this.streamControllers[R]={controller:H,startCall:j,pullCall:null,cancelCall:null,isClosed:!1},N.postMessage({sourceName:S,targetName:D,action:s,streamId:R,data:c,desiredSize:H.desiredSize},w),j.promise},pull:H=>{let j=Promise.withResolvers();return this.streamControllers[R].pullCall=j,N.postMessage({sourceName:S,targetName:D,stream:a,streamId:R,desiredSize:H.desiredSize}),j.promise},cancel:H=>{(0,i.assert)(H instanceof Error,"cancel must have a valid reason");let j=Promise.withResolvers();return this.streamControllers[R].cancelCall=j,this.streamControllers[R].isClosed=!0,N.postMessage({sourceName:S,targetName:D,stream:g,streamId:R,reason:T(H)}),j.promise}},f)}#t(s){let c=s.streamId,f=this.sourceName,w=s.sourceName,R=this.comObj,S=this,D=this.actionHandler[s.action],N={enqueue(H,j=1,Y){if(this.isCancelled)return;let it=this.desiredSize;this.desiredSize-=j,it>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),R.postMessage({sourceName:f,targetName:w,stream:v,streamId:c,chunk:H},Y)},close(){this.isCancelled||(this.isCancelled=!0,R.postMessage({sourceName:f,targetName:w,stream:m,streamId:c}),delete S.streamSinks[c])},error(H){(0,i.assert)(H instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,R.postMessage({sourceName:f,targetName:w,stream:u,streamId:c,reason:T(H)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:s.desiredSize,ready:null};N.sinkCapability.resolve(),N.ready=N.sinkCapability.promise,this.streamSinks[c]=N,new Promise((function(H){H(D(s.data,N))})).then((function(){R.postMessage({sourceName:f,targetName:w,stream:x,streamId:c,success:!0})}),(function(H){R.postMessage({sourceName:f,targetName:w,stream:x,streamId:c,reason:T(H)})}))}#e(s){let c=s.streamId,f=this.sourceName,w=s.sourceName,R=this.comObj,S=this.streamControllers[c],D=this.streamSinks[c];switch(s.stream){case x:s.success?S.startCall.resolve():S.startCall.reject(T(s.reason));break;case p:s.success?S.pullCall.resolve():S.pullCall.reject(T(s.reason));break;case a:if(!D){R.postMessage({sourceName:f,targetName:w,stream:p,streamId:c,success:!0});break}D.desiredSize<=0&&s.desiredSize>0&&D.sinkCapability.resolve(),D.desiredSize=s.desiredSize,new Promise((function(N){N(D.onPull?.())})).then((function(){R.postMessage({sourceName:f,targetName:w,stream:p,streamId:c,success:!0})}),(function(N){R.postMessage({sourceName:f,targetName:w,stream:p,streamId:c,reason:T(N)})}));break;case v:if((0,i.assert)(S,"enqueue should have stream controller"),S.isClosed)break;S.controller.enqueue(s.chunk);break;case m:if((0,i.assert)(S,"close should have stream controller"),S.isClosed)break;S.isClosed=!0,S.controller.close(),this.#i(S,c);break;case u:(0,i.assert)(S,"error should have stream controller"),S.controller.error(T(s.reason)),this.#i(S,c);break;case d:s.success?S.cancelCall.resolve():S.cancelCall.reject(T(s.reason)),this.#i(S,c);break;case g:if(!D)break;new Promise((function(N){N(D.onCancel?.(T(s.reason)))})).then((function(){R.postMessage({sourceName:f,targetName:w,stream:d,streamId:c,success:!0})}),(function(N){R.postMessage({sourceName:f,targetName:w,stream:d,streamId:c,reason:T(N)})})),D.sinkCapability.reject(T(s.reason)),D.isCancelled=!0,delete this.streamSinks[c];break;default:throw new Error("Unexpected stream case")}}async#i(s,c){await Promise.allSettled([s.startCall?.promise,s.pullCall?.promise,s.cancelCall?.promise]),delete this.streamControllers[c]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},651:(n,t,e)=>{e.d(t,{MurmurHash3_64:()=>g});let i=3285377520,r=4294901760,o=65535;class g{constructor(m){this.h1=m?4294967295&m:i,this.h2=m?4294967295&m:i}update(m){let v,u;if(typeof m=="string"){v=new Uint8Array(2*m.length),u=0;for(let S=0,D=m.length;S<D;S++){let N=m.charCodeAt(S);N<=255?v[u++]=N:(v[u++]=N>>>8,v[u++]=255&N)}}else{if(!ArrayBuffer.isView(m))throw new Error("Invalid data format, must be a string or TypedArray.");v=m.slice(),u=v.byteLength}let a=u>>2,p=u-4*a,x=new Uint32Array(v.buffer,0,a),T=0,l=0,y=this.h1,s=this.h2,c=3432918353,f=461845907,w=11601,R=13715;for(let S=0;S<a;S++)1&S?(T=x[S],T=T*c&r|T*w&o,T=T<<15|T>>>17,T=T*f&r|T*R&o,y^=T,y=y<<13|y>>>19,y=5*y+3864292196):(l=x[S],l=l*c&r|l*w&o,l=l<<15|l>>>17,l=l*f&r|l*R&o,s^=l,s=s<<13|s>>>19,s=5*s+3864292196);switch(T=0,p){case 3:T^=v[4*a+2]<<16;case 2:T^=v[4*a+1]<<8;case 1:T^=v[4*a],T=T*c&r|T*w&o,T=T<<15|T>>>17,T=T*f&r|T*R&o,1&a?y^=T:s^=T}this.h1=y,this.h2=s}hexdigest(){let m=this.h1,v=this.h2;return m^=v>>>1,m=3981806797*m&r|36045*m&o,v=4283543511*v&r|(2950163797*(v<<16|m>>>16)&r)>>>16,m^=v>>>1,m=444984403*m&r|60499*m&o,v=3301882366*v&r|(3120437893*(v<<16|m>>>16)&r)>>>16,m^=v>>>1,(m>>>0).toString(16).padStart(8,"0")+(v>>>0).toString(16).padStart(8,"0")}}},292:(n,t,e)=>{e.d(t,{AbortException:()=>G,AnnotationBorderStyleType:()=>s,AnnotationEditorParamsType:()=>p,AnnotationEditorPrefix:()=>u,AnnotationEditorType:()=>a,AnnotationMode:()=>v,AnnotationPrefix:()=>U,AnnotationType:()=>y,BaseException:()=>z,CMapCompressionType:()=>f,FONT_IDENTITY_MATRIX:()=>o,FeatureTest:()=>b,FormatError:()=>nt,IDENTITY_MATRIX:()=>r,ImageKind:()=>l,InvalidPDFException:()=>et,LINE_FACTOR:()=>d,MAX_IMAGE_SIZE_TO_CACHE:()=>g,MissingPDFException:()=>st,OPS:()=>w,PasswordException:()=>W,PasswordResponses:()=>R,PermissionFlag:()=>x,RenderingIntentFlag:()=>m,TextRenderingMode:()=>T,UnexpectedResponseException:()=>ct,UnknownErrorException:()=>X,Util:()=>P,VerbosityLevel:()=>c,assert:()=>it,bytesToString:()=>A,createValidAbsoluteUrl:()=>ot,getUuid:()=>L,getVerbosityLevel:()=>N,info:()=>H,isNodeJS:()=>i,normalizeUnicode:()=>E,objectFromMap:()=>h,setVerbosityLevel:()=>D,shadow:()=>K,string32:()=>I,stringToBytes:()=>_,unreachable:()=>Y,warn:()=>j});let i=!(typeof process!="object"||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&process.type!=="browser"),r=[1,0,0,1,0,0],o=[.001,0,0,.001,0,0],g=1e7,d=1.35,m={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,OPLIST:256},v={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},u="pdfjs_internal_editor_",a={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},p={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},x={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},T={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},l={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},y={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},s={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},c={ERRORS:0,WARNINGS:1,INFOS:5},f={NONE:0,BINARY:1},w={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},R={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},S=c.WARNINGS;function D(B){Number.isInteger(B)&&(S=B)}function N(){return S}function H(B){S>=c.INFOS&&console.log(`Info: ${B}`)}function j(B){S>=c.WARNINGS&&console.log(`Warning: ${B}`)}function Y(B){throw new Error(B)}function it(B,k){B||Y(k)}function ot(B,k=null,F=null){if(!B)return null;try{if(F&&typeof B=="string"&&(F.addDefaultProtocol&&B.startsWith("www.")&&B.match(/\./g)?.length>=2&&(B=`http://${B}`),F.tryConvertEncoding))try{B=(function(Z){return decodeURIComponent(escape(Z))})(B)}catch{}let V=k?new URL(B,k):new URL(B);if((function(Z){switch(Z?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}})(V))return V}catch{}return null}function K(B,k,F,V=!1){return Object.defineProperty(B,k,{value:F,enumerable:!V,configurable:!0,writable:!1}),F}let z=(function(){function k(F,V){this.constructor===k&&Y("Cannot initialize BaseException."),this.message=F,this.name=V}return k.prototype=new Error,k.constructor=k,k})();class W extends z{constructor(k,F){super(k,"PasswordException"),this.code=F}}class X extends z{constructor(k,F){super(k,"UnknownErrorException"),this.details=F}}class et extends z{constructor(k){super(k,"InvalidPDFException")}}class st extends z{constructor(k){super(k,"MissingPDFException")}}class ct extends z{constructor(k,F){super(k,"UnexpectedResponseException"),this.status=F}}class nt extends z{constructor(k){super(k,"FormatError")}}class G extends z{constructor(k){super(k,"AbortException")}}function A(B){typeof B=="object"&&B?.length!==void 0||Y("Invalid argument for bytesToString");let k=B.length,F=8192;if(k<F)return String.fromCharCode.apply(null,B);let V=[];for(let Q=0;Q<k;Q+=F){let Z=Math.min(Q+F,k),tt=B.subarray(Q,Z);V.push(String.fromCharCode.apply(null,tt))}return V.join("")}function _(B){typeof B!="string"&&Y("Invalid argument for stringToBytes");let k=B.length,F=new Uint8Array(k);for(let V=0;V<k;++V)F[V]=255&B.charCodeAt(V);return F}function I(B){return String.fromCharCode(B>>24&255,B>>16&255,B>>8&255,255&B)}function h(B){let k=Object.create(null);for(let[F,V]of B)k[F]=V;return k}class b{static get isLittleEndian(){return K(this,"isLittleEndian",(function(){let F=new Uint8Array(4);return F[0]=1,new Uint32Array(F.buffer,0,1)[0]===1})())}static get isEvalSupported(){return K(this,"isEvalSupported",(function(){try{return new Function(""),!0}catch{return!1}})())}static get isOffscreenCanvasSupported(){return K(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?K(this,"platform",{isMac:navigator.platform.includes("Mac")}):K(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return K(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}let C=Array.from(Array(256).keys(),(B=>B.toString(16).padStart(2,"0")));class P{static makeHexColor(k,F,V){return`#${C[k]}${C[F]}${C[V]}`}static scaleMinMax(k,F){let V;k[0]?(k[0]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=k[0],F[2]*=k[0],k[3]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=k[3],F[3]*=k[3]):(V=F[0],F[0]=F[1],F[1]=V,V=F[2],F[2]=F[3],F[3]=V,k[1]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=k[1],F[3]*=k[1],k[2]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=k[2],F[2]*=k[2]),F[0]+=k[4],F[1]+=k[5],F[2]+=k[4],F[3]+=k[5]}static transform(k,F){return[k[0]*F[0]+k[2]*F[1],k[1]*F[0]+k[3]*F[1],k[0]*F[2]+k[2]*F[3],k[1]*F[2]+k[3]*F[3],k[0]*F[4]+k[2]*F[5]+k[4],k[1]*F[4]+k[3]*F[5]+k[5]]}static applyTransform(k,F){return[k[0]*F[0]+k[1]*F[2]+F[4],k[0]*F[1]+k[1]*F[3]+F[5]]}static applyInverseTransform(k,F){let V=F[0]*F[3]-F[1]*F[2];return[(k[0]*F[3]-k[1]*F[2]+F[2]*F[5]-F[4]*F[3])/V,(-k[0]*F[1]+k[1]*F[0]+F[4]*F[1]-F[5]*F[0])/V]}static getAxialAlignedBoundingBox(k,F){let V=this.applyTransform(k,F),Q=this.applyTransform(k.slice(2,4),F),Z=this.applyTransform([k[0],k[3]],F),tt=this.applyTransform([k[2],k[1]],F);return[Math.min(V[0],Q[0],Z[0],tt[0]),Math.min(V[1],Q[1],Z[1],tt[1]),Math.max(V[0],Q[0],Z[0],tt[0]),Math.max(V[1],Q[1],Z[1],tt[1])]}static inverseTransform(k){let F=k[0]*k[3]-k[1]*k[2];return[k[3]/F,-k[1]/F,-k[2]/F,k[0]/F,(k[2]*k[5]-k[4]*k[3])/F,(k[4]*k[1]-k[5]*k[0])/F]}static singularValueDecompose2dScale(k){let F=[k[0],k[2],k[1],k[3]],V=k[0]*F[0]+k[1]*F[2],Q=k[0]*F[1]+k[1]*F[3],Z=k[2]*F[0]+k[3]*F[2],tt=k[2]*F[1]+k[3]*F[3],rt=(V+tt)/2,pt=Math.sqrt((V+tt)**2-4*(V*tt-Z*Q))/2,dt=rt+pt||1,lt=rt-pt||1;return[Math.sqrt(dt),Math.sqrt(lt)]}static normalizeRect(k){let F=k.slice(0);return k[0]>k[2]&&(F[0]=k[2],F[2]=k[0]),k[1]>k[3]&&(F[1]=k[3],F[3]=k[1]),F}static intersect(k,F){let V=Math.max(Math.min(k[0],k[2]),Math.min(F[0],F[2])),Q=Math.min(Math.max(k[0],k[2]),Math.max(F[0],F[2]));if(V>Q)return null;let Z=Math.max(Math.min(k[1],k[3]),Math.min(F[1],F[3])),tt=Math.min(Math.max(k[1],k[3]),Math.max(F[1],F[3]));return Z>tt?null:[V,Z,Q,tt]}static#t(k,F,V,Q,Z,tt,rt,pt,dt,lt){if(dt<=0||dt>=1)return;let vt=1-dt,Et=dt*dt,wt=Et*dt,Ct=vt*(vt*(vt*k+3*dt*F)+3*Et*V)+wt*Q,Tt=vt*(vt*(vt*Z+3*dt*tt)+3*Et*rt)+wt*pt;lt[0]=Math.min(lt[0],Ct),lt[1]=Math.min(lt[1],Tt),lt[2]=Math.max(lt[2],Ct),lt[3]=Math.max(lt[3],Tt)}static#e(k,F,V,Q,Z,tt,rt,pt,dt,lt,vt,Et){if(Math.abs(dt)<1e-12){Math.abs(lt)>=1e-12&&this.#t(k,F,V,Q,Z,tt,rt,pt,-vt/lt,Et);return}let wt=lt**2-4*vt*dt;if(wt<0)return;let Ct=Math.sqrt(wt),Tt=2*dt;this.#t(k,F,V,Q,Z,tt,rt,pt,(-lt+Ct)/Tt,Et),this.#t(k,F,V,Q,Z,tt,rt,pt,(-lt-Ct)/Tt,Et)}static bezierBoundingBox(k,F,V,Q,Z,tt,rt,pt,dt){return dt?(dt[0]=Math.min(dt[0],k,rt),dt[1]=Math.min(dt[1],F,pt),dt[2]=Math.max(dt[2],k,rt),dt[3]=Math.max(dt[3],F,pt)):dt=[Math.min(k,rt),Math.min(F,pt),Math.max(k,rt),Math.max(F,pt)],this.#e(k,V,Z,rt,F,Q,tt,pt,3*(3*(V-Z)-k+rt),6*(k-2*V+Z),3*(V-k),dt),this.#e(k,V,Z,rt,F,Q,tt,pt,3*(3*(Q-tt)-F+pt),6*(F-2*Q+tt),3*(Q-F),dt),dt}}let O=null,M=null;function E(B){return O||(O=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,M=new Map([["\uFB05","\u017Ft"]])),B.replaceAll(O,((k,F,V)=>F?F.normalize("NFKC"):M.get(V)))}function L(){if(typeof crypto<"u"&&typeof crypto?.randomUUID=="function")return crypto.randomUUID();let B=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto?.getRandomValues=="function")crypto.getRandomValues(B);else for(let k=0;k<32;k++)B[k]=Math.floor(255*Math.random());return A(B)}let U="pdfjs_internal_id_"}},Qc={};function ji(n){var t=Qc[n];if(t!==void 0)return t.exports;var e=Qc[n]={exports:{}};return nd[n](e,e.exports,ji),e.exports}ys=typeof Symbol=="function"?Symbol("webpack queues"):"__webpack_queues__",en=typeof Symbol=="function"?Symbol("webpack exports"):"__webpack_exports__",sn=typeof Symbol=="function"?Symbol("webpack error"):"__webpack_error__",yr=n=>{n&&n.d<1&&(n.d=1,n.forEach((t=>t.r--)),n.forEach((t=>t.r--?t.r++:t())))},ji.a=(n,t,e)=>{var i;e&&((i=[]).d=-1);var r,o,g,d=new Set,m=n.exports,v=new Promise(((u,a)=>{g=a,o=u}));v[en]=m,v[ys]=u=>(i&&u(i),d.forEach(u),v.catch((a=>{}))),n.exports=v,t((u=>{r=(T=>T.map((l=>{if(l!==null&&typeof l=="object"){if(l[ys])return l;if(l.then){var y=[];y.d=0,l.then((f=>{s[en]=f,yr(y)}),(f=>{s[sn]=f,yr(y)}));var s={};return s[ys]=f=>f(y),s}}var c={};return c[ys]=f=>{},c[en]=l,c})))(u);var a,p=()=>r.map((T=>{if(T[sn])throw T[sn];return T[en]})),x=new Promise((T=>{(a=()=>T(p)).r=0;var l=y=>y!==i&&!d.has(y)&&(d.add(y),y&&!y.d&&(a.r++,y.push(a)));r.map((y=>y[ys](l)))}));return a.r?x:p()}),(u=>(u?g(v[sn]=u):o(m),yr(i)))),i&&i.d<0&&(i.d=0)};ji.d=(n,t)=>{for(var e in t)ji.o(t,e)&&!ji.o(n,e)&&Object.defineProperty(n,e,{enumerable:!0,get:t[e]})};ji.o=(n,t)=>Object.prototype.hasOwnProperty.call(n,t);var St=ji(228),np=(St=globalThis.pdfjsLib=await(globalThis.pdfjsLibPromise=St)).AbortException,rp=St.AnnotationEditorLayer,ap=St.AnnotationEditorParamsType,op=St.AnnotationEditorType,cp=St.AnnotationEditorUIManager,lp=St.AnnotationLayer,hp=St.AnnotationMode,dp=St.CMapCompressionType,up=St.ColorPicker,pp=St.DOMSVGFactory,fp=St.DrawLayer,gp=St.FeatureTest,Zc=St.GlobalWorkerOptions,mp=St.ImageKind,bp=St.InvalidPDFException,yp=St.MissingPDFException,vp=St.OPS,wp=St.Outliner,xp=St.PDFDataRangeTransport,Ap=St.PDFDateString,Sp=St.PDFWorker,Ep=St.PasswordResponses,_p=St.PermissionFlag,Cp=St.PixelsPerInch,Pp=St.RenderingCancelledException,Tp=St.UnexpectedResponseException,kp=St.Util,Rp=St.VerbosityLevel,Mp=St.XfaLayer,Dp=St.build,Ip=St.createValidAbsoluteUrl,Lp=St.fetchData,tl=St.getDocument,Fp=St.getFilenameFromUrl,Op=St.getPdfFilenameFromUrl,Np=St.getXfaPageViewport,Bp=St.isDataScheme,Up=St.isPdfFile,$p=St.noContextMenu,Hp=St.normalizeUnicode,jp=St.renderTextLayer,zp=St.setLayerDimensions,Vp=St.shadow,Wp=St.updateTextLayer,Gp=St.version;ii();Zc.workerSrc=Ne("js/lib/pdf.worker.min.mjs");async function vr(n,t=2){let e=await tl({data:n}).promise,i=[];for(let r=1;r<=e.numPages;r++){let o=await e.getPage(r),g=o.getViewport({scale:t}),d=document.createElement("canvas"),m=d.getContext("2d");d.width=g.width,d.height=g.height,await o.render({canvasContext:m,viewport:g}).promise,i.push(d.toDataURL("image/jpeg",.82))}return i}ii();Js();var zi=class extends Be{async recognizeImageText(t,e={}){return bs(t,e)}async recognizeDocumentPages(t,e={}){return Hi(t,e)}async getOcrWorker(t="eng",e=null){return ms(t,e)}async terminateOcrWorker(){return hi()}};var Vi=class extends Ue{async exportDocumentAsPdf(t,e,i={}){return tn(t,e,i)}async renderPdfPagesToDataUrls(t){let e=t instanceof ArrayBuffer?t:await t.arrayBuffer();return vr(e)}};var He=class{async connect(t={}){throw new Error("SyncPort.connect() must be implemented by adapter")}async disconnect(){throw new Error("SyncPort.disconnect() must be implemented by adapter")}};var nn=class extends He{#t=null;#e=null;#i=null;constructor(t=null,e=null){super(),this.#e=t,this.#i=e}async connect(t={}){let e=t.repo||this.#e,i=t.onStateChange||this.#i;return this.#t=new di(e,i),this.#t}async disconnect(){this.#t&&typeof this.#t.destroy=="function"&&(this.#t.destroy(),this.#t=null)}};var rn=class extends He{async connect(){return{step:"disconnected",peerId:null,destroy:()=>{}}}async disconnect(){}};ni("export",ja);ni("ocr",new zi);ni("sync",di);ni("pdf",new Vi);ni("imageProcessor",new $e);typeof window<"u"&&(window.Copio=wr);var Xf=wr;export{vc as BUILD_DATE,Vt as COPIO_EVENTS,$e as Canvas2DAdapter,Qs as CopioDocOcrDialog,Oi as CopioEngine,zs as CopioScanner,Zs as CopioSyncDialog,ti as DocRepository,Us as Document,_e as ImageProcessorPort,Se as IndexedDbStorageAdapter,br as LicenseManager,qe as MemoryStorageAdapter,Li as NullImageProcessorAdapter,de as NullOcrAdapter,Ee as NullPdfAdapter,rn as NullSyncAdapter,Be as OcrPort,Si as OpfsStorageAdapter,Fi as Page,Vi as PdfKitAdapter,Ue as PdfPort,nn as PeerJsAdapter,Ys as SUPPORTED_LANGUAGES,$s as ScanSession,he as StoragePort,di as SyncManager,He as SyncPort,zi as TesseractWasmAdapter,wc as VERSION,ur as adoptScannerStyles,Pa as clearNotifications,ns as createDefaultAdapter,Xf as default,lr as dispatchCopioEvent,ds as docRepository,Ha as exportDocumentAsImages,tn as exportDocumentAsPdf,Jn as extractExif,Qn as fileToBase64,ir as getAssetBase,ai as getContainer,ya as getCroppedSrc,ms as getOcrWorker,si as getRegisteredService,dr as getScannerStyleSheet,cr as hasActiveEdits,yc as loadCropper,nr as loadJsZip,sr as loadPdfKit,rr as loadPeerJs,ar as loadQrCode,ei as loadScript,or as loadTesseract,us as normalizeEditStack,Dt as notify,Un as probeOpfs,Di as randomId,Hi as recognizeDocumentPages,bs as recognizeImageText,ni as registerService,vr as renderPdfPagesToDataUrls,Ne as resolveAssetUrl,ba as rotateSrc,js as scannerCss,Ii as setAssetBase,ri as setContainer,hi as terminateOcrWorker,ma as thresholdSrc};
|
|
2612
1535
|
/**
|
|
2613
1536
|
* @license
|
|
2614
1537
|
* Copyright 2019 Google LLC
|