@copio/sdk 0.1.1 → 0.1.3
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/LICENSE +661 -0
- package/LICENSE-COMMERCIAL.md +43 -0
- package/README.md +6 -1
- package/THIRD_PARTY_NOTICES.md +416 -0
- package/dist/adapters/image/canvas2d-adapter.js +1 -1
- package/dist/adapters/image/index.js +1 -1
- package/dist/adapters/image/null-image-processor-adapter.js +1 -1
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/indexeddb-adapter.js +1 -1
- package/dist/adapters/memory-adapter.js +1 -1
- package/dist/adapters/ocr/index.js +1 -1
- package/dist/adapters/ocr/null-ocr-adapter.js +1 -1
- package/dist/adapters/ocr/tesseract-wasm-adapter.js +1 -1
- package/dist/adapters/pdf/index.js +1 -1
- package/dist/adapters/pdf/null-pdf-adapter.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/adapters/storage/memory-adapter.js +1 -1
- package/dist/adapters/sync/index.js +1 -1
- package/dist/adapters/sync/null-sync-adapter.js +1 -1
- package/dist/adapters/sync/peerjs-adapter.js +1 -1
- package/dist/cdn.js +106 -249
- package/dist/{chunk-A5G52Q2W.js → chunk-2AB5L3Y2.js} +2 -2
- package/dist/{chunk-DGGK5KEX.js → chunk-4ICUYKSR.js} +2 -2
- package/dist/{chunk-K7RTGT3Q.js → chunk-4XWSVHFW.js} +69 -198
- package/dist/{chunk-IUBYFIV6.js → chunk-4YYY7PHH.js} +2 -2
- package/dist/{chunk-N7Q34F2P.js → chunk-534NMCRQ.js} +4 -4
- package/dist/{chunk-UCV3MQ6I.js → chunk-5KUKBKWL.js} +1 -1
- package/dist/{chunk-E7JYVRJA.js → chunk-5OTO5WFV.js} +2 -2
- package/dist/{chunk-N4R55VRR.js → chunk-6DSLE3AY.js} +1 -1
- package/dist/chunk-DIU5BGU5.js +2 -0
- package/dist/chunk-DOKG4LX2.js +2 -0
- package/dist/{chunk-B2EK6INF.js → chunk-DY5ZSP4Q.js} +2 -2
- package/dist/chunk-FAVTIE3M.js +8 -0
- package/dist/chunk-FQRADJY6.js +2 -0
- package/dist/chunk-IH2AI54D.js +2 -0
- package/dist/{chunk-PVNRK4OH.js → chunk-J7HWZNIP.js} +2 -2
- package/dist/{chunk-SH4P4XSZ.js → chunk-KH5JE65X.js} +2 -2
- package/dist/chunk-MEE2NNYB.js +2 -0
- package/dist/{chunk-KIMVF5UG.js → chunk-NEEWG3OP.js} +1 -1
- package/dist/{chunk-YHLOPPXM.js → chunk-O6FQFVKY.js} +1 -1
- package/dist/chunk-RDCHJL6F.js +2 -0
- package/dist/{chunk-B7HT2X67.js → chunk-U3V3VZGO.js} +2 -2
- package/dist/{chunk-HN3336JN.js → chunk-ULTSZWZO.js} +1 -1
- package/dist/{chunk-BKZEOOH4.js → chunk-WETG2JD7.js} +2 -2
- package/dist/{chunk-V2FP4EEH.js → chunk-YNY65JUJ.js} +1 -1
- package/dist/chunk-ZT72PD2C.js +2 -0
- package/dist/core.js +1 -1
- package/dist/custom-elements.json +672 -510
- package/dist/export.js +1 -1
- package/dist/index.js +11 -19
- package/dist/ocr.js +1 -1
- package/dist/scanner.js +88 -217
- package/dist/sync.js +1 -1
- package/dist/types/js/adapters/storage/blob-store.d.ts +48 -0
- package/dist/types/js/adapters/storage/index.d.ts +11 -4
- package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +46 -9
- package/dist/types/js/adapters/storage/memory-adapter.d.ts +7 -0
- package/dist/types/js/adapters/storage/opfs-adapter.d.ts +160 -0
- package/dist/types/js/adapters/storage/storage-port.d.ts +7 -0
- package/dist/types/js/components/copio-header.d.ts +4 -0
- package/dist/types/js/routes/doc/copio-carousel.d.ts +1 -2
- package/dist/types/js/routes/doc/copio-images.d.ts +0 -4
- package/dist/types/js/routes/home/copio-row.d.ts +2 -2
- package/dist/types/js/routes/ocr/copio-doc-ocr-dialog.d.ts +0 -2
- package/dist/types/js/services/doc-repository.d.ts +1 -0
- package/dist/types/js/services/export-utils.d.ts +8 -12
- package/dist/types/js/services/ocr-service.d.ts +2 -1
- package/dist/types/js/utils/module-loader.d.ts +0 -6
- package/dist/types/js/utils/utils.d.ts +5 -3
- package/dist/types/sdk/core.d.ts +13 -2
- package/dist/types/sdk/events.d.ts +4 -4
- package/dist/types/sdk/index.d.ts +3 -3
- package/dist/types/sdk/models.d.ts +66 -0
- package/dist/types/sdk/styles.d.ts +1 -1
- package/dist/types/sdk/version.d.ts +1 -1
- package/package.json +27 -4
- package/sdk/cdn.js +1 -0
- package/sdk/core.js +60 -0
- package/sdk/events.js +3 -2
- package/sdk/index.js +4 -3
- package/sdk/license.js +1 -0
- package/sdk/models.js +79 -3
- package/sdk/scanner.js +45 -7
- package/sdk/styles.js +12 -5
- package/sdk/sync.js +1 -0
- package/sdk/version.js +2 -1
- package/dist/chunk-36F637QU.js +0 -2
- package/dist/chunk-4JPEWIT4.js +0 -2
- package/dist/chunk-B5BEYYR2.js +0 -8
- package/dist/chunk-G65H4ZTJ.js +0 -2
- package/dist/chunk-K6YP7EET.js +0 -8
- package/dist/chunk-LI54F6PA.js +0 -2
- package/dist/chunk-OI4WCW7E.js +0 -2
- package/dist/chunk-QPUCXOOR.js +0 -2
package/dist/cdn.js
CHANGED
|
@@ -1,16 +1,22 @@
|
|
|
1
|
-
var td=Object.defineProperty;var Es=(s,t,e)=>()=>{if(e)throw e[0];try{return s&&(t=s(s=0)),t}catch(i){throw e=[i],i}};var yi=(s,t)=>{for(var e in t)td(s,e,{get:t[e],enumerable:!0})};var nl={};yi(nl,{Path2D:()=>Lu,createCanvas:()=>Ru,default:()=>Mu});var Mu,Ru,Lu,rl=Es(()=>{Mu={},Ru=()=>null,Lu=globalThis.Path2D||class{}});var vh={};yi(vh,{Path2D:()=>Nu,createCanvas:()=>Ou,default:()=>Fu});var Fu,Ou,Nu,wh=Es(()=>{Fu={},Ou=()=>null,Nu=globalThis.Path2D||class{}});var xh={};yi(xh,{Path2D:()=>Uu,createCanvas:()=>$u,default:()=>Bu});var Bu,$u,Uu,Ah=Es(()=>{Bu={},$u=()=>null,Uu=globalThis.Path2D||class{}});var Sh={};yi(Sh,{Path2D:()=>ju,createCanvas:()=>Hu,default:()=>zu});var zu,Hu,ju,Eh=Es(()=>{zu={},Hu=()=>null,ju=globalThis.Path2D||class{}});var Ch={};yi(Ch,{Path2D:()=>Wu,createCanvas:()=>Gu,default:()=>Vu});var Vu,Gu,Wu,_h=Es(()=>{Vu={},Gu=()=>null,Wu=globalThis.Path2D||class{}});var kh={};yi(kh,{Path2D:()=>Ku,createCanvas:()=>Xu,default:()=>qu});var qu,Xu,Ku,Th=Es(()=>{qu={},Xu=()=>null,Ku=globalThis.Path2D||class{}});var Oo={};yi(Oo,{BUILD_DATE:()=>qc,COPIO_EVENTS:()=>te,Canvas2DAdapter:()=>li,CopioAddEditDialog:()=>qn,CopioCarousel:()=>Wn,CopioDocOcrDialog:()=>ir,CopioEngine:()=>cs,CopioHeader:()=>Kn,CopioImages:()=>$n,CopioLoader:()=>Yn,CopioRow:()=>Xn,CopioScanner:()=>Zn,CopioSyncDialog:()=>sr,DocRepository:()=>_i,Document:()=>En,ImageProcessorPort:()=>qe,IndexedDbStorageAdapter:()=>Ji,LicenseManager:()=>Fo,MemoryStorageAdapter:()=>vi,NullImageProcessorAdapter:()=>as,NullOcrAdapter:()=>Pe,NullPdfAdapter:()=>We,NullSyncAdapter:()=>or,OcrPort:()=>oi,Page:()=>ls,PdfKitAdapter:()=>vs,PdfPort:()=>ai,PeerJsAdapter:()=>rr,SUPPORTED_LANGUAGES:()=>Lo,ScanSession:()=>Cn,StoragePort:()=>Ue,SyncManager:()=>Ui,SyncPort:()=>ui,TesseractWasmAdapter:()=>ys,VERSION:()=>Xc,adoptScannerStyles:()=>Mo,clearNotifications:()=>ol,createDefaultAdapter:()=>Ls,dispatchCopioEvent:()=>lo,docRepository:()=>Fa,exportDocumentAsImages:()=>xl,exportDocumentAsMarkdown:()=>Al,exportDocumentAsPdf:()=>nr,extractExif:()=>zs,fileToBase64:()=>Hs,getAssetBase:()=>eo,getContainer:()=>Fi,getCroppedSrc:()=>Ra,getOcrWorker:()=>tr,getRegisteredService:()=>Ti,getScannerStyleSheet:()=>Io,hasActiveEdits:()=>ao,loadCropper:()=>io,loadJsZip:()=>so,loadMarked:()=>ki,loadPdfKit:()=>Vs,loadPeerJs:()=>no,loadQrCode:()=>ro,loadScript:()=>ri,loadTesseract:()=>oo,normalizeEditStack:()=>_n,notify:()=>Pt,randomId:()=>we,recognizeDocumentPages:()=>en,recognizeImageText:()=>er,registerService:()=>Pi,renderPdfPagesToDataUrls:()=>Ri,resolveAssetUrl:()=>ni,rotateSrc:()=>Ma,scannerCss:()=>Qn,setAssetBase:()=>os,setContainer:()=>Li,terminateOcrWorker:()=>bs,thresholdSrc:()=>Ia});var Ue=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 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 vi=class extends Ue{#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 savePage(t,e,i){this.#e.set(`${t}/${e}`,i);let n=this.#t.get(t);if(n){let o=n.pages.findIndex(l=>l.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 l=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};n.pages.push(l)}}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 Si=s=>typeof s;var Yl=Si(""),ed=Si(!0),Jl=Si(0),id=Si(Si),xr="type",Hi="default",Ko="Listener",Hl="Result",Yo="add",ji="Has",hn="Ids",Ai="Table",jl=Ai+"s",sd=Ai+hn,Ts="Row",Ql=Ts+"Count",Zl=Ts+hn,nd="Sorted"+Ts+hn,an="Cell",Cr=an+hn,_r="Value",Vl=_r+"s",rd=_r+hn,Bt=s=>""+s;var od=(s,t="",e)=>s.split(t,e),Jo=globalThis,Ir=Math,jo=Ir.max,Vo=Ir.min,ad=Ir.floor,tc=isFinite,St=s=>s==null,$t=(s,t,e)=>St(s)?e?.():t(s),ec=s=>s==Yl||s==ed,ld=s=>Si(s)==Yl,ze=s=>Si(s)==id,Ps=s=>Array.isArray(s),Qo=(s,t,e)=>s.slice(t,e),Ce=s=>s.length,ic=()=>{};var Go=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},Zo=(s,t)=>s.includes(t),kr=(s,t)=>s.every(t),sc=(s,t)=>Ce(s)===Ce(t)&&kr(s,((e,i)=>t[i]===e)),Gl=(s,t)=>kr(s,((e,i)=>i==0||t(s[i-1],e)<=0)),ta=(s,t)=>s.sort(t),ve=(s,t)=>s.forEach(t),Wi=(s,t)=>s.map(t),Wl=s=>nc(s,((t,e)=>t+e),0),ln=s=>Ce(s)==0,nc=(s,t,e)=>s.reduce(t,e),ye=(s,...t)=>s.push(...t),ql=s=>s.pop(),rc=s=>s.shift(),_s=s=>{let t=Si(s);return ec(t)||t==Jl&&tc(s)?t:void 0};var Tr=(s,t,e,i,n)=>St(n)?s.delCell(t,e,i,!0):s.setCell(t,e,i,n),ea=(s,t,e)=>St(e)?s.delValue(t):s.setValue(t,e),ra=s=>t=>nc(Ds(t),((e,i)=>e+s(i)),0),Is=s=>s?.size??0,qi=ra(Is),Ze=ra(qi),Wo=ra(Ze),Ht=(s,t)=>s?.has(t)??!1,vt=s=>St(s)||Is(s)==0,Ds=s=>[...s?.values()??[]],ks=s=>s.clear(),yt=(s,t)=>s?.forEach(t),je=(s,t)=>s?.delete(t),Ei=Object,Xl=s=>Ei.getPrototypeOf(s),cd=Ei.isFrozen,oc=Ei.entries,Pr=s=>!St(s)&&$t(Xl(s),(t=>t==Ei.prototype||St(Xl(t))),(()=>!0)),hd=Ei.keys,Ms=Ei.freeze,dd=(s=[])=>Ei.fromEntries(s),on=(s,t)=>t in s,ac=(s,t)=>(delete s[t],s),ud=(s,t)=>ve(oc(s),(([e,i])=>t(i,e))),Qe=(s,t)=>dd(((e,i)=>Wi(oc(e),(([n,o])=>i(o,n))))(s,((e,i)=>[i,t(e,i)]))),He=s=>Pr(s)&&(t=>Ce(hd(t)))(s)==0;var wi=(s,t,e,i=0)=>St(s)||!Pr(s)||!i&&He(s)||cd(s)?(e?.(),!1):(ud(s,((n,o)=>{t(n,o)||ac(s,o)})),!!i||!He(s)),ft=s=>new Map(s),Gi=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)?(je(s,t),s):s?.set(t,e),zt=(s,t,e,i)=>(Ht(s,t)?i?.(ht(s,t)):bt(s,t,e()),ht(s,t)),Vi=(s,t,e,i=bt)=>(Qe(t,((n,o)=>e(s,o,n))),Yt(s,(n=>on(t,n)?0:i(s,n))),s),be=(s,t,e,i)=>{let n={};return yt(s,((o,l)=>{if(!e?.(o,l)){let h=t?t(o,l):o;i?.(h)||(n[l]=h)}})),n},ia=(s,t,e)=>be(s,(i=>be(i,t,e)),vt,He),Ar=(s,t,e)=>be(s,(i=>ia(i,t,e)),vt,He),xi=(s,t)=>{let e=ft();return yt(s,((i,n)=>e.set(n,t?.(i)??i))),e},sa=s=>xi(s,xi),qo=s=>xi(s,sa),cn=(s,t,e,i,n=0)=>$t((e?zt: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 l=cn(o,t,e,i,n+1);return vt(o)&&bt(s,t[n]),l})),Jt=s=>new Set(Ps(s)||St(s)?s:[s]),Vt=(s,t)=>s?.add(t),Mr=(s,t,e,i,n)=>{let o=s.hasRow,l=ft(),h=ft(),g=ft(),m=ft(),d=ft(),a=ft(),f=(y,r,...c)=>{let b=zt(a,y,Jt);return ve(c,(w=>Vt(b,w)&&r&&s.callListener(w))),c},A=(y,...r)=>$t(ht(a,y),(c=>{ve(ln(r)?Ds(c):r,(b=>{s.delListener(b),je(c,b)})),vt(c)&&bt(a,y)})),C=(y,r)=>{bt(l,y,r),Ht(h,y)||(bt(h,y,t()),bt(m,y,ft()),bt(d,y,ft()),n(g))},u=y=>{bt(l,y),bt(h,y),bt(m,y),bt(d,y),A(y),n(g)};return[()=>s,()=>Gi(l),y=>Yt(h,y),y=>Ht(h,y),y=>ht(l,y),y=>ht(h,y),(y,r)=>bt(h,y,r),C,(y,r,c,b,w)=>{C(y,r);let P=ft(),E=ft(),I=ht(m,y),N=ht(d,y),z=X=>{let it=j=>s.getCell(r,X,j),at=ht(I,X),K=o(r,X)?e(b(it,X)):void 0;if(at===K||Ps(at)&&Ps(K)&&sc(at,K)||bt(P,X,[at,K]),!St(w)){let j=ht(N,X),G=o(r,X)?w(it,X):void 0;j!=G&&bt(E,X,G)}},H=X=>{c((()=>{yt(P,(([,it],at)=>bt(I,at,it))),yt(E,((it,at)=>bt(N,at,it)))}),P,E,I,N,X),ks(P),ks(E)};Yt(I,z),s.hasTable(r)&&ve(s.getRowIds(r),(X=>{Ht(I,X)||z(X)})),H(!0),A(y),f(y,0,s.addRowListener(r,null,((X,it,at)=>z(at))),s.addTableListener(r,(()=>H())))},u,y=>i(y,g),()=>Yt(a,u),f,A]},Dr=(s,t)=>ld(s)?e=>e(s):s??(()=>t??""),dn=(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}},pd=/^\d+$/,lc=()=>{let s=[],t=0;return[e=>(e?rc(s):null)??""+t++,e=>{pd.test(e)&&Ce(s)<1e3&&ye(s,e)}]},un=s=>{let t,[e,i]=lc(),n=ft();return[(o,l,h,g=[],m=()=>[])=>{t??=s();let d=e(1);return bt(n,d,[o,l,h,g,m]),Vt(cn(l,h??[""],Jt),d),d},(o,l,...h)=>ve(((g,m=[""])=>{let d=[],a=(f,A)=>A==Ce(m)?ye(d,f):m[A]===null?yt(f,(C=>a(C,A+1))):ve([m[A],null],(C=>a(ht(f,C),A+1)));return a(g,0),d})(o,l),(g=>yt(g,(m=>ht(n,m)[0](t,...l??[],...h))))),o=>$t(ht(n,o),(([,l,h])=>(cn(l,h??[""],void 0,(g=>(je(g,o),vt(g)?1:0))),bt(n,o),i(o),h))),o=>$t(ht(n,o),(([l,,h=[],g,m])=>{let d=(...a)=>{let f=Ce(a);f==Ce(h)?l(t,...a,...m(a)):St(h[f])?ve(g[f]?.(...a)??[],(A=>d(...a,A))):d(...a,h[f])};d()}))]},Ip=dn((s=>{let t,e,i,n=100,o=ft(),l=ft(),h=1,g=ft(),m=ft(),[d,a,f]=un((()=>G)),A=ft(),C=ft(),u=[],y=[],r=(Y,et)=>{h=0,s.transaction((()=>{let[rt,ct]=ht(A,et);yt(rt,((st,W)=>yt(st,((x,T)=>yt(x,((R,p)=>Tr(s,W,T,p,R[Y]))))))),yt(ct,((st,W)=>ea(s,W,st[Y])))})),h=1},c=Y=>{bt(A,Y),bt(C,Y),a(m,[Y])},b=(Y,et)=>ve(((rt,ct)=>rt.splice(0,ct))(Y,et??Ce(Y)),c),w=()=>b(u,Ce(u)-n),P=()=>$t(t,(()=>{ye(u,t),w(),b(y),t=void 0,i=1})),E=()=>{t=ql(u),i=1},I,N,z=(Y="")=>(St(t)&&(t=""+e++,bt(A,t,[o,l]),K(t,Y),o=ft(),l=ft(),i=1),t),H=()=>{ln(u)||(((Y,...et)=>{Y.unshift(...et)})(y,z()),r(0,t),t=ql(u),i=1)},X=()=>{ln(y)||(ye(u,t),t=rc(y),r(1,t),i=1)},it=()=>{i&&(a(g),i=0)},at=Y=>{let et=z(Y);return it(),et},K=(Y,et)=>(j(Y)&&ht(C,Y)!==et&&(bt(C,Y,et),a(m,[Y])),G),j=Y=>Ht(A,Y),G={setSize:Y=>(n=Y,w(),G),addCheckpoint:at,setCheckpoint:K,getStore:()=>s,getCheckpointIds:()=>[[...u],t,[...y]],forEachCheckpoint:Y=>Yt(C,Y),hasCheckpoint:j,getCheckpoint:Y=>ht(C,Y),goBackward:()=>(H(),it(),G),goForward:()=>(X(),it(),G),goTo:Y=>{let et=Zo(u,Y)?H:Zo(y,Y)?X:null;for(;!St(et)&&Y!=t;)et();return it(),G},addCheckpointIdsListener:Y=>d(Y,g),addCheckpointListener:(Y,et)=>d(et,m,[Y]),delListener:Y=>(f(Y),G),clear:()=>(b(u),b(y),St(t)||c(t),t=void 0,e=0,at(),G),clearForward:()=>(ln(y)||(b(y),a(g)),G),destroy:()=>{s.delListener(I),s.delListener(N)},getListenerStats:()=>({checkpointIds:qi(g),checkpoint:qi(m)}),_registerListeners:()=>{I=s.addCellListener(null,null,null,((Y,et,rt,ct,st,W)=>{if(h){P();let x=zt(o,et,ft),T=zt(x,rt,ft),R=zt(T,ct,(()=>[W,void 0]));R[1]=st,R[0]===st&&vt(bt(T,ct))&&vt(bt(x,rt))&&vt(bt(o,et))&&E(),it()}})),N=s.addValueListener(null,((Y,et,rt,ct)=>{if(h){P();let st=zt(l,et,(()=>[ct,void 0]));st[1]=rt,st[0]===rt&&vt(bt(l,et))&&E(),it()}}))}};return Ms(G.clear())}),(s=>s._registerListeners())),fd=od("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),Mp=ft(Wi(fd,((s,t)=>[s,t])));var Rp=Jo.crypto?s=>Jo.crypto.getRandomValues(s):s=>Wi(s,(()=>ad(256*Ir.random())));var gd=JSON.stringify,Xo=JSON.parse,Cs=s=>gd(s,((t,e)=>{return i=Map,e instanceof i?Ei.fromEntries([...e]):e;var i})),Lp=new Jo.TextEncoder;var Fp=2**36,Op=2**30,Np=2**24,Bp=2**18;var cc=(s,t)=>(s??0)<(t??0)?-1:1,$p=dn((s=>{let t=ft(),e=ft(),[i,n,o]=un((()=>c)),[l,h,g,m,d,a,f,,A,C,u,y]=Mr(s,ft,(b=>St(b)?"":Ps(b)?Wi(b,Bt):Bt(b)),i,n),r=(b,w,P)=>{let E=d(b);yt(P,((I,N)=>w(N,(z=>yt(I,(H=>z(H,(X=>s.forEachCell(E,H,X)))))))))},c={setIndexDefinition:(b,w,P,E,I,N=cc)=>{let z=St(I)?void 0:([H],[X])=>I(H,X);return A(b,w,((H,X,it,at,K,j)=>{let G=0,Y=Jt(),et=Jt(),rt=a(b);if(yt(X,(([ct,st],W)=>{let x=Jt(ct),T=Jt(st);yt(x,(R=>je(T,R)?je(x,R):0)),yt(x,(R=>{Vt(Y,R),$t(ht(rt,R),(p=>{je(p,W),vt(p)&&(bt(rt,R),G=1)}))})),yt(T,(R=>{Vt(Y,R),Ht(rt,R)||(bt(rt,R,Jt()),G=1),Vt(ht(rt,R),W),St(E)||Vt(et,R)}))})),H(),vt(K)||(j?Yt(rt,(ct=>Vt(et,ct))):Yt(it,(ct=>$t(ht(at,ct),(st=>ve(Ps(st)?st:[st],(W=>Vt(et,W))))))),yt(et,(ct=>{let st=(x,T)=>N(ht(K,x),ht(K,T),ct),W=[...ht(rt,ct)];Gl(W,st)||(bt(rt,ct,Jt(ta(W,st))),Vt(Y,ct))}))),(G||j)&&!St(z)){let ct=[...rt];Gl(ct,z)||(f(b,ft(ta(ct,z))),G=1)}G&&n(t,[b]),yt(Y,(ct=>n(e,[b,ct])))}),Dr(P),$t(E,Dr)),c},delIndexDefinition:b=>(C(b),c),getStore:l,getIndexIds:h,forEachIndex:b=>g(((w,P)=>b(w,(E=>r(w,E,P))))),forEachSlice:(b,w)=>r(b,w,a(b)),hasIndex:m,hasSlice:(b,w)=>Ht(a(b),w),getTableId:d,getSliceIds:b=>Gi(a(b)),getSliceRowIds:(b,w)=>Ds(ht(a(b),w)),addIndexIdsListener:u,addSliceIdsListener:(b,w)=>i(w,t,[b]),addSliceRowIdsListener:(b,w,P)=>i(P,e,[b,w]),delListener:b=>(o(b),c),destroy:y,getListenerStats:()=>({sliceIds:qi(t),sliceRowIds:Ze(e)})};return Ms(c)}));var Sr=s=>[s,s],qt=(s,t=qi)=>t(s[0])+t(s[1]),Xt=()=>[ft(),ft()],Kl=s=>[...s],Er=([s,t])=>s===t,rn=(s,t,e)=>bt(s,t,ht(s,t)==-e?void 0:e),pn=()=>{let s,t,e=!1,i=!1,n=0,o=[],l=ft(),h=ft(),g=ft(),m=ft(),d=ft(),a=ft(),f=ft(),A=ft(),C=ft(),u=ft(),y=ft(),r=ft(),c=ft(),b=ft(),w=Jt(),P=ft(),E=ft(),I=ft(),N=ft(),z=Xt(),H=Xt(),X=Xt(),it=Xt(),at=Xt(),K=Xt(),j=Xt(),G=Xt(),Y=Xt(),et=Xt(),rt=Xt(),ct=Xt(),st=Xt(),W=Xt(),x=Xt(),T=Xt(),R=Xt(),p=Xt(),v=Xt(),_=Xt(),k=Xt(),O=Xt(),M=ft(),S=Xt(),[L,U,$,D]=un((()=>de)),F=B=>{if(!wi(B,((J,ot)=>Zo([xr,Hi],ot))))return!1;let q=B[xr];return!(!ec(q)&&q!=Jl)&&(_s(B[Hi])!=q&&ac(B,Hi),!0)},V=Ps,Q=(B,q)=>(!s||Ht(y,q)||Be(q))&&wi(B,((J,ot)=>Z(q,ot,J)),(()=>Be(q))),Z=(B,q,J,ot)=>wi(ot?J:dt(J,B,q),((ut,mt)=>$t(tt(B,q,mt,ut),(At=>(J[mt]=At,!0)),(()=>!1))),(()=>Be(B,q))),tt=(B,q,J,ot)=>s?$t(ht(ht(y,B),J),(ut=>_s(ot)!=ut[xr]?Be(B,q,J,ot,ut[Hi]):ot),(()=>Be(B,q,J,ot))):St(_s(ot))?Be(B,q,J,ot):ot,nt=(B,q)=>wi(q?B:lt(B),((J,ot)=>$t(pt(ot,J),(ut=>(B[ot]=ut,!0)),(()=>!1))),(()=>zi())),pt=(B,q)=>t?$t(ht(c,B),(J=>_s(q)!=J[xr]?zi(B,q,J[Hi]):q),(()=>zi(B,q))):St(_s(q))?zi(B,q):q,dt=(B,q,J)=>($t(ht(r,q),(([ot,ut])=>{yt(ot,((mt,At)=>{on(B,At)||(B[At]=mt)})),yt(ut,(mt=>{on(B,mt)||Be(q,J,mt)}))})),B),lt=B=>(t&&(yt(b,((q,J)=>{on(B,J)||(B[J]=q)})),yt(w,(q=>{on(B,q)||zi(q)}))),B),wt=B=>Vi(y,B,((q,J,ot)=>{let ut=ft(),mt=Jt();Vi(zt(y,J,ft),ot,((At,Dt,Rt)=>{bt(At,Dt,Rt),$t(Rt[Hi],(Je=>bt(ut,Dt,Je)),(()=>Vt(mt,Dt)))})),bt(r,J,[ut,mt])}),((q,J)=>{bt(y,J),bt(r,J)})),Tt=B=>Vi(c,B,((q,J,ot)=>{bt(c,J,ot),$t(ot[Hi],(ut=>bt(b,J,ut)),(()=>Vt(w,J)))}),((q,J)=>{bt(c,J),bt(b,J),je(w,J)})),xt=B=>He(B)?br():gr(B),It=B=>Vi(I,B,((q,J,ot)=>Lt(J,ot)),((q,J)=>pi(J))),Lt=(B,q)=>Vi(zt(I,B,(()=>(gi(B,1),bt(P,B,lc()),bt(E,B,ft()),ft()))),q,((J,ot,ut)=>Ut(B,J,ot,ut)),((J,ot)=>fi(B,J,ot))),Ut=(B,q,J,ot,ut)=>Vi(zt(q,J,(()=>(ws(B,J,1),ft()))),ot,((mt,At,Dt)=>jt(B,J,mt,At,Dt)),((mt,At)=>le(B,q,J,mt,At,ut))),jt=(B,q,J,ot,ut)=>{Ht(J,ot)||Me(B,q,ot,1);let mt=ht(J,ot);ut!==mt&&(ne(B,q,ot,mt,ut),bt(J,ot,ut))},he=(B,q,J,ot,ut)=>$t(ht(q,J),(mt=>jt(B,J,mt,ot,ut)),(()=>Ut(B,q,J,dt({[ot]:ut},B,J)))),Se=B=>He(B)?yr():mr(B),Ne=B=>Vi(N,B,((q,J,ot)=>Te(J,ot)),((q,J)=>oe(J))),Te=(B,q)=>{Ht(N,B)||ar(B,1);let J=ht(N,B);q!==J&&(xs(B,J,q),bt(N,B,q))},Ie=B=>ht(I,B)??Lt(B,{}),pi=B=>Lt(B,{}),fi=(B,q,J)=>{let[,ot]=ht(P,B);ot(J),Ut(B,q,J,{},!0)},le=(B,q,J,ot,ut,mt)=>{let At=ht(ht(r,B)?.[0],ut);if(!St(At)&&!mt)return jt(B,J,ot,ut,At);let Dt=Rt=>{ne(B,J,Rt,ht(ot,Rt)),Me(B,J,Rt,-1),bt(ot,Rt)};St(At)?Dt(ut):Yt(ot,Dt),vt(ot)&&(ws(B,J,-1),vt(bt(q,J))&&(gi(B,-1),bt(I,B),bt(P,B),bt(E,B)))},oe=B=>{let q=ht(b,B);if(!St(q))return Te(B,q);xs(B,ht(N,B)),ar(B,-1),bt(N,B)},gi=(B,q)=>rn(l,B,q),ws=(B,q,J)=>rn(zt(m,B,ft),q,J)&&bt(g,B,zt(g,B,(()=>0))+J),Me=(B,q,J,ot)=>{let ut=ht(E,B),mt=ht(ut,J)??0;(mt==0&&ot==1||mt==1&&ot==-1)&&rn(zt(h,B,ft),J,ot),bt(ut,J,mt!=-ot?mt+ot:null),rn(zt(zt(d,B,ft),q,ft),J,ot)},ne=(B,q,J,ot,ut)=>{zt(zt(zt(a,B,ft),q,ft),J,(()=>[ot,0]))[1]=ut,o[3]?.(B,q,J,ut)},ar=(B,q)=>rn(f,B,q),xs=(B,q,J)=>{zt(A,B,(()=>[q,0]))[1]=J,o[4]?.(B,J)},Be=(B,q,J,ot,ut)=>(ye(zt(zt(zt(C,B,ft),q,ft),J,(()=>[])),ot),ut),zi=(B,q,J)=>(ye(zt(u,B,(()=>[])),q),J),$e=(B,q,J)=>$t(ht(ht(ht(a,B),q),J),(([ot,ut])=>[!0,ot,ut]),(()=>[!1,...Sr(dr(B,q,J))])),lr=B=>$t(ht(A,B),(([q,J])=>[!0,q,J]),(()=>[!1,...Sr(ur(B))])),As=B=>vt(C)||vt(T[B])?0:yt(B?qo(C):C,((q,J)=>yt(q,((ot,ut)=>yt(ot,((mt,At)=>U(T[B],[J,ut,At],mt))))))),mi=B=>vt(u)||vt(R[B])?0:yt(B?xi(u):u,((q,J)=>U(R[B],[J],q))),pe=(B,q,J,ot)=>{if(!vt(B))return U(q,ot,(()=>be(B))),Yt(B,((ut,mt)=>U(J,[...ot??[],ut],mt==1))),1},cr=B=>{let q=pr();q!=e&&U(z[B],void 0,q);let J=vt(et[B]),ot=vt(st[B])&&vt(W[B])&&vt(Y[B])&&vt(rt[B])&&vt(K[B])&&vt(j[B])&&vt(G[B])&&J&&vt(X[B])&&vt(it[B]),ut=vt(x[B])&&vt(ct[B])&&vt(at[B])&&vt(H[B]);if(!ot||!ut){let mt=B?[xi(l),sa(h),xi(g),sa(m),qo(d),qo(a)]:[l,h,g,m,d,a];if(!ot){pe(mt[0],X[B],it[B]),yt(mt[1],((Dt,Rt)=>pe(Dt,K[B],j[B],[Rt]))),yt(mt[2],((Dt,Rt)=>{Dt!=0&&U(G[B],[Rt],kl(Rt))}));let At=Jt();yt(mt[3],((Dt,Rt)=>{pe(Dt,Y[B],rt[B],[Rt])&&!J&&(U(et[B],[Rt,null]),Vt(At,Rt))})),J||yt(mt[5],((Dt,Rt)=>{if(!Ht(At,Rt)){let Je=Jt();yt(Dt,(bi=>yt(bi,(([vr,wr],nn)=>wr!==vr?Vt(Je,nn):je(bi,nn))))),yt(Je,(bi=>U(et[B],[Rt,bi])))}})),yt(mt[4],((Dt,Rt)=>yt(Dt,((Je,bi)=>pe(Je,st[B],W[B],[Rt,bi])))))}if(!ut){let At;yt(mt[5],((Dt,Rt)=>{let Je;yt(Dt,((bi,vr)=>{let wr;yt(bi,(([nn,zl],Zh)=>{zl!==nn&&(U(x[B],[Rt,vr,Zh],zl,nn,$e),At=Je=wr=1)})),wr&&U(ct[B],[Rt,vr],$e)})),Je&&U(at[B],[Rt],$e)})),At&&U(H[B],void 0,$e)}}},El=B=>{let q=fr();q!=i&&U(p[B],void 0,q);let J=vt(_[B])&&vt(k[B]),ot=vt(O[B])&&vt(v[B]);if(!J||!ot){let ut=B?[xi(f),xi(A)]:[f,A];if(J||pe(ut[0],_[B],k[B]),!ot){let mt;yt(ut[1],(([At,Dt],Rt)=>{Dt!==At&&(U(O[B],[Rt],Dt,At,lr),mt=1)})),mt&&U(v[B],void 0,lr)}}},Wt=(B,...q)=>(Ho((()=>B(...Wi(q,Bt)))),de),Cl=(B,q,J,ot,ut)=>{let mt=hr(B,q,...J);return L((()=>{let At=hr(B,q,...J);sc(At,mt)||(mt=At,ot(de,B,q,...J,mt))}),et[ut?1:0],[B,q],[Ee])},No=()=>Ar(I),Ee=()=>Gi(I),_l=B=>Gi(ht(E,Bt(B))),kl=B=>Is(ht(I,Bt(B))),Ss=B=>Gi(ht(I,Bt(B))),hr=(B,q,J,ot=0,ut)=>{return Pr(B)?hr(B.tableId,B.cellId,B.descending,B.offset,B.limit):Wi(Qo(ta((mt=ht(I,Bt(B)),At=(Dt,Rt)=>[St(q)?Rt:ht(Dt,Bt(q)),Rt],Wi([...mt?.entries()??[]],(([Dt,Rt])=>At(Rt,Dt)))),(([Dt],[Rt])=>cc(Dt,Rt)*(J?-1:1))),ot,St(ut)?ut:ot+ut),(([,Dt])=>Dt));var mt,At},Bo=(B,q)=>Gi(ht(ht(I,Bt(B)),Bt(q))),dr=(B,q,J)=>ht(ht(ht(I,Bt(B)),Bt(q)),Bt(J)),$o=()=>be(N),Uo=()=>Gi(N),ur=B=>ht(N,Bt(B)),pr=()=>!vt(I),Tl=B=>Ht(I,Bt(B)),Pl=(B,q)=>Ht(ht(E,Bt(B)),Bt(q)),Dl=(B,q)=>Ht(ht(I,Bt(B)),Bt(q)),Il=(B,q,J)=>Ht(ht(ht(I,Bt(B)),Bt(q)),Bt(J)),fr=()=>!vt(N),Ml=B=>Ht(N,Bt(B)),gr=B=>Wt((()=>(q=>wi(q,Q,Be))(B)?It(B):0)),mr=B=>Wt((()=>nt(B)?Ne(B):0)),Rl=B=>(Go((()=>xt(Xo(B)))),de),Ll=B=>Wt((()=>{if((s=wi(B,(q=>wi(q,F))))&&(wt(B),!vt(I))){let q=No();br(),gr(q)}})),Fl=B=>Wt((()=>{if(t=(q=>wi(q,F))(B)){let q=$o();zo(),yr(),t=!0,Tt(B),mr(q)}})),br=()=>Wt((()=>It({}))),Ol=B=>Wt((q=>Ht(I,q)?pi(q):0),B),Nl=(B,q)=>Wt(((J,ot)=>$t(ht(I,J),(ut=>Ht(ut,ot)?fi(J,ut,ot):0))),B,q),yr=()=>Wt((()=>Ne({}))),Bl=()=>Wt((()=>{wt({}),s=!1})),zo=()=>Wt((()=>{Tt({}),t=!1})),Ho=(B,q)=>{if(n!=-1){$l();let J=B();return Ul(q),J}},$l=()=>(n!=-1&&n++,n==1&&(o[0]?.(),U(M)),de),Ul=B=>(n>0&&(n--,n==0&&(n=1,As(1),vt(a)||cr(1),mi(1),vt(A)||El(1),B?.(de)&&(yt(a,((q,J)=>yt(q,((ot,ut)=>yt(ot,(([mt],At)=>Tr(de,J,ut,At,mt))))))),ks(a),yt(A,(([q],J)=>ea(de,J,q))),ks(A)),U(S[0],void 0),n=-1,As(0),vt(a)||cr(0),mi(0),vt(A)||El(0),o[1]?.(),U(S[1],void 0),o[2]?.(),n=0,e=pr(),i=fr(),ve([l,h,g,m,d,a,C,f,A,u],ks))),de),de={getContent:()=>[No(),$o()],getTables:No,getTableIds:Ee,getTable:B=>ia(ht(I,Bt(B))),getTableCellIds:_l,getRowCount:kl,getRowIds:Ss,getSortedRowIds:hr,getRow:(B,q)=>be(ht(ht(I,Bt(B)),Bt(q))),getCellIds:Bo,getCell:dr,getValues:$o,getValueIds:Uo,getValue:ur,hasTables:pr,hasTable:Tl,hasTableCell:Pl,hasRow:Dl,hasCell:Il,hasValues:fr,hasValue:Ml,getTablesJson:()=>Cs(I),getValuesJson:()=>Cs(N),getJson:()=>Cs([I,N]),getTablesSchemaJson:()=>Cs(y),getValuesSchemaJson:()=>Cs(c),getSchemaJson:()=>Cs([y,c]),hasTablesSchema:()=>s,hasValuesSchema:()=>t,setContent:B=>Wt((()=>{let q=ze(B)?B():B;V(q)&&(([J,ot])=>{(He(J)?br:gr)(J),(He(ot)?yr:mr)(ot)})(q)})),setTables:gr,setTable:(B,q)=>Wt((J=>Q(q,J)?Lt(J,q):0),B),setRow:(B,q,J)=>Wt(((ot,ut)=>Z(ot,ut,J)?Ut(ot,Ie(ot),ut,J):0),B,q),addRow:(B,q,J=!0)=>Ho((()=>{let ot;return Z(B,ot,q)&&(B=Bt(B),Ut(B,Ie(B),ot=((ut,mt)=>{let[At]=ht(P,ut),Dt;do Dt=At(mt);while(Ht(ht(I,ut),Dt));return Dt})(B,J?1:0),q)),ot})),setPartialRow:(B,q,J)=>Wt(((ot,ut)=>{if(Z(ot,ut,J,1)){let mt=Ie(ot);Qe(J,((At,Dt)=>he(ot,mt,ut,Dt,At)))}}),B,q),setCell:(B,q,J,ot)=>Wt(((ut,mt,At)=>$t(tt(ut,mt,At,ze(ot)?ot(dr(ut,mt,At)):ot),(Dt=>he(ut,Ie(ut),mt,At,Dt)))),B,q,J),setValues:mr,setPartialValues:B=>Wt((()=>nt(B,1)?Qe(B,((q,J)=>Te(J,q))):0)),setValue:(B,q)=>Wt((J=>$t(pt(J,ze(q)?q(ur(J)):q),(ot=>Te(J,ot)))),B),applyChanges:B=>Wt((()=>{Qe(B[0],((q,J)=>St(q)?Ol(J):Qe(q,((ot,ut)=>St(ot)?Nl(J,ut):Qe(ot,((mt,At)=>Tr(de,J,ut,At,mt))))))),Qe(B[1],((q,J)=>ea(de,J,q)))})),setTablesJson:Rl,setValuesJson:B=>(Go((()=>Se(Xo(B)))),de),setJson:B=>Wt((()=>Go((()=>{let[q,J]=Xo(B);xt(q),Se(J)}),(()=>Rl(B))))),setTablesSchema:Ll,setValuesSchema:Fl,setSchema:(B,q)=>Wt((()=>{Ll(B),Fl(q)})),delTables:br,delTable:Ol,delRow:Nl,delCell:(B,q,J,ot)=>Wt(((ut,mt,At)=>$t(ht(I,ut),(Dt=>$t(ht(Dt,mt),(Rt=>Ht(Rt,At)?le(ut,Dt,mt,Rt,At,ot):0))))),B,q,J),delValues:yr,delValue:B=>Wt((q=>Ht(N,q)?oe(q):0),B),delTablesSchema:Bl,delValuesSchema:zo,delSchema:()=>Wt((()=>{Bl(),zo()})),transaction:Ho,startTransaction:$l,getTransactionChanges:()=>[be(a,((B,q)=>ht(l,q)===-1?void 0:be(B,((J,ot)=>ht(ht(m,q),ot)===-1?void 0:be(J,(([,ut])=>ut),(ut=>Er(ut)))),vt,He)),vt,He),be(A,(([,B])=>B),(B=>Er(B))),1],getTransactionLog:()=>[!vt(a),!vt(A),Ar(a,Kl,Er),Ar(C),be(A,Kl,Er),be(u),be(l),ia(m),Ar(d),be(f)],finishTransaction:Ul,forEachTable:B=>yt(I,((q,J)=>B(J,(ot=>yt(q,((ut,mt)=>ot(mt,(At=>Yt(ut,At))))))))),forEachTableCell:(B,q)=>Yt(ht(E,Bt(B)),q),forEachRow:(B,q)=>yt(ht(I,Bt(B)),((J,ot)=>q(ot,(ut=>Yt(J,ut))))),forEachCell:(B,q,J)=>Yt(ht(ht(I,Bt(B)),Bt(q)),J),forEachValue:B=>Yt(N,B),addSortedRowIdsListener:(B,q,J,ot,ut,mt,At)=>Pr(B)?Cl(B.tableId,B.cellId,[B.descending??!1,B.offset??0,B.limit],q,J):Cl(B,q,[J,ot,ut],mt,At),addStartTransactionListener:B=>L(B,M),addWillFinishTransactionListener:B=>L(B,S[0]),addDidFinishTransactionListener:B=>L(B,S[1]),callListener:B=>(D(B),de),delListener:B=>($(B),de),getListenerStats:()=>({hasTables:qt(z),tables:qt(H),tableIds:qt(X),hasTable:qt(it),table:qt(at),tableCellIds:qt(K),hasTableCell:qt(j,Ze),rowCount:qt(G),rowIds:qt(Y),sortedRowIds:qt(et),hasRow:qt(rt,Ze),row:qt(ct,Ze),cellIds:qt(st,Ze),hasCell:qt(W,Wo),cell:qt(x,Wo),invalidCell:qt(T,Wo),hasValues:qt(p),values:qt(v),valueIds:qt(_),hasValue:qt(k),value:qt(O),invalidValue:qt(R),transaction:qi(M)+qt(S)}),isMergeable:()=>!1,createStore:pn,addListener:L,callListeners:U,setInternalListeners:(B,q,J,ot,ut)=>o=[B,q,J,ot,ut]};return Qe({[ji+jl]:[0,z,[],()=>[pr()]],[jl]:[0,H],[sd]:[0,X],[ji+Ai]:[1,it,[Ee],B=>[Tl(...B)]],[Ai]:[1,at,[Ee]],[Ai+Cr]:[1,K,[Ee]],[ji+Ai+an]:[2,j,[Ee,_l],B=>[Pl(...B)]],[Ql]:[1,G,[Ee]],[Zl]:[1,Y,[Ee]],[ji+Ts]:[2,rt,[Ee,Ss],B=>[Dl(...B)]],[Ts]:[2,ct,[Ee,Ss]],[Cr]:[2,st,[Ee,Ss]],[ji+an]:[3,W,[Ee,Ss,Bo],B=>[Il(...B)]],[an]:[3,x,[Ee,Ss,Bo],B=>Sr(dr(...B))],InvalidCell:[3,T],[ji+Vl]:[0,p,[],()=>[fr()]],[Vl]:[0,v],[rd]:[0,_],[ji+_r]:[1,k,[Uo],B=>[Ml(...B)]],[_r]:[1,O,[Uo],B=>Sr(ur(B[0]))],InvalidValue:[1,R]},(([B,q,J,ot],ut)=>{de[Yo+ut+Ko]=(...mt)=>L(mt[B],q[mt[B+1]?1:0],B>0?Qo(mt,0,B):void 0,J,ot)})),Ms(de)};var na=ft([["avg",[(s,t)=>Wl(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=>jo(...s),(s,t)=>jo(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:jo(t,s)]],["min",[s=>Vo(...s),(s,t)=>Vo(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:Vo(t,s)]],["sum",[s=>Wl(s),(s,t)=>s+t,(s,t)=>s-t,(s,t,e)=>s-e+t]]]),hc=(s,t,e,i,n,o=!1)=>{if(vt(e))return;let[l,h,g,m]=n;return o||=St(s),yt(i,(([d,a])=>{o||(s=St(d)?h?.(s,a,t++):St(a)?g?.(s,d,t--):m?.(s,a,d,t),o||=St(s))})),o?l(Ds(e),Is(e)):s},Up=dn((s=>{let t=ft(),[e,i,n]=un((()=>y)),[o,l,h,g,m,d,a,,f,A,C,u]=Mr(s,ic,(r=>isNaN(r)||St(r)||r===!0||r===!1||r===""?void 0:1*r),e,i),y={setMetricDefinition:(r,c,b,w,P,E,I)=>{let N=ze(b)?[b,P,E,I]:ht(na,b)??ht(na,"sum");return f(r,c,((z,H,X,it,at,K)=>{let j=d(r),G=Is(it);K||=St(j),z();let Y=hc(j,G,it,H,N,K);tc(Y)||(Y=void 0),Y!=j&&(a(r,Y),i(t,[r],Y,j))}),Dr(w,1)),y},delMetricDefinition:r=>(A(r),y),getStore:o,getMetricIds:l,forEachMetric:h,hasMetric:g,getTableId:m,getMetric:d,addMetricIdsListener:C,addMetricListener:(r,c)=>e(c,t,[r]),delListener:r=>(n(r),y),destroy:u,getListenerStats:()=>({metric:qi(t)})};return Ms(y)})),zp=dn((s=>{let t=s.createStore,e=t(),i=t(),n=ft(),{addListener:o,callListeners:l,delListener:h}=i,[g,m,d,a,f,,,A,,C,u,y,r,c]=Mr(s,(()=>!0),ic,o,l),b=(I,N,...z)=>ve(z,(H=>Vt(zt(zt(n,N,ft),I,Jt),H))),w=I=>{$t(ht(n,I),(N=>{Yt(N,((z,H)=>yt(H,(X=>z.delListener(X))))),ks(N)})),ve([i,e],(N=>N.delTable(I)))},P=(I,N,z)=>b(N,I,N.addStartTransactionListener(z.startTransaction),N.addDidFinishTransactionListener((()=>z.finishTransaction()))),E={setQueryDefinition:(I,N,z)=>{A(I,N),w(I);let H=[],X=[[null,[N,null,null,[],ft()]]],it=[],at=[],K=[];z({select:(st,W)=>{let x=ze(st)?[Ce(H)+"",st]:[St(W)?st:W,T=>T(st,W)];return ye(H,x),{as:T=>x[0]=T}},join:(st,W,x)=>{let T=St(x)||ze(W)?null:W,R=St(T)?W:x,p=[st,[st,T,ze(R)?R:v=>v(R),[],ft()]];return ye(X,p),{as:v=>p[0]=v}},where:(st,W,x)=>ye(it,ze(st)?st:St(x)?T=>T(st)===W:T=>T(st,W)===x),group:(st,W,x,T,R)=>{let p=[st,[st,ze(W)?[W,x,T,R]:ht(na,W)??[(v,_)=>_]]];return ye(at,p),{as:v=>p[0]=v}},having:(st,W)=>ye(K,ze(st)?st:x=>x(st)===W)});let j=ft(H);if(vt(j))return E;let G=ft(X);Yt(G,((st,[,W])=>$t(ht(G,W),(({3:x})=>St(st)?0:ye(x,st)))));let Y=ft(at),et=e;if(vt(Y)&&ln(K))et=i;else{P(I,et,i);let st=ft();Yt(Y,((R,[p,v])=>Vt(zt(st,p,Jt),[R,v])));let W=Jt();Yt(j,(R=>Ht(st,R)?0:Vt(W,R)));let x=ft(),T=(R,p,v,_)=>$t(R,(([k,O,M,S])=>{Yt(p,((L,[U])=>{let $=zt(k,L,ft),D=ht($,v),F=_?void 0:U;if(D!==F){let V=Jt([[D,F]]),Q=Is($);bt($,v,F),yt(ht(st,L),(([Z,tt])=>{let nt=hc(S[Z],Q,$,V,tt);S[Z]=St(_s(nt))?null:nt}))}})),vt(O)||!kr(K,(L=>L((U=>S[U]))))?i.delRow(I,M):St(M)?R[2]=i.addRow(I,S):i.setRow(I,M,S)}));b(et,I,et.addRowListener(I,null,((R,p,v,_)=>{let k=[],O=[],M=ft(),S=et.hasRow(I,v),L=!S;yt(W,(U=>{let[$,D,F]=_(I,v,U);ye(k,D),ye(O,F),L||=$})),Yt(st,(U=>{let[$,,D]=_(I,v,U);(L||$)&&bt(M,U,[D])})),L&&T(cn(x,k,void 0,(([,U])=>(je(U,v),vt(U)))),M,v,1),S&&T(cn(x,O,(()=>{let U={};return yt(W,($=>U[$]=et.getCell(I,v,$))),[ft(),Jt(),void 0,U]}),(([,U])=>{Vt(U,v)})),M,v)})))}P(I,s,et);let rt=(st,W,x,T)=>{let R=p=>s.getCell(W,x,p);ve(T,(p=>{let[v,,_,k,O]=ht(G,p),M=_?.(R,st),[S,L]=ht(O,st)??[];M!=S&&(St(L)||c(I,L),bt(O,st,St(M)?null:[M,...r(I,1,s.addRowListener(v,M,(()=>rt(st,v,M,k))))]))})),(p=>{let v=(_,k)=>s.getCell(...St(k)?[N,p,_]:_===N?[N,p,k]:[ht(G,_)?.[0],ht(ht(G,_)?.[4],p)?.[0],k]);et.transaction((()=>kr(it,(_=>_(v)))?Yt(j,((_,k)=>Tr(et,I,p,_,k(v,p)))):et.delRow(I,p)))})(st)},{3:ct}=ht(G,null);return et.transaction((()=>r(I,1,s.addRowListener(N,null,((st,W,x)=>{s.hasRow(N,x)?rt(x,N,x,ct):(et.delRow(I,x),yt(G,(({4:T})=>$t(ht(T,x),(([,R])=>{c(I,R),bt(T,x)})))))}))))),E},delQueryDefinition:I=>(w(I),C(I),E),getStore:g,getQueryIds:m,forEachQuery:d,hasQuery:a,getTableId:f,addQueryIdsListener:I=>u((()=>I(E))),delListener:I=>(h(I),E),destroy:y,getListenerStats:()=>{let{tables:I,tableIds:N,transaction:z,...H}=i.getListenerStats();return H}};return Qe({[Ai]:[1,1],[Ai+Cr]:[0,1],[Ql]:[0,1],[Zl]:[0,1],[nd]:[0,5],[Ts]:[1,2],[Cr]:[0,2],[an]:[1,3]},(([I,N],z)=>{ve(I?["get","has","forEach"]:["get"],(H=>E[H+Hl+z]=(...X)=>i[H+z](...X))),E[Yo+Hl+z+Ko]=(...H)=>i[Yo+z+Ko](...Qo(H,0,N),((X,...it)=>H[N](E,...it)),!0)})),Ms(E)})),Hp=dn((s=>{let t=ft(),e=ft(),i=ft(),n=ft(),[o,l,h]=un((()=>P)),[g,m,d,a,f,A,,,C,u,y,r]=Mr(s,(()=>[ft(),ft(),ft(),ft()]),(E=>St(E)?void 0:E+""),o,l),c=(E,I,N)=>$t(A(E),(([z,,H])=>{if(!Ht(H,I)){let X=Jt();if(f(E)!=w(E))Vt(X,I);else{let it=I;for(;!St(it)&&!Ht(X,it);)Vt(X,it),it=ht(z,it)}if(N)return X;bt(H,I,X)}return ht(H,I)})),b=(E,I)=>$t(A(E),(([,,N])=>bt(N,I))),w=E=>ht(t,E),P={setRelationshipDefinition:(E,I,N,z)=>(bt(t,E,N),C(E,I,((H,X)=>{let it=Jt(),at=Jt(),K=Jt(),[j,G]=A(E);yt(X,(([Y,et],rt)=>{St(Y)||(Vt(at,Y),$t(ht(G,Y),(ct=>{je(ct,rt),vt(ct)&&bt(G,Y)}))),St(et)||(Vt(at,et),Ht(G,et)||bt(G,et,Jt()),Vt(ht(G,et),rt)),Vt(it,rt),bt(j,rt,et),Yt(ht(n,E),(ct=>{Ht(c(E,ct),rt)&&Vt(K,ct)}))})),H(),yt(it,(Y=>l(e,[E,Y]))),yt(at,(Y=>l(i,[E,Y]))),yt(K,(Y=>{b(E,Y),l(n,[E,Y])}))}),Dr(z)),P),delRelationshipDefinition:E=>(bt(t,E),u(E),P),getStore:g,getRelationshipIds:m,forEachRelationship:E=>d((I=>E(I,(N=>s.forEachRow(f(I),N))))),hasRelationship:a,getLocalTableId:f,getRemoteTableId:w,getRemoteRowId:(E,I)=>ht(A(E)?.[0],I),getLocalRowIds:(E,I)=>Ds(ht(A(E)?.[1],I)),getLinkedRowIds:(E,I)=>St(A(E))?[I]:Ds(c(E,I,!0)),addRelationshipIdsListener:y,addRemoteRowIdListener:(E,I,N)=>o(N,e,[E,I]),addLocalRowIdsListener:(E,I,N)=>o(N,i,[E,I]),addLinkedRowIdsListener:(E,I,N)=>(c(E,I),o(N,n,[E,I])),delListener:E=>(b(...h(E)??[]),P),destroy:r,getListenerStats:()=>({remoteRowId:Ze(e),localRowIds:Ze(i),linkedRowIds:Ze(n)})};return Ms(P)}));var pc=Promise,md=globalThis,dc=md.window,bd=1e3,yd=(s,t,e)=>setInterval(s,t*bd),vd=clearInterval,Ve=s=>s==null,Nr=(s,t,e)=>Ve(s)?e?.():t(s),aa=s=>Array.isArray(s),Ki=s=>s.length,wd=(s,t)=>s.test(t),fc=s=>new pc(s),gc=async s=>pc.all(s),mc=s=>{throw new Error(s)},Xi=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},la=(s,t)=>s.forEach(t),fn=(s,t)=>s.map(t),xd=(s,t)=>s.splice(0,t),Br=(s,...t)=>s.push(...t),bc=s=>s.shift(),Rs=Object,uc=s=>Rs.getPrototypeOf(s),Ad=Rs.entries,Sd=s=>!Ve(s)&&Nr(uc(s),t=>t==Rs.prototype||Ve(uc(t)),()=>!0),Ed=Rs.keys,Cd=Rs.freeze,_d=(s=[])=>Rs.fromEntries(s),kd=(s,t)=>t in s,Td=(s,t)=>fn(Ad(s),([e,i])=>t(i,e)),Pd=s=>Ki(Ed(s)),Rr=s=>Sd(s)&&Pd(s)==0,Dd=s=>s?.size??0,Id=(s,t)=>s?.has(t)??!1,yc=s=>Ve(s)||Dd(s)==0,vc=(s,t)=>s?.forEach(t),wc=(s,t)=>s?.delete(t),gn=s=>new Map(s),Re=(s,t)=>s?.get(t),Yi=(s,t,e)=>Ve(e)?(wc(s,t),s):s?.set(t,e),ca=(s,t,e,i)=>(Id(s,t)?i?.(Re(s,t)):Yi(s,t,e()),Re(s,t)),ha=(s,t,e,i,n=0)=>Nr((e?ca:Re)(s,t[n],n>Ki(t)-2?e:gn),o=>{if(n>Ki(t)-2)return i?.(o)&&Yi(s,t[n]),o;let l=ha(o,t,e,i,n+1);return yc(o)&&Yi(s,t[n]),l}),Md=/^\d+$/,Rd=()=>{let s=[],t=0;return[e=>(e?bc(s):null)??""+t++,e=>{wd(Md,e)&&Ki(s)<1e3&&Br(s,e)}]},Ld=s=>new Set(aa(s)||Ve(s)?s:[s]),Fd=(s,t)=>s?.add(t),Od=(s,t=[""])=>{let e=[],i=(n,o)=>o==Ki(t)?Br(e,n):t[o]===null?vc(n,l=>i(l,o+1)):la([t[o],null],l=>i(Re(n,l),o+1));return i(s,0),e},Nd=s=>{let t,[e,i]=Rd(),n=gn();return[(o,l,h,g=[],m=()=>[])=>{t??=s();let d=e(1);return Yi(n,d,[o,l,h,g,m]),Fd(ha(l,h??[""],Ld),d),d},(o,l,...h)=>la(Od(o,l),g=>vc(g,m=>Re(n,m)[0](t,...l??[],...h))),o=>Nr(Re(n,o),([,l,h])=>(ha(l,h??[""],void 0,g=>(wc(g,o),yc(g)?1:0)),Yi(n,o),i(o),h)),o=>Nr(Re(n,o),([l,,h=[],g,m])=>{let d=(...a)=>{let f=Ki(a);f==Ki(h)?l(t,...a,...m(a)):Ve(h[f])?la(g[f]?.(...a)??[],A=>d(...a,A)):d(...a,h[f])};d()})]},Lr=gn(),Fr=gn(),Bd=(s=1,t,e)=>s!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[n]])=>!Rr(i)||!Rr(n),t.setDefaultContent]:s!=2?[0,t.getContent,t.getTransactionChanges,([i,n])=>!Rr(i)||!Rr(n),t.setContent]:mc("Store type not supported by this Persister"),$d=(s,t,e,i,n,o,l,h={},g=0,m=[])=>{let d=0,a=0,f=0,A,C,u;ca(Lr,m,()=>0),ca(Fr,m,()=>[]);let y=gn(),[r,c,b,w,P]=Bd(l,s,g),[E,I,N]=Nd(()=>p),z=v=>{v!=d&&(d=v,I(y,void 0,d))},H=async()=>{if(!Re(Lr,m)){for(Yi(Lr,m,1);!Ve(A=bc(Re(Fr,m)));)await Xi(A,o);Yi(Lr,m,0)}},X=v=>{(r&&aa(v?.[0])?v?.[2]===1?s.applyMergeableChanges:s.setMergeableContent:v?.[2]===1?s.applyChanges:s.setContent)(v)},it=async v=>(d!=2&&(z(1),a++,await R(async()=>{await Xi(async()=>{let _=await t();aa(_)?X(_):v?P(v):mc(`Content is not an array: ${_}`)},()=>{v&&P(v)}),z(0)})),p),at=async v=>(K(),await it(v),await Xi(async()=>C=await i(async(_,k)=>{k||_?d!=2&&(z(1),a++,X(k??_),z(0)):await it()}),o),p),K=async()=>(C&&(await Xi(()=>n(C),o),C=void 0),p),j=()=>!Ve(C),G=async v=>(d!=1&&(z(2),f++,await R(async()=>{await Xi(()=>e(c,v),o),z(0)})),p),Y=async()=>(et(),await G(),u=s.addDidFinishTransactionListener(()=>{let v=b();w(v)&&G(v)}),p),et=async()=>(u&&(s.delListener(u),u=void 0),p),rt=()=>!Ve(u),ct=async(v,_=!1)=>{let[k,O]=_?[Y,at]:[at,Y];return await k(v),await O(v),p},st=async(v=!1)=>{let[_,k]=v?[et,K]:[K,et];return await _(),await k(),p},W=()=>d,x=v=>E(v,y),T=v=>(N(v),s),R=async(...v)=>(Br(Re(Fr,m),...v),await H(),p),p={load:it,startAutoLoad:at,stopAutoLoad:K,isAutoLoading:j,save:G,startAutoSave:Y,stopAutoSave:et,isAutoSaving:rt,startAutoPersisting:ct,stopAutoPersisting:st,getStatus:W,addStatusListener:x,delListener:T,schedule:R,getStore:()=>s,destroy:()=>(xd(Re(Fr,m)),st()),getStats:()=>({loads:a,saves:f}),...h};return Cd(p)},oa=["t","v"],Ud={keyPath:"k"},zd=async(s,t)=>{let e=Td(t,(i,n)=>Or(s,"put",{k:n,v:i}));fn(await Or(s,"getAllKeys"),i=>kd(t,i)?0:Br(e,Or(s,"delete",i))),await gc(e)},Or=async(s,t,e)=>fc((i,n)=>{let o=s[t](e);o.onsuccess=()=>i(o.result),o.onerror=()=>n(`objectStore.${t} error`)}),$r=(s,t,e=1,i)=>{let n=async(o,l=[],h=0)=>fc((g,m)=>{let d=(dc?dc.indexedDB:indexedDB).open(t,h?2:void 0);d.onupgradeneeded=()=>h&&fn(oa,a=>Xi(()=>d.result.createObjectStore(a,Ud))),d.onsuccess=()=>Xi(async()=>{let a=d.result.transaction(oa,"readwrite"),f=await gc(fn(oa,(A,C)=>o(a.objectStore(A),l[C])));d.result.close(),g(f)},a=>{d.result.close(),m(a)}),d.onerror=()=>m("indexedDB.open error")});return $d(s,async()=>await n(async o=>_d(fn(await Or(o,"getAll"),({k:l,v:h})=>[l,h]))),o=>n((l,h)=>zd(l,h),o(),1),o=>yd(o,e),o=>vd(o),i,1,{getDbName:()=>t})};var Ur=pn();Ur.setTable("docs",{});var zr=$r(Ur,"copio-db");zr.startAutoLoad();zr.startAutoSave();var Ji=class extends Ue{#t=null;#e=null;#i="copio-db";#n=!1;constructor(t={}){super(),t.dbName&&t.dbName!=="copio-db"?(this.#i=t.dbName,this.#t=t.store||pn(),this.#t.setTable("docs",{}),this.#e=t.persister||$r(this.#t,this.#i),this.#n=!0):(this.#t=t.store||Ur,this.#e=t.persister||zr,this.#i="copio-db")}get store(){return this.#t}get persister(){return this.#e}async init(){return this.#n?(await this.#e.load(),this.#e.startAutoLoad(),this.#e.startAutoSave()):await this.#e.load(),{kind:"indexeddb",persistent:!0}}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#r(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#r(e.pages)}}async getDoc(t){return this.getDocSync(t)}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#r(e.pages);this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(i)})}async deleteDoc(t){this.#t.delRow("docs",t)}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(l=>l.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 l=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};n.pages.push(l)}await this.saveDoc(t,n)}async getPage(t,e){let i=await this.getDoc(t);if(!i)return null;let n=i.pages.find(o=>o.id===e);return n?n.src??n:null}async deletePage(t,e){let i=await this.getDoc(t);i&&(i.pages=i.pages.filter(n=>n.id!==e),await this.saveDoc(t,i))}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#r(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function Ls(s={}){return s.forceMemory?new vi:typeof indexedDB<"u"?new Ji(s):new vi}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 Ea=typeof self<"u"?self:global,wn=typeof navigator<"u",Hd=wn&&typeof HTMLImageElement>"u",xc=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),Ca=Ea.Buffer,Hr=Ea.BigInt,_a=!!Ca,jr=s=>Rc(s)?void 0:s,jd=s=>s!==void 0;function Rc(s){return s===void 0||(s instanceof Map?s.size===0:Object.values(s).filter(jd).length===0)}function re(s){let t=new Error(s);throw delete t.stack,t}function Lc(s){return(s=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(s).trim())===""?void 0:s}function Ac(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 fa=s=>String.fromCharCode.apply(null,s),Sc=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function Fc(s){return Sc?Sc.decode(s):_a?Buffer.from(s).toString("utf8"):decodeURIComponent(escape(fa(s)))}var ii=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 Fc(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return fa(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 fa(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 ga(s,t){re(`${s} '${t}' was not loaded, try using full build of exifr.`)}var xn=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||ga(this.kind,t),e&&(t in e||(function(i,n){re(`Unknown ${i} '${n}'.`)})(this.kind,t),e[t].enabled||ga(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},ns=new xn("file parser"),ge=new xn("segment parser"),rs=new xn("file reader"),Oc=Ea.fetch;function Ec(s,t){return(e=s).startsWith("data:")||e.length>1e4?ba(s,t,"base64"):xc&&s.includes("://")?ma(s,t,"url",Ns):xc?ba(s,t,"fs"):wn?ma(s,t,"url",Ns):void re("Invalid input argument");var e}async function ma(s,t,e,i){return rs.has(e)?ba(s,t,e):i?(async function(n,o){let l=await o(n);return new ii(l)})(s,i):void re(`Parser ${e} is not loaded`)}async function ba(s,t,e){let i=new(rs.get(e))(s,t);return await i.read(),i}var Ns=s=>Oc(s).then((t=>t.arrayBuffer())),Bs=s=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(s)})),ya=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 Le(s,t,e){let i=new ya;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 ka(s,t,e){let i,n=s.get(t);for(i of e)n.set(i[0],i[1])}var ei=new Map,Us=new Map,ss=new Map,Zi=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],An=["jfif","xmp","icc","iptc","ihdr"],$s=["tiff",...An],Zt=["ifd0","ifd1","exif","gps","interop"],ts=[...$s,...Zt],es=["makerNote","userComment"],Sn=["translateKeys","translateValues","reviveValues","multiSegment"],is=[...Sn,"sanitize","mergeOutput","silentErrors"],Vr=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},Qi=class extends Vr{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=ei.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:l}=i;o&&o.length>0&&this.translateTagSet(o,this.pick),l&&l.length>0&&this.translateTagSet(l,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 Sn)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,n,{tagKeys:o,tagValues:l}=this.dict;for(i of t)typeof i=="string"?(n=l.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,Gr(this.pick,this.deps)):this.enabled&&this.pick.size>0&&Gr(this.pick,this.deps)}},fe={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},Cc=new Map,Ci=class extends Vr{static useCached(t){let e=Cc.get(t);return e!==void 0||(e=new this(t),Cc.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=wn?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of Zi)this[t]=fe[t];for(t of is)this[t]=fe[t];for(t of es)this[t]=fe[t];for(t of ts)this[t]=new Qi(t,fe[t],void 0,this)}setupFromTrue(){let t;for(t of Zi)this[t]=fe[t];for(t of is)this[t]=fe[t];for(t of es)this[t]=!0;for(t of ts)this[t]=new Qi(t,!0,void 0,this)}setupFromArray(t){let e;for(e of Zi)this[e]=fe[e];for(e of is)this[e]=fe[e];for(e of es)this[e]=fe[e];for(e of ts)this[e]=new Qi(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),Zi))this[e]=da(t[e],fe[e]);for(e of is)this[e]=da(t[e],fe[e]);for(e of es)this[e]=da(t[e],fe[e]);for(e of $s)this[e]=new Qi(e,fe[e],t[e],this);for(e of Zt)this[e]=new Qi(e,fe[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,Zt,ts),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 l of n)this[l].enabled=!1;let o=_c(t,i);for(let[l,h]of o)Gr(this[l].pick,h),this[l].enabled=!0}else if(e&&e.length){let o=_c(e,i);for(let[l,h]of o)Gr(this[l].skip,h)}}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!An.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of $s)this[t].enabled&&!ge.has(t)&&ga("segment parser",t)}};function _c(s,t){let e,i,n,o,l=[];for(n of t){for(o of(e=ei.get(n),i=[],e))(s.includes(o[0])||s.includes(o[1]))&&i.push(o[0]);i.length&&l.push([n,i])}return l}function da(s,t){return s!==void 0?s:t!==void 0?t:void 0}function Gr(s,t){for(let e of t)s.add(e)}Nt(Ci,"default",fe);var si=class{constructor(t){Nt(this,"parsers",{}),Nt(this,"output",{}),Nt(this,"errors",[]),Nt(this,"pushToErrors",(e=>this.errors.push(e))),this.options=Ci.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?Ec(e,i):wn&&!Hd&&e instanceof HTMLImageElement?Ec(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new ii(e):wn&&e instanceof Blob?ma(e,i,"blob",Bs):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 ns)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=ge.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),l=this.parsers.tiff=new i(o,t,e),h=await l.extractThumbnail();return e.close&&e.close(),h}};async function Ta(s,t){let e=new si(t);return await e.read(s),e.parse()}var Vd=Object.freeze({__proto__:null,parse:Ta,Exifr:si,fileParsers:ns,segmentParsers:ge,fileReaders:rs,tagKeys:ei,tagValues:Us,tagRevivers:ss,createDictionary:Le,extendDictionary:ka,fetchUrlAsArrayBuffer:Ns,readBlobAsArrayBuffer:Bs,chunkedProps:Zi,otherSegments:An,segments:$s,tiffBlocks:Zt,segmentsAndBlocks:ts,tiffExtractables:es,inheritables:Sn,allFormatters:is,Options:Ci}),Wr=class{constructor(t,e,i){Nt(this,"errors",[]),Nt(this,"ensureSegmentChunk",(async n=>{let o=n.start,l=n.size||65536;if(this.file.chunked)if(this.file.available(o,l))n.chunk=this.file.subarray(o,l);else try{n.chunk=await this.file.readChunk(o,l)}catch(h){re(`Couldn't read segment: ${JSON.stringify(n)}. ${h.message}`)}else this.file.byteLength>o+l?n.chunk=this.file.subarray(o,l):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(ge.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 l=this.parsers[i];l&&l.append||l||this.createParser(i,n)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},ti=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,l=i-n;return{offset:e,length:i,headerLength:n,start:o,size:l,end:o+l}}static parse(t,e={}){return new this(t,new Ci({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof ii?t:new ii(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=ss.get(e),n=Us.get(e),o=ei.get(e),l=this.options[e],h=l.reviveValues&&!!i,g=l.translateValues&&!!n,m=l.translateKeys&&!!o,d={};for(let[a,f]of t)h&&i.has(a)?f=i.get(a)(f):g&&n.has(a)&&(f=this.translateValue(f,n.get(a))),m&&o.has(a)&&(a=o.get(a)||a),d[a]=f;return d}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(ti,"headerLength",4),Nt(ti,"type",void 0),Nt(ti,"multiSegment",!1),Nt(ti,"canHandle",(()=>!1));function Gd(s){return s===192||s===194||s===196||s===219||s===221||s===218||s===254}function Wd(s){return s>=224&&s<=239}function qd(s,t,e){for(let[i,n]of ge)if(n.canHandle(s,t,e))return i}var qr=class extends Wr{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(ge.keyList())):(t=t===void 0?ge.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&ge.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:l}=this;if(!n&&this.file.chunked&&(n=Array.from(o).some((h=>{let g=ge.get(h),m=this.options[h];return g.multiSegment&&m.multiSegment})),n&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let h=!1;for(;l.size>0&&!h&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:g}=i,m=this.appSegments.some((d=>!this.file.available(d.offset||d.start,d.length||d.size)));if(h=t>g&&!m?!await i.readNextChunk(t):!await i.readNextChunk(g),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,n,o,l,h,g,{file:m,findAll:d,wanted:a,remaining:f,options:A}=this;for(;t<e;t++)if(m.getUint8(t)===255){if(i=m.getUint8(t+1),Wd(i)){if(n=m.getUint16(t+2),o=qd(m,t,n),o&&a.has(o)&&(l=ge.get(o),h=l.findPosition(m,t),g=A[o],h.type=o,this.appSegments.push(h),!d&&(l.multiSegment&&g.multiSegment?(this.unfinishedMultiSegment=h.chunkNumber<h.chunkCount,this.unfinishedMultiSegment||f.delete(o)):f.delete(o),f.size===0)))break;A.recordUnknownSegments&&(h=ti.findPosition(m,t),h.marker=i,this.unknownSegments.push(h)),t+=n+1}else if(Gd(i)){if(n=m.getUint16(t+2),i===218&&A.stopAfterSos!==!1)return;A.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,l,h=new Map;for(let g=0;g<e.length;g++)n=e[g],o=n[i],h.has(o)?l=h.get(o):h.set(o,l=[]),l.push(n);return Array.from(h)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let n=ge.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(qr,"type","jpeg"),ns.set("jpeg",qr);var Xd=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],va=class extends ti{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 l=n.size>0,h=o.size===0,g=this.chunk.getUint16(t);t+=2;for(let m=0;m<g;m++){let d=this.chunk.getUint16(t);if(l){if(n.has(d)&&(i.set(d,this.parseTag(t,d,e)),n.delete(d),n.size===0))break}else!h&&o.has(d)||i.set(d,this.parseTag(t,d,e));t+=12}return i}parseTag(t,e,i){let{chunk:n}=this,o=n.getUint16(t+2),l=n.getUint32(t+4),h=Xd[o];if(h*l<=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,l);if(o===2)return Lc(n.getString(t,l));if(o===7)return n.getUint8Array(t,l);if(l===1)return this.parseTagValue(o,t);{let g=new((function(d){switch(d){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))(l),m=h;for(let d=0;d<l;d++)g[d]=this.parseTagValue(o,t),t+=m;return g}}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}`)}}},bn=class extends va{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.
|
|
2
|
-
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,Ac(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,Ac(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",kc(...t.get(2),t.get(1))),t.set("longitude",kc(...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],!Rc(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 kc(s,t,e,i){var n=s+t/60+e/3600;return i!=="S"&&i!=="W"||(n*=-1),n}Nt(bn,"type","tiff"),Nt(bn,"headerLength",10),ge.set("tiff",bn);var Kd=Object.freeze({__proto__:null,default:Vd,Exifr:si,fileParsers:ns,segmentParsers:ge,fileReaders:rs,tagKeys:ei,tagValues:Us,tagRevivers:ss,createDictionary:Le,extendDictionary:ka,fetchUrlAsArrayBuffer:Ns,readBlobAsArrayBuffer:Bs,chunkedProps:Zi,otherSegments:An,segments:$s,tiffBlocks:Zt,segmentsAndBlocks:ts,tiffExtractables:es,inheritables:Sn,allFormatters:is,Options:Ci,parse:Ta}),Pa={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},Nc=Object.assign({},Pa,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Yd(s){let t=new si(Nc);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 Bc=Object.assign({},Pa,{tiff:!1,ifd1:!0,mergeOutput:!1});async function Jd(s){let t=new si(Bc);await t.read(s);let e=await t.extractThumbnail();return e&&_a?Ca.from(e):e}async function Qd(s){let t=await this.thumbnail(s);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var $c=Object.assign({},Pa,{firstChunkSize:4e4,ifd0:[274]});async function Uc(s){let t=new si($c);await t.read(s);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var zc=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}}),Fs=!0,Os=!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;Fs=Number(e)+.1*Number(i)<13.4,Os=!1}}else if(s.includes("OS X 10")){let[,t]=s.match(/OS X 10[_.](\d+)/);Fs=Os=Number(t)<15}if(s.includes("Chrome/")){let[,t]=s.match(/Chrome\/(\d+)/);Fs=Os=Number(t)<81}else if(s.includes("Firefox/")){let[,t]=s.match(/Firefox\/(\d+)/);Fs=Os=Number(t)<77}}async function Zd(s){let t=await Uc(s);return Object.assign({canvas:Fs,css:Os},zc[t])}var wa=class extends ii{constructor(...t){super(...t),Nt(this,"ranges",new xa),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=_a?Ca.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)}},xa=class{constructor(){Nt(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let n=t+e,o=this.list.filter((l=>Tc(t,l.offset,n)||Tc(t,l.end,n)));if(o.length>0){t=Math.min(t,...o.map((h=>h.offset))),n=Math.max(n,...o.map((h=>h.end))),e=n-t;let l=o.shift();l.offset=t,l.length=e,l.end=n,this.list=this.list.filter((h=>!o.includes(h)))}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 Tc(s,t,e){return s<=t&&t<=e}var Xr=class extends wa{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(){}};rs.set("blob",class extends Xr{async readWhole(){this.chunked=!1;let s=await Bs(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 Bs(i);return this.set(n,s,!0)}});var tu=Object.freeze({__proto__:null,default:Kd,Exifr:si,fileParsers:ns,segmentParsers:ge,fileReaders:rs,tagKeys:ei,tagValues:Us,tagRevivers:ss,createDictionary:Le,extendDictionary:ka,fetchUrlAsArrayBuffer:Ns,readBlobAsArrayBuffer:Bs,chunkedProps:Zi,otherSegments:An,segments:$s,tiffBlocks:Zt,segmentsAndBlocks:ts,tiffExtractables:es,inheritables:Sn,allFormatters:is,Options:Ci,parse:Ta,gpsOnlyOptions:Nc,gps:Yd,thumbnailOnlyOptions:Bc,thumbnail:Jd,thumbnailUrl:Qd,orientationOnlyOptions:$c,orientation:Uc,rotations:zc,get rotateCanvas(){return Fs},get rotateCss(){return Os},rotation:Zd});rs.set("url",class extends Xr{async readWhole(){this.chunked=!1;let s=await Ns(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 Oc(this.input,{headers:i}),o=await n.arrayBuffer(),l=o.byteLength;if(n.status!==416)return l!==t&&(this.size=s+l),this.set(o,s,!0)}});ii.prototype.getUint64=function(s){let t=this.getUint32(s),e=this.getUint32(s+4);return t<1048575?t<<32|e:typeof Hr!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),Hr(t)<<Hr(32)|Hr(e)):void re("Trying to read 64b value but JS can only handle 53b numbers.")};var Aa=class extends Wr{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}},Kr=class extends Aa{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[l,h]=o;await this.file.ensureChunk(l,h);let g=4+this.file.getUint32(l);l+=g,h-=g,await this.registerSegment("tiff",l,h)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,n,o,l=t.start,h=this.file.getUint16(l);for(l+=2;h--;){if(e=this.parseBoxHead(l),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);l+=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++),[l,h]=this.get8bits(i++),g=t.version===2?4:2,m=t.version===1||t.version===2?2:0,d=h+n+o,a=t.version===2?4:2,f=this.file.getUintBytes(i,a);for(i+=a;f--;){let A=this.file.getUintBytes(i,g);i+=g+m+2+l;let C=this.file.getUint16(i);if(i+=2,A===e)return C>1&&console.warn(`ILOC box has more than one extent but we're only processing one
|
|
3
|
-
Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+h,n),this.file.getUintBytes(i+h+n,o)];i+=C*d}}},Yr=class extends Kr{};Nt(Yr,"type","heic");var Jr=class extends Kr{};Nt(Jr,"type","avif"),ns.set("heic",Yr),ns.set("avif",Jr),Le(ei,["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"]]),Le(ei,"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"]]),Le(ei,"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"]]),Le(Us,["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 yn=Le(Us,"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"}]]),Pc={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};yn.set(37392,Pc),yn.set(41488,Pc);var ua={0:"Normal",1:"Low",2:"High"};function Dc(s){return typeof s=="object"&&s.length!==void 0?s[0]:s}function Ic(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 pa(s){if(typeof s=="string"){var[t,e,i,n,o,l]=s.trim().split(/[-: ]/g).map(Number),h=new Date(t,e-1,i);return Number.isNaN(n)||Number.isNaN(o)||Number.isNaN(l)||(h.setHours(n),h.setMinutes(o),h.setSeconds(l)),Number.isNaN(+h)?s:h}}function mn(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(Mc(s[e+1],s[e]));else for(let e=0;e<s.length;e+=2)t.push(Mc(s[e],s[e+1]));return Lc(String.fromCodePoint(...t))}function Mc(s,t){return s<<8|t}yn.set(41992,ua),yn.set(41993,ua),yn.set(41994,ua),Le(ss,["ifd0","ifd1"],[[50827,function(s){return typeof s!="string"?Fc(s):s}],[306,pa],[40091,mn],[40092,mn],[40093,mn],[40094,mn],[40095,mn]]),Le(ss,"exif",[[40960,Ic],[36864,Ic],[36867,pa],[36868,pa],[40962,Dc],[40963,Dc]]),Le(ss,"gps",[[0,s=>Array.from(s).join(".")],[7,s=>Array.from(s).join(":")]]);var vn=class extends ti{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:ii.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let l={},h={};for(let g of Gc)l[g]=[],h[g]=0;return o.replace(nu,((g,m,d)=>{if(m==="<"){let a=++h[d];return l[d].push(a),`${g}#${a}`}return`${g}#${l[d].pop()}`}))})(t);let e=Qr.findAll(t,"rdf","Description");e.length===0&&e.push(new Qr("rdf","Description",void 0,t));let i,n={};for(let o of e)for(let l of o.properties)i=su(l.ns,n),Hc(l,i);return(function(o){let l;for(let h in o)l=o[h]=jr(o[h]),l===void 0&&delete o[h];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(vn,"type","xmp"),Nt(vn,"multiSegment",!0),ge.set("xmp",vn);var Sa=class s{static findAll(t){return jc(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=Vc(n),new s(e,i,n)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},Qr=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 jc(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=Sa.findAll(i),this.children=s.findAll(n),this.value=this.children.length===0?Vc(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 iu(this.children.map(eu));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)Hc(e,t);return this.value!==void 0&&(t.value=this.value),jr(t)}};function Hc(s,t){let e=s.serialize();e!==void 0&&(t[s.name]=e)}var eu=s=>s.serialize(),iu=s=>s.length===1?s[0]:s,su=(s,t)=>t[s]?t[s]:t[s]={};function jc(s,t){let e,i=[];if(!s)return i;for(;(e=t.exec(s))!==null;)i.push(e);return i}function Vc(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 Gc=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],nu=new RegExp(`(<|\\/)(${Gc.join("|")})`,"g"),Wc=tu;async function zs(s){try{return await Wc.parse(s)||null}catch{return null}}function we(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),s=>s.toString(16).padStart(2,"0")).join("")}async function Hs(s){if(typeof createImageBitmap>"u"||typeof document>"u"){if(s&&typeof s.arrayBuffer=="function"){let h=await s.arrayBuffer(),g=globalThis.Buffer,m=typeof g<"u"?g.from(h).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(h)));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((h,g)=>{let m=new FileReader;m.onload=()=>h(m.result),m.onerror=g,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 l=s.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(l,l==="image/png"?void 0:.82)}function Da(s,t=21,e=.2,i=128){let{data:n,width:o,height:l}=s,h=o+1,g=new Float64Array((o+1)*(l+1)),m=new Float64Array((o+1)*(l+1)),d=new Uint8Array(o*l);for(let f=0;f<l;f++){let A=0,C=0,u=f*o,y=(f+1)*h,r=f*h;for(let c=0;c<o;c++){let b=(u+c)*4,w=n[b]*77+n[b+1]*150+n[b+2]*29>>8;d[u+c]=w,A+=w,C+=w*w,g[y+c+1]=g[r+c+1]+A,m[y+c+1]=m[r+c+1]+C}}let a=Math.floor(t/2);for(let f=0;f<l;f++){let A=Math.max(0,f-a),C=Math.min(l-1,f+a),u=A*h,y=(C+1)*h;for(let r=0;r<o;r++){let c=Math.max(0,r-a),b=Math.min(o-1,r+a),w=(b-c+1)*(C-A+1),P=g[y+b+1]-g[u+b+1]-g[y+c]+g[u+c],E=m[y+b+1]-m[u+b+1]-m[y+c]+m[u+c],I=P/w,N=Math.max(0,E/w-I*I),z=Math.sqrt(N),H=I*(1+e*(z/i-1)),X=f*o+r,it=d[X]<H?0:255,at=X*4;n[at]=it,n[at+1]=it,n[at+2]=it}}return s}function Ia(s,t=21,e=.2,i=128){return new Promise(n=>{let o=new Image;o.onload=()=>{let l=document.createElement("canvas");l.width=o.width,l.height=o.height;let h=l.getContext("2d");h.drawImage(o,0,0);let g=h.getImageData(0,0,l.width,l.height);Da(g,t,e,i),h.putImageData(g,0,0);let m=s.startsWith("data:image/png"),d=m?"image/png":"image/jpeg";n(l.toDataURL(d,m?void 0:.82))},o.src=s})}function Ma(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"),l=o?"image/png":"image/jpeg";t(i.toDataURL(l,o?void 0:.82))},e.src=s})}function Ra(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 Ge(s){if(!s||typeof s!="object")return{crop:null,rotation:0,filter:"none"};let t=s.crop&&typeof s.crop=="object"&&s.crop.width>0&&s.crop.height>0?{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)}:null,e=(Math.round(s.rotation||0)%360+360)%360,i=s.filter==="bw"?"bw":"none";return{crop:t,rotation:e,filter:i}}function La(s){if(!s)return!1;let t=Ge(s);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function js(s,t){let e=Ge(t),i=s.naturalWidth||s.width||0,n=s.naturalHeight||s.height||0,o=document.createElement("canvas"),l=i,h=n,g=0,m=0;e.crop&&(g=Math.max(0,Math.min(e.crop.x,i)),m=Math.max(0,Math.min(e.crop.y,n)),l=Math.max(1,Math.min(e.crop.width,i-g)),h=Math.max(1,Math.min(e.crop.height,n-m))),o.width=l,o.height=h,o.getContext("2d").drawImage(s,g,m,l,h,0,0,l,h);let a=o;if(e.rotation!==0){let f=e.rotation,A=document.createElement("canvas");f===90||f===270?(A.width=a.height,A.height=a.width):(A.width=a.width,A.height=a.height);let C=A.getContext("2d");C.translate(A.width/2,A.height/2),C.rotate(f*Math.PI/180),C.drawImage(a,-a.width/2,-a.height/2),a=A}if(e.filter==="bw"){let f=a.getContext("2d"),A=f.getImageData(0,0,a.width,a.height);Da(A),f.putImageData(A,0,0)}return a}function Zr(s,t){if(!s)return Promise.resolve("");let e=Ge(t);return La(e)?new Promise((i,n)=>{let o=new Image;o.onload=()=>{try{let l=s.startsWith("data:image/png"),h=l?"image/png":"image/jpeg",g=js(o,e);i(g.toDataURL(h,l?void 0:.82))}catch(l){n(l)}},o.onerror=n,o.src=s}):Promise.resolve(s)}var _i=class{#t=null;#e=new Map;#i=new Map;constructor(t=Ls()){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){return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=we(),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){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(l=>l.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(l=>[l.id,l])),o=[];for(let l of e)n.has(l)&&(o.push(n.get(l)),n.delete(l));for(let l of n.values())o.push(l);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 l=o.pages.findIndex(d=>d.id===e);if(l===-1)return;let[h]=o.pages.splice(l,1);await this.saveDoc(t,o);let g=`${t}:${e}`;if(this.#r(g),!i||n<=0){if(typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(d){console.warn("[DocRepository] Adapter deletePage error:",d)}return}let m=setTimeout(async()=>{if(this.#i.delete(g),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(d){console.warn("[DocRepository] Adapter deletePage error:",d)}},n);return this.#i.set(g,{docId:t,pageId:e,page:h,index:l,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 l=Math.min(n.index,o.pages.length);return o.pages.splice(l,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)e[i.id]={name:i.name,pages:JSON.stringify(i.pages)};return e}async importDocs(t){let e=0;for(let[i,n]of Object.entries(t||{})){await this.getDoc(i)||e++;let l=this.#s(n.pages);await this.saveDoc(i,{name:n.name||"",pages:l})}return e}#s(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},Fa=new _i;var Oa=".";function eo(){return Oa}function os(s){typeof s=="string"&&(Oa=s.replace(/\/+$/,"")||".")}function ni(s){if(!s)return"";if(/^(https?:|\/\/|data:|blob:)/i.test(s))return s;let t=s.replace(/^\/+/,""),e=Oa;return!e||e==="."?t:`${e}/${t}`}var to=new Map;function ri(s,t){let e=t();if(e)return Promise.resolve(e);if(to.has(s))return to.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 l=ni(s),h=document.querySelector(`script[src="${l}"], script[src="${s}"]`);if(h){if(t()){n(t());return}h.addEventListener("load",()=>n(t()),{once:!0}),h.addEventListener("error",()=>o(new Error(`Failed to load "${s}": Network error`)),{once:!0});return}let g=document.createElement("script");g.src=l,g.async=!0,g.onload=()=>{let m=t();n(m)},g.onerror=()=>{to.delete(s),g.remove(),o(new Error(`Failed to load script "${s}": Network error`))},document.head.appendChild(g)});return to.set(s,i),i}async function io(){return ri("js/lib/cropper.js",()=>window.Cropper)}async function Vs(){return ri("js/lib/pdfkit.js",()=>window.PDFDocument)}async function so(){return ri("js/lib/jszip.min.js",()=>window.JSZip)}async function ki(){return ri("js/lib/marked.min.js",()=>window.marked)}async function no(){return ri("js/lib/peerjs.min.js",()=>window.Peer)}async function ro(){return ri("js/lib/qrcode.js",()=>window.qrcode)}async function oo(){return ri("js/lib/tesseract.min.js",()=>window.Tesseract)}var qc="2026-11-01T15:53:54.232Z",Xc="0.1.0";var oi=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 Pe=class extends oi{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 ai=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 We=class extends ai{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 qe=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 ru(s){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=s})}var li=class extends qe{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await ru(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),js(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 as=class extends qe{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 _n(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;if(s&&s.rotate!==void 0){let n=(Math.round(Number(s.rotate)/90)*90%360+360)%360;(n===90||n===180||n===270)&&(e=n)}let i=s&&s.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:i}}function ao(s){return s?!!(s.crop||s.rotate&&s.rotate!==0||s.filter&&s.filter!=="none"):!1}var ls=class{constructor(t){this.id=t.id,this.src=t.src,this.originalSrc=t.originalSrc||t.src,this.edits=_n(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}get isModified(){return ao(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}}},En=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 ls?e:new ls(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}}},Cn=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 lo(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 $a=["crop","rotate","filter","ocr","export","sync"],Na=["pdf","zip","png","jpg"],Ba=["eng"],Ua={};function Pi(s,t){!s||!t||(Ua[s]=t,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[s]=t))}function Ti(s){return Ua[s]?Ua[s]:typeof globalThis<"u"&&globalThis.__copio_services__?.[s]?globalThis.__copio_services__[s]:null}function ou(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($a):new Set($a)}function co(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 cs=class{#t=new Set($a);#e=[...Na];#i=[...Ba];#n=0;#r="";#s=null;#o=null;#c={};#a=!0;#d=!0;#p=null;#u=new Map;#l=new Map;constructor(t={}){this.#s=t.storage||Ls(t),this.#o=t.repository||new _i(this.#s),t.services&&(this.#c={...t.services}),t.imageProcessor?(this.#p=t.imageProcessor,this.#c.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#p=this.getService("imageProcessor"):typeof document<"u"?this.#p=new li:this.#p=new as,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#e=co(t.exportFormats,Na)),t.ocrLanguages!==void 0&&(this.#i=co(t.ocrLanguages,Ba)),t.maxPages!==void 0&&(this.#n=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&os(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]||Ti(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=ou(t),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof Pe&&this.setService("ocr",Ti("ocr"))):(this.#a=!1,this.setService("ocr",new Pe))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof Pe&&this.setService("ocr",Ti("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#a=!1,this.setService("ocr",new Pe))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(t){this.#a=!!t,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof Pe&&this.setService("ocr",Ti("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new Pe))}get pdf(){return this.#d&&this.#e.includes("pdf")}set pdf(t){this.#d=!!t,this.#d?(this.#e.includes("pdf")||this.#e.push("pdf"),this.getService("pdf")instanceof We&&this.setService("pdf",Ti("pdf"))):(this.#e=this.#e.filter(e=>e!=="pdf"),this.setService("pdf",new We))}get exportFormats(){return[...this.#e]}set exportFormats(t){this.#e=co(t,Na),this.#e.includes("pdf")?(this.#d=!0,this.getService("pdf")instanceof We&&this.setService("pdf",Ti("pdf"))):(this.#d=!1,this.setService("pdf",new We))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(t){this.#i=co(t,Ba)}get maxPages(){return this.#n}set maxPages(t){this.#n=Math.max(0,Number(t)||0)}get assetBase(){return eo()}set assetBase(t){os(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 _i(this.#s))}#f(t,e){this.#u.has(t)||this.#u.set(t,[]);let i=this.#u.get(t);i.push(e),i.length>50&&i.shift(),this.#l.has(t)&&(this.#l.get(t).length=0)}get imageProcessor(){return this.#p}setImageProcessor(t){t&&(this.#p=t,this.setService("imageProcessor",t))}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),n=i?.pages?i.pages.map(o=>o.id):[];return this.#f(t,{type:"reorder",priorOrder:n,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 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 l=o.pages.find(f=>f.id===e);if(!l)throw new Error(`Page with ID "${e}" not found in document "${n}"`);let h={...l.edits||{crop:null,rotate:0,filter:"none"}},g=l.src,m=_n({...h,...i}),d=l.originalSrc||l.src,a=d;return this.#p&&(a=await this.#p.renderEdits(d,m)),await this.updatePage(n,e,{originalSrc:d,src:a,edits:m}),this.#f(n,{type:"edit",pageId:e,priorEdits:h,priorSrc:g,newEdits:m,newSrc:a}),{...l,originalSrc:d,src:a,edits:m}}async undo(t){let e=await this.#g(t),i=e?this.#u.get(e):null;if(!i||i.length===0)return null;let n=i.pop();return this.#l.has(e)||this.#l.set(e,[]),this.#l.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.#o.reorderPages(e,n.priorOrder),{type:"reorder",priorOrder:n.priorOrder}):n}async redo(t){let e=await this.#g(t),i=e?this.#l.get(e):null;if(!i||i.length===0)return null;let n=i.pop();return this.#u.has(e)||this.#u.set(e,[]),this.#u.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.#o.subscribe(t)}async addFiles(t,e=null){if(!t||t.length===0)return[];let i=Array.from(t),n=[];for(let l of i)if(l.type==="application/pdf"){let h=this.getService("pdf");if(h&&typeof h.renderPdfPagesToDataUrls=="function"){let g=await h.renderPdfPagesToDataUrls(l);for(let m of g)n.push({id:we(),src:m,originalSrc:m,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:l.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(l.type&&l.type.startsWith("image/")){let h=await Hs(l),g=null;try{g=await zs(l)}catch{}n.push({id:we(),src:h,originalSrc:h,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:l.name||"Captured Image",orientation:g})}if(n.length===0)return[];let o=e;if(o)await this.getDocument(o)||await this.#o.saveDoc(o,{name:"Scanned Document",pages:[]});else{let l=await this.listDocuments();l.length>0?o=l[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let l=(await this.getDocument(o))?.pages||[],h=Math.max(0,this.#n-l.length);if(h<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);n.splice(h)}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#h(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 l=new Error('Feature "export" is disabled');throw Object.assign(l,{code:"FEATURE_DISABLED"}),l}if(!this.#d||!this.#e.includes("pdf")){let l=new Error('Feature "pdf" is disabled');throw Object.assign(l,{code:"FEATURE_DISABLED"}),l}let{docName:i,pages:n}=await this.#h(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,...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let l=new Error('Feature "export" is disabled');throw Object.assign(l,{code:"FEATURE_DISABLED"}),l}let{docName:i,pages:n}=await this.#h(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.#a||!this.hasFeature("ocr")){let m=new Error('Feature "ocr" is disabled');throw Object.assign(m,{code:"FEATURE_DISABLED"}),m}let{pages:n}=await this.#h(t),o=n;e&&(o=n.filter(m=>m.id===e));let l=this.getService("ocr");if(!l||typeof l.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let h=i.lang||this.#i[0]||"eng",g=await l.recognizeDocumentPages(o,{lang:h,...i});return{text:g.combinedText,...g}}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)}};function Kc(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 Ke(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Kc(Object(e),!0).forEach(function(i){au(s,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):Kc(Object(e)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(e,i))})}return s}function go(s){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?go=function(t){return typeof t}:go=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},go(s)}function au(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function hi(){return hi=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},hi.apply(this,arguments)}function lu(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 cu(s,t){if(s==null)return{};var e=lu(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 hu="1.15.6";function ci(s){if(typeof window<"u"&&window.navigator)return!!navigator.userAgent.match(s)}var di=ci(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),Fn=ci(/Edge/i),Yc=ci(/firefox/i),Dn=ci(/safari/i)&&!ci(/chrome/i)&&!ci(/android/i),tl=ci(/iP(ad|od|hone)/i),nh=ci(/chrome/i)&&ci(/android/i),rh={capture:!1,passive:!1};function Ot(s,t,e){s.addEventListener(t,e,!di&&rh)}function Ft(s,t,e){s.removeEventListener(t,e,!di&&rh)}function wo(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 oh(s){return s.host&&s!==document&&s.host.nodeType?s.host:s.parentNode}function Oe(s,t,e,i){if(s){e=e||document;do{if(t!=null&&(t[0]===">"?s.parentNode===e&&wo(s,t):wo(s,t))||i&&s===e)return s;if(s===e)break}while(s=oh(s))}return null}var Jc=/\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(Jc," ").replace(" "+t+" "," ");s.className=(i+(e?" "+t:"")).replace(Jc," ")}}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 Ks(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 ah(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 Xe(){var s=document.scrollingElement;return s||document.documentElement}function ie(s,t,e,i,n){if(!(!s.getBoundingClientRect&&s!==window)){var o,l,h,g,m,d,a;if(s!==window&&s.parentNode&&s!==Xe()?(o=s.getBoundingClientRect(),l=o.top,h=o.left,g=o.bottom,m=o.right,d=o.height,a=o.width):(l=0,h=0,g=window.innerHeight,m=window.innerWidth,d=window.innerHeight,a=window.innerWidth),(t||e)&&s!==window&&(n=n||s.parentNode,!di))do if(n&&n.getBoundingClientRect&&(Et(n,"transform")!=="none"||e&&Et(n,"position")!=="static")){var f=n.getBoundingClientRect();l-=f.top+parseInt(Et(n,"border-top-width")),h-=f.left+parseInt(Et(n,"border-left-width")),g=l+o.height,m=h+o.width;break}while(n=n.parentNode);if(i&&s!==window){var A=Ks(n||s),C=A&&A.a,u=A&&A.d;A&&(l/=u,h/=C,a/=C,d/=u,g=l+d,m=h+a)}return{top:l,left:h,bottom:g,right:m,width:a,height:d}}}function Qc(s,t,e){for(var i=Mi(s,!0),n=ie(s)[t];i;){var o=ie(i)[e],l=void 0;if(e==="top"||e==="left"?l=n>=o:l=n<=o,!l)return i;if(i===Xe())break;i=Mi(i,!1)}return!1}function Ys(s,t,e,i){for(var n=0,o=0,l=s.children;o<l.length;){if(l[o].style.display!=="none"&&l[o]!==Ct.ghost&&(i||l[o]!==Ct.dragged)&&Oe(l[o],e.draggable,s,!1)){if(n===t)return l[o];n++}o++}return null}function el(s,t){for(var e=s.lastElementChild;e&&(e===Ct.ghost||Et(e,"display")==="none"||t&&!wo(e,t));)e=e.previousElementSibling;return e||null}function De(s,t){var e=0;if(!s||!s.parentNode)return-1;for(;s=s.previousElementSibling;)s.nodeName.toUpperCase()!=="TEMPLATE"&&s!==Ct.clone&&(!t||wo(s,t))&&e++;return e}function Zc(s){var t=0,e=0,i=Xe();if(s)do{var n=Ks(s),o=n.a,l=n.d;t+=s.scrollLeft*o,e+=s.scrollTop*l}while(s!==i&&(s=s.parentNode));return[t,e]}function du(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 Mi(s,t){if(!s||!s.getBoundingClientRect)return Xe();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 Xe();if(i||t)return e;i=!0}}while(e=e.parentNode);return Xe()}function uu(s,t){if(s&&t)for(var e in t)t.hasOwnProperty(e)&&(s[e]=t[e]);return s}function za(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 In;function lh(s,t){return function(){if(!In){var e=arguments,i=this;e.length===1?s.call(i,e[0]):s.apply(i,e),In=setTimeout(function(){In=void 0},t)}}}function pu(){clearTimeout(In),In=void 0}function ch(s,t,e){s.scrollLeft+=t,s.scrollTop+=e}function hh(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 dh(s,t,e){var i={};return Array.from(s.children).forEach(function(n){var o,l,h,g;if(!(!Oe(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((l=i.top)!==null&&l!==void 0?l:1/0,m.top),i.right=Math.max((h=i.right)!==null&&h!==void 0?h:-1/0,m.right),i.bottom=Math.max((g=i.bottom)!==null&&g!==void 0?g:-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 fu(){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=Ke({},s[s.length-1].rect);if(n.thisAnimationDuration){var l=Ks(n,!0);l&&(o.top-=l.f,o.left-=l.e)}n.fromRect=o}})}},addAnimationState:function(i){s.push(i)},removeAnimationState:function(i){s.splice(du(s,{target:i}),1)},animateAll:function(i){var n=this;if(!this.options.animation){clearTimeout(t),typeof i=="function"&&i();return}var o=!1,l=0;s.forEach(function(h){var g=0,m=h.target,d=m.fromRect,a=ie(m),f=m.prevFromRect,A=m.prevToRect,C=h.rect,u=Ks(m,!0);u&&(a.top-=u.f,a.left-=u.e),m.toRect=a,m.thisAnimationDuration&&za(f,a)&&!za(d,a)&&(C.top-a.top)/(C.left-a.left)===(d.top-a.top)/(d.left-a.left)&&(g=mu(C,f,A,n.options)),za(a,d)||(m.prevFromRect=d,m.prevToRect=a,g||(g=n.options.animation),n.animate(m,C,a,g)),g&&(o=!0,l=Math.max(l,g),clearTimeout(m.animationResetTimer),m.animationResetTimer=setTimeout(function(){m.animationTime=0,m.prevFromRect=null,m.fromRect=null,m.prevToRect=null,m.thisAnimationDuration=null},g),m.thisAnimationDuration=g)}),clearTimeout(t),o?t=setTimeout(function(){typeof i=="function"&&i()},l):typeof i=="function"&&i(),s=[]},animate:function(i,n,o,l){if(l){Et(i,"transition",""),Et(i,"transform","");var h=Ks(this.el),g=h&&h.a,m=h&&h.d,d=(n.left-o.left)/(g||1),a=(n.top-o.top)/(m||1);i.animatingX=!!d,i.animatingY=!!a,Et(i,"transform","translate3d("+d+"px,"+a+"px,0)"),this.forRepaintDummy=gu(i),Et(i,"transition","transform "+l+"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},l)}}}}function gu(s){return s.offsetWidth}function mu(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 Gs=[],Ha={initializeByDefault:!0},On={mount:function(t){for(var e in Ha)Ha.hasOwnProperty(e)&&!(e in t)&&(t[e]=Ha[e]);Gs.forEach(function(i){if(i.pluginName===t.pluginName)throw"Sortable: Cannot mount plugin ".concat(t.pluginName," more than once")}),Gs.push(t)},pluginEvent:function(t,e,i){var n=this;this.eventCanceled=!1,i.cancel=function(){n.eventCanceled=!0};var o=t+"Global";Gs.forEach(function(l){e[l.pluginName]&&(e[l.pluginName][o]&&e[l.pluginName][o](Ke({sortable:e},i)),e.options[l.pluginName]&&e[l.pluginName][t]&&e[l.pluginName][t](Ke({sortable:e},i)))})},initializePlugins:function(t,e,i,n){Gs.forEach(function(h){var g=h.pluginName;if(!(!t.options[g]&&!h.initializeByDefault)){var m=new h(t,e,t.options);m.sortable=t,m.options=t.options,t[g]=m,hi(i,m.defaults)}});for(var o in t.options)if(t.options.hasOwnProperty(o)){var l=this.modifyOption(t,o,t.options[o]);typeof l<"u"&&(t.options[o]=l)}},getEventProperties:function(t,e){var i={};return Gs.forEach(function(n){typeof n.eventProperties=="function"&&hi(i,n.eventProperties.call(e[n.pluginName],t))}),i},modifyOption:function(t,e,i){var n;return Gs.forEach(function(o){t[o.pluginName]&&o.optionListeners&&typeof o.optionListeners[e]=="function"&&(n=o.optionListeners[e].call(t[o.pluginName],i))}),n}};function bu(s){var t=s.sortable,e=s.rootEl,i=s.name,n=s.targetEl,o=s.cloneEl,l=s.toEl,h=s.fromEl,g=s.oldIndex,m=s.newIndex,d=s.oldDraggableIndex,a=s.newDraggableIndex,f=s.originalEvent,A=s.putSortable,C=s.extraEventProperties;if(t=t||e&&e[Ae],!!t){var u,y=t.options,r="on"+i.charAt(0).toUpperCase()+i.substr(1);window.CustomEvent&&!di&&!Fn?u=new CustomEvent(i,{bubbles:!0,cancelable:!0}):(u=document.createEvent("Event"),u.initEvent(i,!0,!0)),u.to=l||e,u.from=h||e,u.item=n||e,u.clone=o,u.oldIndex=g,u.newIndex=m,u.oldDraggableIndex=d,u.newDraggableIndex=a,u.originalEvent=f,u.pullMode=A?A.lastPutMode:void 0;var c=Ke(Ke({},C),On.getEventProperties(i,t));for(var b in c)u[b]=c[b];e&&e.dispatchEvent(u),y[r]&&y[r].call(t,u)}}var yu=["evt"],xe=function(t,e){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},n=i.evt,o=cu(i,yu);On.pluginEvent.bind(Ct)(t,e,Ke({dragEl:gt,parentEl:Qt,ghostEl:kt,rootEl:Gt,nextEl:us,lastDownEl:mo,cloneEl:Kt,cloneHidden:Ii,dragStarted:kn,putSortable:ce,activeSortable:Ct.active,originalEvent:n,oldIndex:Xs,oldDraggableIndex:Mn,newIndex:ke,newDraggableIndex:Di,hideGhostForTarget:gh,unhideGhostForTarget:mh,cloneNowHidden:function(){Ii=!0},cloneNowShown:function(){Ii=!1},dispatchSortableEvent:function(h){me({sortable:e,name:h,originalEvent:n})}},o))};function me(s){bu(Ke({putSortable:ce,cloneEl:Kt,targetEl:gt,rootEl:Gt,oldIndex:Xs,oldDraggableIndex:Mn,newIndex:ke,newDraggableIndex:Di},s))}var gt,Qt,kt,Gt,us,mo,Kt,Ii,Xs,ke,Mn,Di,ho,ce,qs=!1,xo=!1,Ao=[],hs,Fe,ja,Va,th,eh,kn,Ws,Rn,Ln=!1,uo=!1,bo,ue,Ga=[],Ya=!1,So=[],Co=typeof document<"u",po=tl,ih=Fn||di?"cssFloat":"float",vu=Co&&!nh&&!tl&&"draggable"in document.createElement("div"),uh=(function(){if(Co){if(di)return!1;var s=document.createElement("x");return s.style.cssText="pointer-events:auto",s.style.pointerEvents==="auto"}})(),ph=function(t,e){var i=Et(t),n=parseInt(i.width)-parseInt(i.paddingLeft)-parseInt(i.paddingRight)-parseInt(i.borderLeftWidth)-parseInt(i.borderRightWidth),o=Ys(t,0,e),l=Ys(t,1,e),h=o&&Et(o),g=l&&Et(l),m=h&&parseInt(h.marginLeft)+parseInt(h.marginRight)+ie(o).width,d=g&&parseInt(g.marginLeft)+parseInt(g.marginRight)+ie(l).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&&h.float&&h.float!=="none"){var a=h.float==="left"?"left":"right";return l&&(g.clear==="both"||g.clear===a)?"vertical":"horizontal"}return o&&(h.display==="block"||h.display==="flex"||h.display==="table"||h.display==="grid"||m>=n&&i[ih]==="none"||l&&i[ih]==="none"&&m+d>n)?"vertical":"horizontal"},wu=function(t,e,i){var n=i?t.left:t.top,o=i?t.right:t.bottom,l=i?t.width:t.height,h=i?e.left:e.top,g=i?e.right:e.bottom,m=i?e.width:e.height;return n===h||o===g||n+l/2===h+m/2},xu=function(t,e){var i;return Ao.some(function(n){var o=n[Ae].options.emptyInsertThreshold;if(!(!o||el(n))){var l=ie(n),h=t>=l.left-o&&t<=l.right+o,g=e>=l.top-o&&e<=l.bottom+o;if(h&&g)return i=n}}),i},fh=function(t){function e(o,l){return function(h,g,m,d){var a=h.options.group.name&&g.options.group.name&&h.options.group.name===g.options.group.name;if(o==null&&(l||a))return!0;if(o==null||o===!1)return!1;if(l&&o==="clone")return o;if(typeof o=="function")return e(o(h,g,m,d),l)(h,g,m,d);var f=(l?h:g).options.group.name;return o===!0||typeof o=="string"&&o===f||o.join&&o.indexOf(f)>-1}}var i={},n=t.group;(!n||go(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},gh=function(){!uh&&kt&&Et(kt,"display","none")},mh=function(){!uh&&kt&&Et(kt,"display","")};Co&&!nh&&document.addEventListener("click",function(s){if(xo)return s.preventDefault(),s.stopPropagation&&s.stopPropagation(),s.stopImmediatePropagation&&s.stopImmediatePropagation(),xo=!1,!1},!0);var ds=function(t){if(gt){t=t.touches?t.touches[0]:t;var e=xu(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)}}},Au=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=hi({},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 ph(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(l,h){l.setData("Text",h.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&&(!Dn||tl),emptyInsertThreshold:5};On.initializePlugins(this,s,e);for(var i in e)!(i in t)&&(t[i]=e[i]);fh(t);for(var n in this)n.charAt(0)==="_"&&typeof this[n]=="function"&&(this[n]=this[n].bind(this));this.nativeDraggable=t.forceFallback?!1:vu,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)),Ao.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),hi(this,fu())}Ct.prototype={constructor:Ct,_isOutsideThisEl:function(t){!this.el.contains(t)&&t!==this.el&&(Ws=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,l=t.type,h=t.touches&&t.touches[0]||t.pointerType&&t.pointerType==="touch"&&t,g=(h||t).target,m=t.target.shadowRoot&&(t.path&&t.path[0]||t.composedPath&&t.composedPath()[0])||g,d=n.filter;if(Du(i),!gt&&!(/mousedown|pointerdown/.test(l)&&t.button!==0||n.disabled)&&!m.isContentEditable&&!(!this.nativeDraggable&&Dn&&g&&g.tagName.toUpperCase()==="SELECT")&&(g=Oe(g,n.draggable,i,!1),!(g&&g.animated)&&mo!==g)){if(Xs=De(g),Mn=De(g,n.draggable),typeof d=="function"){if(d.call(this,t,g,this)){me({sortable:e,rootEl:m,name:"filter",targetEl:g,toEl:i,fromEl:i}),xe("filter",e,{evt:t}),o&&t.preventDefault();return}}else if(d&&(d=d.split(",").some(function(a){if(a=Oe(m,a.trim(),i,!1),a)return me({sortable:e,rootEl:a,name:"filter",targetEl:g,fromEl:i,toEl:i}),xe("filter",e,{evt:t}),!0}),d)){o&&t.preventDefault();return}n.handle&&!Oe(m,n.handle,i,!1)||this._prepareDragStart(t,h,g)}}},_prepareDragStart:function(t,e,i){var n=this,o=n.el,l=n.options,h=o.ownerDocument,g;if(i&&!gt&&i.parentNode===o){var m=ie(i);if(Gt=o,gt=i,Qt=gt.parentNode,us=gt.nextSibling,mo=i,ho=l.group,Ct.dragged=gt,hs={target:gt,clientX:(e||t).clientX,clientY:(e||t).clientY},th=hs.clientX-m.left,eh=hs.clientY-m.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,gt.style["will-change"]="all",g=function(){if(xe("delayEnded",n,{evt:t}),Ct.eventCanceled){n._onDrop();return}n._disableDelayedDragEvents(),!Yc&&n.nativeDraggable&&(gt.draggable=!0),n._triggerDragStart(t,e),me({sortable:n,name:"choose",originalEvent:t}),_e(gt,l.chosenClass,!0)},l.ignore.split(",").forEach(function(d){ah(gt,d.trim(),Wa)}),Ot(h,"dragover",ds),Ot(h,"mousemove",ds),Ot(h,"touchmove",ds),l.supportPointer?(Ot(h,"pointerup",n._onDrop),!this.nativeDraggable&&Ot(h,"pointercancel",n._onDrop)):(Ot(h,"mouseup",n._onDrop),Ot(h,"touchend",n._onDrop),Ot(h,"touchcancel",n._onDrop)),Yc&&this.nativeDraggable&&(this.options.touchStartThreshold=4,gt.draggable=!0),xe("delayStart",this,{evt:t}),l.delay&&(!l.delayOnTouchOnly||e)&&(!this.nativeDraggable||!(Fn||di))){if(Ct.eventCanceled){this._onDrop();return}l.supportPointer?(Ot(h,"pointerup",n._disableDelayedDrag),Ot(h,"pointercancel",n._disableDelayedDrag)):(Ot(h,"mouseup",n._disableDelayedDrag),Ot(h,"touchend",n._disableDelayedDrag),Ot(h,"touchcancel",n._disableDelayedDrag)),Ot(h,"mousemove",n._delayedDragTouchMoveHandler),Ot(h,"touchmove",n._delayedDragTouchMoveHandler),l.supportPointer&&Ot(h,"pointermove",n._delayedDragTouchMoveHandler),n._dragStartTimer=setTimeout(g,l.delay)}else g()}},_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&&Wa(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(Gt,"dragstart",this._onDragStart));try{document.selection?yo(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(t,e){if(qs=!1,Gt&>){xe("dragStarted",this,{evt:e}),this.nativeDraggable&&Ot(document,"dragover",Au);var i=this.options;!t&&_e(gt,i.dragClass,!1),_e(gt,i.ghostClass,!0),Ct.active=this,t&&this._appendGhost(),me({sortable:this,name:"start",originalEvent:e})}else this._nulling()},_emulateDragOver:function(){if(Fe){this._lastX=Fe.clientX,this._lastY=Fe.clientY,gh();for(var t=document.elementFromPoint(Fe.clientX,Fe.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(Fe.clientX,Fe.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:Fe.clientX,clientY:Fe.clientY,target:t,rootEl:e}),i&&!this.options.dragoverBubble)break}t=e}while(e=oh(e));mh()}},_onTouchMove:function(t){if(hs){var e=this.options,i=e.fallbackTolerance,n=e.fallbackOffset,o=t.touches?t.touches[0]:t,l=kt&&Ks(kt,!0),h=kt&&l&&l.a,g=kt&&l&&l.d,m=po&&ue&&Zc(ue),d=(o.clientX-hs.clientX+n.x)/(h||1)+(m?m[0]-Ga[0]:0)/(h||1),a=(o.clientY-hs.clientY+n.y)/(g||1)+(m?m[1]-Ga[1]:0)/(g||1);if(!Ct.active&&!qs){if(i&&Math.max(Math.abs(o.clientX-this._lastX),Math.abs(o.clientY-this._lastY))<i)return;this._onDragStart(t,!0)}if(kt){l?(l.e+=d-(ja||0),l.f+=a-(Va||0)):l={a:1,b:0,c:0,d:1,e:d,f:a};var f="matrix(".concat(l.a,",").concat(l.b,",").concat(l.c,",").concat(l.d,",").concat(l.e,",").concat(l.f,")");Et(kt,"webkitTransform",f),Et(kt,"mozTransform",f),Et(kt,"msTransform",f),Et(kt,"transform",f),ja=d,Va=a,Fe=o}t.cancelable&&t.preventDefault()}},_appendGhost:function(){if(!kt){var t=this.options.fallbackOnBody?document.body:Gt,e=ie(gt,!0,po,!0,t),i=this.options;if(po){for(ue=t;Et(ue,"position")==="static"&&Et(ue,"transform")==="none"&&ue!==document;)ue=ue.parentNode;ue!==document.body&&ue!==document.documentElement?(ue===document&&(ue=Xe()),e.top+=ue.scrollTop,e.left+=ue.scrollLeft):ue=Xe(),Ga=Zc(ue)}kt=gt.cloneNode(!0),_e(kt,i.ghostClass,!1),_e(kt,i.fallbackClass,!0),_e(kt,i.dragClass,!0),Et(kt,"transition",""),Et(kt,"transform",""),Et(kt,"box-sizing","border-box"),Et(kt,"margin",0),Et(kt,"top",e.top),Et(kt,"left",e.left),Et(kt,"width",e.width),Et(kt,"height",e.height),Et(kt,"opacity","0.8"),Et(kt,"position",po?"absolute":"fixed"),Et(kt,"zIndex","100000"),Et(kt,"pointerEvents","none"),Ct.ghost=kt,t.appendChild(kt),Et(kt,"transform-origin",th/parseInt(kt.style.width)*100+"% "+eh/parseInt(kt.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=hh(gt),Kt.removeAttribute("id"),Kt.draggable=!1,Kt.style["will-change"]="",this._hideClone(),_e(Kt,this.options.chosenClass,!1),Ct.clone=Kt),i.cloneId=yo(function(){xe("clone",i),!Ct.eventCanceled&&(i.options.removeCloneOnHide||Gt.insertBefore(Kt,gt),i._hideClone(),me({sortable:i,name:"clone"}))}),!e&&_e(gt,o.dragClass,!0),e?(xo=!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)")),qs=!0,i._dragStartId=yo(i._dragStarted.bind(i,e,t)),Ot(document,"selectstart",i),kn=!0,window.getSelection().removeAllRanges(),Dn&&Et(document.body,"user-select","none")},_onDragOver:function(t){var e=this.el,i=t.target,n,o,l,h=this.options,g=h.group,m=Ct.active,d=ho===g,a=h.sort,f=ce||m,A,C=this,u=!1;if(Ya)return;function y(et,rt){xe(et,C,Ke({evt:t,isOwner:d,axis:A?"vertical":"horizontal",revert:l,dragRect:n,targetRect:o,canSort:a,fromSortable:f,target:i,completed:c,onMove:function(st,W){return fo(Gt,e,gt,n,st,ie(st),t,W)},changed:b},rt))}function r(){y("dragOverAnimationCapture"),C.captureAnimationState(),C!==f&&f.captureAnimationState()}function c(et){return y("dragOverCompleted",{insertion:et}),et&&(d?m._hideClone():m._showClone(C),C!==f&&(_e(gt,ce?ce.options.ghostClass:m.options.ghostClass,!1),_e(gt,h.ghostClass,!0)),ce!==C&&C!==Ct.active?ce=C:C===Ct.active&&ce&&(ce=null),f===C&&(C._ignoreWhileAnimating=i),C.animateAll(function(){y("dragOverAnimationComplete"),C._ignoreWhileAnimating=null}),C!==f&&(f.animateAll(),f._ignoreWhileAnimating=null)),(i===gt&&!gt.animated||i===e&&!i.animated)&&(Ws=null),!h.dragoverBubble&&!t.rootEl&&i!==document&&(gt.parentNode[Ae]._isOutsideThisEl(t.target),!et&&ds(t)),!h.dragoverBubble&&t.stopPropagation&&t.stopPropagation(),u=!0}function b(){ke=De(gt),Di=De(gt,h.draggable),me({sortable:C,name:"change",toEl:e,newIndex:ke,newDraggableIndex:Di,originalEvent:t})}if(t.preventDefault!==void 0&&t.cancelable&&t.preventDefault(),i=Oe(i,h.draggable,e,!0),y("dragOver"),Ct.eventCanceled)return u;if(gt.contains(t.target)||i.animated&&i.animatingX&&i.animatingY||C._ignoreWhileAnimating===i)return c(!1);if(xo=!1,m&&!h.disabled&&(d?a||(l=Qt!==Gt):ce===this||(this.lastPutMode=ho.checkPull(this,m,gt,t))&&g.checkPut(this,m,gt,t))){if(A=this._getDirection(t,i)==="vertical",n=ie(gt),y("dragOverValid"),Ct.eventCanceled)return u;if(l)return Qt=Gt,r(),this._hideClone(),y("revert"),Ct.eventCanceled||(us?Gt.insertBefore(gt,us):Gt.appendChild(gt)),c(!0);var w=el(e,h.draggable);if(!w||_u(t,A,this)&&!w.animated){if(w===gt)return c(!1);if(w&&e===t.target&&(i=w),i&&(o=ie(i)),fo(Gt,e,gt,n,i,o,t,!!i)!==!1)return r(),w&&w.nextSibling?e.insertBefore(gt,w.nextSibling):e.appendChild(gt),Qt=e,b(),c(!0)}else if(w&&Cu(t,A,this)){var P=Ys(e,0,h,!0);if(P===gt)return c(!1);if(i=P,o=ie(i),fo(Gt,e,gt,n,i,o,t,!1)!==!1)return r(),e.insertBefore(gt,P),Qt=e,b(),c(!0)}else if(i.parentNode===e){o=ie(i);var E=0,I,N=gt.parentNode!==e,z=!wu(gt.animated&>.toRect||n,i.animated&&i.toRect||o,A),H=A?"top":"left",X=Qc(i,"top","top")||Qc(gt,"top","top"),it=X?X.scrollTop:void 0;Ws!==i&&(I=o[H],Ln=!1,uo=!z&&h.invertSwap||N),E=ku(t,i,o,A,z?1:h.swapThreshold,h.invertedSwapThreshold==null?h.swapThreshold:h.invertedSwapThreshold,uo,Ws===i);var at;if(E!==0){var K=De(gt);do K-=E,at=Qt.children[K];while(at&&(Et(at,"display")==="none"||at===kt))}if(E===0||at===i)return c(!1);Ws=i,Rn=E;var j=i.nextElementSibling,G=!1;G=E===1;var Y=fo(Gt,e,gt,n,i,o,t,G);if(Y!==!1)return(Y===1||Y===-1)&&(G=Y===1),Ya=!0,setTimeout(Eu,30),r(),G&&!j?e.appendChild(gt):i.parentNode.insertBefore(gt,G?j:i),X&&ch(X,0,it-X.scrollTop),Qt=gt.parentNode,I!==void 0&&!uo&&(bo=Math.abs(I-ie(i)[H])),b(),c(!0)}if(e.contains(gt))return c(!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",ds),Ft(document,"mousemove",ds),Ft(document,"touchmove",ds)},_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(ke=De(gt),Di=De(gt,i.draggable),xe("drop",this,{evt:t}),Qt=gt&>.parentNode,ke=De(gt),Di=De(gt,i.draggable),Ct.eventCanceled){this._nulling();return}qs=!1,uo=!1,Ln=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),Ja(this.cloneId),Ja(this._dragStartId),this.nativeDraggable&&(Ft(document,"drop",this),Ft(e,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),Dn&&Et(document.body,"user-select",""),Et(gt,"transform",""),t&&(kn&&(t.cancelable&&t.preventDefault(),!i.dropBubble&&t.stopPropagation()),kt&&kt.parentNode&&kt.parentNode.removeChild(kt),(Gt===Qt||ce&&ce.lastPutMode!=="clone")&&Kt&&Kt.parentNode&&Kt.parentNode.removeChild(Kt),gt&&(this.nativeDraggable&&Ft(gt,"dragend",this),Wa(gt),gt.style["will-change"]="",kn&&!qs&&_e(gt,ce?ce.options.ghostClass:this.options.ghostClass,!1),_e(gt,this.options.chosenClass,!1),me({sortable:this,name:"unchoose",toEl:Qt,newIndex:null,newDraggableIndex:null,originalEvent:t}),Gt!==Qt?(ke>=0&&(me({rootEl:Qt,name:"add",toEl:Qt,fromEl:Gt,originalEvent:t}),me({sortable:this,name:"remove",toEl:Qt,originalEvent:t}),me({rootEl:Qt,name:"sort",toEl:Qt,fromEl:Gt,originalEvent:t}),me({sortable:this,name:"sort",toEl:Qt,originalEvent:t})),ce&&ce.save()):ke!==Xs&&ke>=0&&(me({sortable:this,name:"update",toEl:Qt,originalEvent:t}),me({sortable:this,name:"sort",toEl:Qt,originalEvent:t})),Ct.active&&((ke==null||ke===-1)&&(ke=Xs,Di=Mn),me({sortable:this,name:"end",toEl:Qt,originalEvent:t}),this.save()))),this._nulling()},_nulling:function(){xe("nulling",this),Gt=gt=Qt=kt=us=Kt=mo=Ii=hs=Fe=kn=ke=Di=Xs=Mn=Ws=Rn=ce=ho=Ct.dragged=Ct.ghost=Ct.clone=Ct.active=null,So.forEach(function(t){t.checked=!0}),So.length=ja=Va=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":gt&&(this._onDragOver(t),Su(t));break;case"selectstart":t.preventDefault();break}},toArray:function(){for(var t=[],e,i=this.el.children,n=0,o=i.length,l=this.options;n<o;n++)e=i[n],Oe(e,l.draggable,this.el,!1)&&t.push(e.getAttribute(l.dataIdAttr)||Pu(e));return t},sort:function(t,e){var i={},n=this.el;this.toArray().forEach(function(o,l){var h=n.children[l];Oe(h,this.options.draggable,n,!1)&&(i[o]=h)},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 Oe(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=On.modifyOption(this,t,e);typeof n<"u"?i[t]=n:i[t]=e,t==="group"&&fh(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(),Ao.splice(Ao.indexOf(this.el),1),this.el=t=null},_hideClone:function(){if(!Ii){if(xe("hideClone",this),Ct.eventCanceled)return;Et(Kt,"display","none"),this.options.removeCloneOnHide&&Kt.parentNode&&Kt.parentNode.removeChild(Kt),Ii=!0}},_showClone:function(t){if(t.lastPutMode!=="clone"){this._hideClone();return}if(Ii){if(xe("showClone",this),Ct.eventCanceled)return;gt.parentNode==Gt&&!this.options.group.revertClone?Gt.insertBefore(Kt,gt):us?Gt.insertBefore(Kt,us):Gt.appendChild(Kt),this.options.group.revertClone&&this.animate(gt,Kt),Et(Kt,"display",""),Ii=!1}}};function Su(s){s.dataTransfer&&(s.dataTransfer.dropEffect="move"),s.cancelable&&s.preventDefault()}function fo(s,t,e,i,n,o,l,h){var g,m=s[Ae],d=m.options.onMove,a;return window.CustomEvent&&!di&&!Fn?g=new CustomEvent("move",{bubbles:!0,cancelable:!0}):(g=document.createEvent("Event"),g.initEvent("move",!0,!0)),g.to=t,g.from=s,g.dragged=e,g.draggedRect=i,g.related=n||t,g.relatedRect=o||ie(t),g.willInsertAfter=h,g.originalEvent=l,s.dispatchEvent(g),d&&(a=d.call(m,g,l)),a}function Wa(s){s.draggable=!1}function Eu(){Ya=!1}function Cu(s,t,e){var i=ie(Ys(e.el,0,e.options,!0)),n=dh(e.el,e.options,kt),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 _u(s,t,e){var i=ie(el(e.el,e.options.draggable)),n=dh(e.el,e.options,kt),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 ku(s,t,e,i,n,o,l,h){var g=i?s.clientY:s.clientX,m=i?e.height:e.width,d=i?e.top:e.left,a=i?e.bottom:e.right,f=!1;if(!l){if(h&&bo<m*n){if(!Ln&&(Rn===1?g>d+m*o/2:g<a-m*o/2)&&(Ln=!0),Ln)f=!0;else if(Rn===1?g<d+bo:g>a-bo)return-Rn}else if(g>d+m*(1-n)/2&&g<a-m*(1-n)/2)return Tu(t)}return f=f||l,f&&(g<d+m*o/2||g>a-m*o/2)?g>d+m/2?1:-1:0}function Tu(s){return De(gt)<De(s)?1:-1}function Pu(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 Du(s){So.length=0;for(var t=s.getElementsByTagName("input"),e=t.length;e--;){var i=t[e];i.checked&&So.push(i)}}function yo(s){return setTimeout(s,0)}function Ja(s){return clearTimeout(s)}Co&&Ot(document,"touchmove",function(s){(Ct.active||qs)&&s.cancelable&&s.preventDefault()});Ct.utils={on:Ot,off:Ft,css:Et,find:ah,is:function(t,e){return!!Oe(t,e,t,!1)},extend:uu,throttle:lh,closest:Oe,toggleClass:_e,clone:hh,index:De,nextTick:yo,cancelNextTick:Ja,detectDirection:ph,getChild:Ys,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=Ke(Ke({},Ct.utils),i.utils)),On.mount(i)})};Ct.create=function(s,t){return new Ct(s,t)};Ct.version=hu;var ee=[],Tn,Qa,Za=!1,qa,Xa,Eo,Pn;function Iu(){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)),sh(),vo(),pu()},nulling:function(){Eo=Qa=Tn=Za=Pn=qa=Xa=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,l=(e.touches?e.touches[0]:e).clientY,h=document.elementFromPoint(o,l);if(Eo=e,i||this.options.forceAutoScrollFallback||Fn||di||Dn){Ka(e,this.options,h,i);var g=Mi(h,!0);Za&&(!Pn||o!==qa||l!==Xa)&&(Pn&&sh(),Pn=setInterval(function(){var m=Mi(document.elementFromPoint(o,l),!0);m!==g&&(g=m,vo()),Ka(e,n.options,m,i)},10),qa=o,Xa=l)}else{if(!this.options.bubbleScroll||Mi(h,!0)===Xe()){vo();return}Ka(e,this.options,Mi(h,!1),!1)}}},hi(s,{pluginName:"scroll",initializeByDefault:!0})}function vo(){ee.forEach(function(s){clearInterval(s.pid)}),ee=[]}function sh(){clearInterval(Pn)}var Ka=lh(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,l=t.scrollSensitivity,h=t.scrollSpeed,g=Xe(),m=!1,d;Qa!==e&&(Qa=e,vo(),Tn=t.scroll,d=t.scrollFn,Tn===!0&&(Tn=Mi(e,!0)));var a=0,f=Tn;do{var A=f,C=ie(A),u=C.top,y=C.bottom,r=C.left,c=C.right,b=C.width,w=C.height,P=void 0,E=void 0,I=A.scrollWidth,N=A.scrollHeight,z=Et(A),H=A.scrollLeft,X=A.scrollTop;A===g?(P=b<I&&(z.overflowX==="auto"||z.overflowX==="scroll"||z.overflowX==="visible"),E=w<N&&(z.overflowY==="auto"||z.overflowY==="scroll"||z.overflowY==="visible")):(P=b<I&&(z.overflowX==="auto"||z.overflowX==="scroll"),E=w<N&&(z.overflowY==="auto"||z.overflowY==="scroll"));var it=P&&(Math.abs(c-n)<=l&&H+b<I)-(Math.abs(r-n)<=l&&!!H),at=E&&(Math.abs(y-o)<=l&&X+w<N)-(Math.abs(u-o)<=l&&!!X);if(!ee[a])for(var K=0;K<=a;K++)ee[K]||(ee[K]={});(ee[a].vx!=it||ee[a].vy!=at||ee[a].el!==A)&&(ee[a].el=A,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(Eo);var j=ee[this.layer].vy?ee[this.layer].vy*h:0,G=ee[this.layer].vx?ee[this.layer].vx*h:0;typeof d=="function"&&d.call(Ct.dragged.parentNode[Ae],G,j,s,Eo,ee[this.layer].el)!=="continue"||ch(ee[this.layer].el,G,j)}.bind({layer:a}),24))),a++}while(t.bubbleScroll&&f!==g&&(f=Mi(f,!1)));Za=m}},30),bh=function(t){var e=t.originalEvent,i=t.putSortable,n=t.dragEl,o=t.activeSortable,l=t.dispatchSortableEvent,h=t.hideGhostForTarget,g=t.unhideGhostForTarget;if(e){var m=i||o;h();var d=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:e,a=document.elementFromPoint(d.clientX,d.clientY);g(),m&&!m.el.contains(a)&&(l("spill"),this.onSpill({dragEl:n,putSortable:i}))}};function il(){}il.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=Ys(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:bh};hi(il,{pluginName:"revertOnSpill"});function sl(){}sl.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:bh};hi(sl,{pluginName:"removeOnSpill"});Ct.mount(new Iu);Ct.mount(sl,il);var yh=Ct;var Js,Nn,Bn,_o,Yu={976:(s,t,e)=>{e.d(t,{AnnotationLayer:()=>T,FreeTextAnnotationElement:()=>H,InkAnnotationElement:()=>Y,StampAnnotationElement:()=>W});var i=e(292),n=e(419),o=e(792);function l(R){return Math.floor(255*Math.max(0,Math.min(1,R))).toString(16).padStart(2,"0")}function h(R){return Math.max(0,Math.min(255,255*R))}class g{static CMYK_G([p,v,_,k]){return["G",1-Math.min(1,.3*p+.59*_+.11*v+k)]}static G_CMYK([p]){return["CMYK",0,0,0,1-p]}static G_RGB([p]){return["RGB",p,p,p]}static G_rgb([p]){return[p=h(p),p,p]}static G_HTML([p]){let v=l(p);return`#${v}${v}${v}`}static RGB_G([p,v,_]){return["G",.3*p+.59*v+.11*_]}static RGB_rgb(p){return p.map(h)}static RGB_HTML(p){return`#${p.map(l).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([p,v,_,k]){return["RGB",1-Math.min(1,p+k),1-Math.min(1,_+k),1-Math.min(1,v+k)]}static CMYK_rgb([p,v,_,k]){return[h(1-Math.min(1,p+k)),h(1-Math.min(1,_+k)),h(1-Math.min(1,v+k))]}static CMYK_HTML(p){let v=this.CMYK_RGB(p).slice(1);return this.RGB_HTML(v)}static RGB_CMYK([p,v,_]){let k=1-p,O=1-v,M=1-_;return["CMYK",k,O,M,Math.min(k,O,M)]}}var m=e(284);let d=1e3,a=new WeakSet;function f(R){return{width:R[2]-R[0],height:R[3]-R[1]}}class A{static create(p){switch(p.data.annotationType){case i.AnnotationType.LINK:return new u(p);case i.AnnotationType.TEXT:return new y(p);case i.AnnotationType.WIDGET:switch(p.data.fieldType){case"Tx":return new c(p);case"Btn":return p.data.radioButton?new P(p):p.data.checkBox?new w(p):new E(p);case"Ch":return new I(p);case"Sig":return new b(p)}return new r(p);case i.AnnotationType.POPUP:return new N(p);case i.AnnotationType.FREETEXT:return new H(p);case i.AnnotationType.LINE:return new X(p);case i.AnnotationType.SQUARE:return new it(p);case i.AnnotationType.CIRCLE:return new at(p);case i.AnnotationType.POLYLINE:return new K(p);case i.AnnotationType.CARET:return new G(p);case i.AnnotationType.INK:return new Y(p);case i.AnnotationType.POLYGON:return new j(p);case i.AnnotationType.HIGHLIGHT:return new et(p);case i.AnnotationType.UNDERLINE:return new rt(p);case i.AnnotationType.SQUIGGLY:return new ct(p);case i.AnnotationType.STRIKEOUT:return new st(p);case i.AnnotationType.STAMP:return new W(p);case i.AnnotationType.FILEATTACHMENT:return new x(p);default:return new C(p)}}}class C{#t=!1;constructor(p,{isRenderable:v=!1,ignoreBorder:_=!1,createQuadrilaterals:k=!1}={}){this.isRenderable=v,this.data=p.data,this.layer=p.layer,this.linkService=p.linkService,this.downloadManager=p.downloadManager,this.imageResourcesPath=p.imageResourcesPath,this.renderForms=p.renderForms,this.svgFactory=p.svgFactory,this.annotationStorage=p.annotationStorage,this.enableScripting=p.enableScripting,this.hasJSActions=p.hasJSActions,this._fieldObjects=p.fieldObjects,this.parent=p.parent,v&&(this.container=this._createContainer(_)),k&&this._createQuadrilaterals()}static _hasPopupData({titleObj:p,contentsObj:v,richText:_}){return!!(p?.str||v?.str||_?.str)}get hasPopupData(){return C._hasPopupData(this.data)}_createContainer(p){let{data:v,parent:{page:_,viewport:k}}=this,O=document.createElement("section");O.setAttribute("data-annotation-id",v.id),this instanceof r||(O.tabIndex=d),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:S,pageX:L,pageY:U}=k.rawDims;if(!v.rect||this instanceof N){let{rotation:Q}=v;return v.hasOwnCanvas||Q===0||this.setRotation(Q,O),O}let{width:$,height:D}=f(v.rect),F=i.Util.normalizeRect([v.rect[0],_.view[3]-v.rect[1]+_.view[1],v.rect[2],_.view[3]-v.rect[3]+_.view[1]]);if(!p&&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 nt=`calc(${Q}px * var(--scale-factor)) / calc(${Z}px * var(--scale-factor))`;O.style.borderRadius=nt}else if(this instanceof P){let nt=`calc(${$}px * var(--scale-factor)) / calc(${D}px * var(--scale-factor))`;O.style.borderRadius=nt}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 tt=v.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)/S+"%";let{rotation:V}=v;return v.hasOwnCanvas||V===0?(O.style.width=100*$/M+"%",O.style.height=100*D/S+"%"):this.setRotation(V,O),O}setRotation(p,v=this.container){if(!this.data.rect)return;let{pageWidth:_,pageHeight:k}=this.parent.viewport.rawDims,{width:O,height:M}=f(this.data.rect),S,L;p%180==0?(S=100*O/_,L=100*M/k):(S=100*M/_,L=100*O/k),v.style.width=`${S}%`,v.style.height=`${L}%`,v.setAttribute("data-main-rotation",(360-p)%360)}get _commonActions(){let p=(v,_,k)=>{let O=k.detail[v],M=O[0],S=O.slice(1);k.target.style[_]=g[`${M}_HTML`](S),this.annotationStorage.setValue(this.data.id,{[_]:g[`${M}_rgb`](S)})};return(0,i.shadow)(this,"_commonActions",{display:v=>{let{display:_}=v.detail,k=_%2==1;this.container.style.visibility=k?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:k,noPrint:_===1||_===2})},print:v=>{this.annotationStorage.setValue(this.data.id,{noPrint:!v.detail.print})},hidden:v=>{let{hidden:_}=v.detail;this.container.style.visibility=_?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:_,noView:_})},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=>{p("bgColor","backgroundColor",v)},fillColor:v=>{p("fillColor","backgroundColor",v)},fgColor:v=>{p("fgColor","color",v)},textColor:v=>{p("textColor","color",v)},borderColor:v=>{p("borderColor","borderColor",v)},strokeColor:v=>{p("strokeColor","borderColor",v)},rotation:v=>{let _=v.detail.rotation;this.setRotation(_),this.annotationStorage.setValue(this.data.id,{rotation:_})}})}_dispatchEventFromSandbox(p,v){let _=this._commonActions;for(let k of Object.keys(v.detail))(p[k]||_[k])?.(v)}_setDefaultPropertiesFromJS(p){if(!this.enableScripting)return;let v=this.annotationStorage.getRawValue(this.data.id);if(!v)return;let _=this._commonActions;for(let[k,O]of Object.entries(v)){let M=_[k];M&&(M({detail:{[k]:O},target:p}),delete v[k])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:p}=this.data;if(!p)return;let[v,_,k,O]=this.data.rect;if(p.length===1){let[,{x:Z,y:tt},{x:nt,y:pt}]=p[0];if(k===Z&&O===tt&&v===nt&&_===pt)return}let{style:M}=this.container,S;if(this.#t){let{borderColor:Z,borderWidth:tt}=M;M.borderWidth=0,S=["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=k-v,U=O-_,{svgFactory:$}=this,D=$.createElement("svg");D.classList.add("quadrilateralsContainer"),D.setAttribute("width",0),D.setAttribute("height",0);let F=$.createElement("defs");D.append(F);let V=$.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:nt,y:pt}]of p){let dt=$.createElement("rect"),lt=(nt-v)/L,wt=(O-tt)/U,Tt=(Z-nt)/L,xt=(tt-pt)/U;dt.setAttribute("x",lt),dt.setAttribute("y",wt),dt.setAttribute("width",Tt),dt.setAttribute("height",xt),V.append(dt),S?.push(`<rect vector-effect="non-scaling-stroke" x="${lt}" y="${wt}" width="${Tt}" height="${xt}"/>`)}this.#t&&(S.push("</g></svg>')"),M.backgroundImage=S.join("")),this.container.append(D),this.container.style.clipPath=`url(#${Q})`}_createPopup(){let{container:p,data:v}=this;p.setAttribute("aria-haspopup","dialog");let _=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(_.render())}render(){(0,i.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(p,v=null){let _=[];if(this._fieldObjects){let k=this._fieldObjects[p];if(k)for(let{page:O,id:M,exportValues:S}of k){if(O===-1||M===v)continue;let L=typeof S=="string"?S:null,U=document.querySelector(`[data-element-id="${M}"]`);!U||a.has(U)?_.push({id:M,exportValue:L,domElement:U}):(0,i.warn)(`_getElementsByName - element not allowed: ${M}`)}return _}for(let k of document.getElementsByName(p)){let{exportValue:O}=k,M=k.getAttribute("data-element-id");M!==v&&a.has(k)&&_.push({id:M,exportValue:O,domElement:k})}return _}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 p=this.getElementsToTriggerPopup();if(Array.isArray(p))for(let v of p)v.classList.add("highlightArea");else p.classList.add("highlightArea")}get _isEditable(){return!1}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:p,data:{id:v}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:p,editId:v})}))}}class u extends C{constructor(p,v=null){super(p,{isRenderable:!0,ignoreBorder:!!v?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=p.data.isTooltipOnly}render(){let{data:p,linkService:v}=this,_=document.createElement("a");_.setAttribute("data-element-id",p.id);let k=!1;return p.url?(v.addLinkAttributes(_,p.url,p.newWindow),k=!0):p.action?(this._bindNamedAction(_,p.action),k=!0):p.attachment?(this.#e(_,p.attachment,p.attachmentDest),k=!0):p.setOCGState?(this.#i(_,p.setOCGState),k=!0):p.dest?(this._bindLink(_,p.dest),k=!0):(p.actions&&(p.actions.Action||p.actions["Mouse Up"]||p.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(_,p),k=!0),p.resetForm?(this._bindResetFormAction(_,p.resetForm),k=!0):this.isTooltipOnly&&!k&&(this._bindLink(_,""),k=!0)),this.container.classList.add("linkAnnotation"),k&&this.container.append(_),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(p,v){p.href=this.linkService.getDestinationHash(v),p.onclick=()=>(v&&this.linkService.goToDestination(v),!1),(v||v==="")&&this.#t()}_bindNamedAction(p,v){p.href=this.linkService.getAnchorUrl(""),p.onclick=()=>(this.linkService.executeNamedAction(v),!1),this.#t()}#e(p,v,_=null){p.href=this.linkService.getAnchorUrl(""),p.onclick=()=>(this.downloadManager?.openOrDownloadData(v.content,v.filename,_),!1),this.#t()}#i(p,v){p.href=this.linkService.getAnchorUrl(""),p.onclick=()=>(this.linkService.executeSetOCGState(v),!1),this.#t()}_bindJSAction(p,v){p.href=this.linkService.getAnchorUrl("");let _=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let k of Object.keys(v.actions)){let O=_.get(k);O&&(p[O]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v.id,name:k}}),!1))}p.onclick||(p.onclick=()=>!1),this.#t()}_bindResetFormAction(p,v){let _=p.onclick;_||(p.href=this.linkService.getAnchorUrl("")),this.#t(),this._fieldObjects?p.onclick=()=>{_?.();let{fields:k,refs:O,include:M}=v,S=[];if(k.length!==0||O.length!==0){let $=new Set(O);for(let D of k){let F=this._fieldObjects[D]||[];for(let{id:V}of F)$.add(V)}for(let D of Object.values(this._fieldObjects))for(let F of D)$.has(F.id)===M&&S.push(F)}else for(let $ of Object.values(this._fieldObjects))S.push(...$);let L=this.annotationStorage,U=[];for(let $ of S){let{id:D}=$;switch(U.push(D),$.type){case"text":{let V=$.defaultValue||"";L.setValue(D,{value:V});break}case"checkbox":case"radiobutton":{let V=$.defaultValue===$.exportValues;L.setValue(D,{value:V});break}case"combobox":case"listbox":{let V=$.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:U,name:"ResetForm"}}),!1}:((0,i.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),_||(p.onclick=()=>!1))}}class y extends C{constructor(p){super(p,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let p=document.createElement("img");return p.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",p.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),p.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(p),this.container}}class r extends C{render(){return this.container}showElementAndHideCanvas(p){this.data.hasOwnCanvas&&(p.previousSibling?.nodeName==="CANVAS"&&(p.previousSibling.hidden=!0),p.hidden=!1)}_getKeyModifier(p){return i.FeatureTest.platform.isMac?p.metaKey:p.ctrlKey}_setEventListener(p,v,_,k,O){_.includes("mouse")?p.addEventListener(_,(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)}})})):p.addEventListener(_,(M=>{if(_==="blur"){if(!v.focused||!M.relatedTarget)return;v.focused=!1}else if(_==="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(p,v,_,k){for(let[O,M]of _)(M==="Action"||this.data.actions?.[M])&&(M!=="Focus"&&M!=="Blur"||(v||={focused:!1}),this._setEventListener(p,v,O,M,k),M!=="Focus"||this.data.actions?.Blur?M!=="Blur"||this.data.actions?.Focus||this._setEventListener(p,v,"focus","Focus",null):this._setEventListener(p,v,"blur","Blur",null))}_setBackgroundColor(p){let v=this.data.backgroundColor||null;p.style.backgroundColor=v===null?"transparent":i.Util.makeHexColor(v[0],v[1],v[2])}_setTextStyle(p){let v=["left","center","right"],{fontColor:_}=this.data.defaultAppearanceData,k=this.data.defaultAppearanceData.fontSize||9,O=p.style,M,S=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*k))||1);M=Math.min(k,S(U/i.LINE_FACTOR))}else{let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2);M=Math.min(k,S(L/i.LINE_FACTOR))}O.fontSize=`calc(${M}px * var(--scale-factor))`,O.color=i.Util.makeHexColor(_[0],_[1],_[2]),this.data.textAlignment!==null&&(O.textAlign=v[this.data.textAlignment])}_setRequired(p,v){v?p.setAttribute("required",!0):p.removeAttribute("required"),p.setAttribute("aria-required",v)}}class c extends r{constructor(p){super(p,{isRenderable:p.renderForms||p.data.hasOwnCanvas||!p.data.hasAppearance&&!!p.data.fieldValue})}setPropertyOnSiblings(p,v,_,k){let O=this.annotationStorage;for(let M of this._getElementsByName(p.name,p.id))M.domElement&&(M.domElement[v]=_),O.setValue(M.id,{[k]:_})}render(){let p=this.annotationStorage,v=this.data.id;this.container.classList.add("textWidgetAnnotation");let _=null;if(this.renderForms){let k=p.getValue(v,{value:this.data.fieldValue}),O=k.value||"",M=p.getValue(v,{charLimit:this.data.maxLen}).charLimit;M&&O.length>M&&(O=O.slice(0,M));let S=k.formattedValue||this.data.textContent?.join(`
|
|
4
|
-
`)||null;S&&this.data.comb&&(S=S.replaceAll(/\s+/g,""));let L={userValue:O,formattedValue:S,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(_=document.createElement("textarea"),_.textContent=S??O,this.data.doNotScroll&&(_.style.overflowY="hidden")):(_=document.createElement("input"),_.type="text",_.setAttribute("value",S??O),this.data.doNotScroll&&(_.style.overflowX="hidden")),this.data.hasOwnCanvas&&(_.hidden=!0),a.add(_),_.setAttribute("data-element-id",v),_.disabled=this.data.readOnly,_.name=this.data.fieldName,_.tabIndex=d,this._setRequired(_,this.data.required),M&&(_.maxLength=M),_.addEventListener("input",($=>{p.setValue(v,{value:$.target.value}),this.setPropertyOnSiblings(_,"value",$.target.value,"value"),L.formattedValue=null})),_.addEventListener("resetform",($=>{let D=this.data.defaultFieldValue??"";_.value=L.userValue=D,L.formattedValue=null}));let U=$=>{let{formattedValue:D}=L;D!=null&&($.target.value=D),$.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){_.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)})),_.addEventListener("updatefromsandbox",(D=>{this.showElementAndHideCanvas(D.target);let F={value(V){L.userValue=V.detail.value??"",p.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),p.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 tt=L.userValue;tt&&!(tt.length<=Q)&&(tt=tt.slice(0,Q),Z.value=L.userValue=tt,p.setValue(v,{value:tt}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:tt,willCommit:!0,commitKey:1,selStart:Z.selectionStart,selEnd:Z.selectionEnd}}))}};this._dispatchEventFromSandbox(F,D)})),_.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 $=U;U=null,_.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}}),$(D)})),this.data.actions?.Keystroke&&_.addEventListener("beforeinput",(D=>{L.lastCommittedValue=null;let{data:F,target:V}=D,{value:Q,selectionStart:Z,selectionEnd:tt}=V,nt=Z,pt=tt;switch(D.inputType){case"deleteWordBackward":{let dt=Q.substring(0,Z).match(/\w*[^\w]*$/);dt&&(nt-=dt[0].length);break}case"deleteWordForward":{let dt=Q.substring(Z).match(/^[^\w]*\w*/);dt&&(pt+=dt[0].length);break}case"deleteContentBackward":Z===tt&&(nt-=1);break;case"deleteContentForward":Z===tt&&(pt+=1)}D.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:Q,change:F||"",willCommit:!1,selStart:nt,selEnd:pt}})})),this._setEventListeners(_,L,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(D=>D.target.value))}if(U&&_.addEventListener("blur",U),this.data.comb){let $=(this.data.rect[2]-this.data.rect[0])/M;_.classList.add("comb"),_.style.letterSpacing=`calc(${$}px * var(--scale-factor) - 1ch)`}}else _=document.createElement("div"),_.textContent=this.data.fieldValue,_.style.verticalAlign="middle",_.style.display="table-cell",this.data.hasOwnCanvas&&(_.hidden=!0);return this._setTextStyle(_),this._setBackgroundColor(_),this._setDefaultPropertiesFromJS(_),this.container.append(_),this.container}}class b extends r{constructor(p){super(p,{isRenderable:!!p.data.hasOwnCanvas})}}class w extends r{constructor(p){super(p,{isRenderable:p.renderForms})}render(){let p=this.annotationStorage,v=this.data,_=v.id,k=p.getValue(_,{value:v.exportValue===v.fieldValue}).value;typeof k=="string"&&(k=k!=="Off",p.setValue(_,{value:k})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let O=document.createElement("input");return a.add(O),O.setAttribute("data-element-id",_),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=d,O.addEventListener("change",(M=>{let{name:S,checked:L}=M.target;for(let U of this._getElementsByName(S,_)){let $=L&&U.exportValue===v.exportValue;U.domElement&&(U.domElement.checked=$),p.setValue(U.id,{value:$})}p.setValue(_,{value:L})})),O.addEventListener("resetform",(M=>{let S=v.defaultFieldValue||"Off";M.target.checked=S===v.exportValue})),this.enableScripting&&this.hasJSActions&&(O.addEventListener("updatefromsandbox",(M=>{let S={value(L){L.target.checked=L.detail.value!=="Off",p.setValue(_,{value:L.target.checked})}};this._dispatchEventFromSandbox(S,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 P extends r{constructor(p){super(p,{isRenderable:p.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let p=this.annotationStorage,v=this.data,_=v.id,k=p.getValue(_,{value:v.fieldValue===v.buttonValue}).value;if(typeof k=="string"&&(k=k!==v.buttonValue,p.setValue(_,{value:k})),k)for(let M of this._getElementsByName(v.fieldName,_))p.setValue(M.id,{value:!1});let O=document.createElement("input");if(a.add(O),O.setAttribute("data-element-id",_),O.disabled=v.readOnly,this._setRequired(O,this.data.required),O.type="radio",O.name=v.fieldName,k&&O.setAttribute("checked",!0),O.tabIndex=d,O.addEventListener("change",(M=>{let{name:S,checked:L}=M.target;for(let U of this._getElementsByName(S,_))p.setValue(U.id,{value:!1});p.setValue(_,{value:L})})),O.addEventListener("resetform",(M=>{let S=v.defaultFieldValue;M.target.checked=S!=null&&S===v.buttonValue})),this.enableScripting&&this.hasJSActions){let M=v.buttonValue;O.addEventListener("updatefromsandbox",(S=>{let L={value:U=>{let $=M===U.detail.value;for(let D of this._getElementsByName(U.target.name)){let F=$&&D.id===_;D.domElement&&(D.domElement.checked=F),p.setValue(D.id,{value:F})}}};this._dispatchEventFromSandbox(L,S)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(S=>S.target.checked))}return this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class E extends u{constructor(p){super(p,{ignoreBorder:p.data.hasAppearance})}render(){let p=super.render();p.classList.add("buttonWidgetAnnotation","pushButton");let v=p.lastChild;return this.enableScripting&&this.hasJSActions&&v&&(this._setDefaultPropertiesFromJS(v),v.addEventListener("updatefromsandbox",(_=>{this._dispatchEventFromSandbox({},_)}))),p}}class I extends r{constructor(p){super(p,{isRenderable:p.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let p=this.annotationStorage,v=this.data.id,_=p.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=d;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",($=>{let D=this.data.defaultFieldValue;for(let F of k.options)F.selected=F.value===D}));for(let $ of this.data.options){let D=document.createElement("option");D.textContent=$.displayValue,D.value=$.exportValue,_.value.includes($.exportValue)&&(D.setAttribute("selected",!0),O=!1),k.append(D)}let M=null;if(O){let $=document.createElement("option");$.value=" ",$.setAttribute("hidden",!0),$.setAttribute("selected",!0),k.prepend($),M=()=>{$.remove(),k.removeEventListener("input",M),M=null},k.addEventListener("input",M)}let S=$=>{let D=$?"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=S(!1),U=$=>{let D=$.target.options;return Array.prototype.map.call(D,(F=>({displayValue:F.textContent,exportValue:F.value})))};return this.enableScripting&&this.hasJSActions?(k.addEventListener("updatefromsandbox",($=>{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);p.setValue(v,{value:S(!0)}),L=S(!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),p.setValue(v,{value:S(!0),items:U(F)}),L=S(!1)},clear(F){for(;k.length!==0;)k.remove(0);p.setValue(v,{value:null,items:[]}),L=S(!1)},insert(F){let{index:V,displayValue:Q,exportValue:Z}=F.detail.insert,tt=k.children[V],nt=document.createElement("option");nt.textContent=Q,nt.value=Z,tt?tt.before(nt):k.append(nt),p.setValue(v,{value:S(!0),items:U(F)}),L=S(!1)},items(F){let{items:V}=F.detail;for(;k.length!==0;)k.remove(0);for(let Q of V){let{displayValue:Z,exportValue:tt}=Q,nt=document.createElement("option");nt.textContent=Z,nt.value=tt,k.append(nt)}k.options.length>0&&(k.options[0].selected=!0),p.setValue(v,{value:S(!0),items:U(F)}),L=S(!1)},indices(F){let V=new Set(F.detail.indices);for(let Q of F.target.options)Q.selected=V.has(Q.index);p.setValue(v,{value:S(!0)}),L=S(!1)},editable(F){F.target.disabled=!F.detail.editable}};this._dispatchEventFromSandbox(D,$)})),k.addEventListener("input",($=>{let D=S(!0);p.setValue(v,{value:D}),$.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"]],($=>$.target.value))):k.addEventListener("input",(function($){p.setValue(v,{value:S(!0)})})),this.data.combo&&this._setTextStyle(k),this._setBackgroundColor(k),this._setDefaultPropertiesFromJS(k),this.container.append(k),this.container}}class N extends C{constructor(p){let{data:v,elements:_}=p;super(p,{isRenderable:C._hasPopupData(v)}),this.elements=_}render(){this.container.classList.add("popupAnnotation");let p=new z({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 _ of this.elements)_.popup=p,v.push(_.data.id),_.addHighlightArea();return this.container.setAttribute("aria-controls",v.map((_=>`${i.AnnotationPrefix}${_}`)).join(",")),this.container}}class z{#t=this.#m.bind(this);#e=this.#C.bind(this);#i=this.#S.bind(this);#n=this.#y.bind(this);#r=null;#s=null;#o=null;#c=null;#a=null;#d=null;#p=null;#u=!1;#l=null;#f=null;#g=null;#h=null;#b=!1;constructor({container:p,color:v,elements:_,titleObj:k,modificationDate:O,contentsObj:M,richText:S,parent:L,rect:U,parentRect:$,open:D}){this.#s=p,this.#h=k,this.#o=M,this.#g=S,this.#d=L,this.#r=v,this.#f=U,this.#p=$,this.#a=_,this.#c=n.PDFDateString.toDateObject(O),this.trigger=_.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 _)F.container?.addEventListener("keydown",this.#t);this.#s.hidden=!0,D&&this.#y()}render(){if(this.#l)return;let{page:{view:p},viewport:{rawDims:{pageWidth:v,pageHeight:_,pageX:k,pageY:O}}}=this.#d,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 S=document.createElement("span");S.className="header";let L=document.createElement("h1");if(S.append(L),{dir:L.dir,str:L.textContent}=this.#h,M.append(S),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()})),S.append(pt)}let U=this.#o,$=this.#g;if(!$?.str||U?.str&&U.str!==$.str){let pt=this._formatContents(U);M.append(pt)}else m.XfaLayer.render({xfaHtml:$.html,intent:"richText",div:M}),M.lastChild.classList.add("richText","popupContent");let D=!!this.#p,F=D?this.#p:this.#f;for(let pt of this.#a)if(!F||i.Util.intersect(pt.data.rect,F)!==null){F=pt.data.rect,D=!0;break}let V=i.Util.normalizeRect([F[0],p[3]-F[1]+p[1],F[2],p[3]-F[3]+p[1]]),Q=D?F[2]-F[0]+5:0,Z=V[0]+Q,tt=V[1],{style:nt}=this.#s;nt.left=100*(Z-k)/v+"%",nt.top=100*(tt-O)/_+"%",this.#s.append(M)}_formatContents({str:p,dir:v}){let _=document.createElement("p");_.classList.add("popupContent"),_.dir=v;let k=p.split(/(?:\r\n?|\n)/);for(let O=0,M=k.length;O<M;++O){let S=k[O];_.append(document.createTextNode(S)),O<M-1&&_.append(document.createElement("br"))}return _}#m(p){p.altKey||p.shiftKey||p.ctrlKey||p.metaKey||(p.key==="Enter"||p.key==="Escape"&&this.#u)&&this.#y()}#y(){this.#u=!this.#u,this.#u?(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.#l||this.render(),this.isVisible?this.#u&&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.#u&&this.isVisible&&(this.#s.hidden=!0,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)-1e3)}forceHide(){this.#b=this.isVisible,this.#b&&(this.#s.hidden=!0)}maybeShow(){this.#b&&(this.#b=!1,this.#s.hidden=!1)}get isVisible(){return this.#s.hidden===!1}}class H extends C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0}),this.textContent=p.data.textContent,this.textPosition=p.data.textPosition,this.annotationEditorType=i.AnnotationEditorType.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){let p=document.createElement("div");p.classList.add("annotationTextContent"),p.setAttribute("role","comment");for(let v of this.textContent){let _=document.createElement("span");_.textContent=v,p.append(_)}this.container.append(p)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}get _isEditable(){return this.data.hasOwnCanvas}}class X extends C{#t=null;constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0),O=this.#t=this.svgFactory.createElement("svg:line");return O.setAttribute("x1",p.rect[2]-p.lineCoordinates[0]),O.setAttribute("y1",p.rect[3]-p.lineCoordinates[1]),O.setAttribute("x2",p.rect[2]-p.lineCoordinates[2]),O.setAttribute("y2",p.rect[3]-p.lineCoordinates[3]),O.setAttribute("stroke-width",p.borderStyle.width||1),O.setAttribute("stroke","transparent"),O.setAttribute("fill","transparent"),k.append(O),this.container.append(k),!p.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class it extends C{#t=null;constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0),O=p.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",_-O),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),k.append(M),this.container.append(k),!p.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class at extends C{#t=null;constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0),O=p.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:ellipse");return M.setAttribute("cx",v/2),M.setAttribute("cy",_/2),M.setAttribute("rx",v/2-O/2),M.setAttribute("ry",_/2-O/2),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),k.append(M),this.container.append(k),!p.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class K extends C{#t=null;constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0),O=[];for(let S of p.vertices){let L=S.x-p.rect[0],U=p.rect[3]-S.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",p.borderStyle.width||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),k.append(M),this.container.append(k),!p.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class j extends K{constructor(p){super(p),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class G extends C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class Y extends C{#t=[];constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=i.AnnotationEditorType.INK}render(){this.container.classList.add(this.containerClassName);let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0);for(let O of p.inkLists){let M=[];for(let L of O){let U=L.x-p.rect[0],$=p.rect[3]-L.y;M.push(`${U},${$}`)}M=M.join(" ");let S=this.svgFactory.createElement(this.svgElementName);this.#t.push(S),S.setAttribute("points",M),S.setAttribute("stroke-width",p.borderStyle.width||1),S.setAttribute("stroke","transparent"),S.setAttribute("fill","transparent"),!p.popupRef&&this.hasPopupData&&this._createPopup(),k.append(S)}return this.container.append(k),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class et extends C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this.container}}class rt extends C{constructor(p){super(p,{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 C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class st extends C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class W extends C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class x extends C{#t=null;constructor(p){super(p,{isRenderable:!0});let{filename:v,content:_}=this.data.file;this.filename=(0,n.getFilenameFromUrl)(v,!0),this.content=_,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,filename:v,content:_})}render(){this.container.classList.add("fileAttachmentAnnotation");let{container:p,data:v}=this,_;v.hasAppearance||v.fillAlpha===0?_=document.createElement("div"):(_=document.createElement("img"),_.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(v.name)?"paperclip":"pushpin"}.svg`,v.fillAlpha&&v.fillAlpha<1&&(_.style=`filter: opacity(${Math.round(100*v.fillAlpha)}%);`)),_.addEventListener("dblclick",this.#e.bind(this)),this.#t=_;let{isMac:k}=i.FeatureTest.platform;return p.addEventListener("keydown",(O=>{O.key==="Enter"&&(k?O.metaKey:O.ctrlKey)&&this.#e()})),!v.popupRef&&this.hasPopupData?this._createPopup():_.classList.add("popupTriggerArea"),p.append(_),p}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:p,accessibilityManager:v,annotationCanvasMap:_,page:k,viewport:O}){this.div=p,this.#t=v,this.#e=_,this.page=k,this.viewport=O,this.zIndex=0}#n(p,v){let _=p.firstChild||p;_.id=`${i.AnnotationPrefix}${v}`,this.div.append(p),this.#t?.moveElementInDOM(this.div,p,_,!1)}async render(p){let{annotations:v}=p,_=this.div;(0,n.setLayerDimensions)(_,this.viewport);let k=new Map,O={data:null,layer:_,linkService:p.linkService,downloadManager:p.downloadManager,imageResourcesPath:p.imageResourcesPath||"",renderForms:p.renderForms!==!1,svgFactory:new n.DOMSVGFactory,annotationStorage:p.annotationStorage||new o.AnnotationStorage,enableScripting:p.enableScripting===!0,hasJSActions:p.hasJSActions,fieldObjects:p.fieldObjects,parent:this,elements:null};for(let M of v){if(M.noHTML)continue;let S=M.annotationType===i.AnnotationType.POPUP;if(S){let $=k.get(M.id);if(!$)continue;O.elements=$}else{let{width:$,height:D}=f(M.rect);if($<=0||D<=0)continue}O.data=M;let L=A.create(O);if(!L.isRenderable)continue;if(!S&&M.popupRef){let $=k.get(M.popupRef);$?$.push(L):k.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:p}){let v=this.div;this.viewport=p,(0,n.setLayerDimensions)(v,{rotation:p.rotation}),this.#r(),v.hidden=!1}#r(){if(!this.#e)return;let p=this.div;for(let[v,_]of this.#e){let k=p.querySelector(`[data-annotation-id="${v}"]`);if(!k)continue;let{firstChild:O}=k;O?O.nodeName==="CANVAS"?O.replaceWith(_):O.before(_):k.append(_)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#i.values())}getEditableAnnotation(p){return this.#i.get(p)}}},792:(s,t,e)=>{e.d(t,{AnnotationStorage:()=>h,PrintAnnotationStorage:()=>g,SerializableEmpty:()=>l});var i=e(292),n=e(310),o=e(651);let l=Object.freeze({map:null,hash:"",transfer:void 0});class h{#t=!1;#e=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(d,a){let f=this.#e.get(d);return f===void 0?a:Object.assign(a,f)}getRawValue(d){return this.#e.get(d)}remove(d){if(this.#e.delete(d),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(d,a){let f=this.#e.get(d),A=!1;if(f!==void 0)for(let[C,u]of Object.entries(a))f[C]!==u&&(A=!0,f[C]=u);else A=!0,this.#e.set(d,a);A&&this.#i(),a instanceof n.AnnotationEditor&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(a.constructor._type)}has(d){return this.#e.has(d)}getAll(){return this.#e.size>0?(0,i.objectFromMap)(this.#e):null}setAll(d){for(let[a,f]of Object.entries(d))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 g(this)}get serializable(){if(this.#e.size===0)return l;let d=new Map,a=new o.MurmurHash3_64,f=[],A=Object.create(null),C=!1;for(let[u,y]of this.#e){let r=y instanceof n.AnnotationEditor?y.serialize(!1,A):y;r&&(d.set(u,r),a.update(`${u}:${JSON.stringify(r)}`),C||=!!r.bitmap)}if(C)for(let u of d.values())u.bitmap&&f.push(u.bitmap);return d.size>0?{map:d,hash:a.hexdigest(),transfer:f}:l}get editorStats(){let d=null,a=new Map;for(let f of this.#e.values()){if(!(f instanceof n.AnnotationEditor))continue;let A=f.telemetryFinalData;if(!A)continue;let{type:C}=A;a.has(C)||a.set(C,Object.getPrototypeOf(f).constructor),d||=Object.create(null);let u=d[C]||=new Map;for(let[y,r]of Object.entries(A)){if(y==="type")continue;let c=u.get(y);c||(c=new Map,u.set(y,c));let b=c.get(r)??0;c.set(r,b+1)}}for(let[f,A]of a)d[f]=A.computeTelemetryFinalData(d[f]);return d}}class g extends h{#t;constructor(d){super();let{map:a,hash:f,transfer:A}=d.serializable,C=structuredClone(a,A?{transfer:A}:null);this.#t={map:C,hash:f,transfer:A}}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 S=new Y,{docId:L}=S,U=M.url?j(M.url):null,$=M.data?G(M.data):null,D=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:E,tt=M.worker instanceof x?M.worker:null,nt=M.verbosity,pt=typeof M.docBaseUrl!="string"||(0,h.isDataScheme)(M.docBaseUrl)?null:M.docBaseUrl,dt=typeof M.cMapUrl=="string"?M.cMapUrl:null,lt=M.cMapPacked!==!1,wt=M.CMapReaderFactory||H,Tt=typeof M.standardFontDataUrl=="string"?M.standardFontDataUrl:null,xt=M.StandardFontDataFactory||it,It=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,Ne=M.fontExtraProperties===!0,Te=M.enableXfa===!0,Ie=M.ownerDocument||globalThis.document,pi=M.disableRange===!0,fi=M.disableStream===!0,le=M.disableAutoFetch===!0,oe=M.pdfBug===!0,gi=Q?Q.length:M.length??NaN,ws=typeof M.useSystemFonts=="boolean"?M.useSystemFonts:!o.isNodeJS&&!Se,Me=typeof M.useWorkerFetch=="boolean"?M.useWorkerFetch:wt===h.DOMCMapReaderFactory&&xt===h.DOMStandardFontDataFactory&&dt&&Tt&&(0,h.isValidFetchUrl)(dt,document.baseURI)&&(0,h.isValidFetchUrl)(Tt,document.baseURI),ne=M.canvasFactory||new z({ownerDocument:Ie}),ar=M.filterFactory||new X({docId:L,ownerDocument:Ie});(0,o.setVerbosityLevel)(nt);let xs={canvasFactory:ne,filterFactory:ar};if(Me||(xs.cMapReaderFactory=new wt({baseUrl:dt,isCompressed:lt}),xs.standardFontDataFactory=new xt({baseUrl:Tt})),!tt){let $e={verbosity:nt,port:f.GlobalWorkerOptions.workerPort};tt=$e.port?x.fromPort($e):new x($e),S._worker=tt}let Be={docId:L,apiVersion:"4.1.392",data:$,password:V,disableAutoFetch:le,rangeChunkSize:Z,length:gi,docBaseUrl:pt,enableXfa:Te,evaluatorOptions:{maxImageSize:Lt,disableFontFace:Se,ignoreErrors:It,isEvalSupported:Ut,isOffscreenCanvasSupported:jt,canvasMaxAreaInBytes:he,fontExtraProperties:Ne,useSystemFonts:ws,cMapUrl:Me?dt:null,standardFontDataUrl:Me?Tt:null}},zi={ignoreErrors:It,isEvalSupported:Ut,disableFontFace:Se,fontExtraProperties:Ne,enableXfa:Te,ownerDocument:Ie,disableAutoFetch:le,pdfBug:oe,styleElement:null};return tt.promise.then((function(){if(S.destroyed)throw new Error("Loading aborted");let $e=K(tt,Be),lr=new Promise((function(As){let mi;Q?mi=new y.PDFDataTransportStream(Q,{disableRange:pi,disableStream:fi}):$||(mi=(pe=>o.isNodeJS?(function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype})()&&(0,h.isValidFetchUrl)(pe.url)?new r.PDFFetchStream(pe):new b.PDFNodeStream(pe):(0,h.isValidFetchUrl)(pe.url)?new r.PDFFetchStream(pe):new c.PDFNetworkStream(pe))({url:U,length:gi,httpHeaders:D,withCredentials:F,rangeChunkSize:Z,disableRange:pi,disableStream:fi})),As(mi)}));return Promise.all([$e,lr]).then((function([As,mi]){if(S.destroyed)throw new Error("Loading aborted");let pe=new A.MessageHandler(L,As,tt.port),cr=new T(pe,S,mi,zi,xs);S._transport=cr,pe.send("Ready",null)}))})).catch(S._capability.reject),S},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.")},G=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:()=>x,build:()=>O,getDocument:()=>at,version:()=>k});var o=e(292),l=e(792),h=e(419),g=e(10),m=e(573),d=e(923),a=e(814),f=e(164),A=e(178),C=e(62),u=e(626),y=e(585),r=e(94),c=e(457),b=e(786),w=e(50),P=i([m,b]);[m,b]=P.then?(await P)():P;let E=65536,I=100,N=5e3,z=o.isNodeJS?m.NodeCanvasFactory:h.DOMCanvasFactory,H=o.isNodeJS?m.NodeCMapReaderFactory:h.DOMCMapReaderFactory,X=o.isNodeJS?m.NodeFilterFactory:h.DOMFilterFactory,it=o.isNodeJS?m.NodeStandardFontDataFactory:h.DOMStandardFontDataFactory;async function K(M,S){if(M.destroyed)throw new Error("Worker was destroyed");let L=await M.messageHandler.sendWithPromise("GetDocRequest",S,S.data?[S.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(S){throw this._worker?.port&&delete this._worker._pendingDestroy,S}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class et{constructor(S,L,U=!1,$=null){this.length=S,this.initialData=L,this.progressiveDone=U,this.contentDispositionFilename=$,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(S){this._rangeListeners.push(S)}addProgressListener(S){this._progressListeners.push(S)}addProgressiveReadListener(S){this._progressiveReadListeners.push(S)}addProgressiveDoneListener(S){this._progressiveDoneListeners.push(S)}onDataRange(S,L){for(let U of this._rangeListeners)U(S,L)}onDataProgress(S,L){this._readyCapability.promise.then((()=>{for(let U of this._progressListeners)U(S,L)}))}onDataProgressiveRead(S){this._readyCapability.promise.then((()=>{for(let L of this._progressiveReadListeners)L(S)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(let S of this._progressiveDoneListeners)S()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(S,L){(0,o.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class rt{constructor(S,L){this._pdfInfo=S,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(S){return this._transport.getPage(S)}getPageIndex(S){return this._transport.getPageIndex(S)}getDestinations(){return this._transport.getDestinations()}getDestination(S){return this._transport.getDestination(S)}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:S="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(S);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(S=!1){return this._transport.startCleanup(S||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(S,L,U,$=!1){this._pageIndex=S,this._pageInfo=L,this._transport=U,this._stats=$?new h.StatTimer:null,this._pdfBug=$,this.commonObjs=U.commonObjs,this.objs=new p,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:S,rotation:L=this.rotate,offsetX:U=0,offsetY:$=0,dontFlip:D=!1}={}){return new h.PageViewport({viewBox:this.view,scale:S,rotation:L,offsetX:U,offsetY:$,dontFlip:D})}getAnnotations({intent:S="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(S);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:S,viewport:L,intent:U="display",annotationMode:$=o.AnnotationMode.ENABLE,transform:D=null,background:F=null,optionalContentConfigPromise:V=null,annotationCanvasMap:Q=null,pageColors:Z=null,printAnnotationStorage:tt=null}){this._stats?.time("Overall");let nt=this._transport.getRenderingIntent(U,$,tt),{renderingIntent:pt,cacheKey:dt}=nt;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 wt=!!(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(nt));let Tt=Lt=>{lt.renderTasks.delete(xt),(this._maybeCleanupAfterRender||wt)&&(this.#e=!0),this.#i(!wt),Lt?(xt.capability.reject(Lt),this._abortOperatorList({intentState:lt,reason:Lt instanceof Error?Lt:new Error(Lt)})):xt.capability.resolve(),this._stats?.timeEnd("Rendering"),this._stats?.timeEnd("Overall")},xt=new _({callback:Tt,params:{canvasContext:S,viewport:L,transform:D,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:!wt,pdfBug:this._pdfBug,pageColors:Z});(lt.renderTasks||=new Set).add(xt);let It=xt.task;return Promise.all([lt.displayReadyCapability.promise,V]).then((([Lt,Ut])=>{if(this.destroyed)Tt();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(Tt),It}getOperatorList({intent:S="display",annotationMode:L=o.AnnotationMode.ENABLE,printAnnotationStorage:U=null}={}){let $=this._transport.getRenderingIntent(S,L,U,!0),D,F=this._intentStates.get($.cacheKey);return F||(F=Object.create(null),this._intentStates.set($.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($)),F.opListReadCapability.promise}streamTextContent({includeMarkedContent:S=!1,disableNormalization:L=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:S===!0,disableNormalization:L===!0},{highWaterMark:100,size:U=>U.items.length})}getTextContent(S={}){if(this._transport._htmlForXfa)return this.getXfa().then((U=>w.XfaText.textContent(U)));let L=this.streamTextContent(S);return new Promise((function(U,$){let D=L.getReader(),F={items:[],styles:Object.create(null)};(function V(){D.read().then((function({value:Q,done:Z}){Z?U(F):(Object.assign(F.styles,Q.styles),F.items.push(...Q.items),V())}),$)})()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let S=[];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)S.push(U.completed),U.cancel();return this.objs.clear(),this.#e=!1,this.#n(),Promise.all(S)}cleanup(S=!1){this.#e=!0;let L=this.#i(!1);return S&&L&&(this._stats&&=new h.StatTimer),L}#i(S=!1){if(this.#n(),!this.#e||this.destroyed)return!1;if(S)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(S,L){let U=this._intentStates.get(L);U&&(this._stats?.timeEnd("Page Request"),U.displayReadyCapability?.resolve(S))}_renderPageChunk(S,L){for(let U=0,$=S.length;U<$;U++)L.operatorList.fnArray.push(S.fnArray[U]),L.operatorList.argsArray.push(S.argsArray[U]);L.operatorList.lastChunk=S.lastChunk,L.operatorList.separateAnnots=S.separateAnnots;for(let U of L.renderTasks)U.operatorListChanged();S.lastChunk&&this.#i(!0)}_pumpOperatorList({renderingIntent:S,cacheKey:L,annotationStorageSerializable:U}){let{map:$,transfer:D}=U,F=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:S,cacheKey:L,annotationStorage:$},D).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:S,reason:L,force:U=!1}){if(S.streamReader){if(S.streamReaderCancelTimeout&&(clearTimeout(S.streamReaderCancelTimeout),S.streamReaderCancelTimeout=null),!U){if(S.renderTasks.size>0)return;if(L instanceof h.RenderingCancelledException){let $=I;L.extraDelay>0&&L.extraDelay<1e3&&($+=L.extraDelay),S.streamReaderCancelTimeout=setTimeout((()=>{S.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:S,reason:L,force:!0})}),$);return}}if(S.streamReader.cancel(new o.AbortException(L.message)).catch((()=>{})),S.streamReader=null,!this._transport.destroyed){for(let[$,D]of this._intentStates)if(D===S){this._intentStates.delete($);break}this.cleanup()}}}get stats(){return this._stats}}class st{#t=new Set;#e=Promise.resolve();postMessage(S,L){let U={data:structuredClone(S,L?{transfer:L}:null)};this.#e.then((()=>{for(let $ of this.#t)$.call(this,U)}))}addEventListener(S,L){this.#t.add(L)}removeEventListener(S,L){this.#t.delete(L)}terminate(){this.#t.clear()}}let W={isWorkerDisabled:!1,fakeWorkerId:0};o.isNodeJS&&(W.isWorkerDisabled=!0,f.GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"),W.isSameOrigin=function(M,S){let L;try{if(L=new URL(M),!L.origin||L.origin==="null")return!1}catch{return!1}let U=new URL(S,L);return L.origin===U.origin},W.createCDNWrapper=function(M){let S=`await import("${M}");`;return URL.createObjectURL(new Blob([S],{type:"text/javascript"}))};class x{static#t;constructor({name:S=null,port:L=null,verbosity:U=(0,o.getVerbosityLevel)()}={}){if(this.name=S,this.destroyed=!1,this.verbosity=U,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,L){if(x.#t?.has(L))throw new Error("Cannot use more than one PDFWorker per port.");(x.#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(S){this._port=S,this._messageHandler=new A.MessageHandler("main","worker",S),this._messageHandler.on("ready",(function(){})),this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!W.isWorkerDisabled&&!x.#e){let{workerSrc:S}=x;try{W.isSameOrigin(window.location.href,S)||(S=W.createCDNWrapper(new URL(S,window.location).href));let L=new Worker(S,{type:"module"}),U=new A.MessageHandler("main","worker",L),$=()=>{L.removeEventListener("error",D),U.destroy(),L.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},D=()=>{this._webWorker||$()};L.addEventListener("error",D),U.on("test",(V=>{L.removeEventListener("error",D),this.destroyed?$():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",D),this.destroyed)$();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(){W.isWorkerDisabled||((0,o.warn)("Setting up fake worker."),W.isWorkerDisabled=!0),x._setupFakeWorkerGlobal.then((S=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}let L=new st;this._port=L;let U="fake"+W.fakeWorkerId++,$=new A.MessageHandler(U+"_worker",U,L);S.setup($,L);let D=new A.MessageHandler(U,U+"_worker",L);this._messageHandler=D,this._readyCapability.resolve(),D.send("configure",{verbosity:this.verbosity})})).catch((S=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${S.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),x.#t?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(S){if(!S?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");let L=this.#t?.get(S.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 x(S)}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(S,L,U,$,D){this.messageHandler=S,this.loadingTask=L,this.commonObjs=new p,this.fontLoader=new g.FontLoader({ownerDocument:$.ownerDocument,styleElement:$.styleElement}),this._params=$,this.canvasFactory=D.canvasFactory,this.filterFactory=D.filterFactory,this.cMapReaderFactory=D.cMapReaderFactory,this.standardFontDataFactory=D.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=U,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#r(S,L=null){let U=this.#t.get(S);if(U)return U;let $=this.messageHandler.sendWithPromise(S,L);return this.#t.set(S,$),$}get annotationStorage(){return(0,o.shadow)(this,"annotationStorage",new l.AnnotationStorage)}getRenderingIntent(S,L=o.AnnotationMode.ENABLE,U=null,$=!1){let D=o.RenderingIntentFlag.DISPLAY,F=l.SerializableEmpty;switch(S){case"any":D=o.RenderingIntentFlag.ANY;break;case"display":break;case"print":D=o.RenderingIntentFlag.PRINT;break;default:(0,o.warn)(`getRenderingIntent - invalid intent: ${S}`)}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&&U instanceof l.PrintAnnotationStorage?U:this.annotationStorage).serializable;break;default:(0,o.warn)(`getRenderingIntent - invalid annotationMode: ${L}`)}return $&&(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 S=[];for(let U of this.#e.values())S.push(U._destroy());this.#e.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let L=this.messageHandler.sendWithPromise("Terminate",null);return S.push(L),Promise.all(S).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:S,loadingTask:L}=this;S.on("GetReader",((U,$)=>{(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}},$.onPull=()=>{this._fullReader.read().then((function({value:D,done:F}){F?$.close():((0,o.assert)(D instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),$.enqueue(new Uint8Array(D),1,[D]))})).catch((D=>{$.error(D)}))},$.onCancel=D=>{this._fullReader.cancel(D),$.ready.catch((F=>{if(!this.destroyed)throw F}))}})),S.on("ReaderHeadersReady",(U=>{let $=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})}),$.resolve({isStreamingSupported:D.isStreamingSupported,isRangeSupported:D.isRangeSupported,contentLength:D.contentLength})}),$.reject),$.promise})),S.on("GetRangeReader",((U,$)=>{(0,o.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let D=this._networkStream.getRangeReader(U.begin,U.end);D?($.onPull=()=>{D.read().then((function({value:F,done:V}){V?$.close():((0,o.assert)(F instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),$.enqueue(new Uint8Array(F),1,[F]))})).catch((F=>{$.error(F)}))},$.onCancel=F=>{D.cancel(F),$.ready.catch((V=>{if(!this.destroyed)throw V}))}):$.close()})),S.on("GetDoc",(({pdfInfo:U})=>{this._numPages=U.numPages,this._htmlForXfa=U.htmlForXfa,delete U.htmlForXfa,L._capability.resolve(new rt(U,this))})),S.on("DocException",(function(U){let $;switch(U.name){case"PasswordException":$=new o.PasswordException(U.message,U.code);break;case"InvalidPDFException":$=new o.InvalidPDFException(U.message);break;case"MissingPDFException":$=new o.MissingPDFException(U.message);break;case"UnexpectedResponseException":$=new o.UnexpectedResponseException(U.message,U.status);break;case"UnknownErrorException":$=new o.UnknownErrorException(U.message,U.details);break;default:(0,o.unreachable)("DocException - expected a valid Error.")}L._capability.reject($)})),S.on("PasswordRequest",(U=>{if(this.#n=Promise.withResolvers(),L.onPassword){let $=D=>{D instanceof Error?this.#n.reject(D):this.#n.resolve({password:D})};try{L.onPassword($,U.code)}catch(D){this.#n.reject(D)}}else this.#n.reject(new o.PasswordException(U.message,U.code));return this.#n.promise})),S.on("DataLoaded",(U=>{L.onProgress?.({loaded:U.length,total:U.length}),this.downloadInfoCapability.resolve(U)})),S.on("StartRenderPage",(U=>{this.destroyed||this.#e.get(U.pageIndex)._startRenderPage(U.transparency,U.cacheKey)})),S.on("commonobj",(([U,$,D])=>{if(this.destroyed||this.commonObjs.has(U))return null;switch($){case"Font":let F=this._params;if("error"in D){let tt=D.error;(0,o.warn)(`Error during font loading: ${tt}`),this.commonObjs.resolve(U,tt);break}let V=F.pdfBug&&globalThis.FontInspector?.enabled?(tt,nt)=>globalThis.FontInspector.fontAdded(tt,nt):null,Q=new g.FontFaceObject(D,{isEvalSupported:F.isEvalSupported,disableFontFace:F.disableFontFace,ignoreErrors:F.ignoreErrors,inspectFont:V});this.fontLoader.bind(Q).catch((()=>S.sendWithPromise("FontFallback",{id:U}))).finally((()=>{!F.fontExtraProperties&&Q.data&&(Q.data=null),this.commonObjs.resolve(U,Q)}));break;case"CopyLocalImage":let{imageRef:Z}=D;(0,o.assert)(Z,"The imageRef must be defined.");for(let tt of this.#e.values())for(let[,nt]of tt.objs)if(nt.ref===Z)return nt.dataLen?(this.commonObjs.resolve(U,structuredClone(nt)),nt.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(U,D);break;default:throw new Error(`Got unknown common object type ${$}`)}return null})),S.on("obj",(([U,$,D,F])=>{if(this.destroyed)return;let V=this.#e.get($);if(!V.objs.has(U))if(V._intentStates.size!==0)switch(D){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 ${D}`)}else F?.bitmap?.close()})),S.on("DocProgress",(U=>{this.destroyed||L.onProgress?.({loaded:U.loaded,total:U.total})})),S.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.")))),S.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:S,transfer:L}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:S,filename:this._fullReader?.filename??null},L).finally((()=>{this.annotationStorage.resetModified()}))}getPage(S){if(!Number.isInteger(S)||S<=0||S>this._numPages)return Promise.reject(new Error("Invalid page request."));let L=S-1,U=this.#i.get(L);if(U)return U;let $=this.messageHandler.sendWithPromise("GetPage",{pageIndex:L}).then((D=>{if(this.destroyed)throw new Error("Transport destroyed");let F=new ct(L,D,this,this._params.pdfBug);return this.#e.set(L,F),F}));return this.#i.set(L,$),$}getPageIndex(S){return typeof S!="object"||S===null||!Number.isInteger(S.num)||S.num<0||!Number.isInteger(S.gen)||S.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:S.num,gen:S.gen})}getAnnotations(S,L){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:S,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(S){return typeof S!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:S})}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(S){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:S})}getStructTree(S){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:S})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(S){return this.#r("GetOptionalContentConfig").then((L=>new u.OptionalContentConfig(L,S)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let S="GetMetadata",L=this.#t.get(S);if(L)return L;let U=this.messageHandler.sendWithPromise(S,null).then(($=>({info:$[0],metadata:$[1]?new C.Metadata($[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#t.set(S,U),U}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(S=!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(),S||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),(0,a.cleanupTextLayer)()}}get loadingParams(){let{disableAutoFetch:S,enableXfa:L}=this._params;return(0,o.shadow)(this,"loadingParams",{disableAutoFetch:S,enableXfa:L})}}let R=Symbol("INITIAL_DATA");class p{#t=Object.create(null);#e(S){return this.#t[S]||={...Promise.withResolvers(),data:R}}get(S,L=null){if(L){let $=this.#e(S);return $.promise.then((()=>L($.data))),null}let U=this.#t[S];if(!U||U.data===R)throw new Error(`Requesting object that isn't resolved yet ${S}.`);return U.data}has(S){let L=this.#t[S];return!!L&&L.data!==R}resolve(S,L=null){let U=this.#e(S);U.data=L,U.resolve()}clear(){for(let S in this.#t){let{data:L}=this.#t[S];L?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(let S in this.#t){let{data:L}=this.#t[S];L!==R&&(yield[S,L])}}}class v{#t=null;constructor(S){this.#t=S,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(S=0){this.#t.cancel(null,S)}get separateAnnots(){let{separateAnnots:S}=this.#t.operatorList;if(!S)return!1;let{annotationCanvasMap:L}=this.#t;return S.form||S.canvas&&L?.size>0}}class _{static#t=new WeakSet;constructor({callback:S,params:L,objs:U,commonObjs:$,annotationCanvasMap:D,operatorList:F,pageIndex:V,canvasFactory:Q,filterFactory:Z,useRequestAnimationFrame:tt=!1,pdfBug:nt=!1,pageColors:pt=null}){this.callback=S,this.params=L,this.objs=U,this.commonObjs=$,this.annotationCanvasMap=D,this.operatorListIdx=null,this.operatorList=F,this._pageIndex=V,this.canvasFactory=Q,this.filterFactory=Z,this._pdfBug=nt,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 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:S=!1,optionalContentConfig:L}){if(this.cancelled)return;if(this._canvas){if(_.#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.");_.#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:$,transform:D,background:F}=this.params;this.gfx=new d.CanvasGraphics(U,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:L},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:D,viewport:$,transparency:S,background:F}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(S=null,L=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),_.#t.delete(this._canvas),this.callback(S||new h.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(),_.#t.delete(this._canvas),this.callback())))}}let k="4.1.392",O="fcb76a78d";n()}catch(E){n(E)}}))},583:(s,t,e)=>{e.d(t,{BaseCMapReaderFactory:()=>l,BaseCanvasFactory:()=>o,BaseFilterFactory:()=>n,BaseSVGFactory:()=>g,BaseStandardFontDataFactory:()=>h});var i=e(292);class n{constructor(){this.constructor===n&&(0,i.unreachable)("Cannot initialize BaseFilterFactory.")}addFilter(d){return"none"}addHCMFilter(d,a){return"none"}addHighlightHCMFilter(d,a,f,A,C){return"none"}destroy(d=!1){}}class o{constructor(){this.constructor===o&&(0,i.unreachable)("Cannot initialize BaseCanvasFactory.")}create(d,a){if(d<=0||a<=0)throw new Error("Invalid canvas size");let f=this._createCanvas(d,a);return{canvas:f,context:f.getContext("2d")}}reset(d,a,f){if(!d.canvas)throw new Error("Canvas is not specified");if(a<=0||f<=0)throw new Error("Invalid canvas size");d.canvas.width=a,d.canvas.height=f}destroy(d){if(!d.canvas)throw new Error("Canvas is not specified");d.canvas.width=0,d.canvas.height=0,d.canvas=null,d.context=null}_createCanvas(d,a){(0,i.unreachable)("Abstract method `_createCanvas` called.")}}class l{constructor({baseUrl:d=null,isCompressed:a=!0}){this.constructor===l&&(0,i.unreachable)("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=d,this.isCompressed=a}async fetch({name:d}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!d)throw new Error("CMap name must be specified.");let a=this.baseUrl+d+(this.isCompressed?".bcmap":""),f=this.isCompressed?i.CMapCompressionType.BINARY:i.CMapCompressionType.NONE;return this._fetchData(a,f).catch((A=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${a}`)}))}_fetchData(d,a){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class h{constructor({baseUrl:d=null}){this.constructor===h&&(0,i.unreachable)("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=d}async fetch({filename:d}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!d)throw new Error("Font filename must be specified.");let a=`${this.baseUrl}${d}`;return this._fetchData(a).catch((f=>{throw new Error(`Unable to load font data at: ${a}`)}))}_fetchData(d){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class g{constructor(){this.constructor===g&&(0,i.unreachable)("Cannot initialize BaseSVGFactory.")}create(d,a,f=!1){if(d<=0||a<=0)throw new Error("Invalid SVG dimensions");let A=this._createSVG("svg:svg");return A.setAttribute("version","1.1"),f||(A.setAttribute("width",`${d}px`),A.setAttribute("height",`${a}px`)),A.setAttribute("preserveAspectRatio","none"),A.setAttribute("viewBox",`0 0 ${d} ${a}`),A}createElement(d){if(typeof d!="string")throw new Error("Invalid SVG element type");return this._createSVG(d)}_createSVG(d){(0,i.unreachable)("Abstract method `_createSVG` called.")}}},923:(s,t,e)=>{e.d(t,{CanvasGraphics:()=>st});var i=e(292),n=e(419);let o="Fill",l="Stroke",h="Shading";function g(W,x){if(!x)return;let T=x[2]-x[0],R=x[3]-x[1],p=new Path2D;p.rect(x[0],x[1],T,R),W.clip(p)}class m{constructor(){this.constructor===m&&(0,i.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,i.unreachable)("Abstract method `getPattern` called.")}}class d extends m{constructor(x){super(),this._type=x[1],this._bbox=x[2],this._colorStops=x[3],this._p0=x[4],this._p1=x[5],this._r0=x[6],this._r1=x[7],this.matrix=null}_createGradient(x){let T;this._type==="axial"?T=x.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(T=x.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let R of this._colorStops)T.addColorStop(R[0],R[1]);return T}getPattern(x,T,R,p){let v;if(p===l||p===o){let _=T.current.getClippedPathBoundingBox(p,(0,n.getCurrentTransform)(x))||[0,0,0,0],k=Math.ceil(_[2]-_[0])||1,O=Math.ceil(_[3]-_[1])||1,M=T.cachedCanvases.getCanvas("pattern",k,O,!0),S=M.context;S.clearRect(0,0,S.canvas.width,S.canvas.height),S.beginPath(),S.rect(0,0,S.canvas.width,S.canvas.height),S.translate(-_[0],-_[1]),R=i.Util.transform(R,[1,0,0,1,_[0],_[1]]),S.transform(...T.baseTransform),this.matrix&&S.transform(...this.matrix),g(S,this._bbox),S.fillStyle=this._createGradient(S),S.fill(),v=x.createPattern(M.canvas,"no-repeat");let L=new DOMMatrix(R);v.setTransform(L)}else g(x,this._bbox),v=this._createGradient(x);return v}}function a(W,x,T,R,p,v,_,k){let O=x.coords,M=x.colors,S=W.data,L=4*W.width,U;O[T+1]>O[R+1]&&(U=T,T=R,R=U,U=v,v=_,_=U),O[R+1]>O[p+1]&&(U=R,R=p,p=U,U=_,_=k,k=U),O[T+1]>O[R+1]&&(U=T,T=R,R=U,U=v,v=_,_=U);let $=(O[T]+x.offsetX)*x.scaleX,D=(O[T+1]+x.offsetY)*x.scaleY,F=(O[R]+x.offsetX)*x.scaleX,V=(O[R+1]+x.offsetY)*x.scaleY,Q=(O[p]+x.offsetX)*x.scaleX,Z=(O[p+1]+x.offsetY)*x.scaleY;if(D>=Z)return;let tt=M[v],nt=M[v+1],pt=M[v+2],dt=M[_],lt=M[_+1],wt=M[_+2],Tt=M[k],xt=M[k+1],It=M[k+2],Lt=Math.round(D),Ut=Math.round(Z),jt,he,Se,Ne,Te,Ie,pi,fi;for(let le=Lt;le<=Ut;le++){if(le<V){let ne=le<D?0:(D-le)/(D-V);jt=$-($-F)*ne,he=tt-(tt-dt)*ne,Se=nt-(nt-lt)*ne,Ne=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-Tt)*ne,Se=lt-(lt-xt)*ne,Ne=wt-(wt-It)*ne}let oe;oe=le<D?0:le>Z?1:(D-le)/(D-Z),Te=$-($-Q)*oe,Ie=tt-(tt-Tt)*oe,pi=nt-(nt-xt)*oe,fi=pt-(pt-It)*oe;let gi=Math.round(Math.min(jt,Te)),ws=Math.round(Math.max(jt,Te)),Me=L*le+4*gi;for(let ne=gi;ne<=ws;ne++)oe=(jt-ne)/(jt-Te),oe<0?oe=0:oe>1&&(oe=1),S[Me++]=he-(he-Ie)*oe|0,S[Me++]=Se-(Se-pi)*oe|0,S[Me++]=Ne-(Ne-fi)*oe|0,S[Me++]=255}}function f(W,x,T){let R=x.coords,p=x.colors,v,_;switch(x.type){case"lattice":let k=x.verticesPerRow,O=Math.floor(R.length/k)-1,M=k-1;for(v=0;v<O;v++){let S=v*k;for(let L=0;L<M;L++,S++)a(W,T,R[S],R[S+1],R[S+k],p[S],p[S+1],p[S+k]),a(W,T,R[S+k+1],R[S+1],R[S+k],p[S+k+1],p[S+1],p[S+k])}break;case"triangles":for(v=0,_=R.length;v<_;v+=3)a(W,T,R[v],R[v+1],R[v+2],p[v],p[v+1],p[v+2]);break;default:throw new Error("illegal figure")}}class A extends m{constructor(x){super(),this._coords=x[2],this._colors=x[3],this._figures=x[4],this._bounds=x[5],this._bbox=x[7],this._background=x[8],this.matrix=null}_createMeshCanvas(x,T,R){let p=Math.floor(this._bounds[0]),v=Math.floor(this._bounds[1]),_=Math.ceil(this._bounds[2])-p,k=Math.ceil(this._bounds[3])-v,O=Math.min(Math.ceil(Math.abs(_*x[0]*1.1)),3e3),M=Math.min(Math.ceil(Math.abs(k*x[1]*1.1)),3e3),S=_/O,L=k/M,U={coords:this._coords,colors:this._colors,offsetX:-p,offsetY:-v,scaleX:1/S,scaleY:1/L},$=O+4,D=M+4,F=R.getCanvas("mesh",$,D,!1),V=F.context,Q=V.createImageData(O,M);if(T){let Z=Q.data;for(let tt=0,nt=Z.length;tt<nt;tt+=4)Z[tt]=T[0],Z[tt+1]=T[1],Z[tt+2]=T[2],Z[tt+3]=255}for(let Z of this._figures)f(Q,Z,U);return V.putImageData(Q,2,2),{canvas:F.canvas,offsetX:p-2*S,offsetY:v-2*L,scaleX:S,scaleY:L}}getPattern(x,T,R,p){g(x,this._bbox);let v;if(p===h)v=i.Util.singularValueDecompose2dScale((0,n.getCurrentTransform)(x));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 _=this._createMeshCanvas(v,p===h?null:this._background,T.cachedCanvases);return p!==h&&(x.setTransform(...T.baseTransform),this.matrix&&x.transform(...this.matrix)),x.translate(_.offsetX,_.offsetY),x.scale(_.scaleX,_.scaleY),x.createPattern(_.canvas,"no-repeat")}}class C extends m{getPattern(){return"hotpink"}}let u=1,y=2;class r{static MAX_PATTERN_SIZE=3e3;constructor(x,T,R,p,v){this.operatorList=x[2],this.matrix=x[3]||[1,0,0,1,0,0],this.bbox=x[4],this.xstep=x[5],this.ystep=x[6],this.paintType=x[7],this.tilingType=x[8],this.color=T,this.ctx=R,this.canvasGraphicsFactory=p,this.baseTransform=v}createPatternCanvas(x){let T=this.operatorList,R=this.bbox,p=this.xstep,v=this.ystep,_=this.paintType,k=this.tilingType,O=this.color,M=this.canvasGraphicsFactory;(0,i.info)("TilingType: "+k);let S=R[0],L=R[1],U=R[2],$=R[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(p,this.ctx.canvas.width,V[0]),Z=this.getSizeAndScale(v,this.ctx.canvas.height,V[1]),tt=x.cachedCanvases.getCanvas("pattern",Q.size,Z.size,!0),nt=tt.context,pt=M.createCanvasGraphics(nt);pt.groupLevel=x.groupLevel,this.setFillAndStrokeStyleToContext(pt,_,O);let dt=S,lt=L,wt=U,Tt=$;return S<0&&(dt=0,wt+=Math.abs(S)),L<0&&(lt=0,Tt+=Math.abs(L)),nt.translate(-Q.scale*dt,-Z.scale*lt),pt.transform(Q.scale,0,0,Z.scale,0,0),nt.save(),this.clipBbox(pt,dt,lt,wt,Tt),pt.baseTransform=(0,n.getCurrentTransform)(pt.ctx),pt.executeOperatorList(T),pt.endDrawing(),{canvas:tt.canvas,scaleX:Q.scale,scaleY:Z.scale,offsetX:dt,offsetY:lt}}getSizeAndScale(x,T,R){x=Math.abs(x);let p=Math.max(r.MAX_PATTERN_SIZE,T),v=Math.ceil(x*R);return v>=p?v=p:R=v/x,{scale:R,size:v}}clipBbox(x,T,R,p,v){let _=p-T,k=v-R;x.ctx.rect(T,R,_,k),x.current.updateRectMinMax((0,n.getCurrentTransform)(x.ctx),[T,R,p,v]),x.clip(),x.endPath()}setFillAndStrokeStyleToContext(x,T,R){let p=x.ctx,v=x.current;switch(T){case u:let _=this.ctx;p.fillStyle=_.fillStyle,p.strokeStyle=_.strokeStyle,v.fillColor=_.fillStyle,v.strokeColor=_.strokeStyle;break;case y:let k=i.Util.makeHexColor(R[0],R[1],R[2]);p.fillStyle=k,p.strokeStyle=k,v.fillColor=k,v.strokeColor=k;break;default:throw new i.FormatError(`Unsupported paint type: ${T}`)}}getPattern(x,T,R,p){let v=R;p!==h&&(v=i.Util.transform(v,T.baseTransform),this.matrix&&(v=i.Util.transform(v,this.matrix)));let _=this.createPatternCanvas(T),k=new DOMMatrix(v);k=k.translate(_.offsetX,_.offsetY),k=k.scale(1/_.scaleX,1/_.scaleY);let O=x.createPattern(_.canvas,"repeat");return O.setTransform(k),O}}function c({src:W,srcPos:x=0,dest:T,width:R,height:p,nonBlackColor:v=4294967295,inverseDecode:_=!1}){let k=i.FeatureTest.isLittleEndian?4278190080:255,[O,M]=_?[v,k]:[k,v],S=R>>3,L=7&R,U=W.length;T=new Uint32Array(T.buffer);let $=0;for(let D=0;D<p;D++){for(let V=x+S;x<V;x++){let Q=x<U?W[x]:255;T[$++]=128&Q?M:O,T[$++]=64&Q?M:O,T[$++]=32&Q?M:O,T[$++]=16&Q?M:O,T[$++]=8&Q?M:O,T[$++]=4&Q?M:O,T[$++]=2&Q?M:O,T[$++]=1&Q?M:O}if(L===0)continue;let F=x<U?W[x++]:255;for(let V=0;V<L;V++)T[$++]=F&1<<7-V?M:O}return{srcPos:x,destPos:$}}let b=4096,w=16;class P{constructor(x){this.canvasFactory=x,this.cache=Object.create(null)}getCanvas(x,T,R){let p;return this.cache[x]!==void 0?(p=this.cache[x],this.canvasFactory.reset(p,T,R)):(p=this.canvasFactory.create(T,R),this.cache[x]=p),p}delete(x){delete this.cache[x]}clear(){for(let x in this.cache){let T=this.cache[x];this.canvasFactory.destroy(T),delete this.cache[x]}}}function E(W,x,T,R,p,v,_,k,O,M){let[S,L,U,$,D,F]=(0,n.getCurrentTransform)(W);if(L===0&&U===0){let V=_*S+D,Q=Math.round(V),Z=k*$+F,tt=Math.round(Z),nt=(_+O)*S+D,pt=Math.abs(Math.round(nt)-Q)||1,dt=(k+M)*$+F,lt=Math.abs(Math.round(dt)-tt)||1;return W.setTransform(Math.sign(S),0,0,Math.sign($),Q,tt),W.drawImage(x,T,R,p,v,0,0,pt,lt),W.setTransform(S,L,U,$,D,F),[pt,lt]}if(S===0&&$===0){let V=k*U+D,Q=Math.round(V),Z=_*L+F,tt=Math.round(Z),nt=(k+M)*U+D,pt=Math.abs(Math.round(nt)-Q)||1,dt=(_+O)*L+F,lt=Math.abs(Math.round(dt)-tt)||1;return W.setTransform(0,Math.sign(L),Math.sign(U),0,Q,tt),W.drawImage(x,T,R,p,v,0,0,lt,pt),W.setTransform(S,L,U,$,D,F),[lt,pt]}return W.drawImage(x,T,R,p,v,_,k,O,M),[Math.hypot(S,L)*O,Math.hypot(U,$)*M]}class I{constructor(x,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,x,T])}clone(){let x=Object.create(this);return x.clipBox=this.clipBox.slice(),x}setCurrentPoint(x,T){this.x=x,this.y=T}updatePathMinMax(x,T,R){[T,R]=i.Util.applyTransform([T,R],x),this.minX=Math.min(this.minX,T),this.minY=Math.min(this.minY,R),this.maxX=Math.max(this.maxX,T),this.maxY=Math.max(this.maxY,R)}updateRectMinMax(x,T){let R=i.Util.applyTransform(T,x),p=i.Util.applyTransform(T.slice(2),x),v=i.Util.applyTransform([T[0],T[3]],x),_=i.Util.applyTransform([T[2],T[1]],x);this.minX=Math.min(this.minX,R[0],p[0],v[0],_[0]),this.minY=Math.min(this.minY,R[1],p[1],v[1],_[1]),this.maxX=Math.max(this.maxX,R[0],p[0],v[0],_[0]),this.maxY=Math.max(this.maxY,R[1],p[1],v[1],_[1])}updateScalingPathMinMax(x,T){i.Util.scaleMinMax(x,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(x,T,R,p,v,_,k,O,M,S){let L=i.Util.bezierBoundingBox(T,R,p,v,_,k,O,M,S);S||this.updateRectMinMax(x,L)}getPathBoundingBox(x=o,T=null){let R=[this.minX,this.minY,this.maxX,this.maxY];if(x===l){T||(0,i.unreachable)("Stroke bounding box must include transform.");let p=i.Util.singularValueDecompose2dScale(T),v=p[0]*this.lineWidth/2,_=p[1]*this.lineWidth/2;R[0]-=v,R[1]-=_,R[2]+=v,R[3]+=_}return R}updateClipFromPath(){let x=i.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(x||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(x){this.clipBox=x,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(x=o,T=null){return i.Util.intersect(this.clipBox,this.getPathBoundingBox(x,T))}}function N(W,x){if(typeof ImageData<"u"&&x instanceof ImageData){W.putImageData(x,0,0);return}let T=x.height,R=x.width,p=T%w,v=(T-p)/w,_=p===0?v:v+1,k=W.createImageData(R,w),O,M=0,S=x.data,L=k.data,U,$,D,F;if(x.kind===i.ImageKind.GRAYSCALE_1BPP){let V=S.byteLength,Q=new Uint32Array(L.buffer,0,L.byteLength>>2),Z=Q.length,tt=R+7>>3,nt=4294967295,pt=i.FeatureTest.isLittleEndian?4278190080:255;for(U=0;U<_;U++){for(D=U<v?w:p,O=0,$=0;$<D;$++){let dt=V-M,lt=0,wt=dt>tt?R:8*dt-7,Tt=-8&wt,xt=0,It=0;for(;lt<Tt;lt+=8)It=S[M++],Q[O++]=128&It?nt:pt,Q[O++]=64&It?nt:pt,Q[O++]=32&It?nt:pt,Q[O++]=16&It?nt:pt,Q[O++]=8&It?nt:pt,Q[O++]=4&It?nt:pt,Q[O++]=2&It?nt:pt,Q[O++]=1&It?nt:pt;for(;lt<wt;lt++)xt===0&&(It=S[M++],xt=128),Q[O++]=It&xt?nt:pt,xt>>=1}for(;O<Z;)Q[O++]=0;W.putImageData(k,0,U*w)}}else if(x.kind===i.ImageKind.RGBA_32BPP){for($=0,F=R*w*4,U=0;U<v;U++)L.set(S.subarray(M,M+F)),M+=F,W.putImageData(k,0,$),$+=w;U<_&&(F=R*p*4,L.set(S.subarray(M,M+F)),W.putImageData(k,0,$))}else{if(x.kind!==i.ImageKind.RGB_24BPP)throw new Error(`bad image kind: ${x.kind}`);for(D=w,F=R*D,U=0;U<_;U++){for(U>=v&&(D=p,F=R*D),O=0,$=F;$--;)L[O++]=S[M++],L[O++]=S[M++],L[O++]=S[M++],L[O++]=255;W.putImageData(k,0,U*w)}}}function z(W,x){if(x.bitmap){W.drawImage(x.bitmap,0,0);return}let T=x.height,R=x.width,p=T%w,v=(T-p)/w,_=p===0?v:v+1,k=W.createImageData(R,w),O=0,M=x.data,S=k.data;for(let L=0;L<_;L++){let U=L<v?w:p;({srcPos:O}=c({src:M,srcPos:O,dest:S,width:R,height:U,nonBlackColor:0})),W.putImageData(k,0,L*w)}}function H(W,x){let T=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let R of T)W[R]!==void 0&&(x[R]=W[R]);W.setLineDash!==void 0&&(x.setLineDash(W.getLineDash()),x.lineDashOffset=W.lineDashOffset)}function X(W){if(W.strokeStyle=W.fillStyle="#000000",W.fillRule="nonzero",W.globalAlpha=1,W.lineWidth=1,W.lineCap="butt",W.lineJoin="miter",W.miterLimit=10,W.globalCompositeOperation="source-over",W.font="10px sans-serif",W.setLineDash!==void 0&&(W.setLineDash([]),W.lineDashOffset=0),!i.isNodeJS){let{filter:x}=W;x!=="none"&&x!==""&&(W.filter="none")}}function it(W,x,T,R){let p=W.length;for(let v=3;v<p;v+=4){let _=W[v];if(_===0)W[v-3]=x,W[v-2]=T,W[v-1]=R;else if(_<255){let k=255-_;W[v-3]=W[v-3]*_+x*k>>8,W[v-2]=W[v-2]*_+T*k>>8,W[v-1]=W[v-1]*_+R*k>>8}}}function at(W,x,T){let R=W.length;for(let p=3;p<R;p+=4){let v=T?T[W[p]]:W[p];x[p]=x[p]*v*.00392156862745098|0}}function K(W,x,T){let R=W.length;for(let p=3;p<R;p+=4){let v=77*W[p-3]+152*W[p-2]+28*W[p-1];x[p]=T?x[p]*T[v>>8]>>8:x[p]*v>>16}}function j(W,x,T,R){let p=R[0],v=R[1],_=R[2]-p,k=R[3]-v;_!==0&&k!==0&&((function(M,S,L,U,$,D,F,V,Q,Z,tt){let nt=!!D,pt=nt?D[0]:0,dt=nt?D[1]:0,lt=nt?D[2]:0,wt=$==="Luminosity"?K:at,Tt=Math.min(U,Math.ceil(1048576/L));for(let xt=0;xt<U;xt+=Tt){let It=Math.min(Tt,U-xt),Lt=M.getImageData(V-Z,xt+(Q-tt),L,It),Ut=S.getImageData(V,xt+Q,L,It);nt&&it(Lt.data,pt,dt,lt),wt(Lt.data,Ut.data,F),S.putImageData(Ut,V,xt+Q)}})(x.context,T,_,k,x.subtype,x.backdrop,x.transferMap,p,v,x.offsetX,x.offsetY),W.save(),W.globalAlpha=1,W.globalCompositeOperation="source-over",W.setTransform(1,0,0,1,0,0),W.drawImage(T.canvas,0,0),W.restore())}function G(W,x){let T=i.Util.singularValueDecompose2dScale(W);T[0]=Math.fround(T[0]),T[1]=Math.fround(T[1]);let R=Math.fround((globalThis.devicePixelRatio||1)*n.PixelsPerInch.PDF_TO_CSS_UNITS);return x!==void 0?x:T[0]<=R||T[1]<=R}let Y=["butt","round","square"],et=["miter","round","bevel"],rt={},ct={};class st{constructor(x,T,R,p,v,{optionalContentConfig:_,markedContentStack:k=null},O,M){this.ctx=x,this.current=new I(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=R,this.canvasFactory=p,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=_,this.cachedCanvases=new P(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(x,T=null){return typeof x=="string"?x.startsWith("g_")?this.commonObjs.get(x):this.objs.get(x):T}beginDrawing({transform:x,viewport:T,transparency:R=!1,background:p=null}){let v=this.ctx.canvas.width,_=this.ctx.canvas.height,k=this.ctx.fillStyle;if(this.ctx.fillStyle=p||"#ffffff",this.ctx.fillRect(0,0,v,_),this.ctx.fillStyle=k,R){let O=this.cachedCanvases.getCanvas("transparent",v,_);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(),X(this.ctx),x&&(this.ctx.transform(...x),this.outputScaleX=x[0],this.outputScaleY=x[0]),this.ctx.transform(...T.transform),this.viewportScale=T.scale,this.baseTransform=(0,n.getCurrentTransform)(this.ctx)}executeOperatorList(x,T,R,p){let v=x.argsArray,_=x.fnArray,k=T||0,O=v.length;if(O===k)return k;let M=O-k>10&&typeof R=="function",S=M?Date.now()+15:0,L=0,U=this.commonObjs,$=this.objs,D;for(;;){if(p!==void 0&&k===p.nextBreakPoint)return p.breakIt(k,R),k;if(D=_[k],D!==i.OPS.dependency)this[D].apply(this,v[k]);else for(let F of v[k]){let V=F.startsWith("g_")?U:$;if(!V.has(F))return V.get(F,R),k}if(k++,k===O)return k;if(M&&++L>10){if(Date.now()>S)return R(),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 x of this._cachedBitmapsMap.values()){for(let T of x.values())typeof HTMLCanvasElement<"u"&&T instanceof HTMLCanvasElement&&(T.width=T.height=0);x.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){let x=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(x!=="none"){let T=this.ctx.filter;this.ctx.filter=x,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=T}}}_scaleImage(x,T){let R=x.width,p=x.height,v,_,k=Math.max(Math.hypot(T[0],T[1]),1),O=Math.max(Math.hypot(T[2],T[3]),1),M=R,S=p,L="prescale1";for(;k>2&&M>1||O>2&&S>1;){let U=M,$=S;k>2&&M>1&&(U=M>=16384?Math.floor(M/2)-1||1:Math.ceil(M/2),k/=M/U),O>2&&S>1&&($=S>=16384?Math.floor(S/2)-1||1:Math.ceil(S)/2,O/=S/$),v=this.cachedCanvases.getCanvas(L,U,$),_=v.context,_.clearRect(0,0,U,$),_.drawImage(x,0,0,M,S,0,0,U,$),x=v.canvas,M=U,S=$,L=L==="prescale1"?"prescale2":"prescale1"}return{img:x,paintWidth:M,paintHeight:S}}_createMaskCanvas(x){let T=this.ctx,{width:R,height:p}=x,v=this.current.fillColor,_=this.current.patternFill,k=(0,n.getCurrentTransform)(T),O,M,S,L;if((x.bitmap||x.data)&&x.count>1){let wt=x.bitmap||x.data.buffer;M=JSON.stringify(_?k:[k.slice(0,4),v]),O=this._cachedBitmapsMap.get(wt),O||(O=new Map,this._cachedBitmapsMap.set(wt,O));let Tt=O.get(M);if(Tt&&!_)return{canvas:Tt,offsetX:Math.round(Math.min(k[0],k[2])+k[4]),offsetY:Math.round(Math.min(k[1],k[3])+k[5])};S=Tt}S||(L=this.cachedCanvases.getCanvas("maskCanvas",R,p),z(L.context,x));let U=i.Util.transform(k,[1/R,0,0,-1/p,0,0]);U=i.Util.transform(U,[1,0,0,1,0,-p]);let[$,D,F,V]=i.Util.getAxialAlignedBoundingBox([0,0,R,p],U),Q=Math.round(F-$)||1,Z=Math.round(V-D)||1,tt=this.cachedCanvases.getCanvas("fillCanvas",Q,Z),nt=tt.context,pt=$,dt=D;nt.translate(-pt,-dt),nt.transform(...U),S||(S=this._scaleImage(L.canvas,(0,n.getCurrentTransformInverse)(nt)),S=S.img,O&&_&&O.set(M,S)),nt.imageSmoothingEnabled=G((0,n.getCurrentTransform)(nt),x.interpolate),E(nt,S,0,0,S.width,S.height,0,0,R,p),nt.globalCompositeOperation="source-in";let lt=i.Util.transform((0,n.getCurrentTransformInverse)(nt),[1,0,0,1,-pt,-dt]);return nt.fillStyle=_?v.getPattern(T,this,lt,o):v,nt.fillRect(0,0,R,p),O&&!_&&(this.cachedCanvases.delete("fillCanvas"),O.set(M,tt.canvas)),{canvas:tt.canvas,offsetX:Math.round(pt),offsetY:Math.round(dt)}}setLineWidth(x){x!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=x,this.ctx.lineWidth=x}setLineCap(x){this.ctx.lineCap=Y[x]}setLineJoin(x){this.ctx.lineJoin=et[x]}setMiterLimit(x){this.ctx.miterLimit=x}setDash(x,T){let R=this.ctx;R.setLineDash!==void 0&&(R.setLineDash(x),R.lineDashOffset=T)}setRenderingIntent(x){}setFlatness(x){}setGState(x){for(let[T,R]of x)switch(T){case"LW":this.setLineWidth(R);break;case"LC":this.setLineCap(R);break;case"LJ":this.setLineJoin(R);break;case"ML":this.setMiterLimit(R);break;case"D":this.setDash(R[0],R[1]);break;case"RI":this.setRenderingIntent(R);break;case"FL":this.setFlatness(R);break;case"Font":this.setFont(R[0],R[1]);break;case"CA":this.current.strokeAlpha=R;break;case"ca":this.current.fillAlpha=R,this.ctx.globalAlpha=R;break;case"BM":this.ctx.globalCompositeOperation=R;break;case"SMask":this.current.activeSMask=R?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(R)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let x=this.inSMaskMode;this.current.activeSMask&&!x?this.beginSMaskMode():!this.current.activeSMask&&x&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let x=this.ctx.canvas.width,T=this.ctx.canvas.height,R="smaskGroupAt"+this.groupLevel,p=this.cachedCanvases.getCanvas(R,x,T);this.suspendedCtx=this.ctx,this.ctx=p.context;let v=this.ctx;v.setTransform(...(0,n.getCurrentTransform)(this.suspendedCtx)),H(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(S,L){O.translate(S,L),this.__originalTranslate(S,L)},k.scale=function(S,L){O.scale(S,L),this.__originalScale(S,L)},k.transform=function(S,L,U,$,D,F){O.transform(S,L,U,$,D,F),this.__originalTransform(S,L,U,$,D,F)},k.setTransform=function(S,L,U,$,D,F){O.setTransform(S,L,U,$,D,F),this.__originalSetTransform(S,L,U,$,D,F)},k.resetTransform=function(){O.resetTransform(),this.__originalResetTransform()},k.rotate=function(S){O.rotate(S),this.__originalRotate(S)},k.clip=function(S){O.clip(S),this.__originalClip(S)},k.moveTo=function(M,S){O.moveTo(M,S),this.__originalMoveTo(M,S)},k.lineTo=function(M,S){O.lineTo(M,S),this.__originalLineTo(M,S)},k.bezierCurveTo=function(M,S,L,U,$,D){O.bezierCurveTo(M,S,L,U,$,D),this.__originalBezierCurveTo(M,S,L,U,$,D)},k.rect=function(M,S,L,U){O.rect(M,S,L,U),this.__originalRect(M,S,L,U)},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(),H(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(x){if(!this.current.activeSMask)return;x?(x[0]=Math.floor(x[0]),x[1]=Math.floor(x[1]),x[2]=Math.ceil(x[2]),x[3]=Math.ceil(x[3])):x=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let T=this.current.activeSMask;j(this.suspendedCtx,T,this.ctx,x),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?(H(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let x=this.current;this.stateStack.push(x),this.current=x.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),H(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(x,T,R,p,v,_){this.ctx.transform(x,T,R,p,v,_),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(x,T,R){let p=this.ctx,v=this.current,_,k,O=v.x,M=v.y,S=(0,n.getCurrentTransform)(p),L=S[0]===0&&S[3]===0||S[1]===0&&S[2]===0,U=L?R.slice(0):null;for(let $=0,D=0,F=x.length;$<F;$++)switch(0|x[$]){case i.OPS.rectangle:O=T[D++],M=T[D++];let V=T[D++],Q=T[D++],Z=O+V,tt=M+Q;p.moveTo(O,M),V===0||Q===0?p.lineTo(Z,tt):(p.lineTo(Z,M),p.lineTo(Z,tt),p.lineTo(O,tt)),L||v.updateRectMinMax(S,[O,M,Z,tt]),p.closePath();break;case i.OPS.moveTo:O=T[D++],M=T[D++],p.moveTo(O,M),L||v.updatePathMinMax(S,O,M);break;case i.OPS.lineTo:O=T[D++],M=T[D++],p.lineTo(O,M),L||v.updatePathMinMax(S,O,M);break;case i.OPS.curveTo:_=O,k=M,O=T[D+4],M=T[D+5],p.bezierCurveTo(T[D],T[D+1],T[D+2],T[D+3],O,M),v.updateCurvePathMinMax(S,_,k,T[D],T[D+1],T[D+2],T[D+3],O,M,U),D+=6;break;case i.OPS.curveTo2:_=O,k=M,p.bezierCurveTo(O,M,T[D],T[D+1],T[D+2],T[D+3]),v.updateCurvePathMinMax(S,_,k,O,M,T[D],T[D+1],T[D+2],T[D+3],U),O=T[D+2],M=T[D+3],D+=4;break;case i.OPS.curveTo3:_=O,k=M,O=T[D+2],M=T[D+3],p.bezierCurveTo(T[D],T[D+1],O,M,O,M),v.updateCurvePathMinMax(S,_,k,T[D],T[D+1],O,M,O,M,U),D+=4;break;case i.OPS.closePath:p.closePath()}L&&v.updateScalingPathMinMax(S,U),v.setCurrentPoint(O,M)}closePath(){this.ctx.closePath()}stroke(x=!0){let T=this.ctx,R=this.current.strokeColor;T.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof R=="object"&&R?.getPattern?(T.save(),T.strokeStyle=R.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),l),this.rescaleAndStroke(!1),T.restore()):this.rescaleAndStroke(!0)),x&&this.consumePath(this.current.getClippedPathBoundingBox()),T.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(x=!0){let T=this.ctx,R=this.current.fillColor,p=!1;this.current.patternFill&&(T.save(),T.fillStyle=R.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),o),p=!0);let v=this.current.getClippedPathBoundingBox();this.contentVisible&&v!==null&&(this.pendingEOFill?(T.fill("evenodd"),this.pendingEOFill=!1):T.fill()),p&&T.restore(),x&&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=rt}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 x=this.pendingTextPaths,T=this.ctx;if(x!==void 0){T.save(),T.beginPath();for(let R of x)T.setTransform(...R.transform),T.translate(R.x,R.y),R.addToPath(T,R.fontSize);T.restore(),T.clip(),T.beginPath(),delete this.pendingTextPaths}else T.beginPath()}setCharSpacing(x){this.current.charSpacing=x}setWordSpacing(x){this.current.wordSpacing=x}setHScale(x){this.current.textHScale=x/100}setLeading(x){this.current.leading=-x}setFont(x,T){let R=this.commonObjs.get(x),p=this.current;if(!R)throw new Error(`Can't find font for ${x}`);if(p.fontMatrix=R.fontMatrix||i.FONT_IDENTITY_MATRIX,p.fontMatrix[0]!==0&&p.fontMatrix[3]!==0||(0,i.warn)("Invalid font matrix for font "+x),T<0?(T=-T,p.fontDirection=-1):p.fontDirection=1,this.current.font=R,this.current.fontSize=T,R.isType3Font)return;let v=R.loadedName||"sans-serif",_=R.systemFontInfo?.css||`"${v}", ${R.fallbackName}`,k="normal";R.black?k="900":R.bold&&(k="bold");let O=R.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 ${_}`}setTextRenderingMode(x){this.current.textRenderingMode=x}setTextRise(x){this.current.textRise=x}moveText(x,T){this.current.x=this.current.lineX+=x,this.current.y=this.current.lineY+=T}setLeadingMoveText(x,T){this.setLeading(-T),this.moveText(x,T)}setTextMatrix(x,T,R,p,v,_){this.current.textMatrix=[x,T,R,p,v,_],this.current.textMatrixScale=Math.hypot(x,T),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(x,T,R,p){let v=this.ctx,_=this.current,k=_.font,O=_.textRenderingMode,M=_.fontSize/_.fontSizeScale,S=O&i.TextRenderingMode.FILL_STROKE_MASK,L=!!(O&i.TextRenderingMode.ADD_TO_PATH_FLAG),U=_.patternFill&&!k.missingFile,$;(k.disableFontFace||L||U)&&($=k.getPathGenerator(this.commonObjs,x)),k.disableFontFace||U?(v.save(),v.translate(T,R),v.beginPath(),$(v,M),p&&v.setTransform(...p),S!==i.TextRenderingMode.FILL&&S!==i.TextRenderingMode.FILL_STROKE||v.fill(),S!==i.TextRenderingMode.STROKE&&S!==i.TextRenderingMode.FILL_STROKE||v.stroke(),v.restore()):(S!==i.TextRenderingMode.FILL&&S!==i.TextRenderingMode.FILL_STROKE||v.fillText(x,T,R),S!==i.TextRenderingMode.STROKE&&S!==i.TextRenderingMode.FILL_STROKE||v.strokeText(x,T,R)),L&&(this.pendingTextPaths||=[]).push({transform:(0,n.getCurrentTransform)(v),x:T,y:R,fontSize:M,addToPath:$})}get isFontSubpixelAAEnabled(){let{context:x}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);x.scale(1.5,1),x.fillText("I",0,10);let T=x.getImageData(0,0,10,10).data,R=!1;for(let p=3;p<T.length;p+=4)if(T[p]>0&&T[p]<255){R=!0;break}return(0,i.shadow)(this,"isFontSubpixelAAEnabled",R)}showText(x){let T=this.current,R=T.font;if(R.isType3Font)return this.showType3Text(x);let p=T.fontSize;if(p===0)return;let v=this.ctx,_=T.fontSizeScale,k=T.charSpacing,O=T.wordSpacing,M=T.fontDirection,S=T.textHScale*M,L=x.length,U=R.vertical,$=U?1:-1,D=R.defaultVMetrics,F=p*T.fontMatrix[0],V=T.textRenderingMode===i.TextRenderingMode.FILL&&!R.disableFontFace&&!T.patternFill;v.save(),v.transform(...T.textMatrix),v.translate(T.x,T.y+T.textRise),M>0?v.scale(S,-1):v.scale(S,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,tt=T.textMatrixScale;if(tt===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/=tt;if(_!==1&&(v.scale(_,_),Z/=_),v.lineWidth=Z,R.isInvalidPDFjsFont){let dt=[],lt=0;for(let wt of x)dt.push(wt.unicode),lt+=wt.width;v.fillText(dt.join(""),0,0),T.x+=lt*F*S,v.restore(),this.compose();return}let nt,pt=0;for(nt=0;nt<L;++nt){let dt=x[nt];if(typeof dt=="number"){pt+=$*dt*p/1e3;continue}let lt=!1,wt=(dt.isSpace?O:0)+k,Tt=dt.fontChar,xt=dt.accent,It,Lt,Ut=dt.width;if(U){let jt=dt.vmetric||D,he=-(dt.vmetric?jt[1]:.5*Ut)*F,Se=jt[2]*F;Ut=jt?-jt[0]:Ut,It=he/_,Lt=(pt+Se)/_}else It=pt/_,Lt=0;if(R.remeasure&&Ut>0){let jt=1e3*v.measureText(Tt).width/p*_;if(Ut<jt&&this.isFontSubpixelAAEnabled){let he=Ut/jt;lt=!0,v.save(),v.scale(he,1),It/=he}else Ut!==jt&&(It+=(Ut-jt)/2e3*p/_)}if(this.contentVisible&&(dt.isInFont||R.missingFile)){if(V&&!xt)v.fillText(Tt,It,Lt);else if(this.paintChar(Tt,It,Lt,Q),xt){let jt=It+p*xt.offset.x/_,he=Lt-p*xt.offset.y/_;this.paintChar(xt.fontChar,jt,he,Q)}}pt+=U?Ut*F-wt*M:Ut*F+wt*M,lt&&v.restore()}U?T.y-=pt:T.x+=pt*S,v.restore(),this.compose()}showType3Text(x){let T=this.ctx,R=this.current,p=R.font,v=R.fontSize,_=R.fontDirection,k=p.vertical?1:-1,O=R.charSpacing,M=R.wordSpacing,S=R.textHScale*_,L=R.fontMatrix||i.FONT_IDENTITY_MATRIX,U=x.length,$,D,F,V;if(R.textRenderingMode!==i.TextRenderingMode.INVISIBLE&&v!==0){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,T.save(),T.transform(...R.textMatrix),T.translate(R.x,R.y),T.scale(S,_),$=0;$<U;++$){if(D=x[$],typeof D=="number"){V=k*D*v/1e3,this.ctx.translate(V,0),R.x+=V*S;continue}let Q=(D.isSpace?M:0)+O,Z=p.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),R.x+=F*S}T.restore(),this.processingType3=null}}setCharWidth(x,T){}setCharWidthAndBounds(x,T,R,p,v,_){this.ctx.rect(R,p,v-R,_-p),this.ctx.clip(),this.endPath()}getColorN_Pattern(x){let T;if(x[0]==="TilingPattern"){let R=x[1],p=this.baseTransform||(0,n.getCurrentTransform)(this.ctx),v={createCanvasGraphics:_=>new st(_,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};T=new r(x,R,this.ctx,v,p)}else T=this._getPattern(x[1],x[2]);return T}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(x,T,R){let p=i.Util.makeHexColor(x,T,R);this.ctx.strokeStyle=p,this.current.strokeColor=p}setFillRGBColor(x,T,R){let p=i.Util.makeHexColor(x,T,R);this.ctx.fillStyle=p,this.current.fillColor=p,this.current.patternFill=!1}_getPattern(x,T=null){let R;return this.cachedPatterns.has(x)?R=this.cachedPatterns.get(x):(R=(function(v){switch(v[0]){case"RadialAxial":return new d(v);case"Mesh":return new A(v);case"Dummy":return new C}throw new Error(`Unknown IR type: ${v[0]}`)})(this.getObject(x)),this.cachedPatterns.set(x,R)),T&&(R.matrix=T),R}shadingFill(x){if(!this.contentVisible)return;let T=this.ctx;this.save();let R=this._getPattern(x);T.fillStyle=R.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),h);let p=(0,n.getCurrentTransformInverse)(T);if(p){let{width:v,height:_}=T.canvas,[k,O,M,S]=i.Util.getAxialAlignedBoundingBox([0,0,v,_],p);this.ctx.fillRect(k,O,M-k,S-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(x,T){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),Array.isArray(x)&&x.length===6&&this.transform(...x),this.baseTransform=(0,n.getCurrentTransform)(this.ctx),T)){let R=T[2]-T[0],p=T[3]-T[1];this.ctx.rect(T[0],T[1],R,p),this.current.updateRectMinMax((0,n.getCurrentTransform)(this.ctx),T),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(x){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let T=this.ctx;x.isolated||(0,i.info)("TODO: Support non-isolated groups."),x.knockout&&(0,i.warn)("Knockout groups not supported.");let R=(0,n.getCurrentTransform)(T);if(x.matrix&&T.transform(...x.matrix),!x.bbox)throw new Error("Bounding box is required.");let p=i.Util.getAxialAlignedBoundingBox(x.bbox,(0,n.getCurrentTransform)(T)),v=[0,0,T.canvas.width,T.canvas.height];p=i.Util.intersect(p,v)||[0,0,0,0];let _=Math.floor(p[0]),k=Math.floor(p[1]),O=Math.max(Math.ceil(p[2])-_,1),M=Math.max(Math.ceil(p[3])-k,1),S=1,L=1;O>b&&(S=O/b,O=b),M>b&&(L=M/b,M=b),this.current.startNewPathAndClipBox([0,0,O,M]);let U="groupAt"+this.groupLevel;x.smask&&(U+="_smask_"+this.smaskCounter++%2);let $=this.cachedCanvases.getCanvas(U,O,M),D=$.context;D.scale(1/S,1/L),D.translate(-_,-k),D.transform(...R),x.smask?this.smaskStack.push({canvas:$.canvas,context:D,offsetX:_,offsetY:k,scaleX:S,scaleY:L,subtype:x.smask.subtype,backdrop:x.smask.backdrop,transferMap:x.smask.transferMap||null,startTransformInverse:null}):(T.setTransform(1,0,0,1,0,0),T.translate(_,k),T.scale(S,L),T.save()),H(T,D),this.ctx=D,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(T),this.groupLevel++}endGroup(x){if(!this.contentVisible)return;this.groupLevel--;let T=this.ctx,R=this.groupStack.pop();if(this.ctx=R,this.ctx.imageSmoothingEnabled=!1,x.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let p=(0,n.getCurrentTransform)(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...p);let v=i.Util.getAxialAlignedBoundingBox([0,0,T.canvas.width,T.canvas.height],p);this.ctx.drawImage(T.canvas,0,0),this.ctx.restore(),this.compose(v)}}beginAnnotation(x,T,R,p,v){if(this.#t(),X(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),Array.isArray(T)&&T.length===4){let _=T[2]-T[0],k=T[3]-T[1];if(v&&this.annotationCanvasMap){(R=R.slice())[4]-=T[0],R[5]-=T[1],(T=T.slice())[0]=T[1]=0,T[2]=_,T[3]=k;let[O,M]=i.Util.singularValueDecompose2dScale((0,n.getCurrentTransform)(this.ctx)),{viewportScale:S}=this,L=Math.ceil(_*this.outputScaleX*S),U=Math.ceil(k*this.outputScaleY*S);this.annotationCanvas=this.canvasFactory.create(L,U);let{canvas:$,context:D}=this.annotationCanvas;this.annotationCanvasMap.set(x,$),this.annotationCanvas.savedCtx=this.ctx,this.ctx=D,this.ctx.save(),this.ctx.setTransform(O,0,0,-M,0,k*M),X(this.ctx)}else X(this.ctx),this.ctx.rect(T[0],T[1],_,k),this.ctx.clip(),this.endPath()}this.current=new I(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...R),this.transform(...p)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(x){if(!this.contentVisible)return;let T=x.count;(x=this.getObject(x.data,x)).count=T;let R=this.ctx,p=this.processingType3;if(p&&(p.compiled===void 0&&(p.compiled=(function(O){let{width:M,height:S}=O;if(M>1e3||S>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,$,D,F,V=new Uint8Array(U*(S+1)),Q=M+7&-8,Z=new Uint8Array(Q*S),tt=0;for(let lt of O.data){let wt=128;for(;wt>0;)Z[tt++]=lt&wt?0:255,wt>>=1}let nt=0;for(tt=0,Z[tt]!==0&&(V[0]=1,++nt),D=1;D<M;D++)Z[tt]!==Z[tt+1]&&(V[D]=Z[tt]?2:1,++nt),tt++;for(Z[tt]!==0&&(V[D]=2,++nt),$=1;$<S;$++){tt=$*Q,F=$*U,Z[tt-Q]!==Z[tt]&&(V[F]=Z[tt]?1:8,++nt);let lt=(Z[tt]?4:0)+(Z[tt-Q]?8:0);for(D=1;D<M;D++)lt=(lt>>2)+(Z[tt+1]?4:0)+(Z[tt-Q+1]?8:0),L[lt]&&(V[F+D]=L[lt],++nt),tt++;if(Z[tt-Q]!==Z[tt]&&(V[F+D]=Z[tt]?2:4,++nt),nt>1e3)return null}for(tt=Q*(S-1),F=$*U,Z[tt]!==0&&(V[F]=8,++nt),D=1;D<M;D++)Z[tt]!==Z[tt+1]&&(V[F+D]=Z[tt]?4:8,++nt),tt++;if(Z[tt]!==0&&(V[F+D]=4,++nt),nt>1e3)return null;let pt=new Int32Array([0,U,-1,0,-U,0,0,0,1]),dt=new Path2D;for($=0;nt&&$<=S;$++){let lt=$*U,wt=lt+M;for(;lt<wt&&!V[lt];)lt++;if(lt===wt)continue;dt.moveTo(lt%U,$);let Tt=lt,xt=V[lt];do{let It=pt[xt];do lt+=It;while(!V[lt]);let Lt=V[lt];Lt!==5&&Lt!==10?(xt=Lt,V[lt]=0):(xt=Lt&51*xt>>4,V[lt]&=xt>>2|xt<<2),dt.lineTo(lt%U,lt/U|0),V[lt]||--nt}while(Tt!==lt);--$}return Z=null,V=null,function(lt){lt.save(),lt.scale(1/M,-1/S),lt.translate(0,-S),lt.fill(dt),lt.beginPath(),lt.restore()}})(x)),p.compiled)){p.compiled(R);return}let v=this._createMaskCanvas(x),_=v.canvas;R.save(),R.setTransform(1,0,0,1,0,0),R.drawImage(_,v.offsetX,v.offsetY),R.restore(),this.compose()}paintImageMaskXObjectRepeat(x,T,R=0,p=0,v,_){if(!this.contentVisible)return;x=this.getObject(x.data,x);let k=this.ctx;k.save();let O=(0,n.getCurrentTransform)(k);k.transform(T,R,p,v,0,0);let M=this._createMaskCanvas(x);k.setTransform(1,0,0,1,M.offsetX-O[4],M.offsetY-O[5]);for(let S=0,L=_.length;S<L;S+=2){let U=i.Util.transform(O,[T,R,p,v,_[S],_[S+1]]),[$,D]=i.Util.applyTransform([0,0],U);k.drawImage(M.canvas,$,D)}k.restore(),this.compose()}paintImageMaskXObjectGroup(x){if(!this.contentVisible)return;let T=this.ctx,R=this.current.fillColor,p=this.current.patternFill;for(let v of x){let{data:_,width:k,height:O,transform:M}=v,S=this.cachedCanvases.getCanvas("maskCanvas",k,O),L=S.context;L.save(),z(L,this.getObject(_,v)),L.globalCompositeOperation="source-in",L.fillStyle=p?R.getPattern(L,this,(0,n.getCurrentTransformInverse)(T),o):R,L.fillRect(0,0,k,O),L.restore(),T.save(),T.transform(...M),T.scale(1,-1),E(T,S.canvas,0,0,k,O,0,-1,1,1),T.restore()}this.compose()}paintImageXObject(x){if(!this.contentVisible)return;let T=this.getObject(x);T?this.paintInlineImageXObject(T):(0,i.warn)("Dependent image isn't ready yet")}paintImageXObjectRepeat(x,T,R,p){if(!this.contentVisible)return;let v=this.getObject(x);if(!v){(0,i.warn)("Dependent image isn't ready yet");return}let _=v.width,k=v.height,O=[];for(let M=0,S=p.length;M<S;M+=2)O.push({transform:[T,0,0,R,p[M],p[M+1]],x:0,y:0,w:_,h:k});this.paintInlineImageXObjectGroup(v,O)}applyTransferMapsToCanvas(x){return this.current.transferMaps!=="none"&&(x.filter=this.current.transferMaps,x.drawImage(x.canvas,0,0),x.filter="none"),x.canvas}applyTransferMapsToBitmap(x){if(this.current.transferMaps==="none")return x.bitmap;let{bitmap:T,width:R,height:p}=x,v=this.cachedCanvases.getCanvas("inlineImage",R,p),_=v.context;return _.filter=this.current.transferMaps,_.drawImage(T,0,0),_.filter="none",v.canvas}paintInlineImageXObject(x){if(!this.contentVisible)return;let T=x.width,R=x.height,p=this.ctx;if(this.save(),!i.isNodeJS){let{filter:k}=p;k!=="none"&&k!==""&&(p.filter="none")}p.scale(1/T,-1/R);let v;if(x.bitmap)v=this.applyTransferMapsToBitmap(x);else if(typeof HTMLElement=="function"&&x instanceof HTMLElement||!x.data)v=x;else{let k=this.cachedCanvases.getCanvas("inlineImage",T,R).context;N(k,x),v=this.applyTransferMapsToCanvas(k)}let _=this._scaleImage(v,(0,n.getCurrentTransformInverse)(p));p.imageSmoothingEnabled=G((0,n.getCurrentTransform)(p),x.interpolate),E(p,_.img,0,0,_.paintWidth,_.paintHeight,0,-R,T,R),this.compose(),this.restore()}paintInlineImageXObjectGroup(x,T){if(!this.contentVisible)return;let R=this.ctx,p;if(x.bitmap)p=x.bitmap;else{let v=x.width,_=x.height,k=this.cachedCanvases.getCanvas("inlineImage",v,_).context;N(k,x),p=this.applyTransferMapsToCanvas(k)}for(let v of T)R.save(),R.transform(...v.transform),R.scale(1,-1),E(R,p,v.x,v.y,v.w,v.h,0,-1,1,1),R.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(x){}markPointProps(x,T){}beginMarkedContent(x){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(x,T){x==="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(x){let T=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(x);let R=this.ctx;this.pendingClip&&(T||(this.pendingClip===ct?R.clip("evenodd"):R.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),R.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let x=(0,n.getCurrentTransform)(this.ctx);if(x[1]===0&&x[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(x[0]),Math.abs(x[3]));else{let T=Math.abs(x[0]*x[3]-x[2]*x[1]),R=Math.hypot(x[0],x[2]),p=Math.hypot(x[1],x[3]);this._cachedGetSinglePixelWidth=Math.max(R,p)/T}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:x}=this.current,{a:T,b:R,c:p,d:v}=this.ctx.getTransform(),_,k;if(R===0&&p===0){let O=Math.abs(T),M=Math.abs(v);if(O===M)if(x===0)_=k=1/O;else{let S=O*x;_=k=S<1?1/S:1}else if(x===0)_=1/O,k=1/M;else{let S=O*x,L=M*x;_=S<1?1/S:1,k=L<1?1/L:1}}else{let O=Math.abs(T*v-R*p),M=Math.hypot(T,R),S=Math.hypot(p,v);if(x===0)_=S/O,k=M/O;else{let L=x*O;_=S>L?S/L:1,k=M>L?M/L:1}}this._cachedScaleForStroking[0]=_,this._cachedScaleForStroking[1]=k}return this._cachedScaleForStroking}rescaleAndStroke(x){let{ctx:T}=this,{lineWidth:R}=this.current,[p,v]=this.getScaleForStroking();if(T.lineWidth=R||1,p===1&&v===1){T.stroke();return}let _=T.getLineDash();if(x&&T.save(),T.scale(p,v),_.length>0){let k=Math.max(p,v);T.setLineDash(_.map((O=>O/k))),T.lineDashOffset/=k}T.stroke(),x&&T.restore()}isContentVisible(){for(let x=this.markedContentStack.length-1;x>=0;x--)if(!this.markedContentStack[x].visible)return!1;return!0}}for(let W in i.OPS)st.prototype[W]!==void 0&&(st.prototype[i.OPS[W]]=st.prototype[W])},419:(s,t,e)=>{e.d(t,{DOMCMapReaderFactory:()=>d,DOMCanvasFactory:()=>g,DOMFilterFactory:()=>h,DOMSVGFactory:()=>f,DOMStandardFontDataFactory:()=>a,PDFDateString:()=>I,PageViewport:()=>A,PixelsPerInch:()=>l,RenderingCancelledException:()=>C,StatTimer:()=>b,fetchData:()=>m,getColorValues:()=>H,getCurrentTransform:()=>X,getCurrentTransformInverse:()=>it,getFilenameFromUrl:()=>r,getPdfFilenameFromUrl:()=>c,getRGB:()=>z,getXfaPageViewport:()=>N,isDataScheme:()=>u,isPdfFile:()=>y,isValidFetchUrl:()=>w,noContextMenu:()=>P,setLayerDimensions:()=>at});var i=e(583),n=e(292);let o="http://www.w3.org/2000/svg";class l{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}class h extends i.BaseFilterFactory{#t;#e;#i;#n;#r;#s=0;constructor({docId:j,ownerDocument:G=globalThis.document}={}){super(),this.#i=j,this.#n=G}get#o(){return this.#t||=new Map}get#c(){return this.#r||=new Map}get#a(){if(!this.#e){let j=this.#n.createElement("div"),{style:G}=j;G.visibility="hidden",G.contain="strict",G.width=G.height=0,G.position="absolute",G.top=G.left=0,G.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 G,Y,et,rt,ct=this.#o.get(j);if(ct)return ct;if(j.length===1){let T=j[0],R=new Array(256);for(let p=0;p<256;p++)R[p]=T[p]/255;rt=G=Y=et=R.join(",")}else{let[T,R,p]=j,v=new Array(256),_=new Array(256),k=new Array(256);for(let O=0;O<256;O++)v[O]=T[O]/255,_[O]=R[O]/255,k[O]=p[O]/255;G=v.join(","),Y=_.join(","),et=k.join(","),rt=`${G}${Y}${et}`}if(ct=this.#o.get(rt),ct)return this.#o.set(j,ct),ct;let st=`g_${this.#i}_transfer_map_${this.#s++}`,W=`url(#${st})`;this.#o.set(j,W),this.#o.set(rt,W);let x=this.#p(st);return this.#l(G,Y,et,x),W}addHCMFilter(j,G){let Y=`${j}-${G}`,et="base",rt=this.#c.get(et);if(rt?.key===Y||(rt?(rt.filter?.remove(),rt.key=Y,rt.url="none",rt.filter=null):(rt={key:Y,url:"none",filter:null},this.#c.set(et,rt)),!j||!G))return rt.url;let ct=this.#f(j);j=n.Util.makeHexColor(...ct);let st=this.#f(G);if(G=n.Util.makeHexColor(...st),this.#a.style.color="",j==="#000000"&&G==="#ffffff"||j===G)return rt.url;let W=new Array(256);for(let v=0;v<=255;v++){let _=v/255;W[v]=_<=.03928?_/12.92:((_+.055)/1.055)**2.4}let x=W.join(","),T=`g_${this.#i}_hcm_filter`,R=rt.filter=this.#p(T);this.#l(x,x,x,R),this.#d(R);let p=(v,_)=>{let k=ct[v]/255,O=st[v]/255,M=new Array(_+1);for(let S=0;S<=_;S++)M[S]=k+S/_*(O-k);return M.join(",")};return this.#l(p(0,5),p(1,5),p(2,5),R),rt.url=`url(#${T})`,rt.url}addHighlightHCMFilter(j,G,Y,et,rt){let ct=`${G}-${Y}-${et}-${rt}`,st=this.#c.get(j);if(st?.key===ct||(st?(st.filter?.remove(),st.key=ct,st.url="none",st.filter=null):(st={key:ct,url:"none",filter:null},this.#c.set(j,st)),!G||!Y))return st.url;let[W,x]=[G,Y].map(this.#f.bind(this)),T=Math.round(.2126*W[0]+.7152*W[1]+.0722*W[2]),R=Math.round(.2126*x[0]+.7152*x[1]+.0722*x[2]),[p,v]=[et,rt].map(this.#f.bind(this));R<T&&([T,R,p,v]=[R,T,v,p]),this.#a.style.color="";let _=(M,S,L)=>{let U=new Array(256),$=(R-T)/L,D=M/255,F=(S-M)/(255*L),V=0;for(let Q=0;Q<=L;Q++){let Z=Math.round(T+Q*$),tt=D+Q*F;for(let nt=V;nt<=Z;nt++)U[nt]=tt;V=Z+1}for(let Q=V;Q<256;Q++)U[Q]=U[V-1];return U.join(",")},k=`g_${this.#i}_hcm_${j}_filter`,O=st.filter=this.#p(k);return this.#d(O),this.#l(_(p[0],v[0],5),_(p[1],v[1],5),_(p[2],v[2],5),O),st.url=`url(#${k})`,st.url}destroy(j=!1){(!j||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)}#d(j){let G=this.#n.createElementNS(o,"feColorMatrix");G.setAttribute("type","matrix"),G.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(G)}#p(j){let G=this.#n.createElementNS(o,"filter");return G.setAttribute("color-interpolation-filters","sRGB"),G.setAttribute("id",j),this.#a.append(G),G}#u(j,G,Y){let et=this.#n.createElementNS(o,G);et.setAttribute("type","discrete"),et.setAttribute("tableValues",Y),j.append(et)}#l(j,G,Y,et){let rt=this.#n.createElementNS(o,"feComponentTransfer");et.append(rt),this.#u(rt,"feFuncR",j),this.#u(rt,"feFuncG",G),this.#u(rt,"feFuncB",Y)}#f(j){return this.#a.style.color=j,z(getComputedStyle(this.#a).getPropertyValue("color"))}}class g extends i.BaseCanvasFactory{constructor({ownerDocument:j=globalThis.document}={}){super(),this._document=j}_createCanvas(j,G){let Y=this._document.createElement("canvas");return Y.width=j,Y.height=G,Y}}async function m(K,j="text"){if(w(K,document.baseURI)){let G=await fetch(K);if(!G.ok)throw new Error(G.statusText);switch(j){case"arraybuffer":return G.arrayBuffer();case"blob":return G.blob();case"json":return G.json()}return G.text()}return new Promise(((G,Y)=>{let et=new XMLHttpRequest;et.open("GET",K,!0),et.responseType=j,et.onreadystatechange=()=>{if(et.readyState===XMLHttpRequest.DONE)if(et.status!==200&&et.status!==0)Y(new Error(et.statusText));else{switch(j){case"arraybuffer":case"blob":case"json":G(et.response);return}G(et.responseText)}},et.send(null)}))}class d extends i.BaseCMapReaderFactory{_fetchData(j,G){return m(j,this.isCompressed?"arraybuffer":"text").then((Y=>({cMapData:Y instanceof ArrayBuffer?new Uint8Array(Y):(0,n.stringToBytes)(Y),compressionType:G})))}}class a extends i.BaseStandardFontDataFactory{_fetchData(j){return m(j,"arraybuffer").then((G=>new Uint8Array(G)))}}class f extends i.BaseSVGFactory{_createSVG(j){return document.createElementNS(o,j)}}class A{constructor({viewBox:j,scale:G,rotation:Y,offsetX:et=0,offsetY:rt=0,dontFlip:ct=!1}){this.viewBox=j,this.scale=G,this.rotation=Y,this.offsetX=et,this.offsetY=rt;let st=(j[2]+j[0])/2,W=(j[3]+j[1])/2,x,T,R,p,v,_,k,O;switch((Y%=360)<0&&(Y+=360),Y){case 180:x=-1,T=0,R=0,p=1;break;case 90:x=0,T=1,R=1,p=0;break;case 270:x=0,T=-1,R=-1,p=0;break;case 0:x=1,T=0,R=0,p=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}ct&&(R=-R,p=-p),x===0?(v=Math.abs(W-j[1])*G+et,_=Math.abs(st-j[0])*G+rt,k=(j[3]-j[1])*G,O=(j[2]-j[0])*G):(v=Math.abs(st-j[0])*G+et,_=Math.abs(W-j[1])*G+rt,k=(j[2]-j[0])*G,O=(j[3]-j[1])*G),this.transform=[x*G,T*G,R*G,p*G,v-x*G*st-R*G*W,_-T*G*st-p*G*W],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:G=this.rotation,offsetX:Y=this.offsetX,offsetY:et=this.offsetY,dontFlip:rt=!1}={}){return new A({viewBox:this.viewBox.slice(),scale:j,rotation:G,offsetX:Y,offsetY:et,dontFlip:rt})}convertToViewportPoint(j,G){return n.Util.applyTransform([j,G],this.transform)}convertToViewportRectangle(j){let G=n.Util.applyTransform([j[0],j[1]],this.transform),Y=n.Util.applyTransform([j[2],j[3]],this.transform);return[G[0],G[1],Y[0],Y[1]]}convertToPdfPoint(j,G){return n.Util.applyInverseTransform([j,G],this.transform)}}class C extends n.BaseException{constructor(j,G=0){super(j,"RenderingCancelledException"),this.extraDelay=G}}function u(K){let j=K.length,G=0;for(;G<j&&K[G].trim()==="";)G++;return K.substring(G,G+5).toLowerCase()==="data:"}function y(K){return typeof K=="string"&&/\.pdf$/i.test(K)}function r(K,j=!1){return j||([K]=K.split(/[#?]/,1)),K.substring(K.lastIndexOf("/")+1)}function c(K,j="document.pdf"){if(typeof K!="string")return j;if(u(K))return(0,n.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),j;let G=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,Y=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(K),et=G.exec(Y[1])||G.exec(Y[2])||G.exec(Y[3]);if(et&&(et=et[0],et.includes("%")))try{et=G.exec(decodeURIComponent(et))[0]}catch{}return et||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=[],G=0;for(let{name:Y}of this.times)G=Math.max(Y.length,G);for(let{name:Y,start:et,end:rt}of this.times)j.push(`${Y.padEnd(G)} ${rt-et}ms
|
|
5
|
-
`);return j.join("")}}function w(K,j){try{let{protocol:G}=j?new URL(K,j):new URL(K);return G==="http:"||G==="https:"}catch{return!1}}function P(K){K.preventDefault()}let E;class I{static toDateObject(j){if(!j||typeof j!="string")return null;E||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");let G=E.exec(j);if(!G)return null;let Y=parseInt(G[1],10),et=parseInt(G[2],10);et=et>=1&&et<=12?et-1:0;let rt=parseInt(G[3],10);rt=rt>=1&&rt<=31?rt:1;let ct=parseInt(G[4],10);ct=ct>=0&&ct<=23?ct:0;let st=parseInt(G[5],10);st=st>=0&&st<=59?st:0;let W=parseInt(G[6],10);W=W>=0&&W<=59?W:0;let x=G[7]||"Z",T=parseInt(G[8],10);T=T>=0&&T<=23?T:0;let R=parseInt(G[9],10)||0;return R=R>=0&&R<=59?R:0,x==="-"?(ct+=T,st+=R):x==="+"&&(ct-=T,st-=R),new Date(Date.UTC(Y,et,rt,ct,st,W))}}function N(K,{scale:j=1,rotation:G=0}){let{width:Y,height:et}=K.attributes.style,rt=[0,0,parseInt(Y),parseInt(et)];return new A({viewBox:rt,scale:j,rotation:G})}function z(K){if(K.startsWith("#")){let j=parseInt(K.slice(1),16);return[(16711680&j)>>16,(65280&j)>>8,255&j]}return K.startsWith("rgb(")?K.slice(4,-1).split(",").map((j=>parseInt(j))):K.startsWith("rgba(")?K.slice(5,-1).split(",").map((j=>parseInt(j))).slice(0,3):((0,n.warn)(`Not a valid color format: "${K}"`),[0,0,0])}function H(K){let j=document.createElement("span");j.style.visibility="hidden",document.body.append(j);for(let G of K.keys()){j.style.color=G;let Y=window.getComputedStyle(j).color;K.set(G,z(Y))}j.remove()}function X(K){let{a:j,b:G,c:Y,d:et,e:rt,f:ct}=K.getTransform();return[j,G,Y,et,rt,ct]}function it(K){let{a:j,b:G,c:Y,d:et,e:rt,f:ct}=K.getTransform().invertSelf();return[j,G,Y,et,rt,ct]}function at(K,j,G=!1,Y=!0){if(j instanceof A){let{pageWidth:et,pageHeight:rt}=j.rawDims,{style:ct}=K,st=n.FeatureTest.isCSSRoundSupported,W=`var(--scale-factor) * ${et}px`,x=`var(--scale-factor) * ${rt}px`,T=st?`round(${W}, 1px)`:`calc(${W})`,R=st?`round(${x}, 1px)`:`calc(${x})`;G&&j.rotation%180!=0?(ct.width=R,ct.height=T):(ct.width=T,ct.height=R)}Y&&K.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:h}){this.pageIndex=h}setParent(h){if(this.#t){if(this.#t!==h){if(this.#i.size>0)for(let g of this.#i.values())g.remove(),h.append(g);this.#t=h}}else this.#t=h}static get _svgFactory(){return(0,n.shadow)(this,"_svgFactory",new i.DOMSVGFactory)}static#r(h,{x:g=0,y:m=0,width:d=1,height:a=1}={}){let{style:f}=h;f.top=100*m+"%",f.left=100*g+"%",f.width=100*d+"%",f.height=100*a+"%"}#s(h){let g=o._svgFactory.create(1,1,!0);return this.#t.append(g),g.setAttribute("aria-hidden",!0),o.#r(g,h),g}#o(h,g){let m=o._svgFactory.createElement("clipPath");h.append(m);let d=`clip_${g}`;m.setAttribute("id",d),m.setAttribute("clipPathUnits","objectBoundingBox");let a=o._svgFactory.createElement("use");return m.append(a),a.setAttribute("href",`#${g}`),a.classList.add("clip"),d}highlight(h,g,m,d=!1){let a=this.#e++,f=this.#s(h.box);f.classList.add("highlight"),h.free&&f.classList.add("free");let A=o._svgFactory.createElement("defs");f.append(A);let C=o._svgFactory.createElement("path");A.append(C);let u=`path_p${this.pageIndex}_${a}`;C.setAttribute("id",u),C.setAttribute("d",h.toSVGPath()),d&&this.#n.set(a,C);let y=this.#o(A,u),r=o._svgFactory.createElement("use");return f.append(r),f.setAttribute("fill",g),f.setAttribute("fill-opacity",m),r.setAttribute("href",`#${u}`),this.#i.set(a,f),{id:a,clipPathId:`url(#${y})`}}highlightOutline(h){let g=this.#e++,m=this.#s(h.box);m.classList.add("highlightOutline");let d=o._svgFactory.createElement("defs");m.append(d);let a=o._svgFactory.createElement("path");d.append(a);let f=`path_p${this.pageIndex}_${g}`;a.setAttribute("id",f),a.setAttribute("d",h.toSVGPath()),a.setAttribute("vector-effect","non-scaling-stroke");let A;if(h.free){m.classList.add("free");let y=o._svgFactory.createElement("mask");d.append(y),A=`mask_p${this.pageIndex}_${g}`,y.setAttribute("id",A),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 c=o._svgFactory.createElement("use");y.append(c),c.setAttribute("href",`#${f}`),c.setAttribute("stroke","none"),c.setAttribute("fill","black"),c.setAttribute("fill-rule","nonzero"),c.classList.add("mask")}let C=o._svgFactory.createElement("use");m.append(C),C.setAttribute("href",`#${f}`),A&&C.setAttribute("mask",`url(#${A})`);let u=C.cloneNode();return m.append(u),C.classList.add("mainOutline"),u.classList.add("secondaryOutline"),this.#i.set(g,m),g}finalizeLine(h,g){let m=this.#n.get(h);this.#n.delete(h),this.updateBox(h,g.box),m.setAttribute("d",g.toSVGPath())}updateLine(h,g){this.#i.get(h).firstChild.firstChild.setAttribute("d",g.toSVGPath())}removeFreeHighlight(h){this.remove(h),this.#n.delete(h)}updatePath(h,g){this.#n.get(h).setAttribute("d",g.toSVGPath())}updateBox(h,g){o.#r(this.#i.get(h),g)}show(h,g){this.#i.get(h).classList.toggle("hidden",!g)}rotate(h,g){this.#i.get(h).setAttribute("data-main-rotation",g)}changeColor(h,g){this.#i.get(h).setAttribute("fill",g)}changeOpacity(h,g){this.#i.get(h).setAttribute("fill-opacity",g)}addClass(h,g){this.#i.get(h).classList.add(g)}removeClass(h,g){this.#i.get(h).classList.remove(g)}remove(h){this.#t!==null&&(this.#i.get(h).remove(),this.#i.delete(h))}destroy(){this.#t=null;for(let h of this.#i.values())h.remove();this.#i.clear()}}},731:(s,t,e)=>{e.d(t,{AnnotationEditorLayer:()=>u});var i=e(292),n=e(310),o=e(830),l=e(976);let h=/\r\n?|\n/g;class g 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;#o="";#c=`${this.id}-editor`;#a;#d=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let r=g.prototype,c=P=>P.isEmpty(),b=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"],r.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],r.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],r._translateEmpty,{args:[-b,0],checker:c}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],r._translateEmpty,{args:[-w,0],checker:c}],[["ArrowRight","mac+ArrowRight"],r._translateEmpty,{args:[b,0],checker:c}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],r._translateEmpty,{args:[w,0],checker:c}],[["ArrowUp","mac+ArrowUp"],r._translateEmpty,{args:[0,-b],checker:c}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],r._translateEmpty,{args:[0,-w],checker:c}],[["ArrowDown","mac+ArrowDown"],r._translateEmpty,{args:[0,b],checker:c}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],r._translateEmpty,{args:[0,w],checker:c}]]))}static _type="freetext";static _editorType=i.AnnotationEditorType.FREETEXT;constructor(r){super({...r,name:"freeTextEditor"}),this.#s=r.color||g._defaultColor||n.AnnotationEditor._defaultLineColor,this.#a=r.fontSize||g._defaultFontSize}static initialize(r,c){n.AnnotationEditor.initialize(r,c,{strings:["pdfjs-free-text-default-content"]});let b=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(b.getPropertyValue("--freetext-padding"))}static updateDefaultParams(r,c){switch(r){case i.AnnotationEditorParamsType.FREETEXT_SIZE:g._defaultFontSize=c;break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:g._defaultColor=c}}updateParams(r,c){switch(r){case i.AnnotationEditorParamsType.FREETEXT_SIZE:this.#p(c);break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:this.#u(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,g._defaultFontSize],[i.AnnotationEditorParamsType.FREETEXT_COLOR,g._defaultColor||n.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,this.#a],[i.AnnotationEditorParamsType.FREETEXT_COLOR,this.#s]]}#p(r){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()},b=this.#a;this.addCommands({cmd:c.bind(this,r),undo:c.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#u(r){let c=w=>{this.#s=this.editorDiv.style.color=w},b=this.#s;this.addCommands({cmd:c.bind(this,r),undo:c.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(r,c){this._uiManager.translateSelectedEditors(r,c,!0)}getInitialTranslation(){let r=this.parentScale;return[-g._internalPadding*r,-(g._internalPadding+this.#a)*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.#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(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()}#l(){let r=[];this.editorDiv.normalize();for(let c of this.editorDiv.childNodes)r.push(g.#g(c));return r.join(`
|
|
6
|
-
|
|
7
|
-
`);if(!w)return;let P=window.getSelection();if(!P.rangeCount)return;this.editorDiv.normalize(),P.deleteFromDocument();let E=P.getRangeAt(0);if(!w.includes(`
|
|
8
|
-
`)){E.insertNode(document.createTextNode(w)),this.editorDiv.normalize(),P.collapseToStart();return}let{startContainer:I,startOffset:N}=E,z=[],H=[];if(I.nodeType===Node.TEXT_NODE){let at=I.parentElement;if(H.push(I.nodeValue.slice(N).replaceAll(h,"")),at!==this.editorDiv){let K=z;for(let j of this.editorDiv.childNodes)j!==at?K.push(g.#g(j)):K=H}z.push(I.nodeValue.slice(0,N).replaceAll(h,""))}else if(I===this.editorDiv){let at=z,K=0;for(let j of this.editorDiv.childNodes)K++===N&&(at=H),at.push(g.#g(j))}this.#o=`${z.join(`
|
|
9
|
-
`)}${w}${H.join(`
|
|
10
|
-
`)}`,this.#h();let X=new Range,it=z.reduce(((at,K)=>at+K.length),0);for(let{firstChild:at}of this.editorDiv.childNodes)if(at.nodeType===Node.TEXT_NODE){let K=at.nodeValue.length;if(it<=K){X.setStart(at,it),X.setEnd(at,it);break}it-=K}P.removeAllRanges(),P.addRange(X)}#h(){if(this.editorDiv.replaceChildren(),this.#o)for(let r of this.#o.split(`
|
|
11
|
-
`)){let c=document.createElement("div");c.append(r?document.createTextNode(r):document.createElement("br")),this.editorDiv.append(c)}}#b(){return this.#o.replaceAll("\xA0"," ")}static#m(r){return r.replaceAll(" ","\xA0")}get contentDiv(){return this.editorDiv}static deserialize(r,c,b){let w=null;if(r instanceof l.FreeTextAnnotationElement){let{data:{defaultAppearanceData:{fontSize:E,fontColor:I},rect:N,rotation:z,id:H},textContent:X,textPosition:it,parent:{page:{pageNumber:at}}}=r;if(!X||X.length===0)return null;w=r={annotationType:i.AnnotationEditorType.FREETEXT,color:Array.from(I),fontSize:E,value:X.join(`
|
|
12
|
-
`),position:it,pageIndex:at-1,rect:N,rotation:z,id:H,deleted:!1}}let P=super.deserialize(r,c,b);return P.#a=r.fontSize,P.#s=i.Util.makeHexColor(...r.color),P.#o=g.#m(r.value),P.annotationElementId=r.id||null,P.#d=w,P}serialize(r=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};let c=g._internalPadding*this.parentScale,b=this.getRect(c,c),w=n.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#s),P={annotationType:i.AnnotationEditorType.FREETEXT,color:w,fontSize:this.#a,value:this.#b(),pageIndex:this.pageIndex,rect:b,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return r?P:this.annotationElementId&&!this.#y(P)?null:(P.id=this.annotationElementId,P)}#y(r){let{value:c,fontSize:b,color:w,pageIndex:P}=this.#d;return this._hasBeenMoved||r.value!==c||r.fontSize!==b||r.color.some(((E,I)=>E!==w[I]))||r.pageIndex!==P}}var m=e(61),d=e(259),a=e(419);class f extends n.AnnotationEditor{#t=null;#e=0;#i;#n=null;#r=null;#s=null;#o=null;#c=0;#a=null;#d=null;#p=null;#u=!1;#l=this.#_.bind(this);#f=null;#g;#h=null;#b="";#m;#y="";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.#y=r.methodOfCreation||"",this.#b=r.text||"",this._isDraggable=!1,r.highlightId>-1?(this.#u=!0,this.#C(r),this.#E()):(this.#t=r.anchorNode,this.#e=r.anchorOffset,this.#o=r.focusNode,this.#c=r.focusOffset,this.#S(),this.#E(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#u?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#m,methodOfCreation:this.#y}}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.#d=r.getOutlines(),{x:this.x,y:this.y,width:this.width,height:this.height}=this.#d.box;let c=new m.Outliner(this.#i,.0025,.001,this._uiManager.direction==="ltr");this.#s=c.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:c,clipPathId:b}){if(this.#d=r,this.#s=r.getNewOutline(this.#m/2+1.5,.0025),c>=0)this.#p=c,this.#n=b,this.parent.drawLayer.finalizeLine(c,r),this.#h=this.parent.drawLayer.highlightOutline(this.#s);else if(this.parent){let z=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#p,r),this.parent.drawLayer.updateBox(this.#p,f.#A(this.#d.box,(z-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#h,this.#s),this.parent.drawLayer.updateBox(this.#h,f.#A(this.#s.box,z))}let{x:w,y:P,width:E,height:I}=r.box;switch(this.rotation){case 0:this.x=w,this.y=P,this.width=E,this.height=I;break;case 90:{let[z,H]=this.parentDimensions;this.x=P,this.y=1-w,this.width=E*H/z,this.height=I*z/H;break}case 180:this.x=1-w,this.y=1-P,this.width=E,this.height=I;break;case 270:{let[z,H]=this.parentDimensions;this.x=1-P,this.y=w,this.width=E*H/z,this.height=I*z/H;break}}let{lastPoint:N}=this.#s.box;this.#f=[(N[0]-w)/E,(N[1]-P)/I]}static initialize(r,c){n.AnnotationEditor.initialize(r,c),f._defaultColor||=c.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(r,c){switch(r){case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:f._defaultColor=c;break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:f._defaultThickness=c}}translateInPage(r,c){}get toolbarPosition(){return this.#f}updateParams(r,c){switch(r){case i.AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#I(c);break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#w(c)}}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.#u]]}#I(r){let c=w=>{this.color=w,this.parent?.drawLayer.changeColor(this.#p,w),this.#r?.updateColor(w)},b=this.color;this.addCommands({cmd:c.bind(this,r),undo:c.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 c=this.#m,b=w=>{this.#m=w,this.#x(w)};this.addCommands({cmd:b.bind(this,r),undo:b.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:r},!0)}async addEditToolbar(){let r=await super.addEditToolbar();return r?(this._uiManager.highlightColors&&(this.#r=new d.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.#k())}getBaseTranslation(){return[0,0]}getRect(r,c){return super.getRect(r,c,this.#k())}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 c=!1;this.parent&&!r?this.#v():r&&(this.#E(r),c=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(r),this.show(this._isVisible),c&&this.select()}#x(r){if(!this.#u)return;this.#C({highlightOutlines:this.#d.getNewOutline(r/2)}),this.fixAndSetPosition();let[c,b]=this.parentDimensions;this.setDims(this.width*c,this.height*b)}#v(){this.#p!==null&&this.parent&&(this.parent.drawLayer.remove(this.#p),this.#p=null,this.parent.drawLayer.remove(this.#h),this.#h=null)}#E(r=this.parent){this.#p===null&&({id:this.#p,clipPathId:this.#n}=r.drawLayer.highlight(this.#d,this.color,this.#g),this.#h=r.drawLayer.highlightOutline(this.#s),this.#a&&(this.#a.style.clipPath=this.#n))}static#A({x:r,y:c,width:b,height:w},P){switch(P){case 90:return{x:1-c-w,y:r,width:w,height:b};case 180:return{x:1-r-b,y:1-c-w,width:b,height:w};case 270:return{x:c,y:1-r-b,width:w,height:b}}return{x:r,y:c,width:b,height:w}}rotate(r){let{drawLayer:c}=this.parent,b;this.#u?(r=(r-this.rotation+360)%360,b=f.#A(this.#d.box,r)):b=f.#A(this,r),c.rotate(this.#p,r),c.rotate(this.#h,r),c.updateBox(this.#p,b),c.updateBox(this.#h,f.#A(this.#s.box,r))}render(){if(this.div)return this.div;let r=super.render();this.#b&&(r.setAttribute("aria-label",this.#b),r.setAttribute("role","mark")),this.#u?r.classList.add("free"):this.div.addEventListener("keydown",this.#l);let c=this.#a=document.createElement("div");r.append(c),c.setAttribute("aria-hidden","true"),c.className="internal",c.style.clipPath=this.#n;let[b,w]=this.parentDimensions;return this.setDims(this.width*b,this.height*w),(0,o.bindEvents)(this,this.#a,["pointerover","pointerleave"]),this.enableEditing(),r}pointerover(){this.parent.drawLayer.addClass(this.#h,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#h,"hovered")}#_(r){f._keyboardManager.exec(this,r)}_moveCaret(r){switch(this.parent.unselect(this),r){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1)}}#T(r){if(!this.#t)return;let c=window.getSelection();r?c.setPosition(this.#t,this.#e):c.setPosition(this.#o,this.#c)}select(){super.select(),this.#h&&(this.parent?.drawLayer.removeClass(this.#h,"hovered"),this.parent?.drawLayer.addClass(this.#h,"selected"))}unselect(){super.unselect(),this.#h&&(this.parent?.drawLayer.removeClass(this.#h,"selected"),this.#u||this.#T(!1))}get _mustFixPosition(){return!this.#u}show(r=this._isVisible){super.show(r),this.parent&&(this.parent.drawLayer.show(this.#p,r),this.parent.drawLayer.show(this.#h,r))}#k(){return this.#u?this.rotation:0}#M(){if(this.#u)return null;let[r,c]=this.pageDimensions,b=this.#i,w=new Array(8*b.length),P=0;for(let{x:E,y:I,width:N,height:z}of b){let H=E*r,X=(1-I-z)*c;w[P]=w[P+4]=H,w[P+1]=w[P+3]=X,w[P+2]=w[P+6]=H+N*r,w[P+5]=w[P+7]=X+z*c,P+=8}return w}#P(r){return this.#d.serialize(r,this.#k())}static startHighlighting(r,c,{target:b,x:w,y:P}){let{x:E,y:I,width:N,height:z}=b.getBoundingClientRect(),H=K=>{this.#L(r,K)},X={capture:!0,passive:!1},it=K=>{K.preventDefault(),K.stopPropagation()},at=K=>{b.removeEventListener("pointermove",H),window.removeEventListener("blur",at),window.removeEventListener("pointerup",at),window.removeEventListener("pointerdown",it,X),window.removeEventListener("contextmenu",a.noContextMenu),this.#R(r,K)};window.addEventListener("blur",at),window.addEventListener("pointerup",at),window.addEventListener("pointerdown",it,X),window.addEventListener("contextmenu",a.noContextMenu),b.addEventListener("pointermove",H),this._freeHighlight=new m.FreeOutliner({x:w,y:P},[E,I,N,z],r.scale,this._defaultThickness/2,c,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=r.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static#L(r,c){this._freeHighlight.add(c)&&r.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#R(r,c){this._freeHighlight.isEmpty()?r.drawLayer.removeFreeHighlight(this._freeHighlightId):r.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(r,c,b){let w=super.deserialize(r,c,b),{rect:[P,E,I,N],color:z,quadPoints:H}=r;w.color=i.Util.makeHexColor(...z),w.#g=r.opacity;let[X,it]=w.pageDimensions;w.width=(I-P)/X,w.height=(N-E)/it;let at=w.#i=[];for(let K=0;K<H.length;K+=8)at.push({x:(H[4]-I)/X,y:(N-(1-H[K+5]))/it,width:(H[K+2]-H[K])/X,height:(H[K+5]-H[K+1])/it});return w.#S(),w}serialize(r=!1){if(this.isEmpty()||r)return null;let c=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.#P(c),pageIndex:this.pageIndex,rect:c,rotation:this.#k(),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}}class A 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);#o=null;#c=new Path2D;#a=!1;#d=!1;#p=!1;#u=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(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,c){n.AnnotationEditor.initialize(r,c)}static updateDefaultParams(r,c){switch(r){case i.AnnotationEditorParamsType.INK_THICKNESS:A._defaultThickness=c;break;case i.AnnotationEditorParamsType.INK_COLOR:A._defaultColor=c;break;case i.AnnotationEditorParamsType.INK_OPACITY:A._defaultOpacity=c/100}}updateParams(r,c){switch(r){case i.AnnotationEditorParamsType.INK_THICKNESS:this.#h(c);break;case i.AnnotationEditorParamsType.INK_COLOR:this.#b(c);break;case i.AnnotationEditorParamsType.INK_OPACITY:this.#m(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,A._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,A._defaultColor||n.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*A._defaultOpacity)]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,this.thickness||A._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,this.color||A._defaultColor||n.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*(this.opacity??A._defaultOpacity))]]}#h(r){let c=w=>{this.thickness=w,this.#N()},b=this.thickness;this.addCommands({cmd:c.bind(this,r),undo:c.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#b(r){let c=w=>{this.color=w,this.#_()},b=this.color;this.addCommands({cmd:c.bind(this,r),undo:c.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 c=w=>{this.opacity=w,this.#_()};r/=100;let b=this.opacity;this.addCommands({cmd:c.bind(this,r),undo:c.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.#k(),this.#M()),this.isAttachedToDOM||(this.parent.add(this),this.#P()),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.#u.disconnect(),this.#u=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,c]=this.parentDimensions,b=this.width*r,w=this.height*c;this.setDimensions(b,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}#y(){let{parentRotation:r,parentDimensions:[c,b]}=this;switch(r){case 90:return[0,b,b,c];case 180:return[c,b,c,b];case 270:return[c,0,b,c];default:return[0,0,c,b]}}#S(){let{ctx:r,color:c,opacity:b,thickness:w,parentScale:P,scaleFactor:E}=this;r.lineWidth=w*P/E,r.lineCap="round",r.lineJoin="round",r.miterLimit=10,r.strokeStyle=`${c}${(0,o.opacityToHex)(b)}`}#C(r,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.#p||(this.#p=!0,this.#P(),this.thickness||=A._defaultThickness,this.color||=A._defaultColor||n.AnnotationEditor._defaultLineColor,this.opacity??=A._defaultOpacity),this.currentPath.push([r,c]),this.#d=!1,this.#S(),this.#g=()=>{this.#v(),this.#g&&window.requestAnimationFrame(this.#g)},window.requestAnimationFrame(this.#g)}#I(r,c){let[b,w]=this.currentPath.at(-1);if(this.currentPath.length>1&&r===b&&c===w)return;let P=this.currentPath,E=this.#c;P.push([r,c]),this.#d=!0,P.length<=2?(E.moveTo(...P[0]),E.lineTo(r,c)):(P.length===3&&(this.#c=E=new Path2D,E.moveTo(...P[0])),this.#E(E,...P.at(-3),...P.at(-2),r,c))}#w(){if(this.currentPath.length===0)return;let r=this.currentPath.at(-1);this.#c.lineTo(...r)}#x(r,c){this.#g=null,r=Math.min(Math.max(r,0),this.canvas.width),c=Math.min(Math.max(c,0),this.canvas.height),this.#I(r,c),this.#w();let b;if(this.currentPath.length!==1)b=this.#A();else{let E=[r,c];b=[[E,E.slice(),E.slice(),E]]}let w=this.#c,P=this.currentPath;this.currentPath=[],this.#c=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(P),this.paths.push(b),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.#k(),this.#M()),this.#N())},mustExec:!0})}#v(){if(!this.#d)return;this.#d=!1;let r=Math.ceil(this.thickness*this.parentScale),c=this.currentPath.slice(-3),b=c.map((E=>E[0])),w=c.map((E=>E[1])),{ctx:P}=(Math.min(...b),Math.max(...b),Math.min(...w),Math.max(...w),this);P.save(),P.clearRect(0,0,this.canvas.width,this.canvas.height);for(let E of this.bezierPath2D)P.stroke(E);P.stroke(this.#c),P.restore()}#E(r,c,b,w,P,E,I){let N=(c+w)/2,z=(b+P)/2,H=(w+E)/2,X=(P+I)/2;r.bezierCurveTo(N+2*(w-N)/3,z+2*(P-z)/3,H+2*(w-H)/3,X+2*(P-X)/3,H,X)}#A(){let r=this.currentPath;if(r.length<=2)return[[r[0],r[0],r.at(-1),r.at(-1)]];let c=[],b,[w,P]=r[0];for(b=1;b<r.length-2;b++){let[it,at]=r[b],[K,j]=r[b+1],G=(it+K)/2,Y=(at+j)/2,et=[w+2*(it-w)/3,P+2*(at-P)/3],rt=[G+2*(it-G)/3,Y+2*(at-Y)/3];c.push([[w,P],et,rt,[G,Y]]),[w,P]=[G,Y]}let[E,I]=r[b],[N,z]=r[b+1],H=[w+2*(E-w)/3,P+2*(I-P)/3],X=[N+2*(E-N)/3,z+2*(I-z)/3];return c.push([[w,P],H,X,[N,z]]),c}#_(){if(this.isEmpty()){this.#R();return}this.#S();let{canvas:r,ctx:c}=this;c.setTransform(1,0,0,1,0,0),c.clearRect(0,0,r.width,r.height),this.#R();for(let b of this.bezierPath2D)c.stroke(b)}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(r){this._focusEventsAllowed&&(super.focusin(r),this.enableEditMode())}canvasPointerdown(r){r.button===0&&this.isInEditMode()&&!this.#a&&(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.#I(r.offsetX,r.offsetY)}canvasPointerup(r){r.preventDefault(),this.#T(r)}canvasPointerleave(r){this.#T(r)}#T(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.#o&&clearTimeout(this.#o),this.#o=setTimeout((()=>{this.#o=null,this.canvas.removeEventListener("contextmenu",a.noContextMenu)}),10),this.#x(r.offsetX,r.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#k(){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.#u=new ResizeObserver((r=>{let c=r[0].contentRect;c.width&&c.height&&this.setDimensions(c.width,c.height)})),this.#u.observe(this.div)}get isResizable(){return!this.isEmpty()&&this.#a}render(){if(this.div)return this.div;let r,c;this.width&&(r=this.x,c=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");let[b,w,P,E]=this.#y();if(this.setAt(b,w,0,0),this.setDims(P,E),this.#k(),this.width){let[I,N]=this.parentDimensions;this.setAspectRatio(this.width*I,this.height*N),this.setAt(r*I,c*N,this.width*I,this.height*N),this.#p=!0,this.#P(),this.setDims(this.width*I,this.height*N),this.#_(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#M(),this.div}#P(){if(!this.#p)return;let[r,c]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*r),this.canvas.height=Math.ceil(this.height*c),this.#R()}setDimensions(r,c){let b=Math.round(r),w=Math.round(c);if(this.#l===b&&this.#f===w)return;this.#l=b,this.#f=w,this.canvas.style.visibility="hidden";let[P,E]=this.parentDimensions;this.width=r/P,this.height=c/E,this.fixAndSetPosition(),this.#a&&this.#L(r,c),this.#P(),this.#_(),this.canvas.style.visibility="visible",this.fixDims()}#L(r,c){let b=this.#U(),w=(r-b)/this.#e,P=(c-b)/this.#t;this.scaleFactor=Math.min(w,P)}#R(){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 c=new Path2D;for(let b=0,w=r.length;b<w;b++){let[P,E,I,N]=r[b];b===0&&c.moveTo(...P),c.bezierCurveTo(E[0],E[1],I[0],I[1],N[0],N[1])}return c}static#O(r,c,b){let[w,P,E,I]=c;switch(b){case 0:for(let N=0,z=r.length;N<z;N+=2)r[N]+=w,r[N+1]=I-r[N+1];break;case 90:for(let N=0,z=r.length;N<z;N+=2){let H=r[N];r[N]=r[N+1]+w,r[N+1]=H+P}break;case 180:for(let N=0,z=r.length;N<z;N+=2)r[N]=E-r[N],r[N+1]+=P;break;case 270:for(let N=0,z=r.length;N<z;N+=2){let H=r[N];r[N]=E-r[N+1],r[N+1]=I-H}break;default:throw new Error("Invalid rotation")}return r}static#V(r,c,b){let[w,P,E,I]=c;switch(b){case 0:for(let N=0,z=r.length;N<z;N+=2)r[N]-=w,r[N+1]=I-r[N+1];break;case 90:for(let N=0,z=r.length;N<z;N+=2){let H=r[N];r[N]=r[N+1]-P,r[N+1]=H-w}break;case 180:for(let N=0,z=r.length;N<z;N+=2)r[N]=E-r[N],r[N+1]-=P;break;case 270:for(let N=0,z=r.length;N<z;N+=2){let H=r[N];r[N]=I-r[N+1],r[N+1]=E-H}break;default:throw new Error("Invalid rotation")}return r}#G(r,c,b,w){let P=[],E=this.thickness/2,I=r*c+E,N=r*b+E;for(let z of this.paths){let H=[],X=[];for(let it=0,at=z.length;it<at;it++){let[K,j,G,Y]=z[it];if(K[0]===Y[0]&&K[1]===Y[1]&&at===1){let p=r*K[0]+I,v=r*K[1]+N;H.push(p,v),X.push(p,v);break}let et=r*K[0]+I,rt=r*K[1]+N,ct=r*j[0]+I,st=r*j[1]+N,W=r*G[0]+I,x=r*G[1]+N,T=r*Y[0]+I,R=r*Y[1]+N;it===0&&(H.push(et,rt),X.push(et,rt)),H.push(ct,st,W,x,T,R),X.push(ct,st),it===at-1&&X.push(T,R)}P.push({bezier:A.#O(H,w,this.rotation),points:A.#O(X,w,this.rotation)})}return P}#H(){let r=1/0,c=-1/0,b=1/0,w=-1/0;for(let P of this.paths)for(let[E,I,N,z]of P){let H=i.Util.bezierBoundingBox(...E,...I,...N,...z);r=Math.min(r,H[0]),b=Math.min(b,H[1]),c=Math.max(c,H[2]),w=Math.max(w,H[3])}return[r,b,c,w]}#U(){return this.#a?Math.ceil(this.thickness*this.parentScale):0}#N(r=!1){if(this.isEmpty())return;if(!this.#a){this.#_();return}let c=this.#H(),b=this.#U();this.#e=Math.max(n.AnnotationEditor.MIN_SIZE,c[2]-c[0]),this.#t=Math.max(n.AnnotationEditor.MIN_SIZE,c[3]-c[1]);let w=Math.ceil(b+this.#e*this.scaleFactor),P=Math.ceil(b+this.#t*this.scaleFactor),[E,I]=this.parentDimensions;this.width=w/E,this.height=P/I,this.setAspectRatio(w,P);let N=this.translationX,z=this.translationY;this.translationX=-c[0],this.translationY=-c[1],this.#P(),this.#_(),this.#l=w,this.#f=P,this.setDims(w,P);let H=r?b/this.scaleFactor/2:0;this.translate(N-this.translationX-H,z-this.translationY-H)}static deserialize(r,c,b){if(r instanceof l.InkAnnotationElement)return null;let w=super.deserialize(r,c,b);w.thickness=r.thickness,w.color=i.Util.makeHexColor(...r.color),w.opacity=r.opacity;let[P,E]=w.pageDimensions,I=w.width*P,N=w.height*E,z=w.parentScale,H=r.thickness/2;w.#a=!0,w.#l=Math.round(I),w.#f=Math.round(N);let{paths:X,rect:it,rotation:at}=r;for(let{bezier:j}of X){j=A.#V(j,it,at);let G=[];w.paths.push(G);let Y=z*(j[0]-H),et=z*(j[1]-H);for(let ct=2,st=j.length;ct<st;ct+=6){let W=z*(j[ct]-H),x=z*(j[ct+1]-H),T=z*(j[ct+2]-H),R=z*(j[ct+3]-H),p=z*(j[ct+4]-H),v=z*(j[ct+5]-H);G.push([[Y,et],[W,x],[T,R],[p,v]]),Y=p,et=v}let rt=this.#F(G);w.bezierPath2D.push(rt)}let K=w.#H();return w.#e=Math.max(n.AnnotationEditor.MIN_SIZE,K[2]-K[0]),w.#t=Math.max(n.AnnotationEditor.MIN_SIZE,K[3]-K[1]),w.#L(I,N),w}serialize(){if(this.isEmpty())return null;let r=this.getRect(0,0),c=n.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);return{annotationType:i.AnnotationEditorType.INK,color:c,thickness:this.thickness,opacity:this.opacity,paths:this.#G(this.scaleFactor/this.parentScale,this.translationX,this.translationY,r),pageIndex:this.pageIndex,rect:r,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}}class C extends n.AnnotationEditor{#t=null;#e=null;#i=null;#n=null;#r=null;#s="";#o=null;#c=null;#a=null;#d=!1;#p=!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,c){n.AnnotationEditor.initialize(r,c)}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,c){c.pasteEditor(i.AnnotationEditorType.STAMP,{bitmapFile:r.getAsFile()})}#u(r,c=!1){r?(this.#t=r.bitmap,c||(this.#e=r.id,this.#d=r.isSvg),r.file&&(this.#s=r.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.#u(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((b=>this.#u(b))).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((b=>this.#u(b))).finally((()=>this.#l()));return}let r=document.createElement("input");r.type="file",r.accept=C.supportedTypesStr,this.#i=new Promise((c=>{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.#u(b)}else this.remove();c()})),r.addEventListener("cancel",(()=>{this.remove(),c()}))})).finally((()=>this.#l())),r.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 r,c;if(this.width&&(r=this.x,c=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#t?this.#g():this.#f(),this.width){let[b,w]=this.parentDimensions;this.setAt(r*b,c*w,this.width*b,this.height*w)}return this.div}#g(){let{div:r}=this,{width:c,height:b}=this.#t,[w,P]=this.pageDimensions,E=.75;if(this.width)c=this.width*w,b=this.height*P;else if(c>E*w||b>E*P){let H=Math.min(E*w/c,E*P/b);c*=H,b*=H}let[I,N]=this.parentDimensions;this.setDims(c*I/w,b*N/P),this._uiManager.enableWaiting(!1);let z=this.#o=document.createElement("canvas");r.append(z),r.hidden=!1,this.#m(c,b),this.#S(),this.#p||(this.parent.addUndoableEditor(this),this.#p=!0),this._reportTelemetry({action:"inserted_image"}),this.#s&&z.setAttribute("aria-label",this.#s)}#h(r,c){let[b,w]=this.parentDimensions;this.width=r/b,this.height=c/w,this.setDims(r,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(r,c)}),200)}#b(r,c){let{width:b,height:w}=this.#t,P=b,E=w,I=this.#t;for(;P>2*r||E>2*c;){let N=P,z=E;P>2*r&&(P=P>=16384?Math.floor(P/2)-1:Math.ceil(P/2)),E>2*c&&(E=E>=16384?Math.floor(E/2)-1:Math.ceil(E/2));let H=new OffscreenCanvas(P,E);H.getContext("2d").drawImage(I,0,0,N,z,0,0,P,E),I=H.transferToImageBitmap()}return I}#m(r,c){r=Math.ceil(r),c=Math.ceil(c);let b=this.#o;if(!b||b.width===r&&b.height===c)return;b.width=r,b.height=c;let w=this.#d?this.#t:this.#b(r,c);if(this._uiManager.hasMLManager&&!this.hasAltText()){let E=new OffscreenCanvas(r,c);E.getContext("2d").drawImage(w,0,0,w.width,w.height,0,0,r,c),E.convertToBlob().then((I=>{let N=new FileReader;N.onload=()=>{let z=N.result;this._uiManager.mlGuess({service:"image-to-text",request:{imageData:z}}).then((H=>{let X=H?.output||"";this.parent&&X&&!this.hasAltText()&&(this.altTextData={altText:X,decorative:!1})}))},N.readAsDataURL(I)}))}let P=b.getContext("2d");P.filter=this._uiManager.hcmFilter,P.drawImage(w,0,0,w.width,w.height,0,0,r,c)}getImageForAltText(){return this.#o}#y(r){if(r){if(this.#d){let b=this._uiManager.imageManager.getSvgUrl(this.#e);if(b)return b}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.#d){let[c,b]=this.pageDimensions,w=Math.round(this.width*c*a.PixelsPerInch.PDF_TO_CSS_UNITS),P=Math.round(this.height*b*a.PixelsPerInch.PDF_TO_CSS_UNITS),E=new OffscreenCanvas(w,P);return E.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,w,P),E.transferToImageBitmap()}return structuredClone(this.#t)}#S(){this.#c=new ResizeObserver((r=>{let c=r[0].contentRect;c.width&&c.height&&this.#h(c.width,c.height)})),this.#c.observe(this.div)}static deserialize(r,c,b){if(r instanceof l.StampAnnotationElement)return null;let w=super.deserialize(r,c,b),{rect:P,bitmapUrl:E,bitmapId:I,isSvg:N,accessibilityData:z}=r;I&&b.imageManager.isValidId(I)?w.#e=I:w.#n=E,w.#d=N;let[H,X]=w.pageDimensions;return w.width=(P[2]-P[0])/H,w.height=(P[3]-P[1])/X,z&&(w.altTextData=z),w}serialize(r=!1,c=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.#d,structTreeParentId:this._structTreeParentId};if(r)return b.bitmapUrl=this.#y(!0),b.accessibilityData=this.altTextData,b;let{decorative:w,altText:P}=this.altTextData;if(!w&&P&&(b.accessibilityData={type:"Figure",alt:P}),c===null)return b;c.stamps||=new Map;let E=this.#d?(b.rect[2]-b.rect[0])*(b.rect[3]-b.rect[1]):null;if(c.stamps.has(this.#e)){if(this.#d){let I=c.stamps.get(this.#e);E>I.area&&(I.area=E,I.serialized.bitmap.close(),I.serialized.bitmap=this.#y(!1))}}else c.stamps.set(this.#e,{area:E,serialized:b}),b.bitmap=this.#y(!1);return b}}class u{#t;#e=!1;#i=null;#n=null;#r=null;#s=null;#o=null;#c=new Map;#a=!1;#d=!1;#p=!1;#u=null;#l;static _initialized=!1;static#f=new Map([g,A,C,f].map((r=>[r._editorType,r])));constructor({uiManager:r,pageIndex:c,div:b,accessibilityManager:w,annotationLayer:P,drawLayer:E,textLayer:I,viewport:N,l10n:z}){let H=[...u.#f.values()];if(!u._initialized){u._initialized=!0;for(let X of H)X.initialize(z,r)}r.registerEditorTypes(H),this.#l=r,this.pageIndex=c,this.div=b,this.#t=w,this.#i=P,this.viewport=N,this.#u=I,this.drawLayer=E,this.#l.addLayer(this)}get isEmpty(){return this.#c.size===0}get isInvisible(){return this.isEmpty&&this.#l.getMode()===i.AnnotationEditorType.NONE}updateToolbar(r){this.#l.updateToolbar(r)}updateMode(r=this.#l.getMode()){switch(this.#y(),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:c}=this.div;for(let b of u.#f.values())c.toggle(`${b._type}Editing`,r===b._editorType);this.div.hidden=!1}hasTextLayer(r){return r===this.#u?.div}addInkEditorIfNeeded(r){if(this.#l.getMode()===i.AnnotationEditorType.INK){if(!r){for(let c of this.#c.values())if(c.isEmpty()){c.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(r){this.#l.setEditingState(r)}addCommands(r){this.#l.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.#c.values())b.enableEditing(),b.annotationElementId&&r.add(b.annotationElementId);if(!this.#i)return;let c=this.#i.getEditableAnnotations();for(let b of c){if(b.hide(),this.#l.isDeletedAnnotationElement(b.data.id)||r.has(b.data.id))continue;let w=this.deserialize(b);w&&(this.addOrRebuild(w),w.enableEditing())}}disable(){this.#p=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let r=new Set;for(let b of this.#c.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 w of b){let{id:P}=w.data;r.has(P)||this.#l.isDeletedAnnotationElement(P)||w.show()}}this.#y(),this.isEmpty&&(this.div.hidden=!0);let{classList:c}=this.div;for(let b of u.#f.values())c.remove(`${b._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#p=!1}getEditableAnnotation(r){return this.#i?.getEditableAnnotation(r)||null}setActiveEditor(r){this.#l.getActive()!==r&&this.#l.setActiveEditor(r)}enableTextSelection(){this.div.tabIndex=-1,this.#u?.div&&!this.#s&&(this.#s=this.#g.bind(this),this.#u.div.addEventListener("pointerdown",this.#s),this.#u.div.classList.add("highlighting"))}disableTextSelection(){this.div.tabIndex=0,this.#u?.div&&this.#s&&(this.#u.div.removeEventListener("pointerdown",this.#s),this.#s=null,this.#u.div.classList.remove("highlighting"))}#g(r){if(this.#l.unselectAll(),r.target===this.#u.div){let{isMac:c}=i.FeatureTest.platform;if(r.button!==0||r.ctrlKey&&c)return;this.#l.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),f.startHighlighting(this,this.#l.direction==="ltr",r),this.#u.div.addEventListener("pointerup",(()=>{this.#u.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.#c.set(r.id,r);let{annotationElementId:c}=r;c&&this.#l.isDeletedAnnotationElement(c)&&this.#l.removeDeletedAnnotationElement(r)}detach(r){this.#c.delete(r.id),this.#t?.removePointerInTextLayer(r.contentDiv),!this.#p&&r.annotationElementId&&this.#l.addDeletedAnnotationElement(r)}remove(r){this.detach(r),this.#l.removeEditor(r),r.div.remove(),r.isAttachedToDOM=!1,this.#d||this.addInkEditorIfNeeded(!1)}changeParent(r){r.parent!==this&&(r.annotationElementId&&(this.#l.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.#l.addEditor(r),this.attach(r),!r.isAttachedToDOM){let c=r.render();this.div.append(c),r.isAttachedToDOM=!0}r.fixAndSetPosition(),r.onceAdded(),this.#l.addToAnnotationStorage(r),r._reportTelemetry(r.telemetryInitialData)}}moveEditorInDOM(r){if(!r.isAttachedToDOM)return;let{activeElement:c}=document;r.div.contains(c)&&!this.#o&&(r._focusEventsAllowed=!1,this.#o=setTimeout((()=>{this.#o=null,r.div.contains(document.activeElement)?r._focusEventsAllowed=!0:(r.div.addEventListener("focusin",(()=>{r._focusEventsAllowed=!0}),{once:!0}),c.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.#l.getId()}get#h(){return u.#f.get(this.#l.getMode())}#b(r){let c=this.#h;return c?new c.prototype.constructor(r):null}canCreateNewEmptyEditor(){return this.#h?.canCreateNewEmptyEditor()}pasteEditor(r,c){this.#l.updateToolbar(r),this.#l.updateMode(r);let{offsetX:b,offsetY:w}=this.#m(),P=this.getNextId(),E=this.#b({parent:this,id:P,x:b,y:w,uiManager:this.#l,isCentered:!0,...c});E&&this.add(E)}deserialize(r){return u.#f.get(r.annotationType??r.annotationEditorType)?.deserialize(r,this,this.#l)||null}createAndAddNewEditor(r,c,b={}){let w=this.getNextId(),P=this.#b({parent:this,id:w,x:r.offsetX,y:r.offsetY,uiManager:this.#l,isCentered:c,...b});return P&&this.add(P),P}#m(){let{x:r,y:c,width:b,height:w}=this.div.getBoundingClientRect(),P=Math.max(0,r),E=Math.max(0,c),I=(P+Math.min(window.innerWidth,r+b))/2-r,N=(E+Math.min(window.innerHeight,c+w))/2-c,[z,H]=this.viewport.rotation%180==0?[I,N]:[N,I];return{offsetX:z,offsetY:H}}addNewEditor(){this.createAndAddNewEditor(this.#m(),!0)}setSelected(r){this.#l.setSelected(r)}toggleSelected(r){this.#l.toggleSelected(r)}isSelected(r){return this.#l.isSelected(r)}unselect(r){this.#l.unselect(r)}pointerup(r){let{isMac:c}=i.FeatureTest.platform;!(r.button!==0||r.ctrlKey&&c)&&r.target===this.div&&this.#a&&(this.#a=!1,this.#e?this.#l.getMode()!==i.AnnotationEditorType.STAMP?this.createAndAddNewEditor(r,!1):this.#l.unselectAll():this.#e=!0)}pointerdown(r){if(this.#l.getMode()===i.AnnotationEditorType.HIGHLIGHT&&this.enableTextSelection(),this.#a){this.#a=!1;return}let{isMac:c}=i.FeatureTest.platform;if(r.button!==0||r.ctrlKey&&c||r.target!==this.div)return;this.#a=!0;let b=this.#l.getActive();this.#e=!b||b.isEmpty()}findNewParent(r,c,b){let w=this.#l.findParent(c,b);return w===null||w===this?!1:(w.changeParent(r),!0)}destroy(){this.#l.getActive()?.parent===this&&(this.#l.commitOrRemove(),this.#l.setActiveEditor(null)),this.#o&&(clearTimeout(this.#o),this.#o=null);for(let r of this.#c.values())this.#t?.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,this.#c.clear(),this.#l.removeLayer(this)}#y(){this.#d=!0;for(let r of this.#c.values())r.isEmpty()&&r.remove();this.#d=!1}render({viewport:r}){this.viewport=r,(0,a.setLayerDimensions)(this.div,r);for(let c of this.#l.getEditors(this.pageIndex))this.add(c),c.rebuild();this.updateMode()}update({viewport:r}){this.#l.commitOrRemove(),this.#y();let c=this.viewport.rotation,b=r.rotation;if(this.viewport=r,(0,a.setLayerDimensions)(this.div,{rotation:b}),c!==b)for(let w of this.#c.values())w.rotate(b);this.addInkEditorIfNeeded(!1)}get pageDimensions(){let{pageWidth:r,pageHeight:c}=this.viewport.rawDims;return[r,c]}get scale(){return this.#l.viewParameters.realScale}}},259:(s,t,e)=>{e.d(t,{ColorPicker:()=>l});var i=e(292),n=e(830),o=e(419);class l{#t=this.#g.bind(this);#e=this.#b.bind(this);#i=null;#n=null;#r;#s=null;#o=!1;#c=!1;#a=null;#d;#p=null;#u;static get _keyboardManager(){return(0,i.shadow)(this,"_keyboardManager",new n.KeyboardManager([[["Escape","mac+Escape"],l.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],l.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],l.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],l.prototype._moveToPrevious],[["Home","mac+Home"],l.prototype._moveToBeginning],[["End","mac+End"],l.prototype._moveToEnd]]))}constructor({editor:g=null,uiManager:m=null}){g?(this.#c=!1,this.#u=i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.#a=g):(this.#c=!0,this.#u=i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR),this.#p=g?._uiManager||m,this.#d=this.#p._eventBus,this.#r=g?.color||this.#p?.highlightColors.values().next().value||"#FFFF98"}renderButton(){let g=this.#i=document.createElement("button");g.className="colorPicker",g.tabIndex="0",g.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),g.setAttribute("aria-haspopup",!0),g.addEventListener("click",this.#h.bind(this)),g.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,g.append(m),g}renderMainDropdown(){let g=this.#s=this.#l();return g.setAttribute("aria-orientation","horizontal"),g.setAttribute("aria-labelledby","highlightColorPickerLabel"),g}#l(){let g=document.createElement("div");g.addEventListener("contextmenu",o.noContextMenu),g.className="dropdown",g.role="listbox",g.setAttribute("aria-multiselectable",!1),g.setAttribute("aria-orientation","vertical"),g.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(let[m,d]of this.#p.highlightColors){let a=document.createElement("button");a.tabIndex="0",a.role="option",a.setAttribute("data-color",d),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=d,a.setAttribute("aria-selected",d===this.#r),a.addEventListener("click",this.#f.bind(this,d)),g.append(a)}return g.addEventListener("keydown",this.#t),g}#f(g,m){m.stopPropagation(),this.#d.dispatch("switchannotationeditorparams",{source:this,type:this.#u,value:g})}_colorSelectFromKeyboard(g){if(g.target===this.#i){this.#h(g);return}let m=g.target.getAttribute("data-color");m&&this.#f(m,g)}_moveToNext(g){this.#m?g.target!==this.#i?g.target.nextSibling?.focus():this.#s.firstChild?.focus():this.#h(g)}_moveToPrevious(g){g.target!==this.#s?.firstChild&&g.target!==this.#i?(this.#m||this.#h(g),g.target.previousSibling?.focus()):this.#m&&this._hideDropdownFromKeyboard()}_moveToBeginning(g){this.#m?this.#s.firstChild?.focus():this.#h(g)}_moveToEnd(g){this.#m?this.#s.lastChild?.focus():this.#h(g)}#g(g){l._keyboardManager.exec(this,g)}#h(g){if(this.#m){this.hideDropdown();return}if(this.#o=g.detail===0,window.addEventListener("pointerdown",this.#e),this.#s){this.#s.classList.remove("hidden");return}let m=this.#s=this.#l();this.#i.append(m)}#b(g){this.#s?.contains(g.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(g){if(this.#n&&(this.#n.style.backgroundColor=g),!this.#s)return;let m=this.#p.highlightColors.values();for(let d of this.#s.children)d.setAttribute("aria-selected",m.next().value===g)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null,this.#s?.remove(),this.#s=null}}},310:(s,t,e)=>{e.d(t,{AnnotationEditor:()=>g});var i=e(830),n=e(292),o=e(419);class l{#t="";#e=!1;#i=null;#n=null;#r=null;#s=!1;#o=null;static _l10nPromise=null;constructor(a){this.#o=a}static initialize(a){l._l10nPromise||=a}async render(){let a=this.#i=document.createElement("button");a.className="altText";let f=await l._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",(C=>C.stopPropagation()));let A=C=>{C.preventDefault(),this.#o._uiManager.editAltText(this.#o)};return a.addEventListener("click",A,{capture:!0}),a.addEventListener("keydown",(C=>{C.target===a&&C.key==="Enter"&&(this.#s=!0,A(C))})),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:f}){(this.#t!==a||this.#e!==f)&&(this.#t=a,this.#e=f,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"),l._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((C=>{a.setAttribute("aria-label",C)}));let f=this.#n;if(!f){this.#n=f=document.createElement("span"),f.className="tooltip",f.setAttribute("role","tooltip");let C=f.id=`alt-text-tooltip-${this.#o.id}`;a.setAttribute("aria-describedby",C);let u=100;a.addEventListener("mouseenter",(()=>{this.#r=setTimeout((()=>{this.#r=null,this.#n.classList.add("show"),this.#o._reportTelemetry({action:"alt_text_tooltip"})}),u)})),a.addEventListener("mouseleave",(()=>{this.#r&&(clearTimeout(this.#r),this.#r=null),this.#n?.classList.remove("show")}))}f.innerText=this.#e?await l._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#t,f.parentNode||a.append(f),this.#o.getImageForAltText()?.setAttribute("aria-describedby",f.id)}}var h=e(362);class g{#t=null;#e=null;#i=!1;#n=!1;#r=null;#s=null;#o=this.focusin.bind(this);#c=this.focusout.bind(this);#a=null;#d="";#p=!1;#u=null;#l=!1;#f=!1;#g=!1;#h=null;#b=0;#m=0;#y=null;_initialOptions=Object.create(null);_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#S=!1;#C=g._zIndex++;static _borderLineWidth=-1;static _colorManager=new i.ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let a=g.prototype._resizeWithKeyboard,f=i.AnnotationEditorUIManager.TRANSLATE_SMALL,A=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:[-A,0]}],[["ArrowRight","mac+ArrowRight"],a,{args:[f,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],a,{args:[A,0]}],[["ArrowUp","mac+ArrowUp"],a,{args:[0,-f]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],a,{args:[0,-A]}],[["ArrowDown","mac+ArrowDown"],a,{args:[0,f]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],a,{args:[0,A]}],[["Escape","mac+Escape"],g.prototype._stopResizingWithKeyboard]]))}constructor(a){this.constructor===g&&(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:A,pageHeight:C,pageX:u,pageY:y}}=this.parent.viewport;this.rotation=f,this.pageRotation=(360+f-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[A,C],this.pageTranslation=[u,y];let[r,c]=this.parentDimensions;this.x=a.x/r,this.y=a.y/c,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,A){if(g._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((u=>[u,a.get(u.replaceAll(/([A-Z])/g,(y=>`-${y.toLowerCase()}`)))]))),A?.strings)for(let u of A.strings)g._l10nPromise.set(u,a.get(u));if(g._borderLineWidth!==-1)return;let C=getComputedStyle(document.documentElement);g._borderLineWidth=parseFloat(C.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.#p?this.#p=!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,A,C){let[u,y]=this.parentDimensions;[A,C]=this.screenToPageTranslation(A,C),this.x=(a+A)/u,this.y=(f+C)/y,this.fixAndSetPosition()}#I([a,f],A,C){[A,C]=this.screenToPageTranslation(A,C),this.x+=A/a,this.y+=C/f,this.fixAndSetPosition()}translate(a,f){this.#I(this.parentDimensions,a,f)}translateInPage(a,f){this.#u||=[this.x,this.y],this.#I(this.pageDimensions,a,f),this.div.scrollIntoView({block:"nearest"})}drag(a,f){this.#u||=[this.x,this.y];let[A,C]=this.parentDimensions;if(this.x+=a/A,this.y+=f/C,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:b,y:w}=this.div.getBoundingClientRect();this.parent.findNewParent(this,b,w)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:u,y}=this,[r,c]=this.getBaseTranslation();u+=r,y+=c,this.div.style.left=`${(100*u).toFixed(2)}%`,this.div.style.top=`${(100*y).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#u&&(this.#u[0]!==this.x||this.#u[1]!==this.y)}getBaseTranslation(){let[a,f]=this.parentDimensions,{_borderLineWidth:A}=g,C=A/a,u=A/f;switch(this.rotation){case 90:return[-C,u];case 180:return[C,u];case 270:return[C,-u];default:return[-C,-u]}}get _mustFixPosition(){return!0}fixAndSetPosition(a=this.rotation){let[f,A]=this.pageDimensions,{x:C,y:u,width:y,height:r}=this;if(y*=f,r*=A,C*=f,u*=A,this._mustFixPosition)switch(a){case 0:C=Math.max(0,Math.min(f-y,C)),u=Math.max(0,Math.min(A-r,u));break;case 90:C=Math.max(0,Math.min(f-r,C)),u=Math.min(A,Math.max(y,u));break;case 180:C=Math.min(f,Math.max(y,C)),u=Math.min(A,Math.max(r,u));break;case 270:C=Math.min(f,Math.max(r,C)),u=Math.max(0,Math.min(A-y,u))}this.x=C/=f,this.y=u/=A;let[c,b]=this.getBaseTranslation();C+=c,u+=b;let{style:w}=this.div;w.left=`${(100*C).toFixed(2)}%`,w.top=`${(100*u).toFixed(2)}%`,this.moveInDOM()}static#w(a,f,A){switch(A){case 90:return[f,-a];case 180:return[-a,-f];case 270:return[-f,a];default:return[a,f]}}screenToPageTranslation(a,f){return g.#w(a,f,this.parentRotation)}pageTranslationToScreen(a,f){return g.#w(a,f,360-this.parentRotation)}#x(a){switch(a){case 90:{let[f,A]=this.pageDimensions;return[0,-f/A,A/f,0]}case 180:return[-1,0,0,-1];case 270:{let[f,A]=this.pageDimensions;return[0,f/A,-A/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,A]}=this,C=f*a,u=A*a;return n.FeatureTest.isCSSRoundSupported?[Math.round(C),Math.round(u)]:[C,u]}setDims(a,f){let[A,C]=this.parentDimensions;this.div.style.width=`${(100*a/A).toFixed(2)}%`,this.#n||(this.div.style.height=`${(100*f/C).toFixed(2)}%`)}fixDims(){let{style:a}=this.div,{height:f,width:A}=a,C=A.endsWith("%"),u=!this.#n&&f.endsWith("%");if(C&&u)return;let[y,r]=this.parentDimensions;C||(a.width=`${(100*parseFloat(A)/y).toFixed(2)}%`),this.#n||u||(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 A=document.createElement("div");this.#r.append(A),A.classList.add("resizer",f),A.setAttribute("data-resizer-name",f),A.addEventListener("pointerdown",this.#E.bind(this,f)),A.addEventListener("contextmenu",o.noContextMenu),A.tabIndex=-1}this.div.prepend(this.#r)}#E(a,f){f.preventDefault();let{isMac:A}=n.FeatureTest.platform;if(f.button!==0||f.ctrlKey&&A)return;this.#e?.toggle(!1);let C=this.#_.bind(this,a),u=this._isDraggable;this._isDraggable=!1;let y={passive:!0,capture:!0};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",C,y);let r=this.x,c=this.y,b=this.width,w=this.height,P=this.parent.div.style.cursor,E=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(f.target).cursor;let I=()=>{this.parent.togglePointerEvents(!0),this.#e?.toggle(!0),this._isDraggable=u,window.removeEventListener("pointerup",I),window.removeEventListener("blur",I),window.removeEventListener("pointermove",C,y),this.parent.div.style.cursor=P,this.div.style.cursor=E,this.#A(r,c,b,w)};window.addEventListener("pointerup",I),window.addEventListener("blur",I)}#A(a,f,A,C){let u=this.x,y=this.y,r=this.width,c=this.height;u===a&&y===f&&r===A&&c===C||this.addCommands({cmd:()=>{this.width=r,this.height=c,this.x=u,this.y=y;let[b,w]=this.parentDimensions;this.setDims(b*r,w*c),this.fixAndSetPosition()},undo:()=>{this.width=A,this.height=C,this.x=a,this.y=f;let[b,w]=this.parentDimensions;this.setDims(b*A,w*C),this.fixAndSetPosition()},mustExec:!0})}#_(a,f){let[A,C]=this.parentDimensions,u=this.x,y=this.y,r=this.width,c=this.height,b=g.MIN_SIZE/A,w=g.MIN_SIZE/C,P=_=>Math.round(1e4*_)/1e4,E=this.#x(this.rotation),I=(_,k)=>[E[0]*_+E[2]*k,E[1]*_+E[3]*k],N=this.#x(360-this.rotation),z,H,X=!1,it=!1;switch(a){case"topLeft":X=!0,z=(_,k)=>[0,0],H=(_,k)=>[_,k];break;case"topMiddle":z=(_,k)=>[_/2,0],H=(_,k)=>[_/2,k];break;case"topRight":X=!0,z=(_,k)=>[_,0],H=(_,k)=>[0,k];break;case"middleRight":it=!0,z=(_,k)=>[_,k/2],H=(_,k)=>[0,k/2];break;case"bottomRight":X=!0,z=(_,k)=>[_,k],H=(_,k)=>[0,0];break;case"bottomMiddle":z=(_,k)=>[_/2,k],H=(_,k)=>[_/2,0];break;case"bottomLeft":X=!0,z=(_,k)=>[0,k],H=(_,k)=>[_,0];break;case"middleLeft":it=!0,z=(_,k)=>[0,k/2],H=(_,k)=>[_,k/2]}let at=z(r,c),K=H(r,c),j=I(...K),G=P(u+j[0]),Y=P(y+j[1]),et=1,rt=1,[ct,st]=this.screenToPageTranslation(f.movementX,f.movementY);[ct,st]=(W=ct/A,x=st/C,[N[0]*W+N[2]*x,N[1]*W+N[3]*x]);var W,x;if(X){let _=Math.hypot(r,c);et=rt=Math.max(Math.min(Math.hypot(K[0]-at[0]-ct,K[1]-at[1]-st)/_,1/r,1/c),b/r,w/c)}else it?et=Math.max(b,Math.min(1,Math.abs(K[0]-at[0]-ct)))/r:rt=Math.max(w,Math.min(1,Math.abs(K[1]-at[1]-st)))/c;let T=P(r*et),R=P(c*rt);j=I(...H(T,R));let p=G-j[0],v=Y-j[1];this.width=T,this.height=R,this.x=p,this.y=v,this.setDims(A*T,C*R),this.fixAndSetPosition()}altTextFinish(){this.#e?.finish()}async addEditToolbar(){return this.#a||this.#f?this.#a:(this.#a=new h.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||(l.initialize(g._l10nPromise),this.#e=new l(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,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[A,C]=this.getInitialTranslation();return this.translate(A,C),(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.#p=!0,this._isDraggable?this.#k(a):this.#T(a))}#T(a){let{isMac:f}=n.FeatureTest.platform;a.ctrlKey&&!f||a.shiftKey||a.metaKey&&f?this.parent.toggleSelected(this):this.parent.setSelected(this)}#k(a){let f=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let A,C;f&&(this.div.classList.add("moving"),A={passive:!0,capture:!0},this.#b=a.clientX,this.#m=a.clientY,C=y=>{let{clientX:r,clientY:c}=y,[b,w]=this.screenToPageTranslation(r-this.#b,c-this.#m);this.#b=r,this.#m=c,this._uiManager.dragSelectedEditors(b,w)},window.addEventListener("pointermove",C,A));let u=()=>{window.removeEventListener("pointerup",u),window.removeEventListener("blur",u),f&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",C,A)),this.#p=!1,this._uiManager.endDragSession()||this.#T(a)};window.addEventListener("pointerup",u),window.addEventListener("blur",u)}moveInDOM(){this.#h&&clearTimeout(this.#h),this.#h=setTimeout((()=>{this.#h=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(a,f,A){a.changeParent(this),this.x=f,this.y=A,this.fixAndSetPosition()}getRect(a,f,A=this.rotation){let C=this.parentScale,[u,y]=this.pageDimensions,[r,c]=this.pageTranslation,b=a/C,w=f/C,P=this.x*u,E=this.y*y,I=this.width*u,N=this.height*y;switch(A){case 0:return[P+b+r,y-E-w-N+c,P+b+I+r,y-E-w+c];case 90:return[P+w+r,y-E+b+c,P+w+N+r,y-E+b+I+c];case 180:return[P-b-I+r,y-E+w+c,P-b+r,y-E+w+N+c];case 270:return[P-w-N+r,y-E-b-I+c,P-w+r,y-E-b+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(a,f){let[A,C,u,y]=a,r=u-A,c=y-C;switch(this.rotation){case 0:return[A,f-y,r,c];case 90:return[A,f-C,c,r];case 180:return[u,f-C,r,c];case 270:return[u,f-y,c,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.#o),this.div?.addEventListener("focusout",this.#c)}rotate(a){}serialize(a=!1,f=null){(0,n.unreachable)("An editor must be serializable")}static deserialize(a,f,A){let C=new this.prototype.constructor({parent:f,id:f.getNextId(),uiManager:A});C.rotation=a.rotation;let[u,y]=C.pageDimensions,[r,c,b,w]=C.getRectInCurrentCoords(a.rect,y);return C.x=r/u,C.y=c/y,C.width=b/u,C.height=w/y,C}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.#h&&(clearTimeout(this.#h),this.#h=null),this.#F(),this.removeEditToolbar(),this.#y){for(let a of this.#y.values())clearTimeout(a);this.#y=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.#P.bind(this);for(let c of this.#t){let b=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",y),c.addEventListener("blur",r),c.addEventListener("focus",this.#L.bind(this,b)),g._l10nPromise.get(`pdfjs-editor-resizer-label-${b}`).then((w=>c.setAttribute("aria-label",w)))}}let A=this.#t[0],C=0;for(let y of f){if(y===A)break;C++}let u=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(u!==C){if(u<C)for(let r=0;r<C-u;r++)this.#r.append(this.#r.firstChild);else if(u>C)for(let r=0;r<u-C;r++)this.#r.firstChild.before(this.#r.lastChild);let y=0;for(let r of f){let c=this.#t[y++].getAttribute("data-resizer-name");g._l10nPromise.get(`pdfjs-editor-resizer-label-${c}`).then((b=>r.setAttribute("aria-label",b)))}}this.#R(0),this.#g=!0,this.#r.firstChild.focus({focusVisible:!0}),a.preventDefault(),a.stopImmediatePropagation()}#M(a){g._resizerKeyboardManager.exec(this,a)}#P(a){this.#g&&a.relatedTarget?.parentNode!==this.#r&&this.#F()}#L(a){this.#d=this.#g?a:""}#R(a){if(this.#t)for(let f of this.#t)f.tabIndex=a}_resizeWithKeyboard(a,f){this.#g&&this.#_(this.#d,{movementX:a,movementY:f})}#F(){if(this.#g=!1,this.#R(-1),this.#s){let{savedX:a,savedY:f,savedWidth:A,savedHeight:C}=this.#s;this.#A(a,f,A,C),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,f){}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,f){this.#n=!0;let A=a/f,{style:C}=this.div;C.aspectRatio=A,C.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.#y||=new Map;let{action:A}=a,C=this.#y.get(A);C&&clearTimeout(C),C=setTimeout((()=>{this._reportTelemetry(a),this.#y.delete(A),this.#y.size===0&&(this.#y=null)}),g._telemetryTimeout),this.#y.set(A,C)}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 g{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:()=>h,Outliner:()=>n});var i=e(292);class n{#t;#e=[];#i=[];constructor(d,a=0,f=0,A=!0){let C=1/0,u=-1/0,y=1/0,r=-1/0,c=10**-4;for(let{x:z,y:H,width:X,height:it}of d){let at=Math.floor((z-a)/c)*c,K=Math.ceil((z+X+a)/c)*c,j=Math.floor((H-a)/c)*c,G=Math.ceil((H+it+a)/c)*c,Y=[at,j,G,!0],et=[K,j,G,!1];this.#e.push(Y,et),C=Math.min(C,at),u=Math.max(u,K),y=Math.min(y,j),r=Math.max(r,G)}let b=u-C+2*f,w=r-y+2*f,P=C-f,E=y-f,I=this.#e.at(A?-1:-2),N=[I[0],I[2]];for(let z of this.#e){let[H,X,it]=z;z[0]=(H-P)/b,z[1]=(X-E)/w,z[2]=(it-E)/w}this.#t={x:P,y:E,width:b,height:w,lastPoint:N}}getOutlines(){this.#e.sort(((a,f)=>a[0]-f[0]||a[1]-f[1]||a[2]-f[2]));let d=[];for(let a of this.#e)a[3]?(d.push(...this.#c(a)),this.#s(a)):(this.#o(a),d.push(...this.#c(a)));return this.#n(d)}#n(d){let a=[],f=new Set;for(let u of d){let[y,r,c]=u;a.push([y,r,u],[y,c,u])}a.sort(((u,y)=>u[1]-y[1]||u[0]-y[0]));for(let u=0,y=a.length;u<y;u+=2){let r=a[u][2],c=a[u+1][2];r.push(c),c.push(r),f.add(r),f.add(c)}let A=[],C;for(;f.size>0;){let u=f.values().next().value,[y,r,c,b,w]=u;f.delete(u);let P=y,E=r;for(C=[y,c],A.push(C);;){let I;if(f.has(b))I=b;else{if(!f.has(w))break;I=w}f.delete(I),[y,r,c,b,w]=I,P!==y&&(C.push(P,E,y,E===r?r:c),P=y),E=E===r?c:r}C.push(P,E)}return new l(A,this.#t)}#r(d){let a=this.#i,f=0,A=a.length-1;for(;f<=A;){let C=f+A>>1,u=a[C][0];if(u===d)return C;u<d?f=C+1:A=C-1}return A+1}#s([,d,a]){let f=this.#r(d);this.#i.splice(f,0,[d,a])}#o([,d,a]){let f=this.#r(d);for(let A=f;A<this.#i.length;A++){let[C,u]=this.#i[A];if(C!==d)break;if(C===d&&u===a){this.#i.splice(A,1);return}}for(let A=f-1;A>=0;A--){let[C,u]=this.#i[A];if(C!==d)break;if(C===d&&u===a){this.#i.splice(A,1);return}}}#c(d){let[a,f,A]=d,C=[[a,f,A]],u=this.#r(A);for(let y=0;y<u;y++){let[r,c]=this.#i[y];for(let b=0,w=C.length;b<w;b++){let[,P,E]=C[b];if(!(c<=P||E<=r))if(P>=r)if(E>c)C[b][1]=c;else{if(w===1)return[];C.splice(b,1),b--,w--}else C[b][2]=r,E>c&&C.push([a,c,E])}}return C}}class o{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(d,a){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof g}}class l extends o{#t;#e;constructor(d,a){super(),this.#e=d,this.#t=a}toSVGPath(){let d=[];for(let a of this.#e){let[f,A]=a;d.push(`M${f} ${A}`);for(let C=2;C<a.length;C+=2){let u=a[C],y=a[C+1];u===f?(d.push(`V${y}`),A=y):y===A&&(d.push(`H${u}`),f=u)}d.push("Z")}return d.join(" ")}serialize([d,a,f,A],C){let u=[],y=f-d,r=A-a;for(let c of this.#e){let b=new Array(c.length);for(let w=0;w<c.length;w+=2)b[w]=d+c[w]*y,b[w+1]=A-c[w+1]*r;u.push(b)}return u}get box(){return this.#t}}class h{#t;#e=[];#i;#n;#r=[];#s=new Float64Array(18);#o;#c;#a;#d;#p;#u;#l=[];static#f=8;static#g=2;static#h=h.#f+h.#g;constructor({x:d,y:a},f,A,C,u,y=0){this.#t=f,this.#u=C*A,this.#n=u,this.#s.set([NaN,NaN,NaN,NaN,d,a],6),this.#i=y,this.#d=h.#f*A,this.#a=h.#h*A,this.#p=A,this.#l.push(d,a)}get free(){return!0}isEmpty(){return isNaN(this.#s[8])}#b(){let d=this.#s.subarray(4,6),a=this.#s.subarray(16,18),[f,A,C,u]=this.#t;return[(this.#o+(d[0]-a[0])/2-f)/C,(this.#c+(d[1]-a[1])/2-A)/u,(this.#o+(a[0]-d[0])/2-f)/C,(this.#c+(a[1]-d[1])/2-A)/u]}add({x:d,y:a}){this.#o=d,this.#c=a;let[f,A,C,u]=this.#t,[y,r,c,b]=this.#s.subarray(8,12),w=d-c,P=a-b,E=Math.hypot(w,P);if(E<this.#a)return!1;let I=E-this.#d,N=I/E,z=N*w,H=N*P,X=y,it=r;y=c,r=b,c+=z,b+=H,this.#l?.push(d,a);let at=z/I,K=-H/I*this.#u,j=at*this.#u;return this.#s.set(this.#s.subarray(2,8),0),this.#s.set([c+K,b+j],4),this.#s.set(this.#s.subarray(14,18),12),this.#s.set([c-K,b-j],16),isNaN(this.#s[6])?(this.#r.length===0&&(this.#s.set([y+K,r+j],2),this.#r.push(NaN,NaN,NaN,NaN,(y+K-f)/C,(r+j-A)/u),this.#s.set([y-K,r-j],14),this.#e.push(NaN,NaN,NaN,NaN,(y-K-f)/C,(r-j-A)/u)),this.#s.set([X,it,y,r,c,b],6),!this.isEmpty()):(this.#s.set([X,it,y,r,c,b],6),Math.abs(Math.atan2(it-r,X-y)-Math.atan2(H,z))<Math.PI/2?([y,r,c,b]=this.#s.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((y+c)/2-f)/C,((r+b)/2-A)/u),[y,r,X,it]=this.#s.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((X+y)/2-f)/C,((it+r)/2-A)/u),!0):([X,it,y,r,c,b]=this.#s.subarray(0,6),this.#r.push(((X+5*y)/6-f)/C,((it+5*r)/6-A)/u,((5*y+c)/6-f)/C,((5*r+b)/6-A)/u,((y+c)/2-f)/C,((r+b)/2-A)/u),[c,b,y,r,X,it]=this.#s.subarray(12,18),this.#e.push(((X+5*y)/6-f)/C,((it+5*r)/6-A)/u,((5*y+c)/6-f)/C,((5*r+b)/6-A)/u,((y+c)/2-f)/C,((r+b)/2-A)/u),!0))}toSVGPath(){if(this.isEmpty())return"";let d=this.#r,a=this.#e,f=this.#s.subarray(4,6),A=this.#s.subarray(16,18),[C,u,y,r]=this.#t,[c,b,w,P]=this.#b();if(isNaN(this.#s[6])&&!this.isEmpty())return`M${(this.#s[2]-C)/y} ${(this.#s[3]-u)/r} L${(this.#s[4]-C)/y} ${(this.#s[5]-u)/r} L${c} ${b} L${w} ${P} L${(this.#s[16]-C)/y} ${(this.#s[17]-u)/r} L${(this.#s[14]-C)/y} ${(this.#s[15]-u)/r} Z`;let E=[];E.push(`M${d[4]} ${d[5]}`);for(let I=6;I<d.length;I+=6)isNaN(d[I])?E.push(`L${d[I+4]} ${d[I+5]}`):E.push(`C${d[I]} ${d[I+1]} ${d[I+2]} ${d[I+3]} ${d[I+4]} ${d[I+5]}`);E.push(`L${(f[0]-C)/y} ${(f[1]-u)/r} L${c} ${b} L${w} ${P} L${(A[0]-C)/y} ${(A[1]-u)/r}`);for(let I=a.length-6;I>=6;I-=6)isNaN(a[I])?E.push(`L${a[I+4]} ${a[I+5]}`):E.push(`C${a[I]} ${a[I+1]} ${a[I+2]} ${a[I+3]} ${a[I+4]} ${a[I+5]}`);return E.push(`L${a[4]} ${a[5]} Z`),E.join(" ")}getOutlines(){let d=this.#r,a=this.#e,f=this.#s,A=f.subarray(4,6),C=f.subarray(16,18),[u,y,r,c]=this.#t,b=new Float64Array((this.#l?.length??0)+2);for(let H=0,X=b.length-2;H<X;H+=2)b[H]=(this.#l[H]-u)/r,b[H+1]=(this.#l[H+1]-y)/c;b[b.length-2]=(this.#o-u)/r,b[b.length-1]=(this.#c-y)/c;let[w,P,E,I]=this.#b();if(isNaN(f[6])&&!this.isEmpty()){let H=new Float64Array(36);return H.set([NaN,NaN,NaN,NaN,(f[2]-u)/r,(f[3]-y)/c,NaN,NaN,NaN,NaN,(f[4]-u)/r,(f[5]-y)/c,NaN,NaN,NaN,NaN,w,P,NaN,NaN,NaN,NaN,E,I,NaN,NaN,NaN,NaN,(f[16]-u)/r,(f[17]-y)/c,NaN,NaN,NaN,NaN,(f[14]-u)/r,(f[15]-y)/c],0),new g(H,b,this.#t,this.#p,this.#i,this.#n)}let N=new Float64Array(this.#r.length+24+this.#e.length),z=d.length;for(let H=0;H<z;H+=2)isNaN(d[H])?N[H]=N[H+1]=NaN:(N[H]=d[H],N[H+1]=d[H+1]);N.set([NaN,NaN,NaN,NaN,(A[0]-u)/r,(A[1]-y)/c,NaN,NaN,NaN,NaN,w,P,NaN,NaN,NaN,NaN,E,I,NaN,NaN,NaN,NaN,(C[0]-u)/r,(C[1]-y)/c],z),z+=24;for(let H=a.length-6;H>=6;H-=6)for(let X=0;X<6;X+=2)isNaN(a[H+X])?(N[z]=N[z+1]=NaN,z+=2):(N[z]=a[H+X],N[z+1]=a[H+X+1],z+=2);return N.set([NaN,NaN,NaN,NaN,a[4],a[5]],z),new g(N,b,this.#t,this.#p,this.#i,this.#n)}}class g extends o{#t;#e=null;#i;#n;#r;#s;#o;constructor(d,a,f,A,C,u){super(),this.#o=d,this.#r=a,this.#t=f,this.#s=A,this.#i=C,this.#n=u,this.#d(u);let{x:y,y:r,width:c,height:b}=this.#e;for(let w=0,P=d.length;w<P;w+=2)d[w]=(d[w]-y)/c,d[w+1]=(d[w+1]-r)/b;for(let w=0,P=a.length;w<P;w+=2)a[w]=(a[w]-y)/c,a[w+1]=(a[w+1]-r)/b}toSVGPath(){let d=[`M${this.#o[4]} ${this.#o[5]}`];for(let a=6,f=this.#o.length;a<f;a+=6)isNaN(this.#o[a])?d.push(`L${this.#o[a+4]} ${this.#o[a+5]}`):d.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 d.push("Z"),d.join(" ")}serialize([d,a,f,A],C){let u=f-d,y=A-a,r,c;switch(C){case 0:r=this.#c(this.#o,d,A,u,-y),c=this.#c(this.#r,d,A,u,-y);break;case 90:r=this.#a(this.#o,d,a,u,y),c=this.#a(this.#r,d,a,u,y);break;case 180:r=this.#c(this.#o,f,a,-u,y),c=this.#c(this.#r,f,a,-u,y);break;case 270:r=this.#a(this.#o,f,A,-u,-y),c=this.#a(this.#r,f,A,-u,-y)}return{outline:Array.from(r),points:[Array.from(c)]}}#c(d,a,f,A,C){let u=new Float64Array(d.length);for(let y=0,r=d.length;y<r;y+=2)u[y]=a+d[y]*A,u[y+1]=f+d[y+1]*C;return u}#a(d,a,f,A,C){let u=new Float64Array(d.length);for(let y=0,r=d.length;y<r;y+=2)u[y]=a+d[y+1]*A,u[y+1]=f+d[y]*C;return u}#d(d){let a=this.#o,f=a[4],A=a[5],C=f,u=A,y=f,r=A,c=f,b=A,w=d?Math.max:Math.min;for(let z=6,H=a.length;z<H;z+=6){if(isNaN(a[z]))C=Math.min(C,a[z+4]),u=Math.min(u,a[z+5]),y=Math.max(y,a[z+4]),r=Math.max(r,a[z+5]),b<a[z+5]?(c=a[z+4],b=a[z+5]):b===a[z+5]&&(c=w(c,a[z+4]));else{let X=i.Util.bezierBoundingBox(f,A,...a.slice(z,z+6));C=Math.min(C,X[0]),u=Math.min(u,X[1]),y=Math.max(y,X[2]),r=Math.max(r,X[3]),b<X[3]?(c=X[2],b=X[3]):b===X[3]&&(c=w(c,X[2]))}f=a[z+4],A=a[z+5]}let P=C-this.#i,E=u-this.#i,I=y-C+2*this.#i,N=r-u+2*this.#i;this.#e={x:P,y:E,width:I,height:N,lastPoint:[c,b]}}get box(){return this.#e}getNewOutline(d,a){let{x:f,y:A,width:C,height:u}=this.#e,[y,r,c,b]=this.#t,w=C*c,P=u*b,E=f*c+y,I=A*b+r,N=new h({x:this.#r[0]*w+E,y:this.#r[1]*P+I},this.#t,this.#s,d,this.#n,a??this.#i);for(let z=2;z<this.#r.length;z+=2)N.add({x:this.#r[z]*w+E,y:this.#r[z+1]*P+I});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(h){this.#i=h}render(){let h=this.#t=document.createElement("div");h.className="editToolbar",h.setAttribute("role","toolbar"),h.addEventListener("contextmenu",i.noContextMenu),h.addEventListener("pointerdown",n.#r);let g=this.#n=document.createElement("div");g.className="buttons",h.append(g);let m=this.#i.toolbarPosition;if(m){let{style:d}=h,a=this.#i._uiManager.direction==="ltr"?1-m[0]:m[0];d.insetInlineEnd=100*a+"%",d.top=`calc(${100*m[1]}% + var(--editor-toolbar-vert-offset))`}return this.#a(),h}static#r(h){h.stopPropagation()}#s(h){this.#i._focusEventsAllowed=!1,h.preventDefault(),h.stopPropagation()}#o(h){this.#i._focusEventsAllowed=!0,h.preventDefault(),h.stopPropagation()}#c(h){h.addEventListener("focusin",this.#s.bind(this),{capture:!0}),h.addEventListener("focusout",this.#o.bind(this),{capture:!0}),h.addEventListener("contextmenu",i.noContextMenu)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden")}#a(){let h=document.createElement("button");h.className="delete",h.tabIndex=0,h.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#i.editorType}-button`),this.#c(h),h.addEventListener("click",(g=>{this.#i._uiManager.delete()})),this.#n.append(h)}get#d(){let h=document.createElement("div");return h.className="divider",h}addAltTextButton(h){this.#c(h),this.#n.prepend(h,this.#d)}addColorPicker(h){this.#e=h;let g=h.renderButton();this.#c(g),this.#n.prepend(g,this.#d)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class o{#t=null;#e=null;#i;constructor(h){this.#i=h}#n(){let h=this.#e=document.createElement("div");h.className="editToolbar",h.setAttribute("role","toolbar"),h.addEventListener("contextmenu",i.noContextMenu);let g=this.#t=document.createElement("div");return g.className="buttons",h.append(g),this.#s(),h}#r(h,g){let m=0,d=0;for(let a of h){let f=a.y+a.height;if(f<m)continue;let A=a.x+(g?a.width:0);f>m?(d=A,m=f):g?A>d&&(d=A):A<d&&(d=A)}return[g?1-d:d,m]}show(h,g,m){let[d,a]=this.#r(g,m),{style:f}=this.#e||=this.#n();h.append(this.#e),f.insetInlineEnd=100*d+"%",f.top=`calc(${100*a}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#s(){let h=document.createElement("button");h.className="highlightButton",h.tabIndex=0,h.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");let g=document.createElement("span");h.append(g),g.className="visuallyHidden",g.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label"),h.addEventListener("contextmenu",i.noContextMenu),h.addEventListener("click",(()=>{this.#i.highlightSelection("floating_button")})),this.#t.append(h)}}},830:(s,t,e)=>{e.d(t,{AnnotationEditorUIManager:()=>A,ColorManager:()=>f,KeyboardManager:()=>a,bindEvents:()=>l,opacityToHex:()=>h});var i=e(292),n=e(419),o=e(362);function l(C,u,y){for(let r of y)u.addEventListener(r,C[r].bind(C))}function h(C){return Math.round(Math.min(255,Math.max(1,255*C))).toString(16).padStart(2,"0")}class g{#t=0;constructor(){}get id(){return`${i.AnnotationEditorPrefix}${this.#t++}`}}class m{#t=(0,i.getUuid)();#e=0;#i=null;static get _isSVGFittingCanvas(){let u=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((()=>(u.drawImage(y,0,0,1,1,0,0,1,3),new Uint32Array(u.getImageData(0,0,1,1).data.buffer)[0]===0)));return(0,i.shadow)(this,"_isSVGFittingCanvas",r)}async#n(u,y){this.#i||=new Map;let r=this.#i.get(u);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 c;if(typeof y=="string"?(r.url=y,c=await(0,n.fetchData)(y,"blob")):c=r.file=y,c.type==="image/svg+xml"){let b=m._isSVGFittingCanvas,w=new FileReader,P=new Image,E=new Promise(((I,N)=>{P.onload=()=>{r.bitmap=P,r.isSvg=!0,I()},w.onload=async()=>{let z=r.svgUrl=w.result;P.src=await b?`${z}#svgView(preserveAspectRatio(none))`:z},P.onerror=w.onerror=N}));w.readAsDataURL(c),await E}else r.bitmap=await createImageBitmap(c);r.refCounter=1}catch(c){console.error(c),r=null}return this.#i.set(u,r),r&&this.#i.set(r.id,r),r}async getFromFile(u){let{lastModified:y,name:r,size:c,type:b}=u;return this.#n(`${y}_${r}_${c}_${b}`,u)}async getFromUrl(u){return this.#n(u,u)}async getFromId(u){this.#i||=new Map;let y=this.#i.get(u);return y?y.bitmap?(y.refCounter+=1,y):y.file?this.getFromFile(y.file):this.getFromUrl(y.url):null}getSvgUrl(u){let y=this.#i.get(u);return y?.isSvg?y.svgUrl:null}deleteId(u){this.#i||=new Map;let y=this.#i.get(u);y&&(y.refCounter-=1,y.refCounter===0&&(y.bitmap=null))}isValidId(u){return u.startsWith(`image_${this.#t}_`)}}class d{#t=[];#e=!1;#i;#n=-1;constructor(u=128){this.#i=u}add({cmd:u,undo:y,post:r,mustExec:c,type:b=NaN,overwriteIfSameType:w=!1,keepUndo:P=!1}){if(c&&u(),this.#e)return;let E={cmd:u,undo:y,post:r,type:b};if(this.#n===-1){this.#t.length>0&&(this.#t.length=0),this.#n=0,this.#t.push(E);return}if(w&&this.#t[this.#n].type===b){P&&(E.undo=this.#t[this.#n].undo),this.#t[this.#n]=E;return}let I=this.#n+1;I===this.#i?this.#t.splice(0,1):(this.#n=I,I<this.#t.length&&this.#t.splice(I)),this.#t.push(E)}undo(){if(this.#n===-1)return;this.#e=!0;let{undo:u,post:y}=this.#t[this.#n];u(),y?.(),this.#e=!1,this.#n-=1}redo(){if(this.#n<this.#t.length-1){this.#n+=1,this.#e=!0;let{cmd:u,post:y}=this.#t[this.#n];u(),y?.(),this.#e=!1}}hasSomethingToUndo(){return this.#n!==-1}hasSomethingToRedo(){return this.#n<this.#t.length-1}destroy(){this.#t=null}}class a{constructor(u){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:y}=i.FeatureTest.platform;for(let[r,c,b={}]of u)for(let w of r){let P=w.startsWith("mac+");y&&P?(this.callbacks.set(w.slice(4),{callback:c,options:b}),this.allKeys.add(w.split("+").at(-1))):!y&&!P&&(this.callbacks.set(w,{callback:c,options:b}),this.allKeys.add(w.split("+").at(-1)))}}#t(u){u.altKey&&this.buffer.push("alt"),u.ctrlKey&&this.buffer.push("ctrl"),u.metaKey&&this.buffer.push("meta"),u.shiftKey&&this.buffer.push("shift"),this.buffer.push(u.key);let y=this.buffer.join("+");return this.buffer.length=0,y}exec(u,y){if(!this.allKeys.has(y.key))return;let r=this.callbacks.get(this.#t(y));if(!r)return;let{callback:c,options:{bubbles:b=!1,args:w=[],checker:P=null}}=r;(!P||P(u,y))&&(c.bind(u,...w,y)(),b||(y.stopPropagation(),y.preventDefault()))}}class f{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let u=new Map([["CanvasText",null],["Canvas",null]]);return(0,n.getColorValues)(u),(0,i.shadow)(this,"_colors",u)}convert(u){let y=(0,n.getRGB)(u);if(!window.matchMedia("(forced-colors: active)").matches)return y;for(let[r,c]of this._colors)if(c.every(((b,w)=>b===y[w])))return f._colorsMapping.get(r);return y}getHexCode(u){let y=this._colors.get(u);return y?i.Util.makeHexColor(...y):u}}class A{#t=null;#e=new Map;#i=new Map;#n=null;#r=null;#s=new d;#o=0;#c=new Set;#a=null;#d=null;#p=new Set;#u=!1;#l=null;#f=null;#g=null;#h=!1;#b=null;#m=new g;#y=!1;#S=!1;#C=null;#I=null;#w=null;#x=i.AnnotationEditorType.NONE;#v=new Set;#E=null;#A=null;#_=null;#T=this.blur.bind(this);#k=this.focus.bind(this);#M=this.copy.bind(this);#P=this.cut.bind(this);#L=this.paste.bind(this);#R=this.keydown.bind(this);#F=this.keyup.bind(this);#O=this.onEditingAction.bind(this);#V=this.onPageChanging.bind(this);#G=this.onScaleChanging.bind(this);#H=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;#z=null;#K=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let u=A.prototype,y=w=>w.#z.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&w.hasSomethingToControl(),r=(w,{target:P})=>{if(P instanceof HTMLInputElement){let{type:E}=P;return E!=="text"&&E!=="number"}return!0},c=this.TRANSLATE_SMALL,b=this.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new a([[["ctrl+a","mac+meta+a"],u.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],u.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],u.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"],u.delete,{checker:r}],[["Enter","mac+Enter"],u.addNewEditorFromKeyboard,{checker:(w,{target:P})=>!(P instanceof HTMLButtonElement)&&w.#z.contains(P)&&!w.isEnterHandled}],[[" ","mac+ "],u.addNewEditorFromKeyboard,{checker:(w,{target:P})=>!(P instanceof HTMLButtonElement)&&w.#z.contains(document.activeElement)}],[["Escape","mac+Escape"],u.unselectAll],[["ArrowLeft","mac+ArrowLeft"],u.translateSelectedEditors,{args:[-c,0],checker:y}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],u.translateSelectedEditors,{args:[-b,0],checker:y}],[["ArrowRight","mac+ArrowRight"],u.translateSelectedEditors,{args:[c,0],checker:y}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],u.translateSelectedEditors,{args:[b,0],checker:y}],[["ArrowUp","mac+ArrowUp"],u.translateSelectedEditors,{args:[0,-c],checker:y}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],u.translateSelectedEditors,{args:[0,-b],checker:y}],[["ArrowDown","mac+ArrowDown"],u.translateSelectedEditors,{args:[0,c],checker:y}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],u.translateSelectedEditors,{args:[0,b],checker:y}]]))}constructor(u,y,r,c,b,w,P,E,I){this.#z=u,this.#K=y,this.#n=r,this._eventBus=c,this._eventBus._on("editingaction",this.#O),this._eventBus._on("pagechanging",this.#V),this._eventBus._on("scalechanging",this.#G),this._eventBus._on("rotationchanging",this.#U),this.#rt(),this.#J(),this.#r=b.annotationStorage,this.#l=b.filterFactory,this.#A=w,this.#g=P||null,this.#u=E,this.#w=I||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.#G),this._eventBus._off("rotationchanging",this.#U);for(let u of this.#i.values())u.destroy();this.#i.clear(),this.#e.clear(),this.#p.clear(),this.#t=null,this.#v.clear(),this.#s.destroy(),this.#n?.destroy(),this.#b?.hide(),this.#b=null,this.#f&&(clearTimeout(this.#f),this.#f=null),this.#B&&(clearTimeout(this.#B),this.#B=null),this.#ot()}async mlGuess(u){return this.#w?.guess(u)||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.#z).direction)}get highlightColors(){return(0,i.shadow)(this,"highlightColors",this.#g?new Map(this.#g.split(",").map((u=>u.split("=").map((y=>y.trim()))))):null)}get highlightColorNames(){return(0,i.shadow)(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(u=>u.reverse()))):null)}setMainHighlightColorPicker(u){this.#I=u}editAltText(u){this.#n?.editAltText(this,u)}onPageChanging({pageNumber:u}){this.#o=u-1}focusMainContainer(){this.#z.focus()}findParent(u,y){for(let r of this.#i.values()){let{x:c,y:b,width:w,height:P}=r.div.getBoundingClientRect();if(u>=c&&u<=c+w&&y>=b&&y<=b+P)return r}return null}disableUserSelect(u=!1){this.#K.classList.toggle("noUserSelect",u)}addShouldRescale(u){this.#p.add(u)}removeShouldRescale(u){this.#p.delete(u)}onScaleChanging({scale:u}){this.commitOrRemove(),this.viewParameters.realScale=u*n.PixelsPerInch.PDF_TO_CSS_UNITS;for(let y of this.#p)y.onScaleChanging()}onRotationChanging({pagesRotation:u}){this.commitOrRemove(),this.viewParameters.rotation=u}#q({anchorNode:u}){return u.nodeType===Node.TEXT_NODE?u.parentElement:u}highlightSelection(u=""){let y=document.getSelection();if(!y||y.isCollapsed)return;let{anchorNode:r,anchorOffset:c,focusNode:b,focusOffset:w}=y,P=y.toString(),E=this.#q(y).closest(".textLayer"),I=this.getSelectionBoxes(E);if(I){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(E)){N.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:u,boxes:I,anchorNode:r,anchorOffset:c,focusNode:b,focusOffset:w,text:P});break}}}#st(){let u=document.getSelection();if(!u||u.isCollapsed)return;let y=this.#q(u).closest(".textLayer"),r=this.getSelectionBoxes(y);r&&(this.#b||=new o.HighlightToolbar(this),this.#b.show(y,r,this.direction==="ltr"))}addToAnnotationStorage(u){u.isEmpty()||!this.#r||this.#r.has(u.id)||this.#r.setValue(u.id,u)}#nt(){let u=document.getSelection();if(!u||u.isCollapsed){this.#E&&(this.#b?.hide(),this.#E=null,this.#D({hasSelectedText:!1}));return}let{anchorNode:y}=u;if(y!==this.#E)if(this.#q(u).closest(".textLayer")){if(this.#b?.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.#h=this.isShiftKeyDown,!this.isShiftKeyDown)){let r=c=>{(c.type!=="pointerup"||c.button===0)&&(window.removeEventListener("pointerup",r),window.removeEventListener("blur",r),c.type==="pointerup"&&this.#X("main_toolbar"))};window.addEventListener("pointerup",r),window.addEventListener("blur",r)}}else this.#E&&(this.#b?.hide(),this.#E=null,this.#D({hasSelectedText:!1}))}#X(u=""){this.#x===i.AnnotationEditorType.HIGHLIGHT?this.highlightSelection(u):this.#u&&this.#st()}#rt(){document.addEventListener("selectionchange",this.#H)}#ot(){document.removeEventListener("selectionchange",this.#H)}#at(){window.addEventListener("focus",this.#k),window.addEventListener("blur",this.#T)}#Y(){window.removeEventListener("focus",this.#k),window.removeEventListener("blur",this.#T)}blur(){if(this.isShiftKeyDown=!1,this.#h&&(this.#h=!1,this.#X("main_toolbar")),!this.hasSelection)return;let{activeElement:u}=document;for(let y of this.#v)if(y.div.contains(u)){this.#C=[y,u],y._focusEventsAllowed=!1;break}}focus(){if(!this.#C)return;let[u,y]=this.#C;this.#C=null,y.addEventListener("focusin",(()=>{u._focusEventsAllowed=!0}),{once:!0}),y.focus()}#J(){window.addEventListener("keydown",this.#R),window.addEventListener("keyup",this.#F)}#Q(){window.removeEventListener("keydown",this.#R),window.removeEventListener("keyup",this.#F)}#Z(){document.addEventListener("copy",this.#M),document.addEventListener("cut",this.#P),document.addEventListener("paste",this.#L)}#tt(){document.removeEventListener("copy",this.#M),document.removeEventListener("cut",this.#P),document.removeEventListener("paste",this.#L)}addEditListeners(){this.#J(),this.#Z()}removeEditListeners(){this.#Q(),this.#tt()}copy(u){if(u.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let y=[];for(let r of this.#v){let c=r.serialize(!0);c&&y.push(c)}y.length!==0&&u.clipboardData.setData("application/pdfjs",JSON.stringify(y))}cut(u){this.copy(u),this.delete()}paste(u){u.preventDefault();let{clipboardData:y}=u;for(let b of y.items)for(let w of this.#d)if(w.isHandlingMimeForPasting(b.type)){w.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 c=this.currentLayer;try{let b=[];for(let E of r){let I=c.deserialize(E);if(!I)return;b.push(I)}let w=()=>{for(let E of b)this.#et(E);this.#it(b)},P=()=>{for(let E of b)E.remove()};this.addCommands({cmd:w,undo:P,mustExec:!0})}catch(b){(0,i.warn)(`paste: "${b.message}".`)}}keydown(u){this.isShiftKeyDown||u.key!=="Shift"||(this.isShiftKeyDown=!0),this.#x===i.AnnotationEditorType.NONE||this.isEditorHandlingKeyboard||A._keyboardManager.exec(this,u)}keyup(u){this.isShiftKeyDown&&u.key==="Shift"&&(this.isShiftKeyDown=!1,this.#h&&(this.#h=!1,this.#X("main_toolbar")))}onEditingAction({name:u}){switch(u){case"undo":case"redo":case"delete":case"selectAll":this[u]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#D(u){Object.entries(u).some((([y,r])=>this.#N[y]!==r))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#N,u)}),this.#x===i.AnnotationEditorType.HIGHLIGHT&&u.hasSelectedEditor===!1&&this.#$([[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]]))}#$(u){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:u})}setEditingState(u){u?(this.#at(),this.#Z(),this.#D({isEditing:this.#x!==i.AnnotationEditorType.NONE,isEmpty:this.#W(),hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:this.#s.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Y(),this.#tt(),this.#D({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(u){if(!this.#d){this.#d=u;for(let y of this.#d)this.#$(y.defaultPropertiesToUpdate)}}getId(){return this.#m.id}get currentLayer(){return this.#i.get(this.#o)}getLayer(u){return this.#i.get(u)}get currentPageIndex(){return this.#o}addLayer(u){this.#i.set(u.pageIndex,u),this.#y?u.enable():u.disable()}removeLayer(u){this.#i.delete(u.pageIndex)}updateMode(u,y=null,r=!1){if(this.#x!==u)if(this.#x=u,u!==i.AnnotationEditorType.NONE){this.setEditingState(!0),this.#lt(),this.unselectAll();for(let c of this.#i.values())c.updateMode(u);if(y||!r){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.#ct()}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(u){u!==this.#x&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:u})}updateParams(u,y){if(this.#d){switch(u){case i.AnnotationEditorParamsType.CREATE:this.currentLayer.addNewEditor();return;case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:this.#I?.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(u,y),this.showAllEditors("highlight",y)}for(let r of this.#v)r.updateParams(u,y);for(let r of this.#d)r.updateDefaultParams(u,y)}}showAllEditors(u,y,r=!1){for(let c of this.#e.values())c.editorType===u&&c.show(y);(this.#_?.get(i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==y&&this.#$([[i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,y]])}enableWaiting(u=!1){if(this.#S!==u){this.#S=u;for(let y of this.#i.values())u?y.disableClick():y.enableClick(),y.div.classList.toggle("waiting",u)}}#lt(){if(!this.#y){this.#y=!0;for(let u of this.#i.values())u.enable();for(let u of this.#e.values())u.enable()}}#ct(){if(this.unselectAll(),this.#y){this.#y=!1;for(let u of this.#i.values())u.disable();for(let u of this.#e.values())u.disable()}}getEditors(u){let y=[];for(let r of this.#e.values())r.pageIndex===u&&y.push(r);return y}getEditor(u){return this.#e.get(u)}addEditor(u){this.#e.set(u.id,u)}removeEditor(u){u.div.contains(document.activeElement)&&(this.#f&&clearTimeout(this.#f),this.#f=setTimeout((()=>{this.focusMainContainer(),this.#f=null}),0)),this.#e.delete(u.id),this.unselect(u),u.annotationElementId&&this.#c.has(u.annotationElementId)||this.#r?.remove(u.id)}addDeletedAnnotationElement(u){this.#c.add(u.annotationElementId),u.deleted=!0}isDeletedAnnotationElement(u){return this.#c.has(u)}removeDeletedAnnotationElement(u){this.#c.delete(u.annotationElementId),u.deleted=!1}#et(u){let y=this.#i.get(u.pageIndex);y?y.addOrRebuild(u):(this.addEditor(u),this.addToAnnotationStorage(u))}setActiveEditor(u){this.#t!==u&&(this.#t=u,u&&this.#$(u.propertiesToUpdate))}get#ht(){let u=null;for(u of this.#v);return u}updateUI(u){this.#ht===u&&this.#$(u.propertiesToUpdate)}toggleSelected(u){this.#v.has(u)?(this.#v.delete(u),u.unselect(),this.#D({hasSelectedEditor:this.hasSelection})):(this.#v.add(u),u.select(),this.#$(u.propertiesToUpdate),this.#D({hasSelectedEditor:!0}))}setSelected(u){for(let y of this.#v)y!==u&&y.unselect();this.#v.clear(),this.#v.add(u),u.select(),this.#$(u.propertiesToUpdate),this.#D({hasSelectedEditor:!0})}isSelected(u){return this.#v.has(u)}get firstSelectedEditor(){return this.#v.values().next().value}unselect(u){u.unselect(),this.#v.delete(u),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.#W()})}redo(){this.#s.redo(),this.#D({hasSomethingToUndo:!0,hasSomethingToRedo:this.#s.hasSomethingToRedo(),isEmpty:this.#W()})}addCommands(u){this.#s.add(u),this.#D({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#W()})}#W(){if(this.#e.size===0)return!0;if(this.#e.size===1)for(let u of this.#e.values())return u.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;let u=[...this.#v];this.addCommands({cmd:()=>{for(let y of u)y.remove()},undo:()=>{for(let y of u)this.#et(y)},mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#it(u){for(let y of this.#v)y.unselect();this.#v.clear();for(let y of u)y.isEmpty()||(this.#v.add(y),y.select());this.#D({hasSelectedEditor:this.hasSelection})}selectAll(){for(let u of this.#v)u.commit();this.#it(this.#e.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#x!==i.AnnotationEditorType.NONE))&&this.hasSelection){for(let u of this.#v)u.unselect();this.#v.clear(),this.#D({hasSelectedEditor:!1})}}translateSelectedEditors(u,y,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;this.#j[0]+=u,this.#j[1]+=y;let[c,b]=this.#j,w=[...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 P of w)this.#e.has(P.id)&&P.translateInPage(c,b)},undo:()=>{for(let P of w)this.#e.has(P.id)&&P.translateInPage(-c,-b)},mustExec:!1})}),1e3);for(let P of w)P.translateInPage(u,y)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#a=new Map;for(let u of this.#v)this.#a.set(u,{savedX:u.x,savedY:u.y,savedPageIndex:u.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#a)return!1;this.disableUserSelect(!1);let u=this.#a;this.#a=null;let y=!1;for(let[{x:c,y:b,pageIndex:w},P]of u)P.newX=c,P.newY=b,P.newPageIndex=w,y||=c!==P.savedX||b!==P.savedY||w!==P.savedPageIndex;if(!y)return!1;let r=(c,b,w,P)=>{if(this.#e.has(c.id)){let E=this.#i.get(P);E?c._setParentAndPosition(E,b,w):(c.pageIndex=P,c.x=b,c.y=w)}};return this.addCommands({cmd:()=>{for(let[c,{newX:b,newY:w,newPageIndex:P}]of u)r(c,b,w,P)},undo:()=>{for(let[c,{savedX:b,savedY:w,savedPageIndex:P}]of u)r(c,b,w,P)},mustExec:!0}),!0}dragSelectedEditors(u,y){if(this.#a)for(let r of this.#a.keys())r.drag(u,y)}rebuild(u){if(u.parent===null){let y=this.getLayer(u.pageIndex);y?(y.changeParent(u),y.addOrRebuild(u)):(this.addEditor(u),this.addToAnnotationStorage(u),u.rebuild())}else u.parent.addOrRebuild(u)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#v.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(u){return this.#t===u}getActive(){return this.#t}getMode(){return this.#x}get imageManager(){return(0,i.shadow)(this,"imageManager",new m)}getSelectionBoxes(u){if(!u)return null;let y=document.getSelection();for(let I=0,N=y.rangeCount;I<N;I++)if(!u.contains(y.getRangeAt(I).commonAncestorContainer))return null;let{x:r,y:c,width:b,height:w}=u.getBoundingClientRect(),P;switch(u.getAttribute("data-main-rotation")){case"90":P=(I,N,z,H)=>({x:(N-c)/w,y:1-(I+z-r)/b,width:H/w,height:z/b});break;case"180":P=(I,N,z,H)=>({x:1-(I+z-r)/b,y:1-(N+H-c)/w,width:z/b,height:H/w});break;case"270":P=(I,N,z,H)=>({x:1-(N+H-c)/w,y:(I-r)/b,width:H/w,height:z/b});break;default:P=(I,N,z,H)=>({x:(I-r)/b,y:(N-c)/w,width:z/b,height:H/w})}let E=[];for(let I=0,N=y.rangeCount;I<N;I++){let z=y.getRangeAt(I);if(!z.collapsed)for(let{x:H,y:X,width:it,height:at}of z.getClientRects())it!==0&&at!==0&&E.push(P(H,X,it,at))}return E.length===0?null:E}}},94:(s,t,e)=>{e.d(t,{PDFFetchStream:()=>g});var i=e(292),n=e(490);function o(a,f,A){return{method:"GET",headers:a,signal:A.signal,mode:"cors",credentials:f?"include":"same-origin",redirect:"follow"}}function l(a){let f=new Headers;for(let A in a){let C=a[A];C!==void 0&&f.append(A,C)}return f}function h(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:((0,i.warn)(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class g{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,A){if(A<=this._progressiveDataLength)return null;let C=new d(this,f,A);return this._rangeRequestReaders.push(C),C}cancelAllRequests(f){this._fullRequestReader?.cancel(f);for(let A of this._rangeRequestReaders.slice(0))A.cancel(f)}}class m{constructor(f){this._stream=f,this._reader=null,this._loaded=0,this._filename=null;let A=f.source;this._withCredentials=A.withCredentials||!1,this._contentLength=A.length,this._headersCapability=Promise.withResolvers(),this._disableRange=A.disableRange||!1,this._rangeChunkSize=A.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!A.disableStream,this._isRangeSupported=!A.disableRange,this._headers=l(this._stream.httpHeaders);let C=A.url;fetch(C,o(this._headers,this._withCredentials,this._abortController)).then((u=>{if(!(0,n.validateResponseStatus)(u.status))throw(0,n.createResponseStatusError)(u.status,C);this._reader=u.body.getReader(),this._headersCapability.resolve();let y=b=>u.headers.get(b),{allowRangeRequests:r,suggestedLength:c}=(0,n.validateRangeRequestCapabilities)({getResponseHeader:y,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=c||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:A}=await this._reader.read();return A?{value:f,done:A}:(this._loaded+=f.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:h(f),done:!1})}cancel(f){this._reader?.cancel(f),this._abortController.abort()}}class d{constructor(f,A,C){this._stream=f,this._reader=null,this._loaded=0;let u=f.source;this._withCredentials=u.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!u.disableStream,this._abortController=new AbortController,this._headers=l(this._stream.httpHeaders),this._headers.append("Range",`bytes=${A}-${C-1}`);let y=u.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:A}=await this._reader.read();return A?{value:f,done:A}:(this._loaded+=f.byteLength,this.onProgress?.({loaded:this._loaded}),{value:h(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:h=globalThis.document,styleElement:g=null}){this._document=h,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(h){this.nativeFontFaces.add(h),this._document.fonts.add(h)}removeNativeFontFace(h){this.nativeFontFaces.delete(h),this._document.fonts.delete(h)}insertRule(h){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));let g=this.styleElement.sheet;g.insertRule(h,g.cssRules.length)}clear(){for(let h of this.nativeFontFaces)this._document.fonts.delete(h);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:h,_inspectFont:g}){if(h&&!this.#t.has(h.loadedName))if((0,i.assert)(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:m,src:d,style:a}=h,f=new FontFace(m,d,a);this.addNativeFontFace(f);try{await f.load(),this.#t.add(m),g?.(h)}catch{(0,i.warn)(`Cannot load system font: ${h.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(h){if(h.attached||h.missingFile&&!h.systemFontInfo)return;if(h.attached=!0,h.systemFontInfo){await this.loadSystemFont(h);return}if(this.isFontLoadingAPISupported){let m=h.createNativeFontFace();if(m){this.addNativeFontFace(m);try{await m.loaded}catch(d){throw(0,i.warn)(`Failed to load font '${m.family}': '${d}'.`),h.disableFontFace=!0,d}}return}let g=h.createFontFaceRule();if(g){if(this.insertRule(g),this.isSyncFontLoadingSupported)return;await new Promise((m=>{let d=this._queueLoadingCallback(m);this._prepareFontLoadEvent(h,d)}))}}get isFontLoadingAPISupported(){let h=!!this._document?.fonts;return(0,i.shadow)(this,"isFontLoadingAPISupported",h)}get isSyncFontLoadingSupported(){let h=!1;return(i.isNodeJS||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(h=!0),(0,i.shadow)(this,"isSyncFontLoadingSupported",h)}_queueLoadingCallback(h){let{loadingRequests:g}=this,m={done:!1,complete:function(){for((0,i.assert)(!m.done,"completeRequest() cannot be called twice."),m.done=!0;g.length>0&&g[0].done;){let a=g.shift();setTimeout(a.callback,0)}},callback:h};return g.push(m),m}get _loadTestFont(){let h=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return(0,i.shadow)(this,"_loadTestFont",h)}_prepareFontLoadEvent(h,g){function m(E,I){return E.charCodeAt(I)<<24|E.charCodeAt(I+1)<<16|E.charCodeAt(I+2)<<8|255&E.charCodeAt(I+3)}function d(E,I,N,z){return E.substring(0,I)+z+E.substring(I+N)}let a,f,A=this._document.createElement("canvas");A.width=1,A.height=1;let C=A.getContext("2d"),u=0,y=`lt${Date.now()}${this.loadTestFontId++}`,r=this._loadTestFont;r=d(r,976,y.length,y);let c=1482184792,b=m(r,16);for(a=0,f=y.length-3;a<f;a+=4)b=b-c+m(y,a)|0;a<y.length&&(b=b-c+m(y+"XXX",a)|0),r=d(r,16,4,(0,i.string32)(b));let w=`@font-face {font-family:"${y}";src:${`url(data:font/opentype;base64,${btoa(r)});`}}`;this.insertRule(w);let P=this._document.createElement("div");P.style.visibility="hidden",P.style.width=P.style.height="10px",P.style.position="absolute",P.style.top=P.style.left="0px";for(let E of[h.loadedName,y]){let I=this._document.createElement("span");I.textContent="Hi",I.style.fontFamily=E,P.append(I)}this._document.body.append(P),(function E(I,N){if(++u>30){(0,i.warn)("Load test font never loaded."),N();return}C.font="30px "+I,C.fillText(".",0,20),C.getImageData(0,0,1,1).data[3]>0?N():setTimeout(E.bind(null,I,N))})(y,(()=>{P.remove(),g.complete()}))}}class o{constructor(h,{isEvalSupported:g=!0,disableFontFace:m=!1,ignoreErrors:d=!1,inspectFont:a=null}){this.compiledGlyphs=Object.create(null);for(let f in h)this[f]=h[f];this.isEvalSupported=g!==!1,this.disableFontFace=m===!0,this.ignoreErrors=d===!0,this._inspectFont=a}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let h;if(this.cssFontInfo){let g={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(g.style=`oblique ${this.cssFontInfo.italicAngle}deg`),h=new FontFace(this.cssFontInfo.fontFamily,this.data,g)}else h=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),h}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let h=(0,i.bytesToString)(this.data),g=`url(data:${this.mimetype};base64,${btoa(h)});`,m;if(this.cssFontInfo){let d=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(d+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),m=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${d}src:${g}}`}else m=`@font-face {font-family:"${this.loadedName}";src:${g}}`;return this._inspectFont?.(this,g),m}getPathGenerator(h,g){if(this.compiledGlyphs[g]!==void 0)return this.compiledGlyphs[g];let m;try{m=h.get(this.loadedName+"_path_"+g)}catch(d){if(!this.ignoreErrors)throw d;return(0,i.warn)(`getPathGenerator - ignoring character: "${d}".`),this.compiledGlyphs[g]=function(a,f){}}if(this.isEvalSupported&&i.FeatureTest.isEvalSupported){let d=[];for(let a of m){let f=a.args!==void 0?a.args.join(","):"";d.push("c.",a.cmd,"(",f,`);
|
|
13
|
-
`)}return this.compiledGlyphs[g]=new Function("c","size",d.join(""))}return this.compiledGlyphs[g]=function(d,a){for(let f of m)f.cmd==="scale"&&(f.args=[a,-a]),d[f.cmd].apply(d,f.args)}}}},62:(s,t,e)=>{e.d(t,{Metadata:()=>n});var i=e(292);class n{#t;#e;constructor({parsedData:l,rawData:h}){this.#t=l,this.#e=h}getRaw(){return this.#e}get(l){return this.#t.get(l)??null}getAll(){return(0,i.objectFromMap)(this.#t)}has(l){return this.#t.has(l)}}},457:(s,t,e)=>{e.d(t,{PDFNetworkStream:()=>l});var i=e(292),n=e(490);class o{constructor(d,a={}){this.url=d,this.isHttp=/^https?:/i.test(d),this.httpHeaders=this.isHttp&&a.httpHeaders||Object.create(null),this.withCredentials=a.withCredentials||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(d,a,f){let A={begin:d,end:a};for(let C in f)A[C]=f[C];return this.request(A)}requestFull(d){return this.request(d)}request(d){let a=new XMLHttpRequest,f=this.currXhrId++,A=this.pendingRequests[f]={xhr:a};a.open("GET",this.url),a.withCredentials=this.withCredentials;for(let C in this.httpHeaders){let u=this.httpHeaders[C];u!==void 0&&a.setRequestHeader(C,u)}return this.isHttp&&"begin"in d&&"end"in d?(a.setRequestHeader("Range",`bytes=${d.begin}-${d.end-1}`),A.expectedStatus=206):A.expectedStatus=200,a.responseType="arraybuffer",d.onError&&(a.onerror=function(C){d.onError(a.status)}),a.onreadystatechange=this.onStateChange.bind(this,f),a.onprogress=this.onProgress.bind(this,f),A.onHeadersReceived=d.onHeadersReceived,A.onDone=d.onDone,A.onError=d.onError,A.onProgress=d.onProgress,a.send(null),f}onProgress(d,a){let f=this.pendingRequests[d];f&&f.onProgress?.(a)}onStateChange(d,a){let f=this.pendingRequests[d];if(!f)return;let A=f.xhr;if(A.readyState>=2&&f.onHeadersReceived&&(f.onHeadersReceived(),delete f.onHeadersReceived),A.readyState!==4||!(d in this.pendingRequests))return;if(delete this.pendingRequests[d],A.status===0&&this.isHttp){f.onError?.(A.status);return}let C=A.status||200;if(!(C===200&&f.expectedStatus===206)&&C!==f.expectedStatus){f.onError?.(A.status);return}let u=(function(r){let c=r.response;return typeof c!="string"?c:(0,i.stringToBytes)(c).buffer})(A);if(C===206){let y=A.getResponseHeader("Content-Range"),r=/bytes (\d+)-(\d+)\/(\d+)/.exec(y);f.onDone({begin:parseInt(r[1],10),chunk:u})}else u?f.onDone({begin:0,chunk:u}):f.onError?.(A.status)}getRequestXhr(d){return this.pendingRequests[d].xhr}isPendingRequest(d){return d in this.pendingRequests}abortRequest(d){let a=this.pendingRequests[d].xhr;delete this.pendingRequests[d],a.abort()}}class l{constructor(d){this._source=d,this._manager=new o(d.url,{httpHeaders:d.httpHeaders,withCredentials:d.withCredentials}),this._rangeChunkSize=d.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(d){let a=this._rangeRequestReaders.indexOf(d);a>=0&&this._rangeRequestReaders.splice(a,1)}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new h(this._manager,this._source),this._fullRequestReader}getRangeReader(d,a){let f=new g(this._manager,d,a);return f.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(f),f}cancelAllRequests(d){this._fullRequestReader?.cancel(d);for(let a of this._rangeRequestReaders.slice(0))a.cancel(d)}}class h{constructor(d,a){this._manager=d;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=d.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 d=this._fullRequestId,a=this._manager.getRequestXhr(d),f=u=>a.getResponseHeader(u),{allowRangeRequests:A,suggestedLength:C}=(0,n.validateRangeRequestCapabilities)({getResponseHeader:f,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});A&&(this._isRangeSupported=!0),this._contentLength=C||this._contentLength,this._filename=(0,n.extractFilenameFromHeader)(f),this._isRangeSupported&&this._manager.abortRequest(d),this._headersReceivedCapability.resolve()}_onDone(d){if(d&&(this._requests.length>0?this._requests.shift().resolve({value:d.chunk,done:!1}):this._cachedChunks.push(d.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(d){this._storedError=(0,n.createResponseStatusError)(d,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(d){this.onProgress?.({loaded:d.loaded,total:d.lengthComputable?d.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 d=Promise.withResolvers();return this._requests.push(d),d.promise}cancel(d){this._done=!0,this._headersReceivedCapability.reject(d);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 g{constructor(d,a,f){this._manager=d;let A={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=d.url,this._requestId=d.requestRange(a,f,A),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(d){let a=d.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(d){this._storedError=(0,n.createResponseStatusError)(d,this._url);for(let a of this._requests)a.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(d){this.isStreamingSupported||this.onProgress?.({loaded:d.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 d=Promise.withResolvers();return this._requests.push(d),d.promise}cancel(d){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:()=>h,extractFilenameFromHeader:()=>l,validateRangeRequestCapabilities:()=>o,validateResponseStatus:()=>g});var i=e(292),n=e(419);function o({getResponseHeader:m,isHttp:d,rangeChunkSize:a,disableRange:f}){let A={allowRangeRequests:!1,suggestedLength:void 0},C=parseInt(m("Content-Length"),10);return!Number.isInteger(C)||(A.suggestedLength=C,C<=2*a)||f||!d||m("Accept-Ranges")!=="bytes"||(m("Content-Encoding")||"identity")!=="identity"||(A.allowRangeRequests=!0),A}function l(m){let d=m("Content-Disposition");if(d){let a=(function(A){let C=!0,u=y("filename\\*","i").exec(A);if(u){u=u[1];let E=b(u);return E=unescape(E),E=w(E),E=P(E),c(E)}if(u=(function(I){let N=[],z,H=y("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(z=H.exec(I))!==null;){let[,it,at,K]=z;if(it=parseInt(it,10),it in N){if(it===0)break}else N[it]=[at,K]}let X=[];for(let it=0;it<N.length&&it in N;++it){let[at,K]=N[it];K=b(K),at&&(K=unescape(K),it===0&&(K=w(K))),X.push(K)}return X.join("")})(A),u)return c(P(u));if(u=y("filename","i").exec(A),u){u=u[1];let E=b(u);return E=P(E),c(E)}function y(E,I){return new RegExp("(?:^|;)\\s*"+E+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',I)}function r(E,I){if(E){if(!/^[\x00-\xFF]+$/.test(I))return I;try{let N=new TextDecoder(E,{fatal:!0}),z=(0,i.stringToBytes)(I);I=N.decode(z),C=!1}catch{}}return I}function c(E){return C&&/[\x80-\xff]/.test(E)&&(E=r("utf-8",E),C&&(E=r("iso-8859-1",E))),E}function b(E){if(E.startsWith('"')){let I=E.slice(1).split('\\"');for(let N=0;N<I.length;++N){let z=I[N].indexOf('"');z!==-1&&(I[N]=I[N].slice(0,z),I.length=N+1),I[N]=I[N].replaceAll(/\\(.)/g,"$1")}E=I.join('"')}return E}function w(E){let I=E.indexOf("'");return I===-1?E:r(E.slice(0,I),E.slice(I+1).replace(/^[^']*'/,""))}function P(E){return!E.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(E)?E:E.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(I,N,z,H){if(z==="q"||z==="Q")return r(N,H=(H=H.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(X,it){return String.fromCharCode(parseInt(it,16))})));try{H=atob(H)}catch{}return r(N,H)}))}return""})(d);if(a.includes("%"))try{a=decodeURIComponent(a)}catch{}if((0,n.isPdfFile)(a))return a}return null}function h(m,d){return m===404||m===0&&d.startsWith("file:")?new i.MissingPDFException('Missing PDF "'+d+'".'):new i.UnexpectedResponseException(`Unexpected server response (${m}) while retrieving PDF "${d}".`,m)}function g(m){return m===200||m===206}},786:(s,t,e)=>{e.a(s,(async(i,n)=>{try{let f=function(P){let E=d.parse(P);return E.protocol==="file:"||E.host?E:/^[a-z]:[/\\]/i.test(P)?d.parse(`file:///${P}`):(E.host||(E.protocol="file:"),E)},y=function(P,E){return{protocol:P.protocol,auth:P.auth,host:P.hostname,port:P.port,path:P.path,method:"GET",headers:E}};e.d(t,{PDFNodeStream:()=>A});var o=e(292),l=e(490);let h,g,m,d;o.isNodeJS&&(h=await Promise.resolve().then(()=>(rl(),nl)),g=await Promise.resolve().then(()=>(wh(),vh)),m=await Promise.resolve().then(()=>(Ah(),xh)),d=await Promise.resolve().then(()=>(Eh(),Sh)));let a=/^file:\/\/\/[a-zA-Z]:\//;class A{constructor(E){this.source=E,this.url=f(E.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&E.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(E,I){if(I<=this._progressiveDataLength)return null;let N=this.isFsUrl?new w(this,E,I):new c(this,E,I);return this._rangeRequestReaders.push(N),N}cancelAllRequests(E){this._fullRequestReader?.cancel(E);for(let I of this._rangeRequestReaders.slice(0))I.cancel(E)}}class C{constructor(E){this._url=E.url,this._done=!1,this._storedError=null,this.onProgress=null;let I=E.source;this._contentLength=I.length,this._loaded=0,this._filename=null,this._disableRange=I.disableRange||!1,this._rangeChunkSize=I.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!I.disableStream,this._isRangeSupported=!I.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 E=this._readableStream.read();return E===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=E.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(E).buffer,done:!1})}cancel(E){this._readableStream?this._readableStream.destroy(E):this._error(E)}_error(E){this._storedError=E,this._readCapability.resolve()}_setReadableStream(E){this._readableStream=E,E.on("readable",(()=>{this._readCapability.resolve()})),E.on("end",(()=>{E.destroy(),this._done=!0,this._readCapability.resolve()})),E.on("error",(I=>{this._error(I)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new o.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class u{constructor(E){this._url=E.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let I=E.source;this._isStreamingSupported=!I.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 E=this._readableStream.read();return E===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=E.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(E).buffer,done:!1})}cancel(E){this._readableStream?this._readableStream.destroy(E):this._error(E)}_error(E){this._storedError=E,this._readCapability.resolve()}_setReadableStream(E){this._readableStream=E,E.on("readable",(()=>{this._readCapability.resolve()})),E.on("end",(()=>{E.destroy(),this._done=!0,this._readCapability.resolve()})),E.on("error",(I=>{this._error(I)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class r extends C{constructor(E){super(E);let I=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 z=it=>this._readableStream.headers[it.toLowerCase()],{allowRangeRequests:H,suggestedLength:X}=(0,l.validateRangeRequestCapabilities)({getResponseHeader:z,isHttp:E.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=H,this._contentLength=X||this._contentLength,this._filename=(0,l.extractFilenameFromHeader)(z)};this._request=null,this._url.protocol==="http:"?this._request=g.request(y(this._url,E.httpHeaders),I):this._request=m.request(y(this._url,E.httpHeaders),I),this._request.on("error",(N=>{this._storedError=N,this._headersCapability.reject(N)})),this._request.end()}}class c extends u{constructor(E,I,N){super(E),this._httpHeaders={};for(let H in E.httpHeaders){let X=E.httpHeaders[H];X!==void 0&&(this._httpHeaders[H]=X)}this._httpHeaders.Range=`bytes=${I}-${N-1}`;let z=H=>{if(H.statusCode!==404)this._setReadableStream(H);else{let X=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=X}};this._request=null,this._url.protocol==="http:"?this._request=g.request(y(this._url,this._httpHeaders),z):this._request=m.request(y(this._url,this._httpHeaders),z),this._request.on("error",(H=>{this._storedError=H})),this._request.end()}}class b extends C{constructor(E){super(E);let I=decodeURIComponent(this._url.path);a.test(this._url.href)&&(I=I.replace(/^\//,"")),h.promises.lstat(I).then((N=>{this._contentLength=N.size,this._setReadableStream(h.createReadStream(I)),this._headersCapability.resolve()}),(N=>{N.code==="ENOENT"&&(N=new o.MissingPDFException(`Missing PDF "${I}".`)),this._storedError=N,this._headersCapability.reject(N)}))}}class w extends u{constructor(E,I,N){super(E);let z=decodeURIComponent(this._url.path);a.test(this._url.href)&&(z=z.replace(/^\//,"")),this._setReadableStream(h.createReadStream(z,{start:I,end:N-1}))}}n()}catch(h){n(h)}}),1)},573:(s,t,e)=>{e.a(s,(async(i,n)=>{try{e.d(t,{NodeCMapReaderFactory:()=>f,NodeCanvasFactory:()=>a,NodeFilterFactory:()=>d,NodeStandardFontDataFactory:()=>A});var o=e(583);let l,h,g;if(e(292).isNodeJS){l=await Promise.resolve().then(()=>(rl(),nl));try{h=await Promise.resolve().then(()=>(_h(),Ch))}catch{}try{g=await Promise.resolve().then(()=>(Th(),kh))}catch{}}let m=function(C){return l.promises.readFile(C).then((u=>new Uint8Array(u)))};class d extends o.BaseFilterFactory{}class a extends o.BaseCanvasFactory{_createCanvas(u,y){return h.createCanvas(u,y)}}class f extends o.BaseCMapReaderFactory{_fetchData(u,y){return m(u).then((r=>({cMapData:r,compressionType:y})))}}class A extends o.BaseStandardFontDataFactory{_fetchData(u){return m(u)}}n()}catch(l){n(l)}}),1)},626:(s,t,e)=>{e.d(t,{OptionalContentConfig:()=>h});var i=e(292),n=e(651);let o=Symbol("INTERNAL");class l{#t=!1;#e=!1;#i=!1;#n=!0;constructor(m,{name:d,intent:a,usage:f}){this.#t=!!(m&i.RenderingIntentFlag.DISPLAY),this.#e=!!(m&i.RenderingIntentFlag.PRINT),this.name=d,this.intent=a,this.usage=f}get visible(){if(this.#i)return this.#n;if(!this.#n)return!1;let{print:m,view:d}=this.usage;return this.#t?d?.viewState!=="OFF":!this.#e||m?.printState!=="OFF"}_setVisible(m,d,a=!1){m!==o&&(0,i.unreachable)("Internal method `_setVisible` called."),this.#i=a,this.#n=d}}class h{#t=null;#e=new Map;#i=null;#n=null;constructor(m,d=i.RenderingIntentFlag.DISPLAY){if(this.renderingIntent=d,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 l(d,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 d=m.length;if(d<2)return!0;let a=m[0];for(let f=1;f<d;f++){let A=m[f],C;if(Array.isArray(A))C=this.#r(A);else{if(!this.#e.has(A))return(0,i.warn)(`Optional content group not found: ${A}`),!0;C=this.#e.get(A).visible}switch(a){case"And":if(!C)return!1;break;case"Or":if(C)return!0;break;case"Not":return!C;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 d of m.ids){if(!this.#e.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(this.#e.get(d).visible)return!0}return!1}if(m.policy==="AllOn"){for(let d of m.ids){if(!this.#e.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(!this.#e.get(d).visible)return!1}return!0}if(m.policy==="AnyOff"){for(let d of m.ids){if(!this.#e.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(!this.#e.get(d).visible)return!0}return!1}if(m.policy==="AllOff"){for(let d of m.ids){if(!this.#e.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(this.#e.get(d).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,d=!0){let a=this.#e.get(m);a?(a._setVisible(o,!!d,!0),this.#t=null):(0,i.warn)(`Optional content group not found: ${m}`)}setOCGState({state:m,preserveRB:d}){let a;for(let f of m){switch(f){case"ON":case"OFF":case"Toggle":a=f;continue}let A=this.#e.get(f);if(A)switch(a){case"ON":A._setVisible(o,!0);break;case"OFF":A._setVisible(o,!1);break;case"Toggle":A._setVisible(o,!A.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[d,a]of this.#e)m.update(`${d}:${a.visible}`);return this.#t=m.hexdigest()}}},814:(s,t,e)=>{e.d(t,{cleanupTextLayer:()=>d,renderTextLayer:()=>C,updateTextLayer:()=>u});var i=e(292),n=e(419);let o=30,l=.8,h=new Map,g=null;function m(){if(!g){let y=document.createElement("canvas");y.className="hiddenCanvasElement",document.body.append(y),g=y.getContext("2d",{alpha:!1})}return g}function d(){g?.canvas.remove(),g=null}function a(y,r,c){let b=document.createElement("span"),w={angle:0,canvasWidth:0,hasText:r.str!=="",hasEOL:r.hasEOL,fontSize:0};y._textDivs.push(b);let P=i.Util.transform(y._transform,r.transform),E=Math.atan2(P[1],P[0]),I=c[r.fontName];I.vertical&&(E+=Math.PI/2);let N=y._fontInspectorEnabled&&I.fontSubstitution||I.fontFamily,z=Math.hypot(P[2],P[3]),H=z*(function(Y){let et=h.get(Y);if(et)return et;let rt=m(),ct=rt.font;rt.canvas.width=rt.canvas.height=o,rt.font=`${o}px ${Y}`;let st=rt.measureText(""),W=st.fontBoundingBoxAscent,x=Math.abs(st.fontBoundingBoxDescent);if(W){let R=W/(W+x);return h.set(Y,R),rt.canvas.width=rt.canvas.height=0,rt.font=ct,R}rt.strokeStyle="red",rt.clearRect(0,0,o,o),rt.strokeText("g",0,0);let T=rt.getImageData(0,0,o,o).data;x=0;for(let R=T.length-1-3;R>=0;R-=4)if(T[R]>0){x=Math.ceil(R/4/o);break}rt.clearRect(0,0,o,o),rt.strokeText("A",0,o),T=rt.getImageData(0,0,o,o).data,W=0;for(let R=0,p=T.length;R<p;R+=4)if(T[R]>0){W=o-Math.floor(R/4/o);break}if(rt.canvas.width=rt.canvas.height=0,rt.font=ct,W){let R=W/(W+x);return h.set(Y,R),R}return h.set(Y,l),l})(N),X,it;E===0?(X=P[4],it=P[5]-H):(X=P[4]+H*Math.sin(E),it=P[5]-H*Math.cos(E));let at="calc(var(--scale-factor)*",K=b.style;y._container===y._rootContainer?(K.left=`${(100*X/y._pageWidth).toFixed(2)}%`,K.top=`${(100*it/y._pageHeight).toFixed(2)}%`):(K.left=`${at}${X.toFixed(2)}px)`,K.top=`${at}${it.toFixed(2)}px)`),K.fontSize=`${at}${z.toFixed(2)}px)`,K.fontFamily=N,w.fontSize=z,b.setAttribute("role","presentation"),b.textContent=r.str,b.dir=r.dir,y._fontInspectorEnabled&&(b.dataset.fontName=I.fontSubstitutionLoadedName||r.fontName),E!==0&&(w.angle=E*(180/Math.PI));let j=!1;if(r.str.length>1)j=!0;else if(r.str!==" "&&r.transform[0]!==r.transform[3]){let G=Math.abs(r.transform[0]),Y=Math.abs(r.transform[3]);G!==Y&&Math.max(G,Y)/Math.min(G,Y)>1.5&&(j=!0)}j&&(w.canvasWidth=I.vertical?r.height:r.width),y._textDivProperties.set(b,w),y._isReadableStream&&y._layoutText(b)}function f(y){let{div:r,scale:c,properties:b,ctx:w,prevFontSize:P,prevFontFamily:E}=y,{style:I}=r,N="";if(b.canvasWidth!==0&&b.hasText){let{fontFamily:z}=I,{canvasWidth:H,fontSize:X}=b;(P!==X||E!==z)&&(w.font=`${X*c}px ${z}`,y.prevFontSize=X,y.prevFontFamily=z);let{width:it}=w.measureText(r.textContent);it>0&&(N=`scaleX(${H*c/it})`)}b.angle!==0&&(N=`rotate(${b.angle}deg) ${N}`),N.length>0&&(I.transform=N)}class A{constructor({textContentSource:r,container:c,viewport:b,textDivs:w,textDivProperties:P,textContentItemsStr:E}){this._textContentSource=r,this._isReadableStream=r instanceof ReadableStream,this._container=this._rootContainer=c,this._textDivs=w||[],this._textContentItemsStr=E||[],this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled,this._reader=null,this._textDivProperties=P||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:I,pageHeight:N,pageX:z,pageY:H}=b.rawDims;this._transform=[1,0,0,-1,-z,H+N],this._pageWidth=I,this._pageHeight=N,(0,n.setLayerDimensions)(c,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,c){for(let b of r)if(b.str!==void 0)this._textContentItemsStr.push(b.str),a(this,b,c);else if(b.type==="beginMarkedContentProps"||b.type==="beginMarkedContent"){let w=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),b.id!==null&&this._container.setAttribute("id",`${b.id}`),w.append(this._container)}else b.type==="endMarkedContent"&&(this._container=this._container.parentNode)}_layoutText(r){let c=this._layoutTextParams.properties=this._textDivProperties.get(r);if(this._layoutTextParams.div=r,f(this._layoutTextParams),c.hasText&&this._container.append(r),c.hasEOL){let b=document.createElement("br");b.setAttribute("role","presentation"),this._container.append(b)}}_render(){let{promise:r,resolve:c,reject:b}=Promise.withResolvers(),w=Object.create(null);if(this._isReadableStream){let P=()=>{this._reader.read().then((({value:E,done:I})=>{I?c():(Object.assign(w,E.styles),this._processItems(E.items,w),P())}),b)};this._reader=this._textContentSource.getReader(),P()}else{if(!this._textContentSource)throw new Error('No "textContentSource" parameter specified.');{let{items:P,styles:E}=this._textContentSource;this._processItems(P,E),c()}}r.then((()=>{w=null,(function(E){if(E._canceled)return;let I=E._textDivs,N=E._capability;if(I.length>1e5)N.resolve();else{if(!E._isReadableStream)for(let z of I)E._layoutText(z);N.resolve()}})(this)}),this._capability.reject)}}function C(y){let r=new A(y);return r._render(),r}function u({container:y,viewport:r,textDivs:c,textDivProperties:b,mustRotate:w=!0,mustRescale:P=!0}){if(w&&(0,n.setLayerDimensions)(y,{rotation:r.rotation}),P){let E=m(),I={prevFontSize:null,prevFontFamily:null,div:null,scale:r.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:E};for(let N of c)I.properties=b.get(N),I.div=N,f(I)}}},585:(s,t,e)=>{e.d(t,{PDFDataTransportStream:()=>o});var i=e(292),n=e(419);class o{constructor(m,{disableRange:d=!1,disableStream:a=!1}){(0,i.assert)(m,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');let{length:f,initialData:A,progressiveDone:C,contentDispositionFilename:u}=m;if(this._queuedChunks=[],this._progressiveDone=C,this._contentDispositionFilename=u,A?.length>0){let y=A instanceof Uint8Array&&A.byteLength===A.buffer.byteLength?A.buffer:new Uint8Array(A).buffer;this._queuedChunks.push(y)}this._pdfDataRangeTransport=m,this._isStreamingSupported=!a,this._isRangeSupported=!d,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:d}){let a=d instanceof Uint8Array&&d.byteLength===d.buffer.byteLength?d.buffer:new Uint8Array(d).buffer;if(m===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(a):this._queuedChunks.push(a);else{let f=this._rangeReaders.some((function(A){return A._begin!==m?!1:(A._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 d=this._rangeReaders.indexOf(m);d>=0&&this._rangeReaders.splice(d,1)}getFullReader(){(0,i.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let m=this._queuedChunks;return this._queuedChunks=null,new l(this,m,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(m,d){if(d<=this._progressiveDataLength)return null;let a=new h(this,m,d);return this._pdfDataRangeTransport.requestDataRange(m,d),this._rangeReaders.push(a),a}cancelAllRequests(m){this._fullRequestReader?.cancel(m);for(let d of this._rangeReaders.slice(0))d.cancel(m);this._pdfDataRangeTransport.abort()}}class l{constructor(m,d,a=!1,f=null){this._stream=m,this._done=a||!1,this._filename=(0,n.isPdfFile)(f)?f:null,this._queuedChunks=d||[],this._loaded=0;for(let A of this._queuedChunks)this._loaded+=A.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 d of this._requests)d.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class h{constructor(m,d,a){this._stream=m,this._begin=d,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 d of this._requests)d.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 d=this._queuedChunk;return this._queuedChunk=null,{value:d,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 d of this._requests)d.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(l,h,g,m,d){let a=m.getValue(h,{value:null});switch(g.name){case"textarea":if(a.value!==null&&(l.textContent=a.value),d==="print")break;l.addEventListener("input",(f=>{m.setValue(h,{value:f.target.value})}));break;case"input":if(g.attributes.type==="radio"||g.attributes.type==="checkbox"){if(a.value===g.attributes.xfaOn?l.setAttribute("checked",!0):a.value===g.attributes.xfaOff&&l.removeAttribute("checked"),d==="print")break;l.addEventListener("change",(f=>{m.setValue(h,{value:f.target.checked?f.target.getAttribute("xfaOn"):f.target.getAttribute("xfaOff")})}))}else{if(a.value!==null&&l.setAttribute("value",a.value),d==="print")break;l.addEventListener("input",(f=>{m.setValue(h,{value:f.target.value})}))}break;case"select":if(a.value!==null){l.setAttribute("value",a.value);for(let f of g.children)f.attributes.value===a.value?f.attributes.selected=!0:f.attributes.hasOwnProperty("selected")&&delete f.attributes.selected}l.addEventListener("input",(f=>{let A=f.target.options,C=A.selectedIndex===-1?"":A[A.selectedIndex].value;m.setValue(h,{value:C})}))}}static setAttributes({html:l,element:h,storage:g=null,intent:m,linkService:d}){let{attributes:a}=h,f=l instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${m}`);for(let[A,C]of Object.entries(a))if(C!=null)switch(A){case"class":C.length&&l.setAttribute(A,C.join(" "));break;case"dataId":break;case"id":l.setAttribute("data-element-id",C);break;case"style":Object.assign(l.style,C);break;case"textContent":l.textContent=C;break;default:(!f||A!=="href"&&A!=="newWindow")&&l.setAttribute(A,C)}f&&d.addLinkAttributes(l,a.href,a.newWindow),g&&a.dataId&&this.setupStorage(l,a.dataId,h,g)}static render(l){let h=l.annotationStorage,g=l.linkService,m=l.xfaHtml,d=l.intent||"display",a=document.createElement(m.name);m.attributes&&this.setAttributes({html:a,element:m,intent:d,linkService:g});let f=d!=="richText",A=l.div;if(A.append(a),l.viewport){let y=`matrix(${l.viewport.transform.join(",")})`;A.style.transform=y}f&&A.setAttribute("class","xfaLayer xfaFont");let C=[];if(m.children.length===0){if(m.value){let y=document.createTextNode(m.value);a.append(y),f&&i.XfaText.shouldBuildText(m.name)&&C.push(y)}return{textDivs:C}}let u=[[m,-1,a]];for(;u.length>0;){let[y,r,c]=u.at(-1);if(r+1===y.children.length){u.pop();continue}let b=y.children[++u.at(-1)[1]];if(b===null)continue;let{name:w}=b;if(w==="#text"){let E=document.createTextNode(b.value);C.push(E),c.append(E);continue}let P=b?.attributes?.xmlns?document.createElementNS(b.attributes.xmlns,w):document.createElement(w);if(c.append(P),b.attributes&&this.setAttributes({html:P,element:b,storage:h,intent:d,linkService:g}),b.children?.length>0)u.push([b,-1,P]);else if(b.value){let E=document.createTextNode(b.value);f&&i.XfaText.shouldBuildText(w)&&C.push(E),P.append(E)}}for(let y of A.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))y.setAttribute("readOnly",!0);return{textDivs:C}}static update(l){let h=`matrix(${l.viewport.transform.join(",")})`;l.div.style.transform=h,l.div.hidden=!1}}},50:(s,t,e)=>{e.d(t,{XfaText:()=>i});class i{static textContent(o){let l=[],h={items:l,styles:Object.create(null)};return(function g(m){if(!m)return;let d=null,a=m.name;if(a==="#text")d=m.value;else{if(!i.shouldBuildText(a))return;m?.attributes?.textContent?d=m.attributes.textContent:m.value&&(d=m.value)}if(d!==null&&l.push({str:d}),m.children)for(let f of m.children)g(f)})(o),h}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:()=>d.AnnotationEditorUIManager,AnnotationLayer:()=>a.AnnotationLayer,AnnotationMode:()=>o.AnnotationMode,CMapCompressionType:()=>o.CMapCompressionType,ColorPicker:()=>f.ColorPicker,DOMSVGFactory:()=>h.DOMSVGFactory,DrawLayer:()=>A.DrawLayer,FeatureTest:()=>o.FeatureTest,GlobalWorkerOptions:()=>C.GlobalWorkerOptions,ImageKind:()=>o.ImageKind,InvalidPDFException:()=>o.InvalidPDFException,MissingPDFException:()=>o.MissingPDFException,OPS:()=>o.OPS,Outliner:()=>u.Outliner,PDFDataRangeTransport:()=>l.PDFDataRangeTransport,PDFDateString:()=>h.PDFDateString,PDFWorker:()=>l.PDFWorker,PasswordResponses:()=>o.PasswordResponses,PermissionFlag:()=>o.PermissionFlag,PixelsPerInch:()=>h.PixelsPerInch,RenderingCancelledException:()=>h.RenderingCancelledException,UnexpectedResponseException:()=>o.UnexpectedResponseException,Util:()=>o.Util,VerbosityLevel:()=>o.VerbosityLevel,XfaLayer:()=>y.XfaLayer,build:()=>l.build,createValidAbsoluteUrl:()=>o.createValidAbsoluteUrl,fetchData:()=>h.fetchData,getDocument:()=>l.getDocument,getFilenameFromUrl:()=>h.getFilenameFromUrl,getPdfFilenameFromUrl:()=>h.getPdfFilenameFromUrl,getXfaPageViewport:()=>h.getXfaPageViewport,isDataScheme:()=>h.isDataScheme,isPdfFile:()=>h.isPdfFile,noContextMenu:()=>h.noContextMenu,normalizeUnicode:()=>o.normalizeUnicode,renderTextLayer:()=>g.renderTextLayer,setLayerDimensions:()=>h.setLayerDimensions,shadow:()=>o.shadow,updateTextLayer:()=>g.updateTextLayer,version:()=>l.version});var o=e(292),l=e(831),h=e(419),g=e(814),m=e(731),d=e(830),a=e(976),f=e(259),A=e(47),C=e(164),u=e(61),y=e(284),r=i([l]);l=(r.then?(await r)():r)[0],n()}catch(c){n(c)}}))},178:(s,t,e)=>{e.d(t,{MessageHandler:()=>u});var i=e(292);let n=1,o=2,l=1,h=2,g=3,m=4,d=5,a=6,f=7,A=8;function C(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 u{constructor(r,c,b){this.sourceName=r,this.targetName=c,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=w=>{let P=w.data;if(P.targetName!==this.sourceName)return;if(P.stream){this.#e(P);return}if(P.callback){let I=P.callbackId,N=this.callbackCapabilities[I];if(!N)throw new Error(`Cannot resolve callback ${I}`);if(delete this.callbackCapabilities[I],P.callback===n)N.resolve(P.data);else{if(P.callback!==o)throw new Error("Unexpected callback case");N.reject(C(P.reason))}return}let E=this.actionHandler[P.action];if(!E)throw new Error(`Unknown action from worker: ${P.action}`);if(P.callbackId){let I=this.sourceName,N=P.sourceName;new Promise((function(z){z(E(P.data))})).then((function(z){b.postMessage({sourceName:I,targetName:N,callback:n,callbackId:P.callbackId,data:z})}),(function(z){b.postMessage({sourceName:I,targetName:N,callback:o,callbackId:P.callbackId,reason:C(z)})}))}else P.streamId?this.#t(P):E(P.data)},b.addEventListener("message",this._onComObjOnMessage)}on(r,c){let b=this.actionHandler;if(b[r])throw new Error(`There is already an actionName called "${r}"`);b[r]=c}send(r,c,b){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:r,data:c},b)}sendWithPromise(r,c,b){let w=this.callbackId++,P=Promise.withResolvers();this.callbackCapabilities[w]=P;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:r,callbackId:w,data:c},b)}catch(E){P.reject(E)}return P.promise}sendWithStream(r,c,b,w){let P=this.streamId++,E=this.sourceName,I=this.targetName,N=this.comObj;return new ReadableStream({start:z=>{let H=Promise.withResolvers();return this.streamControllers[P]={controller:z,startCall:H,pullCall:null,cancelCall:null,isClosed:!1},N.postMessage({sourceName:E,targetName:I,action:r,streamId:P,data:c,desiredSize:z.desiredSize},w),H.promise},pull:z=>{let H=Promise.withResolvers();return this.streamControllers[P].pullCall=H,N.postMessage({sourceName:E,targetName:I,stream:a,streamId:P,desiredSize:z.desiredSize}),H.promise},cancel:z=>{(0,i.assert)(z instanceof Error,"cancel must have a valid reason");let H=Promise.withResolvers();return this.streamControllers[P].cancelCall=H,this.streamControllers[P].isClosed=!0,N.postMessage({sourceName:E,targetName:I,stream:l,streamId:P,reason:C(z)}),H.promise}},b)}#t(r){let c=r.streamId,b=this.sourceName,w=r.sourceName,P=this.comObj,E=this,I=this.actionHandler[r.action],N={enqueue(z,H=1,X){if(this.isCancelled)return;let it=this.desiredSize;this.desiredSize-=H,it>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),P.postMessage({sourceName:b,targetName:w,stream:m,streamId:c,chunk:z},X)},close(){this.isCancelled||(this.isCancelled=!0,P.postMessage({sourceName:b,targetName:w,stream:g,streamId:c}),delete E.streamSinks[c])},error(z){(0,i.assert)(z instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,P.postMessage({sourceName:b,targetName:w,stream:d,streamId:c,reason:C(z)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:r.desiredSize,ready:null};N.sinkCapability.resolve(),N.ready=N.sinkCapability.promise,this.streamSinks[c]=N,new Promise((function(z){z(I(r.data,N))})).then((function(){P.postMessage({sourceName:b,targetName:w,stream:A,streamId:c,success:!0})}),(function(z){P.postMessage({sourceName:b,targetName:w,stream:A,streamId:c,reason:C(z)})}))}#e(r){let c=r.streamId,b=this.sourceName,w=r.sourceName,P=this.comObj,E=this.streamControllers[c],I=this.streamSinks[c];switch(r.stream){case A:r.success?E.startCall.resolve():E.startCall.reject(C(r.reason));break;case f:r.success?E.pullCall.resolve():E.pullCall.reject(C(r.reason));break;case a:if(!I){P.postMessage({sourceName:b,targetName:w,stream:f,streamId:c,success:!0});break}I.desiredSize<=0&&r.desiredSize>0&&I.sinkCapability.resolve(),I.desiredSize=r.desiredSize,new Promise((function(N){N(I.onPull?.())})).then((function(){P.postMessage({sourceName:b,targetName:w,stream:f,streamId:c,success:!0})}),(function(N){P.postMessage({sourceName:b,targetName:w,stream:f,streamId:c,reason:C(N)})}));break;case m:if((0,i.assert)(E,"enqueue should have stream controller"),E.isClosed)break;E.controller.enqueue(r.chunk);break;case g:if((0,i.assert)(E,"close should have stream controller"),E.isClosed)break;E.isClosed=!0,E.controller.close(),this.#i(E,c);break;case d:(0,i.assert)(E,"error should have stream controller"),E.controller.error(C(r.reason)),this.#i(E,c);break;case h:r.success?E.cancelCall.resolve():E.cancelCall.reject(C(r.reason)),this.#i(E,c);break;case l:if(!I)break;new Promise((function(N){N(I.onCancel?.(C(r.reason)))})).then((function(){P.postMessage({sourceName:b,targetName:w,stream:h,streamId:c,success:!0})}),(function(N){P.postMessage({sourceName:b,targetName:w,stream:h,streamId:c,reason:C(N)})})),I.sinkCapability.reject(C(r.reason)),I.isCancelled=!0,delete this.streamSinks[c];break;default:throw new Error("Unexpected stream case")}}async#i(r,c){await Promise.allSettled([r.startCall?.promise,r.pullCall?.promise,r.cancelCall?.promise]),delete this.streamControllers[c]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},651:(s,t,e)=>{e.d(t,{MurmurHash3_64:()=>l});let i=3285377520,n=4294901760,o=65535;class l{constructor(g){this.h1=g?4294967295&g:i,this.h2=g?4294967295&g:i}update(g){let m,d;if(typeof g=="string"){m=new Uint8Array(2*g.length),d=0;for(let E=0,I=g.length;E<I;E++){let N=g.charCodeAt(E);N<=255?m[d++]=N:(m[d++]=N>>>8,m[d++]=255&N)}}else{if(!ArrayBuffer.isView(g))throw new Error("Invalid data format, must be a string or TypedArray.");m=g.slice(),d=m.byteLength}let a=d>>2,f=d-4*a,A=new Uint32Array(m.buffer,0,a),C=0,u=0,y=this.h1,r=this.h2,c=3432918353,b=461845907,w=11601,P=13715;for(let E=0;E<a;E++)1&E?(C=A[E],C=C*c&n|C*w&o,C=C<<15|C>>>17,C=C*b&n|C*P&o,y^=C,y=y<<13|y>>>19,y=5*y+3864292196):(u=A[E],u=u*c&n|u*w&o,u=u<<15|u>>>17,u=u*b&n|u*P&o,r^=u,r=r<<13|r>>>19,r=5*r+3864292196);switch(C=0,f){case 3:C^=m[4*a+2]<<16;case 2:C^=m[4*a+1]<<8;case 1:C^=m[4*a],C=C*c&n|C*w&o,C=C<<15|C>>>17,C=C*b&n|C*P&o,1&a?y^=C:r^=C}this.h1=y,this.h2=r}hexdigest(){let g=this.h1,m=this.h2;return g^=m>>>1,g=3981806797*g&n|36045*g&o,m=4283543511*m&n|(2950163797*(m<<16|g>>>16)&n)>>>16,g^=m>>>1,g=444984403*g&n|60499*g&o,m=3301882366*m&n|(3120437893*(m<<16|g>>>16)&n)>>>16,g^=m>>>1,(g>>>0).toString(16).padStart(8,"0")+(m>>>0).toString(16).padStart(8,"0")}}},292:(s,t,e)=>{e.d(t,{AbortException:()=>W,AnnotationBorderStyleType:()=>r,AnnotationEditorParamsType:()=>f,AnnotationEditorPrefix:()=>d,AnnotationEditorType:()=>a,AnnotationMode:()=>m,AnnotationPrefix:()=>U,AnnotationType:()=>y,BaseException:()=>j,CMapCompressionType:()=>b,FONT_IDENTITY_MATRIX:()=>o,FeatureTest:()=>v,FormatError:()=>st,IDENTITY_MATRIX:()=>n,ImageKind:()=>u,InvalidPDFException:()=>et,LINE_FACTOR:()=>h,MAX_IMAGE_SIZE_TO_CACHE:()=>l,MissingPDFException:()=>rt,OPS:()=>w,PasswordException:()=>G,PasswordResponses:()=>P,PermissionFlag:()=>A,RenderingIntentFlag:()=>g,TextRenderingMode:()=>C,UnexpectedResponseException:()=>ct,UnknownErrorException:()=>Y,Util:()=>k,VerbosityLevel:()=>c,assert:()=>it,bytesToString:()=>x,createValidAbsoluteUrl:()=>at,getUuid:()=>L,getVerbosityLevel:()=>N,info:()=>z,isNodeJS:()=>i,normalizeUnicode:()=>S,objectFromMap:()=>p,setVerbosityLevel:()=>I,shadow:()=>K,string32:()=>R,stringToBytes:()=>T,unreachable:()=>X,warn:()=>H});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],l=1e7,h=1.35,g={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},d="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},A={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},C={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},u={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},c={ERRORS:0,WARNINGS:1,INFOS:5},b={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},P={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},E=c.WARNINGS;function I($){Number.isInteger($)&&(E=$)}function N(){return E}function z($){E>=c.INFOS&&console.log(`Info: ${$}`)}function H($){E>=c.WARNINGS&&console.log(`Warning: ${$}`)}function X($){throw new Error($)}function it($,D){$||X(D)}function at($,D=null,F=null){if(!$)return null;try{if(F&&typeof $=="string"&&(F.addDefaultProtocol&&$.startsWith("www.")&&$.match(/\./g)?.length>=2&&($=`http://${$}`),F.tryConvertEncoding))try{$=(function(Z){return decodeURIComponent(escape(Z))})($)}catch{}let V=D?new URL($,D):new URL($);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($,D,F,V=!1){return Object.defineProperty($,D,{value:F,enumerable:!V,configurable:!0,writable:!1}),F}let j=(function(){function D(F,V){this.constructor===D&&X("Cannot initialize BaseException."),this.message=F,this.name=V}return D.prototype=new Error,D.constructor=D,D})();class G 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 et extends j{constructor(D){super(D,"InvalidPDFException")}}class rt extends j{constructor(D){super(D,"MissingPDFException")}}class ct extends j{constructor(D,F){super(D,"UnexpectedResponseException"),this.status=F}}class st extends j{constructor(D){super(D,"FormatError")}}class W extends j{constructor(D){super(D,"AbortException")}}function x($){typeof $=="object"&&$?.length!==void 0||X("Invalid argument for bytesToString");let D=$.length,F=8192;if(D<F)return String.fromCharCode.apply(null,$);let V=[];for(let Q=0;Q<D;Q+=F){let Z=Math.min(Q+F,D),tt=$.subarray(Q,Z);V.push(String.fromCharCode.apply(null,tt))}return V.join("")}function T($){typeof $!="string"&&X("Invalid argument for stringToBytes");let D=$.length,F=new Uint8Array(D);for(let V=0;V<D;++V)F[V]=255&$.charCodeAt(V);return F}function R($){return String.fromCharCode($>>24&255,$>>16&255,$>>8&255,255&$)}function p($){let D=Object.create(null);for(let[F,V]of $)D[F]=V;return D}class v{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 _=Array.from(Array(256).keys(),($=>$.toString(16).padStart(2,"0")));class k{static makeHexColor(D,F,V){return`#${_[D]}${_[F]}${_[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),tt=this.applyTransform([D[2],D[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(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],tt=D[2]*F[1]+D[3]*F[3],nt=(V+tt)/2,pt=Math.sqrt((V+tt)**2-4*(V*tt-Z*Q))/2,dt=nt+pt||1,lt=nt-pt||1;return[Math.sqrt(dt),Math.sqrt(lt)]}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])),tt=Math.min(Math.max(D[1],D[3]),Math.max(F[1],F[3]));return Z>tt?null:[V,Z,Q,tt]}static#t(D,F,V,Q,Z,tt,nt,pt,dt,lt){if(dt<=0||dt>=1)return;let wt=1-dt,Tt=dt*dt,xt=Tt*dt,It=wt*(wt*(wt*D+3*dt*F)+3*Tt*V)+xt*Q,Lt=wt*(wt*(wt*Z+3*dt*tt)+3*Tt*nt)+xt*pt;lt[0]=Math.min(lt[0],It),lt[1]=Math.min(lt[1],Lt),lt[2]=Math.max(lt[2],It),lt[3]=Math.max(lt[3],Lt)}static#e(D,F,V,Q,Z,tt,nt,pt,dt,lt,wt,Tt){if(Math.abs(dt)<1e-12){Math.abs(lt)>=1e-12&&this.#t(D,F,V,Q,Z,tt,nt,pt,-wt/lt,Tt);return}let xt=lt**2-4*wt*dt;if(xt<0)return;let It=Math.sqrt(xt),Lt=2*dt;this.#t(D,F,V,Q,Z,tt,nt,pt,(-lt+It)/Lt,Tt),this.#t(D,F,V,Q,Z,tt,nt,pt,(-lt-It)/Lt,Tt)}static bezierBoundingBox(D,F,V,Q,Z,tt,nt,pt,dt){return dt?(dt[0]=Math.min(dt[0],D,nt),dt[1]=Math.min(dt[1],F,pt),dt[2]=Math.max(dt[2],D,nt),dt[3]=Math.max(dt[3],F,pt)):dt=[Math.min(D,nt),Math.min(F,pt),Math.max(D,nt),Math.max(F,pt)],this.#e(D,V,Z,nt,F,Q,tt,pt,3*(3*(V-Z)-D+nt),6*(D-2*V+Z),3*(V-D),dt),this.#e(D,V,Z,nt,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 S($){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"]])),$.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 $=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto?.getRandomValues=="function")crypto.getRandomValues($);else for(let D=0;D<32;D++)$[D]=Math.floor(255*Math.random());return x($)}let U="pdfjs_internal_id_"}},Ph={};function ps(s){var t=Ph[s];if(t!==void 0)return t.exports;var e=Ph[s]={exports:{}};return Yu[s](e,e.exports,ps),e.exports}Js=typeof Symbol=="function"?Symbol("webpack queues"):"__webpack_queues__",Nn=typeof Symbol=="function"?Symbol("webpack exports"):"__webpack_exports__",Bn=typeof Symbol=="function"?Symbol("webpack error"):"__webpack_error__",_o=s=>{s&&s.d<1&&(s.d=1,s.forEach((t=>t.r--)),s.forEach((t=>t.r--?t.r++:t())))},ps.a=(s,t,e)=>{var i;e&&((i=[]).d=-1);var n,o,l,h=new Set,g=s.exports,m=new Promise(((d,a)=>{l=a,o=d}));m[Nn]=g,m[Js]=d=>(i&&d(i),h.forEach(d),m.catch((a=>{}))),s.exports=m,t((d=>{n=(C=>C.map((u=>{if(u!==null&&typeof u=="object"){if(u[Js])return u;if(u.then){var y=[];y.d=0,u.then((b=>{r[Nn]=b,_o(y)}),(b=>{r[Bn]=b,_o(y)}));var r={};return r[Js]=b=>b(y),r}}var c={};return c[Js]=b=>{},c[Nn]=u,c})))(d);var a,f=()=>n.map((C=>{if(C[Bn])throw C[Bn];return C[Nn]})),A=new Promise((C=>{(a=()=>C(f)).r=0;var u=y=>y!==i&&!h.has(y)&&(h.add(y),y&&!y.d&&(a.r++,y.push(a)));n.map((y=>y[Js](u)))}));return a.r?A:f()}),(d=>(d?l(m[Bn]=d):o(g),_o(i)))),i&&i.d<0&&(i.d=0)};ps.d=(s,t)=>{for(var e in t)ps.o(t,e)&&!ps.o(s,e)&&Object.defineProperty(s,e,{enumerable:!0,get:t[e]})};ps.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var _t=ps(228),Xf=(_t=globalThis.pdfjsLib=await(globalThis.pdfjsLibPromise=_t)).AbortException,Kf=_t.AnnotationEditorLayer,Yf=_t.AnnotationEditorParamsType,Jf=_t.AnnotationEditorType,Qf=_t.AnnotationEditorUIManager,Zf=_t.AnnotationLayer,tg=_t.AnnotationMode,eg=_t.CMapCompressionType,ig=_t.ColorPicker,sg=_t.DOMSVGFactory,ng=_t.DrawLayer,rg=_t.FeatureTest,Dh=_t.GlobalWorkerOptions,og=_t.ImageKind,ag=_t.InvalidPDFException,lg=_t.MissingPDFException,cg=_t.OPS,hg=_t.Outliner,dg=_t.PDFDataRangeTransport,ug=_t.PDFDateString,pg=_t.PDFWorker,fg=_t.PasswordResponses,gg=_t.PermissionFlag,mg=_t.PixelsPerInch,bg=_t.RenderingCancelledException,yg=_t.UnexpectedResponseException,vg=_t.Util,wg=_t.VerbosityLevel,xg=_t.XfaLayer,Ag=_t.build,Sg=_t.createValidAbsoluteUrl,Eg=_t.fetchData,Ih=_t.getDocument,Cg=_t.getFilenameFromUrl,_g=_t.getPdfFilenameFromUrl,kg=_t.getXfaPageViewport,Tg=_t.isDataScheme,Pg=_t.isPdfFile,Dg=_t.noContextMenu,Ig=_t.normalizeUnicode,Mg=_t.renderTextLayer,Rg=_t.setLayerDimensions,Lg=_t.shadow,Fg=_t.updateTextLayer,Og=_t.version;Dh.workerSrc=ni("js/lib/pdf.worker.min.mjs");async function Ri(s,t=2){let e=await Ih({data:s}).promise,i=[];for(let n=1;n<=e.numPages;n++){let o=await e.getPage(n),l=o.getViewport({scale:t}),h=document.createElement("canvas"),g=h.getContext("2d");h.width=l.width,h.height=l.height,await o.render({canvasContext:g,viewport:l}).promise,i.push(h.toDataURL("image/jpeg",.82))}return i}var Lh=null,Mh={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}};function Li(s){Lh=s||null}function Fi(){return Lh||(typeof document<"u"?document.body:null)}function ol(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function Rh(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=Mh[n]||Mh.info,l=e.container||Fi();if(i?.toastStack&&l){let a=i.toastStack;a.parentElement!==l&&l.appendChild(a),l!==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 h=document.createElement("sl-alert");h.variant=o.slVariant,h.closable=e.closable!==!1,h.duration=e.duration!==void 0?e.duration:o.defaultDuration;let g=e.icon!==void 0?e.icon:o.defaultIcon;if(g){let a=document.createElement("sl-icon");a.slot="icon",a.name=g,h.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",A=>{A.preventDefault(),A.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(A,h),e.action.autoClose!==!1&&h.hide()}),a.appendChild(f),h.appendChild(a)}else h.appendChild(m);let d=h.toast();return h.toastPromise=d,h}function Qu(s,t={}){return Pt.show({message:s,variant:"success",...t})}function Zu(s,t={}){return Pt.show({message:s,variant:"error",...t})}function tp(s,t={}){return Pt.show({message:s,variant:"warning",...t})}function ep(s,t={}){return Pt.show({message:s,variant:"info",...t})}function ip(s,t,e={}){return Pt.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 sp(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(u=>setTimeout(u,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||Fi(),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 u=document.createElement("sl-icon");u.slot="icon",u.name=o,n.appendChild(u)}let l=document.createElement("div");l.className="notify-progress-wrapper",l.style.display="flex",l.style.flexDirection="column",l.style.gap="0.35rem",l.style.minWidth="220px";let h=document.createElement("div");h.style.display="flex",h.style.justifyContent="space-between",h.style.alignItems="center",h.style.gap="0.5rem";let g=document.createElement("span");g.className="notify-progress-message",g.style.fontWeight="500",g.style.fontSize="0.9rem",g.textContent=e.message||"Processing...",h.appendChild(g);let m=document.createElement("span");m.className="notify-progress-status",m.style.fontSize="0.78rem",m.style.color="#64748b",m.style.fontWeight="600";let d=e.done!==void 0?e.done:0,a=e.total!==void 0?e.total:0;a>0?m.textContent=`${d} / ${a}`:e.value!==void 0&&(m.textContent=`${e.value}%`),h.appendChild(m),l.appendChild(h);let f=document.createElement("sl-progress-bar");a>0?f.value=Math.round(d/a*100):e.value!==void 0?f.value=e.value:f.indeterminate=!0,l.appendChild(f),n.appendChild(l);let A=customElements.get("sl-alert");if(A?.toastStack&&i){let u=A.toastStack;u.parentElement!==i&&i.appendChild(u)}return n.toast(),{alert:n,progressBar:f,update({done:u,total:y,value:r,message:c}={}){if(c!==void 0&&(g.textContent=c),y!==void 0&&u!==void 0){f.indeterminate=!1;let b=Math.min(100,Math.max(0,Math.round(u/Math.max(y,1)*100)));f.value=b,m.textContent=`${u} / ${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 Pt=Object.assign(function(s,t){return Rh(s,t)},{show:Rh,success:Qu,error:Zu,warning:tp,info:ep,undo:ip,progress:sp,clear:ol,setContainer:Li,getContainer:Fi});var Fh=`
|
|
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}
|
|
2
|
+
|
|
3
|
+
${u.text}`:u.text).join(`
|
|
4
|
+
|
|
5
|
+
---
|
|
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=`
|
|
14
20
|
.cropper-container {
|
|
15
21
|
direction: ltr;
|
|
16
22
|
font-size: 0;
|
|
@@ -295,9 +301,9 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
295
301
|
.cropper-disabled .cropper-point {
|
|
296
302
|
cursor: not-allowed;
|
|
297
303
|
}
|
|
298
|
-
`;var
|
|
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=`
|
|
299
305
|
<style>
|
|
300
|
-
${
|
|
306
|
+
${Vh}
|
|
301
307
|
</style>
|
|
302
308
|
<style>
|
|
303
309
|
.container {
|
|
@@ -443,40 +449,6 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
443
449
|
padding: 0.5rem 0.75rem;
|
|
444
450
|
}
|
|
445
451
|
}
|
|
446
|
-
.markdown-card {
|
|
447
|
-
width: 100%;
|
|
448
|
-
height: 100%;
|
|
449
|
-
border: 1px solid #334155;
|
|
450
|
-
border-radius: 4px;
|
|
451
|
-
background: #0f172a;
|
|
452
|
-
color: #f8fafc;
|
|
453
|
-
padding: 10px;
|
|
454
|
-
box-sizing: border-box;
|
|
455
|
-
font-family: monospace;
|
|
456
|
-
font-size: 0.72rem;
|
|
457
|
-
overflow: hidden;
|
|
458
|
-
display: flex;
|
|
459
|
-
flex-direction: column;
|
|
460
|
-
}
|
|
461
|
-
.markdown-card-header {
|
|
462
|
-
display: flex;
|
|
463
|
-
align-items: center;
|
|
464
|
-
gap: 4px;
|
|
465
|
-
font-weight: bold;
|
|
466
|
-
font-size: 0.75rem;
|
|
467
|
-
color: #38bdf8;
|
|
468
|
-
margin-bottom: 6px;
|
|
469
|
-
white-space: nowrap;
|
|
470
|
-
overflow: hidden;
|
|
471
|
-
text-overflow: ellipsis;
|
|
472
|
-
}
|
|
473
|
-
.markdown-card-body {
|
|
474
|
-
flex: 1;
|
|
475
|
-
opacity: 0.8;
|
|
476
|
-
word-break: break-word;
|
|
477
|
-
overflow: hidden;
|
|
478
|
-
line-height: 1.35;
|
|
479
|
-
}
|
|
480
452
|
button.add-btn {
|
|
481
453
|
width: 100%;
|
|
482
454
|
aspect-ratio: 1;
|
|
@@ -509,17 +481,9 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
509
481
|
${t}
|
|
510
482
|
<div class="container"></div>
|
|
511
483
|
|
|
512
|
-
<input type="file" class="file-input" accept="image/*,application/pdf
|
|
484
|
+
<input type="file" class="file-input" accept="image/*,application/pdf" multiple style="display: none">
|
|
513
485
|
<input type="file" class="camera-input" accept="image/*" capture="environment" style="display: none">
|
|
514
486
|
|
|
515
|
-
<sl-dialog label="Edit Markdown Text" class="text-dialog" style="--width: min(92%, 560px)">
|
|
516
|
-
<div style="margin-bottom: 1rem;">
|
|
517
|
-
<sl-textarea class="text-editor" rows="12" placeholder="Enter markdown content..."></sl-textarea>
|
|
518
|
-
</div>
|
|
519
|
-
<sl-button slot="footer" variant="default" class="cancel-text">Cancel</sl-button>
|
|
520
|
-
<sl-button slot="footer" variant="primary" class="apply-text">Save Text</sl-button>
|
|
521
|
-
</sl-dialog>
|
|
522
|
-
|
|
523
487
|
<sl-dialog label="Image Data" class="data-dialog">
|
|
524
488
|
<div class="exif-data" style="font-size: 0.85rem; line-height: 1.6;"></div>
|
|
525
489
|
<sl-button slot="footer" variant="primary" class="close-data">Close</sl-button>
|
|
@@ -532,30 +496,10 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
532
496
|
<sl-button slot="footer" variant="default" class="cancel-crop">Cancel</sl-button>
|
|
533
497
|
<sl-button slot="footer" variant="primary" class="apply-crop">Apply</sl-button>
|
|
534
498
|
</sl-dialog>
|
|
535
|
-
`,this.#
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
<sl-icon name="file-earmark-text"></sl-icon> ${d}
|
|
540
|
-
</div>
|
|
541
|
-
<div class="markdown-card-body">${a}</div>
|
|
542
|
-
</div>
|
|
543
|
-
<sl-dropdown class="image-menu" data-index="${h}">
|
|
544
|
-
<sl-button slot="trigger" variant="default" size="small" circle>
|
|
545
|
-
<sl-icon name="three-dots-vertical"></sl-icon>
|
|
546
|
-
</sl-button>
|
|
547
|
-
<sl-menu>
|
|
548
|
-
<sl-menu-item value="edittext">Edit Text</sl-menu-item>
|
|
549
|
-
<sl-menu-item value="download">Download Markdown</sl-menu-item>
|
|
550
|
-
<sl-divider></sl-divider>
|
|
551
|
-
<sl-menu-item value="delete">Delete</sl-menu-item>
|
|
552
|
-
</sl-menu>
|
|
553
|
-
</sl-dropdown>
|
|
554
|
-
</div>
|
|
555
|
-
`}let g=La(l.edits),m=l.edits?.filter==="bw";return`
|
|
556
|
-
<div class="image-wrapper" data-index="${h}">
|
|
557
|
-
<img src="${l.src}" draggable="false">
|
|
558
|
-
<sl-dropdown class="image-menu" data-index="${h}">
|
|
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}">
|
|
559
503
|
<sl-button slot="trigger" variant="default" size="small" circle>
|
|
560
504
|
<sl-icon name="three-dots-vertical"></sl-icon>
|
|
561
505
|
</sl-button>
|
|
@@ -569,10 +513,10 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
569
513
|
<sl-menu-item value="crop">Crop</sl-menu-item>
|
|
570
514
|
<sl-menu-item value="rotate">Rotate</sl-menu-item>
|
|
571
515
|
<sl-menu-item value="threshold">
|
|
572
|
-
<sl-icon slot="prefix" name="${
|
|
573
|
-
${
|
|
516
|
+
<sl-icon slot="prefix" name="${h?"check-lg":"circle"}"></sl-icon>
|
|
517
|
+
${h?"Remove Black & White":"Black & White"}
|
|
574
518
|
</sl-menu-item>
|
|
575
|
-
<sl-menu-item value="reset" ?disabled=${!
|
|
519
|
+
<sl-menu-item value="reset" ?disabled=${!l}>
|
|
576
520
|
<sl-icon slot="prefix" name="arrow-counterclockwise"></sl-icon>
|
|
577
521
|
Reset to Original
|
|
578
522
|
</sl-menu-item>
|
|
@@ -585,18 +529,15 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
585
529
|
</div>
|
|
586
530
|
`}).join("");t.innerHTML=`
|
|
587
531
|
${e}
|
|
588
|
-
<button class="add-btn add-image-btn" title="Add image
|
|
532
|
+
<button class="add-btn add-image-btn" title="Add image or PDF" aria-label="Add image or PDF">
|
|
589
533
|
<sl-icon name="plus-lg"></sl-icon>
|
|
590
534
|
</button>
|
|
591
535
|
<button class="add-btn add-camera-btn" title="Capture from camera" aria-label="Capture from camera">
|
|
592
536
|
<sl-icon name="camera"></sl-icon>
|
|
593
537
|
</button>
|
|
594
|
-
<button class="add-btn add-note-btn" title="New blank note" aria-label="New blank note">
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
`;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()});let o=t.querySelector(".add-note-btn");o&&(o.onclick=()=>{this.addBlankNote()}),t.querySelectorAll(".image-menu").forEach(l=>{l.querySelector("sl-menu").addEventListener("sl-select",g=>{g.stopPropagation();let m=parseInt(l.dataset.index),d=g.detail.item.value;if(d==="ocr")l.hide(),this.dispatchEvent(new CustomEvent("copio:ocr-page",{bubbles:!0,composed:!0,detail:{page:this.#t[m],pageIndex:m}}));else if(d==="crop")l.hide(),this.openCropDialog(m);else if(d==="rotate")this.rotateImage(m);else if(d==="threshold")this.thresholdImage(m);else if(d==="reset")l.hide(),this.resetImage(m);else if(d==="showdata")l.hide(),this.showImageData(m);else if(d==="edittext")l.hide(),this.openTextDialog(m);else if(d==="download")this.downloadImage(m);else if(d==="delete"){let[a]=this.#t.splice(m,1);this.#h();let f=a.name||(a.type==="markdown"?"Markdown Note":`Page ${m+1}`);Pt.undo(`Deleted ${f}`,()=>{this.#t.splice(m,0,a),this.#h(),Pt.success(`Restored ${f}`)},{duration:5e3})}})}),this.#b(t)}#b(t){if(this.#i){try{this.#i.destroy()}catch(e){console.warn("Error destroying Sortable:",e)}this.#i=null}this.#i=yh.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.#h()}})}async openCropDialog(t){this.#n=t;let e=this.#t[t];if(!e||e.type==="markdown")return;let i=this.shadowRoot.querySelector(".crop-dialog"),n=this.shadowRoot.querySelector("#crop-image");e.originalSrc=e.originalSrc||e.src,e.edits=Ge(e.edits),n.src=e.originalSrc,i.show();let o=await io(),l=e.edits?.crop,h=()=>{this.#e&&this.#e.destroy(),this.#e=new o(n,{viewMode:1,autoCropArea:.88,responsive:!0,ready:()=>{if(l)try{if(l.width>0&&l.height>0)this.#e.setData({x:l.x,y:l.y,width:l.width,height:l.height});else if(l.normalized&&l.normalized.w>0){let g=this.#e.getImageData();this.#e.setData({x:Math.round(l.normalized.x*g.naturalWidth),y:Math.round(l.normalized.y*g.naturalHeight),width:Math.round(l.normalized.w*g.naturalWidth),height:Math.round(l.normalized.h*g.naturalHeight)})}else if(typeof l.w=="number"&&l.w>0){let g=this.#e.getImageData();this.#e.setData({x:Math.round(l.x*g.naturalWidth),y:Math.round(l.y*g.naturalHeight),width:Math.round(l.w*g.naturalWidth),height:Math.round(l.h*g.naturalHeight)})}}catch(g){console.warn("Failed restoring prior crop box:",g)}}})};n.onload=h,n.complete&&n.naturalWidth>0&&!this.#e&&h()}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,l=Math.max(0,Math.min(1,e.x/n)),h=Math.max(0,Math.min(1,e.y/o)),g=Math.max(0,Math.min(1,e.width/n)),m=Math.max(0,Math.min(1,e.height/o));t.edits={...Ge(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(l.toFixed(4)),y:Number(h.toFixed(4)),w:Number(g.toFixed(4)),h:Number(m.toFixed(4))}}};let d=this.#e.getCroppedCanvas();if(d){let a=js(d,{crop:null,rotation:t.edits.rotation,filter:t.edits.filter}),f=t.originalSrc.startsWith("data:image/png"),A=f?"image/png":"image/jpeg";t.src=a.toDataURL(A,f?void 0:.82)}this.#h(),this.closeCropDialog()}}async rotateImage(t){let e=this.#t[t];!e||e.type==="markdown"||(e.originalSrc=e.originalSrc||e.src,e.edits={...Ge(e.edits),rotation:((e.edits?.rotation||0)+90)%360},e.src=await Zr(e.originalSrc,e.edits),this.#h())}async thresholdImage(t){let e=this.#t[t];if(!e||e.type==="markdown")return;e.originalSrc=e.originalSrc||e.src;let i=e.edits?.filter==="bw";e.edits={...Ge(e.edits),filter:i?"none":"bw"},e.src=await Zr(e.originalSrc,e.edits),this.#h(),i?Pt.info("Restored color (removed B&W filter)"):Pt.success("Applied B&W threshold filter")}resetImage(t){let e=this.#t[t];!e||e.type==="markdown"||(e.edits={crop:null,rotation:0,filter:"none"},e.src=e.originalSrc||e.src,this.#h(),Pt.success("Reset page to original"))}addBlankNote(){let t={id:we(),type:"markdown",name:"New Note",content:""};this.#t.push(t),this.#h(),this.openTextDialog(this.#t.length-1)}downloadImage(t){let e=this.#t[t];if(!e)return;if(e.type==="markdown"){let l=new Blob([e.content||""],{type:"text/markdown;charset=utf-8"}),h=this.#u(URL.createObjectURL(l)),g=document.createElement("a"),m=e.name||`document-${t+1}.md`;g.href=h,g.download=m,g.click(),this.#l(h),Pt.success(`Downloaded "${m}"`);return}if(!e.src)return;let i="jpg";if(e.src.startsWith("data:")){let l=e.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);l&&l[1].includes("png")&&(i="png")}let n=document.createElement("a"),o=`image-${t+1}.${i}`;n.href=e.src,n.download=o,n.click(),Pt.success(`Downloaded "${o}"`)}openTextDialog(t){this.#r=t;let e=this.shadowRoot.querySelector(".text-dialog"),i=this.shadowRoot.querySelector(".text-editor");i.value=this.#t[t].content||"",e.label=this.#t[t].name||"Note",e.show()}applyTextEdit(){if(this.#r!==null&&this.#t[this.#r]){let t=this.shadowRoot.querySelector(".text-editor");this.#t[this.#r].content=t.value,this.#h(),this.closeTextDialog()}}closeTextDialog(){let t=this.shadowRoot.querySelector(".text-dialog");this.#r=null,t.hide()}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 l=new Set(["MakerNote","UserComment","FlashPixVersion","ExifVersion","ComponentsConfiguration","SceneType","thumbnail"]);for(let[h,g]of Object.entries(i)){if(l.has(h)||g===void 0||g===null)continue;let m=g instanceof Array?g.join(", "):String(g);m.length>200||o.push(`<strong>${h}:</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 Ri(e)).map(n=>({id:we(),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 if(n.name?.endsWith(".md")||n.name?.endsWith(".markdown")||n.type==="text/markdown"||n.type==="text/plain"){let o=await n.text();e.push({id:we(),type:"markdown",name:n.name,content:o})}else{let[o,l]=await Promise.all([Hs(n),zs(n)]);e.push({id:we(),src:o,originalSrc:o,edits:{crop:null,rotation:0,filter:"none"},exif:l})}this.#t.push(...e),this.#h();let i=e.length;Pt.success(`Imported ${i} page${i!==1?"s":""}`)}catch(i){console.error("Failed to import files:",i),Pt.error("Failed to import files")}}get ocr(){return this.#d!==!1}set ocr(t){this.#d=!!t,this.#s&&this.#h()}get pdf(){return this.#p!==!1}set pdf(t){this.#p=!!t,this.#s&&this.#h()}get images(){return this.#t}set images(t){let e=Array.isArray(t)?t:[];this.#t=e.map(i=>!i||i.type==="markdown"?i:{...i,originalSrc:i.originalSrc||i.src||"",edits:Ge(i.edits)}),this.#s&&this.#h()}};customElements.define("copio-images",$n);var ko=globalThis,fl=ko.ShadowRoot&&(ko.ShadyCSS===void 0||ko.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,gl=Symbol(),Oh=new WeakMap,To=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==gl)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(fl&&t===void 0){let i=e!==void 0&&e.length===1;i&&(t=Oh.get(e)),t===void 0&&((this.i=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Oh.set(e,t))}return t}toString(){return this.cssText}},np=s=>new To(typeof s=="string"?s:s+"",void 0,gl),Bi=(s,...t)=>{let e=s.length===1?s[0]:t.reduce(((i,n,o)=>i+(l=>{if(l._$cssResult$===!0)return l.cssText;if(typeof l=="number")return l;throw Error("Value passed to 'css' function must be a 'css' function result: "+l+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+s[o+1]),s[0]);return new To(e,s,gl)},rp=(s,t)=>{if(fl)s.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let i=document.createElement("style"),n=ko.litNonce;n!==void 0&&i.setAttribute("nonce",n),i.textContent=e.cssText,s.appendChild(i)}},Nh=fl?s=>s:s=>s instanceof CSSStyleSheet?(t=>{let e="";for(let i of t.cssRules)e+=i.cssText;return np(e)})(s):s,{is:op,defineProperty:ap,getOwnPropertyDescriptor:lp,getOwnPropertyNames:cp,getOwnPropertySymbols:hp,getPrototypeOf:dp}=Object,Do=globalThis,Bh=Do.trustedTypes,up=Bh?Bh.emptyScript:"",pp=Do.reactiveElementPolyfillSupport,zn=(s,t)=>s,ll={toAttribute(s,t){switch(t){case Boolean:s=s?up: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}},Wh=(s,t)=>!op(s,t),$h={attribute:!0,type:String,converter:ll,reflect:!1,useDefault:!1,hasChanged:Wh};Symbol.metadata??=Symbol("metadata"),Do.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=$h){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&&ap(this.prototype,t,n)}}static getPropertyDescriptor(t,e,i){let{get:n,set:o}=lp(this.prototype,t)??{get(){return this[e]},set(l){this[e]=l}};return{get:n,set(l){let h=n?.call(this);o?.call(this,l),this.requestUpdate(t,h,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??$h}static o(){if(this.hasOwnProperty(zn("elementProperties")))return;let t=dp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(zn("finalized")))return;if(this.finalized=!0,this.o(),this.hasOwnProperty(zn("properties"))){let e=this.properties,i=[...cp(e),...hp(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(Nh(n))}else t!==void 0&&e.push(Nh(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 rp(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:ll).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),l=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:ll;this.m=n;let h=l.fromAttribute(e,o.type);this[n]=h??this.T?.get(n)??h,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??Wh)(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},l){i&&!(this.T??=new Map).has(t)&&(this.T.set(t,l??e??this[t]),o!==!0||l!==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:l}=o,h=this[n];l!==!0||this._$AL.has(n)||h===void 0||this.M(n,void 0,o,h)}}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[zn("elementProperties")]=new Map,Oi[zn("finalized")]=new Map,pp?.({ReactiveElement:Oi}),(Do.reactiveElementVersions??=[]).push("2.1.1");var ml=globalThis,Po=ml.trustedTypes,Uh=Po?Po.createPolicy("lit-html",{createHTML:s=>s}):void 0,qh="$lit$",Ni=`lit$${Math.random().toFixed(9).slice(2)}$`,Xh="?"+Ni,fp=`<${Xh}>`,ms=document,Hn=()=>ms.createComment(""),jn=s=>s===null||typeof s!="object"&&typeof s!="function",bl=Array.isArray,gp=s=>bl(s)||typeof s?.[Symbol.iterator]=="function",al=`[
|
|
598
|
-
\f\r]`,Un=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,zh=/-->/g,Hh=/>/g,fs=RegExp(`>|${al}(?:([^\\s"'>=/]+)(${al}*=${al}*(?:[^
|
|
599
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),jh=/'/g,Vh=/"/g,Kh=/^(?:script|style|textarea|title)$/i,yl=s=>(t,...e)=>({_$litType$:s,strings:t,values:e}),Mt=yl(1),Xg=yl(2),Kg=yl(3),Qs=Symbol.for("lit-noChange"),ae=Symbol.for("lit-nothing"),Gh=new WeakMap,gs=ms.createTreeWalker(ms,129);function Yh(s,t){if(!bl(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return Uh!==void 0?Uh.createHTML(t):t}var mp=(s,t)=>{let e=s.length-1,i=[],n,o=t===2?"<svg>":t===3?"<math>":"",l=Un;for(let h=0;h<e;h++){let g=s[h],m,d,a=-1,f=0;for(;f<g.length&&(l.lastIndex=f,d=l.exec(g),d!==null);)f=l.lastIndex,l===Un?d[1]==="!--"?l=zh:d[1]!==void 0?l=Hh:d[2]!==void 0?(Kh.test(d[2])&&(n=RegExp("</"+d[2],"g")),l=fs):d[3]!==void 0&&(l=fs):l===fs?d[0]===">"?(l=n??Un,a=-1):d[1]===void 0?a=-2:(a=l.lastIndex-d[2].length,m=d[1],l=d[3]===void 0?fs:d[3]==='"'?Vh:jh):l===Vh||l===jh?l=fs:l===zh||l===Hh?l=Un:(l=fs,n=void 0);let A=l===fs&&s[h+1].startsWith("/>")?" ":"";o+=l===Un?g+fp:a>=0?(i.push(m),g.slice(0,a)+qh+g.slice(a)+Ni+A):g+Ni+(a===-2?h:A)}return[Yh(s,o+(s[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},Vn=class s{constructor({strings:t,_$litType$:e},i){let n;this.parts=[];let o=0,l=0,h=t.length-1,g=this.parts,[m,d]=mp(t,e);if(this.el=s.createElement(m,i),gs.currentNode=this.el.content,e===2||e===3){let a=this.el.content.firstChild;a.replaceWith(...a.childNodes)}for(;(n=gs.nextNode())!==null&&g.length<h;){if(n.nodeType===1){if(n.hasAttributes())for(let a of n.getAttributeNames())if(a.endsWith(qh)){let f=d[l++],A=n.getAttribute(a).split(Ni),C=/([.?@])?(.*)/.exec(f);g.push({type:1,index:o,name:C[2],strings:A,ctor:C[1]==="."?hl:C[1]==="?"?dl:C[1]==="@"?ul:tn}),n.removeAttribute(a)}else a.startsWith(Ni)&&(g.push({type:6,index:o}),n.removeAttribute(a));if(Kh.test(n.tagName)){let a=n.textContent.split(Ni),f=a.length-1;if(f>0){n.textContent=Po?Po.emptyScript:"";for(let A=0;A<f;A++)n.append(a[A],Hn()),gs.nextNode(),g.push({type:2,index:++o});n.append(a[f],Hn())}}}else if(n.nodeType===8)if(n.data===Xh)g.push({type:2,index:o});else{let a=-1;for(;(a=n.data.indexOf(Ni,a+1))!==-1;)g.push({type:7,index:o}),a+=Ni.length-1}o++}}static createElement(t,e){let i=ms.createElement("template");return i.innerHTML=t,i}};function Zs(s,t,e=s,i){if(t===Qs)return t;let n=i!==void 0?e.N?.[i]:e.O,o=jn(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=Zs(s,n._$AS(s,t.values),n,i)),t}var cl=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??ms).importNode(e,!0);gs.currentNode=n;let o=gs.nextNode(),l=0,h=0,g=i[0];for(;g!==void 0;){if(l===g.index){let m;g.type===2?m=new Gn(o,o.nextSibling,this,t):g.type===1?m=new g.ctor(o,g.name,g.strings,this,t):g.type===6&&(m=new pl(o,this,t)),this._$AV.push(m),g=i[++h]}l!==g?.index&&(o=gs.nextNode(),l++)}return gs.currentNode=ms,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++}},Gn=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=Zs(this,t,e),jn(t)?t===ae||t==null||t===""?(this._$AH!==ae&&this._$AR(),this._$AH=ae):t!==this._$AH&&t!==Qs&&this.L(t):t._$litType$!==void 0?this.j(t):t.nodeType!==void 0?this.I(t):gp(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&&jn(this._$AH)?this._$AA.nextSibling.data=t:this.I(ms.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=Vn.createElement(Yh(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.V(e);else{let o=new cl(n,this),l=o.R(this.options);o.V(e),this.I(l),this._$AH=o}}_$AC(t){let e=Gh.get(t.strings);return e===void 0&&Gh.set(t.strings,e=new Vn(t)),e}H(t){bl(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(Hn()),this.B(Hn()),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))}},tn=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,l=!1;if(o===void 0)t=Zs(this,t,e,0),l=!jn(t)||t!==this._$AH&&t!==Qs,l&&(this._$AH=t);else{let h=t,g,m;for(t=o[0],g=0;g<o.length-1;g++)m=Zs(this,h[i+g],e,g),m===Qs&&(m=this._$AH[g]),l||=!jn(m)||m!==this._$AH[g],m===ae?t=ae:t!==ae&&(t+=(m??"")+o[g+1]),this._$AH[g]=m}l&&!n&&this.W(t)}W(t){t===ae?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},hl=class extends tn{constructor(){super(...arguments),this.type=3}W(t){this.element[this.name]=t===ae?void 0:t}},dl=class extends tn{constructor(){super(...arguments),this.type=4}W(t){this.element.toggleAttribute(this.name,!!t&&t!==ae)}},ul=class extends tn{constructor(t,e,i,n,o){super(t,e,i,n,o),this.type=5}_$AI(t,e=this){if((t=Zs(this,t,e,0)??ae)===Qs)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)}},pl=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){Zs(this,t)}};var bp=ml.litHtmlPolyfillSupport;bp?.(Vn,Gn),(ml.litHtmlVersions??=[]).push("3.3.1");var yp=(s,t,e)=>{let i=e?.renderBefore??t,n=i._$litPart$;if(n===void 0){let o=e?.renderBefore??null;i._$litPart$=n=new Gn(t.insertBefore(Hn(),o),o,void 0,e??{})}return n._$AI(s),n},vl=globalThis;var se=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=yp(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this.rt?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this.rt?.setConnected(!1)}render(){return Qs}};se._$litElement$=!0,se.finalized=!0,vl.litElementHydrateSupport?.({LitElement:se});var vp=vl.litElementPolyfillSupport;vp?.({LitElement:se});(vl.litElementVersions??=[]).push("4.2.1");var Wn=class extends se{disconnectedCallback(){super.disconnectedCallback(),this.activeSlideIndex=0}updated(t){super.updated(t),t.has("images")&&Array.isArray(this.images)&&this.images.some(e=>e.type==="markdown")&&(!window.marked||!window.marked.parse)&&ki().then(()=>this.requestUpdate())}static properties={docId:{type:String},docName:{type:String},images:{type:Array},activeSlideIndex:{type:Number,state:!0},ocr:{type:Boolean},pdf:{type:Boolean}};get hasImages(){return(this.images||[]).some(t=>t.type!=="markdown"&&!!t.src)}get hasMarkdown(){return(this.images||[]).some(t=>t.type==="markdown")}get pageCount(){return(this.images||[]).length}static styles=Bi`
|
|
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`
|
|
600
541
|
:host {
|
|
601
542
|
display: block;
|
|
602
543
|
position: absolute;
|
|
@@ -707,87 +648,11 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
707
648
|
background: rgba(15, 23, 42, 0.95);
|
|
708
649
|
border-color: rgba(255, 255, 255, 0.4);
|
|
709
650
|
}
|
|
710
|
-
|
|
711
|
-
width: 100%;
|
|
712
|
-
height: 100%;
|
|
713
|
-
box-sizing: border-box;
|
|
714
|
-
padding: 60px 24px 24px 24px;
|
|
715
|
-
overflow-y: auto;
|
|
716
|
-
background: #151f2a;
|
|
717
|
-
color: #f8fafc;
|
|
718
|
-
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
|
719
|
-
line-height: 1.6;
|
|
720
|
-
}
|
|
721
|
-
.markdown-body {
|
|
722
|
-
max-width: 800px;
|
|
723
|
-
margin: 0 auto;
|
|
724
|
-
}
|
|
725
|
-
.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4 {
|
|
726
|
-
color: #f1f5f9;
|
|
727
|
-
margin-top: 1.5em;
|
|
728
|
-
margin-bottom: 0.5em;
|
|
729
|
-
font-weight: 600;
|
|
730
|
-
line-height: 1.25;
|
|
731
|
-
border-bottom: 1px solid rgba(255,255,255,0.1);
|
|
732
|
-
padding-bottom: 0.3em;
|
|
733
|
-
}
|
|
734
|
-
.markdown-body h1 { font-size: 2em; }
|
|
735
|
-
.markdown-body h2 { font-size: 1.5em; }
|
|
736
|
-
.markdown-body h3 { font-size: 1.25em; }
|
|
737
|
-
.markdown-body p { margin-top: 0; margin-bottom: 1em; }
|
|
738
|
-
.markdown-body ul, .markdown-body ol { padding-left: 2em; margin-bottom: 1em; }
|
|
739
|
-
.markdown-body li { margin-bottom: 0.3em; }
|
|
740
|
-
.markdown-body code {
|
|
741
|
-
background: rgba(255,255,255,0.1);
|
|
742
|
-
padding: 0.2em 0.4em;
|
|
743
|
-
border-radius: 4px;
|
|
744
|
-
font-family: monospace;
|
|
745
|
-
font-size: 0.9em;
|
|
746
|
-
}
|
|
747
|
-
.markdown-body pre {
|
|
748
|
-
background: #0f172a;
|
|
749
|
-
padding: 1em;
|
|
750
|
-
border-radius: 8px;
|
|
751
|
-
overflow-x: auto;
|
|
752
|
-
border: 1px solid rgba(255,255,255,0.1);
|
|
753
|
-
}
|
|
754
|
-
.markdown-body pre code { background: none; padding: 0; }
|
|
755
|
-
.markdown-body blockquote {
|
|
756
|
-
border-left: 4px solid #38bdf8;
|
|
757
|
-
margin: 1em 0;
|
|
758
|
-
padding-left: 1em;
|
|
759
|
-
color: #cbd5e1;
|
|
760
|
-
font-style: italic;
|
|
761
|
-
}
|
|
762
|
-
.markdown-body table {
|
|
763
|
-
border-collapse: collapse;
|
|
764
|
-
width: 100%;
|
|
765
|
-
margin-bottom: 1em;
|
|
766
|
-
}
|
|
767
|
-
.markdown-body th, .markdown-body td {
|
|
768
|
-
border: 1px solid rgba(255,255,255,0.15);
|
|
769
|
-
padding: 8px 12px;
|
|
770
|
-
text-align: left;
|
|
771
|
-
}
|
|
772
|
-
.markdown-body th {
|
|
773
|
-
background: rgba(255,255,255,0.1);
|
|
774
|
-
}
|
|
775
|
-
.markdown-body img {
|
|
776
|
-
max-width: 100%;
|
|
777
|
-
height: auto;
|
|
778
|
-
border-radius: 6px;
|
|
779
|
-
}
|
|
780
|
-
`;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.type==="markdown"||!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})):e==="images"?this.dispatchEvent(new CustomEvent("doc:download-images",{bubbles:!0,composed:!1,detail:i})):e==="markdown"&&this.dispatchEvent(new CustomEvent("doc:download-markdown",{bubbles:!0,composed:!1,detail:i}))}handleSlideChange(t){this.activeSlideIndex=t.detail?.index||0}renderItem(t){if(t.type==="markdown"){let e=t.content||"",i=window.marked&&window.marked.parse?window.marked.parse(e):e;return Mt`
|
|
781
|
-
<sl-carousel-item data-id="${t.id}">
|
|
782
|
-
<div class="markdown-container">
|
|
783
|
-
<div class="markdown-body" .innerHTML=${i}></div>
|
|
784
|
-
</div>
|
|
785
|
-
</sl-carousel-item>
|
|
786
|
-
`}return Mt`
|
|
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`
|
|
787
652
|
<sl-carousel-item data-id="${t.id}">
|
|
788
653
|
<div class="item" style="background-image: url('${t.src}')"></div>
|
|
789
654
|
</sl-carousel-item>
|
|
790
|
-
`}render(){let t=this.
|
|
655
|
+
`}render(){let t=this.visibleImages[this.activeSlideIndex],e=this.ocr!==!1&&t&&!!t.src;return Rt`
|
|
791
656
|
<div class="top-bar">
|
|
792
657
|
<div class="top-bar-left">
|
|
793
658
|
<button class="back" @click=${this.handleBackClick} aria-label="Back">←</button>
|
|
@@ -795,7 +660,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
795
660
|
</div>
|
|
796
661
|
|
|
797
662
|
<div class="top-bar-right">
|
|
798
|
-
${e?
|
|
663
|
+
${e?Rt`
|
|
799
664
|
<button class="ocr-btn" @click=${this.handleOcrClick} aria-label="Extract text">
|
|
800
665
|
<sl-icon name="card-text"></sl-icon>
|
|
801
666
|
<span>Extract Text</span>
|
|
@@ -809,20 +674,22 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
809
674
|
<sl-icon name="chevron-down" style="font-size: 0.75rem;"></sl-icon>
|
|
810
675
|
</button>
|
|
811
676
|
<sl-menu @sl-select=${this.handleExportSelect}>
|
|
812
|
-
${this.pdf!==!1?
|
|
677
|
+
${this.pdf!==!1?Rt`
|
|
813
678
|
<sl-menu-item value="pdf" ?disabled=${this.pageCount===0}>
|
|
814
679
|
<sl-icon slot="prefix" name="file-earmark-pdf"></sl-icon>
|
|
815
680
|
Download as PDF
|
|
816
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
|
+
`:""}
|
|
817
688
|
`:""}
|
|
818
689
|
<sl-menu-item value="images" ?disabled=${this.pageCount===0}>
|
|
819
690
|
<sl-icon slot="prefix" name="images"></sl-icon>
|
|
820
691
|
Download as Images (ZIP)
|
|
821
692
|
</sl-menu-item>
|
|
822
|
-
<sl-menu-item value="markdown" ?disabled=${!this.hasMarkdown}>
|
|
823
|
-
<sl-icon slot="prefix" name="markdown"></sl-icon>
|
|
824
|
-
Download as Markdown
|
|
825
|
-
</sl-menu-item>
|
|
826
693
|
</sl-menu>
|
|
827
694
|
</sl-dropdown>
|
|
828
695
|
</div>
|
|
@@ -833,9 +700,9 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
833
700
|
orientation="vertical"
|
|
834
701
|
@sl-slide-change=${this.handleSlideChange}
|
|
835
702
|
>
|
|
836
|
-
${this.
|
|
703
|
+
${this.visibleImages.map(i=>this.renderItem(i))}
|
|
837
704
|
</sl-carousel>
|
|
838
|
-
`}};customElements.define("copio-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`
|
|
839
706
|
<sl-dialog
|
|
840
707
|
label="Add / Edit"
|
|
841
708
|
class="dialog-add-edit"
|
|
@@ -880,7 +747,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
880
747
|
>
|
|
881
748
|
</div>
|
|
882
749
|
</sl-dialog>
|
|
883
|
-
`}};customElements.define("copio-add-edit-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`
|
|
884
751
|
.wrapper {
|
|
885
752
|
margin-left: auto;
|
|
886
753
|
margin-right: auto;
|
|
@@ -939,7 +806,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
939
806
|
background: white;
|
|
940
807
|
cursor: pointer;
|
|
941
808
|
}
|
|
942
|
-
`;#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-
|
|
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`
|
|
943
810
|
<div class="wrapper" @click=${this.#t}>
|
|
944
811
|
<div class="inner">
|
|
945
812
|
<sl-avatar label="Document icon">
|
|
@@ -947,7 +814,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
947
814
|
</sl-avatar>
|
|
948
815
|
|
|
949
816
|
<div class="titles">
|
|
950
|
-
${this.isRenaming?
|
|
817
|
+
${this.isRenaming?Rt`
|
|
951
818
|
<div class="rename-container" @click=${t=>t.stopPropagation()}>
|
|
952
819
|
<sl-input
|
|
953
820
|
class="rename-input"
|
|
@@ -967,7 +834,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
967
834
|
@click=${this.cancelRename}
|
|
968
835
|
></sl-icon-button>
|
|
969
836
|
</div>
|
|
970
|
-
`:
|
|
837
|
+
`:Rt`
|
|
971
838
|
<div class="doc-title">${this.name||"Untitled Document"}</div>
|
|
972
839
|
<div class="doc-page-count">
|
|
973
840
|
${this.pageCount} ${this.pageCount===1?"page":"pages"}
|
|
@@ -989,7 +856,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
989
856
|
<sl-icon slot="prefix" name="pencil"></sl-icon>
|
|
990
857
|
Rename
|
|
991
858
|
</sl-menu-item>
|
|
992
|
-
${this.ocr!==!1?
|
|
859
|
+
${this.ocr!==!1?Rt`
|
|
993
860
|
<sl-menu-item
|
|
994
861
|
value="extract-ocr"
|
|
995
862
|
?disabled=${!this.hasImages}
|
|
@@ -1000,7 +867,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1000
867
|
</sl-menu-item>
|
|
1001
868
|
`:""}
|
|
1002
869
|
<sl-divider></sl-divider>
|
|
1003
|
-
${this.pdf!==!1?
|
|
870
|
+
${this.pdf!==!1?Rt`
|
|
1004
871
|
<sl-menu-item
|
|
1005
872
|
value="download"
|
|
1006
873
|
?disabled=${this.pageCount===0}
|
|
@@ -1009,6 +876,16 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1009
876
|
<sl-icon slot="prefix" name="file-earmark-pdf"></sl-icon>
|
|
1010
877
|
Download as PDF
|
|
1011
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
|
+
`:""}
|
|
1012
889
|
`:""}
|
|
1013
890
|
<sl-menu-item
|
|
1014
891
|
value="download-images"
|
|
@@ -1018,14 +895,6 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1018
895
|
<sl-icon slot="prefix" name="images"></sl-icon>
|
|
1019
896
|
Download as Images
|
|
1020
897
|
</sl-menu-item>
|
|
1021
|
-
<sl-menu-item
|
|
1022
|
-
value="download-markdown"
|
|
1023
|
-
?disabled=${!this.hasMarkdown}
|
|
1024
|
-
title=${this.hasMarkdown?"Download as Markdown":"No markdown notes in document"}
|
|
1025
|
-
>
|
|
1026
|
-
<sl-icon slot="prefix" name="markdown"></sl-icon>
|
|
1027
|
-
Download as Markdown
|
|
1028
|
-
</sl-menu-item>
|
|
1029
898
|
<sl-divider></sl-divider>
|
|
1030
899
|
<sl-menu-item value="delete">
|
|
1031
900
|
<sl-icon slot="prefix" name="trash"></sl-icon>
|
|
@@ -1034,7 +903,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1034
903
|
</sl-menu>
|
|
1035
904
|
</sl-dropdown>
|
|
1036
905
|
</div>
|
|
1037
|
-
`}};customElements.define("copio-row",
|
|
906
|
+
`}};customElements.define("copio-row",er);var ir=class extends se{static styles=Hi`
|
|
1038
907
|
header {
|
|
1039
908
|
background-color: #151f2a;
|
|
1040
909
|
color: white;
|
|
@@ -1063,7 +932,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1063
932
|
align-items: center;
|
|
1064
933
|
justify-content: center;
|
|
1065
934
|
}
|
|
1066
|
-
`;static properties={_storageEstimate:{state:!0},_isPersisted:{state:!0}};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
|
|
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`
|
|
1067
936
|
<header>
|
|
1068
937
|
<div class="header-left">
|
|
1069
938
|
<sl-dropdown @sl-show=${this.#t}>
|
|
@@ -1078,8 +947,10 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1078
947
|
<sl-menu-item value="clear-cache">Clear cache & update</sl-menu-item>
|
|
1079
948
|
<sl-divider></sl-divider>
|
|
1080
949
|
<sl-menu-item disabled>
|
|
1081
|
-
Storage: ${this._formatBytes(this._storageEstimate?.usage)}
|
|
1082
|
-
|
|
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"})
|
|
1083
954
|
</sl-menu-item>
|
|
1084
955
|
</sl-menu>
|
|
1085
956
|
</sl-dropdown>
|
|
@@ -1087,7 +958,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1087
958
|
<h1>COPIO</h1>
|
|
1088
959
|
<div class="header-right"></div>
|
|
1089
960
|
</header>
|
|
1090
|
-
`}};customElements.define("copio-header",
|
|
961
|
+
`}};customElements.define("copio-header",ir);var sr=class extends se{disconnectedCallback(){super.disconnectedCallback()}static styles=Hi`
|
|
1091
962
|
.lds-roller {
|
|
1092
963
|
display: inline-block;
|
|
1093
964
|
position: relative;
|
|
@@ -1172,7 +1043,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1172
1043
|
transform: rotate(360deg);
|
|
1173
1044
|
}
|
|
1174
1045
|
}
|
|
1175
|
-
`;render(){return
|
|
1046
|
+
`;render(){return Rt`
|
|
1176
1047
|
<div
|
|
1177
1048
|
style="
|
|
1178
1049
|
background: #151f2a;
|
|
@@ -1218,7 +1089,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1218
1089
|
<div></div>
|
|
1219
1090
|
</div>
|
|
1220
1091
|
</div>
|
|
1221
|
-
`}};customElements.define("copio-loader",
|
|
1092
|
+
`}};customElements.define("copio-loader",sr);ci();Bi();var rr=`
|
|
1222
1093
|
:host {
|
|
1223
1094
|
all: initial;
|
|
1224
1095
|
display: block;
|
|
@@ -2003,6 +1874,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2003
1874
|
overflow-x: auto;
|
|
2004
1875
|
min-height: 80px;
|
|
2005
1876
|
flex-shrink: 0;
|
|
1877
|
+
scrollbar-width: thin;
|
|
2006
1878
|
}
|
|
2007
1879
|
|
|
2008
1880
|
.copio-filmstrip-scroll {
|
|
@@ -2025,10 +1897,13 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2025
1897
|
height: 70px;
|
|
2026
1898
|
border-radius: var(--copio-radius-sm);
|
|
2027
1899
|
overflow: hidden;
|
|
2028
|
-
background: #
|
|
1900
|
+
background: var(--copio-color-surface-elevated, #1c2736);
|
|
2029
1901
|
border: 2px solid var(--copio-color-border);
|
|
2030
1902
|
cursor: pointer;
|
|
2031
1903
|
transition: all var(--copio-transition-fast);
|
|
1904
|
+
display: flex;
|
|
1905
|
+
align-items: center;
|
|
1906
|
+
justify-content: center;
|
|
2032
1907
|
}
|
|
2033
1908
|
|
|
2034
1909
|
.copio-filmstrip-item.is-active .copio-thumb-container {
|
|
@@ -2076,9 +1951,11 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2076
1951
|
}
|
|
2077
1952
|
|
|
2078
1953
|
.copio-thumb-img {
|
|
2079
|
-
width: 100%;
|
|
2080
|
-
height: 100%;
|
|
2081
|
-
|
|
1954
|
+
max-width: 100%;
|
|
1955
|
+
max-height: 100%;
|
|
1956
|
+
width: auto;
|
|
1957
|
+
height: auto;
|
|
1958
|
+
object-fit: contain;
|
|
2082
1959
|
}
|
|
2083
1960
|
|
|
2084
1961
|
/* Edit Action Toolbar & Primary Completion Dock */
|
|
@@ -2374,7 +2251,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2374
2251
|
}
|
|
2375
2252
|
.copio-thumb-container {
|
|
2376
2253
|
width: 112px;
|
|
2377
|
-
height:
|
|
2254
|
+
height: 140px;
|
|
2378
2255
|
}
|
|
2379
2256
|
.copio-toolbar,
|
|
2380
2257
|
.copio-controls-dock {
|
|
@@ -2391,7 +2268,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2391
2268
|
min-width: 200px;
|
|
2392
2269
|
}
|
|
2393
2270
|
}
|
|
2394
|
-
`,
|
|
2271
|
+
`,nr=null;function $o(){if(nr)return nr;if(typeof CSSStyleSheet<"u"&&typeof Document<"u"&&"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype)try{return nr=new CSSStyleSheet,nr.replaceSync(rr),nr}catch{return null}return null}function Uo(s){if(!s)return;let t=$o();if(t&&"adoptedStyleSheets"in s){let e=s.adoptedStyleSheets||[];e.includes(t)||(s.adoptedStyleSheets=[...e,t])}else if(!s.querySelector("style[data-copio-encapsulated-styles]")){let e=document.createElement("style");e.setAttribute("data-copio-encapsulated-styles",""),e.textContent=rr,s.appendChild(e)}}var Dp=typeof HTMLElement<"u"?HTMLElement:class{},or=class extends Dp{#t=null;#e=null;#i=null;#n=!1;#r="viewfinder";#s=0;#a=0;#l=!1;#o=!1;#h=null;#u=null;#d=0;#c=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 gs(t)}connectedCallback(){this.shadowRoot&&(Uo(this.shadowRoot),this.#b()),typeof Oi=="function"&&typeof document<"u"&&Ni()===document.body&&Oi(this.shadowRoot?.querySelector(".copio-scanner-container")||this),this.#t&&(this.#i=this.#t.subscribe(async()=>{let t=await this.getPages();this.dispatch(te.PAGES_CHANGED,{pages:t,docId:this.docId}),this.#w()})),this.hasAttribute&&this.hasAttribute("asset-base")&&us(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 Oi=="function"&&typeof document<"u"){let t=this.shadowRoot?.querySelector(".copio-scanner-container")||this;Ni()===t&&Oi(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 n=this.shadowRoot;if(n){let o=n.getElementById("viewfinder-section"),c=n.getElementById("workbench-section");o&&c&&(o.style.display=i==="viewfinder"?"flex":"none",c.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 n of i)"ocr"in n&&(n.ocr=this.ocrEnabled),"pdf"in n&&(n.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=`
|
|
2395
2272
|
<div class="copio-scanner-container copio-scanner-host" part="scanner-root">
|
|
2396
2273
|
<header class="copio-header" part="header">
|
|
2397
2274
|
<div class="copio-header-left">
|
|
@@ -2568,7 +2445,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2568
2445
|
<input type="file" id="internal-file-input" accept="image/*" style="display: none;" />
|
|
2569
2446
|
<slot></slot>
|
|
2570
2447
|
</div>
|
|
2571
|
-
`,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 n=i.target;n.files&&n.files.length>0&&(await this.addFiles(n.files),n.value="")}),t.getElementById("btn-shutter")?.addEventListener("click",async()=>{await this.#_()}),t.getElementById("btn-review")?.addEventListener("click",()=>{this.stage="workbench"}),t.getElementById("btn-retake")?.addEventListener("click",()=>{this.#
|
|
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 n=i.target;n.files&&n.files.length>0&&(await this.addFiles(n.files),n.value="")}),t.getElementById("btn-shutter")?.addEventListener("click",async()=>{await this.#_()}),t.getElementById("btn-review")?.addEventListener("click",()=>{this.stage="workbench"}),t.getElementById("btn-retake")?.addEventListener("click",()=>{this.#l=!0,this.#o=!1,this.stage="viewfinder"}),t.getElementById("btn-rotate")?.addEventListener("click",async()=>{await this.#P()}),t.getElementById("btn-filter-bw")?.addEventListener("click",async()=>{await this.#T()}),t.getElementById("btn-crop")?.addEventListener("click",async()=>{await this.#M()}),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.#o=!1,this.#s=0,this.#w()}),t.getElementById("btn-card-back")?.addEventListener("click",()=>{this.#o=!1,this.#s=1,this.#w()}),this.#C()}#C(){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 n=null,o=!1,c=0,l=0,h=null,m=f=>{let w=f.target.closest(".copio-crop-handle");if(w)n=w.getAttribute("data-handle"),o=!1;else if(f.target===e||f.target.classList.contains("copio-crop-grid"))n=null,o=!0;else return;f.preventDefault(),f.stopPropagation(),c=f.clientX,l=f.clientY,h=this.#h?{...this.#h}:{x:.05,y:.05,w:.9,h:.9},window.addEventListener("pointermove",u),window.addEventListener("pointerup",a)},u=f=>{if(!n&&!o||!h)return;let E=(t.getElementById("canvas-wrapper")||t.getElementById("canvas-viewport"))?.getBoundingClientRect()||{width:300,height:400},p=(f.clientX-c)/Math.max(E.width,1),y=(f.clientY-l)/Math.max(E.height,1),{x:r,y:d,w:b,h:x}=h;if(o)r=Math.min(Math.max(0,r+p),1-b),d=Math.min(Math.max(0,d+y),1-x);else if(n){if(n.includes("w")){let _=Math.min(Math.max(0,r+p),r+b-.1);b+=r-_,r=_}if(n.includes("e")&&(b=Math.min(Math.max(.1,b+p),1-r)),n.includes("n")){let _=Math.min(Math.max(0,d+y),d+x-.1);x+=d-_,d=_}n.includes("s")&&(x=Math.min(Math.max(.1,x+y),1-d))}this.#h={x:r,y:d,w:b,h:x},this.#R()},a=()=>{n=null,o=!1,h=null,window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",a)};e.addEventListener("pointerdown",m),i.forEach(f=>{f.addEventListener("pointerdown",m)})}#R(){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.#c?this.#c:(this.#c=(async()=>{try{await Promise.resolve(),await this.#x()}finally{this.#c=null}})(),this.#c)}async#x(){if(this.shadowRoot)try{let t=await this.getPages();this.#a=t.length;let e=this.shadowRoot,i=e.getElementById("mode-badge");i&&(i.textContent=(this.mode||"single").toUpperCase());let n=e.getElementById("tab-viewfinder"),o=e.getElementById("tab-workbench");n&&n.setAttribute("aria-selected",String(this.#r==="viewfinder")),o&&o.setAttribute("aria-selected",String(this.#r==="workbench"));let c=e.getElementById("viewfinder-section"),l=e.getElementById("workbench-section");c&&l&&(this.#r==="viewfinder"?(c.style.display="flex",l.style.display="none"):(c.style.display="none",l.style.display="flex"));let h=e.getElementById("framing-guide");h&&h.setAttribute("data-aspect",this.aspect||"auto");let m=e.getElementById("step-pill-text");m&&(this.#g?m.textContent="Camera Active \xB7 Tap Shutter to Snap":this.aspect==="card"&&this.maxPages===2?m.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"?m.textContent="Align Card Inside Frame":this.mode==="batch"?m.textContent=`Batch Capture \xB7 Page ${t.length+1}`:m.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"),f=e.getElementById("review-pill-text");if(a&&f&&(t.length>0?(a.style.display="inline-flex",f.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 w=t[this.#s],E=e.getElementById("card-side-switcher");if(E){let x=this.aspect==="card"&&this.maxPages===2;E.style.display=x?"flex":"none";let _=e.getElementById("btn-card-front"),S=e.getElementById("btn-card-back");_&&(_.classList.toggle("active",this.#s===0),_.setAttribute("aria-selected",String(this.#s===0))),S&&(S.classList.toggle("active",this.#s===1),S.setAttribute("aria-selected",String(this.#s===1)))}let p=e.getElementById("canvas-viewport");p&&p.classList.toggle("is-cropping",this.#o);let y=e.getElementById("stage-img");if(y)if(this.#o){let x=w.edits?.rotate||0,_=w.edits?.filter||"none",S=w.originalSrc||w.src||"";if(x!==0||_!=="none"){let R=this.#t?await this.#t.renderEdits(S,{rotate:x,filter:_}):S;y.src=R||S}else y.src=S}else y.src=w.src||w.originalSrc||"";let r=e.getElementById("crop-layer");if(this.#o){if(!r){let S=e.getElementById("canvas-wrapper");r=document.createElement("div"),r.className="copio-crop-layer",r.id="crop-layer",r.innerHTML=`
|
|
2572
2449
|
<div class="copio-crop-box" id="crop-box">
|
|
2573
2450
|
<div class="copio-crop-grid"></div>
|
|
2574
2451
|
<span class="copio-crop-handle nw" data-handle="nw"></span>
|
|
@@ -2580,7 +2457,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2580
2457
|
<span class="copio-crop-handle s edge-s" data-handle="s"></span>
|
|
2581
2458
|
<span class="copio-crop-handle w edge-w" data-handle="w"></span>
|
|
2582
2459
|
</div>
|
|
2583
|
-
`,
|
|
2460
|
+
`,S?.appendChild(r),this.#C()}r.style.display="block";let x=w.edits?.rotate||0,_=w.edits?.crop;this.#h=_?Wa(_,x):{x:.05,y:.05,w:.9,h:.9},this.#R()}else r&&r.remove();let d=e.getElementById("crop-btn-label");d&&(d.textContent=this.#o?"Apply":"Crop");let b=e.getElementById("btn-primary-complete");b&&(this.aspect==="card"&&this.maxPages===2&&t.length===1?b.textContent="Next: Capture Back (Step 2/2) \u2192":this.aspect==="card"&&t.length>=2?b.textContent="\u2713 Complete ID Scan (2 Sides)":this.mode==="batch"?b.textContent=`\u2713 Complete Scan (${t.length} Pages)`:b.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((n,o)=>{let c=document.createElement("div");c.className=`copio-filmstrip-item ${o===this.#s?"is-active":""}`,c.setAttribute("data-index",String(o)),c.innerHTML=`
|
|
2584
2461
|
<div class="copio-thumb-container">
|
|
2585
2462
|
<img src="${n.src||n.originalSrc}" alt="Page ${o+1}" class="copio-thumb-img" />
|
|
2586
2463
|
<span class="copio-thumb-num">${o+1}</span>
|
|
@@ -2591,27 +2468,21 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2591
2468
|
<button type="button" class="copio-reorder-btn move-right" title="Move Right" ${o===t.length-1?"disabled":""}>\u25B6</button>
|
|
2592
2469
|
</div>
|
|
2593
2470
|
`:""}
|
|
2594
|
-
`,
|
|
2471
|
+
`,c.querySelector(".copio-thumb-container")?.addEventListener("click",()=>{this.#s=o,this.#o=!1,this.#w()}),this.mode==="batch"&&(c.querySelector(".move-left")?.addEventListener("click",async l=>{l.stopPropagation(),await this.#E(o,o-1)}),c.querySelector(".move-right")?.addEventListener("click",async l=>{l.stopPropagation(),await this.#E(o,o+1)})),i.appendChild(c)}))}async#E(t,e){let i=await this.getPages();if(e<0||e>=i.length||t===e)return;let n=i.map(c=>c.id),[o]=n.splice(t,1);n.splice(e,0,o),await this.#t.reorderPages(this.#p,n),this.#s=e,this.#w()}#A(){this.#g&&(this.#g.getTracks().forEach(n=>n.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#_(){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 c=o.getContext("2d");if(c){c.drawImage(e,0,0,o.width,o.height);let l=await new Promise(h=>o.toBlob(h,"image/jpeg",.92));if(l){this.#A();let h=new File([l],`capture_${Date.now()}.jpg`,{type:"image/jpeg"});await this.addFiles([h]);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 c=t?.getElementById("step-pill-text");c&&(c.textContent="Camera Active \xB7 Tap Shutter to Snap");return}catch{}let n=t?.getElementById("internal-file-input");n&&typeof n.click=="function"&&n.click()}async#P(){let e=(await this.getPages())[this.#s];if(!e)return;this.#o&&(this.#o=!1,this.#h=null);let n=((e.edits?.rotate||0)+90)%360;await this.#t.applyEdit(this.#p,e.id,{rotate:n}),await this.#w()}async#T(){let e=(await this.getPages())[this.#s];if(!e)return;this.#o&&(this.#o=!1,this.#h=null);let n=(e.edits?.filter||"none")==="bw"?"none":"bw";await this.#t.applyEdit(this.#p,e.id,{filter:n}),await this.#w()}async#M(){let e=(await this.getPages())[this.#s];if(e){if(this.#o){this.#o=!1;let i=this.#h;if(this.#h=null,i){let n=e.edits?.rotate||0,o=Ga(i,n);await this.#t.applyEdit(this.#p,e.id,{crop:o})}}else this.#o=!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(te.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=`
|
|
2595
2472
|
<div class="copio-toast copio-toast-undo">
|
|
2596
2473
|
<span>Page deleted</span>
|
|
2597
2474
|
<button type="button" class="copio-btn-toast-undo" id="btn-toast-undo">
|
|
2598
|
-
Undo (${this.#
|
|
2475
|
+
Undo (${this.#d}s)
|
|
2599
2476
|
</button>
|
|
2600
2477
|
</div>
|
|
2601
|
-
`,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#
|
|
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],c=await this.ocr(o?.id||null),l=c.averageConfidence||0,h=l<=1&&l>0?Math.round(l*100):Math.round(l);i.innerHTML=`
|
|
2602
2479
|
<div class="copio-ocr-content">
|
|
2603
|
-
<pre class="copio-ocr-text">${
|
|
2480
|
+
<pre class="copio-ocr-text">${c.text||"No text detected."}</pre>
|
|
2604
2481
|
<div class="copio-ocr-meta">
|
|
2605
|
-
<span>Confidence: ${
|
|
2482
|
+
<span>Confidence: ${h}%</span>
|
|
2606
2483
|
</div>
|
|
2607
2484
|
</div>
|
|
2608
|
-
`}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.#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((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.#T()}async toggleActivePageBw(){return this.#k()}async toggleCropMode(){return this.#M()}async deleteActivePageWithUndo(){return this.#P()}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 cs&&(this.#t=t)}dispatch(t,e={}){return lo(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.#h);else if(this.#c||this.maxPages>0&&e.length>=this.maxPages){let l=Math.min(this.#s,e.length-1),h=e[l];h&&(i=l,await this.#t.deletePage(this.#h,h.id))}}this.#c=!1;let n=await this.#t.addFiles(t,this.#h);for(let l=0;l<n.length;l++)this.dispatch(te.PAGE_ADDED,{page:n[l],pageNumber:l+1,docId:this.docId,source:"file"});let o=await this.getPages();if(i!==null&&n.length===1&&i<o.length-1){let l=o.map(g=>g.id),h=l.pop();h&&(l.splice(i,0,h),await this.#t.reorderPages(this.#h,l),o=await this.getPages())}return this.#o=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.#h)}async clear(){this.#A(),this.#s=0,this.#o=0,this.#c=!1,this.#a=!1,await this.#t.clear(this.#h),this.dispatch(te.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#w()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#h,t);return this.dispatch(te.EXPORT_COMPLETE,{type:"pdf",format:"pdf",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 exportZip(t={}){try{let e=await this.#t.exportZip(this.#h,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.#h,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",Zn);var Lo=[{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}"}],Ye=null,Ro=null,$i=null;function xp(s){return s==="eng"?ni("assets/tessdata"):"https://tessdata.projectnaptha.com/4.0.0_fast"}function Ap(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 tr(s="eng",t=null){if($i=t,Ye&&Ro===s)return Ye;if(Ye){try{await Ye.terminate()}catch(l){console.warn("Error terminating old OCR worker:",l)}Ye=null,Ro=null}let e=null;if(typeof window<"u"&&!window.Tesseract){$i&&typeof $i=="function"&&$i({status:"downloading-engine",progress:.05,message:"Downloading OCR engine..."});try{e=await Pt.progress({message:"Downloading OCR engine...",total:100,done:0})}catch{}}let n,o;try{n=await oo();let l=xp(s);o=await n.createWorker(s,1,{workerPath:ni("js/lib/tesseract-worker.min.js"),corePath:ni("js/lib/tesseract-core"),langPath:l,logger:h=>{if(e&&h.status==="loading tesseract core"){let g=Math.round((h.progress||0)*100);e.update(g,100,`Downloading OCR engine... ${g>0?g+"%":""}`.trim())}if($i&&typeof $i=="function"){let g=Ap(h.status,h.progress);$i({status:h.status,progress:typeof h.progress=="number"?h.progress:0,message:g,raw:h})}}})}finally{e?.close()}return Ye=o,Ro=s,Ye}async function er(s,t={}){let{lang:e="eng",onProgress:i=null,abortSignal:n=null}=t;if(n?.aborted){let g=new Error("OCR operation cancelled by user");throw g.name="AbortError",g}i&&i({status:"starting",progress:.05,message:"Starting OCR engine..."});let o=await tr(e,i);if(n?.aborted){let g=new Error("OCR operation cancelled by user");throw g.name="AbortError",g}i&&i({status:"recognizing text",progress:.2,message:"Recognizing text..."});let l=null,h=new Promise((g,m)=>{n&&(l=()=>{bs();let d=new Error("OCR operation cancelled by user");d.name="AbortError",m(d)},n.addEventListener("abort",l,{once:!0}))});try{let m=(await Promise.race([o.recognize(s),h]))?.data||{},d=(m.text||"").trim(),a=Math.round(m.confidence||0);return i&&i({status:"done",progress:1,message:"Text recognition complete!"}),{text:d,confidence:a,words:m.words||[],lines:m.lines||[],paragraphs:m.paragraphs||[],hocr:m.hocr||""}}finally{n&&l&&n.removeEventListener("abort",l)}}async function en(s,t={}){let{lang:e="eng",onPageProgress:i=null,abortSignal:n=null}=t,o=(s||[]).filter(d=>d.type!=="markdown"&&d.src);if(o.length===0)return{pagesResults:[],combinedText:"",averageConfidence:0,empty:!0};let l=[],h=0;for(let d=0;d<o.length;d++){if(n?.aborted){let u=new Error("OCR operation cancelled by user");throw u.name="AbortError",u}let a=o[d],f=d+1,A=o.length,C=await er(a.src,{lang:e,abortSignal:n,onProgress:u=>{if(i){let y=(d+(u.progress||0))/A;i({pageIndex:d,pageNumber:f,totalPages:A,pageProgress:u.progress||0,overallProgress:y,message:`Page ${f} of ${A}: ${u.message}`})}}});l.push({pageId:a.id,pageIndex:d,pageNumber:f,...C}),h+=C.confidence}let g=l.map(d=>l.length>1?`## Page ${d.pageNumber}
|
|
2609
|
-
|
|
2610
|
-
${d.text}`:d.text).join(`
|
|
2611
|
-
|
|
2612
|
-
---
|
|
2613
|
-
|
|
2614
|
-
`),m=Math.round(h/l.length);return{pagesResults:l,combinedText:g,averageConfidence:m}}async function bs(){if(Ye){try{await Ye.terminate()}catch(s){console.warn("Error during OCR worker termination:",s)}Ye=null,Ro=null,$i=null}}var ir=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),bs(),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(l=>l.type!=="markdown"&&l.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 en(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)}});this.isOpen&&!e.aborted&&(this.step="done",this.resultText=i.combinedText||"",this.confidence=i.averageConfidence||0,Pt.success("Text recognition complete"))}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",Pt.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,Pt.success("Copied text to clipboard"),setTimeout(()=>{this.copied=!1},2e3)}catch(t){console.error("Failed to copy text:",t),Pt.error("Failed to copy text to clipboard")}};downloadMarkdown=()=>{if(!this.resultText)return;let t=(this.docName||"document").replace(/[/\\?%*:|"<>]/g,"_"),e=new Blob([this.resultText],{type:"text/markdown;charset=utf-8"}),i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=`${t}-ocr.md`,n.click(),URL.revokeObjectURL(i),Pt.success(`Exported OCR markdown (${t}-ocr.md)`)};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),Pt.success(`Exported OCR text (${t}-ocr.txt)`)};saveAsNote=()=>{if(!this.resultText||!this.docId)return;let t={docId:this.docId,content:this.resultText,pageIndex:this._pageIndex};this.dispatchEvent(new CustomEvent("note:save",{bubbles:!0,composed:!1,detail:t})),Pt.success("Saved OCR text as note"),this.close()};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?Mt`
|
|
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`
|
|
2615
2486
|
<sl-dialog
|
|
2616
2487
|
label="${this._dialogLabel}"
|
|
2617
2488
|
open
|
|
@@ -2625,10 +2496,10 @@ ${d.text}`:d.text).join(`
|
|
|
2625
2496
|
@sl-change=${this.handleLangChange}
|
|
2626
2497
|
style="min-width: 180px;"
|
|
2627
2498
|
>
|
|
2628
|
-
${
|
|
2499
|
+
${ar.map(t=>Rt`<sl-option value=${t.code}>${t.flag} ${t.label}</sl-option>`)}
|
|
2629
2500
|
</sl-select>
|
|
2630
2501
|
|
|
2631
|
-
${this.step==="done"?
|
|
2502
|
+
${this.step==="done"?Rt`
|
|
2632
2503
|
<sl-badge
|
|
2633
2504
|
variant=${this.confidence>=75?"success":this.confidence>=50?"warning":"danger"}
|
|
2634
2505
|
>
|
|
@@ -2637,7 +2508,7 @@ ${d.text}`:d.text).join(`
|
|
|
2637
2508
|
`:""}
|
|
2638
2509
|
</div>
|
|
2639
2510
|
|
|
2640
|
-
${this.step==="empty"?
|
|
2511
|
+
${this.step==="empty"?Rt`
|
|
2641
2512
|
<div style="padding: 2.5rem 1rem; text-align: center; color: #64748b;">
|
|
2642
2513
|
<sl-icon name="file-earmark-x" style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #94a3b8;"></sl-icon>
|
|
2643
2514
|
<p style="margin: 0; font-size: 1rem; color: #334155; font-weight: 500;">${this.statusMessage}</p>
|
|
@@ -2645,7 +2516,7 @@ ${d.text}`:d.text).join(`
|
|
|
2645
2516
|
</div>
|
|
2646
2517
|
`:""}
|
|
2647
2518
|
|
|
2648
|
-
${this.step==="processing"?
|
|
2519
|
+
${this.step==="processing"?Rt`
|
|
2649
2520
|
<div style="padding: 2.5rem 1rem; text-align: center;">
|
|
2650
2521
|
<div style="font-size: 1.1rem; color: #0284c7; font-weight: 600; margin-bottom: 1rem;">
|
|
2651
2522
|
${this.statusMessage}
|
|
@@ -2657,14 +2528,14 @@ ${d.text}`:d.text).join(`
|
|
|
2657
2528
|
</div>
|
|
2658
2529
|
`:""}
|
|
2659
2530
|
|
|
2660
|
-
${this.step==="error"?
|
|
2531
|
+
${this.step==="error"?Rt`
|
|
2661
2532
|
<div style="padding: 2rem; text-align: center; color: #ef4444;">
|
|
2662
2533
|
<sl-icon name="x-circle-fill" style="font-size: 2rem;"></sl-icon>
|
|
2663
2534
|
<p style="margin-top: 0.5rem;">${this.statusMessage}</p>
|
|
2664
2535
|
</div>
|
|
2665
2536
|
`:""}
|
|
2666
2537
|
|
|
2667
|
-
${this.step==="done"?
|
|
2538
|
+
${this.step==="done"?Rt`
|
|
2668
2539
|
<div>
|
|
2669
2540
|
<sl-textarea
|
|
2670
2541
|
rows="14"
|
|
@@ -2675,18 +2546,18 @@ ${d.text}`:d.text).join(`
|
|
|
2675
2546
|
</div>
|
|
2676
2547
|
`:""}
|
|
2677
2548
|
|
|
2678
|
-
${this.step==="processing"?
|
|
2549
|
+
${this.step==="processing"?Rt`
|
|
2679
2550
|
<sl-button slot="footer" variant="default" @click=${this.cancel}>
|
|
2680
2551
|
<sl-icon slot="prefix" name="x-lg"></sl-icon>
|
|
2681
2552
|
Cancel
|
|
2682
2553
|
</sl-button>
|
|
2683
2554
|
`:""}
|
|
2684
|
-
${this.step==="empty"||this.step==="error"?
|
|
2555
|
+
${this.step==="empty"||this.step==="error"?Rt`
|
|
2685
2556
|
<sl-button slot="footer" variant="default" @click=${this.close}>
|
|
2686
2557
|
Close
|
|
2687
2558
|
</sl-button>
|
|
2688
2559
|
`:""}
|
|
2689
|
-
${this.step==="done"?
|
|
2560
|
+
${this.step==="done"?Rt`
|
|
2690
2561
|
<sl-button slot="footer" variant="default" @click=${this.close}>
|
|
2691
2562
|
Close
|
|
2692
2563
|
</sl-button>
|
|
@@ -2698,19 +2569,11 @@ ${d.text}`:d.text).join(`
|
|
|
2698
2569
|
<sl-icon slot="prefix" name="download"></sl-icon>
|
|
2699
2570
|
Download .txt
|
|
2700
2571
|
</sl-button>
|
|
2701
|
-
<sl-button slot="footer" variant="default" @click=${this.downloadMarkdown}>
|
|
2702
|
-
<sl-icon slot="prefix" name="download"></sl-icon>
|
|
2703
|
-
Download .md
|
|
2704
|
-
</sl-button>
|
|
2705
|
-
<sl-button slot="footer" variant="primary" @click=${this.saveAsNote}>
|
|
2706
|
-
<sl-icon slot="prefix" name="file-earmark-plus"></sl-icon>
|
|
2707
|
-
Save as Note
|
|
2708
|
-
</sl-button>
|
|
2709
2572
|
`:""}
|
|
2710
2573
|
</sl-dialog>
|
|
2711
|
-
`:""}};customElements.define("copio-doc-ocr-dialog",
|
|
2574
|
+
`:""}};customElements.define("copio-doc-ocr-dialog",cr);var hr=class extends se{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:n,message:o}=this.syncState,c;return t==="init"?c=Rt`<sl-spinner></sl-spinner> Setting up…`:t==="waiting"?c=Rt`
|
|
2712
2575
|
<div .innerHTML=${e}></div>
|
|
2713
|
-
${i?
|
|
2576
|
+
${i?Rt`
|
|
2714
2577
|
<div style="margin: 0.75rem 0; word-break: break-all;">
|
|
2715
2578
|
<a
|
|
2716
2579
|
class="sync-link"
|
|
@@ -2724,28 +2587,22 @@ ${d.text}`:d.text).join(`
|
|
|
2724
2587
|
</div>
|
|
2725
2588
|
`:""}
|
|
2726
2589
|
<p style="margin-top: 0.5rem; color: #6b7280; font-size: 0.9rem;">Waiting for other device…</p>
|
|
2727
|
-
`:t==="connecting"?
|
|
2590
|
+
`:t==="connecting"?c=Rt`<sl-spinner></sl-spinner> Connecting…`:t==="syncing"?c=Rt`<sl-spinner></sl-spinner> Syncing…`:t==="done"?c=Rt`<p>
|
|
2728
2591
|
Sync complete — ${n} doc${n!==1?"s":""} added.
|
|
2729
|
-
</p>`:t==="error"&&(
|
|
2592
|
+
</p>`:t==="error"&&(c=Rt`<p style="color:var(--sl-color-danger-600)">
|
|
2730
2593
|
Error: ${o}
|
|
2731
|
-
</p>`),
|
|
2594
|
+
</p>`),Rt`
|
|
2732
2595
|
<sl-dialog
|
|
2733
2596
|
label="Link Device"
|
|
2734
2597
|
open
|
|
2735
2598
|
@sl-after-hide=${this.closeSyncDialog}
|
|
2736
2599
|
>
|
|
2737
|
-
<div style="text-align:center;padding:1rem">${
|
|
2600
|
+
<div style="text-align:center;padding:1rem">${c}</div>
|
|
2738
2601
|
<sl-button slot="footer" class="sync-close-btn" @click=${this.handleCloseClick}
|
|
2739
2602
|
>Close</sl-button
|
|
2740
2603
|
>
|
|
2741
2604
|
</sl-dialog>
|
|
2742
|
-
`}};customElements.define("copio-sync-dialog",sr);var Fo=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"}};var Sp="https://copio.metered.live/api/v1/turn/credentials?apiKey=d90f0b0b6bdf180ea68238f5c2185074ce37",Ep=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.relay.metered.ca:80"}],Cp=5e3;async function Jh(){let s=new AbortController,t=setTimeout(()=>s.abort(),Cp);try{let e=await fetch(Sp,{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),Ep}finally{clearTimeout(t)}}var _p=3e4,Ui=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([Jh(),no()]);return t!==this.#r?null:new i({config:{iceServers:e}})}#d(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.")})}#p(){clearTimeout(this.#s),this.#s=setTimeout(()=>{let t=this.#n?.step;t&&t!=="done"&&t!=="error"&&this.#c("Connection timed out. Try again.")},_p)}#u(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){Pt.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 ro())(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.#p(),this.#d(e),this.#u(e)}))}startJoiner(t){this.#n?.mode!=="joiner"&&(this.#o({mode:"joiner",step:"connecting"}),this.#p(),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.#d(i),this.#u(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,l]of Object.entries(i||{}))this.#e.hasRow("docs",o)||n++,this.#e.setRow("docs",o,l)}),this.#o({...this.#n,step:"done",added:n}),Pt.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.#c(e.message)}})()}close(){this.#r++,clearTimeout(this.#s),this.#t?.destroy(),this.#t=null,this.#o(null)}};var Sl={};yi(Sl,{exportDocumentAsImages:()=>xl,exportDocumentAsMarkdown:()=>Al,exportDocumentAsPdf:()=>nr,renderMarkdownToPageDataUrls:()=>Qh,renderMarkdownToPdf:()=>wl});function sn(s){return s?s.replace(/✅/g,"Yes").replace(/❌/g,"No").replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`(.*?)`/g,"$1").trim():""}function wl(s,t){if(!window.marked||!window.marked.lexer)return;let e=window.marked.lexer(t||"");function i(n=30){s.y+n>s.page.height-s.page.margins.bottom&&s.addPage({size:"A4",margin:40})}s.addPage({size:"A4",margin:40});for(let n of e)if(n.type==="heading"){i(40),s.moveDown(.3);let o=n.depth===1?20:n.depth===2?15:12;s.font("Helvetica-Bold").fontSize(o).fillColor("#0f172a").text(sn(n.text)),s.moveDown(.2)}else if(n.type==="paragraph"){let o=n.tokens&&n.tokens.find(l=>l.type==="image");if(o&&o.href&&o.href.startsWith("data:"))try{i(180),s.moveDown(.4),s.image(o.href,{fit:[515,300],align:"center"}),s.moveDown(.4)}catch(l){console.error("Error rendering embedded image to PDF:",l)}else i(20),s.font("Helvetica").fontSize(10.5).fillColor("#334155").text(sn(n.text),{lineGap:3}),s.moveDown(.4)}else if(n.type==="hr")i(15),s.moveDown(.2),s.strokeColor("#e2e8f0").lineWidth(1).moveTo(40,s.y).lineTo(555,s.y).stroke(),s.moveDown(.4);else if(n.type==="list"){for(let o=0;o<n.items.length;o++){let l=n.items[o];i(18);let h="\u2022 ";n.ordered?h=`${o+1}. `:l.task&&(h=l.checked?"[x] ":"[ ] "),s.font("Helvetica").fontSize(10.5).fillColor("#334155").text(h+sn(l.text),{indent:10,lineGap:2})}s.moveDown(.4)}else if(n.type==="blockquote"){i(35);let o=s.y;s.font("Helvetica-Oblique").fontSize(10).fillColor("#475569").text(sn(n.text),50,o,{width:495});let l=s.y;s.strokeColor("#0284c7").lineWidth(3).moveTo(42,o).lineTo(42,l).stroke(),s.x=40,s.moveDown(.4)}else if(n.type==="code"){i(50);let o=n.text,l=s.y;s.font("Courier").fontSize(9).fillColor("#0f172a");let h=s.heightOfString(o,{width:495})+16;s.rect(40,l,515,h).fill("#f1f5f9"),s.fillColor("#0f172a").text(o,50,l+8,{width:495}),s.x=40,s.y=l+h+10}else if(n.type==="table"){i(50);let l=515/n.header.length,h=s.y;s.rect(40,h,515,22).fill("#f1f5f9"),s.font("Helvetica-Bold").fontSize(9.5).fillColor("#0f172a"),n.header.forEach((g,m)=>{s.text(sn(g.text),45+m*l,h+6,{width:l-10,align:"left"})}),s.y=h+22,s.font("Helvetica").fontSize(9).fillColor("#334155"),n.rows.forEach((g,m)=>{i(20);let d=s.y;m%2===1&&s.rect(40,d,515,20).fill("#f8fafc"),s.fillColor("#334155"),g.forEach((a,f)=>{s.text(sn(a.text),45+f*l,d+5,{width:l-10,align:"left"})}),s.y=d+20}),s.moveDown(.5)}}async function Qh(s){let[t]=await Promise.all([Vs(),ki()]),e=new t({autoFirstPage:!1}),i=[];e.on("data",l=>i.push(l));let n=new Promise((l,h)=>{e.on("end",async()=>{try{let m=await new Blob(i,{type:"application/pdf"}).arrayBuffer();l(m)}catch(g){h(g)}}),e.on("error",h)});wl(e,s.content||""),e.end();let o=await n;return Ri(o)}async function nr(s,t,e={}){let{onProgress:i,showProgress:n=!0,download:o=!0}=e;if(!t||t.length===0){Pt.warning("No images to export");return}let l=null,h=t.length;try{n&&h>1&&(l=await Pt.progress({message:`Exporting "${s||"document"}.pdf"...`,total:h,done:0}));let g=null;if(typeof window<"u"&&!window.PDFDocument){typeof i=="function"&&i(0,h,"Downloading PDF engine...");try{g=await Pt.progress({message:"Downloading PDF engine...",total:100,done:0})}catch{}}let d=t.some(r=>r.type==="markdown"),a;try{let[r]=await Promise.all([Vs(),d?ki():Promise.resolve()]);a=r}finally{g?.close()}let f=595.28,A=841.89,C=new a({autoFirstPage:!1}),u=[];C.on("data",r=>u.push(r));let y=new Promise((r,c)=>{C.on("end",()=>{try{let b=new Blob(u,{type:"application/pdf"});if(o!==!1){let w=URL.createObjectURL(b),P=document.createElement("a");P.href=w,P.download=`${s||"document"}.pdf`,P.click(),URL.revokeObjectURL(w),Pt.success(`Exported "${s||"document"}.pdf"`)}l?.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:b,docName:s||"document"}})),r(b)}catch(b){c(b)}}),C.on("error",c)});for(let r=0;r<t.length;r++){let c=t[r],b=r+1;if(c.type==="markdown")wl(C,c.content);else{let w=new Image;if(await new Promise(P=>{w.onload=P,w.onerror=E=>{console.warn("Page image failed to load for PDF:",E),P(void 0)},w.src=c.src}),w.width&&w.height){C.addPage({size:"A4"});let P=f/w.width,E=A/w.height,I=Math.min(P,E),N=w.width*I,z=w.height*I,H=(f-N)/2,X=(A-z)/2;C.image(c.src,H,X,{width:N,height:z})}}typeof i=="function"&&i(b,h),l&&l.update({done:b,total:h,message:`Exporting PDF: page ${b} of ${h}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"pdf",done:b,total:h,docName:s||"document"}})),await new Promise(w=>setTimeout(w,0))}return C.end(),await y}catch(g){l?.close(),console.error("Error generating PDF:",g),Pt.error("Failed to generate PDF")}}async function xl(s,t,e={}){let{onProgress:i,showProgress:n=!0,download:o=!0}=e;if(!t||t.length===0){Pt.warning("No images to export");return}let l=null;try{let h=(s||"document").trim(),m=(y=>y.replace(/[/\\?%*:|"<>]/g,"_"))(h)||"document";if(t.length===1&&t[0].type!=="markdown"){let y=t[0],r="jpg";if(y.src.startsWith("data:")){let P=y.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);P&&P[1].includes("png")&&(r="png")}let c=y.src,b=!1,w=null;if(!y.src.startsWith("data:")&&!y.src.startsWith("blob:"))w=await(await fetch(y.src)).blob(),c=URL.createObjectURL(w),b=!0;else if(y.src.startsWith("data:"))try{w=await(await fetch(y.src)).blob()}catch{w=new Blob([y.src],{type:`image/${r}`})}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 P=document.createElement("a");P.href=c,P.download=`${m}.${r}`,P.click(),Pt.success(`Exported "${m}.${r}"`)}return b&&URL.revokeObjectURL(c),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"image",format:r,blob:w,docName:m}})),w}let d=t.length;n&&d>1&&(l=await Pt.progress({message:`Exporting "${m}.zip"...`,total:d,done:0}));let a=t.some(y=>y.type==="markdown"),[f]=await Promise.all([so(),a?Promise.all([Vs(),ki()]):Promise.resolve()]),A=new f,C=0;for(let y=0;y<t.length;y++){let r=t[y],c=[];r.type==="markdown"?c=await Qh(r):c=[r.src];let b=Math.max(2,String(t.length*c.length).length);for(let P=0;P<c.length;P++){let E=c[P],I="jpg",N="";if(E&&E.startsWith("data:")){let X=E.match(/^data:(image\/[a-zA-Z+]+);base64,(.*)$/);X?(X[1].includes("png")&&(I="png"),N=X[2]):N=E.replace(/^data:[^;]+;base64,/,"")}else{let at=await(await(await fetch(E)).blob()).arrayBuffer(),K=String(C+1).padStart(b,"0"),j=`${m}-${K}.${I}`;A.file(j,at),C++;continue}let z=String(C+1).padStart(b,"0"),H=`${m}-${z}.${I}`;A.file(H,N,{base64:!0}),C++}let w=y+1;typeof i=="function"&&i(w,d),l&&l.update({done:w,total:d,message:`Exporting ZIP: page ${w} of ${d}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"zip",done:w,total:d,docName:m}})),await new Promise(P=>setTimeout(P,0))}l&&l.update({message:"Compressing archive..."});let u=await A.generateAsync({type:"blob"},y=>{l&&y.percent&&l.update({value:Math.round(y.percent),message:`Compressing ZIP: ${Math.round(y.percent)}%...`})});if(o!==!1){let y=URL.createObjectURL(u),r=document.createElement("a");r.href=y,r.download=`${m}.zip`,r.click(),URL.revokeObjectURL(y),Pt.success(`Exported "${m}.zip"`)}return l?.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:u,docName:m}})),u}catch(h){l?.close(),console.error("Error downloading images:",h),Pt.error("Failed to download images")}}function Al(s,t){if(!t)return;let e=t.filter(g=>g.type==="markdown");if(e.length===0){Pt.warning("No markdown text in this document");return}let i=(s||"document").trim().replace(/[/\\?%*:|"<>]/g,"_"),n="";e.length===1?n=e[0].content||"":n=e.map((g,m)=>`# Page ${m+1}: ${g.name||""}
|
|
2743
|
-
|
|
2744
|
-
${g.content||""}`).join(`
|
|
2745
|
-
|
|
2746
|
-
---
|
|
2747
|
-
|
|
2748
|
-
`);let o=new Blob([n],{type:"text/markdown;charset=utf-8"}),l=URL.createObjectURL(o),h=document.createElement("a");h.href=l,h.download=`${i}.md`,h.click(),URL.revokeObjectURL(l),Pt.success(`Exported "${i}.md"`)}var ys=class extends oi{async recognizeImageText(t,e={}){return er(t,e)}async recognizeDocumentPages(t,e={}){return en(t,e)}async getOcrWorker(t="eng",e=null){return tr(t,e)}async terminateOcrWorker(){return bs()}};var vs=class extends ai{async exportDocumentAsPdf(t,e,i={}){return nr(t,e,i)}async renderPdfPagesToDataUrls(t){let e=t instanceof ArrayBuffer?t:await t.arrayBuffer();return Ri(e)}};var ui=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 rr=class extends ui{#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 Ui(e,i),this.#t}async disconnect(){this.#t&&typeof this.#t.destroy=="function"&&(this.#t.destroy(),this.#t=null)}};var or=class extends ui{async connect(){return{step:"disconnected",peerId:null,destroy:()=>{}}}async disconnect(){}};Pi("export",Sl);Pi("ocr",new ys);Pi("sync",Ui);Pi("pdf",new vs);Pi("imageProcessor",new li);typeof window<"u"&&(window.Copio=Oo);var $b=Oo;export{qc as BUILD_DATE,te as COPIO_EVENTS,li as Canvas2DAdapter,qn as CopioAddEditDialog,Wn as CopioCarousel,ir as CopioDocOcrDialog,cs as CopioEngine,Kn as CopioHeader,$n as CopioImages,Yn as CopioLoader,Xn as CopioRow,Zn as CopioScanner,sr as CopioSyncDialog,_i as DocRepository,En as Document,qe as ImageProcessorPort,Ji as IndexedDbStorageAdapter,Fo as LicenseManager,vi as MemoryStorageAdapter,as as NullImageProcessorAdapter,Pe as NullOcrAdapter,We as NullPdfAdapter,or as NullSyncAdapter,oi as OcrPort,ls as Page,vs as PdfKitAdapter,ai as PdfPort,rr as PeerJsAdapter,Lo as SUPPORTED_LANGUAGES,Cn as ScanSession,Ue as StoragePort,Ui as SyncManager,ui as SyncPort,ys as TesseractWasmAdapter,Xc as VERSION,Mo as adoptScannerStyles,ol as clearNotifications,Ls as createDefaultAdapter,$b as default,lo as dispatchCopioEvent,Fa as docRepository,xl as exportDocumentAsImages,Al as exportDocumentAsMarkdown,nr as exportDocumentAsPdf,zs as extractExif,Hs as fileToBase64,eo as getAssetBase,Fi as getContainer,Ra as getCroppedSrc,tr as getOcrWorker,Ti as getRegisteredService,Io as getScannerStyleSheet,ao as hasActiveEdits,io as loadCropper,so as loadJsZip,ki as loadMarked,Vs as loadPdfKit,no as loadPeerJs,ro as loadQrCode,ri as loadScript,oo as loadTesseract,_n as normalizeEditStack,Pt as notify,we as randomId,en as recognizeDocumentPages,er as recognizeImageText,Pi as registerService,Ri as renderPdfPagesToDataUrls,ni as resolveAssetUrl,Ma as rotateSrc,Qn as scannerCss,os as setAssetBase,Li as setContainer,bs as terminateOcrWorker,Ia as thresholdSrc};
|
|
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};
|
|
2749
2606
|
/**!
|
|
2750
2607
|
* Sortable 1.15.6
|
|
2751
2608
|
* @author RubaXa <trash@rubaxa.org>
|